:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
"""Pydantic content schemas for `SignalReportArtefact` rows.
Each `SignalReportArtefact` stores its typed payload as JSON text in `content`. This module is
the canonical home of every artefact content shape: one model per artefact type. Raw payloads
are parsed into these models once, at the boundaries — `parse_artefact_content` for API writes
and for reads that consume stored rows — and everything in between passes the typed model
around; the model helpers derive a row's type from the content model's class. The module is
kept deliberately dependency-light so models, views, and temporal code can all import it without
pulling in the report-research / sandbox machinery — its only non-pydantic import is a leaf DTO that
carries no such weight: the cross-product `RepoSelectionResult` (`tasks` facade types re-export).
`RelevantCommit` is defined here rather than reused from the generated `posthog.schema`: importing
that module drags ~1s of generated pydantic onto every process's `django.setup()` path, since this
module loads with the signals models (see docs/internal/django-startup-time.md).
Reads of legacy rows that predate these schemas stay tolerant (parse failures are skipped or
degraded, never raised to users).
"""
from __future__ import annotations
import re
import json
from collections.abc import Mapping
from datetime import datetime
from enum import Enum
from typing import Annotated, Any, Literal, cast
from uuid import UUID
from pydantic import (
BaseModel,
ConfigDict,
Field,
JsonValue,
RootModel,
ValidationError,
field_validator,
model_validator,
)
from products.signals.backend.credential_redaction import redact_credentials
from products.signals.backend.enums import ReportLinkKind, ReportPriority, SuggestedSourceProduct
from products.signals.backend.report_checks import CheckComparison, CheckInconclusiveReason, CheckOutcome
from products.signals.backend.report_metrics import MAX_METRIC_UNIT_LENGTH, ReportMetricValueFormat
from products.tasks.backend.facade.repo_selection_types import RepoSelectionResult
# Product / type identifier parts must be routing-safe — mirrors the custom-agent identifier
# contract (see custom_agent.schemas.validate_identifier_part), kept inline so this module stays
# dependency-light (pydantic only).
_IDENTIFIER_PART_RE = re.compile(r"^[a-z0-9][a-z0-9_-]*$")
class ArtefactContentValidationError(ValueError):
"""Raised when artefact content does not match the schema registered for its type."""
# ── Status artefact schemas ──────────────────────────────────────────────────────
#
# Status artefacts describe the report's current state (judgments, repo selection, suggested
# reviewers); append-only, latest row of each type wins. The judgment models double as LLM
# output schemas in `report_generation/research.py` — their field descriptions are prompt
# material, not just docs.
class ActionabilityChoice(str, Enum):
IMMEDIATELY_ACTIONABLE = "immediately_actionable"
REQUIRES_HUMAN_INPUT = "requires_human_input"
NOT_ACTIONABLE = "not_actionable"
# Report priority scale (P0–P4). Aliased to the shared signal taxonomy enum so the product has a
# single P0–P4 source; kept under the `Priority` name for existing callers.
Priority = ReportPriority
class SignalFinding(BaseModel):
"""Content schema for a `signal_finding` artefact: one investigation result per signal."""
signal_id: str = Field(description="The signal_id from the input signal list")
relevant_code_paths: list[str] = Field(
description=(
"File paths in the codebase relevant to this signal, ordered from most critical first. "
"The first path should be the highest-impact file (e.g. the buggy module or core feature file). "
"Then include supporting paths."
),
)
relevant_commit_hashes: dict[str, str] = Field(
default_factory=dict,
json_schema_extra={"minProperties": 1},
description=(
"A mapping of 'git commit short SHA (7 characters)' -> 'reason'. "
"Each value is one sentence of at most 12 words that explains why the commit is relevant. "
"Name the affected surface or behavior instead of listing implementation details. "
"Use `git blame --ignore-revs-file $(git rev-parse --show-toplevel)/.git-blame-ignore-revs` on "
"the most critical code paths to identify commits that caused, or are most closely related to, "
"the issue described by this report. Prioritize causative commits (e.g. the commit that introduced a bug) "
"over general authorship commits. "
"Exclude commits authored by bots (any GitHub login ending in `[bot]`), "
"commits authored by known LLM authors (such as Claude, OpenAI, etc.), "
"and commits whose only relationship to the code is a repo-wide mechanical change "
"(linting, formatting, import sorting, bulk refactor) — those authors "
"didn't meaningfully shape this code and must not be surfaced as reviewers. Include 1-5 commits."
),
)
data_queried: str = Field(
description=(
"What PostHog MCP queries you ran (e.g. execute-sql, query-run, insight-query) "
"and what the results showed. If no relevant queries could be run, explain why."
),
)
verified: bool = Field(
description=(
"Whether you could confirm the signal's claim by finding supporting evidence "
"in code or data. False if the claim couldn't be verified either way."
),
)
class ActionabilityAssessment(BaseModel):
"""Content schema for an `actionability_judgment` artefact."""
explanation: str = Field(
description=(
"2-3 sentence evidence-grounded explanation of your actionability assessment. "
"Reference specific code paths and data points from your research."
),
)
actionability: ActionabilityChoice = Field(
description="Overall actionability assessment. Must be one of the allowed enum values — do not invent new ones.",
)
already_addressed: bool = Field(
description=(
"Whether the core issue described by this report is already being handled — either fixed "
"in recent code changes, or with a fix already in flight: an open pull request, a recently "
"active branch, or an assigned / in-progress issue or agent task covering the same problem. "
"True in any of those cases; only a fix nobody has started is False. This gates autonomous "
"PRs, so a wrong False opens a duplicate PR against work a human or another agent already "
"has going. Tracked separately from `actionability`."
),
)
@field_validator("explanation")
@classmethod
def explanation_must_not_be_empty(cls, v: str) -> str:
if not v.strip():
raise ValueError("Explanation must not be empty")
return v
def priority_from_judgment(content: str | None) -> str | None:
"""The priority of a `priority_judgment` artefact's content, or None when the content has none.
Tolerant on purpose: an old or malformed judgment reads as "no priority" rather than an error.
"""
try:
data = json.loads(content or "")
except (TypeError, ValueError):
return None
priority = data.get("priority") if isinstance(data, dict) else None
return priority if isinstance(priority, str) else None
class PriorityAdjustment(BaseModel):
previous_priority: Priority | None
previous_judgment_id: UUID | None
source: Literal["inbox_sidebar"] = "inbox_sidebar"
class PriorityAssessment(BaseModel):
"""Content schema for a `priority_judgment` artefact."""
explanation: str = Field(
description=(
"2-3 sentence justification for the priority level. "
"Cite a quantified figure from your research — error frequency, affected user/session count, "
"or scope of affected code paths. If impact could not be measured, say so explicitly and explain "
"why the priority is not lowered further."
),
)
priority: Priority = Field(description="Priority (P0-P4)")
adjustment: PriorityAdjustment | None = Field(
default=None,
exclude_if=lambda adjustment: adjustment is None,
description="Correction metadata recorded when a person changes the priority in the inbox.",
)
dollar_value: float | None = Field(
default=None,
description=(
"Peak estimate (USD) of the real dollar value of merging the fix/change this report leads to. "
"Reason internally about a plausible value range first; set this to the most likely point "
"within that range (the peak of your belief distribution). Should align with the assigned "
"priority. Nullable for backward compatibility only — prefer a best-effort peak over null."
),
)
@field_validator("explanation")
@classmethod
def explanation_must_not_be_empty(cls, v: str) -> str:
if not v.strip():
raise ValueError("Explanation must not be empty")
return v
class SafetyJudgment(BaseModel):
"""Content schema for a `safety_judgment` artefact: the prompt-injection safety verdict."""
choice: bool = Field(description="True when the report's signals are judged safe to act on.")
explanation: str | None = Field(
default=None, description="Why the report was judged unsafe; null/omitted when safe."
)
class RelevantCommit(BaseModel):
"""A commit attributed to a suggested reviewer. Shape mirrors the generated
`posthog.schema.RelevantCommit` exactly so the two stay interchangeable on the wire — defined
here to keep this module off the heavy `posthog.schema` import path (see module docstring)."""
model_config = ConfigDict(extra="forbid")
reason: str = Field(max_length=500)
sha: str
url: str
class SuggestedReviewerEntry(BaseModel):
"""One reviewer in a `suggested_reviewers` artefact's content list.
A reviewer is a PostHog user; a GitHub login is an attribute some of them have. An entry carries
`user_uuid`, `github_login`, or both, and readers match on either — so a teammate who never
connected GitHub still routes a report. Entries written before `user_uuid` existed carry a login
alone, and read-time enrichment resolves those the way it always did.
"""
github_login: str | None = Field(
default=None,
description=(
"GitHub login identifying the reviewer (stored lowercased). Null when the reviewer has "
"no linked GitHub account."
),
)
user_uuid: str | None = Field(
default=None,
description="UUID of the PostHog user this entry routes to. Null on entries written before reviewers carried one.",
)
github_name: str | None = Field(default=None, description="Optional human-readable display name.")
relevant_commits: list[RelevantCommit] = Field(
default_factory=list,
description="Commit evidence explaining why this reviewer is relevant.",
)
reason: str | None = Field(
default=None,
max_length=500,
description="Why this reviewer was chosen — the evidence behind the routing (e.g. recent author on the affected surface, human correction precedent).",
)
is_skill_owner: bool = Field(
default=False,
description=(
"True when this entry was injected by the scout owner guardrail (an editor-controlled "
"`LLMSkillOwner`), rather than derived from commit authorship. Such entries route the "
"report but must never select the autostart task identity — otherwise a skill editor "
"could name a privileged teammate as owner and have an implementation agent run as them."
),
)
is_research_selected: bool = Field(
default=False,
description="Research selected this reviewer. Autostart requires independent ownership or commit confirmation.",
)
is_default_owner: bool = Field(
default=False,
description=(
"True when no evidence selected anyone and the report fell back to the project's default owner. "
"The entry routes the report, but it is not ownership evidence: removing it is not a routing "
"correction, and it never selects the autostart task identity."
),
)
source_skill: str | None = Field(
default=None,
description=(
"Name of the scout skill whose run wrote this entry, stamped server-side at the write. "
"Autostart unions this skill's current owners into its identity exclusion, so the "
"exclusion holds even when the run's best-effort edit tally was lost — the provenance "
"commits atomically with the pick itself. None for entries no scout wrote (pipeline, "
"custom agent, human edits)."
),
)
@field_validator("github_login")
@classmethod
def github_login_must_not_be_empty(cls, v: str | None) -> str | None:
if v is None:
return None
if not v.strip():
raise ValueError("must not be empty or whitespace-only")
# Strip on the way in: read-time enrichment and autostart look logins up with
# `login.lower()` and no strip, so a padded login would persist but never match.
return v.strip()
@field_validator("user_uuid")
@classmethod
def user_uuid_must_be_a_uuid(cls, v: str | None) -> str | None:
if v is None:
return None
# Canonicalize rather than keep the caller's spelling: readers match this value with a jsonb
# containment filter, where a differently-formatted UUID for the same user never hits.
try:
return str(UUID(v.strip()))
except (ValueError, AttributeError):
raise ValueError("must be a UUID")
@model_validator(mode="after")
def must_identify_a_reviewer(self) -> SuggestedReviewerEntry:
if not self.github_login and not self.user_uuid:
raise ValueError("must carry a github_login, a user_uuid, or both")
return self
class SuggestedReviewers(RootModel[list[SuggestedReviewerEntry]]):
"""Content schema for a `suggested_reviewers` artefact — the content root is a JSON list."""
class ReviewerState(BaseModel):
model_config = ConfigDict(extra="forbid", frozen=True)
reviewers_id: UUID | None = None
corrections_id: UUID | None = None
class PROwnerIdentityProof(BaseModel):
model_config = ConfigDict(extra="forbid", frozen=True)
source: Literal["github_user_integration", "github_oauth"]
user_uuid: UUID
github_user_id: int
verified_at: datetime
expires_at: datetime
class PROwnerIdentity(BaseModel):
model_config = ConfigDict(extra="forbid", frozen=True)
login: str = Field(pattern=r"^[a-z0-9](?:-?[a-z0-9]){0,38}$")
proof: PROwnerIdentityProof | None = None
class PROwnerAssignment(BaseModel):
model_config = ConfigDict(extra="forbid", frozen=True)
repository: str
pr_number: int = Field(gt=0)
owners: tuple[PROwnerIdentity, ...]
origin: Literal["report", "claim", "legacy"]
assigned_at: datetime
replaced_logins: tuple[str, ...] = ()
class ReviewerCorrections(BaseModel):
model_config = ConfigDict(extra="forbid", frozen=True)
pinned: tuple[SuggestedReviewerEntry, ...] = ()
excluded: tuple[SuggestedReviewerEntry, ...] = ()
confirmed: bool = False
needs_review: bool = False
class ReviewerProposal(BaseModel):
model_config = ConfigDict(extra="forbid", frozen=True)
expected_state: ReviewerState
source: str = "automatic"
outcome: Literal["selected", "no_suitable_owner", "lookup_failed"] = "selected"
retry_reason: str | None = Field(default=None, max_length=500)
# Why a scout edit found no suitable owner. Required before that outcome may clear a non-empty list.
outcome_reason: str | None = Field(default=None, max_length=500)
@model_validator(mode="after")
def validate_outcome(self) -> ReviewerProposal:
if self.outcome == "lookup_failed" and not self.retry_reason:
raise ValueError("A failed lookup needs a retry reason.")
return self
class ReviewerEdit(BaseModel):
model_config = ConfigDict(extra="forbid", frozen=True)
action: Literal["add", "remove", "replace", "confirm"]
expected_state: ReviewerState | None = None
class ChannelAssignment(BaseModel):
"""The space that currently owns a report. The latest assignment wins."""
channel_id: UUID | None = Field(description="Channel UUID, or null to leave the report unassigned.")
# The inbox renders the reason as one line under the report's evidence, so it is one sentence.
MAX_SOURCE_SUGGESTION_REASON_LENGTH = 300
class SourceSuggestion(BaseModel):
"""A product the team does not use that would have given this report better evidence.
The latest suggestion wins. The report API hides it while the product is in use, so a
suggestion stops showing once the team turns the product on, without a second write.
"""
product: SuggestedSourceProduct = Field(description="The product the team should turn on.")
reason: str = Field(
min_length=1,
max_length=MAX_SOURCE_SUGGESTION_REASON_LENGTH,
description=(
"One sentence on what this product would have shown for this report, specific to its "
"evidence. For example: 'Logs from the checkout service could show whether the timeout "
"starts at the payment provider.'"
),
)
# A scoring pass runs several models over one report (one served, the rest challengers), and every
# one of them lands in a single row. The cap bounds that row, so a manifest that grew past what a
# reader could order cannot make every report read expensive.
MAX_RANKING_MODEL_RESULTS = 5
# The serving manifest owns the role vocabulary, so `roles` stays free text. This is the one role
# a reader of these rows acts on: the model whose scores the inbox would order on.
RANKING_SERVED_ROLE = "served"
class RankingModelResult(BaseModel):
"""One model's part of a scoring pass.
The identity fields mirror the training dag's own columns and its `metadata.json`, so a stored
score joins to the model that wrote it without a lookup. A skipped result is kept rather than
dropped, because "this model could not score this report" is the coverage read the serving work
is measured on.
"""
# Pydantic reserves the `model_` prefix for its own API, so the guard is lifted here. Renaming
# the fields would break the join to the dag, which is the reason they carry these names.
model_config = ConfigDict(protected_namespaces=())
model_name: str = Field(description="Feature family the model belongs to, e.g. `report_embeddings`.")
model_version: str = Field(description="Training partition the model was fit on, as `YYYY-MM-DD`.")
model_kind: str = Field(description="Learner the model store loads the booster with, e.g. `xgboost`.")
roles: list[str] = Field(
default_factory=list,
description=(
"Roles the serving manifest gave this model in the pass. Exactly one result in a pass "
"carries `served`; the rest are challengers."
),
)
feature_schema_version: int = Field(
description="Feature contract version the scores were computed under, from the serving feature set."
)
status: Literal["scored", "skipped"] = Field(description="Whether this model produced probabilities.")
skip_reason: str | None = Field(
default=None, description="Why a skipped model produced no scores, e.g. a missing report vector."
)
# A head's score is consumed as a probability, by a threshold and by the composite score over
# the heads, so a raw margin stored here would be silently wrong rather than unusable. The
# bound belongs on the field so the generated schema carries it too.
scores: dict[str, Annotated[float, Field(ge=0.0, le=1.0)]] = Field(
default_factory=dict,
description="Outcome head name to its calibrated probability. Empty on a skipped model.",
)
# No upper bound: a lift reaches `1 / base_rate`.
lifts: dict[str, Annotated[float, Field(ge=0.0)]] = Field(
default_factory=dict,
description=(
"Outcome head name to its probability divided by the head's base rate "
"(`refit_classification_threshold`) from the model's metadata. Empty on a skipped model. "
"A head without a saved threshold has no entry."
),
)
metadata: dict[str, Any] = Field(
default_factory=dict,
description=(
"Copied from the model's metadata.json: training partition, feature set, per-head "
"readability and holdout summary, so a reader can judge a score without the model store."
),
)
@property
def key(self) -> str:
return f"{self.model_name}@{self.model_version}"
@field_validator("model_name", "model_version", "model_kind")
@classmethod
def identity_must_not_be_empty(cls, v: str) -> str:
if not v.strip():
raise ValueError("must not be empty or whitespace-only")
return v
@model_validator(mode="after")
def status_agrees_with_the_scores(self) -> RankingModelResult:
# `status` and `scores` are two statements about the same thing, so a row that disagrees
# with itself is worse than a missing one: a scored result with no score reads as a model
# that ran, and `RankingScore` would accept it as the served entry, leaving a reader with
# a served model it can get no probability out of.
if self.status == "scored" and not self.scores:
raise ValueError("a scored model must carry at least one score")
if self.status == "skipped" and self.scores:
raise ValueError("a skipped model must carry no scores")
return self
class RankingScore(BaseModel):
"""Content schema for a `ranking_score` artefact: one scoring pass over one report.
A pass writes one artefact carrying every model it ran, so latest-row-wins gives a reader the
report's whole current score in one row. Splitting a pass over one row per model would make
"the current served score" a question about several rows, and a pass that scored a different
set of models than the last one would leave stale rows looking current.
"""
scored_at: datetime = Field(description="When the sweep scored the report.")
embedding_inserted_at: datetime | None = Field(
default=None,
description=(
"Landing time of the report vector the pass scored, which is the sweep's idempotency "
"key. Absent when no model in the pass read a vector."
),
)
manifest_version: str = Field(description="Version of the serving manifest that chose the models for the pass.")
served_key: str = Field(
description="Key in `results` of the model whose scores the inbox would order on, as `<model_name>@<model_version>`."
)
results: dict[str, RankingModelResult] = Field(
min_length=1,
max_length=MAX_RANKING_MODEL_RESULTS,
description="Every model the pass ran, keyed by `<model_name>@<model_version>`.",
)
@field_validator("manifest_version", "served_key")
@classmethod
def must_not_be_empty(cls, v: str) -> str:
if not v.strip():
raise ValueError("must not be empty or whitespace-only")
return v
@model_validator(mode="after")
def served_score_is_resolvable(self) -> RankingScore:
# A consumer reads the served score as `results[served_key]`, so each rule here closes one
# way that expression returns the wrong thing or nothing at all.
served_keys = []
for key, result in self.results.items():
if key != result.key:
raise ValueError(f"result key {key!r} does not match its model {result.key!r}")
if RANKING_SERVED_ROLE in result.roles:
served_keys.append(key)
if len(served_keys) != 1:
raise ValueError(f"exactly one result must carry the {RANKING_SERVED_ROLE!r} role, got {served_keys}")
if self.served_key not in self.results:
raise ValueError(f"served_key {self.served_key!r} is not a key of results")
served = self.results[self.served_key]
if RANKING_SERVED_ROLE not in served.roles:
raise ValueError(f"served_key {self.served_key!r} does not carry the {RANKING_SERVED_ROLE!r} role")
if served.status != "scored":
raise ValueError(f"served_key {self.served_key!r} is {served.status}, so the pass has no served score")
return self
# Reason-only routing feedback still needs to reach the authoring scout.
DISMISSAL_REASON_WRONG_ASSIGNEE = "wrong_assignee"
# Shared by the dismissal writer and repository-corrections reader so they cannot drift apart.
DISMISSAL_REASON_WRONG_REPO = "wrong_repo"
# Reason codes that claim the issue is fixed, rather than stating a preference about the report.
# A later matching signal contradicts the claim, so the grouping stage treats these dismissals the
# way it treats a resolved report: the recurrence gets a fresh report (see `recurrence.py`). The
# `wrong_repo` can also start a fresh report, but does not claim a previous fix.
FIXED_DISMISSAL_REASONS = frozenset({"already_fixed", "fixed_outside_posthog", "pr_merged"})
# Bounds shared by the state API and this schema, so the generic artefact endpoint cannot store a
# dismissal the state API would reject. Readers scan these rows in bulk (`repo_corrections`), so an
# unbounded row is a cost on every repository selection, not just on the write.
DISMISSAL_NOTE_MAX_LENGTH = 4000
DISMISSAL_REASON_MAX_LENGTH = 128
# GitHub caps owners at 39 and repositories at 100 characters.
DISMISSAL_REPOSITORY_MAX_LENGTH = 512
DISMISSAL_IDENTITY_MAX_LENGTH = 128
class Dismissal(BaseModel):
"""Feedback records retain their verdict because the report can change state later.
The user fields predate row-level attribution and are kept for compatibility with existing
rows and readers; new rows also carry attribution on the artefact row itself.
"""
state: Literal["resolved", "suppressed", "potential"] | None = Field(
default=None,
description="Report verdict when this feedback was recorded. Null on legacy feedback with no recorded verdict.",
)
reason: str | None = Field(
default=None, max_length=DISMISSAL_REASON_MAX_LENGTH, description="Caller-owned dismissal reason code."
)
note: str | None = Field(
default=None, max_length=DISMISSAL_NOTE_MAX_LENGTH, description="Free-form dismissal note."
)
selected_repository: str | None = Field(
default=None,
max_length=DISMISSAL_REPOSITORY_MAX_LENGTH,
description=(
"Repository the pipeline had selected when the report was dismissed, in 'owner/repo' "
"format. Recorded on wrong-repo dismissals so selection mistakes are queryable without "
"joining the repo_selection artefact history."
),
)
corrected_repository: str | None = Field(
default=None,
max_length=DISMISSAL_REPOSITORY_MAX_LENGTH,
description=(
"Repository the dismisser said the report should have targeted, in 'owner/repo' format. "
"Fed back into future repository selection for the project."
),
)
user_id: int | None = Field(default=None, description="ID of the dismissing user, when known.")
user_uuid: str | None = Field(
default=None, max_length=DISMISSAL_IDENTITY_MAX_LENGTH, description="UUID of the dismissing user, when known."
)
slack_user_id: str | None = Field(
default=None,
max_length=DISMISSAL_IDENTITY_MAX_LENGTH,
description="Slack user who dismissed via a Slack action, when that's where the click came from.",
)
class VideoSegment(RootModel[dict[str, Any] | list[Any]]):
"""Content schema for a `video_segment` artefact.
Deliberately permissive: the type predates this registry and has no in-repo production
writer, so any JSON object/array validates rather than guessing at a shape.
"""
# ── Log artefact schemas ─────────────────────────────────────────────────────────
#
# Log artefacts record discrete work done on a report; they accumulate and are addressable by id.
# Bounds for referenced source text: references are pointers with a small excerpt, not a vehicle
# for shipping file contents into the report log.
_MAX_CODE_LINE_LENGTH = 1000
_MAX_CODE_REFERENCE_LINES = 20
class CodeReference(BaseModel):
"""Content schema for a `code_reference` artefact: a contiguous span of source lines.
A single-line callout is just `start_line == end_line`.
"""
file_path: str = Field(description="Repository-relative path to the referenced file.")
start_line: int = Field(ge=1, description="First line of the referenced range (1-indexed, inclusive).")
end_line: int = Field(ge=1, description="Last line of the referenced range (1-indexed, inclusive).")
contents: str = Field(
description=f"The exact source text of lines start_line through end_line. At most "
f"{_MAX_CODE_REFERENCE_LINES} lines of at most {_MAX_CODE_LINE_LENGTH} characters each."
)
relevance_note: str = Field(
description="Short note on why this code is relevant to the report.",
)
@field_validator("file_path", "contents", "relevance_note")
@classmethod
def fields_must_not_be_empty(cls, v: str) -> str:
if not v.strip():
raise ValueError("must not be empty or whitespace-only")
return v
@field_validator("contents")
@classmethod
def contents_must_be_bounded(cls, v: str) -> str:
lines = v.split("\n")
if len(lines) > _MAX_CODE_REFERENCE_LINES:
raise ValueError(f"must not exceed {_MAX_CODE_REFERENCE_LINES} lines")
if any(len(line) > _MAX_CODE_LINE_LENGTH for line in lines):
raise ValueError(f"lines must not exceed {_MAX_CODE_LINE_LENGTH} characters")
return v
@model_validator(mode="after")
def line_span_must_be_valid(self) -> CodeReference:
if self.end_line < self.start_line:
raise ValueError("end_line must be greater than or equal to start_line")
if self.end_line - self.start_line + 1 > _MAX_CODE_REFERENCE_LINES:
raise ValueError(f"the referenced range must not exceed {_MAX_CODE_REFERENCE_LINES} lines")
return self
class Commit(BaseModel):
"""Content schema for a `commit` artefact: one commit pushed in relation to the report.
Recorded automatically by the agent harness after each successful signed-commit push (one
artefact per commit), so the report log shows exactly what landed, when, and from which task.
A `commit` artefact only ever records a commit that has already been pushed to a remote branch;
recording an unpushed or local-only commit is always a mistake.
`diff` is an optional point-in-time snapshot of the reviewed code, set only by consumers that
snapshot what they reviewed (e.g. ReviewHog's per-turn diff); the Signals pipeline never sets it.
"""
repository: str = Field(description="GitHub repository the commit was pushed to, as `owner/repo`.")
branch: str = Field(description="Branch the commit was pushed to.")
commit_sha: str = Field(description="Full or abbreviated SHA of the pushed commit.")
message: str = Field(description="The commit message headline.")
note: str | None = Field(default=None, description="Optional short note on what this commit does.")
diff: str | None = Field(
default=None,
description="Optional point-in-time unified diff of the reviewed code, set only by "
"snapshotting consumers (e.g. ReviewHog); the Signals pipeline never populates it.",
)
@field_validator("repository", "branch", "commit_sha", "message")
@classmethod
def fields_must_not_be_empty(cls, v: str) -> str:
if not v.strip():
raise ValueError("must not be empty or whitespace-only")
return v
class TaskRunArtefact(BaseModel):
"""Content schema for a `task_run` artefact: a reference to a `tasks.Task` run executed for
the report (research, implementation, …), surfaced as an entry in the report work log.
`product` / `type` follow the custom-agent identifier shape: the built-in signals pipeline
uses `product="signals"` with `type` in `{research, implementation, repo_selection}`, while a
custom agent supplies its own `identifier()` pair. The artefact is only a pointer — the run's
logs, status and output are read live from the tasks API by `task_id` / `run_id`.
"""
task_id: str = Field(description="UUID of the `tasks.Task` this run belongs to.")
run_id: str | None = Field(default=None, description="UUID of the specific `TaskRun`, if known.")
automation_branch: str | None = Field(
default=None,
description="Server-generated branch for this automatically started implementation run. Absent on manual runs.",
)
product: str = Field(
description="Product that ran the task — `signals` for the built-in pipeline, or a custom agent's "
"product identifier."
)
type: str = Field(
description="Task type within the product — e.g. `research` / `implementation` / `repo_selection` "
"for the signals pipeline, or a custom agent's type identifier."
)
@field_validator("task_id")
@classmethod
def task_id_must_not_be_empty(cls, v: str) -> str:
if not v.strip():
raise ValueError("must not be empty or whitespace-only")
return v
@field_validator("product", "type")
@classmethod
def identifier_part_must_be_routing_safe(cls, v: str) -> str:
normalized = v.strip()
if not _IDENTIFIER_PART_RE.fullmatch(normalized):
raise ValueError(
"must contain only lowercase letters, numbers, underscores, or hyphens, "
"and must start with a lowercase letter or number"
)
return normalized
# ── Task-run vocabulary ──────────────────────────────────────────────────────────
#
# A `task_run` artefact carries a `(product, type)` pair. The built-in signals pipeline uses
# `product="signals"` with one of the `TASK_RUN_TYPE_*` types below; custom agents supply their
# own identifier pair. These live in this leaf module so both the artefact helpers and the
# `SignalReport` model can share them without an import cycle (`task_run_artefacts` re-exports
# them for existing importers).
SIGNALS_PRODUCT = "signals"
TASK_RUN_TYPE_REPO_SELECTION = "repo_selection"
TASK_RUN_TYPE_RESEARCH = "research"
TASK_RUN_TYPE_IMPLEMENTATION = "implementation"
# A discuss-the-report task started by a user from the Inbox (not the automated research run).
TASK_RUN_TYPE_DISCUSSION = "discussion"
# The scout run that authored the report via `emit_report` (or first touched it via `edit_report`) —
# links the report back to the scout's own run so its transcript is reachable from the work log.
TASK_RUN_TYPE_SCOUT = "scout"
# Generic identifiers for a legacy `SignalReportTask` row with no `(product, type)` label — an
# unlabelled link from the brief link-only window before associations carried identifiers.
_LEGACY_TASK_RUN_PRODUCT = "tasks"
_LEGACY_TASK_RUN_TYPE = "agent_run"
_SIGNALS_TASK_RUN_TYPES = frozenset(
{
TASK_RUN_TYPE_REPO_SELECTION,
TASK_RUN_TYPE_RESEARCH,
TASK_RUN_TYPE_IMPLEMENTATION,
TASK_RUN_TYPE_DISCUSSION,
}
)
def task_run_identifier_for_legacy_relationship(relationship: str | None) -> tuple[str, str]:
"""Map a legacy `SignalReportTask.relationship` to the `(product, type)` its `task_run` artefact
would carry — the same mapping `backfill_task_run_artefacts` applies. A labelled signals
relationship keeps its label under `product="signals"`; anything else (including the unlabelled
link-only rows) collapses to the generic `tasks` / `agent_run` identifiers.
"""
if relationship is not None and relationship in _SIGNALS_TASK_RUN_TYPES:
return SIGNALS_PRODUCT, relationship
return _LEGACY_TASK_RUN_PRODUCT, _LEGACY_TASK_RUN_TYPE
class NoteArtefact(BaseModel):
"""Content schema for a `note` artefact: a free-form note authored by an agent or by code."""
note: str = Field(description="The note text (markdown allowed).")
author: str | None = Field(default=None, description="Optional label for who authored the note.")
analytics_query_context: list[dict[str, JsonValue]] | None = Field(
default=None,
exclude_if=lambda value: value is None,
description="Frozen source queries that gate access to the note's evidence.",
)
restricted_to_user_id: int | None = Field(
default=None,
exclude_if=lambda value: value is None,
description="Acting user allowed to read assessment evidence from additional sources.",
)
source_check_ids: list[str] | None = Field(
default=None,
exclude_if=lambda value: value is None,
description="Follow-up checks whose evidence informed this note.",
)
@field_validator("note")
@classmethod
def note_must_not_be_empty(cls, v: str) -> str:
if not v.strip():
raise ValueError("must not be empty or whitespace-only")
return v
class CheckAuthoringStatus(BaseModel):
status: Literal["succeeded", "failed"]
reason: str = Field(min_length=1)
class ScoutNoteLeft(BaseModel):
"""Content schema for a `scout_note_left` artefact: a person left a scout note from this report.
Appended by the notes API in the same transaction as the note, so the report keeps a record of
the steering after the note itself is retired. Never written through the generic artefact API.
"""
note: str = Field(description="The note text as its author wrote it, without the report reference.")
skill_name: str = Field(
default="", description="The scout the note was addressed to, or blank for every scout on the project."
)
scout_note_id: str = Field(description="The id of the scout note this entry records.")
class TitleChange(BaseModel):
"""Content schema for a `title_change` artefact: a record of an edit to the report's title.
Appended automatically by the report edit path whenever the title actually changes, capturing
the value before and after so the report carries an audit trail of who renamed it and when.
Never written through the generic artefact API (it is read-only there) — it only ever reflects
a real edit that was applied to the report.
"""
old_title: str | None = Field(
default=None, description="The report's title before this edit (null if it had no title)."
)
new_title: str = Field(description="The report's title after this edit.")
@field_validator("new_title")
@classmethod
def new_title_must_not_be_empty(cls, v: str) -> str:
if not v.strip():
raise ValueError("must not be empty or whitespace-only")
return v
# The edit history outlives the edit, so a token pasted and then edited out must not stay here.
@field_validator("old_title", "new_title")
@classmethod
def redact_title_credentials(cls, v: str | None) -> str | None:
return None if v is None else redact_credentials(v)
class SummaryChange(BaseModel):
"""Content schema for a `summary_change` artefact: a record of an edit to the report's summary
(its human-facing description).
Appended automatically by the report edit path whenever the summary actually changes, capturing
the value before and after. Like `title_change`, it is read-only through the generic artefact
API and only ever reflects a real edit applied to the report.
"""
old_summary: str | None = Field(
default=None, description="The report's summary before this edit (null if it had no summary)."
)
new_summary: str = Field(description="The report's summary after this edit.")
@field_validator("new_summary")
@classmethod
def new_summary_must_not_be_empty(cls, v: str) -> str:
if not v.strip():
raise ValueError("must not be empty or whitespace-only")
return v
# The edit history outlives the edit, so a token pasted and then edited out must not stay here.
@field_validator("old_summary", "new_summary")
@classmethod
def redact_summary_credentials(cls, v: str | None) -> str | None:
return None if v is None else redact_credentials(v)
class RelatedTo(BaseModel):
"""Content schema for a `related_to` artefact: an untyped link from this report to another
`SignalReport`. Written symmetrically (both reports get an entry pointing at the other), so the
link is discoverable from either side without a model change and the grouping dataset can be
reconstructed later. Direction isn't tracked — the two rows' `created_at` order captures it. The
grouping pipeline writes this pair when a signal that would have grouped into an already-resolved
report spawns a fresh report instead (resolved reports never reopen).
"""
report_id: str = Field(description="UUID of the related SignalReport.")
@field_validator("report_id")
@classmethod
def report_id_must_not_be_empty(cls, v: str) -> str:
if not v.strip():
raise ValueError("must not be empty or whitespace-only")
return v
MAX_REPORT_LINK_REASON_LENGTH = 500
# One write declares one report's place in a stack, so a handful of links is the whole shape. The cap
# bounds the per-link cycle check each write does.
MAX_REPORT_LINKS_PER_WRITE = 10
class ReportLink(BaseModel):
"""Content schema for a `report_link` artefact: a typed, directed link from this report to
another `SignalReport`. The row reads as a sentence starting at the report it is written on:
"this report `kind` the report named by `report_id`".
Unlike `related_to`, nothing is mirrored onto the target. The direction is the payload, so
writing the reverse row would assert the opposite relationship. A reader that wants both
sides queries the type from either end.
`SignalReportArtefact.add_log` rejects a link that names the report it is written on, a link
to a report outside the writing team, and a link that closes a cycle of the same kind, so an
ordering the pipeline reads (a stack of dependent pull requests) can never contradict itself.
"""
kind: ReportLinkKind = Field(description="How this report relates to the report named by `report_id`.")
report_id: str = Field(description="UUID of the SignalReport this link points at, in the same project.")
reason: str | None = Field(
default=None,
max_length=MAX_REPORT_LINK_REASON_LENGTH,
description="Optional one-line note on why the reports are linked this way.",
)
@field_validator("report_id")
@classmethod
def report_id_must_be_a_uuid(cls, v: str) -> str:
try:
return str(UUID(v.strip()))
except ValueError:
raise ValueError("must be a UUID")
# One report is about a handful of issues at most. The cap bounds the writeback each write can start.
MAX_SOURCE_ISSUES_PER_WRITE = 5
class SourceIssue(BaseModel):
"""Content schema for a `source_issue` artefact: an issue in an external tracker that this
report is about, one row per issue.
A scout that files a report about a GitHub issue records it here, so the GitHub writeback can
comment on the issue and grouping can attach the issue's own signal to this report instead of
opening a second one. `url` is normalized from (`repository`, `number`), so an exact match on it
finds every report about one issue. GitHub is the only provider today; the field leaves room for
others.
"""
provider: Literal["github"] = Field(default="github", description="Tracker the issue lives in.")
repository: str = Field(description="`owner/repo` of the issue, lowercased.")
number: int = Field(gt=0, description="Issue number in the repository.")
url: str = Field(description="Normalized issue URL, `https://github.com/<owner>/<repo>/issues/<number>`.")
# GitHub compares repository paths without case, so one spelling keeps one issue one row.
@field_validator("repository")
@classmethod
def repository_is_lowercase(cls, v: str) -> str:
return v.lower()
@model_validator(mode="after")
def url_must_be_normalized(self) -> SourceIssue:
if self.url != f"https://github.com/{self.repository}/issues/{self.number}":
raise ValueError("url must be the normalized URL of `repository` and `number`")
return self
@classmethod
def github(cls, repository: str, number: int) -> SourceIssue:
repository = repository.lower()
return cls(repository=repository, number=number, url=f"https://github.com/{repository}/issues/{number}")
MAX_AUTOSTART_SKIP_DETAIL_LENGTH = 500
class AutostartSkip(BaseModel):
"""Content schema for an `autostart_skip` artefact: automatic implementation was held back by a
typed link to another report.
Only the link gates write this. The other auto-start skips are properties of the report itself
(not actionable, no priority, over quota), and a reader inspecting the report sees those
already. A link gate is the one case where the reason lives on a *different* report, so without
a row on the log the inbox can only show that nothing started.
"""
skip_reason: Literal["duplicate_of", "blocked_by_dependency", "plan_parent"] = Field(
description="Which link gate held the report back."
)
linked_report_id: str | None = Field(
default=None,
description="UUID of the report the gate acted on, when one report decided it.",
)
detail: str = Field(
max_length=MAX_AUTOSTART_SKIP_DETAIL_LENGTH,
description="One line a reader can act on, naming what has to happen before work starts.",
)
@field_validator("linked_report_id")
@classmethod
def linked_report_id_must_be_a_uuid(cls, v: str | None) -> str | None:
if v is None:
return None
try:
return str(UUID(v.strip()))
except ValueError:
raise ValueError("must be a UUID")
class ImplementationTarget(BaseModel):
task_id: UUID
run_id: UUID
claim_id: UUID | None = None
pr_url: str
head_sha: str = Field(min_length=1)
automation_artefact_id: UUID
class ImplementationAssessment(BaseModel):
obsolete_pr_urls: list[str] = Field(
description="Only URLs from the supplied PostHog candidates whose fixes must be replaced. Empty means keep them all."
)
reason: str = Field(min_length=1, description="What changed and why these specific fixes no longer fit.")
class ImplementationDecision(BaseModel):
"""Server-bound research recommendation, protected because it authorizes replacement work."""
supersede: bool = Field(
description=(
"True only when what you found changes what the fix should be — a different root cause, "
"a different file or layer, a materially wider or narrower scope. More evidence for the "
"same fix is not a reason to set this, because the open pull request already implements "
"that fix. A true decision can start an automated replacement; selected predecessors "
"close only after the replacement completes with verified open PRs."
)
)
reason: str = Field(
description="One or two sentences naming what changed and why the existing pull request no longer fits."
)
targets: list[ImplementationTarget] = Field(default_factory=list)
research_run_count: int | None = None
research_started_at: datetime | None = None
content_revision_count: int = 0
blocked_reason: Literal["revision_limit"] | None = None
@field_validator("reason")
@classmethod
def reason_must_not_be_empty(cls, v: str) -> str:
if not v.strip():
raise ValueError("must not be empty or whitespace-only")
return v
class ImplementationReplacement(BaseModel):
decision_id: UUID
decision: ImplementationDecision
run_id: UUID
class ImplementationDispatch(BaseModel):
decision_id: UUID
source_skill: str | None = None
status: Literal["pending", "processing", "retrying", "blocked", "started", "cancelled"] = "pending"
attempt: int = 0
next_retry_at: datetime | None = None
worker_token: UUID | None = None
lease_until: datetime | None = None
reason: str = ""
class ImplementationHandover(BaseModel):
replacement_id: UUID
status: Literal["processing", "completed", "failed", "cancelled", "needs_attention"]
results: dict[str, Literal["closed", "already_closed", "skipped"]] = Field(default_factory=dict)
replacement_pr_urls: list[str] = Field(default_factory=list)
explanation: str = ""
attempt: int = 0
worker_token: UUID | None = None
lease_until: datetime | None = None
class CodeReviewCounts(BaseModel):
"""One review turn's valid findings by effective priority (threshold-independent)."""
must_fix: int = Field(default=0, description="Validator-confirmed findings at must_fix priority.")
should_fix: int = Field(default=0, description="Validator-confirmed findings at should_fix priority.")
consider: int = Field(default=0, description="Validator-confirmed findings at consider priority.")
class CodeReview(BaseModel):
"""Content schema for a `code_review` artefact: one ReviewHog review turn over the report's
implementation output.
Pointer-first: counts + links + the `review_report_id` drill-down handle (the SQL join key into
the review_hog tables). The full rendered body lives on `ReviewReport.report_markdown` — even for
stored-only turns — and is never duplicated here. System-generated: the ReviewHog workflow is the
only writer, so the type is read-only through the generic artefact API.
"""
review_report_id: str = Field(description="ReviewHog ReviewReport UUID — the drill-down handle (SQL join key).")
repository: str = Field(description="GitHub repository the reviewed code lives in, as 'owner/repo'.")
head_sha: str = Field(description="The reviewed head commit SHA.")
head_branch: str = Field(description="The reviewed head branch.")
base_branch: str = Field(description="The branch the reviewed diff was computed against.")
pr_number: int | None = Field(default=None, description="PR number; absent for branch-only targets.")
pr_url: str | None = Field(default=None, description="PR URL; absent for branch-only targets.")
review_url: str | None = Field(default=None, description="GitHub review permalink, when published.")
outcome: Literal["published", "stored", "failed"] = Field(
description=(
"What the turn did: 'published' (comments posted to the PR), 'stored' (findings persisted "
"only — no PR, nothing publishable, or publishing off), or 'failed' (the turn errored)."
)
)
counts: CodeReviewCounts = Field(
default_factory=CodeReviewCounts,
description="Valid (is_valid=True) findings by effective priority, independent of the publish threshold.",
)
class WorkClaim(BaseModel):
display_name: str | None = Field(
default=None, description="Server-generated actor label at claim time. Null for older claims."
)
class WorkRelease(BaseModel):
reason: Literal["released", "taken_over"] = Field(description="Why ownership ended.")
class PullRequestLink(BaseModel):
url: str = Field(description="Canonical GitHub pull request URL.")
class CheckResult(BaseModel):
"""Content schema for a `check_result` artefact: one run of a `SignalReportCheck`.
The forward-looking half of a report's log. A report says what was true when it was written; a
check result says whether that still holds, measured on the check's own schedule. System-generated
— the check executor is the only writer, so the type is read-only through the generic artefact API.
"""
check_id: str = Field(description="UUID of the SignalReportCheck this run belongs to.")
kind: str = Field(description="The check's kind, e.g. `metric_threshold`.")
title: str = Field(description="The check's title, copied so the log entry reads on its own.")
outcome: CheckOutcome = Field(
description=(
"`passed` (the expectation held), `failed` (it did not), `errored` (the check could not be measured), "
"or `inconclusive` (the run worked but could not settle the claim)."
)
)
explanation: str = Field(description="One line saying what was measured and how it compared.")
reason: CheckInconclusiveReason | None = Field(
default=None,
description=(
"Why an `inconclusive` run could not settle the claim. Required on `inconclusive`, absent on any other "
"outcome."
),
)
observed_value: float | None = Field(default=None, description="The measured value; absent when the run errored.")
baseline_value: float | None = Field(
default=None, description="The value recorded when the check was written, when the author gave one."
)
threshold: str | None = Field(default=None, description="The expectation the value was compared against.")
run_id: str | None = Field(
default=None,
description="Scout run that answered an `agent` check. Absent on a deterministic run, which has none.",
)
@field_validator("explanation")
@classmethod
def explanation_must_not_be_empty(cls, v: str) -> str:
if not v.strip():
raise ValueError("must not be empty or whitespace-only")
return v
@model_validator(mode="after")
def reason_must_match_outcome(self) -> CheckResult:
if (self.outcome == "inconclusive") != (self.reason is not None):
raise ValueError("`reason` is required on an `inconclusive` result and refused on any other")
return self
class CheckObservation(BaseModel):
explanation: str
check_id: str
title: str
monitoring_started_at: datetime
measured_at: datetime
monitoring_ends_at: datetime | None = None
value_format: ReportMetricValueFormat | None = None
unit: str | None = Field(default=None, max_length=MAX_METRIC_UNIT_LENGTH)
comparison: CheckComparison | None = None
observed_value: float | None = Field(default=None, allow_inf_nan=False)
matches: bool | None = None
error: str | None = None
@model_validator(mode="after")
def measurement_is_complete(self) -> CheckObservation:
if self.measured_at <= self.monitoring_started_at:
raise ValueError("An observation must end after Monitoring starts.")
if self.monitoring_ends_at is not None and self.measured_at >= self.monitoring_ends_at:
raise ValueError("An interim observation must precede the Monitoring deadline.")
if self.error is None:
if self.observed_value is None or self.matches is None or self.comparison is None:
raise ValueError("A measured observation needs its value, comparison, and match result.")
elif not self.error.strip() or self.observed_value is not None or self.matches is not None:
raise ValueError("An errored observation needs an error and no measured result.")
return self
class CheckLifecycleEntry(BaseModel):
"""What every entry in a check's life carries, so the three cannot drift apart.
A check soaks for days before its first run, so its verdict alone leaves the log silent over
the window a reader most wants explained. These types fill that silence. All are
system-generated: `check_result`'s writer is the executor, and the writers below are in
`report_check_artefacts`.
"""
check_id: str = Field(description="UUID of the SignalReportCheck this entry describes.")
kind: str = Field(description="The check's kind, e.g. `metric_threshold`.")
title: str = Field(description="The check's title, copied so the log entry reads on its own.")
class CheckScheduled(CheckLifecycleEntry):
"""A check now watches this report: when it runs, what it watches, and which lane answers it."""
rationale: str = Field(default="", description="Why the author wrote the check, in their own words.")
next_run_at: str = Field(description="ISO 8601 date of the first run. Provisional when `arms_on_resolve`.")
arms_on_resolve: bool = Field(
description="True when the report has not resolved yet, so the clock starts at the resolve."
)
soak_minutes: int | None = Field(
default=None, description="How long after the resolve the first run waits. Absent on a dated check."
)
skill_name: str | None = Field(
default=None,
description="Scout skill that answers an `agent` check. Absent when it runs on the fleet's follow-up scout.",
)
runs: int = Field(default=1, description="How many runs the check was written for.")
class CheckExpired(CheckLifecycleEntry):
"""A check reached its horizon without deciding, the one transition nobody chose.
An absent `last_run_at` is what a reader acts on: the claim was never re-measured, so the
report's conclusion still stands unverified.
"""
expired_at: str = Field(description="ISO 8601 time the sweep retired the check.")
last_run_at: str | None = Field(
default=None, description="ISO 8601 time of the last run. Absent when the check never ran at all."
)
class CheckCancelled(CheckLifecycleEntry):
"""A check was stopped before it could decide.
Kept apart from `check_scheduled` so each entry records one transition and the renderer reads
the type rather than a nullable field.
"""
reason: Literal[
"stopped_by_person",
"stopped_by_scout",
"replaced_by_research",
"replaced_by_request",
"no_check_lane",
"monitoring_completed",
] = Field(description="Which path stopped the check.")
# ── Type mapping ─────────────────────────────────────────────────────────────────
# Content models that describe the report's current state (latest row of each type wins) vs
# entries that record discrete work (accumulate). `SignalFinding` (keyed by signal_id) and
# `Dismissal` (stacking) have their own semantics; `VideoSegment` is a legacy plain append.
class ImpactMeasurementPlan(BaseModel):
"""One version of a proposed impact measurement, keyed by metric_id within a report."""
model_config = ConfigDict(extra="forbid")
metric_id: str = Field(max_length=100)
title: str = Field(max_length=200)
kind: str
query: dict[str, Any]
value_format: str = "number"
unit: str | None = None
goal_value: float
goal_direction: Literal["at_most", "at_least"]
goal_grain: Literal["whole_window", "per_interval"] = "whole_window"
decision_window_days: int | None = Field(default=None, ge=1, le=30)
minimum_data_points: int | None = Field(default=None, ge=1, le=1000)
eligibility_query: dict[str, Any] | None = None
activated: bool = Field(default=False, strict=True)
retired: bool = Field(default=False, strict=True)
@field_validator("goal_value", "decision_window_days", "minimum_data_points", mode="before")
@classmethod
def reject_coerced_flags_and_counts(cls, value: object) -> object:
if isinstance(value, bool):
raise ValueError("provide a number, not a boolean")
return value
@model_validator(mode="after")
def validate_measurement(self) -> ImpactMeasurementPlan:
from products.signals.backend.report_metrics import ReportMetric
validated_metric = ReportMetric.model_validate(
self.model_dump(exclude={"activated", "retired", "goal_grain", "eligibility_query"})
)
self.metric_id = validated_metric.metric_id
if self.minimum_data_points is not None and self.eligibility_query is None:
raise ValueError("minimum_data_points requires an eligibility_query for qualifying opportunities")
if self.eligibility_query is not None:
ReportMetric.model_validate(
{
"metric_id": "eligible",
"title": "Qualifying opportunities",
"kind": "occurrences",
"value_format": "count",
"query": self.eligibility_query,
}
)
return self
StatusArtefactContent = (
CheckAuthoringStatus
| SafetyJudgment
| ActionabilityAssessment
| PriorityAssessment
| RepoSelectionResult
| SuggestedReviewers
| ReviewerCorrections
| ChannelAssignment
| ImplementationDecision
| ImplementationDispatch
| RankingScore
| SourceSuggestion
)
LogArtefactContent = (
CodeReference
| PROwnerAssignment
| Commit
| TaskRunArtefact
| NoteArtefact
| ScoutNoteLeft
| TitleChange
| SummaryChange
| CodeReview
| RelatedTo
| ReportLink
| SourceIssue
| AutostartSkip
| WorkClaim
| WorkRelease
| PullRequestLink
| CheckResult
| CheckObservation
| CheckScheduled
| CheckExpired
| CheckCancelled
| ImplementationReplacement
| ImplementationHandover
| ImpactMeasurementPlan
)
ArtefactContent = StatusArtefactContent | LogArtefactContent | SignalFinding | Dismissal | VideoSegment
# Keys are `SignalReportArtefact.ArtefactType` values, kept as plain strings so this module stays
# Django-free; a test asserts the key set matches the model enum exactly.
ARTEFACT_CONTENT_SCHEMAS: Mapping[str, type[BaseModel]] = {
"video_segment": VideoSegment,
"safety_judgment": SafetyJudgment,
"actionability_judgment": ActionabilityAssessment,
"priority_judgment": PriorityAssessment,
"signal_finding": SignalFinding,
"repo_selection": RepoSelectionResult,
"suggested_reviewers": SuggestedReviewers,
"reviewer_corrections": ReviewerCorrections,
"pr_owner_assignment": PROwnerAssignment,
"channel_assignment": ChannelAssignment,
"ranking_score": RankingScore,
"dismissal": Dismissal,
"code_reference": CodeReference,
"commit": Commit,
"task_run": TaskRunArtefact,
"note": NoteArtefact,
"check_authoring": CheckAuthoringStatus,
"scout_note_left": ScoutNoteLeft,
"title_change": TitleChange,
"summary_change": SummaryChange,
"code_review": CodeReview,
"related_to": RelatedTo,
"report_link": ReportLink,
"source_issue": SourceIssue,
"autostart_skip": AutostartSkip,
"work_claim": WorkClaim,
"work_release": WorkRelease,
"pull_request": PullRequestLink,
"check_result": CheckResult,
"check_observation": CheckObservation,
"check_scheduled": CheckScheduled,
"check_expired": CheckExpired,
"check_cancelled": CheckCancelled,
"implementation_decision": ImplementationDecision,
"implementation_dispatch": ImplementationDispatch,
"implementation_replacement": ImplementationReplacement,
"implementation_handover": ImplementationHandover,
"impact_measurement_plan": ImpactMeasurementPlan,
"source_suggestion": SourceSuggestion,
}
_ARTEFACT_TYPE_BY_MODEL: Mapping[type[BaseModel], str] = {model: t for t, model in ARTEFACT_CONTENT_SCHEMAS.items()}
# Artefact types the write API must reject. `video_segment` is a legacy, fully-permissive type
# (`dict | list`, so even `{}` validates) that predates the typed-content contract; accepting writes
# would let callers persist arbitrary or empty payloads. It stays readable so stored legacy rows
# still parse, but new ones can never be created or updated through the API.
# `title_change` / `summary_change` are system-generated edit-history records: the report edit path
# is their only writer, so accepting them through the generic API would let a caller fabricate edits
# that never happened. They stay readable (and so show up in the report's artefact log) but cannot
# be created or edited directly.
# `check_result` is likewise system-generated — the check executor is its only writer; accepting it
# through the API would let a caller fabricate a verdict for a soak that never ran. The three
# lifecycle types around it are closed for the same reason: a fabricated `check_scheduled` claims a
# watch nobody set up, and a fabricated `check_expired` or `check_cancelled` retires one that is
# still running.
# `code_review` is likewise system-generated — the ReviewHog workflow is its only writer; accepting
# it through the API would let a caller fabricate review receipts for reviews that never ran.
# `autostart_skip` records a decision only auto-start can make. Accepting it through the API would
# let a caller claim work was held back by a gate that never ran.
# Replacement decisions, reservations, and outcomes authorize GitHub closures. Only the server
# may write them; API writes would let callers fabricate automation provenance or completion.
# `ranking_score` is model output: the scoring sweep is its only writer, so accepting it through
# the API would let a caller fabricate a probability the model never produced.
# `source_issue` is written by the report authoring tools, which validate the URL and start the
# writeback that comments on the issue. A row written here would route another issue's signals
# into this report without either.
NON_WRITABLE_ARTEFACT_TYPES: frozenset[str] = frozenset(
{
"reviewer_corrections",
"pr_owner_assignment",
"task_run",
"video_segment",
"title_change",
"summary_change",
"scout_note_left",
"code_review",
"work_claim",
"work_release",
"pull_request",
"check_result",
"check_observation",
"check_scheduled",
"check_authoring",
"check_expired",
"check_cancelled",
"report_link",
"source_issue",
"autostart_skip",
"implementation_decision",
"implementation_dispatch",
"implementation_replacement",
"implementation_handover",
"ranking_score",
"impact_measurement_plan",
}
)
def artefact_type_for_model(model: type[BaseModel]) -> str:
"""The artefact type a content model class persists as (exact class match).
Deriving the row's type from the model class makes a type/content mismatch unrepresentable.
Raises `ArtefactContentValidationError` for models that aren't artefact content schemas.
"""
artefact_type = _ARTEFACT_TYPE_BY_MODEL.get(model)
if artefact_type is None:
raise ArtefactContentValidationError(f"{model.__name__} is not an artefact content model")
return artefact_type
def artefact_type_for(content: BaseModel) -> str:
"""The artefact type a content model instance persists as. See `artefact_type_for_model`."""
return artefact_type_for_model(type(content))
def parse_artefact_content(artefact_type: str, content: str | dict | list) -> ArtefactContent:
"""Parse a raw payload (JSON text or deserialized JSON) into `artefact_type`'s content model.
The boundary parser: API writes and reads of stored rows come through here once, and
everything past the boundary passes the typed model around. Raises
`ArtefactContentValidationError` on an unknown type, malformed JSON, or schema mismatch.
"""
schema = ARTEFACT_CONTENT_SCHEMAS.get(artefact_type)
if schema is None:
raise ArtefactContentValidationError(f"Unknown artefact type {artefact_type!r}")
try:
if isinstance(content, str):
return cast(ArtefactContent, schema.model_validate_json(content))
return cast(ArtefactContent, schema.model_validate(content))
except ValidationError as e:
raise ArtefactContentValidationError(str(e)) from e