@trillboards/edge-sdk 0.2.196 → 0.2.200
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.
- package/deploy/detector/pyproject.toml +1 -1
- package/deploy/detector/tests/test_colors_v2.py +79 -0
- package/deploy/detector/tests/test_detection_colors_wire.py +25 -0
- package/deploy/detector/tests/test_held_phone_customer_packaging.py +102 -0
- package/deploy/detector/trillboards_detector/_version.py +2 -2
- package/deploy/detector/trillboards_detector/colors.py +30 -11
- package/deploy/detector/trillboards_detector/server.py +1 -1
- package/deploy/litertlm/test_attention_token_budget.py +57 -0
- package/deploy/litertlm/trillboards_litertlm_shim.py +96 -1
- package/deploy/macos/build-macos-pkg.sh +14 -2
- package/deploy/windows/build-windows.ps1 +12 -2
- package/deploy/windows/ci/test-published-install.ps1 +167 -8
- package/deploy/windows/setup-detector.ps1 +4 -1
- package/dist/DetectionColors.d.ts +11 -4
- package/dist/DetectionColors.d.ts.map +1 -1
- package/dist/DetectionColors.js +5 -2
- package/dist/DetectionColors.js.map +1 -1
- package/dist/DetectorFields.d.ts +138 -4
- package/dist/DetectorFields.d.ts.map +1 -1
- package/dist/DetectorFields.js +101 -11
- package/dist/DetectorFields.js.map +1 -1
- package/dist/EdgeAgent.js +1 -1
- package/dist/LiteRtVlmProvider.d.ts.map +1 -1
- package/dist/LiteRtVlmProvider.js +10 -1
- package/dist/LiteRtVlmProvider.js.map +1 -1
- package/dist/PhoneEmbeddingClassifier.d.ts +28 -0
- package/dist/PhoneEmbeddingClassifier.d.ts.map +1 -0
- package/dist/PhoneEmbeddingClassifier.js +40 -0
- package/dist/PhoneEmbeddingClassifier.js.map +1 -0
- package/dist/RetainedFieldContract.d.ts +9 -1
- package/dist/RetainedFieldContract.d.ts.map +1 -1
- package/dist/RetainedFieldContract.js +19 -3
- package/dist/RetainedFieldContract.js.map +1 -1
- package/dist/ScopedVlmReview.d.ts +6 -2
- package/dist/ScopedVlmReview.d.ts.map +1 -1
- package/dist/ScopedVlmReview.js +55 -5
- package/dist/ScopedVlmReview.js.map +1 -1
- package/dist/SensingProfileClient.d.ts +6 -0
- package/dist/SensingProfileClient.d.ts.map +1 -1
- package/dist/SensingProfileClient.js +7 -0
- package/dist/SensingProfileClient.js.map +1 -1
- package/dist/diagnose.d.ts +1 -1
- package/dist/diagnose.js +1 -1
- package/dist/localSensing.d.ts +5 -2
- package/dist/localSensing.d.ts.map +1 -1
- package/dist/localSensing.js +56 -8
- package/dist/localSensing.js.map +1 -1
- package/package.json +3 -3
- package/retained/ProfileAuthorityClient.cjs +1 -1
- package/retained/RetainedCaptureClient.cjs +2 -1
- package/retained/WebsiteAdmissionCaptureClient.cjs +478 -0
- package/retained/WebsiteAdmissionState.cjs +75 -0
- package/retained/__tests__/actor-perception.test.cjs +1 -1
- package/retained/__tests__/actor-window.test.cjs +1 -1
- package/retained/__tests__/archive-lifecycle.test.cjs +1 -1
- package/retained/__tests__/runtime.test.cjs +30 -2
- package/retained/__tests__/website-admission-realtime.test.cjs +503 -0
- package/retained/__tests__/website-admission.test.cjs +806 -0
- package/retained/manager.cjs +4 -1
- package/retained/pilot-profile-client.cjs +2 -1
|
@@ -0,0 +1,478 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const fs = require('node:fs');
|
|
4
|
+
const crypto = require('node:crypto');
|
|
5
|
+
const assert = require('node:assert/strict');
|
|
6
|
+
const { RetainedCaptureClient } = require('./RetainedCaptureClient.cjs');
|
|
7
|
+
const { phoneSearchPolicy, admissionContextHash, choosePhoneReview, coversPhoneDecision, recheckAnchorAt } = require('./WebsiteAdmissionState.cjs');
|
|
8
|
+
const hash = value => crypto.createHash('sha256').update(JSON.stringify(value ?? null)).digest('hex');
|
|
9
|
+
const imageHash = bytes => crypto.createHash('sha256').update(bytes).digest('hex');
|
|
10
|
+
function save(file, row) {
|
|
11
|
+
const tmp = file + '.admission-tmp', fd = fs.openSync(tmp, 'w');
|
|
12
|
+
try { fs.writeFileSync(fd, JSON.stringify(row)); fs.fsyncSync(fd); }
|
|
13
|
+
finally { fs.closeSync(fd); }
|
|
14
|
+
fs.renameSync(tmp, file);
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** Unknown/older metadata means MORE review, never a guessed rule. */
|
|
18
|
+
function readAdmission(context, screenId, capturedAtMs) {
|
|
19
|
+
const a = context?.websiteReviewAdmission;
|
|
20
|
+
if (!a || a.version !== 1 || a.kind !== 'wait_boolean_endpoints' || a.screenId !== screenId
|
|
21
|
+
|| typeof a.profileId !== 'string' || !a.profileId || typeof a.profileName !== 'string' || !a.profileName
|
|
22
|
+
|| !Array.isArray(a.rules) || !a.rules.length || a.rules.length > 64
|
|
23
|
+
|| context.profileState !== 'active' || context.temporalReviewContract || context.orderedSequence
|
|
24
|
+
|| context.orderedCaptureContract || context.temporalComparisonContracts?.length
|
|
25
|
+
|| context.absenceWatchedFields?.length) return null;
|
|
26
|
+
const required = context.retainedFieldContract?.required;
|
|
27
|
+
if (!Array.isArray(required) || required.some(f => !f || f.type !== 'boolean')) return null;
|
|
28
|
+
const declared = new Map(required.map(f => [f?.field, f?.type]));
|
|
29
|
+
if (a.rules.some(r => !r || typeof r.routeId !== 'string' || !r.routeId || typeof r.revision !== 'string' || !r.revision
|
|
30
|
+
|| typeof r.field !== 'string' || declared.get(r.field) !== 'boolean'
|
|
31
|
+
|| !Number.isSafeInteger(r.waitMs) || r.waitMs < 1000 || r.waitMs > 600000 || r.waitMs % 1000 !== 0)
|
|
32
|
+
|| new Set(a.rules.map(r => r.routeId)).size !== a.rules.length) return null;
|
|
33
|
+
const lease = a.lease;
|
|
34
|
+
if (!Number.isSafeInteger(capturedAtMs) || !Number.isSafeInteger(lease?.issuedAtMs)
|
|
35
|
+
|| !Number.isSafeInteger(lease.expiresAtMs) || lease.issuedAtMs < 0
|
|
36
|
+
|| lease.expiresAtMs - lease.issuedAtMs !== 30000
|
|
37
|
+
|| capturedAtMs < lease.issuedAtMs - 5000 || capturedAtMs >= lease.expiresAtMs) return null;
|
|
38
|
+
const { revision, lease: _lease, ...identity } = a;
|
|
39
|
+
if (revision !== hash(identity) || a.phoneSearch !== undefined && !phoneSearchPolicy(context, a)) return null;
|
|
40
|
+
return a;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** Renewal is not a rule/model/geometry edit. The two original contexts remain
|
|
44
|
+
* separately hashed by the archive; only this scheduling identity omits lease
|
|
45
|
+
* timestamps, so a five-second renewal cannot restart a ten-second timer.
|
|
46
|
+
*/
|
|
47
|
+
|
|
48
|
+
/** Mirrors only the server's endpoint clock, NOT its alert eligibility/output.
|
|
49
|
+
* Early negatives keep the first positive. Unknown is not a false reading.
|
|
50
|
+
*/
|
|
51
|
+
function advanceAdmission(admission, row, previous) {
|
|
52
|
+
assert(row.result?.structured && row.result.evidenceSha256 === row.imageSha256,
|
|
53
|
+
'Website admission requires this original image\'s durable model result');
|
|
54
|
+
const contextSha256 = admissionContextHash(row.candidate.reviewContext);
|
|
55
|
+
const prior = previous?.contextSha256 === contextSha256 ? previous : null;
|
|
56
|
+
if (prior && row.capturedAt <= prior.capturedAt) return prior;
|
|
57
|
+
const anchors = Object.create(null);
|
|
58
|
+
for (const rule of admission.rules) {
|
|
59
|
+
let anchor = recheckAnchorAt(prior?.anchors[rule.routeId] ?? null, rule.waitMs, row.capturedAt);
|
|
60
|
+
const value = row.result.structured[rule.field];
|
|
61
|
+
const waiting = anchor && row.capturedAt < anchor.capturedAt + rule.waitMs;
|
|
62
|
+
if (value === false && !waiting) anchor = null;
|
|
63
|
+
else if (value === true && !anchor) anchor = { evidenceId: row.id, capturedAt: row.capturedAt,
|
|
64
|
+
imageSha256: row.imageSha256, field: rule.field, confirmed: false };
|
|
65
|
+
else if (value === true && anchor && !waiting) anchor = { ...anchor, confirmed: true };
|
|
66
|
+
anchors[rule.routeId] = anchor;
|
|
67
|
+
}
|
|
68
|
+
return { contextSha256, evidenceId: row.id, capturedAt: row.capturedAt, anchors };
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** The ordinary website still owns all conditions, timing and delivery.
|
|
72
|
+
* 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
|
+
*/
|
|
77
|
+
class WebsiteAdmissionCaptureClient extends RetainedCaptureClient {
|
|
78
|
+
constructor(client, directory, options) {
|
|
79
|
+
super(client, directory, options);
|
|
80
|
+
assert(typeof options.pairedCameraId === 'string' && options.pairedCameraId, 'Paired camera identity required');
|
|
81
|
+
this.pairedCameraId = options.pairedCameraId;
|
|
82
|
+
this.deferred = new Map();
|
|
83
|
+
this.states = new Map();
|
|
84
|
+
this.admissionMetadata = new Map();
|
|
85
|
+
this.phoneReceipts = new Map();
|
|
86
|
+
this.phoneProofChecks = new Map();
|
|
87
|
+
this.admissionNowMs = options.admissionNowMs ?? Date.now;
|
|
88
|
+
assert(typeof this.admissionNowMs === 'function', 'Admission decision clock required');
|
|
89
|
+
for (const row of this.records.values()) {
|
|
90
|
+
if (row.disposition === 'awaiting_rule_decision') this.deferred.set(row.id, row);
|
|
91
|
+
this.metadata(row);
|
|
92
|
+
if (row.result) this.remember(row);
|
|
93
|
+
}
|
|
94
|
+
for (const row of this.records.values()) {
|
|
95
|
+
const decision = this.validPhoneDecision(row);
|
|
96
|
+
if (decision && decision.fromCapturedAtMs < decision.untilCapturedAtMs) this.phoneReceipts.set(row.id, decision);
|
|
97
|
+
}
|
|
98
|
+
// Capture-order archives drain unchanged. In realtime mode the base
|
|
99
|
+
// scheduler retires only unanswered work its queue has not taken.
|
|
100
|
+
}
|
|
101
|
+
admission(context, at) { return readAdmission(context, this.pairedCameraId, at); }
|
|
102
|
+
followUpFor(row, anchors) {
|
|
103
|
+
const due = anchors.filter(({ rule, anchor }) => anchor && !anchor.confirmed
|
|
104
|
+
&& row.capturedAt >= anchor.capturedAt + rule.waitMs)
|
|
105
|
+
.sort((a, b) => a.anchor.capturedAt + a.rule.waitMs - b.anchor.capturedAt - b.rule.waitMs
|
|
106
|
+
|| a.rule.routeId.localeCompare(b.rule.routeId));
|
|
107
|
+
for (const { rule, anchor } of due) {
|
|
108
|
+
const followUp = { version: 1, routeId: rule.routeId, anchorCapturedAtMs: anchor.capturedAt, waitMs: rule.waitMs };
|
|
109
|
+
if (this.followUpOf({ ...row, followUp })) return followUp;
|
|
110
|
+
}
|
|
111
|
+
return null;
|
|
112
|
+
}
|
|
113
|
+
admissionSelection(row) {
|
|
114
|
+
const admission = this.admission(row.candidate.reviewContext, row.capturedAt);
|
|
115
|
+
const remembered = this.states.get(admissionContextHash(row.candidate.reviewContext));
|
|
116
|
+
const state = remembered && remembered.capturedAt < row.capturedAt ? remembered : null;
|
|
117
|
+
const anchors = admission && state ? admission.rules.map(rule => ({ rule,
|
|
118
|
+
anchor: recheckAnchorAt(state.anchors[rule.routeId], rule.waitMs, row.capturedAt) })) : [];
|
|
119
|
+
const expired = anchors.some(({ rule, anchor }) => !anchor && state.anchors[rule.routeId]);
|
|
120
|
+
const waiting = anchors.length > 0 && anchors.every(({ rule, anchor }) =>
|
|
121
|
+
anchor && !anchor.confirmed && row.capturedAt < anchor.capturedAt + rule.waitMs);
|
|
122
|
+
const followUp = this.followUpFor(row, anchors);
|
|
123
|
+
let choice;
|
|
124
|
+
if (waiting) choice = { selected: false, disposition: 'archived_wait_window', selectionReason: 'before_all_website_wait_deadlines' };
|
|
125
|
+
else if (admission && (!state || expired || followUp)) choice = { selected: true, disposition: 'pending_review',
|
|
126
|
+
selectionReason: followUp ? 'website_wait_deadline_check' : 'website_initial_or_context_change' };
|
|
127
|
+
else choice = super.chooseReview(row.candidate, row.imageSha256,
|
|
128
|
+
this.nextDue === null || row.capturedAt >= this.nextDue, row.reviewStage);
|
|
129
|
+
return { choice, anchors, followUp };
|
|
130
|
+
}
|
|
131
|
+
commitAdmissionSelection(row, { choice, anchors, followUp }) {
|
|
132
|
+
const next = { ...row, ...choice, ruleSelection: { version: 1, mode: 'website_wait_endpoints',
|
|
133
|
+
reason: choice.selectionReason, contextSha256: hash(row.candidate.reviewContext),
|
|
134
|
+
anchors: anchors.map(entry => entry.anchor).filter(Boolean) },
|
|
135
|
+
...(followUp ? { followUp, scheduledReviewPriority: 'urgent' } : {}) };
|
|
136
|
+
save(this.file(row.id), next); // disk first; a failed promotion remains deferred
|
|
137
|
+
Object.assign(row, next); this.records.set(row.id, row); this.deferred.delete(row.id);
|
|
138
|
+
if (row.selected) {
|
|
139
|
+
this.entries.set(row.id, row); this.counts.selected++;
|
|
140
|
+
if (!this.previousSelectedRecord || row.capturedAt >= this.previousSelectedRecord.capturedAt) {
|
|
141
|
+
this.previousSelectedRecord = row;
|
|
142
|
+
this.nextDue = this.anchor + (Math.floor((row.capturedAt - this.anchor) / this.intervalMs) + 1) * this.intervalMs;
|
|
143
|
+
}
|
|
144
|
+
this.groupReferences.set(this.referenceKey(row.capturedAt, row.imageSha256, row.candidate.reviewContext), row.id);
|
|
145
|
+
if (this.groupReferences.size > 256) this.groupReferences.delete(this.groupReferences.keys().next().value);
|
|
146
|
+
} else if (row.disposition === 'archived_grouped_unchanged') this.counts.grouped++;
|
|
147
|
+
}
|
|
148
|
+
knownRealtime(row) {
|
|
149
|
+
const context = row.candidate.reviewContext;
|
|
150
|
+
return context && context.profileState === 'active' && context.schema && typeof context.schema === 'object' && !Array.isArray(context.schema)
|
|
151
|
+
&& !context.temporalReviewContract && !context.orderedSequence && !context.orderedCaptureContract;
|
|
152
|
+
}
|
|
153
|
+
captureOrderAdmissionCandidates(onlyAnswered = false) {
|
|
154
|
+
const now = this.realtime.now(), freshnessMs = this.realtime.freshnessMs;
|
|
155
|
+
const stale = row => !row.result && this.knownRealtime(row)
|
|
156
|
+
&& freshnessMs > 0 && now >= row.capturedAt + freshnessMs;
|
|
157
|
+
let retired = 0;
|
|
158
|
+
for (const row of this.entries.values()) {
|
|
159
|
+
if (!stale(row)) continue;
|
|
160
|
+
if (retired < 16) {
|
|
161
|
+
if (this.retireUnreviewed(row, 'expired', now)) retired++;
|
|
162
|
+
} else {
|
|
163
|
+
// Keep archive writes bounded, but no legacy queued copy may start
|
|
164
|
+
// while its archive expiry awaits the next pump. In-flight work and
|
|
165
|
+
// saved queue answers remain protected by the same native queue API.
|
|
166
|
+
const outcome = this.reviewQueue.withdraw(row.id);
|
|
167
|
+
if (outcome === 'withdrawn' || outcome === 'absent') this.queued.delete(row.id);
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
const rows = [...this.entries.values()].filter(row => !stale(row) && (!onlyAnswered || row.result));
|
|
171
|
+
return this.captureOrderCandidates(rows).map(candidate => {
|
|
172
|
+
const row = this.entries.get(candidate.retainedId);
|
|
173
|
+
return !row.result && this.knownRealtime(row) && freshnessMs > 0
|
|
174
|
+
? { ...candidate, reviewDeadlineAtMs: row.capturedAt + freshnessMs } : candidate;
|
|
175
|
+
});
|
|
176
|
+
}
|
|
177
|
+
realtimeAdmissionCandidates() {
|
|
178
|
+
// A completed answer is a receipt dependency, never new inference. Preserve
|
|
179
|
+
// unknown/ordered originals too; only known realtime work can age out here.
|
|
180
|
+
if ([...this.entries.values()].some(row => row.result))
|
|
181
|
+
return this.prioritize(this.captureOrderAdmissionCandidates(true));
|
|
182
|
+
const pending = [...this.entries.values(), ...this.deferred.values()]
|
|
183
|
+
.sort((a, b) => a.capturedAt - b.capturedAt || a.id.localeCompare(b.id));
|
|
184
|
+
if (!pending.length || !this.knownRealtime(pending[0])) return null;
|
|
185
|
+
const prefix = [];
|
|
186
|
+
for (const row of pending) {
|
|
187
|
+
const meta = this.metadata(row);
|
|
188
|
+
// Known profile/model revisions still use upstream newest-frame
|
|
189
|
+
// scheduling. Each row's own captured context determines its wait state;
|
|
190
|
+
// no answer or anchor transfers to another question. Unknown/ordered
|
|
191
|
+
// contexts and explicit phone-search provenance retain their barriers.
|
|
192
|
+
if (!this.knownRealtime(row) || meta.admission && meta.phoneSearch) break;
|
|
193
|
+
prefix.push(row);
|
|
194
|
+
}
|
|
195
|
+
if (!prefix.length || [...this.entries.values()].some(row => !prefix.includes(row))) return null;
|
|
196
|
+
const choices = new Map(prefix.map(row => [row.id, this.admissionSelection(row)]));
|
|
197
|
+
const eligible = prefix.filter(row => row.selected || choices.get(row.id).choice.selected);
|
|
198
|
+
const target = eligible.find(row => this.followUpOf(row) || choices.get(row.id).followUp) ?? eligible.at(-1);
|
|
199
|
+
let writes = 0;
|
|
200
|
+
if (target && this.deferred.has(target.id)) {
|
|
201
|
+
this.commitAdmissionSelection(target, choices.get(target.id)); writes++;
|
|
202
|
+
} else if (target && !this.followUpOf(target) && choices.get(target.id).followUp) {
|
|
203
|
+
// Upgrade an already selected genuine endpoint before the base scheduler
|
|
204
|
+
// can compare it to a newer frame. Its saved anchor stays unchanged.
|
|
205
|
+
const next = { ...target, followUp: choices.get(target.id).followUp, scheduledReviewPriority: 'urgent' };
|
|
206
|
+
save(this.file(target.id), next); Object.assign(target, next); writes++;
|
|
207
|
+
}
|
|
208
|
+
// Scan globally to choose the slot, then drain at most sixteen admission
|
|
209
|
+
// commits. Older selections are retired by the base scheduler (including
|
|
210
|
+
// queued copies), not labelled reviewed or given another image's answer.
|
|
211
|
+
for (const row of prefix) {
|
|
212
|
+
if (writes >= 16) break;
|
|
213
|
+
if (!this.deferred.has(row.id) || target && row.capturedAt > target.capturedAt) continue;
|
|
214
|
+
this.commitAdmissionSelection(row, choices.get(row.id)); writes++;
|
|
215
|
+
}
|
|
216
|
+
let offered = super.pendingOrderedCandidates();
|
|
217
|
+
if (target && this.followUpOf(target)) offered = offered.filter(candidate => candidate.retainedId === target.id);
|
|
218
|
+
// A queued older selection that the base could not retire is in flight.
|
|
219
|
+
// Keep its successor durable but unoffered until the original resolves.
|
|
220
|
+
if (target && [...this.entries.values()].some(row => !row.result && this.queued.has(row.id)
|
|
221
|
+
&& !this.followUpOf(row) && row.capturedAt < target.capturedAt)) offered = [];
|
|
222
|
+
return this.prioritize(offered);
|
|
223
|
+
}
|
|
224
|
+
chooseReview(c, digest, due, stage) {
|
|
225
|
+
// Archive first. The pump applies realtime scheduling to known contexts,
|
|
226
|
+
// while preserving genuinely unknown and ordered observation dependencies.
|
|
227
|
+
if (stage !== null) {
|
|
228
|
+
return { selected: false, disposition: 'awaiting_rule_decision' };
|
|
229
|
+
}
|
|
230
|
+
return super.chooseReview(c, digest, due, stage);
|
|
231
|
+
}
|
|
232
|
+
releaseAdmissionMetadata() {
|
|
233
|
+
for (const id of this.admissionMetadata?.keys() ?? []) if (!this.records.has(id)) this.admissionMetadata.delete(id);
|
|
234
|
+
for (const id of this.phoneReceipts?.keys() ?? []) if (!this.records.has(id)) this.phoneReceipts.delete(id);
|
|
235
|
+
}
|
|
236
|
+
reclaim(at) {
|
|
237
|
+
try { super.reclaim(at); } finally { this.releaseAdmissionMetadata(); }
|
|
238
|
+
}
|
|
239
|
+
retainOrderedCapture(c) {
|
|
240
|
+
const before = this.counts.captures;
|
|
241
|
+
super.retainOrderedCapture(c);
|
|
242
|
+
if (this.counts.captures !== before && this.previousCaptureRecord.disposition === 'awaiting_rule_decision') {
|
|
243
|
+
this.deferred.set(this.previousCaptureRecord.id, this.previousCaptureRecord);
|
|
244
|
+
}
|
|
245
|
+
if (this.counts.captures !== before) this.metadata(this.previousCaptureRecord);
|
|
246
|
+
}
|
|
247
|
+
remember(row) {
|
|
248
|
+
const admission = this.admission(row.candidate.reviewContext, row.capturedAt);
|
|
249
|
+
if (!admission) return;
|
|
250
|
+
const key = admissionContextHash(row.candidate.reviewContext);
|
|
251
|
+
this.states.set(key, advanceAdmission(admission, row, this.states.get(key)));
|
|
252
|
+
}
|
|
253
|
+
archivePins() {
|
|
254
|
+
const pins = super.archivePins();
|
|
255
|
+
const contexts = new Set();
|
|
256
|
+
if (this.previousCaptureRecord) contexts.add(admissionContextHash(this.previousCaptureRecord.candidate.reviewContext));
|
|
257
|
+
for (const row of [...(this.deferred?.values() ?? []), ...this.entries.values()]) {
|
|
258
|
+
pins.add(row.id); contexts.add(admissionContextHash(row.candidate.reviewContext));
|
|
259
|
+
for (const anchor of row.ruleSelection?.anchors ?? []) pins.add(anchor.evidenceId);
|
|
260
|
+
}
|
|
261
|
+
for (const [key, state] of this.states ?? []) {
|
|
262
|
+
if (!contexts.has(key)) { this.states.delete(key); continue; }
|
|
263
|
+
pins.add(state.evidenceId);
|
|
264
|
+
for (const anchor of Object.values(state.anchors)) if (anchor) pins.add(anchor.evidenceId);
|
|
265
|
+
}
|
|
266
|
+
const proofRows = new Set([...this.entries.keys(), ...this.phoneReceipts.keys()]);
|
|
267
|
+
for (const state of this.states.values()) {
|
|
268
|
+
proofRows.add(state.evidenceId);
|
|
269
|
+
for (const anchor of Object.values(state.anchors)) if (anchor) proofRows.add(anchor.evidenceId);
|
|
270
|
+
}
|
|
271
|
+
for (const id of proofRows) {
|
|
272
|
+
const row = this.records.get(id), proofId = row?.phoneAdmissionDecision?.policy?.evidenceId;
|
|
273
|
+
if (proofId && this.records.has(proofId)) pins.add(proofId);
|
|
274
|
+
if (this.phoneReceipts.has(id)) pins.add(id);
|
|
275
|
+
}
|
|
276
|
+
return pins;
|
|
277
|
+
}
|
|
278
|
+
metadata(row) {
|
|
279
|
+
if (!this.admissionMetadata.has(row.id)) {
|
|
280
|
+
const context = row.candidate.reviewContext;
|
|
281
|
+
this.admissionMetadata.set(row.id, { admission: this.admission(context, row.capturedAt),
|
|
282
|
+
contextSha256: admissionContextHash(context), originalContextSha256: hash(context),
|
|
283
|
+
phoneSearch: phoneSearchPolicy(context) });
|
|
284
|
+
}
|
|
285
|
+
return this.admissionMetadata.get(row.id);
|
|
286
|
+
}
|
|
287
|
+
policyImageValid(authority, expectedSha256) {
|
|
288
|
+
if (!authority || authority.imageSha256 !== expectedSha256) return false;
|
|
289
|
+
const key = authority.id + ':' + expectedSha256;
|
|
290
|
+
if (!this.phoneProofChecks.has(key)) {
|
|
291
|
+
let valid = false;
|
|
292
|
+
try { valid = imageHash(fs.readFileSync(this.image(authority))) === expectedSha256; } catch { /* retain pending */ }
|
|
293
|
+
this.phoneProofChecks.set(key, valid);
|
|
294
|
+
}
|
|
295
|
+
return this.phoneProofChecks.get(key);
|
|
296
|
+
}
|
|
297
|
+
policyProof(authority, decisionAtMs) {
|
|
298
|
+
const meta = this.metadata(authority);
|
|
299
|
+
return { evidenceId: authority.id, capturedAt: authority.capturedAt, imageSha256: authority.imageSha256,
|
|
300
|
+
contextSha256: meta.originalContextSha256, revision: meta.admission.revision,
|
|
301
|
+
intervalMs: meta.phoneSearch.intervalMs, decisionAtMs };
|
|
302
|
+
}
|
|
303
|
+
validPhoneDecision(row) {
|
|
304
|
+
const decision = row?.phoneAdmissionDecision;
|
|
305
|
+
if (!decision || decision.version !== 1 || decision.kind !== 'phone_only_admission'
|
|
306
|
+
|| !row.selected || decision.contextSha256 !== this.metadata(row).contextSha256
|
|
307
|
+
|| !['phone_search_current', 'website_wait_deadline_check'].includes(decision.reason)
|
|
308
|
+
|| row.ruleSelection?.reason !== decision.reason || row.ruleSelection?.contextSha256 !== hash(row.candidate.reviewContext)
|
|
309
|
+
|| !Number.isSafeInteger(decision.fromCapturedAtMs) || decision.untilCapturedAtMs !== row.capturedAt
|
|
310
|
+
|| decision.fromCapturedAtMs > decision.untilCapturedAtMs) return null;
|
|
311
|
+
const proof = decision.policy, authority = this.records.get(proof?.evidenceId);
|
|
312
|
+
if (!authority || authority.reviewStage === null || authority.capturedAt !== proof.capturedAt
|
|
313
|
+
|| authority.imageSha256 !== proof.imageSha256 || proof.decisionAtMs < authority.capturedAt
|
|
314
|
+
|| row.capturedAt > authority.capturedAt) return null;
|
|
315
|
+
const meta = this.metadata(authority), lease = meta.admission?.lease;
|
|
316
|
+
if (!meta.admission || !meta.phoneSearch || meta.contextSha256 !== decision.contextSha256
|
|
317
|
+
|| meta.originalContextSha256 !== proof.contextSha256 || meta.admission.revision !== proof.revision
|
|
318
|
+
|| meta.phoneSearch.intervalMs !== proof.intervalMs || !Number.isSafeInteger(proof.decisionAtMs)
|
|
319
|
+
|| proof.decisionAtMs < lease.issuedAtMs - 5000 || proof.decisionAtMs >= lease.expiresAtMs
|
|
320
|
+
|| !this.policyImageValid(authority, proof.imageSha256)) return null;
|
|
321
|
+
return decision;
|
|
322
|
+
}
|
|
323
|
+
coveringDecision(row) {
|
|
324
|
+
const key = this.metadata(row).contextSha256;
|
|
325
|
+
for (const [id, receipt] of this.phoneReceipts) {
|
|
326
|
+
if (coversPhoneDecision(row, receipt, key) && this.validPhoneDecision(this.records.get(id))) return receipt;
|
|
327
|
+
}
|
|
328
|
+
return null;
|
|
329
|
+
}
|
|
330
|
+
commitPhoneOmission(row, proof, reason) {
|
|
331
|
+
const next = { ...row, selected: false, disposition: reason === 'before_all_website_wait_deadlines'
|
|
332
|
+
? 'archived_wait_window' : 'archived_phone_search_unreviewed', selectionReason: reason,
|
|
333
|
+
phoneAdmissionOmission: { version: 1, reason, policy: proof } };
|
|
334
|
+
save(this.file(row.id), next); // no in-memory advancement before fsync + rename
|
|
335
|
+
Object.assign(row, next); this.records.set(row.id, row); this.deferred.delete(row.id);
|
|
336
|
+
}
|
|
337
|
+
settlePhoneOmissions(limit = 32) {
|
|
338
|
+
let committed = 0;
|
|
339
|
+
for (const row of this.deferred.values()) {
|
|
340
|
+
const decision = this.coveringDecision(row);
|
|
341
|
+
if (!decision) continue;
|
|
342
|
+
this.commitPhoneOmission(row, decision.policy, 'phone_search_superseded');
|
|
343
|
+
if (++committed >= limit) break;
|
|
344
|
+
}
|
|
345
|
+
const earliest = new Map();
|
|
346
|
+
for (const row of this.deferred.values()) {
|
|
347
|
+
const key = this.metadata(row).contextSha256;
|
|
348
|
+
earliest.set(key, Math.min(earliest.get(key) ?? Infinity, row.capturedAt));
|
|
349
|
+
}
|
|
350
|
+
for (const [id, decision] of this.phoneReceipts) {
|
|
351
|
+
if ((earliest.get(decision.contextSha256) ?? Infinity) >= decision.untilCapturedAtMs) this.phoneReceipts.delete(id);
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
phonePlan() {
|
|
355
|
+
const authority = this.previousCaptureRecord;
|
|
356
|
+
if (!authority || authority.reviewStage === null) return null;
|
|
357
|
+
const current = this.metadata(authority);
|
|
358
|
+
if (!current.admission || !current.phoneSearch) return null;
|
|
359
|
+
// Only NEW decisions need current authority. A persisted decision retains
|
|
360
|
+
// its original decision time across restart, never a renewed lease.
|
|
361
|
+
let now, liveContext;
|
|
362
|
+
try { now = this.admissionNowMs(); liveContext = this.client.captureReviewContext?.(); } catch { return null; }
|
|
363
|
+
const liveAdmission = this.admission(liveContext, now), livePhone = phoneSearchPolicy(liveContext);
|
|
364
|
+
if (!Number.isSafeInteger(now) || now < authority.capturedAt
|
|
365
|
+
|| !this.admission(authority.candidate.reviewContext, now)
|
|
366
|
+
|| !liveAdmission || !livePhone || admissionContextHash(liveContext) !== current.contextSha256
|
|
367
|
+
|| JSON.stringify(livePhone) !== JSON.stringify(current.phoneSearch)
|
|
368
|
+
|| !this.policyImageValid(authority, authority.imageSha256)) return null;
|
|
369
|
+
const rows = [];
|
|
370
|
+
for (const row of this.deferred.values()) {
|
|
371
|
+
if (this.coveringDecision(row)) continue;
|
|
372
|
+
const meta = this.metadata(row);
|
|
373
|
+
// A different/unknown legacy dependency is a real barrier, never skipped.
|
|
374
|
+
if (!meta.admission || meta.contextSha256 !== current.contextSha256) break;
|
|
375
|
+
if (rows.length && row.capturedAt <= rows[rows.length - 1].capturedAt) break;
|
|
376
|
+
rows.push(row);
|
|
377
|
+
}
|
|
378
|
+
if (!rows.length) return null;
|
|
379
|
+
const state = this.states.get(current.contextSha256);
|
|
380
|
+
// Never use an answer from the future to omit an older unresolved capture.
|
|
381
|
+
if (state && rows[0].capturedAt <= state.capturedAt) return null;
|
|
382
|
+
return { ...choosePhoneReview(rows, current.admission, state, current.phoneSearch.intervalMs),
|
|
383
|
+
authority, decisionAtMs: now, contextSha256: current.contextSha256, fromCapturedAtMs: rows[0].capturedAt };
|
|
384
|
+
}
|
|
385
|
+
applyPhonePlan(plan) {
|
|
386
|
+
const proof = this.policyProof(plan.authority, plan.decisionAtMs);
|
|
387
|
+
if (plan.kind === 'omit') {
|
|
388
|
+
let count = 0;
|
|
389
|
+
for (const row of this.deferred.values()) {
|
|
390
|
+
if (this.coveringDecision(row)) continue;
|
|
391
|
+
const meta = this.metadata(row);
|
|
392
|
+
if (!meta.admission || meta.contextSha256 !== plan.contextSha256) break;
|
|
393
|
+
this.commitPhoneOmission(row, proof, plan.reason);
|
|
394
|
+
if (++count >= 32) break;
|
|
395
|
+
}
|
|
396
|
+
return [];
|
|
397
|
+
}
|
|
398
|
+
const row = plan.row, reason = plan.kind === 'confirmation' ? 'website_wait_deadline_check' : 'phone_search_current';
|
|
399
|
+
const decision = { version: 1, kind: 'phone_only_admission', contextSha256: plan.contextSha256,
|
|
400
|
+
fromCapturedAtMs: plan.fromCapturedAtMs, untilCapturedAtMs: row.capturedAt, policy: proof, reason };
|
|
401
|
+
const next = { ...row, selected: true, disposition: 'pending_review', selectionReason: reason,
|
|
402
|
+
ruleSelection: { version: 1, mode: 'website_wait_endpoints', reason,
|
|
403
|
+
contextSha256: hash(row.candidate.reviewContext), anchors: plan.anchors.map(entry => entry.anchor).filter(Boolean) },
|
|
404
|
+
phoneAdmissionDecision: decision,
|
|
405
|
+
...(plan.kind === 'confirmation' ? { scheduledReviewPriority: 'urgent',
|
|
406
|
+
followUp: this.followUpFor(row, plan.anchors) } : {}) };
|
|
407
|
+
save(this.file(row.id), next); // this one receipt covers the safe prefix before it can advance
|
|
408
|
+
Object.assign(row, next); this.records.set(row.id, row); this.deferred.delete(row.id);
|
|
409
|
+
this.entries.set(row.id, row); this.counts.selected++;
|
|
410
|
+
if (decision.fromCapturedAtMs < decision.untilCapturedAtMs) this.phoneReceipts.set(row.id, decision);
|
|
411
|
+
this.nextDue = this.anchor + (Math.floor((row.capturedAt - this.anchor) / this.intervalMs) + 1) * this.intervalMs;
|
|
412
|
+
if (!this.previousSelectedRecord || row.capturedAt >= this.previousSelectedRecord.capturedAt) this.previousSelectedRecord = row;
|
|
413
|
+
this.groupReferences.set(this.referenceKey(row.capturedAt, row.imageSha256, row.candidate.reviewContext), row.id);
|
|
414
|
+
if (this.groupReferences.size > 256) this.groupReferences.delete(this.groupReferences.keys().next().value);
|
|
415
|
+
return this.prioritize(super.pendingOrderedCandidates());
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
async prepare(request) {
|
|
419
|
+
this.phoneProofChecks.clear(); // do not reuse a pump's JPEG proof after external file changes
|
|
420
|
+
const row = this.records.get(request.evidenceId);
|
|
421
|
+
if (row?.phoneAdmissionDecision) {
|
|
422
|
+
const decision = this.validPhoneDecision(row);
|
|
423
|
+
assert(decision, 'Phone admission policy provenance missing or changed; keep evidence pending');
|
|
424
|
+
}
|
|
425
|
+
for (const anchor of row?.ruleSelection?.anchors ?? []) {
|
|
426
|
+
const first = this.records.get(anchor.evidenceId);
|
|
427
|
+
assert(first && first.id === anchor.evidenceId && first.capturedAt === anchor.capturedAt
|
|
428
|
+
&& first.imageSha256 === anchor.imageSha256
|
|
429
|
+
&& admissionContextHash(first.candidate.reviewContext) === admissionContextHash(row.candidate.reviewContext)
|
|
430
|
+
&& first.result?.structured?.[anchor.field] === true
|
|
431
|
+
&& imageHash(fs.readFileSync(this.image(first))) === anchor.imageSha256,
|
|
432
|
+
'Website wait anchor missing or changed; keep evidence pending');
|
|
433
|
+
}
|
|
434
|
+
const prepared = await super.prepare(request);
|
|
435
|
+
this.remember(this.records.get(request.evidenceId));
|
|
436
|
+
return prepared;
|
|
437
|
+
}
|
|
438
|
+
pendingOrderedCandidates() {
|
|
439
|
+
this.phoneProofChecks.clear();
|
|
440
|
+
this.releaseAdmissionMetadata();
|
|
441
|
+
this.settlePhoneOmissions();
|
|
442
|
+
if (this.realtime) {
|
|
443
|
+
const offered = this.realtimeAdmissionCandidates();
|
|
444
|
+
if (offered !== null) return offered;
|
|
445
|
+
}
|
|
446
|
+
// Capture-order and unknown-policy barriers retain their original FIFO
|
|
447
|
+
// interpretation. No wait/phone authority is invented by realtime mode.
|
|
448
|
+
if (this.entries.size) return this.prioritize(this.realtime
|
|
449
|
+
? this.captureOrderAdmissionCandidates() : super.pendingOrderedCandidates());
|
|
450
|
+
const phonePlan = this.phonePlan();
|
|
451
|
+
if (phonePlan) return this.applyPhonePlan(phonePlan);
|
|
452
|
+
let processed = 0;
|
|
453
|
+
for (const row of this.deferred.values()) {
|
|
454
|
+
if (this.coveringDecision(row)) continue;
|
|
455
|
+
if (++processed > 32) break;
|
|
456
|
+
this.commitAdmissionSelection(row, this.admissionSelection(row));
|
|
457
|
+
if (row.selected) return this.prioritize(this.realtime
|
|
458
|
+
? this.captureOrderAdmissionCandidates() : super.pendingOrderedCandidates());
|
|
459
|
+
}
|
|
460
|
+
return [];
|
|
461
|
+
}
|
|
462
|
+
prioritize(items) {
|
|
463
|
+
return items.map(c => this.entries.get(c.retainedId)?.scheduledReviewPriority
|
|
464
|
+
? { ...c, reviewPriority: this.entries.get(c.retainedId).scheduledReviewPriority } : c);
|
|
465
|
+
}
|
|
466
|
+
stats() {
|
|
467
|
+
const s = super.stats(), pendingAdmission = this.deferred?.size ?? 0;
|
|
468
|
+
const first = this.deferred?.values().next().value?.capturedAt;
|
|
469
|
+
return { ...s, selectedPending: s.pending, pendingAdmission, pending: s.pending + pendingAdmission,
|
|
470
|
+
archivedBetweenReviews: s.archivedBetweenReviews - pendingAdmission,
|
|
471
|
+
retainedWaitWindowCaptures: [...this.records.values()].filter(r => r.disposition === 'archived_wait_window').length,
|
|
472
|
+
retainedPhoneSearchUnreviewed: [...this.records.values()].filter(r => r.disposition === 'archived_phone_search_unreviewed').length,
|
|
473
|
+
oldestPendingCapturedAt: Math.min(s.oldestPendingCapturedAt ?? Infinity, first ?? Infinity) === Infinity ? null
|
|
474
|
+
: Math.min(s.oldestPendingCapturedAt ?? Infinity, first ?? Infinity) };
|
|
475
|
+
}
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
module.exports = { WebsiteAdmissionCaptureClient, readAdmission, advanceAdmission, admissionContextHash };
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
const crypto = require('node:crypto');
|
|
3
|
+
const hash = value => crypto.createHash('sha256').update(JSON.stringify(value)).digest('hex');
|
|
4
|
+
// Mirrors routeReviewTiming; shared native fixtures guard the exact boundary.
|
|
5
|
+
const RECHECK_ANCHOR_GRACE_MS = 60000;
|
|
6
|
+
const recheckAnchorAt = (anchor, waitMs, capturedAt) => anchor
|
|
7
|
+
&& capturedAt - anchor.capturedAt <= waitMs + RECHECK_ANCHOR_GRACE_MS ? anchor : null;
|
|
8
|
+
|
|
9
|
+
function phoneSearchPolicy(context, admission = context?.websiteReviewAdmission) {
|
|
10
|
+
const policy = admission?.phoneSearch;
|
|
11
|
+
if (!policy || Object.keys(policy).sort().join(',') !== 'canonicalField,fields,intervalMs,kind,version'
|
|
12
|
+
|| policy.version !== 1 || policy.kind !== 'phone_only_search'
|
|
13
|
+
|| policy.canonicalField !== 'phone_use' || !Number.isSafeInteger(policy.intervalMs)
|
|
14
|
+
|| policy.intervalMs < 500 || policy.intervalMs > 600000
|
|
15
|
+
|| !Array.isArray(policy.fields) || !policy.fields.length || policy.fields.length > 65
|
|
16
|
+
|| new Set(policy.fields).size !== policy.fields.length
|
|
17
|
+
|| JSON.stringify(policy.fields) !== JSON.stringify([...policy.fields].sort())
|
|
18
|
+
|| policy.fields.some(field => field !== 'phone_use' && !/^alert_focus_[a-p]{16}$/.test(field))) return null;
|
|
19
|
+
const required = context?.retainedFieldContract?.required;
|
|
20
|
+
if (!Array.isArray(required) || !required.length || !Array.isArray(admission.rules)
|
|
21
|
+
|| required.some(field => field?.type !== 'boolean' || !policy.fields.includes(field.field))
|
|
22
|
+
|| policy.fields.some(field => !required.some(entry => entry.field === field))
|
|
23
|
+
|| admission.rules.some(rule => !policy.fields.includes(rule.field))) return null;
|
|
24
|
+
return policy;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** Only scheduling additions and lease renewal are normalized. Everything else
|
|
28
|
+
* in the captured context, including model/schema/geometry, remains in this hash.
|
|
29
|
+
* The original complete context and its archival hash are never overwritten.
|
|
30
|
+
*/
|
|
31
|
+
function admissionContextHash(context) {
|
|
32
|
+
const copy = { ...context }, admission = copy.websiteReviewAdmission;
|
|
33
|
+
if (admission?.version === 1 && admission.kind === 'wait_boolean_endpoints') {
|
|
34
|
+
const { revision, lease: _lease, ...identity } = admission;
|
|
35
|
+
if (revision === hash(identity) && (identity.phoneSearch === undefined || phoneSearchPolicy(context, admission))) {
|
|
36
|
+
const { phoneSearch: _search, ...semantic } = identity;
|
|
37
|
+
copy.websiteReviewAdmission = { ...semantic, revision: hash(semantic) };
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
return hash(copy);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** These are admission choices, never alert decisions or inferred negatives. */
|
|
44
|
+
function choosePhoneReview(rows, admission, state, intervalMs) {
|
|
45
|
+
if (!rows.length) return null;
|
|
46
|
+
const at = capturedAt => admission.rules.map(rule => ({ rule,
|
|
47
|
+
anchor: recheckAnchorAt(state?.anchors[rule.routeId] ?? null, rule.waitMs, capturedAt) }));
|
|
48
|
+
const confirmations = admission.rules.flatMap(rule => {
|
|
49
|
+
const anchor = state?.anchors[rule.routeId];
|
|
50
|
+
if (!anchor || anchor.confirmed) return [];
|
|
51
|
+
const dueAtMs = anchor.capturedAt + rule.waitMs;
|
|
52
|
+
const row = rows.find(candidate => candidate.capturedAt >= dueAtMs
|
|
53
|
+
&& recheckAnchorAt(anchor, rule.waitMs, candidate.capturedAt));
|
|
54
|
+
return row ? [{ row, dueAtMs }] : [];
|
|
55
|
+
}).sort((a, b) => a.row.capturedAt - b.row.capturedAt || a.dueAtMs - b.dueAtMs);
|
|
56
|
+
if (confirmations.length) {
|
|
57
|
+
const { row, dueAtMs } = confirmations[0];
|
|
58
|
+
return { kind: 'confirmation', row, anchors: at(row.capturedAt), dueAtMs };
|
|
59
|
+
}
|
|
60
|
+
const anchors = at(rows[rows.length - 1].capturedAt);
|
|
61
|
+
if (anchors.length && anchors.every(entry => entry.anchor && !entry.anchor.confirmed)) {
|
|
62
|
+
return { kind: 'omit', reason: 'before_all_website_wait_deadlines', anchors };
|
|
63
|
+
}
|
|
64
|
+
if (state && rows[rows.length - 1].capturedAt < state.capturedAt + intervalMs) {
|
|
65
|
+
return { kind: 'omit', reason: 'phone_search_interval', anchors };
|
|
66
|
+
}
|
|
67
|
+
return { kind: 'search', row: rows[rows.length - 1], anchors };
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function coversPhoneDecision(row, decision, contextSha256) {
|
|
71
|
+
return decision.contextSha256 === contextSha256
|
|
72
|
+
&& row.capturedAt >= decision.fromCapturedAtMs && row.capturedAt < decision.untilCapturedAtMs;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
module.exports = { phoneSearchPolicy, admissionContextHash, choosePhoneReview, coversPhoneDecision, recheckAnchorAt };
|
|
@@ -22,7 +22,7 @@ function fixture(extra={}){
|
|
|
22
22
|
const observed=[];
|
|
23
23
|
const client={getEndpoint:()=> 'http://127.0.0.1:18791/v2/earner/audience-analyze',
|
|
24
24
|
async reviewCandidate(req){observed.push(req);req.checkpointAnalysis({version:1,evidenceSha256:hash(req.jpeg)});},
|
|
25
|
-
async analyze(req){return {ok:true,body:{accepted:true,evidenceId:req.evidenceId,evidenceReview:{capturedAtMs:req.capturedAt}}};}};
|
|
25
|
+
async analyze(req){return {ok:true,body:{accepted:true,evidenceId:req.evidenceId,evidenceReview:{version:1,capturedAtMs:req.capturedAt}}};}};
|
|
26
26
|
const options={cameraId:'human_feed_name',intervalMs:500,offerWindow:1,actorPerceiver,
|
|
27
27
|
maxCaptures:100,maxBytes:100000,archiveRetentionMs:500,...extra};
|
|
28
28
|
const archive=new RetainedCaptureClient(client,directory,options);
|
|
@@ -30,7 +30,7 @@ function fixture(){
|
|
|
30
30
|
}};
|
|
31
31
|
const client={getEndpoint:()=> 'http://127.0.0.1:18791/v2/earner/audience-analyze',
|
|
32
32
|
async reviewCandidate(req){requests.push(req);req.checkpointAnalysis({version:1,evidenceSha256:hash(req.jpeg)});},
|
|
33
|
-
async analyze(req){return {ok:true,body:{accepted:true,evidenceId:req.evidenceId,evidenceReview:{capturedAtMs:req.capturedAt}}};}};
|
|
33
|
+
async analyze(req){return {ok:true,body:{accepted:true,evidenceId:req.evidenceId,evidenceReview:{version:1,capturedAtMs:req.capturedAt}}};}};
|
|
34
34
|
const options={cameraId:'human_feed',actorPerceiver,intervalMs:500,maxCaptures:100,maxBytes:50*1024**2,archiveRetentionMs:500};
|
|
35
35
|
const archive=new RetainedCaptureClient(client,directory,options);
|
|
36
36
|
const capture=async(at,c=context)=>{archive.retainOrderedCapture({name:'human_feed',enqueuedAtMs:at,jpeg,reviewContext:c});
|
|
@@ -10,7 +10,7 @@ function fixture(extra = {}) {
|
|
|
10
10
|
const client = {
|
|
11
11
|
getEndpoint: () => endpoint,
|
|
12
12
|
async reviewCandidate(req) { req.checkpointAnalysis({ fixture: true, evidenceSha256: require('node:crypto').createHash('sha256').update(req.jpeg).digest('hex') }); },
|
|
13
|
-
async analyze(req) { return { ok: true, body: { accepted: true, evidenceId: req.evidenceId, evidenceReview: { capturedAtMs: req.capturedAt } } }; },
|
|
13
|
+
async analyze(req) { return { ok: true, body: { accepted: true, evidenceId: req.evidenceId, evidenceReview: { version: 1, capturedAtMs: req.capturedAt } } }; },
|
|
14
14
|
};
|
|
15
15
|
const options = { cameraId: 'camera6', maxCaptures: 8, maxBytes: 100000, archiveRetentionMs: 500, ...extra };
|
|
16
16
|
const archive = new RetainedCaptureClient(client, directory, options);
|
|
@@ -325,7 +325,15 @@ test('normal website startup resolves thirteen paired cameras with two active pr
|
|
|
325
325
|
profiles++;
|
|
326
326
|
const active = feed === cameras[0] || feed === cameras[1];
|
|
327
327
|
const field = { field: 'door_open', type: 'boolean', description: 'Check this camera door.' };
|
|
328
|
+
const websiteReviewAdmission = feed === cameras[0]
|
|
329
|
+
? require('../../../../../trillboard-api/services/retainedWebsiteReviewAdmission').waitEndpointAdmission({
|
|
330
|
+
screenId: cameraId, profileId: 'door-' + cameraId, profileName: 'Door profile', fields: [field],
|
|
331
|
+
defaultConfirmSamples: 1, routes: [{ routeId: 'fixture-door', mode: 'threshold', enabled: true,
|
|
332
|
+
profileName: 'Door profile', screenMongoIds: [cameraId], updatedAt: '2026-10-20T12:00:00Z',
|
|
333
|
+
condition: { field: 'door_open', op: 'eq', value: true }, reviewTimingMode: 'wait_recheck', reviewWaitSeconds: 10 }],
|
|
334
|
+
}) : null;
|
|
328
335
|
res.end(JSON.stringify({ success: true, screenId: cameraId, profileState: active ? 'active' : 'inactive',
|
|
336
|
+
...(websiteReviewAdmission ? { websiteReviewAdmission } : {}),
|
|
329
337
|
profileName: active ? 'Door profile' : null, profileId: active ? 'door-' + cameraId : null,
|
|
330
338
|
profileType: active ? 'custom_intent' : null, fields: active ? [field] : [], absenceWatchedFields: [],
|
|
331
339
|
retainedPilot: { version: 1, reviewFieldSet: 'declared' },
|
|
@@ -363,7 +371,26 @@ test('normal website startup resolves thirteen paired cameras with two active pr
|
|
|
363
371
|
assert.equal(captured.modelSelection.fieldOwners[0].modelId, 'gemma_4_e2b');
|
|
364
372
|
assert.equal(captured.temporalReviewContract, undefined);
|
|
365
373
|
}
|
|
374
|
+
const firstContext = runtime.clients[0].captureReviewContext();
|
|
375
|
+
assert.equal(firstContext.websiteReviewAdmission.rules[0].waitMs, 10000);
|
|
376
|
+
assert.equal(firstContext.websiteReviewAdmission.screenId, cameras[0].screenId);
|
|
377
|
+
firstContext.websiteReviewAdmission.rules[0].waitMs = 1;
|
|
378
|
+
assert.equal(runtime.clients[0].captureReviewContext().websiteReviewAdmission.rules[0].waitMs, 10000);
|
|
379
|
+
assert.equal(runtime.clients[1].captureReviewContext().websiteReviewAdmission, undefined);
|
|
380
|
+
// No camera/model activity: verify the real client's profile TTL changes
|
|
381
|
+
// only while it holds the short-lived server admission hint.
|
|
382
|
+
const nativeClient = runtime.clients[0].client.client;
|
|
383
|
+
const originalNow = Date.now, fetchedAt = nativeClient.lastProfileFetchMs;
|
|
384
|
+
try {
|
|
385
|
+
Date.now = () => fetchedAt + 4999;
|
|
386
|
+
await runtime.clients[0].prepareReview(); assert.equal(profiles, 13);
|
|
387
|
+
Date.now = () => fetchedAt + 5000;
|
|
388
|
+
await runtime.clients[0].prepareReview(); assert.equal(profiles, 14);
|
|
389
|
+
await runtime.clients[1].prepareReview(); assert.equal(profiles, 14);
|
|
390
|
+
} finally { Date.now = originalNow; }
|
|
366
391
|
assert.equal(opens, 0); assert.equal(models, 0);
|
|
392
|
+
const beforeActors = profiles;
|
|
393
|
+
const beforeActorCapabilities = capabilities;
|
|
367
394
|
actorTasks = true;
|
|
368
395
|
const withActors = await createWebsiteManager(input, path.join(directory, 'actors'), deps);
|
|
369
396
|
for (const [index, client] of withActors.clients.entries()) {
|
|
@@ -377,10 +404,11 @@ test('normal website startup resolves thirteen paired cameras with two active pr
|
|
|
377
404
|
}
|
|
378
405
|
assert.notEqual(withActors.clients[0].actorPerceiver.binding.sourceId,
|
|
379
406
|
withActors.clients[1].actorPerceiver.binding.sourceId);
|
|
380
|
-
assert.equal(opens, 0); assert.equal(models, 0); assert.equal(profiles,
|
|
407
|
+
assert.equal(opens, 0); assert.equal(models, 0); assert.equal(profiles, beforeActors + cameras.length); assert.equal(capabilities, beforeActorCapabilities + cameras.length);
|
|
408
|
+
const beforeDenied = profiles;
|
|
381
409
|
denied = true;
|
|
382
410
|
await assert.rejects(createWebsiteManager(input, path.join(directory, 'denied'), deps), /HTTP 403/);
|
|
383
|
-
assert.equal(profiles,
|
|
411
|
+
assert.equal(profiles, beforeDenied); assert.equal(opens, 0); assert.equal(models, 0);
|
|
384
412
|
} finally {
|
|
385
413
|
await new Promise((resolve, reject) => server.close(error => error ? reject(error) : resolve()));
|
|
386
414
|
fs.rmSync(directory, { recursive: true, force: true });
|