@aragon-agent/cli 0.6.55 → 0.6.57

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 (319) hide show
  1. package/CHANGELOG.md +2935 -2864
  2. package/README.md +160 -45
  3. package/dist/agent/controller.d.ts +47 -0
  4. package/dist/agent/controller.js +153 -2
  5. package/dist/agent/governance-wiring.js +8 -1
  6. package/dist/agent/system-prompt.d.ts +26 -0
  7. package/dist/agent/system-prompt.js +11 -0
  8. package/dist/app/App.js +101 -3
  9. package/dist/cli.js +29 -1
  10. package/dist/commands/builtins.js +4 -0
  11. package/dist/commands/catalog.js +1 -0
  12. package/dist/commands/registry.d.ts +8 -0
  13. package/dist/config/app-paths.d.ts +10 -0
  14. package/dist/config/app-paths.js +12 -0
  15. package/dist/config/cli-commands.d.ts +29 -0
  16. package/dist/config/cli-commands.js +76 -1
  17. package/dist/config/env.d.ts +2 -1
  18. package/dist/config/env.js +12 -1
  19. package/dist/config/load.d.ts +10 -0
  20. package/dist/config/load.js +13 -2
  21. package/dist/config/store.js +11 -1
  22. package/dist/exec/bridge/server.d.ts +7 -0
  23. package/dist/exec/bridge/server.js +6 -2
  24. package/dist/exec/cli-commands.js +4 -0
  25. package/dist/exec/index.js +2 -0
  26. package/dist/exec/options.d.ts +11 -0
  27. package/dist/exec/options.js +21 -1
  28. package/dist/gene/block.d.ts +33 -0
  29. package/dist/gene/block.js +51 -0
  30. package/dist/gene/capacity.d.ts +74 -0
  31. package/dist/gene/capacity.js +169 -0
  32. package/dist/gene/catalog-reconcile.d.ts +13 -0
  33. package/dist/gene/catalog-reconcile.js +105 -0
  34. package/dist/gene/catalog-stats.d.ts +27 -0
  35. package/dist/gene/catalog-stats.js +89 -0
  36. package/dist/gene/catalog-sync.d.ts +82 -0
  37. package/dist/gene/catalog-sync.js +324 -0
  38. package/dist/gene/catalog.d.ts +160 -0
  39. package/dist/gene/catalog.js +433 -0
  40. package/dist/gene/cli-commands.d.ts +50 -0
  41. package/dist/gene/cli-commands.js +500 -0
  42. package/dist/gene/command-report.d.ts +40 -0
  43. package/dist/gene/command-report.js +246 -0
  44. package/dist/gene/command.d.ts +29 -0
  45. package/dist/gene/command.js +561 -0
  46. package/dist/gene/commit-apply-types.d.ts +13 -0
  47. package/dist/gene/commit-apply-types.js +1 -0
  48. package/dist/gene/commit-compound.d.ts +34 -0
  49. package/dist/gene/commit-compound.js +212 -0
  50. package/dist/gene/commit-counts.d.ts +41 -0
  51. package/dist/gene/commit-counts.js +70 -0
  52. package/dist/gene/commit-exec.d.ts +42 -0
  53. package/dist/gene/commit-exec.js +134 -0
  54. package/dist/gene/commit-head.d.ts +52 -0
  55. package/dist/gene/commit-head.js +97 -0
  56. package/dist/gene/commit-plan.d.ts +95 -0
  57. package/dist/gene/commit-plan.js +68 -0
  58. package/dist/gene/commit-prepare.d.ts +63 -0
  59. package/dist/gene/commit-prepare.js +159 -0
  60. package/dist/gene/commit-types.d.ts +234 -0
  61. package/dist/gene/commit-types.js +3 -0
  62. package/dist/gene/curator/agent.d.ts +137 -0
  63. package/dist/gene/curator/agent.js +203 -0
  64. package/dist/gene/curator/budget.d.ts +69 -0
  65. package/dist/gene/curator/budget.js +131 -0
  66. package/dist/gene/curator/conflicts.d.ts +54 -0
  67. package/dist/gene/curator/conflicts.js +143 -0
  68. package/dist/gene/curator/curator.d.ts +170 -0
  69. package/dist/gene/curator/curator.js +617 -0
  70. package/dist/gene/curator/deps.d.ts +34 -0
  71. package/dist/gene/curator/deps.js +48 -0
  72. package/dist/gene/curator/deterministic.d.ts +62 -0
  73. package/dist/gene/curator/deterministic.js +287 -0
  74. package/dist/gene/curator/executors.d.ts +36 -0
  75. package/dist/gene/curator/executors.js +379 -0
  76. package/dist/gene/curator/lanes.d.ts +52 -0
  77. package/dist/gene/curator/lanes.js +99 -0
  78. package/dist/gene/curator/lease.d.ts +76 -0
  79. package/dist/gene/curator/lease.js +171 -0
  80. package/dist/gene/curator/library.d.ts +36 -0
  81. package/dist/gene/curator/library.js +169 -0
  82. package/dist/gene/curator/lifecycle.d.ts +52 -0
  83. package/dist/gene/curator/lifecycle.js +109 -0
  84. package/dist/gene/curator/maintenance.d.ts +71 -0
  85. package/dist/gene/curator/maintenance.js +213 -0
  86. package/dist/gene/curator/probation.d.ts +51 -0
  87. package/dist/gene/curator/probation.js +71 -0
  88. package/dist/gene/curator/probe.d.ts +131 -0
  89. package/dist/gene/curator/probe.js +534 -0
  90. package/dist/gene/curator/prompt.d.ts +18 -0
  91. package/dist/gene/curator/prompt.js +128 -0
  92. package/dist/gene/curator/publish.d.ts +64 -0
  93. package/dist/gene/curator/publish.js +113 -0
  94. package/dist/gene/curator/recheck.d.ts +55 -0
  95. package/dist/gene/curator/recheck.js +104 -0
  96. package/dist/gene/curator/run-events.d.ts +63 -0
  97. package/dist/gene/curator/run-events.js +55 -0
  98. package/dist/gene/curator/similarity.d.ts +13 -0
  99. package/dist/gene/curator/similarity.js +46 -0
  100. package/dist/gene/curator/switches.d.ts +78 -0
  101. package/dist/gene/curator/switches.js +146 -0
  102. package/dist/gene/curator/task-context.d.ts +93 -0
  103. package/dist/gene/curator/task-context.js +63 -0
  104. package/dist/gene/curator/task-runner.d.ts +56 -0
  105. package/dist/gene/curator/task-runner.js +257 -0
  106. package/dist/gene/curator/tool-support.d.ts +112 -0
  107. package/dist/gene/curator/tool-support.js +206 -0
  108. package/dist/gene/curator/toolkit.d.ts +49 -0
  109. package/dist/gene/curator/toolkit.js +104 -0
  110. package/dist/gene/curator/tools-read.d.ts +4 -0
  111. package/dist/gene/curator/tools-read.js +177 -0
  112. package/dist/gene/curator/tools-release.d.ts +73 -0
  113. package/dist/gene/curator/tools-release.js +287 -0
  114. package/dist/gene/curator/tools-verify.d.ts +47 -0
  115. package/dist/gene/curator/tools-verify.js +243 -0
  116. package/dist/gene/curator/tools-write.d.ts +26 -0
  117. package/dist/gene/curator/tools-write.js +434 -0
  118. package/dist/gene/curator/tools.d.ts +23 -0
  119. package/dist/gene/curator/tools.js +21 -0
  120. package/dist/gene/curator/validate/common.d.ts +87 -0
  121. package/dist/gene/curator/validate/common.js +132 -0
  122. package/dist/gene/curator/validate/evidence-tokens.d.ts +24 -0
  123. package/dist/gene/curator/validate/evidence-tokens.js +217 -0
  124. package/dist/gene/curator/validate/index.d.ts +23 -0
  125. package/dist/gene/curator/validate/index.js +62 -0
  126. package/dist/gene/curator/validate/knowledge.d.ts +41 -0
  127. package/dist/gene/curator/validate/knowledge.js +255 -0
  128. package/dist/gene/curator/validate/live-check.d.ts +14 -0
  129. package/dist/gene/curator/validate/live-check.js +150 -0
  130. package/dist/gene/curator/validate/ports.d.ts +67 -0
  131. package/dist/gene/curator/validate/ports.js +1 -0
  132. package/dist/gene/curator/validate/prompts.d.ts +41 -0
  133. package/dist/gene/curator/validate/prompts.js +165 -0
  134. package/dist/gene/curator/validate/skill.d.ts +15 -0
  135. package/dist/gene/curator/validate/skill.js +251 -0
  136. package/dist/gene/curator/validate/tool.d.ts +6 -0
  137. package/dist/gene/curator/validate/tool.js +217 -0
  138. package/dist/gene/curator/validate/types.d.ts +90 -0
  139. package/dist/gene/curator/validate/types.js +1 -0
  140. package/dist/gene/curator/validator-ports.d.ts +38 -0
  141. package/dist/gene/curator/validator-ports.js +29 -0
  142. package/dist/gene/diag.d.ts +209 -0
  143. package/dist/gene/diag.js +549 -0
  144. package/dist/gene/env.d.ts +10 -0
  145. package/dist/gene/env.js +214 -0
  146. package/dist/gene/eval-recorder.d.ts +84 -0
  147. package/dist/gene/eval-recorder.js +222 -0
  148. package/dist/gene/explain-transport.d.ts +3 -0
  149. package/dist/gene/explain-transport.js +39 -0
  150. package/dist/gene/explain.d.ts +96 -0
  151. package/dist/gene/explain.js +293 -0
  152. package/dist/gene/fs.d.ts +39 -0
  153. package/dist/gene/fs.js +139 -0
  154. package/dist/gene/fsck.d.ts +68 -0
  155. package/dist/gene/fsck.js +134 -0
  156. package/dist/gene/gc-library-sweeps.d.ts +9 -0
  157. package/dist/gene/gc-library-sweeps.js +220 -0
  158. package/dist/gene/gc-rejected-set.d.ts +15 -0
  159. package/dist/gene/gc-rejected-set.js +63 -0
  160. package/dist/gene/gc-safe.d.ts +12 -0
  161. package/dist/gene/gc-safe.js +74 -0
  162. package/dist/gene/gc-scope-sweeps.d.ts +18 -0
  163. package/dist/gene/gc-scope-sweeps.js +297 -0
  164. package/dist/gene/gc-types.d.ts +55 -0
  165. package/dist/gene/gc-types.js +26 -0
  166. package/dist/gene/gc.d.ts +42 -0
  167. package/dist/gene/gc.js +129 -0
  168. package/dist/gene/gene-errors.d.ts +23 -0
  169. package/dist/gene/gene-errors.js +29 -0
  170. package/dist/gene/hints.d.ts +91 -0
  171. package/dist/gene/hints.js +394 -0
  172. package/dist/gene/hub.d.ts +149 -0
  173. package/dist/gene/hub.js +371 -0
  174. package/dist/gene/import-plan.d.ts +80 -0
  175. package/dist/gene/import-plan.js +294 -0
  176. package/dist/gene/import-proposal.d.ts +23 -0
  177. package/dist/gene/import-proposal.js +101 -0
  178. package/dist/gene/import-skill-port.d.ts +6 -0
  179. package/dist/gene/import-skill-port.js +53 -0
  180. package/dist/gene/import-sources.d.ts +48 -0
  181. package/dist/gene/import-sources.js +140 -0
  182. package/dist/gene/index-writer.d.ts +36 -0
  183. package/dist/gene/index-writer.js +101 -0
  184. package/dist/gene/learn/learn-call.d.ts +116 -0
  185. package/dist/gene/learn/learn-call.js +165 -0
  186. package/dist/gene/learn/learn-prompt.d.ts +58 -0
  187. package/dist/gene/learn/learn-prompt.js +254 -0
  188. package/dist/gene/learn/learner.d.ts +187 -0
  189. package/dist/gene/learn/learner.js +448 -0
  190. package/dist/gene/learn/ledger.d.ts +220 -0
  191. package/dist/gene/learn/ledger.js +394 -0
  192. package/dist/gene/learn/proposal-build.d.ts +83 -0
  193. package/dist/gene/learn/proposal-build.js +207 -0
  194. package/dist/gene/learn/proposal-guard.d.ts +43 -0
  195. package/dist/gene/learn/proposal-guard.js +37 -0
  196. package/dist/gene/learn/signals-port.d.ts +47 -0
  197. package/dist/gene/learn/signals-port.js +86 -0
  198. package/dist/gene/maintenance-paths.d.ts +7 -0
  199. package/dist/gene/maintenance-paths.js +20 -0
  200. package/dist/gene/maintenance-probation.d.ts +33 -0
  201. package/dist/gene/maintenance-probation.js +127 -0
  202. package/dist/gene/maintenance-proposals.d.ts +24 -0
  203. package/dist/gene/maintenance-proposals.js +68 -0
  204. package/dist/gene/maintenance-runner.d.ts +92 -0
  205. package/dist/gene/maintenance-runner.js +262 -0
  206. package/dist/gene/maintenance-tasks.d.ts +37 -0
  207. package/dist/gene/maintenance-tasks.js +95 -0
  208. package/dist/gene/manager-actions.d.ts +12 -0
  209. package/dist/gene/manager-actions.js +279 -0
  210. package/dist/gene/manager-approve.d.ts +29 -0
  211. package/dist/gene/manager-approve.js +84 -0
  212. package/dist/gene/manager-context.d.ts +90 -0
  213. package/dist/gene/manager-context.js +201 -0
  214. package/dist/gene/manager-detail.d.ts +17 -0
  215. package/dist/gene/manager-detail.js +313 -0
  216. package/dist/gene/manager-gc.d.ts +13 -0
  217. package/dist/gene/manager-gc.js +81 -0
  218. package/dist/gene/manager-library.d.ts +39 -0
  219. package/dist/gene/manager-library.js +90 -0
  220. package/dist/gene/manager-list.d.ts +27 -0
  221. package/dist/gene/manager-list.js +170 -0
  222. package/dist/gene/manager-queue.d.ts +16 -0
  223. package/dist/gene/manager-queue.js +124 -0
  224. package/dist/gene/manager-stats.d.ts +28 -0
  225. package/dist/gene/manager-stats.js +53 -0
  226. package/dist/gene/manager-view.d.ts +27 -0
  227. package/dist/gene/manager-view.js +124 -0
  228. package/dist/gene/manager.d.ts +56 -0
  229. package/dist/gene/manager.js +179 -0
  230. package/dist/gene/orphan-scopes.d.ts +37 -0
  231. package/dist/gene/orphan-scopes.js +150 -0
  232. package/dist/gene/paths.d.ts +73 -0
  233. package/dist/gene/paths.js +239 -0
  234. package/dist/gene/plan-content.d.ts +73 -0
  235. package/dist/gene/plan-content.js +522 -0
  236. package/dist/gene/plan-lifecycle.d.ts +29 -0
  237. package/dist/gene/plan-lifecycle.js +310 -0
  238. package/dist/gene/policy.d.ts +71 -0
  239. package/dist/gene/policy.js +313 -0
  240. package/dist/gene/project-learning.d.ts +25 -0
  241. package/dist/gene/project-learning.js +54 -0
  242. package/dist/gene/propagation.d.ts +48 -0
  243. package/dist/gene/propagation.js +45 -0
  244. package/dist/gene/queue-lock.d.ts +22 -0
  245. package/dist/gene/queue-lock.js +99 -0
  246. package/dist/gene/queue-record.d.ts +57 -0
  247. package/dist/gene/queue-record.js +145 -0
  248. package/dist/gene/queue.d.ts +235 -0
  249. package/dist/gene/queue.js +764 -0
  250. package/dist/gene/read.d.ts +61 -0
  251. package/dist/gene/read.js +252 -0
  252. package/dist/gene/runlog.d.ts +101 -0
  253. package/dist/gene/runlog.js +404 -0
  254. package/dist/gene/schema-lite.d.ts +24 -0
  255. package/dist/gene/schema-lite.js +159 -0
  256. package/dist/gene/scope-guard.d.ts +23 -0
  257. package/dist/gene/scope-guard.js +9 -0
  258. package/dist/gene/scope-lock.d.ts +48 -0
  259. package/dist/gene/scope-lock.js +222 -0
  260. package/dist/gene/scope-verify.d.ts +63 -0
  261. package/dist/gene/scope-verify.js +123 -0
  262. package/dist/gene/secrets.d.ts +43 -0
  263. package/dist/gene/secrets.js +161 -0
  264. package/dist/gene/service-context.d.ts +43 -0
  265. package/dist/gene/service-context.js +79 -0
  266. package/dist/gene/service-prepare.d.ts +25 -0
  267. package/dist/gene/service-prepare.js +219 -0
  268. package/dist/gene/service-types.d.ts +196 -0
  269. package/dist/gene/service-types.js +1 -0
  270. package/dist/gene/service-view.d.ts +41 -0
  271. package/dist/gene/service-view.js +69 -0
  272. package/dist/gene/service.d.ts +114 -0
  273. package/dist/gene/service.js +761 -0
  274. package/dist/gene/session-start.d.ts +36 -0
  275. package/dist/gene/session-start.js +212 -0
  276. package/dist/gene/store-port.d.ts +88 -0
  277. package/dist/gene/store-port.js +10 -0
  278. package/dist/gene/store-rows.d.ts +36 -0
  279. package/dist/gene/store-rows.js +72 -0
  280. package/dist/gene/store.d.ts +125 -0
  281. package/dist/gene/store.js +622 -0
  282. package/dist/gene/tombstones.d.ts +47 -0
  283. package/dist/gene/tombstones.js +61 -0
  284. package/dist/gene/tool-runner.d.ts +47 -0
  285. package/dist/gene/tool-runner.js +154 -0
  286. package/dist/gene/tool-screen.d.ts +41 -0
  287. package/dist/gene/tool-screen.js +227 -0
  288. package/dist/gene/tools.d.ts +112 -0
  289. package/dist/gene/tools.js +539 -0
  290. package/dist/gene/transfer.d.ts +85 -0
  291. package/dist/gene/transfer.js +433 -0
  292. package/dist/gene/ui-hints.d.ts +15 -0
  293. package/dist/gene/ui-hints.js +67 -0
  294. package/dist/gene/usage-fold-cursor.d.ts +24 -0
  295. package/dist/gene/usage-fold-cursor.js +115 -0
  296. package/dist/gene/usage-fold.d.ts +49 -0
  297. package/dist/gene/usage-fold.js +397 -0
  298. package/dist/gene/usage.d.ts +67 -0
  299. package/dist/gene/usage.js +231 -0
  300. package/dist/gene/version-service.d.ts +118 -0
  301. package/dist/gene/version-service.js +453 -0
  302. package/dist/gene/wiring-events.d.ts +43 -0
  303. package/dist/gene/wiring-events.js +113 -0
  304. package/dist/gene/wiring-models.d.ts +46 -0
  305. package/dist/gene/wiring-models.js +84 -0
  306. package/dist/gene/wiring.d.ts +200 -0
  307. package/dist/gene/wiring.js +764 -0
  308. package/dist/governance/prompts/orchestrator-block.js +3 -2
  309. package/dist/host/gene.d.ts +26 -0
  310. package/dist/host/gene.js +24 -0
  311. package/dist/host/index.d.ts +1 -0
  312. package/dist/host/index.js +1 -0
  313. package/dist/team/runtime.d.ts +5 -0
  314. package/dist/team/runtime.js +23 -0
  315. package/dist/team/subagent.d.ts +34 -0
  316. package/dist/team/subagent.js +39 -2
  317. package/dist/tools/index.d.ts +36 -2
  318. package/dist/tools/index.js +48 -7
  319. package/package.json +3 -3
@@ -0,0 +1,764 @@
1
+ /**
2
+ * The persistent proposal queue (gene-bank spec 10.5, 10.6, I-10, I-21, I-22).
3
+ *
4
+ * ASCII ONLY - the whole `gene/` tree is in `glyphs.test.ts::inScope`.
5
+ *
6
+ * THE DIRECTORY IS THE QUEUE. No database, no index file: scheduling is `readdir` plus a sort
7
+ * over file NAMES (`<p>-<createdAt 13>-<dedupe8>-<proposalId>.json`), and every state change is
8
+ * a `rename`. That is what makes it safe across processes without a lock: a TUI, a desktop
9
+ * session and an `exec` run can all enqueue and claim at once, and the only contention point
10
+ * is an atomic `rename(pending/x, claimed/<worker>/x)` that exactly one of them wins.
11
+ *
12
+ * pending/<name> waiting (maybe backed off: `notBefore` is inside the file)
13
+ * claimed/<worker>/<name> one worker owns it; its mtime is the heartbeat
14
+ * claimed/<worker>/<id>.cancel "stop, the basis changed" marker the curator checks (10.5.4)
15
+ * done/<name> settled, kept 7 days / 1000 entries for the activity page
16
+ * dead/<name> gave up or unreadable, kept 30 days, user may retry or discard
17
+ *
18
+ * REWRITE IN PLACE, THEN RENAME. Every transition that changes an item's content (a retry's
19
+ * `attempt` / `notBefore`, a settled item's `outcome`) first rewrites the file where it is and
20
+ * only then renames it to its next directory. The other order leaves a window in which another
21
+ * worker claims the file with the OLD content (no backoff, old attempt count).
22
+ *
23
+ * RENAME IS NOT THE LOCK. The spec leans on "a failed rename means someone else claimed it", which
24
+ * is true on POSIX and FALSE on Windows, where two renames of one source can both succeed (the
25
+ * file object is renamed through an open handle, so the loser just moves it again). Every
26
+ * transition of an item therefore runs under an exclusive-create lock file (queue-lock.ts):
27
+ * claim, merge, settle and recovery all take locks/<name>.lock first, so a merge can no longer
28
+ * re-create a file a claim just moved, and two claimers can no longer both win.
29
+ *
30
+ * NOTHING HERE THROWS. A corrupt file is moved to `dead/` and counted, an I/O failure becomes
31
+ * a typed result: the learner calls `enqueue` from a background task that must not be able to
32
+ * fail a user turn (I-24).
33
+ */
34
+ import { promises as nodeFs } from 'node:fs';
35
+ import { join } from 'node:path';
36
+ import { GENE_LIMITS } from '@aragon-agent/tui/model/gene/limits';
37
+ import { agingPriority, queueFileName } from '@aragon-agent/tui/model/gene/proposal';
38
+ import { withQueueLock } from './queue-lock.js';
39
+ import { coerceQueueRecord, fitRecordToLimit, isQueueName, mergeProposals, parseQueueName, redactProposal, } from './queue-record.js';
40
+ export { coerceQueueRecord, fitRecordToLimit, mergeProposals, parseQueueName, redactProposal };
41
+ import { claimedDir, geneRoot, queueDir, queueFile, } from './paths.js';
42
+ import { defaultIsPidAlive, ensureDir, listDir, moveInside, pathExists, readText, removeInside, retryOnWindowsContention, statOrNull, writeJsonStrict, } from './fs.js';
43
+ const REASON_TOKEN_RE = /[^a-z0-9_]/g;
44
+ /** Wire a queue to the version service's port. `reason` becomes a stable `detail` token. */
45
+ export function versionServiceFence(queue) {
46
+ const total = (r) => r.superseded.length + r.cancelled.length;
47
+ return {
48
+ supersedeStale: async ({ geneId, basisBelow }) => total(await queue.supersedeBelow(geneId, basisBelow)),
49
+ cancelForGene: async ({ geneId, reason }) => {
50
+ const token = reason.toLowerCase().replace(REASON_TOKEN_RE, '_').slice(0, 40);
51
+ const result = token.includes('forget') ? 'forgotten' : 'target_gone';
52
+ return total(await queue.cancelForGene(geneId, result, token || undefined));
53
+ },
54
+ };
55
+ }
56
+ export const QUEUE_MAX_ATTEMPTS = 4;
57
+ /** Backoff after the 1st, 2nd and 3rd transient failure; the 4th goes to `dead/`. */
58
+ export const QUEUE_BACKOFF_MS = [30_000, 120_000, 600_000];
59
+ const CANCEL_SUFFIX = '.cancel';
60
+ /** A settle waits for a short-lived lock holder (a claim step, a sweep) rather than failing. */
61
+ const SETTLE_LOCK_ATTEMPTS = 8;
62
+ const COUNTS_TTL_MS = 1000;
63
+ const DAY_MS = 24 * 60 * 60 * 1000;
64
+ function errorCode(error) {
65
+ const code = error?.code;
66
+ return typeof code === 'string' ? code : undefined;
67
+ }
68
+ function errorMessage(error) {
69
+ return error instanceof Error ? error.message : String(error);
70
+ }
71
+ function targetsGene(proposal, geneId) {
72
+ return (proposal.target?.id === geneId ||
73
+ proposal.mergeInto === geneId ||
74
+ (proposal.mergeFrom ?? []).includes(geneId));
75
+ }
76
+ // ---------------------------------------------------------------------------
77
+ // The queue
78
+ // ---------------------------------------------------------------------------
79
+ export class GeneQueue {
80
+ deps;
81
+ ctx;
82
+ root;
83
+ isPidAlive;
84
+ countsCache = null;
85
+ constructor(deps) {
86
+ this.deps = deps;
87
+ this.ctx = deps.ctx ?? {};
88
+ this.root = geneRoot(this.ctx);
89
+ this.isPidAlive = deps.isPidAlive ?? defaultIsPidAlive;
90
+ }
91
+ // ---- locking -----------------------------------------------------------
92
+ /** Run body while holding the item's lock. attempts > 1 waits for a short-lived holder. */
93
+ withLock(name, body, attempts = 1) {
94
+ return withQueueLock({
95
+ dir: join(this.root, 'queue', 'locks'),
96
+ pid: this.deps.pid,
97
+ attempts,
98
+ ...(this.deps.sleep ? { sleep: this.deps.sleep } : {}),
99
+ }, name, body);
100
+ }
101
+ // ---- enqueue ----------------------------------------------------------
102
+ /** Add a proposal, folding it into a pending one with the same dedupe key (10.5.3). */
103
+ async enqueue(proposal) {
104
+ try {
105
+ return await this.enqueueUnchecked(proposal);
106
+ }
107
+ catch (error) {
108
+ return { ok: false, reason: 'io', message: errorMessage(error) };
109
+ }
110
+ }
111
+ async enqueueUnchecked(proposal) {
112
+ const candidate = coerceQueueRecord({ schema: 1, proposal, attempt: 0, notBefore: 0 });
113
+ if (candidate === null)
114
+ return { ok: false, reason: 'invalid', message: 'not a well-formed proposal' };
115
+ const fitted = fitRecordToLimit(candidate);
116
+ if (fitted === null)
117
+ return { ok: false, reason: 'too_large', message: 'item exceeds the size limit' };
118
+ const incoming = fitted.record.proposal;
119
+ const mergedInto = await this.mergeIntoPending(incoming);
120
+ if (mergedInto !== null)
121
+ return { ok: true, merged: true, proposalId: incoming.id, mergedInto };
122
+ const room = await this.makeRoom(incoming);
123
+ if (room.full)
124
+ return { ok: false, reason: 'queue_full', message: 'queue is full' };
125
+ const path = queueFile('pending', queueFileName(incoming), this.ctx);
126
+ if (path === null)
127
+ return { ok: false, reason: 'invalid', message: 'unusable file name' };
128
+ await writeJsonStrict(path, fitted.record);
129
+ this.invalidateCounts();
130
+ const evicted = room.evicted === undefined ? {} : { evicted: room.evicted };
131
+ return { ok: true, merged: false, proposalId: incoming.id, ...evicted };
132
+ }
133
+ /** Returns the id of the pending proposal `incoming` was folded into, or null. */
134
+ async mergeIntoPending(incoming) {
135
+ const dedupe8 = parseQueueName(queueFileName(incoming))?.dedupe8 ?? '';
136
+ for (const parsed of await this.parsedPending()) {
137
+ if (parsed.dedupe8 !== dedupe8 || parsed.proposalId === incoming.id)
138
+ continue;
139
+ // Under the item's lock: a claim cannot move the file out from under the rewrite. A busy
140
+ // lock means the item is being claimed right now, so it is no longer a merge target.
141
+ const locked = await this.withLock(parsed.name, () => this.mergeInto(parsed, incoming));
142
+ if (locked.held && locked.value !== null)
143
+ return locked.value;
144
+ }
145
+ return null;
146
+ }
147
+ async mergeInto(parsed, incoming) {
148
+ const path = queueFile('pending', parsed.name, this.ctx);
149
+ const found = path === null ? null : await this.readRecord(path);
150
+ if (path === null || found === null || found.proposal.dedupeKey !== incoming.dedupeKey)
151
+ return null;
152
+ const fitted = fitRecordToLimit({ ...found, proposal: mergeProposals(found.proposal, incoming) });
153
+ if (fitted === null)
154
+ return null;
155
+ return (await this.rewritePending(path, parsed, fitted.record)) ? parsed.proposalId : null;
156
+ }
157
+ /** Rewrite a pending file; a changed priority changes the NAME, so the old file is renamed first. */
158
+ async rewritePending(path, parsed, record) {
159
+ const nextName = queueFileName(record.proposal);
160
+ let target = path;
161
+ if (nextName !== parsed.name) {
162
+ const renamed = queueFile('pending', nextName, this.ctx);
163
+ if (renamed === null || !(await this.tryMove(path, renamed)))
164
+ return false;
165
+ target = renamed;
166
+ }
167
+ await this.rewrite(target, record);
168
+ this.invalidateCounts();
169
+ return true;
170
+ }
171
+ /**
172
+ * Enforce the cap (10.5.3): at 500, an incoming p=4 is dropped; otherwise the OLDEST item of
173
+ * the worst class is evicted, provided that class is worse than the incoming one.
174
+ */
175
+ async makeRoom(incoming) {
176
+ const pending = await this.parsedPending();
177
+ if (pending.length < GENE_LIMITS.queueMax)
178
+ return { full: false };
179
+ const worst = Math.max(...pending.map((p) => p.priority));
180
+ if (worst <= incoming.priority)
181
+ return { full: true };
182
+ const victim = pending
183
+ .filter((p) => p.priority === worst)
184
+ .sort((a, b) => a.createdAt - b.createdAt || a.name.localeCompare(b.name))[0];
185
+ const settled = await this.settlePending(victim, { result: 'evicted', detail: 'queue_full' });
186
+ return settled ? { full: false, evicted: victim.proposalId } : { full: true };
187
+ }
188
+ // ---- claim / heartbeat / settle --------------------------------------
189
+ /**
190
+ * Take the next runnable item for `workerId`, or null. A lost race moves on to the next file.
191
+ * `skip` leaves an item pending (nothing is counted or moved): the curator uses it to keep
192
+ * cold-start imports from spending the budget live learning needs.
193
+ */
194
+ async claimNext(workerId, skip) {
195
+ const dir = claimedDir(workerId, this.ctx);
196
+ if (dir === null)
197
+ return null;
198
+ const now = this.deps.now();
199
+ for (const parsed of await this.scheduleOrder(now)) {
200
+ const from = queueFile('pending', parsed.name, this.ctx);
201
+ if (from === null)
202
+ continue;
203
+ const state = await this.readState(from);
204
+ if (state.kind === 'absent')
205
+ continue;
206
+ if (state.kind === 'corrupt') {
207
+ await this.quarantine(from, parsed.name);
208
+ continue;
209
+ }
210
+ if (state.record.notBefore > now)
211
+ continue;
212
+ if (skip !== undefined && (await skip(state.record.proposal)))
213
+ continue;
214
+ const claimed = await this.takeOwnership({ workerId, dir, from, parsed });
215
+ if (claimed !== null)
216
+ return claimed;
217
+ }
218
+ return null;
219
+ }
220
+ /**
221
+ * The claim itself, under the item's lock. The file is READ AGAIN here: between the scheduling
222
+ * peek and the lock another worker may have claimed it, a merge may have rewritten it, or a
223
+ * retry may have pushed its notBefore out - only what is true under the lock counts.
224
+ */
225
+ async takeOwnership(args) {
226
+ const locked = await this.withLock(args.parsed.name, async () => {
227
+ const state = await this.readState(args.from);
228
+ if (state.kind !== 'ok' || state.record.notBefore > this.deps.now())
229
+ return null;
230
+ await ensureDir(args.dir);
231
+ const to = join(args.dir, args.parsed.name);
232
+ if (!(await this.tryMove(args.from, to)))
233
+ return null;
234
+ const now = this.deps.now();
235
+ const item = {
236
+ ...state.record,
237
+ claimedBy: { workerId: args.workerId, pid: this.deps.pid, at: now, heartbeatAt: now },
238
+ };
239
+ await this.rewrite(to, item);
240
+ return { name: args.parsed.name, workerId: args.workerId, path: to, item };
241
+ });
242
+ if (!locked.held || locked.value === null)
243
+ return null;
244
+ this.invalidateCounts();
245
+ return locked.value;
246
+ }
247
+ /** Refresh the heartbeat. False when the claim is gone (recovered by someone else). */
248
+ async heartbeat(claimed) {
249
+ if (!(await pathExists(claimed.path)))
250
+ return false;
251
+ await this.touch(claimed.path);
252
+ return true;
253
+ }
254
+ /** True when a superseding commit asked the worker to stop (10.5.4). */
255
+ async isCancelled(claimed) {
256
+ return pathExists(this.cancelMarker(claimed.workerId, claimed.item.proposal.id));
257
+ }
258
+ /** Settle a claimed item into `done/`. False when the claim was lost in the meantime. */
259
+ async complete(claimed, outcome) {
260
+ const target = queueFile('done', claimed.name, this.ctx);
261
+ if (target === null)
262
+ return false;
263
+ const record = { ...claimed.item, outcome: { ...outcome, at: this.deps.now() } };
264
+ return this.settleClaimed(claimed, async () => {
265
+ await this.rewrite(claimed.path, record);
266
+ return (await this.tryMove(claimed.path, target)) ? { toPending: false } : null;
267
+ });
268
+ }
269
+ /**
270
+ * Settle a claimed item of a project that has been switched off for learning (I3-5, RV-42).
271
+ * NOT `complete` / `discard` / `fail`: those keep the whole proposal, evidence text included,
272
+ * in `done/` or `dead/`. The privacy switch promises that nothing about the session stays, so
273
+ * the proposal is reduced to its identity fields BEFORE it is moved.
274
+ */
275
+ async dropExcluded(claimed) {
276
+ const target = queueFile('done', claimed.name, this.ctx);
277
+ if (target === null)
278
+ return false;
279
+ const record = this.excludedRecord(claimed.item);
280
+ return this.settleClaimed(claimed, async () => {
281
+ await this.rewrite(claimed.path, record);
282
+ return (await this.tryMove(claimed.path, target)) ? { toPending: false } : null;
283
+ });
284
+ }
285
+ /**
286
+ * The user just switched learning off: settle every `pending/` and `dead/` proposal that
287
+ * `isExcluded` matches the same redacted way, without waiting for a claim (RV-56). Returns the
288
+ * proposal ids that were dropped. Items another process is working on (`claimed/`) are left to
289
+ * the curator's own checkpoints.
290
+ */
291
+ async dropExcludedWhere(isExcluded) {
292
+ const dropped = [];
293
+ for (const parsed of await this.parsedPending()) {
294
+ const path = queueFile('pending', parsed.name, this.ctx);
295
+ const record = path === null ? null : await this.readRecord(path);
296
+ if (record === null || !isExcluded(record.proposal))
297
+ continue;
298
+ if (await this.settlePending(parsed, { result: 'project_excluded' }, true))
299
+ dropped.push(record.proposal.id);
300
+ }
301
+ for (const entry of await this.list('dead')) {
302
+ if (entry.item === null || !isExcluded(entry.item.proposal))
303
+ continue;
304
+ const from = queueFile('dead', entry.name, this.ctx);
305
+ const to = queueFile('done', entry.name, this.ctx);
306
+ if (from === null || to === null)
307
+ continue;
308
+ await this.rewrite(from, this.excludedRecord(entry.item));
309
+ if (await this.tryMove(from, to))
310
+ dropped.push(entry.item.proposal.id);
311
+ }
312
+ if (dropped.length > 0)
313
+ this.invalidateCounts();
314
+ return dropped;
315
+ }
316
+ excludedRecord(item) {
317
+ const { claimedBy: _gone, lastError: _error, ...rest } = item;
318
+ return {
319
+ ...rest,
320
+ proposal: redactProposal(item.proposal),
321
+ outcome: { result: 'project_excluded', at: this.deps.now() },
322
+ };
323
+ }
324
+ /** Give an item back untouched (a paused curator): no attempt counted, optional delay. */
325
+ async release(claimed, notBefore = 0) {
326
+ const target = queueFile('pending', claimed.name, this.ctx);
327
+ if (target === null)
328
+ return false;
329
+ const { claimedBy: _gone, ...rest } = claimed.item;
330
+ return this.settleClaimed(claimed, async () => {
331
+ await this.rewrite(claimed.path, { ...rest, notBefore });
332
+ return (await this.tryMove(claimed.path, target)) ? { toPending: true } : null;
333
+ });
334
+ }
335
+ /** Record a failed attempt and apply the retry policy (10.5.5). */
336
+ async fail(claimed, failure) {
337
+ const next = this.applyFailure(claimed.item, failure);
338
+ const target = queueFile(next.state, claimed.name, this.ctx);
339
+ if (target === null)
340
+ return null;
341
+ const { claimedBy: _gone, ...rest } = next.record;
342
+ let result = null;
343
+ const moved = await this.settleClaimed(claimed, async () => {
344
+ await this.rewrite(claimed.path, next.state === 'pending' ? rest : next.record);
345
+ if (!(await this.tryMove(claimed.path, target)))
346
+ return null;
347
+ result = { state: next.state, attempt: next.record.attempt, notBefore: next.record.notBefore };
348
+ return { toPending: next.state === 'pending' };
349
+ });
350
+ return moved ? result : null;
351
+ }
352
+ /**
353
+ * Common frame of a claimed item's exit: under the lock, only if the claim is still ours (the
354
+ * file is still in OUR worker directory - a recovery that took it away makes this a no-op),
355
+ * run move, then tidy up. False when the claim was lost or the lock stayed busy.
356
+ */
357
+ async settleClaimed(claimed, move) {
358
+ const locked = await this.withLock(claimed.name, async () => ((await pathExists(claimed.path)) ? move() : null), SETTLE_LOCK_ATTEMPTS);
359
+ if (!locked.held || locked.value === null)
360
+ return false;
361
+ await this.cleanupAfterSettle(claimed, locked.value.toPending);
362
+ return true;
363
+ }
364
+ applyFailure(item, failure) {
365
+ const now = this.deps.now();
366
+ if (failure.kind === 'validation') {
367
+ // A failed validation is a verdict, not an infrastructure problem: never retried.
368
+ const outcome = { result: 'rejected', detail: 'validation_failed', at: now };
369
+ return { state: 'done', record: { ...item, lastError: failure.error, outcome } };
370
+ }
371
+ if (failure.kind === 'budget') {
372
+ // Waiting for the budget window to reset is not the item's fault: attempts stay as they were.
373
+ const waiting = { ...item, notBefore: failure.resetAt, lastError: 'budget_exhausted' };
374
+ return { state: 'pending', record: waiting };
375
+ }
376
+ const attempt = item.attempt + 1;
377
+ if (attempt >= QUEUE_MAX_ATTEMPTS) {
378
+ return { state: 'dead', record: { ...item, attempt, lastError: failure.error } };
379
+ }
380
+ const delay = QUEUE_BACKOFF_MS[attempt - 1] ?? QUEUE_BACKOFF_MS[QUEUE_BACKOFF_MS.length - 1];
381
+ return { state: 'pending', record: { ...item, attempt, notBefore: now + delay, lastError: failure.error } };
382
+ }
383
+ /**
384
+ * `returnedToPending`: the item itself now lives in `pending/` under this very name, so the
385
+ * stray sweep must not run - it would delete the item we just handed back.
386
+ */
387
+ async cleanupAfterSettle(claimed, returnedToPending = false) {
388
+ this.invalidateCounts();
389
+ await removeInside(this.root, this.cancelMarker(claimed.workerId, claimed.item.proposal.id));
390
+ if (returnedToPending)
391
+ return;
392
+ // Belt and braces: a lock reaped as stale mid-merge could have left a copy behind.
393
+ const stray = queueFile('pending', claimed.name, this.ctx);
394
+ if (stray !== null)
395
+ await removeInside(this.root, stray);
396
+ }
397
+ // ---- recovery ---------------------------------------------------------
398
+ /**
399
+ * Return claimed items whose worker is gone to `pending` with `attempt + 1` (10.5.5): no
400
+ * heartbeat for `claimStaleMs`, or the owning pid is dead. A poison item that keeps killing
401
+ * its worker reaches `QUEUE_MAX_ATTEMPTS` and is quarantined instead of looping forever.
402
+ */
403
+ async recoverStale() {
404
+ const recovered = [];
405
+ const now = this.deps.now();
406
+ for (const workerId of await listDir(queueDir('claimed', this.ctx))) {
407
+ const dir = claimedDir(workerId, this.ctx);
408
+ if (dir === null)
409
+ continue;
410
+ const names = await listDir(dir);
411
+ for (const name of names.filter(isQueueName)) {
412
+ const result = await this.recoverOne({ dir, name, workerId, now });
413
+ if (result !== null)
414
+ recovered.push(result);
415
+ }
416
+ await this.sweepOrphanMarkers(dir);
417
+ await nodeFs.rmdir(dir).catch(() => undefined);
418
+ }
419
+ if (recovered.length > 0)
420
+ this.invalidateCounts();
421
+ return recovered;
422
+ }
423
+ async recoverOne(args) {
424
+ // A busy lock means the owner (or another sweeper) is working on it THIS instant: alive.
425
+ const locked = await this.withLock(args.name, () => this.recoverLocked(args));
426
+ return locked.held ? locked.value : null;
427
+ }
428
+ /** No heartbeat for `claimStaleMs`, or the owning process is gone (a pid that is ours is alive). */
429
+ isAbandoned(record, silentForMs) {
430
+ const pid = record.claimedBy?.pid;
431
+ const ownerGone = pid !== undefined && pid !== this.deps.pid && !this.isPidAlive(pid);
432
+ return ownerGone || silentForMs > GENE_LIMITS.claimStaleMs;
433
+ }
434
+ async recoverLocked(args) {
435
+ const path = join(args.dir, args.name);
436
+ const stamp = await statOrNull(path);
437
+ if (stamp === null)
438
+ return null;
439
+ const state = await this.readState(path);
440
+ if (state.kind !== 'ok') {
441
+ if (state.kind === 'corrupt')
442
+ await this.quarantine(path, args.name);
443
+ return null;
444
+ }
445
+ const record = state.record;
446
+ if (!this.isAbandoned(record, args.now - stamp.mtimeMs))
447
+ return null;
448
+ const attempt = record.attempt + 1;
449
+ const { claimedBy: _gone, ...rest } = record;
450
+ const to = attempt >= QUEUE_MAX_ATTEMPTS ? 'dead' : 'pending';
451
+ await this.rewrite(path, { ...rest, attempt, lastError: 'claim_expired', notBefore: 0 });
452
+ const target = queueFile(to, args.name, this.ctx);
453
+ if (target === null || !(await this.tryMove(path, target)))
454
+ return null;
455
+ await removeInside(this.root, this.cancelMarker(args.workerId, record.proposal.id));
456
+ return { proposalId: record.proposal.id, to, attempt };
457
+ }
458
+ /** A `.cancel` marker whose item is gone (settled elsewhere) is just litter. */
459
+ async sweepOrphanMarkers(dir) {
460
+ const names = await listDir(dir);
461
+ const live = names.filter(isQueueName);
462
+ for (const name of names.filter((n) => n.endsWith(CANCEL_SUFFIX))) {
463
+ const id = name.slice(0, -CANCEL_SUFFIX.length);
464
+ if (!live.some((file) => file.endsWith(`-${id}.json`)))
465
+ await removeInside(this.root, join(dir, name));
466
+ }
467
+ }
468
+ // ---- fences (version service / deletion) ------------------------------
469
+ /** A person committed `newVersion`: proposals built on an older basis are obsolete (I-10). */
470
+ supersedeBelow(geneId, newVersion) {
471
+ return this.settleMatching((p) => p.target?.id === geneId &&
472
+ typeof p.target.basisVersion === 'number' &&
473
+ p.target.basisVersion < newVersion, { result: 'superseded', detail: 'human_edit' });
474
+ }
475
+ /** The gene was deleted or forgotten: nothing aimed at it can be applied (I-17). */
476
+ cancelForGene(geneId, reason, detail) {
477
+ const outcome = { result: reason, ...(detail ? { detail } : {}) };
478
+ return this.settleMatching((p) => targetsGene(p, geneId), outcome);
479
+ }
480
+ async settleMatching(matches, outcome) {
481
+ const result = { superseded: [], cancelled: [] };
482
+ for (const parsed of await this.parsedPending()) {
483
+ const path = queueFile('pending', parsed.name, this.ctx);
484
+ const record = path === null ? null : await this.readRecord(path);
485
+ if (record === null || !matches(record.proposal))
486
+ continue;
487
+ if (await this.settlePending(parsed, outcome))
488
+ result.superseded.push(record.proposal.id);
489
+ }
490
+ for (const entry of await this.list('claimed')) {
491
+ if (entry.item === null || entry.workerId === undefined || !matches(entry.item.proposal))
492
+ continue;
493
+ const marker = this.cancelMarker(entry.workerId, entry.item.proposal.id);
494
+ await writeJsonStrict(marker, { reason: outcome.result, at: this.deps.now() });
495
+ result.cancelled.push(entry.item.proposal.id);
496
+ }
497
+ this.invalidateCounts();
498
+ return result;
499
+ }
500
+ async settlePending(parsed, outcome, redact = false) {
501
+ const from = queueFile('pending', parsed.name, this.ctx);
502
+ const to = queueFile('done', parsed.name, this.ctx);
503
+ if (from === null || to === null)
504
+ return false;
505
+ const locked = await this.withLock(parsed.name, async () => {
506
+ const record = await this.readRecord(from);
507
+ if (record === null && !(await pathExists(from)))
508
+ return false;
509
+ const settled = record && {
510
+ ...record,
511
+ ...(redact ? { proposal: redactProposal(record.proposal) } : {}),
512
+ outcome: { ...outcome, at: this.deps.now() },
513
+ };
514
+ if (settled)
515
+ await this.rewrite(from, settled);
516
+ return this.tryMove(from, to);
517
+ }, SETTLE_LOCK_ATTEMPTS);
518
+ if (!locked.held || !locked.value)
519
+ return false;
520
+ this.invalidateCounts();
521
+ return true;
522
+ }
523
+ // ---- reading -----------------------------------------------------------
524
+ /** Counts per state, cached for one second (12.8); the queue's own writes drop the cache. */
525
+ async counts() {
526
+ const now = this.deps.now();
527
+ if (this.countsCache !== null && now - this.countsCache.at < COUNTS_TTL_MS && now >= this.countsCache.at) {
528
+ return this.countsCache.value;
529
+ }
530
+ const value = {
531
+ pending: await this.countNames(queueDir('pending', this.ctx)),
532
+ claimed: await this.countClaimed(),
533
+ dead: await this.countNames(queueDir('dead', this.ctx)),
534
+ done: await this.countNames(queueDir('done', this.ctx)),
535
+ };
536
+ this.countsCache = { at: now, value };
537
+ return value;
538
+ }
539
+ /** Entries of one state. `pending` is in scheduling order; `done` / `dead` newest first. */
540
+ async list(state) {
541
+ const entries = state === 'claimed' ? await this.listClaimed() : await this.listFlat(state);
542
+ const now = this.deps.now();
543
+ if (state === 'pending') {
544
+ return entries.sort((a, b) => this.scheduleCompare(a.parsed, b.parsed, now));
545
+ }
546
+ return entries.sort((a, b) => b.mtimeMs - a.mtimeMs);
547
+ }
548
+ /** Move a dead item back to `pending` with a clean slate (UI "Retry"). */
549
+ async retryDead(proposalId) {
550
+ const found = (await this.list('dead')).find((e) => e.parsed?.proposalId === proposalId);
551
+ if (!found || found.item === null)
552
+ return false;
553
+ const from = queueFile('dead', found.name, this.ctx);
554
+ const to = queueFile('pending', found.name, this.ctx);
555
+ if (from === null || to === null)
556
+ return false;
557
+ const { lastError: _e, claimedBy: _c, outcome: _o, ...rest } = found.item;
558
+ await this.rewrite(from, { ...rest, attempt: 0, notBefore: 0 });
559
+ const moved = await this.tryMove(from, to);
560
+ if (moved)
561
+ this.invalidateCounts();
562
+ return moved;
563
+ }
564
+ /** Drop a pending or dead item (UI "Discard"); a trace stays in `done/` until it ages out. */
565
+ async discard(proposalId) {
566
+ const pending = (await this.list('pending')).find((e) => e.parsed?.proposalId === proposalId);
567
+ if (pending?.parsed)
568
+ return this.settlePending(pending.parsed, { result: 'discarded' });
569
+ const dead = (await this.list('dead')).find((e) => e.parsed?.proposalId === proposalId);
570
+ const from = dead ? queueFile('dead', dead.name, this.ctx) : null;
571
+ const to = dead ? queueFile('done', dead.name, this.ctx) : null;
572
+ if (!dead || from === null || to === null)
573
+ return false;
574
+ if (dead.item !== null) {
575
+ await this.rewrite(from, { ...dead.item, outcome: { result: 'discarded', at: this.deps.now() } });
576
+ }
577
+ const moved = await this.tryMove(from, to);
578
+ if (moved)
579
+ this.invalidateCounts();
580
+ return moved;
581
+ }
582
+ /** Age out `done/` (7 days, 1000 entries) and `dead/` (30 days). Returns how many files went. */
583
+ async prune() {
584
+ const now = this.deps.now();
585
+ const done = await this.list('done');
586
+ const dead = await this.list('dead');
587
+ const doneTooOld = GENE_LIMITS.doneKeepDays * DAY_MS;
588
+ const deadTooOld = GENE_LIMITS.deadKeepDays * DAY_MS;
589
+ const doomed = [
590
+ ...done.filter((e, i) => i >= GENE_LIMITS.doneKeepMax || now - e.mtimeMs > doneTooOld),
591
+ ...dead.filter((e) => now - e.mtimeMs > deadTooOld),
592
+ ];
593
+ for (const entry of doomed) {
594
+ const path = queueFile(entry.state, entry.name, this.ctx);
595
+ if (path !== null)
596
+ await removeInside(this.root, path);
597
+ }
598
+ if (doomed.length > 0)
599
+ this.invalidateCounts();
600
+ return doomed.length;
601
+ }
602
+ // ---- internals ---------------------------------------------------------
603
+ async parsedPending() {
604
+ const names = await listDir(queueDir('pending', this.ctx));
605
+ return names.map(parseQueueName).filter((p) => p !== null);
606
+ }
607
+ scheduleCompare(a, b, now) {
608
+ if (a === null || b === null)
609
+ return a === b ? 0 : a === null ? 1 : -1;
610
+ const left = agingPriority(a.priority, a.createdAt, now);
611
+ const right = agingPriority(b.priority, b.createdAt, now);
612
+ return left - right || a.createdAt - b.createdAt || a.name.localeCompare(b.name);
613
+ }
614
+ async scheduleOrder(now) {
615
+ return (await this.parsedPending()).sort((a, b) => this.scheduleCompare(a, b, now));
616
+ }
617
+ async listFlat(state) {
618
+ const dir = queueDir(state, this.ctx);
619
+ const entries = [];
620
+ for (const name of await listDir(dir)) {
621
+ if (!isQueueName(name))
622
+ continue;
623
+ const path = join(dir, name);
624
+ entries.push(await this.entryOf({ state, name, path }));
625
+ }
626
+ return entries;
627
+ }
628
+ async listClaimed() {
629
+ const entries = [];
630
+ for (const workerId of await listDir(queueDir('claimed', this.ctx))) {
631
+ const dir = claimedDir(workerId, this.ctx);
632
+ if (dir === null)
633
+ continue;
634
+ for (const name of await listDir(dir)) {
635
+ if (!isQueueName(name))
636
+ continue;
637
+ entries.push(await this.entryOf({ state: 'claimed', name, path: join(dir, name), workerId }));
638
+ }
639
+ }
640
+ return entries;
641
+ }
642
+ async entryOf(args) {
643
+ const stamp = await statOrNull(args.path);
644
+ return {
645
+ state: args.state,
646
+ name: args.name,
647
+ parsed: parseQueueName(args.name),
648
+ ...(args.workerId !== undefined ? { workerId: args.workerId } : {}),
649
+ item: await this.readRecord(args.path),
650
+ mtimeMs: stamp?.mtimeMs ?? 0,
651
+ };
652
+ }
653
+ async countNames(dir) {
654
+ return (await listDir(dir)).filter(isQueueName).length;
655
+ }
656
+ async countClaimed() {
657
+ let total = 0;
658
+ for (const workerId of await listDir(queueDir('claimed', this.ctx))) {
659
+ const dir = claimedDir(workerId, this.ctx);
660
+ if (dir !== null)
661
+ total += await this.countNames(dir);
662
+ }
663
+ return total;
664
+ }
665
+ cancelMarker(workerId, proposalId) {
666
+ const dir = claimedDir(workerId, this.ctx) ?? join(queueDir('claimed', this.ctx), '_invalid');
667
+ return join(dir, `${proposalId}${CANCEL_SUFFIX}`);
668
+ }
669
+ invalidateCounts() {
670
+ this.countsCache = null;
671
+ }
672
+ /**
673
+ * `absent` covers "not there" AND "cannot be read right now" (a Windows scanner holding the
674
+ * file): neither may quarantine a healthy item. Only bytes we DID read and could not parse
675
+ * are `corrupt`.
676
+ */
677
+ async readState(path) {
678
+ const text = await readText(path);
679
+ if (text === null)
680
+ return { kind: 'absent' };
681
+ try {
682
+ const record = coerceQueueRecord(JSON.parse(text));
683
+ return record === null ? { kind: 'corrupt' } : { kind: 'ok', record };
684
+ }
685
+ catch {
686
+ return { kind: 'corrupt' };
687
+ }
688
+ }
689
+ async readRecord(path) {
690
+ const state = await this.readState(path);
691
+ return state.kind === 'ok' ? state.record : null;
692
+ }
693
+ /** Atomic rewrite, then stamp the mtime with the INJECTED clock (it is the heartbeat). */
694
+ async rewrite(path, record) {
695
+ await writeJsonStrict(path, record);
696
+ await this.touch(path);
697
+ }
698
+ async touch(path) {
699
+ const at = new Date(this.deps.now());
700
+ await retryOnWindowsContention(() => nodeFs.utimes(path, at, at)).catch(() => undefined);
701
+ }
702
+ /** `rename` that reports a lost race (source vanished) as false instead of throwing. */
703
+ async tryMove(from, to) {
704
+ try {
705
+ return await moveInside(this.root, from, to);
706
+ }
707
+ catch (error) {
708
+ const code = errorCode(error);
709
+ if (code === 'ENOENT' || code === 'EPERM' || code === 'EBUSY' || code === 'EACCES')
710
+ return false;
711
+ throw error;
712
+ }
713
+ }
714
+ /** An unreadable file cannot be given a `lastError`; it is moved to `dead/` as it is. */
715
+ async quarantine(from, name) {
716
+ const to = queueFile('dead', name, this.ctx);
717
+ if (to !== null)
718
+ await this.tryMove(from, to);
719
+ this.invalidateCounts();
720
+ }
721
+ }
722
+ // ---------------------------------------------------------------------------
723
+ // View mapping (the manager port)
724
+ // ---------------------------------------------------------------------------
725
+ const UNKNOWN_SCOPE = { kind: 'user' };
726
+ /** An unreadable file has no item to describe, so its row comes from its NAME alone. */
727
+ function unreadableView(entry, state) {
728
+ const parsed = entry.parsed;
729
+ return {
730
+ id: parsed?.proposalId ?? entry.name,
731
+ kind: 'maintenance',
732
+ scope: UNKNOWN_SCOPE,
733
+ priority: parsed?.priority ?? 4,
734
+ attempt: 0,
735
+ merged: 0,
736
+ createdAt: parsed?.createdAt ?? 0,
737
+ state,
738
+ lastError: 'unreadable',
739
+ why: 'This queue file could not be read.',
740
+ };
741
+ }
742
+ function itemView(item, state) {
743
+ const p = item.proposal;
744
+ return {
745
+ id: p.id,
746
+ kind: p.kind,
747
+ ...(p.type ? { type: p.type } : {}),
748
+ scope: p.scope,
749
+ ...(p.target?.id ? { target: p.target.id } : {}),
750
+ priority: p.priority,
751
+ attempt: item.attempt,
752
+ merged: p.merged,
753
+ createdAt: p.createdAt,
754
+ state,
755
+ ...(item.lastError ? { lastError: item.lastError } : {}),
756
+ why: p.why,
757
+ };
758
+ }
759
+ /** One row of the queue page. Unreadable files still get a row so the user can discard them. */
760
+ export function toQueueEntryView(entry) {
761
+ if (entry.state === 'done')
762
+ return null;
763
+ return entry.item === null ? unreadableView(entry, entry.state) : itemView(entry.item, entry.state);
764
+ }