diff --git a/.github/workflows/bundled-extension-tests.yml b/.github/workflows/bundled-extension-tests.yml index fd980a8fb6..75f3e5c7a3 100644 --- a/.github/workflows/bundled-extension-tests.yml +++ b/.github/workflows/bundled-extension-tests.yml @@ -35,6 +35,7 @@ on: - 'backend/tests/test_lightrag_relations_extension.py' - 'backend/tests/test_report_sections_extension.py' - 'backend/tests/test_retrieval_plugin_artifacts.py' + - 'backend/tests/test_run_postmortem_extension.py' - 'backend/tests/test_weknora_extension.py' - 'backend/tests/test_workflow_plugin.py' - 'backend/pyproject.toml' @@ -63,6 +64,7 @@ on: - 'backend/tests/test_lightrag_relations_extension.py' - 'backend/tests/test_report_sections_extension.py' - 'backend/tests/test_retrieval_plugin_artifacts.py' + - 'backend/tests/test_run_postmortem_extension.py' - 'backend/tests/test_weknora_extension.py' - 'backend/tests/test_workflow_plugin.py' - 'backend/pyproject.toml' diff --git a/backend/tests/test_extension_documentation.py b/backend/tests/test_extension_documentation.py index c0400c8c97..238b8f5804 100644 --- a/backend/tests/test_extension_documentation.py +++ b/backend/tests/test_extension_documentation.py @@ -185,7 +185,7 @@ def test_bundled_documentation_snapshot_is_current(): script = runpy.run_path(str(root / "scripts/sync_extension_documentation.py")) assert script["DESTINATION"].read_text(encoding="utf-8") == script["render"]() pages = json.loads(script["render"]()) - assert len(pages) == 17 + assert len(pages) == 18 assert pages["deerflow-extension-office-preview"]["id"] == "office-preview" diff --git a/backend/tests/test_run_postmortem_extension.py b/backend/tests/test_run_postmortem_extension.py new file mode 100644 index 0000000000..f9922fda2b --- /dev/null +++ b/backend/tests/test_run_postmortem_extension.py @@ -0,0 +1,83 @@ +"""Bundled run-postmortem example: host loading, route mounting and evidence reads.""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest +from deerflow_extension_api import CompletedRunEvent, CompletedRunEventPage, CompletedRunSnapshot, EvidenceLimits, ExtensionRuntimeDeps +from deerflow_extension_api.run_evidence import RunPage + +from deerflow.extensions.loader import ExtensionSpec, load_extensions + +pytestmark = pytest.mark.bundled_extension + +EXAMPLE = Path(__file__).resolve().parents[2] / "examples/deerflow-extension-run-postmortem" +USE = "deerflow_extension_run_postmortem:install" +PREFIX = "/api/extension-run-postmortem" + + +class FakeEvidence: + """Contract-shaped evidence for one sealed error run.""" + + async def list_changed_runs(self, *, cursor: str | None = None, limit: int = 200) -> RunPage: + return RunPage(items=()) + + async def get_snapshot(self, *, thread_id: str, run_id: str, limits: EvidenceLimits = EvidenceLimits()) -> CompletedRunSnapshot: + return CompletedRunSnapshot(snapshot_ref="snap", evidence_revision="rev", thread_id=thread_id, run_id=run_id, owner_id="alice", agent_id="lead_agent", origin="scheduled", status="error", seal_state="sealed", event_count=2) + + async def read_events(self, *, snapshot_ref: str, cursor: str | None = None, limits: EvidenceLimits = EvidenceLimits()) -> CompletedRunEventPage: + if cursor is not None: + return CompletedRunEventPage() + return CompletedRunEventPage( + items=( + CompletedRunEvent(event_id="e1", seq=1, event_type="run.start", category="trace", content_json=json.dumps({"status": "running"}), content_bytes=0, content_sha256=""), + CompletedRunEvent(event_id="e2", seq=2, event_type="run.error", category="error", content_json=json.dumps({"message": "boom"}), content_bytes=0, content_sha256=""), + ) + ) + + +def _load(monkeypatch, config: dict): + monkeypatch.syspath_prepend(str(EXAMPLE)) + return load_extensions([ExtensionSpec(use=USE, config=config)]) + + +def test_install_registers_one_service_and_its_router(monkeypatch): + loaded, diagnostics = _load(monkeypatch, {"enabled": True}) + + assert not diagnostics + ((_, service),) = loaded.services + assert service.ready is False # the host starts services; install only registers + assert [getattr(router, "prefix", "") for _, router in loaded.routers] == [PREFIX] + + +@pytest.mark.asyncio +async def test_report_is_derived_from_host_evidence(monkeypatch): + loaded, _ = _load(monkeypatch, {"enabled": True}) + ((_, service),) = loaded.services + await service.start(ExtensionRuntimeDeps(completed_run_evidence=FakeEvidence())) + + postmortem = await service.postmortem(thread_id="thread-1", run_id="run-1") + + assert postmortem.owner_id == "alice" + assert [entry.event_type for entry in postmortem.timeline] == ["run.start", "run.error"] + assert {anomaly.code for anomaly in postmortem.anomalies} == {"run_failed", "run_or_model_errors"} + await service.stop() + assert service.ready is False + + +def test_disabled_configuration_registers_nothing(monkeypatch): + loaded, diagnostics = _load(monkeypatch, {"enabled": False}) + + assert not diagnostics + assert loaded.services == () + assert loaded.routers == () + + +def test_a_mistyped_off_switch_fails_the_load(monkeypatch): + loaded, diagnostics = _load(monkeypatch, {"enabled": "false"}) + + assert diagnostics + assert loaded.services == () + assert loaded.routers == () diff --git a/examples/README.md b/examples/README.md index b26cbf8892..3c530433ca 100644 --- a/examples/README.md +++ b/examples/README.md @@ -13,8 +13,9 @@ Additional examples cover [Office file previews](deerflow-extension-office-previ [text-list classification](deerflow-extension-jev-classify/README.md), [context pruning](deerflow-extension-jev-context/README.md), [advisory screening of fetched content](deerflow-extension-jev-screening/README.md), -[sectioned long-form report writing](deerflow-extension-report-sections/README.md), and -[evidence-gated skill self-evolution](deerflow-extension-skill-evolution/README.md). +[sectioned long-form report writing](deerflow-extension-report-sections/README.md), +[evidence-gated skill self-evolution](deerflow-extension-skill-evolution/README.md), and +[run postmortems from sealed evidence](deerflow-extension-run-postmortem/README.md). ## Describe the extension diff --git a/examples/deerflow-extension-run-postmortem/README.md b/examples/deerflow-extension-run-postmortem/README.md new file mode 100644 index 0000000000..1c148ba354 --- /dev/null +++ b/examples/deerflow-extension-run-postmortem/README.md @@ -0,0 +1,89 @@ +# Run postmortem — explain one sealed run from its own evidence + +An opt-in Python plugin that turns a finished run's persisted evidence into a +**verdict, an anomaly list, a timeline and a shareable Markdown report**. It +answers the question an operator asks after a run goes wrong: *what actually +happened, and what should I check next?* + +It uses extension API 0.2.11 with no host code changes. The host owns evidence +storage, sealing, retention and authorization; this package owns only the +interpretation of one sealed run. + +## What it produces + +``` +GET /api/extension-run-postmortem/runs/{thread_id}/{run_id} +GET /api/extension-run-postmortem/runs/{thread_id}/{run_id}/markdown +``` + +```jsonc +{ + "verdict": "Run ended with status error.", + "anomalies": [ + {"code": "run_failed", "detail": "run status is error (Artifact delivery incomplete: ...)"}, + {"code": "delivery_incomplete", "detail": "delivery unsatisfied (presented=0, produced=1)"} + ], + "message_counts": {"user": 1, "assistant": 2, "tool_results": 1}, + "delivery": {"satisfied": false, "presented": 0, "produced": 1}, + "timeline": [{"seq": 1, "event_type": "run.start", "summary": "run.start"}, ...], + "caveats": ["No complete background subagent, remote MCP, or external side-effect coverage.", ...] +} +``` + +Anomaly codes: `evidence_partial` (seal not complete), `run_failed`, +`run_or_model_errors`, `guardrail_triggered`, `delivery_incomplete`, +`tool_failures`, `stopped_early`, `subagent_unfinished`, plus three distinct +read-bound signals: `evidence_bounded` (the caller's `max_events` cut the read), +`evidence_incomplete` (the snapshot retains more events than it returned), and +`evidence_truncated` (the host truncated event payloads). + +The Markdown route renders the same data as a document that can be attached to +an incident ticket. Query `max_events` (1–2000, default 200) bounds the work. + +## Install and configure + +From the DeerFlow checkout root: + +```sh +make extension-install SOURCE=examples/deerflow-extension-run-postmortem +``` + +Grant the evidence capability in `config.yaml` and restart the Gateway: + +```yaml +plugins: + - use: deerflow_extension_run_postmortem:install + name: run-postmortem + host_access: + evidence: + owners: ["your-user-id"] +``` + +Prerequisites are the durable database backend and `run_events.backend: db`, +the same as any completed-run evidence consumer. Without the grant the service +fails to start and the Gateway reports a diagnostic; nothing else changes. + +Callers are bound twice: the route requires an authenticated principal, asks the +host's request-scoped reader whether the run is visible (when the host offers +one), and compares the snapshot owner with the caller. A run owned by someone +else answers `404`, never `403`, so the route does not disclose existence. + +## Design notes + +- **Bounded reads.** One request reads at most `max_events` events, follows the + host cursor, and stops on a repeated cursor. Event payloads are truncated per + the host's `EvidenceLimits`. +- **Pure derivation.** `postmortem.py` contains no I/O; the service only fetches + a snapshot and its pages. That keeps the interpretation unit-testable and the + HTTP surface thin. +- **Evidence is not authorization.** The snapshot and events are data. The route + binds the caller explicitly; references in the evidence confer no access. +- **Truncation is reported, never hidden.** A short read or a truncated payload + becomes an `evidence_truncated` anomaly plus a caveat. + +## Tests + +```sh +cd examples/deerflow-extension-run-postmortem +uv run pytest -q +``` diff --git a/examples/deerflow-extension-run-postmortem/deerflow_extension_run_postmortem/__init__.py b/examples/deerflow-extension-run-postmortem/deerflow_extension_run_postmortem/__init__.py new file mode 100644 index 0000000000..3c372b2b7b --- /dev/null +++ b/examples/deerflow-extension-run-postmortem/deerflow_extension_run_postmortem/__init__.py @@ -0,0 +1,36 @@ +"""Run postmortem example: one sealed run, explained from its own evidence. + +Install via ``config.yaml -> plugins:`` with a ``host_access.evidence`` grant +(see README.md). Without the grant the service fails to start and the Gateway +reports a diagnostic; nothing else changes. +""" + +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any + +from deerflow_extension_api import ExtensionInstall, ExtensionRegistry, extension + +from deerflow_extension_run_postmortem.service import PostmortemService, build_router + +__all__ = ["install"] + + +@extension(api="0.2.11", name="run-postmortem") +def install(registry: ExtensionRegistry, config: Mapping[str, Any]) -> None: + """Register the report service and its HTTP surface.""" + # ``is False`` alone would silently keep the plugin on for ``enabled: 0`` or + # ``enabled: "false"``; a mistyped off switch must fail the deployment. + enabled = config.get("enabled", True) + if type(enabled) is not bool: + raise ValueError(f"run-postmortem: config.enabled must be a boolean, got {enabled!r}") + if not enabled: + return + + service = PostmortemService() + registry.service(service) + registry.routers((build_router(service),)) + + +_entry_point: ExtensionInstall = install diff --git a/examples/deerflow-extension-run-postmortem/deerflow_extension_run_postmortem/deerflow-extension.json b/examples/deerflow-extension-run-postmortem/deerflow_extension_run_postmortem/deerflow-extension.json new file mode 100644 index 0000000000..38178787db --- /dev/null +++ b/examples/deerflow-extension-run-postmortem/deerflow_extension_run_postmortem/deerflow-extension.json @@ -0,0 +1,51 @@ +{ + "schema_version": 1, + "id": "catalog/runPostmortem", + "locales": { + "zh-CN": { + "title": "运行复盘", + "description": "把一次已封存运行的事件证据整理成时间线、异常清单与可分享的 Markdown 报告,用来回答“这次为什么失败/卡住”。", + "usage": [ + { + "title": "安装并授权", + "description": "通过 make extension-install 安装示例,在 config.yaml 的 plugins 中授予 host_access.evidence 后重启 Gateway。" + }, + { + "title": "查看单次运行报告", + "description": "调用 /api/extension-run-postmortem/runs/{thread_id}/{run_id} 获取结构化复盘,或在末尾追加 /markdown 下载可分享报告。" + }, + { + "title": "先看异常再读时间线", + "description": "anomalies 汇总部分封存、错误事件、护栏触发、交付未完成、工具失败与证据截断;timeline 则是按事件序号展开的执行轨迹。" + } + ], + "requirements": [ + "需要持久化 run store 与数据库事件存储(run_events.backend: db)。", + "需要在 config.yaml 中显式授予 host_access.evidence。" + ] + }, + "en-US": { + "title": "Run postmortem", + "description": "Turns one sealed run's event evidence into a timeline, an anomaly list and a shareable Markdown report that answers \"why did this run fail or stall\".", + "usage": [ + { + "title": "Install and grant access", + "description": "Install the example with make extension-install, grant host_access.evidence in config.yaml plugins, then restart Gateway." + }, + { + "title": "Open a run report", + "description": "Call /api/extension-run-postmortem/runs/{thread_id}/{run_id} for the structured report, or append /markdown for a shareable document." + }, + { + "title": "Read anomalies before the timeline", + "description": "anomalies summarizes partial sealing, error events, guardrail hits, incomplete delivery, tool failures and truncated evidence; timeline expands the run by event sequence." + } + ], + "requirements": [ + "Requires a durable run store and the database event store (run_events.backend: db).", + "Requires an explicit host_access.evidence grant in config.yaml." + ] + } + }, + "docs_url": "https://github.com/bytedance/deer-flow/tree/main/examples/deerflow-extension-run-postmortem#readme" +} diff --git a/examples/deerflow-extension-run-postmortem/deerflow_extension_run_postmortem/postmortem.py b/examples/deerflow-extension-run-postmortem/deerflow_extension_run_postmortem/postmortem.py new file mode 100644 index 0000000000..41db203898 --- /dev/null +++ b/examples/deerflow-extension-run-postmortem/deerflow_extension_run_postmortem/postmortem.py @@ -0,0 +1,413 @@ +"""Turn sealed-run evidence into a bounded, human-readable postmortem. + +The host hands plugins immutable snapshots and bounded event pages; this module +owns only the interpretation. Everything here is pure so the service and the +HTTP surface stay thin and the derivation stays unit-testable without a host. +""" + +from __future__ import annotations + +import json +from dataclasses import dataclass, field +from typing import Any + +from deerflow_extension_api import CompletedRunEvent, CompletedRunSnapshot + +_SUMMARY_CAP = 240 +_MESSAGE_EVENT_TYPES = {"llm.human.input", "llm.ai.response", "llm.tool.result"} +_GUARDRAIL_EVENT_TYPES = { + "middleware:guardrail": "guardrail", + "middleware:loop_detection": "loop_detection", + "middleware:safety_termination": "safety termination", +} +_TOOL_FAILURE_STATUSES = {"error", "failed", "failure"} + + +@dataclass(frozen=True) +class TimelineEntry: + """One bounded, printable line derived from a persisted run event.""" + + seq: int + event_type: str + category: str + summary: str + truncated: bool = False + + +@dataclass(frozen=True) +class Anomaly: + """A finding worth checking, with the evidence that produced it.""" + + code: str + detail: str + + +@dataclass(frozen=True) +class DeliverySummary: + satisfied: bool | None = None + presented: int | None = None + produced: int | None = None + + +@dataclass(frozen=True) +class Postmortem: + thread_id: str + run_id: str + owner_id: str + agent_id: str | None + origin: str + status: str + stop_reason: str | None + seal_state: str + seal_error: str | None + events_read: int + events_total: int + counts_by_category: dict[str, int] = field(default_factory=dict) + counts_by_type: dict[str, int] = field(default_factory=dict) + message_counts: dict[str, int] = field(default_factory=dict) + tool_failures: int = 0 + delivery: DeliverySummary = field(default_factory=DeliverySummary) + subagents_started: int = 0 + subagents_ended: int = 0 + timeline: tuple[TimelineEntry, ...] = () + anomalies: tuple[Anomaly, ...] = () + caveats: tuple[str, ...] = () + snapshot_ref: str = "" + evidence_revision: str = "" + + @property + def verdict(self) -> str: + if self.status == "success": + return "Run completed successfully." if not self.anomalies else "Run completed; review the anomalies below." + if self.status == "waiting_for_input": + return "Run paused for human input." + if not self.status: + return "Run status is not recorded in this evidence." + return f"Run ended with status {self.status}." + + +def _loads(raw: str, fallback: Any) -> Any: + try: + return json.loads(raw) if raw else fallback + except (TypeError, ValueError): + return fallback + + +def _text(value: Any, cap: int = _SUMMARY_CAP) -> str: + """Collapse a value to one bounded line of printable text.""" + if isinstance(value, str): + text = value + elif isinstance(value, (dict, list)): + text = json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":")) + elif value is None: + text = "" + else: + text = str(value) + text = " ".join(text.split()) + return text if len(text) <= cap else text[: cap - 1] + "…" + + +def _content_text(content: Any) -> str: + """Flatten a message-like payload (string, block list or dump) to text.""" + if isinstance(content, str): + return content + if isinstance(content, list): + parts: list[str] = [] + for block in content: + if isinstance(block, str): + parts.append(block) + elif isinstance(block, dict): + text = block.get("text") + if isinstance(text, str): + parts.append(text) + elif block.get("type") not in (None, "text"): + parts.append(f"[{block.get('type')}]") + return " ".join(parts) + if isinstance(content, dict): + return _content_text(content.get("content")) + return "" + + +def _message_summary(event_type: str, content: Any) -> str: + if not isinstance(content, (dict, str, list)): + return _text(content) + if event_type == "llm.ai.response" and isinstance(content, dict): + tool_calls = content.get("tool_calls") + if isinstance(tool_calls, list) and tool_calls: + names = [] + for call in tool_calls: + if isinstance(call, dict): + name = call.get("name") or call.get("function", {}).get("name") + names.append(str(name or "?")) + return _text("assistant → " + ", ".join(names)) + return _text("assistant: " + (_content_text(content) or "(empty)")) + if event_type == "llm.tool.result" and isinstance(content, dict): + name = content.get("name") or content.get("tool") + body = _content_text(content) + return _text(f"tool {name or '?'}: {body or '(empty)'}") + return _text("user: " + _content_text(content)) + + +def _tool_failed(content: Any) -> bool: + """A tool result reports failure only through explicit markers.""" + if not isinstance(content, dict): + return False + status = content.get("status") + if isinstance(status, str) and status.lower() in _TOOL_FAILURE_STATUSES: + return True + if content.get("is_error") is True or content.get("error") is True: + return True + text = _content_text(content).lstrip() + # A bare "Error " prefix is prose ("Error handling in this tool ..."), + # not a marker; only the structured fields above and "Error:" signal it. + return text.startswith("Error:") + + +def _delivery_summary(content: Any) -> DeliverySummary: + if not isinstance(content, dict): + return DeliverySummary() + satisfied = content.get("satisfied") + presented = content.get("presented") + produced = content.get("produced_paths") + return DeliverySummary( + satisfied=satisfied if isinstance(satisfied, bool) else None, + presented=presented if type(presented) is int else None, + produced=len(produced) if isinstance(produced, list) else None, + ) + + +def _subagent_summary(event_type: str, content: Any) -> str: + name = None + if isinstance(content, dict): + name = content.get("name") or content.get("subagent") or content.get("agent") + action = event_type.rsplit(".", 1)[-1] + return _text(f"subagent {action}: {name or '?'}") + + +def _summary(event: CompletedRunEvent, content: Any) -> str: + event_type = event.event_type + if event_type in _MESSAGE_EVENT_TYPES: + return _message_summary(event_type, content) + if event_type == "run.delivery": + delivery = _delivery_summary(content) + if delivery.satisfied is None: + return _text("delivery receipt recorded") + return _text(f"delivery: satisfied={delivery.satisfied} presented={delivery.presented} produced={delivery.produced}") + if event_type.startswith("subagent."): + return _subagent_summary(event_type, content) + if event_type.startswith("middleware:"): + tag = event_type.split(":", 1)[1] + detail = _content_text(content) or _text(content) + return _text(f"{tag}: {detail}") + if event_type == "workspace_changes" and isinstance(content, dict): + files = content.get("files") or content.get("changes") + if isinstance(files, list): + return _text(f"workspace: {len(files)} file(s) changed") + return _text("workspace changes recorded") + if event_type == "context:memory": + return _text(f"memory context: {_text(content)}") + if event_type in {"run.error", "llm.error"}: + return _text(f"{event_type}: {_content_text(content) or _text(content)}") + if event_type in {"run.start", "run.end", "run.terminal"}: + status = None + if isinstance(content, dict): + status = content.get("status") or content.get("stop_reason") + return _text(f"{event_type}: {status}" if status else event_type) + return _text(_content_text(content) or event.content_json) + + +def build_postmortem(snapshot: CompletedRunSnapshot, events: list[CompletedRunEvent] | tuple[CompletedRunEvent, ...], *, max_events: int | None = None) -> Postmortem: + """Derive the bounded report from a snapshot and the events read for it. + + ``max_events`` is the caller's read bound (``None`` when unbounded), so a + short read caused by that bound is reported as ``evidence_bounded`` rather + than as retention or sealing damage. + """ + counts_by_category: dict[str, int] = {} + counts_by_type: dict[str, int] = {} + message_counts = {"user": 0, "assistant": 0, "tool_results": 0} + tool_failures = 0 + delivery = DeliverySummary() + subagents_started = 0 + subagents_ended = 0 + timeline: list[TimelineEntry] = [] + error_details: list[str] = [] + guardrail_hits: list[str] = [] + + for event in events: + content = _loads(event.content_json, event.content_json) + counts_by_category[event.category] = counts_by_category.get(event.category, 0) + 1 + counts_by_type[event.event_type] = counts_by_type.get(event.event_type, 0) + 1 + if event.event_type == "llm.human.input": + message_counts["user"] += 1 + elif event.event_type == "llm.ai.response": + message_counts["assistant"] += 1 + elif event.event_type == "llm.tool.result": + message_counts["tool_results"] += 1 + if _tool_failed(content): + tool_failures += 1 + elif event.event_type == "run.delivery": + delivery = _delivery_summary(content) + elif event.event_type == "subagent.start": + subagents_started += 1 + elif event.event_type == "subagent.end": + subagents_ended += 1 + if event.event_type in {"run.error", "llm.error"}: + error_details.append(_text(_content_text(content) or _text(content), 160)) + if event.event_type in _GUARDRAIL_EVENT_TYPES: + guardrail_hits.append(f"{_GUARDRAIL_EVENT_TYPES[event.event_type]}: {_text(_content_text(content) or _text(content), 160)}") + timeline.append( + TimelineEntry( + seq=event.seq, + event_type=event.event_type, + category=event.category, + summary=_summary(event, content), + truncated=event.truncated, + ) + ) + + anomalies: list[Anomaly] = [] + if snapshot.seal_state != "sealed": + detail = f"seal state is {snapshot.seal_state or 'unknown'}" + if snapshot.seal_error: + detail += f": {_text(snapshot.seal_error, 160)}" + anomalies.append(Anomaly("evidence_partial", detail)) + if snapshot.status == "error": + anomalies.append(Anomaly("run_failed", f"run status is error ({error_details[0] if error_details else 'no error event retained'})")) + if error_details: + anomalies.append(Anomaly("run_or_model_errors", f"{len(error_details)} error event(s); first: {error_details[0]}")) + if guardrail_hits: + anomalies.append(Anomaly("guardrail_triggered", f"{len(guardrail_hits)} guardrail event(s); first: {guardrail_hits[0]}")) + if delivery.satisfied is False: + anomalies.append(Anomaly("delivery_incomplete", f"delivery unsatisfied (presented={delivery.presented}, produced={delivery.produced})")) + if tool_failures: + anomalies.append(Anomaly("tool_failures", f"{tool_failures} tool result(s) report a failure")) + if snapshot.stop_reason: + anomalies.append(Anomaly("stopped_early", f"stop_reason={snapshot.stop_reason}")) + if subagents_started > subagents_ended: + anomalies.append(Anomaly("subagent_unfinished", f"{subagents_started} started, {subagents_ended} ended; background completion may be outside this evidence")) + if any(entry.truncated for entry in timeline): + anomalies.append(Anomaly("evidence_truncated", "some event payloads were truncated by the evidence reader")) + if len(events) < snapshot.event_count: + if max_events is not None and len(events) >= max_events: + anomalies.append(Anomaly("evidence_bounded", f"read {len(events)} of {snapshot.event_count} retained event(s); bounded by max_events={max_events}")) + else: + anomalies.append(Anomaly("evidence_incomplete", f"read {len(events)} of {snapshot.event_count} retained event(s); the remainder is not available in this snapshot")) + + caveats = list(snapshot.coverage_limits) + if snapshot.expires_at: + caveats.append(f"Evidence expires at {snapshot.expires_at}.") + if not events: + caveats.append("No run events were retained for this snapshot.") + if max_events is not None and len(events) >= max_events and len(events) < snapshot.event_count: + caveats.append(f"Report bounded by max_events={max_events}; raise the bound for a longer timeline.") + + return Postmortem( + thread_id=snapshot.thread_id, + run_id=snapshot.run_id, + owner_id=snapshot.owner_id, + agent_id=snapshot.agent_id, + origin=snapshot.origin, + status=snapshot.status, + stop_reason=snapshot.stop_reason, + seal_state=snapshot.seal_state, + seal_error=snapshot.seal_error, + events_read=len(events), + events_total=snapshot.event_count, + counts_by_category=counts_by_category, + counts_by_type=counts_by_type, + message_counts=message_counts, + tool_failures=tool_failures, + delivery=delivery, + subagents_started=subagents_started, + subagents_ended=subagents_ended, + timeline=tuple(timeline), + anomalies=tuple(anomalies), + caveats=tuple(caveats), + snapshot_ref=snapshot.snapshot_ref, + evidence_revision=snapshot.evidence_revision, + ) + + +def to_dict(postmortem: Postmortem) -> dict[str, Any]: + """JSON-safe projection for the HTTP surface.""" + return { + "thread_id": postmortem.thread_id, + "run_id": postmortem.run_id, + "agent_id": postmortem.agent_id, + "origin": postmortem.origin, + "status": postmortem.status, + "stop_reason": postmortem.stop_reason, + "seal_state": postmortem.seal_state, + "seal_error": postmortem.seal_error, + "verdict": postmortem.verdict, + "events_read": postmortem.events_read, + "events_total": postmortem.events_total, + "counts_by_category": dict(postmortem.counts_by_category), + "counts_by_type": dict(postmortem.counts_by_type), + "message_counts": dict(postmortem.message_counts), + "tool_failures": postmortem.tool_failures, + "delivery": { + "satisfied": postmortem.delivery.satisfied, + "presented": postmortem.delivery.presented, + "produced": postmortem.delivery.produced, + }, + "subagents": {"started": postmortem.subagents_started, "ended": postmortem.subagents_ended}, + "anomalies": [{"code": anomaly.code, "detail": anomaly.detail} for anomaly in postmortem.anomalies], + "caveats": list(postmortem.caveats), + "timeline": [{"seq": entry.seq, "event_type": entry.event_type, "category": entry.category, "summary": entry.summary, "truncated": entry.truncated} for entry in postmortem.timeline], + "snapshot_ref": postmortem.snapshot_ref, + "evidence_revision": postmortem.evidence_revision, + } + + +def render_markdown(postmortem: Postmortem) -> str: + """Render the report as a shareable Markdown document.""" + lines = [ + f"# Run postmortem — `{postmortem.run_id}`", + "", + postmortem.verdict, + "", + "## Overview", + "", + "| Field | Value |", + "| --- | --- |", + f"| Thread | `{postmortem.thread_id}` |", + f"| Agent | `{postmortem.agent_id or '-'}` |", + f"| Origin | {postmortem.origin or '-'} |", + f"| Status | {postmortem.status or '-'} |", + f"| Stop reason | {postmortem.stop_reason or '-'} |", + f"| Evidence | {postmortem.seal_state or '-'} ({postmortem.events_read}/{postmortem.events_total} events) |", + "", + "## Anomalies", + "", + ] + if postmortem.anomalies: + lines.extend(f"- **{anomaly.code}** — {anomaly.detail}" for anomaly in postmortem.anomalies) + else: + lines.append("None detected in the retained evidence.") + lines.extend( + [ + "", + "## Activity", + "", + f"- Messages: {postmortem.message_counts.get('user', 0)} user, {postmortem.message_counts.get('assistant', 0)} assistant, {postmortem.message_counts.get('tool_results', 0)} tool results", + f"- Tool failures: {postmortem.tool_failures}", + f"- Subagents: {postmortem.subagents_started} started, {postmortem.subagents_ended} ended", + ] + ) + delivery = postmortem.delivery + if delivery.satisfied is not None: + lines.append(f"- Delivery: satisfied={delivery.satisfied}, presented={delivery.presented}, produced={delivery.produced}") + lines.extend(["", "## Timeline", "", "| # | Event | Summary |", "| --- | --- | --- |"]) + if postmortem.timeline: + for entry in postmortem.timeline: + summary = entry.summary.replace("|", "\\|") + suffix = " _(truncated)_" if entry.truncated else "" + lines.append(f"| {entry.seq} | `{entry.event_type}` | {summary}{suffix} |") + else: + lines.append("| - | - | No retained events |") + lines.extend(["", "## Evidence caveats", ""]) + lines.extend(f"- {caveat}" for caveat in postmortem.caveats) + lines.extend(["", f"_snapshot `{postmortem.snapshot_ref}` · revision `{postmortem.evidence_revision}`_", ""]) + return "\n".join(lines) diff --git a/examples/deerflow-extension-run-postmortem/deerflow_extension_run_postmortem/service.py b/examples/deerflow-extension-run-postmortem/deerflow_extension_run_postmortem/service.py new file mode 100644 index 0000000000..b0621dbd64 --- /dev/null +++ b/examples/deerflow-extension-run-postmortem/deerflow_extension_run_postmortem/service.py @@ -0,0 +1,168 @@ +"""Host-contract service and HTTP surface for the run-postmortem example. + +The service depends only on the public ``deerflow-extension-api`` contract: the +host owns evidence storage, authorization and retention; this package owns only +the interpretation of one sealed run, exposed as JSON and Markdown. +""" + +from __future__ import annotations + +from collections.abc import Awaitable +from typing import Any + +from deerflow_extension_api import ( + CompletedRunEvent, + CompletedRunEvidenceReader, + CompletedRunSnapshot, + EvidenceLimits, + ExtensionPrincipal, + ExtensionRuntimeDeps, + HostCapabilityError, + resolve_principal, + resolve_run_evidence_reader, +) +from fastapi import APIRouter, HTTPException, Query, Request +from fastapi.responses import PlainTextResponse + +from deerflow_extension_run_postmortem.postmortem import Postmortem, build_postmortem, render_markdown, to_dict + +DEFAULT_MAX_EVENTS = 200 +MAX_EVENTS = 2000 +_STATUS_BY_CODE = {"NOT_GRANTED": 409, "NOT_FOUND": 404, "BAD_REQUEST": 400} + + +class PostmortemError(RuntimeError): + """A named, caller-facing failure distinct from host capability errors.""" + + def __init__(self, code: str, message: str = "") -> None: + self.code = code + super().__init__(f"{code}: {message}" if message else code) + + +class PostmortemService: + """Bounded evidence reader plus the pure derivation. + + ``start`` captures the host capability handle; ``stop`` drops it. Every + request reads fresh evidence, so the service holds no per-run cache and a + run that is still being sealed simply yields the evidence available now. + """ + + def __init__(self) -> None: + self._evidence: CompletedRunEvidenceReader | None = None + + # -- ExtensionService protocol ----------------------------------------- + + async def start(self, deps: ExtensionRuntimeDeps) -> None: + self._evidence = deps.completed_run_evidence + if self._evidence is None: + raise PostmortemError( + "NOT_GRANTED", + "completed_run_evidence capability missing; grant host_access.evidence in config.yaml plugins", + ) + + async def stop(self) -> None: + self._evidence = None + + # -- introspection ------------------------------------------------------ + + @property + def ready(self) -> bool: + return self._evidence is not None + + async def postmortem(self, *, thread_id: str, run_id: str, max_events: int = DEFAULT_MAX_EVENTS) -> Postmortem: + if not isinstance(max_events, int) or not 1 <= max_events <= MAX_EVENTS: + raise PostmortemError("BAD_REQUEST", f"max_events must be an integer between 1 and {MAX_EVENTS}") + evidence = self._require_evidence() + limits = EvidenceLimits(max_events=max_events) + snapshot = await evidence.get_snapshot(thread_id=thread_id, run_id=run_id, limits=limits) + return build_postmortem(snapshot, await self._read_events(evidence, snapshot, limits), max_events=max_events) + + async def _read_events(self, evidence: CompletedRunEvidenceReader, snapshot: CompletedRunSnapshot, limits: EvidenceLimits) -> list[CompletedRunEvent]: + """Follow the event cursor until the snapshot ends or the cap is met.""" + events: list[CompletedRunEvent] = [] + cursor: str | None = None + seen_cursors: set[str] = set() + while len(events) < limits.max_events: + page = await evidence.read_events(snapshot_ref=snapshot.snapshot_ref, cursor=cursor, limits=limits) + events.extend(page.items) + if not page.has_more or page.next_cursor is None: + break + if page.next_cursor in seen_cursors: + # A host that repeats a cursor must not spin the request. + break + seen_cursors.add(page.next_cursor) + cursor = page.next_cursor + return events[: limits.max_events] + + def _require_evidence(self) -> CompletedRunEvidenceReader: + if self._evidence is None: + raise PostmortemError("NOT_GRANTED", "service is not started or the evidence capability is missing") + return self._evidence + + +def build_router(service: PostmortemService): + """Expose the report as JSON and as a shareable Markdown document.""" + router = APIRouter(prefix="/api/extension-run-postmortem", tags=["run-postmortem"]) + + def _principal(request: Request) -> ExtensionPrincipal: + principal = resolve_principal(request) + if principal is None: + raise HTTPException(status_code=401, detail="authentication required") + return principal + + async def _require_visible_run(request: Request, thread_id: str, run_id: str) -> None: + """Confirm the anchor is visible to the caller when the host offers it. + + The evidence handle is allowlist-scoped for the plugin, not scoped to the + requesting user, so the route also compares the snapshot owner below. + """ + try: + reader = resolve_run_evidence_reader(request) + if reader is None: + return + status = await reader.get_run_status(thread_id=thread_id, run_id=run_id) + except NotImplementedError: + return + if status is None: + raise PostmortemError("NOT_FOUND", f"run {run_id} is not visible to this caller") + + def _guard(coro: Awaitable[Any]) -> Awaitable[Any]: + async def run(): + try: + return await coro + except PostmortemError as exc: + raise HTTPException(status_code=_STATUS_BY_CODE.get(exc.code, 500), detail=str(exc)) from exc + except PermissionError as exc: + raise HTTPException(status_code=403, detail=str(exc)) from exc + except HostCapabilityError as exc: + status = 404 if exc.code in {"NOT_FOUND", "NOT_FOUND_OR_FORBIDDEN"} else 409 + raise HTTPException(status_code=status, detail=str(exc)) from exc + + return run() + + async def _report(request: Request, thread_id: str, run_id: str, max_events: int) -> Postmortem: + principal = _principal(request) + await _require_visible_run(request, thread_id, run_id) + postmortem = await service.postmortem(thread_id=thread_id, run_id=run_id, max_events=max_events) + if postmortem.owner_id != principal.user_id: + # Never disclose whether another user's run exists. + raise PostmortemError("NOT_FOUND", f"run {run_id} is not visible to this caller") + return postmortem + + @router.get("/health") + async def health() -> dict[str, Any]: + return {"ready": service.ready, "max_events": MAX_EVENTS} + + @router.get("/runs/{thread_id}/{run_id}") + async def report(request: Request, thread_id: str, run_id: str, max_events: int = Query(DEFAULT_MAX_EVENTS, ge=1, le=MAX_EVENTS)) -> dict[str, Any]: + return to_dict(await _guard(_report(request, thread_id, run_id, max_events))) + + @router.get("/runs/{thread_id}/{run_id}/markdown", response_class=PlainTextResponse) + async def report_markdown(request: Request, thread_id: str, run_id: str, max_events: int = Query(DEFAULT_MAX_EVENTS, ge=1, le=MAX_EVENTS)) -> PlainTextResponse: + postmortem = await _guard(_report(request, thread_id, run_id, max_events)) + return PlainTextResponse(render_markdown(postmortem), media_type="text/markdown") + + return router + + +__all__ = ["DEFAULT_MAX_EVENTS", "MAX_EVENTS", "PostmortemError", "PostmortemService", "build_router"] diff --git a/examples/deerflow-extension-run-postmortem/pyproject.toml b/examples/deerflow-extension-run-postmortem/pyproject.toml new file mode 100644 index 0000000000..242bdf4919 --- /dev/null +++ b/examples/deerflow-extension-run-postmortem/pyproject.toml @@ -0,0 +1,43 @@ +[project] +name = "deerflow-extension-run-postmortem" +version = "0.1.0" +description = "Example: explain one sealed DeerFlow run from its own evidence as JSON and Markdown" +readme = "README.md" +requires-python = ">=3.12" +license = "MIT" +dependencies = [ + "deerflow-extension-api>=0.2.11,<0.3", + "fastapi>=0.115.0,<1", +] + +[project.entry-points."deerflow.extensions"] +run-postmortem = "deerflow_extension_run_postmortem:install" + +[project.optional-dependencies] +dev = [ + "httpx>=0.28,<1", + "pytest>=9,<10", + "pytest-asyncio>=1.3,<2", + "ruff>=0.14,<1", +] + +[build-system] +requires = ["hatchling"] +build-backend = "hatchling.build" + +[tool.hatch.build.targets.wheel] +packages = ["deerflow_extension_run_postmortem"] + +[tool.ruff] +line-length = 240 +target-version = "py312" + +[tool.ruff.lint] +select = ["E", "F", "I", "UP"] + +[tool.ruff.lint.isort] +known-first-party = ["deerflow_extension_run_postmortem"] + +[tool.pytest.ini_options] +asyncio_mode = "auto" +asyncio_default_fixture_loop_scope = "function" diff --git a/examples/deerflow-extension-run-postmortem/tests/test_postmortem.py b/examples/deerflow-extension-run-postmortem/tests/test_postmortem.py new file mode 100644 index 0000000000..fe019566be --- /dev/null +++ b/examples/deerflow-extension-run-postmortem/tests/test_postmortem.py @@ -0,0 +1,151 @@ +"""Pure derivation: persisted event shapes in, verdict and anomalies out.""" + +from __future__ import annotations + +import json + +from deerflow_extension_api import CompletedRunEvent, CompletedRunSnapshot + +from deerflow_extension_run_postmortem.postmortem import build_postmortem, render_markdown, to_dict + + +def event(seq: int, event_type: str, category: str, content) -> CompletedRunEvent: + return CompletedRunEvent(event_id=f"e{seq}", seq=seq, event_type=event_type, category=category, content_json=json.dumps(content), content_bytes=0, content_sha256="") + + +def snapshot(**overrides) -> CompletedRunSnapshot: + base = { + "snapshot_ref": "snap", + "evidence_revision": "rev", + "thread_id": "t1", + "run_id": "r1", + "owner_id": "alice", + "agent_id": "lead_agent", + "origin": "interactive", + "status": "success", + "seal_state": "sealed", + "event_count": 0, + "coverage_limits": ("No complete background subagent coverage.",), + } + base.update(overrides) + return CompletedRunSnapshot(**base) + + +def test_success_run_reports_no_anomalies(): + postmortem = build_postmortem( + snapshot(event_count=3), + [ + event(1, "run.start", "trace", {"status": "running"}), + event(2, "llm.human.input", "message", {"content": "write the report"}), + event(3, "run.end", "outputs", {"status": "success"}), + ], + ) + + assert postmortem.verdict == "Run completed successfully." + assert postmortem.anomalies == () + assert postmortem.message_counts["user"] == 1 + assert postmortem.owner_id == "alice" + assert postmortem.timeline[1].summary == "user: write the report" + assert to_dict(postmortem)["verdict"] == "Run completed successfully." + + +def test_error_run_surfaces_every_failure_signal(): + events = [ + event(1, "run.start", "trace", {}), + event(2, "llm.ai.response", "message", {"content": "", "tool_calls": [{"name": "present_files"}]}), + event(3, "llm.tool.result", "message", {"name": "present_files", "content": "Error: only outputs can be presented"}), + event(4, "middleware:guardrail", "middleware", {"message": "loop warning"}), + event(5, "run.delivery", "outputs", {"satisfied": False, "presented": 0, "produced_paths": ["/mnt/user-data/outputs/report.md"]}), + event(6, "run.error", "error", {"message": "Artifact delivery incomplete: no produced output artifact was presented"}), + ] + postmortem = build_postmortem( + snapshot(status="error", stop_reason="recursion_capped", seal_state="partial", seal_error="journal flush interrupted", event_count=8), + events, + ) + + codes = {anomaly.code for anomaly in postmortem.anomalies} + assert { + "evidence_partial", + "run_failed", + "run_or_model_errors", + "guardrail_triggered", + "delivery_incomplete", + "tool_failures", + "stopped_early", + "evidence_incomplete", + } <= codes + assert postmortem.timeline[1].summary == "assistant → present_files" + assert postmortem.tool_failures == 1 + assert postmortem.delivery.satisfied is False + assert postmortem.delivery.produced == 1 + assert postmortem.verdict == "Run ended with status error." + + +def test_subagent_and_workspace_summaries_are_readable(): + events = [ + event(1, "subagent.start", "subagent", {"name": "researcher"}), + event(2, "workspace_changes", "outputs", {"files": [{"path": "a.md"}, {"path": "b.md"}]}), + event(3, "context:memory", "context", "remembered preference"), + ] + postmortem = build_postmortem(snapshot(event_count=3), events) + + assert postmortem.timeline[0].summary == "subagent start: researcher" + assert postmortem.timeline[1].summary == "workspace: 2 file(s) changed" + assert postmortem.timeline[2].summary == "memory context: remembered preference" + assert {anomaly.code for anomaly in postmortem.anomalies} == {"subagent_unfinished"} + + +def test_payloads_are_bounded_and_truncation_is_reported(): + long_text = "x" * 5000 + postmortem = build_postmortem(snapshot(event_count=1), [event(1, "llm.ai.response", "message", {"content": long_text})]) + + assert len(postmortem.timeline[0].summary) <= 240 + assert postmortem.timeline[0].summary.endswith("…") + + +def test_markdown_escapes_table_cells_and_lists_the_caveats(): + events = [event(1, "llm.human.input", "message", {"content": "a | b"}), event(2, "run.delivery", "outputs", {"satisfied": False, "presented": 0, "produced_paths": ["x"]})] + markdown = render_markdown(build_postmortem(snapshot(status="error", event_count=2), events)) + + assert markdown.startswith("# Run postmortem — `r1`") + assert "## Anomalies" in markdown + assert "delivery_incomplete" in markdown + assert "a \\| b" in markdown + assert "No complete background subagent coverage." in markdown + + +def test_unparsable_event_content_falls_back_to_the_raw_string(): + raw = CompletedRunEvent(event_id="e1", seq=1, event_type="unknown.thing", category="trace", content_json="{not json", content_bytes=8, content_sha256="") + postmortem = build_postmortem(snapshot(event_count=1), [raw]) + + assert postmortem.timeline[0].summary == "{not json" + + +def test_bounded_read_is_reported_as_the_caller_bound_not_as_damage(): + events = [event(1, "run.start", "trace", {}), event(2, "run.end", "outputs", {"status": "success"})] + postmortem = build_postmortem(snapshot(event_count=512), events, max_events=2) + + codes = {anomaly.code for anomaly in postmortem.anomalies} + assert "evidence_bounded" in codes + assert "evidence_incomplete" not in codes + assert "evidence_truncated" not in codes + assert any("bounded by max_events=2" in anomaly.detail for anomaly in postmortem.anomalies) + assert any("max_events=2" in caveat for caveat in postmortem.caveats) + + +def test_truncated_payloads_are_reported_on_their_own(): + truncated = CompletedRunEvent(event_id="e1", seq=1, event_type="llm.ai.response", category="message", content_json='{"content": "x"}', content_bytes=1, content_sha256="", truncated=True) + postmortem = build_postmortem(snapshot(event_count=1), [truncated]) + + assert {anomaly.code for anomaly in postmortem.anomalies} == {"evidence_truncated"} + + +def test_prose_starting_with_error_is_not_a_tool_failure(): + prose = event(1, "llm.tool.result", "message", {"name": "read_file", "content": "Error handling in this tool is documented here."}) + marker = event(2, "llm.tool.result", "message", {"name": "read_file", "content": "Error: file not found"}) + + prose_only = build_postmortem(snapshot(event_count=1), [prose]) + marker_only = build_postmortem(snapshot(event_count=1), [marker]) + + assert prose_only.tool_failures == 0 + assert marker_only.tool_failures == 1 diff --git a/examples/deerflow-extension-run-postmortem/tests/test_routes.py b/examples/deerflow-extension-run-postmortem/tests/test_routes.py new file mode 100644 index 0000000000..249b84e96b --- /dev/null +++ b/examples/deerflow-extension-run-postmortem/tests/test_routes.py @@ -0,0 +1,143 @@ +"""HTTP surface: authentication, owner binding, JSON and Markdown responses.""" + +from __future__ import annotations + +import asyncio +import json + +from deerflow_extension_api import CompletedRunEvent, CompletedRunEventPage, CompletedRunSnapshot, EvidenceLimits, ExtensionPrincipal, ExtensionRuntimeDeps, HostCapabilityError +from deerflow_extension_api.auth import EXTENSION_PRINCIPAL_RESOLVER_KEY +from deerflow_extension_api.run_evidence import RUN_EVIDENCE_READER_RESOLVER_KEY, RunPage, RunStatusView +from fastapi import FastAPI +from fastapi.testclient import TestClient + +from deerflow_extension_run_postmortem.service import PostmortemService, build_router + + +def event(seq: int, event_type: str, category: str, content) -> CompletedRunEvent: + return CompletedRunEvent(event_id=f"e{seq}", seq=seq, event_type=event_type, category=category, content_json=json.dumps(content), content_bytes=0, content_sha256="") + + +class FakeEvidence: + def __init__(self, *, owner: str = "alice", missing: bool = False) -> None: + self.owner = owner + self.missing = missing + self.snapshot_calls = 0 + + async def list_changed_runs(self, *, cursor: str | None = None, limit: int = 200) -> RunPage: + return RunPage(items=()) + + async def get_snapshot(self, *, thread_id: str, run_id: str, limits: EvidenceLimits = EvidenceLimits()) -> CompletedRunSnapshot: + self.snapshot_calls += 1 + if self.missing: + raise HostCapabilityError("NOT_FOUND", "run is unavailable in this scope") + return CompletedRunSnapshot(snapshot_ref="snap", evidence_revision="rev", thread_id=thread_id, run_id=run_id, owner_id=self.owner, agent_id="lead_agent", origin="interactive", status="error", seal_state="sealed", event_count=2) + + async def read_events(self, *, snapshot_ref: str, cursor: str | None = None, limits: EvidenceLimits = EvidenceLimits()) -> CompletedRunEventPage: + if cursor is not None: + return CompletedRunEventPage() + return CompletedRunEventPage(items=(event(1, "run.start", "trace", {}), event(2, "run.error", "error", {"message": "boom"}))) + + +def client_for(evidence: FakeEvidence, *, user_id: str | None = "alice") -> TestClient: + service = PostmortemService() + asyncio.run(service.start(ExtensionRuntimeDeps(completed_run_evidence=evidence))) + app = FastAPI() + app.include_router(build_router(service)) + client = TestClient(app) + + def resolver(request): + return None if user_id is None else ExtensionPrincipal(user_id=user_id) + + setattr(client.app.state, EXTENSION_PRINCIPAL_RESOLVER_KEY, resolver) + return client + + +def test_health_reports_readiness(): + response = client_for(FakeEvidence()).get("/api/extension-run-postmortem/health") + + assert response.status_code == 200 + assert response.json()["ready"] is True + + +def test_anonymous_callers_are_rejected(): + response = client_for(FakeEvidence(), user_id=None).get("/api/extension-run-postmortem/runs/t1/r1") + + assert response.status_code == 401 + + +def test_json_report_carries_the_verdict_and_timeline(): + response = client_for(FakeEvidence()).get("/api/extension-run-postmortem/runs/t1/r1") + + assert response.status_code == 200 + body = response.json() + assert body["run_id"] == "r1" + assert body["verdict"] == "Run ended with status error." + assert [item["event_type"] for item in body["timeline"]] == ["run.start", "run.error"] + assert {anomaly["code"] for anomaly in body["anomalies"]} == {"run_failed", "run_or_model_errors"} + + +def test_markdown_route_returns_a_document(): + response = client_for(FakeEvidence()).get("/api/extension-run-postmortem/runs/t1/r1/markdown") + + assert response.status_code == 200 + assert response.headers["content-type"].startswith("text/markdown") + assert response.text.startswith("# Run postmortem — `r1`") + + +def test_another_owners_run_reads_as_missing(): + response = client_for(FakeEvidence(owner="bob")).get("/api/extension-run-postmortem/runs/t1/r1") + + assert response.status_code == 404 + + +def test_an_unavailable_run_reads_as_missing(): + response = client_for(FakeEvidence(missing=True)).get("/api/extension-run-postmortem/runs/t1/r1") + + assert response.status_code == 404 + + +def test_out_of_range_max_events_is_rejected(): + response = client_for(FakeEvidence()).get("/api/extension-run-postmortem/runs/t1/r1?max_events=0") + + assert response.status_code == 422 + + +class _InvisibleRunReader: + """A request-scoped reader for which the anchor run does not exist.""" + + async def get_run_status(self, *, thread_id: str, run_id: str): + return None + + +class _VisibleRunReader: + """A request-scoped reader that confirms the anchor run is visible.""" + + async def get_run_status(self, *, thread_id: str, run_id: str): + return RunStatusView(thread_id=thread_id, run_id=run_id, status="success") + + +def install_visibility_reader(client: TestClient, reader) -> None: + setattr(client.app.state, RUN_EVIDENCE_READER_RESOLVER_KEY, lambda request: reader) + + +def test_an_invisible_run_is_refused_before_any_evidence_is_read(): + evidence = FakeEvidence() + client = client_for(evidence) + install_visibility_reader(client, _InvisibleRunReader()) + + response = client.get("/api/extension-run-postmortem/runs/t1/r1") + + assert response.status_code == 404 + assert evidence.snapshot_calls == 0 + + +def test_a_visible_run_proceeds_through_the_reader_branch(): + evidence = FakeEvidence() + client = client_for(evidence) + install_visibility_reader(client, _VisibleRunReader()) + + response = client.get("/api/extension-run-postmortem/runs/t1/r1") + + assert response.status_code == 200 + assert evidence.snapshot_calls == 1 diff --git a/examples/deerflow-extension-run-postmortem/tests/test_service.py b/examples/deerflow-extension-run-postmortem/tests/test_service.py new file mode 100644 index 0000000000..f0acdd04a5 --- /dev/null +++ b/examples/deerflow-extension-run-postmortem/tests/test_service.py @@ -0,0 +1,118 @@ +"""Service lifecycle, pagination and bounds against a contract-shaped fake host.""" + +from __future__ import annotations + +import json + +import pytest +from deerflow_extension_api import CompletedRunEvent, CompletedRunEventPage, CompletedRunSnapshot, EvidenceLimits, ExtensionRuntimeDeps +from deerflow_extension_api.run_evidence import RunPage + +from deerflow_extension_run_postmortem.service import PostmortemError, PostmortemService + + +def event(seq: int, event_type: str = "run.start") -> CompletedRunEvent: + return CompletedRunEvent(event_id=f"e{seq}", seq=seq, event_type=event_type, category="trace", content_json=json.dumps({"status": "ok"}), content_bytes=2, content_sha256="") + + +def snapshot(owner: str = "alice") -> CompletedRunSnapshot: + return CompletedRunSnapshot(snapshot_ref="snap", evidence_revision="rev", thread_id="t1", run_id="r1", owner_id=owner, agent_id="lead_agent", origin="interactive", status="success", seal_state="sealed", event_count=2) + + +class FakeEvidence: + """Cursor-addressed pages; every call is recorded for assertion.""" + + def __init__(self, pages: dict[str | None, CompletedRunEventPage] | None = None, snap: CompletedRunSnapshot | None = None) -> None: + self.pages = pages or {None: CompletedRunEventPage(items=(event(1), event(2)))} + self.snap = snap or snapshot() + self.read_cursors: list[str | None] = [] + self.snapshot_limits: EvidenceLimits | None = None + + async def list_changed_runs(self, *, cursor: str | None = None, limit: int = 200) -> RunPage: + return RunPage(items=()) + + async def get_snapshot(self, *, thread_id: str, run_id: str, limits: EvidenceLimits = EvidenceLimits()) -> CompletedRunSnapshot: + self.snapshot_limits = limits + return self.snap + + async def read_events(self, *, snapshot_ref: str, cursor: str | None = None, limits: EvidenceLimits = EvidenceLimits()) -> CompletedRunEventPage: + self.read_cursors.append(cursor) + return self.pages.get(cursor, CompletedRunEventPage()) + + +async def test_start_requires_the_evidence_capability(): + service = PostmortemService() + + with pytest.raises(PostmortemError) as excinfo: + await service.start(ExtensionRuntimeDeps()) + + assert excinfo.value.code == "NOT_GRANTED" + assert "host_access.evidence" in str(excinfo.value) + + +async def test_requests_before_start_are_refused(): + service = PostmortemService() + + with pytest.raises(PostmortemError) as excinfo: + await service.postmortem(thread_id="t1", run_id="r1") + + assert excinfo.value.code == "NOT_GRANTED" + + +async def test_pages_are_followed_until_the_host_stops(): + evidence = FakeEvidence( + pages={ + None: CompletedRunEventPage(items=(event(1), event(2)), next_cursor="c2", has_more=True), + "c2": CompletedRunEventPage(items=(event(3),), next_cursor=None, has_more=False), + } + ) + service = PostmortemService() + await service.start(ExtensionRuntimeDeps(completed_run_evidence=evidence)) + + postmortem = await service.postmortem(thread_id="t1", run_id="r1", max_events=20) + + assert [entry.seq for entry in postmortem.timeline] == [1, 2, 3] + assert evidence.read_cursors == [None, "c2"] + assert evidence.snapshot_limits == EvidenceLimits(max_events=20) + + +async def test_a_repeated_cursor_cannot_spin_the_request(): + evidence = FakeEvidence( + pages={ + None: CompletedRunEventPage(items=(event(1),), next_cursor="same", has_more=True), + "same": CompletedRunEventPage(items=(event(2),), next_cursor="same", has_more=True), + } + ) + service = PostmortemService() + await service.start(ExtensionRuntimeDeps(completed_run_evidence=evidence)) + + postmortem = await service.postmortem(thread_id="t1", run_id="r1", max_events=20) + + assert [entry.seq for entry in postmortem.timeline] == [1, 2] + assert evidence.read_cursors == [None, "same"] + + +async def test_max_events_caps_the_read(): + evidence = FakeEvidence( + pages={ + None: CompletedRunEventPage(items=(event(1), event(2)), next_cursor="c2", has_more=True), + "c2": CompletedRunEventPage(items=(event(3), event(4)), next_cursor=None, has_more=False), + } + ) + service = PostmortemService() + await service.start(ExtensionRuntimeDeps(completed_run_evidence=evidence)) + + postmortem = await service.postmortem(thread_id="t1", run_id="r1", max_events=3) + + assert [entry.seq for entry in postmortem.timeline] == [1, 2, 3] + + +@pytest.mark.parametrize("max_events", [0, -1, 5000]) +async def test_max_events_is_bounded(max_events: int): + service = PostmortemService() + await service.start(ExtensionRuntimeDeps(completed_run_evidence=FakeEvidence())) + + with pytest.raises(PostmortemError) as excinfo: + await service.postmortem(thread_id="t1", run_id="r1", max_events=max_events) + + assert excinfo.value.code == "BAD_REQUEST" diff --git a/frontend/src/core/extensions/bundled-documentation.json b/frontend/src/core/extensions/bundled-documentation.json index 27dd921e0a..82f6ca9ed5 100644 --- a/frontend/src/core/extensions/bundled-documentation.json +++ b/frontend/src/core/extensions/bundled-documentation.json @@ -583,6 +583,57 @@ }, "docs_url": "https://github.com/bytedance/deer-flow/tree/main/examples/deerflow-extension-retrieval#readme" }, + "deerflow-extension-run-postmortem": { + "schema_version": 1, + "id": "catalog/runPostmortem", + "locales": { + "zh-CN": { + "title": "运行复盘", + "description": "把一次已封存运行的事件证据整理成时间线、异常清单与可分享的 Markdown 报告,用来回答“这次为什么失败/卡住”。", + "usage": [ + { + "title": "安装并授权", + "description": "通过 make extension-install 安装示例,在 config.yaml 的 plugins 中授予 host_access.evidence 后重启 Gateway。" + }, + { + "title": "查看单次运行报告", + "description": "调用 /api/extension-run-postmortem/runs/{thread_id}/{run_id} 获取结构化复盘,或在末尾追加 /markdown 下载可分享报告。" + }, + { + "title": "先看异常再读时间线", + "description": "anomalies 汇总部分封存、错误事件、护栏触发、交付未完成、工具失败与证据截断;timeline 则是按事件序号展开的执行轨迹。" + } + ], + "requirements": [ + "需要持久化 run store 与数据库事件存储(run_events.backend: db)。", + "需要在 config.yaml 中显式授予 host_access.evidence。" + ] + }, + "en-US": { + "title": "Run postmortem", + "description": "Turns one sealed run's event evidence into a timeline, an anomaly list and a shareable Markdown report that answers \"why did this run fail or stall\".", + "usage": [ + { + "title": "Install and grant access", + "description": "Install the example with make extension-install, grant host_access.evidence in config.yaml plugins, then restart Gateway." + }, + { + "title": "Open a run report", + "description": "Call /api/extension-run-postmortem/runs/{thread_id}/{run_id} for the structured report, or append /markdown for a shareable document." + }, + { + "title": "Read anomalies before the timeline", + "description": "anomalies summarizes partial sealing, error events, guardrail hits, incomplete delivery, tool failures and truncated evidence; timeline expands the run by event sequence." + } + ], + "requirements": [ + "Requires a durable run store and the database event store (run_events.backend: db).", + "Requires an explicit host_access.evidence grant in config.yaml." + ] + } + }, + "docs_url": "https://github.com/bytedance/deer-flow/tree/main/examples/deerflow-extension-run-postmortem#readme" + }, "deerflow-extension-skill-evolution": { "schema_version": 1, "id": "catalog/skillEvolution", diff --git a/frontend/src/core/extensions/catalog.ts b/frontend/src/core/extensions/catalog.ts index 14c72c2847..4fe2e183cd 100644 --- a/frontend/src/core/extensions/catalog.ts +++ b/frontend/src/core/extensions/catalog.ts @@ -83,6 +83,11 @@ export const extensionCatalog = [ package: "deerflow-extension-skill-evolution", namespace: null, }, + { + key: "runPostmortem", + package: "deerflow-extension-run-postmortem", + namespace: null, + }, { key: "lightrag", package: "deerflow-extension-lightrag", namespace: null }, { key: "weknora", package: "deerflow-extension-weknora", namespace: null }, { key: "example", package: "deerflow-extension-example", namespace: null }, diff --git a/frontend/src/core/i18n/locales/en-US.ts b/frontend/src/core/i18n/locales/en-US.ts index 3146c2142c..bc1233cee5 100644 --- a/frontend/src/core/i18n/locales/en-US.ts +++ b/frontend/src/core/i18n/locales/en-US.ts @@ -205,6 +205,7 @@ export const enUS: Translations = { "en-US", ), lightrag: bundledCopy("deerflow-extension-lightrag", "en-US"), + runPostmortem: bundledCopy("deerflow-extension-run-postmortem", "en-US"), weknora: bundledCopy("deerflow-extension-weknora", "en-US"), example: bundledCopy("deerflow-extension-example", "en-US"), }, diff --git a/frontend/src/core/i18n/locales/types.ts b/frontend/src/core/i18n/locales/types.ts index 0462f16404..754c50ed85 100644 --- a/frontend/src/core/i18n/locales/types.ts +++ b/frontend/src/core/i18n/locales/types.ts @@ -154,6 +154,7 @@ export interface Translations { | "knowledgePlatform" | "knowledgeCenter" | "skillEvolution" + | "runPostmortem" | "weknora" | "lightrag" | "example", diff --git a/frontend/src/core/i18n/locales/zh-CN.ts b/frontend/src/core/i18n/locales/zh-CN.ts index a0ec141433..1bde546352 100644 --- a/frontend/src/core/i18n/locales/zh-CN.ts +++ b/frontend/src/core/i18n/locales/zh-CN.ts @@ -193,6 +193,7 @@ export const zhCN: Translations = { "zh-CN", ), lightrag: bundledCopy("deerflow-extension-lightrag", "zh-CN"), + runPostmortem: bundledCopy("deerflow-extension-run-postmortem", "zh-CN"), weknora: bundledCopy("deerflow-extension-weknora", "zh-CN"), example: bundledCopy("deerflow-extension-example", "zh-CN"), },