JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.
Python
fix(observability): stabilize realtime subagent trajectories
alan_chenga4f776fb6b66
diff --git a/jiuwenswarm/agents/harness/agent_observability.py b/jiuwenswarm/agents/harness/agent_observability.pyindex 35e14fae65..3a6e2237b0 100644--- a/jiuwenswarm/agents/harness/agent_observability.py+++ b/jiuwenswarm/agents/harness/agent_observability.py@@ -111,6 +111,7 @@ def sync_agent_observability(*, force: bool = False) -> None:obs_cfg = build_observability_config(cfg,service_name="jiuwenswarm-agent",+ default_backend="otlp",traces_dir=traces_dir,)provider_existed = acquire_observability(obs_cfg)diff --git a/jiuwenswarm/agents/harness/common/session_ops_service.py b/jiuwenswarm/agents/harness/common/session_ops_service.pyindex 486b75a266..411e41940f 100644--- a/jiuwenswarm/agents/harness/common/session_ops_service.py+++ b/jiuwenswarm/agents/harness/common/session_ops_service.py@@ -751,6 +751,9 @@ async def rewind_session_context(chat round does not reload stale pre-rewind messages from memory."""from openjiuwen.core.foundation.llm.schema.message import (+ OPENJIUWEN_MESSAGE_ORIGIN_EXTERNAL_USER,+ OPENJIUWEN_MESSAGE_ORIGIN_METADATA,+ OPENJIUWEN_MESSAGE_SOURCE_KIND_METADATA,UserMessage,AssistantMessage,ToolMessage,@@ -863,7 +866,15 @@ async def rewind_session_context(# ── User message ──if role == "user":if content.strip():- context_messages.append(UserMessage(content=content))+ source_kind = str(record.get("channel_id") or "history").strip()+ context_messages.append(UserMessage(+ content=content,+ metadata={+ OPENJIUWEN_MESSAGE_ORIGIN_METADATA:+ OPENJIUWEN_MESSAGE_ORIGIN_EXTERNAL_USER,+ OPENJIUWEN_MESSAGE_SOURCE_KIND_METADATA: source_kind,+ },+ ))continue# ── Only process assistant events below ──diff --git a/jiuwenswarm/agents/harness/observability_runtime.py b/jiuwenswarm/agents/harness/observability_runtime.pyindex 7e87b25ad3..8db29f05a7 100644--- a/jiuwenswarm/agents/harness/observability_runtime.py+++ b/jiuwenswarm/agents/harness/observability_runtime.py@@ -23,6 +23,7 @@ def build_observability_config(service_name: str,default_exporter: str = "otlp_grpc",default_endpoint: str = "http://localhost:4317",+ default_backend: str = "langfuse",traces_dir: str,) -> Any:"""Build the SDK config for one runtime without initializing the provider."""@@ -33,7 +34,9 @@ def build_observability_config(service_name=config.get("service_name", service_name),exporter=config.get("exporter", default_exporter),endpoint=config.get("endpoint", default_endpoint),+ backend=config.get("backend", default_backend),sample_rate=config.get("sample_rate", 1.0),+ max_attributes=config.get("max_attributes", 200),attribute_value_max_length=config.get("attribute_value_max_length", 10240),redact_prompts=config.get("redact_prompts", False),redact_completions=config.get("redact_completions", False),diff --git a/jiuwenswarm/channels/web/frontend/src/App.css b/jiuwenswarm/channels/web/frontend/src/App.cssindex 20d5624a5b..ded813620e 100644--- a/jiuwenswarm/channels/web/frontend/src/App.css+++ b/jiuwenswarm/channels/web/frontend/src/App.css@@ -18,91 +18,95 @@background: var(--color-surface-card);}+.chat-workspace--trajectory-floating-tools {+ padding-right: 364px;+}+.chat-layout__surface {background: var(--color-surface-card);}+.single-agent-surface {+ position: relative;+ display: flex;+ min-height: 0;+ flex: 1 1 0%;+ flex-direction: column;+}+.chat-surface-toolbar {display: flex;width: 100%;+ height: 40px;min-width: 0;flex: 0 0 auto;align-items: center;justify-content: space-between;gap: 0.5rem;- margin: 0.5rem 0 0.375rem;+ box-sizing: border-box;+ border-bottom: 1px solid var(--color-border-default);+ background: var(--color-surface-card);+ margin: 0;+ padding: 0 1rem;}-.chat-surface-tabs {- display: inline-flex;- flex: 0 0 auto;- gap: 0.125rem;- border: 1px solid var(--color-border-default);- border-radius: 0.5rem;- background: var(--color-action-secondary);- padding: 0.125rem;+/* The conversation title remains the common header for chat and trajectory. */+.single-agent-surface--chat.single-agent-surface--navigation .chat-surface-toolbar {+ position: absolute;+ z-index: 19;+ top: 48px;+ left: 0;}-.chat-surface-layout-controls {+.single-agent-surface--chat.single-agent-surface--navigation .chat-panel-header {+ height: 48px;+ margin-bottom: 40px;+}++.single-agent-surface--trajectory .chat-surface-view[data-testid='single-agent-chat-view'] {display: flex;- min-width: 0;- align-items: center;- justify-content: flex-end;- gap: 0.25rem;+ position: absolute;+ inset: 0;}-.chat-surface-layout-control {- position: relative;- display: inline-flex;- width: 1.75rem;- height: 1.75rem;- align-items: center;- justify-content: center;- border: 1px solid var(--color-border-default);- border-radius: 0.375rem;- background: var(--color-action-secondary);- color: var(--color-text-secondary);- cursor: pointer;- font-size: 1.125rem;- line-height: 1;- padding: 0;- white-space: nowrap;+.single-agent-surface--trajectory .chat-panel-shell {+ height: 100%;}-.chat-surface-layout-control:hover::after,-.chat-surface-layout-control:focus-visible::after {- position: absolute;- z-index: 20;- top: calc(100% + 0.375rem);- right: 0;- width: max-content;- max-width: 12rem;- border-radius: 0.375rem;- background: var(--color-surface-elevated, var(--color-surface-card));- box-shadow: var(--effect-shadow-md);- color: var(--color-text-primary);- content: attr(data-tooltip);- font-size: 0.75rem;- font-weight: 400;- line-height: 1.25rem;- padding: 0.25rem 0.5rem;+.single-agent-surface--trajectory .chat-panel-header {+ height: 48px;+}++.single-agent-surface--trajectory .chat-panel-shell > :not(.chat-panel-header) {+ visibility: hidden;pointer-events: none;}-.chat-surface-layout-control:hover {- border-color: var(--color-border-hover);- background: var(--color-surface-hover);- color: var(--color-text-primary);+.single-agent-surface--trajectory .chat-surface-toolbar {+ position: absolute;+ z-index: 19;+ top: 48px;+ left: 0;}-.chat-surface-layout-control:focus-visible {- outline: 2px solid var(--color-border-focus);- outline-offset: 1px;+.single-agent-surface--trajectory .chat-surface-view[data-testid='single-agent-trajectory-view'] {+ position: absolute;+ z-index: 10;+ top: 88px;+ right: 0;+ bottom: 0;+ left: 0;+ background: var(--color-surface-card);}-.chat-surface-layout-control[aria-pressed='true'] {- border-color: var(--color-border-focus);- color: var(--color-action-primary);+.chat-surface-tabs {+ display: inline-flex;+ flex: 0 0 auto;+ gap: 0.125rem;+ border: 1px solid var(--color-border-default);+ border-radius: 0.5rem;+ background: var(--color-action-secondary);+ padding: 0.125rem;}.chat-surface-tabs__tab {diff --git a/jiuwenswarm/channels/web/frontend/src/features/trajectory/SingleAgentSurface.tsx b/jiuwenswarm/channels/web/frontend/src/features/trajectory/SingleAgentSurface.tsxindex 6f1a5ac64d..a8f3a503af 100644--- a/jiuwenswarm/channels/web/frontend/src/features/trajectory/SingleAgentSurface.tsx+++ b/jiuwenswarm/channels/web/frontend/src/features/trajectory/SingleAgentSurface.tsx@@ -15,8 +15,8 @@ export interface SingleAgentSurfaceProps {tabListLabel: string;trajectory: ReactNode;trajectoryLabel: string;- trajectoryControls?: ReactNode;trajectoryRequested: boolean;+ showNavigation?: boolean;}/**@@ -31,16 +31,20 @@ export function SingleAgentSurface({onViewChange,tabListLabel,trajectory,- trajectoryControls,trajectoryLabel,trajectoryRequested,+ showNavigation = true,}: SingleAgentSurfaceProps) {const agentMode = mode === 'agent';- const resolvedView: ChatSurfaceView = agentMode ? activeView : 'chat';+ const navigationVisible = agentMode && showNavigation;+ const resolvedView: ChatSurfaceView = navigationVisible ? activeView : 'chat';return (- <>- {agentMode ? (+ <div+ className={`single-agent-surface single-agent-surface--${resolvedView} ${navigationVisible ? 'single-agent-surface--navigation' : ''}`}+ data-testid="single-agent-surface"+ >+ {navigationVisible ? (<div className="chat-surface-toolbar"><divclassName="chat-surface-tabs"@@ -69,11 +73,6 @@ export function SingleAgentSurface({{trajectoryLabel}</button></div>- {resolvedView === 'trajectory' && trajectoryControls !== undefined ? (- <div className="chat-surface-layout-controls" data-testid="trajectory-layout-controls">- {trajectoryControls}- </div>- ) : null}</div>) : null}<div@@ -83,7 +82,7 @@ export function SingleAgentSurface({>{chat}</div>- {agentMode && trajectoryRequested ? (+ {navigationVisible && trajectoryRequested ? (<divclassName={`chat-surface-view flex-1 min-h-0 ${resolvedView === 'trajectory' ? '' : 'chat-surface-view--hidden'}`}aria-hidden={resolvedView !== 'trajectory'}@@ -92,6 +91,6 @@ export function SingleAgentSurface({{trajectory}</div>) : null}- </>+ </div>);}diff --git a/jiuwenswarm/channels/web/frontend/src/features/trajectory/TrajectoryPanel.module.css b/jiuwenswarm/channels/web/frontend/src/features/trajectory/TrajectoryPanel.module.cssindex e02aa56eb5..9a03fbfe25 100644--- a/jiuwenswarm/channels/web/frontend/src/features/trajectory/TrajectoryPanel.module.css+++ b/jiuwenswarm/channels/web/frontend/src/features/trajectory/TrajectoryPanel.module.css@@ -70,6 +70,112 @@line-height: 1.25rem;}+.archiveNotice {+ margin: 0;+ border-bottom: 1px solid var(--color-border-default);+ color: var(--color-text-secondary);+ padding: 0.375rem 0.75rem;+ font-size: 0.75rem;+ line-height: 1.25rem;+}++.loadProgress {+ flex: 0 0 auto;+ border-bottom: 1px solid var(--color-border-default);+ background: var(--color-surface-muted);+ padding: 0.375rem 0.75rem 0.5rem;+}++.loadProgressLabel {+ margin-bottom: 0.25rem;+ color: var(--color-text-secondary);+ font-size: 0.6875rem;+ line-height: 1rem;+}++.loadProgressTrack {+ height: 0.25rem;+ overflow: hidden;+ border-radius: 999px;+ background: var(--color-border-default);+}++.loadProgressFill {+ display: block;+ height: 100%;+ border-radius: inherit;+ background: var(--color-action-primary);+ transition: width 120ms ease-out;+}++.loadProgressFillIndeterminate {+ width: 35%;+ animation: trajectory-load-progress 1s ease-in-out infinite;+}++@keyframes trajectory-load-progress {+ from { transform: translateX(-110%); }+ to { transform: translateX(310%); }+}++.subjectBar {+ flex: 0 0 auto;+ border-bottom: 1px solid var(--color-border-default);+ background: var(--color-surface-muted);+}++.subjectTabs {+ display: flex;+ gap: 0.25rem;+ overflow-x: auto;+ padding: 0.375rem 0.75rem 0;+ scrollbar-width: thin;+}++.subjectTab {+ flex: 0 0 auto;+ border: 0;+ border-bottom: 2px solid transparent;+ background: transparent;+ color: var(--color-text-secondary);+ cursor: pointer;+ font-size: 0.75rem;+ line-height: 1.5rem;+ padding: 0 0.625rem;+}++.subjectTab:hover {+ color: var(--color-text-primary);+}++.subjectTab:focus-visible {+ border-radius: 0.25rem;+ outline: 2px solid var(--color-border-focus);+ outline-offset: -2px;+}++.subjectTabActive {+ border-bottom-color: var(--color-border-focus);+ color: var(--color-text-primary);+ font-weight: 600;+}++.subjectMeta {+ display: flex;+ gap: 0.75rem;+ overflow: hidden;+ color: var(--color-text-secondary);+ font-size: 0.6875rem;+ line-height: 1.125rem;+ padding: 0 0.75rem 0.25rem;+ white-space: nowrap;+}++.subjectMeta span {+ overflow: hidden;+ text-overflow: ellipsis;+}+.body {display: flex;min-height: 0;@@ -83,6 +189,20 @@flex: 1 1 0;}+.subjectExplorers,+.subjectExplorer {+ display: flex;+ min-height: 0;+ flex: 1 1 0;+ flex-direction: column;+ overflow: hidden;+}++.subjectExplorersHidden,+.subjectExplorerHidden {+ display: none;+}+.state {display: flex;min-height: 12rem;diff --git a/jiuwenswarm/channels/web/frontend/src/features/trajectory/TrajectoryPanel.tsx b/jiuwenswarm/channels/web/frontend/src/features/trajectory/TrajectoryPanel.tsxindex a99f6f0f5c..c969d24ee5 100644--- a/jiuwenswarm/channels/web/frontend/src/features/trajectory/TrajectoryPanel.tsx+++ b/jiuwenswarm/channels/web/frontend/src/features/trajectory/TrajectoryPanel.tsx@@ -3,6 +3,7 @@/** Session-scoped transport host for the migrated trajectory explorer. */import {+ memo,useCallback,useEffect,useId,@@ -15,14 +16,17 @@ import {} from 'react';import { useTranslation } from 'react-i18next';import { webClient } from '../../services/webClient';-import { saveBlob } from '../../utils/desktopSave';+import { saveBlobWithResult } from '../../utils/desktopSave';import { TrajectoryExplorer } from './client/TrajectoryExplorer';import { JsonTree } from './primitives/JsonTree';import { projectOtelTrajectory } from './projector/otel-trajectory-projector';+import { createTrajectoryV2Reducer } from './projector/trajectory-v2-reducer';import type { OtlpExportTraceServiceRequest } from './shared/otlp';+import type { TrajectoryDiagnostic, TrajectoryUsage } from './trajectory/model';import {getTrajectoryRawRecord,getTrajectoryArchive,+ getTrajectorySessionUsage,getTrajectoryTrace,listTrajectoryTraceRevisions,listTrajectoryTraces,@@ -41,13 +45,18 @@ import {collectHeadRefreshWindow,collectRevisionRefreshWindow,createTrajectoryOperationCoordinator,+ createTrajectoryTraceHintCoordinator,createTrajectoryWindowState,detailRecordIdentity,resetTrajectoryWindowState,+ sameTrajectoryUsageMap,selectSummariesNeedingLoad,+ shouldCatchUpAfterTrajectoryTerminalEvent,spansOf,stageTrajectoryTracePages,trajectoryContentMode,+ type StagedTrajectoryTrace,+ type TrajectoryTerminalEventName,} from './trajectoryWindow';import {RAW_INSPECTOR_DEFAULT_HEIGHT,@@ -55,12 +64,18 @@ import {rawInspectorHeightBounds,rawInspectorKeyboardHeight,} from './trajectoryLayout';+import {+ createTrajectorySubjectViewCache,+ groupTrajectorySubjects,+ MAIN_TRAJECTORY_SUBJECT_ID,+} from './trajectorySubjects';import css from './TrajectoryPanel.module.css';import './client/theme.css';const INITIAL_TRACE_LIMIT = 30;const DETAIL_LIMIT = 1000;const DETAIL_CONCURRENCY = 6;+const LIVE_HINT_PULL_INTERVAL_MS = 80;const MAX_ARCHIVE_BYTES = 128 * 1024 * 1024;interface TraceUpdatedPayload {@@ -83,12 +98,27 @@ export interface TrajectoryPanelProps {sessionId: string;}+interface InitialLoadProgress {+ loaded: number;+ total: number;+}+function recordLabel(record: OtlpExportTraceServiceRequest): string {const span = spansOf(record)[0];if (span === undefined) return 'OTLP record';return `${span.name} · ${span.traceId.slice(0, 8)}/${span.spanId.slice(0, 8)}`;}+function aggregateDiagnostics(+ diagnostics: readonly TrajectoryDiagnostic[],+): readonly { code: string; count: number }[] {+ const counts = new Map<string, number>();+ for (const diagnostic of diagnostics) {+ counts.set(diagnostic.code, (counts.get(diagnostic.code) ?? 0) + 1);+ }+ return [...counts].map(([code, count]) => ({ code, count }));+}+function detailRecordLabel(record: TrajectoryDetailRecord): string {if (record.otlp !== null) return recordLabel(record.otlp);const identity = detailRecordIdentity(record);@@ -105,11 +135,33 @@ function errorMessage(error: unknown, chinese: boolean): string {if (error instanceof TrajectoryApiError && error.code === 'TRAJECTORY_DISABLED') {return chinese ? '轨迹观测当前未启用。' : 'Trajectory observability is disabled.';}+ if (error instanceof TrajectoryApiError && error.code === 'UNSUPPORTED_SESSION_MODE') {+ return chinese ? '当前会话暂时无法加载轨迹。' : 'Trajectory is temporarily unavailable for this session.';+ }if (error instanceof Error && error.message) return error.message;return chinese ? '轨迹数据加载失败。' : 'Failed to load trajectory data.';}-export function TrajectoryPanel({+interface PublishedTrajectoryWindow {+ readonly records: OtlpExportTraceServiceRequest[];+ readonly rawRecords: TrajectoryDetailRecord[];+ readonly lifecycleByRecordId: ReadonlyMap<string, 'running' | 'completed' | 'error'>;+ readonly sessionCumulativeUsageByRequestIdentity: ReadonlyMap<string, TrajectoryUsage>;+}++const EMPTY_PUBLISHED_WINDOW: PublishedTrajectoryWindow = {+ records: [],+ rawRecords: [],+ lifecycleByRecordId: new Map(),+ sessionCumulativeUsageByRequestIdentity: new Map(),+};++/**+ * Tool-panel visibility and other App chrome state must not rebuild the+ * session projection. The panel owns its own transport updates; parent-only+ * layout changes should only resize the already rendered surface.+ */+export const TrajectoryPanel = memo(function TrajectoryPanel({active,sessionId,}: TrajectoryPanelProps) {@@ -120,25 +172,38 @@ export function TrajectoryPanel({const loadedSessionRef = useRef<string | null>(null);const requestControllerRef = useRef<AbortController | null>(null);const refreshPromiseRef = useRef<Promise<void> | null>(null);+ const terminalCatchUpPromiseRef = useRef<Promise<void> | null>(null);+ const terminalCatchUpAgainRef = useRef(false);+ const terminalSettleTimerRef = useRef<number | null>(null);const rebuildPromiseRef = useRef<Promise<boolean> | null>(null);- const hintFrameRef = useRef<number | null>(null);- const pendingHintsRef = useRef(new Map<string, number>());+ const hintFlushScheduledRef = useRef(false);+ const hintCoordinatorRef = useRef(createTrajectoryTraceHintCoordinator());+ const activeRef = useRef(active);+ const deferredPublishRef = useRef(false);+ const initialLoadProgressRef = useRef<({ generation: number } & InitialLoadProgress) | null>(null);+ activeRef.current = active;const bodyRef = useRef<HTMLDivElement>(null);const rawResizeDragRef = useRef<RawInspectorResizeDrag | null>(null);const rawContentId = useId();const archiveInputRef = useRef<HTMLInputElement>(null);- const [records, setRecords] = useState<OtlpExportTraceServiceRequest[]>([]);- const [rawRecords, setRawRecords] = useState<TrajectoryDetailRecord[]>([]);- const [lifecycleByRecordId, setLifecycleByRecordId] = useState(- new Map<string, 'running' | 'completed' | 'error'>(),+ const rawSelectionBySubjectRef = useRef(new Map<string, string>());+ const subjectViewCacheRef = useRef(+ createTrajectorySubjectViewCache<ReturnType<typeof projectOtelTrajectory>>(),);- const [traceCount, setTraceCount] = useState(0);+ const trajectoryV2ReducerRef = useRef(createTrajectoryV2Reducer());+ const sessionCumulativeUsageRef = useRef(new Map<string, TrajectoryUsage>());+ const [publishedWindow, setPublishedWindow] = useState<PublishedTrajectoryWindow>(+ EMPTY_PUBLISHED_WINDOW,+ );+ const [selectedSubjectId, setSelectedSubjectId] = useState(MAIN_TRAJECTORY_SUBJECT_ID);const [hasEarlier, setHasEarlier] = useState(false);const [loading, setLoading] = useState(false);+ const [initialLoadProgress, setInitialLoadProgress] = useState<InitialLoadProgress | null>(null);const [loadingEarlier, setLoadingEarlier] = useState(false);const [exporting, setExporting] = useState(false);const [replayArchive, setReplayArchive] = useState<TrajectoryArchive | null>(null);const [archiveError, setArchiveError] = useState<string | null>(null);+ const [archiveNotice, setArchiveNotice] = useState<string | null>(null);const [invalidRecordSeen, setInvalidRecordSeen] = useState(false);const [error, setError] = useState<string | null>(null);const [rawSelection, setRawSelection] = useState('');@@ -151,6 +216,7 @@ export function TrajectoryPanel({const copy = useMemo(() => chinese ? {loading: '正在加载轨迹…',+ loadingProgress: (loaded: number, total: number) => `正在加载轨迹 ${loaded} / ${total}`,emptyTitle: '暂无轨迹',emptyText: '运行一次单 Agent 对话后,这里会展示模型、推理和工具调用轨迹。',newTitle: '尚未创建会话',@@ -162,8 +228,17 @@ export function TrajectoryPanel({exitReplay: '退出复现',replay: (sourceSession: string) => `只读复现 · ${sourceSession}`,archiveTooLarge: '轨迹归档超过 128 MB,无法在浏览器中导入。',+ exportBrowserStarted: '轨迹归档下载已开始;请在浏览器下载列表确认文件。',+ exportBrowserSaved: '轨迹归档已保存到本地。',+ exportDesktopSaved: '轨迹归档已保存到本地。',+ exportCancelled: '已取消轨迹导出。',+ exportFailed: '轨迹导出失败,请检查浏览器下载权限,或等待桌面保存桥接就绪后重试。',+ subjectTabs: '执行主体',+ subjectParent: (parentId: string) => `父主体 ${parentId}`,+ subjectSession: (subjectSessionId: string) => `执行会话 ${subjectSessionId}`,summary: (traces: number, spans: number) => `${traces} 条 trace · ${spans} 个 OTel Span`,invalid: '· 存在无法投影的原始记录',+ diagnostic: (code: string) => `轨迹数据不完整(${code}),已保留最近一次有效视图。`,raw: (count: number) => `原始 OTel 记录 (${count})`,rawLabel: '选择原始 OTel 记录',rawLoad: '按需加载原始记录',@@ -191,6 +266,7 @@ export function TrajectoryPanel({},} : {loading: 'Loading trajectory…',+ loadingProgress: (loaded: number, total: number) => `Loading trajectory ${loaded} / ${total}`,emptyTitle: 'No trajectory yet',emptyText: 'Run a single-Agent conversation to see model, reasoning, and tool traces here.',newTitle: 'No conversation yet',@@ -202,8 +278,17 @@ export function TrajectoryPanel({exitReplay: 'Exit replay',replay: (sourceSession: string) => `Read-only replay · ${sourceSession}`,archiveTooLarge: 'The trajectory archive exceeds the 128 MB browser import limit.',+ exportBrowserStarted: 'Trajectory archive download started; confirm it in the browser downloads list.',+ exportBrowserSaved: 'Trajectory archive saved locally.',+ exportDesktopSaved: 'Trajectory archive saved locally.',+ exportCancelled: 'Trajectory export was cancelled.',+ exportFailed: 'Trajectory export failed. Check browser download permissions or retry after the desktop save bridge is ready.',+ subjectTabs: 'Execution subjects',+ subjectParent: (parentId: string) => `Parent ${parentId}`,+ subjectSession: (subjectSessionId: string) => `Execution session ${subjectSessionId}`,summary: (traces: number, spans: number) => `${traces} traces · ${spans} OTel spans`,invalid: '· Some raw records could not be projected',+ diagnostic: (code: string) => `Trajectory data is incomplete (${code}); the last valid view was retained.`,raw: (count: number) => `Raw OTel records (${count})`,rawLabel: 'Select a raw OTel record',rawLoad: 'Load raw record on demand',@@ -219,39 +304,73 @@ export function TrajectoryPanel({const publish = useCallback((generation: number) => {if (!operationCoordinatorRef.current.isCurrent(generation)) return;+ if (!activeRef.current) {+ deferredPublishRef.current = true;+ return;+ }+ deferredPublishRef.current = false;const nextRecords = [...windowStateRef.current.buckets.values()].flatMap(bucket => ([...bucket.records.values()]));const nextRawRecords = [...windowStateRef.current.buckets.values()].flatMap(bucket => ([...bucket.rawRecords.values()]));- setRecords(nextRecords);- setRawRecords(nextRawRecords);- setLifecycleByRecordId(new Map(- [...windowStateRef.current.buckets.values()].flatMap(bucket => (- [...(bucket.versions ?? [])].map(([identity, version]) => (- [identity, version.lifecycle] as const- ))- )),- ));- setTraceCount(windowStateRef.current.buckets.size);+ setPublishedWindow({+ records: nextRecords,+ rawRecords: nextRawRecords,+ lifecycleByRecordId: new Map(+ [...windowStateRef.current.buckets.values()].flatMap(bucket => (+ [...(bucket.versions ?? [])].map(([identity, version]) => (+ [identity, version.lifecycle] as const+ ))+ )),+ ),+ sessionCumulativeUsageByRequestIdentity: new Map(sessionCumulativeUsageRef.current),+ });}, []);+ const refreshSessionUsage = useCallback(async (+ signal: AbortSignal,+ generation: number,+ ) => {+ const usage = await getTrajectorySessionUsage(sessionId, { signal });+ if (signal.aborted || !operationCoordinatorRef.current.isCurrent(generation)) return;+ const expectedEpoch = windowStateRef.current.storeEpoch;+ if (expectedEpoch !== null && usage.store_epoch !== expectedEpoch) return;+ const nextUsage = new Map(usage.items.map(item => (+ [`${item.trace_id}\u0000${item.inference_id}`, item.cumulative_usage]+ )));+ if (sameTrajectoryUsageMap(sessionCumulativeUsageRef.current, nextUsage)) return;+ sessionCumulativeUsageRef.current = nextUsage;+ subjectViewCacheRef.current.clear();+ publish(generation);+ }, [publish, sessionId]);+const clearPublishedWindow = useCallback(() => {resetTrajectoryWindowState(windowStateRef.current);- setRecords([]);- setRawRecords([]);- setLifecycleByRecordId(new Map());- setTraceCount(0);+ deferredPublishRef.current = false;+ subjectViewCacheRef.current.clear();+ trajectoryV2ReducerRef.current.clear();+ sessionCumulativeUsageRef.current.clear();+ setPublishedWindow(EMPTY_PUBLISHED_WINDOW);+ initialLoadProgressRef.current = null;+ setInitialLoadProgress(null);+ setSelectedSubjectId(MAIN_TRAJECTORY_SUBJECT_ID);setHasEarlier(false);setInvalidRecordSeen(false);setError(null);setRawSelection('');+ rawSelectionBySubjectRef.current.clear();setFetchedRaw(null);setRawLoading(false);setRawError(null);}, []);+ useEffect(() => {+ if (!active || !deferredPublishRef.current) return;+ publish(operationCoordinatorRef.current.currentGeneration());+ }, [active, publish]);+const loadTrace = useCallback(async (traceId: string,targetRevision: number,@@ -261,6 +380,32 @@ export function TrajectoryPanel({if (!operationCoordinatorRef.current.isCurrent(generation)) return;const current = windowStateRef.current.buckets.get(traceId);if (current !== undefined && current.revision >= targetRevision) return;+ const publishPage = (staged: StagedTrajectoryTrace) => {+ if (signal.aborted || !operationCoordinatorRef.current.isCurrent(generation)) return;+ const latest = windowStateRef.current.buckets.get(traceId);+ // A consumed revision uniquely identifies the trace state visible to+ // this coalesced detail feed. Equal or older concurrent pages cannot add+ // facts and would only trigger another full presentation publish.+ if (latest !== undefined && latest.revision >= staged.bucket.revision) return;+ windowStateRef.current.buckets.set(traceId, staged.bucket);+ if (staged.invalidRecordSeen) setInvalidRecordSeen(true);+ const loadProgress = initialLoadProgressRef.current;+ if (loadProgress !== null && loadProgress.generation === generation) {+ const loaded = Math.min(+ loadProgress.total,+ [...windowStateRef.current.buckets.values()].reduce(+ (count, bucket) => count + bucket.rawRecords.size,+ 0,+ ),+ );+ if (loaded !== loadProgress.loaded) {+ const nextProgress = { ...loadProgress, loaded };+ initialLoadProgressRef.current = nextProgress;+ setInitialLoadProgress({ loaded, total: loadProgress.total });+ }+ }+ publish(generation);+ };const staged = await stageTrajectoryTracePages(current,signal,@@ -269,17 +414,13 @@ export function TrajectoryPanel({sinceRevision,limit: DETAIL_LIMIT,}),+ publishPage,);if (staged === null|| signal.aborted|| !operationCoordinatorRef.current.isCurrent(generation)) return;- const latest = windowStateRef.current.buckets.get(traceId);- if (latest !== current- && latest !== undefined- && latest.revision > staged.bucket.revision) return;- windowStateRef.current.buckets.set(traceId, staged.bucket);- if (staged.invalidRecordSeen) setInvalidRecordSeen(true);- }, [sessionId]);+ setError(null);+ }, [publish, sessionId]);const loadSummaries = useCallback(async (summaries: readonly TrajectoryTraceSummary[],@@ -296,9 +437,8 @@ export function TrajectoryPanel({)));if (signal.aborted|| !operationCoordinatorRef.current.isCurrent(generation)) return;- publish(generation);}- }, [loadTrace, publish]);+ }, [loadTrace]);const rebuildFromHead = useCallback((signal: AbortSignal): Promise<boolean> => {if (rebuildPromiseRef.current !== null) return rebuildPromiseRef.current;@@ -314,6 +454,9 @@ export function TrajectoryPanel({limit: INITIAL_TRACE_LIMIT,});if (signal.aborted || !coordinator.isCurrent(generation)) return false;+ const total = page.items.reduce((count, summary) => count + summary.span_count, 0);+ initialLoadProgressRef.current = { generation, loaded: 0, total };+ setInitialLoadProgress({ loaded: 0, total });await loadSummaries(page.items, signal, generation);if (signal.aborted || !coordinator.isCurrent(generation)) return false;const windowState = windowStateRef.current;@@ -321,6 +464,8 @@ export function TrajectoryPanel({windowState.pageCursor = page.next_cursor;windowState.revisionCursor = page.revision_cursor;windowState.listWindowInitialized = true;+ await refreshSessionUsage(signal, generation);+ if (signal.aborted || !coordinator.isCurrent(generation)) return false;setHasEarlier(page.next_cursor !== null);setError(null);return true;@@ -330,7 +475,11 @@ export function TrajectoryPanel({}return false;} finally {- if (coordinator.isCurrent(generation)) setLoading(false);+ if (coordinator.isCurrent(generation)) {+ initialLoadProgressRef.current = null;+ setInitialLoadProgress(null);+ setLoading(false);+ }}})();rebuildPromiseRef.current = operation;@@ -338,10 +487,10 @@ export function TrajectoryPanel({if (rebuildPromiseRef.current === operation) rebuildPromiseRef.current = null;});return operation;- }, [chinese, clearPublishedWindow, loadSummaries, sessionId]);+ }, [chinese, clearPublishedWindow, loadSummaries, refreshSessionUsage, sessionId]);const refreshLatest = useCallback(async () => {- if (!active || sessionId === 'new' || requestControllerRef.current?.signal.aborted) return;+ if (sessionId === 'new' || requestControllerRef.current?.signal.aborted) return;if (refreshPromiseRef.current !== null) return refreshPromiseRef.current;const signal = requestControllerRef.current?.signal;if (signal === undefined) return;@@ -405,6 +554,8 @@ export function TrajectoryPanel({if (signal.aborted|| !coordinator.isCurrent(generation)|| windowStateRef.current.storeEpoch !== expectedStoreEpoch) return;+ await refreshSessionUsage(signal, generation);+ if (signal.aborted || !coordinator.isCurrent(generation)) return;if (!windowStateRef.current.listWindowInitialized || loadedRevisions.size === 0) {windowStateRef.current.pageCursor = headWindow.firstPageNextCursor;windowStateRef.current.listWindowInitialized = true;@@ -424,45 +575,70 @@ export function TrajectoryPanel({refreshPromiseRef.current = null;}}- }, [active, chinese, loadSummaries, rebuildFromHead, sessionId]);+ }, [chinese, loadSummaries, rebuildFromHead, refreshSessionUsage, sessionId]);++ const catchUpAfterTerminalEvent = useCallback((): Promise<void> => {+ terminalCatchUpAgainRef.current = true;+ if (terminalCatchUpPromiseRef.current !== null) {+ return terminalCatchUpPromiseRef.current;+ }+ const operation = (async () => {+ while (terminalCatchUpAgainRef.current) {+ terminalCatchUpAgainRef.current = false;+ const inFlight = refreshPromiseRef.current;+ if (inFlight !== null) await inFlight;+ await refreshLatest();+ }+ })();+ terminalCatchUpPromiseRef.current = operation;+ void operation.finally(() => {+ if (terminalCatchUpPromiseRef.current === operation) {+ terminalCatchUpPromiseRef.current = null;+ }+ });+ return operation;+ }, [refreshLatest]);const flushTraceHints = useCallback(async () => {const signal = requestControllerRef.current?.signal;- if (!active || signal === undefined || signal.aborted) return;- const hints = [...pendingHintsRef.current];- pendingHintsRef.current.clear();- if (hints.length === 0) return;+ if (signal === undefined || signal.aborted) return;const coordinator = operationCoordinatorRef.current;const generation = coordinator.currentGeneration();- await Promise.all(hints.map(([traceId, revision]) => loadTrace(- traceId,- revision,- signal,- generation,- )));- if (signal.aborted || !coordinator.isCurrent(generation)) return;- publish(generation);- }, [active, loadTrace, publish]);+ await hintCoordinatorRef.current.drain(async (hints) => {+ await Promise.all([...hints].map(([traceId, revision]) => loadTrace(+ traceId,+ revision,+ signal,+ generation,+ )));+ await refreshSessionUsage(signal, generation);+ }, () => new Promise<void>((resolve) => {+ window.setTimeout(resolve, LIVE_HINT_PULL_INTERVAL_MS);+ }));+ }, [loadTrace, refreshSessionUsage]);useEffect(() => {requestControllerRef.current?.abort();refreshPromiseRef.current = null;+ terminalCatchUpPromiseRef.current = null;+ terminalCatchUpAgainRef.current = false;+ if (terminalSettleTimerRef.current !== null) {+ window.clearTimeout(terminalSettleTimerRef.current);+ terminalSettleTimerRef.current = null;+ }rebuildPromiseRef.current = null;operationCoordinatorRef.current.invalidate(() => setLoadingEarlier(false));const controller = new AbortController();requestControllerRef.current = controller;setRawLoading(false);- pendingHintsRef.current.clear();- if (hintFrameRef.current !== null) {- window.cancelAnimationFrame(hintFrameRef.current);- hintFrameRef.current = null;- }+ hintCoordinatorRef.current = createTrajectoryTraceHintCoordinator();+ hintFlushScheduledRef.current = false;const sessionChanged = loadedSessionRef.current !== sessionId;if (sessionChanged) {loadedSessionRef.current = sessionId;clearPublishedWindow();}- if (!active || sessionId === 'new') {+ if (sessionId === 'new') {setLoading(false);return () => controller.abort();}@@ -477,10 +653,10 @@ export function TrajectoryPanel({if (refreshPromiseRef.current === operation) refreshPromiseRef.current = null;});return () => controller.abort();- }, [active, clearPublishedWindow, rebuildFromHead, refreshLatest, sessionId]);+ }, [clearPublishedWindow, rebuildFromHead, refreshLatest, sessionId]);useEffect(() => {- if (!active || sessionId === 'new' || replayArchive !== null) return undefined;+ if (sessionId === 'new' || replayArchive !== null) return undefined;const unsubscribe = webClient.on<TraceUpdatedPayload>('trace.updated', (event) => {if (event.payload.session_id !== sessionId) return;const traceId = event.payload.trace_id;@@ -506,12 +682,17 @@ export function TrajectoryPanel({void refreshLatest();return;}- const prior = pendingHintsRef.current.get(traceId) ?? -1;- if (revision > prior) pendingHintsRef.current.set(traceId, revision);- if (hintFrameRef.current !== null) return;- hintFrameRef.current = window.requestAnimationFrame(() => {- hintFrameRef.current = null;- void flushTraceHints();+ hintCoordinatorRef.current.enqueue(traceId, revision);+ if (hintFlushScheduledRef.current) return;+ hintFlushScheduledRef.current = true;+ queueMicrotask(() => {+ hintFlushScheduledRef.current = false;+ void flushTraceHints().catch(() => {+ // Detail hints are only watermarks. A transient detail fetch must not+ // strand the highest revision; the coordinator requeues it and the+ // revision feed repairs the view without waiting for chat completion.+ void refreshLatest();+ });});});let previousConnectionState = webClient.getState();@@ -521,20 +702,44 @@ export function TrajectoryPanel({}previousConnectionState = nextConnectionState;});+ const terminalEventNames: TrajectoryTerminalEventName[] = [+ 'chat.final',+ 'chat.processing_status',+ 'chat.error',+ 'execution.error',+ 'harness.session_finished',+ ];+ const unsubscribeTerminalEvents = terminalEventNames.map(eventName => (+ webClient.on<Record<string, unknown>>(eventName, (event) => {+ if (!shouldCatchUpAfterTrajectoryTerminalEvent(+ eventName,+ event.payload,+ sessionId,+ )) return;+ if (terminalSettleTimerRef.current !== null) {+ window.clearTimeout(terminalSettleTimerRef.current);+ }+ terminalSettleTimerRef.current = window.setTimeout(() => {+ terminalSettleTimerRef.current = null;+ void catchUpAfterTerminalEvent();+ }, 300);+ })+ ));return () => {unsubscribe();unsubscribeState();- if (hintFrameRef.current !== null) {- window.cancelAnimationFrame(hintFrameRef.current);- hintFrameRef.current = null;+ unsubscribeTerminalEvents.forEach(unsubscribeTerminal => unsubscribeTerminal());+ if (terminalSettleTimerRef.current !== null) {+ window.clearTimeout(terminalSettleTimerRef.current);+ terminalSettleTimerRef.current = null;}- pendingHintsRef.current.clear();+ hintFlushScheduledRef.current = false;};- }, [active, flushTraceHints, rebuildFromHead, refreshLatest, replayArchive, sessionId]);+ }, [catchUpAfterTerminalEvent, flushTraceHints, rebuildFromHead, refreshLatest, replayArchive, sessionId]);const loadEarlier = useCallback((): Promise<boolean> => {const signal = requestControllerRef.current?.signal;- if (!active || replayArchive !== null || signal === undefined || signal.aborted) {+ if (replayArchive !== null || signal === undefined || signal.aborted) {return Promise.resolve(false);}const coordinator = operationCoordinatorRef.current;@@ -578,17 +783,62 @@ export function TrajectoryPanel({return false;}}, setLoadingEarlier);- }, [active, chinese, loadSummaries, rebuildFromHead, replayArchive, sessionId]);+ }, [chinese, loadSummaries, rebuildFromHead, replayArchive, sessionId]);const replayView = useMemo(() => replayArchive === null ? null : trajectoryArchiveView(replayArchive),[replayArchive],);- const displayedRecords = replayView?.records ?? records;- const displayedRawRecords = replayView?.rawRecords ?? rawRecords;- const displayedLifecycle = replayView?.lifecycleByRecordId ?? lifecycleByRecordId;- const displayedTraceCount = replayView?.traceCount ?? traceCount;+ const allDisplayedRecords = replayView?.records ?? publishedWindow.records;+ const allDisplayedRawRecords = replayView?.rawRecords ?? publishedWindow.rawRecords;+ const allDisplayedLifecycle = replayView?.lifecycleByRecordId+ ?? publishedWindow.lifecycleByRecordId;const displayedInvalidRecordSeen = replayView?.invalidRecordSeen ?? invalidRecordSeen;+ const subjectView = useMemo(() => subjectViewCacheRef.current.update(+ groupTrajectorySubjects(+ allDisplayedRecords,+ allDisplayedRawRecords,+ allDisplayedLifecycle,+ replayArchive?.session_id ?? sessionId,+ ),+ group => projectOtelTrajectory(group.records, {+ lifecycleByRecordId: group.lifecycleByRecordId,+ sessionCumulativeUsageByRequestIdentity:+ replayArchive === null+ ? publishedWindow.sessionCumulativeUsageByRequestIdentity+ : new Map(),+ ...(replayArchive === null ? { v2Reducer: trajectoryV2ReducerRef.current } : {}),+ }),+ ), [+ allDisplayedLifecycle,+ allDisplayedRawRecords,+ allDisplayedRecords,+ publishedWindow.sessionCumulativeUsageByRequestIdentity,+ replayArchive?.session_id,+ sessionId,+ ]);+ const subjectGroups = subjectView.groups;+ const selectedSubjectGroup = subjectGroups.byId.get(selectedSubjectId)+ ?? subjectGroups.byId.get(MAIN_TRAJECTORY_SUBJECT_ID)+ ?? subjectGroups.groups[0];+ const displayedRecords = selectedSubjectGroup?.records ?? [];+ const displayedRawRecords = selectedSubjectGroup?.rawRecords ?? [];+ const displayedTraceCount = selectedSubjectGroup?.traceCount ?? 0;+ const subjectSnapshots = subjectView.snapshots;+ const selectedSubjectSnapshot = selectedSubjectGroup === undefined+ ? undefined+ : subjectSnapshots.get(selectedSubjectGroup.subject.id);++ const selectSubject = useCallback((subjectId: string) => {+ rawSelectionBySubjectRef.current.set(selectedSubjectId, rawSelection);+ setSelectedSubjectId(subjectId);+ setRawSelection(rawSelectionBySubjectRef.current.get(subjectId) ?? '');+ }, [rawSelection, selectedSubjectId]);++ useEffect(() => {+ if (subjectGroups.byId.has(selectedSubjectId)) return;+ selectSubject(MAIN_TRAJECTORY_SUBJECT_ID);+ }, [selectSubject, selectedSubjectId, subjectGroups]);useEffect(() => {if (displayedRawRecords.length === 0) {@@ -602,9 +852,10 @@ export function TrajectoryPanel({if (!identities.includes(rawSelection)) {const nextSelection = identities[0] ?? '';windowStateRef.current.rawSelection = nextSelection;+ rawSelectionBySubjectRef.current.set(selectedSubjectId, nextSelection);setRawSelection(nextSelection);}- }, [displayedRawRecords, rawSelection]);+ }, [displayedRawRecords, rawSelection, selectedSubjectId]);useEffect(() => {setFetchedRaw(null);@@ -612,9 +863,6 @@ export function TrajectoryPanel({setRawLoading(false);}, [rawSelection, replayArchive, sessionId]);- const snapshot = useMemo(() => projectOtelTrajectory(displayedRecords, {- lifecycleByRecordId: displayedLifecycle,- }), [displayedLifecycle, displayedRecords]);const rawRecord = useMemo(() => displayedRawRecords.find(record => detailRecordIdentity(record) === rawSelection),[displayedRawRecords, rawSelection],@@ -661,6 +909,7 @@ export function TrajectoryPanel({if (replayArchive === null && (signal === undefined || signal.aborted)) return;setExporting(true);setArchiveError(null);+ setArchiveNotice(null);try {const archive = replayArchive ?? parseTrajectoryArchive(await getTrajectoryArchive(sessionId, { signal }),@@ -669,8 +918,18 @@ export function TrajectoryPanel({const blob = new Blob([`${JSON.stringify(archive, null, 2)}\n`], {type: 'application/json;charset=utf-8',});- const outcome = await saveBlob(blob, `trajectory-${safeSession}.json`);- if (outcome === 'failed') throw new Error('Trajectory archive could not be saved');+ const result = await saveBlobWithResult(+ blob,+ `trajectory-${safeSession}.archive.json`,+ );+ if (result.outcome === 'failed') throw new Error(copy.exportFailed);+ setArchiveNotice(result.outcome === 'cancelled'+ ? copy.exportCancelled+ : result.transport === 'desktop'+ ? copy.exportDesktopSaved+ : result.transport === 'browser-file-picker'+ ? copy.exportBrowserSaved+ : copy.exportBrowserStarted);} catch (exportError) {if (!(exportError instanceof DOMException && exportError.name === 'AbortError')) {setArchiveError(errorMessage(exportError, chinese));@@ -678,17 +937,19 @@ export function TrajectoryPanel({} finally {setExporting(false);}- }, [chinese, exporting, replayArchive, sessionId]);+ }, [chinese, copy, exporting, replayArchive, sessionId]);const importArchive = useCallback(async (event: ChangeEvent<HTMLInputElement>) => {const file = event.currentTarget.files?.[0];event.currentTarget.value = '';if (file === undefined) return;setArchiveError(null);+ setArchiveNotice(null);try {if (file.size > MAX_ARCHIVE_BYTES) throw new Error(copy.archiveTooLarge);const archive = parseTrajectoryArchive(await file.text());setReplayArchive(archive);+ setSelectedSubjectId(MAIN_TRAJECTORY_SUBJECT_ID);setRawSelection('');setFetchedRaw(null);setRawError(null);@@ -700,7 +961,9 @@ export function TrajectoryPanel({const exitReplay = useCallback(() => {const transition = exitTrajectoryReplay(replayArchive);setReplayArchive(transition.archive);+ setSelectedSubjectId(MAIN_TRAJECTORY_SUBJECT_ID);setArchiveError(null);+ setArchiveNotice(null);setRawSelection('');if (transition.catchUpLiveRevision) void refreshLatest();}, [refreshLatest, replayArchive]);@@ -824,6 +1087,7 @@ export function TrajectoryPanel({onChange={(event) => {const nextSelection = event.currentTarget.value;windowStateRef.current.rawSelection = nextSelection;+ rawSelectionBySubjectRef.current.set(selectedSubjectId, nextSelection);setRawSelection(nextSelection);}}>@@ -907,31 +1171,61 @@ export function TrajectoryPanel({} else {content = (<>+ {aggregateDiagnostics(selectedSubjectSnapshot?.diagnostics ?? []).map((diagnostic) => (+ <p+ className={`${css.rawNotice} ${css.errorText}`}+ key={diagnostic.code}+ >+ {copy.diagnostic(diagnostic.code)}{diagnostic.count > 1 ? ` × ${diagnostic.count}` : ''}+ </p>+ ))}{error !== null && replayArchive === null && displayedRecords.length === 0 ? (<p className={`${css.rawNotice} ${css.errorText}`}>{error}</p>) : null}{displayedRecords.length === 0 ? (<div className={css.state}><p className={css.stateText}>{copy.rawOnly}</p></div>- ) : (- <TrajectoryExplorer- snapshot={snapshot}- loading={replayArchive === null ? loading : false}- loadingEarlier={replayArchive === null ? loadingEarlier : false}- hasEarlier={replayArchive === null ? hasEarlier : false}- loadEarlier={loadEarlier}- error={replayArchive === null ? error : null}- messages={copy.toolbar}- colorMode="light"- className={css.explorer}- />- )}+ ) : null}+ <div className={`${css.subjectExplorers} ${+ displayedRecords.length === 0 ? css.subjectExplorersHidden : ''+ }`}>+ {subjectGroups.groups.map((group) => {+ const selected = group.subject.id === selectedSubjectGroup?.subject.id;+ const subjectSnapshot = subjectSnapshots.get(group.subject.id);+ if (subjectSnapshot === undefined || group.records.length === 0) return null;+ return (+ <div+ key={group.subject.id}+ className={`${css.subjectExplorer} ${selected ? '' : css.subjectExplorerHidden}`}+ aria-hidden={!selected}+ data-trajectory-subject-explorer={group.subject.id}+ >+ <TrajectoryExplorer+ active={active && selected}+ snapshot={subjectSnapshot}+ loading={selected && replayArchive === null ? loading : false}+ loadingEarlier={selected && replayArchive === null ? loadingEarlier : false}+ hasEarlier={selected && replayArchive === null ? hasEarlier : false}+ loadEarlier={loadEarlier}+ error={selected && replayArchive === null ? error : null}+ messages={copy.toolbar}+ colorMode="light"+ className={css.explorer}+ />+ </div>+ );+ })}+ </div>{rawInspector}</>);}return (- <section className={css.root} aria-label={chinese ? '轨迹' : 'Trajectory'}>+ <section+ className={css.root}+ aria-label={chinese ? '轨迹' : 'Trajectory'}+ data-active={active ? 'true' : 'false'}+ ><header className={css.header}><div className={css.summary}>{replayArchive === null@@ -980,7 +1274,76 @@ export function TrajectoryPanel({{archiveError === null ? null : (<p className={`${css.archiveError} ${css.errorText}`} role="alert">{archiveError}</p>)}+ {archiveNotice === null ? null : (+ <p className={css.archiveNotice} role="status">{archiveNotice}</p>+ )}+ {replayArchive === null && loading ? (+ <div className={css.loadProgress} role="status" aria-live="polite">+ <div className={css.loadProgressLabel}>+ {initialLoadProgress === null+ ? copy.loading+ : copy.loadingProgress(initialLoadProgress.loaded, initialLoadProgress.total)}+ </div>+ <div+ className={css.loadProgressTrack}+ role="progressbar"+ aria-label={copy.loading}+ {...(initialLoadProgress === null+ ? {}+ : {+ 'aria-valuemin': 0,+ 'aria-valuemax': initialLoadProgress.total,+ 'aria-valuenow': initialLoadProgress.loaded,+ })}+ >+ <span+ className={`${css.loadProgressFill} ${+ initialLoadProgress === null ? css.loadProgressFillIndeterminate : ''+ }`}+ style={initialLoadProgress === null+ ? undefined+ : {+ width: `${initialLoadProgress.total === 0+ ? 100+ : Math.min(100, (initialLoadProgress.loaded / initialLoadProgress.total) * 100)}%`,+ }}+ />+ </div>+ </div>+ ) : null}+ {subjectGroups.groups.length > 1 ? (+ <div className={css.subjectBar}>+ <div className={css.subjectTabs} role="tablist" aria-label={copy.subjectTabs}>+ {subjectGroups.groups.map(group => (+ <button+ key={group.subject.id}+ type="button"+ role="tab"+ aria-selected={group.subject.id === selectedSubjectGroup?.subject.id}+ className={`${css.subjectTab} ${+ group.subject.id === selectedSubjectGroup?.subject.id ? css.subjectTabActive : ''+ }`}+ title={group.subject.id}+ onClick={() => selectSubject(group.subject.id)}+ data-subject-id={group.subject.id}+ >+ {group.label}+ </button>+ ))}+ </div>+ {selectedSubjectGroup?.subject.kind === 'subagent' ? (+ <div className={css.subjectMeta}>+ {selectedSubjectGroup.subject.parentId === null+ ? null+ : <span>{copy.subjectParent(selectedSubjectGroup.subject.parentId)}</span>}+ {selectedSubjectGroup.subject.sessionId === null+ ? null+ : <span>{copy.subjectSession(selectedSubjectGroup.subject.sessionId)}</span>}+ </div>+ ) : null}+ </div>+ ) : null}<div ref={bodyRef} className={css.body}>{content}</div></section>);-}+});diff --git a/jiuwenswarm/channels/web/frontend/src/features/trajectory/client/TrajectoryExplorer.tsx b/jiuwenswarm/channels/web/frontend/src/features/trajectory/client/TrajectoryExplorer.tsxindex f68086a811..d5f140b8ed 100644--- a/jiuwenswarm/channels/web/frontend/src/features/trajectory/client/TrajectoryExplorer.tsx+++ b/jiuwenswarm/channels/web/frontend/src/features/trajectory/client/TrajectoryExplorer.tsx@@ -3,7 +3,7 @@/** Standalone trajectory explorer assembled from the DSH presentation components. */import {- useCallback, useEffect, useMemo, useState, type CSSProperties,+ memo, useCallback, useEffect, useMemo, useRef, useState, type CSSProperties,} from 'react'import type {TrajectoryRequest, TrajectorySnapshot, TrajectoryTurnModel,@@ -35,6 +35,8 @@ interface ExplorerStyle extends CSSProperties {/** Ordinary React props; no Cordis, Session, slot, or locale service is required. */export interface TrajectoryExplorerProps {+ /** Whether this mounted explorer is currently visible and may run its live clock. */+ active?: boolean/** Atomic read model produced by an OTel projector or a static fixture. */snapshot?: TrajectorySnapshot/** Static grouped records; ignored when `snapshot` is supplied. */@@ -97,7 +99,8 @@ function searchIndexes(}/** Render the full toolbar, overview timeline, virtual ledger, and inspector. */-export function TrajectoryExplorer({+export const TrajectoryExplorer = memo(function TrajectoryExplorer({+ active = true,snapshot,turns: staticTurns = [],requests: staticRequests,@@ -122,7 +125,7 @@ export function TrajectoryExplorer({)), [turns])const [liveNowMilliseconds, setLiveNowMilliseconds] = useState(() => Date.now())useEffect(() => {- if (!hasRunningCells) return undefined+ if (!active || !hasRunningCells) return undefinedconst update = () => setLiveNowMilliseconds(Date.now())update()const interval = window.setInterval(update, 250)@@ -134,7 +137,7 @@ export function TrajectoryExplorer({window.clearInterval(interval)document.removeEventListener('visibilitychange', onVisibility)}- }, [hasRunningCells])+ }, [active, hasRunningCells])const [actualDuration, setActualDuration] = useState(false)const [actualTime, setActualTime] = useState(false)const [collapsedTurns, setCollapsedTurns] = useState<ReadonlySet<number>>(EMPTY_TURN_IDS)@@ -146,6 +149,17 @@ export function TrajectoryExplorer({const [selectedTimelineIndex, setSelectedTimelineIndex] = useState<number | null>(null)const [recordSelection, setRecordSelection] = useState<{ readonly index: number } | null>(null)const [recordFocus, setRecordFocus] = useState<{ readonly index: number } | null>(null)+ const [scrollToEndSignal, setScrollToEndSignal] = useState(0)+ const wasActiveRef = useRef(false)+ // Whenever the explorer becomes visible (first mount while active, a chat ->+ // trajectory tab switch, or a subject tab change), ask the ledger to jump to+ // the newest record. The ref starts false so an initially-active explorer+ // still requests the tail on first render.+ useEffect(() => {+ const becameActive = active && !wasActiveRef.current+ wasActiveRef.current = active+ if (becameActive) setScrollToEndSignal(value => value + 1)+ }, [active])const t = useMemo(() => translate ?? trajectoryTranslator(messages),[messages, translate],@@ -280,6 +294,7 @@ export function TrajectoryExplorer({<div className={css.ledger}><TrajectoryTableturns={turns}+ scrollToEndSignal={scrollToEndSignal}{...(requests === undefined ? {} : { requestNumbers: requests })}{...(streamingCells === undefined ? {} : { streamingCells })}timelineFocusIndexes={timelineFocusIndexes}@@ -310,4 +325,4 @@ export function TrajectoryExplorer({</div></TrajectoryThemeProvider>)-}+})diff --git a/jiuwenswarm/channels/web/frontend/src/features/trajectory/client/TrajectoryTable.module.css b/jiuwenswarm/channels/web/frontend/src/features/trajectory/client/TrajectoryTable.module.cssindex f4bfb537a1..5ec59433c7 100644--- a/jiuwenswarm/channels/web/frontend/src/features/trajectory/client/TrajectoryTable.module.css+++ b/jiuwenswarm/channels/web/frontend/src/features/trajectory/client/TrajectoryTable.module.css@@ -751,6 +751,16 @@);}+.errorKindTag {+ color: var(--dsw-alias-state-error-primary);+ background: var(--dsw-alias-state-error-secondary);+ background: color-mix(+ in srgb,+ var(--dsw-alias-state-error-primary) 12%,+ var(--dsw-alias-bg-layer-1)+ );+}+.contentText {display: block;min-width: 0;diff --git a/jiuwenswarm/channels/web/frontend/src/features/trajectory/client/TrajectoryTable.tsx b/jiuwenswarm/channels/web/frontend/src/features/trajectory/client/TrajectoryTable.tsxindex 3846c21bcf..30c31f1dfa 100644--- a/jiuwenswarm/channels/web/frontend/src/features/trajectory/client/TrajectoryTable.tsx+++ b/jiuwenswarm/channels/web/frontend/src/features/trajectory/client/TrajectoryTable.tsx@@ -37,7 +37,7 @@ import {groupTrajectoryVirtualRows, trajectoryVirtualRecordKey,} from '../trajectory/virtual-rows.ts'import type { TrajectoryVirtualRow } from '../trajectory/virtual-rows.ts'-import { trajectoryPreviewText } from '../trajectory/preview.ts'+import { trajectoryDisplayText, trajectoryPreviewText } from '../trajectory/preview.ts'import css from './TrajectoryTable.module.css'const BOTTOM_FOLLOW_THRESHOLD_PX = 2@@ -165,6 +165,7 @@ function useStableVirtualRowStructure(}type DetailTab =+ | 'system-message'| 'system-prompt'| 'tools'| 'overview'@@ -225,10 +226,6 @@ const SYSTEM_PROMPT_TABS: readonly DetailTabItem[] = [{ id: 'system-prompt', label: 'System Prompt' },{ id: 'tools', label: 'Tools' },]-const SYSTEM_UPDATE_TABS: readonly DetailTabItem[] = [- { id: 'diff', label: 'Diff' },- ...SYSTEM_PROMPT_TABS,-]const REQUEST_TABS: readonly DetailTabItem[] = [{ id: 'overview', label: 'Summary' },{ id: 'options', label: 'Options' },@@ -379,6 +376,8 @@ export interface TrajectoryTableProps {recordSelection?: { readonly index: number } | null/** One externally requested record focus without changing inspector selection. */recordFocus?: { readonly index: number } | null+ /** Monotonic counter; each change scrolls the ledger to the newest record. */+ scrollToEndSignal?: number/** Whether the initial history tail is still loading. */historyLoading?: boolean/** Whether one older history page request is pending anywhere. */@@ -478,6 +477,7 @@ function recordRequestKey(record: TableRecord): string {function indexRequestBoundaries(records: readonly TableRecord[]): ReadonlyMap<string, number> {const boundaries = new Map<string, number>()for (const record of records) {+ if (record.cell.requestless === true) continueconst key = recordRequestKey(record)if (boundaries.has(key)) continueif (requestStep(record.group) === undefined) {@@ -763,7 +763,7 @@ function RequestUsagePanel({<UsageRows usage={usage} /></section><section className={css.usageGroup}>- <h4 className={css.usageHeading}>Window cumulative</h4>+ <h4 className={css.usageHeading}>Session cumulative</h4><UsageRows usage={cumulative} /></section></div>@@ -901,20 +901,38 @@ function detailTabs(record: TableRecord): readonly DetailTabItem[] {? []: [{ id: 'otel', label: 'OTel' } as const]if (record.cell.kind === 'system') {- const promptTabs = record.cell.previousPromptDetail === undefined+ const promptTabs = record.cell.promptSystemMessageIndex === undefined+ && record.cell.promptDetail !== undefined? SYSTEM_PROMPT_TABS- : SYSTEM_UPDATE_TABS- return [...promptTabs, ...otel]+ : [+ { id: 'system-message', label: 'System Message' } as const,+ ...(record.cell.promptDetail === undefined+ ? []+ : [+ { id: 'system-prompt', label: 'Full Prompt' } as const,+ { id: 'tools', label: 'Tools' } as const,+ ]),+ ]+ const tabs = record.cell.previousPromptDetail === undefined+ ? promptTabs+ : [{ id: 'diff', label: 'Diff' } as const, ...promptTabs]+ return [...tabs, ...otel]}if (record.cell.kind === 'compacted') {return [{ id: 'overview', label: 'Summary' },{ id: 'raw', label: 'Raw Output' },+ ...(record.cell.compactionDetail === undefined+ ? []+ : [{ id: 'facts', label: 'Facts' } as const]),...otel,]}if (isMarkdownRecord(record)) {return [+ ...(record.cell.kind === 'context' && record.cell.previousInputDetail !== undefined+ ? [{ id: 'diff', label: 'Diff' } as const]+ : []),{ id: 'overview', label: 'Summary' },{ id: 'rendered', label: 'Preview' },{ id: 'raw', label: 'Raw' },@@ -937,9 +955,7 @@ function detailTabs(record: TableRecord): readonly DetailTabItem[] {function recordDisplayText(cell: TrajectoryCellProps): string {if (isToolCallOnly(cell)) return ''if (cell.previewMarkdown !== undefined) {- const preview = trajectoryPreviewText(cell.previewMarkdown)- if (cell.text === '') return preview- return preview === '' ? cell.text : `${cell.text} · ${preview}`+ return trajectoryDisplayText(cell.text, cell.previewMarkdown)}if (cell.text !== '') return cell.textconst markdown = cell.kind === 'user' || cell.kind === 'context'@@ -1306,19 +1322,27 @@ function PromptDiffSection({function SystemPromptDiff({before,after,+ systemMessageIndex,}: {before: TrajectoryPromptSnapshotafter: TrajectoryPromptSnapshot+ systemMessageIndex?: number}) {+ const systemBefore = systemMessageIndex === undefined+ ? before.system+ : before.systemMessages.find(message => message.index === systemMessageIndex)?.content ?? ''+ const systemAfter = systemMessageIndex === undefined+ ? after.system+ : after.systemMessages.find(message => message.index === systemMessageIndex)?.content ?? ''const toolsBefore = JSON.stringify(before.tools, null, 2)const toolsAfter = JSON.stringify(after.tools, null, 2)return (<div className={css.promptDiffSections}>- {before.system !== after.system && (+ {systemBefore !== systemAfter && (<PromptDiffSectiontitle="System Prompt"- before={before.system}- after={after.system}+ before={systemBefore}+ after={systemAfter}/>)}{toolsBefore !== toolsAfter && (@@ -1712,6 +1736,7 @@ export function TrajectoryTable({onRecordSelect,recordSelection = null,recordFocus = null,+ scrollToEndSignal = 0,historyLoading = false,olderHistoryLoading = false,historyStartSeq,@@ -1863,6 +1888,16 @@ export function TrajectoryTable({const selectedPreviousPrompt = selected?.cell.kind === 'system'? selected.cell.previousPromptDetail: undefined+ const selectedPromptSystemMessageIndex = selected?.cell.kind === 'system'+ ? selected.cell.promptSystemMessageIndex+ : undefined+ const selectedPromptText = selected?.cell.kind === 'system'+ ? selected.cell.text+ : undefined+ const selectedPreviousContextText = selected?.cell.kind === 'context'+ ? selected.cell.previousInputDetail+ : undefined+ const systemSelected = selected?.cell.kind === 'system'const promptSelected = selectedPrompt !== undefinedconst selectedState = selected === undefined ? undefined : stateOf(selected)const selectedRequestRecordTemplates = useMemo(() => selectedRequest === null@@ -1928,8 +1963,7 @@ export function TrajectoryTable({: { total: selectedRequestAssistant.cell.total }),})- const selectedRequestCumulativeUsage =- selectedRequestInfo?.cumulativeUsage ?? selectedRequestUsage+ const selectedRequestCumulativeUsage = selectedRequestInfo?.cumulativeUsageconst selectedRequestOptions = selectedRequestInfo?.requestConfigconst selectedRequestFacts = selectedRequestInfo?.recordedFactsconst activeTurn = selectedRequest === null ? selected?.turn : selectedRequest.turn@@ -2217,6 +2251,19 @@ export function TrajectoryTable({virtualRowStructure,virtualizationEnabled,])+ // Host-requested jump to the newest record (e.g. every time the trajectory+ // view becomes visible again). Reuses the tail-follow state so records that+ // stream in after the signal still keep the view pinned to the bottom.+ useEffect(() => {+ if (scrollToEndSignal === 0) return+ const pane = tablePaneRef.current+ if (pane === null) return+ followsTableTail.current = true+ tableScrollInitialized.current = true+ setTableScrollReady(true)+ if (virtualizationEnabled) rowVirtualizer.scrollToEnd({ behavior: 'auto' })+ else pane.scrollTop = pane.scrollHeight+ }, [rowVirtualizer, scrollToEndSignal, virtualizationEnabled])const olderBusy = olderHistoryLoading || olderLoadingconst showInitialLoading = historyLoading || !tableScrollReady@@ -2471,7 +2518,9 @@ export function TrajectoryTable({><spanclassName={`${css.kindTag} ${- record.cell.kind === 'system'+ record.cell.isError+ ? css.errorKindTag+ : record.cell.kind === 'system'? css.systemNeutral: record.cell.kind === 'context'? css.contextGreen@@ -2881,8 +2930,30 @@ export function TrajectoryTable({<SystemPromptDiffbefore={selectedPreviousPrompt}after={selectedPrompt}+ systemMessageIndex={selectedPromptSystemMessageIndex}/>)}+ {!promptSelected+ && selected?.cell.kind === 'context'+ && selectedPreviousContextText !== undefined+ && activeTab === 'diff' && (+ <div className={css.promptDiffSections}>+ <PromptDiffSection+ title="Context Message"+ before={selectedPreviousContextText}+ after={selected.cell.inputDetail ?? selected.cell.text}+ />+ </div>+ )}+ {systemSelected && activeTab === 'system-message' && (+ selectedPromptText === ''+ ? <p className={css.noPayload}>No content in this system message</p>+ : (+ <div className={`${css.markdownPayload} ${css.systemPrompt}`}>+ <MarkdownText text={selectedPromptText ?? ''} />+ </div>+ )+ )}{promptSelected && activeTab === 'system-prompt' && (selectedPrompt.system === ''? <p className={css.noPayload}>No system prompt in this request</p>@@ -3100,6 +3171,16 @@ export function TrajectoryTable({onOpenCall={openCallSummary}/>)}+ {!promptSelected+ && selected?.cell.kind === 'compacted'+ && selected.cell.compactionDetail !== undefined+ && activeTab === 'facts' && (+ <JsonTree+ data={selected.cell.compactionDetail}+ label="Compaction facts JSON"+ className={css.jsonPayload}+ />+ )}{!promptSelected && selected !== undefined && activeTab === 'source' && (<MessageSource record={selected} />)}diff --git a/jiuwenswarm/channels/web/frontend/src/features/trajectory/fixtures/attribute-pressure-llm-call-records.json b/jiuwenswarm/channels/web/frontend/src/features/trajectory/fixtures/attribute-pressure-llm-call-records.jsonnew file mode 100644index 0000000000..afa472e25d--- /dev/null+++ b/jiuwenswarm/channels/web/frontend/src/features/trajectory/fixtures/attribute-pressure-llm-call-records.json@@ -0,0 +1,74 @@+[+ {+ "resourceSpans": [{+ "scopeSpans": [{+ "spans": [{+ "traceId": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",+ "spanId": "0000000000000021",+ "name": "llm.call",+ "startTimeUnixNano": "21000000000",+ "endTimeUnixNano": "22000000000",+ "attributes": [+ { "key": "gen_ai.conversation.id", "value": { "stringValue": "pressure-session" } },+ { "key": "openjiuwen.execution.subject.id", "value": { "stringValue": "subagent:pressure" } },+ { "key": "openjiuwen.inference.id", "value": { "stringValue": "inference-21" } },+ { "key": "openjiuwen.turn.number", "value": { "intValue": "1" } },+ { "key": "openjiuwen.step.number", "value": { "intValue": "21" } },+ { "key": "openjiuwen.execution.subject.request.number", "value": { "intValue": "21" } },+ { "key": "gen_ai.output.messages", "value": { "stringValue": "[{\"role\":\"assistant\",\"parts\":[{\"type\":\"reasoning\",\"content\":\"Need one more tool\"},{\"type\":\"tool_call\",\"id\":\"call-21\",\"name\":\"bash\",\"arguments\":{\"command\":\"pwd\"}}]}]" } },+ { "key": "gen_ai.response.finish_reasons", "value": { "arrayValue": { "values": [{ "stringValue": "tool_calls" }] } } }+ ]+ }]+ }]+ }]+ },+ {+ "resourceSpans": [{+ "scopeSpans": [{+ "spans": [{+ "traceId": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",+ "spanId": "0000000000001021",+ "parentSpanId": "0000000000000021",+ "name": "tool.bash",+ "startTimeUnixNano": "22000000000",+ "endTimeUnixNano": "22500000000",+ "attributes": [+ { "key": "gen_ai.conversation.id", "value": { "stringValue": "pressure-session" } },+ { "key": "openjiuwen.execution.subject.id", "value": { "stringValue": "subagent:pressure" } },+ { "key": "openjiuwen.trajectory.record.kind", "value": { "stringValue": "tool" } },+ { "key": "openjiuwen.inference.id", "value": { "stringValue": "inference-21" } },+ { "key": "openjiuwen.turn.number", "value": { "intValue": "1" } },+ { "key": "openjiuwen.step.number", "value": { "intValue": "21" } },+ { "key": "gen_ai.tool.name", "value": { "stringValue": "bash" } },+ { "key": "gen_ai.tool.call.id", "value": { "stringValue": "call-21" } },+ { "key": "gen_ai.tool.call.arguments", "value": { "stringValue": "{\"command\":\"pwd\"}" } },+ { "key": "gen_ai.tool.call.result", "value": { "stringValue": "{\"output\":\"/workspace\"}" } }+ ]+ }]+ }]+ }]+ },+ {+ "resourceSpans": [{+ "scopeSpans": [{+ "spans": [{+ "traceId": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",+ "spanId": "0000000000000022",+ "name": "llm.call",+ "startTimeUnixNano": "23000000000",+ "endTimeUnixNano": "24000000000",+ "attributes": [+ { "key": "gen_ai.conversation.id", "value": { "stringValue": "pressure-session" } },+ { "key": "openjiuwen.execution.subject.id", "value": { "stringValue": "subagent:pressure" } },+ { "key": "openjiuwen.inference.id", "value": { "stringValue": "inference-22" } },+ { "key": "openjiuwen.turn.number", "value": { "intValue": "1" } },+ { "key": "openjiuwen.step.number", "value": { "intValue": "22" } },+ { "key": "openjiuwen.execution.subject.request.number", "value": { "intValue": "22" } },+ { "key": "gen_ai.output.messages", "value": { "stringValue": "[{\"role\":\"assistant\",\"parts\":[{\"type\":\"reasoning\",\"content\":\"Ready to answer\"},{\"type\":\"text\",\"content\":\"Final pressure-safe answer\"}]}]" } },+ { "key": "gen_ai.response.finish_reasons", "value": { "arrayValue": { "values": [{ "stringValue": "stop" }] } } }+ ]+ }]+ }]+ }]+ }+]diff --git a/jiuwenswarm/channels/web/frontend/src/features/trajectory/fixtures/legacy-langfuse-records.json b/jiuwenswarm/channels/web/frontend/src/features/trajectory/fixtures/legacy-langfuse-records.jsondeleted file mode 100644index d63444f23d..0000000000--- a/jiuwenswarm/channels/web/frontend/src/features/trajectory/fixtures/legacy-langfuse-records.json+++ /dev/null@@ -1,120 +0,0 @@-[- {- "resourceSpans": [- {- "scopeSpans": [- {- "spans": [- {- "traceId": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",- "spanId": "aaaaaaaaaaaaaaaa",- "name": "chat",- "startTimeUnixNano": "1000000000",- "endTimeUnixNano": "2000000000",- "attributes": [- { "key": "gen_ai.operation.name", "value": { "stringValue": "chat" } },- { "key": "gen_ai.system_instructions", "value": { "stringValue": "invalid structured system" } },- { "key": "gen_ai.input.messages", "value": { "stringValue": "invalid structured input" } },- { "key": "gen_ai.prompt.0.role", "value": { "stringValue": "system" } },- { "key": "gen_ai.prompt.0.content", "value": { "stringValue": "legacy system" } },- { "key": "gen_ai.prompt.1.role", "value": { "stringValue": "user" } },- { "key": "gen_ai.prompt.1.content", "value": { "stringValue": "legacy user" } },- { "key": "gen_ai.output.messages", "value": { "stringValue": "invalid structured output" } },- { "key": "langfuse.observation.output", "value": { "stringValue": "{\"choices\":[{\"message\":{\"role\":\"assistant\",\"content\":\"langfuse answer\",\"tool_calls\":[{\"id\":\"call-legacy\",\"type\":\"function\",\"function\":{\"name\":\"lookup\",\"arguments\":\"{\\\"query\\\":\\\"legacy\\\"}\"}}]},\"finish_reason\":\"tool_calls\"}],\"usage\":{\"prompt_tokens\":7,\"completion_tokens\":3}}" } },- { "key": "gen_ai.usage.prompt_tokens", "value": { "intValue": "7" } },- { "key": "gen_ai.usage.completion_tokens", "value": { "intValue": "3" } },- { "key": "gen_ai.usage.cache_tokens", "value": { "intValue": "2" } },- { "key": "gen_ai.usage.reasoning_tokens", "value": { "intValue": "0" } },- { "key": "gen_ai.response.time_to_first_token_ms", "value": { "doubleValue": 250 } }- ],- "status": { "code": 1 }- }- ]- }- ]- }- ]- },- {- "resourceSpans": [- {- "scopeSpans": [- {- "spans": [- {- "traceId": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",- "spanId": "bbbbbbbbbbbbbbbb",- "name": "chat",- "startTimeUnixNano": "3000000000",- "endTimeUnixNano": "4000000000",- "attributes": [- { "key": "gen_ai.operation.name", "value": { "stringValue": "chat" } },- { "key": "gen_ai.prompt", "value": { "stringValue": "scalar user" } },- { "key": "gen_ai.completion", "value": { "stringValue": "scalar answer" } }- ],- "status": { "code": 1 }- }- ]- }- ]- }- ]- },- {- "resourceSpans": [- {- "scopeSpans": [- {- "spans": [- {- "traceId": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",- "spanId": "cccccccccccccccc",- "parentSpanId": "bbbbbbbbbbbbbbbb",- "name": "tool.lookup",- "startTimeUnixNano": "4100000000",- "endTimeUnixNano": "4200000000",- "attributes": [- { "key": "langfuse.observation.type", "value": { "stringValue": "tool" } },- { "key": "gen_ai.tool.name", "value": { "stringValue": "lookup" } },- { "key": "gen_ai.tool.id", "value": { "stringValue": "call-legacy" } },- { "key": "gen_ai.tool.input", "value": { "stringValue": "{\"query\":\"legacy\"}" } },- { "key": "gen_ai.tool.output", "value": { "stringValue": "{\"result\":\"legacy-result\"}" } }- ],- "status": { "code": 1 }- }- ]- }- ]- }- ]- },- {- "resourceSpans": [- {- "scopeSpans": [- {- "spans": [- {- "traceId": "dddddddddddddddddddddddddddddddd",- "spanId": "dddddddddddddddd",- "name": "provider.request",- "startTimeUnixNano": "5000000000",- "endTimeUnixNano": "6000000000",- "attributes": [- { "key": "openjiuwen.session_id", "value": { "stringValue": "old-openjiuwen-session" } },- { "key": "langfuse.observation.type", "value": { "stringValue": "generation" } },- { "key": "langfuse.observation.input", "value": { "stringValue": "[{\"role\":\"user\",\"content\":\"embedded usage question\"}]" } },- { "key": "langfuse.observation.output", "value": { "stringValue": "{\"choices\":[{\"message\":{\"role\":\"assistant\",\"content\":\"embedded usage answer\"},\"finish_reason\":\"stop\"}],\"usage\":{\"input_tokens\":0,\"output_tokens\":4,\"total_tokens\":4,\"cache_tokens\":0,\"cache_creation_input_tokens\":0,\"reasoning_tokens\":0}}" } },- { "key": "dsh.turn.number", "value": { "intValue": "2" } },- { "key": "dsh.step.number", "value": { "intValue": "1" } },- { "key": "dsh.request.number", "value": { "intValue": "1" } }- ],- "status": { "code": 1 }- }- ]- }- ]- }- ]- }-]diff --git a/jiuwenswarm/channels/web/frontend/src/features/trajectory/fixtures/request-subject-number-records.json b/jiuwenswarm/channels/web/frontend/src/features/trajectory/fixtures/request-subject-number-records.jsonnew file mode 100644index 0000000000..34e9ea1895--- /dev/null+++ b/jiuwenswarm/channels/web/frontend/src/features/trajectory/fixtures/request-subject-number-records.json@@ -0,0 +1,106 @@+[+ {+ "resourceSpans": [{ "scopeSpans": [{ "spans": [{+ "traceId": "11111111111111111111111111111111", "spanId": "1000000000000001", "name": "llm.call",+ "startTimeUnixNano": "1000000000", "endTimeUnixNano": "1100000000",+ "attributes": [+ { "key": "gen_ai.operation.name", "value": { "stringValue": "chat" } },+ { "key": "gen_ai.output.messages", "value": { "stringValue": "[{\"role\":\"assistant\",\"parts\":[{\"type\":\"text\",\"content\":\"Repeated output\"}]}]" } },+ { "key": "openjiuwen.turn.number", "value": { "intValue": "1" } },+ { "key": "openjiuwen.request.number", "value": { "intValue": "1" } },+ { "key": "openjiuwen.execution.subject.id", "value": { "stringValue": "main" } },+ { "key": "openjiuwen.execution.subject.request.number", "value": { "intValue": "1" } },+ { "key": "openjiuwen.trajectory.record.kind", "value": { "stringValue": "inference" } }+ ], "status": { "code": 1 }+ }] }] }]+ },+ {+ "resourceSpans": [{ "scopeSpans": [{ "spans": [{+ "traceId": "22222222222222222222222222222222", "spanId": "2000000000000002", "name": "llm.call",+ "startTimeUnixNano": "2000000000", "endTimeUnixNano": "2100000000",+ "attributes": [+ { "key": "gen_ai.operation.name", "value": { "stringValue": "chat" } },+ { "key": "gen_ai.output.messages", "value": { "stringValue": "[{\"role\":\"assistant\",\"parts\":[{\"type\":\"text\",\"content\":\"Repeated output\"}]}]" } },+ { "key": "openjiuwen.turn.number", "value": { "intValue": "2" } },+ { "key": "openjiuwen.request.number", "value": { "intValue": "2" } },+ { "key": "openjiuwen.execution.subject.id", "value": { "stringValue": "main" } },+ { "key": "openjiuwen.execution.subject.request.number", "value": { "intValue": "2" } },+ { "key": "openjiuwen.trajectory.record.kind", "value": { "stringValue": "inference" } }+ ], "status": { "code": 1 }+ }] }] }]+ },+ {+ "resourceSpans": [{ "scopeSpans": [{ "spans": [{+ "traceId": "33333333333333333333333333333333", "spanId": "3000000000000003", "name": "llm.call",+ "startTimeUnixNano": "3000000000", "endTimeUnixNano": "3100000000",+ "attributes": [+ { "key": "gen_ai.operation.name", "value": { "stringValue": "chat" } },+ { "key": "gen_ai.output.messages", "value": { "stringValue": "[{\"role\":\"assistant\",\"parts\":[{\"type\":\"text\",\"content\":\"Repeated output\"}]}]" } },+ { "key": "openjiuwen.turn.number", "value": { "intValue": "1" } },+ { "key": "openjiuwen.request.number", "value": { "intValue": "3" } },+ { "key": "openjiuwen.execution.subject.id", "value": { "stringValue": "subagent-a" } },+ { "key": "openjiuwen.execution.subject.request.number", "value": { "intValue": "1" } },+ { "key": "openjiuwen.trajectory.record.kind", "value": { "stringValue": "inference" } }+ ], "status": { "code": 1 }+ }] }] }]+ },+ {+ "resourceSpans": [{ "scopeSpans": [{ "spans": [{+ "traceId": "33333333333333333333333333333333", "spanId": "4000000000000004", "name": "llm.call",+ "startTimeUnixNano": "3000000000", "endTimeUnixNano": "3200000000",+ "attributes": [+ { "key": "gen_ai.operation.name", "value": { "stringValue": "chat" } },+ { "key": "gen_ai.output.messages", "value": { "stringValue": "[{\"role\":\"assistant\",\"parts\":[{\"type\":\"text\",\"content\":\"Repeated output\"}]}]" } },+ { "key": "openjiuwen.turn.number", "value": { "intValue": "1" } },+ { "key": "openjiuwen.request.number", "value": { "intValue": "4" } },+ { "key": "openjiuwen.execution.subject.id", "value": { "stringValue": "subagent-a" } },+ { "key": "openjiuwen.execution.subject.request.number", "value": { "intValue": "2" } },+ { "key": "openjiuwen.trajectory.record.kind", "value": { "stringValue": "inference" } }+ ], "status": { "code": 1 }+ }] }] }]+ },+ {+ "resourceSpans": [{ "scopeSpans": [{ "spans": [{+ "traceId": "22222222222222222222222222222222", "spanId": "5000000000000005", "name": "llm.call",+ "startTimeUnixNano": "5000000000", "endTimeUnixNano": "5100000000",+ "attributes": [+ { "key": "gen_ai.operation.name", "value": { "stringValue": "chat" } },+ { "key": "gen_ai.output.messages", "value": { "stringValue": "[{\"role\":\"assistant\",\"parts\":[{\"type\":\"text\",\"content\":\"Repeated output\"}]}]" } },+ { "key": "openjiuwen.turn.number", "value": { "intValue": "2" } },+ { "key": "openjiuwen.request.number", "value": { "intValue": "5" } },+ { "key": "openjiuwen.execution.subject.id", "value": { "stringValue": "main" } },+ { "key": "openjiuwen.execution.subject.request.number", "value": { "intValue": "3" } },+ { "key": "openjiuwen.trajectory.record.kind", "value": { "stringValue": "inference" } }+ ], "status": { "code": 1 }+ }] }] }]+ },+ {+ "resourceSpans": [{ "scopeSpans": [{ "spans": [{+ "traceId": "44444444444444444444444444444444", "spanId": "6000000000000006", "name": "llm.call",+ "startTimeUnixNano": "6000000000", "endTimeUnixNano": "6100000000",+ "attributes": [+ { "key": "gen_ai.operation.name", "value": { "stringValue": "chat" } },+ { "key": "gen_ai.output.messages", "value": { "stringValue": "[{\"role\":\"assistant\",\"parts\":[{\"type\":\"text\",\"content\":\"Repeated output\"}]}]" } },+ { "key": "openjiuwen.turn.number", "value": { "intValue": "1" } },+ { "key": "openjiuwen.request.number", "value": { "intValue": "6" } },+ { "key": "openjiuwen.execution.subject.id", "value": { "stringValue": "subagent-b" } },+ { "key": "openjiuwen.execution.subject.request.number", "value": { "intValue": "1" } },+ { "key": "openjiuwen.trajectory.record.kind", "value": { "stringValue": "inference" } }+ ], "status": { "code": 1 }+ }] }] }]+ },+ {+ "resourceSpans": [{ "scopeSpans": [{ "spans": [{+ "traceId": "22222222222222222222222222222222", "spanId": "7000000000000007", "parentSpanId": "5000000000000005", "name": "tool.lookup",+ "startTimeUnixNano": "5200000000", "endTimeUnixNano": "5300000000",+ "attributes": [+ { "key": "gen_ai.operation.name", "value": { "stringValue": "execute_tool" } },+ { "key": "gen_ai.tool.name", "value": { "stringValue": "lookup" } },+ { "key": "openjiuwen.turn.number", "value": { "intValue": "2" } },+ { "key": "openjiuwen.step.number", "value": { "intValue": "1" } },+ { "key": "openjiuwen.execution.subject.id", "value": { "stringValue": "main" } },+ { "key": "openjiuwen.trajectory.record.kind", "value": { "stringValue": "tool" } }+ ], "status": { "code": 1 }+ }] }] }]+ }+]diff --git a/jiuwenswarm/channels/web/frontend/src/features/trajectory/index.ts b/jiuwenswarm/channels/web/frontend/src/features/trajectory/index.tsindex 0347b32a37..1c5d2907d4 100644--- a/jiuwenswarm/channels/web/frontend/src/features/trajectory/index.ts+++ b/jiuwenswarm/channels/web/frontend/src/features/trajectory/index.ts@@ -17,6 +17,17 @@ export {projectOtelTrajectory,} from './projector/otel-trajectory-projector.ts'export type { TrajectoryProjector } from './projector/otel-trajectory-projector.ts'+export {+ createTrajectoryV2Reducer,+ isTrajectoryV2Record,+ reduceTrajectoryV2,+} from './projector/trajectory-v2-reducer.ts'+export type {+ TrajectoryV2EventProjection,+ TrajectoryV2Reducer,+ TrajectoryV2Reduction,+ TrajectoryV2SubjectProjection,+} from './projector/trajectory-v2-reducer.ts'export {normalizeTrajectoryAttributes,normalizeTrajectoryStreamEvents,@@ -40,6 +51,7 @@ export type {} from './shared/otlp.ts'export type {TrajectoryGroupModel,+ TrajectoryDiagnostic,TrajectoryPromptSnapshot,TrajectoryRecordedFacts,TrajectoryRequest,diff --git a/jiuwenswarm/channels/web/frontend/src/features/trajectory/projector/attribute-resolver.ts b/jiuwenswarm/channels/web/frontend/src/features/trajectory/projector/attribute-resolver.tsindex 69454ad36e..c3c12faa19 100644--- a/jiuwenswarm/channels/web/frontend/src/features/trajectory/projector/attribute-resolver.ts+++ b/jiuwenswarm/channels/web/frontend/src/features/trajectory/projector/attribute-resolver.ts@@ -72,8 +72,16 @@ export interface NormalizedTrajectoryAttributes {agentName?: stringagentVersion?: stringagentDescription?: string+ executionSubjectId?: string+ executionSubjectKind?: string+ executionSubjectParentId?: string+ executionSubjectSessionId?: string+ executionSubjectRequestNumber?: bigint+ requestMessages?: unknown+ requestMessagesComplete?: booleansystemInstructions?: unknowninputMessages?: unknown+ inputMessagesComplete?: booleaninputMessageProvenance?: unknownoutputMessages?: unknowntoolDefinitions?: unknown@@ -123,6 +131,7 @@ type MutableNormalized = Omit<NormalizedTrajectoryAttributes, 'sources'> & {interface Resolved<T> {key: stringvalue: T+ complete?: boolean}interface NormalizedPart {@@ -137,6 +146,10 @@ interface NormalizedPart {interface NormalizedMessage {role: stringparts: readonly NormalizedPart[]+ openjiuwen?: {+ kind: 'prompt_attachment_history'+ mode: 'snapshot' | 'delta'+ }}const LEGACY = {@@ -153,12 +166,6 @@ const LEGACY = {toolCallArguments: 'gen_ai.tool.input',toolCallResult: 'gen_ai.tool.output',toolCalls: 'gen_ai.tool_calls',- promptScalar: 'gen_ai.prompt',- completionScalar: 'gen_ai.completion',- promptPrefix: 'gen_ai.prompt',- completionPrefix: 'gen_ai.completion',- langfusePromptPrefix: 'langfuse.gen_ai.prompt',- langfuseCompletionPrefix: 'langfuse.gen_ai.completion',langfuseInput: 'langfuse.observation.input',langfuseOutput: 'langfuse.observation.output',langfuseObservationType: 'langfuse.observation.type',@@ -362,6 +369,44 @@ function normalizedToolCall(value: unknown): NormalizedPart | undefined {}}+function canonicalValue(value: unknown): string {+ if (Array.isArray(value)) return `[${value.map(canonicalValue).join(',')}]`+ const valueObject = object(value)+ if (valueObject === undefined) return JSON.stringify(value) ?? String(value)+ return `{${Object.keys(valueObject).sort().map(key => (+ `${JSON.stringify(key)}:${canonicalValue(valueObject[key])}`+ )).join(',')}}`+}++function sameToolCall(left: NormalizedPart, right: NormalizedPart): boolean {+ if (left.type !== 'tool_call' || right.type !== 'tool_call') return false+ if (left.id !== undefined || right.id !== undefined) {+ return left.id !== undefined && left.id === right.id+ }+ return left.name !== undefined+ && left.name === right.name+ && canonicalValue(left.arguments) === canonicalValue(right.arguments)+}++function mergeToolCallRepresentations(+ primaryParts: readonly NormalizedPart[],+ aliasCalls: readonly NormalizedPart[],+): NormalizedPart[] {+ const consumedPrimaryCalls = new Set<number>()+ const merged = [...primaryParts]+ for (const call of aliasCalls) {+ const primaryIndex = primaryParts.findIndex((part, index) => (+ !consumedPrimaryCalls.has(index) && sameToolCall(part, call)+ ))+ if (primaryIndex >= 0) {+ consumedPrimaryCalls.add(primaryIndex)+ continue+ }+ merged.push(call)+ }+ return merged+}+function normalizedContentParts(value: unknown, reasoning: boolean): NormalizedPart[] {if (typeof value === 'string') return [{ type: reasoning ? 'reasoning' : 'text', content: value }]if (!Array.isArray(value)) {@@ -410,15 +455,30 @@ function normalizedMessage(value: unknown, defaultRole: string): NormalizedMessaconst role = typeof message.role === 'string' ? message.role : defaultRoleconst reasoning = message.is_reasoning === true || role === 'reasoning'const rawParts = message.parts ?? message.content ?? message.text- const parts = normalizedContentParts(rawParts, reasoning)+ let parts = normalizedContentParts(rawParts, reasoning)const calls = message.tool_calls ?? message.toolCallsif (Array.isArray(calls)) {- for (const call of calls) {+ const aliasCalls = calls.flatMap((call): NormalizedPart[] => {const normalized = normalizedToolCall(call)- if (normalized !== undefined) parts.push(normalized)- }+ return normalized === undefined ? [] : [normalized]+ })+ parts = mergeToolCallRepresentations(parts, aliasCalls)+ }+ const openjiuwen = object(message.openjiuwen)+ const promptAttachmentHistory = openjiuwen?.kind === 'prompt_attachment_history'+ && (openjiuwen.mode === 'snapshot' || openjiuwen.mode === 'delta')+ ? {+ kind: openjiuwen.kind,+ mode: openjiuwen.mode,+ } as const+ : undefined+ return {+ role: role === 'reasoning' ? 'assistant' : role,+ parts,+ ...(promptAttachmentHistory === undefined+ ? {}+ : { openjiuwen: promptAttachmentHistory }),}- return { role: role === 'reasoning' ? 'assistant' : role, parts }}function normalizedMessages(value: unknown, defaultRole: string): readonly NormalizedMessage[] {@@ -486,7 +546,7 @@ function indexedMessages(attributes: OtlpAttributeMap,prefix: string,defaultRole: string,-): readonly NormalizedMessage[] | undefined {+): { messages: readonly NormalizedMessage[]; complete: boolean } | undefined {const indexes = new Set<number>()const expression = new RegExp(`^${prefix.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\.(\\d+)\\.`)for (const key of attributes.keys()) {@@ -512,7 +572,12 @@ function indexedMessages(}messages.push({ role: role === 'reasoning' ? 'assistant' : role, parts })}- return messages+ const orderedIndexes = [...indexes].sort((left, right) => left - right)+ return {+ messages,+ complete: orderedIndexes[0] === 0+ && orderedIndexes.every((index, position) => index === position),+ }}function resolveMessages(@@ -527,11 +592,13 @@ function resolveMessages(const value = attributes.get(key)if (value === undefined) continueconst messages = normalizedStructuredMessages(flexibleValue(value), defaultRole)- if (messages !== undefined) return { key, value: messages }+ if (messages !== undefined) return { key, value: messages, complete: true }}for (const prefix of indexedPrefixes) {const indexed = indexedMessages(attributes, prefix, defaultRole)- if (indexed !== undefined) return { key: `${prefix}.*`, value: indexed }+ if (indexed !== undefined) {+ return { key: `${prefix}.*`, value: indexed.messages, complete: indexed.complete }+ }}const observation = resolveFlexible(attributes, [observationKey])if (observation !== undefined) {@@ -588,6 +655,36 @@ function systemFromMessages(value: unknown): readonly NormalizedPart[] | undefinreturn systemParts.length === 0 ? undefined : systemParts}+/**+ * Rebuild the full request as one ordered message list.+ *+ * The standard attributes split the request in two: the instructions given+ * outside the chat history, and the history itself. Views that reason about+ * where a message sat -- which system turn is the prompt-attachment snapshot,+ * above all -- need them back in one sequence, instructions first.+ */+function composedRequestMessages(+ attributes: OtlpAttributeMap,+): Resolved<unknown> | undefined {+ const rawInput = attributes.get(STANDARD_ATTRIBUTES.inputMessages)+ if (rawInput === undefined) return undefined+ const history = normalizedStructuredMessages(flexibleValue(rawInput), 'user')+ if (history === undefined) return undefined++ const instructions = resolveStructuredParts(attributes, [+ STANDARD_ATTRIBUTES.systemInstructions,+ ])+ const leading = instructions === undefined+ ? []+ : [{ role: 'system', parts: instructions.value }]+ return {+ key: STANDARD_ATTRIBUTES.inputMessages,+ value: [...leading, ...history],+ complete: true,+ }+}++function withoutSystemMessages(value: unknown): unknown {if (!Array.isArray(value)) return valuereturn value.filter((candidate) => object(candidate)?.role !== 'system')@@ -802,15 +899,36 @@ export function normalizeTrajectoryAttributes(assign(target, 'agentDescription', resolveString(raw, [STANDARD_ATTRIBUTES.agentDescription,]))+ assign(target, 'executionSubjectId', resolveString(raw, [+ OPENJIUWEN_ATTRIBUTES.executionSubjectId,+ ]))+ assign(target, 'executionSubjectKind', resolveString(raw, [+ OPENJIUWEN_ATTRIBUTES.executionSubjectKind,+ ]))+ assign(target, 'executionSubjectParentId', resolveString(raw, [+ OPENJIUWEN_ATTRIBUTES.executionSubjectParentId,+ ]))+ assign(target, 'executionSubjectSessionId', resolveString(raw, [+ OPENJIUWEN_ATTRIBUTES.executionSubjectSessionId,+ ]))+ assign(target, 'executionSubjectRequestNumber', resolvePositiveInt64(raw, [+ OPENJIUWEN_ATTRIBUTES.executionSubjectRequestNumber,+ ]))++ const requestMessages = composedRequestMessages(raw)+ assign(target, 'requestMessages', requestMessages)+ if (requestMessages !== undefined) {+ target.requestMessagesComplete = requestMessages.complete ?? true+ }const inputMessages = resolveMessages(raw,[STANDARD_ATTRIBUTES.inputMessages,],- [LEGACY.promptPrefix, LEGACY.langfusePromptPrefix],+ [],LEGACY.langfuseInput,- [LEGACY.promptScalar],+ [],'user',)if (inputMessages !== undefined) {@@ -828,6 +946,7 @@ export function normalizeTrajectoryAttributes(key: inputMessages.key,value: withoutSystemMessages(inputMessages.value),})+ target.inputMessagesComplete = inputMessages.complete ?? true} else {assign(target, 'systemInstructions', resolveStructuredParts(raw, [STANDARD_ATTRIBUTES.systemInstructions,@@ -842,21 +961,22 @@ export function normalizeTrajectoryAttributes([STANDARD_ATTRIBUTES.outputMessages,],- [LEGACY.completionPrefix, LEGACY.langfuseCompletionPrefix],+ [],LEGACY.langfuseOutput,- [LEGACY.completionScalar],+ [],'assistant',)if (outputMessages !== undefined) {const calls = resolveFlexible(raw, [LEGACY.toolCalls])- const messages = normalizedMessages(outputMessages.value, 'assistant').map((message, index) => {- if (index !== 0 || calls === undefined || !Array.isArray(calls.value)) return message- const parts = [...message.parts]- for (const call of calls.value) {+ const aliasCalls = calls === undefined || !Array.isArray(calls.value)+ ? []+ : calls.value.flatMap((call): NormalizedPart[] => {const normalized = normalizedToolCall(call)- if (normalized !== undefined) parts.push(normalized)- }- return { ...message, parts }+ return normalized === undefined ? [] : [normalized]+ })+ const messages = normalizedMessages(outputMessages.value, 'assistant').map((message, index) => {+ if (index !== 0 || aliasCalls.length === 0) return message+ return { ...message, parts: mergeToolCallRepresentations(message.parts, aliasCalls) }})assign(target, 'outputMessages', { key: outputMessages.key, value: messages })}@@ -879,6 +999,7 @@ export function normalizeTrajectoryAttributes(]))assign(target, 'toolResourceId', resolveString(raw, [OPENJIUWEN_ATTRIBUTES.toolResourceId,+ STANDARD_ATTRIBUTES.toolId,]))assign(target, 'openJiuwenToolType', resolveString(raw, [OPENJIUWEN_ATTRIBUTES.toolType,diff --git a/jiuwenswarm/channels/web/frontend/src/features/trajectory/projector/otel-trajectory-projector.ts b/jiuwenswarm/channels/web/frontend/src/features/trajectory/projector/otel-trajectory-projector.tsindex 120b2ab1fd..9f4d4de8bc 100644--- a/jiuwenswarm/channels/web/frontend/src/features/trajectory/projector/otel-trajectory-projector.ts+++ b/jiuwenswarm/channels/web/frontend/src/features/trajectory/projector/otel-trajectory-projector.ts@@ -7,8 +7,18 @@ import {readStringAttribute,} from '../semconv/attributes.ts'import {- GEN_AI_OPERATIONS, STANDARD_ATTRIBUTES,+ GEN_AI_OPERATIONS, OPENJIUWEN_ATTRIBUTES, STANDARD_ATTRIBUTES,} from '../semconv/constants.ts'+import {+ createTrajectoryV2Reducer,+ isTrajectoryV2Record,+ reduceTrajectoryV2,+} from './trajectory-v2-reducer.ts'+import type {+ TrajectoryV2EventProjection,+ TrajectoryV2Reducer,+} from './trajectory-v2-reducer.ts'+export { createTrajectoryV2Reducer, reduceTrajectoryV2 } from './trajectory-v2-reducer.ts'import type {NormalizedTrajectoryAttributes, NormalizedTrajectoryStreamEvent,} from './attribute-resolver.ts'@@ -20,10 +30,12 @@ import type {} from '../shared/otlp.ts'import type {TrajectoryPromptSnapshot,+ TrajectoryDiagnostic,TrajectoryRecordedFacts,TrajectoryRequest,TrajectoryRequestConfig,TrajectorySnapshot,+ TrajectorySystemMessage,TrajectoryToolSchema,TrajectoryTurnModel,TrajectoryUsage,@@ -39,6 +51,7 @@ interface ProjectedSpan {parentSpanId: string | undefinedrequest: OtlpExportTraceServiceRequestsourceSequence: number | undefined+ identityRequestNumber: number | undefinedrequestNumber: number | undefinedstreamEvents: readonly NormalizedTrajectoryStreamEvent[]span: OtlpSpan@@ -46,10 +59,13 @@ interface ProjectedSpan {traceId: stringturn: numberlifecycle: 'running' | 'completed' | 'error'+ owningRequestRecordId?: string}export interface TrajectoryProjectionOptions {lifecycleByRecordId?: ReadonlyMap<string, 'running' | 'completed' | 'error'>+ sessionCumulativeUsageByRequestIdentity?: ReadonlyMap<string, TrajectoryUsage>+ v2Reducer?: TrajectoryV2Reducer}interface StructuredPart {@@ -65,6 +81,7 @@ interface StructuredMessage {inputIndex?: numberinputKind?: 'prompt_attachment'parts: readonly StructuredPart[]+ promptAttachmentHistoryMode?: 'snapshot' | 'delta'role: string}@@ -81,7 +98,14 @@ interface MutableTurn {interface InferenceInputProjection {messages: readonly StructuredMessage[]- prompt: TrajectoryPromptSnapshot | undefined+ prompts: readonly PromptCellProjection[]+}++interface PromptCellProjection {+ prompt: TrajectoryPromptSnapshot+ previous?: TrajectoryPromptSnapshot+ systemMessageIndex?: number+ text: string}interface ToolResultFact {@@ -171,11 +195,12 @@ function cellIndex(span: ProjectedSpan, suffix: string): number {}function requestRecordIdentity(span: ProjectedSpan): string | undefined {+ if (span.owningRequestRecordId !== undefined) return span.owningRequestRecordIdif (span.attributes.inferenceId !== undefined) {return `${span.traceId}:inference:${span.attributes.inferenceId}`}- if (span.requestNumber !== undefined) {- return `${span.traceId}:request:${span.requestNumber}`+ if (span.identityRequestNumber !== undefined) {+ return `${span.traceId}:request:${span.identityRequestNumber}`}return isInference(span) ? `${span.traceId}:${span.span.spanId}:request` : undefined}@@ -224,7 +249,16 @@ function structuredMessages(value: unknown): readonly StructuredMessage[] {return value.flatMap((candidate): StructuredMessage[] => {const message = object(candidate)if (message === undefined || typeof message.role !== 'string') return []- return [{ role: message.role, parts: structuredParts(message.parts) }]+ const openjiuwen = object(message.openjiuwen)+ const historyMode = openjiuwen?.kind === 'prompt_attachment_history'+ && (openjiuwen.mode === 'snapshot' || openjiuwen.mode === 'delta')+ ? openjiuwen.mode+ : undefined+ return [{+ role: message.role,+ parts: structuredParts(message.parts),+ ...(historyMode === undefined ? {} : { promptAttachmentHistoryMode: historyMode }),+ }]})}@@ -427,15 +461,63 @@ function toolSchemas(value: unknown): readonly TrajectoryToolSchema[] {function promptSnapshot(attributes: NormalizedTrajectoryAttributes): TrajectoryPromptSnapshot | undefined {const instructions = structuredParts(attributes.systemInstructions)+ const requestSystemMessages: TrajectorySystemMessage[] = []+ let promptAttachmentSlot: number | undefined+ structuredMessages(attributes.requestMessages).forEach((message, index) => {+ if (message.role !== 'system') return+ const content = message.parts+ .flatMap(part => part.content === undefined ? [] : [part.content])+ .join('\n')+ const historyMode = message.promptAttachmentHistoryMode+ ?? promptAttachmentHistoryModeFromContent(content)+ if (historyMode === 'snapshot') {+ promptAttachmentSlot ??= index+ }+ if (historyMode === 'delta' && promptAttachmentSlot !== undefined) {+ const slotIndex = requestSystemMessages.findIndex(candidate => (+ candidate.index === promptAttachmentSlot+ ))+ const replacement = { index: promptAttachmentSlot, content }+ if (slotIndex === -1) requestSystemMessages.push(replacement)+ else requestSystemMessages[slotIndex] = replacement+ return+ }+ requestSystemMessages.push({ index, content })+ })+ const systemMessages = requestSystemMessages.length > 0+ ? requestSystemMessages+ : instructions.length === 0+ ? []+ : [{+ index: 0,+ content: instructions+ .flatMap(part => part.content === undefined ? [] : [part.content])+ .join('\n\n'),+ }]const tools = toolSchemas(attributes.toolDefinitions)- if (instructions.length === 0 && tools.length === 0) return undefined+ if (systemMessages.length === 0 && tools.length === 0) return undefinedreturn {config: requestConfig(attributes),- system: instructions.flatMap(part => part.content === undefined ? [] : [part.content]).join('\n\n'),+ system: systemMessages.map(message => message.content).join('\n\n'),+ systemMessages,tools,}}+function promptAttachmentHistoryModeFromContent(+ content: string,+): 'snapshot' | 'delta' | undefined {+ if (+ content.startsWith('以下动态上下文当前有效')+ || content.startsWith('The following dynamic context is currently active.')+ ) return 'snapshot'+ if (+ content.startsWith('以下动态上下文已经变化')+ || content.startsWith('The following dynamic context has changed.')+ ) return 'delta'+ return undefined+}+function usage(attributes: NormalizedTrajectoryAttributes): TrajectoryUsage {const input = nonNegativeSafeInteger(attributes.usageInputTokens)const cacheRead = nonNegativeSafeInteger(attributes.usageCacheReadTokens)@@ -453,25 +535,6 @@ function usage(attributes: NormalizedTrajectoryAttributes): TrajectoryUsage {}}-function addUsage(total: TrajectoryUsage, next: TrajectoryUsage): TrajectoryUsage {- const sum = (left: number | undefined, right: number | undefined): number | undefined =>- left === undefined && right === undefined ? undefined : (left ?? 0) + (right ?? 0)- const input = sum(total.input, next.input)- const cacheRead = sum(total.cacheRead, next.cacheRead)- const cacheWrite = sum(total.cacheWrite, next.cacheWrite)- const output = sum(total.output, next.output)- const reasoning = sum(total.reasoning, next.reasoning)- const grandTotal = sum(total.total, next.total)- return {- ...(input === undefined ? {} : { input }),- ...(cacheRead === undefined ? {} : { cacheRead }),- ...(cacheWrite === undefined ? {} : { cacheWrite }),- ...(output === undefined ? {} : { output }),- ...(reasoning === undefined ? {} : { reasoning }),- ...(grandTotal === undefined ? {} : { total: grandTotal }),- }-}-function status(projected: ProjectedSpan): 'complete' | 'running' | 'error' {if (projected.lifecycle === 'running') return 'running'if (projected.lifecycle === 'error') return 'error'@@ -526,11 +589,17 @@ function recordKind(span: ProjectedSpan): string | undefined {function isInference(span: ProjectedSpan): boolean {const kind = recordKind(span)if (kind !== undefined) return kind === 'inference'- const name = knownOperation(span)- if (name !== undefined) return name === GEN_AI_OPERATIONS.chat- || name === GEN_AI_OPERATIONS.generateContent- || name === GEN_AI_OPERATIONS.textCompletion- return span.attributes.langfuseObservationType === 'generation'+ const operationName = operation(span)+ if (operationName !== undefined) return operationName === GEN_AI_OPERATIONS.chat+ || operationName === GEN_AI_OPERATIONS.generateContent+ || operationName === GEN_AI_OPERATIONS.textCompletion+ const observationType = span.attributes.langfuseObservationType+ if (observationType !== undefined) return observationType === 'generation'+ return span.span.name === 'llm.call' && (+ span.attributes.inferenceId !== undefined+ || span.attributes.inputMessages !== undefined+ || span.attributes.outputMessages !== undefined+ )}function isTool(span: ProjectedSpan): boolean {@@ -542,6 +611,42 @@ function isTool(span: ProjectedSpan): boolean {return span.span.name.startsWith('tool.') || span.span.name.startsWith('execute_tool')}+function isRoutedAskUserResult(+ span: ProjectedSpan,+ root: ProjectedSpan | undefined,+): boolean {+ const attributes = span.attributes+ const conversationId = attributes.conversationId+ const subjectId = attributes.executionSubjectId+ const subjectKind = attributes.executionSubjectKind+ const subjectSessionId = attributes.executionSubjectSessionId+ const mainSubject = subjectId === 'main'+ && subjectKind === 'main_agent'+ && subjectSessionId === conversationId+ const subagentSubject = subjectKind === 'subagent'+ && attributes.executionSubjectParentId !== undefined+ && subjectSessionId !== undefined+ && conversationId !== undefined+ && (subjectSessionId === conversationId+ || subjectSessionId.startsWith(`${conversationId}_sub_`))+ const rootAttributes = root?.attributes+ const sameRootOwner = rootAttributes !== undefined+ && rootAttributes.conversationId === conversationId+ && rootAttributes.executionSubjectId === subjectId+ && rootAttributes.executionSubjectKind === subjectKind+ && rootAttributes.executionSubjectSessionId === subjectSessionId+ return attributes.toolAuthoritative === true+ && span.attributes.toolName === 'ask_user'+ && attributes.toolCallId !== undefined+ && attributes.toolCallResult !== undefined+ && conversationId !== undefined+ && subjectId !== undefined+ && attributes.requestId !== undefined+ && positiveSafeInteger(attributes.turnNumber) !== undefined+ && (mainSubject || subagentSubject)+ && sameRootOwner+}+function isCompaction(span: ProjectedSpan): boolean {return recordKind(span) === 'compaction'}@@ -569,17 +674,24 @@ function inputCells(projection: InferenceInputProjection,): TrajectoryCell[] {const cells: TrajectoryCell[] = []- const prompt = projection.prompt- if (prompt !== undefined) {- const text = prompt.system !== ''- ? prompt.system- : `${prompt.tools.length} tool definition${prompt.tools.length === 1 ? '' : 's'}`+ for (const promptProjection of projection.prompts) {cells.push({- ...spanCellBase(span, 'system'),+ ...spanCellBase(+ span,+ promptProjection.systemMessageIndex === undefined+ ? 'system:tools'+ : `system:${promptProjection.systemMessageIndex}`,+ ),timeSeconds: null,kind: 'system',- text,- promptDetail: prompt,+ text: promptProjection.text,+ promptDetail: promptProjection.prompt,+ ...(promptProjection.systemMessageIndex === undefined+ ? {}+ : { promptSystemMessageIndex: promptProjection.systemMessageIndex }),+ ...(promptProjection.previous === undefined+ ? {}+ : { previousPromptDetail: promptProjection.previous }),})}projection.messages.forEach((message, index) => {@@ -698,6 +810,7 @@ function toolCell(return {...spanCellBase(span, 'tool'),kind: nested ? 'subtool' : 'tool',+ ...(requestRecordIdentity(span) === undefined ? { requestless: true } : {}),text: inputText === undefined ? name : `${name} · ${inputText.replace(/\s+/g, ' ').slice(0, 160)}`,callId,...(inputText === undefined ? {} : { inputDetail: inputText }),@@ -808,8 +921,33 @@ function provenanceAttachmentIndexes(return new Set(indexes)}-function behaviorSessionKey(span: ProjectedSpan): string {- return span.attributes.conversationId ?? `trace:${span.traceId}`+function spanIdentity(span: ProjectedSpan): string {+ return `${span.traceId}\u0000${span.span.spanId}`+}++function behaviorLineage(+ span: ProjectedSpan,+ spanByIdentity: ReadonlyMap<string, ProjectedSpan>,+): readonly string[] {+ const lineage: string[] = []+ const visited = new Set<string>()+ let parentSpanId = span.parentSpanId+ while (parentSpanId !== undefined) {+ const identity = `${span.traceId}\u0000${parentSpanId}`+ if (visited.has(identity)) break+ visited.add(identity)+ const parent = spanByIdentity.get(identity)+ if (parent === undefined) break+ if (isTool(parent)) lineage.push(parent.span.spanId)+ parentSpanId = parent.parentSpanId+ }+ return lineage.reverse()+}++function behaviorSessionKey(span: ProjectedSpan, lineage: readonly string[]): string {+ const conversation = span.attributes.conversationId ?? `trace:${span.traceId}`+ const subject = span.attributes.executionSubjectId ?? 'legacy-main'+ return `${conversation}\u0000${subject}\u0000${lineage.join('/')}`}function compareInferenceBehavior(left: ProjectedSpan, right: ProjectedSpan): number {@@ -820,6 +958,53 @@ function compareInferenceBehavior(left: ProjectedSpan, right: ProjectedSpan): nu|| left.span.spanId.localeCompare(right.span.spanId)}+function comparePhysicalInference(left: ProjectedSpan, right: ProjectedSpan): number {+ return compareBigint(left.startTimeUnixNano, right.startTimeUnixNano)+ || left.traceId.localeCompare(right.traceId)+ || left.span.spanId.localeCompare(right.span.spanId)+}++function executionSubjectKey(span: ProjectedSpan): string {+ const session = span.attributes.conversationId ?? 'legacy-session'+ const subject = span.attributes.executionSubjectId ?? 'legacy-main'+ return `${session}\u0000${subject}`+}++function assignSubjectRequestNumbers(spans: readonly ProjectedSpan[]): ProjectedSpan[] {+ const inferenceGroups = new Map<string, ProjectedSpan[]>()+ for (const span of spans) {+ if (!isInference(span)) continue+ const key = executionSubjectKey(span)+ const group = inferenceGroups.get(key) ?? []+ group.push(span)+ inferenceGroups.set(key, group)+ }+ const displayNumberByIdentity = new Map<string, number>()+ for (const group of inferenceGroups.values()) {+ const ordered = [...group].sort(comparePhysicalInference)+ const explicitNumbers = ordered.map(span => (+ positiveSafeInteger(span.attributes.executionSubjectRequestNumber)+ ))+ const hasCompleteMonotonicSequence = explicitNumbers.every((number, index) => (+ number === index + 1+ ))+ for (const [index, span] of ordered.entries()) {+ // A partially upgraded or malformed subject must be rebuilt as one+ // chronological sequence. Mixing explicit and inferred values can+ // otherwise create duplicates or gaps while a live archive is loading.+ const number = hasCompleteMonotonicSequence+ ? explicitNumbers[index] as number+ : index + 1+ displayNumberByIdentity.set(spanIdentity(span), number)+ }+ }+ return spans.map(span => (+ !isInference(span)+ ? span+ : { ...span, requestNumber: displayNumberByIdentity.get(spanIdentity(span)) ?? 1 }+ ))+}+function consumePriorOutput(pending: StructuredMessage[],message: StructuredMessage,@@ -916,24 +1101,87 @@ function outputReplayMatches(}function promptBehaviorIdentity(prompt: TrajectoryPromptSnapshot): string {- return structuralIdentity({ system: prompt.system, tools: prompt.tools })+ return structuralIdentity({ systemMessages: prompt.systemMessages, tools: prompt.tools })+}++function promptCellProjections(+ prompt: TrajectoryPromptSnapshot | undefined,+ previous: TrajectoryPromptSnapshot | undefined,+): readonly PromptCellProjection[] {+ if (prompt === undefined) return []+ if (previous === undefined) {+ if (prompt.systemMessages.length > 0) {+ return prompt.systemMessages.map(message => ({+ prompt,+ systemMessageIndex: message.index,+ text: message.content,+ }))+ }+ return [{+ prompt,+ text: `${prompt.tools.length} tool definition${prompt.tools.length === 1 ? '' : 's'}`,+ }]+ }+ if (promptBehaviorIdentity(prompt) === promptBehaviorIdentity(previous)) return []++ const beforeByIndex = new Map(previous.systemMessages.map(message => [message.index, message]))+ const afterByIndex = new Map(prompt.systemMessages.map(message => [message.index, message]))+ const indexes = [...new Set([...beforeByIndex.keys(), ...afterByIndex.keys()])]+ .sort((left, right) => left - right)+ const changed = indexes.flatMap((index): PromptCellProjection[] => {+ const before = beforeByIndex.get(index)+ const after = afterByIndex.get(index)+ if (before?.content === after?.content) return []+ return [{+ prompt,+ previous,+ systemMessageIndex: index,+ text: after?.content ?? 'System message removed',+ }]+ })+ if (structuralIdentity(previous.tools) !== structuralIdentity(prompt.tools)) {+ changed.push({+ prompt,+ previous,+ text: `${prompt.tools.length} tool definition${prompt.tools.length === 1 ? '' : 's'}`,+ })+ }+ return changed}-function projectInferenceInputs(spans: readonly ProjectedSpan[]): {+function projectInferenceInputs(+ spans: readonly ProjectedSpan[],+ v2RequestIds: ReadonlySet<string>,+): {inputsBySpanId: ReadonlyMap<string, InferenceInputProjection>toolResultById: ReadonlyMap<string, ToolResultFact>toolResultBySpanId: ReadonlyMap<string, ToolResultFact>+ diagnostics: readonly TrajectoryDiagnostic[]} {const inputsBySpanId = new Map<string, InferenceInputProjection>()const previousInputsBySession = new Map<string, readonly IndexedMessage[]>()- const previousPromptBySession = new Map<string, string>()+ const previousPromptBySession = new Map<string, TrajectoryPromptSnapshot>()const previousOutputsBySession = new Map<string, readonly StructuredMessage[]>()const toolResults: ToolResultFact[] = []+ const diagnostics: TrajectoryDiagnostic[] = []+ const spanByIdentity = new Map(spans.map(span => [spanIdentity(span), span]))for (const span of spans.filter(isInference).sort(compareInferenceBehavior)) {- const sessionKey = behaviorSessionKey(span)+ const lineage = behaviorLineage(span, spanByIdentity)+ const sessionKey = behaviorSessionKey(span, lineage)+ const parentSessionKey = lineage.length === 0+ ? undefined+ : behaviorSessionKey(span, lineage.slice(0, -1))const currentInputs = structuredMessages(span.attributes.inputMessages)- const previousInputs = previousInputsBySession.get(sessionKey) ?? []+ const handledByV2 = span.attributes.requestId !== undefined+ && v2RequestIds.has(span.attributes.requestId)+ if (handledByV2) {+ inputsBySpanId.set(span.span.spanId, { messages: [], prompts: [] })+ previousOutputsBySession.set(sessionKey, structuredMessages(span.attributes.outputMessages))+ continue+ }+ const previousInputs = previousInputsBySession.get(sessionKey)+ ?? (parentSessionKey === undefined ? [] : previousInputsBySession.get(parentSessionKey) ?? [])const attachmentIndexes = provenanceAttachmentIndexes(span.attributes.inputMessageProvenance)const attachmentIndexSet = new Set(currentInputs.flatMap((message, index): number[] => {const attachment = attachmentIndexes === undefined@@ -945,7 +1193,10 @@ function projectInferenceInputs(spans: readonly ProjectedSpan[]): {attachmentIndexSet.has(inputIndex) ? [] : [{ inputIndex, message }]))const insertedIndexes = lcsInsertedInputIndexes(previousInputs, currentOrdinary)- const replayableOutputs = [...(previousOutputsBySession.get(sessionKey) ?? [])]+ const replayableOutputs = [...(+ previousOutputsBySession.get(sessionKey)+ ?? (parentSessionKey === undefined ? [] : previousOutputsBySession.get(parentSessionKey) ?? [])+ )]const messages = currentInputs.flatMap((message, index): StructuredMessage[] => {const attachment = attachmentIndexSet.has(index)if (!insertedIndexes.has(index) && !attachment) return []@@ -971,13 +1222,13 @@ function projectInferenceInputs(spans: readonly ProjectedSpan[]): {}]})const prompt = promptSnapshot(span.attributes)- const promptIdentity = prompt === undefined ? undefined : promptBehaviorIdentity(prompt)const previousPrompt = previousPromptBySession.get(sessionKey)+ ?? (parentSessionKey === undefined ? undefined : previousPromptBySession.get(parentSessionKey))inputsBySpanId.set(span.span.spanId, {messages,- prompt: promptIdentity === undefined || promptIdentity === previousPrompt ? undefined : prompt,+ prompts: promptCellProjections(prompt, previousPrompt),})- if (promptIdentity !== undefined) previousPromptBySession.set(sessionKey, promptIdentity)+ if (prompt !== undefined) previousPromptBySession.set(sessionKey, prompt)previousInputsBySession.set(sessionKey, currentOrdinary)const outputs = structuredMessages(span.attributes.outputMessages)previousOutputsBySession.set(sessionKey, outputs)@@ -1012,7 +1263,7 @@ function projectInferenceInputs(spans: readonly ProjectedSpan[]): {consumedByTrace.set(span.traceId, consumed)}}- return { inputsBySpanId, toolResultById, toolResultBySpanId }+ return { inputsBySpanId, toolResultById, toolResultBySpanId, diagnostics }}function compactionCell(span: ProjectedSpan, inference: ProjectedSpan | undefined): TrajectoryCell {@@ -1039,6 +1290,7 @@ function requestFor(span: ProjectedSpan,purpose: 'assistant' | 'compaction',rootAttributes: NormalizedTrajectoryAttributes | undefined,+ sessionCumulativeUsageByRequestIdentity: ReadonlyMap<string, TrajectoryUsage> | undefined,): TrajectoryRequest {const requestNumber = span.requestNumber ?? 1const step = positiveSafeInteger(span.attributes.stepNumber) ?? 1@@ -1062,10 +1314,15 @@ function requestFor(requestConfig: requestConfig(span.attributes),recordedFacts: facts,usage: usageValue,+ cumulativeUsage: span.attributes.inferenceId === undefined+ ? undefined+ : sessionCumulativeUsageByRequestIdentity?.get(+ `${span.traceId}\u0000${span.attributes.inferenceId}`,+ ),}const defined = Object.fromEntries(Object.entries(base).filter(([, value]) => value !== undefined))return purpose === 'compaction'- ? { ...defined, purpose, turn: null, step: 0 } as TrajectoryRequest+ ? { ...defined, purpose, turn: span.turn, step } as TrajectoryRequest: { ...defined, purpose, turn: span.turn, step } as TrajectoryRequest}@@ -1109,18 +1366,77 @@ function normalize(: BigInt(span.endTimeUnixNano),explicitTurn: positiveSafeInteger(attributes.turnNumber),sourceSequence: nonNegativeSafeInteger(attributes.sourceSequence),- requestNumber: positiveSafeInteger(attributes.requestNumber),+ identityRequestNumber: positiveSafeInteger(attributes.requestNumber),+ requestNumber: undefined,streamEvents: normalizeTrajectoryStreamEvents(span.events),lifecycle,}})).sort(compareSpans)- const currentByTrace = new Map<string, number>()+ const numbered = assignSubjectRequestNumbers(spans)+ return assignRequestOwnership(numbered)+}++function sameStep(left: ProjectedSpan, right: ProjectedSpan): boolean {+ if (left.traceId !== right.traceId) return false+ if (left.attributes.stepId !== undefined || right.attributes.stepId !== undefined) {+ return left.attributes.stepId !== undefined+ && left.attributes.stepId === right.attributes.stepId+ }+ const leftStep = positiveSafeInteger(left.attributes.stepNumber)+ const rightStep = positiveSafeInteger(right.attributes.stepNumber)+ return leftStep !== undefined && leftStep === rightStep+}++function inferenceRequestIdentity(span: ProjectedSpan): string {+ if (span.attributes.inferenceId !== undefined) {+ return `${span.traceId}:inference:${span.attributes.inferenceId}`+ }+ if (span.identityRequestNumber !== undefined) {+ return `${span.traceId}:request:${span.identityRequestNumber}`+ }+ return `${span.traceId}:${span.span.spanId}:request`+}++function assignRequestOwnership(spans: readonly ProjectedSpan[]): ProjectedSpan[] {+ const spanByIdentity = new Map(spans.map(span => [spanIdentity(span), span]))+ const inferenceById = new Map(spans.filter(isInference).flatMap((span): Array<[string, ProjectedSpan]> => (+ span.attributes.inferenceId === undefined+ ? []+ : [[`${span.traceId}\u0000${span.attributes.inferenceId}`, span]]+ )))+ const inferences = spans.filter(isInference)return spans.map((span) => {- if (!isInference(span)) return span- const current = currentByTrace.get(span.traceId) ?? 0- const requestNumber = span.requestNumber ?? current + 1- currentByTrace.set(span.traceId, Math.max(current, requestNumber))- return { ...span, requestNumber }+ if (!isTool(span)) return span+ if (span.attributes.inferenceId !== undefined) {+ const inference = inferenceById.get(`${span.traceId}\u0000${span.attributes.inferenceId}`)+ return {+ ...span,+ owningRequestRecordId: inference === undefined+ ? `${span.traceId}:inference:${span.attributes.inferenceId}`+ : inferenceRequestIdentity(inference),+ }+ }+ const visited = new Set<string>()+ let parentSpanId = span.parentSpanId+ while (parentSpanId !== undefined) {+ const identity = `${span.traceId}\u0000${parentSpanId}`+ if (visited.has(identity)) break+ visited.add(identity)+ const parent = spanByIdentity.get(identity)+ if (parent === undefined) break+ if (isInference(parent)) {+ return { ...span, owningRequestRecordId: inferenceRequestIdentity(parent) }+ }+ parentSpanId = parent.parentSpanId+ }+ const candidates = inferences.filter(inference => (+ sameStep(inference, span)+ && inference.startTimeUnixNano <= span.startTimeUnixNano+ )).sort(compareInferenceBehavior)+ const inference = candidates.at(-1)+ return inference === undefined+ ? span+ : { ...span, owningRequestRecordId: inferenceRequestIdentity(inference) }})}@@ -1133,13 +1449,111 @@ function group(turn: MutableTurn, step: number): MutableGroup {}function finalizeRequests(requests: readonly TrajectoryRequest[]): TrajectoryRequest[] {- let cumulative: TrajectoryUsage = {}return [...requests].sort((left, right) => (left.startedAt ?? 0) - (right.startedAt ?? 0) || left.number - right.number)- .map((request) => {- cumulative = addUsage(cumulative, request.usage ?? {})- return { ...request, cumulativeUsage: cumulative }- })+}++function requestBehaviorPhase(cell: TrajectoryCell): number {+ if (cell.kind === 'system' || cell.kind === 'user' || cell.kind === 'context') return 0+ if (cell.kind === 'message') return 1+ if (cell.kind === 'tool' || cell.kind === 'subtool') return 2+ return 3+}++function legacyKindOrder(cell: TrajectoryCell): number {+ if (cell.kind === 'system') return 0+ if (cell.kind === 'user' || cell.kind === 'context') return 1+ if (cell.kind === 'message') return 2+ if (cell.kind === 'tool' || cell.kind === 'subtool') return 3+ return 4+}++function isSchemaV2BehaviorCell(cell: TrajectoryCell): boolean {+ const source = object(cell.messageSource)+ return source?.kind === 'trajectory_context_delta'+ || source?.kind === 'trajectory_compaction'+ || source?.kind === 'trajectory_compaction_request'+}++function isSchemaV2CompactionCell(cell: TrajectoryCell): boolean {+ const source = object(cell.messageSource)+ return source?.kind === 'trajectory_compaction'+}++function requestInputSource(cell: TrajectoryCell): Record<string, unknown> | undefined {+ const source = object(cell.messageSource)+ return source?.kind === 'trajectory_context_delta' ? source : undefined+}++function preModelPreparationOrder(cell: TrajectoryCell): number | undefined {+ const source = requestInputSource(cell)+ if (cell.kind === 'system' && source?.transitionKind === 'epoch_baseline') return 0+ if (cell.kind === 'user' && source !== undefined) return 1+ if (cell.requestless === true && (cell.kind === 'tool' || cell.kind === 'subtool')) return 2+ if (source !== undefined && (cell.kind === 'system' || cell.kind === 'context')) return 3+ return undefined+}++function compareTrajectoryCells(left: TrajectoryCell, right: TrajectoryCell): number {+ const leftPreparationOrder = preModelPreparationOrder(left)+ const rightPreparationOrder = preModelPreparationOrder(right)+ if ((leftPreparationOrder === 2 || rightPreparationOrder === 2)+ && leftPreparationOrder !== undefined+ && rightPreparationOrder !== undefined) {+ const preparationOrder = leftPreparationOrder - rightPreparationOrder+ if (preparationOrder !== 0) return preparationOrder+ }+ if (isSchemaV2BehaviorCell(left)+ && isSchemaV2BehaviorCell(right)+ && left.behaviorOrder !== undefined+ && right.behaviorOrder !== undefined) {+ const eventOrder = left.behaviorOrder - right.behaviorOrder+ if (eventOrder !== 0) return eventOrder+ }+ const sameRequest = left.requestRecordId !== undefined+ && left.requestRecordId === right.requestRecordId+ if (sameRequest) {+ // Compaction occurs inside a long physical request, between ordinary+ // assistant/tool cells and the output context checkpoint. Phase-first+ // ordering would always push it behind every USER/MESSAGE/TOOL and creates+ // a non-transitive cycle with schema-v2 sequence ordering. Its recorded+ // event time is therefore the primary cross-source position.+ if (isSchemaV2CompactionCell(left) || isSchemaV2CompactionCell(right)) {+ const physicalOrder = (left.startedAt ?? 0) - (right.startedAt ?? 0)+ if (physicalOrder !== 0) return physicalOrder+ if (left.behaviorOrder !== undefined && right.behaviorOrder !== undefined) {+ const logicalOrder = left.behaviorOrder - right.behaviorOrder+ if (logicalOrder !== 0) return logicalOrder+ }+ }+ if (isSchemaV2BehaviorCell(left)+ && isSchemaV2BehaviorCell(right)+ && left.behaviorOrder !== undefined+ && right.behaviorOrder !== undefined) {+ const eventOrder = left.behaviorOrder - right.behaviorOrder+ if (eventOrder !== 0) return eventOrder+ }+ const phase = requestBehaviorPhase(left) - requestBehaviorPhase(right)+ if (phase !== 0) return phase+ if (left.behaviorOrder !== undefined && right.behaviorOrder !== undefined) {+ const logicalOrder = left.behaviorOrder - right.behaviorOrder+ if (logicalOrder !== 0) return logicalOrder+ }+ if (left.behaviorOrder === undefined && right.behaviorOrder === undefined) {+ const kindOrder = legacyKindOrder(left) - legacyKindOrder(right)+ if (kindOrder !== 0) return kindOrder+ }+ }+ const leftStart = left.startedAt ?? 0+ const rightStart = right.startedAt ?? 0+ if (leftStart !== rightStart) return leftStart - rightStart+ if (left.behaviorOrder !== undefined && right.behaviorOrder !== undefined) {+ const logicalOrder = left.behaviorOrder - right.behaviorOrder+ if (logicalOrder !== 0) return logicalOrder+ }+ const kindOrder = legacyKindOrder(left) - legacyKindOrder(right)+ if (kindOrder !== 0) return kindOrder+ return 0}/** Fold one bounded OTLP record window into the trajectory UI's closed read model. */@@ -1147,11 +1561,26 @@ export function projectOtelTrajectory(records: readonly OtlpExportTraceServiceRequest[],options: TrajectoryProjectionOptions = {},): TrajectorySnapshot {- const spans = normalize(records, options)+ const v2Records = records.filter(isTrajectoryV2Record)+ const legacyRecords = records.filter(record => !isTrajectoryV2Record(record))+ const v2Reduction = options.v2Reducer?.apply(v2Records) ?? reduceTrajectoryV2(v2Records)+ const currentV2SubjectIds = new Set(v2Records.flatMap((record): string[] => {+ const subjectId = readStringAttribute(+ exactAttributeMap(soleSpan(record).attributes),+ OPENJIUWEN_ATTRIBUTES.trajectorySubjectId,+ )+ return subjectId === undefined ? [] : [subjectId]+ }))+ const v2Subjects = [...v2Reduction.subjects.values()].filter(subject => (+ currentV2SubjectIds.has(subject.subjectId)+ ))+ const v2RequestIds = new Set(v2Subjects.flatMap(subject => [...subject.handledRequestIds]))+ const spans = normalize(legacyRecords, options)const mutableTurns = new Map<number, MutableTurn>()const requests: TrajectoryRequest[] = []- const inputProjection = projectInferenceInputs(spans)+ const inputProjection = projectInferenceInputs(spans, v2RequestIds)const toolSpanIds = new Set(spans.filter(isTool).map(span => span.span.spanId))+ const toolBySpanId = new Map(spans.filter(isTool).map(span => [span.span.spanId, span]))const authoritativeToolCallIds = new Set(spans.filter(span => isTool(span) && span.attributes.toolAuthoritative === true).flatMap(span => span.attributes.toolCallId === undefined@@ -1173,6 +1602,12 @@ export function projectOtelTrajectory(const compactionInferences = new Map<number, ProjectedSpan>()const compactions = new Map<number, ProjectedSpan>()const toolSchemaByTurnAndName = new Map<string, string>()+ const inferenceById = new Map(spans.filter(isInference).flatMap((span): Array<[+ string,+ ProjectedSpan,+ ]> => span.attributes.inferenceId === undefined+ ? []+ : [[`${span.traceId}\u0000${span.attributes.inferenceId}`, span]]))for (const span of spans.filter(isInference)) {for (const schema of toolSchemas(span.attributes.toolDefinitions)) {@@ -1188,17 +1623,48 @@ export function projectOtelTrajectory(const purpose = span.attributes.requestPurposeif (purpose === 'compaction') {compactionInferences.set(span.turn, span)- requests.push(requestFor(span, 'compaction', rootByTrace.get(span.traceId)?.attributes))+ requests.push(requestFor(+ span,+ 'compaction',+ rootByTrace.get(span.traceId)?.attributes,+ options.sessionCumulativeUsageByRequestIdentity,+ ))continue}const target = group(turn, step)const inputs = inputProjection.inputsBySpanId.get(span.span.spanId)- ?? { messages: [], prompt: undefined }+ ?? { messages: [], prompts: [] }target.cells.push(...inputCells(span, inputs), assistantCell(span))- requests.push(requestFor(span, 'assistant', rootByTrace.get(span.traceId)?.attributes))+ requests.push(requestFor(+ span,+ 'assistant',+ rootByTrace.get(span.traceId)?.attributes,+ options.sessionCumulativeUsageByRequestIdentity,+ ))continue}if (isTool(span)) {+ const parentTool = span.parentSpanId === undefined+ ? undefined+ : toolBySpanId.get(span.parentSpanId)+ const duplicateMcpLifecycle = span.attributes.toolAuthoritative !== true+ && parentTool?.attributes.toolAuthoritative === true+ && (parentTool.attributes.openJiuwenToolType ?? parentTool.attributes.toolType) === 'mcp'+ && parentTool.attributes.toolResourceId !== undefined+ && parentTool.attributes.toolResourceId === span.attributes.toolResourceId+ if (duplicateMcpLifecycle) continue+ if (+ span.attributes.toolAuthoritative === true+ && span.attributes.toolCallId !== undefined+ && span.owningRequestRecordId === undefined+ && !isRoutedAskUserResult(span, rootByTrace.get(span.traceId))+ ) {+ // A schema-v1 agent tool call must belong to a physical model+ // request. Root-level late callbacks have no such owner; rendering+ // them as Main Agent activity would let a cancelled conversation's+ // subagent leak into whichever run root happened to be alive next.+ continue+ }if (span.attributes.toolAuthoritative !== true&& span.attributes.toolCallId !== undefined@@ -1219,24 +1685,68 @@ export function projectOtelTrajectory(if (isCompaction(span)) compactions.set(span.turn, span)}+ const v2CompactionEvents: TrajectoryV2EventProjection[] = []+ for (const event of v2Subjects.flatMap(subject => [...subject.events])) {+ if (event.turn === null) {+ v2CompactionEvents.push(event)+ continue+ }+ const anchorInferenceId = event.cells.at(-1)?.physicalInferenceId+ const inference = anchorInferenceId === undefined+ ? undefined+ : inferenceById.get(`${event.traceId}\u0000${anchorInferenceId}`)+ const eventTurn = inference?.turn ?? event.turn+ const eventStep = inference === undefined+ ? event.step+ : positiveSafeInteger(inference.attributes.stepNumber) ?? event.step+ const inferencePrompt = inference === undefined+ ? undefined+ : promptSnapshot(inference.attributes)+ const turn = mutableTurns.get(eventTurn) ?? { turn: eventTurn, groups: new Map() }+ mutableTurns.set(eventTurn, turn)+ group(turn, eventStep).cells.push(...event.cells.map((cell) => {+ const physicalInferenceId = cell.physicalInferenceId+ const cellInference = physicalInferenceId === undefined+ ? undefined+ : inferenceById.get(`${event.traceId}\u0000${physicalInferenceId}`)+ return {+ ...cell,+ ...(cell.promptDetail === undefined || inferencePrompt === undefined+ ? {}+ : {+ promptDetail: {+ ...cell.promptDetail,+ config: inferencePrompt.config,+ tools: inferencePrompt.tools,+ },+ ...(cell.previousPromptDetail === undefined+ ? {}+ : {+ previousPromptDetail: {+ ...cell.previousPromptDetail,+ config: inferencePrompt.config,+ tools: inferencePrompt.tools,+ },+ }),+ }),+ ...(physicalInferenceId === undefined+ ? {}+ : {+ requestRecordId: cellInference === undefined+ ? `${event.traceId}:inference:${physicalInferenceId}`+ : inferenceRequestIdentity(cellInference),+ }),+ }+ }))+ }+const turns: TrajectoryTurnModel[] = []for (const turn of [...mutableTurns.values()].sort((left, right) => left.turn - right.turn)) {const groups = [...turn.groups.entries()].sort((left, right) => left[0] - right[0]).map(([, value]) => ({...value,- cells: [...value.cells].sort((left, right) => {- const leftStart = left.startedAt ?? 0- const rightStart = right.startedAt ?? 0- const kindOrder = (cell: TrajectoryCell): number => {- if (cell.kind === 'system') return 0- if (cell.kind === 'user' || cell.kind === 'context') return 1- if (cell.kind === 'message') return 2- if (cell.kind === 'tool') return 3- return 4- }- return leftStart - rightStart || kindOrder(left) - kindOrder(right)- }),+ cells: [...value.cells].sort(compareTrajectoryCells),})).filter(value => value.cells.length > 0)if (groups.length > 0) turns.push({ turn: turn.turn, groups })@@ -1251,10 +1761,26 @@ export function projectOtelTrajectory(})}}+ for (const event of v2CompactionEvents) {+ if (event.cells.length === 0) continue+ turns.push({+ turn: null,+ groups: [{ title: 'Compaction', cells: [...event.cells] }],+ })+ }++ const diagnostics = [+ ...v2Reduction.diagnostics.filter(item => (+ item.subjectId === undefined || currentV2SubjectIds.has(item.subjectId)+ )),+ ...v2Subjects.flatMap(subject => [...subject.diagnostics]),+ ...inputProjection.diagnostics,+ ]return {turns,requests: finalizeRequests(requests),+ ...(diagnostics.length === 0 ? {} : { diagnostics }),}}@@ -1265,8 +1791,10 @@ export interface TrajectoryProjector {/** Stateless projector suitable for an HTTP polling or incremental trace store. */export class OtelGenAiTrajectoryProjector implements TrajectoryProjector {+ private readonly v2Reducer = createTrajectoryV2Reducer()+/** Project the current bounded record window. */project(records: readonly OtlpExportTraceServiceRequest[]): TrajectorySnapshot {- return projectOtelTrajectory(records)+ return projectOtelTrajectory(records, { v2Reducer: this.v2Reducer })}}diff --git a/jiuwenswarm/channels/web/frontend/src/features/trajectory/projector/trajectory-v2-reducer.ts b/jiuwenswarm/channels/web/frontend/src/features/trajectory/projector/trajectory-v2-reducer.tsnew file mode 100644index 0000000000..5ec160d5c9--- /dev/null+++ b/jiuwenswarm/channels/web/frontend/src/features/trajectory/projector/trajectory-v2-reducer.ts@@ -0,0 +1,1203 @@+// Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++/** Idempotent reducer for canonical OpenJiuwen trajectory schema-v2 events. */++import { OPENJIUWEN_ATTRIBUTES } from '../semconv/constants.ts'+import { attributeMap } from '../shared/otlp.ts'+import type { OtlpExportTraceServiceRequest, OtlpSpan } from '../shared/otlp.ts'+import type { TrajectoryDiagnostic, TrajectoryPromptSnapshot } from '../trajectory/model.ts'+import type { TrajectoryCell, TrajectoryCellKind } from '../trajectory/record.ts'++export const TRAJECTORY_V2_SCHEMA_VERSION = '2'++interface ContextMessage {+ message_id: string+ role: string+ origin: 'external_user' | 'harness_internal'+ source_kind?: string+ content?: unknown+ tool_calls?: unknown+ tool_call_id?: string+ metadata?: unknown+}++interface ContextDelta {+ op: 'insert' | 'remove' | 'move' | 'replace'+ message_id: string+ index?: number+ from_index?: number+ message?: ContextMessage+ /** Projection-only predecessor when a remove+insert pair represents one logical slot. */+ display_previous_message?: ContextMessage+}++interface ContextCommitPayload {+ baseline_reason?: string+ window_id: string+ base_window_id: string | null+ complete: true+ messages: ContextMessage[]+ delta: ContextDelta[]+ request_purpose?: string+ correlation_kind?: string+ transition_kind?: string+ caused_by_operation_id?: string+ input_window_id?: string | null+ output_window_id?: string+}++interface ParsedEvent {+ eventId: string+ eventKind: string+ inferenceIds: readonly string[]+ payload: Record<string, unknown>+ recordedAt: bigint+ record: OtlpExportTraceServiceRequest+ requestId?: string+ sequence: number+ sequenceEpoch: string+ span: OtlpSpan+ step: number+ stepId?: string+ subjectId: string+ traceId: string+ turn: number+ turnId?: string+}++export interface TrajectoryV2EventProjection {+ cells: readonly TrajectoryCell[]+ eventId: string+ eventKind: string+ requestId?: string+ sequence: number+ step: number+ stepId?: string+ traceId: string+ turn: number | null+ turnId?: string+}++export interface TrajectoryV2SubjectProjection {+ diagnostics: readonly TrajectoryDiagnostic[]+ events: readonly TrajectoryV2EventProjection[]+ handledRequestIds: ReadonlySet<string>+ subjectId: string+}++export interface TrajectoryV2Reduction {+ diagnostics: readonly TrajectoryDiagnostic[]+ subjects: ReadonlyMap<string, TrajectoryV2SubjectProjection>+}++export interface TrajectoryV2Reducer {+ apply(records: readonly OtlpExportTraceServiceRequest[]): TrajectoryV2Reduction+ clear(): void+}++interface SubjectAccumulator {+ diagnostics: TrajectoryDiagnostic[]+ events: TrajectoryV2EventProjection[]+ handledRequestIds: Set<string>+ windows: Map<string, ContextMessage[]>+}++interface ContextPromptMaterialization {+ slotByMessageId: ReadonlyMap<string, number>+ snapshot: TrajectoryPromptSnapshot+}++function object(value: unknown): Record<string, unknown> | undefined {+ return typeof value === 'object' && value !== null && !Array.isArray(value)+ ? value as Record<string, unknown>+ : undefined+}++function spansOf(record: OtlpExportTraceServiceRequest): readonly OtlpSpan[] {+ return record.resourceSpans.flatMap(resource =>+ (resource.scopeSpans ?? []).flatMap(scope => scope.spans ?? []))+}++function soleSpan(record: OtlpExportTraceServiceRequest): OtlpSpan | undefined {+ const spans = spansOf(record)+ return spans.length === 1 ? spans[0] : undefined+}++function textAttribute(attributes: ReadonlyMap<string, unknown>, key: string): string | undefined {+ const value = attributes.get(key)+ return typeof value === 'string' && value.trim() !== '' ? value.trim() : undefined+}++function bigintAttribute(attributes: ReadonlyMap<string, unknown>, key: string): bigint | undefined {+ const value = attributes.get(key)+ if (typeof value !== 'string' && typeof value !== 'number') return undefined+ try {+ return BigInt(value)+ } catch {+ return undefined+ }+}++function safePositiveInteger(value: bigint | undefined): number | undefined {+ if (value === undefined || value <= 0n || value > BigInt(Number.MAX_SAFE_INTEGER)) return undefined+ return Number(value)+}++function payloadAttribute(attributes: ReadonlyMap<string, unknown>): Record<string, unknown> | undefined {+ const value = attributes.get(OPENJIUWEN_ATTRIBUTES.trajectoryPayload)+ if (typeof value === 'string') {+ try {+ return object(JSON.parse(value) as unknown)+ } catch {+ return undefined+ }+ }+ return object(value)+}++function physicalInferenceIds(+ eventKind: string,+ payload: Readonly<Record<string, unknown>>,+ span: OtlpSpan,+): string[] {+ if (eventKind === 'context.window.commit') {+ return typeof span.parentSpanId === 'string' && span.parentSpanId.trim() !== ''+ ? [span.parentSpanId.trim()]+ : []+ }+ if (eventKind !== 'compaction.completed' || !Array.isArray(payload.model_requests)+ || payload.model_requests.length === 0) return []+ const inferenceIds = payload.model_requests.flatMap((value): string[] => {+ const request = object(value)+ return request === undefined || typeof request.inference_id !== 'string'+ || request.inference_id.trim() === ''+ ? []+ : [request.inference_id.trim()]+ })+ return inferenceIds.length === payload.model_requests.length+ && new Set(inferenceIds).size === inferenceIds.length+ ? inferenceIds+ : []+}++/** Detect schema v2 without consulting any compatibility or LangFuse attribute. */+export function isTrajectoryV2Record(record: OtlpExportTraceServiceRequest): boolean {+ const span = soleSpan(record)+ if (span === undefined) return false+ return textAttribute(attributeMap(span.attributes), OPENJIUWEN_ATTRIBUTES.trajectorySchemaVersion)+ === TRAJECTORY_V2_SCHEMA_VERSION+}++function diagnostic(+ code: string,+ message: string,+ subjectId?: string,+ eventId?: string,+ sequence?: number,+): TrajectoryDiagnostic {+ return {+ code,+ message,+ ...(subjectId === undefined ? {} : { subjectId }),+ ...(eventId === undefined ? {} : { eventId }),+ ...(sequence === undefined ? {} : { sequence }),+ }+}++function appendUniqueDiagnostic(+ target: TrajectoryDiagnostic[],+ value: TrajectoryDiagnostic,+): void {+ const identity = `${value.subjectId ?? ''}:${value.eventId ?? ''}:${value.sequence ?? ''}:${value.code}`+ if (!target.some(item => (+ `${item.subjectId ?? ''}:${item.eventId ?? ''}:${item.sequence ?? ''}:${item.code}` === identity+ ))) target.push(value)+}++function parseEvent(record: OtlpExportTraceServiceRequest): ParsedEvent | TrajectoryDiagnostic {+ const span = soleSpan(record)+ if (span === undefined) {+ return diagnostic('v2.invalid_span_count', 'Schema-v2 records require exactly one Span.')+ }+ const attributes = attributeMap(span.attributes)+ const subjectId = textAttribute(attributes, OPENJIUWEN_ATTRIBUTES.trajectorySubjectId)+ const eventId = textAttribute(attributes, OPENJIUWEN_ATTRIBUTES.trajectoryEventId)+ const eventKind = textAttribute(attributes, OPENJIUWEN_ATTRIBUTES.trajectoryEventKind)+ const sequence = safePositiveInteger(bigintAttribute(+ attributes,+ OPENJIUWEN_ATTRIBUTES.trajectorySubjectSequence,+ ))+ const sequenceEpoch = textAttribute(+ attributes,+ OPENJIUWEN_ATTRIBUTES.trajectorySequenceEpoch,+ )+ const recordedAt = bigintAttribute(+ attributes,+ OPENJIUWEN_ATTRIBUTES.trajectoryRecordedAtUnixNano,+ )+ const sessionId = textAttribute(attributes, OPENJIUWEN_ATTRIBUTES.trajectorySessionId)+ const payload = payloadAttribute(attributes)+ if (subjectId === undefined || eventId === undefined || eventKind === undefined+ || sequence === undefined || sequenceEpoch === undefined+ || recordedAt === undefined || recordedAt < 0n+ || sessionId === undefined || payload === undefined) {+ return diagnostic(+ 'v2.incomplete_envelope',+ 'Schema-v2 event envelope is incomplete; the last valid view was retained.',+ subjectId,+ eventId,+ sequence,+ )+ }+ return {+ subjectId,+ eventId,+ eventKind,+ inferenceIds: physicalInferenceIds(eventKind, payload, span),+ sequence,+ sequenceEpoch,+ recordedAt,+ payload,+ record,+ span,+ traceId: span.traceId,+ requestId: textAttribute(attributes, OPENJIUWEN_ATTRIBUTES.trajectoryRequestId),+ turn: safePositiveInteger(bigintAttribute(attributes, OPENJIUWEN_ATTRIBUTES.turnNumber)) ?? 1,+ step: safePositiveInteger(bigintAttribute(attributes, OPENJIUWEN_ATTRIBUTES.stepNumber)) ?? 1,+ stepId: textAttribute(attributes, OPENJIUWEN_ATTRIBUTES.trajectoryStepId),+ turnId: textAttribute(attributes, OPENJIUWEN_ATTRIBUTES.trajectoryTurnId),+ }+}++function contextMessage(value: unknown): ContextMessage | undefined {+ const candidate = object(value)+ if (candidate === undefined || typeof candidate.message_id !== 'string'+ || candidate.message_id.trim() === '' || typeof candidate.role !== 'string'+ || candidate.role.trim() === ''+ || (candidate.origin !== 'external_user' && candidate.origin !== 'harness_internal')+ || (candidate.source_kind !== undefined+ && (typeof candidate.source_kind !== 'string' || candidate.source_kind.trim() === ''))) {+ return undefined+ }+ return {+ message_id: candidate.message_id,+ role: candidate.role,+ origin: candidate.origin,+ ...(typeof candidate.source_kind !== 'string'+ ? {}+ : { source_kind: candidate.source_kind.trim() }),+ ...(candidate.content === undefined ? {} : { content: candidate.content }),+ ...(candidate.tool_calls === undefined ? {} : { tool_calls: candidate.tool_calls }),+ ...(typeof candidate.tool_call_id !== 'string' ? {} : { tool_call_id: candidate.tool_call_id }),+ ...(candidate.metadata === undefined ? {} : { metadata: candidate.metadata }),+ }+}++function contextDelta(value: unknown): ContextDelta | undefined {+ const candidate = object(value)+ if (candidate === undefined+ || !['insert', 'remove', 'move', 'replace'].includes(String(candidate.op))+ || typeof candidate.message_id !== 'string' || candidate.message_id.trim() === '') return undefined+ const message = candidate.message === undefined ? undefined : contextMessage(candidate.message)+ if ((candidate.op === 'insert' || candidate.op === 'replace') && message === undefined) return undefined+ return {+ op: candidate.op as ContextDelta['op'],+ message_id: candidate.message_id,+ ...(Number.isSafeInteger(candidate.index) && Number(candidate.index) >= 0+ ? { index: Number(candidate.index) }+ : {}),+ ...(Number.isSafeInteger(candidate.from_index) && Number(candidate.from_index) >= 0+ ? { from_index: Number(candidate.from_index) }+ : {}),+ ...(message === undefined ? {} : { message }),+ }+}++function contextCommitPayload(value: Record<string, unknown>): ContextCommitPayload | undefined {+ if (typeof value.window_id !== 'string' || value.window_id.trim() === ''+ || value.complete !== true || !Array.isArray(value.messages) || !Array.isArray(value.delta)+ || !(value.base_window_id === null || typeof value.base_window_id === 'string')) return undefined+ const optionalTextFields = [+ value.request_purpose,+ value.baseline_reason,+ value.correlation_kind,+ value.transition_kind,+ value.caused_by_operation_id,+ value.output_window_id,+ ]+ if (optionalTextFields.some(field => field !== undefined && typeof field !== 'string')) {+ return undefined+ }+ if (value.input_window_id !== undefined && value.input_window_id !== null+ && typeof value.input_window_id !== 'string') return undefined+ const messages = value.messages.map(contextMessage)+ const delta = value.delta.map(contextDelta)+ if (messages.some(message => message === undefined) || delta.some(operation => operation === undefined)) {+ return undefined+ }+ const messageIds = (messages as ContextMessage[]).map(message => message.message_id)+ if (new Set(messageIds).size !== messageIds.length) return undefined+ const epochBaseline = value.transition_kind === 'epoch_baseline'+ if (epochBaseline && (value.base_window_id !== null+ || value.baseline_reason !== 'runtime_epoch_start'+ || delta.length !== 0)) return undefined+ if (!epochBaseline && value.baseline_reason !== undefined) return undefined+ return {+ window_id: value.window_id,+ base_window_id: value.base_window_id,+ complete: true,+ messages: messages as ContextMessage[],+ delta: delta as ContextDelta[],+ ...(typeof value.baseline_reason === 'string' ? { baseline_reason: value.baseline_reason } : {}),+ ...(typeof value.request_purpose === 'string' ? { request_purpose: value.request_purpose } : {}),+ ...(typeof value.correlation_kind === 'string'+ ? { correlation_kind: value.correlation_kind }+ : {}),+ ...(typeof value.transition_kind === 'string' ? { transition_kind: value.transition_kind } : {}),+ ...(typeof value.caused_by_operation_id === 'string'+ ? { caused_by_operation_id: value.caused_by_operation_id }+ : {}),+ ...(value.input_window_id === null+ ? { input_window_id: null }+ : typeof value.input_window_id === 'string'+ ? { input_window_id: value.input_window_id }+ : {}),+ ...(typeof value.output_window_id === 'string' ? { output_window_id: value.output_window_id } : {}),+ }+}++function displayContent(message: ContextMessage | undefined): string {+ if (message === undefined) return ''+ if (typeof message.content === 'string') return message.content+ if (message.content !== undefined) return JSON.stringify(message.content, null, 2) ?? ''+ if (message.tool_calls !== undefined) return JSON.stringify(message.tool_calls, null, 2) ?? ''+ return ''+}++function cellKind(message: ContextMessage | undefined): TrajectoryCellKind {+ if (message?.role === 'system') return 'system'+ if (message?.role === 'user' && message.origin === 'external_user') return 'user'+ return 'context'+}++function promptAttachmentHistoryMode(+ message: ContextMessage | undefined,+): 'snapshot' | 'delta' | undefined {+ if (message === undefined) return undefined+ const metadata = object(message.metadata)+ if (metadata?._openjiuwen_prompt_attachment_history !== true) return undefined+ return metadata.mode === 'snapshot' || metadata.mode === 'delta'+ ? metadata.mode+ : undefined+}++interface LogicalSystemSlot {+ index: number+ key: string+ message: ContextMessage+}++function logicalSystemSlots(messages: readonly ContextMessage[]): LogicalSystemSlot[] {+ const slots: LogicalSystemSlot[] = []+ let attachmentSlot: number | undefined+ messages.forEach((message, index) => {+ if (message.role !== 'system') return+ if (promptAttachmentHistoryMode(message) !== undefined) {+ if (attachmentSlot === undefined) {+ attachmentSlot = slots.length+ slots.push({ index, key: 'prompt-attachment', message })+ } else {+ const previous = slots[attachmentSlot]+ if (previous !== undefined) slots[attachmentSlot] = { ...previous, message }+ }+ return+ }+ slots.push({ index, key: `message:${message.message_id}`, message })+ })+ return slots+}++function systemSlotFingerprint(message: ContextMessage): string {+ const metadata = object(message.metadata)+ const attachment = promptAttachmentHistoryMode(message) !== undefined+ const normalizedMetadata = !attachment || metadata === undefined+ ? metadata+ : Object.fromEntries(Object.entries(metadata).filter(([key]) => (+ key !== 'context_message_id' && key !== 'session_id'+ )))+ return JSON.stringify({+ role: message.role,+ content: message.content,+ tool_calls: message.tool_calls,+ tool_call_id: message.tool_call_id,+ metadata: normalizedMetadata,+ })+}++const EPOCH_INPUT_SOURCE_KINDS = new Set(['query', 'resume', 'steering'])++function epochBaselineCells(+ event: ParsedEvent,+ payload: ContextCommitPayload,+ previous: readonly ContextMessage[],+ behaviorOrder: number,+): TrajectoryCell[] {+ const previousSlots = new Map(logicalSystemSlots(previous).map(slot => [slot.key, slot]))+ const operations: ContextDelta[] = []+ for (const slot of logicalSystemSlots(payload.messages)) {+ const previousSlot = previousSlots.get(slot.key)+ if (previousSlot !== undefined+ && systemSlotFingerprint(previousSlot.message) === systemSlotFingerprint(slot.message)) continue+ operations.push({+ op: previousSlot === undefined ? 'insert' : 'replace',+ message_id: slot.message.message_id,+ index: slot.index,+ message: slot.message,+ })+ }+ payload.messages.forEach((message, index) => {+ if (message.role !== 'user' || message.origin !== 'external_user'+ || message.source_kind === undefined+ || !EPOCH_INPUT_SOURCE_KINDS.has(message.source_kind)) return+ operations.push({+ op: 'insert',+ message_id: message.message_id,+ index,+ message,+ })+ })+ return contextCells(+ event,+ { ...payload, delta: operations },+ previous,+ undefined,+ behaviorOrder,+ )+}++function contextPromptMaterialization(+ messages: readonly ContextMessage[],+): ContextPromptMaterialization {+ const systemMessages: { index: number, content: string }[] = []+ const slotByMessageId = new Map<string, number>()+ let promptAttachmentSlot: number | undefined+ messages.forEach((message, index) => {+ if (message.role !== 'system') return+ const content = displayContent(message)+ const historyMode = promptAttachmentHistoryMode(message)+ if (historyMode === 'snapshot') promptAttachmentSlot ??= index+ if (historyMode !== undefined && promptAttachmentSlot !== undefined) {+ const slotIndex = systemMessages.findIndex(candidate => (+ candidate.index === promptAttachmentSlot+ ))+ const replacement = { index: promptAttachmentSlot, content }+ if (slotIndex === -1) systemMessages.push(replacement)+ else systemMessages[slotIndex] = replacement+ slotByMessageId.set(message.message_id, promptAttachmentSlot)+ return+ }+ systemMessages.push({ index, content })+ slotByMessageId.set(message.message_id, index)+ })+ return {+ slotByMessageId,+ snapshot: {+ config: { provider: '', model: '' },+ system: systemMessages.map(message => message.content).join('\n\n'),+ systemMessages,+ tools: [],+ },+ }+}++function stableIndex(value: string): number {+ let hash = 2166136261+ for (const character of value) {+ hash ^= character.codePointAt(0) ?? 0+ hash = Math.imul(hash, 16777619)+ }+ return hash >>> 0+}++function eventCell(+ event: ParsedEvent,+ suffix: string,+ kind: TrajectoryCellKind,+ text: string,+ messageSource: unknown,+): TrajectoryCell {+ const startedAt = Number(event.recordedAt / 1_000_000n)+ const recordId = `v2:${event.subjectId}:${event.eventId}:${suffix}`+ return {+ index: stableIndex(recordId),+ recordId,+ kind,+ text,+ inputDetail: text,+ messageSource,+ sourceSeq: event.sequence,+ startedAt,+ timeSeconds: null,+ status: 'complete',+ traceDetail: event.record,+ }+}++function applyContextDelta(+ base: readonly ContextMessage[],+ operations: readonly ContextDelta[],+): ContextMessage[] | undefined {+ const messages = [...base]+ for (const operation of operations) {+ const currentIndex = messages.findIndex(message => message.message_id === operation.message_id)+ if (operation.op === 'insert') {+ if (operation.message === undefined || operation.index === undefined+ || operation.index > messages.length || currentIndex !== -1) return undefined+ messages.splice(operation.index, 0, operation.message)+ continue+ }+ if (currentIndex === -1) return undefined+ if (operation.op === 'remove') {+ messages.splice(currentIndex, 1)+ continue+ }+ if (operation.op === 'replace') {+ if (operation.message === undefined) return undefined+ messages[currentIndex] = operation.message+ continue+ }+ if (operation.index === undefined || operation.index >= messages.length) return undefined+ const [moved] = messages.splice(currentIndex, 1)+ if (moved === undefined) return undefined+ messages.splice(operation.index, 0, moved)+ }+ return messages+}++function sameCheckpoint(+ left: readonly ContextMessage[],+ right: readonly ContextMessage[],+): boolean {+ const identity = (value: unknown): string => {+ if (Array.isArray(value)) return `[${value.map(identity).join(',')}]`+ const candidate = object(value)+ if (candidate === undefined) return JSON.stringify(value) ?? String(value)+ return `{${Object.keys(candidate).sort().map(key => (+ `${JSON.stringify(key)}:${identity(candidate[key])}`+ )).join(',')}}`+ }+ return identity(left) === identity(right)+}++function ephemeralContextSlot(message: ContextMessage | undefined): string | undefined {+ const metadata = object(message?.metadata)+ if (metadata?.browser_working_context === true) return 'browser-working-context'+ if (metadata?.browser_state_context === true) return 'browser-state'+ if (metadata?.browser_state_progress_context === true) return 'browser-state-progress'+ return undefined+}++function sameLogicalContextMessage(left: ContextMessage, right: ContextMessage): boolean {+ const normalized = (message: ContextMessage): ContextMessage => {+ const metadata = object(message.metadata)+ const normalizedMetadata = metadata === undefined+ ? undefined+ : Object.fromEntries(Object.entries(metadata).filter(([key]) => key !== 'context_message_id'))+ return {+ ...message,+ message_id: 'logical-context-slot',+ ...(normalizedMetadata === undefined ? {} : { metadata: normalizedMetadata }),+ }+ }+ return sameCheckpoint([normalized(left)], [normalized(right)])+}++function contextDisplayOperations(+ operations: readonly ContextDelta[],+ base: readonly ContextMessage[],+): ContextDelta[] {+ const baseById = new Map(base.map(message => [message.message_id, message]))+ const insertedSlots = new Set(operations.flatMap((operation): string[] => {+ if (operation.op !== 'insert') return []+ const slot = ephemeralContextSlot(operation.message)+ return slot === undefined ? [] : [slot]+ }))+ const removedBySlot = new Map<string, ContextMessage>()+ for (const operation of operations) {+ if (operation.op !== 'remove') continue+ const removed = baseById.get(operation.message_id)+ const slot = ephemeralContextSlot(removed)+ if (slot !== undefined && insertedSlots.has(slot) && removed !== undefined) {+ removedBySlot.set(slot, removed)+ }+ }+ return operations.flatMap((operation): ContextDelta[] => {+ if (operation.op === 'move'+ && ephemeralContextSlot(baseById.get(operation.message_id)) !== undefined) return []+ if (operation.op === 'remove') {+ const slot = ephemeralContextSlot(baseById.get(operation.message_id))+ return slot !== undefined && removedBySlot.has(slot) ? [] : [operation]+ }+ if (operation.op !== 'insert' || operation.message === undefined) return [operation]+ const slot = ephemeralContextSlot(operation.message)+ const removed = slot === undefined ? undefined : removedBySlot.get(slot)+ if (removed === undefined) return [operation]+ if (sameLogicalContextMessage(removed, operation.message)) return []+ return [{ ...operation, op: 'replace', display_previous_message: removed }]+ })+}++function contextCells(+ event: ParsedEvent,+ payload: ContextCommitPayload,+ base: readonly ContextMessage[] | undefined,+ compactionOperationId?: string,+ behaviorOrder = event.sequence,+): TrajectoryCell[] {+ const rawOperations = payload.delta.length > 0+ ? payload.delta+ : payload.base_window_id === null+ ? payload.messages.map((message, index): ContextDelta => ({+ op: 'insert',+ message_id: message.message_id,+ index,+ message,+ }))+ : []+ const operations = contextDisplayOperations(rawOperations, base ?? [])+ const baseById = new Map((base ?? []).map(message => [message.message_id, message]))+ const prompt = contextPromptMaterialization(payload.messages)+ const previousPrompt = base === undefined+ ? undefined+ : contextPromptMaterialization(base)+ return operations.flatMap((operation, index): TrajectoryCell[] => {+ const message = operation.message ?? baseById.get(operation.message_id)+ if (message?.role === 'assistant' || message?.role === 'tool') return []+ // A compaction output checkpoint can remove most of the old window in one+ // delta. Those removals are real diff facts, but rendering their previous+ // content as fresh USER/SYSTEM rows makes every removed occurrence appear+ // a second time. The COMPACTED cell represents that structural rewrite;+ // keep newly inserted memory/recovery occurrences visible below it.+ if (compactionOperationId !== undefined && operation.op === 'remove') return []+ const text = displayContent(message) || `${operation.op} ${operation.message_id}`+ const kind = cellKind(message)+ const previousMessage = operation.display_previous_message+ ?? (operation.op === 'replace' ? baseById.get(operation.message_id) : undefined)+ const previousText = displayContent(previousMessage)+ const currentMessageIndex = payload.messages.findIndex(+ candidate => candidate.message_id === operation.message_id,+ )+ const previousMessageIndex = (base ?? []).findIndex(+ candidate => candidate.message_id === operation.message_id,+ )+ const operationPreviousPrompt = (+ promptAttachmentHistoryMode(message) === 'delta'+ && (base?.length ?? 0) === 0+ && currentMessageIndex >= 0+ )+ ? contextPromptMaterialization(payload.messages.slice(0, currentMessageIndex))+ : previousPrompt+ const promptSystemMessageIndex = prompt.slotByMessageId.get(operation.message_id)+ ?? operationPreviousPrompt?.slotByMessageId.get(operation.message_id)+ ?? (currentMessageIndex >= 0 ? currentMessageIndex : previousMessageIndex)+ return [{+ ...eventCell(event, `context:${index}:${operation.message_id}`, kind, text, {+ kind: 'trajectory_context_delta',+ operation: operation.op,+ messageId: operation.message_id,+ windowId: payload.window_id,+ baseWindowId: payload.base_window_id,+ role: message?.role,+ origin: message?.origin,+ sourceKind: message?.source_kind,+ metadata: message?.metadata,+ transitionKind: payload.transition_kind,+ }),+ physicalInferenceId: event.inferenceIds[0],+ behaviorOrder: behaviorOrder + (index + 1) / (operations.length + 1),+ ...(kind === 'context' && operation.op === 'replace' && previousText !== text+ ? { previousInputDetail: previousText }+ : {}),+ ...(kind !== 'system'+ ? {}+ : {+ promptDetail: prompt.snapshot,+ ...(operationPreviousPrompt === undefined+ ? {}+ : { previousPromptDetail: operationPreviousPrompt.snapshot }),+ ...(promptSystemMessageIndex < 0 ? {} : { promptSystemMessageIndex }),+ }),+ }]+ })+}++function compactionCells(+ event: ParsedEvent,+ behaviorOrder = event.sequence,+): TrajectoryCell[] {+ const text = typeof event.payload.summary === 'string'+ ? event.payload.summary.trim()+ : ''+ const compactSummary = typeof event.payload.compact_summary === 'string'+ ? event.payload.compact_summary+ : undefined+ if (typeof event.payload.operation_id !== 'string' || event.payload.operation_id.trim() === ''+ || text === '') return []+ if (event.inferenceIds.length === 0) {+ if (!Array.isArray(event.payload.model_requests)+ || event.payload.model_requests.length !== 0) return []+ return [{+ ...eventCell(event, 'compaction', 'compacted', text, {+ kind: 'trajectory_compaction',+ operationId: event.payload.operation_id,+ modelFree: true,+ }),+ behaviorOrder,+ requestless: true,+ ...(compactSummary === undefined || compactSummary.trim() === ''+ ? {}+ : { outputDetail: compactSummary }),+ compactionDetail: { ...event.payload },+ }]+ }+ if (compactSummary === undefined || compactSummary.trim() === '') return []+ const requestBoundaries = event.inferenceIds.slice(0, -1).map((inferenceId, index) => ({+ ...eventCell(event, `compaction-request:${index}:${inferenceId}`, 'compacted', '', {+ kind: 'trajectory_compaction_request',+ operationId: event.payload.operation_id,+ inferenceId,+ }),+ physicalInferenceId: inferenceId,+ requestOnly: true,+ behaviorOrder: behaviorOrder - (event.inferenceIds.length - index) / (+ event.inferenceIds.length + 1+ ),+ }))+ const inferenceId = event.inferenceIds.at(-1)+ if (inferenceId === undefined) return []+ return [...requestBoundaries, {+ ...eventCell(event, 'compaction', 'compacted', text, {+ kind: 'trajectory_compaction',+ operationId: event.payload.operation_id,+ inputWindowId: event.payload.input_window_id,+ outputWindowId: event.payload.output_window_id,+ }),+ physicalInferenceId: inferenceId,+ behaviorOrder,+ outputDetail: compactSummary,+ compactionDetail: { ...event.payload },+ }]+}++function isModelFreeCompaction(event: ParsedEvent): boolean {+ return Array.isArray(event.payload.model_requests)+ && event.payload.model_requests.length === 0+}++interface CompactionCorrelation {+ diagnostic?: string+ operationId?: string+}++function compactionOutputCorrelation(+ event: ParsedEvent,+ payload: ContextCommitPayload,+ compactionsByOperationId: ReadonlyMap<string, ParsedEvent | null>,+): CompactionCorrelation {+ const explicitCorrelation = payload.transition_kind === 'compaction'+ || payload.correlation_kind === 'compaction'+ || payload.caused_by_operation_id !== undefined+ || payload.input_window_id !== undefined+ || payload.output_window_id !== undefined+ if (!explicitCorrelation) return {}+ const operationId = payload.caused_by_operation_id?.trim()+ const inputWindowId = payload.input_window_id === null+ ? null+ : payload.input_window_id?.trim()+ const outputWindowId = payload.output_window_id?.trim()+ const compactionKind = payload.transition_kind === 'compaction'+ || payload.correlation_kind === 'compaction'+ if (!compactionKind+ || !operationId || (inputWindowId !== null && !inputWindowId) || !outputWindowId) {+ return {+ diagnostic: 'Explicit compaction correlation is incomplete; the output window was not associated.',+ }+ }+ if (inputWindowId !== payload.base_window_id+ || outputWindowId !== payload.window_id) {+ return {+ diagnostic: 'Explicit compaction correlation conflicts with the context window transition.',+ }+ }+ if (!compactionsByOperationId.has(operationId)) {+ return {+ diagnostic: `Compaction operation ${operationId} is not available for this output window.`,+ }+ }+ const compaction = compactionsByOperationId.get(operationId)+ if (compaction === null || compaction === undefined) {+ return {+ diagnostic: `Compaction operation ${operationId} is ambiguous and was not associated.`,+ }+ }+ if (compaction.sequence >= event.sequence) {+ return {+ diagnostic: `Compaction operation ${operationId} does not precede its output window.`,+ }+ }+ const compactionInput = compaction.payload.input_window_id+ const compactionOutput = compaction.payload.output_window_id+ if ((inputWindowId !== null+ && typeof compactionInput === 'string'+ && compactionInput !== inputWindowId)+ || (typeof compactionOutput === 'string' && compactionOutput !== outputWindowId)) {+ return {+ diagnostic: `Compaction operation ${operationId} conflicts with its declared input/output windows.`,+ }+ }+ return { operationId }+}++function eventFingerprint(event: ParsedEvent): string {+ return JSON.stringify({+ eventKind: event.eventKind,+ payload: event.payload,+ recordedAt: String(event.recordedAt),+ sequence: event.sequence,+ sequenceEpoch: event.sequenceEpoch,+ subjectId: event.subjectId,+ })+}++function orderedEpochEvents(events: readonly ParsedEvent[]): ParsedEvent[] {+ const byEpoch = new Map<string, ParsedEvent[]>()+ for (const event of events) {+ const epoch = byEpoch.get(event.sequenceEpoch) ?? []+ epoch.push(event)+ byEpoch.set(event.sequenceEpoch, epoch)+ }+ return [...byEpoch.entries()]+ .map(([sequenceEpoch, epochEvents]) => {+ const ordered = [...epochEvents].sort((left, right) => (+ left.sequence - right.sequence+ || (left.recordedAt < right.recordedAt ? -1 : left.recordedAt > right.recordedAt ? 1 : 0)+ || left.eventId.localeCompare(right.eventId)+ ))+ const firstRecordedAt = ordered.reduce(+ (earliest, event) => event.recordedAt < earliest ? event.recordedAt : earliest,+ ordered[0]?.recordedAt ?? 0n,+ )+ return { sequenceEpoch, firstRecordedAt, events: ordered }+ })+ .sort((left, right) => (+ left.firstRecordedAt < right.firstRecordedAt+ ? -1+ : left.firstRecordedAt > right.firstRecordedAt+ ? 1+ : left.sequenceEpoch.localeCompare(right.sequenceEpoch)+ ))+ .flatMap(epoch => epoch.events)+}++function rebuildSubject(subjectId: string, events: readonly ParsedEvent[]): TrajectoryV2SubjectProjection {+ const accumulator: SubjectAccumulator = {+ diagnostics: [],+ events: [],+ handledRequestIds: new Set(),+ windows: new Map(),+ }+ const bySequenceByEpoch = new Map<string, Map<number, ParsedEvent>>()+ const expectedByEpoch = new Map<string, number>()+ const blockedEpochs = new Set<string>()+ const compactionsByOperationId = new Map<string, ParsedEvent | null>()+ const referencedCompactionOperationIds = new Set<string>()+ let activeEpoch: string | undefined+ let epochBaselineBase: readonly ContextMessage[] | undefined+ let lastWindow: readonly ContextMessage[] | undefined+ let subjectOrder = 0+ for (const event of orderedEpochEvents(events)) {+ subjectOrder += 1+ if (activeEpoch !== event.sequenceEpoch) {+ activeEpoch = event.sequenceEpoch+ epochBaselineBase = lastWindow+ }+ const bySequence = bySequenceByEpoch.get(event.sequenceEpoch) ?? new Map<number, ParsedEvent>()+ bySequenceByEpoch.set(event.sequenceEpoch, bySequence)+ const collision = bySequence.get(event.sequence)+ if (collision !== undefined) {+ accumulator.diagnostics.push(diagnostic(+ 'v2.sequence_conflict',+ 'Two different events use the same sequence within one epoch; the first valid event was retained.',+ subjectId,+ event.eventId,+ event.sequence,+ ))+ continue+ }+ bySequence.set(event.sequence, event)+ let expected = expectedByEpoch.get(event.sequenceEpoch)+ const completeCheckpoint = event.eventKind === 'context.window.commit'+ && contextCommitPayload(event.payload)?.complete === true+ if (blockedEpochs.has(event.sequenceEpoch)) {+ if (!completeCheckpoint) continue+ blockedEpochs.delete(event.sequenceEpoch)+ expected = event.sequence+ accumulator.diagnostics.push(diagnostic(+ 'v2.checkpoint_recovery',+ 'A complete context checkpoint resumed the blocked sequence epoch.',+ subjectId,+ event.eventId,+ event.sequence,+ ))+ }+ if (expected !== undefined && event.sequence > expected) {+ accumulator.diagnostics.push(diagnostic(+ 'v2.sequence_gap',+ `Expected subject sequence ${expected} but received ${event.sequence}.`,+ subjectId,+ event.eventId,+ event.sequence,+ ))+ if (!completeCheckpoint) {+ blockedEpochs.add(event.sequenceEpoch)+ continue+ }+ accumulator.diagnostics.push(diagnostic(+ 'v2.checkpoint_recovery',+ 'A complete context checkpoint advanced the view across the missing sequence.',+ subjectId,+ event.eventId,+ event.sequence,+ ))+ }+ if (expected === undefined && event.sequence > 1) {+ accumulator.diagnostics.push(diagnostic(+ 'v2.partial_window',+ `The bounded record window begins at subject sequence ${event.sequence}.`,+ subjectId,+ event.eventId,+ event.sequence,+ ))+ }+ expectedByEpoch.set(event.sequenceEpoch, event.sequence + 1)+ if (event.eventKind === 'context.window.commit') {+ if (event.inferenceIds.length !== 1) {+ accumulator.diagnostics.push(diagnostic(+ 'v2.missing_physical_request',+ 'Context commit is missing its physical inference parent.',+ subjectId,+ event.eventId,+ event.sequence,+ ))+ continue+ }+ const payload = contextCommitPayload(event.payload)+ if (payload === undefined) {+ accumulator.diagnostics.push(diagnostic(+ 'v2.invalid_context_commit',+ 'Invalid context.window.commit payload; the last valid context window was retained.',+ subjectId,+ event.eventId,+ event.sequence,+ ))+ continue+ }+ const base = payload.base_window_id === null+ ? []+ : accumulator.windows.get(payload.base_window_id)+ if (payload.base_window_id !== null && base === undefined) {+ accumulator.diagnostics.push(diagnostic(+ 'v2.missing_base_window',+ `Base context window ${payload.base_window_id} is not available; the complete checkpoint was used.`,+ subjectId,+ event.eventId,+ event.sequence,+ ))+ }+ const epochBaseline = payload.transition_kind === 'epoch_baseline'+ if (base !== undefined && !epochBaseline) {+ const reconstructed = applyContextDelta(base, payload.delta)+ if (reconstructed === undefined || !sameCheckpoint(reconstructed, payload.messages)) {+ accumulator.diagnostics.push(diagnostic(+ 'v2.delta_checkpoint_mismatch',+ 'Context delta does not reconstruct its complete checkpoint; the last valid window was retained.',+ subjectId,+ event.eventId,+ event.sequence,+ ))+ continue+ }+ }+ accumulator.windows.set(payload.window_id, payload.messages)+ lastWindow = payload.messages+ if (event.requestId !== undefined) accumulator.handledRequestIds.add(event.requestId)+ const referencedOperationId = payload.caused_by_operation_id?.trim()+ if (referencedOperationId) {+ referencedCompactionOperationIds.add(referencedOperationId)+ }+ const correlation = compactionOutputCorrelation(+ event,+ payload,+ compactionsByOperationId,+ )+ if (correlation.diagnostic !== undefined) {+ accumulator.diagnostics.push(diagnostic(+ 'v2.invalid_compaction_correlation',+ correlation.diagnostic,+ subjectId,+ event.eventId,+ event.sequence,+ ))+ }+ accumulator.events.push({+ eventId: event.eventId,+ eventKind: event.eventKind,+ sequence: event.sequence,+ requestId: event.requestId,+ turn: event.turn,+ step: event.step,+ stepId: event.stepId,+ traceId: event.traceId,+ turnId: event.turnId,+ cells: epochBaseline && epochBaselineBase !== undefined+ ? epochBaselineCells(+ event,+ payload,+ epochBaselineBase,+ subjectOrder,+ )+ : contextCells(+ event,+ payload,+ base,+ correlation.operationId,+ subjectOrder,+ ),+ })+ continue+ }+ if (event.eventKind === 'compaction.completed') {+ const modelRequests = event.payload.model_requests+ if (event.inferenceIds.length === 0+ && (!Array.isArray(modelRequests) || modelRequests.length !== 0)) {+ accumulator.diagnostics.push(diagnostic(+ 'v2.missing_physical_request',+ 'A model-backed compaction event must identify its physical inference.',+ subjectId,+ event.eventId,+ event.sequence,+ ))+ continue+ }+ const cells = compactionCells(event, subjectOrder)+ if (cells.length === 0) {+ accumulator.diagnostics.push(diagnostic(+ 'v2.invalid_compaction',+ 'Invalid compaction.completed payload; the last valid view was retained.',+ subjectId,+ event.eventId,+ event.sequence,+ ))+ continue+ }+ accumulator.events.push({+ eventId: event.eventId,+ eventKind: event.eventKind,+ sequence: event.sequence,+ requestId: event.requestId,+ turn: event.turn,+ step: event.step,+ stepId: event.stepId,+ traceId: event.traceId,+ turnId: event.turnId,+ cells,+ })+ const operationId = String(event.payload.operation_id).trim()+ if (compactionsByOperationId.has(operationId)) {+ compactionsByOperationId.set(operationId, null)+ accumulator.diagnostics.push(diagnostic(+ 'v2.compaction_operation_conflict',+ `Compaction operation ${operationId} is declared by multiple events.`,+ subjectId,+ event.eventId,+ event.sequence,+ ))+ } else {+ compactionsByOperationId.set(operationId, event)+ }+ continue+ }+ accumulator.diagnostics.push(diagnostic(+ 'v2.unknown_event_kind',+ `Unsupported schema-v2 event kind: ${event.eventKind}.`,+ subjectId,+ event.eventId,+ event.sequence,+ ))+ }+ for (const [operationId, compaction] of compactionsByOperationId) {+ if (compaction === null+ || isModelFreeCompaction(compaction)+ || referencedCompactionOperationIds.has(operationId)) continue+ accumulator.diagnostics.push(diagnostic(+ 'v2.missing_compaction_output_correlation',+ `Compaction operation ${operationId} has no explicitly correlated output window.`,+ subjectId,+ compaction.eventId,+ compaction.sequence,+ ))+ }+ return {+ subjectId,+ diagnostics: accumulator.diagnostics,+ events: accumulator.events,+ handledRequestIds: accumulator.handledRequestIds,+ }+}++/** Create one durable UI reducer; duplicate revisions are ignored by event identity. */+export function createTrajectoryV2Reducer(): TrajectoryV2Reducer {+ const eventsBySubject = new Map<string, Map<string, ParsedEvent>>()+ const globalDiagnostics: TrajectoryDiagnostic[] = []+ return {+ apply(records) {+ for (const record of records) {+ if (!isTrajectoryV2Record(record)) continue+ const parsed = parseEvent(record)+ if ('code' in parsed) {+ appendUniqueDiagnostic(globalDiagnostics, parsed)+ continue+ }+ const subjectEvents = eventsBySubject.get(parsed.subjectId) ?? new Map<string, ParsedEvent>()+ const existing = subjectEvents.get(parsed.eventId)+ if (existing === undefined) {+ subjectEvents.set(parsed.eventId, parsed)+ eventsBySubject.set(parsed.subjectId, subjectEvents)+ } else if (eventFingerprint(existing) !== eventFingerprint(parsed)) {+ appendUniqueDiagnostic(globalDiagnostics, diagnostic(+ 'v2.event_id_conflict',+ 'The same event ID changed payload; the first immutable event was retained.',+ parsed.subjectId,+ parsed.eventId,+ parsed.sequence,+ ))+ }+ }+ const subjects = new Map([...eventsBySubject].map(([subjectId, events]) => (+ [subjectId, rebuildSubject(subjectId, [...events.values()])] as const+ )))+ return { diagnostics: globalDiagnostics, subjects }+ },+ clear() {+ eventsBySubject.clear()+ globalDiagnostics.length = 0+ },+ }+}++/** Stateless convenience boundary used by tests and archive replay. */+export function reduceTrajectoryV2(+ records: readonly OtlpExportTraceServiceRequest[],+): TrajectoryV2Reduction {+ return createTrajectoryV2Reducer().apply(records)+}diff --git a/jiuwenswarm/channels/web/frontend/src/features/trajectory/semconv/constants.ts b/jiuwenswarm/channels/web/frontend/src/features/trajectory/semconv/constants.tsindex 2b6b5f89ff..932748237f 100644--- a/jiuwenswarm/channels/web/frontend/src/features/trajectory/semconv/constants.ts+++ b/jiuwenswarm/channels/web/frontend/src/features/trajectory/semconv/constants.ts@@ -50,6 +50,7 @@ export const STANDARD_ATTRIBUTES = {agentVersion: 'gen_ai.agent.version',agentDescription: 'gen_ai.agent.description',toolName: 'gen_ai.tool.name',+ toolId: 'gen_ai.tool.id',toolCallId: 'gen_ai.tool.call.id',toolType: 'gen_ai.tool.type',toolDescription: 'gen_ai.tool.description',@@ -77,6 +78,12 @@ export const OPENJIUWEN_ATTRIBUTES = {stepId: 'openjiuwen.step.id',stepNumber: 'openjiuwen.step.number',inferenceId: 'openjiuwen.inference.id',+ executionSubjectId: 'openjiuwen.execution.subject.id',+ executionSubjectDisplayName: 'openjiuwen.execution.subject.display_name',+ executionSubjectKind: 'openjiuwen.execution.subject.kind',+ executionSubjectParentId: 'openjiuwen.execution.subject.parent_id',+ executionSubjectSessionId: 'openjiuwen.execution.subject.session_id',+ executionSubjectRequestNumber: 'openjiuwen.execution.subject.request.number',trajectoryKind: 'openjiuwen.trajectory.record.kind',requestPurpose: 'openjiuwen.request.purpose',requestNumber: 'openjiuwen.request.number',@@ -103,6 +110,18 @@ export const OPENJIUWEN_ATTRIBUTES = {streamToolCallId: 'openjiuwen.stream.tool_call.id',streamToolName: 'openjiuwen.stream.tool_call.name',streamArgumentsDelta: 'openjiuwen.stream.tool_call.arguments_delta',+ trajectorySchemaVersion: 'openjiuwen.trajectory.schema_version',+ trajectoryEventId: 'openjiuwen.trajectory.event_id',+ trajectoryEventKind: 'openjiuwen.trajectory.event_kind',+ trajectorySubjectId: 'openjiuwen.trajectory.subject_id',+ trajectorySubjectSequence: 'openjiuwen.trajectory.subject_sequence',+ trajectorySequenceEpoch: 'openjiuwen.trajectory.sequence_epoch',+ trajectorySessionId: 'openjiuwen.trajectory.session_id',+ trajectoryTurnId: 'openjiuwen.trajectory.turn_id',+ trajectoryStepId: 'openjiuwen.trajectory.step_id',+ trajectoryRequestId: 'openjiuwen.trajectory.request_id',+ trajectoryRecordedAtUnixNano: 'openjiuwen.trajectory.recorded_at_unix_nano',+ trajectoryPayload: 'openjiuwen.trajectory.payload',} as const/** OpenJiuwen event names added alongside existing DSH and llm.chunk events. */diff --git a/jiuwenswarm/channels/web/frontend/src/features/trajectory/trajectory/model.ts b/jiuwenswarm/channels/web/frontend/src/features/trajectory/trajectory/model.tsindex e3b418afe5..f9cf8fe304 100644--- a/jiuwenswarm/channels/web/frontend/src/features/trajectory/trajectory/model.ts+++ b/jiuwenswarm/channels/web/frontend/src/features/trajectory/trajectory/model.ts@@ -71,10 +71,17 @@ export interface TrajectoryToolSchema {parameters: object | unknown[]}+/** One real system message slot in the model request, preserving boundaries. */+export interface TrajectorySystemMessage {+ index: number+ content: string+}+/** Effective prompt state displayed by SYSTEM records. */export interface TrajectoryPromptSnapshot {config: TrajectoryRequestConfigsystem: string+ systemMessages: readonly TrajectorySystemMessage[]tools: readonly TrajectoryToolSchema[]}@@ -127,7 +134,7 @@ interface TrajectoryRequestBase {/** One purpose-discriminated request paired with its display number. */export type TrajectoryRequest = TrajectoryRequestBase & (| { purpose?: 'assistant'; turn: number; step: number }- | { purpose: 'compaction'; turn: number | null; step: 0 }+ | { purpose: 'compaction'; turn: number; step: number })/** Snapshot consumed atomically by `TrajectoryExplorer`. */@@ -135,4 +142,14 @@ export interface TrajectorySnapshot {turns: readonly TrajectoryTurnModel[]requests?: readonly TrajectoryRequest[]streamingCells?: readonly TrajectoryCell[]+ diagnostics?: readonly TrajectoryDiagnostic[]+}++/** Non-fatal projection issue that preserves the last valid trajectory view. */+export interface TrajectoryDiagnostic {+ code: string+ message: string+ subjectId?: string+ eventId?: string+ sequence?: number}diff --git a/jiuwenswarm/channels/web/frontend/src/features/trajectory/trajectory/preview.ts b/jiuwenswarm/channels/web/frontend/src/features/trajectory/trajectory/preview.tsindex c39489c120..f05d53e477 100644--- a/jiuwenswarm/channels/web/frontend/src/features/trajectory/trajectory/preview.ts+++ b/jiuwenswarm/channels/web/frontend/src/features/trajectory/trajectory/preview.ts@@ -6,7 +6,7 @@* under the repository MIT license.*/-import { extractMarkdownPlainText } from '../primitives/index.ts'+import { extractMarkdownPlainText } from '../primitives/markdown/plain-text.ts'const PREVIEW_SOURCE_CHARACTERS = 2_048const PREVIEW_OUTPUT_CHARACTERS = 512@@ -24,3 +24,14 @@ export function trajectoryPreviewText(text: string): string {? `${preview}…`: preview}++/**+ * Combine a record label with its Markdown preview without echoing the same+ * assistant output twice when the label is the retained source text.+ */+export function trajectoryDisplayText(text: string, markdown: string): string {+ const preview = trajectoryPreviewText(markdown)+ if (text === '') return preview+ if (preview === '') return text+ return trajectoryPreviewText(text) === preview ? text : `${text} · ${preview}`+}diff --git a/jiuwenswarm/channels/web/frontend/src/features/trajectory/trajectory/record.ts b/jiuwenswarm/channels/web/frontend/src/features/trajectory/trajectory/record.tsindex bc29411bc8..04dfeeefe0 100644--- a/jiuwenswarm/channels/web/frontend/src/features/trajectory/trajectory/record.ts+++ b/jiuwenswarm/channels/web/frontend/src/features/trajectory/trajectory/record.ts@@ -45,6 +45,8 @@ export interface TrajectoryCell {recordId?: string/** Physical model request owning this row; several requests may share one Step. */requestRecordId?: string+ /** Schema-v2 physical inference identity, resolved without temporal inference. */+ physicalInferenceId?: stringkind: TrajectoryCellKind/** Explicit lifecycle; payload capture policy never determines completion. */status?: 'complete' | 'running' | 'error'@@ -52,14 +54,24 @@ export interface TrajectoryCell {previewMarkdown?: stringopensTurn?: booleansourceSeq?: number+ /** Stable logical position inside one request when wall-clock timestamps overlap. */+ behaviorOrder?: numbermessageSource?: unknown/** Original one-Span OTLP export request for the generic OTel inspector. */traceDetail?: unknownrequestOnly?: boolean+ /** Behavior event that must not create a synthetic Request boundary. */+ requestless?: booleaninputDetail?: string+ /** Previous content for a same-slot USER/CONTEXT replacement. */+ previousInputDetail?: stringpromptDetail?: TrajectoryPromptSnapshotpreviousPromptDetail?: TrajectoryPromptSnapshot+ /** Real request-message slot represented by this SYSTEM row. */+ promptSystemMessageIndex?: numberoutputDetail?: string+ /** Structured schema-v2 compaction payload shown independently from Markdown output. */+ compactionDetail?: Readonly<Record<string, unknown>>thinkingDetail?: stringsourceBlocks?: readonly TrajectorySourceBlock[]outputBlocks?: readonly TrajectorySourceBlock[]diff --git a/jiuwenswarm/channels/web/frontend/src/features/trajectory/trajectory/search-index.ts b/jiuwenswarm/channels/web/frontend/src/features/trajectory/trajectory/search-index.tsindex 48dcd73043..d66acd53f4 100644--- a/jiuwenswarm/channels/web/frontend/src/features/trajectory/trajectory/search-index.ts+++ b/jiuwenswarm/channels/web/frontend/src/features/trajectory/trajectory/search-index.ts@@ -9,7 +9,7 @@import type { TrajectoryTurnModel } from './model.ts'import type { TrajectoryCellProps } from './record.ts'import { trajectoryRecordId } from './record.ts'-import { trajectoryPreviewText } from './preview.ts'+import { trajectoryDisplayText, trajectoryPreviewText } from './preview.ts'interface SearchEntry {readonly sources: readonly string[]@@ -31,9 +31,7 @@ function sameSources(left: readonly string[], right: readonly string[]): booleanfunction markdownPreview(cell: TrajectoryCellProps): string {if (cell.previewMarkdown === undefined) return ''- const preview = trajectoryPreviewText(cell.previewMarkdown)- if (cell.text === '') return preview- return preview === '' ? cell.text : `${cell.text} · ${preview}`+ return trajectoryDisplayText(cell.text, cell.previewMarkdown)}function resultPreview(cell: TrajectoryCellProps): string {diff --git a/jiuwenswarm/channels/web/frontend/src/features/trajectory/trajectoryClient.ts b/jiuwenswarm/channels/web/frontend/src/features/trajectory/trajectoryClient.tsindex a4eec8a26f..402d45dcbf 100644--- a/jiuwenswarm/channels/web/frontend/src/features/trajectory/trajectoryClient.ts+++ b/jiuwenswarm/channels/web/frontend/src/features/trajectory/trajectoryClient.ts@@ -4,6 +4,7 @@import { getApiBase } from '../../utils/env';import type { OtlpExportTraceServiceRequest } from './shared/otlp';+import type { TrajectoryUsage } from './trajectory/model';export interface TrajectoryTraceSummary {trace_id: string;@@ -37,6 +38,23 @@ export interface TrajectoryRevisionListResponse {has_more: boolean;}+export interface TrajectorySessionUsageItem {+ trace_id: string;+ inference_id: string;+ subject_id: string;+ start_time_unix_nano: string;+ usage: TrajectoryUsage;+ cumulative_usage: TrajectoryUsage;+}++export interface TrajectorySessionUsageResponse {+ schema_version: 1;+ session_id: string;+ store_epoch: string;+ scope: 'session';+ items: TrajectorySessionUsageItem[];+}+export interface TrajectoryDetailRecord {ingest_seq: number;record_id?: string;@@ -148,6 +166,55 @@ function validStoreEpoch(value: unknown): value is string {&& value.length <= 512;}+function validUsage(value: unknown): value is TrajectoryUsage {+ if (!object(value)) return false;+ return ['input', 'cacheRead', 'cacheWrite', 'output', 'reasoning', 'total'].every((key) => {+ const item = value[key];+ return item === undefined || (Number.isSafeInteger(item) && Number(item) >= 0);+ });+}++function validSessionUsageItem(value: unknown): value is TrajectorySessionUsageItem {+ if (!object(value)) return false;+ return typeof value.trace_id === 'string'+ && /^[0-9a-f]{32}$/.test(value.trace_id)+ && typeof value.inference_id === 'string'+ && value.inference_id.trim().length > 0+ && typeof value.subject_id === 'string'+ && value.subject_id.trim().length > 0+ && typeof value.start_time_unix_nano === 'string'+ && /^\d+$/.test(value.start_time_unix_nano)+ && validUsage(value.usage)+ && validUsage(value.cumulative_usage);+}++export async function getTrajectorySessionUsage(+ sessionId: string,+ options: { signal?: AbortSignal } = {},+): Promise<TrajectorySessionUsageResponse> {+ const response = await fetch(trajectoryUrl(+ `/api/trajectory/sessions/${encodeURIComponent(sessionId)}/usage`,+ ), {+ cache: 'no-store',+ signal: options.signal,+ });+ const payload = await readResponse(response);+ if (!object(payload)+ || payload.schema_version !== 1+ || payload.session_id !== sessionId+ || !validStoreEpoch(payload.store_epoch)+ || payload.scope !== 'session'+ || !Array.isArray(payload.items)+ || !payload.items.every(validSessionUsageItem)) {+ throw new TrajectoryApiError(+ 'Trajectory session usage response is invalid',+ 502,+ 'INVALID_RESPONSE',+ );+ }+ return payload as unknown as TrajectorySessionUsageResponse;+}+export async function listTrajectoryTraces(sessionId: string,options: {diff --git a/jiuwenswarm/channels/web/frontend/src/features/trajectory/trajectoryLayout.ts b/jiuwenswarm/channels/web/frontend/src/features/trajectory/trajectoryLayout.tsindex 92d34511b3..0dfa601498 100644--- a/jiuwenswarm/channels/web/frontend/src/features/trajectory/trajectoryLayout.ts+++ b/jiuwenswarm/channels/web/frontend/src/features/trajectory/trajectoryLayout.ts@@ -12,27 +12,18 @@ export interface RawInspectorHeightBounds {max: number;}-export interface TrajectoryHostLayout {- effectiveTeamAreaExpanded: boolean;- hideSessions: boolean;- hideTasks: boolean;-}--export function resolveTrajectoryHostLayout(+export function shouldInsetTrajectoryForFloatingTasks(mode: string,activeView: string,- sessionsCollapsed: boolean,- tasksCollapsed: boolean,- teamAreaExpanded: boolean,-): TrajectoryHostLayout {- const trajectoryActive = mode === 'agent' && activeView === 'trajectory';- const hideSessions = trajectoryActive && sessionsCollapsed;- const hideTasks = trajectoryActive && tasksCollapsed;- return {- effectiveTeamAreaExpanded: teamAreaExpanded && !hideTasks,- hideSessions,- hideTasks,- };+ taskPanelAvailable: boolean,+ taskPanelHidden: boolean,+ taskPanelExpanded: boolean,+): boolean {+ return mode === 'agent'+ && activeView === 'trajectory'+ && taskPanelAvailable+ && !taskPanelHidden+ && !taskPanelExpanded;}export function rawInspectorHeightBounds(containerHeight: number): RawInspectorHeightBounds {diff --git a/jiuwenswarm/channels/web/frontend/src/features/trajectory/trajectorySubjects.ts b/jiuwenswarm/channels/web/frontend/src/features/trajectory/trajectorySubjects.tsnew file mode 100644index 0000000000..5306fb5fff--- /dev/null+++ b/jiuwenswarm/channels/web/frontend/src/features/trajectory/trajectorySubjects.ts@@ -0,0 +1,326 @@+// Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++/** Explicit execution-subject grouping shared by live and archive trajectory views. */++import { OPENJIUWEN_ATTRIBUTES } from './semconv/constants';+import { stringAttribute, type OtlpExportTraceServiceRequest } from './shared/otlp';+import type { TrajectoryDetailRecord } from './trajectoryClient';+import { detailRecordIdentity, spansOf } from './trajectoryWindow';++export const MAIN_TRAJECTORY_SUBJECT_ID = 'main';+export const UNASSIGNED_TRAJECTORY_SUBJECT_ID = '__unassigned__';++export type TrajectorySubjectKind = 'main_agent' | 'subagent' | 'unassigned';++export interface TrajectorySubject {+ id: string;+ displayName: string;+ kind: TrajectorySubjectKind;+ parentId: string | null;+ sessionId: string | null;+}++export interface TrajectorySubjectGroup {+ subject: TrajectorySubject;+ records: OtlpExportTraceServiceRequest[];+ rawRecords: TrajectoryDetailRecord[];+ lifecycleByRecordId: Map<string, 'running' | 'completed' | 'error'>;+ traceCount: number;+ firstObservedTimeUnixNano: string | null;+ label: string;+}++export interface TrajectorySubjectGroups {+ groups: TrajectorySubjectGroup[];+ byId: ReadonlyMap<string, TrajectorySubjectGroup>;+}++export interface TrajectorySubjectView<TSnapshot> {+ groups: TrajectorySubjectGroups;+ snapshots: ReadonlyMap<string, TSnapshot>;+}++export interface TrajectorySubjectViewCache<TSnapshot> {+ update: (+ candidate: TrajectorySubjectGroups,+ project: (group: TrajectorySubjectGroup) => TSnapshot,+ ) => TrajectorySubjectView<TSnapshot>;+ clear: () => void;+}++const mainSubject: TrajectorySubject = {+ id: MAIN_TRAJECTORY_SUBJECT_ID,+ displayName: 'Main Agent',+ kind: 'main_agent',+ parentId: null,+ sessionId: null,+};++const unassignedSubject: TrajectorySubject = {+ id: UNASSIGNED_TRAJECTORY_SUBJECT_ID,+ displayName: 'Unassigned',+ kind: 'unassigned',+ parentId: null,+ sessionId: null,+};++function firstSpan(record: OtlpExportTraceServiceRequest | null | undefined) {+ if (record === null || record === undefined) return undefined;+ const spans = spansOf(record);+ return spans.length === 1 ? spans[0] : undefined;+}++export function trajectorySubjectOf(+ record: OtlpExportTraceServiceRequest | null | undefined,+): TrajectorySubject {+ const span = firstSpan(record);+ if (span === undefined) return unassignedSubject;+ const trajectorySchemaVersion = stringAttribute(+ span.attributes,+ OPENJIUWEN_ATTRIBUTES.trajectorySchemaVersion,+ );+ if (trajectorySchemaVersion === '2') {+ const trajectorySubjectId = stringAttribute(+ span.attributes,+ OPENJIUWEN_ATTRIBUTES.trajectorySubjectId,+ )?.trim();+ if (!trajectorySubjectId) return unassignedSubject;+ const legacyDisplayName = stringAttribute(+ span.attributes,+ OPENJIUWEN_ATTRIBUTES.executionSubjectDisplayName,+ )?.trim();+ const parentId = stringAttribute(+ span.attributes,+ OPENJIUWEN_ATTRIBUTES.executionSubjectParentId,+ )?.trim();+ const sessionId = stringAttribute(+ span.attributes,+ OPENJIUWEN_ATTRIBUTES.executionSubjectSessionId,+ )?.trim();+ if (trajectorySubjectId === MAIN_TRAJECTORY_SUBJECT_ID) {+ return {+ id: trajectorySubjectId,+ displayName: legacyDisplayName || mainSubject.displayName,+ kind: 'main_agent',+ parentId: parentId || null,+ sessionId: sessionId || null,+ };+ }+ return {+ id: trajectorySubjectId,+ displayName: legacyDisplayName+ || trajectorySubjectId.replace(/^subagent:/, '')+ || trajectorySubjectId,+ kind: 'subagent',+ parentId: parentId || MAIN_TRAJECTORY_SUBJECT_ID,+ sessionId: sessionId || null,+ };+ }+ const id = stringAttribute(span.attributes, OPENJIUWEN_ATTRIBUTES.executionSubjectId);+ const displayName = stringAttribute(+ span.attributes,+ OPENJIUWEN_ATTRIBUTES.executionSubjectDisplayName,+ );+ const kind = stringAttribute(span.attributes, OPENJIUWEN_ATTRIBUTES.executionSubjectKind);+ const parentId = stringAttribute(+ span.attributes,+ OPENJIUWEN_ATTRIBUTES.executionSubjectParentId,+ );+ const subjectSessionId = stringAttribute(+ span.attributes,+ OPENJIUWEN_ATTRIBUTES.executionSubjectSessionId,+ );++ if (id === undefined && displayName === undefined && kind === undefined+ && parentId === undefined && subjectSessionId === undefined) {+ return mainSubject;+ }+ if (kind === 'main_agent' && id === MAIN_TRAJECTORY_SUBJECT_ID) {+ return {+ id,+ displayName: displayName?.trim() || mainSubject.displayName,+ kind,+ parentId: parentId?.trim() || null,+ sessionId: subjectSessionId?.trim() || null,+ };+ }+ if (kind === 'subagent' && id?.trim() && displayName?.trim() && parentId?.trim()) {+ return {+ id,+ displayName: displayName.trim(),+ kind,+ parentId: parentId.trim(),+ sessionId: subjectSessionId?.trim() || null,+ };+ }+ return unassignedSubject;+}++function compareNano(left: string | null, right: string | null): number {+ if (left === right) return 0;+ if (left === null) return 1;+ if (right === null) return -1;+ if (left.length !== right.length) return left.length - right.length;+ return left.localeCompare(right);+}++function traceCount(records: readonly OtlpExportTraceServiceRequest[]): number {+ return new Set(records.flatMap(record => spansOf(record).map(span => span.traceId))).size;+}++function sameSubject(left: TrajectorySubject, right: TrajectorySubject): boolean {+ return left.id === right.id+ && left.displayName === right.displayName+ && left.kind === right.kind+ && left.parentId === right.parentId+ && left.sessionId === right.sessionId;+}++function sameArrayItems<T>(left: readonly T[], right: readonly T[]): boolean {+ return left.length === right.length && left.every((item, index) => item === right[index]);+}++function sameLifecycle(+ left: ReadonlyMap<string, 'running' | 'completed' | 'error'>,+ right: ReadonlyMap<string, 'running' | 'completed' | 'error'>,+): boolean {+ return left.size === right.size+ && [...left].every(([identity, lifecycle]) => right.get(identity) === lifecycle);+}++function sameGroup(left: TrajectorySubjectGroup, right: TrajectorySubjectGroup): boolean {+ return sameSubject(left.subject, right.subject)+ && left.label === right.label+ && left.traceCount === right.traceCount+ && left.firstObservedTimeUnixNano === right.firstObservedTimeUnixNano+ && sameArrayItems(left.records, right.records)+ && sameArrayItems(left.rawRecords, right.rawRecords)+ && sameLifecycle(left.lifecycleByRecordId, right.lifecycleByRecordId);+}++function sameProjectionInput(+ left: TrajectorySubjectGroup,+ right: TrajectorySubjectGroup,+): boolean {+ return sameArrayItems(left.records, right.records)+ && sameLifecycle(left.lifecycleByRecordId, right.lifecycleByRecordId);+}++/** Preserve unchanged subject and projection identities across live publishes. */+export function createTrajectorySubjectViewCache<TSnapshot>(): TrajectorySubjectViewCache<TSnapshot> {+ let previousGroups: TrajectorySubjectGroups | null = null;+ let previousSnapshots = new Map<string, TSnapshot>();+ return {+ update: (candidate, project) => {+ const stableGroups = candidate.groups.map((group) => {+ const prior = previousGroups?.byId.get(group.subject.id);+ return prior !== undefined && sameGroup(prior, group) ? prior : group;+ });+ const groups = {+ groups: stableGroups,+ byId: new Map(stableGroups.map(group => [group.subject.id, group])),+ };+ const snapshots = new Map(stableGroups.map((group) => {+ const priorGroup = previousGroups?.byId.get(group.subject.id);+ const priorSnapshot = previousSnapshots.get(group.subject.id);+ return priorGroup !== undefined+ && sameProjectionInput(priorGroup, group)+ && previousSnapshots.has(group.subject.id)+ ? [group.subject.id, priorSnapshot as TSnapshot] as const+ : [group.subject.id, project(group)] as const;+ }));+ previousGroups = groups;+ previousSnapshots = snapshots;+ return { groups, snapshots };+ },+ clear: () => {+ previousGroups = null;+ previousSnapshots = new Map();+ },+ };+}++export function groupTrajectorySubjects(+ records: readonly OtlpExportTraceServiceRequest[],+ rawRecords: readonly TrajectoryDetailRecord[],+ lifecycleByRecordId: ReadonlyMap<string, 'running' | 'completed' | 'error'>,+ ownerSessionId?: string,+): TrajectorySubjectGroups {+ const mutable = new Map<string, Omit<TrajectorySubjectGroup, 'label' | 'traceCount'>>();+ const ensure = (subject: TrajectorySubject, observedTime: string | null) => {+ const current = mutable.get(subject.id);+ if (current !== undefined) {+ if (compareNano(observedTime, current.firstObservedTimeUnixNano) < 0) {+ current.firstObservedTimeUnixNano = observedTime;+ }+ return current;+ }+ const group = {+ subject,+ records: [],+ rawRecords: [],+ lifecycleByRecordId: new Map<string, 'running' | 'completed' | 'error'>(),+ firstObservedTimeUnixNano: observedTime,+ };+ mutable.set(subject.id, group);+ return group;+ };++ ensure(mainSubject, null);+ for (const record of records) {+ const span = firstSpan(record);+ const subject = trajectorySubjectOf(record);+ if (subject.kind === 'subagent'+ && subject.sessionId !== null+ && ownerSessionId+ && !subject.sessionId.startsWith(`${ownerSessionId}_sub_`)) continue;+ ensure(subject, span?.startTimeUnixNano ?? null).records.push(record);+ }+ for (const rawRecord of rawRecords) {+ const span = firstSpan(rawRecord.otlp);+ const subject = trajectorySubjectOf(rawRecord.otlp);+ if (subject.kind === 'subagent'+ && subject.sessionId !== null+ && ownerSessionId+ && !subject.sessionId.startsWith(`${ownerSessionId}_sub_`)) continue;+ const group = ensure(+ subject,+ rawRecord.observed_time_unix_nano ?? span?.startTimeUnixNano ?? null,+ );+ group.rawRecords.push(rawRecord);+ const identity = detailRecordIdentity(rawRecord);+ const lifecycle = identity === null ? undefined : lifecycleByRecordId.get(identity);+ if (identity !== null && lifecycle !== undefined) {+ group.lifecycleByRecordId.set(identity, lifecycle);+ }+ }++ const ordered = [...mutable.values()].sort((left, right) => {+ if (left.subject.kind === 'main_agent') return right.subject.kind === 'main_agent' ? 0 : -1;+ if (right.subject.kind === 'main_agent') return 1;+ if (left.subject.kind === 'unassigned') return right.subject.kind === 'unassigned' ? 0 : 1;+ if (right.subject.kind === 'unassigned') return -1;+ return compareNano(left.firstObservedTimeUnixNano, right.firstObservedTimeUnixNano)+ || left.subject.id.localeCompare(right.subject.id);+ });+ const displayTotals = new Map<string, number>();+ for (const group of ordered) {+ if (group.subject.kind !== 'subagent') continue;+ displayTotals.set(+ group.subject.displayName,+ (displayTotals.get(group.subject.displayName) ?? 0) + 1,+ );+ }+ const displayOrdinals = new Map<string, number>();+ const groups = ordered.map((group): TrajectorySubjectGroup => {+ let label = group.subject.displayName;+ if (group.subject.kind === 'subagent'+ && (displayTotals.get(group.subject.displayName) ?? 0) > 1) {+ const ordinal = (displayOrdinals.get(group.subject.displayName) ?? 0) + 1;+ displayOrdinals.set(group.subject.displayName, ordinal);+ label = `${group.subject.displayName} ${ordinal}`;+ }+ return { ...group, label, traceCount: traceCount(group.records) };+ });+ return { groups, byId: new Map(groups.map(group => [group.subject.id, group])) };+}diff --git a/jiuwenswarm/channels/web/frontend/src/features/trajectory/trajectoryWindow.ts b/jiuwenswarm/channels/web/frontend/src/features/trajectory/trajectoryWindow.tsindex 1562412a66..77bc12d504 100644--- a/jiuwenswarm/channels/web/frontend/src/features/trajectory/trajectoryWindow.ts+++ b/jiuwenswarm/channels/web/frontend/src/features/trajectory/trajectoryWindow.ts@@ -6,6 +6,7 @@ import type {OtlpExportTraceServiceRequest,OtlpSpan,} from './shared/otlp';+import type { TrajectoryUsage } from './trajectory/model';import type {TrajectoryDetailRecord,TrajectoryRevisionListResponse,@@ -67,6 +68,14 @@ export interface TrajectoryOperationCoordinator {) => Promise<boolean>;}+export interface TrajectoryTraceHintCoordinator {+ enqueue: (traceId: string, revision: number) => void;+ drain: (+ loadBatch: (hints: ReadonlyMap<string, number>) => Promise<void>,+ pace?: () => Promise<void>,+ ) => Promise<void>;+}+export interface StagedTrajectoryTrace {bucket: TrajectoryTraceBucket;invalidRecordSeen: boolean;@@ -74,6 +83,47 @@ export interface StagedTrajectoryTrace {export type TrajectoryContentMode = 'new' | 'loading' | 'blocking-error' | 'empty' | 'data';+export type TrajectoryTerminalEventName =+ | 'chat.final'+ | 'chat.processing_status'+ | 'chat.error'+ | 'execution.error'+ | 'harness.session_finished';++function sameUsage(left: TrajectoryUsage, right: TrajectoryUsage): boolean {+ return left.input === right.input+ && left.cacheRead === right.cacheRead+ && left.cacheWrite === right.cacheWrite+ && left.output === right.output+ && left.reasoning === right.reasoning+ && left.total === right.total;+}++/** Report whether a cumulative-usage refresh changes any projected request fact. */+export function sameTrajectoryUsageMap(+ left: ReadonlyMap<string, TrajectoryUsage>,+ right: ReadonlyMap<string, TrajectoryUsage>,+): boolean {+ return left.size === right.size+ && [...left].every(([identity, usage]) => {+ const candidate = right.get(identity);+ return candidate !== undefined && sameUsage(usage, candidate);+ });+}++function trajectoryEventSessionId(payload: Record<string, unknown>): string | null {+ if (typeof payload.session_id === 'string' && payload.session_id.trim()) {+ return payload.session_id;+ }+ for (const key of ['payload', 'event'] as const) {+ const nested = payload[key];+ if (typeof nested !== 'object' || nested === null || Array.isArray(nested)) continue;+ const nestedSessionId = trajectoryEventSessionId(nested as Record<string, unknown>);+ if (nestedSessionId !== null) return nestedSessionId;+ }+ return null;+}+type TraceListPageLoader = (cursor: string | null,signal: AbortSignal,@@ -89,6 +139,8 @@ type TraceDetailPageLoader = (signal: AbortSignal,) => Promise<TrajectoryTraceDetailResponse>;+type TraceDetailPagePublisher = (staged: StagedTrajectoryTrace) => void;+function invalidPagination(message: string): Error {const error = new Error(message);error.name = 'TrajectoryPaginationError';@@ -106,6 +158,19 @@ export function createTrajectoryWindowState(): TrajectoryWindowState {};}+/** Recognize session terminal events that must repair a missed trajectory hint. */+export function shouldCatchUpAfterTrajectoryTerminalEvent(+ eventName: TrajectoryTerminalEventName,+ payload: Record<string, unknown>,+ sessionId: string,+): boolean {+ if (trajectoryEventSessionId(payload) !== sessionId) return false;+ if (eventName === 'chat.processing_status') {+ return payload.is_processing === false;+ }+ return true;+}+export function resetTrajectoryWindowState(state: TrajectoryWindowState): void {state.buckets = new Map<string, TrajectoryTraceBucket>();state.storeEpoch = null;@@ -159,6 +224,45 @@ export function createTrajectoryOperationCoordinator(): TrajectoryOperationCoord};}+/** Coalesce trace hints while making one flight chase every later watermark. */+export function createTrajectoryTraceHintCoordinator(): TrajectoryTraceHintCoordinator {+ const pending = new Map<string, number>();+ let flight: Promise<void> | null = null;++ const enqueue = (traceId: string, revision: number): void => {+ const prior = pending.get(traceId) ?? -1;+ if (revision > prior) pending.set(traceId, revision);+ };+ const drain = (+ loadBatch: (hints: ReadonlyMap<string, number>) => Promise<void>,+ pace?: () => Promise<void>,+ ): Promise<void> => {+ if (flight !== null) return flight;+ const operation = (async () => {+ let firstBatch = true;+ while (pending.size > 0) {+ if (!firstBatch && pace !== undefined) await pace();+ const hints = new Map(pending);+ pending.clear();+ try {+ await loadBatch(hints);+ } catch (error) {+ for (const [traceId, revision] of hints) enqueue(traceId, revision);+ throw error;+ }+ firstBatch = false;+ }+ })();+ flight = operation;+ const clearFlight = () => {+ if (flight === operation) flight = null;+ };+ void operation.then(clearFlight, clearFlight);+ return operation;+ };+ return { enqueue, drain };+}+export function spansOf(record: OtlpExportTraceServiceRequest): OtlpSpan[] {return record.resourceSpans.flatMap(resource => (resource.scopeSpans ?? []@@ -365,6 +469,7 @@ export async function stageTrajectoryTracePages(current: TrajectoryTraceBucket | undefined,signal: AbortSignal,loadPage: TraceDetailPageLoader,+ publishPage?: TraceDetailPagePublisher,): Promise<StagedTrajectoryTrace | null> {let sinceRevision = current?.revision ?? 0;let stagedRecords = new Map<string, OtlpExportTraceServiceRequest>(@@ -396,22 +501,26 @@ export async function stageTrajectoryTracePages(stagedRawRecords = applied.bucket.rawRecords;stagedVersions = applied.bucket.versions ?? new Map();invalidRecordSeen = invalidRecordSeen || applied.invalidRecordSeen;- stagedRevision = detail.revision;- if (!detail.has_more) break;- if (detail.next_since_revision <= sinceRevision) {+ const consumedRevision = detail.has_more+ ? detail.next_since_revision+ : detail.revision;+ if (detail.has_more && consumedRevision <= sinceRevision) {throw invalidPagination('Trajectory detail pagination did not advance');}- sinceRevision = detail.next_since_revision;+ stagedRevision = consumedRevision;+ const progress = {+ bucket: {+ revision: stagedRevision,+ records: stagedRecords,+ rawRecords: stagedRawRecords,+ versions: stagedVersions,+ },+ invalidRecordSeen,+ };+ publishPage?.(progress);+ if (!detail.has_more) return progress;+ sinceRevision = consumedRevision;}- return {- bucket: {- revision: stagedRevision,- records: stagedRecords,- rawRecords: stagedRawRecords,- versions: stagedVersions,- },- invalidRecordSeen,- };}export function trajectoryContentMode(input: {diff --git a/jiuwenswarm/channels/web/frontend/tests/fixtures/trajectory-archive-subjects.json b/jiuwenswarm/channels/web/frontend/tests/fixtures/trajectory-archive-subjects.jsonnew file mode 100644index 0000000000..9f74352738--- /dev/null+++ b/jiuwenswarm/channels/web/frontend/tests/fixtures/trajectory-archive-subjects.json@@ -0,0 +1,73 @@+{+ "format": "openjiuwen.trajectory.archive",+ "archive_version": 1,+ "session_id": "browser-subject-fixture",+ "store_epoch": "browser-fixture-epoch",+ "revision": "2",+ "exported_at": "2026-08-21T00:00:00Z",+ "records": [+ {+ "record_id": "11111111111111111111111111111111:0000000000000001",+ "record_revision": 1,+ "lifecycle": "final",+ "operation": "upsert",+ "change_seq": "1",+ "observed_time_unix_nano": "100",+ "trace_id": "11111111111111111111111111111111",+ "span_id": "0000000000000001",+ "raw_json_base64": "eyJyZXNvdXJjZVNwYW5zIjpbeyJzY29wZVNwYW5zIjpbeyJzcGFucyI6W3sidHJhY2VJZCI6IjExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExIiwic3BhbklkIjoiMDAwMDAwMDAwMDAwMDAwMSIsIm5hbWUiOiJtYWluIHJlcXVlc3QiLCJzdGFydFRpbWVVbml4TmFubyI6IjEwMCIsImVuZFRpbWVVbml4TmFubyI6IjExMCIsImF0dHJpYnV0ZXMiOlt7ImtleSI6Im9wZW5qaXV3ZW4uZXhlY3V0aW9uLnN1YmplY3QuaWQiLCJ2YWx1ZSI6eyJzdHJpbmdWYWx1ZSI6Im1haW4ifX0seyJrZXkiOiJvcGVuaml1d2VuLmV4ZWN1dGlvbi5zdWJqZWN0LmRpc3BsYXlfbmFtZSIsInZhbHVlIjp7InN0cmluZ1ZhbHVlIjoiTWFpbiBBZ2VudCJ9fSx7ImtleSI6Im9wZW5qaXV3ZW4uZXhlY3V0aW9uLnN1YmplY3Qua2luZCIsInZhbHVlIjp7InN0cmluZ1ZhbHVlIjoibWFpbl9hZ2VudCJ9fSx7ImtleSI6Im9wZW5qaXV3ZW4uZXhlY3V0aW9uLnN1YmplY3Quc2Vzc2lvbl9pZCIsInZhbHVlIjp7InN0cmluZ1ZhbHVlIjoiYnJvd3Nlci1zdWJqZWN0LWZpeHR1cmUifX1dfV19XX1dfQ==",+ "raw_valid": true,+ "otlp": {+ "resourceSpans": [{+ "scopeSpans": [{+ "spans": [{+ "traceId": "11111111111111111111111111111111",+ "spanId": "0000000000000001",+ "name": "main request",+ "startTimeUnixNano": "100",+ "endTimeUnixNano": "110",+ "attributes": [+ {"key": "openjiuwen.execution.subject.id", "value": {"stringValue": "main"}},+ {"key": "openjiuwen.execution.subject.display_name", "value": {"stringValue": "Main Agent"}},+ {"key": "openjiuwen.execution.subject.kind", "value": {"stringValue": "main_agent"}},+ {"key": "openjiuwen.execution.subject.session_id", "value": {"stringValue": "browser-subject-fixture"}}+ ]+ }]+ }]+ }]+ }+ },+ {+ "record_id": "11111111111111111111111111111111:0000000000000002",+ "record_revision": 1,+ "lifecycle": "final",+ "operation": "upsert",+ "change_seq": "2",+ "observed_time_unix_nano": "200",+ "trace_id": "11111111111111111111111111111111",+ "span_id": "0000000000000002",+ "raw_json_base64": "eyJyZXNvdXJjZVNwYW5zIjpbeyJzY29wZVNwYW5zIjpbeyJzcGFucyI6W3sidHJhY2VJZCI6IjExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExIiwic3BhbklkIjoiMDAwMDAwMDAwMDAwMDAwMiIsIm5hbWUiOiJzdWJhZ2VudCByZXF1ZXN0Iiwic3RhcnRUaW1lVW5peE5hbm8iOiIyMDAiLCJlbmRUaW1lVW5peE5hbm8iOiIyMTAiLCJhdHRyaWJ1dGVzIjpbeyJrZXkiOiJvcGVuaml1d2VuLmV4ZWN1dGlvbi5zdWJqZWN0LmlkIiwidmFsdWUiOnsic3RyaW5nVmFsdWUiOiJzdWJhZ2VudDpicm93c2VyLW9uZSJ9fSx7ImtleSI6Im9wZW5qaXV3ZW4uZXhlY3V0aW9uLnN1YmplY3QuZGlzcGxheV9uYW1lIiwidmFsdWUiOnsic3RyaW5nVmFsdWUiOiJSZXNlYXJjaGVyIn19LHsia2V5Ijoib3BlbmppdXdlbi5leGVjdXRpb24uc3ViamVjdC5raW5kIiwidmFsdWUiOnsic3RyaW5nVmFsdWUiOiJzdWJhZ2VudCJ9fSx7ImtleSI6Im9wZW5qaXV3ZW4uZXhlY3V0aW9uLnN1YmplY3QucGFyZW50X2lkIiwidmFsdWUiOnsic3RyaW5nVmFsdWUiOiJtYWluIn19LHsia2V5Ijoib3BlbmppdXdlbi5leGVjdXRpb24uc3ViamVjdC5zZXNzaW9uX2lkIiwidmFsdWUiOnsic3RyaW5nVmFsdWUiOiJicm93c2VyLXN1YmFnZW50LXNlc3Npb24ifX1dfV19XX1dfQ==",+ "raw_valid": true,+ "otlp": {+ "resourceSpans": [{+ "scopeSpans": [{+ "spans": [{+ "traceId": "11111111111111111111111111111111",+ "spanId": "0000000000000002",+ "name": "subagent request",+ "startTimeUnixNano": "200",+ "endTimeUnixNano": "210",+ "attributes": [+ {"key": "openjiuwen.execution.subject.id", "value": {"stringValue": "subagent:browser-one"}},+ {"key": "openjiuwen.execution.subject.display_name", "value": {"stringValue": "Researcher"}},+ {"key": "openjiuwen.execution.subject.kind", "value": {"stringValue": "subagent"}},+ {"key": "openjiuwen.execution.subject.parent_id", "value": {"stringValue": "main"}},+ {"key": "openjiuwen.execution.subject.session_id", "value": {"stringValue": "browser-subagent-session"}}+ ]+ }]+ }]+ }]+ }+ }+ ]+}diff --git a/jiuwenswarm/channels/web/frontend/tests/singleAgentSurface.test.mjs b/jiuwenswarm/channels/web/frontend/tests/singleAgentSurface.test.mjsindex 230e26570e..22eb06fa3b 100644--- a/jiuwenswarm/channels/web/frontend/tests/singleAgentSurface.test.mjs+++ b/jiuwenswarm/channels/web/frontend/tests/singleAgentSurface.test.mjs@@ -10,22 +10,68 @@ import { createRoot } from 'react-dom/client';import { SingleAgentSurface } from '../node_modules/.cache/trajectory-host/SingleAgentSurface.mjs';-test('trajectory host exposes icon-only accessible sidebar controls', () => {+test('trajectory host relies on native sidebar controls', () => {const appSource = readFileSync(new URL('../src/App.tsx', import.meta.url), 'utf8');const panelSource = readFileSync(new URL('../src/features/trajectory/TrajectoryPanel.tsx', import.meta.url),'utf8',);+ const explorerSource = readFileSync(+ new URL('../src/features/trajectory/client/TrajectoryExplorer.tsx', import.meta.url),+ 'utf8',+ );+ const tableSource = readFileSync(+ new URL('../src/features/trajectory/client/TrajectoryTable.tsx', import.meta.url),+ 'utf8',+ );+ const chatPanelSource = readFileSync(+ new URL('../src/components/ChatPanel/index.tsx', import.meta.url),+ 'utf8',+ );+ const appStyles = readFileSync(new URL('../src/App.css', import.meta.url), 'utf8');- assert.match(appSource, /data-testid="trajectory-toggle-sessions"[\s\S]*?<span aria-hidden="true">/);- assert.match(appSource, /data-testid="trajectory-toggle-tasks"[\s\S]*?<span aria-hidden="true">/);- assert.match(appSource, /aria-label=\{trajectorySessionsCollapsed/);- assert.match(appSource, /data-tooltip=\{trajectoryTasksCollapsed/);+ assert.doesNotMatch(appSource, /data-testid="trajectory-toggle-sessions"/);+ assert.doesNotMatch(appSource, /data-testid="trajectory-toggle-tasks"/);+ assert.match(appSource, /chat-workspace--trajectory-floating-tools/);+ assert.match(appSource, /shouldInsetTrajectoryForFloatingTasks/);+ assert.doesNotMatch(appStyles, /transition:\s*padding-right/);+ assert.match(appSource, /showNavigation=\{sessionId !== NEW_CONVERSATION_ID\}/);assert.doesNotMatch(panelSource, /window\.setInterval/);assert.doesNotMatch(panelSource, /data-testid="trajectory-refresh"/);assert.match(panelSource, /data-testid="trajectory-archive-import"/);assert.match(panelSource, /data-testid="trajectory-archive-export"/);+ assert.doesNotMatch(panelSource, /preferBrowserFilePicker/);assert.match(panelSource, /data-testid="trajectory-archive-exit"/);+ assert.doesNotMatch(panelSource, /if \(!active \|\| sessionId === 'new'/);+ assert.match(panelSource, /'harness\.session_finished'/);+ assert.match(panelSource, /subjectGroups\.groups\.map/);+ assert.match(panelSource, /key=\{group\.subject\.id\}/);+ assert.match(panelSource, /data-trajectory-subject-explorer/);+ assert.match(panelSource, /createTrajectorySubjectViewCache/);+ assert.match(panelSource, /active=\{active && selected\}/);+ assert.match(panelSource, /deferredPublishRef\.current = true/);+ assert.match(panelSource, /setPublishedWindow\(\{/);+ assert.match(panelSource, /page\.items\.reduce\(\(count, summary\) => count \+ summary\.span_count, 0\)/);+ assert.match(panelSource, /role="progressbar"/);+ assert.match(panelSource, /initialLoadProgress\.loaded \/ initialLoadProgress\.total/);+ assert.match(panelSource, /error\.code === 'UNSUPPORTED_SESSION_MODE'/);+ assert.match(panelSource, /if \(staged === null[\s\S]*setError\(null\);/);+ assert.doesNotMatch(panelSource, /setRecords\(|setRawRecords\(|setLifecycleByRecordId\(/);+ assert.match(panelSource, /export const TrajectoryPanel = memo/);+ assert.match(explorerSource, /export const TrajectoryExplorer = memo/);+ assert.match(chatPanelSource, /export const ChatPanel = React\.memo/);+ assert.match(+ appStyles,+ /\.single-agent-surface--trajectory \.chat-panel-shell > :not\(\.chat-panel-header\) \{[\s\S]*?visibility: hidden;/,+ );+ assert.match(explorerSource, /if \(!active \|\| !hasRunningCells\) return undefined/);+ assert.match(tableSource, /\{ id: 'raw', label: 'Raw Output' \}/);+ assert.match(tableSource, /\{ id: 'facts', label: 'Facts' \}/);+ assert.match(tableSource, /data=\{selected\.cell\.compactionDetail\}/);+ assert.match(tableSource, /record\.cell\.isError[\s\S]*?css\.errorKindTag/);+ assert.match(tableSource, /label="Compaction facts JSON"/);+ assert.match(tableSource, />Session cumulative</);+ assert.doesNotMatch(tableSource, />Window cumulative</);});const dom = new JSDOM('<!doctype html><html><body></body></html>', {@@ -159,37 +205,28 @@ test('single-Agent tabs keep chat mounted and load trajectory only after first rassert.equal(counters.trajectoryUnmounts, 1);});-test('non-Agent modes never expose tabs or mount trajectory UI', async () => {- let trajectoryMounts = 0;- function TrajectoryProbe() {- trajectoryMounts += 1;- return React.createElement('div', null, 'trace');- }-+test('single-Agent welcome surface hides navigation until a conversation exists', async () => {const container = document.createElement('div');document.body.append(container);const root = createRoot(container);+await act(async () => {root.render(React.createElement(SingleAgentSurface, {- activeView: 'trajectory',- chat: React.createElement('div', { 'data-testid': 'chat-probe' }, 'chat'),+ activeView: 'chat',+ chat: React.createElement('div', { 'data-testid': 'welcome-probe' }, 'welcome'),chatLabel: 'Chat',- mode: 'team',+ mode: 'agent',onViewChange: () => {},+ showNavigation: false,tabListLabel: 'Single Agent surface',- trajectory: React.createElement(TrajectoryProbe),+ trajectory: React.createElement('div', null, 'trace'),trajectoryLabel: 'Trajectory',- trajectoryRequested: true,+ trajectoryRequested: false,}));});+ assert.ok(container.querySelector('[data-testid="welcome-probe"]'));assert.equal(container.querySelector('[data-testid="single-agent-surface-tabs"]'), null);- assert.equal(container.querySelector('[data-testid="single-agent-trajectory-view"]'), null);- assert.equal(- container.querySelector('[data-testid="single-agent-chat-view"]').getAttribute('aria-hidden'),- 'false',- );- assert.equal(trajectoryMounts, 0);await act(async () => {root.unmount();@@ -197,67 +234,37 @@ test('non-Agent modes never expose tabs or mount trajectory UI', async () => {container.remove();});-test('trajectory layout controls retain their state while chat stays mounted', async () => {- function Harness() {- const [activeView, setActiveView] = useState('chat');- const [collapsed, setCollapsed] = useState(false);- return React.createElement(SingleAgentSurface, {- activeView,- chat: React.createElement('div', { 'data-testid': 'chat-probe' }, 'chat'),- chatLabel: 'Chat',- mode: 'agent',- onViewChange: setActiveView,- tabListLabel: 'Single Agent surface',- trajectory: React.createElement('div', { 'data-testid': 'trajectory-probe' }, 'trace'),- trajectoryControls: React.createElement('button', {- 'aria-pressed': collapsed,- 'data-testid': 'layout-control',- onClick: () => setCollapsed((value) => !value),- type: 'button',- }, collapsed ? 'Show sessions' : 'Collapse sessions'),- trajectoryLabel: 'Trajectory',- trajectoryRequested: true,- });+test('non-Agent modes never expose tabs or mount trajectory UI', async () => {+ let trajectoryMounts = 0;+ function TrajectoryProbe() {+ trajectoryMounts += 1;+ return React.createElement('div', null, 'trace');}const container = document.createElement('div');document.body.append(container);const root = createRoot(container);await act(async () => {- root.render(React.createElement(Harness));+ root.render(React.createElement(SingleAgentSurface, {+ activeView: 'trajectory',+ chat: React.createElement('div', { 'data-testid': 'chat-probe' }, 'chat'),+ chatLabel: 'Chat',+ mode: 'team',+ onViewChange: () => {},+ tabListLabel: 'Single Agent surface',+ trajectory: React.createElement(TrajectoryProbe),+ trajectoryLabel: 'Trajectory',+ trajectoryRequested: true,+ }));});- assert.equal(container.querySelector('[data-testid="trajectory-layout-controls"]'), null);-- await act(async () => {- click(container.querySelector('[data-testid="single-agent-trajectory-tab"]'));- });+ assert.equal(container.querySelector('[data-testid="single-agent-surface-tabs"]'), null);+ assert.equal(container.querySelector('[data-testid="single-agent-trajectory-view"]'), null);assert.equal(- container.querySelector('[data-testid="layout-control"]').getAttribute('aria-pressed'),+ container.querySelector('[data-testid="single-agent-chat-view"]').getAttribute('aria-hidden'),'false',);-- await act(async () => {- click(container.querySelector('[data-testid="layout-control"]'));- });- assert.equal(- container.querySelector('[data-testid="layout-control"]').getAttribute('aria-pressed'),- 'true',- );-- await act(async () => {- click(container.querySelector('[data-testid="single-agent-chat-tab"]'));- });- assert.equal(container.querySelector('[data-testid="trajectory-layout-controls"]'), null);- assert.ok(container.querySelector('[data-testid="chat-probe"]'));-- await act(async () => {- click(container.querySelector('[data-testid="single-agent-trajectory-tab"]'));- });- assert.equal(- container.querySelector('[data-testid="layout-control"]').getAttribute('aria-pressed'),- 'true',- );+ assert.equal(trajectoryMounts, 0);await act(async () => {root.unmount();diff --git a/jiuwenswarm/channels/web/frontend/tests/trajectoryLayout.test.mjs b/jiuwenswarm/channels/web/frontend/tests/trajectoryLayout.test.mjsindex 75c7c44cff..171ffd9cef 100644--- a/jiuwenswarm/channels/web/frontend/tests/trajectoryLayout.test.mjs+++ b/jiuwenswarm/channels/web/frontend/tests/trajectoryLayout.test.mjs@@ -9,7 +9,7 @@ import {clampRawInspectorHeight,rawInspectorHeightBounds,rawInspectorKeyboardHeight,- resolveTrajectoryHostLayout,+ shouldInsetTrajectoryForFloatingTasks,} from '../node_modules/.cache/trajectory-layout/trajectoryLayout.js';test('raw inspector height is clamped to its fixed minimum and container-relative maximum', () => {@@ -30,17 +30,25 @@ test('raw inspector separator supports keyboard resizing and ignores unrelated kassert.equal(rawInspectorKeyboardHeight(125, 'ArrowDown', 600), 120);});-test('sidebar suppression applies only to the single-Agent trajectory view', () => {- assert.deepEqual(- resolveTrajectoryHostLayout('agent', 'trajectory', true, true, true),- { hideSessions: true, hideTasks: true, effectiveTeamAreaExpanded: false },+test('trajectory reserves space only for a visible collapsed floating task panel', () => {+ assert.equal(+ shouldInsetTrajectoryForFloatingTasks('agent', 'trajectory', true, false, false),+ true,);- assert.deepEqual(- resolveTrajectoryHostLayout('agent', 'chat', true, true, true),- { hideSessions: false, hideTasks: false, effectiveTeamAreaExpanded: true },+ assert.equal(+ shouldInsetTrajectoryForFloatingTasks('agent', 'trajectory', true, true, false),+ false,);- assert.deepEqual(- resolveTrajectoryHostLayout('team', 'trajectory', true, true, true),- { hideSessions: false, hideTasks: false, effectiveTeamAreaExpanded: true },+ assert.equal(+ shouldInsetTrajectoryForFloatingTasks('agent', 'trajectory', true, false, true),+ false,+ );+ assert.equal(+ shouldInsetTrajectoryForFloatingTasks('agent', 'chat', true, false, false),+ false,+ );+ assert.equal(+ shouldInsetTrajectoryForFloatingTasks('team', 'trajectory', true, false, false),+ false,);});diff --git a/jiuwenswarm/channels/web/frontend/tests/trajectoryPreview.test.mjs b/jiuwenswarm/channels/web/frontend/tests/trajectoryPreview.test.mjsnew file mode 100644index 0000000000..d5b9455ff9--- /dev/null+++ b/jiuwenswarm/channels/web/frontend/tests/trajectoryPreview.test.mjs@@ -0,0 +1,27 @@+// Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++import assert from 'node:assert/strict';+import test from 'node:test';++import {+ trajectoryDisplayText,+} from '../node_modules/.cache/trajectory-preview/preview.mjs';++test('assistant source and its compact Markdown preview are displayed once', () => {+ const output = '你好!我是你的个人智能体,有什么可以帮你的吗?\n\n随时告诉我。';+ assert.equal(trajectoryDisplayText(output, output), output);+});++test('equivalent whitespace-normalized assistant previews are displayed once', () => {+ assert.equal(+ trajectoryDisplayText('第一段\n\n第二段', '第一段 第二段'),+ '第一段\n\n第二段',+ );+});++test('a distinct record label still precedes its Markdown preview', () => {+ assert.equal(+ trajectoryDisplayText('Assistant response', '**完成**'),+ 'Assistant response · 完成',+ );+});diff --git a/jiuwenswarm/channels/web/frontend/tests/trajectoryProjector.test.mjs b/jiuwenswarm/channels/web/frontend/tests/trajectoryProjector.test.mjsindex 86d4f7a3d6..2885c19f8a 100644--- a/jiuwenswarm/channels/web/frontend/tests/trajectoryProjector.test.mjs+++ b/jiuwenswarm/channels/web/frontend/tests/trajectoryProjector.test.mjs@@ -2,7 +2,10 @@ import assert from 'node:assert/strict';import { readFile } from 'node:fs/promises';import test from 'node:test';-import { projectOtelTrajectory } from '../node_modules/.cache/trajectory-projector/projector.mjs';+import {+ createTrajectoryV2Reducer,+ projectOtelTrajectory,+} from '../node_modules/.cache/trajectory-projector/projector.mjs';function fixtureUrl(name) {return new URL(`../src/features/trajectory/fixtures/${name}`, import.meta.url);@@ -22,6 +25,143 @@ function cellsOf(snapshot) {));}+function spansOf(records) {+ return records.flatMap(record => (+ record.resourceSpans.flatMap(resource => (+ resource.scopeSpans.flatMap(scope => scope.spans)+ ))+ ));+}++function setStringAttribute(span, key, value) {+ const current = span.attributes.find(attribute => attribute.key === key);+ if (current === undefined) {+ span.attributes.push({ key, value: { stringValue: value } });+ return;+ }+ current.value = { stringValue: value };+}++function structuredMessage(role, content) {+ return { role, parts: [{ type: 'text', content }] };+}++function promptAttachmentMessage(mode, content) {+ return {+ ...structuredMessage('system', content),+ openjiuwen: { kind: 'prompt_attachment_history', mode },+ };+}++function v2Attribute(key, value, integer = false) {+ return { key, value: integer ? { intValue: String(value) } : { stringValue: String(value) } };+}++function v2Record({+ eventId,+ eventKind = 'context.window.commit',+ payload,+ requestId = 'request-1',+ sequence,+ sequenceEpoch = 'epoch-1',+ inferenceId = `inference-${sequence}`,+ step = sequence,+ stepId,+ subjectId = 'main',+ time = sequence * 1_000_000,+ traceId = '99999999999999999999999999999999',+ turn = 1,+ turnId,+}) {+ return {+ resourceSpans: [{+ scopeSpans: [{+ spans: [{+ traceId,+ spanId: String(sequence).padStart(16, '0'),+ parentSpanId: eventKind === 'context.window.commit' ? inferenceId : undefined,+ name: eventKind,+ startTimeUnixNano: String(time),+ endTimeUnixNano: String(time + 1),+ attributes: [+ v2Attribute('openjiuwen.trajectory.schema_version', '2'),+ v2Attribute('openjiuwen.trajectory.event_id', eventId),+ v2Attribute('openjiuwen.trajectory.event_kind', eventKind),+ v2Attribute('openjiuwen.trajectory.subject_id', subjectId),+ v2Attribute('openjiuwen.trajectory.subject_sequence', sequence, true),+ v2Attribute('openjiuwen.trajectory.sequence_epoch', sequenceEpoch),+ v2Attribute('openjiuwen.trajectory.session_id', 'session-v2'),+ v2Attribute('openjiuwen.trajectory.request_id', requestId),+ v2Attribute('openjiuwen.trajectory.recorded_at_unix_nano', time, true),+ v2Attribute('openjiuwen.turn.number', turn, true),+ v2Attribute('openjiuwen.step.number', step, true),+ ...(stepId === undefined+ ? []+ : [v2Attribute('openjiuwen.trajectory.step_id', stepId)]),+ ...(turnId === undefined+ ? []+ : [v2Attribute('openjiuwen.trajectory.turn_id', turnId)]),+ v2Attribute('openjiuwen.trajectory.payload', JSON.stringify(payload)),+ v2Attribute('langfuse.gen_ai.prompt.0.role', 'user'),+ v2Attribute('langfuse.gen_ai.prompt.0.content', 'must never become a v2 row'),+ ],+ }],+ }],+ }],+ };+}++function contextCommit(windowId, baseWindowId, messages, delta) {+ return {+ window_id: windowId,+ base_window_id: baseWindowId,+ complete: true,+ messages,+ delta: baseWindowId === null ? [] : delta,+ request_purpose: 'assistant',+ ...(baseWindowId === null ? {+ transition_kind: 'epoch_baseline',+ baseline_reason: 'runtime_epoch_start',+ } : {}),+ };+}++function contextMessage(messageId, role, content, origin) {+ const resolvedOrigin = origin ?? (role === 'user' ? 'external_user' : 'harness_internal');+ return {+ message_id: messageId,+ role,+ origin: resolvedOrigin,+ ...(resolvedOrigin === 'external_user' ? { source_kind: 'web' } : {}),+ content,+ };+}++function trajectoryPromptAttachmentMessage(messageId, content, state, mode = 'snapshot') {+ return {+ ...contextMessage(messageId, 'system', content, 'harness_internal'),+ metadata: {+ _openjiuwen_prompt_attachment_history: true,+ mode,+ session_id: 'session-v2',+ state,+ context_message_id: messageId,+ },+ };+}++function browserEphemeralContextMessage(messageId, slot, content) {+ const metadataKey = {+ working: 'browser_working_context',+ state: 'browser_state_context',+ progress: 'browser_state_progress_context',+ }[slot];+ return {+ ...contextMessage(messageId, 'user', content, 'harness_internal'),+ metadata: { [metadataKey]: true },+ };+}+test('Core forced-close child projects as error with its diagnostic reason', async () => {const snapshot = await projectFixture('core-contract-records.json');const forcedTool = cellsOf(snapshot).find(cell => (@@ -34,6 +174,186 @@ test('Core forced-close child projects as error with its diagnostic reason', asyassert.equal(forcedTool.result, 'trace_safety_flush');});+test('historical MCP raw lifecycle span is folded into its authoritative tool', async () => {+ const records = await fixtureRecords('core-contract-records.json');+ const tools = spansOf(records).filter(span => span.name.startsWith('tool.'));+ const authoritative = tools.find(span => span.attributes.some(attribute => (+ attribute.key === 'openjiuwen.tool.authoritative' && attribute.value.boolValue === true+ )));+ const lifecycle = tools.find(span => span !== authoritative);+ assert.ok(authoritative && lifecycle);+ const resourceId = 'playwright.playwright-official.browser_navigate';+ setStringAttribute(authoritative, 'gen_ai.tool.type', 'mcp');+ setStringAttribute(authoritative, 'openjiuwen.tool.type', 'mcp');+ setStringAttribute(authoritative, 'openjiuwen.tool.resource_id', resourceId);+ setStringAttribute(lifecycle, 'gen_ai.tool.id', resourceId);+ lifecycle.parentSpanId = authoritative.spanId;+ lifecycle.attributes = lifecycle.attributes.filter(attribute => (+ attribute.key !== 'gen_ai.tool.call.id'+ ));++ const projectedTools = cellsOf(projectOtelTrajectory(records)).filter(cell => (+ cell.kind === 'tool' || cell.kind === 'subtool'+ ));++ assert.equal(projectedTools.length, 1);+ assert.equal(projectedTools[0].kind, 'tool');+});++test('OTLP JSON numeric error status marks a failed tool cell', async () => {+ const records = await fixtureRecords('agent-loop-records.json');+ const tool = spansOf(records).find(span => span.attributes.some(attribute => (+ attribute.key === 'gen_ai.tool.call.id'+ && attribute.value.stringValue === 'call-loop-1'+ )));+ assert.ok(tool);+ tool.status = { code: 2, message: 'tool reported failure' };++ const snapshot = projectOtelTrajectory(records);+ const failedTool = cellsOf(snapshot).find(cell => cell.callId === 'call-loop-1');+ assert.ok(failedTool);+ assert.equal(failedTool.status, 'error');+ assert.equal(failedTool.isError, true);+ assert.equal(failedTool.result, 'tool reported failure');+});++test('ownerless ask_user result remains one routed TOOL while other ownerless tools stay isolated', async () => {+ const records = await fixtureRecords('core-contract-records.json');+ const toolRecord = records.find(record => spansOf([record]).some(span => (+ span.attributes.some(attribute => (+ attribute.key === 'openjiuwen.tool.authoritative'+ && attribute.value.boolValue === true+ ))+ )));+ assert.ok(toolRecord);+ const askUserRecord = structuredClone(toolRecord);+ const askUser = spansOf([askUserRecord])[0];+ assert.ok(askUser);+ const rootRecord = records.find(record => spansOf([record]).some(span => (+ span.spanId === askUser.parentSpanId+ )));+ assert.ok(rootRecord);+ const routedRootRecord = structuredClone(rootRecord);+ const routedRoot = spansOf([routedRootRecord])[0];+ assert.ok(routedRoot);+ askUser.name = 'tool.ask_user';+ setStringAttribute(askUser, 'gen_ai.tool.name', 'ask_user');+ setStringAttribute(askUser, 'gen_ai.tool.call.id', 'call-ask-user');+ setStringAttribute(askUser, 'gen_ai.tool.call.arguments', '{"questions":["Keep local?"]}');+ setStringAttribute(askUser, 'gen_ai.tool.call.result', 'Keep local');+ setStringAttribute(askUser, 'session.id', 'session-ask-user');+ setStringAttribute(askUser, 'gen_ai.conversation.id', 'session-ask-user');+ setStringAttribute(askUser, 'openjiuwen.execution.subject.id', 'main');+ setStringAttribute(askUser, 'openjiuwen.execution.subject.kind', 'main_agent');+ setStringAttribute(askUser, 'openjiuwen.execution.subject.session_id', 'session-ask-user');+ setStringAttribute(askUser, 'openjiuwen.request.id', 'resume-request');+ const turn = askUser.attributes.find(attribute => attribute.key === 'openjiuwen.turn.number');+ assert.ok(turn);+ turn.value = { intValue: '2' };+ setStringAttribute(routedRoot, 'session.id', 'session-ask-user');+ setStringAttribute(routedRoot, 'gen_ai.conversation.id', 'session-ask-user');+ setStringAttribute(routedRoot, 'openjiuwen.execution.subject.id', 'main');+ setStringAttribute(routedRoot, 'openjiuwen.execution.subject.kind', 'main_agent');+ setStringAttribute(routedRoot, 'openjiuwen.execution.subject.session_id', 'session-ask-user');++ const askUserCells = cellsOf(projectOtelTrajectory([routedRootRecord, askUserRecord]));+ assert.equal(askUserCells.length, 1);+ assert.equal(askUserCells[0].kind, 'tool');+ assert.match(askUserCells[0].text, /^ask_user/);+ assert.equal(askUserCells[0].callId, 'call-ask-user');+ assert.match(askUserCells[0].inputDetail, /Keep local/);+ assert.match(askUserCells[0].outputDetail, /Keep local/);+ assert.equal(askUserCells[0].requestRecordId, undefined);+ assert.equal(askUserCells[0].requestless, true);++ assert.equal(cellsOf(projectOtelTrajectory([askUserRecord])).length, 0);+ setStringAttribute(askUser, 'gen_ai.tool.name', 'bash');+ askUser.name = 'tool.bash';+ assert.equal(cellsOf(projectOtelTrajectory([routedRootRecord, askUserRecord])).length, 0);+});++test('system and external user lead pre-model tools while generated context follows them', async () => {+ const records = await fixtureRecords('core-contract-records.json');+ const rootRecord = structuredClone(records.find(record => spansOf([record]).some(span => (+ span.attributes.some(attribute => (+ attribute.key === 'openjiuwen.trace.root' && attribute.value.boolValue === true+ ))+ ))));+ const toolRecord = structuredClone(records.find(record => spansOf([record]).some(span => (+ span.attributes.some(attribute => (+ attribute.key === 'openjiuwen.tool.authoritative'+ && attribute.value.boolValue === true+ ))+ ))));+ const llmRecord = structuredClone(records.find(record => spansOf([record]).some(span => (+ span.name === 'llm.call'+ ))));+ assert.ok(rootRecord && toolRecord && llmRecord);+ const root = spansOf([rootRecord])[0];+ const tool = spansOf([toolRecord])[0];+ const llm = spansOf([llmRecord])[0];+ assert.ok(root && tool && llm);+ root.startTimeUnixNano = '1000000';+ root.endTimeUnixNano = '9000000';+ tool.startTimeUnixNano = '2000000';+ tool.endTimeUnixNano = '2500000';+ llm.startTimeUnixNano = '3000000';+ llm.endTimeUnixNano = '5000000';+ tool.name = 'tool.ask_user';+ tool.parentSpanId = root.spanId;+ setStringAttribute(tool, 'gen_ai.tool.name', 'ask_user');+ setStringAttribute(tool, 'gen_ai.tool.call.id', 'call-pre-model');+ setStringAttribute(tool, 'gen_ai.tool.call.arguments', '{"question":"Continue?"}');+ setStringAttribute(tool, 'gen_ai.tool.call.result', 'Continue');+ for (const span of [root, tool, llm]) {+ setStringAttribute(span, 'session.id', 'session-pre-model');+ setStringAttribute(span, 'gen_ai.conversation.id', 'session-pre-model');+ setStringAttribute(span, 'openjiuwen.execution.subject.id', 'main');+ setStringAttribute(span, 'openjiuwen.execution.subject.kind', 'main_agent');+ setStringAttribute(span, 'openjiuwen.execution.subject.session_id', 'session-pre-model');+ setStringAttribute(span, 'openjiuwen.request.id', 'request-pre-model');+ }+ setStringAttribute(llm, 'openjiuwen.inference.id', llm.spanId);+ const inferenceId = llm.attributes.find(attribute => (+ attribute.key === 'openjiuwen.inference.id'+ ))?.value.stringValue;+ assert.ok(inferenceId);+ const system = contextMessage(+ 'pre-model-system',+ 'system',+ 'system must lead the trajectory',+ 'harness_internal',+ );+ const user = contextMessage('pre-model-user', 'user', 'current request');+ user.source_kind = 'query';+ const preparedContext = browserEphemeralContextMessage(+ 'pre-model-state',+ 'state',+ 'prepared browser state',+ );+ const baseline = v2Record({+ eventId: 'event-pre-model-baseline',+ requestId: 'request-pre-model',+ sequence: 1,+ subjectId: 'main',+ time: 4_000_000,+ traceId: root.traceId,+ inferenceId,+ payload: contextCommit('window-pre-model', null, [system, user, preparedContext], []),+ });++ const snapshot = projectOtelTrajectory([rootRecord, toolRecord, llmRecord, baseline]);+ const cells = cellsOf(snapshot);++ assert.equal(snapshot.requests.length, 1);+ assert.equal(cells[0].kind, 'system');+ const setupTool = cells.find(cell => cell.kind === 'tool');+ assert.ok(setupTool);+ assert.equal(setupTool.requestless, true);+ assert.ok(cells.findIndex(cell => cell.text === 'current request') < cells.indexOf(setupTool));+ assert.ok(cells.findIndex(cell => cell.text === 'prepared browser state') > cells.indexOf(setupTool));+});+test('standard and OpenJiuwen fields win over conflicting legacy aliases', async () => {const snapshot = await projectFixture('core-contract-records.json');const request = snapshot.requests?.[0];@@ -49,22 +369,1123 @@ test('standard and OpenJiuwen fields win over conflicting legacy aliases', asyncassert.equal(assistant?.text, 'Core answer');});-test('legacy Langfuse and indexed gen_ai records remain projectable', async () => {- const snapshot = await projectFixture('legacy-langfuse-records.json');+test('schema-v2 context events preserve occurrence identity and never read Langfuse fields', () => {+ const first = contextMessage('message-a', 'user', 'same content');+ const second = contextMessage('message-b', 'user', 'same content');+ const record = v2Record({+ eventId: 'event-1',+ sequence: 1,+ payload: contextCommit('window-1', null, [first, second], [+ { op: 'insert', message_id: first.message_id, index: 0, message: first },+ { op: 'insert', message_id: second.message_id, index: 1, message: second },+ ]),+ });++ const cells = cellsOf(projectOtelTrajectory([record, record]));+ assert.deepEqual(cells.map(cell => cell.text), ['same content', 'same content']);+ assert.ok(cells.every(cell => cell.messageSource.kind === 'trajectory_context_delta'));+ assert.ok(cells.every(cell => !cell.text.includes('must never')));+});++test('schema-v2 user rows require the explicit Core external-user origin', () => {+ const external = contextMessage('external-user', 'user', 'same content');+ const internal = contextMessage(+ 'internal-user',+ 'user',+ 'same content',+ 'harness_internal',+ );+ const valid = v2Record({+ eventId: 'event-message-origins',+ sequence: 1,+ payload: contextCommit('window-message-origins', null, [external, internal], [+ { op: 'insert', message_id: external.message_id, index: 0, message: external },+ { op: 'insert', message_id: internal.message_id, index: 1, message: internal },+ ]),+ });+ const missingOriginMessage = { message_id: 'missing-origin', role: 'user', content: 'raw user' };+ const invalid = v2Record({+ eventId: 'event-missing-origin',+ sequence: 2,+ payload: contextCommit('window-missing-origin', 'window-message-origins', [+ external,+ internal,+ missingOriginMessage,+ ], [{+ op: 'insert',+ message_id: missingOriginMessage.message_id,+ index: 2,+ message: missingOriginMessage,+ }]),+ });++ const snapshot = projectOtelTrajectory([valid, invalid]);const cells = cellsOf(snapshot);- assert.equal(cells.find(cell => cell.kind === 'system')?.text, 'legacy system');- assert.ok(cells.some(cell => cell.kind === 'message' && cell.text === 'langfuse answer'));- assert.ok(cells.some(cell => (- cell.kind === 'tool'- && cell.callId === 'call-legacy'- && cell.result?.includes('legacy-result')+ assert.deepEqual(cells.map(cell => cell.kind), ['user', 'context']);+ assert.deepEqual(cells.map(cell => cell.messageSource.origin), [+ 'external_user',+ 'harness_internal',+ ]);+ assert.ok(snapshot.diagnostics.some(diagnostic => (+ diagnostic.code === 'v2.invalid_context_commit'+ && diagnostic.eventId === 'event-missing-origin')));- assert.ok(snapshot.requests?.some(request => (- request.recordedFacts?.correlation?.sessionId === 'old-openjiuwen-session'- && request.usage?.input === 0- && request.usage?.output === 4+});++test('schema-v2 system rows bind their own message and the complete prompt snapshot', () => {+ const stable = contextMessage('system-stable', 'system', 'stable instructions');+ const dynamic = contextMessage('system-dynamic', 'system', 'dynamic runtime context');+ const user = contextMessage('user-message', 'user', 'hello');+ const record = v2Record({+ eventId: 'event-system-detail',+ sequence: 1,+ payload: contextCommit('window-system-detail', null, [stable, dynamic, user], [+ { op: 'insert', message_id: stable.message_id, index: 0, message: stable },+ { op: 'insert', message_id: dynamic.message_id, index: 1, message: dynamic },+ { op: 'insert', message_id: user.message_id, index: 2, message: user },+ ]),+ });++ const systemCells = cellsOf(projectOtelTrajectory([record]))+ .filter(cell => cell.kind === 'system');+ assert.deepEqual(systemCells.map(cell => cell.text), [+ 'stable instructions',+ 'dynamic runtime context',+ ]);+ assert.deepEqual(systemCells.map(cell => cell.promptSystemMessageIndex), [0, 1]);+ assert.ok(systemCells.every(cell => (+ cell.promptDetail?.system === 'stable instructions\n\ndynamic runtime context')));+ assert.deepEqual(systemCells[0].promptDetail?.systemMessages, [+ { index: 0, content: 'stable instructions' },+ { index: 1, content: 'dynamic runtime context' },+ ]);+});++test('schema-v2 removed system rows retain their message-detail binding', () => {+ const system = contextMessage('system-removal', 'system', 'instructions being removed');+ const initial = v2Record({+ eventId: 'event-system-before-removal',+ sequence: 1,+ payload: contextCommit('window-before-removal', null, [system], [+ { op: 'insert', message_id: system.message_id, index: 0, message: system },+ ]),+ });+ const removed = v2Record({+ eventId: 'event-system-removal',+ sequence: 2,+ payload: contextCommit('window-after-removal', 'window-before-removal', [], [+ { op: 'remove', message_id: system.message_id, from_index: 0 },+ ]),+ });++ const removalCell = cellsOf(projectOtelTrajectory([initial, removed]))+ .find(cell => cell.recordId?.includes('event-system-removal'));+ assert.equal(removalCell?.kind, 'system');+ assert.equal(removalCell?.text, 'instructions being removed');+ assert.equal(removalCell?.promptSystemMessageIndex, 0);+ assert.equal(removalCell?.promptDetail?.system, '');+ assert.equal(removalCell?.previousPromptDetail?.system, 'instructions being removed');+});++test('schema-v2 system updates retain the previous prompt for diff rendering', () => {+ const before = contextMessage('system-update', 'system', 'runtime mode: agent');+ const after = contextMessage('system-update', 'system', 'runtime mode: smart agent');+ const initial = v2Record({+ eventId: 'event-system-before-update',+ sequence: 1,+ payload: contextCommit('window-before-update', null, [before], [+ { op: 'insert', message_id: before.message_id, index: 0, message: before },+ ]),+ });+ const replaced = v2Record({+ eventId: 'event-system-update',+ sequence: 2,+ payload: contextCommit('window-after-update', 'window-before-update', [after], [+ { op: 'replace', message_id: after.message_id, index: 0, message: after },+ ]),+ });++ const updateCell = cellsOf(projectOtelTrajectory([initial, replaced]))+ .find(cell => cell.recordId?.includes('event-system-update'));+ assert.equal(updateCell?.kind, 'system');+ assert.equal(updateCell?.text, 'runtime mode: smart agent');+ assert.equal(updateCell?.previousPromptDetail?.system, 'runtime mode: agent');+ assert.equal(updateCell?.promptDetail?.system, 'runtime mode: smart agent');+});++test('schema-v2 prompt attachment deltas update one Full Prompt slot', () => {+ const stable = contextMessage('system-stable', 'system', 'stable instructions');+ const before = {+ ...contextMessage('dynamic-snapshot', 'system', 'runtime mode: agent'),+ metadata: {+ _openjiuwen_prompt_attachment_history: true,+ mode: 'snapshot',+ },+ };+ const after = {+ ...contextMessage('dynamic-delta', 'system', 'runtime mode: smart agent'),+ metadata: {+ _openjiuwen_prompt_attachment_history: true,+ mode: 'delta',+ },+ };+ const updated = v2Record({+ eventId: 'event-dynamic-update',+ sequence: 1,+ payload: contextCommit('window-dynamic-update', null, [stable, before, after], [+ { op: 'insert', message_id: stable.message_id, index: 0, message: stable },+ { op: 'insert', message_id: before.message_id, index: 1, message: before },+ { op: 'insert', message_id: after.message_id, index: 2, message: after },+ ]),+ });++ const systemCells = cellsOf(projectOtelTrajectory([updated]))+ .filter(cell => cell.kind === 'system');+ assert.deepEqual(systemCells.map(cell => cell.text), [+ 'stable instructions',+ 'runtime mode: agent',+ 'runtime mode: smart agent',+ ]);+ const updateCell = systemCells[2];+ assert.equal(updateCell.promptSystemMessageIndex, 1);+ assert.deepEqual(updateCell.previousPromptDetail?.systemMessages, [+ { index: 0, content: 'stable instructions' },+ { index: 1, content: 'runtime mode: agent' },+ ]);+ assert.deepEqual(updateCell.promptDetail?.systemMessages, [+ { index: 0, content: 'stable instructions' },+ { index: 1, content: 'runtime mode: smart agent' },+ ]);+ assert.equal(+ updateCell.promptDetail?.system,+ 'stable instructions\n\nruntime mode: smart agent',+ );+});++test('browser ephemeral context replacement does not replay removed or unchanged slots', () => {+ const system = contextMessage(+ 'browser-system',+ 'system',+ 'browser agent prompt',+ 'harness_internal',+ );+ const query = contextMessage('browser-query', 'user', 'research stocks');+ const workingA = browserEphemeralContextMessage('working-a', 'working', 'working memory');+ const stateA = browserEphemeralContextMessage('state-a', 'state', 'state: about:blank');+ const progressA = browserEphemeralContextMessage('progress-a', 'progress', 'progress: initial');+ const baselineMessages = [system, query, workingA, stateA, progressA];+ const baseline = v2Record({+ eventId: 'event-browser-baseline',+ sequence: 1,+ payload: contextCommit('window-browser-a', null, baselineMessages, []),+ });+ const workingB = browserEphemeralContextMessage('working-b', 'working', 'working memory');+ const stateB = browserEphemeralContextMessage('state-b', 'state', 'state: finance page');+ const progressB = browserEphemeralContextMessage('progress-b', 'progress', 'progress: changed');+ const nextMessages = [system, query, workingB, stateB, progressB];+ const next = v2Record({+ eventId: 'event-browser-next',+ sequence: 2,+ payload: contextCommit('window-browser-b', 'window-browser-a', nextMessages, [+ { op: 'remove', message_id: workingA.message_id, index: 2 },+ { op: 'remove', message_id: stateA.message_id, index: 3 },+ { op: 'remove', message_id: progressA.message_id, index: 4 },+ { op: 'insert', message_id: workingB.message_id, index: 2, message: workingB },+ { op: 'insert', message_id: stateB.message_id, index: 3, message: stateB },+ { op: 'insert', message_id: progressB.message_id, index: 4, message: progressB },+ ]),+ });+ const assistant = contextMessage(+ 'browser-assistant',+ 'assistant',+ 'continue browsing',+ 'harness_internal',+ );+ const stateC = browserEphemeralContextMessage('state-b', 'state', 'state: losers page');+ const stableMessages = [system, query, assistant, workingB, stateC, progressB];+ const stable = v2Record({+ eventId: 'event-browser-stable-id',+ sequence: 3,+ payload: contextCommit('window-browser-c', 'window-browser-b', stableMessages, [+ { op: 'insert', message_id: assistant.message_id, index: 2, message: assistant },+ { op: 'move', message_id: workingB.message_id, from_index: 2, index: 3 },+ { op: 'move', message_id: stateB.message_id, from_index: 3, index: 4 },+ { op: 'replace', message_id: stateB.message_id, index: 4, message: stateC },+ { op: 'move', message_id: progressB.message_id, from_index: 4, index: 5 },+ ]),+ });++ const contexts = cellsOf(projectOtelTrajectory([baseline, next, stable])).filter(cell => (+ cell.kind === 'context'+ ));++ assert.deepEqual(contexts.map(cell => cell.text), [+ 'working memory',+ 'state: about:blank',+ 'progress: initial',+ 'state: finance page',+ 'progress: changed',+ 'state: losers page',+ ]);+ assert.deepEqual(contexts.slice(-3).map(cell => cell.messageSource.operation), [+ 'replace',+ 'replace',+ 'replace',+ ]);+ assert.deepEqual(contexts.slice(-3).map(cell => cell.previousInputDetail), [+ 'state: about:blank',+ 'progress: initial',+ 'state: finance page',+ ]);+});++test('schema-v2 compaction stays at its event position without replaying removed users', () => {+ const requestId = 'request-compaction-real-shape';+ const turnId = 'turn-compaction-real-shape';+ const stepId = 'step-compaction-real-shape';+ const original = contextMessage('message-original-user', 'user', 'research the bash tool');+ const transient = contextMessage(+ 'message-compaction-request',+ 'user',+ '## NON-NEGOTIABLE OUTPUT RULES',+ 'harness_internal',+ );+ const memory = contextMessage(+ 'message-compacted-memory',+ 'user',+ '<memory_block_current>compressed work</memory_block_current>',+ 'harness_internal',+ );+ const recovered = contextMessage(+ 'message-recovered-context',+ 'user',+ '<recovered_context>restored state</recovered_context>',+ 'harness_internal',+ );+ const before = v2Record({+ eventId: 'event-before-compaction',+ requestId,+ sequence: 1,+ step: 33,+ stepId,+ turnId,+ payload: {+ ...contextCommit('window-before-compaction', null, [original, transient], [+ { op: 'insert', message_id: original.message_id, index: 0, message: original },+ { op: 'insert', message_id: transient.message_id, index: 1, message: transient },+ ]),+ request_purpose: 'compaction',+ },+ });+ const compacted = v2Record({+ eventId: 'event-compaction-completed',+ eventKind: 'compaction.completed',+ requestId,+ sequence: 2,+ step: 33,+ stepId,+ turnId,+ payload: {+ type: 'context.compression_state',+ operation_id: 'operation-compaction-1',+ status: 'completed',+ phase: 'get_context_window',+ processor: 'CurrentRoundCompressor',+ model: 'openai/Deepseek-V4-Flash-0731',+ before: { messages: 101, tokens: 134929, context_percent: 67 },+ after: { messages: 8, tokens: 10326, context_percent: 5 },+ saved: { messages: 93, tokens: 124603, percent: 92.3 },+ duration_ms: 123645,+ model_requests: [{ request_id: 'physical-compaction-request', inference_id: 'inference-2' }],+ summary: 'Compressed 101 -> 8 messages',+ compact_summary: '# Compacted context\n\n- preserved the complete research result',+ },+ });+ const output = v2Record({+ eventId: 'event-after-compaction',+ requestId,+ sequence: 3,+ step: 33,+ stepId,+ turnId,+ payload: {+ ...contextCommit(+ 'window-after-compaction',+ 'window-before-compaction',+ [original, memory, recovered],+ [+ { op: 'remove', message_id: transient.message_id, from_index: 1 },+ { op: 'insert', message_id: memory.message_id, index: 1, message: memory },+ { op: 'insert', message_id: recovered.message_id, index: 2, message: recovered },+ ],+ ),+ transition_kind: 'compaction',+ caused_by_operation_id: 'operation-compaction-1',+ input_window_id: 'window-before-compaction',+ output_window_id: 'window-after-compaction',+ },+ });++ const snapshot = projectOtelTrajectory([output, compacted, before]);+ const cells = cellsOf(snapshot);++ assert.equal(snapshot.turns.length, 1);+ assert.deepEqual(cells.map(cell => cell.kind), [+ 'user', 'context', 'compacted', 'context', 'context',+ ]);+ assert.deepEqual(cells.map(cell => cell.text), [+ 'research the bash tool',+ '## NON-NEGOTIABLE OUTPUT RULES',+ 'Compressed 101 -> 8 messages',+ '<memory_block_current>compressed work</memory_block_current>',+ '<recovered_context>restored state</recovered_context>',+ ]);+ assert.deepEqual(cells.map(cell => cell.behaviorOrder), [+ 1 + 1 / 3,+ 1 + 2 / 3,+ 2,+ 3.5,+ 3.75,+ ]);+ assert.equal(cells[2].messageSource.operationId, 'operation-compaction-1');+ assert.equal(cells[2].outputDetail, '# Compacted context\n\n- preserved the complete research result');+ assert.deepEqual(cells[2].compactionDetail.before, {+ messages: 101,+ tokens: 134929,+ context_percent: 67,+ });+ assert.deepEqual(cells[2].compactionDetail.saved, {+ messages: 93,+ tokens: 124603,+ percent: 92.3,+ });+ assert.equal(cells[2].compactionDetail.duration_ms, 123645);+ assert.equal(cells[2].compactionDetail.processor, 'CurrentRoundCompressor');+ assert.equal(cells[2].compactionDetail.model, 'openai/Deepseek-V4-Flash-0731');+});++test('schema-v2 compaction never guesses missing or conflicting output correlation', () => {+ const build = (correlation) => {+ const retained = contextMessage('retained-user', 'user', 'retained user');+ const removed = contextMessage('removed-user', 'user', 'removed user');+ const before = v2Record({+ eventId: `before-${correlation.case}`,+ requestId: 'request-correlation',+ sequence: 1,+ step: 8,+ stepId: 'step-correlation',+ turnId: 'turn-correlation',+ payload: contextCommit('window-input', null, [retained, removed], [+ { op: 'insert', message_id: retained.message_id, index: 0, message: retained },+ { op: 'insert', message_id: removed.message_id, index: 1, message: removed },+ ]),+ });+ const compacted = v2Record({+ eventId: `compacted-${correlation.case}`,+ eventKind: 'compaction.completed',+ requestId: 'request-correlation',+ sequence: 2,+ step: 8,+ stepId: 'step-correlation',+ turnId: 'turn-correlation',+ payload: {+ operation_id: 'operation-correlation',+ input_window_id: 'window-input',+ output_window_id: 'window-output',+ summary: 'compacted',+ compact_summary: 'complete compacted output',+ model_requests: [{ request_id: 'physical-correlation-request', inference_id: 'inference-2' }],+ },+ });+ const output = v2Record({+ eventId: `output-${correlation.case}`,+ requestId: 'request-correlation',+ sequence: 3,+ step: 8,+ stepId: 'step-correlation',+ turnId: 'turn-correlation',+ payload: {+ ...contextCommit('window-output', 'window-input', [retained], [+ { op: 'remove', message_id: removed.message_id, from_index: 1 },+ ]),+ ...correlation.fields,+ },+ });+ return projectOtelTrajectory([output, compacted, before]);+ };++ const missing = build({ case: 'missing', fields: {} });+ assert.equal(cellsOf(missing).filter(cell => cell.text === 'removed user').length, 2);+ assert.ok(missing.diagnostics.some(diagnostic => (+ diagnostic.code === 'v2.missing_compaction_output_correlation'+ )));++ const incomplete = build({+ case: 'incomplete',+ fields: {+ transition_kind: 'compaction',+ caused_by_operation_id: 'operation-correlation',+ },+ });+ assert.equal(cellsOf(incomplete).filter(cell => cell.text === 'removed user').length, 2);+ assert.ok(incomplete.diagnostics.some(diagnostic => (+ diagnostic.code === 'v2.invalid_compaction_correlation'+ )));++ const conflicting = build({+ case: 'conflicting',+ fields: {+ transition_kind: 'compaction',+ caused_by_operation_id: 'operation-correlation',+ input_window_id: 'wrong-window',+ output_window_id: 'window-output',+ },+ });+ assert.equal(cellsOf(conflicting).filter(cell => cell.text === 'removed user').length, 2);+ assert.ok(conflicting.diagnostics.some(diagnostic => (+ diagnostic.code === 'v2.invalid_compaction_correlation'+ )));+});++test('epoch baseline preserves independent compaction correlation', () => {+ const compacted = v2Record({+ eventId: 'event-baseline-compaction',+ eventKind: 'compaction.completed',+ sequence: 1,+ payload: {+ operation_id: 'operation-baseline-compaction',+ model_requests: [{ request_id: 'physical-compaction', inference_id: 'inference-1' }],+ summary: 'Compacted before restart baseline',+ compact_summary: 'Compacted result',+ },+ });+ const memory = contextMessage(+ 'baseline-memory',+ 'user',+ '<memory_block_current>restored</memory_block_current>',+ 'harness_internal',+ );+ const baseline = v2Record({+ eventId: 'event-correlated-baseline',+ sequence: 2,+ payload: {+ ...contextCommit('window-correlated-baseline', null, [memory], []),+ correlation_kind: 'compaction',+ caused_by_operation_id: 'operation-baseline-compaction',+ input_window_id: null,+ output_window_id: 'window-correlated-baseline',+ },+ });++ const snapshot = projectOtelTrajectory([baseline, compacted]);++ assert.ok(cellsOf(snapshot).some(cell => (+ cell.kind === 'compacted' && cell.text === 'Compacted before restart baseline'+ )));+ assert.ok(!(snapshot.diagnostics ?? []).some(diagnostic => (+ diagnostic.code === 'v2.invalid_compaction_correlation'+ )));+});++test('model-free compaction remains visible without a physical model request', () => {+ const compacted = v2Record({+ eventId: 'event-model-free-compaction',+ eventKind: 'compaction.completed',+ sequence: 1,+ payload: {+ operation_id: 'operation-model-free',+ status: 'completed',+ processor: 'ToolResultWindowProcessor',+ model: '',+ model_requests: [],+ summary: 'Compressed 8 -> 8 messages, saved 5.9k tokens',+ compact_summary: '',+ },+ });++ const snapshot = projectOtelTrajectory([compacted]);+ const cells = cellsOf(snapshot);++ assert.equal(cells.length, 1);+ assert.equal(cells[0].kind, 'compacted');+ assert.equal(cells[0].messageSource.modelFree, true);+ assert.equal(cells[0].requestRecordId, undefined);+ assert.equal(cells[0].requestless, true);+ assert.ok(!(snapshot.diagnostics ?? []).some(diagnostic => (+ diagnostic.code === 'v2.missing_physical_request'+ || diagnostic.code === 'v2.missing_compaction_output_correlation'+ )));+});++test('v2 request context keeps logical input order when its event timestamp follows inference start', async () => {+ const records = structuredClone(await fixtureRecords('core-contract-records.json'));+ const inferenceRecord = records[1];+ const inference = spansOf([inferenceRecord])[0];+ setStringAttribute(inference, 'openjiuwen.step.id', 'step-first-request');+ setStringAttribute(inference, 'openjiuwen.request.id', 'request-first-order');+ setStringAttribute(inference, 'openjiuwen.inference.id', 'inference-first-request');+ inference.startTimeUnixNano = '2000000000';+ inference.endTimeUnixNano = '4000000000';+ const system = contextMessage('system-first', 'system', 'stable system');+ const user = contextMessage('user-first', 'user', 'first user');+ const event = v2Record({+ eventId: 'event-first-order',+ inferenceId: 'inference-first-request',+ requestId: 'request-first-order',+ sequence: 1,+ step: 1,+ stepId: 'step-first-request',+ time: 2005000000,+ traceId: inference.traceId,+ payload: contextCommit('window-first-order', null, [system, user], [+ { op: 'insert', message_id: system.message_id, index: 0, message: system },+ { op: 'insert', message_id: user.message_id, index: 1, message: user },+ ]),+ });++ const cumulative = { input: 1200, output: 300, total: 1500 };+ const snapshot = projectOtelTrajectory([inferenceRecord, event], {+ sessionCumulativeUsageByRequestIdentity: new Map([+ [`${inference.traceId}\u0000inference-first-request`, cumulative],+ ]),+ });+ const cells = cellsOf(snapshot);+ assert.deepEqual(cells.map(cell => cell.kind), ['system', 'user', 'message']);+ assert.deepEqual(cells.map(cell => cell.text), ['stable system', 'first user', 'Core answer']);+ assert.ok(cells[2].startedAt < cells[0].startedAt, 'recorded timestamps must remain unmodified');+ assert.ok(cells.every(cell => cell.requestRecordId === cells[2].requestRecordId));+ assert.deepEqual(snapshot.requests[0].cumulativeUsage, cumulative);+});++test('schema-v2 subject state stays isolated when concurrent subagents reuse sequences and window IDs', () => {+ const firstMessage = contextMessage('first', 'user', 'first subagent');+ const secondMessage = contextMessage('second', 'user', 'second subagent');+ const first = v2Record({+ eventId: 'event-first',+ sequence: 1,+ subjectId: 'subagent:first',+ payload: contextCommit('shared-window-id', null, [firstMessage], [+ { op: 'insert', message_id: 'first', index: 0, message: firstMessage },+ ]),+ });+ const second = v2Record({+ eventId: 'event-second',+ sequence: 1,+ subjectId: 'subagent:second',+ payload: contextCommit('shared-window-id', null, [secondMessage], [+ { op: 'insert', message_id: 'second', index: 0, message: secondMessage },+ ]),+ });+ const reducer = createTrajectoryV2Reducer();+ const firstSnapshot = projectOtelTrajectory([first], { v2Reducer: reducer });+ const secondSnapshot = projectOtelTrajectory([second], { v2Reducer: reducer });++ assert.deepEqual(cellsOf(firstSnapshot).map(cell => cell.text), ['first subagent']);+ assert.deepEqual(cellsOf(secondSnapshot).map(cell => cell.text), ['second subagent']);+});++test('schema-v2 sequence validation is isolated across runtime epochs', () => {+ const beforeRestart = contextMessage('before-restart', 'user', 'before restart');+ const afterRestart = contextMessage('after-restart', 'user', 'after restart');+ const records = [+ v2Record({+ eventId: 'event-before-restart',+ sequence: 1,+ sequenceEpoch: 'runtime-a',+ time: 1_000_000,+ traceId: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',+ payload: contextCommit('window-before-restart', null, [beforeRestart], [{+ op: 'insert',+ message_id: beforeRestart.message_id,+ index: 0,+ message: beforeRestart,+ }]),+ }),+ v2Record({+ eventId: 'event-after-restart',+ sequence: 1,+ sequenceEpoch: 'runtime-b',+ time: 2_000_000,+ traceId: 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb',+ payload: contextCommit('window-after-restart', null, [afterRestart], [{+ op: 'insert',+ message_id: afterRestart.message_id,+ index: 0,+ message: afterRestart,+ }]),+ }),+ ];++ const snapshot = projectOtelTrajectory(records);++ assert.deepEqual(cellsOf(snapshot).map(cell => cell.text), [+ 'before restart',+ 'after restart',+ ]);+ assert.ok(!(snapshot.diagnostics ?? []).some(diagnostic => (+ diagnostic.code === 'v2.sequence_conflict'+ )));+});++test('schema-v2 sequence orders interleaved traces inside one epoch', () => {+ const first = contextMessage('epoch-first', 'user', 'first input');+ const second = contextMessage('epoch-second', 'user', 'second input');+ const records = [+ v2Record({+ eventId: 'event-epoch-second',+ sequence: 2,+ sequenceEpoch: 'runtime-a',+ step: 1,+ time: 1_000_000,+ traceId: 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb',+ payload: contextCommit('window-epoch-second', 'window-epoch-first', [first, second], [{+ op: 'insert', message_id: second.message_id, index: 1, message: second,+ }]),+ }),+ v2Record({+ eventId: 'event-epoch-first',+ sequence: 1,+ sequenceEpoch: 'runtime-a',+ step: 1,+ time: 2_000_000,+ traceId: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',+ payload: contextCommit('window-epoch-first', null, [first], [{+ op: 'insert', message_id: first.message_id, index: 0, message: first,+ }]),+ }),+ ];++ const snapshot = projectOtelTrajectory(records);++ assert.deepEqual(cellsOf(snapshot).map(cell => cell.text), [+ 'first input',+ 'second input',+ ]);+ assert.equal(snapshot.diagnostics, undefined);+});++test('new epoch baseline does not replay unchanged logical system slots', () => {+ const stable = contextMessage(+ 'openjiuwen:request-system-slot:0',+ 'system',+ 'stable prompt',+ 'harness_internal',+ );+ const dynamic = trajectoryPromptAttachmentMessage(+ 'dynamic-a',+ 'runtime state',+ { runtime: 'same' },+ );+ const restoredDynamic = trajectoryPromptAttachmentMessage(+ 'dynamic-b',+ 'runtime state',+ { runtime: 'same' },+ );+ const current = contextMessage('current-query', 'user', 'current input');+ current.source_kind = 'query';+ const records = [+ v2Record({+ eventId: 'event-baseline-a',+ sequence: 1,+ sequenceEpoch: 'runtime-a',+ time: 1_000_000,+ payload: contextCommit('window-baseline-a', null, [stable, dynamic], []),+ }),+ v2Record({+ eventId: 'event-baseline-b',+ sequence: 1,+ sequenceEpoch: 'runtime-b',+ time: 2_000_000,+ payload: contextCommit('window-baseline-b', null, [+ stable,+ restoredDynamic,+ current,+ ], []),+ }),+ ];++ const cells = cellsOf(projectOtelTrajectory(records));++ assert.equal(cells.filter(cell => cell.kind === 'system').length, 2);+ assert.deepEqual(cells.filter(cell => cell.kind === 'user').map(cell => cell.text), [+ 'current input',+ ]);+});++test('new epoch baseline renders one update for a changed logical system slot', () => {+ const stable = contextMessage(+ 'openjiuwen:request-system-slot:0',+ 'system',+ 'stable prompt',+ 'harness_internal',+ );+ const before = trajectoryPromptAttachmentMessage(+ 'dynamic-a',+ 'runtime state: old',+ { runtime: 'old' },+ );+ const after = trajectoryPromptAttachmentMessage(+ 'dynamic-b',+ 'runtime state: new',+ { runtime: 'new' },+ );+ const records = [+ v2Record({+ eventId: 'event-update-a',+ sequence: 1,+ sequenceEpoch: 'runtime-a',+ time: 1_000_000,+ payload: contextCommit('window-update-a', null, [stable, before], []),+ }),+ v2Record({+ eventId: 'event-update-b',+ sequence: 1,+ sequenceEpoch: 'runtime-b',+ time: 2_000_000,+ payload: contextCommit('window-update-b', null, [stable, after], []),+ }),+ ];++ const systems = cellsOf(projectOtelTrajectory(records)).filter(cell => cell.kind === 'system');++ assert.equal(systems.length, 3);+ assert.equal(systems.at(-1).text, 'runtime state: new');+ assert.equal(systems.at(-1).messageSource.operation, 'replace');+ assert.ok(systems.at(-1).previousPromptDetail);+});++test('schema-v2 still rejects duplicate sequences inside one epoch', () => {+ const first = contextMessage('same-epoch-first', 'user', 'first');+ const second = contextMessage('same-epoch-second', 'user', 'second');+ const records = [+ v2Record({+ eventId: 'event-same-epoch-first',+ sequence: 1,+ sequenceEpoch: 'runtime-a',+ time: 1_000_000,+ payload: contextCommit('window-same-epoch-first', null, [first], [{+ op: 'insert', message_id: first.message_id, index: 0, message: first,+ }]),+ }),+ v2Record({+ eventId: 'event-same-epoch-second',+ sequence: 1,+ sequenceEpoch: 'runtime-a',+ time: 2_000_000,+ payload: contextCommit('window-same-epoch-second', null, [second], [{+ op: 'insert', message_id: second.message_id, index: 0, message: second,+ }]),+ }),+ ];++ const snapshot = projectOtelTrajectory(records);++ assert.deepEqual(cellsOf(snapshot).map(cell => cell.text), ['first']);+ assert.ok(snapshot.diagnostics.some(diagnostic => (+ diagnostic.code === 'v2.sequence_conflict'+ )));+});++test('attribute pressure and invalid v2 payloads cannot erase the last canonical event view', () => {+ const message = contextMessage('message-pressure', 'user', 'canonical pressure-safe input');+ const valid = v2Record({+ eventId: 'event-pressure',+ sequence: 1,+ payload: contextCommit('window-pressure', null, [message], [+ { op: 'insert', message_id: message.message_id, index: 0, message },+ ]),+ });+ const span = spansOf([valid])[0];+ for (let index = 0; index < 210; index += 1) {+ span.attributes.push(v2Attribute(`langfuse.gen_ai.prompt.${index}.content`, `legacy-${index}`));+ }+ const invalid = v2Record({+ eventId: 'event-invalid',+ sequence: 2,+ payload: { window_id: 'incomplete-window', complete: false },+ });+ const snapshot = projectOtelTrajectory([valid, invalid]);++ assert.deepEqual(cellsOf(snapshot).map(cell => cell.text), ['canonical pressure-safe input']);+ assert.ok(snapshot.diagnostics.some(item => item.code === 'v2.invalid_context_commit'));+});++test('only explicit compaction.completed events create v2 compaction history', () => {+ const record = v2Record({+ eventId: 'compaction-1',+ eventKind: 'compaction.completed',+ sequence: 1,+ payload: {+ operation_id: 'operation-1',+ input_window_id: 'window-before',+ output_window_id: 'window-after',+ summary: 'real compacted summary',+ compact_summary: 'full compacted result',+ model_requests: [{ request_id: 'physical-request-1', inference_id: 'inference-1' }],+ },+ });+ const missingCompactSummary = v2Record({+ eventId: 'compaction-missing-result',+ eventKind: 'compaction.completed',+ subjectId: 'subject-invalid-compaction',+ sequence: 1,+ payload: {+ operation_id: 'operation-missing-result',+ input_window_id: 'window-before-invalid',+ output_window_id: 'window-after-invalid',+ summary: 'statistics without the required result',+ model_requests: [{ request_id: 'physical-missing-result', inference_id: 'inference-1' }],+ },+ });+ const snapshot = projectOtelTrajectory([record, missingCompactSummary]);+ const cells = cellsOf(snapshot);++ assert.equal(cells.length, 1);+ assert.equal(cells[0].kind, 'compacted');+ assert.equal(cells[0].text, 'real compacted summary');+ assert.equal(cells[0].outputDetail, 'full compacted result');+ assert.equal(cells[0].compactionDetail.operation_id, 'operation-1');+ assert.equal(cells[0].messageSource.kind, 'trajectory_compaction');+ assert.ok(snapshot.diagnostics.some(diagnostic => (+ diagnostic.code === 'v2.invalid_compaction'+ && diagnostic.subjectId === 'subject-invalid-compaction'+ )));+});++test('one-to-many compaction inferences retain physical request boundaries', () => {+ const compacted = v2Record({+ eventId: 'compaction-many-requests',+ eventKind: 'compaction.completed',+ sequence: 1,+ payload: {+ operation_id: 'operation-many-requests',+ summary: 'compacted through two model calls',+ compact_summary: 'complete compacted output',+ model_requests: [+ { request_id: 'physical-request-a', inference_id: 'inference-a' },+ { request_id: 'physical-request-b', inference_id: 'inference-b' },+ ],+ },+ });+ const nextUser = contextMessage(+ 'assistant-context',+ 'user',+ 'internal assistant context',+ 'harness_internal',+ );+ const assistantContext = v2Record({+ eventId: 'assistant-physical-request',+ inferenceId: 'inference-assistant',+ sequence: 2,+ payload: contextCommit('assistant-window', null, [nextUser], [{+ op: 'insert',+ message_id: nextUser.message_id,+ index: 0,+ message: nextUser,+ }]),+ });++ const cells = cellsOf(projectOtelTrajectory([assistantContext, compacted]));+ const requestOnly = cells.find(cell => cell.requestOnly === true);+ const compactedCell = cells.find(cell => cell.kind === 'compacted' && cell.requestOnly !== true);+ const assistantCell = cells.find(cell => cell.text === 'internal assistant context');+ const traceId = compacted.resourceSpans[0].scopeSpans[0].spans[0].traceId;++ assert.equal(requestOnly?.requestRecordId, `${traceId}:inference:inference-a`);+ assert.equal(compactedCell?.requestRecordId, `${traceId}:inference:inference-b`);+ assert.equal(assistantCell?.requestRecordId, `${traceId}:inference:inference-assistant`);+ assert.notEqual(requestOnly?.requestRecordId, compactedCell?.requestRecordId);+ assert.notEqual(compactedCell?.requestRecordId, assistantCell?.requestRecordId);+});++test('schema-v2 reducer retains delta history for remove, move, and replace operations', () => {+ const alpha = contextMessage('alpha', 'user', 'alpha');+ const beta = contextMessage('beta', 'user', 'beta');+ const replacement = contextMessage('alpha', 'user', 'alpha replaced');+ const records = [+ v2Record({+ eventId: 'event-1',+ sequence: 1,+ payload: contextCommit('window-1', null, [alpha, beta], [+ { op: 'insert', message_id: 'alpha', index: 0, message: alpha },+ { op: 'insert', message_id: 'beta', index: 1, message: beta },+ ]),+ }),+ v2Record({+ eventId: 'event-2',+ sequence: 2,+ payload: contextCommit('window-2', 'window-1', [replacement], [+ { op: 'move', message_id: 'beta', from_index: 1, index: 0 },+ { op: 'remove', message_id: 'beta', from_index: 0 },+ { op: 'replace', message_id: 'alpha', index: 0, message: replacement },+ ]),+ }),+ ];++ const cells = cellsOf(projectOtelTrajectory(records));+ assert.deepEqual(cells.map(cell => cell.messageSource.operation), [+ 'insert', 'insert', 'move', 'remove', 'replace',+ ]);+ assert.ok(cells.some(cell => cell.text === 'alpha'));+ assert.ok(cells.some(cell => cell.text === 'alpha replaced'));+});++test('schema-v2 complete checkpoints recover across gaps and remain idempotent when gaps arrive later', () => {+ const one = contextMessage('one', 'user', 'one');+ const three = contextMessage('three', 'user', 'three');+ const first = v2Record({+ eventId: 'event-1',+ sequence: 1,+ payload: contextCommit('window-1', null, [one], [+ { op: 'insert', message_id: 'one', index: 0, message: one },+ ]),+ });+ const third = v2Record({+ eventId: 'event-3',+ sequence: 3,+ payload: contextCommit('window-3', 'missing-window', [one, three], [+ { op: 'insert', message_id: 'three', index: 1, message: three },+ ]),+ });+ const reducer = createTrajectoryV2Reducer();+ const recovered = projectOtelTrajectory([first, third], { v2Reducer: reducer });+ const duplicate = projectOtelTrajectory([third], { v2Reducer: reducer });++ assert.deepEqual(cellsOf(recovered).map(cell => cell.text), ['one', 'three']);+ assert.deepEqual(cellsOf(duplicate).map(cell => cell.text), ['one', 'three']);+ assert.ok(duplicate.diagnostics.some(item => item.code === 'v2.checkpoint_recovery'));+ assert.ok(duplicate.diagnostics.some(item => item.code === 'v2.missing_base_window'));+});++test('attribute-pressure llm.call spans keep tool-only and final Assistant requests visible', async () => {+ const snapshot = await projectFixture('attribute-pressure-llm-call-records.json');+ const cells = cellsOf(snapshot);+ const assistants = cells.filter(cell => cell.kind === 'message');+ const tool = cells.find(cell => cell.kind === 'tool');++ assert.equal(assistants.length, 2);+ assert.equal(assistants[0].text, 'Need one more tool');+ assert.equal(assistants[0].sourceBlocks.filter(block => block.type === 'tool-call').length, 1);+ assert.equal(assistants[1].text, 'Final pressure-safe answer');+ assert.ok(tool);+ assert.equal(tool.requestRecordId, assistants[0].requestRecordId);+ assert.notEqual(tool.requestRecordId, assistants[1].requestRecordId);+ assert.deepEqual(snapshot.requests.map(request => request.recordId), [+ 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:inference:inference-21',+ 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:inference:inference-22',+ ]);+});++test('canonical v2 context suppresses partial legacy diagnostics for the same request', async () => {+ const records = await fixtureRecords('attribute-pressure-llm-call-records.json');+ const llmSpans = spansOf(records).filter(span => span.name === 'llm.call');+ for (const span of llmSpans) {+ setStringAttribute(span, 'openjiuwen.request.id', 'request-pressure');+ }+ const system = contextMessage(+ 'pressure-system',+ 'system',+ 'complete canonical prompt',+ 'harness_internal',+ );+ const context = v2Record({+ eventId: 'event-pressure-context',+ requestId: 'request-pressure',+ sequence: 1,+ subjectId: 'subagent:pressure',+ traceId: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',+ inferenceId: 'inference-21',+ payload: contextCommit('window-pressure', null, [system], []),+ });++ const snapshot = projectOtelTrajectory([...records, context]);++ assert.ok(cellsOf(snapshot).some(cell => (+ cell.kind === 'system' && cell.text === 'complete canonical prompt'+ )));+ assert.ok(!(snapshot.diagnostics ?? []).some(diagnostic => (+ diagnostic.code === 'legacy.partial_snapshot'+ )));+});++test('Request numbers are local to an execution subject without changing physical ownership', async () => {+ const snapshot = await projectFixture('request-subject-number-records.json');+ const requests = snapshot.requests ?? [];++ assert.deepEqual(+ requests.map(request => [request.recordId, request.number]),+ [+ ['11111111111111111111111111111111:request:1', 1],+ ['22222222222222222222222222222222:request:2', 2],+ ['33333333333333333333333333333333:request:3', 1],+ ['33333333333333333333333333333333:request:4', 2],+ ['22222222222222222222222222222222:request:5', 3],+ ['44444444444444444444444444444444:request:6', 1],+ ],+ );+ const cells = cellsOf(snapshot);+ const mainThird = cells.find(cell => (+ cell.kind === 'message'+ && cell.requestRecordId === '22222222222222222222222222222222:request:5'+ ));+ const ownedTool = cells.find(cell => cell.kind === 'tool' && cell.text === 'lookup');+ assert.ok(mainThird && ownedTool);+ assert.equal(ownedTool.requestRecordId, mainThird.requestRecordId);+ assert.equal(cells.filter(cell => cell.kind === 'message' && cell.text === 'Repeated output').length, 6);+});++test('legacy archives deterministically rebuild Request numbers per subject and physical time', async () => {+ const records = await fixtureRecords('request-subject-number-records.json');+ for (const span of spansOf(records)) {+ span.attributes = span.attributes.filter(attribute => (+ attribute.key !== 'openjiuwen.execution.subject.request.number'+ ));+ }+ const reversed = structuredClone(records).reverse();+ const projected = projectOtelTrajectory(records);+ const projectedReversed = projectOtelTrajectory(reversed);+ const numbers = (projected.requests ?? []).map(request => [request.recordId, request.number]);++ assert.deepEqual(numbers, [+ ['11111111111111111111111111111111:request:1', 1],+ ['22222222222222222222222222222222:request:2', 2],+ ['33333333333333333333333333333333:request:3', 1],+ ['33333333333333333333333333333333:request:4', 2],+ ['22222222222222222222222222222222:request:5', 3],+ ['44444444444444444444444444444444:request:6', 1],+ ]);+ assert.deepEqual(+ (projectedReversed.requests ?? []).map(request => [request.recordId, request.number]),+ numbers,+ );+});++test('partially upgraded subject numbers rebuild the whole subject without gaps or duplicates', async () => {+ const records = await fixtureRecords('request-subject-number-records.json');+ const inferenceSpans = spansOf(records).filter(span => span.name === 'llm.call');+ assert.ok(inferenceSpans.length > 2);+ inferenceSpans[0].attributes = inferenceSpans[0].attributes.filter(attribute => (+ attribute.key !== 'openjiuwen.execution.subject.request.number'+ ));+ const malformed = inferenceSpans[1].attributes.find(attribute => (+ attribute.key === 'openjiuwen.execution.subject.request.number'+ ));+ assert.ok(malformed);+ malformed.value = { intValue: '99' };++ assert.deepEqual(+ (projectOtelTrajectory(records).requests ?? []).map(request => [request.recordId, request.number]),+ [+ ['11111111111111111111111111111111:request:1', 1],+ ['22222222222222222222222222222222:request:2', 2],+ ['33333333333333333333333333333333:request:3', 1],+ ['33333333333333333333333333333333:request:4', 2],+ ['22222222222222222222222222222222:request:5', 3],+ ['44444444444444444444444444444444:request:6', 1],+ ],+ );});test('behavior projection tracks session prompts, repeated users, attachments, and tools', async () => {@@ -84,6 +1505,8 @@ test('behavior projection tracks session prompts, repeated users, attachments, a'Session system v1','Session system v2',]);+ assert.equal(systemCells[0].previousPromptDetail, undefined);+ assert.equal(systemCells[1].previousPromptDetail?.system, 'Session system v1');assert.equal(repeatedUserCells.length, 2);assert.equal(cells.filter(cell => cell.text === 'New context fact').length, 1);assert.equal(attachmentCells.length, 4);@@ -119,6 +1542,46 @@ test('behavior projection tracks session prompts, repeated users, attachments, a))));});+test('real system message boundaries stay separate and only the changed slot updates', async () => {+ const records = await fixtureRecords('agent-loop-records.json');+ for (const span of spansOf(records)) {+ const instructions = span.attributes.find(attribute => (+ attribute.key === 'gen_ai.system_instructions'+ ));+ if (instructions === undefined) continue;+ const parts = JSON.parse(instructions.value.stringValue);+ const dynamic = parts.map(part => part.content ?? '').join('\n\n');+ // The stable prompt is the instruction given outside the history;+ // prompt-attachment turns are injected into the history itself.+ setStringAttribute(span, 'gen_ai.system_instructions', JSON.stringify([+ { type: 'text', content: 'Stable identity' },+ ]));+ const inputMessages = dynamic === 'Session system v2'+ ? [+ promptAttachmentMessage('snapshot', 'Session system v1'),+ ...Array.from({ length: 5 }, (_, index) => (+ structuredMessage(index % 2 === 0 ? 'user' : 'assistant', `history ${index}`)+ )),+ promptAttachmentMessage('delta', dynamic),+ ]+ : [promptAttachmentMessage('snapshot', dynamic)];+ setStringAttribute(span, 'gen_ai.input.messages', JSON.stringify(inputMessages));+ }++ const systemCells = cellsOf(projectOtelTrajectory(records))+ .filter(cell => cell.kind === 'system');+ assert.deepEqual(systemCells.map(cell => cell.text), [+ 'Stable identity',+ 'Session system v1',+ 'Session system v2',+ ]);+ assert.deepEqual(systemCells.map(cell => cell.promptSystemMessageIndex), [0, 1, 1]);+ assert.equal(systemCells[2].previousPromptDetail?.systemMessages[0].content, 'Stable identity');+ assert.equal(systemCells[2].previousPromptDetail?.systemMessages[1].content, 'Session system v1');+ assert.equal(systemCells[2].promptDetail?.systemMessages[1].content, 'Session system v2');+ assert.equal(systemCells[2].promptDetail?.system, 'Stable identity\n\nSession system v2');+});+test('legacy tool records without call ids use trace-local name and order fallback', async () => {const records = await fixtureRecords('agent-loop-records.json');const spans = records.flatMap(record => (@@ -235,6 +1698,110 @@ test('adjacent assistant replay uses stable text and tool-call projections acrosassert.ok(contextCells.every(cell => cell.timeSeconds === null));});+test('tool-ancestor branches do not reset the physical main context chain', async () => {+ const records = await fixtureRecords('agent-loop-records.json');+ const spans = spansOf(records);+ const first = spans.find(span => span.spanId === '1000000000000001');+ const second = spans.find(span => span.spanId === '2000000000000002');+ const branchTool = spans.find(span => span.spanId === '3000000000000003');+ const branch = spans.find(span => span.spanId === '4000000000000004');+ const final = spans.find(span => span.spanId === '5000000000000005');+ assert.ok(first && second && branchTool && branch && final);++ for (const span of spans) {+ setStringAttribute(span, 'openjiuwen.execution.subject.id', 'subagent-physical-1');+ }+ setStringAttribute(first, 'gen_ai.input.messages', JSON.stringify([+ structuredMessage('user', 'Root A'),+ ]));+ setStringAttribute(first, 'gen_ai.output.messages', JSON.stringify([+ structuredMessage('assistant', 'Root answer A'),+ ]));+ setStringAttribute(second, 'gen_ai.input.messages', JSON.stringify([+ structuredMessage('user', 'Root A'),+ structuredMessage('assistant', 'Root answer A'),+ structuredMessage('user', 'Before branch'),+ ]));+ setStringAttribute(second, 'gen_ai.output.messages', JSON.stringify([+ structuredMessage('assistant', 'Before branch answer'),+ ]));+ branch.parentSpanId = branchTool.spanId;+ setStringAttribute(branch, 'gen_ai.input.messages', JSON.stringify([+ structuredMessage('user', 'Nested multimodal branch'),+ ]));+ setStringAttribute(branch, 'gen_ai.output.messages', JSON.stringify([+ structuredMessage('assistant', 'Nested answer'),+ ]));+ setStringAttribute(final, 'gen_ai.input.messages', JSON.stringify([+ structuredMessage('user', 'Root A'),+ structuredMessage('assistant', 'Root answer A'),+ structuredMessage('user', 'Before branch'),+ structuredMessage('assistant', 'Before branch answer'),+ structuredMessage('user', 'After branch'),+ ]));+ setStringAttribute(final, 'gen_ai.output.messages', JSON.stringify([+ structuredMessage('assistant', 'Final answer'),+ ]));++ const inputs = cellsOf(projectOtelTrajectory(records)).filter(cell => (+ cell.kind === 'user' || cell.kind === 'context'+ ));+ assert.deepEqual(inputs.map(cell => cell.text), [+ 'Root A',+ 'Before branch',+ 'Nested multimodal branch',+ 'After branch',+ ]);+});++test('legacy tool-call aliases do not duplicate structured calls in one physical inference', async () => {+ const records = await fixtureRecords('core-contract-records.json');+ const inference = spansOf(records).find(span => span.spanId === '2000000000000000');+ assert.ok(inference);+ setStringAttribute(inference, 'gen_ai.output.messages', JSON.stringify([+ {+ role: 'assistant',+ parts: [+ { type: 'text', content: 'Core answer' },+ { type: 'tool_call', id: 'call-1', name: 'search', arguments: { q: 'next' } },+ ],+ tool_calls: [+ { id: 'call-1', name: 'search', arguments: { q: 'next' } },+ ],+ },+ ]));+ setStringAttribute(inference, 'gen_ai.tool_calls', JSON.stringify([+ { id: 'call-1', name: 'search', arguments: { q: 'next' } },+ ]));++ const assistant = cellsOf(projectOtelTrajectory(records)).find(cell => cell.kind === 'message');+ assert.ok(assistant);+ assert.equal(assistant.sourceBlocks.filter(block => block.type === 'tool-call').length, 1);+});++test('no-id calls keep physical multiplicity within one source and across output messages', async () => {+ const records = await fixtureRecords('core-contract-records.json');+ const inference = spansOf(records).find(span => span.spanId === '2000000000000000');+ assert.ok(inference);+ const call = { type: 'tool_call', name: 'search', arguments: { q: 'same' } };+ setStringAttribute(inference, 'gen_ai.output.messages', JSON.stringify([+ {+ role: 'assistant',+ parts: [call],+ tool_calls: [+ { name: 'search', arguments: { q: 'same' } },+ { name: 'search', arguments: { q: 'same' } },+ ],+ },+ { role: 'assistant', parts: [call] },+ ]));++ const assistant = cellsOf(projectOtelTrajectory(records)).find(cell => cell.kind === 'message');+ assert.ok(assistant);+ const calls = assistant.sourceBlocks.filter(block => block.type === 'tool-call');+ assert.equal(calls.length, 3);+});+test('provisional inference projects running lifecycle without a fabricated end time', async () => {const records = await fixtureRecords('standard-records.json');const inferenceRecord = records.find(record => record.resourceSpans.some(resource => (@@ -302,4 +1869,17 @@ test('every inference keeps an independent request identity inside a shared stepassistants.map(cell => cell.requestRecordId),requestIds,);++ const spans = spansOf(records);+ const secondInference = spans.find(span => span.spanId === '2000000000000002');+ const tool = spans.find(span => span.spanId === '3000000000000003');+ assert.ok(secondInference && tool);+ tool.parentSpanId = secondInference.spanId;+ const ownedSnapshot = projectOtelTrajectory(records);+ const ownedTool = cellsOf(ownedSnapshot).find(cell => cell.kind === 'tool');+ const owner = cellsOf(ownedSnapshot).find(cell => (+ cell.kind === 'message' && cell.recordId?.includes(secondInference.spanId)+ ));+ assert.ok(ownedTool && owner);+ assert.equal(ownedTool.requestRecordId, owner.requestRecordId);});diff --git a/jiuwenswarm/channels/web/frontend/tests/trajectorySubjects.test.mjs b/jiuwenswarm/channels/web/frontend/tests/trajectorySubjects.test.mjsnew file mode 100644index 0000000000..616d7d9e52--- /dev/null+++ b/jiuwenswarm/channels/web/frontend/tests/trajectorySubjects.test.mjs@@ -0,0 +1,352 @@+import assert from 'node:assert/strict';+import test from 'node:test';++import {+ createTrajectorySubjectViewCache,+ groupTrajectorySubjects,+ MAIN_TRAJECTORY_SUBJECT_ID,+ UNASSIGNED_TRAJECTORY_SUBJECT_ID,+} from '../node_modules/.cache/trajectory-window/trajectorySubjects.mjs';+import {+ parseTrajectoryArchive,+ trajectoryArchiveView,+} from '../node_modules/.cache/trajectory-window/trajectoryArchive.mjs';++const TRACE_ID = '11111111111111111111111111111111';++function attribute(key, value) {+ return { key, value: { stringValue: value } };+}++function record(spanId, name, startTimeUnixNano, subject) {+ const attributes = subject === undefined ? [] : [+ attribute('openjiuwen.execution.subject.id', subject.id),+ attribute('openjiuwen.execution.subject.display_name', subject.displayName),+ attribute('openjiuwen.execution.subject.kind', subject.kind),+ ...(subject.parentId === null+ ? []+ : [attribute('openjiuwen.execution.subject.parent_id', subject.parentId)]),+ attribute('openjiuwen.execution.subject.session_id', subject.sessionId),+ ];+ return {+ resourceSpans: [{+ scopeSpans: [{+ spans: [{+ traceId: TRACE_ID,+ spanId,+ name,+ startTimeUnixNano,+ endTimeUnixNano: `${BigInt(startTimeUnixNano) + 10n}`,+ attributes,+ }],+ }],+ }],+ };+}++function detail(otlp, ingestSeq) {+ const span = otlp.resourceSpans[0].scopeSpans[0].spans[0];+ return {+ ingest_seq: ingestSeq,+ record_id: `${span.traceId}:${span.spanId}`,+ record_revision: 1,+ lifecycle: 'completed',+ operation: 'upsert',+ observed_time_unix_nano: span.startTimeUnixNano,+ trace_id: span.traceId,+ span_id: span.spanId,+ otlp,+ raw_valid: true,+ };+}++const main = {+ id: 'main',+ displayName: 'Main Agent',+ kind: 'main_agent',+ parentId: null,+ sessionId: 'session-main',+};+const subagentOne = {+ id: 'subagent:one',+ displayName: 'Researcher',+ kind: 'subagent',+ parentId: 'main',+ sessionId: 'session-sub-one',+};+const subagentTwo = {+ id: 'subagent:two',+ displayName: 'Researcher',+ kind: 'subagent',+ parentId: 'main',+ sessionId: 'session-sub-two',+};++test('explicit subject identity separates repeated same-name subagent invocations', () => {+ const records = [+ record('0000000000000001', 'main context', '100', main),+ record('0000000000000002', 'subagent one request', '200', subagentOne),+ record('0000000000000003', 'subagent two request', '300', subagentTwo),+ ];+ const rawRecords = records.map(detail);+ const lifecycle = new Map(rawRecords.map(item => [item.record_id, 'completed']));+ const result = groupTrajectorySubjects(records, rawRecords, lifecycle);++ assert.deepEqual(result.groups.map(group => group.subject.id), [+ MAIN_TRAJECTORY_SUBJECT_ID,+ subagentOne.id,+ subagentTwo.id,+ ]);+ assert.deepEqual(result.groups.map(group => group.label), [+ 'Main Agent',+ 'Researcher 1',+ 'Researcher 2',+ ]);+ assert.deepEqual(+ result.byId.get(subagentOne.id).records.map(item => item.resourceSpans[0].scopeSpans[0].spans[0].name),+ ['subagent one request'],+ );+ assert.equal(result.byId.get(subagentOne.id).subject.parentId, 'main');+ assert.equal(result.byId.get(subagentOne.id).subject.sessionId, 'session-sub-one');+ assert.equal(result.byId.get(subagentOne.id).lifecycleByRecordId.size, 1);+});++test('an incremental first subagent record creates its subject group immediately', () => {+ const mainRecord = record('0000000000000010', 'main request', '100', main);+ const firstWindow = groupTrajectorySubjects(+ [mainRecord],+ [detail(mainRecord, 1)],+ new Map(),+ );+ assert.deepEqual(firstWindow.groups.map(group => group.subject.id), [+ MAIN_TRAJECTORY_SUBJECT_ID,+ ]);++ const subagentRecord = record(+ '0000000000000011',+ 'first live subagent request',+ '200',+ subagentOne,+ );+ const nextWindow = groupTrajectorySubjects(+ [mainRecord, subagentRecord],+ [detail(mainRecord, 1), detail(subagentRecord, 2)],+ new Map(),+ );+ assert.deepEqual(nextWindow.groups.map(group => group.subject.id), [+ MAIN_TRAJECTORY_SUBJECT_ID,+ subagentOne.id,+ ]);+ assert.equal(nextWindow.byId.get(subagentOne.id).records.length, 1);+});++test('the first schema-v2 subagent event creates a tab without misusing the owner session as execution session', () => {+ const subagentEvent = record('0000000000000019', 'context.window.commit', '400');+ const span = subagentEvent.resourceSpans[0].scopeSpans[0].spans[0];+ span.attributes.push(+ attribute('openjiuwen.trajectory.schema_version', '2'),+ attribute('openjiuwen.trajectory.subject_id', 'subagent:v2-first'),+ attribute('openjiuwen.trajectory.session_id', 'session-main'),+ );++ const result = groupTrajectorySubjects(+ [subagentEvent],+ [detail(subagentEvent, 1)],+ new Map(),+ 'session-main',+ );+ const group = result.byId.get('subagent:v2-first');++ assert.ok(group);+ assert.equal(group.subject.kind, 'subagent');+ assert.equal(group.subject.parentId, MAIN_TRAJECTORY_SUBJECT_ID);+ assert.equal(group.subject.sessionId, null);+ assert.equal(group.records.length, 1);+});++test('subject view cache reuses every unchanged group and projection', () => {+ const records = [+ record('0000000000000020', 'main request', '100', main),+ record('0000000000000021', 'subagent one request', '200', subagentOne),+ record('0000000000000022', 'subagent two request', '300', subagentTwo),+ ];+ const rawRecords = records.map(detail);+ const lifecycle = new Map(rawRecords.map(item => [item.record_id, 'completed']));+ const cache = createTrajectorySubjectViewCache();+ let projections = 0;+ const project = (group) => ({ subjectId: group.subject.id, call: ++projections });+ const first = cache.update(+ groupTrajectorySubjects(records, rawRecords, lifecycle),+ project,+ );+ const second = cache.update(+ groupTrajectorySubjects([...records], [...rawRecords], new Map(lifecycle)),+ project,+ );++ assert.equal(projections, 3);+ for (const group of first.groups.groups) {+ assert.equal(second.groups.byId.get(group.subject.id), group);+ assert.equal(second.snapshots.get(group.subject.id), first.snapshots.get(group.subject.id));+ }+});++test('one changed subagent invalidates only its own projection cache entry', () => {+ const mainRecord = record('0000000000000030', 'main request', '100', main);+ const subOneRecord = record('0000000000000031', 'subagent one request', '200', subagentOne);+ const subTwoRecord = record('0000000000000032', 'subagent two request', '300', subagentTwo);+ const records = [mainRecord, subOneRecord, subTwoRecord];+ const rawRecords = records.map(detail);+ const lifecycle = new Map(rawRecords.map(item => [item.record_id, 'completed']));+ const cache = createTrajectorySubjectViewCache();+ let projections = 0;+ const project = (group) => ({ subjectId: group.subject.id, call: ++projections });+ const first = cache.update(groupTrajectorySubjects(records, rawRecords, lifecycle), project);+ const changedSubOne = record(+ '0000000000000033',+ 'subagent one terminal record',+ '400',+ subagentOne,+ );+ const nextRecords = [...records, changedSubOne];+ const nextRawRecords = [...rawRecords, detail(changedSubOne, 4)];+ const second = cache.update(+ groupTrajectorySubjects(nextRecords, nextRawRecords, lifecycle),+ project,+ );++ assert.equal(projections, 4);+ assert.equal(+ second.snapshots.get(MAIN_TRAJECTORY_SUBJECT_ID),+ first.snapshots.get(MAIN_TRAJECTORY_SUBJECT_ID),+ );+ assert.notEqual(+ second.snapshots.get(subagentOne.id),+ first.snapshots.get(subagentOne.id),+ );+ assert.equal(+ second.snapshots.get(subagentTwo.id),+ first.snapshots.get(subagentTwo.id),+ );+});++test('adding a same-name subagent relabels its peer without reprojecting that peer', () => {+ const mainRecord = record('0000000000000040', 'main request', '100', main);+ const subOneRecord = record('0000000000000041', 'subagent one request', '200', subagentOne);+ const cache = createTrajectorySubjectViewCache();+ let projections = 0;+ const project = (group) => ({ subjectId: group.subject.id, call: ++projections });+ const firstRecords = [mainRecord, subOneRecord];+ const firstRaw = firstRecords.map(detail);+ const first = cache.update(+ groupTrajectorySubjects(firstRecords, firstRaw, new Map()),+ project,+ );+ const subTwoRecord = record('0000000000000042', 'subagent two request', '300', subagentTwo);+ const secondRecords = [...firstRecords, subTwoRecord];+ const secondRaw = [...firstRaw, detail(subTwoRecord, 3)];+ const second = cache.update(+ groupTrajectorySubjects(secondRecords, secondRaw, new Map()),+ project,+ );++ assert.equal(projections, 3);+ assert.equal(first.groups.byId.get(subagentOne.id).label, 'Researcher');+ assert.equal(second.groups.byId.get(subagentOne.id).label, 'Researcher 1');+ assert.equal(+ second.snapshots.get(subagentOne.id),+ first.snapshots.get(subagentOne.id),+ );+});++test('legacy records stay in Main but malformed explicit subjects never leak into Main', () => {+ const legacy = record('0000000000000004', 'legacy main', '100');+ const malformed = record('0000000000000005', 'malformed', '200', {+ ...subagentOne,+ parentId: null,+ });+ const records = [legacy, malformed];+ const result = groupTrajectorySubjects(records, records.map(detail), new Map());++ assert.deepEqual(+ result.byId.get(MAIN_TRAJECTORY_SUBJECT_ID).records.map(item => item.resourceSpans[0].scopeSpans[0].spans[0].name),+ ['legacy main'],+ );+ assert.deepEqual(+ result.byId.get(UNASSIGNED_TRAJECTORY_SUBJECT_ID).records.map(item => item.resourceSpans[0].scopeSpans[0].spans[0].name),+ ['malformed'],+ );+});++test('a subagent execution session owned by another chat is excluded', () => {+ const ownerSession = 'session-current';+ const current = record('0000000000000008', 'current subagent', '100', {+ ...subagentOne,+ sessionId: `${ownerSession}_sub_general_current`,+ });+ const leaked = record('0000000000000009', 'old subagent', '200', {+ ...subagentTwo,+ sessionId: 'session-previous_sub_general_old',+ });++ const result = groupTrajectorySubjects(+ [current, leaked],+ [detail(current, 1), detail(leaked, 2)],+ new Map(),+ ownerSession,+ );++ assert.ok(result.byId.has(subagentOne.id));+ assert.equal(result.byId.has(subagentTwo.id), false);+});++test('Archive v1 replay produces the same execution-subject groups as live records', () => {+ const records = [+ record('0000000000000006', 'main request', '100', main),+ record('0000000000000007', 'subagent request', '200', subagentOne),+ ];+ const archiveRecords = records.map((otlp, index) => {+ const span = otlp.resourceSpans[0].scopeSpans[0].spans[0];+ return {+ record_id: `${span.traceId}:${span.spanId}`,+ record_revision: 1,+ lifecycle: 'final',+ operation: 'upsert',+ change_seq: String(index + 1),+ observed_time_unix_nano: span.startTimeUnixNano,+ trace_id: span.traceId,+ span_id: span.spanId,+ raw_json_base64: Buffer.from(JSON.stringify(otlp)).toString('base64'),+ raw_valid: true,+ otlp,+ };+ });+ const archive = parseTrajectoryArchive(JSON.stringify({+ format: 'openjiuwen.trajectory.archive',+ archive_version: 1,+ session_id: 'session-main',+ store_epoch: 'epoch-1',+ revision: '2',+ exported_at: '2026-08-21T00:00:00Z',+ records: archiveRecords,+ }));+ const replay = trajectoryArchiveView(archive);+ const live = groupTrajectorySubjects(+ records,+ records.map(detail),+ new Map(records.map(item => {+ const span = item.resourceSpans[0].scopeSpans[0].spans[0];+ return [`${span.traceId}:${span.spanId}`, 'completed'];+ })),+ );+ const archived = groupTrajectorySubjects(+ replay.records,+ replay.rawRecords,+ replay.lifecycleByRecordId,+ );++ assert.deepEqual(+ archived.groups.map(group => [group.subject.id, group.records.length]),+ live.groups.map(group => [group.subject.id, group.records.length]),+ );+});diff --git a/jiuwenswarm/channels/web/frontend/tests/trajectoryWindow.test.mjs b/jiuwenswarm/channels/web/frontend/tests/trajectoryWindow.test.mjsindex 31b8ab54da..5556761537 100644--- a/jiuwenswarm/channels/web/frontend/tests/trajectoryWindow.test.mjs+++ b/jiuwenswarm/channels/web/frontend/tests/trajectoryWindow.test.mjs@@ -8,14 +8,119 @@ import {collectHeadRefreshWindow,collectRevisionRefreshWindow,createTrajectoryOperationCoordinator,+ createTrajectoryTraceHintCoordinator,createTrajectoryWindowState,resetTrajectoryWindowState,+ sameTrajectoryUsageMap,selectSummariesNeedingLoad,+ shouldCatchUpAfterTrajectoryTerminalEvent,stageTrajectoryTracePages,trajectoryContentMode,} from '../node_modules/.cache/trajectory-window/trajectoryWindow.mjs';++test('unchanged cumulative usage does not require another trajectory publish', () => {+ const previous = new Map([+ ['trace-a\0inference-1', { input: 10, cacheRead: 2, output: 3, reasoning: 1, total: 13 }],+ ]);+ const same = new Map([+ ['trace-a\0inference-1', { input: 10, cacheRead: 2, output: 3, reasoning: 1, total: 13 }],+ ]);+ const changed = new Map([+ ['trace-a\0inference-1', { input: 10, cacheRead: 2, output: 4, reasoning: 1, total: 14 }],+ ]);++ assert.equal(sameTrajectoryUsageMap(previous, same), true);+ assert.equal(sameTrajectoryUsageMap(previous, changed), false);+ assert.equal(sameTrajectoryUsageMap(previous, new Map()), false);+});++test('one hint flight chases the highest revision that arrives while loading', async () => {+ const coordinator = createTrajectoryTraceHintCoordinator();+ const batches = [];+ let releaseFirstBatch;+ const firstBatch = new Promise(resolve => {+ releaseFirstBatch = resolve;+ });+ coordinator.enqueue('a'.repeat(32), 10);+ const flight = coordinator.drain(async (hints) => {+ batches.push([...hints]);+ if (batches.length === 1) await firstBatch;+ });++ coordinator.enqueue('a'.repeat(32), 11);+ coordinator.enqueue('a'.repeat(32), 13);+ coordinator.enqueue('b'.repeat(32), 2);+ const sharedFlight = coordinator.drain(async () => {+ assert.fail('a second loader must not create a concurrent flight');+ });+ assert.equal(sharedFlight, flight);++ releaseFirstBatch();+ await flight;+ assert.deepEqual(batches, [+ [['a'.repeat(32), 10]],+ [['a'.repeat(32), 13], ['b'.repeat(32), 2]],+ ]);+});++test('a drained hint coordinator accepts a later independent flight', async () => {+ const coordinator = createTrajectoryTraceHintCoordinator();+ const batches = [];+ coordinator.enqueue('c'.repeat(32), 1);+ await coordinator.drain(async hints => batches.push([...hints]));+ coordinator.enqueue('c'.repeat(32), 2);+ await coordinator.drain(async hints => batches.push([...hints]));++ assert.deepEqual(batches, [+ [['c'.repeat(32), 1]],+ [['c'.repeat(32), 2]],+ ]);+});++test('a paced hint flight bounds pulls while retaining the newest watermark', async () => {+ const coordinator = createTrajectoryTraceHintCoordinator();+ const batches = [];+ const paceWaiters = [];+ coordinator.enqueue('d'.repeat(32), 1);+ const flight = coordinator.drain(+ async hints => {+ batches.push([...hints]);+ if (batches.length === 1) {+ coordinator.enqueue('d'.repeat(32), 2);+ coordinator.enqueue('d'.repeat(32), 9);+ }+ },+ () => new Promise(resolve => paceWaiters.push(resolve)),+ );++ await new Promise(resolve => setImmediate(resolve));+ assert.deepEqual(batches, [[['d'.repeat(32), 1]]]);+ assert.equal(paceWaiters.length, 1);+ paceWaiters.shift()();+ await flight;+ assert.deepEqual(batches, [+ [['d'.repeat(32), 1]],+ [['d'.repeat(32), 9]],+ ]);+});++test('a failed hint batch is requeued for the next recovery drain', async () => {+ const coordinator = createTrajectoryTraceHintCoordinator();+ coordinator.enqueue('e'.repeat(32), 7);+ await assert.rejects(+ coordinator.drain(async () => {+ throw new Error('temporary detail failure');+ }),+ /temporary detail failure/,+ );++ const recovered = [];+ await coordinator.drain(async hints => recovered.push([...hints]));+ assert.deepEqual(recovered, [[['e'.repeat(32), 7]]]);+});import {getTrajectoryArchive,+ getTrajectorySessionUsage,getTrajectoryTrace,listTrajectoryTraceRevisions,listTrajectoryTraces,@@ -31,6 +136,34 @@ import { liveElapsedSeconds } from '../node_modules/.cache/trajectory-window/recconst SESSION_ID = 'session-1';const STORE_EPOCH = 'epoch-1';+test('session terminal events catch up missed trajectory hints without treating start as terminal', () => {+ assert.equal(shouldCatchUpAfterTrajectoryTerminalEvent(+ 'chat.processing_status',+ { session_id: SESSION_ID, is_processing: false },+ SESSION_ID,+ ), true);+ assert.equal(shouldCatchUpAfterTrajectoryTerminalEvent(+ 'chat.processing_status',+ { session_id: SESSION_ID, is_processing: true },+ SESSION_ID,+ ), false);+ assert.equal(shouldCatchUpAfterTrajectoryTerminalEvent(+ 'chat.final',+ { session_id: SESSION_ID },+ SESSION_ID,+ ), true);+ assert.equal(shouldCatchUpAfterTrajectoryTerminalEvent(+ 'harness.session_finished',+ { payload: { event: { session_id: SESSION_ID } } },+ SESSION_ID,+ ), true);+ assert.equal(shouldCatchUpAfterTrajectoryTerminalEvent(+ 'chat.error',+ { session_id: 'another-session' },+ SESSION_ID,+ ), false);+});+function hexId(value, width) {return value.toString(16).padStart(width, '0');}@@ -376,6 +509,42 @@ test('trajectory client consumes opaque list and revision cursors', async () =>}});+test('trajectory client reads session cumulative usage by physical request identity', async () => {+ const originalFetch = globalThis.fetch;+ const traceId = 'a'.repeat(32);+ try {+ globalThis.fetch = async input => {+ assert.match(String(input), /\/sessions\/session-1\/usage$/);+ return new Response(JSON.stringify({+ schema_version: 1,+ session_id: SESSION_ID,+ store_epoch: STORE_EPOCH,+ scope: 'session',+ items: [{+ trace_id: traceId,+ inference_id: 'inference-1',+ subject_id: 'main',+ start_time_unix_nano: '10',+ usage: { input: 2, output: 1, total: 3 },+ cumulative_usage: { input: 5, output: 3, total: 8 },+ }],+ }), { status: 200 });+ };++ const usage = await getTrajectorySessionUsage(SESSION_ID);++ assert.equal(usage.scope, 'session');+ assert.equal(usage.items[0].trace_id, traceId);+ assert.deepEqual(usage.items[0].cumulative_usage, {+ input: 5,+ output: 3,+ total: 8,+ });+ } finally {+ globalThis.fetch = originalFetch;+ }+});+test('trajectory client accepts the additive provisional detail contract', async () => {const originalFetch = globalThis.fetch;const record = projectedRecord(11);@@ -921,6 +1090,90 @@ test('a later detail-page failure leaves the current bucket untouched', async ()assert.deepEqual([...current.rawRecords.keys()], [identity]);});+test('progressive detail publish exposes only consumed page revisions before a later failure', async () => {+ const existing = projectedRecord(20);+ const identity = `${existing.trace_id}:${existing.span_id}`;+ const current = {+ revision: 20,+ records: new Map([[identity, existing.otlp]]),+ rawRecords: new Map([[identity, existing]]),+ };+ const published = [];+ let calls = 0;+ const controller = new AbortController();++ await assert.rejects(+ stageTrajectoryTracePages(+ current,+ controller.signal,+ async () => {+ calls += 1;+ if (calls === 1) {+ return detailPage({+ revision: 30,+ records: [projectedRecord(21)],+ hasMore: true,+ nextSinceRevision: 21,+ });+ }+ throw new Error('page two failed after visible progress');+ },+ progress => published.push(progress),+ ),+ /page two failed after visible progress/,+ );++ assert.equal(published.length, 1);+ assert.equal(published[0].bucket.revision, 21);+ assert.equal(published[0].bucket.records.size, 2);+ assert.notEqual(published[0].bucket.revision, 30);+ assert.equal(current.revision, 20);+});++test('progressive detail publish advances each page cursor and reaches target only at the final page', async () => {+ const published = [];+ let calls = 0;+ const controller = new AbortController();+ const staged = await stageTrajectoryTracePages(+ undefined,+ controller.signal,+ async (sinceRevision) => {+ calls += 1;+ if (calls === 1) {+ assert.equal(sinceRevision, 0);+ return detailPage({+ revision: 3,+ records: [projectedRecord(1)],+ hasMore: true,+ nextSinceRevision: 1,+ });+ }+ if (calls === 2) {+ assert.equal(sinceRevision, 1);+ return detailPage({+ revision: 3,+ records: [projectedRecord(2)],+ hasMore: true,+ nextSinceRevision: 2,+ });+ }+ assert.equal(sinceRevision, 2);+ return detailPage({+ revision: 3,+ records: [projectedRecord(3)],+ hasMore: false,+ nextSinceRevision: 3,+ });+ },+ progress => published.push(progress),+ );++ assert.ok(staged);+ assert.deepEqual(published.map(progress => progress.bucket.revision), [1, 2, 3]);+ assert.deepEqual(published.map(progress => progress.bucket.records.size), [1, 2, 3]);+ assert.equal(staged, published[2]);+});+test('aborting after a staged detail page never returns a publishable bucket', async () => {const current = {revision: 0,diff --git a/jiuwenswarm/common/mode_matrix.py b/jiuwenswarm/common/mode_matrix.pyindex 920609a422..38d33ba449 100644--- a/jiuwenswarm/common/mode_matrix.py+++ b/jiuwenswarm/common/mode_matrix.py@@ -113,7 +113,12 @@ TEAM_CANONICAL_MODES: frozenset[str] = frozenset(# UI. This is deliberately an allowlist: future modes must opt in explicitly# instead of becoming readable merely because they are not known Team modes.SINGLE_AGENT_CANONICAL_MODES: frozenset[str] = frozenset(- {"agent", "agent.fast", "agent.plan", "code", "code.normal", "code.plan"}+ {+ NEW_AGENT_WORK_NORMAL,+ NEW_AGENT_WORK_PLAN,+ NEW_AGENT_CODE_NORMAL,+ NEW_AGENT_CODE_PLAN,+ })# 所有表示"正处于 plan"的 canonical 模式。diff --git a/jiuwenswarm/gateway/channel_manager/web/trajectory_http.py b/jiuwenswarm/gateway/channel_manager/web/trajectory_http.pyindex f4005915c8..82c3391ad3 100644--- a/jiuwenswarm/gateway/channel_manager/web/trajectory_http.py+++ b/jiuwenswarm/gateway/channel_manager/web/trajectory_http.py@@ -57,7 +57,10 @@ class TrajectoryHttpService:metadata_loader: SessionMetadataLoader | None = None,) -> None:self.settings = settings- self.reader = reader or AsyncTrajectoryReader(settings.database_path)+ self.reader = reader or AsyncTrajectoryReader(+ settings.database_path,+ session_scoped=True,+ )self._metadata_loader = metadata_loader or _load_session_metadataasync def list_traces(@@ -148,6 +151,31 @@ class TrajectoryHttpService:)return response+ async def get_session_usage(self, session_id: str) -> Response:+ """Return session-complete request usage partitioned by execution subject."""+ error = self._validate_access(session_id)+ if error is not None:+ return error+ try:+ items, store_epoch = await self.reader.get_session_request_usage(session_id)+ except Exception:+ logger.exception(+ "Trajectory session-usage query failed: session_id=%s",+ session_id,+ )+ return _error_response(+ "trajectory query failed",+ "TRAJECTORY_QUERY_FAILED",+ 500,+ )+ return _json_response({+ "schema_version": 1,+ "session_id": session_id,+ "store_epoch": store_epoch,+ "scope": "session",+ "items": items,+ })+async def list_revisions(self,session_id: str,@@ -479,6 +507,18 @@ def attach_trajectory_routes(return origin_errorreturn await service.export_archive(session_id)+ @app.get(f"{TRAJECTORY_API_PREFIX}/sessions/{{session_id}}/usage")+ async def get_trajectory_session_usage(+ session_id: str,+ request: Request,+ ) -> Response:+ """Read session-complete cumulative request usage."""+ request.state.trajectory_route_handled = True+ origin_error = _validate_http_origin(request)+ if origin_error is not None:+ return origin_error+ return await service.get_session_usage(session_id)+@app.get(f"{TRAJECTORY_API_PREFIX}/sessions/{{session_id}}/traces/{{trace_id}}")async def get_trajectory_trace(session_id: str,diff --git a/jiuwenswarm/observability/__init__.py b/jiuwenswarm/observability/__init__.pyindex ea8e89157e..422c957710 100644--- a/jiuwenswarm/observability/__init__.py+++ b/jiuwenswarm/observability/__init__.py@@ -10,7 +10,10 @@ from jiuwenswarm.observability.models import (TraceSinkStats,WriteBatchResult,)-from jiuwenswarm.observability.sink import TrajectoryRecordSink+from jiuwenswarm.observability.sink import (+ TrajectoryRecordSink,+ TrajectorySessionSinkRouter,+)from jiuwenswarm.observability.runtime import (get_trajectory_runtime_sink,shutdown_trajectory_runtime,@@ -26,6 +29,7 @@ __all__ = ["TraceRecordData","TraceSinkStats","TrajectoryRecordSink",+ "TrajectorySessionSinkRouter","TrajectoryStore","TrajectoryStoreSettings","WriteBatchResult",diff --git a/jiuwenswarm/observability/config.py b/jiuwenswarm/observability/config.pyindex 41874b2d74..f2909d7d5a 100644--- a/jiuwenswarm/observability/config.py+++ b/jiuwenswarm/observability/config.py@@ -4,6 +4,7 @@from __future__ import annotations+import hashlibfrom collections.abc import Mappingfrom dataclasses import dataclassfrom pathlib import Path@@ -18,6 +19,7 @@ DEFAULT_FLUSH_INTERVAL_MS = 200DEFAULT_RETENTION_DAYS = 7DEFAULT_POLL_INTERVAL_MS = 2000DEFAULT_DETAIL_MAX_BYTES = 4 * 1024 * 1024+DEFAULT_SESSION_DATABASE_DIRECTORY = "sessions"@dataclass(frozen=True, slots=True)@@ -60,13 +62,33 @@ def _positive_int(value: Any, default: int, *, minimum: int = 1) -> int:def _resolve_database_path(value: Any, workspace: Path) -> Path:raw_path = str(value or "").strip()if not raw_path:- return workspace / ".trace" / "trajectory.sqlite3"+ return workspace / ".trace" / DEFAULT_SESSION_DATABASE_DIRECTORYconfigured = Path(raw_path).expanduser()if configured.is_absolute():return configuredreturn workspace / configured+def session_database_path(database_root: Path, session_id: str) -> Path:+ """Return the traversal-safe SQLite path owned by one session.++ Args:+ database_root: Root directory containing all session databases.+ session_id: Stable session identifier used only as hash input.++ Returns:+ A platform-independent path containing no user-controlled component.++ Raises:+ ValueError: If the session identifier is empty or padded.+ """+ normalized_session_id = str(session_id or "").strip()+ if not normalized_session_id or normalized_session_id != session_id:+ raise ValueError("session_id must be a non-empty normalized string")+ digest = hashlib.sha256(normalized_session_id.encode("utf-8")).hexdigest()+ return Path(database_root) / digest[:2] / f"{digest}.sqlite3"++def load_trajectory_store_settings(config: Mapping[str, Any] | None = None,*,@@ -114,6 +136,8 @@ def load_trajectory_store_settings(__all__ = ["DEFAULT_DETAIL_MAX_BYTES",+ "DEFAULT_SESSION_DATABASE_DIRECTORY","TrajectoryStoreSettings","load_trajectory_store_settings",+ "session_database_path",]diff --git a/jiuwenswarm/observability/gateway_hints.py b/jiuwenswarm/observability/gateway_hints.pynew file mode 100644index 0000000000..89499105b0--- /dev/null+++ b/jiuwenswarm/observability/gateway_hints.py@@ -0,0 +1,156 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""Cross-process delivery of committed trajectory revision hints."""++from __future__ import annotations++import asyncio+import logging+import threading+from collections.abc import Awaitable, Callable+from typing import Any++from jiuwenswarm.observability.models import CommittedTraceUpdate++logger = logging.getLogger(__name__)++GatewayPushSender = Callable[[dict[str, Any]], Awaitable[bool | None]]+_RETRY_DELAY_SECONDS = 0.1+++class TrajectoryGatewayHintBridge:+ """Move writer-thread commits onto the AgentServer-to-Gateway socket.++ The trajectory SQLite writer and browser WebSocket channel live in+ different processes. The process-local update broker therefore cannot+ wake the Gateway. This bridge carries only revision watermarks over the+ existing AgentServer push connection; SQLite remains the source of truth.+ """++ def __init__(self) -> None:+ self._lock = threading.Lock()+ self._loop: asyncio.AbstractEventLoop | None = None+ self._sender: GatewayPushSender | None = None+ self._pending: dict[tuple[str, str], CommittedTraceUpdate] = {}+ self._drain_task: asyncio.Task[None] | None = None++ def bind(+ self,+ loop: asyncio.AbstractEventLoop,+ sender: GatewayPushSender,+ ) -> None:+ """Bind the AgentServer event loop and its existing push sender."""+ with self._lock:+ self._loop = loop+ self._sender = sender++ async def unbind(self) -> None:+ """Stop future delivery and cancel the loop-owned drain task."""+ with self._lock:+ self._loop = None+ self._sender = None+ self._pending.clear()+ task = self._drain_task+ self._drain_task = None+ if task is not None and not task.done():+ task.cancel()+ try:+ await task+ except asyncio.CancelledError:+ pass++ def publish(self, updates: tuple[CommittedTraceUpdate, ...]) -> None:+ """Coalesce committed hints and schedule a lossless loop-side drain."""+ with self._lock:+ loop = self._loop+ if loop is None or loop.is_closed():+ return+ for update in updates:+ session_id = str(update.session_id or "").strip()+ trace_id = str(update.trace_id or "").strip()+ if not session_id or not trace_id:+ continue+ key = (session_id, trace_id)+ current = self._pending.get(key)+ if current is None or update.revision >= current.revision:+ self._pending[key] = update+ if not self._pending:+ return+ loop.call_soon_threadsafe(self._ensure_drain)++ def _ensure_drain(self) -> None:+ """Create at most one sender task on the bound event loop."""+ task = self._drain_task+ if task is None or task.done():+ self._drain_task = asyncio.create_task(self._drain())++ async def _drain(self) -> None:+ """Keep draining revisions that arrive while an earlier send is in flight."""+ try:+ while True:+ with self._lock:+ sender = self._sender+ if sender is None or not self._pending:+ return+ updates = tuple(self._pending.values())+ self._pending.clear()+ retry_needed = False+ for update in updates:+ try:+ delivered = await sender(_push_message(update))+ except Exception:+ logger.exception(+ "Trajectory revision hint push failed: session_id=%s trace_id=%s revision=%d",+ update.session_id,+ update.trace_id,+ update.revision,+ )+ delivered = False+ if delivered is False:+ self._requeue(update)+ retry_needed = True+ if retry_needed:+ await asyncio.sleep(_RETRY_DELAY_SECONDS)+ finally:+ self._drain_task = None+ with self._lock:+ loop = self._loop+ has_pending = bool(self._pending)+ if has_pending and loop is not None and not loop.is_closed():+ loop.call_soon(self._ensure_drain)++ def _requeue(self, update: CommittedTraceUpdate) -> None:+ """Keep the newest unsent watermark until the Gateway reconnects."""+ key = (update.session_id, update.trace_id)+ with self._lock:+ current = self._pending.get(key)+ if current is None or update.revision >= current.revision:+ self._pending[key] = update+++def _push_message(update: CommittedTraceUpdate) -> dict[str, Any]:+ return {+ "request_id": (+ f"trajectory:{update.session_id}:{update.trace_id}:{update.revision}"+ ),+ "channel_id": "web",+ "session_id": update.session_id,+ "payload": {+ "event_type": "trace.updated",+ "session_id": update.session_id,+ "trace_id": update.trace_id,+ "revision": update.revision,+ "store_epoch": update.store_epoch,+ "lifecycle": update.lifecycle,+ },+ "is_complete": False,+ }+++trajectory_gateway_hint_bridge = TrajectoryGatewayHintBridge()+++__all__ = [+ "TrajectoryGatewayHintBridge",+ "trajectory_gateway_hint_bridge",+]diff --git a/jiuwenswarm/observability/runtime.py b/jiuwenswarm/observability/runtime.pyindex 234b344dcd..c62765c1d3 100644--- a/jiuwenswarm/observability/runtime.py+++ b/jiuwenswarm/observability/runtime.py@@ -12,24 +12,31 @@ from jiuwenswarm.observability.config import (TrajectoryStoreSettings,load_trajectory_store_settings,)-from jiuwenswarm.observability.sink import CommitCallback, TrajectoryRecordSink+from jiuwenswarm.observability.gateway_hints import trajectory_gateway_hint_bridge+from jiuwenswarm.observability.session_delete import (+ set_trajectory_session_delete_backend,+)+from jiuwenswarm.observability.sink import (+ CommitCallback,+ TrajectorySessionSinkRouter,+)from jiuwenswarm.observability.updates import trajectory_update_brokerlogger = logging.getLogger(__name__)class _SpanRecordProcessorLike(Protocol):- def register_consumer(self, consumer: TrajectoryRecordSink) -> None:+ def register_consumer(self, consumer: TrajectorySessionSinkRouter) -> None:"""Register one sink by object identity."""...- def unregister_consumer(self, consumer: TrajectoryRecordSink) -> None:+ def unregister_consumer(self, consumer: TrajectorySessionSinkRouter) -> None:"""Unregister one sink by object identity."""..._runtime_lock = threading.RLock()-_runtime_sink: TrajectoryRecordSink | None = None+_runtime_sink: TrajectorySessionSinkRouter | None = None_runtime_processor: _SpanRecordProcessorLike | None = None_runtime_settings: TrajectoryStoreSettings | None = None@@ -38,7 +45,7 @@ def sync_trajectory_runtime(settings: TrajectoryStoreSettings | None = None,*,on_commit: CommitCallback | None = None,-) -> TrajectoryRecordSink | None:+) -> TrajectorySessionSinkRouter | None:"""Synchronize the AgentServer sink with the current trajectory settings."""resolved = settings or load_trajectory_store_settings()if not resolved.enabled:@@ -51,7 +58,7 @@ def start_trajectory_runtime(settings: TrajectoryStoreSettings | None = None,*,on_commit: CommitCallback | None = None,-) -> TrajectoryRecordSink | None:+) -> TrajectorySessionSinkRouter | None:"""Start and register the process-wide sink once.The sink is ready before it is exposed to Core. A settings change performs@@ -89,6 +96,7 @@ def start_trajectory_runtime(except Exception:logger.exception("Trajectory runtime startup cleanup failed")raise+ set_trajectory_session_delete_backend(sink)_runtime_sink = sink_runtime_processor = processor_runtime_settings = resolved@@ -106,7 +114,7 @@ def shutdown_trajectory_runtime(*, timeout: float = 15.0) -> bool:return _shutdown_locked(timeout=timeout)-def get_trajectory_runtime_sink() -> TrajectoryRecordSink | None:+def get_trajectory_runtime_sink() -> TrajectorySessionSinkRouter | None:"""Return the active process-local sink for diagnostics."""with _runtime_lock:return _runtime_sink@@ -144,6 +152,7 @@ def _shutdown_locked(*, timeout: float = 15.0) -> bool:stopped = Falseif unregistered and stopped:+ set_trajectory_session_delete_backend(None)_runtime_sink = None_runtime_processor = None_runtime_settings = None@@ -156,13 +165,14 @@ def _create_sink(settings: TrajectoryStoreSettings,*,on_commit: CommitCallback | None,-) -> TrajectoryRecordSink:- return TrajectoryRecordSink(settings, on_commit=on_commit)+) -> TrajectorySessionSinkRouter:+ return TrajectorySessionSinkRouter(settings, on_commit=on_commit)def _combined_commit_callback(on_commit: CommitCallback | None) -> CommitCallback:def _publish(updates) -> None:trajectory_update_broker.publish(updates)+ trajectory_gateway_hint_bridge.publish(updates)if on_commit is not None:on_commit(updates)diff --git a/jiuwenswarm/observability/session_delete.py b/jiuwenswarm/observability/session_delete.pynew file mode 100644index 0000000000..d3fe5982f9--- /dev/null+++ b/jiuwenswarm/observability/session_delete.py@@ -0,0 +1,166 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""Process-local trajectory lifecycle for product Session deletion."""++from __future__ import annotations++import threading+from enum import Enum+from typing import Protocol, runtime_checkable+++@runtime_checkable+class TrajectorySessionDeleteBackend(Protocol):+ """Storage backend capable of deleting one Session atomically."""++ def begin_session_delete(self, session_id: str) -> None:+ """Drain the Session writer after the process tombstone is installed."""+ ...++ def abort_session_delete(self, session_id: str) -> None:+ """Restore the Session writer after product deletion fails."""+ ...++ def commit_session_delete(self, session_id: str) -> None:+ """Close and delete all database files owned by the Session."""+ ...+++class _DeleteState(str, Enum):+ PREPARED = "prepared"+ COMMITTED = "committed"+++class TrajectorySessionDeleteLifecycle:+ """Coordinate Session tombstones with an optional routed store backend.++ The process tombstone is installed before the backend is asked to drain.+ Consequently records arriving during or after deletion cannot reopen a+ Session database. An abort always removes that tombstone, including when+ backend rollback itself reports an error.+ """++ def __init__(self) -> None:+ self._lock = threading.RLock()+ self._backend: TrajectorySessionDeleteBackend | None = None+ self._states: dict[str, _DeleteState] = {}+ self._operation_locks: dict[str, threading.Lock] = {}++ def set_backend(self, backend: TrajectorySessionDeleteBackend | None) -> None:+ """Replace the active routed-store backend without clearing tombstones."""+ with self._lock:+ self._backend = backend++ def begin(self, session_id: str) -> None:+ """Install a tombstone and synchronously drain the Session backend."""+ resolved = _require_session_id(session_id)+ operation_lock = self._operation_lock(resolved)+ with operation_lock:+ with self._lock:+ state = self._states.get(resolved)+ if state is not None:+ return+ self._states[resolved] = _DeleteState.PREPARED+ backend = self._backend+ try:+ if backend is not None:+ backend.begin_session_delete(resolved)+ except Exception:+ with self._lock:+ self._states.pop(resolved, None)+ raise++ def abort(self, session_id: str) -> None:+ """Roll back a prepared deletion and allow the Session to write again."""+ resolved = _require_session_id(session_id)+ operation_lock = self._operation_lock(resolved)+ with operation_lock:+ with self._lock:+ if self._states.get(resolved) is not _DeleteState.PREPARED:+ return+ backend = self._backend+ try:+ if backend is not None:+ backend.abort_session_delete(resolved)+ finally:+ with self._lock:+ self._states.pop(resolved, None)++ def commit(self, session_id: str) -> None:+ """Delete Session storage and retain the tombstone after success."""+ resolved = _require_session_id(session_id)+ operation_lock = self._operation_lock(resolved)+ with operation_lock:+ with self._lock:+ if self._states.get(resolved) is _DeleteState.COMMITTED:+ return+ self._states[resolved] = _DeleteState.PREPARED+ backend = self._backend+ if backend is not None:+ backend.commit_session_delete(resolved)+ with self._lock:+ self._states[resolved] = _DeleteState.COMMITTED++ def accepts_records(self, session_id: str) -> bool:+ """Return whether new records may be routed for this Session."""+ resolved = str(session_id or "").strip()+ if not resolved:+ return False+ with self._lock:+ return resolved not in self._states++ def _operation_lock(self, session_id: str) -> threading.Lock:+ with self._lock:+ operation_lock = self._operation_locks.get(session_id)+ if operation_lock is None:+ operation_lock = threading.Lock()+ self._operation_locks[session_id] = operation_lock+ return operation_lock+++def _require_session_id(session_id: str) -> str:+ resolved = str(session_id or "").strip()+ if not resolved:+ raise ValueError("session_id is required")+ return resolved+++trajectory_session_delete_lifecycle = TrajectorySessionDeleteLifecycle()+++def set_trajectory_session_delete_backend(+ backend: TrajectorySessionDeleteBackend | None,+) -> None:+ """Attach the active routed trajectory store to Session deletion."""+ trajectory_session_delete_lifecycle.set_backend(backend)+++def begin_trajectory_session_delete(session_id: str) -> None:+ """Prepare deletion of one Session's trajectory store."""+ trajectory_session_delete_lifecycle.begin(session_id)+++def abort_trajectory_session_delete(session_id: str) -> None:+ """Abort deletion of one Session's trajectory store."""+ trajectory_session_delete_lifecycle.abort(session_id)+++def commit_trajectory_session_delete(session_id: str) -> None:+ """Commit deletion of one Session's trajectory store."""+ trajectory_session_delete_lifecycle.commit(session_id)+++def trajectory_session_accepts_records(session_id: str) -> bool:+ """Return whether the Session is not tombstoned for deletion."""+ return trajectory_session_delete_lifecycle.accepts_records(session_id)+++__all__ = [+ "TrajectorySessionDeleteBackend",+ "TrajectorySessionDeleteLifecycle",+ "abort_trajectory_session_delete",+ "begin_trajectory_session_delete",+ "commit_trajectory_session_delete",+ "set_trajectory_session_delete_backend",+ "trajectory_session_accepts_records",+]diff --git a/jiuwenswarm/observability/sink.py b/jiuwenswarm/observability/sink.pyindex 9599740b27..5e6da91aad 100644--- a/jiuwenswarm/observability/sink.py+++ b/jiuwenswarm/observability/sink.py@@ -11,8 +11,12 @@ import threadingimport timefrom collections import OrderedDictfrom collections.abc import Callable+from dataclasses import replace-from jiuwenswarm.observability.config import TrajectoryStoreSettings+from jiuwenswarm.observability.config import (+ TrajectoryStoreSettings,+ session_database_path,+)from jiuwenswarm.observability.models import (CommittedTraceUpdate,OtlpSpanRecordLike,@@ -20,6 +24,7 @@ from jiuwenswarm.observability.models import (TraceRecordData,TraceSinkStats,)+from jiuwenswarm.observability.session_delete import trajectory_session_accepts_recordsfrom jiuwenswarm.observability.store import TrajectoryStorelogger = logging.getLogger(__name__)@@ -29,6 +34,20 @@ _RETENTION_INTERVAL_SECONDS = 3600# One retry keeps the two five-second SQLite busy waits below the default# fifteen-second shutdown deadline, including the retry delay._WRITE_RETRY_DELAYS_SECONDS = (0.05,)+_SESSION_WRITER_IDLE_SECONDS = 300.0++_QueuedRecord = tuple[OtlpSpanRecordLike | OtlpSpanSnapshotRecordLike, bool]+++def _record_owner_is_consistent(record: OtlpSpanRecordLike) -> bool:+ """Reject a subagent record whose execution session belongs to another chat."""+ owner = str(getattr(record, "session_id", "") or "").strip()+ subject_session = str(+ getattr(record, "execution_subject_session_id", "") or ""+ ).strip()+ if not owner or not subject_session or subject_session == owner:+ return True+ return subject_session.startswith(f"{owner}_sub_")class TrajectoryRecordSink:@@ -58,6 +77,7 @@ class TrajectoryRecordSink:self._stats_lock = threading.Lock()self._ready = threading.Event()self._stop_requested = threading.Event()+ self._writing = threading.Event()self._thread: threading.Thread | None = Noneself._startup_error: BaseException | None = Noneself._accepting = False@@ -120,6 +140,15 @@ class TrajectoryRecordSink:self._increment("failed")logger.warning("Trajectory record rejected before queueing: raw_json must be bytes")return+ if not _record_owner_is_consistent(record):+ self._increment("failed")+ logger.warning(+ "Trajectory record rejected because execution subject belongs "+ "to another session: session_id=%s subject_session_id=%s",+ getattr(record, "session_id", None),+ getattr(record, "execution_subject_session_id", None),+ )+ returnwith self._state_lock:if not self._accepting:self._increment("dropped")@@ -157,6 +186,9 @@ class TrajectoryRecordSink:self._increment("failed")logger.warning("Trajectory snapshot rejected before queueing: raw_json must be bytes")return+ if not _record_owner_is_consistent(record):+ self._increment("failed")+ returnidentity = (str(getattr(record, "trace_id", "") or "").strip().lower(),str(getattr(record, "span_id", "") or "").strip().lower(),@@ -248,6 +280,15 @@ class TrajectoryRecordSink:with self._state_lock:self._on_commit = on_commit+ def is_idle(self) -> bool:+ """Return whether no record is queued or being committed."""+ with self._state_lock:+ return (+ self._queue.empty()+ and not self._snapshot_pending+ and not self._writing.is_set()+ )+def _writer_main(self) -> None:try:self._store.initialize()@@ -269,9 +310,13 @@ class TrajectoryRecordSink:or not self._queue.empty()or bool(self._snapshot_pending)):- batch = self._take_batch(flush_timeout)- if batch:- self._write_batch(batch)+ self._writing.set()+ try:+ batch = self._take_batch(flush_timeout)+ if batch:+ self._write_batch(batch)+ finally:+ self._writing.clear()if time.monotonic() >= next_retention_at:try:self._store.delete_expired()@@ -287,6 +332,7 @@ class TrajectoryRecordSink:) -> list[tuple[OtlpSpanRecordLike | OtlpSpanSnapshotRecordLike, bool]]:self._work_available.wait(timeout=max(0.001, timeout))self._work_available.clear()+ self._wait_for_snapshot_coalescing(timeout)batch: list[tuple[OtlpSpanRecordLike | OtlpSpanSnapshotRecordLike, bool]] = []while len(batch) < self.settings.batch_size:try:@@ -301,6 +347,27 @@ class TrajectoryRecordSink:self._work_available.set()return batch+ def _wait_for_snapshot_coalescing(self, timeout: float) -> None:+ """Debounce provisional snapshots while letting final records preempt."""+ with self._state_lock:+ has_snapshots = bool(self._snapshot_pending)+ if (+ not has_snapshots+ or not self._queue.empty()+ or self._stop_requested.is_set()+ ):+ return++ deadline = time.monotonic() + max(0.001, timeout)+ while not self._stop_requested.is_set():+ self._work_available.clear()+ if not self._queue.empty():+ return+ remaining = deadline - time.monotonic()+ if remaining <= 0:+ return+ self._work_available.wait(timeout=remaining)+def _write_batch(self,batch: list[tuple[OtlpSpanRecordLike | OtlpSpanSnapshotRecordLike, bool]],@@ -383,4 +450,468 @@ class TrajectoryRecordSink:raise ValueError(f"unknown trajectory counter: {counter}")-__all__ = ["CommitCallback", "TrajectoryRecordSink"]+class _SessionRoute:+ """Start and feed one session writer without blocking the router thread."""++ def __init__(+ self,+ settings: TrajectoryStoreSettings,+ session_id: str,+ on_commit: CommitCallback | None,+ sink_factory: Callable[+ [TrajectoryStoreSettings, CommitCallback | None], TrajectoryRecordSink+ ],+ ) -> None:+ session_settings = replace(+ settings,+ database_path=session_database_path(settings.database_path, session_id),+ )+ self._sink = sink_factory(session_settings, on_commit)+ self._queue: queue.Queue[_QueuedRecord] = queue.Queue(+ maxsize=settings.queue_size,+ )+ self._stop_requested = threading.Event()+ self._state_lock = threading.Lock()+ self._accepting = True+ self._last_activity = time.monotonic()+ self._thread = threading.Thread(+ target=self._run,+ name=f"trajectory-session-route-{session_settings.database_path.stem[:12]}",+ daemon=True,+ )+ self._thread.start()++ def offer(self, item: _QueuedRecord) -> bool:+ """Offer one item without waiting for startup or SQLite."""+ with self._state_lock:+ if not self._accepting:+ return False+ try:+ self._queue.put_nowait(item)+ except queue.Full:+ return False+ self._last_activity = time.monotonic()+ return True++ def can_retire(self, now: float) -> bool:+ """Return whether this route has been fully idle long enough."""+ with self._state_lock:+ return (+ not self._accepting+ or (+ now - self._last_activity >= _SESSION_WRITER_IDLE_SECONDS+ and self._queue.empty()+ and self._sink.is_idle()+ )+ )++ def request_stop(self) -> None:+ """Request a drain without waiting for the route thread."""+ with self._state_lock:+ self._accepting = False+ self._stop_requested.set()++ def join(self, timeout: float) -> bool:+ """Wait for the route and its child sink to drain."""+ self._thread.join(timeout=max(0.0, timeout))+ return not self._thread.is_alive()++ def stats(self) -> TraceSinkStats:+ """Return child writer counters plus route backlog."""+ child = self._sink.stats()+ return TraceSinkStats(+ accepted=child.accepted,+ committed=child.committed,+ dropped=child.dropped,+ failed=child.failed,+ conflicts=child.conflicts,+ queued=child.queued + self._queue.qsize(),+ coalesced=child.coalesced,+ evicted_provisional=child.evicted_provisional,+ dropped_final=child.dropped_final,+ stale_ignored=child.stale_ignored,+ )++ def set_commit_callback(self, on_commit: CommitCallback | None) -> None:+ """Replace the callback used by this child writer."""+ self._sink.set_commit_callback(on_commit)++ def _run(self) -> None:+ try:+ self._sink.start()+ except Exception:+ with self._state_lock:+ self._accepting = False+ logger.exception("Trajectory session writer initialization failed")+ while True:+ try:+ record, snapshot = self._queue.get_nowait()+ except queue.Empty:+ break+ try:+ if snapshot:+ self._sink.consume_snapshot(record)+ else:+ self._sink.consume(record)+ finally:+ self._queue.task_done()+ return+ try:+ while not self._stop_requested.is_set() or not self._queue.empty():+ try:+ record, snapshot = self._queue.get(timeout=0.1)+ except queue.Empty:+ continue+ try:+ if snapshot:+ self._sink.consume_snapshot(record)+ else:+ self._sink.consume(record)+ finally:+ self._queue.task_done()+ finally:+ with self._state_lock:+ self._accepting = False+ self._sink.close()+++class TrajectorySessionSinkRouter:+ """Non-blocking process sink routing each session to an isolated writer."""++ def __init__(+ self,+ settings: TrajectoryStoreSettings,+ *,+ on_commit: CommitCallback | None = None,+ sink_factory: Callable[+ [TrajectoryStoreSettings, CommitCallback | None], TrajectoryRecordSink+ ] | None = None,+ ) -> None:+ self.settings = settings+ self._on_commit = on_commit+ self._sink_factory = sink_factory or _create_session_sink+ self._queue: queue.Queue[tuple[str, _QueuedRecord]] = queue.Queue(+ maxsize=settings.queue_size,+ )+ self._routes: dict[str, _SessionRoute] = {}+ self._orphan_pending: OrderedDict[+ tuple[str, str], _QueuedRecord+ ] = OrderedDict()+ self._routes_lock = threading.Lock()+ self._ingress_condition = threading.Condition()+ self._ingress_pending: dict[str, int] = {}+ self._state_lock = threading.Lock()+ self._stats_lock = threading.Lock()+ self._ready = threading.Event()+ self._stop_requested = threading.Event()+ self._thread: threading.Thread | None = None+ self._accepting = False+ self._accepted = 0+ self._dropped = 0+ self._failed = 0+ self._dropped_final = 0++ def start(self, *, timeout: float = 10.0) -> None:+ """Start the lightweight routing thread without opening SQLite."""+ with self._state_lock:+ if self._thread is not None:+ return+ self._stop_requested.clear()+ self._ready.clear()+ thread = threading.Thread(+ target=self._run,+ name="trajectory-session-router",+ daemon=True,+ )+ self._thread = thread+ thread.start()+ if not self._ready.wait(timeout=max(0.1, float(timeout))):+ self._stop_requested.set()+ raise RuntimeError("Trajectory session router initialization timed out")+ with self._state_lock:+ if self._thread is not thread or not thread.is_alive():+ raise RuntimeError("Trajectory session router stopped during initialization")+ self._accepting = True++ def consume(self, record: OtlpSpanRecordLike) -> None:+ """Accept a final Core record using one constant-cost enqueue."""+ self._consume(record, snapshot=False)++ def consume_snapshot(self, record: OtlpSpanSnapshotRecordLike) -> None:+ """Accept a provisional Core snapshot using one constant-cost enqueue."""+ self._consume(record, snapshot=True)++ def close(self, *, timeout: float = 15.0) -> bool:+ """Stop accepting and drain the router and every session writer."""+ deadline = time.monotonic() + max(0.1, float(timeout))+ with self._state_lock:+ self._accepting = False+ thread = self._thread+ if thread is None:+ return True+ self._stop_requested.set()+ thread.join(timeout=max(0.0, deadline - time.monotonic()))+ if thread.is_alive():+ return False+ with self._routes_lock:+ routes = tuple(self._routes.values())+ for route in routes:+ route.request_stop()+ stopped = True+ for route in routes:+ stopped = route.join(max(0.0, deadline - time.monotonic())) and stopped+ if stopped:+ with self._state_lock:+ self._thread = None+ return stopped++ def stats(self) -> TraceSinkStats:+ """Aggregate ingress and child-writer diagnostics."""+ with self._routes_lock:+ routes = tuple(self._routes.values())+ orphan_count = len(self._orphan_pending)+ child_stats = [route.stats() for route in routes]+ with self._stats_lock:+ accepted = self._accepted+ dropped = self._dropped+ failed = self._failed+ dropped_final = self._dropped_final+ return TraceSinkStats(+ accepted=accepted,+ committed=sum(item.committed for item in child_stats),+ dropped=dropped + sum(item.dropped for item in child_stats),+ failed=failed + sum(item.failed for item in child_stats),+ conflicts=sum(item.conflicts for item in child_stats),+ queued=(+ self._queue.qsize()+ + orphan_count+ + sum(item.queued for item in child_stats)+ ),+ coalesced=sum(item.coalesced for item in child_stats),+ evicted_provisional=sum(item.evicted_provisional for item in child_stats),+ dropped_final=dropped_final + sum(item.dropped_final for item in child_stats),+ stale_ignored=sum(item.stale_ignored for item in child_stats),+ )++ def set_commit_callback(self, on_commit: CommitCallback | None) -> None:+ """Replace the callback for existing and future session writers."""+ with self._state_lock:+ self._on_commit = on_commit+ with self._routes_lock:+ routes = tuple(self._routes.values())+ for route in routes:+ route.set_commit_callback(on_commit)++ def begin_session_delete(self, session_id: str, *, timeout: float = 15.0) -> None:+ """Drain and close one Session route after its tombstone is installed."""+ resolved = str(session_id or "").strip()+ if not resolved:+ raise ValueError("session_id is required")+ deadline = time.monotonic() + max(0.1, float(timeout))+ with self._ingress_condition:+ while self._ingress_pending.get(resolved, 0) > 0:+ remaining = deadline - time.monotonic()+ if remaining <= 0:+ raise RuntimeError(+ "Trajectory Session ingress did not drain before deletion"+ )+ self._ingress_condition.wait(timeout=remaining)+ with self._routes_lock:+ route = self._routes.get(resolved)+ if route is not None:+ route.request_stop()+ if route is None:+ return+ if route.join(max(0.0, deadline - time.monotonic())):+ with self._routes_lock:+ if self._routes.get(resolved) is route:+ self._routes.pop(resolved)+ return+ raise RuntimeError("Trajectory Session writer did not stop before deletion")++ def abort_session_delete(self, session_id: str) -> None:+ """Allow a rolled-back Session to lazily create a fresh route."""+ if not str(session_id or "").strip():+ raise ValueError("session_id is required")++ def commit_session_delete(self, session_id: str) -> None:+ """Idempotently delete one closed Session database and its sidecars."""+ resolved = str(session_id or "").strip()+ if not resolved:+ raise ValueError("session_id is required")+ self.begin_session_delete(resolved)+ database_path = session_database_path(self.settings.database_path, resolved)+ for candidate in (+ database_path,+ database_path.with_name(f"{database_path.name}-wal"),+ database_path.with_name(f"{database_path.name}-shm"),+ ):+ candidate.unlink(missing_ok=True)++ def _consume(+ self,+ record: OtlpSpanRecordLike | OtlpSpanSnapshotRecordLike,+ *,+ snapshot: bool,+ ) -> None:+ raw_session_id = str(getattr(record, "session_id", "") or "")+ session_id = raw_session_id.strip()+ trace_id = str(getattr(record, "trace_id", "") or "").strip().lower()+ span_id = str(getattr(record, "span_id", "") or "").strip().lower()+ if (+ (session_id and session_id != raw_session_id)+ or not trace_id+ or not span_id+ or not isinstance(getattr(record, "raw_json", None), bytes)+ or not _record_owner_is_consistent(record)+ ):+ self._increment("failed")+ return+ if session_id and not trajectory_session_accepts_records(session_id):+ self._increment("dropped")+ if not snapshot:+ self._increment("dropped_final")+ return+ with self._state_lock:+ if session_id and not trajectory_session_accepts_records(session_id):+ self._increment("dropped")+ if not snapshot:+ self._increment("dropped_final")+ return+ if not self._accepting:+ self._increment("dropped")+ return+ with self._ingress_condition:+ try:+ self._queue.put_nowait((session_id, (record, snapshot)))+ except queue.Full:+ self._increment("dropped")+ if not snapshot:+ self._increment("dropped_final")+ return+ self._ingress_pending[session_id] = (+ self._ingress_pending.get(session_id, 0) + 1+ )+ self._increment("accepted")++ def _run(self) -> None:+ self._ready.set()+ while not self._stop_requested.is_set() or not self._queue.empty():+ try:+ session_id, item = self._queue.get(timeout=0.1)+ except queue.Empty:+ self._retire_idle_routes()+ continue+ try:+ if not session_id:+ self._buffer_orphan(item)+ continue+ trace_id = str(getattr(item[0], "trace_id", "") or "").strip().lower()+ with self._routes_lock:+ route = self._routes.get(session_id)+ if route is None:+ route = _SessionRoute(+ self.settings,+ session_id,+ self._on_commit,+ self._sink_factory,+ )+ self._routes[session_id] = route+ routed_items = self._take_orphans_locked(trace_id)+ routed_items.append(item)+ for routed_item in routed_items:+ if route.offer(routed_item):+ continue+ self._increment("dropped")+ if not routed_item[1]:+ self._increment("dropped_final")+ finally:+ self._complete_ingress(session_id)+ self._queue.task_done()+ self._drop_all_orphans()++ def _retire_idle_routes(self) -> None:+ now = time.monotonic()+ with self._routes_lock:+ candidates = [+ (session_id, route)+ for session_id, route in self._routes.items()+ if route.can_retire(now)+ ]+ for _session_id, route in candidates:+ route.request_stop()+ for session_id, route in candidates:+ if not route.join(1.0):+ continue+ with self._routes_lock:+ if self._routes.get(session_id) is route:+ self._routes.pop(session_id)++ def _buffer_orphan(self, item: _QueuedRecord) -> None:+ """Hold a sessionless child until a session-owned span reveals its route."""+ record, _snapshot = item+ identity = (+ str(getattr(record, "trace_id", "") or "").strip().lower(),+ str(getattr(record, "span_id", "") or "").strip().lower(),+ )+ with self._routes_lock:+ previous = self._orphan_pending.pop(identity, None)+ if previous is None and len(self._orphan_pending) >= self.settings.queue_size:+ _evicted_identity, evicted = self._orphan_pending.popitem(last=False)+ self._increment("dropped")+ if not evicted[1]:+ self._increment("dropped_final")+ self._orphan_pending[identity] = item++ def _take_orphans_locked(self, trace_id: str) -> list[_QueuedRecord]:+ identities = [+ identity for identity in self._orphan_pending if identity[0] == trace_id+ ]+ return [self._orphan_pending.pop(identity) for identity in identities]++ def _drop_all_orphans(self) -> None:+ with self._routes_lock:+ orphans = tuple(self._orphan_pending.values())+ self._orphan_pending.clear()+ if not orphans:+ return+ self._increment("dropped", len(orphans))+ final_count = sum(1 for _record, snapshot in orphans if not snapshot)+ if final_count:+ self._increment("dropped_final", final_count)++ def _complete_ingress(self, session_id: str) -> None:+ with self._ingress_condition:+ remaining = self._ingress_pending.get(session_id, 0) - 1+ if remaining > 0:+ self._ingress_pending[session_id] = remaining+ else:+ self._ingress_pending.pop(session_id, None)+ self._ingress_condition.notify_all()++ def _increment(self, counter: str, amount: int = 1) -> None:+ with self._stats_lock:+ if counter == "accepted":+ self._accepted += amount+ elif counter == "dropped":+ self._dropped += amount+ elif counter == "failed":+ self._failed += amount+ elif counter == "dropped_final":+ self._dropped_final += amount+ else:+ raise ValueError(f"unknown trajectory router counter: {counter}")+++def _create_session_sink(+ settings: TrajectoryStoreSettings,+ on_commit: CommitCallback | None,+) -> TrajectoryRecordSink:+ return TrajectoryRecordSink(settings, on_commit=on_commit)+++__all__ = [+ "CommitCallback",+ "TrajectoryRecordSink",+ "TrajectorySessionSinkRouter",+]diff --git a/jiuwenswarm/observability/store.py b/jiuwenswarm/observability/store.pyindex c960a5717f..cab3431577 100644--- a/jiuwenswarm/observability/store.py+++ b/jiuwenswarm/observability/store.py@@ -4,6 +4,7 @@from __future__ import annotations+import asyncioimport base64import binasciiimport json@@ -19,7 +20,10 @@ from typing import Anyimport aiosqlitefrom jiuwenswarm.common.mode_matrix import SINGLE_AGENT_CANONICAL_MODES-from jiuwenswarm.observability.config import DEFAULT_DETAIL_MAX_BYTES+from jiuwenswarm.observability.config import (+ DEFAULT_DETAIL_MAX_BYTES,+ session_database_path,+)from jiuwenswarm.observability.models import (CommittedTraceUpdate,TraceRecordData,@@ -339,12 +343,13 @@ class TrajectoryStore:changed_trace_ids.update(self._reconcile_orphans(connection, records))eligibility_after = self._trace_eligibility(connection, incoming_trace_ids)- eligibility_changed = any(+ visible_trace_removed = any(eligibility_before[trace_id][0]- and eligibility_before[trace_id][1] != eligibility_after[trace_id][1]+ and eligibility_before[trace_id][1]+ and not eligibility_after[trace_id][1]for trace_id in incoming_trace_ids)- if eligibility_changed:+ if visible_trace_removed:self._rotate_store_epoch(connection)else:self._sync_max_ingest_seq(connection)@@ -411,7 +416,12 @@ class TrajectoryStore:record.source,record.created_at,int(resolved_has_error),- sqlite3.Binary(record.raw_json),+ # The change journal is a revision index, not a second payload+ # store. Detail reads load the complete snapshot from+ # trajectory_current_records, while final archives use+ # otlp_span_records. Keeping the full BLOB here multiplied+ # every streaming revision into unbounded write amplification.+ sqlite3.Binary(b""),record.raw_sha256,record.update_kind,),@@ -572,7 +582,7 @@ class TrajectoryStore:row["source"],created_at,row["has_error"],- row["raw_json"],+ sqlite3.Binary(b""),row["raw_sha256"],),)@@ -950,10 +960,67 @@ class TrajectoryStore:class AsyncTrajectoryReader:- """Gateway-side read-only view over the shared trajectory database."""+ """Gateway-side read-only view over trajectory SQLite databases."""- def __init__(self, database_path: Path) -> None:+ def __init__(self, database_path: Path, *, session_scoped: bool = False) -> None:self.database_path = Path(database_path)+ self.session_scoped = session_scoped+ self._usage_locks: dict[str, asyncio.Lock] = {}+ self._usage_cache: dict[str, dict[str, Any]] = {}++ async def get_session_request_usage(+ self,+ session_id: str,+ ) -> tuple[list[dict[str, Any]], str]:+ """Return session-complete cumulative usage partitioned by execution subject."""+ usage_lock = self._usage_locks.setdefault(session_id, asyncio.Lock())+ async with usage_lock:+ connection = await self._connect(session_id)+ if connection is None:+ return [], _ABSENT_STORE_EPOCH+ try:+ await connection.execute("BEGIN")+ store_epoch = await _read_store_epoch(connection)+ watermark = await _session_revision_watermark(connection, session_id)+ cache = self._usage_cache.get(session_id)+ cache_valid = (+ cache is not None+ and cache["store_epoch"] == store_epoch+ and int(cache["watermark"]) <= watermark+ )+ after_revision = int(cache["watermark"]) if cache_valid else 0+ facts = dict(cache["facts"]) if cache_valid else {}+ async with connection.execute(+ """+ SELECT trace_id,+ start_time_unix_nano,+ change_seq,+ raw_json+ FROM trajectory_current_records+ WHERE session_id = ? AND change_seq > ?+ ORDER BY change_seq ASC+ """,+ (session_id, after_revision),+ ) as statement:+ rows = await statement.fetchall()+ for row in rows:+ fact = _request_usage_fact(+ bytes(row["raw_json"]),+ trace_id=str(row["trace_id"]),+ start_time_unix_nano=int(row["start_time_unix_nano"]),+ )+ if fact is None:+ continue+ facts[(fact["trace_id"], fact["inference_id"])] = fact+ self._usage_cache[session_id] = {+ "store_epoch": store_epoch,+ "watermark": watermark,+ "facts": facts,+ }+ finally:+ await connection.rollback()+ await connection.close()+ return _cumulative_request_usage(tuple(facts.values())), store_epochasync def list_traces(self,@@ -977,7 +1044,7 @@ class AsyncTrajectoryReader:session_id: str,) -> tuple[list[dict[str, Any]], str, int]:"""Read every current record for one session from one SQLite snapshot."""- connection = await self._connect()+ connection = await self._connect(session_id)if connection is None:return [], _ABSENT_STORE_EPOCH, 0try:@@ -1033,7 +1100,7 @@ class AsyncTrajectoryReader:) -> tuple[list[dict[str, Any]], str | None, str, str]:"""List summaries and a polling baseline from one SQLite snapshot."""cursor_value = decode_trace_cursor(cursor) if cursor else None- connection = await self._connect()+ connection = await self._connect(session_id)if connection is None:store_epoch = _ABSENT_STORE_EPOCHif cursor_value is not None:@@ -1166,7 +1233,7 @@ class AsyncTrajectoryReader:after_ingest_seq,through_ingest_seq,) = decode_revision_cursor(after_revision)- connection = await self._connect()+ connection = await self._connect(session_id)if connection is None:store_epoch = _ABSENT_STORE_EPOCHstable_cursor = encode_revision_cursor(session_id, store_epoch, 0)@@ -1275,7 +1342,7 @@ class AsyncTrajectoryReader:max_bytes: int = DEFAULT_DETAIL_MAX_BYTES,) -> dict[str, Any] | None:"""Read a complete or incremental page for one trace."""- connection = await self._connect()+ connection = await self._connect(session_id)if connection is None:return Nonetry:@@ -1305,6 +1372,11 @@ class AsyncTrajectoryReader:since_revision > 0 and since_revision < first_revision)effective_since = 0 if reset else since_revision+ # Detail is a coalesced current-state delta, not a replay of every+ # journal revision. Every current record is a complete upsert+ # snapshot. Any future operation that removes one identity without+ # rotating store_epoch must add a durable tombstone before this+ # query can support it safely.async with connection.execute("""SELECT change_seq AS ingest_seq,@@ -1312,10 +1384,10 @@ class AsyncTrajectoryReader:span_id,record_revision,lifecycle,- operation,+ 'upsert' AS operation,observed_time_unix_nano,LENGTH(raw_json) AS raw_size_bytes- FROM trajectory_changes+ FROM trajectory_current_recordsWHERE session_id = ?AND trace_id = ?AND change_seq > ?@@ -1354,11 +1426,11 @@ class AsyncTrajectoryReader:span_id,record_revision,lifecycle,- operation,+ 'upsert' AS operation,observed_time_unix_nano,LENGTH(raw_json) AS raw_size_bytes,raw_json- FROM trajectory_changes+ FROM trajectory_current_recordsWHERE session_id = ?AND trace_id = ?AND change_seq > ?@@ -1405,7 +1477,7 @@ class AsyncTrajectoryReader:span_id: str,) -> bytes | None:"""Return exact raw bytes when the identity belongs to the session."""- connection = await self._connect()+ connection = await self._connect(session_id)if connection is None:return Nonetry:@@ -1432,11 +1504,14 @@ class AsyncTrajectoryReader:await connection.close()return bytes(row["raw_json"]) if row is not None else None- async def _connect(self) -> aiosqlite.Connection | None:- if not self.database_path.is_file():+ async def _connect(self, session_id: str) -> aiosqlite.Connection | None:+ database_path = self.database_path+ if self.session_scoped:+ database_path = session_database_path(database_path, session_id)+ if not database_path.is_file():return Noneconnection = await aiosqlite.connect(- f"{self.database_path.resolve().as_uri()}?mode=ro",+ f"{database_path.resolve().as_uri()}?mode=ro",timeout=_BUSY_TIMEOUT_MS / 1000,uri=True,)@@ -1797,6 +1872,109 @@ def _record_has_error(raw_json: bytes) -> bool:return False+def _otlp_attribute_value(value: Any) -> Any:+ if not isinstance(value, dict):+ return None+ for key in (+ "stringValue",+ "intValue",+ "doubleValue",+ "boolValue",+ ):+ if key in value:+ return value[key]+ return None+++def _request_usage_fact(+ raw_json: bytes,+ *,+ trace_id: str,+ start_time_unix_nano: int,+) -> dict[str, Any] | None:+ try:+ payload = _strict_otlp_payload(raw_json)+ except Exception:+ return None+ spans = []+ for resource_span in payload.get("resourceSpans", []):+ if not isinstance(resource_span, dict):+ continue+ for scope_span in resource_span.get("scopeSpans", []):+ if isinstance(scope_span, dict):+ spans.extend(scope_span.get("spans", []))+ if len(spans) != 1 or not isinstance(spans[0], dict):+ return None+ if spans[0].get("name") != "llm.call":+ return None+ attributes = {+ str(attribute.get("key")): _otlp_attribute_value(attribute.get("value"))+ for attribute in spans[0].get("attributes", [])+ if isinstance(attribute, dict) and isinstance(attribute.get("key"), str)+ }+ inference_id = str(attributes.get("openjiuwen.inference.id") or "").strip()+ if not inference_id:+ return None+ subject_id = str(attributes.get("openjiuwen.execution.subject.id") or "main").strip()+ usage_keys = {+ "input": ("gen_ai.usage.input_tokens", "gen_ai.usage.prompt_tokens"),+ "cacheRead": ("gen_ai.usage.cache_read.input_tokens", "gen_ai.usage.cache_tokens"),+ "cacheWrite": ("gen_ai.usage.cache_creation.input_tokens",),+ "output": ("gen_ai.usage.output_tokens", "gen_ai.usage.completion_tokens"),+ "reasoning": ("gen_ai.usage.reasoning.output_tokens", "gen_ai.usage.reasoning_tokens"),+ "total": ("gen_ai.usage.total_tokens",),+ }+ usage: dict[str, int] = {}+ for output_key, attribute_keys in usage_keys.items():+ raw_value = next(+ (+ attributes[key]+ for key in attribute_keys+ if attributes.get(key) is not None+ ),+ None,+ )+ try:+ value = int(raw_value)+ except (TypeError, ValueError, OverflowError):+ continue+ if 0 <= value <= _MAX_SQLITE_INTEGER:+ usage[output_key] = value+ return {+ "trace_id": trace_id,+ "inference_id": inference_id,+ "subject_id": subject_id or "main",+ "start_time_unix_nano": start_time_unix_nano,+ "usage": usage,+ }+++def _cumulative_request_usage(+ facts: Sequence[dict[str, Any]],+) -> list[dict[str, Any]]:+ cumulative_by_subject: dict[str, dict[str, int]] = {}+ result: list[dict[str, Any]] = []+ for fact in sorted(+ facts,+ key=lambda item: (+ str(item["subject_id"]),+ int(item["start_time_unix_nano"]),+ str(item["trace_id"]),+ str(item["inference_id"]),+ ),+ ):+ subject_id = str(fact["subject_id"])+ cumulative = cumulative_by_subject.setdefault(subject_id, {})+ for key, value in dict(fact["usage"]).items():+ cumulative[key] = cumulative.get(key, 0) + int(value)+ result.append({+ **fact,+ "start_time_unix_nano": str(fact["start_time_unix_nano"]),+ "cumulative_usage": dict(cumulative),+ })+ return result++def _trace_summary_from_row(row: aiosqlite.Row) -> dict[str, Any]:return {"trace_id": str(row["trace_id"]),diff --git a/jiuwenswarm/resources/config.yaml b/jiuwenswarm/resources/config.yamlindex 2bcb5f4703..b377bab2ee 100644--- a/jiuwenswarm/resources/config.yaml+++ b/jiuwenswarm/resources/config.yaml@@ -497,7 +497,7 @@ agent_observability:# ============================================================trajectory_ui:enabled: true # 启用“对话 / 轨迹”数据链路- db_path: "" # 空值默认 ~/.jiuwenswarm/.trace/trajectory.sqlite3+ db_path: "" # Session database root; defaults to ~/.jiuwenswarm/.trace/sessionsretention_days: 7 # SQLite 轨迹保留天数queue_size: 4096 # Agent 主线程非阻塞写入队列上限batch_size: 64 # writer 单事务最大记录数diff --git a/jiuwenswarm/server/runtime/session/session_history.py b/jiuwenswarm/server/runtime/session/session_history.pyindex 1dcefb67c0..d1fefedf7c 100644--- a/jiuwenswarm/server/runtime/session/session_history.py+++ b/jiuwenswarm/server/runtime/session/session_history.py@@ -1197,7 +1197,10 @@ def append_history_record(user_content=content_text if role_norm == "user" else None,# 传入渠道元数据,首次写入时持久化channel_metadata=channel_metadata,- mode=mode,+ # A subagent record carries its own history mode, but it belongs+ # to the parent product Session and must not replace that Session's+ # routing mode with the internal ``subagent`` label.+ mode=None if subagent_id else mode,# 用户消息时刷新 last_user_message_at(用消息时间戳,比请求到达时刻更精确;# 与 AgentServer 的 _sync_chat_request_metadata 互补,覆盖所有记录用户消息的路径)last_user_message_at=float(timestamp) if role_norm == "user" else None,diff --git a/tests/unit_tests/agentserver/test_observability_config_mapping.py b/tests/unit_tests/agentserver/test_observability_config_mapping.pynew file mode 100644index 0000000000..f318d9e1a0--- /dev/null+++ b/tests/unit_tests/agentserver/test_observability_config_mapping.py@@ -0,0 +1,27 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++from jiuwenswarm.agents.harness.observability_runtime import build_observability_config+++def test_single_agent_native_backend_defaults_are_forwarded() -> None:+ config = build_observability_config(+ {},+ service_name="jiuwenswarm-agent",+ default_backend="otlp",+ traces_dir="/tmp/traces",+ )++ assert config.backend == "otlp"+ assert config.max_attributes == 200+++def test_observability_backend_and_attribute_limit_can_be_configured() -> None:+ config = build_observability_config(+ {"backend": "langfuse", "max_attributes": 512},+ service_name="jiuwenswarm-agent",+ default_backend="otlp",+ traces_dir="/tmp/traces",+ )++ assert config.backend == "langfuse"+ assert config.max_attributes == 512diff --git a/tests/unit_tests/agentserver/test_subagent_history_routing.py b/tests/unit_tests/agentserver/test_subagent_history_routing.pynew file mode 100644index 0000000000..02d69fafbf--- /dev/null+++ b/tests/unit_tests/agentserver/test_subagent_history_routing.py@@ -0,0 +1,41 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""Regression tests for parent-owned subagent history persistence."""++from __future__ import annotations++from jiuwenswarm.server.runtime.agent_adapter import interface_deep+from jiuwenswarm.server.runtime.agent_adapter.interface_deep import (+ JiuWenSwarmDeepAdapter,+)+++def test_subagent_history_writes_use_dedicated_child_bucket(monkeypatch) -> None:+ persisted = []+ monkeypatch.setattr(+ interface_deep,+ "append_history_record",+ lambda **kwargs: persisted.append(kwargs),+ )+ projection = {+ "parent_session_id": "parent-session",+ "subagent_id": "subagent-1",+ "task_id": "task-1",+ "seq": 1,+ "role": "assistant",+ "content": "result",+ "summary": "working",+ "event_type": "chat.final",+ }++ JiuWenSwarmDeepAdapter._persist_subagent_transcript_message(projection)+ JiuWenSwarmDeepAdapter._persist_subagent_activity(projection)+ JiuWenSwarmDeepAdapter._persist_subagent_roster_history(+ projection,+ {"description": "worker"},+ )++ assert len(persisted) == 3+ assert all(item["session_id"] == "parent-session" for item in persisted)+ assert all(item["subagent_id"] == "subagent-1" for item in persisted)+ assert all(item["mode"] == "subagent" for item in persisted)diff --git a/tests/unit_tests/channel/test_trajectory_http.py b/tests/unit_tests/channel/test_trajectory_http.pyindex c396d57ecd..f708786613 100644--- a/tests/unit_tests/channel/test_trajectory_http.py+++ b/tests/unit_tests/channel/test_trajectory_http.py@@ -32,7 +32,10 @@ from jiuwenswarm.gateway.channel_manager.web.trajectory_http import (TrajectoryHttpService,attach_trajectory_routes,)-from jiuwenswarm.observability.config import TrajectoryStoreSettings+from jiuwenswarm.observability.config import (+ TrajectoryStoreSettings,+ session_database_path,+)from jiuwenswarm.observability.models import TraceRecordDatafrom jiuwenswarm.observability.store import AsyncTrajectoryReader, TrajectoryStore@@ -76,7 +79,7 @@ def _seed(database_path: Path, *, session_id: str = "session-1") -> bytes:session_id=session_id,request_id="request-1",run_id="run-1",- agent_mode="agent",+ agent_mode="agent.work.normal",schema_version="1",)store = TrajectoryStore(database_path)@@ -100,7 +103,7 @@ def _append_late_span(database_path: Path, *, session_id: str = "session-1") ->session_id=session_id,request_id="request-1",run_id="run-1",- agent_mode="agent",+ agent_mode="agent.work.normal",schema_version="1",)store = TrajectoryStore(database_path)@@ -111,7 +114,7 @@ def _append_late_span(database_path: Path, *, session_id: str = "session-1") ->store.close()-def _metadata_loader(mode: str = "agent"):+def _metadata_loader(mode: str = "agent.work.normal"):def _load(session_id: str) -> dict[str, str]:if session_id in {"session-1", "session-2"}:return {"session_id": session_id, "mode": mode, "team_name": ""}@@ -315,7 +318,7 @@ async def test_http_archive_exports_all_current_records_beyond_list_window(session_id="session-1",request_id=f"request-{index + 1}",run_id="run-archive",- agent_mode="agent",+ agent_mode="agent.work.normal",schema_version="1",record_revision=3,observed_time_unix_nano=200 + index,@@ -354,7 +357,7 @@ async def test_http_archive_exports_all_current_records_beyond_list_window(session_id="session-1",request_id="request-live",run_id="run-archive",- agent_mode="agent",+ agent_mode="agent.work.normal",schema_version="1",lifecycle="running",)@@ -425,7 +428,7 @@ async def test_http_archive_preserves_invalid_otlp_as_raw_base64(tmp_path: Path)session_id="session-1",request_id="request-invalid",run_id="run-invalid",- agent_mode="agent",+ agent_mode="agent.work.normal",schema_version="1",)store = TrajectoryStore(database_path)@@ -452,6 +455,129 @@ async def test_http_archive_preserves_invalid_otlp_as_raw_base64(tmp_path: Path)test_logger.info("archive retained malformed OTLP bytes for offline diagnostics")+async def test_archive_get_download_preserves_execution_subject_and_access(+ tmp_path: Path,+) -> None:+ database_root = tmp_path / "sessions"+ database_path = session_database_path(database_root, "session-1")+ raw_payload = json.loads(_raw_record())+ raw_span = raw_payload["resourceSpans"][0]["scopeSpans"][0]["spans"][0]+ subject_attributes = {+ "openjiuwen.execution.subject.id": "subagent:research:invocation-7",+ "openjiuwen.execution.subject.display_name": "Research Agent",+ "openjiuwen.execution.subject.kind": "subagent",+ "openjiuwen.execution.subject.parent_id": "main",+ "openjiuwen.execution.subject.session_id": "subsession-research-7",+ }+ raw_span["attributes"] = [+ {"key": key, "value": {"stringValue": value}}+ for key, value in subject_attributes.items()+ ]+ raw_json = json.dumps(raw_payload, separators=(",", ":")).encode("utf-8")+ core_record = SimpleNamespace(+ raw_json=raw_json,+ trace_id=_TRACE_ID,+ span_id=_SPAN_ID,+ parent_span_id=None,+ start_time_unix_nano=100,+ end_time_unix_nano=200,+ session_id="session-1",+ request_id="request-subagent",+ run_id="run-subagent",+ agent_mode="agent.work.normal",+ schema_version="1",+ )+ store = TrajectoryStore(database_path)+ store.initialize()+ try:+ store.write_records([TraceRecordData.from_core_record(core_record)])+ connection = store._require_connection()+ stored_raw = bytes(+ connection.execute(+ "SELECT raw_json FROM otlp_span_records WHERE trace_id = ? AND span_id = ?",+ (_TRACE_ID, _SPAN_ID),+ ).fetchone()["raw_json"]+ )+ current_raw = bytes(+ connection.execute(+ "SELECT raw_json FROM trajectory_current_records WHERE trace_id = ? AND span_id = ?",+ (_TRACE_ID, _SPAN_ID),+ ).fetchone()["raw_json"]+ )+ change_raw = bytes(+ connection.execute(+ "SELECT raw_json FROM trajectory_changes WHERE trace_id = ? AND span_id = ?",+ (_TRACE_ID, _SPAN_ID),+ ).fetchone()["raw_json"]+ )+ finally:+ store.close()+ app = FastAPI()+ attach_trajectory_routes(+ app,+ SimpleNamespace(),+ settings=_settings(database_root),+ metadata_loader=_metadata_loader(),+ )+ team_app = FastAPI()+ attach_trajectory_routes(+ team_app,+ SimpleNamespace(),+ settings=_settings(database_root),+ metadata_loader=_metadata_loader("team.plan.normal"),+ )++ async with httpx.AsyncClient(+ transport=httpx.ASGITransport(app=app),+ base_url="http://test",+ ) as client:+ response = await client.get(+ f"{TRAJECTORY_API_PREFIX}/sessions/session-1/archive"+ )+ missing = await client.get(+ f"{TRAJECTORY_API_PREFIX}/sessions/session-missing/archive"+ )+ async with httpx.AsyncClient(+ transport=httpx.ASGITransport(app=team_app),+ base_url="http://test",+ ) as client:+ forbidden = await client.get(+ f"{TRAJECTORY_API_PREFIX}/sessions/session-1/archive"+ )++ assert response.status_code == 200+ assert response.headers["cache-control"] == "no-store"+ assert response.headers["content-type"] == "application/json"+ assert response.headers["content-disposition"] == (+ 'attachment; filename="trajectory-session-1.archive.json"'+ )+ assert int(response.headers["content-length"]) == len(response.content)+ assert len(response.content) > len(raw_json)+ assert stored_raw == raw_json+ assert current_raw == raw_json+ assert change_raw == b""+ payload = response.json()+ assert payload["format"] == "openjiuwen.trajectory.archive"+ assert payload["archive_version"] == 1+ assert len(payload["records"]) == 1+ archived_record = payload["records"][0]+ assert base64.b64decode(+ archived_record["raw_json_base64"],+ validate=True,+ ) == raw_json+ archived_span = archived_record["otlp"]["resourceSpans"][0]["scopeSpans"][0]["spans"][0]+ assert {+ attribute["key"]: attribute["value"]["stringValue"]+ for attribute in archived_span["attributes"]+ } == subject_attributes+ assert missing.status_code == 404+ assert missing.json()["code"] == "NOT_FOUND"+ assert forbidden.status_code == 403+ assert forbidden.json()["code"] == "UNSUPPORTED_SESSION_MODE"+ test_logger.info("archive GET downloaded non-empty subject-preserving single-Agent data")++@pytest.mark.asyncioasync def test_http_revision_feed_exposes_epoch_reset_after_retention(tmp_path: Path,@@ -552,6 +678,59 @@ async def test_http_forbids_team_and_auto_harness_sessions(tmp_path: Path) -> Notest_logger.info("non-single-Agent sessions rejected by the server")+ "mode",+ [+ "agent.work.normal",+ "agent.work.plan",+ "agent.code.normal",+ "agent.code.plan",+ ],+)+async def test_http_accepts_new_single_agent_canonical_modes(+ tmp_path: Path,+ mode: str,+) -> None:+ database_path = tmp_path / "trajectory.sqlite3"+ _seed(database_path)+ service = TrajectoryHttpService(+ _settings(database_path),+ reader=AsyncTrajectoryReader(database_path),+ metadata_loader=_metadata_loader(mode),+ )++ response = await service.list_traces("session-1", limit=30, cursor=None)++ assert response.status_code == 200+ assert len(_response_json(response)["items"]) == 1+ test_logger.info("new canonical single-Agent mode can read trajectory: %s", mode)+++ "mode",+ ["agent", "agent.fast", "agent.plan", "code", "code.normal", "code.plan"],+)+async def test_http_rejects_legacy_single_agent_mode_names(+ tmp_path: Path,+ mode: str,+) -> None:+ database_path = tmp_path / "trajectory.sqlite3"+ _seed(database_path)+ service = TrajectoryHttpService(+ _settings(database_path),+ reader=AsyncTrajectoryReader(database_path),+ metadata_loader=_metadata_loader(mode),+ )++ response = await service.list_traces("session-1", limit=30, cursor=None)++ assert response.status_code == 403+ assert _response_json(response)["code"] == "UNSUPPORTED_SESSION_MODE"+ test_logger.info("legacy single-Agent mode rejected: %s", mode)++@pytest.mark.asyncioasync def test_http_fails_closed_for_unknown_or_missing_session_mode(tmp_path: Path,@@ -1094,7 +1273,8 @@ def test_real_web_proxy_preserves_outer_host_and_guards_all_trajectory_reads() -> None:monkeypatch.setenv("JIUWENSWARM_ENABLE_ORIGIN_CHECK", "1")monkeypatch.setenv("JIUWENSWARM_WS_ALLOWED_ORIGIN_HOSTS", "trusted.example")- database_path = tmp_path / "trajectory.sqlite3"+ database_root = tmp_path / "sessions"+ database_path = session_database_path(database_root, "session-1")expected_raw = _seed(database_path)captured_headers: list[dict[str, str | None]] = []app = FastAPI()@@ -1117,7 +1297,7 @@ def test_real_web_proxy_preserves_outer_host_and_guards_all_trajectory_reads(attach_trajectory_routes(app,SimpleNamespace(),- settings=_settings(database_path),+ settings=_settings(database_root),metadata_loader=_metadata_loader(),)diff --git a/tests/unit_tests/channel/test_trajectory_usage_http.py b/tests/unit_tests/channel/test_trajectory_usage_http.pynew file mode 100644index 0000000000..095ec90b78--- /dev/null+++ b/tests/unit_tests/channel/test_trajectory_usage_http.py@@ -0,0 +1,53 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""HTTP contract tests for session-complete trajectory usage."""++from __future__ import annotations++import json+from pathlib import Path++import pytest++from jiuwenswarm.gateway.channel_manager.web.trajectory_http import TrajectoryHttpService+from jiuwenswarm.observability.config import TrajectoryStoreSettings+++class _UsageReader:+ async def get_session_request_usage(self, session_id: str):+ return ([{+ "trace_id": "1" * 32,+ "inference_id": "inference-1",+ "subject_id": "main",+ "start_time_unix_nano": "10",+ "usage": {"input": 2, "total": 3},+ "cumulative_usage": {"input": 5, "total": 8},+ }], "epoch-1")+++async def test_http_exposes_session_scoped_request_usage(tmp_path: Path) -> None:+ settings = TrajectoryStoreSettings(+ enabled=True,+ database_path=tmp_path,+ retention_days=7,+ queue_size=16,+ batch_size=8,+ flush_interval_ms=20,+ poll_interval_ms=2000,+ )+ service = TrajectoryHttpService(+ settings,+ reader=_UsageReader(),+ metadata_loader=lambda _session_id: {+ "mode": "agent.work.normal",+ "team_name": "",+ },+ )++ response = await service.get_session_usage("session-1")+ payload = json.loads(response.body)++ assert response.status_code == 200+ assert payload["scope"] == "session"+ assert payload["items"][0]["cumulative_usage"] == {"input": 5, "total": 8}diff --git a/tests/unit_tests/observability/test_core_processor_integration.py b/tests/unit_tests/observability/test_core_processor_integration.pyindex 0b9116b09c..f583359e39 100644--- a/tests/unit_tests/observability/test_core_processor_integration.py+++ b/tests/unit_tests/observability/test_core_processor_integration.py@@ -17,6 +17,9 @@ from jiuwenswarm.observability.config import TrajectoryStoreSettingsfrom jiuwenswarm.observability.sink import TrajectoryRecordSinkfrom jiuwenswarm.observability.store import AsyncTrajectoryReaderfrom openjiuwen.extensions.observability.span_record_processor import SpanRecordProcessor+from openjiuwen.extensions.observability.trajectory_events import (+ emit_context_window_commit,+)def _settings(database_path: Path) -> TrajectoryStoreSettings:@@ -108,7 +111,7 @@ async def test_core_processor_delivers_child_then_complete_root_without_reencodi"openjiuwen.session.id": session_id,"openjiuwen.request.id": request_id,"openjiuwen.run.id": request_id,- "openjiuwen.agent.mode": "agent",+ "openjiuwen.agent.mode": "agent.work.normal",},)child = tracer.start_span(@@ -182,7 +185,7 @@ async def test_core_snapshot_is_visible_before_end_and_finalizes_same_identity("gen_ai.conversation.id": session_id,"openjiuwen.request.id": "request-live","openjiuwen.run.id": "run-live",- "openjiuwen.agent.mode": "agent",+ "openjiuwen.agent.mode": "agent.work.normal",}root = tracer.start_span("agent.agent.session-core-swarm-live",@@ -257,3 +260,81 @@ async def test_core_snapshot_is_visible_before_end_and_finalizes_same_identity(processor.unregister_consumer(sink)assert sink.close(timeout=5) is Trueprovider.shutdown()+++async def test_native_context_event_is_queryable_before_parent_request_ends(+ tmp_path: Path,+) -> None:+ database_path = tmp_path / "trajectory-native-event.sqlite3"+ sink = TrajectoryRecordSink(_settings(database_path))+ processor = SpanRecordProcessor()+ provider = TracerProvider()+ provider.add_span_processor(processor)+ tracer = provider.get_tracer("tests.core-swarm-native-event")+ reader = AsyncTrajectoryReader(database_path)++ session_id = "session-native-event"+ parent = None+ sink.start()+ processor.register_consumer(sink)+ try:+ parent = tracer.start_span(+ "llm.call",+ attributes={+ "openjiuwen.trace.schema_version": "2",+ "openjiuwen.session.id": session_id,+ "gen_ai.conversation.id": session_id,+ "openjiuwen.request.id": "request-native-event",+ "openjiuwen.run.id": "run-native-event",+ "openjiuwen.agent.mode": "agent.work.normal",+ "openjiuwen.execution.subject.id": "main",+ "openjiuwen.execution.subject.kind": "main_agent",+ "openjiuwen.execution.subject.session_id": session_id,+ "openjiuwen.turn.number": 1,+ "openjiuwen.step.number": 1,+ },+ )+ event = emit_context_window_commit(+ tracer=tracer,+ llm_span=parent,+ messages=[+ {+ "message_id": "user-1",+ "role": "user",+ "content": "hello",+ "metadata": {"context_message_id": "user-1"},+ }+ ],+ request_purpose="agent",+ )+ assert event is not None++ trace_id = f"{parent.get_span_context().trace_id:032x}"+ event_span_id = f"{event.get_span_context().span_id:016x}"+ record = await _wait_for_record(+ reader,+ session_id,+ trace_id,+ event_span_id,+ lifecycle="final",+ minimum_revision=2,+ )++ span = _span(record)+ assert _attribute(span, "openjiuwen.trajectory.schema_version") == "2"+ assert (+ _attribute(span, "openjiuwen.trajectory.event_kind")+ == "context.window.commit"+ )+ assert _attribute(span, "openjiuwen.execution.subject.id") == "main"+ payload = json.loads(_attribute(span, "openjiuwen.trajectory.payload"))+ assert payload["complete"] is True+ assert payload["messages"][0]["message_id"] == "user-1"+ assert payload["delta"][0]["op"] == "insert"+ finally:+ if parent is not None:+ parent.end()+ processor.unregister_consumer(sink)+ assert sink.close(timeout=5) is True+ provider.shutdown()diff --git a/tests/unit_tests/observability/test_session_trajectory_routing.py b/tests/unit_tests/observability/test_session_trajectory_routing.pynew file mode 100644index 0000000000..50694896be--- /dev/null+++ b/tests/unit_tests/observability/test_session_trajectory_routing.py@@ -0,0 +1,306 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""Tests for per-session trajectory database routing."""++from __future__ import annotations++import json+import logging+import threading+from collections.abc import Sequence+from pathlib import Path+from types import SimpleNamespace++import pytest++from jiuwenswarm.observability.config import (+ TrajectoryStoreSettings,+ session_database_path,+)+from jiuwenswarm.observability.models import TraceRecordData, WriteBatchResult+from jiuwenswarm.observability.sink import (+ CommitCallback,+ TrajectoryRecordSink,+ TrajectorySessionSinkRouter,+)+from jiuwenswarm.observability.store import AsyncTrajectoryReader, TrajectoryStore++test_logger = logging.getLogger("tests.session_trajectory_routing")+++def _settings(database_root: Path, *, flush_interval_ms: int = 20) -> TrajectoryStoreSettings:+ return TrajectoryStoreSettings(+ enabled=True,+ database_path=database_root,+ retention_days=7,+ queue_size=64,+ batch_size=8,+ flush_interval_ms=flush_interval_ms,+ poll_interval_ms=2000,+ )+++def _record(+ session_id: str,+ trace_id: str,+ span_id: str,+ *,+ revision: int = 1,+) -> SimpleNamespace:+ raw_json = json.dumps(+ {+ "resourceSpans": [+ {+ "resource": {},+ "scopeSpans": [+ {+ "scope": {},+ "spans": [+ {+ "traceId": trace_id,+ "spanId": span_id,+ "parentSpanId": "",+ "name": "agent.run",+ "startTimeUnixNano": "100",+ "endTimeUnixNano": "200",+ "status": {},+ }+ ],+ }+ ],+ }+ ]+ },+ separators=(",", ":"),+ ).encode("utf-8")+ return SimpleNamespace(+ raw_json=raw_json,+ trace_id=trace_id,+ span_id=span_id,+ parent_span_id=None,+ start_time_unix_nano=100,+ end_time_unix_nano=200,+ session_id=session_id,+ request_id=f"request-{session_id}",+ run_id=f"run-{session_id}",+ agent_mode="agent.work.normal",+ schema_version="1",+ record_revision=revision,+ observed_time_unix_nano=100 + revision,+ )+++def _snapshot(+ session_id: str,+ trace_id: str,+ span_id: str,+ revision: int,+) -> SimpleNamespace:+ record = _record(+ session_id,+ trace_id,+ span_id,+ revision=revision,+ )+ record.lifecycle = "running"+ record.update_kind = "stream_chunk"+ return record+++async def test_router_writes_and_reads_each_session_database(+ tmp_path: Path,+) -> None:+ root = tmp_path / "sessions"+ router = TrajectorySessionSinkRouter(_settings(root))+ first_trace = "1" * 32+ second_trace = "2" * 32++ router.start()+ router.consume(_record("session-a", first_trace, "a" * 16))+ router.consume(_record("session-b", second_trace, "b" * 16))+ assert router.close(timeout=5) is True++ first_path = session_database_path(root, "session-a")+ second_path = session_database_path(root, "session-b")+ assert first_path != second_path+ assert first_path.is_file()+ assert second_path.is_file()+ reader = AsyncTrajectoryReader(root, session_scoped=True)+ first_items, _cursor = await reader.list_traces(+ "session-a",+ limit=10,+ cursor=None,+ )+ second_items, _cursor = await reader.list_traces(+ "session-b",+ limit=10,+ cursor=None,+ )+ assert [item["trace_id"] for item in first_items] == [first_trace]+ assert [item["trace_id"] for item in second_items] == [second_trace]+ assert router.stats().queued == 0+ test_logger.info("router drained two sessions into independently readable files")+++async def test_router_holds_sessionless_child_until_owned_root_arrives(+ tmp_path: Path,+) -> None:+ root = tmp_path / "sessions"+ router = TrajectorySessionSinkRouter(_settings(root))+ trace_id = "6" * 32+ child = _record("", trace_id, "1" * 16)+ owned_root = _record("session-owner", trace_id, "2" * 16)++ router.start()+ router.consume(child)+ router.consume(owned_root)+ assert router.close(timeout=5) is True++ reader = AsyncTrajectoryReader(root, session_scoped=True)+ detail = await reader.get_trace_records(+ "session-owner",+ trace_id,+ since_revision=0,+ limit=10,+ )+ assert detail is not None+ assert [record["span_id"] for record in detail["records"]] == [+ "1" * 16,+ "2" * 16,+ ]+ test_logger.info("sessionless child retained its order before the owned root")+++class _ControlledStore:+ def __init__(self, *, blocked: bool) -> None:+ self.blocked = blocked+ self.write_started = threading.Event()+ self.release_write = threading.Event()++ def initialize(self) -> None:+ return++ def delete_expired(self, *, now: int | None = None) -> int:+ return 0++ def write_records(self, records: Sequence[TraceRecordData]) -> WriteBatchResult:+ self.write_started.set()+ if self.blocked:+ self.release_write.wait(timeout=10)+ return WriteBatchResult(+ inserted=len(records),+ conflicts=0,+ updates=(),+ )++ def close(self) -> None:+ return+++def test_blocked_session_writer_does_not_delay_another_session(+ tmp_path: Path,+) -> None:+ root = tmp_path / "sessions"+ blocked_store = _ControlledStore(blocked=True)+ other_store = _ControlledStore(blocked=False)+ blocked_path = session_database_path(root, "session-blocked")++ def _sink_factory(+ settings: TrajectoryStoreSettings,+ on_commit: CommitCallback | None,+ ) -> TrajectoryRecordSink:+ store = blocked_store if settings.database_path == blocked_path else other_store+ return TrajectoryRecordSink(settings, on_commit=on_commit, store=store)++ router = TrajectorySessionSinkRouter(+ _settings(root),+ sink_factory=_sink_factory,+ )+ router.start()+ try:+ router.consume(+ _record("session-blocked", "3" * 32, "c" * 16),+ )+ assert blocked_store.write_started.wait(timeout=5)+ router.consume(+ _record("session-free", "4" * 32, "d" * 16),+ )+ assert other_store.write_started.wait(timeout=2)+ finally:+ blocked_store.release_write.set()+ assert router.close(timeout=5) is True+ assert router.stats().committed == 2+ test_logger.info("one blocked session did not head-of-line block another writer")+++def test_same_session_snapshots_coalesce_and_final_record_wins(+ tmp_path: Path,+) -> None:+ root = tmp_path / "sessions"+ settings = _settings(root, flush_interval_ms=100)+ router = TrajectorySessionSinkRouter(settings)+ trace_id = "5" * 32+ span_id = "e" * 16+ final_record = _record("session-one", trace_id, span_id, revision=51)++ router.start()+ for revision in range(1, 51):+ router.consume_snapshot(+ _snapshot("session-one", trace_id, span_id, revision),+ )+ router.consume(final_record)+ assert router.close(timeout=5) is True++ store = TrajectoryStore(session_database_path(root, "session-one"))+ store.initialize()+ try:+ assert store.fetch_raw(trace_id, span_id) == final_record.raw_json+ finally:+ store.close()+ stats = router.stats()+ assert stats.coalesced > 0+ assert stats.dropped_final == 0+ test_logger.info("same-session snapshot burst coalesced before its ordered final")+++def test_session_delete_waits_only_for_target_ingress(tmp_path: Path) -> None:+ router = TrajectorySessionSinkRouter(_settings(tmp_path / "sessions"))++ class _JoinMustNotRunQueue:+ def join(self) -> None:+ raise AssertionError("global ingress join must not be used")++ router._queue = _JoinMustNotRunQueue()+ router._ingress_pending["session-b"] = 1+ router.begin_session_delete("session-a", timeout=0.1)+ test_logger.info("Session deletion did not join the process-wide ingress queue")+++def test_idle_retirement_keeps_route_registered_when_join_times_out(+ tmp_path: Path,+) -> None:+ router = TrajectorySessionSinkRouter(_settings(tmp_path / "sessions"))++ class _TimedOutRoute:+ def __init__(self) -> None:+ self.stop_requested = False++ def can_retire(self, now: float) -> bool:+ return True++ def request_stop(self) -> None:+ self.stop_requested = True++ def join(self, timeout: float) -> bool:+ return False++ route = _TimedOutRoute()+ router._routes["session-a"] = route++ router._retire_idle_routes()++ assert route.stop_requested is True+ assert router._routes["session-a"] is route+ test_logger.info("timed-out idle writer stayed registered against duplication")diff --git a/tests/unit_tests/observability/test_trace_sink.py b/tests/unit_tests/observability/test_trace_sink.pyindex 12143f93f0..2901739d85 100644--- a/tests/unit_tests/observability/test_trace_sink.py+++ b/tests/unit_tests/observability/test_trace_sink.py@@ -30,6 +30,7 @@ def _settings(*,queue_size: int = 16,batch_size: int = 8,+ flush_interval_ms: int = 10,) -> TrajectoryStoreSettings:return TrajectoryStoreSettings(enabled=True,@@ -37,7 +38,7 @@ def _settings(retention_days=7,queue_size=queue_size,batch_size=batch_size,- flush_interval_ms=10,+ flush_interval_ms=flush_interval_ms,poll_interval_ms=2000,)@@ -79,7 +80,7 @@ def _record(*, span_id: str = _SPAN_ID) -> SimpleNamespace:session_id="session-1",request_id="request-1",run_id="run-1",- agent_mode="agent",+ agent_mode="agent.work.normal",schema_version="1",)@@ -130,6 +131,17 @@ class _BusyThenSuccessfulStore(_BlockingStore):return WriteBatchResult(inserted=len(records), conflicts=0, updates=())+class _RecordingStore(_BlockingStore):+ def __init__(self) -> None:+ super().__init__()+ self.batches: list[tuple[TraceRecordData, ...]] = []++ def write_records(self, records: Sequence[TraceRecordData]) -> WriteBatchResult:+ self.batches.append(tuple(records))+ self.write_started.set()+ return WriteBatchResult(inserted=len(records), conflicts=0, updates=())++class _PausingInitializeStore(_BlockingStore):def __init__(self) -> None:super().__init__()@@ -198,6 +210,22 @@ def test_sink_drops_without_blocking_when_not_started(tmp_path: Path) -> None:test_logger.info("inactive sink rejected record without queueing")+def test_sink_rejects_subject_session_owned_by_another_chat(tmp_path: Path) -> None:+ sink = TrajectoryRecordSink(_settings(tmp_path / "trajectory.sqlite3"))+ record = _record()+ record.execution_subject_session_id = "session-previous_sub_general_deadbeef"++ sink.start()+ try:+ sink.consume(record)+ stats = sink.stats()+ assert stats.accepted == 0+ assert stats.failed == 1+ assert stats.queued == 0+ finally:+ assert sink.close(timeout=5) is True++def test_sink_queue_full_drops_without_blocking(tmp_path: Path) -> None:store = _BlockingStore()sink = TrajectoryRecordSink(@@ -243,7 +271,7 @@ def test_sink_coalesces_pending_live_snapshots_by_identity(tmp_path: Path) -> Nosink.consume_snapshot(_snapshot(revision))stats_while_blocked = sink.stats()assert stats_while_blocked.queued == 1- assert stats_while_blocked.coalesced == 8+ assert stats_while_blocked.coalesced >= 8finally:store.release_write.set()assert sink.close(timeout=5) is True@@ -251,6 +279,31 @@ def test_sink_coalesces_pending_live_snapshots_by_identity(tmp_path: Path) -> Notest_logger.info("live snapshot flood retained only the newest pending identity")+def test_sink_debounces_snapshot_flood_before_sqlite_write(tmp_path: Path) -> None:+ store = _RecordingStore()+ sink = TrajectoryRecordSink(+ _settings(+ tmp_path / "trajectory.sqlite3",+ batch_size=8,+ flush_interval_ms=100,+ ),+ store=store,+ )+ sink.start()+ try:+ for revision in range(1, 51):+ sink.consume_snapshot(_snapshot(revision))+ assert store.write_started.wait(timeout=2)+ finally:+ assert sink.close(timeout=5) is True++ assert len(store.batches) == 1+ assert len(store.batches[0]) == 1+ assert store.batches[0][0].record_revision == 50+ assert sink.stats().coalesced == 49+ test_logger.info("snapshot debounce persisted one latest revision from a burst")++def test_sink_rejects_invalid_raw_type_without_raising(tmp_path: Path) -> None:sink = TrajectoryRecordSink(_settings(tmp_path / "trajectory.sqlite3"))record = _record()diff --git a/tests/unit_tests/observability/test_trace_store.py b/tests/unit_tests/observability/test_trace_store.pyindex d77d2876cf..4182348fe6 100644--- a/tests/unit_tests/observability/test_trace_store.py+++ b/tests/unit_tests/observability/test_trace_store.py@@ -82,7 +82,7 @@ def _core_record(session_id: str | None = "session-1",request_id: str | None = "request-1",run_id: str | None = "run-1",- agent_mode: str | None = "agent",+ agent_mode: str | None = "agent.work.normal",start_time: int = 100,end_time: int = 200,raw_json: bytes | None = None,@@ -112,15 +112,20 @@ def _stored_record(**overrides: object) -> TraceRecordData:return TraceRecordData.from_core_record(_core_record(**overrides))-def _snapshot_record(revision: int, *, name: str) -> TraceRecordData:- raw_json = _raw_record(_TRACE_ID, _ROOT_SPAN_ID, name=name).replace(+def _snapshot_record_for(+ span_id: str,+ revision: int,+ *,+ name: str,+) -> TraceRecordData:+ raw_json = _raw_record(_TRACE_ID, span_id, name=name).replace(b',"endTimeUnixNano":"200"',b"",)snapshot = SimpleNamespace(raw_json=raw_json,trace_id=_TRACE_ID,- span_id=_ROOT_SPAN_ID,+ span_id=span_id,parent_span_id=None,start_time_unix_nano=100,observed_time_unix_nano=100 + revision,@@ -129,13 +134,17 @@ def _snapshot_record(revision: int, *, name: str) -> TraceRecordData:session_id="session-1",request_id="request-1",run_id="run-1",- agent_mode="agent",+ agent_mode="agent.work.normal",schema_version="1",lifecycle="running",)return TraceRecordData.from_core_snapshot(snapshot)+def _snapshot_record(revision: int, *, name: str) -> TraceRecordData:+ return _snapshot_record_for(_ROOT_SPAN_ID, revision, name=name)++def _detail_span_id(record: dict[str, Any]) -> str:return str(record["otlp"]["resourceSpans"][0]["scopeSpans"][0]["spans"][0]["spanId"]@@ -217,6 +226,14 @@ async def test_live_revisions_finalize_in_place_and_reject_late_running(""",(_TRACE_ID, _ROOT_SPAN_ID),).fetchone()+ journal_payload_bytes = connection.execute(+ """+ SELECT COALESCE(SUM(LENGTH(raw_json)), 0) AS payload_bytes+ FROM trajectory_changes+ WHERE trace_id = ? AND span_id = ?+ """,+ (_TRACE_ID, _ROOT_SPAN_ID),+ ).fetchone()finally:store.close()@@ -229,6 +246,8 @@ async def test_live_revisions_finalize_in_place_and_reject_late_running(assert current["lifecycle"] == "final"assert bytes(current["raw_json"]) == final_record.raw_jsonassert change_count is not None and int(change_count["count"]) == 3+ assert journal_payload_bytes is not None+ assert int(journal_payload_bytes["payload_bytes"]) == 0detail = await AsyncTrajectoryReader(database_path).get_trace_records("session-1",@@ -237,11 +256,7 @@ async def test_live_revisions_finalize_in_place_and_reject_late_running(limit=100,)assert detail is not None- assert [record["lifecycle"] for record in detail["records"]] == [- "running",- "running",- "final",- ]+ assert [record["lifecycle"] for record in detail["records"]] == ["final"]assert {record["record_id"] for record in detail["records"]} == {f"{_TRACE_ID}:{_ROOT_SPAN_ID}"}@@ -250,7 +265,115 @@ async def test_live_revisions_finalize_in_place_and_reject_late_running(_TRACE_ID,_ROOT_SPAN_ID,) == final_record.raw_json- test_logger.info("running revisions atomically converged on one authoritative final identity")+ assert detail["next_since_revision"] == detail["revision"]+ test_logger.info("detail sync returned only the authoritative final identity")+++async def test_detail_delta_coalesces_missed_revisions_but_keeps_live_progress(+ tmp_path: Path,+) -> None:+ database_path = tmp_path / "trajectory.sqlite3"+ store = TrajectoryStore(database_path)+ store.initialize()+ try:+ store.write_records([_snapshot_record(1, name="running-1")])+ finally:+ store.close()++ reader = AsyncTrajectoryReader(database_path)+ running = await reader.get_trace_records(+ "session-1",+ _TRACE_ID,+ since_revision=0,+ limit=100,+ )+ assert running is not None+ assert [record["lifecycle"] for record in running["records"]] == ["running"]++ store.initialize()+ try:+ store.write_records([_snapshot_record(2, name="running-2")])+ final_record = _stored_record(+ raw_json=_raw_record(_TRACE_ID, _ROOT_SPAN_ID, name="final"),+ )+ store.write_records([final_record])+ finally:+ store.close()++ final = await reader.get_trace_records(+ "session-1",+ _TRACE_ID,+ since_revision=running["next_since_revision"],+ limit=100,+ )+ assert final is not None+ assert len(final["records"]) == 1+ assert final["records"][0]["lifecycle"] == "final"+ assert final["records"][0]["record_revision"] == 1+ assert final["next_since_revision"] == final["revision"]+ test_logger.info("missed running snapshots collapsed while live and final states remained visible")+++async def test_detail_delta_does_not_skip_concurrent_updates_across_pages(+ tmp_path: Path,+) -> None:+ database_path = tmp_path / "trajectory.sqlite3"+ store = TrajectoryStore(database_path)+ store.initialize()+ try:+ store.write_records([+ _snapshot_record_for(_ROOT_SPAN_ID, 1, name="root-running-1"),+ _snapshot_record_for(_CHILD_SPAN_ID, 1, name="child-running-1"),+ ])+ finally:+ store.close()++ reader = AsyncTrajectoryReader(database_path)+ first_page = await reader.get_trace_records(+ "session-1",+ _TRACE_ID,+ since_revision=0,+ limit=1,+ )+ assert first_page is not None+ assert first_page["has_more"] is True+ assert [_detail_span_id(record) for record in first_page["records"]] == [+ _ROOT_SPAN_ID+ ]++ store.initialize()+ try:+ store.write_records([+ _snapshot_record_for(_ROOT_SPAN_ID, 2, name="root-running-2"),+ _snapshot_record_for(_CHILD_SPAN_ID, 2, name="child-running-2"),+ ])+ finally:+ store.close()++ cursor = first_page["next_since_revision"]+ observed: list[tuple[str, int]] = []+ while True:+ page = await reader.get_trace_records(+ "session-1",+ _TRACE_ID,+ since_revision=cursor,+ limit=1,+ )+ assert page is not None+ observed.extend(+ (_detail_span_id(record), int(record["record_revision"]))+ for record in page["records"]+ )+ assert page["next_since_revision"] > cursor+ cursor = page["next_since_revision"]+ if not page["has_more"]:+ assert cursor == page["revision"]+ break++ assert observed == [(_ROOT_SPAN_ID, 2), (_CHILD_SPAN_ID, 2)]+ test_logger.info("concurrent updates to returned and pending identities converged without skips")@pytest.mark.asyncio@@ -696,7 +819,7 @@ async def test_reader_rejects_team_unknown_and_mixed_mode_traces(_stored_record(trace_id=mixed_trace_id,span_id="1" * 16,- agent_mode="agent",+ agent_mode="agent.work.normal",raw_json=_raw_record(mixed_trace_id, "1" * 16),),_stored_record(@@ -1520,7 +1643,9 @@ async def test_global_eligibility_keeps_record_paths_session_isolated(@pytest.mark.asyncio-async def test_reverse_eligibility_change_rotates_epoch(tmp_path: Path) -> None:+async def test_newly_eligible_trace_preserves_epoch_and_updates_revision_feed(+ tmp_path: Path,+) -> None:database_path = tmp_path / "trajectory.sqlite3"unknown_span_id = "5" * 16known_span_id = "6" * 16@@ -1558,7 +1683,7 @@ async def test_reverse_eligibility_change_rotates_epoch(tmp_path: Path) -> None:[_stored_record(span_id=known_span_id,- agent_mode="agent",+ agent_mode="agent.work.normal",raw_json=_raw_record(_TRACE_ID, known_span_id),)]@@ -1567,7 +1692,7 @@ async def test_reverse_eligibility_change_rotates_epoch(tmp_path: Path) -> None:finally:store.close()- assert new_epoch != old_epoch+ assert new_epoch == old_epochvisible_items, _cursor = await reader.list_traces("session-1", limit=30, cursor=None)@@ -1575,9 +1700,12 @@ async def test_reverse_eligibility_change_rotates_epoch(tmp_path: Path) -> None:revisions = await reader.list_trace_revisions("session-1", after_revision=old_cursor, limit=30)- assert revisions[4] is True- assert revisions[5] == new_epoch- test_logger.info("ineligible-to-eligible reconciliation rotated the store epoch")+ assert len(revisions[0]) == 1+ assert revisions[0][0]["trace_id"] == _TRACE_ID+ assert revisions[0][0]["span_count"] == 2+ assert revisions[4] is False+ assert revisions[5] == old_epoch+ test_logger.info("newly eligible trace stayed on the incremental revision feed")@pytest.mark.asynciodiff --git a/tests/unit_tests/observability/test_trajectory_config.py b/tests/unit_tests/observability/test_trajectory_config.pyindex 7007130b01..2f36370186 100644--- a/tests/unit_tests/observability/test_trajectory_config.py+++ b/tests/unit_tests/observability/test_trajectory_config.py@@ -5,12 +5,14 @@from __future__ import annotationsimport logging+import refrom pathlib import Pathfrom jiuwenswarm.observability.config import (DEFAULT_QUEUE_SIZE,TrajectoryStoreSettings,load_trajectory_store_settings,+ session_database_path,)test_logger = logging.getLogger("tests.trajectory_config")@@ -21,7 +23,7 @@ def test_config_defaults_keep_legacy_installations_disabled(tmp_path: Path) -> Nassert settings == TrajectoryStoreSettings(enabled=False,- database_path=tmp_path / ".trace" / "trajectory.sqlite3",+ database_path=tmp_path / ".trace" / "sessions",retention_days=7,queue_size=4096,batch_size=64,@@ -51,3 +53,19 @@ def test_config_resolves_relative_path_and_rejects_non_positive_limits(assert settings.queue_size == DEFAULT_QUEUE_SIZEassert settings.batch_size == 12test_logger.info("trajectory config normalized paths and unsafe limits")+++def test_session_database_path_is_deterministic_and_traversal_safe(+ tmp_path: Path,+) -> None:+ database_root = tmp_path / "trajectory-sessions"++ first = session_database_path(database_root, "../../outside\\session")+ second = session_database_path(database_root, "../../outside\\session")++ assert first == second+ assert first.parent.parent == database_root+ assert re.fullmatch(r"[0-9a-f]{2}", first.parent.name)+ assert re.fullmatch(r"[0-9a-f]{64}\.sqlite3", first.name)+ assert "outside" not in str(first.relative_to(database_root))+ test_logger.info("session database paths contain only SHA-256 components")diff --git a/tests/unit_tests/observability/test_trajectory_gateway_hints.py b/tests/unit_tests/observability/test_trajectory_gateway_hints.pynew file mode 100644index 0000000000..d60e96cc11--- /dev/null+++ b/tests/unit_tests/observability/test_trajectory_gateway_hints.py@@ -0,0 +1,155 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""Tests for the AgentServer-to-Gateway trajectory hint bridge."""++from __future__ import annotations++import asyncio+import logging+from types import SimpleNamespace++import pytest++from jiuwenswarm.gateway.message_handler.message_handler import MessageHandler+from jiuwenswarm.observability.gateway_hints import TrajectoryGatewayHintBridge+from jiuwenswarm.observability.models import CommittedTraceUpdate+from jiuwenswarm.server.gateway_push.wire import build_server_push_wire++test_logger = logging.getLogger("tests.trajectory_gateway_hints")+++async def test_bridge_catches_up_revision_committed_while_send_is_in_flight() -> None:+ bridge = TrajectoryGatewayHintBridge()+ first_send_started = asyncio.Event()+ release_first_send = asyncio.Event()+ sent: list[dict[str, object]] = []++ async def _send(message: dict[str, object]) -> None:+ sent.append(message)+ if len(sent) == 1:+ first_send_started.set()+ await release_first_send.wait()++ loop = asyncio.get_running_loop()+ bridge.bind(loop, _send)+ bridge.publish(+ (+ CommittedTraceUpdate("session-1", "a" * 32, 10, lifecycle="running"),+ CommittedTraceUpdate("session-1", "a" * 32, 11, lifecycle="running"),+ )+ )+ await first_send_started.wait()+ bridge.publish(+ (+ CommittedTraceUpdate("session-1", "a" * 32, 12, lifecycle="final"),+ )+ )+ release_first_send.set()++ for _attempt in range(20):+ if len(sent) == 2:+ break+ await asyncio.sleep(0)+ await bridge.unbind()++ assert [message["payload"]["revision"] for message in sent] == [11, 12]+ assert sent[1]["payload"]["lifecycle"] == "final"+ test_logger.info("in-flight send caught up the terminal revision")+++async def test_gateway_routes_cross_process_hint_into_webchannel_coalescer() -> None:+ handler = object.__new__(MessageHandler)+ scheduled: list[tuple[CommittedTraceUpdate, ...]] = []+ web_channel = SimpleNamespace(+ _schedule_trajectory_updates=lambda updates: scheduled.append(tuple(updates))+ )+ handler._resolve_web_channel = lambda: web_channel+ handler._stream_sessions = {}+ wire = build_server_push_wire(+ {+ "request_id": "trajectory:session-1:trace:21",+ "channel_id": "web",+ "session_id": "session-1",+ "is_complete": False,+ "payload": {+ "event_type": "trace.updated",+ "session_id": "session-1",+ "trace_id": "b" * 32,+ "revision": 21,+ "store_epoch": "epoch-1",+ "lifecycle": "running",+ },+ }+ )++ await handler._handle_agent_server_push(wire)++ assert scheduled == [+ (+ CommittedTraceUpdate(+ session_id="session-1",+ trace_id="b" * 32,+ revision=21,+ store_epoch="epoch-1",+ lifecycle="running",+ ),+ )+ ]+ test_logger.info("Gateway handed the cross-process hint to WebChannel")+++async def test_bridge_preserves_first_hints_for_distinct_subagent_traces() -> None:+ bridge = TrajectoryGatewayHintBridge()+ sent: list[dict[str, object]] = []++ async def _send(message: dict[str, object]) -> None:+ sent.append(message)++ bridge.bind(asyncio.get_running_loop(), _send)+ bridge.publish(+ (+ CommittedTraceUpdate("session-1", "c" * 32, 1, lifecycle="running"),+ CommittedTraceUpdate("session-1", "d" * 32, 2, lifecycle="running"),+ )+ )+ for _attempt in range(20):+ if len(sent) == 2:+ break+ await asyncio.sleep(0)+ await bridge.unbind()++ assert {message["payload"]["trace_id"] for message in sent} == {+ "c" * 32,+ "d" * 32,+ }+ test_logger.info("first updates for distinct execution traces were both delivered")+++async def test_bridge_retries_hint_rejected_during_gateway_disconnect() -> None:+ bridge = TrajectoryGatewayHintBridge()+ attempts: list[dict[str, object]] = []+ delivered = asyncio.Event()++ async def _send(message: dict[str, object]) -> bool:+ attempts.append(message)+ if len(attempts) == 1:+ return False+ delivered.set()+ return True++ bridge.bind(asyncio.get_running_loop(), _send)+ bridge.publish(+ (+ CommittedTraceUpdate("session-1", "e" * 32, 31, lifecycle="final"),+ )+ )+ await asyncio.wait_for(delivered.wait(), timeout=2)+ await bridge.unbind()++ assert len(attempts) == 2+ assert attempts[1]["payload"]["revision"] == 31+ test_logger.info("temporary Gateway disconnect retained and retried the watermark")diff --git a/tests/unit_tests/observability/test_trajectory_session_delete.py b/tests/unit_tests/observability/test_trajectory_session_delete.pynew file mode 100644index 0000000000..9b006983fb--- /dev/null+++ b/tests/unit_tests/observability/test_trajectory_session_delete.py@@ -0,0 +1,211 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""Tests for Session-scoped trajectory deletion lifecycle."""++from __future__ import annotations++import json+import logging+import time+from pathlib import Path+from types import SimpleNamespace++import pytest++from jiuwenswarm.observability.config import (+ TrajectoryStoreSettings,+ session_database_path,+)+from jiuwenswarm.observability.session_delete import (+ TrajectorySessionDeleteLifecycle,+)+from jiuwenswarm.observability.sink import TrajectorySessionSinkRouter++test_logger = logging.getLogger("tests.trajectory_session_delete")++_TRACE_ID = "9" * 32+_SPAN_ID = "d" * 16+++class _RecordingBackend:+ def __init__(self) -> None:+ self.events: list[tuple[str, str]] = []+ self.abort_error: Exception | None = None++ def begin_session_delete(self, session_id: str) -> None:+ self.events.append(("begin", session_id))++ def abort_session_delete(self, session_id: str) -> None:+ self.events.append(("abort", session_id))+ if self.abort_error is not None:+ raise self.abort_error++ def commit_session_delete(self, session_id: str) -> None:+ self.events.append(("commit", session_id))+++def _settings(database_root: Path) -> TrajectoryStoreSettings:+ return TrajectoryStoreSettings(+ enabled=True,+ database_path=database_root,+ retention_days=7,+ queue_size=32,+ batch_size=8,+ flush_interval_ms=10,+ poll_interval_ms=2000,+ )+++def _record(session_id: str) -> SimpleNamespace:+ raw_json = json.dumps(+ {+ "resourceSpans": [+ {+ "resource": {},+ "scopeSpans": [+ {+ "scope": {},+ "spans": [+ {+ "traceId": _TRACE_ID,+ "spanId": _SPAN_ID,+ "parentSpanId": "",+ "name": "agent.run",+ "startTimeUnixNano": "100",+ "endTimeUnixNano": "200",+ "status": {},+ }+ ],+ }+ ],+ }+ ]+ },+ separators=(",", ":"),+ ).encode("utf-8")+ return SimpleNamespace(+ raw_json=raw_json,+ trace_id=_TRACE_ID,+ span_id=_SPAN_ID,+ parent_span_id=None,+ start_time_unix_nano=100,+ end_time_unix_nano=200,+ session_id=session_id,+ request_id="request-1",+ run_id="run-1",+ agent_mode="agent.work.normal",+ schema_version="1",+ )+++def _wait_until(predicate, *, timeout: float = 5.0) -> None:+ deadline = time.monotonic() + timeout+ while time.monotonic() < deadline:+ if predicate():+ return+ time.sleep(0.01)+ raise AssertionError("condition was not satisfied before timeout")+++def test_successful_delete_closes_route_and_removes_sqlite_sidecars(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ lifecycle = TrajectorySessionDeleteLifecycle()+ router = TrajectorySessionSinkRouter(_settings(tmp_path / "sessions"))+ lifecycle.set_backend(router)+ monkeypatch.setattr(+ "jiuwenswarm.observability.sink.trajectory_session_accepts_records",+ lifecycle.accepts_records,+ )+ session_id = "session-delete-success"+ database_path = session_database_path(router.settings.database_path, session_id)+ router.start()+ try:+ router.consume(_record(session_id))+ _wait_until(lambda: database_path.is_file() and router.stats().committed == 1)+ lifecycle.begin(session_id)+ for suffix in ("-wal", "-shm"):+ database_path.with_name(f"{database_path.name}{suffix}").touch()+ lifecycle.commit(session_id)+ assert not database_path.exists()+ assert not database_path.with_name(f"{database_path.name}-wal").exists()+ assert not database_path.with_name(f"{database_path.name}-shm").exists()+ assert lifecycle.accepts_records(session_id) is False+ finally:+ assert router.close(timeout=5) is True+ test_logger.info("Session deletion removed the database and both SQLite sidecars")+++def test_failed_product_delete_aborts_and_allows_writes_again() -> None:+ lifecycle = TrajectorySessionDeleteLifecycle()+ backend = _RecordingBackend()+ lifecycle.set_backend(backend)++ lifecycle.begin("session-delete-abort")+ assert lifecycle.accepts_records("session-delete-abort") is False+ lifecycle.abort("session-delete-abort")++ assert lifecycle.accepts_records("session-delete-abort") is True+ assert backend.events == [+ ("begin", "session-delete-abort"),+ ("abort", "session-delete-abort"),+ ]+++def test_abort_releases_tombstone_even_when_backend_rollback_fails() -> None:+ lifecycle = TrajectorySessionDeleteLifecycle()+ backend = _RecordingBackend()+ backend.abort_error = RuntimeError("rollback failed")+ lifecycle.set_backend(backend)+ lifecycle.begin("session-delete-abort-error")++ with pytest.raises(RuntimeError, match="rollback failed"):+ lifecycle.abort("session-delete-abort-error")++ assert lifecycle.accepts_records("session-delete-abort-error") is True+++def test_late_record_is_rejected_while_session_is_tombstoned(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ lifecycle = TrajectorySessionDeleteLifecycle()+ router = TrajectorySessionSinkRouter(_settings(tmp_path / "sessions"))+ lifecycle.set_backend(router)+ monkeypatch.setattr(+ "jiuwenswarm.observability.sink.trajectory_session_accepts_records",+ lifecycle.accepts_records,+ )+ session_id = "session-delete-late"+ database_path = session_database_path(router.settings.database_path, session_id)+ router.start()+ try:+ lifecycle.begin(session_id)+ router.consume(_record(session_id))+ assert router.stats().dropped == 1+ assert not database_path.exists()+ lifecycle.commit(session_id)+ router.consume(_record(session_id))+ assert router.stats().dropped == 2+ assert not database_path.exists()+ finally:+ assert router.close(timeout=5) is True+++def test_repeated_begin_commit_and_abort_are_idempotent() -> None:+ lifecycle = TrajectorySessionDeleteLifecycle()+ backend = _RecordingBackend()+ lifecycle.set_backend(backend)++ lifecycle.begin("session-delete-repeat")+ lifecycle.begin("session-delete-repeat")+ lifecycle.commit("session-delete-repeat")+ lifecycle.commit("session-delete-repeat")+ lifecycle.abort("session-delete-repeat")++ assert backend.events == [+ ("begin", "session-delete-repeat"),+ ("commit", "session-delete-repeat"),+ ]+ assert lifecycle.accepts_records("session-delete-repeat") is Falsediff --git a/tests/unit_tests/observability/test_trajectory_session_usage.py b/tests/unit_tests/observability/test_trajectory_session_usage.pynew file mode 100644index 0000000000..3a62b9bf46--- /dev/null+++ b/tests/unit_tests/observability/test_trajectory_session_usage.py@@ -0,0 +1,130 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""Tests for session-complete request usage projections."""++from __future__ import annotations++import asyncio+import json+from pathlib import Path+from types import SimpleNamespace++import pytest++from jiuwenswarm.observability.config import session_database_path+from jiuwenswarm.observability.models import TraceRecordData+from jiuwenswarm.observability.store import AsyncTrajectoryReader, TrajectoryStore+++def _record(+ session_id: str,+ trace_id: str,+ span_id: str,+ inference_id: str,+ subject_id: str,+ start: int,+ input_tokens: int,+ *,+ span_name: str = "llm.call",+) -> TraceRecordData:+ attributes = {+ "openjiuwen.inference.id": inference_id,+ "openjiuwen.execution.subject.id": subject_id,+ "gen_ai.usage.input_tokens": input_tokens,+ "gen_ai.usage.output_tokens": 1,+ "gen_ai.usage.total_tokens": input_tokens + 1,+ }+ raw_json = json.dumps({+ "resourceSpans": [{+ "resource": {},+ "scopeSpans": [{+ "scope": {},+ "spans": [{+ "traceId": trace_id,+ "spanId": span_id,+ "name": span_name,+ "startTimeUnixNano": str(start),+ "endTimeUnixNano": str(start + 1),+ "attributes": [+ {"key": key, "value": {"intValue": str(value)}}+ if isinstance(value, int)+ else {"key": key, "value": {"stringValue": value}}+ for key, value in attributes.items()+ ],+ }],+ }],+ }],+ }, separators=(",", ":")).encode()+ return TraceRecordData.from_core_record(SimpleNamespace(+ raw_json=raw_json,+ trace_id=trace_id,+ span_id=span_id,+ parent_span_id=None,+ start_time_unix_nano=start,+ end_time_unix_nano=start + 1,+ session_id=session_id,+ request_id="request-1",+ run_id="run-1",+ agent_mode="agent.work.normal",+ schema_version="1",+ ))+++async def test_session_usage_partitions_subjects_and_uses_physical_identity(+ tmp_path: Path,+) -> None:+ database_path = tmp_path / "trajectory.sqlite3"+ store = TrajectoryStore(database_path)+ store.initialize()+ try:+ store.write_records([+ _record("session-1", "1" * 32, "1" * 16, "shared", "main", 10, 10),+ _record("session-1", "2" * 32, "2" * 16, "shared", "subagent:one", 20, 20),+ _record("session-1", "1" * 32, "3" * 16, "main-next", "main", 30, 5),+ _record(+ "session-1",+ "1" * 32,+ "4" * 16,+ "main-next",+ "main",+ 31,+ 999,+ span_name="llm.reasoning",+ ),+ ])+ finally:+ store.close()++ items, _epoch = await AsyncTrajectoryReader(database_path).get_session_request_usage(+ "session-1"+ )++ by_identity = {+ (item["trace_id"], item["inference_id"]): item for item in items+ }+ assert len(by_identity) == 3+ assert by_identity[("1" * 32, "main-next")]["cumulative_usage"]["input"] == 15+ assert by_identity[("2" * 32, "shared")]["cumulative_usage"]["input"] == 20+++async def test_session_usage_reader_locks_are_session_isolated(tmp_path: Path) -> None:+ root = tmp_path / "sessions"+ for session_id, digit in (("session-a", "a"), ("session-b", "b")):+ store = TrajectoryStore(session_database_path(root, session_id))+ store.initialize()+ try:+ store.write_records([+ _record(session_id, digit * 32, digit * 16, digit, "main", 10, 1)+ ])+ finally:+ store.close()+ reader = AsyncTrajectoryReader(root, session_scoped=True)++ await asyncio.gather(+ reader.get_session_request_usage("session-a"),+ reader.get_session_request_usage("session-b"),+ )++ assert reader._usage_locks["session-a"] is not reader._usage_locks["session-b"]diff --git a/tests/unit_tests/observability/test_trajectory_updates.py b/tests/unit_tests/observability/test_trajectory_updates.pyindex 31e5122ce0..8404abea90 100644--- a/tests/unit_tests/observability/test_trajectory_updates.py+++ b/tests/unit_tests/observability/test_trajectory_updates.py@@ -89,3 +89,52 @@ async def test_webchannel_routes_trace_update_to_matching_session_only() -> None"lifecycle": "final",}test_logger.info("trace update hint stayed scoped to its session")+++async def test_webchannel_coalesces_running_backlog_into_latest_final_hint(+ monkeypatch,+) -> None:+ monkeypatch.setattr(+ "jiuwenswarm.gateway.channel_manager.web.web_connect."+ "_TRAJECTORY_HINT_COALESCE_SECONDS",+ 0,+ )+ channel = WebChannel.__new__(WebChannel)+ channel._trajectory_pending_updates = {}+ channel._trajectory_send_task = None+ sent: list[tuple[CommittedTraceUpdate, ...]] = []++ async def _send(updates) -> None:+ sent.append(tuple(updates))++ channel._send_trajectory_updates = _send+ running = CommittedTraceUpdate(+ session_id="session-1",+ trace_id="3" * 32,+ revision=100,+ lifecycle="running",+ )+ stale = CommittedTraceUpdate(+ session_id="session-1",+ trace_id="3" * 32,+ revision=99,+ lifecycle="running",+ )+ final = CommittedTraceUpdate(+ session_id="session-1",+ trace_id="3" * 32,+ revision=101,+ lifecycle="final",+ )++ channel._schedule_trajectory_updates((running,))+ channel._schedule_trajectory_updates((stale, final))+ task = channel._trajectory_send_task+ assert task is not None+ await task++ assert sent == [(final,)]+ assert channel._trajectory_pending_updates == {}+ assert channel._trajectory_send_task is None+ test_logger.info("latest final hint absorbed the queued running backlog")diff --git a/tests/unit_tests/test_mode_matrix.py b/tests/unit_tests/test_mode_matrix.pynew file mode 100644index 0000000000..f9d66475d6--- /dev/null+++ b/tests/unit_tests/test_mode_matrix.py@@ -0,0 +1,453 @@+"""Web 组合模式解析与 TUI 历史模式直通的回归测试。"""++import pytest++from jiuwenswarm.common.schema.agent import AgentRequest+from jiuwenswarm.common.schema.message import Mode+from jiuwenswarm.common.mode_matrix import (+ NEW_AGENT_WORK_NORMAL,+ NEW_AGENT_WORK_PLAN,+ NEW_AGENT_CODE_NORMAL,+ NEW_AGENT_CODE_PLAN,+ NEW_TEAM_WORK_NORMAL,+ NEW_TEAM_WORK_PLAN,+ NEW_TEAM_CODE_NORMAL,+ NEW_TEAM_CODE_PLAN,+ base_mode_without_plan,+ deprecate_mode,+ is_plan_mode,+ is_single_agent_mode,+ is_team_mode,+ resolve_request_mode,+)+from jiuwenswarm.server.agent_ws_server import (+ _apply_resolved_mode_to_request,+ resolve_agent_request_mode,+)+++def _resolve(params):+ return resolve_request_mode(params, resolve_agent_request_mode)+++def test_request_preserves_original_mode_when_web_composition_rewrites_it():+ request = AgentRequest(+ request_id="req-1",+ params={"mode": "agent.plan", "work_mode": "code"},+ )++ assert _apply_resolved_mode_to_request(request, work_mode="code") == ("code", "plan")+ assert request.params["mode"] == "code.plan"+ assert getattr(request, "_original_mode") == "agent.plan"+++# ── Web 组合:work_mode 决定 profile,mode 决定是否 plan / team ─────────────+++ ("mode", "work_mode", "expected"),+ [+ ("agent", "work", ("agent", None, "agent")),+ ("agent.plan", "work", ("agent", "plan", "agent.plan")),+ ("agent", "code", ("code", "normal", "code.normal")),+ ("agent.plan", "code", ("code", "plan", "code.plan")),+ ("team", "work", ("team", None, "team")),+ ("team", "code", ("code", "team", "code.team")),+ ],+)+def test_web_composition_covers_all_supported_combinations(mode, work_mode, expected):+ resolved = _resolve({"mode": mode, "work_mode": work_mode})++ assert (resolved.manager_mode, resolved.sub_mode, resolved.canonical_mode) == expected+ assert resolved.from_web_composition is True+ assert resolved.is_code_profile is (work_mode == "code")+++ ("mode", "work_mode", "expected_plan"),+ [+ ("agent", "work", False),+ ("agent.plan", "work", True),+ ("agent.plan", "code", True),+ ],+)+def test_web_composition_plan_flag(mode, work_mode, expected_plan):+ resolved = _resolve({"mode": mode, "work_mode": work_mode})++ assert resolved.is_plan is expected_plan+ assert resolved.is_team is False+++ ("work_mode", "expected_manager", "expected_canonical"),+ [("work", "team", "team"), ("code", "code", "code.team")],+)+def test_web_team_uses_matching_profile(work_mode, expected_manager, expected_canonical):+ resolved = _resolve({"mode": "team", "work_mode": work_mode})++ assert resolved.from_web_composition is True+ assert (resolved.manager_mode, resolved.sub_mode, resolved.canonical_mode) == (+ expected_manager,+ None if work_mode == "work" else "team",+ expected_canonical,+ )+ assert resolved.is_team is True+ assert resolved.is_code_profile is (work_mode == "code")+++ ("mode", "work_mode", "expected_normal"),+ [+ ("agent.plan", "work", "agent"),+ ("agent.plan", "code", "code.normal"),+ ],+)+def test_plan_exit_mode_is_profile_aware(mode, work_mode, expected_normal):+ assert _resolve({"mode": mode, "work_mode": work_mode}).normal_mode == expected_normal++[email protected]("work_mode", ["work", "code"])+def test_web_team_plan_is_not_composable(work_mode):+ """Team Plan 不参与 Web 组合,正式别名始终选择 normal profile。"""+ resolved = _resolve({"mode": "team.plan", "work_mode": work_mode})++ assert resolved.from_web_composition is False+ assert (resolved.manager_mode, resolved.sub_mode, resolved.canonical_mode) == (+ "team",+ "plan",+ "team.plan.normal",+ )+ assert resolved.profile == "normal"+++# ── P6.4:新三段命名串 agent.work.normal / agent.work.plan 的 Web 组合分支 ────+++ ("mode", "work_mode", "expected"),+ [+ (NEW_AGENT_WORK_NORMAL, "work", ("agent", None, NEW_AGENT_WORK_NORMAL)),+ (NEW_AGENT_WORK_PLAN, "work", ("agent", "plan", NEW_AGENT_WORK_PLAN)),+ ],+)+def test_web_new_three_segment_modes_hit_composition_branch(mode, work_mode, expected):+ """P6.4:前端 wireMode.ts 产出的新三段命名串必须命中组合分支。++ 回归 P6.1 改 wireMode.ts、P6.4 扩 ``WEB_COMPOSABLE_MODES`` 的接通点:+ 前端发 ``agent.work.plan`` + 后端读到 work_mode=work(来自 session metadata),+ 组合分支应直接产出 ``(agent, plan, agent.work.plan)`` 三元组,+ 而不是落 legacy 默认 ``agent``。+ """+ resolved = _resolve({"mode": mode, "work_mode": work_mode})++ assert resolved.from_web_composition is True+ assert (resolved.manager_mode, resolved.sub_mode, resolved.canonical_mode) == expected+++def test_web_new_plan_string_is_plan_flag_true():+ resolved = _resolve({"mode": NEW_AGENT_WORK_PLAN, "work_mode": "work"})++ assert resolved.is_plan is True+ assert resolved.is_team is False+ assert resolved.is_code_profile is False+ assert resolved.profile == "normal"+++def test_web_new_normal_string_is_plan_flag_false():+ resolved = _resolve({"mode": NEW_AGENT_WORK_NORMAL, "work_mode": "work"})++ assert resolved.is_plan is False+ assert resolved.is_team is False+ assert resolved.is_code_profile is False+ assert resolved.profile == "normal"+++def test_web_new_plan_normal_mode_uses_three_segment_exit():+ """P6.4:plan 退出后应回到新三段命名的 normal 变体。"""+ resolved = _resolve({"mode": NEW_AGENT_WORK_PLAN, "work_mode": "work"})++ assert resolved.normal_mode == NEW_AGENT_WORK_NORMAL+++def test_web_new_strings_take_work_mode_from_kwarg_when_params_omit_it():+ """P6.2 退场后,前端不再 spread work_mode;后端从 kwarg(session metadata)取。++ 模拟 ``resolve_request_mode(work_mode="work", params={"mode": "agent.work.plan"})``+ 调用方不传 params 里的 work_mode 字段,组合分支仍应触发。+ """+ resolved = resolve_request_mode(+ {"mode": NEW_AGENT_WORK_PLAN},+ resolve_agent_request_mode,+ work_mode="work",+ )++ assert resolved.from_web_composition is True+ assert resolved.canonical_mode == NEW_AGENT_WORK_PLAN+ assert resolved.work_mode == "work"+++def test_web_new_strings_without_work_mode_fall_to_legacy():+ """没带 work_mode(也无 kwarg)的新串仍按 legacy 处理。++ 前端 wireMode.ts 总会产出 work profile 的串,但若 session metadata 没存+ work_mode(极端边界),后端应落 legacy 不报错。新串落 legacy 也不能被折叠:+ 此处钉住 legacy 短路后仍解析出 agent.work.plan 而非 code.normal。+ """+ resolved = _resolve({"mode": NEW_AGENT_WORK_PLAN})++ assert resolved.from_web_composition is False+ assert (resolved.manager_mode, resolved.sub_mode, resolved.canonical_mode) == (+ "agent", "plan", NEW_AGENT_WORK_PLAN,+ )+ assert resolved.is_plan is True+++# ── P6.5:新三段命名 canonical 的完整解析(TUI 直发,不经 Web 组合)───────────+++ ("mode", "expected"),+ [+ (NEW_AGENT_WORK_NORMAL, ("agent", None, NEW_AGENT_WORK_NORMAL)),+ (NEW_AGENT_WORK_PLAN, ("agent", "plan", NEW_AGENT_WORK_PLAN)),+ (NEW_AGENT_CODE_NORMAL, ("code", "normal", NEW_AGENT_CODE_NORMAL)),+ (NEW_AGENT_CODE_PLAN, ("code", "plan", NEW_AGENT_CODE_PLAN)),+ (NEW_TEAM_WORK_NORMAL, ("team", None, NEW_TEAM_WORK_NORMAL)),+ (NEW_TEAM_WORK_PLAN, ("team", "plan", NEW_TEAM_WORK_PLAN)),+ (NEW_TEAM_CODE_NORMAL, ("code", "team", NEW_TEAM_CODE_NORMAL)),+ (NEW_TEAM_CODE_PLAN, ("code", "team", NEW_TEAM_CODE_PLAN)),+ ],+)+def test_new_canonical_resolves_self_describing(mode, expected):+ """P6.5:8 个新 canonical 按串自身语义解析,不依赖 work_mode。++ 铁律:environment/state 段内嵌在串里,manager/sub 三元组与 Web 组合分支+ 产出的结果一一对应,绝不回退到 legacy 归并。+ """+ resolved = _resolve({"mode": mode})++ assert (resolved.manager_mode, resolved.sub_mode, resolved.canonical_mode) == expected+ assert resolved.from_web_composition is False+++ ("mode", "work_mode", "expected"),+ [+ (NEW_AGENT_WORK_PLAN, "code", ("agent", "plan", NEW_AGENT_WORK_PLAN)),+ (NEW_AGENT_WORK_NORMAL, "code", ("agent", None, NEW_AGENT_WORK_NORMAL)),+ (NEW_AGENT_CODE_PLAN, "work", ("code", "plan", NEW_AGENT_CODE_PLAN)),+ (NEW_AGENT_CODE_NORMAL, "work", ("code", "normal", NEW_AGENT_CODE_NORMAL)),+ (NEW_TEAM_WORK_PLAN, "code", ("team", "plan", NEW_TEAM_WORK_PLAN)),+ (NEW_TEAM_CODE_PLAN, "work", ("code", "team", NEW_TEAM_CODE_PLAN)),+ ],+)+def test_new_canonical_ignores_supplemented_work_mode(mode, work_mode, expected):+ """P6.5 回归:TUI 会话被补上 work_mode="code" 时不得覆盖新 canonical。++ 这就是本 bug 的复现路径:TUI 发送 ``agent.work.plan``,``_prepare_code_mode_chat_turn``+ 从 session metadata 补 work_mode="code",修复前 legacy 把 ``agent.work.plan``+ 折叠成 ``code.normal``,导致模型自述 code.normal 而 TUI 显示 agent.work.plan。+ 新 canonical 必须按串自身语义解析,忽略补充的 work_mode。+ """+ resolved = resolve_request_mode(+ {"mode": mode},+ resolve_agent_request_mode,+ work_mode=work_mode,+ )++ assert (resolved.manager_mode, resolved.sub_mode, resolved.canonical_mode) == expected+ assert resolved.canonical_mode != "code.normal"+ assert resolved.from_web_composition is False+++# ── TUI / CLI / cron:不带 work_mode 时必须完全走历史解析 ───────────────────+++ ("raw_mode", "expected"),+ [+ ("agent", ("agent", None, "agent")),+ ("agent.plan", ("agent", "plan", "agent.plan")),+ ("agent.fast", ("agent", None, "agent")),+ ("plan", ("agent", None, "agent")),+ ("code.normal", ("code", "normal", "code.normal")),+ ("code.plan", ("code", "plan", "code.plan")),+ ("code.team", ("code", "team", "code.team")),+ ("team.code", ("code", "team", "code.team")),+ ("team", ("team", None, "team")),+ ("team.plan", ("team", "plan", "team.plan.normal")),+ ("team.plan.normal", ("team", "plan", "team.plan.normal")),+ ("team.plan.code", ("code", "team", "team.plan.code")),+ ],+)+def test_legacy_modes_are_untouched_without_work_mode(raw_mode, expected):+ resolved = _resolve({"mode": raw_mode})++ assert (resolved.manager_mode, resolved.sub_mode, resolved.canonical_mode) == expected+ assert resolved.from_web_composition is False+++ "raw_mode", ["code.plan", "code.team", "team.plan.normal", "team.plan.code", "agent.fast"]+)+def test_legacy_full_modes_ignore_work_mode(raw_mode):+ """即便某个客户端同时带了 work_mode,完整模式串仍按历史语义解析。++ ``code.normal`` 不在此列:它是 ``resolve_agent_request_mode`` 早就会按+ ``work_mode`` 改写的"可归属"模式,见+ :func:`test_legacy_neutral_modes_still_follow_work_mode`。+ """+ with_work = _resolve({"mode": raw_mode, "work_mode": "work"})+ without_work = _resolve({"mode": raw_mode})++ assert with_work.canonical_mode == without_work.canonical_mode+ assert with_work.manager_mode == without_work.manager_mode+ assert with_work.from_web_composition is False+++ ("raw_mode", "work_mode", "expected"),+ [+ ("code.normal", "work", ("agent", None, "agent")),+ ("code.normal", "code", ("code", "normal", "code.normal")),+ ("code", "work", ("agent", None, "agent")),+ ("agent", "code", ("code", "normal", "code.normal")),+ ],+)+def test_legacy_neutral_modes_still_follow_work_mode(raw_mode, work_mode, expected):+ """``agent`` / ``code`` / ``code.normal`` 由 work_mode 决定归属(历史行为)。++ 这三个取值只表达"普通单 agent",不表达工作环境,因此 ``resolve_agent_request_mode``+ 在 Web 组合模式引入之前就会用 ``work_mode``(通常来自会话 metadata)改写它们。+ 组合分支不接管这些请求(``code.normal`` 等不是 Web 组合值,``agent`` 则由+ 组合分支给出同样的结果),此处把这条历史约定钉住。+ """+ resolved = _resolve({"mode": raw_mode, "work_mode": work_mode})++ assert (resolved.manager_mode, resolved.sub_mode, resolved.canonical_mode) == expected+++def test_invalid_work_mode_falls_back_to_legacy():+ resolved = _resolve({"mode": "agent.plan", "work_mode": "nonsense"})++ # 非法 work_mode 退历史解析:agent.plan 按真实 plan 模式落 legacy canonical。+ assert resolved.from_web_composition is False+ assert (resolved.manager_mode, resolved.sub_mode, resolved.canonical_mode) == (+ "agent", "plan", "agent.plan",+ )+ assert resolved.is_plan is True+++def test_missing_mode_defaults_to_agent():+ assert _resolve({}).canonical_mode == "agent"+++# ── 纯函数 ──────────────────────────────────────────────────────────────────+++ ("mode", "expected"),+ [+ ("agent.plan", True),+ ("code.plan", True),+ ("team.plan", True),+ ("team.plan.normal", True),+ ("team.plan.code", True),+ ("agent", False),+ ("team", False),+ ("code.normal", False),+ ("code.team", False),+ ],+)+def test_is_plan_mode(mode, expected):+ assert is_plan_mode(mode) is expected+++ ("mode", "expected"),+ [+ ("team", True),+ ("team.plan", True),+ ("team.plan.normal", True),+ ("team.plan.code", True),+ ("code.team", True),+ ("agent", False),+ ("agent.plan", False),+ ("code.plan", False),+ ],+)+def test_is_team_mode(mode, expected):+ assert is_team_mode(mode) is expected+++ "mode",+ [+ NEW_AGENT_WORK_NORMAL,+ NEW_AGENT_WORK_PLAN,+ NEW_AGENT_CODE_NORMAL,+ NEW_AGENT_CODE_PLAN,+ ],+)+def test_single_agent_modes_use_new_canonical_names(mode):+ assert is_single_agent_mode(mode)+++ "mode",+ ["agent", "agent.fast", "agent.plan", "code", "code.normal", "code.plan"],+)+def test_single_agent_mode_rejects_legacy_names(mode):+ assert not is_single_agent_mode(mode)+++ "mode",+ [NEW_TEAM_WORK_NORMAL, NEW_TEAM_WORK_PLAN, NEW_TEAM_CODE_NORMAL, NEW_TEAM_CODE_PLAN],+)+def test_single_agent_mode_rejects_new_team_canonical_names(mode):+ assert not is_single_agent_mode(mode)+++def test_base_mode_without_plan_is_identity_for_normal_modes():+ assert base_mode_without_plan("agent") == "agent"+ assert base_mode_without_plan("code.team") == "code.team"+++def test_unknown_mode_passes_through():+ """铁律 3:未知值 / None / 空串原样返回,不破坏未识别输入。++ ``deprecate_mode("") == ""`` 不变式(review 修复前空串被 normalize 成+ ``agent`` 再映射为 ``agent.work.normal``,违反 PLAN 文档契约)。+ ``deprecate_mode(None) is None`` 不变式(review 修复前 None 走兜底+ 返回 ``agent.work.normal``,与 docstring 契约不符)。+ """+ assert deprecate_mode("unknown_mode") == "unknown_mode"+ assert deprecate_mode("") == ""+ assert deprecate_mode(" ") == " "+ assert deprecate_mode(None) is None+++def test_deprecate_mode_hits_legacy_canonicals():+ """DEPRECATION_MAP 命中路径:旧 canonical(字符串与枚举入参)映射到新 canonical。++ 与 :func:`test_unknown_mode_passes_through` 互补——那边钉 unknown / 空值+ 原样返回,这边钉已知旧串必须命中映射表。+ """+ assert deprecate_mode("agent.plan") == NEW_AGENT_WORK_PLAN+ assert deprecate_mode("code.plan") == NEW_AGENT_CODE_PLAN+ assert deprecate_mode("team") == NEW_TEAM_WORK_NORMAL+ # team.plan → team.plan.normal → team.work.plan(MODE_ALIASES + DEPRECATION_MAP 两步)+ assert deprecate_mode("team.plan") == NEW_TEAM_WORK_PLAN+ # 枚举入参同样走映射(先取 .value 再查表)+ assert deprecate_mode(Mode.AGENT_PLAN) == NEW_AGENT_WORK_PLAN+ assert deprecate_mode(Mode.AGENT_FAST) == NEW_AGENT_WORK_NORMAL+++ "mode", ["team", "team.plan", "team.plan.normal", "team.plan.code", "code.team"]+)+def test_team_modes_are_team_params(mode):+ from jiuwenswarm.server.utils.utils import is_team_params++ assert is_team_params({"mode": mode})diff --git a/tests/unit_tests/test_session_context_message_origin.py b/tests/unit_tests/test_session_context_message_origin.pynew file mode 100644index 0000000000..357c16471d--- /dev/null+++ b/tests/unit_tests/test_session_context_message_origin.py@@ -0,0 +1,30 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""Tests for provenance on messages restored from product Session history."""++from openjiuwen.core.foundation.llm.schema.message import (+ OPENJIUWEN_MESSAGE_ORIGIN_EXTERNAL_USER,+ OPENJIUWEN_MESSAGE_ORIGIN_METADATA,+ OPENJIUWEN_MESSAGE_SOURCE_KIND_METADATA,+ UserMessage,+)++from jiuwenswarm.agents.harness.common.session_ops_service import (+ _build_context_messages_from_history,+)+++def test_restored_product_session_users_remain_external_inputs() -> None:+ messages, skipped = _build_context_messages_from_history([{+ "role": "user",+ "content": "original browser input",+ "channel_id": "web",+ }])++ assert skipped == 0+ assert len(messages) == 1+ assert isinstance(messages[0], UserMessage)+ assert messages[0].metadata[OPENJIUWEN_MESSAGE_ORIGIN_METADATA] == (+ OPENJIUWEN_MESSAGE_ORIGIN_EXTERNAL_USER+ )+ assert messages[0].metadata[OPENJIUWEN_MESSAGE_SOURCE_KIND_METADATA] == "web"diff --git a/tests/unit_tests/test_session_metadata.py b/tests/unit_tests/test_session_metadata.pyindex f441f0b01a..a263acb14a 100644--- a/tests/unit_tests/test_session_metadata.py+++ b/tests/unit_tests/test_session_metadata.py@@ -2097,6 +2097,68 @@ class TestLazyMigrationOnRead:assert data["status"] == "idle"assert "last_user_message_at" in data+ @staticmethod+ def test_repairs_subagent_mode_leaked_into_web_parent(sessions_dir):+ from jiuwenswarm.server.runtime.session.session_metadata import (+ _METADATA_CACHE,+ get_session_metadata,+ )++ session_dir = sessions_dir / "web_parent"+ session_dir.mkdir()+ (session_dir / "metadata.json").write_text(+ json.dumps(+ {+ "session_id": "web_parent",+ "channel_id": "web",+ "mode": "subagent",+ "team_name": "",+ "work_mode": "work",+ }+ ),+ encoding="utf-8",+ )+ _METADATA_CACHE.pop("web_parent", None)++ metadata = get_session_metadata(+ "web_parent",+ cache_bust=True,+ enable_writeback=False,+ )++ assert metadata["mode"] == "agent.work.normal"++ @staticmethod+ def test_keeps_standalone_subagent_channel_mode(sessions_dir):+ from jiuwenswarm.server.runtime.session.session_metadata import (+ _METADATA_CACHE,+ get_session_metadata,+ )++ session_dir = sessions_dir / "subagent_session"+ session_dir.mkdir()+ (session_dir / "metadata.json").write_text(+ json.dumps(+ {+ "session_id": "subagent_session",+ "channel_id": "subagent",+ "mode": "subagent",+ "team_name": "",+ "work_mode": "work",+ }+ ),+ encoding="utf-8",+ )+ _METADATA_CACHE.pop("subagent_session", None)++ metadata = get_session_metadata(+ "subagent_session",+ cache_bust=True,+ enable_writeback=False,+ )++ assert metadata["mode"] == "subagent"+@staticmethoddef test_last_user_message_at_uses_last_message_at_when_present(sessions_dir):"""有 last_message_at 时优先用它,不被 or 短路跳过 0.0。"""