@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,79 @@
1
+ import { containsCjk, tokenizeDetailed, tokenizeQuery, } from '@aragon-agent/tui/model/gene/tokenize';
2
+ // ---------------------------------------------------------------------------
3
+ // Holdout (13: a randomised comparison needs a deterministic, per-run draw)
4
+ // ---------------------------------------------------------------------------
5
+ function fnv1a32(text) {
6
+ let hash = 0x811c9dc5;
7
+ for (let i = 0; i < text.length; i += 1) {
8
+ hash ^= text.charCodeAt(i);
9
+ hash = Math.imul(hash, 0x01000193) >>> 0;
10
+ }
11
+ return hash >>> 0;
12
+ }
13
+ /** 0..99, the same for the same run id on every machine and every restart. */
14
+ export function holdoutBucket(runId) {
15
+ return fnv1a32(runId) % 100;
16
+ }
17
+ /** `hash(runId) % 100 < holdoutPercent`: the run deliberately does not use the library. */
18
+ export function isHoldoutRun(runId, percent) {
19
+ return Number.isFinite(percent) && percent > 0 && holdoutBucket(runId) < percent;
20
+ }
21
+ // ---------------------------------------------------------------------------
22
+ // Task text -> query terms
23
+ // ---------------------------------------------------------------------------
24
+ const TEXT_CAP = 4000;
25
+ const TERMS_CAP = 48;
26
+ /**
27
+ * Terms for the planner. UNSTEMMED words (`raws`): the planner joins them and the searcher stems
28
+ * them once, and stemming a stem is not guaranteed to be a no-op. CJK has no raw form (the
29
+ * tokenizer treats it as a separator), so its bigrams are appended from `tokenizeQuery`.
30
+ */
31
+ export function queryTermsOf(text) {
32
+ const clipped = text.slice(0, TEXT_CAP);
33
+ const terms = new Set(tokenizeDetailed(clipped).raws);
34
+ if (containsCjk(clipped)) {
35
+ for (const token of tokenizeQuery(clipped))
36
+ if (containsCjk(token))
37
+ terms.add(token);
38
+ }
39
+ return [...terms].slice(0, TERMS_CAP);
40
+ }
41
+ export function offContext(role, budgetItems = 0, budgetTokens = 0) {
42
+ return { role, loadedItems: 0, loadedTokens: 0, budgetItems, budgetTokens, stopReason: 'off' };
43
+ }
44
+ /**
45
+ * What the zone last said, per role. The system prompt is rebuilt every user turn, so the text
46
+ * lives HERE (not in the controller) and `renderContextBlock` just hands it back; hysteresis needs
47
+ * the previous text to keep it byte for byte.
48
+ */
49
+ export class ContextState {
50
+ snapshots = new Map();
51
+ view;
52
+ /** The visible gene set changed after the last plan; applied at the NEXT user turn (9.3). */
53
+ dirty = false;
54
+ constructor(role) {
55
+ this.view = offContext(role);
56
+ }
57
+ previous(role) {
58
+ return this.snapshots.get(role);
59
+ }
60
+ remember(role, snapshot) {
61
+ this.snapshots.set(role, snapshot);
62
+ }
63
+ /** Forget the hysteresis memory of one role, or of all of them. */
64
+ reset(role) {
65
+ if (role === undefined)
66
+ this.snapshots.clear();
67
+ else
68
+ this.snapshots.delete(role);
69
+ }
70
+ textOf(role) {
71
+ return this.snapshots.get(role)?.text ?? '';
72
+ }
73
+ setView(view) {
74
+ this.view = view;
75
+ }
76
+ getView() {
77
+ return this.view;
78
+ }
79
+ }
@@ -0,0 +1,25 @@
1
+ import type { GeneResult, GeneScope, GeneType } from '@aragon-agent/tui/model/gene/types';
2
+ import { type CapacityEnv } from './capacity.js';
3
+ import { type PreparedContent } from './commit-prepare.js';
4
+ import type { GeneActor } from './commit-types.js';
5
+ import type { ApplicableChange } from './commit-apply-types.js';
6
+ import type { GeneStore } from './store.js';
7
+ export interface PrepareEnv {
8
+ store: GeneStore;
9
+ cap: CapacityEnv;
10
+ now: () => number;
11
+ knownSecrets: () => readonly string[];
12
+ random: (n: number) => number;
13
+ }
14
+ export interface Prepared {
15
+ /** The scope whose lock the commit takes. */
16
+ scope: GeneScope;
17
+ reason: string;
18
+ content?: PreparedContent;
19
+ newId?: string;
20
+ /** Set when this commit adds a published gene of this type (the capacity pre-step runs). */
21
+ growsType?: GeneType;
22
+ }
23
+ export declare function defaultRandom(n: number): number;
24
+ export declare function checkScopeFor(env: PrepareEnv, scope: GeneScope, actor: GeneActor): GeneResult<void>;
25
+ export declare function prepareChange(env: PrepareEnv, change: ApplicableChange, actor: GeneActor): Promise<GeneResult<Prepared>>;
@@ -0,0 +1,219 @@
1
+ /**
2
+ * Everything the version service decides BEFORE it takes a lock (gene-bank spec 7.1 step 1,
3
+ * 7.2, 11.1, 11.3; I-12, I-16, I-22).
4
+ *
5
+ * ASCII ONLY - the whole `gene/` tree is in `glyphs.test.ts::inScope`.
6
+ *
7
+ * `prepareChange` turns a request into a `Prepared`: which scope's lock to take, the cleaned
8
+ * reason, the finalised content and evidence, the freshly minted id for a create, and - for the
9
+ * operations that add a PUBLISHED gene to the library - the type whose capacity must be checked.
10
+ * It reads the disk only to learn what a request refers to (a head's type, the evidence a gene
11
+ * already has) and never writes; everything it reads is re-read under the lock by the planner,
12
+ * so a race here costs at worst a wasted pre-check, never a wrong write.
13
+ *
14
+ * WHAT IS REFUSED HERE rather than in a planner: invalid ids and scopes, a read-only team scope,
15
+ * automation reaching for the team scope at all, content that fails validation or contains a
16
+ * secret, an oversight gene proposed by a non-human, a reason that is missing or not English, and
17
+ * the library-wide pin / candidate budgets. A planner still re-checks the per-scope bounds inside
18
+ * the lock, because the library-wide figures here are a cached sum.
19
+ */
20
+ import { randomInt } from 'node:crypto';
21
+ import { GENE_TYPES } from '@aragon-agent/tui/model/gene/types';
22
+ import { geneTypeOfId, isValidGeneId, isValidScope, mintGeneId, } from '@aragon-agent/tui/model/gene/ids';
23
+ import { geneFail, geneOk } from './gene-errors.js';
24
+ import { geneLooksLikeSecret } from './secrets.js';
25
+ import { scopeDir } from './paths.js';
26
+ import { scopeKeyIsSafe } from './scope-guard.js';
27
+ import { checkCandidateBudget, checkPinBudget } from './capacity.js';
28
+ import { cleanReason, prepareContent } from './commit-prepare.js';
29
+ export function defaultRandom(n) {
30
+ return randomInt(n);
31
+ }
32
+ const HEALTH_REASON_MAX = 120;
33
+ export function checkScopeFor(env, scope, actor) {
34
+ if (!isValidScope(scope) || !scopeKeyIsSafe(scope)) {
35
+ return geneFail('GENE_SCOPE_FORBIDDEN', 'That scope is not valid.', 'bad_scope');
36
+ }
37
+ if (scope.kind === 'team' && actor.kind === 'curator') {
38
+ return geneFail('GENE_SCOPE_FORBIDDEN', 'The curator never writes the team scope.', 'team');
39
+ }
40
+ if (!env.store.isWritable(scope) || scopeDir(scope, env.store.ctx) === null) {
41
+ return geneFail('GENE_SCOPE_READONLY', 'The team scope is read-only.');
42
+ }
43
+ return geneOk(undefined);
44
+ }
45
+ function checkId(id) {
46
+ if (isValidGeneId(id))
47
+ return geneOk(undefined);
48
+ return geneFail('GENE_INVALID_ID', 'That gene id is not valid.');
49
+ }
50
+ async function mintId(env, change, actor) {
51
+ const imported = actor.kind === 'import' || actor.kind === 'migration';
52
+ if (change.id !== undefined && imported) {
53
+ const valid = isValidGeneId(change.id) && geneTypeOfId(change.id) === change.type;
54
+ return valid ? geneOk(change.id) : geneFail('GENE_INVALID_ID', 'That gene id is not valid.');
55
+ }
56
+ for (let attempt = 0; attempt < 5; attempt += 1) {
57
+ const id = mintGeneId(change.type, env.random);
58
+ if (!(await env.store.headExistsAnywhere(change.scope, id)))
59
+ return geneOk(id);
60
+ }
61
+ return geneFail('GENE_UNAVAILABLE', 'Could not allocate a gene id.', 'id_collision');
62
+ }
63
+ async function prepareCreate(env, change, actor) {
64
+ if (!GENE_TYPES.includes(change.type)) {
65
+ return geneFail('GENE_INVALID_CONTENT', 'Unknown gene type.', 'bad_schema');
66
+ }
67
+ const secrets = env.knownSecrets();
68
+ const reason = cleanReason(change.reason, secrets);
69
+ if (!reason.ok)
70
+ return reason;
71
+ const id = await mintId(env, change, actor);
72
+ if (!id.ok)
73
+ return id;
74
+ const content = prepareContent({
75
+ type: change.type,
76
+ content: change.content,
77
+ scope: change.scope,
78
+ actor,
79
+ geneId: id.value,
80
+ knownSecrets: secrets,
81
+ now: env.now(),
82
+ random: env.random,
83
+ class: change.class ?? 'standard',
84
+ ...(change.evidence ? { evidence: change.evidence } : {}),
85
+ });
86
+ if (!content.ok)
87
+ return content;
88
+ const budget = await createBudgets(env, change, actor);
89
+ if (!budget.ok)
90
+ return budget;
91
+ const prepared = {
92
+ scope: change.scope,
93
+ reason: reason.value,
94
+ content: content.value,
95
+ newId: id.value,
96
+ };
97
+ if (actor.kind === 'user')
98
+ prepared.growsType = change.type;
99
+ return geneOk(prepared);
100
+ }
101
+ async function createBudgets(env, change, actor) {
102
+ if (actor.kind !== 'user')
103
+ return checkCandidateBudget(env.cap, change.type);
104
+ return change.pinned === true ? checkPinBudget(env.cap, change.type) : geneOk(undefined);
105
+ }
106
+ /** The script text of a stored tool, so the risk floor sees it when an edit omits it. */
107
+ async function storedScript(env, head, edit) {
108
+ if (head.type !== 'tool')
109
+ return undefined;
110
+ const exec = edit.content.payload.exec;
111
+ if (exec === undefined || exec.kind !== 'script')
112
+ return undefined;
113
+ return (await env.store.readEvidence(head.scope, head.id, exec.evidence))?.text;
114
+ }
115
+ async function prepareEdit(env, change, actor) {
116
+ const id = checkId(change.id);
117
+ if (!id.ok)
118
+ return id;
119
+ const read = await env.store.readHead(change.scope, change.id);
120
+ if (read === null) {
121
+ return geneFail('GENE_NOT_FOUND', 'The gene was not found in that state.', 'missing');
122
+ }
123
+ const secrets = env.knownSecrets();
124
+ const reason = cleanReason(change.reason, secrets);
125
+ if (!reason.ok)
126
+ return reason;
127
+ const existing = await env.store.listEvidence(change.scope, change.id);
128
+ const script = await storedScript(env, read.head, change);
129
+ const content = prepareContent({
130
+ type: read.head.type,
131
+ content: change.content,
132
+ scope: change.scope,
133
+ actor,
134
+ geneId: change.id,
135
+ knownSecrets: secrets,
136
+ now: env.now(),
137
+ random: env.random,
138
+ class: read.head.class,
139
+ existingRefs: existing.map((e) => e.ref),
140
+ existingEvidenceBytes: existing.reduce((sum, e) => sum + Buffer.byteLength(e.text), 0),
141
+ ...(script === undefined ? {} : { storedScriptText: script }),
142
+ ...(change.evidence ? { evidence: change.evidence } : {}),
143
+ });
144
+ if (!content.ok)
145
+ return content;
146
+ const prepared = { scope: change.scope, reason: reason.value, content: content.value };
147
+ const publishes = actor.kind === 'user' || change.direct === true;
148
+ if (publishes && read.head.status === 'candidate')
149
+ prepared.growsType = read.head.type;
150
+ return geneOk(prepared);
151
+ }
152
+ const REASON_OPS = new Set(['rejectCandidate', 'archive', 'revoke']);
153
+ /** A health reason is a short machine token: bounded, and never a secret. */
154
+ function checkHealthReason(env, text) {
155
+ if (text === undefined)
156
+ return geneOk(undefined);
157
+ const unusable = text.length > HEALTH_REASON_MAX || geneLooksLikeSecret(text, env.knownSecrets());
158
+ if (!unusable)
159
+ return geneOk(undefined);
160
+ return geneFail('GENE_INVALID_CONTENT', 'The health reason is not acceptable.', 'bad_schema');
161
+ }
162
+ /** Library-wide pin budget (7.4.3), checked only when a PUBLISHED gene is being pinned. */
163
+ async function checkPinning(env, scope, id) {
164
+ const read = await env.store.readHead(scope, id);
165
+ if (read === null || read.head.status !== 'published')
166
+ return geneOk(undefined);
167
+ return checkPinBudget(env.cap, read.head.type);
168
+ }
169
+ /** The checks that depend on the operation's own fields (not on content). */
170
+ async function checkOperationFields(env, change) {
171
+ if (change.op === 'setHealth')
172
+ return checkHealthReason(env, change.healthReason);
173
+ if (change.op === 'setPinned' && change.pinned)
174
+ return checkPinning(env, change.scope, change.id);
175
+ return geneOk(undefined);
176
+ }
177
+ async function prepareSimple(env, change) {
178
+ const scope = change.scope;
179
+ const id = checkId(change.id);
180
+ if (!id.ok)
181
+ return id;
182
+ const prepared = { scope, reason: '' };
183
+ if (REASON_OPS.has(change.op)) {
184
+ const reason = cleanReason(change.reason, env.knownSecrets());
185
+ if (!reason.ok)
186
+ return reason;
187
+ prepared.reason = reason.value;
188
+ }
189
+ const fields = await checkOperationFields(env, change);
190
+ if (!fields.ok)
191
+ return fields;
192
+ const grows = await growthOf(env, change);
193
+ if (grows !== undefined)
194
+ prepared.growsType = grows;
195
+ return geneOk(prepared);
196
+ }
197
+ /** Does this operation add a PUBLISHED gene to the library? (Then capacity is checked first.) */
198
+ async function growthOf(env, change) {
199
+ if (change.op === 'publishCandidate') {
200
+ const read = await env.store.readHead(change.scope, change.id);
201
+ return read !== null && read.head.status === 'candidate' ? read.head.type : undefined;
202
+ }
203
+ if (change.op === 'restore') {
204
+ const read = await env.store.readArchivedHead(change.scope, change.id);
205
+ return read !== null && read.head.currentVersion !== null ? read.head.type : undefined;
206
+ }
207
+ return undefined;
208
+ }
209
+ export async function prepareChange(env, change, actor) {
210
+ const scope = change.scope;
211
+ const allowed = checkScopeFor(env, scope, actor);
212
+ if (!allowed.ok)
213
+ return allowed;
214
+ if (change.op === 'create')
215
+ return prepareCreate(env, change, actor);
216
+ if (change.op === 'edit')
217
+ return prepareEdit(env, change, actor);
218
+ return prepareSimple(env, change);
219
+ }
@@ -0,0 +1,196 @@
1
+ /**
2
+ * Shapes shared by `GeneService`, the tools, the hint engine and the controller
3
+ * (gene-bank spec 9.1, 9.3, 9.4, 12.8).
4
+ *
5
+ * ASCII ONLY - the whole `gene/` tree is in `glyphs.test.ts::inScope`. TYPES ONLY.
6
+ *
7
+ * EVERY RESULT HERE IS TIER-1 OR EXPLICITLY A READ. `GeneSearchOutput` carries brief lines and
8
+ * numbers and no body text anywhere (I-1); `GeneReadOutput` is the only shape that holds tier-2 or
9
+ * tier-3 text, and it exists only as the answer to a `read`. The structure is the guarantee: a
10
+ * consumer cannot print a body out of a search result because the result has no such field.
11
+ */
12
+ import type { GeneConfig } from '@aragon-agent/tui/model/config/schema';
13
+ import type { EnvFingerprint, GeneContextPlan, GeneFilterReason, GeneHealth, GeneRole, GeneScope, GeneScopeKind, GeneSessionView, GeneType, ToolPayload } from '@aragon-agent/tui/model/gene/types';
14
+ import type { GeneCatalog } from './catalog.js';
15
+ import type { GeneStoreReader } from './store-port.js';
16
+ import type { GeneUsageSink, TimerPort } from './usage.js';
17
+ /** Who is calling: the unit of `shown` de-duplication and of the holdout draw. */
18
+ export interface GeneActor {
19
+ runId: string;
20
+ /** Whose visibility rules apply; defaults to the service's own role. */
21
+ role?: GeneRole;
22
+ /** Label of a sub-agent / team member, recorded on usage events. */
23
+ agent?: string;
24
+ }
25
+ export type GeneGate = {
26
+ ok: true;
27
+ } | {
28
+ ok: false;
29
+ code: 'GENE_DISABLED' | 'GENE_USE_OFF' | 'GENE_HOLDOUT';
30
+ message: string;
31
+ };
32
+ export interface GeneLogPort {
33
+ warn(message: string, data?: Record<string, unknown>): void;
34
+ }
35
+ export type GeneVerdict = 'helped' | 'misleading' | 'not_applicable' | 'outdated';
36
+ export type GeneEffect = 'helped' | 'harmed' | 'neutral';
37
+ /** A feedback signal for the learner (7.5, L3): `misleading` / `outdated` are strong ones. */
38
+ export interface GeneFeedbackSignal {
39
+ geneId: string;
40
+ scope: GeneScope;
41
+ verdict: GeneVerdict;
42
+ effect: GeneEffect;
43
+ runId: string;
44
+ agent?: string;
45
+ /** Already secret-redacted and clipped. Never written to the usage log. */
46
+ note?: string;
47
+ }
48
+ export interface GeneServiceDeps {
49
+ reader: GeneStoreReader;
50
+ /** The live configuration; read at CALL time (I-18). */
51
+ getConfig(): GeneConfig;
52
+ getCwd(): string;
53
+ sessionId: string;
54
+ now(): number;
55
+ env(): EnvFingerprint;
56
+ registeredTools(): readonly string[];
57
+ windowTokens(): number;
58
+ /** Configured provider keys, so a feedback note holding one is scrubbed by value. */
59
+ knownSecrets(): readonly string[];
60
+ /** The role of the process's own agent; an actor may override it per call. */
61
+ role: GeneRole;
62
+ usage: GeneUsageSink;
63
+ /** Share a catalog (tests, the manager); otherwise the service builds and owns one. */
64
+ catalog?: GeneCatalog;
65
+ /** Directory name of the team scope under `gene.teamPath`. Default `team`. */
66
+ teamKey?: string;
67
+ /** How long a tool call waits for the index to catch up. Default `searchBudgetMs`. */
68
+ syncWaitMs?: number;
69
+ timer?: TimerPort;
70
+ /** Minimum gap between two view notifications (4 Hz = 250). */
71
+ emitIntervalMs?: number;
72
+ log?: GeneLogPort;
73
+ onFeedback?(signal: GeneFeedbackSignal): void;
74
+ }
75
+ export interface GeneSearchRequest {
76
+ query?: string;
77
+ type?: GeneType | 'all';
78
+ scope?: GeneScopeKind | 'all';
79
+ limit?: number;
80
+ offset?: number;
81
+ explain?: boolean;
82
+ }
83
+ export interface GeneSearchRow {
84
+ id: string;
85
+ type: GeneType;
86
+ scope: GeneScopeKind;
87
+ /** The tier-1 brief line, already escaped. */
88
+ line: string;
89
+ relevance: number;
90
+ /** Scores and field names only, when `explain` was asked for. */
91
+ explain?: string;
92
+ }
93
+ export interface GeneSearchOutput {
94
+ rows: GeneSearchRow[];
95
+ /** Matches before paging. */
96
+ total: number;
97
+ /** Visible genes that existed before filtering. */
98
+ visible: number;
99
+ filtered: Partial<Record<GeneFilterReason, number>>;
100
+ filteredTotal: number;
101
+ offset: number;
102
+ limit: number;
103
+ nextOffset?: number;
104
+ partial?: boolean;
105
+ degraded?: 'index_rebuilding' | 'index_unavailable';
106
+ /** The query had CJK text and few results: suggest English keywords (8.3.3). */
107
+ englishTip: boolean;
108
+ /** A ready-to-print rendering of the above. Contains tier-1 lines only. */
109
+ text: string;
110
+ }
111
+ export interface GeneReadRequest {
112
+ /** A gene id, or a unique name. */
113
+ id?: string;
114
+ name?: string;
115
+ tier?: 2 | 3;
116
+ /** Tier 3: an evidence ref, or `list` / absent for the list. */
117
+ ref?: string;
118
+ /** Character cursor into the rendered text (the `Next:` line says what to pass). */
119
+ offset?: number;
120
+ }
121
+ export interface GeneReadOutput {
122
+ id: string;
123
+ name: string;
124
+ tier: 2 | 3;
125
+ ref?: string;
126
+ /** The chunk, including a trailing `Next:` line when more remains. */
127
+ text: string;
128
+ next?: number;
129
+ }
130
+ export interface GeneFeedbackRequest {
131
+ id: string;
132
+ verdict: GeneVerdict;
133
+ note?: string;
134
+ }
135
+ export interface GeneFeedbackOutput {
136
+ id: string;
137
+ name: string;
138
+ verdict: GeneVerdict;
139
+ effect: GeneEffect;
140
+ }
141
+ export interface GeneToolDescription {
142
+ id: string;
143
+ name: string;
144
+ version: number;
145
+ scope: GeneScope;
146
+ health: GeneHealth;
147
+ payload: ToolPayload;
148
+ }
149
+ export interface GeneToolRun {
150
+ id: string;
151
+ /** The command exited as the gene's contract says it should. */
152
+ ok: boolean;
153
+ /** A failure plainly caused by the arguments (`classifyToolFailure`): neutral, not harmed. */
154
+ inputError?: boolean;
155
+ }
156
+ export interface GeneHintRequest {
157
+ text: string;
158
+ minRelevance: number;
159
+ max: number;
160
+ types?: readonly GeneType[];
161
+ }
162
+ export interface GeneHintHit {
163
+ id: string;
164
+ type: GeneType;
165
+ line: string;
166
+ relevance: number;
167
+ }
168
+ export type GeneContextReason = 'user_turn' | 'cwd' | 'clear' | 'resume' | 'model' | 'settings';
169
+ export interface GeneContextRequest {
170
+ runId: string;
171
+ role?: GeneRole;
172
+ /** The task text; tokenised here. */
173
+ taskText?: string;
174
+ /** Pre-tokenised terms (the reviewer passes ledger terms); used when given. */
175
+ queryTerms?: readonly string[];
176
+ /** Override the process window (a sub-agent's model). */
177
+ windowTokens?: number;
178
+ /** Why the zone is being refreshed; anything but `user_turn` drops the hysteresis state. */
179
+ reason?: GeneContextReason;
180
+ }
181
+ export interface GeneContextOutput {
182
+ /** The `<gene_context>` block, '' when the zone is off or empty. */
183
+ text: string;
184
+ plan: GeneContextPlan | null;
185
+ /** The previous text was kept byte for byte (hysteresis). */
186
+ reused: boolean;
187
+ degraded?: 'index_rebuilding' | 'index_unavailable';
188
+ budgetItems: number;
189
+ budgetTokens: number;
190
+ }
191
+ /** The part of `GeneSessionView` this process knows without the learner and the curator. */
192
+ export type GeneServiceView = Pick<GeneSessionView, 'available' | 'use' | 'autoLearn' | 'revision' | 'library' | 'context' | 'retrieving'>;
193
+ export interface GeneCallerOverrides {
194
+ tools?: readonly string[];
195
+ windowTokens?: number;
196
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,41 @@
1
+ /**
2
+ * Revision and notification bookkeeping for the session view (gene-bank spec 12.8, I-23).
3
+ *
4
+ * ASCII ONLY - the whole `gene/` tree is in `glyphs.test.ts::inScope`.
5
+ *
6
+ * `GeneService` knows WHAT the view says; this class knows WHEN to tell people. It owns three
7
+ * rules the UI relies on:
8
+ * - `revision` is monotonic and bumps only when the view's CONTENT changed, so a subscriber
9
+ * that compares revisions never repaints for nothing;
10
+ * - notifications are throttled to one per `intervalMs` (4 Hz), with a trailing one so the last
11
+ * change is never lost to the throttle;
12
+ * - a throwing subscriber cannot stop the others, and nothing here ever throws.
13
+ */
14
+ import type { GeneServiceView } from './service-types.js';
15
+ import type { TimerPort } from './usage.js';
16
+ export interface ViewEmitterOptions {
17
+ /** The view as it is right now, WITHOUT a revision (the emitter owns that). */
18
+ snapshot(): Omit<GeneServiceView, 'revision'>;
19
+ now(): number;
20
+ timer: TimerPort;
21
+ intervalMs: number;
22
+ onError(error: unknown): void;
23
+ }
24
+ export declare class ViewEmitter {
25
+ private readonly options;
26
+ private readonly listeners;
27
+ private revisionNumber;
28
+ private lastKey;
29
+ private lastNotifyAt;
30
+ private timerHandle;
31
+ private stopped;
32
+ constructor(options: ViewEmitterOptions);
33
+ get revision(): number;
34
+ subscribe(listener: () => void): () => void;
35
+ /** Bump the revision when the view differs from the last one, then notify (throttled). */
36
+ emitIfChanged(): void;
37
+ private notify;
38
+ private deliver;
39
+ /** Stop notifying and release the pending timer. */
40
+ dispose(): void;
41
+ }
@@ -0,0 +1,69 @@
1
+ export class ViewEmitter {
2
+ options;
3
+ listeners = new Set();
4
+ revisionNumber = 0;
5
+ lastKey = '';
6
+ lastNotifyAt = Number.NEGATIVE_INFINITY;
7
+ timerHandle = null;
8
+ stopped = false;
9
+ constructor(options) {
10
+ this.options = options;
11
+ }
12
+ get revision() {
13
+ return this.revisionNumber;
14
+ }
15
+ subscribe(listener) {
16
+ this.listeners.add(listener);
17
+ return () => {
18
+ this.listeners.delete(listener);
19
+ };
20
+ }
21
+ /** Bump the revision when the view differs from the last one, then notify (throttled). */
22
+ emitIfChanged() {
23
+ if (this.stopped)
24
+ return;
25
+ try {
26
+ const key = JSON.stringify(this.options.snapshot());
27
+ if (key === this.lastKey)
28
+ return;
29
+ this.lastKey = key;
30
+ this.revisionNumber += 1;
31
+ this.notify();
32
+ }
33
+ catch (error) {
34
+ this.options.onError(error);
35
+ }
36
+ }
37
+ notify() {
38
+ if (this.listeners.size === 0 || this.timerHandle !== null)
39
+ return;
40
+ const wait = this.lastNotifyAt + this.options.intervalMs - this.options.now();
41
+ if (wait <= 0) {
42
+ this.deliver();
43
+ return;
44
+ }
45
+ this.timerHandle = this.options.timer.set(() => {
46
+ this.timerHandle = null;
47
+ this.deliver();
48
+ }, wait);
49
+ }
50
+ deliver() {
51
+ this.lastNotifyAt = this.options.now();
52
+ for (const listener of [...this.listeners]) {
53
+ try {
54
+ listener();
55
+ }
56
+ catch {
57
+ // One broken subscriber must not stop the others from repainting.
58
+ }
59
+ }
60
+ }
61
+ /** Stop notifying and release the pending timer. */
62
+ dispose() {
63
+ this.stopped = true;
64
+ this.listeners.clear();
65
+ if (this.timerHandle !== null)
66
+ this.options.timer.clear(this.timerHandle);
67
+ this.timerHandle = null;
68
+ }
69
+ }