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

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 (160) hide show
  1. package/dist/activity/read-model.js +1 -1
  2. package/dist/activity/read-model.js.map +1 -1
  3. package/dist/activity/requests.d.ts +3 -1
  4. package/dist/activity/requests.js +1 -1
  5. package/dist/activity/requests.js.map +1 -1
  6. package/dist/activity/tool-activity.d.ts +3 -2
  7. package/dist/activity/tool-activity.js +1 -1
  8. package/dist/activity/tool-activity.js.map +1 -1
  9. package/dist/built-in-run-slots.d.ts +4 -3
  10. package/dist/built-in-run-slots.js +7 -3
  11. package/dist/built-in-run-slots.js.map +1 -1
  12. package/dist/delegation/conversation-send.js +1 -1
  13. package/dist/delegation/conversation-send.js.map +1 -1
  14. package/dist/delegation/conversations.js +4 -4
  15. package/dist/delegation/conversations.js.map +1 -1
  16. package/dist/delegation/execution-identity.d.ts +7 -2
  17. package/dist/delegation/execution-identity.js +34 -3
  18. package/dist/delegation/execution-identity.js.map +1 -1
  19. package/dist/delegation/family-end.d.ts +3 -1
  20. package/dist/delegation/park-notice.d.ts +3 -1
  21. package/dist/delegation/park-notice.js +2 -2
  22. package/dist/delegation/park-notice.js.map +1 -1
  23. package/dist/delegation/private-record-file.js.map +1 -0
  24. package/dist/delegation/provision.js +1 -1
  25. package/dist/delegation/provision.js.map +1 -1
  26. package/dist/delegation/results.js +3 -3
  27. package/dist/delegation/results.js.map +1 -1
  28. package/dist/delegation/scratch-cleanup.js +5 -5
  29. package/dist/delegation/scratch-cleanup.js.map +1 -1
  30. package/dist/delegation/service.js +10 -9
  31. package/dist/delegation/service.js.map +1 -1
  32. package/dist/delegation/worker-cleanup.js +13 -12
  33. package/dist/delegation/worker-cleanup.js.map +1 -1
  34. package/dist/{runs → delegation}/worker-deletion-proof.d.ts +1 -1
  35. package/dist/delegation/worker-deletion-proof.js.map +1 -0
  36. package/dist/delegation/worker-executions.d.ts +70 -0
  37. package/dist/delegation/worker-executions.js +248 -0
  38. package/dist/delegation/worker-executions.js.map +1 -0
  39. package/dist/{runs → delegation}/worker-resource-holders.d.ts +1 -1
  40. package/dist/delegation/worker-resource-holders.js.map +1 -0
  41. package/dist/preview/agent-marker.js +1 -1
  42. package/dist/preview/agent-marker.js.map +1 -1
  43. package/dist/preview/host.d.ts +5 -1
  44. package/dist/preview/host.js +2 -2
  45. package/dist/preview/host.js.map +1 -1
  46. package/dist/preview/run-tools.js +1 -1
  47. package/dist/preview/run-tools.js.map +1 -1
  48. package/dist/runs/event-log.d.ts +79 -0
  49. package/dist/runs/event-log.js +188 -0
  50. package/dist/runs/event-log.js.map +1 -0
  51. package/dist/runs/owned-run-create.d.ts +3 -3
  52. package/dist/runs/owned-run-create.js +1 -2
  53. package/dist/runs/owned-run-create.js.map +1 -1
  54. package/dist/runs/ports.d.ts +68 -22
  55. package/dist/runs/retention.d.ts +3 -1
  56. package/dist/runs/retention.js +3 -3
  57. package/dist/runs/retention.js.map +1 -1
  58. package/dist/runs/run-redaction.d.ts +19 -0
  59. package/dist/runs/run-redaction.js +36 -0
  60. package/dist/runs/run-redaction.js.map +1 -0
  61. package/dist/runs/run-retention.d.ts +1 -1
  62. package/dist/runs/store.d.ts +14 -117
  63. package/dist/runs/store.js +56 -462
  64. package/dist/runs/store.js.map +1 -1
  65. package/dist/runs/transcript-facts-fold.d.ts +1 -1
  66. package/dist/runs/transcript-facts-fold.js +1 -1
  67. package/dist/runs/transcript-facts-fold.js.map +1 -1
  68. package/dist/runs/webhook.d.ts +3 -1
  69. package/dist/runs/webhook.js +3 -3
  70. package/dist/runs/webhook.js.map +1 -1
  71. package/dist/runs/worker-executions-registry.d.ts +31 -0
  72. package/dist/runs/worker-executions-registry.js +20 -0
  73. package/dist/runs/worker-executions-registry.js.map +1 -0
  74. package/dist/server/project-context.d.ts +3 -1
  75. package/dist/server/project-context.js.map +1 -1
  76. package/dist/server/provider-auth-runtime.js +2 -2
  77. package/dist/server/provider-auth-runtime.js.map +1 -1
  78. package/dist/server/run-relationships.d.ts +3 -1
  79. package/dist/server/run-relationships.js +1 -1
  80. package/dist/server/run-relationships.js.map +1 -1
  81. package/dist/server/server.js +2 -2
  82. package/dist/server/server.js.map +1 -1
  83. package/dist/workflows/run/attachment-writer.js +1 -1
  84. package/dist/workflows/run/attachment-writer.js.map +1 -1
  85. package/dist/workflows/run/auto-resume.js +4 -4
  86. package/dist/workflows/run/auto-resume.js.map +1 -1
  87. package/dist/workflows/run/completion-gate.js +1 -1
  88. package/dist/workflows/run/completion-gate.js.map +1 -1
  89. package/dist/workflows/run/continuation-session.js +10 -10
  90. package/dist/workflows/run/continuation-session.js.map +1 -1
  91. package/dist/workflows/run/cut-off-work.d.ts +8 -6
  92. package/dist/workflows/run/cut-off-work.js +2 -2
  93. package/dist/workflows/run/cut-off-work.js.map +1 -1
  94. package/dist/workflows/run/family-reconciler.js +3 -3
  95. package/dist/workflows/run/family-reconciler.js.map +1 -1
  96. package/dist/workflows/run/human-waits.js +4 -4
  97. package/dist/workflows/run/human-waits.js.map +1 -1
  98. package/dist/workflows/run/input-delivery.js +11 -11
  99. package/dist/workflows/run/input-delivery.js.map +1 -1
  100. package/dist/workflows/run/input-receipts.js +3 -3
  101. package/dist/workflows/run/input-receipts.js.map +1 -1
  102. package/dist/workflows/run/launch-context.js +1 -1
  103. package/dist/workflows/run/launch-context.js.map +1 -1
  104. package/dist/workflows/run/launch-read-resolver.d.ts +3 -1
  105. package/dist/workflows/run/launch-read-resolver.js +7 -7
  106. package/dist/workflows/run/launch-read-resolver.js.map +1 -1
  107. package/dist/workflows/run/memory-guard.js +2 -2
  108. package/dist/workflows/run/memory-guard.js.map +1 -1
  109. package/dist/workflows/run/queued-revival.js +5 -5
  110. package/dist/workflows/run/queued-revival.js.map +1 -1
  111. package/dist/workflows/run/run-cancel.js +5 -5
  112. package/dist/workflows/run/run-cancel.js.map +1 -1
  113. package/dist/workflows/run/run-finish.js +5 -5
  114. package/dist/workflows/run/run-finish.js.map +1 -1
  115. package/dist/workflows/run/run-recovery.js +6 -6
  116. package/dist/workflows/run/run-recovery.js.map +1 -1
  117. package/dist/workflows/run/run-settlement.js +12 -12
  118. package/dist/workflows/run/run-settlement.js.map +1 -1
  119. package/dist/workflows/run/run-skills.js +1 -1
  120. package/dist/workflows/run/run-skills.js.map +1 -1
  121. package/dist/workflows/run/session-events.js +4 -4
  122. package/dist/workflows/run/session-events.js.map +1 -1
  123. package/dist/workflows/run/step-loop.js +3 -3
  124. package/dist/workflows/run/step-loop.js.map +1 -1
  125. package/dist/workflows/run/step-session.js +2 -2
  126. package/dist/workflows/run/step-session.js.map +1 -1
  127. package/dist/workflows/run/subagent-waits.js +2 -2
  128. package/dist/workflows/run/subagent-waits.js.map +1 -1
  129. package/dist/workflows/run/turn-bookkeeping.js +2 -2
  130. package/dist/workflows/run/turn-bookkeeping.js.map +1 -1
  131. package/dist/workflows/run/turn-nudges.js +6 -6
  132. package/dist/workflows/run/turn-nudges.js.map +1 -1
  133. package/dist/workflows/run/turn-settler.d.ts +3 -1
  134. package/dist/workflows/run/turn-settler.js +10 -10
  135. package/dist/workflows/run/turn-settler.js.map +1 -1
  136. package/dist/workflows/run/usage-accounting.js +1 -1
  137. package/dist/workflows/run/usage-accounting.js.map +1 -1
  138. package/dist/workflows/run/wake-admission.js +2 -2
  139. package/dist/workflows/run/wake-admission.js.map +1 -1
  140. package/dist/workflows/run/worker-executions.js +6 -6
  141. package/dist/workflows/run/worker-executions.js.map +1 -1
  142. package/dist/workflows/run/worker-orphans.js +10 -10
  143. package/dist/workflows/run/worker-orphans.js.map +1 -1
  144. package/dist/workflows/run/worker-questions.js +14 -14
  145. package/dist/workflows/run/worker-questions.js.map +1 -1
  146. package/dist/workflows/run/workflow-position.d.ts +3 -1
  147. package/dist/workflows/run/worktree-autosave.js +1 -1
  148. package/dist/workflows/run/worktree-autosave.js.map +1 -1
  149. package/dist/workflows/run.js +2 -2
  150. package/dist/workflows/run.js.map +1 -1
  151. package/package.json +4 -4
  152. package/scripts/benchmark-stuck-destroys.ts +2 -2
  153. package/scripts/benchmark-worker-lifecycle.ts +3 -2
  154. package/dist/runs/private-record-file.js.map +0 -1
  155. package/dist/runs/worker-deletion-proof.js.map +0 -1
  156. package/dist/runs/worker-resource-holders.js.map +0 -1
  157. /package/dist/{runs → delegation}/private-record-file.d.ts +0 -0
  158. /package/dist/{runs → delegation}/private-record-file.js +0 -0
  159. /package/dist/{runs → delegation}/worker-deletion-proof.js +0 -0
  160. /package/dist/{runs → delegation}/worker-resource-holders.js +0 -0
@@ -1,26 +1,17 @@
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, stageArchiveFields, stageStepUpdate, stepTotals, redactPatch, clearPin } from './record-write-rules.js';
7
6
  import { publishRunWrite, RunLifecycle, snapshotRun } from './lifecycle.js';
8
- import { workerDeletionProof } from './worker-deletion-proof.js';
9
- import { recordedHolders, workerResourceAuthorized } from './worker-resource-holders.js';
10
7
  import { listPeerTaskSummaries, parseStoredSummary } from './run-summary-page.js';
11
8
  export { parseStoredSummary } from './run-summary-page.js';
12
- import { defined } from '../core/defined.js';
13
- import { deletionRefusal } from './removal-slots.js';
14
- import { admissibleExecution, holderRefusal, SPAWN_NEXT, WorkerAdmissionRefusal, workerExecutionSchema } from './worker-execution.js';
15
- import { agentTmpDirMayExist, agentTmpDirOwnershipProven } from './agent-tmpdir.js';
9
+ import { workerExecutionsFactory } from './worker-executions-registry.js';
16
10
  import { randomUUID, createHash } from 'node:crypto';
17
11
  import { isDeepStrictEqual } from 'node:util';
18
- import { appendFileSync, closeSync, constants, fstatSync, fsyncSync, lstatSync, openSync, readSync, realpathSync, existsSync, mkdirSync, writeFileSync } from 'node:fs';
19
- import { join, resolve } from 'node:path';
12
+ import { existsSync, mkdirSync } from 'node:fs';
13
+ import { join } from 'node:path';
20
14
  import { z } from 'zod';
21
- import { scopeRecordSchema } from '../worker-scope/scope.js';
22
- import { WorkerScopes } from '../worker-scope/worker-scopes.js';
23
- import { readPrivateRecord, writePrivateRecord } from './private-record-file.js';
24
15
  import { delegationStateSchema, workerDestroyRetrySchema, } from '../contract/index.js';
25
16
  import { agentInputSchema, inboxClaimSchema } from '../contract/index.js';
26
17
  import { automationIdOf, stepStateSchema as contractStepStateSchema, toRunSummary, runRecordSchema as contractRunRecordSchema, runPullRequestSchema, mergedPullRequestSchema, } from '../contract/index.js';
@@ -35,17 +26,13 @@ import { HistoryCompressor } from './history-compressor.js';
35
26
  import { LiveItemSnapshots } from './live-item-snapshots.js';
36
27
  import { stampOf } from './transcript-facts.js';
37
28
  import { RunTranscriptFacts } from './transcript-facts-topic.js';
38
- import { hasPlainHistory, historyPaths, readHistoryText, readHistoryTextAsync, restoreHistory } from './history-file.js';
39
- import { workerExecutionIdentitySchema } from '../delegation/execution-identity.js';
40
- import { startToken } from '../core/process-stat.js';
41
- import { collectSecretValues, redactDeep } from '../core/secret-redaction.js';
29
+ import { hasPlainHistory, historyPaths, restoreHistory } from './history-file.js';
42
30
  // Pure, dependency-free reference helpers — the same sanity bound the marker parser applies.
43
31
  import { archivePullRequests, pullRequestKey } from './pull-requests.js';
44
- import { isRepoScopedRef, promptNamesRepo } from './task-refs.js';
45
32
  // Type-only module (zod + nothing else), so this cannot cycle back into the store.
46
33
  import { workflowDefSchema } from '../workflows/types.js';
47
34
  import { applyOutcomes } from './outcome-commit.js';
48
- import { ISSUE_URL_RE, namesForeignReference, originatingIssue, refUrlNumber, referencedPrDeclaration, rescopeRun, resolveIssueReference, resolveReferencedRef, restoreOriginatingIssue, scanEventReferences, trackReferencedIssues, trackReferencedPrs } from './run-references.js';
35
+ import { ISSUE_URL_RE, namesForeignReference, referencedPrDeclaration, rescopeRun, resolveReferencedRef, restoreOriginatingIssue, trackReferencedIssues, trackReferencedPrs } from './run-references.js';
49
36
  import { applyExit, doneCommits, exitDurability, RUN_EXITS } from './run-exits.js';
50
37
  import { assertConversationIdFree } from './conversation-identity.js';
51
38
  export { ConversationIdInUseError } from './conversation-identity.js';
@@ -68,6 +55,8 @@ import { archiveStoreFamily } from './archive-family.js';
68
55
  import { claimStoreFamilies } from './claim-families.js';
69
56
  import { createStoreOwnedRun } from './owned-run-create.js';
70
57
  import { WorkerResultsTopic } from './worker-results.js';
58
+ import { RunEventLogTopic } from './event-log.js';
59
+ import { RunRedaction } from './run-redaction.js';
71
60
  import { claimOwnerLive, closeClaimSession, familyKey, foreignClaimedRunIds, liveForeignClaimedRunIds, openClaimSession, rowFamily } from './run-claims.js';
72
61
  import { assertProjectWritable, projectWriteRefused } from '../server/cockpit-ownership.js';
73
62
  /**
@@ -354,21 +343,6 @@ function isDestroyProgress(before, after) {
354
343
  return false;
355
344
  return isDeepStrictEqual({ ...before, destroy: undefined }, { ...after, destroy: undefined });
356
345
  }
357
- /** NDJSON transcript text to events; a damaged line is skipped, never fatal. */
358
- function parseEvents(raw) {
359
- return raw
360
- .split('\n')
361
- .filter(Boolean)
362
- .map((line) => {
363
- try {
364
- return JSON.parse(line);
365
- }
366
- catch {
367
- return null;
368
- }
369
- })
370
- .filter((e) => e !== null);
371
- }
372
346
  /** An archived page's cursor: the last row's order, opaque to clients. A held run with no row yet
373
347
  * lists after every row (`seq` is infinite), which JSON cannot carry, so it travels as null. */
374
348
  function encodeArchivedCursor(key) {
@@ -401,11 +375,6 @@ function deepFreeze(value) {
401
375
  }
402
376
  return value;
403
377
  }
404
- const WORKER_PROCESS_CAP = 32;
405
- const recordedProcessSchema = z.object({ pid: z.number().int().positive(), startToken: z.string().min(1).max(128).optional(),
406
- pgid: z.number().int().positive().optional() }).strict();
407
- const workerProcessRecordSchema = z.object({ generation: z.string().uuid(), controller: recordedProcessSchema,
408
- processes: z.array(recordedProcessSchema).max(WORKER_PROCESS_CAP) }).strict();
409
378
  /**
410
379
  * Run rows in runs.db plus append-only NDJSON events and an in-process event bus. Hold live,
411
380
  * pinned, related and unsettled records only. Optimistic writes debounce; durable commits
@@ -434,9 +403,7 @@ export class RunStore {
434
403
  published = new RunLifecycle();
435
404
  lifecycle = this.published;
436
405
  /** The lifecycle events run exits write (B12). */
437
- exitEvents = new ExitEvents((id, event) => this.appendEvent(id, event));
438
- /** Every worker's process scope (ADR 0032): spawn sites, Continue and destroy reach it here. */
439
- scopes = new WorkerScopes(this);
406
+ exitEvents = new ExitEvents((id, event) => this.eventLog.appendEvent(id, event));
440
407
  /** Runs gone from memory whose rows the next save or commit deletes. */
441
408
  deleted = new Set();
442
409
  /** Deleted runs whose history files (events, handoff, images, artifacts) go once the delete of
@@ -480,6 +447,20 @@ export class RunStore {
480
447
  retention;
481
448
  /** The saved snapshot of a worker's collected result (hearsay-tools/squawk#4038). */
482
449
  workerResults;
450
+ /** The event log and reference markers (hearsay-tools/squawk#4040). */
451
+ eventLog;
452
+ /** The scrub of events and free text (hearsay-tools/squawk#4040). */
453
+ redaction;
454
+ executions;
455
+ /** A worker's execution, process, identity and scope records (hearsay-tools/squawk#4039), built on
456
+ * first use by the factory this process registered; throws when none is registered. */
457
+ get workerExecutions() {
458
+ 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),
461
+ published: this.published, workerResults: this.workerResults,
462
+ });
463
+ }
483
464
  liveItems = new LiveItemSnapshots();
484
465
  /** Capture both sources on the same synchronous sequence boundary before history IO. */
485
466
  liveReadSnapshot(runId) {
@@ -487,6 +468,7 @@ export class RunStore {
487
468
  }
488
469
  constructor(dataDir) {
489
470
  this.dataDir = dataDir;
471
+ this.redaction = new RunRedaction();
490
472
  this.transcriptFacts = new RunTranscriptFacts(dataDir, {
491
473
  isFallbackRun: (id) => this.isFallbackRun(id),
492
474
  sourceDataDir: (id) => this.sourceDataDir(id),
@@ -499,8 +481,14 @@ export class RunStore {
499
481
  this.workerResults = new WorkerResultsTopic(dataDir, {
500
482
  peek: (id) => this.peek(id), hasRun: (id) => this.hasRun(id), hasFallbackRun: (id) => this.hasFallbackRun(id),
501
483
  writeDir: (id) => this.writeDir(id), sourceDataDir: (id) => this.sourceDataDir(id),
502
- redactResult: (result) => this.redact({ type: 'worker-result', seq: 0, ts: result.observedAt, result }).result,
503
- redactText: (text) => this.redactText(text), commitDelegation: (patches) => this.commitDelegation(patches),
484
+ redactResult: (result) => this.redaction.redact({ type: 'worker-result', seq: 0, ts: result.observedAt, result }).result,
485
+ redactText: (text) => this.redaction.redactText(text), commitDelegation: (patches) => this.commitDelegation(patches),
486
+ });
487
+ this.eventLog = new RunEventLogTopic(dataDir, {
488
+ 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),
490
+ touch: (run, before) => this.touch(run, before), change: (id, apply) => this.change(id, apply), repoHandle: () => this.repoHandle,
491
+ maybeEnqueueHistoryCompress: (run) => this.maybeEnqueueHistoryCompress(run),
504
492
  });
505
493
  this.retention = new RunRetentionTopic(dataDir, {
506
494
  db: () => this.db, held: this.held, deleted: this.deleted, quarantined: this.quarantined,
@@ -511,11 +499,11 @@ export class RunStore {
511
499
  claimFamilies: (families) => this.claimFamilies(families), markDeleted: (id, family) => this.markDeleted(id, family),
512
500
  scheduleSave: () => this.scheduleSave(), commitIndex: (input) => this.commitIndex(input),
513
501
  commitDelegation: (patches) => this.commitDelegation(patches), applyArchived: (run, archived) => this.applyArchived(run, archived),
514
- workerDeletionEvidence: (id) => this.workerDeletionEvidence(id),
502
+ workerDeletionEvidence: (id) => this.workerExecutions.workerDeletionEvidence(id),
515
503
  workerResults: this.workerResults,
516
- readWorkerExecution: (id) => this.readWorkerExecution(id), identityPath: (id) => this.identityPath(id),
517
- processesPath: (id) => this.processesPath(id), scopePath: (id) => this.scopePath(id),
518
- executionPath: (id) => this.executionPath(id), handoffPath: (runId) => this.handoffPath(runId),
504
+ readWorkerExecution: (id) => this.workerExecutions.readWorkerExecution(id), identityPath: (id) => this.workerExecutions.identityPath(id),
505
+ processesPath: (id) => this.workerExecutions.processesPath(id), scopePath: (id) => this.workerExecutions.scopePath(id),
506
+ executionPath: (id) => this.workerExecutions.executionPath(id), handoffPath: (runId) => this.handoffPath(runId),
519
507
  imagesDir: (runId) => this.imagesDir(runId),
520
508
  });
521
509
  this.compressor = new HistoryCompressor(dataDir, (id) => this.isHistoryCompressEligible(id), (id, plain, archive) => this.transcriptFacts.index.adoptArchive(id, plain, stampOf(archive)));
@@ -809,6 +797,15 @@ export class RunStore {
809
797
  }
810
798
  fallbackRefusal(id) { return new RunWriteRefusedError(id, 'fallback', fallbackRunDeleteError(this.dataDir, true)); }
811
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
+ }
812
809
  writeDir(id) { if (this.runOwnership(id) === 'fallback')
813
810
  throw this.fallbackRefusal(id); return runDataDir(this.dataDir, id); }
814
811
  /** Every run whose family another process owns (`foreignClaimedRunIds`). */
@@ -1495,7 +1492,7 @@ export class RunStore {
1495
1492
  // scrubbed: it is the user's own prompt and is replayed into `{{task}}`
1496
1493
  // when a queued run is revived after a restart (#367), so redacting it
1497
1494
  // would corrupt the revived run.
1498
- title: this.redactText(input.title),
1495
+ title: this.redaction.redactText(input.title),
1499
1496
  workflow: input.workflow,
1500
1497
  task: input.task,
1501
1498
  model: input.model,
@@ -1539,9 +1536,9 @@ export class RunStore {
1539
1536
  const root = this.peek(rootId);
1540
1537
  if (root?.delegation?.role !== 'root')
1541
1538
  throw new Error('missing conversation root');
1542
- assertConversationIdFree(root, message ?? delivery?.input, id => this.peek(id), (runId, id) => this.hasProjection(runId, id));
1539
+ assertConversationIdFree(root, message ?? delivery?.input, id => this.peek(id), (runId, id) => this.eventLog.hasProjection(runId, id));
1543
1540
  const staged = new Map();
1544
- stageConversation(staged, root, conversation, delivery, id => this.peek(id), text => this.redactText(text));
1541
+ stageConversation(staged, root, conversation, delivery, id => this.peek(id), text => this.redaction.redactText(text));
1545
1542
  this.commitIndex(staged);
1546
1543
  }
1547
1544
  /** Crash recovery (#505): input a harness accepted but was never seen reading goes
@@ -1809,7 +1806,7 @@ export class RunStore {
1809
1806
  const root = this.peek(conversation.rootId);
1810
1807
  if (root?.delegation?.role !== 'root' || run.delegation.parentRunId !== root.id)
1811
1808
  throw new Error('missing conversation ownership');
1812
- stageConversation(staged, root, conversation.state, { recipientRunId: id, input: conversation.input }, runId => this.peek(runId), text => this.redactText(text));
1809
+ stageConversation(staged, root, conversation.state, { recipientRunId: id, input: conversation.input }, runId => this.peek(runId), text => this.redaction.redactText(text));
1813
1810
  }
1814
1811
  this.commitIndex(staged, undefined, { exits: new Map([[id, exit]]) });
1815
1812
  }
@@ -1820,8 +1817,8 @@ export class RunStore {
1820
1817
  hasRun: (id) => this.hasRun(id),
1821
1818
  held: this.held, deleted: this.deleted, db: this.db,
1822
1819
  buildRun: (ownedInput, id) => this.buildRun(ownedInput, id),
1823
- writeWorkerIdentity: (id, identity) => this.writeWorkerIdentity(id, identity),
1824
- writeWorkerExecution: (id, proof, fresh) => this.writeWorkerExecution(id, proof, fresh),
1820
+ writeWorkerIdentity: (id, identity) => this.workerExecutions.writeWorkerIdentity(id, identity),
1821
+ writeWorkerExecution: (id, proof, fresh) => this.workerExecutions.writeWorkerExecution(id, proof, fresh),
1825
1822
  commitIndex: (owned) => this.commitIndex(owned),
1826
1823
  }, input, parentId, requestId, worker, requestHash, spawnCapacityRefusal, executionIdentity);
1827
1824
  }
@@ -1882,7 +1879,7 @@ export class RunStore {
1882
1879
  if (!facts || !['done', 'review', 'failed', 'cancelled'].includes(run.status) || run.waits?.some(wait => wait.phase === 'open') ||
1883
1880
  run.hasPendingPermission || facts.pendingAsk !== undefined)
1884
1881
  return 'Task or worker work still needs attention. Open the task or archive manually.';
1885
- if (run.delegation?.role === 'invalid' || (run.delegation?.role === 'worker' && this.readWorkerExecution(run.id)?.phase !== 'complete'))
1882
+ if (run.delegation?.role === 'invalid' || (run.delegation?.role === 'worker' && this.workerExecutions.readWorkerExecution(run.id)?.phase !== 'complete'))
1886
1883
  return 'Worker execution has not settled. Open the worker or archive manually.';
1887
1884
  }
1888
1885
  return undefined;
@@ -2032,7 +2029,7 @@ export class RunStore {
2032
2029
  writeRun(id, run, patch, durability, exit) {
2033
2030
  const before = snapshotRun(run);
2034
2031
  const hooks = {
2035
- redact: (text) => this.redactText(text),
2032
+ redact: (text) => this.redaction.redactText(text),
2036
2033
  repoHandle: this.repoHandle,
2037
2034
  restore: () => restoreHistory(this.dataDir, id),
2038
2035
  archive: (record, archived) => this.applyArchived(record, archived, before, exit),
@@ -2047,7 +2044,7 @@ export class RunStore {
2047
2044
  return run;
2048
2045
  }
2049
2046
  redactPatch(patch) {
2050
- return redactPatch(patch, text => this.redactText(text));
2047
+ return redactPatch(patch, text => this.redaction.redactText(text));
2051
2048
  }
2052
2049
  /** Append a step to an existing run (used by "Continue" — spec 003). */
2053
2050
  addStep(runId, step) {
@@ -2063,7 +2060,7 @@ export class RunStore {
2063
2060
  const step = run?.steps.find((s) => s.id === stepId);
2064
2061
  if (!run || !step)
2065
2062
  return;
2066
- const before = snapshotRun(run), next = { ...step, ...stageStepUpdate(patch, text => this.redactText(text)) };
2063
+ const before = snapshotRun(run), next = { ...step, ...stageStepUpdate(patch, text => this.redaction.redactText(text)) };
2067
2064
  // Replaced, never changed in place, so `before` keeps the steps as they were.
2068
2065
  run.steps = run.steps.map((candidate) => candidate === step ? next : candidate);
2069
2066
  Object.assign(run, stepTotals(run.steps));
@@ -2086,7 +2083,7 @@ export class RunStore {
2086
2083
  decodeCold: (row) => this.decodeCold(row),
2087
2084
  writeRefusal: (memberId) => this.writeRefusal(memberId),
2088
2085
  factsPeek: (memberId) => this.transcriptFacts.factsFor(memberId).peek(memberId),
2089
- readWorkerExecution: (memberId) => this.readWorkerExecution(memberId),
2086
+ readWorkerExecution: (memberId) => this.workerExecutions.readWorkerExecution(memberId),
2090
2087
  }, id, isActive);
2091
2088
  }
2092
2089
  /** Blockers are feedback, never archive authority or cleanup permission. */
@@ -2373,150 +2370,6 @@ export class RunStore {
2373
2370
  }
2374
2371
  return count;
2375
2372
  }
2376
- appendEvent(runId, event) {
2377
- const run = this.record(runId);
2378
- if (!run) {
2379
- const ownership = this.runOwnership(runId);
2380
- if (ownership === 'fallback')
2381
- throw this.fallbackRefusal(runId);
2382
- if (ownership === 'foreign' || ownership === 'orphaned' || ownership === 'quarantined')
2383
- throw new RunWriteRefusedError(runId, ownership);
2384
- throw new Error(`unknown run: ${runId}`);
2385
- }
2386
- const seq = this.nextSeq(runId);
2387
- // Scrub credentials before the event touches disk or the live wire (#427):
2388
- // tool-result output is persisted verbatim and served back over the API, so
2389
- // a secret in an agent's command output would otherwise land in `.ai/cezar/`.
2390
- const full = this.redact(defined({ ...event, seq, ts: new Date().toISOString() }));
2391
- // Sync append keeps event order without a write queue; local NDJSON
2392
- // appends at agent-event rates are effectively free.
2393
- if (!hasPlainHistory(this.dataDir, runId))
2394
- restoreHistory(this.dataDir, runId);
2395
- const line = `${JSON.stringify(full)}\n`;
2396
- appendFileSync(this.eventsPath(runId), line, 'utf8');
2397
- this.transcriptFacts.index.append(runId, full, Buffer.byteLength(line));
2398
- this.maybeEnqueueHistoryCompress(run);
2399
- this.liveItems.observe(runId, full, false);
2400
- this.published.publish('run.event', { runId, event: full });
2401
- // Reference discovery runs last, after the event is persisted, indexed and
2402
- // published: the janitor reads the event text and may still update the run.
2403
- const before = snapshotRun(run);
2404
- scanEventReferences(run, full, this.repoHandle, (target, entries) => this.accumulatePullRequests(target, entries), (target) => this.touch(target, before));
2405
- return full;
2406
- }
2407
- /**
2408
- * Apply agent-declared reference markers (spec 2026-07-18-task-ref-markers).
2409
- * Marker values are authoritative for the display tier: they overwrite the
2410
- * regex/namer numbers unless the prompt identifies the originating issue, and a declared PR re-resolves the referenced URL
2411
- * against the candidate working set — including down to `undefined` when no
2412
- * candidate matches (a wrong chip is worse than no chip). The created tier
2413
- * (`pullRequestUrl`) is deliberately untouched.
2414
- *
2415
- * One declaration is NOT a statement about the referenced tier: the number of the PR this run
2416
- * itself created. See `referencedPrDeclaration` — the marker contract asks the agent to
2417
- * re-declare after it opens a PR, and taking that literally cost the task the PR it was about.
2418
- */
2419
- applyMarkerRefs(runId, refs) {
2420
- if (refs.pr === undefined && refs.issue === undefined)
2421
- return this.record(runId);
2422
- return this.change(runId, (run) => {
2423
- const numbers = [...new Set([...(run.markerRefs?.pr === undefined ? [] : [run.markerRefs.pr]),
2424
- ...(refs.prs ?? (refs.pr === undefined ? [] : [refs.pr]))])];
2425
- if (numbers.length)
2426
- this.accumulatePullRequests(run, numbers.flatMap((number) => {
2427
- const matches = (run.referencedPrCandidates ?? []).filter((url) => refUrlNumber(url) === number &&
2428
- (this.repoHandle ? isRepoScopedRef(url, run.task, this.repoHandle) : promptNamesRepo(url, run.task)));
2429
- const url = matches.length === 1 ? matches[0] : matches.length === 0 && this.repoHandle
2430
- ? `https://github.com/${this.repoHandle.owner}/${this.repoHandle.name}/pull/${number}` : undefined;
2431
- const parsed = runPullRequestSchema.safeParse({ number, ...(url ? { url } : {}), source: 'declared' });
2432
- return parsed.success ? [parsed.data] : [];
2433
- }));
2434
- run.markerRefs = {
2435
- ...run.markerRefs,
2436
- ...(refs.pr !== undefined ? { pr: refs.pr } : {}),
2437
- ...(refs.issue !== undefined ? { issue: refs.issue } : {}),
2438
- };
2439
- // `prNumber` is the about-PR as well (it is what paints a numeric-only chip), so a
2440
- // re-declaration naming the created PR only FILLS it — it never overwrites the number the
2441
- // task came in with, which is still the PR this task is about.
2442
- if (refs.pr !== undefined && (run.prNumber === undefined || refs.pr !== refUrlNumber(run.pullRequestUrl))) {
2443
- run.prNumber = refs.pr;
2444
- }
2445
- if (refs.issue !== undefined) {
2446
- run.issueNumber = originatingIssue(run) ?? refs.issue;
2447
- delete run.referencedIssueNumberSeeded;
2448
- }
2449
- if (run.markerRefs.pr !== undefined) {
2450
- run.referencedPullRequestUrl = resolveReferencedRef(run.referencedPrCandidates ?? [], run.task, referencedPrDeclaration(run), this.repoHandle);
2451
- }
2452
- if (run.markerRefs.issue !== undefined) {
2453
- run.referencedIssueUrl = resolveIssueReference(run, this.repoHandle);
2454
- }
2455
- });
2456
- }
2457
- /** Authoritative creation keeps the first scalar for publishing, plus every created identity. */
2458
- recordCreatedPr(runId, url) {
2459
- const run = this.record(runId);
2460
- const parsed = runPullRequestSchema.safeParse({ number: refUrlNumber(url), url, source: 'created' });
2461
- if (!run || !parsed.success)
2462
- return run;
2463
- const before = snapshotRun(run);
2464
- let changed = this.accumulatePullRequests(run, [parsed.data]);
2465
- if (!run.pullRequestUrl) {
2466
- run.pullRequestUrl = url;
2467
- changed = true;
2468
- }
2469
- if (changed)
2470
- this.touch(run, before);
2471
- return run;
2472
- }
2473
- accumulatePullRequests(run, entries) {
2474
- return stagePullRequests(run, entries, this.repoHandle);
2475
- }
2476
- /**
2477
- * Fan an event out to live subscribers WITHOUT writing it to the NDJSON
2478
- * file — the channel for coalesced `item.delta` flushes (protocol-v2
2479
- * performance guardrail: raw deltas never hit disk; replay = the persisted
2480
- * snapshots). Stamped with `seq`/`ts` like persisted lines so the live
2481
- * wire keeps one ordering axis. Finite polling coalesces active item content
2482
- * into bounded in-memory snapshots on that clock; disk replay still has gaps
2483
- * (dedup compares with `>`).
2484
- */
2485
- emitEphemeral(runId, event) {
2486
- const full = this.redact({ ...event, seq: this.nextSeq(runId), ts: new Date().toISOString() });
2487
- this.liveItems.observe(runId, full, true);
2488
- this.published.publish('run.event', { runId, event: full });
2489
- return full;
2490
- }
2491
- /** Lazily-collected concrete secret values from the host env (#427). */
2492
- secretValues = null;
2493
- /** Controller-issued tokens never persist, including when host-secret redaction is disabled. */
2494
- sessionSecrets = new Set();
2495
- registerSessionSecret(value) { this.sessionSecrets.add(value); }
2496
- containsSessionSecret(value) { return [...this.sessionSecrets].some(secret => value.includes(secret)); }
2497
- /**
2498
- * Scrub known credential values / token shapes from an event before it is
2499
- * persisted or fanned out. On by default; `CEZ_REDACT_SECRETS=0` opts out.
2500
- */
2501
- redact(event) {
2502
- const safe = this.sessionSecrets.size ? redactDeep(event, [...this.sessionSecrets]) : event;
2503
- if (productEnv('REDACT_SECRETS') === '0')
2504
- return safe;
2505
- return redactDeep(safe, this.hostSecrets());
2506
- }
2507
- /** Best-effort scrub of one free-text string bound for `runs.json`. Honors
2508
- * the `CEZ_REDACT_SECRETS=0` opt-out itself so every caller inherits it. */
2509
- redactText(text) {
2510
- return redactText(text, [...this.sessionSecrets], () => this.hostSecrets());
2511
- }
2512
- hostSecrets() {
2513
- if (this.secretValues === null)
2514
- this.secretValues = collectSecretValues();
2515
- return this.secretValues;
2516
- }
2517
- hasProjection(runId, projectionId) {
2518
- return this.transcriptFacts.transcriptFacts(runId).projectionIds.includes(projectionId);
2519
- }
2520
2373
  /** Indexed family enumeration, including members not yet flushed to SQLite. */
2521
2374
  listFamilyRunIds(rootId) {
2522
2375
  const ids = new Set([rootId, ...(this.db?.listIdsByParent(rootId) ?? [])]);
@@ -2530,249 +2383,6 @@ export class RunStore {
2530
2383
  ids.delete(id);
2531
2384
  return [...ids];
2532
2385
  }
2533
- /** `readEvents` off the event loop (async read and async brotli), for collection paths. */
2534
- async readEventsAsync(runId) {
2535
- try {
2536
- const raw = await readHistoryTextAsync(this.sourceDataDir(runId), runId);
2537
- return raw === undefined ? [] : parseEvents(raw);
2538
- }
2539
- catch {
2540
- return [];
2541
- }
2542
- }
2543
- readEvents(runId) {
2544
- try {
2545
- const raw = readHistoryText(this.sourceDataDir(runId), runId);
2546
- if (raw === undefined)
2547
- return [];
2548
- return parseEvents(raw);
2549
- }
2550
- catch {
2551
- return [];
2552
- }
2553
- }
2554
- /** Private process-generation evidence; never part of run JSON or SSE. */
2555
- identityPath(id, write = false) {
2556
- return this.executionPath(id, write).replace(/\.execution\.json$/, '.identity.json');
2557
- }
2558
- readWorkerIdentity(id) {
2559
- try {
2560
- const fd = openSync(this.identityPath(id), constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
2561
- try {
2562
- const info = fstatSync(fd);
2563
- if (!info.isFile() || info.size > 16384 || (info.mode & 0o077))
2564
- return undefined;
2565
- const buffer = Buffer.alloc(16385);
2566
- const count = readSync(fd, buffer, 0, buffer.length, 0);
2567
- return workerExecutionIdentitySchema.parse(JSON.parse(buffer.subarray(0, count).toString('utf8')));
2568
- }
2569
- finally {
2570
- closeSync(fd);
2571
- }
2572
- }
2573
- catch {
2574
- return undefined;
2575
- }
2576
- }
2577
- writeWorkerIdentity(id, identity) {
2578
- // Immutable acceptance evidence. An orphan from failed index publication cannot be adopted.
2579
- const fd = openSync(this.identityPath(id, true), constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600);
2580
- try {
2581
- writeFileSync(fd, JSON.stringify(identity));
2582
- fsyncSync(fd);
2583
- }
2584
- finally {
2585
- closeSync(fd);
2586
- }
2587
- }
2588
- executionPath(id, write = false) {
2589
- z.string().uuid().parse(id);
2590
- const dir = join(write ? this.writeDir(id) : this.sourceDataDir(id), 'runs');
2591
- if (write)
2592
- mkdirSync(dir, { recursive: true });
2593
- if (lstatSync(dir).isSymbolicLink() || realpathSync(dir) !== resolve(dir))
2594
- throw new Error('Unsafe execution directory');
2595
- return join(dir, `${id}.execution.json`);
2596
- }
2597
- readWorkerExecution(id) {
2598
- try {
2599
- const proof = readPrivateRecord(this.executionPath(id), 16384, value => workerExecutionSchema.parse(value));
2600
- return typeof proof === 'string' ? undefined : proof;
2601
- }
2602
- catch {
2603
- return undefined;
2604
- }
2605
- }
2606
- writeWorkerExecution(id, proof, fresh = false) {
2607
- writePrivateRecord(this.executionPath(id, true), proof, { fresh });
2608
- }
2609
- /** Complete execution is not permission to reuse/delete persistent resources (#738).
2610
- * Synchronous, fresh and generation/resource fenced; callers hold admission off across awaits. */
2611
- workerResourcesSafe(id, generation, resourceId) {
2612
- // Reclaim and history deletion also need an empty scope; admission does not (ADR 0032).
2613
- return this.workerResourceHolders(id, generation, resourceId) === 'safe' && this.scopes.empty(id);
2614
- }
2615
- /** `workerResourcesSafe` with the refusal's live PIDs (empty when no PID explains it). */
2616
- workerResourceHolders(id, generation, resourceId, opts = {}) {
2617
- if (deletionRefusal(id, 'worktree', this.dataDir))
2618
- return [];
2619
- const run = this.peek(id);
2620
- const proof = this.readWorkerExecution(id);
2621
- if (!workerResourceAuthorized(run, proof, id, generation, resourceId, opts.admittingQueued))
2622
- return [];
2623
- const record = this.readWorkerProcesses(id, generation);
2624
- if (record === 'unknown' || !agentTmpDirOwnershipProven(this.dataDir, id))
2625
- return [];
2626
- // Only the generation's recorded processes count; an outside process blocks nothing (ADR 0032).
2627
- return recordedHolders(record);
2628
- }
2629
- /** Upgrade a legacy completed checkpoint while terminal task ownership is still known.
2630
- * No holder scan here: settlement and scheduling must never wait on cleanup proof. */
2631
- retainWorkerScratchCleanup(id) {
2632
- const run = this.peek(id), proof = this.readWorkerExecution(id);
2633
- if (run?.delegation?.role !== 'worker' || ['queued', 'running', 'waiting'].includes(run.status) || proof?.phase !== 'complete')
2634
- return;
2635
- const { resourceId, path } = run.delegation.workspace;
2636
- if (proof.scratchCleanup?.resourceId === resourceId && proof.scratchCleanup.path === path)
2637
- return;
2638
- this.writeWorkerExecution(id, { ...proof, scratchCleanup: { resourceId, path } });
2639
- }
2640
- /** Cleanup can outlive its index row, but never its generation or terminal task intent. */
2641
- workerScratchResourcesSafe(id, generation, resourceId) {
2642
- if (deletionRefusal(id, 'worktree', this.dataDir))
2643
- return false;
2644
- const run = this.peek(id), proof = this.readWorkerExecution(id);
2645
- if (proof?.phase !== 'complete' || proof.generation !== generation || proof.scratchCleanup?.resourceId !== resourceId ||
2646
- (run && ['queued', 'running', 'waiting'].includes(run.status)))
2647
- return false;
2648
- // A process still in the worker's scope may use its scratch; one outside it is not the worker's.
2649
- if (run?.delegation?.role === 'worker')
2650
- return run.delegation.workspace.path === proof.scratchCleanup.path &&
2651
- this.workerResourceHolders(id, generation, resourceId) === 'safe' && this.scopes.empty(id);
2652
- // A valid different role contradicts the retained intent. Quarantined/missing metadata
2653
- // supplies no new authority; only the private terminal checkpoint authorizes scratch.
2654
- if (run && run.delegation?.role !== 'invalid')
2655
- return false;
2656
- const record = this.readWorkerProcesses(id, generation);
2657
- if (record === 'unknown' || !agentTmpDirOwnershipProven(this.dataDir, id))
2658
- return false;
2659
- return recordedHolders(record) === 'safe' && this.scopes.empty(id);
2660
- }
2661
- commitWorkerExecutionStart(id) {
2662
- const run = this.peek(id);
2663
- if (run?.delegation?.role !== 'worker' || run.delegation.destroy)
2664
- throw new WorkerAdmissionRefusal('the worker is being destroyed', SPAWN_NEXT);
2665
- const prior = admissibleExecution(this.readWorkerExecution(id));
2666
- const holders = this.workerResourceHolders(id, prior.generation, run.delegation.workspace.resourceId, { admittingQueued: true });
2667
- if (holders !== 'safe')
2668
- throw holderRefusal(holders, this.readWorkerProcesses(id, prior.generation));
2669
- const generation = randomUUID();
2670
- // #469: the controller is durable before `starting`, so a crash leaves a provable generation.
2671
- this.writeWorkerProcesses(id, { generation, controller: { pid: process.pid, ...startToken(process.pid) }, processes: [] });
2672
- this.writeWorkerExecution(id, { generation, phase: 'starting' });
2673
- return generation;
2674
- }
2675
- /** Private process record (#469): which processes a generation spawned, never part of run JSON or SSE. */
2676
- processesPath(id, write = false) {
2677
- return this.executionPath(id, write).replace(/\.execution\.json$/, '.processes.json');
2678
- }
2679
- /** Tri-state: only ENOENT is `absent` (legacy, scan-only). A present record that is unreadable,
2680
- * wrongly permissioned, malformed or of another generation is `unknown`: never finalized or reaped. */
2681
- readWorkerProcesses(id, generation) {
2682
- const record = readPrivateRecord(() => this.processesPath(id), 8192, value => workerProcessRecordSchema.parse(value));
2683
- return typeof record === 'string' || record.generation === generation ? record : 'unknown';
2684
- }
2685
- writeWorkerProcesses(id, record) {
2686
- writePrivateRecord(this.processesPath(id, true), workerProcessRecordSchema.parse(record));
2687
- }
2688
- /** Private scope record: the cgroups and process groups the worker owns (ADR 0032). */
2689
- scopePath(id, write = false) {
2690
- return this.executionPath(id, write).replace(/\.execution\.json$/, '.scope.json');
2691
- }
2692
- /** Tri-state like the process record: only ENOENT is `absent`. */
2693
- readWorkerScope(id) {
2694
- const record = readPrivateRecord(() => this.scopePath(id), 65_536, value => scopeRecordSchema.parse(value));
2695
- return typeof record === 'string' || record.workerId === id ? record : 'unknown';
2696
- }
2697
- /** Durable before the caller acts on it. */
2698
- writeWorkerScope(id, record) {
2699
- writePrivateRecord(this.scopePath(id, true), scopeRecordSchema.parse(record));
2700
- }
2701
- /** The scope a run's processes start in: a worker's own, none for any other run (ADR 0032). */
2702
- spawnScope(id) {
2703
- return this.peek(id)?.delegation?.role === 'worker' ? this.scopes.spawnScope(id) : undefined;
2704
- }
2705
- /** Bound to the current generation. Past the cap the record never drops an entry: the
2706
- * working-directory scan is the remaining evidence. */
2707
- appendWorkerProcess(id, generation, pid, pgid) {
2708
- const record = this.readWorkerProcesses(id, generation);
2709
- if (typeof record === 'string' || this.readWorkerExecution(id)?.generation !== generation)
2710
- return false;
2711
- const entry = { pid, ...startToken(pid), ...(pgid === undefined ? {} : { pgid }) };
2712
- if (record.processes.some(known => known.pid === entry.pid && known.startToken === entry.startToken))
2713
- return true;
2714
- if (record.processes.length >= WORKER_PROCESS_CAP)
2715
- return false;
2716
- this.writeWorkerProcesses(id, { ...record, processes: [...record.processes, entry] });
2717
- return true;
2718
- }
2719
- commitWorkerExecutionComplete(id, generation, opts = {}) {
2720
- const proof = this.readWorkerExecution(id);
2721
- if (!proof || proof.generation !== generation)
2722
- return false;
2723
- if (proof.phase === 'queued' && this.peek(id)?.status !== 'cancelled')
2724
- return false;
2725
- try {
2726
- const run = this.peek(id);
2727
- if (run?.delegation?.role !== 'worker')
2728
- return false;
2729
- this.commitIndex(new Map([[id, run]]));
2730
- if (this.readWorkerExecution(id)?.generation !== generation)
2731
- return false;
2732
- this.writeWorkerExecution(id, { generation, phase: 'complete',
2733
- // Nothing abandons an execution any more (hearsay-tools/cezarion#889); keep a checkpoint that already was.
2734
- ...(proof.abandoned ? { abandoned: true } : {}),
2735
- ...(proof.interrupted || (opts.interrupted && proof.phase === 'starting') ? { interrupted: true } : {}),
2736
- ...(proof.phase === 'queued' || proof.neverMaterialized ? { neverMaterialized: true } : {}),
2737
- ...(!['queued', 'running', 'waiting'].includes(run.status) ? { scratchCleanup: {
2738
- resourceId: run.delegation.workspace.resourceId, path: run.delegation.workspace.path
2739
- } } : {}) });
2740
- // The earlier index event cannot attest exit: subscribers must observe the
2741
- // durable private proof before a terminal worker can satisfy a lifecycle wait.
2742
- const settled = this.peek(id);
2743
- this.published.publish('run.updated', { run: settled, before: snapshotRun(settled) });
2744
- return true;
2745
- }
2746
- catch {
2747
- return false;
2748
- }
2749
- }
2750
- /** A deleted child's receipt replaces the private proof only after the deletion checkpoint. */
2751
- workerDeletionEvidence(id) {
2752
- const child = this.peek(id);
2753
- if (child?.delegation?.role !== 'worker' || child.delegation.workspace.ownerRunId !== id ||
2754
- child.delegation.destroy?.phase !== 'complete' || child.delegation.destroy.remaining.length ||
2755
- !['review', 'done', 'failed', 'cancelled'].includes(child.status))
2756
- return false;
2757
- return this.workerDeletionResult(id, child);
2758
- }
2759
- workerDeletionResult(id, child) {
2760
- const parent = this.peek(child.delegation.parentRunId);
2761
- if (parent?.delegation?.role !== 'root' || parent.delegation.historyDeletion)
2762
- return false;
2763
- const receipt = parent.delegation.receipts.find(entry => entry.workerId === id);
2764
- const result = this.workerResults.readWorkerResult(parent.id, id);
2765
- if (!receipt || !result?.settled || result.cleanup !== 'complete' || result.status !== child.status ||
2766
- result.revision !== (child.delegation.executionRevision ?? 0))
2767
- return false;
2768
- const { state: _state, ...workspace } = result.workspace;
2769
- if (JSON.stringify(workspace) !== JSON.stringify(child.delegation.workspace))
2770
- return false;
2771
- return workerDeletionProof(receipt.deletion, result.revision, workspace.resourceId, {
2772
- readProof: () => this.readWorkerExecution(id), resourcesSafe: generation => this.workerResourcesSafe(id, generation, workspace.resourceId),
2773
- scratchMayExist: () => agentTmpDirMayExist(this.dataDir, id), executionExists: () => existsSync(this.executionPath(id)),
2774
- });
2775
- }
2776
2386
  /** Write the pending rows out now (used on shutdown). */
2777
2387
  flush() {
2778
2388
  if (this.saveTimer) {
@@ -2783,22 +2393,6 @@ export class RunStore {
2783
2393
  }
2784
2394
  // ---- internals -----------------------------------------------------------
2785
2395
  seqs = new Map();
2786
- nextSeq(runId) {
2787
- const next = (this.seqs.get(runId) ?? this.rehydrateSeq(runId)) + 1;
2788
- this.seqs.set(runId, next);
2789
- return next;
2790
- }
2791
- /** After a restart the in-memory counter is empty while the run's NDJSON file
2792
- * keeps the history. Restarting from 1 would collide with the seqs a client
2793
- * already replayed — its `seq > maxSeq` dedup then silently drops every
2794
- * resumed event, even across a reload (the frozen-transcript symptom class
2795
- * of #424). One file read on the first post-restart append per run. */
2796
- rehydrateSeq(runId) {
2797
- return this.transcriptFacts.transcriptFacts(runId).lastSeq;
2798
- }
2799
- eventsPath(runId) {
2800
- return historyPaths(this.sourceDataDir(runId), runId).plain;
2801
- }
2802
2396
  /** Same location `handoffPath()` in handoff.ts produces — inlined to keep
2803
2397
  * the store free of upward imports. */
2804
2398
  handoffPath(runId) {