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.

31.6 KB
Raw Blame
from typing import Literal, cast
from uuid import UUID

from drf_spectacular.utils import 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.models.user import User
from posthog.oauth_provenance import INTERNAL_RUN_SCOPE, get_oauth_access_token
from posthog.permissions import APIScopePermission, PostHogFeatureFlagPermission
from posthog.redis import get_client
from posthog.temporal.oauth import CONTEXT_LAYER_INTERNAL_SCOPE

from products.context_layer.backend.facade import api as facade
from products.context_layer.backend.presentation.serializers import (
    ChannelWikiPageSerializer,
    CommitBundleSerializer,
    ContextLayerStatusSerializer,
    DreamRunDetailSerializer,
    DreamRunListSerializer,
    HeadConflictSerializer,
    LintErrorSerializer,
    WikiExportSerializer,
    WikiHealthReportSerializer,
    WikiPageProposalSerializer,
    WikiPageProposalWriteSerializer,
    WikiPageQuerySerializer,
    WikiPageSerializer,
    WikiPageWriteSerializer,
    WikiTreeSerializer,
)
from products.tasks.backend.facade import api as tasks_facade

# Ordinary task runs can land wiki commits with nothing but the writer lock
# pacing them, so a runaway sandbox agent gets a hard daily ceiling per run.
RUN_COMMITS_PER_DAY_CAP = 20


def _context_actor_type(request: Request) -> Literal["user_or_api", "task_agent"]:
    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_agent"
    return "user_or_api"


def _capture_context_page_update(
    organization_id,  # noqa: ANN001
    request: Request,
    *,
    path: str,
    channel_id: str | None,
    is_first_version: bool,
    content_bytes: int,
    base_version_provided: bool,
) -> None:
    if channel_id is None:
        return
    path_parts = path.split("/")
    if len(path_parts) != 4 or path_parts[0] != "projects" or path_parts[2] != "spaces":
        return
    try:
        team_id = int(path_parts[1])
    except ValueError:
        return
    actor_type = _context_actor_type(request)
    tasks_facade.capture_context_wiki_changed(
        organization_id=organization_id,
        team_id=team_id,
        channel_id=channel_id,
        user_id=getattr(request.user, "id", None),
        actor_type=actor_type,
        is_first_version=is_first_version,
        content_bytes=content_bytes,
        base_version_provided=base_version_provided,
    )


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.DreamNotFoundError):
        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,
        )
    if isinstance(error, facade.DependencyUnavailableError):
        return Response(
            {"detail": "The context layer is temporarily unavailable. Try again later."},
            status=status.HTTP_503_SERVICE_UNAVAILABLE,
        )
    raise error


_read_page_schema = extend_schema(
    parameters=[WikiPageQuerySerializer],
    responses={
        200: WikiPageSerializer,
        400: OpenApiResponse(description="Invalid query, or the offset exceeds the page length."),
        404: OpenApiResponse(description="No page at this path."),
        409: OpenApiResponse(description="The wiki changed. Restart from offset zero."),
    },
    summary="Read a wiki page",
)


def _read_page(organization_id, request: Request) -> Response:  # noqa: ANN001
    query = WikiPageQuerySerializer(data=request.query_params)
    query.is_valid(raise_exception=True)
    params = query.validated_data
    try:
        wiki_page = facade.get_page(organization_id, params["path"])
    except facade.ContextLayerStoreError as error:
        return _store_error_response(error)
    if params.get("head_sha") and params["head_sha"] != wiki_page.head_sha:
        return Response(
            {"detail": "The wiki changed. Read again from offset zero.", "head_sha": wiki_page.head_sha},
            status=status.HTTP_409_CONFLICT,
        )
    offset = params["offset"]
    length = len(wiki_page.content)
    if offset > length:
        return Response(
            {"detail": "Offset exceeds the page length. Read again from offset zero."},
            status=status.HTTP_400_BAD_REQUEST,
        )
    end = offset + params["limit"] if "limit" in params else length
    next_offset = end if end < length else None
    page = WikiPageSerializer(
        {
            "path": wiki_page.path,
            "content": wiki_page.content[offset:end],
            "head_sha": wiki_page.head_sha,
            "updated_at": wiki_page.updated_at,
            "offset": offset,
            "total_length": length,
            "next_offset": next_offset,
            "complete": next_offset is None,
        }
    )
    return Response(page.data)


def _assert_run_write_in_scope(organization_id, team_id, request: Request, path: str, content: str) -> None:  # noqa: ANN001
    """Keep instruction files and other channels outside a sandbox run's writes.

    Reads stay open, because the wiki is organization-wide reference material
    every agent is meant to draw on. Writes must stay scoped: the agent route's scope
    override accepts server-minted task tokens, so without this a run steered by
    injected text could rewrite AGENTS.md, and with it the instructions every
    agent in the organization starts from. Shared content also influences other
    agents, so task edits to it require a separate human publication step.
    Direct writes stay bound to the run's channel.

    A no-op for callers without run provenance, so direct human/API writes keep
    the organization-wide editing behavior of the non-agent route.
    """
    access_token = get_oauth_access_token(request)
    token_scopes = set((getattr(access_token, "scope", "") or "").split())
    if INTERNAL_RUN_SCOPE not in token_scopes:
        return

    denied = PermissionDenied(
        "This task can update only its own channel's context page. "
        "Use task-context-wiki-page-propose for shared content, then ask the user to review it in Context > Suggested edits."
    )
    sandbox_task_id = getattr(access_token, "sandbox_task_id", None)
    if sandbox_task_id is None or team_id is None or not facade.is_run_content_path(path):
        raise denied

    channel_id = tasks_facade.task_channel_id(sandbox_task_id, team_id)
    if channel_id is None:
        raise denied
    configured_channel_id = str(channel_id)

    # Both sides resolve inside this organization's own wiki index, so a run
    # cannot reach another organization's pages even by naming its channel.
    requested_channel_id = facade.resolve_page_channel(organization_id, path)
    content_channel_id = facade.page_frontmatter_channel_id(content)
    if configured_channel_id == requested_channel_id and content_channel_id == configured_channel_id:
        return
    if requested_channel_id is not None:
        raise denied
    try:
        _assert_run_may_create_channel_page(organization_id, configured_channel_id, path, content, denied)
    except facade.ContextLayerStoreError as error:
        # A vanished channel or wiki mid-write reads as out of scope, not a 500.
        raise denied from error


def _assert_run_may_create_channel_page(
    organization_id,  # noqa: ANN001
    channel_id: str,
    path: str,
    content: str,
    denied: PermissionDenied,
) -> None:
    """A sandbox run may create its channel's page when the channel truly has none.

    Channels created after wiki enablement never went through the one-time
    import, so their runs would otherwise fall back to legacy channel
    instructions forever. Everything is pinned: the channel must have no page,
    the path must be exactly the one resolution proposed, nothing may already
    exist there, and the content's frontmatter must claim the configured
    channel — so the run cannot plant a page that resolution would hand to a
    different channel.
    """
    if facade.resolve_channel_page(organization_id, channel_id) is not None:
        raise denied
    if path in facade.get_tree(organization_id).paths:
        raise denied
    if path != facade.proposed_channel_page_path(organization_id, channel_id):
        raise denied
    if facade.page_frontmatter_channel_id(content) != channel_id:
        raise denied


def _read_channel_page(organization_id, channel_id: str, *, propose_on_miss: bool = False) -> Response:  # noqa: ANN001
    try:
        path = facade.resolve_channel_page(organization_id, channel_id)
        if path is None and propose_on_miss:
            # The channel has no page yet (created after enablement); hand the
            # caller the canonical path to create it at instead of a dead end.
            proposed = facade.proposed_channel_page_path(organization_id, channel_id)
            return Response(ChannelWikiPageSerializer({"path": proposed, "exists": False}).data)
    except facade.ContextLayerStoreError as error:
        return _store_error_response(error)
    if path is None:
        raise NotFound("This channel has no page in the context wiki.")
    return Response(ChannelWikiPageSerializer({"path": path}).data)


def _write_page(organization_id, request: Request, *, team_id=None) -> Response:  # noqa: ANN001
    serializer = WikiPageWriteSerializer(data=request.data)
    serializer.is_valid(raise_exception=True)
    _assert_run_write_in_scope(
        organization_id,
        team_id,
        request,
        serializer.validated_data["path"],
        serializer.validated_data["content"],
    )
    _assert_run_commit_cap(request)
    user = request.user
    author = (
        facade.CommitAuthor(name=user.first_name or user.email, email=user.email)
        if user and user.is_authenticated
        else None
    )
    content = serializer.validated_data["content"]
    channel_id = facade.page_frontmatter_channel_id(content)
    is_first_version = False
    if channel_id is not None:
        try:
            is_first_version = facade.resolve_channel_page(organization_id, channel_id) is None
        except facade.ContextLayerStoreError:
            pass
    try:
        head_sha = facade.write_page(
            organization_id,
            path=serializer.validated_data["path"],
            content=content,
            base_head=serializer.validated_data.get("base_head"),
            author=author,
        )
    except facade.ContextLayerStoreError as error:
        return _store_error_response(error)
    _capture_context_page_update(
        organization_id,
        request,
        path=serializer.validated_data["path"],
        channel_id=channel_id,
        is_first_version=is_first_version,
        content_bytes=len(content.encode("utf-8")),
        base_version_provided=serializer.validated_data.get("base_head") is not None,
    )
    return Response(ContextLayerStatusSerializer({"head_sha": head_sha}).data)


def _assert_run_commit_cap(request: Request) -> None:
    """Cap how many landings (bundles or page writes) one sandbox run gets per day.

    A task run landing wiki changes has nothing but the writer lock pacing it. Keyed on the run
    provenance the token carries; human and PAT callers have none and stay
    uncapped.
    """
    access_token = get_oauth_access_token(request)
    sandbox_task_id = getattr(access_token, "sandbox_task_id", None)
    if sandbox_task_id is None:
        return
    redis_client = get_client()
    key = f"context_layer:run_commit_cap:{sandbox_task_id}"
    landed = redis_client.incr(key)
    redis_client.expire(key, 86400)
    if landed > RUN_COMMITS_PER_DAY_CAP:
        raise Throttled(detail="This run has landed too many wiki commits today.")


def _land_commits(organization_id, request: Request) -> Response:  # noqa: ANN001
    access_token = get_oauth_access_token(request)
    token_scopes = set((getattr(access_token, "scope", "") or "").split())
    is_task_run = INTERNAL_RUN_SCOPE in token_scopes
    maintenance_run = None
    if is_task_run:
        maintenance_run = tasks_facade.get_latest_active_internal_task_run_for_organization(
            organization_id, ai_stage=facade.DREAM_AI_STAGE
        )
        if maintenance_run is None or maintenance_run.task_id != getattr(access_token, "sandbox_task_id", None):
            raise PermissionDenied("Task runs cannot publish wiki bundles. Propose a page edit for the user to review.")
    serializer = CommitBundleSerializer(data=request.data)
    serializer.is_valid(raise_exception=True)
    if is_task_run and serializer.validated_data.get("branch") is None:
        raise PermissionDenied("Scheduled wiki maintenance must publish a dated dream branch.")
    _assert_run_commit_cap(request)
    bundle_bytes = serializer.validated_data["bundle"].read()
    branch = serializer.validated_data.get("branch")
    try:
        if branch:
            head_sha = facade.land_dream_branch(
                organization_id,
                bundle_bytes,
                branch=branch,
                summary=serializer.validated_data.get("summary") or None,
                task_run_id=maintenance_run.id if maintenance_run is not None else None,
            )
        else:
            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",
        "channel_page",
        "export",
        "dreams",
        "dream",
        "proposals",
    ]
    scope_object_write_actions = ["enable", "update_page", "commits", "apply_proposal"]

    # No sandbox-token override here: a run token carries `scoped_teams`, which
    # `APIScopePermission` refuses on this organization-nested route, so it never
    # reaches these actions. Sandbox runs land commits through the project-nested
    # `ContextLayerAgentViewSet` instead; this route serves humans and
    # `organization:write` tokens.

    @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.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:
        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:
        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:
        try:
            report = facade.get_health_report(self.organization.id)
        except facade.ContextLayerStoreError as error:
            return _store_error_response(error)
        return Response(WikiHealthReportSerializer(report).data)

    @_read_page_schema
    @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(
        responses={
            200: ChannelWikiPageSerializer,
            404: OpenApiResponse(description="This channel has no page in the context wiki."),
        },
        summary="Resolve a channel's wiki page",
    )
    # nosemgrep: api-path-underscore -- shipped public API path, a rename breaks clients
    @action(methods=["GET"], detail=False, url_path=r"channel-pages/(?P<channel_id>[^/.]+)")
    def channel_page(self, request: Request, channel_id: str, **kwargs) -> Response:
        return _read_channel_page(self.organization.id, channel_id)

    @extend_schema(
        request=WikiPageWriteSerializer,
        responses={
            200: ContextLayerStatusSerializer,
            400: LintErrorSerializer,
            403: OpenApiResponse(
                description="The wiki is unavailable, or a run targeted a page outside its own context."
            ),
            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(responses={200: WikiPageProposalSerializer(many=True)}, summary="List your pending wiki edits")
    @action(methods=["GET"], detail=False)
    def proposals(self, request: Request, **kwargs) -> Response:
        user_id = cast(int, request.user.id)
        proposals = facade.list_page_proposals(self.organization.id, user_id)
        return Response(WikiPageProposalSerializer(proposals, many=True).data)

    @extend_schema(
        request=None,
        responses={200: ContextLayerStatusSerializer, 409: HeadConflictSerializer, 400: LintErrorSerializer},
        summary="Apply a reviewed wiki edit",
    )
    @action(methods=["POST"], detail=False, url_path=r"proposals/(?P<proposal_id>[^/.]+)/apply")
    def apply_proposal(self, request: Request, proposal_id: str, **kwargs) -> Response:
        user = cast(User, request.user)
        user_id = cast(int, user.id)
        token = get_oauth_access_token(request)
        scopes = set((getattr(token, "scope", "") or "").split())
        if INTERNAL_RUN_SCOPE in scopes:
            raise PermissionDenied(
                "A task cannot approve a wiki edit. Review and apply it from Context > Suggested edits."
            )
        try:
            proposal_uuid = UUID(proposal_id)
        except ValueError as error:
            raise NotFound("This suggested edit does not exist.") from error
        try:
            head_sha = facade.apply_page_proposal(
                self.organization.id,
                user_id,
                proposal_uuid,
                author=facade.CommitAuthor(name=user.first_name or user.email, email=user.email),
            )
        except facade.ContextLayerStoreError as error:
            return _store_error_response(error)
        return Response(ContextLayerStatusSerializer({"head_sha": head_sha}).data)

    @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(
        operation_id="context_layer_dreams_list",
        responses={200: DreamRunListSerializer, 404: OpenApiResponse(description="The context layer is not enabled.")},
        summary="List dream runs",
        description=(
            "The active dreaming task, when present, plus every landed run newest first. A landed run is one "
            "merge commit `dream: <date>` whose body is the summary; its changes are on the detail read."
        ),
    )
    @action(methods=["GET"], detail=False)
    def dreams(self, request: Request, **kwargs) -> Response:
        try:
            dream_list = facade.list_dream_runs(self.organization.id)
        except facade.ContextLayerStoreError as error:
            return _store_error_response(error)
        return Response(DreamRunListSerializer(dream_list).data)

    @extend_schema(
        operation_id="context_layer_dreams_retrieve",
        responses={
            200: DreamRunDetailSerializer,
            404: OpenApiResponse(description="No dream run at this sha, or the context layer is not enabled."),
        },
        summary="Read one dream run",
        description="One dreaming run with the per-file unified patches it landed.",
    )
    @action(methods=["GET"], detail=False, url_path=r"dreams/(?P<sha>[0-9a-f]{40})")
    def dream(self, request: Request, sha: str, **kwargs) -> Response:
        try:
            detail = facade.get_dream_run(self.organization.id, sha)
        except facade.ContextLayerStoreError as error:
            return _store_error_response(error)
        return Response(DreamRunDetailSerializer(detail).data)

    @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:
        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"
    read_actions = ["page", "channel_page"]
    write_actions = ["update_page", "commits", "propose_page"]

    # Each task scope must come with server-minted run provenance. The write path
    # binds each run to its own channel.
    _RUN_TASK_SCOPES = {
        "commits": "task:write",
        "page": "task:read",
        "channel_page": "task:read",
        "update_page": "task:write",
        "propose_page": "task:write",
    }
    request_dependent_scope_actions = frozenset(_RUN_TASK_SCOPES)

    def dangerously_get_required_scopes(self, request: Request, view=None) -> list[str] | None:  # noqa: ANN001
        """A run acts with task scopes; everyone else faces the organization ones.

        A task scope alone is user-grantable, so it only counts together with the
        action's provenance marker — minted server-side for runs and rejected by
        every user-facing scope validator, so a person cannot ask for it. Callers
        without that marker need the same organization scope 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.
        """
        task_scope = self._RUN_TASK_SCOPES.get(self.action)
        if task_scope is not None:
            access_token = get_oauth_access_token(request)
            token_scopes = set((getattr(access_token, "scope", "") or "").split())
            if INTERNAL_RUN_SCOPE in token_scopes:
                required = [task_scope, INTERNAL_RUN_SCOPE]
                if self.action in self.write_actions:
                    required.append(CONTEXT_LAYER_INTERNAL_SCOPE)
                return required
        if self.action in self.write_actions:
            return ["organization:write"]
        if self.action in self.read_actions:
            return ["organization:read"]
        return None

    @_read_page_schema
    @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(
        responses={
            200: ChannelWikiPageSerializer,
            404: OpenApiResponse(description="This channel does not exist, or the wiki is not enabled."),
        },
        summary="Resolve a channel's wiki page",
        description=(
            "The channel's page path. When the channel has no page yet, responds with the canonical "
            "path to create it at and `exists: false`."
        ),
    )
    # nosemgrep: api-path-underscore -- shipped public API path, a rename breaks clients
    @action(methods=["GET"], detail=False, url_path=r"channel-pages/(?P<channel_id>[^/.]+)")
    def channel_page(self, request: Request, channel_id: str, **kwargs) -> Response:
        # Unlike the organization route, a miss proposes a create path: a run
        # maintaining a post-enablement channel needs somewhere to publish.
        return _read_channel_page(self.organization.id, channel_id, propose_on_miss=True)

    @extend_schema(
        request=WikiPageWriteSerializer,
        responses={
            200: ContextLayerStatusSerializer,
            400: LintErrorSerializer,
            403: OpenApiResponse(description="The wiki is unavailable, or the run lacks permission to edit this page."),
            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, team_id=self.team_id)

    @extend_schema(
        request=WikiPageProposalWriteSerializer,
        responses={201: WikiPageProposalSerializer, 409: HeadConflictSerializer},
        summary="Propose a shared wiki edit for human review",
    )
    @action(methods=["POST"], detail=False, url_path="proposals")
    def propose_page(self, request: Request, **kwargs) -> Response:
        token = get_oauth_access_token(request)
        scopes = set((getattr(token, "scope", "") or "").split())
        task_id = getattr(token, "sandbox_task_id", None)
        if (
            INTERNAL_RUN_SCOPE not in scopes
            or task_id is None
            or tasks_facade.task_channel_id(task_id, self.team_id) is None
        ):
            raise PermissionDenied("Only a task bound to this project can propose a shared wiki edit.")
        serializer = WikiPageProposalWriteSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        _assert_run_commit_cap(request)
        user_id = cast(int, request.user.id)
        try:
            proposal = facade.create_page_proposal(
                self.organization.id,
                team_id=self.team_id,
                user_id=user_id,
                task_id=task_id,
                **serializer.validated_data,
            )
        except facade.ContextLayerStoreError as error:
            return _store_error_response(error)
        return Response(WikiPageProposalSerializer(proposal).data, status=status.HTTP_201_CREATED)

    @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)