@hearsay-tools/squawk 0.18.0-dev.7724 → 0.18.0-dev.7731

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 (55) hide show
  1. package/dist/ci-wait/controller.d.ts +4 -4
  2. package/dist/delegation/routes.d.ts +14 -14
  3. package/dist/runs/lifecycle.d.ts +75 -0
  4. package/dist/runs/lifecycle.js +63 -0
  5. package/dist/runs/lifecycle.js.map +1 -0
  6. package/dist/runs/outcome-commit.d.ts +2 -0
  7. package/dist/runs/outcome-commit.js +1 -1
  8. package/dist/runs/outcome-commit.js.map +1 -1
  9. package/dist/runs/record-write-rules.d.ts +15 -3
  10. package/dist/runs/record-write-rules.js +38 -10
  11. package/dist/runs/record-write-rules.js.map +1 -1
  12. package/dist/runs/store.d.ts +8 -0
  13. package/dist/runs/store.js +135 -131
  14. package/dist/runs/store.js.map +1 -1
  15. package/dist/server/brand-file-routes.d.ts +7 -0
  16. package/dist/server/brand-file-routes.js +19 -0
  17. package/dist/server/brand-file-routes.js.map +1 -0
  18. package/dist/server/server.d.ts +1851 -1851
  19. package/dist/server/server.js +2 -7
  20. package/dist/server/server.js.map +1 -1
  21. package/dist/server/static-ui.js +7 -4
  22. package/dist/server/static-ui.js.map +1 -1
  23. package/dist/server/web-app-manifest.d.ts +23 -0
  24. package/dist/server/web-app-manifest.js +27 -0
  25. package/dist/server/web-app-manifest.js.map +1 -0
  26. package/dist/workflows/run/usage-accounting.js +3 -1
  27. package/dist/workflows/run/usage-accounting.js.map +1 -1
  28. package/package.json +4 -4
  29. package/web/dist/app-icon.png +0 -0
  30. package/web/dist/assets/{activity-motion-4jefGnf3.js → activity-motion-CHWLFQui.js} +1 -1
  31. package/web/dist/assets/{activity-route-CrgEEOkP.js → activity-route-CDZ8vEvw.js} +1 -1
  32. package/web/dist/assets/{commit-diff-panel-BhqIhVpi.js → commit-diff-panel-BiFrj_Kg.js} +1 -1
  33. package/web/dist/assets/{diff-Dtz4yPu-.js → diff-Bp_ZwIlK.js} +2 -2
  34. package/web/dist/assets/{diff-view-01iQrxA3.js → diff-view-BLWY32aP.js} +1 -1
  35. package/web/dist/assets/{file-preview-Bqu0JXBY.js → file-preview-BMb-p58M.js} +1 -1
  36. package/web/dist/assets/{git-toolbar-zEjeF-_V.js → git-toolbar-BLOs2P23.js} +1 -1
  37. package/web/dist/assets/{github-D3a22EyV.js → github-DLd49gwL.js} +1 -1
  38. package/web/dist/assets/{global-activity-route-DXD818_k.js → global-activity-route-C6qUGiQ-.js} +1 -1
  39. package/web/dist/assets/{index-DPA7Ibhf.js → index-D9Yu2XLO.js} +11 -11
  40. package/web/dist/assets/{markdown-Dzq31k8-.js → markdown-HUI2AGRH.js} +1 -1
  41. package/web/dist/assets/{preview-pane-connected-TaIGMKvt.js → preview-pane-connected-Br0FHHb0.js} +1 -1
  42. package/web/dist/assets/{repo-git-BvN7c_-7.js → repo-git-CXxRkRrr.js} +1 -1
  43. package/web/dist/assets/{report-reader-BEGToSIA.js → report-reader-DK9rxnu_.js} +1 -1
  44. package/web/dist/assets/{reports-D61rDO35.js → reports-DyqYeCfW.js} +1 -1
  45. package/web/dist/assets/{run-header-gwQQqs03.js → run-header-DI2Zp-1g.js} +1 -1
  46. package/web/dist/assets/{skills-DB3DAhWt.js → skills-BsojRHiF.js} +1 -1
  47. package/web/dist/assets/{task-changes-C4Hp9Bog.js → task-changes-D0fhNQ8e.js} +1 -1
  48. package/web/dist/assets/{task-commits-IGZ1CJcy.js → task-commits-DfPvhSgU.js} +1 -1
  49. package/web/dist/assets/{task-files-CBrQO4v2.js → task-files-Do9eS-uO.js} +1 -1
  50. package/web/dist/assets/{task-github-item-BJwFCJMl.js → task-github-item-IDiDedZh.js} +1 -1
  51. package/web/dist/assets/{task-thread-Dkn8HN1R.js → task-thread-BK0lz7hd.js} +1 -1
  52. package/web/dist/assets/{thread-state-DVfKElYJ.js → thread-state-D2FZC_j9.js} +1 -1
  53. package/web/dist/assets/{use-hand-to-agent-state-ChF_oDo3.js → use-hand-to-agent-state-CntaNwZk.js} +1 -1
  54. package/web/dist/assets/{workflows-BTzKBfs-.js → workflows-BnU1T_ay.js} +1 -1
  55. package/web/dist/index.html +13 -1
@@ -3,7 +3,8 @@ import { dataReadDirs, runDataDir } from '../project-paths.js';
3
3
  import { addRunSource, copyFallbackFamily, fallbackRunSource, bindWorkerResultPath, fallbackRunDeleteError, workerResultsDirectory } from './project-run-sources.js';
4
4
  import { productEnv } from '../core/product-env.js';
5
5
  import { registeredWaitRecord, registeredReceiptRecord } from './wait-registration-write.js';
6
- import { stageCommit, stageLoaded, stageDurableUpdate, stageDebouncedUpdate, stageConversation, stageArchiveFields, stagePullRequests, stageStepUpdate, redactPatch, redactText, clearPin } from './record-write-rules.js';
6
+ import { stageCommit, stageLoaded, stageDurableUpdate, stageDebouncedUpdate, stageConversation, stageArchiveFields, stagePullRequests, stageStepUpdate, stepTotals, redactPatch, redactText, clearPin } from './record-write-rules.js';
7
+ import { publishRunWrite, RunLifecycle, snapshotRun } from './lifecycle.js';
7
8
  import { workerDeletionProof } from './worker-deletion-proof.js';
8
9
  import { recordedHolders, workerResourceAuthorized } from './worker-resource-holders.js';
9
10
  import { listPeerTaskSummaries, parseStoredSummary } from './run-summary-page.js';
@@ -449,6 +450,9 @@ export class RunStore extends EventEmitter {
449
450
  persistence;
450
451
  /** Runs whose held record is ahead of its row; the next save or commit writes them. */
451
452
  dirty = new Set();
453
+ /** The typed lifecycle events, published beside each emitter event (lifecycle.ts). */
454
+ published = new RunLifecycle();
455
+ lifecycle = this.published;
452
456
  /** The lifecycle events run exits write (B12). */
453
457
  exitEvents = new ExitEvents((id, event) => this.appendEvent(id, event));
454
458
  /** Every worker's process scope (ADR 0032): spawn sites, Continue and destroy reach it here. */
@@ -856,7 +860,8 @@ export class RunStore extends EventEmitter {
856
860
  const row = this.db.get(id);
857
861
  return row ? this.decodeCold(row) : undefined;
858
862
  }
859
- decodeCold(row) {
863
+ /** `loaded` sees the record once the load has normalized it, before it is scoped: a heal's `before`. */
864
+ decodeCold(row, loaded) {
860
865
  this.coldReads.at(row.id, row.revision); // the fence below moves to this revision
861
866
  const decoded = decodeRunRow(row.data);
862
867
  if (!decoded) {
@@ -870,6 +875,7 @@ export class RunStore extends EventEmitter {
870
875
  const family = rowFamily(row);
871
876
  this.coldBase.set(row.id, { revision: row.revision, seq: row.seq, data: row.data, extras, owned: this.claimed.has(family) || this.pendingClaims.has(family) });
872
877
  reconcileLoadedRun(run, { keepLive: this.keepLive });
878
+ loaded?.(run);
873
879
  rescopeRun(run, this.repoHandle);
874
880
  return run;
875
881
  }
@@ -967,8 +973,10 @@ export class RunStore extends EventEmitter {
967
973
  * verdict reads (hearsay-tools/cezarion#1301). */
968
974
  republish(id) {
969
975
  const run = this.peek(id);
970
- if (run)
976
+ if (run) {
977
+ this.published.publish('run.updated', { run, before: snapshotRun(run), source: 'live-release' });
971
978
  this.emit('run', run, 'live-release');
979
+ }
972
980
  }
973
981
  /** Release `holder`'s pin. The run leaves memory at the next sweep once nothing else holds it. */
974
982
  unpin(id, holder) {
@@ -997,8 +1005,9 @@ export class RunStore extends EventEmitter {
997
1005
  return !summary || namesForeignReference(summary, handle);
998
1006
  }) ?? [];
999
1007
  for (const run of [...this.held.values()]) {
1008
+ const before = snapshotRun(run);
1000
1009
  if (rescopeRun(run, this.repoHandle)) {
1001
- this.touch(run);
1010
+ this.touch(run, before);
1002
1011
  healed = true;
1003
1012
  }
1004
1013
  }
@@ -1007,12 +1016,13 @@ export class RunStore extends EventEmitter {
1007
1016
  for (const row of stored) {
1008
1017
  if (!writable.has(rowFamily(row)))
1009
1018
  continue;
1010
- const run = this.decodeCold(row);
1019
+ let before;
1020
+ const run = this.decodeCold(row, (loaded) => { before = snapshotRun(loaded); });
1011
1021
  // `decodeCold` already scoped it with the handle just armed; write it when that changed it.
1012
1022
  if (!run || !this.storedScopeDiffers(row, run))
1013
1023
  continue;
1014
1024
  this.holdDecoded(run);
1015
- this.touch(run);
1025
+ this.touch(run, before ?? snapshotRun(run));
1016
1026
  healed = true;
1017
1027
  }
1018
1028
  // Discovery may finish after headless shutdown's final flush. Persist repairs now: the
@@ -1465,7 +1475,7 @@ export class RunStore extends EventEmitter {
1465
1475
  throw new RunWriteRefusedError(run.id, 'foreign');
1466
1476
  this.held.set(run.id, run);
1467
1477
  this.pruneOldRuns();
1468
- this.touch(run);
1478
+ this.touch(run, undefined);
1469
1479
  return run;
1470
1480
  }
1471
1481
  /** Build without publishing: owned creation must commit its receipt and run together. */
@@ -1715,7 +1725,7 @@ export class RunStore extends EventEmitter {
1715
1725
  if (!staged.changed)
1716
1726
  return { committed: false, answered: [], settled: [] };
1717
1727
  try {
1718
- this.commitIndex(new Map([[id, staged.next]]));
1728
+ this.commitIndex(new Map([[id, staged.next]]), undefined, { exits: new Map([[id, staged.exit]]) });
1719
1729
  }
1720
1730
  catch (error) {
1721
1731
  if (!opts.bestEffort)
@@ -1724,11 +1734,9 @@ export class RunStore extends EventEmitter {
1724
1734
  const live = this.record(id);
1725
1735
  if (!live)
1726
1736
  return { committed: false, answered: staged.answered, settled: staged.settled };
1727
- for (const key of Object.keys(live))
1728
- if (!(key in staged.next))
1729
- delete live[key];
1730
- Object.assign(live, staged.next);
1731
- this.touch(live);
1737
+ const before = snapshotRun(live);
1738
+ replaceRecord(live, staged.next);
1739
+ this.touch(live, before, staged.exit);
1732
1740
  return { committed: false, answered: staged.answered, settled: staged.settled };
1733
1741
  }
1734
1742
  return { committed: true, answered: staged.answered, settled: staged.settled };
@@ -1796,7 +1804,7 @@ export class RunStore extends EventEmitter {
1796
1804
  throw new Error('missing conversation ownership');
1797
1805
  stageConversation(staged, root, conversation.state, { recipientRunId: id, input: conversation.input }, runId => this.peek(runId), text => this.redactText(text));
1798
1806
  }
1799
- this.commitIndex(staged);
1807
+ this.commitIndex(staged, undefined, { exits: new Map([[id, exit]]) });
1800
1808
  }
1801
1809
  workerResultsDir(parentId, write = false) { return workerResultsDirectory(write ? this.writeDir(parentId) : this.sourceDataDir(parentId), parentId, write); }
1802
1810
  workerResultSnapshotPath(parentId, workerId, snapshotId) {
@@ -1870,12 +1878,14 @@ export class RunStore extends EventEmitter {
1870
1878
  * changing held objects or notifying subscribers. On failure retain all pending state; flush()
1871
1879
  * remains best-effort.
1872
1880
  */
1873
- commitIndex(input, source) {
1881
+ commitIndex(input, source, write = {}) {
1882
+ const exits = new Map(write.exits);
1874
1883
  const staged = stageCommit(input, {
1875
1884
  peek: id => this.peek(id),
1876
1885
  completionArchiveBlocker: run => this.completionArchiveBlocker(run),
1877
- stageArchive: (staged, run, archived) => this.stageArchive(staged, run, archived),
1886
+ stageArchive: (staged, run, archived) => this.stageArchive(staged, run, archived, exits),
1878
1887
  });
1888
+ const before = new Map([...staged].map(([id, next]) => [id, next ? write.before?.get(id) ?? snapshotRun(this.peek(id)) : undefined])), to = new Map([...staged].map(([id, next]) => [id, next?.status]));
1879
1889
  if (!this.db)
1880
1890
  throw this.openFailure ?? new Error('runs database unavailable: nothing can be saved');
1881
1891
  this.assertWritable(staged);
@@ -1890,23 +1900,22 @@ export class RunStore extends EventEmitter {
1890
1900
  }
1891
1901
  this.committing.add(id);
1892
1902
  const current = this.held.get(id);
1893
- if (current) {
1894
- for (const key of Object.keys(current)) {
1895
- if (!(key in next))
1896
- delete current[key];
1897
- }
1898
- Object.assign(current, next);
1899
- }
1903
+ if (current)
1904
+ replaceRecord(current, next);
1900
1905
  else
1901
1906
  this.held.set(id, next);
1902
1907
  }
1903
1908
  try {
1904
1909
  for (const id of staged.keys()) {
1905
1910
  const run = this.held.get(id);
1906
- if (run)
1911
+ if (run) {
1912
+ publishRunWrite(this.published, run, before.get(id), source, exits.get(id), to.get(id));
1907
1913
  this.emit('run', run, source);
1908
- else
1914
+ }
1915
+ else {
1916
+ this.published.publish('run.deleted', { runId: id });
1909
1917
  this.emit('deleted', id);
1918
+ }
1910
1919
  }
1911
1920
  }
1912
1921
  finally {
@@ -1932,7 +1941,7 @@ export class RunStore extends EventEmitter {
1932
1941
  }
1933
1942
  /** One archive write for manual actions, merge observations, completion, and sweeps.
1934
1943
  * Archiving files history away; it never stops a process or removes a worktree. */
1935
- stageArchive(staged, root, archived) {
1944
+ stageArchive(staged, root, archived, exits) {
1936
1945
  const ids = root.delegation?.role === 'worker' ? [root.id] :
1937
1946
  [root.id, ...new Set([...(this.db?.listIdsByParent(root.id) ?? []), ...this.listWorkersOf(root.id).map(run => run.id)])];
1938
1947
  const now = new Date().toISOString();
@@ -1945,7 +1954,9 @@ export class RunStore extends EventEmitter {
1945
1954
  restoreHistory(this.dataDir, id);
1946
1955
  }
1947
1956
  const next = { ...member, archiveBlocker: undefined };
1948
- archiveFields(next, archived, now);
1957
+ const exit = archiveFields(next, archived, now);
1958
+ if (exit)
1959
+ exits?.set(id, exit);
1949
1960
  staged.set(id, next);
1950
1961
  }
1951
1962
  }
@@ -2047,10 +2058,10 @@ export class RunStore extends EventEmitter {
2047
2058
  const redacted = this.redactPatch(extras);
2048
2059
  let moved;
2049
2060
  if (!guarded)
2050
- moved = this.writeRun(id, run, applyExit(run, exit, redacted, call), exitDurability(exit, run));
2061
+ moved = this.writeRun(id, run, applyExit(run, exit, redacted, call), exitDurability(exit, run), exit);
2051
2062
  else {
2052
2063
  const input = { ...run, ...redacted };
2053
- this.commitIndex(new Map([[id, { ...(spec.settle?.(input, { ...call, now: new Date().toISOString() }) ?? input), ...applyExit(run, exit, {}, call) }]]));
2064
+ this.commitIndex(new Map([[id, { ...(spec.settle?.(input, { ...call, now: new Date().toISOString() }) ?? input), ...applyExit(run, exit, {}, call) }]]), undefined, { exits: new Map([[id, exit]]) });
2054
2065
  moved = this.peek(id);
2055
2066
  }
2056
2067
  if (event)
@@ -2070,16 +2081,18 @@ export class RunStore extends EventEmitter {
2070
2081
  }
2071
2082
  /** One update of the held record `run`: committed at once, or written to the record for the next
2072
2083
  * save. A debounced write is best-effort, so a locked database cannot stop cleanup. */
2073
- writeRun(id, run, patch, durability) {
2084
+ writeRun(id, run, patch, durability, exit) {
2085
+ const before = snapshotRun(run);
2074
2086
  const hooks = {
2075
2087
  redact: (text) => this.redactText(text),
2076
2088
  repoHandle: this.repoHandle,
2077
2089
  restore: () => restoreHistory(this.dataDir, id),
2078
- archive: (record, archived) => this.applyArchived(record, archived),
2079
- touch: (record) => this.touch(record),
2090
+ archive: (record, archived) => this.applyArchived(record, archived, before, exit),
2091
+ touch: (record) => this.touch(record, before, exit),
2080
2092
  };
2081
2093
  if (durability === 'committed') {
2082
- this.commitIndex(new Map([[id, stageDurableUpdate(run, patch, hooks)]]));
2094
+ const staged = stageDurableUpdate(run, patch, hooks, exit);
2095
+ this.commitIndex(new Map([[id, staged.run]]), undefined, { before: new Map([[id, before]]), exits: new Map([[id, staged.exit]]) });
2083
2096
  return this.record(id);
2084
2097
  }
2085
2098
  stageDebouncedUpdate(run, patch, hooks);
@@ -2093,37 +2106,20 @@ export class RunStore extends EventEmitter {
2093
2106
  const run = this.record(runId);
2094
2107
  if (!run || run.steps.some((s) => s.id === step.id))
2095
2108
  return;
2096
- run.steps.push({ ...step, status: 'pending', iterations: 0, tokensUsed: 0 });
2097
- this.touch(run);
2109
+ const before = snapshotRun(run);
2110
+ run.steps = [...run.steps, { ...step, status: 'pending', iterations: 0, tokensUsed: 0 }];
2111
+ this.touch(run, before);
2098
2112
  }
2099
2113
  updateStep(runId, stepId, patch) {
2100
2114
  const run = this.record(runId);
2101
2115
  const step = run?.steps.find((s) => s.id === stepId);
2102
2116
  if (!run || !step)
2103
2117
  return;
2104
- Object.assign(step, stageStepUpdate(patch, text => this.redactText(text)));
2105
- run.tokensUsed = run.steps.reduce((sum, s) => sum + s.tokensUsed, 0);
2106
- const startedAgentSteps = run.steps.filter((candidate) => candidate.kind === 'agent' && candidate.iterations > 0);
2107
- const directionalComplete = startedAgentSteps.length > 0 &&
2108
- startedAgentSteps.every((candidate) => candidate.usageInvocationsStarted !== undefined &&
2109
- candidate.usageInvocationsObserved !== undefined &&
2110
- candidate.usageInvocationsObserved > 0 &&
2111
- candidate.usageInvocationsStarted === candidate.usageInvocationsObserved &&
2112
- candidate.usageTurnsStarted !== undefined &&
2113
- candidate.usageTurnsRecorded !== undefined &&
2114
- candidate.usageTurnsStarted > 0 &&
2115
- candidate.usageTurnsStarted === candidate.usageTurnsRecorded &&
2116
- candidate.inputTokens !== undefined &&
2117
- candidate.outputTokens !== undefined);
2118
- run.inputTokens = directionalComplete
2119
- ? startedAgentSteps.reduce((sum, candidate) => sum + (candidate.inputTokens ?? 0), 0)
2120
- : undefined;
2121
- run.outputTokens = directionalComplete
2122
- ? startedAgentSteps.reduce((sum, candidate) => sum + (candidate.outputTokens ?? 0), 0)
2123
- : undefined;
2124
- const cost = run.steps.reduce((sum, s) => sum + (s.costUsd ?? 0), 0);
2125
- run.costUsd = run.steps.some((step) => step.costUsd !== undefined) ? cost : undefined;
2126
- this.touch(run);
2118
+ const before = snapshotRun(run), next = { ...step, ...stageStepUpdate(patch, text => this.redactText(text)) };
2119
+ // Replaced, never changed in place, so `before` keeps the steps as they were.
2120
+ run.steps = run.steps.map((candidate) => candidate === step ? next : candidate);
2121
+ Object.assign(run, stepTotals(run.steps));
2122
+ this.touch(run, before);
2127
2123
  }
2128
2124
  listArchiveOnMergeCandidates(afterSeq = 0, limit = 32) {
2129
2125
  return this.db?.listArchiveOnMergeCandidates(afterSeq, limit) ?? [];
@@ -2210,10 +2206,10 @@ export class RunStore extends EventEmitter {
2210
2206
  const now = new Date().toISOString();
2211
2207
  if (merged.some(pr => Date.parse(pr.mergedAt) > Date.parse(now)))
2212
2208
  return false;
2213
- const staged = new Map();
2214
- this.stageArchive(staged, family[0], true);
2209
+ const staged = new Map(), exits = new Map();
2210
+ this.stageArchive(staged, family[0], true, exits);
2215
2211
  staged.get(snapshot.rootId).autoArchive = { reason: 'pull-requests-merged', archivedAt: now, fingerprint: current.fingerprint, pullRequests: merged };
2216
- this.commitIndex(staged);
2212
+ this.commitIndex(staged, undefined, { exits });
2217
2213
  for (const id of staged.keys())
2218
2214
  this.compressor.enqueue(id);
2219
2215
  return true;
@@ -2227,8 +2223,8 @@ export class RunStore extends EventEmitter {
2227
2223
  }
2228
2224
  /** Parent + owned workers; returns how many records flipped `archived`. */
2229
2225
  applyArchivedCascade(run, archived) {
2230
- const staged = new Map();
2231
- this.stageArchive(staged, run, archived);
2226
+ const staged = new Map(), exits = new Map();
2227
+ this.stageArchive(staged, run, archived, exits);
2232
2228
  let changed = 0;
2233
2229
  for (const [id, next] of staged) {
2234
2230
  if (next && this.peek(id)?.archived !== archived)
@@ -2236,15 +2232,14 @@ export class RunStore extends EventEmitter {
2236
2232
  if (next)
2237
2233
  next.completionAction = undefined; // an explicit filing/restoration retires pending work
2238
2234
  }
2239
- this.commitIndex(staged);
2235
+ this.commitIndex(staged, undefined, { exits });
2240
2236
  return changed;
2241
2237
  }
2242
- applyArchived(run, archived) {
2238
+ applyArchived(run, archived, before = snapshotRun(run), exit) {
2243
2239
  const changed = run.archived !== archived;
2244
2240
  // Transcript first: a restore throw aborts with the record unchanged (#818 S3).
2245
2241
  this.syncTranscriptForm(run.id, archived);
2246
- archiveFields(run, archived, new Date().toISOString());
2247
- this.touch(run);
2242
+ this.touch(run, before, archiveFields(run, archived, new Date().toISOString()) ?? exit);
2248
2243
  return changed;
2249
2244
  }
2250
2245
  /** Transcript form follows `archived`: enqueue compression, or restore the plain file now. */
@@ -2323,18 +2318,15 @@ export class RunStore extends EventEmitter {
2323
2318
  * Every active status is pinnable. Archived requests clear stale metadata instead, so a
2324
2319
  * late click racing archive cannot leave a hidden pin that reappears on unarchive. */
2325
2320
  setPinned(id, pinned) {
2326
- const run = this.record(id);
2327
- if (!run)
2328
- return undefined;
2329
- if (pinned && !run.archived) {
2330
- run.pinned = true;
2331
- run.pinnedAt = new Date().toISOString();
2332
- }
2333
- else {
2334
- clearPin(run);
2335
- }
2336
- this.touch(run);
2337
- return run;
2321
+ return this.change(id, (run) => {
2322
+ if (pinned && !run.archived) {
2323
+ run.pinned = true;
2324
+ run.pinnedAt = new Date().toISOString();
2325
+ }
2326
+ else {
2327
+ clearPin(run);
2328
+ }
2329
+ });
2338
2330
  }
2339
2331
  /** Bulk-archive finished runs (#780). `isSweepable` decides which; `archived` counts every
2340
2332
  * record that flipped (cascaded workers included), `ids` lists the top-level runs picked and
@@ -2373,12 +2365,7 @@ export class RunStore extends EventEmitter {
2373
2365
  * updated record rides the existing `run` SSE with no new event. Idempotent by
2374
2366
  * design: opening an already-read thread just re-stamps a later `seenAt`. */
2375
2367
  setRead(id) {
2376
- const run = this.record(id);
2377
- if (!run)
2378
- return undefined;
2379
- run.seenAt = new Date().toISOString();
2380
- this.touch(run);
2381
- return run;
2368
+ return this.change(id, (run) => { run.seenAt = new Date().toISOString(); });
2382
2369
  }
2383
2370
  /** Mark one run as UNread (#775): drop the read receipt so the run rejoins the unread
2384
2371
  * list. The inverse of `setRead` and, like it, `touch`es so the updated record rides the
@@ -2394,11 +2381,15 @@ export class RunStore extends EventEmitter {
2394
2381
  * the marker. WHETHER the action means anything for a given run is UI policy, and lives
2395
2382
  * in the cockpit's `runActionFlags` — the same split the rest of the store keeps. */
2396
2383
  setUnread(id) {
2397
- const run = this.record(id);
2384
+ return this.change(id, (run) => { delete run.seenAt; });
2385
+ }
2386
+ /** A debounced write of the held record `id`: `apply` changes it in place, then `touch` saves it. */
2387
+ change(id, apply) {
2388
+ const run = this.record(id), before = snapshotRun(run);
2398
2389
  if (!run)
2399
2390
  return undefined;
2400
- delete run.seenAt;
2401
- this.touch(run);
2391
+ apply(run);
2392
+ this.touch(run, before);
2402
2393
  return run;
2403
2394
  }
2404
2395
  /**
@@ -2427,8 +2418,9 @@ export class RunStore extends EventEmitter {
2427
2418
  continue;
2428
2419
  if (automation !== undefined && (automationIdOf(run) !== undefined) !== automation)
2429
2420
  continue;
2421
+ const before = snapshotRun(run);
2430
2422
  run.seenAt = now;
2431
- this.touch(run);
2423
+ this.touch(run, before);
2432
2424
  count++;
2433
2425
  }
2434
2426
  return count;
@@ -2457,10 +2449,12 @@ export class RunStore extends EventEmitter {
2457
2449
  this.facts.append(runId, full, Buffer.byteLength(line));
2458
2450
  this.maybeEnqueueHistoryCompress(run);
2459
2451
  this.liveItems.observe(runId, full, false);
2452
+ this.published.publish('run.event', { runId, event: full });
2460
2453
  this.emit('event', { runId, event: full });
2461
2454
  // Reference discovery runs last, after the event is persisted, indexed and
2462
2455
  // published: the janitor reads the event text and may still update the run.
2463
- scanEventReferences(run, full, this.repoHandle, (target, entries) => this.accumulatePullRequests(target, entries), (target) => this.touch(target));
2456
+ const before = snapshotRun(run);
2457
+ scanEventReferences(run, full, this.repoHandle, (target, entries) => this.accumulatePullRequests(target, entries), (target) => this.touch(target, before));
2464
2458
  return full;
2465
2459
  }
2466
2460
  /**
@@ -2476,43 +2470,42 @@ export class RunStore extends EventEmitter {
2476
2470
  * re-declare after it opens a PR, and taking that literally cost the task the PR it was about.
2477
2471
  */
2478
2472
  applyMarkerRefs(runId, refs) {
2479
- const run = this.record(runId);
2480
- if (!run || (refs.pr === undefined && refs.issue === undefined))
2481
- return run;
2482
- const numbers = [...new Set([...(run.markerRefs?.pr === undefined ? [] : [run.markerRefs.pr]),
2483
- ...(refs.prs ?? (refs.pr === undefined ? [] : [refs.pr]))])];
2484
- if (numbers.length)
2485
- this.accumulatePullRequests(run, numbers.flatMap((number) => {
2486
- const matches = (run.referencedPrCandidates ?? []).filter((url) => refUrlNumber(url) === number &&
2487
- (this.repoHandle ? isRepoScopedRef(url, run.task, this.repoHandle) : promptNamesRepo(url, run.task)));
2488
- const url = matches.length === 1 ? matches[0] : matches.length === 0 && this.repoHandle
2489
- ? `https://github.com/${this.repoHandle.owner}/${this.repoHandle.name}/pull/${number}` : undefined;
2490
- const parsed = runPullRequestSchema.safeParse({ number, ...(url ? { url } : {}), source: 'declared' });
2491
- return parsed.success ? [parsed.data] : [];
2492
- }));
2493
- run.markerRefs = {
2494
- ...run.markerRefs,
2495
- ...(refs.pr !== undefined ? { pr: refs.pr } : {}),
2496
- ...(refs.issue !== undefined ? { issue: refs.issue } : {}),
2497
- };
2498
- // `prNumber` is the about-PR as well (it is what paints a numeric-only chip), so a
2499
- // re-declaration naming the created PR only FILLS it — it never overwrites the number the
2500
- // task came in with, which is still the PR this task is about.
2501
- if (refs.pr !== undefined && (run.prNumber === undefined || refs.pr !== refUrlNumber(run.pullRequestUrl))) {
2502
- run.prNumber = refs.pr;
2503
- }
2504
- if (refs.issue !== undefined) {
2505
- run.issueNumber = originatingIssue(run) ?? refs.issue;
2506
- delete run.referencedIssueNumberSeeded;
2507
- }
2508
- if (run.markerRefs.pr !== undefined) {
2509
- run.referencedPullRequestUrl = resolveReferencedRef(run.referencedPrCandidates ?? [], run.task, referencedPrDeclaration(run), this.repoHandle);
2510
- }
2511
- if (run.markerRefs.issue !== undefined) {
2512
- run.referencedIssueUrl = resolveIssueReference(run, this.repoHandle);
2513
- }
2514
- this.touch(run);
2515
- return run;
2473
+ if (refs.pr === undefined && refs.issue === undefined)
2474
+ return this.record(runId);
2475
+ return this.change(runId, (run) => {
2476
+ const numbers = [...new Set([...(run.markerRefs?.pr === undefined ? [] : [run.markerRefs.pr]),
2477
+ ...(refs.prs ?? (refs.pr === undefined ? [] : [refs.pr]))])];
2478
+ if (numbers.length)
2479
+ this.accumulatePullRequests(run, numbers.flatMap((number) => {
2480
+ const matches = (run.referencedPrCandidates ?? []).filter((url) => refUrlNumber(url) === number &&
2481
+ (this.repoHandle ? isRepoScopedRef(url, run.task, this.repoHandle) : promptNamesRepo(url, run.task)));
2482
+ const url = matches.length === 1 ? matches[0] : matches.length === 0 && this.repoHandle
2483
+ ? `https://github.com/${this.repoHandle.owner}/${this.repoHandle.name}/pull/${number}` : undefined;
2484
+ const parsed = runPullRequestSchema.safeParse({ number, ...(url ? { url } : {}), source: 'declared' });
2485
+ return parsed.success ? [parsed.data] : [];
2486
+ }));
2487
+ run.markerRefs = {
2488
+ ...run.markerRefs,
2489
+ ...(refs.pr !== undefined ? { pr: refs.pr } : {}),
2490
+ ...(refs.issue !== undefined ? { issue: refs.issue } : {}),
2491
+ };
2492
+ // `prNumber` is the about-PR as well (it is what paints a numeric-only chip), so a
2493
+ // re-declaration naming the created PR only FILLS it — it never overwrites the number the
2494
+ // task came in with, which is still the PR this task is about.
2495
+ if (refs.pr !== undefined && (run.prNumber === undefined || refs.pr !== refUrlNumber(run.pullRequestUrl))) {
2496
+ run.prNumber = refs.pr;
2497
+ }
2498
+ if (refs.issue !== undefined) {
2499
+ run.issueNumber = originatingIssue(run) ?? refs.issue;
2500
+ delete run.referencedIssueNumberSeeded;
2501
+ }
2502
+ if (run.markerRefs.pr !== undefined) {
2503
+ run.referencedPullRequestUrl = resolveReferencedRef(run.referencedPrCandidates ?? [], run.task, referencedPrDeclaration(run), this.repoHandle);
2504
+ }
2505
+ if (run.markerRefs.issue !== undefined) {
2506
+ run.referencedIssueUrl = resolveIssueReference(run, this.repoHandle);
2507
+ }
2508
+ });
2516
2509
  }
2517
2510
  /** Authoritative creation keeps the first scalar for publishing, plus every created identity. */
2518
2511
  recordCreatedPr(runId, url) {
@@ -2520,13 +2513,14 @@ export class RunStore extends EventEmitter {
2520
2513
  const parsed = runPullRequestSchema.safeParse({ number: refUrlNumber(url), url, source: 'created' });
2521
2514
  if (!run || !parsed.success)
2522
2515
  return run;
2516
+ const before = snapshotRun(run);
2523
2517
  let changed = this.accumulatePullRequests(run, [parsed.data]);
2524
2518
  if (!run.pullRequestUrl) {
2525
2519
  run.pullRequestUrl = url;
2526
2520
  changed = true;
2527
2521
  }
2528
2522
  if (changed)
2529
- this.touch(run);
2523
+ this.touch(run, before);
2530
2524
  return run;
2531
2525
  }
2532
2526
  accumulatePullRequests(run, entries) {
@@ -2544,6 +2538,7 @@ export class RunStore extends EventEmitter {
2544
2538
  emitEphemeral(runId, event) {
2545
2539
  const full = this.redact({ ...event, seq: this.nextSeq(runId), ts: new Date().toISOString() });
2546
2540
  this.liveItems.observe(runId, full, true);
2541
+ this.published.publish('run.event', { runId, event: full });
2547
2542
  this.emit('event', { runId, event: full });
2548
2543
  return full;
2549
2544
  }
@@ -2876,7 +2871,9 @@ export class RunStore extends EventEmitter {
2876
2871
  } } : {}) });
2877
2872
  // The earlier index event cannot attest exit: subscribers must observe the
2878
2873
  // durable private proof before a terminal worker can satisfy a lifecycle wait.
2879
- this.emit('run', this.peek(id));
2874
+ const settled = this.peek(id);
2875
+ this.published.publish('run.updated', { run: settled, before: snapshotRun(settled) });
2876
+ this.emit('run', settled);
2880
2877
  return true;
2881
2878
  }
2882
2879
  catch {
@@ -3047,6 +3044,7 @@ export class RunStore extends EventEmitter {
3047
3044
  removeAgentTmpDir(this.dataDir, id);
3048
3045
  this.seqs.delete(id);
3049
3046
  this.scheduleSave();
3047
+ this.published.publish('run.deleted', { runId: id });
3050
3048
  this.emit('deleted', id);
3051
3049
  }
3052
3050
  return existed;
@@ -3086,9 +3084,11 @@ export class RunStore extends EventEmitter {
3086
3084
  imagesDir(runId) {
3087
3085
  return join(this.sourceDataDir(runId), 'runs', `${runId}-images`);
3088
3086
  }
3089
- touch(run) {
3087
+ /** Save `run` debounced and publish it; `before` is the record at the write's entry (none: created). */
3088
+ touch(run, before, exit) {
3090
3089
  this.dirty.add(run.id);
3091
3090
  this.scheduleSave();
3091
+ publishRunWrite(this.published, run, before, undefined, exit);
3092
3092
  this.emit('run', run);
3093
3093
  this.maybeEnqueueHistoryCompress(run);
3094
3094
  }
@@ -3344,6 +3344,7 @@ export class RunStore extends EventEmitter {
3344
3344
  if (this.isFallbackRun(conflict.id))
3345
3345
  this.held.delete(conflict.id);
3346
3346
  const held = this.held.get(conflict.id);
3347
+ const before = snapshotRun(held ?? staged.get(conflict.id) ?? undefined);
3347
3348
  if (current && conflict.current) {
3348
3349
  // The other writer's record as it stands, normalized only as a live owner's run would be.
3349
3350
  reconcileLoadedRun(current, { keepLive: true });
@@ -3351,11 +3352,13 @@ export class RunStore extends EventEmitter {
3351
3352
  if (held)
3352
3353
  replaceRecord(held, current);
3353
3354
  this.base.set(conflict.id, { revision: conflict.current.revision, seq: conflict.current.seq, data: conflict.current.data, extras: decoded.extras });
3355
+ publishRunWrite(this.published, held ?? current, before ?? snapshotRun(current), 'conflict');
3354
3356
  this.emit('run', held ?? current);
3355
3357
  }
3356
3358
  else {
3357
3359
  this.held.delete(conflict.id);
3358
3360
  this.base.delete(conflict.id);
3361
+ this.published.publish('run.deleted', { runId: conflict.id });
3359
3362
  this.emit('deleted', conflict.id);
3360
3363
  }
3361
3364
  console.error(`[hsq] run ${conflict.id} was changed by another writer (${conflict.reason}); this process will not write it again until Squawk restarts. Evidence: ${join(this.dataDir, RUNS_DB_FILE)}, table run_conflicts, seq ${seqs[index]}.`);
@@ -3396,6 +3399,7 @@ export class RunStore extends EventEmitter {
3396
3399
  close() {
3397
3400
  this.liveItems.clear();
3398
3401
  // Demand-bound feeds stop before storage disappears during project removal/shutdown.
3402
+ this.published.publish('store.closed', {});
3399
3403
  this.emit('closed');
3400
3404
  this.compressor.stop();
3401
3405
  this.fallbackFacts?.stop();
@@ -3426,6 +3430,6 @@ function archiveDigest(value) {
3426
3430
  return createHash('sha256').update(JSON.stringify(value)).digest('hex');
3427
3431
  }
3428
3432
  function archiveFields(run, archived, now) {
3429
- stageArchiveFields(run, archived, now);
3433
+ return stageArchiveFields(run, archived, now);
3430
3434
  }
3431
3435
  //# sourceMappingURL=store.js.map