@hearsay-tools/squawk 0.18.0-dev.7796 → 0.18.0-dev.7804

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 (53) 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/delegation/removal-slot.js +1 -1
  5. package/dist/delegation/removal-slot.js.map +1 -1
  6. package/dist/delegation/results.js +4 -4
  7. package/dist/delegation/results.js.map +1 -1
  8. package/dist/delegation/routes.d.ts +11 -11
  9. package/dist/delegation/service.js +8 -8
  10. package/dist/delegation/service.js.map +1 -1
  11. package/dist/delegation/transport.d.ts +15 -15
  12. package/dist/delegation/worker-cleanup.js +3 -3
  13. package/dist/delegation/worker-cleanup.js.map +1 -1
  14. package/dist/jobs/removal-slot.d.ts +2 -2
  15. package/dist/jobs/removal-slot.js +3 -3
  16. package/dist/jobs/removal-slot.js.map +1 -1
  17. package/dist/runs/agent-tmpdir.d.ts +2 -0
  18. package/dist/runs/agent-tmpdir.js +40 -1
  19. package/dist/runs/agent-tmpdir.js.map +1 -1
  20. package/dist/runs/ports.d.ts +16 -10
  21. package/dist/runs/removal-slots.d.ts +8 -5
  22. package/dist/runs/removal-slots.js.map +1 -1
  23. package/dist/runs/retention.d.ts +4 -2
  24. package/dist/runs/retention.js.map +1 -1
  25. package/dist/runs/run-retention.d.ts +81 -0
  26. package/dist/runs/run-retention.js +224 -0
  27. package/dist/runs/run-retention.js.map +1 -0
  28. package/dist/runs/run-row.d.ts +9 -0
  29. package/dist/runs/run-row.js +7 -0
  30. package/dist/runs/run-row.js.map +1 -1
  31. package/dist/runs/store.d.ts +7 -38
  32. package/dist/runs/store.js +41 -290
  33. package/dist/runs/store.js.map +1 -1
  34. package/dist/runs/worker-result-commit.js +1 -1
  35. package/dist/runs/worker-results.d.ts +38 -0
  36. package/dist/runs/worker-results.js +87 -0
  37. package/dist/runs/worker-results.js.map +1 -0
  38. package/dist/server/live-routes.d.ts +6 -6
  39. package/dist/server/project-run-files.js +1 -1
  40. package/dist/server/project-run-files.js.map +1 -1
  41. package/dist/server/run-checkout.d.ts +3 -1
  42. package/dist/server/run-checkout.js +3 -3
  43. package/dist/server/run-checkout.js.map +1 -1
  44. package/dist/server/server.d.ts +6 -6
  45. package/dist/server/server.js +1 -1
  46. package/dist/server/server.js.map +1 -1
  47. package/dist/workflows/run/completion-gate.js +1 -1
  48. package/dist/workflows/run/completion-gate.js.map +1 -1
  49. package/dist/workflows/run/family-reconciler.js +1 -1
  50. package/dist/workflows/run/family-reconciler.js.map +1 -1
  51. package/dist/workflows/run/run-settlement.js +12 -2
  52. package/dist/workflows/run/run-settlement.js.map +1 -1
  53. package/package.json +4 -4
@@ -1,6 +1,6 @@
1
- import { legacyIndexRows, readableSavedRunner, upgradeLegacyRunRow, upgradeRemovedRunnerResult, withKeptFields } from './legacy-run-rows.js';
1
+ import { legacyIndexRows, readableSavedRunner, upgradeLegacyRunRow, withKeptFields } from './legacy-run-rows.js';
2
2
  import { dataReadDirs, runDataDir } from '../project-paths.js';
3
- import { addRunSource, copyFallbackFamily, fallbackRunSource, bindWorkerResultPath, fallbackRunDeleteError, workerResultsDirectory } from './project-run-sources.js';
3
+ import { addRunSource, copyFallbackFamily, fallbackRunSource, fallbackRunDeleteError } from './project-run-sources.js';
4
4
  import { productEnv } from '../core/product-env.js';
5
5
  import { registeredWaitRecord, registeredReceiptRecord } from './wait-registration-write.js';
6
6
  import { stageCommit, stageLoaded, stageDurableUpdate, stageDebouncedUpdate, stageConversation, stageArchiveFields, stagePullRequests, stageStepUpdate, stepTotals, redactPatch, redactText, clearPin } from './record-write-rules.js';
@@ -10,32 +10,32 @@ 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, 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';
22
22
  import { WorkerScopes } from '../worker-scope/worker-scopes.js';
23
23
  import { readPrivateRecord, writePrivateRecord } from './private-record-file.js';
24
- import { delegationStateSchema, workerResultFileSchema, workerDestroyRetrySchema, } from '../contract/index.js';
24
+ import { delegationStateSchema, workerDestroyRetrySchema, } from '../contract/index.js';
25
25
  import { agentInputSchema, inboxClaimSchema } from '../contract/index.js';
26
26
  import { automationIdOf, stepStateSchema as contractStepStateSchema, toRunSummary, runRecordSchema as contractRunRecordSchema, runPullRequestSchema, mergedPullRequestSchema, } from '../contract/index.js';
27
27
  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
36
  import { stampOf } from './transcript-facts.js';
37
37
  import { RunTranscriptFacts } from './transcript-facts-topic.js';
38
- import { hasPlainHistory, historyPaths, readHistoryText, readHistoryTextAsync, removeHistory, restoreHistory } from './history-file.js';
38
+ import { hasPlainHistory, historyPaths, readHistoryText, readHistoryTextAsync, restoreHistory } from './history-file.js';
39
39
  import { workerExecutionIdentitySchema } from '../delegation/execution-identity.js';
40
40
  import { startToken } from '../core/process-stat.js';
41
41
  import { collectSecretValues, redactDeep } from '../core/secret-redaction.js';
@@ -58,7 +58,8 @@ import { failLoadedInterruptedRun, restoreLoadedUsageLimitHold, settleLoadedStop
58
58
  import { hasLegacyWaitFields, UNREADABLE_WAIT } from './legacy-waits.js';
59
59
  export { ciWaitEntry, holdsWorkerWait, upgradeLegacyWaits, workerWaitEntry } from './legacy-waits.js';
60
60
  import { ExitEvents } from './exit-events.js';
61
- import { encodeRunRow, familyRootOf, 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';
62
63
  import { collectRawExtras, encodeRawRecord } from './raw-record.js';
63
64
  import { ColdReadCache, storedRow } from './cold-reads.js';
64
65
  import { assertNoLegacyCockpit, assertNoLegacyWriter, backUpLegacyIndex, LEGACY_INDEX_FILE, LegacyWriterError, readLegacyIndex } from './legacy-index.js';
@@ -66,8 +67,7 @@ import { toRunStoreOpenError } from './store-open-error.js';
66
67
  import { archiveStoreFamily } from './archive-family.js';
67
68
  import { claimStoreFamilies } from './claim-families.js';
68
69
  import { createStoreOwnedRun } from './owned-run-create.js';
69
- import { commitStoreWorkerResult } from './worker-result-commit.js';
70
- import { supervisedWorkers } from './supervised.js';
70
+ import { WorkerResultsTopic } from './worker-results.js';
71
71
  import { claimOwnerLive, closeClaimSession, familyKey, foreignClaimedRunIds, liveForeignClaimedRunIds, openClaimSession, rowFamily } from './run-claims.js';
72
72
  import { assertProjectWritable, projectWriteRefused } from '../server/cockpit-ownership.js';
73
73
  /**
@@ -199,7 +199,6 @@ const OPEN_RETRY_DELAYS_MS = [50, 100, 200, 400, 800, 1600];
199
199
  function sleepSync(ms) {
200
200
  Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
201
201
  }
202
- const MAX_RUNS_KEPT = 300;
203
202
  /** How many archived root runs the run lists carry per project (#864): `GET /run-summaries?archived=recent`
204
203
  * and `GET /workspace/runs-index`. Unarchived runs are never cut; older archived runs page in
205
204
  * through `GET /run-summaries/archived` and the workspace search. */
@@ -370,11 +369,6 @@ function parseEvents(raw) {
370
369
  })
371
370
  .filter((e) => e !== null);
372
371
  }
373
- function newestFirst(a, b) {
374
- if (a.createdAt !== b.createdAt)
375
- return a.createdAt < b.createdAt ? 1 : -1;
376
- return a.seq < b.seq ? -1 : a.seq > b.seq ? 1 : 0;
377
- }
378
372
  /** An archived page's cursor: the last row's order, opaque to clients. A held run with no row yet
379
373
  * lists after every row (`seq` is infinite), which JSON cannot carry, so it travels as null. */
380
374
  function encodeArchivedCursor(key) {
@@ -482,6 +476,10 @@ export class RunStore {
482
476
  compressor;
483
477
  /** What the transcript says about a run (hearsay-tools/squawk#4036). */
484
478
  transcriptFacts;
479
+ /** Whether a run may go, and its deletion; the count-based archive (hearsay-tools/squawk#4037). */
480
+ retention;
481
+ /** The saved snapshot of a worker's collected result (hearsay-tools/squawk#4038). */
482
+ workerResults;
485
483
  liveItems = new LiveItemSnapshots();
486
484
  /** Capture both sources on the same synchronous sequence boundary before history IO. */
487
485
  liveReadSnapshot(runId) {
@@ -498,6 +496,28 @@ export class RunStore {
498
496
  listConversationRootIds: () => this.listConversationRootIds(),
499
497
  listRunIds: () => this.listRunIds(),
500
498
  });
499
+ this.workerResults = new WorkerResultsTopic(dataDir, {
500
+ peek: (id) => this.peek(id), hasRun: (id) => this.hasRun(id), hasFallbackRun: (id) => this.hasFallbackRun(id),
501
+ writeDir: (id) => this.writeDir(id), sourceDataDir: (id) => this.sourceDataDir(id),
502
+ redactResult: (result) => this.redact({ type: 'worker-result', seq: 0, ts: result.observedAt, result }).result,
503
+ redactText: (text) => this.redactText(text), commitDelegation: (patches) => this.commitDelegation(patches),
504
+ });
505
+ this.retention = new RunRetentionTopic(dataDir, {
506
+ db: () => this.db, held: this.held, deleted: this.deleted, quarantined: this.quarantined,
507
+ historyOwed: this.historyOwed, seqs: this.seqs, published: this.published, transcriptFacts: this.transcriptFacts,
508
+ peek: (id) => this.peek(id), hasRun: (id) => this.hasRun(id), record: (id) => this.record(id),
509
+ listWorkersOf: (parentId) => this.listWorkersOf(parentId), isFallbackRun: (id) => this.isFallbackRun(id),
510
+ hasFallbackRun: (id) => this.hasFallbackRun(id), listOrder: (run) => this.listOrder(run),
511
+ claimFamilies: (families) => this.claimFamilies(families), markDeleted: (id, family) => this.markDeleted(id, family),
512
+ scheduleSave: () => this.scheduleSave(), commitIndex: (input) => this.commitIndex(input),
513
+ commitDelegation: (patches) => this.commitDelegation(patches), applyArchived: (run, archived) => this.applyArchived(run, archived),
514
+ workerDeletionEvidence: (id) => this.workerDeletionEvidence(id),
515
+ workerResults: this.workerResults,
516
+ readWorkerExecution: (id) => this.readWorkerExecution(id), identityPath: (id) => this.identityPath(id),
517
+ processesPath: (id) => this.processesPath(id), scopePath: (id) => this.scopePath(id),
518
+ executionPath: (id) => this.executionPath(id), handoffPath: (runId) => this.handoffPath(runId),
519
+ imagesDir: (runId) => this.imagesDir(runId),
520
+ });
501
521
  this.compressor = new HistoryCompressor(dataDir, (id) => this.isHistoryCompressEligible(id), (id, plain, archive) => this.transcriptFacts.index.adoptArchive(id, plain, stampOf(archive)));
502
522
  }
503
523
  /**
@@ -596,7 +616,6 @@ export class RunStore {
596
616
  sourceDataDir(id) { return this.isFallbackRun(id) ? dataReadDirs(this.dataDir)[1] : runDataDir(this.dataDir, id); }
597
617
  isFallbackRun(id) { return this.db?.isFallback(id) ?? false; }
598
618
  hasFallbackRun(id) { return this.db?.hasFallback(id) ?? false; }
599
- fallbackDeleteError(id, kind = 'record') { return fallbackRunDeleteError(this.dataDir, kind === 'record' ? this.hasFallbackRun(id) : this.isFallbackRun(id), this.peek(id)?.worktreePath); }
600
619
  /**
601
620
  * Open-time load: the live rows, the finished rows a load normalization repairs, then the
602
621
  * delegation families of the live ones. A row that does not parse is skipped and left in the
@@ -1462,7 +1481,7 @@ export class RunStore {
1462
1481
  if (this.db && !this.claimFamilies([run.id]).has(run.id))
1463
1482
  throw new RunWriteRefusedError(run.id, 'foreign');
1464
1483
  this.held.set(run.id, run);
1465
- this.pruneOldRuns();
1484
+ this.retention.pruneOldRuns();
1466
1485
  this.touch(run, undefined);
1467
1486
  return run;
1468
1487
  }
@@ -1794,61 +1813,6 @@ export class RunStore {
1794
1813
  }
1795
1814
  this.commitIndex(staged, undefined, { exits: new Map([[id, exit]]) });
1796
1815
  }
1797
- workerResultsDir(parentId, write = false) { return workerResultsDirectory(write ? this.writeDir(parentId) : this.sourceDataDir(parentId), parentId, write); }
1798
- workerResultSnapshotPath(parentId, workerId, snapshotId) {
1799
- return join(runDataDir(this.dataDir, parentId), 'runs', `${z.uuid().parse(parentId)}-worker-results`, `${z.uuid().parse(workerId)}.${z.uuid().parse(snapshotId)}.json`);
1800
- }
1801
- readWorkerResultFile(parentId, workerId) {
1802
- const parent = this.peek(parentId);
1803
- if (parent?.delegation?.role !== 'root' || !parent.delegation.receipts.some(receipt => receipt.workerId === workerId))
1804
- return undefined;
1805
- const reference = parent.delegation.results?.find(result => result.workerId === workerId);
1806
- if (!reference)
1807
- return undefined;
1808
- try {
1809
- const path = join(this.workerResultsDir(parentId), `${z.uuid().parse(workerId)}.${z.uuid().parse(reference.snapshotId)}.json`);
1810
- const fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
1811
- let raw;
1812
- try {
1813
- const info = fstatSync(fd);
1814
- if (!info.isFile() || info.size > 3_145_728)
1815
- return undefined;
1816
- raw = readFileSync(fd, 'utf8');
1817
- }
1818
- finally {
1819
- closeSync(fd);
1820
- }
1821
- const file = workerResultFileSchema.parse(upgradeRemovedRunnerResult(JSON.parse(raw)));
1822
- if (!bindWorkerResultPath(file.result.diff, this.dataDir, this.hasFallbackRun(parentId), parentId, path))
1823
- return undefined;
1824
- if (file.result.parentRunId !== parentId || file.result.workerId !== workerId || file.result.workspace.ownerRunId !== workerId || file.result.revision !== reference.revision || file.result.observedAt !== reference.observedAt ||
1825
- (file.result.diff.state === 'available' && (file.result.diff.snapshotId !== reference.snapshotId || file.diffSnapshot === undefined)))
1826
- return undefined;
1827
- return file;
1828
- }
1829
- catch {
1830
- return undefined;
1831
- }
1832
- }
1833
- readWorkerResult(parentId, workerId) {
1834
- return this.readWorkerResultFile(parentId, workerId)?.result;
1835
- }
1836
- readWorkerResultDiff(parentId, workerId) {
1837
- return this.readWorkerResultFile(parentId, workerId)?.diffSnapshot;
1838
- }
1839
- /** Publish a pointer only after its redacted immutable snapshot reaches disk. */
1840
- commitWorkerResult(parentId, value, diffSnapshot, opts = {}) {
1841
- return commitStoreWorkerResult({
1842
- redactResult: (result) => this.redact({ type: 'worker-result', seq: 0, ts: result.observedAt, result }).result,
1843
- peek: (id) => this.peek(id),
1844
- readWorkerResultFile: (id, workerId) => this.readWorkerResultFile(id, workerId),
1845
- readWorkerResult: (id, workerId) => this.readWorkerResult(id, workerId),
1846
- redactText: (text) => this.redactText(text),
1847
- workerResultSnapshotPath: (id, workerId, snapshotId) => this.workerResultSnapshotPath(id, workerId, snapshotId),
1848
- workerResultsDir: (id) => this.workerResultsDir(id, true),
1849
- commitDelegation: (patches) => this.commitDelegation(patches),
1850
- }, parentId, value, diffSnapshot, opts);
1851
- }
1852
1816
  /** Create an owned worker run and its parent receipt; `createStoreOwnedRun` holds the checks. */
1853
1817
  createOwnedRun(input, parentId, requestId, worker, requestHash, spawnCapacityRefusal, executionIdentity = { kind: 'internal' }) {
1854
1818
  return createStoreOwnedRun({
@@ -2783,21 +2747,6 @@ export class RunStore {
2783
2747
  return false;
2784
2748
  }
2785
2749
  }
2786
- /** Complete replacement evidence can stand in for absent child history, never for a present execution. */
2787
- readDeletedWorkerResult(parentId, workerId) {
2788
- if (this.hasRun(workerId))
2789
- return undefined;
2790
- const parent = this.peek(parentId);
2791
- if (parent?.delegation?.role !== 'root' || parent.delegation.historyDeletion)
2792
- return undefined;
2793
- const deletion = parent.delegation.receipts.find(receipt => receipt.workerId === workerId)?.deletion;
2794
- if (deletion?.phase !== 'complete')
2795
- return undefined;
2796
- const result = this.readWorkerResult(parentId, workerId);
2797
- return result?.settled && ['review', 'done', 'failed', 'cancelled'].includes(result.status) &&
2798
- result.cleanup === 'complete' && result.revision === deletion.revision &&
2799
- result.workspace.resourceId === deletion.resourceId ? result : undefined;
2800
- }
2801
2750
  /** A deleted child's receipt replaces the private proof only after the deletion checkpoint. */
2802
2751
  workerDeletionEvidence(id) {
2803
2752
  const child = this.peek(id);
@@ -2812,7 +2761,7 @@ export class RunStore {
2812
2761
  if (parent?.delegation?.role !== 'root' || parent.delegation.historyDeletion)
2813
2762
  return false;
2814
2763
  const receipt = parent.delegation.receipts.find(entry => entry.workerId === id);
2815
- const result = this.readWorkerResult(parent.id, id);
2764
+ const result = this.workerResults.readWorkerResult(parent.id, id);
2816
2765
  if (!receipt || !result?.settled || result.cleanup !== 'complete' || result.status !== child.status ||
2817
2766
  result.revision !== (child.delegation.executionRevision ?? 0))
2818
2767
  return false;
@@ -2824,134 +2773,6 @@ export class RunStore {
2824
2773
  scratchMayExist: () => agentTmpDirMayExist(this.dataDir, id), executionExists: () => existsSync(this.executionPath(id)),
2825
2774
  });
2826
2775
  }
2827
- canDeleteRun(id, kind = 'record') {
2828
- if (this.fallbackDeleteError(id, kind))
2829
- return false;
2830
- if (deletionRefusal(id, kind === 'record' ? 'history' : 'worktree', this.dataDir))
2831
- return false;
2832
- const run = this.peek(id);
2833
- if (run?.delegation?.role === 'invalid')
2834
- return false;
2835
- if (run?.delegation?.role === 'worker')
2836
- return supervisedWorkers(this, run).length === 0 && this.workerDeletionEvidence(id);
2837
- const privateWorkers = workerEvidenceRunIds(this.dataDir);
2838
- if (!privateWorkers || privateWorkers.includes(id))
2839
- return false;
2840
- if (run?.delegation?.role === 'root') {
2841
- if (run.delegation.finishRequestedAt && ['queued', 'running', 'waiting'].includes(run.status))
2842
- return false;
2843
- // Keep the parent's receipt and result ownership until each child history is explicitly removed.
2844
- if (this.listWorkersOf(id).length > 0)
2845
- return false;
2846
- return run.delegation.receipts.every(receipt => {
2847
- if (this.hasRun(receipt.workerId) || receipt.deletion?.phase !== 'complete')
2848
- return false;
2849
- // A pending parent deletion already validated the results before removing their bytes.
2850
- if (run.delegation?.role === 'root' && run.delegation.historyDeletion === 'pending')
2851
- return true;
2852
- return this.readDeletedWorkerResult(id, receipt.workerId) !== undefined;
2853
- });
2854
- }
2855
- return this.listWorkersOf(id).length === 0;
2856
- }
2857
- /** Delegated history deletion is synchronous and checkpointed; any failed byte/index removal remains retryable. */
2858
- deleteDelegatedRun(id) {
2859
- const run = this.peek(id);
2860
- try {
2861
- if (run.delegation?.role === 'worker') {
2862
- const parent = this.peek(run.delegation.parentRunId);
2863
- if (parent.delegation?.role !== 'root')
2864
- return false;
2865
- const receipt = parent.delegation.receipts.find(entry => entry.workerId === id);
2866
- const result = this.readWorkerResult(parent.id, id);
2867
- const deletion = receipt.deletion ?? { phase: 'pending', revision: result.revision,
2868
- resourceId: run.delegation.workspace.resourceId, generation: this.readWorkerExecution(id).generation };
2869
- this.commitDelegation([{ id: parent.id, delegation: { ...parent.delegation,
2870
- receipts: parent.delegation.receipts.map(entry => entry.workerId === id ? { ...entry, deletion } : entry),
2871
- } }]);
2872
- // Do not advertise artifact bytes as retained while interrupted deletion is in progress.
2873
- this.commitWorkerResult(parent.id, { ...result, observedAt: new Date().toISOString(),
2874
- diff: result.diff.state === 'available' ? { ...result.diff, snapshotId: randomUUID() } : result.diff,
2875
- artifacts: result.artifacts.state === 'available' ? { ...result.artifacts,
2876
- items: result.artifacts.items.map(item => ({ state: 'unavailable', reason: 'unreadable',
2877
- detail: 'History deletion is in progress', id: item.id, path: item.path })),
2878
- } : result.artifacts,
2879
- }, this.readWorkerResultDiff(parent.id, id));
2880
- this.removeRunHistoryBytes(id);
2881
- // Delete scratch while its generation evidence still exists; failed removal keeps it.
2882
- removeAgentTmpDir(this.dataDir, id);
2883
- if (agentTmpDirMayExist(this.dataDir, id))
2884
- return false;
2885
- // Private process/account evidence is now replaced by the exact parent receipt.
2886
- rmSync(this.identityPath(id), { force: true });
2887
- rmSync(this.processesPath(id), { force: true });
2888
- rmSync(this.scopePath(id), { force: true });
2889
- rmSync(this.executionPath(id), { force: true });
2890
- const retained = this.readWorkerResult(parent.id, id);
2891
- this.commitWorkerResult(parent.id, { ...retained, observedAt: new Date().toISOString(),
2892
- diff: retained.diff.state === 'available' ? { ...retained.diff, snapshotId: randomUUID() } : retained.diff,
2893
- artifacts: retained.artifacts.state === 'available' ? { ...retained.artifacts,
2894
- items: retained.artifacts.items.map(item => ({ state: 'deleted', reason: 'missing', id: item.id, path: item.path })),
2895
- } : retained.artifacts,
2896
- }, this.readWorkerResultDiff(parent.id, id));
2897
- this.commitIndex(new Map([[parent.id, { ...parent, delegation: { ...parent.delegation,
2898
- receipts: parent.delegation.receipts.map(entry => entry.workerId === id ? { ...entry, deletion: { ...deletion, phase: 'complete' } } : entry),
2899
- } }], [id, null]]));
2900
- }
2901
- else if (run.delegation?.role === 'root') {
2902
- this.commitDelegation([{ id, delegation: { ...run.delegation, historyDeletion: 'pending' } }]);
2903
- this.removeRunHistoryBytes(id);
2904
- rmSync(join(runDataDir(this.dataDir, id), 'runs', `${id}-worker-results`), { recursive: true, force: true });
2905
- this.commitIndex(new Map([[id, null]]));
2906
- }
2907
- else
2908
- return false;
2909
- removeAgentTmpDir(this.dataDir, id);
2910
- this.seqs.delete(id);
2911
- return true;
2912
- }
2913
- catch {
2914
- return false;
2915
- }
2916
- }
2917
- removeRunHistoryBytes(id) {
2918
- // Fixed owned paths only: never follow context descriptors supplied in persisted metadata.
2919
- z.uuid().parse(id);
2920
- const dir = join(runDataDir(this.dataDir, id), 'runs');
2921
- if (realpathSync(dir) !== resolve(dir))
2922
- throw new Error('History storage redirected');
2923
- this.removeHistoryFiles(id);
2924
- }
2925
- /** The run's history, handoff and images, then the removal cleanups (`runs/removal-slots.ts`). */
2926
- removeHistoryFiles(id) {
2927
- this.transcriptFacts.index.forget(id);
2928
- removeHistory(this.dataDir, id);
2929
- rmSync(this.handoffPath(id), { force: true });
2930
- rmSync(this.imagesDir(id), { recursive: true, force: true });
2931
- runRemovalCleanups(id, this.dataDir);
2932
- }
2933
- deleteRun(id) {
2934
- const refusal = this.fallbackDeleteError(id);
2935
- if (refusal)
2936
- throw new Error(refusal);
2937
- if (!this.canDeleteRun(id))
2938
- return false;
2939
- const run = this.peek(id);
2940
- if (run && this.db && (this.quarantined.has(id) || !this.claimFamilies([familyKey(run)]).size))
2941
- return false;
2942
- if (run?.delegation?.role === 'worker' || run?.delegation?.role === 'root')
2943
- return this.deleteDelegatedRun(id);
2944
- const existed = run !== undefined;
2945
- this.held.delete(id);
2946
- if (existed) {
2947
- this.markDeleted(id, familyKey(run));
2948
- removeAgentTmpDir(this.dataDir, id);
2949
- this.seqs.delete(id);
2950
- this.scheduleSave();
2951
- this.published.publish('run.deleted', { runId: id });
2952
- }
2953
- return existed;
2954
- }
2955
2776
  /** Write the pending rows out now (used on shutdown). */
2956
2777
  flush() {
2957
2778
  if (this.saveTimer) {
@@ -3013,76 +2834,6 @@ export class RunStore {
3013
2834
  this.deletedFamilies.set(id, family);
3014
2835
  this.historyOwed.add(id);
3015
2836
  }
3016
- /** A deleted run's history files and removal cleanups, once the delete of its row has committed.
3017
- * Best effort: a failure is logged, and the row stays deleted. */
3018
- removeOwedHistory(id) {
3019
- if (!this.historyOwed.delete(id))
3020
- return;
3021
- try {
3022
- this.removeHistoryFiles(id);
3023
- }
3024
- catch (error) {
3025
- console.warn(`[hsq] History cleanup of run ${id} is incomplete: ${error instanceof Error ? error.message : String(error)}`);
3026
- }
3027
- }
3028
- /**
3029
- * Count-based history retention: of the runs past the newest `MAX_RUNS_KEPT` unarchived ones,
3030
- * archive each settled task that is not pinned and whose family this store can claim, together
3031
- * 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
3032
- * laid over them, since a run created or archived since the last save has no row yet; the rows
3033
- * past the cut are then filtered in `runs.db`, so only real candidates decode. Archived runs
3034
- * are never deleted by retention — only an explicit delete, worker destruction, or history
3035
- * deletion removes a run.
3036
- */
3037
- pruneOldRuns() {
3038
- const ranked = new Map();
3039
- for (const key of this.db?.listKeysWhere('archived = ?', [0]) ?? []) {
3040
- if (!this.held.has(key.id) && !this.deleted.has(key.id))
3041
- ranked.set(key.id, key);
3042
- }
3043
- for (const run of this.held.values())
3044
- if (!run.archived)
3045
- ranked.set(run.id, { id: run.id, ...this.listOrder(run) });
3046
- const overflow = [...ranked.values()].sort(newestFirst).slice(MAX_RUNS_KEPT).map((key) => key.id);
3047
- if (overflow.length === 0)
3048
- return;
3049
- const stale = overflow.flatMap((id) => {
3050
- const run = this.held.get(id);
3051
- // Retention must not archive a live task between turns, a pinned run, or a worker on its own.
3052
- return run && !this.hasFallbackRun(id) && RETENTION_RUN_RULE.matches(run) ? [id] : [];
3053
- });
3054
- const skipped = overflow.filter(id => this.hasFallbackRun(id)).length;
3055
- if (skipped)
3056
- console.info(`[hsq] Retention skipped ${skipped} read-only fallback run(s) under ${dataReadDirs(this.dataDir)[1]}.`);
3057
- const cold = overflow.filter((id) => !this.held.has(id) && !this.hasFallbackRun(id));
3058
- if (cold.length > 0) {
3059
- // Another process's runs are its own to keep or archive (#779, plan step 3).
3060
- const rows = this.db.listWhere(guardedJsonSql(RETENTION_RUN_RULE.sql, 0), [JSON.stringify(cold)]);
3061
- const writable = this.claimFamilies(rows.map(rowFamily));
3062
- for (const row of rows)
3063
- if (writable.has(rowFamily(row)))
3064
- stale.push(row.id);
3065
- }
3066
- for (const id of stale) {
3067
- const run = this.record(id);
3068
- if (!run || run.archived || !RETENTION_RUN_RULE.matches(run))
3069
- continue;
3070
- this.archiveSettledFamily(run);
3071
- }
3072
- }
3073
- /** Archive a root with its workers unless a member is live, mid-destroy or pinned, or a history
3074
- * deletion is under way. Each member is marked dirty: the next save writes the family at once. */
3075
- archiveSettledFamily(root) {
3076
- assertRunSlotsSealed();
3077
- const workers = this.listWorkersOf(root.id), family = [root, ...workers];
3078
- if (family.some((run) => isLiveRecord(run) || run.pinned) || (root.delegation?.role === 'root' && root.delegation.historyDeletion))
3079
- return;
3080
- for (const member of [root, ...workers.flatMap((worker) => this.record(worker.id) ?? [])].filter((run) => !run.archived)) {
3081
- this.applyArchived(member, true);
3082
- if (!deletionRefusal(member.id, 'archive-tmp', this.dataDir))
3083
- removeAgentTmpDir(this.dataDir, member.id);
3084
- }
3085
- }
3086
2837
  /** Debounced so token-usage updates don't rewrite a row per event. Nothing to schedule without
3087
2838
  * a database: a `RunStore.unavailable` store, or a closed one, writes nothing. */
3088
2839
  scheduleSave() {
@@ -3176,7 +2927,7 @@ export class RunStore {
3176
2927
  this.liveItems.forget(id);
3177
2928
  this.base.delete(id);
3178
2929
  this.deletedFamilies.delete(id);
3179
- this.removeOwedHistory(id);
2930
+ this.retention.removeOwedHistory(id);
3180
2931
  }
3181
2932
  this.dirty.clear();
3182
2933
  this.deleted.clear();