diff --git a/apps/presentation/dashboard/src/data/status.ts b/apps/presentation/dashboard/src/data/status.ts index 50ea5d5728..72d8d1e663 100644 --- a/apps/presentation/dashboard/src/data/status.ts +++ b/apps/presentation/dashboard/src/data/status.ts @@ -537,6 +537,7 @@ export const runRecordSchema = z.object({ generated_at: z.string(), goal_id: z.string(), turn_instance_id: z.string().nullish().catch(null), + execution_ref: z.string().regex(/^[a-f0-9]{64}$/).optional().catch(undefined), agent_vision: z.record(z.string(), z.unknown()).nullish().catch(null), vision_checkpoint: z.object({ schema_version: z.literal("vision_checkpoint_v0"), diff --git a/apps/presentation/dashboard/src/features/personal-workspace/context-drawer.tsx b/apps/presentation/dashboard/src/features/personal-workspace/context-drawer.tsx index 7acf13899a..b044cea6ac 100644 --- a/apps/presentation/dashboard/src/features/personal-workspace/context-drawer.tsx +++ b/apps/presentation/dashboard/src/features/personal-workspace/context-drawer.tsx @@ -52,6 +52,7 @@ import { parseTodoResumeCondition, todoResumeTransition } from "./todo-resume-co import { MarkdownText } from "./markdown"; import { formatMonitorDate } from "./monitor-readback"; import { parseTodoCompletionProof } from "./todo-completion-feedback"; +import { SourceRunHistory } from "./source-run-history"; import { useDrawerOverlay } from "./workspace-shell"; import { deriveGoalWorkerRoster, @@ -96,45 +97,6 @@ function runRosterState(run: WorkspaceRun): WorkerRosterState { return "waiting"; } -import { GoalStrategyDocument } from "./goal-source-strategies"; - -function SourceRunHistory({ goal, heading = false }: { goal: WorkspaceGoal; heading?: boolean }) { - const { t, locale } = useWorkspaceI18n(); - const history = goal.sourceRunHistory; - const recent = history?.recent ?? []; - const total = history?.total ?? null; - return
- {heading ?

{t("drawer.sourceRunHistory")}

: null} - {goal.sourceAccess?.label} · {t("common.readOnly")} -
-
{t("drawer.sourceRunOriginalGoal")}
{goal.sourceAccess?.original_goal_id ?? goal.goalId}
-
- {recent.length ? <> -

{total === null ? t("drawer.sourceRunRecent", {shown: recent.length}) - : t("drawer.sourceRunCount", {shown: recent.length, count: total})}

-
    {recent.map((run, index) =>
  1. -
    - -
    - {run.classification ?
    {t("drawer.sourceRunRecordType")}
    {run.classification}
    : null} -
    {t("drawer.sourceRunOriginalTurn")}
    - {run.turn_instance_id ? {run.turn_instance_id} : t("drawer.sourceRunUnrecorded")} -
    -
    {t("drawer.sourceRunCheckpoint")}
    - {run.vision_checkpoint ? {run.vision_checkpoint.decision} : t("drawer.sourceRunUnrecorded")} -
    -
    - {run.agent_vision ? - :

    {t("drawer.sourceRunDecisionUnavailable")}

    } -
    -
  2. )}
- :

{t(total === 0 ? "drawer.noExecutionHistory" : "drawer.sourceRunUnavailable")}

} -
; -} - function subagentModelRequest(include: boolean, model: string, effort: string) { if (!include) return {}; if (!model.trim()) return { modelConfig: null }; diff --git a/apps/presentation/dashboard/src/features/personal-workspace/goal-source-strategies.tsx b/apps/presentation/dashboard/src/features/personal-workspace/goal-source-strategies.tsx index 9c338977bb..e9ece3083a 100644 --- a/apps/presentation/dashboard/src/features/personal-workspace/goal-source-strategies.tsx +++ b/apps/presentation/dashboard/src/features/personal-workspace/goal-source-strategies.tsx @@ -203,7 +203,9 @@ export function GoalStrategyDocument({value, recordedAt, agentId, version, origi {Object.keys(additional).length ?
{zh ? "其他决策字段" : "Additional decision fields"}
: null} -
{zh ? "完整原始记录与来源" : "Complete original record and source"} +
{executionRecord + ? (zh ? "执行记录详情与来源" : "Execution record details and source") + : (zh ? "完整原始记录与来源" : "Complete original record and source")}
{JSON.stringify(originalRecord ?? value, null, 2)}
diff --git a/apps/presentation/dashboard/src/features/personal-workspace/i18n.tsx b/apps/presentation/dashboard/src/features/personal-workspace/i18n.tsx index 40243d271b..d4b6fb68f8 100644 --- a/apps/presentation/dashboard/src/features/personal-workspace/i18n.tsx +++ b/apps/presentation/dashboard/src/features/personal-workspace/i18n.tsx @@ -394,6 +394,10 @@ const en = { "drawer.sourceRunCheckpoint": "Strategy checkpoint", "drawer.sourceRunUnrecorded": "Unrecorded", "drawer.sourceRunUnavailable": "Historical execution records are unavailable.", + "drawer.sourceRunLoading": "Reading the source execution…", + "drawer.sourceRunReadFailed": "The source record is unavailable. The index summary is shown below.", + "drawer.sourceRunRetry": "Retry reading the source", + "drawer.sourceRunOutcome": "Delivery outcome", "drawer.noRun": "Execution Session has not started", "drawer.noRunDescription": "Run records will appear here after an Agent starts execution.", "drawer.notAssigned": "Unassigned", @@ -2036,6 +2040,10 @@ const zhCN: Record = { "drawer.sourceRunCheckpoint": "策略检查点", "drawer.sourceRunUnrecorded": "未记录", "drawer.sourceRunUnavailable": "原始执行记录暂不可读。", + "drawer.sourceRunLoading": "正在读取原始执行记录…", + "drawer.sourceRunReadFailed": "原始执行记录暂不可读。下面显示索引摘要。", + "drawer.sourceRunRetry": "重试读取原件", + "drawer.sourceRunOutcome": "交付结果", "drawer.noRun": "尚未启动执行 Session", "drawer.noRunDescription": "Agent 开始执行后,运行记录会稳定显示在这里。", "drawer.notAssigned": "未分配", diff --git a/apps/presentation/dashboard/src/features/personal-workspace/personal-workspace-model.ts b/apps/presentation/dashboard/src/features/personal-workspace/personal-workspace-model.ts index 21e248b2c9..0d027bb271 100644 --- a/apps/presentation/dashboard/src/features/personal-workspace/personal-workspace-model.ts +++ b/apps/presentation/dashboard/src/features/personal-workspace/personal-workspace-model.ts @@ -168,7 +168,7 @@ export type WorkspaceGoal = { sourceAccess?: {namespace: string; label: string; readOnly: true; original_goal_id?: string}; sourceRunHistory?: { total: number | null; - recent: Pick[]; + recent: Pick[]; }; sourceStrategy?: {recordedAt: string; summary: string; observation?: string}; /** Registry organization in this status source; not Agent ownership or execution dependency. */ diff --git a/apps/presentation/dashboard/src/features/personal-workspace/source-run-history.tsx b/apps/presentation/dashboard/src/features/personal-workspace/source-run-history.tsx new file mode 100644 index 0000000000..16e3f9f3b1 --- /dev/null +++ b/apps/presentation/dashboard/src/features/personal-workspace/source-run-history.tsx @@ -0,0 +1,106 @@ +import {useEffect, useState} from "react"; +import {z} from "zod"; +import {requestJson} from "../../data/chat"; +import {GoalStrategyDocument} from "./goal-source-strategies"; +import {useWorkspaceI18n} from "./i18n"; +import type {WorkspaceGoal} from "./personal-workspace-model"; + +type Run = NonNullable["recent"][number]; +const digest = z.string().regex(/^[a-f0-9]{64}$/); +const executionResponse = z.object({ + ok: z.literal(true), + goal_id: z.string(), + source: z.object({namespace: digest}), + execution_ref: digest, + sha256: digest, + record: z.object({ + goal_id: z.string(), + generated_at: z.string(), + agent_id: z.string().nullish(), + classification: z.string().nullish(), + turn_instance_id: z.string().nullish(), + agent_vision: z.record(z.string(), z.unknown()).nullish(), + vision_checkpoint: z.object({decision: z.string().optional()}).passthrough().nullish(), + delivery_outcome: z.string().nullish(), + }).passthrough(), +}); +type Execution = z.infer; + +function SourceRun({goal, run}: {goal: WorkspaceGoal; run: Run}) { + const {t, locale} = useWorkspaceI18n(); + const [expanded, setExpanded] = useState(false); + const [retry, setRetry] = useState(0); + const [result, setResult] = useState(null); + const {goalId} = goal; + const namespace = goal.sourceAccess?.namespace; + const originalGoal = goal.sourceAccess?.original_goal_id ?? goalId; + const ref = run.execution_ref; + const generatedAt = run.generated_at; + + useEffect(() => { + if (!expanded || !ref || !namespace) return; + const controller = new AbortController(); + setResult(null); + const query = new URLSearchParams({ + goal_id: goalId, source_namespace: namespace, execution_ref: ref, generated_at: generatedAt, + }); + void requestJson(`/api/chat/goal-source-execution?${query}`, {signal: controller.signal}) + .then(payload => { + const detail = executionResponse.parse(payload); + if (detail.goal_id !== originalGoal || detail.record.goal_id !== originalGoal + || detail.source.namespace !== namespace || detail.execution_ref !== ref + || detail.record.generated_at !== generatedAt) { + throw new Error("Inconsistent execution source"); + } + if (!controller.signal.aborted) setResult(detail); + }) + .catch(() => {if (!controller.signal.aborted) setResult("unavailable");}); + return () => controller.abort(); + }, [expanded, ref, generatedAt, namespace, originalGoal, goalId, retry]); + + const execution = result && result !== "unavailable" ? result : null; + const record = execution?.record ?? run; + const loading = Boolean(expanded && ref && namespace && result === null); + return
setExpanded(event.currentTarget.open)}> + + {loading ?

{t("drawer.sourceRunLoading")}

: null} + {result === "unavailable" ?
+

{t("drawer.sourceRunReadFailed")}

+ +
: null} +
+ {record.classification ?
{t("drawer.sourceRunRecordType")}
{record.classification}
: null} +
{t("drawer.sourceRunOriginalTurn")}
+ {record.turn_instance_id ? {record.turn_instance_id} : t("drawer.sourceRunUnrecorded")} +
+
{t("drawer.sourceRunCheckpoint")}
+ {record.vision_checkpoint?.decision ? {record.vision_checkpoint.decision} : t("drawer.sourceRunUnrecorded")} +
+ {execution?.record.delivery_outcome ?
{t("drawer.sourceRunOutcome")}
+
{execution.record.delivery_outcome}
: null} +
+ {record.agent_vision || execution ? + : !loading ?

{t("drawer.sourceRunDecisionUnavailable")}

: null} +
; +} + +export function SourceRunHistory({goal, heading = false}: {goal: WorkspaceGoal; heading?: boolean}) { + const {t} = useWorkspaceI18n(); + const recent = goal.sourceRunHistory?.recent ?? []; + const total = goal.sourceRunHistory?.total ?? null; + return
+ {heading ?

{t("drawer.sourceRunHistory")}

: null} + {goal.sourceAccess?.label} · {t("common.readOnly")} +
{t("drawer.sourceRunOriginalGoal")}
{goal.sourceAccess?.original_goal_id ?? goal.goalId}
+ {recent.length ? <> +

{total === null ? t("drawer.sourceRunRecent", {shown: recent.length}) + : t("drawer.sourceRunCount", {shown: recent.length, count: total})}

+
    {recent.map((run, index) =>
  1. + +
  2. )}
+ :

{t(total === 0 ? "drawer.noExecutionHistory" : "drawer.sourceRunUnavailable")}

} +
; +} diff --git a/loopx/chat_server.py b/loopx/chat_server.py index 4c16ae2043..3b44d23488 100644 --- a/loopx/chat_server.py +++ b/loopx/chat_server.py @@ -106,7 +106,10 @@ from .chat.completed_todos import CompletedTodoPages, CompletedTodoRequestMixin from .presentation.explore_results_api import ExploreResultsRequestMixin from .presentation.research_analysis_api import RESEARCH_ANALYSIS_PATH, ResearchAnalysisRequestMixin -from .presentation.goal_source_routing import GOAL_SOURCE_LINKS_PATH, GOAL_SOURCE_STRATEGIES_PATH, GOAL_SOURCE_DOCUMENT_PATH, GoalSourceRequestMixin +from .presentation.goal_source_routing import ( + GOAL_SOURCE_DOCUMENT_PATH, GOAL_SOURCE_EXECUTION_PATH, GOAL_SOURCE_LINKS_PATH, + GOAL_SOURCE_STRATEGIES_PATH, GoalSourceRequestMixin, +) from .chat.todo_detail import TodoDetailRequestMixin from .kiro_cli_goal_mode import KIRO_CLI_BIN from .paths import resolve_runtime_root @@ -1455,6 +1458,7 @@ def do_GET(self) -> None: GOAL_SOURCE_LINKS_PATH: self._goal_source_links, GOAL_SOURCE_STRATEGIES_PATH: self._goal_source_strategies, GOAL_SOURCE_DOCUMENT_PATH: self._goal_source_document, + GOAL_SOURCE_EXECUTION_PATH: self._goal_source_execution, "/api/chat/todo/detail": self._todo_detail, "/api/chat/completed-todos": self._completed_todos, "/api/chat/explore-results": self._explore_results, diff --git a/loopx/control_plane/status/goal_source.py b/loopx/control_plane/status/goal_source.py index 25746ea128..fac5a3d9c8 100644 --- a/loopx/control_plane/status/goal_source.py +++ b/loopx/control_plane/status/goal_source.py @@ -10,6 +10,7 @@ import argparse from copy import deepcopy from dataclasses import asdict, dataclass +from datetime import datetime, timedelta from hashlib import sha256 import json import os @@ -24,6 +25,8 @@ from urllib.request import HTTPRedirectHandler, Request, build_opener from ..content_digest import BARE_SHA256_PATTERN +from ..quota.ledger_readback import _copied_goal_run_file_name +from ..runtime.time import parse_timestamp from ...chat.completed_todos import CompletedTodoPages from ...status_server import is_loopback_host from .ssh_host_catalog import configured_ssh_host_aliases @@ -53,6 +56,34 @@ if len(data) > 128 * 1024: raise ValueError('document too large') print(json.dumps({'text': data.decode('utf-8')})) """ +_READ_EXECUTION = """ +import os, pathlib, stat, sys +root = pathlib.Path(sys.argv[1]).resolve(strict=True) +runs = root / 'goals' / sys.argv[2] / 'runs' +name = sys.argv[3] +if pathlib.Path(name).name != name or runs.resolve(strict=True) != runs: + raise ValueError('invalid archive location') +path = runs / name +before = path.lstat() +if not stat.S_ISREG(before.st_mode): + raise ValueError('execution artifact must be a regular file') +flags = os.O_RDONLY | getattr(os, 'O_NOFOLLOW', 0) | getattr(os, 'O_NONBLOCK', 0) +with os.fdopen(os.open(path, flags), 'rb') as stream: + opened = os.fstat(stream.fileno()) + if not stat.S_ISREG(opened.st_mode) or (opened.st_dev, opened.st_ino) != (before.st_dev, before.st_ino): + raise ValueError('execution artifact changed before it was opened') + limit = int(sys.argv[4]) + data = stream.read(limit + 1) + after = os.fstat(stream.fileno()) + if len(data) > limit or (opened.st_size, opened.st_mtime_ns) != (after.st_size, after.st_mtime_ns): + raise ValueError('execution artifact is too large or changed while reading') +sys.stdout.buffer.write(data) +""" +_RUN_IDENTITY = ("goal_id", "generated_at", "agent_id", "classification", "turn_instance_id") +_RUN_DETAIL_FIELDS = ( + *_RUN_IDENTITY, "todo_id", "agent_vision", "vision_checkpoint", + "delivery_outcome", "delivery_batch_scale", "delivery_boundary", +) class SourceScopeError(ValueError): @@ -78,6 +109,16 @@ def _run(argv, *, env=None): return result.stdout.decode("utf-8") +def _source_execution_ref(namespace, goal_id, run): + if (not isinstance(run, dict) or run.get("goal_id") != goal_id + or not isinstance(run.get("generated_at"), str) or not run["generated_at"]): + return None + # The normal status projection drops file paths. Match the same stable + # identity against the native history window and reject ambiguous matches. + identity = [namespace, *(run.get(field) for field in _RUN_IDENTITY)] + return sha256(json.dumps(identity, separators=(",", ":")).encode()).hexdigest() + + @dataclass(frozen=True) class GoalDocumentSnapshot: declared_path: str @@ -274,15 +315,37 @@ def read_registry_goal(self, goal_id): ] if isinstance(goal.get("authority_sources"), list) else None} for goal in payload["goals"] if isinstance(goal, dict) and goal.get("id") == selected]} - def read_run_history(self, goal_id): + def read_run_history(self, goal_id, *, window: tuple[datetime, datetime] | None = None): self.check_access(goal_id) - # Native history owns index reduction. Its returned coverage is checked - # by the TS projection; the existing byte/time limits fail explicitly. - return json.loads(self._execute([ + # Native history owns index reduction and applies the time window before + # its display limit. Whole-history callers retain their existing query. + args = [ self.cli, "--format", "json", "--registry", self.registry, "--runtime-root", self.runtime_root, "history", "--goal-id", goal_id, "--limit", "1000000", - ])) + ] + if window is not None: + start, end = (stamp.isoformat() for stamp in window) + args.extend(["--since", start, "--until", end]) + return json.loads(self._execute(args)) + + def read_execution(self, goal_id, indexed_run): + self.check_access(goal_id) + recorded_path = indexed_run.get("json_path") + name = _copied_goal_run_file_name(recorded_path, goal_id, ".json") if isinstance(recorded_path, str) else None + if name is None: + raise SourceScopeError("The execution artifact is outside the original Goal") + raw = self._execute([self.python, "-c", _READ_EXECUTION, self.runtime_root, goal_id, + name, str(_MAX_BYTES)]) + record = json.loads(raw) + if not isinstance(record, dict) or any( + record.get(field) != indexed_run.get(field) for field in _RUN_IDENTITY + ): + raise SourceScopeError("The execution artifact differs from the indexed record") + return { + "sha256": sha256(raw.encode()).hexdigest(), + "record": {key: record[key] for key in _RUN_DETAIL_FIELDS if key in record}, + } def read_completed_todos(self, goal_id): self.check_access(goal_id) @@ -411,6 +474,40 @@ def strategies(self, goal_id): self.registered_status(goal_id, fresh=True) return {"ok": True, "goal_id": goal_id, "source": self.source.describe(), **projected} + def execution(self, goal_id, execution_ref, generated_at): + if not BARE_SHA256_PATTERN.fullmatch(execution_ref) or len(generated_at) > 128: + raise SourceScopeError("Choose one recorded source execution") + start = parse_timestamp(generated_at) + if start is None: + raise SourceScopeError("Choose one recorded source execution") + try: + end = start + timedelta(microseconds=1) + except OverflowError as exc: + raise SourceScopeError("The recorded execution timestamp is outside the history range") from exc + self.registered_status(goal_id, fresh=True) + source = self.source + # The timestamp narrows the lookup. The ref still binds the exact + # source, Goal, original timestamp text and execution identity. + history = source.read_run_history(goal_id, window=(start, end)) + native, = history["goals"] + if (history.get("ok") is not True or history.get("goal_filter") != goal_id + or native.get("id") != goal_id or native.get("registry_member") is not True): + raise SourceScopeError("The original Goal is no longer registered") + candidates = native["latest_runs"] + filter_used = history["time_filter"] + if (filter_used["since_inclusive"] != start.isoformat() + or filter_used["until_exclusive"] != end.isoformat() + or native["unique_runs"] != len(candidates)): + raise ValueError("Incomplete native execution history window") + matches = [run for run in candidates if run.get("generated_at") == generated_at + and _source_execution_ref(source.namespace, goal_id, run) == execution_ref] + if len(matches) != 1: + raise SourceScopeError("The selected execution is unavailable in the original source") + detail = source.read_execution(goal_id, matches[0]) + self.registered_status(goal_id, fresh=True) + return {"ok": True, "goal_id": goal_id, "source": source.describe(), + "execution_ref": execution_ref, **detail} + def document(self, goal_id): from ..effect_runtime import effect_runtime_result @@ -520,6 +617,10 @@ def status(self, goal_id, registry=None): if goal["id"] == original_goal_id and goal.get("registry_member") is True), None) if source_goal is None: raise SourceScopeError("The original Goal is no longer registered") + for run in source_goal.get("latest_runs", []): + ref = _source_execution_ref(reader.source.namespace, original_goal_id, run) + if ref is not None: + run["execution_ref"] = ref from ..effect_runtime import effect_runtime_result return effect_runtime_result("presentation.goal_sources.status", {"status": status, "row": row}) diff --git a/loopx/presentation/goal_source_routing.py b/loopx/presentation/goal_source_routing.py index 4889efed82..8bb18390b2 100644 --- a/loopx/presentation/goal_source_routing.py +++ b/loopx/presentation/goal_source_routing.py @@ -7,6 +7,7 @@ GOAL_SOURCE_LINKS_PATH = "/api/chat/goal-sources" GOAL_SOURCE_STRATEGIES_PATH = "/api/chat/goal-source-strategies" GOAL_SOURCE_DOCUMENT_PATH = "/api/chat/goal-source-document" +GOAL_SOURCE_EXECUTION_PATH = "/api/chat/goal-source-execution" def goal_source_catalog(server): @@ -37,14 +38,20 @@ def _goal_source_strategies(self): def _goal_source_document(self): return self._goal_source_read("document") + def _goal_source_execution(self): + return self._goal_source_read("execution") + def _goal_source_read(self, operation): import subprocess from urllib.parse import parse_qs, urlparse + from ..control_plane.status.goal_source import SourceScopeError if not self._require_loopback_origin(): return query = parse_qs(urlparse(self.path).query, keep_blank_values=True) - if (set(query) != {"goal_id", "source_namespace"} + execution_fields = ("execution_ref", "generated_at") if operation == "execution" else () + fields = {"goal_id", "source_namespace", *execution_fields} + if (set(query) != fields or any(len(values) != 1 for values in query.values())): self._send_error("Choose one original Goal and source.", status=400) return @@ -58,16 +65,24 @@ def _goal_source_read(self, operation): self._send_error("Source identity changed; refresh the Goal.", status=409) return try: - result = getattr(reader, operation)(reader.source.goal_id) + parameters = [query[field][0] for field in execution_fields] + result = getattr(reader, operation)(reader.source.goal_id, *parameters) latest = linked_goal_source(self.server, goal_id) if (latest is None or latest[1].source.namespace != reader.source.namespace - or (operation == "document" and latest[1].source != reader.source)): + or (operation != "strategies" and latest[1].source != reader.source)): self._send_error("Source identity changed; refresh the Goal.", status=409) return self._send_json(result) - except (ValueError, TypeError, KeyError, OSError, RuntimeError, subprocess.SubprocessError): - self._send_error("The original strategy history is unavailable; retry after reconnecting." - if operation == "strategies" else "The original task document is unavailable; check its source binding and retry.", status=503) + except (ValueError, TypeError, KeyError, OSError, RuntimeError, subprocess.SubprocessError) as exc: + if operation == "execution" and isinstance(exc, SourceScopeError): + self._send_error("The selected execution or its source changed; refresh the Goal.", status=409) + return + unavailable = { + "strategies": "The original strategy history is unavailable; retry after reconnecting.", + "document": "The original task document is unavailable; check its source binding and retry.", + "execution": "The original execution is unavailable; check its source binding and retry.", + } + self._send_error(unavailable[operation], status=503) def _completed_todos(self): import subprocess diff --git a/tests/presentation/test_linked_goal_sources.py b/tests/presentation/test_linked_goal_sources.py index 0848c3b766..b70b4b972d 100644 --- a/tests/presentation/test_linked_goal_sources.py +++ b/tests/presentation/test_linked_goal_sources.py @@ -5,9 +5,11 @@ """ import copy from concurrent.futures import ThreadPoolExecutor +from datetime import datetime, timedelta import json import os from pathlib import Path +import subprocess import sys from threading import Event import time @@ -182,6 +184,123 @@ def test_strategy_history_reads_every_original_version_without_writing(workspace assert not list(Path(raw['runtime_root']).rglob('research-analysis')) +def test_execution_detail_reads_the_original_archive_only_in_its_source(workspace): + sources = [native_source(workspace), native_source(workspace, 'another-execution')] + cases = [] + for alias, (raw, request, protected) in zip(('archive-a', 'archive-b'), sources): + runs = Path(raw['runtime_root']) / 'goals' / 'solver-goal' / 'runs' + runs.mkdir(parents=True) + index = runs / 'index.jsonl' + stored = {'goal_id': 'solver-goal', 'agent_id': 'source-worker', + 'generated_at': '2026-01-02T10:00:00Z', 'classification': 'state_recorded', + 'turn_instance_id': 'original-turn', 'json_path': '/retired/goals/solver-goal/runs/execution.json'} + index.write_text(json.dumps(stored) + '\n') + protected[index] = index.read_bytes() + record = {**stored, 'agent_vision': {'validation': {'decision': alias}}, + 'vision_checkpoint': {'schema_version': 'vision_checkpoint_v0', 'decision': 'patched'}, + 'delivery_outcome': 'outcome_progress', 'raw_tool_log': 'only in the source'} + artifact = runs / 'execution.json' + artifact.write_bytes((json.dumps(record) + '\n').encode()) + protected[artifact] = artifact.read_bytes() + request('/api/chat/goal-sources', {'parent_goal_id': 'research-owner', 'source': raw, + 'workspace_goal_id': alias}) + namespace = GoalSource.parse(raw).namespace + (status,) = request('/status.json?' + urlencode({'goal_id': alias}))['run_history']['goals'] + (summary,) = status['latest_runs'] + assert summary['goal_id'] == alias and 'agent_vision' not in summary + params = {'goal_id': alias, 'source_namespace': namespace, 'execution_ref': summary['execution_ref'], + 'generated_at': summary['generated_at']} + cases.append((params, record, index, artifact, protected)) + + endpoint = '/api/chat/goal-source-execution?' + for (params, record, index, artifact, protected), (other, *_unused) in (cases, cases[::-1]): + url = endpoint + urlencode(params) + detail = request(url) + assert detail['goal_id'] == detail['record']['goal_id'] == 'solver-goal' + assert detail['execution_ref'] == params['execution_ref'] + assert detail['record']['agent_vision'] == record['agent_vision'] + assert detail['sha256'] == sha256(protected[artifact]).hexdigest() + assert 'raw_tool_log' not in detail['record'] and 'json_path' not in detail['record'] + for field in ('source_namespace', 'execution_ref'): + with pytest.raises(HTTPError) as rejected: + request(endpoint + urlencode({**params, field: other[field]})) + assert rejected.value.code == 409 + for timestamp in ('2026-01-02T10:00:00.000001Z', '2026-01-02T10:00:00+00:00'): + with pytest.raises(HTTPError) as wrong_timestamp: + request(endpoint + urlencode({**params, 'generated_at': timestamp})) + assert wrong_timestamp.value.code == 409 + + duplicate = json.loads(protected[index]) + duplicate['json_path'] = '/retired/goals/solver-goal/runs/duplicate.json' + index.write_bytes(protected[index] + (json.dumps(duplicate) + '\n').encode()) + with pytest.raises(HTTPError) as ambiguous: + request(url) + assert ambiguous.value.code == 409 + index.write_bytes(protected[index]) + + artifact.unlink() + with pytest.raises(HTTPError) as missing: + request(url) + assert missing.value.code == 503 + artifact.write_text(json.dumps({**record, 'turn_instance_id': 'different-turn'})) + with pytest.raises(HTTPError) as wrong_run: + request(url) + assert wrong_run.value.code == 409 + artifact.write_bytes(protected[artifact]) + assert request(url) == detail + assert all(path.read_bytes() == content for path, content in protected.items()) + + +def test_execution_detail_survives_a_large_native_history(workspace): + raw, request, protected = native_source(workspace) + runs = Path(raw['runtime_root']) / 'goals' / 'solver-goal' / 'runs' + runs.mkdir(parents=True) + index = runs / 'index.jsonl' + timestamp = datetime.fromisoformat('2026-01-02T10:00:00.123456+08:00') + original = { + 'goal_id': 'solver-goal', 'agent_id': 'source-worker', 'generated_at': timestamp.isoformat(), + 'classification': 'state_recorded', 'turn_instance_id': 'original-turn', + 'json_path': '/retired/goals/solver-goal/runs/execution.json', + } + artifact = runs / 'execution.json' + artifact.write_text(json.dumps(original) + '\n') + index.write_bytes(artifact.read_bytes()) + request('/api/chat/goal-sources', {'parent_goal_id': 'research-owner', 'source': raw, + 'workspace_goal_id': 'archive'}) + status = '/status.json?goal_id=archive' + (summary,) = request(status)['run_history']['goals'][0]['latest_runs'] + endpoint = '/api/chat/goal-source-execution?' + urlencode({ + 'goal_id': 'archive', 'source_namespace': GoalSource.parse(raw).namespace, + 'execution_ref': summary['execution_ref'], 'generated_at': summary['generated_at'], + }) + short_archive_detail = request(endpoint) + assert short_archive_detail['sha256'] == sha256(artifact.read_bytes()).hexdigest() + + # Newer runs move the selected row outside status's recent window. The + # unfiltered native response exceeds the linked source transport budget. + with index.open('a') as stream: + for position in range(1, 257): + item = { + **original, + 'generated_at': (timestamp + timedelta(minutes=position)).isoformat(), + 'turn_instance_id': f'later-turn-{position}', + 'json_path': f'/retired/goals/solver-goal/runs/later-{position}.json', + 'source_diagnostics': 'a' * (36 * 1024), + } + stream.write(json.dumps(item) + '\n') + full_history = subprocess.run([ + raw['cli'], '--format', 'json', '--registry', raw['registry'], + '--runtime-root', raw['runtime_root'], 'history', '--goal-id', 'solver-goal', + '--limit', '1000000', + ], capture_output=True, check=True, timeout=25) + assert len(full_history.stdout) > 16 * 1024 * 1024 + (fresh_goal,) = GoalSource.parse(raw).read_status('solver-goal')['run_history']['goals'] + assert all(row['turn_instance_id'] != original['turn_instance_id'] for row in fresh_goal['latest_runs']) + protected.update({index: index.read_bytes(), artifact: artifact.read_bytes()}) + assert request(endpoint) == short_archive_detail + assert all(path.read_bytes() == content for path, content in protected.items()) + + def test_strategy_history_rechecks_source_after_unlink_without_blocking_status(workspace, monkeypatch): from threading import Event