p-backlog 0.10.1 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/CHANGELOG.md +40 -0
  2. package/README.md +1 -1
  3. package/README.ru.md +1 -1
  4. package/dist/cli.js +563 -376
  5. package/dist/web/assets/CodeTab-DvhAb0kx.js +1 -0
  6. package/dist/web/assets/CostTab-DHmrPaIY.js +1 -0
  7. package/dist/web/assets/EffectTab-C-W3n29N.js +1 -0
  8. package/dist/web/assets/Figure-CRSlcZF-.css +1 -0
  9. package/dist/web/assets/Figure-DUapj1C7.js +1 -0
  10. package/dist/web/assets/OverviewTab-B-6PIEfD.js +1 -0
  11. package/dist/web/assets/Page-U8D0vJva.js +59 -0
  12. package/dist/web/assets/QualityTab-B9ahq43v.js +1 -0
  13. package/dist/web/assets/ShareBar-B-seexQa.js +1 -0
  14. package/dist/web/assets/{StatsPage-Bmr75f8J.js → StatsPage-DBqHQi5S.js} +1 -1
  15. package/dist/web/assets/StatsTabState-DZ3lMjjx.css +1 -0
  16. package/dist/web/assets/StatsTabState-DlqTtrvX.js +1 -0
  17. package/dist/web/assets/{StatsTable-D-PylWl7.js → StatsTable-ClPy3aOI.js} +1 -1
  18. package/dist/web/assets/UnavailableRepos-8SE6XJSM.js +1 -0
  19. package/dist/web/assets/index-wzgTQj7a.js +2 -0
  20. package/dist/web/assets/start-BR6m00jS.js +38 -0
  21. package/dist/web/assets/start-DPlw6J9o.css +1 -0
  22. package/dist/web/assets/use-grain-panel-DpW0vjfB.js +55 -0
  23. package/dist/web/assets/{web-paths--TbmQ8rA.js → web-paths-X1IR2jNR.js} +1 -1
  24. package/dist/web/index.html +1 -1
  25. package/package.json +1 -1
  26. package/skill/backlog/SKILL.md +8 -1
  27. package/skill/backlog-en/SKILL.md +9 -1
  28. package/dist/web/assets/CodeTab-ClCaW8AS.js +0 -1
  29. package/dist/web/assets/CostTab-CtI3iFiW.js +0 -1
  30. package/dist/web/assets/EffectTab-DcvyEB2U.js +0 -1
  31. package/dist/web/assets/Figure-DkmKAO9C.css +0 -1
  32. package/dist/web/assets/Figure-DxKUx52i.js +0 -1
  33. package/dist/web/assets/OverviewTab-DE_6Z9ps.js +0 -1
  34. package/dist/web/assets/Page-buthlp0V.js +0 -59
  35. package/dist/web/assets/QualityTab-CkoKu4X0.js +0 -1
  36. package/dist/web/assets/ShareBar-BAS4lpze.js +0 -1
  37. package/dist/web/assets/StatsTabState-BacJCCdC.css +0 -1
  38. package/dist/web/assets/StatsTabState-D93FkgT5.js +0 -1
  39. package/dist/web/assets/UnavailableRepos-DyBVFVrQ.js +0 -1
  40. package/dist/web/assets/index-BFmeY_kk.js +0 -2
  41. package/dist/web/assets/start-CJ8zVmAB.js +0 -38
  42. package/dist/web/assets/start-CjkFx30s.css +0 -1
  43. package/dist/web/assets/summaries-D57lRSim.js +0 -1
  44. package/dist/web/assets/use-grain-panel-UcuXHAhT.js +0 -55
package/dist/cli.js CHANGED
@@ -30,7 +30,8 @@ function formatLocalIso(date) {
30
30
 
31
31
  // src/core/numbers.ts
32
32
  var PERCENT = 100;
33
- var BYTES_PER_MEBIBYTE = 1024 * 1024;
33
+ var BYTES_PER_KIBIBYTE = 1024;
34
+ var BYTES_PER_MEBIBYTE = 1024 * BYTES_PER_KIBIBYTE;
34
35
  function roundToTenth(value) {
35
36
  return Math.round(value * 10) / 10;
36
37
  }
@@ -59,7 +60,7 @@ function smallest(values) {
59
60
  // src/core/api/memory.ts
60
61
  var MEMORY_SAMPLE_INTERVAL_MS = 5e3;
61
62
  var MEMORY_HISTORY_MS = HOUR_MS;
62
- function megabytesOf(bytes) {
63
+ function mebibytesOf(bytes) {
63
64
  return roundToTenth(bytes / BYTES_PER_MEBIBYTE);
64
65
  }
65
66
 
@@ -67,6 +68,18 @@ function megabytesOf(bytes) {
67
68
  function errorText(error) {
68
69
  return error instanceof Error ? error.message : String(error);
69
70
  }
71
+ function oncePerKey(keyOf, report) {
72
+ const reported = /* @__PURE__ */ new Set();
73
+ return (...args) => {
74
+ const key = keyOf(...args);
75
+ if (reported.has(key)) return;
76
+ reported.add(key);
77
+ report(...args);
78
+ };
79
+ }
80
+ function oncePerPath(onError) {
81
+ return oncePerKey((path) => path, onError);
82
+ }
70
83
  function warnPathErrors(warn2, describe = (path, detail) => `${path}: ${detail}`) {
71
84
  return (path, error) => warn2(describe(path, errorText(error)));
72
85
  }
@@ -102,13 +115,13 @@ import { z } from "zod";
102
115
 
103
116
  // src/core/store/file-lock.ts
104
117
  import { randomUUID as randomUUID2 } from "node:crypto";
105
- import { rm as rm2, stat as stat2, writeFile as writeFile2 } from "node:fs/promises";
118
+ import { rm as rm2, writeFile as writeFile2 } from "node:fs/promises";
106
119
  import { basename as basename2, dirname as dirname2, join as join2 } from "node:path";
107
120
  import { setTimeout as sleep2 } from "node:timers/promises";
108
121
 
109
122
  // src/core/store/fs-utils.ts
110
123
  import { createHash, randomUUID } from "node:crypto";
111
- import { realpathSync } from "node:fs";
124
+ import { readFileSync, realpathSync } from "node:fs";
112
125
  import { access, appendFile, chmod, link, lstat, open, readdir, readFile, readlink, rename, rm, stat, writeFile } from "node:fs/promises";
113
126
  import { basename, dirname, join } from "node:path";
114
127
  import { setTimeout as sleep } from "node:timers/promises";
@@ -127,17 +140,17 @@ async function readTextIfFile(path) {
127
140
  throw error;
128
141
  }
129
142
  }
130
- async function readReportingFailure(path, read, onError) {
143
+ async function attemptReportingFailure(path, attempt, onError) {
131
144
  try {
132
- return await read(path);
145
+ return await attempt(path);
133
146
  } catch (error) {
134
147
  onError(path, error);
135
148
  return null;
136
149
  }
137
150
  }
138
- function readReportingFailureSync(path, read, onError) {
151
+ function attemptReportingFailureSync(path, attempt, onError) {
139
152
  try {
140
- return read(path);
153
+ return attempt(path);
141
154
  } catch (error) {
142
155
  onError(path, error);
143
156
  return null;
@@ -168,14 +181,20 @@ function lstatOrNull(path) {
168
181
  function linkTargetOrNull(path) {
169
182
  return nullWhenMissing(readlink(path), NO_LINK_CODES);
170
183
  }
171
- function realpathOrNull(path) {
184
+ function nullWhenMissingSync(read) {
172
185
  try {
173
- return realpathSync.native(path);
186
+ return read();
174
187
  } catch (error) {
175
188
  if (isNoFile(error)) return null;
176
189
  throw error;
177
190
  }
178
191
  }
192
+ function realpathOrNull(path) {
193
+ return nullWhenMissingSync(() => realpathSync.native(path));
194
+ }
195
+ function readBytesOrNullSync(path) {
196
+ return nullWhenMissingSync(() => readFileSync(path));
197
+ }
179
198
  function hasAnyErrorCode(error, codes) {
180
199
  return codes.some((code) => hasErrorCode(error, code));
181
200
  }
@@ -239,17 +258,22 @@ function parseJson(text, schema) {
239
258
  try {
240
259
  const parsed = schema.safeParse(JSON.parse(text));
241
260
  return parsed.success ? parsed.data : null;
242
- } catch {
243
- return null;
261
+ } catch (error) {
262
+ if (error instanceof SyntaxError) return null;
263
+ throw error;
244
264
  }
245
265
  }
246
266
  async function readJsonFile(path, schema) {
247
267
  const text = await readTextOrNull(path);
248
268
  return text === null ? null : parseJson(text, schema);
249
269
  }
270
+ var JSON_INDENT = 2;
271
+ function jsonFileText(value) {
272
+ return `${JSON.stringify(value, null, JSON_INDENT)}
273
+ `;
274
+ }
250
275
  async function writeJsonFile(path, value) {
251
- await writeFileAtomic(path, `${JSON.stringify(value, null, 2)}
252
- `);
276
+ await writeFileAtomic(path, jsonFileText(value));
253
277
  }
254
278
  async function removeIfUnchanged(path, version) {
255
279
  const text = await readTextOrNull(path);
@@ -391,12 +415,9 @@ async function tryCreate(lock, token) {
391
415
  }
392
416
  async function abandonedToken(lock) {
393
417
  const token = await readTextOrNull(lock);
394
- try {
395
- return token !== null && Date.now() - (await stat2(lock)).mtimeMs > ABANDONED_AFTER_MS ? token : null;
396
- } catch (error) {
397
- if (hasErrorCode(error, "ENOENT")) return null;
398
- throw error;
399
- }
418
+ if (token === null) return null;
419
+ const info = await statOrNull(lock);
420
+ return info !== null && Date.now() - info.mtimeMs > ABANDONED_AFTER_MS ? token : null;
400
421
  }
401
422
  async function breakAbandoned(lock, abandoned) {
402
423
  const breaker = `${lock}.break`;
@@ -769,10 +790,11 @@ async function settleLanguage(root, env) {
769
790
  const saveFailure = source === "unset" ? await saveLanguageOrFailure(root, language) : null;
770
791
  return { language, invalidSettingsFile: source === "invalid-settings", saveFailure };
771
792
  }
772
- async function readLanguageOrLocale(root, env) {
793
+ async function readLanguageOrLocale(root, env, onUnreadable) {
773
794
  try {
774
795
  return (await decideLanguage(root, env)).language;
775
- } catch {
796
+ } catch (error) {
797
+ onUnreadable(error);
776
798
  return localeLanguage(env);
777
799
  }
778
800
  }
@@ -920,6 +942,23 @@ function forecastSpan(windowDays) {
920
942
  return windowDays % DAYS_PER_WEEK === 0 ? { unit: "week", count: windowDays / DAYS_PER_WEEK } : { unit: "day", count: windowDays };
921
943
  }
922
944
 
945
+ // src/core/messages/labels.ts
946
+ function labelLookups(labels) {
947
+ return {
948
+ categoryLabel: (category) => category === void 0 ? labels.noCategory : labels.category[category],
949
+ categoryRowLabel: (category) => labels.categoryRow[category],
950
+ foundRowLabel: (found) => labels.found[found],
951
+ statusLabel: (status) => labels.status[status],
952
+ priorityLabel: (priority) => labels.priority[priority],
953
+ typeLabel: (type) => labels.type[type],
954
+ resolutionLabel: (resolution) => labels.resolution[resolution],
955
+ evidenceLabel: (evidence2) => labels.evidence[evidence2],
956
+ checkMethodLabel: (method) => labels.checkMethod[method],
957
+ duplicateMatchLabel: (match) => labels.duplicateMatch[match],
958
+ graphStateLabel: (state) => labels.graphState[state]
959
+ };
960
+ }
961
+
923
962
  // src/core/messages/problem-list.ts
924
963
  function problemList(problem3) {
925
964
  return (list) => [...new Set(list.map(problem3))].join("; ");
@@ -963,28 +1002,32 @@ var CATEGORY_LABELS = {
963
1002
  bug: "Bug"
964
1003
  };
965
1004
  var NO_CATEGORY_LABEL = "not set";
966
- var CATEGORY_ROW_LABELS = { ...CATEGORY_LABELS, unset: NO_CATEGORY_LABEL, unknown: "unknown" };
967
- var FOUND_ROW_LABELS = { review: "in review", incidental: "incidentally", manual: "manually", unknown: "unknown", unset: "not recorded" };
968
- var STATUS_LABELS = {
969
- backlog: "backlog",
970
- "in-progress": "in progress",
971
- blocked: "blocked",
972
- done: "done",
973
- cancelled: "cancelled"
974
- };
975
- var TYPE_LABELS = { task: "task", epic: "epic" };
976
- var PRIORITY_LABELS = { low: "low", medium: "medium", high: "high", critical: "critical" };
977
- var RESOLUTION_LABELS = { fixed: "fixed", obsolete: "code gone", duplicate: "duplicate", "epic-done": "epic done" };
978
- var EVIDENCE_LABELS = {
979
- "source-changed": "code changed",
980
- "source-missing": "file missing",
981
- duplicate: "duplicate",
982
- "no-source": "no source",
983
- total: "Total"
1005
+ var LABELS = {
1006
+ category: CATEGORY_LABELS,
1007
+ noCategory: NO_CATEGORY_LABEL,
1008
+ categoryRow: { ...CATEGORY_LABELS, unset: NO_CATEGORY_LABEL, unknown: "unknown" },
1009
+ found: { review: "in review", incidental: "incidentally", manual: "manually", unknown: "unknown", unset: "not recorded" },
1010
+ status: {
1011
+ backlog: "backlog",
1012
+ "in-progress": "in progress",
1013
+ blocked: "blocked",
1014
+ done: "done",
1015
+ cancelled: "cancelled"
1016
+ },
1017
+ type: { task: "task", epic: "epic" },
1018
+ priority: { low: "low", medium: "medium", high: "high", critical: "critical" },
1019
+ resolution: { fixed: "fixed", obsolete: "code gone", duplicate: "duplicate", "epic-done": "epic done" },
1020
+ evidence: {
1021
+ "source-changed": "code changed",
1022
+ "source-missing": "file missing",
1023
+ duplicate: "duplicate",
1024
+ "no-source": "no source",
1025
+ total: "Total"
1026
+ },
1027
+ checkMethod: { symbol: "by symbol", anchor: "by source lines", file: "by file" },
1028
+ duplicateMatch: { source: "by code location", title: "by title", symbol: "by symbol" },
1029
+ graphState: { none: "none", unreadable: "unreadable", stale: "stale", fresh: "fresh" }
984
1030
  };
985
- var CHECK_METHOD_LABELS = { symbol: "by symbol", anchor: "by source lines", file: "by file" };
986
- var DUPLICATE_MATCH_LABELS = { source: "by code location", title: "by title", symbol: "by symbol" };
987
- var GRAPH_STATE_LABELS = { none: "none", unreadable: "unreadable", stale: "stale", fresh: "fresh" };
988
1031
  var COUNT_FORMS = {
989
1032
  task: ["task", "tasks"],
990
1033
  line: ["line", "lines"],
@@ -1031,9 +1074,11 @@ function signal(s) {
1031
1074
  return `Urgent tasks have been waiting more than ${count(s.params.days, "day")}: ${s.params.count}`;
1032
1075
  case "stuck":
1033
1076
  return `Stuck in progress: ${s.params.count}, longest ${s.params.id} \u2014 ${days(s.params.days)}`;
1077
+ case "done-unclosed":
1078
+ return `Checklist done but the task is not closed: ${s.params.count}, longest ${s.params.id} \u2014 close it (backlog close) or add what is left`;
1034
1079
  case "noisy-check": {
1035
1080
  const { evidence: evidence2, method, percent: percent2, decided, windowDays } = s.params;
1036
- const name = method === null ? `"${EVIDENCE_LABELS[evidence2]}"` : `"${EVIDENCE_LABELS[evidence2]}" ${CHECK_METHOD_LABELS[method]}`;
1081
+ const name = method === null ? `"${LABELS.evidence[evidence2]}"` : `"${LABELS.evidence[evidence2]}" ${LABELS.checkMethod[method]}`;
1037
1082
  return `Check ${name} is almost always wrong: precision ${percent2}% on ${decided} decided over ${count(windowDays, "day")}`;
1038
1083
  }
1039
1084
  case "low-changed":
@@ -1156,17 +1201,7 @@ var coreEn = {
1156
1201
  problem,
1157
1202
  problems,
1158
1203
  schemaIssue: schemaIssue2,
1159
- categoryLabel: (category) => category === void 0 ? NO_CATEGORY_LABEL : CATEGORY_LABELS[category],
1160
- categoryRowLabel: (category) => CATEGORY_ROW_LABELS[category],
1161
- foundRowLabel: (found) => FOUND_ROW_LABELS[found],
1162
- statusLabel: (status) => STATUS_LABELS[status],
1163
- priorityLabel: (priority) => PRIORITY_LABELS[priority],
1164
- typeLabel: (type) => TYPE_LABELS[type],
1165
- resolutionLabel: (resolution) => RESOLUTION_LABELS[resolution],
1166
- evidenceLabel: (evidence2) => EVIDENCE_LABELS[evidence2],
1167
- checkMethodLabel: (method) => CHECK_METHOD_LABELS[method],
1168
- duplicateMatchLabel: (match) => DUPLICATE_MATCH_LABELS[match],
1169
- graphStateLabel: (state) => GRAPH_STATE_LABELS[state],
1204
+ ...labelLookups(LABELS),
1170
1205
  count,
1171
1206
  days,
1172
1207
  p90,
@@ -1174,7 +1209,7 @@ var coreEn = {
1174
1209
  forecastTail,
1175
1210
  signal,
1176
1211
  epicDoneReason,
1177
- fileBusy: ({ path, lock, seconds }) => `${path} has been locked by another process for more than ${seconds} s (${lock})`,
1212
+ fileBusy: ({ path, lock, seconds }) => `${path} has been locked by another process for more than ${formatNumber("en", seconds)}${NBSP}s (${lock})`,
1178
1213
  checkFix,
1179
1214
  checkProblem,
1180
1215
  runsNotTrimmed: (error) => `Could not trim the run log: ${error}`,
@@ -1204,28 +1239,32 @@ var CATEGORY_LABELS2 = {
1204
1239
  bug: "\u041E\u0448\u0438\u0431\u043A\u0430"
1205
1240
  };
1206
1241
  var NO_CATEGORY_LABEL2 = "\u043D\u0435 \u0443\u043A\u0430\u0437\u0430\u043D\u0430";
1207
- var CATEGORY_ROW_LABELS2 = { ...CATEGORY_LABELS2, unset: NO_CATEGORY_LABEL2, unknown: "\u043D\u0435\u0438\u0437\u0432\u0435\u0441\u0442\u043D\u0430" };
1208
- var FOUND_ROW_LABELS2 = { review: "\u043D\u0430 \u0440\u0435\u0432\u044C\u044E", incidental: "\u043F\u043E\u043F\u0443\u0442\u043D\u043E", manual: "\u0432\u0440\u0443\u0447\u043D\u0443\u044E", unknown: "\u043D\u0435\u0438\u0437\u0432\u0435\u0441\u0442\u043D\u043E", unset: "\u043D\u0435 \u0437\u0430\u043F\u0438\u0441\u0430\u043D\u043E" };
1209
- var STATUS_LABELS2 = {
1210
- backlog: "\u0432 \u0431\u0435\u043A\u043B\u043E\u0433\u0435",
1211
- "in-progress": "\u0432 \u0440\u0430\u0431\u043E\u0442\u0435",
1212
- blocked: "\u0437\u0430\u0431\u043B\u043E\u043A\u0438\u0440\u043E\u0432\u0430\u043D\u0430",
1213
- done: "\u0441\u0434\u0435\u043B\u0430\u043D\u0430",
1214
- cancelled: "\u043E\u0442\u043C\u0435\u043D\u0435\u043D\u0430"
1215
- };
1216
- var TYPE_LABELS2 = { task: "\u0437\u0430\u0434\u0430\u0447\u0430", epic: "\u044D\u043F\u0438\u043A" };
1217
- var PRIORITY_LABELS2 = { low: "\u043D\u0438\u0437\u043A\u0438\u0439", medium: "\u0441\u0440\u0435\u0434\u043D\u0438\u0439", high: "\u0432\u044B\u0441\u043E\u043A\u0438\u0439", critical: "\u043A\u0440\u0438\u0442\u0438\u0447\u043D\u044B\u0439" };
1218
- var RESOLUTION_LABELS2 = { fixed: "\u0438\u0441\u043F\u0440\u0430\u0432\u043B\u0435\u043D\u043E", obsolete: "\u043A\u043E\u0434\u0430 \u043D\u0435\u0442", duplicate: "\u0434\u0443\u0431\u043B\u044C", "epic-done": "\u044D\u043F\u0438\u043A \u0437\u0430\u0432\u0435\u0440\u0448\u0451\u043D" };
1219
- var EVIDENCE_LABELS2 = {
1220
- "source-changed": "\u043A\u043E\u0434 \u0438\u0437\u043C\u0435\u043D\u0438\u043B\u0441\u044F",
1221
- "source-missing": "\u0444\u0430\u0439\u043B \u043F\u0440\u043E\u043F\u0430\u043B",
1222
- duplicate: "\u0434\u0443\u0431\u043B\u044C",
1223
- "no-source": "\u043D\u0435\u0442 source",
1224
- total: "\u0412\u0441\u0435\u0433\u043E"
1242
+ var LABELS2 = {
1243
+ category: CATEGORY_LABELS2,
1244
+ noCategory: NO_CATEGORY_LABEL2,
1245
+ categoryRow: { ...CATEGORY_LABELS2, unset: NO_CATEGORY_LABEL2, unknown: "\u043D\u0435\u0438\u0437\u0432\u0435\u0441\u0442\u043D\u0430" },
1246
+ found: { review: "\u043D\u0430 \u0440\u0435\u0432\u044C\u044E", incidental: "\u043F\u043E\u043F\u0443\u0442\u043D\u043E", manual: "\u0432\u0440\u0443\u0447\u043D\u0443\u044E", unknown: "\u043D\u0435\u0438\u0437\u0432\u0435\u0441\u0442\u043D\u043E", unset: "\u043D\u0435 \u0437\u0430\u043F\u0438\u0441\u0430\u043D\u043E" },
1247
+ status: {
1248
+ backlog: "\u0432 \u0431\u0435\u043A\u043B\u043E\u0433\u0435",
1249
+ "in-progress": "\u0432 \u0440\u0430\u0431\u043E\u0442\u0435",
1250
+ blocked: "\u0437\u0430\u0431\u043B\u043E\u043A\u0438\u0440\u043E\u0432\u0430\u043D\u0430",
1251
+ done: "\u0441\u0434\u0435\u043B\u0430\u043D\u0430",
1252
+ cancelled: "\u043E\u0442\u043C\u0435\u043D\u0435\u043D\u0430"
1253
+ },
1254
+ type: { task: "\u0437\u0430\u0434\u0430\u0447\u0430", epic: "\u044D\u043F\u0438\u043A" },
1255
+ priority: { low: "\u043D\u0438\u0437\u043A\u0438\u0439", medium: "\u0441\u0440\u0435\u0434\u043D\u0438\u0439", high: "\u0432\u044B\u0441\u043E\u043A\u0438\u0439", critical: "\u043A\u0440\u0438\u0442\u0438\u0447\u043D\u044B\u0439" },
1256
+ resolution: { fixed: "\u0438\u0441\u043F\u0440\u0430\u0432\u043B\u0435\u043D\u043E", obsolete: "\u043A\u043E\u0434\u0430 \u043D\u0435\u0442", duplicate: "\u0434\u0443\u0431\u043B\u044C", "epic-done": "\u044D\u043F\u0438\u043A \u0437\u0430\u0432\u0435\u0440\u0448\u0451\u043D" },
1257
+ evidence: {
1258
+ "source-changed": "\u043A\u043E\u0434 \u0438\u0437\u043C\u0435\u043D\u0438\u043B\u0441\u044F",
1259
+ "source-missing": "\u0444\u0430\u0439\u043B \u043F\u0440\u043E\u043F\u0430\u043B",
1260
+ duplicate: "\u0434\u0443\u0431\u043B\u044C",
1261
+ "no-source": "\u043D\u0435\u0442 source",
1262
+ total: "\u0412\u0441\u0435\u0433\u043E"
1263
+ },
1264
+ checkMethod: { symbol: "\u043F\u043E \u0441\u0438\u043C\u0432\u043E\u043B\u0443", anchor: "\u043F\u043E \u0441\u0442\u0440\u043E\u043A\u0430\u043C source", file: "\u043F\u043E \u0444\u0430\u0439\u043B\u0443" },
1265
+ duplicateMatch: { source: "\u043F\u043E \u043C\u0435\u0441\u0442\u0443 \u0432 \u043A\u043E\u0434\u0435", title: "\u043F\u043E \u0437\u0430\u0433\u043E\u043B\u043E\u0432\u043A\u0443", symbol: "\u043F\u043E \u0441\u0438\u043C\u0432\u043E\u043B\u0443" },
1266
+ graphState: { none: "\u043D\u0435\u0442", unreadable: "\u043D\u0435 \u0447\u0438\u0442\u0430\u0435\u0442\u0441\u044F", stale: "\u0443\u0441\u0442\u0430\u0440\u0435\u043B", fresh: "\u0441\u0432\u0435\u0436\u0438\u0439" }
1225
1267
  };
1226
- var CHECK_METHOD_LABELS2 = { symbol: "\u043F\u043E \u0441\u0438\u043C\u0432\u043E\u043B\u0443", anchor: "\u043F\u043E \u0441\u0442\u0440\u043E\u043A\u0430\u043C source", file: "\u043F\u043E \u0444\u0430\u0439\u043B\u0443" };
1227
- var DUPLICATE_MATCH_LABELS2 = { source: "\u043F\u043E \u043C\u0435\u0441\u0442\u0443 \u0432 \u043A\u043E\u0434\u0435", title: "\u043F\u043E \u0437\u0430\u0433\u043E\u043B\u043E\u0432\u043A\u0443", symbol: "\u043F\u043E \u0441\u0438\u043C\u0432\u043E\u043B\u0443" };
1228
- var GRAPH_STATE_LABELS2 = { none: "\u043D\u0435\u0442", unreadable: "\u043D\u0435 \u0447\u0438\u0442\u0430\u0435\u0442\u0441\u044F", stale: "\u0443\u0441\u0442\u0430\u0440\u0435\u043B", fresh: "\u0441\u0432\u0435\u0436\u0438\u0439" };
1229
1268
  var COUNT_FORMS2 = {
1230
1269
  task: ["\u0437\u0430\u0434\u0430\u0447\u0430", "\u0437\u0430\u0434\u0430\u0447\u0438", "\u0437\u0430\u0434\u0430\u0447"],
1231
1270
  line: ["\u0441\u0442\u0440\u043E\u043A\u0430", "\u0441\u0442\u0440\u043E\u043A\u0438", "\u0441\u0442\u0440\u043E\u043A"],
@@ -1280,9 +1319,11 @@ function signal2(s) {
1280
1319
  return `\u0421\u0440\u043E\u0447\u043D\u044B\u0435 \u0437\u0430\u0434\u0430\u0447\u0438 \u0436\u0434\u0443\u0442 \u0434\u043E\u043B\u044C\u0448\u0435 ${genitive(s.params.days, "day")}: ${s.params.count}`;
1281
1320
  case "stuck":
1282
1321
  return `\u0417\u0430\u0441\u0442\u0440\u044F\u043B\u0438 \u0432 \u0440\u0430\u0431\u043E\u0442\u0435: ${s.params.count}, \u0434\u043E\u043B\u044C\u0448\u0435 \u0432\u0441\u0435\u0445 ${s.params.id} \u2014 ${days2(s.params.days)}`;
1322
+ case "done-unclosed":
1323
+ return `\u0427\u0435\u043A\u043B\u0438\u0441\u0442 \u0432\u044B\u043F\u043E\u043B\u043D\u0435\u043D, \u0430 \u0437\u0430\u0434\u0430\u0447\u0430 \u043D\u0435 \u0437\u0430\u043A\u0440\u044B\u0442\u0430: ${s.params.count}, \u0434\u043E\u043B\u044C\u0448\u0435 \u0432\u0441\u0435\u0445 ${s.params.id} \u2014 \u0437\u0430\u043A\u0440\u043E\u0439\u0442\u0435 (backlog close) \u0438\u043B\u0438 \u0434\u043E\u043F\u0438\u0448\u0438\u0442\u0435, \u0447\u0442\u043E \u043E\u0441\u0442\u0430\u043B\u043E\u0441\u044C`;
1283
1324
  case "noisy-check": {
1284
1325
  const { evidence: evidence2, method, percent: percent2, decided, windowDays } = s.params;
1285
- const name = method === null ? `\xAB${EVIDENCE_LABELS2[evidence2]}\xBB` : `\xAB${EVIDENCE_LABELS2[evidence2]}\xBB ${CHECK_METHOD_LABELS2[method]}`;
1326
+ const name = method === null ? `\xAB${LABELS2.evidence[evidence2]}\xBB` : `\xAB${LABELS2.evidence[evidence2]}\xBB ${LABELS2.checkMethod[method]}`;
1286
1327
  return `\u041F\u0440\u043E\u0432\u0435\u0440\u043A\u0430 ${name} \u043F\u043E\u0447\u0442\u0438 \u0432\u0441\u0435\u0433\u0434\u0430 \u043E\u0448\u0438\u0431\u0430\u0435\u0442\u0441\u044F: \u0442\u043E\u0447\u043D\u043E\u0441\u0442\u044C ${percent2}% \u043D\u0430 ${decided} \u0440\u0435\u0448\u0451\u043D\u043D\u044B\u0445 \u0437\u0430 ${span(windowDays, "day")}`;
1287
1328
  }
1288
1329
  case "low-changed":
@@ -1405,17 +1446,7 @@ var coreRu = {
1405
1446
  problem: problem2,
1406
1447
  problems: problems2,
1407
1448
  schemaIssue: schemaIssue3,
1408
- categoryLabel: (category) => category === void 0 ? NO_CATEGORY_LABEL2 : CATEGORY_LABELS2[category],
1409
- categoryRowLabel: (category) => CATEGORY_ROW_LABELS2[category],
1410
- foundRowLabel: (found) => FOUND_ROW_LABELS2[found],
1411
- statusLabel: (status) => STATUS_LABELS2[status],
1412
- priorityLabel: (priority) => PRIORITY_LABELS2[priority],
1413
- typeLabel: (type) => TYPE_LABELS2[type],
1414
- resolutionLabel: (resolution) => RESOLUTION_LABELS2[resolution],
1415
- evidenceLabel: (evidence2) => EVIDENCE_LABELS2[evidence2],
1416
- checkMethodLabel: (method) => CHECK_METHOD_LABELS2[method],
1417
- duplicateMatchLabel: (match) => DUPLICATE_MATCH_LABELS2[match],
1418
- graphStateLabel: (state) => GRAPH_STATE_LABELS2[state],
1449
+ ...labelLookups(LABELS2),
1419
1450
  count: count2,
1420
1451
  days: days2,
1421
1452
  p90: p902,
@@ -1423,7 +1454,7 @@ var coreRu = {
1423
1454
  forecastTail: forecastTail2,
1424
1455
  signal: signal2,
1425
1456
  epicDoneReason: epicDoneReason2,
1426
- fileBusy: ({ path, lock, seconds }) => `${path} \u0437\u0430\u043D\u044F\u0442 \u0434\u0440\u0443\u0433\u0438\u043C \u043F\u0440\u043E\u0446\u0435\u0441\u0441\u043E\u043C \u0434\u043E\u043B\u044C\u0448\u0435 ${seconds} \u0441 (${lock})`,
1457
+ fileBusy: ({ path, lock, seconds }) => `${path} \u0437\u0430\u043D\u044F\u0442 \u0434\u0440\u0443\u0433\u0438\u043C \u043F\u0440\u043E\u0446\u0435\u0441\u0441\u043E\u043C \u0434\u043E\u043B\u044C\u0448\u0435 ${formatNumber("ru", seconds)}${NBSP}\u0441 (${lock})`,
1427
1458
  checkFix: checkFix2,
1428
1459
  checkProblem: checkProblem2,
1429
1460
  runsNotTrimmed: (error) => `\u041D\u0435 \u0443\u0434\u0430\u043B\u043E\u0441\u044C \u043E\u0431\u0440\u0435\u0437\u0430\u0442\u044C \u0436\u0443\u0440\u043D\u0430\u043B \u0437\u0430\u043F\u0443\u0441\u043A\u043E\u0432: ${error}`,
@@ -1476,6 +1507,12 @@ function countBy(items, keyOf, amountOf = () => 1) {
1476
1507
  return totals2;
1477
1508
  }
1478
1509
 
1510
+ // src/core/journal/creation.ts
1511
+ function taskCreation(record, created) {
1512
+ if (record !== void 0) return { createdAt: Date.parse(record.created), type: record.type };
1513
+ return created === void 0 ? void 0 : { createdAt: Date.parse(created.at), type: created.type };
1514
+ }
1515
+
1479
1516
  // src/core/model/checklist.ts
1480
1517
  var ITEM = /^\s*[-*+]\s+\[(?<mark>[ xX])\]\s+(?<text>.*)$/;
1481
1518
  var FENCE = /^\s{0,3}(?<fence>`{3,}|~{3,})/;
@@ -1928,17 +1965,14 @@ function reportStartEvents(events, keepsHistory) {
1928
1965
  }
1929
1966
  function oldestTask(events) {
1930
1967
  const tasks = [...groupBy(events, (event) => event.task)].flatMap(([task, taskEvents]) => {
1931
- const creation = creationOf(taskEvents);
1968
+ const creation = taskCreation(
1969
+ taskEvents.find((event) => event.kind === "deleted")?.snapshot,
1970
+ taskEvents.findLast((event) => event.kind === "created")
1971
+ );
1932
1972
  return creation?.type === "task" ? [{ task, createdAt: creation.createdAt }] : [];
1933
1973
  });
1934
1974
  return tasks.reduce((oldest, candidate) => oldest === void 0 || candidate.createdAt < oldest.createdAt ? candidate : oldest, void 0)?.task;
1935
1975
  }
1936
- function creationOf(taskEvents) {
1937
- const deleted = taskEvents.find((event) => event.kind === "deleted");
1938
- if (deleted !== void 0) return { createdAt: Date.parse(deleted.snapshot.created), type: deleted.snapshot.type };
1939
- const created = taskEvents.findLast((event) => event.kind === "created");
1940
- return created === void 0 ? void 0 : { createdAt: Date.parse(created.at), type: created.type };
1941
- }
1942
1976
  function earliestEvent(events) {
1943
1977
  return events.reduce((earliest, event) => earliest === void 0 || Date.parse(event.at) < Date.parse(earliest.at) ? event : earliest, void 0);
1944
1978
  }
@@ -1951,7 +1985,7 @@ function lastMomentByTask(events) {
1951
1985
  // src/core/service-log.ts
1952
1986
  import { posix } from "node:path";
1953
1987
  var SERVICE_LOG_LIMIT_BYTES = BYTES_PER_MEBIBYTE;
1954
- var SERVICE_LOG_KEPT_BYTES = 256 * 1024;
1988
+ var SERVICE_LOG_KEPT_BYTES = 256 * BYTES_PER_KIBIBYTE;
1955
1989
  function launchdLogPath(home2) {
1956
1990
  return posix.join(home2, "Library/Logs/p-backlog.log");
1957
1991
  }
@@ -1975,7 +2009,7 @@ async function trimOpenLog(handle, limitBytes, keptBytes) {
1975
2009
  // src/core/store/maintenance.ts
1976
2010
  async function runMaintenance(plan, { root, now, messages, warn: warn2 }) {
1977
2011
  await warnOnFailure(plan.trimRuns(root, now), warn2, messages.runsNotTrimmed);
1978
- const report = plan.sweepClosed === null ? null : await warnOnFailure(plan.sweepClosed(root, now, messages, warnPathErrors(warn2)), warn2, messages.closedNotSwept);
2012
+ const report = plan.sweepClosed === null ? null : await warnOnFailure(plan.sweepClosed(root, { now, onError: warnPathErrors(warn2) }, messages), warn2, messages.closedNotSwept);
1979
2013
  if (plan.compactJournals !== null) {
1980
2014
  const compactionFailed = (dir, error) => warn2(messages.journalNotCompacted(dir, errorText(error)));
1981
2015
  await warnOnFailure(plan.compactJournals(root, now, compactionFailed), warn2, (error) => messages.journalNotCompacted(root, error));
@@ -2274,14 +2308,14 @@ function nextOptional(current, change) {
2274
2308
 
2275
2309
  // src/core/store/sweep.ts
2276
2310
  var SWEPT_AT_FILE = ".swept-at";
2277
- function sweepClosedWhenDue(root, now, messages, onError) {
2278
- return runWhenDue(join10(root, SWEPT_AT_FILE), now, () => sweepClosed(root, now, messages, onError));
2311
+ function sweepClosedWhenDue(root, writes, messages) {
2312
+ return runWhenDue(join10(root, SWEPT_AT_FILE), writes.now, () => sweepClosed(root, writes, messages));
2279
2313
  }
2280
- function sweepClosedAndStamp(root, now, messages, onError) {
2281
- return runAndStamp(join10(root, SWEPT_AT_FILE), now, () => sweepClosed(root, now, messages, onError));
2314
+ function sweepClosedAndStamp(root, writes, messages) {
2315
+ return runAndStamp(join10(root, SWEPT_AT_FILE), writes.now, () => sweepClosed(root, writes, messages));
2282
2316
  }
2283
- async function sweepClosed(root, now, messages, onError) {
2284
- const writes = { now, onError };
2317
+ async function sweepClosed(root, writes, messages) {
2318
+ const { now } = writes;
2285
2319
  const initial = await loadBacklog(root);
2286
2320
  const reopening = await reopenEpicsWithOpenTasks(initial, writes);
2287
2321
  const epics = await closeCompletedEpics(initial, writes, messages);
@@ -2558,6 +2592,7 @@ var cliEn = {
2558
2592
  alreadyInStatus: (id, status) => `${id} is already ${status}`,
2559
2593
  blockedByOpenTasks: (id) => `${id} is blocked by open tasks:`,
2560
2594
  noTakeableInProject: (id) => `Project ${id} has no tasks that can be taken`,
2595
+ resumeAbandoned: (id) => `${id} is already in progress and has not changed for over a day \u2014 finish it first: continue its checklist and "Notes" in the task file`,
2561
2596
  hookUsage: (stopEvent, agents) => `${stopEvent} [--agent ${agents.map(({ agent }) => agent).join("|")}] (for the Stop hook in ${joinAlternatives(
2562
2597
  agents.map(({ label }) => label),
2563
2598
  "or"
@@ -2737,6 +2772,7 @@ var cliRu = {
2737
2772
  alreadyInStatus: (id, status) => `${id} \u0443\u0436\u0435 \u0432 \u0441\u0442\u0430\u0442\u0443\u0441\u0435 ${status}`,
2738
2773
  blockedByOpenTasks: (id) => `${id} \u0437\u0430\u0431\u043B\u043E\u043A\u0438\u0440\u043E\u0432\u0430\u043D\u0430 \u043E\u0442\u043A\u0440\u044B\u0442\u044B\u043C\u0438 \u0437\u0430\u0434\u0430\u0447\u0430\u043C\u0438:`,
2739
2774
  noTakeableInProject: (id) => `\u0412 \u043F\u0440\u043E\u0435\u043A\u0442\u0435 ${id} \u043D\u0435\u0442 \u0437\u0430\u0434\u0430\u0447, \u043A\u043E\u0442\u043E\u0440\u044B\u0435 \u043C\u043E\u0436\u043D\u043E \u0432\u0437\u044F\u0442\u044C \u0432 \u0440\u0430\u0431\u043E\u0442\u0443`,
2775
+ resumeAbandoned: (id) => `${id} \u0443\u0436\u0435 \u0432 \u0440\u0430\u0431\u043E\u0442\u0435 \u0438 \u043D\u0435 \u043C\u0435\u043D\u044F\u043B\u0430\u0441\u044C \u0431\u043E\u043B\u044C\u0448\u0435 \u0441\u0443\u0442\u043E\u043A \u2014 \u0441\u043D\u0430\u0447\u0430\u043B\u0430 \u0434\u043E\u0434\u0435\u043B\u0430\u0439 \u0435\u0451: \u043F\u0440\u043E\u0434\u043E\u043B\u0436\u0438 \u0447\u0435\u043A\u043B\u0438\u0441\u0442 \u0438 \xAB\u0417\u0430\u043C\u0435\u0442\u043A\u0438\xBB \u0432 \u0444\u0430\u0439\u043B\u0435 \u0437\u0430\u0434\u0430\u0447\u0438`,
2740
2776
  hookUsage: (stopEvent, agents) => `${stopEvent} [--agent ${agents.map(({ agent }) => agent).join("|")}] (\u0434\u043B\u044F \u0445\u0443\u043A\u0430 Stop \u0432 ${joinAlternatives(
2741
2777
  agents.map(({ label }) => label),
2742
2778
  "\u0438\u043B\u0438"
@@ -2817,6 +2853,8 @@ import { parseArgs } from "node:util";
2817
2853
  var DEFAULT_PORT = 4317;
2818
2854
  var DECIMAL_DIGITS = /^\d+$/;
2819
2855
  var LOOPBACK_HOST = "127.0.0.1";
2856
+ var LOCALHOST = "localhost";
2857
+ var LOOPBACK_HOSTS = [LOOPBACK_HOST, LOCALHOST, "[::1]"];
2820
2858
  function portNumber(value) {
2821
2859
  if (!DECIMAL_DIGITS.test(value)) return null;
2822
2860
  const port = Number(value);
@@ -2829,7 +2867,7 @@ function loopbackOrigin(port) {
2829
2867
  return `http://${LOOPBACK_HOST}:${port}`;
2830
2868
  }
2831
2869
  function browserOrigin(port) {
2832
- return `http://localhost:${port}`;
2870
+ return `http://${LOCALHOST}:${port}`;
2833
2871
  }
2834
2872
 
2835
2873
  // src/cli/io.ts
@@ -2936,6 +2974,22 @@ async function createTask(root, request) {
2936
2974
  return invalid([{ code: "id-exhausted", attempts: MAX_ID_ATTEMPTS }]);
2937
2975
  }
2938
2976
  async function createProject(root, repoRoot, existingProjects) {
2977
+ for (let attempt = 1; ; attempt++) {
2978
+ const { id, path, text } = await draftProjectFile(root, repoRoot, existingProjects);
2979
+ try {
2980
+ await createFileAtomic(path, text);
2981
+ const parsed = parseProjectFile(text, { id, path });
2982
+ if (!parsed.ok) throw new Error(`${path}: ${parsed.problems.map((problem3) => problem3.code).join(", ")}`);
2983
+ return parsed.value;
2984
+ } catch (error) {
2985
+ if (!hasErrorCode(error, "EEXIST")) throw error;
2986
+ const concurrent = await projectOfRepo(id, path, repoRoot);
2987
+ if (concurrent !== null) return concurrent;
2988
+ if (attempt === MAX_ID_ATTEMPTS) throw error;
2989
+ }
2990
+ }
2991
+ }
2992
+ async function draftProjectFile(root, repoRoot, existingProjects) {
2939
2993
  const name = basename5(repoRoot);
2940
2994
  const entries = await listDir(root);
2941
2995
  const joinable = await Promise.all(entries.map((entry) => entry.isDirectory() && isJoinableProjectDir(join11(root, entry.name), repoRoot)));
@@ -2944,18 +2998,7 @@ async function createProject(root, repoRoot, existingProjects) {
2944
2998
  const prefix = derivePrefix(name, /* @__PURE__ */ new Set([...existingProjects.map((project) => project.prefix), ...prefixesOnDisk.flat()]));
2945
2999
  const dir = join11(root, id);
2946
3000
  await mkdir3(dir, { recursive: true });
2947
- const path = join11(dir, PROJECT_FILE);
2948
- const text = serializeProject({ name, prefix, repos: [repoRoot], active: true, extra: {}, body: "" });
2949
- try {
2950
- await createFileAtomic(path, text);
2951
- } catch (error) {
2952
- const concurrent = hasErrorCode(error, "EEXIST") ? await projectOfRepo(id, path, repoRoot) : null;
2953
- if (concurrent === null) throw error;
2954
- return concurrent;
2955
- }
2956
- const parsed = parseProjectFile(text, { id, path });
2957
- if (!parsed.ok) throw new Error(`${path}: ${parsed.problems.map((problem3) => problem3.code).join(", ")}`);
2958
- return parsed.value;
3001
+ return { id, path: join11(dir, PROJECT_FILE), text: serializeProject({ name, prefix, repos: [repoRoot], active: true, extra: {}, body: "" }) };
2959
3002
  }
2960
3003
  async function isJoinableProjectDir(dir, repoRoot) {
2961
3004
  const entries = await listDir(dir);
@@ -3057,10 +3100,13 @@ var runGitOutcome = (repo, args, input) => gitProcessSlot(async () => {
3057
3100
  return typeof exitCode2 === "number" ? { status: "exited", exitCode: exitCode2, stderr: stderrOf(error) } : { status: "unfinished" };
3058
3101
  }
3059
3102
  });
3060
- var runGit = async (repo, args, input) => {
3061
- const outcome = await runGitOutcome(repo, args, input);
3062
- return args[0] === "grep" && outcome.status === "exited" && outcome.exitCode === GREP_NO_MATCH_EXIT ? "" : stdoutOf(outcome);
3063
- };
3103
+ function asGitRunner(git) {
3104
+ return async (repo, args, input) => {
3105
+ const outcome = await git(repo, args, input);
3106
+ return args[0] === "grep" && outcome.status === "exited" && outcome.exitCode === GREP_NO_MATCH_EXIT ? "" : stdoutOf(outcome);
3107
+ };
3108
+ }
3109
+ var runGit = asGitRunner(runGitOutcome);
3064
3110
  function stdoutOf(outcome) {
3065
3111
  return outcome.status === "ok" ? outcome.stdout : null;
3066
3112
  }
@@ -3068,18 +3114,28 @@ function outputLine(stdout) {
3068
3114
  const line = stdout?.trim();
3069
3115
  return line === void 0 || line === "" ? null : line;
3070
3116
  }
3117
+ function outputLines(stdout) {
3118
+ return stdout?.split("\n").filter((line) => line !== "") ?? null;
3119
+ }
3071
3120
  function literalPathspecs(paths) {
3072
3121
  return paths.map((path) => `:(literal)${path}`);
3073
3122
  }
3123
+ function topLiteralPathspecs(paths) {
3124
+ return paths.map((path) => `:(top,literal)${path}`);
3125
+ }
3074
3126
  function runGitSync(repo, args) {
3075
3127
  try {
3076
3128
  return execFileSync("git", gitArgs(repo, args), { encoding: "utf8", maxBuffer: GIT_OUTPUT_LIMIT, stdio: ["ignore", "pipe", "ignore"] });
3077
- } catch {
3078
- return null;
3129
+ } catch (error) {
3130
+ if (isChildProcessFailure(error)) return null;
3131
+ throw error;
3079
3132
  }
3080
3133
  }
3134
+ function isChildProcessFailure(error) {
3135
+ return typeof error === "object" && error !== null && "status" in error;
3136
+ }
3081
3137
  function gitArgs(repo, args) {
3082
- return ["-C", repo, "--no-optional-locks", "-c", "core.quotePath=false", ...args];
3138
+ return ["-C", repo, "--no-optional-locks", "-c", "core.quotePath=false", "-c", "diff.suppressBlankEmpty=false", ...args];
3083
3139
  }
3084
3140
  function resolveCommits(git, repo, revisions) {
3085
3141
  return resolveObjects(git, repo, revisions, "commit");
@@ -3128,7 +3184,7 @@ function cachedRepoRoots({ onUnreadable, ttlMs = REPO_ROOT_TTL_MS, now = Date.no
3128
3184
  const cached = known.get(dir);
3129
3185
  if (cached !== void 0 && isFresh(cached)) return cached.roots;
3130
3186
  for (const [knownDir, entry] of known) if (!isFresh(entry)) known.delete(knownDir);
3131
- const roots = readReportingFailure(dir, async (path) => await findGitRootsAsync(path) ?? plainDirRoots(path), onUnreadable);
3187
+ const roots = attemptReportingFailure(dir, async (path) => await findGitRootsAsync(path) ?? plainDirRoots(path), onUnreadable);
3132
3188
  known.set(dir, { roots, checkedAt: now() });
3133
3189
  return roots;
3134
3190
  };
@@ -3157,8 +3213,15 @@ function canonicalRoots(worktreePath, mainPath) {
3157
3213
  const main = realpathOrNull(mainPath);
3158
3214
  return worktree === null || main === null ? null : { worktree, main };
3159
3215
  }
3160
- function findProjectForDir(projects, dir, places) {
3161
- const roots = readReportingFailureSync(dir, (path) => findGitRoots(path) ?? plainDirRoots(path), places.onUnreadable);
3216
+ function readGitRoots(dir, onUnreadable) {
3217
+ return attemptReportingFailureSync(dir, (path) => findGitRoots(path) ?? "not-in-repo", onUnreadable) ?? "unreadable";
3218
+ }
3219
+ function repoRootsOf(dirRoots) {
3220
+ return typeof dirRoots === "string" ? null : dirRoots;
3221
+ }
3222
+ function findProjectForDir(projects, dir, dirRoots, places) {
3223
+ if (dirRoots === "unreadable") return void 0;
3224
+ const roots = dirRoots === "not-in-repo" ? attemptReportingFailureSync(dir, plainDirRoots, places.onUnreadable) : dirRoots;
3162
3225
  return roots === null ? void 0 : findProjectForRoots(projects, roots, places);
3163
3226
  }
3164
3227
  function findProjectForRoots(projects, { worktree, main }, places) {
@@ -3175,7 +3238,7 @@ function isSameOrInside(path, container) {
3175
3238
  return relation === "" || !isAbsolute(relation) && relation.split(sep)[0] !== "..";
3176
3239
  }
3177
3240
  function resolvedRepo(repo, { home: home2, onUnreadable }) {
3178
- return readReportingFailureSync(expandHome(repo, home2), realpathOrNull, onUnreadable);
3241
+ return attemptReportingFailureSync(expandHome(repo, home2), realpathOrNull, onUnreadable);
3179
3242
  }
3180
3243
 
3181
3244
  // src/cli/path-inside.ts
@@ -3187,11 +3250,33 @@ function relativeInside(container, path) {
3187
3250
  }
3188
3251
 
3189
3252
  // src/cli/lookups.ts
3253
+ function warnUnreadableSkipped(warn2, core) {
3254
+ return warnPathErrors(warn2, core.unreadableSkipped);
3255
+ }
3256
+ var placesOfRun = /* @__PURE__ */ new WeakMap();
3190
3257
  function repoPlaces(io) {
3191
- return { home: io.home, onUnreadable: warnPathErrors(io.warn, io.core.unreadableSkipped) };
3258
+ const known = placesOfRun.get(io);
3259
+ if (known !== void 0) return known;
3260
+ const places = { home: io.home, onUnreadable: oncePerPath(warnUnreadableSkipped(io.warn, io.core)) };
3261
+ placesOfRun.set(io, places);
3262
+ return places;
3263
+ }
3264
+ var cwdRootsOfRun = /* @__PURE__ */ new WeakMap();
3265
+ function cwdDirRoots(io) {
3266
+ const known = cwdRootsOfRun.get(io);
3267
+ if (known !== void 0) return known;
3268
+ const roots = readGitRoots(io.cwd, repoPlaces(io).onUnreadable);
3269
+ cwdRootsOfRun.set(io, roots);
3270
+ return roots;
3271
+ }
3272
+ function cwdGitRoots(io) {
3273
+ return repoRootsOf(cwdDirRoots(io));
3274
+ }
3275
+ function findProjectForCwd(projects, io) {
3276
+ return findProjectForDir(projects, io.cwd, cwdDirRoots(io), repoPlaces(io));
3192
3277
  }
3193
3278
  function repoLookup(io) {
3194
- return { ...repoPlaces(io), workingDir: io.cwd };
3279
+ return { ...repoPlaces(io), workingRoots: cwdGitRoots(io) };
3195
3280
  }
3196
3281
  function findTaskOrWarn(loaded, io, id) {
3197
3282
  const task = loaded.tasks.find((candidate) => candidate.id === id);
@@ -3213,8 +3298,9 @@ async function ensureProject(loaded, io, explicitId) {
3213
3298
  if (explicitId !== void 0) return findProjectOrWarn(loaded, io, explicitId);
3214
3299
  const existing = findProject(loaded, io, void 0);
3215
3300
  if (existing) return existing;
3216
- const gitRoots = findGitRoots(io.cwd);
3217
- if (gitRoots === null) {
3301
+ const gitRoots = cwdDirRoots(io);
3302
+ if (gitRoots === "unreadable") return void 0;
3303
+ if (gitRoots === "not-in-repo") {
3218
3304
  io.warn(io.cli.notInGitRepo(io.cwd));
3219
3305
  return void 0;
3220
3306
  }
@@ -3251,7 +3337,7 @@ function homeRelative(path, home2) {
3251
3337
  return inside === null ? path : `~/${inside}`;
3252
3338
  }
3253
3339
  function findProject(loaded, io, explicitId) {
3254
- return explicitId === void 0 ? findProjectForDir(loaded.projects, io.cwd, repoPlaces(io)) : loaded.projects.find((project) => project.id === explicitId);
3340
+ return explicitId === void 0 ? findProjectForCwd(loaded.projects, io) : loaded.projects.find((project) => project.id === explicitId);
3255
3341
  }
3256
3342
 
3257
3343
  // src/cli/task-write.ts
@@ -3331,12 +3417,19 @@ var SNIPPET_CONTEXT = 5;
3331
3417
  var HASH_LENGTH = 12;
3332
3418
  var LINE_NUMBER_WIDTH = 5;
3333
3419
  var MIN_MOVABLE_CHARS = 24;
3334
- var ANCHOR_FORMAT = /^([0-9a-f]+)@(\d+)-(\d+)$/;
3420
+ var ANCHOR_FORMAT = /^([0-9a-f]+)@(\d+)-(\d+)(?:\/([0-9a-f]+))?$/;
3335
3421
  function anchorOf(text, source) {
3336
3422
  const span2 = sourceSpan(source);
3337
3423
  const lines = fileLines(text);
3338
3424
  const window = span2 === null ? null : windowOf(span2, lines.length);
3339
- return window === null ? null : `${hashLines(lines.slice(window.from - 1, window.to))}@${window.from}-${window.to}`;
3425
+ if (span2 === null || window === null) return null;
3426
+ return `${hashLines(lines.slice(window.from - 1, window.to))}@${window.from}-${window.to}/${hashLines(lines.slice(span2.first - 1, span2.last))}`;
3427
+ }
3428
+ function windowMatches(text, source, anchor) {
3429
+ const current = anchorOf(text, source);
3430
+ const expected = parseAnchor(anchor);
3431
+ const found = current === null ? null : parseAnchor(current);
3432
+ return expected !== null && found !== null && found.hash === expected.hash && found.from === expected.from && found.to === expected.to;
3340
3433
  }
3341
3434
  function sourceRange(source) {
3342
3435
  const span2 = source === void 0 ? null : sourceSpan(source);
@@ -3347,7 +3440,7 @@ function anchorRange(source) {
3347
3440
  return span2 === null ? null : withContext(span2);
3348
3441
  }
3349
3442
  function locateAnchor(text, source, anchor) {
3350
- return anchorOf(text, source) === anchor ? source : findMoved(text, source, anchor);
3443
+ return windowMatches(text, source, anchor) ? source : findMoved(text, source, anchor);
3351
3444
  }
3352
3445
  function isAnchorFor(anchor, source) {
3353
3446
  const parsed = parseAnchor(anchor);
@@ -3360,18 +3453,28 @@ function findMoved(text, source, anchor) {
3360
3453
  const parsed = parseAnchor(anchor);
3361
3454
  const span2 = sourceSpan(source);
3362
3455
  if (parsed === null || span2 === null) return null;
3363
- const lines = fileLines(text);
3364
- const length = parsed.to - parsed.from + 1;
3365
- const matches = [];
3366
- for (let start2 = 1; start2 + length - 1 <= lines.length; start2++) {
3367
- if (hashLines(lines.slice(start2 - 1, start2 - 1 + length)) === parsed.hash) matches.push(start2);
3368
- }
3369
- const [start] = matches;
3370
- if (matches.length !== 1 || start === void 0) return null;
3371
- if (significantChars(lines.slice(start - 1, start - 1 + length)) < MIN_MOVABLE_CHARS) return null;
3456
+ const start = uniqueBlockStart(fileLines(text), parsed.to - parsed.from + 1, parsed.hash);
3457
+ if (start === null) return null;
3372
3458
  const shift = start - parsed.from;
3373
3459
  return withLines(source, span2.first + shift, span2.isRange ? span2.last + shift : void 0);
3374
3460
  }
3461
+ function findIntactLines(text, source, anchor) {
3462
+ const linesHash = parseAnchor(anchor)?.linesHash;
3463
+ const span2 = sourceSpan(source);
3464
+ if (linesHash === void 0 || span2 === null) return null;
3465
+ const length = span2.last - span2.first + 1;
3466
+ const start = uniqueBlockStart(fileLines(text), length, linesHash);
3467
+ return start === null ? null : withLines(source, start, span2.isRange ? start + length - 1 : void 0);
3468
+ }
3469
+ function uniqueBlockStart(lines, length, hash) {
3470
+ const starts = [];
3471
+ for (let start2 = 1; start2 + length - 1 <= lines.length; start2++) {
3472
+ if (hashLines(lines.slice(start2 - 1, start2 - 1 + length)) === hash) starts.push(start2);
3473
+ }
3474
+ const [start] = starts;
3475
+ if (starts.length !== 1 || start === void 0) return null;
3476
+ return significantChars(lines.slice(start - 1, start - 1 + length)) < MIN_MOVABLE_CHARS ? null : start;
3477
+ }
3375
3478
  function remappedSource(source, lineAt) {
3376
3479
  const span2 = sourceSpan(source);
3377
3480
  return span2 === null ? null : withLines(source, lineAt(span2.first), span2.isRange ? lineAt(span2.last) : void 0);
@@ -3403,7 +3506,7 @@ function withContext(span2) {
3403
3506
  }
3404
3507
  function parseAnchor(anchor) {
3405
3508
  const match = ANCHOR_FORMAT.exec(anchor);
3406
- return match === null ? null : { hash: match[1] ?? "", from: Number(match[2]), to: Number(match[3]) };
3509
+ return match === null ? null : { hash: match[1] ?? "", from: Number(match[2]), to: Number(match[3]), linesHash: match[4] };
3407
3510
  }
3408
3511
  function fileLines(text) {
3409
3512
  const lines = text.split("\n");
@@ -3455,8 +3558,7 @@ function codeCandidate(task, anchor, facts, knownCommits = /* @__PURE__ */ new S
3455
3558
  }
3456
3559
  function anchorPlan(task, anchor, facts) {
3457
3560
  if (task.source === void 0) return [];
3458
- if (anchor.kind === "moved") return [movedPlan(task.id, task.source, anchor)];
3459
- if (anchor.kind === "same") return [];
3561
+ if (anchor.kind === "moved") return [anchor.source === task.source ? { id: task.id, changes: { anchor: anchor.anchor } } : movedPlan(task.id, task.source, anchor)];
3460
3562
  const text = facts.texts.get(sourcePath(task.source));
3461
3563
  const fresh = text === void 0 ? null : anchorOf(text, task.source);
3462
3564
  return fresh === null || fresh === task.anchor ? [] : [{ id: task.id, changes: { anchor: fresh } }];
@@ -3489,8 +3591,8 @@ function anchorState(task, facts) {
3489
3591
  function anchorStateIn(task, text) {
3490
3592
  if (task.anchor === void 0 || task.source === void 0 || !hasLines(task.source) || !isAnchorFor(task.anchor, task.source)) return { kind: "none" };
3491
3593
  if (text === void 0) return { kind: "none" };
3492
- if (anchorOf(text, task.source) === task.anchor) return { kind: "same", source: task.source, anchor: task.anchor };
3493
- const moved = findMoved(text, task.source, task.anchor);
3594
+ if (windowMatches(text, task.source, task.anchor)) return { kind: "same", source: task.source, anchor: task.anchor };
3595
+ const moved = findMoved(text, task.source, task.anchor) ?? findIntactLines(text, task.source, task.anchor);
3494
3596
  const movedAnchor = moved === null ? null : anchorOf(text, moved);
3495
3597
  return moved === null || movedAnchor === null ? { kind: "changed" } : { kind: "moved", source: moved, anchor: movedAnchor };
3496
3598
  }
@@ -3629,6 +3731,8 @@ var HUNK_HEADER = /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/;
3629
3731
  var OMITTED_COUNT = 1;
3630
3732
  var FILE_HEADER = "diff ";
3631
3733
  var EMPTY_OLD_SIDE = 0;
3734
+ var COMMIT_LINE = /^commit (?<commit>[0-9a-f]+)$/;
3735
+ var INDEX_LINE = /^index (?<preimage>[0-9a-f]+)\.\.(?<postimage>[0-9a-f]+)/;
3632
3736
  function hunkHeaderOf(line) {
3633
3737
  const header = HUNK_HEADER.exec(line);
3634
3738
  if (header === null) return null;
@@ -3674,6 +3778,42 @@ function hunkLineOf(line) {
3674
3778
  return null;
3675
3779
  }
3676
3780
  }
3781
+ function patchShapes(patches) {
3782
+ const shapes = /* @__PURE__ */ new Map();
3783
+ let shape = emptyShape();
3784
+ shapes.set("", shape);
3785
+ let hunk;
3786
+ for (const line of patches.split("\n")) {
3787
+ const commit = COMMIT_LINE.exec(line)?.groups?.commit;
3788
+ const header = hunkHeaderOf(line);
3789
+ if (commit !== void 0) {
3790
+ shape = emptyShape();
3791
+ shapes.set(commit, shape);
3792
+ hunk = void 0;
3793
+ } else if (line.startsWith(FILE_HEADER)) hunk = void 0;
3794
+ else if (header !== null) hunk = { oldLine: firstLineOf(header.oldStart, header.oldCount), changing: false };
3795
+ else if (hunk === void 0) shape.blobs ??= blobPairOf(line);
3796
+ else walkHunkLine(hunk, line, shape);
3797
+ }
3798
+ return (commit) => shapes.get(commit) ?? emptyShape();
3799
+ }
3800
+ function blobPairOf(line) {
3801
+ const blobs = INDEX_LINE.exec(line)?.groups;
3802
+ return blobs === void 0 ? void 0 : { preimage: blobs.preimage ?? "", postimage: blobs.postimage ?? "" };
3803
+ }
3804
+ function walkHunkLine(hunk, line, shape) {
3805
+ const hunkLine = hunkLineOf(line);
3806
+ if (hunkLine === null) return;
3807
+ const changed = hunkLine.kind !== "context";
3808
+ if (changed && !hunk.changing) shape.changeStarts.push(hunk.oldLine);
3809
+ if (changed) shape.changedText += `${line}
3810
+ `;
3811
+ hunk.changing = changed;
3812
+ if (hunkLine.kind !== "added") hunk.oldLine += 1;
3813
+ }
3814
+ function emptyShape() {
3815
+ return { blobs: void 0, changeStarts: [], changedText: "" };
3816
+ }
3677
3817
  function changedRanges(hunks) {
3678
3818
  const ranges = [];
3679
3819
  for (const hunk of hunks) {
@@ -3776,6 +3916,7 @@ var REFLOG_MOMENT = /\{(\d+)\}$/;
3776
3916
  var STATUS_CODE_WIDTH = 3;
3777
3917
  var RENAME_OR_COPY = /^[RC]/;
3778
3918
  var ORIGINAL_PATH_FOLLOWS = /^(?:[RC].|.[RC])/;
3919
+ var FACTS_HISTORY_OPTIONS = ["--full-history"];
3779
3920
  async function collectRepoFacts(repo, pathMarks) {
3780
3921
  const paths = [...pathMarks.keys()];
3781
3922
  const [location, files] = await Promise.all([runGitOutcome(repo, ["rev-parse", "--show-prefix", "--revs-only", "HEAD"]), sourceFiles(repo, paths)]);
@@ -3804,7 +3945,7 @@ function earliestMark(marks, paths) {
3804
3945
  return new Date(Math.min(...paths.flatMap((path) => marks.get(path) ?? [])));
3805
3946
  }
3806
3947
  function logArgs(since) {
3807
- return ["log", "--relative", `--since=${since.toISOString()}`, `--format=${RECORD}%h${FIELD}%cI${FIELD}%p${FIELD}%s`, "--name-status", "-M", "--diff-merges=first-parent", "--full-history", "-z"];
3948
+ return ["log", "--relative", `--since=${since.toISOString()}`, `--format=${RECORD}%h${FIELD}%cI${FIELD}%p${FIELD}%s`, "--name-status", "-M", "--diff-merges=first-parent", ...FACTS_HISTORY_OPTIONS, "-z"];
3808
3949
  }
3809
3950
  async function pathLog(repo, since, paths) {
3810
3951
  const inside = paths.filter(isInsideRepo);
@@ -3867,7 +4008,7 @@ async function sourceFiles(repo, paths) {
3867
4008
  const recordUnreadable = (path, error) => {
3868
4009
  unreadable.set(path, error);
3869
4010
  };
3870
- const read = await Promise.all(paths.map((path) => readReportingFailure(path, (relative5) => sourceFile(repo, relative5), recordUnreadable)));
4011
+ const read = await Promise.all(paths.map((path) => attemptReportingFailure(path, (relative5) => sourceFile(repo, relative5), recordUnreadable)));
3871
4012
  const present = read.flatMap((file) => file?.kind === "present" ? [file] : []);
3872
4013
  return {
3873
4014
  existing: new Set(present.map((file) => file.path)),
@@ -3963,7 +4104,7 @@ async function traceSource(task, facts, diffs) {
3963
4104
  if (text === void 0) return UNTRACED;
3964
4105
  const { commits, uncommitted } = changesSince(facts, sourcePath(source), reviewMark(task));
3965
4106
  const fileUntouched = commits.length === 0 && !uncommitted;
3966
- if (fileUntouched && (anchor === void 0 || anchorOf(text, source) === anchor)) return { kind: "traced", current: source, linesChanged: false };
4107
+ if (fileUntouched && (anchor === void 0 || windowMatches(text, source, anchor))) return { kind: "traced", current: source, linesChanged: false };
3967
4108
  const traced = { ...task, source };
3968
4109
  const reference = await referenceOf(traced, text, commits, diffs);
3969
4110
  if (reference.kind === "not-on-branch") return fileUntouched ? { kind: "not-on-branch" } : UNTRACED;
@@ -3999,7 +4140,7 @@ async function referenceOf(task, text, laterCommits, diffs) {
3999
4140
 
4000
4141
  // src/core/check/project-repo.ts
4001
4142
  async function sourceAnchor(repo, source, onUnreadable) {
4002
- const text = repo === void 0 ? null : await readReportingFailure(join13(repo, sourcePath(source)), readTextIfFile, onUnreadable);
4143
+ const text = repo === void 0 ? null : await attemptReportingFailure(join13(repo, sourcePath(source)), readTextIfFile, onUnreadable);
4003
4144
  if (text === null) return { kind: "no-file" };
4004
4145
  const anchor = anchorOf(text, source);
4005
4146
  return anchor === null ? { kind: "uncomputable" } : { kind: "anchor", anchor };
@@ -4008,8 +4149,8 @@ async function relocatedSource(repo, task) {
4008
4149
  const current = repo === void 0 ? null : await currentSourceIn(repo, task);
4009
4150
  return current === null || current === task.source ? void 0 : current;
4010
4151
  }
4011
- async function findRepo(project, { workingDir, ...lookup }) {
4012
- return (await projectCheckout(project, workingDir === void 0 ? null : findGitRoots(workingDir), lookup))?.path;
4152
+ async function findRepo(project, { workingRoots, ...lookup }) {
4153
+ return (await projectCheckout(project, workingRoots, lookup))?.path;
4013
4154
  }
4014
4155
  async function projectCheckout(project, workingRoots, lookup) {
4015
4156
  const repo = await firstExistingRepo(project, lookup);
@@ -4019,7 +4160,7 @@ async function projectCheckout(project, workingRoots, lookup) {
4019
4160
  }
4020
4161
  async function firstExistingRepo(project, { home: home2, onUnreadable }) {
4021
4162
  for (const repo of project.repos.map((path) => expandHome(path, home2))) {
4022
- if (await readReportingFailure(repo, fileExists, onUnreadable) === true) return repo;
4163
+ if (await attemptReportingFailure(repo, fileExists, onUnreadable) === true) return repo;
4023
4164
  }
4024
4165
  return void 0;
4025
4166
  }
@@ -4051,9 +4192,10 @@ function openCodeGraph(repo) {
4051
4192
  return null;
4052
4193
  }
4053
4194
  return codeGraph(db, root);
4054
- } catch {
4055
- closeQuietly(db);
4056
- return null;
4195
+ } catch (error) {
4196
+ closeIfOpen(db);
4197
+ if (isEnvironmentFailure(error)) return null;
4198
+ throw error;
4057
4199
  }
4058
4200
  }
4059
4201
  function readMetadata(db) {
@@ -4079,7 +4221,7 @@ function codeGraph(db, repo) {
4079
4221
  return row === void 0 ? null : { qualifiedName: row.qualified_name, kind: symbolKindOf(row.kind), from: row.line_start, to: row.line_end };
4080
4222
  },
4081
4223
  close() {
4082
- closeQuietly(db);
4224
+ closeIfOpen(db);
4083
4225
  }
4084
4226
  };
4085
4227
  }
@@ -4089,36 +4231,70 @@ function symbolKindOf(stored) {
4089
4231
  function ask(statement, run, fallback) {
4090
4232
  try {
4091
4233
  return run(statement);
4092
- } catch {
4093
- return fallback;
4234
+ } catch (error) {
4235
+ if (isEnvironmentFailure(error)) return fallback;
4236
+ throw error;
4094
4237
  }
4095
4238
  }
4096
- function closeQuietly(db) {
4239
+ function isEnvironmentFailure(error) {
4240
+ return typeof errorCode(error) === "string";
4241
+ }
4242
+ function closeIfOpen(db) {
4097
4243
  try {
4098
4244
  db?.close();
4099
- } catch {
4100
- return;
4245
+ } catch (error) {
4246
+ if (!hasErrorCode(error, "ERR_INVALID_STATE")) throw error;
4101
4247
  }
4102
4248
  }
4103
4249
 
4250
+ // src/core/git/landing.ts
4251
+ async function firstParentLanding(git, repo, commit, head) {
4252
+ const chain = await firstParentChain(git, repo, commit, head);
4253
+ if (chain === null || chain.length === 0) return null;
4254
+ const carries = (index) => contains(git, repo, chain[index]?.commit ?? "", commit);
4255
+ const oldest = chain.length - 1;
4256
+ const oldestCarries = await carries(oldest);
4257
+ if (oldestCarries === null) return null;
4258
+ if (oldestCarries) return chain[oldest] ?? null;
4259
+ if (await carries(0) !== true) return null;
4260
+ let carrying = 0;
4261
+ let notCarrying = oldest;
4262
+ while (notCarrying - carrying > 1) {
4263
+ const middle = Math.floor((carrying + notCarrying) / 2);
4264
+ const middleCarries = await carries(middle);
4265
+ if (middleCarries === null) return null;
4266
+ if (middleCarries) carrying = middle;
4267
+ else notCarrying = middle;
4268
+ }
4269
+ return chain[carrying] ?? null;
4270
+ }
4271
+ async function firstParentChain(git, repo, commit, head) {
4272
+ const lines = outputLines(await git(repo, ["log", "--first-parent", `--format=tformat:%H${FIELD}%P${FIELD}%cI`, `${commit}..${head}`, "--"]));
4273
+ if (lines === null) return null;
4274
+ return lines.map((line) => {
4275
+ const [sha = "", parents = "", committedAt = ""] = line.split(FIELD);
4276
+ return { commit: sha, firstParent: parents.split(" ")[0] ?? "", committedAt };
4277
+ });
4278
+ }
4279
+ async function contains(git, repo, descendant, commit) {
4280
+ const missing = await git(repo, ["rev-list", "--max-count=1", commit, `^${descendant}`, "--"]);
4281
+ return missing === null ? null : missing.trim() === "";
4282
+ }
4283
+
4104
4284
  // src/core/check/landed-content.ts
4105
4285
  var PATCH_OPTIONS = ["-p", "--no-color", "--no-ext-diff", "--no-textconv", "--no-renames", "--no-relative", "--full-index", "--diff-algorithm=myers", "--indent-heuristic"];
4106
4286
  var COMMIT_HEADER = "--format=commit %H";
4107
- var COMMIT_LINE = /^commit (?<commit>[0-9a-f]+)$/;
4108
- var INDEX_LINE = /^index (?<preimage>[0-9a-f]+)\.\.(?<postimage>[0-9a-f]+)/;
4109
4287
  var TREE_PAIR_LINE = /^[0-9a-f]+ [0-9a-f]+$/;
4110
4288
  var NO_COMMIT = /^0+$/;
4111
- var NO_NEWLINE_MARK = "\\";
4112
4289
  var RAW_RECORD = /commit (?<commit>[0-9a-f]+)\0|:\d+ (?<mode>\d+) [0-9a-f]+ (?<object>[0-9a-f]+) [A-Z]\d*\0(?<path>[^\0]*)\0/g;
4113
4290
  async function contentLanded(repo, tip, git) {
4114
4291
  const fork = await forkAt(repo, "HEAD", tip, git);
4115
4292
  if (fork === null) return false;
4116
- const view = { ...fork, repo, history: "simplified", git };
4293
+ const view = { ...fork, repo, historyOptions: [], git };
4117
4294
  const changed = await branchChanges(view, []);
4118
4295
  if (changed === null) return false;
4119
4296
  if (changed.length === 0) return true;
4120
- const pathspecs = changed.map(({ path }) => pathspecOf(path));
4121
- const landed = await headChanges(view, pathspecs);
4297
+ const landed = await headChanges(view, topLiteralPathspecs(changed.map(({ path }) => path)));
4122
4298
  if (landed === null) return false;
4123
4299
  const landedVersions = new Set(landed.map(({ version }) => version));
4124
4300
  for (const { path, version } of changed) {
@@ -4126,11 +4302,11 @@ async function contentLanded(repo, tip, git) {
4126
4302
  }
4127
4303
  return true;
4128
4304
  }
4129
- function commitsCarryingContent(repo, git) {
4305
+ function commitsCarryingContent(repo, git, historyOptions) {
4130
4306
  const forks = /* @__PURE__ */ new Map();
4131
4307
  return async (tip, scope) => {
4132
4308
  const fork = await remembered(forks, tip, () => forkBeforeLanding(repo, tip, git));
4133
- return fork === null ? [] : commitsCarrying({ ...fork, repo, history: "full", git }, scope);
4309
+ return fork === null ? [] : commitsCarrying({ ...fork, repo, historyOptions, git }, scope);
4134
4310
  };
4135
4311
  }
4136
4312
  async function commitsCarrying(view, scope) {
@@ -4157,21 +4333,8 @@ async function forkAt(repo, head, tip, git) {
4157
4333
  async function forkBeforeLanding(repo, tip, git) {
4158
4334
  const fork = await forkAt(repo, "HEAD", tip, git);
4159
4335
  if (fork === null || !tipInHead(fork)) return fork;
4160
- const beforeLanding = await firstParentBeforeLanding(repo, tip, git);
4161
- return beforeLanding === null ? fork : forkAt(repo, beforeLanding, tip, git);
4162
- }
4163
- async function firstParentBeforeLanding(repo, tip, git) {
4164
- const chain = (await git(repo, ["rev-list", "--first-parent", `${tip}..HEAD`]))?.split("\n").filter((sha) => sha !== "") ?? [];
4165
- const chainCarriesTip = async (index) => await git(repo, ["merge-base", "--is-ancestor", tip, chain[index] ?? ""]) !== null;
4166
- if (chain.length === 0 || await chainCarriesTip(chain.length - 1)) return null;
4167
- let carrying = 0;
4168
- let notCarrying = chain.length - 1;
4169
- while (notCarrying - carrying > 1) {
4170
- const middle = Math.floor((carrying + notCarrying) / 2);
4171
- if (await chainCarriesTip(middle)) carrying = middle;
4172
- else notCarrying = middle;
4173
- }
4174
- return chain[notCarrying] ?? null;
4336
+ const landing = await firstParentLanding(git, repo, tip, "HEAD");
4337
+ return landing === null ? fork : forkAt(repo, landing.firstParent, tip, git);
4175
4338
  }
4176
4339
  function tipInHead({ base, tip }) {
4177
4340
  return base.startsWith(tip);
@@ -4182,16 +4345,13 @@ async function branchChanges(view, pathspecs) {
4182
4345
  const changed = await git(repo, ["diff-tree", "-r", "-z", "--no-renames", base, tip, "--", ...pathspecs]);
4183
4346
  return changed === null ? null : rawChanges(changed);
4184
4347
  }
4185
- async function headChanges({ repo, base, head, history, git }, pathspecs) {
4186
- const rawLog = await git(repo, ["log", "--stdin", COMMIT_HEADER, "--raw", "-z", "--no-renames", "--no-abbrev", "--no-relative", ...historyOptions(history)], `${base}..${head}
4348
+ async function headChanges({ repo, base, head, historyOptions, git }, pathspecs) {
4349
+ const rawLog = await git(repo, ["log", "--stdin", COMMIT_HEADER, "--raw", "-z", "--no-renames", "--no-abbrev", "--no-relative", ...historyOptions], `${base}..${head}
4187
4350
  --
4188
4351
  ${pathspecs.join("\n")}
4189
4352
  `);
4190
4353
  return rawLog === null ? null : rawChanges(rawLog);
4191
4354
  }
4192
- function historyOptions(history) {
4193
- return history === "full" ? ["--full-history"] : [];
4194
- }
4195
4355
  function rawChanges(raw) {
4196
4356
  const changes = [];
4197
4357
  let commit = "";
@@ -4213,12 +4373,12 @@ function earliestCopies(copies) {
4213
4373
  return [earliest(copies.squashed), ...everyCommitCopied(copies) ? copies.commitByCommit.map(earliest) : []].flat();
4214
4374
  }
4215
4375
  async function patchCopies(view, path) {
4216
- const { repo, base, tip, head, history, git } = view;
4217
- const onlyPath = ["--", pathspecOf(path)];
4376
+ const { repo, base, tip, head, historyOptions, git } = view;
4377
+ const onlyPath = ["--", ...topLiteralPathspecs([path])];
4218
4378
  const [squashedPatch, branchPatches, headPatches] = await Promise.all([
4219
4379
  patchesOf(repo, ["diff", ...PATCH_OPTIONS, base, tip, ...onlyPath], () => base, git),
4220
4380
  patchesOf(repo, ["log", ...PATCH_OPTIONS, COMMIT_HEADER, `${base}..${tip}`, ...onlyPath], parentOf, git),
4221
- patchesOf(repo, ["log", ...PATCH_OPTIONS, COMMIT_HEADER, "--date-order", ...historyOptions(history), `${base}..${head}`, ...onlyPath], parentOf, git)
4381
+ patchesOf(repo, ["log", ...PATCH_OPTIONS, COMMIT_HEADER, "--date-order", ...historyOptions, `${base}..${head}`, ...onlyPath], parentOf, git)
4222
4382
  ]);
4223
4383
  if (squashedPatch === null || branchPatches === null || headPatches === null) return null;
4224
4384
  const headPatchesById = groupBy(headPatches, ({ id }) => id);
@@ -4233,50 +4393,13 @@ async function patchesOf(repo, patchArgs, preimageOf, git) {
4233
4393
  if (patches === null) return null;
4234
4394
  const ids = await git(repo, ["patch-id", "--stable"], patches);
4235
4395
  if (ids === null) return null;
4236
- const shapes = patchShapesByCommit(patches);
4396
+ const shapeOf = patchShapes(patches);
4237
4397
  return ids.split("\n").filter((line) => line !== "").map((line) => {
4238
4398
  const [id = "", label = ""] = line.split(" ");
4239
4399
  const commit = NO_COMMIT.test(label) ? "" : label;
4240
- const { blobs, changeStarts, changedText } = shapes.get(commit) ?? emptyShape();
4241
- return { id, commit, preimageRevision: preimageOf(commit), blobs, changeStarts, changedText };
4400
+ return { id, commit, preimageRevision: preimageOf(commit), ...shapeOf(commit) };
4242
4401
  });
4243
4402
  }
4244
- function patchShapesByCommit(patches) {
4245
- const shapes = /* @__PURE__ */ new Map();
4246
- let shape = emptyShape();
4247
- shapes.set("", shape);
4248
- let hunk;
4249
- for (const line of patches.split("\n")) {
4250
- const commit = COMMIT_LINE.exec(line)?.groups?.commit;
4251
- const header = hunkHeaderOf(line);
4252
- if (commit !== void 0) {
4253
- shape = emptyShape();
4254
- shapes.set(commit, shape);
4255
- hunk = void 0;
4256
- } else if (line.startsWith(FILE_HEADER)) hunk = void 0;
4257
- else if (header !== null) hunk = { oldLine: firstLineOf(header.oldStart, header.oldCount), changing: false };
4258
- else if (hunk === void 0) shape.blobs ??= blobPairOf(line);
4259
- else walkHunkLine(hunk, line, shape);
4260
- }
4261
- return shapes;
4262
- }
4263
- function blobPairOf(line) {
4264
- const blobs = INDEX_LINE.exec(line)?.groups;
4265
- return blobs === void 0 ? void 0 : { preimage: blobs.preimage ?? "", postimage: blobs.postimage ?? "" };
4266
- }
4267
- function walkHunkLine(hunk, line, shape) {
4268
- const mark = line.charAt(0);
4269
- if (mark === NO_NEWLINE_MARK) return;
4270
- const changed = mark === "-" || mark === "+";
4271
- if (changed && !hunk.changing) shape.changeStarts.push(hunk.oldLine);
4272
- if (changed) shape.changedText += `${line}
4273
- `;
4274
- hunk.changing = changed;
4275
- if (mark !== "+") hunk.oldLine += 1;
4276
- }
4277
- function emptyShape() {
4278
- return { blobs: void 0, changeStarts: [], changedText: "" };
4279
- }
4280
4403
  async function preimageShifts(repoGit, path, pairs) {
4281
4404
  const shifted = pairs.filter(([change, copy]) => shiftsNeeded(change, copy));
4282
4405
  const trees = await resolveTrees(repoGit.git, repoGit.repo, [...new Set(shifted.flatMap(([change, copy]) => [change.preimageRevision, copy.preimageRevision]))]);
@@ -4294,8 +4417,12 @@ async function preimageShifts(repoGit, path, pairs) {
4294
4417
  }
4295
4418
  async function treeDiffShifts({ repo, git }, path, treePairs) {
4296
4419
  if (treePairs.length === 0) return /* @__PURE__ */ new Map();
4297
- const preimageDiffs = await git(repo, ["diff-tree", "--stdin", ...PATCH_OPTIONS, "--unified=0", "--inter-hunk-context=0", "--", pathspecOf(path)], treePairs.map((treePair) => `${treePair}
4298
- `).join(""));
4420
+ const preimageDiffs = await git(
4421
+ repo,
4422
+ ["diff-tree", "--stdin", ...PATCH_OPTIONS, "--unified=0", "--inter-hunk-context=0", "--", ...topLiteralPathspecs([path])],
4423
+ treePairs.map((treePair) => `${treePair}
4424
+ `).join("")
4425
+ );
4299
4426
  return preimageDiffs === null ? /* @__PURE__ */ new Map() : lineShiftsByTreePair(preimageDiffs);
4300
4427
  }
4301
4428
  function lineShiftsByTreePair(preimageDiffs) {
@@ -4335,9 +4462,6 @@ function shiftedLine(line, shifts) {
4335
4462
  function parentOf(commit) {
4336
4463
  return `${commit}^`;
4337
4464
  }
4338
- function pathspecOf(path) {
4339
- return `:(top,literal)${path}`;
4340
- }
4341
4465
  function fileVersion({ mode = "", object = "", path = "" } = {}) {
4342
4466
  return { path, version: `${mode} ${object}\0${path}` };
4343
4467
  }
@@ -4352,11 +4476,12 @@ async function commitsKnownAtCreation({ repo, tasks, facts, anchors, origins, gi
4352
4476
  return [{ taskId: task.id, creation: origin.commit, path, changes: commitsTouchingSince(facts.commits, path, reviewMark(task)) }];
4353
4477
  });
4354
4478
  const branchCommitsByMerge = /* @__PURE__ */ new Map();
4355
- const commitsBroughtBy = (merge, creation, path) => remembered(branchCommitsByMerge, `${merge.sha} ${creation} ${path}`, async () => {
4356
- const shas = await git(repo, ["rev-list", `${merge.sha}^2`, `^${merge.sha}^1`, `^${creation}`, "--", ...literalPathspecs([path])]);
4357
- return shas === null ? null : shas.split("\n").filter((sha) => sha !== "");
4358
- });
4359
- const carryingContent = commitsCarryingContent(repo, git);
4479
+ const commitsBroughtBy = (merge, creation, path) => remembered(
4480
+ branchCommitsByMerge,
4481
+ `${merge.sha} ${creation} ${path}`,
4482
+ async () => outputLines(await git(repo, ["rev-list", `${merge.sha}^2`, `^${merge.sha}^1`, `^${creation}`, "--", ...literalPathspecs([path])]))
4483
+ );
4484
+ const carryingContent = commitsCarryingContent(repo, git, FACTS_HISTORY_OPTIONS);
4360
4485
  const copyAnswers = /* @__PURE__ */ new Map();
4361
4486
  const copiesOfCreation = (creation, path) => remembered(copyAnswers, `${creation} ${path}`, () => carryingContent(creation, literalPathspecs([path])));
4362
4487
  const isCopy = (copies, sha) => copies.some((fullSha) => fullSha.startsWith(sha));
@@ -4424,8 +4549,19 @@ function isQueuedTask(task) {
4424
4549
  return task.type === "task" && task.status === "backlog";
4425
4550
  }
4426
4551
  function pickNextTask(tasks, projectId, index) {
4427
- const candidates = tasks.filter((task) => task.projectId === projectId && isQueuedTask(task) && !isBlocked(task, index));
4428
- return candidates.sort((a, b) => priorityRank(b.priority) - priorityRank(a.priority) || Date.parse(a.created) - Date.parse(b.created) || compareIds(a.id, b.id))[0];
4552
+ return firstInQueueOrder(tasks.filter((task) => task.projectId === projectId && isQueuedTask(task) && !isBlocked(task, index)));
4553
+ }
4554
+ var ABANDONED_AFTER_MS2 = DAY_MS;
4555
+ function pickAbandonedTask(tasks, projectId, index, lastTouched2, now) {
4556
+ const cutoff = now.getTime() - ABANDONED_AFTER_MS2;
4557
+ const abandoned = tasks.filter((task) => task.projectId === projectId && isTakenTask(task) && !isBlocked(task, index) && (lastTouched2.get(task.id) ?? now.getTime()) < cutoff);
4558
+ return firstInQueueOrder(abandoned);
4559
+ }
4560
+ function isTakenTask(task) {
4561
+ return task.type === "task" && task.status === "in-progress";
4562
+ }
4563
+ function firstInQueueOrder(tasks) {
4564
+ return tasks.toSorted((a, b) => priorityRank(b.priority) - priorityRank(a.priority) || Date.parse(a.created) - Date.parse(b.created) || compareIds(a.id, b.id))[0];
4429
4565
  }
4430
4566
  var STALE_LOW_DAYS = DAYS_PER_MONTH;
4431
4567
  function staleLowTasks(tasks, now) {
@@ -4564,7 +4700,7 @@ async function awaitingMerge({ repo, taskIds, origins, git = runGitOutcome }) {
4564
4700
  }
4565
4701
  async function branchAwaitsMerge(repo, branch, git) {
4566
4702
  const tip = lineOf(await git(repo, ["rev-parse", "--verify", "--quiet", `refs/heads/${branch}`]));
4567
- return tip !== null && !await contentLanded(repo, tip, async (dir, args, input) => stdoutOf(await git(dir, args, input)));
4703
+ return tip !== null && !await contentLanded(repo, tip, asGitRunner(git));
4568
4704
  }
4569
4705
  function lineOf(outcome) {
4570
4706
  return outputLine(stdoutOf(outcome));
@@ -4572,11 +4708,10 @@ function lineOf(outcome) {
4572
4708
 
4573
4709
  // src/core/check/symbol-filter.ts
4574
4710
  import { createHash as createHash3 } from "node:crypto";
4575
- import { readFileSync } from "node:fs";
4576
4711
  import { join as join15 } from "node:path";
4577
- function fileHashes(repo) {
4712
+ function fileHashes(repo, onUnreadable) {
4578
4713
  const hashes = /* @__PURE__ */ new Map();
4579
- return (path) => remembered(hashes, path, () => fileHash(join15(repo, path)));
4714
+ return (path) => remembered(hashes, path, () => fileHash(join15(repo, path), onUnreadable));
4580
4715
  }
4581
4716
  function symbolLookup(graph, hashOf) {
4582
4717
  if (graph === null) return () => null;
@@ -4624,12 +4759,9 @@ function shortName(qualifiedName) {
4624
4759
  function watchedRange(symbol, declared) {
4625
4760
  return { from: Math.min(symbol.from, declared.from), to: Math.max(symbol.to, declared.to) };
4626
4761
  }
4627
- function fileHash(path) {
4628
- try {
4629
- return createHash3("sha256").update(readFileSync(path)).digest("hex");
4630
- } catch {
4631
- return null;
4632
- }
4762
+ function fileHash(path, onUnreadable) {
4763
+ const bytes = attemptReportingFailureSync(path, readBytesOrNullSync, onUnreadable);
4764
+ return bytes === null ? null : createHash3("sha256").update(bytes).digest("hex");
4633
4765
  }
4634
4766
  function overlaps(range, watched) {
4635
4767
  return range.from <= watched.to && range.to >= watched.from;
@@ -4657,7 +4789,7 @@ async function projectReview(project, allTasks, { repo, origins, mode, onUnreada
4657
4789
  const review = await reviewedCode(readable, scope);
4658
4790
  const graph = openCodeGraph(repo);
4659
4791
  try {
4660
- const context = await projectContext(readable, review, { repo, facts, graph, mode });
4792
+ const context = await projectContext(readable, review, { repo, facts, graph, mode, onUnreadable });
4661
4793
  const sighted = await sightedBySymbol(tasks, review, context, { mode, skipped });
4662
4794
  const judged = await judgedAgainstMerges(sighted, context, scope);
4663
4795
  return { projectId: project.id, ...judged, skipped: [...skipped], problems: historyProblems(project, repo, facts.history), unchecked: facts.history === "read" ? [] : ["source-changed"] };
@@ -4671,9 +4803,9 @@ async function reviewedCode(tasks, scope) {
4671
4803
  const knownCommits = await commitsKnownAtCreation({ repo, tasks, facts, anchors, origins });
4672
4804
  return withRenamesFollowed(codeReview(tasks, facts, knownCommits, anchors), tasks, scope);
4673
4805
  }
4674
- async function projectContext(tasks, review, { repo, facts, graph, mode }) {
4806
+ async function projectContext(tasks, review, { repo, facts, graph, mode, onUnreadable }) {
4675
4807
  const diffs = repoDiffs(repo);
4676
- const symbolAt = symbolLookup(graph, fileHashes(repo));
4808
+ const symbolAt = symbolLookup(graph, fileHashes(repo, onUnreadable));
4677
4809
  const changedIds = new Set(review.candidates.flatMap((candidate) => candidate.kind === "source-changed" ? [candidate.task.id] : []));
4678
4810
  const locating = mode === "full" && graph !== null ? tasks : tasks.filter((task) => changedIds.has(task.id));
4679
4811
  const traces = await traceSources(locating, facts, diffs);
@@ -4716,7 +4848,7 @@ async function withRenamesFollowed(review, tasks, { repo, onUnreadable }) {
4716
4848
  review.candidates.map(async (candidate) => {
4717
4849
  const task = tasksById.get(candidate.task.id);
4718
4850
  if (candidate.kind !== "source-missing" || candidate.renamedTo === void 0 || task === void 0) return null;
4719
- const text = await readReportingFailure(join16(repo, candidate.renamedTo), readTextIfFile, onUnreadable);
4851
+ const text = await attemptReportingFailure(join16(repo, candidate.renamedTo), readTextIfFile, onUnreadable);
4720
4852
  return text === null ? null : renamePlan(task, candidate.renamedTo, text);
4721
4853
  })
4722
4854
  );
@@ -4802,13 +4934,11 @@ async function checkBacklog(root, loaded, request) {
4802
4934
  return { fixed: [...fixes.fixed, ...anchors.fixed], problems: problems3, candidates: outcome.candidates };
4803
4935
  }
4804
4936
  async function reviewProjects(root, tasks, projects, request) {
4805
- const workingRoots = request.workingDir === void 0 ? null : findGitRoots(request.workingDir);
4806
4937
  const originsOf = (projectId) => creationOrigins(root, projectId, (error) => request.warn(request.messages.branchOriginsReadFailed(projectId, errorText(error))));
4807
- const onUnreadable = warnPathErrors(request.warn, request.messages.unreadableSkipped);
4808
4938
  return Promise.all(
4809
4939
  projects.map(async (project) => {
4810
- const checkout = await projectCheckout(project, workingRoots, { home: request.home, onUnreadable });
4811
- return { review: await projectReview(project, tasks, { repo: checkout?.path, origins: await originsOf(project.id), mode: request.mode, onUnreadable }), checkout };
4940
+ const checkout = await projectCheckout(project, request.workingRoots, request.places);
4941
+ return { review: await projectReview(project, tasks, { repo: checkout?.path, origins: await originsOf(project.id), mode: request.mode, onUnreadable: request.places.onUnreadable }), checkout };
4812
4942
  })
4813
4943
  );
4814
4944
  }
@@ -4890,7 +5020,6 @@ var ID_COLUMN_WIDTH = 10;
4890
5020
  var STATUS_COLUMN_WIDTH = Math.max(...TASK_STATUSES.map((status) => status.length));
4891
5021
  var PRIORITY_COLUMN_WIDTH = Math.max(...PRIORITIES.map((priority) => priority.length));
4892
5022
  var PROGRESS_COLUMN_WIDTH = "100%".length;
4893
- var JSON_INDENT = 2;
4894
5023
  function formatJson(value) {
4895
5024
  return JSON.stringify(value, null, JSON_INDENT);
4896
5025
  }
@@ -4974,7 +5103,15 @@ async function runCheck(args, io) {
4974
5103
  const scope = resolveScope(loaded, io, values);
4975
5104
  if (scope === null) return EXIT.notFound;
4976
5105
  const { projectIds } = scope;
4977
- const report = await checkBacklog(io.backlogRoot, loaded, { projectIds, mode: values.changed ? "changed" : "full", now: io.now(), home: io.home, messages: io.core, warn: io.warn, workingDir: io.cwd });
5106
+ const report = await checkBacklog(io.backlogRoot, loaded, {
5107
+ projectIds,
5108
+ mode: values.changed ? "changed" : "full",
5109
+ now: io.now(),
5110
+ places: repoPlaces(io),
5111
+ messages: io.core,
5112
+ warn: io.warn,
5113
+ workingRoots: cwdGitRoots(io)
5114
+ });
4978
5115
  io.print(values.json ? formatJson(report) : formatReport(io.cli, io.core, report));
4979
5116
  return needsReview(report) ? EXIT.needsReview : EXIT.ok;
4980
5117
  }
@@ -5079,21 +5216,20 @@ function reopeningsOf(history) {
5079
5216
  return history.transitions.filter((transition) => transition.from !== void 0 && isClosed(transition.from) && !isClosed(transition.to));
5080
5217
  }
5081
5218
  function historyOf(id, { projectId, final, created, categoryEvents, priorityEvents, transitions, candidates, verifications, filtered }, unparsed) {
5082
- const createdIso = final?.created ?? created?.at;
5083
- const type = final?.type ?? created?.type;
5084
- if (createdIso === void 0 || type === void 0) return [];
5219
+ const creation = taskCreation(final, created);
5220
+ if (creation === void 0) return [];
5085
5221
  const ordered = withoutUndoneClosings(chronological(transitions));
5086
5222
  const fateUnknown = final === void 0 && unparsed;
5087
5223
  return [
5088
5224
  {
5089
5225
  id,
5090
5226
  projectId,
5091
- type,
5092
- createdAt: Date.parse(createdIso),
5227
+ type: creation.type,
5228
+ createdAt: creation.createdAt,
5093
5229
  source: final?.source ?? created?.source,
5094
5230
  reason: final?.reason,
5095
5231
  finalStatus: final?.status ?? (fateUnknown ? ordered.at(-1)?.to ?? CREATED_STATUS : VANISHED_STATUS),
5096
- transitions: fateUnknown ? ordered : withResolutionOf(final, [...ordered, ...restoredTransitions(final, ordered, Date.parse(createdIso))]),
5232
+ transitions: fateUnknown ? ordered : withResolutionOf(final, [...ordered, ...restoredTransitions(final, ordered, creation.createdAt)]),
5097
5233
  priority: final?.priority ?? chronological(priorityEvents).at(-1)?.to ?? created?.priority,
5098
5234
  category: categoryOf(final, created, categoryEvents),
5099
5235
  found: created?.found,
@@ -5299,7 +5435,7 @@ async function detectAgents(places, onUnreadable) {
5299
5435
  for (const agent of AGENTS) {
5300
5436
  const spec = AGENT_SPECS[agent];
5301
5437
  const dir = spec.homeDir(places);
5302
- const present = spec.alwaysInstalled || await readReportingFailure(dir, isDirectory, onUnreadable);
5438
+ const present = spec.alwaysInstalled || await attemptReportingFailure(dir, isDirectory, onUnreadable);
5303
5439
  if (present === true) detection.found.push(agent);
5304
5440
  else if (present === false) detection.missing.push({ agent, dir });
5305
5441
  }
@@ -5389,7 +5525,7 @@ var enabledPluginsSchema = z9.object({ enabledPlugins: z9.record(z9.string(), z9
5389
5525
  async function agentPluginReportingFailure(agent, places, onUnreadable) {
5390
5526
  const settingsPath = AGENT_SPECS[agent].pluginSettingsPath;
5391
5527
  if (settingsPath === null) return { plugin: null };
5392
- return readReportingFailure(settingsPath(places), readEnabledPlugin, onUnreadable);
5528
+ return attemptReportingFailure(settingsPath(places), readEnabledPlugin, onUnreadable);
5393
5529
  }
5394
5530
  async function readEnabledPlugin(path) {
5395
5531
  const settings = await readJsonFile(path, enabledPluginsSchema);
@@ -5428,16 +5564,14 @@ async function runLanguage(positionals, io) {
5428
5564
  const language = parseChoice(io.language, value, LANGUAGES, io.cli.optionLabel.language);
5429
5565
  await writeSettings(io.backlogRoot, { language });
5430
5566
  io.print(`${io.language} \u2192 ${language}`);
5431
- const { unreadableSkipped } = coreMessages(language);
5432
- const { found } = await detectAgents(io, warnPathErrors(io.warn, unreadableSkipped));
5567
+ const { found } = await detectAgents(io, warnUnreadableSkipped(io.warn, coreMessages(language)));
5433
5568
  for (const agent of found) await relinkSkill(agent, language, io);
5434
5569
  return EXIT.ok;
5435
5570
  }
5436
5571
  async function relinkSkill(agent, language, io) {
5437
5572
  const cli = cliMessages(language);
5438
- const { unreadableSkipped } = coreMessages(language);
5439
5573
  const voice = agentVoice(agent, io);
5440
- const lookup = await agentPluginReportingFailure(agent, io, warnPathErrors(voice.warn, unreadableSkipped));
5574
+ const lookup = await agentPluginReportingFailure(agent, io, warnUnreadableSkipped(voice.warn, coreMessages(language)));
5441
5575
  if (lookup?.plugin) {
5442
5576
  const wanted = pluginToSwitchTo(lookup.plugin, language);
5443
5577
  if (wanted !== null) voice.print(cli.pluginLanguageHint(lookup.plugin, wanted));
@@ -5540,6 +5674,9 @@ import { z as z11 } from "zod";
5540
5674
  function markShown(shown, signals, today) {
5541
5675
  return { ...shown, ...Object.fromEntries(signals.map((signal3) => [signal3.kind, today])) };
5542
5676
  }
5677
+ function signalsToShow(signals, shown, today) {
5678
+ return signals.filter((signal3) => shown[signal3.kind] !== today);
5679
+ }
5543
5680
 
5544
5681
  // src/core/store/signals-shown.ts
5545
5682
  var SIGNALS_SHOWN_FILE = ".signals-shown.json";
@@ -5570,13 +5707,13 @@ async function rememberSessionShown(projectDir2, session, taskIds, now) {
5570
5707
  }
5571
5708
 
5572
5709
  // src/core/stats/scope.ts
5573
- function inProjectScope(items, projectId, projectOf2) {
5710
+ function filterByProject(items, projectId, projectOf2) {
5574
5711
  return items.filter((item) => projectId === void 0 || projectOf2(item) === projectId);
5575
5712
  }
5576
5713
  function statsScope({ tasks, journals, projectId, unparsedTasks: unparsedTasks2 = [] }) {
5577
- const scopedJournals = inProjectScope(journals, projectId, (journal) => journal.projectId);
5578
- const scopedTasks = inProjectScope(tasks, projectId, (task) => task.projectId);
5579
- const unparsedIds = new Set(inProjectScope(unparsedTasks2, projectId, (task) => task.projectId).map((task) => task.id));
5714
+ const scopedJournals = filterByProject(journals, projectId, (journal) => journal.projectId);
5715
+ const scopedTasks = filterByProject(tasks, projectId, (task) => task.projectId);
5716
+ const unparsedIds = new Set(filterByProject(unparsedTasks2, projectId, (task) => task.projectId).map((task) => task.id));
5580
5717
  const journalStart = smallest(scopedJournals.flatMap((journal) => journal.events.map((event) => Date.parse(event.at))));
5581
5718
  return {
5582
5719
  tasksWithEpics: scopedTasks,
@@ -5810,12 +5947,20 @@ function outcomeCounts(episodes) {
5810
5947
  // src/core/stats/signals/signals.ts
5811
5948
  var GROWTH_WEEKS = 3;
5812
5949
  var STUCK_AFTER_DAYS = { "in-progress": 7, blocked: 14 };
5950
+ var DONE_UNCLOSED_AFTER_DAYS = 1;
5813
5951
  var NOISY_MIN_DECIDED = 10;
5814
5952
  var NOISY_MAX_PERCENT = 20;
5815
5953
  var NOISY_WINDOW_DAYS = 14;
5816
5954
  function statsSignals(context) {
5817
5955
  const { now } = context.input;
5818
- return [...debtGrowing(weeklyFlow(context.histories, now)), ...urgentStale(urgentStaleCount(context.openTasks, now)), ...stuck(context), ...noisyChecks(context), ...staleLow(context)];
5956
+ return [
5957
+ ...debtGrowing(weeklyFlow(context.histories, now)),
5958
+ ...urgentStale(urgentStaleCount(context.openTasks, now)),
5959
+ ...stuck(context),
5960
+ ...doneUnclosed(context),
5961
+ ...noisyChecks(context),
5962
+ ...staleLow(context)
5963
+ ];
5819
5964
  }
5820
5965
  function debtGrowing(weeks) {
5821
5966
  const recent = weeks.slice(0, -1).slice(-GROWTH_WEEKS);
@@ -5833,6 +5978,16 @@ function stuck({ scope, tasks, input: { now } }) {
5833
5978
  if (longest === void 0) return [];
5834
5979
  return [{ kind: "stuck", params: { count: stuckTasks.length, id: longest.id, days: longest.days } }];
5835
5980
  }
5981
+ function doneUnclosed({ scope, tasks, input: { now } }) {
5982
+ const checklistDone = new Set(tasks.filter((task) => task.status === "in-progress" && isChecklistDone(task.body)).map((task) => task.id));
5983
+ const unclosed = inWorkTasks(tasks, scope.historiesWithEpics, now).filter((item) => checklistDone.has(item.id) && item.days >= DONE_UNCLOSED_AFTER_DAYS);
5984
+ const longest = unclosed[0];
5985
+ return longest === void 0 ? [] : [{ kind: "done-unclosed", params: { count: unclosed.length, id: longest.id } }];
5986
+ }
5987
+ function isChecklistDone(body) {
5988
+ const items = checklistItems(body);
5989
+ return items.length > 0 && items.every((item) => item.checked);
5990
+ }
5836
5991
  function staleLow({ scope, input: { now } }) {
5837
5992
  const stale = staleLowTasks(scope.tasksWithEpics, now);
5838
5993
  return stale.length === 0 ? [] : [{ kind: "stale-low", params: { days: STALE_LOW_DAYS, count: stale.length } }];
@@ -5855,11 +6010,6 @@ function measuredByClosing(evidence2) {
5855
6010
  return evidence2 !== "total" && isMeasuredEvidence(evidence2);
5856
6011
  }
5857
6012
 
5858
- // src/core/stats/signals/shown.ts
5859
- function signalsToShow(signals, shown, today) {
5860
- return signals.filter((signal3) => shown[signal3.kind] !== today);
5861
- }
5862
-
5863
6013
  // src/cli/agents/stop-event.ts
5864
6014
  import { createHash as createHash4 } from "node:crypto";
5865
6015
  import { z as z13 } from "zod";
@@ -5943,22 +6093,28 @@ var hookCommand = {
5943
6093
  };
5944
6094
  function namesStopEvent(args) {
5945
6095
  const { positionals } = parseArgs2({ args, options: HOOK_OPTIONS, allowPositionals: true, strict: false });
5946
- return positionals[0] === HOOK_STOP_EVENT;
6096
+ return isStopEvent(positionals);
6097
+ }
6098
+ function isStopEvent(positionals) {
6099
+ return positionals.length === 1 && positionals[0] === HOOK_STOP_EVENT;
5947
6100
  }
5948
6101
  async function runHook(args, io) {
5949
6102
  const { values, positionals } = parseCommandArgs(io.language, args, HOOK_OPTIONS);
5950
- if (positionals.length !== 1 || positionals[0] !== HOOK_STOP_EVENT) throw usageError(hookCommand, io.language);
6103
+ if (!isStopEvent(positionals)) throw usageError(hookCommand, io.language);
5951
6104
  const agent = values.agent === void 0 ? DEFAULT_AGENT : parseChoice(io.language, values.agent, AGENTS, io.cli.optionLabel.agent);
5952
6105
  const event = parseStopEvent(agent, await io.readStdin());
5953
6106
  if (event === null || event.skip) return EXIT.ok;
5954
6107
  const loaded = await loadBacklog(io.backlogRoot);
5955
- const project = findProjectForDir(loaded.projects, event.cwd, repoPlaces(io));
6108
+ const places = repoPlaces(io);
6109
+ const cwdRoots = readGitRoots(event.cwd, places.onUnreadable);
6110
+ const project = findProjectForDir(loaded.projects, event.cwd, cwdRoots, places);
5956
6111
  if (!project) return EXIT.ok;
5957
6112
  if (!await isFirstHookOfTurn(agent, event, io)) return EXIT.ok;
5958
- const { candidates } = await checkBacklog(io.backlogRoot, loaded, { projectIds: [project.id], mode: "changed", now: io.now(), home: io.home, messages: io.core, warn: io.warn, workingDir: event.cwd });
6113
+ 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) });
5959
6114
  const lowPriority = new Set(loaded.tasks.filter((task) => task.priority === "low").map((task) => task.id));
5960
- const worthTelling = candidates.filter((candidate) => !lowPriority.has(candidate.task.id));
5961
- const lowCount = candidates.length - worthTelling.length;
6115
+ const pinpointed = candidates.filter((candidate) => !(candidate.kind === "source-changed" && candidate.method === "file"));
6116
+ const worthTelling = pinpointed.filter((candidate) => !lowPriority.has(candidate.task.id));
6117
+ const lowCount = pinpointed.length - worthTelling.length;
5962
6118
  const session = await sessionMemory(project, event.session, io);
5963
6119
  const blocking = worthTelling.filter((candidate) => !session.told.has(candidate.task.id));
5964
6120
  const signals = carriesSystemMessage(agent) ? await freshSignals(
@@ -6200,7 +6356,7 @@ async function anchorOf2(project, source, io) {
6200
6356
  return sourceAnchor(await findRepo(project, lookup), source, lookup.onUnreadable);
6201
6357
  }
6202
6358
  function cwdBelongsTo(project, knownProjects, io) {
6203
- return findProjectForDir([...knownProjects, project], io.cwd, repoPlaces(io))?.id === project.id;
6359
+ return findProjectForCwd([...knownProjects, project], io)?.id === project.id;
6204
6360
  }
6205
6361
  async function allAfterSettling(work) {
6206
6362
  await Promise.allSettled(work);
@@ -6318,7 +6474,7 @@ async function runPrune(args, io) {
6318
6474
  // src/server/start.ts
6319
6475
  import { serve } from "@hono/node-server";
6320
6476
  import { mkdir as mkdir6, rm as rm4, writeFile as writeFile3 } from "node:fs/promises";
6321
- import { join as join31 } from "node:path";
6477
+ import { join as join32 } from "node:path";
6322
6478
 
6323
6479
  // src/server/app.ts
6324
6480
  import { serveStatic } from "@hono/node-server/serve-static";
@@ -6374,12 +6530,14 @@ var batchRequestSchema = z14.strictObject({
6374
6530
  // src/core/check/graph-health.ts
6375
6531
  async function projectGraphHealth(project, tasks, home2) {
6376
6532
  return graphHealth(
6377
- await findRepo(project, { home: home2, onUnreadable: unreadableRepoHasNoGraph }),
6533
+ await findRepo(project, { home: home2, onUnreadable: unreadableRepoHasNoGraph, workingRoots: null }),
6378
6534
  tasks.filter((task) => task.projectId === project.id)
6379
6535
  );
6380
6536
  }
6381
6537
  function unreadableRepoHasNoGraph() {
6382
6538
  }
6539
+ function unreadableSourceIsAbsent() {
6540
+ }
6383
6541
  function graphHealth(repo, tasks) {
6384
6542
  const pinned = tasks.filter((task) => isReviewable(task) && sourceRange(task.source) !== null);
6385
6543
  const unusable = (state) => ({ state, pinned: pinned.length, resolved: 0 });
@@ -6387,7 +6545,7 @@ function graphHealth(repo, tasks) {
6387
6545
  const graph = openCodeGraph(repo);
6388
6546
  if (graph === null) return unusable("unreadable");
6389
6547
  try {
6390
- const hashOf = fileHashes(repo);
6548
+ const hashOf = fileHashes(repo, unreadableSourceIsAbsent);
6391
6549
  const symbolAt = symbolLookup(graph, hashOf);
6392
6550
  const resolved = pinned.filter((task) => symbolOfSource(symbolAt, task.source) !== null).length;
6393
6551
  return { state: isStale(graph, pinned, hashOf) ? "stale" : "fresh", pinned: pinned.length, resolved };
@@ -6579,7 +6737,7 @@ function createJournalSources(root) {
6579
6737
  return { journal: projectJournal(projectId, lines), position: `${projectId}=${generation}:${length}` };
6580
6738
  };
6581
6739
  const rememberedContext = (snapshot, tailed) => (input) => {
6582
- const positions = inProjectScope(tailed, input.projectId, ({ journal }) => journal.projectId).map(({ position }) => position);
6740
+ const positions = filterByProject(tailed, input.projectId, ({ journal }) => journal.projectId).map(({ position }) => position);
6583
6741
  const key = `${snapshotIdOf(snapshot)}|${positions.join(",")}`;
6584
6742
  return { ...remembered2.get(key, () => scopedReportData(input), input.projectId), input };
6585
6743
  };
@@ -6623,6 +6781,7 @@ Backlog directory: ${root}`,
6623
6781
  deletedClosedTasks: (ids) => `Deleted closed tasks: ${ids}`,
6624
6782
  conflictedDuringSweep: (ids) => `Tasks changed during the sweep, will retry next time: ${ids}`,
6625
6783
  invalidAfterSweep: (detail) => `Could not update tasks, fix the files: ${detail}`,
6784
+ languageUnreadable: (detail) => `Could not read the language setting, messages follow the system language: ${detail}`,
6626
6785
  transcriptsScanFailed: (detail) => `Could not read Claude Code transcripts: ${detail}`,
6627
6786
  watcherError: (root, detail) => `Watcher for directory ${root}: ${detail}`,
6628
6787
  listenFailed: (reason) => `p-backlog failed to start: ${reason}`,
@@ -6659,6 +6818,7 @@ var serverRu = {
6659
6818
  deletedClosedTasks: (ids) => `\u0423\u0434\u0430\u043B\u0435\u043D\u044B \u0437\u0430\u043A\u0440\u044B\u0442\u044B\u0435 \u0437\u0430\u0434\u0430\u0447\u0438: ${ids}`,
6660
6819
  conflictedDuringSweep: (ids) => `\u0417\u0430\u0434\u0430\u0447\u0438 \u043C\u0435\u043D\u044F\u043B\u0438\u0441\u044C \u0432\u043E \u0432\u0440\u0435\u043C\u044F \u043F\u0440\u043E\u0445\u043E\u0434\u0430, \u043F\u043E\u0432\u0442\u043E\u0440\u044E \u043F\u0440\u0438 \u0441\u043B\u0435\u0434\u0443\u044E\u0449\u0435\u043C: ${ids}`,
6661
6820
  invalidAfterSweep: (detail) => `\u041D\u0435 \u0443\u0434\u0430\u043B\u043E\u0441\u044C \u043E\u0431\u043D\u043E\u0432\u0438\u0442\u044C \u0437\u0430\u0434\u0430\u0447\u0438, \u0438\u0441\u043F\u0440\u0430\u0432\u044C\u0442\u0435 \u0444\u0430\u0439\u043B\u044B: ${detail}`,
6821
+ languageUnreadable: (detail) => `\u041D\u0435 \u0443\u0434\u0430\u043B\u043E\u0441\u044C \u043F\u0440\u043E\u0447\u0438\u0442\u0430\u0442\u044C \u043D\u0430\u0441\u0442\u0440\u043E\u0439\u043A\u0443 \u044F\u0437\u044B\u043A\u0430, \u0441\u043E\u043E\u0431\u0449\u0435\u043D\u0438\u044F \u0438\u0434\u0443\u0442 \u043D\u0430 \u044F\u0437\u044B\u043A\u0435 \u0441\u0438\u0441\u0442\u0435\u043C\u044B: ${detail}`,
6662
6822
  transcriptsScanFailed: (detail) => `\u041D\u0435 \u0443\u0434\u0430\u043B\u043E\u0441\u044C \u043F\u0440\u043E\u0447\u0438\u0442\u0430\u0442\u044C \u0440\u0430\u0441\u0448\u0438\u0444\u0440\u043E\u0432\u043A\u0438 Claude Code: ${detail}`,
6663
6823
  watcherError: (root, detail) => `\u041D\u0430\u0431\u043B\u044E\u0434\u0430\u0442\u0435\u043B\u044C \u0437\u0430 \u043A\u0430\u0442\u0430\u043B\u043E\u0433\u043E\u043C ${root}: ${detail}`,
6664
6824
  listenFailed: (reason) => `p-backlog \u043D\u0435 \u0437\u0430\u043F\u0443\u0441\u0442\u0438\u043B\u0441\u044F: ${reason}`,
@@ -6704,7 +6864,7 @@ function createTtlCache({ ttlMs, now }) {
6704
6864
 
6705
6865
  // src/server/revisions.ts
6706
6866
  import { randomUUID as randomUUID3 } from "node:crypto";
6707
- import { readFile as readFile2, stat as stat3 } from "node:fs/promises";
6867
+ import { readFile as readFile2, stat as stat2 } from "node:fs/promises";
6708
6868
  function createRevisions() {
6709
6869
  const boot = randomUUID3();
6710
6870
  let seq = 0;
@@ -6736,7 +6896,7 @@ function createRevisions() {
6736
6896
  };
6737
6897
  }
6738
6898
  async function markOf(path) {
6739
- const [text, stats] = await Promise.all([readFile2(path, "utf8"), stat3(path)]);
6899
+ const [text, stats] = await Promise.all([readFile2(path, "utf8"), stat2(path)]);
6740
6900
  return { version: contentVersion(text), mtimeMs: stats.mtimeMs };
6741
6901
  }
6742
6902
  function markIfReadable(path) {
@@ -6756,12 +6916,19 @@ function tasksClosedInWeb(tasks, journals) {
6756
6916
 
6757
6917
  // src/server/snapshot-cache.ts
6758
6918
  function createSnapshotCache({ root, revisions, journalSources, warn: warn2 }) {
6759
- const snapshots = createScopeMemo();
6760
- let generation = 0;
6919
+ let snapshot = null;
6761
6920
  return {
6762
- read: () => snapshots.get(`${generation}`, () => loadSnapshot(root, revisions.current(), journalSources, warn2)),
6921
+ read: () => {
6922
+ if (snapshot !== null) return snapshot;
6923
+ const loading = loadSnapshot(root, revisions.current(), journalSources, warn2);
6924
+ snapshot = loading;
6925
+ loading.catch(() => {
6926
+ if (snapshot === loading) snapshot = null;
6927
+ });
6928
+ return loading;
6929
+ },
6763
6930
  forget: () => {
6764
- generation += 1;
6931
+ snapshot = null;
6765
6932
  }
6766
6933
  };
6767
6934
  }
@@ -7112,9 +7279,8 @@ function parseFixHeaders(output) {
7112
7279
  }
7113
7280
  async function landingDate(git, repo, { fix, paths, mainCommit }) {
7114
7281
  if (fix.full === mainCommit) return fix.date;
7115
- const descendants = await git(repo, ["log", "--first-parent", "--ancestry-path", `--format=tformat:%P${FIELD}%cI`, `${fix.full}..${mainCommit}`, "--"]);
7116
- const [parents = "", mergedAt = ""] = lastLine(descendants).split(FIELD);
7117
- if (mergedAt !== "") return parents.split(" ")[0] === fix.full ? fix.date : mergedAt;
7282
+ const landing = await firstParentLanding(git, repo, fix.full, mainCommit);
7283
+ if (landing !== null) return landing.firstParent === fix.full ? fix.date : landing.committedAt;
7118
7284
  if (fix.subject === "" || paths.length === 0) return void 0;
7119
7285
  const pathspecs = literalPathspecs(paths);
7120
7286
  const squashes = await git(repo, ["log", mainCommit, "--first-parent", `--since=${fix.date}`, "--extended-regexp", `--grep=${subjectLinePattern(fix.subject)}`, "--format=tformat:%cI", "--", ...pathspecs]);
@@ -7342,7 +7508,7 @@ function codeReport(context, code) {
7342
7508
  input: { now, projectId },
7343
7509
  openTasks
7344
7510
  } = context;
7345
- const projects = inProjectScope(code.projects, projectId, (project) => project.projectId);
7511
+ const projects = filterByProject(code.projects, projectId, (project) => project.projectId);
7346
7512
  return {
7347
7513
  ...context.head,
7348
7514
  periods: { churn: lastDays(now, CHURN_DAYS) },
@@ -7360,7 +7526,7 @@ function effectReport(context, code, wholeBacklog) {
7360
7526
  histories
7361
7527
  } = context;
7362
7528
  const statsWindow = statsPeriod(now);
7363
- const projects = inProjectScope(code.projects, projectId, (project) => project.projectId).filter((project) => project.repos.length > 0);
7529
+ const projects = filterByProject(code.projects, projectId, (project) => project.projectId).filter((project) => project.repos.length > 0);
7364
7530
  const deferredByAgent = createdIn(histories, statsWindow).filter((history) => history.found === "incidental");
7365
7531
  const deferred = buildDeferred(deferredByAgent, retainedFixes(histories, now), code);
7366
7532
  const estimate = estimator(estimateSamples(retainedFixes(wholeBacklog.histories, now), code));
@@ -7710,8 +7876,8 @@ var COST_TOTALS_DAYS = 7;
7710
7876
  function costReport({ buckets, runs, projectOf: projectOf2, projectId, now, scan }) {
7711
7877
  const projectByCwd = /* @__PURE__ */ new Map();
7712
7878
  const projectOfCwd = (cwd) => remembered(projectByCwd, cwd, () => projectOf2(cwd));
7713
- const scopedBuckets = inProjectScope(buckets, projectId, (bucket) => projectOfCwd(bucket.cwd));
7714
- const scopedRuns = inProjectScope(
7879
+ const scopedBuckets = filterByProject(buckets, projectId, (bucket) => projectOfCwd(bucket.cwd));
7880
+ const scopedRuns = filterByProject(
7715
7881
  runs.filter((run) => run.command !== SERVE_COMMAND_NAME),
7716
7882
  projectId,
7717
7883
  (run) => projectOfCwd(run.cwd)
@@ -8055,8 +8221,9 @@ async function readBody(c, schema, readLanguage) {
8055
8221
  async function readJson(c) {
8056
8222
  try {
8057
8223
  return { ok: true, value: await c.req.json() };
8058
- } catch {
8059
- return { ok: false };
8224
+ } catch (error) {
8225
+ if (error instanceof SyntaxError) return { ok: false };
8226
+ throw error;
8060
8227
  }
8061
8228
  }
8062
8229
 
@@ -8065,7 +8232,7 @@ import { bodyLimit } from "hono/body-limit";
8065
8232
  var REQUEST_BODY_LIMIT_MEBIBYTES = 1;
8066
8233
  var MUTATING_METHODS = /* @__PURE__ */ new Set(["POST", "PATCH", "PUT", "DELETE"]);
8067
8234
  function localHosts(port) {
8068
- return /* @__PURE__ */ new Set([`127.0.0.1:${port}`, `localhost:${port}`, `[::1]:${port}`]);
8235
+ return new Set(LOOPBACK_HOSTS.map((host) => `${host}:${port}`));
8069
8236
  }
8070
8237
  function allowLocalHostsOnly(allowedHosts, readLanguage) {
8071
8238
  return async (c, next) => {
@@ -8129,7 +8296,7 @@ function createApp({ root, readLanguage, changes, allowedHosts, home: home2, sta
8129
8296
  }
8130
8297
 
8131
8298
  // src/server/change-feed.ts
8132
- import { relative as relative4, sep as sep5 } from "node:path";
8299
+ import { join as join29, relative as relative4, sep as sep5 } from "node:path";
8133
8300
  import { watch } from "chokidar";
8134
8301
  var CHANGE_DEBOUNCE_MS = 100;
8135
8302
  function createDebouncer(delayMs, run) {
@@ -8145,6 +8312,12 @@ function createDebouncer(delayMs, run) {
8145
8312
  function isHiddenPath(root, path) {
8146
8313
  return relative4(root, path).split(sep5).some((segment) => segment.startsWith("."));
8147
8314
  }
8315
+ async function watchDirectoriesMissedAtStart(watcher, root) {
8316
+ const directories = (await listDir(root)).filter((entry) => entry.isDirectory()).map((entry) => join29(root, entry.name));
8317
+ const watched = watcher.getWatched();
8318
+ const missed = directories.filter((path) => !isHiddenPath(root, path) && !(path in watched));
8319
+ if (missed.length > 0 && !watcher.closed) watcher.add(missed);
8320
+ }
8148
8321
  function createChangeFeed({ root, debounceMs, warn: warn2 }) {
8149
8322
  const listeners = /* @__PURE__ */ new Set();
8150
8323
  const { promise: closed, resolve: markClosed } = Promise.withResolvers();
@@ -8160,10 +8333,15 @@ function createChangeFeed({ root, debounceMs, warn: warn2 }) {
8160
8333
  };
8161
8334
  const watcher = watch(root, { ignoreInitial: true, ignored: (path) => isHiddenPath(root, path) });
8162
8335
  watcher.on("all", (_event, path) => reportChange(path));
8163
- watcher.on("ready", () => reportChange(root));
8164
- watcher.on("error", (error) => {
8336
+ const warnWatcherError = (error) => {
8165
8337
  void warn2((messages) => messages.watcherError(root, errorText(error)));
8338
+ };
8339
+ watcher.on("ready", () => {
8340
+ void watchDirectoriesMissedAtStart(watcher, root).catch(warnWatcherError).finally(() => {
8341
+ if (!watcher.closed) reportChange(root);
8342
+ });
8166
8343
  });
8344
+ watcher.on("error", warnWatcherError);
8167
8345
  return {
8168
8346
  subscribe: (listener) => {
8169
8347
  listeners.add(listener);
@@ -8186,7 +8364,7 @@ function createMemorySampler({ intervalMs = MEMORY_SAMPLE_INTERVAL_MS, capacity
8186
8364
  let timer = null;
8187
8365
  const sample = () => {
8188
8366
  const usage = process.memoryUsage();
8189
- const point = { at: formatLocalIso(now()), rssMb: megabytesOf(usage.rss), heapUsedMb: megabytesOf(usage.heapUsed) };
8367
+ const point = { at: formatLocalIso(now()), rssMb: mebibytesOf(usage.rss), heapUsedMb: mebibytesOf(usage.heapUsed) };
8190
8368
  points = [...points, point].slice(-capacity);
8191
8369
  };
8192
8370
  return {
@@ -8203,12 +8381,6 @@ function createMemorySampler({ intervalMs = MEMORY_SAMPLE_INTERVAL_MS, capacity
8203
8381
  };
8204
8382
  }
8205
8383
 
8206
- // src/server/port.ts
8207
- function listenFailure(error, port, messages) {
8208
- const reason = error.code === "EADDRINUSE" ? messages.portBusy(port) : error.message;
8209
- return messages.listenFailed(reason);
8210
- }
8211
-
8212
8384
  // src/server/sweeper.ts
8213
8385
  function startSweeper({ maintain, intervalMs, log, warn: warn2, messages }) {
8214
8386
  let current = Promise.resolve();
@@ -8240,8 +8412,7 @@ import { isDeepStrictEqual } from "node:util";
8240
8412
 
8241
8413
  // src/core/usage/transcripts.ts
8242
8414
  import { createHash as createHash6 } from "node:crypto";
8243
- import { stat as stat4 } from "node:fs/promises";
8244
- import { basename as basename9, join as join30 } from "node:path";
8415
+ import { basename as basename9, join as join31 } from "node:path";
8245
8416
 
8246
8417
  // src/core/stats/cost/attribute.ts
8247
8418
  import { z as z17 } from "zod";
@@ -8609,7 +8780,7 @@ function slotOf(timestamp) {
8609
8780
 
8610
8781
  // src/core/usage/usage-cache.ts
8611
8782
  import { mkdir as mkdir5 } from "node:fs/promises";
8612
- import { join as join29 } from "node:path";
8783
+ import { join as join30 } from "node:path";
8613
8784
  import { z as z19 } from "zod";
8614
8785
 
8615
8786
  // src/core/stats/cost/usage-state.ts
@@ -8651,11 +8822,11 @@ function emptyUsageCache() {
8651
8822
  return { version: USAGE_CACHE_VERSION, files: {} };
8652
8823
  }
8653
8824
  async function readUsageCache(root) {
8654
- return await readJsonFile(join29(root, USAGE_CACHE_FILE), usageCacheSchema) ?? emptyUsageCache();
8825
+ return await readJsonFile(join30(root, USAGE_CACHE_FILE), usageCacheSchema) ?? emptyUsageCache();
8655
8826
  }
8656
8827
  async function writeUsageCache(root, cache) {
8657
8828
  await mkdir5(root, { recursive: true });
8658
- await writeFileAtomic(join29(root, USAGE_CACHE_FILE), JSON.stringify(cache));
8829
+ await writeFileAtomic(join30(root, USAGE_CACHE_FILE), JSON.stringify(cache));
8659
8830
  }
8660
8831
 
8661
8832
  // src/core/usage/transcripts.ts
@@ -8666,28 +8837,24 @@ async function listTranscripts(claudeProjectsDir2) {
8666
8837
  const files = [];
8667
8838
  for (const projectEntry of await listDir(claudeProjectsDir2)) {
8668
8839
  if (!projectEntry.isDirectory()) continue;
8669
- const projectDir2 = join30(claudeProjectsDir2, projectEntry.name);
8840
+ const projectDir2 = join31(claudeProjectsDir2, projectEntry.name);
8670
8841
  for (const entry of await listDir(projectDir2)) {
8671
- const entryPath = join30(projectDir2, entry.name);
8842
+ const entryPath = join31(projectDir2, entry.name);
8672
8843
  if (entry.isFile() && entry.name.endsWith(".jsonl")) {
8673
8844
  files.push(...await listedFile(entryPath));
8674
8845
  continue;
8675
8846
  }
8676
8847
  if (!entry.isDirectory()) continue;
8677
- for (const subagentEntry of await listDir(join30(entryPath, "subagents"), { recursive: true })) {
8678
- if (subagentEntry.isFile() && subagentEntry.name.endsWith(".jsonl")) files.push(...await listedFile(join30(subagentEntry.parentPath, subagentEntry.name)));
8848
+ for (const subagentEntry of await listDir(join31(entryPath, "subagents"), { recursive: true })) {
8849
+ if (subagentEntry.isFile() && subagentEntry.name.endsWith(".jsonl")) files.push(...await listedFile(join31(subagentEntry.parentPath, subagentEntry.name)));
8679
8850
  }
8680
8851
  }
8681
8852
  }
8682
8853
  return files;
8683
8854
  }
8684
8855
  async function listedFile(path) {
8685
- try {
8686
- const { size, mtimeMs } = await stat4(path);
8687
- return [{ path, size, mtimeMs }];
8688
- } catch {
8689
- return [];
8690
- }
8856
+ const stats = await statOrNull(path);
8857
+ return stats === null ? [] : [{ path, size: stats.size, mtimeMs: stats.mtimeMs }];
8691
8858
  }
8692
8859
  async function scanTranscripts({ files, cache, byteBudget, now }) {
8693
8860
  let remainingBudget = byteBudget;
@@ -8868,11 +9035,12 @@ function progressBefore(files, cache) {
8868
9035
  // src/server/start.ts
8869
9036
  var SWEEP_INTERVAL_MS = HOUR_MS;
8870
9037
  var STOP_SIGNALS = ["SIGTERM", "SIGINT", "SIGHUP"];
8871
- var BUNDLED_WEB_DIR = join31(import.meta.dirname, "web");
9038
+ var BUNDLED_WEB_DIR = join32(import.meta.dirname, "web");
8872
9039
  async function startServer({ root, port, home: home2, env, platform, log, warn: warn2, pidFile, staticDir, settledLanguage, now = () => /* @__PURE__ */ new Date() }) {
8873
9040
  await mkdir6(root, { recursive: true });
8874
9041
  const startupMessages = serverMessages(settledLanguage);
8875
- const readLanguage = () => readLanguageOrLocale(root, env);
9042
+ const onLanguageUnreadable = oncePerKey(errorText, (error) => warn2(startupMessages.languageUnreadable(errorText(error))));
9043
+ const readLanguage = () => readLanguageOrLocale(root, env, onLanguageUnreadable);
8876
9044
  const readMessages = () => readLanguage().then(serverMessages);
8877
9045
  const warnLocalized = localizedWarn(readLanguage, warn2);
8878
9046
  const usage = createUsageScanner({ root, claudeProjectsDir: claudeProjectsDir(env, home2), warn: warnLocalized, now });
@@ -8913,6 +9081,10 @@ function closeOnStopSignal(server) {
8913
9081
  for (const signal3 of STOP_SIGNALS) process.once(signal3, stop);
8914
9082
  });
8915
9083
  }
9084
+ function listenFailure(error, port, messages) {
9085
+ const reason = error.code === "EADDRINUSE" ? messages.portBusy(port) : error.message;
9086
+ return messages.listenFailed(reason);
9087
+ }
8916
9088
  function listen(app, port) {
8917
9089
  return new Promise((resolve7, reject) => {
8918
9090
  const server = serve({ fetch: app.fetch, hostname: LOOPBACK_HOST, port }, (info) => {
@@ -8974,7 +9146,7 @@ function isFailure(outcome) {
8974
9146
 
8975
9147
  // src/cli/service/launchd.ts
8976
9148
  import { mkdir as mkdir7, rm as rm5, writeFile as writeFile4 } from "node:fs/promises";
8977
- import { dirname as dirname9, join as join32 } from "node:path";
9149
+ import { dirname as dirname9, join as join33 } from "node:path";
8978
9150
  import { setTimeout as sleep3 } from "node:timers/promises";
8979
9151
 
8980
9152
  // src/cli/service/service.ts
@@ -9038,7 +9210,7 @@ ${entries}
9038
9210
  `;
9039
9211
  }
9040
9212
  function launchdManager(context, delay = sleep3) {
9041
- const file = join32(context.home, "Library/LaunchAgents", `${LABEL}.plist`);
9213
+ const file = join33(context.home, "Library/LaunchAgents", `${LABEL}.plist`);
9042
9214
  const domain = `gui/${context.uid}`;
9043
9215
  const bootout = () => context.exec("launchctl", ["bootout", `${domain}/${LABEL}`]);
9044
9216
  const bootstrap = () => context.exec("launchctl", ["bootstrap", domain, file]);
@@ -9073,7 +9245,7 @@ function launchdManager(context, delay = sleep3) {
9073
9245
 
9074
9246
  // src/cli/service/startup-folder.ts
9075
9247
  import { mkdir as mkdir8, rm as rm6, writeFile as writeFile5 } from "node:fs/promises";
9076
- import { dirname as dirname10, join as join33, win32 } from "node:path";
9248
+ import { dirname as dirname10, join as join34, win32 } from "node:path";
9077
9249
  var SCRIPT_NAME = "p-backlog.vbs";
9078
9250
  var COMMAND_LINE_ARGUMENT = /"[^"]*"|\S+/g;
9079
9251
  var PROCESS_QUERY_TIMEOUT_MS = 15e3;
@@ -9081,21 +9253,21 @@ function vbsString(value) {
9081
9253
  return `"${value.replaceAll('"', '""')}"`;
9082
9254
  }
9083
9255
  function appDataDir(site) {
9084
- return join33(site.env.LOCALAPPDATA ?? join33(site.home, "AppData", "Local"), "p-backlog");
9256
+ return join34(site.env.LOCALAPPDATA ?? join34(site.home, "AppData", "Local"), "p-backlog");
9085
9257
  }
9086
9258
  function startupFolder(site) {
9087
- return join33(site.env.APPDATA ?? join33(site.home, "AppData", "Roaming"), "Microsoft", "Windows", "Start Menu", "Programs", "Startup");
9259
+ return join34(site.env.APPDATA ?? join34(site.home, "AppData", "Roaming"), "Microsoft", "Windows", "Start Menu", "Programs", "Startup");
9088
9260
  }
9089
9261
  function logPath(site) {
9090
- return join33(appDataDir(site), "p-backlog.log");
9262
+ return join34(appDataDir(site), "p-backlog.log");
9091
9263
  }
9092
9264
  function pidFilePath(site) {
9093
- return join33(appDataDir(site), "server.pid");
9265
+ return join34(appDataDir(site), "server.pid");
9094
9266
  }
9095
9267
  var NODE_PATH_ENV = "P_BACKLOG_NODE";
9096
9268
  var CLI_PATH_ENV = "P_BACKLOG_CLI";
9097
9269
  var LOG_PATH_ENV = "P_BACKLOG_LOG";
9098
- var SERVE_COMMAND = `cmd /v:on /c ""!${NODE_PATH_ENV}!" "!${CLI_PATH_ENV}!" ${SERVE_COMMAND_NAME} >> "!${LOG_PATH_ENV}!" 2>&1"`;
9270
+ var SERVE_COMMAND_LINE = `cmd /v:on /c ""!${NODE_PATH_ENV}!" "!${CLI_PATH_ENV}!" ${SERVE_COMMAND_NAME} >> "!${LOG_PATH_ENV}!" 2>&1"`;
9099
9271
  function rotatedLogPath(site) {
9100
9272
  return `${logPath(site)}.old`;
9101
9273
  }
@@ -9127,7 +9299,7 @@ function startupScript(launch) {
9127
9299
  'Set env = shell.Environment("Process")',
9128
9300
  ...Object.entries(env).map(([key, value]) => `env(${vbsString(key)}) = ${vbsString(value)}`),
9129
9301
  ...logRotation(launch),
9130
- `shell.Run ${vbsString(SERVE_COMMAND)}, 0, False`,
9302
+ `shell.Run ${vbsString(SERVE_COMMAND_LINE)}, 0, False`,
9131
9303
  ""
9132
9304
  ].join("\r\n");
9133
9305
  }
@@ -9160,7 +9332,7 @@ function sameWindowsPath(left, right) {
9160
9332
  return win32.normalize(left).toLowerCase() === win32.normalize(right).toLowerCase();
9161
9333
  }
9162
9334
  function startupFolderManager(context) {
9163
- const file = join33(startupFolder(context), SCRIPT_NAME);
9335
+ const file = join34(startupFolder(context), SCRIPT_NAME);
9164
9336
  return {
9165
9337
  file,
9166
9338
  logsHint: logPath(context),
@@ -9187,7 +9359,7 @@ function startupFolderManager(context) {
9187
9359
 
9188
9360
  // src/cli/service/systemd.ts
9189
9361
  import { mkdir as mkdir9, rm as rm7, writeFile as writeFile6 } from "node:fs/promises";
9190
- import { dirname as dirname11, join as join34 } from "node:path";
9362
+ import { dirname as dirname11, join as join35 } from "node:path";
9191
9363
  var SERVICE_NAME = "p-backlog";
9192
9364
  var UNIT = `${SERVICE_NAME}.service`;
9193
9365
  function quoted(value) {
@@ -9222,7 +9394,7 @@ async function systemctlSteps(exec, steps) {
9222
9394
  return "done";
9223
9395
  }
9224
9396
  function systemdManager(context) {
9225
- const file = join34(context.home, ".config/systemd/user", UNIT);
9397
+ const file = join35(context.home, ".config/systemd/user", UNIT);
9226
9398
  return {
9227
9399
  file,
9228
9400
  logsHint: `journalctl --user -u ${SERVICE_NAME}`,
@@ -9263,7 +9435,7 @@ function serviceManagerOf(io) {
9263
9435
  return availableServiceManager(io.platform, serviceContextOf(io));
9264
9436
  }
9265
9437
  async function servicePort(manager, io) {
9266
- const installed = manager === null ? null : await readReportingFailure(manager.file, () => manager.installedPort(), warnPathErrors(io.warn, io.core.unreadableSkipped));
9438
+ const installed = manager === null ? null : await attemptReportingFailure(manager.file, () => manager.installedPort(), warnUnreadableSkipped(io.warn, io.core));
9267
9439
  return installed ?? envPort(io);
9268
9440
  }
9269
9441
  function webUiPort(io) {
@@ -9276,10 +9448,16 @@ async function serverResponds(origin, timeoutMs) {
9276
9448
  try {
9277
9449
  const response = await fetch(`${origin}${PROBE_PATH}`, { signal: AbortSignal.timeout(timeoutMs) });
9278
9450
  return response.ok;
9279
- } catch {
9280
- return false;
9451
+ } catch (error) {
9452
+ if (isUnreachable(error)) return false;
9453
+ throw error;
9281
9454
  }
9282
9455
  }
9456
+ function isUnreachable(fetchFailure) {
9457
+ const networkFailed = fetchFailure instanceof TypeError;
9458
+ const timedOut = fetchFailure instanceof DOMException && fetchFailure.name === "TimeoutError";
9459
+ return networkFailed || timedOut;
9460
+ }
9283
9461
 
9284
9462
  // src/cli/commands/service.ts
9285
9463
  var STATUS_TIMEOUT_MS = 1e3;
@@ -9348,8 +9526,9 @@ async function readJsonConfig(path, schema) {
9348
9526
  let value;
9349
9527
  try {
9350
9528
  value = JSON.parse(text);
9351
- } catch {
9352
- return { failed: "invalid" };
9529
+ } catch (error) {
9530
+ if (error instanceof SyntaxError) return { failed: "invalid" };
9531
+ throw error;
9353
9532
  }
9354
9533
  return schema.safeParse(value).success ? { config: value } : { failed: "invalid" };
9355
9534
  }
@@ -9357,8 +9536,7 @@ async function writeJsonConfig(path, config) {
9357
9536
  await mkdir10(dirname12(path), { recursive: true });
9358
9537
  const target = await writeTargetOf(path);
9359
9538
  const existing = await statOrNull(target);
9360
- await writeFileAtomic(target, `${JSON.stringify(config, null, 2)}
9361
- `, existing === null ? void 0 : existing.mode & 511);
9539
+ await writeFileAtomic(target, jsonFileText(config), existing === null ? void 0 : existing.mode & 511);
9362
9540
  }
9363
9541
  async function readConfigText(path) {
9364
9542
  try {
@@ -9578,7 +9756,7 @@ async function runSetup(args, io) {
9578
9756
  }
9579
9757
  function installedAgents(io) {
9580
9758
  let detection;
9581
- return () => detection ??= detectAgents(io, warnPathErrors(io.warn, io.core.unreadableSkipped));
9759
+ return () => detection ??= detectAgents(io, warnUnreadableSkipped(io.warn, io.core));
9582
9760
  }
9583
9761
  async function targetAgents(option, installed, io) {
9584
9762
  if (option !== void 0) return [parseChoice(io.language, option, AGENTS, io.cli.optionLabel.agent)];
@@ -9588,7 +9766,7 @@ async function targetAgents(option, installed, io) {
9588
9766
  }
9589
9767
  async function setUpAgent(agent, io) {
9590
9768
  const voice = agentVoice(agent, io);
9591
- const lookup = await agentPluginReportingFailure(agent, io, warnPathErrors(voice.warn, io.core.unreadableSkipped));
9769
+ const lookup = await agentPluginReportingFailure(agent, io, warnUnreadableSkipped(voice.warn, io.core));
9592
9770
  if (lookup === null) return false;
9593
9771
  if (lookup.plugin !== null) {
9594
9772
  voice.print(io.cli.pluginManages(lookup.plugin));
@@ -9626,7 +9804,7 @@ async function removeLegacySkillLinks(agent, io, voice) {
9626
9804
  return allSettled;
9627
9805
  }
9628
9806
  function unlinkReportingFailure(skillsDir, io, voice) {
9629
- return readReportingFailure(
9807
+ return attemptReportingFailure(
9630
9808
  skillLinkPath(skillsDir),
9631
9809
  () => unlinkOurSkill(skillsDir),
9632
9810
  (target, error) => voice.warn(io.cli.removeSkillLinkFailed(target, errorCodeOrText(error)))
@@ -9846,7 +10024,7 @@ async function runTake(args, io) {
9846
10024
  if (projectWithId || forceWithoutId) throw usageError(takeCommand, io.language);
9847
10025
  const loaded = await loadBacklog(io.backlogRoot);
9848
10026
  if (mode.kind === "path") return takeByPath(loaded, io, mode.path, values.project, { json: values.json });
9849
- const selected = mode.kind === "next" ? selectNext(loaded, io, values.project) : selectById(loaded, io, mode.id);
10027
+ const selected = mode.kind === "next" ? await selectNext(loaded, io, values.project) : selectById(loaded, io, mode.id);
9850
10028
  if (!selected.ok) return selected.exitCode;
9851
10029
  const refusal = takeRefusal(io, selected.task, buildIndex(loaded.tasks), { ignoreBlockers: values.force });
9852
10030
  if (refusal) {
@@ -9896,7 +10074,7 @@ function isOpenTaskAt(task, path) {
9896
10074
  return workable && task.source !== void 0 && (path === "" || isWithin(sourcePath(task.source), path));
9897
10075
  }
9898
10076
  function repoRelativePath(io, project, path) {
9899
- const roots = findGitRoots(io.cwd);
10077
+ const roots = cwdGitRoots(io);
9900
10078
  if (roots === null || findProjectForRoots([project], roots, repoPlaces(io)) === void 0) return sourcePath(path);
9901
10079
  return relativeInside(roots.worktree, resolve5(realpathSync3(io.cwd), sourcePath(path))) ?? sourcePath(path);
9902
10080
  }
@@ -9917,16 +10095,25 @@ function selectById(loaded, io, id) {
9917
10095
  const task = findTaskOrWarn(loaded, io, id);
9918
10096
  return task ? { ok: true, task } : { ok: false, exitCode: EXIT.notFound };
9919
10097
  }
9920
- function selectNext(loaded, io, projectId) {
10098
+ async function selectNext(loaded, io, projectId) {
9921
10099
  const project = findProjectOrWarn(loaded, io, projectId);
9922
10100
  if (!project) return { ok: false, exitCode: EXIT.notFound };
9923
10101
  const index = buildIndex(loaded.tasks);
10102
+ const abandoned = pickAbandonedTask(loaded.tasks, project.id, index, await lastTouched(loaded.tasks.filter(isTakenTask)), io.now());
10103
+ if (abandoned) {
10104
+ io.warn(io.cli.resumeAbandoned(abandoned.id));
10105
+ return { ok: true, task: abandoned };
10106
+ }
9924
10107
  const task = pickNextTask(loaded.tasks, project.id, index);
9925
10108
  if (task) return { ok: true, task };
9926
10109
  io.warn(io.cli.noTakeableInProject(project.id));
9927
10110
  const blocked = loaded.tasks.some((candidate) => candidate.projectId === project.id && isQueuedTask(candidate) && openBlockers(candidate, index).length > 0);
9928
10111
  return { ok: false, exitCode: blocked ? EXIT.refused : EXIT.notFound };
9929
10112
  }
10113
+ async function lastTouched(tasks) {
10114
+ const touches2 = await Promise.all(tasks.map(async (task) => [task.id, (await statOrNull(task.path))?.mtimeMs]));
10115
+ return new Map(touches2.flatMap(([id, mtimeMs]) => mtimeMs === void 0 ? [] : [[id, mtimeMs]]));
10116
+ }
9930
10117
  function takeRefusal(io, task, index, { ignoreBlockers }) {
9931
10118
  if (task.type === "epic") {
9932
10119
  const openChildren = epicChildren(task, index).filter((child) => !isClosed(child.status));
@@ -10063,7 +10250,8 @@ function commandName(argv2) {
10063
10250
 
10064
10251
  // src/cli/main.ts
10065
10252
  suppressSqliteExperimentalWarning();
10066
- var BYTES_PER_KILOBYTE = 1024;
10253
+ function alreadyReportedByRunCli() {
10254
+ }
10067
10255
  async function readStdin() {
10068
10256
  if (process.stdin.isTTY) return "";
10069
10257
  const chunks = [];
@@ -10087,9 +10275,8 @@ var exitCode = await runCli(argv, {
10087
10275
  stopProcess: (pid) => {
10088
10276
  try {
10089
10277
  process.kill(pid);
10090
- return true;
10091
- } catch {
10092
- return false;
10278
+ } catch (error) {
10279
+ if (!hasErrorCode(error, "ESRCH")) throw error;
10093
10280
  }
10094
10281
  },
10095
10282
  env: process.env,
@@ -10107,10 +10294,10 @@ if (command !== SERVE_COMMAND_NAME) {
10107
10294
  command,
10108
10295
  cwd: process.cwd(),
10109
10296
  ms: Math.round(performance.now()),
10110
- rssMb: megabytesOf(process.resourceUsage().maxRSS * BYTES_PER_KILOBYTE),
10297
+ rssMb: mebibytesOf(process.resourceUsage().maxRSS * BYTES_PER_KIBIBYTE),
10111
10298
  exitCode
10112
10299
  };
10113
- const language = await readLanguageOrLocale(backlogRoot, process.env);
10300
+ const language = await readLanguageOrLocale(backlogRoot, process.env, alreadyReportedByRunCli);
10114
10301
  await appendRun(backlogRoot, run).catch((error) => warn(cliMessages(language).runNotRecorded(errorText(error))));
10115
10302
  await tidyAfterCommand({ backlogRoot, command, language, now: /* @__PURE__ */ new Date(), warn });
10116
10303
  }