@hearsay-tools/squawk 0.18.0-dev.7812 → 0.18.0-dev.7820
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/activity/publisher.js +2 -2
- package/dist/activity/publisher.js.map +1 -1
- package/dist/activity/read-model.js +1 -1
- package/dist/activity/read-model.js.map +1 -1
- package/dist/activity/requests.d.ts +4 -2
- package/dist/activity/requests.js +1 -1
- package/dist/activity/requests.js.map +1 -1
- package/dist/artifacts/reports-index.d.ts +2 -1
- package/dist/artifacts/reports-index.js +1 -1
- package/dist/artifacts/reports-index.js.map +1 -1
- package/dist/ci-wait/controller.d.ts +4 -4
- package/dist/delegation/conversations.d.ts +6 -2
- package/dist/delegation/conversations.js +3 -2
- package/dist/delegation/conversations.js.map +1 -1
- package/dist/delegation/family-end.d.ts +4 -2
- package/dist/delegation/results.js +2 -2
- package/dist/delegation/results.js.map +1 -1
- package/dist/delegation/routes.d.ts +11 -11
- package/dist/delegation/routes.js +1 -1
- package/dist/delegation/routes.js.map +1 -1
- package/dist/delegation/scratch-cleanup.js +2 -2
- package/dist/delegation/scratch-cleanup.js.map +1 -1
- package/dist/delegation/service.js +2 -2
- package/dist/delegation/service.js.map +1 -1
- package/dist/delegation/transport.d.ts +10 -10
- package/dist/delegation/worker-cleanup.js +1 -1
- package/dist/delegation/worker-cleanup.js.map +1 -1
- package/dist/preview/host.d.ts +2 -1
- package/dist/preview/host.js +1 -1
- package/dist/preview/host.js.map +1 -1
- package/dist/project-migration/live.js +3 -3
- package/dist/project-migration/live.js.map +1 -1
- package/dist/runs/claim-families.d.ts +1 -1
- package/dist/runs/claim-families.js +1 -1
- package/dist/runs/live-tasks.js +1 -1
- package/dist/runs/live-tasks.js.map +1 -1
- package/dist/runs/loaded-run-exits.d.ts +23 -0
- package/dist/runs/loaded-run-exits.js +46 -1
- package/dist/runs/loaded-run-exits.js.map +1 -1
- package/dist/runs/ports.d.ts +67 -26
- package/dist/runs/retention.d.ts +3 -1
- package/dist/runs/retention.js +5 -5
- package/dist/runs/retention.js.map +1 -1
- package/dist/runs/run-archive.d.ts +1217 -0
- package/dist/runs/run-archive.js +332 -0
- package/dist/runs/run-archive.js.map +1 -0
- package/dist/runs/run-claims-topic.d.ts +130 -0
- package/dist/runs/run-claims-topic.js +258 -0
- package/dist/runs/run-claims-topic.js.map +1 -0
- package/dist/runs/run-claims.d.ts +1 -1
- package/dist/runs/run-claims.js +1 -1
- package/dist/runs/run-claims.js.map +1 -1
- package/dist/runs/run-database.d.ts +1 -1
- package/dist/runs/run-index.js +3 -1
- package/dist/runs/run-index.js.map +1 -1
- package/dist/runs/run-pins.d.ts +38 -0
- package/dist/runs/run-pins.js +45 -0
- package/dist/runs/run-pins.js.map +1 -0
- package/dist/runs/run-read-flags.d.ts +58 -0
- package/dist/runs/run-read-flags.js +87 -0
- package/dist/runs/run-read-flags.js.map +1 -0
- package/dist/runs/run-references.d.ts +1 -1
- package/dist/runs/run-references.js +1 -1
- package/dist/runs/run-references.js.map +1 -1
- package/dist/runs/store-open.d.ts +45 -0
- package/dist/runs/store-open.js +89 -0
- package/dist/runs/store-open.js.map +1 -0
- package/dist/runs/store.d.ts +13 -237
- package/dist/runs/store.js +78 -816
- package/dist/runs/store.js.map +1 -1
- package/dist/runs/webhook.d.ts +3 -1
- package/dist/runs/webhook.js +2 -2
- package/dist/runs/webhook.js.map +1 -1
- package/dist/serve-boot.d.ts +2 -2
- package/dist/serve-boot.js +1 -1
- package/dist/serve-boot.js.map +1 -1
- package/dist/server/archive-on-merge.js +10 -10
- package/dist/server/archive-on-merge.js.map +1 -1
- package/dist/server/completion-actions.js +8 -8
- package/dist/server/completion-actions.js.map +1 -1
- package/dist/server/project-context.js +2 -2
- package/dist/server/project-context.js.map +1 -1
- package/dist/server/project-run-files.d.ts +3 -1
- package/dist/server/project-run-files.js +3 -3
- 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/run-event-feed.js +2 -2
- package/dist/server/run-event-feed.js.map +1 -1
- package/dist/server/server.d.ts +8619 -8619
- package/dist/server/server.js +15 -15
- package/dist/server/server.js.map +1 -1
- package/dist/workflows/run/continuation-acceptance.js +1 -1
- package/dist/workflows/run/continuation-acceptance.js.map +1 -1
- package/dist/workflows/run/family-reconciler.js +2 -2
- package/dist/workflows/run/family-reconciler.js.map +1 -1
- package/dist/workflows/run/maintenance-claims.js +6 -6
- package/dist/workflows/run/maintenance-claims.js.map +1 -1
- package/dist/workflows/run/run-cancel.js +1 -1
- package/dist/workflows/run/run-cancel.js.map +1 -1
- package/dist/workflows/run/run-recovery.js +3 -3
- package/dist/workflows/run/run-recovery.js.map +1 -1
- package/dist/workflows/run/run-settlement.js +1 -1
- package/dist/workflows/run/run-settlement.js.map +1 -1
- package/dist/workflows/run.js +7 -7
- package/dist/workflows/run.js.map +1 -1
- package/package.json +4 -4
- package/scripts/benchmark-run-store.ts +2 -2
package/dist/runs/store.js
CHANGED
|
@@ -1,38 +1,33 @@
|
|
|
1
1
|
import { legacyIndexRows, readableSavedRunner, upgradeLegacyRunRow, withKeptFields } from './legacy-run-rows.js';
|
|
2
|
-
import {
|
|
3
|
-
import { addRunSource, copyFallbackFamily, fallbackRunSource, fallbackRunDeleteError } from './project-run-sources.js';
|
|
2
|
+
import { addRunSource, fallbackRunSource } from './project-run-sources.js';
|
|
4
3
|
import { registeredWaitRecord, registeredReceiptRecord } from './wait-registration-write.js';
|
|
5
|
-
import { stageCommit,
|
|
4
|
+
import { stageCommit, stageDurableUpdate, stageDebouncedUpdate, stageConversation, stageStepUpdate, stepTotals, redactPatch } from './record-write-rules.js';
|
|
6
5
|
import { publishRunWrite, RunLifecycle, snapshotRun } from './lifecycle.js';
|
|
7
6
|
import { listPeerTaskSummaries, parseStoredSummary } from './run-summary-page.js';
|
|
8
7
|
export { parseStoredSummary } from './run-summary-page.js';
|
|
9
8
|
import { workerExecutionsFactory } from './worker-executions-registry.js';
|
|
10
|
-
import { randomUUID
|
|
9
|
+
import { randomUUID } from 'node:crypto';
|
|
11
10
|
import { isDeepStrictEqual } from 'node:util';
|
|
12
11
|
import { existsSync, mkdirSync } from 'node:fs';
|
|
13
12
|
import { join } from 'node:path';
|
|
14
13
|
import { z } from 'zod';
|
|
15
14
|
import { delegationStateSchema, workerDestroyRetrySchema, } from '../contract/index.js';
|
|
16
15
|
import { agentInputSchema, inboxClaimSchema } from '../contract/index.js';
|
|
17
|
-
import {
|
|
16
|
+
import { stepStateSchema as contractStepStateSchema, toRunSummary, runRecordSchema as contractRunRecordSchema, runPullRequestSchema, } from '../contract/index.js';
|
|
18
17
|
import { queuedMessageSchema } from '../contract/index.js';
|
|
19
18
|
import { previewServerSchema } from '../contract/index.js';
|
|
20
19
|
import { waitSchema } from '../contract/index.js';
|
|
21
20
|
import { isUsageLimitHold } from '../contract/index.js';
|
|
22
|
-
import {
|
|
21
|
+
import { REFERENCED_RUN_RULE } from '../contract/index.js';
|
|
23
22
|
import { matchesRunSearch, sqlPrefilterTokens } from '../contract/index.js';
|
|
24
23
|
import { storedDelegationStateSchema } from './delegation-state.js';
|
|
25
|
-
import { HistoryCompressor } from './history-compressor.js';
|
|
26
24
|
import { LiveItemSnapshots } from './live-item-snapshots.js';
|
|
27
|
-
import { stampOf } from './transcript-facts.js';
|
|
28
25
|
import { RunTranscriptFacts } from './transcript-facts-topic.js';
|
|
29
|
-
import {
|
|
30
|
-
// Pure, dependency-free reference helpers — the same sanity bound the marker parser applies.
|
|
31
|
-
import { archivePullRequests, pullRequestKey } from './pull-requests.js';
|
|
26
|
+
import { restoreHistory } from './history-file.js';
|
|
32
27
|
// Type-only module (zod + nothing else), so this cannot cycle back into the store.
|
|
33
28
|
import { workflowDefSchema } from '../workflows/types.js';
|
|
34
29
|
import { applyOutcomes } from './outcome-commit.js';
|
|
35
|
-
import { ISSUE_URL_RE, namesForeignReference,
|
|
30
|
+
import { ISSUE_URL_RE, namesForeignReference, rescopeRun, restoreOriginatingIssue, trackReferencedIssues, trackReferencedPrs } from './run-references.js';
|
|
36
31
|
import { applyExit, doneCommits, exitDurability, RUN_EXITS } from './run-exits.js';
|
|
37
32
|
import { assertConversationIdFree } from './conversation-identity.js';
|
|
38
33
|
export { ConversationIdInUseError } from './conversation-identity.js';
|
|
@@ -40,24 +35,26 @@ import { LEGACY_RUNNER_IDS } from '../core/runner-ids.js';
|
|
|
40
35
|
import { ARCHIVED_ROOT, RUNS_DB_FILE, RUNS_IMPORT_COMPLETE_KEY, RunConflictError, RunDatabase, RunDatabaseBusyError, } from './run-database.js';
|
|
41
36
|
import { listBranchOwners } from './branch-owners.js';
|
|
42
37
|
import { guardedJsonSql } from './guarded-json-sql.js';
|
|
43
|
-
import {
|
|
44
|
-
import { failLoadedInterruptedRun, restoreLoadedUsageLimitHold, settleLoadedStop } from './loaded-run-exits.js';
|
|
38
|
+
import { reconcileLoadedRun } from './loaded-run-exits.js';
|
|
45
39
|
import { hasLegacyWaitFields, UNREADABLE_WAIT } from './legacy-waits.js';
|
|
46
40
|
export { ciWaitEntry, holdsWorkerWait, upgradeLegacyWaits, workerWaitEntry } from './legacy-waits.js';
|
|
47
41
|
import { ExitEvents } from './exit-events.js';
|
|
48
|
-
import { encodeRunRow, familyRootOf, isLiveRecord,
|
|
42
|
+
import { encodeRunRow, familyRootOf, isLiveRecord, materializedWorktreePath, newestFirst } from './run-row.js';
|
|
49
43
|
import { RunRetentionTopic } from './run-retention.js';
|
|
50
44
|
import { collectRawExtras, encodeRawRecord } from './raw-record.js';
|
|
51
45
|
import { ColdReadCache, storedRow } from './cold-reads.js';
|
|
52
|
-
import {
|
|
46
|
+
import { LEGACY_INDEX_FILE, LegacyWriterError } from './legacy-index.js';
|
|
53
47
|
import { toRunStoreOpenError } from './store-open-error.js';
|
|
54
|
-
import {
|
|
55
|
-
import {
|
|
48
|
+
import { importLegacyIndex, OPEN_RETRY_DELAYS_MS, sleepSync } from './store-open.js';
|
|
49
|
+
import { RunClaimsTopic, RunWriteRefusedError } from './run-claims-topic.js';
|
|
50
|
+
import { RunPinsTopic } from './run-pins.js';
|
|
56
51
|
import { createStoreOwnedRun } from './owned-run-create.js';
|
|
57
52
|
import { WorkerResultsTopic } from './worker-results.js';
|
|
58
53
|
import { RunEventLogTopic } from './event-log.js';
|
|
59
54
|
import { RunRedaction } from './run-redaction.js';
|
|
60
|
-
import {
|
|
55
|
+
import { RunArchiveTopic } from './run-archive.js';
|
|
56
|
+
import { RunReadFlagsTopic } from './run-read-flags.js';
|
|
57
|
+
import { closeClaimSession, familyKey, openClaimSession, rowFamily } from './run-claims.js';
|
|
61
58
|
import { assertProjectWritable, projectWriteRefused } from '../server/cockpit-ownership.js';
|
|
62
59
|
/**
|
|
63
60
|
* A runner id as it may appear in a PERSISTED record (#547), spec 2026-11-18-runner-definitions.
|
|
@@ -180,150 +177,11 @@ export function decodeRunRecord(data) {
|
|
|
180
177
|
}
|
|
181
178
|
}
|
|
182
179
|
export { LEGACY_INDEX_BACKUP_FILE, LEGACY_INDEX_FILE } from './legacy-index.js';
|
|
183
|
-
/** The pauses between open attempts while the database is busy, when `open` may wait (a boot):
|
|
184
|
-
* about 3.5 s in all, with each attempt's own busy timeout. Long enough for another process to
|
|
185
|
-
* finish importing a large `runs.json`. */
|
|
186
|
-
const OPEN_RETRY_DELAYS_MS = [50, 100, 200, 400, 800, 1600];
|
|
187
|
-
/** Block this thread for `ms`. Only `open` does, at boot, when there is nothing else to run. */
|
|
188
|
-
function sleepSync(ms) {
|
|
189
|
-
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
|
|
190
|
-
}
|
|
191
180
|
/** How many archived root runs the run lists carry per project (#864): `GET /run-summaries?archived=recent`
|
|
192
181
|
* and `GET /workspace/runs-index`. Unarchived runs are never cut; older archived runs page in
|
|
193
182
|
* through `GET /run-summaries/archived` and the workspace search. */
|
|
194
183
|
export const ARCHIVED_WINDOW = 200;
|
|
195
|
-
/**
|
|
196
|
-
* Reconcile one record just read off disk with the fact that whichever process wrote it is gone.
|
|
197
|
-
*
|
|
198
|
-
* Mutates and returns `run`. Extracted from `RunStore.open` so the read-only index reader
|
|
199
|
-
* (`./run-index.ts`) answers the SAME question about a `running` row on disk. Two parsers that
|
|
200
|
-
* disagree here is a visible bug, not an internal one: the cockpit would show a task as running
|
|
201
|
-
* in the ⌘K index and failed the moment you opened it.
|
|
202
|
-
*
|
|
203
|
-
* `keepLive` (#367): leave `queued`/`running`/`waiting` untouched so the caller can recover them
|
|
204
|
-
* (RunManager.recover re-queues queued runs, resumes interrupted ones). Without it — one-shot CLI
|
|
205
|
-
* paths that never recover, and the index reader, which has no manager at all — live-looking runs
|
|
206
|
-
* are marked failed so no ghost stays behind.
|
|
207
|
-
*/
|
|
208
|
-
export function reconcileLoadedRun(run, opts) {
|
|
209
|
-
settleLoadedStop(run);
|
|
210
|
-
restoreLoadedUsageLimitHold(run);
|
|
211
|
-
failLoadedInterruptedRun(run, opts);
|
|
212
|
-
clearLoadedStaleResume(run);
|
|
213
|
-
restoreLostReferencedPullRequest(run, referencedPrDeclaration, resolveReferencedRef);
|
|
214
|
-
restoreOriginatingIssue(run);
|
|
215
|
-
// Repository scoping follows reconciliation: stores arm a handle asynchronously, while
|
|
216
|
-
// the read-only index applies its cached handle to these fresh records (#97). This ordering
|
|
217
|
-
// also scopes any referenced PR restored above without filtering candidate evidence first.
|
|
218
|
-
return run;
|
|
219
|
-
}
|
|
220
|
-
function clearLoadedStaleResume(run) {
|
|
221
|
-
// Recovery owns waits; a usage-limit appointment survives while status is waiting.
|
|
222
|
-
stageLoaded(run);
|
|
223
|
-
}
|
|
224
|
-
/**
|
|
225
|
-
* Settle an adopted dead owner’s live run without starting work. Untouched runs cancel; started
|
|
226
|
-
* runs become interrupted. Stop explicitly cancels its target. Mutates run.
|
|
227
|
-
*/
|
|
228
|
-
export function settleOrphanedRun(run, opts = {}) {
|
|
229
|
-
if (opts.stop && (run.status === 'queued' || run.status === 'running' || run.status === 'waiting'))
|
|
230
|
-
run.stopping = true;
|
|
231
|
-
if (run.status === 'queued' && !run.startedAt && run.workflowDef !== undefined &&
|
|
232
|
-
run.steps.every((step) => step.status === 'pending' && !step.startedAt && !step.sessionId)) {
|
|
233
|
-
Object.assign(run, applyExit(run, 'cancel'));
|
|
234
|
-
}
|
|
235
|
-
return reconcileLoadedRun(run, { keepLive: false });
|
|
236
|
-
}
|
|
237
|
-
/** Test seam (#779): `beforeTransaction` runs once `runs.json` is read and parsed, before the
|
|
238
|
-
* import asks for the write lock; `beforeCommit` runs inside the import transaction, after every
|
|
239
|
-
* row is written and before the last check that no older Squawk wrote `runs.json` meanwhile. */
|
|
240
|
-
let legacyImportHook;
|
|
241
|
-
export function __setLegacyImportHookForTests(hook) {
|
|
242
|
-
legacyImportHook = hook;
|
|
243
|
-
}
|
|
244
|
-
/**
|
|
245
|
-
* Import legacy rows and the completion marker atomically, once. Recheck live-writer evidence
|
|
246
|
-
* before commit and preserve exact input bytes in a synced backup. Leave runs.json untouched;
|
|
247
|
-
* invalid entries are skipped and reported.
|
|
248
|
-
*/
|
|
249
|
-
function importLegacyIndex(db, dataDir) {
|
|
250
|
-
assertNoLegacyCockpit(dataDir);
|
|
251
|
-
const snapshot = readLegacyIndex(join(dataDir, LEGACY_INDEX_FILE));
|
|
252
|
-
const parsed = snapshot ? legacyIndexRows(snapshot.bytes, parseRunRecords) : undefined;
|
|
253
|
-
const rows = parsed?.rows ?? [];
|
|
254
|
-
const skipped = parsed?.skipped ?? 0;
|
|
255
|
-
const source = !snapshot ? 'none' : parsed ? LEGACY_INDEX_FILE : `${LEGACY_INDEX_FILE} (unparseable)`;
|
|
256
|
-
assertNoLegacyWriter(dataDir, snapshot);
|
|
257
|
-
legacyImportHook?.beforeTransaction?.();
|
|
258
|
-
let backup;
|
|
259
|
-
const commit = db.transaction({
|
|
260
|
-
upserts: rows,
|
|
261
|
-
deletes: [],
|
|
262
|
-
onlyIfMetaAbsent: RUNS_IMPORT_COMPLETE_KEY,
|
|
263
|
-
beforeCommit: () => {
|
|
264
|
-
legacyImportHook?.beforeCommit?.();
|
|
265
|
-
assertNoLegacyWriter(dataDir, snapshot);
|
|
266
|
-
backup = snapshot ? backUpLegacyIndex(dataDir, snapshot) : undefined;
|
|
267
|
-
const read = snapshot ? { bytes: snapshot.bytes.length, sha256: snapshot.sha256, backup } : {};
|
|
268
|
-
return { [RUNS_IMPORT_COMPLETE_KEY]: JSON.stringify({ at: new Date().toISOString(), source, records: rows.length, ...(skipped > 0 ? { skipped } : {}), ...read }) };
|
|
269
|
-
},
|
|
270
|
-
});
|
|
271
|
-
// Told once, by the import that committed: the marker means no later open reads runs.json again.
|
|
272
|
-
if (commit.skipped || backup === undefined)
|
|
273
|
-
return;
|
|
274
|
-
const kept = `Its exact bytes are kept in ${join(dataDir, backup)}; https://github.com/hearsay-tools/squawk/blob/main/docs/run-history-recovery.md says how to import it after a repair.`;
|
|
275
|
-
if (!parsed)
|
|
276
|
-
console.warn(`[hsq] ${LEGACY_INDEX_FILE} could not be read; no run was imported, and this project starts with an empty history. ${kept}`);
|
|
277
|
-
else if (skipped > 0)
|
|
278
|
-
console.warn(`[hsq] ${skipped} of ${parsed.total} runs in ${LEGACY_INDEX_FILE} could not be read and were not imported. ${kept}`);
|
|
279
|
-
}
|
|
280
|
-
/**
|
|
281
|
-
* Finished rows whose stored summary an open-time normalization would still change: a referenced
|
|
282
|
-
* PR an older Squawk's created-PR declaration erased, or issue attribution displaced by a
|
|
283
|
-
* follow-up declaration (see `reconcileLoadedRun`), or a summary that is not JSON. Not live, so not
|
|
284
|
-
* in the `live` column; open decodes these few and keeps the ones it actually repaired.
|
|
285
|
-
*/
|
|
286
|
-
const LEGACY_REFERENCE_HEAL_SQL = guardedJsonSql("(json_extract(summary, '$.markerRefs.pr') IS NOT NULL AND json_extract(summary, '$.referencedPullRequestUrl') IS NULL)" +
|
|
287
|
-
" OR (NOT EXISTS (SELECT 1 FROM meta WHERE key = 'issue-attribution:' || runs.id AND value = CAST(runs.revision AS TEXT)) AND json_extract(summary, '$.markerRefs.issue') IS NOT NULL)", 1);
|
|
288
|
-
/**
|
|
289
|
-
* The rows whose stored summary reading their record can change, as SQL over `runs`: the rows
|
|
290
|
-
* `open` decodes to normalize (the `live` column it loads by, then `LEGACY_REFERENCE_HEAL_SQL`).
|
|
291
|
-
* With a repository handle, a row whose summary `namesForeignReference` is one too, as
|
|
292
|
-
* `setRepoHandle` reads it. The cold reader (run-index.ts) decodes exactly these rows and serves
|
|
293
|
-
* every other stored summary, so the two read paths cannot disagree about which rows to read.
|
|
294
|
-
* `AUTOMATION_ORIGIN_HEAL_SQL` is left out on purpose: no cross-project view reads
|
|
295
|
-
* `automationId`, and asking it scans `data`.
|
|
296
|
-
*/
|
|
297
|
-
export const LOAD_REPAIR_SQL = `live = 1 OR ${LEGACY_REFERENCE_HEAL_SQL}`;
|
|
298
|
-
/**
|
|
299
|
-
* Rows whose record names the automation that launched it while the stored summary does not
|
|
300
|
-
* (hearsay-tools/cezarion#1332): summaries a Squawk wrote before `RunSummary.automationId`
|
|
301
|
-
* existed. Open rewrites each one's summary once, so the sidebar's Automations tab classifies a
|
|
302
|
-
* finished task nobody has opened since the upgrade. `instr` keeps the JSON parse off every
|
|
303
|
-
* other row.
|
|
304
|
-
*/
|
|
305
|
-
const AUTOMATION_ORIGIN_HEAL_SQL = `instr(data, '"automation') > 0 AND ${guardedJsonSql("json_extract(summary, '$.automationId') IS NULL" +
|
|
306
|
-
" AND (json_extract(data, '$.automation.automationId') IS NOT NULL OR json_extract(data, '$.automationTrigger.automationId') IS NOT NULL)", 0, ['summary', 'data'])}`;
|
|
307
184
|
export { branchOwnerOf } from './branch-owners.js';
|
|
308
|
-
/** The one answer every control gives for a run another Squawk process owns (`409 { error }`). */
|
|
309
|
-
export const RUN_IN_USE_ELSEWHERE = `run is in use by another Squawk process`;
|
|
310
|
-
/** The answer for a run this process stopped writing after a conflicting write. */
|
|
311
|
-
export const RUN_QUARANTINED = `run changed under this Squawk process — restart Squawk to reload it`;
|
|
312
|
-
/** A write this store must not make: another process owns the run, its owner died with work
|
|
313
|
-
* still live (adopt it first), or a conflict quarantined it. Nothing was changed. */
|
|
314
|
-
export class RunWriteRefusedError extends Error {
|
|
315
|
-
runId;
|
|
316
|
-
ownership;
|
|
317
|
-
constructor(runId, ownership, fallbackError) {
|
|
318
|
-
super(ownership === 'fallback' ? fallbackError ?? `run ${runId} is read only in the fallback project directory`
|
|
319
|
-
: ownership === 'quarantined' ? `${RUN_QUARANTINED}: ${runId}`
|
|
320
|
-
: ownership === 'orphaned' ? `run ${runId} belongs to a Squawk process that exited; take it over before writing it`
|
|
321
|
-
: `${RUN_IN_USE_ELSEWHERE}: ${runId}`);
|
|
322
|
-
this.runId = runId;
|
|
323
|
-
this.ownership = ownership;
|
|
324
|
-
this.name = 'RunWriteRefusedError';
|
|
325
|
-
}
|
|
326
|
-
}
|
|
327
185
|
/** Make `target` hold exactly `source`'s fields, keeping the object every holder references. */
|
|
328
186
|
function replaceRecord(target, source) {
|
|
329
187
|
for (const key of Object.keys(target))
|
|
@@ -439,8 +297,10 @@ export class RunStore {
|
|
|
439
297
|
/** Rows whose `data` this store tried to decode and could not: left in the database untouched,
|
|
440
298
|
* and left out of the list rows from then on, as the cold reader leaves them out (run-index.ts). */
|
|
441
299
|
unreadable = new Set();
|
|
442
|
-
/**
|
|
443
|
-
|
|
300
|
+
/** The archive flag, archive on merge, completion actions and the transcript compressor (hearsay-tools/squawk#4041). */
|
|
301
|
+
archive;
|
|
302
|
+
/** The pinned and read flags (hearsay-tools/squawk#4041). */
|
|
303
|
+
readFlags;
|
|
444
304
|
/** What the transcript says about a run (hearsay-tools/squawk#4036). */
|
|
445
305
|
transcriptFacts;
|
|
446
306
|
/** Whether a run may go, and its deletion; the count-based archive (hearsay-tools/squawk#4037). */
|
|
@@ -451,13 +311,17 @@ export class RunStore {
|
|
|
451
311
|
eventLog;
|
|
452
312
|
/** The scrub of events and free text (hearsay-tools/squawk#4040). */
|
|
453
313
|
redaction;
|
|
314
|
+
/** Claims, ownership, sources and fallback (hearsay-tools/squawk#4042). */
|
|
315
|
+
claims;
|
|
316
|
+
/** The holds that keep a run loaded (hearsay-tools/squawk#4042). */
|
|
317
|
+
runPins;
|
|
454
318
|
executions;
|
|
455
319
|
/** A worker's execution, process, identity and scope records (hearsay-tools/squawk#4039), built on
|
|
456
320
|
* first use by the factory this process registered; throws when none is registered. */
|
|
457
321
|
get workerExecutions() {
|
|
458
322
|
return this.executions ??= workerExecutionsFactory()(this.dataDir, {
|
|
459
|
-
peek: (id) => this.peek(id), getRun: (id) => this.getRun(id), writeDir: (id) => this.writeDir(id),
|
|
460
|
-
sourceDataDir: (id) => this.sourceDataDir(id), commitIndex: (input) => this.commitIndex(input),
|
|
323
|
+
peek: (id) => this.peek(id), getRun: (id) => this.getRun(id), writeDir: (id) => this.claims.writeDir(id),
|
|
324
|
+
sourceDataDir: (id) => this.claims.sourceDataDir(id), commitIndex: (input) => this.commitIndex(input),
|
|
461
325
|
published: this.published, workerResults: this.workerResults,
|
|
462
326
|
});
|
|
463
327
|
}
|
|
@@ -469,9 +333,15 @@ export class RunStore {
|
|
|
469
333
|
constructor(dataDir) {
|
|
470
334
|
this.dataDir = dataDir;
|
|
471
335
|
this.redaction = new RunRedaction();
|
|
336
|
+
this.claims = new RunClaimsTopic(dataDir, {
|
|
337
|
+
db: () => this.db, owner: () => this.owner, keepLive: () => this.keepLive, held: this.held, base: this.base, dirty: this.dirty,
|
|
338
|
+
deleted: this.deleted, quarantined: this.quarantined, unreadable: this.unreadable, claimed: this.claimed, pendingClaims: this.pendingClaims,
|
|
339
|
+
exitEvents: this.exitEvents, coldReads: this.coldReads, decodeRunRow, anchoredFamilies: () => this.anchoredFamilies(), scheduleSave: () => this.scheduleSave(),
|
|
340
|
+
});
|
|
341
|
+
this.runPins = new RunPinsTopic({ pins: this.pins, published: this.published, record: (id) => this.record(id), peek: (id) => this.peek(id), sweepIfSettled: (ids) => this.sweepIfSettled(ids) });
|
|
472
342
|
this.transcriptFacts = new RunTranscriptFacts(dataDir, {
|
|
473
|
-
isFallbackRun: (id) => this.isFallbackRun(id),
|
|
474
|
-
sourceDataDir: (id) => this.sourceDataDir(id),
|
|
343
|
+
isFallbackRun: (id) => this.claims.isFallbackRun(id),
|
|
344
|
+
sourceDataDir: (id) => this.claims.sourceDataDir(id),
|
|
475
345
|
isOpen: () => this.db !== null,
|
|
476
346
|
held: this.held,
|
|
477
347
|
listFamilyRunIds: (rootId) => this.listFamilyRunIds(rootId),
|
|
@@ -479,26 +349,26 @@ export class RunStore {
|
|
|
479
349
|
listRunIds: () => this.listRunIds(),
|
|
480
350
|
});
|
|
481
351
|
this.workerResults = new WorkerResultsTopic(dataDir, {
|
|
482
|
-
peek: (id) => this.peek(id), hasRun: (id) => this.hasRun(id), hasFallbackRun: (id) => this.hasFallbackRun(id),
|
|
483
|
-
writeDir: (id) => this.writeDir(id), sourceDataDir: (id) => this.sourceDataDir(id),
|
|
352
|
+
peek: (id) => this.peek(id), hasRun: (id) => this.hasRun(id), hasFallbackRun: (id) => this.claims.hasFallbackRun(id),
|
|
353
|
+
writeDir: (id) => this.claims.writeDir(id), sourceDataDir: (id) => this.claims.sourceDataDir(id),
|
|
484
354
|
redactResult: (result) => this.redaction.redact({ type: 'worker-result', seq: 0, ts: result.observedAt, result }).result,
|
|
485
355
|
redactText: (text) => this.redaction.redactText(text), commitDelegation: (patches) => this.commitDelegation(patches),
|
|
486
356
|
});
|
|
487
357
|
this.eventLog = new RunEventLogTopic(dataDir, {
|
|
488
358
|
seqs: this.seqs, published: this.published, liveItems: this.liveItems, transcriptFacts: this.transcriptFacts, redaction: this.redaction,
|
|
489
|
-
record: (id) => this.record(id), missingRunError: (runId) => this.missingRunError(runId), sourceDataDir: (id) => this.sourceDataDir(id),
|
|
359
|
+
record: (id) => this.record(id), missingRunError: (runId) => this.claims.missingRunError(runId), sourceDataDir: (id) => this.claims.sourceDataDir(id),
|
|
490
360
|
touch: (run, before) => this.touch(run, before), change: (id, apply) => this.change(id, apply), repoHandle: () => this.repoHandle,
|
|
491
|
-
maybeEnqueueHistoryCompress: (run) => this.maybeEnqueueHistoryCompress(run),
|
|
361
|
+
maybeEnqueueHistoryCompress: (run) => this.archive.maybeEnqueueHistoryCompress(run),
|
|
492
362
|
});
|
|
493
363
|
this.retention = new RunRetentionTopic(dataDir, {
|
|
494
364
|
db: () => this.db, held: this.held, deleted: this.deleted, quarantined: this.quarantined,
|
|
495
365
|
historyOwed: this.historyOwed, seqs: this.seqs, published: this.published, transcriptFacts: this.transcriptFacts,
|
|
496
366
|
peek: (id) => this.peek(id), hasRun: (id) => this.hasRun(id), record: (id) => this.record(id),
|
|
497
|
-
listWorkersOf: (parentId) => this.listWorkersOf(parentId), isFallbackRun: (id) => this.isFallbackRun(id),
|
|
498
|
-
hasFallbackRun: (id) => this.hasFallbackRun(id), listOrder: (run) => this.listOrder(run),
|
|
499
|
-
claimFamilies: (families) => this.claimFamilies(families), markDeleted: (id, family) => this.markDeleted(id, family),
|
|
367
|
+
listWorkersOf: (parentId) => this.listWorkersOf(parentId), isFallbackRun: (id) => this.claims.isFallbackRun(id),
|
|
368
|
+
hasFallbackRun: (id) => this.claims.hasFallbackRun(id), listOrder: (run) => this.listOrder(run),
|
|
369
|
+
claimFamilies: (families) => this.claims.claimFamilies(families), markDeleted: (id, family) => this.markDeleted(id, family),
|
|
500
370
|
scheduleSave: () => this.scheduleSave(), commitIndex: (input) => this.commitIndex(input),
|
|
501
|
-
commitDelegation: (patches) => this.commitDelegation(patches), applyArchived: (run, archived) => this.applyArchived(run, archived),
|
|
371
|
+
commitDelegation: (patches) => this.commitDelegation(patches), applyArchived: (run, archived) => this.archive.applyArchived(run, archived),
|
|
502
372
|
workerDeletionEvidence: (id) => this.workerExecutions.workerDeletionEvidence(id),
|
|
503
373
|
workerResults: this.workerResults,
|
|
504
374
|
readWorkerExecution: (id) => this.workerExecutions.readWorkerExecution(id), identityPath: (id) => this.workerExecutions.identityPath(id),
|
|
@@ -506,7 +376,22 @@ export class RunStore {
|
|
|
506
376
|
executionPath: (id) => this.workerExecutions.executionPath(id), handoffPath: (runId) => this.handoffPath(runId),
|
|
507
377
|
imagesDir: (runId) => this.imagesDir(runId),
|
|
508
378
|
});
|
|
509
|
-
this.
|
|
379
|
+
this.archive = new RunArchiveTopic(dataDir, {
|
|
380
|
+
db: () => this.db, held: this.held, deleted: this.deleted, quarantined: this.quarantined, pins: this.pins,
|
|
381
|
+
claimed: this.claimed, base: this.base, owner: () => this.owner, transcriptFacts: this.transcriptFacts,
|
|
382
|
+
decodeRunRow, sortNewestFirst, peek: (id) => this.peek(id), record: (id) => this.record(id),
|
|
383
|
+
listWorkersOf: (parentId) => this.listWorkersOf(parentId), familyOf: (id) => this.familyOf(id),
|
|
384
|
+
claimFamilies: (families, opts) => this.claims.claimFamilies(families, opts), writeRefusal: (id) => this.claims.writeRefusal(id),
|
|
385
|
+
assertWritable: (staged) => this.assertWritable(staged), decodeCold: (row) => this.decodeCold(row),
|
|
386
|
+
listOrder: (run) => this.listOrder(run), commitIndex: (input, source, write) => this.commitIndex(input, source, write),
|
|
387
|
+
touch: (run, before, exit) => this.touch(run, before, exit),
|
|
388
|
+
readWorkerExecution: (id) => this.workerExecutions.readWorkerExecution(id),
|
|
389
|
+
});
|
|
390
|
+
this.readFlags = new RunReadFlagsTopic({
|
|
391
|
+
db: () => this.db, held: this.held, deleted: this.deleted, record: (id) => this.record(id),
|
|
392
|
+
claimFamilies: (families) => this.claims.claimFamilies(families), touch: (run, before) => this.touch(run, before),
|
|
393
|
+
change: (id, apply) => this.change(id, apply),
|
|
394
|
+
});
|
|
510
395
|
}
|
|
511
396
|
/**
|
|
512
397
|
* Open the project's run store. See `reconcileLoadedRun` for what `keepLive` (#367) decides
|
|
@@ -555,13 +440,13 @@ export class RunStore {
|
|
|
555
440
|
if (deferred)
|
|
556
441
|
db.transaction({ upserts: [], deletes: [], meta: { [RUNS_IMPORT_COMPLETE_KEY]: 'none' } });
|
|
557
442
|
else if (db.getMeta(RUNS_IMPORT_COMPLETE_KEY) === undefined)
|
|
558
|
-
importLegacyIndex(db, dataDir);
|
|
443
|
+
importLegacyIndex(db, dataDir, parseRunRecords);
|
|
559
444
|
if (source)
|
|
560
445
|
db = addRunSource(db, dataDir, source);
|
|
561
446
|
store.db = db;
|
|
562
447
|
store.owner = openClaimSession();
|
|
563
448
|
if (!maintenance) {
|
|
564
|
-
store.loadHeldRows();
|
|
449
|
+
store.claims.loadHeldRows();
|
|
565
450
|
store.transcriptFacts.warmTranscriptFacts();
|
|
566
451
|
store.exitEvents.writeLoaded();
|
|
567
452
|
}
|
|
@@ -600,218 +485,6 @@ export class RunStore {
|
|
|
600
485
|
/** Why this store has no database, when it is `RunStore.unavailable`'s: its runs are unknown,
|
|
601
486
|
* not absent. */
|
|
602
487
|
get unavailable() { return this.openFailure; }
|
|
603
|
-
/** Every sidecar for a run follows the winning record, never file-by-file fallback. */
|
|
604
|
-
sourceDataDir(id) { return this.isFallbackRun(id) ? dataReadDirs(this.dataDir)[1] : runDataDir(this.dataDir, id); }
|
|
605
|
-
isFallbackRun(id) { return this.db?.isFallback(id) ?? false; }
|
|
606
|
-
hasFallbackRun(id) { return this.db?.hasFallback(id) ?? false; }
|
|
607
|
-
/**
|
|
608
|
-
* Open-time load: the live rows, the finished rows a load normalization repairs, then the
|
|
609
|
-
* delegation families of the live ones. A row that does not parse is skipped and left in the
|
|
610
|
-
* database untouched; one warning says how many.
|
|
611
|
-
*
|
|
612
|
-
* Only rows this store can claim are loaded (#779, plan step 3). A live row whose family another
|
|
613
|
-
* live process claims — `serve`'s parked run, seen by a headless `cez run` — is that process's:
|
|
614
|
-
* it is not loaded, normalized or recovered here, and stays readable through `getRun` and the
|
|
615
|
-
* list rows. A live row nobody alive claims is taken over, as before: this open recovers it
|
|
616
|
-
* (`keepLive`) or settles it as interrupted.
|
|
617
|
-
*/
|
|
618
|
-
loadHeldRows() {
|
|
619
|
-
let unreadable = 0;
|
|
620
|
-
const decode = (row) => {
|
|
621
|
-
const decoded = decodeRunRow(row.data);
|
|
622
|
-
if (!decoded) {
|
|
623
|
-
unreadable++;
|
|
624
|
-
this.unreadable.add(row.id);
|
|
625
|
-
}
|
|
626
|
-
return decoded;
|
|
627
|
-
};
|
|
628
|
-
const live = this.db.listLive();
|
|
629
|
-
const owned = this.claimFamilies(live.map(rowFamily), { allowLive: true, wait: true });
|
|
630
|
-
for (const row of live) {
|
|
631
|
-
if (!owned.has(rowFamily(row)))
|
|
632
|
-
continue;
|
|
633
|
-
const decoded = decode(row);
|
|
634
|
-
if (decoded)
|
|
635
|
-
this.adoptLoadedRun(decoded, { keepLive: this.keepLive }, row);
|
|
636
|
-
}
|
|
637
|
-
const heal = this.db.listWhere(LEGACY_REFERENCE_HEAL_SQL).filter((row) => !this.held.has(row.id));
|
|
638
|
-
const healable = this.claimFamilies(heal.map(rowFamily));
|
|
639
|
-
for (const row of heal) {
|
|
640
|
-
if (!healable.has(rowFamily(row)))
|
|
641
|
-
continue;
|
|
642
|
-
const decoded = decode(row);
|
|
643
|
-
// Held only when the repair changed it: the next save writes it, then it leaves.
|
|
644
|
-
if (decoded) {
|
|
645
|
-
// Persist verification once even when legacy issue attribution was already correct.
|
|
646
|
-
const needsIssueCheck = decoded.run.markerRefs?.issue !== undefined &&
|
|
647
|
-
this.db.getMeta(`issue-attribution:${row.id}`) !== String(row.revision);
|
|
648
|
-
this.adoptLoadedRun(decoded, { keepLive: this.keepLive, onlyIfChanged: !needsIssueCheck }, row);
|
|
649
|
-
if (needsIssueCheck)
|
|
650
|
-
this.dirty.add(row.id);
|
|
651
|
-
}
|
|
652
|
-
}
|
|
653
|
-
const stale = this.db.listWhere(AUTOMATION_ORIGIN_HEAL_SQL).filter((row) => !this.held.has(row.id));
|
|
654
|
-
const restamp = this.claimFamilies(stale.map(rowFamily));
|
|
655
|
-
for (const row of stale) {
|
|
656
|
-
if (!restamp.has(rowFamily(row)))
|
|
657
|
-
continue;
|
|
658
|
-
const decoded = decode(row);
|
|
659
|
-
// Nothing in the record changes, only its summary: held dirty, the next save rewrites it.
|
|
660
|
-
if (decoded) {
|
|
661
|
-
this.adoptLoadedRun(decoded, { keepLive: this.keepLive }, row);
|
|
662
|
-
this.dirty.add(row.id);
|
|
663
|
-
}
|
|
664
|
-
}
|
|
665
|
-
for (const rootId of this.anchoredFamilies())
|
|
666
|
-
this.holdFamily(rootId, decode);
|
|
667
|
-
this.releaseUnheldClaims();
|
|
668
|
-
if (unreadable > 0)
|
|
669
|
-
console.warn(`[hsq] ${unreadable} run(s) in ${RUNS_DB_FILE} could not be read; they are left in the database untouched.`);
|
|
670
|
-
}
|
|
671
|
-
/** Normalize a record just read from `row` (see `reconcileLoadedRun`) and hold it. Marks the row
|
|
672
|
-
* dirty only when normalization changed it, so the next save persists exactly the runs open()
|
|
673
|
-
* rewrote. A row read up from schema-3 wait fields counts as changed: its rewrite drops them
|
|
674
|
-
* and recomputes its summary and live column (`upgradeLegacyWaits`), as does a summary that does
|
|
675
|
-
* not parse (hearsay-tools/squawk#3530). The caller has claimed the row's family. */
|
|
676
|
-
adoptLoadedRun({ run, extras, upgraded }, opts, row) {
|
|
677
|
-
if (this.db?.familyHasFallback(rowFamily(row)))
|
|
678
|
-
return;
|
|
679
|
-
// Serialized, so a key set to `undefined` reads as the absent key it is once written.
|
|
680
|
-
const before = JSON.stringify(run);
|
|
681
|
-
const wasCancelled = run.status === 'cancelled';
|
|
682
|
-
if (opts.settle)
|
|
683
|
-
settleOrphanedRun(run, { stop: opts.stop });
|
|
684
|
-
else
|
|
685
|
-
reconcileLoadedRun(run, opts);
|
|
686
|
-
const changed = upgraded === true || JSON.stringify(run) !== before || parseStoredSummary(row.summary) === undefined;
|
|
687
|
-
if (opts.onlyIfChanged && !changed)
|
|
688
|
-
return;
|
|
689
|
-
this.held.set(run.id, run);
|
|
690
|
-
this.base.set(run.id, { revision: row.revision, seq: row.seq, data: row.data, extras });
|
|
691
|
-
if (changed)
|
|
692
|
-
this.dirty.add(run.id);
|
|
693
|
-
if (!wasCancelled && run.status === 'cancelled')
|
|
694
|
-
this.exitEvents.loadCancelled(run.id);
|
|
695
|
-
}
|
|
696
|
-
/**
|
|
697
|
-
* Hold one delegation family: its root and every worker filed under it, read through the
|
|
698
|
-
* `parent_run_id` index. No recursion: a worker's own id never names a family. The caller has claimed it. `settle` settles its live rows instead of keeping
|
|
699
|
-
* them for recovery (`settleOrphanedRun`); `stopId` is the run a Stop settles as cancelled.
|
|
700
|
-
*/
|
|
701
|
-
holdFamily(rootId, decode = (row) => decodeRunRow(row.data), settle = false, stopId) {
|
|
702
|
-
const rows = [this.db.get(rootId), ...this.db.listByParent(rootId)];
|
|
703
|
-
for (const row of rows) {
|
|
704
|
-
if (!row || this.held.has(row.id) || this.deleted.has(row.id))
|
|
705
|
-
continue;
|
|
706
|
-
const decoded = decode(row);
|
|
707
|
-
if (decoded)
|
|
708
|
-
this.adoptLoadedRun(decoded, { keepLive: this.keepLive, settle, stop: row.id === stopId }, row);
|
|
709
|
-
}
|
|
710
|
-
}
|
|
711
|
-
/** Make sure this store claims each of `families`; `claimStoreFamilies` takes the free ones. */
|
|
712
|
-
claimFamilies(families, opts = {}) {
|
|
713
|
-
return projectWriteRefused(this.dataDir) ? new Set() : claimStoreFamilies({
|
|
714
|
-
claimed: this.claimed,
|
|
715
|
-
pendingClaims: this.pendingClaims,
|
|
716
|
-
db: this.db,
|
|
717
|
-
owner: this.owner,
|
|
718
|
-
scheduleSave: () => this.scheduleSave(),
|
|
719
|
-
}, families, opts);
|
|
720
|
-
}
|
|
721
|
-
/** Release the claim of every family with nothing left in memory, once nothing is pending: a
|
|
722
|
-
* failed save keeps its families claimed until it succeeds. A failed release retries at the
|
|
723
|
-
* next sweep; `close()` releases the rest. */
|
|
724
|
-
releaseUnheldClaims() {
|
|
725
|
-
if (!this.db || !this.owner || this.dirty.size > 0 || this.deleted.size > 0)
|
|
726
|
-
return;
|
|
727
|
-
const kept = new Set();
|
|
728
|
-
for (const run of this.held.values())
|
|
729
|
-
kept.add(familyKey(run));
|
|
730
|
-
// A claim never taken has nothing to release in the database.
|
|
731
|
-
for (const family of this.pendingClaims.keys())
|
|
732
|
-
if (!kept.has(family))
|
|
733
|
-
this.pendingClaims.delete(family);
|
|
734
|
-
const released = [...this.claimed.keys()].filter((family) => !kept.has(family));
|
|
735
|
-
if (released.length === 0)
|
|
736
|
-
return;
|
|
737
|
-
try {
|
|
738
|
-
this.db.releaseClaims(this.owner.session, released);
|
|
739
|
-
for (const family of released)
|
|
740
|
-
this.claimed.delete(family);
|
|
741
|
-
}
|
|
742
|
-
catch {
|
|
743
|
-
// Busy or failing: the next sweep tries again.
|
|
744
|
-
}
|
|
745
|
-
}
|
|
746
|
-
/**
|
|
747
|
-
* Who may change this run right now (see `RunOwnership`), or undefined when there is no such
|
|
748
|
-
* run. Read-only: nothing is claimed. Controls ask this first, so a run another process owns is
|
|
749
|
-
* refused with `RUN_IN_USE_ELSEWHERE` and a dead process's run is adopted before it is changed.
|
|
750
|
-
*/
|
|
751
|
-
runOwnership(id) {
|
|
752
|
-
if (this.quarantined.has(id))
|
|
753
|
-
return 'quarantined';
|
|
754
|
-
const held = this.held.get(id);
|
|
755
|
-
if (!this.db)
|
|
756
|
-
return held ? 'held' : undefined;
|
|
757
|
-
const family = held ? familyKey(held) : this.deleted.has(id) ? undefined : this.db.familyOf(id);
|
|
758
|
-
if (family === undefined)
|
|
759
|
-
return undefined;
|
|
760
|
-
if (this.db.familyHasFallback(family))
|
|
761
|
-
return 'fallback';
|
|
762
|
-
if (this.claimed.has(family) || this.pendingClaims.has(family))
|
|
763
|
-
return 'held';
|
|
764
|
-
const claim = this.db.getClaim(family);
|
|
765
|
-
if (claim && claimOwnerLive(claim))
|
|
766
|
-
return 'foreign';
|
|
767
|
-
// The same rule `claimFamilies` writes by: a dead owner left only settled runs → free.
|
|
768
|
-
return this.db.familyHasLive(family) ? 'orphaned' : 'free';
|
|
769
|
-
}
|
|
770
|
-
/** Why a control on this run must be refused here, or undefined when this store may change it. */
|
|
771
|
-
writeRefusal(id) {
|
|
772
|
-
const ownership = this.runOwnership(id);
|
|
773
|
-
if (ownership === 'quarantined')
|
|
774
|
-
return RUN_QUARANTINED;
|
|
775
|
-
if (ownership === 'fallback')
|
|
776
|
-
return this.fallbackRefusal(id).message;
|
|
777
|
-
return ownership === 'foreign' || ownership === 'orphaned' ? RUN_IN_USE_ELSEWHERE : undefined;
|
|
778
|
-
}
|
|
779
|
-
/**
|
|
780
|
-
* Claim an orphaned family before a control, then settle its live rows.
|
|
781
|
-
* Stop cancels its target. Return the root id, or undefined for a live owner or missing run.
|
|
782
|
-
*/
|
|
783
|
-
adoptFamily(id, opts = {}) {
|
|
784
|
-
const family = this.db?.familyOf(id);
|
|
785
|
-
if (family === undefined || !this.claimFamilies([family], { allowLive: true, wait: true }).has(family))
|
|
786
|
-
return undefined;
|
|
787
|
-
this.holdFamily(family, undefined, true, opts.stop ? id : undefined);
|
|
788
|
-
this.exitEvents.writeLoaded();
|
|
789
|
-
return family;
|
|
790
|
-
}
|
|
791
|
-
/** Explicit controls only (`requireRunControl`): copy a fallback family in so it can be written. */
|
|
792
|
-
adoptFallbackFamily(id) {
|
|
793
|
-
const members = copyFallbackFamily(this.db, id, this.owner);
|
|
794
|
-
for (const member of members)
|
|
795
|
-
this.coldReads.forget(member);
|
|
796
|
-
return members.length > 0;
|
|
797
|
-
}
|
|
798
|
-
fallbackRefusal(id) { return new RunWriteRefusedError(id, 'fallback', fallbackRunDeleteError(this.dataDir, true)); }
|
|
799
|
-
/** Run files are written only for a family this store may write, never a fallback family. */
|
|
800
|
-
/** The error `appendEvent` throws for a run this store cannot write or does not know. */
|
|
801
|
-
missingRunError(runId) {
|
|
802
|
-
const ownership = this.runOwnership(runId);
|
|
803
|
-
if (ownership === 'fallback')
|
|
804
|
-
return this.fallbackRefusal(runId);
|
|
805
|
-
if (ownership === 'foreign' || ownership === 'orphaned' || ownership === 'quarantined')
|
|
806
|
-
return new RunWriteRefusedError(runId, ownership);
|
|
807
|
-
return new Error(`unknown run: ${runId}`);
|
|
808
|
-
}
|
|
809
|
-
writeDir(id) { if (this.runOwnership(id) === 'fallback')
|
|
810
|
-
throw this.fallbackRefusal(id); return runDataDir(this.dataDir, id); }
|
|
811
|
-
/** Every run whose family another process owns (`foreignClaimedRunIds`). */
|
|
812
|
-
listForeignClaimedRunIds() { return foreignClaimedRunIds(this.db, this.owner); }
|
|
813
|
-
/** Non-terminal rows in the database (both directories) and the runs of families another live store claims. */
|
|
814
|
-
persistedLiveRunIds() { return { live: this.db?.listLive().map((row) => row.id) ?? [], foreign: liveForeignClaimedRunIds(this.db, this.owner) }; }
|
|
815
488
|
/**
|
|
816
489
|
* Whether a held run anchors itself (and its family) in memory. Anything else held is a family
|
|
817
490
|
* member or a settled write, and leaves at the next sweep (`evictSettled`).
|
|
@@ -856,7 +529,7 @@ export class RunStore {
|
|
|
856
529
|
this.base.delete(id);
|
|
857
530
|
this.coldReads.forget(id);
|
|
858
531
|
}
|
|
859
|
-
this.releaseUnheldClaims();
|
|
532
|
+
this.claims.releaseUnheldClaims();
|
|
860
533
|
}
|
|
861
534
|
/** A run read from `runs.db`, normalized like a loaded one (`reconcileLoadedRun`, then the
|
|
862
535
|
* repository scope) but held by nobody. Undefined when absent, deleted or unreadable. */
|
|
@@ -905,7 +578,7 @@ export class RunStore {
|
|
|
905
578
|
if (held)
|
|
906
579
|
return held;
|
|
907
580
|
const family = this.db && !this.deleted.has(id) ? this.db.familyOf(id) : undefined;
|
|
908
|
-
if (family === undefined || !this.claimFamilies([family]).has(family))
|
|
581
|
+
if (family === undefined || !this.claims.claimFamilies([family]).has(family))
|
|
909
582
|
return undefined;
|
|
910
583
|
const run = this.coldReads.claimed(id, this.coldBase.get(id), () => this.db?.revisionOf(id)) ?? this.loadCold(id);
|
|
911
584
|
if (!run)
|
|
@@ -959,38 +632,6 @@ export class RunStore {
|
|
|
959
632
|
hasRun(id) {
|
|
960
633
|
return this.held.has(id) || (!!this.db && !this.deleted.has(id) && this.db.has(id));
|
|
961
634
|
}
|
|
962
|
-
/**
|
|
963
|
-
* Keep a run in memory for `holder` until `unpin(id, holder)`: a RunManager pins the runs it is
|
|
964
|
-
* executing (`active`) and the run a Continue is admitting (`continue`). A finished run is
|
|
965
|
-
* loaded. Pins are per holder, so releasing one never releases another. Returns the held record.
|
|
966
|
-
*/
|
|
967
|
-
pin(id, holder) {
|
|
968
|
-
const run = this.record(id);
|
|
969
|
-
if (!run)
|
|
970
|
-
return undefined;
|
|
971
|
-
let holders = this.pins.get(id);
|
|
972
|
-
if (!holders)
|
|
973
|
-
this.pins.set(id, holders = new Set());
|
|
974
|
-
holders.add(holder);
|
|
975
|
-
return run;
|
|
976
|
-
}
|
|
977
|
-
/** Publish a run's current record again without a write: something read beside the record
|
|
978
|
-
* changed, such as the run leaving the manager's live registries, which a detail's finish
|
|
979
|
-
* verdict reads (hearsay-tools/cezarion#1301). */
|
|
980
|
-
republish(id) {
|
|
981
|
-
const run = this.peek(id);
|
|
982
|
-
if (run)
|
|
983
|
-
this.published.publish('run.updated', { run, before: snapshotRun(run), source: 'live-release' });
|
|
984
|
-
}
|
|
985
|
-
/** Release `holder`'s pin. The run leaves memory at the next sweep once nothing else holds it. */
|
|
986
|
-
unpin(id, holder) {
|
|
987
|
-
const holders = this.pins.get(id);
|
|
988
|
-
if (!holders?.delete(holder))
|
|
989
|
-
return;
|
|
990
|
-
if (holders.size === 0)
|
|
991
|
-
this.pins.delete(id);
|
|
992
|
-
this.sweepIfSettled([id]);
|
|
993
|
-
}
|
|
994
635
|
/**
|
|
995
636
|
* Set discovered repository identity without blocking boot. Recompute conclusions from retained
|
|
996
637
|
* evidence, including cold records; null retains unknown-handle behavior.
|
|
@@ -1016,7 +657,7 @@ export class RunStore {
|
|
|
1016
657
|
}
|
|
1017
658
|
}
|
|
1018
659
|
// Only rows this store may write: another process's runs heal when their owner arms its handle.
|
|
1019
|
-
const writable = this.claimFamilies(stored.map(rowFamily));
|
|
660
|
+
const writable = this.claims.claimFamilies(stored.map(rowFamily));
|
|
1020
661
|
for (const row of stored) {
|
|
1021
662
|
if (!writable.has(rowFamily(row)))
|
|
1022
663
|
continue;
|
|
@@ -1475,7 +1116,7 @@ export class RunStore {
|
|
|
1475
1116
|
throw this.openFailure;
|
|
1476
1117
|
const run = this.buildRun(input, randomUUID());
|
|
1477
1118
|
// A new family, so nobody else can hold it; claimed before anything (an NDJSON event) is written.
|
|
1478
|
-
if (this.db && !this.claimFamilies([run.id]).has(run.id))
|
|
1119
|
+
if (this.db && !this.claims.claimFamilies([run.id]).has(run.id))
|
|
1479
1120
|
throw new RunWriteRefusedError(run.id, 'foreign');
|
|
1480
1121
|
this.held.set(run.id, run);
|
|
1481
1122
|
this.retention.pruneOldRuns();
|
|
@@ -1801,7 +1442,7 @@ export class RunStore {
|
|
|
1801
1442
|
};
|
|
1802
1443
|
staged.set(id, next);
|
|
1803
1444
|
if (Object.prototype.hasOwnProperty.call(patch, 'archived'))
|
|
1804
|
-
this.syncTranscriptForm(id, next.archived);
|
|
1445
|
+
this.archive.syncTranscriptForm(id, next.archived);
|
|
1805
1446
|
if (conversation) {
|
|
1806
1447
|
const root = this.peek(conversation.rootId);
|
|
1807
1448
|
if (root?.delegation?.role !== 'root' || run.delegation.parentRunId !== root.id)
|
|
@@ -1831,8 +1472,8 @@ export class RunStore {
|
|
|
1831
1472
|
const exits = new Map(write.exits);
|
|
1832
1473
|
const staged = stageCommit(input, {
|
|
1833
1474
|
peek: id => this.peek(id),
|
|
1834
|
-
completionArchiveBlocker: run => this.completionArchiveBlocker(run),
|
|
1835
|
-
stageArchive: (staged, run, archived) => this.stageArchive(staged, run, archived, exits),
|
|
1475
|
+
completionArchiveBlocker: run => this.archive.completionArchiveBlocker(run),
|
|
1476
|
+
stageArchive: (staged, run, archived) => this.archive.stageArchive(staged, run, archived, exits),
|
|
1836
1477
|
});
|
|
1837
1478
|
const before = new Map([...staged].map(([id, next]) => [id, next ? write.before?.get(id) ?? snapshotRun(this.peek(id)) : undefined])), committed = new Map([...staged].map(([id, next]) => [id, snapshotRun(next ?? undefined)]));
|
|
1838
1479
|
if (!this.db)
|
|
@@ -1870,79 +1511,7 @@ export class RunStore {
|
|
|
1870
1511
|
}
|
|
1871
1512
|
for (const [id, next] of staged)
|
|
1872
1513
|
if (next?.archived)
|
|
1873
|
-
this.compressor.enqueue(id);
|
|
1874
|
-
}
|
|
1875
|
-
completionArchiveBlocker(root) {
|
|
1876
|
-
const family = [root, ...this.listWorkersOf(root.id)];
|
|
1877
|
-
for (const run of family) {
|
|
1878
|
-
const facts = this.transcriptFacts.factsFor(run.id).peek(run.id);
|
|
1879
|
-
if (!facts || !['done', 'review', 'failed', 'cancelled'].includes(run.status) || run.waits?.some(wait => wait.phase === 'open') ||
|
|
1880
|
-
run.hasPendingPermission || facts.pendingAsk !== undefined)
|
|
1881
|
-
return 'Task or worker work still needs attention. Open the task or archive manually.';
|
|
1882
|
-
if (run.delegation?.role === 'invalid' || (run.delegation?.role === 'worker' && this.workerExecutions.readWorkerExecution(run.id)?.phase !== 'complete'))
|
|
1883
|
-
return 'Worker execution has not settled. Open the worker or archive manually.';
|
|
1884
|
-
}
|
|
1885
|
-
return undefined;
|
|
1886
|
-
}
|
|
1887
|
-
/** One archive write for manual actions, merge observations, completion, and sweeps.
|
|
1888
|
-
* Archiving files history away; it never stops a process or removes a worktree. */
|
|
1889
|
-
stageArchive(staged, root, archived, exits) {
|
|
1890
|
-
const ids = root.delegation?.role === 'worker' ? [root.id] :
|
|
1891
|
-
[root.id, ...new Set([...(this.db?.listIdsByParent(root.id) ?? []), ...this.listWorkersOf(root.id).map(run => run.id)])];
|
|
1892
|
-
const now = new Date().toISOString();
|
|
1893
|
-
for (const id of ids) {
|
|
1894
|
-
const member = staged.get(id) ?? this.peek(id);
|
|
1895
|
-
if (!member)
|
|
1896
|
-
continue;
|
|
1897
|
-
if (!archived) {
|
|
1898
|
-
this.compressor.cancel(id);
|
|
1899
|
-
restoreHistory(this.dataDir, id);
|
|
1900
|
-
}
|
|
1901
|
-
const next = { ...member, archiveBlocker: undefined };
|
|
1902
|
-
const exit = archiveFields(next, archived, now);
|
|
1903
|
-
if (exit)
|
|
1904
|
-
exits?.set(id, exit);
|
|
1905
|
-
staged.set(id, next);
|
|
1906
|
-
}
|
|
1907
|
-
}
|
|
1908
|
-
/** A bounded persisted queue also covers projects without a live RunManager. */
|
|
1909
|
-
listCompletionCandidates(afterSeq = 0, limit = 32) {
|
|
1910
|
-
return this.db?.listCompletionCandidates(afterSeq, limit) ?? [];
|
|
1911
|
-
}
|
|
1912
|
-
canCompleteAction(id, token) {
|
|
1913
|
-
const run = this.record(id);
|
|
1914
|
-
return Boolean(run && run.status === 'done' && !run.archived && (run.autoMergePr || run.archiveWhenDone) &&
|
|
1915
|
-
run.completionAction?.id === token && run.completionAction.phase !== 'complete' && !this.writeRefusal(id));
|
|
1916
|
-
}
|
|
1917
|
-
claimCompletionAction(id, token) {
|
|
1918
|
-
if (!this.canCompleteAction(id, token))
|
|
1919
|
-
return false;
|
|
1920
|
-
const run = this.record(id);
|
|
1921
|
-
this.assertWritable(new Map([[id, run]]));
|
|
1922
|
-
// A normal write may defer its claim until the transaction. A remote mutation
|
|
1923
|
-
// needs the committed claim now, and must not act on a stale row read before it.
|
|
1924
|
-
const claim = this.db?.getClaim(familyKey(run));
|
|
1925
|
-
return Boolean(claim && claim.session === this.owner?.session &&
|
|
1926
|
-
claim.generation === this.claimed.get(familyKey(run)) &&
|
|
1927
|
-
this.db?.get(id)?.revision === this.base.get(id)?.revision);
|
|
1928
|
-
}
|
|
1929
|
-
completeAction(id, token, phase, message) {
|
|
1930
|
-
const run = this.record(id);
|
|
1931
|
-
if (!run || !this.canCompleteAction(id, token))
|
|
1932
|
-
return false;
|
|
1933
|
-
if (run.completionAction?.phase === phase && run.completionAction.message === message)
|
|
1934
|
-
return true;
|
|
1935
|
-
const next = { ...run, completionAction: { id: token, phase, ...(message ? { message } : {}) } };
|
|
1936
|
-
const staged = new Map([[id, next]]);
|
|
1937
|
-
if (phase === 'complete' && next.archiveWhenDone) {
|
|
1938
|
-
const blocker = this.completionArchiveBlocker(next);
|
|
1939
|
-
if (blocker)
|
|
1940
|
-
next.completionAction = { id: token, phase: 'blocked', message: blocker };
|
|
1941
|
-
else
|
|
1942
|
-
this.stageArchive(staged, next, true);
|
|
1943
|
-
}
|
|
1944
|
-
this.commitIndex(staged);
|
|
1945
|
-
return true;
|
|
1514
|
+
this.archive.compressor.enqueue(id);
|
|
1946
1515
|
}
|
|
1947
1516
|
/**
|
|
1948
1517
|
* Refuse (throwing, with nothing changed) a commit that stages a quarantined run, or a run whose
|
|
@@ -1961,11 +1530,11 @@ export class RunStore {
|
|
|
1961
1530
|
held.add(family);
|
|
1962
1531
|
}
|
|
1963
1532
|
// A run this store holds may move to a new family; any other row is claimed as a plain write.
|
|
1964
|
-
const owned = new Set([...this.claimFamilies(held, { allowLive: true }),
|
|
1965
|
-
...this.claimFamilies([...families.values()].filter((family) => !held.has(family)))]);
|
|
1533
|
+
const owned = new Set([...this.claims.claimFamilies(held, { allowLive: true }),
|
|
1534
|
+
...this.claims.claimFamilies([...families.values()].filter((family) => !held.has(family)))]);
|
|
1966
1535
|
for (const [id, family] of families) {
|
|
1967
1536
|
if (!owned.has(family))
|
|
1968
|
-
throw this.runOwnership(id) === 'fallback' ? this.fallbackRefusal(id) : new RunWriteRefusedError(id, this.runOwnership(id) === 'orphaned' ? 'orphaned' : 'foreign');
|
|
1537
|
+
throw this.claims.runOwnership(id) === 'fallback' ? this.claims.fallbackRefusal(id) : new RunWriteRefusedError(id, this.claims.runOwnership(id) === 'orphaned' ? 'orphaned' : 'foreign');
|
|
1969
1538
|
}
|
|
1970
1539
|
}
|
|
1971
1540
|
/** The family of a run this store knows: held, else its row; a run nowhere is its own. */
|
|
@@ -2032,7 +1601,7 @@ export class RunStore {
|
|
|
2032
1601
|
redact: (text) => this.redaction.redactText(text),
|
|
2033
1602
|
repoHandle: this.repoHandle,
|
|
2034
1603
|
restore: () => restoreHistory(this.dataDir, id),
|
|
2035
|
-
archive: (record, archived) => this.applyArchived(record, archived, before, exit),
|
|
1604
|
+
archive: (record, archived) => this.archive.applyArchived(record, archived, before, exit),
|
|
2036
1605
|
touch: (record) => this.touch(record, before, exit),
|
|
2037
1606
|
};
|
|
2038
1607
|
if (durability === 'committed') {
|
|
@@ -2066,268 +1635,6 @@ export class RunStore {
|
|
|
2066
1635
|
Object.assign(run, stepTotals(run.steps));
|
|
2067
1636
|
this.touch(run, before);
|
|
2068
1637
|
}
|
|
2069
|
-
listArchiveOnMergeCandidates(afterSeq = 0, limit = 32) {
|
|
2070
|
-
return this.db?.listArchiveOnMergeCandidates(afterSeq, limit) ?? [];
|
|
2071
|
-
}
|
|
2072
|
-
/** Use unnormalized persisted evidence: cold reads must not turn interrupted work into safety. */
|
|
2073
|
-
archiveFamily(id, isActive) {
|
|
2074
|
-
return archiveStoreFamily({
|
|
2075
|
-
db: this.db,
|
|
2076
|
-
held: this.held,
|
|
2077
|
-
deleted: this.deleted,
|
|
2078
|
-
quarantined: this.quarantined,
|
|
2079
|
-
pins: this.pins,
|
|
2080
|
-
listWorkersOf: (parentId) => this.listWorkersOf(parentId),
|
|
2081
|
-
setArchiveBlocker: (runId, blocker) => this.setArchiveBlocker(runId, blocker),
|
|
2082
|
-
decodeRunRow,
|
|
2083
|
-
decodeCold: (row) => this.decodeCold(row),
|
|
2084
|
-
writeRefusal: (memberId) => this.writeRefusal(memberId),
|
|
2085
|
-
factsPeek: (memberId) => this.transcriptFacts.factsFor(memberId).peek(memberId),
|
|
2086
|
-
readWorkerExecution: (memberId) => this.workerExecutions.readWorkerExecution(memberId),
|
|
2087
|
-
}, id, isActive);
|
|
2088
|
-
}
|
|
2089
|
-
/** Blockers are feedback, never archive authority or cleanup permission. */
|
|
2090
|
-
setArchiveBlocker(id, blocker) {
|
|
2091
|
-
const run = this.record(id);
|
|
2092
|
-
if (!run || run.archived || isDeepStrictEqual(run.archiveBlocker, blocker))
|
|
2093
|
-
return;
|
|
2094
|
-
this.commitIndex(new Map([[id, { ...run, archiveBlocker: blocker }]]));
|
|
2095
|
-
}
|
|
2096
|
-
archiveMergeBlocker(snapshot, missing, repoBase) {
|
|
2097
|
-
const url = `https://github.com/${missing.owner}/${missing.repo}/pull/${missing.number}`;
|
|
2098
|
-
const family = [snapshot.rootId, ...(this.db?.listIdsByParent(snapshot.rootId) ?? [])].flatMap(id => {
|
|
2099
|
-
const run = this.peek(id);
|
|
2100
|
-
return run ? [run] : [];
|
|
2101
|
-
});
|
|
2102
|
-
const member = family.find(run => archivePullRequests([run], repoBase)?.some(pr => pullRequestKey(pr) === pullRequestKey(missing)));
|
|
2103
|
-
this.setArchiveBlocker(snapshot.rootId, { message: `PR ${missing.owner}/${missing.repo}#${missing.number} is not confirmed merged. Check the PR association or archive manually.`,
|
|
2104
|
-
runId: member?.id ?? snapshot.rootId, pullRequestUrl: url });
|
|
2105
|
-
}
|
|
2106
|
-
hasArchiveOnMergeAssociations(id) {
|
|
2107
|
-
return this.db?.archiveFamilyHasPullRequests(id) ?? false;
|
|
2108
|
-
}
|
|
2109
|
-
async prepareArchiveOnMerge(id) {
|
|
2110
|
-
const ids = [id, ...(this.db?.listIdsByParent(id) ?? [])];
|
|
2111
|
-
if (ids.length > 1025)
|
|
2112
|
-
return;
|
|
2113
|
-
for (const memberId of ids)
|
|
2114
|
-
await this.transcriptFacts.factsFor(memberId).ready(memberId);
|
|
2115
|
-
}
|
|
2116
|
-
archiveOnMergeSnapshot(id, repoBase, isActive = () => false) {
|
|
2117
|
-
const family = this.archiveFamily(id, isActive);
|
|
2118
|
-
if (!family)
|
|
2119
|
-
return undefined;
|
|
2120
|
-
return this.archiveSnapshot(family, repoBase);
|
|
2121
|
-
}
|
|
2122
|
-
archiveSnapshot(family, repoBase) {
|
|
2123
|
-
const pullRequests = archivePullRequests(family, repoBase);
|
|
2124
|
-
if (!pullRequests) {
|
|
2125
|
-
this.setArchiveBlocker(family[0].id, { message: 'PR associations cannot be resolved. Check task and worker PRs, or archive manually.' });
|
|
2126
|
-
return undefined;
|
|
2127
|
-
}
|
|
2128
|
-
const fingerprint = archiveDigest(pullRequests);
|
|
2129
|
-
if (family[0].autoArchive?.fingerprint === fingerprint)
|
|
2130
|
-
return undefined;
|
|
2131
|
-
return { rootId: family[0].id, fingerprint, pullRequests, token: archiveDigest(family.map(({ archiveBlocker: _blocker, ...run }) => run)) };
|
|
2132
|
-
}
|
|
2133
|
-
/** No await between final revalidation and the fenced, all-or-nothing cascade. */
|
|
2134
|
-
archiveAfterMerge(snapshot, observations, repoBase, isActive = () => false) {
|
|
2135
|
-
const family = this.archiveFamily(snapshot.rootId, isActive);
|
|
2136
|
-
if (!family)
|
|
2137
|
-
return false;
|
|
2138
|
-
const current = this.archiveSnapshot(family, repoBase);
|
|
2139
|
-
if (!current || current.token !== snapshot.token || current.fingerprint !== snapshot.fingerprint)
|
|
2140
|
-
return false;
|
|
2141
|
-
const parsed = observations.map(observation => mergedPullRequestSchema.safeParse(observation));
|
|
2142
|
-
if (parsed.some(result => !result.success))
|
|
2143
|
-
return false;
|
|
2144
|
-
const merged = parsed.flatMap(result => result.success ? [result.data] : []);
|
|
2145
|
-
const byKey = new Map(merged.map(pr => [pullRequestKey(pr), pr]));
|
|
2146
|
-
if (byKey.size !== current.pullRequests.length || current.pullRequests.some(pr => !byKey.has(pullRequestKey(pr))))
|
|
2147
|
-
return false;
|
|
2148
|
-
const restoredAt = Math.max(0, ...family.map(run => run.manualUnarchivedAt ? Date.parse(run.manualUnarchivedAt) : 0));
|
|
2149
|
-
if (restoredAt && merged.every(pr => Date.parse(pr.mergedAt) <= restoredAt))
|
|
2150
|
-
return false;
|
|
2151
|
-
const now = new Date().toISOString();
|
|
2152
|
-
if (merged.some(pr => Date.parse(pr.mergedAt) > Date.parse(now)))
|
|
2153
|
-
return false;
|
|
2154
|
-
const staged = new Map(), exits = new Map();
|
|
2155
|
-
this.stageArchive(staged, family[0], true, exits);
|
|
2156
|
-
staged.get(snapshot.rootId).autoArchive = { reason: 'pull-requests-merged', archivedAt: now, fingerprint: current.fingerprint, pullRequests: merged };
|
|
2157
|
-
this.commitIndex(staged, undefined, { exits });
|
|
2158
|
-
for (const id of staged.keys())
|
|
2159
|
-
this.compressor.enqueue(id);
|
|
2160
|
-
return true;
|
|
2161
|
-
}
|
|
2162
|
-
setArchived(id, archived) {
|
|
2163
|
-
const run = this.record(id);
|
|
2164
|
-
if (!run)
|
|
2165
|
-
return undefined;
|
|
2166
|
-
this.applyArchivedCascade(run, archived);
|
|
2167
|
-
return run;
|
|
2168
|
-
}
|
|
2169
|
-
/** Parent + owned workers; returns how many records flipped `archived`. */
|
|
2170
|
-
applyArchivedCascade(run, archived) {
|
|
2171
|
-
const staged = new Map(), exits = new Map();
|
|
2172
|
-
this.stageArchive(staged, run, archived, exits);
|
|
2173
|
-
let changed = 0;
|
|
2174
|
-
for (const [id, next] of staged) {
|
|
2175
|
-
if (next && this.peek(id)?.archived !== archived)
|
|
2176
|
-
changed++;
|
|
2177
|
-
if (next)
|
|
2178
|
-
next.completionAction = undefined; // an explicit filing/restoration retires pending work
|
|
2179
|
-
}
|
|
2180
|
-
this.commitIndex(staged, undefined, { exits });
|
|
2181
|
-
return changed;
|
|
2182
|
-
}
|
|
2183
|
-
applyArchived(run, archived, before = snapshotRun(run), exit) {
|
|
2184
|
-
const changed = run.archived !== archived;
|
|
2185
|
-
// Transcript first: a restore throw aborts with the record unchanged (#818 S3).
|
|
2186
|
-
this.syncTranscriptForm(run.id, archived);
|
|
2187
|
-
this.touch(run, before, archiveFields(run, archived, new Date().toISOString()) ?? exit);
|
|
2188
|
-
return changed;
|
|
2189
|
-
}
|
|
2190
|
-
/** Transcript form follows `archived`: enqueue compression, or restore the plain file now. */
|
|
2191
|
-
syncTranscriptForm(id, archived) {
|
|
2192
|
-
if (archived)
|
|
2193
|
-
this.compressor.enqueue(id);
|
|
2194
|
-
else {
|
|
2195
|
-
this.compressor.cancel(id);
|
|
2196
|
-
restoreHistory(this.dataDir, id);
|
|
2197
|
-
}
|
|
2198
|
-
}
|
|
2199
|
-
/**
|
|
2200
|
-
* Whether this store may compress `id`'s transcript: the run exists, is archived, is not in a
|
|
2201
|
-
* live status (queued/running/waiting), and this process holds the family's claim in `claimed`
|
|
2202
|
-
* (not merely `pendingClaims`). Two processes never both write a run (#779, #818 B1).
|
|
2203
|
-
*/
|
|
2204
|
-
isHistoryCompressEligible(id) {
|
|
2205
|
-
if (this.deleted.has(id))
|
|
2206
|
-
return false;
|
|
2207
|
-
try {
|
|
2208
|
-
const run = this.held.get(id) ?? this.peek(id);
|
|
2209
|
-
if (!run || run.archived !== true || isLiveStatus(run.status))
|
|
2210
|
-
return false;
|
|
2211
|
-
return this.holdsCompressClaim(id);
|
|
2212
|
-
}
|
|
2213
|
-
catch {
|
|
2214
|
-
return false;
|
|
2215
|
-
}
|
|
2216
|
-
}
|
|
2217
|
-
/** Take the family claim if free and require it to be in `this.claimed`, not only pending. */
|
|
2218
|
-
holdsCompressClaim(id) {
|
|
2219
|
-
const family = this.familyOf(id);
|
|
2220
|
-
return this.claimFamilies([family]).has(family) && this.claimed.has(family);
|
|
2221
|
-
}
|
|
2222
|
-
/** Startup sweep: enqueue every archived non-live run that still has a plain transcript. */
|
|
2223
|
-
compressArchivedHistory() {
|
|
2224
|
-
try {
|
|
2225
|
-
const ids = new Set();
|
|
2226
|
-
for (const key of this.db?.listKeysWhere('archived = 1 AND live = 0') ?? []) {
|
|
2227
|
-
if (!this.deleted.has(key.id))
|
|
2228
|
-
ids.add(key.id);
|
|
2229
|
-
}
|
|
2230
|
-
for (const run of this.held.values()) {
|
|
2231
|
-
if (run.archived && !isLiveStatus(run.status) && !this.deleted.has(run.id))
|
|
2232
|
-
ids.add(run.id);
|
|
2233
|
-
}
|
|
2234
|
-
for (const id of ids) {
|
|
2235
|
-
try {
|
|
2236
|
-
const { plain } = historyPaths(this.dataDir, id);
|
|
2237
|
-
// Claim only ids with work: a plain file to compress, including both-present leftovers.
|
|
2238
|
-
if (!existsSync(plain))
|
|
2239
|
-
continue;
|
|
2240
|
-
if (!this.holdsCompressClaim(id))
|
|
2241
|
-
continue;
|
|
2242
|
-
if (hasPlainHistory(this.dataDir, id))
|
|
2243
|
-
this.compressor.enqueue(id);
|
|
2244
|
-
}
|
|
2245
|
-
catch {
|
|
2246
|
-
// Best effort: one id must not stop the sweep or boot (#818 S2).
|
|
2247
|
-
}
|
|
2248
|
-
}
|
|
2249
|
-
}
|
|
2250
|
-
catch {
|
|
2251
|
-
// listKeysWhere / open-time fs: never throw out of boot.
|
|
2252
|
-
}
|
|
2253
|
-
}
|
|
2254
|
-
/** Resolves when the transcript compressor is idle (tests, shutdown). */
|
|
2255
|
-
historyIdle() {
|
|
2256
|
-
return this.compressor.idle();
|
|
2257
|
-
}
|
|
2258
|
-
/** Pin one run to the top of this project's task list, or unpin it (#935). Mirrors
|
|
2259
|
-
* `setArchived`: sets the fields, then persists + broadcasts via `touch`, so the updated
|
|
2260
|
-
* record rides the existing `run` SSE with no new event. Idempotent — re-pinning a pinned
|
|
2261
|
-
* run just re-stamps `pinnedAt`.
|
|
2262
|
-
*
|
|
2263
|
-
* Every active status is pinnable. Archived requests clear stale metadata instead, so a
|
|
2264
|
-
* late click racing archive cannot leave a hidden pin that reappears on unarchive. */
|
|
2265
|
-
setPinned(id, pinned) {
|
|
2266
|
-
return this.change(id, (run) => {
|
|
2267
|
-
if (pinned && !run.archived) {
|
|
2268
|
-
run.pinned = true;
|
|
2269
|
-
run.pinnedAt = new Date().toISOString();
|
|
2270
|
-
}
|
|
2271
|
-
else {
|
|
2272
|
-
clearPin(run);
|
|
2273
|
-
}
|
|
2274
|
-
});
|
|
2275
|
-
}
|
|
2276
|
-
/** Bulk-archive finished runs (#780). `isSweepable` decides which; `archived` counts every
|
|
2277
|
-
* record that flipped (cascaded workers included), `ids` lists the top-level runs picked and
|
|
2278
|
-
* `pinnedIds` the subset that carried a pin before `clearPin` dropped it. */
|
|
2279
|
-
archiveFinished(scope, automation) {
|
|
2280
|
-
let archived = 0;
|
|
2281
|
-
// Snapshot first: cascade may archive still-live workers, mutating the held set, and the pin
|
|
2282
|
-
// has to be read before `applyArchived` clears it. Runs not in memory are picked off their
|
|
2283
|
-
// stored summary, which carries every field `isSweepable` reads.
|
|
2284
|
-
const picked = [...this.held.values()].filter((run) => SWEEPABLE_RUN_RULE.matches({ ...run, automationId: automationIdOf(run) }, scope, automation))
|
|
2285
|
-
.map((run) => [run, this.listOrder(run)]);
|
|
2286
|
-
for (const row of this.db?.listWhere(SWEEPABLE_RUN_RULE.sql) ?? []) {
|
|
2287
|
-
if (this.held.has(row.id) || this.deleted.has(row.id))
|
|
2288
|
-
continue;
|
|
2289
|
-
const summary = parseStoredSummary(row.summary);
|
|
2290
|
-
if (summary && SWEEPABLE_RUN_RULE.matches(summary, scope, automation))
|
|
2291
|
-
picked.push([summary, row]);
|
|
2292
|
-
}
|
|
2293
|
-
// Another process's runs are not this store's to archive (#779, plan step 3): they stay out.
|
|
2294
|
-
// A sweepable run is never a worker (`isSweepable`), so each is its own family.
|
|
2295
|
-
const writable = this.claimFamilies(picked.map(([run]) => run.id));
|
|
2296
|
-
const mine = sortNewestFirst(picked.filter(([run]) => writable.has(run.id)));
|
|
2297
|
-
const ids = mine.map((run) => run.id);
|
|
2298
|
-
const pinnedIds = mine.filter((run) => run.pinned).map((run) => run.id);
|
|
2299
|
-
for (const id of ids) {
|
|
2300
|
-
// Re-check: a prior cascade may already have archived this id.
|
|
2301
|
-
const run = this.record(id);
|
|
2302
|
-
if (!run || run.archived)
|
|
2303
|
-
continue;
|
|
2304
|
-
archived += this.applyArchivedCascade(run, true);
|
|
2305
|
-
}
|
|
2306
|
-
return { archived, ids, pinnedIds };
|
|
2307
|
-
}
|
|
2308
|
-
/** Mark one run as read (#unread-done-items): stamp the read receipt now. Mirrors
|
|
2309
|
-
* `setArchived` — sets the field then persists + broadcasts via `touch`, so the
|
|
2310
|
-
* updated record rides the existing `run` SSE with no new event. Idempotent by
|
|
2311
|
-
* design: opening an already-read thread just re-stamps a later `seenAt`. */
|
|
2312
|
-
setRead(id) {
|
|
2313
|
-
return this.change(id, (run) => { run.seenAt = new Date().toISOString(); });
|
|
2314
|
-
}
|
|
2315
|
-
/** Mark one run as UNread (#775): drop the read receipt so the run rejoins the unread
|
|
2316
|
-
* list. The inverse of `setRead` and, like it, `touch`es so the updated record rides the
|
|
2317
|
-
* existing `run` SSE.
|
|
2318
|
-
*
|
|
2319
|
-
* Deleting the field rather than adding a "manually unread" flag is the whole point:
|
|
2320
|
-
* absent `seenAt` is ALREADY what every reader treats as unread (`isUnread` in the
|
|
2321
|
-
* cockpit's read-state.ts, and `markAllRead`'s clause-for-clause copy of it below), so
|
|
2322
|
-
* clearing needs no new state and writes a shape any older Squawk already parses.
|
|
2323
|
-
*
|
|
2324
|
-
* Deliberately unconditional: clearing a receipt is always a legal write, so this
|
|
2325
|
-
* succeeds for an already-unread run (idempotent) and for statuses that can never wear
|
|
2326
|
-
* the marker. WHETHER the action means anything for a given run is UI policy, and lives
|
|
2327
|
-
* in the cockpit's `runActionFlags` — the same split the rest of the store keeps. */
|
|
2328
|
-
setUnread(id) {
|
|
2329
|
-
return this.change(id, (run) => { delete run.seenAt; });
|
|
2330
|
-
}
|
|
2331
1638
|
/** A debounced write of the held record `id`: `apply` changes it in place, then `touch` saves it. */
|
|
2332
1639
|
change(id, apply) {
|
|
2333
1640
|
const run = this.record(id), before = snapshotRun(run);
|
|
@@ -2337,39 +1644,6 @@ export class RunStore {
|
|
|
2337
1644
|
this.touch(run, before);
|
|
2338
1645
|
return run;
|
|
2339
1646
|
}
|
|
2340
|
-
/**
|
|
2341
|
-
* Stamp unread finished runs in bulk and return the count. Keep the rule aligned with cockpit
|
|
2342
|
-
* isUnread: done/failed, finished since seen, not archived; cancelled and usage-limit waiting
|
|
2343
|
-
* runs are excluded. `automation` narrows it to one origin, as in `archiveFinished`
|
|
2344
|
-
* (hearsay-tools/cezarion#1616); absent stamps both.
|
|
2345
|
-
*/
|
|
2346
|
-
markAllRead(automation) {
|
|
2347
|
-
const now = new Date().toISOString();
|
|
2348
|
-
let count = 0;
|
|
2349
|
-
// Runs not in memory are picked by the same rule over their stored summary, then re-checked
|
|
2350
|
-
// on the record before they are stamped.
|
|
2351
|
-
const candidates = [...this.held.values()];
|
|
2352
|
-
const stored = (this.db?.listWhere(guardedJsonSql(UNREAD_RUN_RULE.sql, 0)) ?? []).filter((row) => !this.held.has(row.id) && !this.deleted.has(row.id));
|
|
2353
|
-
// One claim transaction for them all; another process's runs are skipped (`record` refuses).
|
|
2354
|
-
this.claimFamilies(stored.map(rowFamily));
|
|
2355
|
-
for (const row of stored) {
|
|
2356
|
-
const run = this.record(row.id);
|
|
2357
|
-
if (run)
|
|
2358
|
-
candidates.push(run);
|
|
2359
|
-
}
|
|
2360
|
-
for (const run of candidates) {
|
|
2361
|
-
const unread = UNREAD_RUN_RULE.matches(run);
|
|
2362
|
-
if (!unread)
|
|
2363
|
-
continue;
|
|
2364
|
-
if (automation !== undefined && (automationIdOf(run) !== undefined) !== automation)
|
|
2365
|
-
continue;
|
|
2366
|
-
const before = snapshotRun(run);
|
|
2367
|
-
run.seenAt = now;
|
|
2368
|
-
this.touch(run, before);
|
|
2369
|
-
count++;
|
|
2370
|
-
}
|
|
2371
|
-
return count;
|
|
2372
|
-
}
|
|
2373
1647
|
/** Indexed family enumeration, including members not yet flushed to SQLite. */
|
|
2374
1648
|
listFamilyRunIds(rootId) {
|
|
2375
1649
|
const ids = new Set([rootId, ...(this.db?.listIdsByParent(rootId) ?? [])]);
|
|
@@ -2396,24 +1670,18 @@ export class RunStore {
|
|
|
2396
1670
|
/** Same location `handoffPath()` in handoff.ts produces — inlined to keep
|
|
2397
1671
|
* the store free of upward imports. */
|
|
2398
1672
|
handoffPath(runId) {
|
|
2399
|
-
return join(this.sourceDataDir(runId), 'runs', `${runId}.handoff.md`);
|
|
1673
|
+
return join(this.claims.sourceDataDir(runId), 'runs', `${runId}.handoff.md`);
|
|
2400
1674
|
}
|
|
2401
1675
|
/** Agent screenshots persisted by the run manager (see persistImage). */
|
|
2402
1676
|
imagesDir(runId) {
|
|
2403
|
-
return join(this.sourceDataDir(runId), 'runs', `${runId}-images`);
|
|
1677
|
+
return join(this.claims.sourceDataDir(runId), 'runs', `${runId}-images`);
|
|
2404
1678
|
}
|
|
2405
1679
|
/** Save `run` debounced and publish it; `before` is the record at the write's entry (none: created). */
|
|
2406
1680
|
touch(run, before, exit) {
|
|
2407
1681
|
this.dirty.add(run.id);
|
|
2408
1682
|
this.scheduleSave();
|
|
2409
1683
|
publishRunWrite(this.published, run, before, undefined, exit);
|
|
2410
|
-
this.maybeEnqueueHistoryCompress(run);
|
|
2411
|
-
}
|
|
2412
|
-
/** Form follows archived: a terminal archived run with a plain transcript is queued again. */
|
|
2413
|
-
maybeEnqueueHistoryCompress(run) {
|
|
2414
|
-
if (run.archived && !isLiveStatus(run.status) && hasPlainHistory(this.dataDir, run.id)) {
|
|
2415
|
-
this.compressor.enqueue(run.id);
|
|
2416
|
-
}
|
|
1684
|
+
this.archive.maybeEnqueueHistoryCompress(run);
|
|
2417
1685
|
}
|
|
2418
1686
|
/** The held record is gone; the next save or commit deletes its row, fenced by `family`'s claim
|
|
2419
1687
|
* and by the revision this store last saw (kept in `base` until the delete is written). */
|
|
@@ -2500,7 +1768,7 @@ export class RunStore {
|
|
|
2500
1768
|
// that family's claim first; one it cannot take fails the fence below as claim-lost.
|
|
2501
1769
|
const moved = [...new Set(families.values())].filter((family) => !this.claimed.has(family) && !this.pendingClaims.has(family));
|
|
2502
1770
|
if (moved.length > 0)
|
|
2503
|
-
this.claimFamilies(moved, { allowLive: true });
|
|
1771
|
+
this.claims.claimFamilies(moved, { allowLive: true });
|
|
2504
1772
|
let commit;
|
|
2505
1773
|
try {
|
|
2506
1774
|
commit = this.writeIndex({ upserts, deletes, ...(this.owner ? { fence: this.fence(families) } : {}) });
|
|
@@ -2587,7 +1855,7 @@ export class RunStore {
|
|
|
2587
1855
|
}
|
|
2588
1856
|
const decoded = conflict.current ? decodeRunRow(conflict.current.data) : undefined;
|
|
2589
1857
|
const current = decoded?.run;
|
|
2590
|
-
if (this.isFallbackRun(conflict.id))
|
|
1858
|
+
if (this.claims.isFallbackRun(conflict.id))
|
|
2591
1859
|
this.held.delete(conflict.id);
|
|
2592
1860
|
const held = this.held.get(conflict.id);
|
|
2593
1861
|
const before = snapshotRun(held ?? staged.get(conflict.id) ?? undefined);
|
|
@@ -2644,7 +1912,7 @@ export class RunStore {
|
|
|
2644
1912
|
this.liveItems.clear();
|
|
2645
1913
|
// Demand-bound feeds stop before storage disappears during project removal/shutdown.
|
|
2646
1914
|
this.published.publish('store.closed', {});
|
|
2647
|
-
this.compressor.stop();
|
|
1915
|
+
this.archive.compressor.stop();
|
|
2648
1916
|
this.transcriptFacts.stop();
|
|
2649
1917
|
if (this.saveTimer) {
|
|
2650
1918
|
clearTimeout(this.saveTimer);
|
|
@@ -2667,10 +1935,4 @@ export class RunStore {
|
|
|
2667
1935
|
this.db = null;
|
|
2668
1936
|
}
|
|
2669
1937
|
}
|
|
2670
|
-
function archiveDigest(value) {
|
|
2671
|
-
return createHash('sha256').update(JSON.stringify(value)).digest('hex');
|
|
2672
|
-
}
|
|
2673
|
-
function archiveFields(run, archived, now) {
|
|
2674
|
-
return stageArchiveFields(run, archived, now);
|
|
2675
|
-
}
|
|
2676
1938
|
//# sourceMappingURL=store.js.map
|