p-backlog 0.13.0 → 0.13.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. package/CHANGELOG.md +60 -0
  2. package/dist/cli.js +1246 -795
  3. package/dist/web/assets/{CodeTab-BokbzP4a.js → CodeTab-DeM399k_.js} +1 -1
  4. package/dist/web/assets/CostTab-BkuP_lKs.js +1 -0
  5. package/dist/web/assets/EffectTab-C6yxsNf4.js +1 -0
  6. package/dist/web/assets/{Figure-CO87y2TD.js → Figure-CVTyKv4y.js} +1 -1
  7. package/dist/web/assets/{OverviewTab-naYN8aXk.js → OverviewTab-B83eJneA.js} +1 -1
  8. package/dist/web/assets/Page-DLaFG3Qi.js +59 -0
  9. package/dist/web/assets/{QualityTab-BMfBa6YW.js → QualityTab-DCMWjXz4.js} +1 -1
  10. package/dist/web/assets/ShareBar-DLIjLhrg.js +1 -0
  11. package/dist/web/assets/StatsPage-Dyu3XyGq.js +1 -0
  12. package/dist/web/assets/StatsTabState-C2YngECB.js +1 -0
  13. package/dist/web/assets/{StatsTable-CqH14eSD.js → StatsTable-4QrI6DcN.js} +1 -1
  14. package/dist/web/assets/UnavailableRepos-BSMfh0t_.js +1 -0
  15. package/dist/web/assets/index-DBSU7e-A.js +2 -0
  16. package/dist/web/assets/start-B7mNnilg.js +42 -0
  17. package/dist/web/assets/{start-DCkTSXpO.css → start-BmSqjxn9.css} +1 -1
  18. package/dist/web/assets/use-grain-panel-CSj1uVOI.js +55 -0
  19. package/dist/web/assets/web-paths-CziYixFT.js +1 -0
  20. package/dist/web/index.html +1 -1
  21. package/package.json +1 -1
  22. package/skill/backlog/SKILL.md +2 -2
  23. package/skill/backlog-en/SKILL.md +1 -1
  24. package/dist/web/assets/CostTab-D91_w1H0.js +0 -1
  25. package/dist/web/assets/EffectTab-CRlWfFF0.js +0 -1
  26. package/dist/web/assets/Page-BHZdQQhE.js +0 -59
  27. package/dist/web/assets/ShareBar-DBiU0f9_.js +0 -1
  28. package/dist/web/assets/StatsPage-Dr1pco7X.js +0 -1
  29. package/dist/web/assets/StatsTabState-CePos7h7.js +0 -1
  30. package/dist/web/assets/UnavailableRepos-BBbuCPNM.js +0 -1
  31. package/dist/web/assets/index-DpWYLB0A.js +0 -2
  32. package/dist/web/assets/start-Cw9zPEW-.js +0 -42
  33. package/dist/web/assets/use-grain-panel-BKTkjTK3.js +0 -55
  34. package/dist/web/assets/web-paths-yWGbLD6t.js +0 -1
package/dist/cli.js CHANGED
@@ -120,12 +120,13 @@ import { z } from "zod";
120
120
  import { randomUUID } from "node:crypto";
121
121
  import { rm as rm2, utimes, writeFile } from "node:fs/promises";
122
122
  import { basename, dirname, join } from "node:path";
123
- import { setTimeout as sleep } from "node:timers/promises";
123
+ import { setTimeout as sleep2 } from "node:timers/promises";
124
124
 
125
125
  // src/core/store/fs-utils.ts
126
126
  import { createHash } from "node:crypto";
127
127
  import { readFileSync, realpathSync } from "node:fs";
128
128
  import { access, lstat, open, readdir, readFile, readlink, rm, stat } from "node:fs/promises";
129
+ import { setTimeout as sleep } from "node:timers/promises";
129
130
  function contentVersion(text) {
130
131
  return createHash("sha1").update(text).digest("hex");
131
132
  }
@@ -228,15 +229,6 @@ async function readAt(handle, position, length) {
228
229
  function readFileAt(path, position, length) {
229
230
  return withFile(path, (handle) => readAt(handle, position, length));
230
231
  }
231
- function parseJson(text, schema) {
232
- try {
233
- const parsed = schema.safeParse(JSON.parse(text));
234
- return parsed.success ? parsed.data : null;
235
- } catch (error) {
236
- if (error instanceof SyntaxError) return null;
237
- throw error;
238
- }
239
- }
240
232
  async function removeIfUnchanged(path, version) {
241
233
  const text = await readTextOrNull(path);
242
234
  if (text === null) return "already-gone";
@@ -252,12 +244,35 @@ async function listDir(path, { recursive = false } = {}) {
252
244
  throw error;
253
245
  }
254
246
  }
247
+ var BLOCKED_RETRY_DELAYS_MS = [10, 20, 40, 80, 160, 320, 640, 1e3, 1e3, 1e3, 1e3];
248
+ var BLOCKED_RETRIES_TOTAL_MS = sum(BLOCKED_RETRY_DELAYS_MS);
249
+ var BLOCKED_CODES = ["EPERM", "EACCES", "EBUSY"];
250
+ async function retryWhileBlockedOnWindows(attempt) {
251
+ if (!onWindows()) return attempt();
252
+ for (const delayMs of BLOCKED_RETRY_DELAYS_MS) {
253
+ try {
254
+ return await attempt();
255
+ } catch (error) {
256
+ if (!blockedOnWindows(error)) throw error;
257
+ await sleep(delayMs);
258
+ }
259
+ }
260
+ return attempt();
261
+ }
262
+ function blockedOnWindows(error) {
263
+ return onWindows() && hasAnyErrorCode(error, BLOCKED_CODES);
264
+ }
265
+ function onWindows() {
266
+ return process.platform === "win32";
267
+ }
255
268
 
256
269
  // src/core/store/file-lock.ts
257
270
  var RETRY_MS = 10;
258
271
  var ABANDONED_AFTER_MS = 3e4;
272
+ var ABANDONED_BREAK_AFTER_MS = 2 * SECOND_MS;
259
273
  var REFRESH_EVERY_MS = ABANDONED_AFTER_MS / 3;
260
274
  var DEFAULT_WAIT_LIMIT_MS = 5e3;
275
+ var REFUSED_AT_LEAST_MS = SECOND_MS;
261
276
  var FileBusyError = class extends Error {
262
277
  constructor(path, lock, seconds) {
263
278
  super(`${path} is locked: ${lock}`);
@@ -270,8 +285,15 @@ var FileBusyError = class extends Error {
270
285
  lock;
271
286
  seconds;
272
287
  };
288
+ var Refusal = class {
289
+ constructor(error) {
290
+ this.error = error;
291
+ }
292
+ error;
293
+ };
273
294
  async function withFileLock(path, action, options = {}) {
274
295
  const held = await acquire(path, options);
296
+ if (held instanceof Refusal) throw held.error;
275
297
  try {
276
298
  return await action();
277
299
  } finally {
@@ -284,54 +306,107 @@ async function withAvailableLocks(paths, action, { waitLimitMs = DEFAULT_WAIT_LI
284
306
  try {
285
307
  for (const path of [...paths].sort()) {
286
308
  try {
287
- held.push(await acquire(path, { waitLimitMs: giveUpAt - Date.now() }));
309
+ const acquired = await acquire(path, { waitLimitMs: giveUpAt - Date.now() });
310
+ if (!(acquired instanceof Refusal)) held.push(acquired);
288
311
  } catch (error) {
289
312
  if (!(error instanceof FileBusyError)) throw error;
290
313
  }
291
314
  }
292
315
  return await action(new Set(held.map(({ path }) => path)));
293
316
  } finally {
294
- for (const lock of held) await release(lock);
317
+ await releaseAll(held);
295
318
  }
296
319
  }
320
+ async function releaseAll(held) {
321
+ const failure = (await Promise.allSettled(held.map(release))).find((result) => result.status === "rejected");
322
+ if (failure !== void 0) throw failure.reason;
323
+ }
297
324
  async function acquire(path, { waitLimitMs = DEFAULT_WAIT_LIMIT_MS }) {
298
325
  const lock = join(dirname(path), `.${basename(path)}.lock`);
299
326
  const token = `${process.pid} ${randomUUID()}`;
300
327
  const giveUpAt = Date.now() + waitLimitMs;
328
+ let streak = null;
301
329
  for (; ; ) {
302
- if (await tryCreate(lock, token)) return { path, lock, token, stopRefreshing: keepRefreshed(lock, token) };
303
- const abandoned = await abandonedToken(lock);
304
- if (abandoned !== null && await breakAbandoned(lock, abandoned)) continue;
305
- if (Date.now() > giveUpAt) throw new FileBusyError(path, lock, waitLimitMs / SECOND_MS);
306
- await sleep(RETRY_MS);
330
+ const created = await tryCreate(lock, token);
331
+ if (created === "created") return { path, lock, token, stopRefreshing: keepRefreshed(lock, token) };
332
+ const holder = await holderOf(lock);
333
+ const abandoned = tokenIfAbandoned(holder, ABANDONED_AFTER_MS);
334
+ if (abandoned !== null && await breakAbandoned(lock, abandoned)) {
335
+ streak = null;
336
+ continue;
337
+ }
338
+ const refusal = refusalBehind(created, holder);
339
+ streak = extended(streak, refusal);
340
+ if (Date.now() > giveUpAt) {
341
+ if (streak !== null && Date.now() - streak.since >= REFUSED_AT_LEAST_MS) return streak.refusal;
342
+ throw new FileBusyError(path, lock, waitLimitMs / SECOND_MS);
343
+ }
344
+ await sleep2(RETRY_MS);
307
345
  }
308
346
  }
347
+ function extended(streak, refusal) {
348
+ return refusal === null ? null : { refusal, since: streak?.since ?? Date.now() };
349
+ }
350
+ function refusalBehind(created, holder) {
351
+ if (holder instanceof Refusal) return holder;
352
+ return holder === null && created instanceof Refusal ? created : null;
353
+ }
309
354
  async function tryCreate(lock, token) {
310
355
  try {
311
356
  await writeFile(lock, token, { flag: "wx" });
312
- return true;
357
+ return "created";
313
358
  } catch (error) {
314
- if (hasErrorCode(error, "EEXIST")) return false;
359
+ if (hasErrorCode(error, "EEXIST")) return "exists";
360
+ if (deletePendingOnWindows(error)) return new Refusal(error);
315
361
  throw error;
316
362
  }
317
363
  }
318
- async function abandonedToken(lock) {
319
- const token = await readTextOrNull(lock);
320
- if (token === null) return null;
321
- const info = await statOrNull(lock);
322
- return info !== null && Date.now() - info.mtimeMs > ABANDONED_AFTER_MS ? token : null;
364
+ function deletePendingOnWindows(error) {
365
+ return onWindows() && hasErrorCode(error, "EPERM");
366
+ }
367
+ async function holderOf(path) {
368
+ try {
369
+ const token = await readTextOrNull(path);
370
+ if (token === null) return null;
371
+ const info = await statOrNull(path);
372
+ return info === null ? null : { token, changedAt: info.mtimeMs };
373
+ } catch (error) {
374
+ if (blockedOnWindows(error)) return new Refusal(error);
375
+ throw error;
376
+ }
377
+ }
378
+ function tokenIfAbandoned(holder, abandonedAfterMs) {
379
+ if (holder === null || holder instanceof Refusal) return null;
380
+ return Date.now() - holder.changedAt > abandonedAfterMs ? holder.token : null;
381
+ }
382
+ async function abandonedToken(path, abandonedAfterMs) {
383
+ return tokenIfAbandoned(await holderOf(path), abandonedAfterMs);
323
384
  }
324
385
  async function breakAbandoned(lock, abandoned) {
325
386
  const breaker = `${lock}.break`;
326
- if (!await tryCreate(breaker, abandoned)) {
327
- if (await abandonedToken(breaker) !== null) await rm2(breaker, { force: true });
387
+ if (await tryCreate(breaker, abandoned) !== "created") {
388
+ if (await abandonedToken(breaker, ABANDONED_BREAK_AFTER_MS) !== null) await removeUnlessBlocked(breaker);
328
389
  return false;
329
390
  }
330
391
  try {
331
- if (await abandonedToken(lock) === abandoned) await rm2(lock, { force: true });
332
- return true;
392
+ if (await abandonedToken(lock, ABANDONED_AFTER_MS) !== abandoned) return false;
393
+ return await removeUnlessBlocked(lock);
333
394
  } finally {
334
- await rm2(breaker, { force: true });
395
+ await removeUnlessBlocked(breaker);
396
+ }
397
+ }
398
+ function removeUnlessBlocked(path) {
399
+ return orWhenBlocked(
400
+ rm2(path, { force: true }).then(() => true),
401
+ false
402
+ );
403
+ }
404
+ async function orWhenBlocked(work, fallback) {
405
+ try {
406
+ return await work;
407
+ } catch (error) {
408
+ if (blockedOnWindows(error)) return fallback;
409
+ throw error;
335
410
  }
336
411
  }
337
412
  function keepRefreshed(lock, token) {
@@ -361,33 +436,11 @@ async function refreshIfHeld(lock, token) {
361
436
  }
362
437
  async function release({ lock, token, stopRefreshing }) {
363
438
  await stopRefreshing();
364
- if (await readTextOrNull(lock) === token) await rm2(lock, { force: true });
365
- }
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+" }
439
+ await orWhenBlocked(
440
+ retryWhileBlockedOnWindows(async () => {
441
+ if (await readTextOrNull(lock) === token) await rm2(lock, { force: true });
442
+ }),
443
+ void 0
391
444
  );
392
445
  }
393
446
 
@@ -395,46 +448,35 @@ async function appendJsonLines(path, values) {
395
448
  import { randomUUID as randomUUID2 } from "node:crypto";
396
449
  import { chmod, link, rename, rm as rm3 } from "node:fs/promises";
397
450
  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);
451
+ async function writeFileAtomic(path, content, options) {
452
+ await viaTemporaryFile(path, content, (temporary) => replaceFile(temporary, path), { ...options, durable: true });
404
453
  }
405
- async function replacePrefixAtomic(path, prefix, content) {
454
+ async function writeRecomputableFileAtomic(path, content) {
455
+ await viaTemporaryFile(path, content, (temporary) => replaceFile(temporary, path), { durable: false, onErrorAfterPublish: rethrow });
456
+ }
457
+ async function replacePrefixAtomic(path, prefix, content, options) {
406
458
  let seen = prefix;
407
459
  const carryAppended = async (temporary) => {
408
460
  const live = await readBytesOrNull(path) ?? Buffer.alloc(0);
409
461
  if (!startsWithBytes(live, seen)) return false;
410
- if (live.length > seen.length) await writeSynced(temporary, live.subarray(seen.length), "a");
462
+ if (live.length > seen.length) await writeTemporary(temporary, live.subarray(seen.length), { flags: "a", durable: true });
411
463
  seen = live;
412
464
  return true;
413
465
  };
414
- return viaTemporaryFile(path, content, (temporary) => replaceFile(temporary, path, () => carryAppended(temporary)));
466
+ return viaTemporaryFile(path, content, (temporary) => replaceFile(temporary, path, () => carryAppended(temporary)), { ...options, durable: true });
415
467
  }
416
468
  function startsWithBytes(bytes, prefix) {
417
469
  return bytes.length >= prefix.length && bytes.subarray(0, prefix.length).equals(prefix);
418
470
  }
419
- async function replaceFile(temporary, path, prepareRename = async () => true) {
420
- const attempt = async () => {
471
+ async function replaceFile(temporary, path, prepareRename = () => Promise.resolve(true)) {
472
+ return retryWhileBlockedOnWindows(async () => {
421
473
  if (!await prepareRename()) return false;
422
474
  await rename(temporary, path);
423
475
  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();
476
+ });
435
477
  }
436
- async function createFileAtomic(path, content) {
437
- await viaTemporaryFile(path, content, (temporary) => link(temporary, path));
478
+ async function createFileAtomic(path, content, options) {
479
+ await viaTemporaryFile(path, content, (temporary) => link(temporary, path), { ...options, durable: true });
438
480
  }
439
481
  var TEMPORARY_FILE = /^\..+\.[0-9a-f-]{36}\.tmp$/;
440
482
  async function removeTemporariesBefore(dir, cutoff) {
@@ -448,37 +490,97 @@ async function removeTemporariesBefore(dir, cutoff) {
448
490
  function temporaryPathFor(path) {
449
491
  return join2(dirname2(path), `.${basename2(path)}.${randomUUID2()}.tmp`);
450
492
  }
451
- async function viaTemporaryFile(path, content, publish, mode) {
493
+ async function viaTemporaryFile(path, content, publish, { mode, durable, onErrorAfterPublish }) {
452
494
  const temporary = temporaryPathFor(path);
495
+ const reportAfterPublish = (error) => onErrorAfterPublish(path, error);
496
+ let publishReturned = false;
453
497
  try {
454
- await writeSynced(temporary, content, "w", mode);
498
+ await writeTemporary(temporary, content, { flags: "w", mode, durable });
455
499
  if (mode !== void 0) await chmod(temporary, mode);
456
- const published = await publish(temporary);
457
- await syncDirectoryOf(path);
458
- return published;
500
+ const result = await publish(temporary);
501
+ publishReturned = true;
502
+ if (durable) await syncParentDirectory(path).catch(reportAfterPublish);
503
+ return result;
459
504
  } finally {
460
- await rm3(temporary, { force: true });
505
+ await rm3(temporary, { force: true }).catch(publishReturned ? reportAfterPublish : keepPublishFailure);
461
506
  }
462
507
  }
463
- async function writeSynced(path, data, flags, mode) {
508
+ function keepPublishFailure() {
509
+ }
510
+ async function writeTemporary(path, data, { flags, mode, durable }) {
464
511
  await withFile(
465
512
  path,
466
513
  async (handle) => {
467
514
  await handle.writeFile(data, "utf8");
468
- await handle.sync();
515
+ if (durable) await handle.sync();
469
516
  },
470
517
  { flags, mode }
471
518
  );
472
519
  }
473
520
  var DIRECTORY_SYNC_UNSUPPORTED_CODES = ["EINVAL", "ENOTSUP", "EISDIR", "EACCES", "EPERM"];
474
- async function syncDirectoryOf(path) {
475
- if (process.platform === "win32") return;
521
+ async function syncParentDirectory(path) {
522
+ if (onWindows()) return;
476
523
  try {
477
524
  await withFile(dirname2(path), (directory) => directory.sync());
478
525
  } catch (error) {
479
526
  if (!hasAnyErrorCode(error, DIRECTORY_SYNC_UNSUPPORTED_CODES)) throw error;
480
527
  }
481
528
  }
529
+ function rethrow(_path, error) {
530
+ throw error;
531
+ }
532
+
533
+ // src/core/store/json-file.ts
534
+ var JSON_INDENT = 2;
535
+ function parseJson(text, schema) {
536
+ try {
537
+ const parsed = schema.safeParse(JSON.parse(text));
538
+ return parsed.success ? parsed.data : null;
539
+ } catch (error) {
540
+ if (error instanceof SyntaxError) return null;
541
+ throw error;
542
+ }
543
+ }
544
+ function jsonFileText(value) {
545
+ return `${JSON.stringify(value, null, JSON_INDENT)}
546
+ `;
547
+ }
548
+ async function readJsonFile(path, schema) {
549
+ const text = await readTextOrNull(path);
550
+ return text === null ? null : parseJson(text, schema);
551
+ }
552
+ async function writeJsonFile(path, value, options) {
553
+ await writeFileAtomic(path, jsonFileText(value), options);
554
+ }
555
+
556
+ // src/core/store/json-lines.ts
557
+ function parseJsonLines(text, schema) {
558
+ const parsed = text.split("\n").filter((line) => line.trim() !== "").map((line) => parseJson(line, schema));
559
+ const values = parsed.filter((value) => value !== null);
560
+ return { values, invalidLines: parsed.length - values.length };
561
+ }
562
+ async function readJsonLines(path, schema) {
563
+ const text = await readTextOrNull(path) ?? "";
564
+ return parseJsonLines(text, schema);
565
+ }
566
+ function toJsonLines(values) {
567
+ return values.map((value) => `${JSON.stringify(value)}
568
+ `).join("");
569
+ }
570
+ async function appendJsonLines(path, values) {
571
+ const startedEmpty = await withFile(
572
+ path,
573
+ async (handle) => {
574
+ const { size } = await handle.stat();
575
+ const endsMidLine = size > 0 && (await readAt(handle, size - 1, 1))[0] !== NEWLINE;
576
+ await handle.appendFile((endsMidLine ? "\n" : "") + toJsonLines(values), "utf8");
577
+ await handle.sync();
578
+ return size === 0;
579
+ },
580
+ { flags: "a+" }
581
+ );
582
+ if (startedEmpty) await syncParentDirectory(path);
583
+ }
482
584
 
483
585
  // src/core/model/history-window.ts
484
586
  var STATS_WEEKS = 12;
@@ -506,22 +608,22 @@ async function appendRun(root, run) {
506
608
  const path = join3(root, RUNS_FILE);
507
609
  await withFileLock(path, () => appendJsonLines(path, [run]));
508
610
  }
509
- async function trimRuns(root, now) {
611
+ async function trimRuns(root, { now, onError }) {
510
612
  const path = join3(root, RUNS_FILE);
511
613
  return withFileLock(path, async () => {
512
614
  const { values: runs, invalidLines } = await readJsonLines(path, cliRunSchema);
513
615
  const cutoff = retainedSince(now);
514
616
  const kept = runs.filter((run) => Date.parse(run.at) >= cutoff);
515
617
  const removed = runs.length - kept.length + invalidLines;
516
- if (removed > 0) await writeFileAtomic(path, toJsonLines(kept));
618
+ if (removed > 0) await writeFileAtomic(path, toJsonLines(kept), { onErrorAfterPublish: onError });
517
619
  return removed;
518
620
  });
519
621
  }
520
- async function trimRunsWhenStale(root, now) {
622
+ async function trimRunsWhenStale(root, writes) {
521
623
  const first = await firstRun(join3(root, RUNS_FILE));
522
- const staleBefore = retainedSince(now) - STALE_RUN_SLACK_DAYS * DAY_MS;
624
+ const staleBefore = retainedSince(writes.now) - STALE_RUN_SLACK_DAYS * DAY_MS;
523
625
  const needsTrim = first.kind === "unparsable" || first.kind === "run" && first.at < staleBefore;
524
- return needsTrim ? trimRuns(root, now) : 0;
626
+ return needsTrim ? trimRuns(root, writes) : 0;
525
627
  }
526
628
  var NO_RUN = { kind: "none" };
527
629
  async function firstRun(path) {
@@ -535,7 +637,7 @@ async function firstRunIn(handle) {
535
637
  }
536
638
 
537
639
  // src/core/store/paths.ts
538
- import { basename as basename3, dirname as dirname3, join as join4, resolve } from "node:path";
640
+ import { basename as basename3, dirname as dirname3, isAbsolute, join as join4, relative, resolve, sep } from "node:path";
539
641
  var PROJECT_FILE = "project.md";
540
642
  var PID_FILE_ENV = "P_BACKLOG_PID_FILE";
541
643
  var HOME_PREFIX = /^~[\\/]/;
@@ -557,6 +659,11 @@ function projectDir(root, id) {
557
659
  const isPlainName = id !== "" && id !== "." && id !== ".." && basename3(id) === id && !id.includes("\\");
558
660
  return isPlainName ? join4(root, id) : null;
559
661
  }
662
+ function relativeInside(container, path) {
663
+ const inside = relative(container, path);
664
+ const outside = isAbsolute(inside) || inside === ".." || inside.startsWith(`..${sep}`);
665
+ return outside ? null : inside.split(sep).join("/");
666
+ }
560
667
 
561
668
  // src/core/store/settings.ts
562
669
  import { mkdir as mkdir2 } from "node:fs/promises";
@@ -575,22 +682,87 @@ function localeOf(language) {
575
682
  import { z as z2 } from "zod";
576
683
  var settingsSchema = z2.object({ language: z2.enum(LANGUAGES) });
577
684
 
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
- `;
685
+ // src/core/store/load.ts
686
+ import { basename as basename4, join as join5 } from "node:path";
687
+
688
+ // src/core/model/checklist.ts
689
+ var ITEM = /^\s*[-*+]\s+\[(?<mark>[ xX])\]\s+(?<text>.*)$/;
690
+ var FENCE = /^\s{0,3}(?<fence>`{3,}|~{3,})/;
691
+ function checklistItems(body) {
692
+ const items = [];
693
+ let openFence = null;
694
+ for (const [line, content] of body.split("\n").entries()) {
695
+ const fence = FENCE.exec(content)?.groups?.fence;
696
+ if (fence !== void 0) {
697
+ if (openFence === null) openFence = fence;
698
+ else if (fence.startsWith(openFence)) openFence = null;
699
+ continue;
700
+ }
701
+ if (openFence !== null) continue;
702
+ const groups = ITEM.exec(content)?.groups;
703
+ if (groups) items.push({ line, checked: groups.mark !== " ", text: groups.text ?? "" });
704
+ }
705
+ return items;
583
706
  }
584
- async function readJsonFile(path, schema) {
585
- const text = await readTextOrNull(path);
586
- return text === null ? null : parseJson(text, schema);
707
+
708
+ // src/core/model/graph.ts
709
+ var NO_UNLOADED_TASKS = /* @__PURE__ */ new Map();
710
+ var CLOSED_STATUSES = ["done", "cancelled"];
711
+ function isClosed(status) {
712
+ return CLOSED_STATUSES.some((closed) => closed === status);
587
713
  }
588
- async function writeJsonFile(path, value, mode) {
589
- await writeFileAtomic(path, jsonFileText(value), mode);
714
+ function buildIndex(tasks, notLoaded) {
715
+ const byId = /* @__PURE__ */ new Map();
716
+ const dependentsOf = /* @__PURE__ */ new Map();
717
+ const relatedFrom = /* @__PURE__ */ new Map();
718
+ const childrenOf = /* @__PURE__ */ new Map();
719
+ for (const task of tasks) {
720
+ byId.set(task.id, task);
721
+ for (const blockerId of task.blockedBy) appendTo(dependentsOf, blockerId, task);
722
+ for (const relatedId of task.related) appendTo(relatedFrom, relatedId, task);
723
+ if (task.epic !== void 0) appendTo(childrenOf, task.epic, task);
724
+ }
725
+ return { byId, dependentsOf, relatedFrom, childrenOf, notLoaded };
726
+ }
727
+ function openBlockers(task, index) {
728
+ return existingTasks(task.blockedBy, index).filter((blocker) => !isClosed(blocker.status));
729
+ }
730
+ function isBlocked(task, index) {
731
+ return openBlockers(task, index).length > 0;
732
+ }
733
+ function missingReferences(task, index) {
734
+ return [.../* @__PURE__ */ new Set([...task.blockedBy, ...task.related])].filter((id) => !index.byId.has(id));
735
+ }
736
+ function dependentTasks(task, index) {
737
+ return index.dependentsOf.get(task.id) ?? [];
738
+ }
739
+ function relatedTasks(task, index) {
740
+ const both = [...existingTasks(task.related, index), ...index.relatedFrom.get(task.id) ?? []];
741
+ return [...new Map(both.filter((other) => other.id !== task.id).map((other) => [other.id, other])).values()];
742
+ }
743
+ function epicChildren(epic, index) {
744
+ return index.childrenOf.get(epic.id) ?? [];
745
+ }
746
+ function taskProgress(task, index) {
747
+ if (task.status === "done") return 100;
748
+ if (task.type === "epic") {
749
+ const active = epicChildren(task, index).filter((child) => child.status !== "cancelled");
750
+ return active.length === 0 ? null : percent(active.filter((child) => child.status === "done").length, active.length);
751
+ }
752
+ const items = checklistItems(task.body);
753
+ return items.length === 0 ? null : percent(items.filter((item) => item.checked).length, items.length);
754
+ }
755
+ function existingTasks(ids, index) {
756
+ return ids.flatMap((id) => index.byId.get(id) ?? []);
757
+ }
758
+ function appendTo(map, key, task) {
759
+ const list = map.get(key);
760
+ if (list) list.push(task);
761
+ else map.set(key, [task]);
762
+ }
763
+ function percent(part, total) {
764
+ return Math.round(part / total * 100);
590
765
  }
591
-
592
- // src/core/store/load.ts
593
- import { basename as basename4, join as join5 } from "node:path";
594
766
 
595
767
  // src/core/model/ids.ts
596
768
  var ID_PATTERN = /^[A-Z][A-Z0-9]{0,9}-[1-9]\d*$/;
@@ -663,6 +835,11 @@ function schemaIssue({ input, ...issue }) {
663
835
  return issue.code === "invalid_type" ? { kind: "zod", issue, receivedType: z3.core.util.parsedType(input) } : { kind: "zod", issue };
664
836
  }
665
837
 
838
+ // src/core/model/body.ts
839
+ function normalizedBody(body) {
840
+ return body.replace(/^\n+/, "").trimEnd();
841
+ }
842
+
666
843
  // src/core/model/frontmatter.ts
667
844
  var DELIMITER = "---";
668
845
  function parseFrontmatter(text, schema) {
@@ -691,7 +868,7 @@ function stringifyFrontmatter(data, body) {
691
868
  }
692
869
  });
693
870
  const yamlText = document.toString({ lineWidth: 0, flowCollectionPadding: false });
694
- const content = body.replace(/^\n+/, "").trimEnd();
871
+ const content = normalizedBody(body);
695
872
  return content === "" ? `${DELIMITER}
696
873
  ${yamlText}${DELIMITER}
697
874
  ` : `${DELIMITER}
@@ -764,7 +941,7 @@ var LIST_ITEM = /^\s*-\s+(.*)$/;
764
941
  var TRAILING_COMMENT = /\s+#.*$/;
765
942
  var ENCLOSING_BRACKETS = /^[\s[]+|[\s\]]+$/g;
766
943
  var QUOTED = /^(["'])(.*)\1$/;
767
- function reposOfUnparsed(text) {
944
+ function claimedReposOf(text) {
768
945
  const lines = text.split(/\r?\n/);
769
946
  const keyAt = lines.findIndex((line) => REPOS_KEY.test(line));
770
947
  if (keyAt === -1) return [];
@@ -805,19 +982,33 @@ async function parseDocumentOrNull(path, parse2) {
805
982
  }
806
983
  async function readDocumentOrNull(path) {
807
984
  const bytes = await readBytesOrNull(path);
808
- if (bytes === null) return null;
985
+ return bytes === null ? null : documentOf(bytes);
986
+ }
987
+ function documentOf(bytes) {
809
988
  return isUtf8(bytes) ? { ok: true, value: bytes.toString("utf8") } : { ok: false, problems: [{ code: "not-utf8" }] };
810
989
  }
811
990
 
812
991
  // src/core/store/load.ts
813
992
  function unparsedTasks(errors) {
814
- return errors.flatMap(({ path, projectId }) => {
815
- const id = basename4(path, ".md");
816
- return ID_PATTERN.test(id) ? [{ projectId, id }] : [];
817
- });
993
+ return errors.flatMap((error) => error.fileKind === "task" ? [{ projectId: error.projectId, id: taskIdOfFile(error.path) }] : []);
994
+ }
995
+ function isProjectFileError(error) {
996
+ return error.fileKind === "project";
818
997
  }
819
998
  function unparsedProjectFiles(errors) {
820
- return errors.filter((error) => basename4(error.path) === PROJECT_FILE);
999
+ return errors.filter(isProjectFileError);
1000
+ }
1001
+ function unparsedProjectFileOf(errors, projectId) {
1002
+ return unparsedProjectFiles(errors).find((error) => error.projectId === projectId);
1003
+ }
1004
+ function notLoadedTasks(errors) {
1005
+ return new Map(errors.flatMap((error) => error.fileKind === "task" ? [[taskIdOfFile(error.path), "task"]] : error.hiddenTasks.map((id) => [id, "project"])));
1006
+ }
1007
+ function indexOfLoaded({ tasks, errors }) {
1008
+ return buildIndex(tasks, notLoadedTasks(errors));
1009
+ }
1010
+ function taskIdOfFile(path) {
1011
+ return basename4(path, ".md");
821
1012
  }
822
1013
  async function projectDirNames(root) {
823
1014
  return (await listDir(root)).filter((entry) => entry.isDirectory() && !entry.name.startsWith(".")).map((entry) => entry.name);
@@ -832,15 +1023,21 @@ async function loadBacklog(root) {
832
1023
  }
833
1024
  async function loadProjectDir(dir, projectId) {
834
1025
  const projectPath = join5(dir, PROJECT_FILE);
835
- const project = await parseDocumentOrNull(projectPath, (text) => parseProjectFile(text, { id: projectId, path: projectPath }));
836
- if (project === null) return { projects: [], tasks: [], errors: [] };
837
- if (!project.ok) return { projects: [], tasks: [], errors: [{ path: projectPath, projectId, problems: project.problems }] };
1026
+ const bytes = await readBytesOrNull(projectPath);
1027
+ if (bytes === null) return { projects: [], tasks: [], errors: [] };
1028
+ const document = documentOf(bytes);
1029
+ const project = document.ok ? parseProjectFile(document.value, { id: projectId, path: projectPath }) : document;
1030
+ if (!project.ok) {
1031
+ const hiddenTasks = [...await taskIdsOnDisk(dir)].sort(compareIds);
1032
+ const claimedRepos = claimedReposOf(bytes.toString("utf8"));
1033
+ return { projects: [], tasks: [], errors: [{ path: projectPath, projectId, fileKind: "project", problems: project.problems, hiddenTasks, claimedRepos }] };
1034
+ }
838
1035
  const taskPaths = (await taskFileNames(dir)).map((name) => join5(dir, name));
839
1036
  const loaded = await Promise.all(taskPaths.map(async (path) => ({ path, result: await loadTaskFile(path, project.value) })));
840
1037
  return {
841
1038
  projects: [project.value],
842
1039
  tasks: loaded.flatMap(({ result }) => result?.ok ? [result.value] : []),
843
- errors: loaded.flatMap(({ path, result }) => result && !result.ok ? [{ path, projectId, problems: result.problems }] : [])
1040
+ errors: loaded.flatMap(({ path, result }) => result && !result.ok ? [{ path, projectId, fileKind: "task", problems: result.problems }] : [])
844
1041
  };
845
1042
  }
846
1043
  async function loadTaskFile(path, project) {
@@ -874,14 +1071,14 @@ async function readSettingsFile(root) {
874
1071
  const settings = parseJson(text, settingsSchema);
875
1072
  return settings === null ? { found: true, valid: false } : { found: true, valid: true, settings };
876
1073
  }
877
- async function writeSettings(root, settings) {
1074
+ async function writeSettings(root, settings, onError) {
878
1075
  await mkdir2(root, { recursive: true });
879
- await writeJsonFile(settingsFilePath(root), settings);
1076
+ await writeJsonFile(settingsFilePath(root), settings, { onErrorAfterPublish: onError });
880
1077
  }
881
1078
  var LANGUAGE_OF_BACKLOGS_BEFORE_SETTINGS = "ru";
882
- async function settleLanguage(root, env) {
1079
+ async function settleLanguage(root, env, onError) {
883
1080
  const { language, source } = await decideLanguage(root, env);
884
- const saveFailure = source === "unset" ? await saveLanguageOrFailure(root, language) : null;
1081
+ const saveFailure = source === "unset" ? await saveLanguageOrFailure(root, language, onError) : null;
885
1082
  return { language, invalidSettingsFile: source === "invalid-settings", saveFailure };
886
1083
  }
887
1084
  async function readLanguageOrLocale(root, env, onUnreadable) {
@@ -897,9 +1094,9 @@ async function decideLanguage(root, env) {
897
1094
  if (!file.found) return { language: await hasProjects(root) ? LANGUAGE_OF_BACKLOGS_BEFORE_SETTINGS : localeLanguage(env), source: "unset" };
898
1095
  return file.valid ? { language: file.settings.language, source: "settings" } : { language: localeLanguage(env), source: "invalid-settings" };
899
1096
  }
900
- async function saveLanguageOrFailure(root, language) {
1097
+ async function saveLanguageOrFailure(root, language, onError) {
901
1098
  try {
902
- await writeSettings(root, { language });
1099
+ await writeSettings(root, { language }, onError);
903
1100
  return null;
904
1101
  } catch (error) {
905
1102
  return errorText(error);
@@ -1195,6 +1392,9 @@ function schemaIssue2(issue) {
1195
1392
  return zodIssueText(zodEn, issue);
1196
1393
  }
1197
1394
  }
1395
+ var unsafeRepo = (repo, trustCommand) => ({ reason: `git does not trust ${repo} (the directory belongs to another user)`, fix: `Fix: ${trustCommand}` });
1396
+ var UNPARSED_FILE = { task: "its file", project: "its project file" };
1397
+ var taskNotLoaded = (id, file) => `${id} is not loaded: ${UNPARSED_FILE[file]} could not be parsed`;
1198
1398
  function problem(p) {
1199
1399
  switch (p.code) {
1200
1400
  case "self-block":
@@ -1213,6 +1413,8 @@ function problem(p) {
1213
1413
  return "a task cannot be its own epic";
1214
1414
  case "epic-missing":
1215
1415
  return `epic ${p.epic} not found`;
1416
+ case "epic-unparsed":
1417
+ return `epic ${p.epic} is not loaded: ${UNPARSED_FILE[p.fileKind]} could not be parsed`;
1216
1418
  case "epic-not-epic":
1217
1419
  return `${p.epic} is not an epic`;
1218
1420
  case "epic-foreign-project":
@@ -1223,6 +1425,8 @@ function problem(p) {
1223
1425
  return `the epic closes on its own once all its tasks are closed \u2014 close the open ones first: ${p.children.join(", ")}`;
1224
1426
  case "reference-missing":
1225
1427
  return `${p.id} not found`;
1428
+ case "reference-unparsed":
1429
+ return taskNotLoaded(p.id, p.fileKind);
1226
1430
  case "not-utf8":
1227
1431
  return "the file is not UTF-8 \u2014 the backlog leaves it untouched until it is re-saved as UTF-8";
1228
1432
  case "no-frontmatter":
@@ -1273,8 +1477,10 @@ function checkProblem(p) {
1273
1477
  return `Project ${p.projectId}: none of the repos paths exist (${p.repos.join(", ")}) \u2014 its tasks' code cannot be checked`;
1274
1478
  case "project-repo-not-git":
1275
1479
  return `Project ${p.projectId}: ${p.repo} is not a git repository \u2014 commits and code edits of its tasks are not checked`;
1276
- case "project-repo-unsafe":
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}"`;
1480
+ case "project-repo-unsafe": {
1481
+ const { reason, fix } = unsafeRepo(p.repo, p.trustCommand);
1482
+ return `Project ${p.projectId}: ${reason} \u2014 commits and code edits of its tasks are not checked. ${fix}`;
1483
+ }
1278
1484
  case "project-history-unreadable":
1279
1485
  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
1486
  case "project-branches-unreadable":
@@ -1302,6 +1508,8 @@ var coreEn = {
1302
1508
  languageName: "English",
1303
1509
  problem,
1304
1510
  problems,
1511
+ taskNotLoaded,
1512
+ unsafeRepo,
1305
1513
  schemaIssue: schemaIssue2,
1306
1514
  ...labelLookups(LABELS),
1307
1515
  count,
@@ -1448,6 +1656,10 @@ function schemaIssue3(issue) {
1448
1656
  return zodIssueText(zodRu, issue);
1449
1657
  }
1450
1658
  }
1659
+ var unsafeRepo2 = (repo, trustCommand) => ({ reason: `git \u043D\u0435 \u0434\u043E\u0432\u0435\u0440\u044F\u0435\u0442 ${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)`, fix: `\u0418\u0441\u043F\u0440\u0430\u0432\u043B\u0435\u043D\u0438\u0435: ${trustCommand}` });
1660
+ var UNPARSED_FILE_OF_TASK = { task: "\u0435\u0451 \u0444\u0430\u0439\u043B", project: "\u0444\u0430\u0439\u043B \u0435\u0451 \u043F\u0440\u043E\u0435\u043A\u0442\u0430" };
1661
+ var UNPARSED_FILE_OF_EPIC = { task: "\u0435\u0433\u043E \u0444\u0430\u0439\u043B", project: "\u0444\u0430\u0439\u043B \u0435\u0433\u043E \u043F\u0440\u043E\u0435\u043A\u0442\u0430" };
1662
+ var taskNotLoaded2 = (id, file) => `${id} \u043D\u0435 \u0437\u0430\u0433\u0440\u0443\u0436\u0435\u043D\u0430: \u043D\u0435 \u0440\u0430\u0437\u043E\u0431\u0440\u0430\u043D ${UNPARSED_FILE_OF_TASK[file]}`;
1451
1663
  function problem2(p) {
1452
1664
  switch (p.code) {
1453
1665
  case "self-block":
@@ -1466,6 +1678,8 @@ function problem2(p) {
1466
1678
  return "\u0437\u0430\u0434\u0430\u0447\u0430 \u043D\u0435 \u043C\u043E\u0436\u0435\u0442 \u0431\u044B\u0442\u044C \u0441\u0432\u043E\u0438\u043C \u044D\u043F\u0438\u043A\u043E\u043C";
1467
1679
  case "epic-missing":
1468
1680
  return `\u044D\u043F\u0438\u043A ${p.epic} \u043D\u0435 \u043D\u0430\u0439\u0434\u0435\u043D`;
1681
+ case "epic-unparsed":
1682
+ return `\u044D\u043F\u0438\u043A ${p.epic} \u043D\u0435 \u0437\u0430\u0433\u0440\u0443\u0436\u0435\u043D: \u043D\u0435 \u0440\u0430\u0437\u043E\u0431\u0440\u0430\u043D ${UNPARSED_FILE_OF_EPIC[p.fileKind]}`;
1469
1683
  case "epic-not-epic":
1470
1684
  return `${p.epic} \u043D\u0435 \u044F\u0432\u043B\u044F\u0435\u0442\u0441\u044F \u044D\u043F\u0438\u043A\u043E\u043C`;
1471
1685
  case "epic-foreign-project":
@@ -1476,6 +1690,8 @@ function problem2(p) {
1476
1690
  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(", ")}`;
1477
1691
  case "reference-missing":
1478
1692
  return `${p.id} \u043D\u0435 \u043D\u0430\u0439\u0434\u0435\u043D\u0430`;
1693
+ case "reference-unparsed":
1694
+ return taskNotLoaded2(p.id, p.fileKind);
1479
1695
  case "not-utf8":
1480
1696
  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";
1481
1697
  case "no-frontmatter":
@@ -1526,8 +1742,10 @@ function checkProblem2(p) {
1526
1742
  return `\u041F\u0440\u043E\u0435\u043A\u0442 ${p.projectId}: \u043D\u0438 \u043E\u0434\u0438\u043D \u043F\u0443\u0442\u044C \u0438\u0437 repos \u043D\u0435 \u0441\u0443\u0449\u0435\u0441\u0442\u0432\u0443\u0435\u0442 (${p.repos.join(", ")}) \u2014 \u043A\u043E\u0434 \u0435\u0433\u043E \u0437\u0430\u0434\u0430\u0447 \u043D\u0435 \u043F\u0440\u043E\u0432\u0435\u0440\u0438\u0442\u044C`;
1527
1743
  case "project-repo-not-git":
1528
1744
  return `\u041F\u0440\u043E\u0435\u043A\u0442 ${p.projectId}: ${p.repo} \u2014 \u043D\u0435 git-\u0440\u0435\u043F\u043E\u0437\u0438\u0442\u043E\u0440\u0438\u0439, \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`;
1529
- case "project-repo-unsafe":
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}"`;
1745
+ case "project-repo-unsafe": {
1746
+ const { reason, fix } = unsafeRepo2(p.repo, p.trustCommand);
1747
+ return `\u041F\u0440\u043E\u0435\u043A\u0442 ${p.projectId}: ${reason} \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. ${fix}`;
1748
+ }
1531
1749
  case "project-history-unreadable":
1532
1750
  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
1751
  case "project-branches-unreadable":
@@ -1555,6 +1773,8 @@ var coreRu = {
1555
1773
  languageName: "\u0420\u0443\u0441\u0441\u043A\u0438\u0439",
1556
1774
  problem: problem2,
1557
1775
  problems: problems2,
1776
+ taskNotLoaded: taskNotLoaded2,
1777
+ unsafeRepo: unsafeRepo2,
1558
1778
  schemaIssue: schemaIssue3,
1559
1779
  ...labelLookups(LABELS2),
1560
1780
  count: count2,
@@ -1626,84 +1846,6 @@ function taskCreation(record, created) {
1626
1846
  return created === void 0 ? void 0 : { createdAt: Date.parse(created.at), type: created.type };
1627
1847
  }
1628
1848
 
1629
- // src/core/model/checklist.ts
1630
- var ITEM = /^\s*[-*+]\s+\[(?<mark>[ xX])\]\s+(?<text>.*)$/;
1631
- var FENCE = /^\s{0,3}(?<fence>`{3,}|~{3,})/;
1632
- function checklistItems(body) {
1633
- const items = [];
1634
- let openFence = null;
1635
- for (const [line, content] of body.split("\n").entries()) {
1636
- const fence = FENCE.exec(content)?.groups?.fence;
1637
- if (fence !== void 0) {
1638
- if (openFence === null) openFence = fence;
1639
- else if (fence.startsWith(openFence)) openFence = null;
1640
- continue;
1641
- }
1642
- if (openFence !== null) continue;
1643
- const groups = ITEM.exec(content)?.groups;
1644
- if (groups) items.push({ line, checked: groups.mark !== " ", text: groups.text ?? "" });
1645
- }
1646
- return items;
1647
- }
1648
-
1649
- // src/core/model/graph.ts
1650
- var CLOSED_STATUSES = ["done", "cancelled"];
1651
- function isClosed(status) {
1652
- return CLOSED_STATUSES.some((closed) => closed === status);
1653
- }
1654
- function buildIndex(tasks) {
1655
- const byId = /* @__PURE__ */ new Map();
1656
- const dependentsOf = /* @__PURE__ */ new Map();
1657
- const relatedFrom = /* @__PURE__ */ new Map();
1658
- const childrenOf = /* @__PURE__ */ new Map();
1659
- for (const task of tasks) {
1660
- byId.set(task.id, task);
1661
- for (const blockerId of task.blockedBy) appendTo(dependentsOf, blockerId, task);
1662
- for (const relatedId of task.related) appendTo(relatedFrom, relatedId, task);
1663
- if (task.epic !== void 0) appendTo(childrenOf, task.epic, task);
1664
- }
1665
- return { byId, dependentsOf, relatedFrom, childrenOf };
1666
- }
1667
- function openBlockers(task, index) {
1668
- return existingTasks(task.blockedBy, index).filter((blocker) => !isClosed(blocker.status));
1669
- }
1670
- function isBlocked(task, index) {
1671
- return openBlockers(task, index).length > 0;
1672
- }
1673
- function missingReferences(task, index) {
1674
- return [.../* @__PURE__ */ new Set([...task.blockedBy, ...task.related])].filter((id) => !index.byId.has(id));
1675
- }
1676
- function dependentTasks(task, index) {
1677
- return index.dependentsOf.get(task.id) ?? [];
1678
- }
1679
- function relatedTasks(task, index) {
1680
- const both = [...existingTasks(task.related, index), ...index.relatedFrom.get(task.id) ?? []];
1681
- return [...new Map(both.filter((other) => other.id !== task.id).map((other) => [other.id, other])).values()];
1682
- }
1683
- function epicChildren(epic, index) {
1684
- return index.childrenOf.get(epic.id) ?? [];
1685
- }
1686
- function taskProgress(task, index) {
1687
- if (task.status === "done") return 100;
1688
- if (task.type === "epic") {
1689
- const active = epicChildren(task, index).filter((child) => child.status !== "cancelled");
1690
- return active.length === 0 ? null : percent(active.filter((child) => child.status === "done").length, active.length);
1691
- }
1692
- const items = checklistItems(task.body);
1693
- return items.length === 0 ? null : percent(items.filter((item) => item.checked).length, items.length);
1694
- }
1695
- function existingTasks(ids, index) {
1696
- return ids.flatMap((id) => index.byId.get(id) ?? []);
1697
- }
1698
- function appendTo(map, key, task) {
1699
- const list = map.get(key);
1700
- if (list) list.push(task);
1701
- else map.set(key, [task]);
1702
- }
1703
- function percent(part, total) {
1704
- return Math.round(part / total * 100);
1705
- }
1706
-
1707
1849
  // src/core/journal/events.ts
1708
1850
  import { z as z7 } from "zod";
1709
1851
  var CHANGE_SOURCES = ["cli", "web", "check", "sweep"];
@@ -1944,24 +2086,24 @@ function dedupeSightings(sightings) {
1944
2086
  }
1945
2087
 
1946
2088
  // src/core/store/daily.ts
1947
- async function runWhenDue(stampPath, now, action) {
1948
- if (!await isDue(stampPath, now)) return null;
2089
+ async function runWhenDue(stampPath, writes, action) {
2090
+ if (!await isDue(stampPath, writes.now)) return null;
1949
2091
  try {
1950
2092
  return await withFileLock(stampPath, async () => {
1951
- if (!await isDue(stampPath, now)) return null;
1952
- return runAndStamp(stampPath, now, action);
2093
+ if (!await isDue(stampPath, writes.now)) return null;
2094
+ return runAndStamp(stampPath, writes, action);
1953
2095
  });
1954
2096
  } catch (error) {
1955
2097
  if (error instanceof FileBusyError && error.path === stampPath) return null;
1956
2098
  throw error;
1957
2099
  }
1958
2100
  }
1959
- async function runAndStamp(stampPath, now, action) {
2101
+ async function runAndStamp(stampPath, { now, onError }, action) {
1960
2102
  try {
1961
2103
  return await action();
1962
2104
  } finally {
1963
2105
  await writeFileAtomic(stampPath, `${formatLocalIso(now)}
1964
- `);
2106
+ `, { onErrorAfterPublish: onError });
1965
2107
  }
1966
2108
  }
1967
2109
  async function isDue(stampPath, now) {
@@ -1981,7 +2123,7 @@ async function appendJournal(projectDir2, events, onError) {
1981
2123
  onError(path, error);
1982
2124
  }
1983
2125
  }
1984
- var JOURNAL_LOCK_WAIT_MS = REPLACE_RETRIES_TOTAL_MS + 10 * SECOND_MS;
2126
+ var JOURNAL_LOCK_WAIT_MS = 4 * BLOCKED_RETRIES_TOTAL_MS + 10 * SECOND_MS;
1985
2127
  async function appendWaitingForLock(path, events) {
1986
2128
  try {
1987
2129
  await withFileLock(path, () => appendJsonLines(path, events), { waitLimitMs: JOURNAL_LOCK_WAIT_MS });
@@ -2002,8 +2144,9 @@ function markedUndo(event) {
2002
2144
  function bufferedJournal(target) {
2003
2145
  const pending = /* @__PURE__ */ new Map();
2004
2146
  return {
2005
- write: async (projectDir2, events) => {
2147
+ write: (projectDir2, events) => {
2006
2148
  pending.set(projectDir2, [...pending.get(projectDir2) ?? [], ...events]);
2149
+ return Promise.resolve();
2007
2150
  },
2008
2151
  flush: async () => {
2009
2152
  for (const [projectDir2, events] of pending) await target(projectDir2, events);
@@ -2025,13 +2168,13 @@ async function readJournals(root, projectIds) {
2025
2168
  import { rm as rm4 } from "node:fs/promises";
2026
2169
  import { join as join8 } from "node:path";
2027
2170
  var NOT_FOUND2 = { ok: false, reason: "not-found" };
2028
- async function setProjectActive(root, id, active) {
2171
+ async function setProjectActive(root, id, active, onError) {
2029
2172
  const dir = projectDir(root, id);
2030
2173
  if (dir === null) return NOT_FOUND2;
2031
- return editProjectFile({ id, path: join8(dir, PROJECT_FILE) }, (project) => project.active === active ? project : { ...project, active });
2174
+ return editProjectFile({ id, path: join8(dir, PROJECT_FILE) }, onError, (project) => project.active === active ? project : { ...project, active });
2032
2175
  }
2033
- function reserveIssuedUpTo(project, number) {
2034
- return editProjectFile(project, (current) => {
2176
+ function reserveIssuedUpTo(project, number, onError) {
2177
+ return editProjectFile(project, onError, (current) => {
2035
2178
  const issuedUpTo = Math.max(current.issuedUpTo ?? 0, number);
2036
2179
  return issuedUpTo === current.issuedUpTo ? current : { ...current, issuedUpTo };
2037
2180
  });
@@ -2043,17 +2186,25 @@ async function issuedUpToOnDisk(project) {
2043
2186
  async function readProjectFile({ id, path }) {
2044
2187
  return parseDocumentOrNull(path, (text) => parseProjectFile(text, { id, path }));
2045
2188
  }
2046
- async function editProjectFile({ id, path }, edit) {
2189
+ async function editProjectFile({ id, path }, onError, edit) {
2047
2190
  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
- });
2191
+ let written = null;
2192
+ try {
2193
+ return await withFileLock(path, async () => {
2194
+ const parsed = await readProjectFile({ id, path });
2195
+ if (parsed === null) return NOT_FOUND2;
2196
+ if (!parsed.ok) return { ok: false, reason: "invalid", problems: parsed.problems };
2197
+ const project = edit(parsed.value);
2198
+ const changed = project !== parsed.value;
2199
+ if (changed) await writeFileAtomic(path, serializeProject(project), { onErrorAfterPublish: onError });
2200
+ written = { ok: true, project, changed };
2201
+ return written;
2202
+ });
2203
+ } catch (error) {
2204
+ if (written === null) throw error;
2205
+ onError(path, error);
2206
+ return written;
2207
+ }
2057
2208
  }
2058
2209
  async function deleteProject(root, id) {
2059
2210
  const dir = projectDir(root, id);
@@ -2065,23 +2216,23 @@ async function deleteProject(root, id) {
2065
2216
  // src/core/store/journal-compaction.ts
2066
2217
  var COMPACTED_STAMP = ".journal-compacted-at";
2067
2218
  var EPISODE_KINDS = /* @__PURE__ */ new Set(["candidate", "candidate-gone", "candidate-filtered", "verified"]);
2068
- async function compactJournalsWhenDue(root, now, failed2) {
2219
+ async function compactJournalsWhenDue(root, writes, onNotCompacted) {
2069
2220
  const compacted = [];
2070
2221
  for (const name of await projectDirNames(root)) {
2071
2222
  const dir = join9(root, name);
2072
- const removed = await compactProjectWhenDue(dir, now).catch((error) => {
2073
- failed2(dir, error);
2223
+ const removed = await compactProjectWhenDue(dir, writes).catch((error) => {
2224
+ onNotCompacted(dir, error);
2074
2225
  return null;
2075
2226
  });
2076
2227
  if (removed !== null && removed > 0) compacted.push(name);
2077
2228
  }
2078
2229
  return compacted;
2079
2230
  }
2080
- async function compactProjectWhenDue(dir, now) {
2231
+ async function compactProjectWhenDue(dir, writes) {
2081
2232
  if (!await fileExists(join9(dir, JOURNAL_FILE))) return null;
2082
- return runWhenDue(join9(dir, COMPACTED_STAMP), now, async () => compactJournal(dir, await taskIdsOnDisk(dir), now));
2233
+ return runWhenDue(join9(dir, COMPACTED_STAMP), writes, async () => compactJournal(dir, await taskIdsOnDisk(dir), writes));
2083
2234
  }
2084
- async function compactJournal(projectDir2, liveTaskIds, now) {
2235
+ async function compactJournal(projectDir2, liveTaskIds, { now, onError }) {
2085
2236
  const path = join9(projectDir2, JOURNAL_FILE);
2086
2237
  if (!await fileExists(path)) return 0;
2087
2238
  return withFileLock(path, async () => {
@@ -2089,18 +2240,18 @@ async function compactJournal(projectDir2, liveTaskIds, now) {
2089
2240
  const completeLines = journal.subarray(0, journal.lastIndexOf(NEWLINE) + 1);
2090
2241
  const lines = journalLines(completeLines.toString("utf8"));
2091
2242
  const kept = retainedLines(lines, liveTaskIds, retainedSince(now));
2092
- const removed = lines.length - kept.length;
2093
- if (removed === 0 || !await reserveRemovedNumbers(projectDir2, lines, kept)) return 0;
2243
+ const keptLines = new Set(kept);
2244
+ const dropped = lines.filter((line) => !keptLines.has(line));
2245
+ if (dropped.length === 0 || !await reserveDroppedNumbers(projectDir2, dropped, onError)) return 0;
2094
2246
  const replaced = await replacePrefixAtomic(path, completeLines, kept.map(({ text }) => `${text}
2095
- `).join(""));
2096
- return replaced ? removed : 0;
2247
+ `).join(""), { onErrorAfterPublish: onError });
2248
+ return replaced ? dropped.length : 0;
2097
2249
  });
2098
2250
  }
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);
2251
+ async function reserveDroppedNumbers(projectDir2, dropped, onError) {
2252
+ const highest = dropped.reduce((max, { event }) => event === null ? max : Math.max(max, parseId(event.task)?.number ?? 0), 0);
2102
2253
  if (highest === 0) return true;
2103
- const reservation = await reserveIssuedUpTo({ id: basename5(projectDir2), path: join9(projectDir2, PROJECT_FILE) }, highest);
2254
+ const reservation = await reserveIssuedUpTo({ id: basename5(projectDir2), path: join9(projectDir2, PROJECT_FILE) }, highest, onError);
2104
2255
  return reservation.ok || reservation.reason === "not-found";
2105
2256
  }
2106
2257
  function journalLines(text) {
@@ -2171,11 +2322,12 @@ async function trimOpenLog(handle, limitBytes, keptBytes) {
2171
2322
 
2172
2323
  // src/core/store/maintenance.ts
2173
2324
  async function runMaintenance(plan, { root, now, messages, warn: warn2 }) {
2174
- await warnOnFailure(plan.trimRuns(root, now), warn2, messages.runsNotTrimmed);
2175
- const report = plan.sweepClosed === null ? null : await warnOnFailure(plan.sweepClosed(root, { now, onError: warnPathErrors(warn2) }, messages), warn2, messages.closedNotSwept);
2325
+ const writes = { now, onError: warnPathErrors(warn2) };
2326
+ await warnOnFailure(plan.trimRuns(root, writes), warn2, messages.runsNotTrimmed);
2327
+ const report = plan.sweepClosed === null ? null : await warnOnFailure(plan.sweepClosed(root, writes, messages), warn2, messages.closedNotSwept);
2176
2328
  if (plan.compactJournals !== null) {
2177
- const compactionFailed = (dir, error) => warn2(messages.journalNotCompacted(dir, errorText(error)));
2178
- await warnOnFailure(plan.compactJournals(root, now, compactionFailed), warn2, (error) => messages.journalNotCompacted(root, error));
2329
+ const onNotCompacted = warnPathErrors(warn2, messages.journalNotCompacted);
2330
+ await warnOnFailure(plan.compactJournals(root, writes, onNotCompacted), warn2, (error) => messages.journalNotCompacted(root, error));
2179
2331
  }
2180
2332
  if (plan.serviceLog !== null) await warnOnFailure(trimLogFile(plan.serviceLog, SERVICE_LOG_LIMIT_BYTES, SERVICE_LOG_KEPT_BYTES), warn2, messages.serviceLogNotTrimmed);
2181
2333
  return report;
@@ -2208,18 +2360,20 @@ function settleLifecycle(task, now) {
2208
2360
  }
2209
2361
  function scheduledDeletion(task, index) {
2210
2362
  if (!isClosed(task.status) || task.closed === void 0) return void 0;
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 };
2363
+ const keeper = keepingEpicId(task, index);
2364
+ return keeper === void 0 ? { at: new Date(Date.parse(task.closed) + RETENTION_DAYS * DAY_MS) } : { afterEpic: keeper };
2213
2365
  }
2214
2366
  function isExpired(task, now, index) {
2215
2367
  const deletion = scheduledDeletion(task, index);
2216
2368
  return deletion !== void 0 && "at" in deletion && deletion.at.getTime() <= now.getTime();
2217
2369
  }
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;
2370
+ function keepingEpicId(task, index) {
2371
+ if (task.epic === void 0) return void 0;
2372
+ const epic = index.byId.get(task.epic);
2373
+ if (epic === void 0) return index.notLoaded.has(task.epic) ? task.epic : void 0;
2374
+ if (epic.type !== "epic") return void 0;
2221
2375
  const reopensWithOpenTasks = isAutoClosedEpic(epic) && openChildIds(epic, index).length > 0;
2222
- return !isClosed(epic.status) || reopensWithOpenTasks ? epic : void 0;
2376
+ return !isClosed(epic.status) || reopensWithOpenTasks ? epic.id : void 0;
2223
2377
  }
2224
2378
  function planEpicClosing(tasks, parseErrors) {
2225
2379
  const unreadableProjects = new Set(parseErrors.map((error) => error.projectId));
@@ -2230,7 +2384,7 @@ function planEpicClosing(tasks, parseErrors) {
2230
2384
  };
2231
2385
  }
2232
2386
  function completedEpics(tasks) {
2233
- const index = buildIndex(tasks);
2387
+ const index = buildIndex(tasks, NO_UNLOADED_TASKS);
2234
2388
  return tasks.flatMap((epic) => {
2235
2389
  const childIds = completedEpicChildren(epic, index);
2236
2390
  return childIds === null ? [] : [{ epic, childIds }];
@@ -2249,13 +2403,16 @@ function openChildIds(epic, index) {
2249
2403
  return epicChildren(epic, index).flatMap((child) => isClosed(child.status) ? [] : [child.id]);
2250
2404
  }
2251
2405
  function planEpicReopening(tasks) {
2252
- const index = buildIndex(tasks);
2406
+ const index = buildIndex(tasks, NO_UNLOADED_TASKS);
2253
2407
  return tasks.flatMap((epic) => {
2254
2408
  if (!isAutoClosedEpic(epic)) return [];
2255
2409
  const childIds = openChildIds(epic, index);
2256
2410
  return childIds.length === 0 ? [] : [{ epic, childIds }];
2257
2411
  });
2258
2412
  }
2413
+ function closesAfterItsTasks(action, task) {
2414
+ return action.kind === "close" && task.type === "epic";
2415
+ }
2259
2416
  function epicClosingProblems(before, after, index) {
2260
2417
  if (after.type !== "epic" || !isClosed(after.status) || isClosed(before.status)) return [];
2261
2418
  const childIds = openChildIds(after, index);
@@ -2288,7 +2445,7 @@ function integrityErrors(candidate, index) {
2288
2445
  const errors = [];
2289
2446
  if (candidate.blockedBy.includes(candidate.id)) errors.push({ code: "self-block" });
2290
2447
  if (candidate.related.includes(candidate.id)) errors.push({ code: "self-related" });
2291
- errors.push(...epicProblems(candidate, resolve7));
2448
+ errors.push(...epicProblems(candidate, index));
2292
2449
  const children = (index.childrenOf.get(candidate.id) ?? []).filter((task) => task.id !== candidate.id);
2293
2450
  if (candidate.type === "task" && children.length > 0) {
2294
2451
  errors.push({ code: "referenced-as-epic", children: children.map((task) => task.id) });
@@ -2301,24 +2458,30 @@ function integrityErrors(candidate, index) {
2301
2458
  if (candidate.reason !== void 0 && candidate.resolution === void 0) errors.push({ code: "reason-without-resolution" });
2302
2459
  return errors;
2303
2460
  }
2304
- function epicProblems(candidate, resolve7) {
2461
+ function epicProblems(candidate, index) {
2305
2462
  if (candidate.epic === void 0) return [];
2306
2463
  const problems3 = [];
2307
2464
  if (candidate.epic === candidate.id) {
2308
2465
  problems3.push({ code: "epic-self" });
2309
2466
  } else {
2310
- const epic = resolve7(candidate.epic);
2311
- if (!epic) problems3.push({ code: "epic-missing", epic: candidate.epic });
2467
+ const epic = index.byId.get(candidate.epic);
2468
+ if (!epic) problems3.push(missingEpicProblem(candidate.epic, index.notLoaded.get(candidate.epic)));
2312
2469
  else if (epic.type !== "epic") problems3.push({ code: "epic-not-epic", epic: candidate.epic });
2313
2470
  else if (epic.projectId !== candidate.projectId) problems3.push({ code: "epic-foreign-project", epic: candidate.epic });
2314
2471
  }
2315
2472
  if (candidate.type === "epic") problems3.push({ code: "epic-in-epic" });
2316
2473
  return problems3;
2317
2474
  }
2475
+ function missingEpicProblem(epic, file) {
2476
+ return file === void 0 ? { code: "epic-missing", epic } : { code: "epic-unparsed", epic, fileKind: file };
2477
+ }
2318
2478
  function taskWarnings(task, index) {
2319
- const missing = missingReferences(task, index).map((id) => ({ code: "reference-missing", id }));
2479
+ const missing = missingReferences(task, index).map((id) => missingReferenceProblem(id, index.notLoaded.get(id)));
2320
2480
  return [...missing, ...integrityErrors(task, index)];
2321
2481
  }
2482
+ function missingReferenceProblem(id, file) {
2483
+ return file === void 0 ? { code: "reference-missing", id } : { code: "reference-unparsed", id, fileKind: file };
2484
+ }
2322
2485
  function findBlockerCycle(start, resolve7) {
2323
2486
  const visited = /* @__PURE__ */ new Set();
2324
2487
  const walk = (task, path) => {
@@ -2355,6 +2518,9 @@ function withWrittenTasks(tasks, results) {
2355
2518
  const known = new Set(tasks.map((task) => task.id));
2356
2519
  return [...tasks.map((task) => byId.get(task.id) ?? task), ...written.filter((task) => !known.has(task.id))];
2357
2520
  }
2521
+ function indexWithWritten(index, results) {
2522
+ return buildIndex(withWrittenTasks([...index.byId.values()], results), index.notLoaded);
2523
+ }
2358
2524
  function invalid(problems3) {
2359
2525
  return { ok: false, reason: "invalid", problems: problems3 };
2360
2526
  }
@@ -2394,16 +2560,29 @@ async function writeChanges(index, { id, changes, expectedVersion, now, closure,
2394
2560
  const normalized = taskText(applyChanges(current, changes, now, closure));
2395
2561
  if (!normalized.ok) return invalid(normalized.problems);
2396
2562
  const { text, task } = normalized.value;
2397
- const problems3 = [...integrityErrors(task, index), ...epicClosingProblems(current, task, index)];
2563
+ const keepsEpic = task.epic === current.epic;
2564
+ const integrity = integrityErrors(task, index).filter((problem3) => !(keepsEpic && isUnloadedEpic(problem3)));
2565
+ const problems3 = [...integrity, ...epicClosingProblems(current, task, index)];
2398
2566
  if (problems3.length > 0) return invalid(problems3);
2399
- const written = await withTaskLock(current.path, async () => {
2400
- const changedOnDisk = await diskChange(current, expectedVersion);
2401
- if (changedOnDisk !== null) return changedOnDisk;
2402
- await writeFileAtomic(current.path, text);
2567
+ let written = false;
2568
+ try {
2569
+ return await withTaskLock(current.path, async () => {
2570
+ const changedOnDisk = await diskChange(current, expectedVersion);
2571
+ if (changedOnDisk !== null) return changedOnDisk;
2572
+ await writeFileAtomic(current.path, text, { onErrorAfterPublish: onError });
2573
+ written = true;
2574
+ return { ok: true, task };
2575
+ });
2576
+ } catch (error) {
2577
+ if (!written) throw error;
2578
+ onError(current.path, error);
2403
2579
  return { ok: true, task };
2404
- });
2405
- if (written.ok) await journal(dirname4(current.path), changeEvents(current, task, now, via));
2406
- return written;
2580
+ } finally {
2581
+ if (written) await journal(dirname4(current.path), changeEvents(current, task, now, via));
2582
+ }
2583
+ }
2584
+ function isUnloadedEpic(problem3) {
2585
+ return problem3.code === "epic-missing" || problem3.code === "epic-unparsed";
2407
2586
  }
2408
2587
  async function withTaskLock(path, write) {
2409
2588
  try {
@@ -2455,23 +2634,24 @@ function nextOptional(current, change) {
2455
2634
  // src/core/store/sweep.ts
2456
2635
  var SWEPT_AT_FILE = ".swept-at";
2457
2636
  function sweepClosedWhenDue(root, writes, messages) {
2458
- return runWhenDue(join10(root, SWEPT_AT_FILE), writes.now, () => sweepClosed(root, writes, messages));
2637
+ return runWhenDue(join10(root, SWEPT_AT_FILE), writes, () => sweepClosed(root, writes, messages));
2459
2638
  }
2460
2639
  function sweepClosedAndStamp(root, writes, messages) {
2461
- return runAndStamp(join10(root, SWEPT_AT_FILE), writes.now, () => sweepClosed(root, writes, messages));
2640
+ return runAndStamp(join10(root, SWEPT_AT_FILE), writes, () => sweepClosed(root, writes, messages));
2462
2641
  }
2463
2642
  async function sweepClosed(root, writes, messages) {
2464
2643
  const { now } = writes;
2465
2644
  const initial = await loadBacklog(root);
2466
2645
  const reopening = await reopenEpicsWithOpenTasks(initial, writes);
2467
2646
  const epics = await closeCompletedEpics(initial, writes, messages);
2468
- const { projects, tasks } = epics.closed.length > 0 || reopening.reopened.length > 0 ? await loadBacklog(root) : initial;
2469
- const index = buildIndex(tasks);
2647
+ const current = epics.closed.length > 0 || reopening.reopened.length > 0 ? await loadBacklog(root) : initial;
2648
+ const { projects, tasks } = current;
2649
+ const index = indexOfLoaded(current);
2470
2650
  const stillHoldsOpenTasks = new Set(planEpicReopening(tasks).map(({ epic }) => epic.id));
2471
2651
  const expired = tasks.filter((task) => isExpired(task, now, index) && !stillHoldsOpenTasks.has(task.id));
2472
- const reserved = await reserveNumbers(projects, expired);
2652
+ const reserved = await reserveNumbers(projects, expired, writes.onError);
2473
2653
  const removable = expired.filter((task) => reserved.has(task.projectId));
2474
- const removal = await removeWithReferences(tasks, removable, writes);
2654
+ const removal = await removeWithReferences({ tasks, index }, removable, writes);
2475
2655
  await removeAbandonedTemporaries(root, now);
2476
2656
  return {
2477
2657
  closedEpics: epics.closed,
@@ -2486,22 +2666,28 @@ async function removeAbandonedTemporaries(root, now) {
2486
2666
  const projectDirs = (await projectDirNames(root)).map((name) => join10(root, name));
2487
2667
  for (const dir of [root, ...projectDirs]) await removeTemporariesBefore(dir, cutoff);
2488
2668
  }
2489
- async function removeWithReferences(tasks, removable, writes) {
2669
+ async function removeWithReferences(remaining, removable, writes) {
2490
2670
  const conflict = (task) => ({ id: task.id, reason: "conflict" });
2491
- return withAvailableLocks(
2492
- removable.map((task) => task.path),
2493
- async (lockedPaths) => {
2494
- const locked = removable.filter((task) => lockedPaths.has(task.path));
2495
- const unchanged = await unchangedOnDisk(locked);
2496
- const updates = await repairRemainingTasks(tasks, { skipped: removable, removed: unchanged }, writes);
2497
- const removal = await removeLocked(
2498
- unchanged.filter((task) => !updates.stillReferenced.has(task.id)),
2499
- writes
2500
- );
2501
- const untouched = removable.filter((task) => !unchanged.includes(task)).map(conflict);
2502
- return { deleted: removal.deleted, failures: [...updates.failures, ...untouched, ...removal.failures] };
2503
- }
2504
- );
2671
+ const journal = bufferedJournal(writes.journal ?? appendingJournal(writes.onError));
2672
+ const lockedWrites = { ...writes, journal: journal.write };
2673
+ try {
2674
+ return await withAvailableLocks(
2675
+ removable.map((task) => task.path),
2676
+ async (lockedPaths) => {
2677
+ const locked = removable.filter((task) => lockedPaths.has(task.path));
2678
+ const unchanged = await unchangedOnDisk(locked);
2679
+ const updates = await repairRemainingTasks(remaining, { skipped: removable, removed: unchanged }, lockedWrites);
2680
+ const removal = await removeLocked(
2681
+ unchanged.filter((task) => !updates.stillReferenced.has(task.id)),
2682
+ lockedWrites
2683
+ );
2684
+ const untouched = removable.filter((task) => !unchanged.includes(task)).map(conflict);
2685
+ return { deleted: removal.deleted, failures: [...updates.failures, ...untouched, ...removal.failures] };
2686
+ }
2687
+ );
2688
+ } finally {
2689
+ await journal.flush();
2690
+ }
2505
2691
  }
2506
2692
  async function unchangedOnDisk(tasks) {
2507
2693
  const checked = await Promise.all(
@@ -2513,7 +2699,7 @@ async function unchangedOnDisk(tasks) {
2513
2699
  return tasks.filter((_, position) => checked[position]);
2514
2700
  }
2515
2701
  async function reopenEpicsWithOpenTasks(loaded, writes) {
2516
- const index = buildIndex(loaded.tasks);
2702
+ const index = indexOfLoaded(loaded);
2517
2703
  const reopened = [];
2518
2704
  const failures = [];
2519
2705
  for (const { epic } of planEpicReopening(loaded.tasks)) {
@@ -2525,7 +2711,7 @@ async function reopenEpicsWithOpenTasks(loaded, writes) {
2525
2711
  }
2526
2712
  async function closeCompletedEpics(loaded, writes, messages) {
2527
2713
  const plan = planEpicClosing(loaded.tasks, loaded.errors);
2528
- const index = buildIndex(loaded.tasks);
2714
+ const index = indexOfLoaded(loaded);
2529
2715
  const closed = [];
2530
2716
  const failures = [];
2531
2717
  for (const { epic, childIds } of plan.close) {
@@ -2538,8 +2724,7 @@ async function closeCompletedEpics(loaded, writes, messages) {
2538
2724
  const blockingFiles = loaded.errors.filter((error) => waitingProjects.has(error.projectId)).map((error) => error.path);
2539
2725
  return { closed, failures, blockingFiles };
2540
2726
  }
2541
- async function repairRemainingTasks(tasks, { skipped, removed }, writes) {
2542
- const index = buildIndex(tasks);
2727
+ async function repairRemainingTasks({ tasks, index }, { skipped, removed }, writes) {
2543
2728
  const skippedIds = new Set(skipped.map((task) => task.id));
2544
2729
  const removedIds = new Set(removed.map((task) => task.id));
2545
2730
  const failures = [];
@@ -2561,7 +2746,7 @@ async function repairFailure(index, task, changes, writes) {
2561
2746
  function referencedIds(task) {
2562
2747
  return [...task.epic === void 0 ? [] : [task.epic], ...task.blockedBy, ...task.related];
2563
2748
  }
2564
- async function removeLocked(expired, { now, onError }) {
2749
+ async function removeLocked(expired, { now, journal }) {
2565
2750
  const deleted = [];
2566
2751
  const failures = [];
2567
2752
  for (const task of expired) {
@@ -2569,7 +2754,7 @@ async function removeLocked(expired, { now, onError }) {
2569
2754
  if (outcome === "changed") failures.push({ id: task.id, reason: "conflict" });
2570
2755
  if (outcome !== "removed") continue;
2571
2756
  deleted.push(task.id);
2572
- await appendJournal(dirname5(task.path), [deletedEvent(task, now, "sweep")], onError);
2757
+ await journal(dirname5(task.path), [deletedEvent(task, now, "sweep")]);
2573
2758
  }
2574
2759
  return { deleted, failures };
2575
2760
  }
@@ -2593,11 +2778,11 @@ function failureLists(failures, messages) {
2593
2778
  function lacksClosedDate(task) {
2594
2779
  return isClosed(task.status) && task.closed === void 0;
2595
2780
  }
2596
- async function reserveNumbers(projects, expired) {
2781
+ async function reserveNumbers(projects, expired, onError) {
2597
2782
  const reserved = /* @__PURE__ */ new Set();
2598
2783
  for (const project of projects) {
2599
2784
  const numbers = expired.filter((task) => task.projectId === project.id).flatMap((task) => parseId(task.id)?.number ?? []);
2600
- if (numbers.length === 0 || (await reserveIssuedUpTo(project, Math.max(...numbers))).ok) reserved.add(project.id);
2785
+ if (numbers.length === 0 || (await reserveIssuedUpTo(project, Math.max(...numbers), onError)).ok) reserved.add(project.id);
2601
2786
  }
2602
2787
  return reserved;
2603
2788
  }
@@ -2684,6 +2869,7 @@ var cliEn = {
2684
2869
  tagsLine: (tags) => `Tags: ${tags}`,
2685
2870
  epicLine: (ref) => `Epic: ${ref}`,
2686
2871
  epicNotFound: (epicId) => `${epicId} (not found)`,
2872
+ epicNotLoaded: (epicId) => `${epicId} (not loaded)`,
2687
2873
  openBlockersLine: (list) => `Open blockers: ${list}`,
2688
2874
  inactiveBlockersLine: (list) => `Closed or missing blockers: ${list}`,
2689
2875
  blocksLine: (list) => `Blocks: ${list}`,
@@ -2697,6 +2883,7 @@ var cliEn = {
2697
2883
  candidateRenamed: (path, to) => `${path} renamed to ${to}`,
2698
2884
  candidateSimilarTo: (otherId) => `similar to ${otherId}`,
2699
2885
  taskFileUnparsed: (id, problems3) => `Task file ${id} could not be parsed: ${problems3}`,
2886
+ taskOfUnparsedProject: (id, path, problems3) => `Task ${id} not loaded: project file ${path} could not be parsed (${problems3})`,
2700
2887
  projectNotFoundForCwd: (cwd) => `No project found for ${cwd}. Pass --project <id> or add the path to repos of the right project.md`,
2701
2888
  projectNotFound: (id) => `Project ${id} not found`,
2702
2889
  projectFileUnparsed: (path, problems3) => `Project not loaded: ${path} could not be parsed (${problems3})`,
@@ -2732,6 +2919,7 @@ var cliEn = {
2732
2919
  sourceEmpty: "--source cannot be empty",
2733
2920
  sourceFileMissing: (source) => `--source ${source}: no such file in the project repository \u2014 check the path`,
2734
2921
  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`,
2922
+ sourceFileUncheckedUnsafeRepo: (source, { reason, fix }) => `--source ${source}: the file is not on disk and git branches were not read \u2014 ${reason}; the path was not checked. ${fix}`,
2735
2923
  alreadyInStatusNothingToVerify: (id, status) => `${id} is already ${status}: nothing to confirm`,
2736
2924
  verified: (id) => `${id}: confirmed`,
2737
2925
  verifiedWithSource: (id, source) => `${id}: confirmed, source \u2192 ${source}`,
@@ -2871,6 +3059,7 @@ var cliRu = {
2871
3059
  tagsLine: (tags) => `\u0422\u0435\u0433\u0438: ${tags}`,
2872
3060
  epicLine: (ref) => `\u042D\u043F\u0438\u043A: ${ref}`,
2873
3061
  epicNotFound: (epicId) => `${epicId} (\u043D\u0435 \u043D\u0430\u0439\u0434\u0435\u043D)`,
3062
+ epicNotLoaded: (epicId) => `${epicId} (\u043D\u0435 \u0437\u0430\u0433\u0440\u0443\u0436\u0435\u043D)`,
2874
3063
  openBlockersLine: (list) => `\u041E\u0442\u043A\u0440\u044B\u0442\u044B\u0435 \u0431\u043B\u043E\u043A\u0435\u0440\u044B: ${list}`,
2875
3064
  inactiveBlockersLine: (list) => `\u0417\u0430\u043A\u0440\u044B\u0442\u044B\u0435 \u0438\u043B\u0438 \u043D\u0435\u043D\u0430\u0439\u0434\u0435\u043D\u043D\u044B\u0435 \u0431\u043B\u043E\u043A\u0435\u0440\u044B: ${list}`,
2876
3065
  blocksLine: (list) => `\u0411\u043B\u043E\u043A\u0438\u0440\u0443\u0435\u0442: ${list}`,
@@ -2884,6 +3073,7 @@ var cliRu = {
2884
3073
  candidateRenamed: (path, to) => `${path} \u043F\u0435\u0440\u0435\u0438\u043C\u0435\u043D\u043E\u0432\u0430\u043D \u0432 ${to}`,
2885
3074
  candidateSimilarTo: (otherId) => `\u043F\u043E\u0445\u043E\u0436\u0430 \u043D\u0430 ${otherId}`,
2886
3075
  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}`,
3076
+ taskOfUnparsedProject: (id, path, problems3) => `\u0417\u0430\u0434\u0430\u0447\u0430 ${id} \u043D\u0435 \u0437\u0430\u0433\u0440\u0443\u0436\u0435\u043D\u0430: \u0444\u0430\u0439\u043B \u043F\u0440\u043E\u0435\u043A\u0442\u0430 ${path} \u043D\u0435 \u0440\u0430\u0437\u043E\u0431\u0440\u0430\u043D (${problems3})`,
2887
3077
  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`,
2888
3078
  projectNotFound: (id) => `\u041F\u0440\u043E\u0435\u043A\u0442 ${id} \u043D\u0435 \u043D\u0430\u0439\u0434\u0435\u043D`,
2889
3079
  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})`,
@@ -2919,6 +3109,7 @@ var cliRu = {
2919
3109
  sourceEmpty: "--source \u043D\u0435 \u043C\u043E\u0436\u0435\u0442 \u0431\u044B\u0442\u044C \u043F\u0443\u0441\u0442\u044B\u043C",
2920
3110
  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
3111
  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`,
3112
+ sourceFileUncheckedUnsafeRepo: (source, { reason, fix }) => `--source ${source}: \u0444\u0430\u0439\u043B\u0430 \u043D\u0435\u0442 \u043D\u0430 \u0434\u0438\u0441\u043A\u0435, \u0430 \u0432\u0435\u0442\u043A\u0438 git \u043D\u0435 \u043F\u0440\u043E\u0447\u0438\u0442\u0430\u043D\u044B \u2014 ${reason}; \u043F\u0443\u0442\u044C \u043D\u0435 \u043F\u0440\u043E\u0432\u0435\u0440\u0435\u043D. ${fix}`,
2922
3113
  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`,
2923
3114
  verified: (id) => `${id}: \u043F\u043E\u0434\u0442\u0432\u0435\u0440\u0436\u0434\u0435\u043D\u0430`,
2924
3115
  verifiedWithSource: (id, source) => `${id}: \u043F\u043E\u0434\u0442\u0432\u0435\u0440\u0436\u0434\u0435\u043D\u0430, source \u2192 ${source}`,
@@ -2997,7 +3188,7 @@ function warnAboutSweep({ blockingFiles, conflicts, invalid: invalid2 }, message
2997
3188
 
2998
3189
  // src/core/settle-language.ts
2999
3190
  async function settleLanguageReportingProblems(root, env, warn2) {
3000
- const { language, invalidSettingsFile, saveFailure } = await settleLanguage(root, env);
3191
+ const { language, invalidSettingsFile, saveFailure } = await settleLanguage(root, env, warnPathErrors(warn2));
3001
3192
  const messages = coreMessages(language);
3002
3193
  const file = settingsFilePath(root);
3003
3194
  if (invalidSettingsFile) warn2(messages.settingsFileInvalid(file));
@@ -3132,7 +3323,7 @@ ${" ".repeat(head.length)}`;
3132
3323
  }
3133
3324
 
3134
3325
  // src/cli/lookups.ts
3135
- import { basename as basename7, dirname as dirname6 } from "node:path";
3326
+ import { basename as basename8 } from "node:path";
3136
3327
 
3137
3328
  // src/core/check/project-repo.ts
3138
3329
  import { join as join12 } from "node:path";
@@ -3175,6 +3366,8 @@ var runFile = promisify(execFile2);
3175
3366
  var GIT_OUTPUT_LIMIT = 64 * BYTES_PER_MEBIBYTE;
3176
3367
  var GREP_NO_MATCH_EXIT = 1;
3177
3368
  var GIT_PROCESS_LIMIT = 8;
3369
+ var FULL_OBJECT_ID = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/;
3370
+ var FOUND_OBJECT_FIELDS = 3;
3178
3371
  var gitProcessSlot = createLimiter(GIT_PROCESS_LIMIT);
3179
3372
  var runGitOutcome = (repo, args, input) => gitProcessSlot(async () => {
3180
3373
  try {
@@ -3201,6 +3394,9 @@ function outputLine(stdout) {
3201
3394
  const line = stdout?.trim();
3202
3395
  return line === void 0 || line === "" ? null : line;
3203
3396
  }
3397
+ function commitHashOf(line) {
3398
+ return line !== null && FULL_OBJECT_ID.test(line) ? line : null;
3399
+ }
3204
3400
  function outputLines(stdout) {
3205
3401
  return stdout?.split("\n").filter((line) => line !== "") ?? null;
3206
3402
  }
@@ -3224,22 +3420,37 @@ function isChildProcessFailure(error) {
3224
3420
  function gitArgs(repo, args) {
3225
3421
  return ["-C", repo, "--no-optional-locks", "--no-literal-pathspecs", "-c", "core.quotePath=false", "-c", "diff.suppressBlankEmpty=false", ...args];
3226
3422
  }
3423
+ async function objectIds(git, repo, objectNames) {
3424
+ const names = [...new Set(objectNames)];
3425
+ if (names.length === 0) return /* @__PURE__ */ new Map();
3426
+ if (names.some((name) => name.includes("\n"))) return null;
3427
+ const output = await git(repo, ["cat-file", "--batch-check"], names.map((name) => `${name}
3428
+ `).join(""));
3429
+ if (output === null) return null;
3430
+ const lines = output.split("\n");
3431
+ return new Map(
3432
+ names.flatMap((name, index) => {
3433
+ const fields = lines[index]?.split(" ") ?? [];
3434
+ const id = fields[0] ?? "";
3435
+ return fields.length === FOUND_OBJECT_FIELDS && FULL_OBJECT_ID.test(id) ? [[name, id]] : [];
3436
+ })
3437
+ );
3438
+ }
3227
3439
  function resolveCommits(git, repo, revisions) {
3228
- return resolveObjects(git, repo, revisions, "commit");
3440
+ return resolveObjects(git, repo, revisions, "commit", commitHashOf);
3229
3441
  }
3230
3442
  function resolveTrees(git, repo, revisions) {
3231
- return resolveObjects(git, repo, revisions, "tree");
3443
+ return resolveObjects(git, repo, revisions, "tree", (objectName) => objectName);
3232
3444
  }
3233
- async function resolveObjects(git, repo, revisions, type) {
3234
- if (revisions.length === 0) return /* @__PURE__ */ new Map();
3235
- const output = await git(repo, ["cat-file", "--batch-check"], revisions.map((revision) => `${revision}^{${type}}
3236
- `).join(""));
3237
- if (output === null) return null;
3238
- const lines = output.split("\n");
3445
+ async function resolveObjects(git, repo, revisions, type, nameOf) {
3446
+ const peeled = (revision) => `${revision}^{${type}}`;
3447
+ const ids = await objectIds(git, repo, revisions.map(peeled));
3448
+ if (ids === null) return null;
3239
3449
  return new Map(
3240
- revisions.flatMap((revision, index) => {
3241
- const [objectName = "", objectType] = lines[index]?.split(" ") ?? [];
3242
- return objectType === type ? [[revision, objectName]] : [];
3450
+ revisions.flatMap((revision) => {
3451
+ const id = ids.get(peeled(revision));
3452
+ const name = id === void 0 ? null : nameOf(id);
3453
+ return name === null ? [] : [[revision, name]];
3243
3454
  })
3244
3455
  );
3245
3456
  }
@@ -3265,6 +3476,11 @@ function anchorOf(text, source) {
3265
3476
  if (span2 === null || window === null) return null;
3266
3477
  return `${hashLines(lines.slice(window.from - 1, window.to))}@${window.from}-${window.to}/${hashLines(lines.slice(span2.first - 1, span2.last))}`;
3267
3478
  }
3479
+ function codeStateOf(text, source) {
3480
+ const anchor = anchorOf(text, source);
3481
+ const parsed = anchor === null ? null : parseAnchor(anchor);
3482
+ return parsed === null ? void 0 : `${parsed.hash}/${parsed.linesHash}`;
3483
+ }
3268
3484
  function windowMatches(text, source, anchor) {
3269
3485
  const current = anchorOf(text, source);
3270
3486
  const expected = parseAnchor(anchor);
@@ -3365,26 +3581,30 @@ function hashLines(lines) {
3365
3581
  function isReviewable(task) {
3366
3582
  return task.type === "task" && (task.status === "backlog" || task.status === "blocked");
3367
3583
  }
3368
- function sourcePaths(tasks) {
3369
- return [...new Set(tasks.flatMap((task) => task.source === void 0 ? [] : [sourcePath(task.source)]))];
3370
- }
3371
3584
  function reviewMark(task) {
3372
3585
  const verified = task.verified === void 0 ? Number.NEGATIVE_INFINITY : Date.parse(task.verified);
3373
3586
  return Math.max(Date.parse(task.created), verified);
3374
3587
  }
3375
- function taskRef(task) {
3376
- return { id: task.id, title: task.title };
3588
+ function creationOrigin(task, origins) {
3589
+ return task.verified === void 0 ? origins.get(task.id) : void 0;
3590
+ }
3591
+ async function checkoutAtMark(task, origins, headCommitAt) {
3592
+ return creationOrigin(task, origins)?.commit ?? headCommitAt(new Date(reviewMark(task)));
3377
3593
  }
3378
3594
 
3379
3595
  // src/core/check/source-commits.ts
3380
- function changesSince(facts, path, mark) {
3381
- const commits = commitsTouchingSince(facts.commits, path, mark);
3596
+ function changesSinceMark({ facts, late }, task, path) {
3597
+ const mark = reviewMark(task);
3598
+ const commits = [...commitsTouchingSince(facts.commits, path, mark), ...late.get(task.id) ?? []];
3382
3599
  const uncommitted = [...facts.dirtyModifiedAt].some(([file, modifiedAt]) => isWithin(file, path) && modifiedAt > mark);
3383
3600
  return { commits, uncommitted };
3384
3601
  }
3385
3602
  function commitsTouchingSince(commits, path, mark) {
3386
3603
  return commitsAfter(commits, mark).filter((commit) => touches(commit, path));
3387
3604
  }
3605
+ function commitsTouchingUntil(commits, path, mark) {
3606
+ return commits.filter((commit) => Date.parse(commit.date) <= mark && touches(commit, path));
3607
+ }
3388
3608
  function commitsAfter(commits, mark) {
3389
3609
  return commits.filter((commit) => Date.parse(commit.date) > mark);
3390
3610
  }
@@ -3397,21 +3617,21 @@ var MAX_COMMITS = 3;
3397
3617
  function anchorStates(tasks, facts) {
3398
3618
  return new Map(tasks.map((task) => [task.id, anchorState(task, facts)]));
3399
3619
  }
3400
- function codeReview(tasks, facts, knownCommits, anchors) {
3401
- const reviewed = tasks.map((task) => ({ task, anchor: anchors.get(task.id) ?? anchorState(task, facts) }));
3402
- const candidates = reviewed.flatMap(({ task, anchor }) => codeCandidate(task, anchor, facts, knownCommits.get(task.id)));
3403
- const plans = reviewed.flatMap(({ task, anchor }) => anchorPlan(task, anchor, facts));
3620
+ function codeReview(tasks, history, knownCommits, anchors) {
3621
+ const reviewed = tasks.map((task) => ({ task, anchor: anchors.get(task.id) ?? anchorState(task, history.facts) }));
3622
+ const candidates = reviewed.flatMap(({ task, anchor }) => codeCandidate(task, anchor, history, knownCommits.get(task.id)));
3623
+ const plans = reviewed.flatMap(({ task, anchor }) => anchorPlan(task, anchor, history.facts));
3404
3624
  return { candidates, plans };
3405
3625
  }
3406
- function codeCandidate(task, anchor, facts, knownCommits = /* @__PURE__ */ new Set()) {
3626
+ function codeCandidate(task, anchor, history, knownCommits = /* @__PURE__ */ new Set()) {
3407
3627
  if (task.source === void 0) return [];
3628
+ const { facts } = history;
3408
3629
  const path = sourcePath(task.source);
3409
- const mark = reviewMark(task);
3410
3630
  if (!facts.existing.has(path)) {
3411
- return presenceOffDisk(path, facts.branches) === "missing" ? [{ kind: "source-missing", task: taskRef(task), path, renamedTo: followRenames(path, facts.renames, mark) }] : [];
3631
+ return presenceOffDisk(path, facts.branches) === "missing" ? [{ kind: "source-missing", task: taskRef(task), path, renamedTo: followRenames(path, facts.renames, reviewMark(task)) }] : [];
3412
3632
  }
3413
3633
  if (anchor.kind === "same" || anchor.kind === "moved") return [];
3414
- const { commits: changed, uncommitted } = changesSince(facts, path, mark);
3634
+ const { commits: changed, uncommitted } = changesSinceMark(history, task, path);
3415
3635
  const commits = changed.filter((commit) => !knownCommits.has(commit.sha));
3416
3636
  if (anchor.kind === "none" && commits.length === 0 && !uncommitted) return [];
3417
3637
  const method = anchor.kind === "changed" ? "anchor" : "file";
@@ -3477,13 +3697,8 @@ function followRenames(path, commits, mark) {
3477
3697
  function commitRef(commit) {
3478
3698
  return { sha: commit.shortSha, subject: commit.subject };
3479
3699
  }
3480
-
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;
3700
+ function taskRef(task) {
3701
+ return { id: task.id, title: task.title };
3487
3702
  }
3488
3703
 
3489
3704
  // src/core/check/diff-hunks.ts
@@ -3565,7 +3780,7 @@ function walkHunkLine(hunk, line, shape) {
3565
3780
  const hunkLine = hunkLineOf(line);
3566
3781
  if (hunkLine === null) return;
3567
3782
  const changed = hunkLine.kind !== "context";
3568
- if (changed && !hunk.changing) shape.changeStarts.push(hunk.oldLine);
3783
+ if (changed && !hunk.changing) shape.changeStarts.push({ line: hunk.oldLine, insertion: hunkLine.kind === "added" });
3569
3784
  if (changed) shape.changedText += `${line}
3570
3785
  `;
3571
3786
  hunk.changing = changed;
@@ -3659,36 +3874,53 @@ function baseText(hunks, currentText) {
3659
3874
  }
3660
3875
 
3661
3876
  // src/core/check/repo-facts.ts
3662
- import { isAbsolute, join as join11, normalize, sep } from "node:path";
3663
- var SAFE_DIRECTORY_HINT = "safe.directory";
3877
+ import { isAbsolute as isAbsolute2, join as join11, normalize, sep as sep2 } from "node:path";
3878
+
3879
+ // src/core/remembered.ts
3880
+ function remembered(cache, key, compute) {
3881
+ if (cache.has(key)) return cache.get(key);
3882
+ const value = compute();
3883
+ cache.set(key, value);
3884
+ return value;
3885
+ }
3886
+
3887
+ // src/core/check/repo-facts.ts
3888
+ var TRUST_COMMAND = /^git config .*safe\.directory/;
3664
3889
  var DIFF_LINE_LIMIT = 80;
3665
3890
  var REFLOG_MOMENT = /\{(\d+)\}$/;
3666
3891
  var STATUS_CODE_WIDTH = 3;
3667
3892
  var RENAME_OR_COPY = /^[RC]/;
3893
+ var DELETED_FILE_HEADER = /^deleted file mode /m;
3668
3894
  var ORIGINAL_PATH_FOLLOWS = /^(?:[RC].|.[RC])/;
3669
3895
  var LOG_FORMAT = `--format=${RECORD}%H${FIELD}%h${FIELD}%cI${FIELD}%P${FIELD}%s`;
3670
3896
  var FACTS_HISTORY_OPTIONS = ["--full-history"];
3671
3897
  async function locateRepo(repo) {
3672
3898
  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" };
3899
+ if (location.status === "exited") {
3900
+ const trustCommand = trustCommandIn(location.stderr);
3901
+ return trustCommand === void 0 ? { history: "not-a-repo" } : { history: "unsafe-repo", trustCommand };
3902
+ }
3674
3903
  if (location.status === "unfinished") return { history: "unreadable" };
3675
3904
  const [prefix = "", head = ""] = location.stdout.split("\n").map((line) => line.trim());
3676
3905
  return { history: "read", prefix, hasCommits: head !== "" };
3677
3906
  }
3907
+ function trustCommandIn(stderr) {
3908
+ return stderr.split("\n").map((line) => line.trim()).find((line) => TRUST_COMMAND.test(line));
3909
+ }
3678
3910
  async function collectRepoFacts(repo, pathMarks) {
3679
3911
  const paths = [...pathMarks.keys()];
3680
3912
  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);
3913
+ const withoutHistory = (noHistory) => ({ ...noHistory, commits: [], renames: [], dirtyModifiedAt: /* @__PURE__ */ new Map(), branches: unknownBranches(noHistory.history), ...files });
3914
+ if (location.history !== "read") return withoutHistory(location);
3683
3915
  const { prefix, hasCommits } = location;
3684
3916
  const missing = paths.filter((path) => !files.existing.has(path) && !files.unreadable.has(path));
3685
3917
  const [log, renames, status, branches] = await Promise.all([
3686
- hasCommits ? pathLog(repo, earliestMark(pathMarks, paths), paths) : "",
3687
- hasCommits && missing.length > 0 ? runGit(repo, [...logArgs(earliestMark(pathMarks, missing)), "--diff-filter=R"]) : "",
3918
+ hasCommits && paths.length > 0 ? pathLog(repo, [sinceEarliestMark(pathMarks, paths)], paths) : "",
3919
+ hasCommits && missing.length > 0 ? runGit(repo, [...logArgs([sinceEarliestMark(pathMarks, missing)]), "--diff-filter=R"]) : "",
3688
3920
  runGit(repo, ["status", "--porcelain=v1", "-z", "--untracked-files=no"]),
3689
3921
  branchHistoryOf(repo, location, missing)
3690
3922
  ]);
3691
- if (log === null || renames === null || status === null) return withoutHistory("unreadable");
3923
+ if (log === null || renames === null || status === null) return withoutHistory({ history: "unreadable" });
3692
3924
  const dirty = withinRepo(parseStatus(status), prefix);
3693
3925
  return { history: "read", commits: parseLog(log), renames: parseLog(renames), dirtyModifiedAt: await modificationTimes(repo, dirty), branches, ...files };
3694
3926
  }
@@ -3700,16 +3932,20 @@ async function branchHistoryOf(repo, location, paths) {
3700
3932
  function unknownBranches(history) {
3701
3933
  return history === "not-a-repo" ? { kind: "no-repo" } : { kind: "unreadable" };
3702
3934
  }
3703
- function earliestMark(marks, paths) {
3704
- return new Date(Math.min(...paths.flatMap((path) => marks.get(path) ?? [])));
3935
+ function sinceEarliestMark(marks, paths) {
3936
+ return `--since=${new Date(Math.min(...paths.flatMap((path) => marks.get(path) ?? []))).toISOString()}`;
3705
3937
  }
3706
- function logArgs(since) {
3707
- return ["log", "--relative", `--since=${since.toISOString()}`, LOG_FORMAT, "--name-status", "-M", "--diff-merges=first-parent", ...FACTS_HISTORY_OPTIONS, "-z"];
3938
+ function logArgs(selection) {
3939
+ return ["log", ...selection, "--relative", LOG_FORMAT, "--name-status", "-M", "--diff-merges=first-parent", ...FACTS_HISTORY_OPTIONS, "-z"];
3708
3940
  }
3709
- async function pathLog(repo, since, paths) {
3941
+ async function pathLog(repo, selection, paths) {
3710
3942
  const inside = paths.filter(isInsideRepo);
3711
3943
  if (inside.length === 0) return "";
3712
- return runGit(repo, [...logArgs(since), "--", ...literalPathspecs(inside)]);
3944
+ return runGit(repo, [...logArgs(selection), "--", ...literalPathspecs(inside)]);
3945
+ }
3946
+ async function mainlineCommitsOff(repo, base, paths) {
3947
+ const log = await pathLog(repo, ["--first-parent", `${base}..HEAD`], paths);
3948
+ return log === null ? null : parseLog(log);
3713
3949
  }
3714
3950
  async function committedPaths(repo, revisions, paths) {
3715
3951
  const inside = paths.filter(isInsideRepo);
@@ -3719,7 +3955,7 @@ async function committedPaths(repo, revisions, paths) {
3719
3955
  }
3720
3956
  function isInsideRepo(path) {
3721
3957
  const normalized = normalize(path);
3722
- return normalized !== "." && !isAbsolute(normalized) && normalized !== ".." && !normalized.startsWith(`..${sep}`);
3958
+ return normalized !== "." && !isAbsolute2(normalized) && normalized !== ".." && !normalized.startsWith(`..${sep2}`);
3723
3959
  }
3724
3960
  function diffsSince(repo, git = runGit, diffFrom = diffsFrom(repo, git)) {
3725
3961
  const bases = /* @__PURE__ */ new Map();
@@ -3729,19 +3965,25 @@ function diffsSince(repo, git = runGit, diffFrom = diffsFrom(repo, git)) {
3729
3965
  return base === null ? null : diffFrom(path, base);
3730
3966
  };
3731
3967
  }
3732
- function headsAt(repo, git = runGit) {
3968
+ function headCommitsAt(repo) {
3733
3969
  let moves = null;
3970
+ return async (moment) => {
3971
+ moves ??= headMovesNewestFirst(repo);
3972
+ return (await moves).find((move) => move.at <= moment.getTime())?.commit ?? null;
3973
+ };
3974
+ }
3975
+ function ancestorsOfHead(repo) {
3734
3976
  const ancestors = /* @__PURE__ */ new Map();
3977
+ return (commit) => remembered(ancestors, commit, async () => await runGit(repo, ["merge-base", "--is-ancestor", commit, "HEAD"]) !== null);
3978
+ }
3979
+ function headsAt(headCommitAt, isOnThisLine) {
3735
3980
  return async (moment) => {
3736
- moves ??= headMovesNewestFirst(repo, git);
3737
- const commit = (await moves).find((move) => move.at <= moment.getTime())?.commit;
3738
- if (commit === void 0) return null;
3739
- const onThisLine = await remembered(ancestors, commit, async () => await git(repo, ["merge-base", "--is-ancestor", commit, "HEAD"]) !== null);
3740
- return { commit, onThisLine };
3981
+ const commit = await headCommitAt(moment);
3982
+ return commit === null ? null : { commit, onThisLine: await isOnThisLine(commit) };
3741
3983
  };
3742
3984
  }
3743
- async function headMovesNewestFirst(repo, git) {
3744
- const reflog = await git(repo, ["log", "--walk-reflogs", "--date=unix", `--format=%H${FIELD}%gd`, "HEAD"]);
3985
+ async function headMovesNewestFirst(repo) {
3986
+ const reflog = await runGit(repo, ["log", "--walk-reflogs", "--date=unix", `--format=%H${FIELD}%gd`, "HEAD"]);
3745
3987
  return (reflog ?? "").split("\n").flatMap((line) => {
3746
3988
  const [commit = "", selector = ""] = line.split(FIELD);
3747
3989
  const seconds = REFLOG_MOMENT.exec(selector)?.[1];
@@ -3750,17 +3992,17 @@ async function headMovesNewestFirst(repo, git) {
3750
3992
  }
3751
3993
  function diffsFrom(repo, git = runGit) {
3752
3994
  const diffs = /* @__PURE__ */ new Map();
3995
+ const tracked = /* @__PURE__ */ new Map();
3996
+ const isConfirmedTracked = (path) => remembered(tracked, path, async () => outputLine(await git(repo, ["ls-files", "--", ...literalPathspecs([path])])) !== null);
3753
3997
  return (path, commit) => remembered(diffs, `${commit} ${path}`, async () => {
3754
3998
  const diff = await git(repo, ["diff", ...PARSED_DIFF_OPTIONS, "--unified=3", commit, "--", ...literalPathspecs([path])]);
3755
3999
  if (diff === null) return null;
3756
- if (diff === "" && !await isConfirmedTracked(repo, path, git)) return { excerpt: void 0, changed: null, hunks: null };
4000
+ const mayBeUntracked = diff === "" || DELETED_FILE_HEADER.test(diff);
4001
+ if (mayBeUntracked && !await isConfirmedTracked(path)) return { excerpt: void 0, changed: null, hunks: null };
3757
4002
  const hunks = parseHunks(diff);
3758
4003
  return { excerpt: excerptOf(diff), changed: hunks === null ? null : changedRanges(hunks), hunks };
3759
4004
  });
3760
4005
  }
3761
- async function isConfirmedTracked(repo, path, git) {
3762
- return outputLine(await git(repo, ["ls-files", "--", ...literalPathspecs([path])])) !== null;
3763
- }
3764
4006
  function excerptOf(diff) {
3765
4007
  if (diff.trim() === "") return void 0;
3766
4008
  const lines = diff.trimEnd().split("\n");
@@ -3771,7 +4013,7 @@ async function sourceFiles(repo, paths) {
3771
4013
  const recordUnreadable = (path, error) => {
3772
4014
  unreadable.set(path, error);
3773
4015
  };
3774
- const read = await Promise.all(paths.map((path) => attemptReportingFailure(path, (relative5) => sourceFile(repo, relative5), recordUnreadable)));
4016
+ const read = await Promise.all(paths.map((path) => attemptReportingFailure(path, (relative4) => sourceFile(repo, relative4), recordUnreadable)));
3775
4017
  const present = read.flatMap((file) => file?.kind === "present" ? [file] : []);
3776
4018
  return {
3777
4019
  existing: new Set(present.map((file) => file.path)),
@@ -3843,20 +4085,19 @@ async function modificationTimes(repo, paths) {
3843
4085
  // src/core/check/current-source.ts
3844
4086
  var LATER_COMMITS_TO_SEARCH = 5;
3845
4087
  var UNTRACED = { kind: "untraced" };
3846
- function repoDiffs(repo) {
4088
+ function repoDiffs(repo, origins) {
3847
4089
  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)));
4090
+ const since = diffsSince(repo, runGit, from);
4091
+ const headCommitAt = headCommitsAt(repo);
4092
+ const isOnThisLine = ancestorsOfHead(repo);
4093
+ const sinceTaskMark = async (task, path) => {
4094
+ const checkout = await checkoutAtMark(task, origins, headCommitAt);
4095
+ return checkout !== null && await isOnThisLine(checkout) ? from(path, checkout) : since(path, new Date(reviewMark(task)));
3856
4096
  };
4097
+ return { since, from, headAt: headsAt(headCommitAt, isOnThisLine), sinceTaskMark };
3857
4098
  }
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)])));
4099
+ async function traceSources(tasks, history, diffs) {
4100
+ return new Map(await Promise.all(tasks.map(async (task) => [task.id, await traceSource(task, history, diffs)])));
3860
4101
  }
3861
4102
  function currentSourcesOf(traces) {
3862
4103
  return new Map([...traces].map(([id, trace]) => [id, currentOf(trace)]));
@@ -3864,17 +4105,17 @@ function currentSourcesOf(traces) {
3864
4105
  async function currentSourceIn(repo, task) {
3865
4106
  if (task.source === void 0) return null;
3866
4107
  const facts = await collectRepoFacts(repo, /* @__PURE__ */ new Map([[sourcePath(task.source), reviewMark(task)]]));
3867
- return currentOf(await traceSource(task, facts, repoDiffs(repo)));
4108
+ return currentOf(await traceSource(task, { facts, late: /* @__PURE__ */ new Map() }, repoDiffs(repo, /* @__PURE__ */ new Map())));
3868
4109
  }
3869
4110
  function currentOf(trace) {
3870
4111
  return trace.kind === "traced" ? trace.current : null;
3871
4112
  }
3872
- async function traceSource(task, facts, diffs) {
4113
+ async function traceSource(task, history, diffs) {
3873
4114
  const { source, anchor } = task;
3874
4115
  if (source === void 0 || !hasLines(source)) return UNTRACED;
3875
- const text = facts.texts.get(sourcePath(source));
4116
+ const text = history.facts.texts.get(sourcePath(source));
3876
4117
  if (text === void 0) return UNTRACED;
3877
- const { commits, uncommitted } = changesSince(facts, sourcePath(source), reviewMark(task));
4118
+ const { commits, uncommitted } = changesSinceMark(history, task, sourcePath(source));
3878
4119
  const fileUntouched = commits.length === 0 && !uncommitted;
3879
4120
  if (fileUntouched && (anchor === void 0 || windowMatches(text, source, anchor))) return { kind: "traced", current: source, linesChanged: false };
3880
4121
  const traced = { ...task, source };
@@ -3896,8 +4137,9 @@ async function referenceOf(task, text, laterCommits, diffs) {
3896
4137
  const head = anchor === void 0 ? null : await diffs.headAt(mark);
3897
4138
  const headAtMark = async () => head?.onThisLine === true ? diffs.from(path, head.commit) : null;
3898
4139
  const lastCommitBeforeMark = () => diffs.since(path, mark);
4140
+ const sinceTaskMark = () => diffs.sinceTaskMark(task, path);
3899
4141
  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];
4142
+ const references = anchor === void 0 ? [sinceTaskMark] : [headAtMark, lastCommitBeforeMark, ...afterMark];
3901
4143
  const unmatched = head?.onThisLine === false ? { kind: "not-on-branch" } : { kind: "untraced" };
3902
4144
  let search = { kind: "untraced" };
3903
4145
  for (const diffFromReference of references) {
@@ -3921,18 +4163,20 @@ async function sourcePresence(repo, source, onUnreadable) {
3921
4163
  const path = sourcePath(source);
3922
4164
  const onDisk = await attemptReportingFailure(join12(repo, path), fileExists, onUnreadable);
3923
4165
  const presentOrUnreadable = onDisk !== false;
3924
- if (presentOrUnreadable) return "present";
3925
- return presenceOffDisk(path, await branchHistoryOf(repo, await locateRepo(repo), [path]));
4166
+ if (presentOrUnreadable) return { kind: "present" };
4167
+ const location = await locateRepo(repo);
4168
+ if (location.history === "unsafe-repo") return { kind: "unsafe-repo", trustCommand: location.trustCommand };
4169
+ return { kind: presenceOffDisk(path, await branchHistoryOf(repo, location, [path])) };
3926
4170
  }
3927
4171
  async function relocatedSource(repo, task) {
3928
4172
  const current = repo === void 0 ? null : await currentSourceIn(repo, task);
3929
4173
  return current === null || current === task.source ? void 0 : current;
3930
4174
  }
3931
- async function findRepo(project, { workingRoots, ...lookup }) {
3932
- return (await projectCheckout(project, workingRoots, lookup))?.path;
4175
+ async function findRepo(project, { workingRoots, ...context }) {
4176
+ return (await projectCheckout(project, workingRoots, context))?.path;
3933
4177
  }
3934
- async function projectCheckout(project, workingRoots, lookup) {
3935
- const repo = await firstExistingRepo(project, lookup);
4178
+ async function projectCheckout(project, workingRoots, context) {
4179
+ const repo = await firstExistingRepo(project, context);
3936
4180
  if (repo === void 0) return void 0;
3937
4181
  if (workingRoots === null || workingRoots.main !== realpathOrNull(repo)) return { path: repo, linkedWorktree: false };
3938
4182
  return { path: workingRoots.worktree, linkedWorktree: workingRoots.worktree !== workingRoots.main };
@@ -3952,9 +4196,8 @@ import { mkdir as mkdir3 } from "node:fs/promises";
3952
4196
  import { basename as basename6, join as join13 } from "node:path";
3953
4197
  var MAX_ID_ATTEMPTS = 20;
3954
4198
  async function createTask(root, request) {
3955
- const { project, existingTasks: existingTasks2 } = request;
4199
+ const { project, index } = request;
3956
4200
  const dir = join13(root, project.id);
3957
- const index = buildIndex(existingTasks2);
3958
4201
  for (let attempt = 0; attempt < MAX_ID_ATTEMPTS; attempt++) {
3959
4202
  const id = formatId(project.prefix, await nextTaskNumber(dir, project, request.onError));
3960
4203
  const path = join13(dir, taskFileName(id));
@@ -3964,7 +4207,7 @@ async function createTask(root, request) {
3964
4207
  const problems3 = integrityErrors(task, index);
3965
4208
  if (problems3.length > 0) return invalid(problems3);
3966
4209
  try {
3967
- await createFileAtomic(path, text);
4210
+ await createFileAtomic(path, text, { onErrorAfterPublish: request.onError });
3968
4211
  await appendJournal(dir, [createdEvent(task, request.now, request.via, request.provenance)], request.onError);
3969
4212
  return { ok: true, task, reopenedEpic: await reopenEpicOfOpenedTask(index, { before: void 0, after: task }, request) };
3970
4213
  } catch (error) {
@@ -3973,11 +4216,11 @@ async function createTask(root, request) {
3973
4216
  }
3974
4217
  return invalid([{ code: "id-exhausted", attempts: MAX_ID_ATTEMPTS }]);
3975
4218
  }
3976
- async function createProject(root, repoRoot, existingProjects) {
4219
+ async function createProject(root, repoRoot, existingProjects, onError) {
3977
4220
  for (let attempt = 1; ; attempt++) {
3978
4221
  const { id, path, text } = await draftProjectFile(root, repoRoot, existingProjects);
3979
4222
  try {
3980
- await createFileAtomic(path, text);
4223
+ await createFileAtomic(path, text, { onErrorAfterPublish: onError });
3981
4224
  const parsed = parseProjectFile(text, { id, path });
3982
4225
  if (!parsed.ok) throw new Error(`${path}: ${parsed.problems.map((problem3) => problem3.code).join(", ")}`);
3983
4226
  return parsed.value;
@@ -3992,7 +4235,7 @@ async function createProject(root, repoRoot, existingProjects) {
3992
4235
  async function draftProjectFile(root, repoRoot, existingProjects) {
3993
4236
  const name = basename6(repoRoot);
3994
4237
  const entries = await listDir(root);
3995
- const joinable = await Promise.all(entries.map((entry) => entry.isDirectory() && isJoinableProjectDir(join13(root, entry.name), repoRoot)));
4238
+ const joinable = await Promise.all(entries.map((entry) => entry.isDirectory() ? isJoinableProjectDir(join13(root, entry.name), repoRoot) : Promise.resolve(false)));
3996
4239
  const id = deriveProjectId(name, new Set(entries.filter((_, index) => !joinable[index]).map((entry) => entry.name)));
3997
4240
  const prefixesOnDisk = await Promise.all(entries.filter((entry) => entry.isDirectory()).map((entry) => takenPrefixes(join13(root, entry.name))));
3998
4241
  const prefix = derivePrefix(name, /* @__PURE__ */ new Set([...existingProjects.map((project) => project.prefix), ...prefixesOnDisk.flat()]));
@@ -4057,7 +4300,7 @@ function draftTask(id, path, { project, input, now }) {
4057
4300
  }
4058
4301
 
4059
4302
  // src/core/store/resolve-project.ts
4060
- import { isAbsolute as isAbsolute2, relative, resolve as resolve2, sep as sep2 } from "node:path";
4303
+ import { basename as basename7, dirname as dirname6, resolve as resolve2 } from "node:path";
4061
4304
  var REPO_ROOT_TTL_MS = 6e4;
4062
4305
  var SHOW_ROOTS = ["rev-parse", "--show-toplevel", "--git-dir", "--git-common-dir"];
4063
4306
  var LIST_WORKTREES = ["worktree", "list", "--porcelain"];
@@ -4078,7 +4321,7 @@ function cachedRepoRoots({ onUnreadable, ttlMs = REPO_ROOT_TTL_MS, now = Date.no
4078
4321
  const cached = known.get(dir);
4079
4322
  if (cached !== void 0 && isFresh(cached)) return cached.roots;
4080
4323
  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);
4324
+ const roots = attemptReportingFailure(dir, async (path) => await findGitRootsAsync(path) ?? "not-in-repo", onUnreadable).then((found) => found ?? "unreadable");
4082
4325
  known.set(dir, { roots, checkedAt: now() });
4083
4326
  return roots;
4084
4327
  };
@@ -4113,35 +4356,65 @@ function readGitRoots(dir, onUnreadable) {
4113
4356
  function repoRootsOf(dirRoots) {
4114
4357
  return typeof dirRoots === "string" ? null : dirRoots;
4115
4358
  }
4116
- function findProjectForDir(projects, dir, dirRoots, places) {
4117
- const roots = matchingRoots(dir, dirRoots, places);
4118
- return roots === null ? void 0 : findProjectForRoots(projects, roots, places);
4359
+ function lookupProjectForDir(known, dir, dirRoots, context) {
4360
+ const roots = matchingRoots(dir, dirRoots, context);
4361
+ if (roots === null) return { broken: [] };
4362
+ const repo = repoRootsOf(dirRoots);
4363
+ return lookupProject(known, { roots, repoDirName: repo === null ? void 0 : projectIdBase(basename7(repo.main)) }, context);
4364
+ }
4365
+ function lookupProject({ projects, errors }, { roots, repoDirName }, context) {
4366
+ const coveredLength = (repos) => closestCoveringRepo(repos, roots, context)?.length ?? 0;
4367
+ const coverageOf = (error) => {
4368
+ const namedAfterRepo = error.claimedRepos.length === 0 && error.projectId === repoDirName;
4369
+ return { error, length: namedAfterRepo ? roots.main.length : coveredLength(error.claimedRepos) };
4370
+ };
4371
+ const covering = unparsedProjectFiles(errors).map(coverageOf).filter(({ length }) => length > 0);
4372
+ const project = findProjectForRoots(projects, roots, context);
4373
+ const projectLength = project === void 0 ? 0 : coveredLength(project.repos);
4374
+ if (project !== void 0 && covering.every(({ length }) => length <= projectLength)) return { project };
4375
+ return { broken: covering.map(({ error }) => error) };
4119
4376
  }
4120
- function matchingRoots(dir, dirRoots, places) {
4377
+ function matchingRoots(dir, dirRoots, context) {
4121
4378
  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;
4379
+ return dirRoots === "not-in-repo" ? attemptReportingFailureSync(dir, plainDirRoots, context.onUnreadable) : dirRoots;
4132
4380
  }
4133
- function anyRepoCovers(repos, roots, places) {
4134
- return repos.some((repo) => {
4135
- const repoPath = resolvedRepo(repo, places);
4136
- return repoPath !== null && repoCovers(repoPath, roots);
4381
+ function findProjectForRoots(projects, roots, context) {
4382
+ const matches = projects.flatMap((project) => {
4383
+ const repoPath = closestCoveringRepo(project.repos, roots, context);
4384
+ return repoPath === void 0 ? [] : [{ project, repoPath }];
4137
4385
  });
4386
+ return matches.sort((a, b) => b.repoPath.length - a.repoPath.length || Number(b.project.active) - Number(a.project.active))[0]?.project;
4387
+ }
4388
+ function pathFromProjectRepo(project, roots, context, path) {
4389
+ const repoPath = closestCoveringRepo(project.repos, roots, context);
4390
+ if (repoPath === void 0) return null;
4391
+ const enclosingRootsOf = (dir) => repoRootsOf(readGitRoots(dirname6(dir), context.onUnreadable));
4392
+ return relativeInside(repoPath, asInProjectRepoCheckout(path, roots, { repoPath, enclosingRootsOf }));
4393
+ }
4394
+ function asInProjectRepoCheckout(path, roots, { repoPath, enclosingRootsOf }) {
4395
+ const passedMains = /* @__PURE__ */ new Set();
4396
+ let enclosing = roots;
4397
+ let translated = path;
4398
+ while (enclosing !== null && isSameOrInside(enclosing.main, repoPath) && !passedMains.has(enclosing.main)) {
4399
+ passedMains.add(enclosing.main);
4400
+ translated = asInMainCheckout(enclosing, translated);
4401
+ enclosing = enclosing.main === repoPath ? null : enclosingRootsOf(enclosing.main);
4402
+ }
4403
+ return translated;
4404
+ }
4405
+ function asInMainCheckout({ worktree, main }, path) {
4406
+ const inWorktree = relativeInside(worktree, path);
4407
+ return inWorktree === null ? path : resolve2(main, inWorktree);
4408
+ }
4409
+ function closestCoveringRepo(repos, roots, context) {
4410
+ const covering = repos.map((repo) => resolvedRepo(repo, context)).filter((repoPath) => repoPath !== null && repoCovers(repoPath, roots));
4411
+ return covering.sort((a, b) => b.length - a.length)[0];
4138
4412
  }
4139
4413
  function repoCovers(repoPath, { worktree, main }) {
4140
4414
  return isSameOrInside(worktree, repoPath) || isSameOrInside(main, repoPath);
4141
4415
  }
4142
4416
  function isSameOrInside(path, container) {
4143
- const relation = relative(container, path);
4144
- return relation === "" || !isAbsolute2(relation) && relation.split(sep2)[0] !== "..";
4417
+ return relativeInside(container, path) !== null;
4145
4418
  }
4146
4419
  function resolvedRepo(repo, { home: home2, onUnreadable }) {
4147
4420
  return attemptReportingFailureSync(expandHome(repo, home2), realpathOrNull, onUnreadable);
@@ -4151,96 +4424,114 @@ function resolvedRepo(repo, { home: home2, onUnreadable }) {
4151
4424
  function warnUnreadableSkipped(warn2, core) {
4152
4425
  return warnPathErrors(warn2, core.unreadableSkipped);
4153
4426
  }
4154
- var placesOfRun = /* @__PURE__ */ new WeakMap();
4155
- function repoPlaces(io) {
4156
- const known = placesOfRun.get(io);
4427
+ var contextOfRun = /* @__PURE__ */ new WeakMap();
4428
+ function repoContext(io) {
4429
+ const known = contextOfRun.get(io);
4157
4430
  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;
4431
+ const context = { home: io.home, onUnreadable: oncePerPath(warnUnreadableSkipped(io.warn, io.core)) };
4432
+ contextOfRun.set(io, context);
4433
+ return context;
4161
4434
  }
4162
4435
  var cwdRootsOfRun = /* @__PURE__ */ new WeakMap();
4163
4436
  function cwdDirRoots(io) {
4164
4437
  const known = cwdRootsOfRun.get(io);
4165
4438
  if (known !== void 0) return known;
4166
- const roots = readGitRoots(io.cwd, repoPlaces(io).onUnreadable);
4439
+ const roots = readGitRoots(io.cwd, repoContext(io).onUnreadable);
4167
4440
  cwdRootsOfRun.set(io, roots);
4168
4441
  return roots;
4169
4442
  }
4170
4443
  function cwdGitRoots(io) {
4171
4444
  return repoRootsOf(cwdDirRoots(io));
4172
4445
  }
4173
- function findProjectForCwd(projects, io) {
4174
- return findProjectForDir(projects, io.cwd, cwdDirRoots(io), repoPlaces(io));
4446
+ function lookupCwdProject(known, io) {
4447
+ return lookupProjectForDir(known, io.cwd, cwdDirRoots(io), repoContext(io));
4448
+ }
4449
+ function cwdBelongsTo(project, known, io) {
4450
+ const lookup = lookupCwdProject(known, io);
4451
+ return "project" in lookup && lookup.project.id === project.id;
4175
4452
  }
4176
4453
  function repoLookup(io) {
4177
- return { ...repoPlaces(io), workingRoots: cwdGitRoots(io) };
4454
+ return { ...repoContext(io), workingRoots: cwdGitRoots(io) };
4178
4455
  }
4179
4456
  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));
4457
+ const presence = await sourcePresence(repo, source, repoContext(io).onUnreadable);
4458
+ const warning = sourcePresenceWarning(io, presence, repo, source);
4459
+ if (warning !== null) io.warn(warning);
4183
4460
  return presence;
4184
4461
  }
4462
+ function sourcePresenceWarning(io, presence, repo, source) {
4463
+ switch (presence.kind) {
4464
+ case "present":
4465
+ return null;
4466
+ case "missing":
4467
+ return io.cli.sourceFileMissing(source);
4468
+ case "unchecked":
4469
+ return io.cli.sourceFileUnchecked(source);
4470
+ case "unsafe-repo":
4471
+ return io.cli.sourceFileUncheckedUnsafeRepo(source, io.core.unsafeRepo(repo, presence.trustCommand));
4472
+ }
4473
+ }
4185
4474
  function findTaskOrWarn(loaded, io, id) {
4186
4475
  const task = loaded.tasks.find((candidate) => candidate.id === id);
4187
4476
  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));
4477
+ io.warn(missingTaskMessage(loaded, io, id));
4190
4478
  return void 0;
4191
4479
  }
4480
+ function missingTaskMessage(loaded, io, id) {
4481
+ if (!ID_PATTERN.test(id)) return io.cli.taskNotFound(id);
4482
+ const fileName = taskFileName(id);
4483
+ const broken = loaded.errors.find((error) => basename8(error.path) === fileName);
4484
+ if (broken) return io.cli.taskFileUnparsed(id, io.core.problems(broken.problems));
4485
+ const hidingProject = unparsedProjectFiles(loaded.errors).find((error) => error.hiddenTasks.includes(id));
4486
+ return hidingProject ? io.cli.taskOfUnparsedProject(id, hidingProject.path, io.core.problems(hidingProject.problems)) : io.cli.taskNotFound(id);
4487
+ }
4192
4488
  function projectOf(loaded, task) {
4193
4489
  return loaded.projects.find((project) => project.id === task.projectId);
4194
4490
  }
4195
- async function findProjectOrWarn(loaded, io, explicitId) {
4196
- const project = findProject(loaded, io, explicitId);
4491
+ function findProjectOrWarn(loaded, io, explicitId) {
4492
+ return explicitId === void 0 ? findCwdProjectOrWarn(loaded, io) : findNamedProjectOrWarn(loaded, io, explicitId);
4493
+ }
4494
+ function findNamedProjectOrWarn(loaded, io, id) {
4495
+ const project = loaded.projects.find((candidate) => candidate.id === id);
4197
4496
  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));
4497
+ const broken = unparsedProjectFileOf(loaded.errors, id);
4498
+ warnUnparsedOrNotFound(io, broken === void 0 ? [] : [broken], io.cli.projectNotFound(id));
4201
4499
  return void 0;
4202
4500
  }
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);
4501
+ function findCwdProjectOrWarn(loaded, io) {
4502
+ const lookup = lookupCwdProject(loaded, io);
4503
+ if ("project" in lookup) return lookup.project;
4504
+ warnUnparsedOrNotFound(io, lookup.broken, io.cli.projectNotFoundForCwd(io.cwd));
4505
+ return void 0;
4506
+ }
4507
+ function warnUnparsedOrNotFound(io, broken, notFound) {
4508
+ if (broken.length > 0) warnUnparsedProjectFiles(io, broken, io.cli.projectFileUnparsed);
4509
+ else io.warn(notFound);
4207
4510
  }
4208
4511
  function warnUnparsedProjectFiles(io, errors, message) {
4209
4512
  for (const error of errors) io.warn(message(error.path, io.core.problems(error.problems)));
4210
4513
  }
4211
4514
  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;
4515
+ if (explicitId !== void 0) return findNamedProjectOrWarn(loaded, io, explicitId);
4516
+ const lookup = lookupCwdProject(loaded, io);
4517
+ if ("project" in lookup) return lookup.project;
4518
+ if (lookup.broken.length > 0) {
4519
+ warnUnparsedProjectFiles(io, lookup.broken, io.cli.projectNotCreatedFileUnparsed);
4520
+ return void 0;
4521
+ }
4215
4522
  const gitRoots = cwdDirRoots(io);
4216
4523
  if (gitRoots === "unreadable") return void 0;
4217
4524
  if (gitRoots === "not-in-repo") {
4218
4525
  io.warn(io.cli.notInGitRepo(io.cwd));
4219
4526
  return void 0;
4220
4527
  }
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);
4528
+ const created = await createProject(io.backlogRoot, gitRoots.main, loaded.projects, warnPathErrors(io.warn));
4227
4529
  io.warn(io.cli.projectCreated(created.id, created.prefix));
4228
4530
  return created;
4229
4531
  }
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
4532
 
4241
4533
  // src/cli/task-write.ts
4242
- function taskWriter(io, loadedTasks) {
4243
- const index = buildIndex(loadedTasks);
4534
+ function taskWriter(io, index) {
4244
4535
  const onError = warnPathErrors(io.warn);
4245
4536
  return async (task, changes, closure) => {
4246
4537
  const result = await updateTaskInIndex(index, { id: task.id, changes, expectedVersion: task.version, now: io.now(), via: "cli", onError, closure });
@@ -4285,7 +4576,7 @@ function taskFieldCommand(spec) {
4285
4576
  io.print(io.cli.alreadySet(id, before));
4286
4577
  return EXIT.ok;
4287
4578
  }
4288
- const written = await taskWriter(io, loaded.tasks)(task, changes);
4579
+ const written = await taskWriter(io, indexOfLoaded(loaded))(task, changes);
4289
4580
  if (!written.ok) return written.exitCode;
4290
4581
  spec.afterWrite?.(written.task, io, task);
4291
4582
  io.print(`${id}: ${before} \u2192 ${spec.label(written.task, io.language)}`);
@@ -4313,16 +4604,17 @@ import { join as join17 } from "node:path";
4313
4604
 
4314
4605
  // src/core/check/check-fixes.ts
4315
4606
  async function applyFixes(loaded, inScope, { messages, ...writes }) {
4316
- const isGone = goneTaskCheck(loaded);
4607
+ const index = indexOfLoaded(loaded);
4608
+ const isGone = goneTaskCheck(loaded, index);
4317
4609
  const epicFixes = await epicStatusFixes(loaded, inScope, messages);
4318
4610
  const planned = loaded.tasks.filter((task) => inScope(task.projectId)).flatMap((task) => {
4319
4611
  const fix = planFix(task, isGone, epicFixes.get(task.id));
4320
4612
  return fix === null ? [] : [{ task, ...fix }];
4321
4613
  });
4322
- return applyPlanned(buildIndex(loaded.tasks), planned, writes);
4614
+ return applyPlanned(index, planned, writes);
4323
4615
  }
4324
- async function applyAnchorPlans(tasks, plans, writes) {
4325
- const index = buildIndex(tasks);
4616
+ async function applyAnchorPlans(loaded, plans, writes) {
4617
+ const index = indexOfLoaded(loaded);
4326
4618
  const planned = plans.flatMap((plan) => {
4327
4619
  const task = index.byId.get(plan.id);
4328
4620
  return task === void 0 ? [] : [{ task, changes: plan.changes, done: plan.moved === void 0 ? [] : [plan.moved] }];
@@ -4374,19 +4666,17 @@ function goneReferences(task, isGone) {
4374
4666
  const references = [...task.blockedBy, ...task.related, ...task.epic === void 0 ? [] : [task.epic]];
4375
4667
  return [...new Set(references.filter(isGone))];
4376
4668
  }
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));
4669
+ function goneTaskCheck({ projects }, index) {
4670
+ const loadedPrefixes = new Set(projects.map((project) => project.prefix));
4380
4671
  return (id) => {
4381
4672
  const prefix = parseId(id)?.prefix;
4382
- return prefix !== void 0 && loadedPrefixes.has(prefix) && !known.has(id);
4673
+ return prefix !== void 0 && loadedPrefixes.has(prefix) && !index.byId.has(id) && !index.notLoaded.has(id);
4383
4674
  };
4384
4675
  }
4385
4676
 
4386
4677
  // src/core/check/find-problems.ts
4387
- import { basename as basename8 } from "node:path";
4388
4678
  function findProblems(loaded, projects, repos, inScope) {
4389
- const index = buildIndex(loaded.tasks);
4679
+ const index = indexOfLoaded(loaded);
4390
4680
  const integrity = loaded.tasks.filter((task) => inScope(task.projectId)).flatMap((task) => integrityErrors(task, index).map((problem3) => ({ kind: "task-invalid", taskId: task.id, problem: problem3 })));
4391
4681
  const missingRepos = projects.filter((project) => repos.get(project.id) === void 0).map(missingRepoProblem);
4392
4682
  return [...parseProblems(loaded, inScope), ...integrity, ...missingRepos, ...sharedPrefixes(loaded.projects, inScope)];
@@ -4404,7 +4694,7 @@ function parseProblems(loaded, inScope) {
4404
4694
  return [...reported, { kind: "epics-wait-for-files", epicIds: waitingEpicIds }];
4405
4695
  }
4406
4696
  function concernsScope(error, inScope) {
4407
- return inScope(error.projectId) || basename8(error.path) === PROJECT_FILE;
4697
+ return inScope(error.projectId) || isProjectFileError(error);
4408
4698
  }
4409
4699
  function missingRepoProblem(project) {
4410
4700
  return project.repos.length === 0 ? { kind: "project-without-repos", projectId: project.id } : { kind: "project-repos-missing", projectId: project.id, repos: project.repos };
@@ -4524,9 +4814,9 @@ async function contains(git, repo, descendant, commit) {
4524
4814
  }
4525
4815
 
4526
4816
  // src/core/check/landed-content.ts
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"];
4817
+ var PATCH_OPTIONS = ["-p", ...PARSED_DIFF_OPTIONS, "--no-renames", "--no-relative", "--full-index", "--diff-algorithm=myers", "--indent-heuristic", "--unified=0", "--inter-hunk-context=0"];
4529
4818
  var COMMIT_HEADER = "--format=commit %H";
4819
+ var INSERTION_NEIGHBOURS = 2;
4530
4820
  var TREE_PAIR_LINE = /^[0-9a-f]+ [0-9a-f]+$/;
4531
4821
  var NO_COMMIT = /^0+$/;
4532
4822
  var COMMIT_RECORD = /commit (?<commit>[0-9a-f]+)\0/;
@@ -4575,17 +4865,19 @@ async function commitsCarrying(view, scope) {
4575
4865
  return carrying.flat();
4576
4866
  }
4577
4867
  async function forkAt(repo, head, tip, git) {
4578
- const base = outputLine(await git(repo, ["merge-base", head, tip]));
4868
+ const base = commitHashOf(outputLine(await git(repo, ["merge-base", head, tip])));
4579
4869
  return base === null ? null : { base, tip, head };
4580
4870
  }
4581
- async function forkBeforeLanding(repo, tip, git) {
4871
+ async function forkBeforeLanding(repo, revision, git) {
4872
+ const tip = (await resolveCommits(git, repo, [revision]))?.get(revision);
4873
+ if (tip === void 0) return null;
4582
4874
  const fork = await forkAt(repo, "HEAD", tip, git);
4583
4875
  if (fork === null || !tipInHead(fork)) return fork;
4584
4876
  const landing = await firstParentLanding(git, repo, tip, "HEAD");
4585
4877
  return landing === null ? fork : forkAt(repo, landing.firstParent, tip, git);
4586
4878
  }
4587
4879
  function tipInHead({ base, tip }) {
4588
- return base.startsWith(tip);
4880
+ return base === tip;
4589
4881
  }
4590
4882
  async function branchChanges(view, pathspecs) {
4591
4883
  const { repo, base, tip, git } = view;
@@ -4613,7 +4905,7 @@ async function changeLanded(view, path) {
4613
4905
  const copies = await patchCopies(view, path);
4614
4906
  if (copies === null) return "unknown";
4615
4907
  if (copies.squashed.length > 0 || everyCommitCopied(copies)) return "landed";
4616
- return copies.shiftsComplete ? "pending" : "unknown";
4908
+ return copies.editsComplete ? "pending" : "unknown";
4617
4909
  }
4618
4910
  function everyCommitCopied({ commitByCommit }) {
4619
4911
  return commitByCommit.length > 0 && commitByCommit.every((commitCopies) => commitCopies.length > 0);
@@ -4634,9 +4926,9 @@ async function patchCopies(view, path) {
4634
4926
  const headPatchesById = groupBy(headPatches, ({ id }) => id);
4635
4927
  const sameChanges = (change) => (headPatchesById.get(change.id) ?? []).filter((copy) => isSameChange(change, copy));
4636
4928
  const pairs = [...squashedPatch, ...branchPatches].flatMap((change) => sameChanges(change).map((copy) => [change, copy]));
4637
- const { shiftsBetween, complete } = await preimageShifts(view, path, pairs);
4638
- const copiesOf = (change) => sameChanges(change).flatMap((copy) => atSamePlace(change, copy, shiftsBetween) ? [copy.commit] : []);
4639
- return { squashed: squashedPatch.flatMap(copiesOf), commitByCommit: branchPatches.map(copiesOf), shiftsComplete: complete };
4929
+ const { editsBetween, complete } = await preimageEdits(view, path, pairs);
4930
+ const copiesOf = (change) => sameChanges(change).flatMap((copy) => atSamePlace(change, copy, editsBetween) ? [copy.commit] : []);
4931
+ return { squashed: squashedPatch.flatMap(copiesOf), commitByCommit: branchPatches.map(copiesOf), editsComplete: complete };
4640
4932
  }
4641
4933
  async function patchesOf(repo, patchArgs, preimageOf, git) {
4642
4934
  const patches = await git(repo, patchArgs);
@@ -4650,38 +4942,38 @@ async function patchesOf(repo, patchArgs, preimageOf, git) {
4650
4942
  return { id, commit, preimageRevision: preimageOf(commit), ...shapeOf(commit) };
4651
4943
  });
4652
4944
  }
4653
- async function preimageShifts(repoGit, path, pairs) {
4654
- const shifted = pairs.filter(([change, copy]) => shiftsNeeded(change, copy));
4655
- const trees = await resolveTrees(repoGit.git, repoGit.repo, [...new Set(shifted.flatMap(([change, copy]) => [change.preimageRevision, copy.preimageRevision]))]);
4945
+ async function preimageEdits(repoGit, path, pairs) {
4946
+ const comparedPairs = pairs.filter(([change, copy]) => editsNeeded(change, copy));
4947
+ const trees = await resolveTrees(repoGit.git, repoGit.repo, [...new Set(comparedPairs.flatMap(([change, copy]) => [change.preimageRevision, copy.preimageRevision]))]);
4656
4948
  const treePairOf = (change, copy) => {
4657
4949
  const from = trees?.get(change.preimageRevision);
4658
4950
  const to = trees?.get(copy.preimageRevision);
4659
4951
  return from === void 0 || to === void 0 ? null : `${from} ${to}`;
4660
4952
  };
4661
- const shiftsByTreePair = await treeDiffShifts(repoGit, path, [...new Set(shifted.flatMap(([change, copy]) => treePairOf(change, copy) ?? []))]);
4662
- const shiftsBetween = (change, copy) => {
4663
- if (!shiftsNeeded(change, copy)) return [];
4953
+ const editsByTreePair = await treeDiffEdits(repoGit, path, [...new Set(comparedPairs.flatMap(([change, copy]) => treePairOf(change, copy) ?? []))]);
4954
+ const editsBetween = (change, copy) => {
4955
+ if (!editsNeeded(change, copy)) return [];
4664
4956
  const treePair = treePairOf(change, copy);
4665
- return treePair === null ? null : shiftsByTreePair?.get(treePair) ?? null;
4957
+ return treePair === null ? null : editsByTreePair?.get(treePair) ?? null;
4666
4958
  };
4667
- return { shiftsBetween, complete: trees !== null && shiftsByTreePair !== null };
4959
+ return { editsBetween, complete: trees !== null && editsByTreePair !== null };
4668
4960
  }
4669
- async function treeDiffShifts({ repo, git }, path, treePairs) {
4961
+ async function treeDiffEdits({ repo, git }, path, treePairs) {
4670
4962
  if (treePairs.length === 0) return /* @__PURE__ */ new Map();
4671
- const preimageDiffs = await git(repo, ["diff-tree", "--stdin", ...LINE_SHIFT_OPTIONS, "--", ...topLiteralPathspecs([path])], treePairs.map((treePair) => `${treePair}
4963
+ const preimageDiffs = await git(repo, ["diff-tree", "--stdin", ...PATCH_OPTIONS, "--", ...topLiteralPathspecs([path])], treePairs.map((treePair) => `${treePair}
4672
4964
  `).join(""));
4673
- return preimageDiffs === null ? null : lineShiftsByTreePair(preimageDiffs);
4965
+ return preimageDiffs === null ? null : preimageEditsByTreePair(preimageDiffs);
4674
4966
  }
4675
- function lineShiftsByTreePair(preimageDiffs) {
4676
- const shiftsByTreePair = /* @__PURE__ */ new Map();
4677
- let shifts = [];
4967
+ function preimageEditsByTreePair(preimageDiffs) {
4968
+ const editsByTreePair = /* @__PURE__ */ new Map();
4969
+ let edits = [];
4678
4970
  for (const line of preimageDiffs.split("\n")) {
4679
4971
  if (TREE_PAIR_LINE.test(line)) {
4680
- shifts = [];
4681
- shiftsByTreePair.set(line, shifts);
4682
- } else shifts.push(...lineShiftsOf(hunkHeaderOf(line)));
4972
+ edits = [];
4973
+ editsByTreePair.set(line, edits);
4974
+ } else edits.push(...preimageEditsOf(hunkHeaderOf(line)));
4683
4975
  }
4684
- return shiftsByTreePair;
4976
+ return editsByTreePair;
4685
4977
  }
4686
4978
  function isSameChange(change, copy) {
4687
4979
  const changeShownByHunks = change.changeStarts.length > 0;
@@ -4693,18 +4985,33 @@ function sameBlobs(change, copy) {
4693
4985
  function samePreimage(change, copy) {
4694
4986
  return change.blobs !== void 0 && change.blobs.preimage === copy.blobs?.preimage;
4695
4987
  }
4696
- function shiftsNeeded(change, copy) {
4988
+ function editsNeeded(change, copy) {
4697
4989
  return change.changeStarts.length > 0 && !samePreimage(change, copy);
4698
4990
  }
4699
- function atSamePlace(change, copy, shiftsBetween) {
4700
- const shifts = shiftsBetween(change, copy);
4701
- return shifts !== null && change.changeStarts.every((start, index) => shiftedLine(start, shifts) === copy.changeStarts[index]);
4991
+ function atSamePlace(change, copy, editsBetween) {
4992
+ const edits = editsBetween(change, copy);
4993
+ return edits !== null && change.changeStarts.every((start, index) => copyStartsAtSamePlace(start, copy.changeStarts[index], edits));
4994
+ }
4995
+ function copyStartsAtSamePlace(start, copyStart, edits) {
4996
+ const place = placeOf(start);
4997
+ const placeUntouched = !edits.some((edit) => spansOverlap(edit, place));
4998
+ return placeUntouched && shiftedLine(start.line, edits) === copyStart?.line;
4999
+ }
5000
+ function placeOf({ line, insertion }) {
5001
+ return insertion ? { firstLine: line - 1, lineCount: INSERTION_NEIGHBOURS } : { firstLine: line, lineCount: 1 };
5002
+ }
5003
+ function spansOverlap(edit, place) {
5004
+ return edit.firstLine < lineAfter(place) && place.firstLine < lineAfter(edit);
4702
5005
  }
4703
- function lineShiftsOf(header) {
4704
- return header === null ? [] : [{ shiftsLinesAfter: firstLineOf(header.oldStart, header.oldCount) + header.oldCount - 1, delta: header.newCount - header.oldCount }];
5006
+ function lineAfter({ firstLine, lineCount }) {
5007
+ return firstLine + lineCount;
4705
5008
  }
4706
- function shiftedLine(line, shifts) {
4707
- return shifts.reduce((shifted, { shiftsLinesAfter, delta }) => shiftsLinesAfter < line ? shifted + delta : shifted, line);
5009
+ function preimageEditsOf(header) {
5010
+ if (header === null) return [];
5011
+ return [{ firstLine: firstLineOf(header.oldStart, header.oldCount), lineCount: header.oldCount, delta: header.newCount - header.oldCount }];
5012
+ }
5013
+ function shiftedLine(line, edits) {
5014
+ return edits.reduce((shifted, edit) => lineAfter(edit) <= line ? shifted + edit.delta : shifted, line);
4708
5015
  }
4709
5016
  function parentOf(commit) {
4710
5017
  return `${commit}^`;
@@ -4717,15 +5024,15 @@ function fileVersion({ mode = "", object = "", path = "" } = {}) {
4717
5024
  var MERGE_PARENTS = 2;
4718
5025
  async function commitsKnownAtCreation({ repo, tasks, facts, anchors, origins, git = runGit }) {
4719
5026
  const questions = tasks.flatMap((task) => {
4720
- const origin = origins.get(task.id);
4721
- if (origin === void 0 || task.verified !== void 0 || task.source === void 0 || !judgedByCommits(task, anchors)) return [];
5027
+ const origin = creationOrigin(task, origins);
5028
+ if (origin === void 0 || task.source === void 0 || !judgedByCommits(task, anchors)) return [];
4722
5029
  const path = sourcePath(task.source);
4723
- return [{ taskId: task.id, creation: origin.commit, path, changes: commitsTouchingSince(facts.commits, path, reviewMark(task)) }];
5030
+ return [{ taskId: task.id, site: { commit: origin.commit, path }, changes: commitsTouchingSince(facts.commits, path, reviewMark(task)) }];
4724
5031
  });
4725
5032
  const copies = creationCopies(repo, git);
4726
5033
  const answers = await Promise.all(
4727
- questions.map(async ({ taskId, creation, path, changes }) => {
4728
- const known = await Promise.all(changes.map(async (commit) => await isKnownAtCreation(copies, commit, creation, path) ? [commit.sha] : []));
5034
+ questions.map(async ({ taskId, site, changes }) => {
5035
+ const known = await Promise.all(changes.map(async (commit) => await isKnownAtCreation(copies, commit, site) ? [commit.sha] : []));
4729
5036
  return { taskId, known: known.flat() };
4730
5037
  })
4731
5038
  );
@@ -4736,23 +5043,79 @@ function creationCopies(repo, git) {
4736
5043
  const branchCommitsByMerge = /* @__PURE__ */ new Map();
4737
5044
  const copiesByCreation = /* @__PURE__ */ new Map();
4738
5045
  return {
4739
- broughtByMerge: (merge, creation, path) => remembered(
5046
+ broughtByMerge: (merge, { commit, path }) => remembered(
4740
5047
  branchCommitsByMerge,
4741
- `${merge.sha} ${creation} ${path}`,
4742
- async () => outputLines(await git(repo, ["rev-list", `${merge.sha}^2`, `^${merge.sha}^1`, `^${creation}`, "--", ...literalPathspecs([path])]))
5048
+ `${merge.sha} ${commit} ${path}`,
5049
+ async () => outputLines(await git(repo, ["rev-list", `${merge.sha}^2`, `^${merge.sha}^1`, `^${commit}`, "--", ...literalPathspecs([path])]))
4743
5050
  ),
4744
- copiesOf: (creation, path) => remembered(copiesByCreation, `${creation} ${path}`, async () => new Set(await carryingContent(creation, literalPathspecs([path]))))
5051
+ copiesOf: ({ commit, path }) => remembered(copiesByCreation, `${commit} ${path}`, async () => new Set(await carryingContent(commit, literalPathspecs([path]))))
4745
5052
  };
4746
5053
  }
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);
5054
+ async function isKnownAtCreation(copies, commit, site) {
5055
+ if (commit.parents.length !== MERGE_PARENTS) return (await copies.copiesOf(site)).has(commit.sha);
5056
+ const brought = await copies.broughtByMerge(commit, site);
4750
5057
  if (brought === null) return false;
4751
5058
  if (brought.length === 0) return true;
4752
- const copied = await copies.copiesOf(creation, path);
5059
+ const copied = await copies.copiesOf(site);
4753
5060
  return brought.every((sha) => copied.has(sha));
4754
5061
  }
4755
5062
 
5063
+ // src/core/check/late-commits.ts
5064
+ var NO_LATE_COMMITS = /* @__PURE__ */ new Map();
5065
+ async function commitsArrivedLate(question) {
5066
+ if (question.facts.history !== "read") return NO_LATE_COMMITS;
5067
+ const { repo } = question;
5068
+ const edited = await editedSinceCheckout(repo, await markedSources(question));
5069
+ const checkouts = [...new Set(edited.map(({ checkout }) => checkout))];
5070
+ const late = await Promise.all(
5071
+ checkouts.map(
5072
+ (checkout) => arrivedAfter(
5073
+ repo,
5074
+ checkout,
5075
+ edited.filter((source) => source.checkout === checkout)
5076
+ )
5077
+ )
5078
+ );
5079
+ return new Map(late.flat());
5080
+ }
5081
+ async function markedSources({ repo, tasks, facts, anchors, origins, knownCommits }) {
5082
+ const headCommitAt = headCommitsAt(repo);
5083
+ const sourcesByTask = await Promise.all(
5084
+ tasks.map(async (task) => {
5085
+ if (task.source === void 0 || !judgedByCommits(task, anchors)) return [];
5086
+ const path = sourcePath(task.source);
5087
+ if (!facts.existing.has(path) || !isInsideRepo(path) || changedByDate(task, path, facts, knownCommits)) return [];
5088
+ const checkout = await checkoutAtMark(task, origins, headCommitAt);
5089
+ return checkout === null ? [] : [{ taskId: task.id, path, mark: reviewMark(task), checkout }];
5090
+ })
5091
+ );
5092
+ return sourcesByTask.flat();
5093
+ }
5094
+ function changedByDate(task, path, facts, knownCommits) {
5095
+ const { commits, uncommitted } = changesSinceMark({ facts, late: NO_LATE_COMMITS }, task, path);
5096
+ return uncommitted || commits.some((commit) => knownCommits.get(task.id)?.has(commit.sha) !== true);
5097
+ }
5098
+ async function editedSinceCheckout(repo, sources) {
5099
+ const objects = ({ checkout, path }) => ({ commit: `${checkout}^{commit}`, atCheckout: `${checkout}^{commit}:./${path}`, atHead: `HEAD:./${path}` });
5100
+ const ids = await objectIds(
5101
+ runGit,
5102
+ repo,
5103
+ sources.flatMap((source) => Object.values(objects(source)))
5104
+ );
5105
+ if (ids === null) return [];
5106
+ return sources.flatMap((source) => {
5107
+ const { commit, atCheckout, atHead } = objects(source);
5108
+ const checkout = commitHashOf(ids.get(commit) ?? null);
5109
+ return checkout === null || ids.get(atCheckout) === ids.get(atHead) ? [] : [{ ...source, checkout }];
5110
+ });
5111
+ }
5112
+ async function arrivedAfter(repo, checkout, sources) {
5113
+ const headDescendsFromCheckout = await runGit(repo, ["merge-base", "--is-ancestor", checkout, "HEAD"]) !== null;
5114
+ if (!headDescendsFromCheckout) return [];
5115
+ const arrived = await mainlineCommitsOff(repo, checkout, [...new Set(sources.map(({ path }) => path))]) ?? [];
5116
+ return sources.map(({ taskId, path, mark }) => [taskId, commitsTouchingUntil(arrived, path, mark)]);
5117
+ }
5118
+
4756
5119
  // src/core/model/query.ts
4757
5120
  var OPEN_STATUSES = TASK_STATUSES.filter((status) => !isClosed(status));
4758
5121
  var STATUS_SORT_ORDER = ["in-progress", "blocked", "backlog", "done", "cancelled"];
@@ -4875,7 +5238,7 @@ function sharedCount(left, right) {
4875
5238
 
4876
5239
  // src/core/check/duplicates.ts
4877
5240
  function findSimilarTask(draft, tasks) {
4878
- const draftFingerprint = { place: placeOf(draft.source), stems: titleStems(draft.title) };
5241
+ const draftFingerprint = { place: placeOf2(draft.source), stems: titleStems(draft.title) };
4879
5242
  const similar = tasks.filter((task) => task.type === "task" && !isClosed(task.status)).flatMap((task) => {
4880
5243
  const match = sourceTitleMatch(draftFingerprint, fingerprintOf(task));
4881
5244
  return match === null ? [] : [{ task: taskRef(task), match }];
@@ -4892,7 +5255,7 @@ function duplicateCandidates(tasks, symbolOf = () => null) {
4892
5255
  );
4893
5256
  }
4894
5257
  function fingerprintOf(task) {
4895
- return { task, place: placeOf(task.source), stems: titleStems(task.title) };
5258
+ return { task, place: placeOf2(task.source), stems: titleStems(task.title) };
4896
5259
  }
4897
5260
  function duplicateMatch(current, older, symbolOf) {
4898
5261
  if (linked(current.task, older.task) || bothConfirmedAfterCreation(current.task, older.task)) return null;
@@ -4909,7 +5272,7 @@ function sourceTitleMatch(left, right) {
4909
5272
  function titlesMatch(left, right) {
4910
5273
  return similarTitles(left.stems, right.stems) || nearlySameTitles(left.stems, right.stems);
4911
5274
  }
4912
- function placeOf(source) {
5275
+ function placeOf2(source) {
4913
5276
  return source === void 0 ? void 0 : { path: sourcePath(source), lines: lineSuffix(source) };
4914
5277
  }
4915
5278
  function sharedPlace(a, b) {
@@ -4939,8 +5302,8 @@ async function awaitingMerge({ repo, taskIds, origins, git = runGitOutcome }) {
4939
5302
  if (branched.length === 0) return { pending: /* @__PURE__ */ new Set(), unknownBranches: [] };
4940
5303
  const current = lineOf(await git(repo, ["rev-parse", "--abbrev-ref", "HEAD"]));
4941
5304
  const branchStates = /* @__PURE__ */ new Map();
4942
- let shallow;
4943
- const isShallow = () => shallow ??= isShallowClone(repo, git);
5305
+ let completenessLookup;
5306
+ const cloneCompleteness = () => completenessLookup ??= cloneCompletenessOf(repo, git);
4944
5307
  const nested = await Promise.all(
4945
5308
  branched.map(async ({ id, commit, branch }) => {
4946
5309
  if (branch === current) return [];
@@ -4948,8 +5311,10 @@ async function awaitingMerge({ repo, taskIds, origins, git = runGitOutcome }) {
4948
5311
  if (ancestry.status === "unfinished") return [{ id, branch, state: "unknown" }];
4949
5312
  if (ancestry.status === "ok") return [];
4950
5313
  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)) }];
5314
+ if (creationCommitUnreadable && await cloneCompleteness() === "full") return [];
5315
+ const state = await remembered(branchStates, branch, () => branchState(repo, branch, git));
5316
+ const pendingOnlyIfShallow = creationCommitUnreadable && state === "pending" && await cloneCompleteness() === "unknown";
5317
+ return [{ id, branch, state: pendingOnlyIfShallow ? "unknown" : state }];
4953
5318
  })
4954
5319
  );
4955
5320
  const verdicts = nested.flat();
@@ -4959,12 +5324,15 @@ async function awaitingMerge({ repo, taskIds, origins, git = runGitOutcome }) {
4959
5324
  }
4960
5325
  async function branchState(repo, branch, git) {
4961
5326
  const lookup = await git(repo, ["rev-parse", "--verify", "--quiet", `refs/heads/${branch}`]);
4962
- const tip = lineOf(lookup);
5327
+ const tip = commitHashOf(lineOf(lookup));
4963
5328
  if (tip !== null) return landingState(repo, tip, asGitRunner(git));
4964
5329
  return lookup.status === "exited" && lookup.exitCode === NO_SUCH_REF_EXIT ? "deleted" : "unknown";
4965
5330
  }
4966
- async function isShallowClone(repo, git) {
4967
- return lineOf(await git(repo, ["rev-parse", "--is-shallow-repository"])) === "true";
5331
+ async function cloneCompletenessOf(repo, git) {
5332
+ const answer = lineOf(await git(repo, ["rev-parse", "--is-shallow-repository"]));
5333
+ if (answer === "true") return "shallow";
5334
+ if (answer === "false") return "full";
5335
+ return "unknown";
4968
5336
  }
4969
5337
  function lineOf(outcome) {
4970
5338
  return outputLine(stdoutOf(outcome));
@@ -5049,33 +5417,31 @@ async function projectReview(project, allTasks, { repo, origins, mode, onUnreada
5049
5417
  for (const [path, error] of facts.unreadable) onUnreadable(join16(repo, path), error);
5050
5418
  const skipped = new Set(tasks.filter((task) => task.source !== void 0 && facts.unreadable.has(sourcePath(task.source))).map((task) => task.id));
5051
5419
  const readable = tasks.filter((task) => !skipped.has(task.id));
5052
- const scope = { repo, facts, origins, mode, onUnreadable };
5053
- const anchors = anchorStates(readable, facts);
5054
- const review = await reviewedCode(readable, anchors, scope);
5055
5420
  const graph = openCodeGraph(repo);
5056
5421
  try {
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);
5422
+ const anchors = anchorStates(readable, facts);
5423
+ const question = { repo, tasks: readable, facts, anchors, origins };
5424
+ const knownCommits = await commitsKnownAtCreation(question);
5425
+ const late = await commitsArrivedLate({ ...question, knownCommits });
5426
+ const scope = { repo, facts, late, origins, mode, onUnreadable, graph };
5427
+ const review = await withRenamesFollowed(codeReview(readable, { facts, late }, knownCommits, anchors), readable, scope);
5428
+ const context = await projectContext(readable, review, scope);
5429
+ const sighted = await sightedBySymbol(tasks, review, context, { mode, skipped });
5430
+ const { problems: mergeProblems, ...judged } = await judgedAgainstMerges(sighted, context, { repo, origins, projectId: project.id });
5060
5431
  return { projectId: project.id, ...judged, skipped: [...skipped], problems: [...historyProblems(project, repo, facts), ...mergeProblems], unchecked: uncheckedEvidence(tasks, anchors, facts) };
5061
5432
  } finally {
5062
5433
  graph?.close();
5063
5434
  }
5064
5435
  }
5065
- async function reviewedCode(tasks, anchors, scope) {
5066
- const { repo, facts, origins } = scope;
5067
- const knownCommits = await commitsKnownAtCreation({ repo, tasks, facts, anchors, origins });
5068
- return withRenamesFollowed(codeReview(tasks, facts, knownCommits, anchors), tasks, scope);
5069
- }
5070
- async function projectContext(tasks, review, { repo, facts, origins, mode, onUnreadable }, graph) {
5071
- const diffs = repoDiffs(repo);
5436
+ async function projectContext(tasks, review, { repo, facts, late, origins, mode, onUnreadable, graph }) {
5437
+ const diffs = repoDiffs(repo, origins);
5072
5438
  const symbolAt = symbolLookup(graph, fileHashes(repo, onUnreadable));
5073
5439
  const changedIds = new Set(review.candidates.flatMap((candidate) => candidate.kind === "source-changed" ? [candidate.task.id] : []));
5074
5440
  const locating = mode === "full" && graph !== null ? tasks : tasks.filter((task) => changedIds.has(task.id));
5075
- const traces = await traceSources(locating, facts, diffs);
5076
- return { tasksById: new Map(tasks.map((task) => [task.id, task])), located: currentSourcesOf(traces), traces, facts, diffOf: diffsSinceCreation(repo, diffs, origins), symbolAt };
5441
+ const traces = await traceSources(locating, { facts, late }, diffs);
5442
+ return { tasksById: new Map(tasks.map((task) => [task.id, task])), located: currentSourcesOf(traces), traces, facts, diffOf: diffs.sinceTaskMark, symbolAt };
5077
5443
  }
5078
- async function sightedBySymbol(tasks, review, context, { mode }, skipped) {
5444
+ async function sightedBySymbol(tasks, review, context, { mode, skipped }) {
5079
5445
  const duplicates = mode === "full" ? duplicateCandidates(tasks, symbolNames(context.symbolAt, context.located)).filter((candidate) => !skipped.has(candidate.task.id)) : [];
5080
5446
  const byLines = judgedByLines(review.candidates, context.traces);
5081
5447
  const { kept, filtered } = await filterBySymbol(byLines.kept, context);
@@ -5085,7 +5451,7 @@ async function sightedBySymbol(tasks, review, context, { mode }, skipped) {
5085
5451
  };
5086
5452
  return { kept, filtered, plans: settledPlans(review.plans, settlement, context), duplicates };
5087
5453
  }
5088
- async function judgedAgainstMerges(sighted, context, { repo, origins }, projectId) {
5454
+ async function judgedAgainstMerges(sighted, context, { repo, origins, projectId }) {
5089
5455
  const { pending, unknownBranches: unknownBranches2 } = await awaitingMerge({ repo, taskIds: involvedTaskIds(sighted), origins });
5090
5456
  const judged = (id) => !pending.has(id);
5091
5457
  const code = await Promise.all(sighted.kept.filter((candidate) => judged(candidate.task.id)).map((candidate) => withContext2(candidate, context)));
@@ -5133,14 +5499,14 @@ function uncheckedEvidence(tasks, anchors, { history, branches, existing }) {
5133
5499
  function evidenceOf(tasks, evidence2) {
5134
5500
  return tasks.map((task) => ({ task: task.id, evidence: evidence2 }));
5135
5501
  }
5136
- function historyProblems(project, repo, { history, branches }) {
5137
- switch (history) {
5502
+ function historyProblems(project, repo, facts) {
5503
+ switch (facts.history) {
5138
5504
  case "read":
5139
- return branches.kind === "unreadable" ? [{ kind: "project-branches-unreadable", projectId: project.id, repo }] : [];
5505
+ return facts.branches.kind === "unreadable" ? [{ kind: "project-branches-unreadable", projectId: project.id, repo }] : [];
5140
5506
  case "not-a-repo":
5141
5507
  return [{ kind: "project-repo-not-git", projectId: project.id, repo }];
5142
5508
  case "unsafe-repo":
5143
- return [{ kind: "project-repo-unsafe", projectId: project.id, repo }];
5509
+ return [{ kind: "project-repo-unsafe", projectId: project.id, repo, trustCommand: facts.trustCommand }];
5144
5510
  case "unreadable":
5145
5511
  return [{ kind: "project-history-unreadable", projectId: project.id, repo }];
5146
5512
  }
@@ -5173,10 +5539,12 @@ async function withContext2(candidate, { tasksById, located, facts, diffOf }) {
5173
5539
  const current = located.get(task.id) ?? void 0;
5174
5540
  const source = current ?? task.source;
5175
5541
  const snippet = text === void 0 || source === void 0 ? void 0 : snippetOf(text, source);
5542
+ const codeState = text === void 0 || source === void 0 ? void 0 : codeStateOf(text, source);
5176
5543
  const excerpt = (await diffOf(task, candidate.path))?.excerpt;
5177
5544
  const problem3 = firstParagraph(task.body);
5178
5545
  const moved = current === void 0 || current === task.source ? {} : { source: current };
5179
- return { ...candidate, ...moved, ...problem3 === void 0 ? {} : { problem: problem3 }, ...snippet === void 0 ? {} : { snippet }, ...diffFields(excerpt) };
5546
+ const code = { ...snippet === void 0 ? {} : { snippet }, ...codeState === void 0 ? {} : { codeState } };
5547
+ return { ...candidate, ...moved, ...problem3 === void 0 ? {} : { problem: problem3 }, ...code, ...diffFields(excerpt) };
5180
5548
  }
5181
5549
  function diffFields(excerpt) {
5182
5550
  if (excerpt === void 0) return {};
@@ -5199,7 +5567,7 @@ async function checkBacklog(root, loaded, request) {
5199
5567
  const projects = current.projects.filter((project) => inScope(project.id));
5200
5568
  const checked = await reviewProjects(root, current.tasks, projects, request);
5201
5569
  const reviews = checked.map(({ review }) => review);
5202
- const anchors = await applyAnchorPlans(current.tasks, checked.flatMap(plansToApply), writes);
5570
+ const anchors = await applyAnchorPlans(current, checked.flatMap(plansToApply), writes);
5203
5571
  const outcome = candidateOutcome(reviews);
5204
5572
  await recordCandidates(root, current.tasks, outcome, request);
5205
5573
  const repos = new Map(checked.map(({ review, checkout }) => [review.projectId, checkout?.path]));
@@ -5210,8 +5578,8 @@ async function reviewProjects(root, tasks, projects, request) {
5210
5578
  const originsOf = (projectId) => creationOrigins(root, projectId, (error) => request.warn(request.messages.branchOriginsReadFailed(projectId, errorText(error))));
5211
5579
  return Promise.all(
5212
5580
  projects.map(async (project) => {
5213
- const checkout = await projectCheckout(project, request.workingRoots, request.places);
5214
- return { review: await projectReview(project, tasks, { repo: checkout?.path, origins: await originsOf(project.id), mode: request.mode, onUnreadable: request.places.onUnreadable }), checkout };
5581
+ const checkout = await projectCheckout(project, request.workingRoots, request.context);
5582
+ return { review: await projectReview(project, tasks, { repo: checkout?.path, origins: await originsOf(project.id), mode: request.mode, onUnreadable: request.context.onUnreadable }), checkout };
5215
5583
  })
5216
5584
  );
5217
5585
  }
@@ -5320,7 +5688,7 @@ function formatTaskDetails(cli, core, description, fileText) {
5320
5688
  if (task.resolution !== void 0) lines.push(cli.reasonLine(task.resolution, task.reason ?? ""));
5321
5689
  if (task.verified !== void 0) lines.push(cli.verifiedLine(task.verified));
5322
5690
  if (task.tags.length > 0) lines.push(cli.tagsLine(task.tags.join(", ")));
5323
- if (task.epic !== void 0) lines.push(cli.epicLine(description.epic ? formatTaskRef(description.epic) : cli.epicNotFound(task.epic)));
5691
+ if (description.epic !== void 0) lines.push(cli.epicLine(epicRef(cli, description.epic)));
5324
5692
  if (description.openBlockers.length > 0) lines.push(cli.openBlockersLine(description.openBlockers.map(formatTaskRef).join("; ")));
5325
5693
  if (description.inactiveBlockerIds.length > 0) {
5326
5694
  lines.push(cli.inactiveBlockersLine(description.inactiveBlockerIds.join(", ")));
@@ -5331,6 +5699,16 @@ function formatTaskDetails(cli, core, description, fileText) {
5331
5699
  if (description.warnings.length > 0) lines.push(cli.warningsLine(description.warnings.map(core.problem).join("; ")));
5332
5700
  return [...lines, "", fileText.trimEnd()].join("\n");
5333
5701
  }
5702
+ function epicRef(cli, epic) {
5703
+ switch (epic.kind) {
5704
+ case "loaded":
5705
+ return formatTaskRef(epic.task);
5706
+ case "not-loaded":
5707
+ return cli.epicNotLoaded(epic.id);
5708
+ case "missing":
5709
+ return cli.epicNotFound(epic.id);
5710
+ }
5711
+ }
5334
5712
  function formatProgress(progress) {
5335
5713
  return progress === null ? "\u2014" : `${progress}%`;
5336
5714
  }
@@ -5351,13 +5729,13 @@ var SCOPE_OPTIONS = {
5351
5729
  project: { type: "string" },
5352
5730
  "all-projects": { type: "boolean", default: false }
5353
5731
  };
5354
- async function resolveScope(loaded, io, values) {
5732
+ function resolveScope(loaded, io, values) {
5355
5733
  if (values.project !== void 0 && values["all-projects"] === true) throw new UsageError(io.cli.needProjectOrAllProjects);
5356
5734
  if (values["all-projects"] === true) {
5357
5735
  const projectIds = loaded.projects.map((project2) => project2.id);
5358
5736
  return { projectIds, activeIds: activeProjects(loaded.projects).map((project2) => project2.id) };
5359
5737
  }
5360
- const project = await findProjectOrWarn(loaded, io, values.project);
5738
+ const project = findProjectOrWarn(loaded, io, values.project);
5361
5739
  return project === void 0 ? null : { projectIds: [project.id], activeIds: [project.id], project };
5362
5740
  }
5363
5741
 
@@ -5374,21 +5752,27 @@ async function runCheck(args, io) {
5374
5752
  json: { type: "boolean", default: false }
5375
5753
  });
5376
5754
  const loaded = await loadBacklog(io.backlogRoot);
5377
- const scope = await resolveScope(loaded, io, values);
5755
+ const scope = resolveScope(loaded, io, values);
5378
5756
  if (scope === null) return EXIT.notFound;
5379
5757
  const { projectIds } = scope;
5380
5758
  const report = await checkBacklog(io.backlogRoot, loaded, {
5381
5759
  projectIds,
5382
5760
  mode: values.changed ? "changed" : "full",
5383
5761
  now: io.now(),
5384
- places: repoPlaces(io),
5762
+ context: repoContext(io),
5385
5763
  messages: io.core,
5386
5764
  warn: io.warn,
5387
5765
  workingRoots: cwdGitRoots(io)
5388
5766
  });
5389
- io.print(values.json ? formatJson(report) : formatReport(io.cli, io.core, report));
5767
+ io.print(values.json ? formatJson({ ...report, candidates: report.candidates.map(withoutCodeState) }) : formatReport(io.cli, io.core, report));
5390
5768
  return needsReview(report) ? EXIT.needsReview : EXIT.ok;
5391
5769
  }
5770
+ function withoutCodeState(candidate) {
5771
+ if (!("codeState" in candidate)) return candidate;
5772
+ const shown = { ...candidate };
5773
+ delete shown.codeState;
5774
+ return shown;
5775
+ }
5392
5776
  var PROBLEM_NEEDS_REVIEW = {
5393
5777
  "task-invalid": true,
5394
5778
  "fix-failed": true,
@@ -5637,9 +6021,10 @@ async function runClose(args, io) {
5637
6021
  io.warn(io.cli.fixCommitRequired);
5638
6022
  return EXIT.invalid;
5639
6023
  }
5640
- const written = await taskWriter(io, loaded.tasks)(task, { status, related }, { resolution, reason });
6024
+ const index = indexOfLoaded(loaded);
6025
+ const written = await taskWriter(io, index)(task, { status, related }, { resolution, reason });
5641
6026
  if (!written.ok) return written.exitCode;
5642
- const deletion = scheduledDeletion(written.task, buildIndex(loaded.tasks.map((other) => other.id === written.task.id ? written.task : other)));
6027
+ const deletion = scheduledDeletion(written.task, indexWithWritten(index, [written]));
5643
6028
  const change = attachesFix ? status : `${task.status} \u2192 ${status}`;
5644
6029
  io.print(`${id}: ${change} (${resolution})${deletion === void 0 ? "" : io.cli.deletesAtTail(deletionWhen(io.cli, deletion))}`);
5645
6030
  return EXIT.ok;
@@ -5846,7 +6231,7 @@ async function runLanguage(positionals, io) {
5846
6231
  return EXIT.ok;
5847
6232
  }
5848
6233
  const language = parseChoice(io.language, value, LANGUAGES, io.cli.optionLabel.language);
5849
- await writeSettings(io.backlogRoot, { language });
6234
+ await writeSettings(io.backlogRoot, { language }, warnPathErrors(io.warn));
5850
6235
  io.print(`${io.language} \u2192 ${language}`);
5851
6236
  const { found } = await detectAgents(io, warnUnreadableSkipped(io.warn, coreMessages(language)));
5852
6237
  for (const agent of found) await relinkSkill(agent, language, io);
@@ -5893,7 +6278,7 @@ async function runEpic(args, io) {
5893
6278
  const loaded = await loadBacklog(io.backlogRoot);
5894
6279
  const epic = values.to === NO_EPIC ? null : findEpicOrWarn(loaded, io, values.to);
5895
6280
  if (epic === void 0) return EXIT.notFound;
5896
- const move = { loaded, epic, write: taskWriter(io, loaded.tasks), io };
6281
+ const move = { loaded, epic, write: taskWriter(io, indexOfLoaded(loaded)), io };
5897
6282
  return applyAll(new Set(positionals), (id) => moveOne(id, move));
5898
6283
  }
5899
6284
  function findEpicOrWarn(loaded, io, id) {
@@ -5923,16 +6308,16 @@ import { join as join21 } from "node:path";
5923
6308
  import { z as z10 } from "zod";
5924
6309
 
5925
6310
  // src/core/store/json-under-lock.ts
5926
- function updateJsonUnderLock(path, schema, empty, update, options) {
6311
+ function updateJsonUnderLock(path, schema, empty, update, { onErrorAfterPublish, ...lockOptions }) {
5927
6312
  return withFileLock(
5928
6313
  path,
5929
6314
  async () => {
5930
6315
  const next = update(await readJsonFile(path, schema) ?? empty);
5931
6316
  if (next === null) return "unchanged";
5932
- await writeJsonFile(path, next);
6317
+ await writeJsonFile(path, next, { onErrorAfterPublish });
5933
6318
  return "written";
5934
6319
  },
5935
- options
6320
+ lockOptions
5936
6321
  );
5937
6322
  }
5938
6323
 
@@ -5940,12 +6325,18 @@ function updateJsonUnderLock(path, schema, empty, update, options) {
5940
6325
  var HOOK_TURNS_FILE = ".hook-turns.json";
5941
6326
  var CLAIM_WINDOW_MS = 6e4;
5942
6327
  var hookTurnsSchema = z10.record(z10.string(), z10.iso.datetime({ offset: true }));
5943
- async function claimHookTurn(backlogRoot2, turnKey, now) {
5944
- const outcome = await updateJsonUnderLock(join21(backlogRoot2, HOOK_TURNS_FILE), hookTurnsSchema, {}, (turns) => {
5945
- const claimed = Object.entries(turns).filter(([, at]) => now.getTime() - Date.parse(at) < CLAIM_WINDOW_MS);
5946
- if (claimed.some(([key]) => key === turnKey)) return null;
5947
- return { ...Object.fromEntries(claimed), [turnKey]: formatLocalIso(now) };
5948
- });
6328
+ async function claimHookTurn(backlogRoot2, turnKey, { now, onError }) {
6329
+ const outcome = await updateJsonUnderLock(
6330
+ join21(backlogRoot2, HOOK_TURNS_FILE),
6331
+ hookTurnsSchema,
6332
+ {},
6333
+ (turns) => {
6334
+ const claimed = Object.entries(turns).filter(([, at]) => now.getTime() - Date.parse(at) < CLAIM_WINDOW_MS);
6335
+ if (claimed.some(([key]) => key === turnKey)) return null;
6336
+ return { ...Object.fromEntries(claimed), [turnKey]: formatLocalIso(now) };
6337
+ },
6338
+ { onErrorAfterPublish: onError }
6339
+ );
5949
6340
  return outcome === "written";
5950
6341
  }
5951
6342
 
@@ -5967,8 +6358,8 @@ var shownSchema = z11.record(z11.string(), z11.string());
5967
6358
  async function readSignalsShown(projectDir2) {
5968
6359
  return await readJsonFile(join22(projectDir2, SIGNALS_SHOWN_FILE), shownSchema) ?? {};
5969
6360
  }
5970
- async function rememberSignalsShown(projectDir2, signals, today) {
5971
- await updateJsonUnderLock(join22(projectDir2, SIGNALS_SHOWN_FILE), shownSchema, {}, (shown) => markShown(shown, signals, today));
6361
+ async function rememberSignalsShown(projectDir2, signals, today, onError) {
6362
+ await updateJsonUnderLock(join22(projectDir2, SIGNALS_SHOWN_FILE), shownSchema, {}, (shown) => markShown(shown, signals, today), { onErrorAfterPublish: onError });
5972
6363
  }
5973
6364
 
5974
6365
  // src/core/store/session-shown.ts
@@ -5976,17 +6367,31 @@ import { join as join23 } from "node:path";
5976
6367
  import { z as z12 } from "zod";
5977
6368
  var SESSION_SHOWN_FILE = ".candidates-shown.json";
5978
6369
  var SESSION_RETENTION_MS = WEEK_MS;
6370
+ var CODE_STATE_MARK = "@";
5979
6371
  var sessionsShownSchema = z12.record(z12.string(), z12.object({ tasks: z12.array(z12.string()), at: z12.iso.datetime({ offset: true }) }));
6372
+ function shownKey({ taskId, codeState }) {
6373
+ return codeState === void 0 ? taskId : `${taskId}${CODE_STATE_MARK}${codeState}`;
6374
+ }
6375
+ function taskIdOf(key) {
6376
+ return key.split(CODE_STATE_MARK, 1)[0] ?? key;
6377
+ }
5980
6378
  async function readSessionShown(projectDir2, session) {
5981
6379
  const sessions = await readJsonFile(join23(projectDir2, SESSION_SHOWN_FILE), sessionsShownSchema) ?? {};
5982
6380
  return sessions[session]?.tasks ?? [];
5983
6381
  }
5984
- async function rememberSessionShown(projectDir2, session, taskIds, now) {
5985
- await updateJsonUnderLock(join23(projectDir2, SESSION_SHOWN_FILE), sessionsShownSchema, {}, (sessions) => {
5986
- const recent = Object.entries(sessions).filter(([, shown]) => now.getTime() - Date.parse(shown.at) < SESSION_RETENTION_MS);
5987
- const tasks = [.../* @__PURE__ */ new Set([...sessions[session]?.tasks ?? [], ...taskIds])];
5988
- return { ...Object.fromEntries(recent), [session]: { tasks, at: formatLocalIso(now) } };
5989
- });
6382
+ async function rememberSessionShown(projectDir2, session, shown, { now, onError }) {
6383
+ const shownAgain = new Set(shown.map(({ taskId }) => taskId));
6384
+ await updateJsonUnderLock(
6385
+ join23(projectDir2, SESSION_SHOWN_FILE),
6386
+ sessionsShownSchema,
6387
+ {},
6388
+ (sessions) => {
6389
+ const recent = Object.entries(sessions).filter(([, remembered2]) => now.getTime() - Date.parse(remembered2.at) < SESSION_RETENTION_MS);
6390
+ const otherTasks = (sessions[session]?.tasks ?? []).filter((key) => !shownAgain.has(taskIdOf(key)));
6391
+ return { ...Object.fromEntries(recent), [session]: { tasks: [...otherTasks, ...new Set(shown.map(shownKey))], at: formatLocalIso(now) } };
6392
+ },
6393
+ { onErrorAfterPublish: onError }
6394
+ );
5990
6395
  }
5991
6396
 
5992
6397
  // src/core/stats/scope.ts
@@ -6398,18 +6803,19 @@ async function runHook(args, io) {
6398
6803
  const event = parseStopEvent(agent, await io.readStdin());
6399
6804
  if (event === null || event.skip) return EXIT.ok;
6400
6805
  const loaded = await loadBacklog(io.backlogRoot);
6401
- const places = repoPlaces(io);
6402
- const cwdRoots = readGitRoots(event.cwd, places.onUnreadable);
6403
- const project = findProjectForDir(loaded.projects, event.cwd, cwdRoots, places);
6404
- if (!project) return EXIT.ok;
6806
+ const context = repoContext(io);
6807
+ const cwdRoots = readGitRoots(event.cwd, context.onUnreadable);
6808
+ const lookup = lookupProjectForDir(loaded, event.cwd, cwdRoots, context);
6809
+ if (!("project" in lookup)) return EXIT.ok;
6810
+ const { project } = lookup;
6405
6811
  if (!await isFirstHookOfTurn(agent, event, io)) return EXIT.ok;
6406
- const { candidates } = await checkBacklog(io.backlogRoot, loaded, { projectIds: [project.id], mode: "changed", now: io.now(), places, messages: io.core, warn: io.warn, workingRoots: repoRootsOf(cwdRoots) });
6812
+ const { candidates } = await checkBacklog(io.backlogRoot, loaded, { projectIds: [project.id], mode: "changed", now: io.now(), context, messages: io.core, warn: io.warn, workingRoots: repoRootsOf(cwdRoots) });
6407
6813
  const lowPriority = new Set(loaded.tasks.filter((task) => task.priority === "low").map((task) => task.id));
6408
6814
  const pinpointed = candidates.filter((candidate) => !(candidate.kind === "source-changed" && candidate.method === "file"));
6409
6815
  const worthTelling = pinpointed.filter((candidate) => !lowPriority.has(candidate.task.id));
6410
6816
  const lowCount = pinpointed.length - worthTelling.length;
6411
6817
  const session = await sessionMemory(project, event.session, io);
6412
- const blocking = worthTelling.filter((candidate) => !session.told.has(candidate.task.id));
6818
+ const blocking = worthTelling.filter((candidate) => !session.told.has(shownKey(shownTask(candidate))));
6413
6819
  const signals = carriesSystemMessage(agent) ? await freshSignals(
6414
6820
  project,
6415
6821
  loaded.tasks.filter((task) => task.projectId === project.id),
@@ -6423,19 +6829,26 @@ async function runHook(args, io) {
6423
6829
  });
6424
6830
  if (answer !== null) io.print(answer);
6425
6831
  await signals.remember();
6426
- await session.remember(reason?.namedTaskIds ?? []);
6832
+ const named = new Set(reason?.namedTaskIds);
6833
+ await session.remember(blocking.filter((candidate) => named.has(candidate.task.id)).map(shownTask));
6427
6834
  return EXIT.ok;
6428
6835
  }
6836
+ function writesOf(io) {
6837
+ return { now: io.now(), onError: warnPathErrors(io.warn) };
6838
+ }
6429
6839
  async function isFirstHookOfTurn(agent, event, io) {
6430
6840
  if (event.session === void 0 || event.turn === void 0) return true;
6431
6841
  try {
6432
- return await claimHookTurn(io.backlogRoot, `${agent}:${event.session}:${event.turn}`, io.now());
6842
+ return await claimHookTurn(io.backlogRoot, `${agent}:${event.session}:${event.turn}`, writesOf(io));
6433
6843
  } catch (error) {
6434
6844
  if (error instanceof FileBusyError) return false;
6435
6845
  io.warn(io.cli.hookTurnClaimFailed(errorText(error)));
6436
6846
  return true;
6437
6847
  }
6438
6848
  }
6849
+ function shownTask(candidate) {
6850
+ return { taskId: candidate.task.id, codeState: "codeState" in candidate ? candidate.codeState : void 0 };
6851
+ }
6439
6852
  var NO_SESSION_MEMORY = { told: /* @__PURE__ */ new Set(), remember: rememberNothing };
6440
6853
  async function sessionMemory(project, session, io) {
6441
6854
  if (session === void 0) return NO_SESSION_MEMORY;
@@ -6443,8 +6856,8 @@ async function sessionMemory(project, session, io) {
6443
6856
  try {
6444
6857
  return {
6445
6858
  told: new Set(await readSessionShown(projectDir2, session)),
6446
- remember: async (ids) => {
6447
- if (ids.length > 0) await rememberSessionShown(projectDir2, session, ids, io.now()).catch((error) => io.warn(io.cli.sessionShownWriteFailed(errorText(error))));
6859
+ remember: async (shown) => {
6860
+ if (shown.length > 0) await rememberSessionShown(projectDir2, session, shown, writesOf(io)).catch((error) => io.warn(io.cli.sessionShownWriteFailed(errorText(error))));
6448
6861
  }
6449
6862
  };
6450
6863
  } catch (error) {
@@ -6472,7 +6885,7 @@ async function freshSignals(project, tasks, extra, io) {
6472
6885
  }
6473
6886
  async function rememberShown(projectDir2, signals, today, io) {
6474
6887
  try {
6475
- await rememberSignalsShown(projectDir2, signals, today);
6888
+ await rememberSignalsShown(projectDir2, signals, today, warnPathErrors(io.warn));
6476
6889
  } catch (error) {
6477
6890
  io.warn(io.cli.alertsShownWriteFailed(errorText(error)));
6478
6891
  }
@@ -6488,12 +6901,17 @@ function describeTask(task, index) {
6488
6901
  inactiveBlockerIds: task.blockedBy.filter((id) => !open2.some((blocker) => blocker.id === id)),
6489
6902
  blocks: dependentTasks(task, index),
6490
6903
  related: relatedTasks(task, index),
6491
- epic: task.epic === void 0 ? void 0 : index.byId.get(task.epic),
6904
+ epic: task.epic === void 0 ? void 0 : epicReference(task.epic, index),
6492
6905
  children: task.type === "epic" ? epicChildren(task, index) : [],
6493
6906
  warnings: taskWarnings(task, index),
6494
6907
  deletion: scheduledDeletion(task, index)
6495
6908
  };
6496
6909
  }
6910
+ function epicReference(id, index) {
6911
+ const task = index.byId.get(id);
6912
+ if (task !== void 0) return { kind: "loaded", task };
6913
+ return { kind: index.notLoaded.has(id) ? "not-loaded" : "missing", id };
6914
+ }
6497
6915
  function descriptionJson(description) {
6498
6916
  const reference = (task) => ({ id: task.id, title: task.title, status: task.status });
6499
6917
  return {
@@ -6503,7 +6921,7 @@ function descriptionJson(description) {
6503
6921
  openBlockers: description.openBlockers.map(reference),
6504
6922
  blocks: description.blocks.map(reference),
6505
6923
  relatedTasks: description.related.map(reference),
6506
- epicTask: description.epic && reference(description.epic),
6924
+ epicTask: description.epic?.kind === "loaded" ? reference(description.epic.task) : void 0,
6507
6925
  children: description.children.map(reference),
6508
6926
  warnings: description.warnings,
6509
6927
  ...deletionJson(description.deletion)
@@ -6538,13 +6956,13 @@ async function runList(args, io) {
6538
6956
  if (requestedStatuses?.length === 0) throw new UsageError(io.cli.invalidChoice("--status", TASK_STATUSES, values.status ?? ""));
6539
6957
  const statuses = requestedStatuses?.map((status) => parseChoice(io.language, status, TASK_STATUSES, "--status")) ?? OPEN_STATUSES;
6540
6958
  const loaded = await loadBacklog(io.backlogRoot);
6541
- const scope = await resolveScope(loaded, io, values);
6959
+ const scope = resolveScope(loaded, io, values);
6542
6960
  if (scope === null) return EXIT.notFound;
6543
6961
  const projectId = scope.project?.id;
6544
6962
  for (const error of loaded.errors) {
6545
6963
  if (projectId === void 0 || error.projectId === projectId) io.warn(io.cli.parseErrorLine(error.path, io.core.problems(error.problems)));
6546
6964
  }
6547
- const index = buildIndex(loaded.tasks);
6965
+ const index = indexOfLoaded(loaded);
6548
6966
  const inScope = new Set(scope.activeIds);
6549
6967
  const filtered = filterTasks(
6550
6968
  loaded.tasks.filter((task) => inScope.has(task.projectId)),
@@ -6607,8 +7025,9 @@ async function runNew(args, io) {
6607
7025
  const [atSource, body, origin] = await allAfterSettling([
6608
7026
  values.source === void 0 ? void 0 : anchorOf2(project, values.source, io),
6609
7027
  io.readStdin(),
6610
- values.project === void 0 || cwdBelongsTo(project, loaded.projects, io) ? readOrigin(io.cwd) : void 0
7028
+ values.project === void 0 || cwdBelongsTo(project, loaded, io) ? readOrigin(io.cwd) : void 0
6611
7029
  ]);
7030
+ const index = indexOfLoaded(loaded);
6612
7031
  const result = await createTask(io.backlogRoot, {
6613
7032
  project,
6614
7033
  input: {
@@ -6624,7 +7043,7 @@ async function runNew(args, io) {
6624
7043
  related: splitList(values.related),
6625
7044
  body
6626
7045
  },
6627
- existingTasks: loaded.tasks,
7046
+ index,
6628
7047
  now: io.now(),
6629
7048
  via: "cli",
6630
7049
  onError: warnPathErrors(io.warn),
@@ -6636,7 +7055,7 @@ async function runNew(args, io) {
6636
7055
  }
6637
7056
  const { task, reopenedEpic } = result;
6638
7057
  if (reopenedEpic !== void 0) io.warn(io.cli.epicReopened(reopenedEpic.id));
6639
- io.print(values.json ? formatJson(taskJson(task, buildIndex(withWrittenTasks(loaded.tasks, [result])))) : `${task.id} ${task.path}`);
7058
+ io.print(values.json ? formatJson(taskJson(task, indexWithWritten(index, [result]))) : `${task.id} ${task.path}`);
6640
7059
  return EXIT.ok;
6641
7060
  }
6642
7061
  function warnedOfSimilarTask(draft, projectTasks, io) {
@@ -6652,9 +7071,6 @@ async function anchorOf2(project, source, io) {
6652
7071
  if (repo !== void 0) await sourcePresenceOrWarn(io, repo, source);
6653
7072
  return sourceAnchor(repo, source, lookup.onUnreadable);
6654
7073
  }
6655
- function cwdBelongsTo(project, knownProjects, io) {
6656
- return findProjectForCwd([...knownProjects, project], io)?.id === project.id;
6657
- }
6658
7074
  async function allAfterSettling(work) {
6659
7075
  await Promise.allSettled(work);
6660
7076
  return Promise.all(work);
@@ -6703,7 +7119,7 @@ async function changeStatus2(positionals, io) {
6703
7119
  const [id, state, ...rest] = positionals;
6704
7120
  if (id === void 0 || !isProjectState(state) || rest.length > 0) throw usageError(projectCommand, io.language);
6705
7121
  const active = ACTIVE_BY_STATE[state];
6706
- const result = await setProjectActive(io.backlogRoot, id, active);
7122
+ const result = await setProjectActive(io.backlogRoot, id, active, warnPathErrors(io.warn));
6707
7123
  if (!result.ok && result.reason === "invalid") {
6708
7124
  io.warn(`${id}: ${io.core.problems(result.problems)}`);
6709
7125
  return EXIT.invalid;
@@ -6746,7 +7162,7 @@ var pruneCommand = {
6746
7162
  async function runPrune(args, io) {
6747
7163
  const values = parseOptions(io.language, args, { ...SCOPE_OPTIONS, apply: { type: "boolean", default: false } });
6748
7164
  const loaded = await loadBacklog(io.backlogRoot);
6749
- const scope = await resolveScope(loaded, io, values);
7165
+ const scope = resolveScope(loaded, io, values);
6750
7166
  if (scope === null) return EXIT.notFound;
6751
7167
  const { activeIds } = scope;
6752
7168
  const stale = staleLowTasks(
@@ -6762,7 +7178,7 @@ async function runPrune(args, io) {
6762
7178
  io.print(io.cli.cancelStaleHint);
6763
7179
  return EXIT.ok;
6764
7180
  }
6765
- const write = taskWriter(io, loaded.tasks);
7181
+ const write = taskWriter(io, indexOfLoaded(loaded));
6766
7182
  return applyAll(stale, async (task) => {
6767
7183
  const written = await write(task, { status: "cancelled" }, { resolution: "obsolete", reason: io.cli.pruneReason(STALE_LOW_DAYS) });
6768
7184
  if (!written.ok) return written.exitCode;
@@ -6861,14 +7277,19 @@ function isStale(graph, pinned, hashOf) {
6861
7277
  const count3 = (state) => states.filter((candidate) => candidate === state).length;
6862
7278
  return count3("changed") > count3("fresh");
6863
7279
  }
7280
+ function sourcePaths(tasks) {
7281
+ return [...new Set(tasks.flatMap((task) => task.source === void 0 ? [] : [sourcePath(task.source)]))];
7282
+ }
6864
7283
 
6865
7284
  // src/core/store/batch.ts
6866
7285
  async function applyBatch(index, { tasks, action, now, onError }) {
6867
7286
  const ordered = [...tasks].sort((left, right) => compareIds(left.id, right.id));
6868
7287
  const journal = bufferedJournal(appendingJournal(onError));
6869
7288
  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);
7289
+ const [epics, others] = partition(ordered, (task) => {
7290
+ const current = index.byId.get(task.id);
7291
+ return current !== void 0 && closesAfterItsTasks(action, current);
7292
+ });
6872
7293
  const taskOutcomes = await applyInOrder(index, others, step);
6873
7294
  const epicOutcomes = await applyInOrder(indexAfter(index, taskOutcomes), epics, step);
6874
7295
  await journal.flush();
@@ -6881,7 +7302,7 @@ async function applyInOrder(index, tasks, step) {
6881
7302
  }
6882
7303
  function indexAfter(index, outcomes) {
6883
7304
  const done = outcomes.filter((outcome) => outcome.outcome === "done");
6884
- return done.length === 0 ? index : buildIndex(withWrittenTasks([...index.byId.values()], done));
7305
+ return done.length === 0 ? index : indexWithWritten(index, done);
6885
7306
  }
6886
7307
  async function applyOne(index, { id, version }, { action, now, onError, journal }) {
6887
7308
  const current = index.byId.get(id);
@@ -7006,26 +7427,21 @@ function createSnapshotIds() {
7006
7427
  return lastId;
7007
7428
  };
7008
7429
  }
7009
- function pruneUnlessKept(map, projectIds) {
7430
+ function retainProjects(map, projectIds) {
7010
7431
  const kept = new Set(projectIds);
7011
7432
  for (const projectId of map.keys()) if (projectId !== void 0 && !kept.has(projectId)) map.delete(projectId);
7012
7433
  }
7013
7434
  function createScopeMemo() {
7014
7435
  const slots = /* @__PURE__ */ new Map();
7015
7436
  return {
7016
- get: (key, compute, projectId) => {
7437
+ get: (state, compute, projectId) => {
7017
7438
  const remembered2 = slots.get(projectId);
7018
- if (remembered2?.key === key) return remembered2.value;
7439
+ if (remembered2?.state === state) return remembered2.value;
7019
7440
  const value = compute();
7020
- slots.set(projectId, { key, value });
7021
- if (value instanceof Promise) {
7022
- value.catch(() => {
7023
- if (slots.get(projectId)?.value === value) slots.delete(projectId);
7024
- });
7025
- }
7441
+ slots.set(projectId, { state, value });
7026
7442
  return value;
7027
7443
  },
7028
- retain: (projectIds) => pruneUnlessKept(slots, projectIds)
7444
+ retain: (projectIds) => retainProjects(slots, projectIds)
7029
7445
  };
7030
7446
  }
7031
7447
 
@@ -7057,7 +7473,7 @@ function createJournalSources(root) {
7057
7473
  return { journals: tailed.map(({ journal }) => journal), contextOf: rememberedContext(snapshot, tailed) };
7058
7474
  },
7059
7475
  retain: (projectIds) => {
7060
- pruneUnlessKept(tails, projectIds);
7476
+ retainProjects(tails, projectIds);
7061
7477
  remembered2.retain(projectIds);
7062
7478
  }
7063
7479
  };
@@ -7068,6 +7484,7 @@ var serverEn = {
7068
7484
  taskNotFound: (id) => `Task ${id} not found`,
7069
7485
  taskChangedOnDisk: "The task changed on disk",
7070
7486
  projectNotFound: (id) => `Project ${id} not found`,
7487
+ projectFileUnparsed: (path, problems3) => `Project not loaded: ${path} could not be parsed (${problems3})`,
7071
7488
  confirmMismatch: "Confirmation does not match the project id",
7072
7489
  bodyNotParsed: "Request body could not be parsed: JSON expected",
7073
7490
  bodyTooLarge: (mebibytes) => `Request body is larger than ${mebibytes} MiB`,
@@ -7097,6 +7514,7 @@ Backlog directory: ${root}`,
7097
7514
  portBusy: (port) => `port ${port} is already in use`,
7098
7515
  codeCacheReadFailed: (detail) => `Could not read the git cache: ${detail}`,
7099
7516
  codeCacheWriteFailed: (detail) => `Could not save the git cache: ${detail}`,
7517
+ projectsListenerFailed: (detail) => `Could not pass the new project list to the caches, stale entries stay until the next load: ${detail}`,
7100
7518
  journalReadFailed: (path, detail) => `Could not read the journal ${path}, "Closed by agent" will also list this project's tasks closed in the web: ${detail}`
7101
7519
  };
7102
7520
 
@@ -7105,6 +7523,7 @@ var serverRu = {
7105
7523
  taskNotFound: (id) => `\u0417\u0430\u0434\u0430\u0447\u0430 ${id} \u043D\u0435 \u043D\u0430\u0439\u0434\u0435\u043D\u0430`,
7106
7524
  taskChangedOnDisk: "\u0417\u0430\u0434\u0430\u0447\u0430 \u0438\u0437\u043C\u0435\u043D\u0438\u043B\u0430\u0441\u044C \u043D\u0430 \u0434\u0438\u0441\u043A\u0435",
7107
7525
  projectNotFound: (id) => `\u041F\u0440\u043E\u0435\u043A\u0442 ${id} \u043D\u0435 \u043D\u0430\u0439\u0434\u0435\u043D`,
7526
+ 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})`,
7108
7527
  confirmMismatch: "\u041F\u043E\u0434\u0442\u0432\u0435\u0440\u0436\u0434\u0435\u043D\u0438\u0435 \u043D\u0435 \u0441\u043E\u0432\u043F\u0430\u0434\u0430\u0435\u0442 \u0441 id \u043F\u0440\u043E\u0435\u043A\u0442\u0430",
7109
7528
  bodyNotParsed: "\u0422\u0435\u043B\u043E \u0437\u0430\u043F\u0440\u043E\u0441\u0430 \u043D\u0435 \u0440\u0430\u0437\u043E\u0431\u0440\u0430\u043D\u043E: \u043E\u0436\u0438\u0434\u0430\u0435\u0442\u0441\u044F JSON",
7110
7529
  bodyTooLarge: (mebibytes) => `\u0422\u0435\u043B\u043E \u0437\u0430\u043F\u0440\u043E\u0441\u0430 \u0431\u043E\u043B\u044C\u0448\u0435 ${mebibytes} \u041C\u0438\u0411`,
@@ -7134,6 +7553,7 @@ var serverRu = {
7134
7553
  portBusy: (port) => `\u043F\u043E\u0440\u0442 ${port} \u0443\u0436\u0435 \u0437\u0430\u043D\u044F\u0442`,
7135
7554
  codeCacheReadFailed: (detail) => `\u041D\u0435 \u0443\u0434\u0430\u043B\u043E\u0441\u044C \u043F\u0440\u043E\u0447\u0438\u0442\u0430\u0442\u044C \u043A\u044D\u0448 git: ${detail}`,
7136
7555
  codeCacheWriteFailed: (detail) => `\u041D\u0435 \u0443\u0434\u0430\u043B\u043E\u0441\u044C \u0441\u043E\u0445\u0440\u0430\u043D\u0438\u0442\u044C \u043A\u044D\u0448 git: ${detail}`,
7556
+ projectsListenerFailed: (detail) => `\u041D\u0435 \u0443\u0434\u0430\u043B\u043E\u0441\u044C \u043F\u0435\u0440\u0435\u0434\u0430\u0442\u044C \u043A\u044D\u0448\u0430\u043C \u043D\u043E\u0432\u044B\u0439 \u0441\u043F\u0438\u0441\u043E\u043A \u043F\u0440\u043E\u0435\u043A\u0442\u043E\u0432, \u043B\u0438\u0448\u043D\u0438\u0435 \u0437\u0430\u043F\u0438\u0441\u0438 \u043E\u0441\u0442\u0430\u043D\u0443\u0442\u0441\u044F \u0434\u043E \u0441\u043B\u0435\u0434\u0443\u044E\u0449\u0435\u0439 \u0437\u0430\u0433\u0440\u0443\u0437\u043A\u0438: ${detail}`,
7137
7557
  journalReadFailed: (path, detail) => `\u041D\u0435 \u0443\u0434\u0430\u043B\u043E\u0441\u044C \u043F\u0440\u043E\u0447\u0438\u0442\u0430\u0442\u044C \u0436\u0443\u0440\u043D\u0430\u043B ${path}, \xAB\u0417\u0430\u043A\u0440\u044B\u0442\u044B \u0430\u0433\u0435\u043D\u0442\u043E\u043C\xBB \u043F\u043E\u043A\u0430\u0436\u0435\u0442 \u0438 \u0437\u0430\u043A\u0440\u044B\u0442\u044B\u0435 \u0432 \u0432\u0435\u0431\u0435 \u0437\u0430\u0434\u0430\u0447\u0438 \u043F\u0440\u043E\u0435\u043A\u0442\u0430: ${detail}`
7138
7558
  };
7139
7559
 
@@ -7148,26 +7568,26 @@ function localizedWarn(readLanguage, warn2) {
7148
7568
  // src/server/ttl-cache.ts
7149
7569
  function createTtlCache({ ttlMs, now }) {
7150
7570
  const entries = /* @__PURE__ */ new Map();
7151
- const evictExpired = (moment) => {
7152
- for (const [key, entry] of entries) if (moment - entry.at > ttlMs) entries.delete(key);
7571
+ const forgetExpired = (moment) => {
7572
+ for (const [slot, entry] of entries) if (moment - entry.at > ttlMs) entries.delete(slot);
7153
7573
  };
7154
7574
  return {
7155
- get: (key, compute, tags = []) => {
7575
+ get: ({ slot, state }, compute, tags = []) => {
7156
7576
  const moment = now();
7157
- evictExpired(moment);
7158
- const cached = entries.get(key);
7159
- if (cached !== void 0) return cached.value;
7577
+ forgetExpired(moment);
7578
+ const cached = entries.get(slot);
7579
+ if (cached?.state === state) return cached.value;
7160
7580
  const value = compute();
7161
- entries.set(key, { at: moment, value, tags });
7581
+ entries.set(slot, { at: moment, state, value, tags });
7162
7582
  value.catch(() => {
7163
- if (entries.get(key)?.value === value) entries.delete(key);
7583
+ if (entries.get(slot)?.value === value) entries.delete(slot);
7164
7584
  });
7165
7585
  return value;
7166
7586
  },
7167
- clear: () => entries.clear(),
7168
- clearTagged: (tags) => {
7587
+ forgetAll: () => entries.clear(),
7588
+ forgetTagged: (tags) => {
7169
7589
  const tagged = new Set(tags);
7170
- for (const [key, entry] of entries) if (entry.tags.some((tag) => tagged.has(tag))) entries.delete(key);
7590
+ for (const [slot, entry] of entries) if (entry.tags.some((tag) => tagged.has(tag))) entries.delete(slot);
7171
7591
  },
7172
7592
  size: () => entries.size
7173
7593
  };
@@ -7228,11 +7648,24 @@ function tasksClosedInWeb(tasks, journals) {
7228
7648
  // src/server/snapshot-cache.ts
7229
7649
  function createSnapshotCache({ root, revisions, journalSources, warn: warn2 }) {
7230
7650
  let snapshot = null;
7651
+ let loadsStarted = 0;
7652
+ const projectsListeners = [];
7653
+ const announceProjects = (projects) => {
7654
+ for (const listener of projectsListeners) {
7655
+ try {
7656
+ listener(projects);
7657
+ } catch (error) {
7658
+ void warn2((messages) => messages.projectsListenerFailed(errorText(error)));
7659
+ }
7660
+ }
7661
+ };
7231
7662
  return {
7232
7663
  read: () => {
7233
7664
  if (snapshot !== null) return snapshot;
7665
+ loadsStarted += 1;
7666
+ const load = loadsStarted;
7234
7667
  const loading = loadSnapshot(root, revisions.current(), journalSources, warn2).then((loaded) => {
7235
- if (snapshot === loading) journalSources.retain(loaded.projects.map((project) => project.id));
7668
+ if (load === loadsStarted) announceProjects(loaded.projects);
7236
7669
  return loaded;
7237
7670
  });
7238
7671
  snapshot = loading;
@@ -7243,6 +7676,9 @@ function createSnapshotCache({ root, revisions, journalSources, warn: warn2 }) {
7243
7676
  },
7244
7677
  forget: () => {
7245
7678
  snapshot = null;
7679
+ },
7680
+ onProjects: (listener) => {
7681
+ projectsListeners.push(listener);
7246
7682
  }
7247
7683
  };
7248
7684
  }
@@ -7291,7 +7727,7 @@ async function loadSnapshot(root, revision, journalSources, warn2) {
7291
7727
  return { projectId, events: [], invalidLines: 0 };
7292
7728
  });
7293
7729
  const journals = await Promise.all(projectIds.map(readableJournal));
7294
- return { ...loaded, index: buildIndex(loaded.tasks), closedInWeb: tasksClosedInWeb(loaded.tasks, journals), revision };
7730
+ return { ...loaded, index: indexOfLoaded(loaded), closedInWeb: tasksClosedInWeb(loaded.tasks, journals), revision };
7295
7731
  }
7296
7732
 
7297
7733
  // src/server/stats-api.ts
@@ -7338,7 +7774,7 @@ function createCodeCacheFile(root) {
7338
7774
  const snapshot = await readJsonFile(path, snapshotSchema);
7339
7775
  return snapshot === null ? emptyCodeCache() : { repos: snapshot.repos, fixes: snapshot.fixes, unsettled: snapshot.unsettled };
7340
7776
  },
7341
- write: (snapshot) => writeFileAtomic(path, JSON.stringify({ version: CODE_CACHE_VERSION, ...snapshot }))
7777
+ write: (snapshot) => writeRecomputableFileAtomic(path, JSON.stringify({ version: CODE_CACHE_VERSION, ...snapshot }))
7342
7778
  };
7343
7779
  }
7344
7780
 
@@ -7383,7 +7819,7 @@ function forgetStaleFixes(memory, now, requested) {
7383
7819
  forgetFix(memory, key);
7384
7820
  }
7385
7821
  }
7386
- function keepOnlyRepos(memory, kept) {
7822
+ function retainRepos(memory, kept) {
7387
7823
  for (const repo of memory.repos.keys()) if (!kept.has(repo)) memory.repos.delete(repo);
7388
7824
  for (const key of /* @__PURE__ */ new Set([...memory.fixes.keys(), ...memory.unsettledCheckedAt.keys()])) if (!kept.has(repoOfFixKey(key))) forgetFix(memory, key);
7389
7825
  }
@@ -7652,8 +8088,8 @@ function createCodeSource({ home: home2, git = runGit, store, onError = () => {
7652
8088
  const cache = cachePersistence(memory, store, onError);
7653
8089
  const repoCode = repoReader(git, memory);
7654
8090
  let retainedRepos = null;
7655
- const pruneAndPersist = () => {
7656
- if (retainedRepos !== null) keepOnlyRepos(memory, retainedRepos);
8091
+ const retainAndPersist = () => {
8092
+ if (retainedRepos !== null) retainRepos(memory, retainedRepos);
7657
8093
  return cache.persist();
7658
8094
  };
7659
8095
  const expanded = (projects) => [...new Set(projects.flatMap((project) => project.repos.map((repo) => expandHome(repo, home2))))];
@@ -7662,8 +8098,8 @@ function createCodeSource({ home: home2, git = runGit, store, onError = () => {
7662
8098
  retainedRepos = new Set(expanded(backlogProjects));
7663
8099
  },
7664
8100
  stateKey: async (projects) => {
7665
- const states = await Promise.all(expanded(projects).map(async (repo) => `${repo}@${refsKey(await readRefs(git, repo))}`));
7666
- return states.join(" ");
8101
+ const states = await Promise.all(expanded(projects).map(async (repo) => [repo, refsKey(await readRefs(git, repo))]));
8102
+ return JSON.stringify(states);
7667
8103
  },
7668
8104
  collect: async (projects, now) => {
7669
8105
  await cache.restore();
@@ -7675,7 +8111,7 @@ function createCodeSource({ home: home2, git = runGit, store, onError = () => {
7675
8111
  );
7676
8112
  const projectCodes = scanned.map(({ project, repos }) => ({ projectId: project.id, name: project.name, repos: repos.flatMap(({ read }) => read === null ? [] : [read]) }));
7677
8113
  const unavailableRepos = [...new Set(scanned.flatMap(({ repos }) => repos.filter(({ read }) => read === null).map(({ repo }) => repo)))];
7678
- await pruneAndPersist();
8114
+ await retainAndPersist();
7679
8115
  return { projects: projectCodes, unavailableRepos };
7680
8116
  },
7681
8117
  fixCommits: async (projects, requests, now) => {
@@ -7686,7 +8122,7 @@ function createCodeSource({ home: home2, git = runGit, store, onError = () => {
7686
8122
  const lookups = fixLookups(requests, reposOfProject);
7687
8123
  const found = new Map(lookups.flatMap(({ key, repoKeys }) => cachedFixEntries(memory, key, repoKeys)));
7688
8124
  forgetStaleFixes(memory, now, new Set(lookups.flatMap(({ repoKeys }) => repoKeys)));
7689
- await pruneAndPersist();
8125
+ await retainAndPersist();
7690
8126
  return found;
7691
8127
  }
7692
8128
  };
@@ -8275,46 +8711,44 @@ function average(values) {
8275
8711
  // src/server/cost-source.ts
8276
8712
  function createCostSource(root, home2) {
8277
8713
  const runsTail = createJsonlTail(join27(root, RUNS_FILE), cliRunSchema);
8278
- const places = { home: home2, onUnreadable: unreadablePathHasNoProject };
8714
+ const context = { home: home2, onUnreadable: unreadablePathHasNoProject };
8279
8715
  const lookupRepoRoot = cachedRepoRoots({ onUnreadable: unreadablePathHasNoProject });
8280
- const costMemos = createScopeMemo();
8281
- const snapshotIdOf = createSnapshotIds();
8282
8716
  return {
8283
- costReport: async (request) => {
8284
- const { values: runs, length, generation } = await runsTail.read();
8285
- const inputs = { ...request, runs };
8286
- const keyParts = {
8287
- usage: inputs.usage.revision,
8288
- runs: [generation, length],
8289
- scope: [snapshotIdOf(inputs.scope.snapshot), inputs.scope.projects.map((project) => project.id)],
8290
- now: formatLocalDay(inputs.now)
8291
- };
8292
- return costMemos.get(JSON.stringify(keyParts), () => computeCostReport(inputs, places, lookupRepoRoot), inputs.scope.projectId);
8717
+ stateKey: async (usage) => {
8718
+ const { length, generation } = await runsTail.read();
8719
+ return JSON.stringify([usage.revision, generation, length]);
8293
8720
  },
8294
- retain: costMemos.retain
8721
+ costReport: async (request) => {
8722
+ const { values: runs } = await runsTail.read();
8723
+ return computeCostReport({ ...request, runs }, context, lookupRepoRoot);
8724
+ }
8295
8725
  };
8296
8726
  }
8297
- async function computeCostReport({ usage: { cache, scan }, runs, scope: { projects, projectId }, now }, places, lookupRepoRoot) {
8727
+ async function computeCostReport({ usage: { cache, scan }, runs, known, projectId, now }, context, lookupRepoRoot) {
8298
8728
  const buckets = usageBucketsOf(cache);
8299
- const repoRoots = projectId === void 0 ? /* @__PURE__ */ new Map() : await resolveRepoRoots(
8300
- lookupRepoRoot,
8301
- [...buckets, ...runs].map((entry) => entry.cwd)
8729
+ const projectIds = projectId === void 0 ? /* @__PURE__ */ new Map() : await projectIdsOfCwds(
8730
+ [...buckets, ...runs].map((entry) => entry.cwd),
8731
+ known,
8732
+ context,
8733
+ lookupRepoRoot
8734
+ );
8735
+ return costReport({ buckets, runs, projectOf: (cwd) => projectIds.get(cwd) ?? null, projectId, now, scan });
8736
+ }
8737
+ async function projectIdsOfCwds(cwds, known, context, lookupRepoRoot) {
8738
+ const unique = [...new Set(cwds)];
8739
+ const dirRoots = await Promise.all(unique.map(lookupRepoRoot));
8740
+ return new Map(
8741
+ unique.map((cwd, position) => {
8742
+ const lookup = lookupProjectForDir(known, cwd, dirRoots[position] ?? "unreadable", context);
8743
+ return [cwd, "project" in lookup ? lookup.project.id : null];
8744
+ })
8302
8745
  );
8303
- const projectOf2 = (cwd) => {
8304
- const roots = repoRoots.get(cwd) ?? null;
8305
- return roots === null ? null : findProjectForRoots(projects, roots, places)?.id ?? null;
8306
- };
8307
- return costReport({ buckets, runs, projectOf: projectOf2, projectId, now, scan });
8308
8746
  }
8309
8747
  function unreadablePathHasNoProject() {
8310
8748
  }
8311
8749
  function usageBucketsOf(cache) {
8312
8750
  return Object.values(cache.files).flatMap((entry) => entry.buckets);
8313
8751
  }
8314
- async function resolveRepoRoots(lookupRepoRoot, cwds) {
8315
- const unique = [...new Set(cwds)];
8316
- return new Map(await Promise.all(unique.map(async (cwd) => [cwd, await lookupRepoRoot(cwd)])));
8317
- }
8318
8752
 
8319
8753
  // src/server/stats-api.ts
8320
8754
  var REPORT_TTL_MS = 5 * MINUTE_MS;
@@ -8327,57 +8761,47 @@ function createStatsApi({ root, readLanguage, now, home: home2, services: { usag
8327
8761
  const onCodeSourceError = (kind, error) => void warn2((messages) => kind === "read" ? messages.codeCacheReadFailed(errorText(error)) : messages.codeCacheWriteFailed(errorText(error)));
8328
8762
  const codeSource = createCodeSource({ home: home2, store: createCodeCacheFile(root), onError: onCodeSourceError });
8329
8763
  const costSource = createCostSource(root, home2);
8330
- const backlogPruningCaches = async () => {
8331
- const snapshot = await backlog();
8332
- const projectIds = snapshot.projects.map((project) => project.id);
8333
- reports.knowProjects(projectIds);
8334
- costSource.retain(projectIds);
8335
- codeSource.retain(snapshot.projects);
8336
- return snapshot;
8337
- };
8338
8764
  const serveScoped = (kind, report, { sourceKey, wholeBacklog = false } = {}) => routes.get(STATS_REPORT_ROUTES[kind], async (c) => {
8339
8765
  const cachedUnlessForgotten = reports.startRead();
8340
- const scope = await requestScopeOf(c, await backlogPruningCaches(), { wholeBacklog, readLanguage });
8766
+ const scope = await requestScopeOf(c, await backlog(), { wholeBacklog, readLanguage });
8341
8767
  if (!scope.ok) return scope.response;
8342
8768
  const moment = now();
8343
- const key = JSON.stringify([kind, scope.projectId ?? null, formatLocalDay(moment), sourceKey === void 0 ? null : await sourceKey(scope.projects, scope.snapshot)]);
8344
- const tags = wholeBacklog ? [WHOLE_BACKLOG_TAG] : [scope.projectId === void 0 ? ALL_PROJECTS_TAG : projectTag(scope.projectId)];
8345
- const compute = async () => {
8346
- const { journals, contextOf } = await journalSources.read(
8347
- scope.snapshot,
8348
- scope.projects.map((project) => project.id)
8349
- );
8350
- const input = { tasks: scope.tasks, journals, now: moment, projectId: scope.projectId, unparsedTasks: scope.unparsedTasks };
8351
- const wholeBacklogContext = () => contextOf({ ...input, projectId: void 0 });
8352
- return report({ context: contextOf(input), projects: scope.projects, snapshot: scope.snapshot, wholeBacklogContext });
8769
+ const key = {
8770
+ slot: JSON.stringify([kind, scope.projectId ?? null]),
8771
+ state: JSON.stringify([formatLocalDay(moment), sourceKey === void 0 ? null : await sourceKey(scope.projects, scope.snapshot)])
8353
8772
  };
8773
+ const tags = wholeBacklog ? [WHOLE_BACKLOG_TAG] : [scope.projectId === void 0 ? ALL_PROJECTS_TAG : projectTag(scope.projectId)];
8774
+ const compute = async () => report(reportSources(scope, moment, journalSources));
8354
8775
  return c.json(await cachedUnlessForgotten(key, compute, tags));
8355
8776
  });
8356
- const statsOfCode = async ({ context, projects }) => codeReport(context, await codeSource.collect(projects, context.input.now));
8357
- const statsOfEffect = async ({ context, projects, wholeBacklogContext }) => {
8358
- const { projectId, now: now2 } = context.input;
8359
- const backlogContext = projectId === void 0 ? context : wholeBacklogContext();
8360
- const code = await codeSource.collect(projectsInScope(projects, projectId), now2);
8361
- const fixCommits = await codeSource.fixCommits(projects, fixRequests(backlogContext.histories, now2), now2);
8362
- return effectReport(context, { ...code, fixCommits }, backlogContext);
8777
+ const statsOfCode = async ({ context, projects, at }) => codeReport(await context(), await codeSource.collect(projects, at));
8778
+ const statsOfEffect = async ({ context, projectId, at, projects, wholeBacklogContext }) => {
8779
+ const scopedContext = await context();
8780
+ const backlogContext = projectId === void 0 ? scopedContext : await wholeBacklogContext();
8781
+ const code = await codeSource.collect(projectsInScope(projects, projectId), at);
8782
+ const fixCommits = await codeSource.fixCommits(projects, fixRequests(backlogContext.histories, at), at);
8783
+ return effectReport(scopedContext, { ...code, fixCommits }, backlogContext);
8784
+ };
8785
+ const statsOfQuality = async ({ context, projects, snapshot }) => qualityReport(await context(), await graphRowsOf(graphHealth2, projects, snapshot));
8786
+ const statsOfCost = ({ projectId, at, snapshot }) => {
8787
+ usage.scanIfNeverListed();
8788
+ return costSource.costReport({ usage: usage.snapshot(), known: snapshot, projectId, now: at });
8363
8789
  };
8364
- const statsOfQuality = async ({ context, projects, snapshot }) => qualityReport(context, await graphRowsOf(graphHealth2, projects, snapshot));
8365
8790
  const codeState = { sourceKey: (projects) => codeSource.stateKey(projects) };
8366
8791
  const graphState = { sourceKey: async (projects, snapshot) => JSON.stringify(await graphRowsOf(graphHealth2, projects, snapshot)) };
8367
- serveScoped("overview", ({ context }) => statsReport(context));
8792
+ const usageState = { sourceKey: () => costSource.stateKey(usage.snapshot()) };
8793
+ serveScoped("overview", async ({ context }) => statsReport(await context()));
8368
8794
  serveScoped("code", statsOfCode, codeState);
8369
8795
  serveScoped("effect", statsOfEffect, { ...codeState, wholeBacklog: true });
8370
8796
  serveScoped("quality", statsOfQuality, graphState);
8371
- serveScoped("signals", ({ context }) => ({ signals: statsSignals(context) }));
8372
- routes.get(STATS_REPORT_ROUTES.cost, async (c) => {
8373
- const scope = await requestScopeOf(c, await backlogPruningCaches(), { wholeBacklog: true, readLanguage });
8374
- if (!scope.ok) return scope.response;
8375
- usage.scanIfNeverListed();
8376
- const { snapshot, projects, projectId } = scope;
8377
- return c.json(await costSource.costReport({ usage: usage.snapshot(), scope: { snapshot, projects, projectId }, now: now() }));
8378
- });
8797
+ serveScoped("signals", async ({ context }) => ({ signals: statsSignals(await context()) }));
8798
+ serveScoped("cost", statsOfCost, { ...usageState, wholeBacklog: true });
8379
8799
  routes.get(STATS_MEMORY_ROUTE, (c) => c.json({ samples: memory.samples() }));
8380
- return { routes, forgetAll: reports.forgetAll, forgetChanged: reports.forgetChanged };
8800
+ const retain = (projects) => {
8801
+ reports.knowProjects(projects.map((project) => project.id));
8802
+ codeSource.retain(projects);
8803
+ };
8804
+ return { routes, forgetAll: reports.forgetAll, forgetChanged: reports.forgetChanged, retain };
8381
8805
  }
8382
8806
  function createForgettingReportCache(root, now) {
8383
8807
  const reports = createTtlCache({ ttlMs: REPORT_TTL_MS, now: () => now().getTime() });
@@ -8389,13 +8813,13 @@ function createForgettingReportCache(root, now) {
8389
8813
  };
8390
8814
  const forgetAll = () => {
8391
8815
  forgetCount += 1;
8392
- reports.clear();
8816
+ reports.forgetAll();
8393
8817
  };
8394
8818
  const forgetChanged = (paths) => {
8395
8819
  const changedProjectIds = paths.map(projectIdOfPath);
8396
8820
  if (!changedProjectIds.every((projectId) => projectId !== void 0)) return forgetAll();
8397
8821
  forgetCount += 1;
8398
- reports.clearTagged([ALL_PROJECTS_TAG, WHOLE_BACKLOG_TAG, ...changedProjectIds.map(projectTag)]);
8822
+ reports.forgetTagged([ALL_PROJECTS_TAG, WHOLE_BACKLOG_TAG, ...changedProjectIds.map(projectTag)]);
8399
8823
  };
8400
8824
  const startRead = () => {
8401
8825
  const forgetCountAtRead = forgetCount;
@@ -8406,17 +8830,35 @@ function createForgettingReportCache(root, now) {
8406
8830
  };
8407
8831
  return { startRead, knowProjects, forgetAll, forgetChanged };
8408
8832
  }
8833
+ function reportSources(scope, now, journalSources) {
8834
+ const { projectId, projects, snapshot, tasks } = scope;
8835
+ let sources;
8836
+ const contextFor = async (contextProjectId) => {
8837
+ const { journals, contextOf } = await (sources ??= journalSources.read(
8838
+ snapshot,
8839
+ projects.map((project) => project.id)
8840
+ ));
8841
+ return contextOf({ tasks, journals, now, projectId: contextProjectId, unparsedTasks: scope.unparsedTasks });
8842
+ };
8843
+ return { projectId, at: now, projects, snapshot, context: () => contextFor(projectId), wholeBacklogContext: () => contextFor(void 0) };
8844
+ }
8409
8845
  async function requestScopeOf(c, snapshot, { wholeBacklog, readLanguage }) {
8410
8846
  const projectId = c.req.query("project") || void 0;
8411
8847
  const { projects, tasks, errors } = snapshot;
8412
8848
  if (projectId !== void 0 && !projects.some((project) => project.id === projectId)) {
8413
- return { ok: false, response: errorResponse(c, 404, serverMessages(await readLanguage()).projectNotFound(projectId)) };
8849
+ return { ok: false, response: unknownProjectResponse(c, errors, projectId, await readLanguage()) };
8414
8850
  }
8415
8851
  const scoped = projectsInScope(projects, projectId, { wholeBacklog });
8416
8852
  const scopedIds = new Set(scoped.map((project) => project.id));
8417
8853
  const inScope = (task) => scopedIds.has(task.projectId);
8418
8854
  return { ok: true, projectId, projects: scoped, tasks: tasks.filter(inScope), unparsedTasks: unparsedTasks(errors).filter(inScope), snapshot };
8419
8855
  }
8856
+ function unknownProjectResponse(c, errors, projectId, language) {
8857
+ const messages = serverMessages(language);
8858
+ const broken = unparsedProjectFileOf(errors, projectId);
8859
+ if (broken === void 0) return errorResponse(c, 404, messages.projectNotFound(projectId));
8860
+ return errorResponse(c, 422, messages.projectFileUnparsed(broken.path, coreMessages(language).problems(broken.problems)));
8861
+ }
8420
8862
  function graphRowsOf(graphHealth2, projects, snapshot) {
8421
8863
  return Promise.all(projects.map(async (project) => ({ projectId: project.id, name: project.name, ...await graphHealth2(snapshot, project) })));
8422
8864
  }
@@ -8429,6 +8871,10 @@ function createApi({ root, readLanguage, changes, now, home: home2, statsService
8429
8871
  const snapshots = createSnapshotCache({ root, revisions, journalSources, warn: statsServices.warn });
8430
8872
  const graphHealth2 = rememberedGraphHealth(home2, now);
8431
8873
  const stats = createStatsApi({ root, readLanguage, now, home: home2, services: statsServices, backlog: snapshots.read, graphHealth: graphHealth2, journalSources });
8874
+ snapshots.onProjects((projects) => {
8875
+ journalSources.retain(projects.map((project) => project.id));
8876
+ stats.retain(projects);
8877
+ });
8432
8878
  const changeHub = createChangeHub({ revisions, snapshots, derived: stats, changes });
8433
8879
  const onWriteError = warnPathErrors((line) => void statsServices.warn(() => line));
8434
8880
  const deps = { root, readLanguage, now, backlog: snapshots.read, graphHealth: graphHealth2, changeHub, onWriteError };
@@ -8449,8 +8895,8 @@ function rememberedGraphHealth(home2, now) {
8449
8895
  const graphHealths = createTtlCache({ ttlMs: GRAPH_STATE_TTL_MS, now: () => now().getTime() });
8450
8896
  return ({ tasks }, project) => {
8451
8897
  const projectTasks = tasks.filter((task) => task.projectId === project.id);
8452
- const key = JSON.stringify([project.id, project.repos, projectTasks.map((task) => task.version)]);
8453
- return graphHealths.get(key, () => projectGraphHealth(project, projectTasks, home2));
8898
+ const state = JSON.stringify([project.repos, projectTasks.map((task) => task.version)]);
8899
+ return graphHealths.get({ slot: project.id, state }, () => projectGraphHealth(project, projectTasks, home2));
8454
8900
  };
8455
8901
  }
8456
8902
  async function listProjects2(c, { backlog, graphHealth: graphHealth2 }) {
@@ -8460,14 +8906,20 @@ async function listProjects2(c, { backlog, graphHealth: graphHealth2 }) {
8460
8906
  return c.json({ projects: await Promise.all(projects.map(withGraph)), revision });
8461
8907
  }
8462
8908
  async function listTasks(c, { backlog, readLanguage }) {
8463
- const [{ tasks, closedInWeb, errors, revision }, language] = await Promise.all([backlog(), readLanguage()]);
8909
+ const [{ tasks, index, closedInWeb, errors, revision }, language] = await Promise.all([backlog(), readLanguage()]);
8464
8910
  const messages = coreMessages(language);
8465
- return c.json({ tasks, closedInWeb, errors: errors.map(({ problems: problems3, ...error }) => ({ ...error, message: messages.problems(problems3) })), revision });
8911
+ return c.json({
8912
+ tasks,
8913
+ closedInWeb,
8914
+ errors: errors.map(({ path, projectId, fileKind, problems: problems3 }) => ({ path, projectId, fileKind, message: messages.problems(problems3) })),
8915
+ notLoadedTasks: [...index.notLoaded].map(([id, fileKind]) => ({ id, fileKind })),
8916
+ revision
8917
+ });
8466
8918
  }
8467
- async function updateSettings(c, { root, readLanguage }) {
8919
+ async function updateSettings(c, { root, readLanguage, onWriteError }) {
8468
8920
  const body = await readBody(c, settingsRequestSchema, readLanguage);
8469
8921
  if (!body.ok) return body.response;
8470
- await writeSettings(root, body.data);
8922
+ await writeSettings(root, body.data, onWriteError);
8471
8923
  return c.json({ language: body.data.language });
8472
8924
  }
8473
8925
  async function updateTask(c, id, { readLanguage, backlog, now, changeHub, onWriteError }) {
@@ -8478,7 +8930,10 @@ async function updateTask(c, id, { readLanguage, backlog, now, changeHub, onWrit
8478
8930
  const result = await changeHub.ownWrite(update, (updated) => updated.ok ? writtenTasks(updated) : []);
8479
8931
  if (result.ok) return c.json(result.task);
8480
8932
  const messages = serverMessages(body.language);
8481
- if (result.reason === "not-found") return errorResponse(c, 404, messages.taskNotFound(id));
8933
+ if (result.reason === "not-found") {
8934
+ const unparsedFile = index.notLoaded.get(id);
8935
+ return errorResponse(c, 404, unparsedFile === void 0 ? messages.taskNotFound(id) : coreMessages(body.language).taskNotLoaded(id, unparsedFile));
8936
+ }
8482
8937
  if (result.reason === "conflict") return c.json({ errors: [messages.taskChangedOnDisk], current: result.current }, 409);
8483
8938
  if (result.reason === "busy") return fileBusyResponse(c, body.language, result);
8484
8939
  return invalidResponse(c, result, coreMessages(body.language));
@@ -8491,12 +8946,12 @@ async function updateTaskBatch(c, { readLanguage, backlog, now, changeHub, onWri
8491
8946
  const outcomes = await changeHub.ownWrite(batch, (applied) => applied.flatMap((outcome) => outcome.outcome === "done" ? writtenTasks(outcome) : []));
8492
8947
  const messages = serverMessages(body.language);
8493
8948
  const core = coreMessages(body.language);
8494
- return c.json({ results: outcomes.map((outcome) => viewOf(outcome, messages, core)) });
8949
+ return c.json({ results: outcomes.map((outcome) => viewOf(outcome, { messages, core, notLoaded: index.notLoaded })) });
8495
8950
  }
8496
- async function setProjectActivity(c, id, { root, readLanguage, changeHub }) {
8951
+ async function setProjectActivity(c, id, { root, readLanguage, changeHub, onWriteError }) {
8497
8952
  const body = await readBody(c, projectActiveSchema, readLanguage);
8498
8953
  if (!body.ok) return body.response;
8499
- const result = await setProjectActive(root, id, body.data.active).finally(changeHub.forgetAll);
8954
+ const result = await setProjectActive(root, id, body.data.active, onWriteError).finally(changeHub.forgetAll);
8500
8955
  if (result.ok) return c.json(result.project);
8501
8956
  if (result.reason === "invalid") return errorResponse(c, 422, coreMessages(body.language).problems(result.problems));
8502
8957
  return errorResponse(c, 404, serverMessages(body.language).projectNotFound(id));
@@ -8525,11 +8980,15 @@ function revisionEvents(c, changeHub, closed) {
8525
8980
  function invalidResponse(c, result, messages) {
8526
8981
  return errorResponse(c, 422, ...result.problems.map(messages.problem));
8527
8982
  }
8528
- function viewOf(outcome, messages, core) {
8983
+ function viewOf(outcome, texts) {
8529
8984
  if (outcome.outcome === "done") return { id: outcome.id, outcome: "done", version: outcome.task.version, previous: outcome.previous };
8530
- if (outcome.reason === "failed") return { id: outcome.id, outcome: "skipped", reason: outcome.reason, message: messages.batchFailed(outcome.id, outcome.detail) };
8531
- const message = outcome.reason === "invalid" && outcome.problems ? core.problems(outcome.problems) : messages.batchSkipped[outcome.reason](outcome.id);
8532
- return { id: outcome.id, outcome: "skipped", reason: outcome.reason, message };
8985
+ return { id: outcome.id, outcome: "skipped", reason: outcome.reason, message: skipMessage(outcome, texts) };
8986
+ }
8987
+ function skipMessage(outcome, { messages, core, notLoaded }) {
8988
+ if (outcome.reason === "failed") return messages.batchFailed(outcome.id, outcome.detail);
8989
+ if (outcome.reason === "invalid" && outcome.problems) return core.problems(outcome.problems);
8990
+ const unparsedFile = outcome.reason === "not-found" ? notLoaded.get(outcome.id) : void 0;
8991
+ return unparsedFile === void 0 ? messages.batchSkipped[outcome.reason](outcome.id) : core.taskNotLoaded(outcome.id, unparsedFile);
8533
8992
  }
8534
8993
  async function readBody(c, schema, readLanguage) {
8535
8994
  const [body, language] = await Promise.all([readJson(c), readLanguage()]);
@@ -9149,7 +9608,7 @@ async function readUsageCache(root) {
9149
9608
  }
9150
9609
  async function writeUsageCache(root, cache) {
9151
9610
  await mkdir5(root, { recursive: true });
9152
- await writeFileAtomic(join30(root, USAGE_CACHE_FILE), JSON.stringify(cache));
9611
+ await writeRecomputableFileAtomic(join30(root, USAGE_CACHE_FILE), JSON.stringify(cache));
9153
9612
  }
9154
9613
 
9155
9614
  // src/core/usage/transcripts.ts
@@ -9858,11 +10317,11 @@ async function readJsonConfig(path, schema) {
9858
10317
  }
9859
10318
  return schema.safeParse(value).success ? { config: value } : { failed: "invalid" };
9860
10319
  }
9861
- async function writeJsonConfig(path, config) {
10320
+ async function writeJsonConfig({ path, onError }, config) {
9862
10321
  await mkdir10(dirname12(path), { recursive: true });
9863
10322
  const target = await writeTargetOf(path);
9864
10323
  const existing = await statOrNull(target);
9865
- await writeJsonFile(target, config, existing === null ? void 0 : existing.mode & 511);
10324
+ await writeJsonFile(target, config, { mode: existing === null ? void 0 : existing.mode & 511, onErrorAfterPublish: onError });
9866
10325
  }
9867
10326
  async function readConfigText(path) {
9868
10327
  try {
@@ -9910,25 +10369,25 @@ function refreshOurHook(lists, hook, { isOurs, isCurrent }) {
9910
10369
  stale.list[stale.index] = { ...stale.entry, ...hook };
9911
10370
  return "updated";
9912
10371
  }
9913
- async function addStopHookIn(path, schema, slotsOf, hook, ourHook) {
9914
- const read = await readJsonConfig(path, schema);
10372
+ async function addStopHookIn(file, schema, slotsOf, hook, ourHook) {
10373
+ const read = await readJsonConfig(file.path, schema);
9915
10374
  if (!("config" in read)) return read;
9916
10375
  const slots = slotsOf(read.config);
9917
10376
  const refreshed = refreshOurHook(slots.lists, hook, ourHook);
9918
10377
  if (refreshed === "exists") return "exists";
9919
10378
  if (refreshed === "missing") slots.append(hook);
9920
- await writeJsonConfig(path, read.config);
10379
+ await writeJsonConfig(file, read.config);
9921
10380
  return refreshed === "missing" ? "added" : "updated";
9922
10381
  }
9923
- async function removeStopHookIn(path, schema, removeOurs) {
9924
- const read = await readJsonConfig(path, schema);
10382
+ async function removeStopHookIn(file, schema, removeOurs) {
10383
+ const read = await readJsonConfig(file.path, schema);
9925
10384
  if (!("config" in read)) return read;
9926
10385
  if (!removeOurs(read.config)) return "absent";
9927
- await writeJsonConfig(path, read.config);
10386
+ await writeJsonConfig(file, read.config);
9928
10387
  return "removed";
9929
10388
  }
9930
- function addGroupedStopHook(path, hook, ourHook) {
9931
- return addStopHookIn(path, groupedConfigSchema, groupedSlots, hook, ourHook);
10389
+ function addGroupedStopHook(file, hook, ourHook) {
10390
+ return addStopHookIn(file, groupedConfigSchema, groupedSlots, hook, ourHook);
9932
10391
  }
9933
10392
  function groupedSlots(config) {
9934
10393
  config.hooks ??= {};
@@ -9936,8 +10395,8 @@ function groupedSlots(config) {
9936
10395
  const stopGroups = config.hooks.Stop;
9937
10396
  return { lists: stopGroups.flatMap((group) => group.hooks === void 0 ? [] : [group.hooks]), append: (hook) => stopGroups.push({ hooks: [hook] }) };
9938
10397
  }
9939
- function removeGroupedStopHook(path, isOurs) {
9940
- return removeStopHookIn(path, groupedConfigSchema, (config) => {
10398
+ function removeGroupedStopHook(file, isOurs) {
10399
+ return removeStopHookIn(file, groupedConfigSchema, (config) => {
9941
10400
  const hooks = config.hooks;
9942
10401
  if (hooks?.Stop === void 0 || !hooks.Stop.some((group) => hasOurHook(group, isOurs))) return false;
9943
10402
  const kept = hooks.Stop.flatMap((group) => {
@@ -9970,11 +10429,11 @@ function hasCommandOf(commands) {
9970
10429
  }
9971
10430
  var isCurrentClaudeStopHook = hasCommandOf(CURRENT_COMMANDS);
9972
10431
  var isOurClaudeStopHook = hasCommandOf([...CURRENT_COMMANDS, ...RETIRED_COMMANDS]);
9973
- function addClaudeStopHook(settingsPath, platform) {
9974
- return addGroupedStopHook(settingsPath, claudeStopHookFor(platform), { isOurs: isOurClaudeStopHook, isCurrent: isCurrentClaudeStopHook });
10432
+ function addClaudeStopHook(settings, platform) {
10433
+ return addGroupedStopHook(settings, claudeStopHookFor(platform), { isOurs: isOurClaudeStopHook, isCurrent: isCurrentClaudeStopHook });
9975
10434
  }
9976
- function removeClaudeStopHook(settingsPath) {
9977
- return removeGroupedStopHook(settingsPath, isOurClaudeStopHook);
10435
+ function removeClaudeStopHook(settings) {
10436
+ return removeGroupedStopHook(settings, isOurClaudeStopHook);
9978
10437
  }
9979
10438
 
9980
10439
  // src/cli/agents/cursor-hooks.ts
@@ -9984,9 +10443,9 @@ var cursorConfigSchema = z21.object({
9984
10443
  version: z21.number().optional(),
9985
10444
  hooks: z21.object({ stop: z21.array(z21.unknown()).optional() }).passthrough().optional()
9986
10445
  }).passthrough();
9987
- function addCursorStopHook(path, hook, ourHook) {
10446
+ function addCursorStopHook(file, hook, ourHook) {
9988
10447
  return addStopHookIn(
9989
- path,
10448
+ file,
9990
10449
  cursorConfigSchema,
9991
10450
  (config) => {
9992
10451
  config.hooks ??= {};
@@ -9999,8 +10458,8 @@ function addCursorStopHook(path, hook, ourHook) {
9999
10458
  ourHook
10000
10459
  );
10001
10460
  }
10002
- function removeCursorStopHook(path, isOurs) {
10003
- return removeStopHookIn(path, cursorConfigSchema, (config) => {
10461
+ function removeCursorStopHook(file, isOurs) {
10462
+ return removeStopHookIn(file, cursorConfigSchema, (config) => {
10004
10463
  const hooks = config.hooks;
10005
10464
  if (hooks?.stop === void 0 || !hooks.stop.some(isOurs)) return false;
10006
10465
  const kept = hooks.stop.filter((hook) => !isOurs(hook));
@@ -10014,29 +10473,32 @@ function removeCursorStopHook(path, isOurs) {
10014
10473
  var CODEX_HOOK_TIMEOUT_SECONDS = 30;
10015
10474
  var STOP_HOOK_FILES = {
10016
10475
  claude: {
10017
- install: (_agent, path, site) => addClaudeStopHook(path, site.platform),
10018
- remove: (_agent, path) => removeClaudeStopHook(path)
10476
+ install: (_agent, file, site) => addClaudeStopHook(file, site.platform),
10477
+ remove: (_agent, file) => removeClaudeStopHook(file)
10019
10478
  },
10020
10479
  codex: {
10021
- install: (agent, path, site) => {
10480
+ install: (agent, file, site) => {
10022
10481
  const hook = { type: "command", command: posixCommand(agent), commandWindows: windowsCommand(agent, site.cliPath), timeout: CODEX_HOOK_TIMEOUT_SECONDS };
10023
- return addGroupedStopHook(path, hook, ourCurrentHook(agent, hook));
10482
+ return addGroupedStopHook(file, hook, ourCurrentHook(agent, hook));
10024
10483
  },
10025
- remove: (agent, path) => removeGroupedStopHook(path, ourHookOf(agent))
10484
+ remove: (agent, file) => removeGroupedStopHook(file, ourHookOf(agent))
10026
10485
  },
10027
10486
  cursor: {
10028
- install: (agent, path, site) => {
10487
+ install: (agent, file, site) => {
10029
10488
  const hook = { command: site.platform === "win32" ? windowsCommand(agent, site.cliPath) : posixCommand(agent) };
10030
- return addCursorStopHook(path, hook, ourCurrentHook(agent, hook));
10489
+ return addCursorStopHook(file, hook, ourCurrentHook(agent, hook));
10031
10490
  },
10032
- remove: (agent, path) => removeCursorStopHook(path, ourHookOf(agent))
10491
+ remove: (agent, file) => removeCursorStopHook(file, ourHookOf(agent))
10033
10492
  }
10034
10493
  };
10035
10494
  function installAgentHook(agent, site) {
10036
- return STOP_HOOK_FILES[agent].install(agent, AGENT_SPECS[agent].hookConfigPath(site), site);
10495
+ return STOP_HOOK_FILES[agent].install(agent, hookConfigFile(agent, site), site);
10037
10496
  }
10038
10497
  function removeAgentHook(agent, site) {
10039
- return STOP_HOOK_FILES[agent].remove(agent, AGENT_SPECS[agent].hookConfigPath(site));
10498
+ return STOP_HOOK_FILES[agent].remove(agent, hookConfigFile(agent, site));
10499
+ }
10500
+ function hookConfigFile(agent, site) {
10501
+ return { path: AGENT_SPECS[agent].hookConfigPath(site), onError: warnPathErrors(site.warn) };
10040
10502
  }
10041
10503
  function agentStopCommand(agent) {
10042
10504
  return `${HOOK_STOP_COMMAND} --agent ${agent}`;
@@ -10193,7 +10655,7 @@ async function runShow(args, io) {
10193
10655
  const loaded = await loadBacklog(io.backlogRoot);
10194
10656
  const task = findTaskOrWarn(loaded, io, id);
10195
10657
  if (!task) return EXIT.notFound;
10196
- await printTask(io, task, buildIndex(loaded.tasks), { json: values.json });
10658
+ await printTask(io, task, indexOfLoaded(loaded), { json: values.json });
10197
10659
  return EXIT.ok;
10198
10660
  }
10199
10661
  async function printTask(io, task, index, { json }) {
@@ -10208,13 +10670,12 @@ async function printTask(io, task, index, { json }) {
10208
10670
  // src/core/stats/flow/forecast.ts
10209
10671
  var FORECAST_WINDOW_WEEKS = 4;
10210
10672
  var MIN_WINDOW_WEEKS = 1;
10211
- function backlogAgeWeeks(histories, now) {
10212
- const firstCreated = smallest(histories.map((history) => history.createdAt));
10213
- return firstCreated === null ? null : (now.getTime() - firstCreated) / WEEK_MS;
10673
+ function backlogAgeWeeks(backlogSince, now) {
10674
+ return backlogSince === null ? null : (now.getTime() - Date.parse(backlogSince)) / WEEK_MS;
10214
10675
  }
10215
10676
  var clampedWeeks = (weeks) => Math.min(FORECAST_WINDOW_WEEKS, Math.max(MIN_WINDOW_WEEKS, weeks));
10216
- function flowForecast(histories, open2, now) {
10217
- const ageWeeks = backlogAgeWeeks(histories, now);
10677
+ function flowForecast({ histories, head, input: { now } }, open2) {
10678
+ const ageWeeks = backlogAgeWeeks(head.backlogSince, now);
10218
10679
  const windowWeeks = ageWeeks === null ? FORECAST_WINDOW_WEEKS : clampedWeeks(Math.floor(ageWeeks) + 1);
10219
10680
  const observedWeeks = ageWeeks === null ? FORECAST_WINDOW_WEEKS : clampedWeeks(ageWeeks);
10220
10681
  const window = trailingSpan(now.getTime(), windowWeeks * WEEK_MS);
@@ -10273,7 +10734,7 @@ var statsCommand = {
10273
10734
  async function runStats(args, io) {
10274
10735
  const values = parseOptions(io.language, args, { ...SCOPE_OPTIONS, json: { type: "boolean", default: false } });
10275
10736
  const loaded = await loadBacklog(io.backlogRoot);
10276
- const scope = await resolveScope(loaded, io, values);
10737
+ const scope = resolveScope(loaded, io, values);
10277
10738
  if (scope === null) return EXIT.notFound;
10278
10739
  const { project } = scope;
10279
10740
  const journals = await readJournals(io.backlogRoot, scope.activeIds);
@@ -10282,7 +10743,7 @@ async function runStats(args, io) {
10282
10743
  const input = { tasks: loaded.tasks.filter(scoped), journals, now: io.now(), projectId: project?.id, unparsedTasks: unparsedTasks(loaded.errors).filter(scoped) };
10283
10744
  const context = reportContext(input);
10284
10745
  const { totals: totals2 } = statsReport(context);
10285
- const forecast3 = flowForecast(context.histories, totals2.open, io.now());
10746
+ const forecast3 = flowForecast(context, totals2.open);
10286
10747
  const signals = statsSignals(context);
10287
10748
  if (values.json) {
10288
10749
  io.print(formatJson({ totals: totals2, forecast: forecast3, signals, unparsedTasks: context.head.unparsedTasks, invalidJournalLines: context.head.invalidJournalLines, unknownJournalLines: context.head.unknownJournalLines }));
@@ -10329,18 +10790,7 @@ var statusCommand = taskFieldCommand({
10329
10790
  });
10330
10791
 
10331
10792
  // src/cli/commands/take.ts
10332
- import { realpathSync as realpathSync3 } from "node:fs";
10333
10793
  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
10344
10794
  var takeCommand = {
10345
10795
  name: "take",
10346
10796
  usage: (language) => cliMessages(language).takeUsage(),
@@ -10362,13 +10812,14 @@ async function runTake(args, io) {
10362
10812
  if (mode.kind === "path") return takeByPath(loaded, io, mode.path, values.project, { json: values.json });
10363
10813
  const selected = mode.kind === "next" ? await selectNext(loaded, io, values.project) : selectById(loaded, io, mode.id);
10364
10814
  if (!selected.ok) return selected.exitCode;
10365
- const refusal = takeRefusal(io, selected.task, buildIndex(loaded.tasks), { ignoreBlockers: values.force });
10815
+ const index = indexOfLoaded(loaded);
10816
+ const refusal = takeRefusal(io, selected.task, index, { ignoreBlockers: values.force });
10366
10817
  if (refusal) {
10367
10818
  for (const line of refusal.lines) io.warn(line);
10368
10819
  return refusal.code;
10369
10820
  }
10370
- const { code, taken, index } = await takeAll(loaded.tasks, [selected.task], io);
10371
- for (const task of taken) await printTask(io, task, index, { json: values.json });
10821
+ const { code, taken, index: takenIndex } = await takeAll(index, [selected.task], io);
10822
+ for (const task of taken) await printTask(io, task, takenIndex, { json: values.json });
10372
10823
  return code;
10373
10824
  }
10374
10825
  function takeMode(io, values, positionals) {
@@ -10381,11 +10832,11 @@ function takeMode(io, values, positionals) {
10381
10832
  return { kind: "id", id };
10382
10833
  }
10383
10834
  async function takeByPath(loaded, io, path, projectId, { json }) {
10384
- const project = await findProjectOrWarn(loaded, io, projectId);
10835
+ const project = findProjectOrWarn(loaded, io, projectId);
10385
10836
  if (!project) return EXIT.notFound;
10386
- const target = repoRelativePath(io, project, path);
10387
- const index = buildIndex(loaded.tasks);
10388
- const matching = loaded.tasks.filter((task) => task.projectId === project.id && isOpenTaskAt(task, target));
10837
+ const target = repoRelativePath(io, project, loaded, path);
10838
+ const index = indexOfLoaded(loaded);
10839
+ const matching = target === null ? [] : loaded.tasks.filter((task) => task.projectId === project.id && isOpenTaskAt(task, target));
10389
10840
  const refusals = matching.map((task) => takeRefusal(io, task, index, { ignoreBlockers: false }));
10390
10841
  for (const line of refusals.flatMap((refusal) => refusal?.lines ?? [])) io.warn(line);
10391
10842
  const takeable = matching.filter((_, position) => refusals[position] === null);
@@ -10394,7 +10845,7 @@ async function takeByPath(loaded, io, path, projectId, { json }) {
10394
10845
  io.warn(io.cli.noOpenTasksAt(path));
10395
10846
  return EXIT.notFound;
10396
10847
  }
10397
- const { code, taken, index: takenIndex } = await takeAll(loaded.tasks, takeable, io);
10848
+ const { code, taken, index: takenIndex } = await takeAll(index, takeable, io);
10398
10849
  if (json) {
10399
10850
  io.print(formatJson(tasksJson(taken, takenIndex)));
10400
10851
  } else {
@@ -10409,32 +10860,31 @@ function isOpenTaskAt(task, path) {
10409
10860
  const workable = task.type === "task" && !isClosed(task.status) && task.status !== "blocked";
10410
10861
  return workable && task.source !== void 0 && (path === "" || isWithin(sourcePath(task.source), path));
10411
10862
  }
10412
- function repoRelativePath(io, project, path) {
10863
+ function repoRelativePath(io, project, loaded, path) {
10864
+ const typed = sourcePath(path);
10413
10865
  const roots = cwdGitRoots(io);
10414
- if (roots === null || findProjectForRoots([project], roots, repoPlaces(io)) === void 0) return sourcePath(path);
10415
- return relativeInside(roots.worktree, resolve5(realpathSync3(io.cwd), sourcePath(path))) ?? sourcePath(path);
10866
+ if (roots === null || !cwdBelongsTo(project, loaded, io)) return typed;
10867
+ return pathFromProjectRepo(project, roots, repoContext(io), resolve5(realpathOrNull(io.cwd) ?? io.cwd, typed));
10416
10868
  }
10417
- async function takeAll(loadedTasks, chosen, io) {
10418
- const write = taskWriter(io, loadedTasks);
10419
- let tasks = loadedTasks;
10420
- const taken = [];
10869
+ async function takeAll(index, chosen, io) {
10870
+ const write = taskWriter(io, index);
10871
+ const writes = [];
10421
10872
  const code = await applyAll(chosen, async (task) => {
10422
10873
  const written = task.status === "in-progress" ? { ok: true, task } : await write(task, { status: "in-progress" });
10423
10874
  if (!written.ok) return written.exitCode;
10424
- tasks = withWrittenTasks(tasks, [written]);
10425
- taken.push(written.task);
10875
+ writes.push(written);
10426
10876
  return EXIT.ok;
10427
10877
  });
10428
- return { code, taken, index: buildIndex(tasks) };
10878
+ return { code, taken: writes.map((written) => written.task), index: indexWithWritten(index, writes) };
10429
10879
  }
10430
10880
  function selectById(loaded, io, id) {
10431
10881
  const task = findTaskOrWarn(loaded, io, id);
10432
10882
  return task ? { ok: true, task } : { ok: false, exitCode: EXIT.notFound };
10433
10883
  }
10434
10884
  async function selectNext(loaded, io, projectId) {
10435
- const project = await findProjectOrWarn(loaded, io, projectId);
10885
+ const project = findProjectOrWarn(loaded, io, projectId);
10436
10886
  if (!project) return { ok: false, exitCode: EXIT.notFound };
10437
- const index = buildIndex(loaded.tasks);
10887
+ const index = indexOfLoaded(loaded);
10438
10888
  const abandoned = pickAbandonedTask(loaded.tasks, project.id, index, await lastTouched(loaded.tasks.filter(isTakenTask)), io.now());
10439
10889
  if (abandoned) {
10440
10890
  io.warn(io.cli.resumeAbandoned(abandoned.id));
@@ -10480,7 +10930,7 @@ async function runVerify(args, io) {
10480
10930
  if (source === "") throw new UsageError(io.cli.sourceEmpty);
10481
10931
  if (source !== void 0 && positionals.length > 1) throw usageError(verifyCommand, io.language);
10482
10932
  const loaded = await loadBacklog(io.backlogRoot);
10483
- const verification = { loaded, source, write: taskWriter(io, loaded.tasks), io };
10933
+ const verification = { loaded, source, write: taskWriter(io, indexOfLoaded(loaded)), io };
10484
10934
  return applyAll(new Set(positionals), (id) => verifyOne(id, verification));
10485
10935
  }
10486
10936
  async function verifyOne(id, { loaded, source, write, io }) {
@@ -10493,7 +10943,7 @@ async function verifyOne(id, { loaded, source, write, io }) {
10493
10943
  const project = projectOf(loaded, task);
10494
10944
  const lookup = repoLookup(io);
10495
10945
  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;
10946
+ if (source !== void 0 && repo !== void 0 && (await sourcePresenceOrWarn(io, repo, source)).kind === "missing") return EXIT.invalid;
10497
10947
  const target = source ?? await relocatedSource(repo, task);
10498
10948
  const anchored = target ?? task.source;
10499
10949
  const anchor = anchored === void 0 ? void 0 : anchorChange(await sourceAnchor(repo, anchored, lookup.onUnreadable));
@@ -10535,7 +10985,8 @@ var CLI_COMMANDS = [
10535
10985
  serveCommand,
10536
10986
  serviceCommand
10537
10987
  ];
10538
- var HELP_ARGUMENTS = /* @__PURE__ */ new Set(["help", "--help", "-h"]);
10988
+ var HELP_COMMAND = "help";
10989
+ var RUN_WITHOUT_COMMAND = "help";
10539
10990
  var COMMANDS = new Map(CLI_COMMANDS.map((command2) => [command2.name, command2]));
10540
10991
  async function runCli(argv2, env) {
10541
10992
  const [name, ...args] = argv2;
@@ -10545,7 +10996,7 @@ async function runCli(argv2, env) {
10545
10996
  if (language === null) return failureExit;
10546
10997
  const io = cliIo(env, language);
10547
10998
  if (!command2) {
10548
- const askedForHelp = name === void 0 || HELP_ARGUMENTS.has(name);
10999
+ const askedForHelp = name === void 0 || name === HELP_COMMAND || asksForHelp([name], {});
10549
11000
  if (!askedForHelp) {
10550
11001
  io.warn(usageText(CLI_COMMANDS, language));
10551
11002
  return EXIT.invalid;
@@ -10576,7 +11027,7 @@ ${usageText([command2], language)}`);
10576
11027
  }
10577
11028
  function commandName(argv2) {
10578
11029
  const [name, ...args] = argv2;
10579
- if (name === void 0 || !COMMANDS.has(name)) return "help";
11030
+ if (name === void 0 || !COMMANDS.has(name)) return RUN_WITHOUT_COMMAND;
10580
11031
  return name === hookCommand.name && namesStopEvent(args) ? HOOK_STOP_COMMAND : name;
10581
11032
  }
10582
11033