@otium-team/negotium 0.0.0-stage → 0.23.13
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/LICENSE +202 -0
- package/README.md +329 -2
- package/bin/codex-sdk-window-hide.mjs +40 -0
- package/bin/negotium.mjs +22 -0
- package/dist/agent-helpers.js +23090 -0
- package/dist/agent-helpers.js.map +171 -0
- package/dist/background-bash.js +535 -0
- package/dist/background-bash.js.map +16 -0
- package/dist/browser-runtime.js +2334 -0
- package/dist/browser-runtime.js.map +35 -0
- package/dist/canonical-mcp-bridge.js +13 -0
- package/dist/canonical-mcp-bridge.js.map +9 -0
- package/dist/chunk-22kg3fsw.js +79 -0
- package/dist/chunk-22kg3fsw.js.map +9 -0
- package/dist/chunk-d4j77adx.js +336 -0
- package/dist/chunk-d4j77adx.js.map +13 -0
- package/dist/chunk-mk9x18jn.js +172 -0
- package/dist/chunk-mk9x18jn.js.map +12 -0
- package/dist/chunk-qd0vtfm2.js +3923 -0
- package/dist/chunk-qd0vtfm2.js.map +47 -0
- package/dist/chunk-wf7ny8eq.js +206 -0
- package/dist/chunk-wf7ny8eq.js.map +10 -0
- package/dist/chunk-ww8a4ej4.js +54 -0
- package/dist/chunk-ww8a4ej4.js.map +10 -0
- package/dist/cron.js +1 -0
- package/dist/hosted-agent.js +5982 -0
- package/dist/hosted-agent.js.map +62 -0
- package/dist/main.js +60229 -0
- package/dist/main.js.map +340 -0
- package/dist/mcp-catalog.js +39 -0
- package/dist/mcp-catalog.js.map +10 -0
- package/dist/mcp-factories.js +25767 -0
- package/dist/mcp-factories.js.map +181 -0
- package/dist/mcp-servers.js +50 -0
- package/dist/mcp-servers.js.map +10 -0
- package/dist/media.js +570 -0
- package/dist/media.js.map +15 -0
- package/dist/outbox.js +354 -0
- package/dist/outbox.js.map +15 -0
- package/dist/platform-runtime.js +73 -0
- package/dist/platform-runtime.js.map +12 -0
- package/dist/prompts.js +892 -0
- package/dist/prompts.js.map +15 -0
- package/dist/query-runtime.js +1071 -0
- package/dist/query-runtime.js.map +26 -0
- package/dist/registry.js +335 -0
- package/dist/registry.js.map +14 -0
- package/dist/rollout.js +57 -0
- package/dist/rollout.js.map +10 -0
- package/dist/runtime/cron/background-sessions.ts +119 -0
- package/dist/runtime/cron/context.ts +123 -0
- package/dist/runtime/cron/host.ts +67 -0
- package/dist/runtime/cron/index.ts +95 -0
- package/dist/runtime/cron/mcp-server.ts +556 -0
- package/dist/runtime/cron/module.ts +174 -0
- package/dist/runtime/cron/package.json +6 -0
- package/dist/runtime/cron/schedule.ts +211 -0
- package/dist/runtime/cron/scheduler.ts +444 -0
- package/dist/runtime/cron/scripts.ts +203 -0
- package/dist/runtime/cron/store.ts +1163 -0
- package/dist/runtime/cron/summarize.ts +115 -0
- package/dist/runtime/package.json +6 -0
- package/dist/runtime/scripts/faster-whisper-wrapper.py +87 -0
- package/dist/runtime/src/agents/api-topic-agent-switch.ts +179 -0
- package/dist/runtime/src/agents/archiver.ts +677 -0
- package/dist/runtime/src/agents/auth-check.ts +156 -0
- package/dist/runtime/src/agents/claude-notices.ts +130 -0
- package/dist/runtime/src/agents/claude-provider.ts +941 -0
- package/dist/runtime/src/agents/claude-registry.ts +117 -0
- package/dist/runtime/src/agents/claude-runtime-inspection.ts +43 -0
- package/dist/runtime/src/agents/codex-app-server.ts +138 -0
- package/dist/runtime/src/agents/codex-native-multi-agent.ts +360 -0
- package/dist/runtime/src/agents/codex-provider.ts +1193 -0
- package/dist/runtime/src/agents/codex-registry.ts +116 -0
- package/dist/runtime/src/agents/codex-tier-resolver.ts +74 -0
- package/dist/runtime/src/agents/codex-tree-kill.ts +54 -0
- package/dist/runtime/src/agents/codex-tree-manager.ts +230 -0
- package/dist/runtime/src/agents/codex-vault-hook-bridge.ts +240 -0
- package/dist/runtime/src/agents/codex-vault-hook.mjs +50 -0
- package/dist/runtime/src/agents/codex-windows-wrapper.ts +174 -0
- package/dist/runtime/src/agents/compaction-support.ts +75 -0
- package/dist/runtime/src/agents/compaction-tool-projection.ts +125 -0
- package/dist/runtime/src/agents/contracts.ts +75 -0
- package/dist/runtime/src/agents/deep-map.ts +13 -0
- package/dist/runtime/src/agents/execution-host.ts +118 -0
- package/dist/runtime/src/agents/explicit-agent-switch.ts +106 -0
- package/dist/runtime/src/agents/fixtures/claude-attachments.jsonl +2 -0
- package/dist/runtime/src/agents/fixtures/codex-shell.jsonl +5 -0
- package/dist/runtime/src/agents/fork.ts +100 -0
- package/dist/runtime/src/agents/hosted-agent.ts +78 -0
- package/dist/runtime/src/agents/idle-archiver.ts +225 -0
- package/dist/runtime/src/agents/idle-compact.ts +225 -0
- package/dist/runtime/src/agents/index.ts +225 -0
- package/dist/runtime/src/agents/maestro-provider.ts +246 -0
- package/dist/runtime/src/agents/maestro-registry.ts +189 -0
- package/dist/runtime/src/agents/mcp-tools/ask-user.ts +653 -0
- package/dist/runtime/src/agents/mcp-tools/common.ts +23 -0
- package/dist/runtime/src/agents/mcp-tools/inline-assets.ts +203 -0
- package/dist/runtime/src/agents/mcp-tools/publish-html.ts +183 -0
- package/dist/runtime/src/agents/mcp-tools/request-vault.ts +684 -0
- package/dist/runtime/src/agents/mcp-tools/self-config.ts +353 -0
- package/dist/runtime/src/agents/mcp-tools/spawn-subagent.ts +1349 -0
- package/dist/runtime/src/agents/mcp-tools/visual-compat.ts +18 -0
- package/dist/runtime/src/agents/mcp-tools/visuals.ts +60 -0
- package/dist/runtime/src/agents/memory-archive-policy.ts +54 -0
- package/dist/runtime/src/agents/model-catalog.ts +439 -0
- package/dist/runtime/src/agents/public-helpers.ts +149 -0
- package/dist/runtime/src/agents/registry.ts +35 -0
- package/dist/runtime/src/agents/rollout/claude.ts +336 -0
- package/dist/runtime/src/agents/rollout/codex.ts +910 -0
- package/dist/runtime/src/agents/rollout/index.ts +26 -0
- package/dist/runtime/src/agents/rollout/shared.ts +293 -0
- package/dist/runtime/src/agents/self-config-core.ts +704 -0
- package/dist/runtime/src/agents/task-events.ts +59 -0
- package/dist/runtime/src/agents/tool-format.ts +613 -0
- package/dist/runtime/src/agents/topic-agent-switch.ts +189 -0
- package/dist/runtime/src/agents/topic-cleanup.ts +285 -0
- package/dist/runtime/src/agents/vault-tool-policy.ts +36 -0
- package/dist/runtime/src/application/execute-external-user-turn.ts +23 -0
- package/dist/runtime/src/application/submit-runtime-gateway-turn.ts +484 -0
- package/dist/runtime/src/application/submit-user-message.ts +60 -0
- package/dist/runtime/src/application/switch-topic-effort.ts +48 -0
- package/dist/runtime/src/application/switch-topic-model.ts +79 -0
- package/dist/runtime/src/application/topic-service.ts +190 -0
- package/dist/runtime/src/application/turn-follow-ups.ts +291 -0
- package/dist/runtime/src/application/vault-command.ts +170 -0
- package/dist/runtime/src/bus.ts +409 -0
- package/dist/runtime/src/config-public.ts +2 -0
- package/dist/runtime/src/cron-host.ts +33 -0
- package/dist/runtime/src/cron-mcp-host.ts +5 -0
- package/dist/runtime/src/identifiers.ts +49 -0
- package/dist/runtime/src/index.ts +573 -0
- package/dist/runtime/src/mcp/agent-health-server.ts +8 -0
- package/dist/runtime/src/mcp/canonical-bridge-config.ts +84 -0
- package/dist/runtime/src/mcp/canonical-proxy-server.ts +308 -0
- package/dist/runtime/src/mcp/compaction-log-server.ts +25 -0
- package/dist/runtime/src/mcp/decision-server.ts +21 -0
- package/dist/runtime/src/mcp/dm-ipc.ts +60 -0
- package/dist/runtime/src/mcp/factories/agent-health.ts +394 -0
- package/dist/runtime/src/mcp/factories/compaction-log.ts +135 -0
- package/dist/runtime/src/mcp/factories/decision.ts +186 -0
- package/dist/runtime/src/mcp/factories/index.ts +73 -0
- package/dist/runtime/src/mcp/factories/session-comm.ts +184 -0
- package/dist/runtime/src/mcp/factories/session-history.ts +103 -0
- package/dist/runtime/src/mcp/factories/stdio-protection.ts +24 -0
- package/dist/runtime/src/mcp/factories/system-health.ts +259 -0
- package/dist/runtime/src/mcp/factories/task.ts +185 -0
- package/dist/runtime/src/mcp/factories/token-stats.ts +145 -0
- package/dist/runtime/src/mcp/factories/vault.ts +32 -0
- package/dist/runtime/src/mcp/mcp-helpers.ts +40 -0
- package/dist/runtime/src/mcp/peer-bridge.ts +119 -0
- package/dist/runtime/src/mcp/runtime-spec.ts +473 -0
- package/dist/runtime/src/mcp/session-comm/actor-policy.ts +160 -0
- package/dist/runtime/src/mcp/session-comm/bridge-ipc-config.ts +27 -0
- package/dist/runtime/src/mcp/session-comm/context.ts +113 -0
- package/dist/runtime/src/mcp/session-comm/default-host.ts +723 -0
- package/dist/runtime/src/mcp/session-comm/history-target.ts +89 -0
- package/dist/runtime/src/mcp/session-comm/history-tools.ts +113 -0
- package/dist/runtime/src/mcp/session-comm/hub-remote-session.ts +553 -0
- package/dist/runtime/src/mcp/session-comm/limits.ts +8 -0
- package/dist/runtime/src/mcp/session-comm/peer-forward.ts +251 -0
- package/dist/runtime/src/mcp/session-comm/runtime.ts +128 -0
- package/dist/runtime/src/mcp/session-comm/server.ts +1036 -0
- package/dist/runtime/src/mcp/session-comm/tell-permissions.ts +79 -0
- package/dist/runtime/src/mcp/session-comm/topic-catalog.ts +155 -0
- package/dist/runtime/src/mcp/session-comm/topic-config.ts +137 -0
- package/dist/runtime/src/mcp/session-comm/topics.ts +313 -0
- package/dist/runtime/src/mcp/session-history-limits.ts +36 -0
- package/dist/runtime/src/mcp/session-history-reader.ts +359 -0
- package/dist/runtime/src/mcp/session-history-server.ts +19 -0
- package/dist/runtime/src/mcp/stdio-protect.ts +7 -0
- package/dist/runtime/src/mcp/system-health-server.ts +5 -0
- package/dist/runtime/src/mcp/task-server.ts +17 -0
- package/dist/runtime/src/mcp/token-stats-server.ts +10 -0
- package/dist/runtime/src/mcp/vault-server.ts +12 -0
- package/dist/runtime/src/mcp/wiki-search-index.ts +359 -0
- package/dist/runtime/src/mcp/wiki-server.ts +2386 -0
- package/dist/runtime/src/mcp-runtime-host.ts +81 -0
- package/dist/runtime/src/media/file-events.ts +33 -0
- package/dist/runtime/src/media/text-extractor.ts +334 -0
- package/dist/runtime/src/media/video.ts +92 -0
- package/dist/runtime/src/node-host.ts +211 -0
- package/dist/runtime/src/outbox/coalescing-runner.ts +157 -0
- package/dist/runtime/src/outbox/file-ops.ts +267 -0
- package/dist/runtime/src/outbox/index.ts +26 -0
- package/dist/runtime/src/outbox/utils.ts +74 -0
- package/dist/runtime/src/platform/background-bash/context.ts +9 -0
- package/dist/runtime/src/platform/background-bash/manager.ts +292 -0
- package/dist/runtime/src/platform/background-bash/output-buffer.ts +323 -0
- package/dist/runtime/src/platform/config-helpers.ts +47 -0
- package/dist/runtime/src/platform/config.ts +618 -0
- package/dist/runtime/src/platform/constants.ts +30 -0
- package/dist/runtime/src/platform/debug-users.ts +14 -0
- package/dist/runtime/src/platform/delay.ts +1 -0
- package/dist/runtime/src/platform/error.ts +9 -0
- package/dist/runtime/src/platform/file-utils.ts +35 -0
- package/dist/runtime/src/platform/ipc.ts +55 -0
- package/dist/runtime/src/platform/jsonl.ts +277 -0
- package/dist/runtime/src/platform/lifecycle.ts +176 -0
- package/dist/runtime/src/platform/log-rotation.ts +45 -0
- package/dist/runtime/src/platform/logger.ts +42 -0
- package/dist/runtime/src/platform/maestro-bootstrap-env.ts +3 -0
- package/dist/runtime/src/platform/mcp-catalog-policy.ts +63 -0
- package/dist/runtime/src/platform/mcp-config.ts +1329 -0
- package/dist/runtime/src/platform/memoize-import.ts +26 -0
- package/dist/runtime/src/platform/modules.ts +145 -0
- package/dist/runtime/src/platform/node-plugins.ts +46 -0
- package/dist/runtime/src/platform/paths.ts +62 -0
- package/dist/runtime/src/platform/playwright/browser-processes.ts +300 -0
- package/dist/runtime/src/platform/playwright/capability.ts +5 -0
- package/dist/runtime/src/platform/playwright/headed-launch.ts +61 -0
- package/dist/runtime/src/platform/playwright/manager-utils.ts +128 -0
- package/dist/runtime/src/platform/playwright/manager.ts +1502 -0
- package/dist/runtime/src/platform/playwright/mcp-transport.ts +35 -0
- package/dist/runtime/src/platform/playwright/profile-management.ts +33 -0
- package/dist/runtime/src/platform/playwright/public-runtime.ts +52 -0
- package/dist/runtime/src/platform/playwright/transport-probe.ts +89 -0
- package/dist/runtime/src/platform/playwright/vault-broker.ts +261 -0
- package/dist/runtime/src/platform/public-runtime.ts +18 -0
- package/dist/runtime/src/prompts/agents/wiki-archiver.md +194 -0
- package/dist/runtime/src/prompts/builders.ts +696 -0
- package/dist/runtime/src/prompts/sessions/_shared-tools.md +38 -0
- package/dist/runtime/src/prompts/sessions/channel-system.md +13 -0
- package/dist/runtime/src/prompts/sessions/manager-system.md +34 -0
- package/dist/runtime/src/prompts/sessions/surfaces/cli.md +6 -0
- package/dist/runtime/src/prompts/sessions/surfaces/otium-manager.md +18 -0
- package/dist/runtime/src/prompts/sessions/surfaces/otium.md +6 -0
- package/dist/runtime/src/prompts/sessions/surfaces/telegram.md +5 -0
- package/dist/runtime/src/prompts/sessions/surfaces/terminal.md +6 -0
- package/dist/runtime/src/prompts/sessions/topic-system.md +9 -0
- package/dist/runtime/src/prompts/sessions/visual-design.md +38 -0
- package/dist/runtime/src/query/active-rooms.ts +514 -0
- package/dist/runtime/src/query/index.ts +23 -0
- package/dist/runtime/src/query/public-runtime.ts +28 -0
- package/dist/runtime/src/query/room-query-registry.ts +217 -0
- package/dist/runtime/src/query/session-inbox-cleanup.ts +45 -0
- package/dist/runtime/src/query/session-inbox-path.ts +42 -0
- package/dist/runtime/src/query/state.ts +116 -0
- package/dist/runtime/src/query/types.ts +8 -0
- package/dist/runtime/src/runtime/actor-topic-reach.ts +123 -0
- package/dist/runtime/src/runtime/actor-topic-scope.ts +255 -0
- package/dist/runtime/src/runtime/ask-callbacks.ts +217 -0
- package/dist/runtime/src/runtime/attachments.ts +149 -0
- package/dist/runtime/src/runtime/background-session-policy.ts +1 -0
- package/dist/runtime/src/runtime/background-sessions.ts +288 -0
- package/dist/runtime/src/runtime/bashrs-completions.ts +350 -0
- package/dist/runtime/src/runtime/channel-context.ts +115 -0
- package/dist/runtime/src/runtime/context-warning.ts +131 -0
- package/dist/runtime/src/runtime/cron-sessions.ts +35 -0
- package/dist/runtime/src/runtime/delivery-ack.ts +112 -0
- package/dist/runtime/src/runtime/errors.ts +70 -0
- package/dist/runtime/src/runtime/event-heartbeat.ts +77 -0
- package/dist/runtime/src/runtime/file-hooks.ts +81 -0
- package/dist/runtime/src/runtime/footer.ts +23 -0
- package/dist/runtime/src/runtime/gateway-capabilities.ts +22 -0
- package/dist/runtime/src/runtime/inbox.ts +1307 -0
- package/dist/runtime/src/runtime/playwright-turn-abort.ts +59 -0
- package/dist/runtime/src/runtime/public-helpers.ts +78 -0
- package/dist/runtime/src/runtime/remote-session-grant.ts +221 -0
- package/dist/runtime/src/runtime/remote-session-inbox.ts +943 -0
- package/dist/runtime/src/runtime/remote-session-reply-outbox.ts +168 -0
- package/dist/runtime/src/runtime/task-format.ts +18 -0
- package/dist/runtime/src/runtime/tasks.ts +53 -0
- package/dist/runtime/src/runtime/thread-context.ts +123 -0
- package/dist/runtime/src/runtime/thread-read.ts +67 -0
- package/dist/runtime/src/runtime/topic-config.ts +29 -0
- package/dist/runtime/src/runtime/turn-event-stream.ts +1051 -0
- package/dist/runtime/src/runtime/turn-runner.ts +2311 -0
- package/dist/runtime/src/runtime/turn-session.ts +116 -0
- package/dist/runtime/src/runtime/usage-alert.ts +51 -0
- package/dist/runtime/src/runtime/user-turn-envelope.ts +94 -0
- package/dist/runtime/src/runtime/visual-html.ts +175 -0
- package/dist/runtime/src/runtime/visual-store.ts +480 -0
- package/dist/runtime/src/runtime/visuals.ts +209 -0
- package/dist/runtime/src/runtime-gateway.ts +1045 -0
- package/dist/runtime/src/security/sanitize.ts +27 -0
- package/dist/runtime/src/security/sensitive-path.ts +41 -0
- package/dist/runtime/src/storage/activity-log.ts +167 -0
- package/dist/runtime/src/storage/api-messages.ts +766 -0
- package/dist/runtime/src/storage/api-topic-brief.ts +134 -0
- package/dist/runtime/src/storage/api-topic-config.ts +197 -0
- package/dist/runtime/src/storage/api-topics.ts +1647 -0
- package/dist/runtime/src/storage/app-settings.ts +50 -0
- package/dist/runtime/src/storage/ask-user-gates.ts +359 -0
- package/dist/runtime/src/storage/browser-profiles.ts +186 -0
- package/dist/runtime/src/storage/conversation-migration.ts +180 -0
- package/dist/runtime/src/storage/conversations.ts +377 -0
- package/dist/runtime/src/storage/decisions.ts +231 -0
- package/dist/runtime/src/storage/forum/agent-settings.ts +20 -0
- package/dist/runtime/src/storage/forum/index.ts +4 -0
- package/dist/runtime/src/storage/forum/repository.ts +283 -0
- package/dist/runtime/src/storage/forum/schema.ts +314 -0
- package/dist/runtime/src/storage/forum-db.ts +4 -0
- package/dist/runtime/src/storage/remote-session.ts +1028 -0
- package/dist/runtime/src/storage/runtime-events.ts +209 -0
- package/dist/runtime/src/storage/runtime-follow-ups.ts +212 -0
- package/dist/runtime/src/storage/runtime-gateway-submissions.ts +132 -0
- package/dist/runtime/src/storage/runtime-leases.ts +190 -0
- package/dist/runtime/src/storage/runtime-process-leases.ts +288 -0
- package/dist/runtime/src/storage/runtime-topic-state.ts +181 -0
- package/dist/runtime/src/storage/runtime-turn-requests.ts +846 -0
- package/dist/runtime/src/storage/self-schedules.ts +306 -0
- package/dist/runtime/src/storage/session-asks.ts +468 -0
- package/dist/runtime/src/storage/session-inbox-signal.ts +76 -0
- package/dist/runtime/src/storage/session-inbox.ts +161 -0
- package/dist/runtime/src/storage/sqlite.ts +154 -0
- package/dist/runtime/src/storage/storage-contract.ts +54 -0
- package/dist/runtime/src/storage/storage-host.ts +336 -0
- package/dist/runtime/src/storage/storage-public-host.ts +16 -0
- package/dist/runtime/src/storage/storage-public.ts +66 -0
- package/dist/runtime/src/storage/tasks.ts +172 -0
- package/dist/runtime/src/storage/token-stats.ts +432 -0
- package/dist/runtime/src/storage/topic-archive-state.ts +226 -0
- package/dist/runtime/src/storage/topic-archive.ts +169 -0
- package/dist/runtime/src/storage/topic-host-mcp-grants.ts +54 -0
- package/dist/runtime/src/storage/topic-link-records.ts +1085 -0
- package/dist/runtime/src/storage/topic-settings.ts +67 -0
- package/dist/runtime/src/storage/topic-tool-capabilities.ts +89 -0
- package/dist/runtime/src/storage/topic-transcript.ts +98 -0
- package/dist/runtime/src/storage/vault-crypto-core.ts +65 -0
- package/dist/runtime/src/storage/vault-crypto.ts +31 -0
- package/dist/runtime/src/storage/vault-public.ts +27 -0
- package/dist/runtime/src/storage/vault-request-gates.ts +359 -0
- package/dist/runtime/src/storage/vault.ts +388 -0
- package/dist/runtime/src/storage/wiki-summary-names.ts +52 -0
- package/dist/runtime/src/storage/wiki.ts +90 -0
- package/dist/runtime/src/topics/claim-abort.ts +190 -0
- package/dist/runtime/src/topics/create.ts +192 -0
- package/dist/runtime/src/topics/derive.ts +600 -0
- package/dist/runtime/src/topics/lifecycle.ts +425 -0
- package/dist/runtime/src/topics/links.ts +7 -0
- package/dist/runtime/src/topics/personal-general.ts +91 -0
- package/dist/runtime/src/topics/session.ts +1041 -0
- package/dist/runtime/src/topics/update.ts +287 -0
- package/dist/runtime/src/types/api.ts +591 -0
- package/dist/runtime/src/types.ts +418 -0
- package/dist/runtime/src/version.ts +1 -0
- package/dist/runtime/tsconfig.json +13 -0
- package/dist/runtime-gateway.js +514 -0
- package/dist/runtime-gateway.js.map +10 -0
- package/dist/runtime-helpers.js +1792 -0
- package/dist/runtime-helpers.js.map +40 -0
- package/dist/sqlite.js +66 -0
- package/dist/sqlite.js.map +10 -0
- package/dist/storage.js +5223 -0
- package/dist/storage.js.map +47 -0
- package/dist/types/apps/negotium/src/mcp-servers.d.ts +20 -0
- package/dist/types/packages/core/src/agents/api-topic-agent-switch.d.ts +38 -0
- package/dist/types/packages/core/src/agents/archiver.d.ts +87 -0
- package/dist/types/packages/core/src/agents/auth-check.d.ts +19 -0
- package/dist/types/packages/core/src/agents/claude-notices.d.ts +15 -0
- package/dist/types/packages/core/src/agents/claude-provider.d.ts +25 -0
- package/dist/types/packages/core/src/agents/claude-registry.d.ts +3 -0
- package/dist/types/packages/core/src/agents/claude-runtime-inspection.d.ts +9 -0
- package/dist/types/packages/core/src/agents/codex-app-server.d.ts +13 -0
- package/dist/types/packages/core/src/agents/codex-native-multi-agent.d.ts +20 -0
- package/dist/types/packages/core/src/agents/codex-provider.d.ts +64 -0
- package/dist/types/packages/core/src/agents/codex-registry.d.ts +3 -0
- package/dist/types/packages/core/src/agents/codex-tier-resolver.d.ts +10 -0
- package/dist/types/packages/core/src/agents/codex-tree-kill.d.ts +13 -0
- package/dist/types/packages/core/src/agents/codex-tree-manager.d.ts +28 -0
- package/dist/types/packages/core/src/agents/codex-vault-hook-bridge.d.ts +28 -0
- package/dist/types/packages/core/src/agents/codex-windows-wrapper.d.ts +30 -0
- package/dist/types/packages/core/src/agents/compaction-support.d.ts +5 -0
- package/dist/types/packages/core/src/agents/compaction-tool-projection.d.ts +9 -0
- package/dist/types/packages/core/src/agents/contracts.d.ts +68 -0
- package/dist/types/packages/core/src/agents/deep-map.d.ts +2 -0
- package/dist/types/packages/core/src/agents/execution-host.d.ts +33 -0
- package/dist/types/packages/core/src/agents/explicit-agent-switch.d.ts +26 -0
- package/dist/types/packages/core/src/agents/fork.d.ts +50 -0
- package/dist/types/packages/core/src/agents/hosted-agent.d.ts +15 -0
- package/dist/types/packages/core/src/agents/idle-archiver.d.ts +35 -0
- package/dist/types/packages/core/src/agents/idle-compact.d.ts +37 -0
- package/dist/types/packages/core/src/agents/index.d.ts +8 -0
- package/dist/types/packages/core/src/agents/maestro-provider.d.ts +75 -0
- package/dist/types/packages/core/src/agents/maestro-registry.d.ts +3 -0
- package/dist/types/packages/core/src/agents/mcp-tools/ask-user.d.ts +147 -0
- package/dist/types/packages/core/src/agents/mcp-tools/common.d.ts +14 -0
- package/dist/types/packages/core/src/agents/mcp-tools/inline-assets.d.ts +24 -0
- package/dist/types/packages/core/src/agents/mcp-tools/publish-html.d.ts +18 -0
- package/dist/types/packages/core/src/agents/mcp-tools/request-vault.d.ts +124 -0
- package/dist/types/packages/core/src/agents/mcp-tools/self-config.d.ts +45 -0
- package/dist/types/packages/core/src/agents/mcp-tools/spawn-subagent.d.ts +148 -0
- package/dist/types/packages/core/src/agents/mcp-tools/visual-compat.d.ts +55 -0
- package/dist/types/packages/core/src/agents/mcp-tools/visuals.d.ts +70 -0
- package/dist/types/packages/core/src/agents/memory-archive-policy.d.ts +24 -0
- package/dist/types/packages/core/src/agents/model-catalog.d.ts +132 -0
- package/dist/types/packages/core/src/agents/public-helpers.d.ts +17 -0
- package/dist/types/packages/core/src/agents/registry.d.ts +5 -0
- package/dist/types/packages/core/src/agents/rollout/claude.d.ts +77 -0
- package/dist/types/packages/core/src/agents/rollout/codex.d.ts +119 -0
- package/dist/types/packages/core/src/agents/rollout/index.d.ts +6 -0
- package/dist/types/packages/core/src/agents/rollout/shared.d.ts +56 -0
- package/dist/types/packages/core/src/agents/self-config-core.d.ts +199 -0
- package/dist/types/packages/core/src/agents/task-events.d.ts +19 -0
- package/dist/types/packages/core/src/agents/tool-format.d.ts +25 -0
- package/dist/types/packages/core/src/agents/topic-cleanup.d.ts +83 -0
- package/dist/types/packages/core/src/agents/vault-tool-policy.d.ts +2 -0
- package/dist/types/packages/core/src/bus.d.ts +141 -0
- package/dist/types/packages/core/src/identifiers.d.ts +27 -0
- package/dist/types/packages/core/src/mcp/canonical-bridge-config.d.ts +21 -0
- package/dist/types/packages/core/src/mcp/factories/agent-health.d.ts +5 -0
- package/dist/types/packages/core/src/mcp/factories/compaction-log.d.ts +8 -0
- package/dist/types/packages/core/src/mcp/factories/decision.d.ts +18 -0
- package/dist/types/packages/core/src/mcp/factories/index.d.ts +13 -0
- package/dist/types/packages/core/src/mcp/factories/session-comm.d.ts +38 -0
- package/dist/types/packages/core/src/mcp/factories/session-history.d.ts +11 -0
- package/dist/types/packages/core/src/mcp/factories/stdio-protection.d.ts +10 -0
- package/dist/types/packages/core/src/mcp/factories/system-health.d.ts +37 -0
- package/dist/types/packages/core/src/mcp/factories/task.d.ts +13 -0
- package/dist/types/packages/core/src/mcp/factories/token-stats.d.ts +20 -0
- package/dist/types/packages/core/src/mcp/factories/vault.d.ts +9 -0
- package/dist/types/packages/core/src/mcp/mcp-helpers.d.ts +26 -0
- package/dist/types/packages/core/src/mcp/peer-bridge.d.ts +92 -0
- package/dist/types/packages/core/src/mcp/runtime-spec.d.ts +147 -0
- package/dist/types/packages/core/src/mcp/session-comm/actor-policy.d.ts +120 -0
- package/dist/types/packages/core/src/mcp/session-comm/bridge-ipc-config.d.ts +6 -0
- package/dist/types/packages/core/src/mcp/session-comm/context.d.ts +44 -0
- package/dist/types/packages/core/src/mcp/session-comm/history-tools.d.ts +31 -0
- package/dist/types/packages/core/src/mcp/session-comm/hub-remote-session.d.ts +149 -0
- package/dist/types/packages/core/src/mcp/session-comm/limits.d.ts +8 -0
- package/dist/types/packages/core/src/mcp/session-comm/peer-forward.d.ts +85 -0
- package/dist/types/packages/core/src/mcp/session-comm/tell-permissions.d.ts +29 -0
- package/dist/types/packages/core/src/mcp/session-comm/topic-catalog.d.ts +59 -0
- package/dist/types/packages/core/src/mcp/session-history-limits.d.ts +20 -0
- package/dist/types/packages/core/src/mcp/session-history-reader.d.ts +35 -0
- package/dist/types/packages/core/src/mcp/wiki-search-index.d.ts +59 -0
- package/dist/types/packages/core/src/mcp/wiki-server.d.ts +53 -0
- package/dist/types/packages/core/src/media/file-events.d.ts +14 -0
- package/dist/types/packages/core/src/media/text-extractor.d.ts +34 -0
- package/dist/types/packages/core/src/outbox/coalescing-runner.d.ts +68 -0
- package/dist/types/packages/core/src/outbox/file-ops.d.ts +79 -0
- package/dist/types/packages/core/src/outbox/index.d.ts +3 -0
- package/dist/types/packages/core/src/outbox/utils.d.ts +16 -0
- package/dist/types/packages/core/src/platform/background-bash/context.d.ts +1 -0
- package/dist/types/packages/core/src/platform/background-bash/manager.d.ts +34 -0
- package/dist/types/packages/core/src/platform/config-helpers.d.ts +20 -0
- package/dist/types/packages/core/src/platform/config.d.ts +178 -0
- package/dist/types/packages/core/src/platform/constants.d.ts +20 -0
- package/dist/types/packages/core/src/platform/delay.d.ts +1 -0
- package/dist/types/packages/core/src/platform/error.d.ts +6 -0
- package/dist/types/packages/core/src/platform/file-utils.d.ts +16 -0
- package/dist/types/packages/core/src/platform/ipc.d.ts +32 -0
- package/dist/types/packages/core/src/platform/jsonl.d.ts +46 -0
- package/dist/types/packages/core/src/platform/lifecycle.d.ts +40 -0
- package/dist/types/packages/core/src/platform/logger.d.ts +20 -0
- package/dist/types/packages/core/src/platform/maestro-bootstrap-env.d.ts +0 -0
- package/dist/types/packages/core/src/platform/mcp-catalog-policy.d.ts +73 -0
- package/dist/types/packages/core/src/platform/mcp-config.d.ts +286 -0
- package/dist/types/packages/core/src/platform/memoize-import.d.ts +15 -0
- package/dist/types/packages/core/src/platform/paths.d.ts +18 -0
- package/dist/types/packages/core/src/platform/playwright/browser-processes.d.ts +60 -0
- package/dist/types/packages/core/src/platform/playwright/capability.d.ts +1 -0
- package/dist/types/packages/core/src/platform/playwright/headed-launch.d.ts +13 -0
- package/dist/types/packages/core/src/platform/playwright/manager-utils.d.ts +34 -0
- package/dist/types/packages/core/src/platform/playwright/manager.d.ts +194 -0
- package/dist/types/packages/core/src/platform/playwright/mcp-transport.d.ts +4 -0
- package/dist/types/packages/core/src/platform/playwright/profile-management.d.ts +8 -0
- package/dist/types/packages/core/src/platform/playwright/public-runtime.d.ts +6 -0
- package/dist/types/packages/core/src/platform/playwright/transport-probe.d.ts +13 -0
- package/dist/types/packages/core/src/platform/playwright/vault-broker.d.ts +6 -0
- package/dist/types/packages/core/src/platform/public-runtime.d.ts +3 -0
- package/dist/types/packages/core/src/prompts/builders.d.ts +78 -0
- package/dist/types/packages/core/src/query/active-rooms.d.ts +240 -0
- package/dist/types/packages/core/src/query/public-runtime.d.ts +4 -0
- package/dist/types/packages/core/src/query/room-query-registry.d.ts +71 -0
- package/dist/types/packages/core/src/query/session-inbox-cleanup.d.ts +5 -0
- package/dist/types/packages/core/src/query/session-inbox-path.d.ts +8 -0
- package/dist/types/packages/core/src/query/state.d.ts +25 -0
- package/dist/types/packages/core/src/query/types.d.ts +6 -0
- package/dist/types/packages/core/src/runtime/actor-topic-reach.d.ts +63 -0
- package/dist/types/packages/core/src/runtime/actor-topic-scope.d.ts +127 -0
- package/dist/types/packages/core/src/runtime/ask-callbacks.d.ts +53 -0
- package/dist/types/packages/core/src/runtime/attachments.d.ts +36 -0
- package/dist/types/packages/core/src/runtime/background-session-policy.d.ts +1 -0
- package/dist/types/packages/core/src/runtime/background-sessions.d.ts +27 -0
- package/dist/types/packages/core/src/runtime/bashrs-completions.d.ts +50 -0
- package/dist/types/packages/core/src/runtime/channel-context.d.ts +13 -0
- package/dist/types/packages/core/src/runtime/context-warning.d.ts +46 -0
- package/dist/types/packages/core/src/runtime/cron-sessions.d.ts +9 -0
- package/dist/types/packages/core/src/runtime/errors.d.ts +6 -0
- package/dist/types/packages/core/src/runtime/event-heartbeat.d.ts +17 -0
- package/dist/types/packages/core/src/runtime/file-hooks.d.ts +38 -0
- package/dist/types/packages/core/src/runtime/playwright-turn-abort.d.ts +12 -0
- package/dist/types/packages/core/src/runtime/public-helpers.d.ts +17 -0
- package/dist/types/packages/core/src/runtime/remote-session-grant.d.ts +91 -0
- package/dist/types/packages/core/src/runtime/remote-session-inbox.d.ts +206 -0
- package/dist/types/packages/core/src/runtime/remote-session-reply-outbox.d.ts +37 -0
- package/dist/types/packages/core/src/runtime/task-format.d.ts +4 -0
- package/dist/types/packages/core/src/runtime/tasks.d.ts +3 -0
- package/dist/types/packages/core/src/runtime/thread-context.d.ts +62 -0
- package/dist/types/packages/core/src/runtime/topic-config.d.ts +24 -0
- package/dist/types/packages/core/src/runtime/turn-event-stream.d.ts +47 -0
- package/dist/types/packages/core/src/runtime/turn-runner.d.ts +284 -0
- package/dist/types/packages/core/src/runtime/turn-session.d.ts +49 -0
- package/dist/types/packages/core/src/runtime/usage-alert.d.ts +11 -0
- package/dist/types/packages/core/src/runtime/user-turn-envelope.d.ts +37 -0
- package/dist/types/packages/core/src/runtime/visual-html.d.ts +13 -0
- package/dist/types/packages/core/src/runtime/visual-store.d.ts +71 -0
- package/dist/types/packages/core/src/runtime/visuals.d.ts +33 -0
- package/dist/types/packages/core/src/runtime-gateway.d.ts +282 -0
- package/dist/types/packages/core/src/security/sanitize.d.ts +16 -0
- package/dist/types/packages/core/src/security/sensitive-path.d.ts +1 -0
- package/dist/types/packages/core/src/storage/activity-log.d.ts +25 -0
- package/dist/types/packages/core/src/storage/api-messages.d.ts +156 -0
- package/dist/types/packages/core/src/storage/api-topic-brief.d.ts +39 -0
- package/dist/types/packages/core/src/storage/api-topic-config.d.ts +23 -0
- package/dist/types/packages/core/src/storage/api-topics.d.ts +274 -0
- package/dist/types/packages/core/src/storage/app-settings.d.ts +4 -0
- package/dist/types/packages/core/src/storage/ask-user-gates.d.ts +65 -0
- package/dist/types/packages/core/src/storage/browser-profiles.d.ts +31 -0
- package/dist/types/packages/core/src/storage/conversations.d.ts +149 -0
- package/dist/types/packages/core/src/storage/decisions.d.ts +45 -0
- package/dist/types/packages/core/src/storage/forum/agent-settings.d.ts +3 -0
- package/dist/types/packages/core/src/storage/forum/index.d.ts +4 -0
- package/dist/types/packages/core/src/storage/forum/repository.d.ts +42 -0
- package/dist/types/packages/core/src/storage/forum/schema.d.ts +38 -0
- package/dist/types/packages/core/src/storage/forum-db.d.ts +2 -0
- package/dist/types/packages/core/src/storage/remote-session.d.ts +318 -0
- package/dist/types/packages/core/src/storage/runtime-events.d.ts +33 -0
- package/dist/types/packages/core/src/storage/runtime-leases.d.ts +27 -0
- package/dist/types/packages/core/src/storage/runtime-process-leases.d.ts +47 -0
- package/dist/types/packages/core/src/storage/runtime-topic-state.d.ts +39 -0
- package/dist/types/packages/core/src/storage/runtime-turn-requests.d.ts +163 -0
- package/dist/types/packages/core/src/storage/self-schedules.d.ts +54 -0
- package/dist/types/packages/core/src/storage/session-asks.d.ts +78 -0
- package/dist/types/packages/core/src/storage/session-inbox-signal.d.ts +35 -0
- package/dist/types/packages/core/src/storage/session-inbox.d.ts +36 -0
- package/dist/types/packages/core/src/storage/sqlite.d.ts +20 -0
- package/dist/types/packages/core/src/storage/storage-contract.d.ts +46 -0
- package/dist/types/packages/core/src/storage/storage-host.d.ts +41 -0
- package/dist/types/packages/core/src/storage/storage-public-host.d.ts +7 -0
- package/dist/types/packages/core/src/storage/storage-public.d.ts +45 -0
- package/dist/types/packages/core/src/storage/tasks.d.ts +49 -0
- package/dist/types/packages/core/src/storage/token-stats.d.ts +69 -0
- package/dist/types/packages/core/src/storage/topic-archive-state.d.ts +33 -0
- package/dist/types/packages/core/src/storage/topic-archive.d.ts +42 -0
- package/dist/types/packages/core/src/storage/topic-host-mcp-grants.d.ts +5 -0
- package/dist/types/packages/core/src/storage/topic-link-records.d.ts +281 -0
- package/dist/types/packages/core/src/storage/topic-settings.d.ts +19 -0
- package/dist/types/packages/core/src/storage/topic-tool-capabilities.d.ts +37 -0
- package/dist/types/packages/core/src/storage/topic-transcript.d.ts +38 -0
- package/dist/types/packages/core/src/storage/vault-crypto-core.d.ts +6 -0
- package/dist/types/packages/core/src/storage/vault-crypto.d.ts +12 -0
- package/dist/types/packages/core/src/storage/vault-public.d.ts +3 -0
- package/dist/types/packages/core/src/storage/vault-request-gates.d.ts +69 -0
- package/dist/types/packages/core/src/storage/vault.d.ts +49 -0
- package/dist/types/packages/core/src/storage/wiki-summary-names.d.ts +13 -0
- package/dist/types/packages/core/src/storage/wiki.d.ts +15 -0
- package/dist/types/packages/core/src/topics/derive.d.ts +83 -0
- package/dist/types/packages/core/src/topics/lifecycle.d.ts +75 -0
- package/dist/types/packages/core/src/topics/links.d.ts +2 -0
- package/dist/types/packages/core/src/topics/personal-general.d.ts +15 -0
- package/dist/types/packages/core/src/topics/session.d.ts +70 -0
- package/dist/types/packages/core/src/types/api.d.ts +551 -0
- package/dist/types/packages/core/src/types.d.ts +405 -0
- package/dist/types/packages/core/src/version.d.ts +1 -0
- package/dist/types/packages/module-cron/src/background-sessions.d.ts +2 -0
- package/dist/types/packages/module-cron/src/context.d.ts +15 -0
- package/dist/types/packages/module-cron/src/host.d.ts +23 -0
- package/dist/types/packages/module-cron/src/index.d.ts +14 -0
- package/dist/types/packages/module-cron/src/module.d.ts +13 -0
- package/dist/types/packages/module-cron/src/schedule.d.ts +23 -0
- package/dist/types/packages/module-cron/src/scheduler.d.ts +46 -0
- package/dist/types/packages/module-cron/src/scripts.d.ts +29 -0
- package/dist/types/packages/module-cron/src/store.d.ts +152 -0
- package/dist/types/packages/module-cron/src/summarize.d.ts +4 -0
- package/dist/vault.js +848 -0
- package/dist/vault.js.map +18 -0
- package/install-bash-rs.mjs +90 -0
- package/install-browser-rs.mjs +83 -0
- package/package.json +171 -4
|
@@ -0,0 +1,1085 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Durable evidence for the hub↔node topic link (topic-link design v2 §4.2,
|
|
3
|
+
* §4.5, PR7). Two tables, both written by the node and only ever read by a
|
|
4
|
+
* host through the authenticated Runtime Gateway:
|
|
5
|
+
*
|
|
6
|
+
* - `api_topic_create_claims` — one row per host `requestId` on a room-creating
|
|
7
|
+
* request (`POST /topics`, `POST /topics/:id/derive`). Written inside the same
|
|
8
|
+
* SQLite transaction that inserts the topic, so a response lost after commit
|
|
9
|
+
* can always be replayed by id instead of being guessed at (title/parent
|
|
10
|
+
* heuristics are forbidden by the design).
|
|
11
|
+
* - `api_topic_tombstones` — one row per topic that left the host-visible
|
|
12
|
+
* surface, stamped with THIS node's identity. Written by SQLite triggers on
|
|
13
|
+
* `api_topics`, so every delete path (gateway, MCP, CLI, account deletion,
|
|
14
|
+
* future ones) records it in the very statement that removes the row; there
|
|
15
|
+
* is no code path that can delete a topic and forget the tombstone.
|
|
16
|
+
*
|
|
17
|
+
* `api_node_identity` holds the node id the triggers stamp. The node process
|
|
18
|
+
* records its `NODE_ID` there at start (and the delete cascade re-asserts it)
|
|
19
|
+
* via {@link recordTopicLinkNodeIdentity}: a database copied to another install
|
|
20
|
+
* keeps the old id on its old tombstones, so the existence API — which only
|
|
21
|
+
* answers `gone` for a tombstone written under the identity it is answering
|
|
22
|
+
* as — can never turn a copied store's history into a delete on the new node.
|
|
23
|
+
* Until an identity is recorded, tombstones carry NULL and never count as
|
|
24
|
+
* `gone` (fail-safe). This module deliberately does not import
|
|
25
|
+
* `#platform/config`: that would create state paths merely by importing the
|
|
26
|
+
* public storage facade.
|
|
27
|
+
*/
|
|
28
|
+
|
|
29
|
+
import { createHash } from "node:crypto";
|
|
30
|
+
import { GENERAL_TOPIC_ID } from "#platform/constants";
|
|
31
|
+
// Side effect: registers `api_messages`, which the message fence trigger
|
|
32
|
+
// guards (and orders it before this schema).
|
|
33
|
+
import "#storage/api-messages";
|
|
34
|
+
import { db } from "#storage/forum-db";
|
|
35
|
+
// Side effect: registers `runtime_topic_state`, which the message fence
|
|
36
|
+
// trigger reads (and orders it before this schema).
|
|
37
|
+
import "#storage/runtime-topic-state";
|
|
38
|
+
import { registerStorageSchemaInitializer } from "#storage/storage-host";
|
|
39
|
+
|
|
40
|
+
export type TopicCreateClaimOp = "create" | "derive" | "abort";
|
|
41
|
+
export type TopicCreateClaimState = "committed" | "aborted";
|
|
42
|
+
export type TopicTombstoneReason = "deleted" | "unshared";
|
|
43
|
+
|
|
44
|
+
export interface TopicCreateClaim {
|
|
45
|
+
principalKey: string;
|
|
46
|
+
requestId: string;
|
|
47
|
+
op: TopicCreateClaimOp;
|
|
48
|
+
payloadHash: string;
|
|
49
|
+
topicId: string | null;
|
|
50
|
+
state: TopicCreateClaimState;
|
|
51
|
+
nodeId: string | null;
|
|
52
|
+
/** Highest `api_messages.rowid` of the topic when the claim committed (seeded history). */
|
|
53
|
+
seedMaxMessageRowid: number;
|
|
54
|
+
/** Derive only: the source topic the claim was made for (null on create / legacy rows). */
|
|
55
|
+
sourceTopicId: string | null;
|
|
56
|
+
/** Message count of the topic when the claim committed (null on legacy rows). */
|
|
57
|
+
seedMessageCount: number | null;
|
|
58
|
+
/** sha256 of the sorted message ids at claim time (null on legacy rows). */
|
|
59
|
+
seedMessageIdsHash: string | null;
|
|
60
|
+
createdAt: string;
|
|
61
|
+
updatedAt: string;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export interface TopicTombstone {
|
|
65
|
+
seq: number;
|
|
66
|
+
topicId: string;
|
|
67
|
+
nodeId: string | null;
|
|
68
|
+
reason: TopicTombstoneReason;
|
|
69
|
+
surface: string | null;
|
|
70
|
+
surfaceScope: string | null;
|
|
71
|
+
deletedAt: string;
|
|
72
|
+
/**
|
|
73
|
+
* Present on feed entries that come from `api_topic_scope_moves`: the room
|
|
74
|
+
* was moved OUT of `surfaceScope` by an admin scope repair (reported to the
|
|
75
|
+
* old scope as `unshared`). Not a row of `api_topic_tombstones`.
|
|
76
|
+
*/
|
|
77
|
+
scopeMoved?: true;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
interface ClaimRow {
|
|
81
|
+
principal_key: string;
|
|
82
|
+
request_id: string;
|
|
83
|
+
op: string;
|
|
84
|
+
payload_hash: string;
|
|
85
|
+
topic_id: string | null;
|
|
86
|
+
state: string;
|
|
87
|
+
node_id: string | null;
|
|
88
|
+
seed_max_message_rowid: number | bigint | null;
|
|
89
|
+
source_topic_id?: string | null;
|
|
90
|
+
seed_message_count?: number | bigint | null;
|
|
91
|
+
seed_message_ids_hash?: string | null;
|
|
92
|
+
created_at: string;
|
|
93
|
+
updated_at: string;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
interface TombstoneRow {
|
|
97
|
+
seq: number | bigint;
|
|
98
|
+
topic_id: string;
|
|
99
|
+
node_id: string | null;
|
|
100
|
+
reason: string;
|
|
101
|
+
surface: string | null;
|
|
102
|
+
surface_scope: string | null;
|
|
103
|
+
deleted_at: string;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** Claims are kept at least this long (design v2 §4.2: ≥ 30 days). */
|
|
107
|
+
export const TOPIC_CREATE_CLAIM_RETENTION_MS = 30 * 24 * 60 * 60_000;
|
|
108
|
+
|
|
109
|
+
const NODE_IDENTITY_SQL = "(SELECT node_id FROM api_node_identity WHERE singleton = 1)";
|
|
110
|
+
const NOW_SQL = "strftime('%Y-%m-%dT%H:%M:%fZ','now')";
|
|
111
|
+
const TOMBSTONE_SEQ_SQL = "(SELECT seq FROM api_topic_tombstone_seq WHERE singleton = 1)";
|
|
112
|
+
// Advances the never-decreasing tombstone sequence. Runs as the first
|
|
113
|
+
// statement of every tombstone-writing trigger, so the new row's seq is read
|
|
114
|
+
// back from the counter within the same statement/transaction.
|
|
115
|
+
const BUMP_TOMBSTONE_SEQ_SQL =
|
|
116
|
+
"UPDATE api_topic_tombstone_seq SET seq = seq + 1 WHERE singleton = 1";
|
|
117
|
+
const NEW_EPOCH_SQL = "lower(hex(randomblob(16)))";
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* Owner-id prefix of the runtime maintenance fence a claim abort holds while
|
|
121
|
+
* it deletes the claimed topic. While such a fence is live, the
|
|
122
|
+
* `api_messages_claim_abort_fence` trigger refuses every message insert into
|
|
123
|
+
* that topic (any writer, any process), so nothing can land between the
|
|
124
|
+
* abort's "no new messages" check and the delete.
|
|
125
|
+
*/
|
|
126
|
+
export const TOPIC_CLAIM_ABORT_OWNER_PREFIX = "topic-link-abort:";
|
|
127
|
+
/** The message the fence trigger raises; matched by ingress to answer 409. */
|
|
128
|
+
export const TOPIC_CLAIM_ABORT_FENCE_ERROR = "topic_claim_abort_in_progress";
|
|
129
|
+
// Same staleness rule as `runtime-topic-state` (TOPIC_MAINTENANCE_STALE_MS):
|
|
130
|
+
// a crashed abort never blocks a room for longer than a stale fence.
|
|
131
|
+
const CLAIM_ABORT_FENCE_STALE_MS = 30_000;
|
|
132
|
+
const NOW_MS_SQL = "CAST((julianday('now') - 2440587.5) * 86400000 AS INTEGER)";
|
|
133
|
+
const CLAIM_ABORT_FENCE_PREDICATE = `maintenance = 1
|
|
134
|
+
AND maintenance_owner LIKE '${TOPIC_CLAIM_ABORT_OWNER_PREFIX}%'
|
|
135
|
+
AND heartbeat_at IS NOT NULL
|
|
136
|
+
AND heartbeat_at >= ${NOW_MS_SQL} - ${CLAIM_ABORT_FENCE_STALE_MS}`;
|
|
137
|
+
|
|
138
|
+
type SchemaDatabase = {
|
|
139
|
+
exec(sql: string): unknown;
|
|
140
|
+
transaction<T>(fn: () => T): (() => T) & { immediate?: () => T };
|
|
141
|
+
query(sql: string): { all(...params: never[]): unknown[] };
|
|
142
|
+
};
|
|
143
|
+
|
|
144
|
+
const SCHEMA_TABLES = [
|
|
145
|
+
"api_node_identity",
|
|
146
|
+
"api_topic_create_claims",
|
|
147
|
+
"api_topic_tombstones",
|
|
148
|
+
"api_topic_tombstone_seq",
|
|
149
|
+
"api_topic_scope_repair_grants",
|
|
150
|
+
"api_topic_scope_moves",
|
|
151
|
+
];
|
|
152
|
+
const SCHEMA_INDEXES = [
|
|
153
|
+
"idx_api_topic_create_claims_topic",
|
|
154
|
+
"idx_api_topic_create_claims_created",
|
|
155
|
+
"idx_api_topic_create_claims_principal",
|
|
156
|
+
"idx_api_topic_create_claims_settled_at",
|
|
157
|
+
"idx_api_topic_scope_moves_seq",
|
|
158
|
+
];
|
|
159
|
+
/** Columns added to `api_topic_create_claims` after its first release. */
|
|
160
|
+
const CLAIM_ADDED_COLUMNS: Record<string, string> = {
|
|
161
|
+
source_topic_id: "TEXT",
|
|
162
|
+
seed_message_count: "INTEGER",
|
|
163
|
+
seed_message_ids_hash: "TEXT",
|
|
164
|
+
settled_at: "TEXT",
|
|
165
|
+
};
|
|
166
|
+
const SCHEMA_INDEXES_TOMBSTONES = ["idx_api_topic_tombstones_seq"];
|
|
167
|
+
/** Trigger → a marker its current SQL must contain (older builds lack it). */
|
|
168
|
+
const SCHEMA_TRIGGERS: Record<string, string> = {
|
|
169
|
+
api_topics_tombstone_on_delete: "api_topic_tombstone_seq",
|
|
170
|
+
api_topics_tombstone_on_unshare: "api_topic_tombstone_seq",
|
|
171
|
+
api_topics_tombstone_on_reshare: "surface_scope IS NEW.surface_scope",
|
|
172
|
+
api_topics_tombstone_on_insert: "api_topic_tombstones",
|
|
173
|
+
api_messages_claim_abort_fence: TOPIC_CLAIM_ABORT_OWNER_PREFIX,
|
|
174
|
+
api_topics_otium_scope_immutable: "api_topic_scope_repair_grants",
|
|
175
|
+
};
|
|
176
|
+
|
|
177
|
+
/** The message the scope-immutability trigger raises. */
|
|
178
|
+
export const OTIUM_TOPIC_SCOPE_IMMUTABLE_ERROR = "otium_topic_scope_immutable";
|
|
179
|
+
|
|
180
|
+
/**
|
|
181
|
+
* Read-only: whether the schema (and identity) is already current. Every
|
|
182
|
+
* process start runs the initializer, so the common path must not write — a
|
|
183
|
+
* write here would take the database lock on every boot and can fail with
|
|
184
|
+
* SQLITE_BUSY while other processes start concurrently.
|
|
185
|
+
*/
|
|
186
|
+
function topicLinkSchemaIsCurrent(database: SchemaDatabase, nodeId?: string): boolean {
|
|
187
|
+
const objects = new Map(
|
|
188
|
+
(
|
|
189
|
+
database
|
|
190
|
+
.query("SELECT name, sql FROM sqlite_master WHERE type IN ('table','index','trigger')")
|
|
191
|
+
.all() as Array<{ name: string; sql: string | null }>
|
|
192
|
+
).map((row) => [row.name, row.sql ?? ""]),
|
|
193
|
+
);
|
|
194
|
+
for (const name of [...SCHEMA_TABLES, ...SCHEMA_INDEXES, ...SCHEMA_INDEXES_TOMBSTONES]) {
|
|
195
|
+
if (!objects.has(name)) return false;
|
|
196
|
+
}
|
|
197
|
+
for (const [name, marker] of Object.entries(SCHEMA_TRIGGERS)) {
|
|
198
|
+
if (!objects.get(name)?.includes(marker)) return false;
|
|
199
|
+
}
|
|
200
|
+
if (!columnNames(database, "api_node_identity").has("epoch_id")) return false;
|
|
201
|
+
const claimColumns = columnNames(database, "api_topic_create_claims");
|
|
202
|
+
for (const column of Object.keys(CLAIM_ADDED_COLUMNS)) {
|
|
203
|
+
if (!claimColumns.has(column)) return false;
|
|
204
|
+
}
|
|
205
|
+
const identity = database
|
|
206
|
+
.query("SELECT node_id, epoch_id FROM api_node_identity WHERE singleton = 1")
|
|
207
|
+
.all() as Array<{ node_id: string; epoch_id: string | null }>;
|
|
208
|
+
if (identity.some((row) => row.epoch_id === null)) return false;
|
|
209
|
+
if (nodeId && identity[0]?.node_id !== nodeId) return false;
|
|
210
|
+
const counter = database
|
|
211
|
+
.query(
|
|
212
|
+
`SELECT (SELECT seq FROM api_topic_tombstone_seq WHERE singleton = 1) AS counter,
|
|
213
|
+
MAX((SELECT COALESCE(MAX(seq), 0) FROM api_topic_tombstones),
|
|
214
|
+
(SELECT COALESCE(MAX(seq), 0) FROM api_topic_scope_moves)) AS max_seq`,
|
|
215
|
+
)
|
|
216
|
+
.all() as Array<{ counter: number | bigint | null; max_seq: number | bigint }>;
|
|
217
|
+
const row = counter[0];
|
|
218
|
+
return row?.counter !== null && row?.counter !== undefined && row.counter >= row.max_seq;
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
function columnNames(database: SchemaDatabase, table: string): Set<string> {
|
|
222
|
+
const rows = database.query(`PRAGMA table_info(${table})`).all() as Array<{ name: string }>;
|
|
223
|
+
return new Set(rows.map((row) => row.name));
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/**
|
|
227
|
+
* Idempotent, and all-or-nothing: every statement is `IF NOT EXISTS` / an
|
|
228
|
+
* upsert / a drop-and-recreate of a trigger, and the whole set runs in one
|
|
229
|
+
* transaction so a crash half-way never leaves triggers without the table
|
|
230
|
+
* they write to.
|
|
231
|
+
*/
|
|
232
|
+
export function initializeTopicLinkRecordsSchema(database: SchemaDatabase, nodeId?: string): void {
|
|
233
|
+
if (topicLinkSchemaIsCurrent(database, nodeId)) return;
|
|
234
|
+
const migrate = database.transaction(() => {
|
|
235
|
+
database.exec(`
|
|
236
|
+
CREATE TABLE IF NOT EXISTS api_node_identity (
|
|
237
|
+
singleton INTEGER PRIMARY KEY CHECK (singleton = 1),
|
|
238
|
+
node_id TEXT NOT NULL,
|
|
239
|
+
epoch_id TEXT,
|
|
240
|
+
updated_at TEXT NOT NULL
|
|
241
|
+
)
|
|
242
|
+
`);
|
|
243
|
+
// PR7 fix: a random id minted when this store first records an identity.
|
|
244
|
+
// Survives NODE_ID changes; a wiped/recreated store gets a new one.
|
|
245
|
+
if (!columnNames(database, "api_node_identity").has("epoch_id")) {
|
|
246
|
+
database.exec("ALTER TABLE api_node_identity ADD COLUMN epoch_id TEXT");
|
|
247
|
+
}
|
|
248
|
+
database.exec(
|
|
249
|
+
`UPDATE api_node_identity SET epoch_id = ${NEW_EPOCH_SQL} WHERE epoch_id IS NULL`,
|
|
250
|
+
);
|
|
251
|
+
database.exec(`
|
|
252
|
+
CREATE TABLE IF NOT EXISTS api_topic_create_claims (
|
|
253
|
+
principal_key TEXT NOT NULL,
|
|
254
|
+
request_id TEXT NOT NULL,
|
|
255
|
+
op TEXT NOT NULL CHECK (op IN ('create','derive','abort')),
|
|
256
|
+
payload_hash TEXT NOT NULL,
|
|
257
|
+
topic_id TEXT,
|
|
258
|
+
state TEXT NOT NULL CHECK (state IN ('committed','aborted')),
|
|
259
|
+
node_id TEXT,
|
|
260
|
+
seed_max_message_rowid INTEGER NOT NULL DEFAULT 0,
|
|
261
|
+
created_at TEXT NOT NULL,
|
|
262
|
+
updated_at TEXT NOT NULL,
|
|
263
|
+
source_topic_id TEXT,
|
|
264
|
+
seed_message_count INTEGER,
|
|
265
|
+
seed_message_ids_hash TEXT,
|
|
266
|
+
settled_at TEXT,
|
|
267
|
+
PRIMARY KEY (principal_key, request_id)
|
|
268
|
+
)
|
|
269
|
+
`);
|
|
270
|
+
// Review fixes (additive): the derive source a claim was made for, and the
|
|
271
|
+
// exact message set the created topic was seeded with.
|
|
272
|
+
const claimColumns = columnNames(database, "api_topic_create_claims");
|
|
273
|
+
for (const [column, type] of Object.entries(CLAIM_ADDED_COLUMNS)) {
|
|
274
|
+
if (!claimColumns.has(column)) {
|
|
275
|
+
database.exec(`ALTER TABLE api_topic_create_claims ADD COLUMN ${column} ${type}`);
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
database.exec(
|
|
279
|
+
`CREATE INDEX IF NOT EXISTS idx_api_topic_create_claims_principal
|
|
280
|
+
ON api_topic_create_claims(principal_key, state, topic_id)`,
|
|
281
|
+
);
|
|
282
|
+
// Retention anchor of a settled (aborted) claim is its settlement time.
|
|
283
|
+
database.exec(
|
|
284
|
+
`CREATE INDEX IF NOT EXISTS idx_api_topic_create_claims_settled_at
|
|
285
|
+
ON api_topic_create_claims(state, settled_at)`,
|
|
286
|
+
);
|
|
287
|
+
// Scope repair (review fix 6): the one sanctioned way to change an otium
|
|
288
|
+
// topic's surface_scope. A grant row exists only inside the repair's own
|
|
289
|
+
// transaction (inserted and deleted before commit), so no other
|
|
290
|
+
// connection ever observes it.
|
|
291
|
+
database.exec(`
|
|
292
|
+
CREATE TABLE IF NOT EXISTS api_topic_scope_repair_grants (
|
|
293
|
+
topic_id TEXT PRIMARY KEY
|
|
294
|
+
)
|
|
295
|
+
`);
|
|
296
|
+
// Scope move history + audit (one row per admin repair). Its seq comes
|
|
297
|
+
// from the tombstone counter, so moves merge into the tombstone feed in
|
|
298
|
+
// order: a hub bound to the OLD scope sees the move as `unshared`.
|
|
299
|
+
database.exec(`
|
|
300
|
+
CREATE TABLE IF NOT EXISTS api_topic_scope_moves (
|
|
301
|
+
seq INTEGER PRIMARY KEY,
|
|
302
|
+
topic_id TEXT NOT NULL,
|
|
303
|
+
node_id TEXT,
|
|
304
|
+
from_scope TEXT,
|
|
305
|
+
to_scope TEXT NOT NULL,
|
|
306
|
+
actor TEXT NOT NULL,
|
|
307
|
+
reason TEXT NOT NULL,
|
|
308
|
+
claims_left INTEGER NOT NULL,
|
|
309
|
+
moved_at TEXT NOT NULL
|
|
310
|
+
)
|
|
311
|
+
`);
|
|
312
|
+
database.exec(
|
|
313
|
+
"CREATE INDEX IF NOT EXISTS idx_api_topic_scope_moves_seq ON api_topic_scope_moves(topic_id, seq)",
|
|
314
|
+
);
|
|
315
|
+
database.exec(
|
|
316
|
+
"CREATE INDEX IF NOT EXISTS idx_api_topic_create_claims_topic ON api_topic_create_claims(topic_id)",
|
|
317
|
+
);
|
|
318
|
+
database.exec(
|
|
319
|
+
"CREATE INDEX IF NOT EXISTS idx_api_topic_create_claims_created ON api_topic_create_claims(created_at)",
|
|
320
|
+
);
|
|
321
|
+
database.exec(`
|
|
322
|
+
CREATE TABLE IF NOT EXISTS api_topic_tombstones (
|
|
323
|
+
topic_id TEXT PRIMARY KEY,
|
|
324
|
+
seq INTEGER NOT NULL,
|
|
325
|
+
node_id TEXT,
|
|
326
|
+
reason TEXT NOT NULL CHECK (reason IN ('deleted','unshared')),
|
|
327
|
+
surface TEXT,
|
|
328
|
+
surface_scope TEXT,
|
|
329
|
+
deleted_at TEXT NOT NULL
|
|
330
|
+
)
|
|
331
|
+
`);
|
|
332
|
+
database.exec(
|
|
333
|
+
"CREATE INDEX IF NOT EXISTS idx_api_topic_tombstones_seq ON api_topic_tombstones(seq)",
|
|
334
|
+
);
|
|
335
|
+
// Never-decreasing tombstone sequence (PR7 fix). `api_topic_tombstones` is
|
|
336
|
+
// a current-state table whose rows are deleted on reshare/reinsert, so
|
|
337
|
+
// MAX(seq)+1 could hand out a seq a cursor already passed. Seeded from the
|
|
338
|
+
// table on every init, and never lowered.
|
|
339
|
+
database.exec(`
|
|
340
|
+
CREATE TABLE IF NOT EXISTS api_topic_tombstone_seq (
|
|
341
|
+
singleton INTEGER PRIMARY KEY CHECK (singleton = 1),
|
|
342
|
+
seq INTEGER NOT NULL
|
|
343
|
+
)
|
|
344
|
+
`);
|
|
345
|
+
database.exec(`
|
|
346
|
+
INSERT INTO api_topic_tombstone_seq (singleton, seq)
|
|
347
|
+
VALUES (1, (SELECT MAX(
|
|
348
|
+
(SELECT COALESCE(MAX(seq), 0) FROM api_topic_tombstones),
|
|
349
|
+
(SELECT COALESCE(MAX(seq), 0) FROM api_topic_scope_moves))))
|
|
350
|
+
ON CONFLICT(singleton) DO UPDATE SET seq = MAX(api_topic_tombstone_seq.seq, excluded.seq)
|
|
351
|
+
`);
|
|
352
|
+
// Recreated on every init so a store migrated by an earlier build (whose
|
|
353
|
+
// triggers computed MAX(seq)+1) gets the counter-based versions.
|
|
354
|
+
for (const name of [
|
|
355
|
+
"api_topics_tombstone_on_delete",
|
|
356
|
+
"api_topics_tombstone_on_unshare",
|
|
357
|
+
"api_topics_tombstone_on_reshare",
|
|
358
|
+
"api_topics_tombstone_on_insert",
|
|
359
|
+
"api_messages_claim_abort_fence",
|
|
360
|
+
"api_topics_otium_scope_immutable",
|
|
361
|
+
]) {
|
|
362
|
+
database.exec(`DROP TRIGGER IF EXISTS ${name}`);
|
|
363
|
+
}
|
|
364
|
+
// Hard delete, from any writer. `DROP TABLE` (the legacy schema rebuild)
|
|
365
|
+
// does not fire row triggers, so a migration never fabricates tombstones.
|
|
366
|
+
database.exec(`
|
|
367
|
+
CREATE TRIGGER api_topics_tombstone_on_delete
|
|
368
|
+
AFTER DELETE ON api_topics
|
|
369
|
+
BEGIN
|
|
370
|
+
${BUMP_TOMBSTONE_SEQ_SQL};
|
|
371
|
+
INSERT OR REPLACE INTO api_topic_tombstones
|
|
372
|
+
(topic_id, seq, node_id, reason, surface, surface_scope, deleted_at)
|
|
373
|
+
VALUES
|
|
374
|
+
(OLD.id, ${TOMBSTONE_SEQ_SQL}, ${NODE_IDENTITY_SQL}, 'deleted',
|
|
375
|
+
OLD.surface, OLD.surface_scope, ${NOW_SQL});
|
|
376
|
+
END
|
|
377
|
+
`);
|
|
378
|
+
// Left the Otium surface (moved to another surface or hidden). Evidence of
|
|
379
|
+
// a withdrawal, never of a deletion: the existence API still answers
|
|
380
|
+
// `present` for such a topic.
|
|
381
|
+
database.exec(`
|
|
382
|
+
CREATE TRIGGER api_topics_tombstone_on_unshare
|
|
383
|
+
AFTER UPDATE OF surface, visibility ON api_topics
|
|
384
|
+
WHEN OLD.surface = 'otium' AND COALESCE(OLD.visibility, 'visible') != 'hidden'
|
|
385
|
+
AND (NEW.surface IS NOT 'otium' OR NEW.visibility = 'hidden')
|
|
386
|
+
BEGIN
|
|
387
|
+
${BUMP_TOMBSTONE_SEQ_SQL};
|
|
388
|
+
INSERT OR REPLACE INTO api_topic_tombstones
|
|
389
|
+
(topic_id, seq, node_id, reason, surface, surface_scope, deleted_at)
|
|
390
|
+
VALUES
|
|
391
|
+
(OLD.id, ${TOMBSTONE_SEQ_SQL}, ${NODE_IDENTITY_SQL}, 'unshared',
|
|
392
|
+
OLD.surface, OLD.surface_scope, ${NOW_SQL});
|
|
393
|
+
END
|
|
394
|
+
`);
|
|
395
|
+
database.exec(`
|
|
396
|
+
CREATE TRIGGER api_topics_tombstone_on_reshare
|
|
397
|
+
AFTER UPDATE OF surface, visibility ON api_topics
|
|
398
|
+
WHEN NEW.surface = 'otium' AND COALESCE(NEW.visibility, 'visible') != 'hidden'
|
|
399
|
+
BEGIN
|
|
400
|
+
-- Only the withdrawal from the scope the room is back in is undone; an
|
|
401
|
+
-- unshare from another workspace stays that workspace's evidence.
|
|
402
|
+
DELETE FROM api_topic_tombstones
|
|
403
|
+
WHERE topic_id = NEW.id AND reason = 'unshared' AND surface_scope IS NEW.surface_scope;
|
|
404
|
+
END
|
|
405
|
+
`);
|
|
406
|
+
// An otium room's workspace is fixed (review fix 6): a claim, a tombstone
|
|
407
|
+
// and the host's mapping all bind to it, and one topic_id-keyed tombstone
|
|
408
|
+
// cannot express several past scopes. Only the audited scope repair
|
|
409
|
+
// (`adminRepairOtiumTopicScope`) may change it, through a grant row that exists
|
|
410
|
+
// only inside its own transaction. Leaving the otium surface is allowed
|
|
411
|
+
// (that is an unshare, tombstoned with the old scope).
|
|
412
|
+
database.exec(`
|
|
413
|
+
CREATE TRIGGER api_topics_otium_scope_immutable
|
|
414
|
+
BEFORE UPDATE OF surface, surface_scope ON api_topics
|
|
415
|
+
WHEN NEW.surface = 'otium'
|
|
416
|
+
AND OLD.surface_scope IS NOT NEW.surface_scope
|
|
417
|
+
AND NOT EXISTS (SELECT 1 FROM api_topic_scope_repair_grants WHERE topic_id = OLD.id)
|
|
418
|
+
BEGIN
|
|
419
|
+
SELECT RAISE(ABORT, '${OTIUM_TOPIC_SCOPE_IMMUTABLE_ERROR}');
|
|
420
|
+
END
|
|
421
|
+
`);
|
|
422
|
+
// A row that exists again (restored or re-inserted id) is not gone.
|
|
423
|
+
database.exec(`
|
|
424
|
+
CREATE TRIGGER api_topics_tombstone_on_insert
|
|
425
|
+
AFTER INSERT ON api_topics
|
|
426
|
+
BEGIN
|
|
427
|
+
DELETE FROM api_topic_tombstones WHERE topic_id = NEW.id;
|
|
428
|
+
END
|
|
429
|
+
`);
|
|
430
|
+
// A topic a claim abort is deleting accepts no message (PR7 fix): see
|
|
431
|
+
// TOPIC_CLAIM_ABORT_OWNER_PREFIX. Checked by SQLite on every insert path,
|
|
432
|
+
// atomically with the insert itself.
|
|
433
|
+
database.exec(`
|
|
434
|
+
CREATE TRIGGER api_messages_claim_abort_fence
|
|
435
|
+
BEFORE INSERT ON api_messages
|
|
436
|
+
WHEN EXISTS (SELECT 1 FROM runtime_topic_state
|
|
437
|
+
WHERE topic_id = NEW.topic_id AND ${CLAIM_ABORT_FENCE_PREDICATE})
|
|
438
|
+
BEGIN
|
|
439
|
+
SELECT RAISE(ABORT, '${TOPIC_CLAIM_ABORT_FENCE_ERROR}');
|
|
440
|
+
END
|
|
441
|
+
`);
|
|
442
|
+
if (nodeId) {
|
|
443
|
+
database.exec(
|
|
444
|
+
`INSERT INTO api_node_identity (singleton, node_id, epoch_id, updated_at)
|
|
445
|
+
VALUES (1, '${nodeId.replaceAll("'", "''")}', ${NEW_EPOCH_SQL}, ${NOW_SQL})
|
|
446
|
+
ON CONFLICT(singleton) DO UPDATE SET node_id = excluded.node_id, updated_at = excluded.updated_at
|
|
447
|
+
WHERE api_node_identity.node_id IS NOT excluded.node_id`,
|
|
448
|
+
);
|
|
449
|
+
}
|
|
450
|
+
});
|
|
451
|
+
// BEGIN IMMEDIATE when available: a migrating process waits on the busy
|
|
452
|
+
// timeout for another one instead of failing its read→write upgrade.
|
|
453
|
+
if (migrate.immediate) migrate.immediate();
|
|
454
|
+
else migrate();
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
// After api_topics (20), api_messages (30) and runtime_topic_state (32): the
|
|
458
|
+
// triggers name their columns, so the tables must already have their shape.
|
|
459
|
+
registerStorageSchemaInitializer((database) => initializeTopicLinkRecordsSchema(database), 45);
|
|
460
|
+
|
|
461
|
+
// ── canonical payload hash ────────────────────────────────────────────────
|
|
462
|
+
|
|
463
|
+
function canonicalJson(value: unknown): string {
|
|
464
|
+
if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`;
|
|
465
|
+
if (value && typeof value === "object") {
|
|
466
|
+
const entries = Object.entries(value as Record<string, unknown>)
|
|
467
|
+
.filter(([, entry]) => entry !== undefined)
|
|
468
|
+
.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
|
|
469
|
+
return `{${entries.map(([key, entry]) => `${JSON.stringify(key)}:${canonicalJson(entry)}`).join(",")}}`;
|
|
470
|
+
}
|
|
471
|
+
return JSON.stringify(value ?? null);
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
/**
|
|
475
|
+
* sha256 (hex) of the canonical JSON of a room-creating request body without
|
|
476
|
+
* the saga's own `requestId`/`payloadHash` — byte-for-byte the hub's
|
|
477
|
+
* `linkPayloadHash` (otium `link/link-intents.ts`): keys sorted at every depth
|
|
478
|
+
* by UTF-16 code unit, compact separators, `undefined` members dropped.
|
|
479
|
+
*
|
|
480
|
+
* For derive the caller passes `{ sourceTopicId: <path id>, ...body }` (the
|
|
481
|
+
* same body forked from two parents must not hash equal).
|
|
482
|
+
*/
|
|
483
|
+
export function topicLinkPayloadHash(body: Record<string, unknown>): string {
|
|
484
|
+
const { requestId: _requestId, payloadHash: _payloadHash, ...payload } = body;
|
|
485
|
+
return createHash("sha256").update(canonicalJson(payload)).digest("hex");
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
// ── node identity ─────────────────────────────────────────────────────────
|
|
489
|
+
|
|
490
|
+
/** Record the identity new tombstones and claims are stamped with (no-op when unchanged). */
|
|
491
|
+
export function recordTopicLinkNodeIdentity(nodeId: string): void {
|
|
492
|
+
const id = nodeId.trim();
|
|
493
|
+
if (!id) return;
|
|
494
|
+
db.query(
|
|
495
|
+
`INSERT INTO api_node_identity (singleton, node_id, epoch_id, updated_at)
|
|
496
|
+
VALUES (1, ?, ${NEW_EPOCH_SQL}, ${NOW_SQL})
|
|
497
|
+
ON CONFLICT(singleton) DO UPDATE SET node_id = excluded.node_id, updated_at = excluded.updated_at
|
|
498
|
+
WHERE api_node_identity.node_id IS NOT excluded.node_id`,
|
|
499
|
+
).run(id);
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
/**
|
|
503
|
+
* Random id minted when this store first recorded an identity (`dbEpoch` on
|
|
504
|
+
* the wire). A wiped/recreated store answering under the same `NODE_ID` has a
|
|
505
|
+
* different one; a restore of a backup of the SAME store does not (residual
|
|
506
|
+
* risk, see the contract). Null until an identity is recorded.
|
|
507
|
+
*/
|
|
508
|
+
export function topicLinkDbEpoch(): string | null {
|
|
509
|
+
return (
|
|
510
|
+
db
|
|
511
|
+
.query<{ epoch_id: string | null }, []>(
|
|
512
|
+
"SELECT epoch_id FROM api_node_identity WHERE singleton = 1",
|
|
513
|
+
)
|
|
514
|
+
.get()?.epoch_id ?? null
|
|
515
|
+
);
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
/**
|
|
519
|
+
* The highest tombstone seq ever handed out (never decreases, also counts
|
|
520
|
+
* rows later removed by a reshare/reinsert). A hub whose recorded cursor is
|
|
521
|
+
* above this value is talking to a rolled-back store.
|
|
522
|
+
*/
|
|
523
|
+
export function topicTombstoneHighWater(): number {
|
|
524
|
+
const row = db
|
|
525
|
+
.query<{ seq: number | bigint }, []>(
|
|
526
|
+
"SELECT seq FROM api_topic_tombstone_seq WHERE singleton = 1",
|
|
527
|
+
)
|
|
528
|
+
.get();
|
|
529
|
+
return Number(row?.seq ?? 0);
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
/** The identity new tombstones and claims are stamped with. */
|
|
533
|
+
export function topicLinkNodeIdentity(): string | null {
|
|
534
|
+
return (
|
|
535
|
+
db
|
|
536
|
+
.query<{ node_id: string }, []>("SELECT node_id FROM api_node_identity WHERE singleton = 1")
|
|
537
|
+
.get()?.node_id ?? null
|
|
538
|
+
);
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
// ── create claims ─────────────────────────────────────────────────────────
|
|
542
|
+
|
|
543
|
+
function toClaim(row: ClaimRow): TopicCreateClaim {
|
|
544
|
+
return {
|
|
545
|
+
principalKey: row.principal_key,
|
|
546
|
+
requestId: row.request_id,
|
|
547
|
+
op: row.op as TopicCreateClaimOp,
|
|
548
|
+
payloadHash: row.payload_hash,
|
|
549
|
+
topicId: row.topic_id,
|
|
550
|
+
state: row.state as TopicCreateClaimState,
|
|
551
|
+
nodeId: row.node_id,
|
|
552
|
+
seedMaxMessageRowid: Number(row.seed_max_message_rowid ?? 0),
|
|
553
|
+
sourceTopicId: row.source_topic_id ?? null,
|
|
554
|
+
seedMessageCount:
|
|
555
|
+
row.seed_message_count === null || row.seed_message_count === undefined
|
|
556
|
+
? null
|
|
557
|
+
: Number(row.seed_message_count),
|
|
558
|
+
seedMessageIdsHash: row.seed_message_ids_hash ?? null,
|
|
559
|
+
createdAt: row.created_at,
|
|
560
|
+
updatedAt: row.updated_at,
|
|
561
|
+
};
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
export function getTopicCreateClaim(
|
|
565
|
+
principalKey: string,
|
|
566
|
+
requestId: string,
|
|
567
|
+
): TopicCreateClaim | null {
|
|
568
|
+
const row = db
|
|
569
|
+
.query<ClaimRow, [string, string]>(
|
|
570
|
+
"SELECT * FROM api_topic_create_claims WHERE principal_key = ? AND request_id = ?",
|
|
571
|
+
)
|
|
572
|
+
.get(principalKey, requestId);
|
|
573
|
+
return row ? toClaim(row) : null;
|
|
574
|
+
}
|
|
575
|
+
|
|
576
|
+
/**
|
|
577
|
+
* Committed claims of one principal for exactly these topics — for
|
|
578
|
+
* `hostCreate` on topic DTOs. Bounded by the ids asked for (index
|
|
579
|
+
* `(principal_key, state, topic_id)`), never the principal's whole history.
|
|
580
|
+
*/
|
|
581
|
+
export function committedClaimsByTopic(
|
|
582
|
+
principalKey: string,
|
|
583
|
+
topicIds: readonly string[],
|
|
584
|
+
): Map<string, TopicCreateClaim> {
|
|
585
|
+
const byTopic = new Map<string, TopicCreateClaim>();
|
|
586
|
+
const unique = [...new Set(topicIds)];
|
|
587
|
+
for (let start = 0; start < unique.length; start += 500) {
|
|
588
|
+
const chunk = unique.slice(start, start + 500);
|
|
589
|
+
const rows = db
|
|
590
|
+
.query<ClaimRow, string[]>(
|
|
591
|
+
`SELECT * FROM api_topic_create_claims
|
|
592
|
+
WHERE principal_key = ? AND state = 'committed'
|
|
593
|
+
AND topic_id IN (${chunk.map(() => "?").join(",")})`,
|
|
594
|
+
)
|
|
595
|
+
.all(principalKey, ...chunk);
|
|
596
|
+
for (const row of rows) if (row.topic_id) byTopic.set(row.topic_id, toClaim(row));
|
|
597
|
+
}
|
|
598
|
+
return byTopic;
|
|
599
|
+
}
|
|
600
|
+
|
|
601
|
+
function maxMessageRowid(topicId: string): number {
|
|
602
|
+
const row = db
|
|
603
|
+
.query<{ max_rowid: number | bigint | null }, [string]>(
|
|
604
|
+
"SELECT MAX(rowid) AS max_rowid FROM api_messages WHERE topic_id = ?",
|
|
605
|
+
)
|
|
606
|
+
.get(topicId);
|
|
607
|
+
return Number(row?.max_rowid ?? 0);
|
|
608
|
+
}
|
|
609
|
+
|
|
610
|
+
/** Count and sha256 of the sorted message ids of a topic: its exact message set. */
|
|
611
|
+
function messageSetOf(topicId: string): { count: number; hash: string } {
|
|
612
|
+
const ids = db
|
|
613
|
+
.query<{ id: string }, [string]>("SELECT id FROM api_messages WHERE topic_id = ? ORDER BY id")
|
|
614
|
+
.all(topicId)
|
|
615
|
+
.map((row) => row.id);
|
|
616
|
+
return { count: ids.length, hash: createHash("sha256").update(ids.join("\n")).digest("hex") };
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
/**
|
|
620
|
+
* Record a committed claim. MUST be called inside the transaction that inserts
|
|
621
|
+
* the topic row (the `withinCreateTransaction` hook of `registerTopic` /
|
|
622
|
+
* `createDerivedTopic`): a plain INSERT, so a concurrent second request with
|
|
623
|
+
* the same key fails the primary key and rolls its own topic back.
|
|
624
|
+
*/
|
|
625
|
+
export function insertCommittedTopicCreateClaim(input: {
|
|
626
|
+
principalKey: string;
|
|
627
|
+
requestId: string;
|
|
628
|
+
op: "create" | "derive";
|
|
629
|
+
payloadHash: string;
|
|
630
|
+
topicId: string;
|
|
631
|
+
/** Derive: the path source topic the claim is bound to. */
|
|
632
|
+
sourceTopicId?: string;
|
|
633
|
+
}): TopicCreateClaim {
|
|
634
|
+
const now = new Date().toISOString();
|
|
635
|
+
const seed = maxMessageRowid(input.topicId);
|
|
636
|
+
const seeded = messageSetOf(input.topicId);
|
|
637
|
+
db.query(
|
|
638
|
+
`INSERT INTO api_topic_create_claims
|
|
639
|
+
(principal_key, request_id, op, payload_hash, topic_id, state, node_id,
|
|
640
|
+
seed_max_message_rowid, created_at, updated_at,
|
|
641
|
+
source_topic_id, seed_message_count, seed_message_ids_hash)
|
|
642
|
+
VALUES (?, ?, ?, ?, ?, 'committed', ${NODE_IDENTITY_SQL}, ?, ?, ?, ?, ?, ?)`,
|
|
643
|
+
).run(
|
|
644
|
+
input.principalKey,
|
|
645
|
+
input.requestId,
|
|
646
|
+
input.op,
|
|
647
|
+
input.payloadHash,
|
|
648
|
+
input.topicId,
|
|
649
|
+
seed,
|
|
650
|
+
now,
|
|
651
|
+
now,
|
|
652
|
+
input.sourceTopicId ?? null,
|
|
653
|
+
seeded.count,
|
|
654
|
+
seeded.hash,
|
|
655
|
+
);
|
|
656
|
+
const claim = getTopicCreateClaim(input.principalKey, input.requestId);
|
|
657
|
+
if (!claim) throw new Error("topic create claim was not recorded");
|
|
658
|
+
return claim;
|
|
659
|
+
}
|
|
660
|
+
|
|
661
|
+
/**
|
|
662
|
+
* Write the aborted fence for a key that has no claim yet, so a create that
|
|
663
|
+
* arrives after the abort is refused rather than orphaned. No-op (false) when
|
|
664
|
+
* any claim already exists for the key. Callers deciding "no claim" MUST do so
|
|
665
|
+
* in the same transaction (see `abortTopicCreateClaim`).
|
|
666
|
+
*/
|
|
667
|
+
export function insertTopicCreateAbortFence(principalKey: string, requestId: string): boolean {
|
|
668
|
+
const now = new Date().toISOString();
|
|
669
|
+
const inserted = db
|
|
670
|
+
.query(
|
|
671
|
+
`INSERT OR IGNORE INTO api_topic_create_claims
|
|
672
|
+
(principal_key, request_id, op, payload_hash, topic_id, state, node_id,
|
|
673
|
+
seed_max_message_rowid, created_at, updated_at, settled_at)
|
|
674
|
+
VALUES (?, ?, 'abort', '', NULL, 'aborted', ${NODE_IDENTITY_SQL}, 0, ?, ?, ?)`,
|
|
675
|
+
)
|
|
676
|
+
.run(principalKey, requestId, now, now, now);
|
|
677
|
+
return Number(inserted.changes ?? 0) > 0;
|
|
678
|
+
}
|
|
679
|
+
|
|
680
|
+
/**
|
|
681
|
+
* CAS a committed claim to aborted. Only for a caller that has decided the
|
|
682
|
+
* claim's topic in the same transaction (deleted it, or found it gone): a
|
|
683
|
+
* committed claim must never become aborted while its topic lives on.
|
|
684
|
+
*/
|
|
685
|
+
export function flipCommittedTopicCreateClaimToAborted(
|
|
686
|
+
principalKey: string,
|
|
687
|
+
requestId: string,
|
|
688
|
+
): boolean {
|
|
689
|
+
const updated = db
|
|
690
|
+
.query(
|
|
691
|
+
`UPDATE api_topic_create_claims SET state = 'aborted', updated_at = ?1, settled_at = ?1
|
|
692
|
+
WHERE principal_key = ?2 AND request_id = ?3 AND state = 'committed'`,
|
|
693
|
+
)
|
|
694
|
+
.run(new Date().toISOString(), principalKey, requestId);
|
|
695
|
+
return Number(updated.changes ?? 0) > 0;
|
|
696
|
+
}
|
|
697
|
+
|
|
698
|
+
/**
|
|
699
|
+
* Settle a claim as aborted where that is safe without deleting anything, in
|
|
700
|
+
* one `BEGIN IMMEDIATE`: no claim → aborted fence; committed claim whose topic
|
|
701
|
+
* row is already gone → aborted. A committed claim whose topic still exists is
|
|
702
|
+
* returned UNCHANGED (deleting it is `abortTopicCreateClaim`'s job). Returns
|
|
703
|
+
* the stored claim.
|
|
704
|
+
*/
|
|
705
|
+
export function markTopicCreateClaimAborted(
|
|
706
|
+
principalKey: string,
|
|
707
|
+
requestId: string,
|
|
708
|
+
): TopicCreateClaim {
|
|
709
|
+
return db
|
|
710
|
+
.transaction(() => {
|
|
711
|
+
const current = getTopicCreateClaim(principalKey, requestId);
|
|
712
|
+
if (!current) {
|
|
713
|
+
insertTopicCreateAbortFence(principalKey, requestId);
|
|
714
|
+
} else if (current.state === "committed" && !topicRowExists(current.topicId)) {
|
|
715
|
+
flipCommittedTopicCreateClaimToAborted(principalKey, requestId);
|
|
716
|
+
}
|
|
717
|
+
const claim = getTopicCreateClaim(principalKey, requestId);
|
|
718
|
+
if (!claim) throw new Error("topic create claim abort was not recorded");
|
|
719
|
+
return claim;
|
|
720
|
+
})
|
|
721
|
+
.immediate();
|
|
722
|
+
}
|
|
723
|
+
|
|
724
|
+
function topicRowExists(topicId: string | null): boolean {
|
|
725
|
+
if (!topicId) return false;
|
|
726
|
+
return Boolean(
|
|
727
|
+
db
|
|
728
|
+
.query<{ found: number }, [string]>("SELECT 1 AS found FROM api_topics WHERE id = ?")
|
|
729
|
+
.get(topicId),
|
|
730
|
+
);
|
|
731
|
+
}
|
|
732
|
+
|
|
733
|
+
/** Whether a live claim-abort fence currently refuses messages into this topic. */
|
|
734
|
+
export function isTopicClaimAbortFenced(topicId: string): boolean {
|
|
735
|
+
return Boolean(
|
|
736
|
+
db
|
|
737
|
+
.query<{ found: number }, [string]>(
|
|
738
|
+
`SELECT 1 AS found FROM runtime_topic_state WHERE topic_id = ? AND ${CLAIM_ABORT_FENCE_PREDICATE}`,
|
|
739
|
+
)
|
|
740
|
+
.get(topicId),
|
|
741
|
+
);
|
|
742
|
+
}
|
|
743
|
+
|
|
744
|
+
/** Whether an error is the message fence trigger's refusal. */
|
|
745
|
+
export function isTopicClaimAbortFenceError(error: unknown): boolean {
|
|
746
|
+
return error instanceof Error && error.message.includes(TOPIC_CLAIM_ABORT_FENCE_ERROR);
|
|
747
|
+
}
|
|
748
|
+
|
|
749
|
+
/**
|
|
750
|
+
* Whether the claimed topic's messages differ from what it was created with.
|
|
751
|
+
*
|
|
752
|
+
* Compared as an exact SET (count + hash of the sorted ids recorded at claim
|
|
753
|
+
* time), not by rowid: a logical dump/import or a VACUUM that renumbers rowids
|
|
754
|
+
* cannot make a post-create message look seeded. Any difference — a new
|
|
755
|
+
* message, a hard-deleted one — counts, so an abort only ever deletes a topic
|
|
756
|
+
* holding exactly its seeded history. Legacy claims without a recorded set fall
|
|
757
|
+
* back to the rowid boundary.
|
|
758
|
+
*/
|
|
759
|
+
export function topicHasMessagesAfterClaim(claim: TopicCreateClaim): boolean {
|
|
760
|
+
if (!claim.topicId) return false;
|
|
761
|
+
if (claim.seedMessageCount !== null && claim.seedMessageIdsHash !== null) {
|
|
762
|
+
const current = messageSetOf(claim.topicId);
|
|
763
|
+
return current.count !== claim.seedMessageCount || current.hash !== claim.seedMessageIdsHash;
|
|
764
|
+
}
|
|
765
|
+
const row = db
|
|
766
|
+
.query<{ found: number }, [string, number]>(
|
|
767
|
+
"SELECT 1 AS found FROM api_messages WHERE topic_id = ? AND rowid > ? LIMIT 1",
|
|
768
|
+
)
|
|
769
|
+
.get(claim.topicId, claim.seedMaxMessageRowid);
|
|
770
|
+
return Boolean(row);
|
|
771
|
+
}
|
|
772
|
+
|
|
773
|
+
/** Upper bound of claims one prune call removes (bounded work per request). */
|
|
774
|
+
export const TOPIC_CREATE_CLAIM_PRUNE_BATCH = 500;
|
|
775
|
+
|
|
776
|
+
/**
|
|
777
|
+
* Drop claims past the retention window. Returns the number removed.
|
|
778
|
+
*
|
|
779
|
+
* The retention anchor is the claim's LAST settlement: a committed claim is
|
|
780
|
+
* kept from its `created_at`, an aborted one (fence) from its `settled_at` —
|
|
781
|
+
* the moment it became aborted (rows settled before that column existed fall
|
|
782
|
+
* back to `updated_at`). An old committed claim aborted today therefore
|
|
783
|
+
* keeps refusing a late create with the same requestId for a full window.
|
|
784
|
+
* Removes at most `batch` rows per call.
|
|
785
|
+
*/
|
|
786
|
+
export function pruneTopicCreateClaims(
|
|
787
|
+
now: number = Date.now(),
|
|
788
|
+
retentionMs: number = TOPIC_CREATE_CLAIM_RETENTION_MS,
|
|
789
|
+
batch: number = TOPIC_CREATE_CLAIM_PRUNE_BATCH,
|
|
790
|
+
): number {
|
|
791
|
+
const cutoff = new Date(now - retentionMs).toISOString();
|
|
792
|
+
const result = db
|
|
793
|
+
.query(
|
|
794
|
+
`DELETE FROM api_topic_create_claims WHERE rowid IN (
|
|
795
|
+
SELECT rowid FROM api_topic_create_claims
|
|
796
|
+
WHERE (state = 'committed' AND created_at < ?)
|
|
797
|
+
OR (state = 'aborted' AND COALESCE(settled_at, updated_at) < ?)
|
|
798
|
+
LIMIT ?)`,
|
|
799
|
+
)
|
|
800
|
+
.run(cutoff, cutoff, batch);
|
|
801
|
+
return Number(result.changes ?? 0);
|
|
802
|
+
}
|
|
803
|
+
|
|
804
|
+
// ── tombstones ────────────────────────────────────────────────────────────
|
|
805
|
+
|
|
806
|
+
function toTombstone(row: TombstoneRow): TopicTombstone {
|
|
807
|
+
return {
|
|
808
|
+
seq: Number(row.seq),
|
|
809
|
+
topicId: row.topic_id,
|
|
810
|
+
nodeId: row.node_id,
|
|
811
|
+
reason: row.reason as TopicTombstoneReason,
|
|
812
|
+
surface: row.surface,
|
|
813
|
+
surfaceScope: row.surface_scope,
|
|
814
|
+
deletedAt: row.deleted_at,
|
|
815
|
+
};
|
|
816
|
+
}
|
|
817
|
+
|
|
818
|
+
export function getTopicTombstone(topicId: string): TopicTombstone | null {
|
|
819
|
+
const row = db
|
|
820
|
+
.query<TombstoneRow, [string]>("SELECT * FROM api_topic_tombstones WHERE topic_id = ?")
|
|
821
|
+
.get(topicId);
|
|
822
|
+
return row ? toTombstone(row) : null;
|
|
823
|
+
}
|
|
824
|
+
|
|
825
|
+
/** Tombstones after a cursor, oldest first. */
|
|
826
|
+
/**
|
|
827
|
+
* The tombstone feed after a cursor, oldest first: current tombstones merged
|
|
828
|
+
* with scope moves (as `unshared` for the OLD scope, `scopeMoved: true`). Both
|
|
829
|
+
* take their seq from the same never-decreasing counter.
|
|
830
|
+
*/
|
|
831
|
+
export function listTopicTombstonesAfter(after: number, limit: number): TopicTombstone[] {
|
|
832
|
+
return db
|
|
833
|
+
.query<TombstoneRow & { scope_moved: number }, [number, number, number]>(
|
|
834
|
+
`SELECT seq, topic_id, node_id, reason, surface, surface_scope, deleted_at, 0 AS scope_moved
|
|
835
|
+
FROM api_topic_tombstones WHERE seq > ?1
|
|
836
|
+
UNION ALL
|
|
837
|
+
SELECT seq, topic_id, node_id, 'unshared', 'otium', from_scope, moved_at, 1
|
|
838
|
+
FROM api_topic_scope_moves WHERE seq > ?2
|
|
839
|
+
ORDER BY seq ASC LIMIT ?3`,
|
|
840
|
+
)
|
|
841
|
+
.all(after, after, limit)
|
|
842
|
+
.map((row) => ({
|
|
843
|
+
...toTombstone(row),
|
|
844
|
+
...(row.scope_moved ? { scopeMoved: true as const } : {}),
|
|
845
|
+
}));
|
|
846
|
+
}
|
|
847
|
+
|
|
848
|
+
/** The latest admin scope move of a topic (the scope it was moved out of), if any. */
|
|
849
|
+
export function latestTopicScopeMove(topicId: string): TopicTombstone | null {
|
|
850
|
+
const row = db
|
|
851
|
+
.query<
|
|
852
|
+
{ seq: number | bigint; node_id: string | null; from_scope: string | null; moved_at: string },
|
|
853
|
+
[string]
|
|
854
|
+
>(
|
|
855
|
+
`SELECT seq, node_id, from_scope, moved_at FROM api_topic_scope_moves
|
|
856
|
+
WHERE topic_id = ? ORDER BY seq DESC LIMIT 1`,
|
|
857
|
+
)
|
|
858
|
+
.get(topicId);
|
|
859
|
+
if (!row) return null;
|
|
860
|
+
return {
|
|
861
|
+
seq: Number(row.seq),
|
|
862
|
+
topicId,
|
|
863
|
+
nodeId: row.node_id,
|
|
864
|
+
reason: "unshared",
|
|
865
|
+
surface: "otium",
|
|
866
|
+
surfaceScope: row.from_scope,
|
|
867
|
+
deletedAt: row.moved_at,
|
|
868
|
+
scopeMoved: true,
|
|
869
|
+
};
|
|
870
|
+
}
|
|
871
|
+
|
|
872
|
+
// ── otium scope repair (review fix 6 / PR12 admin repair) ────────────────
|
|
873
|
+
|
|
874
|
+
export interface AdminRepairOtiumTopicScopeInput {
|
|
875
|
+
topicId: string;
|
|
876
|
+
/** Only an unscoped room can be repaired: must be `null`. */
|
|
877
|
+
fromScope: null;
|
|
878
|
+
/** Non-empty, no leading/trailing whitespace. */
|
|
879
|
+
toScope: string;
|
|
880
|
+
/**
|
|
881
|
+
* The row the operator observed — compare-and-set. `surface`/`surfaceScope`
|
|
882
|
+
* are required; `createdAt`/`title` pin the exact row when given.
|
|
883
|
+
*/
|
|
884
|
+
expectedRow: { surface: "otium"; surfaceScope: null; createdAt?: string; title?: string };
|
|
885
|
+
/** Who asked (operator/CLI user, `m9-stamp`). Recorded in the history row. */
|
|
886
|
+
actor: string;
|
|
887
|
+
reason: string;
|
|
888
|
+
}
|
|
889
|
+
|
|
890
|
+
export type AdminRepairOtiumTopicScopeRefusal =
|
|
891
|
+
| "invalid_scope"
|
|
892
|
+
| "not_found"
|
|
893
|
+
| "not_otium"
|
|
894
|
+
| "scope_not_null"
|
|
895
|
+
| "row_changed"
|
|
896
|
+
| "title_conflict"
|
|
897
|
+
| "duplicate_manager"
|
|
898
|
+
| "maintenance_in_progress";
|
|
899
|
+
|
|
900
|
+
export type AdminRepairOtiumTopicScopeResult =
|
|
901
|
+
| {
|
|
902
|
+
ok: true;
|
|
903
|
+
topicId: string;
|
|
904
|
+
fromScope: null;
|
|
905
|
+
toScope: string;
|
|
906
|
+
/**
|
|
907
|
+
* Committed create claims of the topic, left on their ORIGINAL principal
|
|
908
|
+
* (never re-bound). A claim whose principal no longer covers the new
|
|
909
|
+
* scope answers `409 claim_topic_moved` on replay/abort.
|
|
910
|
+
*/
|
|
911
|
+
claimsLeft: number;
|
|
912
|
+
/** seq of the scope-move entry in the tombstone feed (also the audit id). */
|
|
913
|
+
moveSeq: number;
|
|
914
|
+
}
|
|
915
|
+
| { ok: false; topicId: string; reason: AdminRepairOtiumTopicScopeRefusal; detail?: string };
|
|
916
|
+
|
|
917
|
+
interface RepairTopicRow {
|
|
918
|
+
id: string;
|
|
919
|
+
title: string;
|
|
920
|
+
kind: string;
|
|
921
|
+
surface: string;
|
|
922
|
+
surface_scope: string | null;
|
|
923
|
+
created_at: string;
|
|
924
|
+
}
|
|
925
|
+
|
|
926
|
+
function repairOneTopicScope(
|
|
927
|
+
input: AdminRepairOtiumTopicScopeInput,
|
|
928
|
+
): AdminRepairOtiumTopicScopeResult {
|
|
929
|
+
const { topicId } = input;
|
|
930
|
+
const refuse = (reason: AdminRepairOtiumTopicScopeRefusal, detail?: string) =>
|
|
931
|
+
({ ok: false, topicId, reason, ...(detail ? { detail } : {}) }) as const;
|
|
932
|
+
const toScope = typeof input.toScope === "string" ? input.toScope : "";
|
|
933
|
+
if (!toScope || toScope !== toScope.trim() || input.fromScope !== null) {
|
|
934
|
+
return refuse("invalid_scope");
|
|
935
|
+
}
|
|
936
|
+
const row = db
|
|
937
|
+
.query<RepairTopicRow, [string]>(
|
|
938
|
+
"SELECT id, title, kind, surface, surface_scope, created_at FROM api_topics WHERE id = ?",
|
|
939
|
+
)
|
|
940
|
+
.get(topicId);
|
|
941
|
+
if (!row) return refuse("not_found");
|
|
942
|
+
if (row.surface !== "otium" || input.expectedRow.surface !== "otium") return refuse("not_otium");
|
|
943
|
+
if (row.surface_scope !== null || input.expectedRow.surfaceScope !== null) {
|
|
944
|
+
return refuse("scope_not_null", row.surface_scope ?? undefined);
|
|
945
|
+
}
|
|
946
|
+
if (
|
|
947
|
+
(input.expectedRow.createdAt !== undefined && input.expectedRow.createdAt !== row.created_at) ||
|
|
948
|
+
(input.expectedRow.title !== undefined && input.expectedRow.title !== row.title)
|
|
949
|
+
) {
|
|
950
|
+
return refuse("row_changed");
|
|
951
|
+
}
|
|
952
|
+
// A claim abort (or any delete/reset/compact) holds the topic right now.
|
|
953
|
+
const busy = db
|
|
954
|
+
.query<{ found: number }, [string, number]>(
|
|
955
|
+
`SELECT 1 AS found FROM runtime_topic_state
|
|
956
|
+
WHERE topic_id = ? AND maintenance = 1 AND heartbeat_at >= ?`,
|
|
957
|
+
)
|
|
958
|
+
.get(topicId, Date.now() - CLAIM_ABORT_FENCE_STALE_MS);
|
|
959
|
+
if (busy) return refuse("maintenance_in_progress");
|
|
960
|
+
if (row.kind === "manager") {
|
|
961
|
+
// Manager rooms are one-per-user and all titled "General", so — exactly as
|
|
962
|
+
// in `findTopicTitleConflict` — they take no part in title conflicts.
|
|
963
|
+
// What must not happen is a SECOND manager room for the same owner in one
|
|
964
|
+
// scope (the PR12 CLI and hub audit D7 enforce it too; this is the
|
|
965
|
+
// primitive's own guard so no caller can create one silently).
|
|
966
|
+
const duplicate = db
|
|
967
|
+
.query<{ id: string }, [string, string, string, string]>(
|
|
968
|
+
`SELECT t.id FROM api_topics t
|
|
969
|
+
JOIN topic_members m ON m.topic_id = t.id AND m.role = 'owner'
|
|
970
|
+
WHERE t.kind = 'manager' AND t.surface = 'otium' AND t.surface_scope IS ?
|
|
971
|
+
AND t.id != ? AND t.id != ?
|
|
972
|
+
AND m.user_id IN (
|
|
973
|
+
SELECT user_id FROM topic_members WHERE topic_id = ? AND role = 'owner'
|
|
974
|
+
)
|
|
975
|
+
LIMIT 1`,
|
|
976
|
+
)
|
|
977
|
+
.get(toScope, topicId, GENERAL_TOPIC_ID, topicId);
|
|
978
|
+
if (duplicate) return refuse("duplicate_manager", duplicate.id);
|
|
979
|
+
} else {
|
|
980
|
+
// Same rule as `findTopicTitleConflict`: manager rooms are not title
|
|
981
|
+
// peers, except the reserved shared `general` row.
|
|
982
|
+
const conflict = db
|
|
983
|
+
.query<{ id: string }, [string, string, string, string]>(
|
|
984
|
+
`SELECT id FROM api_topics
|
|
985
|
+
WHERE LOWER(TRIM(title)) = LOWER(TRIM(?)) AND surface = 'otium' AND surface_scope IS ?
|
|
986
|
+
AND id != ? AND (kind != 'manager' OR id = ?) LIMIT 1`,
|
|
987
|
+
)
|
|
988
|
+
.get(row.title, toScope, topicId, GENERAL_TOPIC_ID);
|
|
989
|
+
if (conflict) return refuse("title_conflict", conflict.id);
|
|
990
|
+
}
|
|
991
|
+
|
|
992
|
+
const claimsLeft = Number(
|
|
993
|
+
db
|
|
994
|
+
.query<{ n: number }, [string]>(
|
|
995
|
+
`SELECT COUNT(*) AS n FROM api_topic_create_claims
|
|
996
|
+
WHERE topic_id = ? AND state = 'committed'`,
|
|
997
|
+
)
|
|
998
|
+
.get(topicId)?.n ?? 0,
|
|
999
|
+
);
|
|
1000
|
+
db.query("INSERT INTO api_topic_scope_repair_grants (topic_id) VALUES (?)").run(topicId);
|
|
1001
|
+
const updated = db
|
|
1002
|
+
.query(
|
|
1003
|
+
`UPDATE api_topics SET surface_scope = ?
|
|
1004
|
+
WHERE id = ? AND surface = 'otium' AND surface_scope IS NULL`,
|
|
1005
|
+
)
|
|
1006
|
+
.run(toScope, topicId);
|
|
1007
|
+
db.query("DELETE FROM api_topic_scope_repair_grants WHERE topic_id = ?").run(topicId);
|
|
1008
|
+
if (Number(updated.changes ?? 0) !== 1) throw new Error("scope repair CAS lost the row");
|
|
1009
|
+
db.query(BUMP_TOMBSTONE_SEQ_SQL).run();
|
|
1010
|
+
db.query(
|
|
1011
|
+
`INSERT INTO api_topic_scope_moves
|
|
1012
|
+
(seq, topic_id, node_id, from_scope, to_scope, actor, reason, claims_left, moved_at)
|
|
1013
|
+
VALUES (${TOMBSTONE_SEQ_SQL}, ?, ${NODE_IDENTITY_SQL}, NULL, ?, ?, ?, ?, ?)`,
|
|
1014
|
+
).run(topicId, toScope, input.actor, input.reason, claimsLeft, new Date().toISOString());
|
|
1015
|
+
const moveSeq = Number(
|
|
1016
|
+
db.query<{ seq: number }, []>(`SELECT ${TOMBSTONE_SEQ_SQL} AS seq`).get()?.seq ?? 0,
|
|
1017
|
+
);
|
|
1018
|
+
return { ok: true, topicId, fromScope: null, toScope, claimsLeft, moveSeq };
|
|
1019
|
+
}
|
|
1020
|
+
|
|
1021
|
+
/**
|
|
1022
|
+
* The ONLY sanctioned way to change an otium topic's `surface_scope` after
|
|
1023
|
+
* creation — the `api_topics_otium_scope_immutable` trigger refuses every other
|
|
1024
|
+
* writer. One-shot, audited, one `BEGIN IMMEDIATE` (joins the caller's
|
|
1025
|
+
* transaction when there is one):
|
|
1026
|
+
*
|
|
1027
|
+
* - only `NULL → <non-empty scope>` on a `surface='otium'` row, compare-and-set
|
|
1028
|
+
* against `expectedRow`; any refusal changes nothing;
|
|
1029
|
+
* - create claims are NOT re-bound: they stay on their original principal, and
|
|
1030
|
+
* replay/abort re-verify that the topic's current scope still belongs to the
|
|
1031
|
+
* claim's principal (else `409 claim_topic_moved`). Re-binding would let the
|
|
1032
|
+
* new scope's principal delete a room another caller created, and that
|
|
1033
|
+
* caller's retry would then create a duplicate;
|
|
1034
|
+
* - the move is recorded in `api_topic_scope_moves` (history + audit) with a
|
|
1035
|
+
* seq from the tombstone counter, and appears in the tombstone feed as an
|
|
1036
|
+
* `unshared` entry for the OLD scope (`scopeMoved: true`);
|
|
1037
|
+
* - tombstones are not rewritten.
|
|
1038
|
+
*
|
|
1039
|
+
* No HTTP route: storage / admin CLI only.
|
|
1040
|
+
*/
|
|
1041
|
+
export function adminRepairOtiumTopicScope(
|
|
1042
|
+
input: AdminRepairOtiumTopicScopeInput,
|
|
1043
|
+
): AdminRepairOtiumTopicScopeResult {
|
|
1044
|
+
return db.transaction(() => repairOneTopicScope(input)).immediate();
|
|
1045
|
+
}
|
|
1046
|
+
|
|
1047
|
+
/**
|
|
1048
|
+
* M-9 bulk variant: stamp every unscoped otium room with `toScope` through the
|
|
1049
|
+
* same per-topic repair (history recorded, claims untouched). Rooms that are
|
|
1050
|
+
* refused (busy, title conflict, duplicate manager) are skipped and reported — the caller decides
|
|
1051
|
+
* whether that leaves its migration incomplete (it must, revision 5).
|
|
1052
|
+
*
|
|
1053
|
+
* `topicIds` narrows the pass to those rooms (the M-9 retry of its pending
|
|
1054
|
+
* set); ids that are no longer unscoped otium rooms are simply not selected.
|
|
1055
|
+
*/
|
|
1056
|
+
export function repairUnscopedOtiumTopicScopes(
|
|
1057
|
+
toScope: string,
|
|
1058
|
+
actor: string,
|
|
1059
|
+
reason: string,
|
|
1060
|
+
options: { topicIds?: readonly string[] } = {},
|
|
1061
|
+
): { stamped: number; skipped: AdminRepairOtiumTopicScopeResult[] } {
|
|
1062
|
+
const skipped: AdminRepairOtiumTopicScopeResult[] = [];
|
|
1063
|
+
let stamped = 0;
|
|
1064
|
+
const all = db
|
|
1065
|
+
.query<RepairTopicRow, []>(
|
|
1066
|
+
`SELECT id, title, kind, surface, surface_scope, created_at FROM api_topics
|
|
1067
|
+
WHERE surface = 'otium' AND surface_scope IS NULL`,
|
|
1068
|
+
)
|
|
1069
|
+
.all();
|
|
1070
|
+
const only = options.topicIds ? new Set(options.topicIds) : null;
|
|
1071
|
+
const rows = only ? all.filter((row) => only.has(row.id)) : all;
|
|
1072
|
+
for (const row of rows) {
|
|
1073
|
+
const result = repairOneTopicScope({
|
|
1074
|
+
topicId: row.id,
|
|
1075
|
+
fromScope: null,
|
|
1076
|
+
toScope,
|
|
1077
|
+
expectedRow: { surface: "otium", surfaceScope: null, createdAt: row.created_at },
|
|
1078
|
+
actor,
|
|
1079
|
+
reason,
|
|
1080
|
+
});
|
|
1081
|
+
if (result.ok) stamped += 1;
|
|
1082
|
+
else skipped.push(result);
|
|
1083
|
+
}
|
|
1084
|
+
return { stamped, skipped };
|
|
1085
|
+
}
|