@vellumai/assistant 0.10.7-dev.202607092332.9deedf4 → 0.10.7-dev.202607100313.fffdfea
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/ARCHITECTURE.md +1 -2
- package/docs/architecture/memory.md +1 -3
- package/node_modules/@vellumai/ces-client/node_modules/@vellumai/service-contracts/package.json +0 -2
- package/node_modules/@vellumai/ces-client/node_modules/@vellumai/service-contracts/src/__tests__/contracts.test.ts +0 -2
- package/node_modules/@vellumai/ces-client/node_modules/@vellumai/service-contracts/src/credential-rpc.ts +3 -5
- package/node_modules/@vellumai/ces-client/node_modules/@vellumai/service-contracts/src/index.ts +2 -4
- package/node_modules/@vellumai/ces-client/node_modules/@vellumai/service-contracts/src/rpc.ts +4 -447
- package/node_modules/@vellumai/gateway-client/node_modules/@vellumai/service-contracts/package.json +0 -2
- package/node_modules/@vellumai/gateway-client/node_modules/@vellumai/service-contracts/src/__tests__/contracts.test.ts +0 -2
- package/node_modules/@vellumai/gateway-client/node_modules/@vellumai/service-contracts/src/credential-rpc.ts +3 -5
- package/node_modules/@vellumai/gateway-client/node_modules/@vellumai/service-contracts/src/index.ts +2 -4
- package/node_modules/@vellumai/gateway-client/node_modules/@vellumai/service-contracts/src/rpc.ts +4 -447
- package/node_modules/@vellumai/service-contracts/package.json +0 -2
- package/node_modules/@vellumai/service-contracts/src/__tests__/contracts.test.ts +0 -2
- package/node_modules/@vellumai/service-contracts/src/credential-rpc.ts +3 -5
- package/node_modules/@vellumai/service-contracts/src/index.ts +2 -4
- package/node_modules/@vellumai/service-contracts/src/rpc.ts +4 -447
- package/openapi.yaml +1 -222
- package/package.json +1 -1
- package/scripts/memory-inspect.ts +2 -8
- package/src/__tests__/approval-routes-http.test.ts +0 -8
- package/src/__tests__/background-workers-disk-pressure.test.ts +4 -2
- package/src/__tests__/compaction-events.test.ts +0 -4
- package/src/__tests__/context-search-memory-source.test.ts +0 -1
- package/src/__tests__/conversation-agent-loop-disk-pressure.test.ts +0 -1
- package/src/__tests__/conversation-agent-loop-inference-profile.test.ts +0 -2
- package/src/__tests__/conversation-agent-loop-overflow.test.ts +0 -2
- package/src/__tests__/conversation-agent-loop.test.ts +0 -4
- package/src/__tests__/conversation-app-control-lifecycle.test.ts +0 -4
- package/src/__tests__/conversation-fork-crud.test.ts +18 -5
- package/src/__tests__/conversation-fork-retrospective.test.ts +483 -0
- package/src/__tests__/conversation-routes-disk-view.test.ts +0 -4
- package/src/__tests__/conversation-store.test.ts +0 -10
- package/src/__tests__/conversation-summarize-up-to.test.ts +0 -4
- package/src/__tests__/credential-execution-api-key-propagation.test.ts +0 -40
- package/src/__tests__/credential-execution-client.test.ts +3 -3
- package/src/__tests__/credential-execution-managed-contract.test.ts +8 -104
- package/src/__tests__/file-write-tool.test.ts +9 -13
- package/src/__tests__/graph-extraction-event-date.test.ts +0 -9
- package/src/__tests__/injection-block.test.ts +0 -1
- package/src/__tests__/job-handler-registration-guard.test.ts +0 -1
- package/src/__tests__/lexical-index-dual-write.test.ts +2 -2
- package/src/__tests__/llm-resolver.test.ts +0 -1
- package/src/__tests__/messages-after-tiebreaker.test.ts +0 -1
- package/src/__tests__/playbook-execution.test.ts +2 -26
- package/src/__tests__/plugin-import-boundary-guard.test.ts +0 -4
- package/src/__tests__/plugin-import-boundary-reverse-guard.test.ts +318 -0
- package/src/__tests__/proxy-approval-callback.test.ts +0 -1
- package/src/__tests__/rebuild-index-graph-nodes.test.ts +0 -4
- package/src/__tests__/send-endpoint-busy.test.ts +0 -12
- package/src/__tests__/service-contracts-import-guard.test.ts +4 -9
- package/src/__tests__/subagent-fork-spawn.test.ts +0 -37
- package/src/__tests__/task-memory-cleanup.test.ts +0 -11
- package/src/__tests__/voice-scoped-grant-consumer.test.ts +0 -1
- package/src/__tests__/voice-session-bridge.test.ts +0 -56
- package/src/__tests__/workspace-migration-009-backfill-conversation-disk-view.test.ts +0 -1
- package/src/__tests__/workspace-migration-013-repair-conversation-disk-view.test.ts +0 -1
- package/src/__tests__/workspace-migration-028-recover-conversations-from-disk-view.test.ts +0 -1
- package/src/__tests__/workspace-migration-129-remove-analyze-conversation-config.test.ts +190 -0
- package/src/cli/commands/db/repair-step-conversation-backfill.ts +0 -1
- package/src/config/bundled-skills/messaging/tools/messaging-analyze-style.ts +0 -6
- package/src/config/bundled-skills/playbooks/tools/playbook-create.ts +0 -3
- package/src/config/bundled-skills/playbooks/tools/playbook-delete.ts +0 -3
- package/src/config/bundled-skills/playbooks/tools/playbook-list.ts +1 -3
- package/src/config/bundled-skills/playbooks/tools/playbook-update.ts +0 -4
- package/src/config/call-site-defaults.ts +0 -1
- package/src/config/feature-flag-registry.json +0 -16
- package/src/config/schema.ts +0 -3
- package/src/config/schemas/call-site-catalog.ts +0 -6
- package/src/config/schemas/llm.ts +0 -1
- package/src/conversations/job-handlers/summarization.ts +0 -2
- package/src/daemon/conversation-agent-loop-handlers.ts +0 -1
- package/src/daemon/conversation-agent-loop.ts +1 -6
- package/src/daemon/conversation-lifecycle.ts +0 -14
- package/src/daemon/conversation-turn-finalize.ts +0 -1
- package/src/daemon/handlers/shared.ts +1 -2
- package/src/export/transcript-formatter.ts +9 -39
- package/src/home/conversation-starter-checkpoints.ts +9 -5
- package/src/home/job-handlers/conversation-starters.ts +24 -54
- package/src/hooks/types.ts +2 -2
- package/src/ipc/routes/__tests__/memory-v2-backfill.test.ts +5 -7
- package/src/persistence/__tests__/bulk-write-gate.test.ts +165 -0
- package/src/persistence/__tests__/immediate-transaction-guard.test.ts +70 -0
- package/src/persistence/auto-analysis-constants.ts +4 -13
- package/src/persistence/bulk-write-gate.ts +82 -0
- package/src/persistence/conversation-bootstrap.ts +3 -3
- package/src/persistence/conversation-crud.ts +158 -80
- package/src/persistence/conversation-key-store.ts +0 -2
- package/src/persistence/conversation-row-batch-delete.ts +16 -1
- package/src/persistence/conversation-types.ts +12 -1
- package/src/persistence/db-async-query.ts +18 -9
- package/src/persistence/db-connection.ts +20 -4
- package/src/persistence/db-maintenance.ts +78 -6
- package/src/persistence/embeddings/qdrant-client.ts +2 -18
- package/src/persistence/fork-message-copy.ts +18 -4
- package/src/persistence/jobs-store.ts +3 -86
- package/src/persistence/migrations/323-delete-non-default-memory-scopes.test.ts +148 -0
- package/src/persistence/migrations/323-delete-non-default-memory-scopes.ts +35 -0
- package/src/persistence/schema/conversations.ts +0 -1
- package/src/persistence/schema/memory-core.ts +17 -28
- package/src/persistence/schema/memory-graph.ts +0 -4
- package/src/persistence/schema/tasks.ts +0 -1
- package/src/persistence/steps.ts +2 -0
- package/src/playbooks/playbook-compiler.ts +2 -10
- package/src/plugins/defaults/memory/__tests__/db-maintenance.test.ts +105 -11
- package/src/plugins/defaults/memory/__tests__/jobs-store-enqueue-gate.test.ts +7 -62
- package/src/plugins/defaults/memory/__tests__/memory-retrospective-job.test.ts +47 -5
- package/src/plugins/defaults/memory/__tests__/memory-retrospective-skill-card.test.ts +29 -1
- package/src/plugins/defaults/memory/__tests__/memory-retrospective-startup-cleanup.test.ts +133 -70
- package/src/plugins/defaults/memory/activation-session-store.ts +1 -1
- package/src/plugins/defaults/memory/config.ts +1 -1
- package/src/plugins/defaults/memory/context-search/sources/conversations.ts +1 -1
- package/src/plugins/defaults/memory/context-search/sources/memory-v2.ts +1 -1
- package/src/plugins/defaults/memory/context-search/sources/memory.ts +1 -1
- package/src/plugins/defaults/memory/filing-jobs.ts +1 -1
- package/src/plugins/defaults/memory/fork-conversation-memory.ts +8 -4
- package/src/plugins/defaults/memory/frontmatter.ts +1 -1
- package/src/plugins/defaults/memory/graph/__tests__/handle-remember-v2.test.ts +4 -25
- package/src/plugins/defaults/memory/graph/bootstrap.ts +12 -18
- package/src/plugins/defaults/memory/graph/capability-seed.ts +4 -18
- package/src/plugins/defaults/memory/graph/consolidation.ts +7 -14
- package/src/plugins/defaults/memory/graph/conversation-graph-memory.ts +1 -3
- package/src/plugins/defaults/memory/graph/decay.ts +5 -10
- package/src/plugins/defaults/memory/graph/extraction-job.ts +2 -3
- package/src/plugins/defaults/memory/graph/extraction.test.ts +1 -9
- package/src/plugins/defaults/memory/graph/extraction.ts +1 -8
- package/src/plugins/defaults/memory/graph/graph-search.ts +1 -2
- package/src/plugins/defaults/memory/graph/injection.test.ts +0 -1
- package/src/plugins/defaults/memory/graph/injection.ts +1 -1
- package/src/plugins/defaults/memory/graph/narrative.ts +1 -3
- package/src/plugins/defaults/memory/graph/pattern-scan.ts +1 -4
- package/src/plugins/defaults/memory/graph/retriever.test.ts +0 -19
- package/src/plugins/defaults/memory/graph/retriever.ts +6 -14
- package/src/plugins/defaults/memory/graph/scoring.test.ts +0 -1
- package/src/plugins/defaults/memory/graph/store.test.ts +6 -58
- package/src/plugins/defaults/memory/graph/store.ts +5 -43
- package/src/plugins/defaults/memory/graph/tool-handlers.test.ts +0 -4
- package/src/plugins/defaults/memory/graph/tool-handlers.ts +1 -11
- package/src/plugins/defaults/memory/graph/types.ts +0 -3
- package/src/plugins/defaults/memory/hooks/init.ts +1 -1
- package/src/plugins/defaults/memory/indexer.ts +2 -45
- package/src/plugins/defaults/memory/injectors.ts +2 -3
- package/src/plugins/defaults/memory/job-handler-registration.ts +0 -4
- package/src/plugins/defaults/memory/job-handlers/backfill.ts +0 -1
- package/src/plugins/defaults/memory/job-handlers/embedding.test.ts +0 -1
- package/src/plugins/defaults/memory/job-handlers/embedding.ts +0 -4
- package/src/plugins/defaults/memory/job-handlers/index-maintenance.ts +1 -1
- package/src/plugins/defaults/memory/job-handlers.ts +5 -9
- package/src/plugins/defaults/memory/jobs/embed-concept-page.ts +1 -1
- package/src/plugins/defaults/memory/jobs/embed-pkb-file.test.ts +41 -21
- package/src/plugins/defaults/memory/jobs/embed-pkb-file.ts +10 -5
- package/src/plugins/defaults/memory/jobs-worker.ts +21 -9
- package/src/plugins/defaults/memory/logging.ts +17 -0
- package/src/plugins/defaults/memory/memory-retrospective-constants.ts +10 -7
- package/src/plugins/defaults/memory/memory-retrospective-enqueue.ts +5 -6
- package/src/plugins/defaults/memory/memory-retrospective-fork-boundary.ts +57 -20
- package/src/plugins/defaults/memory/memory-retrospective-job.ts +13 -15
- package/src/plugins/defaults/memory/memory-retrospective-skill-card.ts +2 -2
- package/src/plugins/defaults/memory/memory-retrospective-startup-cleanup.ts +52 -39
- package/src/plugins/defaults/memory/memory-retrospective-trigger-check.ts +1 -1
- package/src/plugins/defaults/memory/pkb/pkb-index.test.ts +25 -38
- package/src/plugins/defaults/memory/pkb/pkb-index.ts +7 -19
- package/src/plugins/defaults/memory/pkb/pkb-reconcile.test.ts +46 -28
- package/src/plugins/defaults/memory/pkb/pkb-reconcile.ts +4 -9
- package/src/plugins/defaults/memory/pkb/pkb-search.test.ts +3 -9
- package/src/plugins/defaults/memory/pkb/pkb-search.ts +2 -9
- package/src/plugins/defaults/memory/pkb/types.ts +0 -11
- package/src/plugins/defaults/memory/rerank-local.ts +1 -1
- package/src/plugins/defaults/memory/routes/memory-eval-routes.ts +1 -1
- package/src/plugins/defaults/memory/routes/memory-item-routes.test.ts +0 -1
- package/src/plugins/defaults/memory/routes/memory-item-routes.ts +3 -11
- package/src/plugins/defaults/memory/routes/memory-v2-routes.ts +1 -1
- package/src/plugins/defaults/memory/routes/memory-v3-routes.ts +1 -1
- package/src/plugins/defaults/memory/startup.ts +2 -3
- package/src/plugins/defaults/memory/task-memory-cleanup.ts +1 -1
- package/src/plugins/defaults/memory/tools.test.ts +1 -9
- package/src/plugins/defaults/memory/tools.ts +0 -1
- package/src/plugins/defaults/memory/v2/backfill-jobs.ts +1 -1
- package/src/plugins/defaults/memory/v2/cli-command-store.ts +1 -1
- package/src/plugins/defaults/memory/v2/consolidation-job.ts +1 -1
- package/src/plugins/defaults/memory/v2/frontmatter-sweep.ts +1 -1
- package/src/plugins/defaults/memory/v2/injection-events.ts +1 -1
- package/src/plugins/defaults/memory/v2/injection.ts +1 -1
- package/src/plugins/defaults/memory/v2/memory-v2-startup.ts +1 -1
- package/src/plugins/defaults/memory/v2/migration.ts +1 -1
- package/src/plugins/defaults/memory/v2/page-index.ts +1 -1
- package/src/plugins/defaults/memory/v2/prompts/consolidation.ts +1 -1
- package/src/plugins/defaults/memory/v2/prompts/router.ts +1 -1
- package/src/plugins/defaults/memory/v2/qdrant.ts +1 -1
- package/src/plugins/defaults/memory/v2/reranker.ts +1 -1
- package/src/plugins/defaults/memory/v2/router.ts +1 -1
- package/src/plugins/defaults/memory/v2/skill-store.ts +1 -1
- package/src/plugins/defaults/memory/v2/sweep-job.ts +1 -1
- package/src/plugins/defaults/memory/v3/candidate-match.ts +1 -1
- package/src/plugins/defaults/memory/v3/dense.ts +1 -1
- package/src/plugins/defaults/memory/v3/injector.ts +1 -1
- package/src/plugins/defaults/memory/v3/maintain-job.ts +1 -1
- package/src/plugins/defaults/memory/v3/orchestrate.ts +1 -1
- package/src/plugins/defaults/memory/v3/pool-select.ts +1 -1
- package/src/plugins/defaults/memory/v3/prune.ts +1 -1
- package/src/plugins/defaults/memory/v3/section-dense-store.ts +1 -1
- package/src/plugins/defaults/memory/v3/shadow-plugin.ts +1 -1
- package/src/plugins/defaults/memory/worker.ts +1 -1
- package/src/runtime/capabilities.ts +1 -1
- package/src/runtime/routes/__tests__/bookmark-routes.test.ts +0 -1
- package/src/runtime/routes/__tests__/conversation-management-routes.test.ts +0 -1
- package/src/runtime/routes/__tests__/conversation-query-routes.test.ts +0 -1
- package/src/runtime/routes/conversation-starter-routes.ts +12 -23
- package/src/runtime/routes/index.ts +0 -2
- package/src/runtime/services/__tests__/auto-analysis-guard.test.ts +1 -8
- package/src/runtime/services/__tests__/conversation-serializer.test.ts +0 -1
- package/src/runtime/services/auto-analysis-guard.ts +5 -5
- package/src/runtime/services/conversation-serializer.ts +2 -3
- package/src/tasks/SPEC.md +10 -17
- package/src/tools/executor.ts +1 -102
- package/src/tools/filesystem/write.ts +0 -2
- package/src/tools/tool-types.ts +0 -15
- package/src/tools/types.ts +0 -10
- package/src/workspace/migrations/028-recover-conversations-from-disk-view.ts +0 -1
- package/src/workspace/migrations/129-remove-analyze-conversation-config.ts +59 -0
- package/src/workspace/migrations/registry.ts +2 -0
- package/node_modules/@vellumai/ces-client/node_modules/@vellumai/service-contracts/src/__tests__/grants.test.ts +0 -686
- package/node_modules/@vellumai/ces-client/node_modules/@vellumai/service-contracts/src/grants.ts +0 -184
- package/node_modules/@vellumai/ces-client/node_modules/@vellumai/service-contracts/src/rendering.ts +0 -135
- package/node_modules/@vellumai/gateway-client/node_modules/@vellumai/service-contracts/src/__tests__/grants.test.ts +0 -686
- package/node_modules/@vellumai/gateway-client/node_modules/@vellumai/service-contracts/src/grants.ts +0 -184
- package/node_modules/@vellumai/gateway-client/node_modules/@vellumai/service-contracts/src/rendering.ts +0 -135
- package/node_modules/@vellumai/service-contracts/src/__tests__/grants.test.ts +0 -686
- package/node_modules/@vellumai/service-contracts/src/grants.ts +0 -184
- package/node_modules/@vellumai/service-contracts/src/rendering.ts +0 -135
- package/src/__tests__/auto-analysis-end-to-end.test.ts +0 -621
- package/src/__tests__/auto-analysis-prompt.test.ts +0 -50
- package/src/__tests__/config-analysis.test.ts +0 -83
- package/src/__tests__/conversation-analysis-routes.test.ts +0 -156
- package/src/__tests__/credential-execution-approval-bridge.test.ts +0 -297
- package/src/config/schemas/analysis.ts +0 -32
- package/src/credential-execution/approval-bridge.ts +0 -320
- package/src/daemon/__tests__/conversation-lifecycle-auto-analyze.test.ts +0 -449
- package/src/plugins/defaults/memory/__tests__/find-analysis-conversation.test.ts +0 -197
- package/src/runtime/routes/conversation-analysis-routes.ts +0 -75
- package/src/runtime/services/__tests__/analyze-conversation.test.ts +0 -477
- package/src/runtime/services/__tests__/auto-analysis-enqueue.test.ts +0 -386
- package/src/runtime/services/__tests__/auto-analysis-prompt.test.ts +0 -53
- package/src/runtime/services/__tests__/conversation-analyze-job.test.ts +0 -213
- package/src/runtime/services/__tests__/manual-analysis-prompt.test.ts +0 -41
- package/src/runtime/services/analyze-conversation.ts +0 -334
- package/src/runtime/services/auto-analysis-enqueue.ts +0 -130
- package/src/runtime/services/auto-analysis-prompt.ts +0 -55
- package/src/runtime/services/conversation-analyze-job.ts +0 -53
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
// ---------------------------------------------------------------------------
|
|
2
|
+
// Bulk-write gate — process-wide FIFO serialization of bulk main-DB writers.
|
|
3
|
+
// ---------------------------------------------------------------------------
|
|
4
|
+
//
|
|
5
|
+
// The batched bulk writers (fork message-copy, conversation-row batch delete)
|
|
6
|
+
// each hold the main database's write lock only briefly per batch — but SQLite
|
|
7
|
+
// has a single writer, so two bulk streams running concurrently gain no
|
|
8
|
+
// throughput. They only convoy: every batch of each stream contends with the
|
|
9
|
+
// other's (waiting up to `busy_timeout`), and the inter-batch yield each
|
|
10
|
+
// stream inserts for foreground fairness is consumed by the sibling stream
|
|
11
|
+
// instead of the live user turn it was meant for. Concurrent streams are
|
|
12
|
+
// reachable because the memory jobs worker groups jobs by
|
|
13
|
+
// `(type, conversationId)` — retrospectives for two different conversations
|
|
14
|
+
// run in parallel.
|
|
15
|
+
//
|
|
16
|
+
// This gate serializes those streams within the process: one bulk writer runs
|
|
17
|
+
// at a time, the rest queue FIFO, and the write lock (plus the yields) go back
|
|
18
|
+
// to foreground writers. Waiters are bounded by the jobs worker's lane
|
|
19
|
+
// concurrency, and the durable jobs queue upstream coalesces to one pending
|
|
20
|
+
// row per conversation, so the gate cannot accumulate an unbounded backlog.
|
|
21
|
+
//
|
|
22
|
+
// Scope and discipline:
|
|
23
|
+
// - Per-process. The daemon and each worker process have their own gate;
|
|
24
|
+
// bulk writers live almost entirely in the memory worker, so cross-process
|
|
25
|
+
// overlap is rare.
|
|
26
|
+
// - Main DB only. Dedicated files (e.g. the logs DB) have their own write
|
|
27
|
+
// locks and must not queue behind main-DB streams.
|
|
28
|
+
// - Callers wrap only their batch loop — never an LLM call, a wake, or an
|
|
29
|
+
// open transaction — so the worst-case hold is one bulk pass, itself
|
|
30
|
+
// bounded by {@link BULK_BATCH_TIMEOUT_MS} per batch.
|
|
31
|
+
|
|
32
|
+
import { getLogger } from "../util/logger.js";
|
|
33
|
+
import { Mutex } from "../util/mutex.js";
|
|
34
|
+
|
|
35
|
+
const log = getLogger("bulk-write-gate");
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Per-batch subprocess timeout for gated bulk writers. `runAsyncSqlite`'s
|
|
39
|
+
* default cap (1 h) is sized for legitimately long single statements like
|
|
40
|
+
* `VACUUM`; a gated bulk batch is a sub-second write, so a batch anywhere near
|
|
41
|
+
* this bound is wedged (stale lock, dead disk) and must fail rather than hold
|
|
42
|
+
* the gate — and every queued bulk writer behind it — for the full default.
|
|
43
|
+
*/
|
|
44
|
+
export const BULK_BATCH_TIMEOUT_MS = 5 * 60 * 1000;
|
|
45
|
+
|
|
46
|
+
/** Gate waits longer than this are logged — the convoy-formation signal. */
|
|
47
|
+
const CONTENTION_LOG_THRESHOLD_MS = 1000;
|
|
48
|
+
|
|
49
|
+
const gate = new Mutex();
|
|
50
|
+
let heldBy: string | null = null;
|
|
51
|
+
|
|
52
|
+
/** Label of the bulk writer currently holding the gate, or null when free. */
|
|
53
|
+
export function bulkWriteGateHolder(): string | null {
|
|
54
|
+
return heldBy;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Run `fn` as the sole bulk main-DB writer in this process. Callers queue
|
|
59
|
+
* FIFO; the gate is released when `fn` settles (resolve or reject), so a
|
|
60
|
+
* throwing writer never wedges the queue.
|
|
61
|
+
*/
|
|
62
|
+
export async function withBulkWriteGate<T>(
|
|
63
|
+
label: string,
|
|
64
|
+
fn: () => Promise<T>,
|
|
65
|
+
): Promise<T> {
|
|
66
|
+
const waitStartMs = Date.now();
|
|
67
|
+
return await gate.withLock(async () => {
|
|
68
|
+
const waitedMs = Date.now() - waitStartMs;
|
|
69
|
+
if (waitedMs >= CONTENTION_LOG_THRESHOLD_MS) {
|
|
70
|
+
log.info(
|
|
71
|
+
{ label, waitedMs },
|
|
72
|
+
"bulk-write gate: waited for prior bulk writers",
|
|
73
|
+
);
|
|
74
|
+
}
|
|
75
|
+
heldBy = label;
|
|
76
|
+
try {
|
|
77
|
+
return await fn();
|
|
78
|
+
} finally {
|
|
79
|
+
heldBy = null;
|
|
80
|
+
}
|
|
81
|
+
});
|
|
82
|
+
}
|
|
@@ -16,9 +16,9 @@ export interface BootstrapConversationOptions {
|
|
|
16
16
|
/**
|
|
17
17
|
* When set, the new conversation is linked to its parent via the
|
|
18
18
|
* `fork_parent_conversation_id` column. Used by background jobs that
|
|
19
|
-
* spawn
|
|
20
|
-
*
|
|
21
|
-
*
|
|
19
|
+
* spawn conversations off a source conversation (memory-retrospective)
|
|
20
|
+
* so the parent → child relationship is queryable later (e.g. "find the
|
|
21
|
+
* most recent retrospective for this source").
|
|
22
22
|
*/
|
|
23
23
|
forkParentConversationId?: string;
|
|
24
24
|
}
|
|
@@ -14,6 +14,7 @@ import {
|
|
|
14
14
|
like,
|
|
15
15
|
lt,
|
|
16
16
|
lte,
|
|
17
|
+
notInArray,
|
|
17
18
|
or,
|
|
18
19
|
sql,
|
|
19
20
|
} from "drizzle-orm";
|
|
@@ -48,7 +49,6 @@ import {
|
|
|
48
49
|
deleteOrphanAttachments,
|
|
49
50
|
linkAttachmentToMessage,
|
|
50
51
|
} from "./attachments-store.js";
|
|
51
|
-
import { AUTO_ANALYSIS_SOURCE } from "./auto-analysis-constants.js";
|
|
52
52
|
import {
|
|
53
53
|
appendCompactionEvent,
|
|
54
54
|
forkCompactionLedger,
|
|
@@ -67,7 +67,10 @@ import {
|
|
|
67
67
|
import { ensureDisplayOrderMigration } from "./conversation-display-order-migration.js";
|
|
68
68
|
import { ensureGroupMigration } from "./conversation-group-migration.js";
|
|
69
69
|
import { deleteConversationRowsInBatches } from "./conversation-row-batch-delete.js";
|
|
70
|
-
import
|
|
70
|
+
import {
|
|
71
|
+
BACKGROUND_CONVERSATION_TYPES,
|
|
72
|
+
type ConversationCreateType,
|
|
73
|
+
} from "./conversation-types.js";
|
|
71
74
|
import { runAsyncSqlite } from "./db-async-query.js";
|
|
72
75
|
import {
|
|
73
76
|
type DrizzleDb,
|
|
@@ -379,7 +382,6 @@ export interface ConversationRow {
|
|
|
379
382
|
slackContextCompactionWatermarkAt: number | null;
|
|
380
383
|
conversationType: string;
|
|
381
384
|
source: string;
|
|
382
|
-
memoryScopeId: string;
|
|
383
385
|
originChannel: string | null;
|
|
384
386
|
originInterface: string | null;
|
|
385
387
|
forkParentConversationId: string | null;
|
|
@@ -417,7 +419,6 @@ export const parseConversation = createRowMapper<
|
|
|
417
419
|
slackContextCompactionWatermarkAt: "slackContextCompactionWatermarkAt",
|
|
418
420
|
conversationType: "conversationType",
|
|
419
421
|
source: "source",
|
|
420
|
-
memoryScopeId: "memoryScopeId",
|
|
421
422
|
originChannel: "originChannel",
|
|
422
423
|
originInterface: "originInterface",
|
|
423
424
|
forkParentConversationId: "forkParentConversationId",
|
|
@@ -707,7 +708,6 @@ export function createConversation(
|
|
|
707
708
|
const groupId = opts.groupId;
|
|
708
709
|
// Time-ordered UUIDv7 for server-minted conversation ids (see message id).
|
|
709
710
|
const id = opts.id ?? uuidv7();
|
|
710
|
-
const memoryScopeId = "default";
|
|
711
711
|
|
|
712
712
|
// Ensure group_id column exists for deterministic schema readiness,
|
|
713
713
|
// even when this conversation has no groupId (a subsequent query or
|
|
@@ -732,7 +732,6 @@ export function createConversation(
|
|
|
732
732
|
slackContextCompactionWatermarkAt: null as number | null,
|
|
733
733
|
conversationType,
|
|
734
734
|
source,
|
|
735
|
-
memoryScopeId,
|
|
736
735
|
scheduleJobId: opts.scheduleJobId ?? null,
|
|
737
736
|
forkParentConversationId: opts.forkParentConversationId ?? null,
|
|
738
737
|
// Snapshot↔stream alignment baseline, captured at the creation instant.
|
|
@@ -853,41 +852,9 @@ export function countConversationsByScheduleJobId(
|
|
|
853
852
|
);
|
|
854
853
|
}
|
|
855
854
|
|
|
856
|
-
/**
|
|
857
|
-
* Find the rolling analysis conversation for a given source conversation,
|
|
858
|
-
* or null if none exists yet. Used by the auto-analyze loop to append
|
|
859
|
-
* to an existing analysis conversation rather than creating a new one
|
|
860
|
-
* each time the analyze job fires.
|
|
861
|
-
*
|
|
862
|
-
* Returns the most recently updated match if multiple exist (defensive —
|
|
863
|
-
* shouldn't happen in normal operation but the contract is well-defined).
|
|
864
|
-
*
|
|
865
|
-
* Hits `idx_conversations_fork_parent_conversation_id` for the
|
|
866
|
-
* `forkParentConversationId` lookup.
|
|
867
|
-
*/
|
|
868
|
-
export function findAnalysisConversationFor(
|
|
869
|
-
parentConversationId: string,
|
|
870
|
-
): { id: string } | null {
|
|
871
|
-
const db = getDb();
|
|
872
|
-
const row = db
|
|
873
|
-
.select({ id: conversations.id })
|
|
874
|
-
.from(conversations)
|
|
875
|
-
.where(
|
|
876
|
-
and(
|
|
877
|
-
eq(conversations.source, AUTO_ANALYSIS_SOURCE),
|
|
878
|
-
eq(conversations.forkParentConversationId, parentConversationId),
|
|
879
|
-
),
|
|
880
|
-
)
|
|
881
|
-
.orderBy(desc(conversations.updatedAt))
|
|
882
|
-
.limit(1)
|
|
883
|
-
.get();
|
|
884
|
-
return row ? { id: row.id } : null;
|
|
885
|
-
}
|
|
886
|
-
|
|
887
855
|
/**
|
|
888
856
|
* Returns the `source` column for the given conversation, or null if
|
|
889
|
-
* not found. Tiny convenience used by the
|
|
890
|
-
* auto-analyze loop.
|
|
857
|
+
* not found. Tiny convenience used by the auto-analysis legacy-row guard.
|
|
891
858
|
*/
|
|
892
859
|
export function getConversationSource(conversationId: string): string | null {
|
|
893
860
|
const db = getDb();
|
|
@@ -1157,15 +1124,26 @@ interface PopulateForkContentsArgs {
|
|
|
1157
1124
|
/** Source→fork message-id map for every copied row. */
|
|
1158
1125
|
forkedMessageIds: Map<string, string>;
|
|
1159
1126
|
latestForkedAssistant: { messageId: string; messageAt: number } | null;
|
|
1160
|
-
/**
|
|
1127
|
+
/**
|
|
1128
|
+
* True when the fork branches from the source's tip, so its rendered window
|
|
1129
|
+
* equals the source's and the wholesale memory-state carry is valid.
|
|
1130
|
+
*/
|
|
1161
1131
|
isFullHistoryFork: boolean;
|
|
1162
1132
|
/**
|
|
1163
|
-
* Count of leading
|
|
1164
|
-
* (0 when the
|
|
1165
|
-
*
|
|
1166
|
-
*
|
|
1133
|
+
* Count of leading `messagesToCopy` entries behind the compaction event this
|
|
1134
|
+
* fork inherits (0 when the copied range already starts at the visible
|
|
1135
|
+
* window, or the fork branches from uncompacted history). Memory-slug
|
|
1136
|
+
* seeding skips this prefix, since rows behind the fork's summary are not
|
|
1137
|
+
* rendered and must stay re-injectable.
|
|
1167
1138
|
*/
|
|
1168
1139
|
inheritedCompactedMessageCount: number;
|
|
1140
|
+
/**
|
|
1141
|
+
* When true, the source's compaction-event ledger is not copied into the
|
|
1142
|
+
* fork. Set by the retrospective fork whenever it inherits a compaction —
|
|
1143
|
+
* it seeds its own count-adjusted event instead, since the source events'
|
|
1144
|
+
* `compactedMessageCount` values index source-space row positions.
|
|
1145
|
+
*/
|
|
1146
|
+
skipCompactionLedgerCopy?: boolean;
|
|
1169
1147
|
/**
|
|
1170
1148
|
* When provided, a disk-sync entry is appended per copied message for the
|
|
1171
1149
|
* caller to flush after commit. Omitted by the retrospective fork, whose
|
|
@@ -1198,6 +1176,7 @@ function populateForkContentsInProcess(args: PopulateForkContentsArgs): void {
|
|
|
1198
1176
|
latestForkedAssistant,
|
|
1199
1177
|
isFullHistoryFork,
|
|
1200
1178
|
inheritedCompactedMessageCount,
|
|
1179
|
+
skipCompactionLedgerCopy,
|
|
1201
1180
|
diskSyncQueue,
|
|
1202
1181
|
} = args;
|
|
1203
1182
|
const db = getDb();
|
|
@@ -1302,13 +1281,17 @@ function populateForkContentsInProcess(args: PopulateForkContentsArgs): void {
|
|
|
1302
1281
|
});
|
|
1303
1282
|
|
|
1304
1283
|
// Carry the source's compaction events that predate the fork boundary so the
|
|
1305
|
-
// fork owns a correct ledger for its own future forks/compactions.
|
|
1306
|
-
|
|
1307
|
-
|
|
1308
|
-
|
|
1309
|
-
|
|
1310
|
-
|
|
1311
|
-
|
|
1284
|
+
// fork owns a correct ledger for its own future forks/compactions. The
|
|
1285
|
+
// tail-only retrospective fork opts out and seeds a single count-adjusted
|
|
1286
|
+
// event of its own instead.
|
|
1287
|
+
if (!skipCompactionLedgerCopy) {
|
|
1288
|
+
forkCompactionLedger(
|
|
1289
|
+
db,
|
|
1290
|
+
sourceConversationId,
|
|
1291
|
+
fork.id,
|
|
1292
|
+
messagesToCopy.at(-1)?.createdAt ?? null,
|
|
1293
|
+
);
|
|
1294
|
+
}
|
|
1312
1295
|
}
|
|
1313
1296
|
|
|
1314
1297
|
/**
|
|
@@ -1335,17 +1318,28 @@ function latestForkedAssistantFrom(
|
|
|
1335
1318
|
|
|
1336
1319
|
/**
|
|
1337
1320
|
* Async variant of {@link forkConversation} for the memory-retrospective job,
|
|
1338
|
-
* which forks the
|
|
1339
|
-
* conversation on a hot path that must not stall the daemon.
|
|
1321
|
+
* which forks the source conversation's visible window into a throwaway
|
|
1322
|
+
* background conversation on a hot path that must not stall the daemon.
|
|
1340
1323
|
*
|
|
1341
|
-
*
|
|
1342
|
-
*
|
|
1343
|
-
*
|
|
1344
|
-
*
|
|
1345
|
-
*
|
|
1346
|
-
* the
|
|
1347
|
-
*
|
|
1348
|
-
*
|
|
1324
|
+
* Only rows at-or-after the inherited compaction boundary are copied. The
|
|
1325
|
+
* retrospective wake always runs under guardian trust, whose history render
|
|
1326
|
+
* slices `contextCompactedMessageCount` rows off the front and prepends the
|
|
1327
|
+
* summary on `contextSummary` presence alone — so the fork carries the
|
|
1328
|
+
* inherited summary with a compacted count of 0 and renders identically to
|
|
1329
|
+
* the source (summary + tail) without materializing rows the agent cannot
|
|
1330
|
+
* see. The user-facing {@link forkConversation} keeps the full physical
|
|
1331
|
+
* history: user forks are long-lived and browsable, and untrusted-actor
|
|
1332
|
+
* views render the persisted history unsliced.
|
|
1333
|
+
*
|
|
1334
|
+
* The dominant cost — copying the visible tail's message rows — runs OFF the
|
|
1335
|
+
* event loop in a `sqlite3` subprocess (see
|
|
1336
|
+
* {@link copyForkMessagesViaSubprocess}), so `/healthz` and gateway IPC stay
|
|
1337
|
+
* responsive during the copy. The cheap tail (conversation row, attachment
|
|
1338
|
+
* relink, memory-state seeding) runs in-process and reuses
|
|
1339
|
+
* {@link populateForkContentsInProcess}, the same helper the synchronous fork
|
|
1340
|
+
* uses, so the two paths cannot drift on that logic. The cutoff/boundary
|
|
1341
|
+
* computation mirrors {@link forkConversation} and is pinned by a parity
|
|
1342
|
+
* test.
|
|
1349
1343
|
*
|
|
1350
1344
|
* The disk-view projection (`syncMessageToDisk`) is intentionally skipped: the
|
|
1351
1345
|
* fork is GC'd after the retrospective pass and never browsed, and the agent
|
|
@@ -1373,6 +1367,12 @@ export async function forkConversationForRetrospective(params: {
|
|
|
1373
1367
|
}
|
|
1374
1368
|
|
|
1375
1369
|
const sourceMessages = getMessages(conversationId);
|
|
1370
|
+
// The render path hides the first `contextCompactedMessageCount` rows in
|
|
1371
|
+
// THIS load order (`getMessages`, `createdAt` only) — capture it before the
|
|
1372
|
+
// cutoff re-sort below so the tail-only drop-set matches what the source
|
|
1373
|
+
// actually renders even when `createdAt` ties straddle the compaction
|
|
1374
|
+
// boundary.
|
|
1375
|
+
const loadOrderIds = sourceMessages.map((message) => message.id);
|
|
1376
1376
|
if (throughMessageId != null) {
|
|
1377
1377
|
// Re-sort on `(createdAt, id)` so the cutoff slice agrees with the cursor
|
|
1378
1378
|
// the caller chose it from — see the matching note in `forkConversation`.
|
|
@@ -1422,6 +1422,21 @@ export async function forkConversationForRetrospective(params: {
|
|
|
1422
1422
|
const inheritsLatestCompaction =
|
|
1423
1423
|
inheritedCompaction != null &&
|
|
1424
1424
|
inheritedCompaction.compactedAt === sourceConversation.contextCompactedAt;
|
|
1425
|
+
// Copy only the visible tail: rows behind the inherited summary are never
|
|
1426
|
+
// rendered on this fork (the retrospective wake runs under guardian trust,
|
|
1427
|
+
// which slices `contextCompactedMessageCount` rows off the front), so
|
|
1428
|
+
// copying them would hold the write lock for rows the agent cannot see.
|
|
1429
|
+
// The drop-set is the first `compactedMessageCount` rows in LOAD order —
|
|
1430
|
+
// the exact rows the source's render hides — rather than a positional
|
|
1431
|
+
// slice of the re-sorted array, whose tie order can differ at the
|
|
1432
|
+
// boundary. `slice` self-clamps when the ledger count exceeds the row
|
|
1433
|
+
// count, mirroring the render path's clamp.
|
|
1434
|
+
const hiddenRowIds = new Set(
|
|
1435
|
+
loadOrderIds.slice(0, inheritedCompaction?.compactedMessageCount ?? 0),
|
|
1436
|
+
);
|
|
1437
|
+
const rowsToCopy = messagesToCopy.filter(
|
|
1438
|
+
(message) => !hiddenRowIds.has(message.id),
|
|
1439
|
+
);
|
|
1425
1440
|
const forkParentMessageId = messagesToCopy.at(-1)?.id ?? null;
|
|
1426
1441
|
const forkTitle =
|
|
1427
1442
|
params.title ?? `${sourceConversation.title ?? "Untitled"} (Fork)`;
|
|
@@ -1429,7 +1444,7 @@ export async function forkConversationForRetrospective(params: {
|
|
|
1429
1444
|
|
|
1430
1445
|
// Pre-generate the id map in JS so the same map drives the off-loop copy and
|
|
1431
1446
|
// the in-process attachment relink that follows.
|
|
1432
|
-
const idPairs: ForkIdPair[] =
|
|
1447
|
+
const idPairs: ForkIdPair[] = rowsToCopy.map((message) => ({
|
|
1433
1448
|
oldId: message.id,
|
|
1434
1449
|
newId: uuidv7(),
|
|
1435
1450
|
}));
|
|
@@ -1454,9 +1469,19 @@ export async function forkConversationForRetrospective(params: {
|
|
|
1454
1469
|
.set({
|
|
1455
1470
|
forkParentConversationId: sourceConversation.id,
|
|
1456
1471
|
forkParentMessageId,
|
|
1472
|
+
// Stamped at creation so the startup orphan sweep (which only
|
|
1473
|
+
// considers rows with a non-null `lastMessageAt`) can age this
|
|
1474
|
+
// fork even if the daemon crashes before the copy or the
|
|
1475
|
+
// retrospective instruction lands — including the empty-tail
|
|
1476
|
+
// fork, which copies no rows at all. Phase 3 re-derives the same
|
|
1477
|
+
// value from the copied rows when the tail is non-empty.
|
|
1478
|
+
lastMessageAt: boundaryMessageCreatedAt,
|
|
1457
1479
|
contextSummary: inheritedCompaction?.summary ?? null,
|
|
1458
|
-
|
|
1459
|
-
|
|
1480
|
+
// Zero of the fork's own rows sit behind the boundary (the
|
|
1481
|
+
// compacted prefix is not copied). The summary still renders:
|
|
1482
|
+
// the history render keys on `contextSummary` presence, not on
|
|
1483
|
+
// this count.
|
|
1484
|
+
contextCompactedMessageCount: 0,
|
|
1460
1485
|
contextCompactedAt: inheritedCompaction?.compactedAt ?? null,
|
|
1461
1486
|
slackContextCompactionWatermarkTs: inheritsLatestCompaction
|
|
1462
1487
|
? sourceConversation.slackContextCompactionWatermarkTs
|
|
@@ -1494,22 +1519,59 @@ export async function forkConversationForRetrospective(params: {
|
|
|
1494
1519
|
|
|
1495
1520
|
// Phase 3 (in-process): attachments + memory-state seeding, reusing the
|
|
1496
1521
|
// same helper as the synchronous fork. Disk-view projection is skipped.
|
|
1522
|
+
//
|
|
1523
|
+
// The populate transaction reads (attachment links) before its first
|
|
1524
|
+
// write, so a deferred BEGIN would take its snapshot as a reader and any
|
|
1525
|
+
// concurrent writer committing before the first write fails the
|
|
1526
|
+
// read→write upgrade with SQLITE_BUSY_SNAPSHOT — a hard error
|
|
1527
|
+
// `busy_timeout` cannot wait out, which would discard the entire batch
|
|
1528
|
+
// copy from phase 2. `behavior: "immediate"` acquires the write lock at
|
|
1529
|
+
// BEGIN so the snapshot postdates it, and the retry absorbs residual
|
|
1530
|
+
// contention: the transaction rolls back atomically, so re-running it is
|
|
1531
|
+
// safe.
|
|
1497
1532
|
const latestForkedAssistant = latestForkedAssistantFrom(
|
|
1498
|
-
|
|
1533
|
+
rowsToCopy,
|
|
1499
1534
|
forkedMessageIds,
|
|
1500
1535
|
);
|
|
1501
|
-
|
|
1502
|
-
|
|
1503
|
-
|
|
1504
|
-
|
|
1505
|
-
|
|
1506
|
-
|
|
1507
|
-
|
|
1508
|
-
|
|
1509
|
-
|
|
1510
|
-
|
|
1511
|
-
|
|
1512
|
-
|
|
1536
|
+
await withSqliteRetry(
|
|
1537
|
+
() =>
|
|
1538
|
+
db.transaction(
|
|
1539
|
+
() => {
|
|
1540
|
+
populateForkContentsInProcess({
|
|
1541
|
+
fork,
|
|
1542
|
+
sourceConversationId: sourceConversation.id,
|
|
1543
|
+
messagesToCopy: rowsToCopy,
|
|
1544
|
+
forkedMessageIds,
|
|
1545
|
+
latestForkedAssistant,
|
|
1546
|
+
isFullHistoryFork:
|
|
1547
|
+
copyBoundaryIndex === sourceMessages.length - 1,
|
|
1548
|
+
// The copied range already starts at the visible window.
|
|
1549
|
+
inheritedCompactedMessageCount: 0,
|
|
1550
|
+
skipCompactionLedgerCopy: inheritedCompaction != null,
|
|
1551
|
+
});
|
|
1552
|
+
// The fork owns none of the source's ledger events — their
|
|
1553
|
+
// counts index source-space row positions, and this fork row
|
|
1554
|
+
// stores a count of 0. Seed a single event mirroring the fork
|
|
1555
|
+
// row's compaction fields whenever a compaction is inherited
|
|
1556
|
+
// (even when the hidden prefix fell outside the cutoff and
|
|
1557
|
+
// nothing was dropped), so the ledger and the row cache agree
|
|
1558
|
+
// and a fork of this fork inherits the summary with the
|
|
1559
|
+
// fork-local count. With no inherited compaction the default
|
|
1560
|
+
// ledger copy is a natural no-op (no source event is
|
|
1561
|
+
// at-or-before the boundary). Rolls back with the transaction,
|
|
1562
|
+
// so the retry unit stays atomic.
|
|
1563
|
+
if (inheritedCompaction) {
|
|
1564
|
+
appendCompactionEvent(fork.id, {
|
|
1565
|
+
compactedAt: inheritedCompaction.compactedAt,
|
|
1566
|
+
summary: inheritedCompaction.summary,
|
|
1567
|
+
compactedMessageCount: 0,
|
|
1568
|
+
});
|
|
1569
|
+
}
|
|
1570
|
+
},
|
|
1571
|
+
{ behavior: "immediate" },
|
|
1572
|
+
),
|
|
1573
|
+
{ op: "forkConversationForRetrospective.populate" },
|
|
1574
|
+
);
|
|
1513
1575
|
|
|
1514
1576
|
const persistedFork = getConversation(fork.id);
|
|
1515
1577
|
if (!persistedFork) {
|
|
@@ -1816,7 +1878,6 @@ export async function addMessage(
|
|
|
1816
1878
|
role: message.role,
|
|
1817
1879
|
content: message.content,
|
|
1818
1880
|
createdAt: message.createdAt,
|
|
1819
|
-
scopeId: "default",
|
|
1820
1881
|
provenanceTrustClass,
|
|
1821
1882
|
automated,
|
|
1822
1883
|
},
|
|
@@ -2221,12 +2282,29 @@ export function getLastUserTimestampBefore(
|
|
|
2221
2282
|
* newest `role = "user"` row rather than a scan of the whole (potentially
|
|
2222
2283
|
* multi-GB) table.
|
|
2223
2284
|
*/
|
|
2224
|
-
|
|
2285
|
+
/**
|
|
2286
|
+
* Timestamp of the newest user-role message in an interactive
|
|
2287
|
+
* (non-background) conversation, or 0 when none exists. Background machinery
|
|
2288
|
+
* writes user-role rows of its own — the memory-retrospective instruction
|
|
2289
|
+
* message, scheduled/heartbeat wake hints — inside background/scheduled
|
|
2290
|
+
* conversations, so an unfiltered max would keep an always-on install
|
|
2291
|
+
* permanently "active" for consumers gating on human quiet (the
|
|
2292
|
+
* db-maintenance quiet period).
|
|
2293
|
+
*/
|
|
2294
|
+
export function getLastInteractiveUserMessageTimestamp(): number {
|
|
2225
2295
|
const db = getDb();
|
|
2226
2296
|
const row = db
|
|
2227
2297
|
.select({ createdAt: messages.createdAt })
|
|
2228
2298
|
.from(messages)
|
|
2229
|
-
.
|
|
2299
|
+
.innerJoin(conversations, eq(messages.conversationId, conversations.id))
|
|
2300
|
+
.where(
|
|
2301
|
+
and(
|
|
2302
|
+
eq(messages.role, "user"),
|
|
2303
|
+
notInArray(conversations.conversationType, [
|
|
2304
|
+
...BACKGROUND_CONVERSATION_TYPES,
|
|
2305
|
+
]),
|
|
2306
|
+
),
|
|
2307
|
+
)
|
|
2230
2308
|
.orderBy(desc(messages.createdAt))
|
|
2231
2309
|
.limit(1)
|
|
2232
2310
|
.get();
|
|
@@ -217,7 +217,6 @@ export function getOrCreateConversation(
|
|
|
217
217
|
const conversationId = uuid();
|
|
218
218
|
const customTitle = opts?.title?.trim();
|
|
219
219
|
const title = customTitle || GENERATING_TITLE;
|
|
220
|
-
const memoryScopeId = "default";
|
|
221
220
|
// Snapshot↔stream alignment baseline, captured at the creation instant
|
|
222
221
|
// (same seed as `createConversation`; 0 is stored as NULL).
|
|
223
222
|
const initialSeq = getCurrentSeq();
|
|
@@ -241,7 +240,6 @@ export function getOrCreateConversation(
|
|
|
241
240
|
contextCompactedMessageCount: 0,
|
|
242
241
|
contextCompactedAt: null,
|
|
243
242
|
conversationType,
|
|
244
|
-
memoryScopeId,
|
|
245
243
|
})
|
|
246
244
|
.run();
|
|
247
245
|
|
|
@@ -34,6 +34,7 @@
|
|
|
34
34
|
|
|
35
35
|
import { setTimeout as sleep } from "node:timers/promises";
|
|
36
36
|
|
|
37
|
+
import { BULK_BATCH_TIMEOUT_MS, withBulkWriteGate } from "./bulk-write-gate.js";
|
|
37
38
|
import {
|
|
38
39
|
type AsyncSqliteBackend,
|
|
39
40
|
type AsyncSqliteResult,
|
|
@@ -170,9 +171,23 @@ export async function deleteConversationRowsInBatches(
|
|
|
170
171
|
runOptions.forceBackend = "in-process-blocking";
|
|
171
172
|
}
|
|
172
173
|
if (options.dbPath !== undefined) {
|
|
174
|
+
// A dedicated file (e.g. the logs DB) has its own write lock, so its
|
|
175
|
+
// drain must not queue behind — or hold up — main-DB bulk streams.
|
|
173
176
|
runOptions.dbPath = options.dbPath;
|
|
177
|
+
return await drainBatches(options, batchSize, runOptions);
|
|
174
178
|
}
|
|
175
179
|
|
|
180
|
+
return await withBulkWriteGate(
|
|
181
|
+
`conversation-row-delete:${options.table}:${options.conversationId}`,
|
|
182
|
+
() => drainBatches(options, batchSize, runOptions),
|
|
183
|
+
);
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
async function drainBatches(
|
|
187
|
+
options: DeleteConversationRowsOptions,
|
|
188
|
+
batchSize: number,
|
|
189
|
+
runOptions: RunAsyncSqliteOptions,
|
|
190
|
+
): Promise<AsyncSqliteResult> {
|
|
176
191
|
let totalElapsedMs = 0;
|
|
177
192
|
let backend: AsyncSqliteBackend = "in-process-blocking";
|
|
178
193
|
|
|
@@ -190,7 +205,7 @@ export async function deleteConversationRowsInBatches(
|
|
|
190
205
|
const result = await runAsyncSqlite(
|
|
191
206
|
sql,
|
|
192
207
|
`conversation-row-delete:${options.table}:${options.conversationId}`,
|
|
193
|
-
runOptions,
|
|
208
|
+
{ ...runOptions, timeoutMs: BULK_BATCH_TIMEOUT_MS },
|
|
194
209
|
);
|
|
195
210
|
totalElapsedMs += result.elapsedMs;
|
|
196
211
|
backend = result.backend;
|
|
@@ -11,10 +11,21 @@ export type ConversationCreateType = "standard" | "background" | "scheduled";
|
|
|
11
11
|
/** Read-side alias of {@link ConversationCreateType}. */
|
|
12
12
|
export type ConversationType = ConversationCreateType;
|
|
13
13
|
|
|
14
|
+
/**
|
|
15
|
+
* Conversation types created by background machinery (heartbeat runs,
|
|
16
|
+
* scheduled runs, retrospective forks) rather than by a person. Exported as a
|
|
17
|
+
* list so SQL filters (e.g. `notInArray`) share the same set as the predicate
|
|
18
|
+
* below.
|
|
19
|
+
*/
|
|
20
|
+
export const BACKGROUND_CONVERSATION_TYPES = [
|
|
21
|
+
"background",
|
|
22
|
+
"scheduled",
|
|
23
|
+
] as const satisfies readonly ConversationType[];
|
|
24
|
+
|
|
14
25
|
// Tolerant of null/undefined/unknown strings so it can be called directly on
|
|
15
26
|
// raw DB column values without pre-validation.
|
|
16
27
|
export function isBackgroundConversationType(
|
|
17
28
|
t: ConversationType | string | null | undefined,
|
|
18
29
|
): boolean {
|
|
19
|
-
return
|
|
30
|
+
return (BACKGROUND_CONVERSATION_TYPES as readonly string[]).includes(t ?? "");
|
|
20
31
|
}
|
|
@@ -193,11 +193,18 @@ async function runViaCli(
|
|
|
193
193
|
stderr: "pipe",
|
|
194
194
|
});
|
|
195
195
|
|
|
196
|
-
// Match the
|
|
197
|
-
//
|
|
198
|
-
//
|
|
199
|
-
//
|
|
200
|
-
|
|
196
|
+
// Match the daemon connection's pragmas (`applyConnectionPragmas`) so this
|
|
197
|
+
// subprocess writes like every other connection. `busy_timeout` makes it
|
|
198
|
+
// wait for — rather than instantly fail against — a lock held by the
|
|
199
|
+
// still-running in-process connection (and vice versa).
|
|
200
|
+
// `synchronous=NORMAL` overrides the CLI default (FULL), which would fsync
|
|
201
|
+
// the WAL inside every commit's write-lock window and stretch bulk-batch
|
|
202
|
+
// lock holds under I/O pressure: in WAL mode, NORMAL commits become durable
|
|
203
|
+
// at checkpoint (an OS/power crash can lose the last commits, never
|
|
204
|
+
// corrupt) — the durability posture every daemon write already has, so
|
|
205
|
+
// FULL here buys no end-to-end guarantee. Prepended to the piped SQL so
|
|
206
|
+
// both take effect before the statement runs.
|
|
207
|
+
const sqlWithPragma = `PRAGMA busy_timeout=${SQLITE_BUSY_TIMEOUT_MS};\nPRAGMA synchronous=NORMAL;\n${sql}`;
|
|
201
208
|
|
|
202
209
|
// Write the SQL and close stdin so sqlite3 sees EOF and exits.
|
|
203
210
|
proc.stdin.write(sqlWithPragma + "\n");
|
|
@@ -280,11 +287,13 @@ async function runInProcessBlocking(
|
|
|
280
287
|
let sqlite: Database;
|
|
281
288
|
if (usesDedicatedFile) {
|
|
282
289
|
transient = new Database(options.dbPath ?? getDbPath());
|
|
283
|
-
// Match the daemon connection's busy_timeout
|
|
284
|
-
// connection waits for
|
|
285
|
-
//
|
|
286
|
-
// in the else branch already
|
|
290
|
+
// Match the daemon connection's busy_timeout and synchronous pragmas so
|
|
291
|
+
// this transient connection waits for locks and commits like every
|
|
292
|
+
// other writer (see the runViaCli prelude for the synchronous=NORMAL
|
|
293
|
+
// rationale). (The daemon connection reused in the else branch already
|
|
294
|
+
// has both set via applyConnectionPragmas.)
|
|
287
295
|
transient.exec(`PRAGMA busy_timeout=${SQLITE_BUSY_TIMEOUT_MS}`);
|
|
296
|
+
transient.exec("PRAGMA synchronous=NORMAL");
|
|
288
297
|
for (const a of options.attach ?? []) {
|
|
289
298
|
transient.exec(
|
|
290
299
|
`ATTACH DATABASE '${a.path.replace(/'/g, "''")}' AS ${a.alias}`,
|
|
@@ -104,11 +104,21 @@ function applyConnectionPragmas(sqlite: Database): void {
|
|
|
104
104
|
sqlite.exec("PRAGMA foreign_keys = ON");
|
|
105
105
|
sqlite.exec("PRAGMA cache_size=-256000");
|
|
106
106
|
sqlite.exec("PRAGMA temp_store=MEMORY");
|
|
107
|
+
// Checkpointing alone never shrinks the WAL file — a fully-backfilled WAL
|
|
108
|
+
// is reused from offset 0 at its high-water size, so a single write burst
|
|
109
|
+
// otherwise leaves a permanently huge file (disk cost, plus a long recovery
|
|
110
|
+
// scan on the first open after a hard crash). With a size limit, any WAL
|
|
111
|
+
// reset also truncates the file to at most this many bytes. 64 MB
|
|
112
|
+
// comfortably exceeds the WAL's steady-state hover (the ~4 MB autocheckpoint
|
|
113
|
+
// threshold), so normal writes never pay file re-extension.
|
|
114
|
+
sqlite.exec("PRAGMA journal_size_limit=67108864");
|
|
107
115
|
}
|
|
108
116
|
|
|
109
117
|
export function getDb(): DrizzleDb {
|
|
110
118
|
const existing = getStoredDb<DrizzleDb>("main");
|
|
111
|
-
if (existing)
|
|
119
|
+
if (existing) {
|
|
120
|
+
return existing;
|
|
121
|
+
}
|
|
112
122
|
|
|
113
123
|
assertTestDbIsIsolated();
|
|
114
124
|
ensureDataDir();
|
|
@@ -193,7 +203,9 @@ function openDedicatedDb(
|
|
|
193
203
|
*/
|
|
194
204
|
export function getLogsDb(): DrizzleDb | null {
|
|
195
205
|
const existing = getStoredDb<DrizzleDb>("logs");
|
|
196
|
-
if (existing)
|
|
206
|
+
if (existing) {
|
|
207
|
+
return existing;
|
|
208
|
+
}
|
|
197
209
|
return openDedicatedDb("logs", getLogsDbPath());
|
|
198
210
|
}
|
|
199
211
|
|
|
@@ -210,7 +222,9 @@ export function getLogsSqlite(): Database | null {
|
|
|
210
222
|
*/
|
|
211
223
|
export function getMemoryDb(): DrizzleDb | null {
|
|
212
224
|
const existing = getStoredDb<DrizzleDb>("memory");
|
|
213
|
-
if (existing)
|
|
225
|
+
if (existing) {
|
|
226
|
+
return existing;
|
|
227
|
+
}
|
|
214
228
|
return openDedicatedDb("memory", getMemoryDbPath());
|
|
215
229
|
}
|
|
216
230
|
|
|
@@ -227,7 +241,9 @@ export function getMemorySqlite(): Database | null {
|
|
|
227
241
|
*/
|
|
228
242
|
export function getTelemetryDb(): DrizzleDb | null {
|
|
229
243
|
const existing = getStoredDb<DrizzleDb>("telemetry");
|
|
230
|
-
if (existing)
|
|
244
|
+
if (existing) {
|
|
245
|
+
return existing;
|
|
246
|
+
}
|
|
231
247
|
return openDedicatedDb("telemetry", getTelemetryDbPath());
|
|
232
248
|
}
|
|
233
249
|
|