:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(context-layer): let an org with a private project enable the wiki (#87682)
Peter Kirkham1590fc3f2655
diff --git a/products/context_layer/PROVENANCE.md b/products/context_layer/PROVENANCE.mdnew file mode 100644index 000000000000..6f8daebda21b--- /dev/null+++ b/products/context_layer/PROVENANCE.md@@ -0,0 +1,113 @@+# Per-page provenance++Design for gating wiki reads on project access.+Nothing here is built yet: the wiki is readable by anyone in the organization (see the README's "Who can read it").++## Why not a simpler gate++The obvious first idea is one audience for the whole wiki: reading takes access to every project feeding it.+That is safe and it is small, but it is coarse in two ways a user runs into immediately.++One restricted project shrinks the whole wiki's audience to that project's members.+And a project can never be removed from the set, because content synthesized from it is already spread across `org/`, `areas/`, and `decisions/` pages with nothing recording where it came from.+An "include or exclude projects" control needs removal to mean something, so it needs that record.++Scoping by path does not work either, for the same reason: a derived claim lands in an organization-wide page even when its only source is one project.++## The page contract++Two frontmatter fields carry it.++`sources` becomes a list of typed references rather than free text:++```markdown+---+summary: How activation is measured.+status: active+sources: task:018f2c…, space:019a77…, project:2+visibility: project:2+---+```++`visibility` is the set of projects a reader must be able to open to read the page.+The server owns it, the way it owns `index.md` and `scripts/`: it computes the value at land time and the linter rejects a page whose author set it.++A page's visibility is the union of the projects its sources resolve to.+Union, not intersection: a page carrying a fact from project 2 and a fact from project 7 discloses both, so reading it takes access to both.++## Where each check lives++`repo_lint.py` is stdlib-only because it ships into every wiki as `scripts/lint`, so an agent runs the same rules the server enforces.+It has no database, so it cannot resolve a reference to a project.+The split follows from that:++| Check | Runs in |+| ---------------------------------------------------------------- | ------------------------------------- |+| `sources` is present and every entry parses as a typed reference | `scripts/lint`, and again server-side |+| `visibility` is absent or unchanged from what the server wrote | `scripts/lint`, and again server-side |+| Each reference resolves to something real, in this organization | server only, at land |+| `visibility` recomputed and stamped | server only, at land |++## Reference kinds++| Reference | Resolves through | Projects |+| ------------------------ | ----------------------------- | ------------ |+| `project:<id>` | itself | that project |+| `space:<uuid>` | the channel's team | that project |+| `task:<uuid>` | the task's team | that project |+| `loop:<uuid>` | the loop's team | that project |+| `event:<team_id>:<name>` | the definition's team | that project |+| `scaffold` | nothing; server-written pages | none |++A reference the server cannot resolve fails the land.+Defaulting an unresolved reference to "no projects" would make every typo an organization-wide page, which is the leak this design exists to close.++Pull requests are deliberately absent.+A repository does not belong to a project, so a PR only attributes through the task that produced it, and a dream citing a PR cites that task instead.++## Reading++An API read filters the tree and each page against the caller's readable projects.+The filter is per page, so there is no wiki-level audience left: someone who can open project 2 but not project 7 sees every page drawing only on project 2, and the rest is not listed.++A sandbox mount cannot filter that way, because it hands over a git bundle.+It gets a filtered bundle instead: a checkout with the unreadable pages removed, committed as a single commit and cached in object storage under `(head_sha, access key)`, where the access key is a hash of the sorted readable project ids.+Most runs in an organization share one access key, so the cache is warm after the first.++Squashing costs the sandbox its history, which the dreaming skill reads (`git log --merges -10`).+So the dream keeps the full bundle.+It is dispatched by the server rather than by a person, and it already runs as a user who must be able to read everything, which the dispatch check enforces.++## Landing++A filtered clone's history diverges from the wiki's, so commits made in one cannot be rebased onto it.+Runs with a filtered mount therefore write through the page endpoint, which takes a path, content, and a base head, and is already how a loop run writes.+Bundle landing stays with the dream, which is the only writer holding a full clone.++## Excluding a project++Once slices 1 to 3 exist, a project can be excluded. Excluding stops it feeding the wiki, and then:++- A page whose visibility is only that project is deleted.+- A page that also draws on projects still included keeps its visibility, so it stays readable to exactly the people who could read it before. It is queued for the consolidation pass, which either rewrites it without the excluded material or removes it.++Nothing widens.+That is the property the whole design is for: no edit to the project set ever makes existing content readable to someone who could not read it a moment earlier.++## Migrating an existing wiki++Existing pages have free-text sources and no visibility, and every one of them is readable by the whole organization today.+Stamping them all as organization-wide preserves that exactly, and it is the only honest starting point: nothing in the repository records which project a sentence came from, so there is no backfill anyone can compute.+Dreams re-stamp pages as they rewrite them, so provenance sharpens from the day it ships rather than arriving complete.++Turning this on therefore hides nothing retroactively.+It stops new content leaking, and the old content ages out as the wiki is rewritten.++## Landing order++Each slice is useful on its own and safe to deploy alone.++1. **Record provenance.** Typed sources, server-stamped visibility, lint rules, skill and scaffold updates, the migration stamp. Nothing reads visibility yet, so this changes no behavior.+2. **Filter reads.** The tree, page, report, and channel-page endpoints filter per page. This is the slice that stops the wiki being organization-wide.+3. **Filter mounts.** Filtered bundles with the access-key cache, and bundle landing restricted to full-clone runs.+4. **Edit the set.** The include/exclude UI, the exclusion rules above, and the consolidation queue for pages that outlive an excluded project.diff --git a/products/context_layer/README.md b/products/context_layer/README.mdindex 63d4c06ce3d6..d3620899e1a5 100644--- a/products/context_layer/README.md+++ b/products/context_layer/README.md@@ -11,6 +11,17 @@ Each organization gets one Git repo of Markdown, serialized as a `git bundle` in- Writer lock: `context_layer:repo:<organization_id>` in Redis (`SET NX PX 60000`, heartbeat renewal every 20s), so a crashed writer frees the org within a minute.- Writer protocol (every writer, no exceptions): acquire lock, download bundle, clone to tmp, apply commits, lint, upload new bundle, CAS head, release. On CAS failure: re-pull, retry once, then surface the error.+## Who can read it++Anyone in the organization.+The wiki does not model per-project access: a page synthesized from a restricted project is readable by an organization member who cannot open that project, and the sandbox mount follows the same rule.++That is a deliberate first step, not an oversight.+Enablement used to refuse any organization with a restricted project, which locked out the organizations most likely to want this, and gating the wiki properly needs per-page provenance rather than a path rule, because `org/`, `areas/`, and `decisions/` pages synthesize across projects.+[PROVENANCE.md](PROVENANCE.md) designs that.++Until it exists, treat the wiki as organization-wide reference material, and do not enable it for an organization whose project restrictions carry real separation.+## Default structureScaffolded at enablement and enforced by the linter (`backend/repo_lint.py`, also copied into the repo as `scripts/lint`):diff --git a/products/context_layer/backend/enablement.py b/products/context_layer/backend/enablement.pyindex c9d2e9594294..fce3b48315c5 100644--- a/products/context_layer/backend/enablement.py+++ b/products/context_layer/backend/enablement.py@@ -28,26 +28,13 @@ from products.tasks.backend.facade import api as tasks_facadelogger = structlog.get_logger(__name__)-class RestrictedProjectsError(store.ContextLayerStoreError):- """The organization has private projects; enabling waits for per-project partitioning."""--def enable_context_layer(organization_id: uuid.UUID | str,*,created_by_id: int | None = None,) -> ContextLayerConfig:"""Idempotent: re-enabling scaffolds nothing and re-imports only missing pages."""- # Context extracted with one project's credentials must not become readable- # through another, so orgs with private projects cannot enable until the- # wiki is partitioned per project.- private_names = private_project_names(organization_id)- if private_names:- joined = ", ".join(private_names)- raise RestrictedProjectsError(- f"This organization has private projects ({joined}). The context layer does not "- "support them yet. Remove those projects' access restrictions to enable it."- )+ _record_restricted_projects(organization_id)config = store.initialize_repo(organization_id, created_by_id=created_by_id)import_channel_context(organization_id)# The import lands its own commit, so the row read before it is already a@@ -58,6 +45,36 @@ def enable_context_layer(return config+def _record_restricted_projects(organization_id: uuid.UUID | str) -> None:+ """Note when a wiki is enabled for an organization that restricts a project.++ The wiki is organization-wide, so this is the moment that project's+ synthesized context becomes readable to members it excludes. That trade-off+ is deliberate until per-page provenance ships (see PROVENANCE.md), but it+ should be answerable afterwards rather than guessed at, so the organizations+ carrying it are recorded where they are accepted.+ """+ restricted = set(+ Team.objects.filter(organization_id=organization_id, access_control=True).values_list("id", flat=True)+ )+ restricted.update(+ int(resource_id)+ for resource_id in AccessControl.objects.filter(+ team__organization_id=organization_id,+ resource="project",+ resource_id__isnull=False,+ access_level="none",+ ).values_list("resource_id", flat=True)+ if resource_id and resource_id.isdigit()+ )+ if restricted:+ logger.warning(+ "context_layer.enabled_with_restricted_projects",+ organization_id=str(organization_id),+ restricted_project_ids=sorted(restricted),+ )++def _trigger_bootstrap_dream(organization_id: str) -> None:from products.context_layer.backend.temporal.dreaming import ( # noqa: PLC0415, I001 — keeps Temporal off Django's enablement import pathtrigger_bootstrap_dream,@@ -66,44 +83,6 @@ def _trigger_bootstrap_dream(organization_id: str) -> None:trigger_bootstrap_dream(organization_id)-def organization_has_private_projects(organization_id: uuid.UUID | str) -> bool:- """Private projects exist in two representations: the deprecated- `Team.access_control` flag (orgs not yet RBAC-migrated) and a project-level- `AccessControl` row with `access_level="none"`. Enablement must respect- both, and cares about the row existing rather than whether access control- is currently entitled, so it does not gate on the feature."""- if Team.objects.filter(organization_id=organization_id, access_control=True).exists():- return True- # Any project-level "none" row counts — the org-wide default row- # (organization_member/role null) marks a private project, and a member- or- # role-specific denial means at least one person must not see that- # project's context either way.- return AccessControl.objects.filter(- team__organization_id=organization_id,- resource="project",- resource_id__isnull=False,- access_level="none",- ).exists()---def private_project_names(organization_id: uuid.UUID | str) -> list[str]:- """Names of the projects blocking enablement, for the error an org admin- acts on. Same two representations as `organization_has_private_projects`."""- names = set(- Team.objects.filter(organization_id=organization_id, access_control=True).values_list("name", flat=True)- )- restricted_ids = AccessControl.objects.filter(- team__organization_id=organization_id,- resource="project",- resource_id__isnull=False,- access_level="none",- ).values_list("resource_id", flat=True)- names.update(- Team.objects.filter(organization_id=organization_id, id__in=list(restricted_ids)).values_list("name", flat=True)- )- return sorted(names)--def import_channel_context(organization_id: uuid.UUID | str) -> list[str]:"""Write every public channel under its project, importing CONTEXT.md when present.diff --git a/products/context_layer/backend/facade/api.py b/products/context_layer/backend/facade/api.pyindex d60ce9918143..20462c682f26 100644--- a/products/context_layer/backend/facade/api.py+++ b/products/context_layer/backend/facade/api.py@@ -16,11 +16,7 @@ from posthog.dataclasses import frozenfrom posthog.permissions import posthog_feature_flag_enabledfrom products.context_layer.backend import store-from products.context_layer.backend.enablement import (- RestrictedProjectsError,- enable_context_layer,- organization_has_private_projects,-)+from products.context_layer.backend.enablement import enable_context_layerfrom products.context_layer.backend.models import ContextLayerConfigfrom products.context_layer.backend.pages import (PAGE_MAX_BYTES,@@ -81,7 +77,6 @@ __all__ = ["PageNotFoundError","RepoLockUnavailableError","RepoNotFoundError",- "RestrictedProjectsError","WikiPage","WikiHealthFinding","WikiHealthReport",@@ -96,7 +91,6 @@ __all__ = ["is_context_layer_enabled","land_commit_bundle","land_dream_branch",- "organization_has_private_projects","page_frontmatter_channel_id","proposed_channel_page_path","resolve_channel_page",@@ -141,11 +135,6 @@ def get_sandbox_mount(organization_id: uuid.UUID | str) -> ContextLayerMount | N"""A short-lived bundle URL for cloning the wiki into a sandbox, or Nonewhen the organization has no wiki. The presign is minted here, at clonetime, so the sandbox never holds storage credentials."""- if organization_has_private_projects(organization_id):- # The wiki API goes dark when any project turns private; the sandbox- # mount must go dark with it or excluded members could read restricted- # context from any task's sandbox.- return Nonetry:export = store.get_bundle_export(organization_id)except store.ContextLayerStoreError:diff --git a/products/context_layer/backend/presentation/views.py b/products/context_layer/backend/presentation/views.pyindex fa97e7902678..6e951852cbb1 100644--- a/products/context_layer/backend/presentation/views.py+++ b/products/context_layer/backend/presentation/views.py@@ -33,22 +33,6 @@ from products.tasks.backend.facade import api as tasks_facadeRUN_COMMITS_PER_DAY_CAP = 20-def _assert_no_private_projects(organization_id) -> None: # noqa: ANN001- """The wiki is org-readable, so it goes dark the moment any project is private.-- Enablement refuses orgs with private projects, but privacy can arrive later;- imported context must not stay readable to members the project now excludes.- Re-enabling access means removing the project restriction (or, later,- per-project partitioning).- """- if facade.organization_has_private_projects(organization_id):- raise PermissionDenied(- "This organization now has private projects, so its context wiki is unavailable. "- "The context layer does not support private projects yet.",- code="private_projects",- )--def _store_error_response(error: facade.ContextLayerStoreError) -> Response:"""One mapping from store errors to HTTP for every action, so new writersadded in later layers cannot drift from this contract."""@@ -79,7 +63,6 @@ def _store_error_response(error: facade.ContextLayerStoreError) -> Response:def _read_page(organization_id, request: Request) -> Response: # noqa: ANN001- _assert_no_private_projects(organization_id)try:wiki_page = facade.get_page(organization_id, request.query_params.get("path", ""))except facade.ContextLayerStoreError as error:@@ -155,7 +138,6 @@ def _assert_loop_may_create_channel_page(def _read_channel_page(organization_id, channel_id: str, *, propose_on_miss: bool = False) -> Response: # noqa: ANN001- _assert_no_private_projects(organization_id)try:path = facade.resolve_channel_page(organization_id, channel_id)if path is None and propose_on_miss:@@ -171,7 +153,6 @@ def _read_channel_page(organization_id, channel_id: str, *, propose_on_miss: boodef _write_page(organization_id, request: Request) -> Response: # noqa: ANN001- _assert_no_private_projects(organization_id)serializer = WikiPageWriteSerializer(data=request.data)serializer.is_valid(raise_exception=True)_assert_loop_write_in_scope(@@ -218,7 +199,6 @@ def _assert_run_commit_cap(request: Request) -> None:def _land_commits(organization_id, request: Request) -> Response: # noqa: ANN001- _assert_no_private_projects(organization_id)access_token = get_oauth_access_token(request)token_scopes = set((getattr(access_token, "scope", "") or "").split())if LOOP_CONTEXT_INTERNAL_SCOPE in token_scopes:@@ -282,8 +262,6 @@ class ContextLayerViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):user_id = request.user.id if request.user and request.user.is_authenticated else Nonetry:config = facade.enable_context_layer(self.organization.id, created_by_id=user_id)- except facade.RestrictedProjectsError as error:- raise ValidationError(str(error), code="private_projects") from errorexcept facade.ContextLayerStoreError as error:return _store_error_response(error)return Response(@@ -299,7 +277,6 @@ class ContextLayerViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):)@action(methods=["GET"], detail=False)def status(self, request: Request, **kwargs) -> Response:- _assert_no_private_projects(self.organization.id)try:config = facade.get_config(self.organization.id)except facade.ContextLayerStoreError as error:@@ -312,7 +289,6 @@ class ContextLayerViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):)@action(methods=["GET"], detail=False)def tree(self, request: Request, **kwargs) -> Response:- _assert_no_private_projects(self.organization.id)try:wiki_tree = facade.get_tree(self.organization.id)except facade.ContextLayerStoreError as error:@@ -325,7 +301,6 @@ class ContextLayerViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):)@action(methods=["GET"], detail=False, url_path="wiki/report")def report(self, request: Request, **kwargs) -> Response:- _assert_no_private_projects(self.organization.id)try:report = facade.get_health_report(self.organization.id)except facade.ContextLayerStoreError as error:@@ -392,7 +367,6 @@ class ContextLayerViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):)@action(methods=["GET"], detail=False)def export(self, request: Request, **kwargs) -> Response:- _assert_no_private_projects(self.organization.id)try:bundle = facade.get_bundle_export(self.organization.id)except facade.ContextLayerStoreError as error:diff --git a/products/context_layer/backend/test/test_api.py b/products/context_layer/backend/test/test_api.pyindex fbad9e0e7de2..548dabf9d0a8 100644--- a/products/context_layer/backend/test/test_api.py+++ b/products/context_layer/backend/test/test_api.py@@ -171,27 +171,24 @@ class TestContextLayerAPI(APIBaseTest):response = self.client.get(f"{self.base_url}/channel-pages/{uuid4()}/")assert response.status_code == 404- def test_enable_is_blocked_for_orgs_with_private_projects(self, _flag) -> None:- self.team.access_control = True- self.team.save()- response = self.client.post(f"{self.base_url}/enable/")- assert response.status_code == 400- body = response.json()- assert body["code"] == "private_projects"- assert self.team.name in body["detail"]+ @parameterized.expand(["legacy flag", "rbac deny row"])+ def test_a_private_project_does_not_block_the_wiki(self, representation, _flag) -> None:+ # Both representations of a private project used to refuse enablement+ # outright, which locked out every organization that had restricted one.+ if representation == "legacy flag":+ self.team.access_control = True+ self.team.save()+ else:+ AccessControl.objects.create(+ team=self.team,+ resource="project",+ resource_id=str(self.team.id),+ access_level="none",+ )- def test_enable_is_blocked_for_orgs_with_rbac_private_projects(self, _flag) -> None:- AccessControl.objects.create(- team=self.team,- resource="project",- resource_id=str(self.team.id),- access_level="none",- )- response = self.client.post(f"{self.base_url}/enable/")- assert response.status_code == 400- body = response.json()- assert body["code"] == "private_projects"- assert self.team.name in body["detail"]+ self._enable()++ assert self.client.get(f"{self.base_url}/tree/").status_code == 200def test_same_named_spaces_are_scoped_to_their_projects(self, _flag) -> None:with team_scope(self.team.id):@@ -680,17 +677,6 @@ class TestContextLayerAPI(APIBaseTest):assert response.status_code == 409assert "merge commits" in response.json()["detail"]- def test_wiki_goes_dark_when_a_project_becomes_private(self, _flag) -> None:- self._enable()- assert self.client.get(f"{self.base_url}/tree/").status_code == 200-- self.team.access_control = True- self.team.save()-- assert self.client.get(f"{self.base_url}/tree/").status_code == 403- assert self.client.get(f"{self.base_url}/pages/", {"path": "AGENTS.md"}).status_code == 403- assert self.client.get(f"{self.base_url}/export/").status_code == 403-def test_export_returns_a_download_url(self, _flag) -> None:head = self._enable()response = self.client.get(f"{self.base_url}/export/")diff --git a/products/context_layer/backend/test/test_facade.py b/products/context_layer/backend/test/test_facade.pyindex 6859c5a6125f..7cf5a6bc3057 100644--- a/products/context_layer/backend/test/test_facade.py+++ b/products/context_layer/backend/test/test_facade.py@@ -41,9 +41,3 @@ class TestContextLayerFacade(BaseTest):def test_get_sandbox_mount_is_none_without_wiki(self) -> None:assert facade.get_sandbox_mount(self.organization.id) is None-- def test_get_sandbox_mount_goes_dark_with_private_projects(self) -> None:- store.initialize_repo(self.organization.id)- self.team.access_control = True- self.team.save()- assert facade.get_sandbox_mount(self.organization.id) is None