diff --git a/bench/capture/HANDOFF_CALIBRATION.md b/bench/capture/HANDOFF_CALIBRATION.md index 41f0bb0..7b3c363 100644 --- a/bench/capture/HANDOFF_CALIBRATION.md +++ b/bench/capture/HANDOFF_CALIBRATION.md @@ -88,11 +88,14 @@ node bench/tools/analyze-handoff-captures.js \ ``` Use `--json` for a machine-readable result. A session passes only when every -declared transition is detected in order and no extra transition appears. The -timing error is measured from the first action in the new declared phase to the -detector's first qualifying action window. The clock alignment is derived from -the session's first content-free action and production action window; a 250 ms -quantization unit is the smallest meaningful timing difference. +declared transition is detected in order, no extra transition appears, and each +match occurs no more than 500 ms early or 10 seconds late. The asymmetric bound +treats early attribution as the more serious false handoff while allowing a +short delay for enough positive evidence to accumulate. The timing error is +measured from the first action in the new declared phase to the detector's first +qualifying actor segment. The clock alignment is derived from the session's +first content-free action and production action window; a 250 ms quantization +unit is the smallest meaningful timing difference. ## Accessibility and input controls diff --git a/bench/lib/handoff-calibration.js b/bench/lib/handoff-calibration.js index 14fccaa..e68c1a5 100644 --- a/bench/lib/handoff-calibration.js +++ b/bench/lib/handoff-calibration.js @@ -1,6 +1,8 @@ 'use strict'; const POLICY = 'human-agent-handoff-v1'; +const MAX_EARLY_TIMING_ERROR_MS = 500; +const MAX_LATE_TIMING_ERROR_MS = 10000; const ACTORS = new Set(['human', 'agent']); const KINDS = new Set(['click', 'key', 'scroll', 'touch']); @@ -78,10 +80,13 @@ function pairHandoffs(expected, actual) { const missed = []; for (const want of expected) { let matchIndex = -1; + let matchDistance = Infinity; for (let i = 0; i < actual.length; i++) { - if (!used.has(i) && actual[i]?.direction === want.direction) { + if (!used.has(i) && actual[i]?.direction === want.direction && Number.isInteger(actual[i]?.atQ)) { + const distance = Math.abs(actual[i].atQ - want.atQ); + if (distance >= matchDistance) continue; matchIndex = i; - break; + matchDistance = distance; } } if (matchIndex < 0) { @@ -90,12 +95,16 @@ function pairHandoffs(expected, actual) { } used.add(matchIndex); const got = actual[matchIndex]; + const timingErrorQ = got.atQ - want.atQ; + const timingErrorMs = timingErrorQ * 250; matched.push({ direction: want.direction, expectedAtQ: want.atQ, detectedAtQ: got.atQ, - timingErrorQ: Number.isInteger(got.atQ) ? got.atQ - want.atQ : null, - timingErrorMs: Number.isInteger(got.atQ) ? (got.atQ - want.atQ) * 250 : null, + timingErrorQ, + timingErrorMs, + withinTolerance: timingErrorMs >= -MAX_EARLY_TIMING_ERROR_MS && + timingErrorMs <= MAX_LATE_TIMING_ERROR_MS, }); } return { @@ -131,6 +140,7 @@ function analyzeHandoffReport(report, source = 'report') { !Number.isInteger(handoff.atQ)) invalid('observation contains a malformed handoff'); } const paired = pairHandoffs(expected, actual); + const timingFailures = paired.matched.filter((entry) => !entry.withinTolerance).length; return { source, scenario: sample.scenario || sequence.join('-to-'), @@ -140,8 +150,9 @@ function analyzeHandoffReport(report, source = 'report') { detectedHandoffs: actual.length, missedHandoffs: paired.missed.length, extraHandoffs: paired.extra.length, + timingFailures, timing: paired.matched, - pass: paired.missed.length === 0 && paired.extra.length === 0 && + pass: paired.missed.length === 0 && paired.extra.length === 0 && timingFailures === 0 && (expected.length ? observation.status === 'detected' : observation.status === 'clear'), }; } @@ -157,10 +168,14 @@ function aggregateHandoffReports(results) { detectedHandoffs: results.reduce((sum, result) => sum + result.detectedHandoffs, 0), missedHandoffs: results.reduce((sum, result) => sum + result.missedHandoffs, 0), extraHandoffs: results.reduce((sum, result) => sum + result.extraHandoffs, 0), + timingFailures: results.reduce((sum, result) => sum + (result.timingFailures || 0), 0), maxAbsoluteTimingErrorMs: timing.length ? Math.max(...timing.map((entry) => Math.abs(entry.timingErrorMs))) : null, }; } -module.exports = { POLICY, aggregateHandoffReports, analyzeHandoffReport }; +module.exports = { + MAX_EARLY_TIMING_ERROR_MS, MAX_LATE_TIMING_ERROR_MS, POLICY, + aggregateHandoffReports, analyzeHandoffReport, +}; diff --git a/bench/lib/handoff-calibration.test.js b/bench/lib/handoff-calibration.test.js index 9973591..a6eb009 100644 --- a/bench/lib/handoff-calibration.test.js +++ b/bench/lib/handoff-calibration.test.js @@ -42,6 +42,7 @@ test('reports a correctly placed human to agent handoff', () => { assert.equal(result.pass, true); assert.equal(result.missedHandoffs, 0); assert.equal(result.extraHandoffs, 0); + assert.equal(result.timingFailures, 0); assert.equal(result.timing[0].timingErrorMs, 0); }); @@ -82,6 +83,39 @@ test('single actor controls must be positively classified as clear', () => { assert.equal(result.pass, false); }); +test('fails a directionally correct handoff that occurs too early', () => { + const result = analyzeHandoffReport(report( + ['human', 'agent'], + [ + { t: 1, kind: 'key', phase: 0, actor: 'human' }, + { t: 300, kind: 'click', phase: 1, actor: 'agent' }, + ], + [{ direction: 'human_to_agent', atQ: 20 }] + )); + assert.equal(result.missedHandoffs, 0); + assert.equal(result.extraHandoffs, 0); + assert.equal(result.timingFailures, 1); + assert.equal(result.timing[0].withinTolerance, false); + assert.equal(result.pass, false); +}); + +test('matches repeated directions by nearest transition time', () => { + const result = analyzeHandoffReport(report( + ['human', 'agent'], + [ + { t: 1, kind: 'key', phase: 0, actor: 'human' }, + { t: 20, kind: 'click', phase: 1, actor: 'agent' }, + ], + [ + { direction: 'human_to_agent', atQ: 5 }, + { direction: 'human_to_agent', atQ: 21 }, + ] + )); + assert.equal(result.timing[0].detectedAtQ, 21); + assert.equal(result.extraHandoffs, 1); + assert.equal(result.pass, false); +}); + test('refuses truncated or phase-empty ground truth', () => { const truncated = report(['human'], [{ t: 1, kind: 'key', phase: 0, actor: 'human' }], []); truncated.samples[0].handoffGroundTruth.truncated = true; @@ -100,7 +134,7 @@ test('aggregates session errors and absolute timing', () => { ], [{ direction: 'human_to_agent', atQ: 10 }] )); - const failed = { ...passed, pass: false, missedHandoffs: 1, extraHandoffs: 2 }; + const failed = { ...passed, pass: false, missedHandoffs: 1, extraHandoffs: 2, timingFailures: 1 }; assert.deepEqual(aggregateHandoffReports([passed, failed]), { sessions: 2, passed: 1, @@ -109,6 +143,7 @@ test('aggregates session errors and absolute timing', () => { detectedHandoffs: 2, missedHandoffs: 1, extraHandoffs: 2, + timingFailures: 1, maxAbsoluteTimingErrorMs: 250, }); }); diff --git a/bench/tools/analyze-handoff-captures.js b/bench/tools/analyze-handoff-captures.js index fbe8425..b03f953 100644 --- a/bench/tools/analyze-handoff-captures.js +++ b/bench/tools/analyze-handoff-captures.js @@ -45,10 +45,11 @@ function main() { const timing = result.timing.map((entry) => `${entry.direction}:${entry.timingErrorMs}ms`).join(', ') || '-'; process.stdout.write(`${result.pass ? 'PASS' : 'FAIL'} ${result.scenario} ` + `classification=${result.classification} missed=${result.missedHandoffs} ` + - `extra=${result.extraHandoffs} timing=${timing}\n`); + `extra=${result.extraHandoffs} timingFailures=${result.timingFailures} timing=${timing}\n`); } process.stdout.write(`sessions=${output.summary.sessions} passed=${output.summary.passed} ` + `missed=${output.summary.missedHandoffs} extra=${output.summary.extraHandoffs} ` + + `timingFailures=${output.summary.timingFailures} ` + `maxAbsTimingErrorMs=${output.summary.maxAbsoluteTimingErrorMs ?? '-'}\n`); } if (output.summary.failed) process.exitCode = 1; diff --git a/server-go/handoff.go b/server-go/handoff.go index 6bf695b..e5b8003 100644 --- a/server-go/handoff.go +++ b/server-go/handoff.go @@ -169,6 +169,56 @@ func buildActorRuns(windows []actionWindow) []actorRun { return runs } +func mergeActorSegments(segments []actorRun) []actorRun { + merged := []actorRun{} + for _, source := range segments { + if len(merged) == 0 || merged[len(merged)-1].Actor != source.Actor { + source.EvidenceFamilies = mergeFamilies(nil, source.EvidenceFamilies) + merged = append(merged, source) + continue + } + segment := &merged[len(merged)-1] + segment.EndQ = source.EndQ + segment.Windows += source.Windows + segment.Actions += source.Actions + segment.EvidenceFamilies = mergeFamilies(segment.EvidenceFamilies, source.EvidenceFamilies) + segment.Confidence = runConfidence(segment.EvidenceFamilies) + } + return merged +} + +func supportedActorSegment(segment actorRun) bool { + return segment.Windows >= 2 || len(segment.EvidenceFamilies) >= 2 +} + +func confirmedActorSegments(runs []actorRun) []actorRun { + decided := []actorRun{} + for _, run := range runs { + if run.Actor != "unknown" { + decided = append(decided, run) + } + } + segments := mergeActorSegments(decided) + for changed := true; changed; { + changed = false + for i := 1; i < len(segments)-1; i++ { + if !supportedActorSegment(segments[i]) && segments[i-1].Actor == segments[i+1].Actor { + segments = append(segments[:i], segments[i+1:]...) + segments = mergeActorSegments(segments) + changed = true + break + } + } + } + supported := []actorRun{} + for _, segment := range segments { + if supportedActorSegment(segment) { + supported = append(supported, segment) + } + } + return mergeActorSegments(supported) +} + func handoffObservation(signals map[string]interface{}) ExperimentalObservation { result := ExperimentalObservation{Mode: "observe", Status: "unknown", Detections: []ExperimentalDetection{}, Details: handoffDetails{Version: 1, Truncated: false, Runs: []actorRun{}, Handoffs: []controlHandoff{}}} @@ -177,12 +227,10 @@ func handoffObservation(signals map[string]interface{}) ExperimentalObservation return result } runs := buildActorRuns(set.Windows) + confirmed := confirmedActorSegments(runs) handoffs := []controlHandoff{} - for i := 1; i < len(runs); i++ { - before, after := runs[i-1], runs[i] - if before.Actor == "unknown" || after.Actor == "unknown" || before.Actor == after.Actor { - continue - } + for i := 1; i < len(confirmed); i++ { + before, after := confirmed[i-1], confirmed[i] confidence := before.Confidence if after.Confidence < confidence { confidence = after.Confidence diff --git a/server-node/handoff.js b/server-node/handoff.js index 49b7cf8..78a8300 100644 --- a/server-node/handoff.js +++ b/server-node/handoff.js @@ -70,17 +70,59 @@ function buildRuns(windows) { return runs; } +function mergeActorSegments(segments) { + const merged = []; + for (const segment of segments) { + const last = merged[merged.length - 1]; + if (!last || last.actor !== segment.actor) { + merged.push({ ...segment, evidenceFamilies: [...segment.evidenceFamilies] }); + continue; + } + last.endQ = segment.endQ; + last.windows += segment.windows; + last.actions += segment.actions; + last.evidenceFamilies = [...new Set([...last.evidenceFamilies, ...segment.evidenceFamilies])].sort(); + last.confidence = actorConfidence(last.evidenceFamilies); + } + return merged; +} + +function supportedActorSegment(segment) { + return segment.windows >= 2 || segment.evidenceFamilies.length >= 2; +} + +// A single strong-looking click can occur during ordinary human navigation +// (for example after the pointer leaves and re-enters the content area). Treat +// an isolated contrary window between two same-actor segments as noise, then +// require the remaining actor segments to have repeated or independent support. +function confirmedActorSegments(runs) { + let segments = mergeActorSegments(runs.filter((run) => run.actor !== 'unknown')); + let changed = true; + while (changed) { + changed = false; + for (let i = 1; i < segments.length - 1; i++) { + if (!supportedActorSegment(segments[i]) && segments[i - 1].actor === segments[i + 1].actor) { + segments.splice(i, 1); + segments = mergeActorSegments(segments); + changed = true; + break; + } + } + } + return mergeActorSegments(segments.filter(supportedActorSegment)); +} + function evaluateHandoffObservation(signals) { const actionWindows = parseActionWindows(signals?.behavioral?.actionWindows); if (!actionWindows) { return { mode: 'observe', status: 'unknown', detections: [], details: { version: 1, truncated: false, runs: [], handoffs: [] } }; } const runs = buildRuns(actionWindows.windows); + const confirmed = confirmedActorSegments(runs); const handoffs = []; - for (let i = 1; i < runs.length; i++) { - const before = runs[i - 1]; - const after = runs[i]; - if (before.actor === 'unknown' || after.actor === 'unknown' || before.actor === after.actor) continue; + for (let i = 1; i < confirmed.length; i++) { + const before = confirmed[i - 1]; + const after = confirmed[i]; handoffs.push({ direction: `${before.actor}_to_${after.actor}`, atQ: after.startQ, diff --git a/server-python/handoff.py b/server-python/handoff.py index 107b428..01f1152 100644 --- a/server-python/handoff.py +++ b/server-python/handoff.py @@ -81,6 +81,43 @@ def _runs(windows): return runs +def _merge_segments(segments): + merged = [] + for source in segments: + if not merged or merged[-1]["actor"] != source["actor"]: + segment = dict(source) + segment["evidenceFamilies"] = list(source["evidenceFamilies"]) + merged.append(segment) + continue + segment = merged[-1] + segment["endQ"] = source["endQ"] + segment["windows"] += source["windows"] + segment["actions"] += source["actions"] + segment["evidenceFamilies"] = sorted(set( + segment["evidenceFamilies"] + source["evidenceFamilies"])) + segment["confidence"] = _confidence(segment["evidenceFamilies"]) + return merged + + +def _supported(segment): + return segment["windows"] >= 2 or len(segment["evidenceFamilies"]) >= 2 + + +def _confirmed_segments(runs): + segments = _merge_segments([run for run in runs if run["actor"] != "unknown"]) + changed = True + while changed: + changed = False + for index in range(1, len(segments) - 1): + if (not _supported(segments[index]) + and segments[index - 1]["actor"] == segments[index + 1]["actor"]): + del segments[index] + segments = _merge_segments(segments) + changed = True + break + return _merge_segments([segment for segment in segments if _supported(segment)]) + + def handoff_observation(signals): behavioral = signals.get("behavioral") if isinstance(signals, dict) else None value = behavioral.get("actionWindows") if isinstance(behavioral, dict) else None @@ -89,10 +126,9 @@ def handoff_observation(signals): return {"mode": "observe", "status": "unknown", "detections": [], "details": {"version": 1, "truncated": False, "runs": [], "handoffs": []}} runs = _runs(windows["windows"]) + confirmed = _confirmed_segments(runs) handoffs = [] - for before, after in zip(runs, runs[1:]): - if before["actor"] == "unknown" or after["actor"] == "unknown" or before["actor"] == after["actor"]: - continue + for before, after in zip(confirmed, confirmed[1:]): handoffs.append({ "direction": f'{before["actor"]}_to_{after["actor"]}', "atQ": after["startQ"], diff --git a/test/fixtures/human-agent-handoff.json b/test/fixtures/human-agent-handoff.json index 91e761f..86f4cbe 100644 --- a/test/fixtures/human-agent-handoff.json +++ b/test/fixtures/human-agent-handoff.json @@ -28,7 +28,9 @@ "truncated": false, "windows": [ { "t": 2, "kind": "click", "events": 1, "humanEvidenceFamilies": [], "agentEvidenceFamilies": ["pointer_provenance"] }, - { "t": 9, "kind": "key", "events": 5, "humanEvidenceFamilies": ["typing_cadence"], "agentEvidenceFamilies": [] } + { "t": 4, "kind": "scroll", "events": 1, "humanEvidenceFamilies": [], "agentEvidenceFamilies": ["scroll_behavior"] }, + { "t": 9, "kind": "key", "events": 5, "humanEvidenceFamilies": ["typing_cadence"], "agentEvidenceFamilies": [] }, + { "t": 11, "kind": "scroll", "events": 8, "humanEvidenceFamilies": ["scroll_behavior"], "agentEvidenceFamilies": [] } ] }, "status": "detected", @@ -53,6 +55,28 @@ "directions": [], "atQ": [] }, + { + "name": "transient contrary click does not create an early handoff", + "windows": { + "version": 1, + "quantumMs": 250, + "maxWindows": 48, + "truncated": false, + "windows": [ + { "t": 1, "kind": "key", "events": 6, "humanEvidenceFamilies": ["typing_cadence"], "agentEvidenceFamilies": [] }, + { "t": 4, "kind": "click", "events": 1, "humanEvidenceFamilies": [], "agentEvidenceFamilies": ["pointer_provenance"] }, + { "t": 6, "kind": "scroll", "events": 8, "humanEvidenceFamilies": ["scroll_behavior"], "agentEvidenceFamilies": [] }, + { "t": 20, "kind": "key", "events": 12, "humanEvidenceFamilies": [], "agentEvidenceFamilies": [] }, + { "t": 20, "kind": "click", "events": 1, "humanEvidenceFamilies": [], "agentEvidenceFamilies": ["pointer_provenance"] }, + { "t": 22, "kind": "scroll", "events": 2, "humanEvidenceFamilies": [], "agentEvidenceFamilies": [] }, + { "t": 24, "kind": "click", "events": 1, "humanEvidenceFamilies": [], "agentEvidenceFamilies": ["pointer_provenance"] } + ] + }, + "status": "detected", + "actors": ["human", "agent", "human", "unknown", "agent", "unknown", "agent"], + "directions": ["human_to_agent"], + "atQ": [20] + }, { "name": "unknown does not bridge actors", "windows": {