@hearsay-tools/squawk 0.18.0-pr4083.7813 → 0.18.0-pr4084.7814

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.
@@ -2,33 +2,29 @@ import { legacyIndexRows, readableSavedRunner, upgradeLegacyRunRow, withKeptFiel
2
2
  import { dataReadDirs, runDataDir } from '../project-paths.js';
3
3
  import { addRunSource, copyFallbackFamily, fallbackRunSource, fallbackRunDeleteError } from './project-run-sources.js';
4
4
  import { registeredWaitRecord, registeredReceiptRecord } from './wait-registration-write.js';
5
- import { stageCommit, stageLoaded, stageDurableUpdate, stageDebouncedUpdate, stageConversation, stageArchiveFields, stageStepUpdate, stepTotals, redactPatch, clearPin } from './record-write-rules.js';
5
+ import { stageCommit, stageLoaded, stageDurableUpdate, stageDebouncedUpdate, stageConversation, stageStepUpdate, stepTotals, redactPatch } from './record-write-rules.js';
6
6
  import { publishRunWrite, RunLifecycle, snapshotRun } from './lifecycle.js';
7
7
  import { listPeerTaskSummaries, parseStoredSummary } from './run-summary-page.js';
8
8
  export { parseStoredSummary } from './run-summary-page.js';
9
9
  import { workerExecutionsFactory } from './worker-executions-registry.js';
10
- import { randomUUID, createHash } from 'node:crypto';
10
+ import { randomUUID } from 'node:crypto';
11
11
  import { isDeepStrictEqual } from 'node:util';
12
12
  import { existsSync, mkdirSync } from 'node:fs';
13
13
  import { join } from 'node:path';
14
14
  import { z } from 'zod';
15
15
  import { delegationStateSchema, workerDestroyRetrySchema, } from '../contract/index.js';
16
16
  import { agentInputSchema, inboxClaimSchema } from '../contract/index.js';
17
- import { automationIdOf, stepStateSchema as contractStepStateSchema, toRunSummary, runRecordSchema as contractRunRecordSchema, runPullRequestSchema, mergedPullRequestSchema, } from '../contract/index.js';
17
+ import { stepStateSchema as contractStepStateSchema, toRunSummary, runRecordSchema as contractRunRecordSchema, runPullRequestSchema, } from '../contract/index.js';
18
18
  import { queuedMessageSchema } from '../contract/index.js';
19
19
  import { previewServerSchema } from '../contract/index.js';
20
20
  import { waitSchema } from '../contract/index.js';
21
21
  import { isUsageLimitHold } from '../contract/index.js';
22
- import { UNREAD_RUN_RULE, SWEEPABLE_RUN_RULE, REFERENCED_RUN_RULE } from '../contract/index.js';
22
+ import { REFERENCED_RUN_RULE } from '../contract/index.js';
23
23
  import { matchesRunSearch, sqlPrefilterTokens } from '../contract/index.js';
24
24
  import { storedDelegationStateSchema } from './delegation-state.js';
25
- import { HistoryCompressor } from './history-compressor.js';
26
25
  import { LiveItemSnapshots } from './live-item-snapshots.js';
27
- import { stampOf } from './transcript-facts.js';
28
26
  import { RunTranscriptFacts } from './transcript-facts-topic.js';
29
- import { hasPlainHistory, historyPaths, restoreHistory } from './history-file.js';
30
- // Pure, dependency-free reference helpers — the same sanity bound the marker parser applies.
31
- import { archivePullRequests, pullRequestKey } from './pull-requests.js';
27
+ import { restoreHistory } from './history-file.js';
32
28
  // Type-only module (zod + nothing else), so this cannot cycle back into the store.
33
29
  import { workflowDefSchema } from '../workflows/types.js';
34
30
  import { applyOutcomes } from './outcome-commit.js';
@@ -45,18 +41,19 @@ import { failLoadedInterruptedRun, restoreLoadedUsageLimitHold, settleLoadedStop
45
41
  import { hasLegacyWaitFields, UNREADABLE_WAIT } from './legacy-waits.js';
46
42
  export { ciWaitEntry, holdsWorkerWait, upgradeLegacyWaits, workerWaitEntry } from './legacy-waits.js';
47
43
  import { ExitEvents } from './exit-events.js';
48
- import { encodeRunRow, familyRootOf, isLiveRecord, isLiveStatus, materializedWorktreePath, newestFirst } from './run-row.js';
44
+ import { encodeRunRow, familyRootOf, isLiveRecord, materializedWorktreePath, newestFirst } from './run-row.js';
49
45
  import { RunRetentionTopic } from './run-retention.js';
50
46
  import { collectRawExtras, encodeRawRecord } from './raw-record.js';
51
47
  import { ColdReadCache, storedRow } from './cold-reads.js';
52
48
  import { assertNoLegacyCockpit, assertNoLegacyWriter, backUpLegacyIndex, LEGACY_INDEX_FILE, LegacyWriterError, readLegacyIndex } from './legacy-index.js';
53
49
  import { toRunStoreOpenError } from './store-open-error.js';
54
- import { archiveStoreFamily } from './archive-family.js';
55
50
  import { claimStoreFamilies } from './claim-families.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';
55
+ import { RunArchiveTopic } from './run-archive.js';
56
+ import { RunReadFlagsTopic } from './run-read-flags.js';
60
57
  import { claimOwnerLive, closeClaimSession, familyKey, foreignClaimedRunIds, liveForeignClaimedRunIds, openClaimSession, rowFamily } from './run-claims.js';
61
58
  import { assertProjectWritable, projectWriteRefused } from '../server/cockpit-ownership.js';
62
59
  /**
@@ -439,8 +436,10 @@ export class RunStore {
439
436
  /** Rows whose `data` this store tried to decode and could not: left in the database untouched,
440
437
  * and left out of the list rows from then on, as the cold reader leaves them out (run-index.ts). */
441
438
  unreadable = new Set();
442
- /** Background one-at-a-time compressor for archived transcripts (#818). */
443
- compressor;
439
+ /** The archive flag, archive on merge, completion actions and the transcript compressor (hearsay-tools/squawk#4041). */
440
+ archive;
441
+ /** The pinned and read flags (hearsay-tools/squawk#4041). */
442
+ readFlags;
444
443
  /** What the transcript says about a run (hearsay-tools/squawk#4036). */
445
444
  transcriptFacts;
446
445
  /** Whether a run may go, and its deletion; the count-based archive (hearsay-tools/squawk#4037). */
@@ -488,7 +487,7 @@ export class RunStore {
488
487
  seqs: this.seqs, published: this.published, liveItems: this.liveItems, transcriptFacts: this.transcriptFacts, redaction: this.redaction,
489
488
  record: (id) => this.record(id), missingRunError: (runId) => this.missingRunError(runId), sourceDataDir: (id) => this.sourceDataDir(id),
490
489
  touch: (run, before) => this.touch(run, before), change: (id, apply) => this.change(id, apply), repoHandle: () => this.repoHandle,
491
- maybeEnqueueHistoryCompress: (run) => this.maybeEnqueueHistoryCompress(run),
490
+ maybeEnqueueHistoryCompress: (run) => this.archive.maybeEnqueueHistoryCompress(run),
492
491
  });
493
492
  this.retention = new RunRetentionTopic(dataDir, {
494
493
  db: () => this.db, held: this.held, deleted: this.deleted, quarantined: this.quarantined,
@@ -498,7 +497,7 @@ export class RunStore {
498
497
  hasFallbackRun: (id) => this.hasFallbackRun(id), listOrder: (run) => this.listOrder(run),
499
498
  claimFamilies: (families) => this.claimFamilies(families), markDeleted: (id, family) => this.markDeleted(id, family),
500
499
  scheduleSave: () => this.scheduleSave(), commitIndex: (input) => this.commitIndex(input),
501
- commitDelegation: (patches) => this.commitDelegation(patches), applyArchived: (run, archived) => this.applyArchived(run, archived),
500
+ commitDelegation: (patches) => this.commitDelegation(patches), applyArchived: (run, archived) => this.archive.applyArchived(run, archived),
502
501
  workerDeletionEvidence: (id) => this.workerExecutions.workerDeletionEvidence(id),
503
502
  workerResults: this.workerResults,
504
503
  readWorkerExecution: (id) => this.workerExecutions.readWorkerExecution(id), identityPath: (id) => this.workerExecutions.identityPath(id),
@@ -506,7 +505,22 @@ export class RunStore {
506
505
  executionPath: (id) => this.workerExecutions.executionPath(id), handoffPath: (runId) => this.handoffPath(runId),
507
506
  imagesDir: (runId) => this.imagesDir(runId),
508
507
  });
509
- this.compressor = new HistoryCompressor(dataDir, (id) => this.isHistoryCompressEligible(id), (id, plain, archive) => this.transcriptFacts.index.adoptArchive(id, plain, stampOf(archive)));
508
+ this.archive = new RunArchiveTopic(dataDir, {
509
+ db: () => this.db, held: this.held, deleted: this.deleted, quarantined: this.quarantined, pins: this.pins,
510
+ claimed: this.claimed, base: this.base, owner: () => this.owner, transcriptFacts: this.transcriptFacts,
511
+ decodeRunRow, sortNewestFirst, peek: (id) => this.peek(id), record: (id) => this.record(id),
512
+ listWorkersOf: (parentId) => this.listWorkersOf(parentId), familyOf: (id) => this.familyOf(id),
513
+ claimFamilies: (families, opts) => this.claimFamilies(families, opts), writeRefusal: (id) => this.writeRefusal(id),
514
+ assertWritable: (staged) => this.assertWritable(staged), decodeCold: (row) => this.decodeCold(row),
515
+ listOrder: (run) => this.listOrder(run), commitIndex: (input, source, write) => this.commitIndex(input, source, write),
516
+ touch: (run, before, exit) => this.touch(run, before, exit),
517
+ readWorkerExecution: (id) => this.workerExecutions.readWorkerExecution(id),
518
+ });
519
+ this.readFlags = new RunReadFlagsTopic({
520
+ db: () => this.db, held: this.held, deleted: this.deleted, record: (id) => this.record(id),
521
+ claimFamilies: (families) => this.claimFamilies(families), touch: (run, before) => this.touch(run, before),
522
+ change: (id, apply) => this.change(id, apply),
523
+ });
510
524
  }
511
525
  /**
512
526
  * Open the project's run store. See `reconcileLoadedRun` for what `keepLive` (#367) decides
@@ -1801,7 +1815,7 @@ export class RunStore {
1801
1815
  };
1802
1816
  staged.set(id, next);
1803
1817
  if (Object.prototype.hasOwnProperty.call(patch, 'archived'))
1804
- this.syncTranscriptForm(id, next.archived);
1818
+ this.archive.syncTranscriptForm(id, next.archived);
1805
1819
  if (conversation) {
1806
1820
  const root = this.peek(conversation.rootId);
1807
1821
  if (root?.delegation?.role !== 'root' || run.delegation.parentRunId !== root.id)
@@ -1831,8 +1845,8 @@ export class RunStore {
1831
1845
  const exits = new Map(write.exits);
1832
1846
  const staged = stageCommit(input, {
1833
1847
  peek: id => this.peek(id),
1834
- completionArchiveBlocker: run => this.completionArchiveBlocker(run),
1835
- stageArchive: (staged, run, archived) => this.stageArchive(staged, run, archived, exits),
1848
+ completionArchiveBlocker: run => this.archive.completionArchiveBlocker(run),
1849
+ stageArchive: (staged, run, archived) => this.archive.stageArchive(staged, run, archived, exits),
1836
1850
  });
1837
1851
  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
1852
  if (!this.db)
@@ -1870,79 +1884,7 @@ export class RunStore {
1870
1884
  }
1871
1885
  for (const [id, next] of staged)
1872
1886
  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;
1887
+ this.archive.compressor.enqueue(id);
1946
1888
  }
1947
1889
  /**
1948
1890
  * Refuse (throwing, with nothing changed) a commit that stages a quarantined run, or a run whose
@@ -2032,7 +1974,7 @@ export class RunStore {
2032
1974
  redact: (text) => this.redaction.redactText(text),
2033
1975
  repoHandle: this.repoHandle,
2034
1976
  restore: () => restoreHistory(this.dataDir, id),
2035
- archive: (record, archived) => this.applyArchived(record, archived, before, exit),
1977
+ archive: (record, archived) => this.archive.applyArchived(record, archived, before, exit),
2036
1978
  touch: (record) => this.touch(record, before, exit),
2037
1979
  };
2038
1980
  if (durability === 'committed') {
@@ -2066,268 +2008,6 @@ export class RunStore {
2066
2008
  Object.assign(run, stepTotals(run.steps));
2067
2009
  this.touch(run, before);
2068
2010
  }
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
2011
  /** A debounced write of the held record `id`: `apply` changes it in place, then `touch` saves it. */
2332
2012
  change(id, apply) {
2333
2013
  const run = this.record(id), before = snapshotRun(run);
@@ -2337,39 +2017,6 @@ export class RunStore {
2337
2017
  this.touch(run, before);
2338
2018
  return run;
2339
2019
  }
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
2020
  /** Indexed family enumeration, including members not yet flushed to SQLite. */
2374
2021
  listFamilyRunIds(rootId) {
2375
2022
  const ids = new Set([rootId, ...(this.db?.listIdsByParent(rootId) ?? [])]);
@@ -2407,13 +2054,7 @@ export class RunStore {
2407
2054
  this.dirty.add(run.id);
2408
2055
  this.scheduleSave();
2409
2056
  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
- }
2057
+ this.archive.maybeEnqueueHistoryCompress(run);
2417
2058
  }
2418
2059
  /** The held record is gone; the next save or commit deletes its row, fenced by `family`'s claim
2419
2060
  * and by the revision this store last saw (kept in `base` until the delete is written). */
@@ -2644,7 +2285,7 @@ export class RunStore {
2644
2285
  this.liveItems.clear();
2645
2286
  // Demand-bound feeds stop before storage disappears during project removal/shutdown.
2646
2287
  this.published.publish('store.closed', {});
2647
- this.compressor.stop();
2288
+ this.archive.compressor.stop();
2648
2289
  this.transcriptFacts.stop();
2649
2290
  if (this.saveTimer) {
2650
2291
  clearTimeout(this.saveTimer);
@@ -2667,10 +2308,4 @@ export class RunStore {
2667
2308
  this.db = null;
2668
2309
  }
2669
2310
  }
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
2311
  //# sourceMappingURL=store.js.map