@gate-forge/witness 0.13.10 → 0.15.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 (54) hide show
  1. package/dist/adapter/contract-suite.d.ts.map +1 -1
  2. package/dist/adapter/contract-suite.js +2 -8
  3. package/dist/adapter/contract-suite.js.map +1 -1
  4. package/dist/client/witness-client.d.ts +1 -6
  5. package/dist/client/witness-client.d.ts.map +1 -1
  6. package/dist/client/witness-client.js +0 -7
  7. package/dist/client/witness-client.js.map +1 -1
  8. package/dist/constants.d.ts +35 -12
  9. package/dist/constants.d.ts.map +1 -1
  10. package/dist/constants.js +35 -12
  11. package/dist/constants.js.map +1 -1
  12. package/dist/json.d.ts +2 -0
  13. package/dist/json.d.ts.map +1 -1
  14. package/dist/json.js +4 -0
  15. package/dist/json.js.map +1 -1
  16. package/dist/witness/api-settlement.d.ts +2 -0
  17. package/dist/witness/api-settlement.d.ts.map +1 -1
  18. package/dist/witness/api-settlement.js +2 -0
  19. package/dist/witness/api-settlement.js.map +1 -1
  20. package/dist/witness/bin.d.ts.map +1 -1
  21. package/dist/witness/bin.js +48 -1
  22. package/dist/witness/bin.js.map +1 -1
  23. package/dist/witness/browser.d.ts +8 -1
  24. package/dist/witness/browser.d.ts.map +1 -1
  25. package/dist/witness/browser.js +15 -3
  26. package/dist/witness/browser.js.map +1 -1
  27. package/dist/witness/openapi-at-bind.d.ts +48 -0
  28. package/dist/witness/openapi-at-bind.d.ts.map +1 -0
  29. package/dist/witness/openapi-at-bind.js +91 -0
  30. package/dist/witness/openapi-at-bind.js.map +1 -0
  31. package/dist/witness/page-observation.d.ts +1 -0
  32. package/dist/witness/page-observation.d.ts.map +1 -1
  33. package/dist/witness/page-observation.js.map +1 -1
  34. package/dist/witness/page-observer-registration.d.ts +12 -0
  35. package/dist/witness/page-observer-registration.d.ts.map +1 -1
  36. package/dist/witness/page-observer-registration.js +5 -1
  37. package/dist/witness/page-observer-registration.js.map +1 -1
  38. package/dist/witness/page-observer.d.ts.map +1 -1
  39. package/dist/witness/page-observer.js +1 -0
  40. package/dist/witness/page-observer.js.map +1 -1
  41. package/dist/witness/response-shape.d.ts +88 -0
  42. package/dist/witness/response-shape.d.ts.map +1 -0
  43. package/dist/witness/response-shape.js +146 -0
  44. package/dist/witness/response-shape.js.map +1 -0
  45. package/dist/witness/run-options.d.ts +13 -0
  46. package/dist/witness/run-options.d.ts.map +1 -1
  47. package/dist/witness/run-options.js +26 -0
  48. package/dist/witness/run-options.js.map +1 -1
  49. package/dist/witness/server.d.ts.map +1 -1
  50. package/dist/witness/server.js +407 -130
  51. package/dist/witness/server.js.map +1 -1
  52. package/dist/witness/types.d.ts +42 -36
  53. package/dist/witness/types.d.ts.map +1 -1
  54. package/package.json +4 -2
@@ -152,9 +152,9 @@ import { createHash, randomUUID } from 'node:crypto';
152
152
  import { lookup } from 'node:dns/promises';
153
153
  import { readFileSync, renameSync, writeFileSync } from 'node:fs';
154
154
  import { join, resolve } from 'node:path';
155
- import { ATTESTATION_VERSION, attestationMac, behaviorActionDigestOf, DEFAULT_QUEUE_POLL_INTERVAL_MS, DEFAULT_QUEUE_TERMINAL_TIMEOUT_MS, BehaviorCatalogSchema, BEHAVIOR_CASE_KIND, enumerationDigestOf, interpretObservedPath, pathMatchesShape, recordIdOf, resolveHttpRoute, } from '@gate-forge/core';
155
+ import { ATTESTATION_VERSION, attestationMac, behaviorActionDigestOf, DEFAULT_QUEUE_POLL_INTERVAL_MS, DEFAULT_QUEUE_TERMINAL_TIMEOUT_MS, BehaviorCatalogSchema, BEHAVIOR_CASE_KIND, enumerationDigestOf, httpExchangeKind, interpretObservedPath, pathMatchesShape, recordIdOf, resolveHttpRoute, } from '@gate-forge/core';
156
156
  import { canonicalOf } from '../json.js';
157
- import { DEFAULT_REQUEST_TIMEOUT_MS, HTTP_OBSERVED_KIND, KNOWN_RECORD_KINDS, LOOPBACK_HOSTNAME, OBSERVED_EXCHANGES_CAP, OBSERVED_KIND, PERSISTENCE_KIND, RUN_HEADER, DIRECT_CHANNEL, DIRECT_EXCHANGES_CAP, VERIFIER_HEADER, } from '../constants.js';
157
+ import { DEFAULT_REQUEST_TIMEOUT_MS, HTTP_EXCHANGES_KIND, HTTP_OBSERVED_KIND, HTTP_OPENAPI_KIND, KNOWN_RECORD_KINDS, LOOPBACK_HOSTNAME, OBSERVED_EXCHANGES_CAP, OBSERVED_KIND, PERSISTENCE_KIND, RUN_HEADER, VERIFIER_HEADER, } from '../constants.js';
158
158
  import { PageObserverRegistrationError, registerPageObserver, sweepPageVisits } from './page-observer-registration.js';
159
159
  import { AdapterRegistryError, loadAdapters, makeAdapterContext } from './adapter-registry.js';
160
160
  import { AttestationError, assertLoopback, envFingerprintMismatch, probeEnvFingerprint, } from './env-attestation.js';
@@ -165,12 +165,15 @@ import { SURFACE_DESCRIPTOR_VERSION, validateSurface, } from '../surface.js';
165
165
  import { ChaosScheduler, chaosRouteKey } from './chaos.js';
166
166
  import { recordTwinShape } from './twin-shapes.js';
167
167
  import { assertNoStartedConflict, parseRunOptions, } from './run-options.js';
168
+ import { fetchOpenApiAtBind, openApiRecordPayload } from './openapi-at-bind.js';
169
+ import { RESPONSE_BODY_CAP_BYTES, buildResponseShapeIndex, judgeResponseShape, judgeEngineExchange, planResponseShape, shapeRank, } from './response-shape.js';
168
170
  import { validateScopeSnapshot } from './behavior.js';
169
171
  import { BEHAVIOR_BODY_LIMIT_BYTES, BehaviorDriverError, driveBehaviorRequest } from './behavior-request.js';
170
172
  import { OBSERVE_CHANNEL, OBSERVED_E2E_TEST_KIND, SERVER_CHANNEL, SERVER_E2E_TEST_KIND } from '../constants.js';
171
173
  import { QueueObserverError } from '../queue/observer.js';
172
174
  import { driveTaskDelivery, TaskDriverError } from './task.js';
173
- const MAX_BODY_BYTES = 1024 * 1024;
175
+ /** Supervisor JSON bodies (expected-set, behavior catalog, run context). */
176
+ const MAX_BODY_BYTES = 8 * 1024 * 1024;
174
177
  const OBLIGATION_ID_PATTERN = /^[^:]+:.+$/;
175
178
  /**
176
179
  * Bounded response snapshot the observation proxy keeps per forwarded
@@ -505,19 +508,21 @@ async function closeProxyListeners(servers) {
505
508
  })));
506
509
  }
507
510
  /**
508
- * Starts one loopback reverse proxy forwarding to the run's
509
- * attested proxy target. `sessionId` names the session the port belongs
510
- * to (null = the shared unattributed proxy): every exchange completing
511
- * on this port is recorded as an engine observation stamped with that
512
- * session id and the witness-monotonic completion tick.
511
+ * Starts one loopback reverse proxy forwarding to ONE attested app origin.
512
+ * `sessionId` names the session the port belongs to (null = the shared
513
+ * unattributed proxy): every exchange completing on this port is recorded
514
+ * as an engine observation stamped with that session id and the
515
+ * witness-monotonic completion tick.
513
516
  *
514
- * The proxy listens on EVERY loopback address the app hostname
515
- * resolved to, all on ONE port: a browser tries every resolved
516
- * address, but a Node-only client (Playwright's APIRequestContext)
517
- * connects to the single address its resolver picks.
517
+ * The proxy listens on EVERY loopback address that origin's hostname
518
+ * resolved to, all on ONE port: a browser tries every resolved address,
519
+ * but a Node-only client (Playwright's APIRequestContext) connects to the
520
+ * single address its resolver picks. A session with several declared app
521
+ * origins gets one of these per origin, all attributed to the SAME session.
518
522
  *
519
523
  * Args:
520
524
  * state: running witness state.
525
+ * origin: the attested app origin this proxy fronts.
521
526
  * sessionId: owning session id, or null for the shared proxy.
522
527
  *
523
528
  * Returns:
@@ -526,8 +531,8 @@ async function closeProxyListeners(servers) {
526
531
  * Throws:
527
532
  * Error: when the proxy fails to bind.
528
533
  */
529
- async function startObservedProxy(state, sessionId, chaosSession) {
530
- const proxyTargetUrl = new URL(state.options.proxyTarget);
534
+ async function startObservedProxy(state, origin, sessionId, chaosSession) {
535
+ const proxyTargetUrl = new URL(origin.baseUrl);
531
536
  // One scheduler per proxy port: a session's `k` and its recorded
532
537
  // schedule are its own, so two tests in one run can never shift each
533
538
  // other's timing. `chaosSession` is the supervisor-issued test id
@@ -565,7 +570,29 @@ async function startObservedProxy(state, sessionId, chaosSession) {
565
570
  }
566
571
  if (collectionRoutes.size === 0)
567
572
  return null;
568
- return collectionRoutes.get(`${method} ${path}`) ?? null;
573
+ let matched = null;
574
+ for (const [route, candidate] of collectionRoutes) {
575
+ const separator = route.indexOf(' ');
576
+ if (route.slice(0, separator) !== method)
577
+ continue;
578
+ if (matchObserveTemplate(path, route.slice(separator + 1)) === null)
579
+ continue;
580
+ if (matched === null) {
581
+ matched = candidate;
582
+ continue;
583
+ }
584
+ const agrees = matched.shape !== null &&
585
+ candidate.shape !== null &&
586
+ (matched.shape.rowsKey ?? null) === (candidate.shape.rowsKey ?? null) &&
587
+ matched.shape.idKey === candidate.shape.idKey;
588
+ if (!agrees) {
589
+ return {
590
+ shape: null,
591
+ declarations: [...matched.declarations, ...candidate.declarations],
592
+ };
593
+ }
594
+ }
595
+ return matched;
569
596
  };
570
597
  // One request handler shared by EVERY listener of this
571
598
  // proxy: each loopback address gets its own Server
@@ -582,6 +609,23 @@ async function startObservedProxy(state, sessionId, chaosSession) {
582
609
  // recorded byte-identical to today.
583
610
  const forwardUrl = stripMountPath(req.url ?? '/', state.options.mountPath);
584
611
  const testCodeInitiated = req.headers['x-gateforge-initiator'] === 'test-code';
612
+ const rawFetchDest = typeof req.headers['sec-fetch-dest'] === 'string'
613
+ ? req.headers['sec-fetch-dest'].toLowerCase()
614
+ : null;
615
+ const resourceType = typeof req.headers['x-gateforge-resource-type'] === 'string'
616
+ ? req.headers['x-gateforge-resource-type'].toLowerCase()
617
+ : null;
618
+ const inferredFetchDest = resourceType === 'fetch' || resourceType === 'xhr'
619
+ ? 'empty'
620
+ : resourceType === 'document'
621
+ ? 'document'
622
+ : resourceType === 'stylesheet'
623
+ ? 'style'
624
+ : resourceType === 'texttrack'
625
+ ? 'track'
626
+ : resourceType;
627
+ const fetchDest = rawFetchDest ?? inferredFetchDest;
628
+ const resourceTypeConflict = rawFetchDest !== null && inferredFetchDest !== null && rawFetchDest !== inferredFetchDest;
585
629
  // In-flight accounting (plan §11.4): a proxy exchange that starts
586
630
  // before `/run-context` binds must refuse the bind — otherwise
587
631
  // traffic from an older invocation could be signed under the new
@@ -643,6 +687,14 @@ async function startObservedProxy(state, sessionId, chaosSession) {
643
687
  const collectionSnapshot = [];
644
688
  let collectionBytes = 0;
645
689
  let totalBytes = 0;
690
+ // Response-shape plan (0.14 WP4): decided from the route, status and
691
+ // content type held before any byte is copied. Null when this run
692
+ // asked for no shapes; an exchange with no plan carries no verdict.
693
+ const shapePlan = state.responseShape === null
694
+ ? null
695
+ : planResponseShape(state.shapeIndex, method, observedPath, status, upstream.headers['content-type']);
696
+ const shapeBody = [];
697
+ let shapeBytes = 0;
646
698
  upstream.on('data', (chunk) => {
647
699
  totalBytes += chunk.length;
648
700
  if (snapshotBytes < OBSERVED_BODY_SNAPSHOT_BYTES) {
@@ -657,6 +709,12 @@ async function startObservedProxy(state, sessionId, chaosSession) {
657
709
  collectionSnapshot.push(Buffer.from(taken));
658
710
  collectionBytes += taken.length;
659
711
  }
712
+ if (shapePlan !== null && shapePlan.kind === 'validate' && shapeBytes < RESPONSE_BODY_CAP_BYTES) {
713
+ const room = RESPONSE_BODY_CAP_BYTES - shapeBytes;
714
+ const taken = chunk.length > room ? chunk.subarray(0, room) : chunk;
715
+ shapeBody.push(Buffer.from(taken));
716
+ shapeBytes += taken.length;
717
+ }
660
718
  });
661
719
  upstream.on('end', () => {
662
720
  const seq = (state.observedSeq += 1);
@@ -676,6 +734,9 @@ async function startObservedProxy(state, sessionId, chaosSession) {
676
734
  method,
677
735
  path: observedPath,
678
736
  status,
737
+ fetchDest,
738
+ resourceType,
739
+ ...(resourceTypeConflict ? { resourceTypeConflict: true } : {}),
679
740
  seq,
680
741
  bodySha256: createHash('sha256').update(bodySnapshot).digest('hex'),
681
742
  bodyBytes: totalBytes,
@@ -693,6 +754,9 @@ async function startObservedProxy(state, sessionId, chaosSession) {
693
754
  : collectionConflict !== null
694
755
  ? { collectionConflict }
695
756
  : {}),
757
+ ...(shapePlan === null
758
+ ? {}
759
+ : { shape: judgeResponseShape(shapePlan, Buffer.concat(shapeBody), totalBytes) }),
696
760
  });
697
761
  // Response attribution (Observe channel): what the response
698
762
  // NAMED, kept even after the exchange is consumed, so a
@@ -712,7 +776,10 @@ async function startObservedProxy(state, sessionId, chaosSession) {
712
776
  upstream.pipe(res);
713
777
  };
714
778
  const forwardHeaders = { ...req.headers, host: proxyTargetUrl.host };
715
- delete forwardHeaders['x-gateforge-initiator'];
779
+ for (const name of Object.keys(forwardHeaders)) {
780
+ if (name.startsWith('x-gateforge-'))
781
+ delete forwardHeaders[name];
782
+ }
716
783
  const forward = request({
717
784
  protocol: proxyTargetUrl.protocol,
718
785
  hostname: proxyTargetUrl.hostname,
@@ -753,9 +820,8 @@ async function startObservedProxy(state, sessionId, chaosSession) {
753
820
  forward.end();
754
821
  });
755
822
  };
756
- // ONE port for every loopback address the app hostname
823
+ // ONE port for every loopback address THIS ORIGIN's hostname
757
824
  // resolves to: the first listener asks the OS for a free
758
- // port and the rest share it. A browser tries every
759
825
  // resolved address, but a Node-only client (Playwright's
760
826
  // APIRequestContext) connects to the single address its
761
827
  // resolver picks, so every loopback address must answer
@@ -767,7 +833,7 @@ async function startObservedProxy(state, sessionId, chaosSession) {
767
833
  const servers = [];
768
834
  let port = 0;
769
835
  try {
770
- for (const bindHost of state.proxyBindHosts) {
836
+ for (const bindHost of origin.bindHosts) {
771
837
  const server = createServer(proxyHandler);
772
838
  await new Promise((resolveListen, rejectListen) => {
773
839
  server.once('error', rejectListen);
@@ -789,7 +855,7 @@ async function startObservedProxy(state, sessionId, chaosSession) {
789
855
  await closeProxyListeners(servers);
790
856
  if (attempt === PROXY_BIND_ATTEMPTS ||
791
857
  error?.code !== 'EADDRINUSE') {
792
- throw new WitnessStartupError(`observation proxy failed to bind '${state.proxyHost}': ${error instanceof Error ? error.message : String(error)}`);
858
+ throw new WitnessStartupError(`observation proxy failed to bind '${origin.host}': ${error instanceof Error ? error.message : String(error)}`);
793
859
  }
794
860
  // EADDRINUSE on a later address: another process took
795
861
  // the port between assignment and this bind. Retry on
@@ -797,21 +863,28 @@ async function startObservedProxy(state, sessionId, chaosSession) {
797
863
  }
798
864
  }
799
865
  // Unreachable: every attempt returns or throws above.
800
- throw new WitnessStartupError(`observation proxy failed to bind '${state.proxyHost}'`);
866
+ throw new WitnessStartupError(`observation proxy failed to bind '${origin.host}'`);
801
867
  }
802
868
  /**
803
- * The base URL of a started observation proxy: the HOSTNAME
869
+ * The base URL of a started observation proxy: the ORIGIN's HOSTNAME
804
870
  * (never an IP, so Host headers stay exactly as the suite
805
871
  * addresses them) plus the one port every listener shares.
806
872
  */
807
- function proxyUrlOf(state, proxy) {
808
- return `http://${formatHost(state.proxyHost)}:${proxy.port}`;
873
+ function proxyUrlOf(origin, proxy) {
874
+ return `http://${formatHost(origin.host)}:${proxy.port}`;
809
875
  }
810
876
  /**
811
- * Starts the DEDICATED session proxy port (plan Phase 1) and stores it
812
- * on the session. Only called when the run wires an observation proxy;
813
- * the worker's browser uses this origin for the whole test, so all of
814
- * its traffic — absolute paths included — is attributed to the session.
877
+ * Starts the session's DEDICATED observation-proxy ports (plan Phase 1),
878
+ * one per attested app origin, and stores them on the session. Only called
879
+ * when the run wires an observation proxy; the worker's browser uses these
880
+ * origins for the whole test, so all of its traffic — on the primary app
881
+ * AND on every declared additional origin, absolute paths included — is
882
+ * attributed to this one session.
883
+ *
884
+ * A declared origin that fails to bind closes the ports already opened for
885
+ * this session first: a half-attributed session (one origin witnessed, one
886
+ * origin silently absent) is exactly the state this feature exists to
887
+ * remove, so the session opens with none or with all of them.
815
888
  *
816
889
  * Args:
817
890
  * state: running witness state.
@@ -823,17 +896,44 @@ async function startSessionProxy(state, session) {
823
896
  session.proxyUrl = null;
824
897
  return;
825
898
  }
826
- const proxy = await startObservedProxy(state, session.sessionId, session.testId);
827
- session.proxyServer = proxy;
828
- session.proxyUrl = proxyUrlOf(state, proxy);
899
+ const [primary, ...additional] = state.proxyOrigins;
900
+ if (primary === undefined) {
901
+ session.proxyUrl = null;
902
+ return;
903
+ }
904
+ // The primary proxy and every additional origin's proxy are retained on
905
+ // the session so sealing closes every listener, not only the primary.
906
+ try {
907
+ const primaryProxy = await startObservedProxy(state, primary, session.sessionId, session.testId);
908
+ session.proxyServer = primaryProxy;
909
+ session.proxyUrl = proxyUrlOf(primary, primaryProxy);
910
+ for (const origin of additional) {
911
+ const proxy = await startObservedProxy(state, origin, session.sessionId, session.testId);
912
+ session.additionalProxyServers.push(proxy);
913
+ session.additionalProxyUrls.push({ appOrigin: origin.appOrigin, proxyUrl: proxyUrlOf(origin, proxy) });
914
+ }
915
+ }
916
+ catch (error) {
917
+ // Half-attributed is worse than unattributed: close every listener
918
+ // this session opened (its own primary included) and open no session
919
+ // at all, so the caller sees the bind failure rather than a session
920
+ // whose declared origins are only partly witnessed.
921
+ await stopSessionProxy(session);
922
+ session.proxyUrl = null;
923
+ throw error;
924
+ }
829
925
  }
830
926
  /** Closes one session's dedicated proxy listeners (sealed = channel gone). */
831
927
  async function stopSessionProxy(session) {
832
- const proxy = session.proxyServer;
928
+ const servers = [
929
+ ...(session.proxyServer?.servers ?? []),
930
+ ...session.additionalProxyServers.flatMap((proxy) => proxy.servers),
931
+ ];
833
932
  session.proxyServer = null;
834
- if (proxy === null)
835
- return;
836
- await closeProxyListeners(proxy.servers);
933
+ session.additionalProxyServers.length = 0;
934
+ session.additionalProxyUrls.length = 0;
935
+ if (servers.length > 0)
936
+ await closeProxyListeners(servers);
837
937
  }
838
938
  /** Detaches the independent browser observer when its test session ends. */
839
939
  async function stopPageObserver(state, sessionId) {
@@ -850,6 +950,30 @@ function sealPageObservationRecords(state, sessionId, outcome) {
850
950
  }
851
951
  state.pageObservationRecords.delete(sessionId);
852
952
  }
953
+ /**
954
+ * Issues the session's ONE claim-free `http.exchanges` record (0.14
955
+ * WP2): the transport snapshot including assets (watermark, dedup, cap,
956
+ * `truncated`), bound to the
957
+ * SESSION identity instead of an obligation so no claim can ever select
958
+ * it. Only a session that sealed as PASSED retains its exchanges — the
959
+ * same non-passing rule {@link sealPageObservationRecords} applies to
960
+ * page observations — and a session that proxied nothing issues
961
+ * nothing. The record is ledger evidence for the verdict-time
962
+ * `httpLedger`; it never satisfies a claim.
963
+ */
964
+ function issueSessionExchangesRecord(state, session) {
965
+ if (session.outcome !== 'passed')
966
+ return;
967
+ const { exchanges, truncated } = transportSnapshot(state, session);
968
+ if (exchanges.length === 0)
969
+ return;
970
+ issueRecord(state, session.sessionId, HTTP_EXCHANGES_KIND, session.testId, {
971
+ channel: OBSERVE_CHANNEL,
972
+ sessionId: session.sessionId,
973
+ exchanges,
974
+ ...(truncated ? { truncated: true } : {}),
975
+ }, 'engine-observed');
976
+ }
853
977
  function isPlainObject(value) {
854
978
  return typeof value === 'object' && value !== null && !Array.isArray(value);
855
979
  }
@@ -871,8 +995,8 @@ function readBody(req) {
871
995
  req.on('data', (chunk) => {
872
996
  raw += chunk;
873
997
  if (raw.length > MAX_BODY_BYTES) {
874
- rejectBody(new HttpError(400, 'request body too large'));
875
- req.destroy();
998
+ req.pause();
999
+ rejectBody(new HttpError(413, 'request body too large'));
876
1000
  }
877
1001
  });
878
1002
  req.on('end', () => {
@@ -918,6 +1042,35 @@ async function enginePageFor(state, sessionId) {
918
1042
  }
919
1043
  return manager.pageFor(sessionId);
920
1044
  }
1045
+ /**
1046
+ * The loopback addresses one app origin's observation proxy may bind.
1047
+ *
1048
+ * An app hostname can resolve to SEVERAL loopback addresses (`localhost`
1049
+ * commonly answers ::1 and the IPv4 loopback): a browser tries every one,
1050
+ * but a Node-only client connects to the single address its resolver picks.
1051
+ * Fail closed on any non-loopback answer, and serve every loopback address.
1052
+ *
1053
+ * Args:
1054
+ * baseUrl: the origin's base URL (attested here, never forwarded off loopback).
1055
+ * hostname: its logical hostname, with any IPv6 brackets stripped.
1056
+ * role: what is being attested, for the refusal message.
1057
+ *
1058
+ * Returns:
1059
+ * string[]: the resolved loopback addresses, deduplicated.
1060
+ *
1061
+ * Raises:
1062
+ * AttestationError: when the origin is not loopback or resolves to any
1063
+ * non-loopback address.
1064
+ */
1065
+ async function resolveProxyBindHosts(baseUrl, hostname, role) {
1066
+ await assertLoopback(baseUrl, role);
1067
+ const resolved = await lookup(hostname, { all: true });
1068
+ const addresses = resolved.map((record) => record.address);
1069
+ if (addresses.length === 0 || !addresses.every(isLoopbackAddress)) {
1070
+ throw new AttestationError(`${role} hostname '${hostname}' resolved to a non-loopback bind address`);
1071
+ }
1072
+ return [...new Set(addresses)];
1073
+ }
921
1074
  /**
922
1075
  * Starts the witness service.
923
1076
  *
@@ -993,25 +1146,39 @@ export async function startWitness(options) {
993
1146
  }
994
1147
  }
995
1148
  // Keep the browser-facing logical hostname and the control host separate.
996
- // Resolve the proxy bind addresses once, and never bind a non-loopback result.
1149
+ // Resolve the proxy bind addresses once per app origin, and never bind a
1150
+ // non-loopback result.
997
1151
  const proxyHostname = options.proxyTarget ? new URL(options.proxyTarget).hostname : null;
998
1152
  const proxyHost = proxyHostname === null
999
1153
  ? options.host ?? LOOPBACK_HOSTNAME
1000
1154
  : proxyHostname.replace(/^\[|\]$/g, '');
1001
1155
  let proxyBindHosts = proxyHostname === null ? [proxyHost] : [];
1002
1156
  if (proxyHostname !== null) {
1003
- await assertLoopback(options.proxyTarget, 'observation proxy target');
1004
- // The app hostname can resolve to SEVERAL loopback addresses
1005
- // (`localhost` commonly answers ::1 and the IPv4 loopback): a
1006
- // browser tries every one, but a Node-only client connects to
1007
- // the single address its resolver picks. Fail closed on any
1008
- // non-loopback answer, and serve every loopback address.
1009
- const resolved = await lookup(proxyHost, { all: true });
1010
- const addresses = resolved.map((record) => record.address);
1011
- if (addresses.length === 0 || !addresses.every(isLoopbackAddress)) {
1012
- throw new AttestationError(`observation proxy hostname '${proxyHost}' resolved to a non-loopback bind address`);
1013
- }
1014
- proxyBindHosts = [...new Set(addresses)];
1157
+ proxyBindHosts = await resolveProxyBindHosts(options.proxyTarget, proxyHost, 'observation proxy target');
1158
+ }
1159
+ // Declared ADDITIONAL app origins (0.15.0, `.gateforge.yml`
1160
+ // `additionalAppOrigins`, resolved by the CLI): each is attested with the
1161
+ // SAME loopback discipline as the primary target, because it is a second
1162
+ // upstream the witness will forward browser traffic to. A non-loopback or
1163
+ // mixed-resolution origin refuses startup HERE, before any request
1164
+ // surface exists for it.
1165
+ const proxyOrigins = [];
1166
+ if (proxyHostname !== null) {
1167
+ proxyOrigins.push({
1168
+ appOrigin: new URL(options.proxyTarget).origin,
1169
+ baseUrl: options.proxyTarget,
1170
+ host: proxyHost,
1171
+ bindHosts: proxyBindHosts,
1172
+ });
1173
+ }
1174
+ for (const declared of options.additionalAppOrigins ?? []) {
1175
+ const hostname = new URL(declared).hostname.replace(/^\[|\]$/g, '');
1176
+ proxyOrigins.push({
1177
+ appOrigin: new URL(declared).origin,
1178
+ baseUrl: declared,
1179
+ host: hostname,
1180
+ bindHosts: await resolveProxyBindHosts(declared, hostname, 'declared additional app origin'),
1181
+ });
1015
1182
  }
1016
1183
  const state = {
1017
1184
  options: {
@@ -1028,6 +1195,7 @@ export async function startWitness(options) {
1028
1195
  adapters,
1029
1196
  proxyHost,
1030
1197
  proxyBindHosts,
1198
+ proxyOrigins,
1031
1199
  classifications,
1032
1200
  ledger: new Map(),
1033
1201
  preObservations: new Map(),
@@ -1046,6 +1214,9 @@ export async function startWitness(options) {
1046
1214
  ? null
1047
1215
  : { options: options.chaos, entries: [] },
1048
1216
  twinShapes: options.twinShapes === undefined || options.twinShapes === null ? null : options.twinShapes,
1217
+ responseShape: null,
1218
+ openApi: null,
1219
+ shapeIndex: null,
1049
1220
  expectedTests: new Map(),
1050
1221
  enumerationDigest: null,
1051
1222
  pageObservation: null,
@@ -1105,8 +1276,12 @@ export async function startWitness(options) {
1105
1276
  // by URL rewriting.
1106
1277
  let proxyUrl = null;
1107
1278
  if (typeof state.options.proxyTarget === 'string' && state.options.proxyTarget.length > 0) {
1108
- state.proxyServer = await startObservedProxy(state, null, SHARED_PROXY_CHAOS_SESSION);
1109
- proxyUrl = proxyUrlOf(state, state.proxyServer);
1279
+ const sharedOrigin = state.proxyOrigins[0];
1280
+ if (sharedOrigin === undefined) {
1281
+ throw new WitnessStartupError('observation proxy target resolved to no proxy origin');
1282
+ }
1283
+ state.proxyServer = await startObservedProxy(state, sharedOrigin, null, SHARED_PROXY_CHAOS_SESSION);
1284
+ proxyUrl = proxyUrlOf(sharedOrigin, state.proxyServer);
1110
1285
  }
1111
1286
  // DNS binding (loopback-pins): the startup asserts above pinned every
1112
1287
  // operator-provided hostname to its approved loopback IPs. Hand the
@@ -1289,6 +1464,7 @@ async function handleHttpObservation(state, res, body) {
1289
1464
  bodySha256: observedRequest.bodySha256,
1290
1465
  bodyBytes: observedRequest.bodyBytes,
1291
1466
  sessionId: session.sessionId,
1467
+ ...(observedRequest.shape === undefined ? {} : { shape: observedRequest.shape }),
1292
1468
  };
1293
1469
  const issued = claimIds.map((claimId) => issueRecord(state, claimId, 'http.request', session.testId, payload, 'engine-observed'));
1294
1470
  const first = issued[0];
@@ -1490,23 +1666,25 @@ async function handleBrowserAction(state, res, body) {
1490
1666
  // INSIDE the engine interval (ticks between open and close), so the
1491
1667
  // existing single-use http-observation consume path binds them.
1492
1668
  for (const exchange of observation.exchanges) {
1669
+ // Judged with the proxy's plan and judge, so a UI-driven body gets the
1670
+ // same shape verdict as a proxied one (block mode never grades it missing).
1671
+ const shape = state.responseShape === null ? undefined : judgeEngineExchange(state.shapeIndex, exchange);
1493
1672
  state.observed.push({
1494
1673
  method: exchange.method,
1495
1674
  path: exchange.path,
1675
+ fetchDest: exchange.fetchDest ?? null,
1676
+ resourceType: null,
1496
1677
  status: exchange.status,
1497
1678
  seq: (state.observedSeq += 1),
1498
1679
  bodySha256: createHash('sha256').update(exchange.body).digest('hex'),
1499
1680
  bodyBytes: exchange.body.length,
1500
- // Engine-captured exchanges carry no request body (the engine
1501
- // typed the input; entered fields ride the ui.action record) —
1502
- // they can never serve an observe finalize, which requires the
1503
- // proxied request bytes.
1504
1681
  requestBody: null,
1505
1682
  requestTruncated: false,
1506
1683
  requestBytes: 0,
1507
1684
  requestContentType: null,
1508
1685
  sessionId: session.sessionId,
1509
1686
  tick: (state.tick += 1),
1687
+ ...(shape === undefined ? {} : { shape }),
1510
1688
  });
1511
1689
  }
1512
1690
  // Suite-submittable intervals/records stay open-submission; the
@@ -1703,9 +1881,10 @@ async function handleRequest(state, req, res) {
1703
1881
  }
1704
1882
  if (state.engineBrowser === null)
1705
1883
  throw new HttpError(503, 'page sweep needs the engine browser');
1884
+ const sweepSessionId = `page-sweep-${state.options.runId}-${body.audience}`;
1706
1885
  const sweep = await sweepPageVisits({
1707
1886
  browser: state.engineBrowser,
1708
- sessionId: `page-sweep-${state.options.runId}-${body.audience}`,
1887
+ sessionId: sweepSessionId,
1709
1888
  testId: 'page-sweep',
1710
1889
  appBase: requireTrustedUiBase(state),
1711
1890
  audience: body.audience,
@@ -1719,6 +1898,23 @@ async function handleRequest(state, req, res) {
1719
1898
  : {}),
1720
1899
  issueRecord: (obligationId, testId, payload) => issueRecord(state, obligationId, 'page.observed', testId, payload, 'engine-observed').recordId,
1721
1900
  });
1901
+ // ONE claim-free `http.exchanges` record for the sweep session
1902
+ // (0.14 WP2): the same snapshot discipline as a test session
1903
+ // (dedup, cap, `truncated`). A REJECTED sweep session retains no
1904
+ // evidence — the same non-passing rule `sealPageObservationRecords`
1905
+ // applies to page observations — and a sweep that saw no API
1906
+ // exchange issues nothing.
1907
+ if (sweep.sessionRejected === null) {
1908
+ const { exchanges, truncated } = cappedExchangeSnapshot(sweep.exchanges);
1909
+ if (exchanges.length > 0) {
1910
+ issueRecord(state, sweepSessionId, HTTP_EXCHANGES_KIND, 'page-sweep', {
1911
+ channel: 'swept',
1912
+ sessionId: sweepSessionId,
1913
+ exchanges,
1914
+ ...(truncated ? { truncated: true } : {}),
1915
+ }, 'engine-observed');
1916
+ }
1917
+ }
1722
1918
  sendJson(res, 200, { visits: sweep.visits, sessionRejected: sweep.sessionRejected });
1723
1919
  return;
1724
1920
  }
@@ -1825,10 +2021,6 @@ async function handleRequest(state, req, res) {
1825
2021
  await handleSessionPageOrigins(state, res, (await readBody(req)));
1826
2022
  return;
1827
2023
  }
1828
- if (req.method === 'POST' && path === '/sessions/direct-exchanges') {
1829
- await handleSessionDirectExchanges(state, res, (await readBody(req)));
1830
- return;
1831
- }
1832
2024
  if (req.method === 'POST' && path === '/sessions/page-observer') {
1833
2025
  const body = (await readBody(req));
1834
2026
  try {
@@ -2988,12 +3180,13 @@ async function handleSessionOpen(state, res, body) {
2988
3180
  sealedTick: null,
2989
3181
  outcome: null,
2990
3182
  intervals: new Map(),
2991
- // Filled below: the session's DEDICATED observation-proxy port.
3183
+ // Filled below: the session's DEDICATED observation-proxy ports, one
3184
+ // per attested app origin this run declares.
2992
3185
  proxyUrl: null,
3186
+ additionalProxyUrls: [],
3187
+ additionalProxyServers: [],
2993
3188
  proxyServer: null,
2994
3189
  claims,
2995
- directExchanges: [],
2996
- directRecordsIssued: new Set(),
2997
3190
  // The registered expected-set identity this session was minted for
2998
3191
  // (enforcement-review fix 2b); null when no expected set is bound.
2999
3192
  registered: registered !== null
@@ -3045,6 +3238,7 @@ function sessionView(state, session) {
3045
3238
  workerIndex: session.workerIndex,
3046
3239
  openedTick: session.openedTick,
3047
3240
  proxyUrl: session.proxyUrl,
3241
+ additionalProxyUrls: session.additionalProxyUrls.map((entry) => ({ ...entry })),
3048
3242
  claims: [...session.claims],
3049
3243
  };
3050
3244
  }
@@ -3090,6 +3284,7 @@ async function handleSessionClose(state, res, body) {
3090
3284
  session.outcome = outcome;
3091
3285
  }
3092
3286
  sealPageObservationRecords(state, sessionId, session.outcome);
3287
+ issueSessionExchangesRecord(state, session);
3093
3288
  // The session's own evidence died with its proxy at release; the
3094
3289
  // observe snapshots are dropped HERE, at the moment the outcome is
3095
3290
  // finally recorded, so an unreleased session's before-state can
@@ -3106,6 +3301,7 @@ async function handleSessionClose(state, res, body) {
3106
3301
  session.sealedTick = (state.tick += 1);
3107
3302
  session.outcome = typeof outcome === 'string' ? outcome : null;
3108
3303
  sealPageObservationRecords(state, sessionId, session.outcome);
3304
+ issueSessionExchangesRecord(state, session);
3109
3305
  state.workerSessions.delete(session.workerIndex);
3110
3306
  // Observe snapshots die with the session: finalize runs BEFORE seal
3111
3307
  // (the drain finalizes a passed test, then seals), so anything left
@@ -3222,38 +3418,6 @@ async function handleSessionPageOrigins(state, res, body) {
3222
3418
  });
3223
3419
  sendJson(res, 200, { recorded: true });
3224
3420
  }
3225
- /** Stores bounded, deduplicated direct API exchanges on their session. */
3226
- async function handleSessionDirectExchanges(state, res, body) {
3227
- if (!isPlainObject(body))
3228
- throw new HttpError(400, 'direct exchange report body must be an object');
3229
- const session = requireOpenSession(state, body);
3230
- const reported = body['exchanges'];
3231
- if (!Array.isArray(reported) || reported.length === 0) {
3232
- throw new HttpError(400, 'direct exchange report requires at least one exchange');
3233
- }
3234
- const exchanges = reported.map((item) => {
3235
- if (!isPlainObject(item) ||
3236
- typeof item['method'] !== 'string' ||
3237
- !/^[A-Z]+$/.test(item['method']) ||
3238
- typeof item['url'] !== 'string' ||
3239
- item['url'].length === 0 ||
3240
- typeof item['status'] !== 'number' ||
3241
- !Number.isInteger(item['status']) ||
3242
- item['status'] < 100 ||
3243
- item['status'] > 599) {
3244
- throw new HttpError(400, 'each direct exchange must have an uppercase method, URL, and HTTP status');
3245
- }
3246
- return { method: item['method'], url: item['url'], status: item['status'] };
3247
- });
3248
- for (const exchange of exchanges) {
3249
- if (session.directExchanges.some((prior) => prior.method === exchange.method && prior.url === exchange.url && prior.status === exchange.status))
3250
- continue;
3251
- if (session.directExchanges.length >= DIRECT_EXCHANGES_CAP)
3252
- break;
3253
- session.directExchanges.push(exchange);
3254
- }
3255
- sendJson(res, 200, { recorded: true, kept: session.directExchanges.length });
3256
- }
3257
3421
  /**
3258
3422
  * One reported origin, parsed and reduced to its origin form. A value
3259
3423
  * that is not an absolute http(s) URL is refused rather than repaired:
@@ -3926,6 +4090,29 @@ async function takePreObservation(state, session, resourceId, entityId) {
3926
4090
  session.activity += 1;
3927
4091
  return { observationId, observed: ids.length };
3928
4092
  }
4093
+ /**
4094
+ * Whether the ledger holds TEST evidence: any issued record other than
4095
+ * the single run-level OpenAPI metadata record (kind `http.openapi`,
4096
+ * testId `run`) that binding a response-shape run seals. That record is
4097
+ * run metadata sealed at bind time — BEFORE the supervisor drain
4098
+ * registers its PRE-run declarations — so the PRE-run gates must not
4099
+ * treat it as "the run already happened". Any other record (exchanges,
4100
+ * observations, persistence, claims) is real test evidence and counts.
4101
+ *
4102
+ * Args:
4103
+ * state: running witness state.
4104
+ *
4105
+ * Returns:
4106
+ * boolean: true when the ledger holds at least one non-metadata record.
4107
+ */
4108
+ function hasTestEvidenceRecord(state) {
4109
+ for (const record of state.ledger.values()) {
4110
+ if (record.kind === HTTP_OPENAPI_KIND && record.testId === 'run')
4111
+ continue;
4112
+ return true;
4113
+ }
4114
+ return false;
4115
+ }
3929
4116
  /**
3930
4117
  * `POST /runs/server-e2e-declarations` — SUPERVISOR ONLY (verifier key;
3931
4118
  * the same authority as `POST /runs/expected-set`): registers the
@@ -3968,7 +4155,7 @@ async function handleServerE2eDeclarations(state, res, verifier, body) {
3968
4155
  });
3969
4156
  return;
3970
4157
  }
3971
- if (state.ledger.size > 0 || state.sessions.size > 0 || state.serverPreObservations.size > 0) {
4158
+ if (hasTestEvidenceRecord(state) || state.sessions.size > 0 || state.serverPreObservations.size > 0) {
3972
4159
  sendJson(res, 409, {
3973
4160
  error: 'witness already issued evidence or holds open sessions; server-e2e declarations must be ' +
3974
4161
  'registered BEFORE the run — start a fresh witness for a new invocation',
@@ -4019,7 +4206,7 @@ async function handleObserveDeclarations(state, res, verifier, body) {
4019
4206
  });
4020
4207
  return;
4021
4208
  }
4022
- if (state.ledger.size > 0 || state.sessions.size > 0) {
4209
+ if (hasTestEvidenceRecord(state) || state.sessions.size > 0) {
4023
4210
  sendJson(res, 409, {
4024
4211
  error: 'witness already issued evidence or holds open sessions; observe declarations must be ' +
4025
4212
  'registered BEFORE the run — start a fresh witness for a new invocation',
@@ -4164,7 +4351,7 @@ async function observeListEntities(adapterName, adapter, ctx) {
4164
4351
  function matchObserveTemplate(observedPath, template) {
4165
4352
  const segments = template.split('/').filter((segment) => segment.length > 0);
4166
4353
  const idIndex = segments.indexOf('{id}');
4167
- const canonical = segments.map((segment) => (segment === '{id}' ? '{}' : segment)).join('/');
4354
+ const canonical = segments.map((segment) => (segment === '{id}' || segment.startsWith(':') ? '{}' : segment)).join('/');
4168
4355
  if (!pathMatchesShape(observedPath, canonical.startsWith('/') ? canonical : `/${canonical}`)) {
4169
4356
  return null;
4170
4357
  }
@@ -4439,9 +4626,10 @@ function attributeCreatedEntity(state, binding, exchange, fresh) {
4439
4626
  * stays blocking through verdicts, which is the honest outcome).
4440
4627
  *
4441
4628
  * Per obligation (`<resourceId>:persistence:<op>`):
4442
- * - adapter binding + before-snapshot must exist (else typed note);
4443
- * - exactly one 2xx session exchange must match the binding (zero →
4444
- * missing-traffic note; several → ambiguity note);
4629
+ * - exactly one 2xx session exchange must match the binding for
4630
+ * create/update/delete; reads may match repeated exchanges only when
4631
+ * each resolves to the same entity, consuming every matching exchange
4632
+ * single-use (zero → missing-traffic note; disagreement → ambiguity);
4445
4633
  * - create attributes its id to the response the witness proxied,
4446
4634
  * verified against the after-list (a concurrent observed create
4447
4635
  * named by its OWN response is not ambiguity; a new entity no
@@ -4490,18 +4678,7 @@ async function handleObserveFinalize(state, res, verifier, body) {
4490
4678
  // transport record carries. Persistence-vs-persistence consumption is
4491
4679
  // untouched: it still matches against the LIVE log, so one exchange
4492
4680
  // can never credit two persistence claims.
4493
- if (session.directExchanges.length > 0) {
4494
- for (const claimId of session.claims) {
4495
- if (session.directRecordsIssued.has(claimId))
4496
- continue;
4497
- issueRecord(state, claimId, HTTP_OBSERVED_KIND, session.testId, {
4498
- channel: DIRECT_CHANNEL,
4499
- exchanges: session.directExchanges.map((exchange) => ({ ...exchange })),
4500
- }, 'engine-observed');
4501
- session.directRecordsIssued.add(claimId);
4502
- }
4503
- }
4504
- const transport = transportSnapshot(state, session);
4681
+ const transport = transportSnapshot(state, session, false);
4505
4682
  const claims = session.claims.filter((claim) => state.observeDeclarations?.has(claim));
4506
4683
  for (const claimId of claims) {
4507
4684
  const outcome = await finalizeObserveClaim(state, session, claimId, transport);
@@ -4545,31 +4722,77 @@ function zeroTrafficCause(state, session) {
4545
4722
  const reported = pageOriginNote(state, session);
4546
4723
  return reported === '' ? FIXTURE_PAGE_CAUSE : reported;
4547
4724
  }
4548
- function transportSnapshot(state, session) {
4725
+ function transportSnapshot(state, session, includeAssets = true) {
4549
4726
  const watermark = state.runContext === null ? 0 : state.observedSeqAtBind;
4550
- const seen = Object.create(null);
4727
+ // key -> position in `exchanges`, so a repeat can upgrade its shape in place.
4728
+ const seen = new Map();
4551
4729
  const exchanges = [];
4552
4730
  let truncated = false;
4553
4731
  for (const exchange of state.observed) {
4554
4732
  if (exchange.sessionId !== session.sessionId || exchange.seq <= watermark)
4555
4733
  continue;
4556
- const key = `${exchange.method} ${exchange.path} ${String(exchange.status)} ${exchange.initiator ?? 'page'}`;
4557
- if (key in seen)
4734
+ if (!includeAssets && httpExchangeKind(exchange.fetchDest) === 'asset')
4558
4735
  continue;
4559
- seen[key] = true;
4736
+ const key = `${exchange.method} ${exchange.path} ${String(exchange.status)} ${exchange.initiator ?? 'page'} ${exchange.fetchDest ?? ''} ${exchange.resourceType ?? ''}`;
4737
+ const at = seen.get(key);
4738
+ if (at !== undefined) {
4739
+ // A repeat keeps the WORST shape verdict, so a mismatch on any repeat survives the dedup.
4740
+ const kept = exchanges[at];
4741
+ if (kept !== undefined && exchange.shape !== undefined && (kept.shape === undefined || shapeRank(exchange.shape) > shapeRank(kept.shape))) {
4742
+ exchanges[at] = { ...kept, shape: exchange.shape };
4743
+ }
4744
+ continue;
4745
+ }
4560
4746
  if (exchanges.length >= OBSERVED_EXCHANGES_CAP) {
4561
4747
  truncated = true;
4562
4748
  continue;
4563
4749
  }
4750
+ seen.set(key, exchanges.length);
4564
4751
  exchanges.push({
4565
4752
  method: exchange.method,
4566
4753
  url: exchange.path,
4567
4754
  status: exchange.status,
4755
+ fetchDest: exchange.fetchDest,
4568
4756
  ...(exchange.initiator === 'test-code' ? { initiator: exchange.initiator } : {}),
4757
+ resourceType: exchange.resourceType,
4758
+ ...(exchange.resourceTypeConflict ? { resourceTypeConflict: true } : {}),
4759
+ ...(exchange.shape === undefined ? {} : { shape: exchange.shape }),
4569
4760
  });
4570
4761
  }
4571
4762
  return { exchanges, truncated };
4572
4763
  }
4764
+ /**
4765
+ * Applies the SAME snapshot discipline `transportSnapshot` enforces —
4766
+ * dedup by `(method, url, status)`, cap at {@link OBSERVED_EXCHANGES_CAP}
4767
+ * with `truncated: true` past the cap — to an already-captured exchange
4768
+ * list. Ledger callers retain assets; Observe callers must exclude them.
4769
+ */
4770
+ function cappedExchangeSnapshot(exchanges, includeAssets = true) {
4771
+ const seen = Object.create(null);
4772
+ const kept = [];
4773
+ let truncated = false;
4774
+ for (const exchange of exchanges) {
4775
+ if (!includeAssets && httpExchangeKind(exchange.fetchDest) === 'asset')
4776
+ continue;
4777
+ const key = `${exchange.method} ${exchange.url} ${String(exchange.status)} ${exchange.fetchDest ?? ''} ${exchange.resourceType ?? ''}`;
4778
+ if (key in seen)
4779
+ continue;
4780
+ seen[key] = true;
4781
+ if (kept.length >= OBSERVED_EXCHANGES_CAP) {
4782
+ truncated = true;
4783
+ continue;
4784
+ }
4785
+ kept.push({
4786
+ method: exchange.method,
4787
+ url: exchange.url,
4788
+ status: exchange.status,
4789
+ fetchDest: exchange.fetchDest ?? null,
4790
+ resourceType: exchange.resourceType ?? null,
4791
+ ...(exchange.resourceTypeConflict ? { resourceTypeConflict: true } : {}),
4792
+ });
4793
+ }
4794
+ return { exchanges: kept, truncated };
4795
+ }
4573
4796
  /**
4574
4797
  * Resolves one observe-declared claim (record or typed note, never
4575
4798
  * throws). `persistence:*` claims resolve against the session's own
@@ -4636,11 +4859,53 @@ async function finalizeObserveClaim(state, session, claimId, transport) {
4636
4859
  `proxy — drive traffic through the session proxy prefix before claiming the obligation; ` +
4637
4860
  zeroTrafficCause(state, session));
4638
4861
  }
4862
+ let exchangesToConsume = [];
4639
4863
  if (matches.length > 1) {
4640
- return note(`${String(matches.length)} matching ${binding.method} ${binding.path} exchanges — ambiguous, ` +
4641
- 'refusing to pick one (seed through untracked channels so the mutation stands alone)');
4864
+ if (operation !== 'read') {
4865
+ return note(`${String(matches.length)} matching ${binding.method} ${binding.path} exchanges — ambiguous, ` +
4866
+ 'refusing to pick one (seed through untracked channels so the mutation stands alone)');
4867
+ }
4868
+ const resolved = new Set();
4869
+ if (binding.collection === undefined) {
4870
+ for (const match of matches) {
4871
+ if (match.id === null) {
4872
+ return note('the observe binding carries no {id} segment for a non-create operation');
4873
+ }
4874
+ const key = beforeKeyForSegment(snapshot.before, match.id);
4875
+ if (key === null) {
4876
+ return note(`entity '${match.id}' was not in the session-open snapshot — observe binds {id} ` +
4877
+ 'against witness-held before-state, never against suite-declared ids');
4878
+ }
4879
+ resolved.add(key);
4880
+ }
4881
+ if (resolved.size > 1)
4882
+ return note(`${resolved.size} distinct entity ids among repeated read exchanges — ambiguous`);
4883
+ }
4884
+ else {
4885
+ for (const match of matches) {
4886
+ const rows = match.exchange.collectionRows;
4887
+ if (match.exchange.collectionConflict !== undefined || rows === undefined || rows.error !== null ||
4888
+ rows.rowsKey !== (binding.collection.rowsKey ?? null) || rows.idKey !== binding.collection.idKey) {
4889
+ return note(`${matches.length} repeated collection read exchanges could not all resolve to the same entity — ambiguous`);
4890
+ }
4891
+ const held = Object.create(null);
4892
+ for (const id of rows.ids) {
4893
+ const key = beforeKeyForSegment(snapshot.before, String(id));
4894
+ if (key !== null)
4895
+ held[key] = true;
4896
+ }
4897
+ const returned = Object.keys(held).sort(compareStrings);
4898
+ if (returned.length === 0) {
4899
+ return note(`${matches.length} repeated collection read exchanges could not all resolve to the same entity — ambiguous`);
4900
+ }
4901
+ resolved.add(returned[0]);
4902
+ }
4903
+ if (resolved.size > 1)
4904
+ return note(`${resolved.size} distinct entities among repeated collection reads — ambiguous`);
4905
+ }
4906
+ exchangesToConsume = matches.map((match) => match.exchange);
4642
4907
  }
4643
- const matched = matches[0];
4908
+ const matched = matches[matches.length - 1];
4644
4909
  // Resolve the entity id: create attributes the entity to the response
4645
4910
  // the witness proxied (verified against the witness's own after-list,
4646
4911
  // so a concurrent observed create cannot make it ambiguous);
@@ -4676,8 +4941,8 @@ async function finalizeObserveClaim(state, session, claimId, transport) {
4676
4941
  // such row names nothing to prove — both are typed notes.
4677
4942
  const conflict = matched.exchange.collectionConflict;
4678
4943
  if (conflict !== undefined) {
4679
- return note(`this session claims more than one read on ${binding.method} ${binding.path} and they declare ` +
4680
- `DIFFERENT collection shapes (${conflict.join(' vs ')}) — the witness parses that response for ` +
4944
+ return note(`this session claims more than one read on ${binding.method} ${binding.path} and declares DIFFERENT ` +
4945
+ `collection shapes (different declared collection shapes: ${conflict.join(' vs ')}) — the witness parses that response for ` +
4681
4946
  'neither of them, so no record is issued');
4682
4947
  }
4683
4948
  const rows = matched.exchange.collectionRows;
@@ -4767,10 +5032,13 @@ async function finalizeObserveClaim(state, session, claimId, transport) {
4767
5032
  // origin, witnessed trust; the suite-driven-browser distinction rides
4768
5033
  // `channel: 'observe'`, which the grader keys off explicitly.
4769
5034
  const issued = issueRecord(state, claimId, OBSERVED_KIND, session.testId, payload, 'engine-observed');
4770
- // Single-use: the matched exchange can never credit another claim.
4771
- const consumed = state.observed.indexOf(matched.exchange);
4772
- if (consumed !== -1)
4773
- state.observed.splice(consumed, 1);
5035
+ // Single-use: agreeing repeated read exchanges are consumed together.
5036
+ const consumedExchanges = exchangesToConsume.length === 0 ? [matched.exchange] : exchangesToConsume;
5037
+ for (const exchange of consumedExchanges) {
5038
+ const consumed = state.observed.indexOf(exchange);
5039
+ if (consumed !== -1)
5040
+ state.observed.splice(consumed, 1);
5041
+ }
4774
5042
  session.activity += 1;
4775
5043
  return {
4776
5044
  record: { obligationId: claimId, recordId: issued.recordId, operation, entityId: read.entityId },
@@ -5306,7 +5574,7 @@ async function handleRunContext(state, res, verifier, body) {
5306
5574
  });
5307
5575
  return;
5308
5576
  }
5309
- if (state.ledger.size > 0 ||
5577
+ if (hasTestEvidenceRecord(state) ||
5310
5578
  state.observed.length > 0 ||
5311
5579
  state.preObservations.size > 0 ||
5312
5580
  state.serverPreObservations.size > 0 ||
@@ -5343,6 +5611,12 @@ async function handleRunContext(state, res, verifier, body) {
5343
5611
  }
5344
5612
  state.runContext = { runId, invocationId, inputDigest };
5345
5613
  state.observedSeqAtBind = state.observedSeq;
5614
+ if (boundOptions.responseShape !== undefined && state.responseShape === null) {
5615
+ state.responseShape = boundOptions.responseShape;
5616
+ state.openApi = await fetchOpenApiAtBind(state.options.targetBaseUrl ?? null, boundOptions.responseShape.openapiPath, state.options.requestTimeoutMs);
5617
+ state.shapeIndex = state.openApi.status === 'fetched' ? buildResponseShapeIndex(state.openApi.document) : null;
5618
+ issueRecord(state, state.options.runId, HTTP_OPENAPI_KIND, 'run', openApiRecordPayload(state.openApi), 'engine-observed');
5619
+ }
5346
5620
  sendJson(res, 200, { bound: true, runId, invocationId, inputDigest, ...appliedEcho(state) });
5347
5621
  }
5348
5622
  /**
@@ -5360,6 +5634,7 @@ function appliedOptionsOf(state) {
5360
5634
  return {
5361
5635
  chaos: state.chaos === null ? null : state.chaos.options,
5362
5636
  twinShapes: state.twinShapes,
5637
+ responseShape: state.responseShape,
5363
5638
  };
5364
5639
  }
5365
5640
  /**
@@ -5375,7 +5650,9 @@ function appliedOptionsOf(state) {
5375
5650
  */
5376
5651
  function appliedEcho(state) {
5377
5652
  const applied = appliedOptionsOf(state);
5378
- return applied.chaos === null && applied.twinShapes === null ? {} : { applied };
5653
+ return applied.chaos === null && applied.twinShapes === null && applied.responseShape === null
5654
+ ? {}
5655
+ : { applied };
5379
5656
  }
5380
5657
  /**
5381
5658
  * Serves the authenticated live attestation (pin #7, GF-23, plan §11.3):