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.

fix(context): require human review for task wiki edits (#99060)

Peter Kirkham4a6957f5d561
diff --git a/.semgrep/rules/security/idor-team-scoped-models.yaml b/.semgrep/rules/security/idor-team-scoped-models.yaml
index 4df81294da3a..c63c3e205efe 100644
--- a/.semgrep/rules/security/idor-team-scoped-models.yaml
+++ b/.semgrep/rules/security/idor-team-scoped-models.yaml
@@ -399,6 +399,7 @@ rules:
|UserRepoPreference
|VisionAlertConfiguration
|VisionAlertMatch
+ |WikiPageProposal
|WarehouseColumnAnnotation
|WarehouseColumnStatistics
|WebAnalyticsAchievementProgress
@@ -798,6 +799,7 @@ rules:
|UserRepoPreference
|VisionAlertConfiguration
|VisionAlertMatch
+ |WikiPageProposal
|WarehouseColumnAnnotation
|WarehouseColumnStatistics
|WebAnalyticsAchievementProgress
diff --git a/docs/internal/cloud-task-sandbox.md b/docs/internal/cloud-task-sandbox.md
index a38e5483b670..43a5f981c1ac 100644
--- a/docs/internal/cloud-task-sandbox.md
+++ b/docs/internal/cloud-task-sandbox.md
@@ -41,6 +41,27 @@ Do not pass `--create-db` or override pytest `addopts` — either one discards t
If pytest starts the full migration history, the VM image predates the database seed, or the test database was replaced.
Let that migration finish before retrying. Interrupting it leaves a partial database that the next run must continue migrating.
+## Context wiki edits
+
+For a shared-page correction, read the page with `task-context-wiki-page-retrieve`, then send the updated content to `task-context-wiki-page-propose` with the returned `head_sha` as `base_head`.
+The server stores an immutable suggestion without changing the published wiki.
+The user must review the full diff before applying a suggestion.
+The Desktop review interface ships separately, after the backend is deployed.
+Until that interface is available, suggestions stay unpublished. Use direct human page editing for immediate corrections.
+Only that user with wiki write permission can apply the stored content. Task and loop tokens cannot approve suggestions.
+If the wiki changes before approval, publication returns a conflict. Read the page again and submit a new suggestion; never replace the base head to bypass review.
+
+Task runs with `context_layer_internal:write` can propose edits to existing shared Markdown pages under `org/`, `areas/`, and `decisions/`.
+Shared pages must not include `channel_id` frontmatter. Suggestions remain outside the published wiki until approval.
+Tasks can directly update their own channel page with `task-context-wiki-page-update`.
+Instruction files (`AGENTS.md` and `CLAUDE.md`), generated indexes, scripts, and other channels' pages remain protected.
+Loops can edit only their configured channel page, and read-only task tokens cannot write wiki content.
+Do not grant broader token scopes to work around a denied write.
+Ordinary tasks cannot publish commit bundles or use `scripts/publish` to bypass review.
+Server-owned nightly maintenance can publish a dated, content-only dream branch. The server verifies an active internal maintenance task in the organization, not just a branch name or token scope.
+Direct human page editing remains available.
+This review gate applies to server-minted task and loop tokens. Human/API credentials keep their existing permissions.
+
## Other differences
- `hogli devex:feedback` is a no-op here. Do not run it from a cloud task.
diff --git a/products/context_layer/backend/facade/api.py b/products/context_layer/backend/facade/api.py
index 175dab550f27..010a7c3ed49b 100644
--- a/products/context_layer/backend/facade/api.py
+++ b/products/context_layer/backend/facade/api.py
@@ -17,6 +17,7 @@ from posthog.permissions import posthog_feature_flag_enabled
from products.context_layer.backend import store
from products.context_layer.backend.dreams import (
+ DREAM_AI_STAGE,
ActiveDreamRun,
DreamFileDiff,
DreamNotFoundError,
@@ -39,12 +40,19 @@ from products.context_layer.backend.pages import (
get_health_report,
get_page,
get_tree,
+ is_run_content_path,
page_frontmatter_channel_id,
proposed_channel_page_path,
resolve_channel_page,
resolve_page_channel,
write_page,
)
+from products.context_layer.backend.proposals import (
+ WikiPageProposalDTO,
+ apply_page_proposal,
+ create_page_proposal,
+ list_page_proposals,
+)
from products.context_layer.backend.store import (
DREAM_BRANCH_RE,
BundleConflictError,
@@ -72,6 +80,12 @@ MOUNT_PATH_ENV_VAR = "POSTHOG_CONTEXT_LAYER_PATH"
COMMITS_PATH_ENV_VAR = "POSTHOG_CONTEXT_LAYER_COMMITS_PATH"
__all__ = [
+ "DREAM_AI_STAGE",
+ "WikiPageProposalDTO",
+ "apply_page_proposal",
+ "create_page_proposal",
+ "is_run_content_path",
+ "list_page_proposals",
"COMMITS_PATH_ENV_VAR",
"DREAM_BRANCH_RE",
"CONTEXT_LAYER_FEATURE_FLAG",
diff --git a/products/context_layer/backend/migrations/0004_wiki_page_proposal.py b/products/context_layer/backend/migrations/0004_wiki_page_proposal.py
new file mode 100644
index 000000000000..94adc619de32
--- /dev/null
+++ b/products/context_layer/backend/migrations/0004_wiki_page_proposal.py
@@ -0,0 +1,68 @@
+# Generated by Django 5.2.17 on 2026-09-11 10:33
+
+import django.db.models.deletion
+from django.conf import settings
+from django.db import migrations, models
+
+import posthog.uuidt
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("context_layer", "0003_contextlayerconfig_purge_incomplete_at"),
+ ("posthog", "1352_email_lookup_indexes"),
+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name="WikiPageProposal",
+ fields=[
+ (
+ "id",
+ models.UUIDField(
+ default=posthog.uuidt.uuid7,
+ editable=False,
+ primary_key=True,
+ serialize=False,
+ ),
+ ),
+ ("task_id", models.UUIDField()),
+ ("path", models.CharField(max_length=512)),
+ ("original_content", models.TextField()),
+ ("content", models.TextField()),
+ ("base_head", models.CharField(max_length=64)),
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ (
+ "applied_head",
+ models.CharField(blank=True, default="", max_length=64),
+ ),
+ (
+ "created_by",
+ models.ForeignKey(
+ db_constraint=False,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="+",
+ to=settings.AUTH_USER_MODEL,
+ ),
+ ),
+ (
+ "team",
+ models.ForeignKey(
+ db_constraint=False,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="+",
+ to="posthog.team",
+ ),
+ ),
+ ],
+ options={
+ "indexes": [
+ models.Index(
+ fields=["created_by", "-created_at"],
+ name="wiki_proposal_author_created",
+ )
+ ],
+ },
+ ),
+ ]
diff --git a/products/context_layer/backend/migrations/max_migration.txt b/products/context_layer/backend/migrations/max_migration.txt
index 9b00291edb49..9546b7f4fb2c 100644
--- a/products/context_layer/backend/migrations/max_migration.txt
+++ b/products/context_layer/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0003_contextlayerconfig_purge_incomplete_at
+0004_wiki_page_proposal
diff --git a/products/context_layer/backend/models.py b/products/context_layer/backend/models.py
index ca48cf1a6337..456ab2697842 100644
--- a/products/context_layer/backend/models.py
+++ b/products/context_layer/backend/models.py
@@ -1,5 +1,6 @@
from django.db import models
+from posthog.models.scoping.root_mixin import TeamScopedRootMixin
from posthog.models.utils import uuid7
@@ -42,3 +43,19 @@ class ContextLayerConfig(models.Model):
class Meta:
db_table = "context_layer_config"
+
+
+class WikiPageProposal(TeamScopedRootMixin):
+ id = models.UUIDField(primary_key=True, default=uuid7, editable=False)
+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, related_name="+", db_constraint=False)
+ created_by = models.ForeignKey("posthog.User", on_delete=models.CASCADE, related_name="+", db_constraint=False)
+ task_id = models.UUIDField()
+ path = models.CharField(max_length=512)
+ original_content = models.TextField()
+ content = models.TextField()
+ base_head = models.CharField(max_length=64)
+ created_at = models.DateTimeField(auto_now_add=True)
+ applied_head = models.CharField(max_length=64, blank=True, default="")
+
+ class Meta:
+ indexes = [models.Index(fields=["created_by", "-created_at"], name="wiki_proposal_author_created")]
diff --git a/products/context_layer/backend/pages.py b/products/context_layer/backend/pages.py
index 9fdebc9e8d8e..319393d3310f 100644
--- a/products/context_layer/backend/pages.py
+++ b/products/context_layer/backend/pages.py
@@ -78,6 +78,15 @@ def _channel_index_cache_key(organization_id: uuid.UUID | str, head_sha: str) ->
return f"context_layer:channel-index:{organization_id}:{head_sha}"
+def is_run_content_path(path: str) -> bool:
+ parts = path.split("/")
+ return (
+ parts[0] in {"org", "areas", "decisions", "projects"}
+ and path.endswith(".md")
+ and not any(part.lower() in {"", ".", "..", "agents.md", "claude.md", "index.md"} for part in parts)
+ )
+
+
def normalize_page_path(path: str) -> str:
"""Reject anything that could escape the checkout or point at a non-page.
diff --git a/products/context_layer/backend/presentation/serializers.py b/products/context_layer/backend/presentation/serializers.py
index 21c738335798..51a310bad821 100644
--- a/products/context_layer/backend/presentation/serializers.py
+++ b/products/context_layer/backend/presentation/serializers.py
@@ -136,6 +136,24 @@ class WikiPageWriteSerializer(serializers.Serializer):
)
+class WikiPageProposalWriteSerializer(WikiPageWriteSerializer):
+ base_head = serializers.CharField(
+ max_length=64, help_text="The head_sha returned when reading the page. Required to bind the proposed edit."
+ )
+
+
+class WikiPageProposalSerializer(serializers.Serializer):
+ id = serializers.UUIDField(
+ help_text="Immutable suggested edit ID. Only its author can apply it through the user API."
+ )
+ task_id = serializers.UUIDField(help_text="Task that proposed the edit.")
+ path = serializers.CharField(help_text="Shared wiki page to review.")
+ original_content = serializers.CharField(help_text="Page content at the revision the proposal is based on.")
+ content = serializers.CharField(help_text="Proposed page content. This is not published wiki content.")
+ base_head = serializers.CharField(help_text="Wiki revision the proposal is based on.")
+ created_at = serializers.DateTimeField(help_text="When the edit was proposed.")
+
+
class CommitBundleSerializer(serializers.Serializer):
"""Request body for landing agent commits posted back as a git bundle."""
diff --git a/products/context_layer/backend/presentation/views.py b/products/context_layer/backend/presentation/views.py
index c171c2a0bd3d..08a11cd436d7 100644
--- a/products/context_layer/backend/presentation/views.py
+++ b/products/context_layer/backend/presentation/views.py
@@ -1,4 +1,5 @@
-from typing import Literal
+from typing import Literal, cast
+from uuid import UUID
from drf_spectacular.utils import OpenApiParameter, OpenApiResponse, extend_schema
from rest_framework import status, viewsets
@@ -10,6 +11,7 @@ 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
@@ -26,6 +28,8 @@ from products.context_layer.backend.presentation.serializers import (
LintErrorSerializer,
WikiExportSerializer,
WikiHealthReportSerializer,
+ WikiPageProposalSerializer,
+ WikiPageProposalWriteSerializer,
WikiPageSerializer,
WikiPageWriteSerializer,
WikiTreeSerializer,
@@ -124,14 +128,15 @@ def _read_page(organization_id, request: Request) -> Response: # noqa: ANN001
def _assert_run_write_in_scope(organization_id, team_id, request: Request, path: str, content: str) -> None: # noqa: ANN001
- """A sandbox run may only write the context page for its channel.
+ """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 cannot be: the agent route's scope
+ 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. Ordinary tasks bind to their owning
- channel; loops bind to the context target in their frozen configuration.
+ 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.
@@ -143,9 +148,14 @@ def _assert_run_write_in_scope(organization_id, team_id, request: Request, path:
if not is_loop_run and not is_ordinary_run:
return
- denied = PermissionDenied("This run can update only the context page for its channel.")
+ denied = PermissionDenied(
+ "This loop can update only its configured channel's context page."
+ if is_loop_run
+ else "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:
+ if sandbox_task_id is None or team_id is None or not facade.is_run_content_path(path):
raise denied
configured_channel_id = (
@@ -160,10 +170,8 @@ def _assert_run_write_in_scope(organization_id, team_id, request: Request, path:
# 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)
- if (
- configured_channel_id == requested_channel_id
- and facade.page_frontmatter_channel_id(content) == configured_channel_id
- ):
+ 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
@@ -290,8 +298,17 @@ def _land_commits(organization_id, request: Request) -> Response: # noqa: ANN00
# Bundles bypass the page binding _assert_loop_write_in_scope enforces,
# so a loop run must land its edits through the page endpoint instead.
raise PermissionDenied("This loop can update only its context page, not land commit bundles.")
+ is_task_run = INTERNAL_RUN_SCOPE in token_scopes
+ 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")
@@ -324,8 +341,18 @@ class ContextLayerViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
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"]
- scope_object_write_actions = ["enable", "update_page", "commits"]
+ 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
@@ -432,6 +459,43 @@ class ContextLayerViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
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 or LOOP_CONTEXT_INTERNAL_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={
@@ -517,7 +581,7 @@ class ContextLayerAgentViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
# every action below states its scopes explicitly.
scope_object = "INTERNAL"
read_actions = ["page", "channel_page"]
- write_actions = ["update_page", "commits"]
+ write_actions = ["update_page", "commits", "propose_page"]
# Each task scope must come with server-minted run provenance. Page actions
# accept ordinary and loop runs; the write path binds each to its own target.
@@ -526,6 +590,7 @@ class ContextLayerAgentViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
"page": "task:read",
"channel_page": "task:read",
"update_page": "task:write",
+ "propose_page": "task:write",
}
def dangerously_get_required_scopes(self, request: Request, view=None) -> list[str] | None: # noqa: ANN001
@@ -591,9 +656,7 @@ class ContextLayerAgentViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
responses={
200: ContextLayerStatusSerializer,
400: LintErrorSerializer,
- 403: OpenApiResponse(
- description="The wiki is unavailable, or a sandbox run targeted a page outside its channel."
- ),
+ 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",
@@ -602,6 +665,39 @@ class ContextLayerAgentViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
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 LOOP_CONTEXT_INTERNAL_SCOPE 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={
diff --git a/products/context_layer/backend/proposals.py b/products/context_layer/backend/proposals.py
new file mode 100644
index 000000000000..bf0f65d62154
--- /dev/null
+++ b/products/context_layer/backend/proposals.py
@@ -0,0 +1,98 @@
+import uuid
+from datetime import datetime
+
+from posthog.dataclasses import frozen
+
+from products.context_layer.backend import pages, store
+from products.context_layer.backend.models import WikiPageProposal
+from products.context_layer.backend.repo_lint import MAX_FILE_BYTES
+
+
+@frozen
+class WikiPageProposalDTO:
+ id: uuid.UUID
+ task_id: uuid.UUID
+ path: str
+ original_content: str
+ content: str
+ base_head: str
+ created_at: datetime
+
+
+def _proposal_dto(proposal: WikiPageProposal) -> WikiPageProposalDTO:
+ return WikiPageProposalDTO(
+ id=proposal.id,
+ task_id=proposal.task_id,
+ path=proposal.path,
+ original_content=proposal.original_content,
+ content=proposal.content,
+ base_head=proposal.base_head,
+ created_at=proposal.created_at,
+ )
+
+
+def create_page_proposal(
+ organization_id: uuid.UUID,
+ *,
+ team_id: int,
+ user_id: int,
+ task_id: uuid.UUID,
+ path: str,
+ content: str,
+ base_head: str,
+) -> WikiPageProposalDTO:
+ if not pages.is_run_content_path(path) or not path.startswith(("org/", "areas/", "decisions/")):
+ raise pages.InvalidPagePathError("Propose an edit to an existing page under org/, areas/, or decisions/.")
+ if pages.page_frontmatter_channel_id(content) is not None:
+ raise pages.InvalidPagePathError("Shared wiki pages cannot declare channel_id frontmatter.")
+ if len(content.encode("utf-8")) > MAX_FILE_BYTES:
+ raise pages.InvalidPagePathError("The proposed page exceeds the wiki page size limit.")
+ page = pages.get_page(organization_id, path)
+ if page.head_sha != base_head:
+ raise store.HeadConflictError(current_head=page.head_sha)
+ with store.repo_writer_lock(organization_id):
+ current_head = store.get_config(organization_id).head_sha
+ if current_head != base_head:
+ raise store.HeadConflictError(current_head=current_head)
+ proposal = WikiPageProposal.objects.for_team(team_id).create(
+ team_id=team_id,
+ created_by_id=user_id,
+ task_id=task_id,
+ path=path,
+ original_content=page.content,
+ content=content,
+ base_head=base_head,
+ )
+ return _proposal_dto(proposal)
+
+
+def list_page_proposals(organization_id: uuid.UUID, user_id: int) -> list[WikiPageProposalDTO]:
+ proposals = (
+ WikiPageProposal.objects.unscoped()
+ .filter(team__organization_id=organization_id, created_by_id=user_id, applied_head="")
+ .order_by("-created_at")[:100]
+ )
+ return [_proposal_dto(proposal) for proposal in proposals]
+
+
+def apply_page_proposal(
+ organization_id: uuid.UUID, user_id: int, proposal_id: uuid.UUID, *, author: store.CommitAuthor
+) -> str:
+ try:
+ # nosemgrep: idor-lookup-without-team (the organization and creator scope this cross-team review lookup)
+ proposal = WikiPageProposal.objects.unscoped().get(
+ id=proposal_id, team__organization_id=organization_id, created_by_id=user_id
+ )
+ except WikiPageProposal.DoesNotExist as error:
+ raise pages.PageNotFoundError("This suggested edit is not available to you.") from error
+ if proposal.applied_head:
+ return proposal.applied_head
+ head_sha = pages.write_page(
+ organization_id,
+ path=proposal.path,
+ content=proposal.content,
+ base_head=proposal.base_head,
+ author=author,
+ )
+ WikiPageProposal.objects.for_team(proposal.team_id).filter(id=proposal.id).update(applied_head=head_sha)
+ return head_sha
diff --git a/products/context_layer/backend/scaffold.py b/products/context_layer/backend/scaffold.py
index 6c76039a116a..222d20d52a60 100644
--- a/products/context_layer/backend/scaffold.py
+++ b/products/context_layer/backend/scaffold.py
@@ -39,7 +39,7 @@ retrieved live from their authoritative system.
- Keep pages in the directories above; `scripts/lint` checks the structure.
- Write synthesized prose, not raw excerpts from source material.
-- If your work makes a page stale, correct those lines and commit the edit.
+- If your work makes a page stale, propose a correction for the user to review.
- Prune as you write; git history is the archive.
- Keep decisions append-only. Replace one by setting `status: superseded` and linking its replacement.
@@ -47,8 +47,10 @@ retrieved live from their authoritative system.
- `areas/`: Current state, Direction, Links.
- `decisions/`: `sources:` frontmatter, then What, Why, Who.
-- In a sandbox, run `scripts/publish` to land your commits; a linter reviews
- the structure before they land.
+- For a shared-page correction in a task run, use `task-context-wiki-page-retrieve`, then `task-context-wiki-page-propose` with the returned `head_sha` as `base_head`. Ask the user to open Context > Suggested edits, review the diff, and apply it. Suggestions are not published wiki content.
+- Task runs with wiki write access can propose edits to existing shared Markdown pages under `org/`, `areas/`, and `decisions/`. Shared pages must not include `channel_id` frontmatter. Tasks can directly update their own channel page with `task-context-wiki-page-update`. Loops can edit only their configured channel page.
+- Do not edit instruction files (`AGENTS.md` or `CLAUDE.md`), generated indexes, scripts, or other channels' pages through the task tool.
+- Ordinary tasks cannot publish commit bundles or approve suggestions. Direct human editing and server-owned nightly maintenance remain separate publication paths. If the wiki changes before approval, read it again and submit a new suggestion.
## Frontmatter contract
diff --git a/products/context_layer/backend/store.py b/products/context_layer/backend/store.py
index 2825a8eb57e8..f14326bff9d5 100644
--- a/products/context_layer/backend/store.py
+++ b/products/context_layer/backend/store.py
@@ -31,7 +31,7 @@ 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.models import ContextLayerConfig, WikiPageProposal
from products.context_layer.backend.repo_lint import lint_repo
from products.context_layer.backend.scaffold import generate_index, generate_project_indexes, write_default_structure
@@ -667,7 +667,11 @@ def _assert_dream_paths(workdir: Path, base: str, tip: str) -> None:
def _dream_may_edit(path: str, *, status: str = "M") -> bool:
parts = Path(path).parts
- if not path.endswith(".md") or not parts or Path(path).name == "index.md":
+ if (
+ not path.endswith(".md")
+ or not parts
+ or any(part.lower() in {"agents.md", "claude.md", "index.md"} for part in parts)
+ ):
return False
if parts[0] in {"org", "areas", "decisions"}:
return True
@@ -788,6 +792,7 @@ def purge_repo_history(organization_id: uuid.UUID | str, *, message: str = "Purg
with repo_writer_lock(organization_id):
head_sha = get_config(organization_id).head_sha
try:
+ WikiPageProposal.objects.unscoped().filter(team__organization_id=organization_id).delete()
_prune_bundles_except(organization_id, head_sha)
except Exception:
# The rewrite landed but old bundles with the purged content are
diff --git a/products/context_layer/backend/temporal/dreaming.py b/products/context_layer/backend/temporal/dreaming.py
index 2dfb1adb5c5f..9bf44c60cd17 100644
--- a/products/context_layer/backend/temporal/dreaming.py
+++ b/products/context_layer/backend/temporal/dreaming.py
@@ -32,6 +32,7 @@ from posthog.models.team.team import Team
from posthog.ph_client import ph_scoped_capture
from posthog.temporal.common.base import PostHogWorkflow
from posthog.temporal.common.client import sync_connect
+from posthog.temporal.oauth import CONTEXT_LAYER_INTERNAL_SCOPE, MCP_READ_SCOPES
from products.context_layer.backend.dreams import DREAM_AI_STAGE
from products.context_layer.backend.facade import api as context_layer_facade
@@ -192,14 +193,10 @@ async def dispatch_dream_run(input: DispatchDreamRunInput) -> DispatchDreamRunOu
previous_dream_started_at = target.config.last_dream_started_at
await create_task_and_trigger(
_build_dream_prompt(previous_dream_started_at),
- # Read-only MCP surface: the dream gathers from reads and lands its
- # branch through the commits endpoint, which accepts the run token's
- # task:write + internal_run:read pair — it never needs user-facing writes.
- # ACP carries that MCP surface and the publish environment into tool shells.
CustomPromptSandboxContext(
team_id=target.team_id,
user_id=target.user_id,
- posthog_mcp_scopes="read_only",
+ posthog_mcp_scopes=[*MCP_READ_SCOPES, CONTEXT_LAYER_INTERNAL_SCOPE],
runtime="acp",
runtime_adapter="codex",
model="gpt-5.6-sol",
diff --git a/products/context_layer/backend/test/test_api.py b/products/context_layer/backend/test/test_api.py
index a8a768508942..6091e6487e72 100644
--- a/products/context_layer/backend/test/test_api.py
+++ b/products/context_layer/backend/test/test_api.py
@@ -16,8 +16,10 @@ from parameterized import parameterized
import posthog.storage.object_storage as object_storage_module
from posthog.models.oauth import OAuthAccessToken, OAuthApplication
+from posthog.models.organization import Organization
from posthog.models.scoping import team_scope
from posthog.models.team.team import Team
+from posthog.models.user import User
from posthog.storage.object_storage import UnavailableStorage
from posthog.utils import safe_cache_set
@@ -68,7 +70,7 @@ class TestContextLayerAPI(APIBaseTest):
)
return token.token
- def test_agent_route_accepts_the_run_token_the_org_route_refuses(self, _flag) -> None:
+ def test_ordinary_run_cannot_publish_bundles_on_either_route(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.
@@ -83,7 +85,7 @@ class TestContextLayerAPI(APIBaseTest):
HTTP_AUTHORIZATION=f"Bearer {token}",
)
- assert post(self.agent_url).status_code == 200
+ assert post(self.agent_url).status_code == 403
# APIScopePermission refuses any token carrying scoped_teams on a route
# that is not project-nested, which is the whole reason the agent route
@@ -424,10 +426,10 @@ class TestContextLayerAPI(APIBaseTest):
HTTP_AUTHORIZATION=f"Bearer {token}",
)
- def test_commits_accepts_a_sandbox_run_token(self, _flag) -> None:
+ def test_commits_rejects_an_ordinary_sandbox_run_token(self, _flag) -> None:
assert (
self._post_bundle_with_bearer("task:write internal_run:read context_layer_internal:write").status_code
- == 200
+ == 403
)
def test_commits_rejects_read_only_sandbox_run_token(self, _flag) -> None:
@@ -562,13 +564,153 @@ class TestContextLayerAPI(APIBaseTest):
)
assert changed_frontmatter.status_code == 403, changed_frontmatter.content
- outside_channel = self.client.put(
- f"{self.agent_url}/pages/",
- {"path": "AGENTS.md", "content": "# Owned\n", "base_head": created.json()["head_sha"]},
+ for path in (
+ "AGENTS.md",
+ "CLAUDE.md",
+ "index.md",
+ "scripts/publish",
+ "areas/index.md",
+ "areas/AGENTS.md",
+ "areas/claude.md",
+ "areas/../AGENTS.md",
+ "areas/../projects/overview.md",
+ f"projects/{self.team.id}/spaces/sales.md",
+ ):
+ outside_channel = self.client.put(
+ f"{self.agent_url}/pages/",
+ {"path": path, "content": _page("Protected"), "base_head": created.json()["head_sha"]},
+ format="json",
+ HTTP_AUTHORIZATION=f"Bearer {token}",
+ )
+ assert outside_channel.status_code == 403, (path, outside_channel.content)
+
+ @parameterized.expand(["org/product.md", "areas/product.md", "decisions/2026-09-01-product.md"])
+ def test_task_proposes_shared_content_for_human_review(self, _flag: MagicMock, path: str) -> 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
+ self._enable()
+ original = _page("Product").replace("status: active", "status: active\nsources: Product documentation")
+ created = self.client.put(f"{self.base_url}/pages/", {"path": path, "content": original}, format="json")
+ assert created.status_code == 200, created.content
+ task = apps.get_model("tasks", "Task").objects.create(
+ team=self.team, created_by=self.user, title="Update product context", channel_id=channel.id
+ )
+ token = self._bearer(
+ "task:read task:write internal_run:read context_layer_internal:write",
+ scoped_teams=[self.team.id],
+ sandbox_task_id=task.id,
+ )
+ self.client.logout()
+ content = original.replace("Product", "Updated product")
+ payload = {"path": path, "content": content, "base_head": created.json()["head_sha"]}
+
+ updated = self.client.put(
+ f"{self.agent_url}/pages/", payload, format="json", HTTP_AUTHORIZATION=f"Bearer {token}"
+ )
+ assert updated.status_code == 403, updated.content
+ proposed = self.client.post(
+ f"{self.agent_url}/proposals/", payload, format="json", HTTP_AUTHORIZATION=f"Bearer {token}"
+ )
+ assert proposed.status_code == 201, proposed.content
+ proposal = proposed.json()
+ assert proposal["original_content"] == original
+ assert proposal["content"] == content
+ assert proposal["base_head"] == payload["base_head"]
+ page = self.client.get(f"{self.agent_url}/pages/", {"path": path}, HTTP_AUTHORIZATION=f"Bearer {token}")
+ assert page.json()["content"] == original
+ assert page.json()["head_sha"] == payload["base_head"]
+ second = self.client.post(
+ f"{self.agent_url}/proposals/", payload, format="json", HTTP_AUTHORIZATION=f"Bearer {token}"
+ )
+ assert second.status_code == 201, second.content
+
+ apply_url = f"{self.base_url}/proposals/{proposal['id']}/apply/"
+ for scope in (
+ "organization:write internal_run:read context_layer_internal:write",
+ "organization:write loop_context_internal:write",
+ "organization:read",
+ ):
+ denied = self.client.post(apply_url, HTTP_AUTHORIZATION=f"Bearer {self._bearer(scope)}")
+ assert denied.status_code == 403, denied.content
+
+ for restricted_token in (
+ self._loop_run_token(channel.id),
+ self._bearer("task:write internal_run:read", scoped_teams=[self.team.id], sandbox_task_id=task.id),
+ ):
+ denied = self.client.post(
+ f"{self.agent_url}/proposals/",
+ payload,
+ format="json",
+ HTTP_AUTHORIZATION=f"Bearer {restricted_token}",
+ )
+ assert denied.status_code == 403, denied.content
+
+ for protected_path in ("AGENTS.md", "areas/CLAUDE.md", "areas/index.md", "areas/../AGENTS.md"):
+ denied = self.client.post(
+ f"{self.agent_url}/proposals/",
+ {**payload, "path": protected_path},
+ format="json",
+ HTTP_AUTHORIZATION=f"Bearer {token}",
+ )
+ assert denied.status_code == 400, denied.content
+ denied = self.client.post(
+ f"{self.agent_url}/proposals/",
+ {**payload, "content": content.replace("status: active", f"status: active\nchannel_id: {channel.id}")},
format="json",
HTTP_AUTHORIZATION=f"Bearer {token}",
)
- assert outside_channel.status_code == 403, outside_channel.content
+ assert denied.status_code == 400, denied.content
+
+ other_user = User.objects.create_and_join(self.organization, "[email protected]", None)
+ self.client.force_login(other_user)
+ assert self.client.get(f"{self.base_url}/proposals/").json() == []
+ assert self.client.post(apply_url).status_code == 404
+ self.client.force_login(self.user)
+ other_organization = Organization.objects.create(name="Other organization")
+ self.user.join(organization=other_organization)
+ other_base = f"/api/organizations/{other_organization.id}/context_layer"
+ assert self.client.get(f"{other_base}/proposals/").json() == []
+ assert self.client.post(f"{other_base}/proposals/{proposal['id']}/apply/").status_code == 404
+ pending = self.client.get(f"{self.base_url}/proposals/")
+ assert pending.status_code == 200, pending.content
+ assert {item["id"] for item in pending.json()} == {proposal["id"], second.json()["id"]}
+ applied = self.client.post(apply_url, {"content": "Ignore the stored content"}, format="json")
+ assert applied.status_code == 200, applied.content
+ assert self.client.post(apply_url).json() == applied.json()
+ stale_apply = self.client.post(f"{self.base_url}/proposals/{second.json()['id']}/apply/")
+ assert stale_apply.status_code == 409, stale_apply.content
+ assert self.client.get(f"{self.base_url}/proposals/").json() == [second.json()]
+ page = self.client.get(f"{self.base_url}/pages/", {"path": path})
+ assert page.json()["content"] == content
+ assert page.json()["head_sha"] == applied.json()["head_sha"]
+
+ self.client.logout()
+ stale = self.client.post(
+ f"{self.agent_url}/proposals/", payload, format="json", HTTP_AUTHORIZATION=f"Bearer {token}"
+ )
+ assert stale.status_code == 409, stale.content
+ assert stale.json()["current_head"] == applied.json()["head_sha"]
+
+ for restricted_token, restricted_content in (
+ (self._loop_run_token(channel.id), content),
+ (
+ self._bearer(
+ "task:read task:write internal_run:read",
+ scoped_teams=[self.team.id],
+ sandbox_task_id=task.id,
+ ),
+ content,
+ ),
+ (token, content.replace("status: active", f"status: active\nchannel_id: {channel.id}")),
+ ):
+ denied = self.client.put(
+ f"{self.agent_url}/pages/",
+ {"path": path, "content": restricted_content, "base_head": applied.json()["head_sha"]},
+ format="json",
+ HTTP_AUTHORIZATION=f"Bearer {restricted_token}",
+ )
+ assert denied.status_code == 403, denied.content
def test_read_only_task_token_cannot_update_its_channel_page(self, _flag) -> None:
with team_scope(self.team.id):
@@ -662,7 +804,16 @@ class TestContextLayerAPI(APIBaseTest):
def test_run_commit_landings_are_capped_per_day(self, _flag) -> None:
self._enable()
- task = apps.get_model("tasks", "Task").objects.create(team=self.team, created_by=self.user, title="agent work")
+ task = apps.get_model("tasks", "Task").objects.create(
+ team=self.team, created_by=self.user, title="Wiki maintenance", internal=True
+ )
+ apps.get_model("tasks", "TaskRun").objects.create(
+ task=task,
+ team=self.team,
+ status="in_progress",
+ environment="cloud",
+ state={"ai_stage": dreams.DREAM_AI_STAGE},
+ )
token = self._bearer(
"task:write internal_run:read context_layer_internal:write",
scoped_teams=[self.team.id],
@@ -671,10 +822,10 @@ class TestContextLayerAPI(APIBaseTest):
self.client.logout()
def land(path: str):
- bundle_bytes = self._bundle_with_edit(path, _page(path))
+ bundle_bytes = self._bundle_with_edit(path, _page(path), branch="dream/2026-09-11")
return self.client.post(
f"{self.agent_url}/commits/",
- {"bundle": SimpleUploadedFile("out.bundle", bundle_bytes)},
+ {"bundle": SimpleUploadedFile("out.bundle", bundle_bytes), "branch": "dream/2026-09-11"},
format="multipart",
HTTP_AUTHORIZATION=f"Bearer {token}",
)
@@ -684,6 +835,35 @@ class TestContextLayerAPI(APIBaseTest):
capped = land("areas/second.md")
assert capped.status_code == 429
+ @parameterized.expand([False, True])
+ def test_task_cannot_claim_maintenance_with_a_dream_branch(self, _flag: MagicMock, internal: bool) -> None:
+ head = self._enable()
+ task = apps.get_model("tasks", "Task").objects.create(
+ team=self.team, created_by=self.user, title="Wiki suggestion", internal=internal
+ )
+ apps.get_model("tasks", "TaskRun").objects.create(
+ task=task,
+ team=self.team,
+ status="completed" if internal else "in_progress",
+ environment="cloud",
+ state={"ai_stage": dreams.DREAM_AI_STAGE},
+ )
+ token = self._bearer(
+ "task:write internal_run:read context_layer_internal:write",
+ scoped_teams=[self.team.id],
+ sandbox_task_id=task.id,
+ )
+ bundle = self._bundle_with_edit("areas/suggestion.md", _page("Suggestion"), branch="dream/2026-09-11")
+ self.client.logout()
+ response = self.client.post(
+ f"{self.agent_url}/commits/",
+ {"bundle": SimpleUploadedFile("out.bundle", bundle), "branch": "dream/2026-09-11"},
+ format="multipart",
+ HTTP_AUTHORIZATION=f"Bearer {token}",
+ )
+ assert response.status_code == 403, response.content
+ assert store.get_config(self.organization.id).head_sha == head
+
def test_loop_token_cannot_land_commit_bundles(self, _flag) -> None:
# Bundles bypass the loop's page binding, so the bundle route must refuse them.
self._enable()
diff --git a/products/context_layer/backend/test/test_dreaming.py b/products/context_layer/backend/test/test_dreaming.py
index 4b58c261a2c7..b0e598d6a231 100644
--- a/products/context_layer/backend/test/test_dreaming.py
+++ b/products/context_layer/backend/test/test_dreaming.py
@@ -169,6 +169,7 @@ class TestDreamingLane(BaseTest):
assert context.model == "gpt-5.6-sol"
assert context.reasoning_effort == "high"
assert context.initial_permission_mode == "bypassPermissions"
+ assert context.posthog_mcp_scopes == [*dreaming.MCP_READ_SCOPES, dreaming.CONTEXT_LAYER_INTERNAL_SCOPE]
assert trigger_mock.call_args.kwargs["ai_stage"] == dreaming.DREAM_AI_STAGE
prompt = trigger_mock.call_args.args[0]
assert prompt.startswith(
diff --git a/products/context_layer/backend/test/test_store.py b/products/context_layer/backend/test/test_store.py
index d8738a56c61b..e80e336debb5 100644
--- a/products/context_layer/backend/test/test_store.py
+++ b/products/context_layer/backend/test/test_store.py
@@ -1,6 +1,7 @@
import tempfile
import subprocess
from pathlib import Path
+from uuid import uuid4
from posthog.test.base import BaseTest
from unittest.mock import MagicMock, patch
@@ -13,7 +14,7 @@ import posthog.storage.object_storage as object_storage_module
from posthog.storage.object_storage import UnavailableStorage
from products.context_layer.backend import repo_lint, store
-from products.context_layer.backend.models import ContextLayerConfig
+from products.context_layer.backend.models import ContextLayerConfig, WikiPageProposal
class TestRepoWriterLock(SimpleTestCase):
@@ -52,6 +53,9 @@ class TestDreamPathGuard(SimpleTestCase):
assert not store._dream_may_edit("AGENTS.md")
assert not store._dream_may_edit("index.md")
assert not store._dream_may_edit("projects/1/spaces/index.md")
+ assert not store._dream_may_edit("areas/AGENTS.md")
+ assert not store._dream_may_edit("org/claude.md")
+ assert not store._dream_may_edit("decisions/INDEX.md")
assert not store._dream_may_edit("scripts/lint")
assert not store._dream_may_edit("scripts/publish")
@@ -174,7 +178,17 @@ class TestContextLayerStore(BaseTest):
(root / "areas" / "replay.md").write_text(_page("Replay"))
store.apply_changes(self.organization.id, message="Add the replay area page", mutate=add_page)
+ WikiPageProposal.objects.for_team(self.team.id).create(
+ team_id=self.team.id,
+ created_by=self.user,
+ task_id=uuid4(),
+ path="areas/replay.md",
+ original_content="Content to remove",
+ content="Suggested content",
+ base_head=store.get_config(self.organization.id).head_sha,
+ )
store.purge_repo_history(self.organization.id)
+ assert not WikiPageProposal.objects.for_team(self.team.id).exists()
with store.checkout_repo(self.organization.id) as checkout:
assert (checkout.path / "areas" / "replay.md").is_file()
diff --git a/products/context_layer/frontend/generated/api.schemas.ts b/products/context_layer/frontend/generated/api.schemas.ts
index 43789ef77c69..e74be6215694 100644
--- a/products/context_layer/frontend/generated/api.schemas.ts
+++ b/products/context_layer/frontend/generated/api.schemas.ts
@@ -209,6 +209,32 @@ export interface HeadConflictApi {
current_head: string
}
+export interface WikiPageProposalApi {
+ /** Immutable suggested edit ID. Only its author can apply it through the user API. */
+ id: string
+ /** Task that proposed the edit. */
+ task_id: string
+ /** Shared wiki page to review. */
+ path: string
+ /** Page content at the revision the proposal is based on. */
+ original_content: string
+ /** Proposed page content. This is not published wiki content. */
+ content: string
+ /** Wiki revision the proposal is based on. */
+ base_head: string
+ /** When the edit was proposed. */
+ created_at: string
+}
+
+export interface PaginatedWikiPageProposalListApi {
+ count: number
+ /** @nullable */
+ next?: string | null
+ /** @nullable */
+ previous?: string | null
+ results: WikiPageProposalApi[]
+}
+
/**
* Response shape for the wiki's page listing.
*/
@@ -235,6 +261,27 @@ export interface WikiHealthReportApi {
findings: WikiHealthFindingApi[]
}
+/**
+ * Request body for creating or replacing one wiki page.
+ */
+export interface WikiPageProposalWriteApi {
+ /**
+ * Repo-relative Markdown path inside the wiki's structure, for example `projects/12/spaces/general.md`.
+ * @maxLength 512
+ */
+ path: string
+ /**
+ * The complete Markdown content for the page.
+ * @maxLength 1000000
+ */
+ content: string
+ /**
+ * The head_sha returned when reading the page. Required to bind the proposed edit.
+ * @maxLength 64
+ */
+ base_head: string
+}
+
export type ContextLayerPagesRetrieveParams = {
/**
* Repo-relative Markdown path of the page to read.
@@ -242,6 +289,17 @@ export type ContextLayerPagesRetrieveParams = {
path: string
}
+export type ContextLayerProposalsListParams = {
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number
+}
+
export type ContextLayerAgentPagesRetrieveParams = {
/**
* Repo-relative Markdown path of the page to read.
diff --git a/products/context_layer/frontend/generated/api.ts b/products/context_layer/frontend/generated/api.ts
index 16089818f770..2175e828d4df 100644
--- a/products/context_layer/frontend/generated/api.ts
+++ b/products/context_layer/frontend/generated/api.ts
@@ -13,12 +13,16 @@ import type {
CommitBundleApi,
ContextLayerAgentPagesRetrieveParams,
ContextLayerPagesRetrieveParams,
+ ContextLayerProposalsListParams,
ContextLayerStatusApi,
DreamRunDetailApi,
DreamRunListApi,
+ PaginatedWikiPageProposalListApi,
WikiExportApi,
WikiHealthReportApi,
WikiPageApi,
+ WikiPageProposalApi,
+ WikiPageProposalWriteApi,
WikiPageWriteApi,
WikiTreeApi,
} from './api.schemas'
@@ -196,6 +200,56 @@ export const contextLayerPagesUpdate = async (
})
}
+export const getContextLayerProposalsListUrl = (organizationId: string, params?: ContextLayerProposalsListParams) => {
+ 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/proposals/?${stringifiedParams}`
+ : `/api/organizations/${organizationId}/context_layer/proposals/`
+}
+
+/**
+ * The organization's context wiki: a git repo of Markdown pages hosted by PostHog.
+ * @summary List your pending wiki edits
+ */
+export const contextLayerProposalsList = async (
+ organizationId: string,
+ params?: ContextLayerProposalsListParams,
+ options?: RequestInit
+): Promise<PaginatedWikiPageProposalListApi> => {
+ return apiMutator<PaginatedWikiPageProposalListApi>(getContextLayerProposalsListUrl(organizationId, params), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getContextLayerProposalsApplyCreateUrl = (organizationId: string, proposalId: string) => {
+ return `/api/organizations/${organizationId}/context_layer/proposals/${proposalId}/apply/`
+}
+
+/**
+ * The organization's context wiki: a git repo of Markdown pages hosted by PostHog.
+ * @summary Apply a reviewed wiki edit
+ */
+export const contextLayerProposalsApplyCreate = async (
+ organizationId: string,
+ proposalId: string,
+ options?: RequestInit
+): Promise<ContextLayerStatusApi> => {
+ return apiMutator<ContextLayerStatusApi>(getContextLayerProposalsApplyCreateUrl(organizationId, proposalId), {
+ ...options,
+ method: 'POST',
+ })
+}
+
export const getContextLayerStatusRetrieveUrl = (organizationId: string) => {
return `/api/organizations/${organizationId}/context_layer/status/`
}
@@ -370,3 +424,31 @@ export const contextLayerAgentPagesUpdate = async (
body: JSON.stringify(wikiPageWriteApi),
})
}
+
+export const getContextLayerAgentProposalsCreateUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/context_layer/agent/proposals/`
+}
+
+/**
+ * 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 Propose a shared wiki edit for human review
+ */
+export const contextLayerAgentProposalsCreate = async (
+ projectId: string,
+ wikiPageProposalWriteApi: WikiPageProposalWriteApi,
+ options?: RequestInit
+): Promise<WikiPageProposalApi> => {
+ return apiMutator<WikiPageProposalApi>(getContextLayerAgentProposalsCreateUrl(projectId), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(wikiPageProposalWriteApi),
+ })
+}
diff --git a/products/context_layer/frontend/generated/api.zod.ts b/products/context_layer/frontend/generated/api.zod.ts
index 5304e2501d8e..97b4129233ed 100644
--- a/products/context_layer/frontend/generated/api.zod.ts
+++ b/products/context_layer/frontend/generated/api.zod.ts
@@ -140,3 +140,39 @@ export const ContextLayerAgentPagesUpdateBody = /* @__PURE__ */ zod
),
})
.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 Propose a shared wiki edit for human review
+ */
+export const contextLayerAgentProposalsCreateBodyPathMax = 512
+
+export const contextLayerAgentProposalsCreateBodyContentMax = 1000000
+
+export const contextLayerAgentProposalsCreateBodyBaseHeadMax = 64
+
+export const ContextLayerAgentProposalsCreateBody = /* @__PURE__ */ zod
+ .object({
+ path: zod
+ .string()
+ .max(contextLayerAgentProposalsCreateBodyPathMax)
+ .describe(
+ "Repo-relative Markdown path inside the wiki's structure, for example `projects\/12\/spaces\/general.md`."
+ ),
+ content: zod
+ .string()
+ .max(contextLayerAgentProposalsCreateBodyContentMax)
+ .describe('The complete Markdown content for the page.'),
+ base_head: zod
+ .string()
+ .max(contextLayerAgentProposalsCreateBodyBaseHeadMax)
+ .describe('The head_sha returned when reading the page. Required to bind the proposed edit.'),
+ })
+ .describe('Request body for creating or replacing one wiki page.')
diff --git a/products/context_layer/mcp/tools.yaml b/products/context_layer/mcp/tools.yaml
index 356b7a112df2..7ab1f6ec5bee 100644
--- a/products/context_layer/mcp/tools.yaml
+++ b/products/context_layer/mcp/tools.yaml
@@ -36,6 +36,12 @@ tools:
context-layer-pages-update:
operation: context_layer_pages_update
enabled: false
+ context-layer-proposals-apply-create:
+ operation: context_layer_proposals_apply_create
+ enabled: false
+ context-layer-proposals-list:
+ operation: context_layer_proposals_list
+ enabled: false
context-layer-status-retrieve:
operation: context_layer_status_retrieve
enabled: false
@@ -139,6 +145,24 @@ tools:
title: Resolve this task's channel context page
description: Resolve the current task's channel id to its context wiki page path for an unattended task run.
feature_flag: context-layer
+ task-context-wiki-page-propose:
+ operation: context_layer_agent_proposals_create
+ enabled: true
+ scopes:
+ - task:write
+ - internal_run:read
+ - context_layer_internal:write
+ annotations:
+ readOnly: false
+ destructive: false
+ idempotent: false
+ title: Suggest a shared wiki edit
+ description: >
+ Propose a correction to an existing shared Markdown page under org/, areas/, or decisions/. Read it first
+ and pass head_sha as base_head. This stores an immutable suggestion, not a published edit. Ask the user to
+ open Context > Suggested edits, review the diff, and apply it. Tasks cannot approve suggestions or publish
+ bundles. Shared pages cannot include channel_id frontmatter.
+ feature_flag: context-layer
task-context-wiki-page-retrieve:
operation: context_layer_agent_pages_retrieve
enabled: true
@@ -164,5 +188,8 @@ tools:
destructive: true
idempotent: false
title: Update this task's context wiki page
- description: Replace the current task channel's context wiki page using base_head concurrency.
+ description: >
+ Replace the current task channel's context page. Read it first and pass head_sha as base_head. Shared pages
+ require task-context-wiki-page-propose and human review. Instruction files, generated indexes, scripts, and
+ other channels' pages cannot be edited.
feature_flag: context-layer
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index 10a832aea8bd..112a57308de6 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -11244,6 +11244,21 @@
},
"feature_flag": "context-layer"
},
+ "task-context-wiki-page-propose": {
+ "description": "Propose a correction to an existing shared Markdown page under org/, areas/, or decisions/. Read it first and pass head_sha as base_head. This stores an immutable suggestion, not a published edit. Ask the user to open Context > Suggested edits, review the diff, and apply it. Tasks cannot approve suggestions or publish bundles. Shared pages cannot include channel_id frontmatter.",
+ "category": "Context wiki",
+ "feature": "context_layer",
+ "summary": "Suggest a shared wiki edit",
+ "title": "Suggest a shared wiki edit",
+ "required_scopes": ["task:write", "internal_run:read", "context_layer_internal:write"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": false,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ },
+ "feature_flag": "context-layer"
+ },
"task-context-wiki-page-retrieve": {
"description": "Read a context wiki page and its head_sha for an unattended task run.",
"category": "Context wiki",
@@ -11260,7 +11275,7 @@
"feature_flag": "context-layer"
},
"task-context-wiki-page-update": {
- "description": "Replace the current task channel's context wiki page using base_head concurrency.",
+ "description": "Replace the current task channel's context page. Read it first and pass head_sha as base_head. Shared pages require task-context-wiki-page-propose and human review. Instruction files, generated indexes, scripts, and other channels' pages cannot be edited.",
"category": "Context wiki",
"feature": "context_layer",
"summary": "Update this task's context wiki page",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index 90028c97226a..8f49090014f7 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -11844,6 +11844,21 @@
},
"feature_flag": "context-layer"
},
+ "task-context-wiki-page-propose": {
+ "description": "Propose a correction to an existing shared Markdown page under org/, areas/, or decisions/. Read it first and pass head_sha as base_head. This stores an immutable suggestion, not a published edit. Ask the user to open Context > Suggested edits, review the diff, and apply it. Tasks cannot approve suggestions or publish bundles. Shared pages cannot include channel_id frontmatter.",
+ "category": "Context wiki",
+ "feature": "context_layer",
+ "summary": "Suggest a shared wiki edit",
+ "title": "Suggest a shared wiki edit",
+ "required_scopes": ["task:write", "internal_run:read", "context_layer_internal:write"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": false,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ },
+ "feature_flag": "context-layer"
+ },
"task-context-wiki-page-retrieve": {
"description": "Read a context wiki page and its head_sha for an unattended task run.",
"category": "Context wiki",
@@ -11860,7 +11875,7 @@
"feature_flag": "context-layer"
},
"task-context-wiki-page-update": {
- "description": "Replace the current task channel's context wiki page using base_head concurrency.",
+ "description": "Replace the current task channel's context page. Read it first and pass head_sha as base_head. Shared pages require task-context-wiki-page-propose and human review. Instruction files, generated indexes, scripts, and other channels' pages cannot be edited.",
"category": "Context wiki",
"feature": "context_layer",
"summary": "Update this task's context wiki page",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 4d9ce5bd26f6..450f48fd9326 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -62127,6 +62127,32 @@ export namespace Schemas {
results: WebExperimentsAPI[];
}
+ export interface WikiPageProposal {
+ /** Immutable suggested edit ID. Only its author can apply it through the user API. */
+ id: string;
+ /** Task that proposed the edit. */
+ task_id: string;
+ /** Shared wiki page to review. */
+ path: string;
+ /** Page content at the revision the proposal is based on. */
+ original_content: string;
+ /** Proposed page content. This is not published wiki content. */
+ content: string;
+ /** Wiki revision the proposal is based on. */
+ base_head: string;
+ /** When the edit was proposed. */
+ created_at: string;
+ }
+
+ export interface PaginatedWikiPageProposalList {
+ count: number;
+ /** @nullable */
+ next?: string | null;
+ /** @nullable */
+ previous?: string | null;
+ results: WikiPageProposal[];
+ }
+
/**
* * `local` - local
* * `cloud` - cloud
@@ -90443,6 +90469,27 @@ export namespace Schemas {
updated_at: string;
}
+ /**
+ * Request body for creating or replacing one wiki page.
+ */
+ export interface WikiPageProposalWrite {
+ /**
+ * Repo-relative Markdown path inside the wiki's structure, for example `projects/12/spaces/general.md`.
+ * @maxLength 512
+ */
+ path: string;
+ /**
+ * The complete Markdown content for the page.
+ * @maxLength 1000000
+ */
+ content: string;
+ /**
+ * The head_sha returned when reading the page. Required to bind the proposed edit.
+ * @maxLength 64
+ */
+ base_head: string;
+ }
+
/**
* Request body for creating or replacing one wiki page.
*/
@@ -93524,6 +93571,17 @@ export namespace Schemas {
path: string;
};
+ export type ContextLayerProposalsListParams = {
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number;
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number;
+ };
+
export type DomainsListParams = {
/**
* Number of results to return per page.
diff --git a/services/mcp/src/generated/context_layer/api.ts b/services/mcp/src/generated/context_layer/api.ts
index 8b3e811b6372..137825fac875 100644
--- a/services/mcp/src/generated/context_layer/api.ts
+++ b/services/mcp/src/generated/context_layer/api.ts
@@ -3,7 +3,7 @@
* MCP service uses these Zod schemas for generated tool handlers.
* To regenerate: hogli build:openapi
*
- * PostHog API - MCP 3 enabled ops
+ * PostHog API - MCP 4 enabled ops
* OpenAPI spec version: 1.0.0
*/
import * as zod from 'zod'
@@ -87,3 +87,47 @@ export const ContextLayerAgentPagesUpdateBody = () => zod
),
})
.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 Propose a shared wiki edit for human review
+ */
+export const ContextLayerAgentProposalsCreateParams = () => zod.object({
+ project_id: zod
+ .string()
+ .describe(
+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."
+ ),
+})
+
+export const contextLayerAgentProposalsCreateBodyPathMax = 512
+
+export const contextLayerAgentProposalsCreateBodyContentMax = 1000000
+
+export const contextLayerAgentProposalsCreateBodyBaseHeadMax = 64
+
+export const ContextLayerAgentProposalsCreateBody = () => zod
+ .object({
+ path: zod
+ .string()
+ .max(contextLayerAgentProposalsCreateBodyPathMax)
+ .describe(
+ "Repo-relative Markdown path inside the wiki's structure, for example `projects\/12\/spaces\/general.md`."
+ ),
+ content: zod
+ .string()
+ .max(contextLayerAgentProposalsCreateBodyContentMax)
+ .describe('The complete Markdown content for the page.'),
+ base_head: zod
+ .string()
+ .max(contextLayerAgentProposalsCreateBodyBaseHeadMax)
+ .describe('The head_sha returned when reading the page. Required to bind the proposed edit.'),
+ })
+ .describe('Request body for creating or replacing one wiki page.')
diff --git a/services/mcp/src/tools/generated/context_layer.ts b/services/mcp/src/tools/generated/context_layer.ts
index 30dad4d6495c..ca35782f8c11 100644
--- a/services/mcp/src/tools/generated/context_layer.ts
+++ b/services/mcp/src/tools/generated/context_layer.ts
@@ -177,6 +177,38 @@ const taskContextWikiChannelResolve = (): ToolBase<
},
})
+const TaskContextWikiPageProposeSchema = () => {
+ const ContextLayerAgentProposalsCreateBody = orvalSchemas.ContextLayerAgentProposalsCreateBody()
+ return ContextLayerAgentProposalsCreateBody
+}
+
+const taskContextWikiPagePropose = (): ToolBase<
+ ReturnType<typeof TaskContextWikiPageProposeSchema>,
+ Schemas.WikiPageProposal
+> => ({
+ name: 'task-context-wiki-page-propose',
+ schema: TaskContextWikiPageProposeSchema(),
+ handler: async (context: Context, params: z.infer<ReturnType<typeof TaskContextWikiPageProposeSchema>>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const body: Record<string, unknown> = {}
+ if (params.path !== undefined) {
+ body['path'] = params.path
+ }
+ if (params.content !== undefined) {
+ body['content'] = params.content
+ }
+ if (params.base_head !== undefined) {
+ body['base_head'] = params.base_head
+ }
+ const result = await context.api.request<Schemas.WikiPageProposal>({
+ method: 'POST',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/context_layer/agent/proposals/`,
+ body,
+ })
+ return result
+ },
+})
+
const TaskContextWikiPageRetrieveSchema = () => {
const ContextLayerAgentPagesRetrieveQueryParams = orvalSchemas.ContextLayerAgentPagesRetrieveQueryParams()
return ContextLayerAgentPagesRetrieveQueryParams
@@ -241,6 +273,7 @@ export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {
'loop-context-wiki-page-retrieve': loopContextWikiPageRetrieve,
'loop-context-wiki-page-update': loopContextWikiPageUpdate,
'task-context-wiki-channel-resolve': taskContextWikiChannelResolve,
+ 'task-context-wiki-page-propose': taskContextWikiPagePropose,
'task-context-wiki-page-retrieve': taskContextWikiPageRetrieve,
'task-context-wiki-page-update': taskContextWikiPageUpdate,
}