File size: 39,881 Bytes
17c0464
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
import {testRoutineSource, testFrameworkBinding} from "../../testing/framework-fixtures"
import {expect, spyOn, test} from "bun:test";
import {Hono} from "hono";
import {createTestRunAdminApi} from "./test-runs.api";
import {TestSuiteService} from "../../services/test-suite.service";
import {TestHistoryService} from "../../services/test-history.service";
import {LaneRestorationService} from "../../services/lane-restoration.service";
import {TestHostHealthService} from "../../services/test-host-health.service";
import {FrameworkResultService, type StoredFrameworkRun} from "../../services/framework-result.service";
import {TestRunError} from "../../services/test-result-error";
import {requestInputDigest, TestRequestService, type StoredTestRequest, type StoredPreparingRequest, type TestRequestRepository} from "../../services/test-request.service";
import {routineEnrollmentSchema} from "../../types/routine-definition.types";
import {frameworkRunSchema} from "../../types/framework-run.types";
import {TestRequestProgressService} from '../../services/test-request-progress.service';
import {TestHostStateService} from '../../services/test-host-state.service';
import {sharedResourceWait} from '../../services/routine-resource-wait';
import {TestRequestMatchService} from '../../services/test-request-match.service';
import {readAcceptedRoutineRequest} from '../../services/routine-request-input';
import {recordedFrameworkRequestInputSchema} from '../../types/framework-request.types';

test('exact original matching route returns identical no-store JSON outside generic result lookup', async () => {
  const report = {requestId: 'exact-original', stage: 'Candidate check and return', lanes: []}
  const matching = spyOn(TestRequestMatchService.prototype, 'get').mockResolvedValue(report as never)
  const result = spyOn(FrameworkResultService.prototype, 'detailByRun').mockRejectedValue(new Error('must not inspect run history'))
  try {
    const response = await createTestRunAdminApi().request('/requests/exact-original/matching')
    expect(response.status).toBe(200); expect(response.headers.get('Cache-Control')).toBe('no-store')
    expect(await response.json()).toEqual(report); expect(matching).toHaveBeenCalledWith('exact-original'); expect(result).not.toHaveBeenCalled()
  } finally {matching.mockRestore(); result.mockRestore()}
});

test('the ordinary run detail carries live progress until its published result replaces the request', async () => {
  const input = {routineSource: testRoutineSource(), routineId: 'miniapps', definitionRevision: 'a'.repeat(40), platform: 'android',
    laneId: 'phone', resources: [], build: {repository: 'Mentra-Community/MentraOS', channel: 'dev', headSha: 'b'.repeat(40)}};
  const row = {requestId: 'active-request', hostId: 'pro', input, inputSha256: requestInputDigest(input), state: 'accepted' as const};
  const live = {title: 'Miniapps', steps: [{id: 'open', instruction: 'Open miniapp'}], progress: {phase: 'test'}};
  const detail = spyOn(FrameworkResultService.prototype, 'detailByRun').mockRejectedValue(new TestRunError(404, 'pending'));
  const byRequest = spyOn(FrameworkResultService.prototype, 'detail').mockRejectedValue(new TestRunError(404, 'pending'));
  const requests = spyOn(TestRequestService.prototype, 'get').mockResolvedValue(row);
  const progress = spyOn(TestRequestProgressService.prototype, 'get').mockResolvedValue(live as never);
  try {
    const app = createTestRunAdminApi();
    expect(await (await app.request('/active-request')).json()).toMatchObject({kind: 'request', request: {live}});
    expect(progress).toHaveBeenCalledWith(row);
    progress.mockRejectedValueOnce(new Error('Host observation unavailable'));
    const unavailable = await app.request('/active-request');
    expect(unavailable.status).toBe(200);
    expect(await unavailable.json()).toMatchObject({kind: 'request', request: {state: 'accepted', liveUnavailable: true}});
    progress.mockClear(); byRequest.mockResolvedValue({run: {requestId: 'active-request'}, outcome: 'pass'} as never);
    expect(await (await app.request('/active-request')).json()).toMatchObject({kind: 'run', outcome: 'pass'});
    expect(progress).not.toHaveBeenCalled();
  } finally {detail.mockRestore(); byRequest.mockRestore(); requests.mockRestore(); progress.mockRestore();}
});

test("mounted lane run history forwards host, lane and pagination at the collection URL", async () => {
  const calls: Record<string, string>[] = [];
  class Results extends FrameworkResultService {
    override async list(query: Record<string, string> = {}) {
      calls.push(query); return {runs: [], nextCursor: null};
    }
  }
  const app = new Hono();
  app.route("/api/admin/test-runs", createTestRunAdminApi(undefined, undefined, new Results()));
  for (const suffix of ["", "&cursor=cursor%3Anext"]) {
    const response = await app.request(`/api/admin/test-runs?hostId=host%3Aone&laneId=lane%3Atwo${suffix}`);
    expect(response.status).toBe(200);
    expect(await response.json()).toEqual({runs: [], nextCursor: null});
    expect(response.headers.get("Cache-Control")).toBe("no-store");
  }
  expect(calls).toEqual([{hostId: "host:one", laneId: "lane:two"},
    {hostId: "host:one", laneId: "lane:two", cursor: "cursor:next"}]);
});

test("combined history route forwards pagination outside the generic run ID path", async () => {
  const calls: Record<string, string>[] = [];
  class History extends TestHistoryService {
    override async list(query: Record<string, string> = {}) {
      calls.push(query); return {entries: [], nextCursor: null};
    }
  }
  const response = await createTestRunAdminApi(new TestHostHealthService(), new History()).request("/history/list?limit=3&cursor=next");
  expect(response.status).toBe(200);
  expect(await response.json()).toEqual({entries: [], nextCursor: null});
  expect(calls).toEqual([{limit: "3", cursor: "next"}]);
  expect(response.headers.get("Cache-Control")).toBe("no-store");
});

test("history query timeout returns a controlled retryable response", async () => {
  class History extends TestHistoryService {
    override async list(): Promise<never> {throw new TestRunError(503, "Test history query timed out. Try again.");}
  }
  const response = await createTestRunAdminApi(undefined, new History()).request("/history/list?limit=25");
  expect(response.status).toBe(503);
  expect(await response.json()).toEqual({error: "test_run_error", message: "Test history query timed out. Try again."});
  expect(response.headers.get("Cache-Control")).toBe("no-store");
});

test("the valid run ID history still opens its individual result", async () => {
  const detail = spyOn(FrameworkResultService.prototype, "detailByRun").mockResolvedValue({runId: "history"} as never);
  try {
    const response = await createTestRunAdminApi().request("/history");
    expect(response.status).toBe(200);
    expect(await response.json()).toEqual({kind: "run", runId: "history"});
    expect(detail).toHaveBeenCalledWith("history", true);
  } finally {detail.mockRestore();}
});

test("the existing result route prefers actual runs and otherwise shows exact rejected request identity", async () => {
  const calls: string[] = [];
  const input = {
    routineSource: testRoutineSource(),
    routineId: "new-product",
    definitionRevision: "a".repeat(40),
    platform: "android",
    laneId: "phone",
    resources: [],
    build: {repository: "Mentra-Community/MentraOS", channel: "dev", headSha: "b".repeat(40), kind: 'android-apk',
      source: {channel: 'dev', buildRunId: 1, publicationAttempt: 1},
      archive: {name: 'app.apk', url: 'https://artifactscdn.mentraglass.com/app.apk', size: 100, sha256: 'c'.repeat(64)},
      receipt: {url: 'https://artifactscdn.mentraglass.com/receipt', size: 10, sha256: 'd'.repeat(64)}},
  }
  const inputSha256 = requestInputDigest(input);
  class Results extends FrameworkResultService {
    override async detailByRun(id: string): Promise<any> {
      calls.push("run:" + id);
      if (id === "actual") return {run: {result: {runId: id}}, outcome: "pass"};
      throw new TestRunError(id === "outage" ? 503 : 404, "unavailable");
    }
    override async detail(id: string): Promise<any> {
      calls.push("result-request:" + id);
      if (id === "published-request") return {run: {requestId: id, result: {runId: "actual"}}, outcome: "pass"};
      throw new TestRunError(404, "missing result");
    }
  }
  class Requests extends TestRequestService {
    override async get(id: string) {
      calls.push("request:" + id);
      if (id === "missing") return null;
      return {requestId: id, hostId: "mini", input, inputSha256, state: "terminal" as const, terminalStatus: "not-run",
        hostRejection: {requestId: id, hostId: "mini", inputSha256, rejectedAt: "2026-10-03T11:00:00Z",
          code: "missing-definition", reason: "The exact source revision is not installed."}};
    }
  }
  const app = createTestRunAdminApi(undefined, undefined, new Results(), new Requests());
  expect(await (await app.request("/actual")).json()).toMatchObject({kind: "run", outcome: "pass"});
  expect(calls).toEqual(["run:actual"]);
  expect(await (await app.request("/published-request")).json()).toMatchObject({kind: "run", run: {requestId: "published-request"}});
  const response = await app.request("/rejected-request");
  expect(response.headers.get("cache-control")).toBe("no-store");
  const body: any = await response.json();
  expect(body).toMatchObject({kind: "request", request: {requestId: "rejected-request", hostId: "mini", routineId: input.routineId,
    platform: input.platform, laneId: input.laneId, definitionRevision: input.definitionRevision, build: input.build,
    state: "terminal", terminalStatus: "not-run", reason: "missing-definition: The exact source revision is not installed."}});
  expect(body.run).toBeUndefined();
  expect(body.request.steps).toBeUndefined();
  expect((await app.request("/missing")).status).toBe(404);
  calls.length = 0;
  expect((await app.request("/outage")).status).toBe(503);
  expect(calls).toEqual(["run:outage"]);
})

test("a cancelled request read reconciles late host custody and then its real recorded result through the same route", async () => {
  const requestId = "cancelled-request";
  const input = {
    routineSource: testRoutineSource(),
    routineId: "new-product",
    definitionRevision: "a".repeat(40),
    platform: "android",
    laneId: "phone",
    resources: [],
    build: {repository: "Mentra-Community/MentraOS", channel: "dev", headSha: "b".repeat(40), kind: 'android-apk',
      source: {channel: 'dev', buildRunId: 1, publicationAttempt: 1},
      archive: {name: 'app.apk', url: 'https://artifactscdn.mentraglass.com/app.apk', size: 100, sha256: 'c'.repeat(64)},
      receipt: {url: 'https://artifactscdn.mentraglass.com/receipt', size: 10, sha256: 'd'.repeat(64)}},
  }
  let row: StoredTestRequest | null = null, storedRun: StoredFrameworkRun | null = null;
  const repository = {
    async insert(value: StoredTestRequest) {row = structuredClone(value);},
    async get() {return structuredClone(row);},
    async cancel(receipt) {
      if (!row || row.state !== "queued") return null;
      row = {...row, state: "terminal", terminalStatus: "cancelled", hostCancellation: receipt}; return structuredClone(row);
    },
    async accept(receipt) {
      if (!row || row.state !== "terminal" || !row.hostCancellation) return null;
      row.hostReceipt = structuredClone(receipt); return structuredClone(row);
    },
    async reject() {throw new Error("unused rejection");}, async acknowledgeCancellation() {throw new Error("unused cancellation acknowledgement");},
    async queued() {throw new Error("unused queue read");}, async cancellations() {throw new Error("unused cancellation read");},
  } satisfies TestRequestRepository;
  const requests = new TestRequestService(repository);
  const definition = routineEnrollmentSchema.parse({
    routineId: input.routineId,
    platform: input.platform,
    definitionRevision: input.definitionRevision,
    definitionSha256: "d".repeat(64),
    routineSource: testRoutineSource(),
    definition: {
      minimumRoutineApiVersion: 1,
      id: input.routineId,
      title: "New product",
      purpose: "Check",
      platforms: ["android"],
      entry: "home",
      account: "lane",
      resourceRequirements: [],
      requirements: [],
      fixtures: [],
      steps: [{id: "check", instruction: "Check", expected: "Checked"}],
      source: {repository: "Mentra-Community/Mentra-Automated-Testing", revision: input.definitionRevision, path: "routines/new-product/routine.ts"},
    },
  })
  const results = new FrameworkResultService(
    {
    async insert(payload, payloadSha256) {storedRun = {payload, payloadSha256, uploadsComplete: true};},
    async getByRequest() {return structuredClone(storedRun);}, async getByRun() {return structuredClone(storedRun);}, async getAsset() {return null;},
  },
    async () => (row?.hostReceipt ? {hostId: row.hostId, input} : null),
    async run => {
    row = {...row!, state: "terminal", terminalStatus: "cancelled", runId: run.result.runId};
  },
    async () => definition,
  )
  const app = createTestRunAdminApi(undefined, undefined, results, requests);
  const queued = await requests.submit(requestId, "mini", input);
  await requests.cancel(requestId, "2026-10-03T11:01:00Z", "Nightly occurrence reached its completion boundary.");
  const cancelled: any = await (await app.request(`/${requestId}`)).json();
  expect(cancelled).toMatchObject({kind: "request", request: {state: "terminal", terminalStatus: "cancelled", cancellationRequested: true,
    cancellationAcknowledged: false, reason: "Nightly occurrence reached its completion boundary."}});
  expect(cancelled.request.acceptedAt).toBeUndefined();
  expect(cancelled.run).toBeUndefined();
  await requests.accept({requestId, hostId: "mini", inputSha256: queued.inputSha256, acceptedAt: "2026-10-03T11:00:30Z"}, "mini");
  const accepted: any = await (await app.request(`/${requestId}`)).json();
  expect(accepted).toMatchObject({kind: "request", request: {state: "terminal", terminalStatus: "cancelled", acceptedAt: "2026-10-03T11:00:30Z"}});
  expect(accepted.run).toBeUndefined();
  expect(accepted.request.steps).toBeUndefined();
  const run = frameworkRunSchema.parse({
    schemaVersion: 1,
    routineSource: testRoutineSource(),
    frameworkBinding: testFrameworkBinding(),
    requestId,
    hostId: "mini",
    routineId: input.routineId,
    definitionRevision: input.definitionRevision,
    platform: input.platform,
    laneId: input.laneId,
    build: input.build,
    startedAt: "2026-10-03T11:00:30Z",
    finishedAt: "2026-10-03T11:01:30Z",
    assets: [],
    result: {runId: requestId, finishedAt: "2026-10-03T11:01:30Z", setup: {status: "cancelled"}, test: "cancelled",
      steps: [{id: "check", status: "not-run", durationMs: 0}], teardown: {ready: true, outcomes: [], errors: [], unavailableResources: []},
      failures: [], evidence: [], timing: {startedAt: "2026-10-03T11:00:30Z", setupMs: 30000, testMs: 0, teardownMs: 30000}},
  })
  await results.ingest(run, "mini");
  const published: any = await (await app.request(`/${requestId}`)).json();
  expect(published).toMatchObject({kind: "run", outcome: "cancelled", uploadsComplete: true, run});
  expect(published.request).toBeUndefined();
})

test("restoration list has a bounded uncached route outside generic run identities", async () => {
  class Restoration extends LaneRestorationService {
    override async list() {return {generatedAt: "2026-10-05T01:00:00Z", freshForMs: 120_000, hosts: [], truncated: false};}
  }
  const response = await createTestRunAdminApi(undefined, undefined, undefined, undefined, new Restoration()).request("/restoration/list");
  expect(response.status).toBe(200); expect(response.headers.get("Cache-Control")).toBe("no-store");
  expect(await response.json()).toMatchObject({hosts: [], truncated: false});
});

test('current lane and host-filtered history routes remain distinct uncached reads', async () => {
  class Restoration extends LaneRestorationService {
    override async overview() {return {generatedAt: '2026-10-05T01:00:00Z', freshForMs: 120_000, hosts: [], truncated: false}}
    override async list(hostId?: string) {expect(hostId).toBe('selected-host'); return this.overview() as any}
  }
  const app = createTestRunAdminApi(undefined, undefined, undefined, undefined, new Restoration());
  for (const path of ['/lanes/overview', '/restoration/list?hostId=selected-host']) {
    const response = await app.request(path);
    expect(response.status).toBe(200); expect(response.headers.get('Cache-Control')).toBe('no-store');
  }
});

test('historical request detail preserves an absent routine source and original digest without enabling new admission', async () => {
  const input = {routineId: 'old-product', definitionRevision: 'a'.repeat(40), platform: 'android', laneId: 'phone', resources: [],
    build: {repository: 'Mentra-Community/MentraOS', channel: 'dev', headSha: 'b'.repeat(40)}};
  const inputSha256 = requestInputDigest(input), before = JSON.stringify(input);
  const row: StoredTestRequest = {requestId: 'old-request', hostId: 'mini', input, inputSha256, state: 'terminal', terminalStatus: 'not-run',
    hostRejection: {requestId: 'old-request', hostId: 'mini', inputSha256, rejectedAt: '2026-10-03T11:00:00Z', code: 'missing-definition', reason: 'Original source was unavailable.'}};
  class Results extends FrameworkResultService {
    override async detailByRun(): Promise<never> {throw new TestRunError(404, 'missing result');}
    override async detail(): Promise<never> {throw new TestRunError(404, 'missing result');}
  }
  class Requests extends TestRequestService {override async get() {return row;}}
  const response = await createTestRunAdminApi(undefined, undefined, new Results(), new Requests()).request('/old-request');
  expect(response.status).toBe(200);
  const body = await response.json() as {request: unknown};
  expect(body).toMatchObject({kind: 'request', request: {requestId: row.requestId, inputSha256, definitionRevision: input.definitionRevision}});
  expect(body.request).not.toHaveProperty('routineSource');
  expect(JSON.stringify(input)).toBe(before);
  expect(requestInputDigest(input)).toBe(inputSha256);
  await expect(new Requests().submit('new-request', 'mini', input)).rejects.toMatchObject({status: 400});
});

test('historical retired glasses input projects its original identity and digest without enabling new admission', async () => {
  const input = {routineId: 'retired-connection', definitionRevision: 'a'.repeat(40), platform: 'android' as const, laneId: 'old-android',
    routineSource: {...testRoutineSource(), minimumRoutineApiVersion: 43}, glassesModel: 'nimo',
    resources: [{id: 'old-glasses', kind: 'glasses' as const}],
    build: {repository: 'Mentra-Community/MentraOS', channel: 'dev' as const, headSha: 'b'.repeat(40)}};
  const before = JSON.stringify(input), inputSha256 = requestInputDigest(input);
  const row: StoredTestRequest = {requestId: 'retired-request', hostId: 'old-host', input, inputSha256,
    state: 'terminal', terminalStatus: 'not-run'};
  class Results extends FrameworkResultService {
    override async detailByRun(): Promise<never> {throw new TestRunError(404, 'missing result');}
    override async detail(): Promise<never> {throw new TestRunError(404, 'missing result');}
  }
  class Requests extends TestRequestService {override async get() {return row;}}
  const app = createTestRunAdminApi(undefined, undefined, new Results(), new Requests());
  const response = await app.request('/retired-request');
  expect(response.status).toBe(200);
  expect(await response.json()).toMatchObject({kind: 'request', request: {requestId: row.requestId, inputSha256,
    routineId: input.routineId, definitionRevision: input.definitionRevision, routineSource: input.routineSource, build: input.build}});
  expect(readAcceptedRoutineRequest(row)).toEqual({ready: true, input});
  expect(JSON.stringify(input)).toBe(before);
  expect(requestInputDigest(recordedFrameworkRequestInputSchema.parse(input))).toBe(inputSha256);
  await expect(new Requests().submit('new-request', 'old-host', input)).rejects.toMatchObject({status: 400});
  row.inputSha256 = 'c'.repeat(64);
  expect((await app.request('/retired-request')).status).toBe(503);
  expect(() => readAcceptedRoutineRequest(row)).toThrow('frozen input');
  for (const invalid of [{...input, platform: 'unknown'}, {...input, resources: [{id: 'old-glasses', kind: 'unknown'}]},
    {...input, routineSource: {...input.routineSource, minimumRoutineApiVersion: 0}},
    {...input, routineSource: {...input.routineSource, commit: 'c'.repeat(40)}},
    {...input, build: {...input.build, headSha: 'invalid'}}, {...input, glassesStart: {model: 'other'}}])
    expect(recordedFrameworkRequestInputSchema.safeParse(invalid).success).toBe(false);
});


test('activity and detail show input-free exact source preparation with its observed wait reason', async () => {
  const {TestRequestModel} = await import('../../models/test-request.model');
  const source = {channel: 'dev' as const, buildRunId: 1, publicationAttempt: 1};
  const intent = {requestId: 'waiting-main', routineId: 'new-main-routine', platform: 'android' as const, routineRevision: 'a'.repeat(40), laneId: 'phone', source,
    build: {repository: 'Mentra-Community/MentraOS' as const, channel: 'dev' as const, kind: 'android-apk' as const, headSha: 'b'.repeat(40), source,
      archive: {name: 'app.apk', url: 'https://artifactscdn.mentraglass.com/app.apk', size: 100, sha256: 'c'.repeat(64)}, receipt: {url: 'https://artifactscdn.mentraglass.com/receipt', size: 10, sha256: 'd'.repeat(64)}}};
  const row: StoredPreparingRequest = {requestId: intent.requestId, hostId: 'mini', state: 'preparing', dispatchIntent: intent, dispatchIntentSha256: requestInputDigest(intent),
    preparation: {code: 'minimum-routine-api', reason: 'Waiting for the required routine API installation.', observedAt: '2026-10-06T12:00:00Z'}};
  let selected: unknown;
  const find = spyOn(TestRequestModel, 'find').mockReturnValue({sort(){return this},limit(){return this},select(value: unknown){selected=value;return this},read(){return this},readConcern(){return this},lean:async()=>[row]} as any);
  class Results extends FrameworkResultService {override async detailByRun(): Promise<never> {throw new TestRunError(404,'missing')};override async detail(): Promise<never> {throw new TestRunError(404,'missing')}}
  class Requests extends TestRequestService {override async get() {return row}}
  try {
    const api = createTestRunAdminApi(undefined,undefined,new Results(),new Requests());
    const activity = await (await api.request('/activity')).json() as {requests: unknown[]};
    const detail = await (await api.request('/waiting-main')).json() as {request: unknown};
    expect(activity.requests).toEqual([detail.request]);
    expect(detail.request).toMatchObject({routineId:'new-main-routine',platform:'android',laneId:'phone',state:'preparing',definitionRevision:intent.routineRevision,reason:row.preparation!.reason});
    expect(detail.request).not.toHaveProperty('input');expect(detail.request).not.toHaveProperty('inputSha256');
    expect(selected).toMatchObject({dispatchIntent:1,dispatchIntentSha256:1,preparation:1});
  } finally {find.mockRestore()}
});

test('unbound fleet request keeps a stable exact-input URL and shows awaiting runner before assignment', async () => {
  const {portableRoutineSelectionSchema}=await import('../../types/routine-job.types')
  const selected=portableRoutineSelectionSchema.parse({requestId:'fleet-pending',routineId:'new-routine',platform:'android',routineRevision:'a'.repeat(40),
    source:{channel:'pr',prNumber:12,buildRunId:55,publicationAttempt:2},build:{repository:'Mentra-Community/MentraOS',headSha:'b'.repeat(40),channel:'pr',prNumber:12,
      kind:'android-apk',source:{channel:'pr',prNumber:12,buildRunId:55,publicationAttempt:2},
      archive:{name:'app.apk',url:'https://artifactscdn.mentraglass.com/app.apk',size:100,sha256:'c'.repeat(64)},
      receipt:{url:'https://artifactscdn.mentraglass.com/receipt.json',size:10,sha256:'d'.repeat(64)}}})
  const rows={async get(){return {requestId:selected.requestId,state:'awaiting-runner',fleetSelection:selected,fleetSelectionSha256:requestInputDigest(selected),
    fleetDeadline:new Date('2026-10-08T03:00:00Z')}}} as unknown as TestRequestService
  const results={async detailByRun(){throw new TestRunError(404,'missing')},async detail(){throw new TestRunError(404,'missing')}} as unknown as FrameworkResultService
  const app=createTestRunAdminApi(undefined,undefined,results,rows)
  const response=await app.request('/fleet-pending')
  expect(response.status).toBe(200);expect(await response.json()).toMatchObject({kind:'request',request:{requestId:'fleet-pending',state:'awaiting-runner',
    routineId:'new-routine',reason:'Awaiting a compatible testing runner.',build:{headSha:'b'.repeat(40)}}})
})


test("suite summary exposes bounded presentation without reading complete inputs", async () => {
  const reads = spyOn(TestSuiteService.prototype, "summaries").mockResolvedValue(new Map([["nightly-summary", {suiteId: "nightly-summary", members: []} as never]]));
  const full = spyOn(TestSuiteService.prototype, "detail").mockRejectedValue(new Error("Full inputs must not load"));
  try {
    const response = await createTestRunAdminApi().request("/suites/nightly-summary/summary");
    expect(response.status).toBe(200); expect(await response.json()).toEqual({suiteId: "nightly-summary", members: []});
    expect(reads).toHaveBeenCalledTimes(1); expect(reads.mock.calls[0]![0]).toEqual(["nightly-summary"]);
    expect(reads.mock.calls[0]![1]).toBeGreaterThan(Date.now()); expect(full).not.toHaveBeenCalled();
    expect(response.headers.get("Cache-Control")).toBe("no-store");
  } finally {reads.mockRestore();full.mockRestore();}
});

test("suite summary preserves missing and invalid-receipt errors", async () => {
  const reads=spyOn(TestSuiteService.prototype,"summaries");
  try {
    reads.mockResolvedValue(new Map());
    expect((await createTestRunAdminApi().request("/suites/missing/summary")).status).toBe(404);
    reads.mockResolvedValue(new Map([["invalid",new TestRunError(503,"Receipt differs")]]));
    const response=await createTestRunAdminApi().request("/suites/invalid/summary");
    expect(response.status).toBe(503);expect(await response.json()).toEqual({error:"test_run_error",message:"Receipt differs"});
  } finally {reads.mockRestore();}
});

test('unpublished rejection detail keeps its explicit reason without fabricating a run',async()=>{
 const input={routineSource:testRoutineSource(),routineId:'arbitrary',definitionRevision:'a'.repeat(40),platform:'ios-on-mac',laneId:'mac',resources:[],
  build:{repository:'Mentra-Community/MentraOS',channel:'dev',headSha:'b'.repeat(40),kind:'mac-ci-package',source:{channel:'dev',buildRunId:1,publicationAttempt:1},
  archive:{name:'app.zip',url:'https://artifactscdn.mentraglass.com/app.zip',size:100,sha256:'c'.repeat(64)},receipt:{url:'https://artifactscdn.mentraglass.com/receipt',size:10,sha256:'d'.repeat(64)}}};
 const publicationFailure={entityId:'original',payloadSha256:'d'.repeat(64),manifestSha256:'e'.repeat(64),operation:'result-create' as const,status:409 as const,code:'result_conflict' as const,message:'Invalid frozen fixture action',rejectedAt:'2026-10-09T00:00:00.000Z'};
 class Results extends FrameworkResultService {override async detailByRun():Promise<any>{throw new TestRunError(404,'missing')};override async detail():Promise<any>{throw new TestRunError(404,'missing')}}
 class Requests extends TestRequestService {override async get():Promise<any>{return{requestId:'original',hostId:'mini',inputSha256:requestInputDigest(input),input,state:'terminal',terminalStatus:'incomplete',publicationFailure}}}
 const body:any=await(await createTestRunAdminApi(undefined,undefined,new Results(),new Requests()).request('/original')).json();
 expect(body).toMatchObject({kind:'request',request:{state:'terminal',terminalStatus:'incomplete',reason:'Publication failed: Invalid frozen fixture action',reasonAt:publicationFailure.rejectedAt}});
 expect(body.run).toBeUndefined();
});

test('Admin gate cancellation requires operator identity and strict retained generation input', async () => {
 const calls: any[] = [], checks = {async cancelFromAdmin(...args: any[]) {calls.push(args); return {accepted: true}}};
 const gateId = 'pr-check-' + 'a'.repeat(64), body = {operationId: '00000000-0000-4000-8000-000000000001', coverageGeneration: 1, attemptGeneration: 2};
 const unauthenticated = createTestRunAdminApi(undefined, undefined, undefined, undefined, undefined, checks as any);
 expect((await unauthenticated.request(`/pr-checks/${gateId}/cancel`, {method: 'POST', body: JSON.stringify(body), headers: {'Content-Type': 'application/json'}})).status).toBe(403);
 const app = new Hono<any>(); app.use('*', async (c, next) => {c.set('developer', {developerId: 'operator-one', email: 'operator@example.test'}); await next()});
 app.route('/', createTestRunAdminApi(undefined, undefined, undefined, undefined, undefined, checks as any));
 expect((await app.request(`/pr-checks/${gateId}/cancel`, {method: 'POST', body: JSON.stringify({...body, shell: 'bad'}), headers: {'Content-Type': 'application/json'}})).status).toBe(400);
 expect((await app.request(`/pr-checks/${gateId}/cancel`, {method: 'POST', body: JSON.stringify(body), headers: {'Content-Type': 'application/json'}})).status).toBe(202);
 expect(calls).toEqual([[gateId, body, 'admin:operator-one']]);
});

test('activity reads and displays bounded fleet preparation failures', async () => {
 const {TestRequestModel}=await import('../../models/test-request.model');
 const {portableRoutineSelectionSchema}=await import('../../types/routine-job.types');
 const source={channel:'dev',buildRunId:1,publicationAttempt:1},selected=portableRoutineSelectionSchema.parse({requestId:'fleet-failure',routineId:'sample',platform:'android',routineRevision:'a'.repeat(40),source,
  build:{repository:'Mentra-Community/MentraOS',headSha:'b'.repeat(40),channel:'dev',kind:'android-apk',source,archive:{name:'app.apk',url:'https://artifactscdn.mentraglass.com/app.apk',size:100,sha256:'c'.repeat(64)},receipt:{url:'https://artifactscdn.mentraglass.com/receipt',size:10,sha256:'d'.repeat(64)}}});
 const row={requestId:selected.requestId,state:'awaiting-source',fleetSelection:selected,fleetSelectionSha256:requestInputDigest(selected),fleetPreparationStatus:{reason:'Routine source preparation failed during Git blobs; retrying the same request.'}};
 let projection:any;
 const find=spyOn(TestRequestModel,'find').mockReturnValue({sort(){return this},limit(){return this},select(value:any){projection=value;return this},read(){return this},readConcern(){return this},lean:async()=>[{...row,fleetPreparationStatus:projection?.fleetPreparationStatus?row.fleetPreparationStatus:undefined}]} as any);
 try{const response=await createTestRunAdminApi().request('/activity');expect(response.status).toBe(200);expect(await response.json()).toMatchObject({requests:[{requestId:selected.requestId,reason:row.fleetPreparationStatus.reason}]});expect(projection).toMatchObject({fleetPreparationStatus:1});}
 finally{find.mockRestore();}
});
test('Admin activity and request detail project the actual exclusive blocker through existing reason text, with safe unknown fallback', async () => {
  const {TestRequestModel} = await import('../../models/test-request.model');
  const source = {channel: 'dev', buildRunId: 1, publicationAttempt: 1};
  const selected = {requestId: 'account-waiting', routineId: 'account-google', platform: 'ios-on-mac', routineRevision: 'a'.repeat(40), source,
    build: {repository: 'Mentra-Community/MentraOS', headSha: 'b'.repeat(40), channel: 'dev', kind: 'mac-ci-package', source,
      archive: {name: 'app.zip', url: 'https://artifactscdn.mentraglass.com/app.zip', size: 100, sha256: 'c'.repeat(64)},
      receipt: {url: 'https://artifactscdn.mentraglass.com/receipt', size: 10, sha256: 'd'.repeat(64)}}};
  const row = {requestId: selected.requestId, state: 'awaiting-runner', fleetSelection: selected, fleetSelectionSha256: requestInputDigest(selected),
    fleetInputSha256: 'e'.repeat(64), fleetResourceAdmission: {intent: {operationId: `run:${selected.requestId}`, hostId: 'borrower', laneId: 'mac',
      owner: {id: selected.requestId, kind: 'run'}, inputSha256: 'e'.repeat(64), controller: {incarnation: 'one', generation: 1, sequence: 1},
      resources: [{id: 'fixtures', capabilities: ['google-authentication']}]},
      dependencies: [{resourceId: 'private-account', authorityHostId: 'mini', capability: 'google-authentication'}]}};
  const hosts = [{hostId: 'mini', lanes: [], receivedAt: '2026-10-17T01:00:00Z', authorityReservations: [{kind: 'exclusive',
    resourceId: 'private-account', authorityHostId: 'mini', borrowerHostId: 'private-host', laneId: 'private-lane', owner: {id: 'private-owner', kind: 'run'}}]}];
  let projection: any;
  const find = spyOn(TestRequestModel, 'find').mockReturnValue({sort(){return this},limit(){return this},select(value:any){projection=value;return this},read(){return this},readConcern(){return this},lean:async()=>[row]} as any);
  const read = spyOn(TestHostStateService.prototype, 'list').mockResolvedValue(hosts as any);
  const detail = spyOn(FrameworkResultService.prototype, 'detailByRun').mockRejectedValue(new TestRunError(404, 'pending'));
  const byRequest = spyOn(FrameworkResultService.prototype, 'detail').mockRejectedValue(new TestRunError(404, 'pending'));
  const requests = spyOn(TestRequestService.prototype, 'get').mockResolvedValue(row as any);
  try {
    const api = createTestRunAdminApi(), before = structuredClone(row);
    const activity = await (await api.request('/activity')).json() as any;
    const pending = await (await api.request('/account-waiting')).json() as any;
    expect(activity.requests[0].reason).toBe(sharedResourceWait('google-authentication'));
    expect(pending.request.reason).toBe(activity.requests[0].reason); expect(projection.fleetResourceAdmission).toBe(1);
    for (const secret of ['private-account', 'private-host', 'private-lane', 'private-owner']) expect(JSON.stringify(pending.request)).not.toContain(secret);
    expect(row).toEqual(before);
    read.mockRejectedValue(new Error('Authority observation unavailable'));
    expect((await (await api.request('/account-waiting')).json() as any).request.reason).toBe('Awaiting a compatible testing runner.');
    expect((await api.request('/activity')).status).toBe(200);
  } finally {find.mockRestore();read.mockRestore();detail.mockRestore();byRequest.mockRestore();requests.mockRestore();}
});

test('recovery button body uses existing authenticated lane-control admission and refuses anonymous operators', async () => {
  const {LaneControlsService} = await import('../../services/lane-controls.service')
  const observed: unknown[] = []
  class Controls extends LaneControlsService {
    override async submit(value: import('../../types/lane-control.types').LaneControlInput, operator: string, label?: string): Promise<import('../../types/lane-control.types').LaneControlView>
    override async submit(value: import('../../types/lane-control.types').ResourceControlInput, operator: string, label?: string): Promise<import('../../types/lane-control.types').ResourceControlView>
    override async submit(value: unknown, operator: string, label?: string): Promise<import('../../types/lane-control.types').LaneControlView | import('../../types/lane-control.types').ResourceControlView>
    override async submit(value: unknown, operator: string, operatorLabel?: string): Promise<import('../../types/lane-control.types').LaneControlView | import('../../types/lane-control.types').ResourceControlView> {
      const {laneControlInputSchema} = await import('../../types/lane-control.types')
      const input = laneControlInputSchema.parse(value); observed.push({input, operator, operatorLabel})
      return {operationId: input.operationId, hostId: input.hostId, laneId: input.laneId,
        action: input.action, expiresAt: input.expiresAt}
    }
  }
  const body = {operationId: '11111111-1111-4111-8111-111111111111', hostId: 'air', laneId: 'mac',
    expiresAt: Date.now() + 120000, action: 'reopen-repair', repair: {interruptionId: 'repair:mac:98',
      expectedHaltDecisionId: 'halt:98', changedConditions: 'I allowed microphone access.'}}
  const route = () => createTestRunAdminApi(undefined, undefined, undefined, undefined, undefined, undefined, new Controls())
  const options = {method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify(body)}
  expect((await route().request('/lanes/controls', options)).status).toBe(403)
  expect(observed).toEqual([])
  const app = new Hono<any>()
  app.use('*', async (c, next) => {c.set('developer', {developerId: 'signed-in-operator', email: 'signed-in@example.com'}); await next()})
  app.route('/', route())
  const response = await app.request('/lanes/controls', options)
  expect(response.status).toBe(202)
  expect(response.headers.get('Cache-Control')).toBe('no-store')
  expect(observed).toEqual([{input: body, operator: 'signed-in-operator', operatorLabel: 'signed-in@example.com'}])
  expect((await app.request('/lanes/controls', {...options, body: JSON.stringify({...body, ready: true})})).status).toBe(400)
  expect(observed).toHaveLength(1)
})

test('lane reserve forwards an authenticated operator-key label and preserves retries', async () => {
  const {LaneControlsService} = await import('../../services/lane-controls.service')
  const now = Date.now()
  let records: any[] = [], version = 0
  const controls = new LaneControlsService({async get() {return {hostId: 'air', laneControlVersion: version,
    laneControls: records, observedAt: new Date(now), receivedAt: new Date(now),
    snapshot: {laneControls: {schemaVersion: 1, receipts: []}, lanes: [{id: 'mac', dispatchMode: 'automatic'}]}}},
    async replace(_host, expected, next) {if (expected !== version) return false; records = next; version++; return true}}, () => now)
  const app = new Hono<any>()
  app.use('*', async (c, next) => {c.set('developer', {developerId: 'api_key:operator', email: 'credential:operator'}); await next()})
  app.route('/', createTestRunAdminApi(undefined, undefined, undefined, undefined, undefined, undefined, controls))
  const body = {operationId: '33333333-3333-4333-8333-333333333333', hostId: 'air', laneId: 'mac',
    expiresAt: now + 120000, action: 'reserve', purpose: 'Manual work'}
  const options = {method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify(body)}
  const first = await app.request('/lanes/controls', options)
  expect(first.status).toBe(202)
  const repeat = await app.request('/lanes/controls', options)
  expect(repeat.status).toBe(202)
  expect(await repeat.json()).toEqual(await first.json())
  expect(records).toHaveLength(1)
  expect(records[0].operatorLabel).toBe('credential:operator')
  expect(records[0].command).not.toHaveProperty('operatorLabel')
})