Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 8 additions & 5 deletions bench/capture/HANDOFF_CALIBRATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
27 changes: 21 additions & 6 deletions bench/lib/handoff-calibration.js
Original file line number Diff line number Diff line change
@@ -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']);

Expand Down Expand Up @@ -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) {
Expand All @@ -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 {
Expand Down Expand Up @@ -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-'),
Expand All @@ -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'),
};
}
Expand All @@ -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,
};
37 changes: 36 additions & 1 deletion bench/lib/handoff-calibration.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
});

Expand Down Expand Up @@ -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;
Expand All @@ -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,
Expand All @@ -109,6 +143,7 @@ test('aggregates session errors and absolute timing', () => {
detectedHandoffs: 2,
missedHandoffs: 1,
extraHandoffs: 2,
timingFailures: 1,
maxAbsoluteTimingErrorMs: 250,
});
});
3 changes: 2 additions & 1 deletion bench/tools/analyze-handoff-captures.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
58 changes: 53 additions & 5 deletions server-go/handoff.go
Original file line number Diff line number Diff line change
Expand Up @@ -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{}}}
Expand All @@ -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
Expand Down
50 changes: 46 additions & 4 deletions server-node/handoff.js
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
42 changes: 39 additions & 3 deletions server-python/handoff.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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"],
Expand Down
Loading