Skip to content

"Vibe-Trading: Your Personal Trading Agent"

feat(scheduled-research): persist each run's verdict on the job and surface it in the list

Yufeng Hedc9ec417b7d8
diff --git a/agent/src/api/scheduled_routes.py b/agent/src/api/scheduled_routes.py
index 55acc7d47..9e285c2de 100644
--- a/agent/src/api/scheduled_routes.py
+++ b/agent/src/api/scheduled_routes.py
@@ -300,6 +300,7 @@ class ScheduledRunResponse(BaseModel):
delivery_status: str = "none"
delivery_error: Optional[str] = None
delivery_updated_at: Optional[int] = None
+ last_verdict: Optional[Dict[str, Any]] = None
def _job_to_response(job: ScheduledResearchJob) -> "ScheduledRunResponse":
@@ -317,8 +318,10 @@ def _job_to_response(job: ScheduledResearchJob) -> "ScheduledRunResponse":
"""
payload = job.to_dict()
delivery = payload.pop("delivery", {}) or {}
+ last_verdict = payload.pop("last_verdict", None)
return ScheduledRunResponse(
**payload,
+ last_verdict=last_verdict,
delivery_status=delivery.get("status", "none"),
delivery_error=delivery.get("error"),
delivery_updated_at=delivery.get("updated_at"),
diff --git a/agent/src/scheduled_research/executor.py b/agent/src/scheduled_research/executor.py
index 6889a6e00..87b7bcaf3 100644
--- a/agent/src/scheduled_research/executor.py
+++ b/agent/src/scheduled_research/executor.py
@@ -27,6 +27,13 @@ from src.scheduled_research.models import (
validate_timezone,
)
from src.scheduled_research.store import ScheduledResearchJobStore
+from src.scheduled_research.verdict import (
+ VerdictRecord,
+ outcome_of,
+ parse_verdict_section,
+)
+
+from dataclasses import replace as _dc_replace
from src.tools.redaction import redact_internal_paths, redact_text
logger = logging.getLogger(__name__)
@@ -416,17 +423,27 @@ class ScheduledResearchExecutor:
dispatch_error: Exception | None = None
try:
session_id = await self._dispatch(job)
- if job.delivery_channel and isinstance(session_id, str) and session_id:
- # Arm the outbox in the same write that records the firing.
- # The row exists before anything can be sent, so a crash can
- # only ever lose the *speed* of delivery, never the fact that
- # one is owed.
- job.delivery = DeliveryRecord(
- status=DeliveryStatus.PENDING,
- session_id=session_id,
- key=f"{job.id}:{session_id}:{job.delivery_channel}",
- updated_at=now_ms,
- )
+ if isinstance(session_id, str) and session_id:
+ if job.delivery_channel:
+ # Arm the outbox in the same write that records the firing.
+ # The row exists before anything can be sent, so a crash can
+ # only ever lose the *speed* of delivery, never the fact that
+ # one is owed.
+ job.delivery = DeliveryRecord(
+ status=DeliveryStatus.PENDING,
+ session_id=session_id,
+ key=f"{job.id}:{session_id}:{job.delivery_channel}",
+ updated_at=now_ms,
+ )
+ else:
+ # No delivery owed, but the verdict sweep still needs the
+ # link from this job to its run: the session id rides the
+ # record with an explicit NONE so the outbox never picks it.
+ job.delivery = DeliveryRecord(
+ status=DeliveryStatus.NONE,
+ session_id=session_id,
+ updated_at=now_ms,
+ )
except asyncio.CancelledError:
raise
except Exception as exc:
@@ -541,15 +558,25 @@ class ScheduledResearchExecutor:
Returns:
The number of rows whose state changed.
"""
- if self._briefing_reader is None or self._channel_sender is None:
+ if self._briefing_reader is None:
return 0
changed = 0
now = self._now_fn()
for job in list(self._store.load().values()):
+ if not job.delivery.session_id:
+ continue
+ if job.delivery.status is DeliveryStatus.NONE:
+ # No briefing is owed to a channel, but this sweep is the only
+ # terminal-observer a channel-less monitor has: read the run's
+ # end state here and persist its verdict once it lands.
+ changed += self._record_verdict_if_terminal(job, now)
+ continue
+ if not job.delivery_channel:
+ continue
if not self._delivery_is_eligible(job, now):
continue
- if not job.delivery.session_id or not job.delivery_channel:
+ if self._channel_sender is None:
continue
try:
outcome = self._briefing_reader(job.delivery.session_id)
@@ -597,10 +624,68 @@ class ScheduledResearchExecutor:
current.delivery.status = DeliveryStatus.SENT
current.delivery.error = None
current.delivery.updated_at = self._now_fn()
+ # The verdict rides the same write as the terminal delivery state,
+ # never a second pass over the job (#1140's clobbering lesson).
+ if (
+ current.last_verdict is None
+ or current.last_verdict.session_id != current.delivery.session_id
+ ):
+ self._record_verdict_on(current, current.delivery.session_id, text, now)
self._store.upsert(current, validate=False)
changed += 1
return changed
+ def _record_verdict_on(
+ self, job: ScheduledResearchJob, session_id: str, text: str, now_ms: int
+ ) -> None:
+ """Write the run's verdict record onto ``job``, shifting the prior one.
+
+ The previous record embeds one level only: a verdict chain any deeper
+ is noise for the list view.
+ """
+ parse, items = parse_verdict_section(text)
+ previous = job.last_verdict
+ if previous is not None:
+ previous = _dc_replace(previous, previous=None)
+ job.last_verdict = VerdictRecord(
+ session_id=session_id,
+ recorded_at=now_ms,
+ parse=parse,
+ outcome=outcome_of(items),
+ items=items,
+ previous=previous,
+ )
+
+ def _record_verdict_if_terminal(self, job: ScheduledResearchJob, now_ms: int) -> int:
+ """Persist the run's verdict once its session reaches a terminal state.
+
+ Channel-less jobs have no outbox, so this sweep is the only place their
+ terminal briefing is ever read. In-flight runs return ``None`` from the
+ briefing reader and are left for a later pass; failed or cancelled runs
+ produce no briefing, so the prior verdict simply stays visible as stale.
+
+ Returns:
+ 1 when the job record changed, else 0.
+ """
+ session_id = job.delivery.session_id
+ if not session_id:
+ return 0
+ if job.last_verdict is not None and job.last_verdict.session_id == session_id:
+ return 0 # this firing is already recorded
+ try:
+ outcome = self._briefing_reader(session_id) if self._briefing_reader else None
+ except Exception:
+ logger.error("verdict read failed for job %s", job.id, exc_info=True)
+ return 0
+ if outcome is None:
+ return 0
+ status, text = outcome
+ if status != "completed":
+ return 0
+ self._record_verdict_on(job, session_id, text, now_ms)
+ self._store.upsert(job, validate=False)
+ return 1
+
def _mark_delivery_failed(
self, job: ScheduledResearchJob, exc: Exception, *, retryable: bool
) -> None:
diff --git a/agent/src/scheduled_research/models.py b/agent/src/scheduled_research/models.py
index 82f5605da..2adf63f02 100644
--- a/agent/src/scheduled_research/models.py
+++ b/agent/src/scheduled_research/models.py
@@ -16,6 +16,8 @@ from enum import Enum
from typing import Any, Dict, Optional, Set
from zoneinfo import ZoneInfo
+from .verdict import VerdictRecord
+
logger = logging.getLogger(__name__)
# ---------------------------------------------------------------------------
@@ -296,6 +298,28 @@ class DeliveryRecord:
# ---------------------------------------------------------------------------
+def _verdict_record_or_none(data: Any, job_id: str) -> Optional[VerdictRecord]:
+ """Parse a persisted last_verdict, degrading an unreadable one to None.
+
+ A malformed verdict must never take the job down with it, the same way an
+ unusable timezone degrades to UTC rather than quarantining the record.
+ """
+ if data is None:
+ return None
+ if not isinstance(data, dict):
+ logger.warning(
+ "scheduled research job %s drops a non-dict last_verdict %r", job_id, data
+ )
+ return None
+ try:
+ return VerdictRecord.from_dict(data)
+ except (KeyError, TypeError, ValueError) as exc:
+ logger.warning(
+ "scheduled research job %s drops an unreadable last_verdict: %r", job_id, exc
+ )
+ return None
+
+
@dataclass
class ScheduledResearchJob:
"""Mutable persisted state for a scheduled research / backtest job.
@@ -326,6 +350,9 @@ class ScheduledResearchJob:
delivery: Outbox state for the most recent firing. Separate from
``status`` because dispatch returns at enqueue: a job can be
COMPLETED (accepted) while its briefing is still PENDING delivery.
+ last_verdict: The latest run's parsed verdict record, or ``None`` when
+ no completed run produced one yet. Embedded with its own
+ ``previous`` so the list view renders a delta in one query.
"""
id: str
@@ -343,6 +370,7 @@ class ScheduledResearchJob:
delivery_channel: Optional[str] = None
delivery_target: Optional[str] = None
delivery: DeliveryRecord = field(default_factory=DeliveryRecord)
+ last_verdict: Optional[VerdictRecord] = None
def to_dict(self) -> Dict[str, Any]:
"""Serialize to a plain JSON-serializable dict.
@@ -367,6 +395,7 @@ class ScheduledResearchJob:
"delivery_channel": self.delivery_channel,
"delivery_target": self.delivery_target,
"delivery": self.delivery.to_dict(),
+ "last_verdict": self.last_verdict.to_dict() if self.last_verdict else None,
}
@classmethod
@@ -450,4 +479,5 @@ class ScheduledResearchJob:
delivery_channel=delivery_channel,
delivery_target=delivery_target,
delivery=DeliveryRecord.from_dict(data.get("delivery")),
+ last_verdict=_verdict_record_or_none(data.get("last_verdict"), job_id),
)
diff --git a/agent/src/scheduled_research/playbooks/a-share-money-flow.md b/agent/src/scheduled_research/playbooks/a-share-money-flow.md
index c5b764f62..c523d29cc 100644
--- a/agent/src/scheduled_research/playbooks/a-share-money-flow.md
+++ b/agent/src/scheduled_research/playbooks/a-share-money-flow.md
@@ -98,6 +98,12 @@ Markdown, in this order:
6. `## Margin balances` — aggregate change and any notable per-stock change.
7. `## Watch list cross-reference` — omit when no watch list was supplied.
8. `## Data gaps` — always present; write `none` when nothing was missing.
+9. `## Verdict` — the machine-readable tail, and the only section
+ nothing may follow. One line per symbol tracked this run:
+ `- SYMBOL: STATE - one short reason`, with STATE one of `ACTIVE`, `QUIET`.
+ When nothing moved, write the heading with no lines under it; that
+ is a real answer, not an absence. This section reports state, not
+ advice: the Boundaries above still apply.
## Boundaries
diff --git a/agent/src/scheduled_research/playbooks/earnings-season-tracker.md b/agent/src/scheduled_research/playbooks/earnings-season-tracker.md
index 1b5dcc2ff..32a8276fe 100644
--- a/agent/src/scheduled_research/playbooks/earnings-season-tracker.md
+++ b/agent/src/scheduled_research/playbooks/earnings-season-tracker.md
@@ -97,6 +97,12 @@ Markdown, in this order:
4. `## Announcements since last report` — dated, one line each.
5. `## Reporting after the horizon` — symbol and date only.
6. `## Data gaps` — always present; write `none` when nothing was missing.
+7. `## Verdict` — the machine-readable tail, and the only section
+ nothing may follow. One line per symbol tracked this run:
+ `- SYMBOL: STATE - one short reason`, with STATE one of `FILED`, `REVISED`, `QUIET`.
+ When nothing moved, write the heading with no lines under it; that
+ is a real answer, not an absence. This section reports state, not
+ advice: the Boundaries above still apply.
## Boundaries
diff --git a/agent/src/scheduled_research/playbooks/institutional-holdings-diff.md b/agent/src/scheduled_research/playbooks/institutional-holdings-diff.md
index d29e7979e..811949e83 100644
--- a/agent/src/scheduled_research/playbooks/institutional-holdings-diff.md
+++ b/agent/src/scheduled_research/playbooks/institutional-holdings-diff.md
@@ -101,6 +101,12 @@ Markdown, in this order:
6. `## Limitations` — the as-of lag and the instrument-coverage limitation,
stated in two lines.
7. `## Data gaps` — always present; write `none` when nothing was missing.
+8. `## Verdict` — the machine-readable tail, and the only section
+ nothing may follow. One line per symbol tracked this run:
+ `- SYMBOL: STATE - one short reason`, with STATE one of `CHANGED`, `UNCHANGED`.
+ When nothing moved, write the heading with no lines under it; that
+ is a real answer, not an absence. This section reports state, not
+ advice: the Boundaries above still apply.
## Boundaries
diff --git a/agent/src/scheduled_research/playbooks/portfolio-checkup.md b/agent/src/scheduled_research/playbooks/portfolio-checkup.md
index 859798ce8..7b4cf9f93 100644
--- a/agent/src/scheduled_research/playbooks/portfolio-checkup.md
+++ b/agent/src/scheduled_research/playbooks/portfolio-checkup.md
@@ -99,6 +99,12 @@ Markdown, in this order:
5. `## Drawdown` — maximum drawdown, its date range, current distance from
peak; the same for the benchmark.
6. `## Data gaps` — always present; write `none` when nothing was missing.
+7. `## Verdict` — the machine-readable tail, and the only section
+ nothing may follow. One line per symbol tracked this run:
+ `- SYMBOL: STATE - one short reason`, with STATE one of `DRIFT`, `FLAT`.
+ When nothing moved, write the heading with no lines under it; that
+ is a real answer, not an absence. This section reports state, not
+ advice: the Boundaries above still apply.
## Boundaries
diff --git a/agent/src/scheduled_research/playbooks/premarket-brief.md b/agent/src/scheduled_research/playbooks/premarket-brief.md
index 64e7ebb94..838fbbfc0 100644
--- a/agent/src/scheduled_research/playbooks/premarket-brief.md
+++ b/agent/src/scheduled_research/playbooks/premarket-brief.md
@@ -87,6 +87,12 @@ Markdown, in this order:
average, and any dated news naming it.
4. `## On today's calendar` — scheduled releases and events, with local times.
5. `## Data gaps` — always present; write `none` when nothing was missing.
+6. `## Verdict` — the machine-readable tail, and the only section
+ nothing may follow. One line per symbol tracked this run:
+ `- SYMBOL: STATE - one short reason`, with STATE one of `HOT`, `MIXED`, `QUIET`.
+ When nothing moved, write the heading with no lines under it; that
+ is a real answer, not an absence. This section reports state, not
+ advice: the Boundaries above still apply.
Keep the whole brief under roughly 700 words.
diff --git a/agent/src/scheduled_research/verdict.py b/agent/src/scheduled_research/verdict.py
new file mode 100644
index 000000000..f70aa7aa8
--- /dev/null
+++ b/agent/src/scheduled_research/verdict.py
@@ -0,0 +1,138 @@
+"""The machine-readable `## Verdict` tail of a scheduled-research briefing.
+
+Playbooks declare the section as their final output block: one line per
+tracked symbol, ``- SYMBOL: STATE - one short reason``, where STATE is a
+single upper-case token the playbook declares. The heading with no lines
+under it is a real answer ("no calls this run"), not a missing one.
+
+Parsing is strict on purpose: the Market Watch list renders this record
+without ever re-reading the free text, so anything malformed must degrade to
+``contract_violation`` rather than guess.
+"""
+
+from __future__ import annotations
+
+import re
+from dataclasses import dataclass, field
+from typing import Any, Dict, List, Optional
+
+#: Parse states persisted on the record.
+PARSE_OK = "ok"
+PARSE_NO_SECTION = "no_verdict_section"
+PARSE_CONTRACT_VIOLATION = "contract_violation"
+
+_HEADING_RE = re.compile(r"^##\s+Verdict\s*$", re.MULTILINE)
+_NEXT_HEADING_RE = re.compile(r"^##\s", re.MULTILINE)
+#: `- SYMBOL: STATE - reason` (reason optional). STATE stays an opaque token
+#: to the parser; each playbook declares its own small vocabulary.
+_ITEM_RE = re.compile(
+ r"^-\s+([A-Z0-9][A-Z0-9._-]*)\s*:\s*([A-Z][A-Z0-9-]*)(?:\s+-\s+(.+?))?\s*$"
+)
+
+
+@dataclass
+class VerdictItem:
+ """One tracked symbol's verdict line."""
+
+ symbol: str
+ state: str
+ reason: str = ""
+
+ def to_dict(self) -> Dict[str, Any]:
+ return {"symbol": self.symbol, "state": self.state, "reason": self.reason}
+
+ @classmethod
+ def from_dict(cls, data: Dict[str, Any]) -> "VerdictItem":
+ return cls(
+ symbol=str(data.get("symbol", "")),
+ state=str(data.get("state", "")),
+ reason=str(data.get("reason", "")),
+ )
+
+
+@dataclass
+class VerdictRecord:
+ """A run's parsed verdict, persisted on the job at its terminal state.
+
+ Attributes:
+ session_id: The session whose terminal briefing this was parsed from.
+ recorded_at: Epoch-millisecond timestamp of the write; the UI leans on
+ it to render stale verdicts as stale.
+ parse: One of the ``PARSE_*`` states. ``no_verdict_section`` is the
+ permanent state of ad-hoc prompts and renders as nothing, never as
+ a warning.
+ outcome: Server-derived headline: ``no_calls`` when nothing was
+ tracked, the single shared state when every item agrees, else
+ ``mixed``.
+ items: The parsed symbol lines, empty exactly when parse is ``ok``
+ and nothing was tracked.
+ previous: The prior run's record, embedded at write time so the list
+ can render a delta without a second query. One level deep only.
+ """
+
+ session_id: str
+ recorded_at: int
+ parse: str
+ outcome: str
+ items: List[VerdictItem] = field(default_factory=list)
+ previous: Optional["VerdictRecord"] = None
+
+ def to_dict(self) -> Dict[str, Any]:
+ return {
+ "session_id": self.session_id,
+ "recorded_at": self.recorded_at,
+ "parse": self.parse,
+ "outcome": self.outcome,
+ "items": [item.to_dict() for item in self.items],
+ "previous": self.previous.to_dict() if self.previous else None,
+ }
+
+ @classmethod
+ def from_dict(cls, data: Dict[str, Any]) -> "VerdictRecord":
+ previous = data.get("previous")
+ return cls(
+ session_id=str(data.get("session_id", "")),
+ recorded_at=int(data.get("recorded_at", 0)),
+ parse=str(data.get("parse", PARSE_NO_SECTION)),
+ outcome=str(data.get("outcome", "no_calls")),
+ items=[VerdictItem.from_dict(i) for i in data.get("items", [])],
+ previous=cls.from_dict(previous) if isinstance(previous, dict) else None,
+ )
+
+
+def parse_verdict_section(briefing: str) -> tuple[str, List[VerdictItem]]:
+ """Parse the ``## Verdict`` tail of a terminal briefing.
+
+ Returns:
+ ``(parse_state, items)``. ``no_verdict_section`` when no such heading
+ exists, ``contract_violation`` when it exists but a body line does not
+ match the contract, and ``ok`` otherwise, including an empty section.
+ """
+ heading = _HEADING_RE.search(briefing)
+ if heading is None:
+ return PARSE_NO_SECTION, []
+
+ body = briefing[heading.end() :]
+ next_heading = _NEXT_HEADING_RE.search(body)
+ if next_heading is not None:
+ body = body[: next_heading.start()]
+
+ items: List[VerdictItem] = []
+ for line in body.split("\n"):
+ line = line.strip()
+ if not line:
+ continue
+ match = _ITEM_RE.match(line)
+ if match is None:
+ return PARSE_CONTRACT_VIOLATION, []
+ symbol, state, reason = match.groups()
+ items.append(VerdictItem(symbol=symbol, state=state, reason=reason or ""))
+ return PARSE_OK, items
+
+
+def outcome_of(items: List[VerdictItem]) -> str:
+ """The server-derived headline for a parsed item list."""
+ if not items:
+ return "no_calls"
+ states = {item.state for item in items}
+ return states.pop() if len(states) == 1 else "mixed"
diff --git a/agent/tests/test_scheduled_routes.py b/agent/tests/test_scheduled_routes.py
index 6131dfa79..7b0f71891 100644
--- a/agent/tests/test_scheduled_routes.py
+++ b/agent/tests/test_scheduled_routes.py
@@ -409,3 +409,45 @@ def test_create_rejects_a_blank_timezone_for_both_schedule_forms(
json={"prompt": "scan", "schedule": schedule, "timezone": " "},
)
assert response.status_code == 422, schedule
+
+
+def test_list_carries_the_last_verdict_record(
+ client: TestClient, store: ScheduledResearchJobStore
+):
+ from src.scheduled_research.verdict import VerdictItem, VerdictRecord
+
+ verdict = VerdictRecord(
+ session_id="sess-9",
+ recorded_at=1_700_000_100_000,
+ parse="ok",
+ outcome="DRIFT",
+ items=[VerdictItem(symbol="600519.SH", state="DRIFT", reason="band crossed")],
+ previous=VerdictRecord(
+ session_id="sess-8",
+ recorded_at=1_700_000_000_000,
+ parse="ok",
+ outcome="no_calls",
+ items=[],
+ ),
+ )
+ _seed(store, id="with-verdict", last_verdict=verdict)
+
+ response = client.get("/scheduled-runs")
+
+ assert response.status_code == 200
+ (row,) = response.json()
+ assert row["last_verdict"]["outcome"] == "DRIFT"
+ assert row["last_verdict"]["items"][0]["symbol"] == "600519.SH"
+ assert row["last_verdict"]["previous"]["outcome"] == "no_calls"
+
+
+def test_list_omits_verdict_when_never_recorded(
+ client: TestClient, store: ScheduledResearchJobStore
+):
+ _seed(store, id="no-verdict")
+
+ response = client.get("/scheduled-runs")
+
+ assert response.status_code == 200
+ (row,) = response.json()
+ assert row["last_verdict"] is None
diff --git a/agent/tests/test_verdict.py b/agent/tests/test_verdict.py
new file mode 100644
index 000000000..3881f21f1
--- /dev/null
+++ b/agent/tests/test_verdict.py
@@ -0,0 +1,205 @@
+"""Tests for the scheduled-research verdict record and its parser."""
+
+from __future__ import annotations
+
+import asyncio
+from pathlib import Path
+
+from src.scheduled_research.executor import ScheduledResearchExecutor
+from src.scheduled_research.models import (
+ DeliveryRecord,
+ DeliveryStatus,
+ JobStatus,
+ ScheduledResearchJob,
+)
+from src.scheduled_research.store import ScheduledResearchJobStore
+from src.scheduled_research.verdict import (
+ PARSE_CONTRACT_VIOLATION,
+ PARSE_NO_SECTION,
+ PARSE_OK,
+ VerdictRecord,
+ outcome_of,
+ parse_verdict_section,
+)
+
+
+def test_no_verdict_section() -> None:
+ parse, items = parse_verdict_section("## Book summary\nall quiet\n## Data gaps\nnone\n")
+ assert parse == PARSE_NO_SECTION
+ assert items == []
+
+
+def test_verdict_section_with_items() -> None:
+ text = (
+ "## Overnight tape\nstuff\n"
+ "## Verdict\n"
+ "- 600519.SH: FLAT - weight stayed inside the band\n"
+ "- 0700.HK: DRIFT - weight crossed the stated band\n"
+ "\n"
+ "## Data gaps\n"
+ "none\n"
+ )
+ parse, items = parse_verdict_section(text)
+ assert parse == PARSE_OK
+ assert [(i.symbol, i.state, i.reason) for i in items] == [
+ ("600519.SH", "FLAT", "weight stayed inside the band"),
+ ("0700.HK", "DRIFT", "weight crossed the stated band"),
+ ]
+
+
+def test_verdict_section_empty_is_a_real_answer() -> None:
+ parse, items = parse_verdict_section("## Book summary\n...\n## Verdict\n\n## Data gaps\nnone\n")
+ assert parse == PARSE_OK
+ assert items == []
+ assert outcome_of(items) == "no_calls"
+
+
+def test_verdict_section_stops_at_next_heading() -> None:
+ text = "## Verdict\n- AAPL: QUIET - nothing moved\n## Data gaps\n- not: an item\n"
+ parse, items = parse_verdict_section(text)
+ assert parse == PARSE_OK
+ assert len(items) == 1
+
+
+def test_malformed_line_fails_closed() -> None:
+ parse, items = parse_verdict_section("## Verdict\nthis line is not a contract line\n")
+ assert parse == PARSE_CONTRACT_VIOLATION
+ assert items == []
+
+
+def test_reason_is_optional() -> None:
+ parse, items = parse_verdict_section("## Verdict\n- TSLA: HOT\n")
+ assert parse == PARSE_OK
+ assert items[0].reason == ""
+
+
+def test_outcome_mixed_and_uniform() -> None:
+ _, items = parse_verdict_section("## Verdict\n- A: FLAT - x\n- B: FLAT - y\n")
+ assert outcome_of(items) == "FLAT"
+ _, mixed = parse_verdict_section("## Verdict\n- A: FLAT - x\n- B: DRIFT - y\n")
+ assert outcome_of(mixed) == "mixed"
+
+
+def _record(session: str, at: int, symbol: str = "AAPL") -> VerdictRecord:
+ return VerdictRecord(
+ session_id=session,
+ recorded_at=at,
+ parse=PARSE_OK,
+ outcome="FLAT",
+ items=[],
+ )
+
+
+def test_verdict_record_serde_roundtrip() -> None:
+ record = _record("s2", 2000)
+ record.previous = _record("s1", 1000)
+ restored = VerdictRecord.from_dict(record.to_dict())
+ assert restored.session_id == "s2"
+ assert restored.previous is not None and restored.previous.session_id == "s1"
+ assert restored.previous.previous is None
+
+
+def test_verdict_record_from_missing_fields_is_lenient() -> None:
+ restored = VerdictRecord.from_dict({})
+ assert restored.parse == PARSE_NO_SECTION
+ assert restored.items == []
+
+
+def _job_with_session(job_id: str, session_id: str) -> ScheduledResearchJob:
+ return ScheduledResearchJob(
+ id=job_id,
+ prompt=f"prompt for {job_id}",
+ schedule="60000",
+ status=JobStatus.COMPLETED,
+ delivery=DeliveryRecord(status=DeliveryStatus.NONE, session_id=session_id),
+ )
+
+
+def test_sweep_records_verdict_for_channel_less_job(tmp_path: Path) -> None:
+ store = ScheduledResearchJobStore(path=tmp_path / "jobs.json")
+ store.upsert(_job_with_session("job-1", "sess-1"), validate=False)
+ briefing = "## Book summary\n...\n## Verdict\n- 600519.SH: DRIFT - band crossed\n"
+
+ def read_briefing(session_id: str):
+ assert session_id == "sess-1"
+ return ("completed", briefing)
+
+ async def scenario() -> int:
+ executor = ScheduledResearchExecutor(store, _noop_dispatch, briefing_reader=read_briefing)
+ return await executor.sweep_deliveries()
+
+ changed = asyncio.run(scenario())
+ assert changed == 1
+ saved = store.get("job-1")
+ assert saved is not None and saved.last_verdict is not None
+ assert saved.last_verdict.session_id == "sess-1"
+ assert saved.last_verdict.parse == PARSE_OK
+ assert saved.last_verdict.outcome == "DRIFT"
+ assert saved.last_verdict.items[0].symbol == "600519.SH"
+ assert saved.last_verdict.previous is None
+
+
+def test_sweep_verdict_is_written_once_per_firing(tmp_path: Path) -> None:
+ store = ScheduledResearchJobStore(path=tmp_path / "jobs.json")
+ store.upsert(_job_with_session("job-1", "sess-1"), validate=False)
+
+ def read_briefing(session_id: str):
+ return ("completed", "## Verdict\n- A: QUIET - x\n")
+
+ async def scenario() -> tuple[int, int]:
+ executor = ScheduledResearchExecutor(store, _noop_dispatch, briefing_reader=read_briefing)
+ first = await executor.sweep_deliveries()
+ second = await executor.sweep_deliveries()
+ return first, second
+
+ first, second = asyncio.run(scenario())
+ assert (first, second) == (1, 0)
+
+
+def test_sweep_shifts_previous_verdict_one_level(tmp_path: Path) -> None:
+ store = ScheduledResearchJobStore(path=tmp_path / "jobs.json")
+ store.upsert(_job_with_session("job-1", "sess-1"), validate=False)
+ briefings = {
+ "sess-1": ("completed", "## Verdict\n- A: QUIET - first\n"),
+ "sess-2": ("completed", "## Verdict\n- A: DRIFT - second\n"),
+ }
+
+ def read_briefing(session_id: str):
+ return briefings[session_id]
+
+ async def scenario() -> None:
+ executor = ScheduledResearchExecutor(store, _noop_dispatch, briefing_reader=read_briefing)
+ await executor.sweep_deliveries()
+ job = store.get("job-1")
+ assert job is not None
+ job.delivery = DeliveryRecord(status=DeliveryStatus.NONE, session_id="sess-2")
+ store.upsert(job, validate=False)
+ await executor.sweep_deliveries()
+
+ asyncio.run(scenario())
+ saved = store.get("job-1")
+ assert saved is not None and saved.last_verdict is not None
+ assert saved.last_verdict.session_id == "sess-2"
+ previous = saved.last_verdict.previous
+ assert previous is not None and previous.session_id == "sess-1"
+ assert previous.previous is None # the chain stays one level deep
+
+
+def test_sweep_leaves_verdict_alone_while_in_flight(tmp_path: Path) -> None:
+ store = ScheduledResearchJobStore(path=tmp_path / "jobs.json")
+ store.upsert(_job_with_session("job-1", "sess-1"), validate=False)
+
+ def read_briefing(session_id: str):
+ return None # still running
+
+ async def scenario() -> int:
+ executor = ScheduledResearchExecutor(store, _noop_dispatch, briefing_reader=read_briefing)
+ return await executor.sweep_deliveries()
+
+ assert asyncio.run(scenario()) == 0
+ saved = store.get("job-1")
+ assert saved is not None and saved.last_verdict is None
+
+
+async def _noop_dispatch(job: ScheduledResearchJob) -> None:
+ return None