@air-jam/devtools 0.9.3 → 1.0.0-beta.1

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 (263) hide show
  1. package/README.md +60 -0
  2. package/dist/{chunk-VKMJO6VN.js → chunk-2O67AXCU.js} +150 -40
  3. package/dist/chunk-2O67AXCU.js.map +1 -0
  4. package/dist/chunk-AO3ZDXF6.js +142 -0
  5. package/dist/chunk-AO3ZDXF6.js.map +1 -0
  6. package/dist/chunk-ART5TEYT.js +472 -0
  7. package/dist/chunk-ART5TEYT.js.map +1 -0
  8. package/dist/chunk-ASC2CK2R.js +77 -0
  9. package/dist/chunk-ASC2CK2R.js.map +1 -0
  10. package/dist/chunk-E3UZZGAV.js +50 -0
  11. package/dist/chunk-E3UZZGAV.js.map +1 -0
  12. package/dist/chunk-EJTE7UKX.js +64 -0
  13. package/dist/chunk-EJTE7UKX.js.map +1 -0
  14. package/dist/chunk-ESFKNN75.js +110 -0
  15. package/dist/chunk-ESFKNN75.js.map +1 -0
  16. package/dist/chunk-EU7A6PXW.js +1339 -0
  17. package/dist/chunk-EU7A6PXW.js.map +1 -0
  18. package/dist/chunk-FN7E6EA7.js +549 -0
  19. package/dist/chunk-FN7E6EA7.js.map +1 -0
  20. package/dist/chunk-GDFAWHGA.js +190 -0
  21. package/dist/chunk-GDFAWHGA.js.map +1 -0
  22. package/dist/chunk-HZUGBH4Y.js +347 -0
  23. package/dist/chunk-HZUGBH4Y.js.map +1 -0
  24. package/dist/chunk-ITKAOEGX.js +93 -0
  25. package/dist/chunk-ITKAOEGX.js.map +1 -0
  26. package/dist/chunk-JBCUTWRI.js +897 -0
  27. package/dist/chunk-JBCUTWRI.js.map +1 -0
  28. package/dist/chunk-JSI5S4WP.js +1174 -0
  29. package/dist/chunk-JSI5S4WP.js.map +1 -0
  30. package/dist/chunk-L4D675BG.js +97 -0
  31. package/dist/chunk-L4D675BG.js.map +1 -0
  32. package/dist/chunk-M6CJ7GQC.js +133 -0
  33. package/dist/chunk-M6CJ7GQC.js.map +1 -0
  34. package/dist/{chunk-CKFT2ZJE.js → chunk-MEIMOSZC.js} +53 -105
  35. package/dist/chunk-MEIMOSZC.js.map +1 -0
  36. package/dist/{chunk-GUEZP773.js → chunk-O3XG3FNL.js} +204 -41
  37. package/dist/chunk-O3XG3FNL.js.map +1 -0
  38. package/dist/chunk-OM6SCJ7H.js +18 -0
  39. package/dist/chunk-OM6SCJ7H.js.map +1 -0
  40. package/dist/chunk-PKD4WVX5.js +63 -0
  41. package/dist/chunk-PKD4WVX5.js.map +1 -0
  42. package/dist/chunk-PMBLXGFM.js +3384 -0
  43. package/dist/chunk-PMBLXGFM.js.map +1 -0
  44. package/dist/chunk-PMNE5GIN.js +279 -0
  45. package/dist/chunk-PMNE5GIN.js.map +1 -0
  46. package/dist/chunk-QAWI64VR.js +148 -0
  47. package/dist/chunk-QAWI64VR.js.map +1 -0
  48. package/dist/chunk-QGADSPHZ.js +449 -0
  49. package/dist/chunk-QGADSPHZ.js.map +1 -0
  50. package/dist/chunk-SPYN66UV.js +338 -0
  51. package/dist/chunk-SPYN66UV.js.map +1 -0
  52. package/dist/context.d.ts +9 -3
  53. package/dist/context.js +2 -1
  54. package/dist/controller.d.ts +33 -7
  55. package/dist/controller.js +18 -8
  56. package/dist/dependencies.d.ts +44 -0
  57. package/dist/dependencies.js +10 -0
  58. package/dist/dev.d.ts +9 -3
  59. package/dist/dev.js +3 -4
  60. package/dist/game-builds.d.ts +200 -0
  61. package/dist/game-builds.js +16 -0
  62. package/dist/game-builds.js.map +1 -0
  63. package/dist/game-run-watch-CEd_SpAT.d.ts +84 -0
  64. package/dist/game-runs.d.ts +1452 -0
  65. package/dist/game-runs.js +76 -0
  66. package/dist/game-runs.js.map +1 -0
  67. package/dist/game-session-broker-CUvORfMd.d.ts +439 -0
  68. package/dist/game-session-broker.d.ts +4 -57
  69. package/dist/game-session-broker.js +33 -228
  70. package/dist/game-session-broker.js.map +1 -1
  71. package/dist/game-session.d.ts +3931 -10
  72. package/dist/game-session.js +186 -15
  73. package/dist/game-session.js.map +1 -1
  74. package/dist/game-settings.d.ts +16 -0
  75. package/dist/game-settings.js +237 -0
  76. package/dist/game-settings.js.map +1 -0
  77. package/dist/games.d.ts +11 -4
  78. package/dist/games.js +4 -2
  79. package/dist/harness/visual.d.ts +34 -151
  80. package/dist/harness/visual.js +6 -1
  81. package/dist/logs.d.ts +8 -2
  82. package/dist/logs.js +3 -4
  83. package/dist/logs.js.map +1 -1
  84. package/dist/managed-process-scope-BicYi_t9.d.ts +3 -0
  85. package/dist/mcp-config.js +2 -1
  86. package/dist/mcp-config.js.map +1 -1
  87. package/dist/platform-auth.d.ts +8 -111
  88. package/dist/platform-auth.js +9 -1
  89. package/dist/platform-game-analytics.d.ts +51 -0
  90. package/dist/platform-game-analytics.js +49 -0
  91. package/dist/platform-game-analytics.js.map +1 -0
  92. package/dist/platform-game-app-id.d.ts +46 -0
  93. package/dist/platform-game-app-id.js +93 -0
  94. package/dist/platform-game-app-id.js.map +1 -0
  95. package/dist/platform-game-media.d.ts +40 -2
  96. package/dist/platform-game-media.js +1 -1
  97. package/dist/platform-games.d.ts +24 -2
  98. package/dist/platform-games.js +16 -84
  99. package/dist/platform-games.js.map +1 -1
  100. package/dist/quality.d.ts +9 -3
  101. package/dist/quality.js +3 -4
  102. package/dist/quality.js.map +1 -1
  103. package/dist/release.d.ts +226 -16
  104. package/dist/release.js +18 -1331
  105. package/dist/release.js.map +1 -1
  106. package/dist/rooms-check.d.ts +90 -0
  107. package/dist/rooms-check.js +717 -0
  108. package/dist/rooms-check.js.map +1 -0
  109. package/dist/source-tree-contract.d.ts +16 -0
  110. package/dist/source-tree-contract.js +13 -0
  111. package/dist/source-tree-contract.js.map +1 -0
  112. package/dist/testing.d.ts +464 -0
  113. package/dist/testing.js +27 -0
  114. package/dist/testing.js.map +1 -0
  115. package/dist/tooling/describe-game.js +54 -0
  116. package/dist/tooling/describe-game.js.map +1 -0
  117. package/dist/tooling/game-session-broker.js +28 -0
  118. package/dist/tooling/game-session-broker.js.map +1 -0
  119. package/dist/tooling/hold-runtime-host.js +769 -67
  120. package/dist/tooling/hold-runtime-host.js.map +1 -1
  121. package/dist/tooling/list-visual-scenarios.js +18 -55
  122. package/dist/tooling/list-visual-scenarios.js.map +1 -1
  123. package/dist/tooling/process-scope-bootstrap.mjs +24 -0
  124. package/dist/tooling/process-scope-guard.d.ts +2 -0
  125. package/dist/tooling/process-scope-guard.js +388 -0
  126. package/dist/tooling/process-scope-guard.js.map +1 -0
  127. package/dist/tooling/process-scope-windows.ps1 +148 -0
  128. package/dist/tooling/rooms-check-device.d.ts +2 -0
  129. package/dist/tooling/rooms-check-device.js +498 -0
  130. package/dist/tooling/rooms-check-device.js.map +1 -0
  131. package/dist/tooling/run-headless-room.d.ts +2 -0
  132. package/dist/tooling/run-headless-room.js +287 -0
  133. package/dist/tooling/run-headless-room.js.map +1 -0
  134. package/dist/tooling/run-test-profile.d.ts +2 -0
  135. package/dist/tooling/run-test-profile.js +181 -0
  136. package/dist/tooling/run-test-profile.js.map +1 -0
  137. package/dist/tooling/run-visual-capture.js +70 -34
  138. package/dist/tooling/run-visual-capture.js.map +1 -1
  139. package/dist/tooling/seal-game-build.d.ts +2 -0
  140. package/dist/tooling/seal-game-build.js +120 -0
  141. package/dist/tooling/seal-game-build.js.map +1 -0
  142. package/dist/{types-C6NrHt88.d.ts → types-CdYrgrG_.d.ts} +337 -76
  143. package/dist/types-DyRD-ym1.d.ts +141 -0
  144. package/dist/visual.d.ts +9 -3
  145. package/dist/visual.js +24 -68
  146. package/dist/visual.js.map +1 -1
  147. package/package.json +51 -14
  148. package/src/bounded-response.ts +28 -0
  149. package/src/built-game-runtime.ts +152 -0
  150. package/src/context.ts +2 -13
  151. package/src/controller-protocol.ts +22 -0
  152. package/src/controller.ts +747 -597
  153. package/src/current-room-host.ts +166 -0
  154. package/src/decision-provider.ts +102 -0
  155. package/src/dependencies.ts +176 -0
  156. package/src/dependency-install-contract.ts +12 -0
  157. package/src/dev.ts +46 -50
  158. package/src/game-action-observation.ts +11 -1
  159. package/src/game-build-protocol.ts +72 -0
  160. package/src/game-build.ts +483 -0
  161. package/src/game-run-owner.ts +2358 -0
  162. package/src/game-run-protocol.ts +448 -0
  163. package/src/game-run-record.ts +92 -0
  164. package/src/game-run-replay.ts +95 -0
  165. package/src/game-run-watch.ts +155 -0
  166. package/src/game-session-broker.ts +689 -197
  167. package/src/game-session-operations.ts +61 -0
  168. package/src/game-session-protocol.ts +180 -0
  169. package/src/game-session-runtime.ts +861 -0
  170. package/src/game-session.ts +164 -417
  171. package/src/game-settings.ts +295 -0
  172. package/src/games.ts +88 -92
  173. package/src/harness/visual/browser.ts +100 -0
  174. package/src/harness/visual/controller-observation.ts +181 -0
  175. package/src/harness/visual/runner.ts +24 -21
  176. package/src/harness/visual/runtime-controller-observations.ts +151 -0
  177. package/src/harness/visual/scenario-contract.ts +1 -2
  178. package/src/harness/visual/scenario-helpers.ts +5 -1
  179. package/src/harness/visual/screencast.ts +155 -0
  180. package/src/harness/visual/session.ts +72 -41
  181. package/src/harness/visual/types.ts +8 -5
  182. package/src/headless-room-protocol.ts +112 -0
  183. package/src/headless-room.ts +222 -0
  184. package/src/helper-channel.ts +229 -0
  185. package/src/helper-scripts.ts +25 -5
  186. package/src/installed-dependencies.ts +74 -0
  187. package/src/managed-process-scope.ts +481 -0
  188. package/src/node-process-environment.ts +10 -0
  189. package/src/platform-auth.ts +194 -55
  190. package/src/platform-game-analytics.ts +50 -0
  191. package/src/platform-game-app-id.ts +99 -0
  192. package/src/platform-games.ts +13 -111
  193. package/src/policy-artifact-contract.ts +52 -0
  194. package/src/policy-artifacts.ts +134 -0
  195. package/src/process-scope-admission.ts +50 -0
  196. package/src/process-scope-protocol.ts +66 -0
  197. package/src/process-scope.ts +327 -0
  198. package/src/release.ts +28 -42
  199. package/src/rooms-check-fleet.ts +194 -0
  200. package/src/rooms-check-link.ts +138 -0
  201. package/src/rooms-check-protocol.ts +244 -0
  202. package/src/rooms-check.ts +797 -0
  203. package/src/runtime-owner-protocol.ts +106 -18
  204. package/src/source-tree-contract.ts +70 -0
  205. package/src/source-tree.ts +84 -0
  206. package/src/test-profile-process.ts +153 -0
  207. package/src/test-profile-protocol.ts +116 -0
  208. package/src/testing.ts +430 -0
  209. package/src/tooling/declaration-hook.ts +52 -0
  210. package/src/tooling/describe-game.ts +49 -0
  211. package/src/tooling/game-session-broker.ts +7 -0
  212. package/src/tooling/hold-runtime-host.ts +255 -38
  213. package/src/tooling/list-visual-scenarios.ts +19 -62
  214. package/src/tooling/load-game.ts +79 -0
  215. package/src/tooling/process-scope-bootstrap.mjs +24 -0
  216. package/src/tooling/process-scope-guard.ts +213 -0
  217. package/src/tooling/process-scope-windows.ps1 +148 -0
  218. package/src/tooling/rooms-check-device.ts +493 -0
  219. package/src/tooling/run-headless-room.ts +326 -0
  220. package/src/tooling/run-test-profile.ts +190 -0
  221. package/src/tooling/run-visual-capture.ts +37 -23
  222. package/src/tooling/runtime-owner-actions.ts +23 -0
  223. package/src/tooling/seal-game-build.ts +118 -0
  224. package/src/tooling/visual-pack.ts +10 -45
  225. package/src/types.ts +54 -77
  226. package/src/visual.ts +14 -22
  227. package/src/windows-process-scopes.ts +189 -0
  228. package/dist/agent.d.ts +0 -15
  229. package/dist/agent.js +0 -19
  230. package/dist/chunk-5YAARMW5.js +0 -36
  231. package/dist/chunk-5YAARMW5.js.map +0 -1
  232. package/dist/chunk-6WQODT37.js +0 -1019
  233. package/dist/chunk-6WQODT37.js.map +0 -1
  234. package/dist/chunk-CKFT2ZJE.js.map +0 -1
  235. package/dist/chunk-ER3Q2C4G.js +0 -358
  236. package/dist/chunk-ER3Q2C4G.js.map +0 -1
  237. package/dist/chunk-GUEZP773.js.map +0 -1
  238. package/dist/chunk-HIDNI56E.js +0 -33
  239. package/dist/chunk-HIDNI56E.js.map +0 -1
  240. package/dist/chunk-QKXS5D35.js +0 -43
  241. package/dist/chunk-QKXS5D35.js.map +0 -1
  242. package/dist/chunk-S4LSCEVE.js +0 -261
  243. package/dist/chunk-S4LSCEVE.js.map +0 -1
  244. package/dist/chunk-VKMJO6VN.js.map +0 -1
  245. package/dist/chunk-WFUR3MXY.js +0 -67
  246. package/dist/chunk-WFUR3MXY.js.map +0 -1
  247. package/dist/chunk-XEMR7KUE.js +0 -361
  248. package/dist/chunk-XEMR7KUE.js.map +0 -1
  249. package/dist/chunk-ZLPD7FY5.js +0 -191
  250. package/dist/chunk-ZLPD7FY5.js.map +0 -1
  251. package/dist/tooling/agent-contract.js +0 -193
  252. package/dist/tooling/agent-contract.js.map +0 -1
  253. package/dist/tooling/inspect-airjam-agent.js +0 -37
  254. package/dist/tooling/inspect-airjam-agent.js.map +0 -1
  255. package/src/agent.ts +0 -380
  256. package/src/tooling/agent-contract.ts +0 -232
  257. package/src/tooling/agent-declaration.ts +0 -36
  258. package/src/tooling/airjam-agent-inspection.ts +0 -45
  259. package/src/tooling/airjam-agent.ts +0 -118
  260. package/src/tooling/inspect-airjam-agent.ts +0 -20
  261. /package/dist/{agent.js.map → dependencies.js.map} +0 -0
  262. /package/dist/tooling/{agent-contract.d.ts → describe-game.d.ts} +0 -0
  263. /package/dist/tooling/{inspect-airjam-agent.d.ts → game-session-broker.d.ts} +0 -0
@@ -0,0 +1,2358 @@
1
+ import type {
2
+ ControllerLeasedControl,
3
+ ControllerLeasedControlAck,
4
+ } from "@air-jam/sdk/protocol";
5
+ import { PARTICIPANT_CONTROL_DEADLINE_MS } from "@air-jam/sdk/protocol";
6
+ import {
7
+ clipFailureReason,
8
+ describeHostRuntimeFault,
9
+ readHostClip,
10
+ readHostInputLog,
11
+ sameHostRuntimeIdentity,
12
+ type HostAgentRequest,
13
+ type HostAgentResponse,
14
+ type HostObservation,
15
+ } from "@air-jam/sdk/runtime-control";
16
+ import { createHash, randomUUID } from "node:crypto";
17
+ import {
18
+ mkdir,
19
+ open,
20
+ readFile,
21
+ rename,
22
+ type FileHandle,
23
+ } from "node:fs/promises";
24
+ import path from "node:path";
25
+ import { setTimeout as delay } from "node:timers/promises";
26
+ import type { ControllerDisconnection } from "./controller-protocol.js";
27
+ import { CurrentRoomStopped } from "./current-room-host.js";
28
+ import type { DecisionAnswer, DecisionProvider } from "./decision-provider.js";
29
+ import {
30
+ gameBuildIdentitySchema,
31
+ type PinnedGameBuild,
32
+ } from "./game-build-protocol.js";
33
+ import { sealGameBuild, verifyPinnedGameBuild } from "./game-build.js";
34
+ import {
35
+ currentRoomAttachmentSchema,
36
+ gameRunAddressSchema,
37
+ gameRunRecordSchema,
38
+ gameRunSessionIdentitySchema,
39
+ gameRunSteerSchema,
40
+ MAXIMUM_GAME_RUN_MS,
41
+ MAXIMUM_GAME_RUN_STEERING_CHANGES,
42
+ MAXIMUM_GAME_RUN_TRACE_BYTES,
43
+ startGameRunSchema,
44
+ type AirJamGameRunCancellation,
45
+ type AirJamGameRunRecord,
46
+ type CurrentRoomAttachment,
47
+ type GameRunSteerOptions,
48
+ type StartGameRunOptions,
49
+ } from "./game-run-protocol.js";
50
+ import { readGameRunArtifact } from "./game-run-record.js";
51
+ import {
52
+ gameRunWatchRequestSchema,
53
+ type GameRunWatchEvent,
54
+ type GameSurfaceWatcher,
55
+ } from "./game-run-watch.js";
56
+ import { inspectGame } from "./games.js";
57
+ import { startHeadlessRoom, type HeadlessRoom } from "./headless-room.js";
58
+ import {
59
+ assertProcessScopesConfirmed,
60
+ type ProcessScopeObserver,
61
+ } from "./managed-process-scope.js";
62
+ import { verifyPolicyArtifacts } from "./policy-artifacts.js";
63
+ import { startTestProfileProcess } from "./test-profile-process.js";
64
+ import type {
65
+ AirJamDecisionQuestion,
66
+ AirJamPlayControl,
67
+ AirJamPolicyDecision,
68
+ AirJamRunPlayers,
69
+ AirJamRunReceipt,
70
+ AirJamScenarioVerdict,
71
+ AirJamTestProfileDescription,
72
+ } from "./testing.js";
73
+ import { PLAY_RUN_PLAYER } from "./testing.js";
74
+ import type {
75
+ AirJamGameInspection,
76
+ AirJamGameSessionSummary,
77
+ CloseGameSessionResult,
78
+ } from "./types.js";
79
+
80
+ type HostObservationIdentity = HostObservation["identity"];
81
+ type AnsweredDecision = DecisionAnswer & {
82
+ control: AirJamPlayControl;
83
+ durationMs: number;
84
+ note?: "Only option; no model asked.";
85
+ };
86
+
87
+ type EndReason = NonNullable<AirJamGameRunRecord["end"]>["reason"];
88
+ /** Answers below this confidence count as unsure; this many in a row is a stretch. */
89
+ const LOW_CONFIDENCE = 0.6;
90
+ const LOW_CONFIDENCE_STRETCH = 3;
91
+ function agentNickname(index: number) {
92
+ return `Agent ${index + 1}`;
93
+ }
94
+ function failureReason(message: string): EndReason {
95
+ return /trace_budget/.test(message)
96
+ ? "trace_budget"
97
+ : /runtime_replaced|observation_replaced|stale_identity/.test(message)
98
+ ? "runtime_replaced"
99
+ : /seat_replaced/.test(message)
100
+ ? "seat_replaced"
101
+ : "error";
102
+ }
103
+ export type { AirJamGameRunRecord } from "./game-run-protocol.js";
104
+
105
+ export type GameRunParticipant = {
106
+ watch: GameSurfaceWatcher;
107
+ controllerId: string;
108
+ checkConnected: () => Promise<void>;
109
+ observe: (options: {
110
+ scope: "player" | "diagnostic";
111
+ includeImage: boolean;
112
+ expected?: HostObservationIdentity;
113
+ }) => Promise<HostObservation>;
114
+ control: (
115
+ request: Pick<ControllerLeasedControl, "expected" | "lease" | "operation">,
116
+ ) => Promise<ControllerLeasedControlAck>;
117
+ close: () => Promise<ControllerDisconnection>;
118
+ forceClose: () => Promise<ControllerDisconnection>;
119
+ };
120
+ /**
121
+ * The time a run plays on. A live room plays on the wall clock; a headless
122
+ * room's clock is game time, which moves only while the run waits on it.
123
+ */
124
+ export type GameRunClock = {
125
+ now: () => number;
126
+ wait: (ms: number, signal?: AbortSignal) => Promise<void>;
127
+ };
128
+ export const wallClock: GameRunClock = {
129
+ now: () => performance.now(),
130
+ wait: (ms, signal) => delay(ms, undefined, { signal }),
131
+ };
132
+ export type GameRunSession = Omit<
133
+ GameRunParticipant,
134
+ "controllerId" | "close" | "forceClose"
135
+ > & {
136
+ summary: AirJamGameSessionSummary;
137
+ clock: GameRunClock;
138
+ watchHost: GameSurfaceWatcher;
139
+ requestHost?: (
140
+ request: HostAgentRequest,
141
+ timeoutMs: number,
142
+ ) => Promise<HostAgentResponse>;
143
+ readParticipants: () => Promise<{ roomId: string; controllerIds: string[] }>;
144
+ addParticipant: (nickname: string) => Promise<GameRunParticipant>;
145
+ invokeHost: (actionId: string, input: unknown) => Promise<unknown>;
146
+ close: () => Promise<CloseGameSessionResult>;
147
+ forceClose: () => Promise<CloseGameSessionResult>;
148
+ };
149
+ type RunSeat = {
150
+ id: string;
151
+ controllerId: string;
152
+ participant: Pick<
153
+ GameRunParticipant,
154
+ "observe" | "control" | "checkConnected" | "watch"
155
+ >;
156
+ extra?: GameRunParticipant;
157
+ expected?: HostObservationIdentity;
158
+ leaseId: string;
159
+ sequence: number;
160
+ policyCursor: number;
161
+ misses: number;
162
+ staleDecisions: number;
163
+ lowConfidenceStreak: number;
164
+ /** The model's answer to this seat's latest question, for its policy. */
165
+ lastAnswer: { choice: string; confidence: number } | null;
166
+ };
167
+ type Run = {
168
+ record: AirJamGameRunRecord;
169
+ players?: AirJamRunPlayers;
170
+ /** The host's simulation pace when play began, to measure play against. */
171
+ paceStart?: NonNullable<HostObservation["pace"]>;
172
+ attachment?: CurrentRoomAttachment;
173
+ /** The room a headless run plays in, owned by this run. */
174
+ room?: HeadlessRoom;
175
+ /** The session clock's reading when play began. */
176
+ playStartedAt?: number;
177
+ clipStarted?: boolean;
178
+ fromTick?: number;
179
+ directory: string;
180
+ abort: AbortController;
181
+ session?: GameRunSession;
182
+ build?: PinnedGameBuild;
183
+ scopes: Array<() => Promise<void>>;
184
+ watches: Map<string, Promise<void>>;
185
+ policy?: Awaited<ReturnType<typeof startTestProfileProcess>>;
186
+ evaluator?: Awaited<ReturnType<typeof startTestProfileProcess>>;
187
+ evaluation?: Promise<AirJamScenarioVerdict>;
188
+ evaluationCursor: number;
189
+ playEvaluationSent: boolean;
190
+ receiptIndex: number;
191
+ effects: Set<Promise<ControllerLeasedControlAck>>;
192
+ seats: RunSeat[];
193
+ receipts: AirJamRunReceipt[];
194
+ startup?: Promise<void>;
195
+ startupSteps: Set<string>;
196
+ admission?: Promise<void>;
197
+ persistence: Promise<void>;
198
+ tracing: Promise<void>;
199
+ /** Open while the run writes its trace; null once the trace is sealed. */
200
+ traceFile?: FileHandle | null;
201
+ traceBytes: number;
202
+ traceTruncated: boolean;
203
+ termination?: Promise<void>;
204
+ finished: AbortController;
205
+ closed?: CloseGameSessionResult;
206
+ deadline: number;
207
+ timer?: ReturnType<typeof setTimeout>;
208
+ };
209
+
210
+ export class GameRunOwner {
211
+ private runs = new Map<string, Run>();
212
+ private admissions = new Set<Promise<unknown>>();
213
+ private draining = false;
214
+ private stoppingAll: Promise<AirJamGameRunRecord[]> | undefined;
215
+ private directory: string;
216
+ constructor(
217
+ private readonly options: {
218
+ projectDir: string;
219
+ ownerInstanceId: string;
220
+ openSession: (options: {
221
+ runId: string;
222
+ gameId?: string;
223
+ game?: AirJamGameInspection;
224
+ nickname: string;
225
+ settings?: Record<string, number | boolean | string>;
226
+ attachment?: CurrentRoomAttachment;
227
+ build?: PinnedGameBuild;
228
+ room?: HeadlessRoom;
229
+ onScope: ProcessScopeObserver;
230
+ }) => Promise<GameRunSession>;
231
+ sessionClosed: (gameSessionId: string) => void;
232
+ decisions?: DecisionProvider;
233
+ },
234
+ ) {
235
+ this.directory = path.join(
236
+ options.projectDir,
237
+ ".airjam",
238
+ "artifacts",
239
+ "runs",
240
+ );
241
+ }
242
+
243
+ private persist(run: Run) {
244
+ const source = `${JSON.stringify(gameRunRecordSchema.parse(run.record), null, 2)}\n`;
245
+ const pending = run.persistence.then(async () => {
246
+ const temporary = path.join(run.directory, "record.pending.json");
247
+ await open(temporary, "w", 0o600).then(async (file) => {
248
+ try {
249
+ await file.writeFile(source);
250
+ } finally {
251
+ await file.close();
252
+ }
253
+ });
254
+ await rename(temporary, path.join(run.directory, "record.json"));
255
+ });
256
+ run.persistence = pending.catch(() => undefined);
257
+ return pending;
258
+ }
259
+ private trace(run: Run, event: Record<string, unknown>, diagnostic = false) {
260
+ const bytes = Buffer.from(
261
+ `${JSON.stringify({ at: new Date().toISOString(), ...event })}\n`,
262
+ );
263
+ const writing = run.tracing.then(async () => {
264
+ const limit = run.abort.signal.aborted
265
+ ? MAXIMUM_GAME_RUN_TRACE_BYTES
266
+ : MAXIMUM_GAME_RUN_TRACE_BYTES - 131_072;
267
+ if (run.traceBytes + bytes.byteLength > limit) {
268
+ if (diagnostic) return;
269
+ run.traceTruncated = true;
270
+ if (run.abort.signal.aborted) return;
271
+ throw new Error("trace_budget: Run trace reached its byte allowance.");
272
+ }
273
+ if (run.traceFile === null)
274
+ throw new Error("trace_closed: The run trace is already sealed.");
275
+ run.traceFile ??= await open(
276
+ path.join(run.directory, "trace.ndjson"),
277
+ "a",
278
+ 0o600,
279
+ );
280
+ await run.traceFile.writeFile(bytes);
281
+ run.traceBytes += bytes.byteLength;
282
+ });
283
+ // The caller receives failures; the journal must still accept teardown events.
284
+ run.tracing = writing.catch(() => undefined);
285
+ return writing;
286
+ }
287
+ private copy(record: AirJamGameRunRecord): AirJamGameRunRecord {
288
+ return structuredClone(record);
289
+ }
290
+ private quiescent(run: Run) {
291
+ return (
292
+ run.record.state === "ended" &&
293
+ run.record.cleanup?.processesClosed === true &&
294
+ (!run.session ||
295
+ (run.record.cleanup.close?.closed &&
296
+ run.record.cleanup.participantsClosed))
297
+ );
298
+ }
299
+ private observeScopes(run: Run): ProcessScopeObserver {
300
+ return (close) => {
301
+ run.scopes.push(close);
302
+ if (run.abort.signal.aborted)
303
+ void close().catch((error) => console.error(error));
304
+ };
305
+ }
306
+ private prune() {
307
+ const ended = [...this.runs.values()].filter((run) => this.quiescent(run));
308
+ for (const expired of ended.slice(0, Math.max(0, ended.length - 32)))
309
+ this.runs.delete(expired.record.runId);
310
+ }
311
+
312
+ async discover(
313
+ gameId?: string,
314
+ ): Promise<{ gameId: string; profiles: AirJamTestProfileDescription[] }> {
315
+ if (this.draining || this.stoppingAll)
316
+ throw new Error("owner_stopping: Profile discovery admission is closed.");
317
+ if ([...this.runs.values()].some((run) => !this.quiescent(run)))
318
+ throw new Error(
319
+ "run_busy: Wait for the current run to finish before inspecting profiles.",
320
+ );
321
+ assertProcessScopesConfirmed();
322
+ const discovery = (async () => {
323
+ const game = await this.game(gameId);
324
+ await mkdir(this.directory, { recursive: true });
325
+ const policy = await startTestProfileProcess({
326
+ rootDir: game.rootDir,
327
+ configPath: game.configPath,
328
+ seed: 0,
329
+ role: "discover",
330
+ logPath: path.join(this.directory, "discovery.log"),
331
+ });
332
+ try {
333
+ return { gameId: game.id, profiles: policy.profiles };
334
+ } finally {
335
+ await policy.stop();
336
+ }
337
+ })();
338
+ this.admissions.add(discovery);
339
+ try {
340
+ return await discovery;
341
+ } finally {
342
+ this.admissions.delete(discovery);
343
+ }
344
+ }
345
+ private async game(gameId?: string) {
346
+ const game = await inspectGame({ cwd: this.options.projectDir, gameId });
347
+ if (!game?.configPath)
348
+ throw new Error("Choose a game that publishes an Air Jam config.");
349
+ return { ...game, configPath: game.configPath };
350
+ }
351
+
352
+ async start(
353
+ input: StartGameRunOptions,
354
+ attachment?: CurrentRoomAttachment,
355
+ ): Promise<AirJamGameRunRecord> {
356
+ if (this.draining || this.stoppingAll)
357
+ throw new Error("owner_stopping: Run admission is closed.");
358
+ const request = startGameRunSchema.parse({
359
+ ...input,
360
+ cwd: this.options.projectDir,
361
+ });
362
+ const existing = this.runs.get(request.runId);
363
+ if (existing) {
364
+ if (JSON.stringify(existing.record.request) !== JSON.stringify(request))
365
+ throw new Error(
366
+ "run_conflict: Run ID was admitted with a different request.",
367
+ );
368
+ await existing.admission;
369
+ return this.copy(existing.record);
370
+ }
371
+ if (request.target.kind === "current" && !attachment)
372
+ throw new Error(
373
+ "current_attachment_required: Current-room play requires a delegated editor.",
374
+ );
375
+ if (request.target.kind !== "current" && attachment)
376
+ throw new Error(
377
+ "unexpected_attachment: Owned and headless tests do not accept current-room access.",
378
+ );
379
+ const current = attachment
380
+ ? currentRoomAttachmentSchema.parse(attachment)
381
+ : undefined;
382
+ if ([...this.runs.values()].some((run) => !this.quiescent(run)))
383
+ throw new Error(
384
+ "run_busy: This project already has an active or unclosed run.",
385
+ );
386
+ assertProcessScopesConfirmed();
387
+ const priorAdmissions = [...this.admissions];
388
+ const run: Run = {
389
+ attachment: current,
390
+ scopes: [],
391
+ watches: new Map(),
392
+ record: {
393
+ version: 1,
394
+ runId: request.runId,
395
+ ownerInstanceId: this.options.ownerInstanceId,
396
+ request,
397
+ state: "starting",
398
+ startedAt: new Date().toISOString(),
399
+ seats: [],
400
+ evidence: {
401
+ observation: null,
402
+ error: null,
403
+ clip: {
404
+ status: "not-captured",
405
+ reason:
406
+ request.target.kind === "headless"
407
+ ? "headless"
408
+ : "host-unavailable",
409
+ },
410
+ },
411
+ counters: {
412
+ steps: 0,
413
+ applied: 0,
414
+ rejected: 0,
415
+ unconfirmed: 0,
416
+ missed: 0,
417
+ },
418
+ },
419
+ directory: path.join(this.directory, request.runId),
420
+ abort: new AbortController(),
421
+ seats: [],
422
+ startupSteps: new Set(["the game had not been resolved"]),
423
+ evaluationCursor: 0,
424
+ playEvaluationSent: false,
425
+ receiptIndex: 0,
426
+ effects: new Set(),
427
+ receipts: [],
428
+ deadline:
429
+ performance.now() +
430
+ (request.kind === "play"
431
+ ? MAXIMUM_GAME_RUN_MS
432
+ : request.budget.durationMs),
433
+ persistence: Promise.resolve(),
434
+ tracing: Promise.resolve(),
435
+ traceBytes: 0,
436
+ traceTruncated: false,
437
+ finished: new AbortController(),
438
+ };
439
+ this.runs.set(request.runId, run);
440
+ const admission = (async () => {
441
+ await Promise.allSettled(priorAdmissions);
442
+ assertProcessScopesConfirmed();
443
+ await mkdir(this.directory, { recursive: true });
444
+ try {
445
+ await mkdir(run.directory, { mode: 0o700 });
446
+ } catch (error) {
447
+ if (
448
+ !(error instanceof Error) ||
449
+ !("code" in error) ||
450
+ error.code !== "EEXIST"
451
+ )
452
+ throw error;
453
+ try {
454
+ await readFile(path.join(run.directory, "cancelled.json"));
455
+ throw new Error(
456
+ "run_cancelled: This run ID was fenced before admission.",
457
+ );
458
+ } catch (error) {
459
+ if (
460
+ !(error instanceof Error) ||
461
+ !("code" in error) ||
462
+ error.code !== "ENOENT"
463
+ )
464
+ throw error;
465
+ }
466
+ const retained = gameRunRecordSchema.parse(
467
+ JSON.parse(
468
+ await readFile(path.join(run.directory, "record.json"), "utf8"),
469
+ ),
470
+ );
471
+ if (retained.ownerInstanceId !== this.options.ownerInstanceId)
472
+ throw new Error(
473
+ "run_id_reused: A previous owner admitted this run ID.",
474
+ );
475
+ if (JSON.stringify(retained.request) !== JSON.stringify(request))
476
+ throw new Error(
477
+ "run_conflict: Run ID was admitted with a different request.",
478
+ );
479
+ if (retained.state !== "ended")
480
+ throw new Error(
481
+ "run_receipt_invalid: Retained run has no live activity or terminal receipt.",
482
+ );
483
+ run.record = retained;
484
+ return;
485
+ }
486
+ await this.persist(run);
487
+ })();
488
+ run.admission = admission;
489
+ this.admissions.add(admission);
490
+ try {
491
+ await admission;
492
+ } catch (error) {
493
+ this.runs.delete(request.runId);
494
+ throw error;
495
+ } finally {
496
+ this.admissions.delete(admission);
497
+ }
498
+ if (run.record.state === "ended") {
499
+ this.prune();
500
+ return this.copy(run.record);
501
+ }
502
+ if (run.abort.signal.aborted || this.draining) {
503
+ await this.terminate(
504
+ run,
505
+ "owner_stopping",
506
+ "Run admission stopped before startup.",
507
+ );
508
+ return this.copy(run.record);
509
+ }
510
+ run.timer = setTimeout(
511
+ () => {
512
+ void this.terminate(
513
+ run,
514
+ run.record.request.kind === "play" ? "safety_deadline" : "budget",
515
+ run.record.request.kind === "play"
516
+ ? "Play reached its ten-minute safety deadline."
517
+ : this.startupBudgetMessage(run),
518
+ ).catch((error) => console.error(error));
519
+ },
520
+ Math.max(0, run.deadline - performance.now()),
521
+ );
522
+ run.startup = this.initialize(run);
523
+ void run.startup.then(
524
+ () => {
525
+ if (!run.abort.signal.aborted)
526
+ void this.play(run).catch((error) => this.failed(run, error));
527
+ },
528
+ (error) => this.failed(run, error),
529
+ );
530
+ return this.copy(run.record);
531
+ }
532
+
533
+ async read(runId: string): Promise<AirJamGameRunRecord> {
534
+ const run = this.runs.get(runId);
535
+ if (run) {
536
+ if (run.record.state === "ended") await run.termination;
537
+ return this.copy(run.record);
538
+ }
539
+ const source = await readFile(
540
+ path.join(this.directory, runId, "record.json"),
541
+ "utf8",
542
+ );
543
+ const record = gameRunRecordSchema.parse(JSON.parse(source));
544
+ if (
545
+ record.ownerInstanceId !== this.options.ownerInstanceId &&
546
+ record.state !== "ended"
547
+ )
548
+ return {
549
+ ...record,
550
+ state: "ended" as const,
551
+ end: {
552
+ reason: "owner_lost" as const,
553
+ ...(record.request.kind === "test"
554
+ ? { outcome: "inconclusive" as const }
555
+ : {}),
556
+ message:
557
+ "The session owner was replaced. This run cannot resume and has no confirmed teardown.",
558
+ },
559
+ };
560
+ return record;
561
+ }
562
+ list(): AirJamGameRunRecord[] {
563
+ return [...this.runs.values()].map((run) => this.copy(run.record));
564
+ }
565
+ async wait(
566
+ runId: string,
567
+ timeoutMs: number,
568
+ signal?: AbortSignal,
569
+ ): Promise<AirJamGameRunRecord> {
570
+ const run = this.runs.get(runId);
571
+ if (!run || run.record.state === "ended") return this.read(runId);
572
+ const cancellation = new AbortController();
573
+ const combined = signal
574
+ ? AbortSignal.any([signal, cancellation.signal])
575
+ : cancellation.signal;
576
+ let completed = () => {};
577
+ const finished = new Promise<void>((resolve) => {
578
+ completed = resolve;
579
+ run.finished.signal.addEventListener("abort", completed, { once: true });
580
+ });
581
+ try {
582
+ await Promise.race([
583
+ finished,
584
+ delay(timeoutMs, undefined, { signal: combined }),
585
+ ]);
586
+ return await this.read(runId);
587
+ } finally {
588
+ cancellation.abort();
589
+ run.finished.signal.removeEventListener("abort", completed);
590
+ }
591
+ }
592
+ async stop(
593
+ runId: string,
594
+ reason: EndReason = "stopped",
595
+ ): Promise<AirJamGameRunRecord> {
596
+ const run = this.runs.get(runId);
597
+ if (!run || run.record.state === "ended") return this.read(runId);
598
+ run.record.stopRequestedAt ??= new Date().toISOString();
599
+ await this.terminate(
600
+ run,
601
+ reason,
602
+ reason === "stopped" ? "Stopped by the caller." : reason,
603
+ );
604
+ return this.copy(run.record);
605
+ }
606
+ /**
607
+ * Change what one seat is trying to do while its run is active. Steering only
608
+ * changes the intent its policy reads; controls still come from the policy.
609
+ * Each change is recorded with its time and source.
610
+ */
611
+ async steer(input: GameRunSteerOptions): Promise<AirJamGameRunRecord> {
612
+ const { runId, seatId, intent, source } = gameRunSteerSchema.parse(input);
613
+ const run = this.runs.get(runId);
614
+ if (
615
+ !run ||
616
+ run.abort.signal.aborted ||
617
+ run.record.state === "ended" ||
618
+ run.record.state === "stopping"
619
+ )
620
+ throw new Error("run_not_active: Only an active test can be steered.");
621
+ if (!run.record.seats.length)
622
+ throw new Error(
623
+ "run_not_active: Seats are not ready yet; give starting goals as intents.",
624
+ );
625
+ const seat = run.record.seats.find(
626
+ (candidate) => candidate.seatId === seatId,
627
+ );
628
+ if (!seat)
629
+ throw new Error(`run_seat_unknown: Run ${runId} has no seat ${seatId}.`);
630
+ const steering = (run.record.steering ??= []);
631
+ if (steering.length >= MAXIMUM_GAME_RUN_STEERING_CHANGES)
632
+ throw new Error(
633
+ `steering_limit: A run records at most ${MAXIMUM_GAME_RUN_STEERING_CHANGES} steering changes.`,
634
+ );
635
+ seat.intent = intent;
636
+ steering.push({ at: new Date().toISOString(), seatId, intent, source });
637
+ await this.trace(run, { kind: "steer", seatId, intent, source });
638
+ await this.persist(run);
639
+ return this.copy(run.record);
640
+ }
641
+ stopAll(): Promise<AirJamGameRunRecord[]> {
642
+ return (this.stoppingAll ??= (async () => {
643
+ await Promise.allSettled(this.admissions);
644
+ const pending = [...this.runs.values()].filter(
645
+ (run) => !this.quiescent(run),
646
+ );
647
+ const records = await Promise.all(
648
+ pending.map((run) => this.stop(run.record.runId)),
649
+ );
650
+ assertProcessScopesConfirmed();
651
+ return records;
652
+ })().finally(() => {
653
+ this.stoppingAll = undefined;
654
+ }));
655
+ }
656
+ async cancel(runId: string): Promise<AirJamGameRunCancellation> {
657
+ gameRunAddressSchema.parse({ runId });
658
+ const result = (record: AirJamGameRunRecord | null) => ({
659
+ runId,
660
+ ownerInstanceId: this.options.ownerInstanceId,
661
+ fenced: true as const,
662
+ record,
663
+ });
664
+ if (this.runs.has(runId)) return result(await this.stop(runId));
665
+ assertProcessScopesConfirmed();
666
+ await mkdir(this.directory, { recursive: true });
667
+ const directory = path.join(this.directory, runId);
668
+ try {
669
+ await mkdir(directory, { mode: 0o700 });
670
+ } catch (error) {
671
+ if (
672
+ !(error instanceof Error) ||
673
+ !("code" in error) ||
674
+ error.code !== "EEXIST"
675
+ )
676
+ throw error;
677
+ if (this.runs.has(runId)) return result(await this.stop(runId));
678
+ try {
679
+ return result(await this.read(runId));
680
+ } catch (readError) {
681
+ if (
682
+ !(readError instanceof Error) ||
683
+ !("code" in readError) ||
684
+ readError.code !== "ENOENT"
685
+ )
686
+ throw readError;
687
+ }
688
+ }
689
+ const marker = await open(
690
+ path.join(directory, "cancelled.json"),
691
+ "wx",
692
+ 0o600,
693
+ ).catch((error: NodeJS.ErrnoException) => {
694
+ if (error.code === "EEXIST") return null;
695
+ throw error;
696
+ });
697
+ if (marker) {
698
+ try {
699
+ await marker.writeFile(
700
+ JSON.stringify({ runId, cancelledAt: new Date().toISOString() }),
701
+ );
702
+ } finally {
703
+ await marker.close();
704
+ }
705
+ }
706
+ return result(null);
707
+ }
708
+ async closeSession(runId: string, reason: EndReason) {
709
+ const run = this.runs.get(runId);
710
+ if (!run)
711
+ throw new Error(
712
+ "run_session_unavailable: No live activity owns this session.",
713
+ );
714
+ await this.terminate(run, reason, reason);
715
+ if (!this.quiescent(run) || !run.closed?.closed)
716
+ throw new Error(
717
+ "run_cleanup_unconfirmed: Local runtime teardown was not confirmed.",
718
+ );
719
+ return run.closed;
720
+ }
721
+ async drain() {
722
+ this.draining = true;
723
+ await Promise.allSettled(this.admissions);
724
+ const results = await Promise.allSettled(
725
+ [...this.runs.values()].map((run) =>
726
+ this.terminate(run, "owner_stopping", "Session owner is stopping."),
727
+ ),
728
+ );
729
+ const failures = results.flatMap((result) =>
730
+ result.status === "rejected" ? [result.reason] : [],
731
+ );
732
+ if (failures.length)
733
+ throw new AggregateError(failures, "Run cleanup failed.");
734
+ if ([...this.runs.values()].some((run) => !this.quiescent(run)))
735
+ throw new Error(
736
+ "run_cleanup_unconfirmed: An owned process scope did not close.",
737
+ );
738
+ assertProcessScopesConfirmed();
739
+ }
740
+
741
+ private startupBudgetMessage(run: Run) {
742
+ return run.startupSteps.size
743
+ ? `Run reached its time budget during startup: ${[...run.startupSteps].join("; ")}.`
744
+ : "Run reached its time budget.";
745
+ }
746
+
747
+ private async initialize(run: Run) {
748
+ const game = await this.game(run.record.request.gameId);
749
+ if (run.abort.signal.aborted) return;
750
+ run.startupSteps.delete("the game had not been resolved");
751
+ await this.trace(run, { kind: "game_resolved", gameId: game.id });
752
+ if (run.record.request.target.kind === "owned") {
753
+ run.startupSteps.add("the build had not been sealed or reused");
754
+ run.build = await sealGameBuild({
755
+ projectDir: game.rootDir,
756
+ configRelative: path.relative(game.rootDir, game.configPath),
757
+ runDirectory: run.directory,
758
+ signal: run.abort.signal,
759
+ onScope: this.observeScopes(run),
760
+ onBuildLog: (receipt) => {
761
+ run.record.evidence ??= { observation: null, error: null };
762
+ run.record.evidence.buildLog = {
763
+ ...receipt,
764
+ path: `.airjam/artifacts/runs/${run.record.runId}/build.log`,
765
+ };
766
+ },
767
+ });
768
+ run.record.build = {
769
+ ...gameBuildIdentitySchema.parse(run.build.manifest),
770
+ integrity: "sealed",
771
+ };
772
+ run.startupSteps.delete("the build had not been sealed or reused");
773
+ await this.trace(run, {
774
+ kind: "build_sealed",
775
+ build: run.record.build,
776
+ reused: run.build.reused,
777
+ });
778
+ await this.persist(run);
779
+ }
780
+ if (run.abort.signal.aborted) return;
781
+ const common = {
782
+ rootDir: run.build?.rootDir ?? game.rootDir,
783
+ ...(run.build ? { toolingRootDir: run.build.rootDir } : {}),
784
+ configPath: run.build?.configPath ?? game.configPath,
785
+ runKind: run.record.request.kind,
786
+ ...(run.record.request.kind === "test"
787
+ ? { profileId: run.record.request.profileId }
788
+ : {}),
789
+ seed: run.record.request.seed,
790
+ onScope: this.observeScopes(run),
791
+ startupSignal: run.abort.signal,
792
+ };
793
+ // The room starts alongside the profile processes; it needs only the game.
794
+ const room =
795
+ run.record.request.target.kind === "headless"
796
+ ? startHeadlessRoom({
797
+ rootDir: common.rootDir,
798
+ configPath: common.configPath,
799
+ seed: run.record.request.seed,
800
+ settings:
801
+ run.record.request.kind === "test"
802
+ ? run.record.request.settings
803
+ : undefined,
804
+ logPath: path.join(run.directory, "room.log"),
805
+ onScope: common.onScope,
806
+ startupSignal: run.abort.signal,
807
+ })
808
+ : undefined;
809
+ room?.catch(() => undefined);
810
+ const request = run.record.request;
811
+ let profile: AirJamTestProfileDescription | undefined;
812
+ if (request.kind === "test") {
813
+ run.startupSteps.add("the evaluator had not started");
814
+ run.evaluator = await startTestProfileProcess({
815
+ ...common,
816
+ role: "evaluator",
817
+ logPath: path.join(run.directory, "evaluator.log"),
818
+ });
819
+ if (run.abort.signal.aborted) return;
820
+ run.startupSteps.delete("the evaluator had not started");
821
+ await this.trace(run, { kind: "evaluator_started" });
822
+ profile = run.evaluator.profiles.find(
823
+ (candidate) => candidate.id === request.profileId,
824
+ );
825
+ if (!profile) throw new Error("Unknown test profile.");
826
+ const seats = profile.seats;
827
+ const unknownIntent = Object.keys(request.intents ?? {}).find(
828
+ (seatId) => !seats.some((seat) => seat.id === seatId),
829
+ );
830
+ if (unknownIntent)
831
+ throw new Error(
832
+ `run_intent_invalid: Profile ${profile.id} has no seat ${unknownIntent}.`,
833
+ );
834
+ run.record.profile = profile;
835
+ }
836
+ const players = profile ?? PLAY_RUN_PLAYER;
837
+ run.players = players;
838
+ if (run.attachment && players.seats.length > run.attachment.seats)
839
+ throw new Error(
840
+ "current_profile_invalid: The creator's room issued too few seats.",
841
+ );
842
+ const policy =
843
+ request.kind === "test"
844
+ ? profile?.policies.find(
845
+ (candidate) => candidate.id === request.policyId,
846
+ )
847
+ : { id: "model", label: "Decision model", artifacts: undefined };
848
+ if (!policy) throw new Error("Unknown test policy.");
849
+ run.startupSteps.add("the policy had not been prepared");
850
+ const artifacts =
851
+ policy.artifacts === undefined
852
+ ? undefined
853
+ : await verifyPolicyArtifacts({
854
+ projectDir: common.rootDir,
855
+ manifestPath: path.join(common.rootDir, policy.artifacts),
856
+ artifactRootDir: process.env.AIRJAM_TEST_ARTIFACTS_DIR,
857
+ signal: run.abort.signal,
858
+ });
859
+ run.record.policyArtifacts = artifacts?.receipt;
860
+ const preparing = (async () => {
861
+ const initializing = performance.now();
862
+ run.policy = await startTestProfileProcess({
863
+ ...common,
864
+ role: "policy",
865
+ initializationDeadline: run.deadline,
866
+ ...(artifacts ? { artifacts } : {}),
867
+ policyId: policy.id,
868
+ logPath: path.join(run.directory, "policy.log"),
869
+ });
870
+ if (run.abort.signal.aborted) return;
871
+ run.record.policyInitializationMs = performance.now() - initializing;
872
+ run.record.policyPreparation = run.policy.preparation;
873
+ run.startupSteps.delete("the policy had not been prepared");
874
+ await this.trace(run, {
875
+ kind: "policy_prepared",
876
+ initializationMs: run.record.policyInitializationMs,
877
+ preparation: run.policy.preparation,
878
+ ...(artifacts ? { artifacts: artifacts.receipt } : {}),
879
+ });
880
+ })();
881
+ run.startupSteps.add("the session had not opened");
882
+ const attaching = (async () => {
883
+ if (run.abort.signal.aborted) return;
884
+ if (room) {
885
+ run.room = await room;
886
+ if (run.abort.signal.aborted) return;
887
+ }
888
+ run.session = await this.options.openSession({
889
+ runId: run.record.runId,
890
+ gameId: game.id,
891
+ game,
892
+ nickname: agentNickname(0),
893
+ settings:
894
+ run.record.request.kind === "test"
895
+ ? run.record.request.settings
896
+ : undefined,
897
+ attachment: run.attachment,
898
+ build: run.build,
899
+ room: run.room,
900
+ onScope: this.observeScopes(run),
901
+ });
902
+ if (run.abort.signal.aborted) return;
903
+ run.startupSteps.delete("the session had not opened");
904
+ await this.trace(run, {
905
+ kind: "session_opened",
906
+ gameSessionId: run.session.summary.gameSessionId,
907
+ });
908
+ run.startupSteps.add("the participants had not become ready");
909
+ run.record.session = gameRunSessionIdentitySchema.parse(
910
+ run.session.summary,
911
+ );
912
+ if (
913
+ run.attachment &&
914
+ (run.session.summary.semanticAccess !== "delegated-host" ||
915
+ run.session.summary.roomId !==
916
+ new URL(run.attachment.controllerJoinUrl).searchParams.get("room"))
917
+ )
918
+ throw new Error(
919
+ "current_room_scope: The delegated participant did not attach to its authorized room.",
920
+ );
921
+ for (const [index, description] of players.seats.entries()) {
922
+ if (index > 0 && run.abort.signal.aborted) return;
923
+ const extra =
924
+ index === 0
925
+ ? undefined
926
+ : await run.session.addParticipant(agentNickname(index));
927
+ const controllerId =
928
+ extra?.controllerId ?? run.session.summary.controllerId;
929
+ run.seats.push({
930
+ id: description.id,
931
+ controllerId,
932
+ participant: extra ?? run.session,
933
+ extra,
934
+ leaseId: randomUUID(),
935
+ sequence: 0,
936
+ policyCursor: 0,
937
+ misses: 0,
938
+ staleDecisions: 0,
939
+ lowConfidenceStreak: 0,
940
+ lastAnswer: null,
941
+ });
942
+ run.record.seats.push({
943
+ seatId: description.id,
944
+ controllerId,
945
+ intent:
946
+ request.kind === "play"
947
+ ? (request.intent ?? null)
948
+ : (request.intents?.[description.id] ?? null),
949
+ counters: {
950
+ decisions: 0,
951
+ applied: 0,
952
+ rejected: 0,
953
+ unconfirmed: 0,
954
+ timeout: 0,
955
+ blocked: 0,
956
+ effects: 0,
957
+ },
958
+ });
959
+ }
960
+ if (run.abort.signal.aborted) return;
961
+ run.record.state = "setup";
962
+ for (const seat of run.seats) {
963
+ const first = await this.observe(run, seat, false);
964
+ seat.expected = first.identity;
965
+ this.seatRecord(run, seat).expected = first.identity;
966
+ if (seat === run.seats[0]) {
967
+ run.record.expected = first.identity;
968
+ run.fromTick = first.ticks.after ?? 0;
969
+ }
970
+ if (run.abort.signal.aborted) return;
971
+ if (
972
+ (await this.control(run, seat, first, { kind: "release" }, "setup"))
973
+ .status !== "applied"
974
+ )
975
+ throw new Error(
976
+ "Participant control handshake was not acknowledged.",
977
+ );
978
+ }
979
+ const expectedParticipants = run.seats.map((seat) => seat.controllerId);
980
+ const participantsDeadline = performance.now() + 5000;
981
+ let participants = await run.session.readParticipants();
982
+ while (
983
+ !expectedParticipants.every((id) =>
984
+ participants.controllerIds.includes(id),
985
+ )
986
+ ) {
987
+ if (run.abort.signal.aborted) return;
988
+ if (performance.now() >= participantsDeadline)
989
+ throw new Error(
990
+ "seat_replaced: The connected room roster did not include every run player.",
991
+ );
992
+ await delay(25);
993
+ participants = await run.session.readParticipants();
994
+ }
995
+ if (run.abort.signal.aborted) return;
996
+ if (
997
+ participants.roomId !== run.session.summary.roomId ||
998
+ (run.record.request.target.kind !== "current" &&
999
+ participants.controllerIds.length !== expectedParticipants.length)
1000
+ )
1001
+ throw new Error(
1002
+ "seat_replaced: Owned room membership does not match its controlled players.",
1003
+ );
1004
+ run.startupSteps.delete("the participants had not become ready");
1005
+ run.record.rosterJoinedAt = new Date().toISOString();
1006
+ await this.trace(run, {
1007
+ kind: "participants_ready",
1008
+ gameSessionId: run.session.summary.gameSessionId,
1009
+ expected: run.record.expected,
1010
+ ...participants,
1011
+ });
1012
+ })();
1013
+ const startup = await Promise.allSettled([preparing, attaching]);
1014
+ for (const result of startup)
1015
+ if (result.status === "rejected") throw result.reason;
1016
+ if (run.abort.signal.aborted) return;
1017
+ const session = run.session;
1018
+ if (!session)
1019
+ throw new Error("Run participant attachment did not complete.");
1020
+ run.startupSteps.add("the profile setup had not finished");
1021
+ if (
1022
+ !(await this.runProfileSteps(run, session, profile?.setup ?? [], "setup"))
1023
+ )
1024
+ return;
1025
+ await this.persist(run);
1026
+ run.startupSteps.delete("the profile setup had not finished");
1027
+ }
1028
+ /**
1029
+ * A profile's setup or hand-back steps, in order. Setup stops with the run
1030
+ * and its startup budget and retries a stale participant action until then;
1031
+ * hand-back runs after play has stopped and retries a stale action twice.
1032
+ * Returns false when setup stopped early.
1033
+ */
1034
+ private async runProfileSteps(
1035
+ run: Run,
1036
+ session: GameRunSession,
1037
+ steps: AirJamTestProfileDescription["setup"],
1038
+ phase: "setup" | "cleanup",
1039
+ ) {
1040
+ const name = phase === "setup" ? "Setup" : "Hand-back";
1041
+ for (const step of steps) {
1042
+ if (phase === "setup" && run.abort.signal.aborted) return false;
1043
+ if (step.lane === "host") {
1044
+ const result = await session.invokeHost(step.actionId, step.input);
1045
+ await this.trace(run, {
1046
+ kind: phase === "setup" ? "host_setup" : "host_hand_back",
1047
+ actionId: step.actionId,
1048
+ result,
1049
+ });
1050
+ continue;
1051
+ }
1052
+ const seat = run.seats.find((candidate) => candidate.id === step.seatId);
1053
+ if (!seat) throw new Error(`${name} seat is not initialized.`);
1054
+ for (let attempt = 1; ; attempt++) {
1055
+ if (phase === "setup") {
1056
+ if (run.abort.signal.aborted) return false;
1057
+ if (performance.now() >= run.deadline) {
1058
+ // Teardown waits for startup, so it cannot be awaited here.
1059
+ void this.terminate(
1060
+ run,
1061
+ "budget",
1062
+ this.startupBudgetMessage(run),
1063
+ ).catch((error) => console.error(error));
1064
+ return false;
1065
+ }
1066
+ }
1067
+ const observation = await this.observe(run, seat, false);
1068
+ const receipt = await this.control(
1069
+ run,
1070
+ seat,
1071
+ observation,
1072
+ {
1073
+ kind: "action",
1074
+ actionId: step.actionId,
1075
+ input: step.input,
1076
+ deadlineMs: this.deadline(observation),
1077
+ },
1078
+ phase,
1079
+ );
1080
+ if (
1081
+ receipt.status === "rejected" &&
1082
+ receipt.reason === "stale_decision" &&
1083
+ (phase === "setup" || attempt < 3)
1084
+ )
1085
+ continue;
1086
+ if (
1087
+ receipt.status !== "applied" ||
1088
+ receipt.operation.kind !== "action" ||
1089
+ !receipt.operation.result.ok
1090
+ )
1091
+ throw new Error(`${name} action ${step.actionId} was not accepted.`);
1092
+ break;
1093
+ }
1094
+ }
1095
+ return true;
1096
+ }
1097
+ async watch(
1098
+ input: unknown,
1099
+ onEvent: (event: GameRunWatchEvent) => void,
1100
+ signal: AbortSignal,
1101
+ ) {
1102
+ const request = gameRunWatchRequestSchema.parse(input);
1103
+ assertProcessScopesConfirmed();
1104
+ const run = this.runs.get(request.runId);
1105
+ if (
1106
+ !run ||
1107
+ run.record.request.target.kind !== "owned" ||
1108
+ !run.session ||
1109
+ !["setup", "playing"].includes(run.record.state)
1110
+ )
1111
+ throw new Error(
1112
+ "run_watch_unavailable: Only an active owned game can be watched.",
1113
+ );
1114
+ const surfaceKey = JSON.stringify(request.surface);
1115
+ if (run.watches.has(surfaceKey))
1116
+ throw new Error(
1117
+ "run_watch_duplicate: This surface already has a producer.",
1118
+ );
1119
+ if (run.watches.size >= 2)
1120
+ throw new Error("run_watch_limit: At most two surfaces can be produced.");
1121
+ const watcher =
1122
+ request.surface.kind === "host"
1123
+ ? run.session.watchHost
1124
+ : (() => {
1125
+ const seat = run.seats.find(
1126
+ (candidate) =>
1127
+ request.surface.kind === "controller" &&
1128
+ candidate.id === request.surface.seatId,
1129
+ );
1130
+ if (!seat)
1131
+ throw new Error(
1132
+ "run_watch_seat: This player does not belong to the run.",
1133
+ );
1134
+ return seat.participant.watch;
1135
+ })();
1136
+ const active = AbortSignal.any([signal, run.abort.signal]);
1137
+ active.throwIfAborted();
1138
+ run.record.watched = true;
1139
+ const operation = (async () => {
1140
+ await this.persist(run);
1141
+ await this.trace(
1142
+ run,
1143
+ { kind: "watch_started", surface: request.surface },
1144
+ true,
1145
+ );
1146
+ try {
1147
+ await watcher((event) => {
1148
+ if (active.aborted) return;
1149
+ onEvent(
1150
+ event.type === "ready"
1151
+ ? { ...event, runId: request.runId, surface: request.surface }
1152
+ : event,
1153
+ );
1154
+ }, active);
1155
+ } catch (error) {
1156
+ await this.trace(
1157
+ run,
1158
+ {
1159
+ kind: "watch_failed",
1160
+ surface: request.surface,
1161
+ message: error instanceof Error ? error.message : String(error),
1162
+ },
1163
+ true,
1164
+ );
1165
+ throw error;
1166
+ } finally {
1167
+ await this.trace(
1168
+ run,
1169
+ { kind: "watch_stopped", surface: request.surface },
1170
+ true,
1171
+ );
1172
+ }
1173
+ })();
1174
+ run.watches.set(surfaceKey, operation);
1175
+ try {
1176
+ await operation;
1177
+ } finally {
1178
+ run.watches.delete(surfaceKey);
1179
+ }
1180
+ }
1181
+ private seatRecord(run: Run, seat: RunSeat) {
1182
+ const record = run.record.seats.find(
1183
+ (candidate) => candidate.seatId === seat.id,
1184
+ );
1185
+ if (!record) throw new Error("Run seat has no receipt record.");
1186
+ return record;
1187
+ }
1188
+ private elapsed(run: Run) {
1189
+ if (!run.session || run.playStartedAt === undefined)
1190
+ throw new Error("Run play has not started.");
1191
+ return run.session.clock.now() - run.playStartedAt;
1192
+ }
1193
+ /**
1194
+ * Answer a seat's question and keep that seat's running summary of how the
1195
+ * model played it: what it chose, what it missed, and stretches where it
1196
+ * stayed unsure, which often means the brief or the game was unclear.
1197
+ */
1198
+ private async answerFor(
1199
+ run: Run,
1200
+ seat: RunSeat,
1201
+ question: AirJamDecisionQuestion,
1202
+ deadline: number,
1203
+ ) {
1204
+ const record = this.seatRecord(run, seat);
1205
+ const answers = (record.answers ??= {
1206
+ asked: 0,
1207
+ answered: 0,
1208
+ missed: 0,
1209
+ lowConfidence: 0,
1210
+ lowConfidenceStretches: 0,
1211
+ choices: {},
1212
+ });
1213
+ answers.asked++;
1214
+ let answer: AnsweredDecision;
1215
+ try {
1216
+ answer = await this.answer(run, question, deadline);
1217
+ } catch (error) {
1218
+ answers.missed++;
1219
+ throw error;
1220
+ }
1221
+ answers.answered++;
1222
+ answers.choices[answer.choice] = (answers.choices[answer.choice] ?? 0) + 1;
1223
+ if (answer.note) {
1224
+ answers.automatic = (answers.automatic ?? 0) + 1;
1225
+ return answer;
1226
+ }
1227
+ if (answer.confidence < LOW_CONFIDENCE) {
1228
+ answers.lowConfidence++;
1229
+ if (++seat.lowConfidenceStreak === LOW_CONFIDENCE_STRETCH)
1230
+ answers.lowConfidenceStretches++;
1231
+ } else seat.lowConfidenceStreak = 0;
1232
+ return answer;
1233
+ }
1234
+ /**
1235
+ * Take the only option directly, or put the question to the run's decision
1236
+ * model and map its choice back to the option's own control.
1237
+ * It shares the policy's decision deadline, and
1238
+ * a late, failed or undeclared answer is a missed decision, never a fallback.
1239
+ */
1240
+ private async answer(
1241
+ run: Run,
1242
+ question: AirJamDecisionQuestion,
1243
+ deadline: number,
1244
+ ): Promise<AnsweredDecision> {
1245
+ const options = Object.entries(question.options);
1246
+ if (options.length === 1) {
1247
+ const [choice, option] = options[0];
1248
+ return {
1249
+ choice,
1250
+ confidence: 1,
1251
+ control: option.control,
1252
+ durationMs: 0,
1253
+ note: "Only option; no model asked.",
1254
+ };
1255
+ }
1256
+ const decisions = this.options.decisions;
1257
+ if (!decisions)
1258
+ throw new Error(
1259
+ "decision_provider_unavailable: This run's policy asks a decision model, but none is configured.",
1260
+ );
1261
+ const remaining = deadline - performance.now();
1262
+ if (remaining <= 0)
1263
+ throw new Error("policy_timeout: Decision exceeded its deadline.");
1264
+ run.record.decisionModel ??= decisions.model;
1265
+ const started = performance.now();
1266
+ const timeout = AbortSignal.timeout(Math.ceil(remaining));
1267
+ let answered: DecisionAnswer;
1268
+ try {
1269
+ answered = await decisions.ask(
1270
+ question,
1271
+ AbortSignal.any([run.abort.signal, timeout]),
1272
+ );
1273
+ } catch (error) {
1274
+ if (timeout.aborted)
1275
+ throw new Error(
1276
+ "policy_timeout: Decision model exceeded its deadline.",
1277
+ );
1278
+ throw new Error(
1279
+ `decision_failed: ${error instanceof Error ? error.message : String(error)}`,
1280
+ );
1281
+ }
1282
+ const option = Object.hasOwn(question.options, answered.choice)
1283
+ ? question.options[answered.choice]
1284
+ : undefined;
1285
+ if (!option)
1286
+ throw new Error(
1287
+ "decision_failed: Decision model chose an option the policy did not offer.",
1288
+ );
1289
+ return {
1290
+ ...answered,
1291
+ control: option.control,
1292
+ durationMs: performance.now() - started,
1293
+ };
1294
+ }
1295
+ private async startClip(run: Run) {
1296
+ run.record.evidence ??= { observation: null, error: null };
1297
+ if (run.room) {
1298
+ run.record.evidence.clip = { status: "not-captured", reason: "headless" };
1299
+ return;
1300
+ }
1301
+ const expected = run.record.expected;
1302
+ try {
1303
+ if (!run.session?.requestHost || !expected)
1304
+ throw new Error("No host-agent request path is available.");
1305
+ const response = await run.session.requestHost(
1306
+ {
1307
+ operation: "clip-start",
1308
+ roomId: expected.roomId,
1309
+ runtimeId: expected.runtimeId,
1310
+ clipId: run.record.runId,
1311
+ },
1312
+ 5000,
1313
+ );
1314
+ if (
1315
+ response.operation !== "clip-start" ||
1316
+ response.clipId !== run.record.runId
1317
+ )
1318
+ throw new Error("Invalid clip start response.");
1319
+ run.clipStarted = true;
1320
+ await this.trace(
1321
+ run,
1322
+ {
1323
+ kind: "clip-start",
1324
+ clipId: run.record.runId,
1325
+ },
1326
+ true,
1327
+ ).catch(() => {});
1328
+ } catch (error) {
1329
+ run.record.evidence.clip = {
1330
+ status: "not-captured",
1331
+ reason: clipFailureReason(error),
1332
+ };
1333
+ await this.trace(
1334
+ run,
1335
+ {
1336
+ kind: "clip-failure",
1337
+ reason: clipFailureReason(error),
1338
+ message: error instanceof Error ? error.message : String(error),
1339
+ },
1340
+ true,
1341
+ ).catch(() => {});
1342
+ }
1343
+ }
1344
+
1345
+ private async finishClip(run: Run) {
1346
+ run.record.evidence ??= { observation: null, error: null };
1347
+ run.record.evidence.clip ??= {
1348
+ status: "not-captured",
1349
+ reason: run.room ? "headless" : "host-unavailable",
1350
+ };
1351
+ if (!run.clipStarted) return;
1352
+ try {
1353
+ const session = run.session;
1354
+ const expected = run.record.expected;
1355
+ if (!session?.requestHost || !expected)
1356
+ throw new Error("No recording host is available.");
1357
+ const result = await readHostClip(
1358
+ (request) => session.requestHost!(request, 5000),
1359
+ run.record.runId,
1360
+ expected,
1361
+ );
1362
+ if (result.status === "not-captured") {
1363
+ run.record.evidence.clip = result;
1364
+ return;
1365
+ }
1366
+ const source = `${JSON.stringify(result.artifact)}\n`;
1367
+ const file = await open(
1368
+ path.join(run.directory, "clip.json"),
1369
+ "w",
1370
+ 0o600,
1371
+ );
1372
+ try {
1373
+ await file.writeFile(source);
1374
+ } finally {
1375
+ await file.close();
1376
+ }
1377
+ run.record.evidence.clip = {
1378
+ status: "captured",
1379
+ path: `.airjam/artifacts/runs/${run.record.runId}/clip.json`,
1380
+ sha256: createHash("sha256").update(source).digest("hex"),
1381
+ bytes: Buffer.byteLength(source),
1382
+ frames: result.artifact.frames.length,
1383
+ durationMs: result.artifact.durationMs,
1384
+ };
1385
+ } catch (error) {
1386
+ run.record.evidence.clip = {
1387
+ status: "not-captured",
1388
+ reason: clipFailureReason(error),
1389
+ };
1390
+ await this.trace(
1391
+ run,
1392
+ {
1393
+ kind: "clip-failure",
1394
+ reason: clipFailureReason(error),
1395
+ message: error instanceof Error ? error.message : String(error),
1396
+ },
1397
+ true,
1398
+ ).catch(() => {});
1399
+ }
1400
+ }
1401
+
1402
+ private deadline(observation: HostObservation) {
1403
+ if (!observation.clock)
1404
+ throw new Error("Host does not advertise command admission deadlines.");
1405
+ return observation.clock.startedAtMs + PARTICIPANT_CONTROL_DEADLINE_MS;
1406
+ }
1407
+ private async observe(
1408
+ run: Run,
1409
+ seat: RunSeat,
1410
+ includeImage: boolean,
1411
+ diagnostic = false,
1412
+ ) {
1413
+ if (!run.players) throw new Error("Run players are not initialized.");
1414
+ const observation = await seat.participant.observe({
1415
+ scope: diagnostic ? "diagnostic" : run.players.scope,
1416
+ includeImage,
1417
+ expected: seat.expected,
1418
+ });
1419
+ if (
1420
+ seat.expected &&
1421
+ !sameHostRuntimeIdentity(seat.expected, observation.identity)
1422
+ )
1423
+ throw new Error(
1424
+ "runtime_replaced: Observed a different host generation.",
1425
+ );
1426
+ if (observation.controllerId !== seat.controllerId)
1427
+ throw new Error(
1428
+ "seat_replaced: Observation belongs to a different player.",
1429
+ );
1430
+ this.trackPace(run, observation);
1431
+ return observation;
1432
+ }
1433
+ /**
1434
+ * How fast the host's simulation ran during play, against real time. A
1435
+ * starved host plays in slow motion, which quietly makes tests easier, so
1436
+ * the record says so.
1437
+ */
1438
+ private trackPace(run: Run, observation: HostObservation) {
1439
+ const pace = observation.pace;
1440
+ if (run.record.state !== "playing" || !pace) return;
1441
+ if (!run.paceStart || pace.wallMs < run.paceStart.wallMs) {
1442
+ run.paceStart = pace;
1443
+ return;
1444
+ }
1445
+ const wallMs = pace.wallMs - run.paceStart.wallMs;
1446
+ if (wallMs < 1000) return;
1447
+ run.record.hostPace = {
1448
+ framesPerSecond:
1449
+ Math.round(((pace.frames - run.paceStart.frames) / wallMs) * 10_000) /
1450
+ 10,
1451
+ simulationSpeed:
1452
+ Math.round(
1453
+ ((pace.simulatedMs - run.paceStart.simulatedMs) / wallMs) * 100,
1454
+ ) / 100,
1455
+ };
1456
+ }
1457
+ private pruneReceipts(run: Run) {
1458
+ run.receipts = run.receipts.filter(
1459
+ (receipt) =>
1460
+ (run.record.request.kind === "test" &&
1461
+ receipt.index > run.evaluationCursor) ||
1462
+ receipt.sequence >
1463
+ (run.seats.find((seat) => seat.id === receipt.seatId)?.policyCursor ??
1464
+ 0),
1465
+ );
1466
+ }
1467
+ private async evaluationObservation(run: Run, includeImage: boolean) {
1468
+ const primary = run.seats[0];
1469
+ if (!primary?.expected || run.seats.some((seat) => !seat.expected))
1470
+ throw new Error("Run has no fully initialized observation seats.");
1471
+ const checkSeats = () =>
1472
+ Promise.all(run.seats.map((seat) => seat.participant.checkConnected()));
1473
+ await checkSeats();
1474
+ const observation = await this.observe(
1475
+ run,
1476
+ primary,
1477
+ includeImage,
1478
+ run.record.request.kind === "test",
1479
+ );
1480
+ await checkSeats();
1481
+ return observation;
1482
+ }
1483
+ private control(
1484
+ run: Run,
1485
+ seat: RunSeat,
1486
+ observation: Pick<HostObservation, "id" | "identity">,
1487
+ operation: ControllerLeasedControl["operation"],
1488
+ phase: "setup" | "play" | "cleanup",
1489
+ ) {
1490
+ if (phase !== "cleanup" && run.abort.signal.aborted)
1491
+ return Promise.reject(
1492
+ new Error("run_stopped: No new effects after Stop."),
1493
+ );
1494
+ const pending = this.applyControl(run, seat, observation, operation, phase);
1495
+ run.effects.add(pending);
1496
+ void pending
1497
+ .finally(() => run.effects.delete(pending))
1498
+ .catch(() => undefined);
1499
+ return pending;
1500
+ }
1501
+ private async applyControl(
1502
+ run: Run,
1503
+ seat: RunSeat,
1504
+ observation: Pick<HostObservation, "id" | "identity">,
1505
+ operation: ControllerLeasedControl["operation"],
1506
+ phase: "setup" | "play" | "cleanup",
1507
+ ) {
1508
+ const request = {
1509
+ expected: observation.identity,
1510
+ lease: { id: seat.leaseId, sequence: ++seat.sequence },
1511
+ operation,
1512
+ };
1513
+ const send = () => {
1514
+ if (operation.kind !== "release")
1515
+ run.record.lastInputAt = new Date().toISOString();
1516
+ return seat.participant.control(request);
1517
+ };
1518
+ let attempts: 1 | 2 = 1;
1519
+ let acknowledgement = await send();
1520
+ if (acknowledgement.status === "unconfirmed") {
1521
+ await this.trace(run, {
1522
+ kind: "control_attempt",
1523
+ seatId: seat.id,
1524
+ phase,
1525
+ observationId: observation.id,
1526
+ sequence: seat.sequence,
1527
+ operation,
1528
+ receipt: acknowledgement,
1529
+ });
1530
+ if (operation.kind === "release" || !run.abort.signal.aborted) {
1531
+ attempts = 2;
1532
+ acknowledgement = await send();
1533
+ }
1534
+ }
1535
+ if (
1536
+ phase === "cleanup" &&
1537
+ operation.kind === "release" &&
1538
+ acknowledgement.status === "applied"
1539
+ )
1540
+ run.record.releaseAcknowledgedAt = new Date().toISOString();
1541
+ run.record.counters[
1542
+ acknowledgement.status === "applied"
1543
+ ? "applied"
1544
+ : acknowledgement.status === "rejected"
1545
+ ? "rejected"
1546
+ : "unconfirmed"
1547
+ ]++;
1548
+ this.seatRecord(run, seat).counters[
1549
+ acknowledgement.status === "applied"
1550
+ ? "applied"
1551
+ : acknowledgement.status === "rejected"
1552
+ ? "rejected"
1553
+ : "unconfirmed"
1554
+ ]++;
1555
+ if (
1556
+ phase === "play" &&
1557
+ acknowledgement.status === "applied" &&
1558
+ operation.kind !== "release" &&
1559
+ (acknowledgement.operation.kind !== "action" ||
1560
+ acknowledgement.operation.result.ok)
1561
+ )
1562
+ this.seatRecord(run, seat).counters.effects++;
1563
+ const receipt: AirJamRunReceipt = {
1564
+ index: ++run.receiptIndex,
1565
+ seatId: seat.id,
1566
+ phase,
1567
+ sequence: seat.sequence,
1568
+ attempts,
1569
+ operation,
1570
+ acknowledgement,
1571
+ };
1572
+ run.receipts.push(receipt);
1573
+ await this.trace(run, {
1574
+ kind: "control",
1575
+ observationId: observation.id,
1576
+ ...receipt,
1577
+ });
1578
+ return acknowledgement;
1579
+ }
1580
+ private evaluate(
1581
+ run: Run,
1582
+ phase: "play" | "final",
1583
+ observation?: HostObservation,
1584
+ ) {
1585
+ if (run.evaluation)
1586
+ throw new Error("evaluator_busy: A previous evaluation is pending.");
1587
+ const primary = run.seats[0];
1588
+ const evaluator = run.evaluator;
1589
+ if (!primary || !evaluator)
1590
+ throw new Error("Scenario evaluator is not initialized.");
1591
+ const through = run.receiptIndex;
1592
+ const receipts = run.receipts.filter(
1593
+ (receipt) =>
1594
+ receipt.index > run.evaluationCursor && receipt.index <= through,
1595
+ );
1596
+ const pending = (async () => {
1597
+ const sample =
1598
+ observation ?? (await this.evaluationObservation(run, false));
1599
+ run.evaluationCursor = through;
1600
+ if (phase === "play") run.playEvaluationSent = true;
1601
+ const verdict = await evaluator.evaluate(
1602
+ {
1603
+ phase,
1604
+ observation: sample,
1605
+ seats: run.seats.map((seat) => ({
1606
+ seatId: seat.id,
1607
+ controllerId: seat.controllerId,
1608
+ })),
1609
+ receipts,
1610
+ elapsedMs: this.elapsed(run),
1611
+ },
1612
+ 1000,
1613
+ );
1614
+ run.record.evaluation ??= {};
1615
+ run.record.evaluation[phase] = verdict;
1616
+ await this.trace(run, {
1617
+ kind: "evaluation",
1618
+ phase,
1619
+ observationId: sample.id,
1620
+ through,
1621
+ verdict,
1622
+ });
1623
+ this.pruneReceipts(run);
1624
+ return verdict;
1625
+ })();
1626
+ run.evaluation = pending;
1627
+ void pending
1628
+ .finally(() => {
1629
+ if (run.evaluation === pending) run.evaluation = undefined;
1630
+ })
1631
+ .catch(() => undefined);
1632
+ return pending;
1633
+ }
1634
+ private async play(run: Run) {
1635
+ const profile = run.players;
1636
+ const request = run.record.request;
1637
+ const policy = run.policy;
1638
+ const primary = run.seats[0];
1639
+ if (!profile || !policy || !primary)
1640
+ throw new Error("Run policy is not initialized.");
1641
+ const session = run.session;
1642
+ if (!session) throw new Error("Run session is not open.");
1643
+ const clock = session.clock;
1644
+ await this.startClip(run);
1645
+ if (run.abort.signal.aborted) return;
1646
+ run.record.state = "playing";
1647
+ await this.persist(run);
1648
+ if (run.abort.signal.aborted) return;
1649
+ run.playStartedAt = clock.now();
1650
+ run.record.playStartedAt = new Date().toISOString();
1651
+ if (request.kind === "test") {
1652
+ clearTimeout(run.timer);
1653
+ run.deadline = performance.now() + request.budget.durationMs;
1654
+ run.timer = setTimeout(() => {
1655
+ void this.terminate(
1656
+ run,
1657
+ "budget",
1658
+ "Run reached its bounded play budget.",
1659
+ ).catch((error) => console.error(error));
1660
+ }, request.budget.durationMs);
1661
+ }
1662
+ const inFlight = new Map<string, Promise<void>>();
1663
+ let lastTick: number | null = null;
1664
+ let progressedAt = clock.now();
1665
+ while (!run.abort.signal.aborted) {
1666
+ const roundStarted = clock.now();
1667
+ if (
1668
+ request.kind === "test" &&
1669
+ (this.elapsed(run) >= request.budget.durationMs ||
1670
+ (run.record.counters.steps >= request.budget.steps &&
1671
+ inFlight.size === 0))
1672
+ )
1673
+ return this.terminate(
1674
+ run,
1675
+ "budget",
1676
+ "Run reached its bounded play budget.",
1677
+ );
1678
+ if (request.kind === "test") {
1679
+ let verdict: AirJamScenarioVerdict;
1680
+ try {
1681
+ verdict = await this.evaluate(run, "play");
1682
+ } catch (error) {
1683
+ if (run.abort.signal.aborted) return;
1684
+ if (
1685
+ !(error instanceof Error) ||
1686
+ !/^policy_(timeout|busy):/.test(error.message)
1687
+ )
1688
+ throw error;
1689
+ return this.terminate(
1690
+ run,
1691
+ "evaluator_unresponsive",
1692
+ error instanceof Error ? error.message : String(error),
1693
+ );
1694
+ }
1695
+ if (run.abort.signal.aborted) return;
1696
+ if (verdict.status === "failed")
1697
+ return this.terminate(
1698
+ run,
1699
+ "failed",
1700
+ verdict.message ?? "Scenario failed.",
1701
+ );
1702
+ if (verdict.status === "passed") {
1703
+ const tested = run.record.seats.every(
1704
+ (seat) => seat.counters.effects > 0,
1705
+ );
1706
+ return this.terminate(
1707
+ run,
1708
+ tested ? "completed" : "untested_seat",
1709
+ tested
1710
+ ? (verdict.message ?? "Scenario passed.")
1711
+ : "The scenario passed before every seat produced an applied play effect.",
1712
+ );
1713
+ }
1714
+ }
1715
+ for (const seat of run.seats) {
1716
+ if (run.abort.signal.aborted) return;
1717
+ if (inFlight.has(seat.id)) continue;
1718
+ if (
1719
+ request.kind === "test" &&
1720
+ run.record.counters.steps >= request.budget.steps
1721
+ )
1722
+ break;
1723
+ const started = performance.now();
1724
+ const observation = await this.observe(
1725
+ run,
1726
+ seat,
1727
+ run.record.request.target.kind === "owned" && profile.includeImage,
1728
+ );
1729
+ if (run.abort.signal.aborted) return;
1730
+ const tick = observation.ticks.after;
1731
+ if (tick !== lastTick) {
1732
+ lastTick = tick;
1733
+ progressedAt = clock.now();
1734
+ }
1735
+ const fault = observation.host?.after?.fault;
1736
+ if (
1737
+ observation.host?.after?.connectionStatus !== "connected" ||
1738
+ observation.host.after.runtimeState !== "playing" ||
1739
+ (tick !== null && clock.now() - progressedAt > 5000)
1740
+ )
1741
+ return this.terminate(
1742
+ run,
1743
+ "host_not_advancing",
1744
+ fault
1745
+ ? `The observed host stopped advancing: ${describeHostRuntimeFault(fault)}`
1746
+ : "The observed host stopped advancing.",
1747
+ fault ?? undefined,
1748
+ );
1749
+ const step = ++run.record.counters.steps;
1750
+ const counters = this.seatRecord(run, seat).counters;
1751
+ const decisionStarted = performance.now();
1752
+ const decisionDeadline =
1753
+ decisionStarted +
1754
+ Math.min(
1755
+ profile.timing.decisionMs,
1756
+ Math.max(1, run.deadline - decisionStarted),
1757
+ );
1758
+ const decision = (async () => {
1759
+ if (policy.busy()) {
1760
+ counters.blocked++;
1761
+ throw new Error("policy_busy: Previous decision has not returned.");
1762
+ }
1763
+ const receipts = run.receipts.filter(
1764
+ (receipt) =>
1765
+ receipt.seatId === seat.id &&
1766
+ receipt.sequence > seat.policyCursor,
1767
+ );
1768
+ seat.policyCursor = seat.sequence;
1769
+ counters.decisions++;
1770
+ return policy.decide(
1771
+ {
1772
+ observation,
1773
+ seatId: seat.id,
1774
+ intent: this.seatRecord(run, seat).intent,
1775
+ answer: seat.lastAnswer,
1776
+ step,
1777
+ elapsedMs: this.elapsed(run),
1778
+ receipts,
1779
+ },
1780
+ decisionDeadline - decisionStarted,
1781
+ );
1782
+ })();
1783
+ const pending = this.playDecision(run, seat, {
1784
+ observation,
1785
+ step,
1786
+ started,
1787
+ decisionStarted,
1788
+ decisionDeadline,
1789
+ decision,
1790
+ })
1791
+ .catch((error) => this.failed(run, error))
1792
+ .finally(() => {
1793
+ inFlight.delete(seat.id);
1794
+ });
1795
+ inFlight.set(seat.id, pending);
1796
+ // The policy helper has one IPC channel; model answers run outside it.
1797
+ await decision.catch(() => undefined);
1798
+ }
1799
+ if (
1800
+ inFlight.size > 0 &&
1801
+ (inFlight.size === run.seats.length ||
1802
+ (request.kind === "test" &&
1803
+ run.record.counters.steps >= request.budget.steps))
1804
+ )
1805
+ await Promise.race(inFlight.values());
1806
+ await clock
1807
+ .wait(
1808
+ Math.max(0, profile.timing.intervalMs - (clock.now() - roundStarted)),
1809
+ run.abort.signal,
1810
+ )
1811
+ .catch((error) => {
1812
+ if (!run.abort.signal.aborted) throw error;
1813
+ });
1814
+ }
1815
+ }
1816
+ private async playDecision(
1817
+ run: Run,
1818
+ seat: RunSeat,
1819
+ {
1820
+ observation,
1821
+ step,
1822
+ started,
1823
+ decisionStarted,
1824
+ decisionDeadline,
1825
+ decision: pendingDecision,
1826
+ }: {
1827
+ observation: HostObservation;
1828
+ step: number;
1829
+ started: number;
1830
+ decisionStarted: number;
1831
+ decisionDeadline: number;
1832
+ decision: Promise<AirJamPolicyDecision>;
1833
+ },
1834
+ ) {
1835
+ const profile = run.players;
1836
+ if (!profile) throw new Error("Run players are not initialized.");
1837
+ const request = run.record.request;
1838
+ const tick = observation.ticks.after;
1839
+ const counters = this.seatRecord(run, seat).counters;
1840
+ let control: AirJamPlayControl;
1841
+ try {
1842
+ const decision = await pendingDecision;
1843
+ if (run.abort.signal.aborted) return;
1844
+ let answer: AnsweredDecision | undefined;
1845
+ if ("ask" in decision) {
1846
+ // A missed answer must not leave the previous choice to act on.
1847
+ seat.lastAnswer = null;
1848
+ answer = await this.answerFor(
1849
+ run,
1850
+ seat,
1851
+ decision.ask,
1852
+ decisionDeadline,
1853
+ );
1854
+ if (run.abort.signal.aborted) return;
1855
+ control = answer.control;
1856
+ seat.lastAnswer = {
1857
+ choice: answer.choice,
1858
+ confidence: answer.confidence,
1859
+ };
1860
+ } else control = decision.control;
1861
+ if (run.abort.signal.aborted) return;
1862
+ await this.trace(run, {
1863
+ kind: "policy_decision",
1864
+ seatId: seat.id,
1865
+ step,
1866
+ durationMs: performance.now() - decisionStarted,
1867
+ ...(decision.diagnostics ? { diagnostics: decision.diagnostics } : {}),
1868
+ ...(answer
1869
+ ? {
1870
+ answer: {
1871
+ choice: answer.choice,
1872
+ confidence: answer.confidence,
1873
+ durationMs: answer.durationMs,
1874
+ control: answer.control,
1875
+ ...(answer.note ? { note: answer.note } : {}),
1876
+ },
1877
+ }
1878
+ : {}),
1879
+ });
1880
+ this.pruneReceipts(run);
1881
+ } catch (error) {
1882
+ if (run.abort.signal.aborted) return;
1883
+ if (
1884
+ !(error instanceof Error) ||
1885
+ !/^(policy_(timeout|busy)|decision_failed):/.test(error.message)
1886
+ )
1887
+ throw error;
1888
+ if (error.message.startsWith("policy_timeout:")) counters.timeout++;
1889
+ run.record.counters.missed++;
1890
+ const reason = error.message.slice(0, 300);
1891
+ await this.trace(run, {
1892
+ kind: "decision_missed",
1893
+ seatId: seat.id,
1894
+ step,
1895
+ reason,
1896
+ });
1897
+ await this.control(run, seat, observation, { kind: "release" }, "play");
1898
+ if (++seat.misses >= 3)
1899
+ return this.terminate(
1900
+ run,
1901
+ "policy_unresponsive",
1902
+ `Seat ${seat.id} missed three consecutive decision opportunities. Last: ${reason}`,
1903
+ );
1904
+ return;
1905
+ }
1906
+ if (run.abort.signal.aborted) return;
1907
+ seat.misses = 0;
1908
+ const operation: ControllerLeasedControl["operation"] =
1909
+ control.kind === "release"
1910
+ ? { kind: "release" }
1911
+ : control.kind === "input"
1912
+ ? {
1913
+ ...control,
1914
+ ttlMs: profile.timing.inputTtlMs,
1915
+ deadlineMs: this.deadline(observation),
1916
+ }
1917
+ : { ...control, deadlineMs: this.deadline(observation) };
1918
+ if (
1919
+ operation.kind === "action" &&
1920
+ request.kind === "test" &&
1921
+ !run.record.profile?.actions.includes(operation.actionId)
1922
+ )
1923
+ throw new Error(
1924
+ "policy_action_forbidden: Decision requested an action outside the profile.",
1925
+ );
1926
+ const receipt = await this.control(
1927
+ run,
1928
+ seat,
1929
+ observation,
1930
+ operation,
1931
+ "play",
1932
+ );
1933
+ if (receipt.status === "unconfirmed")
1934
+ throw new Error(`control_unconfirmed: ${receipt.reason}`);
1935
+ if (receipt.status === "rejected") {
1936
+ if (receipt.reason === "stale_identity")
1937
+ return this.terminate(
1938
+ run,
1939
+ "runtime_replaced",
1940
+ "The game runtime was replaced.",
1941
+ );
1942
+ if (receipt.reason !== "stale_decision")
1943
+ throw new Error(`control_rejected: ${receipt.reason}`);
1944
+ run.record.counters.missed++;
1945
+ await this.control(run, seat, observation, { kind: "release" }, "play");
1946
+ if (++seat.staleDecisions >= 3)
1947
+ return this.terminate(
1948
+ run,
1949
+ "decision_latency",
1950
+ `Seat ${seat.id} repeatedly arrived too late to apply.`,
1951
+ );
1952
+ } else seat.staleDecisions = 0;
1953
+ await this.trace(run, {
1954
+ kind: "decision",
1955
+ seatId: seat.id,
1956
+ step,
1957
+ observationId: observation.id,
1958
+ tick,
1959
+ durationMs: performance.now() - started,
1960
+ });
1961
+ }
1962
+ private failed(run: Run, error: unknown) {
1963
+ if (run.abort.signal.aborted) return;
1964
+ const message = error instanceof Error ? error.message : String(error);
1965
+ const stopped = error instanceof CurrentRoomStopped;
1966
+ if (stopped) run.record.stopRequestedAt ??= new Date().toISOString();
1967
+ void this.terminate(
1968
+ run,
1969
+ stopped ? "stopped" : failureReason(message),
1970
+ message,
1971
+ ).catch((failure) => console.error(failure));
1972
+ }
1973
+ private terminate(
1974
+ run: Run,
1975
+ reason: EndReason,
1976
+ message: string,
1977
+ hostFault?: NonNullable<AirJamGameRunRecord["end"]>["hostFault"],
1978
+ ) {
1979
+ return (run.termination ??= (async () => {
1980
+ run.record.abortedAt = new Date().toISOString();
1981
+ run.abort.abort();
1982
+ clearTimeout(run.timer);
1983
+ run.record.state = "stopping";
1984
+ run.record.end = {
1985
+ reason,
1986
+ ...(run.record.request.kind === "test"
1987
+ ? { outcome: "inconclusive" as const }
1988
+ : {}),
1989
+ message,
1990
+ ...(hostFault ? { hostFault } : {}),
1991
+ };
1992
+ const cleanup: NonNullable<AirJamGameRunRecord["cleanup"]> = {
1993
+ seats: [],
1994
+ errors: [],
1995
+ participantsClosed: true,
1996
+ };
1997
+ const attempt = async <T>(operation: () => Promise<T>) => {
1998
+ try {
1999
+ return await operation();
2000
+ } catch (error) {
2001
+ cleanup.errors.push(
2002
+ error instanceof Error ? error.message : String(error),
2003
+ );
2004
+ return undefined;
2005
+ }
2006
+ };
2007
+ await attempt(async () => {
2008
+ await run.admission;
2009
+ await run.startup;
2010
+ });
2011
+ await Promise.allSettled([...run.watches.values()]);
2012
+ const policy = run.policy;
2013
+ if (policy && run.record.request.kind === "test")
2014
+ await attempt(() => policy.stop());
2015
+ await Promise.allSettled([...run.effects]);
2016
+ const evaluationInFlight = run.evaluation;
2017
+ if (evaluationInFlight) await attempt(() => evaluationInFlight);
2018
+ if (run.session) {
2019
+ const session = run.session;
2020
+ for (const seat of run.seats) {
2021
+ const seatCleanup: NonNullable<
2022
+ AirJamGameRunRecord["cleanup"]
2023
+ >["seats"][number] = { seatId: seat.id };
2024
+ cleanup.seats.push(seatCleanup);
2025
+ if (seat.expected) {
2026
+ const expected = seat.expected;
2027
+ seatCleanup.release = await attempt(() =>
2028
+ this.control(
2029
+ run,
2030
+ seat,
2031
+ { identity: expected, id: "cleanup" },
2032
+ { kind: "release" },
2033
+ "cleanup",
2034
+ ),
2035
+ );
2036
+ }
2037
+ seat.policyCursor = seat.sequence;
2038
+ }
2039
+ await this.finishClip(run);
2040
+ if (run.record.request.kind === "test") {
2041
+ const primary = run.seats[0];
2042
+ let finalObservation: HostObservation | undefined;
2043
+ try {
2044
+ if (!primary || !run.players)
2045
+ throw new Error("Run has no initialized observation seat.");
2046
+ const before = await this.evaluationObservation(run, false);
2047
+ const settleUntil = session.clock.now() + 2000;
2048
+ let settled: HostObservation;
2049
+ do {
2050
+ await session.clock.wait(run.players.timing.intervalMs);
2051
+ settled = await this.evaluationObservation(run, false);
2052
+ } while (
2053
+ before.ticks.after !== null &&
2054
+ settled.ticks.after === before.ticks.after &&
2055
+ session.clock.now() < settleUntil
2056
+ );
2057
+ if (
2058
+ before.ticks.after !== null &&
2059
+ settled.ticks.after === before.ticks.after
2060
+ ) {
2061
+ const fault = settled.host?.after?.fault;
2062
+ if (fault) run.record.end.hostFault = fault;
2063
+ throw new Error(
2064
+ fault
2065
+ ? `The host did not advance after input release: ${describeHostRuntimeFault(fault)}`
2066
+ : "The host did not advance after input release.",
2067
+ );
2068
+ }
2069
+ finalObservation = await this.evaluationObservation(run, true);
2070
+ if (!run.room && run.record.expected) {
2071
+ const result = await readHostInputLog(
2072
+ (request) => {
2073
+ if (!session.requestHost)
2074
+ throw new Error(
2075
+ "host_unavailable: Studio couldn't reach the game.",
2076
+ );
2077
+ return session.requestHost(request, 5000);
2078
+ },
2079
+ run.record.expected,
2080
+ {
2081
+ scope: finalObservation.scope,
2082
+ controllerId: finalObservation.controllerId,
2083
+ },
2084
+ );
2085
+ run.record.evidence ??= { observation: null, error: null };
2086
+ if (result.status === "not-replayable")
2087
+ run.record.evidence.replay = {
2088
+ reason: result.reason,
2089
+ message: result.message,
2090
+ };
2091
+ else {
2092
+ if (!result.observation)
2093
+ throw new Error(
2094
+ "The recording has no cut-bound observation.",
2095
+ );
2096
+ // Keep the screen capture, with state sampled at the log cut.
2097
+ finalObservation = {
2098
+ ...result.observation,
2099
+ visual: finalObservation.visual,
2100
+ };
2101
+ const inputSource = `${JSON.stringify(result.log)}\n`;
2102
+ const file = await open(
2103
+ path.join(run.directory, "input-log.json"),
2104
+ "w",
2105
+ 0o600,
2106
+ );
2107
+ try {
2108
+ await file.writeFile(inputSource);
2109
+ } finally {
2110
+ await file.close();
2111
+ }
2112
+ run.record.evidence.inputLog = {
2113
+ path: `.airjam/artifacts/runs/${run.record.runId}/input-log.json`,
2114
+ sha256: createHash("sha256")
2115
+ .update(inputSource)
2116
+ .digest("hex"),
2117
+ ticks: result.log.ticks,
2118
+ stepMs: result.log.stepMs,
2119
+ entries: result.log.entries.length,
2120
+ fromTick: run.fromTick ?? 0,
2121
+ full: result.full,
2122
+ };
2123
+ }
2124
+ }
2125
+ const source = `${JSON.stringify(finalObservation)}\n`;
2126
+ const file = await open(
2127
+ path.join(run.directory, "final-observation.json"),
2128
+ "w",
2129
+ 0o600,
2130
+ );
2131
+ try {
2132
+ await file.writeFile(source);
2133
+ } finally {
2134
+ await file.close();
2135
+ }
2136
+ run.record.evidence = {
2137
+ ...run.record.evidence,
2138
+ observation: {
2139
+ path: `.airjam/artifacts/runs/${run.record.runId}/final-observation.json`,
2140
+ sha256: createHash("sha256").update(source).digest("hex"),
2141
+ },
2142
+ error: null,
2143
+ };
2144
+ const saveInputLog = run.room?.saveInputLog;
2145
+ if (saveInputLog)
2146
+ run.record.evidence.inputLog = {
2147
+ path: `.airjam/artifacts/runs/${run.record.runId}/input-log.json`,
2148
+ fromTick: run.fromTick ?? 0,
2149
+ ...(await saveInputLog(
2150
+ path.join(run.directory, "input-log.json"),
2151
+ )),
2152
+ };
2153
+ } catch (error) {
2154
+ const message =
2155
+ error instanceof Error ? error.message : String(error);
2156
+ run.record.evidence = {
2157
+ ...run.record.evidence,
2158
+ observation: null,
2159
+ error: message,
2160
+ };
2161
+ if (run.record.end.reason === "completed")
2162
+ run.record.end = {
2163
+ reason: failureReason(message),
2164
+ outcome: "inconclusive",
2165
+ message,
2166
+ ...(run.record.end.hostFault
2167
+ ? { hostFault: run.record.end.hostFault }
2168
+ : {}),
2169
+ };
2170
+ }
2171
+ if (finalObservation && run.evaluator && run.playEvaluationSent)
2172
+ await attempt(() => this.evaluate(run, "final", finalObservation));
2173
+ const evaluator = run.evaluator;
2174
+ if (evaluator) await attempt(() => evaluator.stop());
2175
+ }
2176
+ // A test in the creator's room hands it back before its players leave,
2177
+ // so the room no longer plays on without them.
2178
+ if (
2179
+ run.record.request.kind === "test" &&
2180
+ run.record.request.target.kind === "current" &&
2181
+ run.record.profile &&
2182
+ run.seats.length > 0 &&
2183
+ run.seats.every((seat) => seat.expected)
2184
+ ) {
2185
+ const steps = run.record.profile.handBack;
2186
+ cleanup.handBack = steps
2187
+ ? (await attempt(() =>
2188
+ this.runProfileSteps(run, session, steps, "cleanup"),
2189
+ ))
2190
+ ? "returned"
2191
+ : "failed"
2192
+ : "undeclared";
2193
+ }
2194
+ for (const seat of run.seats.slice(1)) {
2195
+ const extra = seat.extra;
2196
+ if (!extra)
2197
+ throw new Error("Additional run seat has no owned participant.");
2198
+ let disconnected = await attempt(() => extra.close());
2199
+ if (!disconnected)
2200
+ disconnected = await attempt(() => extra.forceClose());
2201
+ if (!disconnected) cleanup.participantsClosed = false;
2202
+ const receipt = cleanup.seats.find(
2203
+ (candidate) => candidate.seatId === seat.id,
2204
+ );
2205
+ if (!receipt) throw new Error("Run seat has no cleanup receipt.");
2206
+ receipt.disconnection = disconnected;
2207
+ await attempt(() =>
2208
+ this.trace(run, {
2209
+ kind: "seat_left",
2210
+ seatId: seat.id,
2211
+ disconnection: disconnected,
2212
+ }),
2213
+ );
2214
+ }
2215
+ let closed = await attempt(() => session.close());
2216
+ if (!closed?.closed) {
2217
+ cleanup.forced = true;
2218
+ closed = await attempt(() => session.forceClose());
2219
+ }
2220
+ if (closed) {
2221
+ run.closed = closed;
2222
+ cleanup.close = {
2223
+ closed: closed.closed,
2224
+ disconnection: closed.disconnection,
2225
+ };
2226
+ run.record.session = gameRunSessionIdentitySchema.parse(
2227
+ closed.session,
2228
+ );
2229
+ }
2230
+ }
2231
+ if (policy && run.record.request.kind === "play")
2232
+ await attempt(() => policy.stop());
2233
+ const evaluator = run.evaluator;
2234
+ if (!run.session && evaluator) await attempt(() => evaluator.stop());
2235
+ const scopes = await Promise.allSettled(
2236
+ run.scopes.map((close) => close()),
2237
+ );
2238
+ cleanup.processesClosed = scopes.every(
2239
+ (result) => result.status === "fulfilled",
2240
+ );
2241
+ try {
2242
+ assertProcessScopesConfirmed();
2243
+ } catch (error) {
2244
+ cleanup.processesClosed = false;
2245
+ cleanup.errors.push(
2246
+ error instanceof Error ? error.message : String(error),
2247
+ );
2248
+ }
2249
+ for (const result of scopes)
2250
+ if (result.status === "rejected")
2251
+ cleanup.errors.push(
2252
+ result.reason instanceof Error
2253
+ ? result.reason.message
2254
+ : String(result.reason),
2255
+ );
2256
+ const evaluation = run.record.evaluation;
2257
+ if (
2258
+ evaluation?.play?.status === "failed" ||
2259
+ evaluation?.final?.status === "failed"
2260
+ ) {
2261
+ run.record.end = {
2262
+ reason: "failed",
2263
+ outcome: "failed",
2264
+ message:
2265
+ (evaluation.final?.status === "failed"
2266
+ ? evaluation.final
2267
+ : evaluation.play
2268
+ )?.message ?? "Scenario failed.",
2269
+ };
2270
+ } else if (run.record.end.reason === "completed") {
2271
+ const released =
2272
+ cleanup.seats.length === run.record.seats.length &&
2273
+ cleanup.seats.every((seat) => seat.release?.status === "applied");
2274
+ run.record.end.outcome =
2275
+ evaluation?.final?.status === "passed" &&
2276
+ run.record.evidence?.observation &&
2277
+ cleanup.errors.length === 0 &&
2278
+ cleanup.close?.closed &&
2279
+ released &&
2280
+ cleanup.participantsClosed &&
2281
+ cleanup.processesClosed
2282
+ ? "passed"
2283
+ : "inconclusive";
2284
+ if (run.record.end.outcome === "inconclusive")
2285
+ run.record.end.message =
2286
+ cleanup.errors[0] ??
2287
+ (!released
2288
+ ? "Cleanup did not confirm every input release."
2289
+ : "The final evaluation did not confirm the earlier pass.");
2290
+ }
2291
+ if (run.build && run.record.build) {
2292
+ try {
2293
+ await verifyPinnedGameBuild(run.build);
2294
+ run.record.build.integrity = "verified";
2295
+ } catch (error) {
2296
+ run.record.build.integrity = "changed";
2297
+ run.record.end = {
2298
+ reason: "runtime_replaced",
2299
+ ...(run.record.request.kind === "test"
2300
+ ? { outcome: "inconclusive" as const }
2301
+ : {}),
2302
+ message: error instanceof Error ? error.message : String(error),
2303
+ };
2304
+ }
2305
+ }
2306
+ run.record.cleanup = cleanup;
2307
+ run.record.endedAt = new Date().toISOString();
2308
+ run.record.state = "ended";
2309
+ if (run.traceTruncated)
2310
+ run.record.end = {
2311
+ reason: "trace_budget",
2312
+ ...(run.record.request.kind === "test"
2313
+ ? { outcome: "inconclusive" as const }
2314
+ : {}),
2315
+ message:
2316
+ "Trace byte allowance was exhausted; evidence is incomplete.",
2317
+ };
2318
+ await attempt(() =>
2319
+ this.trace(run, { kind: "ended", end: run.record.end, cleanup }),
2320
+ );
2321
+ await attempt(async () => {
2322
+ await run.tracing;
2323
+ const file = run.traceFile;
2324
+ run.traceFile = null;
2325
+ await file?.close();
2326
+ });
2327
+ await attempt(async () => {
2328
+ const bytes = await readGameRunArtifact(
2329
+ this.options.projectDir,
2330
+ run.record.runId,
2331
+ "trace.ndjson",
2332
+ MAXIMUM_GAME_RUN_TRACE_BYTES,
2333
+ );
2334
+ if (!bytes) throw new Error("Run trace is missing.");
2335
+ run.record.evidence ??= { observation: null, error: null };
2336
+ run.record.evidence.trace = {
2337
+ path: `.airjam/artifacts/runs/${run.record.runId}/trace.ndjson`,
2338
+ sha256: createHash("sha256").update(bytes).digest("hex"),
2339
+ bytes: bytes.byteLength,
2340
+ truncated: run.traceTruncated,
2341
+ };
2342
+ });
2343
+ if (
2344
+ run.record.end.outcome === "passed" &&
2345
+ (cleanup.errors.length || run.traceTruncated)
2346
+ )
2347
+ run.record.end = {
2348
+ reason: run.traceTruncated ? "trace_budget" : "error",
2349
+ outcome: "inconclusive",
2350
+ message: cleanup.errors[0] ?? "Trace byte allowance was exhausted.",
2351
+ };
2352
+ await this.persist(run);
2353
+ if (run.session && cleanup.close?.closed && cleanup.participantsClosed)
2354
+ this.options.sessionClosed(run.session.summary.gameSessionId);
2355
+ this.prune();
2356
+ })().finally(() => run.finished.abort()));
2357
+ }
2358
+ }