p-backlog 0.12.2 → 0.13.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 (44) hide show
  1. package/CHANGELOG.md +63 -0
  2. package/README.md +7 -6
  3. package/README.ru.md +6 -5
  4. package/dist/cli.js +1394 -1062
  5. package/dist/web/assets/CodeTab-BokbzP4a.js +1 -0
  6. package/dist/web/assets/CostTab-D91_w1H0.js +1 -0
  7. package/dist/web/assets/EffectTab-CRlWfFF0.js +1 -0
  8. package/dist/web/assets/Figure-CO87y2TD.js +1 -0
  9. package/dist/web/assets/OverviewTab-LJh-9xzS.css +1 -0
  10. package/dist/web/assets/OverviewTab-naYN8aXk.js +1 -0
  11. package/dist/web/assets/Page-BHZdQQhE.js +59 -0
  12. package/dist/web/assets/QualityTab-BMfBa6YW.js +1 -0
  13. package/dist/web/assets/ShareBar-DBiU0f9_.js +1 -0
  14. package/dist/web/assets/StatsPage-Dr1pco7X.js +1 -0
  15. package/dist/web/assets/StatsTabState-CePos7h7.js +1 -0
  16. package/dist/web/assets/{StatsTable-BcgwvoAi.js → StatsTable-CqH14eSD.js} +1 -1
  17. package/dist/web/assets/UnavailableRepos-BBbuCPNM.js +1 -0
  18. package/dist/web/assets/index-DpWYLB0A.js +2 -0
  19. package/dist/web/assets/start-Cw9zPEW-.js +42 -0
  20. package/dist/web/assets/start-DCkTSXpO.css +1 -0
  21. package/dist/web/assets/use-grain-panel-BKTkjTK3.js +55 -0
  22. package/dist/web/assets/web-paths-yWGbLD6t.js +1 -0
  23. package/dist/web/index.html +1 -1
  24. package/package.json +1 -1
  25. package/skill/backlog/SKILL.md +5 -2
  26. package/skill/backlog-en/SKILL.md +4 -2
  27. package/dist/web/assets/CodeTab-CkeyTQS5.js +0 -1
  28. package/dist/web/assets/CostTab-ysoB6lpe.js +0 -1
  29. package/dist/web/assets/EffectTab-BiAZufxv.js +0 -1
  30. package/dist/web/assets/Figure-BaF9nHCH.js +0 -1
  31. package/dist/web/assets/OverviewTab-DeoTLTwg.css +0 -1
  32. package/dist/web/assets/OverviewTab-DufXfiH_.js +0 -1
  33. package/dist/web/assets/Page-DkyFc9L-.js +0 -59
  34. package/dist/web/assets/QualityTab-DFAD-2mI.js +0 -1
  35. package/dist/web/assets/ShareBar-DGwv3w_j.js +0 -1
  36. package/dist/web/assets/StatsPage-BJj_n426.js +0 -1
  37. package/dist/web/assets/StatsTabState-ilDGkRnG.js +0 -1
  38. package/dist/web/assets/UnavailableRepos-7jsmWIpD.js +0 -1
  39. package/dist/web/assets/index-rkd9D77s.js +0 -2
  40. package/dist/web/assets/rolldown-runtime-hePW80VL.js +0 -1
  41. package/dist/web/assets/start-CRCFATfp.css +0 -1
  42. package/dist/web/assets/start-DiikM5Rg.js +0 -42
  43. package/dist/web/assets/use-grain-panel-BVC7wAuR.js +0 -55
  44. package/dist/web/assets/web-paths-BXxhzAwv.js +0 -1
package/dist/cli.js CHANGED
@@ -95,6 +95,9 @@ function errorCode(error) {
95
95
  function hasErrorCode(error, code) {
96
96
  return errorCode(error) === code;
97
97
  }
98
+ function hasAnyErrorCode(error, codes) {
99
+ return codes.some((code) => hasErrorCode(error, code));
100
+ }
98
101
  function errorCodeOrText(error) {
99
102
  const code = errorCode(error);
100
103
  return typeof code === "string" ? code : errorText(error);
@@ -114,17 +117,15 @@ import { join as join3 } from "node:path";
114
117
  import { z } from "zod";
115
118
 
116
119
  // src/core/store/file-lock.ts
117
- import { randomUUID as randomUUID2 } from "node:crypto";
118
- import { rm as rm2, writeFile as writeFile2 } from "node:fs/promises";
119
- import { basename as basename2, dirname as dirname2, join as join2 } from "node:path";
120
- import { setTimeout as sleep2 } from "node:timers/promises";
120
+ import { randomUUID } from "node:crypto";
121
+ import { rm as rm2, utimes, writeFile } from "node:fs/promises";
122
+ import { basename, dirname, join } from "node:path";
123
+ import { setTimeout as sleep } from "node:timers/promises";
121
124
 
122
125
  // src/core/store/fs-utils.ts
123
- import { createHash, randomUUID } from "node:crypto";
126
+ import { createHash } from "node:crypto";
124
127
  import { readFileSync, realpathSync } from "node:fs";
125
- import { access, appendFile, chmod, link, lstat, open, readdir, readFile, readlink, rename, rm, stat, writeFile } from "node:fs/promises";
126
- import { basename, dirname, join } from "node:path";
127
- import { setTimeout as sleep } from "node:timers/promises";
128
+ import { access, lstat, open, readdir, readFile, readlink, rm, stat } from "node:fs/promises";
128
129
  function contentVersion(text) {
129
130
  return createHash("sha1").update(text).digest("hex");
130
131
  }
@@ -195,36 +196,9 @@ function realpathOrNull(path) {
195
196
  function readBytesOrNullSync(path) {
196
197
  return nullWhenMissingSync(() => readFileSync(path));
197
198
  }
198
- function hasAnyErrorCode(error, codes) {
199
- return codes.some((code) => hasErrorCode(error, code));
200
- }
201
- function parseJsonLines(text, schema) {
202
- const parsed = text.split("\n").filter((line) => line.trim() !== "").map((line) => parseJson(line, schema));
203
- const values = parsed.filter((value) => value !== null);
204
- return { values, invalidLines: parsed.length - values.length };
205
- }
206
- async function readJsonLines(path, schema) {
207
- const text = await readTextOrNull(path) ?? "";
208
- return parseJsonLines(text, schema);
209
- }
210
- function toJsonLines(values) {
211
- return values.map((value) => `${JSON.stringify(value)}
212
- `).join("");
213
- }
214
199
  var NEWLINE = 10;
215
- async function appendJsonLines(path, values) {
216
- await withFile(
217
- path,
218
- async (handle) => {
219
- const { size } = await handle.stat();
220
- const endsMidLine = size > 0 && (await readAt(handle, size - 1, 1))[0] !== NEWLINE;
221
- await handle.appendFile((endsMidLine ? "\n" : "") + toJsonLines(values), "utf8");
222
- },
223
- "a+"
224
- );
225
- }
226
- async function withFile(path, use, flags = "r") {
227
- return closingAfter(await open(path, flags), use);
200
+ async function withFile(path, use, { flags = "r", mode } = {}) {
201
+ return closingAfter(await open(path, flags, mode), use);
228
202
  }
229
203
  async function fileExists(path) {
230
204
  return access(path).then(
@@ -235,7 +209,7 @@ async function fileExists(path) {
235
209
  }
236
210
  );
237
211
  }
238
- async function withExistingFile(path, use, flags = "r") {
212
+ async function withExistingFile(path, use, { flags = "r" } = {}) {
239
213
  const handle = await nullWhenMissing(open(path, flags));
240
214
  return handle === null ? null : closingAfter(handle, use);
241
215
  }
@@ -263,18 +237,6 @@ function parseJson(text, schema) {
263
237
  throw error;
264
238
  }
265
239
  }
266
- async function readJsonFile(path, schema) {
267
- const text = await readTextOrNull(path);
268
- return text === null ? null : parseJson(text, schema);
269
- }
270
- var JSON_INDENT = 2;
271
- function jsonFileText(value) {
272
- return `${JSON.stringify(value, null, JSON_INDENT)}
273
- `;
274
- }
275
- async function writeJsonFile(path, value) {
276
- await writeFileAtomic(path, jsonFileText(value));
277
- }
278
240
  async function removeIfUnchanged(path, version) {
279
241
  const text = await readTextOrNull(path);
280
242
  if (text === null) return "already-gone";
@@ -290,71 +252,11 @@ async function listDir(path, { recursive = false } = {}) {
290
252
  throw error;
291
253
  }
292
254
  }
293
- var REPLACE_RETRY_DELAYS_MS = [10, 20, 40, 80, 160, 320, 640, 1e3, 1e3, 1e3, 1e3];
294
- var REPLACE_BLOCKED_CODES = ["EPERM", "EACCES", "EBUSY"];
295
- async function writeFileAtomic(path, content, mode) {
296
- await viaTemporaryFile(path, content, (temporary) => replaceFile(temporary, path), mode);
297
- }
298
- async function replacePrefixAtomic(path, prefix, content) {
299
- let seen = prefix;
300
- const carryAppended = async (temporary) => {
301
- const live = await readBytesOrNull(path) ?? Buffer.alloc(0);
302
- if (!startsWithBytes(live, seen)) return false;
303
- await appendFile(temporary, live.subarray(seen.length));
304
- seen = live;
305
- return true;
306
- };
307
- return viaTemporaryFile(path, content, (temporary) => replaceFile(temporary, path, () => carryAppended(temporary)));
308
- }
309
- function startsWithBytes(bytes, prefix) {
310
- return bytes.length >= prefix.length && bytes.subarray(0, prefix.length).equals(prefix);
311
- }
312
- async function replaceFile(temporary, path, prepareRename = async () => true) {
313
- const attempt = async () => {
314
- if (!await prepareRename()) return false;
315
- await rename(temporary, path);
316
- return true;
317
- };
318
- if (process.platform !== "win32") return attempt();
319
- for (const delayMs of REPLACE_RETRY_DELAYS_MS) {
320
- try {
321
- return await attempt();
322
- } catch (error) {
323
- if (!hasAnyErrorCode(error, REPLACE_BLOCKED_CODES)) throw error;
324
- await sleep(delayMs);
325
- }
326
- }
327
- return attempt();
328
- }
329
- async function createFileAtomic(path, content) {
330
- await viaTemporaryFile(path, content, (temporary) => link(temporary, path));
331
- }
332
- var TEMPORARY_FILE = /^\..+\.[0-9a-f-]{36}\.tmp$/;
333
- async function removeTemporariesBefore(dir, cutoff) {
334
- for (const entry of await listDir(dir)) {
335
- if (!entry.isFile() || !TEMPORARY_FILE.test(entry.name)) continue;
336
- const path = join(dir, entry.name);
337
- const info = await statOrNull(path);
338
- if (info !== null && info.mtimeMs < cutoff.getTime()) await rm(path, { force: true });
339
- }
340
- }
341
- function temporaryPathFor(path) {
342
- return join(dirname(path), `.${basename(path)}.${randomUUID()}.tmp`);
343
- }
344
- async function viaTemporaryFile(path, content, publish, mode) {
345
- const temporary = temporaryPathFor(path);
346
- try {
347
- await writeFile(temporary, content, { encoding: "utf8", mode });
348
- if (mode !== void 0) await chmod(temporary, mode);
349
- return await publish(temporary);
350
- } finally {
351
- await rm(temporary, { force: true });
352
- }
353
- }
354
255
 
355
256
  // src/core/store/file-lock.ts
356
257
  var RETRY_MS = 10;
357
258
  var ABANDONED_AFTER_MS = 3e4;
259
+ var REFRESH_EVERY_MS = ABANDONED_AFTER_MS / 3;
358
260
  var DEFAULT_WAIT_LIMIT_MS = 5e3;
359
261
  var FileBusyError = class extends Error {
360
262
  constructor(path, lock, seconds) {
@@ -393,20 +295,20 @@ async function withAvailableLocks(paths, action, { waitLimitMs = DEFAULT_WAIT_LI
393
295
  }
394
296
  }
395
297
  async function acquire(path, { waitLimitMs = DEFAULT_WAIT_LIMIT_MS }) {
396
- const lock = join2(dirname2(path), `.${basename2(path)}.lock`);
397
- const token = `${process.pid} ${randomUUID2()}`;
298
+ const lock = join(dirname(path), `.${basename(path)}.lock`);
299
+ const token = `${process.pid} ${randomUUID()}`;
398
300
  const giveUpAt = Date.now() + waitLimitMs;
399
301
  for (; ; ) {
400
- if (await tryCreate(lock, token)) return { path, lock, token };
302
+ if (await tryCreate(lock, token)) return { path, lock, token, stopRefreshing: keepRefreshed(lock, token) };
401
303
  const abandoned = await abandonedToken(lock);
402
304
  if (abandoned !== null && await breakAbandoned(lock, abandoned)) continue;
403
305
  if (Date.now() > giveUpAt) throw new FileBusyError(path, lock, waitLimitMs / SECOND_MS);
404
- await sleep2(RETRY_MS);
306
+ await sleep(RETRY_MS);
405
307
  }
406
308
  }
407
309
  async function tryCreate(lock, token) {
408
310
  try {
409
- await writeFile2(lock, token, { flag: "wx" });
311
+ await writeFile(lock, token, { flag: "wx" });
410
312
  return true;
411
313
  } catch (error) {
412
314
  if (hasErrorCode(error, "EEXIST")) return false;
@@ -432,10 +334,152 @@ async function breakAbandoned(lock, abandoned) {
432
334
  await rm2(breaker, { force: true });
433
335
  }
434
336
  }
435
- async function release({ lock, token }) {
337
+ function keepRefreshed(lock, token) {
338
+ let bug = null;
339
+ let refreshing = Promise.resolve();
340
+ const timer = setInterval(() => {
341
+ refreshing = refreshing.then(() => refreshIfHeld(lock, token)).catch((error) => {
342
+ clearInterval(timer);
343
+ if (errorCode(error) === void 0) bug = error;
344
+ });
345
+ }, REFRESH_EVERY_MS);
346
+ timer.unref();
347
+ return async () => {
348
+ clearInterval(timer);
349
+ await refreshing;
350
+ if (bug !== null) throw bug;
351
+ };
352
+ }
353
+ async function refreshIfHeld(lock, token) {
354
+ if (await readTextOrNull(lock) !== token) return;
355
+ const now = /* @__PURE__ */ new Date();
356
+ try {
357
+ await utimes(lock, now, now);
358
+ } catch (error) {
359
+ if (!hasErrorCode(error, "ENOENT")) throw error;
360
+ }
361
+ }
362
+ async function release({ lock, token, stopRefreshing }) {
363
+ await stopRefreshing();
436
364
  if (await readTextOrNull(lock) === token) await rm2(lock, { force: true });
437
365
  }
438
366
 
367
+ // src/core/store/json-lines.ts
368
+ function parseJsonLines(text, schema) {
369
+ const parsed = text.split("\n").filter((line) => line.trim() !== "").map((line) => parseJson(line, schema));
370
+ const values = parsed.filter((value) => value !== null);
371
+ return { values, invalidLines: parsed.length - values.length };
372
+ }
373
+ async function readJsonLines(path, schema) {
374
+ const text = await readTextOrNull(path) ?? "";
375
+ return parseJsonLines(text, schema);
376
+ }
377
+ function toJsonLines(values) {
378
+ return values.map((value) => `${JSON.stringify(value)}
379
+ `).join("");
380
+ }
381
+ async function appendJsonLines(path, values) {
382
+ await withFile(
383
+ path,
384
+ async (handle) => {
385
+ const { size } = await handle.stat();
386
+ const endsMidLine = size > 0 && (await readAt(handle, size - 1, 1))[0] !== NEWLINE;
387
+ await handle.appendFile((endsMidLine ? "\n" : "") + toJsonLines(values), "utf8");
388
+ await handle.sync();
389
+ },
390
+ { flags: "a+" }
391
+ );
392
+ }
393
+
394
+ // src/core/store/atomic-write.ts
395
+ import { randomUUID as randomUUID2 } from "node:crypto";
396
+ import { chmod, link, rename, rm as rm3 } from "node:fs/promises";
397
+ import { basename as basename2, dirname as dirname2, join as join2 } from "node:path";
398
+ import { setTimeout as sleep2 } from "node:timers/promises";
399
+ var REPLACE_RETRY_DELAYS_MS = [10, 20, 40, 80, 160, 320, 640, 1e3, 1e3, 1e3, 1e3];
400
+ var REPLACE_RETRIES_TOTAL_MS = sum(REPLACE_RETRY_DELAYS_MS);
401
+ var REPLACE_BLOCKED_CODES = ["EPERM", "EACCES", "EBUSY"];
402
+ async function writeFileAtomic(path, content, mode) {
403
+ await viaTemporaryFile(path, content, (temporary) => replaceFile(temporary, path), mode);
404
+ }
405
+ async function replacePrefixAtomic(path, prefix, content) {
406
+ let seen = prefix;
407
+ const carryAppended = async (temporary) => {
408
+ const live = await readBytesOrNull(path) ?? Buffer.alloc(0);
409
+ if (!startsWithBytes(live, seen)) return false;
410
+ if (live.length > seen.length) await writeSynced(temporary, live.subarray(seen.length), "a");
411
+ seen = live;
412
+ return true;
413
+ };
414
+ return viaTemporaryFile(path, content, (temporary) => replaceFile(temporary, path, () => carryAppended(temporary)));
415
+ }
416
+ function startsWithBytes(bytes, prefix) {
417
+ return bytes.length >= prefix.length && bytes.subarray(0, prefix.length).equals(prefix);
418
+ }
419
+ async function replaceFile(temporary, path, prepareRename = async () => true) {
420
+ const attempt = async () => {
421
+ if (!await prepareRename()) return false;
422
+ await rename(temporary, path);
423
+ return true;
424
+ };
425
+ if (process.platform !== "win32") return attempt();
426
+ for (const delayMs of REPLACE_RETRY_DELAYS_MS) {
427
+ try {
428
+ return await attempt();
429
+ } catch (error) {
430
+ if (!hasAnyErrorCode(error, REPLACE_BLOCKED_CODES)) throw error;
431
+ await sleep2(delayMs);
432
+ }
433
+ }
434
+ return attempt();
435
+ }
436
+ async function createFileAtomic(path, content) {
437
+ await viaTemporaryFile(path, content, (temporary) => link(temporary, path));
438
+ }
439
+ var TEMPORARY_FILE = /^\..+\.[0-9a-f-]{36}\.tmp$/;
440
+ async function removeTemporariesBefore(dir, cutoff) {
441
+ for (const entry of await listDir(dir)) {
442
+ if (!entry.isFile() || !TEMPORARY_FILE.test(entry.name)) continue;
443
+ const path = join2(dir, entry.name);
444
+ const info = await statOrNull(path);
445
+ if (info !== null && info.mtimeMs < cutoff.getTime()) await rm3(path, { force: true });
446
+ }
447
+ }
448
+ function temporaryPathFor(path) {
449
+ return join2(dirname2(path), `.${basename2(path)}.${randomUUID2()}.tmp`);
450
+ }
451
+ async function viaTemporaryFile(path, content, publish, mode) {
452
+ const temporary = temporaryPathFor(path);
453
+ try {
454
+ await writeSynced(temporary, content, "w", mode);
455
+ if (mode !== void 0) await chmod(temporary, mode);
456
+ const published = await publish(temporary);
457
+ await syncDirectoryOf(path);
458
+ return published;
459
+ } finally {
460
+ await rm3(temporary, { force: true });
461
+ }
462
+ }
463
+ async function writeSynced(path, data, flags, mode) {
464
+ await withFile(
465
+ path,
466
+ async (handle) => {
467
+ await handle.writeFile(data, "utf8");
468
+ await handle.sync();
469
+ },
470
+ { flags, mode }
471
+ );
472
+ }
473
+ var DIRECTORY_SYNC_UNSUPPORTED_CODES = ["EINVAL", "ENOTSUP", "EISDIR", "EACCES", "EPERM"];
474
+ async function syncDirectoryOf(path) {
475
+ if (process.platform === "win32") return;
476
+ try {
477
+ await withFile(dirname2(path), (directory) => directory.sync());
478
+ } catch (error) {
479
+ if (!hasAnyErrorCode(error, DIRECTORY_SYNC_UNSUPPORTED_CODES)) throw error;
480
+ }
481
+ }
482
+
439
483
  // src/core/model/history-window.ts
440
484
  var STATS_WEEKS = 12;
441
485
  var STATS_HISTORY_DAYS = STATS_WEEKS * DAYS_PER_WEEK;
@@ -491,12 +535,13 @@ async function firstRunIn(handle) {
491
535
  }
492
536
 
493
537
  // src/core/store/paths.ts
494
- import { basename as basename3, join as join4, resolve } from "node:path";
538
+ import { basename as basename3, dirname as dirname3, join as join4, resolve } from "node:path";
495
539
  var PROJECT_FILE = "project.md";
496
540
  var PID_FILE_ENV = "P_BACKLOG_PID_FILE";
541
+ var HOME_PREFIX = /^~[\\/]/;
497
542
  function expandHome(path, home2) {
498
543
  if (path === "~") return home2;
499
- return path.startsWith("~/") ? join4(home2, path.slice(2)) : path;
544
+ return HOME_PREFIX.test(path) ? join4(home2, path.slice(2)) : path;
500
545
  }
501
546
  function resolveBacklogRoot(env, home2) {
502
547
  const configured = env.BACKLOG_DIR;
@@ -505,6 +550,9 @@ function resolveBacklogRoot(env, home2) {
505
550
  function taskFileName(id) {
506
551
  return `${id}.md`;
507
552
  }
553
+ function projectDirOf(project) {
554
+ return dirname3(project.path);
555
+ }
508
556
  function projectDir(root, id) {
509
557
  const isPlainName = id !== "" && id !== "." && id !== ".." && basename3(id) === id && !id.includes("\\");
510
558
  return isPlainName ? join4(root, id) : null;
@@ -527,6 +575,20 @@ function localeOf(language) {
527
575
  import { z as z2 } from "zod";
528
576
  var settingsSchema = z2.object({ language: z2.enum(LANGUAGES) });
529
577
 
578
+ // src/core/store/json-file.ts
579
+ var JSON_INDENT = 2;
580
+ function jsonFileText(value) {
581
+ return `${JSON.stringify(value, null, JSON_INDENT)}
582
+ `;
583
+ }
584
+ async function readJsonFile(path, schema) {
585
+ const text = await readTextOrNull(path);
586
+ return text === null ? null : parseJson(text, schema);
587
+ }
588
+ async function writeJsonFile(path, value, mode) {
589
+ await writeFileAtomic(path, jsonFileText(value), mode);
590
+ }
591
+
530
592
  // src/core/store/load.ts
531
593
  import { basename as basename4, join as join5 } from "node:path";
532
594
 
@@ -547,21 +609,21 @@ function compareIds(a, b) {
547
609
  if (!left || !right) return a.localeCompare(b);
548
610
  return left.prefix === right.prefix ? left.number - right.number : left.prefix.localeCompare(right.prefix);
549
611
  }
550
- function derivePrefix(basename10, taken) {
551
- const base = prefixBase(basename10);
612
+ function derivePrefix(basename11, taken) {
613
+ const base = prefixBase(basename11);
552
614
  return firstFree(base, taken, (n) => `${base}${n}`);
553
615
  }
554
- function projectIdBase(basename10) {
555
- const slug = basename10.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
616
+ function projectIdBase(basename11) {
617
+ const slug = basename11.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
556
618
  return slug === "" ? "project" : slug;
557
619
  }
558
- function deriveProjectId(basename10, taken) {
559
- const base = projectIdBase(basename10);
620
+ function deriveProjectId(basename11, taken) {
621
+ const base = projectIdBase(basename11);
560
622
  return firstFree(base, taken, (n) => `${base}-${n}`);
561
623
  }
562
624
  var PREFIX_BASE_LENGTH = 4;
563
- function prefixBase(basename10) {
564
- const words = basename10.split(/[^A-Za-z0-9]+/).filter(Boolean);
625
+ function prefixBase(basename11) {
626
+ const words = basename11.split(/[^A-Za-z0-9]+/).filter(Boolean);
565
627
  const letters = words.length > 1 ? words.map((word) => word.charAt(0)).join("") : words[0] ?? "";
566
628
  const prefix = letters.slice(0, PREFIX_BASE_LENGTH).toUpperCase();
567
629
  if (prefix === "") return "PROJ";
@@ -697,6 +759,26 @@ function serializeProject(project) {
697
759
  const { name, prefix, repos, issuedUpTo, active } = project;
698
760
  return stringifyFrontmatter({ name, prefix, repos, issuedUpTo, active: active ? void 0 : false, ...project.extra }, project.body);
699
761
  }
762
+ var REPOS_KEY = /^\s*repos\s*:(.*)$/;
763
+ var LIST_ITEM = /^\s*-\s+(.*)$/;
764
+ var TRAILING_COMMENT = /\s+#.*$/;
765
+ var ENCLOSING_BRACKETS = /^[\s[]+|[\s\]]+$/g;
766
+ var QUOTED = /^(["'])(.*)\1$/;
767
+ function reposOfUnparsed(text) {
768
+ const lines = text.split(/\r?\n/);
769
+ const keyAt = lines.findIndex((line) => REPOS_KEY.test(line));
770
+ if (keyAt === -1) return [];
771
+ const inline = (REPOS_KEY.exec(lines[keyAt] ?? "")?.[1] ?? "").replace(TRAILING_COMMENT, "");
772
+ const items = inline.trim() === "" ? listItemsAfter(lines.slice(keyAt + 1)) : inline.split(",");
773
+ return items.map(plainRepoItem).filter((item) => item !== "");
774
+ }
775
+ function listItemsAfter(lines) {
776
+ const end = lines.findIndex((line) => !LIST_ITEM.test(line));
777
+ return (end === -1 ? lines : lines.slice(0, end)).map((line) => LIST_ITEM.exec(line)?.[1] ?? "");
778
+ }
779
+ function plainRepoItem(item) {
780
+ return item.replace(TRAILING_COMMENT, "").replace(ENCLOSING_BRACKETS, "").replace(QUOTED, "$2");
781
+ }
700
782
 
701
783
  // src/core/model/task-file.ts
702
784
  var TASK_FIELDS = Object.keys(taskFrontmatterSchema.shape);
@@ -715,6 +797,18 @@ function serializeTask(task) {
715
797
  return stringifyFrontmatter({ ...known, ...task.extra }, task.body);
716
798
  }
717
799
 
800
+ // src/core/store/read-document.ts
801
+ import { isUtf8 } from "node:buffer";
802
+ async function parseDocumentOrNull(path, parse2) {
803
+ const document = await readDocumentOrNull(path);
804
+ return document?.ok === true ? parse2(document.value) : document;
805
+ }
806
+ async function readDocumentOrNull(path) {
807
+ const bytes = await readBytesOrNull(path);
808
+ if (bytes === null) return null;
809
+ return isUtf8(bytes) ? { ok: true, value: bytes.toString("utf8") } : { ok: false, problems: [{ code: "not-utf8" }] };
810
+ }
811
+
718
812
  // src/core/store/load.ts
719
813
  function unparsedTasks(errors) {
720
814
  return errors.flatMap(({ path, projectId }) => {
@@ -722,6 +816,9 @@ function unparsedTasks(errors) {
722
816
  return ID_PATTERN.test(id) ? [{ projectId, id }] : [];
723
817
  });
724
818
  }
819
+ function unparsedProjectFiles(errors) {
820
+ return errors.filter((error) => basename4(error.path) === PROJECT_FILE);
821
+ }
725
822
  async function projectDirNames(root) {
726
823
  return (await listDir(root)).filter((entry) => entry.isDirectory() && !entry.name.startsWith(".")).map((entry) => entry.name);
727
824
  }
@@ -735,9 +832,8 @@ async function loadBacklog(root) {
735
832
  }
736
833
  async function loadProjectDir(dir, projectId) {
737
834
  const projectPath = join5(dir, PROJECT_FILE);
738
- const projectText = await readTextOrNull(projectPath);
739
- if (projectText === null) return { projects: [], tasks: [], errors: [] };
740
- const project = parseProjectFile(projectText, { id: projectId, path: projectPath });
835
+ const project = await parseDocumentOrNull(projectPath, (text) => parseProjectFile(text, { id: projectId, path: projectPath }));
836
+ if (project === null) return { projects: [], tasks: [], errors: [] };
741
837
  if (!project.ok) return { projects: [], tasks: [], errors: [{ path: projectPath, projectId, problems: project.problems }] };
742
838
  const taskPaths = (await taskFileNames(dir)).map((name) => join5(dir, name));
743
839
  const loaded = await Promise.all(taskPaths.map(async (path) => ({ path, result: await loadTaskFile(path, project.value) })));
@@ -748,10 +844,8 @@ async function loadProjectDir(dir, projectId) {
748
844
  };
749
845
  }
750
846
  async function loadTaskFile(path, project) {
751
- const text = await readTextOrNull(path);
752
- if (text === null) return null;
753
- const parsed = parseTaskFile(text, { projectId: project.id, path, version: contentVersion(text) });
754
- if (!parsed.ok) return parsed;
847
+ const parsed = await parseDocumentOrNull(path, (text) => parseTaskFile(text, { projectId: project.id, path, version: contentVersion(text) }));
848
+ if (parsed === null || !parsed.ok) return parsed;
755
849
  const stem = basename4(path, ".md");
756
850
  if (parsed.value.id !== stem) return { ok: false, problems: [{ code: "id-mismatch", id: parsed.value.id, file: stem }] };
757
851
  if (parseId(stem)?.prefix !== project.prefix) {
@@ -1125,8 +1219,12 @@ function problem(p) {
1125
1219
  return `epic ${p.epic} belongs to another project \u2014 clear the epic or pick one from this project`;
1126
1220
  case "epic-in-epic":
1127
1221
  return "an epic cannot belong to another epic";
1222
+ case "epic-closed-with-open-tasks":
1223
+ return `the epic closes on its own once all its tasks are closed \u2014 close the open ones first: ${p.children.join(", ")}`;
1128
1224
  case "reference-missing":
1129
1225
  return `${p.id} not found`;
1226
+ case "not-utf8":
1227
+ return "the file is not UTF-8 \u2014 the backlog leaves it untouched until it is re-saved as UTF-8";
1130
1228
  case "no-frontmatter":
1131
1229
  return "file does not start with frontmatter (---)";
1132
1230
  case "frontmatter-unclosed":
@@ -1156,7 +1254,7 @@ function checkFix(fix) {
1156
1254
  case "epic-reopened":
1157
1255
  return `${fix.taskId}: epic reopened \u2014 it has open tasks: ${fix.childIds.join(", ")}`;
1158
1256
  case "source-moved":
1159
- return sourcePath(fix.from) === sourcePath(fix.to) ? `${fix.taskId}: source moved ${lineSuffix(fix.from)} \u2192 ${lineSuffix(fix.to)}` : `${fix.taskId}: task file renamed, source ${fix.from} \u2192 ${fix.to}`;
1257
+ return sourcePath(fix.from) === sourcePath(fix.to) ? `${fix.taskId}: source moved ${lineSuffix(fix.from)} \u2192 ${lineSuffix(fix.to)}` : `${fix.taskId}: code file renamed, source ${fix.from} \u2192 ${fix.to}`;
1160
1258
  }
1161
1259
  }
1162
1260
  function checkProblem(p) {
@@ -1179,6 +1277,10 @@ function checkProblem(p) {
1179
1277
  return `Project ${p.projectId}: git does not trust ${p.repo} (the directory belongs to another user) \u2014 commits and code edits of its tasks are not checked. Fix: git config --global --add safe.directory "${p.repo}"`;
1180
1278
  case "project-history-unreadable":
1181
1279
  return `Project ${p.projectId}: could not read the git history in ${p.repo} \u2014 commits and code edits of its tasks were not checked`;
1280
+ case "project-branches-unreadable":
1281
+ return `Project ${p.projectId}: could not read the git branches in ${p.repo} (a broken ref or a git failure) \u2014 missing code files of its tasks were not checked`;
1282
+ case "merge-state-unknown":
1283
+ return `Project ${p.projectId}: git in ${p.repo} could not tell whether ${pluralEn(p.branches.length, "branch", "branches")} ${p.branches.join(", ")} landed in the current branch (shallow clone, unrelated history or a git failure) \u2014 tasks created there were checked as usual, without waiting for the merge`;
1182
1284
  case "prefix-shared":
1183
1285
  return `Projects ${p.projectIds.join(", ")} share the prefix ${p.prefix} \u2014 their task IDs collide. Change prefix in project.md of one of them`;
1184
1286
  }
@@ -1370,8 +1472,12 @@ function problem2(p) {
1370
1472
  return `\u044D\u043F\u0438\u043A ${p.epic} \u0438\u0437 \u0434\u0440\u0443\u0433\u043E\u0433\u043E \u043F\u0440\u043E\u0435\u043A\u0442\u0430 \u2014 \u0441\u043D\u0438\u043C\u0438\u0442\u0435 \u044D\u043F\u0438\u043A \u0438\u043B\u0438 \u0432\u044B\u0431\u0435\u0440\u0438\u0442\u0435 \u044D\u043F\u0438\u043A \u044D\u0442\u043E\u0433\u043E \u043F\u0440\u043E\u0435\u043A\u0442\u0430`;
1371
1473
  case "epic-in-epic":
1372
1474
  return "\u044D\u043F\u0438\u043A \u043D\u0435 \u043C\u043E\u0436\u0435\u0442 \u0432\u0445\u043E\u0434\u0438\u0442\u044C \u0432 \u0434\u0440\u0443\u0433\u043E\u0439 \u044D\u043F\u0438\u043A";
1475
+ case "epic-closed-with-open-tasks":
1476
+ return `\u044D\u043F\u0438\u043A \u0437\u0430\u043A\u0440\u043E\u0435\u0442\u0441\u044F \u0441\u0430\u043C, \u043A\u043E\u0433\u0434\u0430 \u0437\u0430\u043A\u0440\u043E\u044E\u0442\u0441\u044F \u0432\u0441\u0435 \u0435\u0433\u043E \u0437\u0430\u0434\u0430\u0447\u0438 \u2014 \u0441\u043D\u0430\u0447\u0430\u043B\u0430 \u0437\u0430\u043A\u0440\u043E\u0439\u0442\u0435 \u043E\u0442\u043A\u0440\u044B\u0442\u044B\u0435: ${p.children.join(", ")}`;
1373
1477
  case "reference-missing":
1374
1478
  return `${p.id} \u043D\u0435 \u043D\u0430\u0439\u0434\u0435\u043D\u0430`;
1479
+ case "not-utf8":
1480
+ return "\u0444\u0430\u0439\u043B \u043D\u0435 \u0432 \u043A\u043E\u0434\u0438\u0440\u043E\u0432\u043A\u0435 UTF-8 \u2014 \u0431\u0435\u043A\u043B\u043E\u0433 \u0435\u0433\u043E \u043D\u0435 \u043C\u0435\u043D\u044F\u0435\u0442, \u043F\u043E\u043A\u0430 \u0435\u0433\u043E \u043D\u0435 \u043F\u0435\u0440\u0435\u0441\u043E\u0445\u0440\u0430\u043D\u044F\u0442 \u0432 UTF-8";
1375
1481
  case "no-frontmatter":
1376
1482
  return "\u0444\u0430\u0439\u043B \u043D\u0435 \u043D\u0430\u0447\u0438\u043D\u0430\u0435\u0442\u0441\u044F \u0441 frontmatter (---)";
1377
1483
  case "frontmatter-unclosed":
@@ -1401,7 +1507,7 @@ function checkFix2(fix) {
1401
1507
  case "epic-reopened":
1402
1508
  return `${fix.taskId}: \u044D\u043F\u0438\u043A \u0441\u043D\u043E\u0432\u0430 \u043E\u0442\u043A\u0440\u044B\u0442 \u2014 \u0432 \u043D\u0451\u043C \u043E\u0442\u043A\u0440\u044B\u0442\u044B\u0435 \u0437\u0430\u0434\u0430\u0447\u0438: ${fix.childIds.join(", ")}`;
1403
1509
  case "source-moved":
1404
- return sourcePath(fix.from) === sourcePath(fix.to) ? `${fix.taskId}: source \u0441\u0434\u0432\u0438\u043D\u0443\u043B\u0441\u044F ${lineSuffix(fix.from)} \u2192 ${lineSuffix(fix.to)}` : `${fix.taskId}: \u0444\u0430\u0439\u043B \u0437\u0430\u0434\u0430\u0447\u0438 \u043F\u0435\u0440\u0435\u0438\u043C\u0435\u043D\u043E\u0432\u0430\u043D, source ${fix.from} \u2192 ${fix.to}`;
1510
+ return sourcePath(fix.from) === sourcePath(fix.to) ? `${fix.taskId}: source \u0441\u0434\u0432\u0438\u043D\u0443\u043B\u0441\u044F ${lineSuffix(fix.from)} \u2192 ${lineSuffix(fix.to)}` : `${fix.taskId}: \u0444\u0430\u0439\u043B \u043A\u043E\u0434\u0430 \u043F\u0435\u0440\u0435\u0438\u043C\u0435\u043D\u043E\u0432\u0430\u043D, source ${fix.from} \u2192 ${fix.to}`;
1405
1511
  }
1406
1512
  }
1407
1513
  function checkProblem2(p) {
@@ -1424,6 +1530,10 @@ function checkProblem2(p) {
1424
1530
  return `\u041F\u0440\u043E\u0435\u043A\u0442 ${p.projectId}: git \u043D\u0435 \u0434\u043E\u0432\u0435\u0440\u044F\u0435\u0442 ${p.repo} (\u043A\u0430\u0442\u0430\u043B\u043E\u0433 \u043F\u0440\u0438\u043D\u0430\u0434\u043B\u0435\u0436\u0438\u0442 \u0434\u0440\u0443\u0433\u043E\u043C\u0443 \u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044E) \u2014 \u043A\u043E\u043C\u043C\u0438\u0442\u044B \u0438 \u043F\u0440\u0430\u0432\u043A\u0438 \u043A\u043E\u0434\u0430 \u0435\u0433\u043E \u0437\u0430\u0434\u0430\u0447 \u043D\u0435 \u043F\u0440\u043E\u0432\u0435\u0440\u044F\u044E\u0442\u0441\u044F. \u0418\u0441\u043F\u0440\u0430\u0432\u043B\u0435\u043D\u0438\u0435: git config --global --add safe.directory "${p.repo}"`;
1425
1531
  case "project-history-unreadable":
1426
1532
  return `\u041F\u0440\u043E\u0435\u043A\u0442 ${p.projectId}: \u043D\u0435 \u0443\u0434\u0430\u043B\u043E\u0441\u044C \u043F\u0440\u043E\u0447\u0438\u0442\u0430\u0442\u044C \u0438\u0441\u0442\u043E\u0440\u0438\u044E git \u0432 ${p.repo} \u2014 \u043A\u043E\u043C\u043C\u0438\u0442\u044B \u0438 \u043F\u0440\u0430\u0432\u043A\u0438 \u043A\u043E\u0434\u0430 \u0435\u0433\u043E \u0437\u0430\u0434\u0430\u0447 \u043D\u0435 \u043F\u0440\u043E\u0432\u0435\u0440\u0435\u043D\u044B`;
1533
+ case "project-branches-unreadable":
1534
+ return `\u041F\u0440\u043E\u0435\u043A\u0442 ${p.projectId}: \u043D\u0435 \u0443\u0434\u0430\u043B\u043E\u0441\u044C \u043F\u0440\u043E\u0447\u0438\u0442\u0430\u0442\u044C \u0432\u0435\u0442\u043A\u0438 git \u0432 ${p.repo} (\u0431\u0438\u0442\u0430\u044F \u0441\u0441\u044B\u043B\u043A\u0430 \u0432 refs \u0438\u043B\u0438 \u0441\u0431\u043E\u0439 git) \u2014 \u043F\u0440\u043E\u043F\u0430\u0432\u0448\u0438\u0435 \u0444\u0430\u0439\u043B\u044B \u043A\u043E\u0434\u0430 \u0435\u0433\u043E \u0437\u0430\u0434\u0430\u0447 \u043D\u0435 \u043F\u0440\u043E\u0432\u0435\u0440\u0435\u043D\u044B`;
1535
+ case "merge-state-unknown":
1536
+ return `\u041F\u0440\u043E\u0435\u043A\u0442 ${p.projectId}: git \u0432 ${p.repo} \u043D\u0435 \u0441\u043C\u043E\u0433 \u043E\u0442\u0432\u0435\u0442\u0438\u0442\u044C, ${p.branches.length === 1 ? "\u0432\u043B\u0438\u0442\u0430 \u043B\u0438 \u0432\u0435\u0442\u043A\u0430" : "\u0432\u043B\u0438\u0442\u044B \u043B\u0438 \u0432\u0435\u0442\u043A\u0438"} ${p.branches.join(", ")} \u0432 \u0442\u0435\u043A\u0443\u0449\u0443\u044E (\u043D\u0435\u043F\u043E\u043B\u043D\u044B\u0439 \u043A\u043B\u043E\u043D, \u043D\u0435\u0441\u0432\u044F\u0437\u0430\u043D\u043D\u0430\u044F \u0438\u0441\u0442\u043E\u0440\u0438\u044F \u0438\u043B\u0438 \u0441\u0431\u043E\u0439 git) \u2014 \u0441\u043E\u0437\u0434\u0430\u043D\u043D\u044B\u0435 \u0442\u0430\u043C \u0437\u0430\u0434\u0430\u0447\u0438 \u043F\u0440\u043E\u0432\u0435\u0440\u0435\u043D\u044B \u043A\u0430\u043A \u043E\u0431\u044B\u0447\u043D\u044B\u0435, \u0431\u0435\u0437 \u043E\u0436\u0438\u0434\u0430\u043D\u0438\u044F \u0441\u043B\u0438\u044F\u043D\u0438\u044F`;
1427
1537
  case "prefix-shared":
1428
1538
  return `\u0423 \u043F\u0440\u043E\u0435\u043A\u0442\u043E\u0432 ${p.projectIds.join(", ")} \u043E\u0434\u0438\u043D \u043F\u0440\u0435\u0444\u0438\u043A\u0441 ${p.prefix} \u2014 ID \u0438\u0445 \u0437\u0430\u0434\u0430\u0447 \u043F\u0435\u0440\u0435\u0441\u0435\u043A\u0430\u044E\u0442\u0441\u044F. \u0421\u043C\u0435\u043D\u0438\u0442\u0435 prefix \u0432 project.md \u043E\u0434\u043D\u043E\u0433\u043E \u0438\u0437 \u043D\u0438\u0445`;
1429
1539
  }
@@ -1485,7 +1595,7 @@ function isBacklogHookFeedback(text) {
1485
1595
  }
1486
1596
 
1487
1597
  // src/core/store/journal-compaction.ts
1488
- import { join as join8 } from "node:path";
1598
+ import { basename as basename5, join as join9 } from "node:path";
1489
1599
 
1490
1600
  // src/core/collections.ts
1491
1601
  function groupBy(items, keyOf) {
@@ -1506,6 +1616,9 @@ function countBy(items, keyOf, amountOf = () => 1) {
1506
1616
  }
1507
1617
  return totals2;
1508
1618
  }
1619
+ function partition(items, matches) {
1620
+ return [items.filter(matches), items.filter((item) => !matches(item))];
1621
+ }
1509
1622
 
1510
1623
  // src/core/journal/creation.ts
1511
1624
  function taskCreation(record, created) {
@@ -1743,13 +1856,13 @@ function filteredEvents(filtered, states, now) {
1743
1856
  const byKey = new Map(filtered.map((sighting) => [filteredKey(sighting.task, sighting.symbol), sighting]));
1744
1857
  return [...byKey.entries()].filter(([key]) => states.get(key) !== "open").map(([, { task, symbol }]) => ({ at, task, via: "check", kind: "candidate-filtered", symbol }));
1745
1858
  }
1746
- function candidateGoneEvents({ sightings, reviewed, checked = CANDIDATE_EVIDENCE }, states, now) {
1859
+ function candidateGoneEvents({ sightings, reviewed, unchecked = [] }, states, now) {
1747
1860
  const at = formatLocalIso(now);
1748
- const seen = new Set(sightings.map((sighting) => episodeKey(sighting.task, sighting.evidence)));
1861
+ const stillOpen = new Set([...sightings, ...unchecked].map((sighting) => episodeKey(sighting.task, sighting.evidence)));
1749
1862
  return reviewed.flatMap(
1750
- (task) => checked.flatMap((evidence2) => {
1863
+ (task) => CANDIDATE_EVIDENCE.flatMap((evidence2) => {
1751
1864
  const key = episodeKey(task, evidence2);
1752
- return seen.has(key) || states.get(key) !== "open" ? [] : [{ at, task, via: "check", kind: "candidate-gone", evidence: evidence2 }];
1865
+ return stillOpen.has(key) || states.get(key) !== "open" ? [] : [{ at, task, via: "check", kind: "candidate-gone", evidence: evidence2 }];
1753
1866
  })
1754
1867
  );
1755
1868
  }
@@ -1868,9 +1981,10 @@ async function appendJournal(projectDir2, events, onError) {
1868
1981
  onError(path, error);
1869
1982
  }
1870
1983
  }
1984
+ var JOURNAL_LOCK_WAIT_MS = REPLACE_RETRIES_TOTAL_MS + 10 * SECOND_MS;
1871
1985
  async function appendWaitingForLock(path, events) {
1872
1986
  try {
1873
- await withFileLock(path, () => appendJsonLines(path, events));
1987
+ await withFileLock(path, () => appendJsonLines(path, events), { waitLimitMs: JOURNAL_LOCK_WAIT_MS });
1874
1988
  } catch (error) {
1875
1989
  if (!(error instanceof FileBusyError)) throw error;
1876
1990
  await appendJsonLines(path, events);
@@ -1907,13 +2021,54 @@ async function readJournals(root, projectIds) {
1907
2021
  return Promise.all(projectIds.map((projectId) => readJournal(join7(root, projectId), projectId)));
1908
2022
  }
1909
2023
 
2024
+ // src/core/store/projects.ts
2025
+ import { rm as rm4 } from "node:fs/promises";
2026
+ import { join as join8 } from "node:path";
2027
+ var NOT_FOUND2 = { ok: false, reason: "not-found" };
2028
+ async function setProjectActive(root, id, active) {
2029
+ const dir = projectDir(root, id);
2030
+ if (dir === null) return NOT_FOUND2;
2031
+ return editProjectFile({ id, path: join8(dir, PROJECT_FILE) }, (project) => project.active === active ? project : { ...project, active });
2032
+ }
2033
+ function reserveIssuedUpTo(project, number) {
2034
+ return editProjectFile(project, (current) => {
2035
+ const issuedUpTo = Math.max(current.issuedUpTo ?? 0, number);
2036
+ return issuedUpTo === current.issuedUpTo ? current : { ...current, issuedUpTo };
2037
+ });
2038
+ }
2039
+ async function issuedUpToOnDisk(project) {
2040
+ const parsed = await readProjectFile(project);
2041
+ return parsed?.ok === true ? parsed.value.issuedUpTo ?? 0 : 0;
2042
+ }
2043
+ async function readProjectFile({ id, path }) {
2044
+ return parseDocumentOrNull(path, (text) => parseProjectFile(text, { id, path }));
2045
+ }
2046
+ async function editProjectFile({ id, path }, edit) {
2047
+ if (!await fileExists(path)) return NOT_FOUND2;
2048
+ return withFileLock(path, async () => {
2049
+ const parsed = await readProjectFile({ id, path });
2050
+ if (parsed === null) return NOT_FOUND2;
2051
+ if (!parsed.ok) return { ok: false, reason: "invalid", problems: parsed.problems };
2052
+ const project = edit(parsed.value);
2053
+ const changed = project !== parsed.value;
2054
+ if (changed) await writeFileAtomic(path, serializeProject(project));
2055
+ return { ok: true, project, changed };
2056
+ });
2057
+ }
2058
+ async function deleteProject(root, id) {
2059
+ const dir = projectDir(root, id);
2060
+ if (dir === null || await readTextOrNull(join8(dir, PROJECT_FILE)) === null) return NOT_FOUND2;
2061
+ await rm4(dir, { recursive: true, force: true });
2062
+ return { ok: true };
2063
+ }
2064
+
1910
2065
  // src/core/store/journal-compaction.ts
1911
2066
  var COMPACTED_STAMP = ".journal-compacted-at";
1912
2067
  var EPISODE_KINDS = /* @__PURE__ */ new Set(["candidate", "candidate-gone", "candidate-filtered", "verified"]);
1913
2068
  async function compactJournalsWhenDue(root, now, failed2) {
1914
2069
  const compacted = [];
1915
2070
  for (const name of await projectDirNames(root)) {
1916
- const dir = join8(root, name);
2071
+ const dir = join9(root, name);
1917
2072
  const removed = await compactProjectWhenDue(dir, now).catch((error) => {
1918
2073
  failed2(dir, error);
1919
2074
  return null;
@@ -1923,11 +2078,11 @@ async function compactJournalsWhenDue(root, now, failed2) {
1923
2078
  return compacted;
1924
2079
  }
1925
2080
  async function compactProjectWhenDue(dir, now) {
1926
- if (!await fileExists(join8(dir, JOURNAL_FILE))) return null;
1927
- return runWhenDue(join8(dir, COMPACTED_STAMP), now, async () => compactJournal(dir, await taskIdsOnDisk(dir), now));
2081
+ if (!await fileExists(join9(dir, JOURNAL_FILE))) return null;
2082
+ return runWhenDue(join9(dir, COMPACTED_STAMP), now, async () => compactJournal(dir, await taskIdsOnDisk(dir), now));
1928
2083
  }
1929
2084
  async function compactJournal(projectDir2, liveTaskIds, now) {
1930
- const path = join8(projectDir2, JOURNAL_FILE);
2085
+ const path = join9(projectDir2, JOURNAL_FILE);
1931
2086
  if (!await fileExists(path)) return 0;
1932
2087
  return withFileLock(path, async () => {
1933
2088
  const journal = await readBytesOrNull(path) ?? Buffer.alloc(0);
@@ -1935,11 +2090,19 @@ async function compactJournal(projectDir2, liveTaskIds, now) {
1935
2090
  const lines = journalLines(completeLines.toString("utf8"));
1936
2091
  const kept = retainedLines(lines, liveTaskIds, retainedSince(now));
1937
2092
  const removed = lines.length - kept.length;
1938
- const replaced = removed > 0 && await replacePrefixAtomic(path, completeLines, kept.map(({ text }) => `${text}
2093
+ if (removed === 0 || !await reserveRemovedNumbers(projectDir2, lines, kept)) return 0;
2094
+ const replaced = await replacePrefixAtomic(path, completeLines, kept.map(({ text }) => `${text}
1939
2095
  `).join(""));
1940
2096
  return replaced ? removed : 0;
1941
2097
  });
1942
2098
  }
2099
+ async function reserveRemovedNumbers(projectDir2, lines, kept) {
2100
+ const keptLines = new Set(kept);
2101
+ const highest = lines.reduce((max, line) => keptLines.has(line) || line.event === null ? max : Math.max(max, parseId(line.event.task)?.number ?? 0), 0);
2102
+ if (highest === 0) return true;
2103
+ const reservation = await reserveIssuedUpTo({ id: basename5(projectDir2), path: join9(projectDir2, PROJECT_FILE) }, highest);
2104
+ return reservation.ok || reservation.reason === "not-found";
2105
+ }
1943
2106
  function journalLines(text) {
1944
2107
  return text.split("\n").filter((line) => line.trim() !== "").map((line) => ({ text: line, event: parseJson(line, journalEventSchema) }));
1945
2108
  }
@@ -1993,7 +2156,7 @@ function serviceLogToTrim(platform, home2) {
1993
2156
  return platform === "darwin" ? launchdLogPath(home2) : null;
1994
2157
  }
1995
2158
  async function trimLogFile(path, limitBytes, keptBytes) {
1996
- return await withExistingFile(path, (handle) => trimOpenLog(handle, limitBytes, keptBytes), "r+") ?? false;
2159
+ return await withExistingFile(path, (handle) => trimOpenLog(handle, limitBytes, keptBytes), { flags: "r+" }) ?? false;
1997
2160
  }
1998
2161
  async function trimOpenLog(handle, limitBytes, keptBytes) {
1999
2162
  const { size } = await handle.stat();
@@ -2022,7 +2185,7 @@ function invalidTasksText(invalid2) {
2022
2185
  }
2023
2186
 
2024
2187
  // src/core/store/sweep.ts
2025
- import { dirname as dirname4, join as join10 } from "node:path";
2188
+ import { dirname as dirname5, join as join10 } from "node:path";
2026
2189
 
2027
2190
  // src/core/model/lifecycle.ts
2028
2191
  var RETENTION_DAYS = 7;
@@ -2043,13 +2206,20 @@ function settleLifecycle(task, now) {
2043
2206
  if (!isClosed(task.status)) return { ...task, closed: void 0, resolution: void 0, reason: void 0 };
2044
2207
  return task.closed === void 0 ? { ...task, closed: formatLocalIso(now) } : task;
2045
2208
  }
2046
- function deletionDate(task) {
2209
+ function scheduledDeletion(task, index) {
2047
2210
  if (!isClosed(task.status) || task.closed === void 0) return void 0;
2048
- return new Date(Date.parse(task.closed) + RETENTION_DAYS * DAY_MS);
2211
+ const keeper = keepingEpic(task, index);
2212
+ return keeper === void 0 ? { at: new Date(Date.parse(task.closed) + RETENTION_DAYS * DAY_MS) } : { afterEpic: keeper.id };
2049
2213
  }
2050
- function isExpired(task, now) {
2051
- const deletesAt = deletionDate(task);
2052
- return deletesAt !== void 0 && deletesAt.getTime() <= now.getTime();
2214
+ function isExpired(task, now, index) {
2215
+ const deletion = scheduledDeletion(task, index);
2216
+ return deletion !== void 0 && "at" in deletion && deletion.at.getTime() <= now.getTime();
2217
+ }
2218
+ function keepingEpic(task, index) {
2219
+ const epic = task.epic === void 0 ? void 0 : index.byId.get(task.epic);
2220
+ if (epic?.type !== "epic") return void 0;
2221
+ const reopensWithOpenTasks = isAutoClosedEpic(epic) && openChildIds(epic, index).length > 0;
2222
+ return !isClosed(epic.status) || reopensWithOpenTasks ? epic : void 0;
2053
2223
  }
2054
2224
  function planEpicClosing(tasks, parseErrors) {
2055
2225
  const unreadableProjects = new Set(parseErrors.map((error) => error.projectId));
@@ -2075,14 +2245,22 @@ function completedEpicChildren(task, index) {
2075
2245
  function isAutoClosedEpic(task) {
2076
2246
  return task.type === "epic" && isClosed(task.status) && task.resolution === "epic-done";
2077
2247
  }
2248
+ function openChildIds(epic, index) {
2249
+ return epicChildren(epic, index).flatMap((child) => isClosed(child.status) ? [] : [child.id]);
2250
+ }
2078
2251
  function planEpicReopening(tasks) {
2079
2252
  const index = buildIndex(tasks);
2080
2253
  return tasks.flatMap((epic) => {
2081
2254
  if (!isAutoClosedEpic(epic)) return [];
2082
- const openChildIds = epicChildren(epic, index).flatMap((child) => isClosed(child.status) ? [] : [child.id]);
2083
- return openChildIds.length === 0 ? [] : [{ epic, childIds: openChildIds }];
2255
+ const childIds = openChildIds(epic, index);
2256
+ return childIds.length === 0 ? [] : [{ epic, childIds }];
2084
2257
  });
2085
2258
  }
2259
+ function epicClosingProblems(before, after, index) {
2260
+ if (after.type !== "epic" || !isClosed(after.status) || isClosed(before.status)) return [];
2261
+ const childIds = openChildIds(after, index);
2262
+ return childIds.length === 0 ? [] : [{ code: "epic-closed-with-open-tasks", children: childIds }];
2263
+ }
2086
2264
  function epicDoneClosure(childIds, messages) {
2087
2265
  return { resolution: "epic-done", reason: messages.epicDoneReason(childIds) };
2088
2266
  }
@@ -2091,47 +2269,6 @@ function closedAt(task, status, now) {
2091
2269
  return isClosed(task.status) ? task.closed : formatLocalIso(now);
2092
2270
  }
2093
2271
 
2094
- // src/core/store/projects.ts
2095
- import { rm as rm3 } from "node:fs/promises";
2096
- import { join as join9 } from "node:path";
2097
- var NOT_FOUND2 = { ok: false, reason: "not-found" };
2098
- async function setProjectActive(root, id, active) {
2099
- const dir = projectDir(root, id);
2100
- if (dir === null) return NOT_FOUND2;
2101
- return editProjectFile({ id, path: join9(dir, PROJECT_FILE) }, (project) => ({ ...project, active }));
2102
- }
2103
- function reserveIssuedUpTo(project, number) {
2104
- return editProjectFile(project, (current) => {
2105
- const issuedUpTo = Math.max(current.issuedUpTo ?? 0, number);
2106
- return issuedUpTo === current.issuedUpTo ? current : { ...current, issuedUpTo };
2107
- });
2108
- }
2109
- async function issuedUpToOnDisk(project) {
2110
- const parsed = await readProjectFile(project);
2111
- return parsed?.ok === true ? parsed.value.issuedUpTo ?? 0 : 0;
2112
- }
2113
- async function readProjectFile({ id, path }) {
2114
- const text = await readTextOrNull(path);
2115
- return text === null ? null : parseProjectFile(text, { id, path });
2116
- }
2117
- async function editProjectFile({ id, path }, edit) {
2118
- if (!await fileExists(path)) return NOT_FOUND2;
2119
- return withFileLock(path, async () => {
2120
- const parsed = await readProjectFile({ id, path });
2121
- if (parsed === null) return NOT_FOUND2;
2122
- if (!parsed.ok) return { ok: false, reason: "invalid", problems: parsed.problems };
2123
- const project = edit(parsed.value);
2124
- if (project !== parsed.value) await writeFileAtomic(path, serializeProject(project));
2125
- return { ok: true, project };
2126
- });
2127
- }
2128
- async function deleteProject(root, id) {
2129
- const dir = projectDir(root, id);
2130
- if (dir === null || await readTextOrNull(join9(dir, PROJECT_FILE)) === null) return NOT_FOUND2;
2131
- await rm3(dir, { recursive: true, force: true });
2132
- return { ok: true };
2133
- }
2134
-
2135
2272
  // src/core/store/references.ts
2136
2273
  function referenceCleanup(task, isGone) {
2137
2274
  const blockedBy = task.blockedBy.filter((id) => !isGone(id));
@@ -2143,7 +2280,7 @@ function referenceCleanup(task, isGone) {
2143
2280
  }
2144
2281
 
2145
2282
  // src/core/store/update.ts
2146
- import { dirname as dirname3 } from "node:path";
2283
+ import { dirname as dirname4 } from "node:path";
2147
2284
 
2148
2285
  // src/core/model/integrity.ts
2149
2286
  function integrityErrors(candidate, index) {
@@ -2212,6 +2349,12 @@ function taskText(draft) {
2212
2349
  function writtenTasks({ task, reopenedEpic }) {
2213
2350
  return reopenedEpic === void 0 ? [task] : [task, reopenedEpic];
2214
2351
  }
2352
+ function withWrittenTasks(tasks, results) {
2353
+ const written = results.flatMap(writtenTasks);
2354
+ const byId = new Map(written.map((task) => [task.id, task]));
2355
+ const known = new Set(tasks.map((task) => task.id));
2356
+ return [...tasks.map((task) => byId.get(task.id) ?? task), ...written.filter((task) => !known.has(task.id))];
2357
+ }
2215
2358
  function invalid(problems3) {
2216
2359
  return { ok: false, reason: "invalid", problems: problems3 };
2217
2360
  }
@@ -2227,7 +2370,7 @@ async function updateTaskInIndex(index, request) {
2227
2370
  return reopenedEpic === void 0 ? result : { ...result, reopenedEpic };
2228
2371
  }
2229
2372
  async function statusToReopen(epic) {
2230
- const { events } = await readJournal(dirname3(epic.path), epic.projectId);
2373
+ const { events } = await readJournal(dirname4(epic.path), epic.projectId);
2231
2374
  return statusBeforeAutoClose(events, epic.id);
2232
2375
  }
2233
2376
  async function reopenEpicOfOpenedTask(index, { before, after }, { now, via, onError, journal }) {
@@ -2251,15 +2394,16 @@ async function writeChanges(index, { id, changes, expectedVersion, now, closure,
2251
2394
  const normalized = taskText(applyChanges(current, changes, now, closure));
2252
2395
  if (!normalized.ok) return invalid(normalized.problems);
2253
2396
  const { text, task } = normalized.value;
2254
- const problems3 = integrityErrors(task, index);
2397
+ const problems3 = [...integrityErrors(task, index), ...epicClosingProblems(current, task, index)];
2255
2398
  if (problems3.length > 0) return invalid(problems3);
2256
- return withTaskLock(current.path, async () => {
2399
+ const written = await withTaskLock(current.path, async () => {
2257
2400
  const changedOnDisk = await diskChange(current, expectedVersion);
2258
2401
  if (changedOnDisk !== null) return changedOnDisk;
2259
2402
  await writeFileAtomic(current.path, text);
2260
- await journal(dirname3(current.path), changeEvents(current, task, now, via));
2261
2403
  return { ok: true, task };
2262
2404
  });
2405
+ if (written.ok) await journal(dirname4(current.path), changeEvents(current, task, now, via));
2406
+ return written;
2263
2407
  }
2264
2408
  async function withTaskLock(path, write) {
2265
2409
  try {
@@ -2270,8 +2414,10 @@ async function withTaskLock(path, write) {
2270
2414
  }
2271
2415
  }
2272
2416
  async function diskChange(snapshot, expectedVersion) {
2273
- const text = await readTextOrNull(snapshot.path);
2274
- if (text === null) return { ok: false, reason: "not-found" };
2417
+ const document = await readDocumentOrNull(snapshot.path);
2418
+ if (document === null) return { ok: false, reason: "not-found" };
2419
+ if (!document.ok) return invalid(document.problems);
2420
+ const text = document.value;
2275
2421
  const version = contentVersion(text);
2276
2422
  if (version === expectedVersion) return null;
2277
2423
  const fresh = parseTaskFile(text, { projectId: snapshot.projectId, path: snapshot.path, version });
@@ -2320,9 +2466,9 @@ async function sweepClosed(root, writes, messages) {
2320
2466
  const reopening = await reopenEpicsWithOpenTasks(initial, writes);
2321
2467
  const epics = await closeCompletedEpics(initial, writes, messages);
2322
2468
  const { projects, tasks } = epics.closed.length > 0 || reopening.reopened.length > 0 ? await loadBacklog(root) : initial;
2323
- const waitsForEpic = (task) => task.epic !== void 0 && epics.leftOpen.has(task.epic);
2469
+ const index = buildIndex(tasks);
2324
2470
  const stillHoldsOpenTasks = new Set(planEpicReopening(tasks).map(({ epic }) => epic.id));
2325
- const expired = tasks.filter((task) => isExpired(task, now) && !waitsForEpic(task) && !stillHoldsOpenTasks.has(task.id));
2471
+ const expired = tasks.filter((task) => isExpired(task, now, index) && !stillHoldsOpenTasks.has(task.id));
2326
2472
  const reserved = await reserveNumbers(projects, expired);
2327
2473
  const removable = expired.filter((task) => reserved.has(task.projectId));
2328
2474
  const removal = await removeWithReferences(tasks, removable, writes);
@@ -2388,10 +2534,9 @@ async function closeCompletedEpics(loaded, writes, messages) {
2388
2534
  if (result.ok) closed.push(epic.id);
2389
2535
  else failures.push(sweepFailure(epic.id, result));
2390
2536
  }
2391
- const leftOpen = /* @__PURE__ */ new Set([...plan.waiting.map(({ epic }) => epic.id), ...failures.map(({ id }) => id)]);
2392
2537
  const waitingProjects = new Set(plan.waiting.map(({ epic }) => epic.projectId));
2393
2538
  const blockingFiles = loaded.errors.filter((error) => waitingProjects.has(error.projectId)).map((error) => error.path);
2394
- return { closed, failures, leftOpen, blockingFiles };
2539
+ return { closed, failures, blockingFiles };
2395
2540
  }
2396
2541
  async function repairRemainingTasks(tasks, { skipped, removed }, writes) {
2397
2542
  const index = buildIndex(tasks);
@@ -2424,7 +2569,7 @@ async function removeLocked(expired, { now, onError }) {
2424
2569
  if (outcome === "changed") failures.push({ id: task.id, reason: "conflict" });
2425
2570
  if (outcome !== "removed") continue;
2426
2571
  deleted.push(task.id);
2427
- await appendJournal(dirname4(task.path), [deletedEvent(task, now, "sweep")], onError);
2572
+ await appendJournal(dirname5(task.path), [deletedEvent(task, now, "sweep")], onError);
2428
2573
  }
2429
2574
  return { deleted, failures };
2430
2575
  }
@@ -2460,10 +2605,13 @@ async function reserveNumbers(projects, expired) {
2460
2605
  // src/cli/messages.en.ts
2461
2606
  var cliEn = {
2462
2607
  usageHeader: "Usage:",
2608
+ alreadySet: (id, value) => `${id}: already ${value}`,
2463
2609
  extraArguments: (args) => `Extra arguments: ${args.join(" ")}`,
2464
2610
  argumentProblem: {
2465
2611
  unknownOption: (option) => `Unknown option ${option}`,
2466
2612
  missingValue: (option) => `Option ${option} needs a value`,
2613
+ valueLooksLikeOption: (option) => `Option ${option} needs a value. If the value starts with "-", pass it as ${option}=value`,
2614
+ repeated: (option) => `Option ${option} is given twice`,
2467
2615
  takesNoValue: (option) => `Option ${option} does not take a value`
2468
2616
  },
2469
2617
  invalidChoice: (label, allowed, value) => `${label}: expected one of ${allowed.join(", ")}, got "${value}"`,
@@ -2551,6 +2699,7 @@ var cliEn = {
2551
2699
  taskFileUnparsed: (id, problems3) => `Task file ${id} could not be parsed: ${problems3}`,
2552
2700
  projectNotFoundForCwd: (cwd) => `No project found for ${cwd}. Pass --project <id> or add the path to repos of the right project.md`,
2553
2701
  projectNotFound: (id) => `Project ${id} not found`,
2702
+ projectFileUnparsed: (path, problems3) => `Project not loaded: ${path} could not be parsed (${problems3})`,
2554
2703
  notInGitRepo: (cwd) => `${cwd} is not inside a git repository: project not created. Pass --project <id> or run the command from a repository`,
2555
2704
  projectCreated: (id, prefix) => `Created project ${id} (${prefix})`,
2556
2705
  projectNotCreatedFileUnparsed: (path, problems3) => `Project not created: ${path} could not be parsed (${problems3}). Fix the file, otherwise a new project could repeat its prefix and task numbers`,
@@ -2581,6 +2730,8 @@ var cliEn = {
2581
2730
  taskCancelled: (id) => `${id}: cancelled`,
2582
2731
  verifyUsage: () => "<ID> [<ID> \u2026] [--source file:line \u2014 only for a single task]",
2583
2732
  sourceEmpty: "--source cannot be empty",
2733
+ sourceFileMissing: (source) => `--source ${source}: no such file in the project repository \u2014 check the path`,
2734
+ sourceFileUnchecked: (source) => `--source ${source}: the file is not on disk and git branches could not be read \u2014 the path was not checked, check it yourself`,
2584
2735
  alreadyInStatusNothingToVerify: (id, status) => `${id} is already ${status}: nothing to confirm`,
2585
2736
  verified: (id) => `${id}: confirmed`,
2586
2737
  verifiedWithSource: (id, source) => `${id}: confirmed, source \u2192 ${source}`,
@@ -2628,6 +2779,7 @@ var cliEn = {
2628
2779
  originalAlreadyClosed: (id, taskId) => `${id} is already closed \u2014 close ${taskId} as fixed or obsolete instead`,
2629
2780
  fixCommitRequired: 'Provide the fix commit: --reason "Fixed in <sha>: \u2026" (the commit must be in the project repository)',
2630
2781
  deletesAtTail: (date) => `. Will be deleted ${date}`,
2782
+ afterEpicCloses: (epic) => `after epic ${epic} closes`,
2631
2783
  listUsage: () => "[--query text] [--status s,\u2026] [--tag t,\u2026] [--project id | --all-projects] [--json]",
2632
2784
  parseErrorLine: (path, problems3) => `Parse error in ${path}: ${problems3}`,
2633
2785
  noTasksFound: "No tasks found",
@@ -2640,10 +2792,13 @@ var cliEn = {
2640
2792
  // src/cli/messages.ru.ts
2641
2793
  var cliRu = {
2642
2794
  usageHeader: "\u0418\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u0435:",
2795
+ alreadySet: (id, value) => `${id}: \u0443\u0436\u0435 ${value}`,
2643
2796
  extraArguments: (args) => `\u041B\u0438\u0448\u043D\u0438\u0435 \u0430\u0440\u0433\u0443\u043C\u0435\u043D\u0442\u044B: ${args.join(" ")}`,
2644
2797
  argumentProblem: {
2645
2798
  unknownOption: (option) => `\u041D\u0435\u0438\u0437\u0432\u0435\u0441\u0442\u043D\u044B\u0439 \u043F\u0430\u0440\u0430\u043C\u0435\u0442\u0440 ${option}`,
2646
2799
  missingValue: (option) => `\u0423 \u043F\u0430\u0440\u0430\u043C\u0435\u0442\u0440\u0430 ${option} \u043D\u0435\u0442 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u044F`,
2800
+ valueLooksLikeOption: (option) => `\u0423 \u043F\u0430\u0440\u0430\u043C\u0435\u0442\u0440\u0430 ${option} \u043D\u0435\u0442 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u044F. \u0415\u0441\u043B\u0438 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435 \u043D\u0430\u0447\u0438\u043D\u0430\u0435\u0442\u0441\u044F \u0441 \xAB-\xBB, \u043F\u0435\u0440\u0435\u0434\u0430\u0439\u0442\u0435 \u0435\u0433\u043E \u0442\u0430\u043A: ${option}=\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435`,
2801
+ repeated: (option) => `\u041F\u0430\u0440\u0430\u043C\u0435\u0442\u0440 ${option} \u0443\u043A\u0430\u0437\u0430\u043D \u0434\u0432\u0430\u0436\u0434\u044B`,
2647
2802
  takesNoValue: (option) => `\u041F\u0430\u0440\u0430\u043C\u0435\u0442\u0440 ${option} \u043D\u0435 \u043F\u0440\u0438\u043D\u0438\u043C\u0430\u0435\u0442 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u044F`
2648
2803
  },
2649
2804
  invalidChoice: (label, allowed, value) => `${label}: \u043E\u0436\u0438\u0434\u0430\u0435\u0442\u0441\u044F \u043E\u0434\u043D\u043E \u0438\u0437 ${allowed.join(", ")}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D\u043E \xAB${value}\xBB`,
@@ -2731,6 +2886,7 @@ var cliRu = {
2731
2886
  taskFileUnparsed: (id, problems3) => `\u0424\u0430\u0439\u043B \u0437\u0430\u0434\u0430\u0447\u0438 ${id} \u043D\u0435 \u0440\u0430\u0437\u043E\u0431\u0440\u0430\u043D: ${problems3}`,
2732
2887
  projectNotFoundForCwd: (cwd) => `\u041F\u0440\u043E\u0435\u043A\u0442 \u0434\u043B\u044F ${cwd} \u043D\u0435 \u043D\u0430\u0439\u0434\u0435\u043D. \u0423\u043A\u0430\u0436\u0438\u0442\u0435 --project <id> \u0438\u043B\u0438 \u0434\u043E\u0431\u0430\u0432\u044C\u0442\u0435 \u043F\u0443\u0442\u044C \u0432 repos \u043D\u0443\u0436\u043D\u043E\u0433\u043E project.md`,
2733
2888
  projectNotFound: (id) => `\u041F\u0440\u043E\u0435\u043A\u0442 ${id} \u043D\u0435 \u043D\u0430\u0439\u0434\u0435\u043D`,
2889
+ projectFileUnparsed: (path, problems3) => `\u041F\u0440\u043E\u0435\u043A\u0442 \u043D\u0435 \u0437\u0430\u0433\u0440\u0443\u0436\u0435\u043D: ${path} \u043D\u0435 \u0440\u0430\u0437\u043E\u0431\u0440\u0430\u043D (${problems3})`,
2734
2890
  notInGitRepo: (cwd) => `${cwd} \u043D\u0435 \u0432 git-\u0440\u0435\u043F\u043E\u0437\u0438\u0442\u043E\u0440\u0438\u0438: \u043F\u0440\u043E\u0435\u043A\u0442 \u043D\u0435 \u0441\u043E\u0437\u0434\u0430\u043D. \u0423\u043A\u0430\u0436\u0438\u0442\u0435 --project <id> \u0438\u043B\u0438 \u0437\u0430\u043F\u0443\u0441\u0442\u0438\u0442\u0435 \u043A\u043E\u043C\u0430\u043D\u0434\u0443 \u0438\u0437 \u0440\u0435\u043F\u043E\u0437\u0438\u0442\u043E\u0440\u0438\u044F`,
2735
2891
  projectCreated: (id, prefix) => `\u0421\u043E\u0437\u0434\u0430\u043D \u043F\u0440\u043E\u0435\u043A\u0442 ${id} (${prefix})`,
2736
2892
  projectNotCreatedFileUnparsed: (path, problems3) => `\u041F\u0440\u043E\u0435\u043A\u0442 \u043D\u0435 \u0441\u043E\u0437\u0434\u0430\u043D: ${path} \u043D\u0435 \u0440\u0430\u0437\u043E\u0431\u0440\u0430\u043D (${problems3}). \u0418\u0441\u043F\u0440\u0430\u0432\u044C\u0442\u0435 \u0444\u0430\u0439\u043B \u2014 \u0438\u043D\u0430\u0447\u0435 \u043D\u043E\u0432\u044B\u0439 \u043F\u0440\u043E\u0435\u043A\u0442 \u043C\u043E\u0436\u0435\u0442 \u043F\u043E\u0432\u0442\u043E\u0440\u0438\u0442\u044C \u0435\u0433\u043E \u043F\u0440\u0435\u0444\u0438\u043A\u0441 \u0438 \u043D\u043E\u043C\u0435\u0440\u0430 \u0437\u0430\u0434\u0430\u0447`,
@@ -2761,6 +2917,8 @@ var cliRu = {
2761
2917
  taskCancelled: (id) => `${id}: \u043E\u0442\u043C\u0435\u043D\u0435\u043D\u0430`,
2762
2918
  verifyUsage: () => "<ID> [<ID> \u2026] [--source \u0444\u0430\u0439\u043B:\u0441\u0442\u0440\u043E\u043A\u0430 \u2014 \u0442\u043E\u043B\u044C\u043A\u043E \u0434\u043B\u044F \u043E\u0434\u043D\u043E\u0439 \u0437\u0430\u0434\u0430\u0447\u0438]",
2763
2919
  sourceEmpty: "--source \u043D\u0435 \u043C\u043E\u0436\u0435\u0442 \u0431\u044B\u0442\u044C \u043F\u0443\u0441\u0442\u044B\u043C",
2920
+ sourceFileMissing: (source) => `--source ${source}: \u0442\u0430\u043A\u043E\u0433\u043E \u0444\u0430\u0439\u043B\u0430 \u043D\u0435\u0442 \u0432 \u0440\u0435\u043F\u043E\u0437\u0438\u0442\u043E\u0440\u0438\u0438 \u043F\u0440\u043E\u0435\u043A\u0442\u0430 \u2014 \u043F\u0440\u043E\u0432\u0435\u0440\u044C\u0442\u0435 \u043F\u0443\u0442\u044C`,
2921
+ sourceFileUnchecked: (source) => `--source ${source}: \u0444\u0430\u0439\u043B\u0430 \u043D\u0435\u0442 \u043D\u0430 \u0434\u0438\u0441\u043A\u0435, \u0430 \u0432\u0435\u0442\u043A\u0438 git \u043F\u0440\u043E\u0447\u0438\u0442\u0430\u0442\u044C \u043D\u0435 \u0443\u0434\u0430\u043B\u043E\u0441\u044C \u2014 \u043F\u0443\u0442\u044C \u043D\u0435 \u043F\u0440\u043E\u0432\u0435\u0440\u0435\u043D, \u043F\u0440\u043E\u0432\u0435\u0440\u044C\u0442\u0435 \u0435\u0433\u043E \u0441\u0430\u043C\u0438`,
2764
2922
  alreadyInStatusNothingToVerify: (id, status) => `${id} \u0443\u0436\u0435 \u0432 \u0441\u0442\u0430\u0442\u0443\u0441\u0435 ${status}: \u043F\u043E\u0434\u0442\u0432\u0435\u0440\u0436\u0434\u0430\u0442\u044C \u043D\u0435\u0447\u0435\u0433\u043E`,
2765
2923
  verified: (id) => `${id}: \u043F\u043E\u0434\u0442\u0432\u0435\u0440\u0436\u0434\u0435\u043D\u0430`,
2766
2924
  verifiedWithSource: (id, source) => `${id}: \u043F\u043E\u0434\u0442\u0432\u0435\u0440\u0436\u0434\u0435\u043D\u0430, source \u2192 ${source}`,
@@ -2808,6 +2966,7 @@ var cliRu = {
2808
2966
  originalAlreadyClosed: (id, taskId) => `${id} \u0443\u0436\u0435 \u0437\u0430\u043A\u0440\u044B\u0442\u0430 \u2014 \u0437\u0430\u043A\u0440\u043E\u0439\u0442\u0435 ${taskId} \u043A\u0430\u043A fixed \u0438\u043B\u0438 obsolete`,
2809
2967
  fixCommitRequired: '\u0423\u043A\u0430\u0436\u0438\u0442\u0435 \u043A\u043E\u043C\u043C\u0438\u0442 \u0438\u0441\u043F\u0440\u0430\u0432\u043B\u0435\u043D\u0438\u044F: --reason "\u0418\u0441\u043F\u0440\u0430\u0432\u043B\u0435\u043D\u043E \u0432 <sha>: \u2026" (\u043A\u043E\u043C\u043C\u0438\u0442 \u0434\u043E\u043B\u0436\u0435\u043D \u0431\u044B\u0442\u044C \u0432 \u0440\u0435\u043F\u043E\u0437\u0438\u0442\u043E\u0440\u0438\u0438 \u043F\u0440\u043E\u0435\u043A\u0442\u0430)',
2810
2968
  deletesAtTail: (date) => `. \u0423\u0434\u0430\u043B\u0438\u0442\u0441\u044F ${date}`,
2969
+ afterEpicCloses: (epic) => `\u043F\u043E\u0441\u043B\u0435 \u0437\u0430\u043A\u0440\u044B\u0442\u0438\u044F \u044D\u043F\u0438\u043A\u0430 ${epic}`,
2811
2970
  listUsage: () => "[--query \u0442\u0435\u043A\u0441\u0442] [--status s,\u2026] [--tag t,\u2026] [--project id | --all-projects] [--json]",
2812
2971
  parseErrorLine: (path, problems3) => `\u041E\u0448\u0438\u0431\u043A\u0430 \u0440\u0430\u0437\u0431\u043E\u0440\u0430 ${path}: ${problems3}`,
2813
2972
  noTasksFound: "\u0417\u0430\u0434\u0430\u0447 \u043D\u0435 \u043D\u0430\u0439\u0434\u0435\u043D\u043E",
@@ -2860,8 +3019,11 @@ function portNumber(value) {
2860
3019
  const port = Number(value);
2861
3020
  return port > 0 && port < 65536 ? port : null;
2862
3021
  }
3022
+ function portUnset(value) {
3023
+ return value === void 0 || value === "";
3024
+ }
2863
3025
  function envPortOrDefault(value) {
2864
- return value === void 0 || value === "" ? DEFAULT_PORT : portNumber(value);
3026
+ return portUnset(value) ? DEFAULT_PORT : portNumber(value);
2865
3027
  }
2866
3028
  function loopbackOrigin(port) {
2867
3029
  return `http://${LOOPBACK_HOST}:${port}`;
@@ -2879,15 +3041,39 @@ var UsageError = class extends Error {
2879
3041
  };
2880
3042
  var ArgumentsError = class extends UsageError {
2881
3043
  };
3044
+ var HelpRequested = class extends Error {
3045
+ };
2882
3046
  var END_OF_OPTIONS = "--";
3047
+ var HELP_OPTION_NAMES = /* @__PURE__ */ new Set(["help", "h"]);
2883
3048
  function parseCommandArgs(language, args, options) {
3049
+ if (asksForHelp(args, options)) throw new HelpRequested();
3050
+ const parsed = parseOrExplain(language, args, options);
3051
+ const repeated = repeatedOption(parsed.tokens, options);
3052
+ if (repeated !== null) throw new ArgumentsError(cliMessages(language).argumentProblem.repeated(repeated));
3053
+ return parsed;
3054
+ }
3055
+ function asksForHelp(args, options) {
3056
+ const optionsEnd = args.indexOf(END_OF_OPTIONS);
3057
+ const { tokens } = parseArgs({ args: optionsEnd === -1 ? args : args.slice(0, optionsEnd), options, strict: false, allowPositionals: true, tokens: true });
3058
+ return tokens.some((token) => token.kind === "option" && HELP_OPTION_NAMES.has(token.name));
3059
+ }
3060
+ function parseOrExplain(language, args, options) {
2884
3061
  try {
2885
- return parseArgs({ args, options, allowPositionals: true });
3062
+ return parseArgs({ args, options, allowPositionals: true, tokens: true });
2886
3063
  } catch (error) {
2887
3064
  const problem3 = argumentProblem(args, options);
2888
3065
  throw new ArgumentsError(problem3 === null ? errorText(error) : cliMessages(language).argumentProblem[problem3.kind](problem3.option));
2889
3066
  }
2890
3067
  }
3068
+ function repeatedOption(tokens, options) {
3069
+ const seen = /* @__PURE__ */ new Set();
3070
+ for (const token of tokens) {
3071
+ if (token.kind !== "option" || token.name === void 0 || options[token.name]?.multiple === true) continue;
3072
+ if (seen.has(token.name)) return `--${token.name}`;
3073
+ seen.add(token.name);
3074
+ }
3075
+ return null;
3076
+ }
2891
3077
  function parseOptions(language, args, options) {
2892
3078
  const { values, positionals } = parseCommandArgs(language, args, options);
2893
3079
  if (positionals.length > 0) throw new ArgumentsError(cliMessages(language).extraArguments(positionals));
@@ -2905,7 +3091,8 @@ function argumentProblem(args, options) {
2905
3091
  if (config.type === "boolean" && hasInlineValue) return { kind: "takesNoValue", option };
2906
3092
  if (config.type === "string" && !hasInlineValue) {
2907
3093
  const value = args[position + 1];
2908
- if (value === void 0 || value.startsWith("-")) return { kind: "missingValue", option };
3094
+ if (value === void 0) return { kind: "missingValue", option };
3095
+ if (value.length > 1 && value.startsWith("-")) return { kind: "valueLooksLikeOption", option };
2909
3096
  position++;
2910
3097
  }
2911
3098
  }
@@ -2945,111 +3132,10 @@ ${" ".repeat(head.length)}`;
2945
3132
  }
2946
3133
 
2947
3134
  // src/cli/lookups.ts
2948
- import { basename as basename6, dirname as dirname5 } from "node:path";
2949
-
2950
- // src/core/store/create.ts
2951
- import { mkdir as mkdir3 } from "node:fs/promises";
2952
- import { basename as basename5, join as join11 } from "node:path";
2953
- var MAX_ID_ATTEMPTS = 20;
2954
- async function createTask(root, request) {
2955
- const { project, existingTasks: existingTasks2 } = request;
2956
- const dir = join11(root, project.id);
2957
- const index = buildIndex(existingTasks2);
2958
- for (let attempt = 0; attempt < MAX_ID_ATTEMPTS; attempt++) {
2959
- const id = formatId(project.prefix, await nextTaskNumber(dir, project));
2960
- const path = join11(dir, taskFileName(id));
2961
- const normalized = taskText(draftTask(id, path, request));
2962
- if (!normalized.ok) return invalid(normalized.problems);
2963
- const { text, task } = normalized.value;
2964
- const problems3 = integrityErrors(task, index);
2965
- if (problems3.length > 0) return invalid(problems3);
2966
- try {
2967
- await createFileAtomic(path, text);
2968
- await appendJournal(dir, [createdEvent(task, request.now, request.via, request.provenance)], request.onError);
2969
- return { ok: true, task, reopenedEpic: await reopenEpicOfOpenedTask(index, { before: void 0, after: task }, request) };
2970
- } catch (error) {
2971
- if (!hasErrorCode(error, "EEXIST")) throw error;
2972
- }
2973
- }
2974
- return invalid([{ code: "id-exhausted", attempts: MAX_ID_ATTEMPTS }]);
2975
- }
2976
- async function createProject(root, repoRoot, existingProjects) {
2977
- for (let attempt = 1; ; attempt++) {
2978
- const { id, path, text } = await draftProjectFile(root, repoRoot, existingProjects);
2979
- try {
2980
- await createFileAtomic(path, text);
2981
- const parsed = parseProjectFile(text, { id, path });
2982
- if (!parsed.ok) throw new Error(`${path}: ${parsed.problems.map((problem3) => problem3.code).join(", ")}`);
2983
- return parsed.value;
2984
- } catch (error) {
2985
- if (!hasErrorCode(error, "EEXIST")) throw error;
2986
- const concurrent = await projectOfRepo(id, path, repoRoot);
2987
- if (concurrent !== null) return concurrent;
2988
- if (attempt === MAX_ID_ATTEMPTS) throw error;
2989
- }
2990
- }
2991
- }
2992
- async function draftProjectFile(root, repoRoot, existingProjects) {
2993
- const name = basename5(repoRoot);
2994
- const entries = await listDir(root);
2995
- const joinable = await Promise.all(entries.map((entry) => entry.isDirectory() && isJoinableProjectDir(join11(root, entry.name), repoRoot)));
2996
- const id = deriveProjectId(name, new Set(entries.filter((_, index) => !joinable[index]).map((entry) => entry.name)));
2997
- const prefixesOnDisk = await Promise.all(entries.filter((entry) => entry.isDirectory()).map((entry) => takenPrefixes(join11(root, entry.name))));
2998
- const prefix = derivePrefix(name, /* @__PURE__ */ new Set([...existingProjects.map((project) => project.prefix), ...prefixesOnDisk.flat()]));
2999
- const dir = join11(root, id);
3000
- await mkdir3(dir, { recursive: true });
3001
- return { id, path: join11(dir, PROJECT_FILE), text: serializeProject({ name, prefix, repos: [repoRoot], active: true, extra: {}, body: "" }) };
3002
- }
3003
- async function isJoinableProjectDir(dir, repoRoot) {
3004
- const entries = await listDir(dir);
3005
- if (entries.some((entry) => entry.name === PROJECT_FILE)) return await projectOfRepo(basename5(dir), join11(dir, PROJECT_FILE), repoRoot) !== null;
3006
- return entries.every((entry) => !entry.name.endsWith(".md"));
3007
- }
3008
- async function projectOfRepo(id, path, repoRoot) {
3009
- const parsed = await readProjectFile({ id, path });
3010
- return parsed?.ok === true && parsed.value.repos.includes(repoRoot) ? parsed.value : null;
3011
- }
3012
- async function nextTaskNumber(dir, project) {
3013
- const onDisk = await maxTaskNumber(dir, project.prefix);
3014
- const reserved = await issuedUpToOnDisk(project);
3015
- return Math.max(onDisk, reserved, project.issuedUpTo ?? 0) + 1;
3016
- }
3017
- async function maxTaskNumber(dir, prefix) {
3018
- const numbers = (await taskFileIds(dir)).flatMap((parsed) => parsed.prefix === prefix ? [parsed.number] : []);
3019
- return Math.max(0, ...numbers);
3020
- }
3021
- var PREFIX_LINE = /^prefix:\s*["']?([^\s"']+)/m;
3022
- async function takenPrefixes(dir) {
3023
- const declared = PREFIX_LINE.exec(await readTextOrNull(join11(dir, PROJECT_FILE)) ?? "")?.[1];
3024
- return [...declared !== void 0 && PREFIX_PATTERN.test(declared) ? [declared] : [], ...(await taskFileIds(dir)).map((parsed) => parsed.prefix)];
3025
- }
3026
- async function taskFileIds(dir) {
3027
- return [...await taskIdsOnDisk(dir)].flatMap((id) => parseId(id) ?? []);
3028
- }
3029
- function draftTask(id, path, { project, input, now }) {
3030
- return {
3031
- id,
3032
- title: input.title,
3033
- type: input.type ?? "task",
3034
- status: "backlog",
3035
- priority: input.priority ?? "medium",
3036
- category: input.category,
3037
- tags: input.tags ?? [],
3038
- epic: input.epic,
3039
- blockedBy: input.blockedBy ?? [],
3040
- related: input.related ?? [],
3041
- created: formatLocalIso(now),
3042
- source: input.source,
3043
- anchor: input.anchor,
3044
- extra: {},
3045
- body: input.body ?? "",
3046
- projectId: project.id,
3047
- path
3048
- };
3049
- }
3135
+ import { basename as basename7, dirname as dirname6 } from "node:path";
3050
3136
 
3051
- // src/core/store/resolve-project.ts
3052
- import { isAbsolute, relative, resolve as resolve2, sep } from "node:path";
3137
+ // src/core/check/project-repo.ts
3138
+ import { join as join12 } from "node:path";
3053
3139
 
3054
3140
  // src/core/git/run.ts
3055
3141
  import { execFile as execFile2, execFileSync } from "node:child_process";
@@ -3082,6 +3168,7 @@ function createLimiter(maxRunning) {
3082
3168
  }
3083
3169
 
3084
3170
  // src/core/git/run.ts
3171
+ var PARSED_DIFF_OPTIONS = ["--no-color", "--no-ext-diff", "--no-textconv"];
3085
3172
  var RECORD = "";
3086
3173
  var FIELD = "";
3087
3174
  var runFile = promisify(execFile2);
@@ -3135,7 +3222,7 @@ function isChildProcessFailure(error) {
3135
3222
  return typeof error === "object" && error !== null && "status" in error;
3136
3223
  }
3137
3224
  function gitArgs(repo, args) {
3138
- return ["-C", repo, "--no-optional-locks", "-c", "core.quotePath=false", "-c", "diff.suppressBlankEmpty=false", ...args];
3225
+ return ["-C", repo, "--no-optional-locks", "--no-literal-pathspecs", "-c", "core.quotePath=false", "-c", "diff.suppressBlankEmpty=false", ...args];
3139
3226
  }
3140
3227
  function resolveCommits(git, repo, revisions) {
3141
3228
  return resolveObjects(git, repo, revisions, "commit");
@@ -3163,329 +3250,82 @@ function ignoreStdinOfExitedGit() {
3163
3250
  return void 0;
3164
3251
  }
3165
3252
 
3166
- // src/core/store/resolve-project.ts
3167
- var REPO_ROOT_TTL_MS = 6e4;
3168
- var SHOW_ROOTS = ["rev-parse", "--show-toplevel", "--git-dir", "--git-common-dir"];
3169
- var LIST_WORKTREES = ["worktree", "list", "--porcelain"];
3170
- function findGitRoots(dir) {
3171
- const parsed = parseRevParse(dir, runGitSync(dir, SHOW_ROOTS));
3172
- if (parsed === null) return null;
3173
- return rootsOf(parsed, parsed.isMainWorktree ? null : runGitSync(dir, LIST_WORKTREES));
3174
- }
3175
- async function findGitRootsAsync(dir) {
3176
- const parsed = parseRevParse(dir, await runGit(dir, SHOW_ROOTS));
3177
- if (parsed === null) return null;
3178
- return rootsOf(parsed, parsed.isMainWorktree ? null : await runGit(dir, LIST_WORKTREES));
3253
+ // src/core/check/anchor.ts
3254
+ import { createHash as createHash2 } from "node:crypto";
3255
+ var LINE_CONTEXT = 2;
3256
+ var SNIPPET_CONTEXT = 5;
3257
+ var HASH_LENGTH = 12;
3258
+ var LINE_NUMBER_WIDTH = 5;
3259
+ var MIN_MOVABLE_CHARS = 24;
3260
+ var ANCHOR_FORMAT = /^([0-9a-f]+)@(\d+)-(\d+)(?:\/([0-9a-f]+))?$/;
3261
+ function anchorOf(text, source) {
3262
+ const span2 = sourceSpan(source);
3263
+ const lines = fileLines(text);
3264
+ const window = span2 === null ? null : windowOf(span2, lines.length);
3265
+ if (span2 === null || window === null) return null;
3266
+ return `${hashLines(lines.slice(window.from - 1, window.to))}@${window.from}-${window.to}/${hashLines(lines.slice(span2.first - 1, span2.last))}`;
3179
3267
  }
3180
- function cachedRepoRoots({ onUnreadable, ttlMs = REPO_ROOT_TTL_MS, now = Date.now }) {
3181
- const known = /* @__PURE__ */ new Map();
3182
- const isFresh = ({ checkedAt }) => now() - checkedAt < ttlMs;
3183
- return (dir) => {
3184
- const cached = known.get(dir);
3185
- if (cached !== void 0 && isFresh(cached)) return cached.roots;
3186
- for (const [knownDir, entry] of known) if (!isFresh(entry)) known.delete(knownDir);
3187
- const roots = attemptReportingFailure(dir, async (path) => await findGitRootsAsync(path) ?? plainDirRoots(path), onUnreadable);
3188
- known.set(dir, { roots, checkedAt: now() });
3189
- return roots;
3190
- };
3268
+ function windowMatches(text, source, anchor) {
3269
+ const current = anchorOf(text, source);
3270
+ const expected = parseAnchor(anchor);
3271
+ const found = current === null ? null : parseAnchor(current);
3272
+ return expected !== null && found !== null && found.hash === expected.hash && found.from === expected.from && found.to === expected.to;
3191
3273
  }
3192
- function rootsOf({ topLevel }, worktreeList) {
3193
- return canonicalRoots(topLevel, mainWorktreeIn(worktreeList) ?? topLevel);
3274
+ function sourceRange(source) {
3275
+ const span2 = source === void 0 ? null : sourceSpan(source);
3276
+ return span2 === null ? null : { from: span2.first, to: span2.last };
3194
3277
  }
3195
- function plainDirRoots(dir) {
3196
- const path = realpathOrNull(dir);
3197
- return path === null ? null : { worktree: path, main: path };
3278
+ function anchorRange(source) {
3279
+ const span2 = sourceSpan(source);
3280
+ return span2 === null ? null : withContext(span2);
3198
3281
  }
3199
- function parseRevParse(dir, output) {
3200
- const [topLevel = "", gitDir = "", commonDir = ""] = (output ?? "").split("\n").map((line) => line.trim());
3201
- if (topLevel === "") return null;
3202
- const isMainWorktree = commonDir === "" || realpathOrNull(resolve2(dir, gitDir)) === realpathOrNull(resolve2(dir, commonDir));
3203
- return { topLevel, isMainWorktree };
3282
+ function locateAnchor(text, source, anchor) {
3283
+ return windowMatches(text, source, anchor) ? source : findMoved(text, source, anchor);
3204
3284
  }
3205
- function mainWorktreeIn(porcelain) {
3206
- const [first = ""] = (porcelain ?? "").split("\n\n");
3207
- const lines = first.split("\n");
3208
- const path = lines.find((line) => line.startsWith("worktree "))?.slice("worktree ".length);
3209
- return path === void 0 || lines.includes("bare") ? null : path;
3285
+ function isAnchorFor(anchor, source) {
3286
+ const parsed = parseAnchor(anchor);
3287
+ const span2 = sourceSpan(source);
3288
+ if (parsed === null || span2 === null) return false;
3289
+ const { from, to } = withContext(span2);
3290
+ return parsed.from === from && parsed.to >= span2.first && parsed.to <= to;
3210
3291
  }
3211
- function canonicalRoots(worktreePath, mainPath) {
3212
- const worktree = realpathOrNull(worktreePath);
3213
- const main = realpathOrNull(mainPath);
3214
- return worktree === null || main === null ? null : { worktree, main };
3292
+ function findMoved(text, source, anchor) {
3293
+ const parsed = parseAnchor(anchor);
3294
+ const span2 = sourceSpan(source);
3295
+ if (parsed === null || span2 === null) return null;
3296
+ const start = uniqueBlockStart(fileLines(text), parsed.to - parsed.from + 1, parsed.hash);
3297
+ if (start === null) return null;
3298
+ const shift = start - parsed.from;
3299
+ return withLines(source, span2.first + shift, span2.isRange ? span2.last + shift : void 0);
3215
3300
  }
3216
- function readGitRoots(dir, onUnreadable) {
3217
- return attemptReportingFailureSync(dir, (path) => findGitRoots(path) ?? "not-in-repo", onUnreadable) ?? "unreadable";
3301
+ function findIntactLines(text, source, anchor) {
3302
+ const linesHash = parseAnchor(anchor)?.linesHash;
3303
+ const span2 = sourceSpan(source);
3304
+ if (linesHash === void 0 || span2 === null) return null;
3305
+ const length = span2.last - span2.first + 1;
3306
+ const start = uniqueBlockStart(fileLines(text), length, linesHash);
3307
+ return start === null ? null : withLines(source, start, span2.isRange ? start + length - 1 : void 0);
3218
3308
  }
3219
- function repoRootsOf(dirRoots) {
3220
- return typeof dirRoots === "string" ? null : dirRoots;
3309
+ function uniqueBlockStart(lines, length, hash) {
3310
+ const starts = [];
3311
+ for (let start2 = 1; start2 + length - 1 <= lines.length; start2++) {
3312
+ if (hashLines(lines.slice(start2 - 1, start2 - 1 + length)) === hash) starts.push(start2);
3313
+ }
3314
+ const [start] = starts;
3315
+ if (starts.length !== 1 || start === void 0) return null;
3316
+ return significantChars(lines.slice(start - 1, start - 1 + length)) < MIN_MOVABLE_CHARS ? null : start;
3221
3317
  }
3222
- function findProjectForDir(projects, dir, dirRoots, places) {
3223
- if (dirRoots === "unreadable") return void 0;
3224
- const roots = dirRoots === "not-in-repo" ? attemptReportingFailureSync(dir, plainDirRoots, places.onUnreadable) : dirRoots;
3225
- return roots === null ? void 0 : findProjectForRoots(projects, roots, places);
3318
+ function remappedSource(source, lineAt) {
3319
+ const span2 = sourceSpan(source);
3320
+ return span2 === null ? null : withLines(source, lineAt(span2.first), span2.isRange ? lineAt(span2.last) : void 0);
3226
3321
  }
3227
- function findProjectForRoots(projects, { worktree, main }, places) {
3228
- const matches = projects.flatMap(
3229
- (project) => project.repos.flatMap((repo) => {
3230
- const repoPath = resolvedRepo(repo, places);
3231
- return repoPath !== null && (isSameOrInside(worktree, repoPath) || isSameOrInside(main, repoPath)) ? [{ project, repoPath }] : [];
3232
- })
3233
- );
3234
- return matches.sort((a, b) => b.repoPath.length - a.repoPath.length)[0]?.project;
3235
- }
3236
- function isSameOrInside(path, container) {
3237
- const relation = relative(container, path);
3238
- return relation === "" || !isAbsolute(relation) && relation.split(sep)[0] !== "..";
3239
- }
3240
- function resolvedRepo(repo, { home: home2, onUnreadable }) {
3241
- return attemptReportingFailureSync(expandHome(repo, home2), realpathOrNull, onUnreadable);
3242
- }
3243
-
3244
- // src/cli/path-inside.ts
3245
- import { isAbsolute as isAbsolute2, relative as relative2, sep as sep2 } from "node:path";
3246
- function relativeInside(container, path) {
3247
- const inside = relative2(container, path);
3248
- const outside = isAbsolute2(inside) || inside === ".." || inside.startsWith(`..${sep2}`);
3249
- return outside ? null : inside.split(sep2).join("/");
3250
- }
3251
-
3252
- // src/cli/lookups.ts
3253
- function warnUnreadableSkipped(warn2, core) {
3254
- return warnPathErrors(warn2, core.unreadableSkipped);
3255
- }
3256
- var placesOfRun = /* @__PURE__ */ new WeakMap();
3257
- function repoPlaces(io) {
3258
- const known = placesOfRun.get(io);
3259
- if (known !== void 0) return known;
3260
- const places = { home: io.home, onUnreadable: oncePerPath(warnUnreadableSkipped(io.warn, io.core)) };
3261
- placesOfRun.set(io, places);
3262
- return places;
3263
- }
3264
- var cwdRootsOfRun = /* @__PURE__ */ new WeakMap();
3265
- function cwdDirRoots(io) {
3266
- const known = cwdRootsOfRun.get(io);
3267
- if (known !== void 0) return known;
3268
- const roots = readGitRoots(io.cwd, repoPlaces(io).onUnreadable);
3269
- cwdRootsOfRun.set(io, roots);
3270
- return roots;
3271
- }
3272
- function cwdGitRoots(io) {
3273
- return repoRootsOf(cwdDirRoots(io));
3274
- }
3275
- function findProjectForCwd(projects, io) {
3276
- return findProjectForDir(projects, io.cwd, cwdDirRoots(io), repoPlaces(io));
3277
- }
3278
- function repoLookup(io) {
3279
- return { ...repoPlaces(io), workingRoots: cwdGitRoots(io) };
3280
- }
3281
- function findTaskOrWarn(loaded, io, id) {
3282
- const task = loaded.tasks.find((candidate) => candidate.id === id);
3283
- if (task) return task;
3284
- const broken = loaded.errors.find((error) => basename6(error.path) === `${id}.md`);
3285
- io.warn(broken ? io.cli.taskFileUnparsed(id, io.core.problems(broken.problems)) : io.cli.taskNotFound(id));
3286
- return void 0;
3287
- }
3288
- function projectOf(loaded, task) {
3289
- return loaded.projects.find((project) => project.id === task.projectId);
3290
- }
3291
- function findProjectOrWarn(loaded, io, explicitId) {
3292
- const project = findProject(loaded, io, explicitId);
3293
- if (project) return project;
3294
- io.warn(explicitId === void 0 ? io.cli.projectNotFoundForCwd(io.cwd) : io.cli.projectNotFound(explicitId));
3295
- return void 0;
3296
- }
3297
- async function ensureProject(loaded, io, explicitId) {
3298
- if (explicitId !== void 0) return findProjectOrWarn(loaded, io, explicitId);
3299
- const existing = findProject(loaded, io, void 0);
3300
- if (existing) return existing;
3301
- const gitRoots = cwdDirRoots(io);
3302
- if (gitRoots === "unreadable") return void 0;
3303
- if (gitRoots === "not-in-repo") {
3304
- io.warn(io.cli.notInGitRepo(io.cwd));
3305
- return void 0;
3306
- }
3307
- const brokenProjectFiles = await brokenProjectFilesOf(loaded, gitRoots, io.home);
3308
- if (brokenProjectFiles.length > 0) {
3309
- for (const error of brokenProjectFiles) io.warn(io.cli.projectNotCreatedFileUnparsed(error.path, io.core.problems(error.problems)));
3310
- return void 0;
3311
- }
3312
- const created = await createProject(io.backlogRoot, gitRoots.main, loaded.projects);
3313
- io.warn(io.cli.projectCreated(created.id, created.prefix));
3314
- return created;
3315
- }
3316
- async function brokenProjectFilesOf(loaded, roots, home2) {
3317
- const repoPaths = [roots.main, roots.worktree].flatMap((path) => [path, homeRelative(path, home2)]);
3318
- const ownId = projectIdBase(basename6(roots.main));
3319
- const broken = loaded.errors.filter((error) => basename6(error.path) === PROJECT_FILE);
3320
- const texts = await Promise.all(broken.map(async (error) => await readTextOrNull(error.path) ?? ""));
3321
- return broken.filter((error, position) => basename6(dirname5(error.path)) === ownId || repoPaths.some((path) => mentionsPath(texts[position] ?? "", path)));
3322
- }
3323
- var PATH_BOUNDARY = /[\s"',[\]]/;
3324
- var TRAILING_SEPARATORS = /^[\\/]*/;
3325
- function mentionsPath(text, path) {
3326
- for (let start = text.indexOf(path); start !== -1; start = text.indexOf(path, start + 1)) {
3327
- const end = start + path.length + (TRAILING_SEPARATORS.exec(text.slice(start + path.length))?.[0].length ?? 0);
3328
- if (isBoundary(text.charAt(start - 1)) && isBoundary(text.charAt(end))) return true;
3329
- }
3330
- return false;
3331
- }
3332
- function isBoundary(char) {
3333
- return char === "" || PATH_BOUNDARY.test(char);
3334
- }
3335
- function homeRelative(path, home2) {
3336
- const inside = relativeInside(home2, path);
3337
- return inside === null ? path : `~/${inside}`;
3338
- }
3339
- function findProject(loaded, io, explicitId) {
3340
- return explicitId === void 0 ? findProjectForCwd(loaded.projects, io) : loaded.projects.find((project) => project.id === explicitId);
3341
- }
3342
-
3343
- // src/cli/task-write.ts
3344
- function taskWriter(io, loadedTasks) {
3345
- const index = buildIndex(loadedTasks);
3346
- const onError = warnPathErrors(io.warn);
3347
- return async (task, changes, closure) => {
3348
- const result = await updateTaskInIndex(index, { id: task.id, changes, expectedVersion: task.version, now: io.now(), via: "cli", onError, closure });
3349
- if (!result.ok) return { ok: false, exitCode: reportUpdateFailure(io, task.id, result) };
3350
- if (result.reopenedEpic !== void 0) io.warn(io.cli.epicReopened(result.reopenedEpic.id));
3351
- return result;
3352
- };
3353
- }
3354
- function tasksAfterWrite(tasks, result) {
3355
- const written = writtenTasks(result);
3356
- const byId = new Map(written.map((candidate) => [candidate.id, candidate]));
3357
- const known = new Set(tasks.map((candidate) => candidate.id));
3358
- return [...tasks.map((candidate) => byId.get(candidate.id) ?? candidate), ...written.filter((candidate) => !known.has(candidate.id))];
3359
- }
3360
- function reportUpdateFailure(io, id, result) {
3361
- switch (result.reason) {
3362
- case "not-found":
3363
- io.warn(io.cli.taskNotFound(id));
3364
- return EXIT.notFound;
3365
- case "conflict":
3366
- io.warn(io.cli.fileConflict(id));
3367
- return EXIT.invalid;
3368
- case "busy":
3369
- io.warn(io.core.fileBusy(result));
3370
- return EXIT.failed;
3371
- case "invalid":
3372
- for (const problem3 of result.problems) io.warn(io.core.problem(problem3));
3373
- return EXIT.invalid;
3374
- }
3375
- }
3376
-
3377
- // src/cli/task-field-command.ts
3378
- function taskFieldCommand(spec) {
3379
- const command2 = {
3380
- name: spec.name,
3381
- usage: () => [`<ID> <${spec.choices}>`],
3382
- run: async (args, io) => {
3383
- const { positionals } = parseCommandArgs(io.language, args, {});
3384
- const [id, rawValue, ...rest] = positionals;
3385
- if (id === void 0 || rawValue === void 0 || rest.length > 0) throw usageError(command2, io.language);
3386
- const value = spec.parse(io.language, rawValue);
3387
- const loaded = await loadBacklog(io.backlogRoot);
3388
- const task = findTaskOrWarn(loaded, io, id);
3389
- if (!task) return EXIT.notFound;
3390
- const written = await taskWriter(io, loaded.tasks)(task, spec.changes(value));
3391
- if (!written.ok) return written.exitCode;
3392
- spec.afterWrite?.(written.task, io, task);
3393
- io.print(`${id}: ${spec.label(task, io.language)} \u2192 ${spec.label(written.task, io.language)}`);
3394
- return EXIT.ok;
3395
- }
3396
- };
3397
- return command2;
3398
- }
3399
-
3400
- // src/cli/commands/category.ts
3401
- var NO_CATEGORY = "none";
3402
- var categoryCommand = taskFieldCommand({
3403
- name: "category",
3404
- choices: `${TASK_CATEGORIES.join("|")}|${NO_CATEGORY}`,
3405
- parse: (language, value) => value === NO_CATEGORY ? null : parseChoice(language, value, TASK_CATEGORIES, cliMessages(language).optionLabel.category),
3406
- changes: (category) => ({ category }),
3407
- label: (task, language) => coreMessages(language).categoryLabel(task.category)
3408
- });
3409
-
3410
- // src/core/check/check-backlog.ts
3411
- import { join as join17 } from "node:path";
3412
-
3413
- // src/core/check/anchor.ts
3414
- import { createHash as createHash2 } from "node:crypto";
3415
- var LINE_CONTEXT = 2;
3416
- var SNIPPET_CONTEXT = 5;
3417
- var HASH_LENGTH = 12;
3418
- var LINE_NUMBER_WIDTH = 5;
3419
- var MIN_MOVABLE_CHARS = 24;
3420
- var ANCHOR_FORMAT = /^([0-9a-f]+)@(\d+)-(\d+)(?:\/([0-9a-f]+))?$/;
3421
- function anchorOf(text, source) {
3422
- const span2 = sourceSpan(source);
3423
- const lines = fileLines(text);
3424
- const window = span2 === null ? null : windowOf(span2, lines.length);
3425
- if (span2 === null || window === null) return null;
3426
- return `${hashLines(lines.slice(window.from - 1, window.to))}@${window.from}-${window.to}/${hashLines(lines.slice(span2.first - 1, span2.last))}`;
3427
- }
3428
- function windowMatches(text, source, anchor) {
3429
- const current = anchorOf(text, source);
3430
- const expected = parseAnchor(anchor);
3431
- const found = current === null ? null : parseAnchor(current);
3432
- return expected !== null && found !== null && found.hash === expected.hash && found.from === expected.from && found.to === expected.to;
3433
- }
3434
- function sourceRange(source) {
3435
- const span2 = source === void 0 ? null : sourceSpan(source);
3436
- return span2 === null ? null : { from: span2.first, to: span2.last };
3437
- }
3438
- function anchorRange(source) {
3439
- const span2 = sourceSpan(source);
3440
- return span2 === null ? null : withContext(span2);
3441
- }
3442
- function locateAnchor(text, source, anchor) {
3443
- return windowMatches(text, source, anchor) ? source : findMoved(text, source, anchor);
3444
- }
3445
- function isAnchorFor(anchor, source) {
3446
- const parsed = parseAnchor(anchor);
3447
- const span2 = sourceSpan(source);
3448
- if (parsed === null || span2 === null) return false;
3449
- const { from, to } = withContext(span2);
3450
- return parsed.from === from && parsed.to >= span2.first && parsed.to <= to;
3451
- }
3452
- function findMoved(text, source, anchor) {
3453
- const parsed = parseAnchor(anchor);
3454
- const span2 = sourceSpan(source);
3455
- if (parsed === null || span2 === null) return null;
3456
- const start = uniqueBlockStart(fileLines(text), parsed.to - parsed.from + 1, parsed.hash);
3457
- if (start === null) return null;
3458
- const shift = start - parsed.from;
3459
- return withLines(source, span2.first + shift, span2.isRange ? span2.last + shift : void 0);
3460
- }
3461
- function findIntactLines(text, source, anchor) {
3462
- const linesHash = parseAnchor(anchor)?.linesHash;
3463
- const span2 = sourceSpan(source);
3464
- if (linesHash === void 0 || span2 === null) return null;
3465
- const length = span2.last - span2.first + 1;
3466
- const start = uniqueBlockStart(fileLines(text), length, linesHash);
3467
- return start === null ? null : withLines(source, start, span2.isRange ? start + length - 1 : void 0);
3468
- }
3469
- function uniqueBlockStart(lines, length, hash) {
3470
- const starts = [];
3471
- for (let start2 = 1; start2 + length - 1 <= lines.length; start2++) {
3472
- if (hashLines(lines.slice(start2 - 1, start2 - 1 + length)) === hash) starts.push(start2);
3473
- }
3474
- const [start] = starts;
3475
- if (starts.length !== 1 || start === void 0) return null;
3476
- return significantChars(lines.slice(start - 1, start - 1 + length)) < MIN_MOVABLE_CHARS ? null : start;
3477
- }
3478
- function remappedSource(source, lineAt) {
3479
- const span2 = sourceSpan(source);
3480
- return span2 === null ? null : withLines(source, lineAt(span2.first), span2.isRange ? lineAt(span2.last) : void 0);
3481
- }
3482
- function snippetOf(text, source) {
3483
- const span2 = sourceSpan(source);
3484
- const lines = fileLines(text);
3485
- if (span2 === null || span2.first > lines.length) return void 0;
3486
- const from = Math.max(1, span2.first - SNIPPET_CONTEXT);
3487
- const to = Math.min(lines.length, span2.last + SNIPPET_CONTEXT);
3488
- return lines.slice(from - 1, to).map((line, index) => `${String(from + index).padStart(LINE_NUMBER_WIDTH)}\u2502 ${line.trimEnd()}`).join("\n");
3322
+ function snippetOf(text, source) {
3323
+ const span2 = sourceSpan(source);
3324
+ const lines = fileLines(text);
3325
+ if (span2 === null || span2.first > lines.length) return void 0;
3326
+ const from = Math.max(1, span2.first - SNIPPET_CONTEXT);
3327
+ const to = Math.min(lines.length, span2.last + SNIPPET_CONTEXT);
3328
+ return lines.slice(from - 1, to).map((line, index) => `${String(from + index).padStart(LINE_NUMBER_WIDTH)}\u2502 ${line.trimEnd()}`).join("\n");
3489
3329
  }
3490
3330
  function withLines(source, first, last) {
3491
3331
  return `${source.replace(SOURCE_LINES, "")}:${last === void 0 ? first : `${first}-${last}`}`;
@@ -3521,8 +3361,7 @@ function hashLines(lines) {
3521
3361
  return createHash2("sha1").update(fragment).digest("hex").slice(0, HASH_LENGTH);
3522
3362
  }
3523
3363
 
3524
- // src/core/check/candidates.ts
3525
- var MAX_COMMITS = 3;
3364
+ // src/core/check/reviewed-task.ts
3526
3365
  function isReviewable(task) {
3527
3366
  return task.type === "task" && (task.status === "backlog" || task.status === "blocked");
3528
3367
  }
@@ -3533,6 +3372,28 @@ function reviewMark(task) {
3533
3372
  const verified = task.verified === void 0 ? Number.NEGATIVE_INFINITY : Date.parse(task.verified);
3534
3373
  return Math.max(Date.parse(task.created), verified);
3535
3374
  }
3375
+ function taskRef(task) {
3376
+ return { id: task.id, title: task.title };
3377
+ }
3378
+
3379
+ // src/core/check/source-commits.ts
3380
+ function changesSince(facts, path, mark) {
3381
+ const commits = commitsTouchingSince(facts.commits, path, mark);
3382
+ const uncommitted = [...facts.dirtyModifiedAt].some(([file, modifiedAt]) => isWithin(file, path) && modifiedAt > mark);
3383
+ return { commits, uncommitted };
3384
+ }
3385
+ function commitsTouchingSince(commits, path, mark) {
3386
+ return commitsAfter(commits, mark).filter((commit) => touches(commit, path));
3387
+ }
3388
+ function commitsAfter(commits, mark) {
3389
+ return commits.filter((commit) => Date.parse(commit.date) > mark);
3390
+ }
3391
+ function touches(commit, path) {
3392
+ return commit.files.some((file) => isWithin(file.path, path) || file.renamedFrom !== void 0 && isWithin(file.renamedFrom, path));
3393
+ }
3394
+
3395
+ // src/core/check/candidates.ts
3396
+ var MAX_COMMITS = 3;
3536
3397
  function anchorStates(tasks, facts) {
3537
3398
  return new Map(tasks.map((task) => [task.id, anchorState(task, facts)]));
3538
3399
  }
@@ -3547,7 +3408,7 @@ function codeCandidate(task, anchor, facts, knownCommits = /* @__PURE__ */ new S
3547
3408
  const path = sourcePath(task.source);
3548
3409
  const mark = reviewMark(task);
3549
3410
  if (!facts.existing.has(path)) {
3550
- return livesOnAnotherBranch(path, facts) ? [] : [{ kind: "source-missing", task: taskRef(task), path, renamedTo: followRenames(path, facts.renames, mark) }];
3411
+ return presenceOffDisk(path, facts.branches) === "missing" ? [{ kind: "source-missing", task: taskRef(task), path, renamedTo: followRenames(path, facts.renames, mark) }] : [];
3551
3412
  }
3552
3413
  if (anchor.kind === "same" || anchor.kind === "moved") return [];
3553
3414
  const { commits: changed, uncommitted } = changesSince(facts, path, mark);
@@ -3577,11 +3438,6 @@ function relocationPlan(task, current, facts) {
3577
3438
  function movedPlan(id, from, to) {
3578
3439
  return { id, changes: { source: to.source, anchor: to.anchor }, moved: { kind: "source-moved", taskId: id, from, to: to.source } };
3579
3440
  }
3580
- function changesSince(facts, path, mark) {
3581
- const commits = commitsTouchingSince(facts.commits, path, mark);
3582
- const uncommitted = [...facts.dirtyModifiedAt].some(([file, modifiedAt]) => isWithin(file, path) && modifiedAt > mark);
3583
- return { commits, uncommitted };
3584
- }
3585
3441
  function judgedByCommits(task, anchors) {
3586
3442
  return task.source !== void 0 && anchors.get(task.id)?.kind === "none";
3587
3443
  }
@@ -3596,6 +3452,16 @@ function anchorStateIn(task, text) {
3596
3452
  const movedAnchor = moved === null ? null : anchorOf(text, moved);
3597
3453
  return moved === null || movedAnchor === null ? { kind: "changed" } : { kind: "moved", source: moved, anchor: movedAnchor };
3598
3454
  }
3455
+ function presenceOffDisk(path, branches) {
3456
+ switch (branches.kind) {
3457
+ case "no-repo":
3458
+ return "missing";
3459
+ case "unreadable":
3460
+ return "unchecked";
3461
+ case "read":
3462
+ return livesOnAnotherBranch(path, branches) ? "present" : "missing";
3463
+ }
3464
+ }
3599
3465
  function livesOnAnotherBranch(path, facts) {
3600
3466
  const committedIn = (files) => [...files].some((file) => isWithin(file, path));
3601
3467
  return !committedIn(facts.committedHere) && committedIn(facts.committedAnywhere);
@@ -3608,124 +3474,18 @@ function followRenames(path, commits, mark) {
3608
3474
  }
3609
3475
  return current === path ? void 0 : current;
3610
3476
  }
3611
- function commitsTouchingSince(commits, path, mark) {
3612
- return commitsAfter(commits, mark).filter((commit) => touches(commit, path));
3613
- }
3614
- function commitsAfter(commits, mark) {
3615
- return commits.filter((commit) => Date.parse(commit.date) > mark);
3616
- }
3617
- function touches(commit, path) {
3618
- return commit.files.some((file) => isWithin(file.path, path) || file.renamedFrom !== void 0 && isWithin(file.renamedFrom, path));
3619
- }
3620
- function taskRef(task) {
3621
- return { id: task.id, title: task.title };
3622
- }
3623
- function commitRef(commit) {
3624
- return { sha: commit.sha, subject: commit.subject };
3477
+ function commitRef(commit) {
3478
+ return { sha: commit.shortSha, subject: commit.subject };
3625
3479
  }
3626
3480
 
3627
- // src/core/check/check-fixes.ts
3628
- async function applyFixes(loaded, inScope, { messages, ...writes }) {
3629
- const isGone = goneTaskCheck(loaded);
3630
- const epicFixes = await epicStatusFixes(loaded, inScope, messages);
3631
- const planned = loaded.tasks.filter((task) => inScope(task.projectId)).flatMap((task) => {
3632
- const fix = planFix(task, isGone, epicFixes.get(task.id));
3633
- return fix === null ? [] : [{ task, ...fix }];
3634
- });
3635
- return applyPlanned(buildIndex(loaded.tasks), planned, writes);
3636
- }
3637
- async function applyAnchorPlans(tasks, plans, writes) {
3638
- const index = buildIndex(tasks);
3639
- const planned = plans.flatMap((plan) => {
3640
- const task = index.byId.get(plan.id);
3641
- return task === void 0 ? [] : [{ task, changes: plan.changes, done: plan.moved === void 0 ? [] : [plan.moved] }];
3642
- });
3643
- return applyPlanned(index, planned, writes);
3644
- }
3645
- async function applyPlanned(index, planned, writes) {
3646
- const fixed = [];
3647
- const failed2 = [];
3648
- for (const { task, changes, closure, done } of planned) {
3649
- const result = await updateTaskInIndex(index, { id: task.id, changes, expectedVersion: task.version, closure, ...writes, via: "check" });
3650
- if (result.ok) fixed.push(...done);
3651
- else failed2.push(fixFailure(task.id, result));
3652
- }
3653
- return { fixed, failed: failed2 };
3654
- }
3655
- function fixFailure(taskId, failure) {
3656
- switch (failure.reason) {
3657
- case "invalid":
3658
- return { kind: "fix-failed", taskId, cause: "invalid", problems: failure.problems };
3659
- case "conflict":
3660
- return { kind: "fix-failed", taskId, cause: "changed-during-check" };
3661
- case "not-found":
3662
- return { kind: "fix-failed", taskId, cause: "gone-during-check" };
3663
- case "busy":
3664
- return { kind: "fix-failed", taskId, cause: "busy-during-check" };
3665
- }
3666
- }
3667
- async function epicStatusFixes(loaded, inScope, messages) {
3668
- const closing = planEpicClosing(loaded.tasks, loaded.errors).close.map(({ epic, childIds }) => [
3669
- epic.id,
3670
- { status: "done", closure: epicDoneClosure(childIds, messages), done: { kind: "epic-closed", taskId: epic.id, childIds } }
3671
- ]);
3672
- const reopenable = planEpicReopening(loaded.tasks).filter(({ epic }) => inScope(epic.projectId));
3673
- const reopening = await Promise.all(
3674
- reopenable.map(async ({ epic, childIds }) => [epic.id, { status: await statusToReopen(epic), done: { kind: "epic-reopened", taskId: epic.id, childIds } }])
3675
- );
3676
- return new Map([...closing, ...reopening]);
3677
- }
3678
- function planFix(task, isGone, epicFix) {
3679
- const cleanup = referenceCleanup(task, isGone);
3680
- if (cleanup === null && epicFix === void 0) return null;
3681
- const done = [];
3682
- if (cleanup !== null) done.push({ kind: "references-removed", taskId: task.id, ids: goneReferences(task, isGone) });
3683
- if (epicFix === void 0) return { changes: cleanup ?? {}, done };
3684
- return { changes: { ...cleanup, status: epicFix.status }, closure: epicFix.closure, done: [...done, epicFix.done] };
3685
- }
3686
- function goneReferences(task, isGone) {
3687
- const references = [...task.blockedBy, ...task.related, ...task.epic === void 0 ? [] : [task.epic]];
3688
- return [...new Set(references.filter(isGone))];
3689
- }
3690
- function goneTaskCheck(loaded) {
3691
- const known = /* @__PURE__ */ new Set([...loaded.tasks.map((task) => task.id), ...unparsedTasks(loaded.errors).map((task) => task.id)]);
3692
- const loadedPrefixes = new Set(loaded.projects.map((project) => project.prefix));
3693
- return (id) => {
3694
- const prefix = parseId(id)?.prefix;
3695
- return prefix !== void 0 && loadedPrefixes.has(prefix) && !known.has(id);
3696
- };
3697
- }
3698
-
3699
- // src/core/check/find-problems.ts
3700
- import { basename as basename7 } from "node:path";
3701
- function findProblems(loaded, projects, repos, inScope) {
3702
- const index = buildIndex(loaded.tasks);
3703
- const integrity = loaded.tasks.filter((task) => inScope(task.projectId)).flatMap((task) => integrityErrors(task, index).map((problem3) => ({ kind: "task-invalid", taskId: task.id, problem: problem3 })));
3704
- const missingRepos = projects.filter((project) => repos.get(project.id) === void 0).map(missingRepoProblem);
3705
- return [...parseProblems(loaded, inScope), ...integrity, ...missingRepos, ...sharedPrefixes(loaded.projects, inScope)];
3706
- }
3707
- function sharedPrefixes(projects, inScope) {
3708
- const idsByPrefix = /* @__PURE__ */ new Map();
3709
- for (const project of projects) idsByPrefix.set(project.prefix, [...idsByPrefix.get(project.prefix) ?? [], project.id]);
3710
- return [...idsByPrefix].filter(([, projectIds]) => projectIds.length > 1 && projectIds.some(inScope)).map(([prefix, projectIds]) => ({ kind: "prefix-shared", prefix, projectIds }));
3711
- }
3712
- function parseProblems(loaded, inScope) {
3713
- const waitingEpicIds = planEpicClosing(loaded.tasks, loaded.errors).waiting.filter(({ epic }) => inScope(epic.projectId)).map(({ epic }) => epic.id);
3714
- const everyFileMayHoldWaitingChild = waitingEpicIds.length > 0;
3715
- const reported = loaded.errors.filter((error) => everyFileMayHoldWaitingChild || concernsScope(error, inScope)).map((error) => ({ kind: "file-not-parsed", path: error.path, problems: error.problems }));
3716
- if (waitingEpicIds.length === 0) return reported;
3717
- return [...reported, { kind: "epics-wait-for-files", epicIds: waitingEpicIds }];
3718
- }
3719
- function concernsScope(error, inScope) {
3720
- return inScope(error.projectId) || basename7(error.path) === PROJECT_FILE;
3721
- }
3722
- function missingRepoProblem(project) {
3723
- return project.repos.length === 0 ? { kind: "project-without-repos", projectId: project.id } : { kind: "project-repos-missing", projectId: project.id, repos: project.repos };
3481
+ // src/core/remembered.ts
3482
+ function remembered(cache, key, compute) {
3483
+ if (cache.has(key)) return cache.get(key);
3484
+ const value = compute();
3485
+ cache.set(key, value);
3486
+ return value;
3724
3487
  }
3725
3488
 
3726
- // src/core/check/project-repo.ts
3727
- import { join as join13 } from "node:path";
3728
-
3729
3489
  // src/core/check/diff-hunks.ts
3730
3490
  var HUNK_HEADER = /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/;
3731
3491
  var OMITTED_COUNT = 1;
@@ -3899,53 +3659,52 @@ function baseText(hunks, currentText) {
3899
3659
  }
3900
3660
 
3901
3661
  // src/core/check/repo-facts.ts
3902
- import { isAbsolute as isAbsolute3, join as join12, normalize, sep as sep3 } from "node:path";
3903
-
3904
- // src/core/remembered.ts
3905
- function remembered(cache, key, compute) {
3906
- if (cache.has(key)) return cache.get(key);
3907
- const value = compute();
3908
- cache.set(key, value);
3909
- return value;
3910
- }
3911
-
3912
- // src/core/check/repo-facts.ts
3662
+ import { isAbsolute, join as join11, normalize, sep } from "node:path";
3913
3663
  var SAFE_DIRECTORY_HINT = "safe.directory";
3914
3664
  var DIFF_LINE_LIMIT = 80;
3915
3665
  var REFLOG_MOMENT = /\{(\d+)\}$/;
3916
3666
  var STATUS_CODE_WIDTH = 3;
3917
3667
  var RENAME_OR_COPY = /^[RC]/;
3918
3668
  var ORIGINAL_PATH_FOLLOWS = /^(?:[RC].|.[RC])/;
3669
+ var LOG_FORMAT = `--format=${RECORD}%H${FIELD}%h${FIELD}%cI${FIELD}%P${FIELD}%s`;
3919
3670
  var FACTS_HISTORY_OPTIONS = ["--full-history"];
3671
+ async function locateRepo(repo) {
3672
+ const location = await runGitOutcome(repo, ["rev-parse", "--show-prefix", "--revs-only", "HEAD"]);
3673
+ if (location.status === "exited") return { history: location.stderr.includes(SAFE_DIRECTORY_HINT) ? "unsafe-repo" : "not-a-repo" };
3674
+ if (location.status === "unfinished") return { history: "unreadable" };
3675
+ const [prefix = "", head = ""] = location.stdout.split("\n").map((line) => line.trim());
3676
+ return { history: "read", prefix, hasCommits: head !== "" };
3677
+ }
3920
3678
  async function collectRepoFacts(repo, pathMarks) {
3921
3679
  const paths = [...pathMarks.keys()];
3922
- const [location, files] = await Promise.all([runGitOutcome(repo, ["rev-parse", "--show-prefix", "--revs-only", "HEAD"]), sourceFiles(repo, paths)]);
3923
- const withoutHistory = (history) => ({ history, commits: [], renames: [], dirtyModifiedAt: /* @__PURE__ */ new Map(), ...UNKNOWN_BRANCH_HISTORY, ...files });
3924
- if (location.status === "exited") return withoutHistory(location.stderr.includes(SAFE_DIRECTORY_HINT) ? "unsafe-repo" : "not-a-repo");
3925
- if (location.status === "unfinished") return withoutHistory("unreadable");
3926
- const [prefix = "", head = ""] = location.stdout.split("\n").map((line) => line.trim());
3927
- const hasCommits = head !== "";
3680
+ const [location, files] = await Promise.all([locateRepo(repo), sourceFiles(repo, paths)]);
3681
+ const withoutHistory = (history) => ({ history, commits: [], renames: [], dirtyModifiedAt: /* @__PURE__ */ new Map(), branches: unknownBranches(history), ...files });
3682
+ if (location.history !== "read") return withoutHistory(location.history);
3683
+ const { prefix, hasCommits } = location;
3928
3684
  const missing = paths.filter((path) => !files.existing.has(path) && !files.unreadable.has(path));
3929
- const [log, renames, status, branchHistory] = await Promise.all([
3685
+ const [log, renames, status, branches] = await Promise.all([
3930
3686
  hasCommits ? pathLog(repo, earliestMark(pathMarks, paths), paths) : "",
3931
3687
  hasCommits && missing.length > 0 ? runGit(repo, [...logArgs(earliestMark(pathMarks, missing)), "--diff-filter=R"]) : "",
3932
3688
  runGit(repo, ["status", "--porcelain=v1", "-z", "--untracked-files=no"]),
3933
- branchHistoryOf(repo, missing)
3689
+ branchHistoryOf(repo, location, missing)
3934
3690
  ]);
3935
3691
  if (log === null || renames === null || status === null) return withoutHistory("unreadable");
3936
3692
  const dirty = withinRepo(parseStatus(status), prefix);
3937
- return { history: "read", commits: parseLog(log), renames: parseLog(renames), dirtyModifiedAt: await modificationTimes(repo, dirty), ...branchHistory, ...files };
3693
+ return { history: "read", commits: parseLog(log), renames: parseLog(renames), dirtyModifiedAt: await modificationTimes(repo, dirty), branches, ...files };
3938
3694
  }
3939
- var UNKNOWN_BRANCH_HISTORY = { committedHere: /* @__PURE__ */ new Set(), committedAnywhere: /* @__PURE__ */ new Set() };
3940
- async function branchHistoryOf(repo, paths) {
3941
- const [here, anywhere] = await Promise.all([committedPaths(repo, "HEAD", paths), committedPaths(repo, "--all", paths)]);
3942
- return here === null || anywhere === null ? UNKNOWN_BRANCH_HISTORY : { committedHere: new Set(here), committedAnywhere: new Set(anywhere) };
3695
+ async function branchHistoryOf(repo, location, paths) {
3696
+ if (location.history !== "read") return unknownBranches(location.history);
3697
+ const [here, anywhere] = await Promise.all([location.hasCommits ? committedPaths(repo, "HEAD", paths) : [], committedPaths(repo, "--all", paths)]);
3698
+ return here === null || anywhere === null ? { kind: "unreadable" } : { kind: "read", committedHere: new Set(here), committedAnywhere: new Set(anywhere) };
3699
+ }
3700
+ function unknownBranches(history) {
3701
+ return history === "not-a-repo" ? { kind: "no-repo" } : { kind: "unreadable" };
3943
3702
  }
3944
3703
  function earliestMark(marks, paths) {
3945
3704
  return new Date(Math.min(...paths.flatMap((path) => marks.get(path) ?? [])));
3946
3705
  }
3947
3706
  function logArgs(since) {
3948
- return ["log", "--relative", `--since=${since.toISOString()}`, `--format=${RECORD}%h${FIELD}%cI${FIELD}%p${FIELD}%s`, "--name-status", "-M", "--diff-merges=first-parent", ...FACTS_HISTORY_OPTIONS, "-z"];
3707
+ return ["log", "--relative", `--since=${since.toISOString()}`, LOG_FORMAT, "--name-status", "-M", "--diff-merges=first-parent", ...FACTS_HISTORY_OPTIONS, "-z"];
3949
3708
  }
3950
3709
  async function pathLog(repo, since, paths) {
3951
3710
  const inside = paths.filter(isInsideRepo);
@@ -3960,7 +3719,7 @@ async function committedPaths(repo, revisions, paths) {
3960
3719
  }
3961
3720
  function isInsideRepo(path) {
3962
3721
  const normalized = normalize(path);
3963
- return normalized !== "." && !isAbsolute3(normalized) && normalized !== ".." && !normalized.startsWith(`..${sep3}`);
3722
+ return normalized !== "." && !isAbsolute(normalized) && normalized !== ".." && !normalized.startsWith(`..${sep}`);
3964
3723
  }
3965
3724
  function diffsSince(repo, git = runGit, diffFrom = diffsFrom(repo, git)) {
3966
3725
  const bases = /* @__PURE__ */ new Map();
@@ -3992,12 +3751,16 @@ async function headMovesNewestFirst(repo, git) {
3992
3751
  function diffsFrom(repo, git = runGit) {
3993
3752
  const diffs = /* @__PURE__ */ new Map();
3994
3753
  return (path, commit) => remembered(diffs, `${commit} ${path}`, async () => {
3995
- const diff = await git(repo, ["-c", "diff.suppressBlankEmpty=false", "diff", "--no-color", "--no-ext-diff", "--no-textconv", commit, "--", path]);
3754
+ const diff = await git(repo, ["diff", ...PARSED_DIFF_OPTIONS, "--unified=3", commit, "--", ...literalPathspecs([path])]);
3996
3755
  if (diff === null) return null;
3756
+ if (diff === "" && !await isConfirmedTracked(repo, path, git)) return { excerpt: void 0, changed: null, hunks: null };
3997
3757
  const hunks = parseHunks(diff);
3998
- return { excerpt: excerptOf(diff), changed: changedRanges(hunks ?? []), hunks };
3758
+ return { excerpt: excerptOf(diff), changed: hunks === null ? null : changedRanges(hunks), hunks };
3999
3759
  });
4000
3760
  }
3761
+ async function isConfirmedTracked(repo, path, git) {
3762
+ return outputLine(await git(repo, ["ls-files", "--", ...literalPathspecs([path])])) !== null;
3763
+ }
4001
3764
  function excerptOf(diff) {
4002
3765
  if (diff.trim() === "") return void 0;
4003
3766
  const lines = diff.trimEnd().split("\n");
@@ -4017,16 +3780,17 @@ async function sourceFiles(repo, paths) {
4017
3780
  };
4018
3781
  }
4019
3782
  async function sourceFile(repo, path) {
4020
- const absolute = join12(repo, path);
3783
+ const absolute = join11(repo, path);
4021
3784
  if (!await fileExists(absolute)) return { kind: "missing", path };
4022
3785
  return { kind: "present", path, text: await readTextIfFile(absolute) };
4023
3786
  }
4024
3787
  function parseLog(output) {
4025
3788
  return output.split(RECORD).filter((record) => record.trim() !== "").map((record) => {
4026
3789
  const headerEnd = record.includes("\0") ? record.indexOf("\0") : record.length;
4027
- const [sha = "", date = "", parents = "", subject = ""] = record.slice(0, headerEnd).trim().split(FIELD);
3790
+ const [sha = "", shortSha = "", date = "", parents = "", subject = ""] = record.slice(0, headerEnd).trim().split(FIELD);
4028
3791
  return {
4029
3792
  sha,
3793
+ shortSha,
4030
3794
  date,
4031
3795
  parents: parents.split(" ").filter((parent) => parent !== ""),
4032
3796
  subject,
@@ -4061,111 +3825,589 @@ function parseStatus(output) {
4061
3825
  paths.push(entry.slice(STATUS_CODE_WIDTH));
4062
3826
  if (ORIGINAL_PATH_FOLLOWS.test(entry)) index++;
4063
3827
  }
4064
- return paths;
3828
+ return paths;
3829
+ }
3830
+ function withinRepo(gitRootPaths, prefix) {
3831
+ return gitRootPaths.filter((path) => path.startsWith(prefix)).map((path) => path.slice(prefix.length));
3832
+ }
3833
+ async function modificationTimes(repo, paths) {
3834
+ const entries = await Promise.all(
3835
+ paths.map(async (path) => {
3836
+ const info = await lstatOrNull(join11(repo, path));
3837
+ return info === null ? [] : [[path, info.mtimeMs]];
3838
+ })
3839
+ );
3840
+ return new Map(entries.flat());
3841
+ }
3842
+
3843
+ // src/core/check/current-source.ts
3844
+ var LATER_COMMITS_TO_SEARCH = 5;
3845
+ var UNTRACED = { kind: "untraced" };
3846
+ function repoDiffs(repo) {
3847
+ const from = diffsFrom(repo);
3848
+ return { since: diffsSince(repo, runGit, from), from, headAt: headsAt(repo) };
3849
+ }
3850
+ function diffsSinceCreation(repo, { since, from }, origins) {
3851
+ const onThisLine = /* @__PURE__ */ new Map();
3852
+ const isOnThisLine = (commit) => remembered(onThisLine, commit, async () => await runGit(repo, ["merge-base", "--is-ancestor", commit, "HEAD"]) !== null);
3853
+ return async (task, path) => {
3854
+ const origin = task.verified === void 0 ? origins.get(task.id) : void 0;
3855
+ return origin !== void 0 && await isOnThisLine(origin.commit) ? from(path, origin.commit) : since(path, new Date(reviewMark(task)));
3856
+ };
3857
+ }
3858
+ async function traceSources(tasks, facts, diffs) {
3859
+ return new Map(await Promise.all(tasks.map(async (task) => [task.id, await traceSource(task, facts, diffs)])));
3860
+ }
3861
+ function currentSourcesOf(traces) {
3862
+ return new Map([...traces].map(([id, trace]) => [id, currentOf(trace)]));
3863
+ }
3864
+ async function currentSourceIn(repo, task) {
3865
+ if (task.source === void 0) return null;
3866
+ const facts = await collectRepoFacts(repo, /* @__PURE__ */ new Map([[sourcePath(task.source), reviewMark(task)]]));
3867
+ return currentOf(await traceSource(task, facts, repoDiffs(repo)));
3868
+ }
3869
+ function currentOf(trace) {
3870
+ return trace.kind === "traced" ? trace.current : null;
3871
+ }
3872
+ async function traceSource(task, facts, diffs) {
3873
+ const { source, anchor } = task;
3874
+ if (source === void 0 || !hasLines(source)) return UNTRACED;
3875
+ const text = facts.texts.get(sourcePath(source));
3876
+ if (text === void 0) return UNTRACED;
3877
+ const { commits, uncommitted } = changesSince(facts, sourcePath(source), reviewMark(task));
3878
+ const fileUntouched = commits.length === 0 && !uncommitted;
3879
+ if (fileUntouched && (anchor === void 0 || windowMatches(text, source, anchor))) return { kind: "traced", current: source, linesChanged: false };
3880
+ const traced = { ...task, source };
3881
+ const reference = await referenceOf(traced, text, commits, diffs);
3882
+ if (reference.kind === "not-on-branch") return fileUntouched ? { kind: "not-on-branch" } : UNTRACED;
3883
+ if (reference.kind === "untraced") return UNTRACED;
3884
+ const lines = anchorRange(reference.source);
3885
+ return { kind: "traced", current: currentSource(reference, text, traced), linesChanged: lines === null || modifiesLines(reference.hunks, lines) };
3886
+ }
3887
+ function currentSource(reference, text, { source, anchor }) {
3888
+ const current = remappedSource(reference.source, (line) => currentLine(reference.hunks, line));
3889
+ if (current === null || anchorOf(text, current) === null) return null;
3890
+ return anchor === void 0 && current !== source ? null : current;
3891
+ }
3892
+ async function referenceOf(task, text, laterCommits, diffs) {
3893
+ const path = sourcePath(task.source);
3894
+ const { anchor } = task;
3895
+ const mark = new Date(reviewMark(task));
3896
+ const head = anchor === void 0 ? null : await diffs.headAt(mark);
3897
+ const headAtMark = async () => head?.onThisLine === true ? diffs.from(path, head.commit) : null;
3898
+ const lastCommitBeforeMark = () => diffs.since(path, mark);
3899
+ const afterMark = laterCommits.toReversed().slice(0, LATER_COMMITS_TO_SEARCH).map((commit) => () => diffs.from(path, commit.sha));
3900
+ const references = anchor === void 0 ? [lastCommitBeforeMark] : [headAtMark, lastCommitBeforeMark, ...afterMark];
3901
+ const unmatched = head?.onThisLine === false ? { kind: "not-on-branch" } : { kind: "untraced" };
3902
+ let search = { kind: "untraced" };
3903
+ for (const diffFromReference of references) {
3904
+ const hunks = (await diffFromReference())?.hunks ?? null;
3905
+ if (hunks === null) continue;
3906
+ const source = anchor === void 0 ? task.source : locateAnchor(baseText(hunks, text), task.source, anchor);
3907
+ if (source !== null) return { kind: "found", hunks, source };
3908
+ search = unmatched;
3909
+ }
3910
+ return search;
3911
+ }
3912
+
3913
+ // src/core/check/project-repo.ts
3914
+ async function sourceAnchor(repo, source, onUnreadable) {
3915
+ const text = repo === void 0 ? null : await attemptReportingFailure(join12(repo, sourcePath(source)), readTextIfFile, onUnreadable);
3916
+ if (text === null) return { kind: "no-file" };
3917
+ const anchor = anchorOf(text, source);
3918
+ return anchor === null ? { kind: "uncomputable" } : { kind: "anchor", anchor };
3919
+ }
3920
+ async function sourcePresence(repo, source, onUnreadable) {
3921
+ const path = sourcePath(source);
3922
+ const onDisk = await attemptReportingFailure(join12(repo, path), fileExists, onUnreadable);
3923
+ const presentOrUnreadable = onDisk !== false;
3924
+ if (presentOrUnreadable) return "present";
3925
+ return presenceOffDisk(path, await branchHistoryOf(repo, await locateRepo(repo), [path]));
3926
+ }
3927
+ async function relocatedSource(repo, task) {
3928
+ const current = repo === void 0 ? null : await currentSourceIn(repo, task);
3929
+ return current === null || current === task.source ? void 0 : current;
3930
+ }
3931
+ async function findRepo(project, { workingRoots, ...lookup }) {
3932
+ return (await projectCheckout(project, workingRoots, lookup))?.path;
3933
+ }
3934
+ async function projectCheckout(project, workingRoots, lookup) {
3935
+ const repo = await firstExistingRepo(project, lookup);
3936
+ if (repo === void 0) return void 0;
3937
+ if (workingRoots === null || workingRoots.main !== realpathOrNull(repo)) return { path: repo, linkedWorktree: false };
3938
+ return { path: workingRoots.worktree, linkedWorktree: workingRoots.worktree !== workingRoots.main };
3939
+ }
3940
+ async function firstExistingRepo(project, { home: home2, onUnreadable }) {
3941
+ for (const repo of project.repos.map((path) => expandHome(path, home2))) {
3942
+ if (await attemptReportingFailure(repo, fileExists, onUnreadable) === true) return repo;
3943
+ }
3944
+ return void 0;
3945
+ }
3946
+ async function hasCommit(repo, sha) {
3947
+ return await runGit(repo, ["cat-file", "-e", `${sha}^{commit}`]) !== null;
3948
+ }
3949
+
3950
+ // src/core/store/create.ts
3951
+ import { mkdir as mkdir3 } from "node:fs/promises";
3952
+ import { basename as basename6, join as join13 } from "node:path";
3953
+ var MAX_ID_ATTEMPTS = 20;
3954
+ async function createTask(root, request) {
3955
+ const { project, existingTasks: existingTasks2 } = request;
3956
+ const dir = join13(root, project.id);
3957
+ const index = buildIndex(existingTasks2);
3958
+ for (let attempt = 0; attempt < MAX_ID_ATTEMPTS; attempt++) {
3959
+ const id = formatId(project.prefix, await nextTaskNumber(dir, project, request.onError));
3960
+ const path = join13(dir, taskFileName(id));
3961
+ const normalized = taskText(draftTask(id, path, request));
3962
+ if (!normalized.ok) return invalid(normalized.problems);
3963
+ const { text, task } = normalized.value;
3964
+ const problems3 = integrityErrors(task, index);
3965
+ if (problems3.length > 0) return invalid(problems3);
3966
+ try {
3967
+ await createFileAtomic(path, text);
3968
+ await appendJournal(dir, [createdEvent(task, request.now, request.via, request.provenance)], request.onError);
3969
+ return { ok: true, task, reopenedEpic: await reopenEpicOfOpenedTask(index, { before: void 0, after: task }, request) };
3970
+ } catch (error) {
3971
+ if (!hasErrorCode(error, "EEXIST")) throw error;
3972
+ }
3973
+ }
3974
+ return invalid([{ code: "id-exhausted", attempts: MAX_ID_ATTEMPTS }]);
3975
+ }
3976
+ async function createProject(root, repoRoot, existingProjects) {
3977
+ for (let attempt = 1; ; attempt++) {
3978
+ const { id, path, text } = await draftProjectFile(root, repoRoot, existingProjects);
3979
+ try {
3980
+ await createFileAtomic(path, text);
3981
+ const parsed = parseProjectFile(text, { id, path });
3982
+ if (!parsed.ok) throw new Error(`${path}: ${parsed.problems.map((problem3) => problem3.code).join(", ")}`);
3983
+ return parsed.value;
3984
+ } catch (error) {
3985
+ if (!hasErrorCode(error, "EEXIST")) throw error;
3986
+ const concurrent = await projectOfRepo(id, path, repoRoot);
3987
+ if (concurrent !== null) return concurrent;
3988
+ if (attempt === MAX_ID_ATTEMPTS) throw error;
3989
+ }
3990
+ }
3991
+ }
3992
+ async function draftProjectFile(root, repoRoot, existingProjects) {
3993
+ const name = basename6(repoRoot);
3994
+ const entries = await listDir(root);
3995
+ const joinable = await Promise.all(entries.map((entry) => entry.isDirectory() && isJoinableProjectDir(join13(root, entry.name), repoRoot)));
3996
+ const id = deriveProjectId(name, new Set(entries.filter((_, index) => !joinable[index]).map((entry) => entry.name)));
3997
+ const prefixesOnDisk = await Promise.all(entries.filter((entry) => entry.isDirectory()).map((entry) => takenPrefixes(join13(root, entry.name))));
3998
+ const prefix = derivePrefix(name, /* @__PURE__ */ new Set([...existingProjects.map((project) => project.prefix), ...prefixesOnDisk.flat()]));
3999
+ const dir = join13(root, id);
4000
+ await mkdir3(dir, { recursive: true });
4001
+ return { id, path: join13(dir, PROJECT_FILE), text: serializeProject({ name, prefix, repos: [repoRoot], active: true, extra: {}, body: "" }) };
4002
+ }
4003
+ async function isJoinableProjectDir(dir, repoRoot) {
4004
+ const entries = await listDir(dir);
4005
+ if (entries.some((entry) => entry.name === PROJECT_FILE)) return await projectOfRepo(basename6(dir), join13(dir, PROJECT_FILE), repoRoot) !== null;
4006
+ return entries.every((entry) => !entry.name.endsWith(".md"));
4007
+ }
4008
+ async function projectOfRepo(id, path, repoRoot) {
4009
+ const parsed = await readProjectFile({ id, path });
4010
+ return parsed?.ok === true && parsed.value.repos.includes(repoRoot) ? parsed.value : null;
4011
+ }
4012
+ async function nextTaskNumber(dir, project, onError) {
4013
+ const onDisk = await maxTaskNumber(dir, project.prefix);
4014
+ const reserved = await issuedUpToOnDisk(project);
4015
+ const journaled = await maxJournaledNumber(dir, project, onError);
4016
+ return Math.max(onDisk, reserved, journaled, project.issuedUpTo ?? 0) + 1;
4017
+ }
4018
+ async function maxJournaledNumber(dir, project, onError) {
4019
+ const journal = await attemptReportingFailure(join13(dir, JOURNAL_FILE), () => readJournal(dir, project.id), onError);
4020
+ const journaledIds = (journal?.events ?? []).flatMap((event) => parseId(event.task) ?? []);
4021
+ return maxNumberWithPrefix(journaledIds, project.prefix);
4022
+ }
4023
+ async function maxTaskNumber(dir, prefix) {
4024
+ return maxNumberWithPrefix(await taskFileIds(dir), prefix);
4025
+ }
4026
+ function maxNumberWithPrefix(ids, prefix) {
4027
+ return ids.reduce((max, parsed) => parsed.prefix === prefix ? Math.max(max, parsed.number) : max, 0);
4028
+ }
4029
+ var PREFIX_LINE = /^prefix:\s*["']?([^\s"']+)/m;
4030
+ async function takenPrefixes(dir) {
4031
+ const declared = PREFIX_LINE.exec(await readTextOrNull(join13(dir, PROJECT_FILE)) ?? "")?.[1];
4032
+ return [...declared !== void 0 && PREFIX_PATTERN.test(declared) ? [declared] : [], ...(await taskFileIds(dir)).map((parsed) => parsed.prefix)];
4033
+ }
4034
+ async function taskFileIds(dir) {
4035
+ return [...await taskIdsOnDisk(dir)].flatMap((id) => parseId(id) ?? []);
4036
+ }
4037
+ function draftTask(id, path, { project, input, now }) {
4038
+ return {
4039
+ id,
4040
+ title: input.title,
4041
+ type: input.type ?? "task",
4042
+ status: "backlog",
4043
+ priority: input.priority ?? "medium",
4044
+ category: input.category,
4045
+ tags: input.tags ?? [],
4046
+ epic: input.epic,
4047
+ blockedBy: input.blockedBy ?? [],
4048
+ related: input.related ?? [],
4049
+ created: formatLocalIso(now),
4050
+ source: input.source,
4051
+ anchor: input.anchor,
4052
+ extra: {},
4053
+ body: input.body ?? "",
4054
+ projectId: project.id,
4055
+ path
4056
+ };
4057
+ }
4058
+
4059
+ // src/core/store/resolve-project.ts
4060
+ import { isAbsolute as isAbsolute2, relative, resolve as resolve2, sep as sep2 } from "node:path";
4061
+ var REPO_ROOT_TTL_MS = 6e4;
4062
+ var SHOW_ROOTS = ["rev-parse", "--show-toplevel", "--git-dir", "--git-common-dir"];
4063
+ var LIST_WORKTREES = ["worktree", "list", "--porcelain"];
4064
+ function findGitRoots(dir) {
4065
+ const parsed = parseRevParse(dir, runGitSync(dir, SHOW_ROOTS));
4066
+ if (parsed === null) return null;
4067
+ return rootsOf(parsed, parsed.isMainWorktree ? null : runGitSync(dir, LIST_WORKTREES));
4068
+ }
4069
+ async function findGitRootsAsync(dir) {
4070
+ const parsed = parseRevParse(dir, await runGit(dir, SHOW_ROOTS));
4071
+ if (parsed === null) return null;
4072
+ return rootsOf(parsed, parsed.isMainWorktree ? null : await runGit(dir, LIST_WORKTREES));
4073
+ }
4074
+ function cachedRepoRoots({ onUnreadable, ttlMs = REPO_ROOT_TTL_MS, now = Date.now }) {
4075
+ const known = /* @__PURE__ */ new Map();
4076
+ const isFresh = ({ checkedAt }) => now() - checkedAt < ttlMs;
4077
+ return (dir) => {
4078
+ const cached = known.get(dir);
4079
+ if (cached !== void 0 && isFresh(cached)) return cached.roots;
4080
+ for (const [knownDir, entry] of known) if (!isFresh(entry)) known.delete(knownDir);
4081
+ const roots = attemptReportingFailure(dir, async (path) => await findGitRootsAsync(path) ?? plainDirRoots(path), onUnreadable);
4082
+ known.set(dir, { roots, checkedAt: now() });
4083
+ return roots;
4084
+ };
4085
+ }
4086
+ function rootsOf({ topLevel }, worktreeList) {
4087
+ return canonicalRoots(topLevel, mainWorktreeIn(worktreeList) ?? topLevel);
4088
+ }
4089
+ function plainDirRoots(dir) {
4090
+ const path = realpathOrNull(dir);
4091
+ return path === null ? null : { worktree: path, main: path };
4092
+ }
4093
+ function parseRevParse(dir, output) {
4094
+ const [topLevel = "", gitDir = "", commonDir = ""] = (output ?? "").split("\n").map((line) => line.trim());
4095
+ if (topLevel === "") return null;
4096
+ const isMainWorktree = commonDir === "" || realpathOrNull(resolve2(dir, gitDir)) === realpathOrNull(resolve2(dir, commonDir));
4097
+ return { topLevel, isMainWorktree };
4098
+ }
4099
+ function mainWorktreeIn(porcelain) {
4100
+ const [first = ""] = (porcelain ?? "").split("\n\n");
4101
+ const lines = first.split("\n");
4102
+ const path = lines.find((line) => line.startsWith("worktree "))?.slice("worktree ".length);
4103
+ return path === void 0 || lines.includes("bare") ? null : path;
4104
+ }
4105
+ function canonicalRoots(worktreePath, mainPath) {
4106
+ const worktree = realpathOrNull(worktreePath);
4107
+ const main = realpathOrNull(mainPath);
4108
+ return worktree === null || main === null ? null : { worktree, main };
4109
+ }
4110
+ function readGitRoots(dir, onUnreadable) {
4111
+ return attemptReportingFailureSync(dir, (path) => findGitRoots(path) ?? "not-in-repo", onUnreadable) ?? "unreadable";
4112
+ }
4113
+ function repoRootsOf(dirRoots) {
4114
+ return typeof dirRoots === "string" ? null : dirRoots;
4115
+ }
4116
+ function findProjectForDir(projects, dir, dirRoots, places) {
4117
+ const roots = matchingRoots(dir, dirRoots, places);
4118
+ return roots === null ? void 0 : findProjectForRoots(projects, roots, places);
4119
+ }
4120
+ function matchingRoots(dir, dirRoots, places) {
4121
+ if (dirRoots === "unreadable") return null;
4122
+ return dirRoots === "not-in-repo" ? attemptReportingFailureSync(dir, plainDirRoots, places.onUnreadable) : dirRoots;
4123
+ }
4124
+ function findProjectForRoots(projects, roots, places) {
4125
+ const matches = projects.flatMap(
4126
+ (project) => project.repos.flatMap((repo) => {
4127
+ const repoPath = resolvedRepo(repo, places);
4128
+ return repoPath !== null && repoCovers(repoPath, roots) ? [{ project, repoPath }] : [];
4129
+ })
4130
+ );
4131
+ return matches.sort((a, b) => b.repoPath.length - a.repoPath.length)[0]?.project;
4132
+ }
4133
+ function anyRepoCovers(repos, roots, places) {
4134
+ return repos.some((repo) => {
4135
+ const repoPath = resolvedRepo(repo, places);
4136
+ return repoPath !== null && repoCovers(repoPath, roots);
4137
+ });
4138
+ }
4139
+ function repoCovers(repoPath, { worktree, main }) {
4140
+ return isSameOrInside(worktree, repoPath) || isSameOrInside(main, repoPath);
4141
+ }
4142
+ function isSameOrInside(path, container) {
4143
+ const relation = relative(container, path);
4144
+ return relation === "" || !isAbsolute2(relation) && relation.split(sep2)[0] !== "..";
4145
+ }
4146
+ function resolvedRepo(repo, { home: home2, onUnreadable }) {
4147
+ return attemptReportingFailureSync(expandHome(repo, home2), realpathOrNull, onUnreadable);
4148
+ }
4149
+
4150
+ // src/cli/lookups.ts
4151
+ function warnUnreadableSkipped(warn2, core) {
4152
+ return warnPathErrors(warn2, core.unreadableSkipped);
4153
+ }
4154
+ var placesOfRun = /* @__PURE__ */ new WeakMap();
4155
+ function repoPlaces(io) {
4156
+ const known = placesOfRun.get(io);
4157
+ if (known !== void 0) return known;
4158
+ const places = { home: io.home, onUnreadable: oncePerPath(warnUnreadableSkipped(io.warn, io.core)) };
4159
+ placesOfRun.set(io, places);
4160
+ return places;
4161
+ }
4162
+ var cwdRootsOfRun = /* @__PURE__ */ new WeakMap();
4163
+ function cwdDirRoots(io) {
4164
+ const known = cwdRootsOfRun.get(io);
4165
+ if (known !== void 0) return known;
4166
+ const roots = readGitRoots(io.cwd, repoPlaces(io).onUnreadable);
4167
+ cwdRootsOfRun.set(io, roots);
4168
+ return roots;
4169
+ }
4170
+ function cwdGitRoots(io) {
4171
+ return repoRootsOf(cwdDirRoots(io));
4172
+ }
4173
+ function findProjectForCwd(projects, io) {
4174
+ return findProjectForDir(projects, io.cwd, cwdDirRoots(io), repoPlaces(io));
4175
+ }
4176
+ function repoLookup(io) {
4177
+ return { ...repoPlaces(io), workingRoots: cwdGitRoots(io) };
4178
+ }
4179
+ async function sourcePresenceOrWarn(io, repo, source) {
4180
+ const presence = await sourcePresence(repo, source, repoPlaces(io).onUnreadable);
4181
+ if (presence === "missing") io.warn(io.cli.sourceFileMissing(source));
4182
+ if (presence === "unchecked") io.warn(io.cli.sourceFileUnchecked(source));
4183
+ return presence;
4184
+ }
4185
+ function findTaskOrWarn(loaded, io, id) {
4186
+ const task = loaded.tasks.find((candidate) => candidate.id === id);
4187
+ if (task) return task;
4188
+ const broken = loaded.errors.find((error) => basename7(error.path) === `${id}.md`);
4189
+ io.warn(broken ? io.cli.taskFileUnparsed(id, io.core.problems(broken.problems)) : io.cli.taskNotFound(id));
4190
+ return void 0;
4191
+ }
4192
+ function projectOf(loaded, task) {
4193
+ return loaded.projects.find((project) => project.id === task.projectId);
4194
+ }
4195
+ async function findProjectOrWarn(loaded, io, explicitId) {
4196
+ const project = findProject(loaded, io, explicitId);
4197
+ if (project) return project;
4198
+ const broken = await unparsedProjectFilesOfScope(loaded, io, explicitId);
4199
+ if (broken.length > 0) warnUnparsedProjectFiles(io, broken, io.cli.projectFileUnparsed);
4200
+ else io.warn(explicitId === void 0 ? io.cli.projectNotFoundForCwd(io.cwd) : io.cli.projectNotFound(explicitId));
4201
+ return void 0;
4202
+ }
4203
+ async function unparsedProjectFilesOfScope(loaded, io, explicitId) {
4204
+ if (explicitId !== void 0) return unparsedProjectFiles(loaded.errors).filter((error) => error.projectId === explicitId);
4205
+ const roots = matchingRoots(io.cwd, cwdDirRoots(io), repoPlaces(io));
4206
+ return roots === null ? [] : unparsedProjectFilesCovering(loaded, roots, io);
4207
+ }
4208
+ function warnUnparsedProjectFiles(io, errors, message) {
4209
+ for (const error of errors) io.warn(message(error.path, io.core.problems(error.problems)));
4210
+ }
4211
+ async function ensureProject(loaded, io, explicitId) {
4212
+ if (explicitId !== void 0) return findProjectOrWarn(loaded, io, explicitId);
4213
+ const existing = findProject(loaded, io, void 0);
4214
+ if (existing) return existing;
4215
+ const gitRoots = cwdDirRoots(io);
4216
+ if (gitRoots === "unreadable") return void 0;
4217
+ if (gitRoots === "not-in-repo") {
4218
+ io.warn(io.cli.notInGitRepo(io.cwd));
4219
+ return void 0;
4220
+ }
4221
+ const broken = await unparsedProjectFilesCovering(loaded, gitRoots, io);
4222
+ if (broken.length > 0) {
4223
+ warnUnparsedProjectFiles(io, broken, io.cli.projectNotCreatedFileUnparsed);
4224
+ return void 0;
4225
+ }
4226
+ const created = await createProject(io.backlogRoot, gitRoots.main, loaded.projects);
4227
+ io.warn(io.cli.projectCreated(created.id, created.prefix));
4228
+ return created;
4229
+ }
4230
+ async function unparsedProjectFilesCovering(loaded, roots, io) {
4231
+ const ownId = projectIdBase(basename7(roots.main));
4232
+ const broken = await Promise.all(unparsedProjectFiles(loaded.errors).map(async (error) => ({ error, text: await readTextOrNull(error.path) ?? "" })));
4233
+ const isOwnProjectDir = ({ error }) => basename7(dirname6(error.path)) === ownId;
4234
+ const listsCoveringRepo = ({ text }) => anyRepoCovers(reposOfUnparsed(text), roots, repoPlaces(io));
4235
+ return broken.filter((file) => isOwnProjectDir(file) || listsCoveringRepo(file)).map(({ error }) => error);
4236
+ }
4237
+ function findProject(loaded, io, explicitId) {
4238
+ return explicitId === void 0 ? findProjectForCwd(loaded.projects, io) : loaded.projects.find((project) => project.id === explicitId);
4239
+ }
4240
+
4241
+ // src/cli/task-write.ts
4242
+ function taskWriter(io, loadedTasks) {
4243
+ const index = buildIndex(loadedTasks);
4244
+ const onError = warnPathErrors(io.warn);
4245
+ return async (task, changes, closure) => {
4246
+ const result = await updateTaskInIndex(index, { id: task.id, changes, expectedVersion: task.version, now: io.now(), via: "cli", onError, closure });
4247
+ if (!result.ok) return { ok: false, exitCode: reportUpdateFailure(io, task.id, result) };
4248
+ if (result.reopenedEpic !== void 0) io.warn(io.cli.epicReopened(result.reopenedEpic.id));
4249
+ return result;
4250
+ };
4251
+ }
4252
+ function reportUpdateFailure(io, id, result) {
4253
+ switch (result.reason) {
4254
+ case "not-found":
4255
+ io.warn(io.cli.taskNotFound(id));
4256
+ return EXIT.notFound;
4257
+ case "conflict":
4258
+ io.warn(io.cli.fileConflict(id));
4259
+ return EXIT.invalid;
4260
+ case "busy":
4261
+ io.warn(io.core.fileBusy(result));
4262
+ return EXIT.failed;
4263
+ case "invalid":
4264
+ for (const problem3 of result.problems) io.warn(io.core.problem(problem3));
4265
+ return EXIT.invalid;
4266
+ }
4065
4267
  }
4066
- function withinRepo(gitRootPaths, prefix) {
4067
- return gitRootPaths.filter((path) => path.startsWith(prefix)).map((path) => path.slice(prefix.length));
4268
+
4269
+ // src/cli/task-field-command.ts
4270
+ function taskFieldCommand(spec) {
4271
+ const command2 = {
4272
+ name: spec.name,
4273
+ usage: () => [`<ID> <${spec.choices}>`],
4274
+ run: async (args, io) => {
4275
+ const { positionals } = parseCommandArgs(io.language, args, {});
4276
+ const [id, rawValue, ...rest] = positionals;
4277
+ if (id === void 0 || rawValue === void 0 || rest.length > 0) throw usageError(command2, io.language);
4278
+ const value = spec.parse(io.language, rawValue);
4279
+ const loaded = await loadBacklog(io.backlogRoot);
4280
+ const task = findTaskOrWarn(loaded, io, id);
4281
+ if (!task) return EXIT.notFound;
4282
+ const changes = spec.changes(value);
4283
+ const before = spec.label(task, io.language);
4284
+ if (alreadyHas(task, changes)) {
4285
+ io.print(io.cli.alreadySet(id, before));
4286
+ return EXIT.ok;
4287
+ }
4288
+ const written = await taskWriter(io, loaded.tasks)(task, changes);
4289
+ if (!written.ok) return written.exitCode;
4290
+ spec.afterWrite?.(written.task, io, task);
4291
+ io.print(`${id}: ${before} \u2192 ${spec.label(written.task, io.language)}`);
4292
+ return EXIT.ok;
4293
+ }
4294
+ };
4295
+ return command2;
4068
4296
  }
4069
- async function modificationTimes(repo, paths) {
4070
- const entries = await Promise.all(
4071
- paths.map(async (path) => {
4072
- const info = await lstatOrNull(join12(repo, path));
4073
- return info === null ? [] : [[path, info.mtimeMs]];
4074
- })
4075
- );
4076
- return new Map(entries.flat());
4297
+ function alreadyHas(task, changes) {
4298
+ return Object.entries(changes).every(([field, next]) => (task[field] ?? null) === (next ?? null));
4077
4299
  }
4078
4300
 
4079
- // src/core/check/current-source.ts
4080
- var LATER_COMMITS_TO_SEARCH = 5;
4081
- var UNTRACED = { kind: "untraced" };
4082
- function repoDiffs(repo) {
4083
- const from = diffsFrom(repo);
4084
- return { since: diffsSince(repo, runGit, from), from, headAt: headsAt(repo) };
4301
+ // src/cli/commands/category.ts
4302
+ var NO_CATEGORY = "none";
4303
+ var categoryCommand = taskFieldCommand({
4304
+ name: "category",
4305
+ choices: `${TASK_CATEGORIES.join("|")}|${NO_CATEGORY}`,
4306
+ parse: (language, value) => value === NO_CATEGORY ? null : parseChoice(language, value, TASK_CATEGORIES, cliMessages(language).optionLabel.category),
4307
+ changes: (category) => ({ category }),
4308
+ label: (task, language) => coreMessages(language).categoryLabel(task.category)
4309
+ });
4310
+
4311
+ // src/core/check/check-backlog.ts
4312
+ import { join as join17 } from "node:path";
4313
+
4314
+ // src/core/check/check-fixes.ts
4315
+ async function applyFixes(loaded, inScope, { messages, ...writes }) {
4316
+ const isGone = goneTaskCheck(loaded);
4317
+ const epicFixes = await epicStatusFixes(loaded, inScope, messages);
4318
+ const planned = loaded.tasks.filter((task) => inScope(task.projectId)).flatMap((task) => {
4319
+ const fix = planFix(task, isGone, epicFixes.get(task.id));
4320
+ return fix === null ? [] : [{ task, ...fix }];
4321
+ });
4322
+ return applyPlanned(buildIndex(loaded.tasks), planned, writes);
4085
4323
  }
4086
- async function traceSources(tasks, facts, diffs) {
4087
- return new Map(await Promise.all(tasks.map(async (task) => [task.id, await traceSource(task, facts, diffs)])));
4324
+ async function applyAnchorPlans(tasks, plans, writes) {
4325
+ const index = buildIndex(tasks);
4326
+ const planned = plans.flatMap((plan) => {
4327
+ const task = index.byId.get(plan.id);
4328
+ return task === void 0 ? [] : [{ task, changes: plan.changes, done: plan.moved === void 0 ? [] : [plan.moved] }];
4329
+ });
4330
+ return applyPlanned(index, planned, writes);
4088
4331
  }
4089
- function currentSourcesOf(traces) {
4090
- return new Map([...traces].map(([id, trace]) => [id, currentOf(trace)]));
4332
+ async function applyPlanned(index, planned, writes) {
4333
+ const fixed = [];
4334
+ const failed2 = [];
4335
+ for (const { task, changes, closure, done } of planned) {
4336
+ const result = await updateTaskInIndex(index, { id: task.id, changes, expectedVersion: task.version, closure, ...writes, via: "check" });
4337
+ if (result.ok) fixed.push(...done);
4338
+ else failed2.push(fixFailure(task.id, result));
4339
+ }
4340
+ return { fixed, failed: failed2 };
4091
4341
  }
4092
- async function currentSourceIn(repo, task) {
4093
- if (task.source === void 0) return null;
4094
- const facts = await collectRepoFacts(repo, /* @__PURE__ */ new Map([[sourcePath(task.source), reviewMark(task)]]));
4095
- return currentOf(await traceSource(task, facts, repoDiffs(repo)));
4342
+ function fixFailure(taskId, failure) {
4343
+ switch (failure.reason) {
4344
+ case "invalid":
4345
+ return { kind: "fix-failed", taskId, cause: "invalid", problems: failure.problems };
4346
+ case "conflict":
4347
+ return { kind: "fix-failed", taskId, cause: "changed-during-check" };
4348
+ case "not-found":
4349
+ return { kind: "fix-failed", taskId, cause: "gone-during-check" };
4350
+ case "busy":
4351
+ return { kind: "fix-failed", taskId, cause: "busy-during-check" };
4352
+ }
4096
4353
  }
4097
- function currentOf(trace) {
4098
- return trace.kind === "traced" ? trace.current : null;
4354
+ async function epicStatusFixes(loaded, inScope, messages) {
4355
+ const closing = planEpicClosing(loaded.tasks, loaded.errors).close.map(({ epic, childIds }) => [
4356
+ epic.id,
4357
+ { status: "done", closure: epicDoneClosure(childIds, messages), done: { kind: "epic-closed", taskId: epic.id, childIds } }
4358
+ ]);
4359
+ const reopenable = planEpicReopening(loaded.tasks).filter(({ epic }) => inScope(epic.projectId));
4360
+ const reopening = await Promise.all(
4361
+ reopenable.map(async ({ epic, childIds }) => [epic.id, { status: await statusToReopen(epic), done: { kind: "epic-reopened", taskId: epic.id, childIds } }])
4362
+ );
4363
+ return new Map([...closing, ...reopening]);
4099
4364
  }
4100
- async function traceSource(task, facts, diffs) {
4101
- const { source, anchor } = task;
4102
- if (source === void 0 || !hasLines(source)) return UNTRACED;
4103
- const text = facts.texts.get(sourcePath(source));
4104
- if (text === void 0) return UNTRACED;
4105
- const { commits, uncommitted } = changesSince(facts, sourcePath(source), reviewMark(task));
4106
- const fileUntouched = commits.length === 0 && !uncommitted;
4107
- if (fileUntouched && (anchor === void 0 || windowMatches(text, source, anchor))) return { kind: "traced", current: source, linesChanged: false };
4108
- const traced = { ...task, source };
4109
- const reference = await referenceOf(traced, text, commits, diffs);
4110
- if (reference.kind === "not-on-branch") return fileUntouched ? { kind: "not-on-branch" } : UNTRACED;
4111
- if (reference.kind === "untraced") return UNTRACED;
4112
- const lines = anchorRange(reference.source);
4113
- return { kind: "traced", current: currentSource(reference, text, traced), linesChanged: lines === null || modifiesLines(reference.hunks, lines) };
4365
+ function planFix(task, isGone, epicFix) {
4366
+ const cleanup = referenceCleanup(task, isGone);
4367
+ if (cleanup === null && epicFix === void 0) return null;
4368
+ const done = [];
4369
+ if (cleanup !== null) done.push({ kind: "references-removed", taskId: task.id, ids: goneReferences(task, isGone) });
4370
+ if (epicFix === void 0) return { changes: cleanup ?? {}, done };
4371
+ return { changes: { ...cleanup, status: epicFix.status }, closure: epicFix.closure, done: [...done, epicFix.done] };
4114
4372
  }
4115
- function currentSource(reference, text, { source, anchor }) {
4116
- const current = remappedSource(reference.source, (line) => currentLine(reference.hunks, line));
4117
- if (current === null || anchorOf(text, current) === null) return null;
4118
- return anchor === void 0 && current !== source ? null : current;
4373
+ function goneReferences(task, isGone) {
4374
+ const references = [...task.blockedBy, ...task.related, ...task.epic === void 0 ? [] : [task.epic]];
4375
+ return [...new Set(references.filter(isGone))];
4119
4376
  }
4120
- async function referenceOf(task, text, laterCommits, diffs) {
4121
- const path = sourcePath(task.source);
4122
- const { anchor } = task;
4123
- const mark = new Date(reviewMark(task));
4124
- const head = anchor === void 0 ? null : await diffs.headAt(mark);
4125
- const headAtMark = async () => head?.onThisLine === true ? diffs.from(path, head.commit) : null;
4126
- const lastCommitBeforeMark = () => diffs.since(path, mark);
4127
- const afterMark = laterCommits.toReversed().slice(0, LATER_COMMITS_TO_SEARCH).map((commit) => () => diffs.from(path, commit.sha));
4128
- const references = anchor === void 0 ? [lastCommitBeforeMark] : [headAtMark, lastCommitBeforeMark, ...afterMark];
4129
- const unmatched = head?.onThisLine === false ? { kind: "not-on-branch" } : { kind: "untraced" };
4130
- let search = { kind: "untraced" };
4131
- for (const diffFromReference of references) {
4132
- const hunks = (await diffFromReference())?.hunks ?? null;
4133
- if (hunks === null) continue;
4134
- const source = anchor === void 0 ? task.source : locateAnchor(baseText(hunks, text), task.source, anchor);
4135
- if (source !== null) return { kind: "found", hunks, source };
4136
- search = unmatched;
4137
- }
4138
- return search;
4377
+ function goneTaskCheck(loaded) {
4378
+ const known = /* @__PURE__ */ new Set([...loaded.tasks.map((task) => task.id), ...unparsedTasks(loaded.errors).map((task) => task.id)]);
4379
+ const loadedPrefixes = new Set(loaded.projects.map((project) => project.prefix));
4380
+ return (id) => {
4381
+ const prefix = parseId(id)?.prefix;
4382
+ return prefix !== void 0 && loadedPrefixes.has(prefix) && !known.has(id);
4383
+ };
4139
4384
  }
4140
4385
 
4141
- // src/core/check/project-repo.ts
4142
- async function sourceAnchor(repo, source, onUnreadable) {
4143
- const text = repo === void 0 ? null : await attemptReportingFailure(join13(repo, sourcePath(source)), readTextIfFile, onUnreadable);
4144
- if (text === null) return { kind: "no-file" };
4145
- const anchor = anchorOf(text, source);
4146
- return anchor === null ? { kind: "uncomputable" } : { kind: "anchor", anchor };
4147
- }
4148
- async function relocatedSource(repo, task) {
4149
- const current = repo === void 0 ? null : await currentSourceIn(repo, task);
4150
- return current === null || current === task.source ? void 0 : current;
4386
+ // src/core/check/find-problems.ts
4387
+ import { basename as basename8 } from "node:path";
4388
+ function findProblems(loaded, projects, repos, inScope) {
4389
+ const index = buildIndex(loaded.tasks);
4390
+ const integrity = loaded.tasks.filter((task) => inScope(task.projectId)).flatMap((task) => integrityErrors(task, index).map((problem3) => ({ kind: "task-invalid", taskId: task.id, problem: problem3 })));
4391
+ const missingRepos = projects.filter((project) => repos.get(project.id) === void 0).map(missingRepoProblem);
4392
+ return [...parseProblems(loaded, inScope), ...integrity, ...missingRepos, ...sharedPrefixes(loaded.projects, inScope)];
4151
4393
  }
4152
- async function findRepo(project, { workingRoots, ...lookup }) {
4153
- return (await projectCheckout(project, workingRoots, lookup))?.path;
4394
+ function sharedPrefixes(projects, inScope) {
4395
+ const idsByPrefix = /* @__PURE__ */ new Map();
4396
+ for (const project of projects) idsByPrefix.set(project.prefix, [...idsByPrefix.get(project.prefix) ?? [], project.id]);
4397
+ return [...idsByPrefix].filter(([, projectIds]) => projectIds.length > 1 && projectIds.some(inScope)).map(([prefix, projectIds]) => ({ kind: "prefix-shared", prefix, projectIds }));
4154
4398
  }
4155
- async function projectCheckout(project, workingRoots, lookup) {
4156
- const repo = await firstExistingRepo(project, lookup);
4157
- if (repo === void 0) return void 0;
4158
- if (workingRoots === null || workingRoots.main !== realpathOrNull(repo)) return { path: repo, linkedWorktree: false };
4159
- return { path: workingRoots.worktree, linkedWorktree: workingRoots.worktree !== workingRoots.main };
4399
+ function parseProblems(loaded, inScope) {
4400
+ const waitingEpicIds = planEpicClosing(loaded.tasks, loaded.errors).waiting.filter(({ epic }) => inScope(epic.projectId)).map(({ epic }) => epic.id);
4401
+ const everyFileMayHoldWaitingChild = waitingEpicIds.length > 0;
4402
+ const reported = loaded.errors.filter((error) => everyFileMayHoldWaitingChild || concernsScope(error, inScope)).map((error) => ({ kind: "file-not-parsed", path: error.path, problems: error.problems }));
4403
+ if (waitingEpicIds.length === 0) return reported;
4404
+ return [...reported, { kind: "epics-wait-for-files", epicIds: waitingEpicIds }];
4160
4405
  }
4161
- async function firstExistingRepo(project, { home: home2, onUnreadable }) {
4162
- for (const repo of project.repos.map((path) => expandHome(path, home2))) {
4163
- if (await attemptReportingFailure(repo, fileExists, onUnreadable) === true) return repo;
4164
- }
4165
- return void 0;
4406
+ function concernsScope(error, inScope) {
4407
+ return inScope(error.projectId) || basename8(error.path) === PROJECT_FILE;
4166
4408
  }
4167
- async function hasCommit(repo, sha) {
4168
- return await runGit(repo, ["cat-file", "-e", `${sha}^{commit}`]) !== null;
4409
+ function missingRepoProblem(project) {
4410
+ return project.repos.length === 0 ? { kind: "project-without-repos", projectId: project.id } : { kind: "project-repos-missing", projectId: project.id, repos: project.repos };
4169
4411
  }
4170
4412
 
4171
4413
  // src/core/check/project-review.ts
@@ -4282,25 +4524,31 @@ async function contains(git, repo, descendant, commit) {
4282
4524
  }
4283
4525
 
4284
4526
  // src/core/check/landed-content.ts
4285
- var PATCH_OPTIONS = ["-p", "--no-color", "--no-ext-diff", "--no-textconv", "--no-renames", "--no-relative", "--full-index", "--diff-algorithm=myers", "--indent-heuristic"];
4527
+ var PATCH_OPTIONS = ["-p", ...PARSED_DIFF_OPTIONS, "--no-renames", "--no-relative", "--full-index", "--diff-algorithm=myers", "--indent-heuristic", "--unified=3", "--inter-hunk-context=0"];
4528
+ var LINE_SHIFT_OPTIONS = [...PATCH_OPTIONS, "--unified=0"];
4286
4529
  var COMMIT_HEADER = "--format=commit %H";
4287
4530
  var TREE_PAIR_LINE = /^[0-9a-f]+ [0-9a-f]+$/;
4288
4531
  var NO_COMMIT = /^0+$/;
4289
- var RAW_RECORD = /commit (?<commit>[0-9a-f]+)\0|:\d+ (?<mode>\d+) [0-9a-f]+ (?<object>[0-9a-f]+) [A-Z]\d*\0(?<path>[^\0]*)\0/g;
4290
- async function contentLanded(repo, tip, git) {
4532
+ var COMMIT_RECORD = /commit (?<commit>[0-9a-f]+)\0/;
4533
+ var FILE_RECORD = /:\d+ (?<mode>\d+) [0-9a-f]+ (?<object>[0-9a-f]+) [A-Z]\d*\0(?<path>[^\0]*)\0/;
4534
+ var RAW_RECORD = new RegExp(`${COMMIT_RECORD.source}|${FILE_RECORD.source}`, "g");
4535
+ async function landingState(repo, tip, git) {
4291
4536
  const fork = await forkAt(repo, "HEAD", tip, git);
4292
- if (fork === null) return false;
4537
+ if (fork === null) return "unknown";
4293
4538
  const view = { ...fork, repo, historyOptions: [], git };
4294
4539
  const changed = await branchChanges(view, []);
4295
- if (changed === null) return false;
4296
- if (changed.length === 0) return true;
4540
+ if (changed === null) return "unknown";
4541
+ if (changed.length === 0) return "landed";
4297
4542
  const landed = await headChanges(view, topLiteralPathspecs(changed.map(({ path }) => path)));
4298
- if (landed === null) return false;
4543
+ if (landed === null) return "unknown";
4299
4544
  const landedVersions = new Set(landed.map(({ version }) => version));
4545
+ let state = "landed";
4300
4546
  for (const { path, version } of changed) {
4301
- if (!landedVersions.has(version) && !await changeLanded(view, path)) return false;
4547
+ const pathState = landedVersions.has(version) ? "landed" : await changeLanded(view, path);
4548
+ if (pathState === "pending") return "pending";
4549
+ if (pathState === "unknown") state = "unknown";
4302
4550
  }
4303
- return true;
4551
+ return state;
4304
4552
  }
4305
4553
  function commitsCarryingContent(repo, git, historyOptions) {
4306
4554
  const forks = /* @__PURE__ */ new Map();
@@ -4363,7 +4611,9 @@ function rawChanges(raw) {
4363
4611
  }
4364
4612
  async function changeLanded(view, path) {
4365
4613
  const copies = await patchCopies(view, path);
4366
- return copies !== null && (copies.squashed.length > 0 || everyCommitCopied(copies));
4614
+ if (copies === null) return "unknown";
4615
+ if (copies.squashed.length > 0 || everyCommitCopied(copies)) return "landed";
4616
+ return copies.shiftsComplete ? "pending" : "unknown";
4367
4617
  }
4368
4618
  function everyCommitCopied({ commitByCommit }) {
4369
4619
  return commitByCommit.length > 0 && commitByCommit.every((commitCopies) => commitCopies.length > 0);
@@ -4384,9 +4634,9 @@ async function patchCopies(view, path) {
4384
4634
  const headPatchesById = groupBy(headPatches, ({ id }) => id);
4385
4635
  const sameChanges = (change) => (headPatchesById.get(change.id) ?? []).filter((copy) => isSameChange(change, copy));
4386
4636
  const pairs = [...squashedPatch, ...branchPatches].flatMap((change) => sameChanges(change).map((copy) => [change, copy]));
4387
- const shiftsBetween = await preimageShifts(view, path, pairs);
4637
+ const { shiftsBetween, complete } = await preimageShifts(view, path, pairs);
4388
4638
  const copiesOf = (change) => sameChanges(change).flatMap((copy) => atSamePlace(change, copy, shiftsBetween) ? [copy.commit] : []);
4389
- return { squashed: squashedPatch.flatMap(copiesOf), commitByCommit: branchPatches.map(copiesOf) };
4639
+ return { squashed: squashedPatch.flatMap(copiesOf), commitByCommit: branchPatches.map(copiesOf), shiftsComplete: complete };
4390
4640
  }
4391
4641
  async function patchesOf(repo, patchArgs, preimageOf, git) {
4392
4642
  const patches = await git(repo, patchArgs);
@@ -4409,21 +4659,18 @@ async function preimageShifts(repoGit, path, pairs) {
4409
4659
  return from === void 0 || to === void 0 ? null : `${from} ${to}`;
4410
4660
  };
4411
4661
  const shiftsByTreePair = await treeDiffShifts(repoGit, path, [...new Set(shifted.flatMap(([change, copy]) => treePairOf(change, copy) ?? []))]);
4412
- return (change, copy) => {
4662
+ const shiftsBetween = (change, copy) => {
4413
4663
  if (!shiftsNeeded(change, copy)) return [];
4414
4664
  const treePair = treePairOf(change, copy);
4415
- return treePair === null ? null : shiftsByTreePair.get(treePair) ?? null;
4665
+ return treePair === null ? null : shiftsByTreePair?.get(treePair) ?? null;
4416
4666
  };
4667
+ return { shiftsBetween, complete: trees !== null && shiftsByTreePair !== null };
4417
4668
  }
4418
4669
  async function treeDiffShifts({ repo, git }, path, treePairs) {
4419
4670
  if (treePairs.length === 0) return /* @__PURE__ */ new Map();
4420
- const preimageDiffs = await git(
4421
- repo,
4422
- ["diff-tree", "--stdin", ...PATCH_OPTIONS, "--unified=0", "--inter-hunk-context=0", "--", ...topLiteralPathspecs([path])],
4423
- treePairs.map((treePair) => `${treePair}
4424
- `).join("")
4425
- );
4426
- return preimageDiffs === null ? /* @__PURE__ */ new Map() : lineShiftsByTreePair(preimageDiffs);
4671
+ const preimageDiffs = await git(repo, ["diff-tree", "--stdin", ...LINE_SHIFT_OPTIONS, "--", ...topLiteralPathspecs([path])], treePairs.map((treePair) => `${treePair}
4672
+ `).join(""));
4673
+ return preimageDiffs === null ? null : lineShiftsByTreePair(preimageDiffs);
4427
4674
  }
4428
4675
  function lineShiftsByTreePair(preimageDiffs) {
4429
4676
  const shiftsByTreePair = /* @__PURE__ */ new Map();
@@ -4475,32 +4722,36 @@ async function commitsKnownAtCreation({ repo, tasks, facts, anchors, origins, gi
4475
4722
  const path = sourcePath(task.source);
4476
4723
  return [{ taskId: task.id, creation: origin.commit, path, changes: commitsTouchingSince(facts.commits, path, reviewMark(task)) }];
4477
4724
  });
4478
- const branchCommitsByMerge = /* @__PURE__ */ new Map();
4479
- const commitsBroughtBy = (merge, creation, path) => remembered(
4480
- branchCommitsByMerge,
4481
- `${merge.sha} ${creation} ${path}`,
4482
- async () => outputLines(await git(repo, ["rev-list", `${merge.sha}^2`, `^${merge.sha}^1`, `^${creation}`, "--", ...literalPathspecs([path])]))
4483
- );
4484
- const carryingContent = commitsCarryingContent(repo, git, FACTS_HISTORY_OPTIONS);
4485
- const copyAnswers = /* @__PURE__ */ new Map();
4486
- const copiesOfCreation = (creation, path) => remembered(copyAnswers, `${creation} ${path}`, () => carryingContent(creation, literalPathspecs([path])));
4487
- const isCopy = (copies, sha) => copies.some((fullSha) => fullSha.startsWith(sha));
4488
- const mergeBringsOnlyCopies = async (merge, creation, path) => {
4489
- const brought = await commitsBroughtBy(merge, creation, path);
4490
- if (brought === null) return false;
4491
- const copies = brought.length === 0 ? [] : await copiesOfCreation(creation, path);
4492
- return brought.every((sha) => isCopy(copies, sha));
4493
- };
4494
- const commitIsCopy = async (commit, creation, path) => isCopy(await copiesOfCreation(creation, path), commit.sha);
4495
- const isKnown = (commit, creation, path) => commit.parents.length === MERGE_PARENTS ? mergeBringsOnlyCopies(commit, creation, path) : commitIsCopy(commit, creation, path);
4725
+ const copies = creationCopies(repo, git);
4496
4726
  const answers = await Promise.all(
4497
4727
  questions.map(async ({ taskId, creation, path, changes }) => {
4498
- const known = await Promise.all(changes.map(async (commit) => await isKnown(commit, creation, path) ? [commit.sha] : []));
4728
+ const known = await Promise.all(changes.map(async (commit) => await isKnownAtCreation(copies, commit, creation, path) ? [commit.sha] : []));
4499
4729
  return { taskId, known: known.flat() };
4500
4730
  })
4501
4731
  );
4502
4732
  return new Map(answers.filter(({ known }) => known.length > 0).map(({ taskId, known }) => [taskId, new Set(known)]));
4503
4733
  }
4734
+ function creationCopies(repo, git) {
4735
+ const carryingContent = commitsCarryingContent(repo, git, FACTS_HISTORY_OPTIONS);
4736
+ const branchCommitsByMerge = /* @__PURE__ */ new Map();
4737
+ const copiesByCreation = /* @__PURE__ */ new Map();
4738
+ return {
4739
+ broughtByMerge: (merge, creation, path) => remembered(
4740
+ branchCommitsByMerge,
4741
+ `${merge.sha} ${creation} ${path}`,
4742
+ async () => outputLines(await git(repo, ["rev-list", `${merge.sha}^2`, `^${merge.sha}^1`, `^${creation}`, "--", ...literalPathspecs([path])]))
4743
+ ),
4744
+ copiesOf: (creation, path) => remembered(copiesByCreation, `${creation} ${path}`, async () => new Set(await carryingContent(creation, literalPathspecs([path]))))
4745
+ };
4746
+ }
4747
+ async function isKnownAtCreation(copies, commit, creation, path) {
4748
+ if (commit.parents.length !== MERGE_PARENTS) return (await copies.copiesOf(creation, path)).has(commit.sha);
4749
+ const brought = await copies.broughtByMerge(commit, creation, path);
4750
+ if (brought === null) return false;
4751
+ if (brought.length === 0) return true;
4752
+ const copied = await copies.copiesOf(creation, path);
4753
+ return brought.every((sha) => copied.has(sha));
4754
+ }
4504
4755
 
4505
4756
  // src/core/model/query.ts
4506
4757
  var OPEN_STATUSES = TASK_STATUSES.filter((status) => !isClosed(status));
@@ -4679,28 +4930,41 @@ function bothConfirmedAfterCreation(a, b) {
4679
4930
 
4680
4931
  // src/core/check/awaiting-merge.ts
4681
4932
  var NOT_AN_ANCESTOR_EXIT = 1;
4933
+ var NO_SUCH_REF_EXIT = 1;
4682
4934
  async function awaitingMerge({ repo, taskIds, origins, git = runGitOutcome }) {
4683
4935
  const branched = taskIds.flatMap((id) => {
4684
4936
  const origin = origins.get(id);
4685
4937
  return origin?.branch === void 0 ? [] : [{ id, commit: origin.commit, branch: origin.branch }];
4686
4938
  });
4687
- if (branched.length === 0) return /* @__PURE__ */ new Set();
4939
+ if (branched.length === 0) return { pending: /* @__PURE__ */ new Set(), unknownBranches: [] };
4688
4940
  const current = lineOf(await git(repo, ["rev-parse", "--abbrev-ref", "HEAD"]));
4689
- const awaitingBranches = /* @__PURE__ */ new Map();
4690
- const pending = await Promise.all(
4941
+ const branchStates = /* @__PURE__ */ new Map();
4942
+ let shallow;
4943
+ const isShallow = () => shallow ??= isShallowClone(repo, git);
4944
+ const nested = await Promise.all(
4691
4945
  branched.map(async ({ id, commit, branch }) => {
4692
4946
  if (branch === current) return [];
4693
4947
  const ancestry = await git(repo, ["merge-base", "--is-ancestor", commit, "HEAD"]);
4694
- const notAnAncestor = ancestry.status === "exited" && ancestry.exitCode === NOT_AN_ANCESTOR_EXIT;
4695
- if (!notAnAncestor) return [];
4696
- return await remembered(awaitingBranches, branch, () => branchAwaitsMerge(repo, branch, git)) ? [id] : [];
4948
+ if (ancestry.status === "unfinished") return [{ id, branch, state: "unknown" }];
4949
+ if (ancestry.status === "ok") return [];
4950
+ const creationCommitUnreadable = ancestry.exitCode !== NOT_AN_ANCESTOR_EXIT;
4951
+ if (creationCommitUnreadable && !await isShallow()) return [];
4952
+ return [{ id, branch, state: await remembered(branchStates, branch, () => branchState(repo, branch, git)) }];
4697
4953
  })
4698
4954
  );
4699
- return new Set(pending.flat());
4955
+ const verdicts = nested.flat();
4956
+ const pending = verdicts.filter(({ state }) => state === "pending").map(({ id }) => id);
4957
+ const unknownBranches2 = new Set(verdicts.filter(({ state }) => state === "unknown").map(({ branch }) => branch));
4958
+ return { pending: new Set(pending), unknownBranches: [...unknownBranches2].sort() };
4959
+ }
4960
+ async function branchState(repo, branch, git) {
4961
+ const lookup = await git(repo, ["rev-parse", "--verify", "--quiet", `refs/heads/${branch}`]);
4962
+ const tip = lineOf(lookup);
4963
+ if (tip !== null) return landingState(repo, tip, asGitRunner(git));
4964
+ return lookup.status === "exited" && lookup.exitCode === NO_SUCH_REF_EXIT ? "deleted" : "unknown";
4700
4965
  }
4701
- async function branchAwaitsMerge(repo, branch, git) {
4702
- const tip = lineOf(await git(repo, ["rev-parse", "--verify", "--quiet", `refs/heads/${branch}`]));
4703
- return tip !== null && !await contentLanded(repo, tip, asGitRunner(git));
4966
+ async function isShallowClone(repo, git) {
4967
+ return lineOf(await git(repo, ["rev-parse", "--is-shallow-repository"])) === "true";
4704
4968
  }
4705
4969
  function lineOf(outcome) {
4706
4970
  return outputLine(stdoutOf(outcome));
@@ -4747,8 +5011,8 @@ async function decide(candidate, { tasksById, located, diffOf, symbolAt }) {
4747
5011
  if (task === void 0) return { kept: candidate };
4748
5012
  const found = symbolOfSource(symbolAt, located.get(task.id) ?? void 0);
4749
5013
  if (found === null) return { kept: candidate };
4750
- const diff = await diffOf(candidate.path, new Date(reviewMark(task)));
4751
- if (diff === null) return { kept: candidate };
5014
+ const diff = await diffOf(task, candidate.path);
5015
+ if (diff === null || diff.changed === null) return { kept: candidate };
4752
5016
  const watched = watchedRange(found.symbol, found.declared);
4753
5017
  if (diff.changed.some((range) => overlaps(range, watched))) return { kept: { ...candidate, method: "symbol" } };
4754
5018
  return { filtered: { task: task.id, symbol: shortName(found.symbol.qualifiedName) } };
@@ -4780,38 +5044,38 @@ async function projectReview(project, allTasks, { repo, origins, mode, onUnreada
4780
5044
  const tasks = allTasks.filter((task) => task.projectId === project.id && isReviewable(task));
4781
5045
  const nothing = { projectId: project.id, candidates: [], filtered: [], plans: [], problems: [], unchecked: [], awaitingMerge: [], skipped: [] };
4782
5046
  if (tasks.length === 0) return nothing;
4783
- if (repo === void 0) return { ...nothing, candidates: mode === "full" ? duplicateCandidates(tasks) : [], unchecked: ["source-changed", "source-missing"] };
5047
+ if (repo === void 0) return { ...nothing, candidates: mode === "full" ? duplicateCandidates(tasks) : [], unchecked: [...evidenceOf(tasks, "source-changed"), ...evidenceOf(tasks, "source-missing")] };
4784
5048
  const facts = await collectRepoFacts(repo, earliestMarks(tasks));
4785
5049
  for (const [path, error] of facts.unreadable) onUnreadable(join16(repo, path), error);
4786
5050
  const skipped = new Set(tasks.filter((task) => task.source !== void 0 && facts.unreadable.has(sourcePath(task.source))).map((task) => task.id));
4787
5051
  const readable = tasks.filter((task) => !skipped.has(task.id));
4788
- const scope = { repo, facts, origins, onUnreadable };
4789
- const review = await reviewedCode(readable, scope);
5052
+ const scope = { repo, facts, origins, mode, onUnreadable };
5053
+ const anchors = anchorStates(readable, facts);
5054
+ const review = await reviewedCode(readable, anchors, scope);
4790
5055
  const graph = openCodeGraph(repo);
4791
5056
  try {
4792
- const context = await projectContext(readable, review, { repo, facts, graph, mode, onUnreadable });
4793
- const sighted = await sightedBySymbol(tasks, review, context, { mode, skipped });
4794
- const judged = await judgedAgainstMerges(sighted, context, scope);
4795
- return { projectId: project.id, ...judged, skipped: [...skipped], problems: historyProblems(project, repo, facts.history), unchecked: facts.history === "read" ? [] : ["source-changed"] };
5057
+ const context = await projectContext(readable, review, scope, graph);
5058
+ const sighted = await sightedBySymbol(tasks, review, context, scope, skipped);
5059
+ const { problems: mergeProblems, ...judged } = await judgedAgainstMerges(sighted, context, scope, project.id);
5060
+ return { projectId: project.id, ...judged, skipped: [...skipped], problems: [...historyProblems(project, repo, facts), ...mergeProblems], unchecked: uncheckedEvidence(tasks, anchors, facts) };
4796
5061
  } finally {
4797
5062
  graph?.close();
4798
5063
  }
4799
5064
  }
4800
- async function reviewedCode(tasks, scope) {
5065
+ async function reviewedCode(tasks, anchors, scope) {
4801
5066
  const { repo, facts, origins } = scope;
4802
- const anchors = anchorStates(tasks, facts);
4803
5067
  const knownCommits = await commitsKnownAtCreation({ repo, tasks, facts, anchors, origins });
4804
5068
  return withRenamesFollowed(codeReview(tasks, facts, knownCommits, anchors), tasks, scope);
4805
5069
  }
4806
- async function projectContext(tasks, review, { repo, facts, graph, mode, onUnreadable }) {
5070
+ async function projectContext(tasks, review, { repo, facts, origins, mode, onUnreadable }, graph) {
4807
5071
  const diffs = repoDiffs(repo);
4808
5072
  const symbolAt = symbolLookup(graph, fileHashes(repo, onUnreadable));
4809
5073
  const changedIds = new Set(review.candidates.flatMap((candidate) => candidate.kind === "source-changed" ? [candidate.task.id] : []));
4810
5074
  const locating = mode === "full" && graph !== null ? tasks : tasks.filter((task) => changedIds.has(task.id));
4811
5075
  const traces = await traceSources(locating, facts, diffs);
4812
- return { tasksById: new Map(tasks.map((task) => [task.id, task])), located: currentSourcesOf(traces), traces, facts, diffOf: diffs.since, symbolAt };
5076
+ return { tasksById: new Map(tasks.map((task) => [task.id, task])), located: currentSourcesOf(traces), traces, facts, diffOf: diffsSinceCreation(repo, diffs, origins), symbolAt };
4813
5077
  }
4814
- async function sightedBySymbol(tasks, review, context, { mode, skipped }) {
5078
+ async function sightedBySymbol(tasks, review, context, { mode }, skipped) {
4815
5079
  const duplicates = mode === "full" ? duplicateCandidates(tasks, symbolNames(context.symbolAt, context.located)).filter((candidate) => !skipped.has(candidate.task.id)) : [];
4816
5080
  const byLines = judgedByLines(review.candidates, context.traces);
4817
5081
  const { kept, filtered } = await filterBySymbol(byLines.kept, context);
@@ -4821,15 +5085,16 @@ async function sightedBySymbol(tasks, review, context, { mode, skipped }) {
4821
5085
  };
4822
5086
  return { kept, filtered, plans: settledPlans(review.plans, settlement, context), duplicates };
4823
5087
  }
4824
- async function judgedAgainstMerges(sighted, context, { repo, origins }) {
4825
- const awaiting = await awaitingMerge({ repo, taskIds: involvedTaskIds(sighted), origins });
4826
- const judged = (id) => !awaiting.has(id);
5088
+ async function judgedAgainstMerges(sighted, context, { repo, origins }, projectId) {
5089
+ const { pending, unknownBranches: unknownBranches2 } = await awaitingMerge({ repo, taskIds: involvedTaskIds(sighted), origins });
5090
+ const judged = (id) => !pending.has(id);
4827
5091
  const code = await Promise.all(sighted.kept.filter((candidate) => judged(candidate.task.id)).map((candidate) => withContext2(candidate, context)));
4828
5092
  return {
4829
5093
  candidates: [...code, ...sighted.duplicates],
4830
5094
  filtered: sighted.filtered.filter((sighting) => judged(sighting.task)),
4831
5095
  plans: sighted.plans.filter((plan) => judged(plan.id)),
4832
- awaitingMerge: [...awaiting]
5096
+ awaitingMerge: [...pending],
5097
+ problems: unknownBranches2.length === 0 ? [] : [{ kind: "merge-state-unknown", projectId, repo, branches: unknownBranches2 }]
4833
5098
  };
4834
5099
  }
4835
5100
  function judgedByLines(candidates, traces) {
@@ -4860,10 +5125,18 @@ async function withRenamesFollowed(review, tasks, { repo, onUnreadable }) {
4860
5125
  function involvedTaskIds({ kept, filtered, plans }) {
4861
5126
  return [.../* @__PURE__ */ new Set([...kept.map((candidate) => candidate.task.id), ...filtered.map((sighting) => sighting.task), ...plans.map((plan) => plan.id)])];
4862
5127
  }
4863
- function historyProblems(project, repo, history) {
5128
+ function uncheckedEvidence(tasks, anchors, { history, branches, existing }) {
5129
+ const changeUnchecked = history === "read" ? [] : tasks.filter((task) => judgedByCommits(task, anchors));
5130
+ const missingUnchecked = branches.kind === "unreadable" ? tasks.filter((task) => task.source !== void 0 && !existing.has(sourcePath(task.source))) : [];
5131
+ return [...evidenceOf(changeUnchecked, "source-changed"), ...evidenceOf(missingUnchecked, "source-missing")];
5132
+ }
5133
+ function evidenceOf(tasks, evidence2) {
5134
+ return tasks.map((task) => ({ task: task.id, evidence: evidence2 }));
5135
+ }
5136
+ function historyProblems(project, repo, { history, branches }) {
4864
5137
  switch (history) {
4865
5138
  case "read":
4866
- return [];
5139
+ return branches.kind === "unreadable" ? [{ kind: "project-branches-unreadable", projectId: project.id, repo }] : [];
4867
5140
  case "not-a-repo":
4868
5141
  return [{ kind: "project-repo-not-git", projectId: project.id, repo }];
4869
5142
  case "unsafe-repo":
@@ -4900,7 +5173,7 @@ async function withContext2(candidate, { tasksById, located, facts, diffOf }) {
4900
5173
  const current = located.get(task.id) ?? void 0;
4901
5174
  const source = current ?? task.source;
4902
5175
  const snippet = text === void 0 || source === void 0 ? void 0 : snippetOf(text, source);
4903
- const excerpt = (await diffOf(candidate.path, new Date(reviewMark(task))))?.excerpt;
5176
+ const excerpt = (await diffOf(task, candidate.path))?.excerpt;
4904
5177
  const problem3 = firstParagraph(task.body);
4905
5178
  const moved = current === void 0 || current === task.source ? {} : { source: current };
4906
5179
  return { ...candidate, ...moved, ...problem3 === void 0 ? {} : { problem: problem3 }, ...snippet === void 0 ? {} : { snippet }, ...diffFields(excerpt) };
@@ -4967,8 +5240,7 @@ async function recordCandidates(root, tasks, { candidates, filtered, unchecked,
4967
5240
  const journal = await readJournal(dir, projectId);
4968
5241
  const states = episodeStates(journal.events);
4969
5242
  const sightings = found.map(sightingOf);
4970
- const checked = CANDIDATE_EVIDENCE.filter((evidence2) => !(unchecked.get(projectId) ?? []).includes(evidence2));
4971
- const gone = endsGone ? candidateGoneEvents({ sightings, reviewed, checked }, states, now) : [];
5243
+ const gone = endsGone ? candidateGoneEvents({ sightings, reviewed, unchecked: unchecked.get(projectId) ?? [] }, states, now) : [];
4972
5244
  await appendJournal(dir, [...candidateEvents(sightings, states, now, mode), ...gone, ...filteredEvents(filteredHere, states, now)], (_path, error) => reportFailure2(error));
4973
5245
  } catch (error) {
4974
5246
  reportFailure2(error);
@@ -5044,8 +5316,7 @@ function formatTaskDetails(cli, core, description, fileText) {
5044
5316
  cli.fileLine(task.path),
5045
5317
  cli.summaryLine({ type: task.type, status: task.status, priority: task.priority, progress: formatProgress(description.progress), categoryTail })
5046
5318
  ];
5047
- const deletesAt = deletionDate(task);
5048
- if (deletesAt !== void 0) lines.push(cli.closedLine(task.closed ?? "", formatLocalDay(deletesAt)));
5319
+ if (description.deletion !== void 0) lines.push(cli.closedLine(task.closed ?? "", deletionWhen(cli, description.deletion)));
5049
5320
  if (task.resolution !== void 0) lines.push(cli.reasonLine(task.resolution, task.reason ?? ""));
5050
5321
  if (task.verified !== void 0) lines.push(cli.verifiedLine(task.verified));
5051
5322
  if (task.tags.length > 0) lines.push(cli.tagsLine(task.tags.join(", ")));
@@ -5063,6 +5334,9 @@ function formatTaskDetails(cli, core, description, fileText) {
5063
5334
  function formatProgress(progress) {
5064
5335
  return progress === null ? "\u2014" : `${progress}%`;
5065
5336
  }
5337
+ function deletionWhen(cli, deletion) {
5338
+ return "at" in deletion ? formatLocalDay(deletion.at) : cli.afterEpicCloses(deletion.afterEpic);
5339
+ }
5066
5340
 
5067
5341
  // src/core/model/project-scope.ts
5068
5342
  function projectsInScope(projects, projectId, { wholeBacklog = false } = {}) {
@@ -5077,13 +5351,13 @@ var SCOPE_OPTIONS = {
5077
5351
  project: { type: "string" },
5078
5352
  "all-projects": { type: "boolean", default: false }
5079
5353
  };
5080
- function resolveScope(loaded, io, values) {
5354
+ async function resolveScope(loaded, io, values) {
5081
5355
  if (values.project !== void 0 && values["all-projects"] === true) throw new UsageError(io.cli.needProjectOrAllProjects);
5082
5356
  if (values["all-projects"] === true) {
5083
5357
  const projectIds = loaded.projects.map((project2) => project2.id);
5084
5358
  return { projectIds, activeIds: activeProjects(loaded.projects).map((project2) => project2.id) };
5085
5359
  }
5086
- const project = findProjectOrWarn(loaded, io, values.project);
5360
+ const project = await findProjectOrWarn(loaded, io, values.project);
5087
5361
  return project === void 0 ? null : { projectIds: [project.id], activeIds: [project.id], project };
5088
5362
  }
5089
5363
 
@@ -5100,7 +5374,7 @@ async function runCheck(args, io) {
5100
5374
  json: { type: "boolean", default: false }
5101
5375
  });
5102
5376
  const loaded = await loadBacklog(io.backlogRoot);
5103
- const scope = resolveScope(loaded, io, values);
5377
+ const scope = await resolveScope(loaded, io, values);
5104
5378
  if (scope === null) return EXIT.notFound;
5105
5379
  const { projectIds } = scope;
5106
5380
  const report = await checkBacklog(io.backlogRoot, loaded, {
@@ -5125,6 +5399,8 @@ var PROBLEM_NEEDS_REVIEW = {
5125
5399
  "project-repo-not-git": false,
5126
5400
  "project-repo-unsafe": false,
5127
5401
  "project-history-unreadable": false,
5402
+ "project-branches-unreadable": false,
5403
+ "merge-state-unknown": false,
5128
5404
  "prefix-shared": false
5129
5405
  };
5130
5406
  function needsReview({ candidates, problems: problems3 }) {
@@ -5197,23 +5473,31 @@ function isOpenAt(history, moment) {
5197
5473
  const first = history.transitions[0];
5198
5474
  return first?.from === void 0 || !isClosed(first.from);
5199
5475
  }
5200
- function closingsOf(history) {
5476
+ function allClosingsOf(history) {
5201
5477
  return history.transitions.filter(isClosingChange);
5202
5478
  }
5203
- function closingsOfIn(history, span2) {
5204
- return closingsOf(history).filter((closing) => span2.contains(closing.at));
5479
+ function lastingClosingOfIn(history, span2) {
5480
+ const closing = lastingClosingOf(history);
5481
+ return closing !== void 0 && span2.contains(closing.at) ? closing : void 0;
5482
+ }
5483
+ function lastingClosingsIn(histories, span2) {
5484
+ return histories.flatMap((history) => lastingClosingOfIn(history, span2) ?? []);
5205
5485
  }
5206
- function closingsIn(histories, span2) {
5207
- return histories.flatMap((history) => closingsOfIn(history, span2));
5486
+ function lastingClosingOf({ transitions }) {
5487
+ const sinceLastReopening = transitions.slice(transitions.findLastIndex(isReopening) + 1);
5488
+ return sinceLastReopening.findLast(isClosingChange);
5208
5489
  }
5209
5490
  function createdIn(histories, span2) {
5210
5491
  return histories.filter((history) => span2.contains(history.createdAt));
5211
5492
  }
5212
5493
  function isFixedNow(history) {
5213
- return isClosed(history.finalStatus) && closingsOf(history).at(-1)?.resolution === "fixed";
5494
+ return isClosed(history.finalStatus) && allClosingsOf(history).at(-1)?.resolution === "fixed";
5214
5495
  }
5215
5496
  function reopeningsOf(history) {
5216
- return history.transitions.filter((transition) => transition.from !== void 0 && isClosed(transition.from) && !isClosed(transition.to));
5497
+ return history.transitions.filter(isReopening);
5498
+ }
5499
+ function isReopening(transition) {
5500
+ return transition.from !== void 0 && isClosed(transition.from) && !isClosed(transition.to);
5217
5501
  }
5218
5502
  function historyOf(id, { projectId, final, created, categoryEvents, priorityEvents, transitions, candidates, verifications, filtered }, unparsed) {
5219
5503
  const creation = taskCreation(final, created);
@@ -5302,7 +5586,7 @@ function fixCommitEntry(history, commits) {
5302
5586
  function retainedFixes(histories, now) {
5303
5587
  const since = retainedSince(now);
5304
5588
  return histories.filter((history) => {
5305
- const closing = closingsOf(history).at(-1);
5589
+ const closing = allClosingsOf(history).at(-1);
5306
5590
  return isFixedNow(history) && closing !== void 0 && closing.at >= since;
5307
5591
  });
5308
5592
  }
@@ -5355,9 +5639,9 @@ async function runClose(args, io) {
5355
5639
  }
5356
5640
  const written = await taskWriter(io, loaded.tasks)(task, { status, related }, { resolution, reason });
5357
5641
  if (!written.ok) return written.exitCode;
5358
- const deletesAt = deletionDate(written.task);
5642
+ const deletion = scheduledDeletion(written.task, buildIndex(loaded.tasks.map((other) => other.id === written.task.id ? written.task : other)));
5359
5643
  const change = attachesFix ? status : `${task.status} \u2192 ${status}`;
5360
- io.print(`${id}: ${change} (${resolution})${deletesAt === void 0 ? "" : io.cli.deletesAtTail(formatLocalDay(deletesAt))}`);
5644
+ io.print(`${id}: ${change} (${resolution})${deletion === void 0 ? "" : io.cli.deletesAtTail(deletionWhen(io.cli, deletion))}`);
5361
5645
  return EXIT.ok;
5362
5646
  }
5363
5647
  function originalProblem(cli, task, original) {
@@ -5447,7 +5731,7 @@ async function isDirectory(path) {
5447
5731
 
5448
5732
  // src/cli/skill-link.ts
5449
5733
  import { mkdir as mkdir4, readlink as readlink2, symlink, unlink } from "node:fs/promises";
5450
- import { basename as basename8, dirname as dirname6, join as join20, resolve as resolve3 } from "node:path";
5734
+ import { basename as basename9, dirname as dirname7, join as join20, resolve as resolve3 } from "node:path";
5451
5735
  import { z as z8 } from "zod";
5452
5736
 
5453
5737
  // src/core/skill-name.ts
@@ -5470,8 +5754,8 @@ function skillLinkPath(skillsDir) {
5470
5754
  return join20(skillsDir, SKILL_NAME);
5471
5755
  }
5472
5756
  async function isPBacklogSkill(path) {
5473
- if (!SKILL_SOURCE_DIRS.has(basename8(path)) || basename8(dirname6(path)) !== SKILL_SOURCES_DIR) return false;
5474
- const manifest = await readTextOrNull(join20(dirname6(dirname6(path)), "package.json"));
5757
+ if (!SKILL_SOURCE_DIRS.has(basename9(path)) || basename9(dirname7(path)) !== SKILL_SOURCES_DIR) return false;
5758
+ const manifest = await readTextOrNull(join20(dirname7(dirname7(path)), "package.json"));
5475
5759
  if (manifest !== null) return parseJson(manifest, packageManifestSchema)?.name === "p-backlog";
5476
5760
  return !await pathExists(path);
5477
5761
  }
@@ -5632,7 +5916,6 @@ async function moveOne(id, { loaded, epic, write, io }) {
5632
5916
  }
5633
5917
 
5634
5918
  // src/cli/commands/hook.ts
5635
- import { dirname as dirname7 } from "node:path";
5636
5919
  import { parseArgs as parseArgs2 } from "node:util";
5637
5920
 
5638
5921
  // src/core/store/hook-turns.ts
@@ -5729,6 +6012,7 @@ function scopedReportData(input) {
5729
6012
  const scope = statsScope(input);
5730
6013
  const histories = scope.historiesWithEpics.filter((history) => history.type === "task");
5731
6014
  const tasks = scope.tasksWithEpics.filter((task) => task.type === "task");
6015
+ const firstCreated = smallest(histories.map((history) => history.createdAt));
5732
6016
  return {
5733
6017
  scope,
5734
6018
  histories,
@@ -5736,6 +6020,7 @@ function scopedReportData(input) {
5736
6020
  openTasks: tasks.filter((task) => !isClosed(task.status)),
5737
6021
  head: {
5738
6022
  taskCount: histories.length,
6023
+ backlogSince: firstCreated === null ? null : formatLocalIso(new Date(firstCreated)),
5739
6024
  journalSince: scope.journalSince,
5740
6025
  invalidJournalLines: scope.invalidJournalLines,
5741
6026
  unknownJournalLines: scope.unknownJournalLines,
@@ -5789,7 +6074,7 @@ function urgentStaleCount(openTasks, now) {
5789
6074
  return openTasks.filter((task) => (task.priority === "critical" || task.priority === "high") && daysBetween(Date.parse(task.created), now.getTime()) >= STALE_URGENT_DAYS).length;
5790
6075
  }
5791
6076
  function closingBreakdown(histories, period2) {
5792
- const closings = closingsIn(histories, period2);
6077
+ const closings = lastingClosingsIn(histories, period2);
5793
6078
  const created = createdIn(histories, period2);
5794
6079
  const byReason = { done: 0, fixed: 0, obsolete: 0, duplicate: 0, cancelled: 0, unknown: 0 };
5795
6080
  for (const closing of closings) byReason[closingReason(closing)] += 1;
@@ -5851,7 +6136,7 @@ function flowOver(periods, histories) {
5851
6136
  return periods.map((period2) => ({
5852
6137
  start: formatLocalIso(new Date(period2.from)),
5853
6138
  created: createdIn(histories, period2).length,
5854
- closed: closingsIn(histories, period2).length,
6139
+ closed: lastingClosingsIn(histories, period2).length,
5855
6140
  openAtEnd: histories.filter((history) => isOpenAt(history, period2.to)).length
5856
6141
  }));
5857
6142
  }
@@ -5931,7 +6216,7 @@ function countsPerKey(episodes, keys, keyOf) {
5931
6216
  });
5932
6217
  }
5933
6218
  function outcomeAfter(history, moment) {
5934
- const closedAt2 = closingsOf(history).find((closing) => closing.at > moment)?.at;
6219
+ const closedAt2 = allClosingsOf(history).find((closing) => closing.at > moment)?.at;
5935
6220
  const verifiedAt = history.verifications.find((verification) => verification > moment);
5936
6221
  if (closedAt2 === void 0) return verifiedAt === void 0 ? "open" : "verified";
5937
6222
  return verifiedAt !== void 0 && verifiedAt < closedAt2 ? "verified" : "closed";
@@ -6063,13 +6348,21 @@ function digest(text) {
6063
6348
  var STOP_REASON_LIMIT = 500;
6064
6349
  function stopReason(language, projectId, candidates) {
6065
6350
  const cli = cliMessages(language);
6066
- const items = candidates.map((candidate) => briefEvidence(cli, candidate));
6067
- const shown = [];
6068
- for (const item of items) {
6069
- if (compose(language, cli, projectId, [...shown, item], items.length - shown.length - 1).length > STOP_REASON_LIMIT) break;
6070
- shown.push(item);
6351
+ const text = (named2) => compose(
6352
+ language,
6353
+ cli,
6354
+ projectId,
6355
+ named2.map(({ item }) => item),
6356
+ candidates.length - named2.length
6357
+ );
6358
+ const named = [];
6359
+ for (const candidate of candidates) {
6360
+ const next = { id: candidate.task.id, item: briefEvidence(cli, candidate) };
6361
+ if (text([...named, next]).length <= STOP_REASON_LIMIT) named.push(next);
6071
6362
  }
6072
- return compose(language, cli, projectId, shown, items.length - shown.length);
6363
+ const [first] = candidates;
6364
+ if (named.length === 0 && first !== void 0) named.push({ id: first.task.id, item: first.task.id });
6365
+ return { text: text(named), namedTaskIds: named.map(({ id }) => id) };
6073
6366
  }
6074
6367
  function compose(language, cli, projectId, shown, hidden) {
6075
6368
  const more = hidden > 0 ? cli.stopReasonMore(hidden) : "";
@@ -6123,13 +6416,14 @@ async function runHook(args, io) {
6123
6416
  lowChangedSignals(lowCount),
6124
6417
  io
6125
6418
  ) : NO_SIGNALS;
6419
+ const reason = blocking.length > 0 ? stopReason(io.language, project.id, blocking) : null;
6126
6420
  const answer = formatStopAnswer(agent, {
6127
- reason: blocking.length > 0 ? stopReason(io.language, project.id, blocking) : null,
6421
+ reason: reason?.text ?? null,
6128
6422
  systemMessage: signals.fresh.length > 0 ? hookMessage(io.language, project.id, signals.fresh.map((signal3) => io.core.signal(signal3)).join("; ")) : null
6129
6423
  });
6130
6424
  if (answer !== null) io.print(answer);
6131
6425
  await signals.remember();
6132
- await session.remember(blocking.map((candidate) => candidate.task.id));
6426
+ await session.remember(reason?.namedTaskIds ?? []);
6133
6427
  return EXIT.ok;
6134
6428
  }
6135
6429
  async function isFirstHookOfTurn(agent, event, io) {
@@ -6145,7 +6439,7 @@ async function isFirstHookOfTurn(agent, event, io) {
6145
6439
  var NO_SESSION_MEMORY = { told: /* @__PURE__ */ new Set(), remember: rememberNothing };
6146
6440
  async function sessionMemory(project, session, io) {
6147
6441
  if (session === void 0) return NO_SESSION_MEMORY;
6148
- const projectDir2 = dirname7(project.path);
6442
+ const projectDir2 = projectDirOf(project);
6149
6443
  try {
6150
6444
  return {
6151
6445
  told: new Set(await readSessionShown(projectDir2, session)),
@@ -6164,7 +6458,7 @@ function lowChangedSignals(count3) {
6164
6458
  return [{ kind: "low-changed", params: { count: count3 } }];
6165
6459
  }
6166
6460
  async function freshSignals(project, tasks, extra, io) {
6167
- const projectDir2 = dirname7(project.path);
6461
+ const projectDir2 = projectDirOf(project);
6168
6462
  const today = formatLocalDay(io.now());
6169
6463
  try {
6170
6464
  const journal = await readJournal(projectDir2, project.id);
@@ -6196,7 +6490,8 @@ function describeTask(task, index) {
6196
6490
  related: relatedTasks(task, index),
6197
6491
  epic: task.epic === void 0 ? void 0 : index.byId.get(task.epic),
6198
6492
  children: task.type === "epic" ? epicChildren(task, index) : [],
6199
- warnings: taskWarnings(task, index)
6493
+ warnings: taskWarnings(task, index),
6494
+ deletion: scheduledDeletion(task, index)
6200
6495
  };
6201
6496
  }
6202
6497
  function descriptionJson(description) {
@@ -6211,12 +6506,12 @@ function descriptionJson(description) {
6211
6506
  epicTask: description.epic && reference(description.epic),
6212
6507
  children: description.children.map(reference),
6213
6508
  warnings: description.warnings,
6214
- deletesAt: deletesAtIso(description.task)
6509
+ ...deletionJson(description.deletion)
6215
6510
  };
6216
6511
  }
6217
- function deletesAtIso(task) {
6218
- const deletesAt = deletionDate(task);
6219
- return deletesAt === void 0 ? void 0 : formatLocalIso(deletesAt);
6512
+ function deletionJson(deletion) {
6513
+ if (deletion === void 0) return {};
6514
+ return "at" in deletion ? { deletesAt: formatLocalIso(deletion.at) } : { deletesAfterEpic: deletion.afterEpic };
6220
6515
  }
6221
6516
  function taskJson(task, index) {
6222
6517
  return descriptionJson(describeTask(task, index));
@@ -6243,7 +6538,7 @@ async function runList(args, io) {
6243
6538
  if (requestedStatuses?.length === 0) throw new UsageError(io.cli.invalidChoice("--status", TASK_STATUSES, values.status ?? ""));
6244
6539
  const statuses = requestedStatuses?.map((status) => parseChoice(io.language, status, TASK_STATUSES, "--status")) ?? OPEN_STATUSES;
6245
6540
  const loaded = await loadBacklog(io.backlogRoot);
6246
- const scope = resolveScope(loaded, io, values);
6541
+ const scope = await resolveScope(loaded, io, values);
6247
6542
  if (scope === null) return EXIT.notFound;
6248
6543
  const projectId = scope.project?.id;
6249
6544
  for (const error of loaded.errors) {
@@ -6341,7 +6636,7 @@ async function runNew(args, io) {
6341
6636
  }
6342
6637
  const { task, reopenedEpic } = result;
6343
6638
  if (reopenedEpic !== void 0) io.warn(io.cli.epicReopened(reopenedEpic.id));
6344
- io.print(values.json ? formatJson(taskJson(task, buildIndex(tasksAfterWrite(loaded.tasks, result)))) : `${task.id} ${task.path}`);
6639
+ io.print(values.json ? formatJson(taskJson(task, buildIndex(withWrittenTasks(loaded.tasks, [result])))) : `${task.id} ${task.path}`);
6345
6640
  return EXIT.ok;
6346
6641
  }
6347
6642
  function warnedOfSimilarTask(draft, projectTasks, io) {
@@ -6353,7 +6648,9 @@ function warnedOfSimilarTask(draft, projectTasks, io) {
6353
6648
  }
6354
6649
  async function anchorOf2(project, source, io) {
6355
6650
  const lookup = repoLookup(io);
6356
- return sourceAnchor(await findRepo(project, lookup), source, lookup.onUnreadable);
6651
+ const repo = await findRepo(project, lookup);
6652
+ if (repo !== void 0) await sourcePresenceOrWarn(io, repo, source);
6653
+ return sourceAnchor(repo, source, lookup.onUnreadable);
6357
6654
  }
6358
6655
  function cwdBelongsTo(project, knownProjects, io) {
6359
6656
  return findProjectForCwd([...knownProjects, project], io)?.id === project.id;
@@ -6390,7 +6687,9 @@ async function runProject(args, io) {
6390
6687
  }
6391
6688
  async function listProjects(io) {
6392
6689
  const loaded = await loadBacklog(io.backlogRoot);
6393
- if (loaded.projects.length === 0) {
6690
+ const broken = unparsedProjectFiles(loaded.errors);
6691
+ warnUnparsedProjectFiles(io, broken, io.cli.projectFileUnparsed);
6692
+ if (loaded.projects.length === 0 && broken.length === 0) {
6394
6693
  io.print(io.cli.noProjects);
6395
6694
  return EXIT.ok;
6396
6695
  }
@@ -6413,7 +6712,8 @@ async function changeStatus2(positionals, io) {
6413
6712
  io.warn(io.cli.projectNotFound(id));
6414
6713
  return EXIT.notFound;
6415
6714
  }
6416
- io.print(`${id}: ${statusWord(io.cli, !active)} \u2192 ${statusWord(io.cli, active)}`);
6715
+ const target = statusWord(io.cli, active);
6716
+ io.print(result.changed ? `${id}: ${statusWord(io.cli, !active)} \u2192 ${target}` : io.cli.alreadySet(id, target));
6417
6717
  return EXIT.ok;
6418
6718
  }
6419
6719
  async function removeProject(positionals, confirm, io) {
@@ -6446,7 +6746,7 @@ var pruneCommand = {
6446
6746
  async function runPrune(args, io) {
6447
6747
  const values = parseOptions(io.language, args, { ...SCOPE_OPTIONS, apply: { type: "boolean", default: false } });
6448
6748
  const loaded = await loadBacklog(io.backlogRoot);
6449
- const scope = resolveScope(loaded, io, values);
6749
+ const scope = await resolveScope(loaded, io, values);
6450
6750
  if (scope === null) return EXIT.notFound;
6451
6751
  const { activeIds } = scope;
6452
6752
  const stale = staleLowTasks(
@@ -6473,7 +6773,7 @@ async function runPrune(args, io) {
6473
6773
 
6474
6774
  // src/server/start.ts
6475
6775
  import { serve } from "@hono/node-server";
6476
- import { mkdir as mkdir6, rm as rm4, writeFile as writeFile3 } from "node:fs/promises";
6776
+ import { mkdir as mkdir6, rm as rm5, writeFile as writeFile2 } from "node:fs/promises";
6477
6777
  import { join as join32 } from "node:path";
6478
6778
 
6479
6779
  // src/server/app.ts
@@ -6566,12 +6866,23 @@ function isStale(graph, pinned, hashOf) {
6566
6866
  async function applyBatch(index, { tasks, action, now, onError }) {
6567
6867
  const ordered = [...tasks].sort((left, right) => compareIds(left.id, right.id));
6568
6868
  const journal = bufferedJournal(appendingJournal(onError));
6569
- const write = action.kind === "restore" ? undoJournal(journal.write) : journal.write;
6570
- const outcomes = [];
6571
- for (const task of ordered) outcomes.push(await applyOne(index, task, { action, now, onError, journal: write }).catch((error) => failed(task.id, error)));
6869
+ const step = { action, now, onError, journal: action.kind === "restore" ? undoJournal(journal.write) : journal.write };
6870
+ const closesAfterItsTasks = (task) => action.kind === "close" && index.byId.get(task.id)?.type === "epic";
6871
+ const [epics, others] = partition(ordered, closesAfterItsTasks);
6872
+ const taskOutcomes = await applyInOrder(index, others, step);
6873
+ const epicOutcomes = await applyInOrder(indexAfter(index, taskOutcomes), epics, step);
6572
6874
  await journal.flush();
6875
+ return [...taskOutcomes, ...epicOutcomes].sort((left, right) => compareIds(left.id, right.id));
6876
+ }
6877
+ async function applyInOrder(index, tasks, step) {
6878
+ const outcomes = [];
6879
+ for (const task of tasks) outcomes.push(await applyOne(index, task, step).catch((error) => failed(task.id, error)));
6573
6880
  return outcomes;
6574
6881
  }
6882
+ function indexAfter(index, outcomes) {
6883
+ const done = outcomes.filter((outcome) => outcome.outcome === "done");
6884
+ return done.length === 0 ? index : buildIndex(withWrittenTasks([...index.byId.values()], done));
6885
+ }
6575
6886
  async function applyOne(index, { id, version }, { action, now, onError, journal }) {
6576
6887
  const current = index.byId.get(id);
6577
6888
  if (!current) return { id, outcome: "skipped", reason: "not-found" };
@@ -6699,12 +7010,6 @@ function pruneUnlessKept(map, projectIds) {
6699
7010
  const kept = new Set(projectIds);
6700
7011
  for (const projectId of map.keys()) if (projectId !== void 0 && !kept.has(projectId)) map.delete(projectId);
6701
7012
  }
6702
- function forgetIfRejected(entries, key, value) {
6703
- if (!(value instanceof Promise)) return;
6704
- value.catch(() => {
6705
- if (entries.get(key)?.value === value) entries.delete(key);
6706
- });
6707
- }
6708
7013
  function createScopeMemo() {
6709
7014
  const slots = /* @__PURE__ */ new Map();
6710
7015
  return {
@@ -6713,7 +7018,11 @@ function createScopeMemo() {
6713
7018
  if (remembered2?.key === key) return remembered2.value;
6714
7019
  const value = compute();
6715
7020
  slots.set(projectId, { key, value });
6716
- forgetIfRejected(slots, projectId, value);
7021
+ if (value instanceof Promise) {
7022
+ value.catch(() => {
7023
+ if (slots.get(projectId)?.value === value) slots.delete(projectId);
7024
+ });
7025
+ }
6717
7026
  return value;
6718
7027
  },
6719
7028
  retain: (projectIds) => pruneUnlessKept(slots, projectIds)
@@ -6734,11 +7043,11 @@ function createJournalSources(root) {
6734
7043
  };
6735
7044
  const readTailed = async (projectId) => {
6736
7045
  const { length, generation, ...lines } = await tailOf(projectId).read();
6737
- return { journal: projectJournal(projectId, lines), position: `${projectId}=${generation}:${length}` };
7046
+ return { journal: projectJournal(projectId, lines), position: { projectId, generation, length } };
6738
7047
  };
6739
7048
  const rememberedContext = (snapshot, tailed) => (input) => {
6740
7049
  const positions = filterByProject(tailed, input.projectId, ({ journal }) => journal.projectId).map(({ position }) => position);
6741
- const key = `${snapshotIdOf(snapshot)}|${positions.join(",")}`;
7050
+ const key = JSON.stringify([snapshotIdOf(snapshot), positions]);
6742
7051
  return { ...remembered2.get(key, () => scopedReportData(input), input.projectId), input };
6743
7052
  };
6744
7053
  return {
@@ -6850,7 +7159,9 @@ function createTtlCache({ ttlMs, now }) {
6850
7159
  if (cached !== void 0) return cached.value;
6851
7160
  const value = compute();
6852
7161
  entries.set(key, { at: moment, value, tags });
6853
- forgetIfRejected(entries, key, value);
7162
+ value.catch(() => {
7163
+ if (entries.get(key)?.value === value) entries.delete(key);
7164
+ });
6854
7165
  return value;
6855
7166
  },
6856
7167
  clear: () => entries.clear(),
@@ -6920,7 +7231,10 @@ function createSnapshotCache({ root, revisions, journalSources, warn: warn2 }) {
6920
7231
  return {
6921
7232
  read: () => {
6922
7233
  if (snapshot !== null) return snapshot;
6923
- const loading = loadSnapshot(root, revisions.current(), journalSources, warn2);
7234
+ const loading = loadSnapshot(root, revisions.current(), journalSources, warn2).then((loaded) => {
7235
+ if (snapshot === loading) journalSources.retain(loaded.projects.map((project) => project.id));
7236
+ return loaded;
7237
+ });
6924
7238
  snapshot = loading;
6925
7239
  loading.catch(() => {
6926
7240
  if (snapshot === loading) snapshot = null;
@@ -6972,7 +7286,6 @@ function createChangeHub({ revisions, snapshots, derived, changes }) {
6972
7286
  async function loadSnapshot(root, revision, journalSources, warn2) {
6973
7287
  const loaded = await loadBacklog(root);
6974
7288
  const projectIds = loaded.projects.map((project) => project.id);
6975
- journalSources.retain(projectIds);
6976
7289
  const readableJournal = (projectId) => journalSources.journal(projectId).catch(async (error) => {
6977
7290
  await warn2((messages) => messages.journalReadFailed(join25(root, projectId, JOURNAL_FILE), errorText(error)));
6978
7291
  return { projectId, events: [], invalidLines: 0 };
@@ -6983,7 +7296,7 @@ async function loadSnapshot(root, revision, journalSources, warn2) {
6983
7296
 
6984
7297
  // src/server/stats-api.ts
6985
7298
  import { Hono } from "hono";
6986
- import { relative as relative3, sep as sep4 } from "node:path";
7299
+ import { relative as relative2, sep as sep3 } from "node:path";
6987
7300
 
6988
7301
  // src/core/api/stats-routes.ts
6989
7302
  var STATS_REPORT_ROUTES = {
@@ -7541,8 +7854,8 @@ function effectReport(context, code, wholeBacklog) {
7541
7854
  adopted.flatMap(({ units }) => units),
7542
7855
  estimate
7543
7856
  ),
7544
- weeks: bucketsOf(weekWindows(now), deferred, periodUnits, estimate),
7545
- days: bucketsOf(dayWindows(now), deferred, periodUnits, estimate),
7857
+ weeks: effectPeriodsOf(weekWindows(now), deferred, periodUnits, estimate),
7858
+ days: effectPeriodsOf(dayWindows(now), deferred, periodUnits, estimate),
7546
7859
  projects: adopted.map(
7547
7860
  ({ project, units }) => projectEffect(
7548
7861
  project,
@@ -7636,7 +7949,7 @@ function estimatedSizeOf(open2, estimate) {
7636
7949
  const sizes = estimates.filter((size) => size !== null);
7637
7950
  return { lines: sum(sizes.map((size) => size.lines)), testLines: sum(sizes.map((size) => size.testLines)) };
7638
7951
  }
7639
- function bucketsOf(windows, deferred, periodUnits, estimate) {
7952
+ function effectPeriodsOf(windows, deferred, periodUnits, estimate) {
7640
7953
  const { fixed, open: open2 } = byKind(deferred);
7641
7954
  return windows.map((window) => {
7642
7955
  const rawRealLines = sum(periodUnits.filter((unit) => window.contains(Date.parse(unit.date))).map((unit) => unit.lines));
@@ -7669,7 +7982,7 @@ function categoryBreakdown(openTasks, histories, period2) {
7669
7982
  target.weight += PRIORITY_WEIGHT[task.priority];
7670
7983
  }
7671
7984
  for (const history of createdIn(histories, period2)) row(history.category).created += 1;
7672
- for (const history of histories) row(history.category).closed += closingsOfIn(history, period2).length;
7985
+ for (const history of histories.filter((history2) => lastingClosingOfIn(history2, period2) !== void 0)) row(history.category).closed += 1;
7673
7986
  return [...rows.values()].filter((entry) => entry.open + entry.created + entry.closed > 0).sort((a, b) => Number(a.category === "unset") - Number(b.category === "unset") || b.weight - a.weight || b.created - a.created || a.category.localeCompare(b.category));
7674
7987
  }
7675
7988
 
@@ -7685,7 +7998,7 @@ function graphFilterEffect(histories, period2) {
7685
7998
  function filterOutcomeBetween(history, from, until) {
7686
7999
  const within = (at) => at > from && at <= until;
7687
8000
  const candidate = history.candidates.find((seen) => seen.evidence === "source-changed" && within(seen.at));
7688
- const closing = closingsOf(history).find((transition) => within(transition.at));
8001
+ const closing = allClosingsOf(history).find((transition) => within(transition.at));
7689
8002
  if (candidate !== void 0 && (closing === void 0 || candidate.at <= closing.at)) return "caught";
7690
8003
  if (closing === void 0 || !SILENT_CLOSINGS.has(closing.resolution)) return "quiet";
7691
8004
  const taken = history.transitions.some((transition) => transition.to === "in-progress" && transition.at > from && transition.at < closing.at);
@@ -7768,10 +8081,10 @@ function totals(histories, now, period2, journalStart) {
7768
8081
  return {
7769
8082
  open: ages.length,
7770
8083
  createdToday: createdIn(histories, today).length,
7771
- closedToday: closingsIn(histories, today).length,
8084
+ closedToday: lastingClosingsIn(histories, today).length,
7772
8085
  openWeight: sum(openNow.map(priorityWeight)),
7773
8086
  createdLastWeek: createdIn(histories, lastWeek).length,
7774
- closedLastWeek: closingsIn(histories, lastWeek).length,
8087
+ closedLastWeek: lastingClosingsIn(histories, lastWeek).length,
7775
8088
  ageMedianDays: median(ages),
7776
8089
  leadTimeMedianDays: median(leadTimes),
7777
8090
  leadTimeP90Days: nearestRank(leadTimes, TAIL_FRACTION),
@@ -7788,13 +8101,16 @@ function previousTotals(histories, nowMs, journalStart) {
7788
8101
  const openThen = histories.filter((history) => isOpenAt(history, weekAgo));
7789
8102
  return {
7790
8103
  open: openThen.length,
7791
- net: createdIn(histories, weekBefore).length - closingsIn(histories, weekBefore).length,
8104
+ net: createdIn(histories, weekBefore).length - lastingClosingsIn(histories, weekBefore).length,
7792
8105
  ageMedianDays: median(openThen.map((history) => daysBetween(history.createdAt, weekAgo))),
7793
8106
  leadTimeMedianDays: median(leadTimesIn(histories, weekBefore))
7794
8107
  };
7795
8108
  }
7796
8109
  function leadTimesIn(histories, span2) {
7797
- return histories.flatMap((history) => closingsOfIn(history, span2).map((closing) => daysBetween(history.createdAt, closing.at)));
8110
+ return histories.flatMap((history) => {
8111
+ const closing = lastingClosingOfIn(history, span2);
8112
+ return closing === void 0 ? [] : [daysBetween(history.createdAt, closing.at)];
8113
+ });
7798
8114
  }
7799
8115
 
7800
8116
  // src/server/cost-source.ts
@@ -7968,18 +8284,18 @@ function createCostSource(root, home2) {
7968
8284
  const { values: runs, length, generation } = await runsTail.read();
7969
8285
  const inputs = { ...request, runs };
7970
8286
  const keyParts = {
7971
- usage: `${inputs.usage.revision}`,
7972
- runs: `${generation}:${length}`,
7973
- scope: `${snapshotIdOf(inputs.scope.snapshot)}/${inputs.scope.projects.map((project) => project.id).join(",")}`,
8287
+ usage: inputs.usage.revision,
8288
+ runs: [generation, length],
8289
+ scope: [snapshotIdOf(inputs.scope.snapshot), inputs.scope.projects.map((project) => project.id)],
7974
8290
  now: formatLocalDay(inputs.now)
7975
8291
  };
7976
- return costMemos.get(Object.values(keyParts).join("|"), () => costOf2(inputs, places, lookupRepoRoot), inputs.scope.projectId);
8292
+ return costMemos.get(JSON.stringify(keyParts), () => computeCostReport(inputs, places, lookupRepoRoot), inputs.scope.projectId);
7977
8293
  },
7978
8294
  retain: costMemos.retain
7979
8295
  };
7980
8296
  }
7981
- async function costOf2({ usage: { cache, scan }, runs, scope: { projects, projectId }, now }, places, lookupRepoRoot) {
7982
- const buckets = bucketsOf2(cache);
8297
+ async function computeCostReport({ usage: { cache, scan }, runs, scope: { projects, projectId }, now }, places, lookupRepoRoot) {
8298
+ const buckets = usageBucketsOf(cache);
7983
8299
  const repoRoots = projectId === void 0 ? /* @__PURE__ */ new Map() : await resolveRepoRoots(
7984
8300
  lookupRepoRoot,
7985
8301
  [...buckets, ...runs].map((entry) => entry.cwd)
@@ -7992,7 +8308,7 @@ async function costOf2({ usage: { cache, scan }, runs, scope: { projects, projec
7992
8308
  }
7993
8309
  function unreadablePathHasNoProject() {
7994
8310
  }
7995
- function bucketsOf2(cache) {
8311
+ function usageBucketsOf(cache) {
7996
8312
  return Object.values(cache.files).flatMap((entry) => entry.buckets);
7997
8313
  }
7998
8314
  async function resolveRepoRoots(lookupRepoRoot, cwds) {
@@ -8002,7 +8318,7 @@ async function resolveRepoRoots(lookupRepoRoot, cwds) {
8002
8318
 
8003
8319
  // src/server/stats-api.ts
8004
8320
  var REPORT_TTL_MS = 5 * MINUTE_MS;
8005
- var ALL_PROJECTS_TAG = "project:*";
8321
+ var ALL_PROJECTS_TAG = "all-projects";
8006
8322
  var WHOLE_BACKLOG_TAG = "whole-backlog";
8007
8323
  var projectTag = (projectId) => `project:${projectId}`;
8008
8324
  function createStatsApi({ root, readLanguage, now, home: home2, services: { usage, memory, warn: warn2 }, backlog, graphHealth: graphHealth2, journalSources }) {
@@ -8024,7 +8340,7 @@ function createStatsApi({ root, readLanguage, now, home: home2, services: { usag
8024
8340
  const scope = await requestScopeOf(c, await backlogPruningCaches(), { wholeBacklog, readLanguage });
8025
8341
  if (!scope.ok) return scope.response;
8026
8342
  const moment = now();
8027
- const key = [kind, scope.projectId ?? "*", formatLocalDay(moment), sourceKey === void 0 ? "" : await sourceKey(scope.projects, scope.snapshot)].join("|");
8343
+ const key = JSON.stringify([kind, scope.projectId ?? null, formatLocalDay(moment), sourceKey === void 0 ? null : await sourceKey(scope.projects, scope.snapshot)]);
8028
8344
  const tags = wholeBacklog ? [WHOLE_BACKLOG_TAG] : [scope.projectId === void 0 ? ALL_PROJECTS_TAG : projectTag(scope.projectId)];
8029
8345
  const compute = async () => {
8030
8346
  const { journals, contextOf } = await journalSources.read(
@@ -8068,7 +8384,7 @@ function createForgettingReportCache(root, now) {
8068
8384
  let knownProjectIds = [];
8069
8385
  let forgetCount = 0;
8070
8386
  const projectIdOfPath = (path) => {
8071
- const [first] = relative3(root, path).split(sep4);
8387
+ const [first] = relative2(root, path).split(sep3);
8072
8388
  return knownProjectIds.find((id) => id === first);
8073
8389
  };
8074
8390
  const forgetAll = () => {
@@ -8196,8 +8512,13 @@ async function removeProject2(c, id, { root, readLanguage, changeHub }) {
8196
8512
  function revisionEvents(c, changeHub, closed) {
8197
8513
  return streamSSE(c, async (stream) => {
8198
8514
  const stopSending = changeHub.onRevision((revision) => void stream.writeSSE({ event: "change", data: JSON.stringify(revision) }));
8199
- const clientGone = new Promise((resolve7) => stream.onAbort(resolve7));
8200
- await Promise.race([clientGone, closed]);
8515
+ const { promise: ended, resolve: resolve7 } = Promise.withResolvers();
8516
+ const end = () => resolve7();
8517
+ stream.onAbort(end);
8518
+ closed.addEventListener("abort", end);
8519
+ if (closed.aborted) end();
8520
+ await ended;
8521
+ closed.removeEventListener("abort", end);
8201
8522
  stopSending();
8202
8523
  });
8203
8524
  }
@@ -8296,7 +8617,8 @@ function createApp({ root, readLanguage, changes, allowedHosts, home: home2, sta
8296
8617
  }
8297
8618
 
8298
8619
  // src/server/change-feed.ts
8299
- import { join as join29, relative as relative4, sep as sep5 } from "node:path";
8620
+ import { setMaxListeners } from "node:events";
8621
+ import { join as join29, relative as relative3, sep as sep4 } from "node:path";
8300
8622
  import { watch } from "chokidar";
8301
8623
  var CHANGE_DEBOUNCE_MS = 100;
8302
8624
  function createDebouncer(delayMs, run) {
@@ -8310,7 +8632,7 @@ function createDebouncer(delayMs, run) {
8310
8632
  };
8311
8633
  }
8312
8634
  function isHiddenPath(root, path) {
8313
- return relative4(root, path).split(sep5).some((segment) => segment.startsWith("."));
8635
+ return relative3(root, path).split(sep4).some((segment) => segment.startsWith("."));
8314
8636
  }
8315
8637
  async function watchDirectoriesMissedAtStart(watcher, root) {
8316
8638
  const directories = (await listDir(root)).filter((entry) => entry.isDirectory()).map((entry) => join29(root, entry.name));
@@ -8320,7 +8642,8 @@ async function watchDirectoriesMissedAtStart(watcher, root) {
8320
8642
  }
8321
8643
  function createChangeFeed({ root, debounceMs, warn: warn2 }) {
8322
8644
  const listeners = /* @__PURE__ */ new Set();
8323
- const { promise: closed, resolve: markClosed } = Promise.withResolvers();
8645
+ const closing = new AbortController();
8646
+ setMaxListeners(0, closing.signal);
8324
8647
  const changedPaths = /* @__PURE__ */ new Set();
8325
8648
  const debouncer = createDebouncer(debounceMs, () => {
8326
8649
  const paths = [...changedPaths];
@@ -8347,11 +8670,11 @@ function createChangeFeed({ root, debounceMs, warn: warn2 }) {
8347
8670
  listeners.add(listener);
8348
8671
  return () => listeners.delete(listener);
8349
8672
  },
8350
- closed,
8673
+ closed: closing.signal,
8351
8674
  close: async () => {
8352
8675
  debouncer.cancel();
8353
8676
  listeners.clear();
8354
- markClosed();
8677
+ closing.abort();
8355
8678
  await watcher.close();
8356
8679
  }
8357
8680
  };
@@ -8412,7 +8735,7 @@ import { isDeepStrictEqual } from "node:util";
8412
8735
 
8413
8736
  // src/core/usage/transcripts.ts
8414
8737
  import { createHash as createHash6 } from "node:crypto";
8415
- import { basename as basename9, join as join31 } from "node:path";
8738
+ import { basename as basename10, join as join31 } from "node:path";
8416
8739
 
8417
8740
  // src/core/stats/cost/attribute.ts
8418
8741
  import { z as z17 } from "zod";
@@ -8897,8 +9220,8 @@ function pruneStaleBuckets(entries, now) {
8897
9220
  }
8898
9221
  function deletedStillReported(cache, listedFiles, now) {
8899
9222
  const reportStart = statsPeriod(now).from;
8900
- const listedSessions = new Set(Object.keys(listedFiles).map((path) => basename9(path)));
8901
- return Object.fromEntries(Object.entries(cache.files).filter(([path, entry]) => !listedSessions.has(basename9(path)) && entry.buckets.some((bucket) => Date.parse(bucket.slot) >= reportStart)));
9223
+ const listedSessions = new Set(Object.keys(listedFiles).map((path) => basename10(path)));
9224
+ return Object.fromEntries(Object.entries(cache.files).filter(([path, entry]) => !listedSessions.has(basename10(path)) && entry.buckets.some((bucket) => Date.parse(bucket.slot) >= reportStart)));
8902
9225
  }
8903
9226
  async function scanChunk(file, start, chunkSize, { longestReadableLine, now }) {
8904
9227
  if (chunkSize <= 0) return { size: file.size, offset: start.offset, state: start.state, buckets: start.buckets };
@@ -9061,10 +9384,10 @@ async function startServer({ root, port, home: home2, env, platform, log, warn:
9061
9384
  await stopBackground();
9062
9385
  await changes.close();
9063
9386
  await closeServer(server);
9064
- if (pidFile !== void 0) await rm4(pidFile, { force: true });
9387
+ if (pidFile !== void 0) await rm5(pidFile, { force: true });
9065
9388
  };
9066
9389
  if (pidFile !== void 0) {
9067
- await writeFile3(pidFile, String(process.pid)).catch(async (error) => {
9390
+ await writeFile2(pidFile, String(process.pid)).catch(async (error) => {
9068
9391
  await close();
9069
9392
  throw error;
9070
9393
  });
@@ -9145,7 +9468,7 @@ function isFailure(outcome) {
9145
9468
  }
9146
9469
 
9147
9470
  // src/cli/service/launchd.ts
9148
- import { mkdir as mkdir7, rm as rm5, writeFile as writeFile4 } from "node:fs/promises";
9471
+ import { mkdir as mkdir7, rm as rm6, writeFile as writeFile3 } from "node:fs/promises";
9149
9472
  import { dirname as dirname9, join as join33 } from "node:path";
9150
9473
  import { setTimeout as sleep3 } from "node:timers/promises";
9151
9474
 
@@ -9160,7 +9483,7 @@ async function numberRecordedIn(file, pattern, encoding = "utf8") {
9160
9483
  throw error;
9161
9484
  });
9162
9485
  const recorded = pattern.exec(text)?.[1];
9163
- return recorded === void 0 ? null : Number(recorded);
9486
+ return recorded === void 0 ? null : portNumber(recorded);
9164
9487
  }
9165
9488
 
9166
9489
  // src/cli/service/launchd.ts
@@ -9221,7 +9544,7 @@ function launchdManager(context, delay = sleep3) {
9221
9544
  await bootout();
9222
9545
  await mkdir7(dirname9(file), { recursive: true });
9223
9546
  await mkdir7(dirname9(launchdLogPath(context.home)), { recursive: true });
9224
- await writeFile4(file, launchdPlist({ ...context, port }));
9547
+ await writeFile3(file, launchdPlist({ ...context, port }));
9225
9548
  let result = await bootstrap();
9226
9549
  for (let attempt = 1; result.code === PREVIOUS_BOOTOUT_UNFINISHED_CODE && attempt < BOOTSTRAP_RETRY_ATTEMPTS; attempt++) {
9227
9550
  await delay(BOOTSTRAP_RETRY_DELAY_MS);
@@ -9233,7 +9556,7 @@ function launchdManager(context, delay = sleep3) {
9233
9556
  if (!await fileExists(file)) return "absent";
9234
9557
  const { code, output } = await bootout();
9235
9558
  if (code !== 0 && !NOT_LOADED_CODES.has(code)) return { failed: "launchctl bootout", code, output };
9236
- await rm5(file, { force: true });
9559
+ await rm6(file, { force: true });
9237
9560
  return "done";
9238
9561
  },
9239
9562
  async registered() {
@@ -9244,7 +9567,7 @@ function launchdManager(context, delay = sleep3) {
9244
9567
  }
9245
9568
 
9246
9569
  // src/cli/service/startup-folder.ts
9247
- import { mkdir as mkdir8, rm as rm6, writeFile as writeFile5 } from "node:fs/promises";
9570
+ import { mkdir as mkdir8, rm as rm7, writeFile as writeFile4 } from "node:fs/promises";
9248
9571
  import { dirname as dirname10, join as join34, win32 } from "node:path";
9249
9572
  var SCRIPT_NAME = "p-backlog.vbs";
9250
9573
  var COMMAND_LINE_ARGUMENT = /"[^"]*"|\S+/g;
@@ -9314,7 +9637,7 @@ async function stopRunningServer(context) {
9314
9637
  }
9315
9638
  if (identity === "ours") context.stopProcess(pid);
9316
9639
  }
9317
- await rm6(file, { force: true });
9640
+ await rm7(file, { force: true });
9318
9641
  }
9319
9642
  async function processIdentity(context, pid) {
9320
9643
  const query = `(Get-CimInstance Win32_Process -Filter 'ProcessId=${pid}').CommandLine`;
@@ -9340,14 +9663,14 @@ function startupFolderManager(context) {
9340
9663
  await stopRunningServer(context);
9341
9664
  await mkdir8(dirname10(file), { recursive: true });
9342
9665
  await mkdir8(appDataDir(context), { recursive: true });
9343
- await writeFile5(file, `\uFEFF${startupScript({ ...context, port })}`, "utf16le");
9666
+ await writeFile4(file, `\uFEFF${startupScript({ ...context, port })}`, "utf16le");
9344
9667
  const { code, output } = await context.exec("wscript.exe", [file]);
9345
9668
  return code === 0 ? "done" : { failed: "wscript.exe", code, output };
9346
9669
  },
9347
9670
  async uninstall() {
9348
9671
  if (!await fileExists(file)) return "absent";
9349
9672
  await stopRunningServer(context);
9350
- await rm6(file, { force: true });
9673
+ await rm7(file, { force: true });
9351
9674
  return "done";
9352
9675
  },
9353
9676
  async registered() {
@@ -9358,7 +9681,7 @@ function startupFolderManager(context) {
9358
9681
  }
9359
9682
 
9360
9683
  // src/cli/service/systemd.ts
9361
- import { mkdir as mkdir9, rm as rm7, writeFile as writeFile6 } from "node:fs/promises";
9684
+ import { mkdir as mkdir9, rm as rm8, writeFile as writeFile5 } from "node:fs/promises";
9362
9685
  import { dirname as dirname11, join as join35 } from "node:path";
9363
9686
  var SERVICE_NAME = "p-backlog";
9364
9687
  var UNIT = `${SERVICE_NAME}.service`;
@@ -9400,14 +9723,14 @@ function systemdManager(context) {
9400
9723
  logsHint: `journalctl --user -u ${SERVICE_NAME}`,
9401
9724
  async install(port) {
9402
9725
  await mkdir9(dirname11(file), { recursive: true });
9403
- await writeFile6(file, systemdUnit({ ...context, port }));
9726
+ await writeFile5(file, systemdUnit({ ...context, port }));
9404
9727
  return systemctlSteps(context.exec, [["daemon-reload"], ["enable", UNIT], ["restart", UNIT]]);
9405
9728
  },
9406
9729
  async uninstall() {
9407
9730
  if (!await fileExists(file)) return "absent";
9408
9731
  const stopped = await systemctlSteps(context.exec, [["disable", "--now", UNIT]]);
9409
9732
  if (stopped !== "done") return stopped;
9410
- await rm7(file, { force: true });
9733
+ await rm8(file, { force: true });
9411
9734
  return systemctlSteps(context.exec, [["daemon-reload"]]);
9412
9735
  },
9413
9736
  async registered() {
@@ -9438,6 +9761,9 @@ async function servicePort(manager, io) {
9438
9761
  const installed = manager === null ? null : await attemptReportingFailure(manager.file, () => manager.installedPort(), warnUnreadableSkipped(io.warn, io.core));
9439
9762
  return installed ?? envPort(io);
9440
9763
  }
9764
+ function portToInstall(manager, io) {
9765
+ return portUnset(io.env.PORT) ? servicePort(manager, io) : Promise.resolve(envPort(io));
9766
+ }
9441
9767
  function webUiPort(io) {
9442
9768
  return servicePort(platformManager(io.platform, serviceContextOf(io)), io);
9443
9769
  }
@@ -9490,7 +9816,7 @@ async function withServiceManager(io, action) {
9490
9816
  return action(manager, io);
9491
9817
  }
9492
9818
  async function installWith(manager, io) {
9493
- const outcome = await manager.install(envPort(io));
9819
+ const outcome = await manager.install(await portToInstall(manager, io));
9494
9820
  if (isFailure(outcome)) return reportFailure(outcome, io);
9495
9821
  io.print(io.cli.serviceInstalled(manager.file));
9496
9822
  io.print(io.cli.serviceLogs(manager.logsHint));
@@ -9506,7 +9832,7 @@ async function statusWith(manager, io) {
9506
9832
  const port = await servicePort(manager, io);
9507
9833
  const [registered, responding] = await Promise.all([manager.registered(), serverResponds(loopbackOrigin(port), STATUS_TIMEOUT_MS)]);
9508
9834
  io.print(io.cli.serviceStatus(registered, responding, port));
9509
- return EXIT.ok;
9835
+ return registered && responding ? EXIT.ok : EXIT.failed;
9510
9836
  }
9511
9837
  function reportFailure({ failed: failed2, code, output }, io) {
9512
9838
  io.warn(io.cli.serviceCommandFailed(failed2, code, output));
@@ -9536,7 +9862,7 @@ async function writeJsonConfig(path, config) {
9536
9862
  await mkdir10(dirname12(path), { recursive: true });
9537
9863
  const target = await writeTargetOf(path);
9538
9864
  const existing = await statOrNull(target);
9539
- await writeFileAtomic(target, jsonFileText(config), existing === null ? void 0 : existing.mode & 511);
9865
+ await writeJsonFile(target, config, existing === null ? void 0 : existing.mode & 511);
9540
9866
  }
9541
9867
  async function readConfigText(path) {
9542
9868
  try {
@@ -9892,7 +10218,7 @@ function flowForecast(histories, open2, now) {
9892
10218
  const windowWeeks = ageWeeks === null ? FORECAST_WINDOW_WEEKS : clampedWeeks(Math.floor(ageWeeks) + 1);
9893
10219
  const observedWeeks = ageWeeks === null ? FORECAST_WINDOW_WEEKS : clampedWeeks(ageWeeks);
9894
10220
  const window = trailingSpan(now.getTime(), windowWeeks * WEEK_MS);
9895
- const closed = closingsIn(histories, window).length;
10221
+ const closed = lastingClosingsIn(histories, window).length;
9896
10222
  const created = createdIn(histories, window).length;
9897
10223
  const weeklyNet = (closed - created) / observedWeeks;
9898
10224
  const weeks = open2 > 0 && weeklyNet > 0 ? Math.ceil(open2 / weeklyNet) : null;
@@ -9947,7 +10273,7 @@ var statsCommand = {
9947
10273
  async function runStats(args, io) {
9948
10274
  const values = parseOptions(io.language, args, { ...SCOPE_OPTIONS, json: { type: "boolean", default: false } });
9949
10275
  const loaded = await loadBacklog(io.backlogRoot);
9950
- const scope = resolveScope(loaded, io, values);
10276
+ const scope = await resolveScope(loaded, io, values);
9951
10277
  if (scope === null) return EXIT.notFound;
9952
10278
  const { project } = scope;
9953
10279
  const journals = await readJournals(io.backlogRoot, scope.activeIds);
@@ -10005,6 +10331,16 @@ var statusCommand = taskFieldCommand({
10005
10331
  // src/cli/commands/take.ts
10006
10332
  import { realpathSync as realpathSync3 } from "node:fs";
10007
10333
  import { resolve as resolve5 } from "node:path";
10334
+
10335
+ // src/cli/path-inside.ts
10336
+ import { isAbsolute as isAbsolute3, relative as relative4, sep as sep5 } from "node:path";
10337
+ function relativeInside(container, path) {
10338
+ const inside = relative4(container, path);
10339
+ const outside = isAbsolute3(inside) || inside === ".." || inside.startsWith(`..${sep5}`);
10340
+ return outside ? null : inside.split(sep5).join("/");
10341
+ }
10342
+
10343
+ // src/cli/commands/take.ts
10008
10344
  var takeCommand = {
10009
10345
  name: "take",
10010
10346
  usage: (language) => cliMessages(language).takeUsage(),
@@ -10045,7 +10381,7 @@ function takeMode(io, values, positionals) {
10045
10381
  return { kind: "id", id };
10046
10382
  }
10047
10383
  async function takeByPath(loaded, io, path, projectId, { json }) {
10048
- const project = findProjectOrWarn(loaded, io, projectId);
10384
+ const project = await findProjectOrWarn(loaded, io, projectId);
10049
10385
  if (!project) return EXIT.notFound;
10050
10386
  const target = repoRelativePath(io, project, path);
10051
10387
  const index = buildIndex(loaded.tasks);
@@ -10085,7 +10421,7 @@ async function takeAll(loadedTasks, chosen, io) {
10085
10421
  const code = await applyAll(chosen, async (task) => {
10086
10422
  const written = task.status === "in-progress" ? { ok: true, task } : await write(task, { status: "in-progress" });
10087
10423
  if (!written.ok) return written.exitCode;
10088
- tasks = tasksAfterWrite(tasks, written);
10424
+ tasks = withWrittenTasks(tasks, [written]);
10089
10425
  taken.push(written.task);
10090
10426
  return EXIT.ok;
10091
10427
  });
@@ -10096,7 +10432,7 @@ function selectById(loaded, io, id) {
10096
10432
  return task ? { ok: true, task } : { ok: false, exitCode: EXIT.notFound };
10097
10433
  }
10098
10434
  async function selectNext(loaded, io, projectId) {
10099
- const project = findProjectOrWarn(loaded, io, projectId);
10435
+ const project = await findProjectOrWarn(loaded, io, projectId);
10100
10436
  if (!project) return { ok: false, exitCode: EXIT.notFound };
10101
10437
  const index = buildIndex(loaded.tasks);
10102
10438
  const abandoned = pickAbandonedTask(loaded.tasks, project.id, index, await lastTouched(loaded.tasks.filter(isTakenTask)), io.now());
@@ -10157,6 +10493,7 @@ async function verifyOne(id, { loaded, source, write, io }) {
10157
10493
  const project = projectOf(loaded, task);
10158
10494
  const lookup = repoLookup(io);
10159
10495
  const repo = project === void 0 ? void 0 : await findRepo(project, lookup);
10496
+ if (source !== void 0 && repo !== void 0 && await sourcePresenceOrWarn(io, repo, source) === "missing") return EXIT.invalid;
10160
10497
  const target = source ?? await relocatedSource(repo, task);
10161
10498
  const anchored = target ?? task.source;
10162
10499
  const anchor = anchored === void 0 ? void 0 : anchorChange(await sourceAnchor(repo, anchored, lookup.onUnreadable));
@@ -10199,7 +10536,6 @@ var CLI_COMMANDS = [
10199
10536
  serviceCommand
10200
10537
  ];
10201
10538
  var HELP_ARGUMENTS = /* @__PURE__ */ new Set(["help", "--help", "-h"]);
10202
- var COMMAND_HELP_FLAGS = /* @__PURE__ */ new Set(["--help", "-h"]);
10203
10539
  var COMMANDS = new Map(CLI_COMMANDS.map((command2) => [command2.name, command2]));
10204
10540
  async function runCli(argv2, env) {
10205
10541
  const [name, ...args] = argv2;
@@ -10217,13 +10553,13 @@ async function runCli(argv2, env) {
10217
10553
  io.print(usageText(CLI_COMMANDS, language));
10218
10554
  return EXIT.ok;
10219
10555
  }
10220
- if (asksForCommandHelp(args)) {
10221
- io.print(usageText([command2], language));
10222
- return EXIT.ok;
10223
- }
10224
10556
  try {
10225
10557
  return await command2.run(args, io);
10226
10558
  } catch (error) {
10559
+ if (error instanceof HelpRequested) {
10560
+ io.print(usageText([command2], language));
10561
+ return EXIT.ok;
10562
+ }
10227
10563
  if (error instanceof ArgumentsError) {
10228
10564
  io.warn(`${error.message}
10229
10565
  ${usageText([command2], language)}`);
@@ -10238,10 +10574,6 @@ ${usageText([command2], language)}`);
10238
10574
  return failureExit;
10239
10575
  }
10240
10576
  }
10241
- function asksForCommandHelp(args) {
10242
- const optionsEnd = args.indexOf(END_OF_OPTIONS);
10243
- return (optionsEnd === -1 ? args : args.slice(0, optionsEnd)).some((arg) => COMMAND_HELP_FLAGS.has(arg));
10244
- }
10245
10577
  function commandName(argv2) {
10246
10578
  const [name, ...args] = argv2;
10247
10579
  if (name === void 0 || !COMMANDS.has(name)) return "help";