@trillboards/edge-sdk 0.2.260 → 0.2.264

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 (65) hide show
  1. package/deploy/windows/ci/test-published-install.ps1 +10 -1
  2. package/dist/AlertClips.d.ts +23 -0
  3. package/dist/AlertClips.d.ts.map +1 -1
  4. package/dist/AlertClips.js +64 -3
  5. package/dist/AlertClips.js.map +1 -1
  6. package/dist/CloudSensingManager.d.ts +36 -0
  7. package/dist/CloudSensingManager.d.ts.map +1 -1
  8. package/dist/CloudSensingManager.js +147 -20
  9. package/dist/CloudSensingManager.js.map +1 -1
  10. package/dist/EdgeAgent.js +1 -1
  11. package/dist/VideoSegmentUploader.d.ts +12 -0
  12. package/dist/VideoSegmentUploader.d.ts.map +1 -1
  13. package/dist/VideoSegmentUploader.js +103 -6
  14. package/dist/VideoSegmentUploader.js.map +1 -1
  15. package/dist/autoSense.d.ts +5 -4
  16. package/dist/autoSense.d.ts.map +1 -1
  17. package/dist/autoSense.js +24 -9
  18. package/dist/autoSense.js.map +1 -1
  19. package/dist/config.d.ts +9 -0
  20. package/dist/config.d.ts.map +1 -1
  21. package/dist/config.js +15 -0
  22. package/dist/config.js.map +1 -1
  23. package/dist/diagnose.d.ts +1 -1
  24. package/dist/diagnose.js +1 -1
  25. package/dist/sensingRunMode.d.ts +8 -0
  26. package/dist/sensingRunMode.d.ts.map +1 -1
  27. package/dist/sensingRunMode.js +59 -11
  28. package/dist/sensingRunMode.js.map +1 -1
  29. package/package.json +6 -5
  30. package/retained/CapturedTheftProfile.cjs +83 -0
  31. package/retained/ExperimentalTheftConnector.cjs +392 -0
  32. package/retained/FrameTheftRuntime.cjs +111 -0
  33. package/retained/FrameTheftWorker.py +136 -0
  34. package/retained/InstalledTheftLifecycle.cjs +165 -0
  35. package/retained/InstalledTheftPackage.cjs +91 -0
  36. package/retained/LiveTheftBinding.cjs +55 -0
  37. package/retained/ObservedReviewCaseEvidence.py +188 -0
  38. package/retained/ObservedSameWristPolicy.py +205 -0
  39. package/retained/OrderedPerceptionDelivery.cjs +72 -0
  40. package/retained/PairedTheftRoute.cjs +402 -0
  41. package/retained/ReplayRpc.cjs +157 -0
  42. package/retained/RetainedCaptureClient.cjs +63 -16
  43. package/retained/SavedTheftSession.cjs +110 -0
  44. package/retained/TheftCaseContract.cjs +36 -0
  45. package/retained/TheftCaseDelivery.cjs +81 -0
  46. package/retained/TheftDeliveryPump.cjs +41 -0
  47. package/retained/TheftMovementOwner.py +234 -0
  48. package/retained/TheftReviewPolicy.cjs +8 -0
  49. package/retained/__tests__/paired-theft-manager.test.cjs +509 -0
  50. package/retained/__tests__/support/live-shelf-api.cjs +139 -0
  51. package/retained/__tests__/support/load-sdk-sources.cjs +41 -0
  52. package/retained/__tests__/support/loopback-proxy.cjs +33 -0
  53. package/retained/__tests__/support/pinned-api-loader.cjs +11 -0
  54. package/retained/__tests__/support/theft-builder.cjs +61 -0
  55. package/retained/__tests__/support/theft-packet-fixture.cjs +58 -0
  56. package/retained/__tests__/support/theft-readiness.cjs +51 -0
  57. package/retained/__tests__/test_live_theft_input.py +103 -0
  58. package/retained/__tests__/theft-case-api.test.cjs +135 -0
  59. package/retained/__tests__/theft-ci-regression.test.cjs +92 -0
  60. package/retained/__tests__/theft-config.test.cjs +84 -0
  61. package/retained/__tests__/theft-entry.test.cjs +76 -0
  62. package/retained/__tests__/theft-native-recovery.test.cjs +90 -0
  63. package/retained/__tests__/theft-readiness.test.cjs +164 -0
  64. package/retained/manager.cjs +61 -7
  65. package/retained/pilot-profile-client.cjs +4 -0
@@ -0,0 +1,136 @@
1
+ """Private frame-only native launcher. No dataset reader or model downloader.
2
+
3
+ The package/config verifier remains responsible for the complete dependency
4
+ closure. This entry additionally pins the three direct runtime sources and
5
+ preserves the existing RF/pose settings. Native startup is not locally proven.
6
+ """
7
+ import argparse
8
+ import contextlib
9
+ import hashlib
10
+ import importlib.util
11
+ import json
12
+ from pathlib import Path
13
+ import re
14
+ import sys
15
+
16
+ from TheftMovementOwner import (movement_owner_type, serve_frames, timing_contract, validate_native_timing,
17
+ OBSERVED_TIMING, LIVE_KIND, LiveMovementAdapter, prepare_live_cameras)
18
+
19
+ RF = '8e8197112112b79d7cc5d0a94ecef659c05317a658aadc7c7643374c539d7615'
20
+ POSE = '9aeb635b83f86aea45cf45d85798f7eba1a162de8e0d721c44e54fe5eebaf47d'
21
+ MODULES = {'native': 'arm_area_native_perception', 'case': 'review_case_evidence', 'wrist': 'same_wrist_policy'}
22
+
23
+
24
+ def read_configuration(filename, expected_hash):
25
+ raw = Path(filename).read_bytes()
26
+ if len(raw) > 1024 * 1024 or not re.fullmatch('[a-f0-9]{64}', expected_hash):
27
+ raise ValueError('Bounded hash-pinned frame-worker configuration required')
28
+ if hashlib.sha256(raw).hexdigest() != expected_hash:
29
+ raise ValueError('Frame-worker configuration hash changed')
30
+ config = json.loads(raw)
31
+ fields = {'version', 'nativeConfig', 'sources'}
32
+ if config.get('version') in (2, 3):
33
+ fields.add('captureTimingPolicy')
34
+ if config.get('captureTimingPolicy') != OBSERVED_TIMING:
35
+ raise ValueError('Explicit unchanged observed timing policy required')
36
+ if set(config) != fields or type(config.get('version')) is not int or config['version'] not in (1, 2, 3):
37
+ raise ValueError('Explicit frame-worker configuration required')
38
+ native = config['nativeConfig']
39
+ keys = {'labRoot', 'journalPath', 'frameRate', 'maxCameras', 'rfdetrThreads', 'poseThreads', 'cameraEnvironments'}
40
+ if not isinstance(native, dict) or set(native) != keys:
41
+ raise ValueError('Complete unchanged native settings required')
42
+ if any(type(native[k]) is not int or native[k] != v
43
+ for k, v in {'frameRate': 2, 'rfdetrThreads': 4, 'poseThreads': 2}.items()):
44
+ raise ValueError('Existing RF/pose/cadence settings changed')
45
+ if not isinstance(native['cameraEnvironments'], dict) or not native['cameraEnvironments']:
46
+ raise ValueError('Explicit original camera environment required')
47
+ if type(native['maxCameras']) is not int or native['maxCameras'] != len(native['cameraEnvironments']):
48
+ raise ValueError('Camera capacity must match configured environments')
49
+ if config['version'] == 3:
50
+ prepare_live_cameras(native)
51
+ elif any(isinstance(row, dict) and row.get('kind') == LIVE_KIND for row in native['cameraEnvironments'].values()):
52
+ raise ValueError('Live camera input requires a version 3 frame configuration')
53
+ if any(not isinstance(native[k], str) or not Path(native[k]).is_absolute() for k in ('labRoot', 'journalPath')):
54
+ raise ValueError('Explicit absolute lab and owned journal paths required')
55
+ if not isinstance(config['sources'], dict) or set(config['sources']) != set(MODULES):
56
+ raise ValueError('All three runtime source pins required')
57
+ return config
58
+
59
+
60
+ @contextlib.contextmanager
61
+ def runtime_types(sources):
62
+ """Verify every direct source before executing any; restore import state."""
63
+ verified = {}
64
+ for kind in MODULES:
65
+ pin = sources[kind]
66
+ if not isinstance(pin, dict) or set(pin) != {'path', 'sha256'}:
67
+ raise ValueError('Exact runtime path/hash pair required')
68
+ file = Path(pin['path'])
69
+ if not file.is_absolute() or file.is_symlink() or not re.fullmatch('[a-f0-9]{64}', pin['sha256']):
70
+ raise ValueError('Explicit regular pinned runtime source required')
71
+ raw = file.read_bytes()
72
+ if len(raw) > 1024 * 1024 or hashlib.sha256(raw).hexdigest() != pin['sha256']:
73
+ raise ValueError('Runtime source changed: ' + kind)
74
+ verified[kind] = (file, raw)
75
+ old_path = sys.path[:]
76
+ old_modules = {name: sys.modules.get(name) for name in MODULES.values()}
77
+ try:
78
+ sys.path[:0] = list(dict.fromkeys(str(file.parent) for file, _ in verified.values()))
79
+ loaded = {}
80
+ for kind, name in MODULES.items():
81
+ file, raw = verified[kind]
82
+ spec = importlib.util.spec_from_file_location(name, file)
83
+ module = importlib.util.module_from_spec(spec)
84
+ sys.modules[name] = module
85
+ # Execute the exact bytes that were hashed, not a later file read.
86
+ exec(compile(raw, str(file), 'exec'), module.__dict__)
87
+ loaded[kind] = module
88
+ native = loaded['native']
89
+ if native.RF_SHA256 != RF or native.POSE_SHA256 != POSE:
90
+ raise ValueError('Native model pins differ from the frozen pipeline')
91
+ yield native.NativePerception, loaded['case'].ReviewCaseEvidence, loaded['wrist'].SameWristLab
92
+ finally:
93
+ sys.path[:] = old_path
94
+ for name, old in old_modules.items():
95
+ if old is None:
96
+ sys.modules.pop(name, None)
97
+ else:
98
+ sys.modules[name] = old
99
+
100
+
101
+ def run(config, input_stream, output_stream, error_stream):
102
+ # Hold the verified import context for the full owned lifetime. Model-source
103
+ # imports/inference may refer to these modules after construction.
104
+ native_config = config['nativeConfig']
105
+ bindings = None
106
+ if config['version'] == 3:
107
+ native_config, bindings = prepare_live_cameras(native_config)
108
+ with contextlib.redirect_stdout(error_stream), runtime_types(config['sources']) as types:
109
+ if timing_contract(types[1], types[2]) != config.get('captureTimingPolicy'):
110
+ raise ValueError('Configured source timing contract mismatch before model startup')
111
+ def create_owner():
112
+ import cv2
113
+ import psutil
114
+ if psutil.virtual_memory().available < 4_500_000_000:
115
+ raise RuntimeError('Native RF/pose admission needs 4.5 GB free')
116
+ cv2.setNumThreads(2)
117
+ owner = movement_owner_type(*types)(native_config)
118
+ return LiveMovementAdapter(owner, bindings) if bindings else owner
119
+ def validate_owner(owner):
120
+ if owner.test_only or owner.native_owners['modelHashes'] != {'rfdetr_medium': RF, 'old_lab_pose': POSE}:
121
+ raise RuntimeError('Actual frozen native RF/pose owners were not established')
122
+ validate_native_timing(owner, config.get('captureTimingPolicy'))
123
+ return serve_frames(create_owner, input_stream, output_stream, error_stream, validate_owner=validate_owner)
124
+
125
+
126
+ def main():
127
+ parser = argparse.ArgumentParser()
128
+ parser.add_argument('--config', required=True)
129
+ parser.add_argument('--config-sha256', required=True)
130
+ args = parser.parse_args()
131
+ config = read_configuration(args.config, args.config_sha256)
132
+ run(config, sys.stdin, sys.stdout, sys.stderr)
133
+
134
+
135
+ if __name__ == '__main__':
136
+ main()
@@ -0,0 +1,165 @@
1
+ 'use strict';
2
+ const assert=require('node:assert/strict');
3
+ const {isDeepStrictEqual}=require('node:util');
4
+ const {nativeErrorDetails}=require('./ReplayRpc.cjs');
5
+
6
+ const ATTACHED=Symbol.for('trillboards.experimentalTheft.installedLifecycle.v1');
7
+ const CONTRACT=Object.freeze({reviewMode:'human_only',reviewPictures:13,queueInclusiveReviewLimitMs:90000,sharedGemma:null});
8
+ const failure=(code,message,cause)=>Object.assign(new Error(message,cause===undefined?undefined:{cause}),{code});
9
+ const cancelled=()=>failure('THEFT_LIFECYCLE_CANCELLED','Theft work belongs to a stopped manager generation');
10
+
11
+ /** Native ownership only. Does not construct cameras, declare Gemma ready,
12
+ * choose profiles, change evidence or load a native module on import.
13
+ * The package binding must supply a verified fresh frame owner per generation
14
+ * and a durable diagnostic sink BEFORE attaching this to the normal manager. */
15
+ class InstalledTheftLifecycle {
16
+ constructor({makeFrame,describeOriginal,availableBytes,onDiagnostic,
17
+ setTimer=setTimeout,clearTimer=clearTimeout,cleanupMs=25000}) {
18
+ assert([makeFrame,describeOriginal,availableBytes,onDiagnostic,setTimer,clearTimer].every(f=>typeof f==='function'),
19
+ 'Explicit native factory, metadata, memory, diagnostic and timer boundaries required');
20
+ assert(Number.isSafeInteger(cleanupMs)&&cleanupMs>0&&cleanupMs<=25000,'Bounded cleanup required');
21
+ this.hooks={makeFrame,describeOriginal,availableBytes,onDiagnostic,setTimer,clearTimer,cleanupMs};
22
+ this.contract=CONTRACT;this.manager=null;this.current=null;this.sequence=0;
23
+ this.stopInFlight=null;this.poisoned=null;this.diagnostics=[];this.cleanup=[];
24
+ this.runtime={rpc:{call:(method,body)=>this.call(method,body)},
25
+ describeOriginal:value=>describeOriginal(value),reviewer:null};
26
+ }
27
+ attach(manager) {
28
+ assert(!this.manager&&manager&&typeof manager.start==='function'&&typeof manager.stop==='function',
29
+ 'One complete manager must be attached once');
30
+ assert(!manager[ATTACHED],'Manager already has an installed theft lifecycle');
31
+ assert(manager.startNativeTheftOnly===undefined,'Do not overwrite an existing native-start owner');
32
+ this.manager=manager;this.originalStart=manager.start.bind(manager);this.originalStop=manager.stop.bind(manager);
33
+ Object.defineProperty(manager,ATTACHED,{value:this,enumerable:false});
34
+ manager.start=(...args)=>this.start(...args);manager.stop=(...args)=>this.stop(...args);
35
+ Object.defineProperty(manager,'startNativeTheftOnly',{
36
+ value:()=>manager.start({nativeTheftOnly:true}),enumerable:false,
37
+ });
38
+ return manager;
39
+ }
40
+ record(component,error,generation) {
41
+ const row={component,generation:generation?.id??null,error:nativeErrorDetails(error)};
42
+ this.diagnostics.push(row);
43
+ try {this.hooks.onDiagnostic(row);return error;}
44
+ catch(sinkError) {
45
+ this.diagnostics.push({component:'diagnostic_write',generation:row.generation,error:nativeErrorDetails(sinkError)});
46
+ return new AggregateError([error,sinkError],'Original failure and diagnostic-write failure',{cause:error});
47
+ }
48
+ }
49
+ start(...args) {
50
+ assert(this.manager,'Attach the normal manager before startup');
51
+ if(this.poisoned)return Promise.reject(this.poisoned);
52
+ if(this.stopInFlight)return Promise.reject(failure('THEFT_LIFECYCLE_STOPPING','Await cleanup before another start'));
53
+ if(this.current) {
54
+ if(this.current.failure)return Promise.reject(this.current.failure);
55
+ if(!isDeepStrictEqual(args,this.current.args))return Promise.reject(
56
+ failure('THEFT_START_OPTIONS_CHANGED','Stop before changing startup options'));
57
+ return this.current.startPromise;
58
+ }
59
+ const generation={id:++this.sequence,args,healthOnly:args[0]?.healthOnly===true,
60
+ state:'starting',stopRequested:false,owner:null,nativeStart:null,nativeReady:false,
61
+ managerStart:null,startPromise:null,stopPromise:null,failure:null};
62
+ this.current=generation;
63
+ generation.managerStart=Promise.resolve().then(()=>{
64
+ if(generation.stopRequested)throw cancelled();
65
+ return this.originalStart(...args);
66
+ });
67
+ generation.startPromise=generation.managerStart.then(value=>{
68
+ if(generation.stopRequested)throw cancelled();
69
+ generation.state='running';return value;
70
+ }).catch(async error=>{
71
+ const primary=error.code==='THEFT_LIFECYCLE_CANCELLED'?error:this.record('camera_start',error,generation);
72
+ generation.failure??=primary;
73
+ try {await this.stopGeneration(generation);}
74
+ catch(cleanupError){throw new AggregateError([primary,cleanupError],'Startup and cleanup failed',{cause:primary});}
75
+ throw primary;
76
+ });
77
+ return generation.startPromise;
78
+ }
79
+ requireRun(generation=this.current) {
80
+ if(!generation||generation!==this.current||generation.stopRequested)throw cancelled();
81
+ if(generation.healthOnly)throw failure('THEFT_HEALTH_ONLY','Health-only mode must not start inference');
82
+ if(generation.failure)throw generation.failure;
83
+ return generation;
84
+ }
85
+ frameFor(generation) {
86
+ this.requireRun(generation);
87
+ if(!generation.nativeStart)generation.nativeStart=Promise.resolve().then(async()=>{
88
+ this.requireRun(generation);
89
+ const owner=this.hooks.makeFrame({generation:generation.id,reviewer:null});
90
+ generation.owner=owner;
91
+ assert(owner&&typeof owner.start==='function'&&typeof owner.close==='function'&&
92
+ owner.rpc&&typeof owner.rpc.call==='function'&&owner.reviewer===null,
93
+ 'One frame-only native owner with Gemma explicitly disabled required');
94
+ await owner.start({availableBytes:this.hooks.availableBytes()});
95
+ this.requireRun(generation);generation.nativeReady=true;return owner;
96
+ }).catch(error=>{
97
+ if(error.code!=='THEFT_LIFECYCLE_CANCELLED')generation.failure??=this.record('perception_start',error,generation);
98
+ throw generation.failure??error;
99
+ });
100
+ return generation.nativeStart;
101
+ }
102
+ async call(method,body) {
103
+ assert(['detect','/movement13'].includes(method),'Only frame detection and movement operations are allowed');
104
+ const generation=this.requireRun(),owner=await this.frameFor(generation);
105
+ this.requireRun(generation);
106
+ try {return await owner.rpc.call(method,body);}
107
+ catch(error) {generation.failure??=this.record('perception_call',error,generation);throw generation.failure;}
108
+ }
109
+ bounded(promise,component,generation) {
110
+ return new Promise((resolve,reject)=>{
111
+ const timer=this.hooks.setTimer(()=>reject(failure('THEFT_STOP_UNCONFIRMED',
112
+ component+' did not finish within '+this.hooks.cleanupMs+'ms',generation.earlyCloseError)),this.hooks.cleanupMs);
113
+ Promise.resolve(promise).then(value=>{this.hooks.clearTimer(timer);resolve(value);},
114
+ error=>{this.hooks.clearTimer(timer);reject(error);});
115
+ });
116
+ }
117
+ async closeOwner(generation) {
118
+ // Closing an existing transport interrupts its pending readiness wait.
119
+ // A factory not yet entered sees stopRequested and cannot construct later.
120
+ let firstClose=null;
121
+ if(generation.owner)firstClose=Promise.resolve().then(()=>generation.owner.close()).catch(error=>{
122
+ generation.earlyCloseError=error;throw error;
123
+ });
124
+ await Promise.allSettled([generation.nativeStart,firstClose].filter(Boolean));
125
+ if(!generation.owner)return {exited:true,started:false};
126
+ const result=await generation.owner.close();
127
+ assert(result?.exited===true,'Native process exit must be confirmed; do not infer cleanup');
128
+ generation.nativeReady=false;return result;
129
+ }
130
+ stopGeneration(generation,args=[]) {
131
+ if(generation.stopPromise)return generation.stopPromise;
132
+ generation.stopRequested=true;generation.state='stopping';
133
+ const stopping=Promise.resolve().then(async()=>{
134
+ const operations=[{component:'camera_stop',promise:Promise.resolve().then(async()=>{
135
+ const result=await this.originalStop(...args);
136
+ await generation.managerStart.catch(()=>{});return result;
137
+ })},{component:'perception_stop',promise:this.closeOwner(generation)}];
138
+ const results=await Promise.allSettled(operations.map(operation=>
139
+ this.bounded(operation.promise,operation.component,generation)));
140
+ const errors=[];
141
+ results.forEach((result,index)=>{
142
+ if(result.status==='rejected')errors.push(this.record(operations[index].component,result.reason,generation));
143
+ });
144
+ this.cleanup.push({generation:generation.id,results:results.map((result,index)=>({
145
+ component:operations[index].component,status:result.status,
146
+ ...(result.status==='fulfilled'?{result:result.value}:{error:nativeErrorDetails(result.reason)})}))});
147
+ if(errors.length) {
148
+ generation.state='failed';this.poisoned=new AggregateError(errors,'Installed theft lifecycle cleanup failed');
149
+ throw this.poisoned;
150
+ }
151
+ generation.state='stopped';if(this.current===generation)this.current=null;
152
+ return results[0].value;
153
+ });
154
+ generation.stopPromise=stopping;this.stopInFlight=stopping;
155
+ stopping.then(()=>{if(this.stopInFlight===stopping)this.stopInFlight=null;},
156
+ ()=>{if(this.stopInFlight===stopping)this.stopInFlight=null;});
157
+ return stopping;
158
+ }
159
+ stop(...args) {
160
+ assert(this.manager,'Attach the normal manager before cleanup');
161
+ if(this.current)return this.stopGeneration(this.current,args);
162
+ return this.originalStop(...args);
163
+ }
164
+ }
165
+ module.exports={InstalledTheftLifecycle};
@@ -0,0 +1,91 @@
1
+ 'use strict';
2
+ const assert=require('node:assert/strict'),fs=require('node:fs'),path=require('node:path'),crypto=require('node:crypto'),os=require('node:os');
3
+ const {InstalledTheftLifecycle}=require('./InstalledTheftLifecycle.cjs');
4
+ const {FrameTheftRuntime}=require('./FrameTheftRuntime.cjs');
5
+ const {nativeErrorDetails}=require('./ReplayRpc.cjs');
6
+ const {KIND,validateEnvironment}=require('./LiveTheftBinding.cjs');
7
+ const hash=bytes=>crypto.createHash('sha256').update(bytes).digest('hex');
8
+ const keys=value=>value&&typeof value==='object'&&!Array.isArray(value)?Object.keys(value).sort().join(','):'';
9
+
10
+ function pinnedJson(file,expected) {
11
+ assert(typeof file==='string'&&path.isAbsolute(file)&&/^[a-f0-9]{64}$/.test(expected),'Absolute pinned private-package path and SHA-256 required');
12
+ assert.equal(fs.realpathSync(file),file,'Nonlinked canonical private-package file required');
13
+ assert(!fs.lstatSync(file).isSymbolicLink(),'Linked private-package file refused');
14
+ const fd=fs.openSync(file,'r');
15
+ try {
16
+ const before=fs.fstatSync(fd,{bigint:true});assert(before.isFile()&&before.size<=1048576n,'Bounded regular private-package JSON required');
17
+ const bytes=fs.readFileSync(fd),after=fs.fstatSync(fd,{bigint:true});
18
+ for(const key of ['dev','ino','size','mtimeNs'])assert.equal(before[key],after[key],'Private package changed during read');
19
+ assert.equal(hash(bytes),expected,'Private package hash differs');return JSON.parse(bytes);
20
+ } finally {fs.closeSync(fd);}
21
+ }
22
+
23
+ /** Direct source/configuration admission only; not a native dependency or
24
+ * portable-installer certificate. No subprocess/model/camera starts on load.
25
+ * The normal manager and existing native-readiness machinery retain profile
26
+ * authority. Full interpreter/DLL closure and relocation remain separate gates. */
27
+ function loadInstalledTheftPackage({file,sha256,stateDirectory}) {
28
+ assert(typeof stateDirectory==='string'&&path.isAbsolute(stateDirectory),'Absolute owned theft-state directory required');
29
+ fs.mkdirSync(stateDirectory,{recursive:true,mode:0o700});
30
+ assert.equal(fs.realpathSync(stateDirectory),stateDirectory,'Nonlinked canonical theft-state directory required');
31
+ const directory=fs.mkdtempSync(path.join(stateDirectory,'manager-'));
32
+ const journal=path.join(directory,'STARTUP-DIAGNOSTICS.jsonl');
33
+ function record(row) {
34
+ const fd=fs.openSync(journal,'a',0o600);
35
+ try {fs.writeSync(fd,JSON.stringify({atMs:Date.now(),...row})+'\n');fs.fsyncSync(fd);}
36
+ finally {fs.closeSync(fd);}
37
+ }
38
+ try {
39
+ const descriptor=pinnedJson(file,sha256);
40
+ assert(keys(descriptor)==='frameRuntime,registration,schema,sharedGemma'&&descriptor.schema==='installed_human_only_theft/v1',
41
+ 'Exact installed human-only theft package required');
42
+ assert.equal(descriptor.sharedGemma,null,'Installed theft must keep Gemma off');
43
+ const registration=descriptor.registration;
44
+ assert(keys(registration)==='profiles,version'&&registration.version===1&&Array.isArray(registration.profiles)&&registration.profiles.length>0
45
+ &&registration.profiles.every(row=>row&&row.reviewMode==='human_only'),'Explicit nonempty human_only package registrations required');
46
+ const frame=descriptor.frameRuntime;
47
+ assert(keys(frame)==='command,configFile,configSha256,pinnedFiles,workerFile','Exact pinned frame-runtime template required');
48
+ assert([frame.command,frame.workerFile,frame.configFile].every(file=>typeof file==='string'&&path.isAbsolute(file)),
49
+ 'Absolute pinned interpreter, worker and configuration required');
50
+ assert(Array.isArray(frame.pinnedFiles)&&frame.pinnedFiles.some(pin=>pin?.path===frame.command),'Interpreter must be included in the verified file pins');
51
+ const verify=()=>{
52
+ assert.deepEqual(pinnedJson(file,sha256),descriptor,'Private-package descriptor changed after admission');
53
+ const checker=Object.create(FrameTheftRuntime.prototype);
54
+ checker.spec={...frame,directory:path.join(directory,'not-created-during-validation')};checker.verifyFiles();
55
+ for(const pin of frame.pinnedFiles)assert.equal(fs.realpathSync(pin.path),pin.path,'Nonlinked canonical runtime input required');
56
+ const live = registration.profiles.filter(row => row.environment?.kind === KIND);
57
+ assert.equal(checker.configuration.version,live.length ? 3 : 2,'Installed capture requires the matching observed-clock configuration');
58
+ assert.equal(checker.configuration.nativeConfig.maxCameras,registration.profiles.length,'Frame camera capacity differs from registrations');
59
+ const environments = checker.configuration.nativeConfig.cameraEnvironments;
60
+ const nativeLive = Object.values(environments).filter(environment => environment?.kind === KIND);
61
+ assert.equal(nativeLive.length,live.length,'Live native cameras differ from descriptor registrations');
62
+ assert.equal(new Set(live.map(row => row.environment.cameraId)).size,live.length,'Duplicate live camera registration');
63
+ for (const row of live) {
64
+ validateEnvironment(row.environment);
65
+ assert.deepEqual(environments[row.environment.cameraId], row.environment, 'Live worker and connector shelf bindings differ');
66
+ }
67
+ return checker.configuration;
68
+ };
69
+ verify();
70
+ const lifecycle=new InstalledTheftLifecycle({
71
+ makeFrame:({generation,reviewer})=>{
72
+ assert.equal(reviewer,null,'Installed theft has no Gemma owner');verify();
73
+ return new FrameTheftRuntime({...structuredClone(frame),directory:path.join(directory,'perception-'+generation),reviewer:null});
74
+ },
75
+ describeOriginal:FrameTheftRuntime.prototype.describeOriginal,
76
+ availableBytes:()=>os.freemem(),onDiagnostic:row=>record(row),
77
+ });
78
+ Object.defineProperty(lifecycle.runtime,'installedLifecycle',{value:lifecycle,enumerable:false});
79
+ lifecycle.runtime.enableCaseDelivery=true;
80
+ Object.defineProperty(lifecycle,'packageBinding',{value:Object.freeze({descriptorFile:file,descriptorSha256:sha256,directory,journal,
81
+ directSourceConfigurationVerified:true,nativeStartupQualified:false,portableDependencyClosureQualified:false}),enumerable:false});
82
+ record({component:'package_configuration',status:'direct_pins_verified_native_and_installer_unverified',
83
+ descriptorSha256:sha256,reviewMode:'human_only',gemma:false,reviewPictures:13,queueInclusiveReviewLimitMs:90000});
84
+ return {registration:structuredClone(registration),runtime:lifecycle.runtime};
85
+ } catch(error) {
86
+ try {record({component:'package_configuration',error:nativeErrorDetails(error)});}
87
+ catch(diagnosticError){throw new AggregateError([error,diagnosticError],'Package validation and diagnostic write failed',{cause:error});}
88
+ throw error;
89
+ }
90
+ }
91
+ module.exports={loadInstalledTheftPackage};
@@ -0,0 +1,55 @@
1
+ 'use strict';
2
+
3
+ const assert = require('node:assert/strict');
4
+ const { createHash } = require('node:crypto');
5
+ const KIND = 'live_shelf_review_v1';
6
+ const TEMPLATE = 'cctv_shelf_movement_review_v1';
7
+ const digest = value => typeof value === 'string' && /^[a-f0-9]{64}$/.test(value);
8
+ const id = value => typeof value === 'string' && /^[a-zA-Z0-9][a-zA-Z0-9_.-]{0,127}$/.test(value);
9
+ const hash = value => createHash('sha256').update(JSON.stringify(value)).digest('hex');
10
+
11
+ function validateEnvironment(environment) {
12
+ assert(environment && Object.keys(environment).sort().join(',') ===
13
+ 'cameraId,frameSize,kind,regionConfigurationSha256,shelf,sourceId', 'Exact live camera and shelf environment required');
14
+ const { kind, cameraId, sourceId, frameSize, shelf, regionConfigurationSha256 } = environment;
15
+ assert(kind === KIND && id(cameraId) && digest(sourceId) && digest(regionConfigurationSha256),
16
+ 'Verified live camera/source identities required');
17
+ assert(Array.isArray(frameSize) && frameSize.length === 2
18
+ && frameSize.every(n => Number.isInteger(n) && n > 0 && n <= 8192), 'Bounded live frame dimensions required');
19
+ assert(Array.isArray(shelf) && shelf.length >= 3 && shelf.length <= 64
20
+ && shelf.every(point => Array.isArray(point) && point.length === 2
21
+ && point.every(n => Number.isInteger(n) && n >= 0 && n <= 1000000)), 'Marked live shelf polygon required');
22
+ const area = shelf.reduce((sum, [x, y], i) => {
23
+ const [nextX, nextY] = shelf[(i + 1) % shelf.length];
24
+ return sum + x * nextY - y * nextX;
25
+ }, 0);
26
+ assert(area && new Set(shelf.map(point => point.join(','))).size === shelf.length, 'Degenerate live shelf polygon refused');
27
+ assert.equal(hash([kind, cameraId, sourceId, frameSize, shelf]), regionConfigurationSha256, 'Live shelf fingerprint differs');
28
+ return environment;
29
+ }
30
+
31
+ // Match the authority issued by the paired server, at capture time. Saved
32
+ // originals still use their own lease, even after the operator switches away.
33
+ function readLiveAdmission(context, binding, at) {
34
+ const a = context?.websiteReviewAdmission;
35
+ if (context?.profileState !== 'active' || a?.kind !== KIND || a.version !== 1
36
+ || Object.keys(a).sort().join(',') !== 'kind,lease,profileId,regionConfigurationSha256,revision,routeId,screenId,selectionId,sourceId,version'
37
+ || a.screenId !== binding.cameraId || a.sourceId !== binding.sourceId
38
+ || a.regionConfigurationSha256 !== binding.regionConfigurationSha256
39
+ || !id(a.profileId) || !id(a.selectionId) || !id(a.routeId)
40
+ || a.selectionId !== context.modelSelection?.selectionId
41
+ || !Number.isSafeInteger(at) || !Number.isSafeInteger(a.lease?.issuedAtMs)
42
+ || !Number.isSafeInteger(a.lease?.expiresAtMs) || a.lease.issuedAtMs < 0
43
+ || a.lease.expiresAtMs - a.lease.issuedAtMs !== 30000
44
+ || at < a.lease.issuedAtMs - 5000 || at >= a.lease.expiresAtMs) return null;
45
+ const basis = [a.version, a.kind, a.screenId, a.profileId, a.selectionId, a.routeId, a.sourceId, a.regionConfigurationSha256];
46
+ return a.revision === hash(basis) ? a : null;
47
+ }
48
+
49
+ function profileHeader(registration, camera) {
50
+ const env = registration?.environment;
51
+ return env?.kind === KIND && env.cameraId === camera.cameraId && env.sourceId === camera.sourceId
52
+ ? env.sourceId + '.' + env.regionConfigurationSha256 : null;
53
+ }
54
+
55
+ module.exports = { KIND, TEMPLATE, validateEnvironment, readLiveAdmission, profileHeader };
@@ -0,0 +1,188 @@
1
+ """Versioned integration copy: original observed clocks, frozen geometry rules.
2
+ Frozen predecessor SHA256: 5aad88ac5a4dafba5eaf5514148346ad60b24c8bd3d1a7ebb9739e5ff6d6ba91
3
+ """
4
+
5
+ from collections import deque
6
+ from dataclasses import dataclass, field
7
+ import math
8
+
9
+
10
+ SUPPORTED = 'supported_observed_arm_appearance_stock_to_upper_approach'
11
+ REVIEW_PICTURES = 13
12
+ REVIEW_LIMIT_MS = 90_000
13
+ CADENCE_MS = 500
14
+ CAPTURE_TIMING_POLICY = {'version': 'observed_capture_clock/v1', 'maximumGapMs': 750,
15
+ 'minimumSpanMs': 500, 'maximumSpanMs': 1500}
16
+
17
+
18
+ def observed_gap(previous, current):
19
+ return (type(previous) is int and type(current) is int
20
+ and 0 < current - previous <= CAPTURE_TIMING_POLICY['maximumGapMs'])
21
+ SAME_WRIST_ROUTE = 'continuous_observed_same_wrist_stock_to_chest'
22
+ COLLAR_ROUTE = 'continuous_observed_same_wrist_stock_to_collar'
23
+
24
+
25
+ def collar_approach(path):
26
+ """Require a tracked lift and two adjacent, corroborated collar observations."""
27
+ if len(path) < 3:
28
+ return False
29
+ origin, first, last = path[0], path[-2], path[-1]
30
+ if (not origin['stock'] or origin['chest']
31
+ or any(row['stock'] or row['chest'] for row in path[1:])
32
+ or any(not observed_gap(a['clock'], b['clock']) for a, b in zip(path, path[1:]))
33
+ or not CADENCE_MS <= first['clock'] - origin['clock'] <= 1500):
34
+ return False
35
+ for row in (first, last):
36
+ depth, lateral = row['torso']
37
+ if not (-.12 <= depth <= .20 and abs(lateral) <= 1.0 and row['armApproachSupported']):
38
+ return False
39
+ start_depth, start_lateral = origin['torso']
40
+ first_depth, first_lateral = first['torso']
41
+ approach = math.hypot(start_depth - .30, start_lateral) - math.hypot(first_depth - .30, first_lateral)
42
+ return start_depth - first_depth >= .35 and approach >= .12
43
+
44
+
45
+ def frame_ref(frame):
46
+ return frame['sourceIndex'], frame['capturedAtMs'], frame['sha256']
47
+
48
+
49
+ @dataclass(frozen=True)
50
+ class Episode:
51
+ origin_ms: int
52
+ arrival_ms: int
53
+ side: str
54
+ references: frozenset
55
+
56
+ @classmethod
57
+ def from_window(cls, actor, window, cue_refs=()):
58
+ if window.get('reason') != SUPPORTED:
59
+ return None
60
+ proof = window.get('armAreaQualification', {})
61
+ if (proof.get('actor') != actor or proof.get('side') != window['side']
62
+ or proof.get('allActualSupportPicturesQualified') is not True
63
+ or proof.get('sourceAndDestinationMasksChecked') is not True):
64
+ return None
65
+ origin = window['movementConfirmation']['stockOriginEvidence']
66
+ if origin['route'] == 'direct_observed_stock_departure':
67
+ if origin['directStockDecision']['eligible'] is not True:
68
+ return None
69
+ origin_ms = window['fromClock']
70
+ elif origin['route'] == 'recent_observed_same_arm_stock_witness_then_separate_motion_window':
71
+ origin_ms = origin['witness']['clock']
72
+ elif origin['route'] == SAME_WRIST_ROUTE:
73
+ wrist_path = window['movementConfirmation']['wristPath']
74
+ if (len(wrist_path) < 3 or not wrist_path[0]['stock'] or not wrist_path[-1]['chest']
75
+ or any(entry['stock'] for entry in wrist_path[1:])
76
+ or any(entry['chest'] for entry in wrist_path[:-1])
77
+ or any(not observed_gap(a['clock'], b['clock']) for a, b in zip(wrist_path, wrist_path[1:]))
78
+ or [entry['clock'] for entry in wrist_path] !=
79
+ [ref['capturedAtMs'] for ref in proof['originals']]):
80
+ return None
81
+ origin_ms = wrist_path[0]['clock']
82
+ elif origin['route'] == COLLAR_ROUTE:
83
+ wrist_path = window['movementConfirmation']['wristPath']
84
+ if (not collar_approach(wrist_path)
85
+ or [entry['clock'] for entry in wrist_path] !=
86
+ [ref['capturedAtMs'] for ref in proof['originals']]):
87
+ return None
88
+ origin_ms = wrist_path[0]['clock']
89
+ else:
90
+ return None
91
+ arrival_ms = window['toClock']
92
+ refs = frozenset(frame_ref(ref) for ref in (*proof['originals'], *cue_refs))
93
+ if (arrival_ms - origin_ms < CAPTURE_TIMING_POLICY['minimumSpanMs'] or not refs
94
+ or min(ref[1] for ref in refs) != origin_ms
95
+ or max(ref[1] for ref in refs) != arrival_ms):
96
+ return None
97
+ return cls(origin_ms, arrival_ms, window['side'], refs)
98
+
99
+
100
+ @dataclass
101
+ class OpenCase:
102
+ case_id: str
103
+ first_ms: int
104
+ last_arrival_ms: int
105
+ pending: list = field(default_factory=list)
106
+ snapshots: int = 0
107
+
108
+
109
+ class ReviewCaseEvidence:
110
+ """One ordered camera/scope session. Emits local receipts, with no delivery."""
111
+
112
+ capture_timing_policy = CAPTURE_TIMING_POLICY
113
+
114
+ def __init__(self, scope):
115
+ self.scope = scope
116
+ self.frames = deque(maxlen=REVIEW_PICTURES)
117
+ self.cases = {}
118
+ self.last_clock = None
119
+
120
+ def observe(self, record, now_ms):
121
+ frame, camera, row = (record[name] for name in ('frame', 'camera', 'row'))
122
+ ref = frame_ref(frame)
123
+ clock = ref[1]
124
+ if camera['scope'] != self.scope or camera['capturedAtMs'] != clock or camera['imageSha256'] != ref[2]:
125
+ raise ValueError('Frame evidence crossed the active camera scope')
126
+ if now_ms < clock or (self.last_clock is not None and clock <= self.last_clock):
127
+ raise ValueError('Strictly ordered observed pictures required')
128
+ reset = (camera['guard'] not in ('initial', 'stable_hypothesis')
129
+ or camera['trackerResetDiagnostic'] is not False
130
+ or camera.get('resetMovementEvidence') is True
131
+ or (self.last_clock is not None and not observed_gap(self.last_clock, clock)))
132
+ self.last_clock = clock
133
+ if reset:
134
+ self.frames.clear()
135
+ self.cases.clear()
136
+ return []
137
+ self.frames.append(ref)
138
+ self.cases = {actor: case for actor, case in self.cases.items()
139
+ if now_ms - case.first_ms <= REVIEW_LIMIT_MS}
140
+ observed = {person['track_id'] for person in record['actualObservedPeople']}
141
+ for cue in row['cues']:
142
+ actor = cue['trackHypothesis']
143
+ if (actor in self.cases or actor not in observed or cue['scope'] != self.scope
144
+ or now_ms - clock > REVIEW_LIMIT_MS):
145
+ continue
146
+ episode = Episode.from_window(actor, cue['support'], cue['sourceFrameReferences'])
147
+ if episode is None or episode.arrival_ms != clock:
148
+ raise ValueError('Opening cue lacks its qualified original episode')
149
+ if len(self.cases) >= 64:
150
+ raise ValueError('Bounded review case capacity reached')
151
+ self.cases[actor] = OpenCase(cue['id'], clock, clock, [episode])
152
+
153
+ refs = set(self.frames)
154
+ for item in row['actors']:
155
+ actor = item['actorHypothesis']
156
+ case = self.cases.get(actor)
157
+ if actor not in observed or case is None or case.last_arrival_ms == clock:
158
+ continue
159
+ eligible = []
160
+ for window in item['allObservedArmWindows']:
161
+ episode = Episode.from_window(actor, window)
162
+ if (episode and case.last_arrival_ms < episode.origin_ms
163
+ and episode.arrival_ms == clock and episode.references <= refs):
164
+ eligible.append(episode)
165
+ if eligible:
166
+ # The existing cue rule prefers the nearest qualified origin.
167
+ episode = min(eligible, key=lambda value: (-value.origin_ms, value.side))
168
+ case.pending.append(episode)
169
+ case.last_arrival_ms = clock
170
+
171
+ if len(refs) != REVIEW_PICTURES or len({value[2] for value in refs}) != REVIEW_PICTURES:
172
+ return []
173
+ receipts = []
174
+ for actor, case in self.cases.items():
175
+ if actor not in observed or not case.pending:
176
+ continue
177
+ if any(not episode.references <= refs for episode in case.pending):
178
+ continue
179
+ receipts.append({'captureTimingPolicy': dict(CAPTURE_TIMING_POLICY), 'caseId': case.case_id, 'actor': actor,
180
+ 'kind': 'open_case' if case.snapshots == 0 else 'add_case_evidence',
181
+ 'firstCaptureMs': case.first_ms, 'deadlineMs': case.first_ms + REVIEW_LIMIT_MS,
182
+ 'snapshotAnchorMs': clock, 'pictures': list(self.frames),
183
+ 'episodes': [{'originMs': e.origin_ms, 'arrivalMs': e.arrival_ms, 'side': e.side,
184
+ 'support': sorted(e.references, key=lambda ref: ref[1])}
185
+ for e in case.pending]})
186
+ case.snapshots += 1
187
+ case.pending.clear()
188
+ return receipts