@aragon-agent/cli 0.6.55 → 0.6.57

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (319) hide show
  1. package/CHANGELOG.md +2935 -2864
  2. package/README.md +160 -45
  3. package/dist/agent/controller.d.ts +47 -0
  4. package/dist/agent/controller.js +153 -2
  5. package/dist/agent/governance-wiring.js +8 -1
  6. package/dist/agent/system-prompt.d.ts +26 -0
  7. package/dist/agent/system-prompt.js +11 -0
  8. package/dist/app/App.js +101 -3
  9. package/dist/cli.js +29 -1
  10. package/dist/commands/builtins.js +4 -0
  11. package/dist/commands/catalog.js +1 -0
  12. package/dist/commands/registry.d.ts +8 -0
  13. package/dist/config/app-paths.d.ts +10 -0
  14. package/dist/config/app-paths.js +12 -0
  15. package/dist/config/cli-commands.d.ts +29 -0
  16. package/dist/config/cli-commands.js +76 -1
  17. package/dist/config/env.d.ts +2 -1
  18. package/dist/config/env.js +12 -1
  19. package/dist/config/load.d.ts +10 -0
  20. package/dist/config/load.js +13 -2
  21. package/dist/config/store.js +11 -1
  22. package/dist/exec/bridge/server.d.ts +7 -0
  23. package/dist/exec/bridge/server.js +6 -2
  24. package/dist/exec/cli-commands.js +4 -0
  25. package/dist/exec/index.js +2 -0
  26. package/dist/exec/options.d.ts +11 -0
  27. package/dist/exec/options.js +21 -1
  28. package/dist/gene/block.d.ts +33 -0
  29. package/dist/gene/block.js +51 -0
  30. package/dist/gene/capacity.d.ts +74 -0
  31. package/dist/gene/capacity.js +169 -0
  32. package/dist/gene/catalog-reconcile.d.ts +13 -0
  33. package/dist/gene/catalog-reconcile.js +105 -0
  34. package/dist/gene/catalog-stats.d.ts +27 -0
  35. package/dist/gene/catalog-stats.js +89 -0
  36. package/dist/gene/catalog-sync.d.ts +82 -0
  37. package/dist/gene/catalog-sync.js +324 -0
  38. package/dist/gene/catalog.d.ts +160 -0
  39. package/dist/gene/catalog.js +433 -0
  40. package/dist/gene/cli-commands.d.ts +50 -0
  41. package/dist/gene/cli-commands.js +500 -0
  42. package/dist/gene/command-report.d.ts +40 -0
  43. package/dist/gene/command-report.js +246 -0
  44. package/dist/gene/command.d.ts +29 -0
  45. package/dist/gene/command.js +561 -0
  46. package/dist/gene/commit-apply-types.d.ts +13 -0
  47. package/dist/gene/commit-apply-types.js +1 -0
  48. package/dist/gene/commit-compound.d.ts +34 -0
  49. package/dist/gene/commit-compound.js +212 -0
  50. package/dist/gene/commit-counts.d.ts +41 -0
  51. package/dist/gene/commit-counts.js +70 -0
  52. package/dist/gene/commit-exec.d.ts +42 -0
  53. package/dist/gene/commit-exec.js +134 -0
  54. package/dist/gene/commit-head.d.ts +52 -0
  55. package/dist/gene/commit-head.js +97 -0
  56. package/dist/gene/commit-plan.d.ts +95 -0
  57. package/dist/gene/commit-plan.js +68 -0
  58. package/dist/gene/commit-prepare.d.ts +63 -0
  59. package/dist/gene/commit-prepare.js +159 -0
  60. package/dist/gene/commit-types.d.ts +234 -0
  61. package/dist/gene/commit-types.js +3 -0
  62. package/dist/gene/curator/agent.d.ts +137 -0
  63. package/dist/gene/curator/agent.js +203 -0
  64. package/dist/gene/curator/budget.d.ts +69 -0
  65. package/dist/gene/curator/budget.js +131 -0
  66. package/dist/gene/curator/conflicts.d.ts +54 -0
  67. package/dist/gene/curator/conflicts.js +143 -0
  68. package/dist/gene/curator/curator.d.ts +170 -0
  69. package/dist/gene/curator/curator.js +617 -0
  70. package/dist/gene/curator/deps.d.ts +34 -0
  71. package/dist/gene/curator/deps.js +48 -0
  72. package/dist/gene/curator/deterministic.d.ts +62 -0
  73. package/dist/gene/curator/deterministic.js +287 -0
  74. package/dist/gene/curator/executors.d.ts +36 -0
  75. package/dist/gene/curator/executors.js +379 -0
  76. package/dist/gene/curator/lanes.d.ts +52 -0
  77. package/dist/gene/curator/lanes.js +99 -0
  78. package/dist/gene/curator/lease.d.ts +76 -0
  79. package/dist/gene/curator/lease.js +171 -0
  80. package/dist/gene/curator/library.d.ts +36 -0
  81. package/dist/gene/curator/library.js +169 -0
  82. package/dist/gene/curator/lifecycle.d.ts +52 -0
  83. package/dist/gene/curator/lifecycle.js +109 -0
  84. package/dist/gene/curator/maintenance.d.ts +71 -0
  85. package/dist/gene/curator/maintenance.js +213 -0
  86. package/dist/gene/curator/probation.d.ts +51 -0
  87. package/dist/gene/curator/probation.js +71 -0
  88. package/dist/gene/curator/probe.d.ts +131 -0
  89. package/dist/gene/curator/probe.js +534 -0
  90. package/dist/gene/curator/prompt.d.ts +18 -0
  91. package/dist/gene/curator/prompt.js +128 -0
  92. package/dist/gene/curator/publish.d.ts +64 -0
  93. package/dist/gene/curator/publish.js +113 -0
  94. package/dist/gene/curator/recheck.d.ts +55 -0
  95. package/dist/gene/curator/recheck.js +104 -0
  96. package/dist/gene/curator/run-events.d.ts +63 -0
  97. package/dist/gene/curator/run-events.js +55 -0
  98. package/dist/gene/curator/similarity.d.ts +13 -0
  99. package/dist/gene/curator/similarity.js +46 -0
  100. package/dist/gene/curator/switches.d.ts +78 -0
  101. package/dist/gene/curator/switches.js +146 -0
  102. package/dist/gene/curator/task-context.d.ts +93 -0
  103. package/dist/gene/curator/task-context.js +63 -0
  104. package/dist/gene/curator/task-runner.d.ts +56 -0
  105. package/dist/gene/curator/task-runner.js +257 -0
  106. package/dist/gene/curator/tool-support.d.ts +112 -0
  107. package/dist/gene/curator/tool-support.js +206 -0
  108. package/dist/gene/curator/toolkit.d.ts +49 -0
  109. package/dist/gene/curator/toolkit.js +104 -0
  110. package/dist/gene/curator/tools-read.d.ts +4 -0
  111. package/dist/gene/curator/tools-read.js +177 -0
  112. package/dist/gene/curator/tools-release.d.ts +73 -0
  113. package/dist/gene/curator/tools-release.js +287 -0
  114. package/dist/gene/curator/tools-verify.d.ts +47 -0
  115. package/dist/gene/curator/tools-verify.js +243 -0
  116. package/dist/gene/curator/tools-write.d.ts +26 -0
  117. package/dist/gene/curator/tools-write.js +434 -0
  118. package/dist/gene/curator/tools.d.ts +23 -0
  119. package/dist/gene/curator/tools.js +21 -0
  120. package/dist/gene/curator/validate/common.d.ts +87 -0
  121. package/dist/gene/curator/validate/common.js +132 -0
  122. package/dist/gene/curator/validate/evidence-tokens.d.ts +24 -0
  123. package/dist/gene/curator/validate/evidence-tokens.js +217 -0
  124. package/dist/gene/curator/validate/index.d.ts +23 -0
  125. package/dist/gene/curator/validate/index.js +62 -0
  126. package/dist/gene/curator/validate/knowledge.d.ts +41 -0
  127. package/dist/gene/curator/validate/knowledge.js +255 -0
  128. package/dist/gene/curator/validate/live-check.d.ts +14 -0
  129. package/dist/gene/curator/validate/live-check.js +150 -0
  130. package/dist/gene/curator/validate/ports.d.ts +67 -0
  131. package/dist/gene/curator/validate/ports.js +1 -0
  132. package/dist/gene/curator/validate/prompts.d.ts +41 -0
  133. package/dist/gene/curator/validate/prompts.js +165 -0
  134. package/dist/gene/curator/validate/skill.d.ts +15 -0
  135. package/dist/gene/curator/validate/skill.js +251 -0
  136. package/dist/gene/curator/validate/tool.d.ts +6 -0
  137. package/dist/gene/curator/validate/tool.js +217 -0
  138. package/dist/gene/curator/validate/types.d.ts +90 -0
  139. package/dist/gene/curator/validate/types.js +1 -0
  140. package/dist/gene/curator/validator-ports.d.ts +38 -0
  141. package/dist/gene/curator/validator-ports.js +29 -0
  142. package/dist/gene/diag.d.ts +209 -0
  143. package/dist/gene/diag.js +549 -0
  144. package/dist/gene/env.d.ts +10 -0
  145. package/dist/gene/env.js +214 -0
  146. package/dist/gene/eval-recorder.d.ts +84 -0
  147. package/dist/gene/eval-recorder.js +222 -0
  148. package/dist/gene/explain-transport.d.ts +3 -0
  149. package/dist/gene/explain-transport.js +39 -0
  150. package/dist/gene/explain.d.ts +96 -0
  151. package/dist/gene/explain.js +293 -0
  152. package/dist/gene/fs.d.ts +39 -0
  153. package/dist/gene/fs.js +139 -0
  154. package/dist/gene/fsck.d.ts +68 -0
  155. package/dist/gene/fsck.js +134 -0
  156. package/dist/gene/gc-library-sweeps.d.ts +9 -0
  157. package/dist/gene/gc-library-sweeps.js +220 -0
  158. package/dist/gene/gc-rejected-set.d.ts +15 -0
  159. package/dist/gene/gc-rejected-set.js +63 -0
  160. package/dist/gene/gc-safe.d.ts +12 -0
  161. package/dist/gene/gc-safe.js +74 -0
  162. package/dist/gene/gc-scope-sweeps.d.ts +18 -0
  163. package/dist/gene/gc-scope-sweeps.js +297 -0
  164. package/dist/gene/gc-types.d.ts +55 -0
  165. package/dist/gene/gc-types.js +26 -0
  166. package/dist/gene/gc.d.ts +42 -0
  167. package/dist/gene/gc.js +129 -0
  168. package/dist/gene/gene-errors.d.ts +23 -0
  169. package/dist/gene/gene-errors.js +29 -0
  170. package/dist/gene/hints.d.ts +91 -0
  171. package/dist/gene/hints.js +394 -0
  172. package/dist/gene/hub.d.ts +149 -0
  173. package/dist/gene/hub.js +371 -0
  174. package/dist/gene/import-plan.d.ts +80 -0
  175. package/dist/gene/import-plan.js +294 -0
  176. package/dist/gene/import-proposal.d.ts +23 -0
  177. package/dist/gene/import-proposal.js +101 -0
  178. package/dist/gene/import-skill-port.d.ts +6 -0
  179. package/dist/gene/import-skill-port.js +53 -0
  180. package/dist/gene/import-sources.d.ts +48 -0
  181. package/dist/gene/import-sources.js +140 -0
  182. package/dist/gene/index-writer.d.ts +36 -0
  183. package/dist/gene/index-writer.js +101 -0
  184. package/dist/gene/learn/learn-call.d.ts +116 -0
  185. package/dist/gene/learn/learn-call.js +165 -0
  186. package/dist/gene/learn/learn-prompt.d.ts +58 -0
  187. package/dist/gene/learn/learn-prompt.js +254 -0
  188. package/dist/gene/learn/learner.d.ts +187 -0
  189. package/dist/gene/learn/learner.js +448 -0
  190. package/dist/gene/learn/ledger.d.ts +220 -0
  191. package/dist/gene/learn/ledger.js +394 -0
  192. package/dist/gene/learn/proposal-build.d.ts +83 -0
  193. package/dist/gene/learn/proposal-build.js +207 -0
  194. package/dist/gene/learn/proposal-guard.d.ts +43 -0
  195. package/dist/gene/learn/proposal-guard.js +37 -0
  196. package/dist/gene/learn/signals-port.d.ts +47 -0
  197. package/dist/gene/learn/signals-port.js +86 -0
  198. package/dist/gene/maintenance-paths.d.ts +7 -0
  199. package/dist/gene/maintenance-paths.js +20 -0
  200. package/dist/gene/maintenance-probation.d.ts +33 -0
  201. package/dist/gene/maintenance-probation.js +127 -0
  202. package/dist/gene/maintenance-proposals.d.ts +24 -0
  203. package/dist/gene/maintenance-proposals.js +68 -0
  204. package/dist/gene/maintenance-runner.d.ts +92 -0
  205. package/dist/gene/maintenance-runner.js +262 -0
  206. package/dist/gene/maintenance-tasks.d.ts +37 -0
  207. package/dist/gene/maintenance-tasks.js +95 -0
  208. package/dist/gene/manager-actions.d.ts +12 -0
  209. package/dist/gene/manager-actions.js +279 -0
  210. package/dist/gene/manager-approve.d.ts +29 -0
  211. package/dist/gene/manager-approve.js +84 -0
  212. package/dist/gene/manager-context.d.ts +90 -0
  213. package/dist/gene/manager-context.js +201 -0
  214. package/dist/gene/manager-detail.d.ts +17 -0
  215. package/dist/gene/manager-detail.js +313 -0
  216. package/dist/gene/manager-gc.d.ts +13 -0
  217. package/dist/gene/manager-gc.js +81 -0
  218. package/dist/gene/manager-library.d.ts +39 -0
  219. package/dist/gene/manager-library.js +90 -0
  220. package/dist/gene/manager-list.d.ts +27 -0
  221. package/dist/gene/manager-list.js +170 -0
  222. package/dist/gene/manager-queue.d.ts +16 -0
  223. package/dist/gene/manager-queue.js +124 -0
  224. package/dist/gene/manager-stats.d.ts +28 -0
  225. package/dist/gene/manager-stats.js +53 -0
  226. package/dist/gene/manager-view.d.ts +27 -0
  227. package/dist/gene/manager-view.js +124 -0
  228. package/dist/gene/manager.d.ts +56 -0
  229. package/dist/gene/manager.js +179 -0
  230. package/dist/gene/orphan-scopes.d.ts +37 -0
  231. package/dist/gene/orphan-scopes.js +150 -0
  232. package/dist/gene/paths.d.ts +73 -0
  233. package/dist/gene/paths.js +239 -0
  234. package/dist/gene/plan-content.d.ts +73 -0
  235. package/dist/gene/plan-content.js +522 -0
  236. package/dist/gene/plan-lifecycle.d.ts +29 -0
  237. package/dist/gene/plan-lifecycle.js +310 -0
  238. package/dist/gene/policy.d.ts +71 -0
  239. package/dist/gene/policy.js +313 -0
  240. package/dist/gene/project-learning.d.ts +25 -0
  241. package/dist/gene/project-learning.js +54 -0
  242. package/dist/gene/propagation.d.ts +48 -0
  243. package/dist/gene/propagation.js +45 -0
  244. package/dist/gene/queue-lock.d.ts +22 -0
  245. package/dist/gene/queue-lock.js +99 -0
  246. package/dist/gene/queue-record.d.ts +57 -0
  247. package/dist/gene/queue-record.js +145 -0
  248. package/dist/gene/queue.d.ts +235 -0
  249. package/dist/gene/queue.js +764 -0
  250. package/dist/gene/read.d.ts +61 -0
  251. package/dist/gene/read.js +252 -0
  252. package/dist/gene/runlog.d.ts +101 -0
  253. package/dist/gene/runlog.js +404 -0
  254. package/dist/gene/schema-lite.d.ts +24 -0
  255. package/dist/gene/schema-lite.js +159 -0
  256. package/dist/gene/scope-guard.d.ts +23 -0
  257. package/dist/gene/scope-guard.js +9 -0
  258. package/dist/gene/scope-lock.d.ts +48 -0
  259. package/dist/gene/scope-lock.js +222 -0
  260. package/dist/gene/scope-verify.d.ts +63 -0
  261. package/dist/gene/scope-verify.js +123 -0
  262. package/dist/gene/secrets.d.ts +43 -0
  263. package/dist/gene/secrets.js +161 -0
  264. package/dist/gene/service-context.d.ts +43 -0
  265. package/dist/gene/service-context.js +79 -0
  266. package/dist/gene/service-prepare.d.ts +25 -0
  267. package/dist/gene/service-prepare.js +219 -0
  268. package/dist/gene/service-types.d.ts +196 -0
  269. package/dist/gene/service-types.js +1 -0
  270. package/dist/gene/service-view.d.ts +41 -0
  271. package/dist/gene/service-view.js +69 -0
  272. package/dist/gene/service.d.ts +114 -0
  273. package/dist/gene/service.js +761 -0
  274. package/dist/gene/session-start.d.ts +36 -0
  275. package/dist/gene/session-start.js +212 -0
  276. package/dist/gene/store-port.d.ts +88 -0
  277. package/dist/gene/store-port.js +10 -0
  278. package/dist/gene/store-rows.d.ts +36 -0
  279. package/dist/gene/store-rows.js +72 -0
  280. package/dist/gene/store.d.ts +125 -0
  281. package/dist/gene/store.js +622 -0
  282. package/dist/gene/tombstones.d.ts +47 -0
  283. package/dist/gene/tombstones.js +61 -0
  284. package/dist/gene/tool-runner.d.ts +47 -0
  285. package/dist/gene/tool-runner.js +154 -0
  286. package/dist/gene/tool-screen.d.ts +41 -0
  287. package/dist/gene/tool-screen.js +227 -0
  288. package/dist/gene/tools.d.ts +112 -0
  289. package/dist/gene/tools.js +539 -0
  290. package/dist/gene/transfer.d.ts +85 -0
  291. package/dist/gene/transfer.js +433 -0
  292. package/dist/gene/ui-hints.d.ts +15 -0
  293. package/dist/gene/ui-hints.js +67 -0
  294. package/dist/gene/usage-fold-cursor.d.ts +24 -0
  295. package/dist/gene/usage-fold-cursor.js +115 -0
  296. package/dist/gene/usage-fold.d.ts +49 -0
  297. package/dist/gene/usage-fold.js +397 -0
  298. package/dist/gene/usage.d.ts +67 -0
  299. package/dist/gene/usage.js +231 -0
  300. package/dist/gene/version-service.d.ts +118 -0
  301. package/dist/gene/version-service.js +453 -0
  302. package/dist/gene/wiring-events.d.ts +43 -0
  303. package/dist/gene/wiring-events.js +113 -0
  304. package/dist/gene/wiring-models.d.ts +46 -0
  305. package/dist/gene/wiring-models.js +84 -0
  306. package/dist/gene/wiring.d.ts +200 -0
  307. package/dist/gene/wiring.js +764 -0
  308. package/dist/governance/prompts/orchestrator-block.js +3 -2
  309. package/dist/host/gene.d.ts +26 -0
  310. package/dist/host/gene.js +24 -0
  311. package/dist/host/index.d.ts +1 -0
  312. package/dist/host/index.js +1 -0
  313. package/dist/team/runtime.d.ts +5 -0
  314. package/dist/team/runtime.js +23 -0
  315. package/dist/team/subagent.d.ts +34 -0
  316. package/dist/team/subagent.js +39 -2
  317. package/dist/tools/index.d.ts +36 -2
  318. package/dist/tools/index.js +48 -7
  319. package/package.json +3 -3
@@ -0,0 +1,214 @@
1
+ /**
2
+ * Environment fingerprint and the bounded file probe (gene-bank spec 6.4, X-5, 8.2 step 4).
3
+ *
4
+ * ASCII ONLY - the whole `gene/` tree is in `glyphs.test.ts::inScope`.
5
+ *
6
+ * `captureEnvFingerprint` runs at session start and on a `/cwd` change. It is SYNCHRONOUS and
7
+ * BOUNDED (at most ~20 `stat`s and one read of at most 2 MB) because it sits on the path to
8
+ * the first prompt, and it NEVER THROWS: a field that cannot be determined is left out. The
9
+ * fingerprint is what turns "this gene says npm" into "this repository has a
10
+ * package-lock.json today" - environment constraints are the knowledge that goes stale first.
11
+ *
12
+ * `makeGlobMatcher` answers `applicability.fileGlobs` ("at least one must match under the
13
+ * cwd"). The walk is capped at 200 entries per query, so a gene can never make retrieval
14
+ * traverse a monorepo; hitting the cap answers `false` (not applicable), the conservative
15
+ * direction for a filter whose job is to avoid showing the wrong advice.
16
+ */
17
+ import { createHash } from 'node:crypto';
18
+ import { existsSync, readFileSync, readdirSync, realpathSync, statSync } from 'node:fs';
19
+ import { dirname, join } from 'node:path';
20
+ import process from 'node:process';
21
+ import { describeShell } from '../agent/system-prompt.js';
22
+ const LOCKFILES = [
23
+ 'package-lock.json',
24
+ 'pnpm-lock.yaml',
25
+ 'yarn.lock',
26
+ 'bun.lockb',
27
+ 'Cargo.lock',
28
+ 'poetry.lock',
29
+ 'Pipfile.lock',
30
+ 'uv.lock',
31
+ 'go.sum',
32
+ 'Gemfile.lock',
33
+ 'composer.lock',
34
+ ];
35
+ const KIND_MARKERS = [
36
+ ['package.json', 'node'],
37
+ ['pyproject.toml', 'python'],
38
+ ['requirements.txt', 'python'],
39
+ ['Cargo.toml', 'rust'],
40
+ ['go.mod', 'go'],
41
+ ['pom.xml', 'java'],
42
+ ['build.gradle', 'java'],
43
+ ['build.gradle.kts', 'java'],
44
+ ['Gemfile', 'ruby'],
45
+ ['composer.json', 'php'],
46
+ ];
47
+ const LOCKFILE_HASH_MAX_BYTES = 2 * 1024 * 1024;
48
+ const GIT_SEARCH_DEPTH = 40;
49
+ const GLOB_ENTRY_CAP = 200;
50
+ function normalisedShell() {
51
+ const { shell } = describeShell();
52
+ const s = shell.toLowerCase();
53
+ if (s.includes('powershell') || s.includes('pwsh'))
54
+ return 'powershell';
55
+ if (s.includes('cmd'))
56
+ return 'cmd';
57
+ if (s.endsWith('zsh'))
58
+ return 'zsh';
59
+ if (s.endsWith('bash') || s.endsWith('/sh') || s === 'sh')
60
+ return 'bash';
61
+ return 'other';
62
+ }
63
+ function platformOs() {
64
+ const p = process.platform;
65
+ return p === 'win32' || p === 'darwin' ? p : 'linux';
66
+ }
67
+ function findGitRoot(start) {
68
+ let dir = start;
69
+ for (let i = 0; i < GIT_SEARCH_DEPTH; i += 1) {
70
+ if (existsSync(join(dir, '.git')))
71
+ return dir;
72
+ const parent = dirname(dir);
73
+ if (parent === dir)
74
+ return null;
75
+ dir = parent;
76
+ }
77
+ return null;
78
+ }
79
+ function detectKinds(cwd) {
80
+ const kinds = new Set();
81
+ for (const [file, kind] of KIND_MARKERS) {
82
+ if (existsSync(join(cwd, file)))
83
+ kinds.add(kind);
84
+ }
85
+ try {
86
+ for (const name of readdirSync(cwd).slice(0, 400)) {
87
+ if (name.endsWith('.csproj') || name.endsWith('.sln'))
88
+ kinds.add('dotnet');
89
+ }
90
+ }
91
+ catch {
92
+ /* an unreadable directory simply contributes nothing */
93
+ }
94
+ return [...kinds].sort();
95
+ }
96
+ function hashLockfile(path) {
97
+ try {
98
+ const stat = statSync(path);
99
+ if (stat.size <= LOCKFILE_HASH_MAX_BYTES) {
100
+ return createHash('sha1').update(readFileSync(path)).digest('hex').slice(0, 12);
101
+ }
102
+ return `s${stat.size}m${Math.floor(stat.mtimeMs)}`;
103
+ }
104
+ catch {
105
+ return undefined;
106
+ }
107
+ }
108
+ /** Never throws; unknown fields are omitted. */
109
+ export function captureEnvFingerprint(cwd) {
110
+ const fp = {
111
+ os: platformOs(),
112
+ arch: process.arch,
113
+ nodeMajor: Number.parseInt(process.versions.node.split('.')[0] ?? '0', 10) || 0,
114
+ shell: normalisedShell(),
115
+ projectKinds: [],
116
+ };
117
+ try {
118
+ fp.projectKinds = detectKinds(cwd);
119
+ for (const name of LOCKFILES) {
120
+ const path = join(cwd, name);
121
+ if (existsSync(path)) {
122
+ fp.lockfile = name;
123
+ const hash = hashLockfile(path);
124
+ if (hash)
125
+ fp.lockfileHash = hash;
126
+ break;
127
+ }
128
+ }
129
+ const real = realpathSync.native(cwd);
130
+ const git = findGitRoot(real);
131
+ if (git) {
132
+ fp.gitRootHash = createHash('sha1').update(git.replace(/\\/g, '/').toLowerCase()).digest('hex').slice(0, 12);
133
+ }
134
+ }
135
+ catch {
136
+ /* the fingerprint is advisory; a half-filled one is still useful */
137
+ }
138
+ return fp;
139
+ }
140
+ /** Translate a simple glob to a RegExp over forward-slash relative paths. */
141
+ function globToRegExp(glob) {
142
+ let re = '';
143
+ for (let i = 0; i < glob.length; i += 1) {
144
+ const ch = glob[i];
145
+ if (ch === '*') {
146
+ if (glob[i + 1] === '*') {
147
+ i += 1;
148
+ if (glob[i + 1] === '/') {
149
+ i += 1;
150
+ re += '(?:.*/)?';
151
+ }
152
+ else {
153
+ re += '.*';
154
+ }
155
+ }
156
+ else {
157
+ re += '[^/]*';
158
+ }
159
+ }
160
+ else if (ch === '?') {
161
+ re += '[^/]';
162
+ }
163
+ else {
164
+ re += ch.replace(/[.+^${}()|[\]\\]/g, '\\$&');
165
+ }
166
+ }
167
+ return new RegExp(`^${re}$`, 'i');
168
+ }
169
+ const SKIP_DIRS = new Set(['node_modules', '.git', 'dist', 'build', 'target', '.next', '.venv', '__pycache__']);
170
+ /**
171
+ * `(glob) => boolean`: does anything under `cwd` match? Walks breadth-first, capped at
172
+ * `GLOB_ENTRY_CAP` entries per call, skipping dependency and build directories.
173
+ */
174
+ export function makeGlobMatcher(cwd) {
175
+ return (glob) => {
176
+ if (typeof glob !== 'string' || glob.length === 0 || glob.length > 200 || glob.includes('..'))
177
+ return false;
178
+ const re = globToRegExp(glob.replace(/\\/g, '/'));
179
+ const queue = [''];
180
+ let seen = 0;
181
+ while (queue.length > 0 && seen < GLOB_ENTRY_CAP) {
182
+ const rel = queue.shift();
183
+ let entries;
184
+ try {
185
+ entries = readdirSync(join(cwd, rel), { withFileTypes: true });
186
+ }
187
+ catch {
188
+ continue;
189
+ }
190
+ for (const entry of entries) {
191
+ seen += 1;
192
+ if (seen > GLOB_ENTRY_CAP)
193
+ break;
194
+ const next = rel === '' ? entry.name : `${rel}/${entry.name}`;
195
+ if (re.test(next))
196
+ return true;
197
+ if (entry.isDirectory() && !SKIP_DIRS.has(entry.name))
198
+ queue.push(next);
199
+ }
200
+ }
201
+ return false;
202
+ };
203
+ }
204
+ /** Do two fingerprints differ in a field a gene may have pinned via `envStamp`? */
205
+ export function envStampMismatches(stamp, current) {
206
+ const bad = [];
207
+ for (const [key, want] of Object.entries(stamp)) {
208
+ const have = current[key];
209
+ const haveText = Array.isArray(have) ? have.join(',') : have === undefined ? '' : String(have);
210
+ if (haveText !== want)
211
+ bad.push(key);
212
+ }
213
+ return bad;
214
+ }
@@ -0,0 +1,84 @@
1
+ /**
2
+ * `GeneEvalRecorder`: one row per user-visible run, for the stats page (gene-bank spec 13,
3
+ * G-26, I-19).
4
+ *
5
+ * ASCII ONLY - the whole `gene/` tree is in `glyphs.test.ts::inScope`.
6
+ *
7
+ * COUNTS, SIGNATURES AND COST - NEVER TEXT (I-19). `GeneRunEval` has no field a sentence could
8
+ * go in, and `record` rebuilds the row from an allow-list rather than spreading its input, so
9
+ * an extra property a caller attached never reaches the file. Identifiers are reduced to a
10
+ * path-safe alphabet and error signatures must be the 16-hex output of `errorSignature`.
11
+ *
12
+ * UNKNOWN PRICE IS NOT ZERO PRICE (13.3). A component that spent tokens at an unknown price
13
+ * records `usd: null`, not `0`; `summarize` then reports the total as a lower bound. A component
14
+ * that spent nothing records `usd: 0` - nothing was spent, and that IS known.
15
+ *
16
+ * WRITES NEVER THROW. A run that cannot be recorded is simply not in the statistics; it must
17
+ * not be able to fail the turn that produced it (I-24).
18
+ */
19
+ import type { GeneCostComponent, GeneRunEval } from '@aragon-agent/tui/model/gene/types';
20
+ import { type GenePathContext } from './paths.js';
21
+ export declare const COST_COMPONENTS: readonly GeneCostComponent[];
22
+ export declare const ERROR_SIGS_MAX = 10;
23
+ export type EvalCost = GeneRunEval['cost'];
24
+ export interface UsageSample {
25
+ inTok: number;
26
+ outTok: number;
27
+ /** null / undefined = the model has no known price. */
28
+ usd?: number | null;
29
+ }
30
+ /**
31
+ * Accumulates one run's spend per component. The controller feeds it the session usage deltas
32
+ * (`main`) and the receipts of the other four, then hands `snapshot()` to the recorder.
33
+ */
34
+ export declare class CostMeter {
35
+ private parts;
36
+ private static fresh;
37
+ add(component: GeneCostComponent, sample: UsageSample): void;
38
+ snapshot(): EvalCost;
39
+ reset(): void;
40
+ }
41
+ /** What the controller supplies at `agent_end`; the recorder stamps `schema` and `t`. */
42
+ export interface EvalRunInput {
43
+ run: string;
44
+ session: string;
45
+ projectKey?: string;
46
+ mode: GeneRunEval['mode'];
47
+ outcome: GeneRunEval['outcome'];
48
+ durationMs: number;
49
+ turns: number;
50
+ toolCalls: number;
51
+ toolErrors: number;
52
+ retries: number;
53
+ userCorrections: number;
54
+ errorSigs: readonly string[];
55
+ genes: GeneRunEval['genes'];
56
+ flags: GeneRunEval['flags'];
57
+ cost: EvalCost;
58
+ }
59
+ export interface EvalRecorderDeps {
60
+ ctx?: Pick<GenePathContext, 'root'>;
61
+ now: () => number;
62
+ onError?: (error: unknown) => void;
63
+ }
64
+ /** Keep only well-formed signatures, once each, up to the cap. */
65
+ export declare function cleanErrorSigs(sigs: readonly unknown[]): string[];
66
+ /** Rebuild a row from the allow-list; the input's extra properties are dropped on the floor. */
67
+ export declare function normalizeEvalRun(input: EvalRunInput, t: number): GeneRunEval;
68
+ export declare class GeneEvalRecorder {
69
+ private readonly deps;
70
+ private readonly ctx;
71
+ constructor(deps: EvalRecorderDeps);
72
+ /** Append the run's row to `eval/<yyyy-mm>.jsonl`. Returns the row, or null if it was lost. */
73
+ record(input: EvalRunInput): Promise<GeneRunEval | null>;
74
+ /**
75
+ * Every row with `t >= sinceMs`, oldest first. Torn or hand-edited lines are skipped. Pass a
76
+ * `sinceMs` 30 days before the window you report on, so `summarize` can see recurrences that
77
+ * straddle the window's start (13.4).
78
+ */
79
+ readSince(sinceMs: number): Promise<GeneRunEval[]>;
80
+ /** Convenience for the stats page: the last `days` days. */
81
+ readWindow(days: number | null): Promise<GeneRunEval[]>;
82
+ /** Drop month files older than `evalKeepMonths` (12). Returns how many went. */
83
+ prune(): Promise<number>;
84
+ }
@@ -0,0 +1,222 @@
1
+ import { GENE_LIMITS } from '@aragon-agent/tui/model/gene/limits';
2
+ import { evalDir, evalFile, geneRoot, monthStamp } from './paths.js';
3
+ import { appendJsonl, listDir, readJsonlFrom, removeInside } from './fs.js';
4
+ export const COST_COMPONENTS = [
5
+ 'main',
6
+ 'reviewer',
7
+ 'curator',
8
+ 'retrieval',
9
+ 'validation',
10
+ ];
11
+ /** Recorded only when something was spent: older rows and quiet runs do not carry it. */
12
+ const OPTIONAL_COST_COMPONENTS = ['explain'];
13
+ export const ERROR_SIGS_MAX = 10;
14
+ const EVAL_FILE_RE = /^(\d{4}-\d{2})\.jsonl$/;
15
+ const MAX_READ_BYTES = 32 * 1024 * 1024;
16
+ const ID_MAX = 80;
17
+ function count(value) {
18
+ return typeof value === 'number' && Number.isFinite(value) && value > 0 ? Math.trunc(value) : 0;
19
+ }
20
+ /**
21
+ * Accumulates one run's spend per component. The controller feeds it the session usage deltas
22
+ * (`main`) and the receipts of the other four, then hands `snapshot()` to the recorder.
23
+ */
24
+ export class CostMeter {
25
+ parts = CostMeter.fresh();
26
+ static fresh() {
27
+ const make = () => ({ inTok: 0, outTok: 0, usd: 0, unpriced: false });
28
+ return {
29
+ main: make(),
30
+ reviewer: make(),
31
+ curator: make(),
32
+ retrieval: make(),
33
+ validation: make(),
34
+ explain: make(),
35
+ };
36
+ }
37
+ add(component, sample) {
38
+ const part = this.parts[component];
39
+ const inTok = count(sample.inTok);
40
+ const outTok = count(sample.outTok);
41
+ part.inTok += inTok;
42
+ part.outTok += outTok;
43
+ const priced = typeof sample.usd === 'number' && Number.isFinite(sample.usd) && sample.usd >= 0;
44
+ if (priced)
45
+ part.usd += sample.usd;
46
+ else if (inTok + outTok > 0)
47
+ part.unpriced = true;
48
+ }
49
+ snapshot() {
50
+ const out = {};
51
+ for (const component of COST_COMPONENTS) {
52
+ const part = this.parts[component];
53
+ out[component] = { inTok: part.inTok, outTok: part.outTok, usd: part.unpriced ? null : part.usd };
54
+ }
55
+ for (const component of OPTIONAL_COST_COMPONENTS) {
56
+ const part = this.parts[component];
57
+ if (part.inTok + part.outTok === 0)
58
+ continue;
59
+ out[component] = { inTok: part.inTok, outTok: part.outTok, usd: part.unpriced ? null : part.usd };
60
+ }
61
+ return out;
62
+ }
63
+ reset() {
64
+ this.parts = CostMeter.fresh();
65
+ }
66
+ }
67
+ // ---------------------------------------------------------------------------
68
+ // Normalisation (pure)
69
+ // ---------------------------------------------------------------------------
70
+ function safeId(value) {
71
+ return String(value ?? '')
72
+ .replace(/[^A-Za-z0-9_.-]/g, '_')
73
+ .slice(0, ID_MAX);
74
+ }
75
+ const MODES = ['build', 'plan', 'govern', 'team'];
76
+ const OUTCOMES = ['completed', 'error', 'aborted'];
77
+ /** Keep only well-formed signatures, once each, up to the cap. */
78
+ export function cleanErrorSigs(sigs) {
79
+ const valid = sigs.filter((s) => typeof s === 'string' && /^[0-9a-f]{16}$/.test(s));
80
+ return [...new Set(valid)].slice(0, ERROR_SIGS_MAX);
81
+ }
82
+ function cleanCost(cost) {
83
+ const out = {};
84
+ for (const component of COST_COMPONENTS) {
85
+ const part = cost?.[component];
86
+ const usd = part?.usd;
87
+ out[component] = {
88
+ inTok: count(part?.inTok),
89
+ outTok: count(part?.outTok),
90
+ usd: typeof usd === 'number' && Number.isFinite(usd) && usd >= 0 ? usd : null,
91
+ };
92
+ }
93
+ for (const component of OPTIONAL_COST_COMPONENTS) {
94
+ const part = cost?.[component];
95
+ if (part === undefined || count(part.inTok) + count(part.outTok) === 0)
96
+ continue;
97
+ const usd = part.usd;
98
+ out[component] = {
99
+ inTok: count(part.inTok),
100
+ outTok: count(part.outTok),
101
+ usd: typeof usd === 'number' && Number.isFinite(usd) && usd >= 0 ? usd : null,
102
+ };
103
+ }
104
+ return out;
105
+ }
106
+ /** Rebuild a row from the allow-list; the input's extra properties are dropped on the floor. */
107
+ export function normalizeEvalRun(input, t) {
108
+ const genes = input.genes ?? { shown: 0, read: 0, adopted: 0, helped: 0, harmed: 0 };
109
+ const projectKey = input.projectKey ? safeId(input.projectKey) : '';
110
+ return {
111
+ schema: 1,
112
+ t,
113
+ run: safeId(input.run),
114
+ session: safeId(input.session),
115
+ ...(projectKey ? { projectKey } : {}),
116
+ mode: MODES.includes(input.mode) ? input.mode : 'build',
117
+ outcome: OUTCOMES.includes(input.outcome) ? input.outcome : 'error',
118
+ durationMs: count(input.durationMs),
119
+ turns: count(input.turns),
120
+ toolCalls: count(input.toolCalls),
121
+ toolErrors: count(input.toolErrors),
122
+ retries: count(input.retries),
123
+ userCorrections: count(input.userCorrections),
124
+ errorSigs: cleanErrorSigs(input.errorSigs ?? []),
125
+ genes: {
126
+ shown: count(genes.shown),
127
+ read: count(genes.read),
128
+ adopted: count(genes.adopted),
129
+ helped: count(genes.helped),
130
+ harmed: count(genes.harmed),
131
+ },
132
+ flags: {
133
+ geneUse: input.flags?.geneUse === true,
134
+ learn: input.flags?.learn === true,
135
+ holdout: input.flags?.holdout === true,
136
+ },
137
+ cost: cleanCost(input.cost),
138
+ };
139
+ }
140
+ function isEvalRow(value) {
141
+ if (typeof value !== 'object' || value === null)
142
+ return false;
143
+ const r = value;
144
+ return (r.schema === 1 &&
145
+ typeof r.t === 'number' &&
146
+ Number.isFinite(r.t) &&
147
+ typeof r.outcome === 'string' &&
148
+ OUTCOMES.includes(r.outcome) &&
149
+ typeof r.durationMs === 'number');
150
+ }
151
+ /** `yyyy-mm` minus `months`, as a plain string comparison key. */
152
+ function monthsBefore(stamp, months) {
153
+ const [year, month] = stamp.split('-').map(Number);
154
+ const index = year * 12 + (month - 1) - months;
155
+ const y = Math.floor(index / 12);
156
+ const m = (index % 12) + 1;
157
+ return `${String(y).padStart(4, '0')}-${String(m).padStart(2, '0')}`;
158
+ }
159
+ // ---------------------------------------------------------------------------
160
+ // The recorder
161
+ // ---------------------------------------------------------------------------
162
+ export class GeneEvalRecorder {
163
+ deps;
164
+ ctx;
165
+ constructor(deps) {
166
+ this.deps = deps;
167
+ this.ctx = deps.ctx ?? {};
168
+ }
169
+ /** Append the run's row to `eval/<yyyy-mm>.jsonl`. Returns the row, or null if it was lost. */
170
+ async record(input) {
171
+ try {
172
+ const t = this.deps.now();
173
+ const path = evalFile(monthStamp(t), this.ctx);
174
+ if (path === null)
175
+ return null;
176
+ const row = normalizeEvalRun(input, t);
177
+ await appendJsonl(path, row);
178
+ return row;
179
+ }
180
+ catch (error) {
181
+ this.deps.onError?.(error);
182
+ return null;
183
+ }
184
+ }
185
+ /**
186
+ * Every row with `t >= sinceMs`, oldest first. Torn or hand-edited lines are skipped. Pass a
187
+ * `sinceMs` 30 days before the window you report on, so `summarize` can see recurrences that
188
+ * straddle the window's start (13.4).
189
+ */
190
+ async readSince(sinceMs) {
191
+ const first = monthStamp(Math.max(0, sinceMs));
192
+ const rows = [];
193
+ for (const name of (await listDir(evalDir(this.ctx))).sort()) {
194
+ const month = EVAL_FILE_RE.exec(name)?.[1];
195
+ const path = month === undefined || month < first ? null : evalFile(month, this.ctx);
196
+ if (path === null)
197
+ continue;
198
+ const read = await readJsonlFrom(path, 0, MAX_READ_BYTES);
199
+ for (const row of read.rows) {
200
+ if (isEvalRow(row) && row.t >= sinceMs)
201
+ rows.push(row);
202
+ }
203
+ }
204
+ return rows.sort((a, b) => a.t - b.t);
205
+ }
206
+ /** Convenience for the stats page: the last `days` days. */
207
+ readWindow(days) {
208
+ return this.readSince(days === null ? 0 : this.deps.now() - days * 24 * 60 * 60 * 1000);
209
+ }
210
+ /** Drop month files older than `evalKeepMonths` (12). Returns how many went. */
211
+ async prune() {
212
+ const cutoff = monthsBefore(monthStamp(this.deps.now()), GENE_LIMITS.evalKeepMonths);
213
+ let removed = 0;
214
+ for (const name of await listDir(evalDir(this.ctx))) {
215
+ const month = EVAL_FILE_RE.exec(name)?.[1];
216
+ const path = month !== undefined && month < cutoff ? evalFile(month, this.ctx) : null;
217
+ if (path !== null && (await removeInside(geneRoot(this.ctx), path)))
218
+ removed += 1;
219
+ }
220
+ return removed;
221
+ }
222
+ }
@@ -0,0 +1,3 @@
1
+ import type { ExplainTransport } from './explain.js';
2
+ /** A transport over the persisted configuration; `provider()` is null until a fast tier works. */
3
+ export declare function createStandaloneExplainTransport(): ExplainTransport;
@@ -0,0 +1,39 @@
1
+ import { resolveFastTier } from '@aragon-agent/tui/model/fast/resolve';
2
+ import { loadConfig, makeGetApiKey } from '../config/load.js';
3
+ import { createFailFastRegistry, createLearnComplete, } from './wiring-models.js';
4
+ function portsOf(config) {
5
+ const main = { providerId: config.provider, modelId: config.model };
6
+ return {
7
+ fastTier: () => resolveFastTier(config, (id, role) => !!makeGetApiKey(config, role)(id)),
8
+ mainModel: () => main,
9
+ getApiKey: (providerId, role) => makeGetApiKey(config, role)(providerId),
10
+ };
11
+ }
12
+ function readConfig() {
13
+ try {
14
+ return loadConfig({}, { quiet: true });
15
+ }
16
+ catch {
17
+ return null;
18
+ }
19
+ }
20
+ /** A transport over the persisted configuration; `provider()` is null until a fast tier works. */
21
+ export function createStandaloneExplainTransport() {
22
+ const registry = createFailFastRegistry();
23
+ return {
24
+ provider() {
25
+ const config = readConfig();
26
+ if (config === null)
27
+ return null;
28
+ const tier = portsOf(config).fastTier();
29
+ return tier.ok ? tier.ref.providerId : null;
30
+ },
31
+ complete(request) {
32
+ const config = readConfig();
33
+ if (config === null)
34
+ throw new Error('configuration unavailable');
35
+ const ports = portsOf(config);
36
+ return createLearnComplete({ slot: () => 'fast', ports, registry })(request);
37
+ },
38
+ };
39
+ }
@@ -0,0 +1,96 @@
1
+ import type { GeneExplainRequest, GeneExplainView } from '@aragon-agent/tui/model/gene/port';
2
+ import type { GeneContent, GeneResult } from '@aragon-agent/tui/model/gene/types';
3
+ import type { LearnComplete } from './learn/learn-call.js';
4
+ import { type ManagerCore } from './manager-context.js';
5
+ export declare const EXPLAIN: {
6
+ readonly timeoutMs: 20000;
7
+ readonly debounceMs: 1000;
8
+ readonly minOutputTokens: 300;
9
+ readonly maxOutputTokens: 2400;
10
+ /** Share of the source's identifiers the translation must still contain. */
11
+ readonly fidelityMin: 0.9;
12
+ /** A gene text is clipped here before it is sent (bodies are capped far below this). */
13
+ readonly inputMaxChars: 14000;
14
+ };
15
+ export type ExplainLang = 'zh' | 'en';
16
+ /** The user-facing tokens of `detail` on a refused explanation. */
17
+ export type ExplainDetail = 'explain_no_fast_model' | 'explain_timeout' | 'explain_unfaithful' | 'explain_failed' | 'lang_unsupported' | 'explain_disabled';
18
+ /** Where the model comes from. `provider()` is null while there is no usable fast tier. */
19
+ export interface ExplainTransport {
20
+ provider(): string | null;
21
+ complete: LearnComplete;
22
+ }
23
+ export interface ExplainSpend {
24
+ inTok: number;
25
+ outTok: number;
26
+ usd: number | undefined;
27
+ }
28
+ export interface ExplainDeps {
29
+ transport(): ExplainTransport | null;
30
+ /** The `gene.explainLanguage` setting, read per call. */
31
+ languageSetting(): string;
32
+ /** The terminal's locale string (`LC_ALL` / `LANG`), for `auto`. */
33
+ locale(): string;
34
+ /** Receives the spend of every completed call (it lands in the next evaluation row). */
35
+ onSpend?(spend: ExplainSpend): void;
36
+ /** The deadline of one call; default `EXPLAIN.timeoutMs` (a test seam). */
37
+ timeoutMs?: number;
38
+ now(): number;
39
+ }
40
+ /**
41
+ * `lang` as the engine understands it: `en*` -> `en`, `zh*` -> `zh`, `auto` -> decided by the
42
+ * setting and the locale, anything else -> null (the caller answers `lang_unsupported`; it does
43
+ * not guess a language).
44
+ */
45
+ export declare function normalizeExplainLang(lang: string, setting: string, locale: string): ExplainLang | null;
46
+ /**
47
+ * Can `x` (explain) work in this session? The language must resolve (`auto` follows the locale,
48
+ * `off` never) and a fast model must exist; otherwise the key is hidden rather than left to fail.
49
+ */
50
+ export declare function explainAvailableFor(setting: string, locale: string, fastTierOk: boolean): boolean;
51
+ /** Output budget scales with the input: Chinese runs about 1.3x the token count of the English. */
52
+ export declare function explainMaxTokens(inputChars: number): number;
53
+ /** True when the text holds at least one CJK ideograph. */
54
+ export declare function hasChinese(text: string): boolean;
55
+ /**
56
+ * The identifiers a faithful translation must keep: code spans, path-like words, upper-snake
57
+ * error codes and numbers of two digits or more. The set is deduplicated and bounded.
58
+ */
59
+ export declare function fidelityTokens(source: string): string[];
60
+ export interface Fidelity {
61
+ ok: boolean;
62
+ kept: number;
63
+ total: number;
64
+ }
65
+ /** Does `output` still contain at least `EXPLAIN.fidelityMin` of the source's identifiers? */
66
+ export declare function checkFidelity(source: string, output: string): Fidelity;
67
+ /** Remove a code fence the model wrapped around the whole reply. */
68
+ export declare function stripOuterFence(text: string): string;
69
+ /** The text sent to the model, and the text the fidelity check is run against. */
70
+ export declare function explainSource(content: Pick<GeneContent, 'name' | 'purpose' | 'trigger' | 'body'>): string;
71
+ export declare function buildExplainPrompt(source: string): {
72
+ system: string;
73
+ user: string;
74
+ };
75
+ type ExplainOutcome = GeneResult<GeneExplainView>;
76
+ export declare class GeneExplainService {
77
+ private readonly core;
78
+ private readonly deps;
79
+ private inflight;
80
+ private tail;
81
+ private lastFailure;
82
+ constructor(core: ManagerCore, deps: ExplainDeps);
83
+ /** The explain port. Never rejects. */
84
+ explain(req: GeneExplainRequest & {
85
+ version?: number;
86
+ }): Promise<ExplainOutcome>;
87
+ private enqueue;
88
+ private run;
89
+ private translate;
90
+ private judge;
91
+ private callModel;
92
+ private readCache;
93
+ /** A write failure only means the next click calls the model again. */
94
+ private writeCache;
95
+ }
96
+ export {};