create-principles-disciple 1.150.2 → 1.150.4

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 (267) hide show
  1. package/_release/product-identity.json +1 -1
  2. package/codex-adapter/dist/ingestion/admission.js +2 -0
  3. package/codex-adapter/dist/pd-hook.d.ts +7 -5
  4. package/codex-adapter/dist/pd-hook.js +18 -7
  5. package/codex-adapter/dist/tool-semantics.js +5 -1
  6. package/codex-adapter/dist/worker/workspace-worker.js +4 -2
  7. package/codex-adapter/package.json +1 -1
  8. package/console/dist/lib/utils.js +16 -1
  9. package/console/dist/web/assets/app.css +147 -46
  10. package/console/dist/web/assets/app.js +35 -32
  11. package/console/package.json +2 -0
  12. package/core/dist/runtime/activation/adaptive-selection-output.d.ts +35 -0
  13. package/core/dist/runtime/activation/adaptive-selection-output.d.ts.map +1 -0
  14. package/core/dist/runtime/activation/adaptive-selection-output.js +38 -0
  15. package/core/dist/runtime/activation/adaptive-selection-output.js.map +1 -0
  16. package/core/dist/runtime/activation-compatibility-read-model.d.ts.map +1 -1
  17. package/core/dist/runtime/activation-compatibility-read-model.js +2 -1
  18. package/core/dist/runtime/activation-compatibility-read-model.js.map +1 -1
  19. package/core/dist/runtime/adapter/artificer-l2-adapter.d.ts.map +1 -1
  20. package/core/dist/runtime/adapter/artificer-l2-adapter.js +89 -27
  21. package/core/dist/runtime/adapter/artificer-l2-adapter.js.map +1 -1
  22. package/core/dist/runtime/adapter/context-budget.d.ts +49 -0
  23. package/core/dist/runtime/adapter/context-budget.d.ts.map +1 -0
  24. package/core/dist/runtime/adapter/context-budget.js +127 -0
  25. package/core/dist/runtime/adapter/context-budget.js.map +1 -0
  26. package/core/dist/runtime/adapter/output-schema-registry.d.ts.map +1 -1
  27. package/core/dist/runtime/adapter/output-schema-registry.js +7 -0
  28. package/core/dist/runtime/adapter/output-schema-registry.js.map +1 -1
  29. package/core/dist/runtime/adapter/pi-ai-runtime-adapter.d.ts +30 -7
  30. package/core/dist/runtime/adapter/pi-ai-runtime-adapter.d.ts.map +1 -1
  31. package/core/dist/runtime/adapter/pi-ai-runtime-adapter.js +559 -211
  32. package/core/dist/runtime/adapter/pi-ai-runtime-adapter.js.map +1 -1
  33. package/core/dist/runtime/candidate-audit.d.ts.map +1 -1
  34. package/core/dist/runtime/candidate-audit.js +2 -1
  35. package/core/dist/runtime/candidate-audit.js.map +1 -1
  36. package/core/dist/runtime/config/pd-config-effective.d.ts.map +1 -1
  37. package/core/dist/runtime/config/pd-config-effective.js +2 -0
  38. package/core/dist/runtime/config/pd-config-effective.js.map +1 -1
  39. package/core/dist/runtime/config/pd-config-types.d.ts +52 -0
  40. package/core/dist/runtime/config/pd-config-types.d.ts.map +1 -1
  41. package/core/dist/runtime/config/pd-config-types.js.map +1 -1
  42. package/core/dist/runtime/config/pd-config-validate.d.ts.map +1 -1
  43. package/core/dist/runtime/config/pd-config-validate.js +134 -0
  44. package/core/dist/runtime/config/pd-config-validate.js.map +1 -1
  45. package/core/dist/runtime/feature-flags/feature-flag-contract.d.ts.map +1 -1
  46. package/core/dist/runtime/feature-flags/feature-flag-contract.js +8 -0
  47. package/core/dist/runtime/feature-flags/feature-flag-contract.js.map +1 -1
  48. package/core/dist/runtime/feature-flags/feature-flag-lifecycle.d.ts.map +1 -1
  49. package/core/dist/runtime/feature-flags/feature-flag-lifecycle.js +24 -0
  50. package/core/dist/runtime/feature-flags/feature-flag-lifecycle.js.map +1 -1
  51. package/core/dist/runtime/index.d.ts +2 -0
  52. package/core/dist/runtime/index.d.ts.map +1 -1
  53. package/core/dist/runtime/index.js +2 -0
  54. package/core/dist/runtime/index.js.map +1 -1
  55. package/core/dist/runtime/internalization/rule-host-input-builder.d.ts +16 -0
  56. package/core/dist/runtime/internalization/rule-host-input-builder.d.ts.map +1 -1
  57. package/core/dist/runtime/internalization/rule-host-input-builder.js +18 -0
  58. package/core/dist/runtime/internalization/rule-host-input-builder.js.map +1 -1
  59. package/core/dist/runtime/internalization/split-diagnostician-runner.d.ts +8 -0
  60. package/core/dist/runtime/internalization/split-diagnostician-runner.d.ts.map +1 -1
  61. package/core/dist/runtime/internalization/split-diagnostician-runner.js +24 -2
  62. package/core/dist/runtime/internalization/split-diagnostician-runner.js.map +1 -1
  63. package/core/dist/runtime/internalization/tool-semantic-registry.d.ts +26 -0
  64. package/core/dist/runtime/internalization/tool-semantic-registry.d.ts.map +1 -1
  65. package/core/dist/runtime/internalization/tool-semantic-registry.js +55 -5
  66. package/core/dist/runtime/internalization/tool-semantic-registry.js.map +1 -1
  67. package/core/dist/runtime/internalization-chain-integrity-read-model.d.ts.map +1 -1
  68. package/core/dist/runtime/internalization-chain-integrity-read-model.js +2 -2
  69. package/core/dist/runtime/internalization-chain-integrity-read-model.js.map +1 -1
  70. package/core/dist/runtime/internalization-integrity-remediation.d.ts.map +1 -1
  71. package/core/dist/runtime/internalization-integrity-remediation.js +2 -2
  72. package/core/dist/runtime/internalization-integrity-remediation.js.map +1 -1
  73. package/core/dist/runtime/operator-health-read-model.d.ts.map +1 -1
  74. package/core/dist/runtime/operator-health-read-model.js +2 -2
  75. package/core/dist/runtime/operator-health-read-model.js.map +1 -1
  76. package/core/dist/runtime/pain-recall-read-model.d.ts.map +1 -1
  77. package/core/dist/runtime/pain-recall-read-model.js +4 -3
  78. package/core/dist/runtime/pain-recall-read-model.js.map +1 -1
  79. package/core/dist/runtime/pruning-read-model.d.ts.map +1 -1
  80. package/core/dist/runtime/pruning-read-model.js +3 -2
  81. package/core/dist/runtime/pruning-read-model.js.map +1 -1
  82. package/core/dist/runtime/risk/risk-calculator-policy.d.ts +12 -2
  83. package/core/dist/runtime/risk/risk-calculator-policy.d.ts.map +1 -1
  84. package/core/dist/runtime/risk/risk-calculator-policy.js +33 -22
  85. package/core/dist/runtime/risk/risk-calculator-policy.js.map +1 -1
  86. package/core/dist/runtime/schema-conformance-read-model.js +2 -2
  87. package/core/dist/runtime/schema-conformance-read-model.js.map +1 -1
  88. package/core/dist/runtime/store/sqlite-connection.d.ts +0 -5
  89. package/core/dist/runtime/store/sqlite-connection.d.ts.map +1 -1
  90. package/core/dist/runtime/store/sqlite-connection.js +4 -12
  91. package/core/dist/runtime/store/sqlite-connection.js.map +1 -1
  92. package/core/dist/runtime/store/storage-paths.d.ts +17 -0
  93. package/core/dist/runtime/store/storage-paths.d.ts.map +1 -0
  94. package/core/dist/runtime/store/storage-paths.js +52 -0
  95. package/core/dist/runtime/store/storage-paths.js.map +1 -0
  96. package/core/dist/runtime/trajectory-retention.d.ts +257 -0
  97. package/core/dist/runtime/trajectory-retention.d.ts.map +1 -0
  98. package/core/dist/runtime/trajectory-retention.js +598 -0
  99. package/core/dist/runtime/trajectory-retention.js.map +1 -0
  100. package/core/dist/telemetry-event.d.ts +2 -2
  101. package/core/dist/telemetry-event.d.ts.map +1 -1
  102. package/core/dist/telemetry-event.js +5 -0
  103. package/core/dist/telemetry-event.js.map +1 -1
  104. package/core/dist/trajectory-store.d.ts +9 -9
  105. package/core/dist/trajectory-store.d.ts.map +1 -1
  106. package/core/dist/trajectory-store.js +9 -12
  107. package/core/dist/trajectory-store.js.map +1 -1
  108. package/core/package.json +1 -1
  109. package/dist/installers/codex-host-installer.d.ts.map +1 -1
  110. package/dist/installers/codex-host-installer.js +92 -5
  111. package/dist/installers/codex-host-installer.js.map +1 -1
  112. package/dist/installers/mcp-binding-shape-mirror.d.ts +27 -0
  113. package/dist/installers/mcp-binding-shape-mirror.d.ts.map +1 -0
  114. package/dist/installers/mcp-binding-shape-mirror.js +105 -0
  115. package/dist/installers/mcp-binding-shape-mirror.js.map +1 -0
  116. package/dist/skill-catalog.d.ts +35 -0
  117. package/dist/skill-catalog.d.ts.map +1 -0
  118. package/dist/skill-catalog.js +85 -0
  119. package/dist/skill-catalog.js.map +1 -0
  120. package/dist/skill-delivery-parity.d.ts +22 -0
  121. package/dist/skill-delivery-parity.d.ts.map +1 -0
  122. package/dist/skill-delivery-parity.js +31 -0
  123. package/dist/skill-delivery-parity.js.map +1 -0
  124. package/host-runtime/dist/active-principle-prompt.d.ts +8 -0
  125. package/host-runtime/dist/active-principle-prompt.js +15 -5
  126. package/host-runtime/dist/adaptive-decision-protocol.d.ts +142 -0
  127. package/host-runtime/dist/adaptive-decision-protocol.js +190 -0
  128. package/host-runtime/dist/adaptive-priority-provider.d.ts +37 -13
  129. package/host-runtime/dist/adaptive-priority-provider.js +65 -62
  130. package/host-runtime/dist/adaptive-selection.d.ts +67 -62
  131. package/host-runtime/dist/adaptive-selection.js +218 -301
  132. package/host-runtime/dist/adaptive-skip-decision.d.ts +26 -14
  133. package/host-runtime/dist/adaptive-skip-decision.js +33 -29
  134. package/host-runtime/dist/codex-rule-context-provider.js +4 -1
  135. package/host-runtime/dist/governance-observation-store.d.ts +40 -1
  136. package/host-runtime/dist/governance-observation-store.js +188 -9
  137. package/host-runtime/dist/governance-signal-admission.d.ts +19 -3
  138. package/host-runtime/dist/governance-signal-admission.js +12 -4
  139. package/host-runtime/dist/host-tool-declaration.d.ts +18 -2
  140. package/host-runtime/dist/host-tool-declaration.js +67 -11
  141. package/host-runtime/dist/host-tool-semantic-resolver.d.ts +7 -0
  142. package/host-runtime/dist/host-tool-semantic-resolver.js +22 -2
  143. package/host-runtime/dist/index.d.ts +3 -0
  144. package/host-runtime/dist/index.js +14 -0
  145. package/host-runtime/dist/production-rulehost-gate.js +36 -4
  146. package/host-runtime/dist/trajectory-retention.d.ts +147 -0
  147. package/host-runtime/dist/trajectory-retention.js +907 -0
  148. package/host-runtime/package.json +1 -1
  149. package/install-layout/dist/index.d.ts +9 -2
  150. package/install-layout/dist/index.js +26 -9
  151. package/install-layout/dist/mcp-binding-contract.d.ts +91 -0
  152. package/install-layout/dist/mcp-binding-contract.js +230 -0
  153. package/install-layout/package.json +1 -1
  154. package/package.json +4 -4
  155. package/pd-cli/dist/commands/build-trajectory-evidence.d.ts.map +1 -1
  156. package/pd-cli/dist/commands/build-trajectory-evidence.js +17 -11
  157. package/pd-cli/dist/commands/build-trajectory-evidence.js.map +1 -1
  158. package/pd-cli/dist/commands/codex-reconcile.d.ts +7 -0
  159. package/pd-cli/dist/commands/codex-reconcile.d.ts.map +1 -1
  160. package/pd-cli/dist/commands/codex-reconcile.js +11 -2
  161. package/pd-cli/dist/commands/codex-reconcile.js.map +1 -1
  162. package/pd-cli/dist/commands/codex-worker.d.ts.map +1 -1
  163. package/pd-cli/dist/commands/codex-worker.js +35 -0
  164. package/pd-cli/dist/commands/codex-worker.js.map +1 -1
  165. package/pd-cli/dist/commands/command-helpers.d.ts +1 -1
  166. package/pd-cli/dist/commands/command-helpers.js +1 -1
  167. package/pd-cli/dist/commands/errors-list.d.ts +1 -1
  168. package/pd-cli/dist/commands/errors-list.js +1 -1
  169. package/pd-cli/dist/commands/health-mcp.d.ts +23 -1
  170. package/pd-cli/dist/commands/health-mcp.d.ts.map +1 -1
  171. package/pd-cli/dist/commands/health-mcp.js +81 -22
  172. package/pd-cli/dist/commands/health-mcp.js.map +1 -1
  173. package/pd-cli/dist/commands/health.d.ts +1 -1
  174. package/pd-cli/dist/commands/health.d.ts.map +1 -1
  175. package/pd-cli/dist/commands/health.js +12 -5
  176. package/pd-cli/dist/commands/health.js.map +1 -1
  177. package/pd-cli/dist/commands/principles-stats.d.ts +1 -1
  178. package/pd-cli/dist/commands/principles-stats.js +1 -1
  179. package/pd-cli/dist/commands/trajectory-retention.d.ts +23 -0
  180. package/pd-cli/dist/commands/trajectory-retention.d.ts.map +1 -0
  181. package/pd-cli/dist/commands/trajectory-retention.js +159 -0
  182. package/pd-cli/dist/commands/trajectory-retention.js.map +1 -0
  183. package/pd-cli/dist/commands/workbuddy-setup.d.ts +69 -0
  184. package/pd-cli/dist/commands/workbuddy-setup.d.ts.map +1 -0
  185. package/pd-cli/dist/commands/workbuddy-setup.js +379 -0
  186. package/pd-cli/dist/commands/workbuddy-setup.js.map +1 -0
  187. package/pd-cli/dist/commands/workbuddy-worker.d.ts.map +1 -1
  188. package/pd-cli/dist/commands/workbuddy-worker.js +42 -6
  189. package/pd-cli/dist/commands/workbuddy-worker.js.map +1 -1
  190. package/pd-cli/dist/index.d.ts +1 -7
  191. package/pd-cli/dist/index.d.ts.map +1 -1
  192. package/pd-cli/dist/index.js +15 -1201
  193. package/pd-cli/dist/index.js.map +1 -1
  194. package/pd-cli/dist/program.d.ts +17 -0
  195. package/pd-cli/dist/program.d.ts.map +1 -0
  196. package/pd-cli/dist/program.js +1263 -0
  197. package/pd-cli/dist/program.js.map +1 -0
  198. package/pd-cli/dist/services/delivery-surfaces.d.ts.map +1 -1
  199. package/pd-cli/dist/services/delivery-surfaces.js +7 -5
  200. package/pd-cli/dist/services/delivery-surfaces.js.map +1 -1
  201. package/pd-cli/dist/services/version-report.d.ts.map +1 -1
  202. package/pd-cli/dist/services/version-report.js +30 -4
  203. package/pd-cli/dist/services/version-report.js.map +1 -1
  204. package/pd-cli/package.json +1 -1
  205. package/pd-mcp-server/dist/version.d.ts +1 -1
  206. package/pd-mcp-server/dist/version.js +1 -1
  207. package/pd-mcp-server/package.json +3 -1
  208. package/plugin/dist/bundle.js +477 -471
  209. package/plugin/dist/constants/tools.d.ts +8 -1
  210. package/plugin/dist/core/trajectory-retention-trigger.d.ts +13 -0
  211. package/plugin/dist/core/trajectory.d.ts +14 -0
  212. package/plugin/dist/hooks/gate-block-helper.d.ts +17 -0
  213. package/plugin/dist/hooks/gate.d.ts +7 -2
  214. package/plugin/dist/host-runtime/openclaw-host-runtime.d.ts +1 -0
  215. package/plugin/dist/index.d.ts +5 -0
  216. package/plugin/dist/openclaw.plugin.json +1 -1
  217. package/plugin/dist/rulehost-evidence.js +29 -23
  218. package/plugin/dist/templates/langs/en/skills/pd-cli-operator/SKILL.md +16 -5
  219. package/plugin/dist/templates/langs/en/skills/pd-control/SKILL.md +7 -6
  220. package/plugin/dist/templates/langs/en/skills/pd-pain-signal/SKILL.md +141 -28
  221. package/plugin/dist/templates/langs/en/skills/pd-review/SKILL.md +15 -1
  222. package/plugin/dist/templates/langs/zh/skills/pd-cli-operator/SKILL.md +16 -5
  223. package/plugin/dist/templates/langs/zh/skills/pd-control/SKILL.md +7 -6
  224. package/plugin/dist/templates/langs/zh/skills/pd-pain-signal/SKILL.md +142 -29
  225. package/plugin/dist/templates/langs/zh/skills/pd-review/SKILL.md +15 -1
  226. package/plugin/openclaw.plugin.json +1 -1
  227. package/plugin/package.json +1 -1
  228. package/plugin/templates/langs/en/skills/pd-cli-operator/SKILL.md +16 -5
  229. package/plugin/templates/langs/en/skills/pd-control/SKILL.md +7 -6
  230. package/plugin/templates/langs/en/skills/pd-pain-signal/SKILL.md +141 -28
  231. package/plugin/templates/langs/en/skills/pd-review/SKILL.md +15 -1
  232. package/plugin/templates/langs/zh/skills/pd-cli-operator/SKILL.md +16 -5
  233. package/plugin/templates/langs/zh/skills/pd-control/SKILL.md +7 -6
  234. package/plugin/templates/langs/zh/skills/pd-pain-signal/SKILL.md +142 -29
  235. package/plugin/templates/langs/zh/skills/pd-review/SKILL.md +15 -1
  236. package/release-manager/dist/installers/codex-host-installer.js +92 -5
  237. package/release-manager/dist/installers/mcp-binding-shape-mirror.js +105 -0
  238. package/release-manager/package.json +1 -1
  239. package/workbuddy-adapter/dist/codec/input-decoder.d.ts +10 -0
  240. package/workbuddy-adapter/dist/codec/input-decoder.js +62 -5
  241. package/workbuddy-adapter/dist/host-adapter.js +1 -0
  242. package/workbuddy-adapter/dist/index.d.ts +1 -0
  243. package/workbuddy-adapter/dist/index.js +1 -0
  244. package/workbuddy-adapter/dist/ingestion/catch-up.d.ts +25 -0
  245. package/workbuddy-adapter/dist/ingestion/catch-up.js +161 -0
  246. package/workbuddy-adapter/dist/ingestion/encode-cwd.d.ts +6 -0
  247. package/workbuddy-adapter/dist/ingestion/encode-cwd.js +39 -0
  248. package/workbuddy-adapter/dist/ingestion/index.d.ts +13 -0
  249. package/workbuddy-adapter/dist/ingestion/index.js +13 -0
  250. package/workbuddy-adapter/dist/ingestion/ingestion.d.ts +46 -0
  251. package/workbuddy-adapter/dist/ingestion/ingestion.js +135 -0
  252. package/workbuddy-adapter/dist/ingestion/transcript-decoder.d.ts +70 -0
  253. package/workbuddy-adapter/dist/ingestion/transcript-decoder.js +554 -0
  254. package/workbuddy-adapter/dist/ingestion/transcript-path.d.ts +39 -0
  255. package/workbuddy-adapter/dist/ingestion/transcript-path.js +117 -0
  256. package/workbuddy-adapter/dist/ingestion/transcript-source.d.ts +15 -0
  257. package/workbuddy-adapter/dist/ingestion/transcript-source.js +152 -0
  258. package/workbuddy-adapter/dist/pd-hook.d.ts +8 -0
  259. package/workbuddy-adapter/dist/pd-hook.js +59 -2
  260. package/workbuddy-adapter/dist/worker/workspace-worker.d.ts +9 -0
  261. package/workbuddy-adapter/dist/worker/workspace-worker.js +46 -17
  262. package/workbuddy-adapter/package.json +1 -1
  263. package/workbuddy-adapter/plugin/hooks/hooks.json +11 -0
  264. package/workbuddy-adapter/plugin/skills/pd-cli-operator/SKILL.md +57 -19
  265. package/workbuddy-adapter/plugin/skills/pd-control/SKILL.md +21 -9
  266. package/workbuddy-adapter/plugin/skills/pd-pain-signal/SKILL.md +72 -61
  267. package/workbuddy-adapter/plugin/skills/pd-review/SKILL.md +27 -12
@@ -0,0 +1,907 @@
1
+ /**
2
+ * Trajectory retention runner — the I/O boundary of SPEC-PD-TR-001.
3
+ *
4
+ * Ownership:
5
+ * - owns: the workspace paths, the single-instance lock, the marker file, the
6
+ * deleted-row export list, opening `trajectory.db`, the WAL assertion, and
7
+ * the explicit `vacuum` entry point.
8
+ * - does NOT own: the retention policy, cutoff arithmetic, table plan or the
9
+ * batch loop — those are pure and live in
10
+ * `@principles/core/runtime/trajectory-retention`.
11
+ * - does NOT own: blob-file pruning (`openclaw-plugin` trajectory store).
12
+ *
13
+ * Hard constraints inherited from the SPEC:
14
+ * - never called from a hook; callers are the host workers and the explicit
15
+ * `pd trajectory` commands;
16
+ * - never switches `journal_mode` (a mode switch needs an exclusive lock and
17
+ * is exactly the SQLITE_BUSY shape this design avoids);
18
+ * - never runs VACUUM automatically.
19
+ */
20
+ import fs from 'node:fs';
21
+ import path from 'node:path';
22
+ import Database from 'better-sqlite3';
23
+ import { EMPTY_RETENTION_MARKER, computeRetentionCutoff, ensureTrajectoryRetentionIndexes, isRetentionCutoffInWindow, missingTrajectoryRetentionIndexes, normalizeRetentionMarker, nextBackoffUntil, resolveTrajectoryRetentionPolicy, runTrajectoryRetentionBatches, TRAJECTORY_RETENTION_TABLES, } from '@principles/core/runtime';
24
+ import { loadPdConfigForPlugin } from './pd-config.js';
25
+ import { releaseExclusiveLock, tryAcquireExclusiveLockSync, } from './product-telemetry/control-state-lock.js';
26
+ export const TRAJECTORY_RETENTION_MARKER_FILENAME = 'trajectory-retention.json';
27
+ export const TRAJECTORY_RETENTION_LOCK_FILENAME = 'trajectory-retention.lock';
28
+ /** 10 minutes: far above the 3 s run budget, so a live run is never taken over. */
29
+ export const TRAJECTORY_RETENTION_LOCK_STALE_MS = 10 * 60 * 1000;
30
+ /**
31
+ * The maintenance connection waits at most this long for the write lock.
32
+ *
33
+ * SPEC §4.2 says `busy_timeout = 5000`; acceptance criterion A8 requires the
34
+ * maintenance run to yield within 300 ms when another writer holds the lock.
35
+ * Those two cannot both hold, and A8 is the measurable one, so the write lock
36
+ * wait wins: a sweeper that queues behind the user's writer turns a background
37
+ * chore into user-visible latency. Reads in WAL mode do not need this wait.
38
+ *
39
+ * 100 ms (not 250) because SQLite's busy handler overshoots its timeout by up
40
+ * to one sleep step (~100 ms): a 250 ms timeout was measured at ~355 ms
41
+ * wall-clock, which breaks A8. Ordinary host writes hold the lock for
42
+ * milliseconds, so 100 ms is still enough to ride out normal contention.
43
+ */
44
+ export const TRAJECTORY_RETENTION_WRITE_LOCK_WAIT_MS = 100;
45
+ /**
46
+ * Index DDL is NOT the hot path and is NEVER attempted by a regular sweep
47
+ * (F2: a 5 s wait at the start of every run stalled the host). Creation only
48
+ * happens in the explicit maintenance entry, which may use this longer wait.
49
+ */
50
+ export const TRAJECTORY_RETENTION_DDL_BUSY_TIMEOUT_MS = 5000;
51
+ /** VACUUM is a foreground, explicit action; it may wait properly. */
52
+ export const TRAJECTORY_RETENTION_VACUUM_BUSY_TIMEOUT_MS = 5000;
53
+ const GOVERNANCE_EXPIRED_INDEX_SQL = "CREATE INDEX IF NOT EXISTS idx_governance_observations_expired_at "
54
+ + "ON governance_observations(expired_at) "
55
+ + "WHERE retention_class IN ('expired','rolled_back')";
56
+ export function trajectoryRetentionPaths(workspaceDir) {
57
+ const stateDir = path.join(workspaceDir, '.state');
58
+ return {
59
+ stateDir,
60
+ dbPath: path.join(stateDir, 'trajectory.db'),
61
+ markerPath: path.join(stateDir, TRAJECTORY_RETENTION_MARKER_FILENAME),
62
+ lockPath: path.join(stateDir, TRAJECTORY_RETENTION_LOCK_FILENAME),
63
+ exportsDir: path.join(stateDir, 'exports'),
64
+ };
65
+ }
66
+ function readMarkerFile(markerPath) {
67
+ let raw;
68
+ try {
69
+ raw = fs.readFileSync(markerPath, 'utf8');
70
+ }
71
+ catch (error) {
72
+ const code = typeof error === 'object' && error !== null && Object.hasOwn(error, 'code')
73
+ ? String(error.code)
74
+ : '';
75
+ // A missing marker is the normal first-run state, not a degradation.
76
+ return { marker: EMPTY_RETENTION_MARKER, ...(code === 'ENOENT' ? {} : { reason: 'marker_unreadable' }) };
77
+ }
78
+ let parsed;
79
+ try {
80
+ parsed = JSON.parse(raw);
81
+ }
82
+ catch {
83
+ return { marker: EMPTY_RETENTION_MARKER, reason: 'marker_unparseable' };
84
+ }
85
+ // Unparseable timestamps are normalised to null by the marker normaliser, so
86
+ // one corrupt field can never wedge retention (review finding 2).
87
+ const normalized = normalizeRetentionMarker(parsed);
88
+ return {
89
+ marker: normalized.marker,
90
+ ...(normalized.damaged ? { reason: 'marker_shape_invalid' } : {}),
91
+ };
92
+ }
93
+ function writeMarkerAtomic(markerPath, marker) {
94
+ fs.mkdirSync(path.dirname(markerPath), { recursive: true });
95
+ const tmpPath = `${markerPath}.${process.pid}.tmp`;
96
+ fs.writeFileSync(tmpPath, `${JSON.stringify(marker, null, 2)}\n`, 'utf8');
97
+ fs.renameSync(tmpPath, markerPath);
98
+ }
99
+ function markerEquals(a, b) {
100
+ return JSON.stringify(a) === JSON.stringify(b);
101
+ }
102
+ /**
103
+ * A skip is still observable, but it must not rewrite the marker on every
104
+ * 120 s worker cycle. Only a CHANGED skip is persisted.
105
+ */
106
+ function recordSkip(args) {
107
+ const { markerPath, marker, outcome, reason } = args;
108
+ const next = {
109
+ ...marker,
110
+ lastOutcome: outcome,
111
+ reason,
112
+ };
113
+ if (!markerEquals(marker, next)) {
114
+ try {
115
+ writeMarkerAtomic(markerPath, next);
116
+ }
117
+ catch {
118
+ // Observability must never turn a skip into a failure.
119
+ }
120
+ }
121
+ return next;
122
+ }
123
+ function readJournalMode(db) {
124
+ const value = db.pragma('journal_mode', { simple: true });
125
+ return typeof value === 'string' ? value.toLowerCase() : '';
126
+ }
127
+ /**
128
+ * Batch export writer: ONE synchronous append per committed batch.
129
+ *
130
+ * The caller writes outside any write transaction (review finding 3), so this
131
+ * never holds SQLite's write lock during file I/O. It deliberately throws on
132
+ * failure: the caller must fail closed and NOT delete a batch it could not
133
+ * audit (SPEC §8.2, review finding 5).
134
+ */
135
+ function createExportWriter(exportsDir, runDate) {
136
+ let initialized = false;
137
+ return (entries) => {
138
+ if (entries.length === 0)
139
+ return;
140
+ if (!initialized) {
141
+ fs.mkdirSync(exportsDir, { recursive: true });
142
+ initialized = true;
143
+ }
144
+ const filePath = path.join(exportsDir, `trajectory-retention-${runDate}.jsonl`);
145
+ const payload = entries
146
+ .map((entry) => `${JSON.stringify({
147
+ table: entry.table,
148
+ id: entry.id,
149
+ [entry.column]: entry.at,
150
+ })}\n`)
151
+ .join('');
152
+ fs.appendFileSync(filePath, payload, 'utf8');
153
+ };
154
+ }
155
+ function tableExists(db, table) {
156
+ const row = db
157
+ .prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?")
158
+ .get(table);
159
+ return row !== undefined;
160
+ }
161
+ function isRecordValue(value) {
162
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
163
+ }
164
+ /**
165
+ * Oldest stored timestamp across every swept table.
166
+ *
167
+ * Used as the conservative cutoff baseline when the marker carries no
168
+ * `lastCutoff` (first run OR lost marker). It is a durable observation point
169
+ * already present in the database, so it needs no second source of truth, and
170
+ * it caps the first sweep at 7 days just like every later sweep.
171
+ */
172
+ function oldestStoredTimestamp(db) {
173
+ let oldest = null;
174
+ for (const plan of TRAJECTORY_RETENTION_TABLES) {
175
+ if (!tableExists(db, plan.table))
176
+ continue;
177
+ const row = db
178
+ .prepare(`SELECT MIN(${plan.timeColumn}) AS at FROM ${plan.table}`)
179
+ .get();
180
+ if (!isRecordValue(row))
181
+ continue;
182
+ const { at } = row;
183
+ if (typeof at !== 'string' || at.length === 0)
184
+ continue;
185
+ if (oldest === null || at < oldest)
186
+ oldest = at;
187
+ }
188
+ return oldest;
189
+ }
190
+ function prepareRetentionPlan(args) {
191
+ const { db, policy, nowMs } = args;
192
+ let { marker } = args;
193
+ let discardedMarkerCutoff = false;
194
+ // F1: a stored lastCutoff is only a usable lower bound while it lies inside
195
+ // the CURRENT window. A fast clock (or a hand-edited marker) can leave a
196
+ // future value behind; clamping it would still delete rows inside the
197
+ // window, so it is discarded BEFORE the conservative baseline is applied.
198
+ if (marker.lastCutoff !== null
199
+ && !isRetentionCutoffInWindow({
200
+ lastCutoff: marker.lastCutoff,
201
+ nowMs,
202
+ retentionDays: policy.retentionDays,
203
+ })) {
204
+ marker = { ...marker, lastCutoff: null };
205
+ discardedMarkerCutoff = true;
206
+ }
207
+ // Marker loss must not bypass the 7-day cutoff cap. A missing `lastCutoff`
208
+ // covers both "first run" and "marker deleted/corrupted"; the oldest stored
209
+ // row is a durable observation point, so use it as the conservative
210
+ // baseline instead of jumping straight to `now - retentionDays`.
211
+ if (marker.lastCutoff === null) {
212
+ const oldest = oldestStoredTimestamp(db);
213
+ if (oldest !== null)
214
+ marker = { ...marker, lastCutoff: oldest };
215
+ }
216
+ return {
217
+ marker,
218
+ decision: computeRetentionCutoff({
219
+ nowMs,
220
+ retentionDays: policy.retentionDays,
221
+ intervalHours: policy.intervalHours,
222
+ marker,
223
+ }),
224
+ discardedMarkerCutoff,
225
+ };
226
+ }
227
+ /**
228
+ * Maintenance-only DDL. Runs here — never in a schema/open path — because
229
+ * creating an index on a large table costs seconds (SPEC §5.2).
230
+ *
231
+ * Throws on failure; the caller treats that as a degraded run and keeps
232
+ * sweeping (indexes are a performance concern, not a correctness precondition).
233
+ */
234
+ function ensureRetentionIndexes(db) {
235
+ const report = ensureTrajectoryRetentionIndexes(db);
236
+ if (tableExists(db, 'governance_observations')) {
237
+ db.exec(GOVERNANCE_EXPIRED_INDEX_SQL);
238
+ report.applied.push(GOVERNANCE_EXPIRED_INDEX_SQL);
239
+ }
240
+ else {
241
+ report.skipped.push(GOVERNANCE_EXPIRED_INDEX_SQL);
242
+ }
243
+ return report;
244
+ }
245
+ function emptyCounts() {
246
+ return { tool_calls: 0, assistant_turns: 0, user_turns: 0, governance_observations: 0 };
247
+ }
248
+ function publicOutcome(outcome) {
249
+ return outcome === 'deferred_busy' ? 'deferred:busy' : outcome;
250
+ }
251
+ function readCountField(value) {
252
+ if (!isRecordValue(value))
253
+ return 0;
254
+ const count = value.c;
255
+ return typeof count === 'number' ? count : 0;
256
+ }
257
+ function skipReport(args) {
258
+ return {
259
+ outcome: args.outcome,
260
+ reason: args.reason,
261
+ workspaceDir: args.workspaceDir,
262
+ cutoff: args.marker?.lastCutoff ?? null,
263
+ deletedByTable: args.deletedByTable ?? emptyCounts(),
264
+ batches: args.batches ?? 0,
265
+ durationMs: args.durationMs ?? 0,
266
+ totalDurationMs: args.totalDurationMs ?? args.durationMs ?? 0,
267
+ maxBatchDurationMs: 0,
268
+ partial: false,
269
+ backoffUntil: args.marker?.backoffUntil ?? null,
270
+ policy: args.policy,
271
+ indexes: args.indexes ?? null,
272
+ indexesError: args.indexesError ?? null,
273
+ ...(args.nextAction === undefined ? {} : { nextAction: args.nextAction }),
274
+ };
275
+ }
276
+ /**
277
+ * One retention attempt for one workspace.
278
+ *
279
+ * Synchronous on purpose: callers are a worker cycle and a CLI command, both
280
+ * of which already own their concurrency, and a fire-and-forget promise in a
281
+ * worker loop is a crash risk with no upside.
282
+ */
283
+ export function runTrajectoryRetention(options) {
284
+ const now = options.now ?? (() => Date.now());
285
+ const trigger = options.trigger ?? 'worker';
286
+ const startedAt = now();
287
+ const workspaceDir = path.resolve(options.workspaceDir);
288
+ const paths = trajectoryRetentionPaths(workspaceDir);
289
+ // Config first: a malformed .pd/config.yaml must delete NOTHING (fail closed).
290
+ const configResult = loadPdConfigForPlugin(workspaceDir);
291
+ if (!configResult.ok) {
292
+ return skipReport({
293
+ workspaceDir,
294
+ policy: { ...resolveTrajectoryRetentionPolicy(undefined), enabled: false },
295
+ outcome: 'skipped',
296
+ reason: `config_invalid: ${configResult.errors.map((error) => error.reason).join('; ') || 'unknown'}`,
297
+ nextAction: `Fix .pd/config.yaml (${configResult.configPath}); retention stays off until it loads`,
298
+ durationMs: now() - startedAt,
299
+ });
300
+ }
301
+ const policy = resolveTrajectoryRetentionPolicy(configResult.effective.config.trajectoryRetention);
302
+ if (policy.degradedReason !== undefined) {
303
+ return skipReport({
304
+ workspaceDir,
305
+ policy,
306
+ outcome: 'skipped',
307
+ reason: `degraded:${policy.degradedReason}`,
308
+ nextAction: 'Fix trajectoryRetention in .pd/config.yaml (see docs/specs/SPEC-PD-TR-001 §3.1); nothing was deleted',
309
+ durationMs: now() - startedAt,
310
+ });
311
+ }
312
+ if (!policy.enabled) {
313
+ return skipReport({
314
+ workspaceDir,
315
+ policy,
316
+ outcome: 'skipped',
317
+ reason: policy.disabledByZeroDays === true ? 'retention_days_zero' : 'retention_disabled',
318
+ nextAction: 'Set trajectoryRetention.enabled=true (and retentionDays>=7) to resume sweeping',
319
+ durationMs: now() - startedAt,
320
+ });
321
+ }
322
+ if (!fs.existsSync(paths.dbPath)) {
323
+ return skipReport({
324
+ workspaceDir,
325
+ policy,
326
+ outcome: 'skipped',
327
+ reason: 'trajectory_db_missing',
328
+ nextAction: 'Initialize the PD workspace (pd runtime init) before expecting a trajectory sweep',
329
+ durationMs: now() - startedAt,
330
+ });
331
+ }
332
+ const { marker: readMarker, reason: markerReason } = readMarkerFile(paths.markerPath);
333
+ let marker = readMarker;
334
+ if (markerReason !== undefined) {
335
+ // A damaged marker costs at most one extra sweep, but it must be visible.
336
+ marker = recordSkip({
337
+ markerPath: paths.markerPath,
338
+ marker,
339
+ outcome: 'marker_damaged',
340
+ reason: markerReason,
341
+ });
342
+ }
343
+ const nowMs = now();
344
+ if (trigger === 'worker') {
345
+ if (marker.backoffUntil !== null) {
346
+ const backoffMs = Date.parse(marker.backoffUntil);
347
+ if (Number.isFinite(backoffMs) && nowMs < backoffMs) {
348
+ return skipReport({
349
+ workspaceDir,
350
+ policy,
351
+ outcome: 'skipped',
352
+ reason: `backoff:until ${marker.backoffUntil}`,
353
+ nextAction: 'No action needed; the next worker cycle retries after the backoff window',
354
+ durationMs: now() - startedAt,
355
+ marker,
356
+ });
357
+ }
358
+ }
359
+ if (marker.lastRunAt !== null) {
360
+ const lastRunMs = Date.parse(marker.lastRunAt);
361
+ if (Number.isFinite(lastRunMs)) {
362
+ if (nowMs - lastRunMs < policy.intervalHours * 60 * 60 * 1000) {
363
+ return skipReport({
364
+ workspaceDir,
365
+ policy,
366
+ outcome: 'skipped',
367
+ reason: `not_due: interval ${policy.intervalHours}h`,
368
+ durationMs: now() - startedAt,
369
+ marker,
370
+ });
371
+ }
372
+ }
373
+ }
374
+ }
375
+ // ── Single instance (SPEC §4.6) ──────────────────────────────────────────
376
+ fs.mkdirSync(paths.stateDir, { recursive: true });
377
+ let lock;
378
+ try {
379
+ lock = tryAcquireExclusiveLockSync(paths.dbPath, {
380
+ lockPath: paths.lockPath,
381
+ staleMs: TRAJECTORY_RETENTION_LOCK_STALE_MS,
382
+ });
383
+ }
384
+ catch {
385
+ lock = undefined;
386
+ }
387
+ if (lock === undefined) {
388
+ return skipReport({
389
+ workspaceDir,
390
+ policy,
391
+ outcome: 'skipped',
392
+ reason: 'locked',
393
+ nextAction: `Inspect ${paths.lockPath}; a stale lock is taken over automatically after 10 minutes`,
394
+ durationMs: now() - startedAt,
395
+ marker,
396
+ });
397
+ }
398
+ let db;
399
+ // Declared before the try so the catch path can report committed work
400
+ // instead of zeroing it (review finding 4).
401
+ const deletedByTable = {};
402
+ let batches = 0;
403
+ const indexes = null;
404
+ let indexesError = null;
405
+ try {
406
+ db = new Database(paths.dbPath);
407
+ db.pragma(`busy_timeout = ${TRAJECTORY_RETENTION_WRITE_LOCK_WAIT_MS}`);
408
+ const journalMode = readJournalMode(db);
409
+ if (journalMode !== 'wal') {
410
+ const nextMarker = recordSkip({
411
+ markerPath: paths.markerPath,
412
+ marker,
413
+ outcome: 'skipped',
414
+ reason: 'journal_mode_not_wal',
415
+ });
416
+ return skipReport({
417
+ workspaceDir,
418
+ policy,
419
+ outcome: 'skipped',
420
+ reason: `journal_mode_not_wal:${journalMode || 'unknown'}`,
421
+ nextAction: 'Let the host open the trajectory database once (it enables WAL); retention never switches the mode itself',
422
+ durationMs: now() - startedAt,
423
+ marker: nextMarker,
424
+ });
425
+ }
426
+ const plan = prepareRetentionPlan({ db, marker, policy, nowMs });
427
+ ({ marker } = plan);
428
+ const { decision, discardedMarkerCutoff } = plan;
429
+ if (decision.kind === 'skip') {
430
+ // Advancing the clock baseline is what makes the skip recoverable: with
431
+ // `intervalHours=6` the forward limit is 7.5 days, so a laptop that was
432
+ // off longer than that would otherwise skip forever. `lastCutoff` is
433
+ // deliberately NOT advanced (review finding 2).
434
+ const clockSkip = decision.reason === 'clock_backwards'
435
+ || decision.reason === 'clock_forward_anomaly'
436
+ || decision.reason === 'marker_timestamp_invalid';
437
+ const nextMarker = recordSkip({
438
+ markerPath: paths.markerPath,
439
+ marker: clockSkip
440
+ ? { ...marker, lastRunAt: new Date(nowMs).toISOString() }
441
+ : marker,
442
+ outcome: 'skipped',
443
+ reason: decision.reason,
444
+ });
445
+ return skipReport({
446
+ workspaceDir,
447
+ policy,
448
+ outcome: 'skipped',
449
+ reason: decision.reason,
450
+ nextAction: 'Check the system clock; retention resumes on the next run once time is plausible again',
451
+ durationMs: now() - startedAt,
452
+ marker: nextMarker,
453
+ });
454
+ }
455
+ // F2: index creation is NOT part of the regular sweep. `CREATE INDEX` on a
456
+ // database with a concurrent writer can wait for seconds; doing it at the
457
+ // start of every run made a 5.7 s host stall. This run only performs a
458
+ // read-only existence check; creation belongs to the explicit maintenance
459
+ // entry (`pd trajectory vacuum --yes`). Missing indexes degrade the plan,
460
+ // which is surfaced and warned instead of silently blocking the sweep.
461
+ const missingIndexes = missingTrajectoryRetentionIndexes(db);
462
+ if (missingIndexes.length > 0) {
463
+ indexesError = `index_missing:${missingIndexes.join(',')}`;
464
+ }
465
+ const runDate = new Date(nowMs).toISOString().slice(0, 10);
466
+ const appendExport = createExportWriter(paths.exportsDir, runDate);
467
+ const run = runTrajectoryRetentionBatches(db, {
468
+ policy,
469
+ cutoff: decision.cutoff,
470
+ hooks: {
471
+ now,
472
+ onBatchPrepared: ({ table, rows }) => {
473
+ const column = table === 'governance_observations' ? 'expired_at' : 'created_at';
474
+ try {
475
+ // Outside the write transaction: one append for the whole batch.
476
+ appendExport(rows.map((row) => ({ table, id: row.id, column, at: row.at })));
477
+ return null;
478
+ }
479
+ catch (error) {
480
+ // Fail closed: no audit entry ⇒ this batch is not deleted.
481
+ return error instanceof Error ? error.message : String(error);
482
+ }
483
+ },
484
+ onBatchCommitted: ({ table, changes }) => {
485
+ batches += 1;
486
+ deletedByTable[table] = (deletedByTable[table] ?? 0) + changes;
487
+ },
488
+ },
489
+ });
490
+ const totalDurationMs = now() - startedAt;
491
+ // Fill in tables the engine reached even when no batch committed, so a
492
+ // stopped run reports `{ tool_calls: 0 }` rather than an empty object.
493
+ for (const [table, count] of Object.entries(run.deletedByTable)) {
494
+ if (deletedByTable[table] === undefined)
495
+ deletedByTable[table] = count;
496
+ }
497
+ const busyOutcome = run.outcome === 'deferred_busy';
498
+ const invariantViolation = run.outcome === 'invariant_violation';
499
+ // A discarded marker cutoff is a one-off, alarming event; `index_missing`
500
+ // is a standing state that every fresh workspace reports, so the event
501
+ // wins the ledger slot and the standing state stays in `indexesError`.
502
+ const outcomeReason = run.reason
503
+ ?? (discardedMarkerCutoff ? 'marker_cutoff_discarded' : null)
504
+ ?? indexesError;
505
+ const markerNext = {
506
+ // Busy is not a completed attempt: keep lastRunAt so the backoff window
507
+ // is what gates the retry, not a fresh intervalHours wait. An invariant
508
+ // violation also keeps the clock baseline (SPEC §4.5) so the next run
509
+ // re-evaluates the same state instead of waiting a full interval (F5).
510
+ lastRunAt: busyOutcome || invariantViolation
511
+ ? marker.lastRunAt
512
+ : new Date(nowMs).toISOString(),
513
+ // Only a complete sweep may advance the cutoff; a partial run resumes
514
+ // against the SAME predicate (it is naturally idempotent).
515
+ lastCutoff: run.outcome === 'completed' ? decision.cutoff : marker.lastCutoff,
516
+ // SPEC §4.4 records the yield token as `deferred:busy`.
517
+ lastOutcome: publicOutcome(run.outcome),
518
+ deletedByTable,
519
+ durationMs: run.durationMs,
520
+ totalDurationMs,
521
+ partial: run.outcome === 'partial' || run.outcome === 'deadline',
522
+ backoffUntil: busyOutcome
523
+ ? nextBackoffUntil(nowMs, marker.consecutiveBusy + 1)
524
+ : null,
525
+ consecutiveBusy: busyOutcome ? marker.consecutiveBusy + 1 : 0,
526
+ reason: outcomeReason,
527
+ };
528
+ writeMarkerAtomic(paths.markerPath, markerNext);
529
+ const auditFailed = run.reason?.startsWith('audit_failed:') === true;
530
+ return {
531
+ outcome: publicOutcome(run.outcome),
532
+ reason: outcomeReason,
533
+ workspaceDir,
534
+ cutoff: run.cutoff,
535
+ deletedByTable,
536
+ batches,
537
+ durationMs: run.durationMs,
538
+ totalDurationMs,
539
+ maxBatchDurationMs: run.maxBatchDurationMs,
540
+ partial: markerNext.partial,
541
+ backoffUntil: markerNext.backoffUntil,
542
+ policy,
543
+ indexes,
544
+ indexesError,
545
+ ...(run.outcome === 'invariant_violation'
546
+ ? {
547
+ nextAction: 'Row counts did not reconcile; sweeping stopped without deleting further. Inspect trajectory.db and the marker before retrying',
548
+ }
549
+ : {}),
550
+ ...(auditFailed
551
+ ? {
552
+ nextAction: 'The deleted-row audit list could not be written, so the batch was NOT deleted. Check .state/exports permissions and free space',
553
+ }
554
+ : {}),
555
+ };
556
+ }
557
+ catch (error) {
558
+ const message = error instanceof Error ? error.message : String(error);
559
+ const busy = message.includes('SQLITE_BUSY') || message.includes('database is locked');
560
+ const elapsedMs = now() - startedAt;
561
+ // The marker is the ledger, so it must carry THIS run's committed counts.
562
+ // `recordSkip` alone would leave the previous run's numbers in place while
563
+ // the CLI report shows the new ones (review item 2).
564
+ const failedMarker = recordSkip({
565
+ markerPath: paths.markerPath,
566
+ marker: {
567
+ ...marker,
568
+ deletedByTable,
569
+ durationMs: elapsedMs,
570
+ totalDurationMs: elapsedMs,
571
+ partial: !busy,
572
+ },
573
+ outcome: busy ? 'deferred' : 'failed',
574
+ reason: message,
575
+ });
576
+ return skipReport({
577
+ workspaceDir,
578
+ policy,
579
+ outcome: busy ? 'deferred:busy' : 'skipped',
580
+ reason: busy ? `sqlite_busy:${message}` : `failed:${message}`,
581
+ nextAction: busy
582
+ ? 'The next worker cycle retries after the backoff window'
583
+ : 'Inspect the trajectory database; nothing further was deleted',
584
+ durationMs: elapsedMs,
585
+ totalDurationMs: elapsedMs,
586
+ marker: failedMarker,
587
+ // Never zero out what already committed before the exception (review 4).
588
+ deletedByTable,
589
+ batches,
590
+ indexes,
591
+ indexesError,
592
+ });
593
+ }
594
+ finally {
595
+ if (db !== undefined) {
596
+ try {
597
+ db.close();
598
+ }
599
+ catch {
600
+ // closing a failed connection must not mask the real outcome
601
+ }
602
+ }
603
+ if (lock !== undefined)
604
+ releaseExclusiveLock(lock);
605
+ }
606
+ }
607
+ const scheduledWorkspaces = new Set();
608
+ const warnedRetention = new Map();
609
+ /**
610
+ * Long-lived failure reasons repeat on every worker cycle. Return a message
611
+ * only when the reason for THIS workspace changed, so a permanently wrong
612
+ * `journal_mode` or a failing index DDL is visible once, not every 120 s
613
+ * (review finding 7).
614
+ */
615
+ export function retentionWarning(report) {
616
+ const reason = report.reason ?? '';
617
+ const persistent = report.outcome === 'invariant_violation'
618
+ || reason.startsWith('journal_mode_not_wal')
619
+ || reason.startsWith('index_failed')
620
+ || reason.startsWith('index_missing')
621
+ || reason.startsWith('config_invalid')
622
+ || reason.startsWith('degraded:')
623
+ || reason.startsWith('clock_')
624
+ || reason.startsWith('failed:')
625
+ || reason.startsWith('audit_failed:')
626
+ || reason === 'marker_damaged'
627
+ || reason === 'marker_cutoff_discarded';
628
+ if (!persistent) {
629
+ if (report.outcome === 'completed' || report.outcome === 'partial') {
630
+ warnedRetention.delete(report.workspaceDir);
631
+ }
632
+ return null;
633
+ }
634
+ const key = `${report.outcome}|${reason}|${report.indexesError ?? ''}`;
635
+ if (warnedRetention.get(report.workspaceDir) === key)
636
+ return null;
637
+ warnedRetention.set(report.workspaceDir, key);
638
+ return `[PD:TrajectoryRetention] ${report.outcome} reason=${reason}`
639
+ + (report.indexesError === null ? '' : ` indexError=${report.indexesError}`);
640
+ }
641
+ /**
642
+ * Schedule the periodic retention run for a long-lived host process.
643
+ *
644
+ * SPEC §4.1: an unref'd interval in the gateway process. Deliberately does NOT
645
+ * run at scheduling time — that call happens inside `before_prompt_build`, and
646
+ * a 3 s sweep there would be exactly the hook latency A3 forbids. The first
647
+ * attempt happens one minute later, off the hook path.
648
+ *
649
+ * Idempotent per workspace: repeated plugin initialisation cannot stack timers.
650
+ * Config is read once here (interval); the runner re-reads it every cycle, so
651
+ * `enabled`/range changes still take effect.
652
+ */
653
+ export function scheduleTrajectoryRetention(workspaceDirInput, logger) {
654
+ const workspaceDir = path.resolve(workspaceDirInput);
655
+ if (scheduledWorkspaces.has(workspaceDir))
656
+ return;
657
+ scheduledWorkspaces.add(workspaceDir);
658
+ const configResult = loadPdConfigForPlugin(workspaceDir);
659
+ const policy = resolveTrajectoryRetentionPolicy(configResult.ok ? configResult.effective.config.trajectoryRetention : undefined);
660
+ const jitterMs = Math.floor(Math.random() * 10 * 60 * 1000) - 5 * 60 * 1000;
661
+ const intervalMs = Math.max(60_000, policy.intervalHours * 60 * 60 * 1000 + jitterMs);
662
+ const tick = () => {
663
+ try {
664
+ const report = runTrajectoryRetention({ workspaceDir, trigger: 'worker' });
665
+ const warning = retentionWarning(report);
666
+ if (warning !== null) {
667
+ logger?.warn?.(warning);
668
+ return;
669
+ }
670
+ // Busy is an expected yield, already covered by the backoff window.
671
+ if (report.outcome === 'deferred:busy')
672
+ return;
673
+ const deleted = Object.values(report.deletedByTable).reduce((sum, count) => sum + count, 0);
674
+ if (report.outcome === 'skipped' && deleted === 0)
675
+ return;
676
+ const message = `[PD:TrajectoryRetention] ${report.outcome} deleted=${deleted} `
677
+ + `batches=${report.batches} durationMs=${report.totalDurationMs}`
678
+ + (report.reason === null ? '' : ` reason=${report.reason}`);
679
+ if (report.outcome === 'completed' || report.outcome === 'partial') {
680
+ logger?.info?.(message);
681
+ }
682
+ else {
683
+ logger?.warn?.(message);
684
+ }
685
+ }
686
+ catch (error) {
687
+ logger?.warn?.(`[PD:TrajectoryRetention] failed: ${error instanceof Error ? error.message : String(error)}`);
688
+ }
689
+ };
690
+ const initial = setTimeout(tick, 60_000);
691
+ initial.unref?.();
692
+ const timer = setInterval(tick, intervalMs);
693
+ timer.unref?.();
694
+ }
695
+ /**
696
+ * Read-only status: never creates the marker, never opens the database for
697
+ * writing, never creates an index.
698
+ *
699
+ * `now` is injectable so the projected next cutoff can be asserted exactly
700
+ * against the run that follows it (F4: one definition of "expired").
701
+ */
702
+ export function readTrajectoryRetentionStatus(workspaceDirInput, now = () => Date.now()) {
703
+ const workspaceDir = path.resolve(workspaceDirInput);
704
+ const paths = trajectoryRetentionPaths(workspaceDir);
705
+ const configResult = loadPdConfigForPlugin(workspaceDir);
706
+ const policy = resolveTrajectoryRetentionPolicy(configResult.ok ? configResult.effective.config.trajectoryRetention : undefined);
707
+ const read = readMarkerFile(paths.markerPath);
708
+ const dbExists = fs.existsSync(paths.dbPath);
709
+ if (!dbExists) {
710
+ return {
711
+ workspaceDir,
712
+ dbPath: paths.dbPath,
713
+ dbExists,
714
+ marker: read.marker,
715
+ markerError: read.reason ?? null,
716
+ policy,
717
+ nextCutoff: null,
718
+ expiredByTable: null,
719
+ indexesMissing: [],
720
+ dbError: null,
721
+ };
722
+ }
723
+ let db;
724
+ let expiredByTable = null;
725
+ let nextCutoff = null;
726
+ let indexesMissing = [];
727
+ let dbError = null;
728
+ try {
729
+ db = new Database(paths.dbPath, { readonly: true });
730
+ indexesMissing = missingTrajectoryRetentionIndexes(db);
731
+ const plan = prepareRetentionPlan({
732
+ db,
733
+ marker: read.marker,
734
+ policy,
735
+ nowMs: now(),
736
+ });
737
+ const sweepable = policy.enabled && policy.retentionDays > 0;
738
+ nextCutoff = sweepable && plan.decision.kind === 'run' ? plan.decision.cutoff : null;
739
+ if (nextCutoff === null) {
740
+ // A skipped run deletes nothing; reporting counts would promise work the
741
+ // next run will not do (F4).
742
+ dbError = plan.decision.kind === 'skip' ? plan.decision.reason : null;
743
+ }
744
+ else {
745
+ const counts = {};
746
+ for (const [table, column, extra] of [
747
+ ['tool_calls', 'created_at', null],
748
+ ['assistant_turns', 'created_at', null],
749
+ ['user_turns', 'created_at', null],
750
+ ['governance_observations', 'expired_at', "retention_class IN ('expired','rolled_back')"],
751
+ ]) {
752
+ if (!tableExists(db, table)) {
753
+ counts[table] = 0;
754
+ continue;
755
+ }
756
+ const predicate = `${column} IS NOT NULL AND ${column} < ?${extra === null ? '' : ` AND ${extra}`}`;
757
+ const row = db
758
+ .prepare(`SELECT COUNT(*) AS c FROM ${table} WHERE ${predicate}`)
759
+ .get(nextCutoff);
760
+ counts[table] = readCountField(row);
761
+ }
762
+ expiredByTable = counts;
763
+ }
764
+ }
765
+ catch (error) {
766
+ dbError = error instanceof Error ? error.message : String(error);
767
+ }
768
+ finally {
769
+ if (db !== undefined) {
770
+ try {
771
+ db.close();
772
+ }
773
+ catch {
774
+ // read-only handle; nothing to recover
775
+ }
776
+ }
777
+ }
778
+ return {
779
+ workspaceDir,
780
+ dbPath: paths.dbPath,
781
+ dbExists,
782
+ marker: read.marker,
783
+ markerError: read.reason ?? null,
784
+ policy,
785
+ nextCutoff,
786
+ expiredByTable,
787
+ indexesMissing,
788
+ dbError,
789
+ };
790
+ }
791
+ /**
792
+ * `pd trajectory vacuum` — the ONLY place VACUUM may run (SPEC §6).
793
+ *
794
+ * VACUUM takes an exclusive lock and cannot be interrupted, which is why it is
795
+ * never scheduled. Default is a dry run: it reports the space requirement and
796
+ * refuses to start when the filesystem cannot hold `2 × size + 10%`.
797
+ */
798
+ export function vacuumTrajectoryDatabase(args) {
799
+ const now = args.now ?? (() => Date.now());
800
+ const startedAt = now();
801
+ const workspaceDir = path.resolve(args.workspaceDir);
802
+ const paths = trajectoryRetentionPaths(workspaceDir);
803
+ const report = {
804
+ workspaceDir,
805
+ dbPath: paths.dbPath,
806
+ applied: false,
807
+ refusedReason: null,
808
+ sizeBeforeBytes: 0,
809
+ sizeAfterBytes: null,
810
+ freeBytes: null,
811
+ requiredBytes: null,
812
+ freelistBefore: null,
813
+ freelistAfter: null,
814
+ indexes: null,
815
+ durationMs: 0,
816
+ };
817
+ if (!fs.existsSync(paths.dbPath)) {
818
+ return {
819
+ ...report,
820
+ refusedReason: 'trajectory_db_missing',
821
+ nextAction: 'Initialize the PD workspace before vacuuming',
822
+ durationMs: now() - startedAt,
823
+ };
824
+ }
825
+ report.sizeBeforeBytes = fs.statSync(paths.dbPath).size;
826
+ report.requiredBytes = Math.ceil(report.sizeBeforeBytes * 2.1);
827
+ try {
828
+ const stats = fs.statfsSync(path.dirname(paths.dbPath));
829
+ report.freeBytes = Number(stats.bavail) * Number(stats.bsize);
830
+ }
831
+ catch {
832
+ report.freeBytes = null;
833
+ }
834
+ let db;
835
+ try {
836
+ db = new Database(paths.dbPath);
837
+ db.pragma(`busy_timeout = ${TRAJECTORY_RETENTION_VACUUM_BUSY_TIMEOUT_MS}`);
838
+ const freePages = db.pragma('freelist_count', { simple: true });
839
+ report.freelistBefore = typeof freePages === 'number' ? freePages : null;
840
+ const mode = readJournalMode(db);
841
+ if (report.freeBytes === null) {
842
+ return {
843
+ ...report,
844
+ refusedReason: 'free_space_unknown',
845
+ nextAction: `Cannot read free space for ${path.dirname(paths.dbPath)}; close hosts and re-run with --yes only after confirming free disk space`,
846
+ durationMs: now() - startedAt,
847
+ };
848
+ }
849
+ if (report.freeBytes < report.requiredBytes) {
850
+ return {
851
+ ...report,
852
+ refusedReason: 'insufficient_free_space',
853
+ nextAction: `Free at least ${report.requiredBytes - report.freeBytes} more bytes in ${path.dirname(paths.dbPath)} (need 2 x file + 10%)`,
854
+ durationMs: now() - startedAt,
855
+ };
856
+ }
857
+ if (!args.apply) {
858
+ return {
859
+ ...report,
860
+ refusedReason: null,
861
+ nextAction: 'Dry run: re-run with --yes to execute VACUUM (close other hosts first; VACUUM needs an exclusive lock)',
862
+ durationMs: now() - startedAt,
863
+ };
864
+ }
865
+ if (mode !== 'wal' && mode !== 'delete') {
866
+ return {
867
+ ...report,
868
+ refusedReason: `journal_mode_not_supported:${mode}`,
869
+ nextAction: 'Let the host open the trajectory database once, then retry',
870
+ durationMs: now() - startedAt,
871
+ };
872
+ }
873
+ // F2: the ONLY place retention indexes may be created. This command is
874
+ // explicit (--yes), already expects an exclusive lock, and is allowed to
875
+ // hold it; the regular sweep only performs a read-only existence check.
876
+ report.indexes = ensureRetentionIndexes(db);
877
+ db.exec('VACUUM');
878
+ const afterPages = db.pragma('freelist_count', { simple: true });
879
+ report.freelistAfter = typeof afterPages === 'number' ? afterPages : null;
880
+ report.applied = true;
881
+ }
882
+ catch (error) {
883
+ const message = error instanceof Error ? error.message : String(error);
884
+ const busy = message.includes('SQLITE_BUSY') || message.includes('database is locked');
885
+ return {
886
+ ...report,
887
+ refusedReason: busy ? 'database_busy' : `vacuum_failed:${message}`,
888
+ nextAction: busy
889
+ ? 'Close the host (it holds a connection) and retry; VACUUM needs an exclusive lock'
890
+ : 'SQLite leaves the original database intact on failure; retry after checking free space',
891
+ durationMs: now() - startedAt,
892
+ };
893
+ }
894
+ finally {
895
+ if (db !== undefined) {
896
+ try {
897
+ db.close();
898
+ }
899
+ catch {
900
+ // the report already describes the outcome
901
+ }
902
+ }
903
+ }
904
+ report.sizeAfterBytes = fs.statSync(paths.dbPath).size;
905
+ report.durationMs = now() - startedAt;
906
+ return report;
907
+ }