p-backlog 0.10.0 → 0.10.2

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 (42) hide show
  1. package/CHANGELOG.md +31 -0
  2. package/README.md +1 -1
  3. package/README.ru.md +1 -1
  4. package/dist/cli.js +485 -355
  5. package/dist/web/assets/CodeTab-V2SPooxh.js +1 -0
  6. package/dist/web/assets/CostTab-D4rugc-u.js +1 -0
  7. package/dist/web/assets/EffectTab-BCaZDgQu.js +1 -0
  8. package/dist/web/assets/Figure-CFYBcH57.js +1 -0
  9. package/dist/web/assets/Figure-CRSlcZF-.css +1 -0
  10. package/dist/web/assets/OverviewTab-kASqwnf1.js +1 -0
  11. package/dist/web/assets/Page-DI7Zd0Be.js +59 -0
  12. package/dist/web/assets/QualityTab-CplJleEW.js +1 -0
  13. package/dist/web/assets/ShareBar-BlEi1dd3.js +1 -0
  14. package/dist/web/assets/{StatsPage-Bmr75f8J.js → StatsPage-FwqJDfSs.js} +1 -1
  15. package/dist/web/assets/StatsTabState-BSoHN7Xc.js +1 -0
  16. package/dist/web/assets/StatsTabState-DZ3lMjjx.css +1 -0
  17. package/dist/web/assets/{StatsTable-D-PylWl7.js → StatsTable-BfRFy0MD.js} +1 -1
  18. package/dist/web/assets/UnavailableRepos-C5PoIyCp.js +1 -0
  19. package/dist/web/assets/index-DV2SbUU8.js +2 -0
  20. package/dist/web/assets/start-BOIixvFc.js +38 -0
  21. package/dist/web/assets/start-DPlw6J9o.css +1 -0
  22. package/dist/web/assets/use-grain-panel-1Qp5t-fC.js +55 -0
  23. package/dist/web/assets/{web-paths--TbmQ8rA.js → web-paths-CM_0PJMa.js} +1 -1
  24. package/dist/web/index.html +1 -1
  25. package/package.json +1 -1
  26. package/dist/web/assets/CodeTab-ClCaW8AS.js +0 -1
  27. package/dist/web/assets/CostTab-CtI3iFiW.js +0 -1
  28. package/dist/web/assets/EffectTab-DcvyEB2U.js +0 -1
  29. package/dist/web/assets/Figure-DkmKAO9C.css +0 -1
  30. package/dist/web/assets/Figure-DxKUx52i.js +0 -1
  31. package/dist/web/assets/OverviewTab-DE_6Z9ps.js +0 -1
  32. package/dist/web/assets/Page-buthlp0V.js +0 -59
  33. package/dist/web/assets/QualityTab-CkoKu4X0.js +0 -1
  34. package/dist/web/assets/ShareBar-BAS4lpze.js +0 -1
  35. package/dist/web/assets/StatsTabState-BacJCCdC.css +0 -1
  36. package/dist/web/assets/StatsTabState-D93FkgT5.js +0 -1
  37. package/dist/web/assets/UnavailableRepos-DyBVFVrQ.js +0 -1
  38. package/dist/web/assets/index-BFmeY_kk.js +0 -2
  39. package/dist/web/assets/start-CJ8zVmAB.js +0 -38
  40. package/dist/web/assets/start-CjkFx30s.css +0 -1
  41. package/dist/web/assets/summaries-D57lRSim.js +0 -1
  42. 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"],
@@ -1033,7 +1076,7 @@ function signal(s) {
1033
1076
  return `Stuck in progress: ${s.params.count}, longest ${s.params.id} \u2014 ${days(s.params.days)}`;
1034
1077
  case "noisy-check": {
1035
1078
  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]}`;
1079
+ const name = method === null ? `"${LABELS.evidence[evidence2]}"` : `"${LABELS.evidence[evidence2]}" ${LABELS.checkMethod[method]}`;
1037
1080
  return `Check ${name} is almost always wrong: precision ${percent2}% on ${decided} decided over ${count(windowDays, "day")}`;
1038
1081
  }
1039
1082
  case "low-changed":
@@ -1156,17 +1199,7 @@ var coreEn = {
1156
1199
  problem,
1157
1200
  problems,
1158
1201
  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],
1202
+ ...labelLookups(LABELS),
1170
1203
  count,
1171
1204
  days,
1172
1205
  p90,
@@ -1174,7 +1207,7 @@ var coreEn = {
1174
1207
  forecastTail,
1175
1208
  signal,
1176
1209
  epicDoneReason,
1177
- fileBusy: ({ path, lock, seconds }) => `${path} has been locked by another process for more than ${seconds} s (${lock})`,
1210
+ fileBusy: ({ path, lock, seconds }) => `${path} has been locked by another process for more than ${formatNumber("en", seconds)}${NBSP}s (${lock})`,
1178
1211
  checkFix,
1179
1212
  checkProblem,
1180
1213
  runsNotTrimmed: (error) => `Could not trim the run log: ${error}`,
@@ -1204,28 +1237,32 @@ var CATEGORY_LABELS2 = {
1204
1237
  bug: "\u041E\u0448\u0438\u0431\u043A\u0430"
1205
1238
  };
1206
1239
  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"
1240
+ var LABELS2 = {
1241
+ category: CATEGORY_LABELS2,
1242
+ noCategory: NO_CATEGORY_LABEL2,
1243
+ categoryRow: { ...CATEGORY_LABELS2, unset: NO_CATEGORY_LABEL2, unknown: "\u043D\u0435\u0438\u0437\u0432\u0435\u0441\u0442\u043D\u0430" },
1244
+ 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" },
1245
+ status: {
1246
+ backlog: "\u0432 \u0431\u0435\u043A\u043B\u043E\u0433\u0435",
1247
+ "in-progress": "\u0432 \u0440\u0430\u0431\u043E\u0442\u0435",
1248
+ blocked: "\u0437\u0430\u0431\u043B\u043E\u043A\u0438\u0440\u043E\u0432\u0430\u043D\u0430",
1249
+ done: "\u0441\u0434\u0435\u043B\u0430\u043D\u0430",
1250
+ cancelled: "\u043E\u0442\u043C\u0435\u043D\u0435\u043D\u0430"
1251
+ },
1252
+ type: { task: "\u0437\u0430\u0434\u0430\u0447\u0430", epic: "\u044D\u043F\u0438\u043A" },
1253
+ 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" },
1254
+ 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" },
1255
+ evidence: {
1256
+ "source-changed": "\u043A\u043E\u0434 \u0438\u0437\u043C\u0435\u043D\u0438\u043B\u0441\u044F",
1257
+ "source-missing": "\u0444\u0430\u0439\u043B \u043F\u0440\u043E\u043F\u0430\u043B",
1258
+ duplicate: "\u0434\u0443\u0431\u043B\u044C",
1259
+ "no-source": "\u043D\u0435\u0442 source",
1260
+ total: "\u0412\u0441\u0435\u0433\u043E"
1261
+ },
1262
+ 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" },
1263
+ 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" },
1264
+ 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
1265
  };
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
1266
  var COUNT_FORMS2 = {
1230
1267
  task: ["\u0437\u0430\u0434\u0430\u0447\u0430", "\u0437\u0430\u0434\u0430\u0447\u0438", "\u0437\u0430\u0434\u0430\u0447"],
1231
1268
  line: ["\u0441\u0442\u0440\u043E\u043A\u0430", "\u0441\u0442\u0440\u043E\u043A\u0438", "\u0441\u0442\u0440\u043E\u043A"],
@@ -1282,7 +1319,7 @@ function signal2(s) {
1282
1319
  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)}`;
1283
1320
  case "noisy-check": {
1284
1321
  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]}`;
1322
+ const name = method === null ? `\xAB${LABELS2.evidence[evidence2]}\xBB` : `\xAB${LABELS2.evidence[evidence2]}\xBB ${LABELS2.checkMethod[method]}`;
1286
1323
  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
1324
  }
1288
1325
  case "low-changed":
@@ -1405,17 +1442,7 @@ var coreRu = {
1405
1442
  problem: problem2,
1406
1443
  problems: problems2,
1407
1444
  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],
1445
+ ...labelLookups(LABELS2),
1419
1446
  count: count2,
1420
1447
  days: days2,
1421
1448
  p90: p902,
@@ -1423,7 +1450,7 @@ var coreRu = {
1423
1450
  forecastTail: forecastTail2,
1424
1451
  signal: signal2,
1425
1452
  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})`,
1453
+ 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
1454
  checkFix: checkFix2,
1428
1455
  checkProblem: checkProblem2,
1429
1456
  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 +1503,12 @@ function countBy(items, keyOf, amountOf = () => 1) {
1476
1503
  return totals2;
1477
1504
  }
1478
1505
 
1506
+ // src/core/journal/creation.ts
1507
+ function taskCreation(record, created) {
1508
+ if (record !== void 0) return { createdAt: Date.parse(record.created), type: record.type };
1509
+ return created === void 0 ? void 0 : { createdAt: Date.parse(created.at), type: created.type };
1510
+ }
1511
+
1479
1512
  // src/core/model/checklist.ts
1480
1513
  var ITEM = /^\s*[-*+]\s+\[(?<mark>[ xX])\]\s+(?<text>.*)$/;
1481
1514
  var FENCE = /^\s{0,3}(?<fence>`{3,}|~{3,})/;
@@ -1928,17 +1961,14 @@ function reportStartEvents(events, keepsHistory) {
1928
1961
  }
1929
1962
  function oldestTask(events) {
1930
1963
  const tasks = [...groupBy(events, (event) => event.task)].flatMap(([task, taskEvents]) => {
1931
- const creation = creationOf(taskEvents);
1964
+ const creation = taskCreation(
1965
+ taskEvents.find((event) => event.kind === "deleted")?.snapshot,
1966
+ taskEvents.findLast((event) => event.kind === "created")
1967
+ );
1932
1968
  return creation?.type === "task" ? [{ task, createdAt: creation.createdAt }] : [];
1933
1969
  });
1934
1970
  return tasks.reduce((oldest, candidate) => oldest === void 0 || candidate.createdAt < oldest.createdAt ? candidate : oldest, void 0)?.task;
1935
1971
  }
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
1972
  function earliestEvent(events) {
1943
1973
  return events.reduce((earliest, event) => earliest === void 0 || Date.parse(event.at) < Date.parse(earliest.at) ? event : earliest, void 0);
1944
1974
  }
@@ -1951,7 +1981,7 @@ function lastMomentByTask(events) {
1951
1981
  // src/core/service-log.ts
1952
1982
  import { posix } from "node:path";
1953
1983
  var SERVICE_LOG_LIMIT_BYTES = BYTES_PER_MEBIBYTE;
1954
- var SERVICE_LOG_KEPT_BYTES = 256 * 1024;
1984
+ var SERVICE_LOG_KEPT_BYTES = 256 * BYTES_PER_KIBIBYTE;
1955
1985
  function launchdLogPath(home2) {
1956
1986
  return posix.join(home2, "Library/Logs/p-backlog.log");
1957
1987
  }
@@ -1975,7 +2005,7 @@ async function trimOpenLog(handle, limitBytes, keptBytes) {
1975
2005
  // src/core/store/maintenance.ts
1976
2006
  async function runMaintenance(plan, { root, now, messages, warn: warn2 }) {
1977
2007
  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);
2008
+ const report = plan.sweepClosed === null ? null : await warnOnFailure(plan.sweepClosed(root, { now, onError: warnPathErrors(warn2) }, messages), warn2, messages.closedNotSwept);
1979
2009
  if (plan.compactJournals !== null) {
1980
2010
  const compactionFailed = (dir, error) => warn2(messages.journalNotCompacted(dir, errorText(error)));
1981
2011
  await warnOnFailure(plan.compactJournals(root, now, compactionFailed), warn2, (error) => messages.journalNotCompacted(root, error));
@@ -2274,14 +2304,14 @@ function nextOptional(current, change) {
2274
2304
 
2275
2305
  // src/core/store/sweep.ts
2276
2306
  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));
2307
+ function sweepClosedWhenDue(root, writes, messages) {
2308
+ return runWhenDue(join10(root, SWEPT_AT_FILE), writes.now, () => sweepClosed(root, writes, messages));
2279
2309
  }
2280
- function sweepClosedAndStamp(root, now, messages, onError) {
2281
- return runAndStamp(join10(root, SWEPT_AT_FILE), now, () => sweepClosed(root, now, messages, onError));
2310
+ function sweepClosedAndStamp(root, writes, messages) {
2311
+ return runAndStamp(join10(root, SWEPT_AT_FILE), writes.now, () => sweepClosed(root, writes, messages));
2282
2312
  }
2283
- async function sweepClosed(root, now, messages, onError) {
2284
- const writes = { now, onError };
2313
+ async function sweepClosed(root, writes, messages) {
2314
+ const { now } = writes;
2285
2315
  const initial = await loadBacklog(root);
2286
2316
  const reopening = await reopenEpicsWithOpenTasks(initial, writes);
2287
2317
  const epics = await closeCompletedEpics(initial, writes, messages);
@@ -2817,6 +2847,8 @@ import { parseArgs } from "node:util";
2817
2847
  var DEFAULT_PORT = 4317;
2818
2848
  var DECIMAL_DIGITS = /^\d+$/;
2819
2849
  var LOOPBACK_HOST = "127.0.0.1";
2850
+ var LOCALHOST = "localhost";
2851
+ var LOOPBACK_HOSTS = [LOOPBACK_HOST, LOCALHOST, "[::1]"];
2820
2852
  function portNumber(value) {
2821
2853
  if (!DECIMAL_DIGITS.test(value)) return null;
2822
2854
  const port = Number(value);
@@ -2829,7 +2861,7 @@ function loopbackOrigin(port) {
2829
2861
  return `http://${LOOPBACK_HOST}:${port}`;
2830
2862
  }
2831
2863
  function browserOrigin(port) {
2832
- return `http://localhost:${port}`;
2864
+ return `http://${LOCALHOST}:${port}`;
2833
2865
  }
2834
2866
 
2835
2867
  // src/cli/io.ts
@@ -2936,6 +2968,22 @@ async function createTask(root, request) {
2936
2968
  return invalid([{ code: "id-exhausted", attempts: MAX_ID_ATTEMPTS }]);
2937
2969
  }
2938
2970
  async function createProject(root, repoRoot, existingProjects) {
2971
+ for (let attempt = 1; ; attempt++) {
2972
+ const { id, path, text } = await draftProjectFile(root, repoRoot, existingProjects);
2973
+ try {
2974
+ await createFileAtomic(path, text);
2975
+ const parsed = parseProjectFile(text, { id, path });
2976
+ if (!parsed.ok) throw new Error(`${path}: ${parsed.problems.map((problem3) => problem3.code).join(", ")}`);
2977
+ return parsed.value;
2978
+ } catch (error) {
2979
+ if (!hasErrorCode(error, "EEXIST")) throw error;
2980
+ const concurrent = await projectOfRepo(id, path, repoRoot);
2981
+ if (concurrent !== null) return concurrent;
2982
+ if (attempt === MAX_ID_ATTEMPTS) throw error;
2983
+ }
2984
+ }
2985
+ }
2986
+ async function draftProjectFile(root, repoRoot, existingProjects) {
2939
2987
  const name = basename5(repoRoot);
2940
2988
  const entries = await listDir(root);
2941
2989
  const joinable = await Promise.all(entries.map((entry) => entry.isDirectory() && isJoinableProjectDir(join11(root, entry.name), repoRoot)));
@@ -2944,23 +2992,12 @@ async function createProject(root, repoRoot, existingProjects) {
2944
2992
  const prefix = derivePrefix(name, /* @__PURE__ */ new Set([...existingProjects.map((project) => project.prefix), ...prefixesOnDisk.flat()]));
2945
2993
  const dir = join11(root, id);
2946
2994
  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;
2995
+ return { id, path: join11(dir, PROJECT_FILE), text: serializeProject({ name, prefix, repos: [repoRoot], active: true, extra: {}, body: "" }) };
2959
2996
  }
2960
2997
  async function isJoinableProjectDir(dir, repoRoot) {
2961
- const path = join11(dir, PROJECT_FILE);
2962
- if (await readTextOrNull(path) !== null) return await projectOfRepo(basename5(dir), path, repoRoot) !== null;
2963
- return (await listDir(dir)).every((entry) => !entry.name.endsWith(".md"));
2998
+ const entries = await listDir(dir);
2999
+ if (entries.some((entry) => entry.name === PROJECT_FILE)) return await projectOfRepo(basename5(dir), join11(dir, PROJECT_FILE), repoRoot) !== null;
3000
+ return entries.every((entry) => !entry.name.endsWith(".md"));
2964
3001
  }
2965
3002
  async function projectOfRepo(id, path, repoRoot) {
2966
3003
  const parsed = await readProjectFile({ id, path });
@@ -3057,10 +3094,13 @@ var runGitOutcome = (repo, args, input) => gitProcessSlot(async () => {
3057
3094
  return typeof exitCode2 === "number" ? { status: "exited", exitCode: exitCode2, stderr: stderrOf(error) } : { status: "unfinished" };
3058
3095
  }
3059
3096
  });
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
- };
3097
+ function asGitRunner(git) {
3098
+ return async (repo, args, input) => {
3099
+ const outcome = await git(repo, args, input);
3100
+ return args[0] === "grep" && outcome.status === "exited" && outcome.exitCode === GREP_NO_MATCH_EXIT ? "" : stdoutOf(outcome);
3101
+ };
3102
+ }
3103
+ var runGit = asGitRunner(runGitOutcome);
3064
3104
  function stdoutOf(outcome) {
3065
3105
  return outcome.status === "ok" ? outcome.stdout : null;
3066
3106
  }
@@ -3068,18 +3108,28 @@ function outputLine(stdout) {
3068
3108
  const line = stdout?.trim();
3069
3109
  return line === void 0 || line === "" ? null : line;
3070
3110
  }
3111
+ function outputLines(stdout) {
3112
+ return stdout?.split("\n").filter((line) => line !== "") ?? null;
3113
+ }
3071
3114
  function literalPathspecs(paths) {
3072
3115
  return paths.map((path) => `:(literal)${path}`);
3073
3116
  }
3117
+ function topLiteralPathspecs(paths) {
3118
+ return paths.map((path) => `:(top,literal)${path}`);
3119
+ }
3074
3120
  function runGitSync(repo, args) {
3075
3121
  try {
3076
3122
  return execFileSync("git", gitArgs(repo, args), { encoding: "utf8", maxBuffer: GIT_OUTPUT_LIMIT, stdio: ["ignore", "pipe", "ignore"] });
3077
- } catch {
3078
- return null;
3123
+ } catch (error) {
3124
+ if (isChildProcessFailure(error)) return null;
3125
+ throw error;
3079
3126
  }
3080
3127
  }
3128
+ function isChildProcessFailure(error) {
3129
+ return typeof error === "object" && error !== null && "status" in error;
3130
+ }
3081
3131
  function gitArgs(repo, args) {
3082
- return ["-C", repo, "--no-optional-locks", "-c", "core.quotePath=false", ...args];
3132
+ return ["-C", repo, "--no-optional-locks", "-c", "core.quotePath=false", "-c", "diff.suppressBlankEmpty=false", ...args];
3083
3133
  }
3084
3134
  function resolveCommits(git, repo, revisions) {
3085
3135
  return resolveObjects(git, repo, revisions, "commit");
@@ -3128,7 +3178,7 @@ function cachedRepoRoots({ onUnreadable, ttlMs = REPO_ROOT_TTL_MS, now = Date.no
3128
3178
  const cached = known.get(dir);
3129
3179
  if (cached !== void 0 && isFresh(cached)) return cached.roots;
3130
3180
  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);
3181
+ const roots = attemptReportingFailure(dir, async (path) => await findGitRootsAsync(path) ?? plainDirRoots(path), onUnreadable);
3132
3182
  known.set(dir, { roots, checkedAt: now() });
3133
3183
  return roots;
3134
3184
  };
@@ -3157,8 +3207,15 @@ function canonicalRoots(worktreePath, mainPath) {
3157
3207
  const main = realpathOrNull(mainPath);
3158
3208
  return worktree === null || main === null ? null : { worktree, main };
3159
3209
  }
3160
- function findProjectForDir(projects, dir, places) {
3161
- const roots = readReportingFailureSync(dir, (path) => findGitRoots(path) ?? plainDirRoots(path), places.onUnreadable);
3210
+ function readGitRoots(dir, onUnreadable) {
3211
+ return attemptReportingFailureSync(dir, (path) => findGitRoots(path) ?? "not-in-repo", onUnreadable) ?? "unreadable";
3212
+ }
3213
+ function repoRootsOf(dirRoots) {
3214
+ return typeof dirRoots === "string" ? null : dirRoots;
3215
+ }
3216
+ function findProjectForDir(projects, dir, dirRoots, places) {
3217
+ if (dirRoots === "unreadable") return void 0;
3218
+ const roots = dirRoots === "not-in-repo" ? attemptReportingFailureSync(dir, plainDirRoots, places.onUnreadable) : dirRoots;
3162
3219
  return roots === null ? void 0 : findProjectForRoots(projects, roots, places);
3163
3220
  }
3164
3221
  function findProjectForRoots(projects, { worktree, main }, places) {
@@ -3175,7 +3232,7 @@ function isSameOrInside(path, container) {
3175
3232
  return relation === "" || !isAbsolute(relation) && relation.split(sep)[0] !== "..";
3176
3233
  }
3177
3234
  function resolvedRepo(repo, { home: home2, onUnreadable }) {
3178
- return readReportingFailureSync(expandHome(repo, home2), realpathOrNull, onUnreadable);
3235
+ return attemptReportingFailureSync(expandHome(repo, home2), realpathOrNull, onUnreadable);
3179
3236
  }
3180
3237
 
3181
3238
  // src/cli/path-inside.ts
@@ -3187,11 +3244,33 @@ function relativeInside(container, path) {
3187
3244
  }
3188
3245
 
3189
3246
  // src/cli/lookups.ts
3247
+ function warnUnreadableSkipped(warn2, core) {
3248
+ return warnPathErrors(warn2, core.unreadableSkipped);
3249
+ }
3250
+ var placesOfRun = /* @__PURE__ */ new WeakMap();
3190
3251
  function repoPlaces(io) {
3191
- return { home: io.home, onUnreadable: warnPathErrors(io.warn, io.core.unreadableSkipped) };
3252
+ const known = placesOfRun.get(io);
3253
+ if (known !== void 0) return known;
3254
+ const places = { home: io.home, onUnreadable: oncePerPath(warnUnreadableSkipped(io.warn, io.core)) };
3255
+ placesOfRun.set(io, places);
3256
+ return places;
3257
+ }
3258
+ var cwdRootsOfRun = /* @__PURE__ */ new WeakMap();
3259
+ function cwdDirRoots(io) {
3260
+ const known = cwdRootsOfRun.get(io);
3261
+ if (known !== void 0) return known;
3262
+ const roots = readGitRoots(io.cwd, repoPlaces(io).onUnreadable);
3263
+ cwdRootsOfRun.set(io, roots);
3264
+ return roots;
3265
+ }
3266
+ function cwdGitRoots(io) {
3267
+ return repoRootsOf(cwdDirRoots(io));
3268
+ }
3269
+ function findProjectForCwd(projects, io) {
3270
+ return findProjectForDir(projects, io.cwd, cwdDirRoots(io), repoPlaces(io));
3192
3271
  }
3193
3272
  function repoLookup(io) {
3194
- return { ...repoPlaces(io), workingDir: io.cwd };
3273
+ return { ...repoPlaces(io), workingRoots: cwdGitRoots(io) };
3195
3274
  }
3196
3275
  function findTaskOrWarn(loaded, io, id) {
3197
3276
  const task = loaded.tasks.find((candidate) => candidate.id === id);
@@ -3213,8 +3292,9 @@ async function ensureProject(loaded, io, explicitId) {
3213
3292
  if (explicitId !== void 0) return findProjectOrWarn(loaded, io, explicitId);
3214
3293
  const existing = findProject(loaded, io, void 0);
3215
3294
  if (existing) return existing;
3216
- const gitRoots = findGitRoots(io.cwd);
3217
- if (gitRoots === null) {
3295
+ const gitRoots = cwdDirRoots(io);
3296
+ if (gitRoots === "unreadable") return void 0;
3297
+ if (gitRoots === "not-in-repo") {
3218
3298
  io.warn(io.cli.notInGitRepo(io.cwd));
3219
3299
  return void 0;
3220
3300
  }
@@ -3251,7 +3331,7 @@ function homeRelative(path, home2) {
3251
3331
  return inside === null ? path : `~/${inside}`;
3252
3332
  }
3253
3333
  function findProject(loaded, io, explicitId) {
3254
- return explicitId === void 0 ? findProjectForDir(loaded.projects, io.cwd, repoPlaces(io)) : loaded.projects.find((project) => project.id === explicitId);
3334
+ return explicitId === void 0 ? findProjectForCwd(loaded.projects, io) : loaded.projects.find((project) => project.id === explicitId);
3255
3335
  }
3256
3336
 
3257
3337
  // src/cli/task-write.ts
@@ -3629,6 +3709,8 @@ var HUNK_HEADER = /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/;
3629
3709
  var OMITTED_COUNT = 1;
3630
3710
  var FILE_HEADER = "diff ";
3631
3711
  var EMPTY_OLD_SIDE = 0;
3712
+ var COMMIT_LINE = /^commit (?<commit>[0-9a-f]+)$/;
3713
+ var INDEX_LINE = /^index (?<preimage>[0-9a-f]+)\.\.(?<postimage>[0-9a-f]+)/;
3632
3714
  function hunkHeaderOf(line) {
3633
3715
  const header = HUNK_HEADER.exec(line);
3634
3716
  if (header === null) return null;
@@ -3674,6 +3756,42 @@ function hunkLineOf(line) {
3674
3756
  return null;
3675
3757
  }
3676
3758
  }
3759
+ function patchShapes(patches) {
3760
+ const shapes = /* @__PURE__ */ new Map();
3761
+ let shape = emptyShape();
3762
+ shapes.set("", shape);
3763
+ let hunk;
3764
+ for (const line of patches.split("\n")) {
3765
+ const commit = COMMIT_LINE.exec(line)?.groups?.commit;
3766
+ const header = hunkHeaderOf(line);
3767
+ if (commit !== void 0) {
3768
+ shape = emptyShape();
3769
+ shapes.set(commit, shape);
3770
+ hunk = void 0;
3771
+ } else if (line.startsWith(FILE_HEADER)) hunk = void 0;
3772
+ else if (header !== null) hunk = { oldLine: firstLineOf(header.oldStart, header.oldCount), changing: false };
3773
+ else if (hunk === void 0) shape.blobs ??= blobPairOf(line);
3774
+ else walkHunkLine(hunk, line, shape);
3775
+ }
3776
+ return (commit) => shapes.get(commit) ?? emptyShape();
3777
+ }
3778
+ function blobPairOf(line) {
3779
+ const blobs = INDEX_LINE.exec(line)?.groups;
3780
+ return blobs === void 0 ? void 0 : { preimage: blobs.preimage ?? "", postimage: blobs.postimage ?? "" };
3781
+ }
3782
+ function walkHunkLine(hunk, line, shape) {
3783
+ const hunkLine = hunkLineOf(line);
3784
+ if (hunkLine === null) return;
3785
+ const changed = hunkLine.kind !== "context";
3786
+ if (changed && !hunk.changing) shape.changeStarts.push(hunk.oldLine);
3787
+ if (changed) shape.changedText += `${line}
3788
+ `;
3789
+ hunk.changing = changed;
3790
+ if (hunkLine.kind !== "added") hunk.oldLine += 1;
3791
+ }
3792
+ function emptyShape() {
3793
+ return { blobs: void 0, changeStarts: [], changedText: "" };
3794
+ }
3677
3795
  function changedRanges(hunks) {
3678
3796
  const ranges = [];
3679
3797
  for (const hunk of hunks) {
@@ -3776,6 +3894,7 @@ var REFLOG_MOMENT = /\{(\d+)\}$/;
3776
3894
  var STATUS_CODE_WIDTH = 3;
3777
3895
  var RENAME_OR_COPY = /^[RC]/;
3778
3896
  var ORIGINAL_PATH_FOLLOWS = /^(?:[RC].|.[RC])/;
3897
+ var FACTS_HISTORY_OPTIONS = ["--full-history"];
3779
3898
  async function collectRepoFacts(repo, pathMarks) {
3780
3899
  const paths = [...pathMarks.keys()];
3781
3900
  const [location, files] = await Promise.all([runGitOutcome(repo, ["rev-parse", "--show-prefix", "--revs-only", "HEAD"]), sourceFiles(repo, paths)]);
@@ -3804,7 +3923,7 @@ function earliestMark(marks, paths) {
3804
3923
  return new Date(Math.min(...paths.flatMap((path) => marks.get(path) ?? [])));
3805
3924
  }
3806
3925
  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"];
3926
+ 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
3927
  }
3809
3928
  async function pathLog(repo, since, paths) {
3810
3929
  const inside = paths.filter(isInsideRepo);
@@ -3867,7 +3986,7 @@ async function sourceFiles(repo, paths) {
3867
3986
  const recordUnreadable = (path, error) => {
3868
3987
  unreadable.set(path, error);
3869
3988
  };
3870
- const read = await Promise.all(paths.map((path) => readReportingFailure(path, (relative5) => sourceFile(repo, relative5), recordUnreadable)));
3989
+ const read = await Promise.all(paths.map((path) => attemptReportingFailure(path, (relative5) => sourceFile(repo, relative5), recordUnreadable)));
3871
3990
  const present = read.flatMap((file) => file?.kind === "present" ? [file] : []);
3872
3991
  return {
3873
3992
  existing: new Set(present.map((file) => file.path)),
@@ -3999,7 +4118,7 @@ async function referenceOf(task, text, laterCommits, diffs) {
3999
4118
 
4000
4119
  // src/core/check/project-repo.ts
4001
4120
  async function sourceAnchor(repo, source, onUnreadable) {
4002
- const text = repo === void 0 ? null : await readReportingFailure(join13(repo, sourcePath(source)), readTextIfFile, onUnreadable);
4121
+ const text = repo === void 0 ? null : await attemptReportingFailure(join13(repo, sourcePath(source)), readTextIfFile, onUnreadable);
4003
4122
  if (text === null) return { kind: "no-file" };
4004
4123
  const anchor = anchorOf(text, source);
4005
4124
  return anchor === null ? { kind: "uncomputable" } : { kind: "anchor", anchor };
@@ -4008,8 +4127,8 @@ async function relocatedSource(repo, task) {
4008
4127
  const current = repo === void 0 ? null : await currentSourceIn(repo, task);
4009
4128
  return current === null || current === task.source ? void 0 : current;
4010
4129
  }
4011
- async function findRepo(project, { workingDir, ...lookup }) {
4012
- return (await projectCheckout(project, workingDir === void 0 ? null : findGitRoots(workingDir), lookup))?.path;
4130
+ async function findRepo(project, { workingRoots, ...lookup }) {
4131
+ return (await projectCheckout(project, workingRoots, lookup))?.path;
4013
4132
  }
4014
4133
  async function projectCheckout(project, workingRoots, lookup) {
4015
4134
  const repo = await firstExistingRepo(project, lookup);
@@ -4019,7 +4138,7 @@ async function projectCheckout(project, workingRoots, lookup) {
4019
4138
  }
4020
4139
  async function firstExistingRepo(project, { home: home2, onUnreadable }) {
4021
4140
  for (const repo of project.repos.map((path) => expandHome(path, home2))) {
4022
- if (await readReportingFailure(repo, fileExists, onUnreadable) === true) return repo;
4141
+ if (await attemptReportingFailure(repo, fileExists, onUnreadable) === true) return repo;
4023
4142
  }
4024
4143
  return void 0;
4025
4144
  }
@@ -4051,9 +4170,10 @@ function openCodeGraph(repo) {
4051
4170
  return null;
4052
4171
  }
4053
4172
  return codeGraph(db, root);
4054
- } catch {
4055
- closeQuietly(db);
4056
- return null;
4173
+ } catch (error) {
4174
+ closeIfOpen(db);
4175
+ if (isEnvironmentFailure(error)) return null;
4176
+ throw error;
4057
4177
  }
4058
4178
  }
4059
4179
  function readMetadata(db) {
@@ -4079,7 +4199,7 @@ function codeGraph(db, repo) {
4079
4199
  return row === void 0 ? null : { qualifiedName: row.qualified_name, kind: symbolKindOf(row.kind), from: row.line_start, to: row.line_end };
4080
4200
  },
4081
4201
  close() {
4082
- closeQuietly(db);
4202
+ closeIfOpen(db);
4083
4203
  }
4084
4204
  };
4085
4205
  }
@@ -4089,36 +4209,70 @@ function symbolKindOf(stored) {
4089
4209
  function ask(statement, run, fallback) {
4090
4210
  try {
4091
4211
  return run(statement);
4092
- } catch {
4093
- return fallback;
4212
+ } catch (error) {
4213
+ if (isEnvironmentFailure(error)) return fallback;
4214
+ throw error;
4094
4215
  }
4095
4216
  }
4096
- function closeQuietly(db) {
4217
+ function isEnvironmentFailure(error) {
4218
+ return typeof errorCode(error) === "string";
4219
+ }
4220
+ function closeIfOpen(db) {
4097
4221
  try {
4098
4222
  db?.close();
4099
- } catch {
4100
- return;
4223
+ } catch (error) {
4224
+ if (!hasErrorCode(error, "ERR_INVALID_STATE")) throw error;
4225
+ }
4226
+ }
4227
+
4228
+ // src/core/git/landing.ts
4229
+ async function firstParentLanding(git, repo, commit, head) {
4230
+ const chain = await firstParentChain(git, repo, commit, head);
4231
+ if (chain === null || chain.length === 0) return null;
4232
+ const carries = (index) => contains(git, repo, chain[index]?.commit ?? "", commit);
4233
+ const oldest = chain.length - 1;
4234
+ const oldestCarries = await carries(oldest);
4235
+ if (oldestCarries === null) return null;
4236
+ if (oldestCarries) return chain[oldest] ?? null;
4237
+ if (await carries(0) !== true) return null;
4238
+ let carrying = 0;
4239
+ let notCarrying = oldest;
4240
+ while (notCarrying - carrying > 1) {
4241
+ const middle = Math.floor((carrying + notCarrying) / 2);
4242
+ const middleCarries = await carries(middle);
4243
+ if (middleCarries === null) return null;
4244
+ if (middleCarries) carrying = middle;
4245
+ else notCarrying = middle;
4101
4246
  }
4247
+ return chain[carrying] ?? null;
4248
+ }
4249
+ async function firstParentChain(git, repo, commit, head) {
4250
+ const lines = outputLines(await git(repo, ["log", "--first-parent", `--format=tformat:%H${FIELD}%P${FIELD}%cI`, `${commit}..${head}`, "--"]));
4251
+ if (lines === null) return null;
4252
+ return lines.map((line) => {
4253
+ const [sha = "", parents = "", committedAt = ""] = line.split(FIELD);
4254
+ return { commit: sha, firstParent: parents.split(" ")[0] ?? "", committedAt };
4255
+ });
4256
+ }
4257
+ async function contains(git, repo, descendant, commit) {
4258
+ const missing = await git(repo, ["rev-list", "--max-count=1", commit, `^${descendant}`, "--"]);
4259
+ return missing === null ? null : missing.trim() === "";
4102
4260
  }
4103
4261
 
4104
4262
  // src/core/check/landed-content.ts
4105
4263
  var PATCH_OPTIONS = ["-p", "--no-color", "--no-ext-diff", "--no-textconv", "--no-renames", "--no-relative", "--full-index", "--diff-algorithm=myers", "--indent-heuristic"];
4106
4264
  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
4265
  var TREE_PAIR_LINE = /^[0-9a-f]+ [0-9a-f]+$/;
4110
4266
  var NO_COMMIT = /^0+$/;
4111
- var NO_NEWLINE_MARK = "\\";
4112
4267
  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
4268
  async function contentLanded(repo, tip, git) {
4114
4269
  const fork = await forkAt(repo, "HEAD", tip, git);
4115
4270
  if (fork === null) return false;
4116
- const view = { ...fork, repo, history: "simplified", git };
4271
+ const view = { ...fork, repo, historyOptions: [], git };
4117
4272
  const changed = await branchChanges(view, []);
4118
4273
  if (changed === null) return false;
4119
4274
  if (changed.length === 0) return true;
4120
- const pathspecs = changed.map(({ path }) => pathspecOf(path));
4121
- const landed = await headChanges(view, pathspecs);
4275
+ const landed = await headChanges(view, topLiteralPathspecs(changed.map(({ path }) => path)));
4122
4276
  if (landed === null) return false;
4123
4277
  const landedVersions = new Set(landed.map(({ version }) => version));
4124
4278
  for (const { path, version } of changed) {
@@ -4126,11 +4280,11 @@ async function contentLanded(repo, tip, git) {
4126
4280
  }
4127
4281
  return true;
4128
4282
  }
4129
- function commitsCarryingContent(repo, git) {
4283
+ function commitsCarryingContent(repo, git, historyOptions) {
4130
4284
  const forks = /* @__PURE__ */ new Map();
4131
4285
  return async (tip, scope) => {
4132
4286
  const fork = await remembered(forks, tip, () => forkBeforeLanding(repo, tip, git));
4133
- return fork === null ? [] : commitsCarrying({ ...fork, repo, history: "full", git }, scope);
4287
+ return fork === null ? [] : commitsCarrying({ ...fork, repo, historyOptions, git }, scope);
4134
4288
  };
4135
4289
  }
4136
4290
  async function commitsCarrying(view, scope) {
@@ -4157,21 +4311,8 @@ async function forkAt(repo, head, tip, git) {
4157
4311
  async function forkBeforeLanding(repo, tip, git) {
4158
4312
  const fork = await forkAt(repo, "HEAD", tip, git);
4159
4313
  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;
4314
+ const landing = await firstParentLanding(git, repo, tip, "HEAD");
4315
+ return landing === null ? fork : forkAt(repo, landing.firstParent, tip, git);
4175
4316
  }
4176
4317
  function tipInHead({ base, tip }) {
4177
4318
  return base.startsWith(tip);
@@ -4182,16 +4323,13 @@ async function branchChanges(view, pathspecs) {
4182
4323
  const changed = await git(repo, ["diff-tree", "-r", "-z", "--no-renames", base, tip, "--", ...pathspecs]);
4183
4324
  return changed === null ? null : rawChanges(changed);
4184
4325
  }
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}
4326
+ async function headChanges({ repo, base, head, historyOptions, git }, pathspecs) {
4327
+ const rawLog = await git(repo, ["log", "--stdin", COMMIT_HEADER, "--raw", "-z", "--no-renames", "--no-abbrev", "--no-relative", ...historyOptions], `${base}..${head}
4187
4328
  --
4188
4329
  ${pathspecs.join("\n")}
4189
4330
  `);
4190
4331
  return rawLog === null ? null : rawChanges(rawLog);
4191
4332
  }
4192
- function historyOptions(history) {
4193
- return history === "full" ? ["--full-history"] : [];
4194
- }
4195
4333
  function rawChanges(raw) {
4196
4334
  const changes = [];
4197
4335
  let commit = "";
@@ -4213,12 +4351,12 @@ function earliestCopies(copies) {
4213
4351
  return [earliest(copies.squashed), ...everyCommitCopied(copies) ? copies.commitByCommit.map(earliest) : []].flat();
4214
4352
  }
4215
4353
  async function patchCopies(view, path) {
4216
- const { repo, base, tip, head, history, git } = view;
4217
- const onlyPath = ["--", pathspecOf(path)];
4354
+ const { repo, base, tip, head, historyOptions, git } = view;
4355
+ const onlyPath = ["--", ...topLiteralPathspecs([path])];
4218
4356
  const [squashedPatch, branchPatches, headPatches] = await Promise.all([
4219
4357
  patchesOf(repo, ["diff", ...PATCH_OPTIONS, base, tip, ...onlyPath], () => base, git),
4220
4358
  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)
4359
+ patchesOf(repo, ["log", ...PATCH_OPTIONS, COMMIT_HEADER, "--date-order", ...historyOptions, `${base}..${head}`, ...onlyPath], parentOf, git)
4222
4360
  ]);
4223
4361
  if (squashedPatch === null || branchPatches === null || headPatches === null) return null;
4224
4362
  const headPatchesById = groupBy(headPatches, ({ id }) => id);
@@ -4233,50 +4371,13 @@ async function patchesOf(repo, patchArgs, preimageOf, git) {
4233
4371
  if (patches === null) return null;
4234
4372
  const ids = await git(repo, ["patch-id", "--stable"], patches);
4235
4373
  if (ids === null) return null;
4236
- const shapes = patchShapesByCommit(patches);
4374
+ const shapeOf = patchShapes(patches);
4237
4375
  return ids.split("\n").filter((line) => line !== "").map((line) => {
4238
4376
  const [id = "", label = ""] = line.split(" ");
4239
4377
  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 };
4378
+ return { id, commit, preimageRevision: preimageOf(commit), ...shapeOf(commit) };
4242
4379
  });
4243
4380
  }
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
4381
  async function preimageShifts(repoGit, path, pairs) {
4281
4382
  const shifted = pairs.filter(([change, copy]) => shiftsNeeded(change, copy));
4282
4383
  const trees = await resolveTrees(repoGit.git, repoGit.repo, [...new Set(shifted.flatMap(([change, copy]) => [change.preimageRevision, copy.preimageRevision]))]);
@@ -4294,8 +4395,12 @@ async function preimageShifts(repoGit, path, pairs) {
4294
4395
  }
4295
4396
  async function treeDiffShifts({ repo, git }, path, treePairs) {
4296
4397
  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(""));
4398
+ const preimageDiffs = await git(
4399
+ repo,
4400
+ ["diff-tree", "--stdin", ...PATCH_OPTIONS, "--unified=0", "--inter-hunk-context=0", "--", ...topLiteralPathspecs([path])],
4401
+ treePairs.map((treePair) => `${treePair}
4402
+ `).join("")
4403
+ );
4299
4404
  return preimageDiffs === null ? /* @__PURE__ */ new Map() : lineShiftsByTreePair(preimageDiffs);
4300
4405
  }
4301
4406
  function lineShiftsByTreePair(preimageDiffs) {
@@ -4335,9 +4440,6 @@ function shiftedLine(line, shifts) {
4335
4440
  function parentOf(commit) {
4336
4441
  return `${commit}^`;
4337
4442
  }
4338
- function pathspecOf(path) {
4339
- return `:(top,literal)${path}`;
4340
- }
4341
4443
  function fileVersion({ mode = "", object = "", path = "" } = {}) {
4342
4444
  return { path, version: `${mode} ${object}\0${path}` };
4343
4445
  }
@@ -4352,11 +4454,12 @@ async function commitsKnownAtCreation({ repo, tasks, facts, anchors, origins, gi
4352
4454
  return [{ taskId: task.id, creation: origin.commit, path, changes: commitsTouchingSince(facts.commits, path, reviewMark(task)) }];
4353
4455
  });
4354
4456
  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);
4457
+ const commitsBroughtBy = (merge, creation, path) => remembered(
4458
+ branchCommitsByMerge,
4459
+ `${merge.sha} ${creation} ${path}`,
4460
+ async () => outputLines(await git(repo, ["rev-list", `${merge.sha}^2`, `^${merge.sha}^1`, `^${creation}`, "--", ...literalPathspecs([path])]))
4461
+ );
4462
+ const carryingContent = commitsCarryingContent(repo, git, FACTS_HISTORY_OPTIONS);
4360
4463
  const copyAnswers = /* @__PURE__ */ new Map();
4361
4464
  const copiesOfCreation = (creation, path) => remembered(copyAnswers, `${creation} ${path}`, () => carryingContent(creation, literalPathspecs([path])));
4362
4465
  const isCopy = (copies, sha) => copies.some((fullSha) => fullSha.startsWith(sha));
@@ -4564,7 +4667,7 @@ async function awaitingMerge({ repo, taskIds, origins, git = runGitOutcome }) {
4564
4667
  }
4565
4668
  async function branchAwaitsMerge(repo, branch, git) {
4566
4669
  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)));
4670
+ return tip !== null && !await contentLanded(repo, tip, asGitRunner(git));
4568
4671
  }
4569
4672
  function lineOf(outcome) {
4570
4673
  return outputLine(stdoutOf(outcome));
@@ -4572,11 +4675,10 @@ function lineOf(outcome) {
4572
4675
 
4573
4676
  // src/core/check/symbol-filter.ts
4574
4677
  import { createHash as createHash3 } from "node:crypto";
4575
- import { readFileSync } from "node:fs";
4576
4678
  import { join as join15 } from "node:path";
4577
- function fileHashes(repo) {
4679
+ function fileHashes(repo, onUnreadable) {
4578
4680
  const hashes = /* @__PURE__ */ new Map();
4579
- return (path) => remembered(hashes, path, () => fileHash(join15(repo, path)));
4681
+ return (path) => remembered(hashes, path, () => fileHash(join15(repo, path), onUnreadable));
4580
4682
  }
4581
4683
  function symbolLookup(graph, hashOf) {
4582
4684
  if (graph === null) return () => null;
@@ -4624,12 +4726,9 @@ function shortName(qualifiedName) {
4624
4726
  function watchedRange(symbol, declared) {
4625
4727
  return { from: Math.min(symbol.from, declared.from), to: Math.max(symbol.to, declared.to) };
4626
4728
  }
4627
- function fileHash(path) {
4628
- try {
4629
- return createHash3("sha256").update(readFileSync(path)).digest("hex");
4630
- } catch {
4631
- return null;
4632
- }
4729
+ function fileHash(path, onUnreadable) {
4730
+ const bytes = attemptReportingFailureSync(path, readBytesOrNullSync, onUnreadable);
4731
+ return bytes === null ? null : createHash3("sha256").update(bytes).digest("hex");
4633
4732
  }
4634
4733
  function overlaps(range, watched) {
4635
4734
  return range.from <= watched.to && range.to >= watched.from;
@@ -4657,7 +4756,7 @@ async function projectReview(project, allTasks, { repo, origins, mode, onUnreada
4657
4756
  const review = await reviewedCode(readable, scope);
4658
4757
  const graph = openCodeGraph(repo);
4659
4758
  try {
4660
- const context = await projectContext(readable, review, { repo, facts, graph, mode });
4759
+ const context = await projectContext(readable, review, { repo, facts, graph, mode, onUnreadable });
4661
4760
  const sighted = await sightedBySymbol(tasks, review, context, { mode, skipped });
4662
4761
  const judged = await judgedAgainstMerges(sighted, context, scope);
4663
4762
  return { projectId: project.id, ...judged, skipped: [...skipped], problems: historyProblems(project, repo, facts.history), unchecked: facts.history === "read" ? [] : ["source-changed"] };
@@ -4671,9 +4770,9 @@ async function reviewedCode(tasks, scope) {
4671
4770
  const knownCommits = await commitsKnownAtCreation({ repo, tasks, facts, anchors, origins });
4672
4771
  return withRenamesFollowed(codeReview(tasks, facts, knownCommits, anchors), tasks, scope);
4673
4772
  }
4674
- async function projectContext(tasks, review, { repo, facts, graph, mode }) {
4773
+ async function projectContext(tasks, review, { repo, facts, graph, mode, onUnreadable }) {
4675
4774
  const diffs = repoDiffs(repo);
4676
- const symbolAt = symbolLookup(graph, fileHashes(repo));
4775
+ const symbolAt = symbolLookup(graph, fileHashes(repo, onUnreadable));
4677
4776
  const changedIds = new Set(review.candidates.flatMap((candidate) => candidate.kind === "source-changed" ? [candidate.task.id] : []));
4678
4777
  const locating = mode === "full" && graph !== null ? tasks : tasks.filter((task) => changedIds.has(task.id));
4679
4778
  const traces = await traceSources(locating, facts, diffs);
@@ -4716,7 +4815,7 @@ async function withRenamesFollowed(review, tasks, { repo, onUnreadable }) {
4716
4815
  review.candidates.map(async (candidate) => {
4717
4816
  const task = tasksById.get(candidate.task.id);
4718
4817
  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);
4818
+ const text = await attemptReportingFailure(join16(repo, candidate.renamedTo), readTextIfFile, onUnreadable);
4720
4819
  return text === null ? null : renamePlan(task, candidate.renamedTo, text);
4721
4820
  })
4722
4821
  );
@@ -4802,13 +4901,11 @@ async function checkBacklog(root, loaded, request) {
4802
4901
  return { fixed: [...fixes.fixed, ...anchors.fixed], problems: problems3, candidates: outcome.candidates };
4803
4902
  }
4804
4903
  async function reviewProjects(root, tasks, projects, request) {
4805
- const workingRoots = request.workingDir === void 0 ? null : findGitRoots(request.workingDir);
4806
4904
  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
4905
  return Promise.all(
4809
4906
  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 };
4907
+ const checkout = await projectCheckout(project, request.workingRoots, request.places);
4908
+ return { review: await projectReview(project, tasks, { repo: checkout?.path, origins: await originsOf(project.id), mode: request.mode, onUnreadable: request.places.onUnreadable }), checkout };
4812
4909
  })
4813
4910
  );
4814
4911
  }
@@ -4890,7 +4987,6 @@ var ID_COLUMN_WIDTH = 10;
4890
4987
  var STATUS_COLUMN_WIDTH = Math.max(...TASK_STATUSES.map((status) => status.length));
4891
4988
  var PRIORITY_COLUMN_WIDTH = Math.max(...PRIORITIES.map((priority) => priority.length));
4892
4989
  var PROGRESS_COLUMN_WIDTH = "100%".length;
4893
- var JSON_INDENT = 2;
4894
4990
  function formatJson(value) {
4895
4991
  return JSON.stringify(value, null, JSON_INDENT);
4896
4992
  }
@@ -4974,7 +5070,15 @@ async function runCheck(args, io) {
4974
5070
  const scope = resolveScope(loaded, io, values);
4975
5071
  if (scope === null) return EXIT.notFound;
4976
5072
  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 });
5073
+ const report = await checkBacklog(io.backlogRoot, loaded, {
5074
+ projectIds,
5075
+ mode: values.changed ? "changed" : "full",
5076
+ now: io.now(),
5077
+ places: repoPlaces(io),
5078
+ messages: io.core,
5079
+ warn: io.warn,
5080
+ workingRoots: cwdGitRoots(io)
5081
+ });
4978
5082
  io.print(values.json ? formatJson(report) : formatReport(io.cli, io.core, report));
4979
5083
  return needsReview(report) ? EXIT.needsReview : EXIT.ok;
4980
5084
  }
@@ -5079,21 +5183,20 @@ function reopeningsOf(history) {
5079
5183
  return history.transitions.filter((transition) => transition.from !== void 0 && isClosed(transition.from) && !isClosed(transition.to));
5080
5184
  }
5081
5185
  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 [];
5186
+ const creation = taskCreation(final, created);
5187
+ if (creation === void 0) return [];
5085
5188
  const ordered = withoutUndoneClosings(chronological(transitions));
5086
5189
  const fateUnknown = final === void 0 && unparsed;
5087
5190
  return [
5088
5191
  {
5089
5192
  id,
5090
5193
  projectId,
5091
- type,
5092
- createdAt: Date.parse(createdIso),
5194
+ type: creation.type,
5195
+ createdAt: creation.createdAt,
5093
5196
  source: final?.source ?? created?.source,
5094
5197
  reason: final?.reason,
5095
5198
  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))]),
5199
+ transitions: fateUnknown ? ordered : withResolutionOf(final, [...ordered, ...restoredTransitions(final, ordered, creation.createdAt)]),
5097
5200
  priority: final?.priority ?? chronological(priorityEvents).at(-1)?.to ?? created?.priority,
5098
5201
  category: categoryOf(final, created, categoryEvents),
5099
5202
  found: created?.found,
@@ -5299,7 +5402,7 @@ async function detectAgents(places, onUnreadable) {
5299
5402
  for (const agent of AGENTS) {
5300
5403
  const spec = AGENT_SPECS[agent];
5301
5404
  const dir = spec.homeDir(places);
5302
- const present = spec.alwaysInstalled || await readReportingFailure(dir, isDirectory, onUnreadable);
5405
+ const present = spec.alwaysInstalled || await attemptReportingFailure(dir, isDirectory, onUnreadable);
5303
5406
  if (present === true) detection.found.push(agent);
5304
5407
  else if (present === false) detection.missing.push({ agent, dir });
5305
5408
  }
@@ -5389,7 +5492,7 @@ var enabledPluginsSchema = z9.object({ enabledPlugins: z9.record(z9.string(), z9
5389
5492
  async function agentPluginReportingFailure(agent, places, onUnreadable) {
5390
5493
  const settingsPath = AGENT_SPECS[agent].pluginSettingsPath;
5391
5494
  if (settingsPath === null) return { plugin: null };
5392
- return readReportingFailure(settingsPath(places), readEnabledPlugin, onUnreadable);
5495
+ return attemptReportingFailure(settingsPath(places), readEnabledPlugin, onUnreadable);
5393
5496
  }
5394
5497
  async function readEnabledPlugin(path) {
5395
5498
  const settings = await readJsonFile(path, enabledPluginsSchema);
@@ -5428,16 +5531,14 @@ async function runLanguage(positionals, io) {
5428
5531
  const language = parseChoice(io.language, value, LANGUAGES, io.cli.optionLabel.language);
5429
5532
  await writeSettings(io.backlogRoot, { language });
5430
5533
  io.print(`${io.language} \u2192 ${language}`);
5431
- const { unreadableSkipped } = coreMessages(language);
5432
- const { found } = await detectAgents(io, warnPathErrors(io.warn, unreadableSkipped));
5534
+ const { found } = await detectAgents(io, warnUnreadableSkipped(io.warn, coreMessages(language)));
5433
5535
  for (const agent of found) await relinkSkill(agent, language, io);
5434
5536
  return EXIT.ok;
5435
5537
  }
5436
5538
  async function relinkSkill(agent, language, io) {
5437
5539
  const cli = cliMessages(language);
5438
- const { unreadableSkipped } = coreMessages(language);
5439
5540
  const voice = agentVoice(agent, io);
5440
- const lookup = await agentPluginReportingFailure(agent, io, warnPathErrors(voice.warn, unreadableSkipped));
5541
+ const lookup = await agentPluginReportingFailure(agent, io, warnUnreadableSkipped(voice.warn, coreMessages(language)));
5441
5542
  if (lookup?.plugin) {
5442
5543
  const wanted = pluginToSwitchTo(lookup.plugin, language);
5443
5544
  if (wanted !== null) voice.print(cli.pluginLanguageHint(lookup.plugin, wanted));
@@ -5540,6 +5641,9 @@ import { z as z11 } from "zod";
5540
5641
  function markShown(shown, signals, today) {
5541
5642
  return { ...shown, ...Object.fromEntries(signals.map((signal3) => [signal3.kind, today])) };
5542
5643
  }
5644
+ function signalsToShow(signals, shown, today) {
5645
+ return signals.filter((signal3) => shown[signal3.kind] !== today);
5646
+ }
5543
5647
 
5544
5648
  // src/core/store/signals-shown.ts
5545
5649
  var SIGNALS_SHOWN_FILE = ".signals-shown.json";
@@ -5570,13 +5674,13 @@ async function rememberSessionShown(projectDir2, session, taskIds, now) {
5570
5674
  }
5571
5675
 
5572
5676
  // src/core/stats/scope.ts
5573
- function inProjectScope(items, projectId, projectOf2) {
5677
+ function filterByProject(items, projectId, projectOf2) {
5574
5678
  return items.filter((item) => projectId === void 0 || projectOf2(item) === projectId);
5575
5679
  }
5576
5680
  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));
5681
+ const scopedJournals = filterByProject(journals, projectId, (journal) => journal.projectId);
5682
+ const scopedTasks = filterByProject(tasks, projectId, (task) => task.projectId);
5683
+ const unparsedIds = new Set(filterByProject(unparsedTasks2, projectId, (task) => task.projectId).map((task) => task.id));
5580
5684
  const journalStart = smallest(scopedJournals.flatMap((journal) => journal.events.map((event) => Date.parse(event.at))));
5581
5685
  return {
5582
5686
  tasksWithEpics: scopedTasks,
@@ -5855,11 +5959,6 @@ function measuredByClosing(evidence2) {
5855
5959
  return evidence2 !== "total" && isMeasuredEvidence(evidence2);
5856
5960
  }
5857
5961
 
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
5962
  // src/cli/agents/stop-event.ts
5864
5963
  import { createHash as createHash4 } from "node:crypto";
5865
5964
  import { z as z13 } from "zod";
@@ -5943,19 +6042,24 @@ var hookCommand = {
5943
6042
  };
5944
6043
  function namesStopEvent(args) {
5945
6044
  const { positionals } = parseArgs2({ args, options: HOOK_OPTIONS, allowPositionals: true, strict: false });
5946
- return positionals[0] === HOOK_STOP_EVENT;
6045
+ return isStopEvent(positionals);
6046
+ }
6047
+ function isStopEvent(positionals) {
6048
+ return positionals.length === 1 && positionals[0] === HOOK_STOP_EVENT;
5947
6049
  }
5948
6050
  async function runHook(args, io) {
5949
6051
  const { values, positionals } = parseCommandArgs(io.language, args, HOOK_OPTIONS);
5950
- if (positionals.length !== 1 || positionals[0] !== HOOK_STOP_EVENT) throw usageError(hookCommand, io.language);
6052
+ if (!isStopEvent(positionals)) throw usageError(hookCommand, io.language);
5951
6053
  const agent = values.agent === void 0 ? DEFAULT_AGENT : parseChoice(io.language, values.agent, AGENTS, io.cli.optionLabel.agent);
5952
6054
  const event = parseStopEvent(agent, await io.readStdin());
5953
6055
  if (event === null || event.skip) return EXIT.ok;
5954
6056
  const loaded = await loadBacklog(io.backlogRoot);
5955
- const project = findProjectForDir(loaded.projects, event.cwd, repoPlaces(io));
6057
+ const places = repoPlaces(io);
6058
+ const cwdRoots = readGitRoots(event.cwd, places.onUnreadable);
6059
+ const project = findProjectForDir(loaded.projects, event.cwd, cwdRoots, places);
5956
6060
  if (!project) return EXIT.ok;
5957
6061
  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 });
6062
+ 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
6063
  const lowPriority = new Set(loaded.tasks.filter((task) => task.priority === "low").map((task) => task.id));
5960
6064
  const worthTelling = candidates.filter((candidate) => !lowPriority.has(candidate.task.id));
5961
6065
  const lowCount = candidates.length - worthTelling.length;
@@ -6153,7 +6257,7 @@ async function runNew(args, io) {
6153
6257
  if (!project) return EXIT.notFound;
6154
6258
  const projectTasks = loaded.tasks.filter((task2) => task2.projectId === project.id);
6155
6259
  if (!values.force && warnedOfSimilarTask({ title: values.title, source: values.source }, projectTasks, io)) return EXIT.refused;
6156
- const [atSource, body, origin] = await Promise.all([
6260
+ const [atSource, body, origin] = await allAfterSettling([
6157
6261
  values.source === void 0 ? void 0 : anchorOf2(project, values.source, io),
6158
6262
  io.readStdin(),
6159
6263
  values.project === void 0 || cwdBelongsTo(project, loaded.projects, io) ? readOrigin(io.cwd) : void 0
@@ -6200,7 +6304,11 @@ async function anchorOf2(project, source, io) {
6200
6304
  return sourceAnchor(await findRepo(project, lookup), source, lookup.onUnreadable);
6201
6305
  }
6202
6306
  function cwdBelongsTo(project, knownProjects, io) {
6203
- return findProjectForDir([...knownProjects, project], io.cwd, repoPlaces(io))?.id === project.id;
6307
+ return findProjectForCwd([...knownProjects, project], io)?.id === project.id;
6308
+ }
6309
+ async function allAfterSettling(work) {
6310
+ await Promise.allSettled(work);
6311
+ return Promise.all(work);
6204
6312
  }
6205
6313
 
6206
6314
  // src/cli/commands/priority.ts
@@ -6314,7 +6422,7 @@ async function runPrune(args, io) {
6314
6422
  // src/server/start.ts
6315
6423
  import { serve } from "@hono/node-server";
6316
6424
  import { mkdir as mkdir6, rm as rm4, writeFile as writeFile3 } from "node:fs/promises";
6317
- import { join as join31 } from "node:path";
6425
+ import { join as join32 } from "node:path";
6318
6426
 
6319
6427
  // src/server/app.ts
6320
6428
  import { serveStatic } from "@hono/node-server/serve-static";
@@ -6370,12 +6478,14 @@ var batchRequestSchema = z14.strictObject({
6370
6478
  // src/core/check/graph-health.ts
6371
6479
  async function projectGraphHealth(project, tasks, home2) {
6372
6480
  return graphHealth(
6373
- await findRepo(project, { home: home2, onUnreadable: unreadableRepoHasNoGraph }),
6481
+ await findRepo(project, { home: home2, onUnreadable: unreadableRepoHasNoGraph, workingRoots: null }),
6374
6482
  tasks.filter((task) => task.projectId === project.id)
6375
6483
  );
6376
6484
  }
6377
6485
  function unreadableRepoHasNoGraph() {
6378
6486
  }
6487
+ function unreadableSourceIsAbsent() {
6488
+ }
6379
6489
  function graphHealth(repo, tasks) {
6380
6490
  const pinned = tasks.filter((task) => isReviewable(task) && sourceRange(task.source) !== null);
6381
6491
  const unusable = (state) => ({ state, pinned: pinned.length, resolved: 0 });
@@ -6383,7 +6493,7 @@ function graphHealth(repo, tasks) {
6383
6493
  const graph = openCodeGraph(repo);
6384
6494
  if (graph === null) return unusable("unreadable");
6385
6495
  try {
6386
- const hashOf = fileHashes(repo);
6496
+ const hashOf = fileHashes(repo, unreadableSourceIsAbsent);
6387
6497
  const symbolAt = symbolLookup(graph, hashOf);
6388
6498
  const resolved = pinned.filter((task) => symbolOfSource(symbolAt, task.source) !== null).length;
6389
6499
  return { state: isStale(graph, pinned, hashOf) ? "stale" : "fresh", pinned: pinned.length, resolved };
@@ -6575,7 +6685,7 @@ function createJournalSources(root) {
6575
6685
  return { journal: projectJournal(projectId, lines), position: `${projectId}=${generation}:${length}` };
6576
6686
  };
6577
6687
  const rememberedContext = (snapshot, tailed) => (input) => {
6578
- const positions = inProjectScope(tailed, input.projectId, ({ journal }) => journal.projectId).map(({ position }) => position);
6688
+ const positions = filterByProject(tailed, input.projectId, ({ journal }) => journal.projectId).map(({ position }) => position);
6579
6689
  const key = `${snapshotIdOf(snapshot)}|${positions.join(",")}`;
6580
6690
  return { ...remembered2.get(key, () => scopedReportData(input), input.projectId), input };
6581
6691
  };
@@ -6619,6 +6729,7 @@ Backlog directory: ${root}`,
6619
6729
  deletedClosedTasks: (ids) => `Deleted closed tasks: ${ids}`,
6620
6730
  conflictedDuringSweep: (ids) => `Tasks changed during the sweep, will retry next time: ${ids}`,
6621
6731
  invalidAfterSweep: (detail) => `Could not update tasks, fix the files: ${detail}`,
6732
+ languageUnreadable: (detail) => `Could not read the language setting, messages follow the system language: ${detail}`,
6622
6733
  transcriptsScanFailed: (detail) => `Could not read Claude Code transcripts: ${detail}`,
6623
6734
  watcherError: (root, detail) => `Watcher for directory ${root}: ${detail}`,
6624
6735
  listenFailed: (reason) => `p-backlog failed to start: ${reason}`,
@@ -6655,6 +6766,7 @@ var serverRu = {
6655
6766
  deletedClosedTasks: (ids) => `\u0423\u0434\u0430\u043B\u0435\u043D\u044B \u0437\u0430\u043A\u0440\u044B\u0442\u044B\u0435 \u0437\u0430\u0434\u0430\u0447\u0438: ${ids}`,
6656
6767
  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}`,
6657
6768
  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}`,
6769
+ 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}`,
6658
6770
  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}`,
6659
6771
  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}`,
6660
6772
  listenFailed: (reason) => `p-backlog \u043D\u0435 \u0437\u0430\u043F\u0443\u0441\u0442\u0438\u043B\u0441\u044F: ${reason}`,
@@ -6700,7 +6812,7 @@ function createTtlCache({ ttlMs, now }) {
6700
6812
 
6701
6813
  // src/server/revisions.ts
6702
6814
  import { randomUUID as randomUUID3 } from "node:crypto";
6703
- import { readFile as readFile2, stat as stat3 } from "node:fs/promises";
6815
+ import { readFile as readFile2, stat as stat2 } from "node:fs/promises";
6704
6816
  function createRevisions() {
6705
6817
  const boot = randomUUID3();
6706
6818
  let seq = 0;
@@ -6732,7 +6844,7 @@ function createRevisions() {
6732
6844
  };
6733
6845
  }
6734
6846
  async function markOf(path) {
6735
- const [text, stats] = await Promise.all([readFile2(path, "utf8"), stat3(path)]);
6847
+ const [text, stats] = await Promise.all([readFile2(path, "utf8"), stat2(path)]);
6736
6848
  return { version: contentVersion(text), mtimeMs: stats.mtimeMs };
6737
6849
  }
6738
6850
  function markIfReadable(path) {
@@ -6752,12 +6864,19 @@ function tasksClosedInWeb(tasks, journals) {
6752
6864
 
6753
6865
  // src/server/snapshot-cache.ts
6754
6866
  function createSnapshotCache({ root, revisions, journalSources, warn: warn2 }) {
6755
- const snapshots = createScopeMemo();
6756
- let generation = 0;
6867
+ let snapshot = null;
6757
6868
  return {
6758
- read: () => snapshots.get(`${generation}`, () => loadSnapshot(root, revisions.current(), journalSources, warn2)),
6869
+ read: () => {
6870
+ if (snapshot !== null) return snapshot;
6871
+ const loading = loadSnapshot(root, revisions.current(), journalSources, warn2);
6872
+ snapshot = loading;
6873
+ loading.catch(() => {
6874
+ if (snapshot === loading) snapshot = null;
6875
+ });
6876
+ return loading;
6877
+ },
6759
6878
  forget: () => {
6760
- generation += 1;
6879
+ snapshot = null;
6761
6880
  }
6762
6881
  };
6763
6882
  }
@@ -7108,9 +7227,8 @@ function parseFixHeaders(output) {
7108
7227
  }
7109
7228
  async function landingDate(git, repo, { fix, paths, mainCommit }) {
7110
7229
  if (fix.full === mainCommit) return fix.date;
7111
- const descendants = await git(repo, ["log", "--first-parent", "--ancestry-path", `--format=tformat:%P${FIELD}%cI`, `${fix.full}..${mainCommit}`, "--"]);
7112
- const [parents = "", mergedAt = ""] = lastLine(descendants).split(FIELD);
7113
- if (mergedAt !== "") return parents.split(" ")[0] === fix.full ? fix.date : mergedAt;
7230
+ const landing = await firstParentLanding(git, repo, fix.full, mainCommit);
7231
+ if (landing !== null) return landing.firstParent === fix.full ? fix.date : landing.committedAt;
7114
7232
  if (fix.subject === "" || paths.length === 0) return void 0;
7115
7233
  const pathspecs = literalPathspecs(paths);
7116
7234
  const squashes = await git(repo, ["log", mainCommit, "--first-parent", `--since=${fix.date}`, "--extended-regexp", `--grep=${subjectLinePattern(fix.subject)}`, "--format=tformat:%cI", "--", ...pathspecs]);
@@ -7338,7 +7456,7 @@ function codeReport(context, code) {
7338
7456
  input: { now, projectId },
7339
7457
  openTasks
7340
7458
  } = context;
7341
- const projects = inProjectScope(code.projects, projectId, (project) => project.projectId);
7459
+ const projects = filterByProject(code.projects, projectId, (project) => project.projectId);
7342
7460
  return {
7343
7461
  ...context.head,
7344
7462
  periods: { churn: lastDays(now, CHURN_DAYS) },
@@ -7356,7 +7474,7 @@ function effectReport(context, code, wholeBacklog) {
7356
7474
  histories
7357
7475
  } = context;
7358
7476
  const statsWindow = statsPeriod(now);
7359
- const projects = inProjectScope(code.projects, projectId, (project) => project.projectId).filter((project) => project.repos.length > 0);
7477
+ const projects = filterByProject(code.projects, projectId, (project) => project.projectId).filter((project) => project.repos.length > 0);
7360
7478
  const deferredByAgent = createdIn(histories, statsWindow).filter((history) => history.found === "incidental");
7361
7479
  const deferred = buildDeferred(deferredByAgent, retainedFixes(histories, now), code);
7362
7480
  const estimate = estimator(estimateSamples(retainedFixes(wholeBacklog.histories, now), code));
@@ -7706,8 +7824,8 @@ var COST_TOTALS_DAYS = 7;
7706
7824
  function costReport({ buckets, runs, projectOf: projectOf2, projectId, now, scan }) {
7707
7825
  const projectByCwd = /* @__PURE__ */ new Map();
7708
7826
  const projectOfCwd = (cwd) => remembered(projectByCwd, cwd, () => projectOf2(cwd));
7709
- const scopedBuckets = inProjectScope(buckets, projectId, (bucket) => projectOfCwd(bucket.cwd));
7710
- const scopedRuns = inProjectScope(
7827
+ const scopedBuckets = filterByProject(buckets, projectId, (bucket) => projectOfCwd(bucket.cwd));
7828
+ const scopedRuns = filterByProject(
7711
7829
  runs.filter((run) => run.command !== SERVE_COMMAND_NAME),
7712
7830
  projectId,
7713
7831
  (run) => projectOfCwd(run.cwd)
@@ -8051,8 +8169,9 @@ async function readBody(c, schema, readLanguage) {
8051
8169
  async function readJson(c) {
8052
8170
  try {
8053
8171
  return { ok: true, value: await c.req.json() };
8054
- } catch {
8055
- return { ok: false };
8172
+ } catch (error) {
8173
+ if (error instanceof SyntaxError) return { ok: false };
8174
+ throw error;
8056
8175
  }
8057
8176
  }
8058
8177
 
@@ -8061,7 +8180,7 @@ import { bodyLimit } from "hono/body-limit";
8061
8180
  var REQUEST_BODY_LIMIT_MEBIBYTES = 1;
8062
8181
  var MUTATING_METHODS = /* @__PURE__ */ new Set(["POST", "PATCH", "PUT", "DELETE"]);
8063
8182
  function localHosts(port) {
8064
- return /* @__PURE__ */ new Set([`127.0.0.1:${port}`, `localhost:${port}`, `[::1]:${port}`]);
8183
+ return new Set(LOOPBACK_HOSTS.map((host) => `${host}:${port}`));
8065
8184
  }
8066
8185
  function allowLocalHostsOnly(allowedHosts, readLanguage) {
8067
8186
  return async (c, next) => {
@@ -8125,7 +8244,7 @@ function createApp({ root, readLanguage, changes, allowedHosts, home: home2, sta
8125
8244
  }
8126
8245
 
8127
8246
  // src/server/change-feed.ts
8128
- import { relative as relative4, sep as sep5 } from "node:path";
8247
+ import { join as join29, relative as relative4, sep as sep5 } from "node:path";
8129
8248
  import { watch } from "chokidar";
8130
8249
  var CHANGE_DEBOUNCE_MS = 100;
8131
8250
  function createDebouncer(delayMs, run) {
@@ -8141,6 +8260,12 @@ function createDebouncer(delayMs, run) {
8141
8260
  function isHiddenPath(root, path) {
8142
8261
  return relative4(root, path).split(sep5).some((segment) => segment.startsWith("."));
8143
8262
  }
8263
+ async function watchDirectoriesMissedAtStart(watcher, root) {
8264
+ const directories = (await listDir(root)).filter((entry) => entry.isDirectory()).map((entry) => join29(root, entry.name));
8265
+ const watched = watcher.getWatched();
8266
+ const missed = directories.filter((path) => !isHiddenPath(root, path) && !(path in watched));
8267
+ if (missed.length > 0 && !watcher.closed) watcher.add(missed);
8268
+ }
8144
8269
  function createChangeFeed({ root, debounceMs, warn: warn2 }) {
8145
8270
  const listeners = /* @__PURE__ */ new Set();
8146
8271
  const { promise: closed, resolve: markClosed } = Promise.withResolvers();
@@ -8156,10 +8281,15 @@ function createChangeFeed({ root, debounceMs, warn: warn2 }) {
8156
8281
  };
8157
8282
  const watcher = watch(root, { ignoreInitial: true, ignored: (path) => isHiddenPath(root, path) });
8158
8283
  watcher.on("all", (_event, path) => reportChange(path));
8159
- watcher.on("ready", () => reportChange(root));
8160
- watcher.on("error", (error) => {
8284
+ const warnWatcherError = (error) => {
8161
8285
  void warn2((messages) => messages.watcherError(root, errorText(error)));
8286
+ };
8287
+ watcher.on("ready", () => {
8288
+ void watchDirectoriesMissedAtStart(watcher, root).catch(warnWatcherError).finally(() => {
8289
+ if (!watcher.closed) reportChange(root);
8290
+ });
8162
8291
  });
8292
+ watcher.on("error", warnWatcherError);
8163
8293
  return {
8164
8294
  subscribe: (listener) => {
8165
8295
  listeners.add(listener);
@@ -8182,7 +8312,7 @@ function createMemorySampler({ intervalMs = MEMORY_SAMPLE_INTERVAL_MS, capacity
8182
8312
  let timer = null;
8183
8313
  const sample = () => {
8184
8314
  const usage = process.memoryUsage();
8185
- const point = { at: formatLocalIso(now()), rssMb: megabytesOf(usage.rss), heapUsedMb: megabytesOf(usage.heapUsed) };
8315
+ const point = { at: formatLocalIso(now()), rssMb: mebibytesOf(usage.rss), heapUsedMb: mebibytesOf(usage.heapUsed) };
8186
8316
  points = [...points, point].slice(-capacity);
8187
8317
  };
8188
8318
  return {
@@ -8199,12 +8329,6 @@ function createMemorySampler({ intervalMs = MEMORY_SAMPLE_INTERVAL_MS, capacity
8199
8329
  };
8200
8330
  }
8201
8331
 
8202
- // src/server/port.ts
8203
- function listenFailure(error, port, messages) {
8204
- const reason = error.code === "EADDRINUSE" ? messages.portBusy(port) : error.message;
8205
- return messages.listenFailed(reason);
8206
- }
8207
-
8208
8332
  // src/server/sweeper.ts
8209
8333
  function startSweeper({ maintain, intervalMs, log, warn: warn2, messages }) {
8210
8334
  let current = Promise.resolve();
@@ -8236,8 +8360,7 @@ import { isDeepStrictEqual } from "node:util";
8236
8360
 
8237
8361
  // src/core/usage/transcripts.ts
8238
8362
  import { createHash as createHash6 } from "node:crypto";
8239
- import { stat as stat4 } from "node:fs/promises";
8240
- import { basename as basename9, join as join30 } from "node:path";
8363
+ import { basename as basename9, join as join31 } from "node:path";
8241
8364
 
8242
8365
  // src/core/stats/cost/attribute.ts
8243
8366
  import { z as z17 } from "zod";
@@ -8605,7 +8728,7 @@ function slotOf(timestamp) {
8605
8728
 
8606
8729
  // src/core/usage/usage-cache.ts
8607
8730
  import { mkdir as mkdir5 } from "node:fs/promises";
8608
- import { join as join29 } from "node:path";
8731
+ import { join as join30 } from "node:path";
8609
8732
  import { z as z19 } from "zod";
8610
8733
 
8611
8734
  // src/core/stats/cost/usage-state.ts
@@ -8647,11 +8770,11 @@ function emptyUsageCache() {
8647
8770
  return { version: USAGE_CACHE_VERSION, files: {} };
8648
8771
  }
8649
8772
  async function readUsageCache(root) {
8650
- return await readJsonFile(join29(root, USAGE_CACHE_FILE), usageCacheSchema) ?? emptyUsageCache();
8773
+ return await readJsonFile(join30(root, USAGE_CACHE_FILE), usageCacheSchema) ?? emptyUsageCache();
8651
8774
  }
8652
8775
  async function writeUsageCache(root, cache) {
8653
8776
  await mkdir5(root, { recursive: true });
8654
- await writeFileAtomic(join29(root, USAGE_CACHE_FILE), JSON.stringify(cache));
8777
+ await writeFileAtomic(join30(root, USAGE_CACHE_FILE), JSON.stringify(cache));
8655
8778
  }
8656
8779
 
8657
8780
  // src/core/usage/transcripts.ts
@@ -8662,28 +8785,24 @@ async function listTranscripts(claudeProjectsDir2) {
8662
8785
  const files = [];
8663
8786
  for (const projectEntry of await listDir(claudeProjectsDir2)) {
8664
8787
  if (!projectEntry.isDirectory()) continue;
8665
- const projectDir2 = join30(claudeProjectsDir2, projectEntry.name);
8788
+ const projectDir2 = join31(claudeProjectsDir2, projectEntry.name);
8666
8789
  for (const entry of await listDir(projectDir2)) {
8667
- const entryPath = join30(projectDir2, entry.name);
8790
+ const entryPath = join31(projectDir2, entry.name);
8668
8791
  if (entry.isFile() && entry.name.endsWith(".jsonl")) {
8669
8792
  files.push(...await listedFile(entryPath));
8670
8793
  continue;
8671
8794
  }
8672
8795
  if (!entry.isDirectory()) continue;
8673
- for (const subagentEntry of await listDir(join30(entryPath, "subagents"), { recursive: true })) {
8674
- if (subagentEntry.isFile() && subagentEntry.name.endsWith(".jsonl")) files.push(...await listedFile(join30(subagentEntry.parentPath, subagentEntry.name)));
8796
+ for (const subagentEntry of await listDir(join31(entryPath, "subagents"), { recursive: true })) {
8797
+ if (subagentEntry.isFile() && subagentEntry.name.endsWith(".jsonl")) files.push(...await listedFile(join31(subagentEntry.parentPath, subagentEntry.name)));
8675
8798
  }
8676
8799
  }
8677
8800
  }
8678
8801
  return files;
8679
8802
  }
8680
8803
  async function listedFile(path) {
8681
- try {
8682
- const { size, mtimeMs } = await stat4(path);
8683
- return [{ path, size, mtimeMs }];
8684
- } catch {
8685
- return [];
8686
- }
8804
+ const stats = await statOrNull(path);
8805
+ return stats === null ? [] : [{ path, size: stats.size, mtimeMs: stats.mtimeMs }];
8687
8806
  }
8688
8807
  async function scanTranscripts({ files, cache, byteBudget, now }) {
8689
8808
  let remainingBudget = byteBudget;
@@ -8864,11 +8983,12 @@ function progressBefore(files, cache) {
8864
8983
  // src/server/start.ts
8865
8984
  var SWEEP_INTERVAL_MS = HOUR_MS;
8866
8985
  var STOP_SIGNALS = ["SIGTERM", "SIGINT", "SIGHUP"];
8867
- var BUNDLED_WEB_DIR = join31(import.meta.dirname, "web");
8986
+ var BUNDLED_WEB_DIR = join32(import.meta.dirname, "web");
8868
8987
  async function startServer({ root, port, home: home2, env, platform, log, warn: warn2, pidFile, staticDir, settledLanguage, now = () => /* @__PURE__ */ new Date() }) {
8869
8988
  await mkdir6(root, { recursive: true });
8870
8989
  const startupMessages = serverMessages(settledLanguage);
8871
- const readLanguage = () => readLanguageOrLocale(root, env);
8990
+ const onLanguageUnreadable = oncePerKey(errorText, (error) => warn2(startupMessages.languageUnreadable(errorText(error))));
8991
+ const readLanguage = () => readLanguageOrLocale(root, env, onLanguageUnreadable);
8872
8992
  const readMessages = () => readLanguage().then(serverMessages);
8873
8993
  const warnLocalized = localizedWarn(readLanguage, warn2);
8874
8994
  const usage = createUsageScanner({ root, claudeProjectsDir: claudeProjectsDir(env, home2), warn: warnLocalized, now });
@@ -8909,6 +9029,10 @@ function closeOnStopSignal(server) {
8909
9029
  for (const signal3 of STOP_SIGNALS) process.once(signal3, stop);
8910
9030
  });
8911
9031
  }
9032
+ function listenFailure(error, port, messages) {
9033
+ const reason = error.code === "EADDRINUSE" ? messages.portBusy(port) : error.message;
9034
+ return messages.listenFailed(reason);
9035
+ }
8912
9036
  function listen(app, port) {
8913
9037
  return new Promise((resolve7, reject) => {
8914
9038
  const server = serve({ fetch: app.fetch, hostname: LOOPBACK_HOST, port }, (info) => {
@@ -8970,7 +9094,7 @@ function isFailure(outcome) {
8970
9094
 
8971
9095
  // src/cli/service/launchd.ts
8972
9096
  import { mkdir as mkdir7, rm as rm5, writeFile as writeFile4 } from "node:fs/promises";
8973
- import { dirname as dirname9, join as join32 } from "node:path";
9097
+ import { dirname as dirname9, join as join33 } from "node:path";
8974
9098
  import { setTimeout as sleep3 } from "node:timers/promises";
8975
9099
 
8976
9100
  // src/cli/service/service.ts
@@ -9034,7 +9158,7 @@ ${entries}
9034
9158
  `;
9035
9159
  }
9036
9160
  function launchdManager(context, delay = sleep3) {
9037
- const file = join32(context.home, "Library/LaunchAgents", `${LABEL}.plist`);
9161
+ const file = join33(context.home, "Library/LaunchAgents", `${LABEL}.plist`);
9038
9162
  const domain = `gui/${context.uid}`;
9039
9163
  const bootout = () => context.exec("launchctl", ["bootout", `${domain}/${LABEL}`]);
9040
9164
  const bootstrap = () => context.exec("launchctl", ["bootstrap", domain, file]);
@@ -9069,7 +9193,7 @@ function launchdManager(context, delay = sleep3) {
9069
9193
 
9070
9194
  // src/cli/service/startup-folder.ts
9071
9195
  import { mkdir as mkdir8, rm as rm6, writeFile as writeFile5 } from "node:fs/promises";
9072
- import { dirname as dirname10, join as join33, win32 } from "node:path";
9196
+ import { dirname as dirname10, join as join34, win32 } from "node:path";
9073
9197
  var SCRIPT_NAME = "p-backlog.vbs";
9074
9198
  var COMMAND_LINE_ARGUMENT = /"[^"]*"|\S+/g;
9075
9199
  var PROCESS_QUERY_TIMEOUT_MS = 15e3;
@@ -9077,21 +9201,21 @@ function vbsString(value) {
9077
9201
  return `"${value.replaceAll('"', '""')}"`;
9078
9202
  }
9079
9203
  function appDataDir(site) {
9080
- return join33(site.env.LOCALAPPDATA ?? join33(site.home, "AppData", "Local"), "p-backlog");
9204
+ return join34(site.env.LOCALAPPDATA ?? join34(site.home, "AppData", "Local"), "p-backlog");
9081
9205
  }
9082
9206
  function startupFolder(site) {
9083
- return join33(site.env.APPDATA ?? join33(site.home, "AppData", "Roaming"), "Microsoft", "Windows", "Start Menu", "Programs", "Startup");
9207
+ return join34(site.env.APPDATA ?? join34(site.home, "AppData", "Roaming"), "Microsoft", "Windows", "Start Menu", "Programs", "Startup");
9084
9208
  }
9085
9209
  function logPath(site) {
9086
- return join33(appDataDir(site), "p-backlog.log");
9210
+ return join34(appDataDir(site), "p-backlog.log");
9087
9211
  }
9088
9212
  function pidFilePath(site) {
9089
- return join33(appDataDir(site), "server.pid");
9213
+ return join34(appDataDir(site), "server.pid");
9090
9214
  }
9091
9215
  var NODE_PATH_ENV = "P_BACKLOG_NODE";
9092
9216
  var CLI_PATH_ENV = "P_BACKLOG_CLI";
9093
9217
  var LOG_PATH_ENV = "P_BACKLOG_LOG";
9094
- var SERVE_COMMAND = `cmd /v:on /c ""!${NODE_PATH_ENV}!" "!${CLI_PATH_ENV}!" ${SERVE_COMMAND_NAME} >> "!${LOG_PATH_ENV}!" 2>&1"`;
9218
+ var SERVE_COMMAND_LINE = `cmd /v:on /c ""!${NODE_PATH_ENV}!" "!${CLI_PATH_ENV}!" ${SERVE_COMMAND_NAME} >> "!${LOG_PATH_ENV}!" 2>&1"`;
9095
9219
  function rotatedLogPath(site) {
9096
9220
  return `${logPath(site)}.old`;
9097
9221
  }
@@ -9123,7 +9247,7 @@ function startupScript(launch) {
9123
9247
  'Set env = shell.Environment("Process")',
9124
9248
  ...Object.entries(env).map(([key, value]) => `env(${vbsString(key)}) = ${vbsString(value)}`),
9125
9249
  ...logRotation(launch),
9126
- `shell.Run ${vbsString(SERVE_COMMAND)}, 0, False`,
9250
+ `shell.Run ${vbsString(SERVE_COMMAND_LINE)}, 0, False`,
9127
9251
  ""
9128
9252
  ].join("\r\n");
9129
9253
  }
@@ -9156,7 +9280,7 @@ function sameWindowsPath(left, right) {
9156
9280
  return win32.normalize(left).toLowerCase() === win32.normalize(right).toLowerCase();
9157
9281
  }
9158
9282
  function startupFolderManager(context) {
9159
- const file = join33(startupFolder(context), SCRIPT_NAME);
9283
+ const file = join34(startupFolder(context), SCRIPT_NAME);
9160
9284
  return {
9161
9285
  file,
9162
9286
  logsHint: logPath(context),
@@ -9183,7 +9307,7 @@ function startupFolderManager(context) {
9183
9307
 
9184
9308
  // src/cli/service/systemd.ts
9185
9309
  import { mkdir as mkdir9, rm as rm7, writeFile as writeFile6 } from "node:fs/promises";
9186
- import { dirname as dirname11, join as join34 } from "node:path";
9310
+ import { dirname as dirname11, join as join35 } from "node:path";
9187
9311
  var SERVICE_NAME = "p-backlog";
9188
9312
  var UNIT = `${SERVICE_NAME}.service`;
9189
9313
  function quoted(value) {
@@ -9218,7 +9342,7 @@ async function systemctlSteps(exec, steps) {
9218
9342
  return "done";
9219
9343
  }
9220
9344
  function systemdManager(context) {
9221
- const file = join34(context.home, ".config/systemd/user", UNIT);
9345
+ const file = join35(context.home, ".config/systemd/user", UNIT);
9222
9346
  return {
9223
9347
  file,
9224
9348
  logsHint: `journalctl --user -u ${SERVICE_NAME}`,
@@ -9259,7 +9383,7 @@ function serviceManagerOf(io) {
9259
9383
  return availableServiceManager(io.platform, serviceContextOf(io));
9260
9384
  }
9261
9385
  async function servicePort(manager, io) {
9262
- const installed = manager === null ? null : await readReportingFailure(manager.file, () => manager.installedPort(), warnPathErrors(io.warn, io.core.unreadableSkipped));
9386
+ const installed = manager === null ? null : await attemptReportingFailure(manager.file, () => manager.installedPort(), warnUnreadableSkipped(io.warn, io.core));
9263
9387
  return installed ?? envPort(io);
9264
9388
  }
9265
9389
  function webUiPort(io) {
@@ -9272,10 +9396,16 @@ async function serverResponds(origin, timeoutMs) {
9272
9396
  try {
9273
9397
  const response = await fetch(`${origin}${PROBE_PATH}`, { signal: AbortSignal.timeout(timeoutMs) });
9274
9398
  return response.ok;
9275
- } catch {
9276
- return false;
9399
+ } catch (error) {
9400
+ if (isUnreachable(error)) return false;
9401
+ throw error;
9277
9402
  }
9278
9403
  }
9404
+ function isUnreachable(fetchFailure) {
9405
+ const networkFailed = fetchFailure instanceof TypeError;
9406
+ const timedOut = fetchFailure instanceof DOMException && fetchFailure.name === "TimeoutError";
9407
+ return networkFailed || timedOut;
9408
+ }
9279
9409
 
9280
9410
  // src/cli/commands/service.ts
9281
9411
  var STATUS_TIMEOUT_MS = 1e3;
@@ -9344,8 +9474,9 @@ async function readJsonConfig(path, schema) {
9344
9474
  let value;
9345
9475
  try {
9346
9476
  value = JSON.parse(text);
9347
- } catch {
9348
- return { failed: "invalid" };
9477
+ } catch (error) {
9478
+ if (error instanceof SyntaxError) return { failed: "invalid" };
9479
+ throw error;
9349
9480
  }
9350
9481
  return schema.safeParse(value).success ? { config: value } : { failed: "invalid" };
9351
9482
  }
@@ -9353,8 +9484,7 @@ async function writeJsonConfig(path, config) {
9353
9484
  await mkdir10(dirname12(path), { recursive: true });
9354
9485
  const target = await writeTargetOf(path);
9355
9486
  const existing = await statOrNull(target);
9356
- await writeFileAtomic(target, `${JSON.stringify(config, null, 2)}
9357
- `, existing === null ? void 0 : existing.mode & 511);
9487
+ await writeFileAtomic(target, jsonFileText(config), existing === null ? void 0 : existing.mode & 511);
9358
9488
  }
9359
9489
  async function readConfigText(path) {
9360
9490
  try {
@@ -9574,7 +9704,7 @@ async function runSetup(args, io) {
9574
9704
  }
9575
9705
  function installedAgents(io) {
9576
9706
  let detection;
9577
- return () => detection ??= detectAgents(io, warnPathErrors(io.warn, io.core.unreadableSkipped));
9707
+ return () => detection ??= detectAgents(io, warnUnreadableSkipped(io.warn, io.core));
9578
9708
  }
9579
9709
  async function targetAgents(option, installed, io) {
9580
9710
  if (option !== void 0) return [parseChoice(io.language, option, AGENTS, io.cli.optionLabel.agent)];
@@ -9584,7 +9714,7 @@ async function targetAgents(option, installed, io) {
9584
9714
  }
9585
9715
  async function setUpAgent(agent, io) {
9586
9716
  const voice = agentVoice(agent, io);
9587
- const lookup = await agentPluginReportingFailure(agent, io, warnPathErrors(voice.warn, io.core.unreadableSkipped));
9717
+ const lookup = await agentPluginReportingFailure(agent, io, warnUnreadableSkipped(voice.warn, io.core));
9588
9718
  if (lookup === null) return false;
9589
9719
  if (lookup.plugin !== null) {
9590
9720
  voice.print(io.cli.pluginManages(lookup.plugin));
@@ -9622,7 +9752,7 @@ async function removeLegacySkillLinks(agent, io, voice) {
9622
9752
  return allSettled;
9623
9753
  }
9624
9754
  function unlinkReportingFailure(skillsDir, io, voice) {
9625
- return readReportingFailure(
9755
+ return attemptReportingFailure(
9626
9756
  skillLinkPath(skillsDir),
9627
9757
  () => unlinkOurSkill(skillsDir),
9628
9758
  (target, error) => voice.warn(io.cli.removeSkillLinkFailed(target, errorCodeOrText(error)))
@@ -9892,7 +10022,7 @@ function isOpenTaskAt(task, path) {
9892
10022
  return workable && task.source !== void 0 && (path === "" || isWithin(sourcePath(task.source), path));
9893
10023
  }
9894
10024
  function repoRelativePath(io, project, path) {
9895
- const roots = findGitRoots(io.cwd);
10025
+ const roots = cwdGitRoots(io);
9896
10026
  if (roots === null || findProjectForRoots([project], roots, repoPlaces(io)) === void 0) return sourcePath(path);
9897
10027
  return relativeInside(roots.worktree, resolve5(realpathSync3(io.cwd), sourcePath(path))) ?? sourcePath(path);
9898
10028
  }
@@ -10059,7 +10189,8 @@ function commandName(argv2) {
10059
10189
 
10060
10190
  // src/cli/main.ts
10061
10191
  suppressSqliteExperimentalWarning();
10062
- var BYTES_PER_KILOBYTE = 1024;
10192
+ function alreadyReportedByRunCli() {
10193
+ }
10063
10194
  async function readStdin() {
10064
10195
  if (process.stdin.isTTY) return "";
10065
10196
  const chunks = [];
@@ -10083,9 +10214,8 @@ var exitCode = await runCli(argv, {
10083
10214
  stopProcess: (pid) => {
10084
10215
  try {
10085
10216
  process.kill(pid);
10086
- return true;
10087
- } catch {
10088
- return false;
10217
+ } catch (error) {
10218
+ if (!hasErrorCode(error, "ESRCH")) throw error;
10089
10219
  }
10090
10220
  },
10091
10221
  env: process.env,
@@ -10103,10 +10233,10 @@ if (command !== SERVE_COMMAND_NAME) {
10103
10233
  command,
10104
10234
  cwd: process.cwd(),
10105
10235
  ms: Math.round(performance.now()),
10106
- rssMb: megabytesOf(process.resourceUsage().maxRSS * BYTES_PER_KILOBYTE),
10236
+ rssMb: mebibytesOf(process.resourceUsage().maxRSS * BYTES_PER_KIBIBYTE),
10107
10237
  exitCode
10108
10238
  };
10109
- const language = await readLanguageOrLocale(backlogRoot, process.env);
10239
+ const language = await readLanguageOrLocale(backlogRoot, process.env, alreadyReportedByRunCli);
10110
10240
  await appendRun(backlogRoot, run).catch((error) => warn(cliMessages(language).runNotRecorded(errorText(error))));
10111
10241
  await tidyAfterCommand({ backlogRoot, command, language, now: /* @__PURE__ */ new Date(), warn });
10112
10242
  }