: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): publish dream edits and expose unpublished runs (#101199)
Peter Kirkham3341fd4529b2
diff --git a/docs/internal/cloud-task-sandbox.md b/docs/internal/cloud-task-sandbox.mdindex ac329b0c32ba..793bdca5283f 100644--- a/docs/internal/cloud-task-sandbox.md+++ b/docs/internal/cloud-task-sandbox.md@@ -59,6 +59,11 @@ Loops can edit only their configured channel page, and read-only task tokens canDo not grant broader token scopes to work around a denied write.Ordinary tasks cannot publish commit bundles or use `scripts/publish` to bypass review.Server-owned nightly maintenance can publish a dated, content-only dream branch. The server verifies an active internal maintenance task in the organization, not just a branch name or token scope.+Scheduled dreams run `scripts/publish --dream <summary-file>` from the mounted wiki after consolidation and lint.+The helper uses the current UTC date for the branch, reuses that branch on retries, creates a local commit, and uploads a git bundle through the context layer API.+The server records the authenticated maintenance run ID in the merge commit. Dream publication status matches this ID, not the commit time, so overlapping runs cannot hide a failed publication.+GitHub signed-commit tools do not apply to this local bundle repository.+The helper reports `publish: landed` only after a successful upload, reports `publish: no changes` for an unchanged wiki, and returns a nonzero exit for failures.Direct human page editing remains available.This review gate applies to server-minted task and loop tokens. Human/API credentials keep their existing permissions.diff --git a/products/context_layer/backend/dreams.py b/products/context_layer/backend/dreams.pyindex 51157803f6ed..f4fb6de6c1dd 100644--- a/products/context_layer/backend/dreams.py+++ b/products/context_layer/backend/dreams.py@@ -14,7 +14,7 @@ import uuidfrom datetime import UTC, datetimefrom posthog.dataclasses import frozen-from posthog.utils import get_safe_cache, safe_cache_set+from posthog.utils import absolute_uri, get_safe_cache, safe_cache_setfrom products.context_layer.backend import storefrom products.tasks.backend.facade import api as tasks_facade@@ -47,6 +47,7 @@ class DreamRun:pages_added: intpages_modified: intpages_deleted: int+ task_run_id: str | None = None@frozen@@ -55,6 +56,13 @@ class ActiveDreamRun:started_at: datetime+@frozen+class UnpublishedDreamRun:+ task_url: str+ run_status: str+ started_at: datetime++@frozenclass DreamFileDiff:path: str@@ -74,13 +82,14 @@ class DreamRunList:head_sha: strdreams: list[DreamRun]active_run: ActiveDreamRun | None+ unpublished_run: UnpublishedDreamRun | None_STATUS_MAP = {"A": "added", "M": "modified", "D": "deleted"}def _list_cache_key(organization_id: uuid.UUID | str, head_sha: str) -> str:- return f"context_layer:dreams:{organization_id}:{head_sha}"+ return f"context_layer:dreams:v2:{organization_id}:{head_sha}"def _detail_cache_key(organization_id: uuid.UUID | str, head_sha: str, sha: str) -> str:@@ -93,19 +102,36 @@ def list_dream_runs(organization_id: uuid.UUID | str) -> DreamRunList:active_run = _get_active_dream_run(organization_id)cached = get_safe_cache(_list_cache_key(organization_id, head_sha))if cached is not None:- return DreamRunList(- head_sha=head_sha,- dreams=[_dream_run_from_dict(entry) for entry in cached if isinstance(entry, dict)],- active_run=active_run,+ dreams = [_dream_run_from_dict(entry) for entry in cached if isinstance(entry, dict)]+ else:+ with store.checkout_repo(organization_id) as checkout:+ dreams = _read_dream_runs(checkout)+ safe_cache_set(+ _list_cache_key(organization_id, head_sha),+ [_dream_run_to_dict(dream) for dream in dreams],+ CACHE_TTL_SECONDS,)- with store.checkout_repo(organization_id) as checkout:- dreams = _read_dream_runs(checkout)- safe_cache_set(- _list_cache_key(organization_id, head_sha),- [_dream_run_to_dict(dream) for dream in dreams],- CACHE_TTL_SECONDS,+ return DreamRunList(+ head_sha=head_sha,+ dreams=dreams,+ active_run=active_run,+ unpublished_run=_get_unpublished_dream_run(organization_id, dreams),+ )+++def _get_unpublished_dream_run(organization_id: uuid.UUID | str, dreams: list[DreamRun]) -> UnpublishedDreamRun | None:+ run = tasks_facade.get_latest_internal_task_run_for_organization(+ organization_id, ai_stage=DREAM_AI_STAGE, terminal_only=True+ )+ if run is None or run.created_at is None or not run.is_terminal:+ return None+ if any(dream.task_run_id == str(run.id) for dream in dreams):+ return None+ return UnpublishedDreamRun(+ task_url=absolute_uri(f"/project/{run.team_id}/tasks/{run.task_id}"),+ run_status=run.status,+ started_at=run.created_at,)- return DreamRunList(head_sha=head_sha, dreams=dreams, active_run=active_run)def _get_active_dream_run(organization_id: uuid.UUID | str) -> ActiveDreamRun | None:@@ -169,6 +195,7 @@ def _read_dream_runs(checkout: store.RepoCheckout) -> list[DreamRun]:subject, _, body = rest.partition(_FIELD_SEPARATOR)if not subject.startswith(DREAM_SUBJECT_PREFIX):continue+ summary, trailer_separator, task_run_id = ("\n\n" + body.strip()).rpartition("\n\nTask-Run-Id: ")counts = {"A": 0, "M": 0, "D": 0}for line in changes.splitlines():status, _, path = line.partition("\t")@@ -180,10 +207,11 @@ def _read_dream_runs(checkout: store.RepoCheckout) -> list[DreamRun]:sha=sha,date=subject.removeprefix(DREAM_SUBJECT_PREFIX).strip(),committed_at=datetime.fromisoformat(committed_at),- summary=body.strip(),+ summary=summary.strip() if trailer_separator else body.strip(),pages_added=counts["A"],pages_modified=counts["M"],pages_deleted=counts["D"],+ task_run_id=task_run_id if trailer_separator else None,))return dreams@@ -229,6 +257,7 @@ def _dream_run_to_dict(dream: DreamRun) -> dict[str, object]:"pages_added": dream.pages_added,"pages_modified": dream.pages_modified,"pages_deleted": dream.pages_deleted,+ "task_run_id": dream.task_run_id,}@@ -241,6 +270,7 @@ def _dream_run_from_dict(data: dict[str, object]) -> DreamRun:pages_added=int(str(data["pages_added"])),pages_modified=int(str(data["pages_modified"])),pages_deleted=int(str(data["pages_deleted"])),+ task_run_id=str(data["task_run_id"]) if data.get("task_run_id") else None,)diff --git a/products/context_layer/backend/presentation/serializers.py b/products/context_layer/backend/presentation/serializers.pyindex 8f92d0e43eb1..98ab308c68d1 100644--- a/products/context_layer/backend/presentation/serializers.py+++ b/products/context_layer/backend/presentation/serializers.py@@ -87,6 +87,14 @@ class ActiveDreamRunSerializer(serializers.Serializer):started_at = serializers.DateTimeField(help_text="When the active dream task was created.")+class UnpublishedDreamRunSerializer(serializers.Serializer):+ task_url = serializers.URLField(help_text="Task URL in its project for the unpublished dream outcome and logs.")+ run_status = serializers.CharField(+ help_text="The terminal task-run state, such as completed, failed, or cancelled."+ )+ started_at = serializers.DateTimeField(help_text="When the unpublished dream task was created.")++class DreamRunListSerializer(serializers.Serializer):"""Response shape for the wiki's dream run listing."""@@ -95,6 +103,10 @@ class DreamRunListSerializer(serializers.Serializer):allow_null=True,help_text="The organization's active dreaming task, or null when no dream is running.",)+ unpublished_run = UnpublishedDreamRunSerializer(+ allow_null=True,+ help_text="The latest finished dream when no update was published after it started, or null otherwise.",+ )dreams = DreamRunSerializer(many=True, help_text="Every landed dream run, newest first.")diff --git a/products/context_layer/backend/presentation/views.py b/products/context_layer/backend/presentation/views.pyindex ea6bc561ab5a..72ad4f838e59 100644--- a/products/context_layer/backend/presentation/views.py+++ b/products/context_layer/backend/presentation/views.py@@ -341,6 +341,7 @@ def _land_commits(organization_id, request: Request) -> Response: # noqa: ANN00# so a loop run must land its edits through the page endpoint instead.raise PermissionDenied("This loop can update only its context page, not land commit bundles.")is_task_run = INTERNAL_RUN_SCOPE in token_scopes+ maintenance_run = Noneif is_task_run:maintenance_run = tasks_facade.get_latest_active_internal_task_run_for_organization(organization_id, ai_stage=facade.DREAM_AI_STAGE@@ -361,6 +362,7 @@ def _land_commits(organization_id, request: Request) -> Response: # noqa: ANN00bundle_bytes,branch=branch,summary=serializer.validated_data.get("summary") or None,+ task_run_id=maintenance_run.id if maintenance_run is not None else None,)else:head_sha = facade.land_commit_bundle(diff --git a/products/context_layer/backend/repo_lint.py b/products/context_layer/backend/repo_lint.pyindex e52f4ae8edac..c6d2cdc1f4c6 100644--- a/products/context_layer/backend/repo_lint.py+++ b/products/context_layer/backend/repo_lint.py@@ -271,15 +271,51 @@ if [ -z "${POSTHOG_API_URL:-}" ] || [ -z "${POSTHOG_PERSONAL_API_KEY:-}" ] || [echo "publish: POSTHOG_API_URL, POSTHOG_PERSONAL_API_KEY, and POSTHOG_CONTEXT_LAYER_COMMITS_PATH must be set (they are inside PostHog sandboxes)" >&2exit 1fi+dream=false+if [ "${1:-}" = "--dream" ]; then+ dream=true+ shift+fi+summary_file="${1:-}"+summary=""+if [ -n "$summary_file" ]; then+ summary="$(cat "$summary_file")"+fi+python3 scripts/lint+git rev-parse --verify origin/main >/dev/nullbranch="$(git rev-parse --abbrev-ref HEAD)"-if ! git bundle create /tmp/context-layer-publish.bundle "origin/main..$branch" 2>/dev/null; then- echo "publish: nothing to publish; commit your edits first"+if [ "$dream" = true ]; then+ if [ -z "$summary" ]; then+ echo "publish: a scheduled dream needs a nonempty summary file" >&2+ exit 1+ fi+ target_branch="dream/$(date -u +%F)"+ if [ "$branch" != "$target_branch" ]; then+ branch="$target_branch"+ if git show-ref --verify --quiet "refs/heads/$branch"; then+ git checkout "$branch"+ else+ git checkout -b "$branch"+ fi+ fi+ git add --all+ if ! git diff --cached --quiet; then+ git -c user.name="PostHog Context Layer" -c user.email="[email protected]" \\+ -c commit.gpgsign=false commit -m "dream: ${branch#dream/}" -m "$summary"+ fi+elif [ -n "$(git status --porcelain)" ]; then+ echo "publish: uncommitted edits; scheduled dreams must use --dream" >&2+ exit 1+fi+if [ "$(git rev-list --count "origin/main..$branch")" = 0 ]; then+ echo "publish: no changes"exit 0fi-summary_file="${1:-}"+bundle="$(mktemp /tmp/context-layer-publish.XXXXXX.bundle)"+trap 'rm -f "$bundle"' EXIT+git bundle create "$bundle" "origin/main..$branch"set --if [ -n "$summary_file" ]; then- summary="$(cat "$summary_file")"set -- "$@" --form-string "summary=$summary"fiif [ "$branch" != "main" ]; then@@ -287,7 +323,7 @@ if [ "$branch" != "main" ]; thenficurl -fsS -X POST \\-H "Authorization: Bearer $POSTHOG_PERSONAL_API_KEY" \\- -F "bundle=@/tmp/context-layer-publish.bundle" \\+ -F "bundle=@$bundle" \\"$@" \\"${POSTHOG_API_URL%/}$POSTHOG_CONTEXT_LAYER_COMMITS_PATH"echo ""diff --git a/products/context_layer/backend/store.py b/products/context_layer/backend/store.pyindex 2e92eab004ac..cf023508ca64 100644--- a/products/context_layer/backend/store.py+++ b/products/context_layer/backend/store.py@@ -739,6 +739,7 @@ def land_dream_branch(*,branch: str,summary: str | None = None,+ task_run_id: uuid.UUID | None = None,) -> str:"""Land a night's `dream/<YYYY-MM-DD>` branch as one two-parent merge commit(`dream: <date>`), keeping the branch ref, so every night stays trackable@@ -762,6 +763,8 @@ def land_dream_branch(merge_args = ["merge", "--no-ff", "--quiet", "-m", f"dream: {branch.removeprefix('dream/')}"]if summary:merge_args.extend(["-m", summary])+ if task_run_id is not None:+ merge_args.extend(["-m", f"Task-Run-Id: {task_run_id}"])_run_git([*merge_args, branch], cwd=workdir)except ContextLayerStoreError as error:raise BundleConflictError(f"the dream branch conflicts with the current head: {error}") from errordiff --git a/products/context_layer/backend/test/test_api.py b/products/context_layer/backend/test/test_api.pyindex 0ea6da786c89..be83861dfafe 100644--- a/products/context_layer/backend/test/test_api.py+++ b/products/context_layer/backend/test/test_api.py@@ -828,7 +828,7 @@ class TestContextLayerAPI(APIBaseTest):task = apps.get_model("tasks", "Task").objects.create(team=self.team, created_by=self.user, title="Wiki maintenance", internal=True)- apps.get_model("tasks", "TaskRun").objects.create(+ run = apps.get_model("tasks", "TaskRun").objects.create(task=task,team=self.team,status="in_progress",@@ -853,6 +853,7 @@ class TestContextLayerAPI(APIBaseTest):with patch.object(views, "RUN_COMMITS_PER_DAY_CAP", 1):assert land("areas/first.md").status_code == 200+ assert dreams.list_dream_runs(self.organization.id).dreams[0].task_run_id == str(run.id)capped = land("areas/second.md")assert capped.status_code == 429@@ -1132,6 +1133,62 @@ class TestContextLayerAPI(APIBaseTest):def test_dreams_404_before_enablement(self, _flag) -> None:assert self.client.get(f"{self.base_url}/dreams/").status_code == 404+ @parameterized.expand(["completed", "failed", "cancelled"])+ @override_settings(SITE_URL="https://example.com")+ def test_dreams_shows_a_finished_run_without_a_published_update(self, _flag: MagicMock, status: str) -> None:+ self._enable()+ task = apps.get_model("tasks", "Task").objects.create(+ team=self.team, created_by=self.user, title="Wiki maintenance", internal=True+ )+ latest = apps.get_model("tasks", "TaskRun").objects.create(+ task=task,+ team=self.team,+ status=status,+ environment="cloud",+ state={"ai_stage": dreams.DREAM_AI_STAGE},+ )+ branch = "dream/2026-08-18"+ views.facade.land_dream_branch(+ self.organization.id,+ self._bundle_with_edit("areas/dreamt.md", _page("Dreamt"), branch),+ branch=branch,+ task_run_id=uuid4(),+ )+ active = apps.get_model("tasks", "TaskRun").objects.create(+ task=task,+ team=self.team,+ status="in_progress",+ environment="cloud",+ state={"ai_stage": dreams.DREAM_AI_STAGE},+ )++ for _ in range(2):+ response = self.client.get(f"{self.base_url}/dreams/")+ assert response.status_code == 200, response.content+ assert response.json()["unpublished_run"] == {+ "task_url": f"https://example.com/project/{self.team.id}/tasks/{task.id}",+ "run_status": status,+ "started_at": latest.created_at.isoformat().replace("+00:00", "Z"),+ }+ assert response.json()["active_run"] == {+ "run_status": "in_progress",+ "started_at": active.created_at.isoformat().replace("+00:00", "Z"),+ }++ branch = "dream/2026-08-19"+ views.facade.land_dream_branch(+ self.organization.id,+ self._bundle_with_edit("areas/published.md", _page("Published"), branch),+ branch=branch,+ summary="Recorded a context update.",+ task_run_id=latest.id,+ )+ for _ in range(2):+ assert self.client.get(f"{self.base_url}/dreams/").json()["unpublished_run"] is None+ assert (+ self.client.get(f"{self.base_url}/dreams/").json()["dreams"][0]["summary"] == "Recorded a context update."+ )+def test_dream_returns_the_runs_per_file_patches(self, _flag) -> None:self._enable()self._land_dream("areas/dreamt.md", _page("Dreamt"), "dream/2026-08-18")diff --git a/products/context_layer/backend/test/test_repo_lint.py b/products/context_layer/backend/test/test_repo_lint.pyindex 0996bf201266..4f33d005818c 100644--- a/products/context_layer/backend/test/test_repo_lint.py+++ b/products/context_layer/backend/test/test_repo_lint.py@@ -114,45 +114,6 @@ class TestRepoLint(SimpleTestCase):def test_default_structure_is_clean(self) -> None:assert lint_repo(self.root) == []- def test_publish_sends_summary_contents_as_text(self) -> None:- bin_dir = self.root / "bin"- bin_dir.mkdir()- (bin_dir / "git").write_text(- """#!/bin/sh-if [ "$1" = "rev-parse" ]; then- echo "dream/2026-09-01"-fi-"""- )- (bin_dir / "curl").write_text(- """#!/bin/sh-for arg do- printf '<%s>\\n' "$arg"-done-"""- )- (bin_dir / "git").chmod(0o755)- (bin_dir / "curl").chmod(0o755)- summary_file = self.root / "dream summary.md"- summary_file.write_text("Reviewed recent activity")-- result = subprocess.run(- [self.root / "scripts" / "publish", summary_file],- cwd=self.root,- env={- **os.environ,- "PATH": f"{bin_dir}:{os.environ['PATH']}",- "POSTHOG_API_URL": "https://example.com",- "POSTHOG_PERSONAL_API_KEY": "test-key",- "POSTHOG_CONTEXT_LAYER_COMMITS_PATH": "/commits/",- },- capture_output=True,- text=True,- check=True,- )-- assert "<--form-string>\n<summary=Reviewed recent activity>" in result.stdout-def test_valid_pages_in_every_directory_are_clean(self) -> None:(self.root / "areas").mkdir()(self.root / "areas" / "analytics.md").write_text(@@ -211,3 +172,125 @@ donedef test_violations_are_reported(self, _name: str, violate: Callable[[Path], None]) -> None:violate(self.root)assert lint_repo(self.root) != []+++class TestWikiPublish(SimpleTestCase):+ def _git(self, *args: str) -> str:+ return subprocess.run(+ ["git", *args], cwd=self.root, env=self.env, check=True, capture_output=True, text=True+ ).stdout.strip()++ def setUp(self) -> None:+ super().setUp()+ self.workspace = Path(tempfile.mkdtemp(prefix="context-layer-publish-"))+ self.addCleanup(shutil.rmtree, self.workspace, ignore_errors=True)+ self.root = self.workspace / "wiki"+ self.root.mkdir()+ write_default_structure(self.root)+ self.bin_dir = self.workspace / "bin"+ self.bin_dir.mkdir()+ (self.bin_dir / "curl").write_text(+ """#!/bin/sh+for arg do+ printf '<%s>\\n' "$arg"+ case "$arg" in+ bundle=@*) cp "${arg#bundle=@}" "$PUBLISH_BUNDLE_PATH" ;;+ esac+done+exit "${PUBLISH_HTTP_EXIT:-0}"+"""+ )+ (self.bin_dir / "curl").chmod(0o755)+ (self.bin_dir / "date").write_text("#!/bin/sh\nprintf '2026-09-16\\n'\n")+ (self.bin_dir / "date").chmod(0o755)+ self.summary_file = self.workspace / "dream summary.md"+ self.summary_file.write_text("Reviewed recent activity\nRemoved an expired priority")+ self.bundle = self.workspace / "received.bundle"+ self.env = {+ **os.environ,+ "PATH": f"{self.bin_dir}:{os.environ['PATH']}",+ "GIT_CONFIG_GLOBAL": "/dev/null",+ "GIT_CONFIG_NOSYSTEM": "1",+ "POSTHOG_API_URL": "https://example.com",+ "POSTHOG_PERSONAL_API_KEY": "test-key",+ "POSTHOG_CONTEXT_LAYER_COMMITS_PATH": "/commits/",+ "PUBLISH_BUNDLE_PATH": str(self.bundle),+ }+ self._git("init", "--initial-branch=main")+ self._git("config", "user.name", "Wiki test")+ self._git("config", "user.email", "[email protected]")+ self._git("add", "--all")+ self._git("commit", "-m", "Seed wiki")+ self._git("update-ref", "refs/remotes/origin/main", "HEAD")+ self._git("remote", "add", "origin", str(self.workspace / "context.bundle"))++ def _publish(self, *args: str) -> subprocess.CompletedProcess[str]:+ return subprocess.run(+ [self.root / "scripts" / "publish", *args, self.summary_file],+ cwd=self.root,+ env=self.env,+ capture_output=True,+ text=True,+ )++ @parameterized.expand([("unstaged",), ("staged",), ("committed",), ("existing_branch",)])+ def test_publish_sends_wiki_edits_and_summary_contents_as_text(self, change_state: str) -> None:+ if change_state == "existing_branch":+ self._git("branch", "dream/2026-09-16")+ (self.root / "areas").mkdir()+ page = self.root / "areas" / "analytics.md"+ page.write_text("---\nsummary: Analytics\nstatus: active\nsources: test\n---\n# Analytics\n")+ if change_state in ("staged", "committed"):+ self._git("add", "--all")+ if change_state == "committed":+ self._git("checkout", "-b", "dream/2026-09-01")+ self._git("commit", "-m", "Add analytics context")+ self._git("config", "commit.gpgsign", "true")+ self._git("config", "gpg.program", "/nonexistent/gpg")++ result = self._publish("--dream")++ assert result.returncode == 0, result.stderr+ assert "<--form-string>\n<summary=Reviewed recent activity\nRemoved an expired priority>" in result.stdout+ assert "publish: landed" in result.stdout+ assert self._git("status", "--porcelain") == ""+ assert self._git("branch", "--show-current") == "dream/2026-09-16"+ self._git("bundle", "verify", str(self.bundle))+ self._git("fetch", str(self.bundle), self._git("branch", "--show-current"))+ assert self._git("show", "FETCH_HEAD:areas/analytics.md") == page.read_text().strip()++ def test_publish_reports_no_changes_without_uploading(self) -> None:+ result = self._publish("--dream")++ assert result.returncode == 0, result.stderr+ assert "publish: no changes" in result.stdout+ assert not self.bundle.exists()++ def test_publish_does_not_hide_bundle_errors(self) -> None:+ self._git("update-ref", "-d", "refs/remotes/origin/main")++ result = self._publish("--dream")++ assert result.returncode != 0+ assert "publish: landed" not in result.stdout+ assert not self.bundle.exists()++ def test_publish_does_not_report_a_rejected_upload_as_landed(self) -> None:+ self._git("checkout", "-b", "dream/2026-09-01")+ self._git("commit", "--allow-empty", "-m", "Review wiki")+ self.env["PUBLISH_HTTP_EXIT"] = "22"++ result = self._publish("--dream")++ assert result.returncode != 0+ assert "publish: landed" not in result.stdout++ def test_publish_refuses_invalid_content_before_committing(self) -> None:+ (self.root / "notes.md").write_text("# Unscoped notes")+ original_head = self._git("rev-parse", "HEAD")++ result = self._publish("--dream")++ assert result.returncode != 0+ assert self._git("rev-parse", "HEAD") == original_head+ assert not self.bundle.exists()diff --git a/products/context_layer/frontend/generated/api.schemas.ts b/products/context_layer/frontend/generated/api.schemas.tsindex 5978fff32a99..90548195c11c 100644--- a/products/context_layer/frontend/generated/api.schemas.ts+++ b/products/context_layer/frontend/generated/api.schemas.ts@@ -82,6 +82,15 @@ export interface ActiveDreamRunApi {started_at: string}+export interface UnpublishedDreamRunApi {+ /** Task URL in its project for the unpublished dream outcome and logs. */+ task_url: string+ /** The terminal task-run state, such as completed, failed, or cancelled. */+ run_status: string+ /** When the unpublished dream task was created. */+ started_at: string+}+/*** One dreaming run: the merge commit it landed as, plus what it changed.*/@@ -110,6 +119,8 @@ export interface DreamRunListApi {head_sha: string/** The organization's active dreaming task, or null when no dream is running. */active_run: ActiveDreamRunApi | null+ /** The latest finished dream when no update was published after it started, or null otherwise. */+ unpublished_run: UnpublishedDreamRunApi | null/** Every landed dream run, newest first. */dreams: DreamRunApi[]}diff --git a/products/context_layer/skills/context-layer-consolidation/SKILL.md b/products/context_layer/skills/context-layer-consolidation/SKILL.mdindex 6d315f25d1aa..b999770f68ce 100644--- a/products/context_layer/skills/context-layer-consolidation/SKILL.md+++ b/products/context_layer/skills/context-layer-consolidation/SKILL.md@@ -5,7 +5,7 @@ description: Keep the context wiki coherent using the deterministic lint report# Context layer consolidation-Start with `scripts/lint --report`. Work the queue on the current dream branch.+Start with `scripts/lint --report`. Work the queue in the mounted wiki before the dream publisher creates its branch and commit.Only edit sourced Markdown content under `org/`, `areas/`, `decisions/`, and existing Space pages. Never edit repository instructions, generated indexes, or `scripts/`; report structural failures in the run summary for the server to repair.@@ -15,6 +15,6 @@ Only edit sourced Markdown content under `org/`, `areas/`, `decisions/`, and exi- Merge near-duplicates and leave a wikilink from the old subject.- Resolve disagreements only with evidence; leave the rest explicit.- Repair or intentionally retain ghost links, add sources, and split oversized pages.-- Name every deletion in the commit message.+- Name every deletion in the run summary. The dream publisher includes it in the commit message.Keep this bounded and evidence-led. Run `scripts/lint` after editing.diff --git a/products/context_layer/skills/context-layer-dreaming/SKILL.md b/products/context_layer/skills/context-layer-dreaming/SKILL.mdindex 098e93c2f9fe..fe8e2f6abb96 100644--- a/products/context_layer/skills/context-layer-dreaming/SKILL.md+++ b/products/context_layer/skills/context-layer-dreaming/SKILL.md@@ -9,13 +9,13 @@ 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.+1. Work in the mounted context wiki. 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. 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.-6. Commit sourced Markdown changes only under `org/`, `areas/`, `decisions/`, and existing `projects/<project-id>/spaces/` pages. Run `scripts/lint`; fix content errors without editing the linter, publisher, generated indexes, or repository instructions. Then run `scripts/lint --report` for the consolidation queue.-7. Write a concise run summary to `/tmp/dream-summary.md` and run `scripts/publish /tmp/dream-summary.md`. Land nothing when no candidate passes the admission test.+6. Keep sourced Markdown changes only under `org/`, `areas/`, `decisions/`, and existing `projects/<project-id>/spaces/` pages. Run `scripts/lint`; fix content errors without editing the linter, publisher, generated indexes, or repository instructions. Then run `scripts/lint --report` for the consolidation queue.+7. Finish consolidation and the health check before publishing. Write a concise run summary to `/tmp/dream-summary.md`, including the reason for each deletion, and run `scripts/publish --dream /tmp/dream-summary.md`. The publisher creates the dated dream branch, commits the wiki edits locally, and sends the bundle to the context layer API. GitHub signed-commit tools cannot commit this local bundle repository. Report publication as successful only when the publisher returns `publish: landed`; `publish: no changes` means no changes were needed. A nonzero exit means publication failed: fix the reported error or state that the dream was not published.## Rulesdiff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.pyindex 5e73176bff86..a66ceee8eddb 100644--- a/products/tasks/backend/facade/api.py+++ b/products/tasks/backend/facade/api.py@@ -1166,30 +1166,37 @@ def get_active_wizard_cloud_run(team_id: int) -> contracts.WizardCloudRunDTO | Nreturn None-def get_latest_active_internal_task_run_for_organization(- organization_id: str | UUID, *, ai_stage: str+def get_latest_internal_task_run_for_organization(+ organization_id: str | UUID, *, ai_stage: str, active_only: bool = False, terminal_only: bool = False) -> contracts.TaskRunDTO | None:- """Return the newest active cloud run for a server-owned organization flow."""- run = (- TaskRun.objects.filter(- team__organization_id=organization_id,- task__team__organization_id=organization_id,- task__internal=True,- environment=TaskRun.Environment.CLOUD,- state__ai_stage=ai_stage,+ runs = TaskRun.objects.filter(+ team__organization_id=organization_id,+ task__team__organization_id=organization_id,+ task__internal=True,+ environment=TaskRun.Environment.CLOUD,+ state__ai_stage=ai_stage,+ )+ if active_only:+ runs = runs.filter(status__in=[TaskRun.Status.NOT_STARTED,TaskRun.Status.QUEUED,TaskRun.Status.IN_PROGRESS,- ],+ ])- .select_related("task", "task__created_by")- .order_by("-created_at", "-id")- .first()- )+ if terminal_only:+ runs = runs.filter(status__in=_TERMINAL_TASK_RUN_STATUSES)+ run = runs.select_related("task", "task__created_by").order_by("-created_at", "-id").first()return _task_run_to_dto(run) if run is not None else None+def get_latest_active_internal_task_run_for_organization(+ organization_id: str | UUID, *, ai_stage: str+) -> contracts.TaskRunDTO | None:+ """Return the newest active cloud run for a server-owned organization flow."""+ return get_latest_internal_task_run_for_organization(organization_id, ai_stage=ai_stage, active_only=True)++def get_stale_queued_task_run_ids(older_than: timedelta,limit: int,diff --git a/products/tasks/backend/tests/test_facade.py b/products/tasks/backend/tests/test_facade.pyindex aa8784d1f6f2..d752b59d9cf7 100644--- a/products/tasks/backend/tests/test_facade.py+++ b/products/tasks/backend/tests/test_facade.py@@ -489,7 +489,7 @@ class TestFacadeReadsAndMappers(TestCase):state={"ai_stage": "context-layer-dream"},)terminal_task = self._make_task(internal=True)- TaskRun.objects.create(+ terminal = TaskRun.objects.create(task=terminal_task,team=self.team,status=TaskRun.Status.COMPLETED,@@ -529,6 +529,17 @@ class TestFacadeReadsAndMappers(TestCase):assert result is not Noneself.assertEqual(result.id, active.id)+ latest = facade.get_latest_internal_task_run_for_organization(+ self.organization.id, ai_stage="context-layer-dream"+ )+ assert latest is not None+ self.assertEqual(latest.id, terminal.id)+ TaskRun.objects.filter(id=active.id).update(created_at=terminal.created_at + timedelta(seconds=1))+ latest_terminal = facade.get_latest_internal_task_run_for_organization(+ self.organization.id, ai_stage="context-layer-dream", terminal_only=True+ )+ assert latest_terminal is not None+ self.assertEqual(latest_terminal.id, terminal.id)def test_count_in_progress_runs_for_github_integration_scopes_to_live_runs_of_that_integration(self):integration = Integration.objects.create(team=self.team, kind="github", config={}, sensitive_config={})diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 5b06744a0b90..acf9e0bd546f 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -31349,6 +31349,15 @@ export namespace Schemas {files: DreamFileDiff[];}+ export interface UnpublishedDreamRun {+ /** Task URL in its project for the unpublished dream outcome and logs. */+ task_url: string;+ /** The terminal task-run state, such as completed, failed, or cancelled. */+ run_status: string;+ /** When the unpublished dream task was created. */+ started_at: string;+ }+/*** Response shape for the wiki's dream run listing.*/@@ -31357,6 +31366,8 @@ export namespace Schemas {head_sha: string;/** The organization's active dreaming task, or null when no dream is running. */active_run: ActiveDreamRun | null;+ /** The latest finished dream when no update was published after it started, or null otherwise. */+ unpublished_run: UnpublishedDreamRun | null;/** Every landed dream run, newest first. */dreams: DreamRun[];}