@hearsay-tools/squawk 0.18.0-dev.7820 → 0.18.0-dev.7830

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 (129) hide show
  1. package/dist/activity/read-model.d.ts +3 -1
  2. package/dist/activity/read-model.js +17 -15
  3. package/dist/activity/read-model.js.map +1 -1
  4. package/dist/activity/requests.d.ts +3 -1
  5. package/dist/activity/requests.js +1 -1
  6. package/dist/activity/requests.js.map +1 -1
  7. package/dist/artifacts/reports-index.d.ts +3 -7
  8. package/dist/artifacts/reports-index.js +6 -6
  9. package/dist/artifacts/reports-index.js.map +1 -1
  10. package/dist/automations/service.js +1 -1
  11. package/dist/automations/service.js.map +1 -1
  12. package/dist/automations/task-template.js +3 -3
  13. package/dist/automations/task-template.js.map +1 -1
  14. package/dist/ci-wait/controller.d.ts +42 -42
  15. package/dist/delegation/conversations.d.ts +6 -2
  16. package/dist/delegation/conversations.js +1 -1
  17. package/dist/delegation/conversations.js.map +1 -1
  18. package/dist/delegation/family-end.d.ts +4 -2
  19. package/dist/delegation/family-end.js +1 -1
  20. package/dist/delegation/family-end.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/task-discovery.js +1 -1
  24. package/dist/delegation/task-discovery.js.map +1 -1
  25. package/dist/delegation/worker-cleanup.js +4 -4
  26. package/dist/delegation/worker-cleanup.js.map +1 -1
  27. package/dist/project-commands.js +1 -1
  28. package/dist/project-commands.js.map +1 -1
  29. package/dist/project-migration/live.js +1 -1
  30. package/dist/project-migration/live.js.map +1 -1
  31. package/dist/runs/branch-owners.d.ts +2 -2
  32. package/dist/runs/cold-reads.d.ts +1 -1
  33. package/dist/runs/cold-reads.js +1 -1
  34. package/dist/runs/lifecycle.d.ts +2 -1
  35. package/dist/runs/lifecycle.js.map +1 -1
  36. package/dist/runs/live-tasks.js +1 -1
  37. package/dist/runs/live-tasks.js.map +1 -1
  38. package/dist/runs/ports.d.ts +63 -31
  39. package/dist/runs/retention.d.ts +4 -3
  40. package/dist/runs/retention.js +2 -2
  41. package/dist/runs/retention.js.map +1 -1
  42. package/dist/runs/run-cold-reads.d.ts +98 -0
  43. package/dist/runs/run-cold-reads.js +194 -0
  44. package/dist/runs/run-cold-reads.js.map +1 -0
  45. package/dist/runs/run-persistence.d.ts +150 -0
  46. package/dist/runs/run-persistence.js +396 -0
  47. package/dist/runs/run-persistence.js.map +1 -0
  48. package/dist/runs/run-queries.d.ts +190 -0
  49. package/dist/runs/run-queries.js +480 -0
  50. package/dist/runs/run-queries.js.map +1 -0
  51. package/dist/runs/run-repo-scope.d.ts +38 -0
  52. package/dist/runs/run-repo-scope.js +78 -0
  53. package/dist/runs/run-repo-scope.js.map +1 -0
  54. package/dist/runs/run-retention.d.ts +6 -2
  55. package/dist/runs/run-retention.js +11 -2
  56. package/dist/runs/run-retention.js.map +1 -1
  57. package/dist/runs/store.d.ts +12 -292
  58. package/dist/runs/store.js +122 -1119
  59. package/dist/runs/store.js.map +1 -1
  60. package/dist/serve-boot.d.ts +3 -1
  61. package/dist/serve-boot.js +2 -2
  62. package/dist/serve-boot.js.map +1 -1
  63. package/dist/server/models-routes.d.ts +13 -13
  64. package/dist/server/project-context.js +3 -3
  65. package/dist/server/project-context.js.map +1 -1
  66. package/dist/server/repo-branches.d.ts +5 -3
  67. package/dist/server/repo-branches.js +1 -1
  68. package/dist/server/repo-branches.js.map +1 -1
  69. package/dist/server/reports-api.d.ts +2 -2
  70. package/dist/server/run-checkout.d.ts +3 -1
  71. package/dist/server/run-checkout.js +2 -2
  72. package/dist/server/run-checkout.js.map +1 -1
  73. package/dist/server/run-relationships.d.ts +3 -1
  74. package/dist/server/run-relationships.js +1 -1
  75. package/dist/server/run-relationships.js.map +1 -1
  76. package/dist/server/server.d.ts +58 -58
  77. package/dist/server/server.js +12 -12
  78. package/dist/server/server.js.map +1 -1
  79. package/dist/server/start-server.js +1 -1
  80. package/dist/server/start-server.js.map +1 -1
  81. package/dist/workflows/run/auto-resume.js +2 -2
  82. package/dist/workflows/run/auto-resume.js.map +1 -1
  83. package/dist/workflows/run/completion-gate.js +1 -1
  84. package/dist/workflows/run/completion-gate.js.map +1 -1
  85. package/dist/workflows/run/continuation-acceptance.js +2 -2
  86. package/dist/workflows/run/continuation-acceptance.js.map +1 -1
  87. package/dist/workflows/run/family-reconciler.d.ts +2 -1
  88. package/dist/workflows/run/family-reconciler.js +8 -8
  89. package/dist/workflows/run/family-reconciler.js.map +1 -1
  90. package/dist/workflows/run/maintenance-claims.js +2 -2
  91. package/dist/workflows/run/maintenance-claims.js.map +1 -1
  92. package/dist/workflows/run/native-skill-input-queue.js +1 -1
  93. package/dist/workflows/run/native-skill-input-queue.js.map +1 -1
  94. package/dist/workflows/run/queued-revival.js +3 -3
  95. package/dist/workflows/run/queued-revival.js.map +1 -1
  96. package/dist/workflows/run/run-cancel.js +5 -5
  97. package/dist/workflows/run/run-cancel.js.map +1 -1
  98. package/dist/workflows/run/run-finish.js +1 -1
  99. package/dist/workflows/run/run-finish.js.map +1 -1
  100. package/dist/workflows/run/run-line.js +2 -2
  101. package/dist/workflows/run/run-line.js.map +1 -1
  102. package/dist/workflows/run/run-recovery.js +6 -6
  103. package/dist/workflows/run/run-recovery.js.map +1 -1
  104. package/dist/workflows/run/run-settlement.js +4 -4
  105. package/dist/workflows/run/run-settlement.js.map +1 -1
  106. package/dist/workflows/run/run-start.js +1 -1
  107. package/dist/workflows/run/run-start.js.map +1 -1
  108. package/dist/workflows/run/step-loop.js +4 -4
  109. package/dist/workflows/run/step-loop.js.map +1 -1
  110. package/dist/workflows/run/turn-nudges.js +1 -1
  111. package/dist/workflows/run/turn-nudges.js.map +1 -1
  112. package/dist/workflows/run/turn-settler.js +1 -1
  113. package/dist/workflows/run/turn-settler.js.map +1 -1
  114. package/dist/workflows/run/usage-accounting.js +1 -1
  115. package/dist/workflows/run/usage-accounting.js.map +1 -1
  116. package/dist/workflows/run/wake-admission.js +1 -1
  117. package/dist/workflows/run/wake-admission.js.map +1 -1
  118. package/dist/workflows/run/worker-questions.js +3 -3
  119. package/dist/workflows/run/worker-questions.js.map +1 -1
  120. package/dist/workflows/run.js +1 -1
  121. package/dist/workflows/run.js.map +1 -1
  122. package/package.json +4 -4
  123. package/scripts/benchmark-automation-lookups.ts +2 -2
  124. package/scripts/benchmark-conversation-lookup.ts +2 -2
  125. package/scripts/benchmark-family-reconcile.ts +2 -2
  126. package/scripts/benchmark-run-store.ts +3 -3
  127. package/scripts/benchmark-workspace-events.ts +2 -2
  128. package/scripts/benchmark-worktree-retention.ts +1 -1
  129. package/scripts/seed-archive-profile.ts +2 -2
@@ -1,10 +1,8 @@
1
1
  import { legacyIndexRows, readableSavedRunner, upgradeLegacyRunRow, withKeptFields } from './legacy-run-rows.js';
2
2
  import { addRunSource, fallbackRunSource } from './project-run-sources.js';
3
3
  import { registeredWaitRecord, registeredReceiptRecord } from './wait-registration-write.js';
4
- import { stageCommit, stageDurableUpdate, stageDebouncedUpdate, stageConversation, stageStepUpdate, stepTotals, redactPatch } from './record-write-rules.js';
5
- import { publishRunWrite, RunLifecycle, snapshotRun } from './lifecycle.js';
6
- import { listPeerTaskSummaries, parseStoredSummary } from './run-summary-page.js';
7
- export { parseStoredSummary } from './run-summary-page.js';
4
+ import { stageDurableUpdate, stageDebouncedUpdate, stageConversation, stageStepUpdate, stepTotals, redactPatch } from './record-write-rules.js';
5
+ import { RunLifecycle, snapshotRun } from './lifecycle.js';
8
6
  import { workerExecutionsFactory } from './worker-executions-registry.js';
9
7
  import { randomUUID } from 'node:crypto';
10
8
  import { isDeepStrictEqual } from 'node:util';
@@ -13,13 +11,11 @@ import { join } from 'node:path';
13
11
  import { z } from 'zod';
14
12
  import { delegationStateSchema, workerDestroyRetrySchema, } from '../contract/index.js';
15
13
  import { agentInputSchema, inboxClaimSchema } from '../contract/index.js';
16
- import { stepStateSchema as contractStepStateSchema, toRunSummary, runRecordSchema as contractRunRecordSchema, runPullRequestSchema, } from '../contract/index.js';
14
+ import { stepStateSchema as contractStepStateSchema, runRecordSchema as contractRunRecordSchema, runPullRequestSchema, } from '../contract/index.js';
17
15
  import { queuedMessageSchema } from '../contract/index.js';
18
16
  import { previewServerSchema } from '../contract/index.js';
19
17
  import { waitSchema } from '../contract/index.js';
20
18
  import { isUsageLimitHold } from '../contract/index.js';
21
- import { REFERENCED_RUN_RULE } from '../contract/index.js';
22
- import { matchesRunSearch, sqlPrefilterTokens } from '../contract/index.js';
23
19
  import { storedDelegationStateSchema } from './delegation-state.js';
24
20
  import { LiveItemSnapshots } from './live-item-snapshots.js';
25
21
  import { RunTranscriptFacts } from './transcript-facts-topic.js';
@@ -27,22 +23,17 @@ import { restoreHistory } from './history-file.js';
27
23
  // Type-only module (zod + nothing else), so this cannot cycle back into the store.
28
24
  import { workflowDefSchema } from '../workflows/types.js';
29
25
  import { applyOutcomes } from './outcome-commit.js';
30
- import { ISSUE_URL_RE, namesForeignReference, rescopeRun, restoreOriginatingIssue, trackReferencedIssues, trackReferencedPrs } from './run-references.js';
26
+ import { trackReferencedIssues, trackReferencedPrs } from './run-references.js';
31
27
  import { applyExit, doneCommits, exitDurability, RUN_EXITS } from './run-exits.js';
32
28
  import { assertConversationIdFree } from './conversation-identity.js';
33
29
  export { ConversationIdInUseError } from './conversation-identity.js';
34
30
  import { LEGACY_RUNNER_IDS } from '../core/runner-ids.js';
35
- import { ARCHIVED_ROOT, RUNS_DB_FILE, RUNS_IMPORT_COMPLETE_KEY, RunConflictError, RunDatabase, RunDatabaseBusyError, } from './run-database.js';
36
- import { listBranchOwners } from './branch-owners.js';
37
- import { guardedJsonSql } from './guarded-json-sql.js';
38
- import { reconcileLoadedRun } from './loaded-run-exits.js';
31
+ import { RUNS_DB_FILE, RUNS_IMPORT_COMPLETE_KEY, RunDatabase, RunDatabaseBusyError, } from './run-database.js';
39
32
  import { hasLegacyWaitFields, UNREADABLE_WAIT } from './legacy-waits.js';
40
33
  export { ciWaitEntry, holdsWorkerWait, upgradeLegacyWaits, workerWaitEntry } from './legacy-waits.js';
41
34
  import { ExitEvents } from './exit-events.js';
42
- import { encodeRunRow, familyRootOf, isLiveRecord, materializedWorktreePath, newestFirst } from './run-row.js';
43
35
  import { RunRetentionTopic } from './run-retention.js';
44
- import { collectRawExtras, encodeRawRecord } from './raw-record.js';
45
- import { ColdReadCache, storedRow } from './cold-reads.js';
36
+ import { collectRawExtras } from './raw-record.js';
46
37
  import { LEGACY_INDEX_FILE, LegacyWriterError } from './legacy-index.js';
47
38
  import { toRunStoreOpenError } from './store-open-error.js';
48
39
  import { importLegacyIndex, OPEN_RETRY_DELAYS_MS, sleepSync } from './store-open.js';
@@ -54,8 +45,11 @@ import { RunEventLogTopic } from './event-log.js';
54
45
  import { RunRedaction } from './run-redaction.js';
55
46
  import { RunArchiveTopic } from './run-archive.js';
56
47
  import { RunReadFlagsTopic } from './run-read-flags.js';
57
- import { closeClaimSession, familyKey, openClaimSession, rowFamily } from './run-claims.js';
58
- import { assertProjectWritable, projectWriteRefused } from '../server/cockpit-ownership.js';
48
+ import { replaceRecord, RunPersistenceTopic } from './run-persistence.js';
49
+ import { closeClaimSession, openClaimSession } from './run-claims.js';
50
+ import { RunColdReadsTopic } from './run-cold-reads.js';
51
+ import { RunQueriesTopic, sortNewestFirst } from './run-queries.js';
52
+ import { RunRepoScopeTopic } from './run-repo-scope.js';
59
53
  /**
60
54
  * A runner id as it may appear in a PERSISTED record (#547), spec 2026-11-18-runner-definitions.
61
55
  *
@@ -181,14 +175,6 @@ export { LEGACY_INDEX_BACKUP_FILE, LEGACY_INDEX_FILE } from './legacy-index.js';
181
175
  * and `GET /workspace/runs-index`. Unarchived runs are never cut; older archived runs page in
182
176
  * through `GET /run-summaries/archived` and the workspace search. */
183
177
  export const ARCHIVED_WINDOW = 200;
184
- export { branchOwnerOf } from './branch-owners.js';
185
- /** Make `target` hold exactly `source`'s fields, keeping the object every holder references. */
186
- function replaceRecord(target, source) {
187
- for (const key of Object.keys(target))
188
- if (!(key in source))
189
- delete target[key];
190
- Object.assign(target, source);
191
- }
192
178
  /**
193
179
  * A worker's destroy moving between two unfinished phases, and nothing else changing: nothing the
194
180
  * family reconcile reads changed, so it may skip that pass (#880). The first request and the
@@ -201,38 +187,6 @@ function isDestroyProgress(before, after) {
201
187
  return false;
202
188
  return isDeepStrictEqual({ ...before, destroy: undefined }, { ...after, destroy: undefined });
203
189
  }
204
- /** An archived page's cursor: the last row's order, opaque to clients. A held run with no row yet
205
- * lists after every row (`seq` is infinite), which JSON cannot carry, so it travels as null. */
206
- function encodeArchivedCursor(key) {
207
- return Buffer.from(JSON.stringify({ c: key.createdAt, s: Number.isFinite(key.seq) ? key.seq : null })).toString('base64url');
208
- }
209
- function decodeArchivedCursor(cursor) {
210
- try {
211
- const parsed = JSON.parse(Buffer.from(cursor, 'base64url').toString('utf8'));
212
- if (typeof parsed !== 'object' || parsed === null)
213
- return undefined;
214
- const { c, s } = parsed;
215
- if (typeof c !== 'string' || !(s === null || (typeof s === 'number' && Number.isInteger(s))))
216
- return undefined;
217
- return { createdAt: c, seq: s ?? Number.POSITIVE_INFINITY };
218
- }
219
- catch {
220
- return undefined;
221
- }
222
- }
223
- /** The items newest first, each by the order beside it. Stable: ties keep their input order. */
224
- function sortNewestFirst(entries) {
225
- return [...entries].sort(([, a], [, b]) => newestFirst(a, b)).map(([item]) => item);
226
- }
227
- /** Tests freeze the copies of cold runs, so an in-place write to one throws instead of vanishing. */
228
- function deepFreeze(value) {
229
- if (value && typeof value === 'object' && !Object.isFrozen(value)) {
230
- Object.freeze(value);
231
- for (const child of Object.values(value))
232
- deepFreeze(child);
233
- }
234
- return value;
235
- }
236
190
  /**
237
191
  * Run rows in runs.db plus append-only NDJSON events and an in-process event bus. Hold live,
238
192
  * pinned, related and unsettled records only. Optimistic writes debounce; durable commits
@@ -246,15 +200,11 @@ export class RunStore {
246
200
  pins = new Map();
247
201
  /** Staged ids while a durable commit installs and announces them: never evicted mid-commit. */
248
202
  committing = new Set();
249
- saveTimer = null;
250
203
  /** `null` once the store is closed, and in a `RunStore.unavailable` store (nothing is written,
251
204
  * nothing is evicted). */
252
205
  db = null;
253
- /** Persistence source for consumers that build the reports index. No index is created here. */
254
- reportSource() { return { db: this.db, dataDir: this.dataDir, openFailure: this.openFailure }; }
255
206
  /** Why `open` failed, in a `RunStore.unavailable` store. */
256
207
  openFailure;
257
- persistence;
258
208
  /** Runs whose held record is ahead of its row; the next save or commit writes them. */
259
209
  dirty = new Set();
260
210
  /** The typed lifecycle events the store publishes after each write (lifecycle.ts). */
@@ -267,10 +217,6 @@ export class RunStore {
267
217
  /** Deleted runs whose history files (events, handoff, images, artifacts) go once the delete of
268
218
  * their row commits: until then a conflict can undo the delete and bring the row back. */
269
219
  historyOwed = new Set();
270
- /** The repository this project IS (#945), armed after `open()` by `setRepoHandle`. Undefined
271
- * until it arrives and `null` when it cannot be known — both mean "unscoped", which is
272
- * exactly the pre-#945 behavior. */
273
- repoHandle;
274
220
  /** `open()`'s `keepLive`, which a run read later from `runs.db` is reconciled with too. */
275
221
  keepLive = false;
276
222
  /** This store's identity in `run_claims`; undefined without a database. */
@@ -285,18 +231,8 @@ export class RunStore {
285
231
  * created the row and has not written it yet. `extras` is what that `data` holds beyond the
286
232
  * schema, which the next write of the row puts back (raw-record.ts). */
287
233
  base = new Map();
288
- /** Rows read cold in the current synchronous turn, so a commit staged from one is fenced against
289
- * the version it was computed from. `owned`: its family was already this store's when read.
290
- * Cleared at the next microtask: no commit spans a turn. */
291
- coldBase = new Map();
292
- coldReads = new ColdReadCache();
293
- /** The family of each pending deletion, whose claim the deleting write is fenced against. */
294
- deletedFamilies = new Map();
295
234
  /** Rows a conflicting write excluded: this store refuses to write them until it is reopened. */
296
235
  quarantined = new Set();
297
- /** Rows whose `data` this store tried to decode and could not: left in the database untouched,
298
- * and left out of the list rows from then on, as the cold reader leaves them out (run-index.ts). */
299
- unreadable = new Set();
300
236
  /** The archive flag, archive on merge, completion actions and the transcript compressor (hearsay-tools/squawk#4041). */
301
237
  archive;
302
238
  /** The pinned and read flags (hearsay-tools/squawk#4041). */
@@ -315,13 +251,21 @@ export class RunStore {
315
251
  claims;
316
252
  /** The holds that keep a run loaded (hearsay-tools/squawk#4042). */
317
253
  runPins;
254
+ /** Flush, persist, the fence, conflicts and the save debounce (hearsay-tools/squawk#4043). */
255
+ persistence;
256
+ /** The held set's cold reads, holds and eviction (hearsay-tools/squawk#4044). */
257
+ rows;
258
+ /** The list and find queries (hearsay-tools/squawk#4044). */
259
+ queries;
260
+ /** The repository this project is, and the repair of the runs it rescopes (hearsay-tools/squawk#4044). */
261
+ repoScope;
318
262
  executions;
319
263
  /** A worker's execution, process, identity and scope records (hearsay-tools/squawk#4039), built on
320
264
  * first use by the factory this process registered; throws when none is registered. */
321
265
  get workerExecutions() {
322
266
  return this.executions ??= workerExecutionsFactory()(this.dataDir, {
323
- peek: (id) => this.peek(id), getRun: (id) => this.getRun(id), writeDir: (id) => this.claims.writeDir(id),
324
- sourceDataDir: (id) => this.claims.sourceDataDir(id), commitIndex: (input) => this.commitIndex(input),
267
+ peek: (id) => this.rows.peek(id), getRun: (id) => this.getRun(id), writeDir: (id) => this.claims.writeDir(id),
268
+ sourceDataDir: (id) => this.claims.sourceDataDir(id), commitIndex: (input) => this.persistence.commitIndex(input),
325
269
  published: this.published, workerResults: this.workerResults,
326
270
  });
327
271
  }
@@ -330,68 +274,83 @@ export class RunStore {
330
274
  liveReadSnapshot(runId) {
331
275
  return { events: this.liveItems.read(runId), throughSeq: this.seqs.get(runId) ?? Infinity };
332
276
  }
333
- constructor(dataDir) {
277
+ constructor(dataDir, persist) {
334
278
  this.dataDir = dataDir;
279
+ this.rows = new RunColdReadsTopic({
280
+ db: () => this.db, keepLive: () => this.keepLive, repoHandle: () => this.repoScope.repoHandle, held: this.held, pins: this.pins,
281
+ committing: this.committing, dirty: this.dirty, deleted: this.deleted, quarantined: this.quarantined, claimed: this.claimed,
282
+ pendingClaims: this.pendingClaims, base: this.base, claims: () => this.claims, persistence: () => this.persistence, decodeRunRow,
283
+ });
335
284
  this.redaction = new RunRedaction();
336
285
  this.claims = new RunClaimsTopic(dataDir, {
337
286
  db: () => this.db, owner: () => this.owner, keepLive: () => this.keepLive, held: this.held, base: this.base, dirty: this.dirty,
338
- deleted: this.deleted, quarantined: this.quarantined, unreadable: this.unreadable, claimed: this.claimed, pendingClaims: this.pendingClaims,
339
- exitEvents: this.exitEvents, coldReads: this.coldReads, decodeRunRow, anchoredFamilies: () => this.anchoredFamilies(), scheduleSave: () => this.scheduleSave(),
287
+ deleted: this.deleted, quarantined: this.quarantined, unreadable: this.rows.unreadable, claimed: this.claimed, pendingClaims: this.pendingClaims,
288
+ exitEvents: this.exitEvents, coldReads: this.rows.coldReads, decodeRunRow, anchoredFamilies: () => this.rows.anchoredFamilies(), scheduleSave: () => this.persistence.scheduleSave(),
340
289
  });
341
- this.runPins = new RunPinsTopic({ pins: this.pins, published: this.published, record: (id) => this.record(id), peek: (id) => this.peek(id), sweepIfSettled: (ids) => this.sweepIfSettled(ids) });
290
+ this.runPins = new RunPinsTopic({ pins: this.pins, published: this.published, record: (id) => this.rows.record(id), peek: (id) => this.rows.peek(id), sweepIfSettled: (ids) => this.persistence.sweepIfSettled(ids) });
342
291
  this.transcriptFacts = new RunTranscriptFacts(dataDir, {
343
292
  isFallbackRun: (id) => this.claims.isFallbackRun(id),
344
293
  sourceDataDir: (id) => this.claims.sourceDataDir(id),
345
294
  isOpen: () => this.db !== null,
346
295
  held: this.held,
347
- listFamilyRunIds: (rootId) => this.listFamilyRunIds(rootId),
348
- listConversationRootIds: () => this.listConversationRootIds(),
349
- listRunIds: () => this.listRunIds(),
296
+ listFamilyRunIds: (rootId) => this.queries.listFamilyRunIds(rootId),
297
+ listConversationRootIds: () => this.queries.listConversationRootIds(),
298
+ listRunIds: () => this.queries.listRunIds(),
350
299
  });
351
300
  this.workerResults = new WorkerResultsTopic(dataDir, {
352
- peek: (id) => this.peek(id), hasRun: (id) => this.hasRun(id), hasFallbackRun: (id) => this.claims.hasFallbackRun(id),
301
+ peek: (id) => this.rows.peek(id), hasRun: (id) => this.rows.hasRun(id), hasFallbackRun: (id) => this.claims.hasFallbackRun(id),
353
302
  writeDir: (id) => this.claims.writeDir(id), sourceDataDir: (id) => this.claims.sourceDataDir(id),
354
303
  redactResult: (result) => this.redaction.redact({ type: 'worker-result', seq: 0, ts: result.observedAt, result }).result,
355
304
  redactText: (text) => this.redaction.redactText(text), commitDelegation: (patches) => this.commitDelegation(patches),
356
305
  });
357
306
  this.eventLog = new RunEventLogTopic(dataDir, {
358
307
  seqs: this.seqs, published: this.published, liveItems: this.liveItems, transcriptFacts: this.transcriptFacts, redaction: this.redaction,
359
- record: (id) => this.record(id), missingRunError: (runId) => this.claims.missingRunError(runId), sourceDataDir: (id) => this.claims.sourceDataDir(id),
360
- touch: (run, before) => this.touch(run, before), change: (id, apply) => this.change(id, apply), repoHandle: () => this.repoHandle,
308
+ record: (id) => this.rows.record(id), missingRunError: (runId) => this.claims.missingRunError(runId), sourceDataDir: (id) => this.claims.sourceDataDir(id),
309
+ touch: (run, before) => this.persistence.touch(run, before), change: (id, apply) => this.change(id, apply), repoHandle: () => this.repoScope.repoHandle,
361
310
  maybeEnqueueHistoryCompress: (run) => this.archive.maybeEnqueueHistoryCompress(run),
362
311
  });
363
312
  this.retention = new RunRetentionTopic(dataDir, {
364
313
  db: () => this.db, held: this.held, deleted: this.deleted, quarantined: this.quarantined,
365
314
  historyOwed: this.historyOwed, seqs: this.seqs, published: this.published, transcriptFacts: this.transcriptFacts,
366
- peek: (id) => this.peek(id), hasRun: (id) => this.hasRun(id), record: (id) => this.record(id),
367
- listWorkersOf: (parentId) => this.listWorkersOf(parentId), isFallbackRun: (id) => this.claims.isFallbackRun(id),
368
- hasFallbackRun: (id) => this.claims.hasFallbackRun(id), listOrder: (run) => this.listOrder(run),
369
- claimFamilies: (families) => this.claims.claimFamilies(families), markDeleted: (id, family) => this.markDeleted(id, family),
370
- scheduleSave: () => this.scheduleSave(), commitIndex: (input) => this.commitIndex(input),
315
+ peek: (id) => this.rows.peek(id), hasRun: (id) => this.rows.hasRun(id), record: (id) => this.rows.record(id),
316
+ listWorkersOf: (parentId) => this.queries.listWorkersOf(parentId), isFallbackRun: (id) => this.claims.isFallbackRun(id),
317
+ hasFallbackRun: (id) => this.claims.hasFallbackRun(id), listOrder: (run) => this.queries.listOrder(run),
318
+ claimFamilies: (families) => this.claims.claimFamilies(families), markDeleted: (id, family) => this.persistence.markDeleted(id, family),
319
+ scheduleSave: () => this.persistence.scheduleSave(), commitIndex: (input) => this.persistence.commitIndex(input),
371
320
  commitDelegation: (patches) => this.commitDelegation(patches), applyArchived: (run, archived) => this.archive.applyArchived(run, archived),
372
321
  workerDeletionEvidence: (id) => this.workerExecutions.workerDeletionEvidence(id),
373
322
  workerResults: this.workerResults,
374
323
  readWorkerExecution: (id) => this.workerExecutions.readWorkerExecution(id), identityPath: (id) => this.workerExecutions.identityPath(id),
375
324
  processesPath: (id) => this.workerExecutions.processesPath(id), scopePath: (id) => this.workerExecutions.scopePath(id),
376
- executionPath: (id) => this.workerExecutions.executionPath(id), handoffPath: (runId) => this.handoffPath(runId),
377
- imagesDir: (runId) => this.imagesDir(runId),
325
+ executionPath: (id) => this.workerExecutions.executionPath(id), sourceDataDir: (id) => this.claims.sourceDataDir(id),
378
326
  });
379
327
  this.archive = new RunArchiveTopic(dataDir, {
380
328
  db: () => this.db, held: this.held, deleted: this.deleted, quarantined: this.quarantined, pins: this.pins,
381
329
  claimed: this.claimed, base: this.base, owner: () => this.owner, transcriptFacts: this.transcriptFacts,
382
- decodeRunRow, sortNewestFirst, peek: (id) => this.peek(id), record: (id) => this.record(id),
383
- listWorkersOf: (parentId) => this.listWorkersOf(parentId), familyOf: (id) => this.familyOf(id),
330
+ decodeRunRow, sortNewestFirst, peek: (id) => this.rows.peek(id), record: (id) => this.rows.record(id),
331
+ listWorkersOf: (parentId) => this.queries.listWorkersOf(parentId), familyOf: (id) => this.persistence.familyOf(id),
384
332
  claimFamilies: (families, opts) => this.claims.claimFamilies(families, opts), writeRefusal: (id) => this.claims.writeRefusal(id),
385
- assertWritable: (staged) => this.assertWritable(staged), decodeCold: (row) => this.decodeCold(row),
386
- listOrder: (run) => this.listOrder(run), commitIndex: (input, source, write) => this.commitIndex(input, source, write),
387
- touch: (run, before, exit) => this.touch(run, before, exit),
333
+ assertWritable: (staged) => this.persistence.assertWritable(staged), decodeCold: (row) => this.rows.decodeCold(row),
334
+ listOrder: (run) => this.queries.listOrder(run), commitIndex: (input, source, write) => this.persistence.commitIndex(input, source, write),
335
+ touch: (run, before, exit) => this.persistence.touch(run, before, exit),
388
336
  readWorkerExecution: (id) => this.workerExecutions.readWorkerExecution(id),
389
337
  });
390
338
  this.readFlags = new RunReadFlagsTopic({
391
- db: () => this.db, held: this.held, deleted: this.deleted, record: (id) => this.record(id),
392
- claimFamilies: (families) => this.claims.claimFamilies(families), touch: (run, before) => this.touch(run, before),
339
+ db: () => this.db, held: this.held, deleted: this.deleted, record: (id) => this.rows.record(id),
340
+ claimFamilies: (families) => this.claims.claimFamilies(families), touch: (run, before) => this.persistence.touch(run, before),
393
341
  change: (id, apply) => this.change(id, apply),
394
342
  });
343
+ this.persistence = new RunPersistenceTopic(dataDir, persist, {
344
+ db: () => this.db, owner: () => this.owner, openFailure: () => this.openFailure, repoHandle: () => this.repoScope.repoHandle,
345
+ held: this.held, committing: this.committing, dirty: this.dirty, deleted: this.deleted, historyOwed: this.historyOwed,
346
+ quarantined: this.quarantined, claimed: this.claimed, pendingClaims: this.pendingClaims, base: this.base, coldBase: this.rows.coldBase,
347
+ coldReads: this.rows.coldReads, liveItems: this.liveItems, published: this.published, archive: this.archive, claims: this.claims,
348
+ retention: this.retention, decodeRunRow, peek: (id) => this.rows.peek(id), isAnchor: (id, run) => this.rows.isAnchor(id, run),
349
+ evictSettled: () => this.rows.evictSettled(),
350
+ });
351
+ this.queries = new RunQueriesTopic({ db: () => this.db, held: this.held, pins: this.pins, deleted: this.deleted, unreadable: this.rows.unreadable,
352
+ base: this.base, coldReads: this.rows.coldReads, rows: this.rows, getRun: (id) => this.getRun(id) });
353
+ this.repoScope = new RunRepoScopeTopic({ db: () => this.db, held: this.held, deleted: this.deleted, claims: this.claims, persistence: this.persistence, rows: this.rows });
395
354
  }
396
355
  /**
397
356
  * Open the project's run store. See `reconcileLoadedRun` for what `keepLive` (#367) decides
@@ -432,9 +391,8 @@ export class RunStore {
432
391
  const deferred = source && !existsSync(path) && !existsSync(join(dataDir, LEGACY_INDEX_FILE));
433
392
  if (!deferred)
434
393
  mkdirSync(join(dataDir, 'runs'), { recursive: true });
435
- const store = new RunStore(dataDir);
394
+ const store = new RunStore(dataDir, persist);
436
395
  store.keepLive = keepLive;
437
- store.persistence = persist;
438
396
  let db = RunDatabase.open(deferred ? ':memory:' : path);
439
397
  try {
440
398
  if (deferred)
@@ -485,396 +443,6 @@ export class RunStore {
485
443
  /** Why this store has no database, when it is `RunStore.unavailable`'s: its runs are unknown,
486
444
  * not absent. */
487
445
  get unavailable() { return this.openFailure; }
488
- /**
489
- * Whether a held run anchors itself (and its family) in memory. Anything else held is a family
490
- * member or a settled write, and leaves at the next sweep (`evictSettled`).
491
- *
492
- * The held set is: every run that is live (`isLiveRecord`), pinned by a RunManager (`pin`),
493
- * dirty, or inside a durable commit; plus the whole delegation family (root and direct
494
- * workers) of any such run. Families are held because the RunManager reads a live run's family
495
- * on every run event — `GET /runs/:id/relationships`, the global `reconcileWorkerWaits` pass
496
- * (about twenty call sites), completion blockers and conversations — and decoding a cold
497
- * record costs about 200 µs (JSON.parse plus the schema). Measured on a copy of a real
498
- * cockpit's `runs.json` (958 runs, 957 of them delegated): a running root with 26 workers
499
- * paid about 5 ms per family read, and the live families together about 10 ms per global
500
- * pass, all on the event loop. Holding them costs memory in proportion to active work, not to
501
- * history.
502
- */
503
- isAnchor(id, run) {
504
- return isLiveRecord(run) || this.pins.has(id) || this.dirty.has(id) || this.committing.has(id);
505
- }
506
- /** The family roots with an anchoring member in memory. */
507
- anchoredFamilies() {
508
- const roots = new Set();
509
- for (const [id, run] of this.held) {
510
- const root = familyRootOf(run);
511
- if (root !== undefined && this.isAnchor(id, run))
512
- roots.add(root);
513
- }
514
- return roots;
515
- }
516
- /** Drop every held run that is neither an anchor nor in an anchored family. A store without a
517
- * database keeps everything: memory is the only copy it has. */
518
- evictSettled() {
519
- if (!this.db)
520
- return;
521
- const families = this.anchoredFamilies();
522
- for (const [id, run] of this.held) {
523
- if (this.isAnchor(id, run))
524
- continue;
525
- const root = familyRootOf(run);
526
- if (root !== undefined && families.has(root))
527
- continue;
528
- this.held.delete(id);
529
- this.base.delete(id);
530
- this.coldReads.forget(id);
531
- }
532
- this.claims.releaseUnheldClaims();
533
- }
534
- /** A run read from `runs.db`, normalized like a loaded one (`reconcileLoadedRun`, then the
535
- * repository scope) but held by nobody. Undefined when absent, deleted or unreadable. */
536
- loadCold(id) {
537
- if (!this.db || this.deleted.has(id))
538
- return undefined;
539
- const row = this.db.get(id);
540
- return row ? this.decodeCold(row) : undefined;
541
- }
542
- /** `loaded` sees the record once the load has normalized it, before it is scoped: a heal's `before`. */
543
- decodeCold(row, loaded) {
544
- this.coldReads.at(row.id, row.revision); // the fence below moves to this revision
545
- const decoded = decodeRunRow(row.data);
546
- if (!decoded) {
547
- this.unreadable.add(row.id);
548
- return undefined;
549
- }
550
- this.unreadable.delete(row.id);
551
- const { run, extras } = decoded;
552
- if (this.coldBase.size === 0)
553
- queueMicrotask(() => this.coldBase.clear());
554
- const family = rowFamily(row);
555
- this.coldBase.set(row.id, { revision: row.revision, seq: row.seq, data: row.data, extras, owned: this.claimed.has(family) || this.pendingClaims.has(family) });
556
- reconcileLoadedRun(run, { keepLive: this.keepLive });
557
- loaded?.(run);
558
- rescopeRun(run, this.repoHandle);
559
- return run;
560
- }
561
- /** Hold a writable row. A fallback family's reads stay detached (the cold-read contract). */
562
- holdDecoded(run) {
563
- if (this.db?.familyHasFallback(familyKey(run)))
564
- return process.env.VITEST ? deepFreeze(run) : run;
565
- const read = this.coldBase.get(run.id);
566
- this.held.set(run.id, run);
567
- if (read)
568
- this.base.set(run.id, storedRow(read));
569
- return run;
570
- }
571
- /**
572
- * Hold a claimed run for a write; leave after settlement unless anchored.
573
- * Take the family claim before reading its row. Return undefined for a live foreign owner
574
- * or a fallback family: neither claim is granted.
575
- */
576
- hold(id) {
577
- const held = this.held.get(id);
578
- if (held)
579
- return held;
580
- const family = this.db && !this.deleted.has(id) ? this.db.familyOf(id) : undefined;
581
- if (family === undefined || !this.claims.claimFamilies([family]).has(family))
582
- return undefined;
583
- const run = this.coldReads.claimed(id, this.coldBase.get(id), () => this.db?.revisionOf(id)) ?? this.loadCold(id);
584
- if (!run)
585
- return undefined;
586
- this.holdDecoded(run);
587
- this.scheduleSave();
588
- return run;
589
- }
590
- /** The record a store write changes in place: held, or loaded to be. Undefined for a run this
591
- * store may not write (another process's, or quarantined), so the write changes nothing. */
592
- record(id) {
593
- if (this.quarantined.has(id))
594
- return undefined;
595
- return this.held.get(id) ?? this.hold(id);
596
- }
597
- /** Read held legacy family members, or a detached cold record. */
598
- peek(id) {
599
- const held = this.held.get(id);
600
- if (held)
601
- return held;
602
- const run = this.loadCold(id);
603
- return run && this.answerCold(run, false);
604
- }
605
- /**
606
- * A run just read off its row, as reads answer it: held when its family is in memory (a live
607
- * family's members are read on every run event), else a copy nobody holds — frozen under
608
- * vitest when it leaves the store (`freeze`).
609
- */
610
- answerCold(run, freeze) {
611
- const root = familyRootOf(run);
612
- if (root !== undefined && this.anchoredFamilies().has(root))
613
- return this.holdDecoded(run);
614
- return freeze && process.env.VITEST ? deepFreeze(run) : run;
615
- }
616
- /** `getRun` for a row a query already read: the held object, else decoded from `row`. */
617
- fromRow(row) {
618
- const held = this.held.get(row.id);
619
- if (held)
620
- return held;
621
- if (this.deleted.has(row.id))
622
- return undefined;
623
- const cached = this.coldReads.at(row.id, row.revision);
624
- if (cached)
625
- return cached;
626
- const run = this.decodeCold(row);
627
- return run && this.coldReads.keep(this.answerCold(run, true), this.coldBase.get(row.id), this.held.has(row.id));
628
- }
629
- /** Run `fn` reading each run that is not held at most once (`ColdReadCache`, hearsay-tools/cezarion#2378). */
630
- withReadCache(fn) { return this.coldReads.scope(fn); }
631
- /** Whether the run exists, held or not, without decoding it. */
632
- hasRun(id) {
633
- return this.held.has(id) || (!!this.db && !this.deleted.has(id) && this.db.has(id));
634
- }
635
- /**
636
- * Set discovered repository identity without blocking boot. Recompute conclusions from retained
637
- * evidence, including cold records; null retains unknown-handle behavior.
638
- */
639
- setRepoHandle(handle) {
640
- this.repoHandle = handle;
641
- if (!handle)
642
- return; // nothing to prove foreign against
643
- // `touch` per healed run: the cockpit is already live when the handle lands, so a corrected
644
- // chip has to reach the open page over SSE, not just the next `runs.json` write.
645
- let healed = false;
646
- const stored = this.db?.listWhere(guardedJsonSql(`${REFERENCED_RUN_RULE.sql} OR json_extract(summary, '$.pullRequests') IS NOT NULL`, 0)).filter((row) => {
647
- if (this.held.has(row.id) || this.deleted.has(row.id))
648
- return false;
649
- const summary = parseStoredSummary(row.summary);
650
- return !summary || namesForeignReference(summary, handle);
651
- }) ?? [];
652
- for (const run of [...this.held.values()]) {
653
- const before = snapshotRun(run);
654
- if (rescopeRun(run, this.repoHandle)) {
655
- this.touch(run, before);
656
- healed = true;
657
- }
658
- }
659
- // Only rows this store may write: another process's runs heal when their owner arms its handle.
660
- const writable = this.claims.claimFamilies(stored.map(rowFamily));
661
- for (const row of stored) {
662
- if (!writable.has(rowFamily(row)))
663
- continue;
664
- let before;
665
- const run = this.decodeCold(row, (loaded) => { before = snapshotRun(loaded); });
666
- // `decodeCold` already scoped it with the handle just armed; write it when that changed it.
667
- if (!run || !this.storedScopeDiffers(row, run))
668
- continue;
669
- this.holdDecoded(run);
670
- this.touch(run, before ?? snapshotRun(run));
671
- healed = true;
672
- }
673
- // Discovery may finish after headless shutdown's final flush. Persist repairs now: the
674
- // debounced save is unref'd, so it cannot keep the CLI alive once the lookup completes.
675
- if (healed)
676
- this.flush();
677
- }
678
- /** Whether the stored summary still names a reference the scoped record no longer has. */
679
- storedScopeDiffers(row, run) {
680
- const summary = parseStoredSummary(row.summary);
681
- return summary?.referencedPullRequestUrl !== run.referencedPullRequestUrl ||
682
- summary?.referencedIssueUrl !== run.referencedIssueUrl || summary?.issueNumber !== run.issueNumber || !isDeepStrictEqual(summary?.pullRequests, run.pullRequests);
683
- }
684
- /**
685
- * The live set, newest first: runs whose record is live (`isLiveRecord`) or that a RunManager
686
- * pins. Finished runs are not here — read one by id (`getRun`), by an indexed query
687
- * (`listWorkersOf`, `findRunByClientRequestId`, `listRunsWithWorktree`,
688
- * `listBranchOwners`), or as list rows (`listRunSummaries`).
689
- */
690
- listRuns() {
691
- return sortNewestFirst([...this.held].filter(([id, run]) => isLiveRecord(run) || this.pins.has(id)).map(([, run]) => [run, this.listOrder(run)]));
692
- }
693
- /** Where a held run lists: its row's insertion order, or after every row while this store has
694
- * not written it yet. The held set keeps such runs in creation order, and so does every list
695
- * that sorts them in held-set order (`sortNewestFirst` is stable). */
696
- listOrder(run) {
697
- return { createdAt: run.createdAt, seq: this.base.get(run.id)?.seq ?? Number.POSITIVE_INFINITY };
698
- }
699
- /**
700
- * EVERY run as a full record, newest first — decoded row by row. Only the legacy `GET /runs`
701
- * (older clients; the cockpit reads `GET /run-summaries`) may call this: it is exactly the
702
- * whole-history parse #779 exists to remove from everything else.
703
- */
704
- listAllRunsForLegacyRoute() {
705
- const runs = new Map();
706
- for (const row of this.db?.listAll() ?? []) {
707
- if (this.deleted.has(row.id) || this.held.has(row.id))
708
- continue;
709
- const run = this.decodeCold(row);
710
- if (run)
711
- runs.set(row.id, [run, row]);
712
- }
713
- for (const [id, run] of this.held)
714
- runs.set(id, [run, this.listOrder(run)]);
715
- return sortNewestFirst(runs.values());
716
- }
717
- /** A bounded page of discoverable peer roots, including the current held overlay. */
718
- listPeerTaskSummaries(options) {
719
- return listPeerTaskSummaries({ db: this.db, held: this.held, skipped: this.deleted,
720
- order: run => this.listOrder(run), cold: id => this.coldSummary(id) }, options);
721
- }
722
- /**
723
- * Every run as its list row, newest first: the stored `summary` column, with each held run's
724
- * own projection laid over it — a debounced save keeps memory up to 300 ms ahead of the row,
725
- * and a run created since the last save has no row yet. `usage` is the caller's to attach.
726
- *
727
- * With `archivedWindow` (#864), the window the cockpit's lists read: every unarchived run, plus
728
- * the newest `archivedWindow` archived ROOT runs, and whether older archived roots were left
729
- * out. Archived workers are never in it (see `RunDatabase.listWindowSummaries`); with `roots`,
730
- * no worker is — the runs index, whose readers list no workers. A held run
731
- * lists by its record, so one archived or unarchived since the last save is ranked as it is now.
732
- *
733
- * A row this store found unreadable is left out, as the cold reader leaves out a row it had to
734
- * decode and could not. A finished row nobody has decoded is served from its summary by both,
735
- * which decodes nothing; reading it is what finds out (`isUnreadable`).
736
- */
737
- listRunSummaries(options = {}) {
738
- const { archivedWindow, roots = false } = options;
739
- // Every skipped row may be an archived root, so ask for that many more: one past the window
740
- // after skipping is how "older ones were left out" is known without counting them.
741
- const rows = (archivedWindow === undefined
742
- ? this.db?.listSummaries()
743
- : this.db?.listWindowSummaries(archivedWindow + 1 + this.deleted.size + this.unreadable.size + this.held.size, { roots })) ?? [];
744
- const summaries = new Map();
745
- for (const row of rows) {
746
- if (this.deleted.has(row.id) || this.held.has(row.id) || this.unreadable.has(row.id))
747
- continue;
748
- const summary = parseStoredSummary(row.summary) ?? this.coldSummary(row.id);
749
- if (summary)
750
- summaries.set(row.id, [summary, row]);
751
- }
752
- for (const [id, run] of this.held) {
753
- if (archivedWindow !== undefined && (run.archived || roots) && run.delegation?.role === 'worker')
754
- continue;
755
- summaries.set(id, [toRunSummary(run), this.listOrder(run)]);
756
- }
757
- const runs = sortNewestFirst(summaries.values());
758
- if (archivedWindow === undefined)
759
- return { runs, truncated: false };
760
- let archived = 0;
761
- const kept = runs.filter((run) => !run.archived || ++archived <= archivedWindow);
762
- return { runs: kept, truncated: archived > archivedWindow };
763
- }
764
- /**
765
- * One page of archived ROOT runs, newest first (#864): `GET /run-summaries/archived`, the
766
- * archived runs past the window. Held runs list by their record, as in `listRunSummaries`.
767
- * `before` is the previous page's `nextCursor`; with `q`, only runs `matchesRunSearch` keeps, and
768
- * `total` counts those. `automationNames` lets `q` match a task by its automation's name, as the
769
- * list's origin line shows it (hearsay-tools/cezarion#1616). A cursor this store did not write
770
- * answers `{ error }`.
771
- *
772
- * Ranking reads every archived root's key (id, created_at, seq: no record, no summary), so the
773
- * page and `total` agree with the held overlay; only the page's own rows are read in full.
774
- */
775
- listArchivedRuns(options) {
776
- let after;
777
- if (options.before !== undefined) {
778
- after = decodeArchivedCursor(options.before);
779
- if (!after)
780
- return { error: 'before is not a cursor this server wrote' };
781
- }
782
- const q = options.q?.trim() ?? '';
783
- const ranked = this.rankArchivedRows(q, options.automationNames);
784
- this.overlayHeldArchived(ranked, q, options.automationNames);
785
- const ordered = [...ranked.entries()].sort(([, a], [, b]) => newestFirst(a, b));
786
- return this.archivedPage(ordered, after, options.limit);
787
- }
788
- /** The archived roots in `runs.db`, each by its key: every one without `q` (no record, no
789
- * summary read), and with `q` the searched rows `matchesRunSearch` keeps, which carry the summary
790
- * the search read. A deleted, held or unreadable run's row is left out; a held run joins in
791
- * `overlayHeldArchived`. */
792
- rankArchivedRows(q, automationNames) {
793
- const skipped = (id) => this.deleted.has(id) || this.held.has(id) || this.unreadable.has(id);
794
- const ranked = new Map();
795
- if (q === '') {
796
- for (const key of this.db?.listKeysWhere(ARCHIVED_ROOT) ?? [])
797
- if (!skipped(key.id))
798
- ranked.set(key.id, key);
799
- }
800
- else {
801
- for (const row of this.db?.searchRootSummaries(sqlPrefilterTokens(q, { automationNames })) ?? []) {
802
- if (skipped(row.id))
803
- continue;
804
- const summary = parseStoredSummary(row.summary) ?? this.coldSummary(row.id);
805
- if (summary?.archived && matchesRunSearch(summary, q, { automationNames }))
806
- ranked.set(row.id, { ...row, summary });
807
- }
808
- }
809
- return ranked;
810
- }
811
- /** Lay the held archived roots over `ranked`, each by its record: it replaces its stored row
812
- * (already left out of `ranked`), and with `q` it must match. A held worker never lists. */
813
- overlayHeldArchived(ranked, q, automationNames) {
814
- for (const [id, run] of this.held) {
815
- if (!run.archived || run.delegation?.role === 'worker')
816
- continue;
817
- const summary = toRunSummary(run);
818
- if (q === '' || matchesRunSearch(summary, q, { automationNames }))
819
- ranked.set(id, { ...this.listOrder(run), summary });
820
- }
821
- }
822
- /** The page of `ordered` after the cursor `after`: its summaries, the cursor of the next page,
823
- * and `total`, the count of all of `ordered`. */
824
- archivedPage(ordered, after, limit) {
825
- const rest = after ? ordered.filter(([, key]) => newestFirst(key, after) > 0) : ordered;
826
- const page = rest.slice(0, limit);
827
- const runs = this.hydrateArchivedPage(page);
828
- const last = page.at(-1)?.[1];
829
- return {
830
- runs,
831
- nextCursor: last && rest.length > page.length ? encodeArchivedCursor(last) : null,
832
- total: ordered.length,
833
- };
834
- }
835
- /** The page's summaries: a ranked key's own, else its stored one, read for the rows that have
836
- * none in a single query. A row whose stored summary does not fit the contract is projected from
837
- * its record; a row that cannot be read at all is left out. */
838
- hydrateArchivedPage(page) {
839
- const cold = new Map((this.db?.getSummaries(page.filter(([, key]) => !key.summary).map(([id]) => id)) ?? [])
840
- .map((row) => [row.id, parseStoredSummary(row.summary) ?? this.coldSummary(row.id)]));
841
- return page.flatMap(([id, key]) => {
842
- const summary = key.summary ?? cold.get(id);
843
- return summary ? [summary] : [];
844
- });
845
- }
846
- /**
847
- * The ROOT runs, archived or not, that match `query` (`matchesRunSearch`), newest first: at most
848
- * `limit`, and whether more matched. The owned half of the workspace search (#864); held runs
849
- * match by their record.
850
- */
851
- searchRunSummaries(query, limit) {
852
- const matched = new Map();
853
- // Rows come newest first, so the newest `limit + 1` row matches are all a page can use; held
854
- // runs, which may be newer than any row, are ranked in below.
855
- this.db?.visitRootSummaries(sqlPrefilterTokens(query), (row) => {
856
- if (this.deleted.has(row.id) || this.held.has(row.id) || this.unreadable.has(row.id))
857
- return true;
858
- const summary = parseStoredSummary(row.summary) ?? this.coldSummary(row.id);
859
- if (summary && matchesRunSearch(summary, query))
860
- matched.set(row.id, [summary, row]);
861
- return matched.size <= limit;
862
- });
863
- for (const [id, run] of this.held) {
864
- if (run.delegation?.role === 'worker')
865
- continue;
866
- const summary = toRunSummary(run);
867
- if (matchesRunSearch(summary, query))
868
- matched.set(id, [summary, this.listOrder(run)]);
869
- }
870
- const runs = sortNewestFirst(matched.values());
871
- return { runs: runs.slice(0, limit), truncated: runs.length > limit };
872
- }
873
- /** A row whose stored summary does not fit the contract any more, projected from its record. */
874
- coldSummary(id) {
875
- const run = this.loadCold(id);
876
- return run ? toRunSummary(run) : undefined;
877
- }
878
446
  /**
879
447
  * The run, or undefined. A held run is the held object (writes install into it). Any other run
880
448
  * is a fresh copy of its row each call, normalized like a loaded record — frozen under vitest —
@@ -884,232 +452,16 @@ export class RunStore {
884
452
  const held = this.held.get(id);
885
453
  if (held)
886
454
  return held;
887
- const cached = this.deleted.has(id) || !this.db ? undefined : this.coldReads.at(id, this.db.revisionOf(id));
455
+ const cached = this.deleted.has(id) || !this.db ? undefined : this.rows.coldReads.at(id, this.db.revisionOf(id));
888
456
  if (cached)
889
457
  return cached;
890
- const run = this.loadCold(id);
891
- return run && this.coldReads.keep(this.answerCold(run, true), this.coldBase.get(id), this.held.has(id));
458
+ const run = this.rows.loadCold(id);
459
+ return run && this.rows.coldReads.keep(this.rows.answerCold(run, true), this.rows.coldBase.get(id), this.held.has(id));
892
460
  }
893
461
  /** Whether the run's row is in `runs.db` but its record could not be read here: what tells a
894
462
  * run that cannot open from one that does not exist. Known once something tried to read it. */
895
463
  isUnreadable(id) {
896
- return this.unreadable.has(id) && !this.held.has(id) && !this.deleted.has(id);
897
- }
898
- /** The ids in memory right now: the held set, for diagnostics and the benchmark's heap pass. */
899
- heldIds() {
900
- return [...this.held.keys()];
901
- }
902
- /**
903
- * The workers a root run owns, newest first, read off its own `receipts` (#659). Every
904
- * `createOwnedRun` writes the receipt and the worker record in one transaction, and the
905
- * receipt list is capped at 1,024 creations (#816), so this is a bounded lookup rather than a walk of the whole
906
- * project index. An ordinary or worker run owns nothing and costs one map read; a receipt
907
- * whose record has been deleted is skipped, never invented. A parent quarantined to
908
- * `invalid` has no readable receipts and reports none, which is also what the cockpit
909
- * assumes for that role.
910
- */
911
- listOwnedWorkers(parentId) {
912
- const parent = this.getRun(parentId);
913
- if (parent?.delegation?.role !== 'root')
914
- return [];
915
- const workers = [];
916
- for (const receipt of parent.delegation.receipts) {
917
- const worker = this.getRun(receipt.workerId);
918
- if (worker?.delegation?.role === 'worker' && worker.delegation.parentRunId === parentId)
919
- workers.push(worker);
920
- }
921
- return workers.sort((a, b) => b.createdAt.localeCompare(a.createdAt));
922
- }
923
- /** Every worker filed under `parentId` (the `parent_run_id` index plus memory), newest first:
924
- * receipts or not, which is what the reconcile and deletion checks ask. */
925
- listWorkersOf(parentId) {
926
- const workers = new Map();
927
- for (const run of this.held.values()) {
928
- if (run.delegation?.role === 'worker' && run.delegation.parentRunId === parentId)
929
- workers.set(run.id, [run, this.listOrder(run)]);
930
- }
931
- // Ids first: a live family's workers are usually all held, and then no record is read at all.
932
- const cold = (this.db?.listIdsByParent(parentId) ?? []).filter((id) => !this.held.has(id) && !this.deleted.has(id));
933
- for (const row of cold.length > 0 ? this.db.getMany(cold) : []) {
934
- const run = this.fromRow(row);
935
- if (run?.delegation?.role === 'worker' && run.delegation.parentRunId === parentId)
936
- workers.set(row.id, [run, row]);
937
- }
938
- return sortNewestFirst(workers.values());
939
- }
940
- /** The id of every worker, held or stored, without decoding any (recovery's worker passes). */
941
- listWorkerIds() {
942
- const ids = new Set(this.db?.listWorkerIds() ?? []);
943
- for (const id of this.deleted)
944
- ids.delete(id);
945
- for (const run of this.held.values())
946
- if (run.delegation?.role === 'worker')
947
- ids.add(run.id);
948
- return [...ids];
949
- }
950
- /** The id of every run whose delegation is quarantined (`invalid`), held or stored: its stored
951
- * summary says so, so nothing is decoded (scratch cleanup). */
952
- listQuarantinedRunIds() {
953
- const ids = new Set((this.db?.listKeysWhere(guardedJsonSql("json_extract(summary, '$.delegation.role') = 'invalid'", 0)) ?? []).map((key) => key.id));
954
- for (const id of this.deleted)
955
- ids.delete(id);
956
- for (const [id, run] of this.held) {
957
- if (run.delegation?.role === 'invalid')
958
- ids.add(id);
959
- else
960
- ids.delete(id);
961
- }
962
- return [...ids];
963
- }
964
- /** All retained tasks this automation started, including variants, finished and archived runs.
965
- * Logs and receipts may compact independently. Read only matching keys in SQLite and overlay
966
- * held records so a debounced provenance update or deletion is reflected immediately. */
967
- countAutomationRuns(automationId) {
968
- const ids = new Set(this.db?.listAutomationRuns(automationId) ?? []);
969
- for (const id of this.deleted)
970
- ids.delete(id);
971
- for (const [id, run] of this.held) {
972
- if (run.automation?.automationId === automationId || run.automationTrigger?.automationId === automationId)
973
- ids.add(id);
974
- else
975
- ids.delete(id);
976
- }
977
- return ids.size;
978
- }
979
- /** First non-archived task referencing a project issue, including secondary references. */
980
- findNonArchivedRunByIssue(repo, number) {
981
- const url = `https://github.com/${repo}/issues/${number}`.toLowerCase();
982
- const matches = (run) => {
983
- if (run.archived)
984
- return false;
985
- const urls = [run.referencedIssueUrl, ...(run.referencedIssueCandidates ?? []),
986
- ...(run.automation?.event.startsWith('issue.') ? [run.automation.githubUrl] : []),
987
- ...[...run.task.matchAll(new RegExp(ISSUE_URL_RE.source, 'gi'))].map((match) => match[0])]
988
- .filter((value) => value !== undefined)
989
- .map((value) => value.replace(/\/+$/, '').toLowerCase())
990
- .filter((value) => value.endsWith(`/issues/${number}`));
991
- // The legacy issueNumber is display-only and cannot establish repository identity.
992
- // Explicit task markers remain project-scoped unless a qualified URL contradicts them.
993
- return urls.includes(url) || (urls.length === 0 && run.markerRefs?.issue === number);
994
- };
995
- for (const run of this.held.values())
996
- if (matches(run))
997
- return run.id;
998
- // Secondary references are record-only: query them in SQLite rather than hydrating every
999
- // finished transcript or relying on the slim summary's primary issue number.
1000
- const where = `archived = 0 AND ${guardedJsonSql(`
1001
- json_extract(data, '$.issueNumber') = ? OR json_extract(data, '$.markerRefs.issue') = ?
1002
- OR lower(rtrim(json_extract(data, '$.referencedIssueUrl'), '/')) = ?
1003
- OR EXISTS (SELECT 1 FROM json_each(data, '$.referencedIssueCandidates') WHERE lower(rtrim(value, '/')) = ?)
1004
- OR (json_extract(data, '$.automation.event') LIKE 'issue.%' AND lower(rtrim(json_extract(data, '$.automation.githubUrl'), '/')) = ?)
1005
- OR instr(lower(json_extract(data, '$.task')), ?) > 0
1006
- `, 0, ['data'])}`;
1007
- for (const key of this.db?.listKeysWhere(where, [number, number, url, url, url, url]) ?? []) {
1008
- if (this.held.has(key.id) || this.deleted.has(key.id) || this.unreadable.has(key.id))
1009
- continue;
1010
- const run = this.getRun(key.id);
1011
- if (run && matches(run))
1012
- return key.id;
1013
- }
1014
- return undefined;
1015
- }
1016
- /**
1017
- * The runs automation receipts launched, by receipt id (`automation.receiptId` or
1018
- * `automationTrigger.receiptId`). Memory answers first; a receipt it does not know costs one
1019
- * pass over `runs.db` that reads the records' JSON in SQLite — only a crash leftover (a
1020
- * receipt still `reserved` at startup) ever asks.
1021
- */
1022
- findRunIdsByAutomationReceipt(receiptIds) {
1023
- const wanted = new Set(receiptIds);
1024
- const found = new Map();
1025
- const receiptOf = (run) => run.automation?.receiptId ?? run.automationTrigger?.receiptId;
1026
- for (const run of this.held.values()) {
1027
- const receipt = receiptOf(run);
1028
- if (receipt !== undefined && wanted.has(receipt))
1029
- found.set(receipt, run.id);
1030
- }
1031
- const missing = [...wanted].filter((receipt) => !found.has(receipt));
1032
- if (missing.length === 0 || !this.db)
1033
- return found;
1034
- for (const id of this.db.listRunsByAutomationReceipt(missing)) {
1035
- if (this.held.has(id) || this.deleted.has(id))
1036
- continue;
1037
- const run = this.getRun(id);
1038
- const receipt = run && receiptOf(run);
1039
- if (receipt !== undefined && wanted.has(receipt) && !found.has(receipt))
1040
- found.set(receipt, id);
1041
- }
1042
- return found;
1043
- }
1044
- /** The id of every root whose delegation carries a conversation, held or stored: recovery's full
1045
- * reconcile pass (#661). `naming` keeps the ledgers whose messages name that run id as sender or
1046
- * recipient. Stored roots come from the `conversation_members` index, so no record is read. */
1047
- listConversationRootIds(naming) {
1048
- const ids = new Set(this.db?.listConversationRoots(naming) ?? []);
1049
- for (const id of this.deleted)
1050
- ids.delete(id);
1051
- for (const [id, run] of this.held) {
1052
- if (run.delegation?.role === 'root' && run.delegation.conversation && (!naming || run.delegation.conversation.messages.some(message => [message.senderRunId, message.recipientRunId].includes(naming))))
1053
- ids.add(id);
1054
- else
1055
- ids.delete(id);
1056
- }
1057
- return [...ids];
1058
- }
1059
- /** The id of every run, held or stored, without decoding any (orphan-worktree sweeps). */
1060
- listRunIds() {
1061
- const ids = new Set(this.db?.listIds() ?? []);
1062
- for (const id of this.deleted)
1063
- ids.delete(id);
1064
- for (const id of this.held.keys())
1065
- ids.add(id);
1066
- return [...ids];
1067
- }
1068
- /** Runs with a materialized worktree directory (`worktreePath`, not reclaimed), most recently
1069
- * finished first, then newest first: worktree retention and the worktrees panel. */
1070
- listRunsWithWorktree() {
1071
- const runs = this.queryRuns(this.db?.listWithWorktree() ?? [], (run) => materializedWorktreePath(run) !== undefined);
1072
- const recency = ([run]) => run.finishedAt ?? run.createdAt;
1073
- return runs.sort((a, b) => (recency(a) < recency(b) ? 1 : recency(a) > recency(b) ? -1 : newestFirst(a[1], b[1]))).map(([run]) => run);
1074
- }
1075
- /**
1076
- * Every run that owns a branch or names the PR it created, as the few fields branch cleanup and
1077
- * git-log attribution read (issue 08 §B3, §B5; a squash commit is attributed by its PR number):
1078
- * the stored summary plus the `branch` and `base_branch` columns, so a Git-tab request decodes
1079
- * no record. Held runs answer from memory.
1080
- */
1081
- listBranchOwners() {
1082
- const rows = (this.db?.listBranchOwners(`branch IS NOT NULL OR ${guardedJsonSql("json_extract(summary, '$.pullRequestUrl') IS NOT NULL", 0)}`) ?? [])
1083
- .filter((row) => !this.deleted.has(row.id) && !this.held.has(row.id));
1084
- return listBranchOwners(rows, [...this.held.values()], (id) => this.getRun(id));
1085
- }
1086
- /** The rows a column query returned, as records, with memory laid over them: a held run
1087
- * answers from memory (matching `matches` there, not on its maybe-older row). */
1088
- queryRuns(rows, matches) {
1089
- const runs = new Map();
1090
- for (const run of this.held.values())
1091
- if (matches(run))
1092
- runs.set(run.id, [run, this.listOrder(run)]);
1093
- for (const row of rows) {
1094
- if (runs.has(row.id) || this.held.has(row.id) || this.deleted.has(row.id))
1095
- continue;
1096
- const run = this.fromRow(row);
1097
- if (run && matches(run))
1098
- runs.set(row.id, [run, row]);
1099
- }
1100
- return [...runs.values()];
1101
- }
1102
- /** The run an idempotent start already created (#504), archived or not. A deleted run is gone
1103
- * with its record, so a retry after deletion honestly creates a fresh one. */
1104
- findRunByClientRequestId(clientRequestId) {
1105
- for (const run of this.held.values())
1106
- if (run.clientRequestId === clientRequestId)
1107
- return run;
1108
- const row = this.db?.findByClientRequestId(clientRequestId);
1109
- if (!row || this.held.has(row.id))
1110
- return undefined;
1111
- const run = this.getRun(row.id);
1112
- return run?.clientRequestId === clientRequestId ? run : undefined;
464
+ return this.rows.unreadable.has(id) && !this.held.has(id) && !this.deleted.has(id);
1113
465
  }
1114
466
  createRun(input) {
1115
467
  if (this.openFailure)
@@ -1120,7 +472,7 @@ export class RunStore {
1120
472
  throw new RunWriteRefusedError(run.id, 'foreign');
1121
473
  this.held.set(run.id, run);
1122
474
  this.retention.pruneOldRuns();
1123
- this.touch(run, undefined);
475
+ this.persistence.touch(run, undefined);
1124
476
  return run;
1125
477
  }
1126
478
  /** Build without publishing: owned creation must commit its receipt and run together. */
@@ -1166,33 +518,33 @@ export class RunStore {
1166
518
  // A prompt that pastes a PR or issue URL is already about that item — seed
1167
519
  // both referenced tiers so queued runs can expose the reference before the
1168
520
  // first agent event (#407, #554).
1169
- trackReferencedPrs(run, input.task, this.repoHandle);
1170
- trackReferencedIssues(run, input.task, this.repoHandle);
521
+ trackReferencedPrs(run, input.task, this.repoScope.repoHandle);
522
+ trackReferencedIssues(run, input.task, this.repoScope.repoHandle);
1171
523
  return run;
1172
524
  }
1173
525
  /** Accept the family ledger and its recipient queue in a single durable index replacement. A new
1174
526
  * message (`message`, or the delivered input) whose ID is in use writes nothing; `recipientDelegation`
1175
527
  * makes a peer recipient with no delegation record a root task in the same write. */
1176
528
  commitConversation(rootId, conversation, delivery, message) {
1177
- const root = this.peek(rootId);
529
+ const root = this.rows.peek(rootId);
1178
530
  if (root?.delegation?.role !== 'root')
1179
531
  throw new Error('missing conversation root');
1180
- assertConversationIdFree(root, message ?? delivery?.input, id => this.peek(id), (runId, id) => this.eventLog.hasProjection(runId, id));
532
+ assertConversationIdFree(root, message ?? delivery?.input, id => this.rows.peek(id), (runId, id) => this.eventLog.hasProjection(runId, id));
1181
533
  const staged = new Map();
1182
- stageConversation(staged, root, conversation, delivery, id => this.peek(id), text => this.redaction.redactText(text));
1183
- this.commitIndex(staged);
534
+ stageConversation(staged, root, conversation, delivery, id => this.rows.peek(id), text => this.redaction.redactText(text));
535
+ this.persistence.commitIndex(staged);
1184
536
  }
1185
537
  /** Crash recovery (#505): input a harness accepted but was never seen reading goes
1186
538
  * back to the queue. Returns the requeued IDs. */
1187
539
  requeueAwaitingReadInputs(id) {
1188
- const ids = (this.peek(id)?.agentInputs ?? []).filter(input => input.awaitingRead && input.deliveredAt && !input.consumedAt).map(input => input.id);
540
+ const ids = (this.rows.peek(id)?.agentInputs ?? []).filter(input => input.awaitingRead && input.deliveredAt && !input.consumedAt).map(input => input.id);
1189
541
  if (ids.length)
1190
542
  this.commitOutcome(id, { kind: 'requeued', inputIds: ids });
1191
543
  return ids;
1192
544
  }
1193
545
  /** Delivered, but the harness never confirmed reading it (#505): stop awaiting a read. */
1194
546
  commitAgentInputsUnconfirmed(id, ids) {
1195
- const run = this.peek(id);
547
+ const run = this.rows.peek(id);
1196
548
  if (!run?.agentInputs || !ids.length)
1197
549
  return;
1198
550
  this.commitAgentInputs(id, run.agentInputs.map(input => {
@@ -1205,7 +557,7 @@ export class RunStore {
1205
557
  /** Observable atomic input checkpoint for the queue itself: enqueue, retire, reorder. Delivery
1206
558
  * and reads are outcomes (`commitOutcome`). */
1207
559
  commitAgentInputs(id, inputs) {
1208
- const run = this.peek(id);
560
+ const run = this.rows.peek(id);
1209
561
  if (!run)
1210
562
  throw new Error('missing agent input target');
1211
563
  const agentInputs = inputs.map(input => agentInputSchema.parse(input));
@@ -1224,11 +576,11 @@ export class RunStore {
1224
576
  throw new Error('live inbox receipt changed');
1225
577
  }
1226
578
  }
1227
- this.commitIndex(new Map([[id, { ...run, agentInputs }]]));
579
+ this.persistence.commitIndex(new Map([[id, { ...run, agentInputs }]]));
1228
580
  }
1229
581
  /** Reserve only unread conversation inputs in one durable index replacement. */
1230
582
  claimInboxInputs(runId, ids, claim) {
1231
- const run = this.peek(runId);
583
+ const run = this.rows.peek(runId);
1232
584
  if (!run)
1233
585
  throw new Error('missing inbox recipient');
1234
586
  const selected = z.array(z.uuid()).min(1).max(32).refine(values => new Set(values).size === values.length).parse(ids);
@@ -1246,12 +598,12 @@ export class RunStore {
1246
598
  }
1247
599
  }
1248
600
  const selectedIds = new Set(selected);
1249
- this.commitIndex(new Map([[runId, { ...run, agentInputs: inputs.map(input => selectedIds.has(input.id)
601
+ this.persistence.commitIndex(new Map([[runId, { ...run, agentInputs: inputs.map(input => selectedIds.has(input.id)
1250
602
  ? agentInputSchema.parse({ ...input, inboxClaim: receipt }) : input) }]]));
1251
603
  }
1252
604
  /** A receipt owns every matching input or none; exact ACK retries preserve the first timestamp. */
1253
605
  ackInboxInputs(runId, receiptId, generation, at) {
1254
- const run = this.peek(runId);
606
+ const run = this.rows.peek(runId);
1255
607
  if (!run)
1256
608
  throw new Error('missing inbox recipient');
1257
609
  inboxClaimSchema.shape.receiptId.parse(receiptId);
@@ -1276,7 +628,7 @@ export class RunStore {
1276
628
  return 'acknowledged';
1277
629
  }
1278
630
  releaseInboxInputs(runId, receiptId, generation) {
1279
- const run = this.peek(runId);
631
+ const run = this.rows.peek(runId);
1280
632
  if (!run)
1281
633
  throw new Error('missing inbox recipient');
1282
634
  inboxClaimSchema.shape.receiptId.parse(receiptId);
@@ -1285,7 +637,7 @@ export class RunStore {
1285
637
  if (!matching.length || matching.some(input => input.inboxClaim?.generation !== generation ||
1286
638
  input.inboxClaim?.acknowledgedAt || input.deliveredAt))
1287
639
  throw new Error('inbox receipt changed');
1288
- this.commitIndex(new Map([[runId, { ...run, agentInputs: run.agentInputs.map(input => {
640
+ this.persistence.commitIndex(new Map([[runId, { ...run, agentInputs: run.agentInputs.map(input => {
1289
641
  if (input.inboxClaim?.receiptId !== receiptId)
1290
642
  return input;
1291
643
  const { inboxClaim: _claim, ...unclaimed } = input;
@@ -1294,13 +646,13 @@ export class RunStore {
1294
646
  return 'released';
1295
647
  }
1296
648
  clearExpiredInboxClaims(runId, now) {
1297
- const run = this.peek(runId);
649
+ const run = this.rows.peek(runId);
1298
650
  if (!run)
1299
651
  throw new Error('missing inbox recipient');
1300
652
  inboxClaimSchema.shape.expiresAt.parse(now);
1301
653
  if (!run.agentInputs?.some(input => input.inboxClaim && !input.inboxClaim.acknowledgedAt && input.inboxClaim.expiresAt <= now))
1302
654
  return;
1303
- this.commitIndex(new Map([[runId, { ...run, agentInputs: run.agentInputs.map(input => {
655
+ this.persistence.commitIndex(new Map([[runId, { ...run, agentInputs: run.agentInputs.map(input => {
1304
656
  if (!input.inboxClaim || input.inboxClaim.acknowledgedAt || input.inboxClaim.expiresAt > now)
1305
657
  return input;
1306
658
  const { inboxClaim: _claim, ...unclaimed } = input;
@@ -1315,40 +667,40 @@ export class RunStore {
1315
667
  * past `WAIT_LIMIT` open ones is refused, so the list stays bounded whatever the caller checked.
1316
668
  */
1317
669
  commitWait(id, wait, input, registration) {
1318
- const run = this.peek(id);
670
+ const run = this.rows.peek(id);
1319
671
  if (!run)
1320
672
  throw new Error('missing wait target');
1321
- this.commitIndex(new Map([[id, registeredWaitRecord(run, wait, input, registration)]]));
673
+ this.persistence.commitIndex(new Map([[id, registeredWaitRecord(run, wait, input, registration)]]));
1322
674
  }
1323
675
  /** Record a deduplicated registration without mutating its wait. */
1324
676
  commitWaitRegistration(id, receipt) {
1325
- const run = this.peek(id);
677
+ const run = this.rows.peek(id);
1326
678
  if (!run)
1327
679
  throw new Error('missing wait target');
1328
- this.commitIndex(new Map([[id, registeredReceiptRecord(run, receipt)]]));
680
+ this.persistence.commitIndex(new Map([[id, registeredReceiptRecord(run, receipt)]]));
1329
681
  }
1330
682
  /** A usage-limit appointment withdrawn, committed at once instead of on the debounced save
1331
683
  * (hearsay-tools/cezarion#1236): a crash right after the withdrawal must not find it on disk,
1332
684
  * or recovery re-arms work the user cancelled. A run held for its resume settles `failed` by
1333
685
  * the `withdraw-hold` exit; any other run only loses its resume fields. */
1334
686
  commitAutoResumeWithdrawal(id) {
1335
- const run = this.peek(id);
687
+ const run = this.rows.peek(id);
1336
688
  if (!run || (run.autoResumeAt === undefined && run.autoResumeAttempts === undefined))
1337
689
  return;
1338
690
  if (isUsageLimitHold(run))
1339
691
  this.move(id, 'withdraw-hold');
1340
692
  else
1341
- this.commitIndex(new Map([[id, { ...run, autoResumeAt: undefined, autoResumeAttempts: undefined, autoResumeReason: undefined }]]));
693
+ this.persistence.commitIndex(new Map([[id, { ...run, autoResumeAt: undefined, autoResumeAttempts: undefined, autoResumeReason: undefined }]]));
1342
694
  }
1343
695
  /** A human message beside a run's waits (hearsay-tools/cezarion#1235): accepted durably, and
1344
696
  * every wait stays. A lifecycle opening becomes
1345
697
  * the human's and keeps its wake text, so the message opens the continuation (and answers a
1346
698
  * pending question) and the owed results still reach the agent. */
1347
699
  commitHumanMessageBesideWaits(id, acceptedHumanMessage) {
1348
- const run = this.peek(id);
700
+ const run = this.rows.peek(id);
1349
701
  if (!run)
1350
702
  throw new Error('missing queued message target');
1351
- this.commitIndex(new Map([[id, { ...run, queuedMessages: [...(run.queuedMessages ?? []), queuedMessageSchema.parse(acceptedHumanMessage)],
703
+ this.persistence.commitIndex(new Map([[id, { ...run, queuedMessages: [...(run.queuedMessages ?? []), queuedMessageSchema.parse(acceptedHumanMessage)],
1352
704
  ...(run.continuationMessage ? { continuationMessage: { ...run.continuationMessage, origin: 'human' } } : {}),
1353
705
  }]]));
1354
706
  }
@@ -1363,32 +715,32 @@ export class RunStore {
1363
715
  * A conversation request outcome is the other sanctioned write: `commitConversation`.
1364
716
  */
1365
717
  commitOutcome(id, outcomes, deps = {}, opts = {}) {
1366
- const run = this.peek(id);
718
+ const run = this.rows.peek(id);
1367
719
  if (!run)
1368
720
  return { committed: false, answered: [], settled: [] };
1369
721
  const staged = applyOutcomes(run, Array.isArray(outcomes) ? outcomes : [outcomes], deps);
1370
722
  if (!staged.changed)
1371
723
  return { committed: false, answered: [], settled: [] };
1372
724
  try {
1373
- this.commitIndex(new Map([[id, staged.next]]), undefined, { exits: new Map([[id, staged.exit]]) });
725
+ this.persistence.commitIndex(new Map([[id, staged.next]]), undefined, { exits: new Map([[id, staged.exit]]) });
1374
726
  }
1375
727
  catch (error) {
1376
728
  if (!opts.bestEffort)
1377
729
  throw error;
1378
730
  console.warn(`[hsq] outcome checkpoint failed: ${error instanceof Error ? error.message : String(error)}`);
1379
- const live = this.record(id);
731
+ const live = this.rows.record(id);
1380
732
  if (!live)
1381
733
  return { committed: false, answered: staged.answered, settled: staged.settled };
1382
734
  const before = snapshotRun(live);
1383
735
  replaceRecord(live, staged.next);
1384
- this.touch(live, before, staged.exit);
736
+ this.persistence.touch(live, before, staged.exit);
1385
737
  return { committed: false, answered: staged.answered, settled: staged.settled };
1386
738
  }
1387
739
  return { committed: true, answered: staged.answered, settled: staged.settled };
1388
740
  }
1389
741
  /** An acknowledged inactive-root Finish must survive the async diff and restart. */
1390
742
  commitRootFinishIntent(id) {
1391
- const run = this.peek(id);
743
+ const run = this.rows.peek(id);
1392
744
  if (run?.status !== 'waiting' || run.delegation?.role !== 'root')
1393
745
  throw new Error('root is not waiting');
1394
746
  if (run.delegation.finishRequestedAt)
@@ -1402,7 +754,7 @@ export class RunStore {
1402
754
  const staged = new Map();
1403
755
  let destroyProgress = true;
1404
756
  for (const patch of patches) {
1405
- const run = this.peek(patch.id);
757
+ const run = this.rows.peek(patch.id);
1406
758
  if (!run || staged.has(patch.id))
1407
759
  throw new Error('missing or duplicate delegation patch target');
1408
760
  const delegation = delegationStateSchema.parse(patch.delegation);
@@ -1412,23 +764,23 @@ export class RunStore {
1412
764
  }
1413
765
  // In-process cause only: consumers can skip metadata replay when delegation
1414
766
  // is disabled without dropping real status or termination-proof notifications.
1415
- this.commitIndex(staged, destroyProgress ? 'delegation-destroy-progress' : 'delegation-checkpoint');
767
+ this.persistence.commitIndex(staged, destroyProgress ? 'delegation-destroy-progress' : 'delegation-checkpoint');
1416
768
  }
1417
769
  /** A pending destroy's automatic retry state, or its removal (hearsay-tools/cezarion#879). Kept on
1418
770
  * the record beside the strict delegation, so an older Squawk strips it rather than quarantining the
1419
771
  * worker. Destroy progress: nothing the family reconcile reads changes. */
1420
772
  commitDestroyRetry(id, retry) {
1421
- const run = this.peek(id);
773
+ const run = this.rows.peek(id);
1422
774
  if (run?.delegation?.role !== 'worker' || !run.delegation.destroy)
1423
775
  throw new Error('missing pending destroy');
1424
776
  if (!retry && !run.destroyRetry)
1425
777
  return;
1426
778
  // An explicit `undefined`, not an omitted key: commitIndex assigns onto the live record.
1427
- this.commitIndex(new Map([[id, { ...run, destroyRetry: retry ? workerDestroyRetrySchema.parse(retry) : undefined }]]), 'delegation-destroy-progress');
779
+ this.persistence.commitIndex(new Map([[id, { ...run, destroyRetry: retry ? workerDestroyRetrySchema.parse(retry) : undefined }]]), 'delegation-destroy-progress');
1428
780
  }
1429
781
  /** Accepted execution revision is public lifecycle identity, separate from process generations. */
1430
782
  commitWorkerContinuation(id, exit, patch = {}, step, conversation) {
1431
- const run = this.peek(id);
783
+ const run = this.rows.peek(id);
1432
784
  if (run?.delegation?.role !== 'worker')
1433
785
  throw new Error('missing worker continuation target');
1434
786
  const delegation = delegationStateSchema.parse({ ...run.delegation,
@@ -1444,114 +796,25 @@ export class RunStore {
1444
796
  if (Object.prototype.hasOwnProperty.call(patch, 'archived'))
1445
797
  this.archive.syncTranscriptForm(id, next.archived);
1446
798
  if (conversation) {
1447
- const root = this.peek(conversation.rootId);
799
+ const root = this.rows.peek(conversation.rootId);
1448
800
  if (root?.delegation?.role !== 'root' || run.delegation.parentRunId !== root.id)
1449
801
  throw new Error('missing conversation ownership');
1450
- stageConversation(staged, root, conversation.state, { recipientRunId: id, input: conversation.input }, runId => this.peek(runId), text => this.redaction.redactText(text));
802
+ stageConversation(staged, root, conversation.state, { recipientRunId: id, input: conversation.input }, runId => this.rows.peek(runId), text => this.redaction.redactText(text));
1451
803
  }
1452
- this.commitIndex(staged, undefined, { exits: new Map([[id, exit]]) });
804
+ this.persistence.commitIndex(staged, undefined, { exits: new Map([[id, exit]]) });
1453
805
  }
1454
806
  /** Create an owned worker run and its parent receipt; `createStoreOwnedRun` holds the checks. */
1455
807
  createOwnedRun(input, parentId, requestId, worker, requestHash, spawnCapacityRefusal, executionIdentity = { kind: 'internal' }) {
1456
808
  return createStoreOwnedRun({
1457
- peek: (id) => this.peek(id),
1458
- hasRun: (id) => this.hasRun(id),
809
+ peek: (id) => this.rows.peek(id),
810
+ hasRun: (id) => this.rows.hasRun(id),
1459
811
  held: this.held, deleted: this.deleted, db: this.db,
1460
812
  buildRun: (ownedInput, id) => this.buildRun(ownedInput, id),
1461
813
  writeWorkerIdentity: (id, identity) => this.workerExecutions.writeWorkerIdentity(id, identity),
1462
814
  writeWorkerExecution: (id, proof, fresh) => this.workerExecutions.writeWorkerExecution(id, proof, fresh),
1463
- commitIndex: (owned) => this.commitIndex(owned),
815
+ commitIndex: (owned) => this.persistence.commitIndex(owned),
1464
816
  }, input, parentId, requestId, worker, requestHash, spawnCapacityRefusal, executionIdentity);
1465
817
  }
1466
- /**
1467
- * Durably replace or delete staged rows together with pending dirty rows. Persist before
1468
- * changing held objects or notifying subscribers. On failure retain all pending state; flush()
1469
- * remains best-effort.
1470
- */
1471
- commitIndex(input, source, write = {}) {
1472
- const exits = new Map(write.exits);
1473
- const staged = stageCommit(input, {
1474
- peek: id => this.peek(id),
1475
- completionArchiveBlocker: run => this.archive.completionArchiveBlocker(run),
1476
- stageArchive: (staged, run, archived) => this.archive.stageArchive(staged, run, archived, exits),
1477
- });
1478
- 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)]));
1479
- if (!this.db)
1480
- throw this.openFailure ?? new Error('runs database unavailable: nothing can be saved');
1481
- this.assertWritable(staged);
1482
- this.persist(staged);
1483
- // Preserve existing record references, but expose the entire transaction before its first event, which
1484
- // carries the record this commit wrote (`committed`). A finished run is held until the next sweep.
1485
- for (const [id, next] of staged) {
1486
- this.coldReads.forget(id);
1487
- if (!next) {
1488
- this.held.delete(id);
1489
- continue;
1490
- }
1491
- this.committing.add(id);
1492
- const current = this.held.get(id);
1493
- if (current)
1494
- replaceRecord(current, next);
1495
- else
1496
- this.held.set(id, next);
1497
- }
1498
- try {
1499
- for (const id of staged.keys()) {
1500
- const run = this.held.get(id);
1501
- if (run)
1502
- publishRunWrite(this.published, committed.get(id) ?? run, before.get(id), source, exits.get(id));
1503
- else
1504
- this.published.publish('run.deleted', { runId: id });
1505
- }
1506
- }
1507
- finally {
1508
- for (const id of staged.keys())
1509
- this.committing.delete(id);
1510
- this.sweepIfSettled(staged.keys());
1511
- }
1512
- for (const [id, next] of staged)
1513
- if (next?.archived)
1514
- this.archive.compressor.enqueue(id);
1515
- }
1516
- /**
1517
- * Refuse (throwing, with nothing changed) a commit that stages a quarantined run, or a run whose
1518
- * family this store does not claim and cannot take: another process owns it, or a dead process
1519
- * left it live and it has not been adopted.
1520
- */
1521
- assertWritable(staged) {
1522
- const families = new Map();
1523
- const held = new Set();
1524
- for (const [id, next] of staged) {
1525
- if (this.quarantined.has(id))
1526
- throw new RunWriteRefusedError(id, 'quarantined');
1527
- const family = next ? familyKey(next) : this.familyOf(id);
1528
- families.set(id, family);
1529
- if (this.held.has(id))
1530
- held.add(family);
1531
- }
1532
- // A run this store holds may move to a new family; any other row is claimed as a plain write.
1533
- const owned = new Set([...this.claims.claimFamilies(held, { allowLive: true }),
1534
- ...this.claims.claimFamilies([...families.values()].filter((family) => !held.has(family)))]);
1535
- for (const [id, family] of families) {
1536
- if (!owned.has(family))
1537
- throw this.claims.runOwnership(id) === 'fallback' ? this.claims.fallbackRefusal(id) : new RunWriteRefusedError(id, this.claims.runOwnership(id) === 'orphaned' ? 'orphaned' : 'foreign');
1538
- }
1539
- }
1540
- /** The family of a run this store knows: held, else its row; a run nowhere is its own. */
1541
- familyOf(id) {
1542
- const held = this.held.get(id);
1543
- return held ? familyKey(held) : this.deletedFamilies.get(id) ?? this.db?.familyOf(id) ?? id;
1544
- }
1545
- /** Schedule the sweep that lets any of `ids` leave memory, when one of them now can. */
1546
- sweepIfSettled(ids) {
1547
- for (const id of ids) {
1548
- const run = this.held.get(id);
1549
- if (run && !this.isAnchor(id, run)) {
1550
- this.scheduleSave();
1551
- return;
1552
- }
1553
- }
1554
- }
1555
818
  /** Move run `id` by `exit` (ADR 0056): its status and `extras` in one write, checked against the
1556
819
  * record that write changes. A run this store cannot write is neither checked nor written. The
1557
820
  * exit decides how the write persists (`exitDurability`), never the extras. A guarded exit (one
@@ -1561,7 +824,7 @@ export class RunStore {
1561
824
  move(id, exit, extras = {}, call = {}) {
1562
825
  const spec = RUN_EXITS[exit];
1563
826
  const guarded = Boolean(spec.guard || spec.settle);
1564
- const run = guarded ? this.peek(id) : this.record(id);
827
+ const run = guarded ? this.rows.peek(id) : this.rows.record(id);
1565
828
  if (!run || spec.guard?.(run) === false) {
1566
829
  if (spec.refused)
1567
830
  throw new Error(spec.refused);
@@ -1575,8 +838,8 @@ export class RunStore {
1575
838
  moved = this.writeRun(id, run, applyExit(run, exit, redacted, call), exitDurability(exit, run), exit);
1576
839
  else {
1577
840
  const input = { ...run, ...redacted };
1578
- this.commitIndex(new Map([[id, { ...(spec.settle?.(input, { ...call, now: new Date().toISOString() }) ?? input), ...applyExit(run, exit, {}, call) }]]), undefined, { exits: new Map([[id, exit]]) });
1579
- moved = this.peek(id);
841
+ 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]]) });
842
+ moved = this.rows.peek(id);
1580
843
  }
1581
844
  if (event)
1582
845
  this.exitEvents.write(id, event);
@@ -1586,7 +849,7 @@ export class RunStore {
1586
849
  * completion option or task access, else the next save writes it. A status in the patch, which only test
1587
850
  * fixtures still write, takes the exit's record rule (`doneCommits`). */
1588
851
  updateRun(id, patch) {
1589
- const run = this.record(id);
852
+ const run = this.rows.record(id);
1590
853
  if (!run)
1591
854
  return undefined;
1592
855
  const committed = (patch.status === 'done' && doneCommits(run)) || patch.handoffRecords !== undefined ||
@@ -1599,15 +862,15 @@ export class RunStore {
1599
862
  const before = snapshotRun(run);
1600
863
  const hooks = {
1601
864
  redact: (text) => this.redaction.redactText(text),
1602
- repoHandle: this.repoHandle,
865
+ repoHandle: this.repoScope.repoHandle,
1603
866
  restore: () => restoreHistory(this.dataDir, id),
1604
867
  archive: (record, archived) => this.archive.applyArchived(record, archived, before, exit),
1605
- touch: (record) => this.touch(record, before, exit),
868
+ touch: (record) => this.persistence.touch(record, before, exit),
1606
869
  };
1607
870
  if (durability === 'committed') {
1608
871
  const staged = stageDurableUpdate(run, patch, hooks, exit);
1609
- this.commitIndex(new Map([[id, staged.run]]), undefined, { before: new Map([[id, before]]), exits: new Map([[id, staged.exit]]) });
1610
- return this.record(id);
872
+ this.persistence.commitIndex(new Map([[id, staged.run]]), undefined, { before: new Map([[id, before]]), exits: new Map([[id, staged.exit]]) });
873
+ return this.rows.record(id);
1611
874
  }
1612
875
  stageDebouncedUpdate(run, patch, hooks);
1613
876
  return run;
@@ -1617,15 +880,15 @@ export class RunStore {
1617
880
  }
1618
881
  /** Append a step to an existing run (used by "Continue" — spec 003). */
1619
882
  addStep(runId, step) {
1620
- const run = this.record(runId);
883
+ const run = this.rows.record(runId);
1621
884
  if (!run || run.steps.some((s) => s.id === step.id))
1622
885
  return;
1623
886
  const before = snapshotRun(run);
1624
887
  run.steps = [...run.steps, { ...step, status: 'pending', iterations: 0, tokensUsed: 0 }];
1625
- this.touch(run, before);
888
+ this.persistence.touch(run, before);
1626
889
  }
1627
890
  updateStep(runId, stepId, patch) {
1628
- const run = this.record(runId);
891
+ const run = this.rows.record(runId);
1629
892
  const step = run?.steps.find((s) => s.id === stepId);
1630
893
  if (!run || !step)
1631
894
  return;
@@ -1633,275 +896,19 @@ export class RunStore {
1633
896
  // Replaced, never changed in place, so `before` keeps the steps as they were.
1634
897
  run.steps = run.steps.map((candidate) => candidate === step ? next : candidate);
1635
898
  Object.assign(run, stepTotals(run.steps));
1636
- this.touch(run, before);
899
+ this.persistence.touch(run, before);
1637
900
  }
1638
901
  /** A debounced write of the held record `id`: `apply` changes it in place, then `touch` saves it. */
1639
902
  change(id, apply) {
1640
- const run = this.record(id), before = snapshotRun(run);
903
+ const run = this.rows.record(id), before = snapshotRun(run);
1641
904
  if (!run)
1642
905
  return undefined;
1643
906
  apply(run);
1644
- this.touch(run, before);
907
+ this.persistence.touch(run, before);
1645
908
  return run;
1646
909
  }
1647
- /** Indexed family enumeration, including members not yet flushed to SQLite. */
1648
- listFamilyRunIds(rootId) {
1649
- const ids = new Set([rootId, ...(this.db?.listIdsByParent(rootId) ?? [])]);
1650
- for (const [id, run] of this.held) {
1651
- if (familyRootOf(run) === rootId)
1652
- ids.add(id);
1653
- else if (id !== rootId)
1654
- ids.delete(id);
1655
- }
1656
- for (const id of this.deleted)
1657
- ids.delete(id);
1658
- return [...ids];
1659
- }
1660
- /** Write the pending rows out now (used on shutdown). */
1661
- flush() {
1662
- if (this.saveTimer) {
1663
- clearTimeout(this.saveTimer);
1664
- this.saveTimer = null;
1665
- }
1666
- this.saveNow();
1667
- }
1668
910
  // ---- internals -----------------------------------------------------------
1669
911
  seqs = new Map();
1670
- /** Same location `handoffPath()` in handoff.ts produces — inlined to keep
1671
- * the store free of upward imports. */
1672
- handoffPath(runId) {
1673
- return join(this.claims.sourceDataDir(runId), 'runs', `${runId}.handoff.md`);
1674
- }
1675
- /** Agent screenshots persisted by the run manager (see persistImage). */
1676
- imagesDir(runId) {
1677
- return join(this.claims.sourceDataDir(runId), 'runs', `${runId}-images`);
1678
- }
1679
- /** Save `run` debounced and publish it; `before` is the record at the write's entry (none: created). */
1680
- touch(run, before, exit) {
1681
- this.dirty.add(run.id);
1682
- this.scheduleSave();
1683
- publishRunWrite(this.published, run, before, undefined, exit);
1684
- this.archive.maybeEnqueueHistoryCompress(run);
1685
- }
1686
- /** The held record is gone; the next save or commit deletes its row, fenced by `family`'s claim
1687
- * and by the revision this store last saw (kept in `base` until the delete is written). */
1688
- markDeleted(id, family) {
1689
- this.liveItems.forget(id);
1690
- this.coldReads.forget(id);
1691
- const read = this.coldBase.get(id);
1692
- if (!this.base.has(id) && read)
1693
- this.base.set(id, storedRow(read));
1694
- this.dirty.delete(id);
1695
- this.deleted.add(id);
1696
- this.deletedFamilies.set(id, family);
1697
- this.historyOwed.add(id);
1698
- }
1699
- /** Debounced so token-usage updates don't rewrite a row per event. Nothing to schedule without
1700
- * a database: a `RunStore.unavailable` store, or a closed one, writes nothing. */
1701
- scheduleSave() {
1702
- if (this.saveTimer || !this.db)
1703
- return;
1704
- this.saveTimer = setTimeout(() => {
1705
- this.saveTimer = null;
1706
- this.saveNow();
1707
- }, 300);
1708
- this.saveTimer.unref?.();
1709
- }
1710
- /** The single database write, so a test can fail it the way a full disk would. */
1711
- writeIndex(changes) {
1712
- const transaction = (changes) => { assertProjectWritable(this.dataDir); return this.db.transaction(changes); };
1713
- return this.persistence ? this.persistence(changes, transaction) : transaction(changes);
1714
- }
1715
- /**
1716
- * Write `staged` plus everything still pending — dirty rows from memory, deletions — in one
1717
- * transaction, then clear the pending marks. Throws with nothing cleared when it fails.
1718
- * Never copies or sorts the whole store: the cost is the rows that changed.
1719
- *
1720
- * Fenced (#779, plan step 3): the transaction commits only if every family it writes still
1721
- * carries this store's claim and every row is at the revision this store last saw. Otherwise
1722
- * nothing is written and `handleConflicts` deals with the rows that changed under it.
1723
- */
1724
- persist(staged) {
1725
- const upserts = [];
1726
- const deletes = [];
1727
- const families = new Map();
1728
- const extras = new Map();
1729
- const encode = (run) => {
1730
- const encoded = encodeRawRecord(run, (this.base.get(run.id) ?? this.coldBase.get(run.id))?.extras);
1731
- extras.set(run.id, encoded.extras);
1732
- const projected = { ...run };
1733
- restoreOriginatingIssue(projected);
1734
- upserts.push({ ...encodeRunRow(run, encoded.data),
1735
- issueAttributionCurrent: isDeepStrictEqual(projected, run) });
1736
- };
1737
- for (const [id, next] of staged) {
1738
- if (next)
1739
- encode(next);
1740
- else
1741
- deletes.push(id);
1742
- families.set(id, next ? familyKey(next) : this.familyOf(id));
1743
- }
1744
- for (const id of this.dirty) {
1745
- const run = this.held.get(id);
1746
- if (!run || staged.has(id))
1747
- continue;
1748
- encode(run);
1749
- families.set(id, familyKey(run));
1750
- }
1751
- for (const id of this.deleted) {
1752
- if (staged.has(id))
1753
- continue;
1754
- deletes.push(id);
1755
- families.set(id, this.familyOf(id));
1756
- }
1757
- // A row's insertion order (`seq`) is the order this write inserts it in, and it is where the
1758
- // run lists among runs created in the same millisecond. Insert new runs in creation order (the
1759
- // held set's, then staged runs not held yet), whether staged or dirty brought them here.
1760
- if (upserts.filter((row) => !this.base.has(row.id)).length > 1) {
1761
- const created = new Map();
1762
- for (const id of [...this.held.keys(), ...staged.keys()])
1763
- if (!created.has(id))
1764
- created.set(id, created.size);
1765
- upserts.sort((a, b) => created.get(a.id) - created.get(b.id));
1766
- }
1767
- // A held run whose write moved it into a new family (a worker quarantined to `invalid`) takes
1768
- // that family's claim first; one it cannot take fails the fence below as claim-lost.
1769
- const moved = [...new Set(families.values())].filter((family) => !this.claimed.has(family) && !this.pendingClaims.has(family));
1770
- if (moved.length > 0)
1771
- this.claims.claimFamilies(moved, { allowLive: true });
1772
- let commit;
1773
- try {
1774
- commit = this.writeIndex({ upserts, deletes, ...(this.owner ? { fence: this.fence(families) } : {}) });
1775
- }
1776
- catch (error) {
1777
- if (error instanceof RunConflictError)
1778
- this.handleConflicts(error, staged);
1779
- throw error;
1780
- }
1781
- for (const [family, generation] of commit.claims) {
1782
- this.claimed.set(family, generation);
1783
- this.pendingClaims.delete(family);
1784
- }
1785
- for (const row of upserts) {
1786
- 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) });
1787
- }
1788
- for (const id of deletes) {
1789
- this.liveItems.forget(id);
1790
- this.base.delete(id);
1791
- this.deletedFamilies.delete(id);
1792
- this.retention.removeOwedHistory(id);
1793
- }
1794
- this.dirty.clear();
1795
- this.deleted.clear();
1796
- if (this.saveTimer) {
1797
- clearTimeout(this.saveTimer);
1798
- this.saveTimer = null;
1799
- }
1800
- }
1801
- /** What a write of these rows (id → family) must still find: this store's claims, at the
1802
- * generations it took them, and each row at the revision it last saw (none for a new row). */
1803
- fence(families) {
1804
- const claims = new Map();
1805
- const rows = new Map();
1806
- for (const [id, family] of families) {
1807
- const pending = this.pendingClaims.get(family);
1808
- // Generations start at 1, so an unclaimed family's 0 fails the fence as claim-lost.
1809
- claims.set(family, pending !== undefined ? { take: pending } : { generation: this.claimed.get(family) ?? 0 });
1810
- rows.set(id, { revision: (this.base.get(id) ?? this.coldBase.get(id))?.revision ?? null, family });
1811
- }
1812
- return { owner: this.owner, claims, rows };
1813
- }
1814
- /**
1815
- * Handle a fenced-write conflict. Save unexpected conflict evidence before clearing pending
1816
- * state or quarantining the row. If evidence persistence fails, retain pending writes. Other
1817
- * rows remain writable; stale unclaimed reads only fail their write.
1818
- */
1819
- handleConflicts(error, staged) {
1820
- const unexpected = error.conflicts.filter((conflict) => this.held.has(conflict.id) || this.deleted.has(conflict.id) || this.coldBase.get(conflict.id)?.owned === true);
1821
- if (unexpected.length === 0 || !this.db || !this.owner)
1822
- return;
1823
- const evidence = unexpected.map((conflict) => {
1824
- const seen = this.base.get(conflict.id) ?? this.coldBase.get(conflict.id);
1825
- const local = staged.has(conflict.id) ? staged.get(conflict.id) : this.deleted.has(conflict.id) ? null : this.held.get(conflict.id) ?? null;
1826
- return {
1827
- runId: conflict.id, reason: conflict.reason,
1828
- baseRevision: seen?.revision ?? null, baseData: seen?.data ?? null,
1829
- localData: local === null ? null : JSON.stringify(local), localDeleted: local === null,
1830
- currentRevision: conflict.current?.revision ?? null, currentData: conflict.current?.data ?? null,
1831
- };
1832
- });
1833
- let seqs;
1834
- try {
1835
- seqs = this.db.recordConflicts(this.owner.session, evidence);
1836
- }
1837
- catch (evidenceError) {
1838
- const message = evidenceError instanceof Error ? evidenceError.message : String(evidenceError);
1839
- console.error(`[hsq] ${RUNS_DB_FILE}: could not record the conflicting write on ${unexpected.map((c) => c.id).join(', ')}; it stays pending: ${message}`);
1840
- return;
1841
- }
1842
- unexpected.forEach((conflict, index) => {
1843
- const family = this.familyOf(conflict.id);
1844
- this.liveItems.forget(conflict.id);
1845
- this.quarantined.add(conflict.id);
1846
- this.coldReads.forget(conflict.id);
1847
- this.dirty.delete(conflict.id);
1848
- this.deleted.delete(conflict.id);
1849
- this.deletedFamilies.delete(conflict.id);
1850
- // The delete did not happen, so the history stays with the row.
1851
- this.historyOwed.delete(conflict.id);
1852
- if (conflict.reason === 'claim-lost') {
1853
- this.claimed.delete(family);
1854
- this.pendingClaims.delete(family);
1855
- }
1856
- const decoded = conflict.current ? decodeRunRow(conflict.current.data) : undefined;
1857
- const current = decoded?.run;
1858
- if (this.claims.isFallbackRun(conflict.id))
1859
- this.held.delete(conflict.id);
1860
- const held = this.held.get(conflict.id);
1861
- const before = snapshotRun(held ?? staged.get(conflict.id) ?? undefined);
1862
- if (current && conflict.current) {
1863
- // The other writer's record as it stands, normalized only as a live owner's run would be.
1864
- reconcileLoadedRun(current, { keepLive: true });
1865
- rescopeRun(current, this.repoHandle);
1866
- if (held)
1867
- replaceRecord(held, current);
1868
- this.base.set(conflict.id, { revision: conflict.current.revision, seq: conflict.current.seq, data: conflict.current.data, extras: decoded.extras });
1869
- publishRunWrite(this.published, held ?? current, before ?? snapshotRun(current), 'conflict');
1870
- }
1871
- else {
1872
- this.held.delete(conflict.id);
1873
- this.base.delete(conflict.id);
1874
- this.published.publish('run.deleted', { runId: conflict.id });
1875
- }
1876
- 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]}.`);
1877
- });
1878
- this.scheduleSave();
1879
- }
1880
- /** Write what is pending, then (unless closing) let every run whose write settled leave memory. */
1881
- saveNow(evict = true) {
1882
- if (!this.db || projectWriteRefused(this.dataDir))
1883
- return;
1884
- // A second attempt only after a conflict excluded its rows: the unrelated rest goes out at once.
1885
- for (let attempt = 0; attempt < 2 && (this.dirty.size > 0 || this.deleted.size > 0); attempt++) {
1886
- const quarantined = this.quarantined.size;
1887
- try {
1888
- this.persist(new Map());
1889
- }
1890
- catch (err) {
1891
- if (err instanceof RunConflictError && this.quarantined.size > quarantined)
1892
- continue;
1893
- // A pending save may outlive its directory; never recreate it or hide live-directory
1894
- // failures. The rows stay pending (and held), so the next save or commit retries them.
1895
- if (existsSync(this.dataDir)) {
1896
- const message = err instanceof Error ? err.message : String(err);
1897
- console.error(`[hsq] failed to save ${RUNS_DB_FILE}: ${message}`);
1898
- }
1899
- break;
1900
- }
1901
- }
1902
- if (evict)
1903
- this.evictSettled();
1904
- }
1905
912
  /**
1906
913
  * Write what is pending and release the database (store disposal, process shutdown).
1907
914
  * Idempotent. A closed store keeps answering reads for what it holds — the final save evicts
@@ -1914,11 +921,7 @@ export class RunStore {
1914
921
  this.published.publish('store.closed', {});
1915
922
  this.archive.compressor.stop();
1916
923
  this.transcriptFacts.stop();
1917
- if (this.saveTimer) {
1918
- clearTimeout(this.saveTimer);
1919
- this.saveTimer = null;
1920
- }
1921
- this.saveNow(false);
924
+ this.persistence.closeSave();
1922
925
  if (this.db && this.owner) {
1923
926
  // Every claim goes with the store. Should the release fail, the claims stay until this
1924
927
  // process exits; from then on they are provably dead and the next opener takes them.