@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,222 @@
1
+ /**
2
+ * The per-SCOPE write lock of the Gene Bank (gene-bank spec 7.1 steps 2 and 9, I-22, RV-5/RV-6).
3
+ *
4
+ * ASCII ONLY - the whole `gene/` tree is in `glyphs.test.ts::inScope`.
5
+ *
6
+ * TWO LAYERS, BECAUSE ONE CANNOT DO BOTH JOBS.
7
+ * 1. An in-process FIFO mutex per scope. The governance lock primitive treats a lock file whose
8
+ * `pid` equals ITS OWN pid as stale and takes it over (`isLockLive` returns false for
9
+ * `info.pid === deps.pid`), so two concurrent commits inside ONE process would both
10
+ * "acquire" the file lock. The mutex is what serialises the commits of this process.
11
+ * 2. A cross-process lock file `lock/<scopeId>.lock` (`{pid, startedAt, heartbeatAt}`, `wx`
12
+ * create) built on the governance `acquireLock` / `refreshLock` / `removeLock`. It only
13
+ * arbitrates between processes.
14
+ *
15
+ * STALE = HEARTBEAT EXPIRED **AND** HOLDER DEAD (spec 7.1), checked here and not left to the
16
+ * primitive, whose own rule is "expired OR dead". The two differ in the cases that matter:
17
+ * a live process that is merely slow must keep its lock, and a lock whose pid was recycled by an
18
+ * unrelated process must not be taken over before its heartbeat expires. The primitive is
19
+ * therefore handed `isPidAlive: () => true` and `staleMs: Infinity` - it can create the file and
20
+ * report contention, but it never takes a lock over by itself.
21
+ *
22
+ * TAKEOVER IS ATOMIC. Two waiters that both see a stale lock must not both win it: each tries to
23
+ * `rename` the stale file to a unique name, and only one rename can succeed (the others find no
24
+ * source). The winner deletes the renamed file; everyone then races the exclusive create again.
25
+ *
26
+ * AT MOST ONE SCOPE LOCK AT A TIME (I-22). An `AsyncLocalStorage` marker is set while a lock body
27
+ * runs; a nested `withLock` (any scope) throws instead of deadlocking. A commit that needs a
28
+ * second scope (dependency propagation, capacity eviction) does it AFTER releasing the first.
29
+ *
30
+ * ANY thrown error releases: the body runs in `try / finally`, the heartbeat is stopped and the
31
+ * file removed before the mutex is handed on.
32
+ */
33
+ import { AsyncLocalStorage } from 'node:async_hooks';
34
+ import { rename, unlink } from 'node:fs/promises';
35
+ import { dirname } from 'node:path';
36
+ import { randomBytes } from 'node:crypto';
37
+ import { scopeId } from '@aragon-agent/tui/model/gene/ids';
38
+ import { GENE_LIMITS } from '@aragon-agent/tui/model/gene/limits';
39
+ import { GeneStoreError } from './gene-errors.js';
40
+ import { acquireLock, defaultIsPidAlive, ensureDir, readLock, refreshLock, removeLock, retryOnWindowsContention, } from './fs.js';
41
+ import * as P from './paths.js';
42
+ const realSleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
43
+ /** Strict FIFO mutex with a bounded wait; `acquire` yields a release function or null. */
44
+ class TimedMutex {
45
+ locked = false;
46
+ waiters = [];
47
+ acquire(timeoutMs) {
48
+ if (!this.locked) {
49
+ this.locked = true;
50
+ return Promise.resolve(() => this.release());
51
+ }
52
+ return new Promise((resolve) => {
53
+ const timer = setTimeout(() => {
54
+ const index = this.waiters.findIndex((w) => w.timer === timer);
55
+ if (index >= 0)
56
+ this.waiters.splice(index, 1);
57
+ resolve(null);
58
+ }, Math.max(0, timeoutMs));
59
+ this.waiters.push({ grant: (release) => resolve(release), timer });
60
+ });
61
+ }
62
+ release() {
63
+ const next = this.waiters.shift();
64
+ if (next === undefined) {
65
+ this.locked = false;
66
+ return;
67
+ }
68
+ clearTimeout(next.timer);
69
+ next.grant(() => this.release());
70
+ }
71
+ }
72
+ /**
73
+ * Keyed by the lock FILE path and shared by every manager in the process: two managers built
74
+ * over the same library (the TUI's and a host's, say) share one pid, and the file primitive
75
+ * cannot tell them apart - only a process-wide mutex can.
76
+ */
77
+ const MUTEXES = new Map();
78
+ export class ScopeLockManager {
79
+ pathContext;
80
+ pid;
81
+ now;
82
+ isPidAlive;
83
+ sleep;
84
+ timeoutMs;
85
+ staleMs;
86
+ heartbeatMs;
87
+ pollMs;
88
+ observer;
89
+ context = new AsyncLocalStorage();
90
+ held = 0;
91
+ constructor(pathContext, options = {}) {
92
+ this.pathContext = pathContext;
93
+ this.pid = options.pid ?? process.pid;
94
+ this.now = options.now ?? Date.now;
95
+ this.isPidAlive = options.isPidAlive ?? defaultIsPidAlive;
96
+ this.sleep = options.sleep ?? realSleep;
97
+ this.timeoutMs = options.timeoutMs ?? GENE_LIMITS.lockTimeoutMs;
98
+ this.staleMs = options.staleMs ?? GENE_LIMITS.lockStaleMs;
99
+ this.heartbeatMs = options.heartbeatMs ?? Math.max(10, Math.floor(this.staleMs / 3));
100
+ this.pollMs = options.pollMs ?? 25;
101
+ this.observer = options.observer ?? {};
102
+ }
103
+ /** How many scope locks this manager holds right now (0 or 1 by construction). */
104
+ get heldCount() {
105
+ return this.held;
106
+ }
107
+ /** Run `body` while holding the write lock of `scope`. Throws `GeneStoreError` on timeout. */
108
+ async withLock(scope, body) {
109
+ const id = scopeId(scope);
110
+ const path = P.scopeLockFile(scope, this.pathContext);
111
+ if (path === null) {
112
+ throw new GeneStoreError('GENE_SCOPE_FORBIDDEN', 'That scope is not valid.', 'bad_scope');
113
+ }
114
+ if (this.context.getStore() !== undefined) {
115
+ const message = 'A commit may hold only one scope lock.';
116
+ throw new GeneStoreError('GENE_UNAVAILABLE', message, 'nested_lock');
117
+ }
118
+ const deadline = this.now() + this.timeoutMs;
119
+ const release = await this.takeMutex(path);
120
+ try {
121
+ await this.acquireFile(path, deadline);
122
+ }
123
+ catch (error) {
124
+ release();
125
+ throw error;
126
+ }
127
+ return this.runHeld(id, path, release, body);
128
+ }
129
+ async takeMutex(lockPath) {
130
+ let mutex = MUTEXES.get(lockPath);
131
+ if (mutex === undefined) {
132
+ mutex = new TimedMutex();
133
+ MUTEXES.set(lockPath, mutex);
134
+ }
135
+ const release = await mutex.acquire(this.timeoutMs);
136
+ if (release === null)
137
+ throw this.timeout();
138
+ return release;
139
+ }
140
+ timeout() {
141
+ return new GeneStoreError('GENE_LOCK_TIMEOUT', 'The gene scope is busy; try again.', 'timeout');
142
+ }
143
+ async runHeld(id, path, releaseMutex, body) {
144
+ this.held += 1;
145
+ this.observer.acquired?.(id);
146
+ // A beat already IN FLIGHT is awaited by nobody (`void this.heartbeat(...)`), and
147
+ // `clearInterval` only stops the beats that have not fired yet. A straggler could therefore
148
+ // write `lock/<id>.lock` after `removeLock` had deleted it: a phantom lock the next committer
149
+ // has to wait out, and on Windows a teardown that fails with ENOTEMPTY because the lock
150
+ // directory was refilled between readdir and rmdir (measured in scope-lock.test.ts,
151
+ // "refreshes the heartbeat while held"). So every beat is tracked and all of them are awaited
152
+ // before the file goes away - release must not race its own heartbeat. A Set rather than a
153
+ // single variable: a beat that is slow to reach the filesystem outlives the next one, and
154
+ // waiting only for the newest still lets the oldest write after the delete.
155
+ const inFlight = new Set();
156
+ const beat = setInterval(() => {
157
+ const pending = this.heartbeat(path);
158
+ inFlight.add(pending);
159
+ void pending.finally(() => inFlight.delete(pending));
160
+ }, this.heartbeatMs);
161
+ beat.unref();
162
+ try {
163
+ return await this.context.run({ scope: id }, body);
164
+ }
165
+ finally {
166
+ clearInterval(beat);
167
+ await Promise.all([...inFlight]);
168
+ await removeLock(path, this.lockDeps()).catch(() => undefined);
169
+ this.held -= 1;
170
+ this.observer.released?.(id);
171
+ releaseMutex();
172
+ }
173
+ }
174
+ async heartbeat(path) {
175
+ try {
176
+ await refreshLock(path, this.lockDeps());
177
+ }
178
+ catch {
179
+ /* a missed beat is survivable: the lock only goes stale after staleMs of silence */
180
+ }
181
+ }
182
+ /** Deps for the governance primitive: it may create the file and report contention only. */
183
+ lockDeps() {
184
+ return {
185
+ now: this.now,
186
+ pid: this.pid,
187
+ isPidAlive: () => true,
188
+ staleMs: Number.POSITIVE_INFINITY,
189
+ };
190
+ }
191
+ async acquireFile(path, deadline) {
192
+ await ensureDir(dirname(path));
193
+ for (;;) {
194
+ const info = await readLock(path);
195
+ if (info !== null && this.isStale(info))
196
+ await this.takeOverStale(path);
197
+ const result = await acquireLock(path, this.lockDeps());
198
+ if (result.ok)
199
+ return;
200
+ if (this.now() >= deadline)
201
+ throw this.timeout();
202
+ await this.sleep(this.pollMs);
203
+ }
204
+ }
205
+ /** Heartbeat expired AND holder dead (7.1). A lock with our own pid is never "stale" here. */
206
+ isStale(info) {
207
+ if (info.pid === this.pid)
208
+ return false;
209
+ const expired = this.now() - info.heartbeatAt >= this.staleMs;
210
+ return expired && !this.isPidAlive(info.pid);
211
+ }
212
+ async takeOverStale(path) {
213
+ const aside = `${path}.stale.${this.pid}.${randomBytes(4).toString('hex')}`;
214
+ try {
215
+ await retryOnWindowsContention(() => rename(path, aside));
216
+ }
217
+ catch {
218
+ return; // somebody else won the takeover, or the file is already gone
219
+ }
220
+ await unlink(aside).catch(() => undefined);
221
+ }
222
+ }
@@ -0,0 +1,63 @@
1
+ /**
2
+ * Checking and repairing one scope against its head files (gene-bank spec 7.1 crash table, 7.7).
3
+ *
4
+ * ASCII ONLY - the whole `gene/` tree is in `glyphs.test.ts::inScope`.
5
+ *
6
+ * THE HEAD FILES ARE THE TRUTH; everything else in a scope is derived or secondary. This module
7
+ * measures how far a scope has drifted from them - after a crash between steps 7 and 8, a
8
+ * hand-edited file, an interrupted archive move - and `repairScope` brings the derived parts back:
9
+ *
10
+ * - the index: a `put` line for a head the index lacks or holds a stale row of, a `del` line for
11
+ * a row whose head is gone (appended to the journal, so readers pick it up by catching up);
12
+ * - `counts.json`, recomputed from the heads;
13
+ * - version / evidence files left on the wrong side of an interrupted archive or restore;
14
+ * - an archived copy of a gene that is also live (live wins; the archived copy is the stale one).
15
+ *
16
+ * `verifyScope` only READS and is safe to run without the scope lock. `repairScope` WRITES and must
17
+ * run inside it (the service takes the lock); it never touches a head, a version's content or
18
+ * evidence text - orphan version files are REPORTED, not deleted, because deleting is the garbage
19
+ * collector's job and it works from the same report.
20
+ */
21
+ import type { GeneScope } from '@aragon-agent/tui/model/gene/types';
22
+ import type { ExtendedCounts, GeneStore } from './store.js';
23
+ import type { ScopeRowsView } from './store-rows.js';
24
+ export interface ScopeReport {
25
+ scope: GeneScope;
26
+ heads: number;
27
+ archived: number;
28
+ counts: {
29
+ onDisk: ExtendedCounts | null;
30
+ expected: ExtendedCounts;
31
+ matches: boolean;
32
+ };
33
+ /** Version files numbered above the head's `latestVersion`: left by a crash before step 7. */
34
+ orphanVersionFiles: Array<{
35
+ id: string;
36
+ n: number;
37
+ }>;
38
+ /** `versions/<id>/` directories whose gene has no head at all. */
39
+ orphanVersionDirs: string[];
40
+ /** A head points at a version file that is not there. */
41
+ missingVersions: Array<{
42
+ id: string;
43
+ n: number;
44
+ }>;
45
+ /** Genes that exist both live and archived. */
46
+ duplicateArchived: string[];
47
+ /** Version / evidence files on the wrong side of an interrupted move. */
48
+ strayFiles: string[];
49
+ index: {
50
+ missing: string[];
51
+ stale: string[];
52
+ extra: string[];
53
+ };
54
+ }
55
+ export interface RepairSummary {
56
+ indexLinesAppended: number;
57
+ countsRewritten: boolean;
58
+ movesCompleted: number;
59
+ duplicatesRemoved: number;
60
+ }
61
+ export declare function verifyScope(store: GeneStore, rows: ScopeRowsView, scope: GeneScope, now: number): Promise<ScopeReport>;
62
+ /** Repair what `verifyScope` found, inside the scope lock. Never rewrites a head or a version. */
63
+ export declare function repairScope(store: GeneStore, rows: ScopeRowsView, scope: GeneScope, now: number): Promise<RepairSummary>;
@@ -0,0 +1,123 @@
1
+ import { rowFromHead } from '@aragon-agent/tui/model/gene/row';
2
+ import { GENE_LIMITS } from '@aragon-agent/tui/model/gene/limits';
3
+ import { applyDelta, contribution, emptyExtendedCounts, rebuildCounts } from './commit-counts.js';
4
+ function countsFrom(heads, archivedBytes, now) {
5
+ let counts = emptyExtendedCounts(now);
6
+ const none = contribution(null, 'none');
7
+ for (const head of heads)
8
+ counts = applyDelta(counts, none, contribution(head, 'live'), 0, now);
9
+ return { ...counts, archivedBytes };
10
+ }
11
+ function sameCounts(a, b) {
12
+ if (a === null)
13
+ return false;
14
+ const types = ['knowledge', 'tool', 'skill'];
15
+ return types.every((t) => a.published[t] === b.published[t] &&
16
+ a.pinned[t] === b.pinned[t] &&
17
+ (a.candidatesByType?.[t] ?? 0) === (b.candidatesByType?.[t] ?? 0));
18
+ }
19
+ async function readAllHeads(store, scope) {
20
+ const ids = (await store.listHeadIds(scope)).slice(0, GENE_LIMITS.maxScanEntries);
21
+ const reads = [];
22
+ for (const id of ids) {
23
+ const read = await store.readHead(scope, id);
24
+ if (read !== null)
25
+ reads.push(read);
26
+ }
27
+ return reads;
28
+ }
29
+ async function findOrphanFiles(store, scope, reads) {
30
+ const orphans = [];
31
+ const missing = [];
32
+ for (const { head } of reads) {
33
+ const numbers = await store.listVersionNumbers(scope, head.id);
34
+ for (const n of numbers)
35
+ if (n > head.latestVersion)
36
+ orphans.push({ id: head.id, n });
37
+ for (const n of [head.currentVersion, head.candidateVersion]) {
38
+ if (n !== null && !numbers.includes(n))
39
+ missing.push({ id: head.id, n });
40
+ }
41
+ }
42
+ return { orphans, missing };
43
+ }
44
+ async function indexDrift(rows, scope, reads) {
45
+ const byId = new Map((await rows.indexOnly(scope)).map((row) => [row.id, row]));
46
+ const drift = { missing: [], stale: [], extra: [] };
47
+ for (const read of reads) {
48
+ const row = byId.get(read.head.id);
49
+ if (row === undefined)
50
+ drift.missing.push(read.head.id);
51
+ else if (row.rev !== read.rev || row.size !== read.size)
52
+ drift.stale.push(read.head.id);
53
+ byId.delete(read.head.id);
54
+ }
55
+ drift.extra = [...byId.keys()].sort();
56
+ return drift;
57
+ }
58
+ export async function verifyScope(store, rows, scope, now) {
59
+ const reads = await readAllHeads(store, scope);
60
+ const archivedIds = await store.listArchivedIds(scope);
61
+ const live = new Set(reads.map((r) => r.head.id));
62
+ let archivedBytes = 0;
63
+ for (const id of archivedIds)
64
+ archivedBytes += await store.archivedBytesOf(scope, id);
65
+ const expected = countsFrom(reads.map((r) => r.head), archivedBytes, now);
66
+ const onDisk = await store.readCounts(scope);
67
+ const files = await findOrphanFiles(store, scope, reads);
68
+ const known = new Set([...live, ...archivedIds]);
69
+ const owners = await store.listVersionOwners(scope);
70
+ const stray = [];
71
+ for (const id of live)
72
+ if (await store.hasStraySides(scope, id, false))
73
+ stray.push(id);
74
+ for (const id of archivedIds) {
75
+ if (!live.has(id) && (await store.hasStraySides(scope, id, true)))
76
+ stray.push(id);
77
+ }
78
+ return {
79
+ scope,
80
+ heads: reads.length,
81
+ archived: archivedIds.length,
82
+ counts: { onDisk, expected, matches: sameCounts(onDisk, expected) },
83
+ orphanVersionFiles: files.orphans,
84
+ orphanVersionDirs: owners.filter((id) => !known.has(id)),
85
+ missingVersions: files.missing,
86
+ duplicateArchived: archivedIds.filter((id) => live.has(id)),
87
+ strayFiles: stray.sort(),
88
+ index: await indexDrift(rows, scope, reads),
89
+ };
90
+ }
91
+ /** Repair what `verifyScope` found, inside the scope lock. Never rewrites a head or a version. */
92
+ export async function repairScope(store, rows, scope, now) {
93
+ const summary = {
94
+ indexLinesAppended: 0,
95
+ countsRewritten: false,
96
+ movesCompleted: 0,
97
+ duplicatesRemoved: 0,
98
+ };
99
+ const report = await verifyScope(store, rows, scope, now);
100
+ for (const id of report.duplicateArchived) {
101
+ await store.removeArchivedHead(scope, id);
102
+ summary.duplicatesRemoved += 1;
103
+ }
104
+ for (const id of report.strayFiles) {
105
+ const archived = (await store.readHead(scope, id)) === null;
106
+ await store.completeMoves(scope, id, archived);
107
+ summary.movesCompleted += 1;
108
+ }
109
+ for (const id of [...report.index.missing, ...report.index.stale]) {
110
+ const read = await store.readHead(scope, id);
111
+ if (read === null)
112
+ continue;
113
+ await store.appendJournal(scope, { op: 'put', row: rowFromHead(read.head, read) });
114
+ summary.indexLinesAppended += 1;
115
+ }
116
+ for (const id of report.index.extra) {
117
+ await store.appendJournal(scope, { op: 'del', id });
118
+ summary.indexLinesAppended += 1;
119
+ }
120
+ await store.writeCounts(scope, await rebuildCounts(store, scope, now));
121
+ summary.countsRewritten = !report.counts.matches;
122
+ return summary;
123
+ }
@@ -0,0 +1,43 @@
1
+ /**
2
+ * Secret screening and redaction for the Gene Bank (gene-bank spec 11.5, I-16, D-32, RV-18).
3
+ *
4
+ * ASCII ONLY - the whole `gene/` tree is in `glyphs.test.ts::inScope`.
5
+ *
6
+ * BUILT ON `memory/secrets.ts::looksLikeSecret`, whose real signature is
7
+ * `(text, knownSecrets?) => SecretVerdict { hit, kind? }` - NOT a boolean. The configured
8
+ * provider API keys MUST be passed as `knownSecrets` (same source as the log redactor): that
9
+ * is the strongest single signal there is, and omitting it is how a key the user pasted once
10
+ * ends up in a file that every future prompt reads (RV-18).
11
+ *
12
+ * TWO USES, DELIBERATELY DIFFERENT (spec 11.5):
13
+ * - `screenSecrets` REFUSES. For writable gene fields: a hit is `GENE_SECRET_DETECTED`, and
14
+ * there is no "save anyway" (unlike agent-memory) because a gene is read automatically and
15
+ * propagates across projects, so the bar is higher.
16
+ * - `redactSecrets` SCRUBS. For evidence and the learning ledger, where the original text is
17
+ * kept for the human but the secret part must not be: `[redacted:<kind>]`.
18
+ *
19
+ * A MATCH NEVER ECHOES THE MATCHED TEXT: `kind` is the whole explanation.
20
+ *
21
+ * EXTRA PATTERNS beyond the memory module: `Authorization:` / `Bearer` headers, connection
22
+ * strings with an inline password, and a conservative long-token heuristic. The heuristic
23
+ * exempts exactly-40 and exactly-64 hex runs because those are git SHAs and sha256 digests,
24
+ * which a coding library legitimately quotes ("fixed in 3f2a..."); any other long hex or
25
+ * base64-looking run with mixed character classes is treated as a credential.
26
+ */
27
+ import { type SecretVerdict } from '../memory/secrets.js';
28
+ export type { SecretVerdict };
29
+ export interface GeneSecretVerdict extends SecretVerdict {
30
+ /** All kinds found, for the refusal message; never the text itself. */
31
+ kinds: string[];
32
+ }
33
+ /** Screen text for a writable field. `knownSecrets` = the user's configured provider keys. */
34
+ export declare function screenSecrets(text: string, knownSecrets?: readonly string[]): GeneSecretVerdict;
35
+ export declare function geneLooksLikeSecret(text: string, knownSecrets?: readonly string[]): boolean;
36
+ export interface Redaction {
37
+ text: string;
38
+ /** True when anything was replaced. */
39
+ redacted: boolean;
40
+ kinds: string[];
41
+ }
42
+ /** Replace secrets (and e-mail / phone numbers) with stable markers. Never throws. */
43
+ export declare function redactSecrets(text: string, knownSecrets?: readonly string[]): Redaction;
@@ -0,0 +1,161 @@
1
+ /**
2
+ * Secret screening and redaction for the Gene Bank (gene-bank spec 11.5, I-16, D-32, RV-18).
3
+ *
4
+ * ASCII ONLY - the whole `gene/` tree is in `glyphs.test.ts::inScope`.
5
+ *
6
+ * BUILT ON `memory/secrets.ts::looksLikeSecret`, whose real signature is
7
+ * `(text, knownSecrets?) => SecretVerdict { hit, kind? }` - NOT a boolean. The configured
8
+ * provider API keys MUST be passed as `knownSecrets` (same source as the log redactor): that
9
+ * is the strongest single signal there is, and omitting it is how a key the user pasted once
10
+ * ends up in a file that every future prompt reads (RV-18).
11
+ *
12
+ * TWO USES, DELIBERATELY DIFFERENT (spec 11.5):
13
+ * - `screenSecrets` REFUSES. For writable gene fields: a hit is `GENE_SECRET_DETECTED`, and
14
+ * there is no "save anyway" (unlike agent-memory) because a gene is read automatically and
15
+ * propagates across projects, so the bar is higher.
16
+ * - `redactSecrets` SCRUBS. For evidence and the learning ledger, where the original text is
17
+ * kept for the human but the secret part must not be: `[redacted:<kind>]`.
18
+ *
19
+ * A MATCH NEVER ECHOES THE MATCHED TEXT: `kind` is the whole explanation.
20
+ *
21
+ * EXTRA PATTERNS beyond the memory module: `Authorization:` / `Bearer` headers, connection
22
+ * strings with an inline password, and a conservative long-token heuristic. The heuristic
23
+ * exempts exactly-40 and exactly-64 hex runs because those are git SHAs and sha256 digests,
24
+ * which a coding library legitimately quotes ("fixed in 3f2a..."); any other long hex or
25
+ * base64-looking run with mixed character classes is treated as a credential.
26
+ */
27
+ import { looksLikeSecret } from '../memory/secrets.js';
28
+ /** Global regexes (used with replace); each is anchored on shapes with a low false-positive rate. */
29
+ const EXTRA_PATTERNS = [
30
+ { kind: 'auth-header', pattern: /\bAuthorization[ \t]*:[ \t]*(?:Bearer|Basic|Token)[ \t]+[A-Za-z0-9._~+/=-]{8,}/gi },
31
+ { kind: 'bearer', pattern: /\bBearer[ \t]+[A-Za-z0-9._~+/=-]{20,}/g },
32
+ { kind: 'conn-string', pattern: /\b[a-z][a-z0-9+.-]{1,20}:\/\/[^\s:@/]{1,64}:[^\s@/]{3,}@[^\s/]+/gi },
33
+ { kind: 'github-pat', pattern: /\bgithub_pat_[A-Za-z0-9_]{22,}/g },
34
+ { kind: 'private-key', pattern: /-----BEGIN [A-Z ]*PRIVATE KEY(?: BLOCK)?-----[\s\S]*?(?:-----END [A-Z ]*PRIVATE KEY(?: BLOCK)?-----|$)/g },
35
+ ];
36
+ const LONG_TOKEN = /\b[A-Za-z0-9+/_=-]{40,}\b/g;
37
+ const EMAIL = /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g;
38
+ /** International-looking phone numbers; requires a leading + or 10+ digits to stay precise. */
39
+ const PHONE = /(?<![\w.])(?:\+\d[\d\s().-]{8,16}\d|\d{3}[ .-]\d{4}[ .-]\d{4})(?![\w.])/g;
40
+ function isHashLike(token) {
41
+ return /^[0-9a-f]{40}$/i.test(token) || /^[0-9a-f]{64}$/i.test(token);
42
+ }
43
+ function charClasses(token) {
44
+ let n = 0;
45
+ if (/[a-z]/.test(token))
46
+ n += 1;
47
+ if (/[A-Z]/.test(token))
48
+ n += 1;
49
+ if (/[0-9]/.test(token))
50
+ n += 1;
51
+ return n;
52
+ }
53
+ function shannonBitsPerChar(token) {
54
+ const counts = new Map();
55
+ for (const ch of token)
56
+ counts.set(ch, (counts.get(ch) ?? 0) + 1);
57
+ let bits = 0;
58
+ for (const c of counts.values()) {
59
+ const p = c / token.length;
60
+ bits -= p * Math.log2(p);
61
+ }
62
+ return bits;
63
+ }
64
+ /** Share of the token made of lowercase runs of 3+ letters: words, not random characters. */
65
+ function wordishRatio(token) {
66
+ let letters = 0;
67
+ for (const m of token.matchAll(/[a-z]{3,}/g))
68
+ letters += m[0].length;
69
+ return letters / token.length;
70
+ }
71
+ /** A path, URL fragment or slug is not a token: those contain separators between WORDS. */
72
+ function looksLikeCredential(token) {
73
+ if (isHashLike(token))
74
+ return false;
75
+ if (/^[0-9a-f]+$/i.test(token))
76
+ return true; // long hex that is not a standard digest length
77
+ if (/^[a-z]+(?:[-_][a-z]+){3,}$/.test(token))
78
+ return false; // kebab / snake prose
79
+ if (wordishRatio(token) >= 0.6)
80
+ return false; // file paths and long slugs read as words
81
+ return charClasses(token) >= 2 && shannonBitsPerChar(token) >= 3.6;
82
+ }
83
+ /** Screen text for a writable field. `knownSecrets` = the user's configured provider keys. */
84
+ export function screenSecrets(text, knownSecrets = []) {
85
+ const kinds = [];
86
+ const base = looksLikeSecret(text, knownSecrets);
87
+ if (base.hit && base.kind)
88
+ kinds.push(base.kind);
89
+ for (const { kind, pattern } of EXTRA_PATTERNS) {
90
+ pattern.lastIndex = 0;
91
+ if (pattern.test(text))
92
+ kinds.push(kind);
93
+ }
94
+ for (const m of text.matchAll(LONG_TOKEN)) {
95
+ if (looksLikeCredential(m[0])) {
96
+ kinds.push('long-token');
97
+ break;
98
+ }
99
+ }
100
+ const unique = [...new Set(kinds)];
101
+ return unique.length > 0 ? { hit: true, kind: unique[0], kinds: unique } : { hit: false, kinds: [] };
102
+ }
103
+ export function geneLooksLikeSecret(text, knownSecrets = []) {
104
+ return screenSecrets(text, knownSecrets).hit;
105
+ }
106
+ /** Replace secrets (and e-mail / phone numbers) with stable markers. Never throws. */
107
+ export function redactSecrets(text, knownSecrets = []) {
108
+ let out = text;
109
+ const kinds = [];
110
+ const mark = (kind) => {
111
+ kinds.push(kind);
112
+ return `[redacted:${kind}]`;
113
+ };
114
+ for (const secret of knownSecrets) {
115
+ if (secret.length >= 8 && out.includes(secret))
116
+ out = out.split(secret).join(mark('configured'));
117
+ }
118
+ for (const { kind, pattern } of EXTRA_PATTERNS) {
119
+ pattern.lastIndex = 0;
120
+ out = out.replace(pattern, () => mark(kind));
121
+ }
122
+ out = out.replace(LONG_TOKEN, (token) => (looksLikeCredential(token) ? mark('long-token') : token));
123
+ // The memory module's shapes (AWS, GitHub, Slack, sk-, JWT, assignments) by re-screening:
124
+ // replace remaining hits shape by shape.
125
+ out = redactBaseShapes(out, kinds);
126
+ out = out.replace(EMAIL, () => {
127
+ kinds.push('email');
128
+ return '[email]';
129
+ });
130
+ out = out.replace(PHONE, () => {
131
+ kinds.push('phone');
132
+ return '[phone]';
133
+ });
134
+ return { text: out, redacted: out !== text, kinds: [...new Set(kinds)] };
135
+ }
136
+ const BASE_REPLACERS = [
137
+ { kind: 'aws-access-key', pattern: /\bAKIA[0-9A-Z]{16}\b/g },
138
+ { kind: 'github-token', pattern: /\bgh[pousr]_[A-Za-z0-9]{36,}\b/g },
139
+ { kind: 'slack-token', pattern: /\bxox[baprs]-[A-Za-z0-9-]{10,}/g },
140
+ { kind: 'api-key-like', pattern: /\bsk-[A-Za-z0-9_-]{20,}/g },
141
+ { kind: 'api-key-like', pattern: /\bAIza[0-9A-Za-z_-]{35}\b/g },
142
+ { kind: 'jwt', pattern: /\beyJ[A-Za-z0-9_-]{5,}\.eyJ[A-Za-z0-9_-]{5,}\.[A-Za-z0-9_-]{5,}/g },
143
+ ];
144
+ const ASSIGNMENT_VALUE = /(\b(?:password|passwd|secret|token|api[_-]?key)\b[ \t]*[:=][ \t]*)(["']?)([^\s"']{8,})\2/gi;
145
+ function redactBaseShapes(text, kinds) {
146
+ let out = text;
147
+ for (const { kind, pattern } of BASE_REPLACERS) {
148
+ pattern.lastIndex = 0;
149
+ out = out.replace(pattern, () => {
150
+ kinds.push(kind);
151
+ return `[redacted:${kind}]`;
152
+ });
153
+ }
154
+ out = out.replace(ASSIGNMENT_VALUE, (whole, head, quote, value) => {
155
+ if (!looksLikeSecret(`password=${value}`).hit)
156
+ return whole;
157
+ kinds.push('assignment');
158
+ return `${head}${quote}[redacted:assignment]${quote}`;
159
+ });
160
+ return out;
161
+ }
@@ -0,0 +1,43 @@
1
+ /**
2
+ * Pieces of `GeneService` that hold no I/O: the holdout draw, task-text tokenising and the state of
3
+ * the auto-context zone (gene-bank spec 8.5, 9.2, 9.3, 13).
4
+ *
5
+ * ASCII ONLY - the whole `gene/` tree is in `glyphs.test.ts::inScope`.
6
+ *
7
+ * Split from `service.ts` for size, and because none of it needs the library: the hysteresis memory
8
+ * is just "the last text we gave each role", the holdout draw is a hash, and tokenising is a pure
9
+ * function of the task text.
10
+ */
11
+ import type { ContextSnapshot } from '@aragon-agent/tui/model/gene/context';
12
+ import type { GeneRole, GeneSessionView } from '@aragon-agent/tui/model/gene/types';
13
+ /** 0..99, the same for the same run id on every machine and every restart. */
14
+ export declare function holdoutBucket(runId: string): number;
15
+ /** `hash(runId) % 100 < holdoutPercent`: the run deliberately does not use the library. */
16
+ export declare function isHoldoutRun(runId: string, percent: number): boolean;
17
+ /**
18
+ * Terms for the planner. UNSTEMMED words (`raws`): the planner joins them and the searcher stems
19
+ * them once, and stemming a stem is not guaranteed to be a no-op. CJK has no raw form (the
20
+ * tokenizer treats it as a separator), so its bigrams are appended from `tokenizeQuery`.
21
+ */
22
+ export declare function queryTermsOf(text: string): string[];
23
+ export type ContextView = GeneSessionView['context'];
24
+ export declare function offContext(role: GeneRole, budgetItems?: number, budgetTokens?: number): ContextView;
25
+ /**
26
+ * What the zone last said, per role. The system prompt is rebuilt every user turn, so the text
27
+ * lives HERE (not in the controller) and `renderContextBlock` just hands it back; hysteresis needs
28
+ * the previous text to keep it byte for byte.
29
+ */
30
+ export declare class ContextState {
31
+ private readonly snapshots;
32
+ private view;
33
+ /** The visible gene set changed after the last plan; applied at the NEXT user turn (9.3). */
34
+ dirty: boolean;
35
+ constructor(role: GeneRole);
36
+ previous(role: GeneRole): ContextSnapshot | undefined;
37
+ remember(role: GeneRole, snapshot: ContextSnapshot): void;
38
+ /** Forget the hysteresis memory of one role, or of all of them. */
39
+ reset(role?: GeneRole): void;
40
+ textOf(role: GeneRole): string;
41
+ setView(view: ContextView): void;
42
+ getView(): ContextView;
43
+ }