@hearsay-tools/squawk 0.18.0-dev.7808 → 0.18.0-dev.7816

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (136) hide show
  1. package/dist/activity/tool-activity.d.ts +3 -2
  2. package/dist/activity/tool-activity.js +1 -1
  3. package/dist/activity/tool-activity.js.map +1 -1
  4. package/dist/ci-wait/controller.d.ts +42 -42
  5. package/dist/delegation/conversation-send.js +1 -1
  6. package/dist/delegation/conversation-send.js.map +1 -1
  7. package/dist/delegation/conversations.js +4 -4
  8. package/dist/delegation/conversations.js.map +1 -1
  9. package/dist/delegation/park-notice.d.ts +3 -1
  10. package/dist/delegation/park-notice.js +2 -2
  11. package/dist/delegation/park-notice.js.map +1 -1
  12. package/dist/delegation/provision.js +1 -1
  13. package/dist/delegation/provision.js.map +1 -1
  14. package/dist/delegation/results.js +1 -1
  15. package/dist/delegation/results.js.map +1 -1
  16. package/dist/delegation/service.js +5 -5
  17. package/dist/delegation/service.js.map +1 -1
  18. package/dist/delegation/transport.d.ts +65 -65
  19. package/dist/delegation/worker-cleanup.js +2 -2
  20. package/dist/delegation/worker-cleanup.js.map +1 -1
  21. package/dist/preview/agent-marker.js +1 -1
  22. package/dist/preview/agent-marker.js.map +1 -1
  23. package/dist/preview/host.d.ts +3 -1
  24. package/dist/preview/host.js +1 -1
  25. package/dist/preview/host.js.map +1 -1
  26. package/dist/preview/run-tools.js +1 -1
  27. package/dist/preview/run-tools.js.map +1 -1
  28. package/dist/runs/event-log.d.ts +79 -0
  29. package/dist/runs/event-log.js +188 -0
  30. package/dist/runs/event-log.js.map +1 -0
  31. package/dist/runs/ports.d.ts +68 -19
  32. package/dist/runs/run-archive.d.ts +1217 -0
  33. package/dist/runs/run-archive.js +332 -0
  34. package/dist/runs/run-archive.js.map +1 -0
  35. package/dist/runs/run-read-flags.d.ts +58 -0
  36. package/dist/runs/run-read-flags.js +87 -0
  37. package/dist/runs/run-read-flags.js.map +1 -0
  38. package/dist/runs/run-redaction.d.ts +19 -0
  39. package/dist/runs/run-redaction.js +36 -0
  40. package/dist/runs/run-redaction.js.map +1 -0
  41. package/dist/runs/store.d.ts +15 -164
  42. package/dist/runs/store.js +70 -613
  43. package/dist/runs/store.js.map +1 -1
  44. package/dist/runs/transcript-facts-fold.d.ts +1 -1
  45. package/dist/runs/transcript-facts-fold.js +1 -1
  46. package/dist/runs/transcript-facts-fold.js.map +1 -1
  47. package/dist/runs/webhook.d.ts +3 -1
  48. package/dist/runs/webhook.js +3 -3
  49. package/dist/runs/webhook.js.map +1 -1
  50. package/dist/serve-boot.js +1 -1
  51. package/dist/serve-boot.js.map +1 -1
  52. package/dist/server/activity-routes.d.ts +23 -23
  53. package/dist/server/archive-on-merge.js +10 -10
  54. package/dist/server/archive-on-merge.js.map +1 -1
  55. package/dist/server/completion-actions.js +6 -6
  56. package/dist/server/completion-actions.js.map +1 -1
  57. package/dist/server/models-routes.d.ts +13 -13
  58. package/dist/server/project-context.d.ts +3 -1
  59. package/dist/server/project-context.js +2 -2
  60. package/dist/server/project-context.js.map +1 -1
  61. package/dist/server/provider-auth-runtime.js +2 -2
  62. package/dist/server/provider-auth-runtime.js.map +1 -1
  63. package/dist/server/provider-sign-in-routes.d.ts +2 -2
  64. package/dist/server/reports-api.d.ts +2 -2
  65. package/dist/server/runner-install-routes.d.ts +10 -10
  66. package/dist/server/runners-routes.d.ts +10 -10
  67. package/dist/server/server.d.ts +3760 -3760
  68. package/dist/server/server.js +8 -8
  69. package/dist/server/server.js.map +1 -1
  70. package/dist/workflows/run/attachment-writer.js +1 -1
  71. package/dist/workflows/run/attachment-writer.js.map +1 -1
  72. package/dist/workflows/run/auto-resume.js +4 -4
  73. package/dist/workflows/run/auto-resume.js.map +1 -1
  74. package/dist/workflows/run/continuation-acceptance.js +1 -1
  75. package/dist/workflows/run/continuation-acceptance.js.map +1 -1
  76. package/dist/workflows/run/continuation-session.js +9 -9
  77. package/dist/workflows/run/continuation-session.js.map +1 -1
  78. package/dist/workflows/run/cut-off-work.d.ts +8 -6
  79. package/dist/workflows/run/cut-off-work.js +2 -2
  80. package/dist/workflows/run/cut-off-work.js.map +1 -1
  81. package/dist/workflows/run/family-reconciler.js +1 -1
  82. package/dist/workflows/run/family-reconciler.js.map +1 -1
  83. package/dist/workflows/run/human-waits.js +4 -4
  84. package/dist/workflows/run/human-waits.js.map +1 -1
  85. package/dist/workflows/run/input-delivery.js +11 -11
  86. package/dist/workflows/run/input-delivery.js.map +1 -1
  87. package/dist/workflows/run/input-receipts.js +3 -3
  88. package/dist/workflows/run/input-receipts.js.map +1 -1
  89. package/dist/workflows/run/launch-context.js +1 -1
  90. package/dist/workflows/run/launch-context.js.map +1 -1
  91. package/dist/workflows/run/launch-read-resolver.d.ts +3 -1
  92. package/dist/workflows/run/launch-read-resolver.js +5 -5
  93. package/dist/workflows/run/launch-read-resolver.js.map +1 -1
  94. package/dist/workflows/run/memory-guard.js +2 -2
  95. package/dist/workflows/run/memory-guard.js.map +1 -1
  96. package/dist/workflows/run/queued-revival.js +5 -5
  97. package/dist/workflows/run/queued-revival.js.map +1 -1
  98. package/dist/workflows/run/run-cancel.js +1 -1
  99. package/dist/workflows/run/run-cancel.js.map +1 -1
  100. package/dist/workflows/run/run-finish.js +5 -5
  101. package/dist/workflows/run/run-finish.js.map +1 -1
  102. package/dist/workflows/run/run-recovery.js +4 -4
  103. package/dist/workflows/run/run-recovery.js.map +1 -1
  104. package/dist/workflows/run/run-settlement.js +12 -12
  105. package/dist/workflows/run/run-settlement.js.map +1 -1
  106. package/dist/workflows/run/run-skills.js +1 -1
  107. package/dist/workflows/run/run-skills.js.map +1 -1
  108. package/dist/workflows/run/session-events.js +4 -4
  109. package/dist/workflows/run/session-events.js.map +1 -1
  110. package/dist/workflows/run/step-loop.js +1 -1
  111. package/dist/workflows/run/step-loop.js.map +1 -1
  112. package/dist/workflows/run/step-session.js +1 -1
  113. package/dist/workflows/run/step-session.js.map +1 -1
  114. package/dist/workflows/run/subagent-waits.js +2 -2
  115. package/dist/workflows/run/subagent-waits.js.map +1 -1
  116. package/dist/workflows/run/turn-bookkeeping.js +2 -2
  117. package/dist/workflows/run/turn-bookkeeping.js.map +1 -1
  118. package/dist/workflows/run/turn-nudges.js +6 -6
  119. package/dist/workflows/run/turn-nudges.js.map +1 -1
  120. package/dist/workflows/run/turn-settler.d.ts +3 -1
  121. package/dist/workflows/run/turn-settler.js +10 -10
  122. package/dist/workflows/run/turn-settler.js.map +1 -1
  123. package/dist/workflows/run/usage-accounting.js +1 -1
  124. package/dist/workflows/run/usage-accounting.js.map +1 -1
  125. package/dist/workflows/run/wake-admission.js +2 -2
  126. package/dist/workflows/run/wake-admission.js.map +1 -1
  127. package/dist/workflows/run/worker-orphans.js +2 -2
  128. package/dist/workflows/run/worker-orphans.js.map +1 -1
  129. package/dist/workflows/run/worker-questions.js +14 -14
  130. package/dist/workflows/run/worker-questions.js.map +1 -1
  131. package/dist/workflows/run/workflow-position.d.ts +3 -1
  132. package/dist/workflows/run/worktree-autosave.js +1 -1
  133. package/dist/workflows/run/worktree-autosave.js.map +1 -1
  134. package/dist/workflows/run.js +2 -2
  135. package/dist/workflows/run.js.map +1 -1
  136. package/package.json +4 -4
@@ -1,42 +1,34 @@
1
1
  import { legacyIndexRows, readableSavedRunner, upgradeLegacyRunRow, withKeptFields } from './legacy-run-rows.js';
2
2
  import { dataReadDirs, runDataDir } from '../project-paths.js';
3
3
  import { addRunSource, copyFallbackFamily, fallbackRunSource, fallbackRunDeleteError } from './project-run-sources.js';
4
- import { productEnv } from '../core/product-env.js';
5
4
  import { registeredWaitRecord, registeredReceiptRecord } from './wait-registration-write.js';
6
- import { stageCommit, stageLoaded, stageDurableUpdate, stageDebouncedUpdate, stageConversation, stageArchiveFields, stagePullRequests, stageStepUpdate, stepTotals, redactPatch, redactText, clearPin } from './record-write-rules.js';
5
+ import { stageCommit, stageLoaded, stageDurableUpdate, stageDebouncedUpdate, stageConversation, stageStepUpdate, stepTotals, redactPatch } from './record-write-rules.js';
7
6
  import { publishRunWrite, RunLifecycle, snapshotRun } from './lifecycle.js';
8
7
  import { listPeerTaskSummaries, parseStoredSummary } from './run-summary-page.js';
9
8
  export { parseStoredSummary } from './run-summary-page.js';
10
- import { defined } from '../core/defined.js';
11
9
  import { workerExecutionsFactory } from './worker-executions-registry.js';
12
- import { randomUUID, createHash } from 'node:crypto';
10
+ import { randomUUID } from 'node:crypto';
13
11
  import { isDeepStrictEqual } from 'node:util';
14
- import { appendFileSync, existsSync, mkdirSync } from 'node:fs';
12
+ import { existsSync, mkdirSync } from 'node:fs';
15
13
  import { join } from 'node:path';
16
14
  import { z } from 'zod';
17
15
  import { delegationStateSchema, workerDestroyRetrySchema, } from '../contract/index.js';
18
16
  import { agentInputSchema, inboxClaimSchema } from '../contract/index.js';
19
- 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';
20
18
  import { queuedMessageSchema } from '../contract/index.js';
21
19
  import { previewServerSchema } from '../contract/index.js';
22
20
  import { waitSchema } from '../contract/index.js';
23
21
  import { isUsageLimitHold } from '../contract/index.js';
24
- import { UNREAD_RUN_RULE, SWEEPABLE_RUN_RULE, REFERENCED_RUN_RULE } from '../contract/index.js';
22
+ import { REFERENCED_RUN_RULE } from '../contract/index.js';
25
23
  import { matchesRunSearch, sqlPrefilterTokens } from '../contract/index.js';
26
24
  import { storedDelegationStateSchema } from './delegation-state.js';
27
- import { HistoryCompressor } from './history-compressor.js';
28
25
  import { LiveItemSnapshots } from './live-item-snapshots.js';
29
- import { stampOf } from './transcript-facts.js';
30
26
  import { RunTranscriptFacts } from './transcript-facts-topic.js';
31
- import { hasPlainHistory, historyPaths, readHistoryText, readHistoryTextAsync, restoreHistory } from './history-file.js';
32
- import { collectSecretValues, redactDeep } from '../core/secret-redaction.js';
33
- // Pure, dependency-free reference helpers — the same sanity bound the marker parser applies.
34
- import { archivePullRequests, pullRequestKey } from './pull-requests.js';
35
- import { isRepoScopedRef, promptNamesRepo } from './task-refs.js';
27
+ import { restoreHistory } from './history-file.js';
36
28
  // Type-only module (zod + nothing else), so this cannot cycle back into the store.
37
29
  import { workflowDefSchema } from '../workflows/types.js';
38
30
  import { applyOutcomes } from './outcome-commit.js';
39
- import { ISSUE_URL_RE, namesForeignReference, originatingIssue, refUrlNumber, referencedPrDeclaration, rescopeRun, resolveIssueReference, resolveReferencedRef, restoreOriginatingIssue, scanEventReferences, trackReferencedIssues, trackReferencedPrs } from './run-references.js';
31
+ import { ISSUE_URL_RE, namesForeignReference, referencedPrDeclaration, rescopeRun, resolveReferencedRef, restoreOriginatingIssue, trackReferencedIssues, trackReferencedPrs } from './run-references.js';
40
32
  import { applyExit, doneCommits, exitDurability, RUN_EXITS } from './run-exits.js';
41
33
  import { assertConversationIdFree } from './conversation-identity.js';
42
34
  export { ConversationIdInUseError } from './conversation-identity.js';
@@ -49,16 +41,19 @@ import { failLoadedInterruptedRun, restoreLoadedUsageLimitHold, settleLoadedStop
49
41
  import { hasLegacyWaitFields, UNREADABLE_WAIT } from './legacy-waits.js';
50
42
  export { ciWaitEntry, holdsWorkerWait, upgradeLegacyWaits, workerWaitEntry } from './legacy-waits.js';
51
43
  import { ExitEvents } from './exit-events.js';
52
- import { encodeRunRow, familyRootOf, isLiveRecord, isLiveStatus, materializedWorktreePath, newestFirst } from './run-row.js';
44
+ import { encodeRunRow, familyRootOf, isLiveRecord, materializedWorktreePath, newestFirst } from './run-row.js';
53
45
  import { RunRetentionTopic } from './run-retention.js';
54
46
  import { collectRawExtras, encodeRawRecord } from './raw-record.js';
55
47
  import { ColdReadCache, storedRow } from './cold-reads.js';
56
48
  import { assertNoLegacyCockpit, assertNoLegacyWriter, backUpLegacyIndex, LEGACY_INDEX_FILE, LegacyWriterError, readLegacyIndex } from './legacy-index.js';
57
49
  import { toRunStoreOpenError } from './store-open-error.js';
58
- import { archiveStoreFamily } from './archive-family.js';
59
50
  import { claimStoreFamilies } from './claim-families.js';
60
51
  import { createStoreOwnedRun } from './owned-run-create.js';
61
52
  import { WorkerResultsTopic } from './worker-results.js';
53
+ import { RunEventLogTopic } from './event-log.js';
54
+ import { RunRedaction } from './run-redaction.js';
55
+ import { RunArchiveTopic } from './run-archive.js';
56
+ import { RunReadFlagsTopic } from './run-read-flags.js';
62
57
  import { claimOwnerLive, closeClaimSession, familyKey, foreignClaimedRunIds, liveForeignClaimedRunIds, openClaimSession, rowFamily } from './run-claims.js';
63
58
  import { assertProjectWritable, projectWriteRefused } from '../server/cockpit-ownership.js';
64
59
  /**
@@ -345,21 +340,6 @@ function isDestroyProgress(before, after) {
345
340
  return false;
346
341
  return isDeepStrictEqual({ ...before, destroy: undefined }, { ...after, destroy: undefined });
347
342
  }
348
- /** NDJSON transcript text to events; a damaged line is skipped, never fatal. */
349
- function parseEvents(raw) {
350
- return raw
351
- .split('\n')
352
- .filter(Boolean)
353
- .map((line) => {
354
- try {
355
- return JSON.parse(line);
356
- }
357
- catch {
358
- return null;
359
- }
360
- })
361
- .filter((e) => e !== null);
362
- }
363
343
  /** An archived page's cursor: the last row's order, opaque to clients. A held run with no row yet
364
344
  * lists after every row (`seq` is infinite), which JSON cannot carry, so it travels as null. */
365
345
  function encodeArchivedCursor(key) {
@@ -420,7 +400,7 @@ export class RunStore {
420
400
  published = new RunLifecycle();
421
401
  lifecycle = this.published;
422
402
  /** The lifecycle events run exits write (B12). */
423
- exitEvents = new ExitEvents((id, event) => this.appendEvent(id, event));
403
+ exitEvents = new ExitEvents((id, event) => this.eventLog.appendEvent(id, event));
424
404
  /** Runs gone from memory whose rows the next save or commit deletes. */
425
405
  deleted = new Set();
426
406
  /** Deleted runs whose history files (events, handoff, images, artifacts) go once the delete of
@@ -456,14 +436,20 @@ export class RunStore {
456
436
  /** Rows whose `data` this store tried to decode and could not: left in the database untouched,
457
437
  * and left out of the list rows from then on, as the cold reader leaves them out (run-index.ts). */
458
438
  unreadable = new Set();
459
- /** Background one-at-a-time compressor for archived transcripts (#818). */
460
- 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;
461
443
  /** What the transcript says about a run (hearsay-tools/squawk#4036). */
462
444
  transcriptFacts;
463
445
  /** Whether a run may go, and its deletion; the count-based archive (hearsay-tools/squawk#4037). */
464
446
  retention;
465
447
  /** The saved snapshot of a worker's collected result (hearsay-tools/squawk#4038). */
466
448
  workerResults;
449
+ /** The event log and reference markers (hearsay-tools/squawk#4040). */
450
+ eventLog;
451
+ /** The scrub of events and free text (hearsay-tools/squawk#4040). */
452
+ redaction;
467
453
  executions;
468
454
  /** A worker's execution, process, identity and scope records (hearsay-tools/squawk#4039), built on
469
455
  * first use by the factory this process registered; throws when none is registered. */
@@ -481,6 +467,7 @@ export class RunStore {
481
467
  }
482
468
  constructor(dataDir) {
483
469
  this.dataDir = dataDir;
470
+ this.redaction = new RunRedaction();
484
471
  this.transcriptFacts = new RunTranscriptFacts(dataDir, {
485
472
  isFallbackRun: (id) => this.isFallbackRun(id),
486
473
  sourceDataDir: (id) => this.sourceDataDir(id),
@@ -493,8 +480,14 @@ export class RunStore {
493
480
  this.workerResults = new WorkerResultsTopic(dataDir, {
494
481
  peek: (id) => this.peek(id), hasRun: (id) => this.hasRun(id), hasFallbackRun: (id) => this.hasFallbackRun(id),
495
482
  writeDir: (id) => this.writeDir(id), sourceDataDir: (id) => this.sourceDataDir(id),
496
- redactResult: (result) => this.redact({ type: 'worker-result', seq: 0, ts: result.observedAt, result }).result,
497
- redactText: (text) => this.redactText(text), commitDelegation: (patches) => this.commitDelegation(patches),
483
+ redactResult: (result) => this.redaction.redact({ type: 'worker-result', seq: 0, ts: result.observedAt, result }).result,
484
+ redactText: (text) => this.redaction.redactText(text), commitDelegation: (patches) => this.commitDelegation(patches),
485
+ });
486
+ this.eventLog = new RunEventLogTopic(dataDir, {
487
+ seqs: this.seqs, published: this.published, liveItems: this.liveItems, transcriptFacts: this.transcriptFacts, redaction: this.redaction,
488
+ record: (id) => this.record(id), missingRunError: (runId) => this.missingRunError(runId), sourceDataDir: (id) => this.sourceDataDir(id),
489
+ touch: (run, before) => this.touch(run, before), change: (id, apply) => this.change(id, apply), repoHandle: () => this.repoHandle,
490
+ maybeEnqueueHistoryCompress: (run) => this.archive.maybeEnqueueHistoryCompress(run),
498
491
  });
499
492
  this.retention = new RunRetentionTopic(dataDir, {
500
493
  db: () => this.db, held: this.held, deleted: this.deleted, quarantined: this.quarantined,
@@ -504,7 +497,7 @@ export class RunStore {
504
497
  hasFallbackRun: (id) => this.hasFallbackRun(id), listOrder: (run) => this.listOrder(run),
505
498
  claimFamilies: (families) => this.claimFamilies(families), markDeleted: (id, family) => this.markDeleted(id, family),
506
499
  scheduleSave: () => this.scheduleSave(), commitIndex: (input) => this.commitIndex(input),
507
- 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),
508
501
  workerDeletionEvidence: (id) => this.workerExecutions.workerDeletionEvidence(id),
509
502
  workerResults: this.workerResults,
510
503
  readWorkerExecution: (id) => this.workerExecutions.readWorkerExecution(id), identityPath: (id) => this.workerExecutions.identityPath(id),
@@ -512,7 +505,22 @@ export class RunStore {
512
505
  executionPath: (id) => this.workerExecutions.executionPath(id), handoffPath: (runId) => this.handoffPath(runId),
513
506
  imagesDir: (runId) => this.imagesDir(runId),
514
507
  });
515
- 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
+ });
516
524
  }
517
525
  /**
518
526
  * Open the project's run store. See `reconcileLoadedRun` for what `keepLive` (#367) decides
@@ -803,6 +811,15 @@ export class RunStore {
803
811
  }
804
812
  fallbackRefusal(id) { return new RunWriteRefusedError(id, 'fallback', fallbackRunDeleteError(this.dataDir, true)); }
805
813
  /** Run files are written only for a family this store may write, never a fallback family. */
814
+ /** The error `appendEvent` throws for a run this store cannot write or does not know. */
815
+ missingRunError(runId) {
816
+ const ownership = this.runOwnership(runId);
817
+ if (ownership === 'fallback')
818
+ return this.fallbackRefusal(runId);
819
+ if (ownership === 'foreign' || ownership === 'orphaned' || ownership === 'quarantined')
820
+ return new RunWriteRefusedError(runId, ownership);
821
+ return new Error(`unknown run: ${runId}`);
822
+ }
806
823
  writeDir(id) { if (this.runOwnership(id) === 'fallback')
807
824
  throw this.fallbackRefusal(id); return runDataDir(this.dataDir, id); }
808
825
  /** Every run whose family another process owns (`foreignClaimedRunIds`). */
@@ -1489,7 +1506,7 @@ export class RunStore {
1489
1506
  // scrubbed: it is the user's own prompt and is replayed into `{{task}}`
1490
1507
  // when a queued run is revived after a restart (#367), so redacting it
1491
1508
  // would corrupt the revived run.
1492
- title: this.redactText(input.title),
1509
+ title: this.redaction.redactText(input.title),
1493
1510
  workflow: input.workflow,
1494
1511
  task: input.task,
1495
1512
  model: input.model,
@@ -1533,9 +1550,9 @@ export class RunStore {
1533
1550
  const root = this.peek(rootId);
1534
1551
  if (root?.delegation?.role !== 'root')
1535
1552
  throw new Error('missing conversation root');
1536
- assertConversationIdFree(root, message ?? delivery?.input, id => this.peek(id), (runId, id) => this.hasProjection(runId, id));
1553
+ assertConversationIdFree(root, message ?? delivery?.input, id => this.peek(id), (runId, id) => this.eventLog.hasProjection(runId, id));
1537
1554
  const staged = new Map();
1538
- stageConversation(staged, root, conversation, delivery, id => this.peek(id), text => this.redactText(text));
1555
+ stageConversation(staged, root, conversation, delivery, id => this.peek(id), text => this.redaction.redactText(text));
1539
1556
  this.commitIndex(staged);
1540
1557
  }
1541
1558
  /** Crash recovery (#505): input a harness accepted but was never seen reading goes
@@ -1798,12 +1815,12 @@ export class RunStore {
1798
1815
  };
1799
1816
  staged.set(id, next);
1800
1817
  if (Object.prototype.hasOwnProperty.call(patch, 'archived'))
1801
- this.syncTranscriptForm(id, next.archived);
1818
+ this.archive.syncTranscriptForm(id, next.archived);
1802
1819
  if (conversation) {
1803
1820
  const root = this.peek(conversation.rootId);
1804
1821
  if (root?.delegation?.role !== 'root' || run.delegation.parentRunId !== root.id)
1805
1822
  throw new Error('missing conversation ownership');
1806
- stageConversation(staged, root, conversation.state, { recipientRunId: id, input: conversation.input }, runId => this.peek(runId), text => this.redactText(text));
1823
+ stageConversation(staged, root, conversation.state, { recipientRunId: id, input: conversation.input }, runId => this.peek(runId), text => this.redaction.redactText(text));
1807
1824
  }
1808
1825
  this.commitIndex(staged, undefined, { exits: new Map([[id, exit]]) });
1809
1826
  }
@@ -1828,8 +1845,8 @@ export class RunStore {
1828
1845
  const exits = new Map(write.exits);
1829
1846
  const staged = stageCommit(input, {
1830
1847
  peek: id => this.peek(id),
1831
- completionArchiveBlocker: run => this.completionArchiveBlocker(run),
1832
- 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),
1833
1850
  });
1834
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)]));
1835
1852
  if (!this.db)
@@ -1867,79 +1884,7 @@ export class RunStore {
1867
1884
  }
1868
1885
  for (const [id, next] of staged)
1869
1886
  if (next?.archived)
1870
- this.compressor.enqueue(id);
1871
- }
1872
- completionArchiveBlocker(root) {
1873
- const family = [root, ...this.listWorkersOf(root.id)];
1874
- for (const run of family) {
1875
- const facts = this.transcriptFacts.factsFor(run.id).peek(run.id);
1876
- if (!facts || !['done', 'review', 'failed', 'cancelled'].includes(run.status) || run.waits?.some(wait => wait.phase === 'open') ||
1877
- run.hasPendingPermission || facts.pendingAsk !== undefined)
1878
- return 'Task or worker work still needs attention. Open the task or archive manually.';
1879
- if (run.delegation?.role === 'invalid' || (run.delegation?.role === 'worker' && this.workerExecutions.readWorkerExecution(run.id)?.phase !== 'complete'))
1880
- return 'Worker execution has not settled. Open the worker or archive manually.';
1881
- }
1882
- return undefined;
1883
- }
1884
- /** One archive write for manual actions, merge observations, completion, and sweeps.
1885
- * Archiving files history away; it never stops a process or removes a worktree. */
1886
- stageArchive(staged, root, archived, exits) {
1887
- const ids = root.delegation?.role === 'worker' ? [root.id] :
1888
- [root.id, ...new Set([...(this.db?.listIdsByParent(root.id) ?? []), ...this.listWorkersOf(root.id).map(run => run.id)])];
1889
- const now = new Date().toISOString();
1890
- for (const id of ids) {
1891
- const member = staged.get(id) ?? this.peek(id);
1892
- if (!member)
1893
- continue;
1894
- if (!archived) {
1895
- this.compressor.cancel(id);
1896
- restoreHistory(this.dataDir, id);
1897
- }
1898
- const next = { ...member, archiveBlocker: undefined };
1899
- const exit = archiveFields(next, archived, now);
1900
- if (exit)
1901
- exits?.set(id, exit);
1902
- staged.set(id, next);
1903
- }
1904
- }
1905
- /** A bounded persisted queue also covers projects without a live RunManager. */
1906
- listCompletionCandidates(afterSeq = 0, limit = 32) {
1907
- return this.db?.listCompletionCandidates(afterSeq, limit) ?? [];
1908
- }
1909
- canCompleteAction(id, token) {
1910
- const run = this.record(id);
1911
- return Boolean(run && run.status === 'done' && !run.archived && (run.autoMergePr || run.archiveWhenDone) &&
1912
- run.completionAction?.id === token && run.completionAction.phase !== 'complete' && !this.writeRefusal(id));
1913
- }
1914
- claimCompletionAction(id, token) {
1915
- if (!this.canCompleteAction(id, token))
1916
- return false;
1917
- const run = this.record(id);
1918
- this.assertWritable(new Map([[id, run]]));
1919
- // A normal write may defer its claim until the transaction. A remote mutation
1920
- // needs the committed claim now, and must not act on a stale row read before it.
1921
- const claim = this.db?.getClaim(familyKey(run));
1922
- return Boolean(claim && claim.session === this.owner?.session &&
1923
- claim.generation === this.claimed.get(familyKey(run)) &&
1924
- this.db?.get(id)?.revision === this.base.get(id)?.revision);
1925
- }
1926
- completeAction(id, token, phase, message) {
1927
- const run = this.record(id);
1928
- if (!run || !this.canCompleteAction(id, token))
1929
- return false;
1930
- if (run.completionAction?.phase === phase && run.completionAction.message === message)
1931
- return true;
1932
- const next = { ...run, completionAction: { id: token, phase, ...(message ? { message } : {}) } };
1933
- const staged = new Map([[id, next]]);
1934
- if (phase === 'complete' && next.archiveWhenDone) {
1935
- const blocker = this.completionArchiveBlocker(next);
1936
- if (blocker)
1937
- next.completionAction = { id: token, phase: 'blocked', message: blocker };
1938
- else
1939
- this.stageArchive(staged, next, true);
1940
- }
1941
- this.commitIndex(staged);
1942
- return true;
1887
+ this.archive.compressor.enqueue(id);
1943
1888
  }
1944
1889
  /**
1945
1890
  * Refuse (throwing, with nothing changed) a commit that stages a quarantined run, or a run whose
@@ -2026,10 +1971,10 @@ export class RunStore {
2026
1971
  writeRun(id, run, patch, durability, exit) {
2027
1972
  const before = snapshotRun(run);
2028
1973
  const hooks = {
2029
- redact: (text) => this.redactText(text),
1974
+ redact: (text) => this.redaction.redactText(text),
2030
1975
  repoHandle: this.repoHandle,
2031
1976
  restore: () => restoreHistory(this.dataDir, id),
2032
- archive: (record, archived) => this.applyArchived(record, archived, before, exit),
1977
+ archive: (record, archived) => this.archive.applyArchived(record, archived, before, exit),
2033
1978
  touch: (record) => this.touch(record, before, exit),
2034
1979
  };
2035
1980
  if (durability === 'committed') {
@@ -2041,7 +1986,7 @@ export class RunStore {
2041
1986
  return run;
2042
1987
  }
2043
1988
  redactPatch(patch) {
2044
- return redactPatch(patch, text => this.redactText(text));
1989
+ return redactPatch(patch, text => this.redaction.redactText(text));
2045
1990
  }
2046
1991
  /** Append a step to an existing run (used by "Continue" — spec 003). */
2047
1992
  addStep(runId, step) {
@@ -2057,274 +2002,12 @@ export class RunStore {
2057
2002
  const step = run?.steps.find((s) => s.id === stepId);
2058
2003
  if (!run || !step)
2059
2004
  return;
2060
- const before = snapshotRun(run), next = { ...step, ...stageStepUpdate(patch, text => this.redactText(text)) };
2005
+ const before = snapshotRun(run), next = { ...step, ...stageStepUpdate(patch, text => this.redaction.redactText(text)) };
2061
2006
  // Replaced, never changed in place, so `before` keeps the steps as they were.
2062
2007
  run.steps = run.steps.map((candidate) => candidate === step ? next : candidate);
2063
2008
  Object.assign(run, stepTotals(run.steps));
2064
2009
  this.touch(run, before);
2065
2010
  }
2066
- listArchiveOnMergeCandidates(afterSeq = 0, limit = 32) {
2067
- return this.db?.listArchiveOnMergeCandidates(afterSeq, limit) ?? [];
2068
- }
2069
- /** Use unnormalized persisted evidence: cold reads must not turn interrupted work into safety. */
2070
- archiveFamily(id, isActive) {
2071
- return archiveStoreFamily({
2072
- db: this.db,
2073
- held: this.held,
2074
- deleted: this.deleted,
2075
- quarantined: this.quarantined,
2076
- pins: this.pins,
2077
- listWorkersOf: (parentId) => this.listWorkersOf(parentId),
2078
- setArchiveBlocker: (runId, blocker) => this.setArchiveBlocker(runId, blocker),
2079
- decodeRunRow,
2080
- decodeCold: (row) => this.decodeCold(row),
2081
- writeRefusal: (memberId) => this.writeRefusal(memberId),
2082
- factsPeek: (memberId) => this.transcriptFacts.factsFor(memberId).peek(memberId),
2083
- readWorkerExecution: (memberId) => this.workerExecutions.readWorkerExecution(memberId),
2084
- }, id, isActive);
2085
- }
2086
- /** Blockers are feedback, never archive authority or cleanup permission. */
2087
- setArchiveBlocker(id, blocker) {
2088
- const run = this.record(id);
2089
- if (!run || run.archived || isDeepStrictEqual(run.archiveBlocker, blocker))
2090
- return;
2091
- this.commitIndex(new Map([[id, { ...run, archiveBlocker: blocker }]]));
2092
- }
2093
- archiveMergeBlocker(snapshot, missing, repoBase) {
2094
- const url = `https://github.com/${missing.owner}/${missing.repo}/pull/${missing.number}`;
2095
- const family = [snapshot.rootId, ...(this.db?.listIdsByParent(snapshot.rootId) ?? [])].flatMap(id => {
2096
- const run = this.peek(id);
2097
- return run ? [run] : [];
2098
- });
2099
- const member = family.find(run => archivePullRequests([run], repoBase)?.some(pr => pullRequestKey(pr) === pullRequestKey(missing)));
2100
- this.setArchiveBlocker(snapshot.rootId, { message: `PR ${missing.owner}/${missing.repo}#${missing.number} is not confirmed merged. Check the PR association or archive manually.`,
2101
- runId: member?.id ?? snapshot.rootId, pullRequestUrl: url });
2102
- }
2103
- hasArchiveOnMergeAssociations(id) {
2104
- return this.db?.archiveFamilyHasPullRequests(id) ?? false;
2105
- }
2106
- async prepareArchiveOnMerge(id) {
2107
- const ids = [id, ...(this.db?.listIdsByParent(id) ?? [])];
2108
- if (ids.length > 1025)
2109
- return;
2110
- for (const memberId of ids)
2111
- await this.transcriptFacts.factsFor(memberId).ready(memberId);
2112
- }
2113
- archiveOnMergeSnapshot(id, repoBase, isActive = () => false) {
2114
- const family = this.archiveFamily(id, isActive);
2115
- if (!family)
2116
- return undefined;
2117
- return this.archiveSnapshot(family, repoBase);
2118
- }
2119
- archiveSnapshot(family, repoBase) {
2120
- const pullRequests = archivePullRequests(family, repoBase);
2121
- if (!pullRequests) {
2122
- this.setArchiveBlocker(family[0].id, { message: 'PR associations cannot be resolved. Check task and worker PRs, or archive manually.' });
2123
- return undefined;
2124
- }
2125
- const fingerprint = archiveDigest(pullRequests);
2126
- if (family[0].autoArchive?.fingerprint === fingerprint)
2127
- return undefined;
2128
- return { rootId: family[0].id, fingerprint, pullRequests, token: archiveDigest(family.map(({ archiveBlocker: _blocker, ...run }) => run)) };
2129
- }
2130
- /** No await between final revalidation and the fenced, all-or-nothing cascade. */
2131
- archiveAfterMerge(snapshot, observations, repoBase, isActive = () => false) {
2132
- const family = this.archiveFamily(snapshot.rootId, isActive);
2133
- if (!family)
2134
- return false;
2135
- const current = this.archiveSnapshot(family, repoBase);
2136
- if (!current || current.token !== snapshot.token || current.fingerprint !== snapshot.fingerprint)
2137
- return false;
2138
- const parsed = observations.map(observation => mergedPullRequestSchema.safeParse(observation));
2139
- if (parsed.some(result => !result.success))
2140
- return false;
2141
- const merged = parsed.flatMap(result => result.success ? [result.data] : []);
2142
- const byKey = new Map(merged.map(pr => [pullRequestKey(pr), pr]));
2143
- if (byKey.size !== current.pullRequests.length || current.pullRequests.some(pr => !byKey.has(pullRequestKey(pr))))
2144
- return false;
2145
- const restoredAt = Math.max(0, ...family.map(run => run.manualUnarchivedAt ? Date.parse(run.manualUnarchivedAt) : 0));
2146
- if (restoredAt && merged.every(pr => Date.parse(pr.mergedAt) <= restoredAt))
2147
- return false;
2148
- const now = new Date().toISOString();
2149
- if (merged.some(pr => Date.parse(pr.mergedAt) > Date.parse(now)))
2150
- return false;
2151
- const staged = new Map(), exits = new Map();
2152
- this.stageArchive(staged, family[0], true, exits);
2153
- staged.get(snapshot.rootId).autoArchive = { reason: 'pull-requests-merged', archivedAt: now, fingerprint: current.fingerprint, pullRequests: merged };
2154
- this.commitIndex(staged, undefined, { exits });
2155
- for (const id of staged.keys())
2156
- this.compressor.enqueue(id);
2157
- return true;
2158
- }
2159
- setArchived(id, archived) {
2160
- const run = this.record(id);
2161
- if (!run)
2162
- return undefined;
2163
- this.applyArchivedCascade(run, archived);
2164
- return run;
2165
- }
2166
- /** Parent + owned workers; returns how many records flipped `archived`. */
2167
- applyArchivedCascade(run, archived) {
2168
- const staged = new Map(), exits = new Map();
2169
- this.stageArchive(staged, run, archived, exits);
2170
- let changed = 0;
2171
- for (const [id, next] of staged) {
2172
- if (next && this.peek(id)?.archived !== archived)
2173
- changed++;
2174
- if (next)
2175
- next.completionAction = undefined; // an explicit filing/restoration retires pending work
2176
- }
2177
- this.commitIndex(staged, undefined, { exits });
2178
- return changed;
2179
- }
2180
- applyArchived(run, archived, before = snapshotRun(run), exit) {
2181
- const changed = run.archived !== archived;
2182
- // Transcript first: a restore throw aborts with the record unchanged (#818 S3).
2183
- this.syncTranscriptForm(run.id, archived);
2184
- this.touch(run, before, archiveFields(run, archived, new Date().toISOString()) ?? exit);
2185
- return changed;
2186
- }
2187
- /** Transcript form follows `archived`: enqueue compression, or restore the plain file now. */
2188
- syncTranscriptForm(id, archived) {
2189
- if (archived)
2190
- this.compressor.enqueue(id);
2191
- else {
2192
- this.compressor.cancel(id);
2193
- restoreHistory(this.dataDir, id);
2194
- }
2195
- }
2196
- /**
2197
- * Whether this store may compress `id`'s transcript: the run exists, is archived, is not in a
2198
- * live status (queued/running/waiting), and this process holds the family's claim in `claimed`
2199
- * (not merely `pendingClaims`). Two processes never both write a run (#779, #818 B1).
2200
- */
2201
- isHistoryCompressEligible(id) {
2202
- if (this.deleted.has(id))
2203
- return false;
2204
- try {
2205
- const run = this.held.get(id) ?? this.peek(id);
2206
- if (!run || run.archived !== true || isLiveStatus(run.status))
2207
- return false;
2208
- return this.holdsCompressClaim(id);
2209
- }
2210
- catch {
2211
- return false;
2212
- }
2213
- }
2214
- /** Take the family claim if free and require it to be in `this.claimed`, not only pending. */
2215
- holdsCompressClaim(id) {
2216
- const family = this.familyOf(id);
2217
- return this.claimFamilies([family]).has(family) && this.claimed.has(family);
2218
- }
2219
- /** Startup sweep: enqueue every archived non-live run that still has a plain transcript. */
2220
- compressArchivedHistory() {
2221
- try {
2222
- const ids = new Set();
2223
- for (const key of this.db?.listKeysWhere('archived = 1 AND live = 0') ?? []) {
2224
- if (!this.deleted.has(key.id))
2225
- ids.add(key.id);
2226
- }
2227
- for (const run of this.held.values()) {
2228
- if (run.archived && !isLiveStatus(run.status) && !this.deleted.has(run.id))
2229
- ids.add(run.id);
2230
- }
2231
- for (const id of ids) {
2232
- try {
2233
- const { plain } = historyPaths(this.dataDir, id);
2234
- // Claim only ids with work: a plain file to compress, including both-present leftovers.
2235
- if (!existsSync(plain))
2236
- continue;
2237
- if (!this.holdsCompressClaim(id))
2238
- continue;
2239
- if (hasPlainHistory(this.dataDir, id))
2240
- this.compressor.enqueue(id);
2241
- }
2242
- catch {
2243
- // Best effort: one id must not stop the sweep or boot (#818 S2).
2244
- }
2245
- }
2246
- }
2247
- catch {
2248
- // listKeysWhere / open-time fs: never throw out of boot.
2249
- }
2250
- }
2251
- /** Resolves when the transcript compressor is idle (tests, shutdown). */
2252
- historyIdle() {
2253
- return this.compressor.idle();
2254
- }
2255
- /** Pin one run to the top of this project's task list, or unpin it (#935). Mirrors
2256
- * `setArchived`: sets the fields, then persists + broadcasts via `touch`, so the updated
2257
- * record rides the existing `run` SSE with no new event. Idempotent — re-pinning a pinned
2258
- * run just re-stamps `pinnedAt`.
2259
- *
2260
- * Every active status is pinnable. Archived requests clear stale metadata instead, so a
2261
- * late click racing archive cannot leave a hidden pin that reappears on unarchive. */
2262
- setPinned(id, pinned) {
2263
- return this.change(id, (run) => {
2264
- if (pinned && !run.archived) {
2265
- run.pinned = true;
2266
- run.pinnedAt = new Date().toISOString();
2267
- }
2268
- else {
2269
- clearPin(run);
2270
- }
2271
- });
2272
- }
2273
- /** Bulk-archive finished runs (#780). `isSweepable` decides which; `archived` counts every
2274
- * record that flipped (cascaded workers included), `ids` lists the top-level runs picked and
2275
- * `pinnedIds` the subset that carried a pin before `clearPin` dropped it. */
2276
- archiveFinished(scope, automation) {
2277
- let archived = 0;
2278
- // Snapshot first: cascade may archive still-live workers, mutating the held set, and the pin
2279
- // has to be read before `applyArchived` clears it. Runs not in memory are picked off their
2280
- // stored summary, which carries every field `isSweepable` reads.
2281
- const picked = [...this.held.values()].filter((run) => SWEEPABLE_RUN_RULE.matches({ ...run, automationId: automationIdOf(run) }, scope, automation))
2282
- .map((run) => [run, this.listOrder(run)]);
2283
- for (const row of this.db?.listWhere(SWEEPABLE_RUN_RULE.sql) ?? []) {
2284
- if (this.held.has(row.id) || this.deleted.has(row.id))
2285
- continue;
2286
- const summary = parseStoredSummary(row.summary);
2287
- if (summary && SWEEPABLE_RUN_RULE.matches(summary, scope, automation))
2288
- picked.push([summary, row]);
2289
- }
2290
- // Another process's runs are not this store's to archive (#779, plan step 3): they stay out.
2291
- // A sweepable run is never a worker (`isSweepable`), so each is its own family.
2292
- const writable = this.claimFamilies(picked.map(([run]) => run.id));
2293
- const mine = sortNewestFirst(picked.filter(([run]) => writable.has(run.id)));
2294
- const ids = mine.map((run) => run.id);
2295
- const pinnedIds = mine.filter((run) => run.pinned).map((run) => run.id);
2296
- for (const id of ids) {
2297
- // Re-check: a prior cascade may already have archived this id.
2298
- const run = this.record(id);
2299
- if (!run || run.archived)
2300
- continue;
2301
- archived += this.applyArchivedCascade(run, true);
2302
- }
2303
- return { archived, ids, pinnedIds };
2304
- }
2305
- /** Mark one run as read (#unread-done-items): stamp the read receipt now. Mirrors
2306
- * `setArchived` — sets the field then persists + broadcasts via `touch`, so the
2307
- * updated record rides the existing `run` SSE with no new event. Idempotent by
2308
- * design: opening an already-read thread just re-stamps a later `seenAt`. */
2309
- setRead(id) {
2310
- return this.change(id, (run) => { run.seenAt = new Date().toISOString(); });
2311
- }
2312
- /** Mark one run as UNread (#775): drop the read receipt so the run rejoins the unread
2313
- * list. The inverse of `setRead` and, like it, `touch`es so the updated record rides the
2314
- * existing `run` SSE.
2315
- *
2316
- * Deleting the field rather than adding a "manually unread" flag is the whole point:
2317
- * absent `seenAt` is ALREADY what every reader treats as unread (`isUnread` in the
2318
- * cockpit's read-state.ts, and `markAllRead`'s clause-for-clause copy of it below), so
2319
- * clearing needs no new state and writes a shape any older Squawk already parses.
2320
- *
2321
- * Deliberately unconditional: clearing a receipt is always a legal write, so this
2322
- * succeeds for an already-unread run (idempotent) and for statuses that can never wear
2323
- * the marker. WHETHER the action means anything for a given run is UI policy, and lives
2324
- * in the cockpit's `runActionFlags` — the same split the rest of the store keeps. */
2325
- setUnread(id) {
2326
- return this.change(id, (run) => { delete run.seenAt; });
2327
- }
2328
2011
  /** A debounced write of the held record `id`: `apply` changes it in place, then `touch` saves it. */
2329
2012
  change(id, apply) {
2330
2013
  const run = this.record(id), before = snapshotRun(run);
@@ -2334,183 +2017,6 @@ export class RunStore {
2334
2017
  this.touch(run, before);
2335
2018
  return run;
2336
2019
  }
2337
- /**
2338
- * Stamp unread finished runs in bulk and return the count. Keep the rule aligned with cockpit
2339
- * isUnread: done/failed, finished since seen, not archived; cancelled and usage-limit waiting
2340
- * runs are excluded. `automation` narrows it to one origin, as in `archiveFinished`
2341
- * (hearsay-tools/cezarion#1616); absent stamps both.
2342
- */
2343
- markAllRead(automation) {
2344
- const now = new Date().toISOString();
2345
- let count = 0;
2346
- // Runs not in memory are picked by the same rule over their stored summary, then re-checked
2347
- // on the record before they are stamped.
2348
- const candidates = [...this.held.values()];
2349
- const stored = (this.db?.listWhere(guardedJsonSql(UNREAD_RUN_RULE.sql, 0)) ?? []).filter((row) => !this.held.has(row.id) && !this.deleted.has(row.id));
2350
- // One claim transaction for them all; another process's runs are skipped (`record` refuses).
2351
- this.claimFamilies(stored.map(rowFamily));
2352
- for (const row of stored) {
2353
- const run = this.record(row.id);
2354
- if (run)
2355
- candidates.push(run);
2356
- }
2357
- for (const run of candidates) {
2358
- const unread = UNREAD_RUN_RULE.matches(run);
2359
- if (!unread)
2360
- continue;
2361
- if (automation !== undefined && (automationIdOf(run) !== undefined) !== automation)
2362
- continue;
2363
- const before = snapshotRun(run);
2364
- run.seenAt = now;
2365
- this.touch(run, before);
2366
- count++;
2367
- }
2368
- return count;
2369
- }
2370
- appendEvent(runId, event) {
2371
- const run = this.record(runId);
2372
- if (!run) {
2373
- const ownership = this.runOwnership(runId);
2374
- if (ownership === 'fallback')
2375
- throw this.fallbackRefusal(runId);
2376
- if (ownership === 'foreign' || ownership === 'orphaned' || ownership === 'quarantined')
2377
- throw new RunWriteRefusedError(runId, ownership);
2378
- throw new Error(`unknown run: ${runId}`);
2379
- }
2380
- const seq = this.nextSeq(runId);
2381
- // Scrub credentials before the event touches disk or the live wire (#427):
2382
- // tool-result output is persisted verbatim and served back over the API, so
2383
- // a secret in an agent's command output would otherwise land in `.ai/cezar/`.
2384
- const full = this.redact(defined({ ...event, seq, ts: new Date().toISOString() }));
2385
- // Sync append keeps event order without a write queue; local NDJSON
2386
- // appends at agent-event rates are effectively free.
2387
- if (!hasPlainHistory(this.dataDir, runId))
2388
- restoreHistory(this.dataDir, runId);
2389
- const line = `${JSON.stringify(full)}\n`;
2390
- appendFileSync(this.eventsPath(runId), line, 'utf8');
2391
- this.transcriptFacts.index.append(runId, full, Buffer.byteLength(line));
2392
- this.maybeEnqueueHistoryCompress(run);
2393
- this.liveItems.observe(runId, full, false);
2394
- this.published.publish('run.event', { runId, event: full });
2395
- // Reference discovery runs last, after the event is persisted, indexed and
2396
- // published: the janitor reads the event text and may still update the run.
2397
- const before = snapshotRun(run);
2398
- scanEventReferences(run, full, this.repoHandle, (target, entries) => this.accumulatePullRequests(target, entries), (target) => this.touch(target, before));
2399
- return full;
2400
- }
2401
- /**
2402
- * Apply agent-declared reference markers (spec 2026-07-18-task-ref-markers).
2403
- * Marker values are authoritative for the display tier: they overwrite the
2404
- * regex/namer numbers unless the prompt identifies the originating issue, and a declared PR re-resolves the referenced URL
2405
- * against the candidate working set — including down to `undefined` when no
2406
- * candidate matches (a wrong chip is worse than no chip). The created tier
2407
- * (`pullRequestUrl`) is deliberately untouched.
2408
- *
2409
- * One declaration is NOT a statement about the referenced tier: the number of the PR this run
2410
- * itself created. See `referencedPrDeclaration` — the marker contract asks the agent to
2411
- * re-declare after it opens a PR, and taking that literally cost the task the PR it was about.
2412
- */
2413
- applyMarkerRefs(runId, refs) {
2414
- if (refs.pr === undefined && refs.issue === undefined)
2415
- return this.record(runId);
2416
- return this.change(runId, (run) => {
2417
- const numbers = [...new Set([...(run.markerRefs?.pr === undefined ? [] : [run.markerRefs.pr]),
2418
- ...(refs.prs ?? (refs.pr === undefined ? [] : [refs.pr]))])];
2419
- if (numbers.length)
2420
- this.accumulatePullRequests(run, numbers.flatMap((number) => {
2421
- const matches = (run.referencedPrCandidates ?? []).filter((url) => refUrlNumber(url) === number &&
2422
- (this.repoHandle ? isRepoScopedRef(url, run.task, this.repoHandle) : promptNamesRepo(url, run.task)));
2423
- const url = matches.length === 1 ? matches[0] : matches.length === 0 && this.repoHandle
2424
- ? `https://github.com/${this.repoHandle.owner}/${this.repoHandle.name}/pull/${number}` : undefined;
2425
- const parsed = runPullRequestSchema.safeParse({ number, ...(url ? { url } : {}), source: 'declared' });
2426
- return parsed.success ? [parsed.data] : [];
2427
- }));
2428
- run.markerRefs = {
2429
- ...run.markerRefs,
2430
- ...(refs.pr !== undefined ? { pr: refs.pr } : {}),
2431
- ...(refs.issue !== undefined ? { issue: refs.issue } : {}),
2432
- };
2433
- // `prNumber` is the about-PR as well (it is what paints a numeric-only chip), so a
2434
- // re-declaration naming the created PR only FILLS it — it never overwrites the number the
2435
- // task came in with, which is still the PR this task is about.
2436
- if (refs.pr !== undefined && (run.prNumber === undefined || refs.pr !== refUrlNumber(run.pullRequestUrl))) {
2437
- run.prNumber = refs.pr;
2438
- }
2439
- if (refs.issue !== undefined) {
2440
- run.issueNumber = originatingIssue(run) ?? refs.issue;
2441
- delete run.referencedIssueNumberSeeded;
2442
- }
2443
- if (run.markerRefs.pr !== undefined) {
2444
- run.referencedPullRequestUrl = resolveReferencedRef(run.referencedPrCandidates ?? [], run.task, referencedPrDeclaration(run), this.repoHandle);
2445
- }
2446
- if (run.markerRefs.issue !== undefined) {
2447
- run.referencedIssueUrl = resolveIssueReference(run, this.repoHandle);
2448
- }
2449
- });
2450
- }
2451
- /** Authoritative creation keeps the first scalar for publishing, plus every created identity. */
2452
- recordCreatedPr(runId, url) {
2453
- const run = this.record(runId);
2454
- const parsed = runPullRequestSchema.safeParse({ number: refUrlNumber(url), url, source: 'created' });
2455
- if (!run || !parsed.success)
2456
- return run;
2457
- const before = snapshotRun(run);
2458
- let changed = this.accumulatePullRequests(run, [parsed.data]);
2459
- if (!run.pullRequestUrl) {
2460
- run.pullRequestUrl = url;
2461
- changed = true;
2462
- }
2463
- if (changed)
2464
- this.touch(run, before);
2465
- return run;
2466
- }
2467
- accumulatePullRequests(run, entries) {
2468
- return stagePullRequests(run, entries, this.repoHandle);
2469
- }
2470
- /**
2471
- * Fan an event out to live subscribers WITHOUT writing it to the NDJSON
2472
- * file — the channel for coalesced `item.delta` flushes (protocol-v2
2473
- * performance guardrail: raw deltas never hit disk; replay = the persisted
2474
- * snapshots). Stamped with `seq`/`ts` like persisted lines so the live
2475
- * wire keeps one ordering axis. Finite polling coalesces active item content
2476
- * into bounded in-memory snapshots on that clock; disk replay still has gaps
2477
- * (dedup compares with `>`).
2478
- */
2479
- emitEphemeral(runId, event) {
2480
- const full = this.redact({ ...event, seq: this.nextSeq(runId), ts: new Date().toISOString() });
2481
- this.liveItems.observe(runId, full, true);
2482
- this.published.publish('run.event', { runId, event: full });
2483
- return full;
2484
- }
2485
- /** Lazily-collected concrete secret values from the host env (#427). */
2486
- secretValues = null;
2487
- /** Controller-issued tokens never persist, including when host-secret redaction is disabled. */
2488
- sessionSecrets = new Set();
2489
- registerSessionSecret(value) { this.sessionSecrets.add(value); }
2490
- containsSessionSecret(value) { return [...this.sessionSecrets].some(secret => value.includes(secret)); }
2491
- /**
2492
- * Scrub known credential values / token shapes from an event before it is
2493
- * persisted or fanned out. On by default; `CEZ_REDACT_SECRETS=0` opts out.
2494
- */
2495
- redact(event) {
2496
- const safe = this.sessionSecrets.size ? redactDeep(event, [...this.sessionSecrets]) : event;
2497
- if (productEnv('REDACT_SECRETS') === '0')
2498
- return safe;
2499
- return redactDeep(safe, this.hostSecrets());
2500
- }
2501
- /** Best-effort scrub of one free-text string bound for `runs.json`. Honors
2502
- * the `CEZ_REDACT_SECRETS=0` opt-out itself so every caller inherits it. */
2503
- redactText(text) {
2504
- return redactText(text, [...this.sessionSecrets], () => this.hostSecrets());
2505
- }
2506
- hostSecrets() {
2507
- if (this.secretValues === null)
2508
- this.secretValues = collectSecretValues();
2509
- return this.secretValues;
2510
- }
2511
- hasProjection(runId, projectionId) {
2512
- return this.transcriptFacts.transcriptFacts(runId).projectionIds.includes(projectionId);
2513
- }
2514
2020
  /** Indexed family enumeration, including members not yet flushed to SQLite. */
2515
2021
  listFamilyRunIds(rootId) {
2516
2022
  const ids = new Set([rootId, ...(this.db?.listIdsByParent(rootId) ?? [])]);
@@ -2524,27 +2030,6 @@ export class RunStore {
2524
2030
  ids.delete(id);
2525
2031
  return [...ids];
2526
2032
  }
2527
- /** `readEvents` off the event loop (async read and async brotli), for collection paths. */
2528
- async readEventsAsync(runId) {
2529
- try {
2530
- const raw = await readHistoryTextAsync(this.sourceDataDir(runId), runId);
2531
- return raw === undefined ? [] : parseEvents(raw);
2532
- }
2533
- catch {
2534
- return [];
2535
- }
2536
- }
2537
- readEvents(runId) {
2538
- try {
2539
- const raw = readHistoryText(this.sourceDataDir(runId), runId);
2540
- if (raw === undefined)
2541
- return [];
2542
- return parseEvents(raw);
2543
- }
2544
- catch {
2545
- return [];
2546
- }
2547
- }
2548
2033
  /** Write the pending rows out now (used on shutdown). */
2549
2034
  flush() {
2550
2035
  if (this.saveTimer) {
@@ -2555,22 +2040,6 @@ export class RunStore {
2555
2040
  }
2556
2041
  // ---- internals -----------------------------------------------------------
2557
2042
  seqs = new Map();
2558
- nextSeq(runId) {
2559
- const next = (this.seqs.get(runId) ?? this.rehydrateSeq(runId)) + 1;
2560
- this.seqs.set(runId, next);
2561
- return next;
2562
- }
2563
- /** After a restart the in-memory counter is empty while the run's NDJSON file
2564
- * keeps the history. Restarting from 1 would collide with the seqs a client
2565
- * already replayed — its `seq > maxSeq` dedup then silently drops every
2566
- * resumed event, even across a reload (the frozen-transcript symptom class
2567
- * of #424). One file read on the first post-restart append per run. */
2568
- rehydrateSeq(runId) {
2569
- return this.transcriptFacts.transcriptFacts(runId).lastSeq;
2570
- }
2571
- eventsPath(runId) {
2572
- return historyPaths(this.sourceDataDir(runId), runId).plain;
2573
- }
2574
2043
  /** Same location `handoffPath()` in handoff.ts produces — inlined to keep
2575
2044
  * the store free of upward imports. */
2576
2045
  handoffPath(runId) {
@@ -2585,13 +2054,7 @@ export class RunStore {
2585
2054
  this.dirty.add(run.id);
2586
2055
  this.scheduleSave();
2587
2056
  publishRunWrite(this.published, run, before, undefined, exit);
2588
- this.maybeEnqueueHistoryCompress(run);
2589
- }
2590
- /** Form follows archived: a terminal archived run with a plain transcript is queued again. */
2591
- maybeEnqueueHistoryCompress(run) {
2592
- if (run.archived && !isLiveStatus(run.status) && hasPlainHistory(this.dataDir, run.id)) {
2593
- this.compressor.enqueue(run.id);
2594
- }
2057
+ this.archive.maybeEnqueueHistoryCompress(run);
2595
2058
  }
2596
2059
  /** The held record is gone; the next save or commit deletes its row, fenced by `family`'s claim
2597
2060
  * and by the revision this store last saw (kept in `base` until the delete is written). */
@@ -2822,7 +2285,7 @@ export class RunStore {
2822
2285
  this.liveItems.clear();
2823
2286
  // Demand-bound feeds stop before storage disappears during project removal/shutdown.
2824
2287
  this.published.publish('store.closed', {});
2825
- this.compressor.stop();
2288
+ this.archive.compressor.stop();
2826
2289
  this.transcriptFacts.stop();
2827
2290
  if (this.saveTimer) {
2828
2291
  clearTimeout(this.saveTimer);
@@ -2845,10 +2308,4 @@ export class RunStore {
2845
2308
  this.db = null;
2846
2309
  }
2847
2310
  }
2848
- function archiveDigest(value) {
2849
- return createHash('sha256').update(JSON.stringify(value)).digest('hex');
2850
- }
2851
- function archiveFields(run, archived, now) {
2852
- return stageArchiveFields(run, archived, now);
2853
- }
2854
2311
  //# sourceMappingURL=store.js.map