principles-disciple 1.127.0 → 1.129.0

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 (593) hide show
  1. package/dist/commands/archive-impl.d.ts +18 -0
  2. package/dist/commands/archive-impl.js +105 -0
  3. package/dist/commands/capabilities.d.ts +3 -0
  4. package/dist/commands/capabilities.js +76 -0
  5. package/dist/commands/context.d.ts +5 -0
  6. package/{src/commands/context.ts → dist/commands/context.js} +34 -83
  7. package/dist/commands/disable-impl.d.ts +22 -0
  8. package/dist/commands/disable-impl.js +118 -0
  9. package/dist/commands/evolution-status.d.ts +4 -0
  10. package/dist/commands/evolution-status.js +187 -0
  11. package/dist/commands/export.d.ts +2 -0
  12. package/dist/commands/export.js +53 -0
  13. package/dist/commands/focus.d.ts +14 -0
  14. package/dist/commands/focus.js +443 -0
  15. package/dist/commands/pain.d.ts +6 -0
  16. package/{src/commands/pain.ts → dist/commands/pain.js} +137 -188
  17. package/dist/commands/principle-rollback.d.ts +4 -0
  18. package/dist/commands/principle-rollback.js +26 -0
  19. package/dist/commands/promote-impl.d.ts +22 -0
  20. package/dist/commands/promote-impl.js +194 -0
  21. package/dist/commands/rollback-impl.d.ts +32 -0
  22. package/dist/commands/rollback-impl.js +180 -0
  23. package/dist/commands/rollback.d.ts +19 -0
  24. package/{src/commands/rollback.ts → dist/commands/rollback.js} +10 -53
  25. package/dist/commands/samples.d.ts +2 -0
  26. package/dist/commands/samples.js +58 -0
  27. package/dist/commands/strategy.d.ts +2 -0
  28. package/dist/commands/strategy.js +16 -0
  29. package/dist/commands/thinking-os.d.ts +2 -0
  30. package/{src/commands/thinking-os.ts → dist/commands/thinking-os.js} +35 -58
  31. package/dist/commands/workflow-debug.d.ts +6 -0
  32. package/{src/commands/workflow-debug.ts → dist/commands/workflow-debug.js} +13 -33
  33. package/dist/config/defaults/runtime.d.ts +58 -0
  34. package/{src/config/defaults/runtime.ts → dist/config/defaults/runtime.js} +4 -41
  35. package/dist/config/errors.d.ts +86 -0
  36. package/dist/config/errors.js +107 -0
  37. package/{src/config/index.ts → dist/config/index.d.ts} +1 -2
  38. package/dist/config/index.js +7 -0
  39. package/dist/constants/diagnostician.d.ts +12 -0
  40. package/{src/constants/diagnostician.ts → dist/constants/diagnostician.js} +0 -1
  41. package/dist/constants/tools.d.ts +17 -0
  42. package/dist/constants/tools.js +53 -0
  43. package/dist/core/__tests__/focus-history.test.d.ts +1 -0
  44. package/dist/core/__tests__/focus-history.test.js +160 -0
  45. package/dist/core/bootstrap-rules.d.ts +50 -0
  46. package/dist/core/bootstrap-rules.js +187 -0
  47. package/dist/core/code-implementation-storage.d.ts +71 -0
  48. package/dist/core/code-implementation-storage.js +139 -0
  49. package/dist/core/config-health.d.ts +27 -0
  50. package/dist/core/config-health.js +60 -0
  51. package/dist/core/config-service.d.ts +15 -0
  52. package/{src/core/config-service.ts → dist/core/config-service.js} +4 -7
  53. package/dist/core/config.d.ts +111 -0
  54. package/{src/core/config.ts → dist/core/config.js} +46 -146
  55. package/dist/core/control-ui-db.d.ts +106 -0
  56. package/dist/core/control-ui-db.js +309 -0
  57. package/dist/core/correction-cue-learner.d.ts +33 -0
  58. package/dist/core/correction-cue-learner.js +184 -0
  59. package/dist/core/correction-types.d.ts +3 -0
  60. package/dist/core/correction-types.js +1 -0
  61. package/dist/core/detection-funnel.d.ts +33 -0
  62. package/{src/core/detection-funnel.ts → dist/core/detection-funnel.js} +17 -37
  63. package/dist/core/detection-service.d.ts +15 -0
  64. package/{src/core/detection-service.ts → dist/core/detection-service.js} +4 -7
  65. package/dist/core/dictionary-service.d.ts +15 -0
  66. package/{src/core/dictionary-service.ts → dist/core/dictionary-service.js} +4 -7
  67. package/dist/core/dictionary.d.ts +38 -0
  68. package/{src/core/dictionary.ts → dist/core/dictionary.js} +33 -59
  69. package/dist/core/empathy-keyword-matcher.d.ts +5 -0
  70. package/dist/core/empathy-keyword-matcher.js +40 -0
  71. package/dist/core/empathy-types.d.ts +2 -0
  72. package/dist/core/empathy-types.js +1 -0
  73. package/dist/core/event-log.d.ts +90 -0
  74. package/dist/core/event-log.js +702 -0
  75. package/dist/core/evolution-engine.d.ts +119 -0
  76. package/dist/core/evolution-engine.js +460 -0
  77. package/dist/core/evolution-logger.d.ts +137 -0
  78. package/dist/core/evolution-logger.js +261 -0
  79. package/dist/core/evolution-migration.d.ts +5 -0
  80. package/dist/core/evolution-migration.js +65 -0
  81. package/dist/core/evolution-reducer.d.ts +124 -0
  82. package/dist/core/evolution-reducer.js +730 -0
  83. package/dist/core/evolution-types.d.ts +50 -0
  84. package/dist/core/evolution-types.js +11 -0
  85. package/dist/core/external-training-contract.d.ts +276 -0
  86. package/dist/core/external-training-contract.js +269 -0
  87. package/dist/core/file-store.d.ts +41 -0
  88. package/dist/core/file-store.js +46 -0
  89. package/dist/core/focus-history.d.ts +50 -0
  90. package/dist/core/focus-history.js +574 -0
  91. package/dist/core/hygiene/tracker.d.ts +22 -0
  92. package/dist/core/hygiene/tracker.js +110 -0
  93. package/dist/core/init.d.ts +30 -0
  94. package/{src/core/init.ts → dist/core/init.js} +87 -118
  95. package/dist/core/local-worker-routing.d.ts +124 -0
  96. package/dist/core/local-worker-routing.js +216 -0
  97. package/dist/core/migration.d.ts +6 -0
  98. package/{src/core/migration.ts → dist/core/migration.js} +10 -18
  99. package/dist/core/model-deployment-registry.d.ts +218 -0
  100. package/dist/core/model-deployment-registry.js +502 -0
  101. package/dist/core/model-training-registry.d.ts +295 -0
  102. package/dist/core/model-training-registry.js +474 -0
  103. package/dist/core/observability.d.ts +40 -0
  104. package/dist/core/observability.js +164 -0
  105. package/dist/core/pain-diagnostic-gate.d.ts +36 -0
  106. package/dist/core/pain-diagnostic-gate.js +105 -0
  107. package/dist/core/pain.d.ts +87 -0
  108. package/dist/core/pain.js +223 -0
  109. package/dist/core/path-resolver.d.ts +60 -0
  110. package/{src/core/path-resolver.ts → dist/core/path-resolver.js} +41 -131
  111. package/dist/core/paths.d.ts +60 -0
  112. package/{src/core/paths.ts → dist/core/paths.js} +4 -13
  113. package/dist/core/pd-config-loader.d.ts +96 -0
  114. package/dist/core/pd-config-loader.js +307 -0
  115. package/dist/core/pd-task-reconciler.d.ts +89 -0
  116. package/dist/core/pd-task-reconciler.js +262 -0
  117. package/dist/core/pd-task-service.d.ts +2 -0
  118. package/dist/core/pd-task-service.js +32 -0
  119. package/dist/core/pd-task-store.d.ts +5 -0
  120. package/dist/core/pd-task-store.js +62 -0
  121. package/dist/core/pd-task-types.d.ts +8 -0
  122. package/dist/core/pd-task-types.js +2 -0
  123. package/dist/core/principle-compiler/__tests__/compiler-replay-gate.test.d.ts +1 -0
  124. package/dist/core/principle-compiler/__tests__/compiler-replay-gate.test.js +132 -0
  125. package/dist/core/principle-compiler/code-validator.d.ts +14 -0
  126. package/dist/core/principle-compiler/code-validator.js +86 -0
  127. package/dist/core/principle-compiler/compiler.d.ts +45 -0
  128. package/dist/core/principle-compiler/compiler.js +287 -0
  129. package/{src/core/principle-compiler/index.ts → dist/core/principle-compiler/index.d.ts} +0 -1
  130. package/dist/core/principle-compiler/index.js +10 -0
  131. package/dist/core/principle-compiler/ledger-registrar.d.ts +28 -0
  132. package/dist/core/principle-compiler/ledger-registrar.js +95 -0
  133. package/{src/core/principle-compiler/template-generator.ts → dist/core/principle-compiler/template-generator.d.ts} +0 -1
  134. package/dist/core/principle-compiler/template-generator.js +7 -0
  135. package/{src/core/principle-injection.ts → dist/core/principle-injection.d.ts} +1 -7
  136. package/dist/core/principle-injection.js +10 -0
  137. package/dist/core/principle-internalization/filesystem-lifecycle-datasource.d.ts +15 -0
  138. package/dist/core/principle-internalization/filesystem-lifecycle-datasource.js +34 -0
  139. package/dist/core/principle-internalization/lifecycle-read-model.d.ts +17 -0
  140. package/{src/core/principle-internalization/lifecycle-read-model.ts → dist/core/principle-internalization/lifecycle-read-model.js} +2 -21
  141. package/dist/core/principle-internalization/lifecycle-refresh.d.ts +2 -0
  142. package/dist/core/principle-internalization/lifecycle-refresh.js +4 -0
  143. package/dist/core/principle-internalization/principle-lifecycle-service.d.ts +28 -0
  144. package/dist/core/principle-internalization/principle-lifecycle-service.js +89 -0
  145. package/dist/core/principle-training-state.d.ts +47 -0
  146. package/dist/core/principle-training-state.js +113 -0
  147. package/dist/core/principle-tree-ledger-adapter.d.ts +32 -0
  148. package/dist/core/principle-tree-ledger-adapter.js +125 -0
  149. package/dist/core/principle-tree-ledger.d.ts +82 -0
  150. package/dist/core/principle-tree-ledger.js +527 -0
  151. package/dist/core/profile.d.ts +62 -0
  152. package/dist/core/profile.js +211 -0
  153. package/dist/core/promotion-gate.d.ts +243 -0
  154. package/dist/core/promotion-gate.js +554 -0
  155. package/dist/core/reflection/reflection-context.d.ts +31 -0
  156. package/dist/core/reflection/reflection-context.js +91 -0
  157. package/dist/core/replay-engine.d.ts +12 -0
  158. package/dist/core/replay-engine.js +82 -0
  159. package/dist/core/risk-calculator.d.ts +22 -0
  160. package/{src/core/risk-calculator.ts → dist/core/risk-calculator.js} +19 -49
  161. package/{src/core/rule-host-helpers.ts → dist/core/rule-host-helpers.d.ts} +0 -1
  162. package/dist/core/rule-host-helpers.js +7 -0
  163. package/{src/core/rule-host-types.ts → dist/core/rule-host-types.d.ts} +1 -8
  164. package/dist/core/rule-host-types.js +7 -0
  165. package/dist/core/rule-host.d.ts +86 -0
  166. package/dist/core/rule-host.js +311 -0
  167. package/dist/core/rule-implementation-runtime.d.ts +18 -0
  168. package/dist/core/rule-implementation-runtime.js +112 -0
  169. package/dist/core/runtime-v2-prompt-activation-reader.d.ts +22 -0
  170. package/dist/core/runtime-v2-prompt-activation-reader.js +99 -0
  171. package/{src/core/schema/db-types.ts → dist/core/schema/db-types.d.ts} +4 -9
  172. package/dist/core/schema/db-types.js +5 -0
  173. package/{src/core/schema/index.ts → dist/core/schema/index.d.ts} +1 -10
  174. package/dist/core/schema/index.js +15 -0
  175. package/dist/core/schema/migration-runner.d.ts +53 -0
  176. package/dist/core/schema/migration-runner.js +170 -0
  177. package/dist/core/schema/migrations/001-init-trajectory.d.ts +6 -0
  178. package/{src/core/schema/migrations/001-init-trajectory.ts → dist/core/schema/migrations/001-init-trajectory.js} +38 -56
  179. package/dist/core/schema/migrations/002-init-central.d.ts +5 -0
  180. package/{src/core/schema/migrations/002-init-central.ts → dist/core/schema/migrations/002-init-central.js} +27 -41
  181. package/dist/core/schema/migrations/003-init-workflow.d.ts +5 -0
  182. package/{src/core/schema/migrations/003-init-workflow.ts → dist/core/schema/migrations/003-init-workflow.js} +16 -21
  183. package/dist/core/schema/migrations/004-add-thinking-and-gfi.d.ts +8 -0
  184. package/{src/core/schema/migrations/004-add-thinking-and-gfi.ts → dist/core/schema/migrations/004-add-thinking-and-gfi.js} +19 -27
  185. package/{src/core/schema/migrations/index.ts → dist/core/schema/migrations/index.d.ts} +1 -16
  186. package/dist/core/schema/migrations/index.js +27 -0
  187. package/dist/core/schema/schema-definitions.d.ts +46 -0
  188. package/{src/core/schema/schema-definitions.ts → dist/core/schema/schema-definitions.js} +242 -291
  189. package/dist/core/session-tracker.d.ts +119 -0
  190. package/{src/core/session-tracker.ts → dist/core/session-tracker.js} +96 -239
  191. package/dist/core/shadow-observation-registry.d.ts +217 -0
  192. package/dist/core/shadow-observation-registry.js +280 -0
  193. package/dist/core/surface-guard.d.ts +31 -0
  194. package/dist/core/surface-guard.js +131 -0
  195. package/dist/core/system-logger.d.ts +8 -0
  196. package/{src/core/system-logger.ts → dist/core/system-logger.js} +20 -34
  197. package/dist/core/thinking-models.d.ts +70 -0
  198. package/dist/core/thinking-models.js +300 -0
  199. package/dist/core/thinking-os-parser.d.ts +35 -0
  200. package/dist/core/thinking-os-parser.js +123 -0
  201. package/dist/core/trajectory-types.d.ts +220 -0
  202. package/dist/core/trajectory-types.js +8 -0
  203. package/dist/core/trajectory.d.ts +242 -0
  204. package/dist/core/trajectory.js +1500 -0
  205. package/dist/core/workflow-funnel-loader.d.ts +72 -0
  206. package/dist/core/workflow-funnel-loader.js +135 -0
  207. package/dist/core/workspace-context.d.ts +111 -0
  208. package/{src/core/workspace-context.ts → dist/core/workspace-context.js} +50 -105
  209. package/dist/core/workspace-dir-validation.d.ts +11 -0
  210. package/dist/core/workspace-dir-validation.js +37 -0
  211. package/dist/core/workspace-guidance-migrator.d.ts +12 -0
  212. package/{src/core/workspace-guidance-migrator.ts → dist/core/workspace-guidance-migrator.js} +21 -59
  213. package/dist/hooks/after-tool-call-helpers.d.ts +89 -0
  214. package/dist/hooks/after-tool-call-helpers.js +475 -0
  215. package/dist/hooks/after-tool-call-types.d.ts +86 -0
  216. package/dist/hooks/after-tool-call-types.js +13 -0
  217. package/dist/hooks/gate-block-helper.d.ts +44 -0
  218. package/dist/hooks/gate-block-helper.js +209 -0
  219. package/dist/hooks/gate.d.ts +16 -0
  220. package/dist/hooks/gate.js +381 -0
  221. package/dist/hooks/lifecycle.d.ts +5 -0
  222. package/dist/hooks/lifecycle.js +287 -0
  223. package/dist/hooks/llm.d.ts +13 -0
  224. package/{src/hooks/llm.ts → dist/hooks/llm.js} +63 -117
  225. package/dist/hooks/message-sanitize.d.ts +24 -0
  226. package/dist/hooks/message-sanitize.js +77 -0
  227. package/dist/hooks/pain.d.ts +33 -0
  228. package/dist/hooks/pain.js +294 -0
  229. package/dist/hooks/prompt.d.ts +52 -0
  230. package/dist/hooks/prompt.js +930 -0
  231. package/dist/hooks/raw-observation-adapter.d.ts +57 -0
  232. package/dist/hooks/raw-observation-adapter.js +170 -0
  233. package/dist/hooks/raw-observation-types.d.ts +62 -0
  234. package/dist/hooks/raw-observation-types.js +15 -0
  235. package/dist/hooks/subagent.d.ts +9 -0
  236. package/{src/hooks/subagent.ts → dist/hooks/subagent.js} +20 -60
  237. package/dist/hooks/trajectory-collector.d.ts +25 -0
  238. package/dist/hooks/trajectory-collector.js +225 -0
  239. package/dist/hooks/trajectory-evidence.d.ts +11 -0
  240. package/dist/hooks/trajectory-evidence.js +88 -0
  241. package/dist/hooks/triage-adapter.d.ts +58 -0
  242. package/{src/hooks/triage-adapter.ts → dist/hooks/triage-adapter.js} +36 -68
  243. package/dist/hooks/trigger-cooldown-tracker.d.ts +30 -0
  244. package/dist/hooks/trigger-cooldown-tracker.js +55 -0
  245. package/dist/i18n/commands.d.ts +26 -0
  246. package/dist/i18n/commands.js +96 -0
  247. package/dist/index.d.ts +50 -0
  248. package/dist/index.js +829 -0
  249. package/dist/openclaw-sdk.d.ts +293 -0
  250. package/dist/openclaw-sdk.js +4 -0
  251. package/dist/service/central-database.d.ts +138 -0
  252. package/dist/service/central-database.js +731 -0
  253. package/dist/service/central-sync-service.d.ts +8 -0
  254. package/dist/service/central-sync-service.js +71 -0
  255. package/dist/service/correction-observer-service.d.ts +19 -0
  256. package/{src/service/correction-observer-service.ts → dist/service/correction-observer-service.js} +36 -76
  257. package/dist/service/evolution-dedup.d.ts +27 -0
  258. package/{src/service/evolution-dedup.ts → dist/service/evolution-dedup.js} +11 -31
  259. package/{src/service/evolution-queue-migration.ts → dist/service/evolution-queue-migration.d.ts} +15 -62
  260. package/dist/service/evolution-queue-migration.js +53 -0
  261. package/dist/service/evolution-worker.d.ts +103 -0
  262. package/{src/service/evolution-worker.ts → dist/service/evolution-worker.js} +169 -331
  263. package/dist/service/internalization-auto-consumer-service.d.ts +8 -0
  264. package/dist/service/internalization-auto-consumer-service.js +322 -0
  265. package/dist/service/keyword-optimization-service.d.ts +44 -0
  266. package/dist/service/keyword-optimization-service.js +137 -0
  267. package/dist/service/phase3-input-filter.d.ts +73 -0
  268. package/dist/service/phase3-input-filter.js +172 -0
  269. package/dist/service/queue-io.d.ts +30 -0
  270. package/dist/service/queue-io.js +79 -0
  271. package/{src/service/queue-migration.ts → dist/service/queue-migration.d.ts} +6 -45
  272. package/dist/service/queue-migration.js +56 -0
  273. package/dist/service/runtime-summary-service.d.ts +158 -0
  274. package/dist/service/runtime-summary-service.js +636 -0
  275. package/dist/service/subagent-workflow/subagent-error-utils.d.ts +8 -0
  276. package/{src/service/subagent-workflow/subagent-error-utils.ts → dist/service/subagent-workflow/subagent-error-utils.js} +3 -6
  277. package/{src/service/subagent-workflow/types.ts → dist/service/subagent-workflow/types.d.ts} +17 -80
  278. package/dist/service/subagent-workflow/types.js +11 -0
  279. package/dist/service/subagent-workflow/workflow-store.d.ts +30 -0
  280. package/{src/service/subagent-workflow/workflow-store.ts → dist/service/subagent-workflow/workflow-store.js} +43 -108
  281. package/dist/service/trajectory-service.d.ts +2 -0
  282. package/dist/service/trajectory-service.js +16 -0
  283. package/dist/service/workflow-watchdog.d.ts +23 -0
  284. package/dist/service/workflow-watchdog.js +103 -0
  285. package/dist/types/event-types.d.ts +2 -0
  286. package/dist/types/event-types.js +1 -0
  287. package/dist/types/hygiene-types.d.ts +2 -0
  288. package/dist/types/hygiene-types.js +1 -0
  289. package/{src/types/principle-tree-schema.ts → dist/types/principle-tree-schema.d.ts} +2 -25
  290. package/dist/types/principle-tree-schema.js +24 -0
  291. package/dist/types/queue.d.ts +2 -0
  292. package/dist/types/queue.js +1 -0
  293. package/dist/types/runtime-summary.d.ts +1 -0
  294. package/dist/types/runtime-summary.js +1 -0
  295. package/dist/types.d.ts +33 -0
  296. package/dist/types.js +16 -0
  297. package/dist/utils/file-lock.d.ts +68 -0
  298. package/dist/utils/file-lock.js +310 -0
  299. package/dist/utils/hashing.d.ts +9 -0
  300. package/{src/utils/hashing.ts → dist/utils/hashing.js} +4 -6
  301. package/dist/utils/io.d.ts +11 -0
  302. package/dist/utils/io.js +174 -0
  303. package/dist/utils/node-vm-polyfill.d.ts +9 -0
  304. package/{src/utils/node-vm-polyfill.ts → dist/utils/node-vm-polyfill.js} +0 -2
  305. package/dist/utils/retry.d.ts +210 -0
  306. package/dist/utils/retry.js +375 -0
  307. package/dist/utils/session-key.d.ts +10 -0
  308. package/{src/utils/session-key.ts → dist/utils/session-key.js} +5 -4
  309. package/dist/utils/shadow-fingerprint.d.ts +16 -0
  310. package/dist/utils/shadow-fingerprint.js +34 -0
  311. package/dist/utils/workspace-resolver.d.ts +82 -0
  312. package/dist/utils/workspace-resolver.js +288 -0
  313. package/openclaw.plugin.json +1 -1
  314. package/package.json +8 -2
  315. package/templates/workspace/.principles/DECISION_POLICY.json +44 -0
  316. package/templates/workspace/.principles/PRINCIPLES.md +20 -0
  317. package/templates/workspace/.principles/PROFILE.json +54 -0
  318. package/templates/workspace/.principles/PROFILE.schema.json +56 -0
  319. package/templates/workspace/.principles/THINKING_OS.md +65 -0
  320. package/templates/workspace/.principles/THINKING_OS_ARCHIVE.md +7 -0
  321. package/templates/workspace/.principles/THINKING_OS_CANDIDATES.md +9 -0
  322. package/templates/workspace/.principles/models/_INDEX.md +27 -0
  323. package/templates/workspace/.principles/models/first_principles.md +62 -0
  324. package/templates/workspace/.principles/models/marketing_4p.md +52 -0
  325. package/templates/workspace/.principles/models/porter_five.md +63 -0
  326. package/templates/workspace/.principles/models/swot.md +60 -0
  327. package/templates/workspace/.principles/models/user_story_map.md +63 -0
  328. package/templates/workspace/.state/WORKBOARD.json +4 -0
  329. package/.dependency-cruiser.json +0 -19
  330. package/ADVANCED_CONFIG_ZH.md +0 -93
  331. package/AGENT_INSTALL.md +0 -173
  332. package/AGENT_INSTALL_EN.md +0 -173
  333. package/CHANGELOG.md +0 -26
  334. package/INSTALL.md +0 -254
  335. package/SKILL.md +0 -63
  336. package/esbuild.config.js +0 -104
  337. package/src/commands/archive-impl.ts +0 -147
  338. package/src/commands/capabilities.ts +0 -89
  339. package/src/commands/disable-impl.ts +0 -159
  340. package/src/commands/evolution-status.ts +0 -247
  341. package/src/commands/export.ts +0 -59
  342. package/src/commands/focus.ts +0 -523
  343. package/src/commands/principle-rollback.ts +0 -32
  344. package/src/commands/promote-impl.ts +0 -254
  345. package/src/commands/rollback-impl.ts +0 -246
  346. package/src/commands/samples.ts +0 -65
  347. package/src/commands/strategy.ts +0 -21
  348. package/src/config/errors.ts +0 -180
  349. package/src/constants/tools.ts +0 -62
  350. package/src/core/AGENTS.md +0 -34
  351. package/src/core/__tests__/focus-history.test.ts +0 -210
  352. package/src/core/bootstrap-rules.ts +0 -216
  353. package/src/core/code-implementation-storage.ts +0 -213
  354. package/src/core/config-health.ts +0 -72
  355. package/src/core/control-ui-db.ts +0 -454
  356. package/src/core/correction-cue-learner.ts +0 -239
  357. package/src/core/correction-types.ts +0 -16
  358. package/src/core/empathy-keyword-matcher.ts +0 -64
  359. package/src/core/empathy-types.ts +0 -18
  360. package/src/core/event-log.ts +0 -787
  361. package/src/core/evolution-engine.ts +0 -613
  362. package/src/core/evolution-logger.ts +0 -357
  363. package/src/core/evolution-migration.ts +0 -77
  364. package/src/core/evolution-reducer.ts +0 -891
  365. package/src/core/evolution-types.ts +0 -110
  366. package/src/core/external-training-contract.ts +0 -530
  367. package/src/core/file-store.ts +0 -80
  368. package/src/core/focus-history.ts +0 -763
  369. package/src/core/hygiene/tracker.ts +0 -122
  370. package/src/core/local-worker-routing.ts +0 -337
  371. package/src/core/model-deployment-registry.ts +0 -724
  372. package/src/core/model-training-registry.ts +0 -815
  373. package/src/core/observability.ts +0 -242
  374. package/src/core/pain-diagnostic-gate.ts +0 -169
  375. package/src/core/pain.ts +0 -309
  376. package/src/core/pd-config-loader.ts +0 -400
  377. package/src/core/pd-task-reconciler.ts +0 -380
  378. package/src/core/pd-task-service.ts +0 -43
  379. package/src/core/pd-task-store.ts +0 -78
  380. package/src/core/pd-task-types.ts +0 -24
  381. package/src/core/principle-compiler/__tests__/compiler-replay-gate.test.ts +0 -174
  382. package/src/core/principle-compiler/code-validator.ts +0 -96
  383. package/src/core/principle-compiler/compiler.ts +0 -327
  384. package/src/core/principle-compiler/ledger-registrar.ts +0 -116
  385. package/src/core/principle-internalization/filesystem-lifecycle-datasource.ts +0 -42
  386. package/src/core/principle-internalization/lifecycle-refresh.ts +0 -11
  387. package/src/core/principle-internalization/principle-lifecycle-service.ts +0 -170
  388. package/src/core/principle-training-state.ts +0 -177
  389. package/src/core/principle-tree-ledger-adapter.ts +0 -145
  390. package/src/core/principle-tree-ledger.ts +0 -725
  391. package/src/core/profile.ts +0 -228
  392. package/src/core/promotion-gate.ts +0 -854
  393. package/src/core/reflection/reflection-context.ts +0 -133
  394. package/src/core/replay-engine.ts +0 -106
  395. package/src/core/rule-host.ts +0 -386
  396. package/src/core/rule-implementation-runtime.ts +0 -145
  397. package/src/core/runtime-v2-prompt-activation-reader.ts +0 -114
  398. package/src/core/schema/migration-runner.ts +0 -207
  399. package/src/core/shadow-observation-registry.ts +0 -508
  400. package/src/core/surface-guard.ts +0 -188
  401. package/src/core/thinking-models.ts +0 -377
  402. package/src/core/thinking-os-parser.ts +0 -165
  403. package/src/core/trajectory-types.ts +0 -247
  404. package/src/core/trajectory.ts +0 -1831
  405. package/src/core/workflow-funnel-loader.ts +0 -195
  406. package/src/core/workspace-dir-validation.ts +0 -52
  407. package/src/hooks/AGENTS.md +0 -31
  408. package/src/hooks/after-tool-call-helpers.ts +0 -601
  409. package/src/hooks/after-tool-call-types.ts +0 -99
  410. package/src/hooks/gate-block-helper.ts +0 -265
  411. package/src/hooks/gate.ts +0 -394
  412. package/src/hooks/lifecycle.ts +0 -334
  413. package/src/hooks/message-sanitize.ts +0 -102
  414. package/src/hooks/pain.ts +0 -358
  415. package/src/hooks/prompt.ts +0 -1102
  416. package/src/hooks/raw-observation-adapter.ts +0 -215
  417. package/src/hooks/raw-observation-types.ts +0 -77
  418. package/src/hooks/trajectory-collector.ts +0 -253
  419. package/src/hooks/trajectory-evidence.ts +0 -97
  420. package/src/hooks/trigger-cooldown-tracker.ts +0 -82
  421. package/src/i18n/commands.ts +0 -101
  422. package/src/index.ts +0 -939
  423. package/src/openclaw-sdk.ts +0 -312
  424. package/src/service/central-database.ts +0 -936
  425. package/src/service/central-sync-service.ts +0 -85
  426. package/src/service/internalization-auto-consumer-service.ts +0 -397
  427. package/src/service/keyword-optimization-service.ts +0 -169
  428. package/src/service/phase3-input-filter.ts +0 -237
  429. package/src/service/queue-io.ts +0 -108
  430. package/src/service/runtime-summary-service.ts +0 -990
  431. package/src/service/trajectory-service.ts +0 -16
  432. package/src/service/workflow-watchdog.ts +0 -125
  433. package/src/types/event-types.ts +0 -39
  434. package/src/types/hygiene-types.ts +0 -8
  435. package/src/types/queue.ts +0 -15
  436. package/src/types/runtime-summary.ts +0 -5
  437. package/src/types.ts +0 -53
  438. package/src/utils/file-lock.ts +0 -394
  439. package/src/utils/io.ts +0 -176
  440. package/src/utils/retry.ts +0 -573
  441. package/src/utils/shadow-fingerprint.ts +0 -42
  442. package/src/utils/workspace-resolver.ts +0 -393
  443. package/tests/README.md +0 -120
  444. package/tests/build-artifacts.test.ts +0 -55
  445. package/tests/commands/evolution-status.test.ts +0 -511
  446. package/tests/commands/export.test.ts +0 -78
  447. package/tests/commands/pain.test.ts +0 -287
  448. package/tests/commands/samples.test.ts +0 -65
  449. package/tests/commands/strategy.test.ts +0 -19
  450. package/tests/commands/thinking-os.test.ts +0 -88
  451. package/tests/core/bootstrap-rules.test.ts +0 -596
  452. package/tests/core/code-implementation-storage.test.ts +0 -300
  453. package/tests/core/code-validator.test.ts +0 -197
  454. package/tests/core/config-service.test.ts +0 -89
  455. package/tests/core/config.test.ts +0 -90
  456. package/tests/core/control-ui-db.test.ts +0 -75
  457. package/tests/core/core-principle-registry-drift.test.ts +0 -39
  458. package/tests/core/core-template-guidance.test.ts +0 -21
  459. package/tests/core/correction-cue-learner.test.ts +0 -345
  460. package/tests/core/detection-service.test.ts +0 -50
  461. package/tests/core/dictionary-service.test.ts +0 -116
  462. package/tests/core/dictionary.test.ts +0 -171
  463. package/tests/core/empathy-keyword-matcher.test.ts +0 -209
  464. package/tests/core/event-log.test.ts +0 -484
  465. package/tests/core/evolution-engine.test.ts +0 -610
  466. package/tests/core/evolution-logger.test.ts +0 -148
  467. package/tests/core/evolution-migration.test.ts +0 -374
  468. package/tests/core/evolution-paths.test.ts +0 -21
  469. package/tests/core/evolution-reducer.compilation-retry.test.ts +0 -189
  470. package/tests/core/evolution-reducer.detector-metadata.test.ts +0 -602
  471. package/tests/core/evolution-types-loop.test.ts +0 -48
  472. package/tests/core/external-training-contract.test.ts +0 -463
  473. package/tests/core/file-store.test.ts +0 -102
  474. package/tests/core/focus-history.test.ts +0 -874
  475. package/tests/core/init-flatten.test.ts +0 -69
  476. package/tests/core/init-refactor.test.ts +0 -87
  477. package/tests/core/init-v1.3.test.ts +0 -46
  478. package/tests/core/init.test.ts +0 -190
  479. package/tests/core/ledger-registrar.test.ts +0 -235
  480. package/tests/core/migration.test.ts +0 -84
  481. package/tests/core/model-deployment-registry.test.ts +0 -858
  482. package/tests/core/model-training-registry.test.ts +0 -908
  483. package/tests/core/observability.test.ts +0 -382
  484. package/tests/core/pain-diagnostic-gate.test.ts +0 -614
  485. package/tests/core/pain-score.property.test.ts +0 -19
  486. package/tests/core/pain.test.ts +0 -132
  487. package/tests/core/path-resolver.test.ts +0 -57
  488. package/tests/core/paths-refactor.test.ts +0 -20
  489. package/tests/core/pd-config-loader.test.ts +0 -407
  490. package/tests/core/pd-task-store.test.ts +0 -126
  491. package/tests/core/phase7-rollout-integration.test.ts +0 -477
  492. package/tests/core/principle-compiler.test.ts +0 -350
  493. package/tests/core/principle-injection.test.ts +0 -223
  494. package/tests/core/principle-internalization/deprecated-readiness.test.ts +0 -193
  495. package/tests/core/principle-internalization/lifecycle-metrics.test.ts +0 -350
  496. package/tests/core/principle-internalization/lifecycle-routing-policy.test.ts +0 -212
  497. package/tests/core/principle-internalization/lineage-source-retired.test.ts +0 -56
  498. package/tests/core/principle-internalization/principle-lifecycle-service.test.ts +0 -189
  499. package/tests/core/principle-training-state.test.ts +0 -939
  500. package/tests/core/principle-tree-ledger-adapter.test.ts +0 -253
  501. package/tests/core/principle-tree-ledger.test.ts +0 -423
  502. package/tests/core/profile.test.ts +0 -56
  503. package/tests/core/promotion-gate.test.ts +0 -561
  504. package/tests/core/queue-purge.test.ts +0 -337
  505. package/tests/core/reflection-context.test.ts +0 -342
  506. package/tests/core/regression-v1-9-1.test.ts +0 -266
  507. package/tests/core/replay-engine.test.ts +0 -165
  508. package/tests/core/risk-calculator.test.ts +0 -168
  509. package/tests/core/rule-host-adversarial-output.test.ts +0 -242
  510. package/tests/core/rule-host-autocorrect-vm.test.ts +0 -163
  511. package/tests/core/rule-host-helpers.test.ts +0 -120
  512. package/tests/core/rule-host-resource-bounds.test.ts +0 -231
  513. package/tests/core/rule-host-sqlite-source.test.ts +0 -720
  514. package/tests/core/rule-host-unhealthy-visibility.test.ts +0 -261
  515. package/tests/core/rule-host-validation.test.ts +0 -315
  516. package/tests/core/rule-implementation-runtime.test.ts +0 -49
  517. package/tests/core/session-tracker.test.ts +0 -191
  518. package/tests/core/surface-guard.test.ts +0 -338
  519. package/tests/core/template-generator.test.ts +0 -101
  520. package/tests/core/trajectory.test.ts +0 -427
  521. package/tests/core/workflow-funnel-loader.test.ts +0 -1028
  522. package/tests/core/workspace-context-factory.test.ts +0 -18
  523. package/tests/core/workspace-context.test.ts +0 -187
  524. package/tests/core/workspace-guidance-migrator.test.ts +0 -248
  525. package/tests/core-anti-growth.test.ts +0 -182
  526. package/tests/evolution-worker-quarantine.test.ts +0 -400
  527. package/tests/evolution-worker-slimming.test.ts +0 -380
  528. package/tests/fixtures/legacy-queue-v1.json +0 -74
  529. package/tests/fixtures/production-compatibility.test.ts +0 -147
  530. package/tests/fixtures/production-mock-generator.ts +0 -282
  531. package/tests/globalSetup.ts +0 -38
  532. package/tests/hook-workspace-nextaction-contract.test.ts +0 -50
  533. package/tests/hooks/confirm-first-removal.test.ts +0 -188
  534. package/tests/hooks/gate-auto-correct-shadow.test.ts +0 -309
  535. package/tests/hooks/gate-auto-correct.test.ts +0 -664
  536. package/tests/hooks/gate-block-helper-profile.test.ts +0 -186
  537. package/tests/hooks/gate-no-path-write-tool.test.ts +0 -171
  538. package/tests/hooks/gate-rule-host-pipeline.test.ts +0 -230
  539. package/tests/hooks/gate-rule-host-real-pipeline.test.ts +0 -190
  540. package/tests/hooks/lifecycle.test.ts +0 -248
  541. package/tests/hooks/message-sanitize.test.ts +0 -244
  542. package/tests/hooks/pain-emission-characterization.test.ts +0 -420
  543. package/tests/hooks/pain.test.ts +0 -795
  544. package/tests/hooks/prompt-characterization.test.ts +0 -476
  545. package/tests/hooks/prompt-diet.test.ts +0 -335
  546. package/tests/hooks/prompt-size-guard.test.ts +0 -319
  547. package/tests/hooks/raw-observation-adapter.test.ts +0 -312
  548. package/tests/hooks/runtime-v2-prompt-activation.test.ts +0 -895
  549. package/tests/hooks/single-gate-pain-admission.test.ts +0 -258
  550. package/tests/hooks/subagent.test.ts +0 -469
  551. package/tests/hooks/trajectory-collector.test.ts +0 -269
  552. package/tests/hooks/trajectory-evidence.test.ts +0 -280
  553. package/tests/hooks/triage-adapter.test.ts +0 -331
  554. package/tests/hygiene-tracker.test.ts +0 -77
  555. package/tests/index.test.ts +0 -142
  556. package/tests/integration/auto-entry-gate.test.ts +0 -256
  557. package/tests/integration/gate-real-io.e2e.test.ts +0 -248
  558. package/tests/integration/m8-legacy-paths.test.ts +0 -63
  559. package/tests/integration/mvp-surface-registry-guard.test.ts +0 -536
  560. package/tests/integration/pain-id-chain-e2e.test.ts +0 -313
  561. package/tests/integration/principle-compiler-e2e.test.ts +0 -403
  562. package/tests/integration/principle-lifecycle.e2e.test.ts +0 -198
  563. package/tests/integration/runtime-v2-pain-guard.test.ts +0 -125
  564. package/tests/integration/trajectory-lifecycle.e2e.test.ts +0 -523
  565. package/tests/internalization-auto-consumer-gate.test.ts +0 -158
  566. package/tests/internalization-auto-consumer-service.test.ts +0 -219
  567. package/tests/plugin-config-resolution-cutover.test.ts +0 -359
  568. package/tests/queue/async-lock.test.ts +0 -200
  569. package/tests/runtime-v2-discovery-guard.test.ts +0 -153
  570. package/tests/scripts/validate-live-path.test.ts +0 -286
  571. package/tests/service/central-database.test.ts +0 -457
  572. package/tests/service/correction-observer-service.test.ts +0 -505
  573. package/tests/service/evolution-worker.compilation-backfill.test.ts +0 -203
  574. package/tests/service/evolution-worker.correction-observer.test.ts +0 -50
  575. package/tests/service/evolution-worker.queue.test.ts +0 -296
  576. package/tests/service/evolution-worker.timeout.test.ts +0 -233
  577. package/tests/service/keyword-optimization-service.test.ts +0 -121
  578. package/tests/service/phase3-input-filter.test.ts +0 -289
  579. package/tests/service/queue-io.test.ts +0 -168
  580. package/tests/service/queue-migration.test.ts +0 -147
  581. package/tests/service/runtime-summary-service.test.ts +0 -1100
  582. package/tests/service/workflow-watchdog.test.ts +0 -281
  583. package/tests/task-compliance.test.ts +0 -166
  584. package/tests/test-utils.ts +0 -48
  585. package/tests/utils/file-lock.test.ts +0 -409
  586. package/tests/utils/hashing.test.ts +0 -32
  587. package/tests/utils/hook-workspace-resolver.test.ts +0 -524
  588. package/tests/utils/io.test.ts +0 -39
  589. package/tests/utils/retry.test.ts +0 -327
  590. package/tests/utils/session-key.test.ts +0 -52
  591. package/tsconfig.json +0 -16
  592. package/vitest.config.ts +0 -61
  593. package/vitest.unit.config.ts +0 -12
@@ -0,0 +1,1500 @@
1
+ import Database from 'better-sqlite3';
2
+ import fs from 'fs';
3
+ import path from 'path';
4
+ import crypto from 'crypto';
5
+ import { withLock } from '../utils/file-lock.js';
6
+ import { atomicWriteFileSync } from '../utils/io.js';
7
+ import { resolvePdPath } from './paths.js';
8
+ import { SampleNotFoundError } from '../config/index.js';
9
+ /**
10
+ * Trajectory database stores HISTORICAL and ANALYTICS data.
11
+ *
12
+ * PURPOSE: Track task outcomes, trust changes, and evolution progress over time.
13
+ * USAGE: Insights, trends, and Phase 3 supporting evidence (where explicitly allowed).
14
+ * NOT FOR: Control decisions, Phase 3 eligibility, or real-time operations.
15
+ *
16
+ * Runtime truth comes from: queue state, workspace trust scorecard, active sessions
17
+ */
18
+ const DEFAULT_INLINE_THRESHOLD = 16 * 1024;
19
+ const DEFAULT_BUSY_TIMEOUT_MS = 5000;
20
+ const DEFAULT_ORPHAN_BLOB_GRACE_DAYS = 7;
21
+ const SCHEMA_VERSION = 1;
22
+ function nowIso() {
23
+ return new Date().toISOString();
24
+ }
25
+ function safeJson(value) {
26
+ return JSON.stringify(value ?? {});
27
+ }
28
+ function fileSizeIfExists(filePath) {
29
+ try {
30
+ return fs.existsSync(filePath) ? fs.statSync(filePath).size : 0;
31
+ }
32
+ catch {
33
+ return 0;
34
+ }
35
+ }
36
+ function summarizeForDiff(text) {
37
+ return text.length > 240 ? `${text.slice(0, 237)}...` : text;
38
+ }
39
+ function redactText(text) {
40
+ return text
41
+ .replace(/[A-Za-z]:\\[^\s"'`]+/g, '<WINDOWS_PATH>')
42
+ .replace(/\/[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)+/g, '<PATH>')
43
+ .replace(/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/gi, '<EMAIL>')
44
+ .replace(/\b(sk|rk|pk)_[A-Za-z0-9]+\b/g, '<TOKEN>');
45
+ }
46
+ export class TrajectoryDatabase {
47
+ workspaceDir;
48
+ stateDir;
49
+ dbPath;
50
+ blobDir;
51
+ exportDir;
52
+ blobInlineThresholdBytes;
53
+ orphanBlobGraceMs;
54
+ db;
55
+ constructor(opts) {
56
+ this.workspaceDir = path.resolve(opts.workspaceDir);
57
+ this.stateDir = resolvePdPath(this.workspaceDir, 'STATE_DIR');
58
+ this.dbPath = resolvePdPath(this.workspaceDir, 'TRAJECTORY_DB');
59
+ this.blobDir = resolvePdPath(this.workspaceDir, 'TRAJECTORY_BLOBS_DIR');
60
+ this.exportDir = resolvePdPath(this.workspaceDir, 'EXPORTS_DIR');
61
+ this.blobInlineThresholdBytes = opts.blobInlineThresholdBytes ?? DEFAULT_INLINE_THRESHOLD;
62
+ this.orphanBlobGraceMs = Math.max(0, (opts.orphanBlobGraceDays ?? DEFAULT_ORPHAN_BLOB_GRACE_DAYS) * 24 * 60 * 60 * 1000);
63
+ fs.mkdirSync(this.stateDir, { recursive: true });
64
+ fs.mkdirSync(this.blobDir, { recursive: true });
65
+ fs.mkdirSync(this.exportDir, { recursive: true });
66
+ this.db = new Database(this.dbPath);
67
+ this.db.pragma('journal_mode = WAL');
68
+ this.db.pragma('foreign_keys = ON');
69
+ this.db.pragma('synchronous = NORMAL');
70
+ this.db.pragma(`busy_timeout = ${Math.max(0, opts.busyTimeoutMs ?? DEFAULT_BUSY_TIMEOUT_MS)}`);
71
+ this.initSchema();
72
+ this.importLegacyArtifacts();
73
+ this.pruneUnreferencedBlobs();
74
+ }
75
+ dispose() {
76
+ this.db.close();
77
+ }
78
+ recordSession(input) {
79
+ const startedAt = input.startedAt ?? nowIso();
80
+ this.withWrite(() => {
81
+ this.db.prepare(`
82
+ INSERT INTO sessions (session_id, started_at, updated_at)
83
+ VALUES (?, ?, ?)
84
+ ON CONFLICT(session_id) DO UPDATE SET updated_at = excluded.updated_at
85
+ `).run(input.sessionId, startedAt, nowIso());
86
+ });
87
+ }
88
+ recordAssistantTurn(input) {
89
+ this.recordSession({ sessionId: input.sessionId, startedAt: input.createdAt });
90
+ const rawStorage = this.storeRawText('assistant', input.rawText);
91
+ const createdAt = input.createdAt ?? nowIso();
92
+ return this.withWrite(() => {
93
+ const result = this.db.prepare(`
94
+ INSERT INTO assistant_turns (
95
+ session_id, run_id, provider, model, raw_text, sanitized_text, usage_json,
96
+ empathy_signal_json, blob_ref, raw_excerpt, created_at
97
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
98
+ `).run(input.sessionId, input.runId, input.provider, input.model, rawStorage.inlineText, input.sanitizedText, safeJson(input.usageJson), safeJson(input.empathySignalJson), rawStorage.blobRef, rawStorage.excerpt, createdAt);
99
+ return Number(result.lastInsertRowid);
100
+ });
101
+ }
102
+ recordUserTurn(input) {
103
+ this.recordSession({ sessionId: input.sessionId, startedAt: input.createdAt });
104
+ const rawStorage = this.storeRawText('user', input.rawText);
105
+ const createdAt = input.createdAt ?? nowIso();
106
+ return this.withWrite(() => {
107
+ const result = this.db.prepare(`
108
+ INSERT INTO user_turns (
109
+ session_id, turn_index, raw_text, blob_ref, raw_excerpt,
110
+ correction_detected, correction_cue, references_assistant_turn_id, created_at
111
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
112
+ `).run(input.sessionId, input.turnIndex, rawStorage.inlineText, rawStorage.blobRef, rawStorage.excerpt, input.correctionDetected ? 1 : 0, input.correctionCue ?? null, input.referencesAssistantTurnId ?? null, createdAt);
113
+ return Number(result.lastInsertRowid);
114
+ });
115
+ }
116
+ recordToolCall(input) {
117
+ this.recordSession({ sessionId: input.sessionId, startedAt: input.createdAt });
118
+ const createdAt = input.createdAt ?? nowIso();
119
+ const rowId = this.withWrite(() => {
120
+ const result = this.db.prepare(`
121
+ INSERT INTO tool_calls (
122
+ session_id, tool_name, outcome, duration_ms, exit_code, error_type, error_message,
123
+ gfi_before, gfi_after, params_json, created_at
124
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
125
+ `).run(input.sessionId, input.toolName, input.outcome, input.durationMs ?? null, input.exitCode ?? null, input.errorType ?? null, input.errorMessage ?? null, input.gfiBefore ?? null, input.gfiAfter ?? null, safeJson(input.paramsJson), createdAt);
126
+ return Number(result.lastInsertRowid);
127
+ });
128
+ if (input.outcome === 'success') {
129
+ this.maybeCreateCorrectionSample(input.sessionId);
130
+ }
131
+ return rowId;
132
+ }
133
+ recordPainEvent(input) {
134
+ this.recordSession({ sessionId: input.sessionId, startedAt: input.createdAt });
135
+ let insertedId = -1;
136
+ this.withWrite(() => {
137
+ // Try INSERT; on UNIQUE constraint violation for canonical_pain_id, do UPDATE instead.
138
+ // SQLite UPSERT (ON CONFLICT) does not support partial unique indexes, so we
139
+ // handle the conflict manually.
140
+ try {
141
+ const runResult = this.db.prepare(`
142
+ INSERT INTO pain_events (
143
+ session_id, source, score, reason, severity, origin, confidence, text, created_at,
144
+ canonical_pain_id, runtime_task_id
145
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
146
+ `).run(input.sessionId, input.source, input.score, input.reason ?? null, input.severity ?? null, input.origin ?? null, input.confidence ?? null, input.text ?? null, input.createdAt ?? nowIso(), input.canonicalPainId ?? null, input.runtimeTaskId ?? null);
147
+ insertedId = Number(runResult.lastInsertRowid);
148
+ }
149
+ catch (insertErr) {
150
+ if (input.canonicalPainId &&
151
+ insertErr instanceof Error &&
152
+ insertErr.message.includes('UNIQUE constraint failed') &&
153
+ insertErr.message.includes('canonical_pain_id')) {
154
+ this.db.prepare(`
155
+ UPDATE pain_events
156
+ SET runtime_task_id = COALESCE(?, runtime_task_id)
157
+ WHERE canonical_pain_id = ?
158
+ `).run(input.runtimeTaskId ?? null, input.canonicalPainId);
159
+ const rawRow = this.db.prepare('SELECT id FROM pain_events WHERE canonical_pain_id = ?').get(input.canonicalPainId);
160
+ // Runtime Contract #1/#2: validate DB row instead of `as` cast
161
+ if (rawRow && typeof rawRow === 'object' && Object.hasOwn(rawRow, 'id') && typeof rawRow.id === 'number') {
162
+ insertedId = rawRow.id;
163
+ }
164
+ else {
165
+ insertedId = -1;
166
+ }
167
+ }
168
+ else {
169
+ throw insertErr;
170
+ }
171
+ }
172
+ });
173
+ // FTS indexing is best-effort — run outside the transaction so it cannot
174
+ // roll back the committed pain event row (MEM-03, MEM-04).
175
+ if (input.text && insertedId > 0) {
176
+ try {
177
+ this.db.prepare(`
178
+ INSERT INTO pain_events_fts (text, pain_event_id) VALUES (?, ?)
179
+ `).run(input.text, insertedId);
180
+ }
181
+ catch (err) {
182
+ // Non-fatal: FTS index is for search convenience, not correctness.
183
+ // Log but do not re-throw — the pain event itself is already committed.
184
+ console.warn(`[trajectory] FTS index insert failed for pain_event ${insertedId}: ${String(err)}`);
185
+ }
186
+ }
187
+ return insertedId;
188
+ }
189
+ /**
190
+ * Search pain_events using FTS5 full-text search (MEM-04).
191
+ * Returns pain events matching the query, ordered by relevance.
192
+ */
193
+ searchPainEvents(query, limit = 10) {
194
+ if (!query || query.trim().length === 0) {
195
+ return [];
196
+ }
197
+ // Escape FTS5 special characters and format query for porter tokenizer
198
+ const ftsQuery = query.trim().split(/\s+/).map(term => `"${term.replace(/"/g, '""')}"`).join(' ');
199
+ try {
200
+ const results = this.db.prepare(`
201
+ SELECT pe.*
202
+ FROM pain_events_fts pf
203
+ JOIN pain_events pe ON pe.id = pf.pain_event_id
204
+ WHERE pain_events_fts MATCH ?
205
+ ORDER BY bm25(pain_events_fts) DESC
206
+ LIMIT ?
207
+ `).all(ftsQuery, limit);
208
+ return results.map(row => ({
209
+ id: row.id,
210
+ sessionId: row.session_id,
211
+ source: row.source,
212
+ score: row.score,
213
+ reason: row.reason,
214
+ severity: row.severity,
215
+ origin: row.origin,
216
+ confidence: row.confidence,
217
+ text: row.text,
218
+ createdAt: row.created_at,
219
+ }));
220
+ }
221
+ catch (err) {
222
+ // If FTS5 query fails (e.g., syntax error), return empty results
223
+ console.warn(`[PD:TrajectoryDatabase] FTS5 search failed: ${String(err)}`);
224
+ return [];
225
+ }
226
+ }
227
+ recordGateBlock(input) {
228
+ this.withWrite(() => {
229
+ this.db.prepare(`
230
+ INSERT INTO gate_blocks (session_id, tool_name, file_path, reason, plan_status, created_at)
231
+ VALUES (?, ?, ?, ?, ?, ?)
232
+ `).run(input.sessionId ?? null, input.toolName, input.filePath ?? null, input.reason, input.planStatus ?? null, input.createdAt ?? nowIso());
233
+ });
234
+ }
235
+ recordTrustChange(input) {
236
+ this.withWrite(() => {
237
+ this.db.prepare(`
238
+ INSERT INTO trust_changes (session_id, previous_score, new_score, delta, reason, created_at)
239
+ VALUES (?, ?, ?, ?, ?, ?)
240
+ `).run(input.sessionId ?? null, input.previousScore, input.newScore, input.delta, input.reason, input.createdAt ?? nowIso());
241
+ });
242
+ }
243
+ recordPrincipleEvent(input) {
244
+ this.withWrite(() => {
245
+ this.db.prepare(`
246
+ INSERT INTO principle_events (principle_id, event_type, payload_json, created_at)
247
+ VALUES (?, ?, ?, ?)
248
+ `).run(input.principleId ?? null, input.eventType, safeJson(input.payload), input.createdAt ?? nowIso());
249
+ });
250
+ }
251
+ recordTaskOutcome(input) {
252
+ this.withWrite(() => {
253
+ this.db.prepare(`
254
+ INSERT INTO task_outcomes (session_id, task_id, outcome, summary, principle_ids_json, created_at)
255
+ VALUES (?, ?, ?, ?, ?, ?)
256
+ `).run(input.sessionId, input.taskId ?? null, input.outcome, input.summary ?? null, safeJson(input.principleIdsJson), input.createdAt ?? nowIso());
257
+ });
258
+ }
259
+ recordEvolutionTask(input) {
260
+ const now = nowIso();
261
+ // Cast to V2 to access new fields
262
+ const v2 = input;
263
+ this.withWrite(() => {
264
+ this.db.prepare(`
265
+ INSERT INTO evolution_tasks (
266
+ task_id, trace_id, source, reason, score, status,
267
+ enqueued_at, started_at, completed_at, resolution, created_at, updated_at,
268
+ task_kind, priority, retry_count, max_retries, last_error, result_ref
269
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
270
+ ON CONFLICT(task_id) DO UPDATE SET
271
+ status = excluded.status,
272
+ started_at = excluded.started_at,
273
+ completed_at = excluded.completed_at,
274
+ resolution = excluded.resolution,
275
+ updated_at = excluded.updated_at,
276
+ task_kind = excluded.task_kind,
277
+ priority = excluded.priority,
278
+ retry_count = excluded.retry_count,
279
+ max_retries = excluded.max_retries,
280
+ last_error = excluded.last_error,
281
+ result_ref = excluded.result_ref
282
+ `).run(input.taskId, input.traceId, input.source, input.reason ?? null, input.score ?? 0, input.status ?? 'pending', input.enqueuedAt ?? null, input.startedAt ?? null, input.completedAt ?? null, input.resolution ?? null, input.createdAt ?? now, input.updatedAt ?? now, v2.taskKind ?? null, v2.priority ?? null, v2.retryCount ?? null, v2.maxRetries ?? null, v2.lastError ?? null, v2.resultRef ?? null);
283
+ });
284
+ }
285
+ updateEvolutionTask(taskId, updates) {
286
+ const now = nowIso();
287
+ // Cast to V2 to access new fields
288
+ const v2Updates = updates;
289
+ this.withWrite(() => {
290
+ const setClauses = ['updated_at = ?'];
291
+ const values = [now];
292
+ if (updates.status !== undefined) {
293
+ setClauses.push('status = ?');
294
+ values.push(updates.status);
295
+ }
296
+ if (updates.startedAt !== undefined) {
297
+ setClauses.push('started_at = ?');
298
+ values.push(updates.startedAt);
299
+ }
300
+ if (updates.completedAt !== undefined) {
301
+ setClauses.push('completed_at = ?');
302
+ values.push(updates.completedAt);
303
+ }
304
+ if (updates.resolution !== undefined) {
305
+ setClauses.push('resolution = ?');
306
+ values.push(updates.resolution);
307
+ }
308
+ if (updates.score !== undefined) {
309
+ setClauses.push('score = ?');
310
+ values.push(updates.score);
311
+ }
312
+ // V2 fields
313
+ if (v2Updates.taskKind !== undefined) {
314
+ setClauses.push('task_kind = ?');
315
+ values.push(v2Updates.taskKind);
316
+ }
317
+ if (v2Updates.priority !== undefined) {
318
+ setClauses.push('priority = ?');
319
+ values.push(v2Updates.priority);
320
+ }
321
+ if (v2Updates.retryCount !== undefined) {
322
+ setClauses.push('retry_count = ?');
323
+ values.push(v2Updates.retryCount);
324
+ }
325
+ if (v2Updates.maxRetries !== undefined) {
326
+ setClauses.push('max_retries = ?');
327
+ values.push(v2Updates.maxRetries);
328
+ }
329
+ if (v2Updates.lastError !== undefined) {
330
+ setClauses.push('last_error = ?');
331
+ values.push(v2Updates.lastError);
332
+ }
333
+ if (v2Updates.resultRef !== undefined) {
334
+ setClauses.push('result_ref = ?');
335
+ values.push(v2Updates.resultRef);
336
+ }
337
+ values.push(taskId);
338
+ this.db.prepare(`
339
+ UPDATE evolution_tasks SET ${setClauses.join(', ')} WHERE task_id = ?
340
+ `).run(...values);
341
+ });
342
+ }
343
+ recordEvolutionEvent(input) {
344
+ this.withWrite(() => {
345
+ this.db.prepare(`
346
+ INSERT INTO evolution_events (trace_id, task_id, stage, level, message, summary, metadata_json, created_at)
347
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)
348
+ `).run(input.traceId, input.taskId ?? null, input.stage, input.level ?? 'info', input.message, input.summary ?? null, safeJson(input.metadata), input.createdAt ?? nowIso());
349
+ });
350
+ }
351
+ /**
352
+ * List evolution tasks with optional filtering.
353
+ *
354
+ * Returns: Analytics data aggregated from trajectory database.
355
+ * Not: Runtime truth or real-time queue state.
356
+ */
357
+ listEvolutionTasks(filters = {}) {
358
+ const conditions = [];
359
+ const values = [];
360
+ if (filters.status) {
361
+ conditions.push('status = ?');
362
+ values.push(filters.status);
363
+ }
364
+ if (filters.dateFrom) {
365
+ conditions.push('created_at >= ?');
366
+ values.push(filters.dateFrom);
367
+ }
368
+ if (filters.dateTo) {
369
+ conditions.push('created_at <= ?');
370
+ values.push(filters.dateTo);
371
+ }
372
+ const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : '';
373
+ const limit = filters.limit ?? 50;
374
+ const offset = filters.offset ?? 0;
375
+ const rows = this.db.prepare(`
376
+ SELECT id, task_id, trace_id, source, reason, score, status,
377
+ enqueued_at, started_at, completed_at, resolution, created_at, updated_at,
378
+ task_kind, priority, retry_count, max_retries, last_error, result_ref
379
+ FROM evolution_tasks
380
+ ${whereClause}
381
+ ORDER BY created_at DESC
382
+ LIMIT ? OFFSET ?
383
+ `).all(...values, limit, offset);
384
+ return rows.map((row) => ({
385
+ id: Number(row.id),
386
+ taskId: String(row.task_id),
387
+ traceId: String(row.trace_id),
388
+ source: String(row.source),
389
+ reason: row.reason ? String(row.reason) : null,
390
+ score: Number(row.score ?? 0),
391
+ status: String(row.status),
392
+ enqueuedAt: row.enqueued_at ? String(row.enqueued_at) : null,
393
+ startedAt: row.started_at ? String(row.started_at) : null,
394
+ completedAt: row.completed_at ? String(row.completed_at) : null,
395
+ resolution: row.resolution ? String(row.resolution) : null,
396
+ createdAt: String(row.created_at),
397
+ updatedAt: String(row.updated_at),
398
+ taskKind: row.task_kind ? row.task_kind : null,
399
+ priority: row.priority ? row.priority : null,
400
+ retryCount: row.retry_count != null ? Number(row.retry_count) : null,
401
+ maxRetries: row.max_retries != null ? Number(row.max_retries) : null,
402
+ lastError: row.last_error ? String(row.last_error) : null,
403
+ resultRef: row.result_ref ? String(row.result_ref) : null,
404
+ }));
405
+ }
406
+ /**
407
+ * List evolution events for a trace or globally.
408
+ *
409
+ * Returns: Analytics data aggregated from trajectory database.
410
+ * Not: Runtime truth or real-time queue state.
411
+ */
412
+ listEvolutionEvents(traceId, filters = {}) {
413
+ const limit = filters.limit ?? 100;
414
+ const offset = filters.offset ?? 0;
415
+ let rows;
416
+ if (traceId) {
417
+ rows = this.db.prepare(`
418
+ SELECT id, trace_id, task_id, stage, level, message, summary, metadata_json, created_at
419
+ FROM evolution_events
420
+ WHERE trace_id = ?
421
+ ORDER BY created_at ASC
422
+ LIMIT ? OFFSET ?
423
+ `).all(traceId, limit, offset);
424
+ }
425
+ else {
426
+ rows = this.db.prepare(`
427
+ SELECT id, trace_id, task_id, stage, level, message, summary, metadata_json, created_at
428
+ FROM evolution_events
429
+ ORDER BY created_at DESC
430
+ LIMIT ? OFFSET ?
431
+ `).all(limit, offset);
432
+ }
433
+ return rows.map((row) => ({
434
+ id: Number(row.id),
435
+ traceId: String(row.trace_id),
436
+ taskId: row.task_id ? String(row.task_id) : null,
437
+ stage: String(row.stage),
438
+ level: String(row.level ?? 'info'),
439
+ message: String(row.message),
440
+ summary: row.summary ? String(row.summary) : null,
441
+ metadata: JSON.parse(String(row.metadata_json ?? '{}')),
442
+ createdAt: String(row.created_at),
443
+ }));
444
+ }
445
+ /**
446
+ * Get evolution task by trace ID.
447
+ *
448
+ * Returns: Analytics data aggregated from trajectory database.
449
+ * Not: Runtime truth or real-time queue state.
450
+ */
451
+ getEvolutionTaskByTraceId(traceId) {
452
+ const row = this.db.prepare(`
453
+ SELECT id, task_id, trace_id, source, reason, score, status,
454
+ enqueued_at, started_at, completed_at, resolution, created_at, updated_at,
455
+ task_kind, priority, retry_count, max_retries, last_error, result_ref
456
+ FROM evolution_tasks
457
+ WHERE trace_id = ?
458
+ LIMIT 1
459
+ `).get(traceId);
460
+ if (!row)
461
+ return null;
462
+ return {
463
+ id: Number(row.id),
464
+ taskId: String(row.task_id),
465
+ traceId: String(row.trace_id),
466
+ source: String(row.source),
467
+ reason: row.reason ? String(row.reason) : null,
468
+ score: Number(row.score ?? 0),
469
+ status: String(row.status),
470
+ enqueuedAt: row.enqueued_at ? String(row.enqueued_at) : null,
471
+ startedAt: row.started_at ? String(row.started_at) : null,
472
+ completedAt: row.completed_at ? String(row.completed_at) : null,
473
+ resolution: row.resolution ? String(row.resolution) : null,
474
+ createdAt: String(row.created_at),
475
+ updatedAt: String(row.updated_at),
476
+ taskKind: row.task_kind ? row.task_kind : null,
477
+ priority: row.priority ? row.priority : null,
478
+ retryCount: row.retry_count != null ? Number(row.retry_count) : null,
479
+ maxRetries: row.max_retries != null ? Number(row.max_retries) : null,
480
+ lastError: row.last_error ? String(row.last_error) : null,
481
+ resultRef: row.result_ref ? String(row.result_ref) : null,
482
+ };
483
+ }
484
+ /**
485
+ * Get evolution task statistics.
486
+ *
487
+ * Returns: Analytics data aggregated from trajectory database.
488
+ * Not: Runtime truth or real-time queue state.
489
+ */
490
+ getEvolutionStats() {
491
+ const rows = this.db.prepare(`
492
+ SELECT status, COUNT(*) as count FROM evolution_tasks GROUP BY status
493
+ `).all();
494
+ const stats = { total: 0, pending: 0, inProgress: 0, completed: 0, failed: 0 };
495
+ for (const row of rows) {
496
+ stats.total += row.count;
497
+ if (row.status === 'pending')
498
+ stats.pending = row.count;
499
+ else if (row.status === 'in_progress')
500
+ stats.inProgress = row.count;
501
+ else if (row.status === 'completed')
502
+ stats.completed = row.count;
503
+ else if (row.status === 'failed')
504
+ stats.failed = row.count;
505
+ }
506
+ return stats;
507
+ }
508
+ /**
509
+ * List recent sessions from the trajectory database.
510
+ *
511
+ * Returns: Recent session records ordered by most recently updated.
512
+ *
513
+ * @param options.limit - Maximum number of sessions to return (default: 20)
514
+ * @param options.dateFrom - Only return sessions updated after this date
515
+ * @param options.dateTo - Only return sessions updated before this date
516
+ */
517
+ listRecentSessions(options = {}) {
518
+ const conditions = [];
519
+ const values = [];
520
+ if (options.dateFrom) {
521
+ conditions.push('updated_at >= ?');
522
+ values.push(options.dateFrom);
523
+ }
524
+ if (options.dateTo) {
525
+ conditions.push('updated_at <= ?');
526
+ values.push(options.dateTo);
527
+ }
528
+ const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : '';
529
+ const limit = options.limit ?? 20;
530
+ const rows = this.db.prepare(`
531
+ SELECT session_id, started_at, updated_at
532
+ FROM sessions
533
+ ${whereClause}
534
+ ORDER BY updated_at DESC
535
+ LIMIT ?
536
+ `).all(...values, limit);
537
+ return rows.map((row) => ({
538
+ sessionId: String(row.session_id),
539
+ startedAt: String(row.started_at),
540
+ updatedAt: String(row.updated_at),
541
+ }));
542
+ }
543
+ /**
544
+ * List assistant turns for a session.
545
+ *
546
+ * Returns: Analytics data aggregated from trajectory database.
547
+ * Not: Runtime truth or real-time queue state.
548
+ */
549
+ listAssistantTurns(sessionId) {
550
+ const rows = this.db.prepare(`
551
+ SELECT id, session_id, run_id, provider, model, raw_text, sanitized_text, blob_ref, created_at
552
+ FROM assistant_turns
553
+ WHERE session_id = ?
554
+ ORDER BY id ASC
555
+ `).all(sessionId);
556
+ return rows.map((row) => ({
557
+ id: Number(row.id),
558
+ sessionId: String(row.session_id),
559
+ runId: String(row.run_id),
560
+ provider: String(row.provider),
561
+ model: String(row.model),
562
+ rawText: this.restoreRawText(row.raw_text, row.blob_ref),
563
+ sanitizedText: String(row.sanitized_text ?? ''),
564
+ blobRef: row.blob_ref ? String(row.blob_ref) : null,
565
+ createdAt: String(row.created_at),
566
+ }));
567
+ }
568
+ /**
569
+ * List tool calls for a session.
570
+ *
571
+ * Returns: Analytics data aggregated from trajectory database.
572
+ * Not: Runtime truth or real-time queue state.
573
+ */
574
+ listToolCallsForSession(sessionId) {
575
+ const rows = this.db.prepare(`
576
+ SELECT id, tool_name, outcome, params_json, duration_ms, exit_code, error_type, error_message,
577
+ gfi_before, gfi_after, created_at
578
+ FROM tool_calls
579
+ WHERE session_id = ?
580
+ ORDER BY id ASC
581
+ `).all(sessionId);
582
+ return rows.map((row) => {
583
+ // Extract filePath from params_json if present
584
+ let filePath = null;
585
+ if (row.params_json && typeof row.params_json === 'string') {
586
+ try {
587
+ const params = JSON.parse(row.params_json);
588
+ if (params && typeof params.filePath === 'string') {
589
+ filePath = params.filePath;
590
+ }
591
+ }
592
+ catch {
593
+ // Ignore malformed JSON
594
+ }
595
+ }
596
+ return {
597
+ id: Number(row.id),
598
+ toolName: String(row.tool_name),
599
+ outcome: String(row.outcome),
600
+ filePath,
601
+ durationMs: row.duration_ms != null ? Number(row.duration_ms) : null,
602
+ exitCode: row.exit_code != null ? Number(row.exit_code) : null,
603
+ errorType: row.error_type ? String(row.error_type) : null,
604
+ errorMessage: row.error_message ? String(row.error_message) : null,
605
+ gfiBefore: row.gfi_before != null ? Number(row.gfi_before) : null,
606
+ gfiAfter: row.gfi_after != null ? Number(row.gfi_after) : null,
607
+ createdAt: String(row.created_at),
608
+ };
609
+ });
610
+ }
611
+ /**
612
+ * List pain events for a session.
613
+ *
614
+ * Returns: Analytics data aggregated from trajectory database.
615
+ * Not: Runtime truth or real-time queue state.
616
+ */
617
+ listPainEventsForSession(sessionId) {
618
+ const rows = this.db.prepare(`
619
+ SELECT id, source, score, reason, severity, origin, confidence, created_at
620
+ FROM pain_events
621
+ WHERE session_id = ?
622
+ ORDER BY created_at ASC
623
+ `).all(sessionId);
624
+ return rows.map((row) => ({
625
+ id: Number(row.id),
626
+ source: String(row.source),
627
+ score: Number(row.score),
628
+ reason: row.reason ? String(row.reason) : null,
629
+ severity: row.severity ? String(row.severity) : null,
630
+ origin: row.origin ? String(row.origin) : null,
631
+ confidence: row.confidence != null ? Number(row.confidence) : null,
632
+ createdAt: String(row.created_at),
633
+ }));
634
+ }
635
+ /**
636
+ * List user turns for a session.
637
+ * Returns sanitized/reduced fields for nocturnal use — NO raw text.
638
+ */
639
+ listUserTurnsForSession(sessionId) {
640
+ const rows = this.db.prepare(`
641
+ SELECT id, turn_index, raw_excerpt, correction_detected, correction_cue, created_at
642
+ FROM user_turns
643
+ WHERE session_id = ?
644
+ ORDER BY turn_index ASC
645
+ `).all(sessionId);
646
+ return rows.map((row) => ({
647
+ id: Number(row.id),
648
+ turnIndex: Number(row.turn_index),
649
+ rawExcerpt: String(row.raw_excerpt ?? ''),
650
+ correctionDetected: Boolean(row.correction_detected),
651
+ correctionCue: row.correction_cue ? String(row.correction_cue) : null,
652
+ createdAt: String(row.created_at),
653
+ }));
654
+ }
655
+ /**
656
+ * List correction samples with optional review status filter.
657
+ *
658
+ * Returns: Analytics data aggregated from trajectory database.
659
+ * Not: Runtime truth or real-time queue state.
660
+ */
661
+ listCorrectionSamples(status = 'pending') {
662
+ const rows = this.db.prepare(`
663
+ SELECT sample_id, session_id, bad_assistant_turn_id, user_correction_turn_id,
664
+ recovery_tool_span_json, diff_excerpt, principle_ids_json, quality_score,
665
+ review_status, export_mode, created_at, updated_at
666
+ FROM correction_samples
667
+ WHERE review_status = ?
668
+ ORDER BY created_at DESC
669
+ `).all(status);
670
+ return rows.map((row) => ({
671
+ sampleId: String(row.sample_id),
672
+ sessionId: String(row.session_id),
673
+ badAssistantTurnId: Number(row.bad_assistant_turn_id),
674
+ userCorrectionTurnId: Number(row.user_correction_turn_id),
675
+ recoveryToolSpanJson: String(row.recovery_tool_span_json),
676
+ diffExcerpt: String(row.diff_excerpt ?? ''),
677
+ principleIdsJson: String(row.principle_ids_json ?? '[]'),
678
+ qualityScore: Number(row.quality_score),
679
+ reviewStatus: row.review_status,
680
+ exportMode: row.export_mode,
681
+ createdAt: String(row.created_at),
682
+ updatedAt: String(row.updated_at),
683
+ }));
684
+ }
685
+ /**
686
+ * List gate blocks for a session.
687
+ * Returns minimal fields for nocturnal use — no raw text.
688
+ */
689
+ listGateBlocksForSession(sessionId) {
690
+ const rows = this.db.prepare(`
691
+ SELECT id, tool_name, file_path, reason, plan_status, created_at
692
+ FROM gate_blocks
693
+ WHERE session_id = ?
694
+ ORDER BY id ASC
695
+ `).all(sessionId);
696
+ return rows.map((row) => ({
697
+ id: Number(row.id),
698
+ toolName: String(row.tool_name),
699
+ filePath: row.file_path ? String(row.file_path) : null,
700
+ reason: String(row.reason),
701
+ planStatus: row.plan_status ? String(row.plan_status) : null,
702
+ createdAt: String(row.created_at),
703
+ }));
704
+ }
705
+ /**
706
+ * List correction samples for a specific session.
707
+ * Returns minimal fields for nocturnal use — correction cue only.
708
+ * #268: Wire correction_samples into nocturnal pipeline.
709
+ */
710
+ listCorrectionSamplesForSession(sessionId) {
711
+ const rows = this.db.prepare(`
712
+ SELECT cs.sample_id, ut.correction_cue
713
+ FROM correction_samples cs
714
+ LEFT JOIN user_turns ut ON ut.id = cs.user_correction_turn_id
715
+ WHERE cs.session_id = ?
716
+ ORDER BY cs.created_at DESC
717
+ `).all(sessionId);
718
+ return rows.map((row) => ({
719
+ correctionCue: row.correction_cue ? String(row.correction_cue) : null,
720
+ }));
721
+ }
722
+ reviewCorrectionSample(sampleId, status, note) {
723
+ const updatedAt = nowIso();
724
+ const updated = this.withWrite(() => {
725
+ const updateResult = this.db.prepare(`
726
+ UPDATE correction_samples
727
+ SET review_status = ?, updated_at = ?
728
+ WHERE sample_id = ?
729
+ `).run(status, updatedAt, sampleId);
730
+ if (updateResult.changes === 0) {
731
+ return false;
732
+ }
733
+ this.db.prepare(`
734
+ INSERT INTO sample_reviews (sample_id, review_status, note, created_at)
735
+ VALUES (?, ?, ?, ?)
736
+ `).run(sampleId, status, note ?? null, updatedAt);
737
+ return true;
738
+ });
739
+ if (!updated) {
740
+ throw new SampleNotFoundError(sampleId);
741
+ }
742
+ const record = this.db.prepare(`
743
+ SELECT sample_id, session_id, bad_assistant_turn_id, user_correction_turn_id,
744
+ recovery_tool_span_json, diff_excerpt, principle_ids_json, quality_score,
745
+ review_status, export_mode, created_at, updated_at
746
+ FROM correction_samples
747
+ WHERE sample_id = ?
748
+ `).get(sampleId);
749
+ if (!record) {
750
+ throw new SampleNotFoundError(`${sampleId} (after update)`);
751
+ }
752
+ // #Phase2b: Emit pain event for rejected corrections
753
+ if (status === 'rejected') {
754
+ this.recordCorrectionRejectedPain({
755
+ session_id: record.session_id,
756
+ quality_score: record.quality_score,
757
+ diff_excerpt: record.diff_excerpt,
758
+ principle_ids_json: record.principle_ids_json,
759
+ created_at: record.created_at,
760
+ });
761
+ }
762
+ return {
763
+ sampleId: String(record.sample_id),
764
+ sessionId: String(record.session_id),
765
+ badAssistantTurnId: Number(record.bad_assistant_turn_id),
766
+ userCorrectionTurnId: Number(record.user_correction_turn_id),
767
+ recoveryToolSpanJson: String(record.recovery_tool_span_json),
768
+ diffExcerpt: String(record.diff_excerpt ?? ''),
769
+ principleIdsJson: String(record.principle_ids_json ?? '[]'),
770
+ qualityScore: Number(record.quality_score),
771
+ reviewStatus: record.review_status,
772
+ exportMode: record.export_mode,
773
+ createdAt: String(record.created_at),
774
+ updatedAt: String(record.updated_at),
775
+ };
776
+ }
777
+ /**
778
+ * When a correction sample is rejected, emit a pain event to the trajectory.
779
+ * This feeds rejected corrections into the nocturnal pipeline as a high-fidelity
780
+ * violation signal (human-verified, unlike heuristic pain detection).
781
+ */
782
+ recordCorrectionRejectedPain(record) {
783
+ const sessionId = String(record.session_id);
784
+ const qualityScore = Number(record.quality_score);
785
+ const diffExcerpt = String(record.diff_excerpt ?? '');
786
+ const principleIds = String(record.principle_ids_json ?? '[]');
787
+ // quality_score (0-100) from correction sample → pain score (0-100), clamped
788
+ const painScore = Math.max(0, Math.min(100, Math.round(Number(qualityScore) || 0)));
789
+ const reason = `Correction rejected (quality ${qualityScore.toFixed(2)}). Principles: ${principleIds}${diffExcerpt ? ` — ${diffExcerpt.slice(0, 120)}` : ''}`;
790
+ try {
791
+ this.recordPainEvent({
792
+ sessionId,
793
+ source: 'correction_rejected',
794
+ score: painScore,
795
+ reason,
796
+ severity: painScore >= 70 ? 'severe' : painScore >= 40 ? 'moderate' : 'mild',
797
+ origin: 'system_infer',
798
+ text: diffExcerpt || undefined,
799
+ createdAt: String(record.created_at),
800
+ });
801
+ }
802
+ catch (err) {
803
+ // Non-fatal: pain event recording should not break the review flow
804
+ console.warn(`[Trajectory] Failed to record correction_rejected pain event: ${String(err)}`);
805
+ }
806
+ }
807
+ /**
808
+ * Export correction samples to JSONL file.
809
+ *
810
+ * Returns: Analytics data aggregated from trajectory database.
811
+ * Not: Runtime truth or real-time queue state.
812
+ */
813
+ exportCorrections(opts) {
814
+ const rows = this.db.prepare(`
815
+ SELECT cs.sample_id, cs.session_id, cs.recovery_tool_span_json, cs.diff_excerpt, cs.quality_score,
816
+ at.raw_text AS assistant_raw_text, at.blob_ref AS assistant_blob_ref, at.sanitized_text,
817
+ ut.raw_text AS user_raw_text, ut.blob_ref AS user_blob_ref, ut.correction_cue
818
+ FROM correction_samples cs
819
+ JOIN assistant_turns at ON at.id = cs.bad_assistant_turn_id
820
+ JOIN user_turns ut ON ut.id = cs.user_correction_turn_id
821
+ WHERE (? = 0 OR cs.review_status = 'approved')
822
+ ORDER BY cs.created_at ASC
823
+ `).all(opts.approvedOnly ? 1 : 0);
824
+ const exportPath = path.join(this.exportDir, `corrections-${Date.now()}-${opts.mode}.jsonl`);
825
+ const lines = rows.map((row) => {
826
+ const assistantRaw = this.restoreRawText(row.assistant_raw_text, row.assistant_blob_ref);
827
+ const userRaw = this.restoreRawText(row.user_raw_text, row.user_blob_ref);
828
+ const assistantText = opts.mode === 'redacted' ? redactText(assistantRaw) : assistantRaw;
829
+ const userText = opts.mode === 'redacted' ? redactText(userRaw) : userRaw;
830
+ return JSON.stringify({
831
+ sample_id: row.sample_id,
832
+ session_id: row.session_id,
833
+ instruction: userText,
834
+ input_context: assistantText,
835
+ bad_attempt_summary: String(row.diff_excerpt ?? ''),
836
+ preferred_response: userText,
837
+ labels: {
838
+ correction_cue: row.correction_cue,
839
+ quality_score: row.quality_score,
840
+ },
841
+ metadata: {
842
+ mode: opts.mode,
843
+ recovery_tool_span_json: row.recovery_tool_span_json,
844
+ },
845
+ });
846
+ });
847
+ atomicWriteFileSync(exportPath, `${lines.join('\n')}${lines.length > 0 ? '\n' : ''}`);
848
+ this.recordExportAudit('corrections', opts.mode, opts.approvedOnly, exportPath, rows.length);
849
+ return { filePath: exportPath, count: rows.length, mode: opts.mode };
850
+ }
851
+ /**
852
+ * Export analytics data to JSON file.
853
+ *
854
+ * Returns: Analytics data aggregated from trajectory database.
855
+ * Not: Runtime truth or real-time queue state.
856
+ */
857
+ exportAnalytics() {
858
+ const payload = {
859
+ generatedAt: nowIso(),
860
+ stats: this.getDataStats(),
861
+ dailyMetrics: this.dailyMetrics(),
862
+ errorClusters: this.db.prepare('SELECT * FROM v_error_clusters').all(),
863
+ principleEffectiveness: this.db.prepare('SELECT * FROM v_principle_effectiveness').all(),
864
+ sampleQueue: this.db.prepare('SELECT * FROM v_sample_queue').all(),
865
+ };
866
+ const exportPath = path.join(this.exportDir, `analytics-${Date.now()}.json`);
867
+ atomicWriteFileSync(exportPath, JSON.stringify(payload, null, 2));
868
+ this.recordExportAudit('analytics', 'raw', true, exportPath, Array.isArray(payload.dailyMetrics) ? payload.dailyMetrics.length : 0);
869
+ return { filePath: exportPath, count: Array.isArray(payload.dailyMetrics) ? payload.dailyMetrics.length : 0 };
870
+ }
871
+ /**
872
+ * Get trajectory database statistics.
873
+ *
874
+ * Returns: Analytics data aggregated from trajectory database.
875
+ * Not: Runtime truth or real-time queue state.
876
+ */
877
+ getDataStats() {
878
+ const getCount = (table, where) => {
879
+ const sql = where ? `SELECT COUNT(*) as count FROM ${table} WHERE ${where}` : `SELECT COUNT(*) as count FROM ${table}`;
880
+ return Number(this.db.prepare(sql).get().count);
881
+ };
882
+ const lastIngest = this.db.prepare(`
883
+ SELECT MAX(ts) AS ts FROM (
884
+ SELECT MAX(created_at) AS ts FROM assistant_turns
885
+ UNION ALL SELECT MAX(created_at) AS ts FROM user_turns
886
+ UNION ALL SELECT MAX(created_at) AS ts FROM tool_calls
887
+ UNION ALL SELECT MAX(created_at) AS ts FROM pain_events
888
+ )
889
+ `).get();
890
+ return {
891
+ dbPath: this.dbPath,
892
+ dbSizeBytes: fileSizeIfExists(this.dbPath),
893
+ assistantTurns: getCount('assistant_turns'),
894
+ userTurns: getCount('user_turns'),
895
+ toolCalls: getCount('tool_calls'),
896
+ painEvents: getCount('pain_events'),
897
+ pendingSamples: getCount('correction_samples', `review_status = 'pending'`),
898
+ approvedSamples: getCount('correction_samples', `review_status = 'approved'`),
899
+ blobBytes: this.computeBlobBytes(),
900
+ lastIngestAt: lastIngest.ts ?? null,
901
+ };
902
+ }
903
+ cleanupBlobStorage() {
904
+ return this.pruneUnreferencedBlobs();
905
+ }
906
+ initSchema() {
907
+ this.db.exec(`
908
+ CREATE TABLE IF NOT EXISTS schema_version (version INTEGER NOT NULL);
909
+ CREATE TABLE IF NOT EXISTS ingest_checkpoint (
910
+ source_key TEXT PRIMARY KEY,
911
+ imported_at TEXT NOT NULL
912
+ );
913
+ CREATE TABLE IF NOT EXISTS sessions (
914
+ session_id TEXT PRIMARY KEY,
915
+ started_at TEXT NOT NULL,
916
+ updated_at TEXT NOT NULL
917
+ );
918
+ CREATE TABLE IF NOT EXISTS assistant_turns (
919
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
920
+ session_id TEXT NOT NULL,
921
+ run_id TEXT NOT NULL,
922
+ provider TEXT NOT NULL,
923
+ model TEXT NOT NULL,
924
+ raw_text TEXT,
925
+ sanitized_text TEXT NOT NULL,
926
+ usage_json TEXT NOT NULL,
927
+ empathy_signal_json TEXT NOT NULL,
928
+ blob_ref TEXT,
929
+ raw_excerpt TEXT,
930
+ created_at TEXT NOT NULL
931
+ );
932
+ CREATE TABLE IF NOT EXISTS user_turns (
933
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
934
+ session_id TEXT NOT NULL,
935
+ turn_index INTEGER NOT NULL,
936
+ raw_text TEXT,
937
+ blob_ref TEXT,
938
+ raw_excerpt TEXT,
939
+ correction_detected INTEGER NOT NULL DEFAULT 0,
940
+ correction_cue TEXT,
941
+ references_assistant_turn_id INTEGER,
942
+ created_at TEXT NOT NULL
943
+ );
944
+ CREATE TABLE IF NOT EXISTS tool_calls (
945
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
946
+ session_id TEXT NOT NULL,
947
+ tool_name TEXT NOT NULL,
948
+ outcome TEXT NOT NULL,
949
+ duration_ms INTEGER,
950
+ exit_code INTEGER,
951
+ error_type TEXT,
952
+ error_message TEXT,
953
+ gfi_before REAL,
954
+ gfi_after REAL,
955
+ params_json TEXT NOT NULL,
956
+ created_at TEXT NOT NULL
957
+ );
958
+ CREATE TABLE IF NOT EXISTS pain_events (
959
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
960
+ session_id TEXT NOT NULL,
961
+ source TEXT NOT NULL,
962
+ score REAL NOT NULL,
963
+ reason TEXT,
964
+ severity TEXT,
965
+ origin TEXT,
966
+ confidence REAL,
967
+ text TEXT,
968
+ created_at TEXT NOT NULL
969
+ );
970
+ CREATE TABLE IF NOT EXISTS gate_blocks (
971
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
972
+ session_id TEXT,
973
+ tool_name TEXT NOT NULL,
974
+ file_path TEXT,
975
+ reason TEXT NOT NULL,
976
+ plan_status TEXT,
977
+ created_at TEXT NOT NULL
978
+ );
979
+ CREATE TABLE IF NOT EXISTS trust_changes (
980
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
981
+ session_id TEXT,
982
+ previous_score REAL NOT NULL,
983
+ new_score REAL NOT NULL,
984
+ delta REAL NOT NULL,
985
+ reason TEXT NOT NULL,
986
+ created_at TEXT NOT NULL
987
+ );
988
+ CREATE TABLE IF NOT EXISTS principle_events (
989
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
990
+ principle_id TEXT,
991
+ event_type TEXT NOT NULL,
992
+ payload_json TEXT NOT NULL,
993
+ created_at TEXT NOT NULL
994
+ );
995
+ CREATE TABLE IF NOT EXISTS task_outcomes (
996
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
997
+ session_id TEXT NOT NULL,
998
+ task_id TEXT,
999
+ outcome TEXT NOT NULL,
1000
+ summary TEXT,
1001
+ principle_ids_json TEXT NOT NULL,
1002
+ created_at TEXT NOT NULL
1003
+ );
1004
+ CREATE TABLE IF NOT EXISTS correction_samples (
1005
+ sample_id TEXT PRIMARY KEY,
1006
+ session_id TEXT NOT NULL,
1007
+ bad_assistant_turn_id INTEGER NOT NULL,
1008
+ user_correction_turn_id INTEGER NOT NULL,
1009
+ recovery_tool_span_json TEXT NOT NULL,
1010
+ diff_excerpt TEXT NOT NULL,
1011
+ principle_ids_json TEXT NOT NULL,
1012
+ quality_score REAL NOT NULL,
1013
+ review_status TEXT NOT NULL,
1014
+ export_mode TEXT NOT NULL,
1015
+ created_at TEXT NOT NULL,
1016
+ updated_at TEXT NOT NULL
1017
+ );
1018
+ CREATE TABLE IF NOT EXISTS sample_reviews (
1019
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
1020
+ sample_id TEXT NOT NULL,
1021
+ review_status TEXT NOT NULL,
1022
+ note TEXT,
1023
+ created_at TEXT NOT NULL
1024
+ );
1025
+ CREATE TABLE IF NOT EXISTS exports_audit (
1026
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
1027
+ export_kind TEXT NOT NULL,
1028
+ mode TEXT NOT NULL,
1029
+ approved_only INTEGER NOT NULL,
1030
+ file_path TEXT NOT NULL,
1031
+ row_count INTEGER NOT NULL,
1032
+ created_at TEXT NOT NULL
1033
+ );
1034
+ CREATE TABLE IF NOT EXISTS evolution_tasks (
1035
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
1036
+ task_id TEXT UNIQUE NOT NULL,
1037
+ trace_id TEXT NOT NULL,
1038
+ source TEXT NOT NULL,
1039
+ reason TEXT,
1040
+ score INTEGER DEFAULT 0,
1041
+ status TEXT DEFAULT 'pending',
1042
+ enqueued_at TEXT,
1043
+ started_at TEXT,
1044
+ completed_at TEXT,
1045
+ resolution TEXT,
1046
+ created_at TEXT NOT NULL,
1047
+ updated_at TEXT NOT NULL
1048
+ );
1049
+ CREATE TABLE IF NOT EXISTS evolution_events (
1050
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
1051
+ trace_id TEXT NOT NULL,
1052
+ task_id TEXT,
1053
+ stage TEXT NOT NULL,
1054
+ level TEXT DEFAULT 'info',
1055
+ message TEXT NOT NULL,
1056
+ summary TEXT,
1057
+ metadata_json TEXT,
1058
+ created_at TEXT NOT NULL
1059
+ );
1060
+ `);
1061
+ // Migration: Add text column to pain_events if it doesn't exist (MEM-01)
1062
+ // SQLite doesn't support IF NOT EXISTS for ADD COLUMN, so we use try/catch
1063
+ try {
1064
+ this.db.exec(`ALTER TABLE pain_events ADD COLUMN text TEXT`);
1065
+ }
1066
+ catch (err) {
1067
+ const message = err instanceof Error ? err.message : String(err);
1068
+ if (!message.includes('duplicate column name') && !message.includes('no column named')) {
1069
+ // Re-throw unexpected errors — silently swallowing migration failures is dangerous
1070
+ throw err;
1071
+ }
1072
+ }
1073
+ // PRI-406: Add canonical_pain_id and runtime_task_id columns to pain_events
1074
+ for (const col of [
1075
+ { name: 'canonical_pain_id', type: 'TEXT' },
1076
+ { name: 'runtime_task_id', type: 'TEXT' },
1077
+ ]) {
1078
+ try {
1079
+ this.db.exec(`ALTER TABLE pain_events ADD COLUMN ${col.name} ${col.type}`);
1080
+ }
1081
+ catch (err) {
1082
+ const message = err instanceof Error ? err.message : String(err);
1083
+ if (!message.includes('duplicate column name') && !message.includes('no column named')) {
1084
+ throw err;
1085
+ }
1086
+ }
1087
+ }
1088
+ // PRI-406: Partial unique index on canonical_pain_id (non-null only) for dedup
1089
+ this.db.exec(`
1090
+ CREATE UNIQUE INDEX IF NOT EXISTS idx_pain_events_canonical_pain_id
1091
+ ON pain_events(canonical_pain_id)
1092
+ WHERE canonical_pain_id IS NOT NULL
1093
+ `);
1094
+ // Create FTS5 virtual table for pain_events text search (MEM-04)
1095
+ this.db.exec(`
1096
+ CREATE VIRTUAL TABLE IF NOT EXISTS pain_events_fts USING fts5(
1097
+ text,
1098
+ pain_event_id UNINDEXED,
1099
+ tokenize='porter unicode61'
1100
+ )
1101
+ `);
1102
+ // V2 migration: Add V2 columns to evolution_tasks if they don't exist
1103
+ // SQLite does not support IF NOT EXISTS for ADD COLUMN, so we must check manually
1104
+ // before each ALTER to avoid "duplicate column name" errors on existing DBs
1105
+ const v2Columns = [
1106
+ { name: 'task_kind', type: 'TEXT' },
1107
+ { name: 'priority', type: 'TEXT' },
1108
+ { name: 'retry_count', type: 'INTEGER' },
1109
+ { name: 'max_retries', type: 'INTEGER' },
1110
+ { name: 'last_error', type: 'TEXT' },
1111
+ { name: 'result_ref', type: 'TEXT' },
1112
+ ];
1113
+ for (const col of v2Columns) {
1114
+ const exists = this.db.prepare(`PRAGMA table_info(evolution_tasks)`).all()
1115
+ .some((row) => row.name === col.name);
1116
+ if (!exists) {
1117
+ this.db.exec(`ALTER TABLE evolution_tasks ADD COLUMN ${col.name} ${col.type}`);
1118
+ }
1119
+ }
1120
+ this.db.exec(`
1121
+ CREATE VIEW IF NOT EXISTS v_error_clusters AS
1122
+ SELECT tool_name, COALESCE(error_type, 'unknown') AS error_type, COUNT(*) AS occurrences
1123
+ FROM tool_calls
1124
+ WHERE outcome = 'failure'
1125
+ GROUP BY tool_name, COALESCE(error_type, 'unknown')
1126
+ ORDER BY occurrences DESC;
1127
+ CREATE VIEW IF NOT EXISTS v_principle_effectiveness AS
1128
+ SELECT event_type, COUNT(*) AS total
1129
+ FROM principle_events
1130
+ GROUP BY event_type
1131
+ ORDER BY total DESC;
1132
+ CREATE VIEW IF NOT EXISTS v_sample_queue AS
1133
+ SELECT review_status, COUNT(*) AS total
1134
+ FROM correction_samples
1135
+ GROUP BY review_status;
1136
+ CREATE INDEX IF NOT EXISTS idx_assistant_turns_session_id ON assistant_turns(session_id);
1137
+ CREATE INDEX IF NOT EXISTS idx_assistant_turns_created_at ON assistant_turns(created_at);
1138
+ CREATE INDEX IF NOT EXISTS idx_assistant_turns_provider_model ON assistant_turns(provider, model);
1139
+ CREATE INDEX IF NOT EXISTS idx_user_turns_session_id ON user_turns(session_id);
1140
+ CREATE INDEX IF NOT EXISTS idx_tool_calls_session_id ON tool_calls(session_id);
1141
+ CREATE INDEX IF NOT EXISTS idx_tool_calls_created_at ON tool_calls(created_at);
1142
+ CREATE INDEX IF NOT EXISTS idx_pain_events_session_id ON pain_events(session_id);
1143
+ CREATE INDEX IF NOT EXISTS idx_correction_samples_review_status ON correction_samples(review_status);
1144
+ CREATE INDEX IF NOT EXISTS idx_evolution_tasks_trace_id ON evolution_tasks(trace_id);
1145
+ CREATE INDEX IF NOT EXISTS idx_evolution_tasks_status ON evolution_tasks(status);
1146
+ CREATE INDEX IF NOT EXISTS idx_evolution_tasks_created_at ON evolution_tasks(created_at);
1147
+ CREATE INDEX IF NOT EXISTS idx_evolution_events_trace_id ON evolution_events(trace_id);
1148
+ CREATE INDEX IF NOT EXISTS idx_evolution_events_created_at ON evolution_events(created_at);
1149
+ `);
1150
+ const row = this.db.prepare('SELECT version FROM schema_version LIMIT 1').get();
1151
+ this.migrateSchema(row?.version);
1152
+ if (!row) {
1153
+ this.db.prepare('INSERT INTO schema_version (version) VALUES (?)').run(SCHEMA_VERSION);
1154
+ }
1155
+ else if (row.version !== SCHEMA_VERSION) {
1156
+ this.db.prepare('UPDATE schema_version SET version = ?').run(SCHEMA_VERSION);
1157
+ }
1158
+ }
1159
+ importLegacyArtifacts() {
1160
+ this.importLegacySessions();
1161
+ this.importLegacyEvents();
1162
+ this.importLegacyEvolution();
1163
+ }
1164
+ migrateSchema(_fromVersion) {
1165
+ this.db.exec(`
1166
+ DROP VIEW IF EXISTS v_daily_metrics;
1167
+ CREATE VIEW IF NOT EXISTS v_daily_metrics AS
1168
+ WITH tool_daily AS (
1169
+ SELECT
1170
+ substr(created_at, 1, 10) AS day,
1171
+ COUNT(*) AS tool_calls,
1172
+ SUM(CASE WHEN outcome = 'failure' THEN 1 ELSE 0 END) AS failures
1173
+ FROM tool_calls
1174
+ GROUP BY substr(created_at, 1, 10)
1175
+ ),
1176
+ correction_daily AS (
1177
+ SELECT
1178
+ substr(created_at, 1, 10) AS day,
1179
+ SUM(CASE WHEN correction_detected = 1 THEN 1 ELSE 0 END) AS user_corrections
1180
+ FROM user_turns
1181
+ GROUP BY substr(created_at, 1, 10)
1182
+ )
1183
+ SELECT
1184
+ tool_daily.day AS day,
1185
+ tool_daily.tool_calls AS tool_calls,
1186
+ tool_daily.failures AS failures,
1187
+ COALESCE(correction_daily.user_corrections, 0) AS user_corrections
1188
+ FROM tool_daily
1189
+ LEFT JOIN correction_daily ON correction_daily.day = tool_daily.day;
1190
+ `);
1191
+ }
1192
+ /**
1193
+ * Get daily metrics for analytics.
1194
+ *
1195
+ * Returns: Analytics data aggregated from trajectory database.
1196
+ * Not: Runtime truth or real-time queue state.
1197
+ */
1198
+ dailyMetrics() {
1199
+ return this.db.prepare('SELECT * FROM v_daily_metrics ORDER BY day ASC').all();
1200
+ }
1201
+ importLegacySessions() {
1202
+ const key = 'legacy:sessions';
1203
+ if (this.isImported(key))
1204
+ return;
1205
+ const sessionDir = resolvePdPath(this.workspaceDir, 'SESSION_DIR');
1206
+ if (!fs.existsSync(sessionDir))
1207
+ return;
1208
+ for (const file of fs.readdirSync(sessionDir).filter((entry) => entry.endsWith('.json'))) {
1209
+ try {
1210
+ const content = JSON.parse(fs.readFileSync(path.join(sessionDir, file), 'utf8'));
1211
+ if (content.sessionId) {
1212
+ const startedAt = typeof content.lastActivityAt === 'number'
1213
+ ? new Date(content.lastActivityAt).toISOString()
1214
+ : nowIso();
1215
+ this.recordSession({ sessionId: content.sessionId, startedAt });
1216
+ }
1217
+ }
1218
+ catch {
1219
+ // Ignore malformed legacy sessions.
1220
+ }
1221
+ }
1222
+ this.markImported(key);
1223
+ }
1224
+ importLegacyEvents() {
1225
+ const key = 'legacy:events';
1226
+ if (this.isImported(key))
1227
+ return;
1228
+ const eventsPath = path.join(this.stateDir, 'logs', 'events.jsonl');
1229
+ if (!fs.existsSync(eventsPath))
1230
+ return;
1231
+ const raw = fs.readFileSync(eventsPath, 'utf8').trim();
1232
+ if (!raw) {
1233
+ this.markImported(key);
1234
+ return;
1235
+ }
1236
+ for (const line of raw.split('\n')) {
1237
+ try {
1238
+ const event = JSON.parse(line);
1239
+ if (event.type === 'pain_signal' && event.sessionId) {
1240
+ this.recordPainEvent({
1241
+ sessionId: event.sessionId,
1242
+ source: String(event.data?.source ?? 'legacy'),
1243
+ score: Number(event.data?.score ?? 0),
1244
+ reason: typeof event.data?.reason === 'string' ? event.data.reason : null,
1245
+ severity: typeof event.data?.severity === 'string' ? event.data.severity : null,
1246
+ origin: typeof event.data?.origin === 'string' ? event.data.origin : null,
1247
+ confidence: typeof event.data?.confidence === 'number' ? event.data.confidence : null,
1248
+ createdAt: event.ts,
1249
+ });
1250
+ }
1251
+ if (event.type === 'trust_change') {
1252
+ this.recordTrustChange({
1253
+ sessionId: event.sessionId,
1254
+ previousScore: Number(event.data?.previousScore ?? 0),
1255
+ newScore: Number(event.data?.newScore ?? 0),
1256
+ delta: Number(event.data?.delta ?? 0),
1257
+ reason: String(event.data?.reason ?? 'legacy'),
1258
+ createdAt: event.ts,
1259
+ });
1260
+ }
1261
+ if (event.type === 'gate_block') {
1262
+ this.recordGateBlock({
1263
+ sessionId: event.sessionId,
1264
+ toolName: String(event.data?.toolName ?? 'unknown'),
1265
+ filePath: typeof event.data?.filePath === 'string' ? event.data.filePath : null,
1266
+ reason: String(event.data?.reason ?? 'legacy'),
1267
+ planStatus: typeof event.data?.planStatus === 'string' ? event.data.planStatus : null,
1268
+ createdAt: event.ts,
1269
+ });
1270
+ }
1271
+ }
1272
+ catch {
1273
+ // Ignore malformed legacy events.
1274
+ }
1275
+ }
1276
+ this.markImported(key);
1277
+ }
1278
+ importLegacyEvolution() {
1279
+ const key = 'legacy:evolution';
1280
+ if (this.isImported(key))
1281
+ return;
1282
+ const evolutionPath = resolvePdPath(this.workspaceDir, 'EVOLUTION_STREAM');
1283
+ if (!fs.existsSync(evolutionPath))
1284
+ return;
1285
+ const raw = fs.readFileSync(evolutionPath, 'utf8').trim();
1286
+ if (!raw) {
1287
+ this.markImported(key);
1288
+ return;
1289
+ }
1290
+ for (const line of raw.split('\n')) {
1291
+ try {
1292
+ const event = JSON.parse(line);
1293
+ this.recordPrincipleEvent({
1294
+ principleId: typeof event.data?.principleId === 'string' ? event.data.principleId : null,
1295
+ eventType: String(event.type ?? 'legacy'),
1296
+ payload: event.data ?? {},
1297
+ createdAt: event.ts,
1298
+ });
1299
+ }
1300
+ catch {
1301
+ // Ignore malformed legacy evolution events.
1302
+ }
1303
+ }
1304
+ this.markImported(key);
1305
+ }
1306
+ markImported(sourceKey) {
1307
+ this.withWrite(() => {
1308
+ this.db.prepare(`
1309
+ INSERT INTO ingest_checkpoint (source_key, imported_at)
1310
+ VALUES (?, ?)
1311
+ ON CONFLICT(source_key) DO UPDATE SET imported_at = excluded.imported_at
1312
+ `).run(sourceKey, nowIso());
1313
+ });
1314
+ }
1315
+ isImported(sourceKey) {
1316
+ const row = this.db.prepare('SELECT source_key FROM ingest_checkpoint WHERE source_key = ?').get(sourceKey);
1317
+ return Boolean(row);
1318
+ }
1319
+ maybeCreateCorrectionSample(sessionId) {
1320
+ const pending = this.db.prepare(`
1321
+ SELECT sample_id FROM correction_samples
1322
+ WHERE session_id = ? AND review_status = 'pending'
1323
+ ORDER BY created_at DESC
1324
+ LIMIT 1
1325
+ `).get(sessionId);
1326
+ if (pending?.sample_id)
1327
+ return;
1328
+ const correctionTurn = this.db.prepare(`
1329
+ SELECT id, references_assistant_turn_id, correction_cue, raw_text, blob_ref
1330
+ FROM user_turns
1331
+ WHERE session_id = ? AND correction_detected = 1
1332
+ ORDER BY id DESC
1333
+ LIMIT 1
1334
+ `).get(sessionId);
1335
+ if (!correctionTurn || !correctionTurn.references_assistant_turn_id)
1336
+ return;
1337
+ // #Phase2b-fix: Tool failure is NOT required for correction samples.
1338
+ // User corrections are the highest-fidelity signal — they indicate the agent
1339
+ // said or did something wrong, regardless of whether tool calls succeeded.
1340
+ // Requiring tool failure excluded the most valuable cases: "agent did something
1341
+ // that technically worked but violated a principle or was logically wrong."
1342
+ const failedCall = this.db.prepare(`
1343
+ SELECT id, tool_name, error_type, error_message
1344
+ FROM tool_calls
1345
+ WHERE session_id = ? AND outcome = 'failure'
1346
+ ORDER BY id DESC
1347
+ LIMIT 1
1348
+ `).get(sessionId);
1349
+ const recentCalls = this.db.prepare(`
1350
+ SELECT id, tool_name, outcome
1351
+ FROM tool_calls
1352
+ WHERE session_id = ?
1353
+ ORDER BY id DESC
1354
+ LIMIT 5
1355
+ `).all(sessionId);
1356
+ const successfulCalls = recentCalls.filter(c => c.outcome === 'success');
1357
+ // Generate sample ID from correction turn + first recent call (or correction id if no calls)
1358
+ const refForHash = successfulCalls[0]?.id ?? correctionTurn.id;
1359
+ const sampleId = `sample_${crypto.createHash('md5').update(`${sessionId}:${correctionTurn.id}:${refForHash}`).digest('hex').slice(0, 12)}`;
1360
+ const userRawText = this.restoreRawText(correctionTurn.raw_text, correctionTurn.blob_ref);
1361
+ // Quality scoring: correction cue is always valuable
1362
+ // Tool failure adds context (20pts), successful calls add context (up to 15pts)
1363
+ // Pure conversation corrections still score 55-75 (high enough to review)
1364
+ const qualityScore = [
1365
+ correctionTurn.references_assistant_turn_id ? 35 : 0,
1366
+ correctionTurn.correction_cue ? 20 : 0,
1367
+ failedCall ? 20 : 0,
1368
+ Math.min(successfulCalls.length, 3) * 5,
1369
+ ].reduce((sum, value) => sum + value, 0);
1370
+ // Diff excerpt: prefer user correction text, fallback to error info, fallback to cue
1371
+ const diffText = userRawText
1372
+ || (failedCall ? String(failedCall.error_message ?? failedCall.error_type ?? failedCall.tool_name) : '')
1373
+ || String(correctionTurn.correction_cue ?? 'user correction');
1374
+ this.withWrite(() => {
1375
+ this.db.prepare(`
1376
+ INSERT OR IGNORE INTO correction_samples (
1377
+ sample_id, session_id, bad_assistant_turn_id, user_correction_turn_id,
1378
+ recovery_tool_span_json, diff_excerpt, principle_ids_json, quality_score,
1379
+ review_status, export_mode, created_at, updated_at
1380
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'pending', 'raw', ?, ?)
1381
+ `).run(sampleId, sessionId, Number(correctionTurn.references_assistant_turn_id), Number(correctionTurn.id), safeJson(successfulCalls.map((call) => ({ id: call.id, toolName: call.tool_name, outcome: call.outcome }))), summarizeForDiff(diffText), '[]', qualityScore, nowIso(), nowIso());
1382
+ });
1383
+ }
1384
+ recordExportAudit(exportKind, mode, approvedOnly, filePath, rowCount) {
1385
+ this.withWrite(() => {
1386
+ this.db.prepare(`
1387
+ INSERT INTO exports_audit (export_kind, mode, approved_only, file_path, row_count, created_at)
1388
+ VALUES (?, ?, ?, ?, ?, ?)
1389
+ `).run(exportKind, mode, approvedOnly ? 1 : 0, filePath, rowCount, nowIso());
1390
+ });
1391
+ }
1392
+ storeRawText(kind, text) {
1393
+ const excerpt = text.length > 200 ? `${text.slice(0, 197)}...` : text;
1394
+ const bytes = Buffer.byteLength(text, 'utf8');
1395
+ if (bytes <= this.blobInlineThresholdBytes) {
1396
+ return { inlineText: text, blobRef: null, excerpt };
1397
+ }
1398
+ const hash = crypto.createHash('sha256').update(text).digest('hex');
1399
+ const relativePath = `${kind}-${hash}.txt`;
1400
+ const fullPath = path.join(this.blobDir, relativePath);
1401
+ if (!fs.existsSync(fullPath)) {
1402
+ atomicWriteFileSync(fullPath, text);
1403
+ }
1404
+ return { inlineText: null, blobRef: relativePath, excerpt };
1405
+ }
1406
+ restoreRawText(inlineText, blobRef) {
1407
+ if (inlineText)
1408
+ return inlineText;
1409
+ if (!blobRef)
1410
+ return '';
1411
+ const fullPath = path.join(this.blobDir, blobRef);
1412
+ return fs.existsSync(fullPath) ? fs.readFileSync(fullPath, 'utf8') : '';
1413
+ }
1414
+ computeBlobBytes() {
1415
+ if (!fs.existsSync(this.blobDir))
1416
+ return 0;
1417
+ return fs.readdirSync(this.blobDir).reduce((sum, file) => sum + fileSizeIfExists(path.join(this.blobDir, file)), 0);
1418
+ }
1419
+ pruneUnreferencedBlobs() {
1420
+ if (!fs.existsSync(this.blobDir)) {
1421
+ return { removedFiles: 0, reclaimedBytes: 0 };
1422
+ }
1423
+ const referenced = new Set();
1424
+ const rows = this.db.prepare(`
1425
+ SELECT blob_ref FROM assistant_turns WHERE blob_ref IS NOT NULL
1426
+ UNION
1427
+ SELECT blob_ref FROM user_turns WHERE blob_ref IS NOT NULL
1428
+ `).all();
1429
+ for (const row of rows) {
1430
+ if (row.blob_ref)
1431
+ referenced.add(String(row.blob_ref));
1432
+ }
1433
+ const now = Date.now();
1434
+ let removedFiles = 0;
1435
+ let reclaimedBytes = 0;
1436
+ for (const entry of fs.readdirSync(this.blobDir)) {
1437
+ if (referenced.has(entry))
1438
+ continue;
1439
+ const fullPath = path.join(this.blobDir, entry);
1440
+ let stat;
1441
+ try {
1442
+ stat = fs.statSync(fullPath);
1443
+ }
1444
+ catch {
1445
+ continue;
1446
+ }
1447
+ if (!stat.isFile())
1448
+ continue;
1449
+ if (this.orphanBlobGraceMs > 0 && now - stat.mtimeMs < this.orphanBlobGraceMs)
1450
+ continue;
1451
+ reclaimedBytes += stat.size;
1452
+ removedFiles += 1;
1453
+ fs.rmSync(fullPath, { force: true });
1454
+ }
1455
+ return { removedFiles, reclaimedBytes };
1456
+ }
1457
+ withWrite(fn) {
1458
+ return withLock(this.dbPath, fn, { lockSuffix: '.trajectory.lock', lockStaleMs: 30000 });
1459
+ }
1460
+ }
1461
+ export class TrajectoryRegistry {
1462
+ static instances = new Map();
1463
+ static get(workspaceDir, opts = {}) {
1464
+ const normalized = path.resolve(workspaceDir);
1465
+ const existing = this.instances.get(normalized);
1466
+ if (existing)
1467
+ return existing;
1468
+ const created = new TrajectoryDatabase({ workspaceDir: normalized, ...opts });
1469
+ this.instances.set(normalized, created);
1470
+ return created;
1471
+ }
1472
+ static dispose(workspaceDir) {
1473
+ const normalized = path.resolve(workspaceDir);
1474
+ const instance = this.instances.get(normalized);
1475
+ if (instance) {
1476
+ instance.dispose();
1477
+ this.instances.delete(normalized);
1478
+ }
1479
+ }
1480
+ static clear() {
1481
+ for (const instance of this.instances.values()) {
1482
+ instance.dispose();
1483
+ }
1484
+ this.instances.clear();
1485
+ }
1486
+ static use(workspaceDir, fn, opts = {}) {
1487
+ const normalized = path.resolve(workspaceDir);
1488
+ const existing = this.instances.get(normalized);
1489
+ if (existing) {
1490
+ return fn(existing);
1491
+ }
1492
+ const transient = new TrajectoryDatabase({ workspaceDir: normalized, ...opts });
1493
+ try {
1494
+ return fn(transient);
1495
+ }
1496
+ finally {
1497
+ transient.dispose();
1498
+ }
1499
+ }
1500
+ }