@aragon-agent/cli 0.6.55 → 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 (319) hide show
  1. package/CHANGELOG.md +2912 -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 +103 -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 +197 -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 +202 -0
  116. package/dist/gene/curator/tools-write.d.ts +26 -0
  117. package/dist/gene/curator/tools-write.js +394 -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 +36 -0
  123. package/dist/gene/curator/validate/evidence-tokens.js +139 -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 +25 -0
  127. package/dist/gene/curator/validate/knowledge.js +216 -0
  128. package/dist/gene/curator/validate/live-check.d.ts +14 -0
  129. package/dist/gene/curator/validate/live-check.js +144 -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 +161 -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 +63 -0
  185. package/dist/gene/learn/learn-call.js +157 -0
  186. package/dist/gene/learn/learn-prompt.d.ts +51 -0
  187. package/dist/gene/learn/learn-prompt.js +245 -0
  188. package/dist/gene/learn/learner.d.ts +181 -0
  189. package/dist/gene/learn/learner.js +426 -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 +211 -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 +81 -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,622 @@
1
+ /**
2
+ * The Gene Bank's file layer (gene-bank spec 6, 6.8, 7.1, 7.7).
3
+ *
4
+ * ASCII ONLY - the whole `gene/` tree is in `glyphs.test.ts::inScope`.
5
+ *
6
+ * ONE CLASS, TWO FACES. The READ methods implement `GeneStoreReader` (the interface every
7
+ * reader - catalog, usage folder, manager - is given) and are TOLERANT: a missing, torn or
8
+ * hand-edited file reads as `null` / `[]`, never as an exception. The WRITE methods are STRICT
9
+ * (fixed key order, two-space indent, trailing newline, temp + rename) and are meant to be
10
+ * called by `GeneVersionService` and nobody else (I-4, I-10): readers hold the reader interface,
11
+ * so "a reader wrote a gene file" does not compile.
12
+ *
13
+ * EVERY PATH COMES FROM `paths.ts`. This file never joins a gene id, a scope key or a ref into
14
+ * a path itself; the builders validate and bound them. Every deletion goes through
15
+ * `removeInside(scopeRoot, ...)`, so a bad identifier cannot aim `rm` outside the scope.
16
+ *
17
+ * ARCHIVE AND TRASH LIVE INSIDE THE SCOPE (6.8 rule 2) so a move is a same-volume `rename`.
18
+ * An archive / trash move is several renames; the ORDER makes every crash point recoverable:
19
+ * archive : write the archived head, delete the live head (COMMIT POINT), then move the
20
+ * version / evidence files. A crash after the commit point leaves versions in their
21
+ * old place; `readVersion` / `listEvidence` look in both places, and
22
+ * `verifyScope` reports (and `completeMoves` finishes) the stragglers.
23
+ * restore : the mirror image (live head first, then delete the archive copy, then move back).
24
+ * trash : head first (it IS the commit point), then the sides.
25
+ *
26
+ * THE TEAM SCOPE IS READ-ONLY (6.8 rule 3): any write to it is `GENE_SCOPE_READONLY`, here and
27
+ * again in the service. `teamWritable` exists only for the one human-approved promotion path.
28
+ *
29
+ * `hooks.beforeWrite` is the fault-injection seam of the tests: it runs before every durable
30
+ * write, so a test can fail "between step 6 and step 7" without mocking the filesystem.
31
+ */
32
+ import { dirname, join } from 'node:path';
33
+ import { promises as nodeFs } from 'node:fs';
34
+ import { isValidScopeKey } from '@aragon-agent/tui/model/gene/ids';
35
+ import { canonicalJson } from '@aragon-agent/tui/model/gene/validate';
36
+ import { VEC_ALGO } from '@aragon-agent/tui/model/gene/hashvec';
37
+ import { GeneStoreError } from './gene-errors.js';
38
+ import * as P from './paths.js';
39
+ import { isReservedDeviceName, scopeKeyIsSafe } from './scope-guard.js';
40
+ import { appendJsonl, listDir, moveInside, pathExists, readJson, readJsonlFrom, readText, removeInside, revOf, statOrNull, writeJsonStrict, } from './fs.js';
41
+ const DAY_MS = 86_400_000;
42
+ const GENE_TYPES_LIST = ['knowledge', 'tool', 'skill'];
43
+ /** The two per-gene directories that follow a head between live, archive and trash. */
44
+ const GENE_SIDES = ['versions', 'evidence'];
45
+ // ---------------------------------------------------------------------------
46
+ // Fixed key order (writes are strict, reads are tolerant and keep unknown keys)
47
+ // ---------------------------------------------------------------------------
48
+ const HEAD_ORDER = [
49
+ 'schema', 'id', 'type', 'scope', 'status', 'health', 'healthReason', 'class', 'trust',
50
+ 'currentVersion', 'candidateVersion', 'latestVersion', 'brief', 'tags', 'pinned', 'pinReason',
51
+ 'probation', 'needsHuman', 'fingerprint', 'createdAt', 'updatedAt', 'humanTouchedAt',
52
+ 'archivedAt', 'revokedAt', 'deps', 'indexData',
53
+ ];
54
+ const VERSION_ORDER = [
55
+ 'schema', 'id', 'n', 'state', 'createdAt', 'author', 'reason', 'proposalId', 'basis',
56
+ 'contentHash', 'content', 'diff', 'validation',
57
+ ];
58
+ const CONTENT_ORDER = [
59
+ 'name', 'purpose', 'trigger', 'tags', 'localeHints', 'body', 'applicability', 'roles', 'deps',
60
+ 'source', 'evidence', 'payload',
61
+ ];
62
+ const EVIDENCE_ORDER = [
63
+ 'schema', 'ref', 'geneId', 'capturedAt', 'kind', 'trust', 'source', 'text', 'redacted',
64
+ ];
65
+ /** Known keys first in the documented order, then any unknown key (kept, sorted). */
66
+ function orderKeys(value, order) {
67
+ const record = value;
68
+ const out = {};
69
+ for (const key of order)
70
+ if (record[key] !== undefined)
71
+ out[key] = record[key];
72
+ for (const key of Object.keys(record).sort()) {
73
+ if (!(key in out) && record[key] !== undefined)
74
+ out[key] = record[key];
75
+ }
76
+ return out;
77
+ }
78
+ function orderHead(head) {
79
+ return orderKeys(head, HEAD_ORDER);
80
+ }
81
+ function orderVersion(version) {
82
+ const ordered = orderKeys(version, VERSION_ORDER);
83
+ ordered.content = orderKeys(version.content, CONTENT_ORDER);
84
+ return ordered;
85
+ }
86
+ // ---------------------------------------------------------------------------
87
+ // Tolerant parsing
88
+ // ---------------------------------------------------------------------------
89
+ function isObject(value) {
90
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
91
+ }
92
+ function isHeadShape(value, id) {
93
+ if (!isObject(value) || value.schema !== 1 || value.id !== id)
94
+ return false;
95
+ const identified = typeof value.type === 'string' && isObject(value.scope) && typeof value.status === 'string';
96
+ return identified && isObject(value.brief) && typeof value.latestVersion === 'number';
97
+ }
98
+ /** Minimal structural check; missing arrays default to empty so a hand-edited head still reads. */
99
+ function parseHead(text, id) {
100
+ try {
101
+ const value = JSON.parse(text);
102
+ if (!isHeadShape(value, id))
103
+ return null;
104
+ const head = value;
105
+ if (!Array.isArray(head.tags))
106
+ head.tags = [];
107
+ if (!Array.isArray(head.deps))
108
+ head.deps = [];
109
+ return head;
110
+ }
111
+ catch {
112
+ return null;
113
+ }
114
+ }
115
+ function parseVersion(text, id, n) {
116
+ try {
117
+ const value = JSON.parse(text);
118
+ if (!isObject(value) || value.schema !== 1 || value.id !== id || value.n !== n)
119
+ return null;
120
+ if (typeof value.state !== 'string' || !isObject(value.content))
121
+ return null;
122
+ return value;
123
+ }
124
+ catch {
125
+ return null;
126
+ }
127
+ }
128
+ function isCounts(value) {
129
+ if (!isObject(value) || value.schema !== 1)
130
+ return false;
131
+ const published = value.published;
132
+ const pinned = value.pinned;
133
+ const numeric = (r) => isObject(r) && GENE_TYPES_LIST.every((t) => typeof r[t] === 'number');
134
+ return numeric(published) && numeric(pinned) && typeof value.archivedBytes === 'number';
135
+ }
136
+ function writeError(code, detail) {
137
+ const message = code === 'GENE_SCOPE_READONLY'
138
+ ? 'The team scope is read-only.'
139
+ : 'That scope or identifier is not valid.';
140
+ return new GeneStoreError(code, message, detail);
141
+ }
142
+ // ---------------------------------------------------------------------------
143
+ // The store
144
+ // ---------------------------------------------------------------------------
145
+ export class GeneStore {
146
+ ctx;
147
+ hooks;
148
+ teamWritable;
149
+ constructor(options) {
150
+ this.ctx = options.ctx;
151
+ this.hooks = options.hooks ?? {};
152
+ this.teamWritable = options.teamWritable ?? false;
153
+ }
154
+ // ---- helpers ----------------------------------------------------------
155
+ /** The scope's own directory, or a typed refusal. Also the bound for every deletion. */
156
+ scopeRoot(scope) {
157
+ const dir = scopeKeyIsSafe(scope) ? P.scopeDir(scope, this.ctx) : null;
158
+ if (dir === null) {
159
+ const noTeamPath = scope.kind === 'team' && this.ctx.teamPath.length === 0;
160
+ throw writeError(noTeamPath ? 'GENE_SCOPE_READONLY' : 'GENE_SCOPE_FORBIDDEN', 'bad_scope');
161
+ }
162
+ return dir;
163
+ }
164
+ isWritable(scope) {
165
+ return !P.isReadOnlyScope(scope) || this.teamWritable;
166
+ }
167
+ assertWritable(scope) {
168
+ const root = this.scopeRoot(scope);
169
+ if (!this.isWritable(scope))
170
+ throw writeError('GENE_SCOPE_READONLY', 'team');
171
+ return root;
172
+ }
173
+ path(built) {
174
+ if (built === null)
175
+ throw writeError('GENE_SCOPE_FORBIDDEN', 'bad_identifier');
176
+ return built;
177
+ }
178
+ async guard(kind, path) {
179
+ await this.hooks.beforeWrite?.(kind, path);
180
+ }
181
+ // ---- reads (tolerant) ---------------------------------------------------
182
+ async readHead(scope, id) {
183
+ const path = P.headFile(scope, id, this.ctx);
184
+ return path === null ? null : this.readHeadAt(path, id);
185
+ }
186
+ async readArchivedHead(scope, id) {
187
+ const path = P.archiveHeadFile(scope, id, this.ctx);
188
+ return path === null ? null : this.readHeadAt(path, id);
189
+ }
190
+ async readHeadAt(path, id) {
191
+ const text = await readText(path);
192
+ if (text === null)
193
+ return null;
194
+ const head = parseHead(text, id);
195
+ if (head === null)
196
+ return null;
197
+ const stamp = await statOrNull(path);
198
+ return { head, rev: revOf(text), mtimeMs: stamp?.mtimeMs ?? 0, size: Buffer.byteLength(text) };
199
+ }
200
+ /** Ids whose head file is under `dir` (`<aa>/<id>.json`). Names only; nothing is opened. */
201
+ async idsUnder(dir) {
202
+ if (dir === null)
203
+ return [];
204
+ const ids = [];
205
+ for (const shard of await listDir(dir)) {
206
+ if (!/^[0-9a-z_]{2}$/.test(shard))
207
+ continue;
208
+ for (const name of await listDir(join(dir, shard))) {
209
+ const id = name.endsWith('.json') ? name.slice(0, -5) : '';
210
+ if (/^g[kts]_[0-9a-z]{10}$/.test(id))
211
+ ids.push(id);
212
+ }
213
+ }
214
+ return ids.sort();
215
+ }
216
+ listHeadIds(scope) {
217
+ return this.idsUnder(P.headsDir(scope, this.ctx));
218
+ }
219
+ listArchivedIds(scope) {
220
+ return this.idsUnder(P.archiveDir(scope, this.ctx));
221
+ }
222
+ /** Where version `n` lives right now: the live directory, else the archive side. */
223
+ async versionPathFor(scope, id, n) {
224
+ const live = P.versionFile(scope, id, n, this.ctx);
225
+ if (live === null)
226
+ return null;
227
+ if (await pathExists(live))
228
+ return live;
229
+ const side = P.archiveSideDir(scope, id, 'versions', this.ctx);
230
+ const archived = side === null ? null : join(side, `${n}.json`);
231
+ return archived !== null && (await pathExists(archived)) ? archived : live;
232
+ }
233
+ async readVersion(scope, id, n) {
234
+ const path = await this.versionPathFor(scope, id, n);
235
+ if (path === null)
236
+ return null;
237
+ const text = await readText(path);
238
+ return text === null ? null : parseVersion(text, id, n);
239
+ }
240
+ async listVersionNumbers(scope, id) {
241
+ const numbers = new Set();
242
+ const dirs = [
243
+ P.versionsDir(scope, id, this.ctx),
244
+ P.archiveSideDir(scope, id, 'versions', this.ctx),
245
+ ];
246
+ for (const dir of dirs) {
247
+ if (dir === null)
248
+ continue;
249
+ for (const name of await listDir(dir)) {
250
+ const match = /^(\d{1,6})\.json$/.exec(name);
251
+ if (match)
252
+ numbers.add(Number(match[1]));
253
+ }
254
+ }
255
+ return [...numbers].filter((n) => n >= 1).sort((a, b) => a - b);
256
+ }
257
+ async evidencePath(scope, id, ref) {
258
+ const live = P.evidenceFile(scope, id, ref, this.ctx);
259
+ if (live === null)
260
+ return null;
261
+ if (await pathExists(live))
262
+ return live;
263
+ const side = P.archiveSideDir(scope, id, 'evidence', this.ctx);
264
+ return side === null ? live : join(side, `${ref}.json`);
265
+ }
266
+ async readEvidence(scope, id, ref) {
267
+ const path = await this.evidencePath(scope, id, ref);
268
+ if (path === null)
269
+ return null;
270
+ const value = await readJson(path);
271
+ const valid = value !== null && value.ref === ref && value.geneId === id && typeof value.text === 'string';
272
+ return valid ? value : null;
273
+ }
274
+ async listEvidence(scope, id) {
275
+ const refs = new Set();
276
+ const dirs = [
277
+ P.evidenceDir(scope, id, this.ctx),
278
+ P.archiveSideDir(scope, id, 'evidence', this.ctx),
279
+ ];
280
+ for (const dir of dirs) {
281
+ if (dir === null)
282
+ continue;
283
+ for (const name of await listDir(dir)) {
284
+ if (/^ev_[0-9a-z]{8}\.json$/.test(name))
285
+ refs.add(name.slice(0, -5));
286
+ }
287
+ }
288
+ const found = [];
289
+ for (const ref of [...refs].sort()) {
290
+ const evidence = await this.readEvidence(scope, id, ref);
291
+ if (evidence !== null)
292
+ found.push(evidence);
293
+ }
294
+ return found;
295
+ }
296
+ async readStatsShard(scope, shard) {
297
+ const path = P.statsFile(scope, shard, this.ctx);
298
+ const value = path === null ? null : await readJson(path);
299
+ return value ?? {};
300
+ }
301
+ async subdirs(path) {
302
+ try {
303
+ const entries = await nodeFs.readdir(path, { withFileTypes: true });
304
+ return entries.filter((e) => e.isDirectory()).map((e) => e.name).sort();
305
+ }
306
+ catch {
307
+ return [];
308
+ }
309
+ }
310
+ async listScopes() {
311
+ const scopes = [{ kind: 'user' }];
312
+ const root = P.scopesRoot(this.ctx);
313
+ const usable = (kind, key) => isValidScopeKey(kind, key) && !isReservedDeviceName(key);
314
+ for (const key of await this.subdirs(join(root, 'projects'))) {
315
+ if (usable('project', key))
316
+ scopes.push({ kind: 'project', key });
317
+ }
318
+ for (const key of await this.subdirs(join(root, 'tasks'))) {
319
+ if (usable('task', key))
320
+ scopes.push({ kind: 'task', key });
321
+ }
322
+ if (this.ctx.teamPath.length > 0) {
323
+ for (const key of await this.subdirs(this.ctx.teamPath)) {
324
+ if (usable('team', key))
325
+ scopes.push({ kind: 'team', key });
326
+ }
327
+ }
328
+ return scopes;
329
+ }
330
+ async readTombstones() {
331
+ const maxBytes = 16 * 1024 * 1024;
332
+ const read = await readJsonlFrom(P.tombstonesFile(this.ctx), 0, maxBytes);
333
+ return read.rows.filter((row) => isObject(row) && typeof row.fingerprint === 'string');
334
+ }
335
+ /** Locate a gene by id across the scopes on disk (live heads only). */
336
+ async findHead(id, scopes) {
337
+ for (const scope of scopes ?? (await this.listScopes())) {
338
+ const read = await this.readHead(scope, id);
339
+ if (read !== null)
340
+ return { scope, read };
341
+ }
342
+ return null;
343
+ }
344
+ async headExistsAnywhere(scope, id) {
345
+ const live = P.headFile(scope, id, this.ctx);
346
+ const archived = P.archiveHeadFile(scope, id, this.ctx);
347
+ if (live !== null && (await pathExists(live)))
348
+ return true;
349
+ return archived !== null && (await pathExists(archived));
350
+ }
351
+ async readSchema() {
352
+ return readJson(P.schemaFile(this.ctx));
353
+ }
354
+ async readProjectMeta(scope) {
355
+ const path = P.projectMetaFile(scope, this.ctx);
356
+ return path === null ? null : readJson(path);
357
+ }
358
+ async readCounts(scope) {
359
+ const path = P.indexFile(scope, 'counts.json', this.ctx);
360
+ const value = path === null ? null : await readJson(path);
361
+ return isCounts(value) ? value : null;
362
+ }
363
+ async readSnapshot(scope) {
364
+ const path = P.indexFile(scope, 'snapshot.json', this.ctx);
365
+ const value = path === null ? null : await readJson(path);
366
+ return value !== null && value.schema === 1 && Array.isArray(value.rows) ? value : null;
367
+ }
368
+ async statIndexFile(scope, name) {
369
+ const path = P.indexFile(scope, name, this.ctx);
370
+ return path === null ? null : statOrNull(path);
371
+ }
372
+ async readJournalFrom(scope, offset) {
373
+ const path = P.indexFile(scope, 'journal.jsonl', this.ctx);
374
+ if (path === null)
375
+ return { rows: [], nextOffset: offset, corrupt: 0 };
376
+ return readJsonlFrom(path, offset);
377
+ }
378
+ /** Bytes under a directory, one level of nesting (version / evidence trees). */
379
+ async dirBytes(dir) {
380
+ if (dir === null)
381
+ return 0;
382
+ let total = 0;
383
+ for (const name of await listDir(dir)) {
384
+ const stamp = await statOrNull(join(dir, name));
385
+ total += stamp?.size ?? 0;
386
+ }
387
+ return total;
388
+ }
389
+ /** Bytes an archived gene occupies: its head plus the version / evidence files beside it. */
390
+ async archivedBytesOf(scope, id) {
391
+ const head = P.archiveHeadFile(scope, id, this.ctx);
392
+ const headBytes = head === null ? 0 : ((await statOrNull(head))?.size ?? 0);
393
+ const versions = await this.dirBytes(P.archiveSideDir(scope, id, 'versions', this.ctx));
394
+ const evidence = await this.dirBytes(P.archiveSideDir(scope, id, 'evidence', this.ctx));
395
+ return headBytes + versions + evidence;
396
+ }
397
+ // ---- writes (strict) ------------------------------------------------------
398
+ async writeHead(scope, head) {
399
+ this.assertWritable(scope);
400
+ return this.writeHeadTo(this.path(P.headFile(scope, head.id, this.ctx)), head);
401
+ }
402
+ async writeHeadTo(path, head) {
403
+ await this.guard('head', path);
404
+ const text = await writeJsonStrict(path, orderHead(head));
405
+ const stamp = await statOrNull(path);
406
+ return { rev: revOf(text), mtimeMs: stamp?.mtimeMs ?? 0, size: Buffer.byteLength(text) };
407
+ }
408
+ /**
409
+ * Write a version file. `create` is for a number the head does not know yet (an orphan from a
410
+ * crashed commit is simply overwritten); `mutate` may change ONLY `state` and `validation`
411
+ * (versions are immutable, 6.2) and throws if anything else differs from what is on disk.
412
+ */
413
+ async writeVersion(scope, version, mode) {
414
+ this.assertWritable(scope);
415
+ if (mode === 'mutate') {
416
+ const existing = await this.readVersion(scope, version.id, version.n);
417
+ if (existing === null || !sameImmutablePart(existing, version)) {
418
+ throw new GeneStoreError('GENE_INVALID_CONTENT', 'A published version is immutable.', 'immutable_version');
419
+ }
420
+ }
421
+ const path = this.path(mode === 'mutate'
422
+ ? await this.versionPathFor(scope, version.id, version.n)
423
+ : P.versionFile(scope, version.id, version.n, this.ctx));
424
+ await this.guard('version', path);
425
+ await writeJsonStrict(path, orderVersion(version));
426
+ }
427
+ async writeEvidence(scope, evidence) {
428
+ this.assertWritable(scope);
429
+ const path = this.path(P.evidenceFile(scope, evidence.geneId, evidence.ref, this.ctx));
430
+ await this.guard('evidence', path);
431
+ await writeJsonStrict(path, orderKeys(evidence, EVIDENCE_ORDER));
432
+ }
433
+ async writeStatsShard(scope, shard, data) {
434
+ this.assertWritable(scope);
435
+ const path = this.path(P.statsFile(scope, shard, this.ctx));
436
+ await this.guard('stats', path);
437
+ await writeJsonStrict(path, data);
438
+ }
439
+ async writeCounts(scope, counts) {
440
+ this.assertWritable(scope);
441
+ const path = this.path(P.indexFile(scope, 'counts.json', this.ctx));
442
+ await this.guard('counts', path);
443
+ await writeJsonStrict(path, counts);
444
+ }
445
+ async appendJournal(scope, entry) {
446
+ this.assertWritable(scope);
447
+ const path = this.path(P.indexFile(scope, 'journal.jsonl', this.ctx));
448
+ await this.guard('journal', path);
449
+ await appendJsonl(path, entry);
450
+ }
451
+ async writeSnapshotAtomic(scope, snapshot) {
452
+ this.assertWritable(scope);
453
+ const path = this.path(P.indexFile(scope, 'snapshot.json', this.ctx));
454
+ await this.guard('snapshot', path);
455
+ await writeJsonStrict(path, snapshot);
456
+ }
457
+ async appendTombstone(tombstone) {
458
+ const path = P.tombstonesFile(this.ctx);
459
+ await this.guard('tombstone', path);
460
+ await appendJsonl(path, tombstone);
461
+ }
462
+ /** Create `schema.json` once; an existing one is returned untouched (extra keys survive). */
463
+ async ensureSchema(now) {
464
+ const existing = await this.readSchema();
465
+ if (existing !== null && existing.schema === 1)
466
+ return existing;
467
+ const created = { schema: 1, createdAt: now, vecAlgo: VEC_ALGO };
468
+ const path = P.schemaFile(this.ctx);
469
+ await this.guard('schema', path);
470
+ await writeJsonStrict(path, created);
471
+ return created;
472
+ }
473
+ /** Idempotent `project.json` (RV-10): rewritten only when `lastSeenAt` is a day or more old. */
474
+ async touchProjectMeta(scope, info, now) {
475
+ this.assertWritable(scope);
476
+ const path = this.path(P.projectMetaFile(scope, this.ctx));
477
+ const existing = await readJson(path);
478
+ if (existing !== null && now - existing.lastSeenAt < DAY_MS)
479
+ return false;
480
+ const meta = {
481
+ schema: 1,
482
+ key: info.key,
483
+ root: info.root,
484
+ label: info.label,
485
+ firstSeenAt: existing?.firstSeenAt ?? now,
486
+ lastSeenAt: now,
487
+ };
488
+ await this.guard('project', path);
489
+ await writeJsonStrict(path, meta);
490
+ return true;
491
+ }
492
+ // ---- moves: archive, restore, trash ----------------------------------------
493
+ /** Move every file of `from` into `to`, then drop the emptied directory. Idempotent. */
494
+ async moveContents(root, from, to) {
495
+ if (from === null || to === null)
496
+ return 0;
497
+ let bytes = 0;
498
+ for (const name of await listDir(from)) {
499
+ const source = join(from, name);
500
+ bytes += (await statOrNull(source))?.size ?? 0;
501
+ await moveInside(root, source, join(to, name));
502
+ }
503
+ await removeInside(root, from);
504
+ return bytes;
505
+ }
506
+ /** The directory a gene's `versions` / `evidence` files live in while the gene is live. */
507
+ liveSide(scope, id, side) {
508
+ return side === 'versions'
509
+ ? P.versionsDir(scope, id, this.ctx)
510
+ : P.evidenceDir(scope, id, this.ctx);
511
+ }
512
+ async moveSides(scope, id, direction) {
513
+ const root = this.scopeRoot(scope);
514
+ let bytes = 0;
515
+ for (const side of GENE_SIDES) {
516
+ const live = this.liveSide(scope, id, side);
517
+ const archived = P.archiveSideDir(scope, id, side, this.ctx);
518
+ const [from, to] = direction === 'toArchive' ? [live, archived] : [archived, live];
519
+ await this.guard('move', from ?? '');
520
+ bytes += await this.moveContents(root, from, to);
521
+ }
522
+ return bytes;
523
+ }
524
+ /** Archive: archived head first, live head removed (commit point), then the sides. */
525
+ async moveToArchive(scope, archivedHead) {
526
+ const root = this.assertWritable(scope);
527
+ const archivePath = this.path(P.archiveHeadFile(scope, archivedHead.id, this.ctx));
528
+ const written = await this.writeHeadTo(archivePath, archivedHead);
529
+ const livePath = this.path(P.headFile(scope, archivedHead.id, this.ctx));
530
+ await this.guard('move', livePath);
531
+ await removeInside(root, livePath);
532
+ const sides = await this.moveSides(scope, archivedHead.id, 'toArchive');
533
+ return { bytes: written.size + sides };
534
+ }
535
+ /** Restore: live head first, archive head removed (commit point), then the sides. */
536
+ async moveFromArchive(scope, liveHead) {
537
+ const root = this.assertWritable(scope);
538
+ const bytes = await this.archivedBytesOf(scope, liveHead.id);
539
+ const livePath = this.path(P.headFile(scope, liveHead.id, this.ctx));
540
+ const written = await this.writeHeadTo(livePath, liveHead);
541
+ const archivePath = this.path(P.archiveHeadFile(scope, liveHead.id, this.ctx));
542
+ await this.guard('move', archivePath);
543
+ await removeInside(root, archivePath);
544
+ await this.moveSides(scope, liveHead.id, 'toLive');
545
+ return { bytes, written };
546
+ }
547
+ /** Complete an interrupted archive / restore: pull stray version / evidence files to the head. */
548
+ async completeMoves(scope, id, headIsArchived) {
549
+ this.assertWritable(scope);
550
+ return this.moveSides(scope, id, headIsArchived ? 'toArchive' : 'toLive');
551
+ }
552
+ /** Delete: head, versions and evidence go to `trash/<id>.<ts>/` (30 days, 7.3). */
553
+ async moveToTrash(scope, id, ts, from) {
554
+ const root = this.assertWritable(scope);
555
+ const entry = this.path(P.trashEntryDir(scope, id, ts, this.ctx));
556
+ const sourceFile = from === 'live' ? P.headFile(scope, id, this.ctx) : P.archiveHeadFile(scope, id, this.ctx);
557
+ const source = this.path(sourceFile);
558
+ const bytes = (await statOrNull(source))?.size ?? 0;
559
+ await this.guard('move', source);
560
+ await moveInside(root, source, join(entry, 'head.json'));
561
+ let sides = 0;
562
+ for (const side of GENE_SIDES) {
563
+ const archived = P.archiveSideDir(scope, id, side, this.ctx);
564
+ sides += await this.moveContents(root, this.liveSide(scope, id, side), join(entry, side));
565
+ sides += await this.moveContents(root, archived, join(entry, side));
566
+ }
567
+ return { bytes: bytes + sides };
568
+ }
569
+ /** Undo `moveToTrash` while the entry still exists. Refuses to overwrite a live head. */
570
+ async restoreFromTrash(scope, id, ts) {
571
+ const root = this.assertWritable(scope);
572
+ const entry = this.path(P.trashEntryDir(scope, id, ts, this.ctx));
573
+ const head = await this.readHeadAt(join(entry, 'head.json'), id);
574
+ if (head === null)
575
+ return null;
576
+ if (await this.headExistsAnywhere(scope, id)) {
577
+ throw new GeneStoreError('GENE_STALE_BASIS', 'The gene exists again; nothing was restored.', 'exists');
578
+ }
579
+ const live = this.path(P.headFile(scope, id, this.ctx));
580
+ await moveInside(root, join(entry, 'head.json'), live);
581
+ await this.moveContents(root, join(entry, 'versions'), P.versionsDir(scope, id, this.ctx));
582
+ await this.moveContents(root, join(entry, 'evidence'), P.evidenceDir(scope, id, this.ctx));
583
+ await removeInside(root, entry);
584
+ return head.head;
585
+ }
586
+ /** Retention (7.3): drop specific version files. Callers choose which; this only bounds them. */
587
+ async removeVersionFiles(scope, id, numbers) {
588
+ const root = this.assertWritable(scope);
589
+ for (const n of numbers) {
590
+ const path = await this.versionPathFor(scope, id, n);
591
+ if (path !== null)
592
+ await removeInside(root, path);
593
+ }
594
+ }
595
+ /** Remove a duplicate archived head when the gene is live again (reconcile only; live wins). */
596
+ async removeArchivedHead(scope, id) {
597
+ const root = this.assertWritable(scope);
598
+ await removeInside(root, this.path(P.archiveHeadFile(scope, id, this.ctx)));
599
+ }
600
+ /** Gene ids that have a directory under `versions/` (live location), heads or not. */
601
+ async listVersionOwners(scope) {
602
+ const probe = P.versionsDir(scope, 'gk_0000000000', this.ctx);
603
+ if (probe === null)
604
+ return [];
605
+ const names = await this.subdirs(dirname(probe));
606
+ return names.filter((name) => /^g[kts]_[0-9a-z]{10}$/.test(name));
607
+ }
608
+ /** Are version / evidence files for `id` sitting on the wrong side of an interrupted move? */
609
+ async hasStraySides(scope, id, headIsArchived) {
610
+ const dirs = GENE_SIDES.map((side) => headIsArchived ? this.liveSide(scope, id, side) : P.archiveSideDir(scope, id, side, this.ctx));
611
+ for (const dir of dirs) {
612
+ if (dir !== null && (await listDir(dir)).length > 0)
613
+ return true;
614
+ }
615
+ return false;
616
+ }
617
+ }
618
+ /** Everything except `state` and `validation` must match (6.2: versions are immutable). */
619
+ function sameImmutablePart(a, b) {
620
+ const strip = (v) => canonicalJson({ ...v, state: null, validation: null });
621
+ return strip(a) === strip(b);
622
+ }
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Tombstones: "never learn this again" (gene-bank spec 6.7, 7.6, I-17).
3
+ *
4
+ * ASCII ONLY - the whole `gene/` tree is in `glyphs.test.ts::inScope`.
5
+ *
6
+ * `delete` and `forget` differ ONLY here. `delete` moves a gene to the trash and leaves no mark,
7
+ * so the same content can be learned again tomorrow. `forget` writes a tombstone (fingerprint +
8
+ * hashed vector) and the version service refuses any later `create` / import that matches it
9
+ * (`GENE_FORGOTTEN`) before it takes a lock or spends a validation token.
10
+ *
11
+ * TWO MATCH RULES, BOTH NEEDED. The fingerprint (type | scope kind | name | key tokens of
12
+ * purpose and trigger) catches the same idea re-learned verbatim. The vector (cosine against the
13
+ * tombstone's, >= `GENE_SCORE.duplicateCosine`) catches the reworded version a model produces on
14
+ * the second try. A fingerprint alone is defeated by one synonym; a vector alone would let two
15
+ * unrelated short genes collide, so the vector is only consulted inside the tombstone's range.
16
+ *
17
+ * RANGE. A tombstone is scoped (the scope it was forgotten in) or `'all'`. Because the fingerprint
18
+ * embeds the scope KIND, forgetting in all scopes writes one tombstone per kind (see the service);
19
+ * this module just matches what is on disk.
20
+ *
21
+ * APPEND-ONLY, READ WHOLE. The file is small (one line per forget) and `readTombstones` is cheap,
22
+ * but it sits on the create path, so the parsed rows are cached against the file's stat.
23
+ */
24
+ import type { GeneScope, GeneTombstone, GeneType } from '@aragon-agent/tui/model/gene/types';
25
+ import type { GeneStore } from './store.js';
26
+ export interface ForgottenQuery {
27
+ fingerprint: string;
28
+ /** Base64 hashed vector of the candidate gene, when known. */
29
+ vec?: string;
30
+ scope: GeneScope;
31
+ type: GeneType;
32
+ }
33
+ export type NewTombstone = Omit<GeneTombstone, 'schema' | 'createdAt'>;
34
+ export declare class TombstoneStore {
35
+ private readonly store;
36
+ private readonly now;
37
+ private cache;
38
+ constructor(store: GeneStore, now?: () => number);
39
+ add(tombstone: NewTombstone): Promise<GeneTombstone>;
40
+ all(): Promise<GeneTombstone[]>;
41
+ /**
42
+ * The first tombstone this candidate matches, or `null`. NEVER throws: a read must not block a
43
+ * write path.
44
+ */
45
+ isForgotten(query: ForgottenQuery): Promise<GeneTombstone | null>;
46
+ private match;
47
+ }