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.

chore(notebooks): remove completed notebooks plan files (#112473)

Sinan Kucukkoseler50656640ded3
diff --git a/frontend/src/lib/components/MarkdownNotebook/README.md b/frontend/src/lib/components/MarkdownNotebook/README.md
index 1ec6370bfb4d..76e844261ff5 100644
--- a/frontend/src/lib/components/MarkdownNotebook/README.md
+++ b/frontend/src/lib/components/MarkdownNotebook/README.md
@@ -2,7 +2,7 @@
A notebook editor that uses markdown as its storage format. The document model is parsed from and serialized back to markdown on every edit, so the markdown string is always the source of truth.
-See [COMPONENTS.md](./COMPONENTS.md) for how to register embeddable components (`<Query ... />`-style tags) and [TODO.md](./TODO.md) for open work.
+See [COMPONENTS.md](./COMPONENTS.md) for how to register embeddable components (`<Query ... />`-style tags).
## Module layout
diff --git a/frontend/src/lib/components/MarkdownNotebook/TODO.md b/frontend/src/lib/components/MarkdownNotebook/TODO.md
deleted file mode 100644
index 537ecaf304db..000000000000
--- a/frontend/src/lib/components/MarkdownNotebook/TODO.md
+++ /dev/null
@@ -1,20 +0,0 @@
-# MarkdownNotebook — open work
-
-The markdown notebook rewrite (markdown storage, custom component tags, conflict-free sync) is implemented in this folder and wired into the notebooks scene via `frontend/src/scenes/notebooks/Notebook/markdownNotebookV2.ts`. What remains is rollout, migration, and a few editor gaps.
-
-## Rollout and migration
-
-- Markdown notebooks are now the default and only experience; the `MARKDOWN_NOTEBOOKS` feature flag has been removed. Legacy TipTap-stored notebooks are converted to markdown at render time and persisted on first edit, and new notebooks, template copies, the scratchpad, canvases, and Max-created notebooks are created in the markdown format.
-- Batch conversion of existing notebooks (`convertNotebookContentToMarkdown`) needs migration validation fixtures built from real production notebook shapes, beyond the unit-test coverage in `notebookUpgradeDialog.test.tsx`.
-- Verify notebook history and sharing behavior survive the upgrade (history diffs against TipTap JSON snapshots predating the conversion).
-- Rollback: `convertMarkdownToNotebookContent` (markdownNotebookDowngrade.ts) converts markdown back to TipTap content. Known one-way losses are documented in its module docstring (discussion reply threads, AI prompts, table alignments) — wire it into a user-facing rollback flow if needed.
-
-## Editor gaps
-
-- (none currently tracked — accessibility for the toolbar/insert menu, comments on code block selections, and canvas drag-and-drop at the drop position have shipped)
-
-## Open questions
-
-- Should custom component props remain JSX-expression syntax in stored markdown, or move to a constrained JSON form?
-- Which embeds need special parsing or security review before general availability?
-- Should the raw markdown debug drawer (`showDebug`) be staff-only in production?
diff --git a/products/notebooks/plan/notebooks_mcp_evals_plan.md b/products/notebooks/plan/notebooks_mcp_evals_plan.md
deleted file mode 100644
index 1f701fcbca4c..000000000000
--- a/products/notebooks/plan/notebooks_mcp_evals_plan.md
+++ /dev/null
@@ -1,225 +0,0 @@
-# Offline evals for markdown notebooks over MCP
-
-How to add agent evals for notebook creation and editing through the MCP tools, using the existing eval harness.
-
-## 1. How evals work in this repo
-
-Everything runs on the standalone harness in `products/posthog_ai/eval_harness/`, not pytest.
-`hogli evals` boots shared infrastructure once (test DB, Django live server, LLM gateway, MCP server, Temporal, personhog), then runs every selected suite concurrently with Braintrust as the eval engine.
-
-Two suite kinds:
-
-| Kind | Marker | Per case | Infra |
-| ------------------- | --------------------------------- | ------------------------------------------------------------------ | ----------------------------- |
-| sandboxed (default) | none | the real coding agent in a real sandbox, talking to the MCP server | everything |
-| one-shot | `SUITE_KIND = SuiteKind.ONE_SHOT` | one in-process model call | test DB, personhog, demo data |
-
-Notebook MCP evals are **sandboxed**: the thing under test is an agent driving real tools against real state, which a one-shot call cannot exercise.
-
-Facts that shape the design:
-
-- Suites are discovered by convention. Product-owned suites live in `products/<product>/evals/` (plural), so ours is `products/notebooks/evals/eval_*.py`, suite id `notebooks/<module>::<fn>`.
-- A suite is one Braintrust experiment. `experiment_name` is the history key, so renaming it resets cross-run comparison.
-- Every case gets its own org/team/user cloned from a master Hedgebox team. Cases never see each other's state. The seeded user is "Karen Smith".
-- The Hedgebox dataset is byte-for-byte reproducible under a fixed seed, so assert shapes and relative date ranges, never absolute counts.
-- Case fields: `name`, `prompt`, `expected` (keyed by scorer `_name()`), `metadata`, `setup` (the seeder).
-- Whatever the seeder returns lands in `output["seed"]`, which is the only channel scorers have for seeded IDs.
-- The harness adds `ExitCodeZero` to every experiment; suites must not declare it.
-- Sandboxed evals are **not** in CI. `.github/workflows/ci-ai.yml` only runs the older `ee/hogai/eval/ci` pytest tree behind an `evals-ready` label. These run on demand, locally or on Modal.
-
-## 2. The surface under test
-
-Behind `revamped-py-notebooks`, the notebook tool set is:
-
-| Tool | Kind | Notes |
-| ------------------------------------------------------------------------------------------------------------------- | ------------ | ---------------------------------------------------------------------------------------------------------------------------------------- |
-| `notebooks-create-markdown` | hand-written | title + optional prose. Explicitly refuses to carry cells |
-| `notebooks-add-cell` | hand-written | `sql` / `python` / `markdown` / `saved_insight` / `component`. sql and python dispatch a run and write the result back into the document |
-| `notebooks-update-cell` | hand-written | edit code and re-run, or omit code to re-run as-is. Returns `stale_dependents` |
-| `notebooks-delete-cell` | hand-written | |
-| `notebook-edit` | hand-written | markdown string replacement (`old_markdown` / `new_markdown` / `replace_all`) |
-| `notebooks-get` | generated | title, markdown, cells, `depends_on`/`dependents`, derived stale status |
-| `notebooks-list-frames`, `notebooks-configure-compute`, `notebooks-run-cell-result`, `notebooks-run-cell-interrupt` | generated | kernel-side |
-
-With the flag **off** the legacy set is registered instead (`notebooks-create`, `notebooks-retrieve`, `notebooks-partial-update`), and the markdown tools disappear.
-The two sets are mutually exclusive, which matters for the harness change below.
-
-## 3. Environment blockers, verified
-
-**a. The markdown tools reach the eval MCP server through a flag override.**
-Tool filtering gates the whole markdown set on `revamped-py-notebooks` (see `services/mcp/tests/unit/tool-filtering.test.ts`), and the eval MCP server sets that flag in `FEATURE_FLAG_OVERRIDES` (`harness/services.py`). Without it the tools are not registered at all.
-Note the side effect: it also removes `notebooks-create` / `notebooks-retrieve` from the eval tool list, so a legacy-notebook eval needs a different lever.
-
-**b. Django-side gating is already satisfied.**
-`harness/lifecycle.py` patches `posthoganalytics.feature_enabled` to return `True` for the whole run, so the flag-gated SQLV2 endpoints answer normally.
-
-**c. Both cell lanes run, docker only.**
-A pure-HogQL run takes the direct lane (`enqueue_direct_run` in `presentation/views/notebook.py`), which rides the async query manager. The harness runs with `TEST=1`, where Celery is eager, so the query executes inline and no sandbox is involved.
-Python and DuckDB runs call `start_sql_v2_run_workflow`, which needs the notebook Temporal workflows registered and a kernel sandbox. The harness now does both (see [Notebook kernel sandboxes](../../posthog_ai/eval_harness/README.md#notebook-kernel-sandboxes)); before that change the run sat at `running` until its poll window expired.
-
-The kernel lane is docker-only: the notebook kernel reads its backend straight off `SANDBOX_PROVIDER`, and the modal provider sets that to `MODAL_EVALS`, which is not a `KernelRuntime.Backend` value. Run python or duckdb cases with `--provider docker`; SQL-only cases work on either provider.
-
-**d. Scopes are fine.** The sandbox context defaults to `"full"` MCP scopes (`custom_prompt_internals.py`), which includes `notebook:write`.
-
-**e. End-state scoring is possible but must be async.**
-Braintrust's base `_run_eval_async` calls `_run_eval_sync` directly on the event loop, so a scorer doing sync ORM work trips Django's async guard. A DB-reading scorer subclasses `AsyncOnlyScorerMixin, Scorer` and does its work in `asyncio.to_thread`. The pattern already exists (`DuplicateUniqueFlagKey` in `products/posthog_ai/evals/experiments/scorers.py`).
-The seeder must return `team_id` for this to work at all.
-
-## 4. Use-case selection
-
-Ground it in what the tools actually do in practice rather than what feels comprehensive.
-Check the MCP analytics for the notebook tools before picking cases (`query-mcp-tool-stats` and `query-mcp-tool-failures` per tool, or the MCP analytics UI). What that showed when this plan was written:
-
-- `notebook-edit` carries by far the highest error rate of the editing tools, and most of its failures are opaque `internal` — what a thrown `Error` looks like in telemetry, meaning `old_markdown` was not found or not unique. Highest-value target, and the one with a real failure signature to reproduce.
-- `notebooks-add-cell` is barely used yet. Evals here lock behavior in before it scales, rather than fixing a fire.
-- The legacy `notebooks-partial-update` fails mostly on HTTP 409 version conflicts.
-
-Selection principles worth keeping:
-
-- One case per behavior you could plausibly regress, not one case per tool.
-- Prefer cases where a wrong answer is cheap to detect and expensive in production (clobbering a document, losing cell results, rebuilding an insight that already exists).
-- Include at least one case where the correct behavior is _not_ calling a tool, and one where the tool rejects the first attempt and the agent must recover. Those catch prompt regressions that success-only cases miss.
-
-### Proposed cases
-
-**Suite 0: `eval_notebook_cells`** (shipped — the lane check)
-
-Two cases, both creating a notebook from scratch: `sql_cell_report` proves the direct lane, `python_cell_from_dataframe` proves the kernel lane end to end (sandbox provisioned, code run, result written back). `CellRunsCompleted` grades the `NotebookNodeRun` rows rather than the transcript, because a dispatched run and a finished one look the same in the log.
-
-**Suite A: `eval_notebook_authoring`** (create from an analysis request)
-
-| Case | Prompt shape | What it grades |
-| -------------------------- | ---------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------- |
-| `create_signup_report` | "Create a notebook called X showing weekly `signed_up` counts over the last 8 weeks, with a short summary" | uses `notebooks-create-markdown`, adds a SQL cell that completes, titles it, adds prose |
-| `multi_cell_dependency` | two related SQL steps where the second reads the first's dataframe | dataframe naming, `refs`, dependency order |
-| `embed_saved_insight` | "Put our 'Weekly signups' insight in a notebook" | reuses the seeded insight via a `saved_insight` cell instead of rewriting the SQL |
-| `component_hogql_rejected` | phrasing that tempts a `component` cell with a HogQL source | the tool rejects it; agent recovers to `cell_type: sql` |
-
-**Suite B: `eval_notebook_editing`** (change an existing notebook without breaking it)
-
-| Case | Prompt shape | What it grades |
-| --------------------- | --------------------------------------------------- | --------------------------------------------------------------------------------------------------------- |
-| `local_prose_edit` | "Reword the intro section of notebook X" | edits only the target span; every other section and both cells survive with their `runId`/`result` intact |
-| `insert_cell_after` | "Add a breakdown cell right after the signups cell" | uses `after_node_id` rather than appending at the end |
-| `delete_one_cell` | "Drop the file-size cell" | deletes exactly one cell |
-| `refresh_stale_cells` | seeded notebook where an upstream cell changed | reads `notebooks-get`, re-runs stale cells in dependency order with `notebooks-update-cell` and no `code` |
-
-Eight sandboxed cases is a sensible first suite. Each case is a full agent run, so cost scales linearly and a 20-case suite gets slow to iterate on.
-
-## 5. Data generation
-
-Hedgebox gives you events, insights, dashboards, and flags, but no notebooks. Editing and orientation cases therefore need a seeder.
-
-Follow the synthesizer/seeder split that `data_warehouse` uses:
-
-- `products/notebooks/evals/synthesizer.py` — pure, Django-free, deterministic. Builds the markdown document as frozen dataclasses: section anchors, cell tags with fixed `nodeId`s, dataframe names, and any planted "needle" the case must find. Unit-testable in `products/notebooks/backend/test/`, never inside the `evals/` tree.
-- `products/notebooks/evals/seeders.py` — takes `CustomPromptSandboxContext`, creates the `Notebook` row in the case's team with `content = buildMarkdownNotebookContent(markdown)` equivalent, and (for staleness cases) `NotebookNodeRun` rows so `notebooks-get` reports realistic run state.
-- `products/notebooks/evals/constants.py` — every literal shared by the prompt, the `expected` payload, and the scorers. Titles, anchor strings, node IDs, dataframe names. This is what stops prompt and scorer from drifting apart.
-
-Seeder contract details that bite:
-
-- Synchronous `def seed_x(context) -> dict[str, Any]`. The harness calls it via `asyncio.to_thread`; never make it async.
-- No per-case parameters. Case-specific state means a dedicated seeder function, not a knob on a shared one.
-- Return everything a scorer needs, including `team_id` and the notebook `short_id`. For editing cases also return `markdown_before` so a scorer can diff against it.
-- A seeder exception marks the case an infra error, excluded from averages, so a broken seeder never reads as an agent regression.
-
-For the authoring suite, the seeder is optional: Hedgebox already ships the "Weekly signups" insight that `embed_saved_insight` needs. A tiny seeder that just returns `{"team_id": ...}` is still worth it, because it unlocks end-state scoring.
-
-## 6. Scoring
-
-Stack three layers. Weight the deterministic ones as the backbone and use judges only where the question is genuinely qualitative.
-
-### Layer 1: tool trajectory, from the agent log
-
-Deterministic `Scorer` subclasses reading `LogParser.cached(output["raw_log"], ...)`. Reuse the generics first (`RequiredToolCall`, `NoToolCall`, `LastToolCallNot`, and `CalledTargetTool` from `cli_mcp/scorers.py`). Notebook-specific additions:
-
-- `UsedMarkdownNotebookFlow` — created through `notebooks-create-markdown`, not by hand-assembling a document.
-- `CellsTitled` — every successful sql/python `add-cell` carried a non-empty `title`. The tool description demands it and PR #75471 exists because agents skip it.
-- `ReusedSavedInsight` — a `saved_insight` cell with the seeded short_id, and no SQL cell duplicating the same query.
-- `RanCellsInDependencyOrder` — for update chains, each upstream re-run precedes its dependents' re-runs.
-- `RecoveredFromToolRejection` — the rejected shape was attempted, then a correct call succeeded. Generalizes `RecoveredToCorrectTool`.
-
-### Layer 2: end state, from the database
-
-This is the layer that actually catches the production failure, and it is new for this repo. Async scorers (`AsyncOnlyScorerMixin, Scorer` + `asyncio.to_thread`) that read the notebook back from Postgres using `seed["team_id"]` and `seed["notebook_short_id"]`:
-
-- `NotebookIsMarkdown` — content is still a single `ph-markdown-notebook` node, not clobbered into legacy rich text.
-- `PreservedUnrelatedContent` — every anchor from `seed["markdown_before"]` except the edit target is still present, and every pre-existing cell tag still carries its `nodeId`, `runId`, and `result` props. Direct counter to the clobbering failure.
-- `CellRunSucceeded` — the `NotebookNodeRun` rows for added cells are `DONE` with a non-empty envelope. Catches "wrote a cell that looks right and errors".
-
-`system.notebooks` also exposes a `markdown` column via HogQL, but a direct ORM read from the scorer is simpler and avoids a query round trip.
-
-### Layer 3: LLM judge, for quality
-
-`JudgedScorer` subclasses implementing `_prepare` only:
-
-- `NotebookAnswersQuestion` — given the final markdown, does the notebook actually answer the prompt: right metric, right window, a chart present, prose that a reader can skim.
-- `CellTitlesAreDescriptive` — titles say what the cell shows, not that it is SQL.
-
-Judges get the final markdown from the same DB read, so they are async by construction.
-
-### Scoring discipline
-
-- `score=None` means "this check does not apply to this case" and is dropped from the aggregate. `0.0` means the agent got it wrong, and also covers broken-judge and missing-input paths that must not vanish silently.
-- Count only successful tool calls (`is_error=False`). The agent is allowed to attempt and fail.
-- One implemented branch per scorer, never both `_run_eval_sync` and `_run_eval_async`.
-- Keep `expected` payloads keyed by scorer name so one scorer list can span the whole suite.
-
-## 7. Layout
-
-```text
-products/notebooks/evals/
- __init__.py
- constants.py # shared literals: titles, anchors, node ids, dataframe names
- synthesizer.py # pure deterministic markdown document builder
- seeders.py # ORM installation into the per-case team [shipped]
- scorers.py # trajectory + end-state + judge scorers [shipped]
- eval_notebook_cells.py # both run lanes [shipped]
- eval_notebook_authoring.py
- eval_notebook_editing.py
-```
-
-No `conftest.py` and no `pytest` import in that tree. Unit tests for the synthesizer go under `products/notebooks/backend/test/`.
-
-Suite skeleton:
-
-```python
-from products.posthog_ai.eval_harness.base import SandboxedPublicEval
-from products.posthog_ai.eval_harness.config import SandboxedEvalCase
-from products.posthog_ai.eval_harness.harness.context import EvalContext
-
-
-async def eval_notebook_editing(ctx: EvalContext) -> None:
- await SandboxedPublicEval(
- experiment_name="sandboxed-notebooks-editing-cli",
- cases=[...],
- scorers=[...],
- ctx=ctx,
- )
-```
-
-Use `SandboxedPublicEval` unless a prompt or seed should not leave the machine; public gets you a Braintrust URL and cross-run history. Keep the `-cli` suffix so the naming lines up with the other MCP suites.
-
-## 8. Rollout order
-
-1. ~~Enable `revamped-py-notebooks` in the eval MCP server, register the notebook Temporal workflows, and reclaim kernel sandboxes.~~ Done, with `eval_notebook_cells` as the case that proves it.
-2. Add `eval_notebook_authoring` — the discrimination cases (reuse a saved insight, recover from the component+HogQL rejection) on trajectory scorers.
-3. Add the document seeder plus `PreservedUnrelatedContent`, then `eval_notebook_editing`.
-4. Add judges last. They are the noisiest layer and the easiest to over-fit.
-5. Once stable, run with `--trials 3` to see variance before treating any score as a baseline.
-
-Commands:
-
-```bash
-hogli evals --list | grep notebooks # confirm discovery, import-checks the modules
-hogli evals eval_notebook_cells --eval python_cell_from_dataframe --provider docker
-hogli evals notebooks --provider docker # whole domain; docker because of the kernel lane
-```
-
-Run from a flox shell. Read the transcript path printed on the final line, then the per-case `<case>.jsonl` and `<case>.summary.txt` in the experiment's agent-log directory. The score alone will not tell you why a case failed.
-
-## 9. Open decisions
-
-- **Kernel lane on modal.** Docker-only today, which caps python-cell cases at four concurrent sandboxes. Lifting it means teaching the notebook kernel that `MODAL_EVALS` is a modal backend, which is production code changed for an eval's benefit — worth it only if the python suite grows past what docker can hold.
-- **Legacy notebook tools.** Enabling the flag hides them, so any eval of `notebooks-create` / `notebooks-partial-update` (the 409-conflict path, which has real error volume) needs a per-suite flag lever rather than a process-wide env var.
-- **Judge model cost.** Judges run per case per scorer. Two judges across eight cases is fine; ten is not.
diff --git a/products/notebooks/plan/notebooks_observability_gaps.md b/products/notebooks/plan/notebooks_observability_gaps.md
deleted file mode 100644
index 38b31cf14c90..000000000000
--- a/products/notebooks/plan/notebooks_observability_gaps.md
+++ /dev/null
@@ -1,390 +0,0 @@
-# Notebooks usage observability — gap analysis & instrumentation plan
-
-Goal: instrument Notebooks so we (PostHog, dogfooding) can answer real usage questions
-from our own event stream. Today the telemetry is frontend-only and missing the three
-load-bearing events: **open/view**, **share**, and **origin-attributed create**.
-
-All findings below reference `master` as of this doc's creation.
-
-## The questions we want to answer
-
-1. Do people **re-visit** their notebooks?
-2. Do people **share** their notebooks?
-3. Do people visit **others'** notebooks?
-4. How often do **PostHog Desktop / Max** create notebooks?
-5. How often do people create notebooks via **their own clients (MCP)**?
-6. What kinds of **problems/questions** start in AI/MCP/Code and end up in notebooks?
-
-## Verdict: none are cleanly answerable today
-
-| # | Question | Answerable now? | Blocking gap |
-| --- | --------------------------------- | --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
-| 1 | Re-visit own notebooks | ❌ | No open/view event exists anywhere |
-| 2 | Share notebooks | ❌ | No analytics event on actual share/enable/grant (only an interest CTA + activity-log rows) |
-| 3 | Visit others' notebooks | ❌ | No view event; no owner-vs-viewer property on any event |
-| 4 | Max / PostHog Desktop create rate | ❌ | `notebook created` is origin-agnostic; Max backend path emits no event. PostHog Desktop creates via the MCP `notebooks-create` tool, so it shares the MCP path with Q5 — `creation_source: mcp` alone won't separate them (see note) |
-| 5 | MCP create rate | ❌ | MCP `notebooks-create` → DRF create → activity-log row only, no analytics event, no source marker |
-| 6 | Problems → notebook | ⚠️ DB-join only | Link exists via `short_id`→`AgentArtifact.conversation`→`Conversation.topic`, but not in event stream; fragile; absent for MCP |
-
-## Current state (what exists today)
-
-### Frontend telemetry (the only analytics that exists)
-
-All direct `posthog.capture(...)`; **no** `eventUsageLogic` involvement.
-
-- `notebook created` — `frontend/src/models/notebooksModel.ts:129` — props: `{ short_id }` only.
- Also fires `addProductIntent({ product_type: NOTEBOOKS, intent_context: NOTEBOOK_CREATED })`.
-- `notebook duplicated` — `frontend/src/scenes/notebooks/Notebook/notebookLogic.ts:893` — `{ short_id }`
-- `notebook content changed` — `notebookLogic.ts:1761` — `{ short_id }`
-- `notebook markdown merge conflict` — `notebookLogic.ts:1482` — `{ short_id, conflict_count }`
-- node-level: `notebook node added` (`Nodes/NodeWrapper.tsx:542`), `notebook node created`
- (`Nodes/utils.tsx:150`), `notebook node expanded` (`Nodes/notebookNodeLogic.ts:1339`),
- `notebook node dropped` (`DropAndPasteHandlerExtension.tsx:144`), title add/edit events.
-- paste/drop: `notebook files dropped/pasted`, `notebook table pasted`, `notebook markdown pasted`.
-- `notebook containing filter applied` — `NotebooksTable/ContainsTypeFilter.tsx:65`
-- `pressed interested in notebook sharing` — `Notebook/NotebookShareModal.tsx:43` —
- **interest CTA, NOT an actual share.**
-
-Missing on the frontend: **any open/view event.** `loadNotebookSuccess`
-(`notebookLogic.ts:1844`), `notebookSceneLogic`, `notebookPanelLogic`, `openNotebook` fire
-zero captures.
-
-### Backend creation paths (all emit NO analytics event)
-
-Choke points: the four helpers in `products/notebooks/backend/logic.py`
-(`create_notebook`, `aupsert_notebook`, `create_group_notebook`, `create_account_notebook`)
-and `NotebookSerializer.create` (`products/notebooks/backend/presentation/views/notebook.py:173`).
-
-| Path | Trigger | Location | Analytics | Activity log |
-| ---- | ----------------------------- | ------------------------------------------------------------------------ | --------- | ----------------------------------------- |
-| 1 | Human UI / REST | `notebook.py:173-206` | none | `log_notebook_activity("created")` `:197` |
-| 2 | MCP `notebooks-create` | same as 1 (`mcp/tools.yaml:33`) | none | same as 1 |
-| 3 | Max `create_notebook` tool | `ee/hogai/tools/create_notebook/helpers.py:105-192` (`aupsert_notebook`) | **none** | **none** |
-| 4 | Max `upsert_account_notebook` | `products/customer_analytics/backend/max_tools.py:403` | none | none |
-| 5 | Anomaly investigation agent | `posthog/temporal/ai/anomaly_investigation/workflow.py:149` | none | none |
-| 6 | Group notebook auto-create | `ee/clickhouse/views/groups.py:873` | none | none |
-
-The `Notebook` model (`products/notebooks/backend/models.py:19-64`) has **no origin/source
-field**. AI-created notebooks are attributed to the human user Max acts for and are
-indistinguishable from hand-created ones.
-
-### Sharing (no analytics event on any real share action)
-
-- Public link: `SharingConfigurationViewSet` enable/disable at `posthog/api/sharing.py:463-560`;
- token refresh `:562-621`. Only `log_activity(scope="Notebook", "sharing enabled|disabled")`
- `:533-554` and `"access token refreshed"` `:605-618` — activity log, not analytics.
-- RBAC grants: `ee/api/rbac/access_control.py` — zero `capture`/`report_user_action`.
-- The only sharing analytics is the frontend interest CTA above.
-
-### AI → notebook linkage (structural, not in event stream)
-
-`Notebook.short_id` → `AgentArtifact.short_id` (`ee/hogai/tools/create_notebook/helpers.py:124,181`)
-→ `AgentArtifact.conversation` FK (`products/posthog_ai/backend/models/assistant.py:340`)
-→ `Conversation.topic` (classified from first question, `assistant.py:57-88`).
-Breaks if the artifact/conversation is deleted. MCP path has no conversation at all.
-
-### ⚠️ Note on "PostHog Desktop" vs generic MCP clients (Q4 vs Q5)
-
-PostHog Desktop creates notebooks **via the MCP `notebooks-create` tool** — it is itself an MCP
-client. So it flows through the same path as Q5 (a customer's own MCP client), and a plain
-`creation_source: mcp` property cannot tell the two apart. To split Q4 from Q5 we need a
-**client identifier** on the create event, e.g.:
-
-- the auth principal (personal API key vs project secret key vs OAuth app) used for the call, and/or
-- the MCP client name / user-agent (PostHog Desktop should send an identifiable client id).
-
-Action: when emitting the server-side `notebook created` event, capture `mcp_client` /
-`api_key_type` (or an `agent`-tagged sub-source like `mcp_posthog_code`) so PostHog Desktop is
-distinguishable from third-party MCP usage. Confirm PostHog Desktop sends a stable client id;
-if not, that's a prerequisite fix.
-
-## Root cause
-
-Instrumentation is frontend-only, but Q4/Q5/Q6 are **server-side flows that never touch the
-browser** (Max, MCP, Temporal). The frontend `notebook created` event literally cannot see
-them. The fix must put capture at the **server-side creation choke point**, plus add a few
-frontend events for view/share.
-
-## Proposed instrumentation
-
-### A. Server-side `notebook created` (covers Q4, Q5, Q6)
-
-Emit one analytics event at the facade choke point so every path is covered uniformly.
-Prefer a single emission site — either in the `logic.py` helpers or in `NotebookSerializer.create`
-plus the two Max tools + Temporal + group paths that bypass the serializer.
-
-Event: `notebook created` (server-side)
-Properties:
-
-- `short_id`
-- `creation_source`: `ui | mcp | max_ai | max_account_notebook | temporal_agent | group_auto`
- - `mcp` vs `ui`: distinguish by auth type / user-agent in the DRF request context.
- - `max_ai` / `max_account_notebook` / `temporal_agent` / `group_auto`: pass an explicit
- source arg into the facade helper from each caller.
-- `mcp_client` / `api_key_type` (when `creation_source = mcp`): identify the calling client so
- **PostHog Desktop** (Q4) is separable from a customer's own MCP client (Q5). See the PostHog
- Code note above — plain `creation_source: mcp` is not enough to split Q4 from Q5.
-- `conversation_id`, `topic`: set when `creation_source` is AI-originated (from the
- `AgentArtifact.conversation` on the Max path). Closes Q6 in the event stream.
-- `visibility`, `node_count` (optional context).
-
-**Resolved: keep both, with distinct event names.**
-The hazard is that a human UI create fires two `notebook created` rows for one logical
-creation (browser at `notebooksModel.ts:129` + the new server-side one at DRF `create`),
-while Max/MCP/Temporal/group creates fire only the server event — so a naive
-`count(notebook created)` becomes `(UI creates × 2) + (non-UI creates × 1)`, over-representing
-UI creation.
-
-Resolution:
-
-- Server-side `notebook created` is the **single source of truth** for counts and cross-path
- attribution (`creation_source`, `mcp_client`, conversation/topic).
-- **Rename** the frontend capture to a client-scoped name (e.g. `notebook created (client)`)
- so it survives as the UI-context / session-replay funnel event. Distinct names make
- double-counting structurally impossible — no reliance on query-time filtering.
-- Keep `addProductIntent(...)` (`notebooksModel.ts:133`) as-is regardless — it is activation
- tracking, not the analytics event.
-
-Why not just delete the frontend event: the browser event carries context the server-side
-Python capture cannot reconstruct — `$session_id`/`$window_id` (session-replay linkage to the
-actual creation session), `$current_url`/`$referrer` (which UI surface created it: dashboard vs
-tree vs scene — the server only sees `POST /notebooks`), active `$feature/*` flag enrollment,
-same-session funnel continuity with `notebook content changed` / `notebook node added`, and
-device/browser/geo autocapture. Deleting it loses all of that.
-
-Belt-and-suspenders if both must share a name later: both events carry `short_id` (a natural
-idempotency key), so `count(distinct short_id)` makes double-emission harmless — but the
-distinct-name approach above is preferred and needs no such discipline.
-
-### B. Sharing events (covers Q2)
-
-- `notebook sharing enabled` — at `posthog/api/sharing.py` enable path. Props: `short_id`,
- `share_type: public_link`, `has_password`.
-- `notebook access granted` — at the RBAC grant path. Props: `short_id`, `access_level`,
- `grantee_type` (user/role).
-
-### C. Frontend `notebook opened` (covers Q1 + Q3 in one event)
-
-Emit in the load path (`loadNotebookSuccess` / `notebookSceneLogic`).
-Properties:
-
-- `short_id`
-- `is_creator`: `notebook.created_by?.uuid === user.uuid` — own vs someone else's
-- `user_access_level`
-- `access_source`: `direct | shared_link`
-- `node_count`
-
-### D. Optional / durable
-
-- Add a `creation_source` field to the `Notebook` model (Django migration) so attribution
- survives conversation/artifact deletion and is queryable in Postgres, not just events.
-- `notebook viewed via shared link` on the anonymous `SharingViewerPageViewSet`
- (`posthog/api/sharing.py:1202`) for external-view counting.
-
-## Implementation plan
-
-Ordered as four independently-shippable PRs, earliest-signal-first so each merge unblocks a
-question on its own. PR 1 is pure additive frontend (lowest risk); PR 2 carries the
-double-count resolution and is the largest.
-
-### Preconditions / conventions
-
-- **Event-name constants.** Add the new event names as constants in one place the product
- owns (e.g. `products/notebooks/backend/analytics.py` for server-side, and a matching
- frontend constant) rather than string literals, so FE/BE names can't drift.
-- **Server-side transport.** Use `report_user_action` (`posthog/event_usage.py:396`) for
- request/user-context paths (UI/MCP) — it already handles `SyntheticUser` (project-secret
- API keys) and pulls request analytics props. For **Temporal / Celery** paths use
- `ph_scoped_capture` (`posthog/ph_client.py:63`) — a plain `posthoganalytics.capture()` in
- those workers is silently dropped (see root `CLAUDE.md`).
-- **Skill gate.** Any serializer/viewset edit here must go through `/improving-drf-endpoints`
- first (see `.claude/rules/drf-endpoints.md`).
-- **Isolation.** Emit at the product boundary (serializer + facade functions), not deep in
- `logic.py` domain helpers — cross-product callers (Max, groups) already reach notebooks via
- `facade.api`, so that is the natural single owner of emission.
-
-### PR 1 — Frontend `notebook opened` (unblocks Q1 + Q3)
-
-Additive, no double-count risk.
-
-**Scope: human / browser opens only.** This event is deliberately client-side so it answers the
-human-behavior questions (revisit own, view others') cleanly and carries browser context
-(`$session_id`, replay linkage, referrer). Programmatic reads (MCP, API clients) are **not**
-this event — they are the server-side `notebook read` in PR 2e. Keeping them apart is the same
-discipline as the `created` split: folding agent reads in here would inflate "revisits" and make
-Q1/Q3 unanswerable.
-
-- [x] Emit `posthog.capture('notebook opened', …)` in the load path — `loadNotebookSuccess`
- (`frontend/src/scenes/notebooks/Notebook/notebookLogic.ts`). Gated once per mount via a
- `cache.hasCapturedOpen` flag (the listener also runs on every polling refresh); the flag
- resets on remount, so revisiting counts as a fresh open. Scratchpad and template notebooks
- are excluded.
-- [x] Properties: `short_id`, `is_creator` (`notebook.created_by?.uuid === user.uuid`),
- `user_access_level`, `access_source` (`direct | shared_link`), `node_count`.
-- [x] Payload/exclusion logic extracted to a pure helper `buildNotebookOpenedEvent`
- (`notebookAnalytics.ts`) and unit-tested (`notebookAnalytics.test.ts`) — covers is_creator
- own/other, shared-vs-direct, scratchpad/template/no-notebook skips, and null content/creator.
- The once-per-mount gate stays in the listener (trivial one-liner, not worth a full-mount test).
-
-### PR 2 — Server-side `notebook created` + FE rename (unblocks Q4/Q5/Q6; resolves double-count)
-
-This is the resolution from section A above — ship the two halves together so counting is
-never briefly double-counted on `master`.
-
-**Emission lives in two layers, not at every caller.** All server/background paths already
-funnel through the four create functions in the facade `api.py` — so capture goes _inside_
-those functions and every workflow/viewset that calls them is covered automatically. Callers
-only ever pass a `creation_source`; they never build a capture call. The only path that
-bypasses the facade is the DRF serializer, and it stays separate because `ui` vs `mcp` needs
-the `request` auth context the facade cannot see.
-
-**2a. Shared capture helper** (`products/notebooks/backend/analytics.py`, new)
-
-- [ ] `capture_notebook_created(*, notebook, creation_source, user=None, request=None, team=None, extra=None)`.
- Picks the transport: `report_user_action` when `request`/`user` present (serializer path);
- `ph_scoped_capture` for the request-less facade/background paths.
-- [ ] Properties per section A: `short_id`, `creation_source`
- (`ui | mcp | max_ai | max_account_notebook | temporal_agent | group_auto`),
- `mcp_client` / `api_key_type` (from `request.successful_authenticator` + user-agent when
- `creation_source = mcp`), `conversation_id` + `topic` (AI paths), optional `visibility`,
- `node_count`.
-
-**2b. Emit inside the four facade create functions** (`facade/api.py`) — covers Q4/Q5/Q6
-server paths with zero per-workflow instrumentation.
-
-- [ ] `create_notebook` (`api.py:142`) — add a `creation_source` param (default e.g.
- `"server"`); emit after `logic.create_notebook` returns. The anomaly Temporal workflow
- (`posthog/temporal/ai/anomaly_investigation/workflow.py:149`) then only passes
- `creation_source="temporal_agent"` — a single kwarg, no capture code in the workflow.
-- [ ] `aupsert_notebook` (`api.py:122`) — emit **only when `created` is True** (aupsert also
- updates). Default source `max_ai`; the Max `create_notebook` tool passes
- `conversation_id`/`topic` from the `AgentArtifact.conversation` so Q6 is closed here.
-- [ ] `create_group_notebook` (`api.py:192`) — default source `group_auto`. `_create_notebook_for_group`
- (`ee/clickhouse/views/groups.py:873`) needs **no change**.
-- [ ] `create_account_notebook` (`api.py:196`) — default source `max_account_notebook`; the Max
- account tool (`products/customer_analytics/backend/max_tools.py:403`) needs no change.
-- [ ] These functions take ids, not `Request`, and several run inside `transaction.atomic`
- (group/account) or a Temporal activity — so route their capture through `ph_scoped_capture`,
- and for the transactional paths fire on `transaction.on_commit` to avoid a phantom event if
- the outer request rolls back.
-
-**2c. Serializer (the one non-facade path)** — `NotebookSerializer.create`
-(`presentation/views/notebook.py:190`)
-
-- [ ] After the `log_notebook_activity` call, emit with source derived from `request`: `mcp`
- when the authenticator is an API key / OAuth app, else `ui`; include `mcp_client` /
- `api_key_type` for the `mcp` case. Uses `report_user_action` (has request + user).
-- [ ] Optional cleanup (own follow-up, not required): route this create through
- `facade.api.create_notebook` so the raw `Notebook.objects.create` at `:190` disappears and
- there is a single create entry point. Deferred because the serializer does extra work
- (`annotate_python_nodes`, `short_id` validation) and needs the request for `ui`/`mcp`.
-
-**2d. Frontend rename (kills the double-count)**
-
-- [ ] Rename the browser capture at `frontend/src/models/notebooksModel.ts:129` from
- `notebook created` to a client-scoped name (e.g. `notebook created (client)`). Keep its
- `short_id` prop and **keep `addProductIntent(...)` at `:133` untouched** — it is activation
- tracking, not the analytics event.
-- [ ] Update any saved insights / dashboards that count `notebook created` to point at the
- server-side event (note this in the PR description for the product team).
-
-**2e. Server-side `notebook read` (agent / programmatic access)** — the read counterpart to the
-`created` split. Answers "how often do MCP / API clients read notebooks?" and closes the loop
-"are AI-created notebooks later consumed by agents?" — a signal none of Q1–Q6 capture.
-
-There are **three distinct ways an agent can read a notebook**, and they do not share a choke
-point — this is important, because instrumenting only the REST endpoint silently misses two of
-them:
-
-1. **REST retrieve** — MCP `notebooks-retrieve` (op `notebooks_retrieve`, "Get notebook") and
- `notebooks-list` (op `notebooks_list`) both exist and return the full `content`. They flow
- through `NotebookViewSet.retrieve` (`notebook.py:613`). **← what 2e captures.**
-2. **HogQL / SQL** — the `notebooks` system table (`posthog/hogql/database/schema/system.py:1225`,
- maps to `posthog_notebook`, `access_scope="notebook"`) exposes `content` **and** `text_content`
- as queryable columns. So `SELECT content, text_content FROM notebooks WHERE short_id = …` reads
- the entire body via the query engine — reachable from Max's SQL tool, the MCP query tool, or any
- query API. **This bypasses the REST endpoint entirely** and 2e does **not** see it (see gap
- below).
-3. **Max artifact handler** — `NotebookHandler.alist` (`ee/hogai/artifacts/handlers/notebook.py:47`)
- reads from the **`AgentArtifact` table, not `posthog_notebook`** (docstring: "Notebooks are only
- stored in the ARTIFACT source"). This is Max re-reading its _own artifact snapshot_, not the live
- product notebook — a different signal, intentionally **out of scope** for `notebook read`.
-
-Instrumentation:
-
-- [ ] Emit `notebook read` at the DRF **retrieve** endpoint (`notebook.py:613`), **gated to
- non-session auth**. Session-cookie requests are the browser and are already covered by PR 1's
- `notebook opened` — skip them here to avoid double-counting the frontend's own fetch. Reuse
- the same authenticator classification helper as the `ui` vs `mcp` split in 2c.
-- [ ] Properties: `short_id`, `read_source` (`mcp | api`), `mcp_client` / `api_key_type`
- (from `request.successful_authenticator` + user-agent), `is_creator`, `user_access_level`.
-- [ ] Scope to single-notebook retrieve. `notebooks-list` is a browse/discovery action with
- different intent and cardinality — leave it out of `notebook read` (capture separately later
- if list usage becomes a question).
-- [ ] **Do not** capture at the facade `get_notebook` / `aget_notebook` — those are called for
- permission checks (`logic.acan_user_edit_notebook`) and Max's dedup existence-check
- (`ee/hogai/tools/create_notebook/helpers.py:124`), so capturing there would fire constantly
- on internal machinery, not intentful reads.
-
-**Known gap — the SQL read path is not covered.** An agent that pulls a notebook via
-`SELECT … FROM notebooks` (path 2) produces no `notebook read` event, so agent-consumption counts
-from 2e are a **lower bound**. Capturing it would mean inspecting executed HogQL for a reference to
-the `notebooks` table in the query pipeline — higher effort, noisier (joins, `count()` over the
-table, permission-driven scans), and easy to over-count. Deferred; call it out explicitly in the PR
-so the metric is read as "REST/MCP reads," not "all agent reads." If SQL-based reads turn out to
-matter, the cleanest follow-up is a dedicated marker in the query layer when the `notebooks` table
-is selected from — not a broadening of 2e.
-
-Verification for PR 2: create one notebook through each of the six paths and confirm exactly
-one server-side `notebook created` per creation with the right `creation_source`, and that a
-UI create no longer produces two `notebook created` rows. For 2e: an MCP retrieve emits one
-`notebook read` with `read_source: mcp`, while opening the same notebook in the browser emits
-`notebook opened` (PR 1) and **no** `notebook read`.
-
-### PR 3 — Sharing events (unblocks Q2)
-
-- [ ] `notebook sharing enabled` — `SharingConfigurationViewSet` enable path
- (`posthog/api/sharing.py:463-560`, next to the `log_activity` at `:533`). Props: `short_id`,
- `share_type: public_link`, `has_password`. Emit on the enable transition only, not on
- idempotent re-saves.
-- [ ] `notebook access granted` — RBAC grant path (`ee/api/rbac/access_control.py`). Props:
- `short_id`, `access_level`, `grantee_type` (`user | role`). Guard the viewset edits with
- `/improving-drf-endpoints`.
-
-### PR 4 — Optional durability
-
-- [ ] Add a `creation_source` field to the `Notebook` model (Django migration via
- `/django-migrations`) so AI attribution survives conversation/artifact deletion and is
- queryable in Postgres. Backfill is not required — new rows only.
-- [ ] `notebook viewed via shared link` on the anonymous `SharingViewerPageViewSet`
- (`posthog/api/sharing.py:1202`) for external-view counting.
-
-### PR 5 — Optional: SQL read path for `notebook read` (closes the 2e gap)
-
-Covers the read surface 2e cannot see — agents pulling notebook bodies via
-`SELECT content, text_content FROM notebooks` against the `notebooks` HogQL system table
-(`posthog/hogql/database/schema/system.py:1225`), which bypasses the REST endpoint entirely.
-
-**Prerequisite (not done here): analyze overall SQL access metrics first.** Before instrumenting,
-understand how notebook-table reads sit within general HogQL/query usage — volume, who runs them
-(Max vs MCP query tool vs API), and how to separate an intentful body read from incidental scans
-(`count()`, joins, permission-driven access). That analysis decides whether a per-table read event
-is even meaningful or just noise. Scope it as its own investigation.
-
-- [ ] (After the analysis) Emit `notebook read` with `read_source: sql` from the query layer when
- an executed HogQL query selects from the `notebooks` table. Mark it clearly so REST/MCP vs SQL
- reads stay separable and 2e's headline metric is not silently redefined.
-- [ ] Guard against over-counting: exclude `count()`-only / metadata scans and permission-check
- queries; ideally fire only when `content` / `text_content` columns are actually projected.
-
-### Coverage check (map back to the questions)
-
-| Question | Unblocked by |
-| ------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| Q1 re-visit own | PR 1 (`is_creator = true` on `notebook opened`) |
-| Q2 share | PR 3 |
-| Q3 visit others' | PR 1 (`is_creator = false`) |
-| Q4 Max / PostHog Desktop create | PR 2 (`creation_source` + `mcp_client`/`api_key_type`) |
-| Q5 MCP create | PR 2 (`creation_source = mcp`) |
-| Q6 problems → notebook | PR 2 (`conversation_id` + `topic` on AI paths) |
-| Q7 agents read notebooks (+ AI-created consumed later) | PR 2e (`notebook read`, `read_source`) — REST/MCP reads, a lower bound; SQL `SELECT FROM notebooks` reads deferred to optional PR 5 (needs SQL-access analysis first) |