rookery-agent 0.1.0 → 0.3.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.
- package/README.md +467 -367
- package/docs/migration.md +88 -88
- package/docs/updates.md +112 -0
- package/package.json +13 -3
- package/packages/cli/dist/commands/config.js +2 -2
- package/packages/cli/dist/commands/doctor.d.ts.map +1 -1
- package/packages/cli/dist/commands/doctor.js +13 -9
- package/packages/cli/dist/commands/doctor.js.map +1 -1
- package/packages/cli/dist/commands/memory.js +1 -1
- package/packages/cli/dist/commands/org.d.ts +2 -2
- package/packages/cli/dist/commands/org.d.ts.map +1 -1
- package/packages/cli/dist/commands/org.js +19 -17
- package/packages/cli/dist/commands/org.js.map +1 -1
- package/packages/cli/dist/commands/serve.js +1 -1
- package/packages/cli/dist/commands/serve.js.map +1 -1
- package/packages/cli/dist/commands/shared.d.ts.map +1 -1
- package/packages/cli/dist/commands/shared.js +2 -1
- package/packages/cli/dist/commands/shared.js.map +1 -1
- package/packages/cli/dist/commands/tasks.d.ts.map +1 -1
- package/packages/cli/dist/commands/tasks.js +25 -11
- package/packages/cli/dist/commands/tasks.js.map +1 -1
- package/packages/cli/dist/commands/tools.js +1 -1
- package/packages/cli/dist/commands/tools.js.map +1 -1
- package/packages/cli/dist/index.js +13 -13
- package/packages/cli/dist/index.js.map +1 -1
- package/packages/cli/dist/repl.d.ts +12 -0
- package/packages/cli/dist/repl.d.ts.map +1 -1
- package/packages/cli/dist/repl.js +170 -16
- package/packages/cli/dist/repl.js.map +1 -1
- package/packages/cli/dist/tui/App.d.ts +7 -3
- package/packages/cli/dist/tui/App.d.ts.map +1 -1
- package/packages/cli/dist/tui/App.js +182 -16
- package/packages/cli/dist/tui/App.js.map +1 -1
- package/packages/cli/dist/tui/commands.d.ts +7 -0
- package/packages/cli/dist/tui/commands.d.ts.map +1 -1
- package/packages/cli/dist/tui/commands.js +70 -8
- package/packages/cli/dist/tui/commands.js.map +1 -1
- package/packages/cli/dist/tui/components/AssignmentsView.js +4 -4
- package/packages/cli/dist/tui/components/AssignmentsView.js.map +1 -1
- package/packages/cli/dist/tui/components/Banner.d.ts +11 -2
- package/packages/cli/dist/tui/components/Banner.d.ts.map +1 -1
- package/packages/cli/dist/tui/components/Banner.js +7 -10
- package/packages/cli/dist/tui/components/Banner.js.map +1 -1
- package/packages/cli/dist/tui/components/CodeBlock.js +2 -2
- package/packages/cli/dist/tui/components/CodeBlock.js.map +1 -1
- package/packages/cli/dist/tui/components/InputBox.d.ts.map +1 -1
- package/packages/cli/dist/tui/components/InputBox.js +4 -4
- package/packages/cli/dist/tui/components/InputBox.js.map +1 -1
- package/packages/cli/dist/tui/components/Logo.d.ts +56 -0
- package/packages/cli/dist/tui/components/Logo.d.ts.map +1 -0
- package/packages/cli/dist/tui/components/Logo.js +50 -0
- package/packages/cli/dist/tui/components/Logo.js.map +1 -0
- package/packages/cli/dist/tui/components/Markdown.js +8 -8
- package/packages/cli/dist/tui/components/Markdown.js.map +1 -1
- package/packages/cli/dist/tui/components/Message.d.ts +1 -1
- package/packages/cli/dist/tui/components/Message.d.ts.map +1 -1
- package/packages/cli/dist/tui/components/Message.js +5 -4
- package/packages/cli/dist/tui/components/Message.js.map +1 -1
- package/packages/cli/dist/tui/components/QuestionView.d.ts +29 -0
- package/packages/cli/dist/tui/components/QuestionView.d.ts.map +1 -0
- package/packages/cli/dist/tui/components/QuestionView.js +53 -0
- package/packages/cli/dist/tui/components/QuestionView.js.map +1 -0
- package/packages/cli/dist/tui/components/SlashPalette.d.ts +5 -2
- package/packages/cli/dist/tui/components/SlashPalette.d.ts.map +1 -1
- package/packages/cli/dist/tui/components/SlashPalette.js +2 -2
- package/packages/cli/dist/tui/components/SlashPalette.js.map +1 -1
- package/packages/cli/dist/tui/components/StatusLine.d.ts +0 -2
- package/packages/cli/dist/tui/components/StatusLine.d.ts.map +1 -1
- package/packages/cli/dist/tui/components/StatusLine.js +8 -5
- package/packages/cli/dist/tui/components/StatusLine.js.map +1 -1
- package/packages/cli/dist/tui/components/ToolGroup.js +2 -2
- package/packages/cli/dist/tui/components/ToolGroup.js.map +1 -1
- package/packages/cli/dist/tui/components/WatchView.d.ts +21 -0
- package/packages/cli/dist/tui/components/WatchView.d.ts.map +1 -0
- package/packages/cli/dist/tui/components/WatchView.js +36 -0
- package/packages/cli/dist/tui/components/WatchView.js.map +1 -0
- package/packages/cli/dist/tui/history.d.ts +20 -0
- package/packages/cli/dist/tui/history.d.ts.map +1 -0
- package/packages/cli/dist/tui/history.js +105 -0
- package/packages/cli/dist/tui/history.js.map +1 -0
- package/packages/cli/dist/tui/hooks/useSlash.d.ts.map +1 -1
- package/packages/cli/dist/tui/hooks/useSlash.js +3 -2
- package/packages/cli/dist/tui/hooks/useSlash.js.map +1 -1
- package/packages/cli/dist/tui/hooks/useTurn.d.ts +58 -1
- package/packages/cli/dist/tui/hooks/useTurn.d.ts.map +1 -1
- package/packages/cli/dist/tui/hooks/useTurn.js +214 -36
- package/packages/cli/dist/tui/hooks/useTurn.js.map +1 -1
- package/packages/cli/dist/tui/hooks/useWatch.d.ts +52 -0
- package/packages/cli/dist/tui/hooks/useWatch.d.ts.map +1 -0
- package/packages/cli/dist/tui/hooks/useWatch.js +145 -0
- package/packages/cli/dist/tui/hooks/useWatch.js.map +1 -0
- package/packages/cli/dist/tui/inkTheme.d.ts +19 -0
- package/packages/cli/dist/tui/inkTheme.d.ts.map +1 -0
- package/packages/cli/dist/tui/inkTheme.js +81 -0
- package/packages/cli/dist/tui/inkTheme.js.map +1 -0
- package/packages/cli/dist/tui/theme.d.ts +39 -29
- package/packages/cli/dist/tui/theme.d.ts.map +1 -1
- package/packages/cli/dist/tui/theme.js +35 -25
- package/packages/cli/dist/tui/theme.js.map +1 -1
- package/packages/cli/dist/tui/types.d.ts +56 -3
- package/packages/cli/dist/tui/types.d.ts.map +1 -1
- package/packages/cli/dist/tui/types.js +85 -0
- package/packages/cli/dist/tui/types.js.map +1 -1
- package/packages/cli/dist/ui/modelNames.d.ts +51 -0
- package/packages/cli/dist/ui/modelNames.d.ts.map +1 -0
- package/packages/cli/dist/ui/modelNames.js +134 -0
- package/packages/cli/dist/ui/modelNames.js.map +1 -0
- package/packages/cli/dist/ui/render.d.ts.map +1 -1
- package/packages/cli/dist/ui/render.js +17 -8
- package/packages/cli/dist/ui/render.js.map +1 -1
- package/packages/cli/dist/ui/speech.js +5 -0
- package/packages/cli/dist/ui/speech.js.map +1 -1
- package/packages/cli/dist/ui/theme.d.ts +33 -9
- package/packages/cli/dist/ui/theme.d.ts.map +1 -1
- package/packages/cli/dist/ui/theme.js +33 -9
- package/packages/cli/dist/ui/theme.js.map +1 -1
- package/packages/cli/package.json +1 -1
- package/packages/core/dist/agents/persona.d.ts.map +1 -1
- package/packages/core/dist/agents/persona.js +5 -2
- package/packages/core/dist/agents/persona.js.map +1 -1
- package/packages/core/dist/computer/accessibility.d.ts +78 -0
- package/packages/core/dist/computer/accessibility.d.ts.map +1 -0
- package/packages/core/dist/computer/accessibility.js +270 -0
- package/packages/core/dist/computer/accessibility.js.map +1 -0
- package/packages/core/dist/computer/assemblies.d.ts +17 -0
- package/packages/core/dist/computer/assemblies.d.ts.map +1 -0
- package/packages/core/dist/computer/assemblies.js +55 -0
- package/packages/core/dist/computer/assemblies.js.map +1 -0
- package/packages/core/dist/computer/browser-init.d.ts +9 -0
- package/packages/core/dist/computer/browser-init.d.ts.map +1 -0
- package/packages/core/dist/computer/browser-init.js +133 -0
- package/packages/core/dist/computer/browser-init.js.map +1 -0
- package/packages/core/dist/computer/cursor.d.ts +30 -0
- package/packages/core/dist/computer/cursor.d.ts.map +1 -0
- package/packages/core/dist/computer/cursor.js +30 -0
- package/packages/core/dist/computer/cursor.js.map +1 -0
- package/packages/core/dist/computer/mcp-server.js +524 -82
- package/packages/core/dist/computer/mcp-server.js.map +1 -1
- package/packages/core/dist/computer/powershell.d.ts +4 -0
- package/packages/core/dist/computer/powershell.d.ts.map +1 -1
- package/packages/core/dist/computer/powershell.js +471 -81
- package/packages/core/dist/computer/powershell.js.map +1 -1
- package/packages/core/dist/computer/screen-text.d.ts +82 -0
- package/packages/core/dist/computer/screen-text.d.ts.map +1 -0
- package/packages/core/dist/computer/screen-text.js +243 -0
- package/packages/core/dist/computer/screen-text.js.map +1 -0
- package/packages/core/dist/computer/sketch.d.ts +66 -0
- package/packages/core/dist/computer/sketch.d.ts.map +1 -0
- package/packages/core/dist/computer/sketch.js +540 -0
- package/packages/core/dist/computer/sketch.js.map +1 -0
- package/packages/core/dist/computer/tools.d.ts +8 -8
- package/packages/core/dist/computer/tools.d.ts.map +1 -1
- package/packages/core/dist/computer/tools.js +186 -31
- package/packages/core/dist/computer/tools.js.map +1 -1
- package/packages/core/dist/computer/validation.d.ts +555 -0
- package/packages/core/dist/computer/validation.d.ts.map +1 -0
- package/packages/core/dist/computer/validation.js +111 -0
- package/packages/core/dist/computer/validation.js.map +1 -0
- package/packages/core/dist/computer/windows-cursor.d.ts +14 -0
- package/packages/core/dist/computer/windows-cursor.d.ts.map +1 -0
- package/packages/core/dist/computer/windows-cursor.js +713 -0
- package/packages/core/dist/computer/windows-cursor.js.map +1 -0
- package/packages/core/dist/config.d.ts +34 -1
- package/packages/core/dist/config.d.ts.map +1 -1
- package/packages/core/dist/config.js +362 -11
- package/packages/core/dist/config.js.map +1 -1
- package/packages/core/dist/cron/scheduler.d.ts +59 -6
- package/packages/core/dist/cron/scheduler.d.ts.map +1 -1
- package/packages/core/dist/cron/scheduler.js +295 -27
- package/packages/core/dist/cron/scheduler.js.map +1 -1
- package/packages/core/dist/cron/store.d.ts +19 -1
- package/packages/core/dist/cron/store.d.ts.map +1 -1
- package/packages/core/dist/cron/store.js +36 -8
- package/packages/core/dist/cron/store.js.map +1 -1
- package/packages/core/dist/external/claude-code.d.ts +4 -0
- package/packages/core/dist/external/claude-code.d.ts.map +1 -0
- package/packages/core/dist/external/claude-code.js +111 -0
- package/packages/core/dist/external/claude-code.js.map +1 -0
- package/packages/core/dist/external/discovery.d.ts +33 -0
- package/packages/core/dist/external/discovery.d.ts.map +1 -0
- package/packages/core/dist/external/discovery.js +144 -0
- package/packages/core/dist/external/discovery.js.map +1 -0
- package/packages/core/dist/external/homes.d.ts +26 -0
- package/packages/core/dist/external/homes.d.ts.map +1 -0
- package/packages/core/dist/external/homes.js +49 -0
- package/packages/core/dist/external/homes.js.map +1 -0
- package/packages/core/dist/external/shared.d.ts +201 -0
- package/packages/core/dist/external/shared.d.ts.map +1 -0
- package/packages/core/dist/external/shared.js +308 -0
- package/packages/core/dist/external/shared.js.map +1 -0
- package/packages/core/dist/gateway/policy.d.ts +117 -2
- package/packages/core/dist/gateway/policy.d.ts.map +1 -1
- package/packages/core/dist/gateway/policy.js +286 -6
- package/packages/core/dist/gateway/policy.js.map +1 -1
- package/packages/core/dist/index.d.ts +38 -12
- package/packages/core/dist/index.d.ts.map +1 -1
- package/packages/core/dist/index.js +66 -12
- package/packages/core/dist/index.js.map +1 -1
- package/packages/core/dist/memory/db.d.ts +1 -1
- package/packages/core/dist/memory/db.d.ts.map +1 -1
- package/packages/core/dist/memory/db.js +878 -1
- package/packages/core/dist/memory/db.js.map +1 -1
- package/packages/core/dist/memory/dream/admission.d.ts +124 -0
- package/packages/core/dist/memory/dream/admission.d.ts.map +1 -0
- package/packages/core/dist/memory/dream/admission.js +116 -0
- package/packages/core/dist/memory/dream/admission.js.map +1 -0
- package/packages/core/dist/memory/dream/candidate.d.ts +152 -0
- package/packages/core/dist/memory/dream/candidate.d.ts.map +1 -0
- package/packages/core/dist/memory/dream/candidate.js +547 -0
- package/packages/core/dist/memory/dream/candidate.js.map +1 -0
- package/packages/core/dist/memory/dream/evaluate.d.ts +394 -0
- package/packages/core/dist/memory/dream/evaluate.d.ts.map +1 -0
- package/packages/core/dist/memory/dream/evaluate.js +1032 -0
- package/packages/core/dist/memory/dream/evaluate.js.map +1 -0
- package/packages/core/dist/memory/dream/frame.d.ts +61 -0
- package/packages/core/dist/memory/dream/frame.d.ts.map +1 -0
- package/packages/core/dist/memory/dream/frame.js +292 -0
- package/packages/core/dist/memory/dream/frame.js.map +1 -0
- package/packages/core/dist/memory/dream/label.d.ts +370 -0
- package/packages/core/dist/memory/dream/label.d.ts.map +1 -0
- package/packages/core/dist/memory/dream/label.js +439 -0
- package/packages/core/dist/memory/dream/label.js.map +1 -0
- package/packages/core/dist/memory/dream/measure.d.ts +114 -0
- package/packages/core/dist/memory/dream/measure.d.ts.map +1 -0
- package/packages/core/dist/memory/dream/measure.js +205 -0
- package/packages/core/dist/memory/dream/measure.js.map +1 -0
- package/packages/core/dist/memory/dream/policy.d.ts +21 -0
- package/packages/core/dist/memory/dream/policy.d.ts.map +1 -0
- package/packages/core/dist/memory/dream/policy.js +157 -0
- package/packages/core/dist/memory/dream/policy.js.map +1 -0
- package/packages/core/dist/memory/dream/probe.d.ts +202 -0
- package/packages/core/dist/memory/dream/probe.d.ts.map +1 -0
- package/packages/core/dist/memory/dream/probe.js +671 -0
- package/packages/core/dist/memory/dream/probe.js.map +1 -0
- package/packages/core/dist/memory/dream/promote.d.ts +312 -0
- package/packages/core/dist/memory/dream/promote.d.ts.map +1 -0
- package/packages/core/dist/memory/dream/promote.js +528 -0
- package/packages/core/dist/memory/dream/promote.js.map +1 -0
- package/packages/core/dist/memory/dream/score.d.ts +103 -0
- package/packages/core/dist/memory/dream/score.d.ts.map +1 -0
- package/packages/core/dist/memory/dream/score.js +334 -0
- package/packages/core/dist/memory/dream/score.js.map +1 -0
- package/packages/core/dist/memory/dream/slots.d.ts +193 -0
- package/packages/core/dist/memory/dream/slots.d.ts.map +1 -0
- package/packages/core/dist/memory/dream/slots.js +0 -0
- package/packages/core/dist/memory/dream/slots.js.map +1 -0
- package/packages/core/dist/memory/dream/trajectory.d.ts +262 -0
- package/packages/core/dist/memory/dream/trajectory.d.ts.map +1 -0
- package/packages/core/dist/memory/dream/trajectory.js +366 -0
- package/packages/core/dist/memory/dream/trajectory.js.map +1 -0
- package/packages/core/dist/memory/extractor.d.ts +7 -0
- package/packages/core/dist/memory/extractor.d.ts.map +1 -1
- package/packages/core/dist/memory/extractor.js +35 -12
- package/packages/core/dist/memory/extractor.js.map +1 -1
- package/packages/core/dist/memory/gate.d.ts +43 -7
- package/packages/core/dist/memory/gate.d.ts.map +1 -1
- package/packages/core/dist/memory/gate.js +91 -4
- package/packages/core/dist/memory/gate.js.map +1 -1
- package/packages/core/dist/memory/recall.d.ts +57 -0
- package/packages/core/dist/memory/recall.d.ts.map +1 -1
- package/packages/core/dist/memory/recall.js +60 -123
- package/packages/core/dist/memory/recall.js.map +1 -1
- package/packages/core/dist/memory/sleep.d.ts +131 -4
- package/packages/core/dist/memory/sleep.d.ts.map +1 -1
- package/packages/core/dist/memory/sleep.js +2384 -65
- package/packages/core/dist/memory/sleep.js.map +1 -1
- package/packages/core/dist/memory/store.d.ts +564 -10
- package/packages/core/dist/memory/store.d.ts.map +1 -1
- package/packages/core/dist/memory/store.js +1673 -102
- package/packages/core/dist/memory/store.js.map +1 -1
- package/packages/core/dist/org/controller.d.ts +268 -4
- package/packages/core/dist/org/controller.d.ts.map +1 -1
- package/packages/core/dist/org/controller.js +2298 -248
- package/packages/core/dist/org/controller.js.map +1 -1
- package/packages/core/dist/org/ponytail.d.ts +1 -1
- package/packages/core/dist/org/ponytail.js +1 -1
- package/packages/core/dist/org/project-mcp.d.ts +3 -3
- package/packages/core/dist/org/prompts.d.ts +44 -30
- package/packages/core/dist/org/prompts.d.ts.map +1 -1
- package/packages/core/dist/org/prompts.js +209 -92
- package/packages/core/dist/org/prompts.js.map +1 -1
- package/packages/core/dist/org/questions.d.ts +104 -0
- package/packages/core/dist/org/questions.d.ts.map +1 -0
- package/packages/core/dist/org/questions.js +136 -0
- package/packages/core/dist/org/questions.js.map +1 -0
- package/packages/core/dist/org/review.d.ts +100 -0
- package/packages/core/dist/org/review.d.ts.map +1 -0
- package/packages/core/dist/org/review.js +256 -0
- package/packages/core/dist/org/review.js.map +1 -0
- package/packages/core/dist/org/store.d.ts +311 -2
- package/packages/core/dist/org/store.d.ts.map +1 -1
- package/packages/core/dist/org/store.js +981 -13
- package/packages/core/dist/org/store.js.map +1 -1
- package/packages/core/dist/org/tools.d.ts +33 -3
- package/packages/core/dist/org/tools.d.ts.map +1 -1
- package/packages/core/dist/org/tools.js +380 -67
- package/packages/core/dist/org/tools.js.map +1 -1
- package/packages/core/dist/providers/catalogue.d.ts +1 -1
- package/packages/core/dist/providers/catalogue.d.ts.map +1 -1
- package/packages/core/dist/providers/catalogue.js +2 -2
- package/packages/core/dist/providers/catalogue.js.map +1 -1
- package/packages/core/dist/providers/claude-code.d.ts +19 -3
- package/packages/core/dist/providers/claude-code.d.ts.map +1 -1
- package/packages/core/dist/providers/claude-code.js +501 -40
- package/packages/core/dist/providers/claude-code.js.map +1 -1
- package/packages/core/dist/providers/claude-tui.d.ts +288 -0
- package/packages/core/dist/providers/claude-tui.d.ts.map +1 -0
- package/packages/core/dist/providers/claude-tui.js +1118 -0
- package/packages/core/dist/providers/claude-tui.js.map +1 -0
- package/packages/core/dist/providers/codex-auth.d.ts +15 -0
- package/packages/core/dist/providers/codex-auth.d.ts.map +1 -0
- package/packages/core/dist/providers/codex-auth.js +127 -0
- package/packages/core/dist/providers/codex-auth.js.map +1 -0
- package/packages/core/dist/providers/codex-bridge.d.ts +58 -0
- package/packages/core/dist/providers/codex-bridge.d.ts.map +1 -0
- package/packages/core/dist/providers/codex-bridge.js +375 -0
- package/packages/core/dist/providers/codex-bridge.js.map +1 -0
- package/packages/core/dist/providers/codex-translate.d.ts +75 -0
- package/packages/core/dist/providers/codex-translate.d.ts.map +1 -0
- package/packages/core/dist/providers/codex-translate.js +383 -0
- package/packages/core/dist/providers/codex-translate.js.map +1 -0
- package/packages/core/dist/providers/model-gateway.d.ts +56 -0
- package/packages/core/dist/providers/model-gateway.d.ts.map +1 -0
- package/packages/core/dist/providers/model-gateway.js +119 -0
- package/packages/core/dist/providers/model-gateway.js.map +1 -0
- package/packages/core/dist/providers/process.d.ts +3 -1
- package/packages/core/dist/providers/process.d.ts.map +1 -1
- package/packages/core/dist/providers/process.js +3 -3
- package/packages/core/dist/providers/process.js.map +1 -1
- package/packages/core/dist/providers/profiles.d.ts +11 -0
- package/packages/core/dist/providers/profiles.d.ts.map +1 -0
- package/packages/core/dist/providers/profiles.js +28 -0
- package/packages/core/dist/providers/profiles.js.map +1 -0
- package/packages/core/dist/providers/provider-catalog.d.ts +72 -0
- package/packages/core/dist/providers/provider-catalog.d.ts.map +1 -0
- package/packages/core/dist/providers/provider-catalog.js +144 -0
- package/packages/core/dist/providers/provider-catalog.js.map +1 -0
- package/packages/core/dist/providers/quota.d.ts +40 -1
- package/packages/core/dist/providers/quota.d.ts.map +1 -1
- package/packages/core/dist/providers/quota.js +288 -25
- package/packages/core/dist/providers/quota.js.map +1 -1
- package/packages/core/dist/providers/registry.d.ts +46 -3
- package/packages/core/dist/providers/registry.d.ts.map +1 -1
- package/packages/core/dist/providers/registry.js +148 -13
- package/packages/core/dist/providers/registry.js.map +1 -1
- package/packages/core/dist/providers/router.d.ts +28 -0
- package/packages/core/dist/providers/router.d.ts.map +1 -0
- package/packages/core/dist/providers/router.js +88 -0
- package/packages/core/dist/providers/router.js.map +1 -0
- package/packages/core/dist/providers/user-settings-guard.d.ts +12 -0
- package/packages/core/dist/providers/user-settings-guard.d.ts.map +1 -0
- package/packages/core/dist/providers/user-settings-guard.js +130 -0
- package/packages/core/dist/providers/user-settings-guard.js.map +1 -0
- package/packages/core/dist/runtime.d.ts +193 -7
- package/packages/core/dist/runtime.d.ts.map +1 -1
- package/packages/core/dist/runtime.js +1676 -219
- package/packages/core/dist/runtime.js.map +1 -1
- package/packages/core/dist/skills/builtin.d.ts +34 -0
- package/packages/core/dist/skills/builtin.d.ts.map +1 -0
- package/packages/core/dist/skills/builtin.js +305 -0
- package/packages/core/dist/skills/builtin.js.map +1 -0
- package/packages/core/dist/skills/shelf.d.ts +30 -0
- package/packages/core/dist/skills/shelf.d.ts.map +1 -0
- package/packages/core/dist/skills/shelf.js +159 -0
- package/packages/core/dist/skills/shelf.js.map +1 -0
- package/packages/core/dist/skills/store.d.ts +66 -4
- package/packages/core/dist/skills/store.d.ts.map +1 -1
- package/packages/core/dist/skills/store.js +105 -18
- package/packages/core/dist/skills/store.js.map +1 -1
- package/packages/core/dist/skills/suggest.d.ts +21 -0
- package/packages/core/dist/skills/suggest.d.ts.map +1 -0
- package/packages/core/dist/skills/suggest.js +150 -0
- package/packages/core/dist/skills/suggest.js.map +1 -0
- package/packages/core/dist/tools/catalog.d.ts +1 -3
- package/packages/core/dist/tools/catalog.d.ts.map +1 -1
- package/packages/core/dist/tools/catalog.js +38 -26
- package/packages/core/dist/tools/catalog.js.map +1 -1
- package/packages/core/dist/tools/hub.d.ts +136 -10
- package/packages/core/dist/tools/hub.d.ts.map +1 -1
- package/packages/core/dist/tools/hub.js +418 -24
- package/packages/core/dist/tools/hub.js.map +1 -1
- package/packages/core/dist/turns/journal.d.ts +78 -0
- package/packages/core/dist/turns/journal.d.ts.map +1 -0
- package/packages/core/dist/turns/journal.js +104 -0
- package/packages/core/dist/turns/journal.js.map +1 -0
- package/packages/core/dist/types.d.ts +1776 -12
- package/packages/core/dist/types.d.ts.map +1 -1
- package/packages/core/dist/types.js.map +1 -1
- package/packages/core/dist/util/blocks.d.ts +41 -0
- package/packages/core/dist/util/blocks.d.ts.map +1 -0
- package/packages/core/dist/util/blocks.js +175 -0
- package/packages/core/dist/util/blocks.js.map +1 -0
- package/packages/core/dist/util/queue.d.ts +12 -0
- package/packages/core/dist/util/queue.d.ts.map +1 -1
- package/packages/core/dist/util/queue.js +16 -0
- package/packages/core/dist/util/queue.js.map +1 -1
- package/packages/core/dist/util/time.d.ts +39 -0
- package/packages/core/dist/util/time.d.ts.map +1 -0
- package/packages/core/dist/util/time.js +71 -0
- package/packages/core/dist/util/time.js.map +1 -0
- package/packages/core/package.json +1 -1
- package/packages/server/dist/auth.d.ts +14 -1
- package/packages/server/dist/auth.d.ts.map +1 -1
- package/packages/server/dist/auth.js +19 -0
- package/packages/server/dist/auth.js.map +1 -1
- package/packages/server/dist/context.d.ts +35 -1
- package/packages/server/dist/context.d.ts.map +1 -1
- package/packages/server/dist/context.js +39 -10
- package/packages/server/dist/context.js.map +1 -1
- package/packages/server/dist/gateways/attachments.d.ts +32 -0
- package/packages/server/dist/gateways/attachments.d.ts.map +1 -0
- package/packages/server/dist/gateways/attachments.js +167 -0
- package/packages/server/dist/gateways/attachments.js.map +1 -0
- package/packages/server/dist/gateways/markdown.d.ts +9 -0
- package/packages/server/dist/gateways/markdown.d.ts.map +1 -0
- package/packages/server/dist/gateways/markdown.js +170 -0
- package/packages/server/dist/gateways/markdown.js.map +1 -0
- package/packages/server/dist/gateways/push.d.ts +1 -1
- package/packages/server/dist/gateways/push.d.ts.map +1 -1
- package/packages/server/dist/gateways/push.js +420 -13
- package/packages/server/dist/gateways/push.js.map +1 -1
- package/packages/server/dist/gateways/telegram-api.d.ts +70 -1
- package/packages/server/dist/gateways/telegram-api.d.ts.map +1 -1
- package/packages/server/dist/gateways/telegram-api.js +140 -1
- package/packages/server/dist/gateways/telegram-api.js.map +1 -1
- package/packages/server/dist/gateways/telegram.d.ts +181 -1
- package/packages/server/dist/gateways/telegram.d.ts.map +1 -1
- package/packages/server/dist/gateways/telegram.js +1572 -78
- package/packages/server/dist/gateways/telegram.js.map +1 -1
- package/packages/server/dist/gateways/threads.d.ts +84 -0
- package/packages/server/dist/gateways/threads.d.ts.map +1 -0
- package/packages/server/dist/gateways/threads.js +289 -0
- package/packages/server/dist/gateways/threads.js.map +1 -0
- package/packages/server/dist/index.d.ts +2 -1
- package/packages/server/dist/index.d.ts.map +1 -1
- package/packages/server/dist/index.js +2 -1
- package/packages/server/dist/index.js.map +1 -1
- package/packages/server/dist/listeners/imap.d.ts +13 -0
- package/packages/server/dist/listeners/imap.d.ts.map +1 -0
- package/packages/server/dist/listeners/imap.js +0 -0
- package/packages/server/dist/listeners/imap.js.map +1 -0
- package/packages/server/dist/listeners/registry.d.ts +18 -0
- package/packages/server/dist/listeners/registry.d.ts.map +1 -0
- package/packages/server/dist/listeners/registry.js +88 -0
- package/packages/server/dist/listeners/registry.js.map +1 -0
- package/packages/server/dist/listeners/types.d.ts +55 -0
- package/packages/server/dist/listeners/types.d.ts.map +1 -0
- package/packages/server/dist/listeners/types.js +2 -0
- package/packages/server/dist/listeners/types.js.map +1 -0
- package/packages/server/dist/main.js +15 -1
- package/packages/server/dist/main.js.map +1 -1
- package/packages/server/dist/routes/chat.d.ts +7 -3
- package/packages/server/dist/routes/chat.d.ts.map +1 -1
- package/packages/server/dist/routes/chat.js +8 -17
- package/packages/server/dist/routes/chat.js.map +1 -1
- package/packages/server/dist/routes/config.d.ts.map +1 -1
- package/packages/server/dist/routes/config.js +66 -7
- package/packages/server/dist/routes/config.js.map +1 -1
- package/packages/server/dist/routes/cron.d.ts.map +1 -1
- package/packages/server/dist/routes/cron.js +65 -8
- package/packages/server/dist/routes/cron.js.map +1 -1
- package/packages/server/dist/routes/dream.d.ts +22 -0
- package/packages/server/dist/routes/dream.d.ts.map +1 -0
- package/packages/server/dist/routes/dream.js +152 -0
- package/packages/server/dist/routes/dream.js.map +1 -0
- package/packages/server/dist/routes/hooks.d.ts +18 -0
- package/packages/server/dist/routes/hooks.d.ts.map +1 -0
- package/packages/server/dist/routes/hooks.js +62 -0
- package/packages/server/dist/routes/hooks.js.map +1 -0
- package/packages/server/dist/routes/listeners.d.ts +10 -0
- package/packages/server/dist/routes/listeners.d.ts.map +1 -0
- package/packages/server/dist/routes/listeners.js +12 -0
- package/packages/server/dist/routes/listeners.js.map +1 -0
- package/packages/server/dist/routes/memories.d.ts.map +1 -1
- package/packages/server/dist/routes/memories.js +55 -3
- package/packages/server/dist/routes/memories.js.map +1 -1
- package/packages/server/dist/routes/org.d.ts.map +1 -1
- package/packages/server/dist/routes/org.js +289 -49
- package/packages/server/dist/routes/org.js.map +1 -1
- package/packages/server/dist/routes/profile.d.ts.map +1 -1
- package/packages/server/dist/routes/profile.js +6 -3
- package/packages/server/dist/routes/profile.js.map +1 -1
- package/packages/server/dist/routes/providers.d.ts.map +1 -1
- package/packages/server/dist/routes/providers.js +66 -7
- package/packages/server/dist/routes/providers.js.map +1 -1
- package/packages/server/dist/routes/questions.d.ts +45 -0
- package/packages/server/dist/routes/questions.d.ts.map +1 -0
- package/packages/server/dist/routes/questions.js +73 -0
- package/packages/server/dist/routes/questions.js.map +1 -0
- package/packages/server/dist/routes/sessions.d.ts.map +1 -1
- package/packages/server/dist/routes/sessions.js +26 -6
- package/packages/server/dist/routes/sessions.js.map +1 -1
- package/packages/server/dist/routes/sleep.d.ts.map +1 -1
- package/packages/server/dist/routes/sleep.js +71 -2
- package/packages/server/dist/routes/sleep.js.map +1 -1
- package/packages/server/dist/routes/terminals.d.ts +25 -0
- package/packages/server/dist/routes/terminals.d.ts.map +1 -0
- package/packages/server/dist/routes/terminals.js +35 -0
- package/packages/server/dist/routes/terminals.js.map +1 -0
- package/packages/server/dist/routes/tools.d.ts.map +1 -1
- package/packages/server/dist/routes/tools.js +140 -6
- package/packages/server/dist/routes/tools.js.map +1 -1
- package/packages/server/dist/routes/updates.d.ts +10 -0
- package/packages/server/dist/routes/updates.d.ts.map +1 -0
- package/packages/server/dist/routes/updates.js +22 -0
- package/packages/server/dist/routes/updates.js.map +1 -0
- package/packages/server/dist/routes/ws.d.ts +11 -5
- package/packages/server/dist/routes/ws.d.ts.map +1 -1
- package/packages/server/dist/routes/ws.js +168 -28
- package/packages/server/dist/routes/ws.js.map +1 -1
- package/packages/server/dist/schemas.d.ts +1177 -215
- package/packages/server/dist/schemas.d.ts.map +1 -1
- package/packages/server/dist/schemas.js +317 -12
- package/packages/server/dist/schemas.js.map +1 -1
- package/packages/server/dist/server.d.ts +7 -1
- package/packages/server/dist/server.d.ts.map +1 -1
- package/packages/server/dist/server.js +210 -3
- package/packages/server/dist/server.js.map +1 -1
- package/packages/server/dist/services/stream.d.ts +94 -5
- package/packages/server/dist/services/stream.d.ts.map +1 -1
- package/packages/server/dist/services/stream.js +9 -20
- package/packages/server/dist/services/stream.js.map +1 -1
- package/packages/server/dist/services/stt.d.ts +65 -0
- package/packages/server/dist/services/stt.d.ts.map +1 -0
- package/packages/server/dist/services/stt.js +306 -0
- package/packages/server/dist/services/stt.js.map +1 -0
- package/packages/server/dist/services/turns.d.ts +54 -0
- package/packages/server/dist/services/turns.d.ts.map +1 -0
- package/packages/server/dist/services/turns.js +186 -0
- package/packages/server/dist/services/turns.js.map +1 -0
- package/packages/server/dist/services/updates.d.ts +99 -0
- package/packages/server/dist/services/updates.d.ts.map +1 -0
- package/packages/server/dist/services/updates.js +316 -0
- package/packages/server/dist/services/updates.js.map +1 -0
- package/packages/server/package.json +1 -1
- package/packages/web/dist/app-icon.svg +2 -0
- package/packages/web/dist/apple-touch-icon.png +0 -0
- package/packages/web/dist/assets/abnfDiagram-O67JEVCF-D7YyFndQ.js +1 -0
- package/packages/web/dist/assets/arc-C_Zgk2dJ.js +1 -0
- package/packages/web/dist/assets/architectureDiagram-NJMV4G6O-eI0adu1B.js +36 -0
- package/packages/web/dist/assets/blockDiagram-BEXU5L5S-WAoOFUA9.js +140 -0
- package/packages/web/dist/assets/c4Diagram-YGBWAQC7-DE8Zyhng.js +38 -0
- package/packages/web/dist/assets/channel-egZxcyUK.js +1 -0
- package/packages/web/dist/assets/chunk-2Q5K7J3B-bnqLP2XD.js +1 -0
- package/packages/web/dist/assets/chunk-3FUC2YCW-Ck1_SVe0.js +2 -0
- package/packages/web/dist/assets/chunk-5VM5RSS4-hDmC41gD.js +15 -0
- package/packages/web/dist/assets/chunk-GTNCS2PH-PoWvfCrT.js +88 -0
- package/packages/web/dist/assets/chunk-GWA4HPMP-D3V0IG43.js +1 -0
- package/packages/web/dist/assets/chunk-JWPE2WC7-BryfpHM5.js +1 -0
- package/packages/web/dist/assets/chunk-NETBCI7D-8ic1iEdT.js +1 -0
- package/packages/web/dist/assets/chunk-WEXAMYUT-nM8tmQT2.js +1 -0
- package/packages/web/dist/assets/chunk-XXDRQBXY-Do28F482.js +1 -0
- package/packages/web/dist/assets/classDiagram-v2-NBCMYWYE-Bop9oNNO.js +217 -0
- package/packages/web/dist/assets/cose-bilkent-JH36ORCC-a7f_bpnt.js +1 -0
- package/packages/web/dist/assets/cynefin-OW5HDTMX-DnArcis_.js +178 -0
- package/packages/web/dist/assets/cynefinDiagram-VND7K2PF-vEuTb1GD.js +62 -0
- package/packages/web/dist/assets/cytoscape.esm-Ix0LnXOy.js +331 -0
- package/packages/web/dist/assets/dagre-6A5THRUB-BgG4MynJ.js +4 -0
- package/packages/web/dist/assets/diagram-22UHCM2B-DRCQpafv.js +200 -0
- package/packages/web/dist/assets/diagram-3UASUU5V-BKgmAXde.js +24 -0
- package/packages/web/dist/assets/diagram-ATOU4E4O-B6Hsy36X.js +3 -0
- package/packages/web/dist/assets/diagram-CDSNMT55-JflyfyoB.js +30 -0
- package/packages/web/dist/assets/diagram-MLGK6HIB-Dd2QPJjT.js +24 -0
- package/packages/web/dist/assets/diagram-MPIPVDR6-DE5QU60x.js +41 -0
- package/packages/web/dist/assets/draco_decoder-C32yEggz.wasm +0 -0
- package/packages/web/dist/assets/draco_decoder-Z1_iN-Ht.wasm +0 -0
- package/packages/web/dist/assets/draco_decoder-fzg4nYZr.js +34 -0
- package/packages/web/dist/assets/draco_wasm_wrapper-DxJM36Ib.js +117 -0
- package/packages/web/dist/assets/draco_wasm_wrapper-fZCQGLGb.js +116 -0
- package/packages/web/dist/assets/ebnfDiagram-ZINNZB2B-D7AQ741b.js +1 -0
- package/packages/web/dist/assets/elk-276RUBZZ-CeewBVLF.js +27 -0
- package/packages/web/dist/assets/erDiagram-OPXOYQCR-mLLYkZ5c.js +99 -0
- package/packages/web/dist/assets/flowDiagram-KWPJA3E3-DtpSpsQN.js +213 -0
- package/packages/web/dist/assets/ganttDiagram-FUAMR5RP-1_lh-3ky.js +292 -0
- package/packages/web/dist/assets/gitGraphDiagram-X574FWY7-DoPXZuT5.js +106 -0
- package/packages/web/dist/assets/graph-Bn3Yngep.js +1 -0
- package/packages/web/dist/assets/index-Cw2Opmx7.js +648 -0
- package/packages/web/dist/assets/index-j0zBRCgT.css +32 -0
- package/packages/web/dist/assets/infoDiagram-VRGFBTTK-DQpRGGiD.js +2 -0
- package/packages/web/dist/assets/ishikawaDiagram-OU5B5YK6-gH5C9Q2e.js +70 -0
- package/packages/web/dist/assets/journeyDiagram-ZHPQQLJL-Bg-oeFjb.js +139 -0
- package/packages/web/dist/assets/kanban-definition-PNTS6WVX-BnpI4VH8.js +89 -0
- package/packages/web/dist/assets/katex-C5jXJg4s.js +257 -0
- package/packages/web/dist/assets/mermaid.core-BwBKxlRA.js +313 -0
- package/packages/web/dist/assets/mindmap-definition-NLK3R4M7-NBnnxEoO.js +96 -0
- package/packages/web/dist/assets/pegDiagram-GJSIUBJH-RrXXbIvO.js +1 -0
- package/packages/web/dist/assets/pieDiagram-5QR66LMP-B27q6Gso.js +39 -0
- package/packages/web/dist/assets/quadrantDiagram-O4NWA36T-DGDsdur2.js +7 -0
- package/packages/web/dist/assets/railroadDiagram-XR7U4H2S-GdjkE3mI.js +1 -0
- package/packages/web/dist/assets/requirementDiagram-PLB6GJNP-DjK0GfgO.js +84 -0
- package/packages/web/dist/assets/sankeyDiagram-IPEJSGJF-BG_AIkwF.js +40 -0
- package/packages/web/dist/assets/scene-D4LPicHk.js +4620 -0
- package/packages/web/dist/assets/sequenceDiagram-PO4LG4MO-CIQwUb4y.js +169 -0
- package/packages/web/dist/assets/sizeCapture-INFHLROL-bpIoPxdJ.js +1 -0
- package/packages/web/dist/assets/stateDiagram-v2-GCMORJYK-8hYXvPPv.js +291 -0
- package/packages/web/dist/assets/swimlanes-2SLR337P-gfflUMF9.js +1 -0
- package/packages/web/dist/assets/swimlanesDiagram-TC7HE7FX-9wdzGXU-.js +8 -0
- package/packages/web/dist/assets/timeline-definition-EJHVYXUP-PHMNoGTZ.js +120 -0
- package/packages/web/dist/assets/usecaseDiagram-POWQR4AR-B2j5iteO.js +370 -0
- package/packages/web/dist/assets/vennDiagram-UO4OBE2U-BzxtZ-_2.js +34 -0
- package/packages/web/dist/assets/wardleyDiagram-VNRHLVJA-DL7YbMpY.js +78 -0
- package/packages/web/dist/assets/xychartDiagram-PMCCYNJV-CisgP1cT.js +7 -0
- package/packages/web/dist/draco/draco_decoder.js +33 -0
- package/packages/web/dist/draco/draco_decoder.wasm +0 -0
- package/packages/web/dist/draco/draco_wasm_wrapper.js +116 -0
- package/packages/web/dist/favicon-16.png +0 -0
- package/packages/web/dist/favicon-32.png +0 -0
- package/packages/web/dist/favicon-48.png +0 -0
- package/packages/web/dist/favicon.ico +0 -0
- package/packages/web/dist/favicon.svg +1 -1
- package/packages/web/dist/icon-192.png +0 -0
- package/packages/web/dist/icon-512.png +0 -0
- package/packages/web/dist/index.html +12 -4
- package/packages/web/dist/logo-light.svg +1 -1
- package/packages/web/dist/logo-mono.svg +2 -0
- package/packages/web/dist/logo-stacked-light.svg +2 -0
- package/packages/web/dist/logo-stacked.svg +2 -0
- package/packages/web/dist/logo-white.svg +2 -0
- package/packages/web/dist/logo.svg +1 -1
- package/packages/web/dist/mark-light.svg +1 -1
- package/packages/web/dist/mark-mono.svg +2 -0
- package/packages/web/dist/mark-small-light.svg +2 -0
- package/packages/web/dist/mark-small.svg +2 -0
- package/packages/web/dist/mark-white.svg +2 -0
- package/packages/web/dist/mark.svg +1 -1
- package/packages/web/dist/models/LICENSE.txt +5 -0
- package/packages/web/dist/models/brain.glb +0 -0
- package/packages/web/dist/site.webmanifest +23 -0
- package/packages/web/dist/wordmark-light.svg +2 -0
- package/packages/web/dist/wordmark.svg +2 -0
- package/packages/web/package.json +1 -1
- package/scripts/rookery.mjs +204 -122
- package/scripts/updater.mjs +227 -0
- package/packages/cli/dist/tui/components/Wordmark.d.ts +0 -35
- package/packages/cli/dist/tui/components/Wordmark.d.ts.map +0 -1
- package/packages/cli/dist/tui/components/Wordmark.js +0 -81
- package/packages/cli/dist/tui/components/Wordmark.js.map +0 -1
- package/packages/core/dist/agents/orchestrator.d.ts +0 -24
- package/packages/core/dist/agents/orchestrator.d.ts.map +0 -1
- package/packages/core/dist/agents/orchestrator.js +0 -88
- package/packages/core/dist/agents/orchestrator.js.map +0 -1
- package/packages/core/dist/agents/roles.d.ts +0 -21
- package/packages/core/dist/agents/roles.d.ts.map +0 -1
- package/packages/core/dist/agents/roles.js +0 -81
- package/packages/core/dist/agents/roles.js.map +0 -1
- package/packages/core/dist/agents/team.d.ts +0 -105
- package/packages/core/dist/agents/team.d.ts.map +0 -1
- package/packages/core/dist/agents/team.js +0 -623
- package/packages/core/dist/agents/team.js.map +0 -1
- package/packages/core/dist/providers/codex.d.ts +0 -10
- package/packages/core/dist/providers/codex.d.ts.map +0 -1
- package/packages/core/dist/providers/codex.js +0 -375
- package/packages/core/dist/providers/codex.js.map +0 -1
- package/packages/core/dist/tools/browser.d.ts +0 -20
- package/packages/core/dist/tools/browser.d.ts.map +0 -1
- package/packages/core/dist/tools/browser.js +0 -72
- package/packages/core/dist/tools/browser.js.map +0 -1
- package/packages/server/dist/routes/agents.d.ts +0 -5
- package/packages/server/dist/routes/agents.d.ts.map +0 -1
- package/packages/server/dist/routes/agents.js +0 -6
- package/packages/server/dist/routes/agents.js.map +0 -1
- package/packages/server/dist/routes/team.d.ts +0 -11
- package/packages/server/dist/routes/team.d.ts.map +0 -1
- package/packages/server/dist/routes/team.js +0 -36
- package/packages/server/dist/routes/team.js.map +0 -1
- package/packages/web/dist/assets/3d-force-graph-BPZmoydi.js +0 -1163
- package/packages/web/dist/assets/index-IBSTzK7-.js +0 -1255
- package/packages/web/dist/assets/index-qUXUui7W.css +0 -1
- package/packages/web/dist/assets/three-spritetext-B9ZIW7c-.js +0 -4
- package/packages/web/dist/assets/three.module-cmFfBtHS.js +0 -4228
|
@@ -3,6 +3,20 @@ import { ASSISTANT_MEMORY_OWNER, } from '../types.js';
|
|
|
3
3
|
import { openDatabase } from './db.js';
|
|
4
4
|
import { OrgStore } from '../org/store.js';
|
|
5
5
|
import { CronStore } from '../cron/store.js';
|
|
6
|
+
import { TurnJournal } from '../turns/journal.js';
|
|
7
|
+
/** meta key prefix under which one corpus fingerprint per night is stored. */
|
|
8
|
+
const CORPUS_STAMP_PREFIX = 'dream.corpus_stamp.';
|
|
9
|
+
/** meta key prefix holding which stamp id is current for an owner. */
|
|
10
|
+
const CORPUS_CURRENT_PREFIX = 'dream.corpus_current.';
|
|
11
|
+
/**
|
|
12
|
+
* The shipped `dream.maxFrameBytes`. The Store holds no config, so the caller
|
|
13
|
+
* reads the key (key table in the build plan, E21: clamped where it is read)
|
|
14
|
+
* and passes it to `saveFrame`; this default is what a caller gets that does
|
|
15
|
+
* not carry the config with it.
|
|
16
|
+
*/
|
|
17
|
+
const DEFAULT_MAX_FRAME_BYTES = 120_000;
|
|
18
|
+
/** How many rows one sweep batch deletes before it commits and continues. */
|
|
19
|
+
const SWEEP_BATCH = 500;
|
|
6
20
|
/** All persistence for sessions, transcripts, long-term memories, the organisation and schedules. */
|
|
7
21
|
export class Store {
|
|
8
22
|
db;
|
|
@@ -10,10 +24,13 @@ export class Store {
|
|
|
10
24
|
org;
|
|
11
25
|
/** Schedules and their runs. */
|
|
12
26
|
cron;
|
|
27
|
+
/** The running-turn journal: every event of a conversation turn, as it happens. */
|
|
28
|
+
turns;
|
|
13
29
|
constructor(pathOrDb) {
|
|
14
30
|
this.db = typeof pathOrDb === 'string' ? openDatabase(pathOrDb) : pathOrDb;
|
|
15
31
|
this.org = new OrgStore(this.db);
|
|
16
32
|
this.cron = new CronStore(this.db);
|
|
33
|
+
this.turns = new TurnJournal(this.db);
|
|
17
34
|
}
|
|
18
35
|
close() {
|
|
19
36
|
this.db.close();
|
|
@@ -39,15 +56,15 @@ export class Store {
|
|
|
39
56
|
.prepare(
|
|
40
57
|
// `agent` is omitted on purpose: the column survives for old rows but
|
|
41
58
|
// a session no longer has one, so it falls back to its SQL default.
|
|
42
|
-
`INSERT INTO sessions
|
|
43
|
-
(id, title, kind, provider, model, cwd, project_id, agent_id, provider_session_id, created_at, updated_at, archived)
|
|
59
|
+
`INSERT INTO sessions
|
|
60
|
+
(id, title, kind, provider, model, cwd, project_id, agent_id, provider_session_id, created_at, updated_at, archived)
|
|
44
61
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, NULL, ?, ?, 0)`)
|
|
45
62
|
.run(session.id, session.title, session.kind, session.provider, session.model ?? null, session.cwd, session.projectId ?? null, session.agentId ?? null, now, now);
|
|
46
63
|
return session;
|
|
47
64
|
}
|
|
48
65
|
getSession(id) {
|
|
49
66
|
const row = this.db
|
|
50
|
-
.prepare(`SELECT s.*, (SELECT COUNT(*) FROM messages m WHERE m.session_id = s.id) AS message_count
|
|
67
|
+
.prepare(`SELECT s.*, (SELECT COUNT(*) FROM messages m WHERE m.session_id = s.id) AS message_count
|
|
51
68
|
FROM sessions s WHERE s.id = ?`)
|
|
52
69
|
.get(id);
|
|
53
70
|
return row ? mapSession(row) : null;
|
|
@@ -59,7 +76,11 @@ export class Store {
|
|
|
59
76
|
listSessions(options = {}) {
|
|
60
77
|
const limit = options.limit ?? 50;
|
|
61
78
|
const scope = (options.agentId === undefined ? '' : options.agentId === null ? ' AND s.agent_id IS NULL' : ' AND s.agent_id = ?') +
|
|
62
|
-
|
|
79
|
+
// A mail answer's or a cron run's transcript is not a conversation to
|
|
80
|
+
// browse, so both stay out of every open list. Asking for `kind:
|
|
81
|
+
// 'mail'` or `kind: 'schedule'` still finds them - the rule is "not by
|
|
82
|
+
// default", not "never".
|
|
83
|
+
(options.kind ? ' AND s.kind = ?' : " AND s.kind NOT IN ('mail', 'schedule')");
|
|
63
84
|
const values = [options.includeArchived ? 1 : 0];
|
|
64
85
|
if (options.agentId)
|
|
65
86
|
values.push(options.agentId);
|
|
@@ -67,10 +88,10 @@ export class Store {
|
|
|
67
88
|
values.push(options.kind);
|
|
68
89
|
values.push(limit);
|
|
69
90
|
const rows = this.db
|
|
70
|
-
.prepare(`SELECT s.*, (SELECT COUNT(*) FROM messages m WHERE m.session_id = s.id) AS message_count
|
|
71
|
-
FROM sessions s
|
|
72
|
-
WHERE (? = 1 OR s.archived = 0)` + scope + `
|
|
73
|
-
ORDER BY s.updated_at DESC
|
|
91
|
+
.prepare(`SELECT s.*, (SELECT COUNT(*) FROM messages m WHERE m.session_id = s.id) AS message_count
|
|
92
|
+
FROM sessions s
|
|
93
|
+
WHERE (? = 1 OR s.archived = 0)` + scope + `
|
|
94
|
+
ORDER BY s.updated_at DESC
|
|
74
95
|
LIMIT ?`)
|
|
75
96
|
.all(...values);
|
|
76
97
|
return rows.map(mapSession);
|
|
@@ -101,6 +122,17 @@ export class Store {
|
|
|
101
122
|
this.db.prepare('UPDATE sessions SET ' + sets.join(', ') + ' WHERE id = ?').run(...values);
|
|
102
123
|
}
|
|
103
124
|
deleteSession(id) {
|
|
125
|
+
// A run's transcript is not part of the conversation that ordered it.
|
|
126
|
+
//
|
|
127
|
+
// `turns.session_id` cascades on session delete, which is right for the
|
|
128
|
+
// chat turns of that conversation - they are the conversation. It is
|
|
129
|
+
// wrong for the runs started from it: deleting a chat silently took the
|
|
130
|
+
// transcripts of every agent run it had launched, while the assignment
|
|
131
|
+
// rows (which have no foreign key) stayed behind holding results whose
|
|
132
|
+
// working record had just been thrown away. Cutting the link first
|
|
133
|
+
// keeps the transcript and loses only what it was - a pointer back to a
|
|
134
|
+
// conversation that no longer exists.
|
|
135
|
+
this.db.prepare("UPDATE turns SET session_id = NULL WHERE session_id = ? AND kind = 'assign'").run(id);
|
|
104
136
|
this.db.prepare('DELETE FROM sessions WHERE id = ?').run(id);
|
|
105
137
|
}
|
|
106
138
|
/* ---------------------------- messages ---------------------------- */
|
|
@@ -115,12 +147,14 @@ export class Store {
|
|
|
115
147
|
agent: input.agent,
|
|
116
148
|
usage: input.usage,
|
|
117
149
|
toolCalls: input.toolCalls,
|
|
150
|
+
blocks: input.blocks,
|
|
151
|
+
turnId: input.turnId,
|
|
118
152
|
createdAt: Date.now(),
|
|
119
153
|
};
|
|
120
154
|
this.db
|
|
121
|
-
.prepare(`INSERT INTO messages (id, session_id, role, content, provider, model, agent, usage, created_at, tool_calls)
|
|
122
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)
|
|
123
|
-
.run(message.id, message.sessionId, message.role, message.content, message.provider ?? null, message.model ?? null, message.agent ?? null, message.usage ? JSON.stringify(message.usage) : null, message.createdAt, message.toolCalls?.length ? JSON.stringify(message.toolCalls) : null);
|
|
155
|
+
.prepare(`INSERT INTO messages (id, session_id, role, content, provider, model, agent, usage, created_at, tool_calls, blocks, turn_id)
|
|
156
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)
|
|
157
|
+
.run(message.id, message.sessionId, message.role, message.content, message.provider ?? null, message.model ?? null, message.agent ?? null, message.usage ? JSON.stringify(message.usage) : null, message.createdAt, message.toolCalls?.length ? JSON.stringify(message.toolCalls) : null, message.blocks?.length ? JSON.stringify(message.blocks) : null, message.turnId ?? null);
|
|
124
158
|
this.db
|
|
125
159
|
.prepare('UPDATE sessions SET updated_at = ? WHERE id = ?')
|
|
126
160
|
.run(message.createdAt, message.sessionId);
|
|
@@ -130,8 +164,8 @@ export class Store {
|
|
|
130
164
|
getMessages(sessionId, limit) {
|
|
131
165
|
const rows = limit
|
|
132
166
|
? this.db
|
|
133
|
-
.prepare(`SELECT * FROM (
|
|
134
|
-
SELECT * FROM messages WHERE session_id = ? ORDER BY created_at DESC LIMIT ?
|
|
167
|
+
.prepare(`SELECT * FROM (
|
|
168
|
+
SELECT * FROM messages WHERE session_id = ? ORDER BY created_at DESC LIMIT ?
|
|
135
169
|
) ORDER BY created_at ASC`)
|
|
136
170
|
.all(sessionId, limit)
|
|
137
171
|
: this.db
|
|
@@ -168,12 +202,23 @@ export class Store {
|
|
|
168
202
|
const base = Math.max(Number(existing.importance), input.importance ?? 0.5);
|
|
169
203
|
const importance = base >= 0.8 ? Math.min(1, base) : Math.min(1, base + 0.02);
|
|
170
204
|
const tags = mergeTags(parseTags(existing.tags), input.tags ?? []);
|
|
205
|
+
// The quote is only ever filled in, never replaced: the first words
|
|
206
|
+
// that confirmed a fact are the ones worth keeping, and a row written
|
|
207
|
+
// before evidence existed gets one the next time it is heard again.
|
|
208
|
+
const evidence = existing.evidence ?? input.evidence?.trim() ?? null;
|
|
209
|
+
// Waking a dormant row is a change to what the night did, so when a
|
|
210
|
+
// sleep run condensed a sentence that byte-exactly matches a memory an
|
|
211
|
+
// earlier night had filed away, the revival carries that run's id like
|
|
212
|
+
// every other touch - otherwise undoing the run cannot know it happened.
|
|
213
|
+
// A plain reinforcement of an awake row keeps the id it already has.
|
|
214
|
+
const revivedByRun = input.sleepRunId && existing.dormant_at != null ? input.sleepRunId : null;
|
|
171
215
|
this.db
|
|
172
|
-
.prepare(`UPDATE memories
|
|
173
|
-
SET importance = ?, tags = ?, updated_at = ?, forgotten = 0,
|
|
174
|
-
dormant_at = NULL, superseded_by = NULL
|
|
216
|
+
.prepare(`UPDATE memories
|
|
217
|
+
SET importance = ?, tags = ?, evidence = ?, updated_at = ?, forgotten = 0,
|
|
218
|
+
dormant_at = NULL, superseded_by = NULL,
|
|
219
|
+
sleep_run_id = COALESCE(?, sleep_run_id)
|
|
175
220
|
WHERE id = ?`)
|
|
176
|
-
.run(importance, JSON.stringify(tags), now, existing.id);
|
|
221
|
+
.run(importance, JSON.stringify(tags), evidence, now, revivedByRun, existing.id);
|
|
177
222
|
return this.getMemory(existing.id);
|
|
178
223
|
}
|
|
179
224
|
const record = {
|
|
@@ -183,6 +228,7 @@ export class Store {
|
|
|
183
228
|
tags: input.tags ?? [],
|
|
184
229
|
importance: clamp01(input.importance ?? 0.5),
|
|
185
230
|
owner,
|
|
231
|
+
evidence: input.evidence?.trim() || undefined,
|
|
186
232
|
sourceSessionId: input.sourceSessionId,
|
|
187
233
|
createdAt: now,
|
|
188
234
|
updatedAt: now,
|
|
@@ -194,18 +240,24 @@ export class Store {
|
|
|
194
240
|
usefulness: 0,
|
|
195
241
|
};
|
|
196
242
|
this.db
|
|
197
|
-
.prepare(`INSERT INTO memories
|
|
198
|
-
(id, kind, content, tags, importance, owner, source_session_id, created_at,
|
|
199
|
-
access_count, forgotten, origin, pinned, sleep_run_id, usefulness)
|
|
200
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 0, 0, ?, ?, ?, 0)`)
|
|
201
|
-
.run(record.id, record.kind, record.content, JSON.stringify(record.tags), record.importance, record.owner, record.sourceSessionId ?? null, now, now, record.origin, record.pinned ? 1 : 0, record.sleepRunId ?? null);
|
|
243
|
+
.prepare(`INSERT INTO memories
|
|
244
|
+
(id, kind, content, tags, importance, owner, evidence, source_session_id, created_at,
|
|
245
|
+
updated_at, access_count, forgotten, origin, pinned, sleep_run_id, usefulness)
|
|
246
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0, 0, ?, ?, ?, 0)`)
|
|
247
|
+
.run(record.id, record.kind, record.content, JSON.stringify(record.tags), record.importance, record.owner, record.evidence ?? null, record.sourceSessionId ?? null, now, now, record.origin, record.pinned ? 1 : 0, record.sleepRunId ?? null);
|
|
202
248
|
return record;
|
|
203
249
|
}
|
|
204
250
|
/**
|
|
205
251
|
* Edit a memory in place. Used by the inspector (pin, re-word, change
|
|
206
252
|
* weight, wake it up) and by the sleep run when it retires one.
|
|
253
|
+
*
|
|
254
|
+
* `actor` says who asked for the edit (concept 4.2b, S5). It defaults to
|
|
255
|
+
* `'model'` so no existing call site changes meaning, and only `'user'`
|
|
256
|
+
* leaves a `user` label behind: pinning is the user saying "this was the
|
|
257
|
+
* point", forgetting is the user saying "this was ballast", and neither
|
|
258
|
+
* claim may be manufactured by the model's own tool.
|
|
207
259
|
*/
|
|
208
|
-
updateMemory(id, patch) {
|
|
260
|
+
updateMemory(id, patch, actor = 'model') {
|
|
209
261
|
const columns = {
|
|
210
262
|
content: 'content',
|
|
211
263
|
kind: 'kind',
|
|
@@ -234,6 +286,14 @@ export class Store {
|
|
|
234
286
|
sets.push('updated_at = ?');
|
|
235
287
|
values.push(Date.now(), id);
|
|
236
288
|
this.db.prepare('UPDATE memories SET ' + sets.join(', ') + ' WHERE id = ?').run(...values);
|
|
289
|
+
// Two patch fields carry a verdict, and only those two: pinning says the
|
|
290
|
+
// row belonged in the prompt, forgetting says it did not. Everything else
|
|
291
|
+
// the inspector can change (wording, weight, tags) says nothing about any
|
|
292
|
+
// turn and writes no label.
|
|
293
|
+
if (actor === 'user' && patch.pinned === true)
|
|
294
|
+
this.#writeUserLabel(id, 1, 'updateMemory:user');
|
|
295
|
+
if (actor === 'user' && patch.forgotten === true)
|
|
296
|
+
this.#writeUserLabel(id, 0, 'updateMemory:user');
|
|
237
297
|
return this.getMemory(id);
|
|
238
298
|
}
|
|
239
299
|
/**
|
|
@@ -248,9 +308,9 @@ export class Store {
|
|
|
248
308
|
// says. Bumping it made an old memory look fresh to the recency score,
|
|
249
309
|
// so after an undo the night would no longer recognise it as stale.
|
|
250
310
|
this.db
|
|
251
|
-
.prepare(`UPDATE memories
|
|
252
|
-
SET dormant_at = ?, superseded_by = ?,
|
|
253
|
-
sleep_run_id = COALESCE(?, sleep_run_id)
|
|
311
|
+
.prepare(`UPDATE memories
|
|
312
|
+
SET dormant_at = ?, superseded_by = ?,
|
|
313
|
+
sleep_run_id = COALESCE(?, sleep_run_id)
|
|
254
314
|
WHERE id = ?`)
|
|
255
315
|
.run(Date.now(), options.supersededBy ?? null, options.runId ?? null, id);
|
|
256
316
|
}
|
|
@@ -294,11 +354,11 @@ export class Store {
|
|
|
294
354
|
*/
|
|
295
355
|
memoriesWithoutEntities(owner, limit = 500) {
|
|
296
356
|
const rows = this.db
|
|
297
|
-
.prepare(`SELECT m.* FROM memories m
|
|
298
|
-
WHERE m.owner = ? AND m.forgotten = 0 AND m.dormant_at IS NULL
|
|
299
|
-
AND m.tags != '[]'
|
|
300
|
-
AND NOT EXISTS (SELECT 1 FROM memory_entity_links l WHERE l.memory_id = m.id)
|
|
301
|
-
ORDER BY m.importance DESC
|
|
357
|
+
.prepare(`SELECT m.* FROM memories m
|
|
358
|
+
WHERE m.owner = ? AND m.forgotten = 0 AND m.dormant_at IS NULL
|
|
359
|
+
AND m.tags != '[]'
|
|
360
|
+
AND NOT EXISTS (SELECT 1 FROM memory_entity_links l WHERE l.memory_id = m.id)
|
|
361
|
+
ORDER BY m.importance DESC
|
|
302
362
|
LIMIT ?`)
|
|
303
363
|
.all(owner, limit);
|
|
304
364
|
return rows.map(mapMemory);
|
|
@@ -306,8 +366,8 @@ export class Store {
|
|
|
306
366
|
/** Every live memory of one owner, oldest first. The sleep run's input. */
|
|
307
367
|
liveMemories(owner) {
|
|
308
368
|
const rows = this.db
|
|
309
|
-
.prepare(`SELECT * FROM memories
|
|
310
|
-
WHERE owner = ? AND forgotten = 0 AND dormant_at IS NULL
|
|
369
|
+
.prepare(`SELECT * FROM memories
|
|
370
|
+
WHERE owner = ? AND forgotten = 0 AND dormant_at IS NULL
|
|
311
371
|
ORDER BY created_at ASC`)
|
|
312
372
|
.all(owner);
|
|
313
373
|
return rows.map(mapMemory);
|
|
@@ -315,9 +375,9 @@ export class Store {
|
|
|
315
375
|
/** Owners with at least one live memory. Used to decide which banks sleep. */
|
|
316
376
|
memoryOwners() {
|
|
317
377
|
const rows = this.db
|
|
318
|
-
.prepare(`SELECT owner, COUNT(*) AS live, MAX(created_at) AS newest
|
|
319
|
-
FROM memories
|
|
320
|
-
WHERE forgotten = 0 AND dormant_at IS NULL
|
|
378
|
+
.prepare(`SELECT owner, COUNT(*) AS live, MAX(created_at) AS newest
|
|
379
|
+
FROM memories
|
|
380
|
+
WHERE forgotten = 0 AND dormant_at IS NULL
|
|
321
381
|
GROUP BY owner`)
|
|
322
382
|
.all();
|
|
323
383
|
return rows.map((row) => ({
|
|
@@ -326,31 +386,125 @@ export class Store {
|
|
|
326
386
|
newest: Number(row.newest ?? 0),
|
|
327
387
|
}));
|
|
328
388
|
}
|
|
329
|
-
/**
|
|
330
|
-
|
|
389
|
+
/**
|
|
390
|
+
* Soft delete, so a wrong memory can be audited rather than vanishing.
|
|
391
|
+
*
|
|
392
|
+
* Frames quote the memories they froze verbatim, so forgetting one must
|
|
393
|
+
* reach them too (R17): never keep a wording longer than the memory it
|
|
394
|
+
* came from. The drop is owner-level because a frame is a snapshot of
|
|
395
|
+
* many rows and cannot be edited piecemeal.
|
|
396
|
+
*
|
|
397
|
+
* `actor` follows `updateMemory`: `'model'` unless the HTTP path says
|
|
398
|
+
* otherwise, and only `'user'` leaves a label (S5).
|
|
399
|
+
*/
|
|
400
|
+
forgetMemory(id, actor = 'model') {
|
|
401
|
+
const row = this.db.prepare('SELECT owner FROM memories WHERE id = ?').get(id);
|
|
331
402
|
this.db
|
|
332
403
|
.prepare('UPDATE memories SET forgotten = 1, updated_at = ? WHERE id = ?')
|
|
333
404
|
.run(Date.now(), id);
|
|
405
|
+
// The old labels die with the target, the new one is born alive (S9):
|
|
406
|
+
// what a label about a forgotten memory claims is still true of the
|
|
407
|
+
// turns it was written about, and `dead_at` is what keeps that history
|
|
408
|
+
// readable instead of deleting it.
|
|
409
|
+
this.markLabelsDead(id);
|
|
410
|
+
if (actor === 'user')
|
|
411
|
+
this.#writeUserLabel(id, 0, 'forgetMemory:user');
|
|
412
|
+
if (row)
|
|
413
|
+
this.dropDreamFramesForOwner(row.owner);
|
|
414
|
+
}
|
|
415
|
+
/**
|
|
416
|
+
* Retiring an agent (agent-performance-management, phase 4): its whole
|
|
417
|
+
* bank goes out of recall for good, but stays on the record rather than
|
|
418
|
+
* being deleted - unlike `forgetMemory`, there is no path back from this.
|
|
419
|
+
* Returns how many rows it touched, for the report.
|
|
420
|
+
*/
|
|
421
|
+
archiveMemories(owner) {
|
|
422
|
+
const result = this.db
|
|
423
|
+
.prepare('UPDATE memories SET archived_at = ? WHERE owner = ? AND archived_at IS NULL')
|
|
424
|
+
.run(Date.now(), owner);
|
|
425
|
+
// The whole bank leaves recall, so its frames are verbatim text without
|
|
426
|
+
// a corpus left to replay against (R17).
|
|
427
|
+
this.dropDreamFramesForOwner(owner);
|
|
428
|
+
// Every target of this owner is gone from recall at once, so the labels
|
|
429
|
+
// go dead in one statement rather than one per memory (S9).
|
|
430
|
+
this.markOwnerLabelsDead(owner);
|
|
431
|
+
return Number(result.changes ?? 0);
|
|
334
432
|
}
|
|
335
|
-
|
|
433
|
+
/** See `forgetMemory` for `actor`; this path is the hard one (`?hard`). */
|
|
434
|
+
deleteMemory(id, actor = 'model') {
|
|
435
|
+
// The owner is read before the row goes, so the frame drop afterwards
|
|
436
|
+
// still knows whose bank the deleted memory belonged to (R17).
|
|
437
|
+
const row = this.db.prepare('SELECT owner FROM memories WHERE id = ?').get(id);
|
|
438
|
+
// Both label steps run while the row is still there: the user label
|
|
439
|
+
// reads the memory's owner and source session off it, and neither is
|
|
440
|
+
// recoverable once the DELETE has run.
|
|
441
|
+
this.markLabelsDead(id);
|
|
442
|
+
if (actor === 'user')
|
|
443
|
+
this.#writeUserLabel(id, 0, 'deleteMemory:user');
|
|
336
444
|
this.db.prepare('DELETE FROM memories WHERE id = ?').run(id);
|
|
445
|
+
if (row)
|
|
446
|
+
this.dropDreamFramesForOwner(row.owner);
|
|
447
|
+
}
|
|
448
|
+
/**
|
|
449
|
+
* The `user` label funnel (concept 4.2b, S5). Only `actor === 'user'`
|
|
450
|
+
* reaches it: the model's own memory tool calls the very same three
|
|
451
|
+
* methods, and a source that can be manufactured by the thing being
|
|
452
|
+
* measured is not a source.
|
|
453
|
+
*
|
|
454
|
+
* The label is session-scoped, because a memory edit names no turn. The
|
|
455
|
+
* only rule that would name one is "the turns that surfaced this memory",
|
|
456
|
+
* and that is a function of the very policy under evaluation - 4.2b rules
|
|
457
|
+
* it out and assigns the label to a session window instead. `turn_id`
|
|
458
|
+
* therefore carries the SESSION id, the way every session-scoped label
|
|
459
|
+
* does, and the evaluator spreads it over `dream.userLabelWindow` around
|
|
460
|
+
* `created_at`. A memory with no source session has no locator at all, so
|
|
461
|
+
* nothing is written rather than a guessed one.
|
|
462
|
+
*/
|
|
463
|
+
#writeUserLabel(memoryId, relevance, evidence) {
|
|
464
|
+
const row = this.db
|
|
465
|
+
.prepare('SELECT owner, source_session_id FROM memories WHERE id = ?')
|
|
466
|
+
.get(memoryId);
|
|
467
|
+
if (!row)
|
|
468
|
+
return;
|
|
469
|
+
const sessionId = row.source_session_id ?? null;
|
|
470
|
+
if (!sessionId)
|
|
471
|
+
return;
|
|
472
|
+
this.putLabel({
|
|
473
|
+
turnId: sessionId,
|
|
474
|
+
target: memoryId,
|
|
475
|
+
source: 'user',
|
|
476
|
+
relevance,
|
|
477
|
+
scope: 'session',
|
|
478
|
+
evidence,
|
|
479
|
+
createdAt: Date.now(),
|
|
480
|
+
owner: row.owner ?? ASSISTANT_MEMORY_OWNER,
|
|
481
|
+
sessionId,
|
|
482
|
+
});
|
|
337
483
|
}
|
|
338
484
|
/**
|
|
339
485
|
* Record that a memory was actually used. This is the only path that
|
|
340
486
|
* raises `usefulness`, and it is damped so a single busy day cannot make
|
|
341
487
|
* a memory permanent.
|
|
488
|
+
*
|
|
489
|
+
* With `ctx` the same call appends one `memory_touches` row per id as
|
|
490
|
+
* well: the counters it raises are monotone and carry no history, so the
|
|
491
|
+
* append-only record is the only place a later night could ever
|
|
492
|
+
* recompute them from (R4). Without `ctx` nothing extra is written - an
|
|
493
|
+
* unrecorded turn costs exactly what it costs today.
|
|
342
494
|
*/
|
|
343
|
-
touchMemories(ids) {
|
|
495
|
+
touchMemories(ids, ctx) {
|
|
344
496
|
if (!ids.length)
|
|
345
497
|
return;
|
|
346
498
|
const now = Date.now();
|
|
347
|
-
const statement = this.db.prepare(`UPDATE memories
|
|
348
|
-
SET last_accessed_at = ?,
|
|
349
|
-
access_count = access_count + 1,
|
|
350
|
-
usefulness = MIN(1.0, usefulness + 0.03)
|
|
499
|
+
const statement = this.db.prepare(`UPDATE memories
|
|
500
|
+
SET last_accessed_at = ?,
|
|
501
|
+
access_count = access_count + 1,
|
|
502
|
+
usefulness = MIN(1.0, usefulness + 0.03)
|
|
351
503
|
WHERE id = ?`);
|
|
352
504
|
for (const id of ids)
|
|
353
505
|
statement.run(now, id);
|
|
506
|
+
if (ctx)
|
|
507
|
+
this.recordTouches(ctx.traceId, ctx.owner, ids, ctx.policyId);
|
|
354
508
|
}
|
|
355
509
|
memoryStats(owner = ASSISTANT_MEMORY_OWNER) {
|
|
356
510
|
const count = (sql) => this.db.prepare(sql).get(owner)?.n ?? 0;
|
|
@@ -361,7 +515,7 @@ export class Store {
|
|
|
361
515
|
const entities = count('SELECT COUNT(*) AS n FROM memory_entities WHERE owner = ?');
|
|
362
516
|
const edges = count('SELECT COUNT(*) AS n FROM memory_edges WHERE owner = ?');
|
|
363
517
|
const rows = this.db
|
|
364
|
-
.prepare(`SELECT kind, COUNT(*) AS n FROM memories
|
|
518
|
+
.prepare(`SELECT kind, COUNT(*) AS n FROM memories
|
|
365
519
|
WHERE owner = ? AND forgotten = 0 AND dormant_at IS NULL GROUP BY kind`)
|
|
366
520
|
.all(owner);
|
|
367
521
|
const byKind = {};
|
|
@@ -393,9 +547,13 @@ export class Store {
|
|
|
393
547
|
// never disagree about how many memories there are.
|
|
394
548
|
const memory = this.memoryStats(owner);
|
|
395
549
|
const totals = {
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
550
|
+
// Mail and cron transcripts are left out here for the same reason
|
|
551
|
+
// `listSessions` hides them: they are not conversations. Counting them
|
|
552
|
+
// would put a number on the conversations card that its own list
|
|
553
|
+
// cannot produce.
|
|
554
|
+
sessions: count("SELECT COUNT(*) AS n FROM sessions WHERE archived = 0 AND kind NOT IN ('mail', 'schedule')"),
|
|
555
|
+
archivedSessions: count("SELECT COUNT(*) AS n FROM sessions WHERE archived = 1 AND kind NOT IN ('mail', 'schedule')"),
|
|
556
|
+
messages: count("SELECT COUNT(*) AS n FROM messages m WHERE NOT EXISTS (SELECT 1 FROM sessions s WHERE s.id = m.session_id AND s.kind IN ('mail', 'schedule'))"),
|
|
399
557
|
assignments: count('SELECT COUNT(*) AS n FROM assignments WHERE org_id = ?', options.orgId),
|
|
400
558
|
runningAssignments: count("SELECT COUNT(*) AS n FROM assignments WHERE org_id = ? AND status IN ('pending', 'running')", options.orgId),
|
|
401
559
|
tasks: count('SELECT COUNT(*) AS n FROM tasks WHERE org_id = ?', options.orgId),
|
|
@@ -432,8 +590,8 @@ export class Store {
|
|
|
432
590
|
*/
|
|
433
591
|
const perDay = (table, column, filter, values) => {
|
|
434
592
|
const rows = this.db
|
|
435
|
-
.prepare(`SELECT strftime('%Y-%m-%d', ${column} / 1000, 'unixepoch', 'localtime') AS day, COUNT(*) AS n
|
|
436
|
-
FROM ${table}
|
|
593
|
+
.prepare(`SELECT strftime('%Y-%m-%d', ${column} / 1000, 'unixepoch', 'localtime') AS day, COUNT(*) AS n
|
|
594
|
+
FROM ${table}
|
|
437
595
|
WHERE ${column} >= ? AND ${column} <= ?` +
|
|
438
596
|
(filter ? ' AND ' + filter : '') +
|
|
439
597
|
' GROUP BY day')
|
|
@@ -461,11 +619,11 @@ export class Store {
|
|
|
461
619
|
let tokensAvailable = false;
|
|
462
620
|
try {
|
|
463
621
|
const rows = this.db
|
|
464
|
-
.prepare(`SELECT strftime('%Y-%m-%d', created_at / 1000, 'unixepoch', 'localtime') AS day,
|
|
465
|
-
SUM(COALESCE(json_extract(usage, '$.inputTokens'), 0)) AS input_tokens,
|
|
466
|
-
SUM(COALESCE(json_extract(usage, '$.outputTokens'), 0)) AS output_tokens
|
|
467
|
-
FROM messages
|
|
468
|
-
WHERE created_at >= ? AND created_at <= ? AND usage IS NOT NULL AND json_valid(usage)
|
|
622
|
+
.prepare(`SELECT strftime('%Y-%m-%d', created_at / 1000, 'unixepoch', 'localtime') AS day,
|
|
623
|
+
SUM(COALESCE(json_extract(usage, '$.inputTokens'), 0)) AS input_tokens,
|
|
624
|
+
SUM(COALESCE(json_extract(usage, '$.outputTokens'), 0)) AS output_tokens
|
|
625
|
+
FROM messages
|
|
626
|
+
WHERE created_at >= ? AND created_at <= ? AND usage IS NOT NULL AND json_valid(usage)
|
|
469
627
|
GROUP BY day`)
|
|
470
628
|
.all(...[since, until]);
|
|
471
629
|
tokensAvailable = rows.length > 0;
|
|
@@ -515,7 +673,7 @@ export class Store {
|
|
|
515
673
|
lastSeenAt: now,
|
|
516
674
|
};
|
|
517
675
|
this.db
|
|
518
|
-
.prepare(`INSERT INTO memory_entities (id, owner, name, slug, kind, mentions, first_seen_at, last_seen_at)
|
|
676
|
+
.prepare(`INSERT INTO memory_entities (id, owner, name, slug, kind, mentions, first_seen_at, last_seen_at)
|
|
519
677
|
VALUES (?, ?, ?, ?, ?, 0, ?, ?)`)
|
|
520
678
|
.run(entity.id, entity.owner, entity.name, entity.slug, entity.kind, now, now);
|
|
521
679
|
return entity;
|
|
@@ -533,9 +691,9 @@ export class Store {
|
|
|
533
691
|
/** Entities of one owner, most-mentioned first. */
|
|
534
692
|
listEntities(options = {}) {
|
|
535
693
|
const rows = this.db
|
|
536
|
-
.prepare(`SELECT * FROM memory_entities
|
|
537
|
-
WHERE owner = ? AND mentions >= ?
|
|
538
|
-
ORDER BY mentions DESC, last_seen_at DESC
|
|
694
|
+
.prepare(`SELECT * FROM memory_entities
|
|
695
|
+
WHERE owner = ? AND mentions >= ?
|
|
696
|
+
ORDER BY mentions DESC, last_seen_at DESC
|
|
539
697
|
LIMIT ?`)
|
|
540
698
|
.all(options.owner ?? ASSISTANT_MEMORY_OWNER, options.minMentions ?? 1, options.limit ?? 200);
|
|
541
699
|
return rows.map(mapEntity);
|
|
@@ -556,9 +714,9 @@ export class Store {
|
|
|
556
714
|
/** Recount live mentions of one entity, and drop it when nothing is left. */
|
|
557
715
|
recountEntity(entityId) {
|
|
558
716
|
const row = this.db
|
|
559
|
-
.prepare(`SELECT COUNT(*) AS n
|
|
560
|
-
FROM memory_entity_links l
|
|
561
|
-
JOIN memories m ON m.id = l.memory_id
|
|
717
|
+
.prepare(`SELECT COUNT(*) AS n
|
|
718
|
+
FROM memory_entity_links l
|
|
719
|
+
JOIN memories m ON m.id = l.memory_id
|
|
562
720
|
WHERE l.entity_id = ? AND m.forgotten = 0 AND m.dormant_at IS NULL`)
|
|
563
721
|
.get(entityId);
|
|
564
722
|
this.db.prepare('UPDATE memory_entities SET mentions = ? WHERE id = ?').run(row.n, entityId);
|
|
@@ -566,40 +724,146 @@ export class Store {
|
|
|
566
724
|
/** Recount every entity of one owner. Cheap enough to run after a night. */
|
|
567
725
|
recountEntities(owner) {
|
|
568
726
|
this.db
|
|
569
|
-
.prepare(`UPDATE memory_entities
|
|
570
|
-
SET mentions = (
|
|
571
|
-
SELECT COUNT(*) FROM memory_entity_links l
|
|
572
|
-
JOIN memories m ON m.id = l.memory_id
|
|
573
|
-
WHERE l.entity_id = memory_entities.id
|
|
574
|
-
AND m.forgotten = 0 AND m.dormant_at IS NULL
|
|
575
|
-
)
|
|
727
|
+
.prepare(`UPDATE memory_entities
|
|
728
|
+
SET mentions = (
|
|
729
|
+
SELECT COUNT(*) FROM memory_entity_links l
|
|
730
|
+
JOIN memories m ON m.id = l.memory_id
|
|
731
|
+
WHERE l.entity_id = memory_entities.id
|
|
732
|
+
AND m.forgotten = 0 AND m.dormant_at IS NULL
|
|
733
|
+
)
|
|
576
734
|
WHERE owner = ?`)
|
|
577
735
|
.run(owner);
|
|
578
736
|
}
|
|
737
|
+
/**
|
|
738
|
+
* Fold one entity into another: two names that mean the same real thing
|
|
739
|
+
* become one node, links and all.
|
|
740
|
+
*
|
|
741
|
+
* Links the surviving entity already holds must go first - the pair table
|
|
742
|
+
* has no room for a second row for the same memory - and memories that
|
|
743
|
+
* were covered on both sides simply keep the one link. Everything runs in
|
|
744
|
+
* one transaction, so a half-merged entity can never exist; the mention
|
|
745
|
+
* recount afterwards is the only thing that can still lag, and it is
|
|
746
|
+
* rebuilt from scratch anyway. Returns false (and changes nothing) when
|
|
747
|
+
* either side is unknown or both names are the same entity; a merge that
|
|
748
|
+
* would not hold must not cost the caller anything.
|
|
749
|
+
*/
|
|
750
|
+
mergeEntities(owner, fromName, intoName) {
|
|
751
|
+
const from = this.findEntity(owner, fromName);
|
|
752
|
+
const into = from ? this.findEntity(owner, intoName) : null;
|
|
753
|
+
if (!from || !into || from.id === into.id)
|
|
754
|
+
return false;
|
|
755
|
+
this.db.exec('BEGIN');
|
|
756
|
+
try {
|
|
757
|
+
this.db
|
|
758
|
+
.prepare(`DELETE FROM memory_entity_links
|
|
759
|
+
WHERE entity_id = ?
|
|
760
|
+
AND memory_id IN (SELECT memory_id FROM memory_entity_links WHERE entity_id = ?)`)
|
|
761
|
+
.run(from.id, into.id);
|
|
762
|
+
this.db.prepare('UPDATE memory_entity_links SET entity_id = ? WHERE entity_id = ?').run(into.id, from.id);
|
|
763
|
+
this.db.prepare('DELETE FROM memory_entities WHERE id = ?').run(from.id);
|
|
764
|
+
}
|
|
765
|
+
catch (error) {
|
|
766
|
+
this.db.exec('ROLLBACK');
|
|
767
|
+
throw error;
|
|
768
|
+
}
|
|
769
|
+
this.db.exec('COMMIT');
|
|
770
|
+
this.recountEntities(owner);
|
|
771
|
+
return true;
|
|
772
|
+
}
|
|
773
|
+
/**
|
|
774
|
+
* Entities of one memory, most-mentioned first. `e.id` breaks ties in
|
|
775
|
+
* `mentions`: `groupByEntity` in recall.ts keeps the first of the equal
|
|
776
|
+
* minima, so which entity that is must never depend on SQLite's internal
|
|
777
|
+
* row order.
|
|
778
|
+
*/
|
|
579
779
|
entitiesFor(memoryId) {
|
|
580
780
|
const rows = this.db
|
|
581
|
-
.prepare(`SELECT e.* FROM memory_entities e
|
|
582
|
-
JOIN memory_entity_links l ON l.entity_id = e.id
|
|
583
|
-
WHERE l.memory_id = ?
|
|
584
|
-
ORDER BY e.mentions DESC`)
|
|
781
|
+
.prepare(`SELECT e.* FROM memory_entities e
|
|
782
|
+
JOIN memory_entity_links l ON l.entity_id = e.id
|
|
783
|
+
WHERE l.memory_id = ?
|
|
784
|
+
ORDER BY e.mentions DESC, e.id`)
|
|
585
785
|
.all(memoryId);
|
|
586
786
|
return rows.map(mapEntity);
|
|
587
787
|
}
|
|
588
|
-
/**
|
|
788
|
+
/**
|
|
789
|
+
* Entities of many memories, in one query instead of one per memory. The
|
|
790
|
+
* dream recorder needs the entities of every row a frame can reach, and a
|
|
791
|
+
* per-memory call would turn one frame into dozens of statements. Per
|
|
792
|
+
* memory the order matches `entitiesFor` (mentions DESC, id ASC); a memory
|
|
793
|
+
* with no entities maps to an empty list rather than to a missing key.
|
|
794
|
+
*/
|
|
795
|
+
entitiesForMany(memoryIds) {
|
|
796
|
+
const grouped = new Map();
|
|
797
|
+
const ids = [...new Set(memoryIds)];
|
|
798
|
+
for (const id of ids)
|
|
799
|
+
grouped.set(id, []);
|
|
800
|
+
if (!ids.length)
|
|
801
|
+
return grouped;
|
|
802
|
+
const rows = this.db
|
|
803
|
+
.prepare(`SELECT l.memory_id, e.* FROM memory_entities e
|
|
804
|
+
JOIN memory_entity_links l ON l.entity_id = e.id
|
|
805
|
+
WHERE l.memory_id IN (` + ids.map(() => '?').join(', ') + `)
|
|
806
|
+
ORDER BY l.memory_id, e.mentions DESC, e.id`)
|
|
807
|
+
.all(...ids);
|
|
808
|
+
for (const row of rows)
|
|
809
|
+
grouped.get(row.memory_id)?.push(mapEntity(row));
|
|
810
|
+
return grouped;
|
|
811
|
+
}
|
|
812
|
+
/**
|
|
813
|
+
* Live memories linked to any of these entities, excluding the ones given.
|
|
814
|
+
* `owner` keeps the result inside one bank: the link table has no owner
|
|
815
|
+
* column, so without the filter a cross-owner link would read across banks.
|
|
816
|
+
*
|
|
817
|
+
* The filter lets `superseded_by` through while it drops archived rows, and
|
|
818
|
+
* that asymmetry is deliberate: `offer` in recall.ts drops superseded rows
|
|
819
|
+
* only after the LIMIT has bitten, so a caller that replays this query must
|
|
820
|
+
* see them too. This is not the gate's form - `similarMemories` there
|
|
821
|
+
* filters neither column.
|
|
822
|
+
*
|
|
823
|
+
* With `perEntity: true` the limit applies per entity instead of over the
|
|
824
|
+
* union, which is the shape the live second hop uses (one call per entity,
|
|
825
|
+
* limit 8); a single LIMIT over a bundled IN (...) call would keep the
|
|
826
|
+
* union's top N instead. In that mode a memory linked to several of the
|
|
827
|
+
* queried entities comes back once per entity, on a row carrying
|
|
828
|
+
* `hopEntityId` - that duplication is wanted, the recorder buckets the rows
|
|
829
|
+
* by entity, so do not "repair" it away with DISTINCT.
|
|
830
|
+
*/
|
|
589
831
|
memoriesForEntities(entityIds, options = {}) {
|
|
590
832
|
if (!entityIds.length)
|
|
591
833
|
return [];
|
|
592
834
|
const exclude = options.exclude ?? [];
|
|
593
|
-
const
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
835
|
+
const where = ' WHERE l.entity_id IN (' + entityIds.map(() => '?').join(', ') + ')' +
|
|
836
|
+
' AND m.forgotten = 0 AND m.dormant_at IS NULL AND m.archived_at IS NULL' +
|
|
837
|
+
(options.owner ? ' AND m.owner = ?' : '') +
|
|
838
|
+
(exclude.length ? ' AND m.id NOT IN (' + exclude.map(() => '?').join(', ') + ')' : '');
|
|
839
|
+
const values = [
|
|
840
|
+
...entityIds,
|
|
841
|
+
...(options.owner ? [options.owner] : []),
|
|
842
|
+
...exclude,
|
|
843
|
+
options.limit ?? 40,
|
|
844
|
+
];
|
|
845
|
+
// `m.id` breaks ties in importance: which row a LIMIT keeps when two
|
|
846
|
+
// importances are equal must not depend on SQLite's internal order.
|
|
847
|
+
const rows = options.perEntity
|
|
848
|
+
? this.db
|
|
849
|
+
.prepare(`SELECT * FROM (
|
|
850
|
+
SELECT m.*, l.entity_id AS hop_entity_id,
|
|
851
|
+
ROW_NUMBER() OVER (PARTITION BY l.entity_id
|
|
852
|
+
ORDER BY m.importance DESC, m.id) AS rn
|
|
853
|
+
FROM memories m
|
|
854
|
+
JOIN memory_entity_links l ON l.memory_id = m.id` + where + `
|
|
855
|
+
) WHERE rn <= ? ORDER BY hop_entity_id, rn`)
|
|
856
|
+
.all(...values)
|
|
857
|
+
: this.db
|
|
858
|
+
.prepare(`SELECT DISTINCT m.* FROM memories m
|
|
859
|
+
JOIN memory_entity_links l ON l.memory_id = m.id` + where +
|
|
860
|
+
' ORDER BY m.importance DESC, m.id LIMIT ?')
|
|
861
|
+
.all(...values);
|
|
862
|
+
// mapMemory builds a fresh object from named columns, so the partition
|
|
863
|
+
// key is re-attached instead of riding through the row.
|
|
864
|
+
return rows.map((row) => row.hop_entity_id === undefined
|
|
865
|
+
? mapMemory(row)
|
|
866
|
+
: { ...mapMemory(row), hopEntityId: row.hop_entity_id });
|
|
603
867
|
}
|
|
604
868
|
/* ------------------------------ edges ------------------------------ */
|
|
605
869
|
/**
|
|
@@ -609,10 +873,17 @@ export class Store {
|
|
|
609
873
|
addEdge(input) {
|
|
610
874
|
if (input.srcId === input.dstId)
|
|
611
875
|
return null;
|
|
876
|
+
// An edge whose endpoints do not both sit in the writer's bank would wire
|
|
877
|
+
// two banks together — refuse it rather than persist the bridge.
|
|
878
|
+
const endpoints = this.db
|
|
879
|
+
.prepare('SELECT owner FROM memories WHERE id IN (?, ?)')
|
|
880
|
+
.all(input.srcId, input.dstId);
|
|
881
|
+
if (endpoints.length !== 2 || endpoints.some((row) => row.owner !== input.owner))
|
|
882
|
+
return null;
|
|
612
883
|
const now = Date.now();
|
|
613
884
|
const existing = this.db
|
|
614
|
-
.prepare('SELECT * FROM memory_edges WHERE src_id = ? AND dst_id = ? AND relation = ?')
|
|
615
|
-
.get(input.srcId, input.dstId, input.relation);
|
|
885
|
+
.prepare('SELECT * FROM memory_edges WHERE src_id = ? AND dst_id = ? AND relation = ? AND owner = ?')
|
|
886
|
+
.get(input.srcId, input.dstId, input.relation, input.owner);
|
|
616
887
|
if (existing) {
|
|
617
888
|
const weight = Math.min(1, Math.max(Number(existing.weight), input.weight ?? 0.5));
|
|
618
889
|
this.db.prepare('UPDATE memory_edges SET weight = ? WHERE id = ?').run(weight, existing.id);
|
|
@@ -630,7 +901,7 @@ export class Store {
|
|
|
630
901
|
createdAt: now,
|
|
631
902
|
};
|
|
632
903
|
this.db
|
|
633
|
-
.prepare(`INSERT INTO memory_edges (id, owner, src_id, dst_id, relation, weight, origin, run_id, created_at)
|
|
904
|
+
.prepare(`INSERT INTO memory_edges (id, owner, src_id, dst_id, relation, weight, origin, run_id, created_at)
|
|
634
905
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`)
|
|
635
906
|
.run(edge.id, edge.owner, edge.srcId, edge.dstId, edge.relation, edge.weight, edge.origin, edge.runId ?? null, now);
|
|
636
907
|
return edge;
|
|
@@ -659,13 +930,13 @@ export class Store {
|
|
|
659
930
|
if (!memory)
|
|
660
931
|
return null;
|
|
661
932
|
const outgoing = this.db
|
|
662
|
-
.prepare(`SELECT e.*, m.id AS o_id FROM memory_edges e JOIN memories m ON m.id = e.dst_id WHERE e.src_id = ?`)
|
|
663
|
-
.all(id)
|
|
933
|
+
.prepare(`SELECT e.*, m.id AS o_id FROM memory_edges e JOIN memories m ON m.id = e.dst_id WHERE e.src_id = ? AND e.owner = ?`)
|
|
934
|
+
.all(id, memory.owner)
|
|
664
935
|
.map((row) => ({ ...mapEdge(row), other: this.getMemory(row.o_id) }))
|
|
665
936
|
.filter((edge) => Boolean(edge.other));
|
|
666
937
|
const incoming = this.db
|
|
667
|
-
.prepare(`SELECT e.*, m.id AS o_id FROM memory_edges e JOIN memories m ON m.id = e.src_id WHERE e.dst_id = ?`)
|
|
668
|
-
.all(id)
|
|
938
|
+
.prepare(`SELECT e.*, m.id AS o_id FROM memory_edges e JOIN memories m ON m.id = e.src_id WHERE e.dst_id = ? AND e.owner = ?`)
|
|
939
|
+
.all(id, memory.owner)
|
|
669
940
|
.map((row) => ({ ...mapEdge(row), other: this.getMemory(row.o_id) }))
|
|
670
941
|
.filter((edge) => Boolean(edge.other));
|
|
671
942
|
return { memory, entities: this.entitiesFor(id), outgoing, incoming };
|
|
@@ -689,8 +960,8 @@ export class Store {
|
|
|
689
960
|
values.push(options.since);
|
|
690
961
|
values.push(...kinds, limit + 1);
|
|
691
962
|
const sql = options.entityId
|
|
692
|
-
? `SELECT m.* FROM memories m
|
|
693
|
-
JOIN memory_entity_links l ON l.memory_id = m.id
|
|
963
|
+
? `SELECT m.* FROM memories m
|
|
964
|
+
JOIN memory_entity_links l ON l.memory_id = m.id
|
|
694
965
|
WHERE m.owner = ? AND l.entity_id = ?` + filters +
|
|
695
966
|
' ORDER BY m.importance DESC, m.updated_at DESC LIMIT ?'
|
|
696
967
|
: `SELECT m.* FROM memories m WHERE m.owner = ?` + filters +
|
|
@@ -721,21 +992,237 @@ export class Store {
|
|
|
721
992
|
.all(...[...ids, ...ids]).map(mapEdge);
|
|
722
993
|
return { entities, memories, edges, links, truncated };
|
|
723
994
|
}
|
|
995
|
+
/* --------------------------- the day's talk --------------------------- */
|
|
996
|
+
/**
|
|
997
|
+
* Conversations that moved since `since`, newest first.
|
|
998
|
+
*
|
|
999
|
+
* Mail and cron-run sessions are left out on purpose: those are the
|
|
1000
|
+
* assistant answering a mail or carrying out a schedule with nobody on the
|
|
1001
|
+
* other end, so there is no user in them to quote, and the evidence rule
|
|
1002
|
+
* would throw away everything they yielded anyway. Archived ones are out
|
|
1003
|
+
* for the same reason they are out of the list - the user put them away.
|
|
1004
|
+
*/
|
|
1005
|
+
sessionsActiveSince(since, limit = 50) {
|
|
1006
|
+
const rows = this.db
|
|
1007
|
+
.prepare(`SELECT s.*, (SELECT COUNT(*) FROM messages m WHERE m.session_id = s.id) AS message_count
|
|
1008
|
+
FROM sessions s
|
|
1009
|
+
WHERE s.archived = 0
|
|
1010
|
+
AND s.kind NOT IN ('mail', 'schedule')
|
|
1011
|
+
AND s.updated_at > ?
|
|
1012
|
+
ORDER BY s.updated_at DESC
|
|
1013
|
+
LIMIT ?`)
|
|
1014
|
+
.all(since, limit);
|
|
1015
|
+
return rows.map(mapSession);
|
|
1016
|
+
}
|
|
1017
|
+
/* ---------------------------- corrections ---------------------------- */
|
|
1018
|
+
/**
|
|
1019
|
+
* Record that the user put something right.
|
|
1020
|
+
*
|
|
1021
|
+
* Kept apart from memories because it is not a fact about the user, it is
|
|
1022
|
+
* evidence about the system: something written down is wrong. The revision
|
|
1023
|
+
* pass consumes these; nothing else reads them.
|
|
1024
|
+
*
|
|
1025
|
+
* `turnId` is what the correction label hangs on (concept 4.2a, S3): the
|
|
1026
|
+
* turn the quote was located in, or absent when the quote could not be
|
|
1027
|
+
* pinned to exactly one turn. Absent is a real answer here - a guessed
|
|
1028
|
+
* turn is worse than no turn, because the label would then claim
|
|
1029
|
+
* something about a turn that never carried the quote.
|
|
1030
|
+
*/
|
|
1031
|
+
addCorrection(input) {
|
|
1032
|
+
this.db
|
|
1033
|
+
.prepare(`INSERT INTO corrections (id, owner, text, quote, session_id, created_at, turn_id)
|
|
1034
|
+
VALUES (?, ?, ?, ?, ?, ?, ?)`)
|
|
1035
|
+
.run(randomUUID(), input.owner, input.text.trim(), input.quote.trim(), input.sessionId ?? null, Date.now(), input.turnId ?? null);
|
|
1036
|
+
}
|
|
1037
|
+
/** Corrections no revision pass has looked at yet, oldest first. */
|
|
1038
|
+
openCorrections(owner, limit = 20) {
|
|
1039
|
+
const rows = this.db
|
|
1040
|
+
.prepare(`SELECT id, text, quote FROM corrections
|
|
1041
|
+
WHERE owner = ? AND consumed_at IS NULL
|
|
1042
|
+
ORDER BY created_at ASC LIMIT ?`)
|
|
1043
|
+
.all(owner, limit);
|
|
1044
|
+
return rows.map((row) => ({
|
|
1045
|
+
id: row.id,
|
|
1046
|
+
text: row.text,
|
|
1047
|
+
quote: row.quote,
|
|
1048
|
+
}));
|
|
1049
|
+
}
|
|
1050
|
+
/**
|
|
1051
|
+
* Mark corrections as looked at. Not removed: a correction is a fact about
|
|
1052
|
+
* what happened, and the record of it outlives the repair it caused.
|
|
1053
|
+
*/
|
|
1054
|
+
consumeCorrections(ids) {
|
|
1055
|
+
if (!ids.length)
|
|
1056
|
+
return;
|
|
1057
|
+
const mark = this.db.prepare('UPDATE corrections SET consumed_at = ? WHERE id = ?');
|
|
1058
|
+
const now = Date.now();
|
|
1059
|
+
for (const id of ids)
|
|
1060
|
+
mark.run(now, id);
|
|
1061
|
+
}
|
|
1062
|
+
/**
|
|
1063
|
+
* Corrections of one owner written since `since`, consumed or not.
|
|
1064
|
+
*
|
|
1065
|
+
* `openCorrections` is the revision pass's reader and deliberately hides
|
|
1066
|
+
* everything a pass has already looked at. The label writer needs the
|
|
1067
|
+
* other view: a correction stays evidence about its turn long after the
|
|
1068
|
+
* repair it caused, and the night that writes labels is not the night
|
|
1069
|
+
* that consumed it.
|
|
1070
|
+
*/
|
|
1071
|
+
correctionsSince(owner, since, limit = 200) {
|
|
1072
|
+
const rows = this.db
|
|
1073
|
+
.prepare(`SELECT id, text, quote, session_id, turn_id, created_at FROM corrections
|
|
1074
|
+
WHERE owner = ? AND created_at >= ?
|
|
1075
|
+
ORDER BY created_at ASC LIMIT ?`)
|
|
1076
|
+
.all(owner, since, limit);
|
|
1077
|
+
return rows.map((row) => ({
|
|
1078
|
+
id: row.id,
|
|
1079
|
+
text: row.text,
|
|
1080
|
+
quote: row.quote,
|
|
1081
|
+
sessionId: row.session_id ?? undefined,
|
|
1082
|
+
turnId: row.turn_id ?? undefined,
|
|
1083
|
+
createdAt: Number(row.created_at),
|
|
1084
|
+
}));
|
|
1085
|
+
}
|
|
1086
|
+
/* ------------------------ skill bookkeeping ------------------------ */
|
|
1087
|
+
/**
|
|
1088
|
+
* Note that a skill was opened.
|
|
1089
|
+
*
|
|
1090
|
+
* On its own this is a usage counter. Joined against the assignment it was
|
|
1091
|
+
* opened in, it becomes the only thing that can say a written procedure is
|
|
1092
|
+
* actually wrong: the run that followed it failed, and the error text is
|
|
1093
|
+
* right there to hand to the rewrite.
|
|
1094
|
+
*/
|
|
1095
|
+
recordSkillUse(input) {
|
|
1096
|
+
this.db
|
|
1097
|
+
.prepare(`INSERT INTO skill_uses (id, skill, owner, assignment_id, session_id, created_at)
|
|
1098
|
+
VALUES (?, ?, ?, ?, ?, ?)`)
|
|
1099
|
+
.run(randomUUID(), input.skill, input.owner, input.assignmentId ?? null, input.sessionId ?? null, Date.now());
|
|
1100
|
+
}
|
|
1101
|
+
/** The memories a distilled skill stands on. Replaces whatever was there. */
|
|
1102
|
+
setSkillSources(skill, owner, memoryIds) {
|
|
1103
|
+
const now = Date.now();
|
|
1104
|
+
this.db.prepare('DELETE FROM skill_sources WHERE skill = ?').run(skill);
|
|
1105
|
+
const insert = this.db.prepare(`INSERT OR IGNORE INTO skill_sources (skill, memory_id, owner, created_at)
|
|
1106
|
+
VALUES (?, ?, ?, ?)`);
|
|
1107
|
+
for (const id of memoryIds)
|
|
1108
|
+
insert.run(skill, id, owner, now);
|
|
1109
|
+
}
|
|
1110
|
+
/** The memory ids a skill currently stands on. */
|
|
1111
|
+
skillSourceIds(skill) {
|
|
1112
|
+
const rows = this.db
|
|
1113
|
+
.prepare('SELECT memory_id FROM skill_sources WHERE skill = ?')
|
|
1114
|
+
.all(skill);
|
|
1115
|
+
return rows.map((row) => row.memory_id);
|
|
1116
|
+
}
|
|
1117
|
+
/**
|
|
1118
|
+
* The ground under a skill, where it has moved since `since`.
|
|
1119
|
+
*
|
|
1120
|
+
* Three ways a source memory stops supporting what stands on it: the night
|
|
1121
|
+
* put it to sleep, the night decided a contradiction against it and filed
|
|
1122
|
+
* it away behind a winner, or somebody edited it. All three mean the same
|
|
1123
|
+
* thing to the skill above - what it was written from no longer reads the
|
|
1124
|
+
* way it did.
|
|
1125
|
+
*/
|
|
1126
|
+
changedSkillSources(skill, since) {
|
|
1127
|
+
const rows = this.db
|
|
1128
|
+
.prepare(`SELECT m.* FROM skill_sources s
|
|
1129
|
+
JOIN memories m ON m.id = s.memory_id
|
|
1130
|
+
WHERE s.skill = ?
|
|
1131
|
+
AND (m.dormant_at IS NOT NULL OR m.superseded_by IS NOT NULL OR m.updated_at > ?)
|
|
1132
|
+
ORDER BY m.updated_at DESC
|
|
1133
|
+
LIMIT 12`)
|
|
1134
|
+
.all(skill, since);
|
|
1135
|
+
return rows.map((row) => {
|
|
1136
|
+
const memory = mapMemory(row);
|
|
1137
|
+
return {
|
|
1138
|
+
memory,
|
|
1139
|
+
replacement: memory.supersededBy ? this.getMemory(memory.supersededBy) : null,
|
|
1140
|
+
};
|
|
1141
|
+
});
|
|
1142
|
+
}
|
|
1143
|
+
/**
|
|
1144
|
+
* Runs that failed with this skill open, newest first.
|
|
1145
|
+
*
|
|
1146
|
+
* The error text matters more than the count. "That the run failed" says
|
|
1147
|
+
* only that something is wrong somewhere; "npm run build:core: no such
|
|
1148
|
+
* script" says which line of the skill is lying.
|
|
1149
|
+
*/
|
|
1150
|
+
failedRunsForSkill(skill, since, limit = 5) {
|
|
1151
|
+
const rows = this.db
|
|
1152
|
+
.prepare(`SELECT DISTINCT a.id, a.task, a.error, a.finished_at FROM skill_uses u
|
|
1153
|
+
JOIN assignments a ON a.id = u.assignment_id
|
|
1154
|
+
WHERE u.skill = ?
|
|
1155
|
+
AND a.status = 'failed'
|
|
1156
|
+
AND a.error IS NOT NULL
|
|
1157
|
+
AND a.finished_at > ?
|
|
1158
|
+
ORDER BY a.finished_at DESC
|
|
1159
|
+
LIMIT ?`)
|
|
1160
|
+
.all(skill, since, limit);
|
|
1161
|
+
return rows.map((row) => ({ task: row.task, error: row.error }));
|
|
1162
|
+
}
|
|
1163
|
+
/**
|
|
1164
|
+
* Keep the file as it reads right now, before something unattended
|
|
1165
|
+
* overwrites it. `content` is null when the skill does not exist yet, which
|
|
1166
|
+
* is how undo knows to delete the folder rather than restore text.
|
|
1167
|
+
*/
|
|
1168
|
+
snapshotSkill(input) {
|
|
1169
|
+
this.db
|
|
1170
|
+
.prepare('INSERT INTO skill_versions (id, skill, content, sleep_run_id, created_at) VALUES (?, ?, ?, ?, ?)')
|
|
1171
|
+
.run(randomUUID(), input.skill, input.content, input.sleepRunId ?? null, Date.now());
|
|
1172
|
+
}
|
|
1173
|
+
/**
|
|
1174
|
+
* When the night last looked at this skill, revision or not.
|
|
1175
|
+
*
|
|
1176
|
+
* Without it a trigger never clears. A source memory that went dormant
|
|
1177
|
+
* stays dormant, so a skill standing on it would be dragged in front of the
|
|
1178
|
+
* model every single night, and a night that decided "this still reads
|
|
1179
|
+
* fine" would decide it again tomorrow at the same cost. Looking counts,
|
|
1180
|
+
* which is why a review that changed nothing still leaves a snapshot.
|
|
1181
|
+
*/
|
|
1182
|
+
lastSkillReviewAt(skill) {
|
|
1183
|
+
const row = this.db
|
|
1184
|
+
.prepare('SELECT MAX(created_at) AS at FROM skill_versions WHERE skill = ?')
|
|
1185
|
+
.get(skill);
|
|
1186
|
+
return Number(row?.at ?? 0);
|
|
1187
|
+
}
|
|
1188
|
+
/**
|
|
1189
|
+
* What the skills of one night looked like before it touched them, oldest
|
|
1190
|
+
* snapshot first - so a caller that keeps the first entry per name gets the
|
|
1191
|
+
* state as it stood before the night began, even if a run wrote twice.
|
|
1192
|
+
*/
|
|
1193
|
+
skillVersionsForRun(runId) {
|
|
1194
|
+
const rows = this.db
|
|
1195
|
+
.prepare('SELECT skill, content FROM skill_versions WHERE sleep_run_id = ? ORDER BY created_at ASC')
|
|
1196
|
+
.all(runId);
|
|
1197
|
+
return rows.map((row) => ({
|
|
1198
|
+
skill: row.skill,
|
|
1199
|
+
content: row.content ?? null,
|
|
1200
|
+
}));
|
|
1201
|
+
}
|
|
724
1202
|
/* --------------------------- sleep runs --------------------------- */
|
|
725
1203
|
createSleepRun(input) {
|
|
726
1204
|
const run = {
|
|
727
1205
|
id: randomUUID(),
|
|
1206
|
+
startedAt: sleepRunStart(this.db),
|
|
728
1207
|
owner: input.owner,
|
|
729
1208
|
trigger: input.trigger,
|
|
730
1209
|
status: 'running',
|
|
731
|
-
startedAt: Date.now(),
|
|
732
1210
|
readCount: 0,
|
|
1211
|
+
replayedCount: 0,
|
|
1212
|
+
learnedCount: 0,
|
|
733
1213
|
mergedCount: 0,
|
|
734
1214
|
dormantCount: 0,
|
|
735
1215
|
edgeCount: 0,
|
|
736
1216
|
insightCount: 0,
|
|
1217
|
+
skillCount: 0,
|
|
1218
|
+
skillRevisedCount: 0,
|
|
737
1219
|
conflictCount: 0,
|
|
738
1220
|
resolvedCount: 0,
|
|
1221
|
+
dreamTracesSeen: 0,
|
|
1222
|
+
dreamFramesScored: 0,
|
|
1223
|
+
dreamCandidates: 0,
|
|
1224
|
+
dreamPromoted: 0,
|
|
1225
|
+
dreamLabelsWritten: 0,
|
|
739
1226
|
modelCalls: 0,
|
|
740
1227
|
};
|
|
741
1228
|
this.db
|
|
@@ -749,12 +1236,21 @@ export class Store {
|
|
|
749
1236
|
finishedAt: 'finished_at',
|
|
750
1237
|
durationMs: 'duration_ms',
|
|
751
1238
|
readCount: 'read_count',
|
|
1239
|
+
replayedCount: 'replayed_count',
|
|
1240
|
+
learnedCount: 'learned_count',
|
|
752
1241
|
mergedCount: 'merged_count',
|
|
753
1242
|
dormantCount: 'dormant_count',
|
|
754
1243
|
edgeCount: 'edge_count',
|
|
755
1244
|
insightCount: 'insight_count',
|
|
1245
|
+
skillCount: 'skill_count',
|
|
1246
|
+
skillRevisedCount: 'skill_revised_count',
|
|
756
1247
|
conflictCount: 'conflict_count',
|
|
757
1248
|
resolvedCount: 'resolved_count',
|
|
1249
|
+
dreamTracesSeen: 'dream_traces_seen',
|
|
1250
|
+
dreamFramesScored: 'dream_frames_scored',
|
|
1251
|
+
dreamCandidates: 'dream_candidates',
|
|
1252
|
+
dreamPromoted: 'dream_promoted',
|
|
1253
|
+
dreamLabelsWritten: 'dream_labels_written',
|
|
758
1254
|
modelCalls: 'model_calls',
|
|
759
1255
|
report: 'report',
|
|
760
1256
|
error: 'error',
|
|
@@ -789,6 +1285,22 @@ export class Store {
|
|
|
789
1285
|
.all(options.limit ?? 30);
|
|
790
1286
|
return rows.map(mapSleepRun);
|
|
791
1287
|
}
|
|
1288
|
+
/**
|
|
1289
|
+
* Sleep runs still marked running from a previous process are failed on
|
|
1290
|
+
* startup, mirroring `CronStore.failStaleRuns` (cron/store.ts) and
|
|
1291
|
+
* `OrgStore.failStaleAssignments`/`failStaleTasks` (org/store.ts). Returns
|
|
1292
|
+
* the rows it changed so the caller can announce them.
|
|
1293
|
+
*/
|
|
1294
|
+
failStaleSleepRuns(reason) {
|
|
1295
|
+
const now = Date.now();
|
|
1296
|
+
const rows = this.db.prepare("SELECT * FROM sleep_runs WHERE status = 'running'").all();
|
|
1297
|
+
if (!rows.length)
|
|
1298
|
+
return [];
|
|
1299
|
+
this.db
|
|
1300
|
+
.prepare("UPDATE sleep_runs SET status = 'failed', error = ?, finished_at = ? WHERE status = 'running'")
|
|
1301
|
+
.run(reason, now);
|
|
1302
|
+
return rows.map((row) => mapSleepRun({ ...row, status: 'failed', error: reason, finished_at: now }));
|
|
1303
|
+
}
|
|
792
1304
|
/** When this owner last finished a night. Drives "what is new since then". */
|
|
793
1305
|
lastSleepAt(owner) {
|
|
794
1306
|
const row = this.db
|
|
@@ -798,14 +1310,21 @@ export class Store {
|
|
|
798
1310
|
}
|
|
799
1311
|
/**
|
|
800
1312
|
* Take back one night, in a single transaction: the memories the run wrote
|
|
801
|
-
* are deleted, everything it put to sleep wakes up, and its edges go.
|
|
802
|
-
*
|
|
1313
|
+
* are deleted, everything it put to sleep wakes up, and its edges go. The
|
|
1314
|
+
* frames go with them - they quote the deleted rows verbatim, and the drop
|
|
1315
|
+
* is the same owner-level mechanics the other memory delete paths use
|
|
1316
|
+
* (R17). This is what makes an unattended nightly process acceptable at
|
|
1317
|
+
* all.
|
|
1318
|
+
*
|
|
1319
|
+
* The night's promotions come back with them (concept 10.4, S25): a
|
|
1320
|
+
* policy version is as much a product of the night as an insight is, and
|
|
1321
|
+
* a night that cannot be taken back in full is not undoable.
|
|
803
1322
|
*/
|
|
804
1323
|
undoSleepRun(id) {
|
|
805
1324
|
const run = this.getSleepRun(id);
|
|
806
1325
|
if (!run || run.undoneAt)
|
|
807
1326
|
return null;
|
|
808
|
-
const counts = { woken: 0, removed: 0, edges: 0 };
|
|
1327
|
+
const counts = { woken: 0, removed: 0, edges: 0, policies: 0 };
|
|
809
1328
|
// Counted up front: deleting a memory cascades its edges away, so a
|
|
810
1329
|
// count taken afterwards would report a fraction of what actually went.
|
|
811
1330
|
const edgesBefore = this.db
|
|
@@ -816,8 +1335,20 @@ export class Store {
|
|
|
816
1335
|
// The two sets are kept disjoint: a memory this run wrote and a memory
|
|
817
1336
|
// it put to sleep are handled by different branches, never both.
|
|
818
1337
|
const written = this.db
|
|
819
|
-
|
|
820
|
-
|
|
1338
|
+
// `extract` belongs here as well as `sleep`: the replay phase harvests
|
|
1339
|
+
// memories out of the day's conversations, and those are as much a
|
|
1340
|
+
// product of the night as an insight is. Still disjoint from the
|
|
1341
|
+
// branch below, which takes the memories the run put to SLEEP - a row
|
|
1342
|
+
// the run wrote is never also a row the run retired. Nor can a run
|
|
1343
|
+
// have written a memory older than itself: a row that carries this
|
|
1344
|
+
// run's id but predates it is one the run revived (see `upsertMemory`)
|
|
1345
|
+
// or one somebody woke again, never one it created, so undo must not
|
|
1346
|
+
// delete it. `sleepRunStart` is what keeps that comparison honest at
|
|
1347
|
+
// millisecond resolution.
|
|
1348
|
+
.prepare(`SELECT id FROM memories
|
|
1349
|
+
WHERE sleep_run_id = ? AND origin IN ('sleep', 'extract') AND dormant_at IS NULL
|
|
1350
|
+
AND created_at >= ?`)
|
|
1351
|
+
.all(id, run.startedAt);
|
|
821
1352
|
// Anything that pointed at a memory this run created must let go first.
|
|
822
1353
|
for (const row of written) {
|
|
823
1354
|
this.db
|
|
@@ -833,12 +1364,44 @@ export class Store {
|
|
|
833
1364
|
.run(row.id);
|
|
834
1365
|
counts.woken += 1;
|
|
835
1366
|
}
|
|
1367
|
+
// Frames quote the rows this run wrote verbatim, and undo deletes those
|
|
1368
|
+
// rows outright, so they must fall inside the same transaction, before
|
|
1369
|
+
// the rows they freeze go - the owner-level drop the four wired delete
|
|
1370
|
+
// paths use, never a piecemeal payload edit (R17).
|
|
1371
|
+
this.dropDreamFramesForOwner(run.owner);
|
|
836
1372
|
for (const row of written) {
|
|
837
1373
|
this.db.prepare('DELETE FROM memories WHERE id = ?').run(row.id);
|
|
838
1374
|
counts.removed += 1;
|
|
839
1375
|
}
|
|
840
1376
|
this.db.prepare('DELETE FROM memory_edges WHERE run_id = ?').run(id);
|
|
841
1377
|
counts.edges = edgesBefore;
|
|
1378
|
+
// The promotions of this night, in the same transaction and with the
|
|
1379
|
+
// same "written by" against "touched by" distinction the memory
|
|
1380
|
+
// branch above makes: a version carrying this run's id that predates
|
|
1381
|
+
// the run was promoted by an earlier night and merely re-read here.
|
|
1382
|
+
const promoted = this.db
|
|
1383
|
+
.prepare(`SELECT id, prev_active_id FROM policy_versions
|
|
1384
|
+
WHERE sleep_run_id = ? AND created_at >= ?`)
|
|
1385
|
+
.all(id, run.startedAt);
|
|
1386
|
+
const retire = this.db.prepare('UPDATE policy_versions SET retired_at = ? WHERE id = ?');
|
|
1387
|
+
const reactivate = this.db.prepare('UPDATE policy_versions SET retired_at = NULL WHERE id = ?');
|
|
1388
|
+
const retiredAt = Date.now();
|
|
1389
|
+
for (const row of promoted) {
|
|
1390
|
+
retire.run(retiredAt, row.id);
|
|
1391
|
+
// NULL means "nothing was active when this was promoted", the same
|
|
1392
|
+
// way `snapshotSkill` records a skill that did not exist yet - there
|
|
1393
|
+
// is then nothing to bring back, and the slot falls to the defaults.
|
|
1394
|
+
const previous = row.prev_active_id ?? null;
|
|
1395
|
+
if (previous)
|
|
1396
|
+
reactivate.run(previous);
|
|
1397
|
+
counts.policies += 1;
|
|
1398
|
+
}
|
|
1399
|
+
// The evaluations of an undone night certify nothing: their traces are
|
|
1400
|
+
// partly gone with the memories above, and `trace_set_hash` disjointness
|
|
1401
|
+
// must not be blocked by a measurement that no longer stands.
|
|
1402
|
+
this.db
|
|
1403
|
+
.prepare('DELETE FROM dream_evals WHERE sleep_run_id = ? AND created_at >= ?')
|
|
1404
|
+
.run(id, run.startedAt);
|
|
842
1405
|
this.db
|
|
843
1406
|
.prepare('UPDATE sleep_runs SET undone_at = ? WHERE id = ?')
|
|
844
1407
|
.run(Date.now(), id);
|
|
@@ -851,6 +1414,801 @@ export class Store {
|
|
|
851
1414
|
this.recountEntities(run.owner);
|
|
852
1415
|
return counts;
|
|
853
1416
|
}
|
|
1417
|
+
/* ------------------------------ dream ------------------------------ */
|
|
1418
|
+
/**
|
|
1419
|
+
* Every write of one framed turn runs inside this bracket: trace, frame
|
|
1420
|
+
* and touches are one transaction, or none of them are.
|
|
1421
|
+
*
|
|
1422
|
+
* A SAVEPOINT rather than a hand-rolled BEGIN (R9): the store runs its
|
|
1423
|
+
* own transactions over raw `exec`, and a bare nested BEGIN throws
|
|
1424
|
+
* exactly when the recorder happens to run inside one of them. A
|
|
1425
|
+
* savepoint nests by construction, so no "am I inside" flag is needed -
|
|
1426
|
+
* that flag is the thing that silently rots the next time someone adds
|
|
1427
|
+
* a transactional procedure. A throw inside the bracket rolls the whole
|
|
1428
|
+
* turn back and propagates, so the caller still sees the recorder error.
|
|
1429
|
+
*/
|
|
1430
|
+
recordDreamTurn(write) {
|
|
1431
|
+
this.db.exec('SAVEPOINT dream_rec');
|
|
1432
|
+
try {
|
|
1433
|
+
write();
|
|
1434
|
+
this.db.exec('RELEASE dream_rec');
|
|
1435
|
+
}
|
|
1436
|
+
catch (error) {
|
|
1437
|
+
this.db.exec('ROLLBACK TO dream_rec');
|
|
1438
|
+
this.db.exec('RELEASE dream_rec');
|
|
1439
|
+
throw error;
|
|
1440
|
+
}
|
|
1441
|
+
}
|
|
1442
|
+
/** Open one trace per recall call; the turn groups them under `turnId` (R19). */
|
|
1443
|
+
beginTrace(input) {
|
|
1444
|
+
const now = Date.now();
|
|
1445
|
+
const trace = {
|
|
1446
|
+
id: randomUUID(),
|
|
1447
|
+
turnId: input.turnId,
|
|
1448
|
+
owner: input.owner,
|
|
1449
|
+
kind: input.kind,
|
|
1450
|
+
site: input.site,
|
|
1451
|
+
pipeline: input.pipeline,
|
|
1452
|
+
sessionId: input.sessionId,
|
|
1453
|
+
sessionKind: input.sessionKind,
|
|
1454
|
+
assignmentId: input.assignmentId,
|
|
1455
|
+
sleepRunId: input.sleepRunId,
|
|
1456
|
+
turnIndex: input.turnIndex ?? 0,
|
|
1457
|
+
policySet: input.policySet,
|
|
1458
|
+
framed: input.framed ?? false,
|
|
1459
|
+
holdout: input.holdout ?? false,
|
|
1460
|
+
audit: input.audit ?? false,
|
|
1461
|
+
degraded: null,
|
|
1462
|
+
startedAt: now,
|
|
1463
|
+
createdAt: now,
|
|
1464
|
+
};
|
|
1465
|
+
this.db
|
|
1466
|
+
.prepare(`INSERT INTO dream_traces
|
|
1467
|
+
(id, turn_id, owner, kind, site, pipeline, session_id, session_kind, assignment_id,
|
|
1468
|
+
sleep_run_id, turn_index, policy_set, framed, holdout, audit, started_at, created_at)
|
|
1469
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)
|
|
1470
|
+
.run(trace.id, trace.turnId, trace.owner, trace.kind, trace.site, trace.pipeline, trace.sessionId ?? null, trace.sessionKind ?? null, trace.assignmentId ?? null, trace.sleepRunId ?? null, trace.turnIndex, JSON.stringify(trace.policySet), trace.framed ? 1 : 0, trace.holdout ? 1 : 0, trace.audit ? 1 : 0, trace.startedAt, trace.createdAt);
|
|
1471
|
+
return trace;
|
|
1472
|
+
}
|
|
1473
|
+
/**
|
|
1474
|
+
* Close a trace. `degraded` is the one closable fact, and an explicit
|
|
1475
|
+
* `null` is a real value ("the call did not degrade"), never a default:
|
|
1476
|
+
* "rows came but all fell below the threshold" is a legitimate miss that
|
|
1477
|
+
* must stay scoreable.
|
|
1478
|
+
*/
|
|
1479
|
+
finishTrace(id, patch) {
|
|
1480
|
+
this.db
|
|
1481
|
+
.prepare('UPDATE dream_traces SET degraded = ?, finished_at = ? WHERE id = ?')
|
|
1482
|
+
.run(patch.degraded ?? null, Date.now(), id);
|
|
1483
|
+
}
|
|
1484
|
+
/**
|
|
1485
|
+
* Traces still open from a previous process are closed on startup, after
|
|
1486
|
+
* the pattern of `failStaleSleepRuns` - deliberately without an owner or
|
|
1487
|
+
* PID filter, and with the same reservation. The reason reaches the
|
|
1488
|
+
* caller's log line rather than the row: `dream_traces` carries no error
|
|
1489
|
+
* column on purpose, because the "unfinished" abstention is derived from
|
|
1490
|
+
* `finished_at` itself at scoring time. Returns how many traces closed.
|
|
1491
|
+
*/
|
|
1492
|
+
failStaleTraces(reason) {
|
|
1493
|
+
// Kept for signature parity with the sibling stale-failers; see above.
|
|
1494
|
+
void reason;
|
|
1495
|
+
const result = this.db
|
|
1496
|
+
.prepare('UPDATE dream_traces SET finished_at = ? WHERE finished_at IS NULL')
|
|
1497
|
+
.run(Date.now());
|
|
1498
|
+
return Number(result.changes ?? 0);
|
|
1499
|
+
}
|
|
1500
|
+
/** Traces without `finished_at`: what a restart owes its closing pass to. */
|
|
1501
|
+
openTraces() {
|
|
1502
|
+
const rows = this.db
|
|
1503
|
+
.prepare('SELECT * FROM dream_traces WHERE finished_at IS NULL ORDER BY started_at ASC, id')
|
|
1504
|
+
.all();
|
|
1505
|
+
return rows.map(mapDreamTrace);
|
|
1506
|
+
}
|
|
1507
|
+
/**
|
|
1508
|
+
* Persist one frame for one slot of a trace. Serialise first, measure
|
|
1509
|
+
* second: the cap guards stored bytes, so it is the serialised payload
|
|
1510
|
+
* that is measured, and a frame over the cap is refused with `false`
|
|
1511
|
+
* rather than thrown at the turn - the trace is closed without a frame
|
|
1512
|
+
* and the night simply never scores that turn.
|
|
1513
|
+
*
|
|
1514
|
+
* The Store holds no config, so the caller reads `dream.maxFrameBytes`
|
|
1515
|
+
* (key table, E21: clamped where it is read) and passes it; the default
|
|
1516
|
+
* here is the shipped value. A payload that cannot be serialised at all
|
|
1517
|
+
* is a recorder error and propagates - the bracket around the turn
|
|
1518
|
+
* takes care of the half-written state.
|
|
1519
|
+
*/
|
|
1520
|
+
saveFrame(traceId, slot, frame, options = {}) {
|
|
1521
|
+
const payload = JSON.stringify(frame);
|
|
1522
|
+
const bytes = Buffer.byteLength(payload, 'utf8');
|
|
1523
|
+
if (bytes > (options.maxFrameBytes ?? DEFAULT_MAX_FRAME_BYTES))
|
|
1524
|
+
return false;
|
|
1525
|
+
// The session is read from the trace: the frame itself does not carry
|
|
1526
|
+
// it, and the delete paths need it as a column (R17). A missing trace
|
|
1527
|
+
// fails the insert on the foreign key, which is the correct outcome -
|
|
1528
|
+
// a frame cannot exist without its trace.
|
|
1529
|
+
const trace = this.db
|
|
1530
|
+
.prepare('SELECT session_id FROM dream_traces WHERE id = ?')
|
|
1531
|
+
.get(traceId);
|
|
1532
|
+
this.db
|
|
1533
|
+
.prepare(`INSERT INTO dream_frames
|
|
1534
|
+
(trace_id, slot, frame_v, owner, session_id, box, corpus_stamp_id, payload, bytes, created_at)
|
|
1535
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)
|
|
1536
|
+
.run(traceId, slot, frame.v, frame.owner, trace?.session_id ?? null, JSON.stringify(frame.box), frame.corpusStampId, payload, bytes, Date.now());
|
|
1537
|
+
return true;
|
|
1538
|
+
}
|
|
1539
|
+
/**
|
|
1540
|
+
* Append one touch row per memory id. Deliberately append-only (R4):
|
|
1541
|
+
* two touches of the same (trace, memory) are two rows, because the
|
|
1542
|
+
* record exists to make the historyless counters reconstructable, not
|
|
1543
|
+
* to dedupe them.
|
|
1544
|
+
*/
|
|
1545
|
+
recordTouches(traceId, owner, ids, policyId) {
|
|
1546
|
+
if (!ids.length)
|
|
1547
|
+
return;
|
|
1548
|
+
const now = Date.now();
|
|
1549
|
+
// The turn id rides along from the trace, so labels can attach at the
|
|
1550
|
+
// turn without a second lookup (R19).
|
|
1551
|
+
const insert = this.db.prepare(`INSERT INTO memory_touches (id, owner, memory_id, turn_id, trace_id, policy_id, at)
|
|
1552
|
+
VALUES (?, ?, ?, (SELECT turn_id FROM dream_traces WHERE id = ?), ?, ?, ?)`);
|
|
1553
|
+
for (const memoryId of ids) {
|
|
1554
|
+
insert.run(randomUUID(), owner, memoryId, traceId, traceId, policyId ?? null, now);
|
|
1555
|
+
}
|
|
1556
|
+
}
|
|
1557
|
+
/**
|
|
1558
|
+
* The night's read path: stored frames of one owner with their traces.
|
|
1559
|
+
* Oldest first with (trace, slot) as the tiebreaker, so the probe walks
|
|
1560
|
+
* a deterministic order; `since` selects on the frame's own creation.
|
|
1561
|
+
*
|
|
1562
|
+
* `newest` says WHICH end the limit cuts from, never which order comes
|
|
1563
|
+
* back: the rows are handed over oldest first either way, so the last
|
|
1564
|
+
* entry is always the newest one and every caller that reads a box or a
|
|
1565
|
+
* trailing slice off the tail keeps reading the same thing. Without it a
|
|
1566
|
+
* limited pool is the OLDEST rows, and a reader that means "since the
|
|
1567
|
+
* last promotion" or "the newest slice" goes structurally dead the moment
|
|
1568
|
+
* an owner holds more frames than the cap - it is pinned to a
|
|
1569
|
+
* weeks-old slice for good. The default stays oldest, because the grid
|
|
1570
|
+
* probe walks and reports exactly that pool.
|
|
1571
|
+
*/
|
|
1572
|
+
framesFor(owner, options = {}) {
|
|
1573
|
+
// Descending on all three keys, so the cut is the exact tail of the
|
|
1574
|
+
// ascending order and reversing it restores that order row for row.
|
|
1575
|
+
const order = options.newest
|
|
1576
|
+
? ' ORDER BY f.created_at DESC, f.trace_id DESC, f.slot DESC LIMIT ?'
|
|
1577
|
+
: ' ORDER BY f.created_at ASC, f.trace_id, f.slot LIMIT ?';
|
|
1578
|
+
const sql = `SELECT t.*, f.trace_id AS f_trace_id, f.owner AS f_owner, f.session_id AS f_session_id,
|
|
1579
|
+
f.slot AS f_slot, f.frame_v AS f_frame_v, f.box AS f_box,
|
|
1580
|
+
f.corpus_stamp_id AS f_corpus_stamp_id, f.payload AS f_payload,
|
|
1581
|
+
f.bytes AS f_bytes, f.created_at AS f_created_at
|
|
1582
|
+
FROM dream_frames f
|
|
1583
|
+
JOIN dream_traces t ON t.id = f.trace_id
|
|
1584
|
+
WHERE f.owner = ?` +
|
|
1585
|
+
(options.since ? ' AND f.created_at >= ?' : '') +
|
|
1586
|
+
order;
|
|
1587
|
+
const values = [owner];
|
|
1588
|
+
if (options.since)
|
|
1589
|
+
values.push(options.since);
|
|
1590
|
+
values.push(options.limit ?? 500);
|
|
1591
|
+
const rows = this.db.prepare(sql).all(...values);
|
|
1592
|
+
if (options.newest)
|
|
1593
|
+
rows.reverse();
|
|
1594
|
+
return rows.map((row) => ({ trace: mapDreamTrace(row), frame: mapDreamFrame(row) }));
|
|
1595
|
+
}
|
|
1596
|
+
/**
|
|
1597
|
+
* How many stored frames one owner has, regardless of any pool limit.
|
|
1598
|
+
* `framesFor` walks a capped pool from one end or the other, so every
|
|
1599
|
+
* reader that can hit the cap reports this count beside the pool it
|
|
1600
|
+
* actually read - a measurement over half the frames must be visible as
|
|
1601
|
+
* one, not pass silently.
|
|
1602
|
+
*/
|
|
1603
|
+
dreamFrameCount(owner) {
|
|
1604
|
+
const row = this.db
|
|
1605
|
+
.prepare('SELECT COUNT(*) AS n FROM dream_frames WHERE owner = ?')
|
|
1606
|
+
.get(owner);
|
|
1607
|
+
return Number(row.n ?? 0);
|
|
1608
|
+
}
|
|
1609
|
+
/**
|
|
1610
|
+
* Delete frames older than `before`, in batches that each own their
|
|
1611
|
+
* transaction. With foreign keys on, deleting a trace cascades its
|
|
1612
|
+
* frames and touches inside the same statement, and an unbounded sweep
|
|
1613
|
+
* would be one long exclusive write lock on the only connection. The
|
|
1614
|
+
* WAL is truncated afterwards so a nightly sweep actually returns space
|
|
1615
|
+
* to the filesystem instead of growing the file forever. Night-side by
|
|
1616
|
+
* design: the per-batch BEGIN must never run inside another
|
|
1617
|
+
* transaction.
|
|
1618
|
+
*/
|
|
1619
|
+
sweepDreamFrames(before) {
|
|
1620
|
+
// Row values pick the exact (trace, slot) pairs: the table's key is a
|
|
1621
|
+
// pair, and deleting by trace_id alone would be wrong the day a second
|
|
1622
|
+
// slot arrives.
|
|
1623
|
+
const statement = this.db.prepare(`DELETE FROM dream_frames WHERE (trace_id, slot) IN
|
|
1624
|
+
(SELECT trace_id, slot FROM dream_frames WHERE created_at < ? LIMIT ${SWEEP_BATCH})`);
|
|
1625
|
+
let swept = 0;
|
|
1626
|
+
for (;;) {
|
|
1627
|
+
this.db.exec('BEGIN');
|
|
1628
|
+
let changes;
|
|
1629
|
+
try {
|
|
1630
|
+
changes = Number(statement.run(before).changes ?? 0);
|
|
1631
|
+
}
|
|
1632
|
+
catch (error) {
|
|
1633
|
+
this.db.exec('ROLLBACK');
|
|
1634
|
+
throw error;
|
|
1635
|
+
}
|
|
1636
|
+
this.db.exec('COMMIT');
|
|
1637
|
+
swept += changes;
|
|
1638
|
+
if (changes < SWEEP_BATCH)
|
|
1639
|
+
break;
|
|
1640
|
+
}
|
|
1641
|
+
this.db.exec('PRAGMA wal_checkpoint(TRUNCATE)');
|
|
1642
|
+
return swept;
|
|
1643
|
+
}
|
|
1644
|
+
/**
|
|
1645
|
+
* Delete traces older than `before` (their frames and touches cascade),
|
|
1646
|
+
* batched like `sweepDreamFrames` and for the same reasons.
|
|
1647
|
+
*/
|
|
1648
|
+
sweepDreamTraces(before) {
|
|
1649
|
+
const statement = this.db.prepare(`DELETE FROM dream_traces WHERE id IN
|
|
1650
|
+
(SELECT id FROM dream_traces WHERE created_at < ? LIMIT ${SWEEP_BATCH})`);
|
|
1651
|
+
let swept = 0;
|
|
1652
|
+
for (;;) {
|
|
1653
|
+
this.db.exec('BEGIN');
|
|
1654
|
+
let changes;
|
|
1655
|
+
try {
|
|
1656
|
+
changes = Number(statement.run(before).changes ?? 0);
|
|
1657
|
+
}
|
|
1658
|
+
catch (error) {
|
|
1659
|
+
this.db.exec('ROLLBACK');
|
|
1660
|
+
throw error;
|
|
1661
|
+
}
|
|
1662
|
+
this.db.exec('COMMIT');
|
|
1663
|
+
swept += changes;
|
|
1664
|
+
if (changes < SWEEP_BATCH)
|
|
1665
|
+
break;
|
|
1666
|
+
}
|
|
1667
|
+
this.db.exec('PRAGMA wal_checkpoint(TRUNCATE)');
|
|
1668
|
+
return swept;
|
|
1669
|
+
}
|
|
1670
|
+
/**
|
|
1671
|
+
* The delete paths of R17: a frame is a verbatim store, so it may never
|
|
1672
|
+
* outlive the memories or the session it came from. Owner and session
|
|
1673
|
+
* sit on the frame as their own columns precisely so these paths never
|
|
1674
|
+
* have to read the payload. `Assistant.deleteSession` calls the session
|
|
1675
|
+
* variant; the three memory-retiring methods call the owner one.
|
|
1676
|
+
*/
|
|
1677
|
+
dropDreamFramesForOwner(owner) {
|
|
1678
|
+
const result = this.db
|
|
1679
|
+
.prepare('DELETE FROM dream_frames WHERE owner = ?')
|
|
1680
|
+
.run(owner);
|
|
1681
|
+
return Number(result.changes ?? 0);
|
|
1682
|
+
}
|
|
1683
|
+
/** See `dropDreamFramesForOwner`. */
|
|
1684
|
+
dropDreamFramesForSession(sessionId) {
|
|
1685
|
+
const result = this.db
|
|
1686
|
+
.prepare('DELETE FROM dream_frames WHERE session_id = ?')
|
|
1687
|
+
.run(sessionId);
|
|
1688
|
+
return Number(result.changes ?? 0);
|
|
1689
|
+
}
|
|
1690
|
+
/**
|
|
1691
|
+
* The document-frequency fingerprint of the corpus, over exactly the
|
|
1692
|
+
* tokens the frames of one night use (R10). bm25 is frozen in the frame
|
|
1693
|
+
* and can never be revalidated, so the corpus is the only observable
|
|
1694
|
+
* that correlates with a frame going stale - and the vocabulary scan
|
|
1695
|
+
* walks the whole index, which is why this runs once per night in the
|
|
1696
|
+
* probe and never inside a turn. The result is cached in `meta` under
|
|
1697
|
+
* its own id; turns stamp only that id onto their frames.
|
|
1698
|
+
*/
|
|
1699
|
+
corpusFingerprint(owner, tokens) {
|
|
1700
|
+
const distinct = [...new Set(tokens)].sort();
|
|
1701
|
+
const df = {};
|
|
1702
|
+
if (distinct.length) {
|
|
1703
|
+
const rows = this.db
|
|
1704
|
+
.prepare('SELECT term, doc FROM memories_fts_v WHERE term IN (' + distinct.map(() => '?').join(', ') + ')')
|
|
1705
|
+
.all(...distinct);
|
|
1706
|
+
for (const row of rows)
|
|
1707
|
+
df[row.term] = Number(row.doc);
|
|
1708
|
+
}
|
|
1709
|
+
// A token the index has never seen still belongs in the fingerprint:
|
|
1710
|
+
// df 0 then and df > 0 today is the largest relative move there is.
|
|
1711
|
+
for (const term of distinct)
|
|
1712
|
+
if (df[term] === undefined)
|
|
1713
|
+
df[term] = 0;
|
|
1714
|
+
const corpus = { id: randomUUID(), owner, at: Date.now(), df };
|
|
1715
|
+
this.setMeta(CORPUS_STAMP_PREFIX + corpus.id, JSON.stringify(corpus));
|
|
1716
|
+
this.setMeta(CORPUS_CURRENT_PREFIX + owner, corpus.id);
|
|
1717
|
+
this.pruneCorpusStamps(owner, corpus.id);
|
|
1718
|
+
return corpus;
|
|
1719
|
+
}
|
|
1720
|
+
/**
|
|
1721
|
+
* Retention for the stamp rows: one is written per night and nothing ever
|
|
1722
|
+
* removed them, so `meta` grew a full df map per night without bound. A
|
|
1723
|
+
* stamp is only ever read through a frame's `corpus_stamp_id` or the
|
|
1724
|
+
* current pointer, so a stamp of this owner that no frame cites and that
|
|
1725
|
+
* is not the fresh one is dead the moment the pointer moves. Corrupt rows
|
|
1726
|
+
* are left alone - a row nothing can parse certifies nothing either way,
|
|
1727
|
+
* and this method never throws into the night.
|
|
1728
|
+
*/
|
|
1729
|
+
pruneCorpusStamps(owner, keepId) {
|
|
1730
|
+
const rows = this.db
|
|
1731
|
+
.prepare('SELECT key, value FROM meta WHERE key LIKE ?')
|
|
1732
|
+
.all(CORPUS_STAMP_PREFIX + '%');
|
|
1733
|
+
if (rows.length <= 1)
|
|
1734
|
+
return;
|
|
1735
|
+
const cited = new Set(this.db
|
|
1736
|
+
.prepare('SELECT DISTINCT corpus_stamp_id AS id FROM dream_frames WHERE corpus_stamp_id IS NOT NULL')
|
|
1737
|
+
.all().map((row) => row.id));
|
|
1738
|
+
const drop = this.db.prepare('DELETE FROM meta WHERE key = ?');
|
|
1739
|
+
for (const row of rows) {
|
|
1740
|
+
const id = row.key.slice(CORPUS_STAMP_PREFIX.length);
|
|
1741
|
+
if (id === keepId || cited.has(id))
|
|
1742
|
+
continue;
|
|
1743
|
+
try {
|
|
1744
|
+
if (JSON.parse(row.value).owner !== owner)
|
|
1745
|
+
continue;
|
|
1746
|
+
}
|
|
1747
|
+
catch {
|
|
1748
|
+
continue;
|
|
1749
|
+
}
|
|
1750
|
+
drop.run(row.key);
|
|
1751
|
+
}
|
|
1752
|
+
}
|
|
1753
|
+
/**
|
|
1754
|
+
* The stamp a turn should carry: the newest fingerprint of this owner.
|
|
1755
|
+
* A meta read and nothing more - computing here would drag the
|
|
1756
|
+
* vocabulary scan into the turn. Null until the first night has stamped
|
|
1757
|
+
* one, and null for a corrupted row rather than a throw: a stamp that
|
|
1758
|
+
* cannot be read simply does not certify anything.
|
|
1759
|
+
*/
|
|
1760
|
+
currentCorpusStamp(owner) {
|
|
1761
|
+
const id = this.getMeta(CORPUS_CURRENT_PREFIX + owner);
|
|
1762
|
+
if (!id)
|
|
1763
|
+
return null;
|
|
1764
|
+
const stored = this.getMeta(CORPUS_STAMP_PREFIX + id);
|
|
1765
|
+
if (!stored)
|
|
1766
|
+
return null;
|
|
1767
|
+
try {
|
|
1768
|
+
return JSON.parse(stored);
|
|
1769
|
+
}
|
|
1770
|
+
catch {
|
|
1771
|
+
return null;
|
|
1772
|
+
}
|
|
1773
|
+
}
|
|
1774
|
+
/* --------------------------- dream, stage 2+ --------------------------- */
|
|
1775
|
+
/*
|
|
1776
|
+
* Labels, policy versions, slot state, evaluations and episodes: what
|
|
1777
|
+
* turns a measurement into a promotion that can be taken back again.
|
|
1778
|
+
* Stage 1 above only records and scores.
|
|
1779
|
+
*
|
|
1780
|
+
* Two rules hold for everything in this block. Every read path filters by
|
|
1781
|
+
* owner in SQL, and once more in JS wherever a join could carry a row
|
|
1782
|
+
* across an owner boundary (concept 10.5) - `dream_evals` has no owner
|
|
1783
|
+
* column of its own and reaches it only through `policy_versions`. And
|
|
1784
|
+
* nothing here deletes evidence: a label whose target is gone gets
|
|
1785
|
+
* `dead_at`, never a DELETE (8.3, S9).
|
|
1786
|
+
*/
|
|
1787
|
+
/**
|
|
1788
|
+
* Write one label; see `putLabels`.
|
|
1789
|
+
*/
|
|
1790
|
+
putLabel(label) {
|
|
1791
|
+
this.putLabels([label]);
|
|
1792
|
+
}
|
|
1793
|
+
/**
|
|
1794
|
+
* Write a batch of labels, returning how many rows went in - that count is
|
|
1795
|
+
* the run's `dreamLabelsWritten`.
|
|
1796
|
+
*
|
|
1797
|
+
* `(turn_id, target, source)` is the key, so one source re-stating its
|
|
1798
|
+
* claim about the same target in the same turn replaces its own row
|
|
1799
|
+
* instead of stacking a second one. A contradiction BETWEEN two sources
|
|
1800
|
+
* keeps both rows, which is exactly what makes it countable rather than
|
|
1801
|
+
* silently overwritten (concept 4.1, S2).
|
|
1802
|
+
*
|
|
1803
|
+
* A session-scoped label carries the SESSION id in `turn_id`: the column
|
|
1804
|
+
* is NOT NULL and part of the key, and `scope` is what says which of the
|
|
1805
|
+
* two a row holds (the comment AP1 left on the table).
|
|
1806
|
+
*/
|
|
1807
|
+
putLabels(labels) {
|
|
1808
|
+
if (!labels.length)
|
|
1809
|
+
return 0;
|
|
1810
|
+
const insert = this.db.prepare(`INSERT OR REPLACE INTO dream_labels
|
|
1811
|
+
(turn_id, target, source, relevance, scope, evidence, dead_at, created_at, owner, session_id)
|
|
1812
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);
|
|
1813
|
+
for (const label of labels) {
|
|
1814
|
+
insert.run(label.turnId, label.target, label.source, label.relevance, label.scope, label.evidence ?? null, label.deadAt ?? null, label.createdAt, label.owner, label.sessionId ?? null);
|
|
1815
|
+
}
|
|
1816
|
+
return labels.length;
|
|
1817
|
+
}
|
|
1818
|
+
/**
|
|
1819
|
+
* Labels of these turns, oldest first. `owner` is optional because a turn
|
|
1820
|
+
* id already belongs to exactly one owner; the paths that have it to hand
|
|
1821
|
+
* pass it, so the filter is in the SQL where 10.5 wants it.
|
|
1822
|
+
*/
|
|
1823
|
+
labelsForTurns(turnIds, owner) {
|
|
1824
|
+
if (!turnIds.length)
|
|
1825
|
+
return [];
|
|
1826
|
+
const sql = 'SELECT * FROM dream_labels WHERE turn_id IN (' +
|
|
1827
|
+
turnIds.map(() => '?').join(', ') +
|
|
1828
|
+
')' +
|
|
1829
|
+
(owner ? ' AND owner = ?' : '') +
|
|
1830
|
+
' ORDER BY created_at ASC, target, source';
|
|
1831
|
+
const values = [...turnIds];
|
|
1832
|
+
if (owner)
|
|
1833
|
+
values.push(owner);
|
|
1834
|
+
const rows = this.db.prepare(sql).all(...values);
|
|
1835
|
+
return rows.map(mapDreamLabel);
|
|
1836
|
+
}
|
|
1837
|
+
/**
|
|
1838
|
+
* The session-scoped labels of these sessions - the unlocatable quote
|
|
1839
|
+
* (4.2a) and the user's edits (4.2b) both land here. Selected on
|
|
1840
|
+
* `turn_id`, not on `session_id`: for `scope = 'session'` the turn column
|
|
1841
|
+
* is where the session id lives, and it is the only one guaranteed to be
|
|
1842
|
+
* filled.
|
|
1843
|
+
*/
|
|
1844
|
+
labelsForSessions(sessionIds, owner) {
|
|
1845
|
+
if (!sessionIds.length)
|
|
1846
|
+
return [];
|
|
1847
|
+
const sql = "SELECT * FROM dream_labels WHERE scope = 'session' AND turn_id IN (" +
|
|
1848
|
+
sessionIds.map(() => '?').join(', ') +
|
|
1849
|
+
')' +
|
|
1850
|
+
(owner ? ' AND owner = ?' : '') +
|
|
1851
|
+
' ORDER BY created_at ASC, target, source';
|
|
1852
|
+
const values = [...sessionIds];
|
|
1853
|
+
if (owner)
|
|
1854
|
+
values.push(owner);
|
|
1855
|
+
const rows = this.db.prepare(sql).all(...values);
|
|
1856
|
+
return rows.map(mapDreamLabel);
|
|
1857
|
+
}
|
|
1858
|
+
/**
|
|
1859
|
+
* Mark every label about one memory dead (S9). The row stays: what it
|
|
1860
|
+
* claims about the turns it was written for is still true, and the label
|
|
1861
|
+
* history is calibration material. Without this, a deleted memory would
|
|
1862
|
+
* drag `reachable_rate` down for a reason that has nothing to do with
|
|
1863
|
+
* labelling and invalidate the evaluation from the wrong end (8.3).
|
|
1864
|
+
*/
|
|
1865
|
+
markLabelsDead(memoryId, at = Date.now()) {
|
|
1866
|
+
const result = this.db
|
|
1867
|
+
.prepare('UPDATE dream_labels SET dead_at = ? WHERE target = ? AND dead_at IS NULL')
|
|
1868
|
+
.run(at, memoryId);
|
|
1869
|
+
return Number(result.changes ?? 0);
|
|
1870
|
+
}
|
|
1871
|
+
/** `markLabelsDead` for a whole bank at once - the archive path (S9). */
|
|
1872
|
+
markOwnerLabelsDead(owner, at = Date.now()) {
|
|
1873
|
+
const result = this.db
|
|
1874
|
+
.prepare('UPDATE dream_labels SET dead_at = ? WHERE owner = ? AND dead_at IS NULL')
|
|
1875
|
+
.run(at, owner);
|
|
1876
|
+
return Number(result.changes ?? 0);
|
|
1877
|
+
}
|
|
1878
|
+
/**
|
|
1879
|
+
* How many labels of each source this owner gained since `since` - the
|
|
1880
|
+
* supply side of 4.5, and what the night reports. Counted on creation, so
|
|
1881
|
+
* a label that has since gone dead still counts: it was written, and the
|
|
1882
|
+
* question here is how much a window actually produces.
|
|
1883
|
+
*/
|
|
1884
|
+
labelCounts(owner, since) {
|
|
1885
|
+
const counts = { correction: 0, review: 0, merge: 0, user: 0 };
|
|
1886
|
+
const rows = this.db
|
|
1887
|
+
.prepare(`SELECT source, COUNT(*) AS n FROM dream_labels
|
|
1888
|
+
WHERE owner = ? AND created_at >= ?
|
|
1889
|
+
GROUP BY source`)
|
|
1890
|
+
.all(owner, since);
|
|
1891
|
+
for (const row of rows) {
|
|
1892
|
+
const source = row.source;
|
|
1893
|
+
if (source in counts)
|
|
1894
|
+
counts[source] = Number(row.n ?? 0);
|
|
1895
|
+
}
|
|
1896
|
+
return counts;
|
|
1897
|
+
}
|
|
1898
|
+
/** Retention for the label table (`dream.retainDays`), batched like the frames. */
|
|
1899
|
+
sweepDreamLabels(before) {
|
|
1900
|
+
// Row values pick the exact key triples, the way `sweepDreamFrames`
|
|
1901
|
+
// picks (trace, slot): the table has no single-column primary key.
|
|
1902
|
+
return this.#sweepInBatches(this.db.prepare(`DELETE FROM dream_labels WHERE (turn_id, target, source) IN
|
|
1903
|
+
(SELECT turn_id, target, source FROM dream_labels WHERE created_at < ? LIMIT ${SWEEP_BATCH})`), before);
|
|
1904
|
+
}
|
|
1905
|
+
/**
|
|
1906
|
+
* Write a new, unpromoted policy version. The version number is the next
|
|
1907
|
+
* one for this `(owner, slot)`; the unique index is what makes that a
|
|
1908
|
+
* constraint rather than a hope.
|
|
1909
|
+
*/
|
|
1910
|
+
createPolicyVersion(input) {
|
|
1911
|
+
const row = this.db
|
|
1912
|
+
.prepare('SELECT MAX(version) AS top FROM policy_versions WHERE owner = ? AND slot = ?')
|
|
1913
|
+
.get(input.owner, input.slot);
|
|
1914
|
+
const version = {
|
|
1915
|
+
id: randomUUID(),
|
|
1916
|
+
owner: input.owner,
|
|
1917
|
+
slot: input.slot,
|
|
1918
|
+
version: Number(row?.top ?? 0) + 1,
|
|
1919
|
+
params: input.params,
|
|
1920
|
+
box: input.box,
|
|
1921
|
+
origin: input.origin,
|
|
1922
|
+
parentId: input.parentId,
|
|
1923
|
+
sleepRunId: input.sleepRunId,
|
|
1924
|
+
rationale: input.rationale,
|
|
1925
|
+
replayScore: input.replayScore,
|
|
1926
|
+
replayN: input.replayN,
|
|
1927
|
+
baselineScore: input.baselineScore,
|
|
1928
|
+
auditDelta: input.auditDelta,
|
|
1929
|
+
auditCiLow: input.auditCiLow,
|
|
1930
|
+
createdAt: Date.now(),
|
|
1931
|
+
};
|
|
1932
|
+
this.db
|
|
1933
|
+
.prepare(`INSERT INTO policy_versions
|
|
1934
|
+
(id, owner, slot, version, params, box, origin, parent_id, sleep_run_id, rationale,
|
|
1935
|
+
replay_score, replay_n, baseline_score, audit_delta, audit_ci_low, created_at)
|
|
1936
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)
|
|
1937
|
+
.run(version.id, version.owner, version.slot, version.version, JSON.stringify(version.params), JSON.stringify(version.box), version.origin, version.parentId ?? null, version.sleepRunId ?? null, version.rationale ?? null, version.replayScore ?? null, version.replayN ?? null, version.baselineScore ?? null, version.auditDelta ?? null, version.auditCiLow ?? null, version.createdAt);
|
|
1938
|
+
return version;
|
|
1939
|
+
}
|
|
1940
|
+
policyVersion(id) {
|
|
1941
|
+
const row = this.db.prepare('SELECT * FROM policy_versions WHERE id = ?').get(id);
|
|
1942
|
+
return row ? mapPolicyVersion(row) : null;
|
|
1943
|
+
}
|
|
1944
|
+
/**
|
|
1945
|
+
* The version the resolver lays over the defaults: promoted, not retired,
|
|
1946
|
+
* highest version. Null until the first promotion, which is the whole of
|
|
1947
|
+
* today's behaviour (AP10 reads this).
|
|
1948
|
+
*/
|
|
1949
|
+
activePolicy(owner, slot) {
|
|
1950
|
+
const row = this.db
|
|
1951
|
+
.prepare(`SELECT * FROM policy_versions
|
|
1952
|
+
WHERE owner = ? AND slot = ? AND promoted_at IS NOT NULL AND retired_at IS NULL
|
|
1953
|
+
ORDER BY version DESC LIMIT 1`)
|
|
1954
|
+
.get(owner, slot);
|
|
1955
|
+
return row ? mapPolicyVersion(row) : null;
|
|
1956
|
+
}
|
|
1957
|
+
/** Newest version first - the version curve and the history drawer. */
|
|
1958
|
+
policyHistory(owner, slot, limit = 50) {
|
|
1959
|
+
const rows = this.db
|
|
1960
|
+
.prepare(`SELECT * FROM policy_versions
|
|
1961
|
+
WHERE owner = ? AND slot = ?
|
|
1962
|
+
ORDER BY version DESC LIMIT ?`)
|
|
1963
|
+
.all(owner, slot, limit);
|
|
1964
|
+
return rows.map(mapPolicyVersion);
|
|
1965
|
+
}
|
|
1966
|
+
/**
|
|
1967
|
+
* Put one version in charge. `prevActiveId` is what was active at that
|
|
1968
|
+
* moment (8.5) - it is stored on the new row AND retired in the same
|
|
1969
|
+
* breath, because a revert or a night's undo has nothing to bring back
|
|
1970
|
+
* otherwise. Undefined means "nothing was active", the way `snapshotSkill`
|
|
1971
|
+
* records a skill that did not exist yet.
|
|
1972
|
+
*/
|
|
1973
|
+
promotePolicyVersion(id, options = {}) {
|
|
1974
|
+
const at = options.at ?? Date.now();
|
|
1975
|
+
this.db
|
|
1976
|
+
.prepare(`UPDATE policy_versions
|
|
1977
|
+
SET promoted_at = ?, retired_at = NULL, prev_active_id = ?,
|
|
1978
|
+
sleep_run_id = COALESCE(?, sleep_run_id)
|
|
1979
|
+
WHERE id = ?`)
|
|
1980
|
+
.run(at, options.prevActiveId ?? null, options.sleepRunId ?? null, id);
|
|
1981
|
+
if (options.prevActiveId)
|
|
1982
|
+
this.retirePolicyVersion(options.prevActiveId, at);
|
|
1983
|
+
const version = this.policyVersion(id);
|
|
1984
|
+
// The slot's own clock moves with the promotion, so "when did this slot
|
|
1985
|
+
// last change" never has to be derived from the version table.
|
|
1986
|
+
if (version) {
|
|
1987
|
+
this.#ensureSlotState(version.owner, version.slot);
|
|
1988
|
+
this.db
|
|
1989
|
+
.prepare('UPDATE dream_slot_state SET last_promoted = ? WHERE owner = ? AND slot = ?')
|
|
1990
|
+
.run(at, version.owner, version.slot);
|
|
1991
|
+
}
|
|
1992
|
+
return version;
|
|
1993
|
+
}
|
|
1994
|
+
retirePolicyVersion(id, at = Date.now()) {
|
|
1995
|
+
this.db
|
|
1996
|
+
.prepare('UPDATE policy_versions SET retired_at = ? WHERE id = ? AND retired_at IS NULL')
|
|
1997
|
+
.run(at, id);
|
|
1998
|
+
}
|
|
1999
|
+
/** The other half of a revert: the version `prev_active_id` points at. */
|
|
2000
|
+
reactivatePolicyVersion(id) {
|
|
2001
|
+
this.db.prepare('UPDATE policy_versions SET retired_at = NULL WHERE id = ?').run(id);
|
|
2002
|
+
}
|
|
2003
|
+
/**
|
|
2004
|
+
* What the wake test actually read, written back next to what the
|
|
2005
|
+
* promotion promised (concept 5.5c).
|
|
2006
|
+
*
|
|
2007
|
+
* `replay_score` is the claim a version was promoted on; `online_score` is
|
|
2008
|
+
* the same quantity measured again, live, once `dream.calibrationTraces`
|
|
2009
|
+
* frames have accumulated since the promotion. The night computes that
|
|
2010
|
+
* drift and freezes the slot on it, but until this setter existed it had
|
|
2011
|
+
* nowhere to put the number it had just read - the column was written by
|
|
2012
|
+
* nothing, so the one reading that could tell a person "the promise held"
|
|
2013
|
+
* survived only inside the night's own report sentence.
|
|
2014
|
+
*/
|
|
2015
|
+
setPolicyOnlineScore(id, score) {
|
|
2016
|
+
this.db.prepare('UPDATE policy_versions SET online_score = ? WHERE id = ?').run(score, id);
|
|
2017
|
+
}
|
|
2018
|
+
/**
|
|
2019
|
+
* Freeze state and cooldown clock of one slot. A slot with no row has
|
|
2020
|
+
* never been promoted and is not frozen, which is a state, not a gap - so
|
|
2021
|
+
* this returns a record rather than null and the callers stay free of a
|
|
2022
|
+
* null check that only ever means "the defaults".
|
|
2023
|
+
*/
|
|
2024
|
+
slotState(owner, slot) {
|
|
2025
|
+
const row = this.db
|
|
2026
|
+
.prepare('SELECT * FROM dream_slot_state WHERE owner = ? AND slot = ?')
|
|
2027
|
+
.get(owner, slot);
|
|
2028
|
+
return row ? mapDreamSlotState(row) : { owner, slot };
|
|
2029
|
+
}
|
|
2030
|
+
/** One of the four causes of 10.3. A frozen slot keeps measuring, never promotes. */
|
|
2031
|
+
freezeSlot(owner, slot, reason, at = Date.now()) {
|
|
2032
|
+
this.#ensureSlotState(owner, slot);
|
|
2033
|
+
this.db
|
|
2034
|
+
.prepare('UPDATE dream_slot_state SET frozen_at = ?, frozen_reason = ? WHERE owner = ? AND slot = ?')
|
|
2035
|
+
.run(at, reason, owner, slot);
|
|
2036
|
+
}
|
|
2037
|
+
/** Thawing is a person's decision; nothing in the night calls this. */
|
|
2038
|
+
thawSlot(owner, slot) {
|
|
2039
|
+
this.#ensureSlotState(owner, slot);
|
|
2040
|
+
this.db
|
|
2041
|
+
.prepare('UPDATE dream_slot_state SET frozen_at = NULL, frozen_reason = NULL WHERE owner = ? AND slot = ?')
|
|
2042
|
+
.run(owner, slot);
|
|
2043
|
+
}
|
|
2044
|
+
setSlotCooldown(owner, slot, until) {
|
|
2045
|
+
this.#ensureSlotState(owner, slot);
|
|
2046
|
+
this.db
|
|
2047
|
+
.prepare('UPDATE dream_slot_state SET cooldown_until = ? WHERE owner = ? AND slot = ?')
|
|
2048
|
+
.run(until, owner, slot);
|
|
2049
|
+
}
|
|
2050
|
+
/**
|
|
2051
|
+
* The row exists or it does not; the three setters above each change one
|
|
2052
|
+
* column and would otherwise have to repeat the whole upsert. Kept as
|
|
2053
|
+
* INSERT OR IGNORE plus UPDATE rather than an upsert clause, which is what
|
|
2054
|
+
* the rest of the store does.
|
|
2055
|
+
*/
|
|
2056
|
+
#ensureSlotState(owner, slot) {
|
|
2057
|
+
this.db
|
|
2058
|
+
.prepare('INSERT OR IGNORE INTO dream_slot_state (owner, slot) VALUES (?, ?)')
|
|
2059
|
+
.run(owner, slot);
|
|
2060
|
+
}
|
|
2061
|
+
/**
|
|
2062
|
+
* Record one candidate evaluation. Written whether or not it promoted:
|
|
2063
|
+
* the night that measures and does not promote is the common case, and
|
|
2064
|
+
* the record of it is what the calibration and the report stand on.
|
|
2065
|
+
*/
|
|
2066
|
+
recordDreamEval(input) {
|
|
2067
|
+
const evaluation = {
|
|
2068
|
+
...input,
|
|
2069
|
+
id: input.id ?? randomUUID(),
|
|
2070
|
+
createdAt: input.createdAt ?? Date.now(),
|
|
2071
|
+
};
|
|
2072
|
+
this.db
|
|
2073
|
+
.prepare(`INSERT INTO dream_evals
|
|
2074
|
+
(id, sleep_run_id, policy_id, slot, traces, closed, abstained, abstain_reasons,
|
|
2075
|
+
reachable_rate, label_coverage, cost_only_share, score, baseline, delta,
|
|
2076
|
+
ci_low, ci_high, audit_delta, audit_ci_low, delta_live, sign_agree, eval_ms,
|
|
2077
|
+
trace_set_hash, evidence_digest, promoted, detail, created_at)
|
|
2078
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)
|
|
2079
|
+
.run(evaluation.id, evaluation.sleepRunId, evaluation.policyId, evaluation.slot, evaluation.traces, evaluation.closed, evaluation.abstained, JSON.stringify(evaluation.abstainReasons), evaluation.reachableRate, evaluation.labelCoverage, evaluation.costOnlyShare, evaluation.score, evaluation.baseline, evaluation.delta, evaluation.ciLow, evaluation.ciHigh, evaluation.auditDelta ?? null, evaluation.auditCiLow ?? null, evaluation.deltaLive ?? null,
|
|
2080
|
+
// NULL is a value here, not a missing one: it means the freshness
|
|
2081
|
+
// check was undetermined because the delta sat inside the margin.
|
|
2082
|
+
evaluation.signAgree === null ? null : evaluation.signAgree ? 1 : 0, evaluation.evalMs, evaluation.traceSetHash, evaluation.evidenceDigest ?? null, evaluation.promoted ? 1 : 0, evaluation.detail ? JSON.stringify(evaluation.detail) : null, evaluation.createdAt);
|
|
2083
|
+
return evaluation;
|
|
2084
|
+
}
|
|
2085
|
+
/**
|
|
2086
|
+
* Evaluations, newest first. `dream_evals` carries no owner of its own,
|
|
2087
|
+
* so the owner filter goes through the join to `policy_versions` - in SQL
|
|
2088
|
+
* and again in JS, because that is exactly the kind of join 10.5 is about.
|
|
2089
|
+
*/
|
|
2090
|
+
listDreamEvals(filter = {}) {
|
|
2091
|
+
const clauses = [];
|
|
2092
|
+
const values = [];
|
|
2093
|
+
if (filter.owner) {
|
|
2094
|
+
clauses.push('p.owner = ?');
|
|
2095
|
+
values.push(filter.owner);
|
|
2096
|
+
}
|
|
2097
|
+
if (filter.slot) {
|
|
2098
|
+
clauses.push('e.slot = ?');
|
|
2099
|
+
values.push(filter.slot);
|
|
2100
|
+
}
|
|
2101
|
+
if (filter.sleepRunId) {
|
|
2102
|
+
clauses.push('e.sleep_run_id = ?');
|
|
2103
|
+
values.push(filter.sleepRunId);
|
|
2104
|
+
}
|
|
2105
|
+
if (filter.policyId) {
|
|
2106
|
+
clauses.push('e.policy_id = ?');
|
|
2107
|
+
values.push(filter.policyId);
|
|
2108
|
+
}
|
|
2109
|
+
if (filter.promoted !== undefined) {
|
|
2110
|
+
clauses.push('e.promoted = ?');
|
|
2111
|
+
values.push(filter.promoted ? 1 : 0);
|
|
2112
|
+
}
|
|
2113
|
+
const sql = `SELECT e.*, p.owner AS p_owner FROM dream_evals e
|
|
2114
|
+
JOIN policy_versions p ON p.id = e.policy_id` +
|
|
2115
|
+
(clauses.length ? ' WHERE ' + clauses.join(' AND ') : '') +
|
|
2116
|
+
' ORDER BY e.created_at DESC, e.id LIMIT ?';
|
|
2117
|
+
values.push(filter.limit ?? 100);
|
|
2118
|
+
const rows = this.db.prepare(sql).all(...values);
|
|
2119
|
+
return rows
|
|
2120
|
+
.filter((row) => !filter.owner || row.p_owner === filter.owner)
|
|
2121
|
+
.map(mapDreamEval);
|
|
2122
|
+
}
|
|
2123
|
+
/**
|
|
2124
|
+
* The trace set the last promotion of this slot stood on. The promotion
|
|
2125
|
+
* gate requires the next one to be disjoint from it, so a candidate cannot
|
|
2126
|
+
* be promoted twice off the same evidence.
|
|
2127
|
+
*/
|
|
2128
|
+
lastPromotedTraceSetHash(owner, slot) {
|
|
2129
|
+
const row = this.db
|
|
2130
|
+
.prepare(`SELECT e.trace_set_hash AS hash, p.owner AS p_owner FROM dream_evals e
|
|
2131
|
+
JOIN policy_versions p ON p.id = e.policy_id
|
|
2132
|
+
WHERE p.owner = ? AND e.slot = ? AND e.promoted = 1
|
|
2133
|
+
ORDER BY e.created_at DESC LIMIT 1`)
|
|
2134
|
+
.get(owner, slot);
|
|
2135
|
+
if (!row || row.p_owner !== owner)
|
|
2136
|
+
return null;
|
|
2137
|
+
return row.hash ?? null;
|
|
2138
|
+
}
|
|
2139
|
+
/** Retention for the evaluation table (`dream.retainDays`). */
|
|
2140
|
+
sweepDreamEvals(before) {
|
|
2141
|
+
return this.#sweepInBatches(this.db.prepare(`DELETE FROM dream_evals WHERE id IN
|
|
2142
|
+
(SELECT id FROM dream_evals WHERE created_at < ? LIMIT ${SWEEP_BATCH})`), before);
|
|
2143
|
+
}
|
|
2144
|
+
/**
|
|
2145
|
+
* Index one episode over the existing turn journal. `id` is the id of the
|
|
2146
|
+
* `turns` or `assignments` row it indexes, so re-indexing the same episode
|
|
2147
|
+
* replaces its row instead of doubling it - this table is an index, never
|
|
2148
|
+
* a second transcript store.
|
|
2149
|
+
*/
|
|
2150
|
+
recordDreamEpisode(input) {
|
|
2151
|
+
const episode = { ...input, createdAt: input.createdAt ?? Date.now() };
|
|
2152
|
+
this.db
|
|
2153
|
+
.prepare(`INSERT OR REPLACE INTO dream_episodes
|
|
2154
|
+
(id, owner, kind, session_id, slot, steps, outcome, holdout, audit,
|
|
2155
|
+
started_at, finished_at, created_at)
|
|
2156
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)
|
|
2157
|
+
.run(episode.id, episode.owner, episode.kind, episode.sessionId ?? null, episode.slot, episode.steps, episode.outcome, episode.holdout ? 1 : 0, episode.audit ? 1 : 0, episode.startedAt, episode.finishedAt ?? null, episode.createdAt);
|
|
2158
|
+
return episode;
|
|
2159
|
+
}
|
|
2160
|
+
/** Episodes of one owner, newest first; `holdout`/`audit` select a split. */
|
|
2161
|
+
dreamEpisodes(owner, options = {}) {
|
|
2162
|
+
const sql = 'SELECT * FROM dream_episodes WHERE owner = ?' +
|
|
2163
|
+
(options.holdout !== undefined ? ' AND holdout = ?' : '') +
|
|
2164
|
+
(options.audit !== undefined ? ' AND audit = ?' : '') +
|
|
2165
|
+
' ORDER BY created_at DESC, id LIMIT ?';
|
|
2166
|
+
const values = [owner];
|
|
2167
|
+
if (options.holdout !== undefined)
|
|
2168
|
+
values.push(options.holdout ? 1 : 0);
|
|
2169
|
+
if (options.audit !== undefined)
|
|
2170
|
+
values.push(options.audit ? 1 : 0);
|
|
2171
|
+
values.push(options.limit ?? 200);
|
|
2172
|
+
const rows = this.db.prepare(sql).all(...values);
|
|
2173
|
+
return rows.map(mapDreamEpisode);
|
|
2174
|
+
}
|
|
2175
|
+
/**
|
|
2176
|
+
* Retention for the episode index. It follows `dream.frameRetainDays`, not
|
|
2177
|
+
* `dream.retainDays`: an episode points straight at journal rows that hold
|
|
2178
|
+
* verbatim text, and no wording outlives the memory it came from (S21).
|
|
2179
|
+
*/
|
|
2180
|
+
sweepDreamEpisodes(before) {
|
|
2181
|
+
return this.#sweepInBatches(this.db.prepare(`DELETE FROM dream_episodes WHERE id IN
|
|
2182
|
+
(SELECT id FROM dream_episodes WHERE created_at < ? LIMIT ${SWEEP_BATCH})`), before);
|
|
2183
|
+
}
|
|
2184
|
+
/**
|
|
2185
|
+
* The batched sweep `sweepDreamFrames` and `sweepDreamTraces` spell out
|
|
2186
|
+
* by hand, for the three small stage-2 tables: one transaction per batch,
|
|
2187
|
+
* so a nightly sweep is never one long exclusive write lock on the only
|
|
2188
|
+
* connection, and a truncating checkpoint at the end so the WAL actually
|
|
2189
|
+
* gives its space back. Night-side by design - the per-batch BEGIN must
|
|
2190
|
+
* never run inside another transaction.
|
|
2191
|
+
*/
|
|
2192
|
+
#sweepInBatches(statement, before) {
|
|
2193
|
+
let swept = 0;
|
|
2194
|
+
for (;;) {
|
|
2195
|
+
this.db.exec('BEGIN');
|
|
2196
|
+
let changes;
|
|
2197
|
+
try {
|
|
2198
|
+
changes = Number(statement.run(before).changes ?? 0);
|
|
2199
|
+
}
|
|
2200
|
+
catch (error) {
|
|
2201
|
+
this.db.exec('ROLLBACK');
|
|
2202
|
+
throw error;
|
|
2203
|
+
}
|
|
2204
|
+
this.db.exec('COMMIT');
|
|
2205
|
+
swept += changes;
|
|
2206
|
+
if (changes < SWEEP_BATCH)
|
|
2207
|
+
break;
|
|
2208
|
+
}
|
|
2209
|
+
this.db.exec('PRAGMA wal_checkpoint(TRUNCATE)');
|
|
2210
|
+
return swept;
|
|
2211
|
+
}
|
|
854
2212
|
/* ------------------------------- meta ------------------------------- */
|
|
855
2213
|
// Beyond the schema version, `meta` is a generic key/value store for small
|
|
856
2214
|
// mappings that don't warrant their own table, e.g. Telegram-chat-to-session.
|
|
@@ -870,7 +2228,9 @@ function mapSession(row) {
|
|
|
870
2228
|
return {
|
|
871
2229
|
id: row.id,
|
|
872
2230
|
title: row.title,
|
|
873
|
-
|
|
2231
|
+
// Anything the column does not know is a chat - that is what the default
|
|
2232
|
+
// was before `kind` existed, and what a stray value should degrade to.
|
|
2233
|
+
kind: (['voice', 'mail', 'schedule'].includes(row.kind) ? row.kind : 'chat'),
|
|
874
2234
|
provider: row.provider,
|
|
875
2235
|
model: row.model ?? undefined,
|
|
876
2236
|
cwd: row.cwd,
|
|
@@ -892,8 +2252,10 @@ function mapMessage(row) {
|
|
|
892
2252
|
provider: row.provider ?? undefined,
|
|
893
2253
|
model: row.model ?? undefined,
|
|
894
2254
|
agent: row.agent ?? undefined,
|
|
895
|
-
toolCalls:
|
|
896
|
-
|
|
2255
|
+
toolCalls: parseJsonColumn(row.tool_calls),
|
|
2256
|
+
blocks: parseJsonColumn(row.blocks),
|
|
2257
|
+
usage: parseJsonColumn(row.usage),
|
|
2258
|
+
turnId: row.turn_id ?? undefined,
|
|
897
2259
|
createdAt: Number(row.created_at),
|
|
898
2260
|
};
|
|
899
2261
|
}
|
|
@@ -905,6 +2267,7 @@ export function mapMemory(row) {
|
|
|
905
2267
|
tags: parseTags(row.tags),
|
|
906
2268
|
importance: Number(row.importance),
|
|
907
2269
|
owner: row.owner ?? ASSISTANT_MEMORY_OWNER,
|
|
2270
|
+
evidence: row.evidence ?? undefined,
|
|
908
2271
|
sourceSessionId: row.source_session_id ?? undefined,
|
|
909
2272
|
createdAt: Number(row.created_at),
|
|
910
2273
|
updatedAt: Number(row.updated_at),
|
|
@@ -917,6 +2280,7 @@ export function mapMemory(row) {
|
|
|
917
2280
|
supersededBy: row.superseded_by ?? undefined,
|
|
918
2281
|
sleepRunId: row.sleep_run_id ?? undefined,
|
|
919
2282
|
usefulness: Number(row.usefulness ?? 0),
|
|
2283
|
+
archivedAt: row.archived_at ? Number(row.archived_at) : undefined,
|
|
920
2284
|
};
|
|
921
2285
|
}
|
|
922
2286
|
export function mapEntity(row) {
|
|
@@ -954,18 +2318,178 @@ export function mapSleepRun(row) {
|
|
|
954
2318
|
finishedAt: row.finished_at ? Number(row.finished_at) : undefined,
|
|
955
2319
|
durationMs: row.duration_ms ? Number(row.duration_ms) : undefined,
|
|
956
2320
|
readCount: Number(row.read_count ?? 0),
|
|
2321
|
+
replayedCount: Number(row.replayed_count ?? 0),
|
|
2322
|
+
learnedCount: Number(row.learned_count ?? 0),
|
|
957
2323
|
mergedCount: Number(row.merged_count ?? 0),
|
|
958
2324
|
dormantCount: Number(row.dormant_count ?? 0),
|
|
959
2325
|
edgeCount: Number(row.edge_count ?? 0),
|
|
960
2326
|
insightCount: Number(row.insight_count ?? 0),
|
|
2327
|
+
skillCount: Number(row.skill_count ?? 0),
|
|
2328
|
+
skillRevisedCount: Number(row.skill_revised_count ?? 0),
|
|
961
2329
|
conflictCount: Number(row.conflict_count ?? 0),
|
|
962
2330
|
resolvedCount: Number(row.resolved_count ?? 0),
|
|
2331
|
+
dreamTracesSeen: Number(row.dream_traces_seen ?? 0),
|
|
2332
|
+
dreamFramesScored: Number(row.dream_frames_scored ?? 0),
|
|
2333
|
+
dreamCandidates: Number(row.dream_candidates ?? 0),
|
|
2334
|
+
dreamPromoted: Number(row.dream_promoted ?? 0),
|
|
2335
|
+
dreamLabelsWritten: Number(row.dream_labels_written ?? 0),
|
|
963
2336
|
modelCalls: Number(row.model_calls ?? 0),
|
|
964
2337
|
report: row.report ?? undefined,
|
|
965
2338
|
error: row.error ?? undefined,
|
|
966
2339
|
undoneAt: row.undone_at ? Number(row.undone_at) : undefined,
|
|
967
2340
|
};
|
|
968
2341
|
}
|
|
2342
|
+
function mapDreamTrace(row) {
|
|
2343
|
+
return {
|
|
2344
|
+
id: row.id,
|
|
2345
|
+
turnId: row.turn_id,
|
|
2346
|
+
owner: row.owner,
|
|
2347
|
+
kind: row.kind,
|
|
2348
|
+
site: row.site,
|
|
2349
|
+
pipeline: row.pipeline,
|
|
2350
|
+
sessionId: row.session_id ?? undefined,
|
|
2351
|
+
sessionKind: row.session_kind ?? undefined,
|
|
2352
|
+
assignmentId: row.assignment_id ?? undefined,
|
|
2353
|
+
sleepRunId: row.sleep_run_id ?? undefined,
|
|
2354
|
+
turnIndex: Number(row.turn_index ?? 0),
|
|
2355
|
+
policySet: parseJsonColumn(row.policy_set) ?? {},
|
|
2356
|
+
framed: Number(row.framed ?? 0) === 1,
|
|
2357
|
+
holdout: Number(row.holdout ?? 0) === 1,
|
|
2358
|
+
audit: Number(row.audit ?? 0) === 1,
|
|
2359
|
+
degraded: row.degraded ?? null,
|
|
2360
|
+
startedAt: Number(row.started_at),
|
|
2361
|
+
finishedAt: row.finished_at ? Number(row.finished_at) : undefined,
|
|
2362
|
+
createdAt: Number(row.created_at),
|
|
2363
|
+
};
|
|
2364
|
+
}
|
|
2365
|
+
/**
|
|
2366
|
+
* Reads the `f_`-prefixed columns of the `framesFor` join. `box` and
|
|
2367
|
+
* `payload` are parsed directly rather than through `parseJsonColumn`:
|
|
2368
|
+
* both are NOT NULL columns only this store's own writer fills, so a row
|
|
2369
|
+
* that does not parse is corruption the night should hear about, not a
|
|
2370
|
+
* field that silently reads as absent.
|
|
2371
|
+
*/
|
|
2372
|
+
function mapDreamFrame(row) {
|
|
2373
|
+
return {
|
|
2374
|
+
traceId: row.f_trace_id,
|
|
2375
|
+
slot: row.f_slot,
|
|
2376
|
+
frameV: Number(row.f_frame_v),
|
|
2377
|
+
owner: row.f_owner,
|
|
2378
|
+
sessionId: row.f_session_id ?? undefined,
|
|
2379
|
+
box: JSON.parse(row.f_box),
|
|
2380
|
+
corpusStampId: row.f_corpus_stamp_id,
|
|
2381
|
+
payload: JSON.parse(row.f_payload),
|
|
2382
|
+
bytes: Number(row.f_bytes),
|
|
2383
|
+
createdAt: Number(row.f_created_at),
|
|
2384
|
+
};
|
|
2385
|
+
}
|
|
2386
|
+
function mapDreamLabel(row) {
|
|
2387
|
+
return {
|
|
2388
|
+
turnId: row.turn_id,
|
|
2389
|
+
target: row.target,
|
|
2390
|
+
source: row.source,
|
|
2391
|
+
relevance: Number(row.relevance),
|
|
2392
|
+
scope: row.scope,
|
|
2393
|
+
evidence: row.evidence ?? undefined,
|
|
2394
|
+
deadAt: row.dead_at ? Number(row.dead_at) : undefined,
|
|
2395
|
+
createdAt: Number(row.created_at),
|
|
2396
|
+
// The column arrived with schema 24, so rows an older build wrote carry
|
|
2397
|
+
// NULL here; they belong to the assistant, which is the only owner that
|
|
2398
|
+
// could have written a label before agents had one.
|
|
2399
|
+
owner: row.owner ?? ASSISTANT_MEMORY_OWNER,
|
|
2400
|
+
sessionId: row.session_id ?? undefined,
|
|
2401
|
+
};
|
|
2402
|
+
}
|
|
2403
|
+
/**
|
|
2404
|
+
* `params` and `box` are parsed directly rather than through
|
|
2405
|
+
* `parseJsonColumn`, for the reason `mapDreamFrame` gives: both are NOT NULL
|
|
2406
|
+
* columns only this store's own writer fills, so a row that does not parse
|
|
2407
|
+
* is corruption the night should hear about, not a field that silently
|
|
2408
|
+
* reads as absent.
|
|
2409
|
+
*/
|
|
2410
|
+
function mapPolicyVersion(row) {
|
|
2411
|
+
return {
|
|
2412
|
+
id: row.id,
|
|
2413
|
+
owner: row.owner,
|
|
2414
|
+
slot: row.slot,
|
|
2415
|
+
version: Number(row.version),
|
|
2416
|
+
params: JSON.parse(row.params),
|
|
2417
|
+
box: JSON.parse(row.box),
|
|
2418
|
+
origin: row.origin,
|
|
2419
|
+
parentId: row.parent_id ?? undefined,
|
|
2420
|
+
prevActiveId: row.prev_active_id ?? undefined,
|
|
2421
|
+
sleepRunId: row.sleep_run_id ?? undefined,
|
|
2422
|
+
rationale: row.rationale ?? undefined,
|
|
2423
|
+
replayScore: row.replay_score === null ? undefined : Number(row.replay_score),
|
|
2424
|
+
replayN: row.replay_n === null ? undefined : Number(row.replay_n),
|
|
2425
|
+
baselineScore: row.baseline_score === null ? undefined : Number(row.baseline_score),
|
|
2426
|
+
auditDelta: row.audit_delta === null ? undefined : Number(row.audit_delta),
|
|
2427
|
+
auditCiLow: row.audit_ci_low === null ? undefined : Number(row.audit_ci_low),
|
|
2428
|
+
onlineScore: row.online_score === null ? undefined : Number(row.online_score),
|
|
2429
|
+
promotedAt: row.promoted_at ? Number(row.promoted_at) : undefined,
|
|
2430
|
+
retiredAt: row.retired_at ? Number(row.retired_at) : undefined,
|
|
2431
|
+
createdAt: Number(row.created_at),
|
|
2432
|
+
};
|
|
2433
|
+
}
|
|
2434
|
+
function mapDreamSlotState(row) {
|
|
2435
|
+
return {
|
|
2436
|
+
owner: row.owner,
|
|
2437
|
+
slot: row.slot,
|
|
2438
|
+
frozenAt: row.frozen_at ? Number(row.frozen_at) : undefined,
|
|
2439
|
+
frozenReason: row.frozen_reason ?? undefined,
|
|
2440
|
+
cooldownUntil: row.cooldown_until ? Number(row.cooldown_until) : undefined,
|
|
2441
|
+
lastPromoted: row.last_promoted ? Number(row.last_promoted) : undefined,
|
|
2442
|
+
};
|
|
2443
|
+
}
|
|
2444
|
+
function mapDreamEval(row) {
|
|
2445
|
+
return {
|
|
2446
|
+
id: row.id,
|
|
2447
|
+
sleepRunId: row.sleep_run_id,
|
|
2448
|
+
policyId: row.policy_id,
|
|
2449
|
+
slot: row.slot,
|
|
2450
|
+
traces: Number(row.traces),
|
|
2451
|
+
closed: Number(row.closed),
|
|
2452
|
+
abstained: Number(row.abstained),
|
|
2453
|
+
abstainReasons: JSON.parse(row.abstain_reasons),
|
|
2454
|
+
reachableRate: Number(row.reachable_rate),
|
|
2455
|
+
labelCoverage: Number(row.label_coverage),
|
|
2456
|
+
costOnlyShare: Number(row.cost_only_share),
|
|
2457
|
+
score: Number(row.score),
|
|
2458
|
+
baseline: Number(row.baseline),
|
|
2459
|
+
delta: Number(row.delta),
|
|
2460
|
+
ciLow: Number(row.ci_low),
|
|
2461
|
+
ciHigh: Number(row.ci_high),
|
|
2462
|
+
auditDelta: row.audit_delta === null ? undefined : Number(row.audit_delta),
|
|
2463
|
+
auditCiLow: row.audit_ci_low === null ? undefined : Number(row.audit_ci_low),
|
|
2464
|
+
deltaLive: row.delta_live === null ? undefined : Number(row.delta_live),
|
|
2465
|
+
// Three worlds, not two: NULL means the freshness check was undetermined,
|
|
2466
|
+
// the way `DreamTrace.degraded` distinguishes "did not degrade" from
|
|
2467
|
+
// "not recorded".
|
|
2468
|
+
signAgree: row.sign_agree === null || row.sign_agree === undefined ? null : Number(row.sign_agree) === 1,
|
|
2469
|
+
evalMs: Number(row.eval_ms),
|
|
2470
|
+
traceSetHash: row.trace_set_hash,
|
|
2471
|
+
evidenceDigest: row.evidence_digest ?? undefined,
|
|
2472
|
+
promoted: Number(row.promoted ?? 0) === 1,
|
|
2473
|
+
detail: parseJsonColumn(row.detail),
|
|
2474
|
+
createdAt: Number(row.created_at),
|
|
2475
|
+
};
|
|
2476
|
+
}
|
|
2477
|
+
function mapDreamEpisode(row) {
|
|
2478
|
+
return {
|
|
2479
|
+
id: row.id,
|
|
2480
|
+
owner: row.owner,
|
|
2481
|
+
kind: row.kind,
|
|
2482
|
+
sessionId: row.session_id ?? undefined,
|
|
2483
|
+
slot: row.slot,
|
|
2484
|
+
steps: Number(row.steps),
|
|
2485
|
+
outcome: row.outcome,
|
|
2486
|
+
holdout: Number(row.holdout ?? 0) === 1,
|
|
2487
|
+
audit: Number(row.audit ?? 0) === 1,
|
|
2488
|
+
startedAt: Number(row.started_at),
|
|
2489
|
+
finishedAt: row.finished_at ? Number(row.finished_at) : undefined,
|
|
2490
|
+
createdAt: Number(row.created_at),
|
|
2491
|
+
};
|
|
2492
|
+
}
|
|
969
2493
|
/**
|
|
970
2494
|
* Normalise a name to the key entities are deduplicated by, so "Rookery",
|
|
971
2495
|
* "rookery" and "Rookery-Agent " all land on the same node.
|
|
@@ -979,6 +2503,21 @@ export function entitySlug(name) {
|
|
|
979
2503
|
.replace(/^-+|-+$/g, '')
|
|
980
2504
|
.slice(0, 60);
|
|
981
2505
|
}
|
|
2506
|
+
/**
|
|
2507
|
+
* A JSON column an older build may have written differently, or not at all.
|
|
2508
|
+
* One malformed row must never cost the whole transcript: the field simply
|
|
2509
|
+
* reads as absent, the way `parseTags` already degrades.
|
|
2510
|
+
*/
|
|
2511
|
+
function parseJsonColumn(value) {
|
|
2512
|
+
if (typeof value !== 'string')
|
|
2513
|
+
return undefined;
|
|
2514
|
+
try {
|
|
2515
|
+
return JSON.parse(value);
|
|
2516
|
+
}
|
|
2517
|
+
catch {
|
|
2518
|
+
return undefined;
|
|
2519
|
+
}
|
|
2520
|
+
}
|
|
982
2521
|
function parseTags(value) {
|
|
983
2522
|
if (typeof value !== 'string')
|
|
984
2523
|
return [];
|
|
@@ -996,4 +2535,36 @@ function mergeTags(a, b) {
|
|
|
996
2535
|
function clamp01(value) {
|
|
997
2536
|
return Math.min(1, Math.max(0, value));
|
|
998
2537
|
}
|
|
2538
|
+
/**
|
|
2539
|
+
* When a night starts, taken so that the stamp falls strictly after every row
|
|
2540
|
+
* that already exists.
|
|
2541
|
+
*
|
|
2542
|
+
* `undoSleepRun` tells the rows a run wrote from the rows it merely touched by
|
|
2543
|
+
* comparing `created_at` against this stamp: a memory that carries the run's
|
|
2544
|
+
* id but predates it was revived by the run (see `upsertMemory`), a policy
|
|
2545
|
+
* version likewise re-promoted, and neither may be deleted when the night is
|
|
2546
|
+
* taken back. `Date.now()` moves in whole milliseconds, so a memory written in
|
|
2547
|
+
* the same tick a night starts compares equal and reads as the night's own -
|
|
2548
|
+
* that is an undo deleting a memory that is older than the night it undoes.
|
|
2549
|
+
* So the boundary is taken from the data rather than from the clock: one past
|
|
2550
|
+
* the newest row in the three tables the undo compares. Nothing is waited for,
|
|
2551
|
+
* and everything the run writes from here on still lands on or after it,
|
|
2552
|
+
* because those rows are stamped `Date.now()` and this is never below it.
|
|
2553
|
+
*
|
|
2554
|
+
* ponytail: the ceiling is that the boundary is a timestamp, not an identity.
|
|
2555
|
+
* A row inserted with a `created_at` in the future - a test fixture, a clock
|
|
2556
|
+
* that jumped and came back - pushes the start past rows the run then writes,
|
|
2557
|
+
* and the undo leaves them behind. The upgrade path is to record on the row
|
|
2558
|
+
* which run created it instead of inferring it from time.
|
|
2559
|
+
*/
|
|
2560
|
+
function sleepRunStart(db) {
|
|
2561
|
+
const row = db
|
|
2562
|
+
.prepare(`SELECT MAX(at) AS at FROM (
|
|
2563
|
+
SELECT MAX(created_at) AS at FROM memories
|
|
2564
|
+
UNION ALL SELECT MAX(created_at) FROM policy_versions
|
|
2565
|
+
UNION ALL SELECT MAX(created_at) FROM dream_evals
|
|
2566
|
+
)`)
|
|
2567
|
+
.get();
|
|
2568
|
+
return Math.max(Date.now(), Number(row?.at ?? 0) + 1);
|
|
2569
|
+
}
|
|
999
2570
|
//# sourceMappingURL=store.js.map
|