AI agent skill that researches any topic across Reddit, X, YouTube, HN, Polymarket, and the web - then synthesizes a grounded summary
Python ai-promptsai-skillblueskyclaudeclaude-codeclawhubdeep-researchhackernewsinstagramopenclawpolymarketrecencyredditresearchsocial-mediatiktoktrendstwitterweb-searchyoutube
feat(schema): versioned agent JSON export profile (--emit=json v1.0, raw fallback) (#810)
Matt Van Horn7abcb9d1086a
diff --git a/CONFIGURATION.md b/CONFIGURATION.mdindex 2668c788..c7683908 100644--- a/CONFIGURATION.md+++ b/CONFIGURATION.md@@ -43,11 +43,12 @@ The engine's `.env` reader doesn't expand `$HOME` — only the tilde, via `Path(- `--save-dir <path>` - one-off output location. **Flag wins over env var.** If neither flag nor env var is set, the engine does not write a file (DB persistence is independent — see `LAST30DAYS_STORE` below).- `--output <file>` - write the rendered output to an exact file path, using the format selected by `--emit`.+- `--json-profile {agent,raw}` - select the research JSON shape used with `--emit=json`. `agent` is the default, versioned workflow contract; `raw` preserves the full internal `Report` dump for debugging and power users. See the [JSON export reference](docs/reference/json-export.md).- `--save-suffix <name>` - distinguish runs of the same topic (e.g. per client: `--save-suffix=acme`).- `--no-browser-cookies` - hard-disable browser-cookie extraction for this run, even when `FROM_BROWSER` is configured. MCP and folder-mode hosts use this for safe defaults.- `--publish-html` - with `--emit=html`, publish the rendered HTML to `ht-ml.app` after local output/save-dir writes. This is explicit opt-in only; pages are public by default.- `--publish-password <password>` - optional shared password for `--publish-html`. Prefer `LAST30DAYS_PUBLISH_PASSWORD=<password>` instead so the password is not visible in the process list or shell history. Use a unique non-personal password; never reuse the user's own password. The provider's update key is treated as secret and is not written to stdout, HTML, raw output, or `.publish.json` metadata.-- `--preflight` - print a human-readable permission preflight. It reports config source, project config trust/ignore state, browser-cookie plan, planned writes, optional commands, source availability, and endpoint overrides without reading browser cookies, writing setup/config/report files, or running research. Add `--emit=json` for machine-readable preflight JSON; use `--diagnose` when you need the full source diagnostic JSON.+- `--preflight` - print a human-readable permission preflight. It reports config source, project config trust/ignore state, browser-cookie plan, planned writes, optional commands, source availability, and endpoint overrides without reading browser cookies, writing setup/config/report files, or running research. Add `--emit=json` for the separate machine-readable preflight contract (`--json-profile` does not change it); use `--diagnose` when you need the full source diagnostic JSON.- `--welcome` - print the first-run welcome text (engine-owned; the skill relays it verbatim on first run). Safe: prints and exits, no reads or writes.- `setup --github-start` / `setup --github-poll` - the two-command ScrapeCreators GitHub device-auth split. `--github-start` submits the device flow, copies the code to the clipboard, opens the browser, and returns the code immediately (foreground); `--github-poll` waits for you to authorize and persists the key. `setup --github` still runs both in one shot for back-compat.@@ -85,7 +86,7 @@ Override the global location with `LAST30DAYS_CONFIG_DIR=/path` (or `LAST30DAYS_The project-scoped file is useful for **intentional per-client setups**: drop a `.claude/last30days.env` into each client folder (`SCRAPECREATORS_API_KEY`, `INCLUDE_SOURCES`, `LAST30DAYS_MEMORY_DIR`, `BSKY_HANDLE`, etc), then opt in with `LAST30DAYS_TRUST_PROJECT_CONFIG=1` from your shell or `~/.config/last30days/.env`. Folder-mode hosts such as Codex desktop do not trust hidden project config by default, and discovery stops at the git root so unrelated parent folders cannot silently influence runs.-**`LAST30DAYS_API_KEY`** + **`LAST30DAYS_API_BASE`** - optional remote-API backend. Set BOTH to route research through a remote API endpoint instead of running the local sources: `LAST30DAYS_API_BASE` is the endpoint (there is no built-in default), and `LAST30DAYS_API_KEY` is the bearer key for it. When both are set (and `--mock` is not passed), the engine submits the topic to that endpoint, polls with progress on stderr, and prints the server's report; none of the per-source keys below are used for that run. Leave either unset to run local sources exactly as normal. Unlike the other keys here, these two are read only from the **process environment** (export them in your shell or host config) - they are deliberately not loaded from the `.env` files above, so a project-scoped `.env` can never silently redirect research to a remote endpoint.+**`LAST30DAYS_API_KEY`** + **`LAST30DAYS_API_BASE`** - optional remote-API backend. Set BOTH to route research through a remote API endpoint instead of running the local sources: `LAST30DAYS_API_BASE` is the endpoint (there is no built-in default), and `LAST30DAYS_API_KEY` is the bearer key for it. When both are set (and `--mock` is not passed), the engine submits the topic to that endpoint, polls with progress on stderr, and prints the server's report; none of the per-source keys below are used for that run. Leave either unset to run local sources exactly as normal. Unlike the other keys here, these two are read only from the **process environment** (export them in your shell or host config) - they are deliberately not loaded from the `.env` files above, so a project-scoped `.env` can never silently redirect research to a remote endpoint. The remote endpoint does not return the local `Report` needed for the versioned agent JSON profile; use `--emit=json --json-profile=raw` for its existing server-response JSON contract.**Source-by-source** - what each key unlocks:diff --git a/README.md b/README.mdindex 65b02547..57ae8222 100644--- a/README.md+++ b/README.md@@ -318,6 +318,8 @@ Two things you'll likely want to know on day one:**Where research files are saved.** `LAST30DAYS_MEMORY_DIR` defaults to `~/Documents/Last30Days/` (Windows: `C:\Users\<you>\Documents\Last30Days\`). Override by setting that env var to any path in your shell, or `--save-dir <path>` per run. Use `--output <file>` when you need the rendered result at an exact path, using the format selected by `--emit`. Use `--save-suffix=<name>` to keep multiple variations of the same topic separate (e.g. per client). Each `--save-dir` run produces `<slug>-raw[-suffix].md`. Run `python3 skills/last30days/scripts/last30days.py --preflight` to review planned writes before a research run.+**Structured output for agents and workflows.** Ask `/last30days` for machine-readable JSON to receive the stable, versioned agent profile. For direct engine use in scripts or development, run `python3 skills/last30days/scripts/last30days.py "AI coding agents" --emit=json`; add `--json-profile=raw` only when you need the unversioned internal `Report` dump. See the [JSON export field reference and versioning policy](docs/reference/json-export.md).+**Trend monitoring across runs.** The default mode produces a fresh markdown snapshot per run. To accumulate findings over time, add `--store` to persist into a SQLite database, then use [`scripts/watchlist.py`](skills/last30days/scripts/watchlist.py) for scheduled runs (with optional Slack / webhook delivery on new findings) and [`scripts/briefing.py`](skills/last30days/scripts/briefing.py) for daily / weekly digests. The full cadence pattern is in [CONFIGURATION.md](CONFIGURATION.md#trend-monitoring-store--watchlist--briefings).Per-client wrapper scripts, custom category-peer subreddits, and the experimental beta channel for in-progress customizations are also documented in [CONFIGURATION.md](CONFIGURATION.md).diff --git a/docs/reference/json-export.md b/docs/reference/json-export.mdnew file mode 100644index 00000000..f7b6775c--- /dev/null+++ b/docs/reference/json-export.md@@ -0,0 +1,111 @@+# Agent JSON export++The agent JSON profile is the stable machine-readable research contract for downstream agents, scripts, dashboards, and workflow tools. Ask the slash command for machine-readable JSON:++```text+/last30days AI coding agents — return the versioned agent JSON export+```++For direct engine use in scripts, cron jobs, or development, use:++```bash+python3 skills/last30days/scripts/last30days.py "AI coding agents" --emit=json+python3 skills/last30days/scripts/last30days.py "AI coding agents" --emit=json --output results.json+```++`--emit=json` defaults to `--json-profile=agent`. The full internal report remains available for debugging and power users:++```bash+python3 skills/last30days/scripts/last30days.py "AI coding agents" --emit=json --json-profile=raw+```++The raw profile is intentionally unversioned and may change when pipeline internals change. It preserves the JSON serialization used before the agent profile was introduced.++When `LAST30DAYS_API_KEY` and `LAST30DAYS_API_BASE` route a run through a configured remote API, the server does not return the local `Report` needed to build this profile. In that mode, `--json-profile=agent` exits with status 2 instead of emitting a misleading shape; use `--json-profile=raw` to retain the remote backend's existing server-response JSON contract.++## Top-level fields++| Field | Type | Meaning |+| --- | --- | --- |+| `schema_version` | string | Agent export contract version. The current version is `1.0`. |+| `query` | string | The research topic supplied to the engine. |+| `generated_at` | string | UTC generation timestamp in RFC 3339 format. |+| `window_days` | integer | Number of days between the report's start and end dates. |+| `source_status` | object | Map of source name to the outcome observed during this run. |+| `clusters` | array | Ranked groups of related results. |+| `results` | array | Ranked, flat evidence results for downstream processing. |++All top-level fields are always present. Empty runs contain empty `clusters` and `results` arrays. Sources appear in `source_status` when the run recorded an outcome for them.++## `source_status`++Each value distinguishes a clean empty result from incomplete coverage:++| State | Meaning |+| --- | --- |+| `ok` | The source completed and returned one or more items. |+| `no-results` | The source completed successfully but found no matching items. |+| `partial` | The source returned some items before a later failure. |+| `rate-limited` | Retrieval was stopped by a provider rate limit. |+| `auth-failed` | Credentials were missing, rejected, or expired during retrieval. |+| `unreachable` | The source or network endpoint could not be reached. |+| `timeout` | Retrieval exceeded its time limit. |+| `schema-drift` | The provider response no longer matched the expected shape. |+| `skipped-unconfigured` | The source was intentionally skipped because required configuration was absent. |+| `error` | Retrieval failed for another reason. |++Consumers must not interpret failure states as evidence that a source had no discussion. Only `no-results` means the source completed cleanly with zero matches.++## Cluster fields++| Field | Type | Meaning |+| --- | --- | --- |+| `title` | string | Cluster headline. |+| `summary` | string | Summary from the cluster's representative ranked result. |+| `sources` | array of strings | Sources represented by the cluster. |+| `engagement_total` | number | Sum of one headline native engagement counter per result. Known sources use their primary count (for example, Digg uses `postCount`); otherwise the largest counter-like field is used. Ranking, ratio, rating, and computed-score metadata are excluded. |++Cluster array order is ranking order. A result's `cluster` value is the zero-based index into this array.++## Result fields++| Field | Type | Meaning |+| --- | --- | --- |+| `title` | string | Result title. |+| `source` | string | Primary source name, such as `reddit`, `x`, `youtube`, or `grounding`. |+| `url` | string | Canonical result URL. It may be empty when the provider supplies no link. |+| `published_at` | string | Primary source item's publication date or timestamp. Omitted when unknown. |+| `summary` | string | Normalized snippet, with the relevance explanation or body used as fallback. |+| `engagement` | object | Native engagement counters from the primary source item, such as Reddit `score` and `num_comments` or X `likes` and `reposts`. |+| `relevance_score` | number | Engine final score normalized to the inclusive `0.0`–`1.0` range. |+| `cluster` | integer | Zero-based index into `clusters`. Omitted when the result is not assigned to a cluster. |++Fields whose value is unknown are omitted rather than emitted as JSON `null`. Strings and collection fields otherwise remain present, including empty strings, objects, or arrays.++## Comparison runs++Comparison queries use an envelope so each entity keeps its own contract:++```json+{+ "schema_version": "1.0",+ "comparison": true,+ "entities": ["OpenAI", "Anthropic"],+ "reports": [+ {"entity": "OpenAI", "report": {"schema_version": "1.0", "query": "OpenAI"}},+ {"entity": "Anthropic", "report": {"schema_version": "1.0", "query": "Anthropic"}}+ ]+}+```++The abbreviated reports above only illustrate the envelope; real reports contain every documented top-level field.++## Versioning policy++- `schema_version` uses `major.minor` numbering.+- Any breaking field removal, rename, type change, semantic change, or envelope change requires a major-version bump.+- Backward-compatible field additions may use a minor-version bump. Consumers should ignore fields they do not recognize.+- The checked-in golden snapshot test locks the complete `1.0` shape. Contract changes must update the version and snapshot deliberately.+- `--json-profile=raw` is outside this compatibility policy because it mirrors internal pipeline dataclasses.++`--preflight --emit=json` is a different machine contract for permission and configuration inspection. `--json-profile` does not alter preflight output.diff --git a/skills/last30days/SKILL.md b/skills/last30days/SKILL.mdindex 85adb1de..d1498038 100644--- a/skills/last30days/SKILL.md+++ b/skills/last30days/SKILL.md@@ -394,7 +394,7 @@ Set `LAST30DAYS_MEMORY_DIR` before invoking the skill to choose where raw researThe engine reads `LAST30DAYS_MEMORY_DIR` from either the process env or `~/.config/last30days/.env`, so direct CLI invocations (`python3 scripts/last30days.py ...`) without `--save-dir` will still save when the env var is set. Mirrors the `LAST30DAYS_STORE` env-or-flag convention. Explicit `--save-dir` always wins.-When both `LAST30DAYS_API_KEY` and `LAST30DAYS_API_BASE` are set, the engine runs the research through that configured remote API instead of local sources (unless `--mock` is passed); `LAST30DAYS_API_BASE` is the endpoint and has no built-in default, so leaving either variable unset runs local sources normally. The invocation is unchanged: same flags, `--quick`/`--deep` map to search depth, progress lines still stream on stderr (`[narrate] step=...` plus a compact elapsed/eta line), and the report prints on stdout and saves to the memory dir as usual, so Steps 1-4 proceed normally on the output. No per-source keys or setup-wizard credentials are needed for the search itself in this mode. Two engine exits need specific handling: exit code 3 means the API asked a clarifying question first - the engine prints the question and options on stderr; present them to the user and re-run with the chosen angle folded into the topic. An insufficient-credits failure (HTTP 402) prints the account's balance, the amount needed, and a billing link - relay those lines to the user verbatim; do not fall back to WebSearch-only synthesis.+When both `LAST30DAYS_API_KEY` and `LAST30DAYS_API_BASE` are set, the engine runs the research through that configured remote API instead of local sources (unless `--mock` is passed); `LAST30DAYS_API_BASE` is the endpoint and has no built-in default, so leaving either variable unset runs local sources normally. The invocation is unchanged: same flags, `--quick`/`--deep` map to search depth, progress lines still stream on stderr (`[narrate] step=...` plus a compact elapsed/eta line), and the report prints on stdout and saves to the memory dir as usual, so Steps 1-4 proceed normally on the output. The exception is research JSON: the remote endpoint does not return the local `Report` needed for the versioned agent profile, so use `--emit=json --json-profile=raw` for its existing server-response JSON contract. No per-source keys or setup-wizard credentials are needed for the search itself in this mode. Two engine exits need specific handling: exit code 3 means the API asked a clarifying question first - the engine prints the question and options on stderr; present them to the user and re-run with the chosen angle folded into the topic. An insufficient-credits failure (HTTP 402) prints the account's balance, the amount needed, and a billing link - relay those lines to the user verbatim; do not fall back to WebSearch-only synthesis.## Step 0: First-Run Setup Wizard@@ -888,6 +888,8 @@ If `--agent` appears in ARGUMENTS (e.g., `/last30days plaud granola --agent`):Agent mode saves raw research data to `LAST30DAYS_MEMORY_DIR` (defaults to `~/Documents/Last30Days`) automatically via `--save-dir` (handled by the script, no extra tool calls). Use `--output <file>` only when a caller needs the rendered stdout artifact at an exact path, with the format controlled by `--emit`.+**Machine-readable JSON exception:** If the user explicitly asks for structured JSON for an agent, script, or workflow, replace the normal `--emit=compact` engine invocation with `--emit=json` and pass the engine's stdout through verbatim instead of synthesizing the report format below. The default `--json-profile=agent` is the stable, versioned flat contract; use `--json-profile=raw` only when the user explicitly requests the full internal `Report` dump. `--preflight --emit=json` is a separate permission-preflight contract and is not affected by `--json-profile`. Full field documentation and the versioning policy live in `docs/reference/json-export.md` in the repository.+Agent mode report format:```diff --git a/skills/last30days/scripts/evaluate_search_quality.py b/skills/last30days/scripts/evaluate_search_quality.pyindex f40bc2d7..d5e3aad2 100644--- a/skills/last30days/scripts/evaluate_search_quality.py+++ b/skills/last30days/scripts/evaluate_search_quality.py@@ -332,6 +332,12 @@ def run_last30days(repo_dir: Path, topic: str, *, search: str, timeout_seconds:if not engine.exists():engine = repo_dir / "scripts" / "last30days.py"cmd = [sys.executable, str(engine), topic, "--emit=json"]+ # Current engines default to the stable agent export, while older revisions+ # used by the evaluator implicitly emit the raw report and do not recognize+ # --json-profile. Request raw explicitly whenever the checked-out engine+ # supports the selector.+ if not engine.exists() or "--json-profile" in engine.read_text(encoding="utf-8"):+ cmd.append("--json-profile=raw")if search:cmd.extend(["--search", search])if quick:@@ -349,7 +355,16 @@ def run_last30days(repo_dir: Path, topic: str, *, search: str, timeout_seconds:)if result.returncode != 0:raise RuntimeError(f"{repo_dir.name} failed for '{topic}' with exit {result.returncode}\n{result.stderr.strip()}")- return json.loads(result.stdout)+ payload = json.loads(result.stdout)+ # Shape guard: the evaluator compares raw Report fields. If the engine+ # emitted the agent profile anyway (flag detection missed a future+ # spelling), fail loudly instead of scoring empty ranked_candidates.+ if "schema_version" in payload and "ranked_candidates" not in payload:+ raise RuntimeError(+ f"{repo_dir.name} emitted the agent JSON profile; the evaluator "+ "requires the raw Report (--json-profile=raw)."+ )+ return payloaddef create_worktree(rev: str) -> Path:diff --git a/skills/last30days/scripts/last30days.py b/skills/last30days/scripts/last30days.pyindex 1f6f7b97..0303dbc0 100644--- a/skills/last30days/scripts/last30days.py+++ b/skills/last30days/scripts/last30days.py@@ -128,6 +128,7 @@ def save_output(synthesis_md: str | None = None,topic_override: str | None = None,rendered_content: str | None = None,+ json_profile: str = "agent",) -> Path:from datetime import datetimepath = Path(save_dir).expanduser().resolve()@@ -147,7 +148,12 @@ def save_output(if rendered_content is not None:content = rendered_contentelif emit in {"json", "html"}:- content = emit_output(report, emit, synthesis_md=synthesis_md)+ content = emit_output(+ report,+ emit,+ synthesis_md=synthesis_md,+ json_profile=json_profile,+ )else:content = render.render_full(report)encoded = content.encode("utf-8")@@ -217,9 +223,15 @@ def emit_output(fun_level: str = "medium",save_path: str | None = None,synthesis_md: str | None = None,+ json_profile: str = "agent",) -> str:if emit == "json":- return json.dumps(schema.to_dict(report), indent=2, sort_keys=True)+ payload = (+ schema.to_dict(report)+ if json_profile == "raw"+ else schema.to_agent_export(report)+ )+ return json.dumps(payload, indent=2, sort_keys=True)if emit == "html":return html_render.render_html(report, fun_level=fun_level, save_path=save_path, synthesis_md=synthesis_md,@@ -239,16 +251,26 @@ def emit_comparison_output(fun_level: str = "medium",save_path: str | None = None,synthesis_md: str | None = None,+ json_profile: str = "agent",) -> str:if emit == "json":payload = {"comparison": True,"entities": [label for label, _ in entity_reports],"reports": [- {"entity": label, "report": schema.to_dict(report)}+ {+ "entity": label,+ "report": (+ schema.to_dict(report)+ if json_profile == "raw"+ else schema.to_agent_export(report)+ ),+ }for label, report in entity_reports],}+ if json_profile == "agent":+ payload["schema_version"] = schema.AGENT_EXPORT_SCHEMA_VERSIONreturn json.dumps(payload, indent=2, sort_keys=True)if emit == "html":return html_render.render_html_comparison(@@ -340,6 +362,12 @@ def build_parser() -> argparse.ArgumentParser:)parser.add_argument("topic", nargs="*", help="Research topic")parser.add_argument("--emit", default="compact", choices=["compact", "json", "context", "md", "html", "brief"])+ parser.add_argument(+ "--json-profile",+ default="agent",+ choices=["agent", "raw"],+ help="JSON export profile for --emit=json (default: agent)",+ )parser.add_argument("--search", help="Comma-separated source list")parser.add_argument("--quick", action="store_true", help="Lower-latency retrieval profile")parser.add_argument("--deep", action="store_true", help="Higher-recall retrieval profile")@@ -839,6 +867,7 @@ def _render_save_and_print(fun_level=fun_level,save_path=footer_save_path,synthesis_md=synthesis_md,+ json_profile=args.json_profile,)else:rendered = emit_output(@@ -847,6 +876,7 @@ def _render_save_and_print(fun_level=fun_level,save_path=footer_save_path,synthesis_md=synthesis_md,+ json_profile=args.json_profile,)publish_companion_paths: list[Path] = []if args.output:@@ -865,6 +895,7 @@ def _render_save_and_print(synthesis_md=synthesis_md,topic_override=comparison_topic(entity_reports) if is_comparison_html else None,rendered_content=rendered if is_comparison_html else None,+ json_profile=args.json_profile,)if args.emit == "html":publish_companion_paths.append(save_path)@@ -878,6 +909,7 @@ def _render_save_and_print(entity_report, args.emit, args.save_dir,suffix=args.save_suffix or "",synthesis_md=synthesis_md,+ json_profile=args.json_profile,)comparison_peer_paths.append(peer_path)sys.stderr.write(f"[last30days] Saved output to {peer_path}\n")@@ -1144,6 +1176,12 @@ def main() -> int:and env.read_secret_env("LAST30DAYS_API_KEY")and os.environ.get("LAST30DAYS_API_BASE")):+ if args.emit == "json" and args.json_profile == "agent":+ sys.stderr.write(+ "[last30days] --json-profile=agent requires the local Report; "+ "the remote API backend only supports --json-profile=raw.\n"+ )+ return 2from lib import hosteddepth = "deep" if args.deep else "quick" if args.quick else "default"return hosted.run_hosted(diff --git a/skills/last30days/scripts/lib/schema.py b/skills/last30days/scripts/lib/schema.pyindex 713bc047..97999878 100644--- a/skills/last30days/scripts/lib/schema.py+++ b/skills/last30days/scripts/lib/schema.py@@ -441,3 +441,142 @@ def candidate_primary_item(candidate: Candidate) -> SourceItem | None:if item.source == candidate.source:return itemreturn candidate.source_items[0]+++AGENT_EXPORT_SCHEMA_VERSION = "1.0"+++def _agent_summary(candidate: Candidate) -> str:+ primary = candidate_primary_item(candidate)+ return (+ candidate.snippet+ or (primary.snippet if primary else "")+ or candidate.explanation+ or (primary.body if primary else "")+ )+++def _agent_engagement(candidate: Candidate) -> dict[str, float | int]:+ primary = candidate_primary_item(candidate)+ return dict(primary.engagement) if primary else {}+++_HEADLINE_ENGAGEMENT_FIELDS_BY_SOURCE = {+ "digg": ("postCount",),+ "reddit": ("score",),+ "stocktwits": ("likes", "reshares"),+}+++def _is_counter_field(field: str) -> bool:+ normalized = field.lower()+ return not (+ # Author-reach and position/score metadata, not per-item engagement.+ normalized in {"rank", "rating", "score", "trustscore", "followers", "subscribers"}+ or normalized.endswith(("_rank", "_score", "_ratio", "_rate", "_followers"))+ )+++def _headline_engagement(candidate: Candidate) -> float:+ """Return the primary item's largest native engagement counter."""+ engagement = _agent_engagement(candidate)+ preferred_fields = _HEADLINE_ENGAGEMENT_FIELDS_BY_SOURCE.get(candidate.source, ())+ preferred_values = [+ float(engagement[field])+ for field in preferred_fields+ if isinstance(engagement.get(field), (int, float))+ and not isinstance(engagement[field], bool)+ ]+ if preferred_values:+ return max(preferred_values)++ values = [+ float(value)+ for field, value in engagement.items()+ if _is_counter_field(field)+ and isinstance(value, (int, float))+ and not isinstance(value, bool)+ ]+ return max(values, default=0.0)+++def _window_days(report: Report) -> int:+ start = datetime.fromisoformat(report.range_from).date()+ end = datetime.fromisoformat(report.range_to).date()+ return max(0, (end - start).days)+++def _agent_generated_at(value: str) -> str:+ parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))+ if parsed.tzinfo is None:+ return value+ return parsed.astimezone(timezone.utc).isoformat().replace("+00:00", "Z")+++def to_agent_export(report: Report) -> dict[str, Any]:+ """Serialize a report to the stable, versioned agent JSON contract."""+ candidates = {candidate.candidate_id: candidate for candidate in report.ranked_candidates}+ cluster_by_candidate: dict[str, int] = {}+ cluster_by_id: dict[str, int] = {}+ exported_clusters: list[dict[str, Any]] = []++ for index, cluster in enumerate(report.clusters):+ cluster_by_id[cluster.cluster_id] = index+ for candidate_id in cluster.candidate_ids:+ cluster_by_candidate.setdefault(candidate_id, index)+ representative = next(+ (candidates[candidate_id] for candidate_id in cluster.representative_ids if candidate_id in candidates),+ None,+ )+ engagement_total = sum(+ _headline_engagement(candidates[candidate_id])+ for candidate_id in cluster.candidate_ids+ if candidate_id in candidates+ )+ exported_clusters.append(+ {+ "title": cluster.title,+ "summary": _agent_summary(representative) if representative else "",+ "sources": list(cluster.sources),+ "engagement_total": (+ int(engagement_total) if engagement_total.is_integer() else engagement_total+ ),+ }+ )++ results: list[dict[str, Any]] = []+ for candidate in report.ranked_candidates:+ primary = candidate_primary_item(candidate)+ cluster_index = cluster_by_id.get(candidate.cluster_id or "")+ if cluster_index is None:+ cluster_index = cluster_by_candidate.get(candidate.candidate_id)+ results.append(+ _drop_none(+ {+ "title": candidate.title,+ "source": candidate.source,+ "url": candidate.url,+ "published_at": primary.published_at if primary else None,+ "summary": _agent_summary(candidate),+ "engagement": _agent_engagement(candidate),+ "relevance_score": round(+ max(0.0, min(1.0, candidate.final_score / 100.0)),+ 4,+ ),+ "cluster": cluster_index,+ }+ )+ )++ return {+ "schema_version": AGENT_EXPORT_SCHEMA_VERSION,+ "query": report.topic,+ "generated_at": _agent_generated_at(report.generated_at),+ "window_days": _window_days(report),+ "source_status": {+ source: outcome.state+ for source, outcome in sorted(report.source_status.items())+ },+ "clusters": exported_clusters,+ "results": results,+ }diff --git a/skills/last30days/scripts/verify_v3.py b/skills/last30days/scripts/verify_v3.pyindex 73319c7d..26ca7420 100644--- a/skills/last30days/scripts/verify_v3.py+++ b/skills/last30days/scripts/verify_v3.py@@ -92,7 +92,7 @@ def verify_smoke() -> list[dict[str, object]]:env["LAST30DAYS_REASONING_PROVIDER"] = providerstart = time.time()result = run_command(- [PYTHON, str(ENGINE), SMOKE_TOPIC, "--emit=json", *extra],+ [PYTHON, str(ENGINE), SMOKE_TOPIC, "--emit=json", "--json-profile=raw", *extra],env=env,timeout=240,)@@ -118,7 +118,7 @@ def verify_latency() -> dict[str, dict[str, object]]:for topic in LATENCY_TOPICS:start = time.time()run_command(- [PYTHON, str(ENGINE), topic, "--emit=json", *extra],+ [PYTHON, str(ENGINE), topic, "--emit=json", "--json-profile=raw", *extra],timeout=300,)timings.append(time.time() - start)diff --git a/skills/last30days/scripts/watchlist.py b/skills/last30days/scripts/watchlist.pyindex c5a4cc00..085e663b 100644--- a/skills/last30days/scripts/watchlist.py+++ b/skills/last30days/scripts/watchlist.py@@ -181,6 +181,7 @@ def _run_topic(topic: dict) -> dict:str(SCRIPT_DIR / "last30days.py"),search_term,"--emit=json",+ "--json-profile=raw","--quick","--lookback-days","90",diff --git a/tests/e2e_comparison.py b/tests/e2e_comparison.pyindex 00dd513a..c346f346 100644--- a/tests/e2e_comparison.py+++ b/tests/e2e_comparison.py@@ -46,7 +46,7 @@ def run_query(script: str, topic: str, timeout: int = 180) -> dict:start = time.time()try:result = subprocess.run(- [sys.executable, script, topic, "--emit=json"],+ [sys.executable, script, topic, "--emit=json", "--json-profile=raw"],capture_output=True,text=True,timeout=timeout,diff --git a/tests/fixtures/agent_export_v1.json b/tests/fixtures/agent_export_v1.jsonnew file mode 100644index 00000000..4ad5b276--- /dev/null+++ b/tests/fixtures/agent_export_v1.json@@ -0,0 +1,84 @@+{+ "schema_version": "1.0",+ "query": "AI coding agents",+ "generated_at": "2026-07-10T00:00:00Z",+ "window_days": 30,+ "source_status": {+ "digg": "ok",+ "github": "auth-failed",+ "grounding": "unreachable",+ "hackernews": "no-results",+ "reddit": "ok",+ "x": "ok",+ "youtube": "rate-limited"+ },+ "clusters": [+ {+ "title": "Agents move into daily coding workflows",+ "summary": "Developers shared concrete agent workflows.",+ "sources": [+ "reddit"+ ],+ "engagement_total": 1543+ },+ {+ "title": "Teams compare coding-agent review loops",+ "summary": "Teams compared how agents fit into code review.",+ "sources": [+ "x"+ ],+ "engagement_total": 800+ },+ {+ "title": "Agents climb the Digg AI leaderboard",+ "summary": "A small Digg cluster appeared low on the leaderboard.",+ "sources": [+ "digg"+ ],+ "engagement_total": 5+ }+ ],+ "results": [+ {+ "title": "Agents move into daily coding workflows",+ "source": "reddit",+ "url": "https://www.reddit.com/r/programming/comments/agent-workflows",+ "published_at": "2026-06-28",+ "summary": "Developers shared concrete agent workflows.",+ "engagement": {+ "score": 1543,+ "num_comments": 201+ },+ "relevance_score": 0.92,+ "cluster": 0+ },+ {+ "title": "Teams compare coding-agent review loops",+ "source": "x",+ "url": "https://x.com/example/status/123",+ "published_at": "2026-07-02",+ "summary": "Teams compared how agents fit into code review.",+ "engagement": {+ "likes": 800,+ "reposts": 50+ },+ "relevance_score": 0.84,+ "cluster": 1+ },+ {+ "title": "Agents climb the Digg AI leaderboard",+ "source": "digg",+ "url": "https://di.gg/ai/agent-leaderboard",+ "published_at": "2026-07-05",+ "summary": "A small Digg cluster appeared low on the leaderboard.",+ "engagement": {+ "postCount": 5,+ "uniqueAuthors": 4,+ "rank": 500,+ "rank_score": 0.0+ },+ "relevance_score": 0.7,+ "cluster": 2+ }+ ]+}diff --git a/tests/test_agent_export.py b/tests/test_agent_export.pynew file mode 100644index 00000000..4de1f1fb--- /dev/null+++ b/tests/test_agent_export.py@@ -0,0 +1,283 @@+import json+from pathlib import Path++import last30days as cli+from lib import health, schema+++GOLDEN = Path(__file__).parent / "fixtures" / "agent_export_v1.json"+++def _report() -> schema.Report:+ reddit_item = schema.SourceItem(+ item_id="reddit-1",+ source="reddit",+ title="Agents move into daily coding workflows",+ body="Developers described where coding agents save time.",+ url="https://www.reddit.com/r/programming/comments/agent-workflows",+ published_at="2026-06-28",+ snippet="Developers shared concrete agent workflows.",+ engagement={"score": 1543, "num_comments": 201},+ )+ x_item = schema.SourceItem(+ item_id="x-1",+ source="x",+ title="Teams compare coding-agent review loops",+ body="A thread compared review loops across several tools.",+ url="https://x.com/example/status/123",+ published_at="2026-07-02",+ snippet="Teams compared how agents fit into code review.",+ engagement={"likes": 800, "reposts": 50},+ )+ digg_item = schema.SourceItem(+ item_id="digg-1",+ source="digg",+ title="Agents climb the Digg AI leaderboard",+ body="A Digg cluster collected five posts from four authors.",+ url="https://di.gg/ai/agent-leaderboard",+ published_at="2026-07-05",+ snippet="A small Digg cluster appeared low on the leaderboard.",+ engagement={"postCount": 5, "uniqueAuthors": 4, "rank": 500, "rank_score": 0.0},+ )+ reddit_candidate = schema.Candidate(+ candidate_id="candidate-reddit",+ item_id=reddit_item.item_id,+ source="reddit",+ title=reddit_item.title,+ url=reddit_item.url,+ snippet=reddit_item.snippet,+ subquery_labels=["workflows"],+ native_ranks={"workflows:reddit": 1},+ local_relevance=0.95,+ freshness=85,+ engagement=100,+ source_quality=0.6,+ rrf_score=0.02,+ final_score=92,+ cluster_id="cluster-workflows",+ source_items=[reddit_item],+ )+ x_candidate = schema.Candidate(+ candidate_id="candidate-x",+ item_id=x_item.item_id,+ source="x",+ title=x_item.title,+ url=x_item.url,+ snippet=x_item.snippet,+ subquery_labels=["reviews"],+ native_ranks={"reviews:x": 1},+ local_relevance=0.88,+ freshness=92,+ engagement=80,+ source_quality=0.68,+ rrf_score=0.018,+ final_score=84,+ source_items=[x_item],+ )+ digg_candidate = schema.Candidate(+ candidate_id="candidate-digg",+ item_id=digg_item.item_id,+ source="digg",+ title=digg_item.title,+ url=digg_item.url,+ snippet=digg_item.snippet,+ subquery_labels=["leaderboard"],+ native_ranks={"leaderboard:digg": 500},+ local_relevance=0.78,+ freshness=75,+ engagement=5,+ source_quality=0.6,+ rrf_score=0.01,+ final_score=70,+ cluster_id="cluster-digg",+ source_items=[digg_item],+ )+ return schema.Report(+ topic="AI coding agents",+ range_from="2026-06-10",+ range_to="2026-07-10",+ generated_at="2026-07-10T00:00:00+00:00",+ provider_runtime=schema.ProviderRuntime(+ reasoning_provider="local",+ planner_model="fixture-planner",+ rerank_model="fixture-reranker",+ ),+ query_plan=schema.QueryPlan(+ intent="research",+ freshness_mode="strict_recent",+ cluster_mode="story",+ raw_topic="AI coding agents",+ subqueries=[+ schema.SubQuery(+ label="workflows",+ search_query="AI coding agent workflows",+ ranking_query="How are developers using AI coding agents?",+ sources=["reddit"],+ )+ ],+ source_weights={"reddit": 1.0, "x": 0.8},+ ),+ clusters=[+ schema.Cluster(+ cluster_id="cluster-workflows",+ title="Agents move into daily coding workflows",+ candidate_ids=[reddit_candidate.candidate_id],+ representative_ids=[reddit_candidate.candidate_id],+ sources=["reddit"],+ score=92,+ ),+ schema.Cluster(+ cluster_id="cluster-reviews",+ title="Teams compare coding-agent review loops",+ candidate_ids=[x_candidate.candidate_id],+ representative_ids=[x_candidate.candidate_id],+ sources=["x"],+ score=84,+ ),+ schema.Cluster(+ cluster_id="cluster-digg",+ title="Agents climb the Digg AI leaderboard",+ candidate_ids=[digg_candidate.candidate_id],+ representative_ids=[digg_candidate.candidate_id],+ sources=["digg"],+ score=70,+ ),+ ],+ ranked_candidates=[reddit_candidate, x_candidate, digg_candidate],+ items_by_source={"reddit": [reddit_item], "x": [x_item], "digg": [digg_item]},+ errors_by_source={+ "youtube": "HTTP 429",+ "github": "HTTP 401",+ "grounding": "DNS failure",+ },+ source_status={+ "reddit": schema.SourceOutcome(source="reddit", state=health.OK, items_returned=1),+ "x": schema.SourceOutcome(source="x", state=health.OK, items_returned=1),+ "digg": schema.SourceOutcome(source="digg", state=health.OK, items_returned=1),+ "hackernews": schema.SourceOutcome(source="hackernews", state=schema.NO_RESULTS),+ "youtube": schema.SourceOutcome(source="youtube", state=schema.RATE_LIMITED),+ "grounding": schema.SourceOutcome(source="grounding", state=schema.UNREACHABLE),+ "github": schema.SourceOutcome(source="github", state=schema.AUTH_FAILED),+ },+ )+++def test_agent_export_matches_v1_golden_contract():+ expected = json.loads(GOLDEN.read_text(encoding="utf-8"))++ assert schema.to_agent_export(_report()) == expected+++def test_agent_export_maps_per_run_source_outcomes_to_states():+ exported = schema.to_agent_export(_report())++ assert exported["source_status"] == {+ "digg": "ok",+ "github": "auth-failed",+ "grounding": "unreachable",+ "hackernews": "no-results",+ "reddit": "ok",+ "x": "ok",+ "youtube": "rate-limited",+ }+++def test_agent_export_uses_digg_post_count_not_rank_for_cluster_engagement():+ exported = schema.to_agent_export(_report())++ assert exported["clusters"][2]["engagement_total"] == 5+++def test_agent_export_excludes_non_counter_metadata_from_cluster_engagement():+ report = _report()+ report.ranked_candidates[0].source = "web"+ report.ranked_candidates[0].source_items[0].source = "web"+ report.ranked_candidates[0].source_items[0].engagement = {+ "views": 5,+ "rank": 500,+ "rank_score": 400,+ "ranking_score": 300,+ "score": 200,+ "upvote_ratio": 0.95,+ "rating": 4.9,+ "trustScore": 3.4,+ }++ exported = schema.to_agent_export(report)++ assert exported["clusters"][0]["engagement_total"] == 5+++def test_raw_profile_is_byte_identical_to_legacy_report_dump():+ report = _report()+ legacy = json.dumps(schema.to_dict(report), indent=2, sort_keys=True)++ assert cli.emit_output(report, "json", json_profile="raw") == legacy+++def test_raw_comparison_profile_is_byte_identical_to_legacy_wrapper():+ report = _report()+ reports = [("AI coding agents", report)]+ legacy = json.dumps(+ {+ "comparison": True,+ "entities": ["AI coding agents"],+ "reports": [{"entity": "AI coding agents", "report": schema.to_dict(report)}],+ },+ indent=2,+ sort_keys=True,+ )++ assert cli.emit_comparison_output(reports, "json", json_profile="raw") == legacy+++def test_json_profile_parser_defaults_to_agent_and_accepts_raw():+ parser = cli.build_parser()++ assert parser.parse_args(["topic", "--emit=json"]).json_profile == "agent"+ assert parser.parse_args(["topic", "--emit=json", "--json-profile=raw"]).json_profile == "raw"+++def _reach_candidate(source, engagement):+ item = schema.SourceItem(+ item_id=f"{source}-reach-1",+ source=source,+ title="reach test",+ body="reach test body",+ url=f"https://example.com/{source}/reach",+ published_at="2026-07-05",+ snippet="reach test snippet",+ engagement=engagement,+ )+ return schema.Candidate(+ candidate_id=f"candidate-{source}-reach",+ item_id=item.item_id,+ source=source,+ title=item.title,+ url=item.url,+ snippet=item.snippet,+ subquery_labels=["primary"],+ native_ranks={f"primary:{source}": 1},+ local_relevance=0.5,+ freshness=50,+ engagement=10,+ source_quality=0.5,+ rrf_score=0.01,+ final_score=50,+ cluster_id="cluster-reach",+ source_items=[item],+ )+++def test_headline_engagement_excludes_author_reach_for_stocktwits():+ candidate = _reach_candidate(+ "stocktwits", {"likes": 12, "reshares": 3, "followers": 250000}+ )+ assert schema._headline_engagement(candidate) == 12.0+++def test_headline_engagement_excludes_followers_generically():+ candidate = _reach_candidate(+ "linkedin", {"reactions": 40, "followers": 90000}+ )+ assert schema._headline_engagement(candidate) == 40.0diff --git a/tests/test_as_of_date.py b/tests/test_as_of_date.pyindex 180c436b..2684c648 100644--- a/tests/test_as_of_date.py+++ b/tests/test_as_of_date.py@@ -51,6 +51,7 @@ class AsOfDateTests(unittest.TestCase):"OpenAI","--mock","--emit=json",+ "--json-profile=raw","--as-of","2020-05-25","--days",diff --git a/tests/test_cli_v3.py b/tests/test_cli_v3.pyindex 65260f1a..0bfd8822 100644--- a/tests/test_cli_v3.py+++ b/tests/test_cli_v3.py@@ -61,9 +61,11 @@ class CliV3Tests(unittest.TestCase):)self.assertEqual(0, result.returncode, result.stderr)payload = json.loads(result.stdout)- self.assertIn("query_plan", payload)- self.assertIn("ranked_candidates", payload)+ self.assertEqual("1.0", payload["schema_version"])+ self.assertEqual("test topic", payload["query"])+ self.assertIn("results", payload)self.assertIn("clusters", payload)+ self.assertIn("source_status", payload)def test_invalid_plan_json_exits_nonzero(self):"""Malformed --plan JSON must fail fast, not silently fall back to the@@ -270,7 +272,7 @@ class CliV3Tests(unittest.TestCase):brief = cli.emit_output(report, "brief")self.assertIn("# last30days v", compact)- self.assertIn('"topic": "OpenClaw vs NanoClaw"', json_output)+ self.assertIn('"query": "OpenClaw vs NanoClaw"', json_output)self.assertIsInstance(context, str)self.assertIn("# Production Brief:", brief)@@ -283,7 +285,7 @@ class CliV3Tests(unittest.TestCase):path = cli.save_output(report, "json", tmp)self.assertEqual(".json", path.suffix)payload = json.loads(path.read_text())- self.assertEqual("OpenClaw vs NanoClaw", payload["topic"])+ self.assertEqual("OpenClaw vs NanoClaw", payload["query"])def test_save_output_uses_unique_dated_fallback(self):report = self.make_report()diff --git a/tests/test_evaluator_v3.py b/tests/test_evaluator_v3.pyindex 25fd62f1..e05f2d17 100644--- a/tests/test_evaluator_v3.py+++ b/tests/test_evaluator_v3.py@@ -194,17 +194,24 @@ class EvaluatorV3Tests(unittest.TestCase):self.assertEqual("config-openai", created["OPENAI_API_KEY"])self.assertEqual("", created["LAST30DAYS_CONFIG_DIR"])- with mock.patch.object(evaluator.subprocess, "run", return_value=mock.Mock(returncode=0, stdout='{"topic":"x"}', stderr="")):- payload = evaluator.run_last30days(- Path("/tmp/repo"),- "topic",- search="reddit",- timeout_seconds=30,- quick=True,- mock=True,- env={"PATH": "/bin"},- )+ with tempfile.TemporaryDirectory() as tmp:+ repo_dir = Path(tmp)+ engine = repo_dir / "skills" / "last30days" / "scripts" / "last30days.py"+ engine.parent.mkdir(parents=True)+ engine.write_text('parser.add_argument("--json-profile")')+ completed = mock.Mock(returncode=0, stdout='{"topic":"x"}', stderr="")+ with mock.patch.object(evaluator.subprocess, "run", return_value=completed) as run:+ payload = evaluator.run_last30days(+ repo_dir,+ "topic",+ search="reddit",+ timeout_seconds=30,+ quick=True,+ mock=True,+ env={"PATH": "/bin"},+ )self.assertEqual("x", payload["topic"])+ self.assertIn("--json-profile=raw", run.call_args.args[0])with mock.patch.object(evaluator.subprocess, "run", return_value=mock.Mock(returncode=2, stdout="", stderr="bad run")):with self.assertRaises(RuntimeError):@@ -218,6 +225,26 @@ class EvaluatorV3Tests(unittest.TestCase):env={"PATH": "/bin"},)+ def test_run_last30days_keeps_legacy_engine_implicit_raw_profile(self):+ with tempfile.TemporaryDirectory() as tmp:+ repo_dir = Path(tmp)+ engine = repo_dir / "skills" / "last30days" / "scripts" / "last30days.py"+ engine.parent.mkdir(parents=True)+ engine.write_text('parser.add_argument("--emit")')+ completed = mock.Mock(returncode=0, stdout='{"topic":"x"}', stderr="")+ with mock.patch.object(evaluator.subprocess, "run", return_value=completed) as run:+ evaluator.run_last30days(+ repo_dir,+ "topic",+ search="reddit",+ timeout_seconds=30,+ quick=False,+ mock=False,+ env={"PATH": "/bin"},+ )++ self.assertNotIn("--json-profile=raw", run.call_args.args[0])+def test_parse_topics_file_and_summary_writer(self):with tempfile.TemporaryDirectory() as tmp:tmp_path = Path(tmp)diff --git a/tests/test_hosted.py b/tests/test_hosted.pyindex 29d6a0f6..a32921b1 100644--- a/tests/test_hosted.py+++ b/tests/test_hosted.py@@ -169,6 +169,47 @@ def test_env_set_routes_to_remote_path(monkeypatch):}]+def test_remote_json_requires_raw_profile(monkeypatch):+ monkeypatch.setenv("LAST30DAYS_API_KEY", TEST_KEY)+ monkeypatch.setenv("LAST30DAYS_API_BASE", TEST_BASE)+ monkeypatch.setattr(+ hosted,+ "run_hosted",+ lambda *args, **kwargs: pytest.fail("remote request should not start"),+ )++ with mock.patch.object(cli.env, "get_config", return_value={}):+ rc, _out, err = run_main(["test", "topic", "--emit=json"])++ assert rc == 2+ assert "remote API backend only supports --json-profile=raw" in err+++def test_remote_raw_json_preserves_existing_server_contract(monkeypatch):+ monkeypatch.setenv("LAST30DAYS_API_KEY", TEST_KEY)+ monkeypatch.setenv("LAST30DAYS_API_BASE", TEST_BASE)+ calls = []+ monkeypatch.setattr(+ hosted,+ "run_hosted",+ lambda topic, depth, **kwargs: calls.append((topic, depth, kwargs)) or 0,+ )++ with mock.patch.object(cli.env, "get_config", return_value={}):+ rc, _out, _err = run_main(+ ["test", "topic", "--emit=json", "--json-profile=raw"]+ )++ assert rc == 0+ assert calls == [+ (+ "test topic",+ "default",+ {"emit": "json", "save_dir": None, "save_suffix": ""},+ )+ ]++@pytest.mark.parametrize(("flag", "expected_depth"),[(["--quick"], "quick"), ([], "default"), (["--deep"], "deep")],diff --git a/tests/test_regression.py b/tests/test_regression.pyindex ded54b48..81d2cc4e 100644--- a/tests/test_regression.py+++ b/tests/test_regression.py@@ -10,7 +10,14 @@ REPO_ROOT = Path(__file__).resolve().parents[1]def run_mock_json(topic: str) -> dict:result = subprocess.run(- [sys.executable, "skills/last30days/scripts/last30days.py", topic, "--mock", "--emit=json"],+ [+ sys.executable,+ "skills/last30days/scripts/last30days.py",+ topic,+ "--mock",+ "--emit=json",+ "--json-profile=raw",+ ],cwd=REPO_ROOT,capture_output=True,text=True,diff --git a/tests/test_render_comparison_multi.py b/tests/test_render_comparison_multi.pyindex 7b612751..b5b6aca2 100644--- a/tests/test_render_comparison_multi.py+++ b/tests/test_render_comparison_multi.py@@ -274,7 +274,8 @@ class EmitComparisonOutputTests(unittest.TestCase):self.assertEqual(payload["entities"], ["OpenAI", "Anthropic"])self.assertEqual(len(payload["reports"]), 2)self.assertEqual(payload["reports"][0]["entity"], "OpenAI")- self.assertIn("topic", payload["reports"][0]["report"])+ self.assertEqual(payload["schema_version"], "1.0")+ self.assertIn("query", payload["reports"][0]["report"])def test_compact_and_md_both_route_to_multi(self):reports = [diff --git a/tests/test_verify_v3.py b/tests/test_verify_v3.pyindex e019f1d8..c788b881 100644--- a/tests/test_verify_v3.py+++ b/tests/test_verify_v3.py@@ -1,6 +1,7 @@import importlib.utilimport unittestfrom pathlib import Path+from unittest import mockdef load_verify_module():@@ -22,6 +23,19 @@ class VerifyV3Tests(unittest.TestCase):self.assertFalse(args.skip_eval)self.assertFalse(args.skip_latency)+ def test_smoke_and_latency_request_raw_json_profile(self):+ module = load_verify_module()+ completed = mock.Mock(stdout='{"clusters": [], "ranked_candidates": []}')+ with mock.patch.object(module, "run_command", return_value=completed) as run:+ module.SMOKE_CASES = [("auto", ["--quick"])]+ module.LATENCY_PROFILES = [("quick", ["--quick"])]+ module.LATENCY_TOPICS = ["topic"]+ module.verify_smoke()+ module.verify_latency()++ commands = [call.args[0] for call in run.call_args_list]+ self.assertTrue(all("--json-profile=raw" in command for command in commands))+if __name__ == "__main__":unittest.main()diff --git a/tests/test_watchlist_commands.py b/tests/test_watchlist_commands.pyindex 830a5fe8..aada4ff6 100644--- a/tests/test_watchlist_commands.py+++ b/tests/test_watchlist_commands.py@@ -374,6 +374,9 @@ def test_run_topic_success(mock_subprocess, temp_db):assert result["status"] == "completed"assert result["new"] == 1assert result["topic"] == "Test Topic"+ argv = mock_subprocess.call_args.args[0]+ assert "--emit=json" in argv+ assert "--json-profile=raw" in argv@patch('watchlist.subprocess.run')