: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
from typing import Any
from rest_framework import serializers
from products.context_layer.backend.facade.api import DREAM_BRANCH_RE, PAGE_MAX_BYTES
# A bundle carries a handful of Markdown commits; anything bigger is not a wiki write-back.
COMMIT_BUNDLE_MAX_BYTES = 25_000_000
class ContextLayerStatusSerializer(serializers.Serializer):
"""Response shape for the wiki's current state."""
head_sha = serializers.CharField(help_text="Commit sha of the wiki's current head.")
class WikiTreeSerializer(serializers.Serializer):
"""Response shape for the wiki's page listing."""
head_sha = serializers.CharField(help_text="Commit sha of the wiki's current head.")
paths = serializers.ListField(
child=serializers.CharField(),
help_text="Repo-relative path of every Markdown page at the current head.",
)
class WikiPageQuerySerializer(serializers.Serializer):
path = serializers.CharField(help_text="Repo-relative Markdown path of the page to read.")
offset = serializers.IntegerField(
required=False, default=0, min_value=0, help_text="Character offset from next_offset."
)
limit = serializers.IntegerField(
required=False, min_value=1, max_value=12000, help_text="Maximum characters to read. Omit for the full page."
)
head_sha = serializers.CharField(
required=False,
max_length=64,
help_text="Head from the first chunk. Required for continuation. A changed head returns 409.",
)
def validate(self, attrs: dict[str, Any]) -> dict[str, Any]:
if attrs["offset"] and (not attrs.get("head_sha") or not attrs.get("limit")):
raise serializers.ValidationError("To continue, pass the head_sha and limit from the first read.")
return attrs
class WikiPageSerializer(serializers.Serializer):
"""Response shape for one wiki page."""
path = serializers.CharField(help_text="Repo-relative path of the page, for example `areas/analytics.md`.")
content = serializers.CharField(allow_blank=True, help_text="The page's Markdown content.")
head_sha = serializers.CharField(
help_text="Commit sha the content was read at; pass back as `base_head` on writes."
)
updated_at = serializers.DateTimeField(help_text="When this page was last changed in the wiki history.")
offset = serializers.IntegerField(help_text="Character offset of this chunk.")
total_length = serializers.IntegerField(help_text="Character length of the complete page.")
next_offset = serializers.IntegerField(allow_null=True, help_text="Next character offset, or null when complete.")
complete = serializers.BooleanField(
help_text="True when no further chunks remain. Do not write a page until all chunks are read."
)
class DreamRunSerializer(serializers.Serializer):
"""One dreaming run: the merge commit it landed as, plus what it changed."""
sha = serializers.CharField(help_text="Merge commit sha the run landed as; pass back as `sha` on the detail read.")
date = serializers.CharField(help_text="The run's date, `YYYY-MM-DD`.")
committed_at = serializers.DateTimeField(help_text="When the run landed.")
summary = serializers.CharField(allow_blank=True, help_text="The run summary the dreaming agent wrote.")
pages_added = serializers.IntegerField(help_text="Pages the run created.")
pages_modified = serializers.IntegerField(help_text="Pages the run edited.")
pages_deleted = serializers.IntegerField(help_text="Pages the run removed.")
class ActiveDreamRunSerializer(serializers.Serializer):
"""A dreaming task that has not reached a terminal state yet."""
run_status = serializers.ChoiceField(
choices=[
("not_started", "not_started"),
("queued", "queued"),
("in_progress", "in_progress"),
],
help_text="The current task-run state for the active dream.",
)
started_at = serializers.DateTimeField(help_text="When the active dream task was created.")
class UnpublishedDreamRunSerializer(serializers.Serializer):
task_url = serializers.URLField(help_text="Task URL in its project for the unpublished dream outcome and logs.")
run_status = serializers.CharField(
help_text="The terminal task-run state, such as completed, failed, or cancelled."
)
started_at = serializers.DateTimeField(help_text="When the unpublished dream task was created.")
class DreamRunListSerializer(serializers.Serializer):
"""Response shape for the wiki's dream run listing."""
head_sha = serializers.CharField(help_text="Commit sha of the wiki's current head.")
active_run = ActiveDreamRunSerializer(
allow_null=True,
help_text="The organization's active dreaming task, or null when no dream is running.",
)
unpublished_run = UnpublishedDreamRunSerializer(
allow_null=True,
help_text="The latest finished dream when no update was published after it started, or null otherwise.",
)
dreams = DreamRunSerializer(many=True, help_text="Every landed dream run, newest first.")
class DreamFileDiffSerializer(serializers.Serializer):
"""One file a dream run changed, with its unified patch."""
path = serializers.CharField(help_text="Repo-relative path of the changed page.")
status = serializers.ChoiceField(
choices=[("added", "added"), ("modified", "modified"), ("deleted", "deleted")],
help_text="How the run changed the page.",
)
patch = serializers.CharField(allow_blank=True, help_text="Unified git patch for this file.")
truncated = serializers.BooleanField(help_text="Whether the patch was cut off for size.")
class DreamRunDetailSerializer(serializers.Serializer):
"""Response shape for one dream run: the run plus the diff it landed."""
run = DreamRunSerializer()
files = DreamFileDiffSerializer(many=True, help_text="Per-file patches, in diff order.")
class WikiHealthFindingSerializer(serializers.Serializer):
category = serializers.CharField(help_text="Stable category used to group this finding.")
path = serializers.CharField(help_text="Wiki page path associated with this finding.")
message = serializers.CharField(help_text="Human-readable explanation of the finding.")
class WikiHealthReportSerializer(serializers.Serializer):
head_sha = serializers.CharField(help_text="Commit sha inspected by the report.")
findings = WikiHealthFindingSerializer(many=True, help_text="Health findings for the current wiki head.")
class ChannelWikiPageSerializer(serializers.Serializer):
"""Response shape for a channel's page identity in the wiki."""
path = serializers.CharField(help_text="Repo-relative path of the wiki page whose frontmatter names the channel.")
exists = serializers.BooleanField(
default=True,
help_text=(
"Whether a page exists at this path. False when the path is a proposal for a channel "
"whose page has not been created yet."
),
)
class WikiPageWriteSerializer(serializers.Serializer):
"""Request body for creating or replacing one wiki page."""
path = serializers.CharField(
max_length=512,
help_text="Repo-relative Markdown path inside the wiki's structure, for example `projects/12/spaces/general.md`.",
)
content = serializers.CharField(
allow_blank=True,
trim_whitespace=False,
max_length=PAGE_MAX_BYTES,
help_text="The complete Markdown content for the page.",
)
base_head = serializers.CharField(
required=False,
allow_null=True,
help_text=(
"Optimistic-concurrency guard: the head sha the edit is based on. A moved head is rejected "
"with 409 and the current head; omit to write unguarded."
),
)
class WikiPageProposalWriteSerializer(WikiPageWriteSerializer):
base_head = serializers.CharField(
max_length=64, help_text="The head_sha returned when reading the page. Required to bind the proposed edit."
)
class WikiPageProposalSerializer(serializers.Serializer):
id = serializers.UUIDField(
help_text="Immutable suggested edit ID. Only its author can apply it through the user API."
)
task_id = serializers.UUIDField(help_text="Task that proposed the edit.")
path = serializers.CharField(help_text="Shared wiki page to review.")
original_content = serializers.CharField(help_text="Page content at the revision the proposal is based on.")
content = serializers.CharField(help_text="Proposed page content. This is not published wiki content.")
base_head = serializers.CharField(help_text="Wiki revision the proposal is based on.")
created_at = serializers.DateTimeField(help_text="When the edit was proposed.")
class CommitBundleSerializer(serializers.Serializer):
"""Request body for landing agent commits posted back as a git bundle."""
bundle = serializers.FileField(
help_text=(
"A `git bundle` carrying the ref to land, created in the agent's clone "
"(for example `git bundle create out.bundle origin/main..main`)."
)
)
summary = serializers.CharField(
required=False,
allow_blank=True,
max_length=10_000,
help_text="Optional run summary stored in the landed commit body.",
)
branch = serializers.CharField(
required=False,
allow_null=True,
max_length=64,
help_text=(
"Land a dated dreaming branch (`dream/<YYYY-MM-DD>`) as one merge commit instead of "
"rebasing onto `main`. Omit for ordinary commits on `main`."
),
)
def validate_branch(self, value): # noqa: ANN001, ANN201
if value is not None and not DREAM_BRANCH_RE.fullmatch(value):
raise serializers.ValidationError("Only dream/<YYYY-MM-DD> branches can be landed; omit for main.")
return value
def validate_bundle(self, value): # noqa: ANN001, ANN201
if value.size > COMMIT_BUNDLE_MAX_BYTES:
raise serializers.ValidationError(f"Bundle exceeds the {COMMIT_BUNDLE_MAX_BYTES // 1_000_000} MB limit.")
return value
class WikiExportSerializer(serializers.Serializer):
"""Response shape for a wiki bundle export."""
url = serializers.CharField(help_text="Short-lived download URL for the wiki's current bundle.")
head_sha = serializers.CharField(help_text="Commit sha of the bundle behind the URL.")
class HeadConflictSerializer(serializers.Serializer):
"""409 body when a guarded write was based on a stale head."""
detail = serializers.CharField(help_text="What moved and what to do next.")
current_head = serializers.CharField(help_text="The wiki's current head sha; re-read pages at this head and retry.")
class LintErrorSerializer(serializers.Serializer):
"""400 body when a write violates the wiki's structure rules."""
detail = serializers.CharField(help_text="What was rejected.")
# The response key is part of the API; DRF's Serializer.errors property only
# matters for validation, which this response-shape serializer never does.
errors = serializers.ListField( # type: ignore[assignment]
child=serializers.CharField(), help_text="One entry per structure violation found by the linter."
)