@hearsay-tools/squawk 0.18.0-pr4074.7790 → 0.18.0-pr4076.7799

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 (75) hide show
  1. package/dist/autosave-removal-slots.d.ts +2 -2
  2. package/dist/autosave-removal-slots.js +2 -2
  3. package/dist/autosave-removal-slots.js.map +1 -1
  4. package/dist/ci-wait/controller.d.ts +46 -46
  5. package/dist/ci-wait/tools.d.ts +4 -4
  6. package/dist/delegation/routes.d.ts +15 -15
  7. package/dist/delegation/service.js +2 -2
  8. package/dist/delegation/service.js.map +1 -1
  9. package/dist/delegation/transport.d.ts +75 -75
  10. package/dist/delegation/worker-cleanup.js +1 -1
  11. package/dist/delegation/worker-cleanup.js.map +1 -1
  12. package/dist/jobs/removal-slot.d.ts +2 -2
  13. package/dist/jobs/removal-slot.js +3 -3
  14. package/dist/jobs/removal-slot.js.map +1 -1
  15. package/dist/runs/agent-tmpdir.d.ts +2 -0
  16. package/dist/runs/agent-tmpdir.js +40 -1
  17. package/dist/runs/agent-tmpdir.js.map +1 -1
  18. package/dist/runs/ports.d.ts +13 -9
  19. package/dist/runs/removal-slots.d.ts +4 -3
  20. package/dist/runs/removal-slots.js.map +1 -1
  21. package/dist/runs/run-retention.d.ts +84 -0
  22. package/dist/runs/run-retention.js +224 -0
  23. package/dist/runs/run-retention.js.map +1 -0
  24. package/dist/runs/run-row.d.ts +11 -0
  25. package/dist/runs/run-row.js +15 -0
  26. package/dist/runs/run-row.js.map +1 -1
  27. package/dist/runs/store.d.ts +6 -46
  28. package/dist/runs/store.js +54 -322
  29. package/dist/runs/store.js.map +1 -1
  30. package/dist/runs/transcript-facts-topic.d.ts +45 -0
  31. package/dist/runs/transcript-facts-topic.js +101 -0
  32. package/dist/runs/transcript-facts-topic.js.map +1 -0
  33. package/dist/server/models-routes.d.ts +13 -13
  34. package/dist/server/project-run-files.js +1 -1
  35. package/dist/server/project-run-files.js.map +1 -1
  36. package/dist/server/provider-sign-in-routes.d.ts +2 -2
  37. package/dist/server/reports-api.d.ts +2 -2
  38. package/dist/server/run-checkout.d.ts +3 -1
  39. package/dist/server/run-checkout.js +3 -3
  40. package/dist/server/run-checkout.js.map +1 -1
  41. package/dist/server/runner-install-routes.d.ts +10 -10
  42. package/dist/server/server.d.ts +1568 -1568
  43. package/dist/server/server.js +1 -1
  44. package/dist/server/server.js.map +1 -1
  45. package/dist/server/workspace-live-routes.d.ts +6 -6
  46. package/dist/workflows/run/continuation-acceptance.js +1 -1
  47. package/dist/workflows/run/continuation-acceptance.js.map +1 -1
  48. package/dist/workflows/run/continuation-session.js +2 -2
  49. package/dist/workflows/run/continuation-session.js.map +1 -1
  50. package/dist/workflows/run/family-reconciler.js +2 -2
  51. package/dist/workflows/run/family-reconciler.js.map +1 -1
  52. package/dist/workflows/run/human-waits.js +4 -4
  53. package/dist/workflows/run/human-waits.js.map +1 -1
  54. package/dist/workflows/run/input-delivery.js +3 -3
  55. package/dist/workflows/run/input-delivery.js.map +1 -1
  56. package/dist/workflows/run/run-finish.js +3 -3
  57. package/dist/workflows/run/run-finish.js.map +1 -1
  58. package/dist/workflows/run/run-recovery.js +6 -6
  59. package/dist/workflows/run/run-recovery.js.map +1 -1
  60. package/dist/workflows/run/run-settlement.js +15 -5
  61. package/dist/workflows/run/run-settlement.js.map +1 -1
  62. package/dist/workflows/run/session-events.js +1 -1
  63. package/dist/workflows/run/session-events.js.map +1 -1
  64. package/dist/workflows/run/turn-nudges.js +2 -2
  65. package/dist/workflows/run/turn-nudges.js.map +1 -1
  66. package/dist/workflows/run/turn-settler.js +1 -1
  67. package/dist/workflows/run/turn-settler.js.map +1 -1
  68. package/dist/workflows/run/worker-questions.js +16 -16
  69. package/dist/workflows/run/worker-questions.js.map +1 -1
  70. package/dist/workflows/run.js +1 -1
  71. package/dist/workflows/run.js.map +1 -1
  72. package/package.json +4 -4
  73. package/scripts/measure-transcript-facts-health.mjs +2 -2
  74. package/scripts/measure-transcript-facts-lag.mjs +1 -1
  75. package/scripts/transcript-facts-fixture.mjs +1 -1
@@ -10,12 +10,12 @@ import { recordedHolders, workerResourceAuthorized } from './worker-resource-hol
10
10
  import { listPeerTaskSummaries, parseStoredSummary } from './run-summary-page.js';
11
11
  export { parseStoredSummary } from './run-summary-page.js';
12
12
  import { defined } from '../core/defined.js';
13
- import { assertRunSlotsSealed, deletionRefusal, runRemovalCleanups } from './removal-slots.js';
14
- import { admissibleExecution, holderRefusal, SPAWN_NEXT, WorkerAdmissionRefusal, workerEvidenceRunIds, workerExecutionSchema } from './worker-execution.js';
15
- import { agentTmpDirMayExist, agentTmpDirOwnershipProven, removeAgentTmpDir } from './agent-tmpdir.js';
13
+ import { deletionRefusal } from './removal-slots.js';
14
+ import { admissibleExecution, holderRefusal, SPAWN_NEXT, WorkerAdmissionRefusal, workerExecutionSchema } from './worker-execution.js';
15
+ import { agentTmpDirMayExist, agentTmpDirOwnershipProven } from './agent-tmpdir.js';
16
16
  import { randomUUID, createHash } from 'node:crypto';
17
17
  import { isDeepStrictEqual } from 'node:util';
18
- import { appendFileSync, closeSync, constants, fstatSync, fsyncSync, lstatSync, openSync, readSync, realpathSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
18
+ import { appendFileSync, closeSync, constants, fstatSync, fsyncSync, lstatSync, openSync, readSync, realpathSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
19
19
  import { join, resolve } from 'node:path';
20
20
  import { z } from 'zod';
21
21
  import { scopeRecordSchema } from '../worker-scope/scope.js';
@@ -28,13 +28,14 @@ import { queuedMessageSchema } from '../contract/index.js';
28
28
  import { previewServerSchema } from '../contract/index.js';
29
29
  import { waitSchema } from '../contract/index.js';
30
30
  import { isUsageLimitHold } from '../contract/index.js';
31
- import { UNREAD_RUN_RULE, SWEEPABLE_RUN_RULE, RETENTION_RUN_RULE, REFERENCED_RUN_RULE } from '../contract/index.js';
31
+ import { UNREAD_RUN_RULE, SWEEPABLE_RUN_RULE, REFERENCED_RUN_RULE } from '../contract/index.js';
32
32
  import { matchesRunSearch, sqlPrefilterTokens } from '../contract/index.js';
33
33
  import { storedDelegationStateSchema } from './delegation-state.js';
34
34
  import { HistoryCompressor } from './history-compressor.js';
35
35
  import { LiveItemSnapshots } from './live-item-snapshots.js';
36
- import { emptyFacts, stampOf, TranscriptFactsIndex } from './transcript-facts.js';
37
- import { hasPlainHistory, historyPaths, readHistoryText, readHistoryTextAsync, removeHistory, restoreHistory } from './history-file.js';
36
+ import { stampOf } from './transcript-facts.js';
37
+ import { RunTranscriptFacts } from './transcript-facts-topic.js';
38
+ import { hasPlainHistory, historyPaths, readHistoryText, readHistoryTextAsync, restoreHistory } from './history-file.js';
38
39
  import { workerExecutionIdentitySchema } from '../delegation/execution-identity.js';
39
40
  import { startToken } from '../core/process-stat.js';
40
41
  import { collectSecretValues, redactDeep } from '../core/secret-redaction.js';
@@ -57,7 +58,8 @@ import { failLoadedInterruptedRun, restoreLoadedUsageLimitHold, settleLoadedStop
57
58
  import { hasLegacyWaitFields, UNREADABLE_WAIT } from './legacy-waits.js';
58
59
  export { ciWaitEntry, holdsWorkerWait, upgradeLegacyWaits, workerWaitEntry } from './legacy-waits.js';
59
60
  import { ExitEvents } from './exit-events.js';
60
- import { encodeRunRow, isLiveRecord, isLiveStatus, materializedWorktreePath } from './run-row.js';
61
+ import { encodeRunRow, familyRootOf, isLiveRecord, isLiveStatus, materializedWorktreePath, newestFirst } from './run-row.js';
62
+ import { RunRetentionTopic } from './run-retention.js';
61
63
  import { collectRawExtras, encodeRawRecord } from './raw-record.js';
62
64
  import { ColdReadCache, storedRow } from './cold-reads.js';
63
65
  import { assertNoLegacyCockpit, assertNoLegacyWriter, backUpLegacyIndex, LEGACY_INDEX_FILE, LegacyWriterError, readLegacyIndex } from './legacy-index.js';
@@ -66,7 +68,6 @@ import { archiveStoreFamily } from './archive-family.js';
66
68
  import { claimStoreFamilies } from './claim-families.js';
67
69
  import { createStoreOwnedRun } from './owned-run-create.js';
68
70
  import { commitStoreWorkerResult } from './worker-result-commit.js';
69
- import { supervisedWorkers } from './supervised.js';
70
71
  import { claimOwnerLive, closeClaimSession, familyKey, foreignClaimedRunIds, liveForeignClaimedRunIds, openClaimSession, rowFamily } from './run-claims.js';
71
72
  import { assertProjectWritable, projectWriteRefused } from '../server/cockpit-ownership.js';
72
73
  /**
@@ -198,10 +199,6 @@ const OPEN_RETRY_DELAYS_MS = [50, 100, 200, 400, 800, 1600];
198
199
  function sleepSync(ms) {
199
200
  Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
200
201
  }
201
- /** Runs (and conversation roots, one family query each) the open-time facts warm-up enumerates
202
- * per event-loop turn (hearsay-tools/cezarion#949), so each slice stays a few milliseconds. */
203
- const WARM_IDS_PER_SLICE = 100;
204
- const MAX_RUNS_KEPT = 300;
205
202
  /** How many archived root runs the run lists carry per project (#864): `GET /run-summaries?archived=recent`
206
203
  * and `GET /workspace/runs-index`. Unarchived runs are never cut; older archived runs page in
207
204
  * through `GET /run-summaries/archived` and the workspace search. */
@@ -372,11 +369,6 @@ function parseEvents(raw) {
372
369
  })
373
370
  .filter((e) => e !== null);
374
371
  }
375
- function newestFirst(a, b) {
376
- if (a.createdAt !== b.createdAt)
377
- return a.createdAt < b.createdAt ? 1 : -1;
378
- return a.seq < b.seq ? -1 : a.seq > b.seq ? 1 : 0;
379
- }
380
372
  /** An archived page's cursor: the last row's order, opaque to clients. A held run with no row yet
381
373
  * lists after every row (`seq` is infinite), which JSON cannot carry, so it travels as null. */
382
374
  function encodeArchivedCursor(key) {
@@ -400,14 +392,6 @@ function decodeArchivedCursor(cursor) {
400
392
  function sortNewestFirst(entries) {
401
393
  return [...entries].sort(([, a], [, b]) => newestFirst(a, b)).map(([item]) => item);
402
394
  }
403
- /** The family a run belongs to, by its root's id. A worker a worker started is filed under the root too. */
404
- function familyRootOf(run) {
405
- if (run.delegation?.role === 'root')
406
- return run.id;
407
- if (run.delegation?.role === 'worker')
408
- return run.delegation.parentRunId;
409
- return undefined;
410
- }
411
395
  /** Tests freeze the copies of cold runs, so an in-place write to one throws instead of vanishing. */
412
396
  function deepFreeze(value) {
413
397
  if (value && typeof value === 'object' && !Object.isFrozen(value)) {
@@ -490,19 +474,46 @@ export class RunStore {
490
474
  unreadable = new Set();
491
475
  /** Background one-at-a-time compressor for archived transcripts (#818). */
492
476
  compressor;
493
- /** Transcript facts the delegation paths ask about, so they never re-read a transcript (#880). */
494
- facts;
477
+ /** What the transcript says about a run (hearsay-tools/squawk#4036). */
478
+ transcriptFacts;
479
+ /** Whether a run may go, and its deletion; the count-based archive (hearsay-tools/squawk#4037). */
480
+ retention;
495
481
  liveItems = new LiveItemSnapshots();
496
- fallbackFacts;
497
- factsFor(id) { return this.isFallbackRun(id) ? this.fallbackFacts ??= new TranscriptFactsIndex(this.sourceDataDir(id), true) : this.facts; }
498
482
  /** Capture both sources on the same synchronous sequence boundary before history IO. */
499
483
  liveReadSnapshot(runId) {
500
484
  return { events: this.liveItems.read(runId), throughSeq: this.seqs.get(runId) ?? Infinity };
501
485
  }
502
486
  constructor(dataDir) {
503
487
  this.dataDir = dataDir;
504
- this.facts = new TranscriptFactsIndex(dataDir);
505
- this.compressor = new HistoryCompressor(dataDir, (id) => this.isHistoryCompressEligible(id), (id, plain, archive) => this.facts.adoptArchive(id, plain, stampOf(archive)));
488
+ this.transcriptFacts = new RunTranscriptFacts(dataDir, {
489
+ isFallbackRun: (id) => this.isFallbackRun(id),
490
+ sourceDataDir: (id) => this.sourceDataDir(id),
491
+ isOpen: () => this.db !== null,
492
+ held: this.held,
493
+ listFamilyRunIds: (rootId) => this.listFamilyRunIds(rootId),
494
+ listConversationRootIds: () => this.listConversationRootIds(),
495
+ listRunIds: () => this.listRunIds(),
496
+ });
497
+ this.retention = new RunRetentionTopic(dataDir, {
498
+ db: () => this.db, held: this.held, deleted: this.deleted, quarantined: this.quarantined,
499
+ historyOwed: this.historyOwed, seqs: this.seqs, published: this.published, transcriptFacts: this.transcriptFacts,
500
+ peek: (id) => this.peek(id), hasRun: (id) => this.hasRun(id), record: (id) => this.record(id),
501
+ listWorkersOf: (parentId) => this.listWorkersOf(parentId), isFallbackRun: (id) => this.isFallbackRun(id),
502
+ hasFallbackRun: (id) => this.hasFallbackRun(id), listOrder: (run) => this.listOrder(run),
503
+ claimFamilies: (families) => this.claimFamilies(families), markDeleted: (id, family) => this.markDeleted(id, family),
504
+ scheduleSave: () => this.scheduleSave(), commitIndex: (input) => this.commitIndex(input),
505
+ commitDelegation: (patches) => this.commitDelegation(patches), applyArchived: (run, archived) => this.applyArchived(run, archived),
506
+ workerDeletionEvidence: (id) => this.workerDeletionEvidence(id),
507
+ readWorkerResult: (parentId, workerId) => this.readWorkerResult(parentId, workerId),
508
+ readWorkerResultDiff: (parentId, workerId) => this.readWorkerResultDiff(parentId, workerId),
509
+ readDeletedWorkerResult: (parentId, workerId) => this.readDeletedWorkerResult(parentId, workerId),
510
+ commitWorkerResult: (parentId, value, diffSnapshot) => this.commitWorkerResult(parentId, value, diffSnapshot),
511
+ readWorkerExecution: (id) => this.readWorkerExecution(id), identityPath: (id) => this.identityPath(id),
512
+ processesPath: (id) => this.processesPath(id), scopePath: (id) => this.scopePath(id),
513
+ executionPath: (id) => this.executionPath(id), handoffPath: (runId) => this.handoffPath(runId),
514
+ imagesDir: (runId) => this.imagesDir(runId),
515
+ });
516
+ this.compressor = new HistoryCompressor(dataDir, (id) => this.isHistoryCompressEligible(id), (id, plain, archive) => this.transcriptFacts.index.adoptArchive(id, plain, stampOf(archive)));
506
517
  }
507
518
  /**
508
519
  * Open the project's run store. See `reconcileLoadedRun` for what `keepLive` (#367) decides
@@ -558,7 +569,7 @@ export class RunStore {
558
569
  store.owner = openClaimSession();
559
570
  if (!maintenance) {
560
571
  store.loadHeldRows();
561
- store.warmTranscriptFacts();
572
+ store.transcriptFacts.warmTranscriptFacts();
562
573
  store.exitEvents.writeLoaded();
563
574
  }
564
575
  }
@@ -600,7 +611,6 @@ export class RunStore {
600
611
  sourceDataDir(id) { return this.isFallbackRun(id) ? dataReadDirs(this.dataDir)[1] : runDataDir(this.dataDir, id); }
601
612
  isFallbackRun(id) { return this.db?.isFallback(id) ?? false; }
602
613
  hasFallbackRun(id) { return this.db?.hasFallback(id) ?? false; }
603
- fallbackDeleteError(id, kind = 'record') { return fallbackRunDeleteError(this.dataDir, kind === 'record' ? this.hasFallbackRun(id) : this.isFallbackRun(id), this.peek(id)?.worktreePath); }
604
614
  /**
605
615
  * Open-time load: the live rows, the finished rows a load normalization repairs, then the
606
616
  * delegation families of the live ones. A row that does not parse is skipped and left in the
@@ -1466,7 +1476,7 @@ export class RunStore {
1466
1476
  if (this.db && !this.claimFamilies([run.id]).has(run.id))
1467
1477
  throw new RunWriteRefusedError(run.id, 'foreign');
1468
1478
  this.held.set(run.id, run);
1469
- this.pruneOldRuns();
1479
+ this.retention.pruneOldRuns();
1470
1480
  this.touch(run, undefined);
1471
1481
  return run;
1472
1482
  }
@@ -1780,7 +1790,7 @@ export class RunStore {
1780
1790
  throw new Error('missing worker continuation target');
1781
1791
  const delegation = delegationStateSchema.parse({ ...run.delegation,
1782
1792
  executionRevision: (run.delegation.executionRevision ?? 0) + 1,
1783
- executionStartSeq: this.transcriptFacts(id).lastSeq,
1793
+ executionStartSeq: this.transcriptFacts.transcriptFacts(id).lastSeq,
1784
1794
  });
1785
1795
  const staged = new Map();
1786
1796
  this.exitEvents.started(id);
@@ -1918,7 +1928,7 @@ export class RunStore {
1918
1928
  completionArchiveBlocker(root) {
1919
1929
  const family = [root, ...this.listWorkersOf(root.id)];
1920
1930
  for (const run of family) {
1921
- const facts = this.factsFor(run.id).peek(run.id);
1931
+ const facts = this.transcriptFacts.factsFor(run.id).peek(run.id);
1922
1932
  if (!facts || !['done', 'review', 'failed', 'cancelled'].includes(run.status) || run.waits?.some(wait => wait.phase === 'open') ||
1923
1933
  run.hasPendingPermission || facts.pendingAsk !== undefined)
1924
1934
  return 'Task or worker work still needs attention. Open the task or archive manually.';
@@ -2125,7 +2135,7 @@ export class RunStore {
2125
2135
  decodeRunRow,
2126
2136
  decodeCold: (row) => this.decodeCold(row),
2127
2137
  writeRefusal: (memberId) => this.writeRefusal(memberId),
2128
- factsPeek: (memberId) => this.factsFor(memberId).peek(memberId),
2138
+ factsPeek: (memberId) => this.transcriptFacts.factsFor(memberId).peek(memberId),
2129
2139
  readWorkerExecution: (memberId) => this.readWorkerExecution(memberId),
2130
2140
  }, id, isActive);
2131
2141
  }
@@ -2154,7 +2164,7 @@ export class RunStore {
2154
2164
  if (ids.length > 1025)
2155
2165
  return;
2156
2166
  for (const memberId of ids)
2157
- await this.factsFor(memberId).ready(memberId);
2167
+ await this.transcriptFacts.factsFor(memberId).ready(memberId);
2158
2168
  }
2159
2169
  archiveOnMergeSnapshot(id, repoBase, isActive = () => false) {
2160
2170
  const family = this.archiveFamily(id, isActive);
@@ -2434,7 +2444,7 @@ export class RunStore {
2434
2444
  restoreHistory(this.dataDir, runId);
2435
2445
  const line = `${JSON.stringify(full)}\n`;
2436
2446
  appendFileSync(this.eventsPath(runId), line, 'utf8');
2437
- this.facts.append(runId, full, Buffer.byteLength(line));
2447
+ this.transcriptFacts.index.append(runId, full, Buffer.byteLength(line));
2438
2448
  this.maybeEnqueueHistoryCompress(run);
2439
2449
  this.liveItems.observe(runId, full, false);
2440
2450
  this.published.publish('run.event', { runId, event: full });
@@ -2554,20 +2564,9 @@ export class RunStore {
2554
2564
  this.secretValues = collectSecretValues();
2555
2565
  return this.secretValues;
2556
2566
  }
2557
- /** The run's indexed transcript facts (#880): a read-only view, never a transcript read once
2558
- * the run's index is loaded. An unreadable transcript answers as empty, as readEvents does. */
2559
- transcriptFacts(runId) {
2560
- return this.factsFor(runId).get(runId) ?? emptyFacts();
2561
- }
2562
- /** The run's transcript facts when they are known: undefined when the transcript exists but its
2563
- * facts are not current or cannot be read, so a caller can tell "no ask" from "no evidence". */
2564
- knownTranscriptFacts(runId) {
2565
- return this.factsFor(runId).peek(runId);
2566
- }
2567
2567
  hasProjection(runId, projectionId) {
2568
- return this.transcriptFacts(runId).projectionIds.includes(projectionId);
2568
+ return this.transcriptFacts.transcriptFacts(runId).projectionIds.includes(projectionId);
2569
2569
  }
2570
- factsWarming = Promise.resolve();
2571
2570
  /** Indexed family enumeration, including members not yet flushed to SQLite. */
2572
2571
  listFamilyRunIds(rootId) {
2573
2572
  const ids = new Set([rootId, ...(this.db?.listIdsByParent(rootId) ?? [])]);
@@ -2581,73 +2580,6 @@ export class RunStore {
2581
2580
  ids.delete(id);
2582
2581
  return [...ids];
2583
2582
  }
2584
- recoveryFactIds(familyRootId) {
2585
- if (familyRootId !== undefined)
2586
- return this.listFamilyRunIds(familyRootId);
2587
- const ids = new Set();
2588
- for (const [id, run] of this.held) {
2589
- if (!isLiveRecord(run))
2590
- continue;
2591
- const root = familyRootOf(run);
2592
- for (const member of root === undefined ? [id] : this.listFamilyRunIds(root))
2593
- ids.add(member);
2594
- }
2595
- return [...ids];
2596
- }
2597
- /** Readiness owns no run snapshot across an await: refresh only the currently held owner. */
2598
- async prepareTranscriptFacts(runIds) {
2599
- for (const id of new Set(runIds)) {
2600
- // Exact sidecars resolve immediately too: recovery must yield to timers/I/O between IDs.
2601
- await new Promise(resolve => setImmediate(resolve));
2602
- await this.factsFor(id).ready(id);
2603
- }
2604
- }
2605
- prepareRecoveryFacts(familyRootId) {
2606
- return this.prepareTranscriptFacts(this.recoveryFactIds(familyRootId));
2607
- }
2608
- /** Register IDs only here; the index yields between cache reads and off-loop rebuilds. */
2609
- warmTranscriptFacts() {
2610
- this.factsWarming = Promise.resolve().then(async () => {
2611
- if (!this.db)
2612
- return;
2613
- const ids = new Set(this.recoveryFactIds());
2614
- // hearsay-tools/cezarion#949: this microtask ends open()'s synchronous slice, and on a
2615
- // large history the JSON scan for conversation roots plus one family query per root cost
2616
- // as much again. Past one slice's worth of runs, yield before the scan and between root
2617
- // batches; a small store (every unit test) still registers in this one microtask.
2618
- const large = this.listRunIds().length > WARM_IDS_PER_SLICE;
2619
- const turn = async () => {
2620
- await new Promise(resolve => setImmediate(resolve));
2621
- return this.db !== null;
2622
- };
2623
- if (large && !await turn())
2624
- return;
2625
- const roots = this.listConversationRootIds();
2626
- for (let i = 0; i < roots.length; i++) {
2627
- if (large && i > 0 && i % WARM_IDS_PER_SLICE === 0 && !await turn())
2628
- return;
2629
- for (const id of this.listFamilyRunIds(roots[i]))
2630
- ids.add(id);
2631
- }
2632
- if (large && !await turn())
2633
- return;
2634
- // Re-list after the yields: a run deleted meanwhile must not be registered again.
2635
- const present = this.listRunIds();
2636
- if (large) {
2637
- const live = new Set(present);
2638
- for (const id of ids)
2639
- if (!live.has(id))
2640
- ids.delete(id);
2641
- }
2642
- for (const id of present)
2643
- ids.add(id);
2644
- await this.facts.warm(ids);
2645
- }).catch(() => undefined);
2646
- }
2647
- /** Resolves when the open-time warm-up is done (tests). */
2648
- factsWarmIdle() {
2649
- return this.factsWarming;
2650
- }
2651
2583
  /** `readEvents` off the event loop (async read and async brotli), for collection paths. */
2652
2584
  async readEventsAsync(runId) {
2653
2585
  try {
@@ -2906,134 +2838,6 @@ export class RunStore {
2906
2838
  scratchMayExist: () => agentTmpDirMayExist(this.dataDir, id), executionExists: () => existsSync(this.executionPath(id)),
2907
2839
  });
2908
2840
  }
2909
- canDeleteRun(id, kind = 'record') {
2910
- if (this.fallbackDeleteError(id, kind))
2911
- return false;
2912
- if (deletionRefusal(id, kind === 'record' ? 'history' : 'worktree', this.dataDir))
2913
- return false;
2914
- const run = this.peek(id);
2915
- if (run?.delegation?.role === 'invalid')
2916
- return false;
2917
- if (run?.delegation?.role === 'worker')
2918
- return supervisedWorkers(this, run).length === 0 && this.workerDeletionEvidence(id);
2919
- const privateWorkers = workerEvidenceRunIds(this.dataDir);
2920
- if (!privateWorkers || privateWorkers.includes(id))
2921
- return false;
2922
- if (run?.delegation?.role === 'root') {
2923
- if (run.delegation.finishRequestedAt && ['queued', 'running', 'waiting'].includes(run.status))
2924
- return false;
2925
- // Keep the parent's receipt and result ownership until each child history is explicitly removed.
2926
- if (this.listWorkersOf(id).length > 0)
2927
- return false;
2928
- return run.delegation.receipts.every(receipt => {
2929
- if (this.hasRun(receipt.workerId) || receipt.deletion?.phase !== 'complete')
2930
- return false;
2931
- // A pending parent deletion already validated the results before removing their bytes.
2932
- if (run.delegation?.role === 'root' && run.delegation.historyDeletion === 'pending')
2933
- return true;
2934
- return this.readDeletedWorkerResult(id, receipt.workerId) !== undefined;
2935
- });
2936
- }
2937
- return this.listWorkersOf(id).length === 0;
2938
- }
2939
- /** Delegated history deletion is synchronous and checkpointed; any failed byte/index removal remains retryable. */
2940
- deleteDelegatedRun(id) {
2941
- const run = this.peek(id);
2942
- try {
2943
- if (run.delegation?.role === 'worker') {
2944
- const parent = this.peek(run.delegation.parentRunId);
2945
- if (parent.delegation?.role !== 'root')
2946
- return false;
2947
- const receipt = parent.delegation.receipts.find(entry => entry.workerId === id);
2948
- const result = this.readWorkerResult(parent.id, id);
2949
- const deletion = receipt.deletion ?? { phase: 'pending', revision: result.revision,
2950
- resourceId: run.delegation.workspace.resourceId, generation: this.readWorkerExecution(id).generation };
2951
- this.commitDelegation([{ id: parent.id, delegation: { ...parent.delegation,
2952
- receipts: parent.delegation.receipts.map(entry => entry.workerId === id ? { ...entry, deletion } : entry),
2953
- } }]);
2954
- // Do not advertise artifact bytes as retained while interrupted deletion is in progress.
2955
- this.commitWorkerResult(parent.id, { ...result, observedAt: new Date().toISOString(),
2956
- diff: result.diff.state === 'available' ? { ...result.diff, snapshotId: randomUUID() } : result.diff,
2957
- artifacts: result.artifacts.state === 'available' ? { ...result.artifacts,
2958
- items: result.artifacts.items.map(item => ({ state: 'unavailable', reason: 'unreadable',
2959
- detail: 'History deletion is in progress', id: item.id, path: item.path })),
2960
- } : result.artifacts,
2961
- }, this.readWorkerResultDiff(parent.id, id));
2962
- this.removeRunHistoryBytes(id);
2963
- // Delete scratch while its generation evidence still exists; failed removal keeps it.
2964
- removeAgentTmpDir(this.dataDir, id);
2965
- if (agentTmpDirMayExist(this.dataDir, id))
2966
- return false;
2967
- // Private process/account evidence is now replaced by the exact parent receipt.
2968
- rmSync(this.identityPath(id), { force: true });
2969
- rmSync(this.processesPath(id), { force: true });
2970
- rmSync(this.scopePath(id), { force: true });
2971
- rmSync(this.executionPath(id), { force: true });
2972
- const retained = this.readWorkerResult(parent.id, id);
2973
- this.commitWorkerResult(parent.id, { ...retained, observedAt: new Date().toISOString(),
2974
- diff: retained.diff.state === 'available' ? { ...retained.diff, snapshotId: randomUUID() } : retained.diff,
2975
- artifacts: retained.artifacts.state === 'available' ? { ...retained.artifacts,
2976
- items: retained.artifacts.items.map(item => ({ state: 'deleted', reason: 'missing', id: item.id, path: item.path })),
2977
- } : retained.artifacts,
2978
- }, this.readWorkerResultDiff(parent.id, id));
2979
- this.commitIndex(new Map([[parent.id, { ...parent, delegation: { ...parent.delegation,
2980
- receipts: parent.delegation.receipts.map(entry => entry.workerId === id ? { ...entry, deletion: { ...deletion, phase: 'complete' } } : entry),
2981
- } }], [id, null]]));
2982
- }
2983
- else if (run.delegation?.role === 'root') {
2984
- this.commitDelegation([{ id, delegation: { ...run.delegation, historyDeletion: 'pending' } }]);
2985
- this.removeRunHistoryBytes(id);
2986
- rmSync(join(runDataDir(this.dataDir, id), 'runs', `${id}-worker-results`), { recursive: true, force: true });
2987
- this.commitIndex(new Map([[id, null]]));
2988
- }
2989
- else
2990
- return false;
2991
- removeAgentTmpDir(this.dataDir, id);
2992
- this.seqs.delete(id);
2993
- return true;
2994
- }
2995
- catch {
2996
- return false;
2997
- }
2998
- }
2999
- removeRunHistoryBytes(id) {
3000
- // Fixed owned paths only: never follow context descriptors supplied in persisted metadata.
3001
- z.uuid().parse(id);
3002
- const dir = join(runDataDir(this.dataDir, id), 'runs');
3003
- if (realpathSync(dir) !== resolve(dir))
3004
- throw new Error('History storage redirected');
3005
- this.removeHistoryFiles(id);
3006
- }
3007
- /** The run's history, handoff and images, then the removal cleanups (`runs/removal-slots.ts`). */
3008
- removeHistoryFiles(id) {
3009
- this.facts.forget(id);
3010
- removeHistory(this.dataDir, id);
3011
- rmSync(this.handoffPath(id), { force: true });
3012
- rmSync(this.imagesDir(id), { recursive: true, force: true });
3013
- runRemovalCleanups(id, this.dataDir);
3014
- }
3015
- deleteRun(id) {
3016
- const refusal = this.fallbackDeleteError(id);
3017
- if (refusal)
3018
- throw new Error(refusal);
3019
- if (!this.canDeleteRun(id))
3020
- return false;
3021
- const run = this.peek(id);
3022
- if (run && this.db && (this.quarantined.has(id) || !this.claimFamilies([familyKey(run)]).size))
3023
- return false;
3024
- if (run?.delegation?.role === 'worker' || run?.delegation?.role === 'root')
3025
- return this.deleteDelegatedRun(id);
3026
- const existed = run !== undefined;
3027
- this.held.delete(id);
3028
- if (existed) {
3029
- this.markDeleted(id, familyKey(run));
3030
- removeAgentTmpDir(this.dataDir, id);
3031
- this.seqs.delete(id);
3032
- this.scheduleSave();
3033
- this.published.publish('run.deleted', { runId: id });
3034
- }
3035
- return existed;
3036
- }
3037
2841
  /** Write the pending rows out now (used on shutdown). */
3038
2842
  flush() {
3039
2843
  if (this.saveTimer) {
@@ -3055,7 +2859,7 @@ export class RunStore {
3055
2859
  * resumed event, even across a reload (the frozen-transcript symptom class
3056
2860
  * of #424). One file read on the first post-restart append per run. */
3057
2861
  rehydrateSeq(runId) {
3058
- return this.transcriptFacts(runId).lastSeq;
2862
+ return this.transcriptFacts.transcriptFacts(runId).lastSeq;
3059
2863
  }
3060
2864
  eventsPath(runId) {
3061
2865
  return historyPaths(this.sourceDataDir(runId), runId).plain;
@@ -3095,76 +2899,6 @@ export class RunStore {
3095
2899
  this.deletedFamilies.set(id, family);
3096
2900
  this.historyOwed.add(id);
3097
2901
  }
3098
- /** A deleted run's history files and removal cleanups, once the delete of its row has committed.
3099
- * Best effort: a failure is logged, and the row stays deleted. */
3100
- removeOwedHistory(id) {
3101
- if (!this.historyOwed.delete(id))
3102
- return;
3103
- try {
3104
- this.removeHistoryFiles(id);
3105
- }
3106
- catch (error) {
3107
- console.warn(`[hsq] History cleanup of run ${id} is incomplete: ${error instanceof Error ? error.message : String(error)}`);
3108
- }
3109
- }
3110
- /**
3111
- * Count-based history retention: of the runs past the newest `MAX_RUNS_KEPT` unarchived ones,
3112
- * archive each settled task that is not pinned and whose family this store can claim, together
3113
- * with its workers, once no member of the family is live (hearsay-tools/squawk#777). Ranked over the row keys (the `created_at` index, no record decoded) with memory
3114
- * laid over them, since a run created or archived since the last save has no row yet; the rows
3115
- * past the cut are then filtered in `runs.db`, so only real candidates decode. Archived runs
3116
- * are never deleted by retention — only an explicit delete, worker destruction, or history
3117
- * deletion removes a run.
3118
- */
3119
- pruneOldRuns() {
3120
- const ranked = new Map();
3121
- for (const key of this.db?.listKeysWhere('archived = ?', [0]) ?? []) {
3122
- if (!this.held.has(key.id) && !this.deleted.has(key.id))
3123
- ranked.set(key.id, key);
3124
- }
3125
- for (const run of this.held.values())
3126
- if (!run.archived)
3127
- ranked.set(run.id, { id: run.id, ...this.listOrder(run) });
3128
- const overflow = [...ranked.values()].sort(newestFirst).slice(MAX_RUNS_KEPT).map((key) => key.id);
3129
- if (overflow.length === 0)
3130
- return;
3131
- const stale = overflow.flatMap((id) => {
3132
- const run = this.held.get(id);
3133
- // Retention must not archive a live task between turns, a pinned run, or a worker on its own.
3134
- return run && !this.hasFallbackRun(id) && RETENTION_RUN_RULE.matches(run) ? [id] : [];
3135
- });
3136
- const skipped = overflow.filter(id => this.hasFallbackRun(id)).length;
3137
- if (skipped)
3138
- console.info(`[hsq] Retention skipped ${skipped} read-only fallback run(s) under ${dataReadDirs(this.dataDir)[1]}.`);
3139
- const cold = overflow.filter((id) => !this.held.has(id) && !this.hasFallbackRun(id));
3140
- if (cold.length > 0) {
3141
- // Another process's runs are its own to keep or archive (#779, plan step 3).
3142
- const rows = this.db.listWhere(guardedJsonSql(RETENTION_RUN_RULE.sql, 0), [JSON.stringify(cold)]);
3143
- const writable = this.claimFamilies(rows.map(rowFamily));
3144
- for (const row of rows)
3145
- if (writable.has(rowFamily(row)))
3146
- stale.push(row.id);
3147
- }
3148
- for (const id of stale) {
3149
- const run = this.record(id);
3150
- if (!run || run.archived || !RETENTION_RUN_RULE.matches(run))
3151
- continue;
3152
- this.archiveSettledFamily(run);
3153
- }
3154
- }
3155
- /** Archive a root with its workers unless a member is live, mid-destroy or pinned, or a history
3156
- * deletion is under way. Each member is marked dirty: the next save writes the family at once. */
3157
- archiveSettledFamily(root) {
3158
- assertRunSlotsSealed();
3159
- const workers = this.listWorkersOf(root.id), family = [root, ...workers];
3160
- if (family.some((run) => isLiveRecord(run) || run.pinned) || (root.delegation?.role === 'root' && root.delegation.historyDeletion))
3161
- return;
3162
- for (const member of [root, ...workers.flatMap((worker) => this.record(worker.id) ?? [])].filter((run) => !run.archived)) {
3163
- this.applyArchived(member, true);
3164
- if (!deletionRefusal(member.id, 'archive-tmp', this.dataDir))
3165
- removeAgentTmpDir(this.dataDir, member.id);
3166
- }
3167
- }
3168
2902
  /** Debounced so token-usage updates don't rewrite a row per event. Nothing to schedule without
3169
2903
  * a database: a `RunStore.unavailable` store, or a closed one, writes nothing. */
3170
2904
  scheduleSave() {
@@ -3258,7 +2992,7 @@ export class RunStore {
3258
2992
  this.liveItems.forget(id);
3259
2993
  this.base.delete(id);
3260
2994
  this.deletedFamilies.delete(id);
3261
- this.removeOwedHistory(id);
2995
+ this.retention.removeOwedHistory(id);
3262
2996
  }
3263
2997
  this.dirty.clear();
3264
2998
  this.deleted.clear();
@@ -3382,9 +3116,7 @@ export class RunStore {
3382
3116
  // Demand-bound feeds stop before storage disappears during project removal/shutdown.
3383
3117
  this.published.publish('store.closed', {});
3384
3118
  this.compressor.stop();
3385
- this.fallbackFacts?.stop();
3386
- this.facts.stop();
3387
- this.facts.flush();
3119
+ this.transcriptFacts.stop();
3388
3120
  if (this.saveTimer) {
3389
3121
  clearTimeout(this.saveTimer);
3390
3122
  this.saveTimer = null;