Download web/server/contract-engine.mjs from loveaa/OneAlign: direct link, hf CLI and curl.
- Browser
- Download file 8.98 kB
-
https://huggingface.co/spaces/loveaa/OneAlign/resolve/main/web/server/contract-engine.mjs
- Command line
-
hf download hf://spaces/loveaa/OneAlign/web/server/contract-engine.mjs
-
curl -L -o contract-engine.mjs https://huggingface.co/spaces/loveaa/OneAlign/resolve/main/web/server/contract-engine.mjs
8.98 kB
| // Shared deterministic runtime for API-authored contracts. No generated code is executed. | |
| export function conditionValue(condition, answers) { | |
| const values=condition.terms.map(term=>{ | |
| const a=answers[term.observer] | |
| if(!a||a.abstained||!a.choice||a.choice==='unknown'||a.choice==='unclear')return null | |
| return term.values.includes(a.choice) | |
| }) | |
| if(condition.operator==='any')return values.includes(true)?true:values.includes(null)?null:false | |
| return values.includes(false)?false:values.includes(null)?null:true | |
| } | |
| export function inWindow(window, minute) { | |
| if(!window)return true | |
| const toMin=s=>Number(s.slice(0,2))*60+Number(s.slice(3)) | |
| const start=toMin(window.start),end=toMin(window.end) | |
| return start<=end?minute>=start&&minute<end:minute>=start||minute<end | |
| } | |
| export function shanghaiMinute(seconds) { | |
| const d=new Date(seconds*1000) | |
| const parts=new Intl.DateTimeFormat('en-GB',{timeZone:'Asia/Shanghai',hour:'2-digit',minute:'2-digit',hourCycle:'h23'}).format(d).split(':') | |
| return Number(parts[0])*60+Number(parts[1]) | |
| } | |
| function ruleState() { | |
| return {firstAt:null,lastAt:null,lastValue:null,baseline:null,candidate:null,candidateCount:0,thenCount:0,positiveSince:null,armedAt:null,active:false,ever:false,episodes:0,unknown:0,valid:0,observations:0,lastNotice:-Infinity,lastLevel:0,summarySent:false} | |
| } | |
| export class ContractEngine { | |
| constructor(plan,{cameraId='camera',sourceId='source',maxGapSeconds=8,maxAgeSeconds=120,startedAt=null,snapshotComparison=false,comparisonMaxAgeSeconds=86400}={}) { | |
| this.plan=plan;this.cameraId=cameraId;this.sourceId=sourceId;this.maxGapSeconds=maxGapSeconds;this.maxAgeSeconds=maxAgeSeconds | |
| this.startedAt=startedAt | |
| this.snapshotComparison=snapshotComparison;this.comparisonMaxAgeSeconds=comparisonMaxAgeSeconds | |
| this.states=Object.fromEntries(plan.rules.map(r=>[r.id,ruleState()]));this.seen=new Set();this.notices=[];this.traces=[];this.todo=new Set() | |
| } | |
| seedSnapshot(answers,capturedAt){ | |
| if(!this.snapshotComparison||!Number.isFinite(capturedAt))return | |
| for(const r of this.plan.rules){if(r.mode!=='change')continue;const value=conditionValue(r.condition,answers);if(value===null)continue;Object.assign(this.states[r.id],{baseline:value,lastValue:value,lastKnownAt:capturedAt})} | |
| } | |
| observe(evidence,answers,{signals={},manual=false}={}) { | |
| const {capturedAt,processedAt=capturedAt,frameId,cameraId=this.cameraId,sourceId=this.sourceId,quality='usable'}=evidence | |
| const trace={frameId,capturedAt,processedAt,rules:[],notices:[],accepted:false} | |
| const reject=reason=>{trace.reason=reason;this.traces.push(trace);return trace} | |
| if(this.plan.status!=='ready')return reject('plan_not_ready') | |
| if(this.seen.has(frameId))return reject('duplicate_frame') | |
| if(!Number.isFinite(capturedAt)||!Number.isFinite(processedAt))return reject('invalid_timestamp') | |
| if(cameraId!==this.cameraId||sourceId!==this.sourceId)return reject('source_mismatch') | |
| if(processedAt-capturedAt>this.maxAgeSeconds||capturedAt>processedAt+1)return reject('stale_evidence') | |
| if(Object.values(this.states).some(s=>s.lastAt!=null&&capturedAt<s.lastAt))return reject('out_of_order') | |
| this.seen.add(frameId);trace.accepted=true | |
| for(const r of this.plan.rules){ | |
| let s=this.states[r.id];const minute=shanghaiMinute(capturedAt) | |
| if(r.mode==='window_summary'&&s.summarySent&&capturedAt>s.summaryDeadline&&inWindow(r.time_window,minute)){s=ruleState();this.states[r.id]=s} | |
| const step={id:r.id,mode:r.mode,value:null,status:'waiting',notified:false} | |
| trace.rules.push(step) | |
| if(!inWindow(r.time_window,minute)||(r.exclude_window&&inWindow(r.exclude_window,minute))){step.status='outside_window';continue} | |
| if(r.requires.some(key=>{const signal=signals[key];return !signal||!signal.value||!Number.isFinite(signal.observedAt)||!Number.isFinite(signal.validUntil)||signal.observedAt>capturedAt+1||signal.validUntil<capturedAt||typeof signal.source!=='string'||!signal.source.length})){step.status='external_gate';continue} | |
| s.observations++ | |
| const gap=s.lastAt==null?0:capturedAt-s.lastAt | |
| s.lastAt=capturedAt | |
| if(s.firstAt==null)s.firstAt=capturedAt | |
| const value=quality==='usable'?conditionValue(r.condition,answers):null | |
| step.value=value | |
| if(value==null){s.unknown++;s.candidate=null;s.candidateCount=0;s.thenCount=0;s.positiveSince=null;step.status='unknown';continue} | |
| s.valid++ | |
| const snapshot=this.snapshotComparison&&['change','occurrence','now'].includes(r.mode) | |
| if(snapshot&&s.lastKnownAt!=null&&capturedAt-s.lastKnownAt>this.comparisonMaxAgeSeconds){s.baseline=null;s.lastValue=null;s.candidate=null;s.candidateCount=0} | |
| if(gap>this.maxGapSeconds){s.positiveSince=null;s.thenCount=0;if(!snapshot){s.candidateCount=0;s.candidate=null}} | |
| s.lastKnownAt=capturedAt | |
| if(s.candidate===value)s.candidateCount++;else{s.candidate=value;s.candidateCount=1} | |
| if(value&&s.positiveSince==null)s.positiveSince=capturedAt | |
| if(!value)s.positiveSince=null | |
| const confirmed=s.candidateCount>=r.confirmation_frames | |
| if(r.mode==='now'){step.status='snapshot';s.lastValue=value;continue} | |
| if(r.mode==='change'&&s.baseline==null){ | |
| if(!confirmed){step.status='confirming_baseline';continue} | |
| s.baseline=value;s.lastValue=value;step.status=value?'target_at_creation':'baseline_recorded';continue | |
| } | |
| let trigger=false | |
| if(r.mode==='sequence'){ | |
| const next=conditionValue(r.then,answers) | |
| s.thenCount=next===true?s.thenCount+1:0 | |
| if(s.armedAt!=null&&capturedAt-s.armedAt>r.within_seconds)s.armedAt=null | |
| if(s.armedAt!=null&&capturedAt>s.armedAt&&s.thenCount>=r.confirmation_frames){trigger=true;s.armedAt=null;step.status='sequence_complete';s.thenCount=0} | |
| else if(value&&confirmed&&s.armedAt==null){s.armedAt=capturedAt;step.status='sequence_armed'} | |
| else step.status=s.armedAt==null?'waiting_first':'waiting_second' | |
| }else if(r.mode==='duration'){ | |
| const duration=s.positiveSince==null?0:capturedAt-s.positiveSince | |
| step.durationSeconds=duration | |
| trigger=!!(value&&confirmed&&duration>=r.duration_seconds&&!s.active) | |
| step.status=trigger?'duration_met':value?'timing':'negative' | |
| }else if(r.mode==='change'){ | |
| trigger=confirmed&&value===true&&s.lastValue===false&&(!r.recovery||!s.active) | |
| step.status=!confirmed?'confirming':trigger?'changed':'unchanged' | |
| }else{ | |
| trigger=confirmed&&value===true&&!s.active | |
| step.status=!confirmed?'confirming':trigger?'occurred':value?'same_episode':'negative' | |
| } | |
| if(confirmed){ | |
| const recovered=r.recovery?conditionValue(r.recovery,answers)===true:!value | |
| if(value&&!s.active&&(r.mode!=='duration'||trigger)){s.episodes++;s.ever=true} | |
| if(r.mode!=='duration'||trigger||!value){if(value)s.active=true;else if(recovered)s.active=false} | |
| s.lastValue=value | |
| if(recovered&&this.todo.has(r.id)){this.todo.delete(r.id);step.recovered=true} | |
| } | |
| if(trigger){ | |
| this.todo.add(r.id) | |
| if(r.notify==='realtime'&&(!manual||r.level===3)&&r.level>0&&(capturedAt-s.lastNotice>=r.cooldown_seconds||r.level>s.lastLevel)){ | |
| const notice={ruleId:r.id,title:r.title,at:capturedAt,level:r.level,status:step.status,frameId} | |
| this.notices.push(notice);trace.notices.push(notice);s.lastNotice=capturedAt;s.lastLevel=r.level;step.notified=true | |
| } | |
| } | |
| } | |
| this.traces.push(trace);return trace | |
| } | |
| finalize(at){ | |
| const reports=[] | |
| for(const r of this.plan.rules){ | |
| if(r.mode!=='window_summary')continue | |
| let s=this.states[r.id] | |
| if(s.summarySent){ | |
| const elapsed=Math.floor((at-s.summaryDeadline)/86400) | |
| if(!Number.isFinite(elapsed)||elapsed<1)continue | |
| const anchor=s.summaryDeadline+elapsed*86400-1 | |
| s=ruleState();s.windowAnchor=anchor;this.states[r.id]=s | |
| } | |
| const toMin=t=>Number(t.slice(0,2))*60+Number(t.slice(3)) | |
| const start=toMin(r.time_window.start),end=toMin(r.time_window.end),anchor=s.firstAt??s.windowAnchor??this.startedAt??at | |
| let base=Math.floor((anchor+8*3600)/86400)*86400-8*3600 | |
| if(end<=start&&shanghaiMinute(anchor)<end)base-=86400 | |
| let deadline=base+end*60+(end<=start?86400:0) | |
| if(s.firstAt==null&&this.startedAt!=null&&this.startedAt>=deadline)deadline+=86400 | |
| if(at<deadline)continue | |
| const result={ruleId:r.id,at,observed:s.ever,episodes:s.episodes,valid:s.valid,unknown:s.unknown,status:s.ever?'observed':s.valid?'not_observed':'insufficient_evidence'} | |
| reports.push(result);s.summarySent=true;s.summaryDeadline=deadline | |
| if(r.notify==='summary'&&r.level>0)this.notices.push({ruleId:r.id,title:r.title,at,level:r.level,status:result.status,summary:true}) | |
| } | |
| return reports | |
| } | |
| snapshot(){return {states:this.states,notices:this.notices,todo:[...this.todo],traces:this.traces}} | |
| } | |