@aragon-agent/cli 0.6.54 → 0.6.56

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 (346) hide show
  1. package/CHANGELOG.md +2912 -2838
  2. package/README.md +4226 -4042
  3. package/dist/agent/controller.d.ts +119 -0
  4. package/dist/agent/controller.js +365 -2
  5. package/dist/agent/governance-wiring.js +8 -1
  6. package/dist/agent/redteam-prompt.d.ts +47 -0
  7. package/dist/agent/redteam-prompt.js +161 -0
  8. package/dist/agent/redteam-wiring.d.ts +159 -0
  9. package/dist/agent/redteam-wiring.js +349 -0
  10. package/dist/agent/system-prompt.d.ts +39 -0
  11. package/dist/agent/system-prompt.js +18 -0
  12. package/dist/app/App.d.ts +10 -1
  13. package/dist/app/App.js +233 -24
  14. package/dist/app/use-redteam-mode.d.ts +56 -0
  15. package/dist/app/use-redteam-mode.js +121 -0
  16. package/dist/cli.js +82 -4
  17. package/dist/commands/builtins.js +43 -1
  18. package/dist/commands/catalog.js +5 -0
  19. package/dist/commands/index-build.js +2 -1
  20. package/dist/commands/redteam-command.d.ts +22 -0
  21. package/dist/commands/redteam-command.js +141 -0
  22. package/dist/commands/registry.d.ts +8 -0
  23. package/dist/config/app-paths.d.ts +10 -0
  24. package/dist/config/app-paths.js +12 -0
  25. package/dist/config/cli-commands.d.ts +29 -0
  26. package/dist/config/cli-commands.js +76 -1
  27. package/dist/config/env.d.ts +3 -1
  28. package/dist/config/env.js +23 -1
  29. package/dist/config/load.d.ts +22 -0
  30. package/dist/config/load.js +22 -2
  31. package/dist/config/redteam-launch.d.ts +77 -0
  32. package/dist/config/redteam-launch.js +58 -0
  33. package/dist/config/store.js +21 -1
  34. package/dist/config/ui-state.d.ts +44 -0
  35. package/dist/config/ui-state.js +38 -0
  36. package/dist/exec/bridge/server.d.ts +7 -0
  37. package/dist/exec/bridge/server.js +6 -2
  38. package/dist/exec/cli-commands.js +4 -0
  39. package/dist/exec/index.js +2 -0
  40. package/dist/exec/options.d.ts +11 -0
  41. package/dist/exec/options.js +21 -1
  42. package/dist/gene/block.d.ts +33 -0
  43. package/dist/gene/block.js +51 -0
  44. package/dist/gene/capacity.d.ts +74 -0
  45. package/dist/gene/capacity.js +169 -0
  46. package/dist/gene/catalog-reconcile.d.ts +13 -0
  47. package/dist/gene/catalog-reconcile.js +105 -0
  48. package/dist/gene/catalog-stats.d.ts +27 -0
  49. package/dist/gene/catalog-stats.js +89 -0
  50. package/dist/gene/catalog-sync.d.ts +82 -0
  51. package/dist/gene/catalog-sync.js +324 -0
  52. package/dist/gene/catalog.d.ts +160 -0
  53. package/dist/gene/catalog.js +433 -0
  54. package/dist/gene/cli-commands.d.ts +50 -0
  55. package/dist/gene/cli-commands.js +500 -0
  56. package/dist/gene/command-report.d.ts +40 -0
  57. package/dist/gene/command-report.js +246 -0
  58. package/dist/gene/command.d.ts +29 -0
  59. package/dist/gene/command.js +561 -0
  60. package/dist/gene/commit-apply-types.d.ts +13 -0
  61. package/dist/gene/commit-apply-types.js +1 -0
  62. package/dist/gene/commit-compound.d.ts +34 -0
  63. package/dist/gene/commit-compound.js +212 -0
  64. package/dist/gene/commit-counts.d.ts +41 -0
  65. package/dist/gene/commit-counts.js +70 -0
  66. package/dist/gene/commit-exec.d.ts +42 -0
  67. package/dist/gene/commit-exec.js +134 -0
  68. package/dist/gene/commit-head.d.ts +52 -0
  69. package/dist/gene/commit-head.js +97 -0
  70. package/dist/gene/commit-plan.d.ts +95 -0
  71. package/dist/gene/commit-plan.js +68 -0
  72. package/dist/gene/commit-prepare.d.ts +63 -0
  73. package/dist/gene/commit-prepare.js +159 -0
  74. package/dist/gene/commit-types.d.ts +234 -0
  75. package/dist/gene/commit-types.js +3 -0
  76. package/dist/gene/curator/agent.d.ts +137 -0
  77. package/dist/gene/curator/agent.js +203 -0
  78. package/dist/gene/curator/budget.d.ts +69 -0
  79. package/dist/gene/curator/budget.js +131 -0
  80. package/dist/gene/curator/conflicts.d.ts +54 -0
  81. package/dist/gene/curator/conflicts.js +143 -0
  82. package/dist/gene/curator/curator.d.ts +170 -0
  83. package/dist/gene/curator/curator.js +617 -0
  84. package/dist/gene/curator/deps.d.ts +34 -0
  85. package/dist/gene/curator/deps.js +48 -0
  86. package/dist/gene/curator/deterministic.d.ts +62 -0
  87. package/dist/gene/curator/deterministic.js +287 -0
  88. package/dist/gene/curator/executors.d.ts +36 -0
  89. package/dist/gene/curator/executors.js +379 -0
  90. package/dist/gene/curator/lanes.d.ts +52 -0
  91. package/dist/gene/curator/lanes.js +99 -0
  92. package/dist/gene/curator/lease.d.ts +76 -0
  93. package/dist/gene/curator/lease.js +171 -0
  94. package/dist/gene/curator/library.d.ts +36 -0
  95. package/dist/gene/curator/library.js +169 -0
  96. package/dist/gene/curator/lifecycle.d.ts +52 -0
  97. package/dist/gene/curator/lifecycle.js +109 -0
  98. package/dist/gene/curator/maintenance.d.ts +71 -0
  99. package/dist/gene/curator/maintenance.js +213 -0
  100. package/dist/gene/curator/probation.d.ts +51 -0
  101. package/dist/gene/curator/probation.js +71 -0
  102. package/dist/gene/curator/probe.d.ts +131 -0
  103. package/dist/gene/curator/probe.js +534 -0
  104. package/dist/gene/curator/prompt.d.ts +18 -0
  105. package/dist/gene/curator/prompt.js +128 -0
  106. package/dist/gene/curator/publish.d.ts +64 -0
  107. package/dist/gene/curator/publish.js +113 -0
  108. package/dist/gene/curator/recheck.d.ts +55 -0
  109. package/dist/gene/curator/recheck.js +103 -0
  110. package/dist/gene/curator/run-events.d.ts +63 -0
  111. package/dist/gene/curator/run-events.js +55 -0
  112. package/dist/gene/curator/similarity.d.ts +13 -0
  113. package/dist/gene/curator/similarity.js +46 -0
  114. package/dist/gene/curator/switches.d.ts +78 -0
  115. package/dist/gene/curator/switches.js +146 -0
  116. package/dist/gene/curator/task-context.d.ts +93 -0
  117. package/dist/gene/curator/task-context.js +63 -0
  118. package/dist/gene/curator/task-runner.d.ts +56 -0
  119. package/dist/gene/curator/task-runner.js +257 -0
  120. package/dist/gene/curator/tool-support.d.ts +112 -0
  121. package/dist/gene/curator/tool-support.js +197 -0
  122. package/dist/gene/curator/toolkit.d.ts +49 -0
  123. package/dist/gene/curator/toolkit.js +104 -0
  124. package/dist/gene/curator/tools-read.d.ts +4 -0
  125. package/dist/gene/curator/tools-read.js +177 -0
  126. package/dist/gene/curator/tools-release.d.ts +73 -0
  127. package/dist/gene/curator/tools-release.js +287 -0
  128. package/dist/gene/curator/tools-verify.d.ts +47 -0
  129. package/dist/gene/curator/tools-verify.js +202 -0
  130. package/dist/gene/curator/tools-write.d.ts +26 -0
  131. package/dist/gene/curator/tools-write.js +394 -0
  132. package/dist/gene/curator/tools.d.ts +23 -0
  133. package/dist/gene/curator/tools.js +21 -0
  134. package/dist/gene/curator/validate/common.d.ts +87 -0
  135. package/dist/gene/curator/validate/common.js +132 -0
  136. package/dist/gene/curator/validate/evidence-tokens.d.ts +36 -0
  137. package/dist/gene/curator/validate/evidence-tokens.js +139 -0
  138. package/dist/gene/curator/validate/index.d.ts +23 -0
  139. package/dist/gene/curator/validate/index.js +62 -0
  140. package/dist/gene/curator/validate/knowledge.d.ts +25 -0
  141. package/dist/gene/curator/validate/knowledge.js +216 -0
  142. package/dist/gene/curator/validate/live-check.d.ts +14 -0
  143. package/dist/gene/curator/validate/live-check.js +144 -0
  144. package/dist/gene/curator/validate/ports.d.ts +67 -0
  145. package/dist/gene/curator/validate/ports.js +1 -0
  146. package/dist/gene/curator/validate/prompts.d.ts +41 -0
  147. package/dist/gene/curator/validate/prompts.js +161 -0
  148. package/dist/gene/curator/validate/skill.d.ts +15 -0
  149. package/dist/gene/curator/validate/skill.js +251 -0
  150. package/dist/gene/curator/validate/tool.d.ts +6 -0
  151. package/dist/gene/curator/validate/tool.js +217 -0
  152. package/dist/gene/curator/validate/types.d.ts +90 -0
  153. package/dist/gene/curator/validate/types.js +1 -0
  154. package/dist/gene/curator/validator-ports.d.ts +38 -0
  155. package/dist/gene/curator/validator-ports.js +29 -0
  156. package/dist/gene/diag.d.ts +209 -0
  157. package/dist/gene/diag.js +549 -0
  158. package/dist/gene/env.d.ts +10 -0
  159. package/dist/gene/env.js +214 -0
  160. package/dist/gene/eval-recorder.d.ts +84 -0
  161. package/dist/gene/eval-recorder.js +222 -0
  162. package/dist/gene/explain-transport.d.ts +3 -0
  163. package/dist/gene/explain-transport.js +39 -0
  164. package/dist/gene/explain.d.ts +96 -0
  165. package/dist/gene/explain.js +293 -0
  166. package/dist/gene/fs.d.ts +39 -0
  167. package/dist/gene/fs.js +139 -0
  168. package/dist/gene/fsck.d.ts +68 -0
  169. package/dist/gene/fsck.js +134 -0
  170. package/dist/gene/gc-library-sweeps.d.ts +9 -0
  171. package/dist/gene/gc-library-sweeps.js +220 -0
  172. package/dist/gene/gc-rejected-set.d.ts +15 -0
  173. package/dist/gene/gc-rejected-set.js +63 -0
  174. package/dist/gene/gc-safe.d.ts +12 -0
  175. package/dist/gene/gc-safe.js +74 -0
  176. package/dist/gene/gc-scope-sweeps.d.ts +18 -0
  177. package/dist/gene/gc-scope-sweeps.js +297 -0
  178. package/dist/gene/gc-types.d.ts +55 -0
  179. package/dist/gene/gc-types.js +26 -0
  180. package/dist/gene/gc.d.ts +42 -0
  181. package/dist/gene/gc.js +129 -0
  182. package/dist/gene/gene-errors.d.ts +23 -0
  183. package/dist/gene/gene-errors.js +29 -0
  184. package/dist/gene/hints.d.ts +91 -0
  185. package/dist/gene/hints.js +394 -0
  186. package/dist/gene/hub.d.ts +149 -0
  187. package/dist/gene/hub.js +371 -0
  188. package/dist/gene/import-plan.d.ts +80 -0
  189. package/dist/gene/import-plan.js +294 -0
  190. package/dist/gene/import-proposal.d.ts +23 -0
  191. package/dist/gene/import-proposal.js +101 -0
  192. package/dist/gene/import-skill-port.d.ts +6 -0
  193. package/dist/gene/import-skill-port.js +53 -0
  194. package/dist/gene/import-sources.d.ts +48 -0
  195. package/dist/gene/import-sources.js +140 -0
  196. package/dist/gene/index-writer.d.ts +36 -0
  197. package/dist/gene/index-writer.js +101 -0
  198. package/dist/gene/learn/learn-call.d.ts +63 -0
  199. package/dist/gene/learn/learn-call.js +157 -0
  200. package/dist/gene/learn/learn-prompt.d.ts +51 -0
  201. package/dist/gene/learn/learn-prompt.js +245 -0
  202. package/dist/gene/learn/learner.d.ts +181 -0
  203. package/dist/gene/learn/learner.js +426 -0
  204. package/dist/gene/learn/ledger.d.ts +220 -0
  205. package/dist/gene/learn/ledger.js +394 -0
  206. package/dist/gene/learn/proposal-build.d.ts +83 -0
  207. package/dist/gene/learn/proposal-build.js +211 -0
  208. package/dist/gene/learn/proposal-guard.d.ts +43 -0
  209. package/dist/gene/learn/proposal-guard.js +37 -0
  210. package/dist/gene/learn/signals-port.d.ts +47 -0
  211. package/dist/gene/learn/signals-port.js +86 -0
  212. package/dist/gene/maintenance-paths.d.ts +7 -0
  213. package/dist/gene/maintenance-paths.js +20 -0
  214. package/dist/gene/maintenance-probation.d.ts +33 -0
  215. package/dist/gene/maintenance-probation.js +127 -0
  216. package/dist/gene/maintenance-proposals.d.ts +24 -0
  217. package/dist/gene/maintenance-proposals.js +68 -0
  218. package/dist/gene/maintenance-runner.d.ts +92 -0
  219. package/dist/gene/maintenance-runner.js +262 -0
  220. package/dist/gene/maintenance-tasks.d.ts +37 -0
  221. package/dist/gene/maintenance-tasks.js +95 -0
  222. package/dist/gene/manager-actions.d.ts +12 -0
  223. package/dist/gene/manager-actions.js +279 -0
  224. package/dist/gene/manager-approve.d.ts +29 -0
  225. package/dist/gene/manager-approve.js +84 -0
  226. package/dist/gene/manager-context.d.ts +90 -0
  227. package/dist/gene/manager-context.js +201 -0
  228. package/dist/gene/manager-detail.d.ts +17 -0
  229. package/dist/gene/manager-detail.js +313 -0
  230. package/dist/gene/manager-gc.d.ts +13 -0
  231. package/dist/gene/manager-gc.js +81 -0
  232. package/dist/gene/manager-library.d.ts +39 -0
  233. package/dist/gene/manager-library.js +90 -0
  234. package/dist/gene/manager-list.d.ts +27 -0
  235. package/dist/gene/manager-list.js +170 -0
  236. package/dist/gene/manager-queue.d.ts +16 -0
  237. package/dist/gene/manager-queue.js +124 -0
  238. package/dist/gene/manager-stats.d.ts +28 -0
  239. package/dist/gene/manager-stats.js +53 -0
  240. package/dist/gene/manager-view.d.ts +27 -0
  241. package/dist/gene/manager-view.js +124 -0
  242. package/dist/gene/manager.d.ts +56 -0
  243. package/dist/gene/manager.js +179 -0
  244. package/dist/gene/orphan-scopes.d.ts +37 -0
  245. package/dist/gene/orphan-scopes.js +150 -0
  246. package/dist/gene/paths.d.ts +73 -0
  247. package/dist/gene/paths.js +239 -0
  248. package/dist/gene/plan-content.d.ts +73 -0
  249. package/dist/gene/plan-content.js +522 -0
  250. package/dist/gene/plan-lifecycle.d.ts +29 -0
  251. package/dist/gene/plan-lifecycle.js +310 -0
  252. package/dist/gene/policy.d.ts +71 -0
  253. package/dist/gene/policy.js +313 -0
  254. package/dist/gene/project-learning.d.ts +25 -0
  255. package/dist/gene/project-learning.js +54 -0
  256. package/dist/gene/propagation.d.ts +48 -0
  257. package/dist/gene/propagation.js +45 -0
  258. package/dist/gene/queue-lock.d.ts +22 -0
  259. package/dist/gene/queue-lock.js +99 -0
  260. package/dist/gene/queue-record.d.ts +57 -0
  261. package/dist/gene/queue-record.js +145 -0
  262. package/dist/gene/queue.d.ts +235 -0
  263. package/dist/gene/queue.js +764 -0
  264. package/dist/gene/read.d.ts +61 -0
  265. package/dist/gene/read.js +252 -0
  266. package/dist/gene/runlog.d.ts +101 -0
  267. package/dist/gene/runlog.js +404 -0
  268. package/dist/gene/schema-lite.d.ts +24 -0
  269. package/dist/gene/schema-lite.js +159 -0
  270. package/dist/gene/scope-guard.d.ts +23 -0
  271. package/dist/gene/scope-guard.js +9 -0
  272. package/dist/gene/scope-lock.d.ts +48 -0
  273. package/dist/gene/scope-lock.js +222 -0
  274. package/dist/gene/scope-verify.d.ts +63 -0
  275. package/dist/gene/scope-verify.js +123 -0
  276. package/dist/gene/secrets.d.ts +43 -0
  277. package/dist/gene/secrets.js +161 -0
  278. package/dist/gene/service-context.d.ts +43 -0
  279. package/dist/gene/service-context.js +79 -0
  280. package/dist/gene/service-prepare.d.ts +25 -0
  281. package/dist/gene/service-prepare.js +219 -0
  282. package/dist/gene/service-types.d.ts +196 -0
  283. package/dist/gene/service-types.js +1 -0
  284. package/dist/gene/service-view.d.ts +41 -0
  285. package/dist/gene/service-view.js +69 -0
  286. package/dist/gene/service.d.ts +114 -0
  287. package/dist/gene/service.js +761 -0
  288. package/dist/gene/session-start.d.ts +36 -0
  289. package/dist/gene/session-start.js +212 -0
  290. package/dist/gene/store-port.d.ts +88 -0
  291. package/dist/gene/store-port.js +10 -0
  292. package/dist/gene/store-rows.d.ts +36 -0
  293. package/dist/gene/store-rows.js +72 -0
  294. package/dist/gene/store.d.ts +125 -0
  295. package/dist/gene/store.js +622 -0
  296. package/dist/gene/tombstones.d.ts +47 -0
  297. package/dist/gene/tombstones.js +61 -0
  298. package/dist/gene/tool-runner.d.ts +47 -0
  299. package/dist/gene/tool-runner.js +154 -0
  300. package/dist/gene/tool-screen.d.ts +41 -0
  301. package/dist/gene/tool-screen.js +227 -0
  302. package/dist/gene/tools.d.ts +112 -0
  303. package/dist/gene/tools.js +539 -0
  304. package/dist/gene/transfer.d.ts +85 -0
  305. package/dist/gene/transfer.js +433 -0
  306. package/dist/gene/ui-hints.d.ts +15 -0
  307. package/dist/gene/ui-hints.js +67 -0
  308. package/dist/gene/usage-fold-cursor.d.ts +24 -0
  309. package/dist/gene/usage-fold-cursor.js +115 -0
  310. package/dist/gene/usage-fold.d.ts +49 -0
  311. package/dist/gene/usage-fold.js +397 -0
  312. package/dist/gene/usage.d.ts +67 -0
  313. package/dist/gene/usage.js +231 -0
  314. package/dist/gene/version-service.d.ts +118 -0
  315. package/dist/gene/version-service.js +453 -0
  316. package/dist/gene/wiring-events.d.ts +43 -0
  317. package/dist/gene/wiring-events.js +113 -0
  318. package/dist/gene/wiring-models.d.ts +46 -0
  319. package/dist/gene/wiring-models.js +81 -0
  320. package/dist/gene/wiring.d.ts +200 -0
  321. package/dist/gene/wiring.js +764 -0
  322. package/dist/governance/prompts/orchestrator-block.js +3 -2
  323. package/dist/host/controller-factory.d.ts +8 -0
  324. package/dist/host/controller-factory.js +7 -0
  325. package/dist/host/gene.d.ts +26 -0
  326. package/dist/host/gene.js +24 -0
  327. package/dist/host/index.d.ts +1 -0
  328. package/dist/host/index.js +1 -0
  329. package/dist/session/checkpoint.d.ts +15 -0
  330. package/dist/session/checkpoint.js +18 -0
  331. package/dist/session/persist.d.ts +21 -0
  332. package/dist/session/persist.js +10 -0
  333. package/dist/session/startup-session.d.ts +11 -2
  334. package/dist/session/startup-session.js +12 -2
  335. package/dist/session/validate-session.js +31 -0
  336. package/dist/team/runtime.d.ts +16 -0
  337. package/dist/team/runtime.js +29 -0
  338. package/dist/team/subagent.d.ts +55 -0
  339. package/dist/team/subagent.js +46 -2
  340. package/dist/tools/index.d.ts +60 -2
  341. package/dist/tools/index.js +68 -10
  342. package/package.json +3 -3
  343. package/skills/project-indexer/SKILL.md +275 -147
  344. package/skills/project-indexer/templates/artifact-hygiene-template.md +14 -0
  345. package/skills/project-indexer/templates/config-template.md +12 -0
  346. package/skills/project-indexer/templates/index-template.md +4 -0
@@ -0,0 +1,211 @@
1
+ import { escapeGeneText } from '@aragon-agent/tui/model/gene/escape';
2
+ import { isValidScope, mintProposalId, scopeId } from '@aragon-agent/tui/model/gene/ids';
3
+ import { GENE_LIMITS, GENE_SCORE } from '@aragon-agent/tui/model/gene/limits';
4
+ import { dedupeKeyOf, priorityOf } from '@aragon-agent/tui/model/gene/proposal';
5
+ import { fingerprintOf } from '@aragon-agent/tui/model/gene/validate-base';
6
+ import { redactSecrets } from '../secrets.js';
7
+ function clipPoints(text, max) {
8
+ const points = Array.from(text);
9
+ return points.length <= max ? text : points.slice(0, max).join('');
10
+ }
11
+ /** The concrete scope for a scope KIND, or null when the session cannot name one. */
12
+ export function resolveScope(kind, session) {
13
+ let scope = null;
14
+ if (kind === 'user')
15
+ scope = { kind: 'user' };
16
+ else if (kind === 'project')
17
+ scope = session.projectKey ? { kind: 'project', key: session.projectKey } : null;
18
+ else if (kind === 'task')
19
+ scope = { kind: 'task', key: session.sessionId };
20
+ return scope !== null && isValidScope(scope) ? scope : null;
21
+ }
22
+ // ---------------------------------------------------------------------------
23
+ // Evidence
24
+ // ---------------------------------------------------------------------------
25
+ /** Same normalisation on both sides, so the model's escaped view of a message still matches. */
26
+ function quoteKey(text) {
27
+ return escapeGeneText(text, 'line');
28
+ }
29
+ /** The model read an entity-escaped prompt and may quote the entities back; undo them once. */
30
+ function unescapeEntities(text) {
31
+ return text.replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&quot;/g, '"').replace(/&amp;/g, '&');
32
+ }
33
+ /** Check quotes against the ledger, scrub secrets, clip. */
34
+ export function verifyEvidence(list, snapshot, knownSecrets) {
35
+ const users = snapshot.users.map((u) => ({ key: quoteKey(u.text), raw: u.text }));
36
+ return list.slice(0, GENE_LIMITS.proposalEvidenceMax).map((entry) => {
37
+ let text = entry.text;
38
+ let trust = entry.trust;
39
+ if (entry.kind === 'user_statement') {
40
+ const keys = [quoteKey(entry.text), quoteKey(unescapeEntities(entry.text))].filter((k) => k.length > 0);
41
+ const hit = users.find((u) => keys.some((key) => u.key.includes(key)));
42
+ text = hit ? hit.raw : text;
43
+ trust = hit ? 'user' : 'untrusted';
44
+ }
45
+ else if (trust === undefined) {
46
+ trust = 'agent';
47
+ }
48
+ const scrubbed = redactSecrets(text, knownSecrets).text;
49
+ return { ...entry, text: clipPoints(scrubbed, GENE_LIMITS.proposalEvidenceTextMax), trust };
50
+ });
51
+ }
52
+ // ---------------------------------------------------------------------------
53
+ // Attributions (I-9)
54
+ // ---------------------------------------------------------------------------
55
+ /** Did anything go wrong AFTER the gene was read? Only then can the gene be blamed. */
56
+ export function troubleAfterRead(snapshot, geneId) {
57
+ const read = snapshot.reads.get(geneId);
58
+ if (!read)
59
+ return false;
60
+ const failed = snapshot.calls.some((c) => c.seq > read.seq && !c.ok);
61
+ const corrected = snapshot.users.some((u) => u.seq > read.seq && u.correction);
62
+ return failed || corrected;
63
+ }
64
+ export function adjustAttributions(attributions, snapshot) {
65
+ const out = { kept: [], downgraded: 0, alreadyAttributed: 0 };
66
+ for (const a of attributions) {
67
+ if (snapshot.feedback.has(a.geneId) || snapshot.runResults.has(a.geneId)) {
68
+ out.alreadyAttributed += 1;
69
+ continue;
70
+ }
71
+ if (a.effect === 'harmed' && !troubleAfterRead(snapshot, a.geneId)) {
72
+ out.downgraded += 1;
73
+ out.kept.push({ ...a, effect: 'unknown' });
74
+ continue;
75
+ }
76
+ out.kept.push(a);
77
+ }
78
+ return out;
79
+ }
80
+ /**
81
+ * `outcome` usage events for the attributions that count (10.1.4): adopted, and `helped` /
82
+ * `harmed` / `neutral`. `unknown` is not an event at all (I-9). A gene whose scope or version
83
+ * cannot be determined is skipped: an event the fold cannot route would be dropped and counted
84
+ * as a defect there.
85
+ */
86
+ export function outcomeEvents(attributions, ctx) {
87
+ const events = [];
88
+ for (const a of attributions) {
89
+ if (a.effect === 'unknown' || !a.adopted)
90
+ continue;
91
+ const scope = ctx.scopeOf(a.geneId);
92
+ const version = ctx.snapshot.reads.get(a.geneId)?.version ?? ctx.versionOf?.(a.geneId);
93
+ if (scope === undefined || version === undefined)
94
+ continue;
95
+ events.push({
96
+ sc: scopeId(scope),
97
+ t: ctx.now,
98
+ k: 'outcome',
99
+ g: a.geneId,
100
+ v: version,
101
+ run: ctx.runId,
102
+ e: a.effect,
103
+ w: GENE_SCORE.adoptionWeights.reviewer,
104
+ by: 'reviewer',
105
+ ...(a.ev ? { ev: a.ev } : {}),
106
+ });
107
+ }
108
+ return events;
109
+ }
110
+ // ---------------------------------------------------------------------------
111
+ // Proposals
112
+ // ---------------------------------------------------------------------------
113
+ function harmFlagged(draft, ctx) {
114
+ if (draft.target === undefined)
115
+ return false;
116
+ const verdict = ctx.snapshot.feedback.get(draft.target);
117
+ const flagged = verdict === 'misleading' || verdict === 'outdated';
118
+ return flagged || ctx.attributions.some((a) => a.geneId === draft.target && a.effect === 'harmed');
119
+ }
120
+ function statesPreference(draft, evidence) {
121
+ const payload = draft.draft?.payload;
122
+ const fromUser = evidence.some((e) => e.kind === 'user_statement' && e.trust === 'user');
123
+ return payload?.kind === 'preference' && fromUser;
124
+ }
125
+ function fingerprintOfDraft(draft, scopeKind) {
126
+ if (draft.kind !== 'create' || draft.type === undefined)
127
+ return undefined;
128
+ return fingerprintOf(draft.type, scopeKind, {
129
+ name: draft.title,
130
+ purpose: draft.draft?.purpose ?? '',
131
+ trigger: draft.draft?.trigger ?? '',
132
+ });
133
+ }
134
+ /** Queue class (10.5.2): a user correction, a harmed target and a revoke each move it up. */
135
+ function priorityFor(draft, ctx, evidence) {
136
+ return priorityOf({
137
+ kind: draft.kind,
138
+ fromUserCorrection: ctx.signals.some((s) => s.id === 'L1'),
139
+ harmedFlag: harmFlagged(draft, ctx),
140
+ userStatedPreference: statesPreference(draft, evidence),
141
+ });
142
+ }
143
+ /** Two proposals with the same key are the same request and fold into one (10.5.3). */
144
+ function dedupeKeyFor(draft, scope, basis) {
145
+ const fingerprint = fingerprintOfDraft(draft, draft.scope);
146
+ return dedupeKeyOf({
147
+ kind: draft.kind,
148
+ scope,
149
+ ...(draft.target ? { targetId: draft.target } : {}),
150
+ ...(fingerprint ? { fingerprint } : {}),
151
+ ...(basis ? { basisVersion: basis.version } : {}),
152
+ });
153
+ }
154
+ /** What the proposal is aimed at: the target with the basis it was based on (I-10), or a merge. */
155
+ function targetFields(draft, basis) {
156
+ if (!draft.target || !basis)
157
+ return {};
158
+ const hash = basis.hash ? { basisHash: basis.hash } : {};
159
+ const target = { id: draft.target, basisVersion: basis.version, ...hash };
160
+ if (draft.kind !== 'merge')
161
+ return { target };
162
+ return { target, mergeInto: draft.target, mergeFrom: draft.mergeFrom ?? [] };
163
+ }
164
+ function originOf(ctx) {
165
+ const goal = ctx.snapshot.goal === '' ? '(unknown)' : ctx.snapshot.goal;
166
+ return {
167
+ source: 'reviewer',
168
+ sessionId: ctx.session.sessionId,
169
+ runId: ctx.session.runId,
170
+ ...(ctx.session.projectKey ? { projectKey: ctx.session.projectKey } : {}),
171
+ ...(ctx.session.agent ? { agent: ctx.session.agent } : {}),
172
+ ...(ctx.session.taskLabel ? { taskLabel: ctx.session.taskLabel } : {}),
173
+ goal: clipPoints(goal, GENE_LIMITS.proposalGoalMax),
174
+ };
175
+ }
176
+ /** A create names its gene; the model's own draft fields ride along. */
177
+ function draftFields(draft) {
178
+ if (draft.kind === 'create')
179
+ return { draft: { ...draft.draft, name: draft.title } };
180
+ return draft.draft ? { draft: draft.draft } : {};
181
+ }
182
+ /** A queue-ready proposal, or null when the draft cannot be anchored (no scope, target vanished). */
183
+ export function buildProposal(draft, ctx) {
184
+ const scope = resolveScope(draft.scope, ctx.session);
185
+ if (scope === null)
186
+ return null;
187
+ const basis = draft.target === undefined ? undefined : ctx.basisOf(draft.target);
188
+ if (draft.target !== undefined && basis === undefined)
189
+ return null;
190
+ const evidence = verifyEvidence(draft.evidence, ctx.snapshot, ctx.knownSecrets);
191
+ const informative = ctx.attributions.filter((a) => a.effect !== 'unknown');
192
+ return {
193
+ schema: 1,
194
+ id: mintProposalId(ctx.random),
195
+ createdAt: ctx.now,
196
+ kind: draft.kind,
197
+ ...(draft.type ? { type: draft.type } : {}),
198
+ scope,
199
+ ...targetFields(draft, basis),
200
+ origin: originOf(ctx),
201
+ why: draft.why,
202
+ expectedBenefit: draft.expectedBenefit,
203
+ ...(draft.applicability ? { applicability: draft.applicability } : {}),
204
+ ...draftFields(draft),
205
+ evidence,
206
+ ...(informative.length > 0 ? { attributions: informative } : {}),
207
+ priority: priorityFor(draft, ctx, evidence),
208
+ dedupeKey: dedupeKeyFor(draft, scope, basis),
209
+ merged: 0,
210
+ };
211
+ }
@@ -0,0 +1,43 @@
1
+ /**
2
+ * The oversight fence for proposals (gene-bank spec 11.3, I-12, TH-5).
3
+ *
4
+ * ASCII ONLY - the whole `gene/` tree is in `glyphs.test.ts::inScope`.
5
+ *
6
+ * WHAT IT PROTECTS. A gene with `class: 'oversight'` (acceptance criteria, checks and balances,
7
+ * review checklists) is the yardstick the executing agents are measured against. If an executing
8
+ * agent could write to it, "learning from experience" would let the thing being checked edit
9
+ * the check. The same goes for a gene visible ONLY to the reviewer role: it is the reviewer's
10
+ * private instruction, and an executor must not be able to plant or alter one.
11
+ *
12
+ * WHO IS FENCED. Every origin EXCEPT the review roles, a person's explicit flag and system
13
+ * maintenance. The test is deliberately "not a reviewer" rather than "is DEV or TEST": an
14
+ * origin whose `agent` is missing or unrecognised is treated as an executor, because the way
15
+ * a fence fails open is by enumerating the dangerous names and missing one.
16
+ *
17
+ * TWO CHECKPOINTS. The learner calls this at ENQUEUE; the curator calls it again at CLAIM,
18
+ * because the queue file is a plain JSON file a person (or a bug) may have edited in between, and
19
+ * because the target gene may have been reclassified since. `GeneVersionService.commit` is the
20
+ * third line (it refuses non-user writes to oversight genes outright), so a miss here is
21
+ * caught later - but a rejected proposal here costs nothing and leaves a clean record.
22
+ *
23
+ * PURE over an injected `lookupGene`, which is the only thing that knows the library.
24
+ */
25
+ import type { GeneClass, GeneProposal, GeneRole } from '@aragon-agent/tui/model/gene/types';
26
+ /** The two facts about a gene the fence needs. */
27
+ export interface GuardGene {
28
+ class?: GeneClass;
29
+ roles?: readonly GeneRole[];
30
+ }
31
+ export type LookupGene = (geneId: string) => GuardGene | undefined;
32
+ export type GuardCode = 'team_scope' | 'oversight_target' | 'reviewer_only_target' | 'oversight_draft' | 'reviewer_only_draft';
33
+ export type GuardVerdict = {
34
+ ok: true;
35
+ } | {
36
+ ok: false;
37
+ code: GuardCode;
38
+ geneId?: string;
39
+ };
40
+ /** May this proposal's author be an executing agent (and so be fenced)? */
41
+ export declare function isExecutionOrigin(origin: GeneProposal['origin']): boolean;
42
+ /** Check one proposal against the fence. `lookupGene` returning undefined means "no such gene". */
43
+ export declare function guardProposal(proposal: GeneProposal, lookupGene: LookupGene): GuardVerdict;
@@ -0,0 +1,37 @@
1
+ /** Review roles of the governance mode, plus the plain words. Everything else executes. */
2
+ const REVIEW_AGENT_RE = /^(?:rev|insp|reviewer|inspector)$/i;
3
+ /** May this proposal's author be an executing agent (and so be fenced)? */
4
+ export function isExecutionOrigin(origin) {
5
+ if (origin.source === 'user_flag' || origin.source === 'system')
6
+ return false;
7
+ return !REVIEW_AGENT_RE.test((origin.agent ?? '').trim());
8
+ }
9
+ function onlyReviewer(roles) {
10
+ return Array.isArray(roles) && roles.length > 0 && roles.every((r) => r === 'reviewer');
11
+ }
12
+ function referencedIds(p) {
13
+ const ids = [p.target?.id, p.mergeInto, ...(p.mergeFrom ?? [])];
14
+ return [...new Set(ids.filter((id) => typeof id === 'string' && id.length > 0))];
15
+ }
16
+ /** Check one proposal against the fence. `lookupGene` returning undefined means "no such gene". */
17
+ export function guardProposal(proposal, lookupGene) {
18
+ // The team scope is read-only to agents (11.1); the normaliser already refuses it, this is the re-check.
19
+ if (proposal.scope?.kind === 'team')
20
+ return { ok: false, code: 'team_scope' };
21
+ if (!isExecutionOrigin(proposal.origin))
22
+ return { ok: true };
23
+ for (const geneId of referencedIds(proposal)) {
24
+ const gene = lookupGene(geneId);
25
+ if (gene?.class === 'oversight')
26
+ return { ok: false, code: 'oversight_target', geneId };
27
+ if (onlyReviewer(gene?.roles))
28
+ return { ok: false, code: 'reviewer_only_target', geneId };
29
+ }
30
+ const draft = proposal.draft;
31
+ // `class` is not part of the content type, but a hand-edited queue file can carry one.
32
+ if (draft?.class === 'oversight')
33
+ return { ok: false, code: 'oversight_draft' };
34
+ if (onlyReviewer(draft?.roles))
35
+ return { ok: false, code: 'reviewer_only_draft' };
36
+ return { ok: true };
37
+ }
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Reduce an `EvidenceLedger` snapshot to the counts the pure gate reads (gene-bank spec
3
+ * 10.1.2) and to the run facts the evaluation row needs (13.1).
4
+ *
5
+ * ASCII ONLY - the whole `gene/` tree is in `glyphs.test.ts::inScope`.
6
+ *
7
+ * The gate (`collectSignals` / `shouldLearn`) takes COUNTS, never text, so deciding whether a run
8
+ * is worth a model call does not need the content of the run (I-8). This file is the only place
9
+ * that turns ledger arrays into those counts, so the definition of "a correction after an
10
+ * action" or "an unattributed gene read" exists once.
11
+ *
12
+ * "NEW SINCE" MATTERS. A strong signal can fire a learning call at `turn_end`, before the run
13
+ * is over. Without a watermark the same correction would fire a second call at `agent_end`.
14
+ * Counts that describe EVENTS (corrections, arcs, flags, repeated errors) are therefore reported
15
+ * relative to the last call; counts that describe the RUN (tool calls, outcome, todo state) stay
16
+ * cumulative, because "was this a real procedure" is a property of the whole run.
17
+ */
18
+ import type { LearnLedgerFacts } from '@aragon-agent/tui/model/gene/signals';
19
+ import type { LedgerSnapshot, LedgerWatermark } from './ledger.js';
20
+ /**
21
+ * Genes read whose effect nothing pinned down: no `gene_feedback`, no `gene_run` result, and
22
+ * not already covered by an earlier learning call.
23
+ */
24
+ export declare function unattributedReads(snap: LedgerSnapshot, mark?: LedgerWatermark): number;
25
+ export declare function factsFromLedger(snap: LedgerSnapshot, mark?: LedgerWatermark): LearnLedgerFacts;
26
+ /** The run facts an evaluation row takes from the ledger; the controller adds the rest. */
27
+ export interface LedgerEvalFacts {
28
+ toolCalls: number;
29
+ toolErrors: number;
30
+ retries: number;
31
+ userCorrections: number;
32
+ turns: number;
33
+ errorSigs: string[];
34
+ genes: {
35
+ shown: number;
36
+ read: number;
37
+ adopted: number;
38
+ helped: number;
39
+ harmed: number;
40
+ };
41
+ }
42
+ /**
43
+ * Deterministic gene counts only. A `helped` here means the agent said so through
44
+ * `gene_feedback` or a `gene_run` succeeded; attributions that the learning call produces later
45
+ * go to the usage log, not into the row written at `agent_end`.
46
+ */
47
+ export declare function evalFactsFromLedger(snap: LedgerSnapshot): LedgerEvalFacts;
@@ -0,0 +1,86 @@
1
+ function delta(now, before) {
2
+ return Math.max(0, now - (before ?? 0));
3
+ }
4
+ /** Most times any one error signature occurred since the mark. */
5
+ function repeatedSince(snap, since) {
6
+ let max = 0;
7
+ for (const [sig, count] of snap.sigCounts) {
8
+ max = Math.max(max, count - (since?.sigCounts.get(sig) ?? 0));
9
+ }
10
+ return max;
11
+ }
12
+ /**
13
+ * Genes read whose effect nothing pinned down: no `gene_feedback`, no `gene_run` result, and
14
+ * not already covered by an earlier learning call.
15
+ */
16
+ export function unattributedReads(snap, mark) {
17
+ const since = mark !== undefined && mark.run === snap.run ? mark : undefined;
18
+ let count = 0;
19
+ for (const id of snap.reads.keys()) {
20
+ const settled = snap.feedback.has(id) || snap.runResults.has(id) || since?.readIds.has(id) === true;
21
+ if (!settled)
22
+ count += 1;
23
+ }
24
+ return count;
25
+ }
26
+ /** A run that has not ended cannot have completed: L5 must not fire mid-run. */
27
+ function outcomeOf(snap) {
28
+ return snap.outcome === 'running' ? 'aborted' : snap.outcome;
29
+ }
30
+ export function factsFromLedger(snap, mark) {
31
+ // The ledger's counters restart with every run, so a mark taken in an earlier run would
32
+ // subtract numbers from a different scale and swallow the new run's signals.
33
+ const since = mark !== undefined && mark.run === snap.run ? mark : undefined;
34
+ const c = snap.counters;
35
+ const b = since?.counters;
36
+ return {
37
+ userCorrections: delta(c.userCorrections, b?.userCorrections),
38
+ toolErrors: delta(c.toolErrors, b?.toolErrors),
39
+ repeatedErrorMaxCount: repeatedSince(snap, since),
40
+ recoveryArcs: delta(c.arcs, b?.arcs),
41
+ flaggedGeneFeedback: delta(c.flaggedFeedback, b?.flaggedFeedback),
42
+ toolCalls: c.toolCalls,
43
+ outcome: outcomeOf(snap),
44
+ todoAllDone: snap.todoAllDone,
45
+ lastVerifyOk: snap.lastVerifyOk,
46
+ unattributedGeneReads: unattributedReads(snap, since),
47
+ unfamiliarRecoveries: delta(c.unfamiliarRecoveries, b?.unfamiliarRecoveries),
48
+ statedFacts: delta(c.statedFacts, b?.statedFacts),
49
+ correctionAfterAction: delta(c.correctionAfterAction, b?.correctionAfterAction),
50
+ };
51
+ }
52
+ /**
53
+ * Deterministic gene counts only. A `helped` here means the agent said so through
54
+ * `gene_feedback` or a `gene_run` succeeded; attributions that the learning call produces later
55
+ * go to the usage log, not into the row written at `agent_end`.
56
+ */
57
+ export function evalFactsFromLedger(snap) {
58
+ const helped = new Set();
59
+ const harmed = new Set();
60
+ for (const [id, verdict] of snap.feedback) {
61
+ if (verdict === 'helped')
62
+ helped.add(id);
63
+ if (verdict === 'misleading' || verdict === 'outdated')
64
+ harmed.add(id);
65
+ }
66
+ for (const [id, ok] of snap.runResults)
67
+ if (ok)
68
+ helped.add(id);
69
+ const adopted = new Set([...helped, ...harmed, ...snap.runResults.keys()]);
70
+ const bySigCount = [...snap.sigCounts.entries()].sort((a, b) => b[1] - a[1]).map(([sig]) => sig);
71
+ return {
72
+ toolCalls: snap.counters.toolCalls,
73
+ toolErrors: snap.counters.toolErrors,
74
+ retries: snap.counters.retries,
75
+ userCorrections: snap.counters.userCorrections,
76
+ turns: snap.counters.turns,
77
+ errorSigs: bySigCount.slice(0, 10),
78
+ genes: {
79
+ shown: snap.shown.size,
80
+ read: snap.reads.size,
81
+ adopted: adopted.size,
82
+ helped: helped.size,
83
+ harmed: harmed.size,
84
+ },
85
+ };
86
+ }
@@ -0,0 +1,7 @@
1
+ import { type GenePathContext } from './paths.js';
2
+ type RootContext = Pick<GenePathContext, 'root'>;
3
+ /** The cross-process guard around one usage fold (defence in depth beside the curator lease). */
4
+ export declare function foldLockFile(ctx?: RootContext): string;
5
+ /** The 30-day "recently rejected" fingerprint set (7.3). */
6
+ export declare function recentlyRejectedFile(ctx?: RootContext): string;
7
+ export {};
@@ -0,0 +1,20 @@
1
+ /**
2
+ * The few library-level paths the background maintenance owns (gene-bank spec 6.8, 7.3, 7.5).
3
+ *
4
+ * ASCII ONLY - the whole `gene/` tree is in `glyphs.test.ts::inScope`.
5
+ *
6
+ * WHY THIS IS NOT IN `paths.ts`. `paths.ts` belongs to the storage work package and is frozen for
7
+ * this one. These two builders take no caller input at all (no id, no scope, no file name), so
8
+ * there is nothing to validate and nothing that can leave the library root; when `paths.ts` is
9
+ * next opened they should move there and this file should disappear.
10
+ */
11
+ import { join } from 'node:path';
12
+ import { geneRoot } from './paths.js';
13
+ /** The cross-process guard around one usage fold (defence in depth beside the curator lease). */
14
+ export function foldLockFile(ctx) {
15
+ return join(geneRoot(ctx), 'lock', 'usage-fold.lock');
16
+ }
17
+ /** The 30-day "recently rejected" fingerprint set (7.3). */
18
+ export function recentlyRejectedFile(ctx) {
19
+ return join(geneRoot(ctx), 'rejected-recent.json');
20
+ }
@@ -0,0 +1,33 @@
1
+ import type { GeneIndexRow, GeneProbation, GeneProposal, GeneStats } from '@aragon-agent/tui/model/gene/types';
2
+ import type { GeneStore } from './store.js';
3
+ export interface ProbationSweepDeps {
4
+ store: GeneStore;
5
+ /** The published rows to consider (the lease holder's catalog). */
6
+ rows: () => Iterable<GeneIndexRow>;
7
+ enqueue: (proposal: GeneProposal) => Promise<{
8
+ ok: boolean;
9
+ }>;
10
+ now: () => number;
11
+ sessionId: string;
12
+ random: (n: number) => number;
13
+ limit?: number;
14
+ }
15
+ export interface ProbationSweepReport {
16
+ examined: number;
17
+ continuing: number;
18
+ graduated: number;
19
+ rollbacks: number;
20
+ enqueued: number;
21
+ }
22
+ /** Outcomes since the probation began, from the weekly rows. */
23
+ export declare function probationWindow(probation: GeneProbation, stats: GeneStats | undefined): GeneProbation;
24
+ export declare class ProbationSweeper {
25
+ private readonly deps;
26
+ private resumeAt;
27
+ constructor(deps: ProbationSweepDeps);
28
+ sweep(): Promise<ProbationSweepReport>;
29
+ /** The next `limit` eligible rows in id order, wrapping around the end. */
30
+ private nextWindow;
31
+ private examine;
32
+ private enqueueRollback;
33
+ }
@@ -0,0 +1,127 @@
1
+ /**
2
+ * The probation sweep: enforce S6 without a model (gene-bank spec 10.7.3 S6, 10.6, I-7, I-9).
3
+ *
4
+ * ASCII ONLY - the whole `gene/` tree is in `glyphs.test.ts::inScope`.
5
+ *
6
+ * A gene the curator published starts on probation (`head.probation`). Nothing writes the head
7
+ * as outcomes arrive - statistics never touch heads - so the sweep reads the outcomes where they
8
+ * live, in the stats shard, and asks the pure decision in `curator/lifecycle.ts`
9
+ * (`evaluateProbation`) what the rule says:
10
+ *
11
+ * rollback harmed at least twice and never helped -> a P0 `revoke` proposal. The `why`
12
+ * starts with a stable token, `probation_rollback:previous` or
13
+ * `probation_rollback:revoke`, telling the deterministic P0 handler whether an
14
+ * earlier published version exists to go back to (S6: "roll back, or revoke a v1").
15
+ * graduate the window is over, or three outcomes arrived: nothing to write. Probation is a
16
+ * record on the head and `isOnProbation` is computed from it, so "graduated" is the
17
+ * absence of a problem, not a new state.
18
+ * continue nothing to do yet.
19
+ *
20
+ * WHERE THE COUNTS COME FROM. The shard keeps `weeks` rows `[weekStart, adopted, helped, harmed]`
21
+ * for the last 13 weeks, so the outcomes since probation began are the rows from the start week
22
+ * on. The week the probation started in may include a few outcomes from just before it, which can
23
+ * only make a rollback slightly earlier. The rows carry no `neutral` column, so "three outcomes"
24
+ * is counted as helped + harmed; a gene that only ever gets neutral outcomes simply graduates on
25
+ * time instead, which is harmless. `harmed >= 2 && helped == 0` - the rule that matters - is exact.
26
+ *
27
+ * NEVER TOUCHES A PINNED GENE (I-7) and never a person's gene. BOUNDED: at most `limit` genes per
28
+ * sweep, resuming where the last sweep stopped, so a large library is covered over several sweeps
29
+ * instead of being read in one.
30
+ */
31
+ import { geneShard } from '@aragon-agent/tui/model/gene/ids';
32
+ import { weekStart } from '@aragon-agent/tui/model/gene/score';
33
+ import { evaluateProbation } from './curator/lifecycle.js';
34
+ import { previousPublished } from './gc-scope-sweeps.js';
35
+ import { buildSystemProposal } from './maintenance-proposals.js';
36
+ const DEFAULT_LIMIT = 200;
37
+ /** Outcomes since the probation began, from the weekly rows. */
38
+ export function probationWindow(probation, stats) {
39
+ const since = weekStart(probation.startedAt);
40
+ let helped = 0;
41
+ let harmed = 0;
42
+ const weeks = stats?.weeks;
43
+ for (const week of Array.isArray(weeks) ? weeks : []) {
44
+ if (!Array.isArray(week) || week[0] < since)
45
+ continue;
46
+ helped += Math.max(0, week[2] || 0);
47
+ harmed += Math.max(0, week[3] || 0);
48
+ }
49
+ helped = Math.max(helped, probation.helped);
50
+ harmed = Math.max(harmed, probation.harmed);
51
+ const adoptions = Math.max(probation.adoptions, helped + harmed);
52
+ return { ...probation, helped, harmed, adoptions };
53
+ }
54
+ function eligible(row) {
55
+ return (row.status === 'published' &&
56
+ !row.pinned &&
57
+ row.trust !== 'human' &&
58
+ row.class === 'standard' &&
59
+ row.scope.kind !== 'team');
60
+ }
61
+ export class ProbationSweeper {
62
+ deps;
63
+ resumeAt = 0;
64
+ constructor(deps) {
65
+ this.deps = deps;
66
+ }
67
+ async sweep() {
68
+ const report = {
69
+ examined: 0,
70
+ continuing: 0,
71
+ graduated: 0,
72
+ rollbacks: 0,
73
+ enqueued: 0,
74
+ };
75
+ for (const row of this.nextWindow()) {
76
+ const read = await this.deps.store.readHead(row.scope, row.id);
77
+ if (read?.head.probation === undefined)
78
+ continue;
79
+ report.examined += 1;
80
+ await this.examine(row, read.head, report);
81
+ }
82
+ return report;
83
+ }
84
+ /** The next `limit` eligible rows in id order, wrapping around the end. */
85
+ nextWindow() {
86
+ const all = [...this.deps.rows()].filter(eligible).sort((a, b) => (a.id < b.id ? -1 : 1));
87
+ if (all.length === 0)
88
+ return [];
89
+ const limit = Math.min(this.deps.limit ?? DEFAULT_LIMIT, all.length);
90
+ const start = this.resumeAt % all.length;
91
+ this.resumeAt = (start + limit) % all.length;
92
+ return Array.from({ length: limit }, (_, i) => all[(start + i) % all.length]);
93
+ }
94
+ async examine(row, head, report) {
95
+ const { store, now } = this.deps;
96
+ const shard = await store.readStatsShard(row.scope, geneShard(row.id));
97
+ const window = probationWindow(head.probation, shard[row.id]);
98
+ const decision = evaluateProbation(window, { now: now(), hasPreviousPublished: true });
99
+ if (decision.action === 'continue')
100
+ report.continuing += 1;
101
+ if (decision.action === 'graduate')
102
+ report.graduated += 1;
103
+ if (decision.action !== 'rollback')
104
+ return;
105
+ report.rollbacks += 1;
106
+ const hasPrevious = (await previousPublished(store, row.scope, head)) !== null;
107
+ if (await this.enqueueRollback(row, head, hasPrevious))
108
+ report.enqueued += 1;
109
+ }
110
+ async enqueueRollback(row, head, hasPrevious) {
111
+ const route = hasPrevious ? 'previous' : 'revoke';
112
+ const action = hasPrevious ? 'roll back to the previous published version' : 'revoke it';
113
+ const proposal = buildSystemProposal({
114
+ kind: 'revoke',
115
+ scope: row.scope,
116
+ type: row.type,
117
+ target: { id: row.id, basisVersion: head.latestVersion },
118
+ now: this.deps.now(),
119
+ sessionId: this.deps.sessionId,
120
+ random: this.deps.random,
121
+ goal: 'Probation check by the background maintenance.',
122
+ why: `probation_rollback:${route} - harmed twice in probation, never helped; ${action}.`,
123
+ expectedBenefit: 'Stops a gene that is hurting runs from being served.',
124
+ });
125
+ return (await this.deps.enqueue(proposal)).ok;
126
+ }
127
+ }
@@ -0,0 +1,24 @@
1
+ import type { GeneEvidenceInput, GeneProposal, GeneScope, GeneType, ProposalKind } from '@aragon-agent/tui/model/gene/types';
2
+ export interface SystemProposalSeed {
3
+ kind: ProposalKind;
4
+ scope: GeneScope;
5
+ now: number;
6
+ sessionId: string;
7
+ random: (n: number) => number;
8
+ /** English, fixed text; clipped to `proposalWhyMax`. */
9
+ why: string;
10
+ expectedBenefit?: string;
11
+ /** English, one line: what made the system ask. Clipped to `proposalGoalMax`. */
12
+ goal: string;
13
+ type?: GeneType;
14
+ target?: {
15
+ id: string;
16
+ basisVersion: number | null;
17
+ };
18
+ /** Distinguishes two target-less requests of the same kind (`capacity:tool`, `periodic`). */
19
+ subject?: string;
20
+ evidence?: GeneEvidenceInput[];
21
+ }
22
+ export declare function buildSystemProposal(seed: SystemProposalSeed): GeneProposal;
23
+ /** Gene ids packed into evidence entries of at most `proposalEvidenceTextMax` characters each. */
24
+ export declare function idsAsEvidence(ids: readonly string[]): GeneEvidenceInput[];