@hearsay-tools/squawk 0.18.0-dev.7808 → 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 (118) 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/delegation/conversation-send.js +1 -1
  5. package/dist/delegation/conversation-send.js.map +1 -1
  6. package/dist/delegation/conversations.js +4 -4
  7. package/dist/delegation/conversations.js.map +1 -1
  8. package/dist/delegation/park-notice.d.ts +3 -1
  9. package/dist/delegation/park-notice.js +2 -2
  10. package/dist/delegation/park-notice.js.map +1 -1
  11. package/dist/delegation/provision.js +1 -1
  12. package/dist/delegation/provision.js.map +1 -1
  13. package/dist/delegation/results.js +1 -1
  14. package/dist/delegation/results.js.map +1 -1
  15. package/dist/delegation/routes.d.ts +11 -11
  16. package/dist/delegation/service.js +5 -5
  17. package/dist/delegation/service.js.map +1 -1
  18. package/dist/delegation/transport.d.ts +4 -4
  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 +30 -8
  32. package/dist/runs/run-redaction.d.ts +19 -0
  33. package/dist/runs/run-redaction.js +36 -0
  34. package/dist/runs/run-redaction.js.map +1 -0
  35. package/dist/runs/store.d.ts +8 -66
  36. package/dist/runs/store.js +36 -214
  37. package/dist/runs/store.js.map +1 -1
  38. package/dist/runs/transcript-facts-fold.d.ts +1 -1
  39. package/dist/runs/transcript-facts-fold.js +1 -1
  40. package/dist/runs/transcript-facts-fold.js.map +1 -1
  41. package/dist/runs/webhook.d.ts +3 -1
  42. package/dist/runs/webhook.js +3 -3
  43. package/dist/runs/webhook.js.map +1 -1
  44. package/dist/server/activity-routes.d.ts +23 -23
  45. package/dist/server/project-context.d.ts +3 -1
  46. package/dist/server/project-context.js.map +1 -1
  47. package/dist/server/provider-auth-runtime.js +2 -2
  48. package/dist/server/provider-auth-runtime.js.map +1 -1
  49. package/dist/server/runners-routes.d.ts +10 -10
  50. package/dist/server/server.d.ts +6 -6
  51. package/dist/server/server.js +2 -2
  52. package/dist/server/server.js.map +1 -1
  53. package/dist/server/workspace-live-routes.d.ts +6 -6
  54. package/dist/workflows/run/attachment-writer.js +1 -1
  55. package/dist/workflows/run/attachment-writer.js.map +1 -1
  56. package/dist/workflows/run/auto-resume.js +4 -4
  57. package/dist/workflows/run/auto-resume.js.map +1 -1
  58. package/dist/workflows/run/continuation-session.js +9 -9
  59. package/dist/workflows/run/continuation-session.js.map +1 -1
  60. package/dist/workflows/run/cut-off-work.d.ts +8 -6
  61. package/dist/workflows/run/cut-off-work.js +2 -2
  62. package/dist/workflows/run/cut-off-work.js.map +1 -1
  63. package/dist/workflows/run/family-reconciler.js +1 -1
  64. package/dist/workflows/run/family-reconciler.js.map +1 -1
  65. package/dist/workflows/run/human-waits.js +4 -4
  66. package/dist/workflows/run/human-waits.js.map +1 -1
  67. package/dist/workflows/run/input-delivery.js +11 -11
  68. package/dist/workflows/run/input-delivery.js.map +1 -1
  69. package/dist/workflows/run/input-receipts.js +3 -3
  70. package/dist/workflows/run/input-receipts.js.map +1 -1
  71. package/dist/workflows/run/launch-context.js +1 -1
  72. package/dist/workflows/run/launch-context.js.map +1 -1
  73. package/dist/workflows/run/launch-read-resolver.d.ts +3 -1
  74. package/dist/workflows/run/launch-read-resolver.js +5 -5
  75. package/dist/workflows/run/launch-read-resolver.js.map +1 -1
  76. package/dist/workflows/run/memory-guard.js +2 -2
  77. package/dist/workflows/run/memory-guard.js.map +1 -1
  78. package/dist/workflows/run/queued-revival.js +5 -5
  79. package/dist/workflows/run/queued-revival.js.map +1 -1
  80. package/dist/workflows/run/run-cancel.js +1 -1
  81. package/dist/workflows/run/run-cancel.js.map +1 -1
  82. package/dist/workflows/run/run-finish.js +5 -5
  83. package/dist/workflows/run/run-finish.js.map +1 -1
  84. package/dist/workflows/run/run-recovery.js +4 -4
  85. package/dist/workflows/run/run-recovery.js.map +1 -1
  86. package/dist/workflows/run/run-settlement.js +12 -12
  87. package/dist/workflows/run/run-settlement.js.map +1 -1
  88. package/dist/workflows/run/run-skills.js +1 -1
  89. package/dist/workflows/run/run-skills.js.map +1 -1
  90. package/dist/workflows/run/session-events.js +4 -4
  91. package/dist/workflows/run/session-events.js.map +1 -1
  92. package/dist/workflows/run/step-loop.js +1 -1
  93. package/dist/workflows/run/step-loop.js.map +1 -1
  94. package/dist/workflows/run/step-session.js +1 -1
  95. package/dist/workflows/run/step-session.js.map +1 -1
  96. package/dist/workflows/run/subagent-waits.js +2 -2
  97. package/dist/workflows/run/subagent-waits.js.map +1 -1
  98. package/dist/workflows/run/turn-bookkeeping.js +2 -2
  99. package/dist/workflows/run/turn-bookkeeping.js.map +1 -1
  100. package/dist/workflows/run/turn-nudges.js +6 -6
  101. package/dist/workflows/run/turn-nudges.js.map +1 -1
  102. package/dist/workflows/run/turn-settler.d.ts +3 -1
  103. package/dist/workflows/run/turn-settler.js +10 -10
  104. package/dist/workflows/run/turn-settler.js.map +1 -1
  105. package/dist/workflows/run/usage-accounting.js +1 -1
  106. package/dist/workflows/run/usage-accounting.js.map +1 -1
  107. package/dist/workflows/run/wake-admission.js +2 -2
  108. package/dist/workflows/run/wake-admission.js.map +1 -1
  109. package/dist/workflows/run/worker-orphans.js +2 -2
  110. package/dist/workflows/run/worker-orphans.js.map +1 -1
  111. package/dist/workflows/run/worker-questions.js +14 -14
  112. package/dist/workflows/run/worker-questions.js.map +1 -1
  113. package/dist/workflows/run/workflow-position.d.ts +3 -1
  114. package/dist/workflows/run/worktree-autosave.js +1 -1
  115. package/dist/workflows/run/worktree-autosave.js.map +1 -1
  116. package/dist/workflows/run.js +2 -2
  117. package/dist/workflows/run.js.map +1 -1
  118. package/package.json +4 -4
@@ -21,6 +21,8 @@ import { type RawExtras } from './raw-record.ts';
21
21
  import { RunStoreOpenError } from './store-open-error.ts';
22
22
  import { type SpawnCapacityRefusal } from './owned-run-create.ts';
23
23
  import { WorkerResultsTopic } from './worker-results.ts';
24
+ import { RunEventLogTopic } from './event-log.ts';
25
+ import { RunRedaction } from './run-redaction.ts';
24
26
  /** Per-store persistence adapter; the second argument is the normal fenced transaction. */
25
27
  export type RunStorePersistence = (changes: RunDatabaseChanges, transaction: RunDatabase['transaction']) => RunDatabaseCommit;
26
28
  export type RunStatus = 'queued' | 'running' | 'waiting' | 'review' | 'done' | 'failed' | 'cancelled';
@@ -3308,6 +3310,10 @@ export declare class RunStore {
3308
3310
  readonly retention: RunRetentionTopic;
3309
3311
  /** The saved snapshot of a worker's collected result (hearsay-tools/squawk#4038). */
3310
3312
  readonly workerResults: WorkerResultsTopic;
3313
+ /** The event log and reference markers (hearsay-tools/squawk#4040). */
3314
+ readonly eventLog: RunEventLogTopic;
3315
+ /** The scrub of events and free text (hearsay-tools/squawk#4040). */
3316
+ readonly redaction: RunRedaction;
3311
3317
  private executions;
3312
3318
  /** A worker's execution, process, identity and scope records (hearsay-tools/squawk#4039), built on
3313
3319
  * first use by the factory this process registered; throws when none is registered. */
@@ -3413,6 +3419,8 @@ export declare class RunStore {
3413
3419
  adoptFallbackFamily(id: string): boolean;
3414
3420
  private fallbackRefusal;
3415
3421
  /** Run files are written only for a family this store may write, never a fallback family. */
3422
+ /** The error `appendEvent` throws for a run this store cannot write or does not know. */
3423
+ private missingRunError;
3416
3424
  private writeDir;
3417
3425
  /** Every run whose family another process owns (`foreignClaimedRunIds`). */
3418
3426
  listForeignClaimedRunIds(): string[];
@@ -3871,77 +3879,11 @@ export declare class RunStore {
3871
3879
  * (hearsay-tools/cezarion#1616); absent stamps both.
3872
3880
  */
3873
3881
  markAllRead(automation?: boolean): number;
3874
- appendEvent(runId: string, event: {
3875
- type: string;
3876
- stepId?: string | undefined;
3877
- [key: string]: unknown;
3878
- }): RunEvent;
3879
- /**
3880
- * Apply agent-declared reference markers (spec 2026-07-18-task-ref-markers).
3881
- * Marker values are authoritative for the display tier: they overwrite the
3882
- * regex/namer numbers unless the prompt identifies the originating issue, and a declared PR re-resolves the referenced URL
3883
- * against the candidate working set — including down to `undefined` when no
3884
- * candidate matches (a wrong chip is worse than no chip). The created tier
3885
- * (`pullRequestUrl`) is deliberately untouched.
3886
- *
3887
- * One declaration is NOT a statement about the referenced tier: the number of the PR this run
3888
- * itself created. See `referencedPrDeclaration` — the marker contract asks the agent to
3889
- * re-declare after it opens a PR, and taking that literally cost the task the PR it was about.
3890
- */
3891
- applyMarkerRefs(runId: string, refs: {
3892
- pr?: number | undefined;
3893
- prs?: readonly number[] | undefined;
3894
- issue?: number | undefined;
3895
- }): RunRecord | undefined;
3896
- /** Authoritative creation keeps the first scalar for publishing, plus every created identity. */
3897
- recordCreatedPr(runId: string, url: string): RunRecord | undefined;
3898
- private accumulatePullRequests;
3899
- /**
3900
- * Fan an event out to live subscribers WITHOUT writing it to the NDJSON
3901
- * file — the channel for coalesced `item.delta` flushes (protocol-v2
3902
- * performance guardrail: raw deltas never hit disk; replay = the persisted
3903
- * snapshots). Stamped with `seq`/`ts` like persisted lines so the live
3904
- * wire keeps one ordering axis. Finite polling coalesces active item content
3905
- * into bounded in-memory snapshots on that clock; disk replay still has gaps
3906
- * (dedup compares with `>`).
3907
- */
3908
- emitEphemeral(runId: string, event: {
3909
- type: string;
3910
- stepId?: string;
3911
- [key: string]: unknown;
3912
- }): RunEvent;
3913
- /** Lazily-collected concrete secret values from the host env (#427). */
3914
- private secretValues;
3915
- /** Controller-issued tokens never persist, including when host-secret redaction is disabled. */
3916
- private readonly sessionSecrets;
3917
- registerSessionSecret(value: string): void;
3918
- containsSessionSecret(value: string): boolean;
3919
- /**
3920
- * Scrub known credential values / token shapes from an event before it is
3921
- * persisted or fanned out. On by default; `CEZ_REDACT_SECRETS=0` opts out.
3922
- */
3923
- private redact;
3924
- /** Best-effort scrub of one free-text string bound for `runs.json`. Honors
3925
- * the `CEZ_REDACT_SECRETS=0` opt-out itself so every caller inherits it. */
3926
- redactText(text: string): string;
3927
- private hostSecrets;
3928
- hasProjection(runId: string, projectionId: string): boolean;
3929
3882
  /** Indexed family enumeration, including members not yet flushed to SQLite. */
3930
3883
  listFamilyRunIds(rootId: string): string[];
3931
- /** `readEvents` off the event loop (async read and async brotli), for collection paths. */
3932
- readEventsAsync(runId: string): Promise<RunEvent[]>;
3933
- readEvents(runId: string): RunEvent[];
3934
3884
  /** Write the pending rows out now (used on shutdown). */
3935
3885
  flush(): void;
3936
3886
  private seqs;
3937
- private nextSeq;
3938
- /** After a restart the in-memory counter is empty while the run's NDJSON file
3939
- * keeps the history. Restarting from 1 would collide with the seqs a client
3940
- * already replayed — its `seq > maxSeq` dedup then silently drops every
3941
- * resumed event, even across a reload (the frozen-transcript symptom class
3942
- * of #424). One file read on the first post-restart append per run. */
3943
- private rehydrateSeq;
3944
- private eventsPath;
3945
3887
  /** Same location `handoffPath()` in handoff.ts produces — inlined to keep
3946
3888
  * the store free of upward imports. */
3947
3889
  private handoffPath;
@@ -1,17 +1,15 @@
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
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
10
  import { randomUUID, createHash } 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';
@@ -28,15 +26,13 @@ import { HistoryCompressor } from './history-compressor.js';
28
26
  import { LiveItemSnapshots } from './live-item-snapshots.js';
29
27
  import { stampOf } from './transcript-facts.js';
30
28
  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';
29
+ import { hasPlainHistory, historyPaths, restoreHistory } from './history-file.js';
33
30
  // Pure, dependency-free reference helpers — the same sanity bound the marker parser applies.
34
31
  import { archivePullRequests, pullRequestKey } from './pull-requests.js';
35
- import { isRepoScopedRef, promptNamesRepo } from './task-refs.js';
36
32
  // Type-only module (zod + nothing else), so this cannot cycle back into the store.
37
33
  import { workflowDefSchema } from '../workflows/types.js';
38
34
  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';
35
+ import { ISSUE_URL_RE, namesForeignReference, referencedPrDeclaration, rescopeRun, resolveReferencedRef, restoreOriginatingIssue, trackReferencedIssues, trackReferencedPrs } from './run-references.js';
40
36
  import { applyExit, doneCommits, exitDurability, RUN_EXITS } from './run-exits.js';
41
37
  import { assertConversationIdFree } from './conversation-identity.js';
42
38
  export { ConversationIdInUseError } from './conversation-identity.js';
@@ -59,6 +55,8 @@ import { archiveStoreFamily } from './archive-family.js';
59
55
  import { claimStoreFamilies } from './claim-families.js';
60
56
  import { createStoreOwnedRun } from './owned-run-create.js';
61
57
  import { WorkerResultsTopic } from './worker-results.js';
58
+ import { RunEventLogTopic } from './event-log.js';
59
+ import { RunRedaction } from './run-redaction.js';
62
60
  import { claimOwnerLive, closeClaimSession, familyKey, foreignClaimedRunIds, liveForeignClaimedRunIds, openClaimSession, rowFamily } from './run-claims.js';
63
61
  import { assertProjectWritable, projectWriteRefused } from '../server/cockpit-ownership.js';
64
62
  /**
@@ -345,21 +343,6 @@ function isDestroyProgress(before, after) {
345
343
  return false;
346
344
  return isDeepStrictEqual({ ...before, destroy: undefined }, { ...after, destroy: undefined });
347
345
  }
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
346
  /** An archived page's cursor: the last row's order, opaque to clients. A held run with no row yet
364
347
  * lists after every row (`seq` is infinite), which JSON cannot carry, so it travels as null. */
365
348
  function encodeArchivedCursor(key) {
@@ -420,7 +403,7 @@ export class RunStore {
420
403
  published = new RunLifecycle();
421
404
  lifecycle = this.published;
422
405
  /** The lifecycle events run exits write (B12). */
423
- exitEvents = new ExitEvents((id, event) => this.appendEvent(id, event));
406
+ exitEvents = new ExitEvents((id, event) => this.eventLog.appendEvent(id, event));
424
407
  /** Runs gone from memory whose rows the next save or commit deletes. */
425
408
  deleted = new Set();
426
409
  /** Deleted runs whose history files (events, handoff, images, artifacts) go once the delete of
@@ -464,6 +447,10 @@ export class RunStore {
464
447
  retention;
465
448
  /** The saved snapshot of a worker's collected result (hearsay-tools/squawk#4038). */
466
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;
467
454
  executions;
468
455
  /** A worker's execution, process, identity and scope records (hearsay-tools/squawk#4039), built on
469
456
  * first use by the factory this process registered; throws when none is registered. */
@@ -481,6 +468,7 @@ export class RunStore {
481
468
  }
482
469
  constructor(dataDir) {
483
470
  this.dataDir = dataDir;
471
+ this.redaction = new RunRedaction();
484
472
  this.transcriptFacts = new RunTranscriptFacts(dataDir, {
485
473
  isFallbackRun: (id) => this.isFallbackRun(id),
486
474
  sourceDataDir: (id) => this.sourceDataDir(id),
@@ -493,8 +481,14 @@ export class RunStore {
493
481
  this.workerResults = new WorkerResultsTopic(dataDir, {
494
482
  peek: (id) => this.peek(id), hasRun: (id) => this.hasRun(id), hasFallbackRun: (id) => this.hasFallbackRun(id),
495
483
  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),
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),
498
492
  });
499
493
  this.retention = new RunRetentionTopic(dataDir, {
500
494
  db: () => this.db, held: this.held, deleted: this.deleted, quarantined: this.quarantined,
@@ -803,6 +797,15 @@ export class RunStore {
803
797
  }
804
798
  fallbackRefusal(id) { return new RunWriteRefusedError(id, 'fallback', fallbackRunDeleteError(this.dataDir, true)); }
805
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
+ }
806
809
  writeDir(id) { if (this.runOwnership(id) === 'fallback')
807
810
  throw this.fallbackRefusal(id); return runDataDir(this.dataDir, id); }
808
811
  /** Every run whose family another process owns (`foreignClaimedRunIds`). */
@@ -1489,7 +1492,7 @@ export class RunStore {
1489
1492
  // scrubbed: it is the user's own prompt and is replayed into `{{task}}`
1490
1493
  // when a queued run is revived after a restart (#367), so redacting it
1491
1494
  // would corrupt the revived run.
1492
- title: this.redactText(input.title),
1495
+ title: this.redaction.redactText(input.title),
1493
1496
  workflow: input.workflow,
1494
1497
  task: input.task,
1495
1498
  model: input.model,
@@ -1533,9 +1536,9 @@ export class RunStore {
1533
1536
  const root = this.peek(rootId);
1534
1537
  if (root?.delegation?.role !== 'root')
1535
1538
  throw new Error('missing conversation root');
1536
- 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));
1537
1540
  const staged = new Map();
1538
- 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));
1539
1542
  this.commitIndex(staged);
1540
1543
  }
1541
1544
  /** Crash recovery (#505): input a harness accepted but was never seen reading goes
@@ -1803,7 +1806,7 @@ export class RunStore {
1803
1806
  const root = this.peek(conversation.rootId);
1804
1807
  if (root?.delegation?.role !== 'root' || run.delegation.parentRunId !== root.id)
1805
1808
  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));
1809
+ stageConversation(staged, root, conversation.state, { recipientRunId: id, input: conversation.input }, runId => this.peek(runId), text => this.redaction.redactText(text));
1807
1810
  }
1808
1811
  this.commitIndex(staged, undefined, { exits: new Map([[id, exit]]) });
1809
1812
  }
@@ -2026,7 +2029,7 @@ export class RunStore {
2026
2029
  writeRun(id, run, patch, durability, exit) {
2027
2030
  const before = snapshotRun(run);
2028
2031
  const hooks = {
2029
- redact: (text) => this.redactText(text),
2032
+ redact: (text) => this.redaction.redactText(text),
2030
2033
  repoHandle: this.repoHandle,
2031
2034
  restore: () => restoreHistory(this.dataDir, id),
2032
2035
  archive: (record, archived) => this.applyArchived(record, archived, before, exit),
@@ -2041,7 +2044,7 @@ export class RunStore {
2041
2044
  return run;
2042
2045
  }
2043
2046
  redactPatch(patch) {
2044
- return redactPatch(patch, text => this.redactText(text));
2047
+ return redactPatch(patch, text => this.redaction.redactText(text));
2045
2048
  }
2046
2049
  /** Append a step to an existing run (used by "Continue" — spec 003). */
2047
2050
  addStep(runId, step) {
@@ -2057,7 +2060,7 @@ export class RunStore {
2057
2060
  const step = run?.steps.find((s) => s.id === stepId);
2058
2061
  if (!run || !step)
2059
2062
  return;
2060
- 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)) };
2061
2064
  // Replaced, never changed in place, so `before` keeps the steps as they were.
2062
2065
  run.steps = run.steps.map((candidate) => candidate === step ? next : candidate);
2063
2066
  Object.assign(run, stepTotals(run.steps));
@@ -2367,150 +2370,6 @@ export class RunStore {
2367
2370
  }
2368
2371
  return count;
2369
2372
  }
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
2373
  /** Indexed family enumeration, including members not yet flushed to SQLite. */
2515
2374
  listFamilyRunIds(rootId) {
2516
2375
  const ids = new Set([rootId, ...(this.db?.listIdsByParent(rootId) ?? [])]);
@@ -2524,27 +2383,6 @@ export class RunStore {
2524
2383
  ids.delete(id);
2525
2384
  return [...ids];
2526
2385
  }
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
2386
  /** Write the pending rows out now (used on shutdown). */
2549
2387
  flush() {
2550
2388
  if (this.saveTimer) {
@@ -2555,22 +2393,6 @@ export class RunStore {
2555
2393
  }
2556
2394
  // ---- internals -----------------------------------------------------------
2557
2395
  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
2396
  /** Same location `handoffPath()` in handoff.ts produces — inlined to keep
2575
2397
  * the store free of upward imports. */
2576
2398
  handoffPath(runId) {