Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(context-layer): add the org context wiki git bundle store (#84387)

Peter Kirkham90d93c81c7ee
diff --git a/.semgrep/rules/security/idor-team-scoped-models.yaml b/.semgrep/rules/security/idor-team-scoped-models.yaml
index ac4376bb0bf5..6e9a3d210e9b 100644
--- a/.semgrep/rules/security/idor-team-scoped-models.yaml
+++ b/.semgrep/rules/security/idor-team-scoped-models.yaml
@@ -830,6 +830,7 @@ rules:
|BillingAlertEvaluationClaim
|BillingAlertEvent
|CIMDVerificationToken
+ |ContextLayerConfig
|IdentityProviderConfig
|LegalDocument
|ManagedWarehouseSourceLifecycle
@@ -902,6 +903,7 @@ rules:
|BillingAlertEvaluationClaim
|BillingAlertEvent
|CIMDVerificationToken
+ |ContextLayerConfig
|IdentityProviderConfig
|LegalDocument
|ManagedWarehouseSourceLifecycle
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 61aa108261ba..6078c42160c3 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -2664,6 +2664,8 @@ importers:
specifier: 'catalog:'
version: 0.2.4([email protected](patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected]))
+ products/context_layer: {}
+
products/conversations:
dependencies:
'@posthog/brand':
diff --git a/posthog/settings/web.py b/posthog/settings/web.py
index 4b546a41f669..98d638c59032 100644
--- a/posthog/settings/web.py
+++ b/posthog/settings/web.py
@@ -78,6 +78,7 @@ PRODUCTS_APPS = [
"products.review_hog.backend.apps.ReviewHogConfig",
"products.logs.backend.apps.LogsConfig",
"products.billing_alerts.backend.apps.BillingAlertsConfig",
+ "products.context_layer.backend.apps.ContextLayerAppConfig",
"products.tracing.backend.apps.TracingConfig",
"products.metrics.backend.apps.MetricsConfig",
"products.apm.backend.apps.ApmConfig",
diff --git a/products/context_layer/README.md b/products/context_layer/README.md
new file mode 100644
index 000000000000..b19b82c9b818
--- /dev/null
+++ b/products/context_layer/README.md
@@ -0,0 +1,28 @@
+# Context layer
+
+An org-wide Markdown wiki in a Git repository, hosted by PostHog, mounted into agent sandboxes, and maintained by nightly dreaming agents. Specified in RFC 1233.
+
+## Store
+
+Each organization gets one Git repo of Markdown, serialized as a `git bundle` in PostHog object storage:
+
+- Bundle location: `context_layer/<organization_id>/bundles/<head_sha>.bundle` (`OBJECT_STORAGE_*` settings).
+- Head pointer: `ContextLayerConfig.head_sha` in Postgres, updated with a compare-and-swap so a lost race is explicit. The bundle for the new head is uploaded before the CAS, so a failed CAS never leaves a dangling pointer.
+- 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.
+
+## Default structure
+
+Scaffolded at enablement and enforced by the linter (`backend/repo_lint.py`, also copied into the repo as `scripts/lint`):
+
+```text
+AGENTS.md map of the wiki + usage guardrails (agent-evolvable)
+CLAUDE.md symlink -> AGENTS.md, for Claude-native harnesses
+org/ mission, ICP, personas, teams, business model
+areas/<area>.md one hub page per product area
+decisions/<date>-<slug>.md product decisions: what, why, who, source
+channels/<slug>.md one page per Desktop channel (frontmatter: channel_id)
+scripts/lint the structure linter (also run server-side at land)
+```
+
+The root file is AGENTS.md because the layer must work for every model and harness; the CLAUDE.md symlink covers Claude-native tooling.
diff --git a/products/context_layer/__init__.py b/products/context_layer/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/context_layer/backend/__init__.py b/products/context_layer/backend/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/context_layer/backend/apps.py b/products/context_layer/backend/apps.py
new file mode 100644
index 000000000000..17839de74478
--- /dev/null
+++ b/products/context_layer/backend/apps.py
@@ -0,0 +1,8 @@
+from django.apps import AppConfig
+
+
+class ContextLayerAppConfig(AppConfig):
+ default_auto_field = "django.db.models.BigAutoField"
+ name = "products.context_layer.backend"
+ label = "context_layer"
+ verbose_name = "Context layer"
diff --git a/products/context_layer/backend/migrations/0001_initial.py b/products/context_layer/backend/migrations/0001_initial.py
new file mode 100644
index 000000000000..1375b1448a1c
--- /dev/null
+++ b/products/context_layer/backend/migrations/0001_initial.py
@@ -0,0 +1,59 @@
+# Generated by Django 5.2.17 on 2026-08-18 12:36
+
+import django.db.models.deletion
+from django.conf import settings
+from django.db import migrations, models
+
+import posthog.uuidt
+
+
+class Migration(migrations.Migration):
+ initial = True
+
+ dependencies = [
+ ("posthog", "1305_alter_identityproviderconfig_saml_relay_state_and_more"),
+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name="ContextLayerConfig",
+ fields=[
+ (
+ "id",
+ models.UUIDField(
+ default=posthog.uuidt.uuid7,
+ editable=False,
+ primary_key=True,
+ serialize=False,
+ ),
+ ),
+ ("head_sha", models.CharField(max_length=64)),
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ ("updated_at", models.DateTimeField(auto_now=True)),
+ (
+ "created_by",
+ models.ForeignKey(
+ blank=True,
+ db_constraint=False,
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ related_name="+",
+ to=settings.AUTH_USER_MODEL,
+ ),
+ ),
+ (
+ "organization",
+ models.OneToOneField(
+ db_constraint=False,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="+",
+ to="posthog.organization",
+ ),
+ ),
+ ],
+ options={
+ "db_table": "context_layer_config",
+ },
+ ),
+ ]
diff --git a/products/context_layer/backend/migrations/__init__.py b/products/context_layer/backend/migrations/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/context_layer/backend/migrations/max_migration.txt b/products/context_layer/backend/migrations/max_migration.txt
new file mode 100644
index 000000000000..cbab66dde92a
--- /dev/null
+++ b/products/context_layer/backend/migrations/max_migration.txt
@@ -0,0 +1 @@
+0001_initial
diff --git a/products/context_layer/backend/models.py b/products/context_layer/backend/models.py
new file mode 100644
index 000000000000..2597df907f26
--- /dev/null
+++ b/products/context_layer/backend/models.py
@@ -0,0 +1,34 @@
+from django.db import models
+
+from posthog.models.utils import uuid7
+
+
+class ContextLayerConfig(models.Model):
+ """One row per organization with the context layer enabled.
+
+ `head_sha` is the compare-and-swap pointer to the current repo bundle in
+ object storage; every landing writer updates it with
+ `UPDATE ... WHERE head_sha = <expected>` so a lost race is explicit.
+ """
+
+ id = models.UUIDField(primary_key=True, default=uuid7, editable=False)
+ organization = models.OneToOneField(
+ "posthog.Organization",
+ on_delete=models.CASCADE,
+ related_name="+",
+ db_constraint=False,
+ )
+ head_sha = models.CharField(max_length=64)
+ created_by = models.ForeignKey(
+ "posthog.User",
+ on_delete=models.SET_NULL,
+ null=True,
+ blank=True,
+ related_name="+",
+ db_constraint=False,
+ )
+ created_at = models.DateTimeField(auto_now_add=True)
+ updated_at = models.DateTimeField(auto_now=True)
+
+ class Meta:
+ db_table = "context_layer_config"
diff --git a/products/context_layer/backend/repo_lint.py b/products/context_layer/backend/repo_lint.py
new file mode 100644
index 000000000000..7ef0a1add132
--- /dev/null
+++ b/products/context_layer/backend/repo_lint.py
@@ -0,0 +1,250 @@
+#!/usr/bin/env python3
+"""Structure linter for a context layer wiki checkout."""
+
+from __future__ import annotations
+
+import re
+import sys
+import subprocess
+from collections import Counter
+from datetime import UTC, date, datetime, timedelta
+from pathlib import Path, PurePosixPath
+
+ALLOWED_ROOT_FILES = {"AGENTS.md", "CLAUDE.md", "index.md"}
+ALLOWED_DIRECTORIES = {"org", "areas", "decisions", "channels", "scripts"}
+MARKDOWN_DIRECTORIES = {"org", "areas", "decisions", "channels"}
+MAX_FILE_BYTES = 16_000
+DECISION_FILE_RE = re.compile(r"^\d{4}-\d{2}-\d{2}-[a-z0-9][a-z0-9-]*\.md$")
+WIKILINK_RE = re.compile(r"\[\[([^\[\]\n]+)\]\]")
+MALFORMED_WIKILINK_RE = re.compile(r"\[\[|\]\]")
+H1_RE = re.compile(r"^#\s+(.+?)\s*$", re.MULTILINE)
+DISAGREEMENT_RE = re.compile(r"^.*\*\*Disagreement:\*\*.*$", re.MULTILINE)
+FRONTMATTER_DELIMITER = "---"
+ALLOWED_STATUSES = {"active", "superseded", "historical"}
+REQUIRED_AGENTS_FRAGMENTS = (
+ "## Admission test",
+ "A fact enters the wiki only if it changes a durable fact, decision, priority, ownership, reusable definition, constraint, or an evidenced recurring pattern.",
+ "External systems remain authoritative",
+ "never edit `index.md`",
+)
+
+
+def _page_paths(root: Path) -> list[Path]:
+ return [
+ path
+ for directory in MARKDOWN_DIRECTORIES
+ for path in sorted((root / directory).rglob("*.md"))
+ if path.is_file() and not path.is_symlink()
+ ]
+
+
+def _wikilink_target(raw_target: str) -> str | None:
+ target = raw_target.split("|", 1)[0].split("#", 1)[0].strip().removesuffix(".md")
+ path = PurePosixPath(target)
+ if not target or path.is_absolute() or ".." in path.parts or target.startswith("."):
+ return None
+ return path.as_posix()
+
+
+def lint_repo(root: Path | str, *, pin_scripts: bool = True) -> list[str]:
+ root = Path(root)
+ errors: list[str] = []
+ agents_md = root / "AGENTS.md"
+ if not agents_md.is_file() or agents_md.is_symlink():
+ errors.append("AGENTS.md must exist at the repo root as a regular file")
+ else:
+ agents_text = agents_md.read_text(encoding="utf-8", errors="replace")
+ for fragment in REQUIRED_AGENTS_FRAGMENTS:
+ if fragment not in agents_text:
+ errors.append(f"AGENTS.md: required guidance is missing: {fragment}")
+
+ claude_md = root / "CLAUDE.md"
+ if not claude_md.is_symlink() or claude_md.resolve() != agents_md.resolve():
+ errors.append("CLAUDE.md must be a symlink to AGENTS.md")
+
+ for entry in sorted(root.iterdir()):
+ if entry.name == ".git":
+ continue
+ if entry.is_dir() and not entry.is_symlink():
+ if entry.name not in ALLOWED_DIRECTORIES:
+ errors.append(f"{entry.name}/: only {', '.join(sorted(ALLOWED_DIRECTORIES))} are allowed at the root")
+ elif entry.name not in ALLOWED_ROOT_FILES:
+ errors.append(f"{entry.name}: only {', '.join(sorted(ALLOWED_ROOT_FILES))} are allowed as root files")
+
+ titles: dict[str, Path] = {}
+ for directory in sorted(MARKDOWN_DIRECTORIES):
+ errors.extend(_lint_markdown_directory(root, directory, titles))
+ errors.extend(_lint_scripts_directory(root, pin_scripts=pin_scripts))
+ return errors
+
+
+def _lint_markdown_directory(root: Path, directory: str, titles: dict[str, Path]) -> list[str]:
+ base = root / directory
+ if not base.is_dir():
+ return []
+ errors: list[str] = []
+ for path in sorted(base.rglob("*")):
+ relative = path.relative_to(root)
+ if path.is_symlink():
+ errors.append(f"{relative}: symlinks are only allowed for the root CLAUDE.md")
+ continue
+ if path.is_dir():
+ continue
+ if path.suffix != ".md":
+ errors.append(f"{relative}: only Markdown pages are allowed under {directory}/")
+ continue
+ if directory == "decisions" and not DECISION_FILE_RE.fullmatch(path.name):
+ errors.append(f"{relative}: decision pages must be named <YYYY-MM-DD>-<slug>.md")
+ fields = _frontmatter(path)
+ if directory == "channels" and not fields.get("channel_id"):
+ errors.append(f"{relative}: channel pages need a non-empty `channel_id` in their frontmatter")
+ if not fields.get("summary") or "\n" in fields.get("summary", ""):
+ errors.append(f"{relative}: frontmatter needs a one-line `summary`")
+ status = fields.get("status")
+ if status not in ALLOWED_STATUSES:
+ errors.append(f"{relative}: frontmatter `status` must be active, superseded, or historical")
+ review_after = fields.get("review_after")
+ if review_after:
+ try:
+ date.fromisoformat(review_after)
+ except ValueError:
+ errors.append(f"{relative}: frontmatter `review_after` must be an ISO date")
+ if directory == "decisions" and not fields.get("sources"):
+ errors.append(f"{relative}: decision pages need non-empty `sources` frontmatter")
+ text = path.read_text(encoding="utf-8", errors="replace")
+ links, malformed = _links(text)
+ if malformed:
+ errors.append(f"{relative}: contains a malformed or escaping wikilink")
+ if status == "superseded" and not any((root / f"{target}.md").is_file() for target in links):
+ errors.append(f"{relative}: superseded pages must wikilink an existing replacement")
+ title_match = H1_RE.search(text)
+ if title_match:
+ normalized = re.sub(r"[^a-z0-9]+", " ", title_match.group(1).casefold()).strip()
+ if normalized in titles:
+ errors.append(f"{relative}: duplicates the normalized title in {titles[normalized].relative_to(root)}")
+ else:
+ titles[normalized] = path
+ return errors
+
+
+def _links(text: str) -> tuple[list[str], bool]:
+ matches = list(WIKILINK_RE.finditer(text))
+ targets = [_wikilink_target(match.group(1)) for match in matches]
+ remainder = WIKILINK_RE.sub("", text)
+ return [target for target in targets if target], any(target is None for target in targets) or bool(
+ MALFORMED_WIKILINK_RE.search(remainder)
+ )
+
+
+def report_repo(root: Path | str) -> list[str]:
+ root = Path(root)
+ pages = _page_paths(root)
+ targets_by_page: dict[Path, list[str]] = {}
+ inbound: Counter[str] = Counter()
+ for path in pages:
+ targets, _ = _links(path.read_text(encoding="utf-8", errors="replace"))
+ targets_by_page[path] = targets
+ inbound.update(targets)
+ findings: list[str] = []
+ today = datetime.now(UTC).date()
+ for path in pages:
+ relative = path.relative_to(root).as_posix()
+ target = relative.removesuffix(".md")
+ fields = _frontmatter(path)
+ age = _git_age(root, relative)
+ if age is not None and age > timedelta(days=90):
+ findings.append(f"stale: {relative}: last changed {age.days} days ago")
+ review_after = fields.get("review_after")
+ if fields.get("status") == "active" and review_after:
+ try:
+ if date.fromisoformat(review_after) < today:
+ findings.append(f"past_review: {relative}: review_after {review_after} has passed")
+ except ValueError:
+ pass
+ if not inbound[target]:
+ findings.append(f"orphan: {relative}: no page links here")
+ if path.stat().st_size > MAX_FILE_BYTES:
+ findings.append(f"oversized: {relative}: exceeds {MAX_FILE_BYTES // 1000} KB")
+ if path.parts[-2] != "decisions" and not fields.get("sources"):
+ findings.append(f"missing_sources: {relative}: no sources recorded")
+ for marker in DISAGREEMENT_RE.findall(path.read_text(encoding="utf-8", errors="replace")):
+ findings.append(f"disagreement: {relative}: {marker.strip()}")
+ existing = {path.relative_to(root).as_posix().removesuffix(".md") for path in pages}
+ ghost_counts = Counter(
+ target for targets in targets_by_page.values() for target in targets if target not in existing
+ )
+ for target, count in sorted(ghost_counts.items()):
+ findings.append(f"ghost_link: {target}.md: referenced by {count} page(s)")
+ return findings
+
+
+def _git_age(root: Path, relative: str) -> timedelta | None:
+ result = subprocess.run(
+ ["git", "log", "-1", "--format=%ct", "--", relative], cwd=root, capture_output=True, text=True, check=False
+ )
+ if not result.stdout.strip():
+ return None
+ changed = datetime.fromtimestamp(int(result.stdout.strip()), tz=UTC)
+ return datetime.now(UTC) - changed
+
+
+def _canonical_scripts() -> dict[str, str]:
+ return {"lint": Path(__file__).read_text(encoding="utf-8")}
+
+
+def _lint_scripts_directory(root: Path, *, pin_scripts: bool = True) -> list[str]:
+ base = root / "scripts"
+ if not base.is_dir():
+ return []
+ canonical = _canonical_scripts()
+ errors: list[str] = []
+ for path in sorted(base.rglob("*")):
+ relative = path.relative_to(root)
+ if path.is_symlink():
+ errors.append(f"{relative}: symlinks are only allowed for the root CLAUDE.md")
+ elif path.parent != base or not path.is_file() or path.name not in canonical:
+ errors.append(f"{relative}: scripts/ may only contain {', '.join(sorted(canonical))}")
+ elif pin_scripts and path.read_text(encoding="utf-8", errors="replace") != canonical[path.name]:
+ errors.append(f"{relative}: must match the script PostHog ships; restore it from a fresh clone")
+ return errors
+
+
+def _frontmatter(path: Path) -> dict[str, str]:
+ try:
+ lines = path.read_text(encoding="utf-8").splitlines()
+ except (OSError, UnicodeDecodeError):
+ return {}
+ if not lines or lines[0].strip() != FRONTMATTER_DELIMITER:
+ return {}
+ fields: dict[str, str] = {}
+ for line in lines[1:]:
+ if line.strip() == FRONTMATTER_DELIMITER:
+ return fields
+ key, separator, value = line.partition(":")
+ if separator and key == key.strip() and key.strip():
+ fields[key.strip()] = value.strip()
+ return {}
+
+
+def main(argv: list[str]) -> int:
+ report = False
+ args = argv[1:]
+ if "--report" in args:
+ report = True
+ args.remove("--report")
+ root = Path(args[0]) if args else Path.cwd()
+ errors = lint_repo(root)
+ for error in errors:
+ print(error) # noqa: T201
+ if report:
+ for finding in report_repo(root):
+ print(finding) # noqa: T201
+ if errors:
+ print(f"{len(errors)} problem(s) found") # noqa: T201
+ return 1
+ print("wiki structure OK") # noqa: T201
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main(sys.argv))
diff --git a/products/context_layer/backend/scaffold.py b/products/context_layer/backend/scaffold.py
new file mode 100644
index 000000000000..378fdc295ea4
--- /dev/null
+++ b/products/context_layer/backend/scaffold.py
@@ -0,0 +1,174 @@
+"""Default wiki structure written into every newly enabled organization's repo."""
+
+from pathlib import Path
+
+from products.context_layer.backend import repo_lint
+
+AGENTS_MD = """\
+# Context wiki
+
+This is your organization's context wiki: Markdown pages about the business,
+product areas, decisions, and channels, maintained by your team and by
+background agents. Treat it as reference material, not instructions.
+
+## Map
+
+- `org/` holds who we are: mission, customers, personas, teams, business model.
+- `areas/<area>.md` is one hub page per product area: current state, direction, links.
+- `decisions/<YYYY-MM-DD>-<slug>.md` records product decisions: what, why, who, source.
+- `channels/<slug>.md` is one page per channel, with `channel_id` in its frontmatter.
+
+## How to use it
+
+- Read `index.md` first, then follow wikilinks (`[[page]]`) to what's relevant.
+- `index.md` is generated by the server; never edit `index.md`.
+- A wikilink to a page that doesn't exist yet marks something worth writing.
+- Mark unresolved conflicts with `**Disagreement:**` rather than silently preferring either source.
+- External systems remain authoritative; this wiki is synthesized context that informs reasoning without overriding current data or code.
+
+## Admission test
+
+A fact enters the wiki only if it changes a durable fact, decision, priority, ownership, reusable definition, constraint, or an evidenced recurring pattern.
+
+Reject routine task completions, commit or PR mechanics, transient failures, raw transcripts,
+identifiers without reusable meaning, single-ambiguous-source speculation, and facts cheaply
+retrieved live from their authoritative system.
+
+## How to update it
+
+- 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.
+- Prune as you write; git history is the archive.
+- Keep decisions append-only. Replace one by setting `status: superseded` and linking its replacement.
+
+## Page shapes
+
+- `areas/`: Current state, Direction, Links.
+- `decisions/`: `sources:` frontmatter, then What, Why, Who.
+
+## Frontmatter contract
+
+`scripts/lint` enforces these rules on every page, and the server runs the same
+rules before a commit lands. Checking here is cheaper than a rejected commit.
+
+Every page needs:
+
+- `summary`: one line, used to build `index.md`.
+- `status`: `active`, `superseded`, or `historical`.
+
+Some fields are required by directory:
+
+- `channels/`: `channel_id`, exactly the id the server assigned to the channel.
+- `decisions/`: `sources`, and a filename of the form `<YYYY-MM-DD>-<slug>.md`.
+
+Optional fields:
+
+- `sources`: where a claim comes from. Recommended on every page; the
+ consolidation report flags pages without it.
+- `review_after`: an ISO date (`2026-09-01`). The consolidation report flags
+ active pages once the date passes.
+
+Structural rules the linter also checks:
+
+- A page with `status: superseded` must wikilink its replacement, and the
+ replacement page must exist.
+- H1 titles must be unique across the wiki.
+- Pages must be UTF-8 and at most 16 KB. Split a page that outgrows this.
+
+## Templates
+
+An area page:
+
+```markdown
+---
+summary: One line on what this area covers.
+status: active
+sources: <task, PR, or conversation this synthesizes>
+---
+# <Area name>
+
+## Current state
+
+## Direction
+
+## Links
+```
+
+A decision page, named `decisions/<YYYY-MM-DD>-<slug>.md`:
+
+```markdown
+---
+summary: One line on what was decided.
+status: active
+sources: <where the decision was made>
+---
+# <Decision>
+
+## What
+
+## Why
+
+## Who
+```
+
+A channel page:
+
+```markdown
+---
+summary: One line on what this channel works on.
+status: active
+channel_id: <the channel's id, assigned by the server>
+---
+# <Channel name>
+```
+"""
+
+ORG_OVERVIEW_MD = """\
+---
+summary: What the organization does, for whom, and how it operates.
+status: active
+sources: initial-scaffold
+---
+# Organization overview
+
+What this organization does, for whom, and how it makes money. Fill in what you
+know and link out with wikilinks; pages that don't exist yet are fine to link.
+
+- Mission:
+- Customers and personas:
+- Business model:
+- Teams:
+"""
+
+
+def generate_index(root: Path) -> str:
+ grouped: dict[str, list[tuple[str, str]]] = {}
+ for directory in sorted(repo_lint.MARKDOWN_DIRECTORIES):
+ for path in sorted((root / directory).rglob("*.md")):
+ summary = repo_lint._frontmatter(path).get("summary")
+ if summary:
+ relative = path.relative_to(root).as_posix().removesuffix(".md")
+ grouped.setdefault(directory, []).append((relative, summary))
+ lines = ["# Context wiki index", ""]
+ for directory, pages in grouped.items():
+ lines.extend((f"## {directory.title()}", ""))
+ lines.extend(f"- [[{path}]] — {summary}" for path, summary in pages)
+ lines.append("")
+ return "\n".join(lines)
+
+
+def write_default_structure(root: Path) -> None:
+ (root / "AGENTS.md").write_text(AGENTS_MD, encoding="utf-8")
+ (root / "CLAUDE.md").symlink_to("AGENTS.md")
+ # areas/, decisions/, and channels/ appear with their first page; git does
+ # not track empty directories, so scaffolding them would not survive a clone.
+ (root / "org").mkdir(exist_ok=True)
+ (root / "scripts").mkdir(exist_ok=True)
+ (root / "org" / "overview.md").write_text(ORG_OVERVIEW_MD, encoding="utf-8")
+ (root / "index.md").write_text(generate_index(root), encoding="utf-8")
+ # Ship the server's linter into the repo so agents run the exact rules the
+ # server enforces at land time. repo_lint stays stdlib-only for this reason.
+ lint_script = root / "scripts" / "lint"
+ lint_script.write_text(Path(repo_lint.__file__).read_text(encoding="utf-8"), encoding="utf-8")
+ lint_script.chmod(0o755)
diff --git a/products/context_layer/backend/store.py b/products/context_layer/backend/store.py
new file mode 100644
index 000000000000..c9466166549f
--- /dev/null
+++ b/products/context_layer/backend/store.py
@@ -0,0 +1,399 @@
+"""Git bundle store for organization context wikis.
+
+One bare Git repo per organization, serialized as a `git bundle` in object
+storage, with the current head sha in Postgres (`ContextLayerConfig.head_sha`)
+as a compare-and-swap pointer. Every writer follows the same protocol: acquire
+the per-org Redis lock, download the bundle, clone to tmp, apply commits, lint,
+upload the new bundle, CAS the head, release. Readers never take the lock.
+"""
+
+from __future__ import annotations
+
+import uuid
+import shutil
+import tempfile
+import threading
+import subprocess
+from collections.abc import Callable, Iterator
+from contextlib import contextmanager
+from pathlib import Path
+
+import structlog
+from redis.exceptions import RedisError
+
+from posthog.dataclasses import frozen
+from posthog.redis import get_client
+from posthog.storage import object_storage
+
+from products.context_layer.backend import repo_lint
+from products.context_layer.backend.models import ContextLayerConfig
+from products.context_layer.backend.repo_lint import lint_repo
+from products.context_layer.backend.scaffold import write_default_structure
+
+logger = structlog.get_logger(__name__)
+
+BUNDLE_KEY_PREFIX = "context_layer"
+DEFAULT_BRANCH = "main"
+LOCK_TTL_MS = 60_000
+LOCK_RENEW_INTERVAL_SECONDS = 20.0
+GIT_TIMEOUT_SECONDS = 60
+COMMITTER_NAME = "PostHog Context Layer"
+COMMITTER_EMAIL = "[email protected]"
+
+
+class ContextLayerStoreError(Exception):
+ pass
+
+
+class RepoNotFoundError(ContextLayerStoreError):
+ """The organization has no context layer repo (no config row or no bundle)."""
+
+
+class RepoLockUnavailableError(ContextLayerStoreError):
+ """Another writer holds the per-org lock; retry later."""
+
+
+class HeadMovedError(ContextLayerStoreError):
+ """The head sha moved underneath a landing writer, twice."""
+
+
+class PurgeIncompleteError(ContextLayerStoreError):
+ """A purge rewrote the history but could not remove every old bundle, so
+ sensitive content may still be readable in object storage."""
+
+
+class LintFailedError(ContextLayerStoreError):
+ def __init__(self, errors: list[str]) -> None:
+ super().__init__("wiki structure lint failed: " + "; ".join(errors))
+ self.errors = errors
+
+
+@frozen
+class RepoCheckout:
+ """A temporary working clone of an organization's wiki."""
+
+ path: Path
+ head_sha: str
+
+
+@frozen
+class CommitAuthor:
+ name: str
+ email: str
+
+
+SYSTEM_AUTHOR = CommitAuthor(name=COMMITTER_NAME, email=COMMITTER_EMAIL)
+
+
+def bundle_prefix(organization_id: uuid.UUID | str) -> str:
+ return f"{BUNDLE_KEY_PREFIX}/{organization_id}/bundles/"
+
+
+def bundle_key(organization_id: uuid.UUID | str, head_sha: str) -> str:
+ return f"{bundle_prefix(organization_id)}{head_sha}.bundle"
+
+
+def _lock_key(organization_id: uuid.UUID | str) -> str:
+ return f"context_layer:repo:{organization_id}"
+
+
+# Renewal and release must check ownership and act atomically: after TTL expiry
+# another writer may hold the key, and a plain get-then-expire/delete could
+# extend or drop that writer's lock. Same scripts as posthog/api/query_coalescer.py.
+_RENEW_LOCK_SCRIPT = """
+if redis.call("get", KEYS[1]) == ARGV[1] then
+ return redis.call("pexpire", KEYS[1], ARGV[2])
+end
+return 0
+"""
+
+_RELEASE_LOCK_SCRIPT = """
+if redis.call("get", KEYS[1]) == ARGV[1] then
+ return redis.call("del", KEYS[1])
+end
+return 0
+"""
+
+
+@contextmanager
+def repo_writer_lock(organization_id: uuid.UUID | str) -> Iterator[None]:
+ """Per-org writer lock: SET NX PX with a heartbeat, so a crashed writer
+ frees the org within `LOCK_TTL_MS` while a slow live writer keeps it."""
+ client = get_client()
+ key = _lock_key(organization_id)
+ token = uuid.uuid4().hex
+ if not client.set(key, token, nx=True, px=LOCK_TTL_MS):
+ raise RepoLockUnavailableError(f"another writer holds the context layer lock for {organization_id}")
+
+ stop = threading.Event()
+
+ def renew() -> None:
+ while not stop.wait(LOCK_RENEW_INTERVAL_SECONDS):
+ try:
+ client.eval(_RENEW_LOCK_SCRIPT, 1, key, token, LOCK_TTL_MS)
+ except RedisError:
+ break
+
+ heartbeat = threading.Thread(target=renew, name=f"context-layer-lock-{organization_id}", daemon=True)
+ heartbeat.start()
+ try:
+ yield
+ finally:
+ stop.set()
+ heartbeat.join(timeout=1)
+ # The write has already landed by the time we release; a Redis error here
+ # must not mask the result. The TTL frees the key if Redis stays down.
+ try:
+ client.eval(_RELEASE_LOCK_SCRIPT, 1, key, token)
+ except RedisError:
+ logger.warning("context_layer.repo_writer_lock.release_failed", organization_id=str(organization_id))
+
+
+def _run_git(args: list[str], cwd: Path) -> str:
+ result = subprocess.run(
+ [
+ "git",
+ "-c",
+ f"user.name={COMMITTER_NAME}",
+ "-c",
+ f"user.email={COMMITTER_EMAIL}",
+ "-c",
+ "commit.gpgsign=false",
+ *args,
+ ],
+ cwd=cwd,
+ capture_output=True,
+ text=True,
+ timeout=GIT_TIMEOUT_SECONDS,
+ )
+ if result.returncode != 0:
+ raise ContextLayerStoreError(f"git {args[0]} failed: {result.stderr.strip()}")
+ return result.stdout.strip()
+
+
+def _download_bundle(organization_id: uuid.UUID | str, head_sha: str, into: Path) -> Path:
+ bundle_bytes = object_storage.read_bytes(bundle_key(organization_id, head_sha), missing_ok=True)
+ if bundle_bytes is None:
+ raise RepoNotFoundError(f"no bundle at head {head_sha} for organization {organization_id}")
+ bundle_path = into / "repo.bundle"
+ bundle_path.write_bytes(bundle_bytes)
+ return bundle_path
+
+
+def _upload_bundle(organization_id: uuid.UUID | str, head_sha: str, workdir: Path) -> None:
+ bundle_path = workdir.parent / f"{head_sha}.bundle"
+ _run_git(["bundle", "create", str(bundle_path), "--all"], cwd=workdir)
+ object_storage.write_from_file(bundle_key(organization_id, head_sha), str(bundle_path))
+
+
+def _prune_bundles_except(organization_id: uuid.UUID | str, keep_head: str) -> None:
+ """Delete every stored bundle for the organization except `keep_head`'s.
+
+ Each landed head keeps its own bundle, so old bundles hold the history a
+ purge is meant to erase. This must run while holding the writer lock, with
+ `keep_head` read under that lock, so it never deletes the live head's bundle.
+ Anything short of a clean listing and delete raises, so a purge never reports
+ success while old bundles remain readable.
+ """
+ keep_key = bundle_key(organization_id, keep_head)
+ existing = object_storage.list_objects(bundle_prefix(organization_id))
+ if existing is None:
+ raise PurgeIncompleteError(f"could not list bundles to purge for organization {organization_id}")
+ stale = [key for key in existing if key != keep_key]
+ if not stale:
+ return
+ failed = object_storage.delete_objects(stale)
+ if failed:
+ raise PurgeIncompleteError(
+ f"could not delete {len(failed)} old bundle(s) while purging organization {organization_id}"
+ )
+
+
+def _prune_bundles_best_effort(organization_id: uuid.UUID | str, keep_heads: set[str]) -> None:
+ """Delete bundles superseded by a landing, keeping the new and previous heads.
+
+ The previous head stays so a reader that fetched the old pointer just before
+ the CAS can still download it; the next landing removes it. Cleanup never
+ fails the write — a missed prune only costs storage until the next landing.
+ """
+ keep_keys = {bundle_key(organization_id, head) for head in keep_heads}
+ try:
+ existing = object_storage.list_objects(bundle_prefix(organization_id)) or []
+ stale = [key for key in existing if key not in keep_keys]
+ if stale:
+ object_storage.delete_objects(stale)
+ except Exception:
+ logger.exception("context_layer.prune_bundles_failed", organization_id=str(organization_id))
+
+
+def _clone_from_bundle(bundle_path: Path, workdir: Path) -> None:
+ _run_git(["clone", "--quiet", str(bundle_path), str(workdir)], cwd=bundle_path.parent)
+ _run_git(["checkout", "--quiet", DEFAULT_BRANCH], cwd=workdir)
+
+
+def _commit_all(workdir: Path, message: str, author: CommitAuthor) -> str:
+ _run_git(["add", "--all"], cwd=workdir)
+ _run_git(["commit", "--quiet", "--author", f"{author.name} <{author.email}>", "-m", message], cwd=workdir)
+ return _run_git(["rev-parse", "HEAD"], cwd=workdir)
+
+
+def _has_changes(workdir: Path) -> bool:
+ return bool(_run_git(["status", "--porcelain"], cwd=workdir))
+
+
+def _refresh_canonical_scripts(workdir: Path) -> None:
+ """Rewrite scripts/ to the content PostHog currently ships.
+
+ Landing is the upgrade point: a wiki scaffolded under an older script
+ version (or carrying a tampered copy) gets the canonical scripts restored
+ as part of the landing commit instead of failing the pinned lint forever.
+ """
+ scripts_dir = workdir / "scripts"
+ if scripts_dir.is_symlink() or not scripts_dir.is_dir():
+ return
+ for name, content in repo_lint._canonical_scripts().items():
+ target = scripts_dir / name
+ if target.is_symlink():
+ # Never write through a link: a checkout could point scripts/lint at
+ # a path writable by the service, and write_text follows symlinks.
+ target.unlink()
+ if not target.exists() or target.read_text(encoding="utf-8", errors="replace") != content:
+ target.write_text(content, encoding="utf-8")
+ target.chmod(0o755)
+
+
+def _lint_or_raise(workdir: Path) -> None:
+ errors = lint_repo(workdir)
+ if errors:
+ raise LintFailedError(errors)
+
+
+def get_config(organization_id: uuid.UUID | str) -> ContextLayerConfig:
+ try:
+ return ContextLayerConfig.objects.get(organization_id=organization_id)
+ except ContextLayerConfig.DoesNotExist:
+ raise RepoNotFoundError(f"organization {organization_id} has no context layer") from None
+
+
+@contextmanager
+def checkout_repo(organization_id: uuid.UUID | str) -> Iterator[RepoCheckout]:
+ """Read-side checkout of the current head into a temporary working tree."""
+ config = get_config(organization_id)
+ with tempfile.TemporaryDirectory(prefix="context-layer-", ignore_cleanup_errors=True) as tmp:
+ tmpdir = Path(tmp)
+ bundle_path = _download_bundle(organization_id, config.head_sha, tmpdir)
+ workdir = tmpdir / "repo"
+ _clone_from_bundle(bundle_path, workdir)
+ yield RepoCheckout(path=workdir, head_sha=config.head_sha)
+
+
+def initialize_repo(
+ organization_id: uuid.UUID | str,
+ *,
+ created_by_id: int | None = None,
+) -> ContextLayerConfig:
+ """Create the organization's wiki with the default structure. Idempotent:
+ an existing config is returned untouched."""
+ existing = ContextLayerConfig.objects.filter(organization_id=organization_id).first()
+ if existing is not None:
+ return existing
+
+ with (
+ repo_writer_lock(organization_id),
+ tempfile.TemporaryDirectory(prefix="context-layer-", ignore_cleanup_errors=True) as tmp,
+ ):
+ workdir = Path(tmp) / "repo"
+ workdir.mkdir()
+ _run_git(["init", "--quiet", "--initial-branch", DEFAULT_BRANCH, str(workdir)], cwd=Path(tmp))
+ write_default_structure(workdir)
+ _lint_or_raise(workdir)
+ head_sha = _commit_all(workdir, "Scaffold the context wiki", SYSTEM_AUTHOR)
+ _upload_bundle(organization_id, head_sha, workdir)
+ config, created = ContextLayerConfig.objects.get_or_create(
+ organization_id=organization_id,
+ defaults={"head_sha": head_sha, "created_by_id": created_by_id},
+ )
+ if not created:
+ logger.info("context_layer.initialize_repo.lost_create_race", organization_id=str(organization_id))
+ return config
+
+
+def apply_changes(
+ organization_id: uuid.UUID | str,
+ *,
+ message: str,
+ mutate: Callable[[Path], None],
+ author: CommitAuthor | None = None,
+) -> str:
+ """Run the writer protocol for a working-tree mutation and return the new head sha.
+
+ `mutate` receives the checkout path and edits files in place; the store
+ commits, lints, uploads, and lands the result. A no-op mutation returns the
+ current head without landing anything.
+ """
+ author = author or SYSTEM_AUTHOR
+ # All writers hold the per-org lock, so the CAS only loses when a previous
+ # writer's lock expired mid-land and its CAS raced ours. One retry re-reads
+ # the moved head and replays the mutation on top of it.
+ for attempt in (1, 2):
+ with repo_writer_lock(organization_id):
+ expected_head = get_config(organization_id).head_sha
+ with tempfile.TemporaryDirectory(prefix="context-layer-", ignore_cleanup_errors=True) as tmp:
+ tmpdir = Path(tmp)
+ bundle_path = _download_bundle(organization_id, expected_head, tmpdir)
+ workdir = tmpdir / "repo"
+ _clone_from_bundle(bundle_path, workdir)
+
+ mutate(workdir)
+ _refresh_canonical_scripts(workdir)
+ if not _has_changes(workdir):
+ return expected_head
+ _lint_or_raise(workdir)
+ new_head = _commit_all(workdir, message, author)
+ _upload_bundle(organization_id, new_head, workdir)
+
+ updated = ContextLayerConfig.objects.filter(
+ organization_id=organization_id, head_sha=expected_head
+ ).update(head_sha=new_head)
+ if updated:
+ _prune_bundles_best_effort(organization_id, {new_head, expected_head})
+ return new_head
+ logger.warning(
+ "context_layer.apply_changes.head_moved",
+ organization_id=str(organization_id),
+ expected_head=expected_head,
+ attempt=attempt,
+ )
+ raise HeadMovedError(f"head moved twice while landing changes for organization {organization_id}")
+
+
+def purge_repo_history(organization_id: uuid.UUID | str, *, message: str = "Purge wiki history") -> str:
+ """Rewrite the wiki to a single commit holding the current tree and delete
+ every old bundle, so no dropped history survives in object storage. The
+ escape hatch for sensitive content committed by mistake.
+
+ Raises `PurgeIncompleteError` if the rewrite lands but an old bundle cannot
+ be removed, so a caller never treats a partial purge as done.
+ """
+
+ def reinitialize_history(root: Path) -> None:
+ shutil.rmtree(root / ".git")
+ _run_git(["init", "--quiet", "--initial-branch", DEFAULT_BRANCH, str(root)], cwd=root)
+
+ apply_changes(organization_id, message=message, mutate=reinitialize_history)
+ # Re-take the lock and prune against the head as it stands now: another writer
+ # may have landed on top of the rewritten tree, and only the current head's
+ # bundle must survive.
+ with repo_writer_lock(organization_id):
+ head_sha = get_config(organization_id).head_sha
+ _prune_bundles_except(organization_id, head_sha)
+ return head_sha
+
+
+def get_bundle_presigned_url(organization_id: uuid.UUID | str, *, expiration_seconds: int = 300) -> str:
+ """Short-lived download URL for the current bundle, for sandbox mounts and export."""
+ config = get_config(organization_id)
+ url = object_storage.get_presigned_url(bundle_key(organization_id, config.head_sha), expiration=expiration_seconds)
+ if url is None:
+ raise ContextLayerStoreError(f"could not presign the bundle for organization {organization_id}")
+ return url
diff --git a/products/context_layer/backend/test/__init__.py b/products/context_layer/backend/test/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/context_layer/backend/test/test_repo_lint.py b/products/context_layer/backend/test/test_repo_lint.py
new file mode 100644
index 000000000000..46440ed3b7c5
--- /dev/null
+++ b/products/context_layer/backend/test/test_repo_lint.py
@@ -0,0 +1,125 @@
+import shutil
+import tempfile
+from collections.abc import Callable
+from pathlib import Path
+
+from django.test import SimpleTestCase
+
+from parameterized import parameterized
+
+from products.context_layer.backend.repo_lint import lint_repo, report_repo
+from products.context_layer.backend.scaffold import write_default_structure
+
+
+def _remove_agents_md(root: Path) -> None:
+ (root / "AGENTS.md").unlink()
+
+
+def _claude_md_regular_file(root: Path) -> None:
+ (root / "CLAUDE.md").unlink()
+ (root / "CLAUDE.md").write_text("not a symlink")
+
+
+def _rogue_root_file(root: Path) -> None:
+ (root / "notes.md").write_text("# notes")
+
+
+def _disallowed_root_directory(root: Path) -> None:
+ (root / "attachments").mkdir()
+ (root / "attachments" / "file.md").write_text("# file")
+
+
+def _non_markdown_page(root: Path) -> None:
+ (root / "areas").mkdir(exist_ok=True)
+ (root / "areas" / "dump.json").write_text("{}")
+
+
+def _misnamed_decision(root: Path) -> None:
+ (root / "decisions").mkdir(exist_ok=True)
+ (root / "decisions" / "pricing.md").write_text("# pricing")
+
+
+def _channel_page_without_channel_id(root: Path) -> None:
+ (root / "channels").mkdir(exist_ok=True)
+ (root / "channels" / "general.md").write_text("---\nowner: someone\n---\n# general")
+
+
+def _channel_page_with_empty_channel_id(root: Path) -> None:
+ (root / "channels").mkdir(exist_ok=True)
+ (root / "channels" / "general.md").write_text("---\nchannel_id: \n---\n# general")
+
+
+def _stray_symlink(root: Path) -> None:
+ (root / "areas").mkdir(exist_ok=True)
+ (root / "areas" / "alias.md").symlink_to("../AGENTS.md")
+
+
+def _oversized_page(root: Path) -> None:
+ (root / "areas").mkdir(exist_ok=True)
+ (root / "areas" / "huge.md").write_text(
+ "---\nsummary: Huge\nstatus: active\nsources: test\n---\n# Huge\n" + "x" * 16_001
+ )
+
+
+def _scripts_symlink(root: Path) -> None:
+ (root / "scripts" / "alias").symlink_to("/etc/hosts")
+
+
+def _scripts_extra_file(root: Path) -> None:
+ (root / "scripts" / "deploy.sh").write_text("#!/bin/sh\n")
+
+
+def _scripts_tampered_lint(root: Path) -> None:
+ lint = root / "scripts" / "lint"
+ lint.write_text(lint.read_text() + "\nimport os # smuggled\n")
+
+
+class TestRepoLint(SimpleTestCase):
+ def setUp(self) -> None:
+ super().setUp()
+ self.root = Path(tempfile.mkdtemp(prefix="context-layer-lint-"))
+ self.addCleanup(shutil.rmtree, self.root, ignore_errors=True)
+ write_default_structure(self.root)
+
+ def test_default_structure_is_clean(self) -> None:
+ assert lint_repo(self.root) == []
+
+ def test_valid_pages_in_every_directory_are_clean(self) -> None:
+ (self.root / "areas").mkdir()
+ (self.root / "areas" / "analytics.md").write_text(
+ "---\nsummary: Analytics\nstatus: active\nsources: test\n---\n# analytics"
+ )
+ (self.root / "decisions").mkdir()
+ (self.root / "decisions" / "2026-08-18-pricing-tiers.md").write_text(
+ "---\nsummary: Pricing\nstatus: active\nsources: test\n---\n# pricing tiers"
+ )
+ (self.root / "channels").mkdir()
+ (self.root / "channels" / "general.md").write_text(
+ "---\nchannel_id: abc123\nsummary: General\nstatus: active\nsources: test\n---\n# general"
+ )
+ assert lint_repo(self.root) == []
+
+ def test_report_findings_do_not_fail_lint(self) -> None:
+ _oversized_page(self.root)
+ assert lint_repo(self.root) == []
+ assert any(finding.startswith("oversized:") for finding in report_repo(self.root))
+
+ @parameterized.expand(
+ [
+ ("missing_agents_md", _remove_agents_md),
+ ("claude_md_regular_file", _claude_md_regular_file),
+ ("rogue_root_file", _rogue_root_file),
+ ("disallowed_root_directory", _disallowed_root_directory),
+ ("non_markdown_page", _non_markdown_page),
+ ("misnamed_decision", _misnamed_decision),
+ ("channel_page_without_channel_id", _channel_page_without_channel_id),
+ ("channel_page_with_empty_channel_id", _channel_page_with_empty_channel_id),
+ ("stray_symlink", _stray_symlink),
+ ("scripts_symlink", _scripts_symlink),
+ ("scripts_extra_file", _scripts_extra_file),
+ ("scripts_tampered_lint", _scripts_tampered_lint),
+ ]
+ )
+ def test_violations_are_reported(self, _name: str, violate: Callable[[Path], None]) -> None:
+ violate(self.root)
+ assert lint_repo(self.root) != []
diff --git a/products/context_layer/backend/test/test_store.py b/products/context_layer/backend/test/test_store.py
new file mode 100644
index 000000000000..71fd813c58f2
--- /dev/null
+++ b/products/context_layer/backend/test/test_store.py
@@ -0,0 +1,210 @@
+import tempfile
+from pathlib import Path
+
+from posthog.test.base import BaseTest
+from unittest.mock import MagicMock, patch
+
+from django.test import SimpleTestCase, override_settings
+
+from redis.exceptions import RedisError
+
+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
+
+
+class TestRepoWriterLock(SimpleTestCase):
+ def test_release_redis_error_does_not_propagate(self) -> None:
+ client = MagicMock()
+ client.set.return_value = True
+ client.eval.side_effect = RedisError("redis unavailable")
+
+ with patch.object(store, "get_client", return_value=client):
+ # Releasing the lock fails, but the write has already landed by then,
+ # so the context manager must exit cleanly rather than raise.
+ with store.repo_writer_lock("org-1"):
+ pass
+
+ assert client.eval.called
+
+
+class TestPruneBundles(SimpleTestCase):
+ ORG = "11111111-1111-1111-1111-111111111111"
+
+ def test_deletes_stale_bundles_and_never_the_kept_head(self) -> None:
+ keep = "a" * 40
+ stale = ["b" * 40, "c" * 40]
+ listed = [store.bundle_key(self.ORG, sha) for sha in [keep, *stale]]
+
+ with patch.object(store, "object_storage") as storage:
+ storage.list_objects.return_value = listed
+ storage.delete_objects.return_value = []
+ store._prune_bundles_except(self.ORG, keep)
+
+ storage.list_objects.assert_called_once_with(store.bundle_prefix(self.ORG))
+ deleted = storage.delete_objects.call_args.args[0]
+ assert set(deleted) == {store.bundle_key(self.ORG, sha) for sha in stale}
+ assert store.bundle_key(self.ORG, keep) not in deleted
+
+ def test_raises_when_a_bundle_delete_fails(self) -> None:
+ keep = "a" * 40
+ stale_key = store.bundle_key(self.ORG, "d" * 40)
+
+ with patch.object(store, "object_storage") as storage:
+ storage.list_objects.return_value = [store.bundle_key(self.ORG, keep), stale_key]
+ storage.delete_objects.return_value = [stale_key]
+ with self.assertRaises(store.PurgeIncompleteError):
+ store._prune_bundles_except(self.ORG, keep)
+
+ def test_raises_and_deletes_nothing_when_listing_unavailable(self) -> None:
+ with patch.object(store, "object_storage") as storage:
+ storage.list_objects.return_value = None
+ with self.assertRaises(store.PurgeIncompleteError):
+ store._prune_bundles_except(self.ORG, "a" * 40)
+ storage.delete_objects.assert_not_called()
+
+
+def _page(title: str) -> str:
+ return f"---\nsummary: {title} page for store tests.\nstatus: active\n---\n# {title}\n"
+
+
+@override_settings(OBJECT_STORAGE_ENABLED=True)
+class TestContextLayerStore(BaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ # The module-level client is cached from whichever settings were active
+ # first; reset it so this class always runs against real object storage.
+ object_storage_module._client = UnavailableStorage()
+ self.addCleanup(setattr, object_storage_module, "_client", UnavailableStorage())
+
+ def test_initialize_repo_scaffolds_default_structure(self) -> None:
+ config = store.initialize_repo(self.organization.id, created_by_id=self.user.id)
+
+ assert len(config.head_sha) == 40
+ with store.checkout_repo(self.organization.id) as checkout:
+ assert checkout.head_sha == config.head_sha
+ assert (checkout.path / "AGENTS.md").is_file()
+ assert (checkout.path / "CLAUDE.md").is_symlink()
+ assert (checkout.path / "org" / "overview.md").is_file()
+ assert (checkout.path / "scripts" / "lint").is_file()
+
+ def test_initialize_repo_is_idempotent(self) -> None:
+ first = store.initialize_repo(self.organization.id)
+ second = store.initialize_repo(self.organization.id)
+ assert first.id == second.id
+ assert first.head_sha == second.head_sha
+
+ def test_apply_changes_lands_commit_and_moves_head(self) -> None:
+ config = store.initialize_repo(self.organization.id)
+
+ def add_area_page(root: Path) -> None:
+ (root / "areas").mkdir(exist_ok=True)
+ (root / "areas" / "analytics.md").write_text(_page("Analytics"))
+
+ new_head = store.apply_changes(
+ self.organization.id, message="Add the analytics area page", mutate=add_area_page
+ )
+
+ assert new_head != config.head_sha
+ config.refresh_from_db()
+ assert config.head_sha == new_head
+ with store.checkout_repo(self.organization.id) as checkout:
+ assert (checkout.path / "areas" / "analytics.md").is_file()
+
+ def test_apply_changes_rejects_lint_violations_without_moving_head(self) -> None:
+ config = store.initialize_repo(self.organization.id)
+
+ def add_rogue_root_file(root: Path) -> None:
+ (root / "secrets.txt").write_text("nope")
+
+ with self.assertRaises(store.LintFailedError):
+ store.apply_changes(self.organization.id, message="Add a rogue file", mutate=add_rogue_root_file)
+ config.refresh_from_db()
+ assert len(config.head_sha) == 40
+
+ def test_apply_changes_noop_returns_current_head(self) -> None:
+ config = store.initialize_repo(self.organization.id)
+ head = store.apply_changes(self.organization.id, message="No changes", mutate=lambda root: None)
+ assert head == config.head_sha
+
+ def test_writer_lock_blocks_concurrent_writer_and_frees_on_exit(self) -> None:
+ store.initialize_repo(self.organization.id)
+
+ with store.repo_writer_lock(self.organization.id):
+ with self.assertRaises(store.RepoLockUnavailableError):
+ store.apply_changes(self.organization.id, message="Blocked", mutate=lambda root: None)
+
+ head = store.apply_changes(self.organization.id, message="Unblocked", mutate=lambda root: None)
+ assert head == ContextLayerConfig.objects.get(organization_id=self.organization.id).head_sha
+
+ def test_purge_repo_history_keeps_tree_and_drops_history(self) -> None:
+ store.initialize_repo(self.organization.id)
+
+ def add_page(root: Path) -> None:
+ (root / "areas").mkdir(exist_ok=True)
+ (root / "areas" / "replay.md").write_text(_page("Replay"))
+
+ store.apply_changes(self.organization.id, message="Add the replay area page", mutate=add_page)
+ store.purge_repo_history(self.organization.id)
+
+ with store.checkout_repo(self.organization.id) as checkout:
+ assert (checkout.path / "areas" / "replay.md").is_file()
+ assert (checkout.path / "CLAUDE.md").is_symlink()
+ commit_count = store._run_git(["rev-list", "--count", "HEAD"], cwd=checkout.path)
+ assert commit_count == "1"
+
+ def test_landing_prunes_bundles_older_than_the_previous_head(self) -> None:
+ h0 = store.initialize_repo(self.organization.id).head_sha
+
+ def add_page(name: str):
+ def mutate(root: Path) -> None:
+ (root / "areas").mkdir(exist_ok=True)
+ (root / "areas" / f"{name}.md").write_text(_page(name))
+
+ return mutate
+
+ h1 = store.apply_changes(self.organization.id, message="Add a", mutate=add_page("a"))
+ h2 = store.apply_changes(self.organization.id, message="Add b", mutate=add_page("b"))
+
+ assert object_storage_module.read_bytes(store.bundle_key(self.organization.id, h0), missing_ok=True) is None
+ assert object_storage_module.read_bytes(store.bundle_key(self.organization.id, h1), missing_ok=True)
+ assert object_storage_module.read_bytes(store.bundle_key(self.organization.id, h2), missing_ok=True)
+
+ def test_landing_restores_tampered_scripts_to_canonical(self) -> None:
+ store.initialize_repo(self.organization.id)
+
+ def tamper(root: Path) -> None:
+ (root / "scripts" / "lint").write_text("#!/bin/sh\necho pwned\n")
+ (root / "areas").mkdir(exist_ok=True)
+ (root / "areas" / "clean.md").write_text(_page("Clean"))
+
+ store.apply_changes(self.organization.id, message="Edit with tampered script", mutate=tamper)
+
+ with store.checkout_repo(self.organization.id) as checkout:
+ shipped = (checkout.path / "scripts" / "lint").read_text()
+ assert shipped == repo_lint._canonical_scripts()["lint"]
+
+ def test_refresh_never_writes_through_a_symlinked_script(self) -> None:
+ store.initialize_repo(self.organization.id)
+ victim = Path(tempfile.mkdtemp()) / "victim.txt"
+ victim.write_text("untouched")
+
+ def symlink_script(root: Path) -> None:
+ lint = root / "scripts" / "lint"
+ lint.unlink()
+ lint.symlink_to(victim)
+
+ store.apply_changes(self.organization.id, message="Symlink the linter", mutate=symlink_script)
+
+ assert victim.read_text() == "untouched"
+ with store.checkout_repo(self.organization.id) as checkout:
+ landed = checkout.path / "scripts" / "lint"
+ assert not landed.is_symlink()
+ assert landed.read_text() == repo_lint._canonical_scripts()["lint"]
+
+ def test_checkout_repo_without_config_raises(self) -> None:
+ with self.assertRaises(store.RepoNotFoundError):
+ with store.checkout_repo(self.organization.id):
+ pass
diff --git a/products/context_layer/package.json b/products/context_layer/package.json
new file mode 100644
index 000000000000..50351e52cc44
--- /dev/null
+++ b/products/context_layer/package.json
@@ -0,0 +1,6 @@
+{
+ "name": "@posthog/products-context-layer",
+ "scripts": {
+ "backend:test": "pytest -c ../../pytest.ini --rootdir ../.. backend/ -v --tb=short"
+ }
+}
diff --git a/products/context_layer/product.yaml b/products/context_layer/product.yaml
new file mode 100644
index 000000000000..9584f1fb8491
--- /dev/null
+++ b/products/context_layer/product.yaml
@@ -0,0 +1,3 @@
+name: Context layer
+owners:
+ - team-posthog-desktop
diff --git a/products/isolation_baseline.txt b/products/isolation_baseline.txt
index a5a4cad01e87..5d4979485c4b 100644
--- a/products/isolation_baseline.txt
+++ b/products/isolation_baseline.txt
@@ -31,6 +31,7 @@ business_knowledge
canvas
cdp
cohorts
+context_layer
conversations
dashboards
data_catalog
diff --git a/tach.toml b/tach.toml
index 176649d727d6..d9cddb05f3ed 100644
--- a/tach.toml
+++ b/tach.toml
@@ -507,6 +507,13 @@ depends_on = [
]
layer = "modules"
+[[modules]]
+path = "products.context_layer"
+depends_on = [
+ "posthog",
+]
+layer = "modules"
+
[[modules]]
path = "products.managed_migrations"
depends_on = [