@hearsay-tools/squawk 0.18.0-dev.7796 → 0.18.0-dev.7801
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.
- package/dist/autosave-removal-slots.d.ts +2 -2
- package/dist/autosave-removal-slots.js +2 -2
- package/dist/autosave-removal-slots.js.map +1 -1
- package/dist/ci-wait/tools.d.ts +4 -4
- package/dist/delegation/routes.d.ts +15 -15
- package/dist/delegation/service.js +2 -2
- package/dist/delegation/service.js.map +1 -1
- package/dist/delegation/transport.d.ts +15 -15
- package/dist/delegation/worker-cleanup.js +1 -1
- package/dist/delegation/worker-cleanup.js.map +1 -1
- package/dist/jobs/removal-slot.d.ts +2 -2
- package/dist/jobs/removal-slot.js +3 -3
- package/dist/jobs/removal-slot.js.map +1 -1
- package/dist/runs/agent-tmpdir.d.ts +2 -0
- package/dist/runs/agent-tmpdir.js +40 -1
- package/dist/runs/agent-tmpdir.js.map +1 -1
- package/dist/runs/ports.d.ts +7 -4
- package/dist/runs/removal-slots.d.ts +4 -3
- package/dist/runs/removal-slots.js.map +1 -1
- package/dist/runs/run-retention.d.ts +84 -0
- package/dist/runs/run-retention.js +224 -0
- package/dist/runs/run-retention.js.map +1 -0
- package/dist/runs/run-row.d.ts +9 -0
- package/dist/runs/run-row.js +7 -0
- package/dist/runs/run-row.js.map +1 -1
- package/dist/runs/store.d.ts +3 -26
- package/dist/runs/store.js +31 -215
- package/dist/runs/store.js.map +1 -1
- package/dist/server/live-routes.d.ts +6 -6
- package/dist/server/project-run-files.js +1 -1
- package/dist/server/project-run-files.js.map +1 -1
- package/dist/server/run-checkout.d.ts +3 -1
- package/dist/server/run-checkout.js +3 -3
- package/dist/server/run-checkout.js.map +1 -1
- package/dist/server/server.d.ts +6 -6
- package/dist/server/server.js +1 -1
- package/dist/server/server.js.map +1 -1
- package/dist/workflows/run/run-settlement.js +12 -2
- package/dist/workflows/run/run-settlement.js.map +1 -1
- package/package.json +4 -4
package/dist/runs/store.d.ts
CHANGED
|
@@ -20,6 +20,7 @@ export { ConversationIdInUseError } from './conversation-identity.ts';
|
|
|
20
20
|
import { RunDatabase, type RunDatabaseChanges, type RunDatabaseCommit } from './run-database.ts';
|
|
21
21
|
import { type BranchOwner } from './branch-owners.ts';
|
|
22
22
|
export { ciWaitEntry, holdsWorkerWait, upgradeLegacyWaits, workerWaitEntry } from './legacy-waits.ts';
|
|
23
|
+
import { RunRetentionTopic } from './run-retention.ts';
|
|
23
24
|
import { type RawExtras } from './raw-record.ts';
|
|
24
25
|
import { RunStoreOpenError } from './store-open-error.ts';
|
|
25
26
|
import { type SpawnCapacityRefusal } from './owned-run-create.ts';
|
|
@@ -3231,8 +3232,6 @@ export declare class RunWriteRefusedError extends Error {
|
|
|
3231
3232
|
readonly ownership: Exclude<RunOwnership, 'held' | 'free'>;
|
|
3232
3233
|
constructor(runId: string, ownership: Exclude<RunOwnership, 'held' | 'free'>, fallbackError?: string);
|
|
3233
3234
|
}
|
|
3234
|
-
/** Newest first, runs created in the same millisecond in insertion order: the order `runs.db`
|
|
3235
|
-
* lists in, and the order every list had while it was a stable sort of the in-memory map. */
|
|
3236
3235
|
/** Why a `run` event fired, when a delegation checkpoint caused it or nothing durable changed
|
|
3237
3236
|
* (`republish`) (in-process only). */
|
|
3238
3237
|
export type CommitSource = 'delegation-checkpoint' | 'delegation-destroy-progress' | 'live-release';
|
|
@@ -3310,6 +3309,8 @@ export declare class RunStore {
|
|
|
3310
3309
|
private readonly compressor;
|
|
3311
3310
|
/** What the transcript says about a run (hearsay-tools/squawk#4036). */
|
|
3312
3311
|
readonly transcriptFacts: RunTranscriptFacts;
|
|
3312
|
+
/** Whether a run may go, and its deletion; the count-based archive (hearsay-tools/squawk#4037). */
|
|
3313
|
+
readonly retention: RunRetentionTopic;
|
|
3313
3314
|
private readonly liveItems;
|
|
3314
3315
|
/** Capture both sources on the same synchronous sequence boundary before history IO. */
|
|
3315
3316
|
liveReadSnapshot(runId: string): {
|
|
@@ -3362,7 +3363,6 @@ export declare class RunStore {
|
|
|
3362
3363
|
sourceDataDir(id: string): string;
|
|
3363
3364
|
isFallbackRun(id: string): boolean;
|
|
3364
3365
|
hasFallbackRun(id: string): boolean;
|
|
3365
|
-
fallbackDeleteError(id: string, kind?: 'record' | 'worktree'): string | undefined;
|
|
3366
3366
|
/**
|
|
3367
3367
|
* Open-time load: the live rows, the finished rows a load normalization repairs, then the
|
|
3368
3368
|
* delegation families of the live ones. A row that does not parse is skipped and left in the
|
|
@@ -3984,13 +3984,6 @@ export declare class RunStore {
|
|
|
3984
3984
|
/** A deleted child's receipt replaces the private proof only after the deletion checkpoint. */
|
|
3985
3985
|
private workerDeletionEvidence;
|
|
3986
3986
|
private workerDeletionResult;
|
|
3987
|
-
canDeleteRun(id: string, kind?: 'record' | 'worktree'): boolean;
|
|
3988
|
-
/** Delegated history deletion is synchronous and checkpointed; any failed byte/index removal remains retryable. */
|
|
3989
|
-
private deleteDelegatedRun;
|
|
3990
|
-
private removeRunHistoryBytes;
|
|
3991
|
-
/** The run's history, handoff and images, then the removal cleanups (`runs/removal-slots.ts`). */
|
|
3992
|
-
private removeHistoryFiles;
|
|
3993
|
-
deleteRun(id: string): boolean;
|
|
3994
3987
|
/** Write the pending rows out now (used on shutdown). */
|
|
3995
3988
|
flush(): void;
|
|
3996
3989
|
private seqs;
|
|
@@ -4014,22 +4007,6 @@ export declare class RunStore {
|
|
|
4014
4007
|
/** The held record is gone; the next save or commit deletes its row, fenced by `family`'s claim
|
|
4015
4008
|
* and by the revision this store last saw (kept in `base` until the delete is written). */
|
|
4016
4009
|
private markDeleted;
|
|
4017
|
-
/** A deleted run's history files and removal cleanups, once the delete of its row has committed.
|
|
4018
|
-
* Best effort: a failure is logged, and the row stays deleted. */
|
|
4019
|
-
private removeOwedHistory;
|
|
4020
|
-
/**
|
|
4021
|
-
* Count-based history retention: of the runs past the newest `MAX_RUNS_KEPT` unarchived ones,
|
|
4022
|
-
* archive each settled task that is not pinned and whose family this store can claim, together
|
|
4023
|
-
* 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
|
|
4024
|
-
* laid over them, since a run created or archived since the last save has no row yet; the rows
|
|
4025
|
-
* past the cut are then filtered in `runs.db`, so only real candidates decode. Archived runs
|
|
4026
|
-
* are never deleted by retention — only an explicit delete, worker destruction, or history
|
|
4027
|
-
* deletion removes a run.
|
|
4028
|
-
*/
|
|
4029
|
-
private pruneOldRuns;
|
|
4030
|
-
/** Archive a root with its workers unless a member is live, mid-destroy or pinned, or a history
|
|
4031
|
-
* deletion is under way. Each member is marked dirty: the next save writes the family at once. */
|
|
4032
|
-
private archiveSettledFamily;
|
|
4033
4010
|
/** Debounced so token-usage updates don't rewrite a row per event. Nothing to schedule without
|
|
4034
4011
|
* a database: a `RunStore.unavailable` store, or a closed one, writes nothing. */
|
|
4035
4012
|
private scheduleSave;
|
package/dist/runs/store.js
CHANGED
|
@@ -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 {
|
|
14
|
-
import { admissibleExecution, holderRefusal, SPAWN_NEXT, WorkerAdmissionRefusal,
|
|
15
|
-
import { agentTmpDirMayExist, agentTmpDirOwnershipProven
|
|
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,
|
|
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,14 +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,
|
|
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,
|
|
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';
|
|
@@ -67,7 +68,6 @@ import { archiveStoreFamily } from './archive-family.js';
|
|
|
67
68
|
import { claimStoreFamilies } from './claim-families.js';
|
|
68
69
|
import { createStoreOwnedRun } from './owned-run-create.js';
|
|
69
70
|
import { commitStoreWorkerResult } from './worker-result-commit.js';
|
|
70
|
-
import { supervisedWorkers } from './supervised.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,8 @@ 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;
|
|
485
481
|
liveItems = new LiveItemSnapshots();
|
|
486
482
|
/** Capture both sources on the same synchronous sequence boundary before history IO. */
|
|
487
483
|
liveReadSnapshot(runId) {
|
|
@@ -498,6 +494,25 @@ export class RunStore {
|
|
|
498
494
|
listConversationRootIds: () => this.listConversationRootIds(),
|
|
499
495
|
listRunIds: () => this.listRunIds(),
|
|
500
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
|
+
});
|
|
501
516
|
this.compressor = new HistoryCompressor(dataDir, (id) => this.isHistoryCompressEligible(id), (id, plain, archive) => this.transcriptFacts.index.adoptArchive(id, plain, stampOf(archive)));
|
|
502
517
|
}
|
|
503
518
|
/**
|
|
@@ -596,7 +611,6 @@ export class RunStore {
|
|
|
596
611
|
sourceDataDir(id) { return this.isFallbackRun(id) ? dataReadDirs(this.dataDir)[1] : runDataDir(this.dataDir, id); }
|
|
597
612
|
isFallbackRun(id) { return this.db?.isFallback(id) ?? false; }
|
|
598
613
|
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
614
|
/**
|
|
601
615
|
* Open-time load: the live rows, the finished rows a load normalization repairs, then the
|
|
602
616
|
* delegation families of the live ones. A row that does not parse is skipped and left in the
|
|
@@ -1462,7 +1476,7 @@ export class RunStore {
|
|
|
1462
1476
|
if (this.db && !this.claimFamilies([run.id]).has(run.id))
|
|
1463
1477
|
throw new RunWriteRefusedError(run.id, 'foreign');
|
|
1464
1478
|
this.held.set(run.id, run);
|
|
1465
|
-
this.pruneOldRuns();
|
|
1479
|
+
this.retention.pruneOldRuns();
|
|
1466
1480
|
this.touch(run, undefined);
|
|
1467
1481
|
return run;
|
|
1468
1482
|
}
|
|
@@ -2824,134 +2838,6 @@ export class RunStore {
|
|
|
2824
2838
|
scratchMayExist: () => agentTmpDirMayExist(this.dataDir, id), executionExists: () => existsSync(this.executionPath(id)),
|
|
2825
2839
|
});
|
|
2826
2840
|
}
|
|
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
2841
|
/** Write the pending rows out now (used on shutdown). */
|
|
2956
2842
|
flush() {
|
|
2957
2843
|
if (this.saveTimer) {
|
|
@@ -3013,76 +2899,6 @@ export class RunStore {
|
|
|
3013
2899
|
this.deletedFamilies.set(id, family);
|
|
3014
2900
|
this.historyOwed.add(id);
|
|
3015
2901
|
}
|
|
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
2902
|
/** Debounced so token-usage updates don't rewrite a row per event. Nothing to schedule without
|
|
3087
2903
|
* a database: a `RunStore.unavailable` store, or a closed one, writes nothing. */
|
|
3088
2904
|
scheduleSave() {
|
|
@@ -3176,7 +2992,7 @@ export class RunStore {
|
|
|
3176
2992
|
this.liveItems.forget(id);
|
|
3177
2993
|
this.base.delete(id);
|
|
3178
2994
|
this.deletedFamilies.delete(id);
|
|
3179
|
-
this.removeOwedHistory(id);
|
|
2995
|
+
this.retention.removeOwedHistory(id);
|
|
3180
2996
|
}
|
|
3181
2997
|
this.dirty.clear();
|
|
3182
2998
|
this.deleted.clear();
|