@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,262 @@
1
+ /**
2
+ * `GeneMaintenanceRunner`: the schedule of everything only the lease holder does
3
+ * (gene-bank spec 10.4, 10.10; I-21, I-22, I-24).
4
+ *
5
+ * ASCII ONLY - the whole `gene/` tree is in `glyphs.test.ts::inScope`.
6
+ *
7
+ * ONE LOOP, ONE TIMER. `start()` arms an injectable, unref'd timer; every `tickMs` it calls
8
+ * `tick(now)`, which is also the whole testable surface: a test hands it a time and reads back
9
+ * which jobs ran. A job is due when `everyMs` has passed since it last STARTED (a failing job
10
+ * waits its turn like a healthy one instead of being retried every tick).
11
+ *
12
+ * job every what
13
+ * recover 30 s return claimed queue items whose worker died to `pending`
14
+ * fold 60 s usage logs -> stats shards (repeats while a backlog remains)
15
+ * capacity 60 s a type at 90% of `capPerType` -> one `maintenance` proposal (once an hour)
16
+ * reconcile 10 min index vs heads (deep), repair the disk, compact the journal when due
17
+ * probation 10 min S6: a gene that harmed twice and never helped -> a P0 `revoke` proposal
18
+ * gc 6 h the budgets of `gc.ts`, then the periodic `maintenance` proposal
19
+ *
20
+ * ONLY WHILE THE LEASE IS HELD. Every tick asks `isLeaseHolder()` first and again between jobs; a
21
+ * process that is not (or no longer is) the holder does nothing, and a process that BECOMES the
22
+ * holder starts every schedule from zero, so the first tick after taking over runs everything
23
+ * once ("session start"). At most one HEAVY job (reconcile, probation, gc) runs per tick so a
24
+ * takeover does not stall the event loop with three library walks back to back; a pause between
25
+ * jobs lets pending I/O callbacks through.
26
+ *
27
+ * NEVER THROWS INTO THE HOST (I-24). Each job is wrapped; a failure is reported to `onError` as an
28
+ * operation name and an error CLASS (no message, path or gene text - I-19) and the loop goes on.
29
+ */
30
+ import { GENE_TYPES } from '@aragon-agent/tui/model/gene/types';
31
+ import { GENE_LIMITS } from '@aragon-agent/tui/model/gene/limits';
32
+ import { ProbationSweeper } from './maintenance-probation.js';
33
+ import { checkCapacity, enqueueMaintenance, reconcileAndRepair, } from './maintenance-tasks.js';
34
+ import { errorToken, foldUsage } from './usage-fold.js';
35
+ import { SYSTEM_TIMER } from './usage.js';
36
+ const HOUR_MS = 3_600_000;
37
+ const MAX_FOLD_PASSES = 5;
38
+ export const DEFAULT_INTERVALS = {
39
+ tickMs: 5_000,
40
+ recoverMs: 30_000,
41
+ foldMs: GENE_LIMITS.foldIntervalMs,
42
+ capacityMs: 60_000,
43
+ reconcileMs: 10 * 60_000,
44
+ probationMs: 10 * 60_000,
45
+ gcMs: 6 * HOUR_MS,
46
+ capacityRenotifyMs: HOUR_MS,
47
+ };
48
+ const yieldToLoop = () => new Promise((resolve) => setImmediate(resolve));
49
+ function defaultRandom(n) {
50
+ return Math.floor(Math.random() * n);
51
+ }
52
+ export class GeneMaintenanceRunner {
53
+ deps;
54
+ intervals;
55
+ now;
56
+ timer;
57
+ lastStart = new Map();
58
+ capacityNotified = new Map();
59
+ foldFailures = new Map();
60
+ sweeper;
61
+ jobs;
62
+ handle = null;
63
+ running = false;
64
+ ticking = null;
65
+ wasLeader = false;
66
+ /** The time of the tick in progress: every job and every proposal it makes shares it. */
67
+ tickAt;
68
+ constructor(deps) {
69
+ this.deps = deps;
70
+ this.intervals = { ...DEFAULT_INTERVALS, ...deps.intervals };
71
+ this.now = deps.now ?? Date.now;
72
+ this.tickAt = this.now();
73
+ this.timer = deps.timer ?? SYSTEM_TIMER;
74
+ const random = deps.random ?? defaultRandom;
75
+ this.sweeper = new ProbationSweeper({
76
+ store: deps.store,
77
+ rows: () => this.publishedRows(),
78
+ enqueue: (proposal) => this.enqueue(proposal),
79
+ now: () => this.tickAt,
80
+ sessionId: deps.sessionId,
81
+ random,
82
+ ...(deps.probationLimit === undefined ? {} : { limit: deps.probationLimit }),
83
+ });
84
+ this.jobs = this.buildJobs();
85
+ }
86
+ // ---- lifecycle -----------------------------------------------------------
87
+ /** Arm the loop. Idempotent. The timer is unref'd, so it never keeps the process alive. */
88
+ start() {
89
+ if (this.running)
90
+ return;
91
+ this.running = true;
92
+ this.schedule();
93
+ }
94
+ /** Stop scheduling and wait for a tick in flight to finish. Never rejects. */
95
+ async stop() {
96
+ this.running = false;
97
+ if (this.handle !== null)
98
+ this.timer.clear(this.handle);
99
+ this.handle = null;
100
+ await this.ticking?.catch(() => undefined);
101
+ }
102
+ schedule() {
103
+ if (!this.running || this.handle !== null)
104
+ return;
105
+ this.handle = this.timer.set(() => {
106
+ this.handle = null;
107
+ void this.tick().finally(() => this.schedule());
108
+ }, this.intervals.tickMs);
109
+ }
110
+ // ---- the testable core ---------------------------------------------------
111
+ /** Run every due job once. `at` overrides the clock (tests). Never rejects. */
112
+ tick(at) {
113
+ if (this.ticking !== null) {
114
+ const leaseHolder = this.deps.isLeaseHolder();
115
+ return Promise.resolve({ leaseHolder, busy: true, ran: [], failed: [] });
116
+ }
117
+ const current = this.runDueSafely(at ?? this.now()).finally(() => {
118
+ this.ticking = null;
119
+ });
120
+ this.ticking = current;
121
+ return current;
122
+ }
123
+ /** Whatever goes wrong inside a tick - even `isLeaseHolder` throwing - stays inside it. */
124
+ async runDueSafely(at) {
125
+ try {
126
+ return await this.runDue(at);
127
+ }
128
+ catch (error) {
129
+ this.note('tick', errorToken(error));
130
+ return { leaseHolder: false, busy: false, ran: [], failed: [] };
131
+ }
132
+ }
133
+ async runDue(at) {
134
+ this.tickAt = at;
135
+ const leaseHolder = this.deps.isLeaseHolder();
136
+ const report = { leaseHolder, busy: false, ran: [], failed: [] };
137
+ if (!report.leaseHolder) {
138
+ this.wasLeader = false;
139
+ return report;
140
+ }
141
+ if (!this.wasLeader) {
142
+ this.wasLeader = true;
143
+ this.lastStart.clear();
144
+ }
145
+ let heavyRan = false;
146
+ for (const job of this.jobs) {
147
+ if (!this.isDue(job, at) || (job.heavy && heavyRan))
148
+ continue;
149
+ if (!this.deps.isLeaseHolder())
150
+ break;
151
+ this.lastStart.set(job.name, at);
152
+ heavyRan = heavyRan || job.heavy;
153
+ await this.runJob(job, report);
154
+ await yieldToLoop();
155
+ }
156
+ return report;
157
+ }
158
+ isDue(job, at) {
159
+ const last = this.lastStart.get(job.name);
160
+ return last === undefined || at - last >= job.everyMs;
161
+ }
162
+ async runJob(job, report) {
163
+ try {
164
+ await job.run();
165
+ report.ran.push(job.name);
166
+ }
167
+ catch (error) {
168
+ report.failed.push(job.name);
169
+ this.note(job.name, errorToken(error));
170
+ }
171
+ }
172
+ note(operation, errorClass) {
173
+ try {
174
+ this.deps.onError?.(operation, errorClass);
175
+ }
176
+ catch {
177
+ /* a broken logger must not break the loop */
178
+ }
179
+ }
180
+ // ---- the jobs --------------------------------------------------------------
181
+ buildJobs() {
182
+ const every = this.intervals;
183
+ return [
184
+ { name: 'recover', everyMs: every.recoverMs, heavy: false, run: () => this.recover() },
185
+ { name: 'fold', everyMs: every.foldMs, heavy: false, run: () => this.fold() },
186
+ { name: 'capacity', everyMs: every.capacityMs, heavy: false, run: () => this.capacity() },
187
+ { name: 'reconcile', everyMs: every.reconcileMs, heavy: true, run: () => this.reconcile() },
188
+ { name: 'probation', everyMs: every.probationMs, heavy: true, run: () => this.probation() },
189
+ { name: 'gc', everyMs: every.gcMs, heavy: true, run: () => this.collectGarbage() },
190
+ ];
191
+ }
192
+ enqueueDeps() {
193
+ return {
194
+ enqueue: (proposal) => this.enqueue(proposal),
195
+ now: () => this.tickAt,
196
+ sessionId: this.deps.sessionId,
197
+ random: this.deps.random ?? defaultRandom,
198
+ };
199
+ }
200
+ async enqueue(proposal) {
201
+ return { ok: (await this.deps.queue.enqueue(proposal)).ok };
202
+ }
203
+ publishedRows() {
204
+ return [...this.deps.catalog.rows()].filter((row) => row.status === 'published');
205
+ }
206
+ async recover() {
207
+ await this.deps.queue.recoverStale();
208
+ }
209
+ /** Fold; while a backlog remains, fold again (bounded) instead of waiting a minute per batch. */
210
+ async fold() {
211
+ for (let pass = 0; pass < MAX_FOLD_PASSES; pass += 1) {
212
+ const result = await foldUsage({
213
+ ...this.deps.fold,
214
+ store: this.deps.store,
215
+ locks: this.deps.locks,
216
+ isLeaseHolder: this.deps.isLeaseHolder,
217
+ now: () => this.tickAt,
218
+ failures: this.foldFailures,
219
+ });
220
+ for (const error of result.errors)
221
+ this.note('fold', error.split(':')[1] ?? 'unknown');
222
+ if (!result.moreAvailable || result.skipped !== undefined || result.errors.length > 0)
223
+ return;
224
+ await yieldToLoop();
225
+ }
226
+ }
227
+ async capacity() {
228
+ const full = await checkCapacity({
229
+ totals: () => this.deps.service.totals(),
230
+ capPerType: () => this.deps.service.limits().capPerType,
231
+ });
232
+ const at = this.tickAt;
233
+ for (const type of GENE_TYPES)
234
+ if (!full.includes(type))
235
+ this.capacityNotified.delete(type);
236
+ for (const type of full) {
237
+ const last = this.capacityNotified.get(type);
238
+ if (last !== undefined && at - last < this.intervals.capacityRenotifyMs)
239
+ continue;
240
+ this.capacityNotified.set(type, at);
241
+ await enqueueMaintenance(this.enqueueDeps(), {
242
+ subject: `capacity:${type}`,
243
+ why: `The ${type} genes reached 90 percent of the library limit; tidy them.`,
244
+ });
245
+ }
246
+ }
247
+ async reconcile() {
248
+ await this.deps.catalog.catchUp();
249
+ await reconcileAndRepair(this.deps.catalog, this.deps.service);
250
+ await this.deps.compactor.compactIfNeeded(this.deps.catalog);
251
+ }
252
+ async probation() {
253
+ await this.sweeper.sweep();
254
+ }
255
+ async collectGarbage() {
256
+ await this.deps.gc.run();
257
+ await enqueueMaintenance(this.enqueueDeps(), {
258
+ subject: 'periodic',
259
+ why: 'Scheduled maintenance: look for duplicate genes, low-value genes and promotions.',
260
+ });
261
+ }
262
+ }
@@ -0,0 +1,37 @@
1
+ import type { GeneProposal, GeneType } from '@aragon-agent/tui/model/gene/types';
2
+ import type { GeneCatalog, ReconcileReport } from './catalog.js';
3
+ import type { GeneVersionService } from './version-service.js';
4
+ export interface RepairReport {
5
+ reconcile: ReconcileReport;
6
+ scopesVerified: number;
7
+ scopesRepaired: number;
8
+ countsRebuilt: number;
9
+ }
10
+ type RepairCatalog = Pick<GeneCatalog, 'reconcile' | 'scopes' | 'countsFor' | 'isLoaded'>;
11
+ type RepairService = Pick<GeneVersionService, 'verifyScope' | 'reconcileScope' | 'rebuildScopeCounts' | 'store'>;
12
+ export declare function reconcileAndRepair(catalog: RepairCatalog, service: RepairService): Promise<RepairReport>;
13
+ export interface CapacityDeps {
14
+ totals: () => Promise<{
15
+ published: Record<GeneType, number>;
16
+ }>;
17
+ capPerType: () => number;
18
+ }
19
+ /** Types whose published count is at or past 90% of the cap (7.2 threshold warning). */
20
+ export declare function checkCapacity(deps: CapacityDeps): Promise<GeneType[]>;
21
+ export interface MaintenanceEnqueueDeps {
22
+ enqueue: (proposal: GeneProposal) => Promise<{
23
+ ok: boolean;
24
+ }>;
25
+ now: () => number;
26
+ sessionId: string;
27
+ random: (n: number) => number;
28
+ }
29
+ /**
30
+ * One `maintenance` proposal in the `user` lane (P4). `subject` keeps the periodic one and each
31
+ * capacity warning distinct, and identical pending requests fold into one in the queue.
32
+ */
33
+ export declare function enqueueMaintenance(deps: MaintenanceEnqueueDeps, request: {
34
+ subject: string;
35
+ why: string;
36
+ }): Promise<boolean>;
37
+ export {};
@@ -0,0 +1,95 @@
1
+ /**
2
+ * The smaller jobs of the background maintenance (gene-bank spec 7.2, 7.7, 10.10).
3
+ *
4
+ * reconcileAndRepair compare the index with the head files, repair what the disk lacks
5
+ * checkCapacity which types reached 90% of `capPerType`
6
+ * enqueueMaintenance the model-free request that makes the curator look at the library
7
+ *
8
+ * ASCII ONLY - the whole `gene/` tree is in `glyphs.test.ts::inScope`.
9
+ *
10
+ * RECONCILE REPAIRS THE DISK, NOT JUST THE MEMORY. `GeneCatalog.reconcile` fixes the lease
11
+ * holder's in-memory index and returns counts; it writes nothing. Every OTHER process reads the
12
+ * derived files, so a drift the lease holder noticed only in memory would stay wrong for them.
13
+ * When the report shows any drift the scopes are verified against their heads and a scope whose
14
+ * index lines are missing, stale or extra goes through `GeneVersionService.reconcileScope`
15
+ * (journal lines + counts + interrupted moves, under the scope lock). Separately, and cheaply,
16
+ * `counts.json` is compared with the counts the catalog derives from its rows: a crash between a
17
+ * journal append and the counts write shows up there and nowhere else, and `rebuildScopeCounts`
18
+ * fixes it.
19
+ */
20
+ import { GENE_CURATION } from '@aragon-agent/tui/model/gene/limits';
21
+ import { GENE_TYPES } from '@aragon-agent/tui/model/gene/types';
22
+ import { buildSystemProposal } from './maintenance-proposals.js';
23
+ function hasDrift(report) {
24
+ return report.added + report.removed + report.repaired > 0;
25
+ }
26
+ async function repairIndexOf(service, scope) {
27
+ const verified = await service.verifyScope(scope);
28
+ if (!verified.ok)
29
+ return false;
30
+ const { missing, stale, extra } = verified.value.index;
31
+ if (missing.length + stale.length + extra.length === 0)
32
+ return false;
33
+ return (await service.reconcileScope(scope)).ok;
34
+ }
35
+ /** `counts.json` against what the catalog's own rows say; true when the file was rebuilt. */
36
+ async function repairCountsOf(catalog, service, scope) {
37
+ const stored = await service.store.readCounts(scope);
38
+ const derived = catalog.countsFor(scope);
39
+ const same = (a, b) => GENE_TYPES.every((type) => a[type] === b[type]);
40
+ const matches = stored !== null &&
41
+ same(stored.published, derived.published) &&
42
+ same(stored.pinned, derived.pinned) &&
43
+ GENE_TYPES.reduce((n, t) => n + (stored.candidatesByType?.[t] ?? 0), 0) === derived.candidates;
44
+ if (matches)
45
+ return false;
46
+ return (await service.rebuildScopeCounts(scope)).ok;
47
+ }
48
+ export async function reconcileAndRepair(catalog, service) {
49
+ const reconcile = await catalog.reconcile({ deep: true });
50
+ const report = {
51
+ reconcile,
52
+ scopesVerified: 0,
53
+ scopesRepaired: 0,
54
+ countsRebuilt: 0,
55
+ };
56
+ const scopes = catalog.scopes().filter((s) => s.kind !== 'team');
57
+ for (const scope of scopes) {
58
+ if (hasDrift(reconcile)) {
59
+ report.scopesVerified += 1;
60
+ if (await repairIndexOf(service, scope))
61
+ report.scopesRepaired += 1;
62
+ }
63
+ // An unloaded catalog derives zeros; comparing them with the file would "repair" a good one.
64
+ if (catalog.isLoaded() && (await repairCountsOf(catalog, service, scope))) {
65
+ report.countsRebuilt += 1;
66
+ }
67
+ }
68
+ return report;
69
+ }
70
+ /** Types whose published count is at or past 90% of the cap (7.2 threshold warning). */
71
+ export async function checkCapacity(deps) {
72
+ const cap = deps.capPerType();
73
+ if (!(cap > 0))
74
+ return [];
75
+ const totals = await deps.totals();
76
+ return GENE_TYPES.filter((type) => totals.published[type] / cap >= GENE_CURATION.capWarnShare);
77
+ }
78
+ /**
79
+ * One `maintenance` proposal in the `user` lane (P4). `subject` keeps the periodic one and each
80
+ * capacity warning distinct, and identical pending requests fold into one in the queue.
81
+ */
82
+ export async function enqueueMaintenance(deps, request) {
83
+ const proposal = buildSystemProposal({
84
+ kind: 'maintenance',
85
+ scope: { kind: 'user' },
86
+ now: deps.now(),
87
+ sessionId: deps.sessionId,
88
+ random: deps.random,
89
+ goal: 'Scheduled library maintenance.',
90
+ why: request.why,
91
+ expectedBenefit: 'Merges duplicates and archives low-value genes before the library fills.',
92
+ subject: request.subject,
93
+ });
94
+ return (await deps.enqueue(proposal)).ok;
95
+ }
@@ -0,0 +1,12 @@
1
+ import type { GeneActionOutcome, GeneActionRequest, GeneDraftCheck, GeneSaveOutcome, GeneSaveRequest } from '@aragon-agent/tui/model/gene/port';
2
+ import type { GeneResult } from '@aragon-agent/tui/model/gene/types';
3
+ import type { GeneExpect } from './commit-types.js';
4
+ import { type ManagerCore } from './manager-context.js';
5
+ /** `0` = "unchecked"; 1 or more = the version the caller saw. */
6
+ export declare function expectOf(expectedVersion: number | undefined): GeneExpect | undefined;
7
+ /** `save`: create (no `id`) or edit. The editor's draft becomes a version, not a file edit. */
8
+ export declare function saveGene(core: ManagerCore, req: GeneSaveRequest): Promise<GeneResult<GeneSaveOutcome>>;
9
+ /** `action`: one of the twelve human operations of 7.6 on one gene. */
10
+ export declare function runGeneAction(core: ManagerCore, req: GeneActionRequest): Promise<GeneResult<GeneActionOutcome>>;
11
+ /** `checkDraft`: live validation of an unsaved draft, plus the risk the static screen derives. */
12
+ export declare function checkDraft(core: ManagerCore, req: Pick<GeneSaveRequest, 'type' | 'scope' | 'content'>): Promise<GeneResult<GeneDraftCheck>>;
@@ -0,0 +1,279 @@
1
+ /**
2
+ * The manager's writes: `save`, `action` and `checkDraft` (gene-bank spec 7.6, 12.4, 16.6).
3
+ *
4
+ * ASCII ONLY - the whole `gene/` tree is in `glyphs.test.ts::inScope`.
5
+ *
6
+ * EVERY WRITE IS A `GeneVersionService.commit` AS THE USER. Nothing here edits a file. The
7
+ * service owns the compare-and-swap, the English / secret / length screens, the oversight fence,
8
+ * the capacity and pin budgets and the proposal fencing; this file only translates a UI request
9
+ * into the right `GeneChange`, which is why it can stay small and why one set of version-service
10
+ * tests proves "nothing writes a gene any other way".
11
+ *
12
+ * `expectedVersion` IS THE VERSION THE PERSON WAS LOOKING AT. A value of 1 or more is compared
13
+ * with the head's `latestVersion` inside the lock and a mismatch is `GENE_STALE_BASIS`, never a
14
+ * retry. 0 means "I did not read it" (a typed command that never opened the gene) and skips the
15
+ * comparison: a person's explicit command may overwrite, an automation never may (I-10).
16
+ *
17
+ * A STALE ANSWER CARRIES THE FRESH HEAD'S VERSION in its `detail` (`version latest=4`), so an
18
+ * editor can offer "keep mine / take theirs / merge" without a second round trip.
19
+ */
20
+ import { dedupeKeyOf } from '@aragon-agent/tui/model/gene/proposal';
21
+ import { mintProposalId } from '@aragon-agent/tui/model/gene/ids';
22
+ import { validateGeneContent, } from '@aragon-agent/tui/model/gene/validate';
23
+ import { geneFail, geneOk } from './gene-errors.js';
24
+ import { approveCandidate, MANAGER_ACTOR } from './manager-approve.js';
25
+ import { findGene } from './manager-context.js';
26
+ import { geneLooksLikeSecret } from './secrets.js';
27
+ import { defaultRandom } from './service-prepare.js';
28
+ import { screenToolExec } from './tool-screen.js';
29
+ const DEFAULT_SAVE_REASON = 'manual edit';
30
+ /** `0` = "unchecked"; 1 or more = the version the caller saw. */
31
+ export function expectOf(expectedVersion) {
32
+ if (expectedVersion === undefined || expectedVersion < 1)
33
+ return undefined;
34
+ return { version: expectedVersion };
35
+ }
36
+ /** A stale-basis failure names the head's current version so the caller can reload at once. */
37
+ async function withFreshness(core, where, result) {
38
+ if (result.ok || result.code !== 'GENE_STALE_BASIS')
39
+ return result;
40
+ const read = await core.lib.store.readHead(where.scope, where.id);
41
+ if (read === null)
42
+ return result;
43
+ const was = result.detail ?? 'version';
44
+ return geneFail('GENE_STALE_BASIS', result.message, `${was} latest=${read.head.latestVersion}`);
45
+ }
46
+ function outcomeOf(done) {
47
+ const out = { id: done.id };
48
+ if (done.version !== undefined)
49
+ out.version = done.version;
50
+ if (done.also !== undefined && done.also.length > 0)
51
+ out.also = done.also;
52
+ return out;
53
+ }
54
+ // ---------------------------------------------------------------------------
55
+ // save
56
+ // ---------------------------------------------------------------------------
57
+ async function touchProject(core, scope) {
58
+ const project = core.project();
59
+ if (scope.kind !== 'project' || project === null || scope.key !== project.key)
60
+ return;
61
+ try {
62
+ await core.lib.store.touchProjectMeta(scope, project, core.now());
63
+ }
64
+ catch {
65
+ /* the label is cosmetic: a save must not fail because project.json could not be written */
66
+ }
67
+ }
68
+ async function createGene(core, req) {
69
+ await touchProject(core, req.scope);
70
+ const done = await core.lib.versions.commit({
71
+ op: 'create',
72
+ type: req.type,
73
+ scope: req.scope,
74
+ content: req.content,
75
+ reason: req.reason.trim() || DEFAULT_SAVE_REASON,
76
+ ...(req.confirmHighRisk === true ? { confirmHighRisk: true } : {}),
77
+ }, MANAGER_ACTOR);
78
+ if (!done.ok)
79
+ return done;
80
+ return geneOk({ id: done.value.id, version: done.value.version ?? 1, supersededProposals: 0 });
81
+ }
82
+ async function editGene(core, req, id) {
83
+ const found = await findGene(core, req.target, id);
84
+ if (!found.ok)
85
+ return found;
86
+ const { scope } = found.value;
87
+ const done = await core.lib.versions.commit({
88
+ op: 'edit',
89
+ scope,
90
+ id,
91
+ content: req.content,
92
+ reason: req.reason.trim() || DEFAULT_SAVE_REASON,
93
+ ...(req.confirmHighRisk === true ? { confirmHighRisk: true } : {}),
94
+ }, MANAGER_ACTOR, expectOf(req.expectedVersion));
95
+ if (!done.ok)
96
+ return withFreshness(core, { scope, id }, done);
97
+ return geneOk({
98
+ id: done.value.id,
99
+ version: done.value.version ?? found.value.read.head.latestVersion,
100
+ supersededProposals: done.value.supersededProposals ?? 0,
101
+ });
102
+ }
103
+ /** `save`: create (no `id`) or edit. The editor's draft becomes a version, not a file edit. */
104
+ export function saveGene(core, req) {
105
+ return req.id === undefined ? createGene(core, req) : editGene(core, req, req.id);
106
+ }
107
+ /** The newest version below the served one that was ever published: the default rollback. */
108
+ async function previousPublished(core, found) {
109
+ const { scope, read } = found;
110
+ const current = read.head.currentVersion;
111
+ if (current === null)
112
+ return null;
113
+ const numbers = await core.lib.store.listVersionNumbers(scope, read.head.id);
114
+ for (const n of [...numbers].reverse()) {
115
+ if (n >= current)
116
+ continue;
117
+ const version = await core.lib.store.readVersion(scope, read.head.id, n);
118
+ if (version?.state === 'superseded' || version?.state === 'published')
119
+ return n;
120
+ }
121
+ return null;
122
+ }
123
+ async function rollbackChange(input) {
124
+ const { found, args } = input;
125
+ const { scope, read } = found;
126
+ const toVersion = args.toVersion ?? (await previousPublished(input.core, found));
127
+ if (toVersion === null) {
128
+ const message = 'There is no earlier published version to roll back to.';
129
+ return geneFail('GENE_NOT_FOUND', message, 'no_previous');
130
+ }
131
+ return geneOk({ op: 'rollback', scope, id: read.head.id, toVersion });
132
+ }
133
+ function promoteChange(input) {
134
+ const { found, args } = input;
135
+ if (args.to === undefined) {
136
+ return geneFail('GENE_SCOPE_FORBIDDEN', 'A target scope is required.', 'missing_to');
137
+ }
138
+ return geneOk({
139
+ op: 'promote',
140
+ scope: found.scope,
141
+ id: found.read.head.id,
142
+ to: args.to,
143
+ ...(args.withDependencies === true ? { withDependencies: true } : {}),
144
+ });
145
+ }
146
+ /** The gene an action is about, in the shape every `GeneChange` with a target carries. */
147
+ function targetOf(input) {
148
+ return { scope: input.found.scope, id: input.found.read.head.id };
149
+ }
150
+ const change = (value) => geneOk(value);
151
+ /**
152
+ * One builder per plain action. A table, not a switch: each row is one `GeneChange` and nothing
153
+ * else, so adding the thirteenth human operation is one row and one test.
154
+ */
155
+ const CHANGE_BUILDERS = {
156
+ pin: (i) => change({
157
+ op: 'setPinned',
158
+ ...targetOf(i),
159
+ pinned: true,
160
+ pinReason: i.args.pinReason ?? 'user_requirement',
161
+ }),
162
+ unpin: (i) => change({ op: 'setPinned', ...targetOf(i), pinned: false }),
163
+ archive: (i) => change({ op: 'archive', ...targetOf(i), reason: i.args.reason ?? 'Archived by the user.' }),
164
+ restore: (i) => change({ op: 'restore', ...targetOf(i), ...(i.args.reason ? { reason: i.args.reason } : {}) }),
165
+ rollback: rollbackChange,
166
+ delete: (i) => change({ op: 'delete', ...targetOf(i) }),
167
+ forget: (i) => change({
168
+ op: 'forget',
169
+ ...targetOf(i),
170
+ ...(i.args.allScopes === true ? { allScopes: true } : {}),
171
+ }),
172
+ confirm: (i) => change({ op: 'confirmPreference', ...targetOf(i) }),
173
+ promote: promoteChange,
174
+ reject: (i) => change({
175
+ op: 'rejectCandidate',
176
+ ...targetOf(i),
177
+ reason: i.args.reason ?? 'Rejected by the user.',
178
+ }),
179
+ };
180
+ /** Everything except `recheck` and `approve`, which are not one plain commit. */
181
+ async function changeFor(action, input) {
182
+ return CHANGE_BUILDERS[action](input);
183
+ }
184
+ function recheckProposal(core, found) {
185
+ const { scope, read } = found;
186
+ const head = read.head;
187
+ const now = core.now();
188
+ const basisVersion = head.latestVersion;
189
+ return {
190
+ schema: 1,
191
+ id: mintProposalId(defaultRandom),
192
+ createdAt: now,
193
+ kind: 'recheck',
194
+ type: head.type,
195
+ scope,
196
+ target: { id: head.id, basisVersion },
197
+ origin: {
198
+ source: 'user_flag',
199
+ sessionId: core.options.sessionId,
200
+ runId: `manager-${now}`,
201
+ goal: 'A re-check was requested from the gene manager.',
202
+ },
203
+ why: 'A person asked for this gene to be checked again.',
204
+ expectedBenefit: 'Confirms the gene is still correct and applies to the current setup.',
205
+ evidence: [],
206
+ priority: 2,
207
+ dedupeKey: dedupeKeyOf({ kind: 'recheck', scope, targetId: head.id, basisVersion }),
208
+ merged: 0,
209
+ };
210
+ }
211
+ async function enqueueRecheck(core, found) {
212
+ if (found.archived) {
213
+ return geneFail('GENE_NOT_FOUND', 'An archived gene cannot be re-checked.', 'archived');
214
+ }
215
+ const queued = await core.lib.queue.enqueue(recheckProposal(core, found));
216
+ if (!queued.ok) {
217
+ return geneFail('GENE_UNAVAILABLE', 'The re-check could not be queued.', queued.reason);
218
+ }
219
+ return geneOk({ id: found.read.head.id });
220
+ }
221
+ /** `action`: one of the twelve human operations of 7.6 on one gene. */
222
+ export async function runGeneAction(core, req) {
223
+ const found = await findGene(core, req.target, req.id);
224
+ if (!found.ok)
225
+ return found;
226
+ const where = { scope: found.value.scope, id: req.id };
227
+ if (req.action === 'recheck')
228
+ return enqueueRecheck(core, found.value);
229
+ const expect = expectOf(req.expectedVersion);
230
+ if (req.action === 'approve') {
231
+ return withFreshness(core, where, await approveCandidate(core, found.value, expect));
232
+ }
233
+ const change = await changeFor(req.action, { core, found: found.value, args: req.args ?? {} });
234
+ if (!change.ok)
235
+ return change;
236
+ const done = await core.lib.versions.commit(change.value, MANAGER_ACTOR, expect);
237
+ if (!done.ok)
238
+ return withFreshness(core, where, done);
239
+ return geneOk(outcomeOf(done.value));
240
+ }
241
+ // ---------------------------------------------------------------------------
242
+ // checkDraft
243
+ // ---------------------------------------------------------------------------
244
+ function toolPayloadOf(req) {
245
+ if (req.type !== 'tool')
246
+ return null;
247
+ const payload = req.content.payload;
248
+ return payload.exec === undefined ? null : payload;
249
+ }
250
+ /** `checkDraft`: live validation of an unsaved draft, plus the risk the static screen derives. */
251
+ export async function checkDraft(core, req) {
252
+ const at = core.now();
253
+ const secrets = core.secrets();
254
+ const verdict = validateGeneContent(req.type, req.content, {
255
+ scope: req.scope,
256
+ actor: 'user',
257
+ secretCheck: (text) => geneLooksLikeSecret(text, secrets),
258
+ });
259
+ const checks = verdict.issues.map((issue) => ({
260
+ code: issue.code,
261
+ ok: false,
262
+ by: 'code',
263
+ detail: `${issue.path}: ${issue.message}${issue.detail ? ` (${issue.detail})` : ''}`,
264
+ at,
265
+ }));
266
+ if (verdict.ok) {
267
+ checks.push({ code: 'live_check', ok: true, by: 'code', at, detail: 'The draft is valid.' });
268
+ }
269
+ const draft = { ok: verdict.ok, checks };
270
+ const payload = toolPayloadOf(req);
271
+ if (payload !== null) {
272
+ // No script text is known for an unsaved draft, so a script reads as `high`: the conservative
273
+ // direction, and exactly what the commit's own risk floor will compute.
274
+ const screened = screenToolExec(payload.exec);
275
+ draft.derivedRisk = screened.risk;
276
+ draft.derivedPermissions = screened.permissions;
277
+ }
278
+ return geneOk(draft);
279
+ }