@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,36 @@
1
+ /**
2
+ * Verbatim-token extraction for the K2 source check (gene-bank spec 10.7.1 K2, RV-10).
3
+ *
4
+ * ASCII ONLY - the whole `gene/` tree is in `glyphs.test.ts::inScope`. PURE.
5
+ *
6
+ * THE RULE THIS IMPLEMENTS. Every path, symbol, error code and number that a draft states must
7
+ * appear VERBATIM in the evidence the proposal carried. A model that "tidies" `src\\a.ts` into
8
+ * `src/a.ts` is fine (paths compare with one separator), a model that invents `src/b.ts` or
9
+ * rounds `1.7 s` to `2 s` is not. This is the deterministic backbone of K2: it needs no
10
+ * filesystem and no model, so it runs even when the evidence's project is not on this machine.
11
+ *
12
+ * WHAT IT IS NOT. It does not decide that the draft is TRUE (that is K4's supported-by-evidence
13
+ * question) and it cannot see a fact the model stated in prose without a token. It is a floor:
14
+ * the specifics that are cheap to check mechanically are checked mechanically.
15
+ *
16
+ * NO FAILURE MESSAGE MAY CARRY A TOKEN (I-19). Callers report counts per kind only.
17
+ */
18
+ export type TokenKind = 'path' | 'symbol' | 'error_code' | 'number';
19
+ export interface VerbatimToken {
20
+ kind: TokenKind;
21
+ text: string;
22
+ }
23
+ /** The checkable specifics of `text`, at most 96, in order of first appearance. */
24
+ export declare function extractVerbatimTokens(text: string): VerbatimToken[];
25
+ /** Is `token` present verbatim in the evidence `corpus`? Paths compare with one separator. */
26
+ export declare function tokenAppearsIn(token: VerbatimToken, corpus: string): boolean;
27
+ export interface TokenReport {
28
+ /** How many tokens the drafted texts contained. */
29
+ checked: number;
30
+ /** The tokens the evidence does not contain; callers report only `kind` counts. */
31
+ missing: VerbatimToken[];
32
+ }
33
+ /** Check every token of `drafted` against `corpus` (all evidence texts joined). */
34
+ export declare function findUnsupportedTokens(drafted: readonly string[], corpus: string): TokenReport;
35
+ /** `path x1, number x2` - kinds and counts only, never the token text (I-19). */
36
+ export declare function summarizeMissing(missing: readonly VerbatimToken[]): string;
@@ -0,0 +1,139 @@
1
+ /**
2
+ * Verbatim-token extraction for the K2 source check (gene-bank spec 10.7.1 K2, RV-10).
3
+ *
4
+ * ASCII ONLY - the whole `gene/` tree is in `glyphs.test.ts::inScope`. PURE.
5
+ *
6
+ * THE RULE THIS IMPLEMENTS. Every path, symbol, error code and number that a draft states must
7
+ * appear VERBATIM in the evidence the proposal carried. A model that "tidies" `src\\a.ts` into
8
+ * `src/a.ts` is fine (paths compare with one separator), a model that invents `src/b.ts` or
9
+ * rounds `1.7 s` to `2 s` is not. This is the deterministic backbone of K2: it needs no
10
+ * filesystem and no model, so it runs even when the evidence's project is not on this machine.
11
+ *
12
+ * WHAT IT IS NOT. It does not decide that the draft is TRUE (that is K4's supported-by-evidence
13
+ * question) and it cannot see a fact the model stated in prose without a token. It is a floor:
14
+ * the specifics that are cheap to check mechanically are checked mechanically.
15
+ *
16
+ * NO FAILURE MESSAGE MAY CARRY A TOKEN (I-19). Callers report counts per kind only.
17
+ */
18
+ const MAX_TOKENS = 96;
19
+ const FILE_EXTENSIONS = 'ts|tsx|js|jsx|mjs|cjs|json|md|yml|yaml|toml|lock|py|rs|go|java|cs|sh|ps1|cmd|bat|txt|log|css|' +
20
+ 'html|xml|sql|ini|cfg|conf|env|exe|dll|so|zip|tgz|gz|map|svg|png|csv';
21
+ const FILE_NAME_RE = new RegExp(`^[\\w@+-]+(?:\\.[\\w@+-]+)*\\.(?:${FILE_EXTENSIONS})$`, 'i');
22
+ const URL_RE = /^https?:\/\/\S+$/i;
23
+ const NUMBER_RE = /^\d+(?:[.,]\d+)*(?:ms|s|sec|min|h|kb|mb|gb|%)?$/i;
24
+ const CAMEL_RE = /^[a-z]+(?:[A-Z][a-z0-9]*)+$/;
25
+ const SNAKE_RE = /^[a-z][a-z0-9]*(?:_[a-z0-9]+)+$/;
26
+ const DOTTED_RE = /^[a-z_][a-z0-9_]{1,30}(?:\.[a-z_][a-z0-9_]{1,30})+$/;
27
+ const CALL_RE = /^([A-Za-z_][\w.]{1,40})\(\)?$/;
28
+ const ERRNO_RE = /^E[A-Z]{2,15}$/;
29
+ const UPPER_SNAKE_RE = /^[A-Z][A-Z0-9]*(?:_[A-Z0-9]+)+$/;
30
+ const COMPILER_CODE_RE = /^(?:TS|CS|CE|LNK|E|W)\d{3,5}$/;
31
+ const LIST_MARKER_RE = /^\s*(?:[-*+]|\d+[.)])\s+/;
32
+ const BACKTICK_RE = /`([^`\n]{2,80})`/g;
33
+ function trimWord(word) {
34
+ let out = word.replace(/^[("'[{<]+/, '').replace(/[)"'\]}>,;:!?]+$/, '');
35
+ // A sentence-ending dot is not part of the token; a dot inside a name is.
36
+ while (out.endsWith('.') && out.length > 1)
37
+ out = out.slice(0, -1);
38
+ return out;
39
+ }
40
+ function isNumericOnly(segments) {
41
+ return segments.every((s) => /^\d+$/.test(s));
42
+ }
43
+ /** Does a slash-bearing word look like a path rather than "and/or"? */
44
+ function looksLikePath(word) {
45
+ if (URL_RE.test(word))
46
+ return true;
47
+ if (!/[\\/]/.test(word))
48
+ return false;
49
+ const segments = word.split(/[\\/]/).filter((s) => s.length > 0);
50
+ if (segments.length === 0 || isNumericOnly(segments))
51
+ return false;
52
+ const last = segments[segments.length - 1] ?? '';
53
+ const hasExtension = /\.[A-Za-z0-9]{1,8}$/.test(last);
54
+ const anchored = /^(?:\.{1,2}[\\/]|[\\/]|~[\\/]|[A-Za-z]:[\\/])/.test(word);
55
+ const directory = /[\\/]$/.test(word);
56
+ return hasExtension || anchored || directory || segments.length >= 3;
57
+ }
58
+ function classify(word, quoted) {
59
+ if (looksLikePath(word) || FILE_NAME_RE.test(word))
60
+ return { kind: 'path', text: word };
61
+ if (quoted)
62
+ return { kind: 'symbol', text: word };
63
+ if (ERRNO_RE.test(word) || UPPER_SNAKE_RE.test(word) || COMPILER_CODE_RE.test(word)) {
64
+ return { kind: 'error_code', text: word };
65
+ }
66
+ if (NUMBER_RE.test(word))
67
+ return { kind: 'number', text: word };
68
+ if (CAMEL_RE.test(word) || SNAKE_RE.test(word) || DOTTED_RE.test(word) || CALL_RE.test(word)) {
69
+ return { kind: 'symbol', text: word };
70
+ }
71
+ return null;
72
+ }
73
+ function quotedSpans(line) {
74
+ const spans = [];
75
+ const rest = line.replace(BACKTICK_RE, (_whole, inner) => {
76
+ spans.push(inner.trim());
77
+ return ' ';
78
+ });
79
+ return { rest, spans };
80
+ }
81
+ function pushUnique(out, seen, token) {
82
+ if (token === null || token.text.length === 0 || out.length >= MAX_TOKENS)
83
+ return;
84
+ const key = `${token.kind}:${token.text}`;
85
+ if (seen.has(key))
86
+ return;
87
+ seen.add(key);
88
+ out.push(token);
89
+ }
90
+ /** The checkable specifics of `text`, at most 96, in order of first appearance. */
91
+ export function extractVerbatimTokens(text) {
92
+ const out = [];
93
+ const seen = new Set();
94
+ for (const rawLine of String(text ?? '').split(/\r?\n/)) {
95
+ const { rest, spans } = quotedSpans(rawLine.replace(LIST_MARKER_RE, ''));
96
+ for (const span of spans)
97
+ pushUnique(out, seen, classify(span, true));
98
+ for (const raw of rest.split(/\s+/))
99
+ pushUnique(out, seen, classify(trimWord(raw), false));
100
+ }
101
+ return out;
102
+ }
103
+ function escapeRegExp(text) {
104
+ return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
105
+ }
106
+ function slashNormal(text) {
107
+ return text.replace(/\\/g, '/');
108
+ }
109
+ /** A number is a whole token: `2` must not be satisfied by `1234` or `2.5`. */
110
+ function numberAppearsIn(text, corpus) {
111
+ const re = new RegExp(`(?<![0-9A-Za-z_.,])${escapeRegExp(text)}(?![0-9A-Za-z_]|[.,]\\d)`);
112
+ return re.test(corpus);
113
+ }
114
+ /** Is `token` present verbatim in the evidence `corpus`? Paths compare with one separator. */
115
+ export function tokenAppearsIn(token, corpus) {
116
+ if (token.kind === 'number')
117
+ return numberAppearsIn(token.text, corpus);
118
+ if (token.kind === 'path')
119
+ return slashNormal(corpus).includes(slashNormal(token.text));
120
+ return corpus.includes(token.text);
121
+ }
122
+ /** Check every token of `drafted` against `corpus` (all evidence texts joined). */
123
+ export function findUnsupportedTokens(drafted, corpus) {
124
+ const tokens = [];
125
+ const seen = new Set();
126
+ for (const text of drafted) {
127
+ for (const token of extractVerbatimTokens(text))
128
+ pushUnique(tokens, seen, token);
129
+ }
130
+ const missing = tokens.filter((token) => !tokenAppearsIn(token, corpus));
131
+ return { checked: tokens.length, missing };
132
+ }
133
+ /** `path x1, number x2` - kinds and counts only, never the token text (I-19). */
134
+ export function summarizeMissing(missing) {
135
+ const counts = new Map();
136
+ for (const token of missing)
137
+ counts.set(token.kind, (counts.get(token.kind) ?? 0) + 1);
138
+ return [...counts.entries()].map(([kind, n]) => `${kind} x${n}`).join(', ');
139
+ }
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Candidate validation entry point (gene-bank spec 10.7).
3
+ *
4
+ * ASCII ONLY - the whole `gene/` tree is in `glyphs.test.ts::inScope`.
5
+ *
6
+ * `validateCandidateDetailed` runs the shared static check, the oversight rules and the checks of
7
+ * the candidate's type, and returns the per-check results (`by: code | model | user`) together with
8
+ * the ROUTING the curator must follow: pass, fail, wait for a person, or convert into a merge /
9
+ * revise. `validateCandidate` is the same thing reduced to the `GeneValidation` that goes into the
10
+ * version file.
11
+ *
12
+ * NEVER THROWS, AND A THROWN PORT IS NEVER A PASS. A validator that cannot do its job (a port
13
+ * rejected, a bug) yields a failing `VALIDATOR_ERROR` check, so an outage cannot publish a gene.
14
+ * Nothing here writes: the outcome is data the publish path acts on.
15
+ */
16
+ import type { GeneValidation } from '@aragon-agent/tui/model/gene/types';
17
+ import type { CandidateContext, CandidateOutcome } from './types.js';
18
+ export type { CandidateContext, CandidateOutcome, CandidateVerdict, DerivedTool, TypeResult } from './types.js';
19
+ export type { ValidatorPorts, ModelJsonRequest, ModelJsonResponse, GeneLookup } from './ports.js';
20
+ export { isSkippedCheck, SKIPPED_PREFIX } from './common.js';
21
+ export declare function validateCandidateDetailed(ctx: CandidateContext): Promise<CandidateOutcome>;
22
+ /** The validation record that goes into the version file. Use the detailed form to route. */
23
+ export declare function validateCandidate(ctx: CandidateContext): Promise<GeneValidation>;
@@ -0,0 +1,62 @@
1
+ import { failCheck, oversightChecks, runStaticChecks, validationOf, verdictOf } from './common.js';
2
+ import { validateKnowledge } from './knowledge.js';
3
+ import { validateSkill } from './skill.js';
4
+ import { validateTool } from './tool.js';
5
+ export { isSkippedCheck, SKIPPED_PREFIX } from './common.js';
6
+ async function dispatch(ctx, report) {
7
+ switch (ctx.type) {
8
+ case 'knowledge':
9
+ return validateKnowledge(ctx, report);
10
+ case 'tool':
11
+ return validateTool(ctx, report);
12
+ case 'skill':
13
+ return validateSkill(ctx, report);
14
+ }
15
+ }
16
+ function errorResult(at) {
17
+ const check = failCheck('VALIDATOR_ERROR', at, 'a validator could not complete');
18
+ return { checks: [check], usage: { in: 0, out: 0 } };
19
+ }
20
+ const FALLBACK_REPORT = { issues: [], storedClass: 'standard', demoted: false };
21
+ export async function validateCandidateDetailed(ctx) {
22
+ const at = ctx.ports.now();
23
+ const targetClass = ctx.target?.head.class;
24
+ let report = FALLBACK_REPORT;
25
+ let result;
26
+ try {
27
+ report = runStaticChecks({
28
+ type: ctx.type,
29
+ content: ctx.content,
30
+ scope: ctx.scope,
31
+ ...(targetClass === undefined ? {} : { targetClass }),
32
+ ...(ctx.requestedClass === undefined ? {} : { requestedClass: ctx.requestedClass }),
33
+ ...(ctx.ports.knownSecrets === undefined ? {} : { knownSecrets: ctx.ports.knownSecrets }),
34
+ });
35
+ result = await dispatch(ctx, report);
36
+ }
37
+ catch {
38
+ result = errorResult(at);
39
+ }
40
+ const checks = [...oversightChecks(report, targetClass, at), ...result.checks];
41
+ const outcome = {
42
+ validation: validationOf(checks, at),
43
+ verdict: verdictOf(checks),
44
+ forceProbation: result.forceProbation === true,
45
+ class: report.storedClass,
46
+ autoProbed: result.autoProbed === true,
47
+ usage: result.usage,
48
+ };
49
+ if (result.needsHuman !== undefined)
50
+ outcome.needsHuman = result.needsHuman;
51
+ if (result.conflict !== undefined)
52
+ outcome.conflict = result.conflict;
53
+ if (result.probation !== undefined)
54
+ outcome.probation = result.probation;
55
+ if (result.derived !== undefined)
56
+ outcome.derived = result.derived;
57
+ return outcome;
58
+ }
59
+ /** The validation record that goes into the version file. Use the detailed form to route. */
60
+ export async function validateCandidate(ctx) {
61
+ return (await validateCandidateDetailed(ctx)).validation;
62
+ }
@@ -0,0 +1,25 @@
1
+ import type { GeneContent, GeneEvidence, GeneScope, GeneValidationCheck } from '@aragon-agent/tui/model/gene/types';
2
+ import type { StaticReport } from './common.js';
3
+ import type { ValidatorPorts } from './ports.js';
4
+ import type { CandidateContext, TypeResult } from './types.js';
5
+ /** The refs a draft cites: its `evidence` list and each claim's `evidence`. */
6
+ export declare function citedRefs(content: GeneContent): string[];
7
+ export interface ResolvedEvidence {
8
+ /** Snapshot evidence plus every cited ref that resolved. Deduplicated by ref. */
9
+ corpus: GeneEvidence[];
10
+ unresolved: number;
11
+ }
12
+ /** Resolve cited refs from the snapshot first, then through `readEvidence` (a revise cites old ones). */
13
+ export declare function resolveEvidence(ports: ValidatorPorts, scope: GeneScope, geneId: string | undefined, content: GeneContent, snapshot: readonly GeneEvidence[]): Promise<ResolvedEvidence>;
14
+ export interface SourceInput {
15
+ ports: ValidatorPorts;
16
+ scope: GeneScope;
17
+ geneId?: string;
18
+ content: GeneContent;
19
+ evidence: readonly GeneEvidence[];
20
+ /** Already-resolved evidence, so a caller that needs the corpus too reads each ref once. */
21
+ resolved?: ResolvedEvidence;
22
+ }
23
+ /** K2, reusable by `recheck` (10.9). Returns the K2 check and, when run, the live_check record. */
24
+ export declare function checkSource(input: SourceInput): Promise<GeneValidationCheck[]>;
25
+ export declare function validateKnowledge(ctx: CandidateContext, report: StaticReport): Promise<TypeResult>;
@@ -0,0 +1,216 @@
1
+ /**
2
+ * Knowledge-gene validation K1-K6 (gene-bank spec 10.7.1, 10.8; RV-10; TH-1).
3
+ *
4
+ * ASCII ONLY - the whole `gene/` tree is in `glyphs.test.ts::inScope`.
5
+ *
6
+ * K1 static the shared content check, minus the preference-horizon rule K3 owns
7
+ * K2 source >= 1 evidence; every cited ref resolves; every path / symbol / error code /
8
+ * number of the draft appears VERBATIM in the evidence texts that were
9
+ * snapshotted at enqueue. The live re-check against the project tree is optional
10
+ * and its absence is recorded, never a failure.
11
+ * K3 scope a temporary preference only in the task scope; a specific path or a project
12
+ * name cannot live in the user scope; environment-bound claims carry applicability
13
+ * K4 supported model: do the evidence texts support the draft? (skipped when a user said it)
14
+ * K5 conflict neighbour relations (see `conflicts.ts`)
15
+ * K6 trust all-untrusted evidence waits for a person (TH-1)
16
+ *
17
+ * Every function returns plain data. A failing detail names fields and counts, never text.
18
+ */
19
+ import { promises as nodeFs } from 'node:fs';
20
+ import { preferenceHorizonFitsScope } from '@aragon-agent/tui/model/gene/validate';
21
+ import { runConflictCheck } from '../conflicts.js';
22
+ import { addUsage, failCheck, okCheck, skippedCheck, splitIssues, staticCheck, trustCheck, } from './common.js';
23
+ import { extractVerbatimTokens, findUnsupportedTokens, summarizeMissing } from './evidence-tokens.js';
24
+ import { liveCheckEvidence } from './live-check.js';
25
+ import { askModel, buildSupportPrompt, parseSupportAnswer } from './prompts.js';
26
+ function payloadOf(content) {
27
+ const raw = content.payload;
28
+ return typeof raw === 'object' && raw !== null ? raw : {};
29
+ }
30
+ // ---------------------------------------------------------------------------
31
+ // K2 - source
32
+ // ---------------------------------------------------------------------------
33
+ /** The refs a draft cites: its `evidence` list and each claim's `evidence`. */
34
+ export function citedRefs(content) {
35
+ const refs = new Set(Array.isArray(content.evidence) ? content.evidence : []);
36
+ for (const claim of payloadOf(content).claims ?? []) {
37
+ if (typeof claim?.evidence === 'string' && claim.evidence.length > 0)
38
+ refs.add(claim.evidence);
39
+ }
40
+ return [...refs];
41
+ }
42
+ /** Resolve cited refs from the snapshot first, then through `readEvidence` (a revise cites old ones). */
43
+ export async function resolveEvidence(ports, scope, geneId, content, snapshot) {
44
+ const byRef = new Map(snapshot.map((e) => [e.ref, e]));
45
+ let unresolved = 0;
46
+ for (const ref of citedRefs(content)) {
47
+ if (byRef.has(ref))
48
+ continue;
49
+ const found = geneId === undefined ? null : await ports.readEvidence(scope, geneId, ref).catch(() => null);
50
+ if (found === null)
51
+ unresolved += 1;
52
+ else
53
+ byRef.set(ref, found);
54
+ }
55
+ return { corpus: [...byRef.values()], unresolved };
56
+ }
57
+ function draftedTexts(content) {
58
+ const claims = (payloadOf(content).claims ?? []).map((c) => String(c?.text ?? ''));
59
+ return [String(content.body ?? ''), ...claims];
60
+ }
61
+ async function rootIsDirectory(root) {
62
+ const stat = await nodeFs.stat(root).catch(() => null);
63
+ return stat !== null && stat.isDirectory();
64
+ }
65
+ /** The optional live check. Returns the info check to record and whether it failed. */
66
+ async function liveCheck(ports, scope, corpus, at) {
67
+ const checkable = corpus.filter((e) => e.kind !== 'user_statement');
68
+ if (checkable.length === 0)
69
+ return { failed: 0 };
70
+ const root = ports.projectRoot?.(scope);
71
+ if (root === undefined || !(await rootIsDirectory(root))) {
72
+ return { check: okCheck('live_check', at, 'skipped_root_unavailable'), failed: 0 };
73
+ }
74
+ const result = await liveCheckEvidence(root, checkable);
75
+ if (result.status === 'nothing_to_check')
76
+ return { failed: 0 };
77
+ if (result.status === 'skipped_budget')
78
+ return { check: okCheck('live_check', at, 'skipped_budget'), failed: 0 };
79
+ const detail = result.status === 'passed' ? 'passed' : `failed: ${result.failed} of ${result.checked}`;
80
+ return { check: okCheck('live_check', at, detail), failed: result.failed };
81
+ }
82
+ /** K2, reusable by `recheck` (10.9). Returns the K2 check and, when run, the live_check record. */
83
+ export async function checkSource(input) {
84
+ const at = input.ports.now();
85
+ const { corpus, unresolved } = input.resolved ??
86
+ (await resolveEvidence(input.ports, input.scope, input.geneId, input.content, input.evidence));
87
+ if (corpus.length === 0)
88
+ return [failCheck('KNOWLEDGE_EVIDENCE_UNRESOLVED', at, 'K2 the proposal carries no evidence')];
89
+ const problems = [];
90
+ if (unresolved > 0)
91
+ problems.push(`${unresolved} cited ref(s) unresolved`);
92
+ const report = findUnsupportedTokens(draftedTexts(input.content), corpus.map((e) => e.text).join('\n'));
93
+ if (report.missing.length > 0)
94
+ problems.push(`not in evidence: ${summarizeMissing(report.missing)}`);
95
+ const live = await liveCheck(input.ports, input.scope, corpus, at);
96
+ if (live.failed > 0)
97
+ problems.push(`${live.failed} evidence item(s) no longer match the project`);
98
+ const main = problems.length > 0
99
+ ? failCheck('KNOWLEDGE_EVIDENCE_UNRESOLVED', at, `K2 ${problems.join('; ')}`)
100
+ : okCheck('K2', at, `${report.checked} specific(s) found in evidence`);
101
+ return live.check === undefined ? [main] : [main, live.check];
102
+ }
103
+ // ---------------------------------------------------------------------------
104
+ // K3 - scope fit
105
+ // ---------------------------------------------------------------------------
106
+ const OS_WORDS = /\b(?:windows|win32|macos|darwin|linux|powershell)\b/i;
107
+ function hasSpecificPath(texts) {
108
+ return texts.some((text) => extractVerbatimTokens(text).some((t) => {
109
+ if (t.kind !== 'path' || /^https?:/i.test(t.text))
110
+ return false;
111
+ const segments = t.text.split(/[\\/]/).filter((s) => s.length > 0);
112
+ return segments.length >= 2 || /^(?:[\\/]|~[\\/]|[A-Za-z]:[\\/])/.test(t.text);
113
+ }));
114
+ }
115
+ function mentionsProject(texts, labels) {
116
+ const haystack = texts.join('\n').toLowerCase();
117
+ return labels.some((label) => {
118
+ const needle = label.trim().toLowerCase();
119
+ if (needle.length < 3)
120
+ return false;
121
+ const escaped = needle.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
122
+ return new RegExp(`(?<![a-z0-9])${escaped}(?![a-z0-9])`).test(haystack);
123
+ });
124
+ }
125
+ function applicabilityEmpty(content) {
126
+ const a = content.applicability ?? {};
127
+ return !a.os?.length && !a.envStamp && !a.projectKinds?.length && !a.fileGlobs?.length && !a.requiresTools?.length;
128
+ }
129
+ function scopeProblems(ctx) {
130
+ const c = ctx.content;
131
+ const texts = [c.name, c.purpose, c.trigger, c.body].map((t) => String(t ?? ''));
132
+ const problems = [];
133
+ if (ctx.scope.kind === 'user' && hasSpecificPath(texts))
134
+ problems.push('a specific path in the user scope');
135
+ if (ctx.scope.kind === 'user' && mentionsProject(texts, ctx.ports.projectLabels ?? [])) {
136
+ problems.push('a project name in the user scope');
137
+ }
138
+ const isPreference = payloadOf(c).kind === 'preference';
139
+ if (!isPreference && OS_WORDS.test(texts.join('\n')) && applicabilityEmpty(c)) {
140
+ problems.push('an environment-bound statement without applicability');
141
+ }
142
+ return problems;
143
+ }
144
+ function checkScope(ctx, at) {
145
+ const out = [];
146
+ const horizon = payloadOf(ctx.content).preference?.horizon;
147
+ if (horizon !== undefined && !preferenceHorizonFitsScope(horizon, ctx.scope.kind)) {
148
+ out.push(failCheck('PREF_HORIZON_SCOPE', at, `K3 a ${horizon} preference cannot live in the ${ctx.scope.kind} scope`));
149
+ }
150
+ const problems = scopeProblems(ctx);
151
+ if (problems.length > 0)
152
+ out.push(failCheck('KNOWLEDGE_SCOPE_MISFIT', at, `K3 ${problems.join('; ')}`));
153
+ return out.length > 0 ? out : [okCheck('K3', at)];
154
+ }
155
+ // ---------------------------------------------------------------------------
156
+ // K4 - supported by the evidence
157
+ // ---------------------------------------------------------------------------
158
+ async function checkSupported(ctx, corpus, usage) {
159
+ const at = ctx.ports.now();
160
+ if (corpus.some((e) => e.kind === 'user_statement' && e.trust !== 'untrusted')) {
161
+ return okCheck('K4', at, 'a user statement is sufficient');
162
+ }
163
+ const prompt = buildSupportPrompt(draftedTexts(ctx.content).join('\n'), corpus.map((e) => e.text));
164
+ const answer = await askModel(ctx.ports, prompt.system, prompt.user);
165
+ if (!answer.ok)
166
+ return skippedCheck('K4', at, answer.reason);
167
+ addUsage(usage, answer.usage);
168
+ const supported = parseSupportAnswer(answer.json);
169
+ if (supported === null)
170
+ return skippedCheck('K4', at, 'bad_model_output');
171
+ const extras = { by: 'model', ...(answer.model ? { model: answer.model } : {}), durationMs: answer.durationMs };
172
+ return supported
173
+ ? okCheck('K4', at, undefined, extras)
174
+ : failCheck('KNOWLEDGE_UNSUPPORTED', at, 'K4 the evidence does not support the draft', extras);
175
+ }
176
+ // ---------------------------------------------------------------------------
177
+ // Entry point
178
+ // ---------------------------------------------------------------------------
179
+ /** K1 owns every static issue except the preference-horizon rule, which is K3's. */
180
+ function isK3Issue(issue) {
181
+ return issue.path === 'payload.preference.horizon';
182
+ }
183
+ export async function validateKnowledge(ctx, report) {
184
+ const at = ctx.ports.now();
185
+ const usage = { in: 0, out: 0 };
186
+ const { rest } = splitIssues(report.issues, isK3Issue);
187
+ const checks = [staticCheck(rest, at)];
188
+ const resolved = await resolveEvidence(ctx.ports, ctx.scope, ctx.geneId, ctx.content, ctx.evidence);
189
+ const source = await checkSource({
190
+ ports: ctx.ports,
191
+ scope: ctx.scope,
192
+ content: ctx.content,
193
+ evidence: ctx.evidence,
194
+ resolved,
195
+ ...(ctx.geneId === undefined ? {} : { geneId: ctx.geneId }),
196
+ });
197
+ checks.push(...source, ...checkScope(ctx, at));
198
+ checks.push(await checkSupported(ctx, resolved.corpus, usage));
199
+ const conflict = await runConflictCheck(ctx.ports, {
200
+ type: 'knowledge',
201
+ scope: ctx.scope,
202
+ content: ctx.content,
203
+ ...(ctx.geneId === undefined ? {} : { geneId: ctx.geneId }),
204
+ });
205
+ checks.push(...conflict.checks);
206
+ addUsage(usage, conflict.usage);
207
+ const trust = trustCheck(ctx.evidence, at);
208
+ checks.push(trust.check);
209
+ const needsHuman = trust.needsHuman ?? (conflict.decision.action === 'needs_human' ? conflict.decision.reason : undefined);
210
+ return {
211
+ checks,
212
+ conflict: conflict.decision,
213
+ usage,
214
+ ...(needsHuman === undefined ? {} : { needsHuman }),
215
+ };
216
+ }
@@ -0,0 +1,14 @@
1
+ import type { GeneEvidence } from '@aragon-agent/tui/model/gene/types';
2
+ export type LiveCheckStatus = 'passed' | 'failed' | 'nothing_to_check' | 'skipped_budget';
3
+ export interface LiveCheckResult {
4
+ status: LiveCheckStatus;
5
+ checked: number;
6
+ failed: number;
7
+ }
8
+ export interface LiveCheckOptions {
9
+ /** Wall clock, injected so the grep budget is testable. */
10
+ clock?: () => number;
11
+ grepBudgetMs?: number;
12
+ }
13
+ /** Re-check `file` and `symbol` evidence against the live project tree. Never throws. */
14
+ export declare function liveCheckEvidence(root: string, evidence: readonly GeneEvidence[], options?: LiveCheckOptions): Promise<LiveCheckResult>;
@@ -0,0 +1,144 @@
1
+ /**
2
+ * The OPTIONAL live evidence check of K2 (gene-bank spec 10.7.1 K2, RV-10).
3
+ *
4
+ * ASCII ONLY - the whole `gene/` tree is in `glyphs.test.ts::inScope`.
5
+ *
6
+ * It runs only when the evidence's project root is reachable on THIS machine. The curator lease
7
+ * holder may be a process in a different project, with no access to the directory the evidence
8
+ * came from, so "cannot check" is a normal outcome and is NEVER a failure: the deterministic
9
+ * verbatim-token check does not depend on this module at all.
10
+ *
11
+ * WHAT IT CHECKS. `file` evidence: the file still exists under the root, its hash (when the
12
+ * evidence recorded one) still matches, otherwise the quoted first line is still in it.
13
+ * `symbol` evidence: a bounded walk finds the symbol (at most 2 s, 3000 files). Every other
14
+ * evidence kind (user statements, transcripts, tool output, urls) has nothing to re-read.
15
+ *
16
+ * ALL PATHS STAY INSIDE THE ROOT. An evidence `path` is data a model wrote down; a `..` in it
17
+ * must not make the curator read outside the project. Such evidence is "not verifiable", which
18
+ * is a skip, not a pass and not a failure.
19
+ */
20
+ import { createHash } from 'node:crypto';
21
+ import { promises as nodeFs } from 'node:fs';
22
+ import { isAbsolute, join } from 'node:path';
23
+ import { isInsideRoot } from '../../paths.js';
24
+ const MAX_FILE_BYTES = 2 * 1024 * 1024;
25
+ const GREP_FILE_BYTES = 512 * 1024;
26
+ const GREP_MAX_FILES = 3000;
27
+ const GREP_BUDGET_MS = 2000;
28
+ const SKIP_DIRS = new Set(['node_modules', '.git', 'dist', 'build', 'target', '.next', '.venv', '__pycache__']);
29
+ const TEXT_FILE_RE = /\.(?:ts|tsx|js|jsx|mjs|cjs|json|md|py|rs|go|java|cs|sh|ps1|cmd|bat|txt|css|html|xml|yml|yaml|toml)$/i;
30
+ function digestMatches(bytes, recorded) {
31
+ const want = recorded.trim().toLowerCase();
32
+ if (!/^[0-9a-f]{7,64}$/.test(want))
33
+ return false;
34
+ const sha1 = createHash('sha1').update(bytes).digest('hex');
35
+ const sha256 = createHash('sha256').update(bytes).digest('hex');
36
+ return sha1.startsWith(want) || sha256.startsWith(want);
37
+ }
38
+ function quoteNeedle(text) {
39
+ const line = text.split(/\r?\n/).map((l) => l.trim()).find((l) => l.length >= 8);
40
+ return (line ?? '').slice(0, 120);
41
+ }
42
+ async function checkFileEvidence(root, evidence) {
43
+ const rel = evidence.source.path;
44
+ if (typeof rel !== 'string' || rel.length === 0)
45
+ return 'unverifiable';
46
+ const path = isAbsolute(rel) ? rel : join(root, rel);
47
+ if (!isInsideRoot(root, path))
48
+ return 'unverifiable';
49
+ let stat;
50
+ try {
51
+ stat = await nodeFs.stat(path);
52
+ }
53
+ catch {
54
+ return 'failed';
55
+ }
56
+ if (!stat.isFile())
57
+ return 'failed';
58
+ if (stat.size > MAX_FILE_BYTES)
59
+ return 'unverifiable';
60
+ const bytes = await nodeFs.readFile(path).catch(() => null);
61
+ if (bytes === null)
62
+ return 'failed';
63
+ const recorded = evidence.source.hash;
64
+ if (typeof recorded === 'string' && recorded.length > 0) {
65
+ return digestMatches(bytes, recorded) ? 'ok' : 'failed';
66
+ }
67
+ const needle = quoteNeedle(evidence.text);
68
+ if (needle.length === 0)
69
+ return 'ok';
70
+ return bytes.toString('utf8').replace(/\r\n/g, '\n').includes(needle) ? 'ok' : 'failed';
71
+ }
72
+ async function grepFile(path, symbol, state) {
73
+ if (!TEXT_FILE_RE.test(path))
74
+ return;
75
+ state.files += 1;
76
+ const stat = await nodeFs.stat(path).catch(() => null);
77
+ if (stat === null || stat.size > GREP_FILE_BYTES)
78
+ return;
79
+ const text = await nodeFs.readFile(path, 'utf8').catch(() => '');
80
+ if (text.includes(symbol))
81
+ state.found = true;
82
+ }
83
+ async function grepSymbol(root, symbol, opts) {
84
+ const started = opts.clock();
85
+ const state = { found: false, files: 0 };
86
+ const queue = [root];
87
+ while (queue.length > 0 && !state.found) {
88
+ if (opts.clock() - started > opts.grepBudgetMs || state.files >= GREP_MAX_FILES)
89
+ return 'budget';
90
+ const dir = queue.shift();
91
+ const entries = await nodeFs.readdir(dir, { withFileTypes: true }).catch(() => []);
92
+ for (const entry of entries) {
93
+ const full = join(dir, entry.name);
94
+ if (entry.isDirectory()) {
95
+ if (!SKIP_DIRS.has(entry.name))
96
+ queue.push(full);
97
+ }
98
+ else if (entry.isFile() && !state.found) {
99
+ await grepFile(full, symbol, state);
100
+ }
101
+ }
102
+ }
103
+ return state.found ? 'found' : 'missing';
104
+ }
105
+ /** Re-check `file` and `symbol` evidence against the live project tree. Never throws. */
106
+ export async function liveCheckEvidence(root, evidence, options = {}) {
107
+ const opts = {
108
+ clock: options.clock ?? Date.now,
109
+ grepBudgetMs: options.grepBudgetMs ?? GREP_BUDGET_MS,
110
+ };
111
+ let checked = 0;
112
+ let failed = 0;
113
+ let budget = false;
114
+ for (const item of evidence) {
115
+ try {
116
+ if (item.kind === 'file') {
117
+ const verdict = await checkFileEvidence(root, item);
118
+ if (verdict === 'unverifiable')
119
+ continue;
120
+ checked += 1;
121
+ if (verdict === 'failed')
122
+ failed += 1;
123
+ }
124
+ else if (item.kind === 'symbol' && typeof item.source.symbol === 'string') {
125
+ const verdict = await grepSymbol(root, item.source.symbol, opts);
126
+ if (verdict === 'budget')
127
+ budget = true;
128
+ else {
129
+ checked += 1;
130
+ if (verdict === 'missing')
131
+ failed += 1;
132
+ }
133
+ }
134
+ }
135
+ catch {
136
+ budget = true;
137
+ }
138
+ }
139
+ if (failed > 0)
140
+ return { status: 'failed', checked, failed };
141
+ if (checked === 0)
142
+ return { status: budget ? 'skipped_budget' : 'nothing_to_check', checked, failed };
143
+ return { status: 'passed', checked, failed };
144
+ }