: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
feat(agent_platform): kernel skills + MCP builder playbooks (#66211)
Danilo Campos2236209dd20c
diff --git a/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/auditing-the-fleet/SKILL.md b/products/agent_platform/backend/kernel_skills/auditing-the-fleet/SKILL.mdsimilarity index 93%rename from products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/auditing-the-fleet/SKILL.mdrename to products/agent_platform/backend/kernel_skills/auditing-the-fleet/SKILL.mdindex e21e21b7a784..48e3a24e2e22 100644--- a/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/auditing-the-fleet/SKILL.md+++ b/products/agent_platform/backend/kernel_skills/auditing-the-fleet/SKILL.md@@ -1,3 +1,10 @@+---+name: auditing-the-fleet+description: The fleet-wide audit — sweep every agent, mine recent sessions for failures/anomalies, classify root causes, and branch a DRAFT proposal per fix (never freeze/promote); write a report to memory. Load when asked to audit all agents or what's underperforming.+agents:+ - agent-builder+---+# Skill — auditing the fleetThe fleet-wide sweep. When the user asks for a fleet-wide sweep@@ -9,9 +16,9 @@ the durable outputs that survive past the conversation.This skill is the orchestration. It leans on two others:- `debugging-sessions` — the per-session failure taxonomy + how to- read an event log. Load it the first time you open a bad session.-- `editing-agents-safely` — the draft → validate mechanics. Load it- before you branch your first proposal.+ read an event log. Fetch the playbook the first time you open a bad session.+- `editing-agents-safely` — the draft → validate mechanics. Fetch the+ playbook before you branch your first proposal.## What a fleet-wide sweep changes@@ -89,7 +96,7 @@ behind it is a guess, and guesses are how this report loses trust.For the population view — failure-rate, cost, and p95 latency rolledup per agent, or "which sessions tripped up this week" in one query —-load `skills/querying-ai-observability` and HogQL the `$ai_*` events+load the `querying-ai-observability` playbook and HogQL the `$ai_*` eventsthe runner captured into this team's project. It's cheaper thanretrieving every session and surfaces systemic patterns (one rootcause across many sessions) the per-session view misses; use it todiff --git a/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/safety-and-boundaries/SKILL.md b/products/agent_platform/backend/kernel_skills/safety-and-boundaries/SKILL.mdsimilarity index 96%rename from products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/safety-and-boundaries/SKILL.mdrename to products/agent_platform/backend/kernel_skills/safety-and-boundaries/SKILL.mdindex 6f9b225993ad..03edf0576860 100644--- a/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/safety-and-boundaries/SKILL.md+++ b/products/agent_platform/backend/kernel_skills/safety-and-boundaries/SKILL.md@@ -1,3 +1,10 @@+---+name: safety-and-boundaries+description: Hard rules — what the Agent Builder MUST NOT do regardless of user request. Load IMMEDIATELY if a request feels like it crosses into raw-secret handling, unprompted promotion, irreversible deletion, or impersonation of another user.+agents:+ - agent-builder+---+# Skill — safety and boundariesThe hard rules. Load this immediately if a request even slightly@@ -36,7 +43,7 @@ secrets. If the user pastes one:paste secrets into chat.")2. Do not echo it, do not put it in a tool call, do not store it.3. Initiate the punch-out flow for whatever they were trying to- set. See `skills/secrets-and-integrations`.+ set. See the `secrets-and-integrations` playbook.4. Recommend they rotate the leaked key.This includes "for testing" — there is no test scenario thatdiff --git a/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/using-the-console-ui/SKILL.md b/products/agent_platform/backend/kernel_skills/using-the-console-ui/SKILL.mdsimilarity index 96%rename from products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/using-the-console-ui/SKILL.mdrename to products/agent_platform/backend/kernel_skills/using-the-console-ui/SKILL.mdindex 94dc6f860fbe..4a5aed087bd9 100644--- a/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/using-the-console-ui/SKILL.md+++ b/products/agent_platform/backend/kernel_skills/using-the-console-ui/SKILL.md@@ -1,3 +1,10 @@+---+name: using-the-console-ui+description: How to drive PostHog Code's read panel as the user works with you — focus_* etiquette, when to call toast, how to handle 'follow mode' being off. Load when the session client kind is `posthog-code`.+agents:+ - agent-builder+---+# Skill — using the PostHog Code UIHow to drive PostHog Code's read panel while you work, so@@ -26,7 +33,7 @@ the tool-call card and the runner parks the session while the userfills it in. Your call returns a synthetic `{queued:true, interactive:true, call_id}`envelope immediately; end the turn cleanly and the real outcomearrives as a wake message on a fresh turn (see-`skills/secrets-and-integrations` Path A for the full loop). Tools+the `secrets-and-integrations` playbook Path A for the full loop). Toolsthat need user input belong here; tools the host can fulfillsilently (navigation, toasts, context reads) stay synchronous.diff --git a/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/working-outside-the-console/SKILL.md b/products/agent_platform/backend/kernel_skills/working-outside-the-console/SKILL.mdsimilarity index 95%rename from products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/working-outside-the-console/SKILL.mdrename to products/agent_platform/backend/kernel_skills/working-outside-the-console/SKILL.mdindex f6e3e232acc7..0c3e95366b17 100644--- a/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/working-outside-the-console/SKILL.md+++ b/products/agent_platform/backend/kernel_skills/working-outside-the-console/SKILL.md@@ -1,3 +1,10 @@+---+name: working-outside-the-console+description: Operating without a UI — MCP / IDE / Slack mode. How to compensate for missing client tools, how to be useful in a text-only chat. Load when the session client kind is NOT `posthog-code`.+agents:+ - agent-builder+---+# Skill — working outside PostHog CodeHow to be useful when there is no UI — load when the sessiondiff --git a/products/agent_platform/backend/logic/kernel_skills.py b/products/agent_platform/backend/logic/kernel_skills.pynew file mode 100644index 000000000000..4333042453c2--- /dev/null+++ b/products/agent_platform/backend/logic/kernel_skills.py@@ -0,0 +1,232 @@+"""Platform-defined *kernel* skills — code-locked operator behaviour the freeze+step injects into an agent's bundle, never authored through the API.++The store (`skill_refs` → the llma-skill store) is the **only** author path into+a bundle's `skills/`. Kernel skills are the platform's complement to that: they+must move in lockstep with the implementation and be identical across every+account, so they can't live in the DB (where a frozen agent could pin a stale+copy while the platform moved on) and they can't be author-authored (there is no+`skills` field on any author endpoint). The freeze step reads them from this+package and materializes them alongside the resolved store skills.++Everything is data-driven: each kernel skill is a folder under `kernel_skills/`+holding a `SKILL.md` whose YAML frontmatter carries its `description` and an+`agents` mapping declaring which agents receive it:++ ---+ name: safety-and-boundaries+ description: One line, <= 280 chars. The system-prompt index line; drives load-skill.+ agents: ["*"] # every agent (the shared baseline), OR+ agents: [agent-builder] # only these slugs (a per-agent skill)+ ---++Adding a kernel skill is "drop a folder."++Two read paths, deliberately split:+ - `_all_kernel_skills()` validates the **whole** shipped set strictly (raises on+ any malformation). It's exercised by a unit test, so a bad folder fails CI+ before merge.+ - `kernel_skills_for(slug)` is the **runtime** path. It only fully validates the+ folders that target the agent being frozen, and skips obvious non-skill+ directories — so a malformed folder for one agent can't take down freeze for+ every other tenant's agent.++NOTE: kernel selection keys on `revision.application.slug`. Per-slug skills are+safe to target by name only because human-readable slugs are gated behind a+first-party allowlist (`AGENT_PLATFORM_EXPLICIT_SLUG_TEAM_IDS`); normal teams get+opaque server-minted slugs and can't self-assign e.g. `agent-builder`. An+`agents: ["*"]` skill bypasses that gate and reaches EVERY agent — use it only+for genuinely universal platform content.+"""++import re+from dataclasses import dataclass+from pathlib import Path++import yaml++_KERNEL_SKILLS_DIR = Path(__file__).resolve().parent.parent / "kernel_skills"+# Frontmatter `agents` wildcard: the skill goes to every agent (the baseline).+_WILDCARD = "*"+# Mirror of the janitor's RESOURCE_ID_REGEX (agent-shared typed-bundle.ts) — the+# id must be a valid bundle folder name the janitor's skill PUT will accept.+_RESOURCE_ID_RE = re.compile(r"^[a-z0-9](?:[a-z0-9_-]*[a-z0-9])?$")+# The janitor caps a derived skill description at this length (deriveSkillDescription).+_DESCRIPTION_MAX = 280+++@dataclass(frozen=True)+class KernelSkill:+ """A platform kernel skill resolved to its bundle-ready form. `agents` is the+ set of slugs it applies to, or `{"*"}` for every agent."""++ id: str+ description: str+ body: str+ agents: frozenset[str]++ def applies_to(self, slug: str) -> bool:+ return _WILDCARD in self.agents or slug in self.agents++ def put_skill_payload(self) -> dict:+ """Body for the janitor ``PUT /revisions/:id/skills/:id`` call — the same+ shape ``ResolvedSkill`` uses, so store and kernel skills materialize+ through one code path. `body` keeps its frontmatter, so the freeze+ derives the same `description` the index here reports (the loader+ enforces that parity)."""+ return {"description": self.description, "body": self.body, "files": []}+++def _frontmatter_block(raw: str) -> str | None:+ """The YAML between the leading ``---`` fences, or None if not well-formed.+ Requires whole-line fences, matching the janitor's `splitFrontmatter`."""+ if not raw.startswith("---\n"):+ return None+ end = raw.find("\n---\n", len("---\n") - 1)+ if end == -1:+ return None+ return raw[len("---\n") : end + 1]+++def _janitor_derived_description(block: str) -> str:+ """Replicate the janitor's freeze-time `deriveSkillDescription`: the value of+ the FIRST physical `description:` line (quotes stripped), capped at 280. This+ — not the full YAML scalar — is what lands in `spec.skills[].description` and+ drives the model's load decision, so the loader checks the file matches it."""+ for line in block.split("\n"):+ m = re.match(r"^description:\s*(.*)$", line)+ if m:+ return m.group(1).strip().strip("\"'")[:_DESCRIPTION_MAX]+ return ""+++def _normalize_agents(raw_agents: object) -> list[str]:+ """The `agents` frontmatter as a list of strings. A bare string becomes a+ one-element list; anything else (missing, number, mapping) becomes empty."""+ if isinstance(raw_agents, str):+ return [raw_agents]+ if isinstance(raw_agents, list):+ return [str(a) for a in raw_agents]+ return []+++def _agents_of(folder: Path) -> list[str] | None:+ """Cheap read of just the `agents` mapping, for runtime applicability scoping.+ Returns None when it can't be determined — the runtime path then skips the+ folder rather than fully validating (and possibly raising on) a folder that+ doesn't even target the agent being frozen."""+ md = folder / "SKILL.md"+ if not md.is_file():+ return None+ # Force UTF-8: every shipped SKILL.md carries em dashes, and `read_text()`'s+ # locale default (e.g. ASCII under `LC_ALL=C`) would raise on the first folder+ # — taking down freeze for every agent, the exact blast radius this path avoids.+ block = _frontmatter_block(md.read_text(encoding="utf-8"))+ if block is None:+ return None+ try:+ fm = yaml.safe_load(block)+ except yaml.YAMLError:+ return None+ if not isinstance(fm, dict):+ return None+ return _normalize_agents(fm.get("agents"))+++def _load_skill(folder: Path) -> KernelSkill:+ """Strict load + validate. Raises ``ValueError`` on any malformation — a+ code-bundled set, so this is a deploy/CI-time fail-fast, not a runtime risk."""+ sid = folder.name+ md = folder / "SKILL.md"+ if not md.is_file():+ raise ValueError(f"kernel skill '{sid}' has no SKILL.md")+ if not _RESOURCE_ID_RE.match(sid) or len(sid) > 64:+ raise ValueError(f"kernel skill folder '{sid}' is not a valid skill id (lowercase/digits/-/_, <=64)")+ raw_bytes = md.read_bytes()+ # The janitor reads the raw bundle bytes from S3 (no universal-newline+ # translation), so a CR would leave its single-line `description:` derivation+ # holding a trailing `\r` that Python's parse never sees — a silent mismatch.+ # Require LF. Checked on the bytes because `read_text()` strips the CR.+ if b"\r" in raw_bytes:+ raise ValueError(f"kernel skill '{sid}' must use LF line endings (no CR)")+ raw = raw_bytes.decode("utf-8")+ block = _frontmatter_block(raw)+ if block is None:+ raise ValueError(f"kernel skill '{sid}' is missing a `---`-fenced YAML frontmatter block")+ try:+ fm = yaml.safe_load(block)+ except yaml.YAMLError as e:+ # Re-raise as ValueError so broken YAML joins the rest of the malformation+ # contract (`_all_kernel_skills`' CI check + the parameterized rejection tests).+ raise ValueError(f"kernel skill '{sid}' has invalid YAML frontmatter: {e}") from e+ if not isinstance(fm, dict):+ raise ValueError(f"kernel skill '{sid}' frontmatter is not a YAML mapping")++ description = str(fm.get("description") or "").strip()+ if not description:+ raise ValueError(f"kernel skill '{sid}' is missing a `description` frontmatter line")+ # The janitor re-derives the description from the body (single physical line,+ # <=280) and discards the payload value. If the file's `description` spans+ # multiple lines or exceeds the cap, the model would silently get a truncated+ # load signal — refuse it here so it fails at deploy, not freeze.+ if _janitor_derived_description(block) != description:+ raise ValueError(+ f"kernel skill '{sid}' description must be a single line of <= {_DESCRIPTION_MAX} chars "+ "(the freeze derivation reads only the first physical line)"+ )++ agents = _normalize_agents(fm.get("agents"))+ if not agents:+ raise ValueError(f"kernel skill '{sid}' needs an `agents` frontmatter mapping (a slug list or \"*\")")+ for a in agents:+ if a != _WILDCARD and not _RESOURCE_ID_RE.match(a):+ raise ValueError(f"kernel skill '{sid}' has an invalid agent slug {a!r} in its `agents` mapping")+ if _WILDCARD in agents and len(agents) > 1:+ raise ValueError(f"kernel skill '{sid}' mixes \"{_WILDCARD}\" with specific slugs — use one or the other")++ return KernelSkill(id=sid, description=description, body=raw, agents=frozenset(agents))+++def _skill_dirs() -> list[Path]:+ """Candidate skill folders. Skips `.`/`_`-prefixed directories (editor/tooling+ cruft like `__pycache__` or `.DS_Store` dirs) so a stray directory can't wedge+ freeze — but keeps any letter/digit-named dir so a genuinely mis-named skill+ folder still trips `_load_skill`'s id check rather than vanishing silently."""+ # A deploy variant that ships the Django code without `kernel_skills/` must+ # degrade to "no kernel skills", not 500 every freeze on a missing-dir+ # `iterdir()`. The strict CI check (`_all_kernel_skills`) still guards the+ # in-repo set, so an accidentally-empty dir can't slip kernel skills out.+ if not _KERNEL_SKILLS_DIR.is_dir():+ return []+ return sorted(p for p in _KERNEL_SKILLS_DIR.iterdir() if p.is_dir() and not p.name.startswith((".", "_")))+++def all_kernel_skill_ids() -> frozenset[str]:+ """Every shipped kernel skill id, across all `agents` mappings — a cheap,+ parse-free folder-name read (no malformation risk). Freeze uses this to tell+ platform-owned inline skill entries (a former/cross-team kernel id carried in a+ forked `spec.skills[]`) apart from genuine pre-store author content: the former+ is the platform's to drop and re-inject, the latter must block the freeze."""+ return frozenset(f.name for f in _skill_dirs())+++def _all_kernel_skills() -> tuple[KernelSkill, ...]:+ """Strictly load + validate the whole shipped set. Exercised by a unit test so+ a malformed kernel folder fails CI before it can reach a freeze."""+ return tuple(_load_skill(f) for f in _skill_dirs())+++def kernel_skills_for(slug: str) -> list[KernelSkill]:+ """The kernel skills an agent receives: every `*`-mapped skill (the baseline)+ plus those naming this slug. Only folders that target this slug are fully+ validated, so a malformed folder for one agent can't 500 the freeze of an+ unrelated agent (the strict `_all_kernel_skills()` CI check guards the shipped+ set). Empty for an agent no kernel skill targets."""+ out: list[KernelSkill] = []+ for folder in _skill_dirs():+ agents = _agents_of(folder)+ if agents is None:+ continue+ if _WILDCARD in agents or slug in agents:+ out.append(_load_skill(folder))+ return outdiff --git a/products/agent_platform/backend/presentation/views.py b/products/agent_platform/backend/presentation/views.pyindex 00ae3165a5d8..0b68cf8539b6 100644--- a/products/agent_platform/backend/presentation/views.py+++ b/products/agent_platform/backend/presentation/views.py@@ -73,6 +73,7 @@ from posthog.security.outbound_proxy import internal_requestsfrom ..db import WRITER_DBfrom ..logic.internal_jwt import AgentInternalAudience, encode_agent_internal_jwtfrom ..logic.janitor_client import JanitorClient, JanitorClientError, default_client+from ..logic.kernel_skills import all_kernel_skill_ids, kernel_skills_forfrom ..logic.posthog_identity_app import provision_posthog_identity_appsfrom ..logic.skill_resolution import assert_skill_refs_readable, resolve_skill_ref, stamp_skill_provenancefrom ..logic.spec_schema import missing_required_secrets@@ -2050,10 +2051,16 @@ class AgentRevisionViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):return Response({**result, "events_url": events_url, "interactivity_url": interactivity_url})# DRF routes the typed bundle verbs across @action + .mapping.<verb>- # chains. Three separate @action decorators with the same url_path- # don't merge — the last one registered wins and the others 405. So- # GET+PUT under /bundle/, PUT+DELETE under /skills/<id>/ and- # /tools/<id>/ share a single @action with mapping chains below.+ # chains. Separate @action decorators with the same url_path don't merge —+ # the last one registered wins and the others 405 — so GET+PUT under /bundle/+ # share a single @action with a mapping chain below.+ # NOTE: skill folders are deliberately NOT author-writable through Django.+ # There is no `skills/<id>` author action (only agent_md/spec/skill_refs/tools);+ # `skills/` is populated only at freeze (resolved store `skill_refs` + injected+ # platform kernel skills). The janitor's `PUT/DELETE /revisions/:id/skills/:id`+ # is internal-only, reachable solely via `janitor_client.put_skill`/`delete_skill`+ # during freeze. Do NOT proxy it through to authors — that re-opens the+ # store-only boundary kernel skills + skill_refs are built to enforce.# ── typed bundle authoring API ──────────────────────────────────────# Django@@ -2380,6 +2387,24 @@ class AgentRevisionViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):r.alias: {"from_template": r.from_template, "version": r.version, "source_version_id": r.source_version_id}for r in resolved_skills}+ # Platform kernel skills — code-locked operator behaviour injected from+ # backend code, never authored through the API. The store (`skill_refs`)+ # is the only author path into `skills/`, so an author can't supply or+ # forge these; the freeze materializes them alongside the resolved store+ # skills below and merges both into the derived `spec.skills[]`. Empty for+ # any agent the platform hasn't designated (see logic/kernel_skills.py).+ # Per-slug targeting is safe to key on the slug only because human-readable+ # slugs are gated behind a first-party allowlist+ # (AGENT_PLATFORM_EXPLICIT_SLUG_TEAM_IDS); a normal team gets an opaque+ # server-minted slug it can't use to claim e.g. `agent-builder`.+ kernel_skills = kernel_skills_for(revision.application.slug)+ kernel_ids = {k.id for k in kernel_skills}+ collisions = sorted(kernel_ids & aliases)+ if collisions:+ raise ValidationError(+ f"Skill reference alias(es) {collisions} collide with a platform kernel skill id — "+ "rename the alias in `skill_refs`."+ )# Migration guard for pre-store agents: a revision forked from one authored# before the store became canonical carries inline skill entries in its# spec with no store provenance. Discriminate on `source_version_id`, NOT@@ -2392,16 +2417,30 @@ class AgentRevisionViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):# left by a failed prior freeze — absent from the spec — is swept on retry# rather than misclassified as legacy. An unreferenced inline skill is# refused: silently dropping it would lose real content.+ #+ # Exempt ANY shipped kernel id (`all_kernel_ids`), not just this agent's+ # applicable set (`kernel_ids`): an inline entry whose id is a platform+ # kernel skill is platform-owned content the author can't author or remove+ # (there is no `skills` write path). It reaches a fork two ways the guard+ # must not brick — a kernel de-designated for this slug, or a cross-team+ # `clone_from` that lands an opaque slug no kernel targets. In both the id+ # is still a shipped kernel, so it's safe to let through: the sweep below+ # drops it from the bundle when it's no longer applicable, re-injecting only+ # what `kernel_ids` still designates. Only a genuinely deleted kernel folder+ # falls through to the legacy path, which is the honest outcome.+ all_kernel_ids = all_kernel_skill_ids()legacy_orphans = sorted(sidfor s in ((revision.spec or {}).get("skills") or [])- if (sid := s.get("id")) and not s.get("source_version_id") and sid not in aliases+ if (sid := s.get("id"))+ and not s.get("source_version_id")+ and sid not in aliases+ and sid not in all_kernel_ids)if legacy_orphans:raise ValidationError(- f"Revision carries inline skill(s) {legacy_orphans} not backed by a store reference "- "(authored before the skill store became canonical). Recreate them in the skill store and set "- "`skill_refs` before freezing — otherwise the freeze would silently drop them."+ f"Revision carries inline skill(s) {legacy_orphans} not backed by a store reference. "+ "These predate the skill store — recreate them in the store and set `skill_refs` before freezing.")# Materialize the resolved refs into the bundle, then seal. Skills are# store-only — nothing else writes `skills/` — so the frozen bundle must@@ -2410,6 +2449,7 @@ class AgentRevisionViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):# freeze already sealed the bundle (its HTTP response was lost): the# janitor refuses edits to a sealed bundle, and its `freeze` is idempotent# — it re-derives the sha + spec from what's already sealed.+ bundle_already_sealed = Falsetry:manifest = janitor_client.manifest(str(revision.id))# Only `skills/<alias>/<file>` paths whose alias matches the janitor's@@ -2427,7 +2467,14 @@ class AgentRevisionViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):# leave a window where the draft has neither the old nor the new skill.for resolved in resolved_skills:janitor_client.put_skill(str(revision.id), resolved.alias, resolved.put_skill_payload())- for stale in bundle_aliases - aliases:+ # Inject the platform kernel skills the same way — re-written from+ # backend code every freeze, so the frozen bundle always carries the+ # current bytes (never a stale DB copy) and stays in lockstep.+ for kskill in kernel_skills:+ janitor_client.put_skill(str(revision.id), kskill.id, kskill.put_skill_payload())+ # Sweep store-orphan folders, but keep the kernel folders just written:+ # `kernel_ids` are legitimate, not leftovers from a removed ref.+ for stale in bundle_aliases - aliases - kernel_ids:try:janitor_client.delete_skill(str(revision.id), stale)except JanitorClientError as e:@@ -2441,6 +2488,7 @@ class AgentRevisionViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):# to the idempotent freeze below. Any other error is a real failure.if not _is_sealed_bundle_conflict(e):raise JanitorUpstreamError(e) from e+ bundle_already_sealed = Trueresult = self._call(janitor_client.freeze, str(revision.id))# Pin resolved versions back into `skill_refs` so an unpinned ref becomes a# concrete pin after its first freeze. A fork copies `skill_refs` verbatim,@@ -2459,6 +2507,29 @@ class AgentRevisionViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):derived_spec = result.get("derived_spec")if derived_spec is not None:stamp_skill_provenance(derived_spec, provenance_by_alias)+ # Post-seal invariant: every kernel skill we injected must be present in+ # the sealed spec. A 2xx `put_skill` whose body didn't materialize (S3+ # eventual consistency, a future janitor derivation change) would+ # otherwise flip a `ready` agent live while silently missing a kernel+ # skill — e.g. `safety-and-boundaries`. Fail before the draft→ready flip+ # so the revision stays a draft and the freeze is retriable.+ #+ # Only enforce it when we actually (re)wrote the bundle this freeze. On+ # the sealed-bundle fall-through the bytes are immutable and `put_skill`+ # can no longer touch them — the freeze that sealed them already ran this+ # check. Re-running it here would permanently wedge the draft whenever+ # the kernel set drifted (grew/renamed) after that seal, or whenever a+ # concurrent freeze won the seal first — turning a lost-response retry+ # into a dead end. The conditional draft→ready UPDATE below is what keeps+ # concurrent freezes consistent in that case.+ if not bundle_already_sealed:+ materialized_ids = {s.get("id") for s in derived_spec.get("skills") or []}+ missing_kernel = sorted(kernel_ids - materialized_ids)+ if missing_kernel:+ raise APIException(+ detail=f"Freeze sealed without kernel skill(s) {missing_kernel}; materialization failed — "+ "revision left in draft. Retry the freeze."+ )fields["spec"] = derived_spec# Conditional draft→ready flip: only the first freeze of a draft wins, so# two concurrent freezes can't both stamp the row, and a `set_skill_refs`diff --git a/products/agent_platform/backend/tests/test_freeze_skill_refs.py b/products/agent_platform/backend/tests/test_freeze_skill_refs.pyindex 05e18112df18..05fdc6869796 100644--- a/products/agent_platform/backend/tests/test_freeze_skill_refs.py+++ b/products/agent_platform/backend/tests/test_freeze_skill_refs.py@@ -11,6 +11,7 @@ from posthog.models.utils import generate_random_token_personal, hash_key_valuefrom products.skills.backend.models.skills import LLMSkill, LLMSkillFilefrom ..logic.janitor_client import JanitorClientError+from ..logic.kernel_skills import KernelSkillfrom ..models import AgentApplication, AgentRevision@@ -170,6 +171,211 @@ class TestFreezeResolvesSkillRefs(APIBaseTest):client.delete_skill.assert_not_called()client.freeze.assert_not_called()+ @staticmethod+ def _kernel(skill_id: str) -> KernelSkill:+ body = f"---\nname: {skill_id}\ndescription: {skill_id} desc\nagents:\n- freeze-agent\n---\n\n# {skill_id}"+ return KernelSkill(id=skill_id, description=f"{skill_id} desc", body=body, agents=frozenset({"freeze-agent"}))++ @patch("products.agent_platform.backend.presentation.views.kernel_skills_for")+ @patch("products.agent_platform.backend.presentation.views._janitor")+ def test_freeze_injects_kernel_skills_alongside_store_refs(+ self, mock_janitor: MagicMock, mock_kernel: MagicMock+ ) -> None:+ # A designated agent's kernel skills (platform code) materialize at freeze+ # next to the resolved store ref — both land in `skills/` via the janitor,+ # and the kernel body keeps its frontmatter so freeze derives its description.+ mock_kernel.return_value = [self._kernel("safety-and-boundaries")]+ client = mock_janitor.return_value+ client.put_skill = MagicMock(return_value={"ok": True})+ client.delete_skill = MagicMock(return_value={"ok": True})+ client.manifest.return_value = {"files": [{"path": "agent.md"}]}+ client.freeze.return_value = {+ "bundle_sha256": "a" * 64,+ "derived_spec": {+ "model": "x",+ "triggers": [],+ "skills": [+ {"id": "triage", "path": "skills/triage/SKILL.md", "description": "d"},+ {+ "id": "safety-and-boundaries",+ "path": "skills/safety-and-boundaries/SKILL.md",+ "description": "k",+ },+ ],+ "tools": [],+ },+ }++ res = self.client.post(self.url)+ self.assertEqual(res.status_code, 200, res.content)+ # Kernel selection keys on the agent's slug — pin the call arg so swapping+ # the call site to anything else can't silently disable kernel injection.+ mock_kernel.assert_called_once_with(self.application.slug)+ materialized = {call.args[1] for call in client.put_skill.call_args_list}+ self.assertEqual(materialized, {"triage", "safety-and-boundaries"})+ kernel_call = next(c for c in client.put_skill.call_args_list if c.args[1] == "safety-and-boundaries")+ self.assertIn("name: safety-and-boundaries", kernel_call.args[2]["body"])++ @patch("products.agent_platform.backend.presentation.views.kernel_skills_for")+ @patch("products.agent_platform.backend.presentation.views._janitor")+ def test_freeze_does_not_sweep_kernel_skill_folder(self, mock_janitor: MagicMock, mock_kernel: MagicMock) -> None:+ # The kernel folder is in the bundle but backed by no store ref — the sweep+ # must keep it (it's platform-injected, not a removed-ref leftover) while+ # still sweeping a genuine orphan.+ mock_kernel.return_value = [self._kernel("safety-and-boundaries")]+ client = mock_janitor.return_value+ client.put_skill = MagicMock(return_value={"ok": True})+ client.delete_skill = MagicMock(return_value={"ok": True})+ client.manifest.return_value = {+ "files": [+ {"path": "agent.md"},+ {"path": "skills/safety-and-boundaries/SKILL.md"},+ {"path": "skills/stale/SKILL.md"},+ {"path": "skills/triage/SKILL.md"},+ ]+ }+ client.freeze.return_value = {+ "bundle_sha256": "a" * 64,+ # The sealed spec carries the injected kernel skill (the freeze asserts+ # every kernel id materialized before flipping to ready).+ "derived_spec": {+ "model": "x",+ "triggers": [],+ "skills": [{"id": "safety-and-boundaries", "path": "skills/safety-and-boundaries/SKILL.md"}],+ "tools": [],+ },+ }++ res = self.client.post(self.url)+ self.assertEqual(res.status_code, 200, res.content)+ mock_kernel.assert_called_once_with(self.application.slug)+ swept = {call.args[1] for call in client.delete_skill.call_args_list}+ self.assertEqual(swept, {"stale"})++ @patch("products.agent_platform.backend.presentation.views.kernel_skills_for")+ @patch("products.agent_platform.backend.presentation.views._janitor")+ def test_freeze_rejects_kernel_id_colliding_with_store_alias(+ self, mock_janitor: MagicMock, mock_kernel: MagicMock+ ) -> None:+ # A kernel skill id that collides with a store ref alias is ambiguous — both+ # would target `skills/triage/`. Refuse before any janitor write.+ mock_kernel.return_value = [self._kernel("triage")]+ client = mock_janitor.return_value+ client.put_skill = MagicMock(return_value={"ok": True})++ res = self.client.post(self.url)+ self.assertEqual(res.status_code, 400, res.content)+ self.assertIn("collide", str(res.content))+ mock_kernel.assert_called_once_with(self.application.slug)+ client.freeze.assert_not_called()+ self.revision.refresh_from_db()+ self.assertEqual(self.revision.state, "draft")++ @patch("products.agent_platform.backend.presentation.views.kernel_skills_for")+ @patch("products.agent_platform.backend.presentation.views._janitor")+ def test_freeze_exempts_kernel_skill_from_legacy_orphan_guard(+ self, mock_janitor: MagicMock, mock_kernel: MagicMock+ ) -> None:+ # A forked spec carries an inline kernel entry (no `source_version_id`, no+ # backing ref). The legacy-orphan guard would refuse it as pre-store content,+ # but it's a current kernel skill — freeze must accept and re-inject it.+ mock_kernel.return_value = [self._kernel("safety-and-boundaries")]+ self.revision.skill_refs = []+ self.revision.spec = {+ "model": "x",+ "triggers": [],+ "skills": [{"id": "safety-and-boundaries", "path": "skills/safety-and-boundaries/SKILL.md"}],+ }+ self.revision.save(update_fields=["skill_refs", "spec"])+ client = mock_janitor.return_value+ client.put_skill = MagicMock(return_value={"ok": True})+ client.delete_skill = MagicMock(return_value={"ok": True})+ client.manifest.return_value = {"files": [{"path": "skills/safety-and-boundaries/SKILL.md"}]}+ client.freeze.return_value = {+ "bundle_sha256": "a" * 64,+ "derived_spec": {+ "model": "x",+ "triggers": [],+ "skills": [{"id": "safety-and-boundaries", "path": "skills/safety-and-boundaries/SKILL.md"}],+ "tools": [],+ },+ }++ res = self.client.post(self.url)+ self.assertEqual(res.status_code, 200, res.content)+ mock_kernel.assert_called_once_with(self.application.slug)+ client.freeze.assert_called_once()+ self.revision.refresh_from_db()+ self.assertEqual(self.revision.state, "ready")++ @patch("products.agent_platform.backend.presentation.views.all_kernel_skill_ids")+ @patch("products.agent_platform.backend.presentation.views.kernel_skills_for")+ @patch("products.agent_platform.backend.presentation.views._janitor")+ def test_freeze_drops_inline_kernel_entry_no_kernel_targets_this_agent(+ self, mock_janitor: MagicMock, mock_kernel: MagicMock, mock_all_kernel_ids: MagicMock+ ) -> None:+ # A cross-team `clone_from` of an agent-builder revision lands an opaque slug+ # no kernel skill targets, but the carried spec still has the inline kernel+ # entry (no `source_version_id`, no backing ref). It's a shipped kernel id, so+ # the legacy-orphan guard must let the freeze through and the sweep must drop+ # the now-inapplicable folder — not brick the fork permanently.+ mock_kernel.return_value = []+ mock_all_kernel_ids.return_value = frozenset({"safety-and-boundaries"})+ self.revision.skill_refs = []+ self.revision.spec = {+ "model": "x",+ "triggers": [],+ "skills": [{"id": "safety-and-boundaries", "path": "skills/safety-and-boundaries/SKILL.md"}],+ }+ self.revision.save(update_fields=["skill_refs", "spec"])+ client = mock_janitor.return_value+ client.put_skill = MagicMock(return_value={"ok": True})+ client.delete_skill = MagicMock(return_value={"ok": True})+ client.manifest.return_value = {"files": [{"path": "skills/safety-and-boundaries/SKILL.md"}]}+ client.freeze.return_value = {+ "bundle_sha256": "a" * 64,+ "derived_spec": {"model": "x", "triggers": [], "skills": [], "tools": []},+ }++ res = self.client.post(self.url)+ self.assertEqual(res.status_code, 200, res.content)+ client.delete_skill.assert_called_once_with(str(self.revision.id), "safety-and-boundaries")+ self.revision.refresh_from_db()+ self.assertEqual(self.revision.state, "ready")++ @patch("products.agent_platform.backend.presentation.views.kernel_skills_for")+ @patch("products.agent_platform.backend.presentation.views._janitor")+ def test_freeze_retry_on_sealed_bundle_does_not_wedge_on_kernel_drift(+ self, mock_janitor: MagicMock, mock_kernel: MagicMock+ ) -> None:+ # A prior freeze sealed the bundle (response lost); the kernel set has since+ # grown, so the sealed spec can't contain the newer kernel id. The retry hits+ # a sealed-bundle 409, falls through to the idempotent freeze, and must NOT+ # re-apply the post-seal kernel invariant against the immutable sealed bytes —+ # otherwise every retry wedges the draft forever.+ mock_kernel.return_value = [self._kernel("safety-and-boundaries")]+ client = mock_janitor.return_value+ client.manifest.return_value = {"files": [{"path": "skills/triage/SKILL.md"}]}+ client.put_skill = MagicMock(+ side_effect=JanitorClientError(409, "revision_not_draft", body={"error": "revision_not_draft"})+ )+ client.freeze.return_value = {+ "bundle_sha256": "a" * 64,+ # Sealed bytes predate the kernel skill — it can't appear here.+ "derived_spec": {+ "model": "x",+ "triggers": [],+ "skills": [{"id": "triage", "path": "skills/triage/SKILL.md"}],+ "tools": [],+ },+ }++ res = self.client.post(self.url)+ self.assertEqual(res.status_code, 200, res.content)+ client.freeze.assert_called_once()+ self.revision.refresh_from_db()+ self.assertEqual(self.revision.state, "ready")+@propertydef _detail_url(self) -> str:return f"/api/projects/{self.team.id}/agent_applications/{self.application.id}/revisions/{self.revision.id}/"diff --git a/products/agent_platform/backend/tests/test_kernel_skills.py b/products/agent_platform/backend/tests/test_kernel_skills.pynew file mode 100644index 000000000000..1246880de914--- /dev/null+++ b/products/agent_platform/backend/tests/test_kernel_skills.py@@ -0,0 +1,109 @@+from __future__ import annotations++import tempfile+from pathlib import Path++from unittest.mock import patch++from django.test import SimpleTestCase++from parameterized import parameterized++from ..logic import kernel_skills as ks+from ..logic.kernel_skills import KernelSkill, _all_kernel_skills, kernel_skills_for+++def _good_md(description: str = "A one-line description.", agents: str = "agent-x") -> str:+ return f"---\nname: s\ndescription: {description}\nagents:\n- {agents}\n---\n\n# Body\n"+++class TestKernelSkillRegistry(SimpleTestCase):+ def test_real_folder_loads_and_maps_to_designated_agent(self) -> None:+ ids = {k.id for k in kernel_skills_for("agent-builder")}+ self.assertIn("safety-and-boundaries", ids)+ # An agent the platform hasn't designated receives none of them.+ self.assertEqual(kernel_skills_for("some-random-user-agent"), [])++ def test_every_kernel_skill_is_well_formed(self) -> None:+ skills = _all_kernel_skills()+ self.assertTrue(skills)+ for k in skills:+ self.assertTrue(k.description, k.id)+ self.assertTrue(k.agents, k.id)+ # body keeps frontmatter so the freeze-time derivation reads the same+ # description the index reports.+ self.assertTrue(k.body.startswith("---\n"), k.id)+ # The janitor derives spec.skills[].description from only the first+ # physical `description:` line, capped at 280 — a folded/over-long+ # description would silently truncate the model's load signal. The+ # loader enforces parity; assert the shipped files honour it.+ self.assertNotIn("\n", k.description, k.id)+ self.assertLessEqual(len(k.description), 280, k.id)++ @parameterized.expand(+ [+ ("wildcard matches anything", frozenset({"*"}), "any-slug", True),+ ("slug in set matches", frozenset({"a", "b"}), "a", True),+ ("slug not in set misses", frozenset({"a", "b"}), "c", False),+ ("wildcard beats specific", frozenset({"*", "a"}), "z", True),+ ]+ )+ def test_applies_to(self, _name: str, agents: frozenset[str], slug: str, expected: bool) -> None:+ skill = KernelSkill(id="x", description="d", body="b", agents=agents)+ self.assertEqual(skill.applies_to(slug), expected)+++class TestKernelSkillLoader(SimpleTestCase):+ @staticmethod+ def _folder(root: str, name: str, content: str | None) -> Path:+ d = Path(root) / name+ d.mkdir()+ if content is not None:+ (d / "SKILL.md").write_text(content)+ return d++ @parameterized.expand(+ [+ ("missing SKILL.md", "ok-id", None),+ ("invalid folder id", "Bad-Caps", _good_md()),+ ("no frontmatter", "ok-id", "# just a body, no fences\n"),+ # LF fences but a CR inside the block — the janitor's single-line+ # derivation and Python's YAML parse would disagree silently.+ ("CR in frontmatter", "ok-id", "---\nname: s\ndescription: x\r\nagents:\n- agent-x\n---\n\nbody"),+ ("empty description", "ok-id", "---\nname: s\ndescription:\nagents:\n- agent-x\n---\n\nbody"),+ # Folded multi-line description: YAML reads the whole thing, the+ # janitor reads only the first line → parity guard must reject it.+ ("folded description", "ok-id", "---\nname: s\ndescription: one\n two\nagents:\n- agent-x\n---\n\nbody"),+ ("missing agents", "ok-id", "---\nname: s\ndescription: x\n---\n\nbody"),+ ("invalid agent slug", "ok-id", _good_md(agents="Bad-Slug")),+ (+ "wildcard mixed with slug",+ "ok-id",+ "---\nname: s\ndescription: x\nagents:\n- '*'\n- agent-x\n---\n\nbody",+ ),+ ]+ )+ def test_load_skill_rejects(self, _name: str, folder_name: str, content: str | None) -> None:+ with tempfile.TemporaryDirectory() as tmp:+ with self.assertRaises(ValueError):+ ks._load_skill(self._folder(tmp, folder_name, content))++ def test_load_skill_accepts_well_formed(self) -> None:+ with tempfile.TemporaryDirectory() as tmp:+ skill = ks._load_skill(self._folder(tmp, "ok-id", _good_md(agents="agent-x")))+ self.assertEqual(skill.id, "ok-id")+ self.assertEqual(skill.agents, frozenset({"agent-x"}))++ def test_runtime_scoping_survives_unrelated_bad_folders(self) -> None:+ # A malformed folder targeting a DIFFERENT agent, plus a cruft dir, must+ # not break freeze for the agent we're loading — runtime only validates+ # folders that target the slug. The strict whole-set loader still rejects+ # the shipped set, so the malformation is caught in CI.+ with tempfile.TemporaryDirectory() as tmp:+ self._folder(tmp, "good", _good_md(agents="agent-x"))+ self._folder(tmp, "__pycache__", "garbage") # cruft: skipped, not a skill+ self._folder(tmp, "broken", "---\nname: s\ndescription: x\n---\n\nbody") # no agents+ with patch.object(ks, "_KERNEL_SKILLS_DIR", Path(tmp)):+ self.assertEqual([k.id for k in ks.kernel_skills_for("agent-x")], ["good"])+ with self.assertRaises(ValueError):+ _all_kernel_skills()diff --git a/products/agent_platform/services/agent-tests/src/cases/example-agent-builder.test.ts b/products/agent_platform/services/agent-tests/src/cases/example-agent-builder.test.tsindex c7ee22512098..25423f01a754 100644--- a/products/agent_platform/services/agent-tests/src/cases/example-agent-builder.test.ts+++ b/products/agent_platform/services/agent-tests/src/cases/example-agent-builder.test.ts@@ -29,11 +29,6 @@ async function loadBundle(): Promise<{ spec: Record<string, unknown>; files: Recconst files: Record<string, string> = {}files['agent.md'] = await readFile(join(BUNDLE_ROOT, 'agent.md'), 'utf-8')files['README.md'] = await readFile(join(BUNDLE_ROOT, 'README.md'), 'utf-8')- const skillDirs = await readdir(join(BUNDLE_ROOT, 'skills'))- for (const id of skillDirs) {- const p = `skills/${id}/SKILL.md`- files[p] = await readFile(join(BUNDLE_ROOT, p), 'utf-8')- }return { spec, files }}@@ -43,16 +38,16 @@ describe('example: agent-builder bundle', () => {expect(() => AgentSpecSchema.parse(spec)).not.toThrow()})- it('every skill path in spec.skills[] exists as a bundle file, incl. the identity skill', async () => {- const { spec, files } = await loadBundle()+ it('carries NO inline skills — kernel skills are platform-injected, playbooks are MCP', async () => {+ const { spec } = await loadBundle()const parsed = AgentSpecSchema.parse(spec)- for (const skill of parsed.skills) {- expect(files[skill.path]).not.toBeUndefined()- expect((skill.description ?? '').length).toBeGreaterThan(30)- }- // The identity skill is the one we added for the MCP/identity swap — it's- // how the builder learns to wire `identity_providers` into agents it builds.- expect(parsed.skills.some((s) => s.id === 'authenticating-as-the-user')).toBe(true)+ // The author-facing bundle never carries skills. Kernel skills (the+ // concierge's own runtime behaviour — safety, console UI, fleet audit)+ // are injected from backend code at freeze (logic/kernel_skills.py), so+ // they move in lockstep with the platform and can't drift per account.+ // Builder playbooks (how to author/edit/wire-identity an agent) are served+ // by the MCP `agent-resolve-resource`, fetched on demand. Neither is here.+ expect(parsed.skills).toEqual([])})it('agent.md is present and non-trivial', async () => {diff --git a/products/agent_platform/services/agent-tests/src/examples/agent-builder/README.md b/products/agent_platform/services/agent-tests/src/examples/agent-builder/README.mdindex 032f6eeb4422..ee32f37bfe37 100644--- a/products/agent_platform/services/agent-tests/src/examples/agent-builder/README.md+++ b/products/agent_platform/services/agent-tests/src/examples/agent-builder/README.md@@ -39,38 +39,42 @@ plus `latest.md`), which is the deliverable of the sweep.The run is deliberately read-and-propose: the skill forbidsfreeze / promote / archive / delete, leaving the validated drafts for-the user to review and promote themselves. See-[`skills/auditing-the-fleet/SKILL.md`](skills/auditing-the-fleet/SKILL.md).+the user to review and promote themselves. `auditing-the-fleet` is a+kernel skill, injected at freeze — see+[`backend/kernel_skills/auditing-the-fleet/SKILL.md`](../../../../../backend/kernel_skills/auditing-the-fleet/SKILL.md).For each mode, the Agent Builder calls the same `agent-applications-*`native tools that the authoring AI uses,acting under the connected user's principal so every write showsup in the activity log as **the user**, not as the Agent Builder.+## Where its guidance lives — three homes, none of them this bundle++The Agent Builder's instructional content sits in exactly one of three+places, chosen by **what the content is for**. None of it ships in this+author-facing bundle — the bundle is just `agent.md`, `spec.json`, and+the faux test cases.++| Home | What | How it reaches the agent |+| ----------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| **Kernel skills** | The concierge's own runtime behaviour, coupled to the platform (safety, console UI, working outside it, fleet audit) | Injected from backend code (`products/agent_platform/backend/kernel_skills/`) at **freeze**; read via `@posthog/load-skill`. Code-locked, identical across accounts, never in the DB. |+| **MCP playbooks** | Reusable builder knowledge — how to read / debug / edit / author agents, identity, secrets, Slack, MCP-surface design, model choice, testing, cost, observability | Served by the MCP `agent-resolve-resource`, fetched on demand. Versioned with the MCP code. |+| **Skill store** | Team-authored reusable agent skills | Pinned via `skill_refs`, materialized into the bundle at freeze. |++Kernel skills are platform-injected (see+[`logic/kernel_skills.py`](../../../../../backend/logic/kernel_skills.py) — a+folder of SKILL.md files whose frontmatter declares an `agents:` mapping).+Authors never write skills inline; `skill_refs` → the store is the only+author path into a bundle's `skills/`.+## Bundle layout```textagent-builder/-├── README.md # this file-├── spec.json # triggers, tools, mcps, skills-├── agent.md # short system prompt; defers to skills-└── skills/ # one folder per skill, each with a SKILL.md- ├── platform-mental-model/SKILL.md # spec / bundle / revision / session- ├── reading-an-agent/SKILL.md # standard inspection flow- ├── debugging-sessions/SKILL.md # failure taxonomy + triage- ├── editing-agents-safely/SKILL.md # branch → validate → freeze → test → promote- ├── authoring-new-agents/SKILL.md # fresh creation flow- ├── choosing-the-model/SKILL.md # match model + reasoning to the job- ├── secrets-and-integrations/SKILL.md # punch-out flow, integrations table- ├── designing-mcp-surfaces/SKILL.md # spec.mcp.tools[] design- ├── running-and-evaluating-tests/SKILL.md # tests + judge skills- ├── setting-up-slack-app/SKILL.md # Slack app creation + scopes- ├── using-the-console-ui/SKILL.md # focus_* + toast etiquette- ├── working-outside-the-console/SKILL.md # MCP / IDE mode; no client tools- ├── cost-and-quota-analysis/SKILL.md # LLM analytics views- ├── querying-ai-observability/SKILL.md # $ai_* event contract + debug/improve queries- ├── auditing-the-fleet/SKILL.md # fleet-wide sweep (on request)- └── safety-and-boundaries/SKILL.md # hard rules+├── README.md # this file+├── spec.json # triggers, tools, mcps — NO skills[] (kernel injected at freeze)+├── agent.md # system prompt; loads kernel skills + fetches MCP playbooks+└── tests/ # faux wiring cases```## Tool surface@@ -126,7 +130,8 @@ agent-applications-create slug=agent-builder name="Agent Builder"agent-applications-revisions-create application_id=<id># write bundle resources via the granular per-resource tools:# agent-applications-revisions-agent-md-update / -tools-update-# skills come from the store: llm-skills-create / -search, then+# kernel skills are injected from backend code at freeze (no author step);+# store skills come from the store: llm-skills-create / -search, then# agent-applications-revisions-skill-refs-setagent-applications-revisions-partial-update revision_id=<rid> spec=<contents of spec.json>agent-applications-revisions-validate-create revision_id=<rid>@@ -146,7 +151,8 @@ session-principal token (`posthog_internal`) + verified user PATs[`services/agent-tests/src/cases/example-agent-builder.test.ts`](../../cases/example-agent-builder.test.ts)loads the bundle from disk and asserts:-- Every `spec.skills[].path` exists in the bundle+- The bundle carries NO inline skills (kernel skills are injected at+ freeze from backend code; builder playbooks are served by the MCP)- `agent.md` is present and non-trivial- `spec.mcps` is empty (the Agent Builder authors via native tools only —no external MCP server in the write path) **and** every declared@@ -175,9 +181,11 @@ Two ways:1. **Fork.** Clone the bundle, edit, deploy under a differentslug. Useful for teams that want bespoke review steps,internal links, or a different tone.-2. **Add a skill upstream.** New shared workflow (e.g.- `judge-test-results`) → add a skill file + a- `spec.skills[]` entry + a one-line description. Re-freeze.+2. **Add guidance upstream**, in the right home (see the table+ above): a new **kernel** behaviour → drop a folder under+ `backend/kernel_skills/<id>/SKILL.md` with an `agents:` mapping in+ its frontmatter; a new **builder playbook** → add it to the MCP+ playbook set; team content → the skill store.Don't fork to add a tool that should be universally available —add it to the canonical bundle so every team benefits.@@ -190,9 +198,11 @@ add it to the canonical bundle so every team benefits.- `limits.max_turns: 80` is generous; most flows finish in 5-15turns. The cap protects against pathological loops whileallowing complex multi-step audits.-- The skill descriptions in `spec.skills[]` are deliberately- prescriptive ("Load when..." / "Load IMMEDIATELY if...") —- this is the only signal the model gets about when to fetch- the skill body. Tune the descriptions before the bodies.+- Kernel skill descriptions live in each SKILL.md's frontmatter+ (`backend/kernel_skills/`) and are deliberately prescriptive+ ("Load when..." / "Load IMMEDIATELY if...") — this is the only+ signal the model gets about when to fetch the skill body. Tune the+ descriptions before the bodies.- `agent.md` is intentionally short. Anything beyond identity,- mode-selection, hard rules, and tone belongs in a skill.+ mode-selection, hard rules, and tone belongs in a kernel skill or+ an MCP playbook.diff --git a/products/agent_platform/services/agent-tests/src/examples/agent-builder/agent.md b/products/agent_platform/services/agent-tests/src/examples/agent-builder/agent.mdindex a3dda3e4ee75..a91b1e5cf5ff 100644--- a/products/agent_platform/services/agent-tests/src/examples/agent-builder/agent.md+++ b/products/agent_platform/services/agent-tests/src/examples/agent-builder/agent.md@@ -58,21 +58,42 @@ Envelope `page` values you may see and what each implies:| `agent-session` | One specific session (`session_id` set on top of `agent`) || `unknown` | The user is on a page the dock can't classify yet |+## Where your guidance comes from++Two distinct sources — keep them straight:++- **Kernel skills** (bundled, `skills/<id>`): your _own_ behaviour, tied to this+ runtime — `safety-and-boundaries`, `using-the-console-ui`,+ `working-outside-the-console`, `auditing-the-fleet`. Load them directly from+ your bundle; they ship with you and never drift.+- **Builder playbooks** (fetched, `posthog__agent-resolve-resource`): how to use+ the authoring tools — the platform model, reading / debugging / editing /+ authoring agents, identity, secrets, Slack setup, MCP-surface design, model+ choice, testing, cost, observability. These are the **single, live,+ scope-aware** source of truth: each comes back with the exact tool names+ callable under the asking user's scopes. **Never recite a tool name or a build+ procedure from memory — fetch the playbook.** Call+ `posthog__agent-resolve-resource({ resource: "<id>" })`.++When something below names a **builder playbook**, that means _fetch it_; when it+names a **kernel skill**, that means _load your bundled copy_. Builder playbooks+are not in your bundle — don't look for `skills/<id>` files for them.+## The three modesYou serve three jobs. Decide which one a message is asking for in-the first turn, then load the matching skill.--| User intent (paraphrase) | Mode | Primary skill |-| --------------------------------------------------------- | ------- | ----------------------- |-| "what does X do?", "is X healthy?", "show me X" | Inspect | `reading-an-agent` |-| "why did session Y fail?", "X is broken", "X did Z wrong" | Debug | `debugging-sessions` |-| "change X", "tweak the prompt", "add a tool" | Edit | `editing-agents-safely` |-| "build me a new agent that..." | Author | `authoring-new-agents` |-| "audit all my agents", "what's underperforming?" | Audit | `auditing-the-fleet` |--Don't pretend you already know the structural concepts. Load-`skills/platform-mental-model` the moment a definition is even+the first turn, then fetch the matching playbook.++| User intent (paraphrase) | Mode | Start by fetching playbook |+| --------------------------------------------------------- | ------- | -------------------------------- |+| "what does X do?", "is X healthy?", "show me X" | Inspect | `reading-an-agent` |+| "why did session Y fail?", "X is broken", "X did Z wrong" | Debug | `debugging-sessions` |+| "change X", "tweak the prompt", "add a tool" | Edit | `editing-agents-safely` |+| "build me a new agent that..." | Author | `authoring-new-agents` |+| "audit all my agents", "what's underperforming?" | Audit | load kernel `auditing-the-fleet` |++Don't pretend you already know the structural concepts. Fetch the+`platform-mental-model` playbook the moment a definition is evenslightly fuzzy in your head.## Hard rules@@ -89,7 +110,7 @@ one, refuse and explain why.2. **Never accept raw secrets in chat.** API keys, OAuth tokens,passwords. If the user pastes one, tell them not to and resetthe secret to whatever you'd have used the punch-out flow for.- See `skills/secrets-and-integrations`.+ Fetch the `secrets-and-integrations` playbook.3. **Never promote without explicit consent.** "Promote" is awrite that affects production traffic. Even when the usersaid "edit and ship X" earlier, confirm again at the moment@@ -140,8 +161,8 @@ How the credential reaches the call depends on the surface:This is also the single most important thing to get right in the agents youbuild: an agent that calls PostHog (or any third-party API) on a user'sbehalf needs an identity provider wired, the right scopes, and a flow that-relays the connect link. Load `skills/authenticating-as-the-user` whenever-you wire one — it's the whole model end to end. In a shared Slack thread+relays the connect link. Fetch the `authenticating-as-the-user` playbook+whenever you wire one — it's the whole model end to end. In a shared Slack thread(`allow_workspace_participants: true`) identity fails closed — you can't actas the thread owner for someone else, so an agent that acts as the user mustkeep participants off (owner-only).@@ -189,14 +210,14 @@ Examples (bad — vague, no commitment):You call a few classes of tool. Mistaking which class a tool is inis a routine cause of confusion; keep the table in mind.-| Class | Examples | When you use it |-| ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |-| PostHog MCP | `posthog__agent-applications-list`, `posthog__agent-applications-retrieve`, `posthog__agent-applications-sessions-retrieve`, `posthog__agent-applications-session-logs` (etc.) | The bulk of your work. Read + write agent state — applications, revisions, sessions, logs — as the asking user. One MCP server, every tool prefixed `posthog__`; the active project is set with `posthog__switch-project` (hard rule #7). |-| PostHog MCP (telemetry) | `posthog__execute-sql`, `posthog__insight-query`, `posthog__get-llm-total-costs-for-project`, `posthog__projects-get`, `posthog__switch-project` | HogQL / insights over the agent's LLM-observability events (`$ai_generation` / `$ai_span` / `$ai_trace`) the runner captured into the team's project, plus project resolution. Use when debugging or improving an agent — load `skills/querying-ai-observability`. |-| PostHog MCP (authoring aids) | `posthog__agent-native-tools-list`, `posthog__agent-resolve-resource` | Ground truth for building/editing: `agent-native-tools-list` is the catalog of valid native tool ids an agent can use; `agent-resolve-resource` fetches the MCP's live, scope-aware playbooks. Your bundled skills are the primary guide — use these alongside. |-| Native (memory) | `@posthog/memory-search`, `@posthog/memory-read`, `@posthog/memory-write` | Your own durable memory — persist a fleet-audit report. Used by `skills/auditing-the-fleet` when a user asks for a fleet-wide sweep. |-| Identity | `@posthog/identity-connect` | Mint a connect / reconnect link for the user's PostHog account — relay it as a markdown link when a capability needs an account that isn't linked yet (Slack). See "Acting as the user". |-| Client | `focus_tab`, `focus_file`, `focus_revision`, `focus_session`, `focus_spec_section`, `toast`, `get_context`, `set_secret` | Driving the PostHog Code host UI, reading the user's current view, and the secure `set_secret` punch-out. Implementation lives in the connecting client; absent (returns `unhandled_client_tool`) outside PostHog Code. |+| Class | Examples | When you use it |+| ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |+| PostHog MCP | `posthog__agent-applications-list`, `posthog__agent-applications-retrieve`, `posthog__agent-applications-sessions-retrieve`, `posthog__agent-applications-session-logs` (etc.) | The bulk of your work. Read + write agent state — applications, revisions, sessions, logs — as the asking user. One MCP server, every tool prefixed `posthog__`; the active project is set with `posthog__switch-project` (hard rule #7). |+| PostHog MCP (telemetry) | `posthog__execute-sql`, `posthog__insight-query`, `posthog__get-llm-total-costs-for-project`, `posthog__projects-get`, `posthog__switch-project` | HogQL / insights over the agent's LLM-observability events (`$ai_generation` / `$ai_span` / `$ai_trace`) the runner captured into the team's project, plus project resolution. Use when debugging or improving an agent — fetch the `querying-ai-observability` playbook. |+| PostHog MCP (authoring aids) | `posthog__agent-native-tools-list`, `posthog__agent-resolve-resource` | Ground truth for building/editing: `agent-native-tools-list` is the catalog of valid native tool ids; `agent-resolve-resource` is **the** source for builder playbooks — pass a playbook id and it returns the doc plus the live, scope-aware tool surface. These playbooks are not in your bundle; fetch them rather than recalling tool names. |+| Native (memory) | `@posthog/memory-search`, `@posthog/memory-read`, `@posthog/memory-write` | Your own durable memory — persist a fleet-audit report. Used by `skills/auditing-the-fleet` when a user asks for a fleet-wide sweep. |+| Identity | `@posthog/identity-connect` | Mint a connect / reconnect link for the user's PostHog account — relay it as a markdown link when a capability needs an account that isn't linked yet (Slack). See "Acting as the user". |+| Client | `focus_tab`, `focus_file`, `focus_revision`, `focus_session`, `focus_spec_section`, `toast`, `get_context`, `set_secret` | Driving the PostHog Code host UI, reading the user's current view, and the secure `set_secret` punch-out. Implementation lives in the connecting client; absent (returns `unhandled_client_tool`) outside PostHog Code. |### The agent-management tools@@ -226,7 +247,7 @@ you already have. Slug lookup costs an extra `list` call internally.| `posthog__agent-applications-sessions-retrieve` | full conversation + usage_total for one session — primary debug entry point || `posthog__agent-applications-session-logs` | structured event log for a session — timing, errors, tool calls in order |-**Write (PostHog MCP `posthog__agent-applications-*` — load `skills/authoring-new-agents` or `skills/editing-agents-safely` before reaching for these; the table omits the `posthog__` prefix for width):**+**Write (PostHog MCP `posthog__agent-applications-*` — fetch the `authoring-new-agents` or `editing-agents-safely` playbook before reaching for these; the table omits the `posthog__` prefix for width):**| Tool | Use when || -------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |@@ -253,11 +274,11 @@ Some trigger types require entries in `application.encrypted_env` that the spec| ------------ | ----------------------------------------- | ----------------------------------------------------------------------------------------------- || `slack` | `SLACK_SIGNING_SECRET`, `SLACK_BOT_TOKEN` | Slack app dashboard → Basic Information (signing secret) / Install App → Bot User OAuth (token) |-Anything else: empty for now. When you author or edit an agent that uses `slack` triggers, invoke the **`set_secret` client tool** for BOTH `SLACK_SIGNING_SECRET` AND `SLACK_BOT_TOKEN` **before** freeze + promote — and surface the `events_url` / `interactivity_url` fields from `posthog__agent-applications-revisions-slack-manifest` so the user knows what to paste into the Slack app dashboard. `set_secret` renders an inline form right next to your tool call in the chat transcript; the user fills it in without leaving the conversation. Do not hand them a `/connections?edit_secret=…` URL when `set_secret` is available — that's the degraded fallback, not the default. See `skills/setting-up-slack-app` for the full step-by-step and `skills/secrets-and-integrations` for the path-A / path-B fallback chain. The promote endpoint will refuse if a key is missing with a clear `Cannot promote: agent is missing required encrypted_env entries: <KEY> (for slack trigger). Set the value(s) via the env editor then retry.` error — recoverable, but a worse user experience than catching it upfront.+Anything else: empty for now. When you author or edit an agent that uses `slack` triggers, invoke the **`set_secret` client tool** for BOTH `SLACK_SIGNING_SECRET` AND `SLACK_BOT_TOKEN` **before** freeze + promote — and surface the `events_url` / `interactivity_url` fields from `posthog__agent-applications-revisions-slack-manifest` so the user knows what to paste into the Slack app dashboard. `set_secret` renders an inline form right next to your tool call in the chat transcript; the user fills it in without leaving the conversation. Do not hand them a `/connections?edit_secret=…` URL when `set_secret` is available — that's the degraded fallback, not the default. Fetch the `setting-up-slack-app` playbook for the full step-by-step and the `secrets-and-integrations` playbook for the path-A / path-B fallback chain. The promote endpoint will refuse if a key is missing with a clear `Cannot promote: agent is missing required encrypted_env entries: <KEY> (for slack trigger). Set the value(s) via the env editor then retry.` error — recoverable, but a worse user experience than catching it upfront.**Platform stance:** slack tools (`@posthog/slack-post-message` etc.) read from the agent's `SLACK_BOT_TOKEN` — not from a team-wide Slack OAuth integration. There is intentionally no fallback. Each agent gets its own Slack app + token so promote/archive cleanly govern per-agent Slack access.-**Slack-trigger behavioral fields** — beyond `trusted_workspaces`, the slack trigger config also has five optional fields that control how the bot reacts to inbound messages: `mention_only` (only respond to @-mentions), `auto_resume_threads` (relax `mention_only` for replies in threads the bot already owns), `allow_workspace_participants` (whether anyone in the workspace can drive an open thread, or only the user who started it — default owner-only), `ack_reaction` (emoji name the ingress posts as `reactions.add` for instant in-Slack feedback), and `allow_direct_messages` (let users DM the bot 1:1 — "talk to it as an app" — not just @-mention it in channels; adds the `im:history` scope + App Home Messages tab, so the app must be reinstalled after enabling). When the user asks anything about emoji reactions, mention-vs-thread behavior, who's allowed to reply in a thread, DMing the bot directly, or "make it respond when X" for a slack-triggered agent, load `skills/setting-up-slack-app` — the "Tuning the slack trigger" section there covers picking + wiring these. If they want the bot to read the surrounding thread (e.g. "what does this alert mean?"), that skill's "Letting the bot read the thread it's in" section covers wiring `@posthog/slack-read-thread`. To actually set the Slack app up, call `posthog__agent-applications-revisions-slack-manifest` and hand the user the generated manifest + the create-from-manifest link rather than dictating scopes by hand — its scopes + event subscriptions are derived from the agent's config, so they're correct by construction.+**Slack-trigger behavioral fields** — beyond `trusted_workspaces`, the slack trigger config also has five optional fields that control how the bot reacts to inbound messages: `mention_only` (only respond to @-mentions), `auto_resume_threads` (relax `mention_only` for replies in threads the bot already owns), `allow_workspace_participants` (whether anyone in the workspace can drive an open thread, or only the user who started it — default owner-only), `ack_reaction` (emoji name the ingress posts as `reactions.add` for instant in-Slack feedback), and `allow_direct_messages` (let users DM the bot 1:1 — "talk to it as an app" — not just @-mention it in channels; adds the `im:history` scope + App Home Messages tab, so the app must be reinstalled after enabling). When the user asks anything about emoji reactions, mention-vs-thread behavior, who's allowed to reply in a thread, DMing the bot directly, or "make it respond when X" for a slack-triggered agent, fetch the `setting-up-slack-app` playbook — the "Tuning the slack trigger" section there covers picking + wiring these. If they want the bot to read the surrounding thread (e.g. "what does this alert mean?"), that playbook's "Letting the bot read the thread it's in" section covers wiring `@posthog/slack-read-thread`. To actually set the Slack app up, call `posthog__agent-applications-revisions-slack-manifest` and hand the user the generated manifest + the create-from-manifest link rather than dictating scopes by hand — its scopes + event subscriptions are derived from the agent's config, so they're correct by construction.### Tabular reference — deterministic structured state for agents@@ -311,7 +332,7 @@ These run in the connecting client, not on the runner. The runner emits the call| Tool | Use it when || -------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- || `focus_tab` | Switch the agent detail panel between `overview` / `configuration` / `sessions`. Args: `{ tab }`. |-| `focus_file` | Open one bundle file in the configuration panel. Args: `{ path }` (e.g. `"skills/research.md"`). |+| `focus_file` | Open one bundle file in the configuration panel. Args: `{ path }` (e.g. `"agent.md"` or `"skills/triage/SKILL.md"`). || `focus_revision` | Open one revision in the configuration panel. Args: `{ revisionId }` (full UUID). || `focus_session` | Open one session in the sessions panel. Args: `{ sessionId }` (full UUID). Do NOT call without an id — if you don't have one yet, list first, then focus. || `focus_spec_section` | Jump to a section of the spec: `triggers` / `tools` / `skills` / `secrets` / `limits`. Args: `{ section }`. |@@ -340,7 +361,7 @@ double-posts). Wire `@posthog/slack-post-message` into a Slack agent'sposting to a different channel, a DM, or editing an earlier message —and tell it to reserve the tool for those cases. The automatic Slackposts are the `ack_reaction`, the relayed assistant replies, and a-failure notice. See `skills/setting-up-slack-app`.+failure notice. Fetch the `setting-up-slack-app` playbook.There is no shell, code execution, or database access. If a user asksfor something that needs one of those, explain what you can offerdiff --git a/products/agent_platform/services/agent-tests/src/examples/agent-builder/spec.json b/products/agent_platform/services/agent-tests/src/examples/agent-builder/spec.jsonindex 470f0d3ed0bb..1dddffad2365 100644--- a/products/agent_platform/services/agent-tests/src/examples/agent-builder/spec.json+++ b/products/agent_platform/services/agent-tests/src/examples/agent-builder/spec.json@@ -14,7 +14,9 @@"scopes": ["agents:read", "agents:write", "agent_session:read"],"audience": "organization"},- { "type": "posthog_internal" }+ {+ "type": "posthog_internal"+ }]}},@@ -24,7 +26,15 @@"allow_restart": true},"auth": {- "modes": [{ "type": "posthog", "audience": "organization" }, { "type": "posthog_internal" }]+ "modes": [+ {+ "type": "posthog",+ "audience": "organization"+ },+ {+ "type": "posthog_internal"+ }+ ]}},{@@ -207,7 +217,9 @@{"id": "posthog","url": "http://localhost:8787/mcp",- "auth": { "provider": "posthog" },+ "auth": {+ "provider": "posthog"+ },"tools": ["agent-applications-list","agent-applications-retrieve",@@ -248,108 +260,30 @@{"name": "agent-applications-revisions-promote-create","requires_approval": true,- "approval_policy": { "type": "principal", "ttl_ms": 900000 }+ "approval_policy": {+ "type": "principal",+ "ttl_ms": 900000+ }},{"name": "agent-applications-revisions-archive-create","requires_approval": true,- "approval_policy": { "type": "principal", "ttl_ms": 900000 }+ "approval_policy": {+ "type": "principal",+ "ttl_ms": 900000+ }},{"name": "agent-applications-destroy","requires_approval": true,- "approval_policy": { "type": "principal", "ttl_ms": 900000 }+ "approval_policy": {+ "type": "principal",+ "ttl_ms": 900000+ }}]}],- "skills": [- {- "id": "platform-mental-model",- "path": "skills/platform-mental-model/SKILL.md",- "description": "What an agent is \u2014 spec, bundle, revision lifecycle, triggers, the runner. Load FIRST when explaining the platform to someone, or any time you catch yourself unsure about a structural term."- },- {- "id": "reading-an-agent",- "path": "skills/reading-an-agent/SKILL.md",- "description": "How to inspect and summarize an existing agent \u2014 which MCP calls to make, in what order, and how to render a concise overview for the user. Load whenever the user asks 'what does X do?' or 'show me Y'."- },- {- "id": "debugging-sessions",- "path": "skills/debugging-sessions/SKILL.md",- "description": "Triaging a failing or anomalous session \u2014 failure taxonomy, how to read the event log + LLM trace, common root causes. Load when the user reports a broken session, a failed approval, or unexpected agent behavior."- },- {- "id": "editing-agents-safely",- "path": "skills/editing-agents-safely/SKILL.md",- "description": "The full edit-promote loop \u2014 branch a draft, surgical edits, validate, freeze, test, promote, rollback. Load whenever the user wants to change ANY part of an existing agent."- },- {- "id": "authoring-new-agents",- "path": "skills/authoring-new-agents/SKILL.md",- "description": "Creating a new agent from scratch \u2014 discover building blocks, design spec, write agent.md and skills, configure tools. Load only when the user is creating a NEW agent; for editing, use editing-agents-safely instead."- },- {- "id": "authenticating-as-the-user",- "path": "skills/authenticating-as-the-user/SKILL.md",- "description": "How an agent acts on a service AS the user \u2014 the identity system. The two axes (principal: who's asking vs credential provider: how the agent gets their token), spec.identity_providers (kind posthog vs bring-your-own oauth2, scopes, binding), how tools/MCPs declare they need a provider (native requires.provider, mcp auth.provider, custom requires_identity), the resolve outcomes (ok / link_required / unavailable), connect + relink links via @posthog/identity-connect, and how to choose OAuth scopes. Load whenever you're wiring an agent that calls PostHog or any third-party API as the user, adding an MCP with auth.provider, deciding scopes, or the user asks about connecting / linking / OAuth / 'act as me'."- },- {- "id": "choosing-the-model",- "path": "skills/choosing-the-model/SKILL.md",- "description": "Picking `spec.model` + `spec.reasoning` for an agent's actual job \u2014 the cost/quality axes (model family, reasoning level, context budget) and how to match model to task without defaulting to the most or least expensive. Load whenever you're about to set or review an agent's model, or the user asks which / cheapest model to use."- },- {- "id": "secrets-and-integrations",- "path": "skills/secrets-and-integrations/SKILL.md",- "description": "Wiring credentials without seeing them \u2014 when to invoke the `set_secret` client tool (the inline form rendered next to your tool call), when to fall back to a deep-link, integrations vs secrets, trigger-required keys (e.g. SLACK_SIGNING_SECRET / SLACK_BOT_TOKEN), what to do when a tool needs auth. ALWAYS load when the user mentions a secret, env key, API key, OAuth, integration, missing credential, Slack setup, or any auth-related error \u2014 `set_secret` is the default path in PostHog Code, do not hand out URLs to /connections without loading this skill first."- },- {- "id": "setting-up-slack-app",- "path": "skills/setting-up-slack-app/SKILL.md",- "description": "End-to-end script for taking a Slack-triggered agent live: Slack-side app creation, OAuth scopes, event subscriptions, the promote-before-URL ordering, and the per-app secrets (SLACK_SIGNING_SECRET / SLACK_BOT_TOKEN). The 'Tuning the slack trigger' section covers mention_only / auto_resume_threads / allow_workspace_participants (who may drive a thread) / ack_reaction and how to pick + wire them; 'Letting the bot read the thread it's in' covers @posthog/slack-read-thread. Load whenever a user wants their agent to listen on Slack, asks about @-mention vs thread behavior, who can reply in a thread, emoji reactions, or reading thread context."- },- {- "id": "designing-mcp-surfaces",- "path": "skills/designing-mcp-surfaces/SKILL.md",- "description": "How to design the MCP tool surface an agent EXPOSES (the spec.mcp.tools[] block) \u2014 when to add curated tools vs rely on `ask`, naming, schemas, prompt templates. Load when the user is making an agent available over MCP."- },- {- "id": "running-and-evaluating-tests",- "path": "skills/running-and-evaluating-tests/SKILL.md",- "description": "Writing test specs, kicking off test runs, reading results, self-evaluation, judge skills. Load before any promote on a non-trivial change, and whenever the user asks to test an agent."- },- {- "id": "using-the-console-ui",- "path": "skills/using-the-console-ui/SKILL.md",- "description": "How to drive PostHog Code's read panel as the user works with you \u2014 focus_* etiquette, when to call toast, how to handle 'follow mode' being off. Load when the session client kind is `posthog-code`."- },- {- "id": "working-outside-the-console",- "path": "skills/working-outside-the-console/SKILL.md",- "description": "Operating without a UI \u2014 MCP / IDE / Slack mode. How to compensate for missing client tools, how to be useful in a text-only chat. Load when the session client kind is NOT `posthog-code`."- },- {- "id": "cost-and-quota-analysis",- "path": "skills/cost-and-quota-analysis/SKILL.md",- "description": "Running cost / token / failure-rate queries against PostHog LLM analytics \u2014 which event names to query, which properties to aggregate, the standard rollups. Load when the user asks about cost, performance, usage, or limits. For the authoritative emitted-event contract use querying-ai-observability."- },- {- "id": "querying-ai-observability",- "path": "skills/querying-ai-observability/SKILL.md",- "description": "The authoritative contract for the LLM-observability events the runner emits into each team's own project (`$ai_generation` / `$ai_span` / `$ai_trace`) and how to HogQL them with `@posthog/query` \u2014 reconstruct a single session's trace, find which sessions tripped up, break down tool errors, and roll up cost / latency / failure-rate per agent. Load whenever you're DEBUGGING a session or IMPROVING an agent and want evidence from real model + tool telemetry, not just the conversation JSON. Pairs with debugging-sessions (per-session triage) and auditing-the-fleet (the nightly sweep)."- },- {- "id": "auditing-the-fleet",- "path": "skills/auditing-the-fleet/SKILL.md",- "description": "The fleet-wide audit \u2014 sweep every agent in the team, mine each one's recent sessions for failures / anomalies / degraded behaviour, classify root causes, branch a DRAFT proposal revision per fix (never freeze or promote), and write the structured report to memory (optionally post a Slack digest). Load whenever the user asks for a fleet-wide health sweep / 'audit all my agents' / 'what's underperforming?'. Builds on debugging-sessions (per-session triage) and editing-agents-safely (the draft-proposal mechanics)."- },- {- "id": "safety-and-boundaries",- "path": "skills/safety-and-boundaries/SKILL.md",- "description": "Hard rules \u2014 what the Agent Builder MUST NOT do regardless of user request. Load IMMEDIATELY if a request feels like it crosses into raw-secret handling, unprompted promotion, irreversible deletion, or impersonation of another user."- }- ],"identity_providers": [{"kind": "posthog",diff --git a/pyproject.toml b/pyproject.tomlindex f38c863abac4..3b9f4d986bd5 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -515,6 +515,7 @@ ignore_imports = ["products.agent_platform.backend.presentation.views -> products.agent_platform.backend.db","products.agent_platform.backend.presentation.views -> products.agent_platform.backend.logic.internal_jwt","products.agent_platform.backend.presentation.views -> products.agent_platform.backend.logic.janitor_client",+ "products.agent_platform.backend.presentation.views -> products.agent_platform.backend.logic.kernel_skills","products.agent_platform.backend.presentation.views -> products.agent_platform.backend.logic.posthog_identity_app","products.agent_platform.backend.presentation.views -> products.agent_platform.backend.logic.skill_resolution","products.agent_platform.backend.presentation.views -> products.agent_platform.backend.logic.spec_schema",diff --git a/services/mcp/playbooks/README.md b/services/mcp/playbooks/README.mdnew file mode 100644index 000000000000..dc47b0361719--- /dev/null+++ b/services/mcp/playbooks/README.md@@ -0,0 +1,50 @@+# MCP builder playbooks++The markdown in this directory is the **single source of truth** for the+agent-platform _builder playbooks_ — operator docs about how to use the+authoring tools (read / debug / edit / author agents, identity, secrets, Slack+setup, MCP-surface design, model choice, testing, cost, observability).++`scripts/copy-instructions.ts` generates `src/tools/agentPlatform/playbook*.generated.ts`+from these files; the `agent-resolve-resource` MCP tool serves them to any+consumer, appending a **live, scope-aware tool surface** computed against the+caller's actual scopes. To add or edit a playbook: change the `<id>/SKILL.md`+here and run `tsx services/mcp/scripts/copy-instructions.ts` (CI does this too).++## Three homes for agent guidance — don't confuse them++Agent-platform instructional content lives in exactly one of three places,+chosen by **what the content is for**. Putting a piece in the wrong home is how+the concierge ended up with the same docs bundled _and_ in the MCP.++| | **Kernel skills** | **MCP playbooks** (here) | **Skill store** |+| ----------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------ | -------------------------------------------------------------------- |+| **What** | The concierge's own runtime behaviour, **coupled to the platform architecture** — its `focus_*` client tools, runtime client-kind modes, the principal/safety model, the fleet-audit workflow | Reusable knowledge about the **authoring tools** — how to build/operate agents | **Team-authored** reusable agent runtime skills |+| **Why this home** | Must move in lockstep with the implementation; identical across every account; **cannot drift in the DB** | Platform docs of the live tool surface; version with the MCP | Content that is _supposed_ to vary per team |+| **Home** | **Code** — `products/agent_platform/backend/kernel_skills/`; injected into the bundle at freeze, like the framework preamble | **Code** — this dir; served via `agent-resolve-resource` | **DB** — the llma-skill store; `skill_refs` → materialized at freeze |+| **Consumer** | The concierge itself | Anyone building agents (human, IDE, _or the concierge_) | Any team agent |++**The discriminator:** _reusable platform knowledge_ → MCP playbook; _this+deployed agent's runtime behaviour_ → kernel skill; _content meant to vary per+team_ → store skill.++**Why kernel can't be a store skill (the drift argument):** if+`safety-and-boundaries` or `using-the-console-ui` were a per-team `skill_refs`+store skill, an account could freeze an agent against a stale copy while the+platform's actual enforcement / client-tool set moved on — the agent would then+_describe a platform it isn't running on_. Kernel content is code-locked so that+can't happen. The store is **only** for content meant to diverge per team.++**Why a playbook isn't a kernel skill:** the concierge _builds_ agents, so it+needs builder knowledge the same way Claude Code does — by fetching it from the+MCP. Builder playbooks are not bundled into any agent; they're fetched on demand+with `agent-resolve-resource`, which is also why they can carry a live+scope-aware tool surface that a static bundled file never could.++## The four kernel skills++These live in the concierge bundle, **not** here:+`safety-and-boundaries`, `using-the-console-ui`, `working-outside-the-console`,+`auditing-the-fleet`. A playbook here must not tell the reader to "load" one of+them (a generic MCP consumer has no such bundled file) — state the relevant fact+inline instead.diff --git a/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/authenticating-as-the-user/SKILL.md b/services/mcp/playbooks/authenticating-as-the-user/SKILL.mdsimilarity index 100%rename from products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/authenticating-as-the-user/SKILL.mdrename to services/mcp/playbooks/authenticating-as-the-user/SKILL.mddiff --git a/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/authoring-new-agents/SKILL.md b/services/mcp/playbooks/authoring-new-agents/SKILL.mdsimilarity index 97%rename from products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/authoring-new-agents/SKILL.mdrename to services/mcp/playbooks/authoring-new-agents/SKILL.mdindex 21a425ed7d34..bd7f3145c0a1 100644--- a/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/authoring-new-agents/SKILL.md+++ b/services/mcp/playbooks/authoring-new-agents/SKILL.md@@ -2,7 +2,7 @@How to build a deployable agent from scratch. Load this only whenthe user is creating a NEW agent. For editing existing agents,-use `skills/editing-agents-safely` instead.+use the `editing-agents-safely` playbook instead.## Don't author until you know the brief@@ -114,7 +114,7 @@ part of the spec:`spec.secrets[]`. They come from the platform-wide`TRIGGER_REQUIRED_SECRETS` registry and live in `encrypted_env`;the promote endpoint refuses if they're missing. See- `skills/secrets-and-integrations`.+ the `secrets-and-integrations` playbook.- **Custom-tool `source.ts` shape** (Phase 5) is the tool's runtimecontract, not spec structure — the field reference won't describe it.@@ -159,14 +159,14 @@ posthog__agent-applications-revisions-partial-update revision_id=<rid> spec=<jso## Phase 4 — configure secrets / integrationsFor each item in `spec.secrets[]`, you cannot accept the value-directly. Load `skills/secrets-and-integrations` and follow the+directly. Load the `secrets-and-integrations` playbook and follow thepunch-out flow.**Also check trigger-required secrets** — some trigger types demandentries in `encrypted_env` that the spec doesn't name explicitly(`SLACK_SIGNING_SECRET` for `slack` triggers, today). The promoteendpoint refuses if any are missing; catch them here so the user-isn't surprised at the end. See `skills/secrets-and-integrations`+isn't surprised at the end. See the `secrets-and-integrations` playbook→ "Trigger-required secrets" for the registry + punch-out flow.For each item in `spec.integrations[]`, check whether the team@@ -175,7 +175,7 @@ install it from the PostHog integrations UI — you can't do thisfor them.When the new agent must call PostHog or a third-party API as the-user, load `skills/authenticating-as-the-user` to wire its identity+user, load the `authenticating-as-the-user` playbook to wire its identityprovider + scopes.## Phase 5 — write the bundle (typed authoring API)@@ -307,7 +307,7 @@ If you see leftover orphan-diagnostic prose in older docs, it's stale.## Phase 7 — freeze + test-Load `skills/running-and-evaluating-tests`. Write 3-5 test cases+Load the `running-and-evaluating-tests` playbook. Write 3-5 test casescovering the happy path, the obvious edge cases, and one hostileinput.@@ -317,7 +317,7 @@ iterate.If tests fail: branch a new draft from the just-frozen ready,fix, re-freeze, re-test. (Same loop as-`skills/editing-agents-safely`.)+the `editing-agents-safely` playbook.)## Phase 8 — promote@@ -343,7 +343,7 @@ revision before promoting.before checking native ones. Cross-check `posthog__agent-native-tools-list`first — half the time the native tool exists.- **Secrets in `agent.md`.** Comes up often. Refuse hard, load- `skills/secrets-and-integrations`.+ the `secrets-and-integrations` playbook.- **Public auth on a chat trigger.** Will be abused. Default to`posthog` and explain why.diff --git a/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/choosing-the-model/SKILL.md b/services/mcp/playbooks/choosing-the-model/SKILL.mdsimilarity index 100%rename from products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/choosing-the-model/SKILL.mdrename to services/mcp/playbooks/choosing-the-model/SKILL.mddiff --git a/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/cost-and-quota-analysis/SKILL.md b/services/mcp/playbooks/cost-and-quota-analysis/SKILL.mdsimilarity index 100%rename from products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/cost-and-quota-analysis/SKILL.mdrename to services/mcp/playbooks/cost-and-quota-analysis/SKILL.mddiff --git a/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/debugging-sessions/SKILL.md b/services/mcp/playbooks/debugging-sessions/SKILL.mdsimilarity index 99%rename from products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/debugging-sessions/SKILL.mdrename to services/mcp/playbooks/debugging-sessions/SKILL.mdindex 0832af521134..15b971f10082 100644--- a/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/debugging-sessions/SKILL.md+++ b/services/mcp/playbooks/debugging-sessions/SKILL.md@@ -44,7 +44,7 @@ completed | closed | failed`. There is no separate5. **For each non-trivial failure** pull the revision (so you canreason about the agent's design, not just the symptom) — same- calls as `skills/reading-an-agent` step 2 + 4.+ calls as the `reading-an-agent` playbook step 2 + 4.6. **Produce a structured report** — see the report shape at thebottom.diff --git a/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/designing-mcp-surfaces/SKILL.md b/services/mcp/playbooks/designing-mcp-surfaces/SKILL.mdsimilarity index 99%rename from products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/designing-mcp-surfaces/SKILL.mdrename to services/mcp/playbooks/designing-mcp-surfaces/SKILL.mdindex e796f19614b6..474111884797 100644--- a/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/designing-mcp-surfaces/SKILL.md+++ b/services/mcp/playbooks/designing-mcp-surfaces/SKILL.md@@ -53,7 +53,7 @@ reason })` as a typed entry; the connecting LLM routes to itsystem, not by a human conversational LLM.If the exposed MCP/tools act on a third-party API as the user, wire an-identity provider — see `skills/authenticating-as-the-user`.+identity provider — see the `authenticating-as-the-user` playbook.Don't add curated tools when:diff --git a/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/editing-agents-safely/SKILL.md b/services/mcp/playbooks/editing-agents-safely/SKILL.mdsimilarity index 95%rename from products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/editing-agents-safely/SKILL.mdrename to services/mcp/playbooks/editing-agents-safely/SKILL.mdindex c2cd002d80e7..da8b3b4271d3 100644--- a/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/editing-agents-safely/SKILL.md+++ b/services/mcp/playbooks/editing-agents-safely/SKILL.md@@ -30,7 +30,7 @@ X". You need to know:- Whether there are pending approvals or in-flight sessions you'ddisrupt-Use the standard flow from `skills/reading-an-agent`. Don't+Use the standard flow from the `reading-an-agent` playbook. Don'tproceed until you've read both `spec` and the relevant file(s).## Step 2 — branch a draft@@ -82,7 +82,7 @@ validate until it's clean rather than guessing the structure.If the edit changes how the agent authenticates to a service (identityprovider, scopes, MCP auth.provider), load-`skills/authenticating-as-the-user`.+the `authenticating-as-the-user` playbook.For each edit, surface to the user:@@ -108,7 +108,7 @@ Common errors:that isn't in the bundle. Either add the file or remove the specentry.- `missing_secret` — `spec.secrets[]` lists a name without a- corresponding env value. Load `skills/secrets-and-integrations`.+ corresponding env value. Load the `secrets-and-integrations` playbook.- `invalid_spec` — Zod parse failed. The error message names thefield and the expected shape; fix it from the validate error andre-run `posthog__agent-applications-revisions-validate-create`@@ -134,7 +134,7 @@ now.") so the user knows the state changed.## Step 6 — test-Load `skills/running-and-evaluating-tests`. At minimum:+Load the `running-and-evaluating-tests` playbook. At minimum:- Find `bundle/tests/*.json` (if any). Run them all.- If there are no tests, write one for the case the edit targets,@@ -197,8 +197,9 @@ Common asks:it AND the edit is purely cosmetic (typo, formatting). Anythingsemantic still gets a test.- **"don't ask me to confirm promote, just do it"** — Refuse.- See `skills/safety-and-boundaries` rule #3. Promote is a- production-affecting write; the user has to type the word.+ Promote is a production-affecting write; the user has to give+ explicit consent (type the word) every time, regardless of what+ they said earlier.- **"I'll edit it later, just leave the draft"** — Fine.Drafts persist; the user can resume by calling you again withthe draft revision id. Surface the id explicitly so they candiff --git a/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/platform-mental-model/SKILL.md b/services/mcp/playbooks/platform-mental-model/SKILL.mdsimilarity index 100%rename from products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/platform-mental-model/SKILL.mdrename to services/mcp/playbooks/platform-mental-model/SKILL.mddiff --git a/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/querying-ai-observability/SKILL.md b/services/mcp/playbooks/querying-ai-observability/SKILL.mdsimilarity index 98%rename from products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/querying-ai-observability/SKILL.mdrename to services/mcp/playbooks/querying-ai-observability/SKILL.mdindex 2f1435f8ceb2..dc32c7461e17 100644--- a/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/querying-ai-observability/SKILL.md+++ b/services/mcp/playbooks/querying-ai-observability/SKILL.md@@ -161,8 +161,8 @@ GROUP BY agentORDER BY cost_usd DESC```-This is the query `auditing-the-fleet` leans on for its nightly-per-agent health line. Filter to one `$agent_application_id` for a+This is the query a fleet-wide audit leans on for its per-agent+health line. Filter to one `$agent_application_id` for asingle-agent deep dive.## How to use the evidencediff --git a/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/reading-an-agent/SKILL.md b/services/mcp/playbooks/reading-an-agent/SKILL.mdsimilarity index 96%rename from products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/reading-an-agent/SKILL.mdrename to services/mcp/playbooks/reading-an-agent/SKILL.mdindex ef8f3d135f75..f70f8070775f 100644--- a/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/reading-an-agent/SKILL.md+++ b/services/mcp/playbooks/reading-an-agent/SKILL.md@@ -106,7 +106,7 @@ Drill in narrowly. Don't repeat the whole summary.| "what skills does it have?" | Already in `spec.skills[]` — render the table || "read me skill X" | `posthog__agent-applications-revisions-bundle-retrieve` — the skill body is in the returned `skills[]` || "what was the latest session?" | `posthog__agent-applications-sessions-list` with `limit: 1`, then `posthog__agent-applications-sessions-retrieve` + `posthog__agent-applications-session-logs` |-| "how much is it costing?" | Load `skills/cost-and-quota-analysis` and run the standard query |+| "how much is it costing?" | Load the `cost-and-quota-analysis` playbook and run the standard query || "show me the bundle" | `posthog__agent-applications-revisions-manifest-retrieve` — file tree only || "what's its history?" | `posthog__agent-applications-revisions-list` — chronological revision states |@@ -130,6 +130,6 @@ load each one individually; that's a separate request the user canmake after they see the list.For "audit this team's agents" — load-`skills/cost-and-quota-analysis` for the cost lens, list the+the `cost-and-quota-analysis` playbook for the cost lens, list theapplications, and combine into one health view. That's its ownmode; the bare inspect flow is per-agent.diff --git a/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/running-and-evaluating-tests/SKILL.md b/services/mcp/playbooks/running-and-evaluating-tests/SKILL.mdsimilarity index 97%rename from products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/running-and-evaluating-tests/SKILL.mdrename to services/mcp/playbooks/running-and-evaluating-tests/SKILL.mdindex bba1961b4cd3..ce217ffef578 100644--- a/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/running-and-evaluating-tests/SKILL.md+++ b/services/mcp/playbooks/running-and-evaluating-tests/SKILL.md@@ -126,7 +126,7 @@ For each case:- **One assertion failed** — read the conversation, identifywhether it's a spec/prompt issue (likely) or a test-spec issue(the assertion was too strict).-- **The case errored** — same flow as `skills/debugging-sessions`+- **The case errored** — same flow as the `debugging-sessions` playbookbut against a test session.For the assistant_text_matches failure pattern: do NOT just@@ -167,7 +167,7 @@ Be honest about what you can and can't judge:## When the user wants to skip testsCommon: "just promote it, the change is small". See-`skills/editing-agents-safely` — pure-cosmetic edits can skip,+the `editing-agents-safely` playbook — pure-cosmetic edits can skip,anything semantic should run at least one test case.If the user insists on skipping for a semantic edit, **note itdiff --git a/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/secrets-and-integrations/SKILL.md b/services/mcp/playbooks/secrets-and-integrations/SKILL.mdsimilarity index 98%rename from products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/secrets-and-integrations/SKILL.mdrename to services/mcp/playbooks/secrets-and-integrations/SKILL.mdindex e08713453b50..b44e7cf18952 100644--- a/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/secrets-and-integrations/SKILL.md+++ b/services/mcp/playbooks/secrets-and-integrations/SKILL.md@@ -78,9 +78,9 @@ and refuses with a clear error if any required key is missing:You can recover from this by setting the key and re-runningpromote — but a better user experience is to catch it during-**Phase 4** of `skills/authoring-new-agents`: as soon as the spec+**Phase 4** of the `authoring-new-agents` playbook: as soon as the specdeclares a `slack` trigger, drive the punch-out for BOTH required-keys before reaching freeze. See `skills/setting-up-slack-app` for+keys before reaching freeze. See the `setting-up-slack-app` playbook forthe step-by-step flow (create app → set Request URL → install →copy + punch-out tokens). PostHog Code's env editor also surfaces"Required for this trigger" hints next to the relevant fields, so a@@ -242,7 +242,7 @@ You can:> Slack is **not** one of these. Use `SLACK_BOT_TOKEN` +> `SLACK_SIGNING_SECRET` on the agent's `encrypted_env` via the-> punch-out flow. See `skills/setting-up-slack-app`.+> punch-out flow. See the `setting-up-slack-app` playbook.## Rotating a secretdiff --git a/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/setting-up-slack-app/SKILL.md b/services/mcp/playbooks/setting-up-slack-app/SKILL.mdsimilarity index 99%rename from products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/setting-up-slack-app/SKILL.mdrename to services/mcp/playbooks/setting-up-slack-app/SKILL.mdindex 32de5c4be2cc..e63312a8f169 100644--- a/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/setting-up-slack-app/SKILL.md+++ b/services/mcp/playbooks/setting-up-slack-app/SKILL.md@@ -407,9 +407,9 @@ present.don't. Each agent's Slack creds live in its own `encrypted_env`.- **Don't ask for the token values in chat.** Every bot token /signing secret comes in through the `set_secret` punch-out — see- `skills/secrets-and-integrations` for the hard rule. A Slack agent+ the `secrets-and-integrations` playbook for the hard rule. A Slack agentthat acts on a service as the user needs an identity provider — see- `skills/authenticating-as-the-user`.+ the `authenticating-as-the-user` playbook.- **Don't invent the events URL.** It comes from`posthog__agent-applications-retrieve.slack_events_url`. If that field isnull, the deployment isn't externally reachable — say so anddiff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex bc79857a936f..bc20a8cfacd7 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -788,7 +788,7 @@"feature_flag": "agent-platform"},"agent-resolve-resource": {- "description": "Fetch an operator playbook — a markdown guide for doing a class of agent-platform operations well. These are the same skills the agent concierge loads; resolve the relevant one BEFORE a non-trivial operation (editing/promoting a revision, wiring secrets, authoring an agent, debugging a session). Many `agent-applications-*` tool descriptions name the playbook to read first. Pass either a bare id or its `posthog://agent-platform/playbooks/<id>` URI — the `resource` parameter enumerates the available playbooks. Returns `{ id, uri, title, content }` where `content` is the full markdown.",+ "description": "Fetch a builder playbook — a markdown guide for using the agent-platform authoring tools well, returned with the live, scope-aware tool surface for the operation. Resolve the relevant one BEFORE a non-trivial operation (editing/promoting a revision, wiring secrets, authoring an agent, debugging a session). Many `agent-applications-*` tool descriptions name the playbook to read first. Pass either a bare id or its `posthog://agent-platform/playbooks/<id>` URI — the `resource` parameter enumerates the available playbooks. Returns `{ id, uri, title, content }` where `content` is the full markdown plus the tool surface.","category": "Agent stack","feature": "agent_platform","summary": "Fetch an agent-platform operator playbook (markdown).",diff --git a/services/mcp/schema/tool-definitions.json b/services/mcp/schema/tool-definitions.jsonindex 55863fb42dc2..785810d5c8d2 100644--- a/services/mcp/schema/tool-definitions.json+++ b/services/mcp/schema/tool-definitions.json@@ -30,7 +30,7 @@}},"agent-resolve-resource": {- "description": "Fetch an operator playbook — a markdown guide for doing a class of agent-platform operations well. These are the same skills the agent concierge loads; resolve the relevant one BEFORE a non-trivial operation (editing/promoting a revision, wiring secrets, authoring an agent, debugging a session). Many `agent-applications-*` tool descriptions name the playbook to read first. Pass either a bare id or its `posthog://agent-platform/playbooks/<id>` URI — the `resource` parameter enumerates the available playbooks. Returns `{ id, uri, title, content }` where `content` is the full markdown.",+ "description": "Fetch a builder playbook — a markdown guide for using the agent-platform authoring tools well, returned with the live, scope-aware tool surface for the operation. Resolve the relevant one BEFORE a non-trivial operation (editing/promoting a revision, wiring secrets, authoring an agent, debugging a session). Many `agent-applications-*` tool descriptions name the playbook to read first. Pass either a bare id or its `posthog://agent-platform/playbooks/<id>` URI — the `resource` parameter enumerates the available playbooks. Returns `{ id, uri, title, content }` where `content` is the full markdown plus the tool surface.","category": "Agent stack","feature": "agent_platform","summary": "Fetch an agent-platform operator playbook (markdown).",diff --git a/services/mcp/schema/tool-inputs.json b/services/mcp/schema/tool-inputs.jsonindex 1dce297a2283..f89e63c4b22b 100644--- a/services/mcp/schema/tool-inputs.json+++ b/services/mcp/schema/tool-inputs.json@@ -20,7 +20,7 @@"properties": {"resource": {"type": "string",- "description": "Which operator playbook to fetch. Accepts either a bare id (one of: auditing-the-fleet, authenticating-as-the-user, authoring-new-agents, choosing-the-model, cost-and-quota-analysis, debugging-sessions, designing-mcp-surfaces, editing-agents-safely, platform-mental-model, querying-ai-observability, reading-an-agent, running-and-evaluating-tests, safety-and-boundaries, secrets-and-integrations, setting-up-slack-app, using-the-console-ui, working-outside-the-console) or its URI form (`posthog://agent-platform/playbooks/<id>`). A playbook is a markdown guide for doing a class of agent-platform operations well — the same skills the agent concierge uses."+ "description": "Which builder playbook to fetch. Accepts either a bare id (one of: authenticating-as-the-user, authoring-new-agents, choosing-the-model, cost-and-quota-analysis, debugging-sessions, designing-mcp-surfaces, editing-agents-safely, platform-mental-model, querying-ai-observability, reading-an-agent, running-and-evaluating-tests, secrets-and-integrations, setting-up-slack-app) or its URI form (`posthog://agent-platform/playbooks/<id>`). A playbook is a markdown guide for using the agent-platform authoring tools well; it comes back with the live, scope-aware tool surface for the operation. Fetch the playbook rather than recalling tool names from memory."}},"required": ["resource"]diff --git a/services/mcp/scripts/copy-instructions.ts b/services/mcp/scripts/copy-instructions.tsindex c94a4f6f4d53..a2bb9138619f 100644--- a/services/mcp/scripts/copy-instructions.ts+++ b/services/mcp/scripts/copy-instructions.ts@@ -11,9 +11,11 @@ import { dirname, join, resolve } from 'path'const ROOT_DIR = resolve(__dirname, '..')const REPO_ROOT = resolve(ROOT_DIR, '../..')-// Single source of truth for the operator playbooks: the agent-builder-// bundle's skills, one `<id>/SKILL.md` per skill.-const SKILLS_DIR = resolve(REPO_ROOT, 'products/agent_platform/services/agent-tests/src/examples/agent-builder/skills')+// Single source of truth for the builder playbooks: `services/mcp/playbooks`,+// one `<id>/SKILL.md` per playbook. These are MCP-owned platform docs about the+// authoring tools — distinct from the concierge's code-bundled *kernel* skills+// (in the agent-builder bundle) and from team `skill_refs` store skills.+const PLAYBOOKS_DIR = resolve(ROOT_DIR, 'playbooks')const PROMPTS = [{@@ -21,10 +23,10 @@ const PROMPTS = [dest: 'shared/guidelines.md',},{- // Operator playbooks embedded so the `agent-resolve-resource` tool can- // serve them. Copied from the agent-builder skills dir (the files the- // agent itself loads); the manifest below is generated from the same.- src: 'products/agent_platform/services/agent-tests/src/examples/agent-builder/skills',+ // Builder playbooks embedded so the `agent-resolve-resource` tool can+ // serve them to any MCP consumer; the manifest below is generated from+ // the same dir.+ src: 'services/mcp/playbooks',dest: 'shared/playbooks',},]@@ -40,9 +42,9 @@ function titleCase(id: string): string {return spaced.charAt(0).toUpperCase() + spaced.slice(1)}-/** Skill ids = subdirs of SKILLS_DIR that contain a SKILL.md, sorted for determinism. */+/** Playbook ids = subdirs of PLAYBOOKS_DIR that contain a SKILL.md, sorted for determinism. */function discoverPlaybookIds(): string[] {- return readdirSync(SKILLS_DIR, { withFileTypes: true })+ return readdirSync(PLAYBOOKS_DIR, { withFileTypes: true }).filter((e) => e.isDirectory()).map((e) => e.name).sort()@@ -62,8 +64,8 @@ function writeIfChanged(path: string, content: string): void {}const GEN_HEADER =- '// AUTO-GENERATED by scripts/copy-instructions.ts from the agent-builder skills dir\n' +- '// (products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/<id>/SKILL.md).\n' ++ '// AUTO-GENERATED by scripts/copy-instructions.ts from the MCP builder playbooks dir\n' ++ '// (services/mcp/playbooks/<id>/SKILL.md).\n' +'// Do not edit by hand — run `tsx services/mcp/scripts/copy-instructions.ts`.\n'/**diff --git a/services/mcp/src/schema/tool-inputs.ts b/services/mcp/src/schema/tool-inputs.tsindex 7f88da56d112..adddcc6b3db5 100644--- a/services/mcp/src/schema/tool-inputs.ts+++ b/services/mcp/src/schema/tool-inputs.ts@@ -29,7 +29,7 @@ export const AgentResolveResourceSchema = z.object({resource: z.string().describe(- `Which operator playbook to fetch. Accepts either a bare id (one of: ${PLAYBOOK_IDS.join(', ')}) or its URI form (\`${PLAYBOOK_URI_PREFIX}<id>\`). A playbook is a markdown guide for doing a class of agent-platform operations well — the same skills the agent concierge uses.`+ `Which builder playbook to fetch. Accepts either a bare id (one of: ${PLAYBOOK_IDS.join(', ')}) or its URI form (\`${PLAYBOOK_URI_PREFIX}<id>\`). A playbook is a markdown guide for using the agent-platform authoring tools well; it comes back with the live, scope-aware tool surface for the operation. Fetch the playbook rather than recalling tool names from memory.`),})diff --git a/services/mcp/src/tools/agentPlatform/playbookContent.generated.ts b/services/mcp/src/tools/agentPlatform/playbookContent.generated.tsindex 75d6922efd36..394c7157954d 100644--- a/services/mcp/src/tools/agentPlatform/playbookContent.generated.ts+++ b/services/mcp/src/tools/agentPlatform/playbookContent.generated.ts@@ -1,7 +1,6 @@-// AUTO-GENERATED by scripts/copy-instructions.ts from the agent-builder skills dir-// (products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/<id>/SKILL.md).+// AUTO-GENERATED by scripts/copy-instructions.ts from the MCP builder playbooks dir+// (services/mcp/playbooks/<id>/SKILL.md).// Do not edit by hand — run `tsx services/mcp/scripts/copy-instructions.ts`.-import auditingTheFleet from '@shared/playbooks/auditing-the-fleet/SKILL.md'import authenticatingAsTheUser from '@shared/playbooks/authenticating-as-the-user/SKILL.md'import authoringNewAgents from '@shared/playbooks/authoring-new-agents/SKILL.md'import choosingTheModel from '@shared/playbooks/choosing-the-model/SKILL.md'@@ -13,16 +12,12 @@ import platformMentalModel from '@shared/playbooks/platform-mental-model/SKILL.mimport queryingAiObservability from '@shared/playbooks/querying-ai-observability/SKILL.md'import readingAnAgent from '@shared/playbooks/reading-an-agent/SKILL.md'import runningAndEvaluatingTests from '@shared/playbooks/running-and-evaluating-tests/SKILL.md'-import safetyAndBoundaries from '@shared/playbooks/safety-and-boundaries/SKILL.md'import secretsAndIntegrations from '@shared/playbooks/secrets-and-integrations/SKILL.md'import settingUpSlackApp from '@shared/playbooks/setting-up-slack-app/SKILL.md'-import usingTheConsoleUi from '@shared/playbooks/using-the-console-ui/SKILL.md'-import workingOutsideTheConsole from '@shared/playbooks/working-outside-the-console/SKILL.md'import type { PlaybookId } from './playbookManifest.generated'export const PLAYBOOK_CONTENT: Record<PlaybookId, string> = {- 'auditing-the-fleet': auditingTheFleet,'authenticating-as-the-user': authenticatingAsTheUser,'authoring-new-agents': authoringNewAgents,'choosing-the-model': choosingTheModel,@@ -34,9 +29,6 @@ export const PLAYBOOK_CONTENT: Record<PlaybookId, string> = {'querying-ai-observability': queryingAiObservability,'reading-an-agent': readingAnAgent,'running-and-evaluating-tests': runningAndEvaluatingTests,- 'safety-and-boundaries': safetyAndBoundaries,'secrets-and-integrations': secretsAndIntegrations,'setting-up-slack-app': settingUpSlackApp,- 'using-the-console-ui': usingTheConsoleUi,- 'working-outside-the-console': workingOutsideTheConsole,}diff --git a/services/mcp/src/tools/agentPlatform/playbookManifest.generated.ts b/services/mcp/src/tools/agentPlatform/playbookManifest.generated.tsindex d19c0afdf23f..240d95c03f90 100644--- a/services/mcp/src/tools/agentPlatform/playbookManifest.generated.ts+++ b/services/mcp/src/tools/agentPlatform/playbookManifest.generated.ts@@ -1,8 +1,7 @@-// AUTO-GENERATED by scripts/copy-instructions.ts from the agent-builder skills dir-// (products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/<id>/SKILL.md).+// AUTO-GENERATED by scripts/copy-instructions.ts from the MCP builder playbooks dir+// (services/mcp/playbooks/<id>/SKILL.md).// Do not edit by hand — run `tsx services/mcp/scripts/copy-instructions.ts`.export const PLAYBOOK_IDS = [- 'auditing-the-fleet','authenticating-as-the-user','authoring-new-agents','choosing-the-model',@@ -14,17 +13,13 @@ export const PLAYBOOK_IDS = ['querying-ai-observability','reading-an-agent','running-and-evaluating-tests',- 'safety-and-boundaries','secrets-and-integrations','setting-up-slack-app',- 'using-the-console-ui',- 'working-outside-the-console',] as constexport type PlaybookId = (typeof PLAYBOOK_IDS)[number]export const PLAYBOOK_TITLES: Record<PlaybookId, string> = {- 'auditing-the-fleet': 'Auditing the fleet','authenticating-as-the-user': 'Authenticating as the user','authoring-new-agents': 'Authoring new agents','choosing-the-model': 'Choosing the model',@@ -36,9 +31,6 @@ export const PLAYBOOK_TITLES: Record<PlaybookId, string> = {'querying-ai-observability': 'Querying ai observability','reading-an-agent': 'Reading an agent','running-and-evaluating-tests': 'Running and evaluating tests',- 'safety-and-boundaries': 'Safety and boundaries','secrets-and-integrations': 'Secrets and integrations','setting-up-slack-app': 'Setting up slack app',- 'using-the-console-ui': 'Using the console ui',- 'working-outside-the-console': 'Working outside the console',}diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-resolve-resource.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-resolve-resource.jsonindex 2f1534a6453b..4290d4362faa 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-resolve-resource.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-resolve-resource.json@@ -2,7 +2,7 @@"$schema": "https://json-schema.org/draft/2020-12/schema","properties": {"resource": {- "description": "Which operator playbook to fetch. Accepts either a bare id (one of: auditing-the-fleet, authenticating-as-the-user, authoring-new-agents, choosing-the-model, cost-and-quota-analysis, debugging-sessions, designing-mcp-surfaces, editing-agents-safely, platform-mental-model, querying-ai-observability, reading-an-agent, running-and-evaluating-tests, safety-and-boundaries, secrets-and-integrations, setting-up-slack-app, using-the-console-ui, working-outside-the-console) or its URI form (`posthog://agent-platform/playbooks/<id>`). A playbook is a markdown guide for doing a class of agent-platform operations well — the same skills the agent concierge uses.",+ "description": "Which builder playbook to fetch. Accepts either a bare id (one of: authenticating-as-the-user, authoring-new-agents, choosing-the-model, cost-and-quota-analysis, debugging-sessions, designing-mcp-surfaces, editing-agents-safely, platform-mental-model, querying-ai-observability, reading-an-agent, running-and-evaluating-tests, secrets-and-integrations, setting-up-slack-app) or its URI form (`posthog://agent-platform/playbooks/<id>`). A playbook is a markdown guide for using the agent-platform authoring tools well; it comes back with the live, scope-aware tool surface for the operation. Fetch the playbook rather than recalling tool names from memory.","type": "string"}},diff --git a/services/mcp/tests/unit/agent-resolve-resource.test.ts b/services/mcp/tests/unit/agent-resolve-resource.test.tsindex 4f9c5caa7982..4ccc49744966 100644--- a/services/mcp/tests/unit/agent-resolve-resource.test.ts+++ b/services/mcp/tests/unit/agent-resolve-resource.test.ts@@ -10,13 +10,10 @@ import { resolveResourceHandler } from '@/tools/agentPlatform/resolveResource'import { getToolDefinitions } from '@/tools/toolDefinitions'import type { Context } from '@/tools/types'-// Canonical source: the agent-builder bundle's skills dir (one `<id>/SKILL.md`-// per skill). The build copies these into shared/playbooks/ (embedded) — both+// Canonical source: the MCP builder-playbooks dir (one `<id>/SKILL.md` per+// playbook). The build copies these into shared/playbooks/ (embedded) — both// must stay in lockstep with PLAYBOOK_IDS.-const SKILLS_DIR = resolve(- __dirname,- '../../../../products/agent_platform/services/agent-tests/src/examples/agent-builder/skills'-)+const PLAYBOOKS_DIR = resolve(__dirname, '../../playbooks')// Context whose api key carries the given scopes (drives the live tool surface).const ctxWithScopes = (scopes: string[]): Context =>@@ -64,12 +61,12 @@ describe('agent-resolve-resource', () => {})describe('playbook inventory', () => {- it('PLAYBOOK_IDS matches the skill dirs in the concierge bundle', () => {- const skillDirs = readdirSync(SKILLS_DIR, { withFileTypes: true })+ it('PLAYBOOK_IDS matches the dirs in the MCP playbooks source', () => {+ const playbookDirs = readdirSync(PLAYBOOKS_DIR, { withFileTypes: true }).filter((e) => e.isDirectory()).map((e) => e.name).sort()- expect(skillDirs).toEqual([...PLAYBOOK_IDS].sort())+ expect(playbookDirs).toEqual([...PLAYBOOK_IDS].sort())})it('every id has embedded, non-empty content', () => {@@ -134,7 +131,7 @@ describe('agent-resolve-resource', () => {})it('playbooks with no associated tools omit the surface section', async () => {- const result = await resolveResourceHandler(ctxWithScopes(['*']), { resource: 'safety-and-boundaries' })+ const result = await resolveResourceHandler(ctxWithScopes(['*']), { resource: 'platform-mental-model' })expect(result.content).not.toContain('Tools for this playbook')expect(result.tools.callable).toHaveLength(0)expect(result.tools.gated).toHaveLength(0)