Skip to content

: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.

feat(context-layer): pages API, enablement import, and commit landing (#84747)

Peter Kirkham7f8dc52c3140
diff --git a/products/context_layer/backend/enablement.py b/products/context_layer/backend/enablement.py
new file mode 100644
index 000000000000..368f2fa39cd5
--- /dev/null
+++ b/products/context_layer/backend/enablement.py
@@ -0,0 +1,188 @@
+"""Enable the context layer for an organization: scaffold the wiki, then import
+existing channel CONTEXT.md documents once.
+
+The legacy ChannelInstructions rows are never deleted, so turning the flag off
+restores the old behavior exactly as it was at import time.
+"""
+
+from __future__ import annotations
+
+import uuid
+from pathlib import Path
+
+from django.utils.text import slugify
+
+import structlog
+
+from posthog.dataclasses import frozen
+from posthog.models.scoping import team_scope
+from posthog.models.team.team import Team
+
+from products.context_layer.backend import store
+from products.context_layer.backend.models import ContextLayerConfig
+from products.tasks.backend.facade import api as tasks_facade
+
+from ee.models.rbac.access_control import AccessControl
+
+logger = structlog.get_logger(__name__)
+
+
+class RestrictedProjectsError(store.ContextLayerStoreError):
+ """The organization has private projects; enabling waits for per-project partitioning."""
+
+
+def enable_context_layer(
+ organization_id: uuid.UUID | str,
+ *,
+ created_by_id: int | None = None,
+) -> ContextLayerConfig:
+ """Idempotent: re-enabling scaffolds nothing and re-imports only missing pages."""
+ # Context extracted with one project's credentials must not become readable
+ # through another, so orgs with private projects cannot enable until the
+ # wiki is partitioned per project.
+ private_names = private_project_names(organization_id)
+ if private_names:
+ joined = ", ".join(private_names)
+ raise RestrictedProjectsError(
+ f"This organization has private projects ({joined}). The context layer does not "
+ "support them yet. Remove those projects' access restrictions to enable it."
+ )
+ config = store.initialize_repo(organization_id, created_by_id=created_by_id)
+ import_channel_context(organization_id)
+ return config
+
+
+def organization_has_private_projects(organization_id: uuid.UUID | str) -> bool:
+ """Private projects exist in two representations: the deprecated
+ `Team.access_control` flag (orgs not yet RBAC-migrated) and a project-level
+ `AccessControl` row with `access_level="none"`. Enablement must respect
+ both, and cares about the row existing rather than whether access control
+ is currently entitled, so it does not gate on the feature."""
+ if Team.objects.filter(organization_id=organization_id, access_control=True).exists():
+ return True
+ # Any project-level "none" row counts — the org-wide default row
+ # (organization_member/role null) marks a private project, and a member- or
+ # role-specific denial means at least one person must not see that
+ # project's context either way.
+ return AccessControl.objects.filter(
+ team__organization_id=organization_id,
+ resource="project",
+ resource_id__isnull=False,
+ access_level="none",
+ ).exists()
+
+
+def private_project_names(organization_id: uuid.UUID | str) -> list[str]:
+ """Names of the projects blocking enablement, for the error an org admin
+ acts on. Same two representations as `organization_has_private_projects`."""
+ names = set(
+ Team.objects.filter(organization_id=organization_id, access_control=True).values_list("name", flat=True)
+ )
+ restricted_ids = AccessControl.objects.filter(
+ team__organization_id=organization_id,
+ resource="project",
+ resource_id__isnull=False,
+ access_level="none",
+ ).values_list("resource_id", flat=True)
+ names.update(
+ Team.objects.filter(organization_id=organization_id, id__in=list(restricted_ids)).values_list("name", flat=True)
+ )
+ return sorted(names)
+
+
+def import_channel_context(organization_id: uuid.UUID | str) -> list[str]:
+ """Write each public channel's latest CONTEXT.md as `channels/<slug>.md`.
+
+ A channel is identified by the `channel_id` in its page's frontmatter, not
+ by its slug: a channel that already has a page anywhere under `channels/`
+ is never re-imported (later wiki edits win), and a new channel whose name
+ collides with an existing page gets a suffixed slug instead of being
+ silently dropped. Personal channels are skipped: their context belongs to
+ one person, and the wiki is org-visible.
+ """
+ candidates: list[tuple[str, str, str]] = []
+ # Order the teams so a same-named channel in two projects always resolves its
+ # slug collision the same way; an unordered scan could swap the pages between runs.
+ for team_id in Team.objects.filter(organization_id=organization_id).order_by("id").values_list("id", flat=True):
+ # The enable request is org-scoped, so the fail-closed channel models
+ # need an explicit team scope per team we read from.
+ with team_scope(team_id):
+ for channel in tasks_facade.list_channels(team_id, None):
+ if channel.channel_type != "public":
+ continue
+ instructions = tasks_facade.get_channel_instructions(channel.id, team_id, None)
+ if instructions is None or instructions.version == 0 or not instructions.content.strip():
+ continue
+ candidates.append((str(channel.id), channel.name, instructions.content))
+
+ if not candidates:
+ return []
+
+ written: list[str] = []
+
+ def mutate(root: Path) -> None:
+ written.clear()
+ index = _existing_channel_pages(root)
+ for channel_id, name, content in candidates:
+ if channel_id in index.channel_ids:
+ continue
+ path = _unique_channel_path(name, channel_id, index.paths)
+ index.paths.add(path)
+ # The linter requires H1 titles to be unique wiki-wide, so a page
+ # that needed a disambiguated path needs a disambiguated title too.
+ title = name if path == f"channels/{slugify(name) or channel_id}.md" else f"{name} ({channel_id[:8]})"
+ target = root / path
+ target.parent.mkdir(parents=True, exist_ok=True)
+ target.write_text(_channel_page(channel_id, name, content, title=title), encoding="utf-8")
+ written.append(path)
+
+ store.apply_changes(organization_id, message="Import channel context", mutate=mutate)
+ return sorted(written)
+
+
+@frozen
+class ImportedChannelIndex:
+ """What already lives under channels/: imported channel ids and taken paths."""
+
+ channel_ids: set[str]
+ paths: set[str]
+
+
+def _existing_channel_pages(root: Path) -> ImportedChannelIndex:
+ channel_ids: set[str] = set()
+ paths: set[str] = set()
+ channels_dir = root / "channels"
+ if channels_dir.is_dir():
+ for page in channels_dir.rglob("*.md"):
+ paths.add(str(page.relative_to(root)))
+ channel_id = _frontmatter_value(page, "channel_id")
+ if channel_id:
+ channel_ids.add(channel_id)
+ return ImportedChannelIndex(channel_ids=channel_ids, paths=paths)
+
+
+def _frontmatter_value(page: Path, key: str) -> str | None:
+ lines = page.read_text(encoding="utf-8", errors="replace").splitlines()
+ if not lines or lines[0].strip() != "---":
+ return None
+ for line in lines[1:]:
+ if line.strip() == "---":
+ return None
+ name, separator, value = line.partition(":")
+ if separator and name.strip() == key:
+ return value.strip() or None
+ return None
+
+
+def _unique_channel_path(name: str, channel_id: str, taken: set[str]) -> str:
+ slug = slugify(name) or channel_id
+ path = f"channels/{slug}.md"
+ if path in taken:
+ # Channel names are only unique per team, so cross-team collisions get
+ # the channel id appended.
+ path = f"channels/{slug}-{channel_id[:8]}.md"
+ return path
+
+
+def _channel_page(channel_id: str, channel_name: str, content: str, *, title: str | None = None) -> str:
+ return f"---\nchannel_id: {channel_id}\nsummary: Context imported from {channel_name}.\nstatus: active\nsources: channel-instructions-import\n---\n\n# {title or channel_name}\n\n{content}\n"
diff --git a/products/context_layer/backend/facade/__init__.py b/products/context_layer/backend/facade/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/context_layer/backend/facade/api.py b/products/context_layer/backend/facade/api.py
new file mode 100644
index 000000000000..ec7288fa7fee
--- /dev/null
+++ b/products/context_layer/backend/facade/api.py
@@ -0,0 +1,63 @@
+"""Facade for the context layer.
+
+The presentation layer (and, in later layers, other products) reaches the
+store, pages, and enablement internals only through here.
+"""
+
+from products.context_layer.backend.enablement import (
+ RestrictedProjectsError,
+ enable_context_layer,
+ organization_has_private_projects,
+)
+from products.context_layer.backend.pages import (
+ PAGE_MAX_BYTES,
+ InvalidPagePathError,
+ PageNotFoundError,
+ WikiHealthFinding,
+ WikiHealthReport,
+ WikiPage,
+ WikiTree,
+ get_health_report,
+ get_page,
+ get_tree,
+ write_page,
+)
+from products.context_layer.backend.store import (
+ BundleConflictError,
+ CommitAuthor,
+ ContextLayerStoreError,
+ HeadConflictError,
+ LintFailedError,
+ RepoLockUnavailableError,
+ RepoNotFoundError,
+ get_bundle_export,
+ get_config,
+ land_commit_bundle,
+)
+
+__all__ = [
+ "PAGE_MAX_BYTES",
+ "BundleConflictError",
+ "CommitAuthor",
+ "ContextLayerStoreError",
+ "HeadConflictError",
+ "InvalidPagePathError",
+ "LintFailedError",
+ "PageNotFoundError",
+ "RepoLockUnavailableError",
+ "RepoNotFoundError",
+ "RestrictedProjectsError",
+ "WikiPage",
+ "WikiHealthFinding",
+ "WikiHealthReport",
+ "WikiTree",
+ "enable_context_layer",
+ "get_bundle_export",
+ "get_config",
+ "get_page",
+ "get_health_report",
+ "get_tree",
+ "organization_has_private_projects",
+ "land_commit_bundle",
+ "write_page",
+]
diff --git a/products/context_layer/backend/pages.py b/products/context_layer/backend/pages.py
new file mode 100644
index 000000000000..a8408f3650b9
--- /dev/null
+++ b/products/context_layer/backend/pages.py
@@ -0,0 +1,201 @@
+"""Read and write wiki pages without putting a bundle download on the request path.
+
+Page contents are cached per head sha, so cache entries are immutable and need
+no invalidation: a landed write moves the head, and the next read warms the new
+sha's entries from one checkout.
+"""
+
+from __future__ import annotations
+
+import uuid
+import posixpath
+from datetime import UTC, datetime
+from pathlib import Path
+
+from posthog.dataclasses import frozen
+from posthog.utils import get_safe_cache, safe_cache_set
+
+from products.context_layer.backend import repo_lint, store
+
+# Entries are keyed by head sha and therefore immutable; the TTL only bounds
+# storage for heads nothing reads anymore.
+CACHE_TTL_SECONDS = 24 * 60 * 60
+PAGE_MAX_BYTES = 1_000_000
+
+
+class PageNotFoundError(store.ContextLayerStoreError):
+ pass
+
+
+class InvalidPagePathError(store.ContextLayerStoreError):
+ pass
+
+
+@frozen
+class WikiPage:
+ path: str
+ content: str
+ head_sha: str
+
+
+@frozen
+class WikiTree:
+ head_sha: str
+ paths: list[str]
+
+
+@frozen
+class WikiHealthFinding:
+ category: str
+ path: str
+ message: str
+
+
+@frozen
+class WikiHealthReport:
+ head_sha: str
+ findings: list[WikiHealthFinding]
+
+
+def _tree_cache_key(organization_id: uuid.UUID | str, head_sha: str) -> str:
+ return f"context_layer:tree:{organization_id}:{head_sha}"
+
+
+def _page_cache_key(organization_id: uuid.UUID | str, head_sha: str, path: str) -> str:
+ return f"context_layer:page:{organization_id}:{head_sha}:{path}"
+
+
+def _report_cache_key(organization_id: uuid.UUID | str, head_sha: str) -> str:
+ return f"context_layer:report:{organization_id}:{head_sha}:{datetime.now(UTC).date().isoformat()}"
+
+
+def normalize_page_path(path: str) -> str:
+ """Reject anything that could escape the checkout or point at a non-page.
+
+ The structural rules come from `repo_lint` so a write into the wrong
+ directory fails here, before paying for a checkout, and fails the same way
+ the land-time lint would."""
+ normalized = posixpath.normpath(path.strip().lstrip("/"))
+ if (
+ not normalized
+ or normalized.startswith((".", "/"))
+ or ".." in normalized.split("/")
+ or not normalized.endswith(".md")
+ ):
+ raise InvalidPagePathError(f"{path!r} is not a wiki page path; expected a relative Markdown path")
+ first_segment = normalized.split("/", 1)[0]
+ if normalized == "index.md":
+ raise InvalidPagePathError("index.md is generated by the server and cannot be edited")
+ # CLAUDE.md is deliberately not writable: it must stay a symlink to AGENTS.md.
+ if normalized != "AGENTS.md" and first_segment not in repo_lint.MARKDOWN_DIRECTORIES:
+ raise InvalidPagePathError(
+ f"{path!r} is outside the wiki structure; pages live in "
+ f"{', '.join(sorted(repo_lint.MARKDOWN_DIRECTORIES))} or at AGENTS.md"
+ )
+ return normalized
+
+
+def get_tree(organization_id: uuid.UUID | str) -> WikiTree:
+ """Every page path in the wiki at the current head."""
+ head_sha = store.get_config(organization_id).head_sha
+ paths = get_safe_cache(_tree_cache_key(organization_id, head_sha))
+ if paths is None:
+ # The head can move between the read above and the checkout; trust the
+ # checkout's head so the returned sha always matches the returned paths.
+ warmed = _warm_cache(organization_id)
+ head_sha, paths = warmed.head_sha, warmed.paths
+ return WikiTree(head_sha=head_sha, paths=paths)
+
+
+def get_page(organization_id: uuid.UUID | str, path: str) -> WikiPage:
+ path = normalize_page_path(path)
+ head_sha = store.get_config(organization_id).head_sha
+ content = get_safe_cache(_page_cache_key(organization_id, head_sha, path))
+ if content is None:
+ # Answer misses from the cached tree when we can: repeated requests for
+ # a nonexistent path must 404 cheaply, not re-download the bundle.
+ known_paths = get_safe_cache(_tree_cache_key(organization_id, head_sha))
+ if known_paths is not None and path not in known_paths:
+ raise PageNotFoundError(f"no page at {path}")
+ warmed = _warm_cache(organization_id)
+ head_sha = warmed.head_sha
+ content = warmed.pages.get(path)
+ if content is None:
+ raise PageNotFoundError(f"no page at {path}")
+ return WikiPage(path=path, content=content, head_sha=head_sha)
+
+
+def get_health_report(organization_id: uuid.UUID | str) -> WikiHealthReport:
+ head_sha = store.get_config(organization_id).head_sha
+ cache_key = _report_cache_key(organization_id, head_sha)
+ cached = get_safe_cache(cache_key)
+ if cached is not None:
+ return WikiHealthReport(
+ head_sha=head_sha,
+ findings=[WikiHealthFinding(**finding) for finding in cached],
+ )
+ with store.checkout_repo(organization_id) as checkout:
+ findings = []
+ for raw in repo_lint.report_repo(checkout.path):
+ category, path, message = raw.split(": ", 2)
+ findings.append(WikiHealthFinding(category=category, path=path, message=message))
+ safe_cache_set(
+ _report_cache_key(organization_id, checkout.head_sha),
+ [{"category": finding.category, "path": finding.path, "message": finding.message} for finding in findings],
+ CACHE_TTL_SECONDS,
+ )
+ return WikiHealthReport(head_sha=checkout.head_sha, findings=findings)
+
+
+def write_page(
+ organization_id: uuid.UUID | str,
+ *,
+ path: str,
+ content: str,
+ base_head: str | None = None,
+ author: store.CommitAuthor | None = None,
+) -> str:
+ """Create or replace one page through the writer protocol; returns the new head."""
+ path = normalize_page_path(path)
+ if len(content.encode("utf-8")) > PAGE_MAX_BYTES:
+ raise InvalidPagePathError(f"page content exceeds the {PAGE_MAX_BYTES // 1_000_000} MB limit")
+
+ def mutate(root: Path) -> None:
+ target = root / path
+ target.parent.mkdir(parents=True, exist_ok=True)
+ target.write_text(content, encoding="utf-8")
+
+ return store.apply_changes(
+ organization_id,
+ message=f"Edit {path}",
+ mutate=mutate,
+ author=author,
+ required_head=base_head,
+ )
+
+
+@frozen
+class WarmedWiki:
+ """One checkout's worth of readable state, keyed to the head it came from."""
+
+ head_sha: str
+ paths: list[str]
+ pages: dict[str, str]
+
+
+def _warm_cache(organization_id: uuid.UUID | str) -> WarmedWiki:
+ """One checkout warms the tree and every page for the checkout's head."""
+ with store.checkout_repo(organization_id) as checkout:
+ pages: dict[str, str] = {}
+ for file_path in sorted(checkout.path.rglob("*.md")):
+ if ".git" in file_path.parts or file_path.is_symlink() or not file_path.is_file():
+ continue
+ relative = str(file_path.relative_to(checkout.path))
+ # The linter rejects non-UTF-8 pages at land time; replacement here
+ # keeps one legacy file from turning every read into a 500.
+ pages[relative] = file_path.read_text(encoding="utf-8", errors="replace")
+ paths = sorted(pages)
+ safe_cache_set(_tree_cache_key(organization_id, checkout.head_sha), paths, CACHE_TTL_SECONDS)
+ for relative, content in pages.items():
+ safe_cache_set(_page_cache_key(organization_id, checkout.head_sha, relative), content, CACHE_TTL_SECONDS)
+ return WarmedWiki(head_sha=checkout.head_sha, paths=paths, pages=pages)
diff --git a/products/context_layer/backend/presentation/__init__.py b/products/context_layer/backend/presentation/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/context_layer/backend/presentation/serializers.py b/products/context_layer/backend/presentation/serializers.py
new file mode 100644
index 000000000000..9dd4fa4309a5
--- /dev/null
+++ b/products/context_layer/backend/presentation/serializers.py
@@ -0,0 +1,113 @@
+from rest_framework import serializers
+
+from products.context_layer.backend.facade.api import 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 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."
+ )
+
+
+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 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 `channels/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 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 wiki's `main` ref, 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.",
+ )
+
+ 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."
+ )
diff --git a/products/context_layer/backend/presentation/views.py b/products/context_layer/backend/presentation/views.py
new file mode 100644
index 000000000000..0cc6dc559ca6
--- /dev/null
+++ b/products/context_layer/backend/presentation/views.py
@@ -0,0 +1,307 @@
+from drf_spectacular.utils import OpenApiParameter, OpenApiResponse, extend_schema
+from rest_framework import status, viewsets
+from rest_framework.decorators import action
+from rest_framework.exceptions import NotFound, PermissionDenied, Throttled, ValidationError
+from rest_framework.parsers import FormParser, MultiPartParser
+from rest_framework.permissions import IsAuthenticated
+from rest_framework.request import Request
+from rest_framework.response import Response
+
+from posthog.api.routing import TeamAndOrgViewSetMixin
+from posthog.oauth_provenance import INTERNAL_RUN_SCOPE, get_oauth_access_token
+from posthog.permissions import APIScopePermission, PostHogFeatureFlagPermission
+
+from products.context_layer.backend.facade import api as facade
+from products.context_layer.backend.presentation.serializers import (
+ CommitBundleSerializer,
+ ContextLayerStatusSerializer,
+ HeadConflictSerializer,
+ LintErrorSerializer,
+ WikiExportSerializer,
+ WikiHealthReportSerializer,
+ WikiPageSerializer,
+ WikiPageWriteSerializer,
+ WikiTreeSerializer,
+)
+
+
+def _assert_no_private_projects(organization_id) -> None: # noqa: ANN001
+ """The wiki is org-readable, so it goes dark the moment any project is private.
+
+ Enablement refuses orgs with private projects, but privacy can arrive later;
+ imported context must not stay readable to members the project now excludes.
+ Re-enabling access means removing the project restriction (or, later,
+ per-project partitioning).
+ """
+ if facade.organization_has_private_projects(organization_id):
+ raise PermissionDenied(
+ "This organization now has private projects, so its context wiki is unavailable. "
+ "The context layer does not support private projects yet.",
+ code="private_projects",
+ )
+
+
+def _store_error_response(error: facade.ContextLayerStoreError) -> Response:
+ """One mapping from store errors to HTTP for every action, so new writers
+ added in later layers cannot drift from this contract."""
+ if isinstance(error, facade.RepoNotFoundError):
+ raise NotFound("The context layer is not enabled for this organization.") from error
+ if isinstance(error, facade.InvalidPagePathError):
+ raise ValidationError(str(error)) from error
+ if isinstance(error, facade.RepoLockUnavailableError):
+ raise Throttled(detail=str(error))
+ if isinstance(error, facade.PageNotFoundError):
+ raise NotFound(str(error)) from error
+ if isinstance(error, facade.HeadConflictError):
+ return Response(
+ {
+ "detail": "The wiki changed since this edit was based; re-read and retry.",
+ "current_head": error.current_head,
+ },
+ status=status.HTTP_409_CONFLICT,
+ )
+ if isinstance(error, facade.BundleConflictError):
+ return Response({"detail": str(error)}, status=status.HTTP_409_CONFLICT)
+ if isinstance(error, facade.LintFailedError):
+ return Response(
+ {"detail": "The change violates the wiki structure.", "errors": error.errors},
+ status=status.HTTP_400_BAD_REQUEST,
+ )
+ raise error
+
+
+def _read_page(organization_id, request: Request) -> Response: # noqa: ANN001
+ _assert_no_private_projects(organization_id)
+ try:
+ wiki_page = facade.get_page(organization_id, request.query_params.get("path", ""))
+ except facade.ContextLayerStoreError as error:
+ return _store_error_response(error)
+ return Response(WikiPageSerializer(wiki_page).data)
+
+
+def _write_page(organization_id, request: Request) -> Response: # noqa: ANN001
+ _assert_no_private_projects(organization_id)
+ serializer = WikiPageWriteSerializer(data=request.data)
+ serializer.is_valid(raise_exception=True)
+ user = request.user
+ author = (
+ facade.CommitAuthor(name=user.first_name or user.email, email=user.email)
+ if user and user.is_authenticated
+ else None
+ )
+ try:
+ head_sha = facade.write_page(
+ organization_id,
+ path=serializer.validated_data["path"],
+ content=serializer.validated_data["content"],
+ base_head=serializer.validated_data.get("base_head"),
+ author=author,
+ )
+ except facade.ContextLayerStoreError as error:
+ return _store_error_response(error)
+ return Response(ContextLayerStatusSerializer({"head_sha": head_sha}).data)
+
+
+def _land_commits(organization_id, request: Request) -> Response: # noqa: ANN001
+ _assert_no_private_projects(organization_id)
+ serializer = CommitBundleSerializer(data=request.data)
+ serializer.is_valid(raise_exception=True)
+ bundle_bytes = serializer.validated_data["bundle"].read()
+ try:
+ head_sha = facade.land_commit_bundle(
+ organization_id, bundle_bytes, summary=serializer.validated_data.get("summary") or None
+ )
+ except facade.ContextLayerStoreError as error:
+ return _store_error_response(error)
+ return Response(ContextLayerStatusSerializer({"head_sha": head_sha}).data)
+
+
+@extend_schema(tags=["context_layer"])
+class ContextLayerViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
+ """The organization's context wiki: a git repo of Markdown pages hosted by PostHog."""
+
+ # No authentication_classes override: the mixin already appends PostHog's
+ # session/PAT/OAuth authenticators, and DRF's stock SessionAuthentication
+ # would run first and skip enforce_two_factor.
+ # The flag is the rollout boundary: the whole surface stays off until the
+ # organization opts into `context-layer`.
+ posthog_feature_flag = "context-layer"
+ permission_classes = [IsAuthenticated, APIScopePermission, PostHogFeatureFlagPermission]
+ scope_object = "organization"
+ scope_object_read_actions = ["status", "tree", "page", "report", "export"]
+ scope_object_write_actions = ["enable", "update_page", "commits"]
+
+ @extend_schema(
+ request=None,
+ responses={201: ContextLayerStatusSerializer},
+ summary="Enable the context layer",
+ description=(
+ "Create the organization's wiki with the default structure and import existing channel "
+ "CONTEXT.md documents once. Idempotent."
+ ),
+ )
+ @action(methods=["POST"], detail=False)
+ def enable(self, request: Request, **kwargs) -> Response:
+ user_id = request.user.id if request.user and request.user.is_authenticated else None
+ try:
+ config = facade.enable_context_layer(self.organization.id, created_by_id=user_id)
+ except facade.RestrictedProjectsError as error:
+ raise ValidationError(str(error), code="private_projects") from error
+ except facade.ContextLayerStoreError as error:
+ return _store_error_response(error)
+ return Response(
+ ContextLayerStatusSerializer({"head_sha": config.head_sha}).data, status=status.HTTP_201_CREATED
+ )
+
+ @extend_schema(
+ responses={
+ 200: ContextLayerStatusSerializer,
+ 404: OpenApiResponse(description="The context layer is not enabled."),
+ },
+ summary="Get the wiki head",
+ )
+ @action(methods=["GET"], detail=False)
+ def status(self, request: Request, **kwargs) -> Response:
+ _assert_no_private_projects(self.organization.id)
+ try:
+ config = facade.get_config(self.organization.id)
+ except facade.ContextLayerStoreError as error:
+ return _store_error_response(error)
+ return Response(ContextLayerStatusSerializer({"head_sha": config.head_sha}).data)
+
+ @extend_schema(
+ responses={200: WikiTreeSerializer, 404: OpenApiResponse(description="The context layer is not enabled.")},
+ summary="List wiki pages",
+ )
+ @action(methods=["GET"], detail=False)
+ def tree(self, request: Request, **kwargs) -> Response:
+ _assert_no_private_projects(self.organization.id)
+ try:
+ wiki_tree = facade.get_tree(self.organization.id)
+ except facade.ContextLayerStoreError as error:
+ return _store_error_response(error)
+ return Response(WikiTreeSerializer(wiki_tree).data)
+
+ @extend_schema(
+ responses={200: WikiHealthReportSerializer},
+ summary="Report wiki health findings",
+ )
+ @action(methods=["GET"], detail=False, url_path="wiki/report")
+ def report(self, request: Request, **kwargs) -> Response:
+ _assert_no_private_projects(self.organization.id)
+ try:
+ report = facade.get_health_report(self.organization.id)
+ except facade.ContextLayerStoreError as error:
+ return _store_error_response(error)
+ return Response(WikiHealthReportSerializer(report).data)
+
+ @extend_schema(
+ parameters=[
+ OpenApiParameter(
+ name="path", type=str, required=True, description="Repo-relative Markdown path of the page to read."
+ )
+ ],
+ responses={200: WikiPageSerializer, 404: OpenApiResponse(description="No page at this path.")},
+ summary="Read a wiki page",
+ )
+ @action(methods=["GET"], detail=False, url_path="pages", url_name="pages")
+ def page(self, request: Request, **kwargs) -> Response:
+ return _read_page(self.organization.id, request)
+
+ @extend_schema(
+ request=WikiPageWriteSerializer,
+ responses={
+ 200: ContextLayerStatusSerializer,
+ 400: LintErrorSerializer,
+ 409: HeadConflictSerializer,
+ },
+ summary="Create or replace a wiki page",
+ )
+ @page.mapping.put
+ def update_page(self, request: Request, **kwargs) -> Response:
+ return _write_page(self.organization.id, request)
+
+ @extend_schema(
+ request=CommitBundleSerializer,
+ responses={
+ 200: ContextLayerStatusSerializer,
+ 400: LintErrorSerializer,
+ 409: OpenApiResponse(description="The posted commits conflict with the current head; re-pull and retry."),
+ },
+ summary="Land agent commits from a git bundle",
+ )
+ @action(methods=["POST"], detail=False, parser_classes=[MultiPartParser, FormParser])
+ def commits(self, request: Request, **kwargs) -> Response:
+ return _land_commits(self.organization.id, request)
+
+ @extend_schema(
+ responses={200: WikiExportSerializer},
+ summary="Export the wiki",
+ description="A short-lived download URL for the wiki's current bundle: the whole repo and its history, one file, standard git.",
+ )
+ @action(methods=["GET"], detail=False)
+ def export(self, request: Request, **kwargs) -> Response:
+ _assert_no_private_projects(self.organization.id)
+ try:
+ bundle = facade.get_bundle_export(self.organization.id)
+ except facade.ContextLayerStoreError as error:
+ return _store_error_response(error)
+ return Response(WikiExportSerializer({"url": bundle.url, "head_sha": bundle.head_sha}).data)
+
+
+@extend_schema(tags=["context_layer"])
+class ContextLayerAgentViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
+ """The same organization wiki, reached by an agent run inside a sandbox.
+
+ This exists as a second, project-nested route because a sandbox run token
+ carries `scoped_teams`, and `APIScopePermission` accepts those only on a
+ project-nested view — on the organization-scoped route above, every sandbox
+ token is refused before it reaches any of this. The wiki is still one repo
+ per organization; the project in the path is how a run token proves which
+ organization it may act for, and is not a scope on the wiki itself.
+ """
+
+ posthog_feature_flag = "context-layer"
+ permission_classes = [IsAuthenticated, APIScopePermission, PostHogFeatureFlagPermission]
+ # The wiki is not an access-control resource, and "organization" is not one a
+ # project-nested view can be checked against: `AccessControlPermission` engages
+ # here (it no-ops on the organization route, which has no team) and would demand
+ # organization *admin* to write — a bar the organization route never sets and
+ # the plain members runs act as do not clear. INTERNAL skips that resource
+ # lookup while keeping the rest of the chain, including project membership and
+ # `scoped_teams` enforcement. It also drops the default scope derivation, so
+ # every action below states its scopes explicitly.
+ scope_object = "INTERNAL"
+ write_actions = ["commits"]
+
+ def dangerously_get_required_scopes(self, request: Request, view=None) -> list[str] | None: # noqa: ANN001
+ """A sandbox run lands commits with task scopes; everyone else uses the organization one.
+
+ `task:write` alone is user-grantable, so it only counts together with
+ `internal_run:read` — minted server-side for sandbox runs and rejected by
+ every user-facing scope validator, so a person cannot ask for it. Callers
+ without that marker need the same `organization:write` the human route asks
+ for, which `scope_object = "INTERNAL"` means naming here rather than
+ deriving. One consequence of INTERNAL: a `*` (full access) token does not
+ short-circuit this check, so it has to carry the organization scope too.
+ """
+ if self.action not in self.write_actions:
+ return None
+ access_token = get_oauth_access_token(request)
+ token_scopes = set((getattr(access_token, "scope", "") or "").split())
+ if INTERNAL_RUN_SCOPE in token_scopes:
+ return ["task:write", INTERNAL_RUN_SCOPE]
+ return ["organization:write"]
+
+ @extend_schema(
+ request=CommitBundleSerializer,
+ responses={
+ 200: ContextLayerStatusSerializer,
+ 400: LintErrorSerializer,
+ 409: OpenApiResponse(description="The posted commits conflict with the current head; re-pull and retry."),
+ },
+ summary="Land agent commits from a git bundle",
+ )
+ @action(methods=["POST"], detail=False, parser_classes=[MultiPartParser, FormParser])
+ def commits(self, request: Request, **kwargs) -> Response:
+ return _land_commits(self.organization.id, request)
diff --git a/products/context_layer/backend/repo_lint.py b/products/context_layer/backend/repo_lint.py
index 7ef0a1add132..c8ea2ebc7e0e 100644
--- a/products/context_layer/backend/repo_lint.py
+++ b/products/context_layer/backend/repo_lint.py
@@ -14,6 +14,10 @@ ALLOWED_ROOT_FILES = {"AGENTS.md", "CLAUDE.md", "index.md"}
ALLOWED_DIRECTORIES = {"org", "areas", "decisions", "channels", "scripts"}
MARKDOWN_DIRECTORIES = {"org", "areas", "decisions", "channels"}
MAX_FILE_BYTES = 16_000
+# Aggregate bounds keep a whole wiki readable in one pass: reads warm every page
+# from a single checkout, so the repository must stay far below worker memory.
+MAX_TOTAL_BYTES = 50_000_000
+MAX_FILE_COUNT = 2_000
DECISION_FILE_RE = re.compile(r"^\d{4}-\d{2}-\d{2}-[a-z0-9][a-z0-9-]*\.md$")
WIKILINK_RE = re.compile(r"\[\[([^\[\]\n]+)\]\]")
MALFORMED_WIKILINK_RE = re.compile(r"\[\[|\]\]")
@@ -70,11 +74,31 @@ def lint_repo(root: Path | str, *, pin_scripts: bool = True) -> list[str]:
errors.append(f"{entry.name}/: only {', '.join(sorted(ALLOWED_DIRECTORIES))} are allowed at the root")
elif entry.name not in ALLOWED_ROOT_FILES:
errors.append(f"{entry.name}: only {', '.join(sorted(ALLOWED_ROOT_FILES))} are allowed as root files")
+ elif entry.name != "CLAUDE.md" and entry.is_symlink():
+ # The server rewrites index.md on every landing, so a symlinked root
+ # file would let a bundle direct that write at an arbitrary path.
+ errors.append(f"{entry.name}: root files other than CLAUDE.md must be regular files")
titles: dict[str, Path] = {}
for directory in sorted(MARKDOWN_DIRECTORIES):
errors.extend(_lint_markdown_directory(root, directory, titles))
errors.extend(_lint_scripts_directory(root, pin_scripts=pin_scripts))
+ total_bytes = 0
+ file_count = 0
+ for path in sorted(root.rglob("*")):
+ if ".git" in path.parts or not path.is_file() or path.is_symlink():
+ continue
+ total_bytes += path.stat().st_size
+ file_count += 1
+ if path.suffix == ".md":
+ try:
+ path.read_text(encoding="utf-8")
+ except UnicodeDecodeError:
+ errors.append(f"{path.relative_to(root)}: pages must be UTF-8 encoded")
+ if total_bytes > MAX_TOTAL_BYTES:
+ errors.append(f"the wiki exceeds the {MAX_TOTAL_BYTES // 1_000_000} MB total size limit")
+ if file_count > MAX_FILE_COUNT:
+ errors.append(f"the wiki exceeds the {MAX_FILE_COUNT} file limit")
return errors
diff --git a/products/context_layer/backend/routes.py b/products/context_layer/backend/routes.py
new file mode 100644
index 000000000000..e2cc8a19270f
--- /dev/null
+++ b/products/context_layer/backend/routes.py
@@ -0,0 +1,15 @@
+from posthog.api.routing import RouterRegistry
+
+from products.context_layer.backend.presentation.views import ContextLayerAgentViewSet, ContextLayerViewSet
+
+
+def register_routes(routers: RouterRegistry) -> None:
+ routers.organizations.register(
+ r"context_layer", ContextLayerViewSet, "organization_context_layer", ["organization_id"]
+ )
+ # A run token carries `scoped_teams`, which APIScopePermission accepts only on a
+ # project-nested route, so runs reach the same wiki here. The `/agent` segment
+ # keeps this path's suffix distinct from the organization one above: an org path
+ # whose suffix matches a project path is treated as a legacy alias and gets
+ # deprecated, which would retire the human route and take its operation ids.
+ routers.projects.register(r"context_layer/agent", ContextLayerAgentViewSet, "project_context_layer", ["team_id"])
diff --git a/products/context_layer/backend/store.py b/products/context_layer/backend/store.py
index c9466166549f..ce21cbaeb5ef 100644
--- a/products/context_layer/backend/store.py
+++ b/products/context_layer/backend/store.py
@@ -22,18 +22,28 @@ import structlog
from redis.exceptions import RedisError
from posthog.dataclasses import frozen
+from posthog.ph_client import ph_scoped_capture
from posthog.redis import get_client
from posthog.storage import object_storage
from products.context_layer.backend import repo_lint
from products.context_layer.backend.models import ContextLayerConfig
from products.context_layer.backend.repo_lint import lint_repo
-from products.context_layer.backend.scaffold import write_default_structure
+from products.context_layer.backend.scaffold import generate_index, write_default_structure
logger = structlog.get_logger(__name__)
BUNDLE_KEY_PREFIX = "context_layer"
DEFAULT_BRANCH = "main"
+BUNDLE_MAX_COMMITS = 100
+BUNDLE_MAX_UNPACKED_BYTES = 200_000_000
+# Sits far above what a legitimate 100-commit history over a 2,000-file wiki
+# produces, and stops a flood of tiny objects from being sized at all.
+BUNDLE_MAX_OBJECTS = 500_000
+# Every incoming commit's tree is materialized and linted, so the cost is the
+# sum across commits rather than the size of any one of them. A prose wiki lands
+# far below this; a bundle that exceeds it has to be split.
+BUNDLE_MAX_CUMULATIVE_TREE_BYTES = 1_000_000_000
LOCK_TTL_MS = 60_000
LOCK_RENEW_INTERVAL_SECONDS = 20.0
GIT_TIMEOUT_SECONDS = 60
@@ -62,6 +72,18 @@ class PurgeIncompleteError(ContextLayerStoreError):
sensitive content may still be readable in object storage."""
+class HeadConflictError(ContextLayerStoreError):
+ """A write guarded by `required_head` was based on a stale head."""
+
+ def __init__(self, *, current_head: str) -> None:
+ super().__init__(f"the wiki head moved to {current_head}; re-read and retry")
+ self.current_head = current_head
+
+
+class BundleConflictError(ContextLayerStoreError):
+ """A posted commit bundle could not be read or rebased onto the current head."""
+
+
class LintFailedError(ContextLayerStoreError):
def __init__(self, errors: list[str]) -> None:
super().__init__("wiki structure lint failed: " + "; ".join(errors))
@@ -82,6 +104,23 @@ class CommitAuthor:
email: str
+@frozen
+class BundleExport:
+ """A presigned download URL for a bundle and the head sha it points at."""
+
+ url: str
+ head_sha: str
+
+
+@frozen
+class LandingStats:
+ pages_added: int
+ pages_modified: int
+ pages_deleted: int
+ total_files: int
+ total_bytes: int
+
+
SYSTEM_AUTHOR = CommitAuthor(name=COMMITTER_NAME, email=COMMITTER_EMAIL)
@@ -149,7 +188,7 @@ def repo_writer_lock(organization_id: uuid.UUID | str) -> Iterator[None]:
logger.warning("context_layer.repo_writer_lock.release_failed", organization_id=str(organization_id))
-def _run_git(args: list[str], cwd: Path) -> str:
+def _run_git(args: list[str], cwd: Path, stdin_text: str | None = None) -> str:
result = subprocess.run(
[
"git",
@@ -162,6 +201,7 @@ def _run_git(args: list[str], cwd: Path) -> str:
*args,
],
cwd=cwd,
+ input=stdin_text,
capture_output=True,
text=True,
timeout=GIT_TIMEOUT_SECONDS,
@@ -241,7 +281,7 @@ def _has_changes(workdir: Path) -> bool:
return bool(_run_git(["status", "--porcelain"], cwd=workdir))
-def _refresh_canonical_scripts(workdir: Path) -> None:
+def _refresh_canonical_scripts(workdir: Path) -> bool:
"""Rewrite scripts/ to the content PostHog currently ships.
Landing is the upgrade point: a wiki scaffolded under an older script
@@ -250,7 +290,8 @@ def _refresh_canonical_scripts(workdir: Path) -> None:
"""
scripts_dir = workdir / "scripts"
if scripts_dir.is_symlink() or not scripts_dir.is_dir():
- return
+ return False
+ changed = False
for name, content in repo_lint._canonical_scripts().items():
target = scripts_dir / name
if target.is_symlink():
@@ -260,6 +301,8 @@ def _refresh_canonical_scripts(workdir: Path) -> None:
if not target.exists() or target.read_text(encoding="utf-8", errors="replace") != content:
target.write_text(content, encoding="utf-8")
target.chmod(0o755)
+ changed = True
+ return changed
def _lint_or_raise(workdir: Path) -> None:
@@ -318,38 +361,48 @@ def initialize_repo(
return config
-def apply_changes(
+def _run_landing(
organization_id: uuid.UUID | str,
*,
- message: str,
- mutate: Callable[[Path], None],
- author: CommitAuthor | None = None,
+ prepare: Callable[[Path], str | None],
+ required_head: str | None = None,
+ lane: str = "interactive",
) -> str:
- """Run the writer protocol for a working-tree mutation and return the new head sha.
+ """The landing half of the writer protocol, shared by every writer.
- `mutate` receives the checkout path and edits files in place; the store
- commits, lints, uploads, and lands the result. A no-op mutation returns the
- current head without landing anything.
+ `prepare` receives a working clone of the current head and returns the new
+ head sha it committed, or `None` for a no-op. All writers hold the per-org
+ lock, so the CAS only loses when a previous writer's lock expired mid-land
+ and its CAS raced ours. One retry re-reads the moved head and replays
+ `prepare` on top of it.
"""
- author = author or SYSTEM_AUTHOR
- # All writers hold the per-org lock, so the CAS only loses when a previous
- # writer's lock expired mid-land and its CAS raced ours. One retry re-reads
- # the moved head and replays the mutation on top of it.
for attempt in (1, 2):
with repo_writer_lock(organization_id):
expected_head = get_config(organization_id).head_sha
+ if required_head is not None and required_head != expected_head:
+ raise HeadConflictError(current_head=expected_head)
with tempfile.TemporaryDirectory(prefix="context-layer-", ignore_cleanup_errors=True) as tmp:
tmpdir = Path(tmp)
bundle_path = _download_bundle(organization_id, expected_head, tmpdir)
workdir = tmpdir / "repo"
_clone_from_bundle(bundle_path, workdir)
- mutate(workdir)
- _refresh_canonical_scripts(workdir)
- if not _has_changes(workdir):
+ new_head = prepare(workdir)
+ if new_head is None:
return expected_head
+ if _refresh_canonical_scripts(workdir):
+ new_head = _commit_all(workdir, "Update wiki scripts to the current version", SYSTEM_AUTHOR)
+ index_path = workdir / "index.md"
+ if index_path.is_symlink():
+ # Never write the generated index through a bundle-supplied
+ # symlink; lint would reject it later, but the write happens first.
+ index_path.unlink()
+ generated_index = generate_index(workdir)
+ if not index_path.exists() or index_path.read_text(encoding="utf-8") != generated_index:
+ index_path.write_text(generated_index, encoding="utf-8")
+ new_head = _commit_all(workdir, "Refresh the generated wiki index", SYSTEM_AUTHOR)
_lint_or_raise(workdir)
- new_head = _commit_all(workdir, message, author)
+ stats = _landing_stats(workdir, expected_head, new_head)
_upload_bundle(organization_id, new_head, workdir)
updated = ContextLayerConfig.objects.filter(
@@ -357,9 +410,23 @@ def apply_changes(
).update(head_sha=new_head)
if updated:
_prune_bundles_best_effort(organization_id, {new_head, expected_head})
+ with ph_scoped_capture() as capture:
+ capture(
+ distinct_id=str(organization_id),
+ event="context layer commits landed",
+ properties={
+ "organization_id": str(organization_id),
+ "lane": lane,
+ "pages_added": stats.pages_added,
+ "pages_modified": stats.pages_modified,
+ "pages_deleted": stats.pages_deleted,
+ "total_files": stats.total_files,
+ "total_bytes": stats.total_bytes,
+ },
+ )
return new_head
logger.warning(
- "context_layer.apply_changes.head_moved",
+ "context_layer.landing.head_moved",
organization_id=str(organization_id),
expected_head=expected_head,
attempt=attempt,
@@ -367,6 +434,234 @@ def apply_changes(
raise HeadMovedError(f"head moved twice while landing changes for organization {organization_id}")
+EMPTY_TREE_SHA = "4b825dc642cb6eb9a060e54bf8d69288fbee4904"
+
+
+def _landing_stats(workdir: Path, old_head: str, new_head: str) -> LandingStats:
+ counts = {"A": 0, "M": 0, "D": 0}
+ try:
+ _run_git(["cat-file", "-e", f"{old_head}^{{commit}}"], cwd=workdir)
+ except ContextLayerStoreError:
+ # A purge rewrites history, so the previous head is no longer an object
+ # in the rewritten repo; count every page as added instead of failing.
+ old_head = EMPTY_TREE_SHA
+ for line in _run_git(["diff", "--name-status", old_head, new_head, "--", "*.md"], cwd=workdir).splitlines():
+ status = line.split("\t", 1)[0][0]
+ if status in counts:
+ counts[status] += 1
+ files = [
+ path for path in workdir.rglob("*") if ".git" not in path.parts and path.is_file() and not path.is_symlink()
+ ]
+ return LandingStats(
+ pages_added=counts["A"],
+ pages_modified=counts["M"],
+ pages_deleted=counts["D"],
+ total_files=len(files),
+ total_bytes=sum(path.stat().st_size for path in files),
+ )
+
+
+def apply_changes(
+ organization_id: uuid.UUID | str,
+ *,
+ message: str,
+ mutate: Callable[[Path], None],
+ author: CommitAuthor | None = None,
+ required_head: str | None = None,
+) -> str:
+ """Run the writer protocol for a working-tree mutation and return the new head sha.
+
+ `mutate` receives the checkout path and edits files in place; the store
+ commits, lints, uploads, and lands the result. A no-op mutation returns the
+ current head without landing anything. `required_head` is the optimistic
+ concurrency guard: when the head no longer matches, `HeadConflictError`
+ carries the current head for the caller's 409.
+ """
+
+ def prepare(workdir: Path) -> str | None:
+ mutate(workdir)
+ if not _has_changes(workdir):
+ return None
+ return _commit_all(workdir, message, author or SYSTEM_AUTHOR)
+
+ return _run_landing(organization_id, prepare=prepare, required_head=required_head)
+
+
+def _assert_bundle_within_bounds(workdir: Path, fetched: str) -> None:
+ """Reject bundles whose incoming history is out of proportion for a wiki.
+
+ The upload cap only bounds the compressed pack, so the limits here are
+ measured on the incoming range's logical shape: commit count, merge shape,
+ the sum of uncompressed object sizes (what a compression bomb hides), and
+ what each commit actually materializes on disk. All limits sit far above
+ anything a legitimate write-back produces.
+ """
+ incoming_range = f"{DEFAULT_BRANCH}..{fetched}"
+ incoming_commits = int(_run_git(["rev-list", "--count", incoming_range], cwd=workdir))
+ if incoming_commits > BUNDLE_MAX_COMMITS:
+ raise BundleConflictError(
+ f"the posted bundle carries {incoming_commits} commits; at most {BUNDLE_MAX_COMMITS} can land at once"
+ )
+ merge_commits = int(_run_git(["rev-list", "--merges", "--count", incoming_range], cwd=workdir))
+ if merge_commits:
+ # The landing rebase linearizes history and silently drops content that
+ # exists only in merge commits (a conflict resolution, for example), so
+ # a bundle carrying merges must be linearized by its author instead.
+ raise BundleConflictError(
+ "the posted bundle contains merge commits; rebase your clone onto its origin/main and repost"
+ )
+ _assert_object_sizes_within_bounds(workdir, incoming_range)
+ _assert_trees_within_bounds(workdir, incoming_range)
+
+
+def _assert_object_sizes_within_bounds(workdir: Path, incoming_range: str) -> None:
+ """Bound the unique objects the incoming range adds.
+
+ Sizes come from one `cat-file --batch-check` process fed every object id, so
+ a bundle carrying tens of thousands of tiny objects costs one git process
+ rather than one per object.
+ """
+ object_ids = [
+ line.split(maxsplit=1)[0]
+ for line in _run_git(["rev-list", "--objects", incoming_range], cwd=workdir).splitlines()
+ if line
+ ]
+ if len(object_ids) > BUNDLE_MAX_OBJECTS:
+ raise BundleConflictError(
+ f"the posted bundle carries {len(object_ids)} objects; at most {BUNDLE_MAX_OBJECTS} can land at once"
+ )
+ if not object_ids:
+ return
+ sizes = _run_git(["cat-file", "--batch-check"], cwd=workdir, stdin_text="\n".join(object_ids) + "\n")
+ incoming_bytes = 0
+ for line in sizes.splitlines():
+ fields = line.split()
+ # `<sha> missing` for anything unreadable; the fetch already proved the
+ # range is complete, so treat it as a malformed bundle rather than zero.
+ if len(fields) < 3:
+ raise BundleConflictError(f"could not size an object in the posted bundle: {line}")
+ incoming_bytes += int(fields[2])
+ if incoming_bytes > BUNDLE_MAX_UNPACKED_BYTES:
+ raise BundleConflictError(
+ f"the posted bundle unpacks past the {BUNDLE_MAX_UNPACKED_BYTES // 1_000_000} MB limit"
+ )
+
+
+def _assert_trees_within_bounds(workdir: Path, incoming_range: str) -> None:
+ """Bound what the incoming commits materialize, per commit and in total.
+
+ The object-size sum counts a blob once, but a checkout pays for every path
+ that references it, so a small bundle can still materialize gigabytes. Each
+ commit's tree is measured by path before anything is checked out, and the
+ running total bounds the whole lint pass.
+ """
+ cumulative_bytes = 0
+ for sha in _run_git(["rev-list", "--reverse", incoming_range], cwd=workdir).split():
+ footprint = _tree_materialized_size(workdir, sha)
+ if footprint.file_count > repo_lint.MAX_FILE_COUNT:
+ raise BundleConflictError(
+ f"commit {sha[:12]} carries {footprint.file_count} files; the wiki allows {repo_lint.MAX_FILE_COUNT}"
+ )
+ if footprint.total_bytes > repo_lint.MAX_TOTAL_BYTES:
+ raise BundleConflictError(
+ f"commit {sha[:12]} checks out to more than the "
+ f"{repo_lint.MAX_TOTAL_BYTES // 1_000_000} MB the wiki allows"
+ )
+ cumulative_bytes += footprint.total_bytes
+ if cumulative_bytes > BUNDLE_MAX_CUMULATIVE_TREE_BYTES:
+ raise BundleConflictError(
+ f"the posted bundle's commits check out to more than the "
+ f"{BUNDLE_MAX_CUMULATIVE_TREE_BYTES // 1_000_000} MB that can be linted at once; "
+ "post it as several smaller bundles"
+ )
+
+
+@frozen
+class _TreeFootprint:
+ """What a commit's tree writes to disk, counted per path."""
+
+ total_bytes: int
+ file_count: int
+
+
+def _tree_materialized_size(workdir: Path, sha: str) -> _TreeFootprint:
+ listing = _run_git(["ls-tree", "-r", "--long", "--full-tree", sha], cwd=workdir)
+ total_bytes = 0
+ file_count = 0
+ for line in listing.splitlines():
+ metadata, _, _ = line.partition("\t")
+ fields = metadata.split()
+ if len(fields) < 4:
+ continue
+ file_count += 1
+ # Submodule entries (`commit`) report `-` and materialize nothing.
+ if fields[3].isdigit():
+ total_bytes += int(fields[3])
+ return _TreeFootprint(total_bytes=total_bytes, file_count=file_count)
+
+
+def _lint_incoming_commits(workdir: Path, base: str, tip: str) -> None:
+ """Lint every incoming commit's tree, not just the final one.
+
+ Landed history is exportable and clonable, so a hazardous intermediate
+ commit (a secret, an oversized dump) must fail the land even when a later
+ commit removes it. `_assert_trees_within_bounds` has already bounded the
+ total work this loop can do.
+ """
+ shas = _run_git(["rev-list", "--reverse", f"{base}..{tip}"], cwd=workdir).split()
+ for sha in shas:
+ _run_git(["checkout", "--quiet", "--force", sha], cwd=workdir)
+ # Historical trees may carry earlier script versions (nothing executes
+ # them); the landed tree is pinned separately by the final lint.
+ errors = lint_repo(workdir, pin_scripts=False)
+ if errors:
+ _run_git(["checkout", "--quiet", "--force", tip], cwd=workdir)
+ raise LintFailedError([f"commit {sha[:12]}: {error}" for error in errors])
+ _run_git(["checkout", "--quiet", "--force", tip], cwd=workdir)
+
+
+def land_commit_bundle(
+ organization_id: uuid.UUID | str, bundle_bytes: bytes, *, summary: str | None = None, lane: str = "dream"
+) -> str:
+ """Land commits an agent made in its own clone, posted back as a bundle.
+
+ The bundle must carry the wiki's `main` ref, with the commits based on some
+ (possibly stale) head we already store. The incoming commits are rebased
+ onto the current head; a rebase conflict raises `BundleConflictError` so the
+ agent can re-pull and retry. Every incoming commit is linted, and bundles
+ that unpack past sane bounds are rejected.
+ """
+
+ def prepare(workdir: Path) -> str | None:
+ incoming = workdir.parent / "incoming.bundle"
+ incoming.write_bytes(bundle_bytes)
+ try:
+ _run_git(["bundle", "verify", "--quiet", str(incoming)], cwd=workdir)
+ _run_git(["fetch", "--quiet", str(incoming), DEFAULT_BRANCH], cwd=workdir)
+ except ContextLayerStoreError as error:
+ raise BundleConflictError(f"could not read the posted bundle: {error}") from error
+ fetched = _run_git(["rev-parse", "FETCH_HEAD"], cwd=workdir)
+ if fetched == _run_git(["rev-parse", "HEAD"], cwd=workdir):
+ return None
+ _assert_bundle_within_bounds(workdir, fetched)
+ _run_git(["checkout", "--quiet", "-B", "incoming", fetched], cwd=workdir)
+ try:
+ _run_git(["rebase", "--quiet", DEFAULT_BRANCH], cwd=workdir)
+ except ContextLayerStoreError as error:
+ raise BundleConflictError(f"the posted commits conflict with the current head: {error}") from error
+ rebased = _run_git(["rev-parse", "HEAD"], cwd=workdir)
+ if summary:
+ subject = _run_git(["log", "-1", "--format=%s"], cwd=workdir)
+ _run_git(["commit", "--amend", "--quiet", "-m", subject, "-m", summary], cwd=workdir)
+ rebased = _run_git(["rev-parse", "HEAD"], cwd=workdir)
+ _lint_incoming_commits(workdir, DEFAULT_BRANCH, rebased)
+ _run_git(["checkout", "--quiet", DEFAULT_BRANCH], cwd=workdir)
+ _run_git(["merge", "--ff-only", "--quiet", rebased], cwd=workdir)
+ return _run_git(["rev-parse", "HEAD"], cwd=workdir)
+
+ return _run_landing(organization_id, prepare=prepare, lane=lane)
+
+
def purge_repo_history(organization_id: uuid.UUID | str, *, message: str = "Purge wiki history") -> str:
"""Rewrite the wiki to a single commit holding the current tree and delete
every old bundle, so no dropped history survives in object storage. The
@@ -390,10 +685,13 @@ def purge_repo_history(organization_id: uuid.UUID | str, *, message: str = "Purg
return head_sha
-def get_bundle_presigned_url(organization_id: uuid.UUID | str, *, expiration_seconds: int = 300) -> str:
- """Short-lived download URL for the current bundle, for sandbox mounts and export."""
+def get_bundle_export(organization_id: uuid.UUID | str, *, expiration_seconds: int = 300) -> BundleExport:
+ """Short-lived download URL for the current bundle, for sandbox mounts and export.
+
+ Reads the head once, so the returned url and head_sha always name the same
+ revision even if a writer lands between calls."""
config = get_config(organization_id)
url = object_storage.get_presigned_url(bundle_key(organization_id, config.head_sha), expiration=expiration_seconds)
if url is None:
raise ContextLayerStoreError(f"could not presign the bundle for organization {organization_id}")
- return url
+ return BundleExport(url=url, head_sha=config.head_sha)
diff --git a/products/context_layer/backend/test/test_api.py b/products/context_layer/backend/test/test_api.py
new file mode 100644
index 000000000000..ced37fb5ed2e
--- /dev/null
+++ b/products/context_layer/backend/test/test_api.py
@@ -0,0 +1,365 @@
+import tempfile
+import subprocess
+from datetime import timedelta
+from pathlib import Path
+from uuid import uuid4
+
+from posthog.test.base import APIBaseTest
+from unittest.mock import patch
+
+from django.core.files.uploadedfile import SimpleUploadedFile
+from django.test import override_settings
+from django.utils import timezone
+
+import posthog.storage.object_storage as object_storage_module
+from posthog.models.oauth import OAuthAccessToken, OAuthApplication
+from posthog.models.scoping import team_scope
+from posthog.models.team.team import Team
+from posthog.storage.object_storage import UnavailableStorage
+
+from products.context_layer.backend import enablement, store
+from products.tasks.backend.facade import api as tasks_facade
+
+from ee.models.rbac.access_control import AccessControl
+
+
+def _page(title: str) -> str:
+ return f"---\nsummary: {title} page for API tests.\nstatus: active\n---\n# {title}\n"
+
+
+@override_settings(OBJECT_STORAGE_ENABLED=True)
+@patch("posthog.permissions.posthog_feature_flag_enabled", return_value=True)
+class TestContextLayerAPI(APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ object_storage_module._client = UnavailableStorage()
+ self.addCleanup(setattr, object_storage_module, "_client", UnavailableStorage())
+ self.base_url = f"/api/organizations/{self.organization.id}/context_layer"
+ self.agent_url = f"/api/projects/{self.team.id}/context_layer/agent"
+
+ def _enable(self) -> str:
+ response = self.client.post(f"{self.base_url}/enable/")
+ assert response.status_code == 201, response.content
+ return response.json()["head_sha"]
+
+ def _bearer(self, scope: str, *, scoped_teams: list[int] | None = None, sandbox_task_id=None) -> str: # noqa: ANN001
+ app = OAuthApplication.objects.create(
+ name="sandbox",
+ client_type=OAuthApplication.CLIENT_CONFIDENTIAL,
+ authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,
+ redirect_uris="https://example.com/callback",
+ algorithm="RS256",
+ organization=self.organization,
+ user=self.user,
+ )
+ token = OAuthAccessToken.objects.create(
+ user=self.user,
+ application=app,
+ token=f"pha_{uuid4().hex}",
+ scope=scope,
+ expires=timezone.now() + timedelta(hours=1),
+ scoped_teams=scoped_teams or [],
+ scoped_organizations=[],
+ sandbox_task_id=sandbox_task_id,
+ )
+ return token.token
+
+ def test_agent_route_accepts_the_run_token_the_org_route_refuses(self, _flag) -> None:
+ self._enable()
+ bundle_bytes = self._bundle_with_edit("areas/from-agent.md", _page("From an agent"))
+ # Minted the way production mints one: bound to a task, scoped to a team.
+ token = self._bearer("task:write internal_run:read", scoped_teams=[self.team.id])
+ self.client.logout()
+
+ def post(base: str):
+ return self.client.post(
+ f"{base}/commits/",
+ {"bundle": SimpleUploadedFile("out.bundle", bundle_bytes)},
+ format="multipart",
+ HTTP_AUTHORIZATION=f"Bearer {token}",
+ )
+
+ assert post(self.agent_url).status_code == 200
+
+ # APIScopePermission refuses any token carrying scoped_teams on a route
+ # that is not project-nested, which is the whole reason the agent route
+ # exists — without it no real sandbox token can publish at all.
+ assert post(self.base_url).status_code == 403
+
+ def test_enable_scaffolds_wiki_and_imports_channel_context(self, _flag) -> None:
+ with team_scope(self.team.id):
+ channel = tasks_facade.resolve_channel(self.team.id, self.user.id, name="growth", star=False)
+ assert channel is not None
+ tasks_facade.publish_channel_instructions(
+ channel.id, self.team.id, self.user.id, content="Focus on activation.", base_version=0
+ )
+
+ self._enable()
+
+ tree = self.client.get(f"{self.base_url}/tree/").json()
+ assert "AGENTS.md" in tree["paths"]
+ assert "channels/growth.md" in tree["paths"]
+ page = self.client.get(f"{self.base_url}/pages/", {"path": "channels/growth.md"}).json()
+ assert f"channel_id: {channel.id}" in page["content"]
+ assert "Focus on activation." in page["content"]
+
+ def test_enable_is_blocked_for_orgs_with_private_projects(self, _flag) -> None:
+ self.team.access_control = True
+ self.team.save()
+ response = self.client.post(f"{self.base_url}/enable/")
+ assert response.status_code == 400
+ body = response.json()
+ assert body["code"] == "private_projects"
+ assert self.team.name in body["detail"]
+
+ def test_enable_is_blocked_for_orgs_with_rbac_private_projects(self, _flag) -> None:
+ AccessControl.objects.create(
+ team=self.team,
+ resource="project",
+ resource_id=str(self.team.id),
+ access_level="none",
+ )
+ response = self.client.post(f"{self.base_url}/enable/")
+ assert response.status_code == 400
+ body = response.json()
+ assert body["code"] == "private_projects"
+ assert self.team.name in body["detail"]
+
+ def test_reimport_keeps_existing_pages_and_suffixes_colliding_new_channels(self, _flag) -> None:
+ with team_scope(self.team.id):
+ channel = tasks_facade.resolve_channel(self.team.id, self.user.id, name="growth", star=False)
+ assert channel is not None
+ tasks_facade.publish_channel_instructions(
+ channel.id, self.team.id, self.user.id, content="First import.", base_version=0
+ )
+ self._enable()
+
+ other_team = Team.objects.create(organization=self.organization, name="Second project")
+ with team_scope(other_team.id):
+ colliding = tasks_facade.resolve_channel(other_team.id, self.user.id, name="growth", star=False)
+ assert colliding is not None
+ tasks_facade.publish_channel_instructions(
+ colliding.id, other_team.id, self.user.id, content="Same name, other project.", base_version=0
+ )
+ enablement.import_channel_context(self.organization.id)
+
+ tree = self.client.get(f"{self.base_url}/tree/").json()
+ suffixed = f"channels/growth-{str(colliding.id)[:8]}.md"
+ assert "channels/growth.md" in tree["paths"]
+ assert suffixed in tree["paths"]
+ original = self.client.get(f"{self.base_url}/pages/", {"path": "channels/growth.md"}).json()
+ assert "First import." in original["content"]
+
+ def test_enable_returns_429_when_a_writer_holds_the_lock(self, _flag) -> None:
+ with patch(
+ "products.context_layer.backend.store.repo_writer_lock",
+ side_effect=store.RepoLockUnavailableError("another writer holds the lock"),
+ ):
+ response = self.client.post(f"{self.base_url}/enable/")
+ assert response.status_code == 429
+
+ def test_endpoints_404_before_enablement(self, _flag) -> None:
+ assert self.client.get(f"{self.base_url}/tree/").status_code == 404
+ assert self.client.get(f"{self.base_url}/status/").status_code == 404
+
+ def test_flag_off_blocks_the_surface(self, flag_mock) -> None:
+ flag_mock.return_value = False
+ assert self.client.post(f"{self.base_url}/enable/").status_code == 403
+
+ def test_page_write_moves_head_and_read_returns_new_content(self, _flag) -> None:
+ head = self._enable()
+ response = self.client.put(
+ f"{self.base_url}/pages/",
+ {"path": "areas/analytics.md", "content": _page("Analytics"), "base_head": head},
+ format="json",
+ )
+ assert response.status_code == 200, response.content
+ new_head = response.json()["head_sha"]
+ assert new_head != head
+
+ page = self.client.get(f"{self.base_url}/pages/", {"path": "areas/analytics.md"}).json()
+ assert page["content"] == _page("Analytics")
+ assert page["head_sha"] == new_head
+
+ def test_page_write_with_stale_base_head_returns_409_with_current_head(self, _flag) -> None:
+ head = self._enable()
+ first = self.client.put(
+ f"{self.base_url}/pages/",
+ {"path": "areas/replay.md", "content": _page("Replay"), "base_head": head},
+ format="json",
+ )
+ assert first.status_code == 200
+ stale = self.client.put(
+ f"{self.base_url}/pages/",
+ {"path": "areas/replay.md", "content": _page("Replay, but stale"), "base_head": head},
+ format="json",
+ )
+ assert stale.status_code == 409
+ assert stale.json()["current_head"] == first.json()["head_sha"]
+
+ def test_page_write_outside_the_structure_returns_400(self, _flag) -> None:
+ self._enable()
+ response = self.client.put(
+ f"{self.base_url}/pages/",
+ {"path": "rogue.md", "content": "# rogue\n"},
+ format="json",
+ )
+ assert response.status_code == 400
+
+ def test_page_write_with_traversal_path_returns_400(self, _flag) -> None:
+ self._enable()
+ response = self.client.put(
+ f"{self.base_url}/pages/",
+ {"path": "../escape.md", "content": "# escape\n"},
+ format="json",
+ )
+ assert response.status_code == 400
+
+ def test_commits_endpoint_lands_a_bundle(self, _flag) -> None:
+ self._enable()
+ bundle_bytes = self._bundle_with_edit("areas/from-agent.md", _page("From an agent"))
+ response = self.client.post(
+ f"{self.base_url}/commits/",
+ {"bundle": SimpleUploadedFile("out.bundle", bundle_bytes)},
+ format="multipart",
+ )
+ assert response.status_code == 200, response.content
+ page = self.client.get(f"{self.base_url}/pages/", {"path": "areas/from-agent.md"}).json()
+ assert page["content"] == _page("From an agent")
+
+ def test_commits_endpoint_rejects_lint_violations(self, _flag) -> None:
+ self._enable()
+ bundle_bytes = self._bundle_with_edit("rogue.txt", "nope")
+ response = self.client.post(
+ f"{self.base_url}/commits/",
+ {"bundle": SimpleUploadedFile("out.bundle", bundle_bytes)},
+ format="multipart",
+ )
+ assert response.status_code == 400
+ assert response.json()["errors"]
+
+ def test_commits_endpoint_rejects_bundles_whose_history_violates_structure(self, _flag) -> None:
+ self._enable()
+ with store.checkout_repo(self.organization.id) as checkout:
+ env_git = ["git", "-c", "user.name=agent", "-c", "[email protected]"]
+ rogue = checkout.path / "secrets.txt"
+ rogue.write_text("hazardous dump")
+ subprocess.run([*env_git, "add", "--all"], cwd=checkout.path, check=True)
+ subprocess.run([*env_git, "commit", "--quiet", "-m", "Add hazard"], cwd=checkout.path, check=True)
+ rogue.unlink()
+ (checkout.path / "areas").mkdir(exist_ok=True)
+ (checkout.path / "areas" / "clean.md").write_text("# Clean\n")
+ subprocess.run([*env_git, "add", "--all"], cwd=checkout.path, check=True)
+ subprocess.run([*env_git, "commit", "--quiet", "-m", "Remove hazard"], cwd=checkout.path, check=True)
+ with tempfile.NamedTemporaryFile(suffix=".bundle") as bundle_file:
+ subprocess.run(
+ [*env_git, "bundle", "create", bundle_file.name, "origin/main..main"],
+ cwd=checkout.path,
+ check=True,
+ )
+ bundle_bytes = Path(bundle_file.name).read_bytes()
+
+ response = self.client.post(
+ f"{self.base_url}/commits/",
+ {"bundle": SimpleUploadedFile("out.bundle", bundle_bytes)},
+ format="multipart",
+ )
+ assert response.status_code == 400
+ assert any("secrets.txt" in error for error in response.json()["errors"])
+
+ def test_commits_endpoint_rejects_bundles_with_too_many_commits(self, _flag) -> None:
+ self._enable()
+ with store.checkout_repo(self.organization.id) as checkout:
+ env_git = ["git", "-c", "user.name=agent", "-c", "[email protected]"]
+ (checkout.path / "areas").mkdir(exist_ok=True)
+ for index in range(4):
+ (checkout.path / "areas" / f"page-{index}.md").write_text(f"# Page {index}\n")
+ subprocess.run([*env_git, "add", "--all"], cwd=checkout.path, check=True)
+ subprocess.run(
+ [*env_git, "commit", "--quiet", "-m", f"Add page {index}"], cwd=checkout.path, check=True
+ )
+ with tempfile.NamedTemporaryFile(suffix=".bundle") as bundle_file:
+ subprocess.run(
+ [*env_git, "bundle", "create", bundle_file.name, "origin/main..main"],
+ cwd=checkout.path,
+ check=True,
+ )
+ bundle_bytes = Path(bundle_file.name).read_bytes()
+
+ with patch.object(store, "BUNDLE_MAX_COMMITS", 3):
+ response = self.client.post(
+ f"{self.base_url}/commits/",
+ {"bundle": SimpleUploadedFile("out.bundle", bundle_bytes)},
+ format="multipart",
+ )
+ assert response.status_code == 409
+ assert "at most 3" in response.json()["detail"]
+
+ def test_commits_endpoint_rejects_bundles_with_merge_commits(self, _flag) -> None:
+ self._enable()
+ with store.checkout_repo(self.organization.id) as checkout:
+ env_git = ["git", "-c", "user.name=agent", "-c", "[email protected]"]
+ subprocess.run([*env_git, "checkout", "--quiet", "-b", "side"], cwd=checkout.path, check=True)
+ (checkout.path / "areas").mkdir(exist_ok=True)
+ (checkout.path / "areas" / "side.md").write_text("# Side\n")
+ subprocess.run([*env_git, "add", "--all"], cwd=checkout.path, check=True)
+ subprocess.run([*env_git, "commit", "--quiet", "-m", "Side edit"], cwd=checkout.path, check=True)
+ subprocess.run([*env_git, "checkout", "--quiet", "main"], cwd=checkout.path, check=True)
+ (checkout.path / "areas").mkdir(exist_ok=True)
+ (checkout.path / "areas" / "main.md").write_text("# Main\n")
+ subprocess.run([*env_git, "add", "--all"], cwd=checkout.path, check=True)
+ subprocess.run([*env_git, "commit", "--quiet", "-m", "Main edit"], cwd=checkout.path, check=True)
+ subprocess.run(
+ [*env_git, "merge", "--no-ff", "--quiet", "-m", "Merge side", "side"], cwd=checkout.path, check=True
+ )
+ with tempfile.NamedTemporaryFile(suffix=".bundle") as bundle_file:
+ subprocess.run(
+ [*env_git, "bundle", "create", bundle_file.name, "origin/main..main"],
+ cwd=checkout.path,
+ check=True,
+ )
+ bundle_bytes = Path(bundle_file.name).read_bytes()
+
+ response = self.client.post(
+ f"{self.base_url}/commits/",
+ {"bundle": SimpleUploadedFile("out.bundle", bundle_bytes)},
+ format="multipart",
+ )
+ assert response.status_code == 409
+ assert "merge commits" in response.json()["detail"]
+
+ def test_wiki_goes_dark_when_a_project_becomes_private(self, _flag) -> None:
+ self._enable()
+ assert self.client.get(f"{self.base_url}/tree/").status_code == 200
+
+ self.team.access_control = True
+ self.team.save()
+
+ assert self.client.get(f"{self.base_url}/tree/").status_code == 403
+ assert self.client.get(f"{self.base_url}/pages/", {"path": "AGENTS.md"}).status_code == 403
+ assert self.client.get(f"{self.base_url}/export/").status_code == 403
+
+ def test_export_returns_a_download_url(self, _flag) -> None:
+ head = self._enable()
+ response = self.client.get(f"{self.base_url}/export/")
+ assert response.status_code == 200
+ body = response.json()
+ assert body["head_sha"] == head
+ assert body["url"].startswith("http")
+
+ def _bundle_with_edit(self, path: str, content: str) -> bytes:
+ """Clone the wiki the way a sandbox does, commit one edit, pack it as a thin bundle."""
+ with store.checkout_repo(self.organization.id) as checkout:
+ target = checkout.path / path
+ target.parent.mkdir(parents=True, exist_ok=True)
+ target.write_text(content)
+ env_git = ["git", "-c", "user.name=agent", "-c", "[email protected]"]
+ subprocess.run([*env_git, "add", "--all"], cwd=checkout.path, check=True)
+ subprocess.run([*env_git, "commit", "--quiet", "-m", f"Edit {path}"], cwd=checkout.path, check=True)
+ with tempfile.NamedTemporaryFile(suffix=".bundle") as bundle_file:
+ subprocess.run(
+ [*env_git, "bundle", "create", bundle_file.name, "origin/main..main"],
+ cwd=checkout.path,
+ check=True,
+ )
+ return Path(bundle_file.name).read_bytes()
diff --git a/products/context_layer/backend/test/test_repo_lint.py b/products/context_layer/backend/test/test_repo_lint.py
index 46440ed3b7c5..17bcd66af82a 100644
--- a/products/context_layer/backend/test/test_repo_lint.py
+++ b/products/context_layer/backend/test/test_repo_lint.py
@@ -54,6 +54,11 @@ def _stray_symlink(root: Path) -> None:
(root / "areas" / "alias.md").symlink_to("../AGENTS.md")
+def _index_symlink(root: Path) -> None:
+ (root / "index.md").unlink()
+ (root / "index.md").symlink_to("/tmp/victim")
+
+
def _oversized_page(root: Path) -> None:
(root / "areas").mkdir(exist_ok=True)
(root / "areas" / "huge.md").write_text(
@@ -69,6 +74,11 @@ def _scripts_extra_file(root: Path) -> None:
(root / "scripts" / "deploy.sh").write_text("#!/bin/sh\n")
+def _non_utf8_page(root: Path) -> None:
+ (root / "areas").mkdir(exist_ok=True)
+ (root / "areas" / "pricing.md").write_bytes(b"# Pricing\n\nCaf\xe9 tier costs \x80100.\n")
+
+
def _scripts_tampered_lint(root: Path) -> None:
lint = root / "scripts" / "lint"
lint.write_text(lint.read_text() + "\nimport os # smuggled\n")
@@ -115,9 +125,11 @@ class TestRepoLint(SimpleTestCase):
("channel_page_without_channel_id", _channel_page_without_channel_id),
("channel_page_with_empty_channel_id", _channel_page_with_empty_channel_id),
("stray_symlink", _stray_symlink),
+ ("index_symlink", _index_symlink),
("scripts_symlink", _scripts_symlink),
("scripts_extra_file", _scripts_extra_file),
("scripts_tampered_lint", _scripts_tampered_lint),
+ ("non_utf8_page", _non_utf8_page),
]
)
def test_violations_are_reported(self, _name: str, violate: Callable[[Path], None]) -> None:
diff --git a/products/context_layer/backend/test/test_store.py b/products/context_layer/backend/test/test_store.py
index 71fd813c58f2..db4f7698c1e3 100644
--- a/products/context_layer/backend/test/test_store.py
+++ b/products/context_layer/backend/test/test_store.py
@@ -1,4 +1,5 @@
import tempfile
+import subprocess
from pathlib import Path
from posthog.test.base import BaseTest
@@ -186,6 +187,25 @@ class TestContextLayerStore(BaseTest):
shipped = (checkout.path / "scripts" / "lint").read_text()
assert shipped == repo_lint._canonical_scripts()["lint"]
+ def test_index_regeneration_never_writes_through_a_symlinked_index(self) -> None:
+ store.initialize_repo(self.organization.id)
+ victim = Path(tempfile.mkdtemp()) / "victim.txt"
+ victim.write_text("untouched")
+
+ def symlink_index(root: Path) -> None:
+ index = root / "index.md"
+ index.unlink()
+ index.symlink_to(victim)
+ (root / "areas").mkdir(exist_ok=True)
+ (root / "areas" / "note.md").write_text(_page("Note"))
+
+ store.apply_changes(self.organization.id, message="Symlink the index", mutate=symlink_index)
+
+ assert victim.read_text() == "untouched"
+ with store.checkout_repo(self.organization.id) as checkout:
+ landed = checkout.path / "index.md"
+ assert landed.is_file() and not landed.is_symlink()
+
def test_refresh_never_writes_through_a_symlinked_script(self) -> None:
store.initialize_repo(self.organization.id)
victim = Path(tempfile.mkdtemp()) / "victim.txt"
@@ -208,3 +228,45 @@ class TestContextLayerStore(BaseTest):
with self.assertRaises(store.RepoNotFoundError):
with store.checkout_repo(self.organization.id):
pass
+
+ def _bundle_with_commits(self, commits: list[dict[str, str]]) -> bytes:
+ with store.checkout_repo(self.organization.id) as checkout:
+ env_git = ["git", "-c", "user.name=agent", "-c", "[email protected]"]
+ for index, files in enumerate(commits):
+ for path, content in files.items():
+ target = checkout.path / path
+ target.parent.mkdir(parents=True, exist_ok=True)
+ target.write_text(content)
+ subprocess.run([*env_git, "add", "--all"], cwd=checkout.path, check=True)
+ subprocess.run([*env_git, "commit", "--quiet", "-m", f"Edit {index}"], cwd=checkout.path, check=True)
+ with tempfile.NamedTemporaryFile(suffix=".bundle") as bundle_file:
+ subprocess.run(
+ [*env_git, "bundle", "create", bundle_file.name, "origin/main..main"],
+ cwd=checkout.path,
+ check=True,
+ )
+ return Path(bundle_file.name).read_bytes()
+
+ def test_land_commit_bundle_rejects_a_tree_that_materializes_past_the_wiki_limit(self) -> None:
+ # One 5 KB blob at 20 paths: deduplicated the objects stay tiny, but the
+ # checkout writes 100 KB, so the limit only holds if it counts by path.
+ store.initialize_repo(self.organization.id)
+ bundle = self._bundle_with_commits([{f"areas/page-{index}.md": "x" * 5_000 for index in range(20)}])
+
+ with patch.object(repo_lint, "MAX_TOTAL_BYTES", 60_000):
+ # BundleConflictError rather than LintFailedError: an oversized tree
+ # has to be rejected before it is ever checked out.
+ with self.assertRaises(store.BundleConflictError) as caught:
+ store.land_commit_bundle(self.organization.id, bundle)
+
+ assert "checks out to more than" in str(caught.exception)
+
+ def test_land_commit_bundle_rejects_a_bundle_past_the_cumulative_tree_budget(self) -> None:
+ store.initialize_repo(self.organization.id)
+ bundle = self._bundle_with_commits([{f"areas/page-{index}.md": "y" * 6_000} for index in range(3)])
+
+ with patch.object(store, "BUNDLE_MAX_CUMULATIVE_TREE_BYTES", 30_000):
+ with self.assertRaises(store.BundleConflictError) as caught:
+ store.land_commit_bundle(self.organization.id, bundle)
+
+ assert "several smaller bundles" in str(caught.exception)
diff --git a/products/context_layer/frontend/generated/api.schemas.ts b/products/context_layer/frontend/generated/api.schemas.ts
new file mode 100644
index 000000000000..7eb85d967e50
--- /dev/null
+++ b/products/context_layer/frontend/generated/api.schemas.ts
@@ -0,0 +1,125 @@
+/**
+ * Auto-generated from the Django backend OpenAPI schema.
+ * To modify these types, update the Django serializers or views, then run:
+ * hogli build:openapi
+ * Questions or issues? #team-devex on Slack
+ *
+ * PostHog API - generated
+ * OpenAPI spec version: 1.0.0
+ */
+/**
+ * Request body for landing agent commits posted back as a git bundle.
+ */
+export interface CommitBundleApi {
+ /** A `git bundle` carrying the wiki's `main` ref, created in the agent's clone (for example `git bundle create out.bundle origin/main..main`). */
+ bundle: string
+ /**
+ * Optional run summary stored in the landed commit body.
+ * @maxLength 10000
+ */
+ summary?: string
+}
+
+/**
+ * Response shape for the wiki's current state.
+ */
+export interface ContextLayerStatusApi {
+ /** Commit sha of the wiki's current head. */
+ head_sha: string
+}
+
+/**
+ * 400 body when a write violates the wiki's structure rules.
+ */
+export interface LintErrorApi {
+ /** What was rejected. */
+ detail: string
+ /** One entry per structure violation found by the linter. */
+ errors: string[]
+}
+
+/**
+ * Response shape for a wiki bundle export.
+ */
+export interface WikiExportApi {
+ /** Short-lived download URL for the wiki's current bundle. */
+ url: string
+ /** Commit sha of the bundle behind the URL. */
+ head_sha: string
+}
+
+/**
+ * Response shape for one wiki page.
+ */
+export interface WikiPageApi {
+ /** Repo-relative path of the page, for example `areas/analytics.md`. */
+ path: string
+ /** The page's Markdown content. */
+ content: string
+ /** Commit sha the content was read at; pass back as `base_head` on writes. */
+ head_sha: string
+}
+
+/**
+ * Request body for creating or replacing one wiki page.
+ */
+export interface WikiPageWriteApi {
+ /**
+ * Repo-relative Markdown path inside the wiki's structure, for example `channels/general.md`.
+ * @maxLength 512
+ */
+ path: string
+ /**
+ * The complete Markdown content for the page.
+ * @maxLength 1000000
+ */
+ content: string
+ /**
+ * 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.
+ * @nullable
+ */
+ base_head?: string | null
+}
+
+/**
+ * 409 body when a guarded write was based on a stale head.
+ */
+export interface HeadConflictApi {
+ /** What moved and what to do next. */
+ detail: string
+ /** The wiki's current head sha; re-read pages at this head and retry. */
+ current_head: string
+}
+
+/**
+ * Response shape for the wiki's page listing.
+ */
+export interface WikiTreeApi {
+ /** Commit sha of the wiki's current head. */
+ head_sha: string
+ /** Repo-relative path of every Markdown page at the current head. */
+ paths: string[]
+}
+
+export interface WikiHealthFindingApi {
+ /** Stable category used to group this finding. */
+ category: string
+ /** Wiki page path associated with this finding. */
+ path: string
+ /** Human-readable explanation of the finding. */
+ message: string
+}
+
+export interface WikiHealthReportApi {
+ /** Commit sha inspected by the report. */
+ head_sha: string
+ /** Health findings for the current wiki head. */
+ findings: WikiHealthFindingApi[]
+}
+
+export type ContextLayerPagesRetrieveParams = {
+ /**
+ * Repo-relative Markdown path of the page to read.
+ */
+ path: string
+}
diff --git a/products/context_layer/frontend/generated/api.ts b/products/context_layer/frontend/generated/api.ts
new file mode 100644
index 000000000000..ed976de5f08a
--- /dev/null
+++ b/products/context_layer/frontend/generated/api.ts
@@ -0,0 +1,218 @@
+import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'
+/**
+ * Auto-generated from the Django backend OpenAPI schema.
+ * To modify these types, update the Django serializers or views, then run:
+ * hogli build:openapi
+ * Questions or issues? #team-devex on Slack
+ *
+ * PostHog API - generated
+ * OpenAPI spec version: 1.0.0
+ */
+import type {
+ CommitBundleApi,
+ ContextLayerPagesRetrieveParams,
+ ContextLayerStatusApi,
+ WikiExportApi,
+ WikiHealthReportApi,
+ WikiPageApi,
+ WikiPageWriteApi,
+ WikiTreeApi,
+} from './api.schemas'
+
+export const getContextLayerCommitsCreateUrl = (organizationId: string) => {
+ return `/api/organizations/${organizationId}/context_layer/commits/`
+}
+
+/**
+ * The organization's context wiki: a git repo of Markdown pages hosted by PostHog.
+ * @summary Land agent commits from a git bundle
+ */
+export const contextLayerCommitsCreate = async (
+ organizationId: string,
+ commitBundleApi: CommitBundleApi,
+ options?: RequestInit
+): Promise<ContextLayerStatusApi> => {
+ const formData = new FormData()
+ formData.append(`bundle`, commitBundleApi.bundle)
+ if (commitBundleApi.summary !== undefined) {
+ formData.append(`summary`, commitBundleApi.summary)
+ }
+
+ return apiMutator<ContextLayerStatusApi>(getContextLayerCommitsCreateUrl(organizationId), {
+ ...options,
+ method: 'POST',
+ body: formData,
+ })
+}
+
+export const getContextLayerEnableCreateUrl = (organizationId: string) => {
+ return `/api/organizations/${organizationId}/context_layer/enable/`
+}
+
+/**
+ * Create the organization's wiki with the default structure and import existing channel CONTEXT.md documents once. Idempotent.
+ * @summary Enable the context layer
+ */
+export const contextLayerEnableCreate = async (
+ organizationId: string,
+ options?: RequestInit
+): Promise<ContextLayerStatusApi> => {
+ return apiMutator<ContextLayerStatusApi>(getContextLayerEnableCreateUrl(organizationId), {
+ ...options,
+ method: 'POST',
+ })
+}
+
+export const getContextLayerExportRetrieveUrl = (organizationId: string) => {
+ return `/api/organizations/${organizationId}/context_layer/export/`
+}
+
+/**
+ * A short-lived download URL for the wiki's current bundle: the whole repo and its history, one file, standard git.
+ * @summary Export the wiki
+ */
+export const contextLayerExportRetrieve = async (
+ organizationId: string,
+ options?: RequestInit
+): Promise<WikiExportApi> => {
+ return apiMutator<WikiExportApi>(getContextLayerExportRetrieveUrl(organizationId), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getContextLayerPagesRetrieveUrl = (organizationId: string, params: ContextLayerPagesRetrieveParams) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/organizations/${organizationId}/context_layer/pages/?${stringifiedParams}`
+ : `/api/organizations/${organizationId}/context_layer/pages/`
+}
+
+/**
+ * The organization's context wiki: a git repo of Markdown pages hosted by PostHog.
+ * @summary Read a wiki page
+ */
+export const contextLayerPagesRetrieve = async (
+ organizationId: string,
+ params: ContextLayerPagesRetrieveParams,
+ options?: RequestInit
+): Promise<WikiPageApi> => {
+ return apiMutator<WikiPageApi>(getContextLayerPagesRetrieveUrl(organizationId, params), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getContextLayerPagesUpdateUrl = (organizationId: string) => {
+ return `/api/organizations/${organizationId}/context_layer/pages/`
+}
+
+/**
+ * The organization's context wiki: a git repo of Markdown pages hosted by PostHog.
+ * @summary Create or replace a wiki page
+ */
+export const contextLayerPagesUpdate = async (
+ organizationId: string,
+ wikiPageWriteApi: WikiPageWriteApi,
+ options?: RequestInit
+): Promise<ContextLayerStatusApi> => {
+ return apiMutator<ContextLayerStatusApi>(getContextLayerPagesUpdateUrl(organizationId), {
+ ...options,
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(wikiPageWriteApi),
+ })
+}
+
+export const getContextLayerStatusRetrieveUrl = (organizationId: string) => {
+ return `/api/organizations/${organizationId}/context_layer/status/`
+}
+
+/**
+ * The organization's context wiki: a git repo of Markdown pages hosted by PostHog.
+ * @summary Get the wiki head
+ */
+export const contextLayerStatusRetrieve = async (
+ organizationId: string,
+ options?: RequestInit
+): Promise<ContextLayerStatusApi> => {
+ return apiMutator<ContextLayerStatusApi>(getContextLayerStatusRetrieveUrl(organizationId), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getContextLayerTreeRetrieveUrl = (organizationId: string) => {
+ return `/api/organizations/${organizationId}/context_layer/tree/`
+}
+
+/**
+ * The organization's context wiki: a git repo of Markdown pages hosted by PostHog.
+ * @summary List wiki pages
+ */
+export const contextLayerTreeRetrieve = async (organizationId: string, options?: RequestInit): Promise<WikiTreeApi> => {
+ return apiMutator<WikiTreeApi>(getContextLayerTreeRetrieveUrl(organizationId), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getContextLayerWikiReportRetrieveUrl = (organizationId: string) => {
+ return `/api/organizations/${organizationId}/context_layer/wiki/report/`
+}
+
+/**
+ * The organization's context wiki: a git repo of Markdown pages hosted by PostHog.
+ * @summary Report wiki health findings
+ */
+export const contextLayerWikiReportRetrieve = async (
+ organizationId: string,
+ options?: RequestInit
+): Promise<WikiHealthReportApi> => {
+ return apiMutator<WikiHealthReportApi>(getContextLayerWikiReportRetrieveUrl(organizationId), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getContextLayerAgentCommitsCreateUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/context_layer/agent/commits/`
+}
+
+/**
+ * The same organization wiki, reached by an agent run inside a sandbox.
+ *
+ * This exists as a second, project-nested route because a sandbox run token
+ * carries `scoped_teams`, and `APIScopePermission` accepts those only on a
+ * project-nested view — on the organization-scoped route above, every sandbox
+ * token is refused before it reaches any of this. The wiki is still one repo
+ * per organization; the project in the path is how a run token proves which
+ * organization it may act for, and is not a scope on the wiki itself.
+ * @summary Land agent commits from a git bundle
+ */
+export const contextLayerAgentCommitsCreate = async (
+ projectId: string,
+ commitBundleApi: CommitBundleApi,
+ options?: RequestInit
+): Promise<ContextLayerStatusApi> => {
+ const formData = new FormData()
+ formData.append(`bundle`, commitBundleApi.bundle)
+ if (commitBundleApi.summary !== undefined) {
+ formData.append(`summary`, commitBundleApi.summary)
+ }
+
+ return apiMutator<ContextLayerStatusApi>(getContextLayerAgentCommitsCreateUrl(projectId), {
+ ...options,
+ method: 'POST',
+ body: formData,
+ })
+}
diff --git a/products/context_layer/frontend/generated/api.zod.ts b/products/context_layer/frontend/generated/api.zod.ts
new file mode 100644
index 000000000000..d8c09c0608d4
--- /dev/null
+++ b/products/context_layer/frontend/generated/api.zod.ts
@@ -0,0 +1,86 @@
+/**
+ * Auto-generated Zod validation schemas from the Django backend OpenAPI schema.
+ * To modify these schemas, update the Django serializers or views, then run:
+ * hogli build:openapi
+ * Questions or issues? #team-devex on Slack
+ *
+ * PostHog API - generated
+ * OpenAPI spec version: 1.0.0
+ */
+import * as zod from 'zod'
+
+/**
+ * The organization's context wiki: a git repo of Markdown pages hosted by PostHog.
+ * @summary Land agent commits from a git bundle
+ */
+export const contextLayerCommitsCreateBodySummaryMax = 10000
+
+export const ContextLayerCommitsCreateBody = /* @__PURE__ */ zod
+ .object({
+ bundle: zod
+ .url()
+ .describe(
+ "A `git bundle` carrying the wiki's `main` ref, created in the agent's clone (for example `git bundle create out.bundle origin\/main..main`)."
+ ),
+ summary: zod
+ .string()
+ .max(contextLayerCommitsCreateBodySummaryMax)
+ .optional()
+ .describe('Optional run summary stored in the landed commit body.'),
+ })
+ .describe('Request body for landing agent commits posted back as a git bundle.')
+
+/**
+ * The organization's context wiki: a git repo of Markdown pages hosted by PostHog.
+ * @summary Create or replace a wiki page
+ */
+export const contextLayerPagesUpdateBodyPathMax = 512
+
+export const contextLayerPagesUpdateBodyContentMax = 1000000
+
+export const ContextLayerPagesUpdateBody = /* @__PURE__ */ zod
+ .object({
+ path: zod
+ .string()
+ .max(contextLayerPagesUpdateBodyPathMax)
+ .describe("Repo-relative Markdown path inside the wiki's structure, for example `channels\/general.md`."),
+ content: zod
+ .string()
+ .max(contextLayerPagesUpdateBodyContentMax)
+ .describe('The complete Markdown content for the page.'),
+ base_head: zod
+ .string()
+ .nullish()
+ .describe(
+ '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.'
+ ),
+ })
+ .describe('Request body for creating or replacing one wiki page.')
+
+/**
+ * The same organization wiki, reached by an agent run inside a sandbox.
+ *
+ * This exists as a second, project-nested route because a sandbox run token
+ * carries `scoped_teams`, and `APIScopePermission` accepts those only on a
+ * project-nested view — on the organization-scoped route above, every sandbox
+ * token is refused before it reaches any of this. The wiki is still one repo
+ * per organization; the project in the path is how a run token proves which
+ * organization it may act for, and is not a scope on the wiki itself.
+ * @summary Land agent commits from a git bundle
+ */
+export const contextLayerAgentCommitsCreateBodySummaryMax = 10000
+
+export const ContextLayerAgentCommitsCreateBody = /* @__PURE__ */ zod
+ .object({
+ bundle: zod
+ .url()
+ .describe(
+ "A `git bundle` carrying the wiki's `main` ref, created in the agent's clone (for example `git bundle create out.bundle origin\/main..main`)."
+ ),
+ summary: zod
+ .string()
+ .max(contextLayerAgentCommitsCreateBodySummaryMax)
+ .optional()
+ .describe('Optional run summary stored in the landed commit body.'),
+ })
+ .describe('Request body for landing agent commits posted back as a git bundle.')
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index f8fbadbf3a39..be27892ca7de 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -17882,6 +17882,19 @@ export namespace Schemas {
Review: 'review',
} as const;
+ /**
+ * Request body for landing agent commits posted back as a git bundle.
+ */
+ export interface CommitBundle {
+ /** A `git bundle` carrying the wiki's `main` ref, created in the agent's clone (for example `git bundle create out.bundle origin/main..main`). */
+ bundle: string;
+ /**
+ * Optional run summary stored in the landed commit body.
+ * @maxLength 10000
+ */
+ summary?: string;
+ }
+
/**
* Response for the `commit` artefact diff endpoint — the commit's branch rendered against the
* repository default branch.
@@ -18286,6 +18299,14 @@ export namespace Schemas {
Eyes: 'eyes',
} as const;
+ /**
+ * Response shape for the wiki's current state.
+ */
+ export interface ContextLayerStatus {
+ /** Commit sha of the wiki's current head. */
+ head_sha: string;
+ }
+
export type ConversationMessagesItem = { [key: string]: unknown };
export type ConversationPendingApprovalsItem = { [key: string]: unknown };
@@ -39775,6 +39796,16 @@ export namespace Schemas {
math_property?: string | null;
}
+ /**
+ * 409 body when a guarded write was based on a stale head.
+ */
+ export interface HeadConflict {
+ /** What moved and what to do next. */
+ detail: string;
+ /** The wiki's current head sha; re-read pages at this head and retry. */
+ current_head: string;
+ }
+
export type HealthCheckSignalExtraPayload = { [key: string]: unknown };
export type HealthCheckSignalExtraSeverityEnum = typeof HealthCheckSignalExtraSeverityEnum[keyof typeof HealthCheckSignalExtraSeverityEnum];
@@ -45687,6 +45718,16 @@ export namespace Schemas {
status: string;
}
+ /**
+ * 400 body when a write violates the wiki's structure rules.
+ */
+ export interface LintError {
+ /** What was rejected. */
+ detail: string;
+ /** One entry per structure violation found by the linter. */
+ errors: string[];
+ }
+
/**
* Typed output for view set `list`.
*/
@@ -83237,6 +83278,75 @@ export namespace Schemas {
results: WidgetCatalogEntry[];
}
+ /**
+ * Response shape for a wiki bundle export.
+ */
+ export interface WikiExport {
+ /** Short-lived download URL for the wiki's current bundle. */
+ url: string;
+ /** Commit sha of the bundle behind the URL. */
+ head_sha: string;
+ }
+
+ export interface WikiHealthFinding {
+ /** Stable category used to group this finding. */
+ category: string;
+ /** Wiki page path associated with this finding. */
+ path: string;
+ /** Human-readable explanation of the finding. */
+ message: string;
+ }
+
+ export interface WikiHealthReport {
+ /** Commit sha inspected by the report. */
+ head_sha: string;
+ /** Health findings for the current wiki head. */
+ findings: WikiHealthFinding[];
+ }
+
+ /**
+ * Response shape for one wiki page.
+ */
+ export interface WikiPage {
+ /** Repo-relative path of the page, for example `areas/analytics.md`. */
+ path: string;
+ /** The page's Markdown content. */
+ content: string;
+ /** Commit sha the content was read at; pass back as `base_head` on writes. */
+ head_sha: string;
+ }
+
+ /**
+ * Request body for creating or replacing one wiki page.
+ */
+ export interface WikiPageWrite {
+ /**
+ * Repo-relative Markdown path inside the wiki's structure, for example `channels/general.md`.
+ * @maxLength 512
+ */
+ path: string;
+ /**
+ * The complete Markdown content for the page.
+ * @maxLength 1000000
+ */
+ content: string;
+ /**
+ * 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.
+ * @nullable
+ */
+ base_head?: string | null;
+ }
+
+ /**
+ * Response shape for the wiki's page listing.
+ */
+ export interface WikiTree {
+ /** Commit sha of the wiki's current head. */
+ head_sha: string;
+ /** Repo-relative path of every Markdown page at the current head. */
+ paths: string[];
+ }
+
/**
* The team's active onboarding wizard cloud run, used to rehydrate
* the setup-progress FAB when the run was started server-side (drop flow).
@@ -85877,6 +85987,13 @@ export namespace Schemas {
offset?: number;
};
+ export type ContextLayerPagesRetrieveParams = {
+ /**
+ * Repo-relative Markdown path of the page to read.
+ */
+ path: string;
+ };
+
export type DomainsListParams = {
/**
* Number of results to return per page.
diff --git a/tach.toml b/tach.toml
index d9cddb05f3ed..2ede1f6c5722 100644
--- a/tach.toml
+++ b/tach.toml
@@ -510,7 +510,9 @@ layer = "modules"
[[modules]]
path = "products.context_layer"
depends_on = [
+ "ee",
"posthog",
+ "products.tasks",
]
layer = "modules"