Make Codex and Claude Code subscriptions go further: a local model router that gives routine agent work to economical models and keeps your strongest model for the hard parts.
Rust ai-agentsai-gatewayclaude-codecodexcoding-agentcost-optimizationdeepseekllm-gatewayllm-routerlocal-firstmodel-routingrusttask-routingtauri
Show protection release evidence and a navigable routing overview (#157)
澄潭d09cdb9f4509
diff --git a/apps/desktop/src/features/PlanQuality.tsx b/apps/desktop/src/features/PlanQuality.tsxindex e5024ac1..15b7dbb4 100644--- a/apps/desktop/src/features/PlanQuality.tsx+++ b/apps/desktop/src/features/PlanQuality.tsx@@ -8,8 +8,10 @@ import { ContentExcerpt } from './Sessions';import { safeDiagnosticCode } from '../error-code';import { observationRead } from './observation-client';import { qualityExecutionModels } from './plan-quality-models';+import { planQualityWindow } from './plan-quality-window';import { PlanQualityStage, type PlanQualitySample } from './PlanQualityStage';import { RoutingObservations, type RoutingSummary } from './RoutingObservations';+import { releasedProtectionEvidence, type ReleasedProtectionEvidence } from './trust/protection-evidence';import { qualityRowSection, qualityRowSectionLabel, qualityGroupLabel, qualityModelRows, qualityNativeModelName, qualityReasoningLabel, type PlanQualityModel, type QualityExecution, type QualityModelRow, type QualitySummary } from './plan-quality-state';export type { PlanQualityModel } from './plan-quality-state';@@ -17,7 +19,7 @@ export type { PlanQualitySample } from './PlanQualityStage';type Page = { samples: PlanQualitySample[]; summary: QualitySummary; routing_observations?: RoutingSummary; next_cursor?: string | null };type ScoreFilter = 'all' | 'low' | 'high' | 'unrated';-type Period = 'all' | 'seven_days';+type Period = 'all' | 'seven_days' | 'one_day';const EMPTY_SUMMARY: QualitySummary = { models: [], scored_stage_count: 0, unrated_stage_count: 0, session_count: 0, available_revisions: [] };export function PlanQuality({@@ -54,14 +56,15 @@ export function PlanQuality({const generation = useRef(0);// A detail filter or next page must retain exactly the same time window.const window = useMemo(() => {- const now = Date.now();- return { from: period === 'seven_days' ? now - 7 * 86_400_000 : undefined, to: now + 1 };- }, [planId, sessionId, planRevision, period, version, refreshVersion, reload, active]);+ return planQualityWindow(period, Date.now());+ }, [planId, sessionId, planRevision, period, version, refreshVersion, reload, active, groupBy]);+ const pairedWindow = useRef<typeof window | null>(null);const revision = version === 'current' ? planRevision || null : version === 'all' ? null : Number(version);- async function load(next: string | null = null) {+ async function load(next: string | null = null, captureRouting = false) {if (!active || (!planId && !sessionId)) return;const epoch = ++generation.current;+ if (captureRouting) pairedWindow.current = window;setBusy(true); setError('');try {const page = await observationRead<Page>('plan_quality', {@@ -73,9 +76,11 @@ export function PlanQuality({competence: score === 'high' ? 'meets_floor' : score === 'low' ? 'below_floor' : null,unrated_only: score === 'unrated', limit: 20, cursor: next,});+ // Aggregate routing evidence belongs to the base read paired with PlanTrust.+ // Detail reads can be clipped by a later retention clock and must not replace it.+ if (captureRouting && pairedWindow.current === window) setRoutingSummary(page.routing_observations ?? null);if (epoch !== generation.current) return;setSummary(page.summary);- setRoutingSummary(page.routing_observations ?? null);const stages = selected && !selected.execution && !selected.trustRow ? [] : page.samples;setSamples(current => next ? [...current, ...stages] : stages);setCursor(selected && !selected.execution && !selected.trustRow ? null : page.next_cursor ?? null);@@ -100,12 +105,14 @@ export function PlanQuality({useEffect(() => {setSummary(EMPTY_SUMMARY);setRoutingSummary(null);+ pairedWindow.current = null;+ return () => { pairedWindow.current = null; };}, [planId, sessionId, revision, window]);useEffect(() => {if (!active) { generation.current++; setBusy(false); return; }setSamples([]); setExecutionModels({}); setCursor(null); setLoaded(false);- void load();+ void load(null, pairedWindow.current !== window);return () => { generation.current++; };}, [planId, sessionId, revision, score, selected?.key, window, active]);@@ -185,7 +192,7 @@ export function PlanQuality({<div className="quality-scope-meta">{text(`${stageCount} 个执行阶段 · ${summary.scored_stage_count} 已评分 · ${summary.unrated_stage_count} 未评分${report ? ` · 证据来自 ${report.session_total} 个会话` : ''}`, `${stageCount} stages · ${summary.scored_stage_count} scored · ${summary.unrated_stage_count} unrated${report ? ` · evidence from ${report.session_total} sessions` : ''}`)}</div><div className="quality-filters">{!compact && <label><span className="sr-only">{text('时间范围', 'Time range')}</span><select className="select" value={period} onChange={event => { resetDetail(); setPeriod(event.target.value as Period); }}>- <option value="seven_days">{text('最近 7 天', 'Last 7 days')}</option><option value="all">{text('全部保留期', 'All retained')}</option>+ <option value="seven_days">{text('最近 7 天', 'Last 7 days')}</option><option value="one_day">{text('最近 24 小时', 'Last 24 hours')}</option><option value="all">{text('全部保留期', 'All retained')}</option></select></label>}{!compact && planRevision && <label><span className="sr-only">{text('路由版本', 'Route version')}</span><select className="select" value={version} onChange={event => { resetDetail(); setVersion(event.target.value); }}><option value="current">{text('当前生效版本', 'Active version')}</option>@@ -195,7 +202,7 @@ export function PlanQuality({<button className="btn btn-quiet quality-refresh" type="button" disabled={busy} onClick={() => setReload(value => value + 1)}><UiIcon name="refresh" />{text('刷新', 'Refresh')}</button></div></div>- {trust.error && <div className="callout warn" role="alert" data-error-code={trust.error}><span>{trust.error.toLowerCase().includes('scope_too_large') ? text('证据超过读取上限。建议需要本版本的全部保留记录;缩短显示时间不一定能减少建议计算范围。', 'Evidence exceeds the read limit. Suggestions need the full retained version; narrowing the displayed window may not reduce that scope.') : text('证据暂时无法读取,当前档位未改变。', 'Evidence is unavailable. Your trust level has not changed.')}</span><button className="btn" type="button" onClick={trust.retry}>{text('重试', 'Retry')}</button></div>}+ {trust.error && <div className="callout warn" role="alert" data-error-code={trust.error}><span>{trust.error.toLowerCase().includes('scope_too_large') ? text('证据超过读取上限。建议需要本版本的全部保留记录;缩短显示时间不一定能减少建议计算范围。', 'Evidence exceeds the read limit. Suggestions need the full retained version; narrowing the displayed window may not reduce that scope.') : text('证据暂时无法读取,当前档位未改变。', 'Evidence is unavailable. Your trust level has not changed.')}</span><button className="btn" type="button" onClick={() => setReload(value => value + 1)}>{text('重试', 'Retry')}</button></div>}{trustScope && !report && !trust.error && <p className="quality-status" role="status">{text('正在读取完整范围的证据…', 'Reading the complete evidence scope…')}</p>}{report && <TrustSuggestions report={report} language={language} onThreshold={onThreshold} onDivision={onDivision} onOpenAgent={onOpenAgent} />}{report && groupBy === 'model' && <TrustTiles report={report} language={language} />}@@ -244,7 +251,7 @@ export function PlanQuality({</section>}{stageSection}{report && groupBy === 'model' && <div className="trust-card-pair">- <ProtectionCard report={report} caught={caught} language={language} onShowLow={showLowStages || undefined} onOpenEvidence={onOpenEvidence} />+ <ProtectionCard report={report} released={releasedProtectionEvidence(report, routingSummary)} caught={caught} language={language} onShowLow={showLowStages || undefined} onOpenEvidence={onOpenEvidence} /><TrustCost value={report.cost} language={language} /></div>}{report && groupBy === 'executor' && <ExecutorOutcomes report={report} language={language} />}@@ -253,14 +260,27 @@ export function PlanQuality({</div>;}-function ProtectionCard({ report, caught, language, onShowLow, onOpenEvidence }: { report: TrustReport; caught: PlanQualitySample[] | null; language: 'zh' | 'en'; onShowLow?: () => void; onOpenEvidence?: (sessionId: string, requestId: string) => void }) {+function ProtectionCard({ report, released, caught, language, onShowLow, onOpenEvidence }: { report: TrustReport; released: ReleasedProtectionEvidence; caught: PlanQualitySample[] | null; language: 'zh' | 'en'; onShowLow?: () => void; onOpenEvidence?: (sessionId: string, requestId: string) => void }) {const text = (zh: string, en: string) => language === 'zh' ? zh : en;const protections = report.rows.reduce((total, row) => total + row.protections.length, 0);const relays = report.rows.reduce((total, row) => total + row.availability_relays, 0);+ const releaseReason = released.kind === 'available' ? text('之前的问题已修正或与当前工作无关,允许新模型继续。', 'Earlier problems were fixed or unrelated, allowing Regular to continue.') : {+ missing: text('历史保护记录尚不可用。', 'Historical protection records are not available yet.'),+ partial: text('历史保护记录覆盖不完整。', 'Historical protection records have incomplete coverage.'),+ plan: text('历史保护记录与当前路由范围不同。', 'Historical protection records cover a different route scope.'),+ revision: text('历史保护记录与当前路由版本不同。', 'Historical protection records cover a different route version.'),+ time: text('历史保护记录与当前时间范围不同。', 'Historical protection records cover a different time range.'),+ branch: text('历史保护记录与当前分支范围不同。', 'Historical protection records cover different branches.'),+ }[released.reason];const time = (ms: number) => new Date(ms).toLocaleString(language === 'zh' ? 'zh-CN' : 'en-US', { month: 'numeric', day: 'numeric', hour: '2-digit', minute: '2-digit', hour12: false });return <section className="trust-card trust-protection"><h3>{text(`被拦下的 ${protections} 次`, `${protections} stages caught`)}</h3><p>{protections ? text('这些轮次因低分保护而交给主力模型,计数来自实际发生的记录。', 'These turns went to Primary through low-score protection; the count comes from recorded routing.') : text('还没有因为低分转交主力的阶段。', 'No stage has been handed to Primary after a low score yet.')}</p>+ <div className="trust-release" data-release-state={released.kind}>+ <strong>{released.kind === 'available' ? text(`解除 ${released.count} 次`, `${released.count} protections released`) : text('解除次数 —', 'Protections released —')}</strong>+ <p>{releaseReason}</p>+ {released.kind === 'available' && <p className="field-help">{text('解除按路由判断次数统计,与上方保护阶段数分开。', 'Releases count routing decisions; protections above count stages.')}</p>}+ </div>{caught && caught.length > 0 && <ul className="trust-caught">{caught.map(sample => <li key={sample.segment_id}><div><strong><ContentExcerpt session={sample.session_id} language={language} fallback={text('会话记录', 'Session')} limit={40} /></strong><span>{time(sample.first_at_ms)} · {text(`评分 ${sample.assessment?.score.toFixed(2) ?? '—'}`, `score ${sample.assessment?.score.toFixed(2) ?? '—'}`)}{sample.assessment?.reason ? text(`(${sample.assessment.reason})`, ` (${sample.assessment.reason})`) : ''} → {text('下一轮主力', 'next turn Primary')}</span></div>diff --git a/apps/desktop/src/features/RoutingObservations.tsx b/apps/desktop/src/features/RoutingObservations.tsxindex fc0ae00d..d68848c3 100644--- a/apps/desktop/src/features/RoutingObservations.tsx+++ b/apps/desktop/src/features/RoutingObservations.tsx@@ -15,6 +15,8 @@ type Counts = {unavailable_per_requested: number | null; suppressed_per_opportunity: number | null; suppressed_per_c_decision: number | null;};export type RoutingSummary = {+ plan_id: string | null; session_id: string | null; plan_revision: number | null;+ requested_from_ms: number | null; requested_to_ms: number | null;coverage: string; covered_from_ms: number; covered_to_ms: number; retained_decisions: number;known_non_c_decisions: number; legacy_or_unknown_decisions: number; unknown_scope_decisions: number; missing_projection_events: number; scan_limited: boolean;cohorts: { cohort: { protocol: string; content_digest: string; bundle_digest: string; scope_id: string; standard: string; provider: string; model: string; simple_threshold_millis: number; competence_floor_millis: number }; counts: Counts }[];diff --git a/apps/desktop/src/features/RoutingTimeline.tsx b/apps/desktop/src/features/RoutingTimeline.tsxindex 0b0bc226..0d5514b3 100644--- a/apps/desktop/src/features/RoutingTimeline.tsx+++ b/apps/desktop/src/features/RoutingTimeline.tsx@@ -1,4 +1,4 @@-import { Fragment, useCallback, useEffect, useRef, useState } from 'react';+import { Fragment, useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react';import { formatMoney } from '../ui';import { safeDiagnosticCode } from '../error-code';import { observationBusyRetryMs } from './observation-failure';@@ -10,11 +10,16 @@ import './routing-timeline.css';type Cost = { model_configuration_id: string | null; currency: string | null; valuation_kind: string | null; known_micros: number | null; unknown_contributions: number };export type TimelineRequest = { request_id: string; started_at_ms: number; duration_ms: number | null; native_model: string | null; input_tokens: number | null; output_tokens: number | null; cache_read_tokens: number | null; cache_read_share: number | null; costs: Cost[]; outcome: string | null };+export type TimelineProtection = {+ outcome: 'applied' | 'suppressed' | 'retained_unavailable' | 'not_needed' | 'not_considered';+ previous_score: number | null; competence_floor_millis: number;+ applicability_probability: number | null; applicability_boundary_millis: number;+};export type TimelineTurn = {turn_id: string; agent_turn_id: string | null; segment_id: string | null; started_at_ms: number; finished_at_ms: number | null;boundary: 'new_user_message' | 'context_rebuilt' | 'unknown'; plan_id: string | null; plan_revision: number | null;branch_id: string | null; model_configuration_id: string | null; reasoning_profile_id: string | null; group: string | null;- selection: { simple_probability: number | null; simple_threshold_millis: number | null; selection_reason: string; competence_trigger?: { score: number; floor_millis: number } | null } | null;+ selection: { simple_probability: number | null; simple_threshold_millis: number | null; selection_reason: string; competence_trigger?: { score: number; floor_millis: number } | null; historical_protection?: TimelineProtection | null } | null;tool_continuations: number; relays: { request_id: string; from_model: string | null; to_model: string | null }[];assessment_state: string; assessment: { score: number; partial: boolean; target_from_ordinal: number; target_through_ordinal: number } | null;competence_floor_millis: number | null; protected_turn_ids: string[]; status: string; requests: TimelineRequest[];@@ -47,6 +52,8 @@ export function RoutingTimeline({ session, language, active, displayed, refreshVconst [allRequests, setAllRequests] = useState(false);const [arrivals, setArrivals] = useState(new Set<string>());const [unseen, setUnseen] = useState<string[]>([]);+ const [viewport, setViewport] = useState({ from: 0, to: 1 });+ const [overviewFocus, setOverviewFocus] = useState<string | null>(null);const watermark = useRef<string | null>(null);const blockedScope = useRef(false);const probed = useRef(false);@@ -54,7 +61,7 @@ export function RoutingTimeline({ session, language, active, displayed, refreshVconst stored = useRef(new Map<string, TimelineTurn>());const scroller = useRef<HTMLDivElement>(null);useEffect(() => { blockedScope.current = false; setError(''); }, [session]);- useEffect(() => { watermark.current = null; probed.current = false; lastRead.current = -Infinity; stored.current.clear(); setTurns([]); setSelected(null); setLoaded(false); setArrivals(new Set()); setUnseen([]); }, [session, refreshVersion]);+ useEffect(() => { watermark.current = null; probed.current = false; lastRead.current = -Infinity; stored.current.clear(); setTurns([]); setSelected(null); setOverviewFocus(null); setLoaded(false); setArrivals(new Set()); setUnseen([]); }, [session, refreshVersion]);useEffect(() => {if (!arrivals.size) return;const timer = window.setTimeout(() => setArrivals(new Set()), 600);@@ -108,26 +115,35 @@ export function RoutingTimeline({ session, language, active, displayed, refreshVif (!pane || !pane.clientWidth) return;const viewport = pane.getBoundingClientRect();const labelWidth = pane.querySelector('.routing-lane-label')?.getBoundingClientRect().width ?? 0;- const visible = new Set([...pane.querySelectorAll<HTMLElement>('[data-turn-id]')].filter(element => {+ const elements = [...pane.querySelectorAll<HTMLElement>('[data-turn-id]')];+ const indices: number[] = [];+ const visible = new Set(elements.filter((element, index) => {const bounds = element.getBoundingClientRect();- return bounds.right > viewport.left + labelWidth && bounds.left < viewport.right;+ const inside = bounds.right > viewport.left + labelWidth && bounds.left < viewport.right;+ if (inside) indices.push(index);+ return inside;}).map(element => element.dataset.turnId));+ if (indices.length) {+ const from = indices[0], to = indices[indices.length - 1] + 1;+ setViewport(previous => previous.from === from && previous.to === to ? previous : { from, to });+ }setUnseen(previous => { const next = previous.filter(id => !visible.has(id)); return next.length === previous.length ? previous : next; });}, []);- // Follow until a turn is selected; otherwise retain the reading position and acknowledge visible arrivals.- useEffect(() => {+ // Set the initial position before interaction; later arrivals retain an explicitly selected turn.+ useLayoutEffect(() => {if (!displayed || !scroller.current) return;if (!selected) { scroller.current.scrollLeft = scroller.current.scrollWidth; setUnseen([]); }- else markVisible();+ markVisible();}, [turns.length, selected, displayed, markVisible]);useEffect(() => {if (!displayed || !scroller.current) return;const observer = new ResizeObserver(markVisible); observer.observe(scroller.current);return () => observer.disconnect();- }, [displayed, markVisible]);+ }, [displayed, markVisible, turns.length > 0]);useEffect(() => setAllRequests(false), [selected]);const selectedTurn = turns.find(t => t.turn_id === selected) ?? turns[turns.length - 1];+ const overviewTabStop = turns.some(turn => turn.turn_id === overviewFocus) ? overviewFocus : selectedTurn?.turn_id;const index = (turn: TimelineTurn) => turns.indexOf(turn) + 1;const boundary = (turn: TimelineTurn) => turn.boundary === 'new_user_message' ? text('新消息', 'New message') : turn.boundary === 'context_rebuilt' ? text('上下文重建', 'Context rebuilt') : text('边界未确认', 'Boundary unknown');const laneName = (lane: Lane) => lane === 'primary' ? text('主力', 'Primary') : lane === 'regular' ? text('常规', 'Regular') : text('分组未记录', 'Group unknown');@@ -157,6 +173,47 @@ export function RoutingTimeline({ session, language, active, displayed, refreshV}const last = turns[turns.length - 1];const running = last?.status === 'running';+ const protectionLabel = (turn: TimelineTurn) => {+ switch (turn.selection?.historical_protection?.outcome) {+ case 'applied': return text('低分保护', 'Low-score protection');+ case 'suppressed': return text('已解除保护', 'Protection released');+ case 'retained_unavailable': return text('判断不可用,保留保护', 'Judgment unavailable; protection retained');+ case 'not_needed': return text('无需低分保护', 'Protection not needed');+ case 'not_considered': return text('未进入保护判断', 'Protection not considered');+ default: return '';+ }+ };+ function selectTurn(turn: TimelineTurn, navigate = false) {+ setSelected(turn.turn_id);+ if (turn.requests[0]) onSelectRequest(turn.requests[0]);+ if (!navigate || !scroller.current) return;+ const pane = scroller.current;+ const element = [...pane.querySelectorAll<HTMLElement>('[data-turn-id]')].find(node => node.dataset.turnId === turn.turn_id);+ if (!element) return;+ const bounds = element.getBoundingClientRect(), outer = pane.getBoundingClientRect();+ const labels = pane.querySelector('.routing-lane-label')?.getBoundingClientRect().width ?? 0;+ const left = pane.scrollLeft + bounds.left - outer.left - labels - (pane.clientWidth - labels - bounds.width) / 2;+ pane.scrollTo({ left, behavior: matchMedia('(prefers-reduced-motion: reduce)').matches ? 'auto' : 'smooth' });+ }++ function historicalExplanation(turn: TimelineTurn) {+ const history = turn.selection?.historical_protection;+ if (!history) return <><p>{explanation(turn)}</p><p className="muted">{text('历史保护结果未记录。', 'Historical protection result was not recorded.')}</p></>;+ const p = turn.selection?.simple_probability, threshold = turn.selection?.simple_threshold_millis;+ const simple = p != null && threshold != null ? p * 1000 >= threshold : null;+ const task = simple == null ? text('难度判断不可用', 'Difficulty judgment unavailable') : simple ? text('简单', 'Simple') : text('复杂', 'Complex');+ const a = history.applicability_probability;+ const applicability = history.outcome === 'applied' ? text('之前的问题仍相关', 'The earlier problem still matters')+ : history.outcome === 'suppressed' ? text('之前的问题已修正或不再相关', 'The earlier problem was fixed or no longer matters')+ : history.outcome === 'retained_unavailable' ? text('无法判断之前的问题,保留保护', 'Earlier problem judgment unavailable; protection retained')+ : history.outcome === 'not_needed' ? text('无需历史低分保护', 'Historical protection not needed') : text('未进入历史低分保护判断', 'Historical protection was not considered');+ return <div className="routing-judgments">+ <p>{text('当前工作:', 'Current task: ')}{task}{p != null && <> ({p.toFixed(2)}{threshold != null && <> {simple ? '≥' : '<'} {fixed(threshold)}</>})</>}</p>+ <p>{text('上一阶段:', 'Previous stage: ')}{history.previous_score == null ? text('评分未记录', 'Score not recorded') : history.previous_score.toFixed(2)} · {text('胜任下限 ', 'Competence floor ')}{fixed(history.competence_floor_millis)}</p>+ <p>{history.outcome === 'not_needed' && a != null ? <>{text('之前的问题相关概率 ', 'Earlier problem relevance ')}{a.toFixed(2)} · {applicability}</> : <>{applicability}{a != null && <> ({a.toFixed(2)})</>}</>}</p>+ <strong>→ {laneName(laneOf(turn))} · {modelOf(turn) ?? text('模型未记录', 'Model unknown')}</strong>+ </div>;+ }function explanation(turn: TimelineTurn) {const target = `${laneName(laneOf(turn))} · ${modelOf(turn) ?? text('模型未记录', 'model unknown')}`;@@ -201,7 +258,7 @@ export function RoutingTimeline({ session, language, active, displayed, refreshV: selectedTurn.boundary === 'context_rebuilt' ? text('上下文中的消息步骤比上一份可比较记录少,按压缩归因;已重新判断。回退或共享会话的后台、子代理请求也可能满足此条件。', 'The context has fewer message steps than the prior comparable checkpoint, so this is attributed to compaction and judged again. Rewinds or background and subagent requests sharing a session can also meet this condition.'): text('没有足够记录确认这一轮的起因。', 'The retained records do not establish what started this turn.')}</p>{selectedTurn.requests[0] && <blockquote className="routing-quote"><ContentExcerpt request={selectedTurn.requests[0].request_id} language={language} fallback={text('这一轮的消息未记录或已清理', 'This turn’s message is unrecorded or cleared')} limit={140} revision={selectedTurn.content_digest} /></blockquote>}- <div className="routing-detail-block"><span>{text('阶段开始时的模型选择', 'Model selection at the start of this stage')}</span><p>{explanation(selectedTurn)}</p></div>+ <div className="routing-detail-block"><span>{text('阶段开始时的模型选择', 'Model selection at the start of this stage')}</span>{historicalExplanation(selectedTurn)}</div><div className="routing-detail-block"><span>{text('胜任评分', 'Competence score')}</span><div><span className={`routing-score ${scoreTone(selectedTurn)}`}>{score(selectedTurn)}</span></div><p>{scoreExplanation(selectedTurn)}</p></div><p className="routing-detail-facts">{[status(selectedTurn),@@ -236,6 +293,33 @@ export function RoutingTimeline({ session, language, active, displayed, refreshV<div className="routing-tile"><span>{text('Agent 轮次', 'Agent turns')}</span><strong>{turns.length}</strong><small>{text(`${turns.reduce((n, turn) => n + turn.requests.length, 0)} 个请求`, `${turns.reduce((n, turn) => n + turn.requests.length, 0)} requests`)}</small></div></div>}{turns.length > 0 && <div className="routing-lanes-card">+ <div className="routing-overview">+ <div className="routing-overview-head"><strong>{text(`${turns.length} 轮总览`, `${turns.length} turns at a glance`)}</strong><span>{text('● 低分 / 失败 · ◆ 保护 · ✓ 解除', '● Low score / failure · ◆ Protected · ✓ Released')}</span></div>+ <svg className="routing-overview-track" role="group" aria-label={text('轮次总览,选择以定位', 'Turn overview; select to navigate')}>+ {turns.map((turn, i) => {+ const outcome = turn.selection?.historical_protection?.outcome;+ const protectedTurn = outcome === 'applied' || outcome === 'retained_unavailable' || turn.selection?.selection_reason === 'low_competence';+ const problem = below(turn) || turn.status === 'failed' || turn.requests.some(failed);+ const label = [`T${i + 1}`, laneName(laneOf(turn)), problem ? text('低分或失败', 'Low score or failure') : '', protectionLabel(turn)].filter(Boolean).join(' · ');+ return <g key={turn.turn_id} className={`routing-overview-turn ${tone(laneOf(turn))}`} role="button" tabIndex={overviewTabStop === turn.turn_id ? 0 : -1} aria-label={label} aria-pressed={selectedTurn?.turn_id === turn.turn_id} data-overview-turn={turn.turn_id} data-protection={outcome} data-problem={problem || undefined} onFocus={() => setOverviewFocus(turn.turn_id)} onClick={() => { setOverviewFocus(turn.turn_id); selectTurn(turn, true); }} onKeyDown={event => {+ const next = event.key === 'Home' ? 0 : event.key === 'End' ? turns.length - 1+ : event.key === 'ArrowRight' || event.key === 'ArrowDown' ? (i + 1) % turns.length+ : event.key === 'ArrowLeft' || event.key === 'ArrowUp' ? (i + turns.length - 1) % turns.length : null;+ if (next !== null) {+ event.preventDefault();+ event.currentTarget.parentElement?.querySelectorAll<SVGGElement>('.routing-overview-turn')[next]?.focus();+ }+ if (event.key === 'Enter' || event.key === ' ') { event.preventDefault(); selectTurn(turn, true); }+ }}>+ <title>{label}</title>+ <rect className="routing-overview-mark" x={`${i * 100 / turns.length}%`} y="10" width={`${100 / turns.length}%`} height="16" rx="3" />+ {problem && <circle className="routing-overview-problem" cx={`${(i + .5) * 100 / turns.length}%`} cy="5" r="2.5" />}+ {(protectedTurn || outcome === 'suppressed') && <text className={`routing-overview-outcome${outcome === 'suppressed' ? ' released' : ''}`} x={`${(i + .5) * 100 / turns.length}%`} y="35" textAnchor="middle">{outcome === 'suppressed' ? '✓' : '◆'}</text>}+ </g>;+ })}+ <rect className="routing-overview-window" x={`${Math.min(viewport.from, turns.length - 1) * 100 / turns.length}%`} y="8" width={`${Math.max(1, Math.min(viewport.to, turns.length) - Math.min(viewport.from, turns.length - 1)) * 100 / turns.length}%`} height="20" rx="4" />+ </svg>+ </div>{selected && unseen.length > 0 && <div className="routing-lanes-notice" role="status"><button type="button" className="btn routing-new-turns" onClick={() => {scroller.current?.scrollTo({ left: scroller.current.scrollWidth, behavior: matchMedia('(prefers-reduced-motion: reduce)').matches ? 'auto' : 'smooth' });setUnseen([]);@@ -247,10 +331,11 @@ export function RoutingTimeline({ session, language, active, displayed, refreshV{/* One column per agent turn; the grid flows by column, so focus and reading order follow time. */}{turns.map(turn => <Fragment key={turn.turn_id}><div className="routing-turn-head" title={new Date(turn.started_at_ms).toLocaleString(language === 'zh' ? 'zh-CN' : 'en')}><strong>T{index(turn)}</strong>{turn.boundary !== 'unknown' && <span className="badge no-dot">{boundary(turn)}</span>}</div>- {lanes.map(lane => <div className={`routing-lane-cell${laneOf(turn) !== lane ? ' routing-cell-empty' : ''}`} key={lane} aria-hidden={laneOf(turn) !== lane || undefined}>{laneOf(turn) === lane && <button type="button" className={`routing-turn ${tone(lane)}${selectedTurn?.turn_id === turn.turn_id ? ' selected' : ''}`} data-turn-id={turn.turn_id} data-new={arrivals.has(turn.turn_id) || undefined} aria-pressed={selectedTurn?.turn_id === turn.turn_id} onClick={() => { setSelected(turn.turn_id); if (turn.requests[0]) onSelectRequest(turn.requests[0]); }}>+ {lanes.map(lane => <div className={`routing-lane-cell${laneOf(turn) !== lane ? ' routing-cell-empty' : ''}`} key={lane} aria-hidden={laneOf(turn) !== lane || undefined}>{laneOf(turn) === lane && <button type="button" className={`routing-turn ${tone(lane)}${selectedTurn?.turn_id === turn.turn_id ? ' selected' : ''}`} data-turn-id={turn.turn_id} data-new={arrivals.has(turn.turn_id) || undefined} aria-pressed={selectedTurn?.turn_id === turn.turn_id} onClick={() => selectTurn(turn)}><span className="sr-only">{text(`轮次 ${index(turn)}`, `Turn ${index(turn)}`)}</span><strong className="routing-turn-reason">{reason(turn)}</strong><span className="routing-turn-meta">{probability(turn)}</span>+ {['suppressed', 'retained_unavailable'].includes(turn.selection?.historical_protection?.outcome ?? '') && <span className={`badge no-dot routing-protection-badge ${turn.selection?.historical_protection?.outcome === 'suppressed' ? 'good' : 'warn'}`}>{protectionLabel(turn)}</span>}<span className="routing-ticks" aria-label={text(`${turn.requests.length} 个请求`, `${turn.requests.length} requests`)}>{turn.requests.slice(0, TICKS).map(request => <i key={request.request_id} className={failed(request) ? 'failed' : undefined} />)}{turn.requests.length > TICKS && <em>+{turn.requests.length - TICKS}</em>}</span><span className={`routing-score ${scoreTone(turn)}`}>{score(turn)}</span>{(turn.selection?.competence_trigger || turn.protected_turn_ids.length > 0 || turn.evidence_partial || turn.relays.length > 0) && <span className="routing-turn-flags">diff --git a/apps/desktop/src/features/plan-quality-window.ts b/apps/desktop/src/features/plan-quality-window.tsnew file mode 100644index 00000000..0a199766--- /dev/null+++ b/apps/desktop/src/features/plan-quality-window.ts@@ -0,0 +1,13 @@+export type QualityPeriod = 'all' | 'seven_days' | 'one_day';++const DAY_MS = 86_400_000;+const RETENTION_MS = 7 * DAY_MS;+// Both bounded reads must finish before their shared lower bound ages out.+const READ_MARGIN_MS = 60_000;++export function planQualityWindow(period: QualityPeriod, now: number) {+ return {+ from: Math.max(0, now - (period === 'one_day' ? DAY_MS : RETENTION_MS - READ_MARGIN_MS)),+ to: now + 1,+ };+}diff --git a/apps/desktop/src/features/routing-timeline.css b/apps/desktop/src/features/routing-timeline.cssindex 131875c2..13483fbc 100644--- a/apps/desktop/src/features/routing-timeline.css+++ b/apps/desktop/src/features/routing-timeline.css@@ -11,6 +11,23 @@.routing-tile > strong.purple { color: var(--purple); }.routing-tile > small { color: var(--text-muted); font-size: calc(12px * var(--hr-text-scale)); }.routing-lanes-card { display: grid; gap: 10px; min-width: 0; padding: 16px 16px 12px; border: 1px solid var(--border); border-radius: var(--radius-md); background: var(--panel-solid); }+.routing-overview { min-width: 0; padding-bottom: 8px; border-bottom: 1px solid var(--border); }+.routing-overview-head { display: flex; flex-wrap: wrap; align-items: baseline; justify-content: space-between; gap: 4px 12px; color: var(--text-muted); font-size: calc(11px * var(--hr-text-scale)); }+.routing-overview-head strong { color: var(--text-soft); font-size: calc(12px * var(--hr-text-scale)); font-weight: 550; }+.routing-overview-track { display: block; width: 100%; height: 38px; overflow: visible; }+.routing-overview-turn { color: var(--text-faint); cursor: pointer; outline: none; }+.routing-overview-turn.cyan { color: var(--cyan); }+.routing-overview-turn.purple { color: var(--purple); }+.routing-overview-mark { fill: currentColor; stroke: var(--panel-solid); stroke-width: 2; }+.routing-overview-turn[aria-pressed=true] .routing-overview-mark, .routing-overview-turn:hover .routing-overview-mark, .routing-overview-turn:focus-visible .routing-overview-mark { stroke: var(--accent-bright); }+.routing-overview-turn:focus-visible .routing-overview-mark { stroke-width: 3; }+.routing-overview-problem { fill: var(--red); }+.routing-overview-outcome { fill: var(--purple); font-size: 10px; }+.routing-overview-outcome.released { fill: var(--green); }+.routing-overview-window { fill: color-mix(in srgb, var(--accent) 10%, transparent); stroke: var(--text-soft); stroke-width: 1.5; pointer-events: none; }+.routing-judgments { display: grid; gap: 4px; }+.routing-judgments > strong { color: var(--text); font-size: calc(13px * var(--hr-text-scale)); font-weight: 600; }+.routing-protection-badge { justify-self: start; max-width: 100%; white-space: normal; }.routing-lanes-scroll { min-width: 0; overflow-x: auto; padding: 2px 2px 4px; }.routing-lanes { display: grid; width: max-content; min-width: 100%; grid-auto-flow: column; grid-template-columns: var(--routing-label-width); grid-auto-columns: clamp(var(--routing-cell-width), 18vw, 232px); grid-template-rows: auto; gap: 10px; align-items: stretch; }.routing-lanes[data-lanes='1'] { grid-template-rows: repeat(2, auto); }diff --git a/apps/desktop/src/features/trust/protection-evidence.ts b/apps/desktop/src/features/trust/protection-evidence.tsnew file mode 100644index 00000000..138e6c7f--- /dev/null+++ b/apps/desktop/src/features/trust/protection-evidence.ts@@ -0,0 +1,26 @@+import type { RoutingSummary } from '../RoutingObservations';+import type { TrustReport } from './types';++export type ReleasedProtectionEvidence = { kind: 'available'; count: number } | {+ kind: 'unavailable'; reason: 'missing' | 'partial' | 'plan' | 'revision' | 'time' | 'branch';+};++/** Decisions and scored stages are separate populations, even when their scope agrees. */+export function releasedProtectionEvidence(report: TrustReport, summary: RoutingSummary | null): ReleasedProtectionEvidence {+ const unavailable = (reason: Extract<ReleasedProtectionEvidence, { kind: 'unavailable' }>['reason']): ReleasedProtectionEvidence => ({ kind: 'unavailable', reason });+ if (!summary) return unavailable('missing');+ if (summary.coverage !== 'complete' || summary.scan_limited) return unavailable('partial');+ if (summary.plan_id !== report.plan_id || summary.session_id !== null) return unavailable('plan');+ const revision = report.revision === 'active' ? report.active_revision : report.revision === 'all' ? null : report.revision;+ if (summary.plan_revision !== revision) return unavailable('revision');+ if (summary.covered_from_ms !== report.from_ms || summary.covered_to_ms !== report.to_ms) return unavailable('time');+ if (!summary.cohorts.length) return unavailable('missing');+ const branches = new Set(report.branches.map(branch => branch.branch_id));+ if (summary.cohorts.some(({ cohort }) => !branches.has(cohort.scope_id))) return unavailable('branch');+ let count = 0;+ for (const { counts } of summary.cohorts) {+ if (!Number.isSafeInteger(counts.suppressed) || counts.suppressed < 0) return unavailable('partial');+ count += counts.suppressed;+ }+ return Number.isSafeInteger(count) ? { kind: 'available', count } : unavailable('partial');+}diff --git a/apps/desktop/src/features/trust/trust.css b/apps/desktop/src/features/trust/trust.cssindex 753bc7a4..086596c5 100644--- a/apps/desktop/src/features/trust/trust.css+++ b/apps/desktop/src/features/trust/trust.css@@ -1,4 +1,7 @@.trust-control { display: grid; gap: 12px; min-width: 0; padding: 20px 22px; border: 1px solid var(--border); border-radius: var(--radius-md); background: var(--panel); }+.trust-release { margin: 14px 0; padding: 12px 14px; border: 1px solid var(--border); border-radius: var(--radius-sm); background: color-mix(in srgb, var(--cyan) 5%, var(--panel)); overflow-wrap: anywhere; }+.trust-release > strong { color: var(--text); }+.trust-release > p { margin: 6px 0 0; }.trust-control-head { display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 8px 12px; }.trust-control-head h3 { margin: 0; font-size: calc(16px * var(--hr-text-scale)); font-weight: 650; }.trust-control-help, .trust-control-evidence { margin: 0; color: var(--text-muted); font-size: calc(12px * var(--hr-text-scale)); line-height: 1.6; overflow-wrap: anywhere; }diff --git a/apps/desktop/tests/README.md b/apps/desktop/tests/README.mdindex 61674afe..6a31d38b 100644--- a/apps/desktop/tests/README.md+++ b/apps/desktop/tests/README.md@@ -61,6 +61,16 @@ proves native authorization, persistence, process cleanup or real model calls.| Change model grouping or inspect page controls | `desktop.models.view-switch`, `desktop.presentation.control-layout`; [presentation scenarios](v3/browser/presentation-interactions.mjs) | Production styles preserve model/connection counts, selected model and visible selection. Chinese/English and light/dark checks reject browser-default buttons and horizontal overflow from long recent-session titles at the supported small window. || Try a new model, judge its evidence and follow live routing | `timeline.initial-failure-retry-recovers.*`, `timeline.polls-only-while-displayed-and-visible`, `trust.scoring-states.both-groupings.*`, `quickstart.*.inline-connection-guard.model-change-and-back` in [trial scenarios](v3/visual/new-model-trial-active.mjs) | A failed timeline read keeps its tab, error and Retry until recovery, while only a confirmed empty read hides the tab; polling continues only while the timeline is shown and the window is visible, after one availability probe. Per-model and per-executor groupings both show scoring coverage and complete/partial/awaiting/unscored counts. Changing models, going back or leaving the quick start asks before discarding the inline connection form; Cancel keeps the model and input. `HIROUTE_BROWSER_TRANSPORT=console` runs the same scenarios over the console host. Real feed retrieval, saved trials and live sessions require native acceptance. |+The [historical protection and overview scenarios](v3/visual/new-model-trial-protection-active.mjs)+run with `node tests/v3/visual/new-model-trial.mjs <evidence-directory> --protection`.+They verify scope-matched release counts and explicit unavailable reasons, a selectable+24-hour interval inside independently clipped retention boundaries, the opening+selection's historical-protection outcome/previous score, and forty-turn overview+navigation, viewport tracking, keyboard access and live append. Use the same+`HIROUTE_BROWSER_TRANSPORT=console` switch for the console host. These remain+production-component scenarios with synthetic data; real protection/release+records and native acceptance need their own evidence. Run browser suites serially.+The [trial interaction refinements](v3/visual/new-model-trial-polish-active.mjs)run with `node tests/v3/visual/new-model-trial.mjs <evidence-directory> --polish`.They cover cached trust-level replay, precise-value debounce, shared reason labels,diff --git a/apps/desktop/tests/plan-quality-window.test.mjs b/apps/desktop/tests/plan-quality-window.test.mjsnew file mode 100644index 00000000..f74b1a73--- /dev/null+++ b/apps/desktop/tests/plan-quality-window.test.mjs@@ -0,0 +1,29 @@+import test from 'node:test';+import assert from 'node:assert/strict';+import { planQualityWindow } from '../src/features/plan-quality-window.ts';+import { releasedProtectionEvidence } from '../src/features/trust/protection-evidence.ts';++const DAY = 86_400_000;+for (const period of ['seven_days', 'all', 'one_day']) {+ test(`${period} keeps independently timed reads in the same retained interval`, () => {+ const now = 20 * DAY;+ const scope = planQualityWindow(period, now);+ const effectiveFrom = queryNow => Math.max(scope.from, queryNow - 7 * DAY + 1);+ const report = { plan_id: 'trial', revision: 'active', active_revision: 8, from_ms: effectiveFrom(now + 10), to_ms: scope.to, branches: [{ branch_id: 'coding' }] };+ const summary = { plan_id: 'trial', session_id: null, plan_revision: 8, covered_from_ms: effectiveFrom(now + 500), covered_to_ms: scope.to, coverage: 'complete', scan_limited: false, cohorts: [{ cohort: { scope_id: 'coding' }, counts: { suppressed: 5 } }] };+ assert.deepEqual(releasedProtectionEvidence(report, summary), { kind: 'available', count: 5 });+ assert.equal(scope.to, now + 1);+ if (period === 'one_day') assert.equal(scope.from, now - DAY);+ else assert.equal(scope.from, now - 7 * DAY + 60_000);+ assert.equal(releasedProtectionEvidence(report, { ...summary, covered_from_ms: report.from_ms + 1 }).kind, 'unavailable');+ });+}++test('a window captured beyond its read margin still fails closed after retention moves', () => {+ const now = 20 * DAY;+ const scope = planQualityWindow('all', now);+ const report = { plan_id: 'trial', revision: 'active', active_revision: 8, from_ms: scope.from, to_ms: scope.to, branches: [{ branch_id: 'coding' }] };+ const summary = { plan_id: 'trial', session_id: null, plan_revision: 8, covered_from_ms: now - 7 * DAY + 60_001, covered_to_ms: scope.to, coverage: 'complete', scan_limited: false, cohorts: [{ cohort: { scope_id: 'coding' }, counts: { suppressed: 5 } }] };+ assert.deepEqual(releasedProtectionEvidence(report, summary), { kind: 'unavailable', reason: 'time' });+ assert.equal(planQualityWindow('all', 1000).from, 0);+});diff --git a/apps/desktop/tests/protection-evidence.test.mjs b/apps/desktop/tests/protection-evidence.test.mjsnew file mode 100644index 00000000..2dea01fa--- /dev/null+++ b/apps/desktop/tests/protection-evidence.test.mjs@@ -0,0 +1,32 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { releasedProtectionEvidence } from '../src/features/trust/protection-evidence.ts';++const report = { plan_id: 'trial', revision: 'active', active_revision: 8, from_ms: 100, to_ms: 200, branches: [{ branch_id: 'coding' }] };+const cohort = (scope_id, suppressed) => ({ cohort: { scope_id }, counts: { suppressed } });+const summary = () => ({ plan_id: 'trial', session_id: null, plan_revision: 8, covered_from_ms: 100, covered_to_ms: 200, coverage: 'complete', scan_limited: false, cohorts: [cohort('coding', 2), cohort('coding', 3)] });++test('complete matching decision cohorts retain their separate release count, including zero', () => {+ assert.deepEqual(releasedProtectionEvidence(report, summary()), { kind: 'available', count: 5 });+ assert.deepEqual(releasedProtectionEvidence(report, { ...summary(), cohorts: [cohort('coding', 0)] }), { kind: 'available', count: 0 });+});++test('unknown and partial populations do not become zero', () => {+ for (const value of [null, { ...summary(), cohorts: [] }]) assert.deepEqual(releasedProtectionEvidence(report, value), { kind: 'unavailable', reason: 'missing' });+ for (const value of [{ ...summary(), coverage: 'partial' }, { ...summary(), scan_limited: true }]) assert.deepEqual(releasedProtectionEvidence(report, value), { kind: 'unavailable', reason: 'partial' });+});++test('Plan, session, published revision, time and branch identities must all match', () => {+ for (const [patch, reason] of [+ [{ plan_id: 'other' }, 'plan'], [{ session_id: 'one-session' }, 'plan'],+ [{ plan_revision: 7 }, 'revision'], [{ plan_revision: null }, 'revision'],+ [{ covered_from_ms: 101 }, 'time'], [{ covered_to_ms: 201 }, 'time'],+ [{ cohorts: [cohort('coding', 2), cohort('unrelated', 100)] }, 'branch'],+ ]) assert.deepEqual(releasedProtectionEvidence(report, { ...summary(), ...patch }), { kind: 'unavailable', reason });+});++test('all-revision and explicit historical selections agree only with their corresponding read scope', () => {+ assert.deepEqual(releasedProtectionEvidence({ ...report, revision: 'all' }, { ...summary(), plan_revision: null }), { kind: 'available', count: 5 });+ assert.deepEqual(releasedProtectionEvidence({ ...report, revision: 7 }, { ...summary(), plan_revision: 7 }), { kind: 'available', count: 5 });+ assert.equal(releasedProtectionEvidence({ ...report, revision: 7 }, summary()).kind, 'unavailable');+});diff --git a/apps/desktop/tests/v3/browser/new-model-trial.tsx b/apps/desktop/tests/v3/browser/new-model-trial.tsxindex 16151d06..a7953073 100644--- a/apps/desktop/tests/v3/browser/new-model-trial.tsx+++ b/apps/desktop/tests/v3/browser/new-model-trial.tsx@@ -6,6 +6,7 @@ import { useState } from 'react';import { createRoot } from 'react-dom/client';import { mockIPC } from './host-mock';import { Sessions } from '../../../src/features/Sessions';+import type { TimelineTurn } from '../../../src/features/RoutingTimeline';import { Models } from '../../../src/features/models/Models';import { PlanEditor } from '../../../src/plan-editor';import { PresentationRoot, ProductPage } from '../../../src/ui';@@ -14,6 +15,11 @@ import type { ModelFeedStatus } from '../../../src/features/model-feed/types';import type { TrustReport } from '../../../src/features/trust/types';import '../../../src/occami/styles.css';const params = new URLSearchParams(location.search);+if (params.get('release-evidence') === 'retention') {+ let clock = Date.now();+ Date.now = () => clock;+ Object.assign(window, { advanceRetentionClock: (ms: number) => { clock += ms; } });+}const readCost = ['handoff', 'suggestion-cadence'].includes(params.get('view') ?? '');if (readCost) installReadCostClock();const language = params.get('lang') === 'zh' ? 'zh' : 'en';@@ -61,7 +67,20 @@ const homeSuggestions = [];const timelineRequests = (params.has('polish') ? Array.from({length:Number(params.get('turns')??2)},(_,i)=>i+1) : params.has('stale-timeline') ? [1,2,3] : [1,2]).map(i => ({request_id:`request-${i}`,started_at_ms:Date.now()-10000+i*1000,duration_ms:1500,native_model:i===1?'primary-model':'trial-model',input_tokens:1000,output_tokens:200,cache_read_tokens:990,cache_read_share:0.99,costs:[{model_configuration_id:i===1?'Primary':'Trial',currency:'USD',valuation_kind:'usage_estimate',known_micros:1250,unknown_contributions:i===1?0:1}],outcome:params.get('request-outcome')??'accepted'}));let timelinePolls=0; let busyReturned=false;-const timelineTurn = (i:number,updated=false) => ({turn_id:`request-${i}`,agent_turn_id:`turn-${i}`,segment_id:`stage-${i}`,started_at_ms:timelineRequests[i-1].started_at_ms,finished_at_ms:timelineRequests[i-1].started_at_ms+1500,boundary:i===1?'new_user_message':params.get('boundary')==='rebuilt'?'context_rebuilt':'unknown',plan_id:dailyPlan.agent_plan_id,plan_revision:8,branch_id:'smart_saving',model_configuration_id:i===1?'Primary model with a long readable name':'Trial model',reasoning_profile_id:'high',group:i===1?'primary':'regular',selection:{simple_probability:i===1?0.62:0.94,simple_threshold_millis:900,selection_reason:i===1?'complex_task':'simple_task',competence_trigger:null},tool_continuations:1,relays:[],assessment_state:updated?'scored':'pending',assessment:updated?{score:0.4,partial:false,target_from_ordinal:1,target_through_ordinal:1}:null,competence_floor_millis:500,protected_turn_ids:[],status:'completed',requests:[timelineRequests[i-1]],cost_by_model:timelineRequests[i-1].costs,evidence_partial:false,content_digest:`digest-${i}-${updated}`});+const timelineTurn = (i:number,updated=false): TimelineTurn => { const turn: TimelineTurn = {turn_id:`request-${i}`,agent_turn_id:`turn-${i}`,segment_id:`stage-${i}`,started_at_ms:timelineRequests[i-1].started_at_ms,finished_at_ms:timelineRequests[i-1].started_at_ms+1500,boundary:i===1?'new_user_message':params.get('boundary')==='rebuilt'?'context_rebuilt':'unknown',plan_id:dailyPlan.agent_plan_id,plan_revision:8,branch_id:'smart_saving',model_configuration_id:i===1?'Primary model with a long readable name':'Trial model',reasoning_profile_id:'high',group:i===1?'primary':'regular',selection:{simple_probability:i===1?0.62:0.94,simple_threshold_millis:900,selection_reason:i===1?'complex_task':'simple_task',competence_trigger:null},tool_continuations:1,relays:[],assessment_state:updated?'scored':'pending',assessment:updated?{score:0.4,partial:false,target_from_ordinal:1,target_through_ordinal:1}:null,competence_floor_millis:500,protected_turn_ids:[],status:'completed',requests:[timelineRequests[i-1]],cost_by_model:timelineRequests[i-1].costs,evidence_partial:false,content_digest:`digest-${i}-${updated}`};+ if(params.has('protection')) {+ const outcome = (['applied','suppressed','retained_unavailable','not_needed','not_considered',null] as const)[(i-1)%6];+ const protectedTurn = outcome==='applied' || outcome==='retained_unavailable';+ turn.group=protectedTurn?'primary':'regular';+ turn.selection!.simple_probability=0.94;+ turn.selection!.selection_reason=protectedTurn?'low_competence':'simple_task';+ turn.selection!.historical_protection=outcome ? {outcome,previous_score:outcome==='not_needed'?0.8:outcome==='not_considered'?null:0.3,competence_floor_millis:500,applicability_probability:outcome==='applied'?0.99:outcome==='suppressed'?0.05:null,applicability_boundary_millis:500} : null;+ turn.requests=[{...turn.requests[0],native_model:protectedTurn?'primary-model':'trial-model',outcome:i%6===0?'failed':'completed'}];+ turn.model_configuration_id=protectedTurn?'Primary model':'Trial model';+ turn.status=i%6===0?'failed':'completed';turn.assessment_state='scored';turn.assessment={score:i%5===0?0.2:0.91,partial:false,target_from_ordinal:i,target_through_ordinal:i};+ }+ return turn;+};let pendingTimelineTurns: number[] = [];Object.assign(window, { appendTrialTurns: (count = 1) => {for (let n=0;n<count;n++) {@@ -93,6 +112,11 @@ mockIPC(async (command, payload: any) => {if (command === 'observation_read' && payload.request.intent.view === 'plan_trust') {const value=structuredClone(report); if(params.has('cost')) value.cost={kind:'available',difference_micros:6000,comparison:{currency:'USD',coverage:'complete',request_count:3,compared_request_count:3,missing_request_count:0,excluded_request_count:0,routed_estimate_micros:18000,reference_estimate_micros:12000,compared_routed_subtotal_micros:18000,compared_reference_subtotal_micros:12000,retention_boundary_partial:false,arithmetic_overflow:false}}; if(params.has('division')) value.branches[0].suggestion={kind:'explore_division'}; if (params.has('empty')) {value.rows=[]; value.branches[0].full_history={executed:0,complete:0,meets_floor:0,partial:0,awaiting_assessment:0,unscored:0,sessions:0};}if(params.has('cost-partial') || params.has('cost-unknown')) {const known=params.has('cost-partial');value.cost={kind:'available',difference_micros:null,comparison:{currency:'USD',coverage:known?'partial':'unknown',request_count:3,compared_request_count:known?1:0,missing_request_count:known?2:3,excluded_request_count:known?2:3,routed_estimate_micros:null,reference_estimate_micros:null,compared_routed_subtotal_micros:known?6000:null,compared_reference_subtotal_micros:known?4000:null,retention_boundary_partial:false,arithmetic_overflow:false}};}+ if(params.has('release-evidence')) {+ const q=payload.request.intent.query;+ value.from_ms=params.get('release-evidence')==='retention'?Math.max(q.from_ms??0,Date.now()-7*86_400_000+10):q.from_ms??0;+ value.to_ms=q.to_ms;value.revision=q.revision;+ }if (payload.request.intent.query.group_by === 'executor') value.rows.forEach(row => row.executor='deepseek_harness');return value;}@@ -107,7 +131,7 @@ mockIPC(async (command, payload: any) => {if(params.has('polish')) {const indices=query.after_watermark==null?timelineRequests.map((_,i)=>i+1):pendingTimelineTurns;const turns=indices.map(i=>timelineTurn(i));pendingTimelineTurns=[];- if(params.has('reason') && turns[0]) turns[0].selection.selection_reason=params.get('reason')!;+ if(params.has('reason') && turns[0]) turns[0].selection!.selection_reason=params.get('reason')!;return {turns,watermark:`watermark-${timelinePolls}`,complete:true};}if(params.has('stale-timeline') && query.after_watermark==='watermark-1') throw {message_key:'application.error.change_preview_stale'};@@ -122,6 +146,13 @@ mockIPC(async (command, payload: any) => {if(view==='facts') return {facts:[],projection_partial:false,next_cursor:null};}if (command === 'observation_read' && ['timeline','catalog','content'].includes(payload.request.intent.view)) return mockProductInvoke(command,payload,'ready');+ if(command==='observation_read' && payload.request.intent.view==='plan_quality' && params.has('release-evidence')) {+ const q=payload.request.intent.query, state=params.get('release-evidence');+ const counts={c_decisions:10,requested:10,unavailable:0,no_target_omissions:0,partial_target_omissions:0,inherited:0,required_question_missing:0,gate_opportunities:5,suppressed:state==='zero'?0:5,unavailable_per_requested:0,suppressed_per_opportunity:state==='zero'?0:1,suppressed_per_c_decision:state==='zero'?0:0.5};+ const coveredFrom=state==='retention'?Math.max(q.from_ms??0,Date.now()-7*86_400_000+20):(q.from_ms??0)+(state==='time'?1:0);+ const routing={plan_id:state==='plan'?'other-plan':q.plan_id,session_id:null,plan_revision:state==='revision'?99:q.plan_revision,requested_from_ms:q.from_ms??null,requested_to_ms:q.to_ms,covered_from_ms:coveredFrom,covered_to_ms:q.to_ms,coverage:state==='partial'?'partial':'complete',retained_decisions:10,known_non_c_decisions:0,legacy_or_unknown_decisions:0,unknown_scope_decisions:0,missing_projection_events:0,scan_limited:false,cohorts:state==='empty'?[]:[{cohort:{protocol:'fixture',content_digest:'fixture',bundle_digest:'fixture',scope_id:state==='branch'?'another-branch':'smart_saving',standard:'default',provider:'Fixture service',model:'Judgment model',simple_threshold_millis:720,competence_floor_millis:500},counts}]};+ return {samples:q.cursor?qualitySamples.map(s=>({...s,segment_id:s.segment_id+'-next'})):qualitySamples,summary:{models:qualityModels,scored_stage_count:58,unrated_stage_count:19,session_count:9,available_revisions:[8]},routing_observations:state==='missing'?undefined:routing,next_cursor:state==='retention' && q.execution && !q.cursor?'retained-next':null};+ }if (command === 'observation_read' && payload.request.intent.query.execution && !params.has('empty')) {const {execution,competence}=payload.request.intent.query;const pick=competence==='below_floor'?qualitySamples.filter(s=>s.assessment.score<0.6):competence==='meets_floor'?qualitySamples.filter(s=>s.assessment.score>=0.6):qualitySamples;diff --git a/apps/desktop/tests/v3/visual/new-model-trial-active.mjs b/apps/desktop/tests/v3/visual/new-model-trial-active.mjsindex 80f4de14..1f535b63 100644--- a/apps/desktop/tests/v3/visual/new-model-trial-active.mjs+++ b/apps/desktop/tests/v3/visual/new-model-trial-active.mjs@@ -6,6 +6,11 @@ const [port,base,output]=process.argv.slice(2);const client=await connectPage(Number(port));const keepAlive=setInterval(()=>{},1000);const results=[];+await client.send('Page.addScriptToEvaluateOnNewDocument', { source: `+ window.fixtureBrowserErrors = [];+ addEventListener('error', event => window.fixtureBrowserErrors.push({ message: event.message, file: event.filename, line: event.lineno }), true);+ addEventListener('unhandledrejection', event => window.fixtureBrowserErrors.push({ rejection: String(event.reason) }));+` });const click=async(selector,text)=>{ const deadline=Date.now()+5000; for(;;){ const result=await evaluate(client,`(()=>{const el=[...document.querySelectorAll(${JSON.stringify(selector)})].find(e=>e.getClientRects().length && !e.matches(':disabled') && e.textContent.includes(${JSON.stringify(text)}));if(!el)return JSON.stringify([...document.querySelectorAll(${JSON.stringify(selector)})].map(e=>[e.textContent.trim().slice(0,40),e.getClientRects().length,e.matches(':disabled')]));el.click();return true;})()`); if(result===true)return; if(Date.now()>deadline)throw Error(`Missing control ${selector} "${text}": ${result}`); await new Promise(resolve=>setTimeout(resolve,50)); } };const shot=async name=>{await evaluate(client,`Promise.all(document.getAnimations().filter(a=>a.effect?.getComputedTiming().iterations!==Infinity).map(a=>a.finished.catch(()=>{}))).then(()=>true)`);const value=await client.send('Page.captureScreenshot',{format:'png'});await writeFile(path.join(output,`${name}.png`),Buffer.from(value.data,'base64'));};const hostTransport=process.env.HIROUTE_BROWSER_TRANSPORT??'tauri';@@ -361,4 +366,11 @@ try {results.push({id:`quickstart.${lang}.inline-connection-guard.model-change-and-back`,status:'passed'});}await writeFile(path.join(output,'report.json'),JSON.stringify({proof:'production components with synthetic IPC; no native or provider claim',results},null,2));console.log(JSON.stringify({passed:results.length,output}));-} catch(error) {await shot('failure');const details=await evaluate(client,`({text:document.body.innerText,trace:window.trialTrace??[]})`).catch(()=>null);await writeFile(path.join(output,'failure.json'),JSON.stringify({error:String(error.stack??error),details,results},null,2));throw error;} finally {clearInterval(keepAlive);client.close();}+} catch(error) {+ const failure={error:String(error.stack??error),results};+ try { failure.page=await evaluate(client,`({url:location.href,text:document.body?.innerText??'',trace:window.trialTrace??null,errors:window.fixtureBrowserErrors??[],resources:performance.getEntriesByType('resource').map(e=>({name:e.name,status:e.responseStatus,duration:e.duration}))})`); }+ catch(captureError) {failure.pageCaptureError=String(captureError);}+ try {await shot('failure');} catch(captureError) {failure.screenshotError=String(captureError);}+ await writeFile(path.join(output,'failure.json'),JSON.stringify(failure,null,2));+ throw error;+} finally {clearInterval(keepAlive);client.close();}diff --git a/apps/desktop/tests/v3/visual/new-model-trial-protection-active.mjs b/apps/desktop/tests/v3/visual/new-model-trial-protection-active.mjsnew file mode 100644index 00000000..59937cd9--- /dev/null+++ b/apps/desktop/tests/v3/visual/new-model-trial-protection-active.mjs@@ -0,0 +1,179 @@+import assert from 'node:assert/strict';+import { writeFile } from 'node:fs/promises';+import path from 'node:path';+import { connectPage, evaluate, waitFor } from './cdp-client.mjs';++const [port, base, output] = process.argv.slice(2);+const client = await connectPage(Number(port));+const results = [];+const transport = process.env.HIROUTE_BROWSER_TRANSPORT ?? 'tauri';+const shot = async (name, settle = true) => {+ if (settle) await evaluate(client, `Promise.all(document.getAnimations().filter(a=>a.effect?.getComputedTiming().iterations!==Infinity).map(a=>a.finished.catch(()=>{}))).then(()=>true)`);+ const value = await client.send('Page.captureScreenshot', { format: 'png' });+ await writeFile(path.join(output, `${name}.png`), Buffer.from(value.data, 'base64'));+};+async function open(query, width, height, theme, lang) {+ const url = `${base}new-model-trial.html?polish=1&lang=${lang}&theme=${theme}&${query}${transport === 'console' ? '&transport=console' : ''}`;+ await client.send('Page.enable');+ await client.send('Runtime.enable');+ await client.send('Emulation.setDeviceMetricsOverride', { width, height, deviceScaleFactor: 1, mobile: false });+ await client.send('Page.navigate', { url });+ await waitFor(client, `location.href===${JSON.stringify(url)} && !!document.querySelector('.plan-editor,.new-models,.sessions-page')`);+ await evaluate(client, 'document.fonts.ready.then(()=>true)');+ if (transport === 'console') assert.equal(await evaluate(client, 'window.fixtureTransport'), 'console');+ if (width === 755 && query.startsWith('view=timeline')) {+ await click('.toolbar-actions button', lang === 'zh' ? '紧凑视图' : 'Compact view');+ await waitFor(client, `document.querySelector('.sessions-page').classList.contains('is-compact')`);+ }+}+async function click(selector, text) {+ const expression = `(()=>{const el=[...document.querySelectorAll(${JSON.stringify(selector)})].find(e=>e.getClientRects().length&&!e.matches(':disabled')&&e.textContent.includes(${JSON.stringify(text)}));if(!el)return false;el.click();return true;})()`;+ await waitFor(client, expression);+}+async function check(id, run) {+ if (process.env.PROTECTION_CASE && !id.startsWith(process.env.PROTECTION_CASE)) return;+ try { await run(); results.push({ id, status: 'passed' }); }+ catch (error) {+ await shot(`failure-${id}`);+ const geometry = await evaluate(client, `({width:innerWidth,document:document.documentElement.scrollWidth,lanes:[...document.querySelectorAll('.routing-lanes-scroll')].map(e=>({width:e.clientWidth,scroll:e.scrollWidth,visible:e.getClientRects().length}))})`).catch(() => null);+ await writeFile(path.join(output, `failure-${id}.json`), JSON.stringify({ error: String(error.stack ?? error), geometry }, null, 2));+ results.push({ id, status: 'failed', error: String(error.stack ?? error) });+ await client.send('Emulation.setEmulatedMedia', { features: [] });+ }+}+const matrix = process.env.PROTECTION_BASELINE ? [['en', 'light', process.env.PROTECTION_BASELINE === '755' ? 755 : 1200, process.env.PROTECTION_BASELINE === '755' ? 600 : 813]]+ : ['en', 'zh'].flatMap(lang => ['light', 'dark'].flatMap(theme => [[lang, theme, 1200, 813], [lang, theme, 755, 600]]));+try {+ for (const [lang, theme, width, height] of matrix) {+ const name = `${lang}-${theme}-${width}`;+ const load = query => open(query,width,height,theme,lang);+ const visible = i => `(()=>{const p=document.querySelector('.routing-lanes-scroll'),v=p.getBoundingClientRect(),l=p.querySelector('.routing-lane-label').getBoundingClientRect().width,r=p.querySelector('[data-turn-id="request-${i}"]').getBoundingClientRect();return r.left>=v.left+l-1&&r.right<=v.right+1;})()`;+ const choose = async i => {+ await evaluate(client,`document.querySelector('[data-overview-turn="request-${i}"]').dispatchEvent(new MouseEvent('click',{bubbles:true}));true`);+ await waitFor(client,`document.querySelector('.routing-detail-head > strong')?.textContent==='T${i}'`);+ await waitFor(client,visible(i));+ };+ const fits = `document.documentElement.scrollWidth<=innerWidth+1 && [...document.querySelectorAll('.routing-overview,.routing-turn-detail,.trust-protection')].filter(e=>e.getClientRects().length).every(e=>e.scrollWidth<=e.clientWidth+1)`;+ const range = `(()=>{const p=document.querySelector('.routing-lanes-scroll'),v=p.getBoundingClientRect(),l=p.querySelector('.routing-lane-label').getBoundingClientRect().width,es=[...p.querySelectorAll('[data-turn-id]')],is=es.map((e,i)=>({i,r:e.getBoundingClientRect()})).filter(({r})=>r.right>v.left+l&&r.left<v.right).map(({i})=>i),w=document.querySelector('.routing-overview-window');return is.length&&Math.abs(parseFloat(w.getAttribute('x'))*es.length/100-is[0])<.01&&Math.abs(parseFloat(w.getAttribute('width'))*es.length/100-(is.at(-1)-is[0]+1))<.01;})()`;+ await check(`release-evidence-${name}`,async()=>{+ for(const state of ['valid','zero','partial','empty','missing','plan','revision','time','branch']) {+ await load(`view=editor&release-evidence=${state}`);+ await waitFor(client,`!!document.querySelector('[data-trust-control="smart"]')`);+ await click('[role="tab"]',lang==='zh'?'模型表现':'Model performance');+ const numeric=state==='valid'||state==='zero';+ await waitFor(client,`document.querySelector('.trust-release')?.dataset.releaseState===${JSON.stringify(numeric?'available':'unavailable')}`);+ const value=await evaluate(client,`document.querySelector('.trust-release').textContent`);+ if(numeric) assert.ok(value.includes(lang==='zh'?`解除 ${state==='zero'?0:5} 次`:`${state==='zero'?0:5} protections released`),value);+ else {assert.ok(value.includes('—'),value);assert.ok(!/5 protections|解除 5/.test(value),value);}+ if(!['valid','zero','missing'].includes(state)) await waitFor(client,`!!document.querySelector('.routing-observations')`);+ const reasons={partial:lang==='zh'?'覆盖不完整':'incomplete coverage',plan:lang==='zh'?'路由范围不同':'different route scope',revision:lang==='zh'?'路由版本不同':'different route version',time:lang==='zh'?'时间范围不同':'different time range',branch:lang==='zh'?'分支范围不同':'different branches'};+ if(reasons[state]) await waitFor(client,`document.querySelector('.trust-release').textContent.includes(${JSON.stringify(reasons[state])})`);+ assert.ok(await evaluate(client,fits));+ if(['valid','partial','empty'].includes(state)) {await evaluate(client,`document.querySelector('.trust-protection').scrollIntoView({block:'center'});true`);await shot(`released-${state}-${name}`);}+ }+ });+ await check(`retained-window-${name}`,async()=>{+ await load('view=editor&release-evidence=retention');+ await waitFor(client,`!!document.querySelector('[data-trust-control="smart"]')`);+ await click('[role="tab"]',lang==='zh'?'模型表现':'Model performance');+ for(const period of ['seven_days','all','one_day']) {+ await evaluate(client,`(()=>{const s=document.querySelector('.quality-filters select');s.value=${JSON.stringify(period)};s.dispatchEvent(new Event('change',{bubbles:true}));return true;})()`);+ await waitFor(client,`document.querySelector('.trust-release')?.dataset.releaseState==='available'`);+ assert.equal(await evaluate(client,`document.querySelector('.trust-release').dataset.releaseState`),'available',`${period} must use one retained interval`);+ assert.ok(await evaluate(client,`document.querySelector('.trust-release').textContent.includes(${JSON.stringify(lang==='zh'?'解除 5 次':'5 protections released')})`));+ const scope=await evaluate(client,`(()=>{const xs=window.trialTrace.filter(x=>x.command==='observation_read').map(x=>x.payload.request.intent),t=xs.filter(x=>x.view==='plan_trust').at(-1).query,q=xs.filter(x=>x.view==='plan_quality'&&x.query.include_routing_observations).at(-1).query;return {trust:[t.from_ms,t.to_ms],quality:[q.from_ms,q.to_ms]};})()`);+ assert.deepEqual(scope.trust,scope.quality);+ if(period==='one_day') assert.equal(scope.trust[1]-scope.trust[0],86_400_001);+ else {assert.ok(scope.trust[0]>scope.trust[1]-7*86_400_000+20);assert.ok(scope.trust[1]-scope.trust[0]>6.99*86_400_000);}+ await evaluate(client,`document.querySelector('.trust-protection').scrollIntoView({block:'center'});true`);+ await shot(`retained-window-${period}-${name}`);+ }+ await click('.segmented button',lang==='zh'?'按执行 Agent':'By execution agent');+ await waitFor(client,`!document.querySelector('.trust-release')`);+ await click('.segmented button',lang==='zh'?'按模型':'By model');+ await waitFor(client,`document.querySelector('.trust-release')?.dataset.releaseState==='available'`);+ assert.equal(await evaluate(client,`document.querySelector('.quality-filters select').value`),'one_day');+ assert.ok(await evaluate(client,fits));+ });+ await check(`aged-retained-window-${name}`,async()=>{+ for (const period of ['seven_days','all']) {+ await load('view=editor&release-evidence=retention');+ await waitFor(client,`!!document.querySelector('[data-trust-control="smart"]')`);+ await click('[role="tab"]',lang==='zh'?'模型表现':'Model performance');+ await evaluate(client,`(()=>{const s=document.querySelector('.quality-filters select');s.value=${JSON.stringify(period)};s.dispatchEvent(new Event('change',{bubbles:true}));return true;})()`);+ await waitFor(client,`document.querySelector('.trust-release')?.dataset.releaseState==='available'`);+ const trustCount=await evaluate(client,`trialTrace.filter(x=>x.payload?.request?.intent?.view==='plan_trust').length`);+ await evaluate(client,`window.advanceRetentionClock(120_000);true`);+ await click('.trust-protection button',lang==='zh'?'查看全部低分阶段':'View all low-score stages');+ await waitFor(client,`!!document.querySelector('.quality-more:not(:disabled)')`);+ assert.equal(await evaluate(client,`document.querySelector('.trust-release').dataset.releaseState`),'available','filter preserves paired base summary after retention moves');+ await click('.quality-more',lang==='zh'?'加载更多阶段':'Load more stages');+ await waitFor(client,`!document.querySelector('.quality-more')`);+ assert.ok(await evaluate(client,`document.querySelector('.trust-release').textContent.includes(${JSON.stringify(lang==='zh'?'解除 5 次':'5 protections released')})`),'pagination preserves the paired count');+ assert.equal(await evaluate(client,`trialTrace.filter(x=>x.payload?.request?.intent?.view==='plan_trust').length`),trustCount,'filters do not refresh the aggregate scope');+ await click('.segmented button',lang==='zh'?'按执行 Agent':'By execution agent');+ await waitFor(client,`!!document.querySelector('[data-execution-group="executor"]')`);+ await evaluate(client,`window.advanceRetentionClock(120_000);true`);+ await click('.segmented button',lang==='zh'?'按模型':'By model');+ await waitFor(client,`document.querySelector('.trust-release')?.dataset.releaseState==='available'`);+ const scope=await evaluate(client,`(()=>{const xs=trialTrace.filter(x=>x.command==='observation_read').map(x=>x.payload.request.intent),t=xs.filter(x=>x.view==='plan_trust').at(-1).query,q=xs.filter(x=>x.view==='plan_quality'&&x.query.include_routing_observations).at(-1).query;return {trust:[t.from_ms,t.to_ms],quality:[q.from_ms,q.to_ms],now:Date.now()};})()`);+ assert.deepEqual(scope.trust,scope.quality);+ assert.equal(scope.trust[1],scope.now+1,'group changes capture a fresh interval');+ }+ });+ await check(`history-outcomes-${name}`,async()=>{+ await load('view=timeline&turns=40&protection=1');+ await waitFor(client,`document.querySelectorAll('.routing-turn').length===40`);+ for(const [i,phrase] of [[1,lang==='zh'?'之前的问题仍相关':'earlier problem still matters'],[2,lang==='zh'?'之前的问题已修正或不再相关':'earlier problem was fixed or no longer matters'],[3,lang==='zh'?'无法判断之前的问题,保留保护':'problem judgment unavailable; protection retained'],[4,lang==='zh'?'无需历史低分保护':'Historical protection not needed'],[5,lang==='zh'?'未进入历史低分保护判断':'Historical protection was not considered'],[6,lang==='zh'?'历史保护结果未记录':'Historical protection result was not recorded']]) {+ await choose(i);await waitFor(client,`document.querySelector('.routing-detail-block')?.textContent.includes(${JSON.stringify(phrase)})`);+ if(i<=3) assert.ok(await evaluate(client,`document.querySelector('.routing-judgments').textContent.includes('0.30')&&document.querySelector('.routing-judgments').textContent.includes('0.50')`));+ if(i===1) assert.ok(await evaluate(client,`document.querySelector('.routing-judgments').textContent.includes('0.99')&&!document.querySelector('.routing-judgments').textContent.includes('0.91')`));+ if(i===2) assert.ok(await evaluate(client,`document.querySelector('[data-turn-id="request-2"] .routing-protection-badge').textContent.includes(${JSON.stringify(lang==='zh'?'已解除保护':'Protection released')})&&document.querySelector('.routing-judgments').textContent.includes('0.05')`));+ if(i===3) assert.equal(await evaluate(client,`document.querySelector('.routing-judgments').textContent.includes('0.00')`),false);+ assert.ok(await evaluate(client,fits));+ if(i===1||i===2){await evaluate(client,`document.querySelector('.routing-turn-detail').scrollIntoView({block:'center'});true`);await shot(`outcome-${i===1?'protected':'released'}-${name}`);}+ }+ assert.equal(await evaluate(client,`/q[012]|digest|retained_unavailable|suppressed|system_one/.test(document.querySelector('.routing-timeline').textContent)`),false);+ });+ await check(`overview-navigation-${name}`,async()=>{+ await load('view=timeline&turns=40&protection=1');await waitFor(client,`document.querySelectorAll('.routing-overview-turn').length===40`);+ assert.equal(await evaluate(client,`document.querySelectorAll('.routing-overview-turn[tabindex="0"]').length`),1,'The entire overview has one tab stop');+ assert.equal(await evaluate(client,`document.querySelectorAll('.routing-overview-turn[tabindex="-1"]').length`),39);+ assert.ok(await evaluate(client,`[...document.querySelectorAll('.routing-overview-turn')].every(e=>e.getAttribute('aria-label')?.startsWith('T'))`));+ await evaluate(client,`document.querySelector('.routing-overview-turn[tabindex="0"]').focus();true`);+ const key=async(key,code=key)=>{for(const type of ['keyDown','keyUp'])await client.send('Input.dispatchKeyEvent',{type,key,code});};+ await key('Home');assert.equal(await evaluate(client,`document.activeElement.dataset.overviewTurn`),'request-1');+ await key('ArrowLeft');assert.equal(await evaluate(client,`document.activeElement.dataset.overviewTurn`),'request-40');+ await key('ArrowRight');assert.equal(await evaluate(client,`document.activeElement.dataset.overviewTurn`),'request-1');+ await key('ArrowRight');assert.equal(await evaluate(client,`document.activeElement.dataset.overviewTurn`),'request-2');+ await key(' ','Space');await waitFor(client,`document.querySelector('.routing-detail-head > strong')?.textContent==='T2'`);+ await key('End');assert.equal(await evaluate(client,`document.activeElement.dataset.overviewTurn`),'request-40');+ await key('Tab');assert.ok(await evaluate(client,`!document.activeElement.closest('.routing-overview')`),'Tab leaves the overview');+ assert.equal(await evaluate(client,`document.querySelectorAll('.routing-overview-turn[data-protection=suppressed]').length`),7);+ assert.ok(await evaluate(client,`document.querySelectorAll('.routing-overview-turn[data-problem=true]').length>0`));+ assert.ok(await evaluate(client,`getComputedStyle(document.querySelector('.routing-overview-turn.cyan')).color===getComputedStyle(document.querySelector('.routing-turn.cyan .routing-turn-reason')).color`));+ await choose(1);await waitFor(client,range);const before=await evaluate(client,`document.querySelector('.routing-overview-window').getAttribute('x')`);+ await choose(40);await waitFor(client,range);assert.notEqual(await evaluate(client,`document.querySelector('.routing-overview-window').getAttribute('x')`),before);+ await client.send('Emulation.setEmulatedMedia',{features:[{name:'prefers-reduced-motion',value:'reduce'}]});+ await evaluate(client,`document.querySelector('[data-overview-turn="request-5"]').focus();true`);+ for(const type of ['keyDown','keyUp'])await client.send('Input.dispatchKeyEvent',{type,key:'Enter',code:'Enter'});+ await waitFor(client,`document.querySelector('.routing-detail-head > strong')?.textContent==='T5'`);await waitFor(client,visible(5));await waitFor(client,range);+ await client.send('Emulation.setDeviceMetricsOverride',{width:width===755?1200:755,height:height===600?813:600,deviceScaleFactor:1,mobile:false});await waitFor(client,range);assert.ok(await evaluate(client,fits));+ await client.send('Emulation.setDeviceMetricsOverride',{width,height,deviceScaleFactor:1,mobile:false});await waitFor(client,range);+ await evaluate(client,`document.querySelector('[data-turn-id="request-1"]').focus();true`);+ for(const type of ['keyDown','keyUp'])await client.send('Input.dispatchKeyEvent',{type,key:'Tab',code:'Tab'});+ assert.equal(await evaluate(client,`document.activeElement.dataset.turnId`),'request-2');+ await choose(5);await evaluate(client,'appendTrialTurns(1);true');await waitFor(client,`document.querySelectorAll('.routing-overview-turn').length===41`);+ assert.equal(await evaluate(client,`document.querySelector('.routing-overview-turn[aria-pressed=true]').dataset.overviewTurn`),'request-5');await waitFor(client,range);+ await evaluate(client,`document.querySelector('.routing-overview').scrollIntoView({block:'center'});true`);+ await waitFor(client,`(()=>{const e=document.querySelector('.routing-overview'),r=e.getBoundingClientRect();return r.top>=0&&r.bottom<=innerHeight&&e.contains(document.elementFromPoint(r.left+r.width/2,r.top+r.height/2));})()`);+ await shot(`overview-${name}`);assert.ok(await evaluate(client,fits));+ await client.send('Emulation.setEmulatedMedia',{features:[]});+ });+ }+} finally {+ client.close();+ await writeFile(path.join(output, 'report.json'), JSON.stringify({ proof: 'Production components with synthetic IPC', results }, null, 2));+}+console.log(JSON.stringify({ passed: results.filter(r => r.status === 'passed').length, failed: results.filter(r => r.status !== 'passed').length, output }));+if (!results.length || results.some(result => result.status !== 'passed')) process.exitCode = 1;diff --git a/apps/desktop/tests/v3/visual/new-model-trial.mjs b/apps/desktop/tests/v3/visual/new-model-trial.mjsindex f2130aa6..5ad5fdb0 100644--- a/apps/desktop/tests/v3/visual/new-model-trial.mjs+++ b/apps/desktop/tests/v3/visual/new-model-trial.mjs@@ -1,5 +1,5 @@import { spawn } from 'node:child_process';-import { mkdtemp, mkdir, rm } from 'node:fs/promises';+import { mkdtemp, mkdir, rm, writeFile } from 'node:fs/promises';import net from 'node:net';import os from 'node:os';import path from 'node:path';@@ -57,19 +57,24 @@ const profile = await mkdtemp(path.join(os.tmpdir(), 'hiroute-v3-new-model-trialawait mkdir(outputRoot, { recursive: true });let vite;let chrome;+let viteLog = '';+const captureVite = chunk => { viteLog = (viteLog + chunk.toString()).slice(-65536); };try {vite = spawn(path.join(desktopRoot, 'node_modules/.bin/vite'), ['tests/v3/browser', '--host', '127.0.0.1', '--port', String(httpPort), '--strictPort'], { cwd: desktopRoot, detached: true, stdio: ['ignore', 'pipe', 'pipe'] });+ vite.stdout.on('data', captureVite);+ vite.stderr.on('data', captureVite);await new Promise((resolve, reject) => { vite.once('spawn', resolve); vite.once('error', reject); });await waitFor(`http://127.0.0.1:${httpPort}/`);const chromeExecutable = process.env.CHROME_BIN || (process.platform === 'darwin' ? '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome' : 'google-chrome');chrome = spawn(chromeExecutable, ['--headless=new', '--disable-gpu', `--remote-debugging-port=${cdpPort}`, '--remote-allow-origins=*', `--user-data-dir=${profile}`, '--window-size=1280,900', 'about:blank'], { detached: true, stdio: ['ignore', 'pipe', 'pipe'] });await new Promise((resolve, reject) => { chrome.once('spawn', resolve); chrome.once('error', reject); });await waitFor(`http://127.0.0.1:${cdpPort}/json/version`);- const runner = spawn(process.execPath, [path.join(here, process.argv.includes('--polish') ? 'new-model-trial-polish-active.mjs' : 'new-model-trial-active.mjs'), String(cdpPort), `http://127.0.0.1:${httpPort}/`, outputRoot], { cwd: desktopRoot, stdio: 'inherit' });+ const runner = spawn(process.execPath, [path.join(here, process.argv.includes('--protection') ? 'new-model-trial-protection-active.mjs' : process.argv.includes('--polish') ? 'new-model-trial-polish-active.mjs' : 'new-model-trial-active.mjs'), String(cdpPort), `http://127.0.0.1:${httpPort}/`, outputRoot], { cwd: desktopRoot, stdio: 'inherit' });const outcome = await waitForExit(runner);if (outcome.code !== 0) process.exitCode = outcome.code ?? 1;} finally {await terminate(chrome);await terminate(vite);+ await writeFile(path.join(outputRoot, 'vite.log'), viteLog);await removeProfile(profile);}diff --git a/contracts/cli/contract-set.v1.json b/contracts/cli/contract-set.v1.jsonindex ac6beef5..5ac6443c 100644--- a/contracts/cli/contract-set.v1.json+++ b/contracts/cli/contract-set.v1.json@@ -1,5 +1,5 @@{- "descriptor_digest": "sha256:b18d4b3eaa4e0ec39d26d15a87c35049433aebd5feeb241607231103a9cafe5b",+ "descriptor_digest": "sha256:6442c5e2453d65985ee602d119f10db1467c7671cd770be616ebb2b9b284c39c","files": {"agent-check-request.v1.schema.json": "sha256:fbd9e9b19282a5ed8c3e30b5ae16538bc01318a70e4bb7c7a55e8e0472553feb","agent-launch-descriptor-request.v1.schema.json": "sha256:28f2f9d2d7f9a1618bea0f13383002429bc9e0ff56166cbee86958a245d0fd48",@@ -10,7 +10,7 @@"console-launch-request.v1.schema.json": "sha256:bb201709ef64e99036a97d5879a32a8e4e3a9517010e1041def223e723e7f385","console-token-create.v1.schema.json": "sha256:10cc9b80ed0bec4a5ca80e098cf0ee94710eedd7dfce292cf4a8770a11be78ec","console-token-revoke.v1.schema.json": "sha256:fbec29753f6effd3c854bff57984b3c3932ac5b6f2345e52151e353c15933b36",- "coverage-manifest.v1.json": "sha256:c10c888b84c0c6804c45729f18f8736ee723a1f4e1e9842df5f457b7708f63d9",+ "coverage-manifest.v1.json": "sha256:b7d3228b8de570eea6c816727cc379c9ad577469de302ea8ab9735332415d23b","delegation-cancel-request.v1.schema.json": "sha256:0822c53fc16acfcd618fbef66410939f33f634313389a6df4705f414a468b878","delegation-continue-request.v1.schema.json": "sha256:da2f81607f37d154a0fa698a107b37d4b0e9d5a03693dcbcc41e0b7e65db5b93","delegation-get-request.v1.schema.json": "sha256:85b29839c1c508018ebe40e4b2bb5c1dce7c3a87c27efa30b196b2d1b6658471",@@ -24,7 +24,7 @@"local-control-hello.v2.schema.json": "sha256:32fbce882152a886b79bd139d3b4e459b48d94e0634e56ccb189b2c9971ad772","local-control.v2.schema.json": "sha256:4b654de90cd6e333b3953379e5b2e1c5125f1dcbe307b7c7c73f12bb2032d18c","machine-envelope.v2.schema.json": "sha256:23e019a3d024ae302a44105caff4ec95d3fb409a29f936dea1360e543ae6abd6",- "manifest.v1.json": "sha256:500094d02e7a11951f35764d6dd1f7cb90797934ac8fc7cada04b0c727fba831",+ "manifest.v1.json": "sha256:eafe60bd52aa71ddc75f99fe7cb272486fdfe1fccb5c7f90bfd006db588867a8","model-availability.v1.schema.json": "sha256:5965a0360f17ef815a85eb924b65506f1e5b75471fb8170d234a8178c358b6ef","model-feed-removal-preview.v1.schema.json": "sha256:a78cc643d1f5b7b714209969ec8b4f748b9415da49331c0bf877b3bc94d8e971","model-feed-remove.v1.schema.json": "sha256:49a8fb7e2ba909141937cca4e73828706b0b67ea44622ae553c6da12fa8036cc",@@ -36,9 +36,10 @@"plan-draft-change.v1.schema.json": "sha256:cbf6f1ff62fbf04e659c69342a509bbf2b2acc21b3426c3a8e4e138e26cf58c3","plan-editor.v2.schema.json": "sha256:85084c42de1e8d7be3b84401a47ec5e15406431dfad983cd3b48718e93533fe1","plan-lifecycle-change.v1.schema.json": "sha256:23700c0ea1fbc9834e653c4edc8268e346912270c92be4904f9759426f641562",- "planned-manifest.v1.json": "sha256:64ab06c7ede14e6b15c37d011dceb62a33c4d8b9c5d5bd36d493b39f2c151f6c",+ "planned-manifest.v1.json": "sha256:2cf3bfe6a618a2d867baca680721b63bf02753a2aed94993d964e0f18645b2b8","prepare-discovered-model-connection-request.v1.schema.json": "sha256:4451d8d7d06160f399d683bc3987ac2bd458af09994e4e0d989687667f6af1bd","publication-checkpoint-change.v1.schema.json": "sha256:b130577cdae0f1e5dc9f736b8b6f40f22555b4750b4604fdc76c4b65d5b96aa3",+ "routing-timeline-selection.v1.schema.json": "sha256:6c508d2a463d993da29c325fdc14a63c4ca35444a07584760cd196f28485da70","session-list-query.v1.schema.json": "sha256:1f71a89fc019b59c3499708c0760b694b8cb8532028b56d98702cd3b2721cd44","session-lookup.v1.schema.json": "sha256:0c9e0ea31bdde7f720a9a17e8dc175902a20b3fb92abc21ce4bdae9fc3d97587","setup-apply-request.v1.schema.json": "sha256:b44377ecb53e609574cd2e1d49624d6bc8e148f7b60a99c2ea9db861e0c2cabd",diff --git a/contracts/cli/coverage-manifest.v1.json b/contracts/cli/coverage-manifest.v1.jsonindex e3fce930..46c11bfc 100644--- a/contracts/cli/coverage-manifest.v1.json+++ b/contracts/cli/coverage-manifest.v1.json@@ -1471,7 +1471,7 @@}}],- "descriptor_digest": "sha256:b18d4b3eaa4e0ec39d26d15a87c35049433aebd5feeb241607231103a9cafe5b",+ "descriptor_digest": "sha256:6442c5e2453d65985ee602d119f10db1467c7671cd770be616ebb2b9b284c39c","schema_version": {"major": 1,"minor": 0diff --git a/contracts/cli/manifest.v1.json b/contracts/cli/manifest.v1.jsonindex 77c49905..7b756692 100644--- a/contracts/cli/manifest.v1.json+++ b/contracts/cli/manifest.v1.json@@ -5,7 +5,7 @@},"product_contract_revision": "487a807c8dc25cfb24e8b097882cd3bb9716a009","proposal_map_revision": "ab4da93cc49c6ec56a01e046230411ff1ca82300",- "descriptor_digest": "sha256:b18d4b3eaa4e0ec39d26d15a87c35049433aebd5feeb241607231103a9cafe5b",+ "descriptor_digest": "sha256:6442c5e2453d65985ee602d119f10db1467c7671cd770be616ebb2b9b284c39c","visibility": "release","commands": [{@@ -3204,7 +3204,7 @@],"idempotency": "not_applicable","help": {- "purpose": "Read agent turns with selection, score, requests and costs; --follow streams changed turns.",+ "purpose": "Read agent turns with selection, historical protection, score, requests and costs; --follow streams changed turns.","usage": "hiroute sessions timeline <SESSION_ID> [--follow] [--after-watermark <WATERMARK>] [--limit <1..200>] --output json","arguments_and_options": "JSON input: choose exactly one of --request-stdin or --request-file <PATH>. Both read one bounded UTF-8 JSON request with the same strict typed parser; unknown fields, duplicate members, trailing JSON, repeated/mixed sources and human-option mixtures are rejected before Local Control. A file must be regular; relative paths resolve from the current directory (prefix option-shaped filenames with ./). Existing command byte limits and separate protected-input/capability channels remain unchanged. Required SESSION_ID; optional --after-watermark and --limit 1..200 (default 50). --follow streams one NDJSON change event per new or updated agent turn every two seconds, until interrupted. A watermark is opaque and scoped to this session and page size. No configuration is changed.","effects": "Read-only; no product side effect.",diff --git a/contracts/cli/planned-manifest.v1.json b/contracts/cli/planned-manifest.v1.jsonindex 93d5411f..3a66bc6c 100644--- a/contracts/cli/planned-manifest.v1.json+++ b/contracts/cli/planned-manifest.v1.json@@ -5,7 +5,7 @@},"product_contract_revision": "487a807c8dc25cfb24e8b097882cd3bb9716a009","proposal_map_revision": "ab4da93cc49c6ec56a01e046230411ff1ca82300",- "descriptor_digest": "sha256:b18d4b3eaa4e0ec39d26d15a87c35049433aebd5feeb241607231103a9cafe5b",+ "descriptor_digest": "sha256:6442c5e2453d65985ee602d119f10db1467c7671cd770be616ebb2b9b284c39c","visibility": "planned","commands": [{@@ -4800,7 +4800,7 @@],"idempotency": "not_applicable","help": {- "purpose": "Read agent turns with selection, score, requests and costs; --follow streams changed turns.",+ "purpose": "Read agent turns with selection, historical protection, score, requests and costs; --follow streams changed turns.","usage": "hiroute sessions timeline <SESSION_ID> [--follow] [--after-watermark <WATERMARK>] [--limit <1..200>] --output json","arguments_and_options": "JSON input: choose exactly one of --request-stdin or --request-file <PATH>. Both read one bounded UTF-8 JSON request with the same strict typed parser; unknown fields, duplicate members, trailing JSON, repeated/mixed sources and human-option mixtures are rejected before Local Control. A file must be regular; relative paths resolve from the current directory (prefix option-shaped filenames with ./). Existing command byte limits and separate protected-input/capability channels remain unchanged. Required SESSION_ID; optional --after-watermark and --limit 1..200 (default 50). --follow streams one NDJSON change event per new or updated agent turn every two seconds, until interrupted. A watermark is opaque and scoped to this session and page size. No configuration is changed.","effects": "Read-only; no product side effect.",diff --git a/contracts/cli/routing-timeline-selection.v1.schema.json b/contracts/cli/routing-timeline-selection.v1.schema.jsonnew file mode 100644index 00000000..476af048--- /dev/null+++ b/contracts/cli/routing-timeline-selection.v1.schema.json@@ -0,0 +1,500 @@+{+ "$defs": {+ "ApplicabilityReasonV1": {+ "enum": [+ "no_target",+ "partial_target",+ "pending",+ "dispatch_not_started",+ "answered",+ "invalid_output",+ "timeout",+ "unavailable",+ "rejected_input",+ "authentication_rejected",+ "rate_limited",+ "endpoint_rejected",+ "required_question_missing"+ ],+ "type": "string"+ },+ "ApplicabilityStateV1": {+ "enum": [+ "not_requested",+ "valid",+ "unavailable"+ ],+ "type": "string"+ },+ "BranchExecutionPolicyV1": {+ "additionalProperties": false,+ "properties": {+ "criteria_digest": {+ "description": "Digest of the effective frozen standard, for built-in and custom decisions.",+ "type": [+ "string",+ "null"+ ]+ },+ "floor_millis": {+ "format": "uint16",+ "maximum": 65535,+ "minimum": 0,+ "type": "integer"+ },+ "name": {+ "type": "string"+ }+ },+ "required": [+ "name",+ "floor_millis"+ ],+ "type": "object"+ },+ "ClassifierFallbackReasonV1": {+ "enum": [+ "timeout",+ "unavailable",+ "rejected_input",+ "invalid_output"+ ],+ "type": "string"+ },+ "CompetenceProtectionV1": {+ "additionalProperties": false,+ "properties": {+ "floor_millis": {+ "format": "uint16",+ "maximum": 65535,+ "minimum": 0,+ "type": "integer"+ },+ "from_group": {+ "$ref": "#/$defs/ExecutionGroupV1"+ },+ "score": {+ "type": "number"+ },+ "segment_id": {+ "type": "string"+ }+ },+ "required": [+ "segment_id",+ "score",+ "floor_millis",+ "from_group"+ ],+ "type": "object"+ },+ "ComplexityDecisionSourceV1": {+ "enum": [+ "inherited",+ "external_classifier",+ "user_phrase",+ "builtin_rules",+ "unresolved"+ ],+ "type": "string"+ },+ "ComplexityReasonCodeV1": {+ "enum": [+ "INHERITED_TOOL_CONTINUATION",+ "INHERITED_TASK_ROOT",+ "USER_COMPLEX_PHRASE",+ "DEEP_REASONING",+ "MULTI_FILE_SCOPE",+ "MULTI_CONSTRAINT",+ "IMPLEMENTATION_ACTION",+ "FAILURE_OR_DIFF_STRUCTURE",+ "HUMAN_LENGTH_MEDIUM",+ "HUMAN_LENGTH_LARGE",+ "TASK_CONTEXT_UNRESOLVED",+ "TASK_LANGUAGE_FALLBACK",+ "CLASSIFIER_ASSESSMENT_INVALID"+ ],+ "type": "string"+ },+ "DecisionProtocolV1": {+ "enum": [+ "system_one_legacy",+ "system_one_c",+ "custom_extension_v1",+ "local_rules"+ ],+ "type": "string"+ },+ "ExecutionGroupV1": {+ "enum": [+ "regular",+ "primary"+ ],+ "type": "string"+ },+ "HistoricalProtectionActionV1": {+ "enum": [+ "not_considered",+ "not_needed",+ "applied",+ "suppressed",+ "retained_unavailable"+ ],+ "type": "string"+ },+ "ModelGroupReasonV1": {+ "enum": [+ "simple_task",+ "complex_task",+ "low_competence",+ "degree_unavailable",+ "single_group",+ "decision_fallback",+ "availability_relay",+ "heuristic"+ ],+ "type": "string"+ },+ "ProtectionEligibilityV1": {+ "enum": [+ "invalid_boundary",+ "no_target",+ "partial_target",+ "unrated",+ "different_plan",+ "different_category",+ "different_policy",+ "ambiguous_attribution",+ "single_group",+ "eligible"+ ],+ "type": "string"+ },+ "RoutingObservationV1": {+ "additionalProperties": false,+ "properties": {+ "applicability_boundary_millis": {+ "format": "uint16",+ "maximum": 65535,+ "minimum": 0,+ "type": "integer"+ },+ "applicability_probability": {+ "type": [+ "number",+ "null"+ ]+ },+ "applicability_reason": {+ "$ref": "#/$defs/ApplicabilityReasonV1"+ },+ "applicability_requested": {+ "type": "boolean"+ },+ "applicability_state": {+ "$ref": "#/$defs/ApplicabilityStateV1"+ },+ "bundle_digest": {+ "type": "string"+ },+ "competence_floor_millis": {+ "format": "uint16",+ "maximum": 65535,+ "minimum": 0,+ "type": "integer"+ },+ "content_digest": {+ "type": "string"+ },+ "eligibility": {+ "$ref": "#/$defs/ProtectionEligibilityV1"+ },+ "model": {+ "type": "string"+ },+ "prior_removed": {+ "format": "uint32",+ "minimum": 0,+ "type": "integer"+ },+ "prior_retained": {+ "format": "uint32",+ "minimum": 0,+ "type": "integer"+ },+ "protection_action": {+ "$ref": "#/$defs/HistoricalProtectionActionV1"+ },+ "protocol": {+ "type": "string"+ },+ "provider": {+ "type": "string"+ },+ "request_bytes": {+ "format": "uint32",+ "minimum": 0,+ "type": "integer"+ },+ "score": {+ "type": [+ "number",+ "null"+ ]+ },+ "simple_probability": {+ "type": [+ "number",+ "null"+ ]+ },+ "simple_threshold_millis": {+ "format": "uint16",+ "maximum": 65535,+ "minimum": 0,+ "type": "integer"+ },+ "stage_removed": {+ "format": "uint32",+ "minimum": 0,+ "type": "integer"+ },+ "stage_retained": {+ "format": "uint32",+ "minimum": 0,+ "type": "integer"+ },+ "standard": {+ "type": "string"+ },+ "target_complete": {+ "type": "boolean"+ },+ "target_segment": {+ "type": [+ "string",+ "null"+ ]+ }+ },+ "required": [+ "protocol",+ "content_digest",+ "bundle_digest",+ "provider",+ "model",+ "standard",+ "target_complete",+ "eligibility",+ "applicability_requested",+ "applicability_state",+ "applicability_reason",+ "protection_action",+ "simple_threshold_millis",+ "competence_floor_millis",+ "applicability_boundary_millis",+ "request_bytes",+ "prior_retained",+ "prior_removed",+ "stage_retained",+ "stage_removed"+ ],+ "type": "object"+ },+ "RoutingTimelineProtectionV1": {+ "additionalProperties": false,+ "properties": {+ "applicability_boundary_millis": {+ "format": "uint16",+ "maximum": 65535,+ "minimum": 0,+ "type": "integer"+ },+ "applicability_probability": {+ "type": [+ "number",+ "null"+ ]+ },+ "competence_floor_millis": {+ "format": "uint16",+ "maximum": 65535,+ "minimum": 0,+ "type": "integer"+ },+ "outcome": {+ "$ref": "#/$defs/HistoricalProtectionActionV1"+ },+ "previous_score": {+ "type": [+ "number",+ "null"+ ]+ }+ },+ "required": [+ "outcome",+ "competence_floor_millis",+ "applicability_boundary_millis"+ ],+ "type": "object"+ }+ },+ "$id": "hiroute://contracts/cli/routing-timeline-selection.v1.schema.json",+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "additionalProperties": false,+ "description": "Opening-decision read view. Persisted BranchDecisionV1 remains unchanged.",+ "properties": {+ "branch_id": {+ "type": "string"+ },+ "classification_duration_micros": {+ "format": "uint64",+ "minimum": 0,+ "type": [+ "integer",+ "null"+ ]+ },+ "competence_trigger": {+ "anyOf": [+ {+ "$ref": "#/$defs/CompetenceProtectionV1"+ },+ {+ "type": "null"+ }+ ]+ },+ "complexity_score": {+ "format": "uint8",+ "maximum": 255,+ "minimum": 0,+ "type": [+ "integer",+ "null"+ ]+ },+ "decision_protocol": {+ "anyOf": [+ {+ "$ref": "#/$defs/DecisionProtocolV1"+ },+ {+ "type": "null"+ }+ ]+ },+ "decision_source": {+ "$ref": "#/$defs/ComplexityDecisionSourceV1"+ },+ "execution_group": {+ "$ref": "#/$defs/ExecutionGroupV1"+ },+ "fallback_reason": {+ "anyOf": [+ {+ "$ref": "#/$defs/ClassifierFallbackReasonV1"+ },+ {+ "type": "null"+ }+ ]+ },+ "fallback_used": {+ "type": "boolean"+ },+ "historical_protection": {+ "anyOf": [+ {+ "$ref": "#/$defs/RoutingTimelineProtectionV1"+ },+ {+ "type": "null"+ }+ ]+ },+ "matched_user_phrase_ids": {+ "items": {+ "type": "string"+ },+ "type": "array"+ },+ "payload_digest": {+ "type": "string"+ },+ "policy": {+ "anyOf": [+ {+ "$ref": "#/$defs/BranchExecutionPolicyV1"+ },+ {+ "type": "null"+ }+ ]+ },+ "reason_codes": {+ "items": {+ "$ref": "#/$defs/ComplexityReasonCodeV1"+ },+ "type": "array"+ },+ "routing_observation": {+ "anyOf": [+ {+ "$ref": "#/$defs/RoutingObservationV1"+ },+ {+ "type": "null"+ }+ ]+ },+ "schema_version": {+ "type": "string"+ },+ "selection_reason": {+ "$ref": "#/$defs/ModelGroupReasonV1"+ },+ "simple_probability": {+ "type": [+ "number",+ "null"+ ]+ },+ "simple_threshold_millis": {+ "format": "uint16",+ "maximum": 65535,+ "minimum": 0,+ "type": [+ "integer",+ "null"+ ]+ },+ "strategy_id": {+ "type": "string"+ },+ "threshold": {+ "format": "uint8",+ "maximum": 255,+ "minimum": 0,+ "type": [+ "integer",+ "null"+ ]+ }+ },+ "required": [+ "execution_group",+ "selection_reason",+ "strategy_id",+ "schema_version",+ "payload_digest",+ "branch_id",+ "decision_source",+ "reason_codes",+ "matched_user_phrase_ids",+ "fallback_used"+ ],+ "title": "RoutingTimelineSelectionV1",+ "type": "object"+}diff --git a/crates/application-api/src/commands.rs b/crates/application-api/src/commands.rsindex 4425da19..70bc3643 100644--- a/crates/application-api/src/commands.rs+++ b/crates/application-api/src/commands.rs@@ -1108,7 +1108,7 @@ const COMMANDS: &[StaticCommandDescriptor] = &[["CLI-069", "APP-069"],Released,Query,- "Read agent turns with selection, score, requests and costs; --follow streams changed turns."+ "Read agent turns with selection, historical protection, score, requests and costs; --follow streams changed turns."),command!("observation.plan-trust",diff --git a/crates/application-api/src/generated.rs b/crates/application-api/src/generated.rsindex ed607fdb..86eeb404 100644--- a/crates/application-api/src/generated.rs+++ b/crates/application-api/src/generated.rs@@ -378,6 +378,18 @@ fn value_query_schema() -> Value {pub fn generated_contract_files() -> Vec<GeneratedContractFile> {let mut files = BTreeMap::from([+ (+ "routing-timeline-selection.v1.schema.json",+ pretty_json(&{+ let mut schema = serde_json::to_value(schemars::schema_for!(+ hiroute_domain::RoutingTimelineSelectionV1+ ))+ .expect("timeline selection schema");+ schema["$id"] =+ json!("hiroute://contracts/cli/routing-timeline-selection.v1.schema.json");+ schema+ }),+ ),("console-launch-request.v1.schema.json",pretty_json(@@ -645,6 +657,7 @@ mod tests {"planned-manifest.v1.json","prepare-discovered-model-connection-request.v1.schema.json","publication-checkpoint-change.v1.schema.json",+ "routing-timeline-selection.v1.schema.json","session-list-query.v1.schema.json","session-lookup.v1.schema.json","setup-apply-request.v1.schema.json",diff --git a/crates/cli/tests/routing_timeline_follow.rs b/crates/cli/tests/routing_timeline_follow.rsindex 378079bd..b936f768 100644--- a/crates/cli/tests/routing_timeline_follow.rs+++ b/crates/cli/tests/routing_timeline_follow.rs@@ -3,14 +3,16 @@use hiroute_domain::*;use hiroute_observation::{DigestAuthority, LocalObservationStore};use std::{+ collections::VecDeque,process::{Child, Command, Stdio},- sync::{Arc, mpsc},+ sync::{Arc, Mutex, mpsc},time::{Duration, Instant},};struct TracedStore {store: Arc<LocalObservationStore>,busy: mpsc::Sender<bool>,+ pages: Option<Mutex<VecDeque<RoutingTimelinePageV1>>>,}impl ObservationQueryPort for TracedStore {@@ -20,7 +22,20 @@ impl ObservationQueryPort for TracedStore {q: &RoutingTimelineQueryV1,now: i64,) -> Result<RoutingTimelinePageV1, ObservationQueryError> {- let result = ObservationQueryPort::observed_routing_timeline(&*self.store, r, q, now);+ // Controlled pages exercise the CLI consumer; storage projections have their own tests.+ let result = if let Some(pages) = &self.pages {+ Ok(pages+ .lock()+ .unwrap()+ .pop_front()+ .unwrap_or(RoutingTimelinePageV1 {+ turns: vec![],+ watermark: "settled".into(),+ complete: true,+ }))+ } else {+ ObservationQueryPort::observed_routing_timeline(&*self.store, r, q, now)+ };if matches!(&result, Err(ObservationQueryError::ReaderBusy)) {self.busy.send(true).unwrap();} else if result.is_ok() {@@ -119,6 +134,7 @@ fn review_cli_follow_retries_real_busy_reads() {ports.observation = Arc::new(TracedStore {store: store.clone(),busy,+ pages: None,});let endpoint = root.path().join("runtime");let mut server = hiroute_daemon::control::start_control(@@ -186,3 +202,171 @@ fn review_cli_follow_retries_real_busy_reads() {server.shutdown();server.join(Duration::from_secs(3)).unwrap();}++#[test]+fn follow_preserves_historical_protection_in_initial_and_changed_turns() {+ if std::env::var_os("HIROUTE_PROTECTION_TEST_CHILD").is_none() {+ let home = tempfile::tempdir().unwrap();+ let output = Command::new(std::env::current_exe().unwrap())+ .args([+ "--exact",+ "follow_preserves_historical_protection_in_initial_and_changed_turns",+ "--nocapture",+ ])+ .env("HOME", home.path())+ .env("HIROUTE_PROTECTION_TEST_CHILD", "1")+ .env_remove("PI_CODING_AGENT_DIR")+ .env_remove("CLAUDE_CONFIG_DIR")+ .env_remove("CODEX_HOME")+ .env_remove("DSH_CONFIG_DIR")+ .output()+ .unwrap();+ assert!(+ output.status.success(),+ "{}\n{}",+ String::from_utf8_lossy(&output.stdout),+ String::from_utf8_lossy(&output.stderr)+ );+ return;+ }+ let root = tempfile::tempdir().unwrap();+ use std::os::unix::fs::PermissionsExt;+ std::fs::set_permissions(root.path(), std::fs::Permissions::from_mode(0o700)).unwrap();+ let state = root.path().join("state");+ std::fs::create_dir(&state).unwrap();+ std::fs::set_permissions(&state, std::fs::Permissions::from_mode(0o700)).unwrap();+ let runtime = hiroute_daemon::control::ProductionControlRuntime::open(&state).unwrap();+ let store = Arc::new(+ LocalObservationStore::open(+ root.path().join("observation"),+ DigestAuthority::new([29; 32]),+ )+ .unwrap(),+ );+ let turns: Vec<RoutingTimelineTurnV1> = ["applied", "suppressed", "retained_unavailable", "not_needed"].into_iter().enumerate().map(|(i, outcome)| {+ let protected = matches!(outcome, "applied" | "retained_unavailable");+ serde_json::from_value(serde_json::json!({+ "turn_id":format!("turn-{i}"),"agent_turn_id":null,"segment_id":null,+ "started_at_ms":1000+i,"finished_at_ms":null,"boundary":"new_user_message",+ "plan_id":"trial","plan_revision":8,"branch_id":"smart_saving",+ "model_configuration_id":"trial-model","reasoning_profile_id":null,+ "group":if protected {"primary"} else {"regular"},+ "selection":{+ "execution_group":if protected {"primary"} else {"regular"},+ "simple_probability":0.94,"simple_threshold_millis":900,+ "selection_reason":if protected {"low_competence"} else {"simple_task"},+ "strategy_id":"routing","schema_version":"routing/v1",+ "payload_digest":CanonicalDigest::of_bytes(b"consumer-fixture"),+ "branch_id":"smart_saving","complexity_score":null,"threshold":null,+ "decision_source":"external_classifier","reason_codes":[],"matched_user_phrase_ids":[],+ "fallback_used":false,"classification_duration_micros":1,"fallback_reason":null,+ "historical_protection":{+ "outcome":outcome,"previous_score":if outcome=="not_needed" {0.8} else {0.3},+ "competence_floor_millis":500,+ "applicability_probability":if outcome=="retained_unavailable" {None} else {Some(if outcome=="suppressed" {0.05} else {0.99})},+ "applicability_boundary_millis":500+ }+ },+ "tool_continuations":0,"relays":[],"transitions":[],"assessment_state":"pending",+ "assessment":null,"competence_floor_millis":500,"protected_turn_ids":[],"status":"running",+ "requests":[],"cost_by_model":[],"evidence_partial":false,"content_digest":format!("initial-{i}")+ })).unwrap()+ }).collect();+ let mut changed = turns[0].clone();+ changed.status = "completed".into();+ changed.finished_at_ms = Some(2000);+ changed.content_digest = "later-completion".into();+ let pages = VecDeque::from([+ RoutingTimelinePageV1 {+ turns,+ watermark: "initial".into(),+ complete: true,+ },+ RoutingTimelinePageV1 {+ turns: vec![changed.clone()],+ watermark: "changed".into(),+ complete: true,+ },+ RoutingTimelinePageV1 {+ turns: vec![changed],+ watermark: "same".into(),+ complete: true,+ },+ ]);+ let (busy, reads) = mpsc::channel();+ let mut ports = runtime.application_ports();+ ports.observation = Arc::new(TracedStore {+ store,+ busy,+ pages: Some(Mutex::new(pages)),+ });+ let endpoint = root.path().join("runtime");+ let mut server = hiroute_daemon::control::start_control(+ hiroute_application::ApplicationService::new(ports),+ &endpoint,+ )+ .unwrap();+ let mut child = OwnedChild(Some(+ Command::new(env!("CARGO_BIN_EXE_hiroute"))+ .args([+ "sessions",+ "timeline",+ "trial-session",+ "--follow",+ "--output",+ "json",+ ])+ .env("HIROUTE_RUNTIME_DIR", &endpoint)+ .stdout(Stdio::piped())+ .stderr(Stdio::piped())+ .spawn()+ .unwrap(),+ ));+ for _ in 0..4 {+ assert!(+ !reads+ .recv_timeout(Duration::from_secs(8))+ .expect("CLI did not consume the next page")+ );+ }+ nix::sys::signal::kill(+ nix::unistd::Pid::from_raw(child.0.as_ref().unwrap().id() as i32),+ nix::sys::signal::Signal::SIGINT,+ )+ .unwrap();+ let deadline = Instant::now() + Duration::from_secs(5);+ while child.0.as_mut().unwrap().try_wait().unwrap().is_none() {+ assert!(Instant::now() < deadline, "follow did not stop on Ctrl-C");+ std::thread::sleep(Duration::from_millis(20));+ }+ let output = child.0.take().unwrap().wait_with_output().unwrap();+ assert!(output.status.success(), "{output:?}");+ let events: Vec<serde_json::Value> = String::from_utf8(output.stdout)+ .unwrap()+ .lines()+ .map(|line| serde_json::from_str(line).unwrap())+ .collect();+ assert_eq!(+ events.len(),+ 5,+ "four initial turns and one completion; the equal digest is deduplicated"+ );+ for (event, outcome) in events.iter().zip([+ "applied",+ "suppressed",+ "retained_unavailable",+ "not_needed",+ "applied",+ ]) {+ let history = &event["turn"]["selection"]["historical_protection"];+ assert_eq!(history["outcome"], outcome);+ assert_eq!(history["competence_floor_millis"], 500);+ assert_eq!(+ history["applicability_probability"].is_null(),+ outcome == "retained_unavailable"+ );+ }+ assert_eq!(events[4]["turn"]["status"], "completed");+ server.shutdown();+ server.join(Duration::from_secs(3)).unwrap();+}diff --git a/crates/domain/src/observation/routing_timeline.rs b/crates/domain/src/observation/routing_timeline.rsindex da0b24f6..a98d5ce5 100644--- a/crates/domain/src/observation/routing_timeline.rs+++ b/crates/domain/src/observation/routing_timeline.rs@@ -1,5 +1,9 @@//! Read projections over recorded execution facts. A watermark is opaque and scope-bound.use super::{BranchDecisionV1, PlanQualityAssessment};+use crate::{+ CanonicalDigest, ClassifierFallbackReasonV1, ComplexityDecisionSourceV1,+ ComplexityReasonCodeV1, DecisionProtocolV1,+};use serde::{Deserialize, Serialize};#[derive(schemars::JsonSchema, Clone, Debug, Deserialize, Serialize)]@@ -44,7 +48,7 @@ pub struct RoutingTimelineTurnV1 {pub model_configuration_id: Option<String>,pub reasoning_profile_id: Option<String>,pub group: Option<crate::ExecutionGroupV1>,- pub selection: Option<BranchDecisionV1>,+ pub selection: Option<RoutingTimelineSelectionV1>,pub tool_continuations: u64,pub relays: Vec<RoutingTimelineRelayV1>,#[serde(default)]@@ -61,6 +65,109 @@ pub struct RoutingTimelineTurnV1 {pub content_digest: String,}+/// Opening-decision read view. Persisted BranchDecisionV1 remains unchanged.+#[derive(schemars::JsonSchema, Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]+#[serde(deny_unknown_fields)]+pub struct RoutingTimelineSelectionV1 {+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub decision_protocol: Option<DecisionProtocolV1>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub routing_observation: Option<crate::RoutingObservationV1>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub policy: Option<crate::BranchExecutionPolicyV1>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub competence_trigger: Option<crate::CompetenceProtectionV1>,+ pub execution_group: crate::ExecutionGroupV1,+ pub simple_probability: Option<serde_json::Number>,+ pub simple_threshold_millis: Option<u16>,+ pub selection_reason: crate::ModelGroupReasonV1,+ pub strategy_id: String,+ pub schema_version: String,+ pub payload_digest: CanonicalDigest,+ pub branch_id: String,+ pub complexity_score: Option<u8>,+ pub threshold: Option<u8>,+ pub decision_source: ComplexityDecisionSourceV1,+ pub reason_codes: Vec<ComplexityReasonCodeV1>,+ pub matched_user_phrase_ids: Vec<String>,+ pub fallback_used: bool,+ pub classification_duration_micros: Option<u64>,+ pub fallback_reason: Option<ClassifierFallbackReasonV1>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub historical_protection: Option<RoutingTimelineProtectionV1>,+}++#[derive(schemars::JsonSchema, Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]+#[serde(deny_unknown_fields)]+pub struct RoutingTimelineProtectionV1 {+ pub outcome: crate::HistoricalProtectionActionV1,+ pub previous_score: Option<serde_json::Number>,+ pub competence_floor_millis: u16,+ pub applicability_probability: Option<serde_json::Number>,+ pub applicability_boundary_millis: u16,+}++impl From<BranchDecisionV1> for RoutingTimelineSelectionV1 {+ fn from(value: BranchDecisionV1) -> Self {+ let historical_protection =+ value+ .routing_observation+ .as_ref()+ .map(|observation| RoutingTimelineProtectionV1 {+ outcome: observation.protection_action,+ previous_score: observation.score.clone(),+ competence_floor_millis: observation.competence_floor_millis,+ applicability_probability: observation.applicability_probability.clone(),+ applicability_boundary_millis: observation.applicability_boundary_millis,+ });+ let BranchDecisionV1 {+ decision_protocol,+ routing_observation,+ policy,+ competence_trigger,+ execution_group,+ simple_probability,+ simple_threshold_millis,+ selection_reason,+ strategy_id,+ schema_version,+ payload_digest,+ branch_id,+ complexity_score,+ threshold,+ decision_source,+ reason_codes,+ matched_user_phrase_ids,+ fallback_used,+ classification_duration_micros,+ fallback_reason,+ } = value;+ Self {+ decision_protocol,+ routing_observation,+ policy,+ competence_trigger,+ execution_group,+ simple_probability,+ simple_threshold_millis,+ selection_reason,+ strategy_id,+ schema_version,+ payload_digest,+ branch_id,+ complexity_score,+ threshold,+ decision_source,+ reason_codes,+ matched_user_phrase_ids,+ fallback_used,+ classification_duration_micros,+ fallback_reason,+ historical_protection,+ }+ }+}+#[derive(Clone, Debug, Deserialize, Serialize)]#[serde(deny_unknown_fields)]pub struct RoutingTimelineRelayV1 {diff --git a/crates/observation/src/query_v2/routing_timeline/projection.rs b/crates/observation/src/query_v2/routing_timeline/projection.rsindex a6910bf1..bacf30c1 100644--- a/crates/observation/src/query_v2/routing_timeline/projection.rs+++ b/crates/observation/src/query_v2/routing_timeline/projection.rs@@ -483,7 +483,9 @@ fn make_turn(members: &[&Request]) -> Result<Projected, ObservationV2Error> {}}let decision = first.decision.as_ref();- let selection = decision.and_then(|d| d.complexity.clone());+ let selection = decision+ .and_then(|d| d.complexity.clone())+ .map(RoutingTimelineSelectionV1::from);Ok(Projected {position,view: RoutingTimelineTurnV1 {diff --git a/crates/observation/src/store/tests/plan_quality.rs b/crates/observation/src/store/tests/plan_quality.rsindex af6d239e..6cb2b79b 100644--- a/crates/observation/src/store/tests/plan_quality.rs+++ b/crates/observation/src/store/tests/plan_quality.rs@@ -11,6 +11,7 @@ use super::support::{Fixture, fact_channel, offer_fact, open_store, writer};mod routing_observations;mod routing_observations_released;+mod routing_timeline_protection;mod summary;mod trust;diff --git a/crates/observation/src/store/tests/plan_quality/routing_timeline_protection.rs b/crates/observation/src/store/tests/plan_quality/routing_timeline_protection.rsnew file mode 100644index 00000000..26481db4--- /dev/null+++ b/crates/observation/src/store/tests/plan_quality/routing_timeline_protection.rs@@ -0,0 +1,186 @@+use super::*;+use crate::store::tests::support::route_decision;+use hiroute_domain::*;++#[test]+fn timeline_preserves_opening_protection_and_keeps_later_scores_separate() {+ for variant in [2, 3, 4, 7] {+ let directory = tempfile::tempdir().unwrap();+ let store = open_store(directory.path());+ let current = Fixture::new(&format!("timeline-protection-{variant}"));+ let mut previous = current.clone();+ previous.request = LogicalRequestId::parse(format!("previous-{variant}")).unwrap();+ let channel = fact_channel(¤t, 1024 * 1024);+ let writer = writer(&store);+ let observation = super::routing_observations::observation(variant);+ let mut route = route_decision(PLAN);+ let ExecutionFactV1::RouteDecision(decision) = &mut route else {+ unreachable!()+ };+ let selection = decision.complexity.as_mut().unwrap();+ selection.decision_protocol = Some(DecisionProtocolV1::SystemOneC);+ selection.routing_observation = Some(observation.clone());+ selection.simple_probability = observation.simple_probability.clone();+ selection.simple_threshold_millis = Some(observation.simple_threshold_millis);+ selection.complexity_score = None;+ selection.threshold = None;+ selection.decision_source = ComplexityDecisionSourceV1::ExternalClassifier;+ selection.classification_duration_micros = Some(1);+ let protected = matches!(+ observation.protection_action,+ HistoricalProtectionActionV1::Applied+ | HistoricalProtectionActionV1::RetainedUnavailable+ );+ selection.execution_group = if protected {+ ExecutionGroupV1::Primary+ } else {+ ExecutionGroupV1::Regular+ };+ selection.selection_reason = if protected {+ ModelGroupReasonV1::LowCompetence+ } else {+ ModelGroupReasonV1::SimpleTask+ };+ if protected {+ selection.competence_trigger = Some(CompetenceProtectionV1 {+ segment_id: "stage-source".into(),+ score: observation.score.clone().unwrap(),+ floor_millis: observation.competence_floor_millis,+ from_group: ExecutionGroupV1::Regular,+ });+ }+ let original_selection = serde_json::to_value(&selection).unwrap();+ let previous_score = observation.score.as_ref().unwrap().as_f64().unwrap();+ let mut continuation = current.clone();+ continuation.request = LogicalRequestId::parse(format!("continuation-{variant}")).unwrap();+ let mut inherited = route.clone();+ if let ExecutionFactV1::RouteDecision(decision) = &mut inherited {+ decision.complexity.as_mut().unwrap().decision_source =+ ComplexityDecisionSourceV1::Inherited;+ decision.reason_ledger.push(ReasonLedgerEntryV1 {+ ordinal: 1,+ code: LedgerReasonCodeV1::ContextHoldApplied,+ group_id: None,+ });+ }+ let mut close = finished(+ ¤t,+ "current-stage",+ "current-turn",+ 2,+ SMART_SAVING_SCOPE_ID,+ 1200,+ );+ if let ExecutionFactV1::AgentTurnFinished {+ last_request_id, ..+ } = &mut close+ {+ *last_request_id = Some(continuation.request.clone());+ }+ let facts = [+ previous.fact(+ 1,+ finished(+ &previous,+ "stage-source",+ "previous-turn",+ 1,+ SMART_SAVING_SCOPE_ID,+ 1000,+ ),+ 1010,+ ),+ previous.fact(+ 2,+ assessment(+ &previous,+ "stage-source",+ ("previous-turn", "previous-turn", 1, 1),+ 1100,+ previous_score,+ ),+ 1100,+ ),+ current.fact(3, route, 1200),+ continuation.fact(4, inherited, 1205),+ current.fact(5, close, 1210),+ current.fact(+ 6,+ assessment(+ ¤t,+ "current-stage",+ ("current-turn", "current-turn", 2, 2),+ 1300,+ 0.95,+ ),+ 1300,+ ),+ ];+ for fact in facts {+ assert!(matches!(+ offer_fact(&writer, &channel, fact),+ WriterCycleOutcome::Ack(_)+ ));+ }+ let query = RoutingTimelineQueryV1 {+ session_id: current.session.to_string(),+ after_watermark: None,+ limit: 50,+ };+ let page = store+ .observed_routing_timeline(&reader(), &query, 5000)+ .unwrap();+ let turn = page+ .turns+ .iter()+ .find(|turn| turn.turn_id == current.request.as_str())+ .unwrap();+ assert_eq!(+ page.turns.len(),+ 2,+ "a continuation stays inside the opening turn"+ );+ assert_eq!(turn.requests.len(), 2);+ assert_eq!(turn.tool_continuations, 1);+ let selection = turn.selection.as_ref().unwrap();+ let history = selection.historical_protection.as_ref().unwrap();+ assert_eq!(history.outcome, observation.protection_action);+ assert_eq!(history.previous_score, observation.score);+ assert_eq!(+ history.applicability_probability,+ observation.applicability_probability+ );+ assert_eq!(+ history.competence_floor_millis,+ observation.competence_floor_millis+ );+ assert_eq!(turn.assessment.as_ref().unwrap().score, 0.95);+ let mut serialized = serde_json::to_value(selection).unwrap();+ serialized+ .as_object_mut()+ .unwrap()+ .remove("historical_protection");+ assert_eq!(+ serialized, original_selection,+ "existing selection fields keep their wire meaning"+ );+ let encoded = serde_json::to_value(turn).unwrap();+ let decoded: RoutingTimelineTurnV1 = serde_json::from_value(encoded).unwrap();+ assert_eq!(decoded.selection.as_ref().unwrap(), selection);+ }+}++#[test]+fn selections_without_historical_observations_remain_unrecorded() {+ let ExecutionFactV1::RouteDecision(decision) = route_decision(PLAN) else {+ unreachable!()+ };+ let original = decision.complexity.unwrap();+ let view = RoutingTimelineSelectionV1::from(original.clone());+ assert!(view.historical_protection.is_none());+ let bytes = serde_json::to_value(&view).unwrap();+ assert!(bytes.get("historical_protection").is_none());+ assert_eq!(bytes, serde_json::to_value(original).unwrap());+ let decoded: RoutingTimelineSelectionV1 = serde_json::from_value(bytes).unwrap();+ assert!(decoded.historical_protection.is_none());+}diff --git a/docs/code-map/README.md b/docs/code-map/README.mdindex ff426551..63c14c4a 100644--- a/docs/code-map/README.md+++ b/docs/code-map/README.md@@ -28,7 +28,7 @@ results in the relevant run record.| Configure, adjust or disable an Agent's models and task collaboration | [Agent/Worker map](worker-context.md), [Desktop feature guide](../../apps/desktop/src/features/agents/README.md) | [Settings ordering](../../crates/application/src/operations/tests/settings_tail.rs), [saved native model journey](../../crates/daemon/tests/support/additional_model_product.py) || Route an authenticated model request and apply bounded fallback | [Gateway map](../../crates/gateway/README.md), [execution core](../../crates/gateway-core/src) | [Real listener scenarios](../../tools/e2e-harness/tests/p0_gateway_runtime.rs) || Delegate, read, cancel or continue a Worker task | [Worker lifecycle and native differences](worker-context.md#follow-a-task-through-its-owners) | [Delegation](../../tools/product-e2e/tests/worker_delegation.rs), [read/Continue](../../tools/product-e2e/tests/worker_read.rs) |-| Inspect sessions, content, cost and competence | [Observation owners](architecture.md#observation-and-conversation-boundaries), [decision attribution](decision-foundation.md#observation-and-public-consumers) | [Concurrent routing timeline and incremental read bounds](../../crates/observation/src/store/tests/plan_quality/routing_timeline.rs), [stage summaries](../../crates/observation/src/store/tests/plan_quality/summary.rs) |+| Inspect sessions, content, cost and competence | [Observation owners](architecture.md#observation-and-conversation-boundaries), [decision attribution](decision-foundation.md#observation-and-public-consumers) | [Concurrent routing timeline and incremental read bounds](../../crates/observation/src/store/tests/plan_quality/routing_timeline.rs), [opening protection projection](../../crates/observation/src/store/tests/plan_quality/routing_timeline_protection.rs), [stage summaries](../../crates/observation/src/store/tests/plan_quality/summary.rs) || Connect, resume or adjust through a terminal/Agent | [CLI journey](../../crates/cli/src/quickstart.rs), [complete Plan recovery](../../crates/cli/src/quickstart/plan_restore.rs), [shared authoring](../../crates/application/src/routing/editor_options.rs), [installed schemas](../../crates/application-api/src/command_schemas.rs), [shared management Skill](../../assets/skills/hiroute-management/SKILL.md) | [Installed Quickstart](../../crates/daemon/tests/support/quickstart_product.py), [effective evidence](../../crates/daemon/src/control/runtime/settings_effective_tests.rs) || Manage the service through CLI or Desktop | [client-core](../../crates/client-core/src), [CLI](../../crates/cli/src), [Desktop host](../../apps/desktop/src-tauri/src), [daemon control](../../crates/daemon/src/control) | [Real control process](../../tools/product-e2e/tests/control_shell.rs), [Desktop test map](../../apps/desktop/tests/README.md) || Configure and open the authenticated console locally or remotely | [Console owner](../../crates/daemon/src/console), [shared product session](../../crates/product-session/src), [console guide](../web-console.md) | [Real role-all authority/HTTP composition](../../crates/daemon/src/console/tests.rs), [production browser scenarios](../../apps/desktop/tests/v3/visual/console-scenarios.mjs) |diff --git a/docs/code-map/decision-foundation.md b/docs/code-map/decision-foundation.mdindex 907ee2bd..1d9d24e3 100644--- a/docs/code-map/decision-foundation.md+++ b/docs/code-map/decision-foundation.md@@ -144,3 +144,11 @@ and [CLI entry tests](../../crates/cli/src/lib.rs) must remain aligned.Documentation fixtures and native windows with constructed observation recordsillustrate the product. Neither capture method proves live-provider behavior oranswer quality; acceptance records must identify the actual revision and scenario.++The session timeline uses a [read-specific selection](../../crates/domain/src/observation/routing_timeline.rs)+to expose opening historical-protection evidence while preserving the stored decision.+The [protection evidence guard](../../apps/desktop/src/features/trust/protection-evidence.ts)+checks complete matching Plan, revision, time and branch scope before placing a+released-decision count beside protected stages. Product requirements belong to+[smart-saving routing](../../issue-spec/specs/smart-saving-routing/spec.md) and+[session history](../../issue-spec/specs/session-history/spec.md).diff --git a/e2e/product/schema/contract-set.v1.json b/e2e/product/schema/contract-set.v1.jsonindex 980c12cd..e5a8e17a 100644--- a/e2e/product/schema/contract-set.v1.json+++ b/e2e/product/schema/contract-set.v1.json@@ -1,10 +1,10 @@{- "descriptor_digest": "sha256:b18d4b3eaa4e0ec39d26d15a87c35049433aebd5feeb241607231103a9cafe5b",+ "descriptor_digest": "sha256:6442c5e2453d65985ee602d119f10db1467c7671cd770be616ebb2b9b284c39c","files": {"dependency-gate.v1.json": "sha256:b8ac81155266dca921f159d1cfabec6605f2e4bab0320ad6b23a3dbee51e6fa1","product-action.v1.schema.json": "sha256:faf815b27fd292e564a7d51de20c5a2825abbe710315a2364a9932ae3b5e4b7e","product-oracle-evidence.v1.schema.json": "sha256:faab6582bf3fba307b0f9f2949c51726409a209b0fa62e847114e0c6301038c6",- "product-oracle-manifest.v1.json": "sha256:aaa97c7e048e67e80e886ed0a2a5dedf5e1b9c4a62a9d90166c9b4b391be8aea",+ "product-oracle-manifest.v1.json": "sha256:6d7ff50ffdc3d7b8e6c32654a364f6a271e0a56768e6ed63111c326117f72f0b","product-result.v1.schema.json": "sha256:72fc76be77572e40eed7516754911b45fdc9d55a8c089ba74c21427a33809def"},"schema_version": {diff --git a/e2e/product/schema/product-oracle-manifest.v1.json b/e2e/product/schema/product-oracle-manifest.v1.jsonindex d6c1fbde..92b3019c 100644--- a/e2e/product/schema/product-oracle-manifest.v1.json+++ b/e2e/product/schema/product-oracle-manifest.v1.json@@ -1,5 +1,5 @@{- "descriptor_digest": "sha256:b18d4b3eaa4e0ec39d26d15a87c35049433aebd5feeb241607231103a9cafe5b",+ "descriptor_digest": "sha256:6442c5e2453d65985ee602d119f10db1467c7671cd770be616ebb2b9b284c39c","expected_red_reasons": [],"planned_commands": ["console.open",diff --git a/issue-spec/specs/session-history/spec.md b/issue-spec/specs/session-history/spec.mdindex 7bed8609..45f0c866 100644--- a/issue-spec/specs/session-history/spec.md+++ b/issue-spec/specs/session-history/spec.md@@ -552,6 +552,55 @@ For a model and reasoning configuration in scope, the model performance view SHASource SPEC comments:- https://github.com/higress-group/HiRoute/issues/140#issuecomment-6236472910+### Requirement: Routing timelines explain historical protection at the opening selection++The session routing-timeline read and public CLI follow output MUST expose the opening selection's recorded historical-protection outcome, previous stage score and competence floor when available, and applicability probability when valid. The result distinguishes applied protection, released protection, protection retained because judgment was unavailable, and protection not needed. Unconsidered or unrecorded evidence remains explicit; it MUST NOT imply a release or zero probability. The lane marks released protection distinctly from an ordinary simple-task selection. Selected-turn details explain the current task's simple probability and threshold, the previous stage score and floor, and whether the earlier problem still matters, ending with the actual recorded group. The previous score comes from the opening decision, not the selected turn's later assessment. Continuations inherit the opening selection and are not additional protection decisions. Existing selection, read and follow meanings remain unchanged. This view does not alter routing, stored facts or assessment semantics. Labels use plain capability names and exclude internal protocol labels, digests and question identifiers.++#### Scenario: Protection applied++- **WHEN** an opening selection records simple probability 0.94 at threshold 0.90, previous score 0.30 below floor 0.50, applicability probability 0.99 and applied protection+- **THEN** the timeline marks protection and explains that the problem still matters and this turn went to Primary++#### Scenario: Protection released++- **WHEN** the same simple and low-score inputs have applicability probability 0.05 and recorded released protection+- **THEN** the lane marks released protection and explains that the problem no longer matters and Regular continued++#### Scenario: Judgment unavailable++- **WHEN** the record retains protection because applicability judgment was unavailable+- **THEN** the timeline explains the unavailable judgment and retained Primary protection without inventing a probability++#### Scenario: No protection and missing evidence differ++- **WHEN** a record says protection was not needed, or historical-protection evidence is absent or unconsidered+- **THEN** the view distinguishes those states and never calls missing evidence released protection++Source SPEC comments:+- https://github.com/higress-group/HiRoute/issues/140#issuecomment-6253018980++### Requirement: Long routing timelines provide a navigable overview++Above the routing lanes, session detail MUST provide a compact overview with one chronological mark per retained agent turn. Marks use the same Regular and Primary colors as the lanes and identify recorded low scores or failures, protection, and released protection. An outline shows the visible lane interval and follows scrolling, resizing and newly received turns. Activating a mark scrolls its turn into the lane viewport and selects it without changing routing or calling a model. The overview stays within the supported small window and has one Tab stop with roving focus across its chronologically ordered marks. Arrow keys move focus, Home and End reach the first and last mark, and Enter or Space selects the focused turn. Each mark retains a readable accessible label. Tab leaves the overview without visiting every mark. Chronological keyboard access through the lanes remains available; the overview is not the sole accessible path to a turn. Unknown groups and unavailable evidence remain distinct. Existing live-arrival handling, explicit-selection retention and reduced-motion preferences still apply.++#### Scenario: Forty-turn overview++- **WHEN** a session has forty retained Regular and Primary turns with low-score, failure, protection and release evidence+- **THEN** forty chronological marks reflect that evidence and the visible-interval outline matches the lanes++#### Scenario: Navigate and resize++- **WHEN** a user activates an offscreen mark and resizes to the smallest supported window+- **THEN** the selected turn becomes visible, details match it, the outline follows the viewport and the page has no horizontal overflow++#### Scenario: Keyboard and live append++- **WHEN** turns arrive while the user navigates overview marks or lane controls by keyboard+- **THEN** the overview keeps one Tab stop and its readable labels, arrow navigation and activation work, and chronological lane focus and live-follow or explicit-selection behavior remain available as matching marks are added++Source SPEC comments:+- https://github.com/higress-group/HiRoute/issues/140#issuecomment-6253019758+## Implementation references- [Native identity resolver](../../../crates/gateway/src/context_hold/identity.rs) anddiff --git a/issue-spec/specs/smart-saving-routing/spec.md b/issue-spec/specs/smart-saving-routing/spec.mdindex b238d350..6003099e 100644--- a/issue-spec/specs/smart-saving-routing/spec.md+++ b/issue-spec/specs/smart-saving-routing/spec.md@@ -232,6 +232,42 @@ User-facing Desktop text, website guides, README files and user documentation SHSource SPEC comments:- https://github.com/higress-group/HiRoute/issues/140#issuecomment-6236473660+### Requirement: The trust view distinguishes released historical protection++The Plan model-performance protection card MUST show how many historical low-score protections were released because the previous problem was fixed or unrelated and Regular continued. This count describes retained routing decisions and remains separate from the trust report's protected-stage count. A numeric count is permitted only when routing-observation coverage is complete and its Plan, published-revision selection, effective time interval and branch scopes match the protection card's trust report. Model and score filters must not relabel a Plan-wide count as a filtered-model count. Cohorts may be aggregated only within the matching branch scopes. A complete matching recorded cohort with no releases shows zero. Missing observations, incomplete coverage or any unproven scope alignment MUST show an unavailable value and a plain-language reason; unknown evidence MUST NOT become zero. The observation disclosure remains available with its own scope when a count cannot be placed beside protections. The release explanation uses capability language and MUST NOT display internal protocol labels, digests or question identifiers. No route, assessment, suggestion threshold or stored record changes through this view.++The view MUST offer last-24-hours, default last-seven-days and all-retained scopes. For every period, the stage and routing-decision reads MUST use the same captured explicit interval with its lower bound inside the retention boundary and a bounded read margin. Reads taken at different instants MUST NOT make an otherwise complete matching release count unavailable at the normal seven-day edge. Actual effective-interval mismatches still show unavailable. Changing the displayed period does not narrow the full active-revision evidence used for suggestions.++The routing release aggregate SHALL remain the result of the base read paired with the trust report. Later detail score/model filters and pagination SHALL NOT replace it with a separately clipped aggregate, even after the bounded read margin has elapsed. A grouping, period or revision change, explicit refresh or retry SHALL capture a fresh interval and reread both sources together. Actual scope mismatches remain unavailable.++#### Scenario: Inspect every period inside the retention boundary++- **WHEN** the user opens the default last-seven-days view or selects all retained records or the last 24 hours, and the two complete evidence reads occur at different instants+- **THEN** both use the same explicit retained interval and the protection card shows the aligned release count; detail navigation preserves the pair and grouping captures a fresh paired interval.++#### Scenario: Aligned complete evidence++- **WHEN** a trust report and complete routing observations match Plan, revision, time and branches and matching cohorts contain five released protections+- **THEN** the protection card shows five releases separately from its protected-stage count and explains that Regular continued after the earlier problem stopped mattering++#### Scenario: Incomplete or mismatched scope++- **WHEN** observations have partial coverage or a different Plan, revision, interval or branch scope+- **THEN** the protection card shows an unavailable value with the corresponding reason, while the observation disclosure retains its actual scope++#### Scenario: Missing and zero evidence differ++- **WHEN** there are no recorded historical-protection observations, or a complete matching recorded cohort has zero releases+- **THEN** missing evidence is unavailable with a reason, whereas the complete matching recorded cohort shows zero++#### Scenario: Filter and paginate after the read margin expires++- **WHEN** the default seven-day or all-retained view remains open for more than one minute, then the user selects low-score stages and loads another page+- **THEN** the release count stays bound to the original paired base read; grouping afterward refreshes both sources with one new interval.++Source SPEC comments:+- https://github.com/higress-group/HiRoute/issues/140#issuecomment-6253018308+## Implementation references- [Two-group policy](../../../crates/gateway/src/core_runtime/classification/group_policy.rs)