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): recover newly completed dream tasks (#87596)

Peter Kirkhamdacd5ea45348
diff --git a/products/context_layer/README.md b/products/context_layer/README.md
index af60b7d4726e..63d4c06ce3d6 100644
--- a/products/context_layer/README.md
+++ b/products/context_layer/README.md
@@ -31,4 +31,4 @@ The root file is AGENTS.md because the layer must work for every model and harne
## 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. 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. 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/temporal/dreaming.py b/products/context_layer/backend/temporal/dreaming.py
index b1bfdeef4ef3..19e87f3b0626 100644
--- a/products/context_layer/backend/temporal/dreaming.py
+++ b/products/context_layer/backend/temporal/dreaming.py
@@ -44,6 +44,7 @@ DISPATCH_CAP_PER_TICK = 200
FAILURE_STREAK_PAUSE_THRESHOLD = 3
SKILLS_DIR = Path(__file__).parent.parent.parent / "skills"
COORDINATOR_DISTINCT_ID = "context-layer-coordinator"
+COMPLETED_TASK_RECOVERY_WINDOW = dt.timedelta(days=7)
def _capture_lane_event(distinct_id: str, event: str, properties: dict[str, str | int]) -> None:
@@ -233,7 +234,13 @@ def _build_dream_prompt(since: dt.datetime | None) -> str:
if since is None:
preamble = "This is the first dream: review the last 7 days of organizational activity."
else:
- preamble = f"Review organizational activity since {since.astimezone(dt.UTC).isoformat()}."
+ since_utc = since.astimezone(dt.UTC)
+ recovery_cutoff = since_utc - COMPLETED_TASK_RECOVERY_WINDOW
+ preamble = (
+ f"Review organizational activity since {since_utc.isoformat()}. "
+ f"For completed tasks, recover from {recovery_cutoff.isoformat()} so work that completed after an "
+ "earlier review is reconsidered."
+ )
return f"{preamble}\n\n{_dream_skills_content()}"
diff --git a/products/context_layer/backend/test/test_dreaming.py b/products/context_layer/backend/test/test_dreaming.py
index 7bcafb95a9e8..cf465b98f8fd 100644
--- a/products/context_layer/backend/test/test_dreaming.py
+++ b/products/context_layer/backend/test/test_dreaming.py
@@ -5,6 +5,7 @@ from posthog.test.base import BaseTest
from unittest.mock import AsyncMock, MagicMock, patch
from django.contrib import admin as django_admin
+from django.test import SimpleTestCase
from django.utils import timezone
from parameterized import parameterized
@@ -14,6 +15,24 @@ from products.context_layer.backend.models import ContextLayerConfig
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."),
+ (
+ datetime(2026, 8, 20, 3, 0, tzinfo=UTC),
+ (
+ "Review organizational activity since 2026-08-20T03:00:00+00:00. "
+ "For completed tasks, recover from 2026-08-13T03:00:00+00:00 so work that completed after an "
+ "earlier review is reconsidered."
+ ),
+ ),
+ ]
+ )
+ def test_activity_window(self, last_dream_started_at, expected_preamble) -> None:
+ assert dreaming._build_dream_prompt(last_dream_started_at).startswith(expected_preamble)
+
+
class TestDreamingLane(BaseTest):
def _config(self, **overrides) -> ContextLayerConfig:
defaults = {"organization": self.organization, "head_sha": "a" * 40, "created_by": self.user}
@@ -95,17 +114,8 @@ class TestDreamingLane(BaseTest):
assert "The server scaffolds every public Space and regenerates its indexes" in prompt
assert "name: context-layer-dreaming" not in prompt
- @parameterized.expand(
- [
- (None, "This is the first dream: review the last 7 days of organizational activity."),
- (
- datetime(2026, 8, 20, 3, 0, tzinfo=UTC),
- "Review organizational activity since 2026-08-20T03:00:00+00:00.",
- ),
- ]
- )
- def test_dispatch_prompt_carries_the_activity_window(self, last_dream_started_at, expected_preamble) -> None:
- config = self._config(last_dream_started_at=last_dream_started_at)
+ 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)
trigger_mock = AsyncMock()
with (
@@ -126,7 +136,7 @@ class TestDreamingLane(BaseTest):
assert context.reasoning_effort == "high"
assert context.initial_permission_mode == "bypassPermissions"
prompt = trigger_mock.call_args.args[0]
- assert prompt.startswith(expected_preamble)
+ assert prompt.startswith("This is the first dream: review the last 7 days of organizational activity.")
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 b9c00e738293..5cf08d54a187 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 window 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. 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 the 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. 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.
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.