@trillboards/edge-sdk 0.2.224 → 0.2.226

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/deploy/windows/README.md +9 -4
  2. package/deploy/windows/ci/test-rollout-proofs.ps1 +300 -38
  3. package/deploy/windows/install-update.ps1 +5 -2
  4. package/deploy/windows/register-detector-task.ps1 +19 -1
  5. package/dist/AlertClips.d.ts +16 -1
  6. package/dist/AlertClips.d.ts.map +1 -1
  7. package/dist/AlertClips.js +35 -2
  8. package/dist/AlertClips.js.map +1 -1
  9. package/dist/CloudSensingManager.d.ts +33 -0
  10. package/dist/CloudSensingManager.d.ts.map +1 -1
  11. package/dist/CloudSensingManager.js +57 -0
  12. package/dist/CloudSensingManager.js.map +1 -1
  13. package/dist/DurableVlmCandidateSpool.d.ts +17 -0
  14. package/dist/DurableVlmCandidateSpool.d.ts.map +1 -1
  15. package/dist/DurableVlmCandidateSpool.js +46 -0
  16. package/dist/DurableVlmCandidateSpool.js.map +1 -1
  17. package/dist/EdgeAgent.js +1 -1
  18. package/dist/VideoSegmentUploader.d.ts +28 -2
  19. package/dist/VideoSegmentUploader.d.ts.map +1 -1
  20. package/dist/VideoSegmentUploader.js +53 -6
  21. package/dist/VideoSegmentUploader.js.map +1 -1
  22. package/dist/autoSense.d.ts +11 -1
  23. package/dist/autoSense.d.ts.map +1 -1
  24. package/dist/autoSense.js +33 -2
  25. package/dist/autoSense.js.map +1 -1
  26. package/dist/cli.d.ts.map +1 -1
  27. package/dist/cli.js +5 -1
  28. package/dist/cli.js.map +1 -1
  29. package/dist/connectorUpdate.d.ts +189 -38
  30. package/dist/connectorUpdate.d.ts.map +1 -1
  31. package/dist/connectorUpdate.js +333 -48
  32. package/dist/connectorUpdate.js.map +1 -1
  33. package/dist/connectorUpdateApply.d.ts +23 -1
  34. package/dist/connectorUpdateApply.d.ts.map +1 -1
  35. package/dist/connectorUpdateApply.js +72 -1
  36. package/dist/connectorUpdateApply.js.map +1 -1
  37. package/dist/connectorUpdateApplyMac.d.ts +4 -0
  38. package/dist/connectorUpdateApplyMac.d.ts.map +1 -1
  39. package/dist/connectorUpdateApplyMac.js +14 -0
  40. package/dist/connectorUpdateApplyMac.js.map +1 -1
  41. package/dist/diagnose.d.ts +1 -1
  42. package/dist/diagnose.js +1 -1
  43. package/dist/localSensing.d.ts +37 -2
  44. package/dist/localSensing.d.ts.map +1 -1
  45. package/dist/localSensing.js +65 -2
  46. package/dist/localSensing.js.map +1 -1
  47. package/dist/sensingRunMode.d.ts +12 -0
  48. package/dist/sensingRunMode.d.ts.map +1 -1
  49. package/dist/sensingRunMode.js.map +1 -1
  50. package/package.json +3 -3
  51. package/retained/WebsiteAdmissionCaptureClient.cjs +117 -11
  52. package/retained/WebsiteAdmissionState.cjs +1 -1
  53. package/retained/__tests__/website-admission-realtime.test.cjs +128 -4
  54. package/retained/__tests__/website-admission.test.cjs +27 -0
  55. package/retained/manager.cjs +11 -0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trillboards/edge-sdk",
3
- "version": "0.2.224",
3
+ "version": "0.2.226",
4
4
  "description": "Composable cross-platform Edge AI SDK for audience sensing on DOOH/CTV devices",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -11,8 +11,8 @@
11
11
  "scripts": {
12
12
  "build": "tsc",
13
13
  "postbuild": "chmod +x dist/cli.js dist/mcp-server.js",
14
- "test": "jest --passWithNoTests --forceExit && node --test retained/__tests__/runtime.test.cjs retained/__tests__/archive-lifecycle.test.cjs retained/__tests__/actor-perception.test.cjs retained/__tests__/actor-window.test.cjs retained/__tests__/website-admission.test.cjs retained/__tests__/realtime-schedule.test.cjs retained/__tests__/upgrade-backlog.test.cjs retained/__tests__/website-admission-realtime.test.cjs retained/__tests__/evidence-uploads.test.cjs scripts/__tests__/local-sense-wiring-detector.test.cjs",
15
- "test:retained": "node --test retained/__tests__/runtime.test.cjs retained/__tests__/archive-lifecycle.test.cjs retained/__tests__/actor-perception.test.cjs retained/__tests__/actor-window.test.cjs retained/__tests__/website-admission.test.cjs retained/__tests__/realtime-schedule.test.cjs retained/__tests__/upgrade-backlog.test.cjs retained/__tests__/website-admission-realtime.test.cjs retained/__tests__/evidence-uploads.test.cjs scripts/__tests__/local-sense-wiring-detector.test.cjs",
14
+ "test": "jest --passWithNoTests --forceExit && node --test retained/__tests__/runtime.test.cjs retained/__tests__/archive-lifecycle.test.cjs retained/__tests__/actor-perception.test.cjs retained/__tests__/actor-window.test.cjs retained/__tests__/website-admission.test.cjs retained/__tests__/realtime-schedule.test.cjs retained/__tests__/upgrade-backlog.test.cjs retained/__tests__/website-admission-realtime.test.cjs retained/__tests__/evidence-uploads.test.cjs scripts/__tests__/local-sense-wiring-detector.test.cjs scripts/__tests__/alert-safe-point-verdict.test.mjs",
15
+ "test:retained": "node --test retained/__tests__/runtime.test.cjs retained/__tests__/archive-lifecycle.test.cjs retained/__tests__/actor-perception.test.cjs retained/__tests__/actor-window.test.cjs retained/__tests__/website-admission.test.cjs retained/__tests__/realtime-schedule.test.cjs retained/__tests__/upgrade-backlog.test.cjs retained/__tests__/website-admission-realtime.test.cjs retained/__tests__/evidence-uploads.test.cjs scripts/__tests__/local-sense-wiring-detector.test.cjs scripts/__tests__/alert-safe-point-verdict.test.mjs",
16
16
  "clean": "rm -rf dist",
17
17
  "prepublishOnly": "npm run build"
18
18
  },
@@ -4,7 +4,7 @@ const fs = require('node:fs');
4
4
  const crypto = require('node:crypto');
5
5
  const assert = require('node:assert/strict');
6
6
  const { RetainedCaptureClient } = require('./RetainedCaptureClient.cjs');
7
- const { phoneSearchPolicy, admissionContextHash, choosePhoneReview, coversPhoneDecision, recheckAnchorAt } = require('./WebsiteAdmissionState.cjs');
7
+ const { phoneSearchPolicy, admissionContextHash, choosePhoneReview, coversPhoneDecision, recheckAnchorAt, RECHECK_ANCHOR_GRACE_MS } = require('./WebsiteAdmissionState.cjs');
8
8
  const hash = value => crypto.createHash('sha256').update(JSON.stringify(value ?? null)).digest('hex');
9
9
  const imageHash = bytes => crypto.createHash('sha256').update(bytes).digest('hex');
10
10
  function save(file, row) {
@@ -68,19 +68,41 @@ function advanceAdmission(admission, row, previous) {
68
68
  return { contextSha256, evidenceId: row.id, capturedAt: row.capturedAt, anchors };
69
69
  }
70
70
 
71
+ /** A live look the camera is owed: see liveLookDue. */
72
+ const LIVE_LOOK = Object.freeze({ selected: true, disposition: 'pending_review', selectionReason: 'live_look_interval' });
73
+
71
74
  /** The ordinary website still owns all conditions, timing and delivery.
72
75
  * Originals are archived first; only redundant observations INSIDE every active
73
- * wait window may be omitted from inference. No image is called reviewed unless
74
- * the actual model ran. Realtime scheduling exposes the current selection to
75
- * the shared scheduler; durable admission bookkeeping remains bounded per pump.
76
+ * wait window may be omitted from inference, and never the camera's live look
77
+ * (liveLookIntervalMs). No image is called reviewed unless the actual model ran.
78
+ * Realtime scheduling exposes the current selection to the shared scheduler;
79
+ * durable admission bookkeeping remains bounded per pump.
76
80
  */
77
81
  class WebsiteAdmissionCaptureClient extends RetainedCaptureClient {
78
82
  constructor(client, directory, options) {
79
83
  super(client, directory, options);
80
84
  assert(typeof options.pairedCameraId === 'string' && options.pairedCameraId, 'Paired camera identity required');
85
+ // How often a live alert camera is looked at when nothing in it changed, or while a
86
+ // wait/recheck window omits its changed frames (0 = only the grouping and the website
87
+ // decide). Texas, 2026-11-09: still cameras were looked at only when the frame grouper
88
+ // re-selected — every 5 s (a follow-up, or the reset each 5 s lease renewal causes) or 10 s
89
+ // (its quiet check) — while camera 23, whose drawn area changes on every frame, took the
90
+ // box's other 37% of looks. With a frame always waiting, the spool's least-recently-served
91
+ // rotation gives every camera one look per round. Not part of the archive POLICY: it moves
92
+ // which frames are reviewed, never how an original is captured or kept.
93
+ assert(options.liveLookIntervalMs === undefined || Number.isSafeInteger(options.liveLookIntervalMs)
94
+ && options.liveLookIntervalMs >= this.intervalMs && options.liveLookIntervalMs <= 60000, 'Invalid live look interval');
95
+ this.liveLookIntervalMs = options.liveLookIntervalMs ?? 0;
96
+ // When this camera's newest live look started (its frozen reviewSchedule.startedAtMs), so a
97
+ // restart decides from the same durable facts. See liveLookDue.
98
+ this.liveLookStartedAtMs = null;
99
+ for (const row of this.records.values()) this.noteLiveLookStart(row);
81
100
  this.pairedCameraId = options.pairedCameraId;
82
101
  this.deferred = new Map();
83
102
  this.states = new Map();
103
+ // Per admission context: when its soonest unconfirmed wait/recheck follow-up
104
+ // falls due (anchor capture + the rule's wait). See nextAlertFollowUpDueAtMs.
105
+ this.followUpDue = new Map();
84
106
  this.admissionMetadata = new Map();
85
107
  this.phoneReceipts = new Map();
86
108
  this.phoneProofChecks = new Map();
@@ -112,7 +134,41 @@ class WebsiteAdmissionCaptureClient extends RetainedCaptureClient {
112
134
  }
113
135
  return null;
114
136
  }
115
- admissionSelection(row) {
137
+ /**
138
+ * A live realtime original is owed a look once it is liveLookIntervalMs past the start of
139
+ * the camera's newest live look (before any look has started, past its newest selection),
140
+ * whatever the grouping or a wait window says. From then until the next look starts, each
141
+ * newer original replaces it (realtime: newest wins), so the look reads a frame at most one
142
+ * capture old. A changed frame still selects at once (grouping); this bounds how long an
143
+ * unchanged camera goes unseen.
144
+ *
145
+ * Why the look's start: when the box is the bound, a camera's turn comes once per round, and
146
+ * the cadence the camera actually gets is the gap between the CAPTURE times of the frames
147
+ * its turns read. Measured on the Texas shape (5 cameras, 700 ms looks, a 3.5 s round):
148
+ * counting from the newest selection put the reviewed frames on the interval's own grid and
149
+ * on the grouper's follow-ups (gaps 3.0-5.0 s, frames up to 1.7 s old); counting from the
150
+ * look's start gives gaps of the round itself, at a fraction of the spool writes that
151
+ * selecting every frame costs, and none on a box with room. The start is the frozen
152
+ * reviewSchedule.startedAtMs, so a restart decides from the same durable facts.
153
+ */
154
+ liveLookDue(row, lastSelectedAt) {
155
+ if (!(this.liveLookIntervalMs > 0) || !this.realtime || row.reviewStage === null || !this.knownRealtime(row)) return false;
156
+ const since = this.liveLookStartedAtMs ?? lastSelectedAt;
157
+ return Number.isSafeInteger(since) && row.capturedAt - since >= this.liveLookIntervalMs;
158
+ }
159
+ /**
160
+ * A live look (latest or follow-up slot, never backlog) that has started: its frozen start
161
+ * time. At load the newest archived start wins; a look starting now always replaces it, so a
162
+ * store-PC clock stepped backwards cannot leave a future start blocking the camera's looks.
163
+ */
164
+ noteLiveLookStart(row, startingNow = false) {
165
+ const schedule = row?.reviewSchedule;
166
+ if (!schedule || !['latest', 'follow_up'].includes(schedule.slot) || !Number.isSafeInteger(schedule.startedAtMs)) return;
167
+ if (startingNow || this.liveLookStartedAtMs === null || schedule.startedAtMs > this.liveLookStartedAtMs) {
168
+ this.liveLookStartedAtMs = schedule.startedAtMs;
169
+ }
170
+ }
171
+ admissionSelection(row, lastSelectedAt = this.previousSelectedRecord?.capturedAt ?? null) {
116
172
  const admission = this.admission(row.candidate.reviewContext, row.capturedAt);
117
173
  const remembered = this.states.get(admissionContextHash(row.candidate.reviewContext));
118
174
  const state = remembered && remembered.capturedAt < row.capturedAt ? remembered : null;
@@ -122,12 +178,20 @@ class WebsiteAdmissionCaptureClient extends RetainedCaptureClient {
122
178
  const waiting = anchors.length > 0 && anchors.every(({ rule, anchor }) =>
123
179
  anchor && !anchor.confirmed && row.capturedAt < anchor.capturedAt + rule.waitMs);
124
180
  const followUp = this.followUpFor(row, anchors);
181
+ const lookDue = this.liveLookDue(row, lastSelectedAt);
125
182
  let choice;
126
- if (waiting) choice = { selected: false, disposition: 'archived_wait_window', selectionReason: 'before_all_website_wait_deadlines' };
183
+ // The server's wait/recheck clock ignores answers inside the window (routeReviewTiming:
184
+ // intermediate answers cannot cancel or clear an episode), so a live look there only keeps
185
+ // the camera watched; the deadline endpoint keeps its own reserved, urgent slot.
186
+ if (waiting) choice = lookDue ? LIVE_LOOK
187
+ : { selected: false, disposition: 'archived_wait_window', selectionReason: 'before_all_website_wait_deadlines' };
127
188
  else if (admission && (!state || expired || followUp)) choice = { selected: true, disposition: 'pending_review',
128
189
  selectionReason: followUp ? 'website_wait_deadline_check' : 'website_initial_or_context_change' };
129
- else choice = super.chooseReview(row.candidate, row.imageSha256,
130
- this.nextDue === null || row.capturedAt >= this.nextDue, row.reviewStage);
190
+ else {
191
+ choice = super.chooseReview(row.candidate, row.imageSha256,
192
+ this.nextDue === null || row.capturedAt >= this.nextDue, row.reviewStage);
193
+ if (lookDue && !choice.selected && choice.disposition === 'archived_grouped_unchanged') choice = LIVE_LOOK;
194
+ }
131
195
  return { choice, anchors, followUp };
132
196
  }
133
197
  commitAdmissionSelection(row, { choice, anchors, followUp }) {
@@ -199,7 +263,18 @@ class WebsiteAdmissionCaptureClient extends RetainedCaptureClient {
199
263
  }
200
264
  const inPrefix = new Set(prefix.map(row => row.id));
201
265
  if (!prefix.length || [...this.entries.keys()].some(id => !inPrefix.has(id))) return null;
202
- const choices = new Map(prefix.map(row => [row.id, this.admissionSelection(row)]));
266
+ // One pass decides several originals before committing any: each selection it makes is
267
+ // the camera's newest by the time the next original is decided, so a live look falls due
268
+ // liveLookIntervalMs after it, not after the last committed selection.
269
+ let lastSelectedAt = this.previousSelectedRecord?.capturedAt ?? null;
270
+ const choices = new Map();
271
+ for (const row of prefix) {
272
+ const selection = this.admissionSelection(row, lastSelectedAt);
273
+ choices.set(row.id, selection);
274
+ if ((row.selected || selection.choice.selected) && (lastSelectedAt === null || row.capturedAt > lastSelectedAt)) {
275
+ lastSelectedAt = row.capturedAt;
276
+ }
277
+ }
203
278
  const eligible = prefix.filter(row => row.selected || choices.get(row.id).choice.selected);
204
279
  const target = eligible.find(row => this.followUpOf(row) || choices.get(row.id).followUp) ?? eligible.at(-1);
205
280
  let writes = 0;
@@ -276,7 +351,33 @@ class WebsiteAdmissionCaptureClient extends RetainedCaptureClient {
276
351
  const admission = this.admission(row.candidate.reviewContext, row.capturedAt);
277
352
  if (!admission) return;
278
353
  const key = admissionContextHash(row.candidate.reviewContext);
279
- this.states.set(key, advanceAdmission(admission, row, this.states.get(key)));
354
+ const state = advanceAdmission(admission, row, this.states.get(key));
355
+ this.states.set(key, state);
356
+ let due = null;
357
+ for (const rule of admission.rules) {
358
+ const anchor = state.anchors[rule.routeId];
359
+ if (!anchor || anchor.confirmed) continue;
360
+ const at = anchor.capturedAt + rule.waitMs;
361
+ if (due === null || at < due) due = at;
362
+ }
363
+ if (due === null) this.followUpDue.delete(key); else this.followUpDue.set(key, due);
364
+ }
365
+ /**
366
+ * When this camera's soonest unconfirmed wait/recheck follow-up falls due (capture clock), or null.
367
+ * connectorUpdate's alert_work safe point: a follow-up due while the box restarts waits for the
368
+ * restart. It stays due (in the past) until its look is answered, confirming or clearing the anchor;
369
+ * an anchor older than wait + the server's grace confirms nothing (recheckAnchorAt) and is ignored,
370
+ * and so is a context the archive no longer holds. The anchor itself is rebuilt from the durable
371
+ * archive at startup, so a follow-up due after the restart is not at risk.
372
+ */
373
+ nextAlertFollowUpDueAtMs(nowMs = this.realtime?.now?.() ?? Date.now()) {
374
+ let next = null;
375
+ for (const [key, due] of this.followUpDue) {
376
+ if (!this.states.has(key)) { this.followUpDue.delete(key); continue; }
377
+ if (nowMs > due + RECHECK_ANCHOR_GRACE_MS) continue;
378
+ if (next === null || due < next) next = due;
379
+ }
380
+ return next;
280
381
  }
281
382
  archivePins() {
282
383
  const pins = super.archivePins();
@@ -459,7 +560,12 @@ class WebsiteAdmissionCaptureClient extends RetainedCaptureClient {
459
560
  && imageHash(fs.readFileSync(this.image(first))) === anchor.imageSha256,
460
561
  'Website wait anchor missing or changed; keep evidence pending');
461
562
  }
462
- const prepared = await super.prepare(request);
563
+ // The base freezes reviewSchedule.startedAtMs before its first await, and not at all when
564
+ // it refuses the request, so only a look that actually started moves the live-look clock.
565
+ const live = this.records.get(request.evidenceId), unanswered = !live?.result;
566
+ const preparing = super.prepare(request);
567
+ if (unanswered) this.noteLiveLookStart(this.records.get(request.evidenceId), true);
568
+ const prepared = await preparing;
463
569
  this.remember(this.records.get(request.evidenceId));
464
570
  return prepared;
465
571
  }
@@ -72,4 +72,4 @@ function coversPhoneDecision(row, decision, contextSha256) {
72
72
  && row.capturedAt >= decision.fromCapturedAtMs && row.capturedAt < decision.untilCapturedAtMs;
73
73
  }
74
74
 
75
- module.exports = { phoneSearchPolicy, admissionContextHash, choosePhoneReview, coversPhoneDecision, recheckAnchorAt };
75
+ module.exports = { phoneSearchPolicy, admissionContextHash, choosePhoneReview, coversPhoneDecision, recheckAnchorAt, RECHECK_ANCHOR_GRACE_MS };
@@ -9,6 +9,7 @@ const fs = require('node:fs'), os = require('node:os'), path = require('node:pat
9
9
  const { WebsiteAdmissionCaptureClient, readAdmission } = require('../WebsiteAdmissionCaptureClient.cjs');
10
10
  const { RetainedCaptureClient, RECHECK_ANCHOR_GRACE_MS } = require('../RetainedCaptureClient.cjs');
11
11
  const { DurableVlmCandidateSpool } = require('../../dist/DurableVlmCandidateSpool');
12
+ const { FrameGroupingShadow, groupingScopes } = require('../../dist/FrameGroupingShadow');
12
13
  const admissionApi = require('../../../../../trillboard-api/services/retainedWebsiteReviewAdmission');
13
14
  const timing = require('../../../../../trillboard-api/services/fein/routeReviewTiming');
14
15
  const { isHistoricalReview } = require('../../../../../trillboard-api/services/retainedCctvReviewProtocol');
@@ -48,8 +49,20 @@ function context(name, at, extra = {}) {
48
49
  delete captured.websiteReviewAdmission;
49
50
  return captured;
50
51
  }
51
- function rig(t, names = ['phone'], { freshnessMs = LIVE_BOUND_MS } = {}) {
52
+ // The website manager's grouping for an immediate rule (retained/manager.cjs: every website
53
+ // camera's rule is immediate, so followUpMs is 5000).
54
+ const GROUPING = { mode: 'shadow', separateProfileWork: true, pixelDelta: 12, minChangedPixels: 12,
55
+ quietIntervalMs: 10000, followUpMs: 5000 };
56
+ // The motion-resolution grey frame the grouper compares. A still scene repeats it exactly; a
57
+ // moving one shifts 40 bright pixels on every frame, a visible change each time (Texas camera 23).
58
+ function scene(at, moving) {
59
+ const data = new Uint8Array(32 * 24).fill(90);
60
+ if (moving) for (let i = 0; i < 40; i++) data[(i * 13 + Math.floor(at / 100)) % data.length] = 220;
61
+ return { width: 32, height: 24, data };
62
+ }
63
+ function rig(t, names = ['phone'], { freshnessMs = LIVE_BOUND_MS, grouping = false, liveLookIntervalMs, moving = [] } = {}) {
52
64
  const root = fs.mkdtempSync(path.join(os.tmpdir(), 'website-admission-realtime-'));
65
+ const groupers = new Map();
53
66
  const state = { now: 1000, answer: true, accepted: true, receiptVersion: 1 };
54
67
  const archives = new Map(), clients = new Map(), current = new Map(), server = new Map();
55
68
  const calls = [], uploads = [];
@@ -89,6 +102,8 @@ function rig(t, names = ['phone'], { freshnessMs = LIVE_BOUND_MS } = {}) {
89
102
  cameraId: name, pairedCameraId: 'paired-' + name, intervalMs: 500, offerWindow: 16,
90
103
  maxCaptures: 1000, maxBytes: 128 * 1024 ** 2, archiveRetentionMs: 600000,
91
104
  realtimeReview: { freshnessMs, now: () => state.now }, admissionNowMs: () => state.now,
105
+ ...(grouping ? { selectionMode: 'state-change-v1', groupingPolicy: GROUPING } : {}),
106
+ ...(liveLookIntervalMs === undefined ? {} : { liveLookIntervalMs }),
92
107
  });
93
108
  archive.attachReviewQueue(spool); archives.set(name, archive); return archive;
94
109
  }
@@ -100,9 +115,17 @@ function rig(t, names = ['phone'], { freshnessMs = LIVE_BOUND_MS } = {}) {
100
115
  function capture(name, at, extra = {}) {
101
116
  state.now = at;
102
117
  const captured = context(name, at, extra); current.set(name, captured);
103
- const archive = archives.get(name);
104
- archive.retainOrderedCapture({ name, enqueuedAtMs: at, jpeg: original(), captureMode: 'periodic',
105
- reason: 'motion', signature: String(at), reviewKind: 'event', reviewContext: captured });
118
+ const archive = archives.get(name), jpeg = original();
119
+ // With grouping on, the real grouper decides from the scene, exactly as CloudSensingManager feeds it.
120
+ let groupingShadow;
121
+ if (grouping) {
122
+ if (!groupers.has(name)) groupers.set(name, new FrameGroupingShadow(GROUPING));
123
+ groupingShadow = groupers.get(name).observe(scene(at, moving.includes(name)), groupingScopes(captured),
124
+ captured, at, sha(jpeg));
125
+ }
126
+ archive.retainOrderedCapture({ name, enqueuedAtMs: at, jpeg, captureMode: 'periodic',
127
+ reason: 'motion', signature: String(at), reviewKind: 'event', reviewContext: captured,
128
+ ...(groupingShadow ? { groupingShadow } : {}) });
106
129
  return archive.previousCaptureRecord;
107
130
  }
108
131
  function pump() {
@@ -302,6 +325,107 @@ test('three website cameras rotate fairly while one producer accumulates changed
302
325
  assert.deepEqual(served.slice(turn, turn + 3).sort(), ['door', 'lot', 'paint']);
303
326
  });
304
327
 
328
+ // A still camera, decided by the real grouper: without a live-look interval it is looked at
329
+ // only when the grouper re-selects (its first view, the 5 s follow-up, then the 10 s quiet
330
+ // check), the cadence the Texas store's still cameras showed on 2026-11-09.
331
+ test('a still website camera is looked at every live-look interval, not only when the grouper re-selects', async t => {
332
+ const runs = new Map();
333
+ for (const liveLookIntervalMs of [undefined, 2000]) {
334
+ const r = rig(t, ['person'], { grouping: true, liveLookIntervalMs }); r.state.answer = false;
335
+ const looked = [];
336
+ for (let at = 1000; at <= 12000; at += 500) {
337
+ r.capture('person', at, { websiteReviewAdmission: undefined });
338
+ if (r.pump().length) { const item = await r.review(); await r.upload(); looked.push(item.enqueuedAtMs); }
339
+ }
340
+ runs.set(liveLookIntervalMs, { r, looked });
341
+ }
342
+ assert.deepEqual(runs.get(undefined).looked, [1000, 6000]);
343
+ const { r, looked } = runs.get(2000);
344
+ assert.deepEqual(looked, [1000, 3000, 5000, 6000, 8000, 10000, 12000]);
345
+ const reasons = looked.map(at => [...r.archives.get('person').records.values()].find(row => row.capturedAt === at).selectionReason);
346
+ assert.deepEqual(reasons, ['group_selected', 'live_look_interval', 'live_look_interval', 'group_selected',
347
+ 'live_look_interval', 'live_look_interval', 'live_look_interval']);
348
+ const skipped = [...r.archives.get('person').records.values()].filter(row => !looked.includes(row.capturedAt));
349
+ assert(skipped.length && skipped.every(row => row.disposition === 'archived_grouped_unchanged'),
350
+ 'Between live looks an unchanged frame stays a saved, unreviewed grouped view');
351
+ });
352
+
353
+ test('a website wait window keeps the camera\'s live look; the server still confirms only at the deadline', async t => {
354
+ const r = rig(t, ['phone'], { liveLookIntervalMs: 2000 });
355
+ const first = r.capture('phone', 1000); await r.serve(); // true: the ten-second wait starts at 1000
356
+ const looked = [], eligible = [];
357
+ for (let at = 1500; at < 11000; at += 500) {
358
+ r.capture('phone', at);
359
+ if (r.pump().length) {
360
+ const item = await r.review(), delivered = await r.upload();
361
+ looked.push(item.enqueuedAtMs); eligible.push(delivered.decision.eligible);
362
+ }
363
+ }
364
+ assert.deepEqual(looked, [3000, 5000, 7000, 9000]);
365
+ assert.deepEqual(eligible, [false, false, false, false], 'A positive inside the window confirms nothing');
366
+ const omitted = [...r.archives.get('phone').records.values()].filter(row => row.capturedAt > 1000 && !looked.includes(row.capturedAt));
367
+ assert(omitted.length && omitted.every(row => row.disposition === 'archived_wait_window'));
368
+ const due = r.capture('phone', 11000); r.pump();
369
+ const item = r.spool.take(undefined, 'review');
370
+ assert.equal(item.spoolId, due.id);
371
+ assert.equal(item.reviewPriority, 'urgent', 'The deadline endpoint keeps its reserved, urgent slot');
372
+ await r.review(item); const delivered = await r.upload();
373
+ assert.equal(delivered.decision.eligible, true);
374
+ assert.equal(delivered.decision.confirmationBasis, 'first_and_follow_up');
375
+ assert.equal(delivered.decision.state.anchorCapturedAtMs, first.capturedAt);
376
+ });
377
+
378
+ // The Texas store PC at night, 2026-11-09: five alert cameras, camera 23's drawn area changing on
379
+ // every frame and the other four still, on a box that finishes ~1.46 looks a second. Served one at
380
+ // a time here, 700 ms each on the 100 ms clock: the same throughput.
381
+ async function texasNight(t, liveLookIntervalMs) {
382
+ const names = ['c20', 'c22', 'c23', 'c24', 'c3'], LOOK_MS = 700;
383
+ const r = rig(t, names, { grouping: true, liveLookIntervalMs, moving: ['c23'] }); r.state.answer = false;
384
+ const looks = [];
385
+ let busyUntil = 0;
386
+ for (let at = 1000; at <= 61000; at += 100) {
387
+ // Each camera captures every 500 ms, 100 ms after the previous one (the manager's feed stagger).
388
+ r.capture(names[(at / 100) % names.length], at, { websiteReviewAdmission: undefined });
389
+ r.pump();
390
+ if (at < busyUntil) continue;
391
+ const item = r.spool.take(at, 'review');
392
+ if (!item) continue;
393
+ await r.review(item); await r.upload();
394
+ looks.push({ name: item.name, capturedAt: item.enqueuedAtMs, startedAt: at });
395
+ busyUntil = at + LOOK_MS;
396
+ }
397
+ const pct = (values, q) => { const v = [...values].sort((a, b) => a - b); return v[Math.min(v.length - 1, Math.floor(q * v.length))]; };
398
+ const cameras = {};
399
+ for (const name of names) {
400
+ const mine = looks.filter(look => look.name === name);
401
+ const gaps = mine.slice(1).map((look, i) => look.capturedAt - mine[i].capturedAt);
402
+ cameras[name] = { looks: mine.length, share: mine.length / looks.length, gapP50: pct(gaps, 0.5), gapP90: pct(gaps, 0.9),
403
+ gapMax: Math.max(...gaps), ageMax: Math.max(...mine.map(look => look.startedAt - look.capturedAt)) };
404
+ }
405
+ return { looks, cameras };
406
+ }
407
+
408
+ test('Texas shape: the still cameras starve beside the changing one without a live-look interval', async t => {
409
+ const { cameras } = await texasNight(t, undefined);
410
+ t.diagnostic(JSON.stringify(cameras));
411
+ assert(cameras.c23.share > 0.5, 'camera 23 took ' + cameras.c23.share);
412
+ for (const name of ['c20', 'c22', 'c24', 'c3']) assert(cameras[name].gapP90 >= 9500, name + ' ' + JSON.stringify(cameras[name]));
413
+ });
414
+
415
+ test('Texas shape: with the live-look interval every camera gets one look per round, none above its share', async t => {
416
+ const { looks, cameras } = await texasNight(t, 2000);
417
+ t.diagnostic(JSON.stringify(cameras));
418
+ const share = looks.length / 5;
419
+ for (const [name, camera] of Object.entries(cameras)) {
420
+ const detail = name + ' ' + JSON.stringify(camera);
421
+ assert(Math.abs(camera.looks - share) <= 1.5, 'not one look per round: ' + detail);
422
+ // Five cameras x 700 ms: a round is 3.5 s.
423
+ assert(camera.gapP50 <= 4000 && camera.gapP90 <= 4000 && camera.gapMax <= 5000, detail);
424
+ // A still camera's waiting frame is never older than the interval plus one capture.
425
+ assert(camera.ageMax <= 2500, 'stale frame served: ' + detail);
426
+ }
427
+ });
428
+
305
429
  const exemptions = {
306
430
  temporalReviewContract: { version: 1, cameraId: 'phone', field: 'phone_use', mode: 'any', minObservations: 1,
307
431
  durationMs: 0, maxGapMs: 2000, unknownPolicy: 'reset_confirmation_keep_alert_latch' },
@@ -172,6 +172,33 @@ test('slow inference never adds duration, and a negative follow-up clears the an
172
172
  assert.equal([...f.archive.states.values()][0].anchors['fixture-phone'].capturedAt, 11500);
173
173
  });
174
174
 
175
+ test('a connector update sees the follow-up a wait window owes until its look is answered, across a restart', async t => {
176
+ const f = fixture(t);
177
+ assert.equal(f.archive.nextAlertFollowUpDueAtMs(500), null); // no wait window open
178
+ f.capture(1000); await f.deliver(); // the first sighting anchors a 10-s wait
179
+ assert.equal(f.archive.nextAlertFollowUpDueAtMs(2000), 11000);
180
+ // The anchor is durable: a restarted connector owes the same follow-up.
181
+ assert.equal(f.recover().nextAlertFollowUpDueAtMs(2000), 11000);
182
+ for (let at = 1500; at <= 11000; at += 500) f.capture(at);
183
+ // Due and still unanswered: past due, still owed.
184
+ assert.equal(f.archive.nextAlertFollowUpDueAtMs(11200), 11000);
185
+ const [followUp] = f.archive.pendingOrderedCandidates();
186
+ assert.equal(followUp.reviewPriority, 'urgent');
187
+ await f.deliver(followUp); // positive: the anchor is confirmed, nothing more is owed
188
+ assert.equal(f.archive.nextAlertFollowUpDueAtMs(12000), null);
189
+ });
190
+
191
+ test('a follow-up stops being owed when its look clears the anchor, or when the anchor expires unanswered', async t => {
192
+ const f = fixture(t); f.capture(1000); await f.deliver();
193
+ for (let at = 1500; at <= 11000; at += 500) f.capture(at);
194
+ f.answer(false); await f.deliver(f.archive.pendingOrderedCandidates()[0]);
195
+ assert.equal(f.archive.nextAlertFollowUpDueAtMs(11500), null);
196
+ // An anchor older than wait + the server's 60-s grace confirms nothing (recheckAnchorAt).
197
+ const g = fixture(t); g.capture(1000); await g.deliver();
198
+ assert.equal(g.archive.nextAlertFollowUpDueAtMs(11000 + 60000), 11000);
199
+ assert.equal(g.archive.nextAlertFollowUpDueAtMs(11000 + 60001), null);
200
+ });
201
+
175
202
  test('unknown endpoint retains the anchor and reviews the next frame, not a fabricated negative', async t => {
176
203
  const f = fixture(t); f.capture(1000); await f.deliver(); f.capture(11000); f.capture(11500);
177
204
  f.answer(null); await f.deliver();
@@ -28,6 +28,16 @@ function assertSelectedModelsPrepared(models, actorPolicy, requiresDetector) {
28
28
  // artifact identity still pass before capture; this is not a second installer.
29
29
  /** LocalDetectorClient's own per-call default, which every other detector call of a look waits. */
30
30
  const PAIRED_DETECTOR_CALL_MS = 5000;
31
+ /**
32
+ * A website alert camera's newest frame is reviewed once it is this far past both the camera's
33
+ * newest selection and the start of its newest look, changed or not
34
+ * (WebsiteAdmissionCaptureClient.liveLookDue). Half the 4 s look target: when the box is the
35
+ * bound, every camera has a fresh frame waiting before its turn comes, so the spool's
36
+ * least-recently-served rotation splits the box evenly (Texas: five cameras, ~1.46 looks/s with
37
+ * two in flight, one look per camera every ~3.4 s, each of a frame ~1.4 s old); on a box with
38
+ * room a still camera is looked at every 2-2.5 s. A changed frame still selects at once.
39
+ */
40
+ const LIVE_LOOK_INTERVAL_MS = 2000;
31
41
 
32
42
  async function createWebsiteManager(input, stateDirectory, deps = {}) {
33
43
  const config = JSON.parse(JSON.stringify(input));
@@ -171,6 +181,7 @@ async function createWebsiteManager(input, stateDirectory, deps = {}) {
171
181
  offerWindow: rule.mode === 'wait_recheck' ? 1 : 16, unclearRetryMs: 2000,
172
182
  // Latest frame wins per camera; capture-order contracts keep their window.
173
183
  realtimeReview: { freshnessMs },
184
+ ...(websiteManaged ? { liveLookIntervalMs: LIVE_LOOK_INTERVAL_MS } : {}),
174
185
  ...(rule.mode==='immediate'?{actorPerceiver:new SelectedActorPerceptionClient(binding)}:{}),
175
186
  });
176
187
  loop.client = client; clients.push(client);