@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,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
+ }
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Approving a candidate: the person's path to publication (gene-bank spec 7.6, 10.7.2, 12.2, RV-1,
3
+ * I-25).
4
+ *
5
+ * ASCII ONLY - the whole `gene/` tree is in `glyphs.test.ts::inScope`.
6
+ *
7
+ * `approve` IS A PUBLICATION BY A PERSON, `trust: 'human'`, skipping the curator. For most
8
+ * candidates that is just `publishCandidate`. A TOOL gene is different: the background curator
9
+ * only ever probes a single read-only command on its own, so every other tool (a script, a
10
+ * composite, a command that writes, anything it rated `high`) reaches here still unprobed, with
11
+ * `needsHuman: probe_approval | high_risk_tool`. For those the person's click means
12
+ * "APPROVE AND PROBE": the example runs in the sandbox (`runApprovedProbe`), and only when it
13
+ * passes is the candidate published, with the approval - bound to this exact content hash - and
14
+ * the probe's checks written into its validation.
15
+ *
16
+ * WHAT MAKES THE APPROVAL MEAN SOMETHING. The person was shown the full argv or script
17
+ * (`candidates()` -> `probePreview`) before this is called; the port has no "I read it" field, so
18
+ * that is the UI's contract (the approve button stays disabled until the text was scrolled). What
19
+ * THIS file enforces: the approval carries the hash of the version it saw, so an edit after the
20
+ * click invalidates it (`approval_stale`); the commit carries `expectedVersion`, so a stale view
21
+ * is `GENE_STALE_BASIS`; a failed example publishes NOTHING and names the failing check codes.
22
+ */
23
+ import type { GeneActionOutcome } from '@aragon-agent/tui/model/gene/port';
24
+ import type { GeneResult } from '@aragon-agent/tui/model/gene/types';
25
+ import type { FoundGene, ManagerCore } from './manager-context.js';
26
+ import type { GeneActor, GeneExpect } from './commit-types.js';
27
+ export declare const MANAGER_ACTOR: GeneActor;
28
+ /** `approve`: publish the pending candidate as a person, probing a tool first when it needs it. */
29
+ export declare function approveCandidate(core: ManagerCore, found: FoundGene, expect: GeneExpect | undefined): Promise<GeneResult<GeneActionOutcome>>;
@@ -0,0 +1,84 @@
1
+ import { mergeApprovedProbe, runApprovedProbe, } from './curator/probe.js';
2
+ import { geneFail, geneOk } from './gene-errors.js';
3
+ import { screenToolExec } from './tool-screen.js';
4
+ export const MANAGER_ACTOR = { kind: 'user', label: 'manager' };
5
+ function toolPayloadOf(version) {
6
+ const payload = version.content.payload;
7
+ const isTool = payload.exec !== undefined && typeof payload.risk === 'string';
8
+ return isTool ? payload : null;
9
+ }
10
+ /** Does this candidate need a person-approved probe before it can be published? */
11
+ async function probePlanFor(core, found, candidate) {
12
+ const payload = toolPayloadOf(candidate);
13
+ if (payload === null)
14
+ return null;
15
+ const { scope, read } = found;
16
+ let scriptText;
17
+ if (payload.exec.kind === 'script') {
18
+ const impl = await core.lib.store.readEvidence(scope, read.head.id, payload.exec.evidence);
19
+ scriptText = impl?.text;
20
+ }
21
+ const why = read.head.needsHuman?.reason;
22
+ const flagged = why === 'probe_approval' || why === 'high_risk_tool';
23
+ const screened = screenToolExec(payload.exec, scriptText);
24
+ if (!flagged && screened.autoProbeEligible)
25
+ return null;
26
+ return scriptText === undefined ? { payload } : { payload, scriptText };
27
+ }
28
+ /** The checks that failed, as stable codes: output text never leaves the probe (I-19). */
29
+ function failingCodes(validation) {
30
+ const codes = validation.checks.filter((check) => !check.ok).map((check) => check.code);
31
+ return `probe_failed:${codes.length > 0 ? codes.join(',') : 'unknown'}`;
32
+ }
33
+ async function probeCandidate(core, found, candidate, plan) {
34
+ const approval = {
35
+ by: 'user',
36
+ at: core.now(),
37
+ contentHash: candidate.contentHash,
38
+ };
39
+ const outcome = await runApprovedProbe({ id: found.read.head.id }, candidate, approval, {
40
+ confirmHighRisk: true,
41
+ ...(plan.scriptText === undefined ? {} : { scriptText: plan.scriptText }),
42
+ ...core.options.probe,
43
+ });
44
+ if (!outcome.ok)
45
+ return geneFail(outcome.code, outcome.message, outcome.reason);
46
+ if (!outcome.validation.ok) {
47
+ const message = 'The tool failed its example run, so it was not published.';
48
+ return geneFail('GENE_TOOL_BROKEN', message, failingCodes(outcome.validation));
49
+ }
50
+ const base = candidate.validation ?? { at: core.now(), ok: true, checks: [] };
51
+ return geneOk(mergeApprovedProbe(base, outcome));
52
+ }
53
+ /** `approve`: publish the pending candidate as a person, probing a tool first when it needs it. */
54
+ export async function approveCandidate(core, found, expect) {
55
+ const { scope, read } = found;
56
+ const head = read.head;
57
+ if (found.archived || head.candidateVersion === null) {
58
+ return geneFail('GENE_NOT_FOUND', 'The gene has no candidate to approve.', 'no_candidate');
59
+ }
60
+ const candidate = await core.lib.store.readVersion(scope, head.id, head.candidateVersion);
61
+ if (candidate === null) {
62
+ return geneFail('GENE_NOT_FOUND', 'The candidate version is missing.', 'candidate_missing');
63
+ }
64
+ const plan = await probePlanFor(core, found, candidate);
65
+ let validation;
66
+ if (plan !== null) {
67
+ const probed = await probeCandidate(core, found, candidate, plan);
68
+ if (!probed.ok)
69
+ return probed;
70
+ validation = probed.value;
71
+ }
72
+ const committed = await core.lib.versions.commit({
73
+ op: 'publishCandidate',
74
+ scope,
75
+ id: head.id,
76
+ ...(validation === undefined ? {} : { validation }),
77
+ }, MANAGER_ACTOR, expect);
78
+ if (!committed.ok)
79
+ return committed;
80
+ const out = { id: head.id };
81
+ if (committed.value.version !== undefined)
82
+ out.version = committed.value.version;
83
+ return geneOk(out);
84
+ }
@@ -0,0 +1,90 @@
1
+ import { type GeneConfig } from '@aragon-agent/tui/model/config/schema';
2
+ import type { GeneTarget } from '@aragon-agent/tui/model/gene/port';
3
+ import type { EnvFingerprint, GeneCaller, GeneHead, GeneResult, GeneScope } from '@aragon-agent/tui/model/gene/types';
4
+ import { GeneCatalog } from './catalog.js';
5
+ import { type SharedLibrary } from './manager-library.js';
6
+ import type { ApprovedProbeOptions } from './curator/probe.js';
7
+ import type { ExplainSpend, ExplainTransport } from './explain.js';
8
+ import type { SkillSourcePort } from './import-sources.js';
9
+ import type { HeadRead } from './store-port.js';
10
+ export interface GeneManagerOptions {
11
+ /** Working directory of the session; decides which project scope is "visible". */
12
+ cwd: string;
13
+ sessionId: string;
14
+ /** External read-only team directory from `gene.teamPath`, or ''. */
15
+ teamPath?: string;
16
+ /** Library root override (tests). Defaults to `<home>/genes`. */
17
+ root?: string;
18
+ /** Live gene configuration; defaults to the persisted one, clamped and cached for 2 s. */
19
+ config?: () => GeneConfig;
20
+ /** The user's provider keys, so text holding one is scrubbed by value. Default: the registry. */
21
+ knownSecrets?: () => readonly string[];
22
+ /** Who is running the manager; goes on run records. Default `tui`. */
23
+ kind?: 'tui' | 'desktop' | 'exec';
24
+ /** Allow the one human-approved promotion into the team directory. Default false. */
25
+ teamWritable?: boolean;
26
+ now?: () => number;
27
+ /** The environment the "applies here" line is computed against (tests). */
28
+ env?: () => EnvFingerprint;
29
+ /** Test seams of the sandboxed probe a person approves. Production passes nothing. */
30
+ probe?: ApprovedProbeOptions;
31
+ /** The model an explanation uses. Default: the fast tier of the persisted configuration. */
32
+ explainTransport?: ExplainTransport;
33
+ /** Receives the spend of every explanation (a session routes it into its cost row). */
34
+ onExplainSpend?: (spend: ExplainSpend) => void;
35
+ /** The skills a cold-start import reads. Default: a read-only service over the configuration. */
36
+ skillSources?: () => SkillSourcePort | null;
37
+ /** Deadline of one explanation call in ms (a test seam; default 20 s). */
38
+ explainTimeoutMs?: number;
39
+ /** The terminal's locale string, for `explainLanguage: auto`. Default `LC_ALL` / `LANG`. */
40
+ locale?: () => string;
41
+ }
42
+ export interface ProjectInfo {
43
+ key: string;
44
+ root: string;
45
+ label: string;
46
+ }
47
+ /** The key of the team scope under `gene.teamPath` (the service uses the same default). */
48
+ export declare const TEAM_SCOPE_KEY = "team";
49
+ /** The catalogs built so far, keyed by their scope list; the oldest is dropped past six. */
50
+ export declare class CatalogPool {
51
+ private readonly lib;
52
+ private readonly now;
53
+ private readonly byKey;
54
+ constructor(lib: SharedLibrary, now: () => number);
55
+ /** A catalog over exactly `scopes`, caught up with the disk. Never rejects. */
56
+ acquire(scopes: readonly GeneScope[]): Promise<GeneCatalog>;
57
+ private evict;
58
+ dispose(): void;
59
+ }
60
+ export interface ManagerCore {
61
+ readonly options: GeneManagerOptions;
62
+ readonly lib: SharedLibrary;
63
+ readonly pool: CatalogPool;
64
+ config(): GeneConfig;
65
+ now(): number;
66
+ secrets(): readonly string[];
67
+ project(): ProjectInfo | null;
68
+ visibleScopes(): GeneScope[];
69
+ scopesOf(target: GeneTarget): Promise<GeneResult<GeneScope[]>>;
70
+ env(): EnvFingerprint;
71
+ /** A caller for score explanations: the session's scopes, role `main`, tools not checked. */
72
+ callerFor(scopes: GeneScope[], tools: readonly string[]): GeneCaller;
73
+ }
74
+ /** Build the shared state of one manager. Never throws. */
75
+ export declare function createManagerCore(options: GeneManagerOptions): ManagerCore;
76
+ export interface FoundGene {
77
+ scope: GeneScope;
78
+ read: HeadRead;
79
+ /** The head was in `archive/`, not `genes/`. */
80
+ archived: boolean;
81
+ }
82
+ /**
83
+ * Locate a gene by id among the scopes `target` addresses: live first, then archived. The id is
84
+ * validated before any path is built from it.
85
+ */
86
+ export declare function findGene(core: ManagerCore, target: GeneTarget, id: string): Promise<GeneResult<FoundGene>>;
87
+ /** The version number whose content a head serves: published, else the pending candidate. */
88
+ export declare function servedVersion(head: GeneHead): number;
89
+ /** Run a port method body so that nothing it throws escapes (I-24). */
90
+ export declare function guarded<T>(work: () => Promise<GeneResult<T>>): Promise<GeneResult<T>>;
@@ -0,0 +1,201 @@
1
+ /**
2
+ * What every part of the manager shares: the library handle, the session's identity, the scopes
3
+ * a request addresses and the catalogs built over them (gene-bank spec 11.1, 12.4, 16.6).
4
+ *
5
+ * ASCII ONLY - the whole `gene/` tree is in `glyphs.test.ts::inScope`.
6
+ *
7
+ * THE MANAGER IS THE ONE CONSUMER ALLOWED TO LOAD ANOTHER PROJECT'S SCOPE (11.1). An Agent's
8
+ * `GeneService` only ever loads user + its own project + team + its own task scope, so a filter
9
+ * bug cannot leak another project's genes into a prompt. Here a `GeneTarget` is resolved to an
10
+ * explicit scope list and a catalog is built over exactly that list; `allProjects` is the one
11
+ * target that reaches everything on disk, and it exists for the human-only "all projects" view.
12
+ *
13
+ * NO PATH CROSSES THIS FILE'S OUTPUT. A target names a scope by kind and key; the engine turns it
14
+ * into a directory (`paths.ts`), and nothing returned to a caller contains one.
15
+ */
16
+ import { isValidScope, isValidScopeKey, isValidGeneId, scopeId, } from '@aragon-agent/tui/model/gene/ids';
17
+ import { clampGeneConfig, DEFAULT_GENE_CONFIG, } from '@aragon-agent/tui/model/config/schema';
18
+ import { getSecrets } from '@aragon-agent/tui/model/logging/secret-registry';
19
+ import { readConfigFile } from '../config/store.js';
20
+ import { resolveProjectKey } from '../memory/paths.js';
21
+ import { GeneCatalog } from './catalog.js';
22
+ import { captureEnvFingerprint, makeGlobMatcher } from './env.js';
23
+ import { geneFail, geneOk, toGeneFailure } from './gene-errors.js';
24
+ import { getGeneLibrary, limitsFromConfig, } from './manager-library.js';
25
+ import { scopeKeyIsSafe } from './scope-guard.js';
26
+ /** The key of the team scope under `gene.teamPath` (the service uses the same default). */
27
+ export const TEAM_SCOPE_KEY = 'team';
28
+ const CONFIG_TTL_MS = 2000;
29
+ const ENV_TTL_MS = 60_000;
30
+ const MAX_CATALOGS = 6;
31
+ /** The catalogs built so far, keyed by their scope list; the oldest is dropped past six. */
32
+ export class CatalogPool {
33
+ lib;
34
+ now;
35
+ byKey = new Map();
36
+ constructor(lib, now) {
37
+ this.lib = lib;
38
+ this.now = now;
39
+ }
40
+ /** A catalog over exactly `scopes`, caught up with the disk. Never rejects. */
41
+ async acquire(scopes) {
42
+ const key = scopes.map(scopeId).sort().join('|');
43
+ let catalog = this.byKey.get(key);
44
+ if (catalog === undefined) {
45
+ catalog = new GeneCatalog({ reader: this.lib.store, now: this.now });
46
+ catalog.setScopes(scopes);
47
+ }
48
+ else {
49
+ this.byKey.delete(key);
50
+ }
51
+ this.byKey.set(key, catalog);
52
+ this.evict();
53
+ await catalog.catchUp();
54
+ return catalog;
55
+ }
56
+ evict() {
57
+ while (this.byKey.size > MAX_CATALOGS) {
58
+ const oldest = this.byKey.keys().next().value;
59
+ this.byKey.get(oldest)?.dispose();
60
+ this.byKey.delete(oldest);
61
+ }
62
+ }
63
+ dispose() {
64
+ for (const catalog of this.byKey.values())
65
+ catalog.dispose();
66
+ this.byKey.clear();
67
+ }
68
+ }
69
+ function persistedConfig() {
70
+ try {
71
+ return clampGeneConfig(readConfigFile().config?.gene);
72
+ }
73
+ catch {
74
+ return DEFAULT_GENE_CONFIG;
75
+ }
76
+ }
77
+ function cachedConfig(read, now) {
78
+ let held = null;
79
+ return () => {
80
+ const t = now();
81
+ if (held !== null && t >= held.at && t - held.at < CONFIG_TTL_MS)
82
+ return held.value;
83
+ held = { at: t, value: read() };
84
+ return held.value;
85
+ };
86
+ }
87
+ function identifyProject(cwd) {
88
+ try {
89
+ const identity = resolveProjectKey(cwd);
90
+ return isValidScopeKey('project', identity.key) ? identity : null;
91
+ }
92
+ catch {
93
+ return null;
94
+ }
95
+ }
96
+ /** Build the shared state of one manager. Never throws. */
97
+ export function createManagerCore(options) {
98
+ const now = options.now ?? Date.now;
99
+ const config = options.config ?? cachedConfig(persistedConfig, now);
100
+ const secrets = options.knownSecrets ?? getSecrets;
101
+ const teamPath = options.teamPath ?? config().teamPath;
102
+ const lib = getGeneLibrary({
103
+ ...(options.root === undefined ? {} : { root: options.root }),
104
+ teamPath,
105
+ ...(options.teamWritable ? { teamWritable: true } : {}),
106
+ kind: options.kind ?? 'tui',
107
+ now,
108
+ });
109
+ lib.tuning.limits = () => limitsFromConfig(config());
110
+ lib.tuning.knownSecrets = secrets;
111
+ const project = identifyProject(options.cwd);
112
+ let envHeld = null;
113
+ const env = () => {
114
+ if (options.env !== undefined)
115
+ return options.env();
116
+ const t = now();
117
+ if (envHeld === null || t < envHeld.at || t - envHeld.at > ENV_TTL_MS) {
118
+ envHeld = { at: t, value: captureEnvFingerprint(options.cwd) };
119
+ }
120
+ return envHeld.value;
121
+ };
122
+ const core = {
123
+ options,
124
+ lib,
125
+ pool: new CatalogPool(lib, now),
126
+ config,
127
+ now,
128
+ secrets,
129
+ project: () => project,
130
+ visibleScopes: () => visibleScopes(options, project, teamPath),
131
+ scopesOf: (target) => resolveScopes(core, target, teamPath),
132
+ env,
133
+ callerFor: (scopes, tools) => ({
134
+ role: 'main',
135
+ scopes,
136
+ tools: [...tools],
137
+ env: env(),
138
+ windowTokens: 0,
139
+ matchesGlob: makeGlobMatcher(options.cwd),
140
+ }),
141
+ };
142
+ return core;
143
+ }
144
+ function visibleScopes(options, project, teamPath) {
145
+ const scopes = [{ kind: 'user' }];
146
+ if (project !== null)
147
+ scopes.push({ kind: 'project', key: project.key });
148
+ if (teamPath.length > 0)
149
+ scopes.push({ kind: 'team', key: TEAM_SCOPE_KEY });
150
+ const session = options.sessionId;
151
+ if (isValidScopeKey('task', session))
152
+ scopes.push({ kind: 'task', key: session });
153
+ return scopes.filter((scope) => isValidScope(scope) && scopeKeyIsSafe(scope));
154
+ }
155
+ async function resolveScopes(core, target, teamPath) {
156
+ if (target.kind === 'visible')
157
+ return geneOk(core.visibleScopes());
158
+ if (target.kind === 'allProjects')
159
+ return geneOk(await core.lib.store.listScopes());
160
+ const scope = target.scope;
161
+ if (!isValidScope(scope) || !scopeKeyIsSafe(scope)) {
162
+ return geneFail('GENE_SCOPE_FORBIDDEN', 'That scope is not valid.', 'bad_scope');
163
+ }
164
+ if (scope.kind === 'team' && teamPath.length === 0) {
165
+ return geneFail('GENE_SCOPE_READONLY', 'No team directory is configured.', 'no_team');
166
+ }
167
+ return geneOk([scope]);
168
+ }
169
+ /**
170
+ * Locate a gene by id among the scopes `target` addresses: live first, then archived. The id is
171
+ * validated before any path is built from it.
172
+ */
173
+ export async function findGene(core, target, id) {
174
+ if (!isValidGeneId(id))
175
+ return geneFail('GENE_INVALID_ID', 'That gene id is not valid.');
176
+ const scopes = await core.scopesOf(target);
177
+ if (!scopes.ok)
178
+ return scopes;
179
+ for (const scope of scopes.value) {
180
+ const live = await core.lib.store.readHead(scope, id);
181
+ if (live !== null)
182
+ return geneOk({ scope, read: live, archived: false });
183
+ const kept = await core.lib.store.readArchivedHead(scope, id);
184
+ if (kept !== null)
185
+ return geneOk({ scope, read: kept, archived: true });
186
+ }
187
+ return geneFail('GENE_NOT_FOUND', 'No gene with that id was found.', 'missing');
188
+ }
189
+ /** The version number whose content a head serves: published, else the pending candidate. */
190
+ export function servedVersion(head) {
191
+ return head.currentVersion ?? head.candidateVersion ?? head.latestVersion;
192
+ }
193
+ /** Run a port method body so that nothing it throws escapes (I-24). */
194
+ export async function guarded(work) {
195
+ try {
196
+ return await work();
197
+ }
198
+ catch (error) {
199
+ return toGeneFailure(error);
200
+ }
201
+ }