: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
fix(context-layer): unblock malformed wiki-link imports (#89715)
Peter Kirkham021e422ab641
diff --git a/products/context_layer/README.md b/products/context_layer/README.mdindex d3620899e1a5..73a3601e9677 100644--- a/products/context_layer/README.md+++ b/products/context_layer/README.md@@ -40,6 +40,8 @@ scripts/publish the server-owned publishing clientThe root file is AGENTS.md because the layer must work for every model and harness; the CLAUDE.md symlink covers Claude-native tooling.+During enablement, malformed wiki-link brackets in legacy Space context are encoded as readable HTML entities instead of blocking setup. The imported page includes a note asking the dreaming agent to review and repair those links. Later wiki edits still pass through the strict structure linter.+## DreamingA nightly Temporal coordinator (`context-layer-dream-coordinator`, 03:00 UTC) dispatches one cloud task per enabled organization using GPT-5.6 Sol with high reasoning. Before dispatch, deterministic reconciliation creates a project-scoped page for every public Space and regenerates the project and Space indexes. The run works unlocked on its own clone all night, on a dated `dream/<YYYY-MM-DD>` branch, and lands it through the commits endpoint as one two-parent merge commit (`dream: <date>`): `git log --merges` lists the dreams, and `git revert -m 1` undoes a whole night. The skills live in `products/context_layer/skills/` and source context from completed tasks and loops, merged PRs, and instrumented events. Each run also rechecks completed tasks from the previous seven days so work that finishes after an earlier review is not lost behind the incremental cursor. Dream branches may change sourced content pages only; the server rejects changes to repository instructions, generated indexes, scripts, or Space paths. A per-org failure streak pauses a lane after repeated dispatch failures (`ContextLayerConfig.dreaming_paused`).diff --git a/products/context_layer/backend/enablement.py b/products/context_layer/backend/enablement.pyindex fce3b48315c5..8f2d60b0fafb 100644--- a/products/context_layer/backend/enablement.py+++ b/products/context_layer/backend/enablement.py@@ -20,7 +20,7 @@ from posthog.models.scoping import team_scopefrom posthog.models.team.team import Teamfrom products.access_control.backend.models.access_control import AccessControl-from products.context_layer.backend import store+from products.context_layer.backend import repo_lint, storefrom products.context_layer.backend.models import ContextLayerConfigfrom products.context_layer.backend.scaffold import AGENTS_MDfrom products.tasks.backend.facade import api as tasks_facade@@ -205,5 +205,37 @@ def _channel_page(team_id: int, channel_id: str, channel_name: str, content: strelse:summary = f"Context imported from {title}."source = "channel-instructions-import"- body = f"\n{content.strip()}\n"+ sanitized_content, repaired = _sanitize_imported_context(content.strip())+ repair_note = (+ "\n> **Import note:** Some wiki-link brackets in this imported context were encoded because they were "+ "malformed. Review and repair the links.\n"+ if repaired+ else ""+ )+ body = f"{repair_note}\n{sanitized_content}\n"return f"---\nteam_id: {team_id}\nchannel_id: {channel_id}\nsummary: {summary}\nstatus: active\nsources: {source}\n---\n\n# {title} (project {team_id}, Space {channel_id[:8]})\n{body}"+++def _sanitize_imported_context(content: str) -> tuple[str, bool]:+ parts: list[str] = []+ cursor = 0+ repaired = False+ for match in repo_lint.WIKILINK_RE.finditer(content):+ prefix, changed = _encode_wikilink_brackets(content[cursor : match.start()])+ parts.append(prefix)+ repaired |= changed+ if repo_lint._wikilink_target(match.group(1)) is None:+ encoded, _ = _encode_wikilink_brackets(match.group(0))+ parts.append(encoded)+ repaired = True+ else:+ parts.append(match.group(0))+ cursor = match.end()+ suffix, changed = _encode_wikilink_brackets(content[cursor:])+ parts.append(suffix)+ return "".join(parts), repaired or changed+++def _encode_wikilink_brackets(content: str) -> tuple[str, bool]:+ encoded = content.replace("[[", "[[").replace("]]", "]]")+ return encoded, encoded != contentdiff --git a/products/context_layer/backend/test/test_api.py b/products/context_layer/backend/test/test_api.pyindex 7f9a08ca669a..f2ec5a805ed0 100644--- a/products/context_layer/backend/test/test_api.py+++ b/products/context_layer/backend/test/test_api.py@@ -129,6 +129,27 @@ class TestContextLayerAPI(APIBaseTest):assert resolved.status_code == 200assert resolved.json() == {"path": path, "exists": True}+ def test_enable_sanitizes_malformed_wikilinks_in_legacy_context(self, _flag) -> None:+ with team_scope(self.team.id):+ channel = tasks_facade.resolve_channel(self.team.id, self.user.id, name="research", star=False)+ assert channel is not None+ tasks_facade.publish_channel_instructions(+ channel.id,+ self.team.id,+ self.user.id,+ content="Keep [[areas/insights]] current. Ignore [[../secrets]] and review [[unfinished notes.",+ base_version=0,+ )++ self._enable()++ path = f"projects/{self.team.id}/spaces/research.md"+ page = self.client.get(f"{self.base_url}/pages/", {"path": path}).json()+ assert "[[areas/insights]]" in page["content"]+ assert "[[../secrets]]" in page["content"]+ assert "[[unfinished notes." in page["content"]+ assert "Some wiki-link brackets in this imported context were encoded" in page["content"]+def test_enable_scaffolds_space_page_without_legacy_context(self, _flag) -> None:with team_scope(self.team.id):channel = tasks_facade.resolve_channel(self.team.id, self.user.id, name="empty-space", star=False)