@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,761 @@
1
+ import { geneBriefLine } from '@aragon-agent/tui/model/gene/brief';
2
+ import { budgetUnits, planGeneContext, renderGeneContextText, resolveGeneBudgets, stabilizeGeneContext, } from '@aragon-agent/tui/model/gene/context';
3
+ import { describeGeneError } from '@aragon-agent/tui/model/gene/copy';
4
+ import { isValidEvidenceRef, isValidGeneId, isValidScope, isValidScopeKey, scopeId, } from '@aragon-agent/tui/model/gene/ids';
5
+ import { GENE_LIMITS } from '@aragon-agent/tui/model/gene/limits';
6
+ import { isVisibleScope, matchApplicability, normalizeName, } from '@aragon-agent/tui/model/gene/search';
7
+ import { containsCjk } from '@aragon-agent/tui/model/gene/tokenize';
8
+ import { buildGeneRulesBlock } from './block.js';
9
+ import { GeneCatalog } from './catalog.js';
10
+ import { makeGlobMatcher } from './env.js';
11
+ import { getLogger } from '../logging/logger.js';
12
+ import { resolveProjectKey } from '../memory/paths.js';
13
+ import { assembleSearchOutput, chunkText, explainLine, renderEvidenceList, renderEvidenceText, renderTier2, withCursor, } from './read.js';
14
+ import { redactSecrets } from './secrets.js';
15
+ import { ContextState, isHoldoutRun, offContext, queryTermsOf } from './service-context.js';
16
+ import { ViewEmitter } from './service-view.js';
17
+ import { SYSTEM_TIMER } from './usage.js';
18
+ /** `helped|misleading|not_applicable|outdated` -> the outcome ladder (7.5). */
19
+ const EFFECT_OF = {
20
+ helped: 'helped',
21
+ misleading: 'harmed',
22
+ not_applicable: 'neutral',
23
+ outdated: 'harmed',
24
+ };
25
+ /** Attribution weights by source (7.5). */
26
+ const WEIGHT = { agent: 1.0, tool: 0.8 };
27
+ const HINT_BUDGET_MS = 8;
28
+ const QUERY_CAP = 400;
29
+ const TOKEN_UNITS = 4;
30
+ const OFFSET_CAP = 100_000;
31
+ const defaultLog = {
32
+ warn: (message, data) => getLogger().warn('tool', message, data),
33
+ };
34
+ function gateClosed(code) {
35
+ return { ok: false, code, message: describeGeneError(code) };
36
+ }
37
+ function fail(code, detail) {
38
+ const message = describeGeneError(code, detail);
39
+ return { ok: false, code, message, ...(detail !== undefined ? { detail } : {}) };
40
+ }
41
+ function clampInt(value, min, max, fallback) {
42
+ const n = typeof value === 'number' && Number.isFinite(value) ? Math.floor(value) : fallback;
43
+ return Math.max(min, Math.min(max, n));
44
+ }
45
+ /** Published, in an authorised scope, and written for this role (I-6: nothing else is visible). */
46
+ function visibleTo(row, caller) {
47
+ return (row.status === 'published' &&
48
+ isVisibleScope(row.scope, caller) &&
49
+ Array.isArray(row.roles) &&
50
+ row.roles.includes(caller.role));
51
+ }
52
+ /** Resolve after `ms` or when `job` settles, whichever is first. Never rejects or leaks a timer. */
53
+ function settleWithin(job, ms, timer) {
54
+ return new Promise((resolve) => {
55
+ const handle = timer.set(resolve, ms);
56
+ const done = () => {
57
+ timer.clear(handle);
58
+ resolve();
59
+ };
60
+ job.then(done, done);
61
+ });
62
+ }
63
+ function isSwitchedOff(budgets) {
64
+ return budgets.maxItems === 0 || budgets.maxTokens === 0;
65
+ }
66
+ function readOutput(row, tier, chunk, command, ref) {
67
+ return {
68
+ id: row.id,
69
+ name: row.brief.name,
70
+ tier,
71
+ ...(ref !== undefined ? { ref } : {}),
72
+ text: withCursor(chunk, command),
73
+ ...(chunk.next !== undefined ? { next: chunk.next } : {}),
74
+ };
75
+ }
76
+ function teamScopeOf(key) {
77
+ return isValidScopeKey('team', key) ? { kind: 'team', key } : null;
78
+ }
79
+ export class GeneService {
80
+ deps;
81
+ catalog;
82
+ ownsCatalog;
83
+ timer;
84
+ ctx;
85
+ view;
86
+ offChange;
87
+ scopeKey = '\u0000';
88
+ scopeList = [{ kind: 'user' }];
89
+ projectLabel;
90
+ matcher;
91
+ busy = 0;
92
+ libraryCache = null;
93
+ disposed = false;
94
+ constructor(deps) {
95
+ this.deps = deps;
96
+ this.ownsCatalog = deps.catalog === undefined;
97
+ this.catalog =
98
+ deps.catalog ??
99
+ new GeneCatalog({
100
+ reader: deps.reader,
101
+ now: deps.now,
102
+ onError: (op, error) => this.warn(op, error),
103
+ });
104
+ this.timer = deps.timer ?? SYSTEM_TIMER;
105
+ this.ctx = new ContextState(deps.role);
106
+ this.view = new ViewEmitter({
107
+ snapshot: () => this.snapshotView(),
108
+ now: deps.now,
109
+ timer: this.timer,
110
+ intervalMs: deps.emitIntervalMs ?? 250,
111
+ onError: (error) => this.warn('emit', error),
112
+ });
113
+ this.offChange = this.catalog.onChange(() => {
114
+ this.ctx.dirty = true;
115
+ this.emitIfChanged();
116
+ });
117
+ }
118
+ // ===========================================================================
119
+ // Lifecycle
120
+ // ===========================================================================
121
+ /** Load the index. The controller calls it at construction, off the critical path. */
122
+ async start() {
123
+ try {
124
+ this.syncScopes();
125
+ await this.catalog.catchUp();
126
+ this.emitIfChanged();
127
+ }
128
+ catch (error) {
129
+ this.warn('start', error);
130
+ }
131
+ }
132
+ async dispose() {
133
+ if (this.disposed)
134
+ return;
135
+ this.disposed = true;
136
+ this.offChange();
137
+ this.view.dispose();
138
+ if (this.ownsCatalog)
139
+ this.catalog.dispose();
140
+ try {
141
+ await this.deps.usage.dispose?.();
142
+ }
143
+ catch (error) {
144
+ this.warn('dispose', error);
145
+ }
146
+ }
147
+ // ===========================================================================
148
+ // Switches and callers
149
+ // ===========================================================================
150
+ /**
151
+ * The three reasons a call is refused, evaluated against the LIVE config (I-18). The holdout
152
+ * draw (13) needs the run; without one only the two user switches apply.
153
+ */
154
+ gate(runId) {
155
+ const cfg = this.deps.getConfig();
156
+ if (!cfg.enabled)
157
+ return gateClosed('GENE_DISABLED');
158
+ if (!cfg.use)
159
+ return gateClosed('GENE_USE_OFF');
160
+ if (runId !== undefined && isHoldoutRun(runId, cfg.holdoutPercent)) {
161
+ return gateClosed('GENE_HOLDOUT');
162
+ }
163
+ return { ok: true };
164
+ }
165
+ /** The scopes this session may see: user, current project, team (if set), this session's task. */
166
+ getScopes() {
167
+ this.syncScopes();
168
+ return this.scopeList;
169
+ }
170
+ /** Who is asking, from where, with which tools (8.2 step 1 - 4). */
171
+ buildCaller(role = this.deps.role, over = {}) {
172
+ this.syncScopes();
173
+ return {
174
+ role,
175
+ scopes: this.scopeList,
176
+ tools: [...(over.tools ?? this.deps.registeredTools())],
177
+ env: this.deps.env(),
178
+ windowTokens: over.windowTokens ?? this.deps.windowTokens(),
179
+ ...(this.matcher !== undefined ? { matchesGlob: this.matcher } : {}),
180
+ };
181
+ }
182
+ syncScopes() {
183
+ const cwd = this.deps.getCwd();
184
+ const team = this.deps.getConfig().teamPath;
185
+ const key = `${cwd}\u0000${team}`;
186
+ if (key === this.scopeKey)
187
+ return;
188
+ this.scopeKey = key;
189
+ const scopes = [{ kind: 'user' }];
190
+ const project = this.identify(cwd);
191
+ if (project !== null)
192
+ scopes.push({ kind: 'project', key: project.key });
193
+ const teamScope = team.length > 0 ? teamScopeOf(this.deps.teamKey ?? 'team') : null;
194
+ if (teamScope !== null)
195
+ scopes.push(teamScope);
196
+ const session = this.deps.sessionId;
197
+ if (isValidScopeKey('task', session))
198
+ scopes.push({ kind: 'task', key: session });
199
+ this.scopeList = scopes.filter(isValidScope);
200
+ this.projectLabel = project?.label;
201
+ this.matcher = makeGlobMatcher(cwd);
202
+ this.catalog.setScopes(this.scopeList);
203
+ }
204
+ identify(cwd) {
205
+ try {
206
+ const identity = resolveProjectKey(cwd);
207
+ return isValidScopeKey('project', identity.key) ? identity : null;
208
+ }
209
+ catch (error) {
210
+ this.warn('identify', error);
211
+ return null;
212
+ }
213
+ }
214
+ /** Scopes, then a bounded wait for the index to catch up. */
215
+ async readyCaller(actor) {
216
+ this.syncScopes();
217
+ await this.syncIndex();
218
+ return this.buildCaller(actor.role);
219
+ }
220
+ async syncIndex() {
221
+ const wait = this.deps.syncWaitMs ?? GENE_LIMITS.searchBudgetMs;
222
+ await settleWithin(this.catalog.catchUp(), wait, this.timer);
223
+ }
224
+ // ===========================================================================
225
+ // gene_search (tier 1)
226
+ // ===========================================================================
227
+ async search(actor, req = {}) {
228
+ return this.guard('search', () => this.tracked(() => this.runSearch(actor, req)));
229
+ }
230
+ async runSearch(actor, req) {
231
+ const gate = this.gate(actor.runId);
232
+ if (!gate.ok)
233
+ return fail(gate.code);
234
+ const caller = await this.readyCaller(actor);
235
+ const query = (req.query ?? '').trim().slice(0, QUERY_CAP);
236
+ const limit = clampInt(req.limit, 1, GENE_LIMITS.searchMax, GENE_LIMITS.searchDefault);
237
+ const offset = clampInt(req.offset, 0, OFFSET_CAP, 0);
238
+ const opts = {
239
+ query,
240
+ type: req.type ?? 'all',
241
+ scope: req.scope ?? 'all',
242
+ limit,
243
+ offset,
244
+ now: this.deps.now(),
245
+ };
246
+ const result = this.catalog.search(opts, caller);
247
+ const explain = req.explain === true;
248
+ const rows = result.hits.map((hit) => this.searchRow(hit, opts, caller, explain));
249
+ for (const hit of result.hits)
250
+ this.expose(hit.row, actor, 'retrieved', 'search');
251
+ return {
252
+ ok: true,
253
+ value: assembleSearchOutput({
254
+ rows,
255
+ total: result.total,
256
+ visible: result.visible,
257
+ filtered: result.filtered,
258
+ offset,
259
+ limit,
260
+ explain,
261
+ cjkQuery: containsCjk(query),
262
+ ...(result.partial === true ? { partial: true } : {}),
263
+ ...(result.degraded !== undefined ? { degraded: result.degraded } : {}),
264
+ }),
265
+ };
266
+ }
267
+ searchRow(hit, opts, caller, explain) {
268
+ const { row } = hit;
269
+ return {
270
+ id: row.id,
271
+ type: row.type,
272
+ scope: row.scope.kind,
273
+ line: geneBriefLine(row),
274
+ relevance: Math.round(hit.relevance * 1000) / 1000,
275
+ ...(explain ? { explain: explainLine(this.catalog.explain(row, opts, caller)) } : {}),
276
+ };
277
+ }
278
+ // ===========================================================================
279
+ // gene_read (tier 2 / tier 3)
280
+ // ===========================================================================
281
+ async read(actor, req) {
282
+ return this.guard('read', () => this.tracked(() => this.runRead(actor, req)));
283
+ }
284
+ async runRead(actor, req) {
285
+ const gate = this.gate(actor.runId);
286
+ if (!gate.ok)
287
+ return fail(gate.code);
288
+ const caller = await this.readyCaller(actor);
289
+ const found = this.resolve(req.id ?? req.name, caller);
290
+ if (!found.ok)
291
+ return found;
292
+ return req.tier === 3
293
+ ? this.readTier3(actor, found.value, caller, req)
294
+ : this.readTier2(actor, found.value, caller, req);
295
+ }
296
+ /** An id, or a unique name among the genes this caller may see. */
297
+ resolve(ref, caller) {
298
+ const key = (ref ?? '').trim();
299
+ if (key.length === 0)
300
+ return fail('GENE_INVALID_ID');
301
+ if (/^g[kts]_/.test(key) && !isValidGeneId(key))
302
+ return fail('GENE_INVALID_ID');
303
+ if (isValidGeneId(key)) {
304
+ const row = this.catalog.get(key);
305
+ if (row === undefined || !visibleTo(row, caller))
306
+ return fail('GENE_NOT_FOUND');
307
+ return { ok: true, value: row };
308
+ }
309
+ return this.resolveByName(key, caller);
310
+ }
311
+ resolveByName(name, caller) {
312
+ const wanted = normalizeName(name);
313
+ if (wanted.length === 0)
314
+ return fail('GENE_NOT_FOUND');
315
+ const matches = [];
316
+ for (const row of this.catalog.rows()) {
317
+ if (visibleTo(row, caller) && normalizeName(row.brief.name) === wanted)
318
+ matches.push(row);
319
+ }
320
+ if (matches.length === 0)
321
+ return fail('GENE_NOT_FOUND');
322
+ if (matches.length > 1) {
323
+ return fail('GENE_AMBIGUOUS_NAME', matches.slice(0, 5).map((r) => r.id).join(','));
324
+ }
325
+ return { ok: true, value: matches[0] };
326
+ }
327
+ /**
328
+ * The head and the current version, read from disk. The index row only found the gene; the HEAD
329
+ * decides whether it may be served (a row can lag a commit by a catch-up), including its role.
330
+ */
331
+ async loadPublished(row, caller) {
332
+ const read = await this.deps.reader.readHead(row.scope, row.id);
333
+ const head = read?.head;
334
+ if (head === undefined || head.status !== 'published' || head.currentVersion === null) {
335
+ return fail('GENE_NOT_FOUND');
336
+ }
337
+ const version = await this.deps.reader.readVersion(row.scope, row.id, head.currentVersion);
338
+ if (version === null)
339
+ return fail('GENE_UNAVAILABLE', 'version_missing');
340
+ if (!version.content.roles.includes(caller.role))
341
+ return fail('GENE_NOT_FOUND');
342
+ return { ok: true, value: { head, content: version.content } };
343
+ }
344
+ async readTier2(actor, row, caller, req) {
345
+ const loaded = await this.loadPublished(row, caller);
346
+ if (!loaded.ok)
347
+ return loaded;
348
+ const applies = matchApplicability(row.applicability, caller, row);
349
+ const text = renderTier2({
350
+ row,
351
+ content: loaded.value.content,
352
+ requires: this.requiresOf(loaded.value.content, caller),
353
+ canRun: caller.tools.includes('gene_run'),
354
+ ...(applies.ok ? {} : { notApplicable: applies.reason }),
355
+ });
356
+ const offset = req.offset ?? 0;
357
+ const chunk = chunkText(text, offset, GENE_LIMITS.readChunkTier2);
358
+ if (offset <= 0)
359
+ this.expose(row, actor, 'read', 'read');
360
+ return { ok: true, value: readOutput(row, 2, chunk, `gene_read id=${row.id}`) };
361
+ }
362
+ /** A skill's dependencies as tier-1 lines - or a bare id when the caller may not see one. */
363
+ requiresOf(content, caller) {
364
+ const ids = new Set();
365
+ for (const dep of content.deps)
366
+ if (dep.kind === 'requires')
367
+ ids.add(dep.id);
368
+ const payload = content.payload;
369
+ for (const dep of Array.isArray(payload.requires) ? payload.requires : [])
370
+ ids.add(dep.id);
371
+ return [...ids].slice(0, GENE_LIMITS.depsMax).map((id) => {
372
+ const dep = this.catalog.get(id);
373
+ return { id, line: dep !== undefined && visibleTo(dep, caller) ? geneBriefLine(dep) : null };
374
+ });
375
+ }
376
+ async readTier3(actor, row, caller, req) {
377
+ const loaded = await this.loadPublished(row, caller);
378
+ if (!loaded.ok)
379
+ return loaded;
380
+ const ref = (req.ref ?? '').trim();
381
+ const listing = ref === '' || ref === 'list';
382
+ const text = listing ? await this.evidenceListing(row) : await this.evidenceBody(row, ref);
383
+ if (typeof text !== 'string')
384
+ return text;
385
+ const offset = req.offset ?? 0;
386
+ if (offset <= 0)
387
+ this.expose(row, actor, 'readL3', 'read');
388
+ const chunk = chunkText(text, offset, GENE_LIMITS.readChunkTier3);
389
+ const command = `gene_read id=${row.id} tier=3${listing ? '' : ` ref=${ref}`}`;
390
+ return { ok: true, value: readOutput(row, 3, chunk, command, listing ? undefined : ref) };
391
+ }
392
+ async evidenceListing(row) {
393
+ return renderEvidenceList(row.id, await this.deps.reader.listEvidence(row.scope, row.id));
394
+ }
395
+ async evidenceBody(row, ref) {
396
+ if (!isValidEvidenceRef(ref))
397
+ return fail('GENE_NOT_FOUND', 'evidence ref');
398
+ const evidence = await this.deps.reader.readEvidence(row.scope, row.id, ref);
399
+ if (evidence === null)
400
+ return fail('GENE_NOT_FOUND', 'evidence ref');
401
+ return renderEvidenceText(evidence);
402
+ }
403
+ // ===========================================================================
404
+ // gene_feedback / gene_run support
405
+ // ===========================================================================
406
+ /** Record the Agent's verdict. Writes no gene and queues nothing: only usage events. */
407
+ async feedback(actor, req) {
408
+ return this.guard('feedback', async () => {
409
+ const gate = this.gate(actor.runId);
410
+ if (!gate.ok)
411
+ return fail(gate.code);
412
+ const effect = EFFECT_OF[req.verdict];
413
+ if (effect === undefined)
414
+ return fail('GENE_ARGS_INVALID', 'verdict');
415
+ const found = this.resolve(req.id, this.buildCaller(actor.role));
416
+ if (!found.ok)
417
+ return found;
418
+ const row = found.value;
419
+ this.recordOutcome(row, actor, { effect, by: 'agent', weight: WEIGHT.agent });
420
+ this.deps.onFeedback?.({
421
+ geneId: row.id,
422
+ scope: row.scope,
423
+ verdict: req.verdict,
424
+ effect,
425
+ runId: actor.runId,
426
+ ...(actor.agent !== undefined ? { agent: actor.agent } : {}),
427
+ ...(req.note !== undefined ? { note: this.cleanNote(req.note) } : {}),
428
+ });
429
+ const name = row.brief.name;
430
+ return { ok: true, value: { id: row.id, name, verdict: req.verdict, effect } };
431
+ });
432
+ }
433
+ /** Secret-scrubbed, one line, <= 200 chars. Goes to the learner, never into the usage log. */
434
+ cleanNote(note) {
435
+ const scrubbed = redactSecrets(note, this.deps.knownSecrets()).text.replace(/\s+/g, ' ').trim();
436
+ return scrubbed.slice(0, GENE_LIMITS.noteFieldMax);
437
+ }
438
+ /** `adopted` plus its `outcome`, both carrying the attribution source and weight (7.5). */
439
+ recordOutcome(row, actor, outcome) {
440
+ const sc = scopeId(row.scope);
441
+ const base = { sc, t: this.deps.now(), g: row.id, v: row.v, run: actor.runId };
442
+ const agent = actor.agent !== undefined ? { agent: actor.agent } : {};
443
+ this.record({ ...base, k: 'adopted', by: outcome.by, ...agent });
444
+ this.record({ ...base, k: 'outcome', e: outcome.effect, w: outcome.weight, by: outcome.by });
445
+ }
446
+ /** What `gene_run` needs: the tool payload of a published, healthy, applicable tool gene. */
447
+ async describeTool(actor, id) {
448
+ return this.guard('describeTool', async () => {
449
+ const gate = this.gate(actor.runId);
450
+ if (!gate.ok)
451
+ return fail(gate.code);
452
+ const caller = await this.readyCaller(actor);
453
+ const found = this.resolve(id, caller);
454
+ if (!found.ok)
455
+ return found;
456
+ const row = found.value;
457
+ if (row.type !== 'tool')
458
+ return fail('GENE_NOT_FOUND', 'not a tool gene');
459
+ if (row.health === 'broken')
460
+ return fail('GENE_TOOL_BROKEN');
461
+ const applies = matchApplicability(row.applicability, caller, row);
462
+ if (!applies.ok)
463
+ return fail('GENE_NOT_FOUND', applies.reason);
464
+ const loaded = await this.loadPublished(row, caller);
465
+ if (!loaded.ok)
466
+ return loaded;
467
+ const { head, content } = loaded.value;
468
+ if (head.health === 'broken')
469
+ return fail('GENE_TOOL_BROKEN');
470
+ return {
471
+ ok: true,
472
+ value: {
473
+ id: row.id,
474
+ name: row.brief.name,
475
+ version: head.currentVersion ?? row.v,
476
+ scope: row.scope,
477
+ health: head.health,
478
+ payload: content.payload,
479
+ },
480
+ };
481
+ });
482
+ }
483
+ /** A tool gene's result: `helped` on success, `neutral` for a bad argument, else `harmed`. */
484
+ async recordToolOutcome(actor, run) {
485
+ return this.guard('recordToolOutcome', async () => {
486
+ const found = this.resolve(run.id, this.buildCaller(actor.role));
487
+ if (!found.ok)
488
+ return found;
489
+ const effect = run.ok ? 'helped' : run.inputError === true ? 'neutral' : 'harmed';
490
+ this.recordOutcome(found.value, actor, { effect, by: 'tool', weight: WEIGHT.tool });
491
+ return { ok: true, value: { effect } };
492
+ });
493
+ }
494
+ // ===========================================================================
495
+ // Hints (9.4)
496
+ // ===========================================================================
497
+ /**
498
+ * A local, synchronous lookup for the hint engine: tier-1 only, no disk, an 8 ms budget. Returns
499
+ * `[]` when hints or the library are off. Counting a hint as `shown` is the engine's call
500
+ * (`markHintsShown`) because only it knows which hits it actually printed.
501
+ */
502
+ hintSearch(actor, req) {
503
+ try {
504
+ if (!this.deps.getConfig().hints || !this.gate(actor.runId).ok)
505
+ return [];
506
+ const query = req.text.trim().slice(0, QUERY_CAP);
507
+ if (query.length === 0)
508
+ return [];
509
+ const max = clampInt(req.max, 1, GENE_LIMITS.hintMaxLines, GENE_LIMITS.hintMaxLines);
510
+ const opts = {
511
+ query,
512
+ type: 'all',
513
+ scope: 'all',
514
+ limit: Math.min(GENE_LIMITS.searchMax, max * 3),
515
+ minRelevance: req.minRelevance,
516
+ now: this.deps.now(),
517
+ };
518
+ const result = this.catalog.search(opts, this.buildCaller(actor.role), HINT_BUDGET_MS);
519
+ const wanted = req.types === undefined ? null : new Set(req.types);
520
+ // The index lets an exact name / tag / error-code hit past the relevance floor; a hint is
521
+ // unsolicited, so the engine's own floor is enforced strictly here (9.4: 0.45 - 0.55).
522
+ return result.hits
523
+ .filter((hit) => hit.relevance >= req.minRelevance)
524
+ .filter((hit) => wanted === null || wanted.has(hit.row.type))
525
+ .slice(0, max)
526
+ .map((hit) => ({
527
+ id: hit.row.id,
528
+ type: hit.row.type,
529
+ line: geneBriefLine(hit.row),
530
+ relevance: hit.relevance,
531
+ }));
532
+ }
533
+ catch (error) {
534
+ this.warn('hintSearch', error);
535
+ return [];
536
+ }
537
+ }
538
+ markHintsShown(actor, ids) {
539
+ for (const id of ids) {
540
+ const row = this.catalog.get(id);
541
+ if (row !== undefined)
542
+ this.expose(row, actor, 'shown', 'hint');
543
+ }
544
+ }
545
+ // ===========================================================================
546
+ // The auto context zone (8.5, 9.2, 9.3)
547
+ // ===========================================================================
548
+ /**
549
+ * Plan, render and remember the `<gene_context>` block for a role. Never throws: any failure
550
+ * yields an empty block, which is the byte-equivalent "feature absent" prompt (I-20).
551
+ */
552
+ async planContext(req) {
553
+ const role = req.role ?? this.deps.role;
554
+ this.busy += 1;
555
+ this.emitIfChanged();
556
+ try {
557
+ return await this.runPlan(req, role);
558
+ }
559
+ catch (error) {
560
+ this.warn('planContext', error);
561
+ return this.absent(role, { degraded: 'index_unavailable' });
562
+ }
563
+ finally {
564
+ this.busy -= 1;
565
+ this.emitIfChanged();
566
+ }
567
+ }
568
+ async runPlan(req, role) {
569
+ if (req.reason !== undefined && req.reason !== 'user_turn')
570
+ this.ctx.reset(role);
571
+ const window = req.windowTokens ?? this.deps.windowTokens();
572
+ const budgets = resolveGeneBudgets(this.deps.getConfig(), role, window);
573
+ if (!this.gate(req.runId).ok || isSwitchedOff(budgets))
574
+ return this.absent(role, { budgets });
575
+ this.syncScopes();
576
+ await this.syncIndex();
577
+ if (this.catalog.state() !== 'ready') {
578
+ return this.absent(role, { budgets, degraded: 'index_rebuilding' });
579
+ }
580
+ return this.settle(req, role, budgets, this.planFor(req, role, budgets));
581
+ }
582
+ planFor(req, role, budgets) {
583
+ const over = req.windowTokens !== undefined ? { windowTokens: req.windowTokens } : {};
584
+ const queryTerms = req.queryTerms !== undefined ? [...req.queryTerms] : queryTermsOf(req.taskText ?? '');
585
+ const caller = this.buildCaller(role, over);
586
+ const input = { role, queryTerms, caller, budgets, now: this.deps.now() };
587
+ return planGeneContext(input, this.catalog.index, this.catalog.statsOf);
588
+ }
589
+ settle(req, role, budgets, plan) {
590
+ const pinned = new Set(plan.lines.filter((l) => l.reason === 'pinned').map((l) => l.id));
591
+ const text = renderGeneContextText(plan, {
592
+ role,
593
+ ...(this.projectLabel !== undefined ? { project: this.projectLabel } : {}),
594
+ budgetItems: budgets.maxItems,
595
+ budgetTokens: budgets.maxTokens,
596
+ });
597
+ const previous = this.ctx.previous(role);
598
+ const ids = plan.lines.map((l) => l.id);
599
+ const kept = stabilizeGeneContext(previous, { ids, text, pinnedIds: pinned });
600
+ const pinnedIds = kept.reused && previous ? previous.pinnedIds : pinned;
601
+ this.ctx.remember(role, { ids: kept.ids, text: kept.text, pinnedIds });
602
+ this.ctx.dirty = false;
603
+ this.markShown(req, role, kept.ids);
604
+ this.ctx.setView({
605
+ role,
606
+ loadedItems: kept.ids.length,
607
+ loadedTokens: Math.ceil(budgetUnits(kept.text) / TOKEN_UNITS),
608
+ budgetItems: budgets.maxItems,
609
+ budgetTokens: budgets.maxTokens,
610
+ stopReason: plan.stopReason,
611
+ });
612
+ this.emitIfChanged();
613
+ return {
614
+ text: kept.text,
615
+ plan,
616
+ reused: kept.reused,
617
+ budgetItems: budgets.maxItems,
618
+ budgetTokens: budgets.maxTokens,
619
+ };
620
+ }
621
+ /** The zone is absent: remember an EMPTY snapshot so `renderContextBlock` yields '' too. */
622
+ absent(role, why) {
623
+ const budgets = why.budgets ?? { maxItems: 0, maxTokens: 0 };
624
+ this.ctx.remember(role, { ids: [], text: '', pinnedIds: new Set() });
625
+ this.ctx.setView(offContext(role, budgets.maxItems, budgets.maxTokens));
626
+ return {
627
+ text: '',
628
+ plan: null,
629
+ reused: false,
630
+ budgetItems: budgets.maxItems,
631
+ budgetTokens: budgets.maxTokens,
632
+ ...(why.degraded !== undefined ? { degraded: why.degraded } : {}),
633
+ };
634
+ }
635
+ /** `shown` once per (run, gene): the recorder dedupes, so a rebuilt zone never inflates it. */
636
+ markShown(req, role, ids) {
637
+ for (const id of ids) {
638
+ const row = this.catalog.get(id);
639
+ if (row !== undefined)
640
+ this.expose(row, { runId: req.runId, role }, 'shown', 'context');
641
+ }
642
+ }
643
+ /** The last planned `<gene_context>` block for a role; '' when off. For the prompt builder. */
644
+ renderContextBlock(role = this.deps.role) {
645
+ return this.gate().ok ? this.ctx.textOf(role) : '';
646
+ }
647
+ /** The stable `<gene_library>` rules block; '' unless the library is on and its tools exist. */
648
+ renderRulesBlock(toolNames, runId) {
649
+ return buildGeneRulesBlock({ active: this.gate(runId).ok, toolNames });
650
+ }
651
+ /** Drop the hysteresis memory (`/clear`, `/resume`, `/cwd`): the next plan lands in full. */
652
+ invalidateContext(role) {
653
+ this.ctx.reset(role);
654
+ }
655
+ /** The visible set changed after the last plan; it applies at the next user turn. */
656
+ isContextDirty() {
657
+ return this.ctx.dirty;
658
+ }
659
+ // ===========================================================================
660
+ // The session view (12.8)
661
+ // ===========================================================================
662
+ getView() {
663
+ return { ...this.snapshotView(), revision: this.view.revision };
664
+ }
665
+ /** Everything in the view except the revision, which the emitter owns. */
666
+ snapshotView() {
667
+ const cfg = this.deps.getConfig();
668
+ return {
669
+ available: cfg.enabled,
670
+ use: cfg.use,
671
+ autoLearn: cfg.autoLearn,
672
+ library: this.libraryView(cfg),
673
+ context: this.ctx.getView(),
674
+ retrieving: this.busy > 0,
675
+ };
676
+ }
677
+ libraryView(cfg) {
678
+ const version = this.catalog.version();
679
+ const cached = this.libraryCache;
680
+ if (cached?.version === version && cached.cap === cfg.capPerType)
681
+ return cached.value;
682
+ const counts = this.catalog.libraryCounts();
683
+ const overCap = {};
684
+ for (const type of ['knowledge', 'tool', 'skill']) {
685
+ if (counts[type] > cfg.capPerType)
686
+ overCap[type] = counts[type] - cfg.capPerType;
687
+ }
688
+ const { knowledge, tool, skill, candidates, pinned } = counts;
689
+ const value = { knowledge, tool, skill, candidates, pinned, overCap };
690
+ this.libraryCache = { version, cap: cfg.capPerType, value };
691
+ return value;
692
+ }
693
+ subscribe(listener) {
694
+ return this.view.subscribe(listener);
695
+ }
696
+ /**
697
+ * Bump the revision when the view differs from the last one, and tell subscribers - at most
698
+ * every `emitIntervalMs` (4 Hz), with a trailing notification so the last change is not lost.
699
+ */
700
+ emitIfChanged() {
701
+ if (!this.disposed)
702
+ this.view.emitIfChanged();
703
+ }
704
+ // ===========================================================================
705
+ // Plumbing
706
+ // ===========================================================================
707
+ /** Every public async method funnels here: an exception becomes `GENE_UNAVAILABLE`. */
708
+ async guard(op, job) {
709
+ try {
710
+ return await job();
711
+ }
712
+ catch (error) {
713
+ this.warn(op, error);
714
+ return fail('GENE_UNAVAILABLE');
715
+ }
716
+ }
717
+ /** Marks the service `retrieving` for the duration of a call (local, ephemeral, 12.8). */
718
+ async tracked(job) {
719
+ this.busy += 1;
720
+ this.emitIfChanged();
721
+ try {
722
+ return await job();
723
+ }
724
+ finally {
725
+ this.busy -= 1;
726
+ this.emitIfChanged();
727
+ }
728
+ }
729
+ expose(row, actor, k, src) {
730
+ this.record({
731
+ sc: scopeId(row.scope),
732
+ t: this.deps.now(),
733
+ k,
734
+ g: row.id,
735
+ v: row.v,
736
+ run: actor.runId,
737
+ src,
738
+ ...(actor.agent !== undefined ? { agent: actor.agent } : {}),
739
+ });
740
+ }
741
+ record(event) {
742
+ try {
743
+ this.deps.usage.record(event);
744
+ }
745
+ catch (error) {
746
+ this.warn('usage', error);
747
+ }
748
+ }
749
+ /** Operation name and error CLASS only (I-19): a message can hold a path or a gene's text. */
750
+ warn(op, error) {
751
+ try {
752
+ const code = error?.code;
753
+ const name = error instanceof Error ? error.name : 'Error';
754
+ const label = typeof code === 'string' ? code : name;
755
+ (this.deps.log ?? defaultLog).warn(`gene ${op} failed`, { op, error: label });
756
+ }
757
+ catch {
758
+ // Logging must never be the thing that fails a user turn.
759
+ }
760
+ }
761
+ }