@hearsay-tools/squawk 0.18.0-pr4084.7814 → 0.18.0-pr4088.7818

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 (97) hide show
  1. package/dist/activity/publisher.js +2 -2
  2. package/dist/activity/publisher.js.map +1 -1
  3. package/dist/activity/read-model.js +1 -1
  4. package/dist/activity/read-model.js.map +1 -1
  5. package/dist/activity/requests.d.ts +4 -2
  6. package/dist/activity/requests.js +1 -1
  7. package/dist/activity/requests.js.map +1 -1
  8. package/dist/artifacts/reports-index.d.ts +2 -1
  9. package/dist/artifacts/reports-index.js +1 -1
  10. package/dist/artifacts/reports-index.js.map +1 -1
  11. package/dist/ci-wait/controller.d.ts +46 -46
  12. package/dist/delegation/conversations.d.ts +6 -2
  13. package/dist/delegation/conversations.js +3 -2
  14. package/dist/delegation/conversations.js.map +1 -1
  15. package/dist/delegation/family-end.d.ts +4 -2
  16. package/dist/delegation/results.js +2 -2
  17. package/dist/delegation/results.js.map +1 -1
  18. package/dist/delegation/routes.d.ts +10 -10
  19. package/dist/delegation/routes.js +1 -1
  20. package/dist/delegation/routes.js.map +1 -1
  21. package/dist/delegation/scratch-cleanup.js +2 -2
  22. package/dist/delegation/scratch-cleanup.js.map +1 -1
  23. package/dist/delegation/service.js +2 -2
  24. package/dist/delegation/service.js.map +1 -1
  25. package/dist/delegation/transport.d.ts +14 -14
  26. package/dist/delegation/worker-cleanup.js +1 -1
  27. package/dist/delegation/worker-cleanup.js.map +1 -1
  28. package/dist/preview/host.d.ts +2 -1
  29. package/dist/preview/host.js +1 -1
  30. package/dist/preview/host.js.map +1 -1
  31. package/dist/project-migration/live.js +3 -3
  32. package/dist/project-migration/live.js.map +1 -1
  33. package/dist/runs/claim-families.d.ts +1 -1
  34. package/dist/runs/claim-families.js +1 -1
  35. package/dist/runs/live-tasks.js +1 -1
  36. package/dist/runs/live-tasks.js.map +1 -1
  37. package/dist/runs/loaded-run-exits.d.ts +23 -0
  38. package/dist/runs/loaded-run-exits.js +46 -1
  39. package/dist/runs/loaded-run-exits.js.map +1 -1
  40. package/dist/runs/ports.d.ts +27 -13
  41. package/dist/runs/retention.d.ts +3 -1
  42. package/dist/runs/retention.js +5 -5
  43. package/dist/runs/retention.js.map +1 -1
  44. package/dist/runs/run-claims-topic.d.ts +130 -0
  45. package/dist/runs/run-claims-topic.js +258 -0
  46. package/dist/runs/run-claims-topic.js.map +1 -0
  47. package/dist/runs/run-claims.d.ts +1 -1
  48. package/dist/runs/run-claims.js +1 -1
  49. package/dist/runs/run-claims.js.map +1 -1
  50. package/dist/runs/run-database.d.ts +1 -1
  51. package/dist/runs/run-index.js +3 -1
  52. package/dist/runs/run-index.js.map +1 -1
  53. package/dist/runs/run-pins.d.ts +38 -0
  54. package/dist/runs/run-pins.js +45 -0
  55. package/dist/runs/run-pins.js.map +1 -0
  56. package/dist/runs/run-references.d.ts +1 -1
  57. package/dist/runs/run-references.js +1 -1
  58. package/dist/runs/run-references.js.map +1 -1
  59. package/dist/runs/store-open.d.ts +45 -0
  60. package/dist/runs/store-open.js +89 -0
  61. package/dist/runs/store-open.js.map +1 -0
  62. package/dist/runs/store.d.ts +6 -139
  63. package/dist/runs/store.js +44 -417
  64. package/dist/runs/store.js.map +1 -1
  65. package/dist/runs/webhook.d.ts +3 -1
  66. package/dist/runs/webhook.js +2 -2
  67. package/dist/runs/webhook.js.map +1 -1
  68. package/dist/serve-boot.d.ts +2 -2
  69. package/dist/server/completion-actions.js +2 -2
  70. package/dist/server/completion-actions.js.map +1 -1
  71. package/dist/server/models-routes.d.ts +13 -13
  72. package/dist/server/project-run-files.d.ts +3 -1
  73. package/dist/server/project-run-files.js +3 -3
  74. package/dist/server/project-run-files.js.map +1 -1
  75. package/dist/server/reports-api.d.ts +2 -2
  76. package/dist/server/run-checkout.d.ts +3 -1
  77. package/dist/server/run-checkout.js +3 -3
  78. package/dist/server/run-checkout.js.map +1 -1
  79. package/dist/server/run-event-feed.js +2 -2
  80. package/dist/server/run-event-feed.js.map +1 -1
  81. package/dist/server/server.js +9 -9
  82. package/dist/server/server.js.map +1 -1
  83. package/dist/server/workspace-live-routes.d.ts +6 -6
  84. package/dist/workflows/run/family-reconciler.js +2 -2
  85. package/dist/workflows/run/family-reconciler.js.map +1 -1
  86. package/dist/workflows/run/maintenance-claims.js +6 -6
  87. package/dist/workflows/run/maintenance-claims.js.map +1 -1
  88. package/dist/workflows/run/run-cancel.js +1 -1
  89. package/dist/workflows/run/run-cancel.js.map +1 -1
  90. package/dist/workflows/run/run-recovery.js +3 -3
  91. package/dist/workflows/run/run-recovery.js.map +1 -1
  92. package/dist/workflows/run/run-settlement.js +1 -1
  93. package/dist/workflows/run/run-settlement.js.map +1 -1
  94. package/dist/workflows/run.js +7 -7
  95. package/dist/workflows/run.js.map +1 -1
  96. package/package.json +4 -4
  97. package/scripts/benchmark-run-store.ts +2 -2
@@ -1,8 +1,7 @@
1
1
  import { legacyIndexRows, readableSavedRunner, upgradeLegacyRunRow, withKeptFields } from './legacy-run-rows.js';
2
- import { dataReadDirs, runDataDir } from '../project-paths.js';
3
- import { addRunSource, copyFallbackFamily, fallbackRunSource, fallbackRunDeleteError } from './project-run-sources.js';
2
+ import { addRunSource, fallbackRunSource } from './project-run-sources.js';
4
3
  import { registeredWaitRecord, registeredReceiptRecord } from './wait-registration-write.js';
5
- import { stageCommit, stageLoaded, stageDurableUpdate, stageDebouncedUpdate, stageConversation, stageStepUpdate, stepTotals, redactPatch } from './record-write-rules.js';
4
+ import { stageCommit, stageDurableUpdate, stageDebouncedUpdate, stageConversation, stageStepUpdate, stepTotals, redactPatch } from './record-write-rules.js';
6
5
  import { publishRunWrite, RunLifecycle, snapshotRun } from './lifecycle.js';
7
6
  import { listPeerTaskSummaries, parseStoredSummary } from './run-summary-page.js';
8
7
  export { parseStoredSummary } from './run-summary-page.js';
@@ -28,7 +27,7 @@ import { restoreHistory } from './history-file.js';
28
27
  // Type-only module (zod + nothing else), so this cannot cycle back into the store.
29
28
  import { workflowDefSchema } from '../workflows/types.js';
30
29
  import { applyOutcomes } from './outcome-commit.js';
31
- import { ISSUE_URL_RE, namesForeignReference, referencedPrDeclaration, rescopeRun, resolveReferencedRef, restoreOriginatingIssue, trackReferencedIssues, trackReferencedPrs } from './run-references.js';
30
+ import { ISSUE_URL_RE, namesForeignReference, rescopeRun, restoreOriginatingIssue, trackReferencedIssues, trackReferencedPrs } from './run-references.js';
32
31
  import { applyExit, doneCommits, exitDurability, RUN_EXITS } from './run-exits.js';
33
32
  import { assertConversationIdFree } from './conversation-identity.js';
34
33
  export { ConversationIdInUseError } from './conversation-identity.js';
@@ -36,8 +35,7 @@ import { LEGACY_RUNNER_IDS } from '../core/runner-ids.js';
36
35
  import { ARCHIVED_ROOT, RUNS_DB_FILE, RUNS_IMPORT_COMPLETE_KEY, RunConflictError, RunDatabase, RunDatabaseBusyError, } from './run-database.js';
37
36
  import { listBranchOwners } from './branch-owners.js';
38
37
  import { guardedJsonSql } from './guarded-json-sql.js';
39
- import { restoreLostReferencedPullRequest } from './loaded-run-healing.js';
40
- import { failLoadedInterruptedRun, restoreLoadedUsageLimitHold, settleLoadedStop } from './loaded-run-exits.js';
38
+ import { reconcileLoadedRun } from './loaded-run-exits.js';
41
39
  import { hasLegacyWaitFields, UNREADABLE_WAIT } from './legacy-waits.js';
42
40
  export { ciWaitEntry, holdsWorkerWait, upgradeLegacyWaits, workerWaitEntry } from './legacy-waits.js';
43
41
  import { ExitEvents } from './exit-events.js';
@@ -45,16 +43,18 @@ import { encodeRunRow, familyRootOf, isLiveRecord, materializedWorktreePath, new
45
43
  import { RunRetentionTopic } from './run-retention.js';
46
44
  import { collectRawExtras, encodeRawRecord } from './raw-record.js';
47
45
  import { ColdReadCache, storedRow } from './cold-reads.js';
48
- import { assertNoLegacyCockpit, assertNoLegacyWriter, backUpLegacyIndex, LEGACY_INDEX_FILE, LegacyWriterError, readLegacyIndex } from './legacy-index.js';
46
+ import { LEGACY_INDEX_FILE, LegacyWriterError } from './legacy-index.js';
49
47
  import { toRunStoreOpenError } from './store-open-error.js';
50
- import { claimStoreFamilies } from './claim-families.js';
48
+ import { importLegacyIndex, OPEN_RETRY_DELAYS_MS, sleepSync } from './store-open.js';
49
+ import { RunClaimsTopic, RunWriteRefusedError } from './run-claims-topic.js';
50
+ import { RunPinsTopic } from './run-pins.js';
51
51
  import { createStoreOwnedRun } from './owned-run-create.js';
52
52
  import { WorkerResultsTopic } from './worker-results.js';
53
53
  import { RunEventLogTopic } from './event-log.js';
54
54
  import { RunRedaction } from './run-redaction.js';
55
55
  import { RunArchiveTopic } from './run-archive.js';
56
56
  import { RunReadFlagsTopic } from './run-read-flags.js';
57
- import { claimOwnerLive, closeClaimSession, familyKey, foreignClaimedRunIds, liveForeignClaimedRunIds, openClaimSession, rowFamily } from './run-claims.js';
57
+ import { closeClaimSession, familyKey, openClaimSession, rowFamily } from './run-claims.js';
58
58
  import { assertProjectWritable, projectWriteRefused } from '../server/cockpit-ownership.js';
59
59
  /**
60
60
  * A runner id as it may appear in a PERSISTED record (#547), spec 2026-11-18-runner-definitions.
@@ -177,150 +177,11 @@ export function decodeRunRecord(data) {
177
177
  }
178
178
  }
179
179
  export { LEGACY_INDEX_BACKUP_FILE, LEGACY_INDEX_FILE } from './legacy-index.js';
180
- /** The pauses between open attempts while the database is busy, when `open` may wait (a boot):
181
- * about 3.5 s in all, with each attempt's own busy timeout. Long enough for another process to
182
- * finish importing a large `runs.json`. */
183
- const OPEN_RETRY_DELAYS_MS = [50, 100, 200, 400, 800, 1600];
184
- /** Block this thread for `ms`. Only `open` does, at boot, when there is nothing else to run. */
185
- function sleepSync(ms) {
186
- Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
187
- }
188
180
  /** How many archived root runs the run lists carry per project (#864): `GET /run-summaries?archived=recent`
189
181
  * and `GET /workspace/runs-index`. Unarchived runs are never cut; older archived runs page in
190
182
  * through `GET /run-summaries/archived` and the workspace search. */
191
183
  export const ARCHIVED_WINDOW = 200;
192
- /**
193
- * Reconcile one record just read off disk with the fact that whichever process wrote it is gone.
194
- *
195
- * Mutates and returns `run`. Extracted from `RunStore.open` so the read-only index reader
196
- * (`./run-index.ts`) answers the SAME question about a `running` row on disk. Two parsers that
197
- * disagree here is a visible bug, not an internal one: the cockpit would show a task as running
198
- * in the ⌘K index and failed the moment you opened it.
199
- *
200
- * `keepLive` (#367): leave `queued`/`running`/`waiting` untouched so the caller can recover them
201
- * (RunManager.recover re-queues queued runs, resumes interrupted ones). Without it — one-shot CLI
202
- * paths that never recover, and the index reader, which has no manager at all — live-looking runs
203
- * are marked failed so no ghost stays behind.
204
- */
205
- export function reconcileLoadedRun(run, opts) {
206
- settleLoadedStop(run);
207
- restoreLoadedUsageLimitHold(run);
208
- failLoadedInterruptedRun(run, opts);
209
- clearLoadedStaleResume(run);
210
- restoreLostReferencedPullRequest(run, referencedPrDeclaration, resolveReferencedRef);
211
- restoreOriginatingIssue(run);
212
- // Repository scoping follows reconciliation: stores arm a handle asynchronously, while
213
- // the read-only index applies its cached handle to these fresh records (#97). This ordering
214
- // also scopes any referenced PR restored above without filtering candidate evidence first.
215
- return run;
216
- }
217
- function clearLoadedStaleResume(run) {
218
- // Recovery owns waits; a usage-limit appointment survives while status is waiting.
219
- stageLoaded(run);
220
- }
221
- /**
222
- * Settle an adopted dead owner’s live run without starting work. Untouched runs cancel; started
223
- * runs become interrupted. Stop explicitly cancels its target. Mutates run.
224
- */
225
- export function settleOrphanedRun(run, opts = {}) {
226
- if (opts.stop && (run.status === 'queued' || run.status === 'running' || run.status === 'waiting'))
227
- run.stopping = true;
228
- if (run.status === 'queued' && !run.startedAt && run.workflowDef !== undefined &&
229
- run.steps.every((step) => step.status === 'pending' && !step.startedAt && !step.sessionId)) {
230
- Object.assign(run, applyExit(run, 'cancel'));
231
- }
232
- return reconcileLoadedRun(run, { keepLive: false });
233
- }
234
- /** Test seam (#779): `beforeTransaction` runs once `runs.json` is read and parsed, before the
235
- * import asks for the write lock; `beforeCommit` runs inside the import transaction, after every
236
- * row is written and before the last check that no older Squawk wrote `runs.json` meanwhile. */
237
- let legacyImportHook;
238
- export function __setLegacyImportHookForTests(hook) {
239
- legacyImportHook = hook;
240
- }
241
- /**
242
- * Import legacy rows and the completion marker atomically, once. Recheck live-writer evidence
243
- * before commit and preserve exact input bytes in a synced backup. Leave runs.json untouched;
244
- * invalid entries are skipped and reported.
245
- */
246
- function importLegacyIndex(db, dataDir) {
247
- assertNoLegacyCockpit(dataDir);
248
- const snapshot = readLegacyIndex(join(dataDir, LEGACY_INDEX_FILE));
249
- const parsed = snapshot ? legacyIndexRows(snapshot.bytes, parseRunRecords) : undefined;
250
- const rows = parsed?.rows ?? [];
251
- const skipped = parsed?.skipped ?? 0;
252
- const source = !snapshot ? 'none' : parsed ? LEGACY_INDEX_FILE : `${LEGACY_INDEX_FILE} (unparseable)`;
253
- assertNoLegacyWriter(dataDir, snapshot);
254
- legacyImportHook?.beforeTransaction?.();
255
- let backup;
256
- const commit = db.transaction({
257
- upserts: rows,
258
- deletes: [],
259
- onlyIfMetaAbsent: RUNS_IMPORT_COMPLETE_KEY,
260
- beforeCommit: () => {
261
- legacyImportHook?.beforeCommit?.();
262
- assertNoLegacyWriter(dataDir, snapshot);
263
- backup = snapshot ? backUpLegacyIndex(dataDir, snapshot) : undefined;
264
- const read = snapshot ? { bytes: snapshot.bytes.length, sha256: snapshot.sha256, backup } : {};
265
- return { [RUNS_IMPORT_COMPLETE_KEY]: JSON.stringify({ at: new Date().toISOString(), source, records: rows.length, ...(skipped > 0 ? { skipped } : {}), ...read }) };
266
- },
267
- });
268
- // Told once, by the import that committed: the marker means no later open reads runs.json again.
269
- if (commit.skipped || backup === undefined)
270
- return;
271
- const kept = `Its exact bytes are kept in ${join(dataDir, backup)}; https://github.com/hearsay-tools/squawk/blob/main/docs/run-history-recovery.md says how to import it after a repair.`;
272
- if (!parsed)
273
- console.warn(`[hsq] ${LEGACY_INDEX_FILE} could not be read; no run was imported, and this project starts with an empty history. ${kept}`);
274
- else if (skipped > 0)
275
- console.warn(`[hsq] ${skipped} of ${parsed.total} runs in ${LEGACY_INDEX_FILE} could not be read and were not imported. ${kept}`);
276
- }
277
- /**
278
- * Finished rows whose stored summary an open-time normalization would still change: a referenced
279
- * PR an older Squawk's created-PR declaration erased, or issue attribution displaced by a
280
- * follow-up declaration (see `reconcileLoadedRun`), or a summary that is not JSON. Not live, so not
281
- * in the `live` column; open decodes these few and keeps the ones it actually repaired.
282
- */
283
- const LEGACY_REFERENCE_HEAL_SQL = guardedJsonSql("(json_extract(summary, '$.markerRefs.pr') IS NOT NULL AND json_extract(summary, '$.referencedPullRequestUrl') IS NULL)" +
284
- " OR (NOT EXISTS (SELECT 1 FROM meta WHERE key = 'issue-attribution:' || runs.id AND value = CAST(runs.revision AS TEXT)) AND json_extract(summary, '$.markerRefs.issue') IS NOT NULL)", 1);
285
- /**
286
- * The rows whose stored summary reading their record can change, as SQL over `runs`: the rows
287
- * `open` decodes to normalize (the `live` column it loads by, then `LEGACY_REFERENCE_HEAL_SQL`).
288
- * With a repository handle, a row whose summary `namesForeignReference` is one too, as
289
- * `setRepoHandle` reads it. The cold reader (run-index.ts) decodes exactly these rows and serves
290
- * every other stored summary, so the two read paths cannot disagree about which rows to read.
291
- * `AUTOMATION_ORIGIN_HEAL_SQL` is left out on purpose: no cross-project view reads
292
- * `automationId`, and asking it scans `data`.
293
- */
294
- export const LOAD_REPAIR_SQL = `live = 1 OR ${LEGACY_REFERENCE_HEAL_SQL}`;
295
- /**
296
- * Rows whose record names the automation that launched it while the stored summary does not
297
- * (hearsay-tools/cezarion#1332): summaries a Squawk wrote before `RunSummary.automationId`
298
- * existed. Open rewrites each one's summary once, so the sidebar's Automations tab classifies a
299
- * finished task nobody has opened since the upgrade. `instr` keeps the JSON parse off every
300
- * other row.
301
- */
302
- const AUTOMATION_ORIGIN_HEAL_SQL = `instr(data, '"automation') > 0 AND ${guardedJsonSql("json_extract(summary, '$.automationId') IS NULL" +
303
- " AND (json_extract(data, '$.automation.automationId') IS NOT NULL OR json_extract(data, '$.automationTrigger.automationId') IS NOT NULL)", 0, ['summary', 'data'])}`;
304
184
  export { branchOwnerOf } from './branch-owners.js';
305
- /** The one answer every control gives for a run another Squawk process owns (`409 { error }`). */
306
- export const RUN_IN_USE_ELSEWHERE = `run is in use by another Squawk process`;
307
- /** The answer for a run this process stopped writing after a conflicting write. */
308
- export const RUN_QUARANTINED = `run changed under this Squawk process — restart Squawk to reload it`;
309
- /** A write this store must not make: another process owns the run, its owner died with work
310
- * still live (adopt it first), or a conflict quarantined it. Nothing was changed. */
311
- export class RunWriteRefusedError extends Error {
312
- runId;
313
- ownership;
314
- constructor(runId, ownership, fallbackError) {
315
- super(ownership === 'fallback' ? fallbackError ?? `run ${runId} is read only in the fallback project directory`
316
- : ownership === 'quarantined' ? `${RUN_QUARANTINED}: ${runId}`
317
- : ownership === 'orphaned' ? `run ${runId} belongs to a Squawk process that exited; take it over before writing it`
318
- : `${RUN_IN_USE_ELSEWHERE}: ${runId}`);
319
- this.runId = runId;
320
- this.ownership = ownership;
321
- this.name = 'RunWriteRefusedError';
322
- }
323
- }
324
185
  /** Make `target` hold exactly `source`'s fields, keeping the object every holder references. */
325
186
  function replaceRecord(target, source) {
326
187
  for (const key of Object.keys(target))
@@ -450,13 +311,17 @@ export class RunStore {
450
311
  eventLog;
451
312
  /** The scrub of events and free text (hearsay-tools/squawk#4040). */
452
313
  redaction;
314
+ /** Claims, ownership, sources and fallback (hearsay-tools/squawk#4042). */
315
+ claims;
316
+ /** The holds that keep a run loaded (hearsay-tools/squawk#4042). */
317
+ runPins;
453
318
  executions;
454
319
  /** A worker's execution, process, identity and scope records (hearsay-tools/squawk#4039), built on
455
320
  * first use by the factory this process registered; throws when none is registered. */
456
321
  get workerExecutions() {
457
322
  return this.executions ??= workerExecutionsFactory()(this.dataDir, {
458
- peek: (id) => this.peek(id), getRun: (id) => this.getRun(id), writeDir: (id) => this.writeDir(id),
459
- sourceDataDir: (id) => this.sourceDataDir(id), commitIndex: (input) => this.commitIndex(input),
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),
460
325
  published: this.published, workerResults: this.workerResults,
461
326
  });
462
327
  }
@@ -468,9 +333,15 @@ export class RunStore {
468
333
  constructor(dataDir) {
469
334
  this.dataDir = dataDir;
470
335
  this.redaction = new RunRedaction();
336
+ this.claims = new RunClaimsTopic(dataDir, {
337
+ 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(),
340
+ });
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) });
471
342
  this.transcriptFacts = new RunTranscriptFacts(dataDir, {
472
- isFallbackRun: (id) => this.isFallbackRun(id),
473
- sourceDataDir: (id) => this.sourceDataDir(id),
343
+ isFallbackRun: (id) => this.claims.isFallbackRun(id),
344
+ sourceDataDir: (id) => this.claims.sourceDataDir(id),
474
345
  isOpen: () => this.db !== null,
475
346
  held: this.held,
476
347
  listFamilyRunIds: (rootId) => this.listFamilyRunIds(rootId),
@@ -478,14 +349,14 @@ export class RunStore {
478
349
  listRunIds: () => this.listRunIds(),
479
350
  });
480
351
  this.workerResults = new WorkerResultsTopic(dataDir, {
481
- peek: (id) => this.peek(id), hasRun: (id) => this.hasRun(id), hasFallbackRun: (id) => this.hasFallbackRun(id),
482
- writeDir: (id) => this.writeDir(id), sourceDataDir: (id) => this.sourceDataDir(id),
352
+ peek: (id) => this.peek(id), hasRun: (id) => this.hasRun(id), hasFallbackRun: (id) => this.claims.hasFallbackRun(id),
353
+ writeDir: (id) => this.claims.writeDir(id), sourceDataDir: (id) => this.claims.sourceDataDir(id),
483
354
  redactResult: (result) => this.redaction.redact({ type: 'worker-result', seq: 0, ts: result.observedAt, result }).result,
484
355
  redactText: (text) => this.redaction.redactText(text), commitDelegation: (patches) => this.commitDelegation(patches),
485
356
  });
486
357
  this.eventLog = new RunEventLogTopic(dataDir, {
487
358
  seqs: this.seqs, published: this.published, liveItems: this.liveItems, transcriptFacts: this.transcriptFacts, redaction: this.redaction,
488
- record: (id) => this.record(id), missingRunError: (runId) => this.missingRunError(runId), sourceDataDir: (id) => this.sourceDataDir(id),
359
+ record: (id) => this.record(id), missingRunError: (runId) => this.claims.missingRunError(runId), sourceDataDir: (id) => this.claims.sourceDataDir(id),
489
360
  touch: (run, before) => this.touch(run, before), change: (id, apply) => this.change(id, apply), repoHandle: () => this.repoHandle,
490
361
  maybeEnqueueHistoryCompress: (run) => this.archive.maybeEnqueueHistoryCompress(run),
491
362
  });
@@ -493,9 +364,9 @@ export class RunStore {
493
364
  db: () => this.db, held: this.held, deleted: this.deleted, quarantined: this.quarantined,
494
365
  historyOwed: this.historyOwed, seqs: this.seqs, published: this.published, transcriptFacts: this.transcriptFacts,
495
366
  peek: (id) => this.peek(id), hasRun: (id) => this.hasRun(id), record: (id) => this.record(id),
496
- listWorkersOf: (parentId) => this.listWorkersOf(parentId), isFallbackRun: (id) => this.isFallbackRun(id),
497
- hasFallbackRun: (id) => this.hasFallbackRun(id), listOrder: (run) => this.listOrder(run),
498
- claimFamilies: (families) => this.claimFamilies(families), markDeleted: (id, family) => this.markDeleted(id, family),
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),
499
370
  scheduleSave: () => this.scheduleSave(), commitIndex: (input) => this.commitIndex(input),
500
371
  commitDelegation: (patches) => this.commitDelegation(patches), applyArchived: (run, archived) => this.archive.applyArchived(run, archived),
501
372
  workerDeletionEvidence: (id) => this.workerExecutions.workerDeletionEvidence(id),
@@ -510,7 +381,7 @@ export class RunStore {
510
381
  claimed: this.claimed, base: this.base, owner: () => this.owner, transcriptFacts: this.transcriptFacts,
511
382
  decodeRunRow, sortNewestFirst, peek: (id) => this.peek(id), record: (id) => this.record(id),
512
383
  listWorkersOf: (parentId) => this.listWorkersOf(parentId), familyOf: (id) => this.familyOf(id),
513
- claimFamilies: (families, opts) => this.claimFamilies(families, opts), writeRefusal: (id) => this.writeRefusal(id),
384
+ claimFamilies: (families, opts) => this.claims.claimFamilies(families, opts), writeRefusal: (id) => this.claims.writeRefusal(id),
514
385
  assertWritable: (staged) => this.assertWritable(staged), decodeCold: (row) => this.decodeCold(row),
515
386
  listOrder: (run) => this.listOrder(run), commitIndex: (input, source, write) => this.commitIndex(input, source, write),
516
387
  touch: (run, before, exit) => this.touch(run, before, exit),
@@ -518,7 +389,7 @@ export class RunStore {
518
389
  });
519
390
  this.readFlags = new RunReadFlagsTopic({
520
391
  db: () => this.db, held: this.held, deleted: this.deleted, record: (id) => this.record(id),
521
- claimFamilies: (families) => this.claimFamilies(families), touch: (run, before) => this.touch(run, before),
392
+ claimFamilies: (families) => this.claims.claimFamilies(families), touch: (run, before) => this.touch(run, before),
522
393
  change: (id, apply) => this.change(id, apply),
523
394
  });
524
395
  }
@@ -569,13 +440,13 @@ export class RunStore {
569
440
  if (deferred)
570
441
  db.transaction({ upserts: [], deletes: [], meta: { [RUNS_IMPORT_COMPLETE_KEY]: 'none' } });
571
442
  else if (db.getMeta(RUNS_IMPORT_COMPLETE_KEY) === undefined)
572
- importLegacyIndex(db, dataDir);
443
+ importLegacyIndex(db, dataDir, parseRunRecords);
573
444
  if (source)
574
445
  db = addRunSource(db, dataDir, source);
575
446
  store.db = db;
576
447
  store.owner = openClaimSession();
577
448
  if (!maintenance) {
578
- store.loadHeldRows();
449
+ store.claims.loadHeldRows();
579
450
  store.transcriptFacts.warmTranscriptFacts();
580
451
  store.exitEvents.writeLoaded();
581
452
  }
@@ -614,218 +485,6 @@ export class RunStore {
614
485
  /** Why this store has no database, when it is `RunStore.unavailable`'s: its runs are unknown,
615
486
  * not absent. */
616
487
  get unavailable() { return this.openFailure; }
617
- /** Every sidecar for a run follows the winning record, never file-by-file fallback. */
618
- sourceDataDir(id) { return this.isFallbackRun(id) ? dataReadDirs(this.dataDir)[1] : runDataDir(this.dataDir, id); }
619
- isFallbackRun(id) { return this.db?.isFallback(id) ?? false; }
620
- hasFallbackRun(id) { return this.db?.hasFallback(id) ?? false; }
621
- /**
622
- * Open-time load: the live rows, the finished rows a load normalization repairs, then the
623
- * delegation families of the live ones. A row that does not parse is skipped and left in the
624
- * database untouched; one warning says how many.
625
- *
626
- * Only rows this store can claim are loaded (#779, plan step 3). A live row whose family another
627
- * live process claims — `serve`'s parked run, seen by a headless `cez run` — is that process's:
628
- * it is not loaded, normalized or recovered here, and stays readable through `getRun` and the
629
- * list rows. A live row nobody alive claims is taken over, as before: this open recovers it
630
- * (`keepLive`) or settles it as interrupted.
631
- */
632
- loadHeldRows() {
633
- let unreadable = 0;
634
- const decode = (row) => {
635
- const decoded = decodeRunRow(row.data);
636
- if (!decoded) {
637
- unreadable++;
638
- this.unreadable.add(row.id);
639
- }
640
- return decoded;
641
- };
642
- const live = this.db.listLive();
643
- const owned = this.claimFamilies(live.map(rowFamily), { allowLive: true, wait: true });
644
- for (const row of live) {
645
- if (!owned.has(rowFamily(row)))
646
- continue;
647
- const decoded = decode(row);
648
- if (decoded)
649
- this.adoptLoadedRun(decoded, { keepLive: this.keepLive }, row);
650
- }
651
- const heal = this.db.listWhere(LEGACY_REFERENCE_HEAL_SQL).filter((row) => !this.held.has(row.id));
652
- const healable = this.claimFamilies(heal.map(rowFamily));
653
- for (const row of heal) {
654
- if (!healable.has(rowFamily(row)))
655
- continue;
656
- const decoded = decode(row);
657
- // Held only when the repair changed it: the next save writes it, then it leaves.
658
- if (decoded) {
659
- // Persist verification once even when legacy issue attribution was already correct.
660
- const needsIssueCheck = decoded.run.markerRefs?.issue !== undefined &&
661
- this.db.getMeta(`issue-attribution:${row.id}`) !== String(row.revision);
662
- this.adoptLoadedRun(decoded, { keepLive: this.keepLive, onlyIfChanged: !needsIssueCheck }, row);
663
- if (needsIssueCheck)
664
- this.dirty.add(row.id);
665
- }
666
- }
667
- const stale = this.db.listWhere(AUTOMATION_ORIGIN_HEAL_SQL).filter((row) => !this.held.has(row.id));
668
- const restamp = this.claimFamilies(stale.map(rowFamily));
669
- for (const row of stale) {
670
- if (!restamp.has(rowFamily(row)))
671
- continue;
672
- const decoded = decode(row);
673
- // Nothing in the record changes, only its summary: held dirty, the next save rewrites it.
674
- if (decoded) {
675
- this.adoptLoadedRun(decoded, { keepLive: this.keepLive }, row);
676
- this.dirty.add(row.id);
677
- }
678
- }
679
- for (const rootId of this.anchoredFamilies())
680
- this.holdFamily(rootId, decode);
681
- this.releaseUnheldClaims();
682
- if (unreadable > 0)
683
- console.warn(`[hsq] ${unreadable} run(s) in ${RUNS_DB_FILE} could not be read; they are left in the database untouched.`);
684
- }
685
- /** Normalize a record just read from `row` (see `reconcileLoadedRun`) and hold it. Marks the row
686
- * dirty only when normalization changed it, so the next save persists exactly the runs open()
687
- * rewrote. A row read up from schema-3 wait fields counts as changed: its rewrite drops them
688
- * and recomputes its summary and live column (`upgradeLegacyWaits`), as does a summary that does
689
- * not parse (hearsay-tools/squawk#3530). The caller has claimed the row's family. */
690
- adoptLoadedRun({ run, extras, upgraded }, opts, row) {
691
- if (this.db?.familyHasFallback(rowFamily(row)))
692
- return;
693
- // Serialized, so a key set to `undefined` reads as the absent key it is once written.
694
- const before = JSON.stringify(run);
695
- const wasCancelled = run.status === 'cancelled';
696
- if (opts.settle)
697
- settleOrphanedRun(run, { stop: opts.stop });
698
- else
699
- reconcileLoadedRun(run, opts);
700
- const changed = upgraded === true || JSON.stringify(run) !== before || parseStoredSummary(row.summary) === undefined;
701
- if (opts.onlyIfChanged && !changed)
702
- return;
703
- this.held.set(run.id, run);
704
- this.base.set(run.id, { revision: row.revision, seq: row.seq, data: row.data, extras });
705
- if (changed)
706
- this.dirty.add(run.id);
707
- if (!wasCancelled && run.status === 'cancelled')
708
- this.exitEvents.loadCancelled(run.id);
709
- }
710
- /**
711
- * Hold one delegation family: its root and every worker filed under it, read through the
712
- * `parent_run_id` index. No recursion: a worker's own id never names a family. The caller has claimed it. `settle` settles its live rows instead of keeping
713
- * them for recovery (`settleOrphanedRun`); `stopId` is the run a Stop settles as cancelled.
714
- */
715
- holdFamily(rootId, decode = (row) => decodeRunRow(row.data), settle = false, stopId) {
716
- const rows = [this.db.get(rootId), ...this.db.listByParent(rootId)];
717
- for (const row of rows) {
718
- if (!row || this.held.has(row.id) || this.deleted.has(row.id))
719
- continue;
720
- const decoded = decode(row);
721
- if (decoded)
722
- this.adoptLoadedRun(decoded, { keepLive: this.keepLive, settle, stop: row.id === stopId }, row);
723
- }
724
- }
725
- /** Make sure this store claims each of `families`; `claimStoreFamilies` takes the free ones. */
726
- claimFamilies(families, opts = {}) {
727
- return projectWriteRefused(this.dataDir) ? new Set() : claimStoreFamilies({
728
- claimed: this.claimed,
729
- pendingClaims: this.pendingClaims,
730
- db: this.db,
731
- owner: this.owner,
732
- scheduleSave: () => this.scheduleSave(),
733
- }, families, opts);
734
- }
735
- /** Release the claim of every family with nothing left in memory, once nothing is pending: a
736
- * failed save keeps its families claimed until it succeeds. A failed release retries at the
737
- * next sweep; `close()` releases the rest. */
738
- releaseUnheldClaims() {
739
- if (!this.db || !this.owner || this.dirty.size > 0 || this.deleted.size > 0)
740
- return;
741
- const kept = new Set();
742
- for (const run of this.held.values())
743
- kept.add(familyKey(run));
744
- // A claim never taken has nothing to release in the database.
745
- for (const family of this.pendingClaims.keys())
746
- if (!kept.has(family))
747
- this.pendingClaims.delete(family);
748
- const released = [...this.claimed.keys()].filter((family) => !kept.has(family));
749
- if (released.length === 0)
750
- return;
751
- try {
752
- this.db.releaseClaims(this.owner.session, released);
753
- for (const family of released)
754
- this.claimed.delete(family);
755
- }
756
- catch {
757
- // Busy or failing: the next sweep tries again.
758
- }
759
- }
760
- /**
761
- * Who may change this run right now (see `RunOwnership`), or undefined when there is no such
762
- * run. Read-only: nothing is claimed. Controls ask this first, so a run another process owns is
763
- * refused with `RUN_IN_USE_ELSEWHERE` and a dead process's run is adopted before it is changed.
764
- */
765
- runOwnership(id) {
766
- if (this.quarantined.has(id))
767
- return 'quarantined';
768
- const held = this.held.get(id);
769
- if (!this.db)
770
- return held ? 'held' : undefined;
771
- const family = held ? familyKey(held) : this.deleted.has(id) ? undefined : this.db.familyOf(id);
772
- if (family === undefined)
773
- return undefined;
774
- if (this.db.familyHasFallback(family))
775
- return 'fallback';
776
- if (this.claimed.has(family) || this.pendingClaims.has(family))
777
- return 'held';
778
- const claim = this.db.getClaim(family);
779
- if (claim && claimOwnerLive(claim))
780
- return 'foreign';
781
- // The same rule `claimFamilies` writes by: a dead owner left only settled runs → free.
782
- return this.db.familyHasLive(family) ? 'orphaned' : 'free';
783
- }
784
- /** Why a control on this run must be refused here, or undefined when this store may change it. */
785
- writeRefusal(id) {
786
- const ownership = this.runOwnership(id);
787
- if (ownership === 'quarantined')
788
- return RUN_QUARANTINED;
789
- if (ownership === 'fallback')
790
- return this.fallbackRefusal(id).message;
791
- return ownership === 'foreign' || ownership === 'orphaned' ? RUN_IN_USE_ELSEWHERE : undefined;
792
- }
793
- /**
794
- * Claim an orphaned family before a control, then settle its live rows.
795
- * Stop cancels its target. Return the root id, or undefined for a live owner or missing run.
796
- */
797
- adoptFamily(id, opts = {}) {
798
- const family = this.db?.familyOf(id);
799
- if (family === undefined || !this.claimFamilies([family], { allowLive: true, wait: true }).has(family))
800
- return undefined;
801
- this.holdFamily(family, undefined, true, opts.stop ? id : undefined);
802
- this.exitEvents.writeLoaded();
803
- return family;
804
- }
805
- /** Explicit controls only (`requireRunControl`): copy a fallback family in so it can be written. */
806
- adoptFallbackFamily(id) {
807
- const members = copyFallbackFamily(this.db, id, this.owner);
808
- for (const member of members)
809
- this.coldReads.forget(member);
810
- return members.length > 0;
811
- }
812
- fallbackRefusal(id) { return new RunWriteRefusedError(id, 'fallback', fallbackRunDeleteError(this.dataDir, true)); }
813
- /** Run files are written only for a family this store may write, never a fallback family. */
814
- /** The error `appendEvent` throws for a run this store cannot write or does not know. */
815
- missingRunError(runId) {
816
- const ownership = this.runOwnership(runId);
817
- if (ownership === 'fallback')
818
- return this.fallbackRefusal(runId);
819
- if (ownership === 'foreign' || ownership === 'orphaned' || ownership === 'quarantined')
820
- return new RunWriteRefusedError(runId, ownership);
821
- return new Error(`unknown run: ${runId}`);
822
- }
823
- writeDir(id) { if (this.runOwnership(id) === 'fallback')
824
- throw this.fallbackRefusal(id); return runDataDir(this.dataDir, id); }
825
- /** Every run whose family another process owns (`foreignClaimedRunIds`). */
826
- listForeignClaimedRunIds() { return foreignClaimedRunIds(this.db, this.owner); }
827
- /** Non-terminal rows in the database (both directories) and the runs of families another live store claims. */
828
- persistedLiveRunIds() { return { live: this.db?.listLive().map((row) => row.id) ?? [], foreign: liveForeignClaimedRunIds(this.db, this.owner) }; }
829
488
  /**
830
489
  * Whether a held run anchors itself (and its family) in memory. Anything else held is a family
831
490
  * member or a settled write, and leaves at the next sweep (`evictSettled`).
@@ -870,7 +529,7 @@ export class RunStore {
870
529
  this.base.delete(id);
871
530
  this.coldReads.forget(id);
872
531
  }
873
- this.releaseUnheldClaims();
532
+ this.claims.releaseUnheldClaims();
874
533
  }
875
534
  /** A run read from `runs.db`, normalized like a loaded one (`reconcileLoadedRun`, then the
876
535
  * repository scope) but held by nobody. Undefined when absent, deleted or unreadable. */
@@ -919,7 +578,7 @@ export class RunStore {
919
578
  if (held)
920
579
  return held;
921
580
  const family = this.db && !this.deleted.has(id) ? this.db.familyOf(id) : undefined;
922
- if (family === undefined || !this.claimFamilies([family]).has(family))
581
+ if (family === undefined || !this.claims.claimFamilies([family]).has(family))
923
582
  return undefined;
924
583
  const run = this.coldReads.claimed(id, this.coldBase.get(id), () => this.db?.revisionOf(id)) ?? this.loadCold(id);
925
584
  if (!run)
@@ -973,38 +632,6 @@ export class RunStore {
973
632
  hasRun(id) {
974
633
  return this.held.has(id) || (!!this.db && !this.deleted.has(id) && this.db.has(id));
975
634
  }
976
- /**
977
- * Keep a run in memory for `holder` until `unpin(id, holder)`: a RunManager pins the runs it is
978
- * executing (`active`) and the run a Continue is admitting (`continue`). A finished run is
979
- * loaded. Pins are per holder, so releasing one never releases another. Returns the held record.
980
- */
981
- pin(id, holder) {
982
- const run = this.record(id);
983
- if (!run)
984
- return undefined;
985
- let holders = this.pins.get(id);
986
- if (!holders)
987
- this.pins.set(id, holders = new Set());
988
- holders.add(holder);
989
- return run;
990
- }
991
- /** Publish a run's current record again without a write: something read beside the record
992
- * changed, such as the run leaving the manager's live registries, which a detail's finish
993
- * verdict reads (hearsay-tools/cezarion#1301). */
994
- republish(id) {
995
- const run = this.peek(id);
996
- if (run)
997
- this.published.publish('run.updated', { run, before: snapshotRun(run), source: 'live-release' });
998
- }
999
- /** Release `holder`'s pin. The run leaves memory at the next sweep once nothing else holds it. */
1000
- unpin(id, holder) {
1001
- const holders = this.pins.get(id);
1002
- if (!holders?.delete(holder))
1003
- return;
1004
- if (holders.size === 0)
1005
- this.pins.delete(id);
1006
- this.sweepIfSettled([id]);
1007
- }
1008
635
  /**
1009
636
  * Set discovered repository identity without blocking boot. Recompute conclusions from retained
1010
637
  * evidence, including cold records; null retains unknown-handle behavior.
@@ -1030,7 +657,7 @@ export class RunStore {
1030
657
  }
1031
658
  }
1032
659
  // Only rows this store may write: another process's runs heal when their owner arms its handle.
1033
- const writable = this.claimFamilies(stored.map(rowFamily));
660
+ const writable = this.claims.claimFamilies(stored.map(rowFamily));
1034
661
  for (const row of stored) {
1035
662
  if (!writable.has(rowFamily(row)))
1036
663
  continue;
@@ -1489,7 +1116,7 @@ export class RunStore {
1489
1116
  throw this.openFailure;
1490
1117
  const run = this.buildRun(input, randomUUID());
1491
1118
  // A new family, so nobody else can hold it; claimed before anything (an NDJSON event) is written.
1492
- if (this.db && !this.claimFamilies([run.id]).has(run.id))
1119
+ if (this.db && !this.claims.claimFamilies([run.id]).has(run.id))
1493
1120
  throw new RunWriteRefusedError(run.id, 'foreign');
1494
1121
  this.held.set(run.id, run);
1495
1122
  this.retention.pruneOldRuns();
@@ -1903,11 +1530,11 @@ export class RunStore {
1903
1530
  held.add(family);
1904
1531
  }
1905
1532
  // A run this store holds may move to a new family; any other row is claimed as a plain write.
1906
- const owned = new Set([...this.claimFamilies(held, { allowLive: true }),
1907
- ...this.claimFamilies([...families.values()].filter((family) => !held.has(family)))]);
1533
+ const owned = new Set([...this.claims.claimFamilies(held, { allowLive: true }),
1534
+ ...this.claims.claimFamilies([...families.values()].filter((family) => !held.has(family)))]);
1908
1535
  for (const [id, family] of families) {
1909
1536
  if (!owned.has(family))
1910
- throw this.runOwnership(id) === 'fallback' ? this.fallbackRefusal(id) : new RunWriteRefusedError(id, this.runOwnership(id) === 'orphaned' ? 'orphaned' : 'foreign');
1537
+ throw this.claims.runOwnership(id) === 'fallback' ? this.claims.fallbackRefusal(id) : new RunWriteRefusedError(id, this.claims.runOwnership(id) === 'orphaned' ? 'orphaned' : 'foreign');
1911
1538
  }
1912
1539
  }
1913
1540
  /** The family of a run this store knows: held, else its row; a run nowhere is its own. */
@@ -2043,11 +1670,11 @@ export class RunStore {
2043
1670
  /** Same location `handoffPath()` in handoff.ts produces — inlined to keep
2044
1671
  * the store free of upward imports. */
2045
1672
  handoffPath(runId) {
2046
- return join(this.sourceDataDir(runId), 'runs', `${runId}.handoff.md`);
1673
+ return join(this.claims.sourceDataDir(runId), 'runs', `${runId}.handoff.md`);
2047
1674
  }
2048
1675
  /** Agent screenshots persisted by the run manager (see persistImage). */
2049
1676
  imagesDir(runId) {
2050
- return join(this.sourceDataDir(runId), 'runs', `${runId}-images`);
1677
+ return join(this.claims.sourceDataDir(runId), 'runs', `${runId}-images`);
2051
1678
  }
2052
1679
  /** Save `run` debounced and publish it; `before` is the record at the write's entry (none: created). */
2053
1680
  touch(run, before, exit) {
@@ -2141,7 +1768,7 @@ export class RunStore {
2141
1768
  // that family's claim first; one it cannot take fails the fence below as claim-lost.
2142
1769
  const moved = [...new Set(families.values())].filter((family) => !this.claimed.has(family) && !this.pendingClaims.has(family));
2143
1770
  if (moved.length > 0)
2144
- this.claimFamilies(moved, { allowLive: true });
1771
+ this.claims.claimFamilies(moved, { allowLive: true });
2145
1772
  let commit;
2146
1773
  try {
2147
1774
  commit = this.writeIndex({ upserts, deletes, ...(this.owner ? { fence: this.fence(families) } : {}) });
@@ -2228,7 +1855,7 @@ export class RunStore {
2228
1855
  }
2229
1856
  const decoded = conflict.current ? decodeRunRow(conflict.current.data) : undefined;
2230
1857
  const current = decoded?.run;
2231
- if (this.isFallbackRun(conflict.id))
1858
+ if (this.claims.isFallbackRun(conflict.id))
2232
1859
  this.held.delete(conflict.id);
2233
1860
  const held = this.held.get(conflict.id);
2234
1861
  const before = snapshotRun(held ?? staged.get(conflict.id) ?? undefined);