@modelprofile.com/flexharness 16.3.0 → 16.4.0

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 (41) hide show
  1. package/dist_ts/00_commitinfo_data.js +1 -1
  2. package/dist_ts/classes.flexharness.core.d.ts +6 -0
  3. package/dist_ts/classes.flexharness.core.js +28 -15
  4. package/dist_ts/classes.flexharness.d.ts +6 -1
  5. package/dist_ts/classes.flexharness.js +8 -1
  6. package/dist_ts/classes.flexharness.projects.d.ts +10 -0
  7. package/dist_ts/classes.flexharness.projects.js +48 -21
  8. package/dist_ts/classes.flexharness.prompts.js +5 -3
  9. package/dist_ts/classes.flexharness.runs.js +6 -3
  10. package/dist_ts/classes.flexharness.sessions.d.ts +8 -1
  11. package/dist_ts/classes.flexharness.sessions.js +30 -20
  12. package/dist_ts/index.d.ts +1 -1
  13. package/dist_ts/index.js +2 -2
  14. package/dist_ts/interfaces.d.ts +42 -0
  15. package/dist_ts/interfaces.flexharness.d.ts +8 -0
  16. package/dist_ts/interfaces.js +1 -1
  17. package/dist_ts/utils.json.d.ts +21 -1
  18. package/dist_ts/utils.json.js +432 -191
  19. package/dist_ts/utils.projectionchange.d.ts +12 -2
  20. package/dist_ts/utils.projectionchange.js +41 -22
  21. package/dist_ts/utils.transfer.d.ts +15 -1
  22. package/dist_ts/utils.transfer.js +55 -7
  23. package/dist_ts/utils.validation.d.ts +3 -1
  24. package/dist_ts/utils.validation.js +19 -1
  25. package/package.json +3 -3
  26. package/readme.md +32 -4
  27. package/ts/00_commitinfo_data.ts +1 -1
  28. package/ts/classes.flexharness.core.ts +29 -20
  29. package/ts/classes.flexharness.projects.ts +57 -29
  30. package/ts/classes.flexharness.prompts.ts +4 -2
  31. package/ts/classes.flexharness.runs.ts +5 -2
  32. package/ts/classes.flexharness.sessions.ts +49 -19
  33. package/ts/classes.flexharness.ts +13 -0
  34. package/ts/index.ts +1 -0
  35. package/ts/interfaces.flexharness.ts +5 -0
  36. package/ts/interfaces.ts +59 -0
  37. package/ts/readme.md +32 -4
  38. package/ts/utils.json.ts +521 -198
  39. package/ts/utils.projectionchange.ts +62 -26
  40. package/ts/utils.transfer.ts +68 -6
  41. package/ts/utils.validation.ts +19 -0
package/ts/utils.json.ts CHANGED
@@ -11,10 +11,12 @@ import {
11
11
  } from './interfaces.js';
12
12
  import type {
13
13
  IFlexJsonLimits,
14
+ IFlexMessage,
14
15
  IFlexPermissionSnapshot,
15
16
  IFlexProjectionSnapshotV1,
16
17
  IFlexProjectionSnapshotV2,
17
18
  IFlexProjectionSnapshotV3,
19
+ IFlexReversionSegment,
18
20
  IFlexScopeSnapshot,
19
21
  IFlexSubagentProvenance,
20
22
  TFlexAgentModelMessage,
@@ -327,12 +329,15 @@ const ARRAY_INDEX_PATTERN = /^(0|[1-9]\d*)$/;
327
329
  /**
328
330
  * One walk over a value as JSON sees it. The path to the current value is kept as segments and only
329
331
  * formatted for an error, and `ancestors` holds the objects on that path to detect cycles.
332
+ * `knownEntries` names arrays whose first entries are already known to be JSON values: a walk that
333
+ * does not copy checks those entries are present but does not descend into them.
330
334
  */
331
335
  interface IJsonWalk {
332
336
  readonly root: string;
333
337
  readonly segments: Array<string | number>;
334
338
  readonly ancestors: object[];
335
339
  readonly copy: boolean;
340
+ readonly knownEntries?: ReadonlyMap<unknown, number>;
336
341
  }
337
342
 
338
343
  function failJsonWalk(walk: IJsonWalk, message: string): never {
@@ -390,11 +395,14 @@ function walkJsonValue(walk: IJsonWalk, value: unknown): unknown {
390
395
  }
391
396
  }
392
397
  const items: unknown[] | undefined = walk.copy ? [] : undefined;
398
+ const known = walk.knownEntries?.get(value) ?? 0;
393
399
  for (let index = 0; index < length; index++) {
394
400
  walk.segments.push(index);
395
401
  if (!(index in value)) failJsonWalk(walk, 'is a sparse array entry.');
396
- const item = walkJsonValue(walk, value[index]);
397
- items?.push(item);
402
+ if (index >= known) {
403
+ const item = walkJsonValue(walk, value[index]);
404
+ items?.push(item);
405
+ }
398
406
  walk.segments.pop();
399
407
  }
400
408
  copy = items;
@@ -1231,6 +1239,54 @@ interface IValidatedProjectionBody {
1231
1239
  stagedMessages: IValidatedMessageIdentity[];
1232
1240
  }
1233
1241
 
1242
+ interface IValidatedStagedTerminal {
1243
+ runId: string;
1244
+ user?: IValidatedMessageIdentity;
1245
+ assistant: IValidatedMessageIdentity;
1246
+ }
1247
+
1248
+ const stagedTerminalKeys = [
1249
+ 'runId',
1250
+ 'status',
1251
+ 'userMessage',
1252
+ 'assistantMessage',
1253
+ 'model',
1254
+ 'usage',
1255
+ 'finishReason',
1256
+ 'steps',
1257
+ ];
1258
+
1259
+ /** One staged terminal by itself: its fields, and messages that belong to its run and status. */
1260
+ function validateStagedTerminal(value: unknown, path: string): IValidatedStagedTerminal {
1261
+ const terminal = requireRecord(value, path);
1262
+ requireOnlyKeys(terminal, stagedTerminalKeys, path);
1263
+ const runId = requireString(terminal.runId, `${path}.runId`);
1264
+ if (!['completed', 'failed', 'cancelled'].includes(String(terminal.status))) {
1265
+ throw new FlexHarnessStoreFormatError(`${path}.status is invalid.`);
1266
+ }
1267
+ const user = terminal.userMessage === undefined
1268
+ ? undefined
1269
+ : validateMessage(terminal.userMessage, `${path}.userMessage`);
1270
+ const assistant = validateMessage(terminal.assistantMessage, `${path}.assistantMessage`);
1271
+ if ((user && user.role !== 'user') || assistant.role !== 'assistant') {
1272
+ throw new FlexHarnessStoreFormatError(`${path} has invalid terminal message roles.`);
1273
+ }
1274
+ if ((user && (user.runId !== runId || user.sessionId !== assistant.sessionId)) || assistant.runId !== runId) {
1275
+ throw new FlexHarnessStoreFormatError(`${path} has uncorrelated terminal messages.`);
1276
+ }
1277
+ if (assistant.status !== terminal.status) {
1278
+ throw new FlexHarnessStoreFormatError(`${path}.status does not match its assistant message.`);
1279
+ }
1280
+ if (user && user.status !== terminal.status) {
1281
+ throw new FlexHarnessStoreFormatError(`${path}.status does not match its user message.`);
1282
+ }
1283
+ if (terminal.model !== undefined) validateModel(terminal.model, `${path}.model`);
1284
+ if (terminal.usage !== undefined) validateUsage(terminal.usage, `${path}.usage`);
1285
+ requireOptionalString(terminal.finishReason, `${path}.finishReason`);
1286
+ if (terminal.steps !== undefined) requireNonNegativeInteger(terminal.steps, `${path}.steps`);
1287
+ return { runId, ...(user ? { user } : {}), assistant };
1288
+ }
1289
+
1234
1290
  function validateProjectionBody(snapshot: Record<string, unknown>): IValidatedProjectionBody {
1235
1291
  const visibleMessages = validateMessages(snapshot.messages, '$snapshot.messages');
1236
1292
  let projectionSessionId = visibleMessages[0]?.sessionId;
@@ -1245,49 +1301,15 @@ function validateProjectionBody(snapshot: Record<string, unknown>): IValidatedPr
1245
1301
  const stagedMessages: IValidatedMessageIdentity[] = [];
1246
1302
  for (let index = 0; index < snapshot.stagedTerminals.length; index++) {
1247
1303
  const path = `$snapshot.stagedTerminals[${index}]`;
1248
- const terminal = requireRecord(snapshot.stagedTerminals[index], path);
1249
- requireOnlyKeys(
1250
- terminal,
1251
- [
1252
- 'runId',
1253
- 'status',
1254
- 'userMessage',
1255
- 'assistantMessage',
1256
- 'model',
1257
- 'usage',
1258
- 'finishReason',
1259
- 'steps',
1260
- ],
1261
- path,
1262
- );
1263
- const runId = requireString(terminal.runId, `${path}.runId`);
1304
+ const { runId, user, assistant } = validateStagedTerminal(snapshot.stagedTerminals[index], path);
1264
1305
  if (runIds.has(runId)) {
1265
1306
  throw new FlexHarnessStoreFormatError(`Snapshot contains duplicate staged run "${runId}".`);
1266
1307
  }
1267
1308
  runIds.add(runId);
1268
- if (!['completed', 'failed', 'cancelled'].includes(String(terminal.status))) {
1269
- throw new FlexHarnessStoreFormatError(`${path}.status is invalid.`);
1270
- }
1271
- const user = terminal.userMessage === undefined
1272
- ? undefined
1273
- : validateMessage(terminal.userMessage, `${path}.userMessage`);
1274
- const assistant = validateMessage(terminal.assistantMessage, `${path}.assistantMessage`);
1275
- if ((user && user.role !== 'user') || assistant.role !== 'assistant') {
1276
- throw new FlexHarnessStoreFormatError(`${path} has invalid terminal message roles.`);
1277
- }
1278
- if ((user && (user.runId !== runId || user.sessionId !== assistant.sessionId)) || assistant.runId !== runId) {
1279
- throw new FlexHarnessStoreFormatError(`${path} has uncorrelated terminal messages.`);
1280
- }
1281
- if (assistant.status !== terminal.status) {
1282
- throw new FlexHarnessStoreFormatError(`${path}.status does not match its assistant message.`);
1283
- }
1284
1309
  if (!user && visibleMessages.some((message) =>
1285
1310
  message.runId === runId && message.role === 'user' && message.steerId === undefined)) {
1286
1311
  throw new FlexHarnessStoreFormatError(`${path} omits its projected prompt message.`);
1287
1312
  }
1288
- if (user && user.status !== terminal.status) {
1289
- throw new FlexHarnessStoreFormatError(`${path}.status does not match its user message.`);
1290
- }
1291
1313
  if (user) stagedMessages.push(user);
1292
1314
  stagedMessages.push(assistant);
1293
1315
  projectionSessionId ??= assistant.sessionId;
@@ -1302,10 +1324,6 @@ function validateProjectionBody(snapshot: Record<string, unknown>): IValidatedPr
1302
1324
  }
1303
1325
  stagedMessageIds.add(messageId);
1304
1326
  }
1305
- if (terminal.model !== undefined) validateModel(terminal.model, `${path}.model`);
1306
- if (terminal.usage !== undefined) validateUsage(terminal.usage, `${path}.usage`);
1307
- requireOptionalString(terminal.finishReason, `${path}.finishReason`);
1308
- if (terminal.steps !== undefined) requireNonNegativeInteger(terminal.steps, `${path}.steps`);
1309
1327
  }
1310
1328
  return { messages: visibleMessages, stagedMessages };
1311
1329
  }
@@ -1682,134 +1700,433 @@ const sessionMetricsBreakdownKeys = [
1682
1700
  'lifetimeTokenBreakdownComplete',
1683
1701
  ];
1684
1702
 
1685
- export function assertFlexProjectionSnapshotV3(
1686
- value: unknown,
1687
- ): asserts value is IFlexProjectionSnapshotV3 {
1688
- assertJsonSerializable(value, '$snapshot');
1689
- const snapshot = requireRecord(value, '$snapshot');
1690
- requireOnlyKeys(snapshot, [
1691
- 'schemaVersion',
1692
- 'revision',
1693
- 'metrics',
1694
- 'messages',
1695
- 'stagedTerminals',
1696
- 'reversionSegments',
1697
- 'revertCursor',
1698
- 'excludedRunIds',
1699
- 'pendingReversion',
1700
- 'pendingReversionReleases',
1701
- ], '$snapshot');
1702
- if (Object.hasOwn(snapshot, 'metrics')) assertSessionMetrics(snapshot.metrics);
1703
- if (snapshot.schemaVersion !== 3) {
1704
- throw new FlexHarnessStoreFormatError('Projection snapshot schemaVersion must be 3.');
1703
+ const projectionSnapshotKeys = [
1704
+ 'schemaVersion',
1705
+ 'revision',
1706
+ 'metrics',
1707
+ 'messages',
1708
+ 'stagedTerminals',
1709
+ 'reversionSegments',
1710
+ 'revertCursor',
1711
+ 'excludedRunIds',
1712
+ 'pendingReversion',
1713
+ 'pendingReversionReleases',
1714
+ ];
1715
+
1716
+ const reversionSegmentKeys = [
1717
+ 'runId',
1718
+ 'userMessageId',
1719
+ 'status',
1720
+ 'contextAvailable',
1721
+ 'eventIds',
1722
+ 'workspaceCaptured',
1723
+ 'captureId',
1724
+ 'workspaceReference',
1725
+ 'protocolVersion',
1726
+ 'provenance',
1727
+ 'disposition',
1728
+ 'affectedWorkspaces',
1729
+ 'reasonCode',
1730
+ ];
1731
+
1732
+ /**
1733
+ * One schema-3 reversion segment by itself: its fields and the workspace ownership its
1734
+ * provenance, status and disposition allow.
1735
+ */
1736
+ function validateReversionSegment(value: unknown, path: string): void {
1737
+ const segment = requireRecord(value, path);
1738
+ requireOnlyKeys(segment, reversionSegmentKeys, path);
1739
+ requireString(segment.runId, `${path}.runId`);
1740
+ requireOptionalString(segment.userMessageId, `${path}.userMessageId`);
1741
+ const status = String(segment.status);
1742
+ if (!['capturing', 'completed', 'failed', 'cancelled'].includes(status)) {
1743
+ throw new FlexHarnessStoreFormatError(`${path}.status is invalid.`);
1705
1744
  }
1706
- if (!Array.isArray(snapshot.reversionSegments)) {
1707
- throw new FlexHarnessStoreFormatError('Snapshot reversionSegments must be an array.');
1745
+ if (typeof segment.contextAvailable !== 'boolean') {
1746
+ throw new FlexHarnessStoreFormatError(`${path}.contextAvailable must be a boolean.`);
1708
1747
  }
1709
- const retainedCaptureIds = new Set<string>();
1710
- for (let index = 0; index < snapshot.reversionSegments.length; index++) {
1711
- const path = `$snapshot.reversionSegments[${index}]`;
1712
- const segment = requireRecord(snapshot.reversionSegments[index], path);
1713
- requireOnlyKeys(segment, [
1714
- 'runId',
1715
- 'userMessageId',
1716
- 'status',
1717
- 'contextAvailable',
1718
- 'eventIds',
1719
- 'workspaceCaptured',
1720
- 'captureId',
1721
- 'workspaceReference',
1722
- 'protocolVersion',
1723
- 'provenance',
1724
- 'disposition',
1725
- 'affectedWorkspaces',
1726
- 'reasonCode',
1727
- ], path);
1728
- const protocolVersion = segment.protocolVersion;
1729
- if (protocolVersion !== 1 && protocolVersion !== 2) {
1730
- throw new FlexHarnessStoreFormatError(`${path}.protocolVersion is invalid.`);
1748
+ const eventIds = requireStringArray(segment.eventIds, `${path}.eventIds`);
1749
+ if (eventIds.some((id) => !id) || new Set(eventIds).size !== eventIds.length) {
1750
+ throw new FlexHarnessStoreFormatError(`${path}.eventIds is invalid.`);
1751
+ }
1752
+ const captureId = requireOptionalString(segment.captureId, `${path}.captureId`);
1753
+ if (
1754
+ segment.workspaceReference !== undefined
1755
+ && Buffer.byteLength(JSON.stringify(segment.workspaceReference)) > FLEX_REVERSION_REFERENCE_MAX_BYTES
1756
+ ) {
1757
+ throw new FlexHarnessStoreFormatError(`${path}.workspaceReference exceeds its byte limit.`);
1758
+ }
1759
+ const protocolVersion = segment.protocolVersion;
1760
+ if (protocolVersion !== 1 && protocolVersion !== 2) {
1761
+ throw new FlexHarnessStoreFormatError(`${path}.protocolVersion is invalid.`);
1762
+ }
1763
+ if (segment.provenance !== 'transcript' && segment.provenance !== 'workspace') {
1764
+ throw new FlexHarnessStoreFormatError(`${path}.provenance is invalid.`);
1765
+ }
1766
+ if (segment.workspaceCaptured !== (segment.provenance === 'workspace')) {
1767
+ throw new FlexHarnessStoreFormatError(`${path}.workspaceCaptured does not match its provenance.`);
1768
+ }
1769
+ if (protocolVersion === 2 && segment.provenance !== 'workspace') {
1770
+ throw new FlexHarnessStoreFormatError(`${path} uses protocol 2 without workspace provenance.`);
1771
+ }
1772
+ if (protocolVersion === 1 && segment.affectedWorkspaces !== undefined) {
1773
+ throw new FlexHarnessStoreFormatError(`${path} protocol 1 contains affected workspace metadata.`);
1774
+ }
1775
+ const disposition = segment.disposition;
1776
+ if (segment.affectedWorkspaces !== undefined) {
1777
+ validateAffectedWorkspaces(segment.affectedWorkspaces, `${path}.affectedWorkspaces`);
1778
+ }
1779
+ if (segment.reasonCode !== undefined) {
1780
+ const reasonCode = requireBoundedString(
1781
+ segment.reasonCode,
1782
+ `${path}.reasonCode`,
1783
+ FLEX_REVERSION_REASON_CODE_MAX_BYTES,
1784
+ );
1785
+ if (!/^[A-Za-z0-9][A-Za-z0-9._-]*$/u.test(reasonCode)) {
1786
+ throw new FlexHarnessStoreFormatError(`${path}.reasonCode is invalid.`);
1787
+ }
1788
+ }
1789
+ if (segment.provenance === 'transcript') {
1790
+ if (
1791
+ disposition !== undefined
1792
+ || captureId !== undefined
1793
+ || segment.workspaceReference !== undefined
1794
+ || segment.affectedWorkspaces !== undefined
1795
+ || segment.reasonCode !== undefined
1796
+ ) throw new FlexHarnessStoreFormatError(`${path} transcript provenance contains workspace data.`);
1797
+ return;
1798
+ }
1799
+ if (status === 'capturing') {
1800
+ if (disposition !== 'pending' || captureId === undefined || segment.workspaceReference !== undefined) {
1801
+ throw new FlexHarnessStoreFormatError(`${path} has invalid pending workspace ownership.`);
1731
1802
  }
1732
- if (segment.provenance !== 'transcript' && segment.provenance !== 'workspace') {
1733
- throw new FlexHarnessStoreFormatError(`${path}.provenance is invalid.`);
1803
+ if (segment.affectedWorkspaces !== undefined || segment.reasonCode !== undefined) {
1804
+ throw new FlexHarnessStoreFormatError(`${path} pending workspace capture has terminal metadata.`);
1734
1805
  }
1735
- if (segment.workspaceCaptured !== (segment.provenance === 'workspace')) {
1736
- throw new FlexHarnessStoreFormatError(`${path}.workspaceCaptured does not match its provenance.`);
1806
+ return;
1807
+ }
1808
+ if (protocolVersion === 1 && disposition !== 'revertible') {
1809
+ throw new FlexHarnessStoreFormatError(`${path} terminal protocol-1 workspace capture is not revertible.`);
1810
+ }
1811
+ if (protocolVersion === 2 && !['revertible', 'no-change', 'nonrevertible'].includes(String(disposition))) {
1812
+ throw new FlexHarnessStoreFormatError(`${path} terminal protocol-2 capture lacks a conclusive disposition.`);
1813
+ }
1814
+ if (disposition === 'revertible') {
1815
+ if (captureId === undefined || segment.workspaceReference === undefined) {
1816
+ throw new FlexHarnessStoreFormatError(`${path} revertible capture lacks retained ownership.`);
1737
1817
  }
1738
- if (protocolVersion === 2 && segment.provenance !== 'workspace') {
1739
- throw new FlexHarnessStoreFormatError(`${path} uses protocol 2 without workspace provenance.`);
1818
+ if (protocolVersion === 2 && segment.affectedWorkspaces === undefined) {
1819
+ throw new FlexHarnessStoreFormatError(`${path} revertible protocol-2 capture lacks affected workspaces.`);
1740
1820
  }
1741
- if (protocolVersion === 1 && segment.affectedWorkspaces !== undefined) {
1742
- throw new FlexHarnessStoreFormatError(`${path} protocol 1 contains affected workspace metadata.`);
1821
+ if (segment.reasonCode !== undefined) {
1822
+ throw new FlexHarnessStoreFormatError(`${path} revertible capture has a reason code.`);
1743
1823
  }
1744
- const status = String(segment.status);
1745
- const disposition = segment.disposition;
1746
- const captureId = segment.captureId;
1747
- if (captureId !== undefined) retainedCaptureIds.add(String(captureId));
1748
- if (segment.affectedWorkspaces !== undefined) {
1749
- validateAffectedWorkspaces(segment.affectedWorkspaces, `${path}.affectedWorkspaces`);
1824
+ return;
1825
+ }
1826
+ if (captureId !== undefined || segment.workspaceReference !== undefined) {
1827
+ throw new FlexHarnessStoreFormatError(`${path} terminal disposition retains segment ownership.`);
1828
+ }
1829
+ if (disposition === 'no-change') {
1830
+ if (Array.isArray(segment.affectedWorkspaces) && segment.affectedWorkspaces.length > 0) {
1831
+ throw new FlexHarnessStoreFormatError(`${path} no-change capture affects a workspace.`);
1750
1832
  }
1751
1833
  if (segment.reasonCode !== undefined) {
1752
- const reasonCode = requireBoundedString(
1753
- segment.reasonCode,
1754
- `${path}.reasonCode`,
1755
- FLEX_REVERSION_REASON_CODE_MAX_BYTES,
1756
- );
1757
- if (!/^[A-Za-z0-9][A-Za-z0-9._-]*$/u.test(reasonCode)) {
1758
- throw new FlexHarnessStoreFormatError(`${path}.reasonCode is invalid.`);
1759
- }
1834
+ throw new FlexHarnessStoreFormatError(`${path} no-change capture has a reason code.`);
1760
1835
  }
1761
- if (segment.provenance === 'transcript') {
1762
- if (
1763
- disposition !== undefined
1764
- || captureId !== undefined
1765
- || segment.workspaceReference !== undefined
1766
- || segment.affectedWorkspaces !== undefined
1767
- || segment.reasonCode !== undefined
1768
- ) throw new FlexHarnessStoreFormatError(`${path} transcript provenance contains workspace data.`);
1769
- continue;
1770
- }
1771
- if (status === 'capturing') {
1772
- if (disposition !== 'pending' || captureId === undefined || segment.workspaceReference !== undefined) {
1773
- throw new FlexHarnessStoreFormatError(`${path} has invalid pending workspace ownership.`);
1774
- }
1775
- if (segment.affectedWorkspaces !== undefined || segment.reasonCode !== undefined) {
1776
- throw new FlexHarnessStoreFormatError(`${path} pending workspace capture has terminal metadata.`);
1777
- }
1778
- continue;
1836
+ }
1837
+ if (disposition === 'nonrevertible' && segment.reasonCode === undefined) {
1838
+ throw new FlexHarnessStoreFormatError(`${path} nonrevertible capture lacks a reason code.`);
1839
+ }
1840
+ }
1841
+
1842
+ /**
1843
+ * How many entries at the start of a schema-3 projection's two lists it kept from a projection
1844
+ * already validated for the same session.
1845
+ */
1846
+ export interface IKeptProjectionEntries {
1847
+ readonly messages: number;
1848
+ readonly reversionSegments: number;
1849
+ }
1850
+
1851
+ const noKeptProjectionEntries: IKeptProjectionEntries = Object.freeze({ messages: 0, reversionSegments: 0 });
1852
+
1853
+ /** The identities of a projection's messages that relate its entries to each other. */
1854
+ interface IProjectionMessageFacts {
1855
+ /** The session of every message: the one asked for, else the first message's. */
1856
+ sessionId?: string;
1857
+ visible: Map<string, IFlexMessage>;
1858
+ staged: Map<string, IValidatedMessageIdentity>;
1859
+ /** Runs whose prompt (a user message that is not a steer) is a visible message. */
1860
+ visiblePromptRunIds: Set<string>;
1861
+ /** Runs whose prompt is a staged message. */
1862
+ stagedPromptRunIds: Set<string>;
1863
+ /** Runs with an assistant message, visible or staged. */
1864
+ assistantRunIds: Set<string>;
1865
+ }
1866
+
1867
+ function requireProjectionSession(facts: IProjectionMessageFacts, messageSessionId: string, where: string): void {
1868
+ facts.sessionId ??= messageSessionId;
1869
+ if (messageSessionId !== facts.sessionId) {
1870
+ throw new FlexHarnessStoreFormatError(`${where} does not belong to session "${facts.sessionId}".`);
1871
+ }
1872
+ }
1873
+
1874
+ /**
1875
+ * Validates the visible messages after the `kept` first in full, then reads every message's
1876
+ * identity once: IDs are unique, all belong to one session, and the facts the staged terminals
1877
+ * and reversion segments are checked against.
1878
+ */
1879
+ function relateProjectionMessages(
1880
+ value: unknown,
1881
+ kept: number,
1882
+ sessionId: string | undefined,
1883
+ ): IProjectionMessageFacts {
1884
+ if (!Array.isArray(value)) {
1885
+ throw new FlexHarnessStoreFormatError('$snapshot.messages must be an array.');
1886
+ }
1887
+ for (let index = kept; index < value.length; index++) {
1888
+ validateMessage(value[index], `$snapshot.messages[${index}]`);
1889
+ }
1890
+ const facts: IProjectionMessageFacts = {
1891
+ ...(sessionId === undefined ? {} : { sessionId }),
1892
+ visible: new Map(),
1893
+ staged: new Map(),
1894
+ visiblePromptRunIds: new Set(),
1895
+ stagedPromptRunIds: new Set(),
1896
+ assistantRunIds: new Set(),
1897
+ };
1898
+ for (const message of value as IFlexMessage[]) {
1899
+ if (facts.visible.has(message.messageId)) {
1900
+ throw new FlexHarnessStoreFormatError(`$snapshot.messages contains duplicate message "${message.messageId}".`);
1779
1901
  }
1780
- if (protocolVersion === 1 && disposition !== 'revertible') {
1781
- throw new FlexHarnessStoreFormatError(`${path} terminal protocol-1 workspace capture is not revertible.`);
1902
+ facts.visible.set(message.messageId, message);
1903
+ requireProjectionSession(facts, message.sessionId, `Projection message "${message.messageId}"`);
1904
+ if (message.role === 'assistant') facts.assistantRunIds.add(message.runId);
1905
+ else if (message.steerId === undefined) facts.visiblePromptRunIds.add(message.runId);
1906
+ }
1907
+ return facts;
1908
+ }
1909
+
1910
+ function relateStagedTerminals(value: unknown, facts: IProjectionMessageFacts): void {
1911
+ if (!Array.isArray(value)) {
1912
+ throw new FlexHarnessStoreFormatError('Snapshot stagedTerminals must be an array.');
1913
+ }
1914
+ const runIds = new Set<string>();
1915
+ for (let index = 0; index < value.length; index++) {
1916
+ const path = `$snapshot.stagedTerminals[${index}]`;
1917
+ const { runId, user, assistant } = validateStagedTerminal(value[index], path);
1918
+ if (runIds.has(runId)) {
1919
+ throw new FlexHarnessStoreFormatError(`Snapshot contains duplicate staged run "${runId}".`);
1782
1920
  }
1783
- if (protocolVersion === 2 && !['revertible', 'no-change', 'nonrevertible'].includes(String(disposition))) {
1784
- throw new FlexHarnessStoreFormatError(`${path} terminal protocol-2 capture lacks a conclusive disposition.`);
1921
+ runIds.add(runId);
1922
+ if (!user && facts.visiblePromptRunIds.has(runId)) {
1923
+ throw new FlexHarnessStoreFormatError(`${path} omits its projected prompt message.`);
1785
1924
  }
1786
- if (disposition === 'revertible') {
1787
- if (captureId === undefined || segment.workspaceReference === undefined) {
1788
- throw new FlexHarnessStoreFormatError(`${path} revertible capture lacks retained ownership.`);
1925
+ for (const message of user ? [user, assistant] : [assistant]) {
1926
+ requireProjectionSession(facts, message.sessionId, `Staged terminal "${runId}"`);
1927
+ if (facts.staged.has(message.messageId)) {
1928
+ throw new FlexHarnessStoreFormatError(
1929
+ `Snapshot staged terminals contain duplicate message "${message.messageId}".`,
1930
+ );
1789
1931
  }
1790
- if (protocolVersion === 2 && segment.affectedWorkspaces === undefined) {
1791
- throw new FlexHarnessStoreFormatError(`${path} revertible protocol-2 capture lacks affected workspaces.`);
1932
+ facts.staged.set(message.messageId, message);
1933
+ }
1934
+ if (user && user.steerId === undefined) facts.stagedPromptRunIds.add(runId);
1935
+ facts.assistantRunIds.add(runId);
1936
+ }
1937
+ }
1938
+
1939
+ /** The identities of a projection's reversion segments that the cursor and pending work refer to. */
1940
+ interface IReversionSegmentFacts {
1941
+ indexByRunId: Map<string, number>;
1942
+ /** Indexes of the completed segments, in order: the candidates the revert cursor counts. */
1943
+ completed: number[];
1944
+ /** Capture IDs the segments retain. */
1945
+ captureIds: Set<string>;
1946
+ /** Runs of capture-backed segments still capturing. */
1947
+ capturingRunIds: string[];
1948
+ }
1949
+
1950
+ /**
1951
+ * Validates the segments after the `kept` first in full, then reads every segment's identity
1952
+ * once: run, event and capture IDs are unique, and each segment matches its run's messages.
1953
+ */
1954
+ function relateReversionSegments(
1955
+ value: unknown,
1956
+ kept: number,
1957
+ messages: IProjectionMessageFacts,
1958
+ ): IReversionSegmentFacts {
1959
+ if (!Array.isArray(value)) {
1960
+ throw new FlexHarnessStoreFormatError('Snapshot reversionSegments must be an array.');
1961
+ }
1962
+ if (value.length > FLEX_REVERSION_MAXIMUM_LIMITS.maxSegments) {
1963
+ throw new FlexHarnessStoreFormatError('Snapshot reversionSegments exceeds its hard limit.');
1964
+ }
1965
+ for (let index = kept; index < value.length; index++) {
1966
+ validateReversionSegment(value[index], `$snapshot.reversionSegments[${index}]`);
1967
+ }
1968
+ const facts: IReversionSegmentFacts = {
1969
+ indexByRunId: new Map(),
1970
+ completed: [],
1971
+ captureIds: new Set(),
1972
+ capturingRunIds: [],
1973
+ };
1974
+ const eventIds = new Set<string>();
1975
+ for (let index = 0; index < value.length; index++) {
1976
+ const segment = value[index] as IFlexReversionSegment;
1977
+ const { runId, userMessageId, captureId } = segment;
1978
+ if (facts.indexByRunId.has(runId)) {
1979
+ throw new FlexHarnessStoreFormatError(`Snapshot contains duplicate reversion run "${runId}".`);
1980
+ }
1981
+ facts.indexByRunId.set(runId, index);
1982
+ for (const eventId of segment.eventIds) {
1983
+ if (eventIds.has(eventId)) {
1984
+ throw new FlexHarnessStoreFormatError(`Snapshot reuses reversion event "${eventId}".`);
1792
1985
  }
1793
- if (segment.reasonCode !== undefined) {
1794
- throw new FlexHarnessStoreFormatError(`${path} revertible capture has a reason code.`);
1986
+ eventIds.add(eventId);
1987
+ }
1988
+ if (captureId !== undefined) {
1989
+ if (facts.captureIds.has(captureId)) {
1990
+ throw new FlexHarnessStoreFormatError(`Snapshot contains duplicate capture "${captureId}".`);
1795
1991
  }
1796
- } else {
1797
- if (captureId !== undefined || segment.workspaceReference !== undefined) {
1798
- throw new FlexHarnessStoreFormatError(`${path} terminal disposition retains segment ownership.`);
1992
+ facts.captureIds.add(captureId);
1993
+ if (segment.status === 'capturing') facts.capturingRunIds.push(runId);
1994
+ }
1995
+ if (segment.status === 'completed') facts.completed.push(index);
1996
+ if (userMessageId === undefined) {
1997
+ // An assistant-only continuation: its run has no prompt and an assistant message.
1998
+ if (messages.visiblePromptRunIds.has(runId) || messages.stagedPromptRunIds.has(runId)) {
1999
+ throw new FlexHarnessStoreFormatError(
2000
+ `$snapshot.reversionSegments[${index}] omits its projected prompt identity.`,
2001
+ );
1799
2002
  }
1800
- if (disposition === 'no-change') {
1801
- if (Array.isArray(segment.affectedWorkspaces) && segment.affectedWorkspaces.length > 0) {
1802
- throw new FlexHarnessStoreFormatError(`${path} no-change capture affects a workspace.`);
1803
- }
1804
- if (segment.reasonCode !== undefined) {
1805
- throw new FlexHarnessStoreFormatError(`${path} no-change capture has a reason code.`);
1806
- }
2003
+ if (!messages.assistantRunIds.has(runId)) {
2004
+ throw new FlexHarnessStoreFormatError(
2005
+ `$snapshot.reversionSegments[${index}] does not match its projected turn messages.`,
2006
+ );
1807
2007
  }
1808
- if (disposition === 'nonrevertible' && segment.reasonCode === undefined) {
1809
- throw new FlexHarnessStoreFormatError(`${path} nonrevertible capture lacks a reason code.`);
2008
+ } else {
2009
+ const visible = messages.visible.get(userMessageId);
2010
+ const staged = messages.staged.get(userMessageId);
2011
+ if (
2012
+ !(visible?.runId === runId && visible.role === 'user')
2013
+ && !(staged?.runId === runId && staged.role === 'user')
2014
+ ) {
2015
+ throw new FlexHarnessStoreFormatError(
2016
+ `$snapshot.reversionSegments[${index}] does not match its projected turn messages.`,
2017
+ );
1810
2018
  }
1811
2019
  }
1812
2020
  }
2021
+ return facts;
2022
+ }
2023
+
2024
+ /** Checks a pending apply against the segments: it moves the cursor by one unit, applied in order. */
2025
+ function validatePendingApply(
2026
+ pending: Record<string, unknown>,
2027
+ revertCursor: number,
2028
+ segments: readonly IFlexReversionSegment[],
2029
+ facts: IReversionSegmentFacts,
2030
+ ): void {
2031
+ // Schema-2 snapshots had no protocolVersion; the one a schema-3 apply carries is not read.
2032
+ requireOnlyKeys(pending, [
2033
+ 'kind',
2034
+ 'operationId',
2035
+ 'direction',
2036
+ 'fromCursor',
2037
+ 'toCursor',
2038
+ 'segmentRunIds',
2039
+ 'appliedRunIds',
2040
+ 'protocolVersion',
2041
+ ], '$snapshot.pendingReversion');
2042
+ requireString(pending.operationId, '$snapshot.pendingReversion.operationId');
2043
+ if (!['undo', 'redo'].includes(String(pending.direction))) {
2044
+ throw new FlexHarnessStoreFormatError('Snapshot pending apply direction is invalid.');
2045
+ }
2046
+ requireNonNegativeInteger(pending.fromCursor, '$snapshot.pendingReversion.fromCursor');
2047
+ requireNonNegativeInteger(pending.toCursor, '$snapshot.pendingReversion.toCursor');
2048
+ const pendingRuns = requireStringArray(pending.segmentRunIds, '$snapshot.pendingReversion.segmentRunIds');
2049
+ const appliedRuns = requireStringArray(pending.appliedRunIds, '$snapshot.pendingReversion.appliedRunIds');
2050
+ if (new Set(pendingRuns).size !== pendingRuns.length || new Set(appliedRuns).size !== appliedRuns.length) {
2051
+ throw new FlexHarnessStoreFormatError('Snapshot pending apply run IDs are invalid.');
2052
+ }
2053
+ if (appliedRuns.some((runId) => !pendingRuns.includes(runId))) {
2054
+ throw new FlexHarnessStoreFormatError('Snapshot pending apply progress is invalid.');
2055
+ }
2056
+ const fromCursor = Number(pending.fromCursor);
2057
+ const toCursor = Number(pending.toCursor);
2058
+ const direction = pending.direction as 'undo' | 'redo';
2059
+ if (
2060
+ fromCursor !== revertCursor
2061
+ || (direction === 'undo' && !(toCursor >= 0 && toCursor < fromCursor))
2062
+ || (direction === 'redo' && !(toCursor > fromCursor && toCursor <= facts.completed.length))
2063
+ ) {
2064
+ throw new FlexHarnessStoreFormatError('Snapshot pending apply cursor movement is invalid.');
2065
+ }
2066
+ const rangeStart = Math.min(fromCursor, toCursor);
2067
+ const rangeEnd = Math.max(fromCursor, toCursor);
2068
+ const first = facts.completed[rangeStart];
2069
+ if (first === undefined) {
2070
+ throw new FlexHarnessStoreFormatError('Snapshot pending apply has no target candidate.');
2071
+ }
2072
+ // The unit runs from the first candidate it moves over, or the history's start, up to the
2073
+ // next candidate it leaves in place, or the history's end.
2074
+ const start = rangeStart === 0 ? 0 : first;
2075
+ const end = facts.completed[rangeEnd] ?? segments.length;
2076
+ const exactRuns = segments.slice(start, end).map((segment) => segment.runId);
2077
+ if (pendingRuns.length !== exactRuns.length || pendingRuns.some((runId, index) => runId !== exactRuns[index])) {
2078
+ throw new FlexHarnessStoreFormatError('Snapshot pending apply segment unit is invalid.');
2079
+ }
2080
+ const applyOrder = direction === 'undo' ? [...exactRuns].reverse() : exactRuns;
2081
+ if (appliedRuns.some((runId, index) => runId !== applyOrder[index])) {
2082
+ throw new FlexHarnessStoreFormatError('Snapshot pending apply progress is out of order.');
2083
+ }
2084
+ }
2085
+
2086
+ /**
2087
+ * Validates a schema-3 projection whose lists start with `kept` entries of a projection already
2088
+ * validated for the same session (`sessionId`, or the one its messages share) and unchanged
2089
+ * since. Those entries are read only for the identities that relate entries to each other, in
2090
+ * one pass over every entry; everything else is checked in full. With nothing kept it is the
2091
+ * full validation of a schema-3 projection.
2092
+ */
2093
+ export function assertProjectionSnapshotEntries(
2094
+ value: unknown,
2095
+ kept: IKeptProjectionEntries,
2096
+ sessionId: string | undefined,
2097
+ ): asserts value is IFlexProjectionSnapshotV3 {
2098
+ const snapshot = requireRecord(value, '$snapshot');
2099
+ const knownEntries = new Map<unknown, number>();
2100
+ if (kept.messages > 0) knownEntries.set(snapshot.messages, kept.messages);
2101
+ if (kept.reversionSegments > 0) knownEntries.set(snapshot.reversionSegments, kept.reversionSegments);
2102
+ walkJsonValue({ root: '$snapshot', segments: [], ancestors: [], copy: false, knownEntries }, snapshot);
2103
+ requireOnlyKeys(snapshot, projectionSnapshotKeys, '$snapshot');
2104
+ if (snapshot.schemaVersion !== 3) {
2105
+ throw new FlexHarnessStoreFormatError('Projection snapshot schemaVersion must be 3.');
2106
+ }
2107
+ requireNonNegativeInteger(snapshot.revision, 'Snapshot revision');
2108
+ if (Object.hasOwn(snapshot, 'metrics')) assertSessionMetrics(snapshot.metrics);
2109
+ const messages = relateProjectionMessages(snapshot.messages, kept.messages, sessionId);
2110
+ relateStagedTerminals(snapshot.stagedTerminals, messages);
2111
+ const segmentList = snapshot.reversionSegments as IFlexReversionSegment[];
2112
+ const segments = relateReversionSegments(segmentList, kept.reversionSegments, messages);
2113
+ requireNonNegativeInteger(snapshot.revertCursor, '$snapshot.revertCursor');
2114
+ if (segments.completed.length > FLEX_REVERSION_MAXIMUM_LIMITS.maxCompletedTurns) {
2115
+ throw new FlexHarnessStoreFormatError('Snapshot completed reversion turns exceed their hard limit.');
2116
+ }
2117
+ const revertCursor = Number(snapshot.revertCursor);
2118
+ if (revertCursor > segments.completed.length) {
2119
+ throw new FlexHarnessStoreFormatError('Snapshot revertCursor exceeds its candidate count.');
2120
+ }
2121
+ const excludedRunIds = requireStringArray(snapshot.excludedRunIds, '$snapshot.excludedRunIds');
2122
+ if (
2123
+ excludedRunIds.some((id) => !id)
2124
+ || new Set(excludedRunIds).size !== excludedRunIds.length
2125
+ ) throw new FlexHarnessStoreFormatError('Snapshot excludedRunIds is invalid.');
2126
+ if (excludedRunIds.length > FLEX_REVERSION_MAXIMUM_LIMITS.maxExcludedRunIds) {
2127
+ throw new FlexHarnessStoreFormatError('Snapshot excludedRunIds exceeds its hard limit.');
2128
+ }
2129
+ let captureOwnerRunId: string | undefined;
1813
2130
  if (snapshot.pendingReversion !== undefined) {
1814
2131
  const pending = requireRecord(snapshot.pendingReversion, '$snapshot.pendingReversion');
1815
2132
  if (pending.kind === 'capture') {
@@ -1818,74 +2135,76 @@ export function assertFlexProjectionSnapshotV3(
1818
2135
  ['kind', 'runId', 'captureId', 'state', 'protocolVersion'],
1819
2136
  '$snapshot.pendingReversion',
1820
2137
  );
2138
+ const runId = requireString(pending.runId, '$snapshot.pendingReversion.runId');
2139
+ requireString(pending.captureId, '$snapshot.pendingReversion.captureId');
2140
+ if (!['preparing', 'prepared', 'finalizing'].includes(String(pending.state))) {
2141
+ throw new FlexHarnessStoreFormatError('Snapshot pending capture state is invalid.');
2142
+ }
1821
2143
  if (pending.protocolVersion !== 1 && pending.protocolVersion !== 2) {
1822
2144
  throw new FlexHarnessStoreFormatError('$snapshot.pendingReversion.protocolVersion is invalid.');
1823
2145
  }
1824
- const matching = snapshot.reversionSegments.filter((entry) => {
1825
- const segment = entry as Record<string, unknown>;
1826
- return segment.runId === pending.runId
1827
- && segment.captureId === pending.captureId
1828
- && segment.protocolVersion === pending.protocolVersion
1829
- && segment.status === 'capturing'
1830
- && segment.disposition === 'pending';
1831
- });
1832
- if (matching.length !== 1) {
2146
+ const index = segments.indexByRunId.get(runId);
2147
+ const segment = index === undefined ? undefined : segmentList[index];
2148
+ if (
2149
+ segment === undefined
2150
+ || segment.captureId !== pending.captureId
2151
+ || segment.protocolVersion !== pending.protocolVersion
2152
+ || segment.status !== 'capturing'
2153
+ || segment.disposition !== 'pending'
2154
+ ) {
1833
2155
  throw new FlexHarnessStoreFormatError('Snapshot pending capture does not match exactly one segment.');
1834
2156
  }
2157
+ captureOwnerRunId = runId;
2158
+ } else if (pending.kind === 'apply') {
2159
+ validatePendingApply(pending, revertCursor, segmentList, segments);
2160
+ } else {
2161
+ throw new FlexHarnessStoreFormatError('Snapshot pendingReversion kind is invalid.');
1835
2162
  }
1836
2163
  }
1837
- if (!Array.isArray(snapshot.pendingReversionReleases)) {
2164
+ if (segments.capturingRunIds.some((runId) => runId !== captureOwnerRunId)) {
2165
+ throw new FlexHarnessStoreFormatError(
2166
+ 'Snapshot contains a capture-backed capturing segment without exact pending ownership.',
2167
+ );
2168
+ }
2169
+ const releases = snapshot.pendingReversionReleases;
2170
+ if (!Array.isArray(releases)) {
1838
2171
  throw new FlexHarnessStoreFormatError('Snapshot pendingReversionReleases must be an array.');
1839
2172
  }
2173
+ if (releases.length > FLEX_REVERSION_MAXIMUM_LIMITS.maxPendingReversionReleases) {
2174
+ throw new FlexHarnessStoreFormatError('Snapshot pending reversion releases exceed their hard limit.');
2175
+ }
1840
2176
  const releaseCaptureIds = new Set<string>();
1841
- for (let index = 0; index < snapshot.pendingReversionReleases.length; index++) {
2177
+ for (let index = 0; index < releases.length; index++) {
1842
2178
  const path = `$snapshot.pendingReversionReleases[${index}]`;
1843
- const release = requireRecord(snapshot.pendingReversionReleases[index], path);
2179
+ const release = requireRecord(releases[index], path);
1844
2180
  requireOnlyKeys(release, ['runId', 'captureId', 'reference', 'protocolVersion'], path);
2181
+ requireString(release.runId, `${path}.runId`);
1845
2182
  const captureId = requireString(release.captureId, `${path}.captureId`);
1846
2183
  if (release.protocolVersion !== 1 && release.protocolVersion !== 2) {
1847
2184
  throw new FlexHarnessStoreFormatError(`${path}.protocolVersion is invalid.`);
1848
2185
  }
1849
- if (releaseCaptureIds.has(captureId) || retainedCaptureIds.has(captureId)) {
2186
+ if (releaseCaptureIds.has(captureId) || segments.captureIds.has(captureId)) {
1850
2187
  throw new FlexHarnessStoreFormatError(`${path} has duplicate durable capture ownership.`);
1851
2188
  }
1852
2189
  releaseCaptureIds.add(captureId);
2190
+ if (!Object.prototype.hasOwnProperty.call(release, 'reference')) {
2191
+ throw new FlexHarnessStoreFormatError(`${path}.reference is required.`);
2192
+ }
2193
+ if (Buffer.byteLength(JSON.stringify(release.reference)) > FLEX_REVERSION_REFERENCE_MAX_BYTES) {
2194
+ throw new FlexHarnessStoreFormatError(`${path}.reference exceeds its byte limit.`);
2195
+ }
1853
2196
  }
1854
- const { metrics: _metrics, ...compatibleSnapshot } = snapshot;
1855
- const compatibleV2 = {
1856
- ...compatibleSnapshot,
1857
- schemaVersion: 2,
1858
- reversionSegments: snapshot.reversionSegments.map((entry) => {
1859
- const segment = entry as Record<string, unknown>;
1860
- return {
1861
- runId: segment.runId,
1862
- ...(segment.userMessageId === undefined ? {} : { userMessageId: segment.userMessageId }),
1863
- status: segment.status,
1864
- contextAvailable: segment.contextAvailable,
1865
- eventIds: segment.eventIds,
1866
- workspaceCaptured: segment.provenance === 'workspace'
1867
- && (segment.status === 'capturing' || segment.disposition === 'revertible'),
1868
- ...(segment.captureId === undefined ? {} : { captureId: segment.captureId }),
1869
- ...(segment.workspaceReference === undefined
1870
- ? {}
1871
- : { workspaceReference: segment.workspaceReference }),
1872
- };
1873
- }),
1874
- ...(snapshot.pendingReversion === undefined
1875
- ? {}
1876
- : {
1877
- pendingReversion: (() => {
1878
- const { protocolVersion: _protocolVersion, ...pending } = snapshot.pendingReversion as
1879
- Record<string, unknown>;
1880
- return pending;
1881
- })(),
1882
- }),
1883
- pendingReversionReleases: snapshot.pendingReversionReleases.map((entry) => {
1884
- const { protocolVersion: _protocolVersion, ...release } = entry as Record<string, unknown>;
1885
- return release;
1886
- }),
1887
- };
1888
- assertFlexProjectionSnapshotV2(compatibleV2);
2197
+ }
2198
+
2199
+ /**
2200
+ * Validates a schema-3 projection snapshot. With `sessionId`, every message and staged terminal
2201
+ * must belong to that session; without, they must share one.
2202
+ */
2203
+ export function assertFlexProjectionSnapshotV3(
2204
+ value: unknown,
2205
+ sessionId?: string,
2206
+ ): asserts value is IFlexProjectionSnapshotV3 {
2207
+ assertProjectionSnapshotEntries(value, noKeptProjectionEntries, sessionId);
1889
2208
  }
1890
2209
 
1891
2210
  /**
@@ -1900,12 +2219,16 @@ export function assertFlexProjectionSnapshot(
1900
2219
  const record = requireRecord(value, '$snapshot');
1901
2220
  if (record.schemaVersion === 1) assertFlexProjectionSnapshotV1(value);
1902
2221
  else if (record.schemaVersion === 2) assertFlexProjectionSnapshotV2(value);
1903
- else assertFlexProjectionSnapshotV3(value);
2222
+ else {
2223
+ assertFlexProjectionSnapshotV3(value, sessionId);
2224
+ return;
2225
+ }
1904
2226
  if (sessionId !== undefined) assertProjectionSession(value, sessionId);
1905
2227
  }
1906
2228
 
2229
+ /** Requires every message and staged terminal of a schema-1 or schema-2 projection to belong to `sessionId`. */
1907
2230
  function assertProjectionSession(
1908
- snapshot: IFlexProjectionSnapshotV1 | IFlexProjectionSnapshotV2 | IFlexProjectionSnapshotV3,
2231
+ snapshot: IFlexProjectionSnapshotV1 | IFlexProjectionSnapshotV2,
1909
2232
  sessionId: string,
1910
2233
  ): void {
1911
2234
  for (const message of snapshot.messages) {