@hearsay-tools/squawk 0.18.0-dev.7816 → 0.18.0-dev.7825

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (128) hide show
  1. package/dist/activity/publisher.js +2 -2
  2. package/dist/activity/publisher.js.map +1 -1
  3. package/dist/activity/read-model.js +1 -1
  4. package/dist/activity/read-model.js.map +1 -1
  5. package/dist/activity/requests.d.ts +4 -2
  6. package/dist/activity/requests.js +1 -1
  7. package/dist/activity/requests.js.map +1 -1
  8. package/dist/artifacts/reports-index.d.ts +4 -7
  9. package/dist/artifacts/reports-index.js +7 -7
  10. package/dist/artifacts/reports-index.js.map +1 -1
  11. package/dist/ci-wait/controller.d.ts +42 -42
  12. package/dist/delegation/conversations.d.ts +6 -2
  13. package/dist/delegation/conversations.js +3 -2
  14. package/dist/delegation/conversations.js.map +1 -1
  15. package/dist/delegation/family-end.d.ts +4 -2
  16. package/dist/delegation/results.js +2 -2
  17. package/dist/delegation/results.js.map +1 -1
  18. package/dist/delegation/routes.d.ts +65 -65
  19. package/dist/delegation/routes.js +1 -1
  20. package/dist/delegation/routes.js.map +1 -1
  21. package/dist/delegation/scratch-cleanup.js +2 -2
  22. package/dist/delegation/scratch-cleanup.js.map +1 -1
  23. package/dist/delegation/service.js +2 -2
  24. package/dist/delegation/service.js.map +1 -1
  25. package/dist/delegation/transport.d.ts +65 -65
  26. package/dist/delegation/worker-cleanup.js +1 -1
  27. package/dist/delegation/worker-cleanup.js.map +1 -1
  28. package/dist/preview/host.d.ts +2 -1
  29. package/dist/preview/host.js +1 -1
  30. package/dist/preview/host.js.map +1 -1
  31. package/dist/project-migration/live.js +3 -3
  32. package/dist/project-migration/live.js.map +1 -1
  33. package/dist/runs/claim-families.d.ts +1 -1
  34. package/dist/runs/claim-families.js +1 -1
  35. package/dist/runs/lifecycle.d.ts +2 -1
  36. package/dist/runs/lifecycle.js.map +1 -1
  37. package/dist/runs/live-tasks.js +1 -1
  38. package/dist/runs/live-tasks.js.map +1 -1
  39. package/dist/runs/loaded-run-exits.d.ts +23 -0
  40. package/dist/runs/loaded-run-exits.js +46 -1
  41. package/dist/runs/loaded-run-exits.js.map +1 -1
  42. package/dist/runs/ports.d.ts +38 -14
  43. package/dist/runs/retention.d.ts +3 -1
  44. package/dist/runs/retention.js +5 -5
  45. package/dist/runs/retention.js.map +1 -1
  46. package/dist/runs/run-claims-topic.d.ts +130 -0
  47. package/dist/runs/run-claims-topic.js +258 -0
  48. package/dist/runs/run-claims-topic.js.map +1 -0
  49. package/dist/runs/run-claims.d.ts +1 -1
  50. package/dist/runs/run-claims.js +1 -1
  51. package/dist/runs/run-claims.js.map +1 -1
  52. package/dist/runs/run-database.d.ts +1 -1
  53. package/dist/runs/run-index.js +3 -1
  54. package/dist/runs/run-index.js.map +1 -1
  55. package/dist/runs/run-persistence.d.ts +150 -0
  56. package/dist/runs/run-persistence.js +396 -0
  57. package/dist/runs/run-persistence.js.map +1 -0
  58. package/dist/runs/run-pins.d.ts +38 -0
  59. package/dist/runs/run-pins.js +45 -0
  60. package/dist/runs/run-pins.js.map +1 -0
  61. package/dist/runs/run-references.d.ts +1 -1
  62. package/dist/runs/run-references.js +1 -1
  63. package/dist/runs/run-references.js.map +1 -1
  64. package/dist/runs/run-retention.d.ts +6 -2
  65. package/dist/runs/run-retention.js +11 -2
  66. package/dist/runs/run-retention.js.map +1 -1
  67. package/dist/runs/store-open.d.ts +45 -0
  68. package/dist/runs/store-open.js +89 -0
  69. package/dist/runs/store-open.js.map +1 -0
  70. package/dist/runs/store.d.ts +9 -209
  71. package/dist/runs/store.js +88 -802
  72. package/dist/runs/store.js.map +1 -1
  73. package/dist/runs/webhook.d.ts +3 -1
  74. package/dist/runs/webhook.js +2 -2
  75. package/dist/runs/webhook.js.map +1 -1
  76. package/dist/serve-boot.d.ts +2 -2
  77. package/dist/server/completion-actions.js +2 -2
  78. package/dist/server/completion-actions.js.map +1 -1
  79. package/dist/server/models-routes.d.ts +13 -13
  80. package/dist/server/project-run-files.d.ts +3 -1
  81. package/dist/server/project-run-files.js +3 -3
  82. package/dist/server/project-run-files.js.map +1 -1
  83. package/dist/server/provider-sign-in-routes.d.ts +2 -2
  84. package/dist/server/reports-api.d.ts +2 -2
  85. package/dist/server/run-checkout.d.ts +3 -1
  86. package/dist/server/run-checkout.js +3 -3
  87. package/dist/server/run-checkout.js.map +1 -1
  88. package/dist/server/run-event-feed.js +2 -2
  89. package/dist/server/run-event-feed.js.map +1 -1
  90. package/dist/server/runner-install-routes.d.ts +10 -10
  91. package/dist/server/server.d.ts +1593 -1593
  92. package/dist/server/server.js +9 -9
  93. package/dist/server/server.js.map +1 -1
  94. package/dist/server/start-server.js +1 -1
  95. package/dist/server/start-server.js.map +1 -1
  96. package/dist/workflows/run/continuation-acceptance.js +2 -2
  97. package/dist/workflows/run/continuation-acceptance.js.map +1 -1
  98. package/dist/workflows/run/family-reconciler.d.ts +2 -1
  99. package/dist/workflows/run/family-reconciler.js +2 -2
  100. package/dist/workflows/run/family-reconciler.js.map +1 -1
  101. package/dist/workflows/run/maintenance-claims.js +6 -6
  102. package/dist/workflows/run/maintenance-claims.js.map +1 -1
  103. package/dist/workflows/run/native-skill-input-queue.js +1 -1
  104. package/dist/workflows/run/native-skill-input-queue.js.map +1 -1
  105. package/dist/workflows/run/queued-revival.js +3 -3
  106. package/dist/workflows/run/queued-revival.js.map +1 -1
  107. package/dist/workflows/run/run-cancel.js +5 -5
  108. package/dist/workflows/run/run-cancel.js.map +1 -1
  109. package/dist/workflows/run/run-finish.js +1 -1
  110. package/dist/workflows/run/run-finish.js.map +1 -1
  111. package/dist/workflows/run/run-recovery.js +3 -3
  112. package/dist/workflows/run/run-recovery.js.map +1 -1
  113. package/dist/workflows/run/run-settlement.js +5 -5
  114. package/dist/workflows/run/run-settlement.js.map +1 -1
  115. package/dist/workflows/run/step-loop.js +4 -4
  116. package/dist/workflows/run/step-loop.js.map +1 -1
  117. package/dist/workflows/run/turn-nudges.js +1 -1
  118. package/dist/workflows/run/turn-nudges.js.map +1 -1
  119. package/dist/workflows/run/turn-settler.js +1 -1
  120. package/dist/workflows/run/turn-settler.js.map +1 -1
  121. package/dist/workflows/run/usage-accounting.js +1 -1
  122. package/dist/workflows/run/usage-accounting.js.map +1 -1
  123. package/dist/workflows/run.js +7 -7
  124. package/dist/workflows/run.js.map +1 -1
  125. package/package.json +4 -4
  126. package/scripts/benchmark-family-reconcile.ts +1 -1
  127. package/scripts/benchmark-run-store.ts +5 -5
  128. package/scripts/benchmark-workspace-events.ts +2 -2
@@ -1,9 +1,8 @@
1
1
  import { legacyIndexRows, readableSavedRunner, upgradeLegacyRunRow, withKeptFields } from './legacy-run-rows.js';
2
- import { dataReadDirs, runDataDir } from '../project-paths.js';
3
- import { addRunSource, copyFallbackFamily, fallbackRunSource, fallbackRunDeleteError } from './project-run-sources.js';
2
+ import { addRunSource, fallbackRunSource } from './project-run-sources.js';
4
3
  import { registeredWaitRecord, registeredReceiptRecord } from './wait-registration-write.js';
5
- import { stageCommit, stageLoaded, stageDurableUpdate, stageDebouncedUpdate, stageConversation, stageStepUpdate, stepTotals, redactPatch } from './record-write-rules.js';
6
- import { publishRunWrite, RunLifecycle, snapshotRun } from './lifecycle.js';
4
+ import { stageDurableUpdate, stageDebouncedUpdate, stageConversation, stageStepUpdate, stepTotals, redactPatch } from './record-write-rules.js';
5
+ import { RunLifecycle, snapshotRun } from './lifecycle.js';
7
6
  import { listPeerTaskSummaries, parseStoredSummary } from './run-summary-page.js';
8
7
  export { parseStoredSummary } from './run-summary-page.js';
9
8
  import { workerExecutionsFactory } from './worker-executions-registry.js';
@@ -28,34 +27,35 @@ import { restoreHistory } from './history-file.js';
28
27
  // Type-only module (zod + nothing else), so this cannot cycle back into the store.
29
28
  import { workflowDefSchema } from '../workflows/types.js';
30
29
  import { applyOutcomes } from './outcome-commit.js';
31
- import { ISSUE_URL_RE, namesForeignReference, referencedPrDeclaration, rescopeRun, resolveReferencedRef, restoreOriginatingIssue, trackReferencedIssues, trackReferencedPrs } from './run-references.js';
30
+ import { ISSUE_URL_RE, namesForeignReference, rescopeRun, trackReferencedIssues, trackReferencedPrs } from './run-references.js';
32
31
  import { applyExit, doneCommits, exitDurability, RUN_EXITS } from './run-exits.js';
33
32
  import { assertConversationIdFree } from './conversation-identity.js';
34
33
  export { ConversationIdInUseError } from './conversation-identity.js';
35
34
  import { LEGACY_RUNNER_IDS } from '../core/runner-ids.js';
36
- import { ARCHIVED_ROOT, RUNS_DB_FILE, RUNS_IMPORT_COMPLETE_KEY, RunConflictError, RunDatabase, RunDatabaseBusyError, } from './run-database.js';
35
+ import { ARCHIVED_ROOT, RUNS_DB_FILE, RUNS_IMPORT_COMPLETE_KEY, RunDatabase, RunDatabaseBusyError, } from './run-database.js';
37
36
  import { listBranchOwners } from './branch-owners.js';
38
37
  import { guardedJsonSql } from './guarded-json-sql.js';
39
- import { restoreLostReferencedPullRequest } from './loaded-run-healing.js';
40
- import { failLoadedInterruptedRun, restoreLoadedUsageLimitHold, settleLoadedStop } from './loaded-run-exits.js';
38
+ import { reconcileLoadedRun } from './loaded-run-exits.js';
41
39
  import { hasLegacyWaitFields, UNREADABLE_WAIT } from './legacy-waits.js';
42
40
  export { ciWaitEntry, holdsWorkerWait, upgradeLegacyWaits, workerWaitEntry } from './legacy-waits.js';
43
41
  import { ExitEvents } from './exit-events.js';
44
- import { encodeRunRow, familyRootOf, isLiveRecord, materializedWorktreePath, newestFirst } from './run-row.js';
42
+ import { familyRootOf, isLiveRecord, materializedWorktreePath, newestFirst } from './run-row.js';
45
43
  import { RunRetentionTopic } from './run-retention.js';
46
- import { collectRawExtras, encodeRawRecord } from './raw-record.js';
44
+ import { collectRawExtras } from './raw-record.js';
47
45
  import { ColdReadCache, storedRow } from './cold-reads.js';
48
- import { assertNoLegacyCockpit, assertNoLegacyWriter, backUpLegacyIndex, LEGACY_INDEX_FILE, LegacyWriterError, readLegacyIndex } from './legacy-index.js';
46
+ import { LEGACY_INDEX_FILE, LegacyWriterError } from './legacy-index.js';
49
47
  import { toRunStoreOpenError } from './store-open-error.js';
50
- import { claimStoreFamilies } from './claim-families.js';
48
+ import { importLegacyIndex, OPEN_RETRY_DELAYS_MS, sleepSync } from './store-open.js';
49
+ import { RunClaimsTopic, RunWriteRefusedError } from './run-claims-topic.js';
50
+ import { RunPinsTopic } from './run-pins.js';
51
51
  import { createStoreOwnedRun } from './owned-run-create.js';
52
52
  import { WorkerResultsTopic } from './worker-results.js';
53
53
  import { RunEventLogTopic } from './event-log.js';
54
54
  import { RunRedaction } from './run-redaction.js';
55
55
  import { RunArchiveTopic } from './run-archive.js';
56
56
  import { RunReadFlagsTopic } from './run-read-flags.js';
57
- import { claimOwnerLive, closeClaimSession, familyKey, foreignClaimedRunIds, liveForeignClaimedRunIds, openClaimSession, rowFamily } from './run-claims.js';
58
- import { assertProjectWritable, projectWriteRefused } from '../server/cockpit-ownership.js';
57
+ import { replaceRecord, RunPersistenceTopic } from './run-persistence.js';
58
+ import { closeClaimSession, familyKey, openClaimSession, rowFamily } from './run-claims.js';
59
59
  /**
60
60
  * A runner id as it may appear in a PERSISTED record (#547), spec 2026-11-18-runner-definitions.
61
61
  *
@@ -177,157 +177,11 @@ export function decodeRunRecord(data) {
177
177
  }
178
178
  }
179
179
  export { LEGACY_INDEX_BACKUP_FILE, LEGACY_INDEX_FILE } from './legacy-index.js';
180
- /** The pauses between open attempts while the database is busy, when `open` may wait (a boot):
181
- * about 3.5 s in all, with each attempt's own busy timeout. Long enough for another process to
182
- * finish importing a large `runs.json`. */
183
- const OPEN_RETRY_DELAYS_MS = [50, 100, 200, 400, 800, 1600];
184
- /** Block this thread for `ms`. Only `open` does, at boot, when there is nothing else to run. */
185
- function sleepSync(ms) {
186
- Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
187
- }
188
180
  /** How many archived root runs the run lists carry per project (#864): `GET /run-summaries?archived=recent`
189
181
  * and `GET /workspace/runs-index`. Unarchived runs are never cut; older archived runs page in
190
182
  * through `GET /run-summaries/archived` and the workspace search. */
191
183
  export const ARCHIVED_WINDOW = 200;
192
- /**
193
- * Reconcile one record just read off disk with the fact that whichever process wrote it is gone.
194
- *
195
- * Mutates and returns `run`. Extracted from `RunStore.open` so the read-only index reader
196
- * (`./run-index.ts`) answers the SAME question about a `running` row on disk. Two parsers that
197
- * disagree here is a visible bug, not an internal one: the cockpit would show a task as running
198
- * in the ⌘K index and failed the moment you opened it.
199
- *
200
- * `keepLive` (#367): leave `queued`/`running`/`waiting` untouched so the caller can recover them
201
- * (RunManager.recover re-queues queued runs, resumes interrupted ones). Without it — one-shot CLI
202
- * paths that never recover, and the index reader, which has no manager at all — live-looking runs
203
- * are marked failed so no ghost stays behind.
204
- */
205
- export function reconcileLoadedRun(run, opts) {
206
- settleLoadedStop(run);
207
- restoreLoadedUsageLimitHold(run);
208
- failLoadedInterruptedRun(run, opts);
209
- clearLoadedStaleResume(run);
210
- restoreLostReferencedPullRequest(run, referencedPrDeclaration, resolveReferencedRef);
211
- restoreOriginatingIssue(run);
212
- // Repository scoping follows reconciliation: stores arm a handle asynchronously, while
213
- // the read-only index applies its cached handle to these fresh records (#97). This ordering
214
- // also scopes any referenced PR restored above without filtering candidate evidence first.
215
- return run;
216
- }
217
- function clearLoadedStaleResume(run) {
218
- // Recovery owns waits; a usage-limit appointment survives while status is waiting.
219
- stageLoaded(run);
220
- }
221
- /**
222
- * Settle an adopted dead owner’s live run without starting work. Untouched runs cancel; started
223
- * runs become interrupted. Stop explicitly cancels its target. Mutates run.
224
- */
225
- export function settleOrphanedRun(run, opts = {}) {
226
- if (opts.stop && (run.status === 'queued' || run.status === 'running' || run.status === 'waiting'))
227
- run.stopping = true;
228
- if (run.status === 'queued' && !run.startedAt && run.workflowDef !== undefined &&
229
- run.steps.every((step) => step.status === 'pending' && !step.startedAt && !step.sessionId)) {
230
- Object.assign(run, applyExit(run, 'cancel'));
231
- }
232
- return reconcileLoadedRun(run, { keepLive: false });
233
- }
234
- /** Test seam (#779): `beforeTransaction` runs once `runs.json` is read and parsed, before the
235
- * import asks for the write lock; `beforeCommit` runs inside the import transaction, after every
236
- * row is written and before the last check that no older Squawk wrote `runs.json` meanwhile. */
237
- let legacyImportHook;
238
- export function __setLegacyImportHookForTests(hook) {
239
- legacyImportHook = hook;
240
- }
241
- /**
242
- * Import legacy rows and the completion marker atomically, once. Recheck live-writer evidence
243
- * before commit and preserve exact input bytes in a synced backup. Leave runs.json untouched;
244
- * invalid entries are skipped and reported.
245
- */
246
- function importLegacyIndex(db, dataDir) {
247
- assertNoLegacyCockpit(dataDir);
248
- const snapshot = readLegacyIndex(join(dataDir, LEGACY_INDEX_FILE));
249
- const parsed = snapshot ? legacyIndexRows(snapshot.bytes, parseRunRecords) : undefined;
250
- const rows = parsed?.rows ?? [];
251
- const skipped = parsed?.skipped ?? 0;
252
- const source = !snapshot ? 'none' : parsed ? LEGACY_INDEX_FILE : `${LEGACY_INDEX_FILE} (unparseable)`;
253
- assertNoLegacyWriter(dataDir, snapshot);
254
- legacyImportHook?.beforeTransaction?.();
255
- let backup;
256
- const commit = db.transaction({
257
- upserts: rows,
258
- deletes: [],
259
- onlyIfMetaAbsent: RUNS_IMPORT_COMPLETE_KEY,
260
- beforeCommit: () => {
261
- legacyImportHook?.beforeCommit?.();
262
- assertNoLegacyWriter(dataDir, snapshot);
263
- backup = snapshot ? backUpLegacyIndex(dataDir, snapshot) : undefined;
264
- const read = snapshot ? { bytes: snapshot.bytes.length, sha256: snapshot.sha256, backup } : {};
265
- return { [RUNS_IMPORT_COMPLETE_KEY]: JSON.stringify({ at: new Date().toISOString(), source, records: rows.length, ...(skipped > 0 ? { skipped } : {}), ...read }) };
266
- },
267
- });
268
- // Told once, by the import that committed: the marker means no later open reads runs.json again.
269
- if (commit.skipped || backup === undefined)
270
- return;
271
- const kept = `Its exact bytes are kept in ${join(dataDir, backup)}; https://github.com/hearsay-tools/squawk/blob/main/docs/run-history-recovery.md says how to import it after a repair.`;
272
- if (!parsed)
273
- console.warn(`[hsq] ${LEGACY_INDEX_FILE} could not be read; no run was imported, and this project starts with an empty history. ${kept}`);
274
- else if (skipped > 0)
275
- console.warn(`[hsq] ${skipped} of ${parsed.total} runs in ${LEGACY_INDEX_FILE} could not be read and were not imported. ${kept}`);
276
- }
277
- /**
278
- * Finished rows whose stored summary an open-time normalization would still change: a referenced
279
- * PR an older Squawk's created-PR declaration erased, or issue attribution displaced by a
280
- * follow-up declaration (see `reconcileLoadedRun`), or a summary that is not JSON. Not live, so not
281
- * in the `live` column; open decodes these few and keeps the ones it actually repaired.
282
- */
283
- const LEGACY_REFERENCE_HEAL_SQL = guardedJsonSql("(json_extract(summary, '$.markerRefs.pr') IS NOT NULL AND json_extract(summary, '$.referencedPullRequestUrl') IS NULL)" +
284
- " OR (NOT EXISTS (SELECT 1 FROM meta WHERE key = 'issue-attribution:' || runs.id AND value = CAST(runs.revision AS TEXT)) AND json_extract(summary, '$.markerRefs.issue') IS NOT NULL)", 1);
285
- /**
286
- * The rows whose stored summary reading their record can change, as SQL over `runs`: the rows
287
- * `open` decodes to normalize (the `live` column it loads by, then `LEGACY_REFERENCE_HEAL_SQL`).
288
- * With a repository handle, a row whose summary `namesForeignReference` is one too, as
289
- * `setRepoHandle` reads it. The cold reader (run-index.ts) decodes exactly these rows and serves
290
- * every other stored summary, so the two read paths cannot disagree about which rows to read.
291
- * `AUTOMATION_ORIGIN_HEAL_SQL` is left out on purpose: no cross-project view reads
292
- * `automationId`, and asking it scans `data`.
293
- */
294
- export const LOAD_REPAIR_SQL = `live = 1 OR ${LEGACY_REFERENCE_HEAL_SQL}`;
295
- /**
296
- * Rows whose record names the automation that launched it while the stored summary does not
297
- * (hearsay-tools/cezarion#1332): summaries a Squawk wrote before `RunSummary.automationId`
298
- * existed. Open rewrites each one's summary once, so the sidebar's Automations tab classifies a
299
- * finished task nobody has opened since the upgrade. `instr` keeps the JSON parse off every
300
- * other row.
301
- */
302
- const AUTOMATION_ORIGIN_HEAL_SQL = `instr(data, '"automation') > 0 AND ${guardedJsonSql("json_extract(summary, '$.automationId') IS NULL" +
303
- " AND (json_extract(data, '$.automation.automationId') IS NOT NULL OR json_extract(data, '$.automationTrigger.automationId') IS NOT NULL)", 0, ['summary', 'data'])}`;
304
184
  export { branchOwnerOf } from './branch-owners.js';
305
- /** The one answer every control gives for a run another Squawk process owns (`409 { error }`). */
306
- export const RUN_IN_USE_ELSEWHERE = `run is in use by another Squawk process`;
307
- /** The answer for a run this process stopped writing after a conflicting write. */
308
- export const RUN_QUARANTINED = `run changed under this Squawk process — restart Squawk to reload it`;
309
- /** A write this store must not make: another process owns the run, its owner died with work
310
- * still live (adopt it first), or a conflict quarantined it. Nothing was changed. */
311
- export class RunWriteRefusedError extends Error {
312
- runId;
313
- ownership;
314
- constructor(runId, ownership, fallbackError) {
315
- super(ownership === 'fallback' ? fallbackError ?? `run ${runId} is read only in the fallback project directory`
316
- : ownership === 'quarantined' ? `${RUN_QUARANTINED}: ${runId}`
317
- : ownership === 'orphaned' ? `run ${runId} belongs to a Squawk process that exited; take it over before writing it`
318
- : `${RUN_IN_USE_ELSEWHERE}: ${runId}`);
319
- this.runId = runId;
320
- this.ownership = ownership;
321
- this.name = 'RunWriteRefusedError';
322
- }
323
- }
324
- /** Make `target` hold exactly `source`'s fields, keeping the object every holder references. */
325
- function replaceRecord(target, source) {
326
- for (const key of Object.keys(target))
327
- if (!(key in source))
328
- delete target[key];
329
- Object.assign(target, source);
330
- }
331
185
  /**
332
186
  * A worker's destroy moving between two unfinished phases, and nothing else changing: nothing the
333
187
  * family reconcile reads changed, so it may skip that pass (#880). The first request and the
@@ -385,15 +239,11 @@ export class RunStore {
385
239
  pins = new Map();
386
240
  /** Staged ids while a durable commit installs and announces them: never evicted mid-commit. */
387
241
  committing = new Set();
388
- saveTimer = null;
389
242
  /** `null` once the store is closed, and in a `RunStore.unavailable` store (nothing is written,
390
243
  * nothing is evicted). */
391
244
  db = null;
392
- /** Persistence source for consumers that build the reports index. No index is created here. */
393
- reportSource() { return { db: this.db, dataDir: this.dataDir, openFailure: this.openFailure }; }
394
245
  /** Why `open` failed, in a `RunStore.unavailable` store. */
395
246
  openFailure;
396
- persistence;
397
247
  /** Runs whose held record is ahead of its row; the next save or commit writes them. */
398
248
  dirty = new Set();
399
249
  /** The typed lifecycle events the store publishes after each write (lifecycle.ts). */
@@ -429,8 +279,6 @@ export class RunStore {
429
279
  * Cleared at the next microtask: no commit spans a turn. */
430
280
  coldBase = new Map();
431
281
  coldReads = new ColdReadCache();
432
- /** The family of each pending deletion, whose claim the deleting write is fenced against. */
433
- deletedFamilies = new Map();
434
282
  /** Rows a conflicting write excluded: this store refuses to write them until it is reopened. */
435
283
  quarantined = new Set();
436
284
  /** Rows whose `data` this store tried to decode and could not: left in the database untouched,
@@ -450,13 +298,19 @@ export class RunStore {
450
298
  eventLog;
451
299
  /** The scrub of events and free text (hearsay-tools/squawk#4040). */
452
300
  redaction;
301
+ /** Claims, ownership, sources and fallback (hearsay-tools/squawk#4042). */
302
+ claims;
303
+ /** The holds that keep a run loaded (hearsay-tools/squawk#4042). */
304
+ runPins;
305
+ /** Flush, persist, the fence, conflicts and the save debounce (hearsay-tools/squawk#4043). */
306
+ persistence;
453
307
  executions;
454
308
  /** A worker's execution, process, identity and scope records (hearsay-tools/squawk#4039), built on
455
309
  * first use by the factory this process registered; throws when none is registered. */
456
310
  get workerExecutions() {
457
311
  return this.executions ??= workerExecutionsFactory()(this.dataDir, {
458
- peek: (id) => this.peek(id), getRun: (id) => this.getRun(id), writeDir: (id) => this.writeDir(id),
459
- sourceDataDir: (id) => this.sourceDataDir(id), commitIndex: (input) => this.commitIndex(input),
312
+ peek: (id) => this.peek(id), getRun: (id) => this.getRun(id), writeDir: (id) => this.claims.writeDir(id),
313
+ sourceDataDir: (id) => this.claims.sourceDataDir(id), commitIndex: (input) => this.persistence.commitIndex(input),
460
314
  published: this.published, workerResults: this.workerResults,
461
315
  });
462
316
  }
@@ -465,12 +319,18 @@ export class RunStore {
465
319
  liveReadSnapshot(runId) {
466
320
  return { events: this.liveItems.read(runId), throughSeq: this.seqs.get(runId) ?? Infinity };
467
321
  }
468
- constructor(dataDir) {
322
+ constructor(dataDir, persist) {
469
323
  this.dataDir = dataDir;
470
324
  this.redaction = new RunRedaction();
325
+ this.claims = new RunClaimsTopic(dataDir, {
326
+ db: () => this.db, owner: () => this.owner, keepLive: () => this.keepLive, held: this.held, base: this.base, dirty: this.dirty,
327
+ deleted: this.deleted, quarantined: this.quarantined, unreadable: this.unreadable, claimed: this.claimed, pendingClaims: this.pendingClaims,
328
+ exitEvents: this.exitEvents, coldReads: this.coldReads, decodeRunRow, anchoredFamilies: () => this.anchoredFamilies(), scheduleSave: () => this.persistence.scheduleSave(),
329
+ });
330
+ this.runPins = new RunPinsTopic({ pins: this.pins, published: this.published, record: (id) => this.record(id), peek: (id) => this.peek(id), sweepIfSettled: (ids) => this.persistence.sweepIfSettled(ids) });
471
331
  this.transcriptFacts = new RunTranscriptFacts(dataDir, {
472
- isFallbackRun: (id) => this.isFallbackRun(id),
473
- sourceDataDir: (id) => this.sourceDataDir(id),
332
+ isFallbackRun: (id) => this.claims.isFallbackRun(id),
333
+ sourceDataDir: (id) => this.claims.sourceDataDir(id),
474
334
  isOpen: () => this.db !== null,
475
335
  held: this.held,
476
336
  listFamilyRunIds: (rootId) => this.listFamilyRunIds(rootId),
@@ -478,49 +338,56 @@ export class RunStore {
478
338
  listRunIds: () => this.listRunIds(),
479
339
  });
480
340
  this.workerResults = new WorkerResultsTopic(dataDir, {
481
- peek: (id) => this.peek(id), hasRun: (id) => this.hasRun(id), hasFallbackRun: (id) => this.hasFallbackRun(id),
482
- writeDir: (id) => this.writeDir(id), sourceDataDir: (id) => this.sourceDataDir(id),
341
+ peek: (id) => this.peek(id), hasRun: (id) => this.hasRun(id), hasFallbackRun: (id) => this.claims.hasFallbackRun(id),
342
+ writeDir: (id) => this.claims.writeDir(id), sourceDataDir: (id) => this.claims.sourceDataDir(id),
483
343
  redactResult: (result) => this.redaction.redact({ type: 'worker-result', seq: 0, ts: result.observedAt, result }).result,
484
344
  redactText: (text) => this.redaction.redactText(text), commitDelegation: (patches) => this.commitDelegation(patches),
485
345
  });
486
346
  this.eventLog = new RunEventLogTopic(dataDir, {
487
347
  seqs: this.seqs, published: this.published, liveItems: this.liveItems, transcriptFacts: this.transcriptFacts, redaction: this.redaction,
488
- record: (id) => this.record(id), missingRunError: (runId) => this.missingRunError(runId), sourceDataDir: (id) => this.sourceDataDir(id),
489
- touch: (run, before) => this.touch(run, before), change: (id, apply) => this.change(id, apply), repoHandle: () => this.repoHandle,
348
+ record: (id) => this.record(id), missingRunError: (runId) => this.claims.missingRunError(runId), sourceDataDir: (id) => this.claims.sourceDataDir(id),
349
+ touch: (run, before) => this.persistence.touch(run, before), change: (id, apply) => this.change(id, apply), repoHandle: () => this.repoHandle,
490
350
  maybeEnqueueHistoryCompress: (run) => this.archive.maybeEnqueueHistoryCompress(run),
491
351
  });
492
352
  this.retention = new RunRetentionTopic(dataDir, {
493
353
  db: () => this.db, held: this.held, deleted: this.deleted, quarantined: this.quarantined,
494
354
  historyOwed: this.historyOwed, seqs: this.seqs, published: this.published, transcriptFacts: this.transcriptFacts,
495
355
  peek: (id) => this.peek(id), hasRun: (id) => this.hasRun(id), record: (id) => this.record(id),
496
- listWorkersOf: (parentId) => this.listWorkersOf(parentId), isFallbackRun: (id) => this.isFallbackRun(id),
497
- hasFallbackRun: (id) => this.hasFallbackRun(id), listOrder: (run) => this.listOrder(run),
498
- claimFamilies: (families) => this.claimFamilies(families), markDeleted: (id, family) => this.markDeleted(id, family),
499
- scheduleSave: () => this.scheduleSave(), commitIndex: (input) => this.commitIndex(input),
356
+ listWorkersOf: (parentId) => this.listWorkersOf(parentId), isFallbackRun: (id) => this.claims.isFallbackRun(id),
357
+ hasFallbackRun: (id) => this.claims.hasFallbackRun(id), listOrder: (run) => this.listOrder(run),
358
+ claimFamilies: (families) => this.claims.claimFamilies(families), markDeleted: (id, family) => this.persistence.markDeleted(id, family),
359
+ scheduleSave: () => this.persistence.scheduleSave(), commitIndex: (input) => this.persistence.commitIndex(input),
500
360
  commitDelegation: (patches) => this.commitDelegation(patches), applyArchived: (run, archived) => this.archive.applyArchived(run, archived),
501
361
  workerDeletionEvidence: (id) => this.workerExecutions.workerDeletionEvidence(id),
502
362
  workerResults: this.workerResults,
503
363
  readWorkerExecution: (id) => this.workerExecutions.readWorkerExecution(id), identityPath: (id) => this.workerExecutions.identityPath(id),
504
364
  processesPath: (id) => this.workerExecutions.processesPath(id), scopePath: (id) => this.workerExecutions.scopePath(id),
505
- executionPath: (id) => this.workerExecutions.executionPath(id), handoffPath: (runId) => this.handoffPath(runId),
506
- imagesDir: (runId) => this.imagesDir(runId),
365
+ executionPath: (id) => this.workerExecutions.executionPath(id), sourceDataDir: (id) => this.claims.sourceDataDir(id),
507
366
  });
508
367
  this.archive = new RunArchiveTopic(dataDir, {
509
368
  db: () => this.db, held: this.held, deleted: this.deleted, quarantined: this.quarantined, pins: this.pins,
510
369
  claimed: this.claimed, base: this.base, owner: () => this.owner, transcriptFacts: this.transcriptFacts,
511
370
  decodeRunRow, sortNewestFirst, peek: (id) => this.peek(id), record: (id) => this.record(id),
512
- listWorkersOf: (parentId) => this.listWorkersOf(parentId), familyOf: (id) => this.familyOf(id),
513
- claimFamilies: (families, opts) => this.claimFamilies(families, opts), writeRefusal: (id) => this.writeRefusal(id),
514
- assertWritable: (staged) => this.assertWritable(staged), decodeCold: (row) => this.decodeCold(row),
515
- listOrder: (run) => this.listOrder(run), commitIndex: (input, source, write) => this.commitIndex(input, source, write),
516
- touch: (run, before, exit) => this.touch(run, before, exit),
371
+ listWorkersOf: (parentId) => this.listWorkersOf(parentId), familyOf: (id) => this.persistence.familyOf(id),
372
+ claimFamilies: (families, opts) => this.claims.claimFamilies(families, opts), writeRefusal: (id) => this.claims.writeRefusal(id),
373
+ assertWritable: (staged) => this.persistence.assertWritable(staged), decodeCold: (row) => this.decodeCold(row),
374
+ listOrder: (run) => this.listOrder(run), commitIndex: (input, source, write) => this.persistence.commitIndex(input, source, write),
375
+ touch: (run, before, exit) => this.persistence.touch(run, before, exit),
517
376
  readWorkerExecution: (id) => this.workerExecutions.readWorkerExecution(id),
518
377
  });
519
378
  this.readFlags = new RunReadFlagsTopic({
520
379
  db: () => this.db, held: this.held, deleted: this.deleted, record: (id) => this.record(id),
521
- claimFamilies: (families) => this.claimFamilies(families), touch: (run, before) => this.touch(run, before),
380
+ claimFamilies: (families) => this.claims.claimFamilies(families), touch: (run, before) => this.persistence.touch(run, before),
522
381
  change: (id, apply) => this.change(id, apply),
523
382
  });
383
+ this.persistence = new RunPersistenceTopic(dataDir, persist, {
384
+ db: () => this.db, owner: () => this.owner, openFailure: () => this.openFailure, repoHandle: () => this.repoHandle,
385
+ held: this.held, committing: this.committing, dirty: this.dirty, deleted: this.deleted, historyOwed: this.historyOwed,
386
+ quarantined: this.quarantined, claimed: this.claimed, pendingClaims: this.pendingClaims, base: this.base, coldBase: this.coldBase,
387
+ coldReads: this.coldReads, liveItems: this.liveItems, published: this.published, archive: this.archive, claims: this.claims,
388
+ retention: this.retention, decodeRunRow, peek: (id) => this.peek(id), isAnchor: (id, run) => this.isAnchor(id, run),
389
+ evictSettled: () => this.evictSettled(),
390
+ });
524
391
  }
525
392
  /**
526
393
  * Open the project's run store. See `reconcileLoadedRun` for what `keepLive` (#367) decides
@@ -561,21 +428,20 @@ export class RunStore {
561
428
  const deferred = source && !existsSync(path) && !existsSync(join(dataDir, LEGACY_INDEX_FILE));
562
429
  if (!deferred)
563
430
  mkdirSync(join(dataDir, 'runs'), { recursive: true });
564
- const store = new RunStore(dataDir);
431
+ const store = new RunStore(dataDir, persist);
565
432
  store.keepLive = keepLive;
566
- store.persistence = persist;
567
433
  let db = RunDatabase.open(deferred ? ':memory:' : path);
568
434
  try {
569
435
  if (deferred)
570
436
  db.transaction({ upserts: [], deletes: [], meta: { [RUNS_IMPORT_COMPLETE_KEY]: 'none' } });
571
437
  else if (db.getMeta(RUNS_IMPORT_COMPLETE_KEY) === undefined)
572
- importLegacyIndex(db, dataDir);
438
+ importLegacyIndex(db, dataDir, parseRunRecords);
573
439
  if (source)
574
440
  db = addRunSource(db, dataDir, source);
575
441
  store.db = db;
576
442
  store.owner = openClaimSession();
577
443
  if (!maintenance) {
578
- store.loadHeldRows();
444
+ store.claims.loadHeldRows();
579
445
  store.transcriptFacts.warmTranscriptFacts();
580
446
  store.exitEvents.writeLoaded();
581
447
  }
@@ -614,218 +480,6 @@ export class RunStore {
614
480
  /** Why this store has no database, when it is `RunStore.unavailable`'s: its runs are unknown,
615
481
  * not absent. */
616
482
  get unavailable() { return this.openFailure; }
617
- /** Every sidecar for a run follows the winning record, never file-by-file fallback. */
618
- sourceDataDir(id) { return this.isFallbackRun(id) ? dataReadDirs(this.dataDir)[1] : runDataDir(this.dataDir, id); }
619
- isFallbackRun(id) { return this.db?.isFallback(id) ?? false; }
620
- hasFallbackRun(id) { return this.db?.hasFallback(id) ?? false; }
621
- /**
622
- * Open-time load: the live rows, the finished rows a load normalization repairs, then the
623
- * delegation families of the live ones. A row that does not parse is skipped and left in the
624
- * database untouched; one warning says how many.
625
- *
626
- * Only rows this store can claim are loaded (#779, plan step 3). A live row whose family another
627
- * live process claims — `serve`'s parked run, seen by a headless `cez run` — is that process's:
628
- * it is not loaded, normalized or recovered here, and stays readable through `getRun` and the
629
- * list rows. A live row nobody alive claims is taken over, as before: this open recovers it
630
- * (`keepLive`) or settles it as interrupted.
631
- */
632
- loadHeldRows() {
633
- let unreadable = 0;
634
- const decode = (row) => {
635
- const decoded = decodeRunRow(row.data);
636
- if (!decoded) {
637
- unreadable++;
638
- this.unreadable.add(row.id);
639
- }
640
- return decoded;
641
- };
642
- const live = this.db.listLive();
643
- const owned = this.claimFamilies(live.map(rowFamily), { allowLive: true, wait: true });
644
- for (const row of live) {
645
- if (!owned.has(rowFamily(row)))
646
- continue;
647
- const decoded = decode(row);
648
- if (decoded)
649
- this.adoptLoadedRun(decoded, { keepLive: this.keepLive }, row);
650
- }
651
- const heal = this.db.listWhere(LEGACY_REFERENCE_HEAL_SQL).filter((row) => !this.held.has(row.id));
652
- const healable = this.claimFamilies(heal.map(rowFamily));
653
- for (const row of heal) {
654
- if (!healable.has(rowFamily(row)))
655
- continue;
656
- const decoded = decode(row);
657
- // Held only when the repair changed it: the next save writes it, then it leaves.
658
- if (decoded) {
659
- // Persist verification once even when legacy issue attribution was already correct.
660
- const needsIssueCheck = decoded.run.markerRefs?.issue !== undefined &&
661
- this.db.getMeta(`issue-attribution:${row.id}`) !== String(row.revision);
662
- this.adoptLoadedRun(decoded, { keepLive: this.keepLive, onlyIfChanged: !needsIssueCheck }, row);
663
- if (needsIssueCheck)
664
- this.dirty.add(row.id);
665
- }
666
- }
667
- const stale = this.db.listWhere(AUTOMATION_ORIGIN_HEAL_SQL).filter((row) => !this.held.has(row.id));
668
- const restamp = this.claimFamilies(stale.map(rowFamily));
669
- for (const row of stale) {
670
- if (!restamp.has(rowFamily(row)))
671
- continue;
672
- const decoded = decode(row);
673
- // Nothing in the record changes, only its summary: held dirty, the next save rewrites it.
674
- if (decoded) {
675
- this.adoptLoadedRun(decoded, { keepLive: this.keepLive }, row);
676
- this.dirty.add(row.id);
677
- }
678
- }
679
- for (const rootId of this.anchoredFamilies())
680
- this.holdFamily(rootId, decode);
681
- this.releaseUnheldClaims();
682
- if (unreadable > 0)
683
- console.warn(`[hsq] ${unreadable} run(s) in ${RUNS_DB_FILE} could not be read; they are left in the database untouched.`);
684
- }
685
- /** Normalize a record just read from `row` (see `reconcileLoadedRun`) and hold it. Marks the row
686
- * dirty only when normalization changed it, so the next save persists exactly the runs open()
687
- * rewrote. A row read up from schema-3 wait fields counts as changed: its rewrite drops them
688
- * and recomputes its summary and live column (`upgradeLegacyWaits`), as does a summary that does
689
- * not parse (hearsay-tools/squawk#3530). The caller has claimed the row's family. */
690
- adoptLoadedRun({ run, extras, upgraded }, opts, row) {
691
- if (this.db?.familyHasFallback(rowFamily(row)))
692
- return;
693
- // Serialized, so a key set to `undefined` reads as the absent key it is once written.
694
- const before = JSON.stringify(run);
695
- const wasCancelled = run.status === 'cancelled';
696
- if (opts.settle)
697
- settleOrphanedRun(run, { stop: opts.stop });
698
- else
699
- reconcileLoadedRun(run, opts);
700
- const changed = upgraded === true || JSON.stringify(run) !== before || parseStoredSummary(row.summary) === undefined;
701
- if (opts.onlyIfChanged && !changed)
702
- return;
703
- this.held.set(run.id, run);
704
- this.base.set(run.id, { revision: row.revision, seq: row.seq, data: row.data, extras });
705
- if (changed)
706
- this.dirty.add(run.id);
707
- if (!wasCancelled && run.status === 'cancelled')
708
- this.exitEvents.loadCancelled(run.id);
709
- }
710
- /**
711
- * Hold one delegation family: its root and every worker filed under it, read through the
712
- * `parent_run_id` index. No recursion: a worker's own id never names a family. The caller has claimed it. `settle` settles its live rows instead of keeping
713
- * them for recovery (`settleOrphanedRun`); `stopId` is the run a Stop settles as cancelled.
714
- */
715
- holdFamily(rootId, decode = (row) => decodeRunRow(row.data), settle = false, stopId) {
716
- const rows = [this.db.get(rootId), ...this.db.listByParent(rootId)];
717
- for (const row of rows) {
718
- if (!row || this.held.has(row.id) || this.deleted.has(row.id))
719
- continue;
720
- const decoded = decode(row);
721
- if (decoded)
722
- this.adoptLoadedRun(decoded, { keepLive: this.keepLive, settle, stop: row.id === stopId }, row);
723
- }
724
- }
725
- /** Make sure this store claims each of `families`; `claimStoreFamilies` takes the free ones. */
726
- claimFamilies(families, opts = {}) {
727
- return projectWriteRefused(this.dataDir) ? new Set() : claimStoreFamilies({
728
- claimed: this.claimed,
729
- pendingClaims: this.pendingClaims,
730
- db: this.db,
731
- owner: this.owner,
732
- scheduleSave: () => this.scheduleSave(),
733
- }, families, opts);
734
- }
735
- /** Release the claim of every family with nothing left in memory, once nothing is pending: a
736
- * failed save keeps its families claimed until it succeeds. A failed release retries at the
737
- * next sweep; `close()` releases the rest. */
738
- releaseUnheldClaims() {
739
- if (!this.db || !this.owner || this.dirty.size > 0 || this.deleted.size > 0)
740
- return;
741
- const kept = new Set();
742
- for (const run of this.held.values())
743
- kept.add(familyKey(run));
744
- // A claim never taken has nothing to release in the database.
745
- for (const family of this.pendingClaims.keys())
746
- if (!kept.has(family))
747
- this.pendingClaims.delete(family);
748
- const released = [...this.claimed.keys()].filter((family) => !kept.has(family));
749
- if (released.length === 0)
750
- return;
751
- try {
752
- this.db.releaseClaims(this.owner.session, released);
753
- for (const family of released)
754
- this.claimed.delete(family);
755
- }
756
- catch {
757
- // Busy or failing: the next sweep tries again.
758
- }
759
- }
760
- /**
761
- * Who may change this run right now (see `RunOwnership`), or undefined when there is no such
762
- * run. Read-only: nothing is claimed. Controls ask this first, so a run another process owns is
763
- * refused with `RUN_IN_USE_ELSEWHERE` and a dead process's run is adopted before it is changed.
764
- */
765
- runOwnership(id) {
766
- if (this.quarantined.has(id))
767
- return 'quarantined';
768
- const held = this.held.get(id);
769
- if (!this.db)
770
- return held ? 'held' : undefined;
771
- const family = held ? familyKey(held) : this.deleted.has(id) ? undefined : this.db.familyOf(id);
772
- if (family === undefined)
773
- return undefined;
774
- if (this.db.familyHasFallback(family))
775
- return 'fallback';
776
- if (this.claimed.has(family) || this.pendingClaims.has(family))
777
- return 'held';
778
- const claim = this.db.getClaim(family);
779
- if (claim && claimOwnerLive(claim))
780
- return 'foreign';
781
- // The same rule `claimFamilies` writes by: a dead owner left only settled runs → free.
782
- return this.db.familyHasLive(family) ? 'orphaned' : 'free';
783
- }
784
- /** Why a control on this run must be refused here, or undefined when this store may change it. */
785
- writeRefusal(id) {
786
- const ownership = this.runOwnership(id);
787
- if (ownership === 'quarantined')
788
- return RUN_QUARANTINED;
789
- if (ownership === 'fallback')
790
- return this.fallbackRefusal(id).message;
791
- return ownership === 'foreign' || ownership === 'orphaned' ? RUN_IN_USE_ELSEWHERE : undefined;
792
- }
793
- /**
794
- * Claim an orphaned family before a control, then settle its live rows.
795
- * Stop cancels its target. Return the root id, or undefined for a live owner or missing run.
796
- */
797
- adoptFamily(id, opts = {}) {
798
- const family = this.db?.familyOf(id);
799
- if (family === undefined || !this.claimFamilies([family], { allowLive: true, wait: true }).has(family))
800
- return undefined;
801
- this.holdFamily(family, undefined, true, opts.stop ? id : undefined);
802
- this.exitEvents.writeLoaded();
803
- return family;
804
- }
805
- /** Explicit controls only (`requireRunControl`): copy a fallback family in so it can be written. */
806
- adoptFallbackFamily(id) {
807
- const members = copyFallbackFamily(this.db, id, this.owner);
808
- for (const member of members)
809
- this.coldReads.forget(member);
810
- return members.length > 0;
811
- }
812
- fallbackRefusal(id) { return new RunWriteRefusedError(id, 'fallback', fallbackRunDeleteError(this.dataDir, true)); }
813
- /** Run files are written only for a family this store may write, never a fallback family. */
814
- /** The error `appendEvent` throws for a run this store cannot write or does not know. */
815
- missingRunError(runId) {
816
- const ownership = this.runOwnership(runId);
817
- if (ownership === 'fallback')
818
- return this.fallbackRefusal(runId);
819
- if (ownership === 'foreign' || ownership === 'orphaned' || ownership === 'quarantined')
820
- return new RunWriteRefusedError(runId, ownership);
821
- return new Error(`unknown run: ${runId}`);
822
- }
823
- writeDir(id) { if (this.runOwnership(id) === 'fallback')
824
- throw this.fallbackRefusal(id); return runDataDir(this.dataDir, id); }
825
- /** Every run whose family another process owns (`foreignClaimedRunIds`). */
826
- listForeignClaimedRunIds() { return foreignClaimedRunIds(this.db, this.owner); }
827
- /** Non-terminal rows in the database (both directories) and the runs of families another live store claims. */
828
- persistedLiveRunIds() { return { live: this.db?.listLive().map((row) => row.id) ?? [], foreign: liveForeignClaimedRunIds(this.db, this.owner) }; }
829
483
  /**
830
484
  * Whether a held run anchors itself (and its family) in memory. Anything else held is a family
831
485
  * member or a settled write, and leaves at the next sweep (`evictSettled`).
@@ -870,7 +524,7 @@ export class RunStore {
870
524
  this.base.delete(id);
871
525
  this.coldReads.forget(id);
872
526
  }
873
- this.releaseUnheldClaims();
527
+ this.claims.releaseUnheldClaims();
874
528
  }
875
529
  /** A run read from `runs.db`, normalized like a loaded one (`reconcileLoadedRun`, then the
876
530
  * repository scope) but held by nobody. Undefined when absent, deleted or unreadable. */
@@ -919,13 +573,13 @@ export class RunStore {
919
573
  if (held)
920
574
  return held;
921
575
  const family = this.db && !this.deleted.has(id) ? this.db.familyOf(id) : undefined;
922
- if (family === undefined || !this.claimFamilies([family]).has(family))
576
+ if (family === undefined || !this.claims.claimFamilies([family]).has(family))
923
577
  return undefined;
924
578
  const run = this.coldReads.claimed(id, this.coldBase.get(id), () => this.db?.revisionOf(id)) ?? this.loadCold(id);
925
579
  if (!run)
926
580
  return undefined;
927
581
  this.holdDecoded(run);
928
- this.scheduleSave();
582
+ this.persistence.scheduleSave();
929
583
  return run;
930
584
  }
931
585
  /** The record a store write changes in place: held, or loaded to be. Undefined for a run this
@@ -973,38 +627,6 @@ export class RunStore {
973
627
  hasRun(id) {
974
628
  return this.held.has(id) || (!!this.db && !this.deleted.has(id) && this.db.has(id));
975
629
  }
976
- /**
977
- * Keep a run in memory for `holder` until `unpin(id, holder)`: a RunManager pins the runs it is
978
- * executing (`active`) and the run a Continue is admitting (`continue`). A finished run is
979
- * loaded. Pins are per holder, so releasing one never releases another. Returns the held record.
980
- */
981
- pin(id, holder) {
982
- const run = this.record(id);
983
- if (!run)
984
- return undefined;
985
- let holders = this.pins.get(id);
986
- if (!holders)
987
- this.pins.set(id, holders = new Set());
988
- holders.add(holder);
989
- return run;
990
- }
991
- /** Publish a run's current record again without a write: something read beside the record
992
- * changed, such as the run leaving the manager's live registries, which a detail's finish
993
- * verdict reads (hearsay-tools/cezarion#1301). */
994
- republish(id) {
995
- const run = this.peek(id);
996
- if (run)
997
- this.published.publish('run.updated', { run, before: snapshotRun(run), source: 'live-release' });
998
- }
999
- /** Release `holder`'s pin. The run leaves memory at the next sweep once nothing else holds it. */
1000
- unpin(id, holder) {
1001
- const holders = this.pins.get(id);
1002
- if (!holders?.delete(holder))
1003
- return;
1004
- if (holders.size === 0)
1005
- this.pins.delete(id);
1006
- this.sweepIfSettled([id]);
1007
- }
1008
630
  /**
1009
631
  * Set discovered repository identity without blocking boot. Recompute conclusions from retained
1010
632
  * evidence, including cold records; null retains unknown-handle behavior.
@@ -1025,12 +647,12 @@ export class RunStore {
1025
647
  for (const run of [...this.held.values()]) {
1026
648
  const before = snapshotRun(run);
1027
649
  if (rescopeRun(run, this.repoHandle)) {
1028
- this.touch(run, before);
650
+ this.persistence.touch(run, before);
1029
651
  healed = true;
1030
652
  }
1031
653
  }
1032
654
  // Only rows this store may write: another process's runs heal when their owner arms its handle.
1033
- const writable = this.claimFamilies(stored.map(rowFamily));
655
+ const writable = this.claims.claimFamilies(stored.map(rowFamily));
1034
656
  for (const row of stored) {
1035
657
  if (!writable.has(rowFamily(row)))
1036
658
  continue;
@@ -1040,13 +662,13 @@ export class RunStore {
1040
662
  if (!run || !this.storedScopeDiffers(row, run))
1041
663
  continue;
1042
664
  this.holdDecoded(run);
1043
- this.touch(run, before ?? snapshotRun(run));
665
+ this.persistence.touch(run, before ?? snapshotRun(run));
1044
666
  healed = true;
1045
667
  }
1046
668
  // Discovery may finish after headless shutdown's final flush. Persist repairs now: the
1047
669
  // debounced save is unref'd, so it cannot keep the CLI alive once the lookup completes.
1048
670
  if (healed)
1049
- this.flush();
671
+ this.persistence.flush();
1050
672
  }
1051
673
  /** Whether the stored summary still names a reference the scoped record no longer has. */
1052
674
  storedScopeDiffers(row, run) {
@@ -1489,11 +1111,11 @@ export class RunStore {
1489
1111
  throw this.openFailure;
1490
1112
  const run = this.buildRun(input, randomUUID());
1491
1113
  // A new family, so nobody else can hold it; claimed before anything (an NDJSON event) is written.
1492
- if (this.db && !this.claimFamilies([run.id]).has(run.id))
1114
+ if (this.db && !this.claims.claimFamilies([run.id]).has(run.id))
1493
1115
  throw new RunWriteRefusedError(run.id, 'foreign');
1494
1116
  this.held.set(run.id, run);
1495
1117
  this.retention.pruneOldRuns();
1496
- this.touch(run, undefined);
1118
+ this.persistence.touch(run, undefined);
1497
1119
  return run;
1498
1120
  }
1499
1121
  /** Build without publishing: owned creation must commit its receipt and run together. */
@@ -1553,7 +1175,7 @@ export class RunStore {
1553
1175
  assertConversationIdFree(root, message ?? delivery?.input, id => this.peek(id), (runId, id) => this.eventLog.hasProjection(runId, id));
1554
1176
  const staged = new Map();
1555
1177
  stageConversation(staged, root, conversation, delivery, id => this.peek(id), text => this.redaction.redactText(text));
1556
- this.commitIndex(staged);
1178
+ this.persistence.commitIndex(staged);
1557
1179
  }
1558
1180
  /** Crash recovery (#505): input a harness accepted but was never seen reading goes
1559
1181
  * back to the queue. Returns the requeued IDs. */
@@ -1597,7 +1219,7 @@ export class RunStore {
1597
1219
  throw new Error('live inbox receipt changed');
1598
1220
  }
1599
1221
  }
1600
- this.commitIndex(new Map([[id, { ...run, agentInputs }]]));
1222
+ this.persistence.commitIndex(new Map([[id, { ...run, agentInputs }]]));
1601
1223
  }
1602
1224
  /** Reserve only unread conversation inputs in one durable index replacement. */
1603
1225
  claimInboxInputs(runId, ids, claim) {
@@ -1619,7 +1241,7 @@ export class RunStore {
1619
1241
  }
1620
1242
  }
1621
1243
  const selectedIds = new Set(selected);
1622
- this.commitIndex(new Map([[runId, { ...run, agentInputs: inputs.map(input => selectedIds.has(input.id)
1244
+ this.persistence.commitIndex(new Map([[runId, { ...run, agentInputs: inputs.map(input => selectedIds.has(input.id)
1623
1245
  ? agentInputSchema.parse({ ...input, inboxClaim: receipt }) : input) }]]));
1624
1246
  }
1625
1247
  /** A receipt owns every matching input or none; exact ACK retries preserve the first timestamp. */
@@ -1658,7 +1280,7 @@ export class RunStore {
1658
1280
  if (!matching.length || matching.some(input => input.inboxClaim?.generation !== generation ||
1659
1281
  input.inboxClaim?.acknowledgedAt || input.deliveredAt))
1660
1282
  throw new Error('inbox receipt changed');
1661
- this.commitIndex(new Map([[runId, { ...run, agentInputs: run.agentInputs.map(input => {
1283
+ this.persistence.commitIndex(new Map([[runId, { ...run, agentInputs: run.agentInputs.map(input => {
1662
1284
  if (input.inboxClaim?.receiptId !== receiptId)
1663
1285
  return input;
1664
1286
  const { inboxClaim: _claim, ...unclaimed } = input;
@@ -1673,7 +1295,7 @@ export class RunStore {
1673
1295
  inboxClaimSchema.shape.expiresAt.parse(now);
1674
1296
  if (!run.agentInputs?.some(input => input.inboxClaim && !input.inboxClaim.acknowledgedAt && input.inboxClaim.expiresAt <= now))
1675
1297
  return;
1676
- this.commitIndex(new Map([[runId, { ...run, agentInputs: run.agentInputs.map(input => {
1298
+ this.persistence.commitIndex(new Map([[runId, { ...run, agentInputs: run.agentInputs.map(input => {
1677
1299
  if (!input.inboxClaim || input.inboxClaim.acknowledgedAt || input.inboxClaim.expiresAt > now)
1678
1300
  return input;
1679
1301
  const { inboxClaim: _claim, ...unclaimed } = input;
@@ -1691,14 +1313,14 @@ export class RunStore {
1691
1313
  const run = this.peek(id);
1692
1314
  if (!run)
1693
1315
  throw new Error('missing wait target');
1694
- this.commitIndex(new Map([[id, registeredWaitRecord(run, wait, input, registration)]]));
1316
+ this.persistence.commitIndex(new Map([[id, registeredWaitRecord(run, wait, input, registration)]]));
1695
1317
  }
1696
1318
  /** Record a deduplicated registration without mutating its wait. */
1697
1319
  commitWaitRegistration(id, receipt) {
1698
1320
  const run = this.peek(id);
1699
1321
  if (!run)
1700
1322
  throw new Error('missing wait target');
1701
- this.commitIndex(new Map([[id, registeredReceiptRecord(run, receipt)]]));
1323
+ this.persistence.commitIndex(new Map([[id, registeredReceiptRecord(run, receipt)]]));
1702
1324
  }
1703
1325
  /** A usage-limit appointment withdrawn, committed at once instead of on the debounced save
1704
1326
  * (hearsay-tools/cezarion#1236): a crash right after the withdrawal must not find it on disk,
@@ -1711,7 +1333,7 @@ export class RunStore {
1711
1333
  if (isUsageLimitHold(run))
1712
1334
  this.move(id, 'withdraw-hold');
1713
1335
  else
1714
- this.commitIndex(new Map([[id, { ...run, autoResumeAt: undefined, autoResumeAttempts: undefined, autoResumeReason: undefined }]]));
1336
+ this.persistence.commitIndex(new Map([[id, { ...run, autoResumeAt: undefined, autoResumeAttempts: undefined, autoResumeReason: undefined }]]));
1715
1337
  }
1716
1338
  /** A human message beside a run's waits (hearsay-tools/cezarion#1235): accepted durably, and
1717
1339
  * every wait stays. A lifecycle opening becomes
@@ -1721,7 +1343,7 @@ export class RunStore {
1721
1343
  const run = this.peek(id);
1722
1344
  if (!run)
1723
1345
  throw new Error('missing queued message target');
1724
- this.commitIndex(new Map([[id, { ...run, queuedMessages: [...(run.queuedMessages ?? []), queuedMessageSchema.parse(acceptedHumanMessage)],
1346
+ this.persistence.commitIndex(new Map([[id, { ...run, queuedMessages: [...(run.queuedMessages ?? []), queuedMessageSchema.parse(acceptedHumanMessage)],
1725
1347
  ...(run.continuationMessage ? { continuationMessage: { ...run.continuationMessage, origin: 'human' } } : {}),
1726
1348
  }]]));
1727
1349
  }
@@ -1743,7 +1365,7 @@ export class RunStore {
1743
1365
  if (!staged.changed)
1744
1366
  return { committed: false, answered: [], settled: [] };
1745
1367
  try {
1746
- this.commitIndex(new Map([[id, staged.next]]), undefined, { exits: new Map([[id, staged.exit]]) });
1368
+ this.persistence.commitIndex(new Map([[id, staged.next]]), undefined, { exits: new Map([[id, staged.exit]]) });
1747
1369
  }
1748
1370
  catch (error) {
1749
1371
  if (!opts.bestEffort)
@@ -1754,7 +1376,7 @@ export class RunStore {
1754
1376
  return { committed: false, answered: staged.answered, settled: staged.settled };
1755
1377
  const before = snapshotRun(live);
1756
1378
  replaceRecord(live, staged.next);
1757
- this.touch(live, before, staged.exit);
1379
+ this.persistence.touch(live, before, staged.exit);
1758
1380
  return { committed: false, answered: staged.answered, settled: staged.settled };
1759
1381
  }
1760
1382
  return { committed: true, answered: staged.answered, settled: staged.settled };
@@ -1785,7 +1407,7 @@ export class RunStore {
1785
1407
  }
1786
1408
  // In-process cause only: consumers can skip metadata replay when delegation
1787
1409
  // is disabled without dropping real status or termination-proof notifications.
1788
- this.commitIndex(staged, destroyProgress ? 'delegation-destroy-progress' : 'delegation-checkpoint');
1410
+ this.persistence.commitIndex(staged, destroyProgress ? 'delegation-destroy-progress' : 'delegation-checkpoint');
1789
1411
  }
1790
1412
  /** A pending destroy's automatic retry state, or its removal (hearsay-tools/cezarion#879). Kept on
1791
1413
  * the record beside the strict delegation, so an older Squawk strips it rather than quarantining the
@@ -1797,7 +1419,7 @@ export class RunStore {
1797
1419
  if (!retry && !run.destroyRetry)
1798
1420
  return;
1799
1421
  // An explicit `undefined`, not an omitted key: commitIndex assigns onto the live record.
1800
- this.commitIndex(new Map([[id, { ...run, destroyRetry: retry ? workerDestroyRetrySchema.parse(retry) : undefined }]]), 'delegation-destroy-progress');
1422
+ this.persistence.commitIndex(new Map([[id, { ...run, destroyRetry: retry ? workerDestroyRetrySchema.parse(retry) : undefined }]]), 'delegation-destroy-progress');
1801
1423
  }
1802
1424
  /** Accepted execution revision is public lifecycle identity, separate from process generations. */
1803
1425
  commitWorkerContinuation(id, exit, patch = {}, step, conversation) {
@@ -1822,7 +1444,7 @@ export class RunStore {
1822
1444
  throw new Error('missing conversation ownership');
1823
1445
  stageConversation(staged, root, conversation.state, { recipientRunId: id, input: conversation.input }, runId => this.peek(runId), text => this.redaction.redactText(text));
1824
1446
  }
1825
- this.commitIndex(staged, undefined, { exits: new Map([[id, exit]]) });
1447
+ this.persistence.commitIndex(staged, undefined, { exits: new Map([[id, exit]]) });
1826
1448
  }
1827
1449
  /** Create an owned worker run and its parent receipt; `createStoreOwnedRun` holds the checks. */
1828
1450
  createOwnedRun(input, parentId, requestId, worker, requestHash, spawnCapacityRefusal, executionIdentity = { kind: 'internal' }) {
@@ -1833,98 +1455,9 @@ export class RunStore {
1833
1455
  buildRun: (ownedInput, id) => this.buildRun(ownedInput, id),
1834
1456
  writeWorkerIdentity: (id, identity) => this.workerExecutions.writeWorkerIdentity(id, identity),
1835
1457
  writeWorkerExecution: (id, proof, fresh) => this.workerExecutions.writeWorkerExecution(id, proof, fresh),
1836
- commitIndex: (owned) => this.commitIndex(owned),
1458
+ commitIndex: (owned) => this.persistence.commitIndex(owned),
1837
1459
  }, input, parentId, requestId, worker, requestHash, spawnCapacityRefusal, executionIdentity);
1838
1460
  }
1839
- /**
1840
- * Durably replace or delete staged rows together with pending dirty rows. Persist before
1841
- * changing held objects or notifying subscribers. On failure retain all pending state; flush()
1842
- * remains best-effort.
1843
- */
1844
- commitIndex(input, source, write = {}) {
1845
- const exits = new Map(write.exits);
1846
- const staged = stageCommit(input, {
1847
- peek: id => this.peek(id),
1848
- completionArchiveBlocker: run => this.archive.completionArchiveBlocker(run),
1849
- stageArchive: (staged, run, archived) => this.archive.stageArchive(staged, run, archived, exits),
1850
- });
1851
- const before = new Map([...staged].map(([id, next]) => [id, next ? write.before?.get(id) ?? snapshotRun(this.peek(id)) : undefined])), committed = new Map([...staged].map(([id, next]) => [id, snapshotRun(next ?? undefined)]));
1852
- if (!this.db)
1853
- throw this.openFailure ?? new Error('runs database unavailable: nothing can be saved');
1854
- this.assertWritable(staged);
1855
- this.persist(staged);
1856
- // Preserve existing record references, but expose the entire transaction before its first event, which
1857
- // carries the record this commit wrote (`committed`). A finished run is held until the next sweep.
1858
- for (const [id, next] of staged) {
1859
- this.coldReads.forget(id);
1860
- if (!next) {
1861
- this.held.delete(id);
1862
- continue;
1863
- }
1864
- this.committing.add(id);
1865
- const current = this.held.get(id);
1866
- if (current)
1867
- replaceRecord(current, next);
1868
- else
1869
- this.held.set(id, next);
1870
- }
1871
- try {
1872
- for (const id of staged.keys()) {
1873
- const run = this.held.get(id);
1874
- if (run)
1875
- publishRunWrite(this.published, committed.get(id) ?? run, before.get(id), source, exits.get(id));
1876
- else
1877
- this.published.publish('run.deleted', { runId: id });
1878
- }
1879
- }
1880
- finally {
1881
- for (const id of staged.keys())
1882
- this.committing.delete(id);
1883
- this.sweepIfSettled(staged.keys());
1884
- }
1885
- for (const [id, next] of staged)
1886
- if (next?.archived)
1887
- this.archive.compressor.enqueue(id);
1888
- }
1889
- /**
1890
- * Refuse (throwing, with nothing changed) a commit that stages a quarantined run, or a run whose
1891
- * family this store does not claim and cannot take: another process owns it, or a dead process
1892
- * left it live and it has not been adopted.
1893
- */
1894
- assertWritable(staged) {
1895
- const families = new Map();
1896
- const held = new Set();
1897
- for (const [id, next] of staged) {
1898
- if (this.quarantined.has(id))
1899
- throw new RunWriteRefusedError(id, 'quarantined');
1900
- const family = next ? familyKey(next) : this.familyOf(id);
1901
- families.set(id, family);
1902
- if (this.held.has(id))
1903
- held.add(family);
1904
- }
1905
- // A run this store holds may move to a new family; any other row is claimed as a plain write.
1906
- const owned = new Set([...this.claimFamilies(held, { allowLive: true }),
1907
- ...this.claimFamilies([...families.values()].filter((family) => !held.has(family)))]);
1908
- for (const [id, family] of families) {
1909
- if (!owned.has(family))
1910
- throw this.runOwnership(id) === 'fallback' ? this.fallbackRefusal(id) : new RunWriteRefusedError(id, this.runOwnership(id) === 'orphaned' ? 'orphaned' : 'foreign');
1911
- }
1912
- }
1913
- /** The family of a run this store knows: held, else its row; a run nowhere is its own. */
1914
- familyOf(id) {
1915
- const held = this.held.get(id);
1916
- return held ? familyKey(held) : this.deletedFamilies.get(id) ?? this.db?.familyOf(id) ?? id;
1917
- }
1918
- /** Schedule the sweep that lets any of `ids` leave memory, when one of them now can. */
1919
- sweepIfSettled(ids) {
1920
- for (const id of ids) {
1921
- const run = this.held.get(id);
1922
- if (run && !this.isAnchor(id, run)) {
1923
- this.scheduleSave();
1924
- return;
1925
- }
1926
- }
1927
- }
1928
1461
  /** Move run `id` by `exit` (ADR 0056): its status and `extras` in one write, checked against the
1929
1462
  * record that write changes. A run this store cannot write is neither checked nor written. The
1930
1463
  * exit decides how the write persists (`exitDurability`), never the extras. A guarded exit (one
@@ -1948,7 +1481,7 @@ export class RunStore {
1948
1481
  moved = this.writeRun(id, run, applyExit(run, exit, redacted, call), exitDurability(exit, run), exit);
1949
1482
  else {
1950
1483
  const input = { ...run, ...redacted };
1951
- this.commitIndex(new Map([[id, { ...(spec.settle?.(input, { ...call, now: new Date().toISOString() }) ?? input), ...applyExit(run, exit, {}, call) }]]), undefined, { exits: new Map([[id, exit]]) });
1484
+ this.persistence.commitIndex(new Map([[id, { ...(spec.settle?.(input, { ...call, now: new Date().toISOString() }) ?? input), ...applyExit(run, exit, {}, call) }]]), undefined, { exits: new Map([[id, exit]]) });
1952
1485
  moved = this.peek(id);
1953
1486
  }
1954
1487
  if (event)
@@ -1975,11 +1508,11 @@ export class RunStore {
1975
1508
  repoHandle: this.repoHandle,
1976
1509
  restore: () => restoreHistory(this.dataDir, id),
1977
1510
  archive: (record, archived) => this.archive.applyArchived(record, archived, before, exit),
1978
- touch: (record) => this.touch(record, before, exit),
1511
+ touch: (record) => this.persistence.touch(record, before, exit),
1979
1512
  };
1980
1513
  if (durability === 'committed') {
1981
1514
  const staged = stageDurableUpdate(run, patch, hooks, exit);
1982
- this.commitIndex(new Map([[id, staged.run]]), undefined, { before: new Map([[id, before]]), exits: new Map([[id, staged.exit]]) });
1515
+ this.persistence.commitIndex(new Map([[id, staged.run]]), undefined, { before: new Map([[id, before]]), exits: new Map([[id, staged.exit]]) });
1983
1516
  return this.record(id);
1984
1517
  }
1985
1518
  stageDebouncedUpdate(run, patch, hooks);
@@ -1995,7 +1528,7 @@ export class RunStore {
1995
1528
  return;
1996
1529
  const before = snapshotRun(run);
1997
1530
  run.steps = [...run.steps, { ...step, status: 'pending', iterations: 0, tokensUsed: 0 }];
1998
- this.touch(run, before);
1531
+ this.persistence.touch(run, before);
1999
1532
  }
2000
1533
  updateStep(runId, stepId, patch) {
2001
1534
  const run = this.record(runId);
@@ -2006,7 +1539,7 @@ export class RunStore {
2006
1539
  // Replaced, never changed in place, so `before` keeps the steps as they were.
2007
1540
  run.steps = run.steps.map((candidate) => candidate === step ? next : candidate);
2008
1541
  Object.assign(run, stepTotals(run.steps));
2009
- this.touch(run, before);
1542
+ this.persistence.touch(run, before);
2010
1543
  }
2011
1544
  /** A debounced write of the held record `id`: `apply` changes it in place, then `touch` saves it. */
2012
1545
  change(id, apply) {
@@ -2014,7 +1547,7 @@ export class RunStore {
2014
1547
  if (!run)
2015
1548
  return undefined;
2016
1549
  apply(run);
2017
- this.touch(run, before);
1550
+ this.persistence.touch(run, before);
2018
1551
  return run;
2019
1552
  }
2020
1553
  /** Indexed family enumeration, including members not yet flushed to SQLite. */
@@ -2030,251 +1563,8 @@ export class RunStore {
2030
1563
  ids.delete(id);
2031
1564
  return [...ids];
2032
1565
  }
2033
- /** Write the pending rows out now (used on shutdown). */
2034
- flush() {
2035
- if (this.saveTimer) {
2036
- clearTimeout(this.saveTimer);
2037
- this.saveTimer = null;
2038
- }
2039
- this.saveNow();
2040
- }
2041
1566
  // ---- internals -----------------------------------------------------------
2042
1567
  seqs = new Map();
2043
- /** Same location `handoffPath()` in handoff.ts produces — inlined to keep
2044
- * the store free of upward imports. */
2045
- handoffPath(runId) {
2046
- return join(this.sourceDataDir(runId), 'runs', `${runId}.handoff.md`);
2047
- }
2048
- /** Agent screenshots persisted by the run manager (see persistImage). */
2049
- imagesDir(runId) {
2050
- return join(this.sourceDataDir(runId), 'runs', `${runId}-images`);
2051
- }
2052
- /** Save `run` debounced and publish it; `before` is the record at the write's entry (none: created). */
2053
- touch(run, before, exit) {
2054
- this.dirty.add(run.id);
2055
- this.scheduleSave();
2056
- publishRunWrite(this.published, run, before, undefined, exit);
2057
- this.archive.maybeEnqueueHistoryCompress(run);
2058
- }
2059
- /** The held record is gone; the next save or commit deletes its row, fenced by `family`'s claim
2060
- * and by the revision this store last saw (kept in `base` until the delete is written). */
2061
- markDeleted(id, family) {
2062
- this.liveItems.forget(id);
2063
- this.coldReads.forget(id);
2064
- const read = this.coldBase.get(id);
2065
- if (!this.base.has(id) && read)
2066
- this.base.set(id, storedRow(read));
2067
- this.dirty.delete(id);
2068
- this.deleted.add(id);
2069
- this.deletedFamilies.set(id, family);
2070
- this.historyOwed.add(id);
2071
- }
2072
- /** Debounced so token-usage updates don't rewrite a row per event. Nothing to schedule without
2073
- * a database: a `RunStore.unavailable` store, or a closed one, writes nothing. */
2074
- scheduleSave() {
2075
- if (this.saveTimer || !this.db)
2076
- return;
2077
- this.saveTimer = setTimeout(() => {
2078
- this.saveTimer = null;
2079
- this.saveNow();
2080
- }, 300);
2081
- this.saveTimer.unref?.();
2082
- }
2083
- /** The single database write, so a test can fail it the way a full disk would. */
2084
- writeIndex(changes) {
2085
- const transaction = (changes) => { assertProjectWritable(this.dataDir); return this.db.transaction(changes); };
2086
- return this.persistence ? this.persistence(changes, transaction) : transaction(changes);
2087
- }
2088
- /**
2089
- * Write `staged` plus everything still pending — dirty rows from memory, deletions — in one
2090
- * transaction, then clear the pending marks. Throws with nothing cleared when it fails.
2091
- * Never copies or sorts the whole store: the cost is the rows that changed.
2092
- *
2093
- * Fenced (#779, plan step 3): the transaction commits only if every family it writes still
2094
- * carries this store's claim and every row is at the revision this store last saw. Otherwise
2095
- * nothing is written and `handleConflicts` deals with the rows that changed under it.
2096
- */
2097
- persist(staged) {
2098
- const upserts = [];
2099
- const deletes = [];
2100
- const families = new Map();
2101
- const extras = new Map();
2102
- const encode = (run) => {
2103
- const encoded = encodeRawRecord(run, (this.base.get(run.id) ?? this.coldBase.get(run.id))?.extras);
2104
- extras.set(run.id, encoded.extras);
2105
- const projected = { ...run };
2106
- restoreOriginatingIssue(projected);
2107
- upserts.push({ ...encodeRunRow(run, encoded.data),
2108
- issueAttributionCurrent: isDeepStrictEqual(projected, run) });
2109
- };
2110
- for (const [id, next] of staged) {
2111
- if (next)
2112
- encode(next);
2113
- else
2114
- deletes.push(id);
2115
- families.set(id, next ? familyKey(next) : this.familyOf(id));
2116
- }
2117
- for (const id of this.dirty) {
2118
- const run = this.held.get(id);
2119
- if (!run || staged.has(id))
2120
- continue;
2121
- encode(run);
2122
- families.set(id, familyKey(run));
2123
- }
2124
- for (const id of this.deleted) {
2125
- if (staged.has(id))
2126
- continue;
2127
- deletes.push(id);
2128
- families.set(id, this.familyOf(id));
2129
- }
2130
- // A row's insertion order (`seq`) is the order this write inserts it in, and it is where the
2131
- // run lists among runs created in the same millisecond. Insert new runs in creation order (the
2132
- // held set's, then staged runs not held yet), whether staged or dirty brought them here.
2133
- if (upserts.filter((row) => !this.base.has(row.id)).length > 1) {
2134
- const created = new Map();
2135
- for (const id of [...this.held.keys(), ...staged.keys()])
2136
- if (!created.has(id))
2137
- created.set(id, created.size);
2138
- upserts.sort((a, b) => created.get(a.id) - created.get(b.id));
2139
- }
2140
- // A held run whose write moved it into a new family (a worker quarantined to `invalid`) takes
2141
- // that family's claim first; one it cannot take fails the fence below as claim-lost.
2142
- const moved = [...new Set(families.values())].filter((family) => !this.claimed.has(family) && !this.pendingClaims.has(family));
2143
- if (moved.length > 0)
2144
- this.claimFamilies(moved, { allowLive: true });
2145
- let commit;
2146
- try {
2147
- commit = this.writeIndex({ upserts, deletes, ...(this.owner ? { fence: this.fence(families) } : {}) });
2148
- }
2149
- catch (error) {
2150
- if (error instanceof RunConflictError)
2151
- this.handleConflicts(error, staged);
2152
- throw error;
2153
- }
2154
- for (const [family, generation] of commit.claims) {
2155
- this.claimed.set(family, generation);
2156
- this.pendingClaims.delete(family);
2157
- }
2158
- for (const row of upserts) {
2159
- this.base.set(row.id, { revision: commit.revisions.get(row.id), seq: commit.seqs.get(row.id), data: row.data, extras: extras.get(row.id) });
2160
- }
2161
- for (const id of deletes) {
2162
- this.liveItems.forget(id);
2163
- this.base.delete(id);
2164
- this.deletedFamilies.delete(id);
2165
- this.retention.removeOwedHistory(id);
2166
- }
2167
- this.dirty.clear();
2168
- this.deleted.clear();
2169
- if (this.saveTimer) {
2170
- clearTimeout(this.saveTimer);
2171
- this.saveTimer = null;
2172
- }
2173
- }
2174
- /** What a write of these rows (id → family) must still find: this store's claims, at the
2175
- * generations it took them, and each row at the revision it last saw (none for a new row). */
2176
- fence(families) {
2177
- const claims = new Map();
2178
- const rows = new Map();
2179
- for (const [id, family] of families) {
2180
- const pending = this.pendingClaims.get(family);
2181
- // Generations start at 1, so an unclaimed family's 0 fails the fence as claim-lost.
2182
- claims.set(family, pending !== undefined ? { take: pending } : { generation: this.claimed.get(family) ?? 0 });
2183
- rows.set(id, { revision: (this.base.get(id) ?? this.coldBase.get(id))?.revision ?? null, family });
2184
- }
2185
- return { owner: this.owner, claims, rows };
2186
- }
2187
- /**
2188
- * Handle a fenced-write conflict. Save unexpected conflict evidence before clearing pending
2189
- * state or quarantining the row. If evidence persistence fails, retain pending writes. Other
2190
- * rows remain writable; stale unclaimed reads only fail their write.
2191
- */
2192
- handleConflicts(error, staged) {
2193
- const unexpected = error.conflicts.filter((conflict) => this.held.has(conflict.id) || this.deleted.has(conflict.id) || this.coldBase.get(conflict.id)?.owned === true);
2194
- if (unexpected.length === 0 || !this.db || !this.owner)
2195
- return;
2196
- const evidence = unexpected.map((conflict) => {
2197
- const seen = this.base.get(conflict.id) ?? this.coldBase.get(conflict.id);
2198
- const local = staged.has(conflict.id) ? staged.get(conflict.id) : this.deleted.has(conflict.id) ? null : this.held.get(conflict.id) ?? null;
2199
- return {
2200
- runId: conflict.id, reason: conflict.reason,
2201
- baseRevision: seen?.revision ?? null, baseData: seen?.data ?? null,
2202
- localData: local === null ? null : JSON.stringify(local), localDeleted: local === null,
2203
- currentRevision: conflict.current?.revision ?? null, currentData: conflict.current?.data ?? null,
2204
- };
2205
- });
2206
- let seqs;
2207
- try {
2208
- seqs = this.db.recordConflicts(this.owner.session, evidence);
2209
- }
2210
- catch (evidenceError) {
2211
- const message = evidenceError instanceof Error ? evidenceError.message : String(evidenceError);
2212
- console.error(`[hsq] ${RUNS_DB_FILE}: could not record the conflicting write on ${unexpected.map((c) => c.id).join(', ')}; it stays pending: ${message}`);
2213
- return;
2214
- }
2215
- unexpected.forEach((conflict, index) => {
2216
- const family = this.familyOf(conflict.id);
2217
- this.liveItems.forget(conflict.id);
2218
- this.quarantined.add(conflict.id);
2219
- this.coldReads.forget(conflict.id);
2220
- this.dirty.delete(conflict.id);
2221
- this.deleted.delete(conflict.id);
2222
- this.deletedFamilies.delete(conflict.id);
2223
- // The delete did not happen, so the history stays with the row.
2224
- this.historyOwed.delete(conflict.id);
2225
- if (conflict.reason === 'claim-lost') {
2226
- this.claimed.delete(family);
2227
- this.pendingClaims.delete(family);
2228
- }
2229
- const decoded = conflict.current ? decodeRunRow(conflict.current.data) : undefined;
2230
- const current = decoded?.run;
2231
- if (this.isFallbackRun(conflict.id))
2232
- this.held.delete(conflict.id);
2233
- const held = this.held.get(conflict.id);
2234
- const before = snapshotRun(held ?? staged.get(conflict.id) ?? undefined);
2235
- if (current && conflict.current) {
2236
- // The other writer's record as it stands, normalized only as a live owner's run would be.
2237
- reconcileLoadedRun(current, { keepLive: true });
2238
- rescopeRun(current, this.repoHandle);
2239
- if (held)
2240
- replaceRecord(held, current);
2241
- this.base.set(conflict.id, { revision: conflict.current.revision, seq: conflict.current.seq, data: conflict.current.data, extras: decoded.extras });
2242
- publishRunWrite(this.published, held ?? current, before ?? snapshotRun(current), 'conflict');
2243
- }
2244
- else {
2245
- this.held.delete(conflict.id);
2246
- this.base.delete(conflict.id);
2247
- this.published.publish('run.deleted', { runId: conflict.id });
2248
- }
2249
- console.error(`[hsq] run ${conflict.id} was changed by another writer (${conflict.reason}); this process will not write it again until Squawk restarts. Evidence: ${join(this.dataDir, RUNS_DB_FILE)}, table run_conflicts, seq ${seqs[index]}.`);
2250
- });
2251
- this.scheduleSave();
2252
- }
2253
- /** Write what is pending, then (unless closing) let every run whose write settled leave memory. */
2254
- saveNow(evict = true) {
2255
- if (!this.db || projectWriteRefused(this.dataDir))
2256
- return;
2257
- // A second attempt only after a conflict excluded its rows: the unrelated rest goes out at once.
2258
- for (let attempt = 0; attempt < 2 && (this.dirty.size > 0 || this.deleted.size > 0); attempt++) {
2259
- const quarantined = this.quarantined.size;
2260
- try {
2261
- this.persist(new Map());
2262
- }
2263
- catch (err) {
2264
- if (err instanceof RunConflictError && this.quarantined.size > quarantined)
2265
- continue;
2266
- // A pending save may outlive its directory; never recreate it or hide live-directory
2267
- // failures. The rows stay pending (and held), so the next save or commit retries them.
2268
- if (existsSync(this.dataDir)) {
2269
- const message = err instanceof Error ? err.message : String(err);
2270
- console.error(`[hsq] failed to save ${RUNS_DB_FILE}: ${message}`);
2271
- }
2272
- break;
2273
- }
2274
- }
2275
- if (evict)
2276
- this.evictSettled();
2277
- }
2278
1568
  /**
2279
1569
  * Write what is pending and release the database (store disposal, process shutdown).
2280
1570
  * Idempotent. A closed store keeps answering reads for what it holds — the final save evicts
@@ -2287,11 +1577,7 @@ export class RunStore {
2287
1577
  this.published.publish('store.closed', {});
2288
1578
  this.archive.compressor.stop();
2289
1579
  this.transcriptFacts.stop();
2290
- if (this.saveTimer) {
2291
- clearTimeout(this.saveTimer);
2292
- this.saveTimer = null;
2293
- }
2294
- this.saveNow(false);
1580
+ this.persistence.closeSave();
2295
1581
  if (this.db && this.owner) {
2296
1582
  // Every claim goes with the store. Should the release fail, the claims stay until this
2297
1583
  // process exits; from then on they are provably dead and the next opener takes them.