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-layer): expand dream activity coverage (#90502)

Peter Kirkham01bc19dd4432
diff --git a/products/context_layer/README.md b/products/context_layer/README.md
index 73a3601e9677..edac3d014cfc 100644
--- a/products/context_layer/README.md
+++ b/products/context_layer/README.md
@@ -44,4 +44,4 @@ During enablement, malformed wiki-link brackets in legacy Space context are enco
## Dreaming
-A 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`).
+A 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. Each tick dispatches up to 1,000 due organizations, least-recently-dreamt first. 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. Activity pagination follows cursors until the window or budget is exhausted: up to 100 newest items total per Space across channel-scoped sources, and 100 per organization-wide source. 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. A first dream includes empty public Space pages in its scan and fills them only when their channels have qualifying activity in the seed window. 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/temporal/dreaming.py b/products/context_layer/backend/temporal/dreaming.py
index 19e87f3b0626..663922c682b9 100644
--- a/products/context_layer/backend/temporal/dreaming.py
+++ b/products/context_layer/backend/temporal/dreaming.py
@@ -38,7 +38,7 @@ from products.context_layer.backend.models import ContextLayerConfig
logger = structlog.get_logger(__name__)
-DISPATCH_CAP_PER_TICK = 200
+DISPATCH_CAP_PER_TICK = 1000
# Dispatch failures, not run failures: a lane pauses when we cannot even start
# its nightly run several nights in a row, and a human unpauses it.
FAILURE_STREAK_PAUSE_THRESHOLD = 3
@@ -232,7 +232,11 @@ def _build_dream_prompt(since: dt.datetime | None) -> str:
"""The activity window this dream should review, then the canonical skills:
synthesis first, then the bounded consolidation pass on the same branch."""
if since is None:
- preamble = "This is the first dream: review the last 7 days of organizational activity."
+ preamble = (
+ "This is the first dream: review the last 7 days of organizational activity. "
+ "Treat this as a seed run: include public Space pages that still have no substantive content, "
+ "and fill them only when their channels have qualifying activity in the seed window."
+ )
else:
since_utc = since.astimezone(dt.UTC)
recovery_cutoff = since_utc - COMPLETED_TASK_RECOVERY_WINDOW
diff --git a/products/context_layer/backend/test/test_dreaming.py b/products/context_layer/backend/test/test_dreaming.py
index cf465b98f8fd..8fd36f3f23ba 100644
--- a/products/context_layer/backend/test/test_dreaming.py
+++ b/products/context_layer/backend/test/test_dreaming.py
@@ -18,7 +18,14 @@ from products.context_layer.backend.temporal import dreaming
class TestDreamPrompt(SimpleTestCase):
@parameterized.expand(
[
- (None, "This is the first dream: review the last 7 days of organizational activity."),
+ (
+ None,
+ (
+ "This is the first dream: review the last 7 days of organizational activity. "
+ "Treat this as a seed run: include public Space pages that still have no substantive content, "
+ "and fill them only when their channels have qualifying activity in the seed window."
+ ),
+ ),
(
datetime(2026, 8, 20, 3, 0, tzinfo=UTC),
(
@@ -32,6 +39,44 @@ class TestDreamPrompt(SimpleTestCase):
def test_activity_window(self, last_dream_started_at, expected_preamble) -> None:
assert dreaming._build_dream_prompt(last_dream_started_at).startswith(expected_preamble)
+ def test_dream_prompt_carries_both_skills_without_frontmatter(self) -> None:
+ prompt = dreaming._build_dream_prompt(None)
+ assert "# Context layer dreaming" in prompt
+ assert "# Context layer consolidation" in prompt
+ assert "channel-list" in prompt
+ assert "channel-instructions-retrieve" not in prompt
+ assert "A queued, running, test, demo, fixture, or abandoned task is not evidence" in prompt
+ assert "never edit, delete, move, or replace them" in prompt
+ assert "The server scaffolds every public Space and regenerates its indexes" in prompt
+ assert "include every public Space page with no substantive content in the activity scan" in prompt
+ assert "at most 100 newest activity items across all channel-scoped sources for each Space" in prompt
+ assert "at most 100 newest items from each organization-wide source" in prompt
+ assert "next_cursor" in prompt
+ assert "offset" in prompt
+ assert "name: context-layer-dreaming" not in prompt
+
+
+class TestDreamCandidates(SimpleTestCase):
+ def test_fetch_candidates_caps_each_tick_at_one_thousand(self) -> None:
+ configs = [MagicMock(last_dream_started_at=None, organization_id=index) for index in range(1001)]
+ queryset = MagicMock()
+ queryset.order_by.return_value = configs
+
+ with (
+ patch.object(dreaming.ContextLayerConfig.objects, "filter", return_value=queryset),
+ patch.object(dreaming.context_layer_facade, "is_context_layer_enabled", return_value=True),
+ patch.object(dreaming, "_capture_lane_event") as capture_mock,
+ ):
+ candidates = dreaming._fetch_dream_candidates()
+
+ assert len(candidates) == 1000
+ assert candidates[-1] == "999"
+ capture_mock.assert_called_once_with(
+ dreaming.COORDINATOR_DISTINCT_ID,
+ "context layer dream dispatch cap reached",
+ {"cap": 1000},
+ )
+
class TestDreamingLane(BaseTest):
def _config(self, **overrides) -> ContextLayerConfig:
@@ -103,17 +148,6 @@ class TestDreamingLane(BaseTest):
assert prepared.team_id == self.team.id
assert prepared.user_id == self.user.id
- def test_dream_prompt_carries_both_skills_without_frontmatter(self) -> None:
- prompt = dreaming._build_dream_prompt(None)
- assert "# Context layer dreaming" in prompt
- assert "# Context layer consolidation" in prompt
- assert "channel-list" in prompt
- assert "channel-instructions-retrieve" not in prompt
- assert "A queued, running, test, demo, fixture, or abandoned task is not evidence" in prompt
- assert "never edit, delete, move, or replace them" in prompt
- assert "The server scaffolds every public Space and regenerates its indexes" in prompt
- assert "name: context-layer-dreaming" not in prompt
-
def test_dispatch_prompt_carries_the_activity_window(self) -> None:
config = self._config()
target = dreaming._DreamDispatchTarget(config=config, team_id=self.team.id, user_id=self.user.id)
@@ -136,7 +170,9 @@ class TestDreamingLane(BaseTest):
assert context.reasoning_effort == "high"
assert context.initial_permission_mode == "bypassPermissions"
prompt = trigger_mock.call_args.args[0]
- assert prompt.startswith("This is the first dream: review the last 7 days of organizational activity.")
+ assert prompt.startswith(
+ "This is the first dream: review the last 7 days of organizational activity. Treat this as a seed run:"
+ )
assert "# Context layer dreaming" in prompt
def test_admin_unpause_action_leaves_the_streak_alone(self) -> None:
diff --git a/products/context_layer/skills/context-layer-dreaming/SKILL.md b/products/context_layer/skills/context-layer-dreaming/SKILL.md
index 5cf08d54a187..11fff4ca509e 100644
--- a/products/context_layer/skills/context-layer-dreaming/SKILL.md
+++ b/products/context_layer/skills/context-layer-dreaming/SKILL.md
@@ -10,7 +10,7 @@ Improve the mounted context wiki with durable, sourced facts from recent organiz
## Protocol
1. Create `dream/$(date +%F)`. Read `AGENTS.md`, `index.md`, and the last ten merge commits with `git log --merges --format='%s%n%b' -10`. The server owns `AGENTS.md`, `CLAUDE.md`, every `index.md`, and `scripts/`; never edit, delete, move, or replace them. Do not change the wiki's tooling to make a proposed edit pass.
-2. Take the activity windows from the run prompt. Start with Spaces: call `channel-list`, exclude the personal `#me` channel, and match every public channel id against the frontmatter of `projects/<project-id>/spaces/*.md`. The server scaffolds every public Space and regenerates its indexes before the dream starts. Read every matched page. If a page is unexpectedly missing, record `wiki-miss: missing scaffold for <channel_id>` in the run summary and leave structure repair to the server; do not create, move, or rename Space pages. Continue in priority order with **completed** tasks and their outcomes, merged pull requests, completed loop runs and summaries, and newly created event and property definitions. Use the recovery cutoff for completed tasks and their outcomes so a task that was still in progress during an earlier dream is reconsidered after completion, and the incremental cutoff for the other sources. A queued, running, test, demo, fixture, or abandoned task is not evidence of an organizational fact or decision. Cap each activity source at roughly the 200 most recent items in its window. When a night can't cover everything, prefer newest first and note the cutoff in the run summary. When a source is unavailable or a query fails, record that limitation in the run summary; do not treat it as evidence that the source contains no candidate facts.
+2. Take the activity windows from the run prompt. Start with Spaces: call `channel-list`, exclude the personal `#me` channel, and match every public channel id against the frontmatter of `projects/<project-id>/spaces/*.md`. The server scaffolds every public Space and regenerates its indexes before the dream starts. Read every matched page. If a page is unexpectedly missing, record `wiki-miss: missing scaffold for <channel_id>` in the run summary and leave structure repair to the server; do not create, move, or rename Space pages. On a first or seed dream, include every public Space page with no substantive content in the activity scan and inspect qualifying activity attributable to its channel. Populate an empty Space only when activity in the seed window passes the admission test; leave genuinely inactive Spaces untouched. Continue in priority order with **completed** tasks and their outcomes, merged pull requests, completed loop runs and summaries, and newly created event and property definitions. Use the recovery cutoff for completed tasks and their outcomes so a task that was still in progress during an earlier dream is reconsidered after completion, and the incremental cutoff for the other sources. A queued, running, test, demo, fixture, or abandoned task is not evidence of an organizational fact or decision. Inspect at most 100 newest activity items across all channel-scoped sources for each Space, and at most 100 newest items from each organization-wide source. Page through a source while it returns a `next` or `next_cursor`; for offset pagination, advance `offset` by the number of results returned. Stop when the applicable item budget is reached, the source is exhausted, or the oldest item is before the applicable cutoff. When a budget prevents covering the full window, record the oldest covered item, unreviewed source, and remaining cursor in the run summary. When a source is unavailable or a query fails, record that limitation in the run summary; do not treat it as evidence that the source contains no candidate facts.
3. Review the same recent task and loop conversations for moments where the wiki itself failed the agent: context it needed that no content page held, a page that misled it, or a page it was told to read and clearly didn't need. Fix or create a content page when the admission test permits, and record each miss as a line in your run summary starting `wiki-miss:` — these lines set the health check's priorities and identify server-owned map changes for a later product update.
4. List candidate facts before editing. For each candidate, record the completed source and read the existing owning page plus its directly linked context before deciding. Apply the 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. Existing context that identifies activity as dogfooding, testing, demo data, or fixtures defeats promotion into real organizational strategy. A contradiction is a reason to reject the candidate or preserve an explicit disagreement, never permission to silently overwrite the existing claim.
5. Find the owning page through the index and update it. Record `sources`, set `review_after` for claims that will age, condense superseded text, and use `**Disagreement:**` for unresolved conflicts.