:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(agent_platform): harden platform invariants across bug-classes (#69107)
Danilo Campos0a63e8473627
diff --git a/.github/workflows/ci-agents.yml b/.github/workflows/ci-agents.ymlindex 83fb816f040c..2e9bf1e8945c 100644--- a/.github/workflows/ci-agents.yml+++ b/.github/workflows/ci-agents.yml@@ -45,6 +45,10 @@ jobs:- .github/workflows/ci-agents.yml- 'products/agent_platform/services/**'- 'products/agent_platform/packages/**'+ # Generated vocabularies (TS source of truth → checked-in JSON+ # Django imports). A JSON-only edit must re-run the freshness+ # test in agent-shared, else drift ships green.+ - 'products/agent_platform/backend/logic/*.generated.json'# Transitional: in-flight branches still have these at the# old paths. Drop once they've rebased onto the move.- 'services/agent-ingress/**'diff --git a/.prettierignore b/.prettierignorenew file mode 100644index 000000000000..dbd72c3371fc--- /dev/null+++ b/.prettierignore@@ -0,0 +1 @@+products/agent_platform/**/*.generated.jsondiff --git a/package.json b/package.jsonindex 265e60b81d4d..b5bbfef378f3 100644--- a/package.json+++ b/package.json@@ -107,7 +107,8 @@"bin/hogli format:python","uv run --no-sync ty check"],- "*.{md,mdx}": "bin/hogli format:markdown"+ "*.{md,mdx}": "bin/hogli format:markdown",+ "products/agent_platform/**/*.{ts,py}": "products/agent_platform/bin/coherence-precommit"},"browserslist": {"development": [diff --git a/products/agent_platform/.gitignore b/products/agent_platform/.gitignorenew file mode 100644index 000000000000..d657708712bd--- /dev/null+++ b/products/agent_platform/.gitignore@@ -0,0 +1,2 @@+# Local coherence CLI cache (pre-commit gate; see bin/coherence-install)+.coherence-tool/diff --git a/products/agent_platform/backend/.gitignore b/products/agent_platform/backend/.gitignorenew file mode 100644index 000000000000..b897b584bc44--- /dev/null+++ b/products/agent_platform/backend/.gitignore@@ -0,0 +1,2 @@+.coherence-out/+.coherence/diff --git a/products/agent_platform/backend/coherence.config.json b/products/agent_platform/backend/coherence.config.jsonnew file mode 100644index 000000000000..991738c2a32c--- /dev/null+++ b/products/agent_platform/backend/coherence.config.json@@ -0,0 +1,10 @@+{+ "outputDir": ".coherence-out",+ "entryDir": "logic",+ "ignore": ["migrations", "__pycache__", ".coherence-out"],+ "codeExt": ["py"],+ "typecheck": ["uv", "run", "--no-sync", "ty", "check", "logic"],+ "test": ["env", "DJANGO_SETTINGS_MODULE=posthog.settings", "python", "-m", "pytest", "-q", "-k"],+ "testMatch": "[1-9][0-9]* passed",+ "language": "python"+}diff --git a/products/agent_platform/backend/logic/Logic.spec.md b/products/agent_platform/backend/logic/Logic.spec.mdnew file mode 100644index 000000000000..f6d8e41c1294--- /dev/null+++ b/products/agent_platform/backend/logic/Logic.spec.md@@ -0,0 +1,24 @@+# Logic++Django-side authoring logic: the promote-time secret gate and the loaders for the TS-emitted vocabulary artifacts the control plane consumes instead of hand-maintaining mirrors.++## invariants++- unregistered-trigger-fail-closed+- generated-vocabulary-loader+- artifact-ci-coverage++## works when++- typechecks+- boundary "unregistered-trigger-fail-closed" at missing_required_secrets+- passes test "test_missing_required_secrets_fails_closed_on_unregistered_trigger"+- boundary "generated-vocabulary-loader" at \_load+- passes test "test_generated_vocabularies_load_and_are_nonempty"+- boundary "artifact-ci-coverage" at TRIGGER_REQUIRED_SECRETS via test "test_ci_agents_filter_covers_every_generated_artifact"++## why++unregistered-trigger-fail-closed: the promote gate walks each trigger's required-secret contract, and a trigger type the node schema accepts but this registry doesn't know must BLOCK promote rather than pass with zero required secrets — the old `.get(type, [])` fail-open let a new trigger ship with its signing secret never enforced. `missing_required_secrets` is the single gate every promote crosses; the oracle proves an unregistered type yields a blocking entry.+generated-vocabulary-loader: every vocabulary Django consumes (trigger secrets, routes, approval states, stop reasons) loads through one `_load` that reads UTF-8 explicitly, fails closed with a legible `ImproperlyConfigured` naming the file and the regen command, and rejects wrong-shaped artifacts — a corrupt or missing generated JSON must be a clear boot-time error, not a cryptic traceback or a silent empty vocabulary.+artifact-ci-coverage: a guard only counts if CI actually invokes it — the TS freshness test that welds each generated JSON to its source runs under a CI path filter, and an artifact outside that filter can drift green. The oracle enumerates every `*.generated.json` on disk and asserts the `ci-agents` filter covers each, so adding an artifact without CI coverage is a red build naming the file.diff --git a/products/agent_platform/backend/logic/approval_request_states.generated.json b/products/agent_platform/backend/logic/approval_request_states.generated.jsonnew file mode 100644index 000000000000..b4ca462b7ee4--- /dev/null+++ b/products/agent_platform/backend/logic/approval_request_states.generated.json@@ -0,0 +1,8 @@+[+ "queued",+ "approving",+ "dispatched",+ "dispatched_failed",+ "rejected",+ "expired"+]diff --git a/products/agent_platform/backend/logic/assistant_stop_reasons.generated.json b/products/agent_platform/backend/logic/assistant_stop_reasons.generated.jsonnew file mode 100644index 000000000000..5796dc5aaac1--- /dev/null+++ b/products/agent_platform/backend/logic/assistant_stop_reasons.generated.json@@ -0,0 +1,7 @@+[+ "stop",+ "length",+ "toolUse",+ "error",+ "aborted"+]diff --git a/products/agent_platform/backend/logic/generated.py b/products/agent_platform/backend/logic/generated.pynew file mode 100644index 000000000000..d8e9aa7f0cc7--- /dev/null+++ b/products/agent_platform/backend/logic/generated.py@@ -0,0 +1,50 @@+"""Loaders for TS-emitted spec vocabularies (source: services/agent-shared/src/spec/).++Don't edit *.generated.json; regenerate: UPDATE_GENERATED=1 npx vitest run src/spec/spec-codegen.test.ts.+"""++from __future__ import annotations++import json+from pathlib import Path+from typing import Any++from django.core.exceptions import ImproperlyConfigured++_DIR = Path(__file__).parent+++def _load(name: str, expected: type) -> Any:+ # Runs at django.setup(); fail closed but legibly on a missing/corrupt artifact. Read+ # UTF-8 explicitly — the trigger-secret registry contains `→`, which a C/POSIX default decode chokes on.+ path = _DIR / name+ try:+ value = json.loads(path.read_text(encoding="utf-8"))+ except (OSError, ValueError) as e:+ raise ImproperlyConfigured(+ f"agent_platform: generated vocabulary '{name}' is missing or corrupt ({e}). "+ "Regenerate with: UPDATE_GENERATED=1 npx vitest run src/spec/spec-codegen.test.ts"+ ) from e+ # Fail closed on a wrong-container artifact so it surfaces here by name, not later+ # as an AttributeError on `.get()` deep in the promote path.+ if not isinstance(value, expected):+ raise ImproperlyConfigured(+ f"agent_platform: generated vocabulary '{name}' has unexpected shape "+ f"{type(value).__name__}, expected {expected.__name__}"+ )+ return value+++# Per-trigger-type required secrets (source: trigger-secrets.ts).+TRIGGER_REQUIRED_SECRETS: dict[str, list[dict[str, Any]]] = _load("trigger_required_secrets.generated.json", dict)++# Per-trigger ingress route catalogue `{route_name: path}`, `{}` for triggers with no+# inbound HTTP route (cron). Source: trigger-routes.ts, also imported by agent-ingress so the two can't drift.+TRIGGER_ROUTES: dict[str, dict[str, str]] = _load("trigger_routes.generated.json", dict)++# States the runner writes to `agent_tool_approval_request.state` (source: approval-store.ts).+# Consumed by the DRF serializer choices and the model's DB CheckConstraint.+APPROVAL_REQUEST_STATES: list[str] = _load("approval_request_states.generated.json", list)++# Assistant turn stop reasons (source: spec.ts). Consumed by the assistant-message serializer's `stopReason` choices.+ASSISTANT_STOP_REASONS: list[str] = _load("assistant_stop_reasons.generated.json", list)diff --git a/products/agent_platform/backend/logic/spec_schema.py b/products/agent_platform/backend/logic/spec_schema.pyindex fcd1a35f719f..11384fe6f7fe 100644--- a/products/agent_platform/backend/logic/spec_schema.py+++ b/products/agent_platform/backend/logic/spec_schema.py@@ -17,44 +17,17 @@ from __future__ import annotationsfrom typing import Any+from .generated import TRIGGER_REQUIRED_SECRETS+# ── Per-trigger-type required secrets ──────────────────────────────────────#-# Mirrors `services/agent-shared/src/spec/trigger-secrets.ts` for the-# Django-side validation path. Keep the two in lockstep — the slack trigger-# handler in agent-ingress reads `SLACK_SIGNING_SECRET_KEY` and the freeze /-# promote gate here rejects revisions whose agent's `encrypted_env` is missing-# the same key.+# `TRIGGER_REQUIRED_SECRETS` imported from the generated artifact (source: trigger-secrets.ts).+# The promote gate here rejects revisions whose `encrypted_env` misses a `required` key.SLACK_SIGNING_SECRET_KEY = "SLACK_SIGNING_SECRET"SLACK_BOT_TOKEN_KEY = "SLACK_BOT_TOKEN"-TRIGGER_REQUIRED_SECRETS: dict[str, list[dict[str, Any]]] = {- "chat": [],- "webhook": [],- "cron": [],- "mcp": [],- "slack": [- {- "key": SLACK_SIGNING_SECRET_KEY,- "label": "Slack signing secret",- "description": (- "Your Slack app's signing secret. Find it under Settings → Basic Information → "- "Signing Secret. Required to verify inbound Slack event signatures."- ),- "required": True,- },- {- "key": SLACK_BOT_TOKEN_KEY,- "label": "Slack bot user OAuth token",- "description": (- "Your Slack app's bot token (starts with `xoxb-`). Find it under Settings → "- "Install App → Bot User OAuth Token after installing the app to your workspace. "- "Used by native slack tools to call the Slack API."- ),- "required": True,- },- ],-}+__all__ = ["SLACK_SIGNING_SECRET_KEY", "SLACK_BOT_TOKEN_KEY", "TRIGGER_REQUIRED_SECRETS", "missing_required_secrets"]def _auth_mode_secret_requirement(mode: dict[str, Any]) -> dict[str, Any] | None:@@ -97,6 +70,7 @@ def missing_required_secrets(spec: dict[str, Any], env_map: dict[str, str]) -> lif not isinstance(triggers, list):return outseen_keys: set[str] = set()+ seen_unknown: set[str] = set()def consider(requirement: dict[str, Any], trigger_type: str) -> None:if not requirement.get("required"):@@ -114,7 +88,27 @@ def missing_required_secrets(spec: dict[str, Any], env_map: dict[str, str]) -> ltrigger_type = trigger.get("type")if not isinstance(trigger_type, str):continue- for requirement in TRIGGER_REQUIRED_SECRETS.get(trigger_type, []):+ requirements = TRIGGER_REQUIRED_SECRETS.get(trigger_type)+ if requirements is None:+ # Fail closed: a type absent from this registry means Django's secret contract+ # drifted behind the zod `TriggerType` enum. Block promote loudly rather than pass+ # with zero required secrets.+ if trigger_type not in seen_unknown:+ seen_unknown.add(trigger_type)+ out.append(+ {+ "key": f"<no secret contract for '{trigger_type}' trigger>",+ "label": "Unregistered trigger type",+ "description": (+ f"The '{trigger_type}' trigger has no entry in TRIGGER_REQUIRED_SECRETS; "+ "add its required-secret contract in spec_schema.py before promoting."+ ),+ "required": True,+ "trigger": trigger_type,+ }+ )+ continue+ for requirement in requirements:consider(requirement, trigger_type)auth = trigger.get("auth")modes = auth.get("modes") if isinstance(auth, dict) else Nonediff --git a/products/agent_platform/backend/logic/trigger_required_secrets.generated.json b/products/agent_platform/backend/logic/trigger_required_secrets.generated.jsonnew file mode 100644index 000000000000..91332519c33b--- /dev/null+++ b/products/agent_platform/backend/logic/trigger_required_secrets.generated.json@@ -0,0 +1,20 @@+{+ "chat": [],+ "webhook": [],+ "cron": [],+ "mcp": [],+ "slack": [+ {+ "key": "SLACK_SIGNING_SECRET",+ "label": "Slack signing secret",+ "description": "Your Slack app's signing secret. Find it under Settings → Basic Information → Signing Secret. Required to verify inbound Slack event signatures.",+ "required": true+ },+ {+ "key": "SLACK_BOT_TOKEN",+ "label": "Slack bot user OAuth token",+ "description": "Your Slack app's bot token (starts with `xoxb-`). Find it under Settings → Install App → Bot User OAuth Token after installing the app to your workspace. Used by native slack tools to call the Slack API.",+ "required": true+ }+ ]+}diff --git a/products/agent_platform/backend/logic/trigger_routes.generated.json b/products/agent_platform/backend/logic/trigger_routes.generated.jsonnew file mode 100644index 000000000000..b32c9b0d4c07--- /dev/null+++ b/products/agent_platform/backend/logic/trigger_routes.generated.json@@ -0,0 +1,22 @@+{+ "chat": {+ "run": "/run",+ "send": "/send",+ "cancel": "/cancel",+ "listen": "/listen",+ "client_tool_result": "/client_tool_result"+ },+ "slack": {+ "events": "/slack/events",+ "interactivity": "/slack/interactivity"+ },+ "cron": {},+ "webhook": {+ "post": "/webhook"+ },+ "mcp": {+ "rpc": "/mcp",+ "stream": "/mcp/stream",+ "connect_info": "/mcp/connect-info"+ }+}diff --git a/products/agent_platform/backend/models.py b/products/agent_platform/backend/models.pyindex 8f288f865e4c..0f2444770d40 100644--- a/products/agent_platform/backend/models.py+++ b/products/agent_platform/backend/models.py@@ -28,6 +28,8 @@ from posthog.helpers.encrypted_fields import EncryptedTextFieldfrom posthog.models.scoping.product_mixin import ProductTeamModelfrom posthog.models.utils import UUIDModel+from .logic.generated import APPROVAL_REQUEST_STATES+REVISION_STATE_CHOICES = [("draft", "draft"),("ready", "ready"),@@ -296,16 +298,10 @@ class AgentToolApprovalRequest(ProductTeamModel, UUIDModel):constraints = [models.CheckConstraint(name="agent_tool_approval_request_state_valid",- condition=Q(- state__in=[- "queued",- "approving",- "dispatched",- "dispatched_failed",- "rejected",- "expired",- ]- ),+ # Imported from the generated artifact (source: approval-store.ts). Changing it+ # needs a migration, deploy-ordered vs the runner: widen the CHECK before a new+ # state, narrow after it stops being written.+ condition=Q(state__in=APPROVAL_REQUEST_STATES),),models.UniqueConstraint(fields=["session_id", "tool_name", "args_hash"],diff --git a/products/agent_platform/backend/presentation/serializers.py b/products/agent_platform/backend/presentation/serializers.pyindex bc37328e410e..48b77e2ede31 100644--- a/products/agent_platform/backend/presentation/serializers.py+++ b/products/agent_platform/backend/presentation/serializers.py@@ -22,6 +22,8 @@ from rest_framework import serializersfrom posthog.models import User+from products.mcp_store.backend.facade.api import unauthorized_installation_ids+from ..models import REVISION_STATE_CHOICES, AgentApplication, AgentRevision# Opaque random slug: leading letter (DNS-label-safe) + lowercase alphanumerics.@@ -100,6 +102,35 @@ def _validate_mcp_tool_names_unique(spec: Any) -> None:seen.add(name)+def _validate_mcp_connection_ownership(spec: Any, context: dict[str, Any], author_id: int | None) -> None:+ # Early authoring feedback, NOT the security boundary — the runtime+ # `PgMcpConnectionStore.resolve` is authoritative (scopes lookups to the revision+ # author). Lenient when author/team can't be resolved, since the runtime still enforces.+ if not isinstance(spec, dict):+ return+ mcps = spec.get("mcps")+ if not isinstance(mcps, list):+ return+ referenced: list[tuple[int, str]] = []+ for i, mcp in enumerate(mcps):+ if isinstance(mcp, dict):+ conn = mcp.get("connection")+ if isinstance(conn, str) and conn:+ referenced.append((i, conn))+ if not referenced:+ return+ get_team = context.get("get_team")+ team = get_team() if callable(get_team) else None+ if team is None or author_id is None:+ return+ rejected = set(unauthorized_installation_ids(team.id, author_id, [conn for _, conn in referenced]))+ for i, conn in referenced:+ if conn in rejected:+ raise serializers.ValidationError(+ f"spec.mcps.{i}.connection: installation not found or not owned by the agent author"+ )++class AgentApplicationSerializer(serializers.ModelSerializer):slack_events_url = serializers.SerializerMethodField(help_text=(@@ -353,6 +384,14 @@ class AgentRevisionSerializer(serializers.ModelSerializer):# here — keeping one in lockstep with zod was the drift this removed. We# still enforce the cross-field invariant the serializer owns._validate_mcp_tool_names_unique(value)+ # The owning author is the existing revision's creator on edit; on create+ # it is the request user (which `perform_create` stamps as `created_by`).+ author_id: int | None = getattr(self.instance, "created_by_id", None)+ if author_id is None:+ request_user = getattr(self.context.get("request"), "user", None)+ if request_user is not None and getattr(request_user, "is_authenticated", False):+ author_id = request_user.id+ _validate_mcp_connection_ownership(value, self.context, author_id)return valueclass Meta:diff --git a/products/agent_platform/backend/presentation/views.py b/products/agent_platform/backend/presentation/views.pyindex 3bfc31b0e563..7575edf606fd 100644--- a/products/agent_platform/backend/presentation/views.py+++ b/products/agent_platform/backend/presentation/views.py@@ -72,6 +72,7 @@ from posthog.permissions import get_authenticator_scopesfrom posthog.security.outbound_proxy import internal_requestsfrom ..db import WRITER_DB+from ..logic.generated import APPROVAL_REQUEST_STATES, ASSISTANT_STOP_REASONS, TRIGGER_ROUTESfrom ..logic.internal_jwt import AgentInternalAudience, encode_agent_internal_jwtfrom ..logic.janitor_client import JanitorClient, JanitorClientError, default_clientfrom ..logic.kernel_skills import all_kernel_skill_ids, kernel_skills_for@@ -113,6 +114,10 @@ from .serializers import (logger = logging.getLogger(__name__)+# `TRIGGER_ROUTES` keys are the full trigger-kind enumeration (`Record<TriggerType, …>`,+# cron included), so help_text can render the list without hand-copying it.+_TRIGGER_KIND_ENUM = " | ".join(TRIGGER_ROUTES.keys())+def _resolve_application(queryset: QuerySet, lookup_value: str | None) -> AgentApplication | None:"""Look up by UUID if the URL value parses as one, otherwise by slug.@@ -296,43 +301,11 @@ def _mint_preview_jwt(return token, ttl_seconds-# Per-trigger route catalogue. Mirrors the `path:` arrays in each-# `services/agent-ingress/src/triggers/<type>.ts` `routes` export — keep-# these tables in sync (a sibling test validates the chat one). Source of-# truth is still the ingress; this is here so the preview-token caller-# doesn't have to grep the ingress source to know which path to hit.-_TRIGGER_ROUTES: dict[str, dict[str, str]] = {- "chat": {- "run": "/run",- "send": "/send",- "cancel": "/cancel",- "listen": "/listen",- "client_tool_result": "/client_tool_result",- },- "mcp": {- "rpc": "/mcp",- "stream": "/mcp/stream",- "connect_info": "/mcp/connect-info",- },- "slack": {- "events": "/slack/events",- "interactivity": "/slack/interactivity",- },- "webhook": {- "post": "/webhook",- },- # `cron` triggers have no externally-callable ingress endpoint —- # they fire from the janitor's scheduler. Omit from the catalogue- # so the preview response doesn't advertise a URL the caller can't- # actually hit.-}--def _build_preview_endpoints(ingress_slug: str, spec: dict[str, Any]) -> dict[str, dict[str, str]]:- """Return `{trigger_type: {route_name: absolute_url}}` for every- trigger the spec declares that has a public ingress route in- `_TRIGGER_ROUTES`. Empty when no public agent-ingress URL is configured- for the active routing mode (local dev without `bin/agent-tunnel`)."""+ """Return `{trigger_type: {route_name: absolute_url}}` for every spec trigger with a+ public ingress route in `TRIGGER_ROUTES`. `cron` maps to `{}` (no ingress endpoint) and+ is skipped. Empty when no public agent-ingress URL is configured (local dev without+ `bin/agent-tunnel`)."""triggers = spec.get("triggers") or []if not isinstance(triggers, list):return {}@@ -343,7 +316,7 @@ def _build_preview_endpoints(ingress_slug: str, spec: dict[str, Any]) -> dict[stttype = trigger.get("type")if not isinstance(ttype, str):continue- routes = _TRIGGER_ROUTES.get(ttype)+ routes = TRIGGER_ROUTES.get(ttype)if not routes:continue# First trigger of a given type wins; spec-side validation@@ -467,7 +440,8 @@ _AGENT_ASSISTANT_MESSAGE = inline_serializer("model": drf_serializers.CharField(required=False),"usage": drf_serializers.DictField(child=drf_serializers.JSONField(), required=False),"stopReason": drf_serializers.ChoiceField(- choices=["stop", "length", "toolUse", "error", "aborted"],+ # Imported from the generated artifact (source: spec.ts) so it can't drift from what the runner writes.+ choices=ASSISTANT_STOP_REASONS,required=False,),"errorMessage": drf_serializers.CharField(required=False),@@ -1131,7 +1105,7 @@ class AgentApplicationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):required=False,help_text=("Trigger-specific metadata stamped at session creation. Discriminated on "- "`kind`: chat | slack | cron | webhook | mcp. The Zod source of truth is "+ f"`kind`: {_TRIGGER_KIND_ENUM}. The Zod source of truth is ""`agent-shared/src/runtime/trigger-metadata.ts`; the node side validates ""and strips unknown keys at the persistence boundary, so consumers can ""trust `kind` and per-kind fields. TODO: narrow this DictField to a "@@ -1338,7 +1312,7 @@ class AgentApplicationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):required=False,help_text=("Trigger-specific metadata stamped at session creation. Discriminated on "- "`kind`: chat | slack | cron | webhook | mcp. The Zod source of truth is "+ f"`kind`: {_TRIGGER_KIND_ENUM}. The Zod source of truth is ""`agent-shared/src/runtime/trigger-metadata.ts`; the node side validates and ""strips unknown keys at the persistence boundary, so consumers can trust ""`kind` and per-kind fields. TODO: narrow this DictField to a polymorphic "@@ -1494,14 +1468,8 @@ class AgentApplicationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):help_text="Resolved approval policy (type: principal|agent, allow_edit) at request time.",),"state": drf_serializers.ChoiceField(- choices=[- "queued",- "approving",- "dispatched",- "dispatched_failed",- "rejected",- "expired",- ],+ # Imported from the generated artifact (source: approval-store.ts) so it can't drift from what the runner writes.+ choices=APPROVAL_REQUEST_STATES,help_text="Lifecycle state. `queued` = awaiting an approver; `approving` = decision landed and tool dispatch is in flight; `dispatched`/`dispatched_failed` = approved + tool ran; `rejected` = approver said no; `expired` = TTL elapsed.",),"decision_by": drf_serializers.CharField(@@ -1676,10 +1644,12 @@ class AgentApplicationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):raise JanitorUpstreamError(e) from e# Only `agent`-type approvals are decided through the console. A# `principal`-type request is the session owner's to clear at the ingress- # decision API; collapse it to not-found here. (Legacy rows queued before- # the principal/agent split carry `approvers[]` instead of `type` — map- # `team_admins` → agent so an in-flight old row stays decidable.)- scope = existing.get("approver_scope", {})+ # decision API; collapse it to not-found here.+ #+ # Legacy fallback keeps this decode order-independent across a janitor rollout:+ # an old janitor may return the pre-resolution `approvers[]` shape (no `type`),+ # which we still resolve. Transitional.+ scope = existing.get("approver_scope") or {}approval_type = scope.get("type")if approval_type is None:approval_type = "agent" if "team_admins" in (scope.get("approvers") or []) else "principal"@@ -3594,7 +3564,7 @@ class AgentFleetViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):required=False,help_text=("Trigger-specific metadata stamped at session creation. Discriminated on "- "`kind`: chat | slack | cron | webhook | mcp. The Zod source of truth is "+ f"`kind`: {_TRIGGER_KIND_ENUM}. The Zod source of truth is ""`agent-shared/src/runtime/trigger-metadata.ts`; the node side validates ""and strips unknown keys at the persistence boundary, so consumers can ""trust `kind` and per-kind fields. TODO: narrow this DictField to a "diff --git a/products/agent_platform/backend/tests/test_approvals_api.py b/products/agent_platform/backend/tests/test_approvals_api.pyindex 3f6fb1fd286a..43232ec83430 100644--- a/products/agent_platform/backend/tests/test_approvals_api.py+++ b/products/agent_platform/backend/tests/test_approvals_api.py@@ -160,6 +160,30 @@ class TestApprovalEndpointsAuth(APIBaseTest):self.assertEqual(resp.status_code, status.HTTP_404_NOT_FOUND)mock_janitor.return_value.decide_approval.assert_not_called()+ @parameterized.expand(+ [+ ("legacy_team_admins_decidable", {"approvers": ["team_admins"]}, True),+ ("legacy_session_principal_not_decidable", {"approvers": ["session_principal"]}, False),+ ("empty_scope_not_decidable", {}, False),+ ]+ )+ @patch("products.agent_platform.backend.presentation.views._janitor")+ def test_decide_gate_resolves_legacy_scope_shapes(self, _name, scope, decidable, mock_janitor) -> None:+ self._set_org_level(OrganizationMembership.Level.ADMIN)+ mock_janitor.return_value.get_approval.return_value = {+ "id": self.approval_id,+ "application_id": str(self.application.id),+ "approver_scope": scope,+ }+ mock_janitor.return_value.decide_approval.return_value = {"ok": True, "state": "approving"}+ resp = self.client.post(self.url_decide, {"decision": "approve"}, format="json")+ if decidable:+ self.assertEqual(resp.status_code, status.HTTP_200_OK)+ mock_janitor.return_value.decide_approval.assert_called_once()+ else:+ self.assertEqual(resp.status_code, status.HTTP_404_NOT_FOUND)+ mock_janitor.return_value.decide_approval.assert_not_called()+# A Personal API key resolves to an authenticated User but is not# `SessionAuthentication` — agent (owner) decisions require a human acting# interactively (session or first-party OAuth), so a PAT is always rejected.diff --git a/products/agent_platform/backend/tests/test_ci_guard_coverage.py b/products/agent_platform/backend/tests/test_ci_guard_coverage.pynew file mode 100644index 000000000000..a465b6fc18cb--- /dev/null+++ b/products/agent_platform/backend/tests/test_ci_guard_coverage.py@@ -0,0 +1,70 @@+from __future__ import annotations++import fnmatch+from pathlib import Path+from typing import Any++import yaml++_REPO_ROOT = Path(__file__).resolve().parents[4]+_CI_AGENTS = _REPO_ROOT / ".github" / "workflows" / "ci-agents.yml"+_GENERATED_DIR = Path(__file__).resolve().parent.parent / "logic"++# Named, not counted, so a path break or dropped artifact reds by name. Add new artifacts here.+_EXPECTED_ARTIFACTS = {+ "approval_request_states.generated.json",+ "assistant_stop_reasons.generated.json",+ "trigger_required_secrets.generated.json",+ "trigger_routes.generated.json",+}+++def _glob_match(path: str, pattern: str) -> bool:+ # fnmatch's `*` crosses `/`, but the CI gate (dorny/paths-filter → picomatch) treats `*` as+ # single-segment and `**` as multi-segment. Match the gate so we don't greenlight a pattern it wouldn't.+ p_segs = path.split("/")+ pat_segs = pattern.split("/")++ def match(pi: int, si: int) -> bool:+ if pi == len(pat_segs):+ return si == len(p_segs)+ if pat_segs[pi] == "**":+ return any(match(pi + 1, k) for k in range(si, len(p_segs) + 1))+ if si == len(p_segs):+ return False+ if fnmatch.fnmatch(p_segs[si], pat_segs[pi]):+ return match(pi + 1, si + 1)+ return False++ return match(0, 0)+++def _agents_filter_patterns() -> list[str]:+ workflow = yaml.safe_load(_CI_AGENTS.read_text(encoding="utf-8"))+ for job in (workflow.get("jobs") or {}).values():+ for step in job.get("steps") or []:+ with_block: dict[str, Any] = step.get("with") or {}+ raw = with_block.get("filters")+ if not isinstance(raw, str):+ continue+ parsed = yaml.safe_load(raw) or {}+ agents = parsed.get("agents")+ if isinstance(agents, list):+ return [p for p in agents if isinstance(p, str)]+ raise AssertionError("could not find the `agents` path filter in ci-agents.yml")+++def test_ci_agents_filter_covers_every_generated_artifact() -> None:+ patterns = _agents_filter_patterns()+ generated = sorted(p.name for p in _GENERATED_DIR.glob("*.generated.json"))+ missing = _EXPECTED_ARTIFACTS - set(generated)+ assert not missing, f"expected generated artifacts absent (path change or deletion?): {sorted(missing)}"++ for name in generated:+ rel = f"products/agent_platform/backend/logic/{name}"+ covered = any(_glob_match(rel, pattern) for pattern in patterns)+ assert covered, (+ f"{rel} is not covered by the ci-agents path filter, so an edit to it "+ f"would not re-run the freshness guard. Add its directory to the `agents` "+ f"filter in .github/workflows/ci-agents.yml."+ )diff --git a/products/agent_platform/backend/tests/test_mcp_connection_authz.py b/products/agent_platform/backend/tests/test_mcp_connection_authz.pynew file mode 100644index 000000000000..a88315803cfc--- /dev/null+++ b/products/agent_platform/backend/tests/test_mcp_connection_authz.py@@ -0,0 +1,88 @@+from __future__ import annotations++from typing import Any++from posthog.test.base import APIBaseTest++from parameterized import parameterized+from rest_framework import serializers++from posthog.models import User++from products.mcp_store.backend.models import MCPServerInstallation++from ..models import AgentApplication, AgentRevision+from ..presentation.serializers import AgentRevisionSerializer+++def _spec_with_connection(connection_id: str) -> dict[str, Any]:+ return {+ "mcps": [+ {+ "id": "m",+ "url": "https://mcp.example.test/mcp",+ "kind": "agent",+ "default_tool_approval": "approve",+ "connection": connection_id,+ }+ ]+ }+++class TestMcpConnectionAuthz(APIBaseTest):+ databases = {"default", "agent_platform_db_writer", "agent_platform_db_reader"}++ def setUp(self) -> None:+ super().setUp()+ self.other = User.objects.create_and_join(self.organization, "[email protected]", "pw")+ self.mine = MCPServerInstallation.objects.create(+ team=self.team, user=self.user, url="https://mine.example.test/mcp"+ )+ self.theirs = MCPServerInstallation.objects.create(+ team=self.team, user=self.other, url="https://theirs.example.test/mcp"+ )+ self.application = AgentApplication.all_teams.create(+ team_id=self.team.id, slug="agent", name="Agent", description=""+ )++ def _serializer(self, user: User | None, instance: AgentRevision | None = None) -> AgentRevisionSerializer:+ request = type("Req", (), {"user": user})()+ return AgentRevisionSerializer(instance=instance, context={"request": request, "get_team": lambda: self.team})++ def test_accepts_connection_owned_by_author(self) -> None:+ spec = _spec_with_connection(str(self.mine.id))+ self.assertEqual(self._serializer(self.user).validate_spec(spec)["mcps"][0]["connection"], str(self.mine.id))++ def test_accepts_spec_without_any_connection(self) -> None:+ spec = {"mcps": [{"id": "m", "url": "https://x.test", "kind": "principal", "auth": {"provider": "gh"}}]}+ self.assertEqual(self._serializer(self.user).validate_spec(spec), spec | {"skills": []})++ @parameterized.expand(+ [+ ("teammate_owned_idor",),+ ("nonexistent_uuid",),+ ("not_a_uuid",),+ ]+ )+ def test_rejects_unowned_connection(self, case: str) -> None:+ connection_id = {+ "teammate_owned_idor": lambda: str(self.theirs.id),+ "nonexistent_uuid": lambda: "00000000-0000-0000-0000-000000000000",+ "not_a_uuid": lambda: "not-a-uuid",+ }[case]()+ with self.assertRaises(serializers.ValidationError):+ self._serializer(self.user).validate_spec(_spec_with_connection(connection_id))++ def test_editor_can_save_owners_revision_referencing_owners_connection(self) -> None:+ revision = AgentRevision.all_teams.create(+ application=self.application, state="draft", spec={}, created_by_id=self.user.id+ )+ result = self._serializer(self.other, instance=revision).validate_spec(_spec_with_connection(str(self.mine.id)))+ self.assertEqual(result["mcps"][0]["connection"], str(self.mine.id))++ def test_editor_cannot_add_their_own_connection_to_owners_revision(self) -> None:+ revision = AgentRevision.all_teams.create(+ application=self.application, state="draft", spec={}, created_by_id=self.user.id+ )+ with self.assertRaises(serializers.ValidationError):+ self._serializer(self.other, instance=revision).validate_spec(_spec_with_connection(str(self.theirs.id)))diff --git a/products/agent_platform/backend/tests/test_spec_schema.py b/products/agent_platform/backend/tests/test_spec_schema.pyindex 8a0272533707..51cc8935f9f3 100644--- a/products/agent_platform/backend/tests/test_spec_schema.py+++ b/products/agent_platform/backend/tests/test_spec_schema.py@@ -15,6 +15,7 @@ import pytestfrom rest_framework.exceptions import ValidationError+from ..logic.generated import APPROVAL_REQUEST_STATES, ASSISTANT_STOP_REASONS, TRIGGER_REQUIRED_SECRETS, TRIGGER_ROUTESfrom ..logic.spec_schema import SLACK_BOT_TOKEN_KEY, SLACK_SIGNING_SECRET_KEY, missing_required_secretsfrom ..presentation.serializers import AgentRevisionSerializer, AgentSpecField@@ -127,6 +128,26 @@ def test_missing_required_secrets_skips_triggers_without_requirements() -> None:assert missing_required_secrets(spec, {}) == []+def test_generated_vocabularies_load_and_are_nonempty() -> None:+ assert APPROVAL_REQUEST_STATES and all(isinstance(s, str) and s for s in APPROVAL_REQUEST_STATES)+ assert ASSISTANT_STOP_REASONS and all(isinstance(s, str) and s for s in ASSISTANT_STOP_REASONS)+ assert TRIGGER_REQUIRED_SECRETS.get("slack")+ assert TRIGGER_ROUTES+ assert TRIGGER_ROUTES.get("chat") == {+ "run": "/run",+ "send": "/send",+ "cancel": "/cancel",+ "listen": "/listen",+ "client_tool_result": "/client_tool_result",+ }+++def test_missing_required_secrets_fails_closed_on_unregistered_trigger() -> None:+ spec = {"triggers": [{"type": "github", "config": {}}]}+ missing = missing_required_secrets(spec, {})+ assert [entry["trigger"] for entry in missing] == ["github"]++# AgentSpecField coerces a stringified-JSON-object spec back to an object. The MCP# write tools expose `spec` as an opaque arg, so an authoring model sometimes# passes the whole spec as a JSON string; stored verbatim it's the characters of adiff --git a/products/agent_platform/bin/coherence-install b/products/agent_platform/bin/coherence-installnew file mode 100755index 000000000000..38c7035e07aa--- /dev/null+++ b/products/agent_platform/bin/coherence-install@@ -0,0 +1,33 @@+#!/usr/bin/env bash+# coherence-install — one-time local setup for the agent-platform coherence+# pre-commit gate (a one-week evaluation; NOT wired into CI).+#+# Clones + builds the pinned coherence CLI into a gitignored cache. Re-run to+# update the pin. Needs network + Node >= 22 once; after that the pre-commit+# hook just runs the built CLI (zero runtime deps).+set -euo pipefail++# Full 40-char SHA (not a short pin): unambiguous, collision-resistant.+PIN="bb40f4a1e7f673b6caf20bf11b57b557019aa0f8" # daniloc/coherence v0.9.0 (bump deliberately)+REPO_ROOT="$(git rev-parse --show-toplevel)"+DEST="$REPO_ROOT/products/agent_platform/.coherence-tool/repo"++if [ -d "$DEST/.git" ] &&+ [ "$(git -C "$DEST" rev-parse HEAD 2>/dev/null)" = "$PIN" ] &&+ [ -f "$DEST/dist/cli.js" ]; then+ echo "[coherence] already installed at $PIN"+ exit 0+fi++echo "[coherence] installing daniloc/coherence@$PIN (clone + build, one time) ..."+rm -rf "$DEST"+git clone --quiet https://github.com/daniloc/coherence.git "$DEST"+git -C "$DEST" checkout --quiet "$PIN"+# npm (not pnpm) on purpose: this is an isolated clone outside the pnpm+# workspace with its own package-lock.json — `npm ci` honours that lockfile for+# a deterministic install (pnpm would ignore it). `--ignore-scripts` blocks any+# dependency lifecycle script from executing; the build is a plain `tsc` that+# doesn't need them. npm ships with Node, which we already require.+(cd "$DEST" && npm ci --ignore-scripts --silent && npm run build --silent)+echo "[coherence] ready. 'coherence verify --fast' now runs on agent_platform pre-commits."+echo "[coherence] bypass any single commit with 'git commit --no-verify'."diff --git a/products/agent_platform/bin/coherence-precommit b/products/agent_platform/bin/coherence-precommitnew file mode 100755index 000000000000..6940081cff83--- /dev/null+++ b/products/agent_platform/bin/coherence-precommit@@ -0,0 +1,78 @@+#!/usr/bin/env bash+# coherence-precommit — lint-staged command for agent_platform changes.+#+# For each coherence root (a dir with coherence.config.json) whose files are+# staged, runs two cheap gates (no DB, no test runner):+# - `verify --fast` — structural claims + boundary anchoring + meta-oracle.+# Blocks on a red: a declared claim that isn't honest.+# - `log --strict` — the loss-ratchet. Blocks when the commit DROPS an+# invariant/boundary/parity. Without this, the cheapest+# way to green a failing verify is to delete the claim,+# and nothing would notice. A dropped claim must be+# deliberate (re-add it, or `--no-verify` knowingly).+# (The novelty advisory it also prints is advisory only —+# it never fails the commit.)+#+# Scoped: lint-staged only invokes this for products/agent_platform/** files.+# Graceful: if a staged file touches no coherence root it does nothing; if the+# tool isn't installed it self-bootstraps (see coherence-install), and if that+# fails (e.g. offline) it skips this commit rather than blocking.+# Bypass any commit with `git commit --no-verify`.+#+# bash 3.2 compatible on purpose (stock macOS ships 3.2): no associative arrays.+set -uo pipefail++REPO_ROOT="$(git rev-parse --show-toplevel)"+CLI="$REPO_ROOT/products/agent_platform/.coherence-tool/repo/dist/cli.js"++# Map each staged file (passed by lint-staged) to its coherence root: the+# nearest ancestor dir holding a coherence.config.json. Accumulate newline-+# delimited, then `sort -u` to dedup — no `declare -A` (needs bash >= 4 and+# hard-errors on macOS's bash 3.2).+roots=""+for f in "$@"; do+ d="$(cd "$(dirname "$f")" 2>/dev/null && pwd)" || continue+ while [ -n "$d" ] && [ "$d" != "/" ]; do+ if [ -f "$d/coherence.config.json" ]; then+ roots="$roots$d+"+ break+ fi+ [ "$d" = "$REPO_ROOT" ] && break+ d="$(dirname "$d")"+ done+done+roots="$(printf '%s' "$roots" | sort -u | sed '/^$/d')"++# Nothing under a coherence root (a doc, the hook itself) → no-op, and in+# particular don't trigger the install.+[ -n "$roots" ] || exit 0++# Auto-bootstrap on first use, now that we know a root is actually affected.+if [ ! -f "$CLI" ]; then+ printf '\033[36m[coherence] first-time setup: installing the eval tool (one-time clone + build)...\033[0m\n' >&2+ "$REPO_ROOT/products/agent_platform/bin/coherence-install" >&2 || true+fi+if [ ! -f "$CLI" ]; then+ printf '\033[33m[coherence] tool unavailable (offline?) — skipping this commit; will retry next time.\033[0m\n' >&2+ exit 0+fi++status=0+OLDIFS="$IFS"+IFS='+'+for root in $roots; do+ rel="${root#$REPO_ROOT/}"+ printf '\033[36m[coherence] verify --fast: %s\033[0m\n' "$rel" >&2+ if ! (cd "$root" && node "$CLI" verify --fast >&2); then+ status=1+ fi+ # Loss-ratchet: fail if this commit drops a claim (HEAD -> working tree).+ printf '\033[36m[coherence] log --strict: %s\033[0m\n' "$rel" >&2+ if ! (cd "$root" && node "$CLI" log --strict >&2); then+ status=1+ fi+done+IFS="$OLDIFS"+exit "$status"diff --git a/products/agent_platform/bin/coherence-uninstall b/products/agent_platform/bin/coherence-uninstallnew file mode 100755index 000000000000..da7c3f9f7d15--- /dev/null+++ b/products/agent_platform/bin/coherence-uninstall@@ -0,0 +1,73 @@+#!/usr/bin/env bash+# coherence-uninstall — remove the coherence evaluation HARNESS, leaving the+# production hardening it motivated fully intact.+#+# Why this exists: the adoption PR squash-merges into ONE commit on master that+# mixes the harness (this tooling + the *.spec.md claims + per-root config) with+# real chokepoint hardening (IDOR / owner-scoping / bug-class fixes in *.ts). So+# `git revert <that commit>` is the WRONG tool — it would undo the hardening and+# reopen those bug classes. This script removes ONLY the harness:+# - the CLI scripts (bin/coherence-*), docs, per-root coherence.config.json,+# every *.spec.md claim file, and the gitignored caches.+# Every *.ts / *.test.ts change stays. A test that enumerates its domain is a+# better test whether or not coherence reads it.+#+# It does NOT edit package.json (structured, shared — a blind edit risks+# corrupting it). It prints the one line to remove, which is the gate's actual+# on/off switch: until that line is gone, lint-staged will try to run the+# now-deleted hook and error on every agent_platform commit.+#+# bash 3.2 compatible (stock macOS ships 3.2): no associative arrays, no mapfile.+set -uo pipefail++REPO_ROOT="$(git rev-parse --show-toplevel)"+AP="$REPO_ROOT/products/agent_platform"+BIN="$AP/bin"++printf '\033[36m[coherence] teardown — removing the evaluation harness (hardening stays).\033[0m\n'++# Derive the config + claim files (find, so this stays correct as specs are+# added or removed; in agent_platform, *.spec.md is the coherence convention —+# ordinary tests are *.test.ts). Plus the fixed CLI scripts and docs, and the+# gitignored cache/output dirs.+files="$(find "$AP" -type f \( -name coherence.config.json -o -name '*.spec.md' \) 2>/dev/null)+$BIN/coherence-install+$BIN/coherence-precommit+$BIN/coherence-uninstall+$AP/docs/coherence-onboarding.md+$AP/docs/coherence-overview.md"++dirs="$(find "$AP" -type d \( -name .coherence -o -name .coherence-out -o -name .coherence-tool \) 2>/dev/null)"++removed=0+OLDIFS="$IFS"+IFS='+'+for p in $files $dirs; do+ [ -n "$p" ] || continue+ if [ -e "$p" ]; then+ rm -rf "$p"+ printf ' removed %s\n' "${p#$REPO_ROOT/}"+ removed=$((removed + 1))+ fi+done+IFS="$OLDIFS"++printf '\n\033[36m[coherence] removed %s harness file(s)/dir(s).\033[0m\n\n' "$removed"++printf 'ONE required manual step — the gate'\''s actual off switch:\n'+printf ' Delete the coherence line from package.json (lint-staged), and drop the\n'+printf ' trailing comma from the line above it so the JSON stays valid:\n'+if grep -n 'coherence-precommit' "$REPO_ROOT/package.json" >/dev/null 2>&1; then+ grep -n 'coherence-precommit' "$REPO_ROOT/package.json" | sed 's/^/ /'+else+ printf ' (already removed — nothing to do)\n'+fi++printf '\nOptional cleanup (harmless if left — they just ignore dirs that no longer exist):\n'+printf ' .gitignore lines for .coherence-tool/ , .coherence-out/ , .coherence/\n'++printf '\nKEPT on purpose (this is hardening, not harness):\n'+printf ' every *.ts / *.test.ts change, the mcp_store facade, pyproject.toml / tach.toml edits.\n'+printf '\n\033[33mDo NOT `git revert` the squashed adoption commit — it also carries the\n'+printf 'hardening (IDOR / owner-scoping chokepoints); reverting reopens those bugs.\033[0m\n'diff --git a/products/agent_platform/docs/coherence-onboarding.md b/products/agent_platform/docs/coherence-onboarding.mdnew file mode 100644index 000000000000..cee183745a3a--- /dev/null+++ b/products/agent_platform/docs/coherence-onboarding.md@@ -0,0 +1,222 @@+# Coherence — the doctrine and the harness++The transferable half of this stack: the doctrine that says _why_ we build boundaries+this way (Danilo's Mnemion doctrine), and the harness that checks them+([daniloc/coherence](https://github.com/daniloc/coherence)). For the concrete inventory of+what we actually built here, see [coherence-overview.md](coherence-overview.md). Read this+before authoring or maintaining a boundary.++## The doctrine++> A recurring bug is a structural question answered at call sites instead of at a boundary.+> Don't patch faster: invert the architecture so the bug becomes **unrepresentable**.++The fix-one-open-another loop _is_ the diagnosis. When two findings cluster on one seam,+stop patching sinks and enforce the invariant from a single home.++**The conversion, O(N) → O(1).** Turn a **block-list** (N guards you must remember at N+sinks; fails open the moment one is forgotten) into a **chokepoint** (one reference monitor+every path physically crosses). A chokepoint earns trust from four properties that must+travel together:++1. **One declarative home, and it's data.** A table keyed by the thing it governs: not a+ predicate copied across sites, not a naming convention standing in for an unmodeled fact,+ not prose in a doc.+2. **Derive, never duplicate.** Every gate computes from the table.+3. **Enforce where the invariant lives:** the chokepoint all paths cross on the protected+ thing, not the convenient layer.+4. **Fail closed.** Absence resolves to the safe state; forgetting to update the table is safe.++**The linchpin: prove totality.** A chokepoint is not enough; you must _know_ it's the only+path. A totality oracle converts the unanswerable block-list question ("did we find every+sink?") into a checkable one ("does the one declaration cover the enumerable domain, and+fail loud if not?"). A boundary without an oracle is a half-boundary; don't ship it.++**Capability over convention.** An oracle proves the _anatomy_ exists (the chokepoint+symbol, the green test). It cannot prove the chokepoint is un-routable-_around_: that comes+from the type system. A named capability constructor with no trust parameter to dial at a+call site makes the wrong call _unexpressible_, not merely guarded. Conventions are failures+lurking in the code; we want contracts.++**The graded ladder (match rigor to consequence).** _enshrined_ (the unsafe state is+unrepresentable in types) > _totality-checked_ (an oracle proves the N sites agree) >+_convention_ (held by memory). Push security boundaries up; the target is zero security+rules at the convention tier. Don't over-enshrine: making every crossing a ceremony is its+own inner-platform pathology.++**The manifold this describes.** Charts (trust domains: owner-trusted, served-untrusted,+agent-mcp, public-egress, ...) stitched by transition maps (the chokepoints). Trust is+directional: most crossings preserve or lower it, only an _enshrined_ crossing may raise it.+A convention crossing is where the manifold can tear. The **atlas** is that map made+legible: it derives each crossing's tier from the live boundary claims and flags any+tier-3 security crossing. (We haven't built the atlas layer here yet; it's the next increment.)++**The metric: blast radius.** How many files an agent must read and keep in sync to add one+invariant. Drive it toward one, and make the convergent move the _cheapest_ one, or the+divergent move is the one that gets made.++> In one breath: one declarative home (data, not convention) → derive every gate → enforce+> at the chokepoint all paths cross → fail closed → assert totality so the absence of holes+> is _checked_, not hoped → make the boundary un-routable in types → keep intent, structure,+> and evolution converged.++## The harness++`coherence` is a zero-dependency Node CLI that derives a graph from a `*.spec.md` tree plus+the code, then verifies the claims haven't rotted. The core is language- and+platform-agnostic; TypeScript and Python adapters cover this repo. Its one load-bearing+feature: a `boundary` claim welds a declared **invariant** → a **chokepoint symbol** → a+**totality oracle**, and fails the build if the oracle is renamed, deleted, or missing.+Reach for it when a correctness commitment must _stay_ enforced under future edits, not for+one-off bugs.++### Claim grammar (the part to get right)++Each claim in a spec's `## works when` list is verified at one tier:++- **structural** (instant): `typechecks` · `X exists` · `X imports Y`.+- **executable**: `passes test "<name>"` shells the test runner with `<name>`. This is the+ _single front door_: an invariant enforced by a test is named in the spec, so `verify`+ runs it, and a claim pointing at a renamed or deleted test goes **red**.+- **boundary** (the ratchet): `boundary "<inv>" at <symbol> [via test|guard "<oracle>"]`.+ `via test` means a live-domain totality oracle (loops an imported SSOT / call result / the+ anchor). `via guard` means a source-property assertion with no enumerable domain.++The gate: every name in a spec's `## invariants` list **must** be anchored by a `boundary`+claim, or coverage fails. That is the doctrine made machinery: you can't ship a+half-boundary. Coverage gates node-contract completeness (claims + a `## why`), not a+docblock on every symbol.++### Authoring boundaries without fooling yourself++The ratchet is only as honest as the oracle behind it. Four edges, all found by running it:++1. **`via test "<name>"` must name a `describe`, not an `it()`.** The meta-oracle resolves+ the oracle by `describe` title; an `it()` name resolves not-found and falls through to the+ runner, so the claim goes green off the passing test and the meta-oracle never judges it.+ Name the `describe` after the invariant.+2. **Oracle names are regex.** `-t "<name>"` treats parens and brackets as groups that can+ match nothing, surfacing as `0 passed`, not a failure. Keep titles free of regex metacharacters.+3. **The meta-oracle proves anatomy, not semantics.** It proves the oracle _iterates a live+ domain_; it cannot prove the assertion exercises the real enforcement rather than a+ _proxy_. A unit test with a fake DB asserting the owner arg was _passed_ stays green while+ the SQL `WHERE owner` predicate is deleted and the IDOR reopens.+4. **`decompose` / `drift` are degenerate with a single node:** they need a real multi-node+ spec tree to say anything.++**The discipline: validate by perturbation, not by a green run.** For every boundary: revert+the fix (or inject the exact violation the invariant forbids) → confirm the oracle goes+**red** → restore. If it stays green, the oracle tests a proxy; rewrite it against the real+mechanism. The layered defense is `oracle → meta-oracle → perturbation`, each catching what+the layer below can be fooled about; the injection is ground truth. For an impact read,+inject a _fair_ set: in-domain violations, out-of-domain logic bugs (blind spots), and+benign edits (false alarms), and score which go red.++## Setup and the local gate++```sh+git clone --branch v0.9.0 https://github.com/daniloc/coherence.git /tmp/coherence+cd /tmp/coherence && npm ci --ignore-scripts && npm run build # → dist/cli.js (Node ≥22, zero runtime deps)+```++The gate pins `daniloc/coherence` at commit `bb40f4a` (v0.9.0) — see+`bin/coherence-install`. v0.9.0 carries everything the gate leans on: `it.each` domain+recognition, domain-floor detection, the NOT-FOUND hard-fail on `via test`, the `parity`+claim type, Python support, and markdown-escape-robust claim parsing. For eventual CI+adoption it installs as a git dependency (`github:daniloc/coherence`) rather than a clone.++Each node service is its own root and ships a `coherence.config.json`:++```json+{+ "outputDir": ".coherence-out",+ "entryDir": "src",+ "ignore": ["node_modules", "dist", ".coherence-out"],+ "codeExt": ["ts"],+ "typecheck": ["npx", "tsc", "--noEmit", "-p", "."],+ "test": ["npx", "vitest", "run", "-t"],+ "testMatch": "[1-9][0-9]* passed",+ "language": "typescript"+}+```++Set `testMatch`: without it a runner like `vitest -t` exits 0 even when the name matched+nothing, and a deleted oracle stays green.++The harness is **not wired into CI** (a personal-repo tool, deliberately local-only for a+one-week evaluation). The gate is a **local pre-commit hook**, scoped to agent_platform, and+it **self-installs on first use**: your first commit touching `products/agent_platform/**`+does a one-time clone + build of the pinned CLI into a gitignored cache (`.coherence-tool/`),+then runs two cheap gates in each coherence root you touched — `coherence verify --fast`+(structural claims + boundary anchoring + the meta-oracle; no DB, no test runner) and+`coherence log --strict` (the loss-ratchet: reds if the commit drops an invariant/boundary/+parity) — and blocks the commit on a red from either. Run+`products/agent_platform/bin/coherence-install` upfront if you'd rather not wait on that first+commit. It's wired through lint-staged, so it fires only for agent_platform changes; bypass a+single commit with `git commit --no-verify`. If the install can't run (offline), it skips that+commit and retries next time rather than blocking.++What the fast pre-commit catches locally: an unanchored invariant, a renamed or missing+chokepoint symbol, a vacuous or weak oracle (the meta-oracle), a missing floor (all via+`verify`), plus a _dropped_ invariant/boundary/parity (via `log --strict` — so the cheapest+way to green a failing `verify`, deleting the claim, is caught too). What it does **not** run+is the oracle tests themselves (real DB / real dispatch) — those are ordinary vitest/pytest+tests that run in CI regardless, so a semantic regression is still caught there. The+pre-commit is advisory-by-consent (bypassable, and only for whoever has it installed); the+same `verify` + `log --strict` in CI would be unbypassable enforcement, but that's a+deliberate not-yet for this one-week evaluation.+The declared invariants live in the `*.spec.md` next to the code — read the ones in any+directory you edit; they are the checklist of what your change must not break.++## Backing this out++This is a one-week evaluation, so the exit is designed to be clean. The one thing to+understand first: the adoption PR squash-merges into a single commit on master that carries+**two** things — the harness (this tooling + the `*.spec.md` claims + per-root config) _and_+real chokepoint hardening (IDOR / owner-scoping / bug-class fixes in `*.ts`). Those are woven+into the same squash.++**Do not `git revert` that commit.** It would undo the hardening too and reopen the exact bug+classes the branch closed. Removing coherence means removing the _harness_ while keeping the+_hardening_. Three tiers, easiest first:++1. **Disable, don't remove (instant, zero-risk).** The gate is a _local_ pre-commit hook, not+ CI. Delete the one lint-staged line in `package.json`+ (`"products/agent_platform/**/*.{ts,py}": ".../coherence-precommit"`) and the gate goes+ dormant for everyone immediately; the specs and configs become inert. This is the real+ "call off the evaluation" move — no history rewrite.+2. **Full teardown (later, at leisure).** Run+ [`bin/coherence-uninstall`](../bin/coherence-uninstall). It removes exactly the harness —+ every `coherence.config.json`, every `*.spec.md`, the CLI scripts, the docs, the gitignored+ caches — and prints the one manual step (the `package.json` line, which it won't edit+ blindly). It touches no `*.ts` / `*.test.ts`: a test that enumerates its domain is a better+ test whether or not coherence reads it, so those stay.+3. **Never the blunt revert** — see above.++The oracle test files, the `mcp_store` facade, and the `pyproject.toml` / `tach.toml` edits are+hardening, not harness; they survive all three tiers.++## Command reference++- `verify [--fast|--staged|--since <ref>]`: run claims + boundary anchoring + coverage.+ `--staged`/`--since` scope to changed components; `--fast` skips executable/live claims.+- `log [--strict]`: the temporal ledger of which invariants/boundaries a diff added, removed,+ or rewired. `--strict` exits nonzero on a _loss_, so a PR can't silently drop a guard.+- `decompose`: LOCALITY report, how much co-change stays inside one component (three-graph+ agreement). Advisory.+- `drift`: decompose's derivative, is the agent converging (one concern, one home) or+ decohering (concerns smearing)? Names the hot seam. Advisory.+- `scaffold <boundary|component|invariant> <name>`: emits the complete shape so you can't+ ship a half-boundary (the gradient flip).+- `why-lint [--check]`: flags `## why` prose that re-states an anchored mechanism, and+ invariants/paragraphs left un-anchored.+- `onboard` · `graph` · `overview` · `docs [--check]`: bootstrap and doc generation.++## Honest limits++- Oracles can be proxies; only perturbation catches that.+- `via guard` source-scans are brittle to renames; watch their friction.+- It's a personal-repo git dependency: a supply-chain consideration before CI adoption.+- Where it's the _wrong_ tool: effects (the dispatch may be tabular, the handler stays+ imperative), one-offs (a table of one is worse than an `if`), and history (migrations and+ audit logs are point-in-time by design; you can't derive them).diff --git a/products/agent_platform/docs/coherence-overview.md b/products/agent_platform/docs/coherence-overview.mdnew file mode 100644index 000000000000..ad9afde1771a--- /dev/null+++ b/products/agent_platform/docs/coherence-overview.md@@ -0,0 +1,127 @@+# Coherence in the agent platform++Orientation for this stack: what we set out to do, and the concrete boundaries we built.+Every invariant below is declared as a coherence `boundary` — an invariant welded to a+chokepoint symbol and an oracle. Two gates keep them honest: `coherence verify` reds the+build on a boundary that's left unanchored or whose oracle doesn't hold ("can't ship a+half-boundary"), and `coherence log --strict` reds it on a boundary that's dropped — so the+cheapest way to green a failing `verify` (delete the claim) is itself caught. For the method+behind this — the doctrine and the harness that checks it — see+[coherence-onboarding.md](coherence-onboarding.md).++## The goal++A recurring bug is a **structural question answered at call sites** — "did we cover every+sink?", "does this need approval?", "is this the owner?" — re-decided by hand at each site,+so one forgotten site is a latent tear. The cure is always the same move: promote the+convention to a **contract**:++> one declarative **home** (data, not memory) → **derive** every gate from it → enforce at+> the single **chokepoint** all paths cross → **fail closed** → **assert totality** so the+> absence of holes is _checked, not hoped_ → and where it matters most, make the unsafe+> state **unrepresentable** in the type system.++Rigor is graded — **enshrined** (can't compile) > **totality-checked** (an oracle proves the+N sites agree) > **convention** (a doc you hope people read) — and the target is to leave+**no security rule at the convention tier**.++## The bug-shapes we targeted++The stack is organized around the classes that actually recur in this codebase:++1. **Fail-open defaults** — `.get(type, [])`, `requires_approval` defaulting false: the+ permissive answer fires exactly when knowledge is absent.+2. **Wrong-layer authorization** — enforcing at the convenient layer (team) instead of the+ invariant's layer (the credential's owner) → IDOR.+3. **Hand-mirror drift** — a TS enum and a Python list maintained separately, silently+ diverging.+4. **Untrustworthy oracles** — a green test that is vacuous (empty domain), tests a _proxy_+ (a fake DB pool asserts the arg was _passed_, not that the SQL actually filters), or never+ _runs_ (a CI path-filter gap).+5. **Silent drops** — a content-type mislabel or an unregistered trigger swallowed with no+ trace.++## What we built — 25 boundaries across 6 roots++### A. Wrong-layer authorization — enforce at the invariant's layer, not the convenient one++| Boundary | Anchor | Oracle | Shrieks when… |+| --------------------------------- | ---------------------- | ------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ |+| `connection-owner-isolation` | `PgMcpConnectionStore` | test _"cannot return owner B"_ | the shared-MCP-credential lookup stops scoping to the spec author — IDOR, proven with real two-owner SQL (not a fake pool) |+| `connection-bearer-single-reader` | `PgMcpConnectionStore` | guard _"reads of sensitive_configuration are confined"_ | any module other than the store reads the credential column (the owner check is only complete if the store is the sole reader) |+| `team-api-key-isolation` | `PgTeamApiKeyResolver` | test _"returns only its own api_token"_ | the `WHERE id = $1` is dropped/inverted and a sibling team's `phc_` token leaks |+| `shared-secret-single-principal` | `sharedSecretVerifier` | test _"yields a single team-scoped principal"_ | a per-caller identity is smuggled into `shared_secret` mode (forgeable behind the secret) |++### B. Fail-open → fail-closed / can't-omit++| Boundary | Anchor | Oracle | Shrieks when… |+| ---------------------------------- | -------------------------- | ----------------------------------------------- | ------------------------------------------------------------------------------------------------- |+| `unregistered-trigger-fail-closed` | `missing_required_secrets` | test _"…fails_closed_on_unregistered_trigger"_ | the old `.get(type, [])` returns — an unknown trigger promotes with its signing secret unenforced |+| `native-tool-approval-floor` | `nativeToolApprovalClass` | test _"native tool authorization accessor"_ | a tool ships without a declared `approval` class — a compile error (required field) |+| `gated-dispatch-single-path` | `gateTool` | test _"gate chokepoint — fail-closed dispatch"_ | any tool reaches the loop unbranded — `assertToolsGated` throws at boot |+| `approval-authority-totality` | `effectiveApprovalType` | test _"approval-authority totality"_ | a new approval-type enum member isn't handled (total over the enum) |++### C. Single-source — one derived thing, no drift++| Boundary | Anchor | Oracle | Shrieks when… |+| ------------------------------------ | -------------------------- | ------------------------------------------------------------ | ------------------------------------------------------------------------------------ |+| `generated-vocabulary-single-source` | `GENERATED_ARTIFACTS` | test _"spec generated artifacts"_ | a checked-in JSON drifts from its TS source |+| `trigger-routes-single-source` | `TRIGGER_ROUTES` | test _"spec generated artifacts"_ | the TS route map and the emitted JSON disagree |+| `approval-state-vocabulary` | `APPROVAL_REQUEST_STATES` | test _"spec generated artifacts"_ | the runner's states and the DRF/DB copy diverge |+| `generated-vocabulary-loader` | `_load` | test _"…vocabularies_load_and_are_nonempty"_ | Django loads a corrupt / missing / wrong-shape artifact instead of failing closed |+| `artifact-ci-coverage` | `TRIGGER_REQUIRED_SECRETS` | test _"…filter_covers_every_generated_artifact"_ | a generated artifact escapes the CI path-filter (the _guard-must-be-run_ meta-check) |+| `gateway-wire-single-source` | `extractGatewayRequestId` | test _"request id single-sourcing"_ | dispatch and cost-lookup key on two different ideas of "the request id" |+| `approval-wire-resolved` | `serializeApprovalRequest` | test _"resolves a legacy approvers"_ | an approval is serialized outside the one shared serializer |+| `approval-wire-consumption` | `buildJanitorApp` | guard _"approval routes never bypass the shared serializer"_ | a janitor route serializes an approval by hand |++### D. Make the unsafe _value_ unrepresentable++| Boundary | Anchor | Oracle | Shrieks when… |+| ------------------------------- | ------------------------- | --------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- |+| `gateway-cost-provenance` | `assertGatewayProvenance` | test _"cost provenance guard"_ | a non-gateway (or negative/blank) cost reaches analytics |+| `direct-http-capability-divide` | `DirectHttpClient` | guard _"does NOT accept a proxyUrl in its options"_ | the no-proxy internal client gains a `proxyUrl` hatch or is threaded onto agent-reachable context (class identity _is_ the capability) |+| `django-fernet-interop` | `EncryptedFields` | test _"urlsafe regression"_ | the runner can't decrypt exactly what Django encrypted (urlsafe-base64 mismatch) |++### E. Bounds & edge-totality on inputs++| Boundary | Anchor | Oracle | Shrieks when… |+| -------------------------- | ----------------- | ----------------------------------------- | --------------------------------------------------------------------------------------------------- |+| `tenant-array-bounds` | `AgentSpecSchema` | test _"agent spec tenant-array bounds"_ | a tenant array ships without `maxItems` (incl. `anyOf`-wrapped nullable arrays) |+| `trigger-edge-conformance` | `TRIGGER_MODULES` | test _"trigger-module conformance suite"_ | a trigger regresses content-type / drop / dedup / signing (with double-entry over the edge classes) |++### F. Liveness — nothing gets stuck, nothing mutates after seal++| Boundary | Anchor | Oracle | Shrieks when… |+| ---------------------------- | ------------------------ | ----------------------------------------------------------------------------------------------------- | ------------------------------------------------------------ |+| `freeze-validate-lockstep` | `validateRevisionBundle` | tests: missing entrypoint / unknown tool / unserved model / client-tool-with-webhook / malformed cron | the janitor freezes something the runner would reject |+| `sweep-bounded-retries` | `sweepOnce` | test _"poison-pills a stuck running session after maxRetries"_ | a stuck session isn't reaped after `maxRetries` |+| `bundle-freeze-immutability` | `S3BundleStore` | test _"freezes and blocks further writes"_ | a live revision's frozen bundle is written again |+| `enqueue-idempotency` | `enqueueOrResume` | test _"returns the original session id on a duplicate call"_ | a redelivered event doesn't collapse to the original session |++**Density:** `agent-shared` carries 14 (the shared substrate is where cross-tenant and+single-source invariants concentrate); the rest spread across ingress, runner, janitor,+tools, and the Django backend. Every root also declares `typechecks` as its tier-0 floor.++The oracles are kept honest by **defect injection**: every boundary was proven to go _red_+when the invariant is violated — the only check that tests semantics, not anatomy (a green+oracle can be a proxy; a passing meta-oracle can't tell).++## Where we are on the ladder — honestly++- **All 25 render tier-2 today** (totality-checked): declared, oracle-guarded, floored+ against vacuous passes.+- **2 are tier-1-eligible** (the illegal value is structurally _unrepresentable_): the+ required `approval` field, and the no-`proxyUrl` capability divide — which now carries its+ backing `via guard`.+- **Not built yet: the trust-manifold grading layer** — the crossing-by-crossing view that+ would emit a "zero tier-3 security crossings" report and reconcile enshrinement claims.+ That's the next frontier.++## Is this worth it?++The leverage is real but bounded. Coherence catches the _boundary-class_ regressions above —+a deleted `WHERE owner`, a drifted vocabulary, an ungated tool, a vacuous oracle — and makes+the convergent move (add a row to one home) cheaper than the divergent one (add a guard at a+new call site). It catches nothing _outside_ its declared boundaries, and a green run can lull+you there. It earns its place on the security-critical chokepoints; over-applying it —+enshrining everything, essaying every rationale — is its own pathology.diff --git a/products/agent_platform/services/agent-ingress/.gitignore b/products/agent_platform/services/agent-ingress/.gitignoreindex 83631f817f87..20b35bdd7d6e 100644--- a/products/agent_platform/services/agent-ingress/.gitignore+++ b/products/agent_platform/services/agent-ingress/.gitignore@@ -1,3 +1,5 @@dist/node_modules/*.tsbuildinfo+.coherence-out/+.coherence/diff --git a/products/agent_platform/services/agent-ingress/coherence.config.json b/products/agent_platform/services/agent-ingress/coherence.config.jsonnew file mode 100644index 000000000000..2c5ed58c551f--- /dev/null+++ b/products/agent_platform/services/agent-ingress/coherence.config.json@@ -0,0 +1,10 @@+{+ "outputDir": ".coherence-out",+ "entryDir": "src",+ "ignore": ["node_modules", "dist", ".coherence-out"],+ "codeExt": ["ts"],+ "typecheck": ["npx", "tsc", "--noEmit", "-p", "."],+ "test": ["npx", "vitest", "run", "-t"],+ "testMatch": "[1-9][0-9]* passed",+ "language": "typescript"+}diff --git a/products/agent_platform/services/agent-ingress/src/enqueue/Enqueue.spec.md b/products/agent_platform/services/agent-ingress/src/enqueue/Enqueue.spec.mdnew file mode 100644index 000000000000..58230c57d786--- /dev/null+++ b/products/agent_platform/services/agent-ingress/src/enqueue/Enqueue.spec.md@@ -0,0 +1,26 @@+# Enqueue++Single-caller-facing auth resolution (identity vs. credentials split, per-mode+verifiers) plus the one place every trigger creates or resumes an+`AgentSession` — `enqueueOrResume`. Session ACL enforcement (`acl.ts`) sits+between the two: it decides whether an incoming principal may advance an+existing session.++## invariants++- shared-secret-single-principal+- enqueue-idempotency++## works when++- typechecks+- boundary "shared-secret-single-principal" at sharedSecretVerifier+- passes test "yields a single team-scoped principal"+- boundary "enqueue-idempotency" at enqueueOrResume+- passes test "returns the original session id on a duplicate call"+- passes test "unique-violation on insert resolves to the original session id"++## why++shared-secret-single-principal: `shared_secret` auth is single-principal by design — every holder of an agent's shared secret is the same trust principal, because nothing behind the secret can forge-resistantly distinguish one holder from another. `x-external-key` is a session-routing tag (dedupe/resume key), never a credential, and `principalsMatch`'s `shared_secret` arm discriminates only on `team_id`. Adding any per-caller header, claim, or discriminator behind the secret creates a false boundary — any other holder of the same secret can self-assert the same header — and this exact mistake shipped and was reverted twice (a spec-level `caller_id_header`, then a follow-up `x-posthog-caller-id` header; both undone once review caught that either construction defeats the ACL it appears to add). Per-caller isolation is `jwt` mode's job (its `sub` is upstream-signed, not self-asserted); the sanctioned path for continuity-with-isolation under `shared_secret`, if a real use case ever needs it, is server-issued unguessable resume tokens, not a self-asserted header. The oracle pins the mint site so a future patch that reads a caller-asserted header back into the principal fails the assertion instead of silently reopening the hole.+enqueue-idempotency: `enqueueOrResume` runs the idempotency check before the `externalKey` resume path — `findByIdempotencyKey(application.id, idempotencyKey)` short-circuits a duplicate call to the original session id, deliberately discarding the incoming principal and seed message (Stripe-shaped semantics: same request, same result, no side effect replayed). The unique index on `(application_id, idempotency_key)` is the safety net for the window between that pre-check and the `INSERT`: a concurrent writer landing first raises a Postgres unique-violation (SQLSTATE `23505`), which `enqueueOrResumeInner` catches and resolves by re-querying `findByIdempotencyKey` rather than surfacing a raw constraint error or letting the caller believe it created a fresh session. Without both halves, a redelivered webhook (e.g. a provider's `Idempotency-Key` header) racing another delivery of the same event would either duplicate a session's side effects or break the trigger with an unhandled DB error. Both oracles run against real Postgres via `PgSessionQueue` — the race test wraps the queue in a `Proxy` that reproduces the actual timing window (pre-check sees nothing, insert then hits the real unique-violation code) rather than mocking the outcome.diff --git a/products/agent_platform/services/agent-ingress/src/triggers/Triggers.spec.md b/products/agent_platform/services/agent-ingress/src/triggers/Triggers.spec.mdnew file mode 100644index 000000000000..59acbde9a594--- /dev/null+++ b/products/agent_platform/services/agent-ingress/src/triggers/Triggers.spec.md@@ -0,0 +1,16 @@+# Triggers++Inbound trigger modules — each ships one self-describing route list from which mounting, guards, schema publication, and auth advertisement all cascade. The edge semantics every module must share (content-type robustness, drop semantics, dedup, signing fail-closed) are a checked contract, not a convention copied from the previous trigger.++## invariants++- trigger-edge-conformance++## works when++- typechecks+- boundary "trigger-edge-conformance" at TRIGGER_MODULES via test "trigger-module conformance suite"++## why++trigger-edge-conformance: every new trigger historically re-learned the same edge bugs by copying its predecessor — a urlencoded-mislabeled body passing signature verification but silently dropping or corrupting the event, allowlist misses answered with provider-hostile 4xx (recorded as failed deliveries and retried), dedup silently disabled when the delivery-id header is absent, and fail-open when a signing secret is unresolved. The conformance suite iterates the live `TRIGGER_MODULES` registry and requires a fixture per module (the ratchet: registering a trigger without conformance fixtures is a red build naming the type), then asserts each applicable edge class through real HTTP responses and observed enqueues. Assertions are exact-match on seed content, not substring — a garbled-but-overlapping payload must still fail.diff --git a/products/agent_platform/services/agent-ingress/src/triggers/chat.ts b/products/agent_platform/services/agent-ingress/src/triggers/chat.tsindex 76aaa34c2e89..137e75142e3a 100644--- a/products/agent_platform/services/agent-ingress/src/triggers/chat.ts+++ b/products/agent_platform/services/agent-ingress/src/triggers/chat.ts@@ -13,7 +13,7 @@import { z } from 'zod'-import { buildClientToolResultMarker } from '@posthog/agent-shared'+import { buildClientToolResultMarker, TRIGGER_ROUTES } from '@posthog/agent-shared'import { buildElevationResponse, principalDisplay, recordElevationRequest, requireAclAccess } from '../enqueue/acl'import { enqueueOrResume } from '../enqueue/enqueue'@@ -318,35 +318,35 @@ export const chatTrigger: TriggerModule = {routes: [defineRoute({method: 'POST',- path: '/run',+ path: TRIGGER_ROUTES.chat.run,auth: 'agent_spec',schema: ChatRunBodySchema,handler: runHandler,}),defineRoute({method: 'POST',- path: '/send',+ path: TRIGGER_ROUTES.chat.send,auth: 'agent_spec',schema: ChatSendBodySchema,handler: sendHandler,}),defineRoute({method: 'POST',- path: '/cancel',+ path: TRIGGER_ROUTES.chat.cancel,auth: 'agent_spec',schema: ChatCancelBodySchema,handler: cancelHandler,}),defineRoute({method: 'GET',- path: '/listen',+ path: TRIGGER_ROUTES.chat.listen,auth: 'agent_spec',schema: ChatListenQuerySchema,handler: listenHandler,}),defineRoute({method: 'POST',- path: '/client_tool_result',+ path: TRIGGER_ROUTES.chat.client_tool_result,auth: 'agent_spec',schema: ChatClientToolResultBodySchema,handler: clientToolResultHandler,diff --git a/products/agent_platform/services/agent-ingress/src/triggers/conformance.test.ts b/products/agent_platform/services/agent-ingress/src/triggers/conformance.test.tsnew file mode 100644index 000000000000..93d28f735744--- /dev/null+++ b/products/agent_platform/services/agent-ingress/src/triggers/conformance.test.ts@@ -0,0 +1,606 @@+/**+ * Trigger-module conformance suite.+ *+ * Every `TRIGGER_MODULES` entry re-implements the same edges (signature+ * verification, content-type robustness, untrusted-vs-broken sender, redelivery+ * dedup); this encodes that contract once against the real HTTP surface so a new+ * trigger must satisfy it explicitly. `CONFORMANCE_FIXTURES` is the source of+ * truth for which edge classes apply to which trigger.+ *+ * Auth enforcement (declared kind == enforced kind) is covered by+ * agent-tests/src/cases/auth-contract.test.ts; this suite owns edge semantics —+ * what happens once a request clears (or deliberately fails) that gate.+ */++import { createHmac, randomUUID } from 'crypto'+import { Express } from 'express'+import { Pool } from 'pg'+import request from 'supertest'+import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest'++import {+ AgentApplication,+ AgentRevision,+ AgentSession,+ AgentSpecSchema,+ DirectHttpClient,+ EncryptedFields,+ PgApprovalStore,+ PgCredentialBroker,+ PgIdentityCredentialStore,+ PgIdentityLinkStateStore,+ PgIdentityStore,+ PgRevisionStore,+ PgSessionQueue,+ PgTransportBindingStore,+ RedisSessionEventBus,+ SecretResolver,+} from '@posthog/agent-shared'+import { reset } from '@posthog/agent-shared/testing'++import { buildApp, TRIGGER_MODULES } from '../routing/server'+import { encodeElevationActionValue } from './slack'+import type { TriggerType } from './types'++const TEST_DB_URL =+ process.env.AGENT_TEST_DB_URL ?? 'postgres://posthog:posthog@localhost:5432/agent_runtime_queue_test'+// nosemgrep: trailofbits.generic.redis-unencrypted-transport.redis-unencrypted-transport+const REDIS_URL = process.env.REDIS_URL ?? 'redis://localhost:6379'+const HARNESS_ENCRYPTION_SALT_KEYS = '01234567890123456789012345678901'+const SLACK_SECRET = 'conformance-slack-secret'++const PUBLIC_AUTH = { modes: [{ type: 'public' as const, acknowledge_public_exposure: true as const }] }++/** An HTTP request the harness fires verbatim — headers/body come from the fixture and are never mutated, so a fixture-set signature or Content-Type survives untouched. */+interface RawRequest {+ path: string+ headers: Record<string, string>+ rawBody: string+}++interface DeployedTrigger {+ application: AgentApplication+ revision: AgentRevision+}++/**+ * One trigger's conformance contract. Optional fields are edge classes the+ * trigger opts into by declaring them, letting the assertions below iterate+ * generically instead of hardcoding trigger names.+ */+interface ConformanceFixture {+ type: TriggerType+ /** Deploy a fresh agent wired only for this trigger's happy path (public+ * auth, permissive allowlist where applicable). */+ deployHappy(): Promise<DeployedTrigger>+ /** A valid, fully-authenticated request for a fresh event tagged by+ * `nonce` — reused across edge classes to build a "this should work"+ * baseline before perturbing one axis at a time. */+ validRequest(dep: DeployedTrigger, nonce: string): RawRequest+ /** Pull the enqueued/resumed session id out of a successful response body. */+ sessionIdFromResponse(body: unknown): string | undefined+ /** Normalize a session's seed message to a string for comparison. */+ contentOf(session: AgentSession): string+ /** The SAME logical event as `validRequest`, but mislabeled with a+ * mismatched Content-Type (JSON sent as `application/x-www-form-urlencoded`).+ * Omitted only for a route whose natural transport already IS urlencoded+ * (the slack-interactivity case). */+ mislabeledRequest?(dep: DeployedTrigger, nonce: string): RawRequest+ /** The EXACT seed a correct parse of `mislabeledRequest` produces. Exact,+ * not substring: Express's urlencoded mis-parse yields a garbage object+ * that, re-stringified into a seed, still CONTAINS the nonce — only exact+ * equality catches the garbled-but-still-2xx shape. */+ expectedContentAfterMislabel?(nonce: string): string+ /** Signature verification. Declared only by triggers whose auth is a+ * computed signature over the raw body (today: slack). */+ signing?: {+ /** Build a request signed with `secret` — pass the real secret for a+ * "missing secret resolver" probe, or a wrong one for an "invalid+ * signature" probe. */+ request(dep: DeployedTrigger, nonce: string, secret: string): RawRequest+ }+ /** A secondary trust gate evaluated AFTER auth succeeds (today: slack's+ * `trusted_workspaces`). Declared only by triggers that have one. */+ allowlist?: {+ /** Deploy an agent whose allowlist will reject the probe identity+ * `rejectedRequest` uses. */+ deployRejecting(): Promise<DeployedTrigger>+ /** A request that authenticates/signs fine but misses the allowlist. */+ rejectedRequest(dep: DeployedTrigger, nonce: string): RawRequest+ }+ /** Redelivery dedup. Declared only by triggers with a dedup identity+ * (a provider delivery-id header, or — for slack — the event's own+ * (channel, ts) coordinates). */+ dedup?: {+ /** Build a request carrying the same dedup identity for a given+ * `nonce`; calling this twice with the same nonce must collapse to+ * one session. */+ request(dep: DeployedTrigger, nonce: string): RawRequest+ }+}++function jsonRequest(path: string, body: unknown, extraHeaders: Record<string, string> = {}): RawRequest {+ return { path, headers: { 'content-type': 'application/json', ...extraHeaders }, rawBody: JSON.stringify(body) }+}++/** Same bytes as `jsonRequest`, but the Content-Type header lies — raw body is still valid JSON. */+function mislabeledAsUrlencoded(path: string, body: unknown, extraHeaders: Record<string, string> = {}): RawRequest {+ return {+ path,+ headers: { 'content-type': 'application/x-www-form-urlencoded', ...extraHeaders },+ rawBody: JSON.stringify(body),+ }+}++function signSlackBody(rawBody: string, secret: string): { ts: string; sig: string } {+ const ts = String(Math.floor(Date.now() / 1000))+ const mac = createHmac('sha256', secret).update(`v0:${ts}:${rawBody}`).digest('hex')+ return { ts, sig: `v0=${mac}` }+}++function slackSignedRequest(path: string, bodyObj: unknown, contentType: string, secret: string): RawRequest {+ const raw = JSON.stringify(bodyObj)+ const { ts, sig } = signSlackBody(raw, secret)+ return {+ path,+ headers: { 'content-type': contentType, 'x-slack-request-timestamp': ts, 'x-slack-signature': sig },+ rawBody: raw,+ }+}++/** Seed message content is `ConversationMessage['content']`, which can be a+ * plain string or a structured block list — normalize to a string so the+ * content-type test can `.toContain(nonce)` regardless of shape. */+function seedContent(session: AgentSession): string {+ const content = session.conversation[0]?.content ?? ''+ return typeof content === 'string' ? content : JSON.stringify(content)+}++function slackEventBody(nonce: string, workspace: string): Record<string, unknown> {+ return {+ type: 'event_callback',+ team_id: workspace,+ event: { type: 'message', channel: `C-${nonce}`, user: 'U1', text: `hello-${nonce}`, ts: `${nonce}.000` },+ }+}++/** The exact seed slack.ts builds for a plain `message` event from+ * `slackEventBody` (never hits the mention/DM/resume branches). Mirrors the+ * `slackContext` template in `slack.ts`. */+function expectedSlackSeed(nonce: string, workspace: string): string {+ return [+ '[slack]',+ `channel: C-${nonce}`,+ `ts: ${nonce}.000`,+ `thread_ts: ${nonce}.000`,+ `workspace: ${workspace}`,+ 'user: U1',+ 'mention: false',+ 'dm: false',+ '',+ `hello-${nonce}`,+ ].join('\n')+}++let pool: Pool+let bus: RedisSessionEventBus+let revisions: PgRevisionStore+let queue: PgSessionQueue+let approvals: PgApprovalStore+let credentialBroker: PgCredentialBroker+let happyApp: Express++function buildTestApp(overrides: { slackSigningSecretResolver?: SecretResolver } = {}): Express {+ return buildApp({+ revisions,+ queue,+ approvals,+ bus,+ credentialBroker,+ identities: new PgIdentityStore(pool),+ http: new DirectHttpClient(),+ identityCredentials: new PgIdentityCredentialStore(pool, { encryptionSaltKeys: HARNESS_ENCRYPTION_SALT_KEYS }),+ identityLinks: new PgIdentityLinkStateStore(pool),+ transportBindings: new PgTransportBindingStore(pool),+ envEncryption: new EncryptedFields(HARNESS_ENCRYPTION_SALT_KEYS),+ routingMode: 'path',+ pathPrefix: '/agents',+ slackSigningSecretResolver: overrides.slackSigningSecretResolver ?? {+ async resolve(): Promise<string | null> {+ return SLACK_SECRET+ },+ },+ })+}++async function deployAgent(triggers: unknown[]): Promise<DeployedTrigger> {+ const slug = `conformance-${randomUUID().slice(0, 12)}`+ const application = await revisions.createApplication({ team_id: 1, slug, name: slug, description: '' })+ const revision = await revisions.createRevision({+ application_id: application.id,+ parent_revision_id: null,+ created_by_id: null,+ bundle_uri: 's3://x/',+ spec: AgentSpecSchema.parse({ model: 'test/x', triggers }),+ })+ await revisions.setRevisionState(revision.id, 'live')+ await revisions.setLiveRevision(application.id, revision.id)+ return { application, revision }+}++async function fire(app: Express, req: RawRequest): Promise<request.Response> {+ let r = request(app).post(req.path)+ for (const [name, value] of Object.entries(req.headers)) {+ r = r.set(name, value)+ }+ return r.send(req.rawBody)+}++const CONFORMANCE_FIXTURES: Partial<Record<TriggerType, ConformanceFixture>> = {+ chat: {+ type: 'chat',+ async deployHappy() {+ return deployAgent([{ type: 'chat', config: {}, auth: PUBLIC_AUTH }])+ },+ validRequest(dep, nonce) {+ return jsonRequest(`/agents/${dep.application.slug}/run`, {+ message: `hello-${nonce}`,+ external_key: `chat-ext-${nonce}`,+ })+ },+ mislabeledRequest(dep, nonce) {+ return mislabeledAsUrlencoded(`/agents/${dep.application.slug}/run`, { message: `hello-${nonce}` })+ },+ // ChatRunBodySchema requires `message` as a top-level key, which urlencoded mis-parsing can't produce, so this arm 400s first (unreachable today; declared for parity).+ expectedContentAfterMislabel: (nonce) => `hello-${nonce}`,+ sessionIdFromResponse: (body) => (body as { session_id?: string }).session_id,+ contentOf: seedContent,+ // No signing (bearer auth, not a body signature), no allowlist (auth+ // IS the gate), no dedup (client picks external_key; there's no+ // provider delivery id to redeliver).+ },+ webhook: {+ type: 'webhook',+ async deployHappy() {+ return deployAgent([{ type: 'webhook', config: { path: '/webhook' }, auth: PUBLIC_AUTH }])+ },+ validRequest(dep, nonce) {+ return jsonRequest(`/agents/${dep.application.slug}/webhook`, { event: `payload-${nonce}` })+ },+ mislabeledRequest(dep, nonce) {+ return mislabeledAsUrlencoded(`/agents/${dep.application.slug}/webhook`, { event: `payload-${nonce}` })+ },+ // webhook.ts delivers the body verbatim as the first user message (JSON-stringified), so a correct parse of `{ event: ... }` produces exactly this string.+ expectedContentAfterMislabel: (nonce) => JSON.stringify({ event: `payload-${nonce}` }),+ sessionIdFromResponse: (body) => (body as { session_id?: string }).session_id,+ contentOf: seedContent,+ // No allowlist knob — auth is the only gate webhook has.+ dedup: {+ request(dep, nonce) {+ // `X-GitHub-Delivery` is one of the provider delivery-id+ // headers webhook.ts keys dedup on.+ return jsonRequest(+ `/agents/${dep.application.slug}/webhook`,+ { event: `dedup-${nonce}` },+ { 'x-github-delivery': `gh-${nonce}` }+ )+ },+ },+ },+ mcp: {+ type: 'mcp',+ async deployHappy() {+ return deployAgent([{ type: 'mcp', config: {}, auth: PUBLIC_AUTH }])+ },+ validRequest(dep, nonce) {+ return jsonRequest(`/agents/${dep.application.slug}/mcp`, {+ jsonrpc: '2.0',+ id: 1,+ method: 'tools/call',+ params: { name: 'ask', arguments: { message: `hello-${nonce}` } },+ })+ },+ mislabeledRequest(dep, nonce) {+ return mislabeledAsUrlencoded(`/agents/${dep.application.slug}/mcp`, {+ jsonrpc: '2.0',+ id: 1,+ method: 'tools/call',+ params: { name: 'ask', arguments: { message: `hello-${nonce}` } },+ })+ },+ // McpRequestBodySchema requires `jsonrpc`/`method` as top-level keys, which urlencoded mis-parsing can't produce, so this arm 400s first (unreachable; declared for parity).+ expectedContentAfterMislabel: (nonce) => `hello-${nonce}`,+ sessionIdFromResponse(body) {+ const rpc = body as { result?: { content?: Array<{ text?: string }> } }+ const text = rpc.result?.content?.[0]?.text+ if (!text) {+ return undefined+ }+ try {+ return (JSON.parse(text) as { session_id?: string }).session_id+ } catch {+ return undefined+ }+ },+ contentOf: seedContent,+ // No signing, no allowlist, no dedup — MCP has no provider+ // delivery-id concept; session continuation is client-driven.+ },+ slack: {+ type: 'slack',+ async deployHappy() {+ return deployAgent([{ type: 'slack', config: { trusted_workspaces: '*' } }])+ },+ validRequest(dep, nonce) {+ return slackSignedRequest(+ `/agents/${dep.application.slug}/slack/events`,+ slackEventBody(nonce, 'T-TRUSTED'),+ 'application/json',+ SLACK_SECRET+ )+ },+ mislabeledRequest(dep, nonce) {+ return slackSignedRequest(+ `/agents/${dep.application.slug}/slack/events`,+ slackEventBody(nonce, 'T-TRUSTED'),+ 'application/x-www-form-urlencoded',+ SLACK_SECRET+ )+ },+ expectedContentAfterMislabel: (nonce) => expectedSlackSeed(nonce, 'T-TRUSTED'),+ sessionIdFromResponse: (body) => (body as { session_id?: string }).session_id,+ contentOf: seedContent,+ signing: {+ request(dep, nonce, secret) {+ return slackSignedRequest(+ `/agents/${dep.application.slug}/slack/events`,+ slackEventBody(nonce, 'T-TRUSTED'),+ 'application/json',+ secret+ )+ },+ },+ allowlist: {+ async deployRejecting() {+ return deployAgent([{ type: 'slack', config: { trusted_workspaces: ['T-ALLOWED-ONLY'] } }])+ },+ rejectedRequest(dep, nonce) {+ return slackSignedRequest(+ `/agents/${dep.application.slug}/slack/events`,+ slackEventBody(nonce, 'T-NOT-ALLOWED'),+ 'application/json',+ SLACK_SECRET+ )+ },+ },+ dedup: {+ request(dep, nonce) {+ // Same nonce twice → same (channel, ts) → the same `slack:msg:<channel>:<ts>` idempotency key slack.ts computes; the dedup identity is the event envelope, not a wire header.+ return slackSignedRequest(+ `/agents/${dep.application.slug}/slack/events`,+ slackEventBody(nonce, 'T-TRUSTED'),+ 'application/json',+ SLACK_SECRET+ )+ },+ },+ },+}++describe('trigger-module conformance suite', () => {+ beforeAll(async () => {+ pool = new Pool({ connectionString: TEST_DB_URL })+ bus = new RedisSessionEventBus({+ url: REDIS_URL,+ channelPrefix: `conformance_${Math.random().toString(36).slice(2, 10)}`,+ })+ await bus.connect()+ revisions = new PgRevisionStore(pool)+ queue = new PgSessionQueue(pool)+ approvals = new PgApprovalStore(pool)+ credentialBroker = new PgCredentialBroker(pool, { encryptionSaltKeys: HARNESS_ENCRYPTION_SALT_KEYS })+ })++ beforeEach(async () => {+ await reset({ databaseUrl: TEST_DB_URL })+ happyApp = buildTestApp()+ })++ afterAll(async () => {+ await bus.disconnect()+ await pool.end()+ })++ describe('fixture totality (the ratchet)', () => {+ it(`every TRIGGER_MODULES entry has a CONFORMANCE_FIXTURES entry (floor: ${TRIGGER_MODULES.length} modules)`, () => {+ // Floor first: a totality loop over an empty `TRIGGER_MODULES` passes vacuously, so pin a count floor — a registry collapsing to nothing fails here instead of silently disabling every case.+ expect(TRIGGER_MODULES.length).toBeGreaterThanOrEqual(4)+ const missing = TRIGGER_MODULES.map((m) => m.type).filter((t) => !CONFORMANCE_FIXTURES[t])+ // A newly registered trigger with no fixture shows up here by name.+ expect(missing).toEqual([])+ })+ })++ // The inner suites filter fixtures with `.filter(f => f.<edge>)`, but that+ // predicate is a hidden hand-list — a trigger that omits an edge key is+ // silently uncovered and green. Double-entry guards it: EXPECTED (below) is+ // reconciled against the fixtures both ways. `signing` is derived from the+ // live modules (a `slack_signing` route auto-appears); the bespoke edges are+ // declared explicitly, keeping "is this list complete?" a visible judgment.+ describe('edge-class membership (double-entry over the filter-predicate hand-lists)', () => {+ type EdgeKey = 'signing' | 'mislabeledRequest' | 'allowlist' | 'dedup'+ const declares = (edge: EdgeKey): Set<TriggerType> =>+ new Set(+ Object.values(CONFORMANCE_FIXTURES)+ .filter((f): f is ConformanceFixture => Boolean(f?.[edge]))+ .map((f) => f.type)+ )+ const EXPECTED: Record<EdgeKey, Set<TriggerType>> = {+ signing: new Set(+ TRIGGER_MODULES.filter((m) => m.routes.some((r) => r.auth === 'slack_signing')).map((m) => m.type)+ ),+ mislabeledRequest: new Set<TriggerType>(['chat', 'webhook', 'mcp', 'slack']),+ allowlist: new Set<TriggerType>(['slack']),+ dedup: new Set<TriggerType>(['webhook', 'slack']),+ }+ const edges = Object.keys(EXPECTED) as EdgeKey[]++ it.each(edges)('%s: in scope for at least one trigger (floor — never vacuous)', (edge) => {+ expect(EXPECTED[edge].size).toBeGreaterThanOrEqual(1)+ })+ it.each(edges)('%s: every trigger in scope declares a fixture (no silent under-coverage)', (edge) => {+ const missing = [...EXPECTED[edge]].filter((t) => !declares(edge).has(t))+ expect(missing, `in scope for ${edge} but no fixture declares it: ${missing.join(', ')}`).toEqual([])+ })+ it.each(edges)('%s: every fixture that declares it is in scope (no stray/misclassified case)', (edge) => {+ const stray = [...declares(edge)].filter((t) => !EXPECTED[edge].has(t))+ expect(stray, `fixture declares ${edge} but it is not classified in scope: ${stray.join(', ')}`).toEqual([])+ })+ })++ describe('signing fail-closed', () => {+ const fixtures = Object.values(CONFORMANCE_FIXTURES).filter(+ (f): f is ConformanceFixture & { signing: NonNullable<ConformanceFixture['signing']> } =>+ Boolean(f?.signing)+ )++ it.each(fixtures)('$type: unresolvable signing secret → 5xx, never a 2xx', async (fx) => {+ const dep = await fx.deployHappy()+ const unconfiguredApp = buildTestApp({+ slackSigningSecretResolver: {+ async resolve(): Promise<string | null> {+ return null+ },+ },+ })+ const req = fx.signing.request(dep, randomUUID().slice(0, 8), SLACK_SECRET)+ const res = await fire(unconfiguredApp, req)+ expect(res.status).toBeGreaterThanOrEqual(500)+ expect(res.status).toBeLessThan(600)+ })++ it.each(fixtures)('$type: invalid signature → 401', async (fx) => {+ const dep = await fx.deployHappy()+ const req = fx.signing.request(dep, randomUUID().slice(0, 8), 'definitely-the-wrong-secret')+ const res = await fire(happyApp, req)+ expect(res.status).toBe(401)+ expect((res.body as { error?: string }).error).toBe('invalid_signature')+ })+ })++ describe('content-type robustness (urlencoded-mislabeled body must never silently drop)', () => {+ const fixtures = Object.values(CONFORMANCE_FIXTURES).filter(+ (+ f+ ): f is ConformanceFixture & {+ mislabeledRequest: NonNullable<ConformanceFixture['mislabeledRequest']>+ expectedContentAfterMislabel: NonNullable<ConformanceFixture['expectedContentAfterMislabel']>+ } => Boolean(f?.mislabeledRequest)+ )++ it.each(fixtures)(+ '$type: a JSON body mislabeled as application/x-www-form-urlencoded is rejected explicitly or processed correctly — never acked while dropped',+ async (fx) => {+ const dep = await fx.deployHappy()+ const nonce = randomUUID().slice(0, 8)+ const before = await queue.listByApplication(dep.application.id, { limit: 50 })+ const req = fx.mislabeledRequest(dep, nonce)+ const res = await fire(happyApp, req)+ const accepted = res.status >= 200 && res.status < 300+ if (accepted) {+ // "process correctly" arm: assert the body was actually parsed, not just acked. Exact equality (not substring) — see `expectedContentAfterMislabel`.+ const sessionId = fx.sessionIdFromResponse(res.body)+ expect(sessionId).toBeTruthy()+ const session = await queue.get(sessionId!)+ expect(session).not.toBeNull()+ expect(fx.contentOf(session!)).toBe(fx.expectedContentAfterMislabel(nonce))+ } else {+ // "reject explicitly" arm: a clear 4xx naming the problem —+ // never a 5xx (that's the trigger's own fault, not the+ // caller's) and never a bare ack.+ expect(res.status).toBeGreaterThanOrEqual(400)+ expect(res.status).toBeLessThan(500)+ expect((res.body as { error?: string })?.error).toBeTruthy()+ }+ const after = await queue.listByApplication(dep.application.id, { limit: 50 })+ expect(after.length).toBe(before.length + (accepted ? 1 : 0))+ }+ )++ // Slack's interactivity route legitimately receives `payload=<json>` as+ // urlencoded, so this is its dedicated "process correctly" arm: prove the+ // Express body-parser actually extracts `payload` (a regression would 400+ // on `missing_payload` instead of reaching the session lookup below).+ it('slack: /slack/interactivity legitimately consumes application/x-www-form-urlencoded payload=', async () => {+ const dep = await deployAgent([{ type: 'slack', config: { trusted_workspaces: '*' } }])+ const actionValue = encodeElevationActionValue({+ sessionId: randomUUID(),+ requestId: randomUUID(),+ decision: 'grant',+ })+ const payload = JSON.stringify({+ type: 'block_actions',+ team: { id: 'T-TRUSTED' },+ user: { id: 'U1', team_id: 'T-TRUSTED' },+ actions: [{ action_id: 'a', value: actionValue }],+ })+ const raw = `payload=${encodeURIComponent(payload)}`+ const { ts, sig } = signSlackBody(raw, SLACK_SECRET)+ const res = await request(happyApp)+ .post(`/agents/${dep.application.slug}/slack/interactivity`)+ .set('content-type', 'application/x-www-form-urlencoded')+ .set('x-slack-request-timestamp', ts)+ .set('x-slack-signature', sig)+ .send(raw)+ expect(res.status).toBe(404)+ expect((res.body as { error?: string }).error).toBe('session_not_found')+ })+ })++ describe('drop semantics: an authenticated event that fails an allowlist must ack 2xx with a drop indication', () => {+ const fixtures = Object.values(CONFORMANCE_FIXTURES).filter(+ (f): f is ConformanceFixture & { allowlist: NonNullable<ConformanceFixture['allowlist']> } =>+ Boolean(f?.allowlist)+ )++ it.each(fixtures)('$type: allowlist miss → 2xx ack with drop indication, never a 4xx', async (fx) => {+ const dep = await fx.allowlist.deployRejecting()+ const nonce = randomUUID().slice(0, 8)+ const before = await queue.listByApplication(dep.application.id, { limit: 50 })+ const req = fx.allowlist.rejectedRequest(dep, nonce)+ const res = await fire(happyApp, req)+ // A signed, authenticated delivery that misses an allowlist is a+ // routing decision, not a delivery failure — providers retry+ // non-2xx responses, so a 4xx here would cause redelivery storms.+ expect(res.status).toBeGreaterThanOrEqual(200)+ expect(res.status).toBeLessThan(300)+ expect((res.body as { dropped?: string }).dropped).toBeTruthy()+ const after = await queue.listByApplication(dep.application.id, { limit: 50 })+ expect(after.length).toBe(before.length)+ })+ })++ describe('dedup: a redelivered event collapses to one enqueue', () => {+ const fixtures = Object.values(CONFORMANCE_FIXTURES).filter(+ (f): f is ConformanceFixture & { dedup: NonNullable<ConformanceFixture['dedup']> } => Boolean(f?.dedup)+ )++ it.each(fixtures)('$type: the same event delivered twice → a single session', async (fx) => {+ const dep = await fx.deployHappy()+ const nonce = randomUUID().slice(0, 8)+ const first = await fire(happyApp, fx.dedup.request(dep, nonce))+ const firstSessionId = fx.sessionIdFromResponse(first.body)+ expect(firstSessionId).toBeTruthy()++ const second = await fire(happyApp, fx.dedup.request(dep, nonce))+ const secondSessionId = fx.sessionIdFromResponse(second.body)+ expect(secondSessionId).toBe(firstSessionId)++ const sessions = await queue.listByApplication(dep.application.id, { limit: 50 })+ expect(sessions).toHaveLength(1)+ const session = await queue.get(firstSessionId!)+ expect(session!.conversation).toHaveLength(1)+ expect(session!.pending_inputs).toHaveLength(0)+ })+ })+})diff --git a/products/agent_platform/services/agent-ingress/src/triggers/mcp.ts b/products/agent_platform/services/agent-ingress/src/triggers/mcp.tsindex 1b401820cedb..d6264a11ca69 100644--- a/products/agent_platform/services/agent-ingress/src/triggers/mcp.ts+++ b/products/agent_platform/services/agent-ingress/src/triggers/mcp.ts@@ -45,7 +45,13 @@ import { randomUUID } from 'crypto'import { Request } from 'express'import { z } from 'zod'-import { AgentSession, lastAssistantTextPreview, SessionPrincipal, triggerAuthConfig } from '@posthog/agent-shared'+import {+ AgentSession,+ lastAssistantTextPreview,+ SessionPrincipal,+ TRIGGER_ROUTES,+ triggerAuthConfig,+} from '@posthog/agent-shared'import { buildElevationResponse, principalDisplay, recordElevationRequest, requireAclAccess } from '../enqueue/acl'import { principalsMatch } from '../enqueue/auth'@@ -594,21 +600,21 @@ export const mcpTrigger: TriggerModule = {routes: [{method: 'POST',- path: '/mcp',+ path: TRIGGER_ROUTES.mcp.rpc,bodySchema: z.toJSONSchema(McpRequestBodySchema),auth: 'custom',handler: mcpHandler,},defineRoute({method: 'GET',- path: '/mcp/stream',+ path: TRIGGER_ROUTES.mcp.stream,auth: 'agent_spec',schema: McpStreamQuerySchema,handler: mcpStreamHandler,}),{method: 'GET',- path: '/mcp/connect-info',+ path: TRIGGER_ROUTES.mcp.connect_info,// Public — anyone who knows the URL can ask "how do I connect?".// Discovery cannot itself require auth without a chicken-and-egg.auth: 'public',diff --git a/products/agent_platform/services/agent-ingress/src/triggers/slack.ts b/products/agent_platform/services/agent-ingress/src/triggers/slack.tsindex 964fd158cf5b..a0774ba2c0a3 100644--- a/products/agent_platform/services/agent-ingress/src/triggers/slack.ts+++ b/products/agent_platform/services/agent-ingress/src/triggers/slack.ts@@ -25,6 +25,7 @@ import {principalsMatch,SessionPrincipal,SLACK_BOT_TOKEN_KEY,+ TRIGGER_ROUTES,} from '@posthog/agent-shared'import { applyElevationDecline, applyElevationGrant, authorizeGrant } from '../enqueue/acl'@@ -41,7 +42,11 @@ export { verifySlackSignature }async function slackEventsHandler(ctx: RouteCtx): Promise<void> {const { req, res, deps, resolved } = ctx- // Signature already verified by the slack_signing guard.+ // Signature guard hashes raw bytes, so a mislabeled Content-Type passes it; under urlencoded Express mis-parses the JSON and drops the event behind a bare 200. Reject explicitly.+ if (req.is('application/json') === false) {+ res.status(400).json({ error: 'invalid_content_type', expected: 'application/json' })+ return+ }const slackSpecTrigger = resolved.revision.spec.triggers.find((t) => t.type === 'slack')const body = req.body as {type?: string@@ -90,14 +95,15 @@ async function slackEventsHandler(ctx: RouteCtx): Promise<void> {// message events lack event.team; fall back to the envelope team_id.const workspaceId = event.team ?? body.team_id ?? 'unknown'if (trusted !== '*' && (!Array.isArray(trusted) || !trusted.includes(workspaceId))) {- // The rejected workspace id is otherwise only in the 403 body — surface- // it (plus the configured allowlist) so "why is Slack getting a 403?"+ // The rejected workspace id is otherwise only in the log line — surface+ // it (plus the configured allowlist) so "why did Slack get dropped?"// is answerable from the logs alone.log.warn({ slug: resolved.application.slug, workspace: workspaceId, trusted_workspaces: trusted ?? null },'slack_event_rejected_workspace_not_trusted')- res.status(403).json({ error: 'workspace_not_trusted', workspace: workspaceId })+ // Ack-and-drop, not 4xx: an untrusted-workspace delivery is a routing decision, not a failure. Providers retry non-2xx, so ack like the other drop paths (dm_not_enabled, mention_only).+ res.json({ ok: true, dropped: 'workspace_not_trusted', workspace: workspaceId })return}@@ -834,14 +840,14 @@ export const slackTrigger: TriggerModule = {routes: [{method: 'POST',- path: '/slack/events',+ path: TRIGGER_ROUTES.slack.events,bodySchema: z.toJSONSchema(SlackEventBodySchema),auth: 'slack_signing',handler: slackEventsHandler,},{method: 'POST',- path: '/slack/interactivity',+ path: TRIGGER_ROUTES.slack.interactivity,// Slack posts urlencoded `payload=<json>` — published schema is the// decoded JSON so authoring tools see the actual interactivity// contract, not just an opaque form-data envelope.diff --git a/products/agent_platform/services/agent-ingress/src/triggers/webhook.ts b/products/agent_platform/services/agent-ingress/src/triggers/webhook.tsindex cb79c2213109..cb3705e4e44e 100644--- a/products/agent_platform/services/agent-ingress/src/triggers/webhook.ts+++ b/products/agent_platform/services/agent-ingress/src/triggers/webhook.ts@@ -11,6 +11,8 @@ import { Request } from 'express'import { createHash } from 'node:crypto'import type { z } from 'zod'+import { TRIGGER_ROUTES } from '@posthog/agent-shared'+import { principalDisplay } from '../enqueue/acl'import { enqueueOrResume } from '../enqueue/enqueue'import { defineRoute, type AuthedRouteCtx, type TriggerModule } from './types'@@ -18,6 +20,11 @@ import { WebhookBodySchema } from './webhook.schemas'async function webhookHandler(ctx: AuthedRouteCtx<z.infer<typeof WebhookBodySchema>>): Promise<void> {const { req, res, deps, resolved } = ctx+ // A mislabeled urlencoded Content-Type still passes `WebhookBodySchema` (Express parses the raw JSON into a garbage form object), which would silently become the seed message. Reject explicitly.+ if (req.is('application/json') === false) {+ res.status(400).json({ error: 'invalid_content_type', expected: 'application/json' })+ return+ }const body = ctx.parsedconst externalKeyHeader = req.headers['x-external-key']const externalKey = typeof externalKeyHeader === 'string' ? externalKeyHeader : null@@ -99,7 +106,7 @@ export const webhookTrigger: TriggerModule = {routes: [defineRoute({method: 'POST',- path: '/webhook',+ path: TRIGGER_ROUTES.webhook.post,auth: 'agent_spec',schema: WebhookBodySchema,handler: webhookHandler,diff --git a/products/agent_platform/services/agent-janitor/.gitignore b/products/agent_platform/services/agent-janitor/.gitignoreindex 83631f817f87..20b35bdd7d6e 100644--- a/products/agent_platform/services/agent-janitor/.gitignore+++ b/products/agent_platform/services/agent-janitor/.gitignore@@ -1,3 +1,5 @@dist/node_modules/*.tsbuildinfo+.coherence-out/+.coherence/diff --git a/products/agent_platform/services/agent-janitor/coherence.config.json b/products/agent_platform/services/agent-janitor/coherence.config.jsonnew file mode 100644index 000000000000..2c5ed58c551f--- /dev/null+++ b/products/agent_platform/services/agent-janitor/coherence.config.json@@ -0,0 +1,10 @@+{+ "outputDir": ".coherence-out",+ "entryDir": "src",+ "ignore": ["node_modules", "dist", ".coherence-out"],+ "codeExt": ["ts"],+ "typecheck": ["npx", "tsc", "--noEmit", "-p", "."],+ "test": ["npx", "vitest", "run", "-t"],+ "testMatch": "[1-9][0-9]* passed",+ "language": "typescript"+}diff --git a/products/agent_platform/services/agent-janitor/src/Janitor.spec.md b/products/agent_platform/services/agent-janitor/src/Janitor.spec.mdnew file mode 100644index 000000000000..d95e6ad5d926--- /dev/null+++ b/products/agent_platform/services/agent-janitor/src/Janitor.spec.md@@ -0,0 +1,28 @@+# Janitor++Operational service: internal HTTP for Django (session lifecycle, approval decisions, revision authoring/freeze), the periodic queue sweep, and cron firing. It doubles as the agent-admin surface because it already has DB + bundle store access.++## invariants++- freeze-validate-lockstep+- approval-wire-consumption+- sweep-bounded-retries++## works when++- typechecks+- boundary "freeze-validate-lockstep" at validateRevisionBundle+- passes test "reports missing_entrypoint when agent.md is absent"+- passes test "catches unknown native tool ids and resolves valid ones"+- passes test "flags a manual model the gateway does not serve; passes one it does"+- passes test "rejects a required client tool when a webhook trigger is also configured"+- passes test "flags a malformed cron schedule"+- boundary "approval-wire-consumption" at buildJanitorApp via guard "approval routes never bypass the shared serializer"+- boundary "sweep-bounded-retries" at sweepOnce+- passes test "poison-pills a stuck running session after maxRetries re-queues"++## why++freeze-validate-lockstep: `validateRevisionBundle` is the single freeze-time gate a revision must pass before promotion to `ready`, and its checks deliberately mirror the paths the runtime would otherwise handle by silently degrading rather than rejecting — an unregistered native tool id is dropped from the toolset in `build-agent-tools.ts` (agent-runner) instead of erroring, a missing `agent.md` renders as a placeholder string in `system-prompt.ts`, and a sub-minute cron schedule would otherwise rely on the runtime's `MAX_FIRINGS_PER_TICK` backstop instead of failing outright. Freezing converts each of those silent runtime degradations into an explicit, author-visible error at promotion time, so a broken revision can't ship as a mysteriously half-working agent. The oracle pins five representative checks (missing entrypoint, unregistered native tool, a rejected model, a required client tool without a chat trigger, and a malformed cron schedule) as passing behavioral tests.+approval-wire-consumption: every janitor route that returns an approval row (`GET /approvals`, `GET /fleet/approvals`, `GET /approvals/:id`) must go through the shared `serializeApprovalRequest`, the one function that resolves `approver_scope.type` via `effectiveApprovalType` (declared `approval-wire-resolved` in agent-shared's `Persistence.spec.md`). A hand-rolled response bypassing it would ship the raw, unresolved scope and reintroduce the undefined-type regression that boundary was written to prevent one layer down. `serializeApprovalRequest` itself is defined in agent-shared, outside this package's own symbol graph, so this boundary anchors at `buildJanitorApp` — the one function that wires every approval route — and backs it with a source-property guard: no non-test file in the janitor's own source references `approver_scope` directly, the field a hand-rolled shape would have to touch.+sweep-bounded-retries: `sweepOnce` is the sole caller of `queue.reapStuckRunning` in the janitor, and it always supplies a bounded `maxRetries` (default 3) rather than re-queuing a stuck session unconditionally. The bound is enforced atomically inside `PgSessionQueue.reapStuckRunning`'s `retry_count < maxRetries` / `>= maxRetries` predicates, so a crash-looping session is poisoned (failed) instead of being re-queued forever and re-running its side effects on every sweep tick. The oracle exercises the real Postgres-backed queue across three consecutive sweeps and asserts the exact tick where the session flips from requeue to poison — a non-proxy check against real enforcement.diff --git a/products/agent_platform/services/agent-janitor/src/approval-wire-boundary.test.ts b/products/agent_platform/services/agent-janitor/src/approval-wire-boundary.test.tsnew file mode 100644index 000000000000..ff45ebe480bc--- /dev/null+++ b/products/agent_platform/services/agent-janitor/src/approval-wire-boundary.test.ts@@ -0,0 +1,40 @@+import { readdirSync, readFileSync, statSync } from 'node:fs'+import { dirname, join, relative } from 'node:path'+import { fileURLToPath } from 'node:url'+import { describe, expect, it } from 'vitest'++/**+ * Approval-wire chokepoint oracle: fails the build if any non-test janitor+ * source touches `approver_scope` directly instead of going through the shared+ * `serializeApprovalRequest` (which resolves the type). See Persistence.spec.md+ * "approval-wire-resolved".+ */+const SRC_ROOT = dirname(fileURLToPath(import.meta.url))+const ALLOWED: string[] = []++function nonTestSourcesReferencing(token: string): string[] {+ const out: string[] = []+ const walk = (dir: string): void => {+ for (const name of readdirSync(dir)) {+ const p = join(dir, name)+ if (statSync(p).isDirectory()) {+ walk(p)+ continue+ }+ if (!p.endsWith('.ts') || p.endsWith('.test.ts')) {+ continue+ }+ if (readFileSync(p, 'utf-8').includes(token)) {+ out.push(relative(SRC_ROOT, p))+ }+ }+ }+ walk(SRC_ROOT)+ return out.sort()+}++describe('approval wire chokepoint (single serializer)', () => {+ it('approval routes never bypass the shared serializer', () => {+ expect(nonTestSourcesReferencing('approver_scope')).toEqual(ALLOWED)+ })+})diff --git a/products/agent_platform/services/agent-janitor/src/server.ts b/products/agent_platform/services/agent-janitor/src/server.tsindex 8febbaa8ebb6..c0eece4c6569 100644--- a/products/agent_platform/services/agent-janitor/src/server.ts+++ b/products/agent_platform/services/agent-janitor/src/server.ts@@ -57,6 +57,7 @@ import {GatewayCatalog,ApprovalStore,applyApprovalDecision,+ serializeApprovalRequest,BundleEntry,BundleStore,buildSlackManifest,@@ -701,28 +702,6 @@ export function buildJanitorApp(opts: JanitorServerOpts): Express {return true}- const summariseApproval = (r: ApprovalRequest): Record<string, unknown> => ({- id: r.id,- session_id: r.session_id,- application_id: r.application_id,- team_id: r.team_id,- revision_id: r.revision_id,- turn: r.turn,- tool_call_id: r.tool_call_id,- tool_name: r.tool_name,- proposed_args: r.proposed_args,- decided_args: r.decided_args,- assistant_message: r.assistant_message,- approver_scope: r.approver_scope,- state: r.state,- decision_by: r.decision_by,- decision_at: r.decision_at,- decision_reason: r.decision_reason,- dispatch_outcome: r.dispatch_outcome,- created_at: r.created_at,- expires_at: r.expires_at,- })-app.get('/approvals',asyncHandler(async (req, res) => {@@ -735,7 +714,7 @@ export function buildJanitorApp(opts: JanitorServerOpts): Express {limit: q.limit,offset: q.offset,})- res.json({ results: rows.map(summariseApproval) })+ res.json({ results: rows.map(serializeApprovalRequest) })}))@@ -757,7 +736,7 @@ export function buildJanitorApp(opts: JanitorServerOpts): Express {limit: q.limit,offset: q.offset,})- res.json({ results: rows.map(summariseApproval) })+ res.json({ results: rows.map(serializeApprovalRequest) })}))@@ -772,7 +751,7 @@ export function buildJanitorApp(opts: JanitorServerOpts): Express {res.status(404).json({ error: 'not_found' })return}- res.json(summariseApproval(row))+ res.json(serializeApprovalRequest(row))}))diff --git a/products/agent_platform/services/agent-runner/.gitignore b/products/agent_platform/services/agent-runner/.gitignoreindex 83631f817f87..20b35bdd7d6e 100644--- a/products/agent_platform/services/agent-runner/.gitignore+++ b/products/agent_platform/services/agent-runner/.gitignore@@ -1,3 +1,5 @@dist/node_modules/*.tsbuildinfo+.coherence-out/+.coherence/diff --git a/products/agent_platform/services/agent-runner/coherence.config.json b/products/agent_platform/services/agent-runner/coherence.config.jsonnew file mode 100644index 000000000000..2c5ed58c551f--- /dev/null+++ b/products/agent_platform/services/agent-runner/coherence.config.json@@ -0,0 +1,10 @@+{+ "outputDir": ".coherence-out",+ "entryDir": "src",+ "ignore": ["node_modules", "dist", ".coherence-out"],+ "codeExt": ["ts"],+ "typecheck": ["npx", "tsc", "--noEmit", "-p", "."],+ "test": ["npx", "vitest", "run", "-t"],+ "testMatch": "[1-9][0-9]* passed",+ "language": "typescript"+}diff --git a/products/agent_platform/services/agent-runner/src/loop/Loop.spec.md b/products/agent_platform/services/agent-runner/src/loop/Loop.spec.mdnew file mode 100644index 000000000000..8aa7966ac2c5--- /dev/null+++ b/products/agent_platform/services/agent-runner/src/loop/Loop.spec.md@@ -0,0 +1,16 @@+# Loop++The session turn loop: model streaming, tool dispatch, and the approval gate that decides whether a tool call executes now or queues for a human decision.++## invariants++- gated-dispatch-single-path++## works when++- typechecks+- boundary "gated-dispatch-single-path" at gateTool via test "gate chokepoint — fail-closed dispatch"++## why++gated-dispatch-single-path: whether a gated tool call may execute is decided in exactly one place. Every tool lane (native, custom, MCP inline, MCP proxy, client, synthetic helpers) is wrapped through `gateTool`, which stamps a module-private brand; `assertToolsGated` runs before tools reach the model loop and throws on any unbranded tool, so a lane that skips the gate is a loud boot-time failure instead of a silent fail-open — the shape behind repeated production fixes where one wrap site was forgotten while the others were patched. The oracle enumerates every approval authority in `ApprovalTypeSchema.options` (floored, so an emptied enum can't pass vacuously) and asserts a gated call never reaches the real executor without a decision row, plus that an unbranded tool injected into dispatch throws.diff --git a/products/agent_platform/services/agent-runner/src/loop/driver.test.ts b/products/agent_platform/services/agent-runner/src/loop/driver.test.tsindex 8bbed6a2f240..cd594afa8e45 100644--- a/products/agent_platform/services/agent-runner/src/loop/driver.test.ts+++ b/products/agent_platform/services/agent-runner/src/loop/driver.test.ts@@ -19,6 +19,7 @@ import {AgentRevision,type ApprovalRequest,type ApprovalStore,+ ApprovalTypeSchema,AgentSession,AgentSpecSchema,buildTestBundleStore,@@ -41,6 +42,7 @@ const KAFKA_HOSTS = process.env.KAFKA_HOSTS ?? 'localhost:9092'import { buildApprovalDecidedMarker } from '@posthog/agent-shared'import { runSession } from './driver'+import { assertToolsGated, gateTool } from './gate-tool'import type { OpenedMcp, RemoteMcpTool } from './mcp-clients'const FAUX_MODEL_ID = 'faux/test'@@ -187,6 +189,42 @@ async function run(})}+// Minimal `OpenedMcp` stub that tracks `callTool` invocations, so a test can+// assert the gated path never reached the remote.+function makeFakeMcp(+ prefix: string,+ ref: McpRef,+ tools: Record<string, { description: string; result: unknown }>+): OpenedMcp & { calls: Array<{ name: string; args: Record<string, unknown> }> } {+ const calls: Array<{ name: string; args: Record<string, unknown> }> = []+ return {+ prefix,+ ref,+ listTools: async (): Promise<RemoteMcpTool[]> =>+ Object.entries(tools).map(([name, t]) => ({+ name,+ description: t.description,+ inputSchema: { type: 'object' },+ })),+ callTool: async (name, args) => {+ calls.push({ name, args })+ const result = tools[name]?.result ?? null+ return {+ content: [{ type: 'text' as const, text: JSON.stringify(result) }],+ structuredContent: result as Record<string, unknown>,+ }+ },+ close: async () => undefined,+ calls,+ } as OpenedMcp & { calls: typeof calls }+}++const principalAlice: SessionPrincipal = {+ kind: 'posthog',+ user_id: 'alice',+ team_id: 1,+}+describe('driver runSession', () => {// These tests use `@posthog/query` purely as a generic native tool. The// sessions carry no `posthog` principal, so the tool fails closed@@ -366,38 +404,6 @@ describe('driver runSession', () => {* relies on (which always queues — there is no fast-path).*/describe('MCP tool approval gating', () => {- // Minimal `OpenedMcp` stub — same shape as `build-agent-tools.test.ts`'s- // helper but trimmed to what these cases need. Tracks `callTool`- // invocations so we can assert the gated path didn't reach the- // remote.- function makeFakeMcp(- prefix: string,- ref: McpRef,- tools: Record<string, { description: string; result: unknown }>- ): OpenedMcp & { calls: Array<{ name: string; args: Record<string, unknown> }> } {- const calls: Array<{ name: string; args: Record<string, unknown> }> = []- return {- prefix,- ref,- listTools: async (): Promise<RemoteMcpTool[]> =>- Object.entries(tools).map(([name, t]) => ({- name,- description: t.description,- inputSchema: { type: 'object' },- })),- callTool: async (name, args) => {- calls.push({ name, args })- const result = tools[name]?.result ?? null- return {- content: [{ type: 'text' as const, text: JSON.stringify(result) }],- structuredContent: result as Record<string, unknown>,- }- },- close: async () => undefined,- calls,- } as OpenedMcp & { calls: typeof calls }- }-// Route through `AgentSpecSchema.parse` so the approval-policy// defaults (`type`, `allow_edit`, `ttl_ms`) get materialised — the// runner reads the strict shape, not the zod input form.@@ -422,12 +428,6 @@ describe('driver runSession', () => {],}).mcps[0]- const principalAlice: SessionPrincipal = {- kind: 'posthog',- user_id: 'alice',- team_id: 1,- }-it('queues an approval row when the model calls a gated MCP tool', async () => {// Concierge-shape: the model invokes promote-create; the// dispatcher's MCP lookup finds `level: 'approve'` on the@@ -464,6 +464,26 @@ describe('driver runSession', () => {expect(rows[0].state).toBe('queued')})+ it('gates a mutating native tool even when its spec entry omits requires_approval (intrinsic floor)', async () => {+ // `@posthog/identity-connect` is intrinsically gated (approval class+ // `approve`), so the runtime floors the gate by intrinsic class even+ // though the spec ref leaves `requires_approval` false. (Read-only+ // `@posthog/query` in the same shape is NOT gated — see "dispatches a+ // native tool then completes" above. `@posthog/http-request` is+ // deliberately `allow`, so it would NOT gate here.)+ const approvals = new PgApprovalStore(pool)+ const session = makeSession({ principal: principalAlice })+ const out = await run(makeRev({ tools: [{ kind: 'native', id: '@posthog/identity-connect' }] }), session, {+ script: [toolUse([call('@posthog/identity-connect', { provider: 'posthog' })]), stop('queued')],+ approvals,+ })+ expect(out.state).toBe('completed')+ const rows = await approvals.listBySession(TEST_SESSION_ID)+ expect(rows).toHaveLength(1)+ expect(rows[0].tool_name).toBe('@posthog/identity-connect')+ expect(rows[0].state).toBe('queued')+ })+it('does NOT queue when the matching tools[] entry is allow-level (inclusion only)', async () => {// `agent-applications-list` is in tools[] with `level: 'allow'` —// exposed but not gated. The dispatcher's MCP lookup returns a@@ -786,6 +806,84 @@ describe('driver runSession', () => {})})+ /**+ * Pin the two fail-closed properties of the gate chokepoint (gate-tool.ts):+ * under any approval authority a gated call queues and never runs the real+ * executor; an unbranded tool throws at `assertToolsGated` before dispatch.+ */+ describe('gate chokepoint — fail-closed dispatch', () => {+ it('enumerates at least two approval authorities — an empty enum would pass every case below vacuously', () => {+ expect(ApprovalTypeSchema.options.length).toBeGreaterThanOrEqual(2)+ })++ it.each(ApprovalTypeSchema.options)(+ 'queues instead of executing a tool gated under approval type=%s (real executor never runs)',+ async (authority) => {+ const ref: McpRef = AgentSpecSchema.parse({+ model: FAUX_MODEL_ID,+ mcps: [+ {+ kind: 'agent',+ default_tool_approval: 'deny',+ id: 'gate',+ url: 'https://example.com/gate',+ secrets: [],+ tools: [+ {+ name: 'risky',+ level: 'approve',+ approval_policy: { type: authority, ttl_ms: 900_000 },+ },+ ],+ },+ ],+ }).mcps[0]+ const mcp = makeFakeMcp('gate', ref, { risky: { description: 'd', result: { done: true } } })+ const approvals = new PgApprovalStore(pool)+ const session = makeSession({ principal: principalAlice })+ const out = await run(makeRev({ mcps: [ref as never] }), session, {+ script: [toolUse([call('gate__risky', { x: 1 })]), stop('queued')],+ approvals,+ mcpClients: [mcp],+ })+ expect(out.state).toBe('completed')+ // The real executor never ran, regardless of who decides.+ expect(mcp.calls).toEqual([])+ const rows = await approvals.listBySession(TEST_SESSION_ID)+ expect(rows).toHaveLength(1)+ expect(rows[0].state).toBe('queued')+ expect(rows[0].approver_scope).toMatchObject({ type: authority })+ }+ )++ it('throws before dispatch when a tool reaches the chokepoint unbranded (a lane bypassed gateTool)', () => {+ const bypassedExecute = vi.fn(async () => ({ content: [], details: {} }))+ const branded = gateTool(+ {+ name: 'ok-tool',+ label: 'ok-tool',+ description: '',+ parameters: { type: 'object' } as never,+ execute: async () => ({ content: [], details: {} }),+ },+ () => ({ gate: false }),+ async () => ({ content: [], details: {} }) as never+ )+ // Simulates a future lane that builds an `AgentTool` without ever+ // calling `gateTool`.+ const bypassed = {+ name: 'bypassed-tool',+ label: 'bypassed-tool',+ description: '',+ parameters: { type: 'object' } as never,+ execute: bypassedExecute,+ }+ expect(() => assertToolsGated([branded, bypassed as never])).toThrow(/bypassed-tool/)+ // The unbranded tool's execute is never invoked.+ expect(bypassedExecute).not.toHaveBeenCalled()+ })+ })+/*** Covers the gateway-metadata streamFn wrapper + the post-turn settled* cost fetch. Uses a recording `streamFn` injected via deps so we can@@ -1133,7 +1231,7 @@ describe('driver runSession', () => {expect(out.state).toBe('completed')const gens = events.filter((e): e is AnalyticsGenerationEvent => e.kind === 'generation')expect(gens).toHaveLength(1)- expect(gens[0].cost_usd).toBeUndefined()+ expect(gens[0].cost).toBeUndefined()})})diff --git a/products/agent_platform/services/agent-runner/src/loop/driver.ts b/products/agent_platform/services/agent-runner/src/loop/driver.tsindex a75f4a6867b2..0dad216d4e06 100644--- a/products/agent_platform/services/agent-runner/src/loop/driver.ts+++ b/products/agent_platform/services/agent-runner/src/loop/driver.ts@@ -33,14 +33,7 @@* `pending_inputs` — handled in `getSteeringMessages`.*/-import type {- AgentContext,- AgentEvent,- AgentEventSink,- AgentMessage,- AgentToolResult,- StreamFn,-} from '@earendil-works/pi-agent-core'+import type { AgentContext, AgentEvent, AgentEventSink, AgentMessage, StreamFn } from '@earendil-works/pi-agent-core'import { runAgentLoop } from '@earendil-works/pi-agent-core'import type { AssistantMessage, Message } from '@earendil-works/pi-ai'import { streamSimple } from '@earendil-works/pi-ai'@@ -60,9 +53,12 @@ import {ConversationMessage,CredentialBroker,createLogger,+ extractGatewayRequestId,FRAMEWORK_PROMPT_VERSION,+ GATEWAY_REQUEST_ID_HEADER,GatewayCatalog,GatewayClient,+ gatewaySettledCost,generationSpanId,HttpFetcher,IdentityCredentialStore,@@ -85,15 +81,18 @@ import {SLACK_BOT_TOKEN_KEY,SlackStatusReporter,slackTextFromContent,+ resolveToolRefApprovalLevel,TabularStore,ToolContext,toolSpanId,WebSearchProvider,} from '@posthog/agent-shared'+import { nativeToolApprovalClass } from '@posthog/agent-tools'import { approvalMarkerRequestId, ApprovalPolicy, dispatchApprovedResult, queueApprovalResult } from './approval'import { AgentToolDeps, buildAgentTools, MetaControl, RealToolExecute, ToolResultDetails } from './build-agent-tools'import { fallbackStreamFn, ResolvedModel } from './fallback-stream'+import { assertToolsGated, gateTool, QueueGated } from './gate-tool'import { resolveMaxOutputTokens } from './max-output-tokens'import type { McpOpenFailure, OpenedMcp } from './mcp-clients'import {@@ -541,10 +540,10 @@ export async function runSession(rev: AgentRevision, session: AgentSession, depslet lastOutput: unknown = nullconst toolStarts = new Map<string, { args: Record<string, unknown>; t0: number }>()- // Keep each tool's real execute, then swap gated tools for the queue path.- // The real execute is what an approved call runs on resume (the human has- // already cleared the gate). `approvals` is mandatory (runSession throws- // otherwise), so gating is unconditional — there is no ungated fast path.+ // Keep each tool's real execute (what an approved call runs on resume,+ // once the human has cleared the gate), then rebuild every tool through+ // `gateTool`. `approvals` is mandatory (runSession throws otherwise), so+ // gating is unconditional — there is no ungated fast path.const realExecute = new Map<string, RealToolExecute>()for (const tool of tools) {// Tools are named with their original id.@@ -555,20 +554,20 @@ export async function runSession(rev: AgentRevision, session: AgentSession, deps// pi-agent-core Promise.alls a turn's tool calls, so two gated// calls in one turn would both pass the max_open_approvals count// check before either row lands. Chain the count+insert critical- // section instead: one worker owns a session run (queue claim is- // exclusive), so an in-process chain is a sufficient lock — no- // other process inserts queued rows for this session.+ // section instead so a session's gated writes serialize in-process.+ // This is a single-worker best-effort lock, NOT a hard guarantee:+ // the stuck-running reaper (`reapStuckRunning`) can requeue a+ // slow-but-alive session on a time threshold with no fencing, so two+ // workers may briefly run one session, each with its own chain. The+ // cap can then overshoot — bounded and self-correcting once a+ // decision frees a slot (see the TOCTOU note in approval.ts). A hard+ // cap would need SQL-level enforcement or a claim lease/fence token.let gateChain: Promise<unknown> = Promise.resolve()- // Shared by the static wrap and the dynamic proxy wrap. Every gated- // call queues for a human decision — being the asker is not consent- // to the specific call (the model could have been steered by content- // it read). `toolName` is what the approval row records.- const queueGated = async (- toolName: string,- toolCallId: string,- args: Record<string, unknown>,- policy: ApprovalPolicy- ): Promise<AgentToolResult<ToolResultDetails>> => {+ // Shared by every lane's resolver below. Every gated call queues for+ // a human decision — being the asker is not consent to the specific+ // call (the model could have been steered by content it read).+ // `toolName` is what the approval row records.+ const queueGated: QueueGated = async (toolName, toolCallId, args, policy) => {const run = gateChain.then(() =>queueApprovalResult({approvals,@@ -609,33 +608,32 @@ export async function runSession(rev: AgentRevision, session: AgentSession, deps// so the synthetic read-only helpers below can be recognised as ours.const proxiedPrefixes = proxiedPrefixesFromCallTools(mcpProxyCallTools.keys())- for (const tool of tools) {+ for (let i = 0; i < tools.length; i++) {+ const tool = tools[i]const id = tool.name// Proxy `call_tool` gates dynamically: the underlying tool is// only known at call time (the `tool_name` arg), so re-key the// gate on `<prefix>__<tool_name>` per call.const proxyEntry = mcpProxyCallTools.get(id)if (proxyEntry) {- const realProxyExecute = tool.execute as RealToolExecute- tool.execute = async (toolCallId, args) => {- const a = (args ?? {}) as Record<string, unknown>- const raw = typeof a.tool_name === 'string' ? a.tool_name : ''- // Resolve the same way `call_tool` will at dispatch time- // (mcp-proxy.ts `resolveProxyRemoteName`): prefer the raw- // name when it exists in the exposed catalog, only strip- // `<prefix>__` when the stripped name does. Unconditionally- // stripping was a bypass: a remote tool whose RAW name was- // `<prefix>__delete` would gate as `delete` (no entry,- // policy=allow) while dispatch ran the raw `<prefix>__delete`.- // Sharing the resolver keeps the two paths in lockstep.- const remoteName = proxyEntry.resolveRemoteName(raw)- const exposedName = `${proxyEntry.client.prefix}${PREFIX_SEPARATOR}${remoteName}`- const gate = lookupMcpToolApproval(exposedName, rev.spec)- if (gate?.requires_approval) {- return queueGated(exposedName, toolCallId, a, gate.approval_policy)- }- return realProxyExecute(toolCallId, a)- }+ tools[i] = gateTool(+ tool,+ (_toolCallId, args) => {+ const raw = typeof args.tool_name === 'string' ? args.tool_name : ''+ // Resolve the same way `call_tool` will at dispatch time+ // (mcp-proxy.ts `resolveProxyRemoteName`): prefer the raw+ // name when it exists in the exposed catalog, only strip+ // `<prefix>__` when the stripped name does. Gate and dispatch+ // must key on the same name or one tool gates while another runs.+ const remoteName = proxyEntry.resolveRemoteName(raw)+ const exposedName = `${proxyEntry.client.prefix}${PREFIX_SEPARATOR}${remoteName}`+ const gate = lookupMcpToolApproval(exposedName, rev.spec)+ return gate?.requires_approval+ ? { gate: true, toolName: exposedName, policy: gate.approval_policy }+ : { gate: false }+ },+ queueGated+ )continue}// Synthetic proxy read-only helpers (`explore_tools` /@@ -645,6 +643,7 @@ export async function runSession(rev: AgentRevision, session: AgentSession, deps// `lookupMcpToolApproval` (which can't tell a synthetic helper from// a real same-named tool); the proxy-aware check lives here.if (isProxyReadOnlyHelper(id, proxiedPrefixes)) {+ tools[i] = gateTool(tool, () => ({ gate: false }), queueGated)continue}@@ -656,7 +655,17 @@ export async function runSession(rev: AgentRevision, session: AgentSession, deps// Client tools have no approval field today so they skip// either path. (PR 7 — runtime-mcps.md "Resolved design".)const ref = rev.spec.tools.find((t) => t.id === id)- const nativeRef = ref && ref.kind !== 'client' && ref.requires_approval ? ref : null+ // The effective approval level FLOORS the spec's `requires_approval`:+ // a mutating native tool (intrinsic class `approve`, e.g.+ // `@posthog/memory-write`) is gated even when the author left+ // `requires_approval` false. Authors may tighten (set+ // `requires_approval`), never loosen below intrinsic.+ const nativeRef =+ ref &&+ ref.kind !== 'client' &&+ resolveToolRefApprovalLevel(ref, { nativeApprovalClass: nativeToolApprovalClass }) === 'approve'+ ? ref+ : null// Only fall through to MCP lookup when there's NO `spec.tools`// entry at all. A `client` tool whose id collides with an// MCP-exposed `<prefix>__<remote>` name is an author bug —@@ -670,13 +679,18 @@ export async function runSession(rev: AgentRevision, session: AgentSession, deps: mcpGate?.requires_approval? mcpGate.approval_policy: null- if (policy) {- tool.execute = async (toolCallId, args) =>- queueGated(id, toolCallId, (args ?? {}) as Record<string, unknown>, policy)- }+ tools[i] = gateTool(+ tool,+ () => (policy ? { gate: true, toolName: id, policy } : { gate: false }),+ queueGated+ )}}+ // Fail-closed: every tool must be `gateTool`-branded before dispatch+ // (see gate-tool.ts).+ assertToolsGated(tools)+const sink: AgentEventSink = async (event: AgentEvent): Promise<void> => {switch (event.type) {case 'turn_start': {@@ -866,11 +880,11 @@ export async function runSession(rev: AgentRevision, session: AgentSession, depsphc: deps.gatewayUsage.phc,})if (usage) {- const cost = Number(usage.cost_usd)- if (Number.isFinite(cost)) {+ const settled = gatewaySettledCost(usage)+ if (settled) {session.usage_total = {...session.usage_total,- cost_total: session.usage_total.cost_total + cost,+ cost_total: session.usage_total.cost_total + settled.usd,}} else {runLog.warn(@@ -982,12 +996,12 @@ export async function runSession(rev: AgentRevision, session: AgentSession, depsphc: deps.gatewayUsage.phc,})if (usage) {- const cost = Number(usage.cost_usd)+ const settled = gatewaySettledCost(usage)session.usage_total = {...session.usage_total,tokens_in: session.usage_total.tokens_in + (usage.input_tokens ?? 0),tokens_out: session.usage_total.tokens_out + (usage.output_tokens ?? 0),- cost_total: session.usage_total.cost_total + (Number.isFinite(cost) ? cost : 0),+ cost_total: session.usage_total.cost_total + (settled?.usd ?? 0),}}} catch (err) {@@ -1427,6 +1441,9 @@ function sanitizingStreamFn(base: StreamFn, safeToOriginal: Map<string, string>)export function sanitizeOutboundContext<T extends { tools?: Array<{ name: string }>; messages?: Message[] }>(context: T): T {+ // Provider-wire projection (the tool schemas the model sees), NOT the+ // executable dispatch array — the `{ ...t }` spread drops the gate brand.+ // If you ever dispatch off this result, re-gate it first.return {...context,tools: context.tools?.map((t) => ({ ...t, name: providerSafeName(t.name) })),@@ -1472,11 +1489,13 @@ export function translateAssistantNamesBack(** The usage lookup keys off the GATEWAY's id, not ours. The gateway mints its* own settlement reference server-side — a client-chosen id would let a caller- * collapse every debit as a duplicate — and returns it in the `X-Request-ID`- * response header; it ignores any inbound `X-Request-Id`. We read it back via- * pi-ai's `onResponse` (header keys are lowercased). Keying off the- * runner-chosen id never matched the ledger → `getUsage` 404'd every turn and- * cost stayed $0. A missing header (no `onResponse`, gateway misroute) just+ * collapse every debit as a duplicate — and returns it in the response header+ * named by `GATEWAY_REQUEST_ID_HEADER` (agent-shared's `gateway-wire`); it+ * ignores any inbound `X-Request-Id`. We read it back via+ * `extractGatewayRequestId` off pi-ai's `onResponse` (header keys are+ * lowercased) — the SAME function `gateway-client.ts`'s settled-cost lookup+ * builds its URL from (`gatewayUsagePath`), so the two sides can't key on+ * different ids. A missing header (no `onResponse`, gateway misroute) just* leaves the turn's entry unset → cost merge is skipped (fail-open).*/function gatewayMetadataStreamFn(@@ -1485,6 +1504,7 @@ function gatewayMetadataStreamFn(gatewayHeaders: Record<string, string> | undefined,turnRequestIds: Map<number, string>): StreamFn {+ const log = createLogger('runner')let outboundTurn = 0return async (model, context, options) => {outboundTurn++@@ -1495,9 +1515,21 @@ function gatewayMetadataStreamFn(...options,headers: { ...gatewayHeaders, ...options?.headers, 'Idempotency-Key': idempotencyKey },onResponse: async (response, m) => {- const id = response.headers['x-request-id']+ const id = extractGatewayRequestId(response.headers)if (id) {turnRequestIds.set(turnIndex, id)+ } else if (response.headers[GATEWAY_REQUEST_ID_HEADER]) {+ // Header present but rejected by the charset guard → no settlement+ // id, so this turn's cost silently won't settle. Surface it as a+ // diagnosable gap rather than a phantom $0 (per review).+ log.warn(+ {+ session_id: sessionId,+ turn: turnIndex,+ rejected: String(response.headers[GATEWAY_REQUEST_ID_HEADER]).slice(0, 64),+ },+ 'gateway.request_id.rejected'+ )}await priorOnResponse?.(response, m)},diff --git a/products/agent_platform/services/agent-runner/src/loop/gate-tool.ts b/products/agent_platform/services/agent-runner/src/loop/gate-tool.tsnew file mode 100644index 000000000000..8003875fe3e1--- /dev/null+++ b/products/agent_platform/services/agent-runner/src/loop/gate-tool.ts@@ -0,0 +1,73 @@+import type { AgentTool, AgentToolResult } from '@earendil-works/pi-agent-core'+import type { TSchema } from '@earendil-works/pi-ai'++import type { ApprovalPolicy } from './approval'+import type { RealToolExecute, ToolResultDetails } from './build-agent-tools'++/** Per-call gate outcome: dispatch for real, or queue for a human decision+ * under `toolName` (which may differ from the tool's own name — the MCP+ * proxy's `call_tool` re-keys onto the underlying remote tool). */+export type GateDecision = { gate: false } | { gate: true; toolName: string; policy: ApprovalPolicy }++/** Decide the gate outcome for one call. Most tools ignore the args (a fixed+ * policy resolved once at session start); the MCP proxy's `call_tool`+ * inspects `args.tool_name` to re-key the gate per call. */+export type ResolveGate = (toolCallId: string, args: Record<string, unknown>) => GateDecision | Promise<GateDecision>++/** Queues a gated call for a human decision instead of running it. */+export type QueueGated = (+ toolName: string,+ toolCallId: string,+ args: Record<string, unknown>,+ policy: ApprovalPolicy+) => Promise<AgentToolResult<ToolResultDetails>>++/** Set by `gateTool`, checked by `assertToolsGated`. Module-private so+ * nothing outside this file can forge the brand on a hand-rolled tool. */+const GATED = Symbol('gateTool.branded')++type Gated<T> = T & { [GATED]?: true }++/**+ * Wrap a tool's `execute` so every call is routed through `resolve` first:+ * gated calls queue via `queue` (never touching the real executor); ungated+ * calls run the tool's original `execute` unchanged. Returns a new tool+ * object carrying the brand `assertToolsGated` checks for.+ *+ * This is the ONLY place that is allowed to decide "does this call reach the+ * real executor" — every tool lane (native/custom/client/MCP inline/MCP+ * proxy) must construct its dispatched tool through this function.+ */+export function gateTool(+ tool: AgentTool<TSchema, ToolResultDetails>,+ resolve: ResolveGate,+ queue: QueueGated+): AgentTool<TSchema, ToolResultDetails> {+ const realExecute = tool.execute as RealToolExecute+ const gated: Gated<AgentTool<TSchema, ToolResultDetails>> = {+ ...tool,+ execute: async (toolCallId, args) => {+ const a = (args ?? {}) as Record<string, unknown>+ const decision = await resolve(toolCallId, a)+ return decision.gate ? queue(decision.toolName, toolCallId, a, decision.policy) : realExecute(toolCallId, a)+ },+ }+ gated[GATED] = true+ return gated+}++/**+ * Fail-closed chokepoint: throws (naming the tool) unless every tool carries+ * the brand `gateTool` stamps. Call at the single point the driver hands the+ * tool surface to the model loop — an unbranded tool means some lane built an+ * `AgentTool[]` without routing through `gateTool`.+ */+export function assertToolsGated(tools: ReadonlyArray<AgentTool<TSchema, ToolResultDetails>>): void {+ for (const tool of tools) {+ if (!(tool as Gated<AgentTool<TSchema, ToolResultDetails>>)[GATED]) {+ throw new Error(+ `approval gate bypassed for tool "${tool.name}" — every tool must be wrapped via gateTool() before dispatch`+ )+ }+ }+}diff --git a/products/agent_platform/services/agent-runner/src/models/ai-gateway-model.ts b/products/agent_platform/services/agent-runner/src/models/ai-gateway-model.tsindex 77d6acd8e054..a4c253e2ab84 100644--- a/products/agent_platform/services/agent-runner/src/models/ai-gateway-model.ts+++ b/products/agent_platform/services/agent-runner/src/models/ai-gateway-model.ts@@ -20,14 +20,17 @@* <phs_…>` (it reads only that header). pi-ai's openai shapes already send the* apiKey as `Authorization: Bearer`, but its anthropic-messages shape sends it* as `x-api-key` with no `Authorization` — so a Claude model would 401 at the- * gateway's auth tier. We pin `Authorization: Bearer <key>` on the model so- * every shape authenticates the way the gateway expects. pi-ai still sends the- * key as the provider credential too (x-api-key for Anthropic), which the+ * gateway's auth tier. We pin the header via agent-shared's+ * `gatewayAuthHeader` (the same builder every other gateway caller uses) so+ * every shape authenticates the way the gateway expects. pi-ai still sends+ * the key as the provider credential too (x-api-key for Anthropic), which the* gateway overrides when it forwards to the upstream provider.*/import type { Model } from '@earendil-works/pi-ai'+import { gatewayAuthHeader } from '@posthog/agent-shared'+import { resolveModel } from './pi-client'export interface AiGatewayModelOpts {@@ -64,7 +67,7 @@ export function posthogAiGatewayModel(opts: AiGatewayModelOpts): Model<string> {baseUrl: gatewayBaseUrlForApi(native.api, opts.baseUrl),headers: {...native.headers,- Authorization: `Bearer ${opts.apiKey}`,+ ...gatewayAuthHeader(opts.apiKey),},}}diff --git a/products/agent_platform/services/agent-runner/src/workers/worker.ts b/products/agent_platform/services/agent-runner/src/workers/worker.tsindex 914e03563efe..5d02c417b58d 100644--- a/products/agent_platform/services/agent-runner/src/workers/worker.ts+++ b/products/agent_platform/services/agent-runner/src/workers/worker.ts@@ -499,11 +499,15 @@ export class Worker {log: (level, msg, meta) => sLog[level](meta ?? {}, msg),}): undefined- // Bind the connection resolver to this session's team.+ // Scope connection resolution to this session's team AND the spec+ // author (`created_by_id`): a connection resolves only if the+ // installation belongs to the spec's author, so no authoring path can+ // make the runner hand out a credential the author doesn't own. This is+ // the IDOR boundary; a null author fails closed.const mcpConnections = this.deps.mcpConnections? {resolve: (connectionId: string) =>- this.deps.mcpConnections!.resolve(connectionId, session.team_id),+ this.deps.mcpConnections!.resolve(connectionId, session.team_id, rev.created_by_id),}: undefinedconst opened = await openMcpClients(rev.spec.mcps, {diff --git a/products/agent_platform/services/agent-shared/.gitignore b/products/agent_platform/services/agent-shared/.gitignoreindex 83631f817f87..20b35bdd7d6e 100644--- a/products/agent_platform/services/agent-shared/.gitignore+++ b/products/agent_platform/services/agent-shared/.gitignore@@ -1,3 +1,5 @@dist/node_modules/*.tsbuildinfo+.coherence-out/+.coherence/diff --git a/products/agent_platform/services/agent-shared/coherence.config.json b/products/agent_platform/services/agent-shared/coherence.config.jsonnew file mode 100644index 000000000000..2c5ed58c551f--- /dev/null+++ b/products/agent_platform/services/agent-shared/coherence.config.json@@ -0,0 +1,10 @@+{+ "outputDir": ".coherence-out",+ "entryDir": "src",+ "ignore": ["node_modules", "dist", ".coherence-out"],+ "codeExt": ["ts"],+ "typecheck": ["npx", "tsc", "--noEmit", "-p", "."],+ "test": ["npx", "vitest", "run", "-t"],+ "testMatch": "[1-9][0-9]* passed",+ "language": "typescript"+}diff --git a/products/agent_platform/services/agent-shared/src/index.ts b/products/agent_platform/services/agent-shared/src/index.tsindex 05f92a4cf80b..7151250f2b76 100644--- a/products/agent_platform/services/agent-shared/src/index.ts+++ b/products/agent_platform/services/agent-shared/src/index.ts@@ -17,9 +17,11 @@ export * from './spec/slack-manifest'export * from './spec/summarize-conversation'export * from './spec/tool'export * from './spec/custom-tool'+export * from './spec/tool-approval'export * from './spec/framework-preamble'export * from './spec/system-prompt'export * from './spec/trigger-secrets'+export * from './spec/trigger-routes'export * from './storage/bundle'export * from './storage/s3-bundle-store'@@ -30,6 +32,7 @@ export * from './persistence/revision-store'export * from './persistence/identity-store'export * from './persistence/identity-admin-store'export * from './persistence/approval-store'+export * from './persistence/session-state-reaper'export * from './persistence/approval-decision'export * from './persistence/create-pool'export * from './persistence/pg-queue'@@ -70,6 +73,7 @@ export * from './runtime/team-api-key-resolver'export * from './runtime/mcp-connection-store'export * from './runtime/gateway-catalog'export * from './runtime/gateway-client'+export * from './runtime/gateway-wire'export * from './runtime/failure-notifier'export * from './runtime/http-client'export * from './runtime/internal-jwt'diff --git a/products/agent_platform/services/agent-shared/src/persistence/Persistence.spec.md b/products/agent_platform/services/agent-shared/src/persistence/Persistence.spec.mdnew file mode 100644index 000000000000..cae7027bbc78--- /dev/null+++ b/products/agent_platform/services/agent-shared/src/persistence/Persistence.spec.md@@ -0,0 +1,23 @@+# Persistence++Postgres-backed stores for the agent runtime, including the approval-gated tool-call store. Approval authority (who may clear a gated call) and the wire shape the console/ingress consume are resolved here through a single owner.++## invariants++- approval-authority-totality+- approval-wire-resolved+- approval-state-vocabulary++## works when++- typechecks+- boundary "approval-authority-totality" at effectiveApprovalType via test "approval-authority totality"+- boundary "approval-wire-resolved" at serializeApprovalRequest+- passes test "resolves a legacy approvers"+- boundary "approval-state-vocabulary" at APPROVAL_REQUEST_STATES via test "spec generated artifacts"++## why++approval-authority-totality: `effectiveApprovalType` decides WHO may clear a gated tool call — `principal` (the end user, weaker gate) or `agent` (the owner via console, stronger gate). Recognition of a concrete authority is derived from `ApprovalTypeSchema` (not a hardcoded `=== 'agent' || === 'principal'`), so a new authority added to the enum is honored instead of silently downgrading to the weakest gate. The oracle enumerates `ApprovalTypeSchema.options` — the same source that defines the vocabulary — and asserts each round-trips, with a floor so it can't pass vacuously if the projection collapses.+approval-wire-resolved: every surface that gates on approval authority (janitor read routes, the runner's `approval_required` SSE frame, the ingress decision API) must consume a resolved `approver_scope.type`, never the raw legacy `approvers[]` shape. `serializeApprovalRequest` is the single serializer that resolves it via `effectiveApprovalType`; a hand-rolled copy that returned the scope raw had drifted and left legacy rows with an undefined type. The oracle asserts a legacy scope is resolved (not passed raw), which is the contract the Django decide gate trusts — and the gate keeps a one-line legacy fallback so the decode stays correct regardless of janitor/Django deploy order.+approval-state-vocabulary: the runner writes `APPROVAL_REQUEST_STATES` strings into `agent_tool_approval_request.state`, and the Django side's DRF `choices` and DB `CheckConstraint` derive from the emitted `approval_request_states.generated.json` — one authored home, so a new state can't be rejected by a drifted CHECK at insert time. The freshness oracle welds the checked-in artifact to this constant; moving the live DB constraint still requires a deploy-ordered Django migration (widen before the runner writes a new state), which Django's missing-migration CI check forces whenever this list changes.diff --git a/products/agent_platform/services/agent-shared/src/persistence/approval-scope-totality.test.ts b/products/agent_platform/services/agent-shared/src/persistence/approval-scope-totality.test.tsnew file mode 100644index 000000000000..7d00bc8d4a22--- /dev/null+++ b/products/agent_platform/services/agent-shared/src/persistence/approval-scope-totality.test.ts@@ -0,0 +1,21 @@+import { describe, expect, it } from 'vitest'++import { ApprovalTypeSchema } from '../spec/spec'+import { effectiveApprovalType } from './approval-store'++describe('approval-authority totality', () => {+ it('every concrete ApprovalType round-trips (no silent downgrade)', () => {+ // Floor: an empty domain would pass vacuously — fail loud if the+ // vocabulary projection ever collapses.+ expect(ApprovalTypeSchema.options.length).toBeGreaterThanOrEqual(2)+ for (const type of ApprovalTypeSchema.options) {+ const resolved = effectiveApprovalType({ type, allow_edit: false })+ expect(resolved, `authority "${type}" must resolve to itself, not the default gate`).toBe(type)+ }+ })++ it('a legacy team_admins scope resolves to the owner gate (agent)', () => {+ const legacy = { approvers: ['team_admins'] } as never+ expect(effectiveApprovalType(legacy)).toBe('agent')+ })+})diff --git a/products/agent_platform/services/agent-shared/src/persistence/approval-store.test.ts b/products/agent_platform/services/agent-shared/src/persistence/approval-store.test.tsindex 2db5f9b979c3..a6acedb38da3 100644--- a/products/agent_platform/services/agent-shared/src/persistence/approval-store.test.ts+++ b/products/agent_platform/services/agent-shared/src/persistence/approval-store.test.ts@@ -4,7 +4,14 @@ import { Pool } from 'pg'import { reset } from '@posthog/agent-shared/testing'import { AssistantMessageRecord } from '../spec/spec'-import { ApprovalStore, effectiveApprovalType, hashCanonicalArgs, UpsertApprovalRequestInput } from './approval-store'+import {+ ApprovalRequest,+ ApprovalStore,+ effectiveApprovalType,+ hashCanonicalArgs,+ serializeApprovalRequest,+ UpsertApprovalRequestInput,+} from './approval-store'import { PgApprovalStore } from './pg-approval-store'describe('effectiveApprovalType', () => {@@ -19,6 +26,39 @@ describe('effectiveApprovalType', () => {})})+describe('serializeApprovalRequest wire shape', () => {+ const rowWithScope = (approver_scope: unknown): ApprovalRequest => ({+ id: 'a',+ session_id: 's',+ application_id: 'app',+ team_id: 1,+ revision_id: 'r',+ turn: 0,+ tool_call_id: 'tc',+ tool_name: 'tool',+ proposed_args: {},+ args_hash: Buffer.alloc(0),+ assistant_message: { role: 'assistant', content: [], timestamp: 0 } as AssistantMessageRecord,+ approver_scope: approver_scope as ApprovalRequest['approver_scope'],+ state: 'queued',+ decision_by: null,+ decision_at: null,+ decision_reason: null,+ decided_args: null,+ dispatch_outcome: null,+ created_at: 't',+ expires_at: 't',+ })++ // The serializer must resolve the type, not pass the scope raw: a raw legacy+ // scope reaches the console with an undefined type and the decide gate 404s a+ // decidable owner approval.+ it('resolves a legacy approvers[] scope to a concrete type and drops the raw approvers', () => {+ const out = serializeApprovalRequest(rowWithScope({ approvers: ['team_admins'], allow_edit: false }))+ expect(out.approver_scope).toEqual({ type: 'agent', allow_edit: false })+ })+})+const TEST_DB_URL =process.env.AGENT_TEST_DB_URL ?? 'postgres://posthog:posthog@localhost:5432/agent_runtime_queue_test'diff --git a/products/agent_platform/services/agent-shared/src/persistence/approval-store.ts b/products/agent_platform/services/agent-shared/src/persistence/approval-store.tsindex 83f32d81f487..54ada6f9180f 100644--- a/products/agent_platform/services/agent-shared/src/persistence/approval-store.ts+++ b/products/agent_platform/services/agent-shared/src/persistence/approval-store.ts@@ -15,9 +15,22 @@import { createHash } from 'node:crypto'-import { ApprovalType, AssistantMessageRecord } from '../spec/spec'+import { ApprovalType, ApprovalTypeSchema, AssistantMessageRecord, legacyApproversToApprovalType } from '../spec/spec'-export type ApprovalRequestState = 'queued' | 'approving' | 'dispatched' | 'dispatched_failed' | 'rejected' | 'expired'+/**+ * Source of truth for the approval-request state vocabulary: Django's DRF+ * `choices` and the DB `CheckConstraint` derive from the emitted JSON (see+ * `spec/spec-codegen.ts`), not a hand-copy. Lifecycle order; terminal last.+ */+export const APPROVAL_REQUEST_STATES = [+ 'queued',+ 'approving',+ 'dispatched',+ 'dispatched_failed',+ 'rejected',+ 'expired',+] as const+export type ApprovalRequestState = (typeof APPROVAL_REQUEST_STATES)[number]export interface ApprovalRequest {id: string@@ -53,21 +66,21 @@ export interface ApprovalRequest {/*** Effective approval authority for a stored row. New rows carry `type`; rows* queued before the principal/agent rebuild carry the legacy `approvers[]`- * scope with no `type`, so `scope.type` is `undefined` on them. Map a legacy- * `team_admins` scope → `agent` so an in-flight old row stays gated to the- * console (and isn't mistaken for a principal request) for its whole TTL during- * the migration window. Mirrors the Django `approvals_decide` fallback — every- * surface that gates on type MUST resolve through this, not read `.type` raw.+ * scope with no `type`, so `scope.type` is `undefined` on them. Every surface+ * that gates on type MUST resolve through this, not read `.type` raw.+ *+ * Uses `ApprovalTypeSchema` (not a hardcoded check) so a new enum authority isn't+ * silently downgraded to the weakest gate; legacy rows map via+ * `legacyApproversToApprovalType`; last-resort `principal` mirrors Django's+ * `approvals_decide` fallback.*/export function effectiveApprovalType(scope: ApprovalRequest['approver_scope']): ApprovalType {const s = scope as unknown as { type?: unknown; approvers?: unknown }- if (s.type === 'agent' || s.type === 'principal') {- return s.type- }- if (Array.isArray(s.approvers) && s.approvers.includes('team_admins')) {- return 'agent'+ const parsed = ApprovalTypeSchema.safeParse(s.type)+ if (parsed.success) {+ return parsed.data}- return 'principal'+ return legacyApproversToApprovalType(s.approvers) ?? 'principal'}/**diff --git a/products/agent_platform/services/agent-shared/src/persistence/session-state-reaper.test.ts b/products/agent_platform/services/agent-shared/src/persistence/session-state-reaper.test.tsnew file mode 100644index 000000000000..5e186145185b--- /dev/null+++ b/products/agent_platform/services/agent-shared/src/persistence/session-state-reaper.test.ts@@ -0,0 +1,30 @@+import { describe, expect, it } from 'vitest'++import { LIVE_SESSION_STATES } from './queue'+import { isFinalSessionState, SESSION_STATE_REAPER } from './session-state-reaper'++/**+ * Cross-checks the compile-time classification against `queue.ts`: a state the+ * queue considers LIVE must have a forward path (never `final`, else it wedges),+ * and the `final` set is exactly the lifecycle-final states.+ */+describe('session-state reaper classification', () => {+ it('every live state (per queue.ts) has a forward path, never final', () => {+ const wrongly_final = LIVE_SESSION_STATES.filter((s) => SESSION_STATE_REAPER[s] === 'final')+ expect(wrongly_final, `live states marked final (would wedge): ${wrongly_final.join(', ')}`).toEqual([])+ })++ it('final states are exactly the lifecycle-final states', () => {+ const final = (Object.keys(SESSION_STATE_REAPER) as (keyof typeof SESSION_STATE_REAPER)[])+ .filter((s) => isFinalSessionState(s))+ .sort()+ expect(final).toEqual(['cancelled', 'closed', 'failed'])+ })++ it('completed is reaped, not final (open-but-idle → swept closed)', () => {+ // The exact disagreement guarded against: queue.ts counts `completed` as+ // not-live, but it must NOT be final here — the sweep still closes it.+ expect(isFinalSessionState('completed')).toBe(false)+ expect(SESSION_STATE_REAPER.completed).toBe('sweep-closes')+ })+})diff --git a/products/agent_platform/services/agent-shared/src/persistence/session-state-reaper.ts b/products/agent_platform/services/agent-shared/src/persistence/session-state-reaper.tsnew file mode 100644index 000000000000..13492c3ef8e6--- /dev/null+++ b/products/agent_platform/services/agent-shared/src/persistence/session-state-reaper.ts@@ -0,0 +1,29 @@+/**+ * Classifies the reaper for every `SessionState` — the process that moves a state+ * forward even if the holder dies, so a session can't wedge. Keying the `Record`+ * on the union makes a new state a compile error until it's classified.+ *+ * `final` differs from `queue.ts`'s "terminal" (= not live): `completed` is not+ * live yet not final (the sweep closes it), so it's `sweep-closes`.+ *+ * final — lifecycle-final (closed/cancelled/failed); no reaper needed.+ * worker-claims — a runner Worker claims it off the queue and advances it.+ * sweep-requeues — janitor sweep re-queues it if the worker died holding it.+ * sweep-closes — janitor sweep advances it to a final state when idle.+ */+import type { SessionState } from '../spec/spec'++export type ReaperKind = 'final' | 'worker-claims' | 'sweep-requeues' | 'sweep-closes'++export const SESSION_STATE_REAPER: Record<SessionState, ReaperKind> = {+ queued: 'worker-claims',+ running: 'sweep-requeues',+ completed: 'sweep-closes',+ closed: 'final',+ cancelled: 'final',+ failed: 'final',+}++export function isFinalSessionState(s: SessionState): boolean {+ return SESSION_STATE_REAPER[s] === 'final'+}diff --git a/products/agent_platform/services/agent-shared/src/runtime/Runtime.spec.md b/products/agent_platform/services/agent-shared/src/runtime/Runtime.spec.mdnew file mode 100644index 000000000000..b33a8675304c--- /dev/null+++ b/products/agent_platform/services/agent-shared/src/runtime/Runtime.spec.md@@ -0,0 +1,39 @@+# Runtime++Cross-process runtime services shared by the agent node services: event bus, log sink, per-leaf encryption, the team API-key resolver, and the MCP connection store that mints shared-credential bearers.++## invariants++- connection-owner-isolation+- connection-bearer-single-reader+- team-api-key-isolation+- django-fernet-interop+- gateway-wire-single-source+- gateway-cost-provenance+- direct-http-capability-divide++## works when++- typechecks+- boundary "connection-owner-isolation" at PgMcpConnectionStore+- passes test "cannot return owner B"+- boundary "connection-bearer-single-reader" at PgMcpConnectionStore via guard "reads of sensitive_configuration are confined"+- boundary "team-api-key-isolation" at PgTeamApiKeyResolver+- passes test "returns only its own api_token"+- boundary "django-fernet-interop" at EncryptedFields+- passes test "urlsafe regression"+- boundary "gateway-wire-single-source" at extractGatewayRequestId+- passes test "request id single-sourcing"+- boundary "gateway-cost-provenance" at assertGatewayProvenance+- passes test "cost provenance guard"+- boundary "direct-http-capability-divide" at DirectHttpClient via guard "does NOT accept a proxyUrl in its options"++## why++connection-owner-isolation: a shared MCP connection's stored bearer belongs to the spec author (`agent_revision.created_by_id`). resolve scopes the lookup to (installation, team, owner) so no authoring path can hand a credential to a non-owner — enforced at the runtime chokepoint every session crosses, not at spec-write (which is routable-around). The oracle runs the real exported SQL against real Postgres with two owners, because a fake-pool test only proves the param is passed, not that the predicate filters.+connection-bearer-single-reader: the owner check is complete only if the store is the sole reader of the credential column, so the oracle confirms no other module reads it and the chokepoint can't be bypassed.+team-api-key-isolation: the resolver's `phc_` lookup is the team's bearer to PostHog services; dropping or inverting the `WHERE id = $1` predicate mints a sibling team's token (cross-tenant billing/attribution) while every fake-pool unit test stays green. The oracle runs the real exported `SELECT_TEAM_API_TOKEN` against real Postgres with two teams.+django-fernet-interop: the runner decrypts what Django's `EncryptedTextField` wrote, so key derivation must match Django's urlsafe-base64 form exactly — standard base64 differs only for salt keys whose encoding contains `+`/`/`, and that divergence fails silently (every decrypt of Django ciphertext breaks for that key, with nothing wrong at rest). The oracle decrypts real Django-written ciphertext, including a key that exercises the urlsafe divergence.+gateway-wire-single-source: the runner↔ai-gateway contract (auth header shape, the response header carrying the gateway's settlement id, the usage-lookup path built from that id) is declared once in `gateway-wire.ts` and imported by dispatch, catalog, and the settled-cost lookup — the same symbol on both sides, so keying settlement by the wrong id or drifting the header shape is unrepresentable rather than remembered. The oracle drives a stubbed gateway end-to-end and asserts the id dispatch received is the id the cost lookup keys on.+gateway-cost-provenance: cost figures on analytics generation events must come from gateway-settled usage, never local estimates — `GatewaySettledCost` carries a literal `source: 'gateway'` and `assertGatewayProvenance` backstops it at `buildAnalyticsProperties`, the single funnel both sinks route every event through, dropping-and-logging a forged or unsourced cost instead of emitting it.+direct-http-capability-divide: two HTTP clients exist deliberately separate. `HttpClient` is proxy-bound (smokescreen in prod) and is the only client agent-influenced code can reach — `ToolContext.http` is typed `HttpFetcher` and every non-test construction site hands it an `HttpClient`. `DirectHttpClient` carries no proxy dispatcher at all and is reserved for cluster-internal calls the platform makes to itself (`HttpGatewayClient`, the PostHog introspector); it must never be threaded onto `ToolContext` or a runner `WorkerDeps` — a NO_PROXY-style hostname allowlist would defeat the divide (an `@posthog/http-request` call against an in-cluster `*.svc.cluster.local` hostname would match a suffix rule and bypass smokescreen entirely), so the class identity itself is the capability, not a runtime check. Bare global `fetch` is lint-banned across `services/agent-*/src` (`no-restricted-globals` in `.oxlintrc.json`) because Node's built-in `fetch` ignores `HTTP_PROXY`/`HTTPS_PROXY` and would silently skip both clients. The oracle pins the half of the divide that's actually executable: `DirectHttpClient`'s constructor has no `proxyUrl` option (a compile-time `@ts-expect-error` on the options type), so there is no escape hatch to wire a proxy onto the internal-only client after the fact.diff --git a/products/agent_platform/services/agent-shared/src/runtime/analytics-sink.test.ts b/products/agent_platform/services/agent-shared/src/runtime/analytics-sink.test.tsindex 2da9b5741837..53fc4914f300 100644--- a/products/agent_platform/services/agent-shared/src/runtime/analytics-sink.test.ts+++ b/products/agent_platform/services/agent-shared/src/runtime/analytics-sink.test.ts@@ -44,7 +44,7 @@ function genEvent(teamId: number, overrides: Partial<AnalyticsEvent> = {}): Analinput_tokens: 10,output_tokens: 5,latency_ms: 1200,- cost_usd: 0.002,+ cost: { source: 'gateway', usd: 0.002 },stop_reason: 'stop',...overrides,} as AnalyticsEventdiff --git a/products/agent_platform/services/agent-shared/src/runtime/analytics-sink.ts b/products/agent_platform/services/agent-shared/src/runtime/analytics-sink.tsindex a6119cf51187..56f2e8020ba0 100644--- a/products/agent_platform/services/agent-shared/src/runtime/analytics-sink.ts+++ b/products/agent_platform/services/agent-shared/src/runtime/analytics-sink.ts@@ -26,6 +26,7 @@import { PostHog } from 'posthog-node'+import { assertGatewayProvenance, type GatewaySettledCost } from './gateway-wire'import { createLogger } from './logger'/**@@ -80,11 +81,11 @@ export interface AnalyticsGenerationEvent extends AnalyticsEventBase {/** Wall-clock duration of the pi-ai call, milliseconds. */latency_ms: number/**- * Total cost in USD. No longer set by the runner — the gateway emits cost on- * the gateway path, and ingestion prices direct-path events from the- * catalog. pi-ai's estimate is never used. Kept on the shape for consumers.+ * Settled cost, when known. Provenance-tagged (see `./gateway-wire`) so a+ * pi-ai/provider estimate can't be assigned without a type error;+ * `buildAnalyticsProperties` also throws on a wrong-provenance value cast in.*/- cost_usd?: number+ cost?: GatewaySettledCost/** pi-ai stopReason — `stop`, `length`, `toolUse`, `error`, `aborted`. */stop_reason?: string/** 0-based index of the model in the policy list that answered. >0 means a fallback. */@@ -211,8 +212,11 @@ export function buildAnalyticsProperties(event: AnalyticsEvent): Record<string,base.$ai_total_tokens = event.total_tokens}base.$ai_latency = event.latency_ms / 1000- if (event.cost_usd !== undefined) {- base.$ai_total_cost_usd = event.cost_usd+ if (event.cost !== undefined) {+ // Throws (caught by the sinks around this call) on anything that+ // isn't a genuine gateway-settled figure — the single choke point+ // that keeps a client-side cost estimate out of analytics.+ base.$ai_total_cost_usd = assertGatewayProvenance(event.cost).usd}if (event.stop_reason) {base.$ai_stop_reason = event.stop_reason@@ -478,7 +482,17 @@ export class RoutingAnalyticsSink implements AnalyticsSink {const resolved = keyByTeam.get(event.team_id) ?? nullconst apiKey = resolved ?? this.opts.fallbackApiKey ?? nullconst eventName = eventNameFor(event)- const properties = buildAnalyticsProperties(event)+ let properties: Record<string, unknown>+ try {+ // Can throw — e.g. the cost-provenance guard rejecting a+ // non-gateway-settled figure. Drop just this event rather than+ // letting a bad property bag reach `tap`/`capture`.+ properties = buildAnalyticsProperties(event)+ } catch (err) {+ this.log.error('dropping event: invalid properties', { event: eventName, error: String(err) })+ dropped+++ continue+ }this.opts.tap?.({ apiKey, eventName, event, properties })if (!apiKey) {dropped++diff --git a/products/agent_platform/services/agent-shared/src/runtime/encryption-interop.test.ts b/products/agent_platform/services/agent-shared/src/runtime/encryption-interop.test.tsnew file mode 100644index 000000000000..5754ce297670--- /dev/null+++ b/products/agent_platform/services/agent-shared/src/runtime/encryption-interop.test.ts@@ -0,0 +1,31 @@+import { describe, expect, it } from 'vitest'++import { EncryptedFields } from './encryption'++// Fixtures decrypt real Django-written ciphertext; `trickyKey`'s base64 contains+// `+`/`/`, the case where standard vs urlsafe base64 derivation diverges.+// Generated by posthog/helpers/encrypted_fields.py's derivation via Python Fernet.+const FIXTURES = {+ safeKey: 'a_very_secret_salt_key_32_bytes!',+ trickyKey: '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~?',+ safeToken:+ 'gAAAAABqREGn3YEj5EgsqDzxxfmwhZKhDHGqjcr0bdhaeEz9qX9zywiVDvcFGyQQticdRN82T1nlrUgfaa1KZ7Wi-GI0srFJQhhqjCCdWqFFs_cOu5WazZw=',+ trickyToken:+ 'gAAAAABqREGnwU9VnjMcO9wcSFIJlWyyEJDnh2aqUSTbgOCWb7mBdPx6aH1KrkErqsBTxXCgUbYdulRXFYl0QYwEVaYWb2JUFHWXFrOS0rAo5FA5XRxXnXQ=',+ leaf3600: 'gAAAAABqREGnsLgiWzBjhTwlT9zdQsgJJPcVZI5CNtHQ2Csxjp7iSx1pGxNbRYg0eFMsNip4BDgaXKgOsJmjx7Zqkj08zN8VQQ==',+} as const++describe('Django ↔ TS encryption interop', () => {+ it('decrypts a Django-written token for a base64-safe salt key', () => {+ expect(new EncryptedFields(FIXTURES.safeKey).decrypt(FIXTURES.safeToken)).toBe('hello-django-secret')+ })++ it('decrypts a Django-written token for a key whose base64 contains +// (urlsafe regression)', () => {+ expect(new EncryptedFields(FIXTURES.trickyKey).decrypt(FIXTURES.trickyToken)).toBe('hello-django-secret')+ })++ it('decrypts a per-leaf JSON-field value (str()-encoded scalar) as Django writes it', () => {+ // Django encodes each scalar leaf as encrypt(str(value)); "3600" comes back as a string.+ expect(new EncryptedFields(FIXTURES.safeKey).decryptJsonFieldValue(FIXTURES.leaf3600)).toBe('3600')+ })+})diff --git a/products/agent_platform/services/agent-shared/src/runtime/encryption.ts b/products/agent_platform/services/agent-shared/src/runtime/encryption.tsindex b322f078850f..c051a1948113 100644--- a/products/agent_platform/services/agent-shared/src/runtime/encryption.ts+++ b/products/agent_platform/services/agent-shared/src/runtime/encryption.ts@@ -15,6 +15,15 @@import { Fernet } from 'fernet-nodejs'+/**+ * Derive a Fernet key exactly as Django does: urlsafe base64, not standard. If a+ * salt key's base64 contains `+`/`/` the two diverge, `fernet-nodejs` rejects the+ * key, and the runner can't decrypt Django's ciphertext.+ */+function toFernetKey(saltKey: string): string {+ return Buffer.from(saltKey, 'utf-8').toString('base64').replace(/\+/g, '-').replace(/\//g, '_')+}+export class EncryptedFields {private readonly fernets: Fernet[]@@ -30,7 +39,7 @@ export class EncryptedFields {if (keys.length === 0) {throw new Error('EncryptedFields: no keys configured (set ENCRYPTION_SALT_KEYS to a 32-byte UTF-8 string)')}- this.fernets = keys.map((k) => new Fernet(Buffer.from(k, 'utf-8').toString('base64')))+ this.fernets = keys.map((k) => new Fernet(toFernetKey(k)))}encrypt(value: string): string {diff --git a/products/agent_platform/services/agent-shared/src/runtime/gateway-catalog.ts b/products/agent_platform/services/agent-shared/src/runtime/gateway-catalog.tsindex 6684783a31b0..f6bae9eae844 100644--- a/products/agent_platform/services/agent-shared/src/runtime/gateway-catalog.ts+++ b/products/agent_platform/services/agent-shared/src/runtime/gateway-catalog.ts@@ -10,6 +10,7 @@*/import { MODEL_POLICY_LEVELS, type ModelEntry, type ModelPolicy, type ModelLevel } from '../spec/spec'+import { gatewayAuthHeader } from './gateway-wire'import type { HttpFetcher } from './http-client'import { createLogger } from './logger'@@ -307,7 +308,7 @@ export class HttpGatewayCatalog implements GatewayCatalog {private async fetchModels(): Promise<CatalogModel[]> {const headers: Record<string, string> = { Accept: 'application/json' }if (this.bearer) {- headers.Authorization = `Bearer ${this.bearer}`+ Object.assign(headers, gatewayAuthHeader(this.bearer))}const res = await this.http.fetch(`${this.baseUrl}/models`, {method: 'GET',diff --git a/products/agent_platform/services/agent-shared/src/runtime/gateway-client.test.ts b/products/agent_platform/services/agent-shared/src/runtime/gateway-client.test.tsindex 5322373fc3bb..f1dc98b487e2 100644--- a/products/agent_platform/services/agent-shared/src/runtime/gateway-client.test.ts+++ b/products/agent_platform/services/agent-shared/src/runtime/gateway-client.test.ts@@ -1,4 +1,13 @@+import { type AnalyticsGenerationEvent, buildAnalyticsProperties } from './analytics-sink'import { HttpGatewayClient } from './gateway-client'+import {+ assertGatewayProvenance,+ extractGatewayRequestId,+ GATEWAY_REQUEST_ID_HEADER,+ gatewayAuthHeader,+ gatewaySettledCost,+ gatewayUsagePath,+} from './gateway-wire'import type { HttpFetcher } from './http-client'// Minimal fetch stub: queue of {status, body} responses returned in@@ -170,3 +179,122 @@ describe('HttpGatewayClient.getWalletBalance', () => {}})})++describe('gateway-wire: request id single-sourcing (dispatch -> settled-cost lookup)', () => {+ it.each([+ { minted: 'gw-req-a1b2c3', clientChosen: 'agent:sess-1:1:11111111-1111-1111-1111-111111111111' },+ { minted: 'gw-req-z9y8x7', clientChosen: 'agent:sess-2:4:22222222-2222-2222-2222-222222222222' },+ ])(+ 'keys the settled-cost lookup on the gateway-minted id ($minted), never the dispatch-side id ($clientChosen)',+ async ({ minted, clientChosen }) => {+ // The gateway ignores the client-sent id (e.g. Idempotency-Key) and+ // returns its own settlement id in a response header.+ const dispatchResponseHeaders: Record<string, string | undefined> = {+ [GATEWAY_REQUEST_ID_HEADER]: minted,+ 'idempotency-key': clientChosen,+ }+ const extractedId = extractGatewayRequestId(dispatchResponseHeaders)+ expect(extractedId).toBe(minted)++ const { http, calls, restore } = installFetch([+ { status: 200, body: { request_id: minted, team_id: 1, cost_usd: '0.01', settled_at: '' } },+ ])+ try {+ const client = new HttpGatewayClient({ baseUrl: 'http://gw/v1', http })+ const usage = await client.getUsage(extractedId!, { phc: 'phc_test' })++ // Driven through the public `getUsage` API with the id+ // `extractGatewayRequestId` produced — the lookup URL is built+ // from that same id via `gatewayUsagePath`, never the+ // client-chosen one.+ expect(calls).toHaveLength(1)+ expect(calls[0].url).toBe(`http://gw/v1${gatewayUsagePath(minted)}`)+ expect(calls[0].url).not.toContain(clientChosen)+ expect(usage?.request_id).toBe(minted)+ } finally {+ restore()+ }+ }+ )++ it('extracts nothing when the gateway never stamped the header — never falls back to a client-chosen id', () => {+ expect(extractGatewayRequestId({})).toBeUndefined()+ expect(extractGatewayRequestId({ 'idempotency-key': 'agent:sess:1:nonce' })).toBeUndefined()+ })++ it.each(['phc_abc123', 'phs_project-secret'])(+ 'getUsage authenticates with exactly what gatewayAuthHeader builds for %s',+ async (token) => {+ const { http, calls, restore } = installFetch([+ { status: 200, body: { request_id: 'x', team_id: 0, cost_usd: '0', settled_at: '' } },+ ])+ try {+ const client = new HttpGatewayClient({ baseUrl: 'http://gw/v1', http })+ await client.getUsage('x', { phc: token })+ expect(calls[0].authorization).toBe(gatewayAuthHeader(token).Authorization)+ } finally {+ restore()+ }+ }+ )+})++describe('gateway-wire: cost provenance guard', () => {+ it.each([+ ['0.42', 0.42],+ ['0', 0],+ ['1234.5678', 1234.5678],+ ])('gatewaySettledCost tags a finite wire value (%s) as gateway-settled', (wire, expected) => {+ expect(gatewaySettledCost({ cost_usd: wire })).toEqual({ source: 'gateway', usd: expected })+ })++ it.each(['not-a-number', 'NaN', 'Infinity'])(+ 'gatewaySettledCost returns null for a non-finite wire value (%s)',+ (wire) => {+ expect(gatewaySettledCost({ cost_usd: wire })).toBeNull()+ }+ )++ it('accepts a genuinely gateway-settled cost', () => {+ expect(assertGatewayProvenance({ source: 'gateway', usd: 0.1 })).toEqual({ source: 'gateway', usd: 0.1 })+ })++ it.each([+ { source: 'pi_estimate', usd: 0.5 },+ { source: 'client_side', usd: 1 },+ { source: undefined, usd: 2 },+ { source: 'gateway', usd: Number.NaN },+ { source: 'gateway', usd: 'not-a-number' },+ ])('rejects a non-gateway-provenance cost (source=$source, usd=$usd)', ({ source, usd }) => {+ expect(() => assertGatewayProvenance({ source, usd })).toThrow(/non-gateway/)+ })++ it('the single analytics emission point (buildAnalyticsProperties) drops a forged non-gateway cost with an error, not silently', () => {+ const baseEvent: Omit<AnalyticsGenerationEvent, 'cost'> = {+ kind: 'generation',+ ts: '2026-06-10T00:00:00.000Z',+ team_id: 1,+ application_id: 'app_1',+ revision_id: 'rev_1',+ session_id: 'sess_1',+ turn: 1,+ span_id: 'sess_1:gen:1',+ distinct_id: 'agent:app_1',+ model: 'anthropic/claude-haiku-4-5',+ provider: 'anthropic',+ input: [],+ output: [],+ input_tokens: 1,+ output_tokens: 1,+ latency_ms: 10,+ }+ // A pi-ai estimate forged into the branded slot via a cast — the only way+ // this can resurface once the type blocks a plain literal. The runtime+ // guard must still catch it.+ const forged = { ...baseEvent, cost: { source: 'pi_estimate', usd: 99 } } as unknown as AnalyticsGenerationEvent+ expect(() => buildAnalyticsProperties(forged)).toThrow(/non-gateway/)++ const legitimate: AnalyticsGenerationEvent = { ...baseEvent, cost: { source: 'gateway', usd: 0.03 } }+ expect(buildAnalyticsProperties(legitimate).$ai_total_cost_usd).toBe(0.03)+ })+})diff --git a/products/agent_platform/services/agent-shared/src/runtime/gateway-client.ts b/products/agent_platform/services/agent-shared/src/runtime/gateway-client.tsindex 59d9c1800ab8..7aaff1f72475 100644--- a/products/agent_platform/services/agent-shared/src/runtime/gateway-client.ts+++ b/products/agent_platform/services/agent-shared/src/runtime/gateway-client.ts@@ -8,6 +8,7 @@* per-team via `TeamApiKeyResolver`).*/+import { gatewayAuthHeader, gatewayUsagePath } from './gateway-wire'import type { HttpFetcher } from './http-client'import { createLogger } from './logger'@@ -99,7 +100,7 @@ export class HttpGatewayClient implements GatewayClient {// makes the lookup miss against ledger rows whose reference_id// contains literal colons. Our id format (`agent:<uuid>:<turn>`)// is path-safe — only `:` and hex with dashes.- const res = await this.fetchJson(`/usage/${requestId}`, opts.phc)+ const res = await this.fetchJson(gatewayUsagePath(requestId), opts.phc)if (res.kind === 'ok') {return res.body as GatewayUsage}@@ -141,7 +142,7 @@ export class HttpGatewayClient implements GatewayClient {const timer = setTimeout(() => ac.abort(), this.timeoutMs)try {const res = await this.http.fetch(`${this.baseUrl}${path}`, {- headers: { Authorization: `Bearer ${phc}` },+ headers: gatewayAuthHeader(phc),signal: ac.signal,})if (res.status === 200) {diff --git a/products/agent_platform/services/agent-shared/src/runtime/gateway-wire.ts b/products/agent_platform/services/agent-shared/src/runtime/gateway-wire.tsnew file mode 100644index 000000000000..82dbf4738637--- /dev/null+++ b/products/agent_platform/services/agent-shared/src/runtime/gateway-wire.ts@@ -0,0 +1,88 @@+/**+ * Single-sourced runner ↔ ai-gateway wire contract. Every caller (usage/wallet+ * client, model catalog, runner dispatch) must agree on three facts, each of+ * which shipped as a bug when re-derived independently:+ * - auth: the gateway reads only `Authorization: Bearer` (an `x-api-key`-only+ * provider shape 401s).+ * - settlement id: key the settled-cost lookup on the gateway's server-minted+ * id, not a client-chosen one, or the `/usage` lookup 404s forever.+ * - cost provenance: only a figure parsed from a `/usage` response is billed.+ */++import type { GatewayUsage } from './gateway-client'++/**+ * Every gateway surface authenticates the same way. Build the header through+ * this, not inline `Bearer ${token}`, so a provider's own wire shape can't+ * reintroduce the `x-api-key` 401.+ */+export function gatewayAuthHeader(token: string): { Authorization: string } {+ return { Authorization: `Bearer ${token}` }+}++/**+ * Response header carrying the gateway's server-minted settlement id (never the+ * caller's Idempotency-Key). Both dispatch and the settled-cost lookup import+ * this constant so they can't drift onto two ideas of "the request id".+ */+export const GATEWAY_REQUEST_ID_HEADER = 'x-request-id'++/**+ * Safe charset for the settlement id before it's interpolated into the authed+ * `GET /v1/usage/{id}` path. Server-minted, so this is defense-in-depth: a `/`,+ * `?`, whitespace or control char must not reshape the URL.+ */+const GATEWAY_REQUEST_ID_PATTERN = /^[A-Za-z0-9._-]+$/++/**+ * Pull the gateway's settlement id off response headers. Returns `undefined` if+ * absent or failing the charset check — callers must skip the settled-cost+ * fetch, never fall back to a locally-chosen id.+ */+export function extractGatewayRequestId(headers: Record<string, string | undefined>): string | undefined {+ const id = headers[GATEWAY_REQUEST_ID_HEADER]+ return id && GATEWAY_REQUEST_ID_PATTERN.test(id) ? id : undefined+}++/**+ * Settled-usage lookup path. Takes the id from `extractGatewayRequestId` — never+ * a client-chosen id — so dispatch and lookup build the same URL.+ */+export function gatewayUsagePath(requestId: string): string {+ return `/usage/${requestId}`+}++/**+ * A provably gateway-settled cost — the only kind reportable as billed. The+ * `source: 'gateway'` literal blocks assigning a provider estimate without a+ * type error; only `gatewaySettledCost` produces one.+ */+export interface GatewaySettledCost {+ readonly source: 'gateway'+ readonly usd: number+}++/**+ * Parse a settled-usage response into a provenance-tagged cost; `null` if+ * absent/blank/non-numeric/negative. Blank matters because `Number('') === 0`+ * would settle as a real $0; negatives aren't settlements we model.+ */+export function gatewaySettledCost(usage: Pick<GatewayUsage, 'cost_usd'>): GatewaySettledCost | null {+ if (typeof usage.cost_usd === 'string' && usage.cost_usd.trim() === '') {+ return null+ }+ const usd = Number(usage.cost_usd)+ return Number.isFinite(usd) && usd >= 0 ? { source: 'gateway', usd } : null+}++/**+ * The single point deciding whether a cost may reach analytics. Throws on+ * anything not `source: 'gateway'` with finite non-negative `usd` — including a+ * cast-in object — so the pi-estimate leak can't return. Sinks catch around it.+ */+export function assertGatewayProvenance(cost: { source?: unknown; usd?: unknown }): GatewaySettledCost {+ if (cost.source !== 'gateway' || typeof cost.usd !== 'number' || !Number.isFinite(cost.usd) || cost.usd < 0) {+ throw new Error(`gateway-wire: refusing non-gateway cost provenance (source=${String(cost.source)})`)+ }+ return { source: 'gateway', usd: cost.usd }+}diff --git a/products/agent_platform/services/agent-shared/src/runtime/mcp-connection-boundary.test.ts b/products/agent_platform/services/agent-shared/src/runtime/mcp-connection-boundary.test.tsnew file mode 100644index 000000000000..3a38b5905e50--- /dev/null+++ b/products/agent_platform/services/agent-shared/src/runtime/mcp-connection-boundary.test.ts@@ -0,0 +1,39 @@+import { readdirSync, readFileSync, statSync } from 'node:fs'+import { dirname, join, relative } from 'node:path'+import { fileURLToPath } from 'node:url'+import { describe, expect, it } from 'vitest'++/**+ * The owner-scoped `resolve` is the IDOR boundary only if it's the sole reader of+ * `sensitive_configuration`. This fails the build if any non-test file other than+ * the connection store references that column.+ */+const SRC_ROOT = join(dirname(fileURLToPath(import.meta.url)), '..')+const ALLOWED = ['runtime/mcp-connection-store.ts']++function nonTestSourcesReferencing(token: string): string[] {+ const out: string[] = []+ const walk = (dir: string): void => {+ for (const name of readdirSync(dir)) {+ const p = join(dir, name)+ if (statSync(p).isDirectory()) {+ walk(p)+ continue+ }+ if (!p.endsWith('.ts') || p.endsWith('.test.ts')) {+ continue+ }+ if (readFileSync(p, 'utf-8').includes(token)) {+ out.push(relative(SRC_ROOT, p))+ }+ }+ }+ walk(SRC_ROOT)+ return out.sort()+}++describe('connection-bearer chokepoint (no second reader)', () => {+ it('reads of sensitive_configuration are confined to the owner-scoped store', () => {+ expect(nonTestSourcesReferencing('sensitive_configuration')).toEqual(ALLOWED)+ })+})diff --git a/products/agent_platform/services/agent-shared/src/runtime/mcp-connection-store.sql.test.ts b/products/agent_platform/services/agent-shared/src/runtime/mcp-connection-store.sql.test.tsnew file mode 100644index 000000000000..55f188cc5aea--- /dev/null+++ b/products/agent_platform/services/agent-shared/src/runtime/mcp-connection-store.sql.test.ts@@ -0,0 +1,60 @@+import { Pool, type PoolClient } from 'pg'+import { afterAll, beforeAll, describe, expect, it } from 'vitest'++import { SELECT_INSTALLATION } from './mcp-connection-store'++/**+ * The fake-pool unit test only asserts `resolve` passes the owner param, not that+ * the query filters on it — drop `AND i.user_id` and the IDOR reopens while unit+ * tests stay green. This runs the real `SELECT_INSTALLATION` against Postgres+ * with two owners to catch that.+ */+const TEST_DB_URL =+ process.env.AGENT_TEST_DB_URL ?? 'postgres://posthog:posthog@localhost:5432/agent_runtime_queue_test'++const TEAM = 1+const OWNER_A = 100+const OWNER_B = 200++describe('SELECT_INSTALLATION owner isolation (real SQL)', () => {+ let pool: Pool+ let client: PoolClient // one connection — temp tables are session-scoped++ beforeAll(async () => {+ pool = new Pool({ connectionString: TEST_DB_URL, max: 1 })+ client = await pool.connect()+ // Temp tables shadow the real mcp_store_* tables for this session only —+ // no schema/migration dependency, auto-dropped on disconnect.+ await client.query(`+ CREATE TEMP TABLE mcp_store_mcpservertemplate (+ id text PRIMARY KEY, oauth_metadata jsonb, oauth_credentials jsonb+ );+ CREATE TEMP TABLE mcp_store_mcpserverinstallation (+ id text PRIMARY KEY, team_id int, user_id int, url text, auth_type text,+ is_enabled boolean, sensitive_configuration jsonb, oauth_metadata jsonb, template_id text+ );+ INSERT INTO mcp_store_mcpserverinstallation+ (id, team_id, user_id, url, auth_type, is_enabled, sensitive_configuration, oauth_metadata, template_id)+ VALUES+ ('inst-a', ${TEAM}, ${OWNER_A}, 'https://a.test/mcp', 'api_key', true, '{}'::jsonb, '{}'::jsonb, NULL),+ ('inst-b', ${TEAM}, ${OWNER_B}, 'https://b.test/mcp', 'api_key', true, '{}'::jsonb, '{}'::jsonb, NULL);+ `)+ })++ afterAll(async () => {+ client?.release()+ await pool?.end()+ })++ it("owner A's lookup cannot return owner B's installation (the IDOR)", async () => {+ const { rows } = await client.query(SELECT_INSTALLATION, ['inst-b', TEAM, OWNER_A])+ expect(rows).toHaveLength(0)+ })++ it('the owner can fetch their own installation', async () => {+ const bAsB = await client.query(SELECT_INSTALLATION, ['inst-b', TEAM, OWNER_B])+ const aAsA = await client.query(SELECT_INSTALLATION, ['inst-a', TEAM, OWNER_A])+ expect(bAsB.rows).toHaveLength(1)+ expect(aAsA.rows).toHaveLength(1)+ })+})diff --git a/products/agent_platform/services/agent-shared/src/runtime/mcp-connection-store.test.ts b/products/agent_platform/services/agent-shared/src/runtime/mcp-connection-store.test.tsindex 398ab9bb4d88..44fda9fd3a7f 100644--- a/products/agent_platform/services/agent-shared/src/runtime/mcp-connection-store.test.ts+++ b/products/agent_platform/services/agent-shared/src/runtime/mcp-connection-store.test.ts@@ -8,6 +8,8 @@ import { PgMcpConnectionStore } from './mcp-connection-store'const KEY = '01234567890123456789012345678901'const enc = new EncryptedFields(KEY)const nowSec = Math.floor(Date.now() / 1000)+// Spec author / installation owner threaded into resolve (agent_revision.created_by_id).+const OWNER = 7function fakeResponse(opts: { ok: boolean; status?: number; body?: unknown; text?: string }): Response {return {@@ -104,11 +106,21 @@ function oauthRow(}describe('PgMcpConnectionStore', () => {- it('scopes the lookup to (connectionId, teamId)', async () => {+ it('scopes the lookup to (connectionId, teamId, ownerUserId) — the IDOR boundary', async () => {+ // The owner (spec author) must be in the WHERE params; dropping it would let+ // a spec reference a connection owned by a different user in the same team.const { pool, calls } = makeFakePool(oauthRow())const store = new PgMcpConnectionStore(pool, enc, makeFakeHttp(fakeResponse({ ok: true })))- await store.resolve('conn-1', 42)- expect(calls[0].values).toEqual(['conn-1', 42])+ await store.resolve('conn-1', 42, OWNER)+ expect(calls[0].values).toEqual(['conn-1', 42, OWNER])+ })++ it('fails closed on a null owner without touching the DB', async () => {+ // An unattributable spec (no created_by_id) cannot use a stored credential.+ const { pool, calls } = makeFakePool(oauthRow())+ const store = new PgMcpConnectionStore(pool, enc, makeFakeHttp(fakeResponse({ ok: true })))+ await expect(store.resolve('conn-1', 42, null)).resolves.toEqual({ kind: 'not_found' })+ expect(calls).toHaveLength(0)})it('resolves an api-key installation without refresh', async () => {@@ -124,7 +136,7 @@ describe('PgMcpConnectionStore', () => {})const http = makeFakeHttp(fakeResponse({ ok: true }))const store = new PgMcpConnectionStore(pool, enc, http)- await expect(store.resolve('c', 1)).resolves.toEqual({+ await expect(store.resolve('c', 1, OWNER)).resolves.toEqual({kind: 'resolved',url: 'https://mcp.example.com/mcp',bearer: 'key-1',@@ -137,7 +149,7 @@ describe('PgMcpConnectionStore', () => {const { pool, writes } = makeFakePool(oauthRow({ expiring: false }))const http = makeFakeHttp(fakeResponse({ ok: true }))const store = new PgMcpConnectionStore(pool, enc, http)- await expect(store.resolve('c', 1)).resolves.toEqual({+ await expect(store.resolve('c', 1, OWNER)).resolves.toEqual({kind: 'resolved',url: 'https://mcp.example.com/mcp',bearer: 'tok-1',@@ -152,7 +164,7 @@ describe('PgMcpConnectionStore', () => {fakeResponse({ ok: true, body: { access_token: 'tok-2', refresh_token: 'refresh-2', expires_in: 1800 } }))const store = new PgMcpConnectionStore(pool, enc, http)- const res = await store.resolve('c', 1)+ const res = await store.resolve('c', 1, OWNER)expect(res).toEqual({kind: 'resolved',url: 'https://mcp.example.com/mcp',@@ -178,7 +190,7 @@ describe('PgMcpConnectionStore', () => {const { pool } = makeFakePool(oauthRow({ expiring: true, secret: 'secret-1' }))const http = makeFakeHttp(fakeResponse({ ok: true, body: { access_token: 'tok-2', expires_in: 1800 } }))const store = new PgMcpConnectionStore(pool, enc, http)- await store.resolve('c', 1)+ await store.resolve('c', 1, OWNER)const init = http.calls[0].init!expect((init.headers as Record<string, string>).Authorization).toBe(`Basic ${Buffer.from('client-1:secret-1').toString('base64')}`@@ -195,7 +207,7 @@ describe('PgMcpConnectionStore', () => {)const http = makeFakeHttp(fakeResponse({ ok: true, body: { access_token: 'tok-2', expires_in: 1800 } }))const store = new PgMcpConnectionStore(pool, enc, http)- await store.resolve('c', 1)+ await store.resolve('c', 1, OWNER)const init = http.calls[0].init!expect((init.headers as Record<string, string>).Authorization).toBeUndefined()const body = String(init.body)@@ -207,7 +219,7 @@ describe('PgMcpConnectionStore', () => {const { pool } = makeFakePool(oauthRow({ expiring: true, resource: 'https://api.example.com' }))const http = makeFakeHttp(fakeResponse({ ok: true, body: { access_token: 'tok-2', expires_in: 1800 } }))const store = new PgMcpConnectionStore(pool, enc, http)- await store.resolve('c', 1)+ await store.resolve('c', 1, OWNER)expect(String(http.calls[0].init?.body)).toContain('resource=https%3A%2F%2Fapi.example.com')})@@ -215,7 +227,7 @@ describe('PgMcpConnectionStore', () => {const { pool, writes } = makeFakePool(oauthRow({ expiring: true }))const http = makeFakeHttp(fakeResponse({ ok: false, status: 302, text: '' }))const store = new PgMcpConnectionStore(pool, enc, http)- await expect(store.resolve('c', 1)).rejects.toThrow(/mcp_connection_needs_reauth/)+ await expect(store.resolve('c', 1, OWNER)).rejects.toThrow(/mcp_connection_needs_reauth/)// Don't follow redirects (Django uses allow_redirects=False), and treat a// 3xx as a permanent misconfig → needs_reauth, not an endless retry.expect(http.calls[0].init?.redirect).toBe('manual')@@ -227,7 +239,7 @@ describe('PgMcpConnectionStore', () => {const { pool, writes } = makeFakePool(oauthRow({ expiring: true }))const http = makeFakeHttp(fakeResponse({ ok: true, body: { access_token: 'tok-2', expires_in: null } }))const store = new PgMcpConnectionStore(pool, enc, http)- await store.resolve('c', 1)+ await store.resolve('c', 1, OWNER)const written = enc.decryptJsonFieldValue(JSON.parse(writes[0].values[0] as string)) as Record<string, unknown>// Storing "null" NaN-poisons isTokenExpiring → pins the bearer as// never-refreshing. Keep the prior numeric value instead.@@ -239,7 +251,7 @@ describe('PgMcpConnectionStore', () => {const { pool, writes } = makeFakePool(oauthRow({ expiring: true }))const http = makeFakeHttp(fakeResponse({ ok: true, body: { access_token: 'tok-2', expires_in: 1800 } }))const store = new PgMcpConnectionStore(pool, enc, http)- await store.resolve('c', 1)+ await store.resolve('c', 1, OWNER)const written = enc.decryptJsonFieldValue(JSON.parse(writes[0].values[0] as string)) as Record<string, unknown>expect(written.refresh_token).toBe('refresh-1')})@@ -247,26 +259,26 @@ describe('PgMcpConnectionStore', () => {it('returns needs_reauth when the credential is flagged', async () => {const { pool } = makeFakePool(oauthRow({ needsReauth: true }))const store = new PgMcpConnectionStore(pool, enc, makeFakeHttp(fakeResponse({ ok: true })))- await expect(store.resolve('c', 1)).resolves.toEqual({ kind: 'needs_reauth' })+ await expect(store.resolve('c', 1, OWNER)).resolves.toEqual({ kind: 'needs_reauth' })})it('returns disabled when the installation is disabled', async () => {const { pool } = makeFakePool(oauthRow({ isEnabled: false }))const store = new PgMcpConnectionStore(pool, enc, makeFakeHttp(fakeResponse({ ok: true })))- await expect(store.resolve('c', 1)).resolves.toEqual({ kind: 'disabled' })+ await expect(store.resolve('c', 1, OWNER)).resolves.toEqual({ kind: 'disabled' })})it('returns not_found when no row matches', async () => {const { pool } = makeFakePool(null)const store = new PgMcpConnectionStore(pool, enc, makeFakeHttp(fakeResponse({ ok: true })))- await expect(store.resolve('c', 1)).resolves.toEqual({ kind: 'not_found' })+ await expect(store.resolve('c', 1, OWNER)).resolves.toEqual({ kind: 'not_found' })})it('flags needs_reauth (and stops retrying) on a permanent 4xx refresh rejection', async () => {const { pool, writes } = makeFakePool(oauthRow({ expiring: true }))const http = makeFakeHttp(fakeResponse({ ok: false, status: 400, text: 'invalid_grant' }))const store = new PgMcpConnectionStore(pool, enc, http)- await expect(store.resolve('c', 1)).rejects.toThrow(/mcp_connection_needs_reauth/)+ await expect(store.resolve('c', 1, OWNER)).rejects.toThrow(/mcp_connection_needs_reauth/)// Wrote needs_reauth back so the next resolve short-circuits instead of// re-hitting the token endpoint every session.expect(writes).toHaveLength(1)@@ -278,7 +290,7 @@ describe('PgMcpConnectionStore', () => {const { pool, writes } = makeFakePool(oauthRow({ expiring: true, noRefreshToken: true }))const http = makeFakeHttp(fakeResponse({ ok: true }))const store = new PgMcpConnectionStore(pool, enc, http)- await expect(store.resolve('c', 1)).rejects.toThrow(/mcp_connection_needs_reauth/)+ await expect(store.resolve('c', 1, OWNER)).rejects.toThrow(/mcp_connection_needs_reauth/)// Nothing to refresh with → no token-endpoint call…expect(http.calls).toHaveLength(0)// …but needs_reauth is written back so the next resolve short-circuits@@ -292,7 +304,7 @@ describe('PgMcpConnectionStore', () => {const { pool, writes } = makeFakePool(oauthRow({ expiring: true }))const http = makeFakeHttp(fakeResponse({ ok: false, status: 503, text: 'upstream down' }))const store = new PgMcpConnectionStore(pool, enc, http)- await expect(store.resolve('c', 1)).rejects.toThrow(/mcp_connection_refresh_failed/)+ await expect(store.resolve('c', 1, OWNER)).rejects.toThrow(/mcp_connection_refresh_failed/)expect(writes).toHaveLength(0)})})diff --git a/products/agent_platform/services/agent-shared/src/runtime/mcp-connection-store.ts b/products/agent_platform/services/agent-shared/src/runtime/mcp-connection-store.tsindex f9c78d0748b2..baf00c846070 100644--- a/products/agent_platform/services/agent-shared/src/runtime/mcp-connection-store.ts+++ b/products/agent_platform/services/agent-shared/src/runtime/mcp-connection-store.ts@@ -22,14 +22,17 @@ export type McpConnectionResolution =| { kind: 'needs_reauth' }/** Owner disabled the installation (`is_enabled = false`). */| { kind: 'disabled' }- /** No installation with this id for the agent's team. */+ /** No installation for this id + team + owning user. The IDOR boundary: an+ * installation owned by a different user (even same team) is `not_found`, so a+ * spec author can only use a connection whose credential they own. */| { kind: 'not_found' }export interface McpConnectionStore {- /** Resolve an installation (UUID, scoped to `teamId`) to URL + bearer,- * refreshing an expiring OAuth token in place. Throws+ /** Resolve an installation (scoped to `teamId` AND `ownerUserId`) to URL ++ * bearer, refreshing an expiring OAuth token. `ownerUserId` is the spec+ * author; a null owner fails closed to `not_found`. Throws* `mcp_connection_refresh_failed` on a transient refresh failure. */- resolve(connectionId: string, teamId: number): Promise<McpConnectionResolution>+ resolve(connectionId: string, teamId: number, ownerUserId: number | null): Promise<McpConnectionResolution>}interface InstallationRow {@@ -65,7 +68,7 @@ interface TokenResponse {expires_in?: number}-const SELECT_INSTALLATION = `+export const SELECT_INSTALLATION = `SELECT i.url,i.auth_type,i.is_enabled,@@ -76,7 +79,7 @@ const SELECT_INSTALLATION = `t.oauth_credentials AS template_oauth_credentialsFROM mcp_store_mcpserverinstallation iLEFT JOIN mcp_store_mcpservertemplate t ON t.id = i.template_id- WHERE i.id = $1 AND i.team_id = $2`+ WHERE i.id = $1 AND i.team_id = $2 AND i.user_id = $3`/** Reads `mcp_store_mcpserverinstallation` (+ optional template) from the main* DB. Pass the main-DB pool. Write-back needs UPDATE on that table. */@@ -89,9 +92,40 @@ export class PgMcpConnectionStore implements McpConnectionStore {private readonly http: HttpFetcher) {}- async resolve(connectionId: string, teamId: number): Promise<McpConnectionResolution> {- const { rows } = await this.pool.query<InstallationRow>(SELECT_INSTALLATION, [connectionId, teamId])+ async resolve(connectionId: string, teamId: number, ownerUserId: number | null): Promise<McpConnectionResolution> {+ // Fail closed: a spec with no resolvable author cannot use a stored+ // credential. Short-circuit before touching the DB.+ if (ownerUserId == null) {+ // Greppable signal: owner-scoping turns a live agent whose author+ // can't be resolved into a not_found. Surface it so affected agents+ // can be found in logs instead of failing silently mid-session.+ this.log.warn({ connection_id: connectionId, team_id: teamId }, 'mcp_connection.resolve_null_author')+ return { kind: 'not_found' }+ }+ const { rows } = await this.pool.query<InstallationRow>(SELECT_INSTALLATION, [+ connectionId,+ teamId,+ ownerUserId,+ ])if (rows.length === 0) {+ // Distinguish "genuinely absent" (a normal not_found) from "exists+ // but owned by another team member" — the latter is a live agent the+ // owner-scoping tightening just broke, worth surfacing for an audit.+ // Miss-path only: the happy path returns rows above and never probes,+ // so this fires ~at the broken-ref rate it measures. Keep it a separate+ // existence check (no sensitive column) — folding it into the scoped+ // SELECT would pull the credential row back before the owner check,+ // undoing the SQL-level enforcement.+ const probe = await this.pool.query(+ 'SELECT 1 FROM mcp_store_mcpserverinstallation WHERE id = $1 AND team_id = $2',+ [connectionId, teamId]+ )+ if (probe.rows.length > 0) {+ this.log.warn(+ { connection_id: connectionId, team_id: teamId, owner_user_id: ownerUserId },+ 'mcp_connection.resolve_owner_mismatch'+ )+ }return { kind: 'not_found' }}const row = rows[0]@@ -119,7 +153,7 @@ export class PgMcpConnectionStore implements McpConnectionStore {if (!isTokenExpiring(sensitive)) {return { kind: 'resolved', url: row.url, bearer: accessToken }}- const refreshed = await this.refresh(connectionId, teamId)+ const refreshed = await this.refresh(connectionId, teamId, ownerUserId)return { kind: 'resolved', url: row.url, bearer: refreshed }}@@ -130,14 +164,20 @@ export class PgMcpConnectionStore implements McpConnectionStore {* short-circuits to "owner must reconnect" instead of re-hitting the IdP on* every run; a TRANSIENT failure (5xx / 429 / network) rolls back so the* next session retries. */- private async refresh(connectionId: string, teamId: number): Promise<string> {+ private async refresh(connectionId: string, teamId: number, ownerUserId: number): Promise<string> {const client = await this.pool.connect()let committed = falsetry {await client.query('BEGIN')+ // The FOR UPDATE row lock below is held across the external token-+ // endpoint call, so a concurrent refresh for the same connection+ // would otherwise block up to the fetch timeout waiting on it. Fail+ // fast on lock acquisition instead of piling connections behind it.+ await client.query("SET LOCAL lock_timeout = '3s'")const { rows } = await client.query<InstallationRow>(`${SELECT_INSTALLATION} FOR UPDATE OF i`, [connectionId,teamId,+ ownerUserId,])if (rows.length === 0) {throw new Error(`mcp_connection_refresh_failed: ${connectionId} (row vanished)`)diff --git a/products/agent_platform/services/agent-shared/src/runtime/team-api-key-resolver.sql.test.ts b/products/agent_platform/services/agent-shared/src/runtime/team-api-key-resolver.sql.test.tsnew file mode 100644index 000000000000..c7394cac5495--- /dev/null+++ b/products/agent_platform/services/agent-shared/src/runtime/team-api-key-resolver.sql.test.ts@@ -0,0 +1,52 @@+import { Pool, type PoolClient } from 'pg'+import { afterAll, beforeAll, describe, expect, it } from 'vitest'++import { SELECT_TEAM_API_TOKEN } from './team-api-key-resolver'++/**+ * The fake-pool unit test only asserts `resolve` passes `[teamId]`, not that the+ * query filters on it — drop `WHERE id = $1` and the resolver mints another+ * team's `phc_` bearer while unit tests stay green. This runs the real+ * `SELECT_TEAM_API_TOKEN` against Postgres with two teams to catch that.+ */+const TEST_DB_URL =+ process.env.AGENT_TEST_DB_URL ?? 'postgres://posthog:posthog@localhost:5432/agent_runtime_queue_test'++const TEAM_ONE = 1+const TEAM_TWO = 2++describe('SELECT_TEAM_API_TOKEN team isolation (real SQL)', () => {+ let pool: Pool+ let client: PoolClient // one connection — temp tables are session-scoped++ beforeAll(async () => {+ pool = new Pool({ connectionString: TEST_DB_URL, max: 1 })+ client = await pool.connect()+ // Temp table shadows real posthog_team for this session only — no schema+ // dependency, auto-dropped on disconnect.+ await client.query(`+ CREATE TEMP TABLE posthog_team (id int PRIMARY KEY, api_token text);+ INSERT INTO posthog_team (id, api_token) VALUES+ (${TEAM_ONE}, 'phc_team_one'),+ (${TEAM_TWO}, 'phc_team_two');+ `)+ })++ afterAll(async () => {+ client?.release()+ await pool?.end()+ })++ it("a team's lookup returns only its own api_token (never a sibling's)", async () => {+ const one = await client.query<{ api_token: string }>(SELECT_TEAM_API_TOKEN, [TEAM_ONE])+ const two = await client.query<{ api_token: string }>(SELECT_TEAM_API_TOKEN, [TEAM_TWO])+ expect(one.rows).toHaveLength(1)+ expect(one.rows[0].api_token).toBe('phc_team_one')+ expect(two.rows[0].api_token).toBe('phc_team_two')+ })++ it('a missing team returns zero rows (no fallback to a sibling)', async () => {+ const { rows } = await client.query(SELECT_TEAM_API_TOKEN, [999])+ expect(rows).toHaveLength(0)+ })+})diff --git a/products/agent_platform/services/agent-shared/src/runtime/team-api-key-resolver.ts b/products/agent_platform/services/agent-shared/src/runtime/team-api-key-resolver.tsindex 2792baafb387..7d4d871b6df4 100644--- a/products/agent_platform/services/agent-shared/src/runtime/team-api-key-resolver.ts+++ b/products/agent_platform/services/agent-shared/src/runtime/team-api-key-resolver.ts@@ -26,6 +26,13 @@ export interface PgTeamApiKeyResolverOpts {ttlMs?: number}+/**+ * Exported so the real-SQL isolation oracle runs the actual statement, not a+ * drifting copy. `WHERE id = $1` is the tenant boundary: drop it and `resolve`+ * mints another team's `api_token` bearer.+ */+export const SELECT_TEAM_API_TOKEN = 'SELECT api_token FROM posthog_team WHERE id = $1'+/*** Reads `posthog_team.api_token` from the main PostHog database. The token is* the team's public capture key (`phc_...`) — not secret-grade, but treated@@ -52,10 +59,7 @@ export class PgTeamApiKeyResolver implements TeamApiKeyResolver {if (cached && cached.expires > Date.now()) {return cached.value}- const { rows } = await this.pool.query<{ api_token: string | null }>(- 'SELECT api_token FROM posthog_team WHERE id = $1',- [teamId]- )+ const { rows } = await this.pool.query<{ api_token: string | null }>(SELECT_TEAM_API_TOKEN, [teamId])if (rows.length === 0) {throw new TeamApiKeyNotFoundError(`team_id=${teamId} not found`)}diff --git a/products/agent_platform/services/agent-shared/src/spec/Spec.spec.md b/products/agent_platform/services/agent-shared/src/spec/Spec.spec.mdnew file mode 100644index 000000000000..764867cb7762--- /dev/null+++ b/products/agent_platform/services/agent-shared/src/spec/Spec.spec.md@@ -0,0 +1,22 @@+# Spec++The agent spec schema (`AgentSpecSchema`, zod) — the single source of truth for the `revision.spec` JSONB — plus the codegen bridge that emits spec vocabularies as checked-in JSON for the Django control plane to import.++## invariants++- tenant-array-bounds+- generated-vocabulary-single-source+- trigger-routes-single-source++## works when++- typechecks+- boundary "tenant-array-bounds" at AgentSpecSchema via test "agent spec tenant-array bounds"+- boundary "generated-vocabulary-single-source" at GENERATED_ARTIFACTS via test "spec generated artifacts"+- boundary "trigger-routes-single-source" at TRIGGER_ROUTES via test "spec generated artifacts"++## why++tenant-array-bounds: every top-level array in the spec is author-controlled and flows into a loop/query at freeze/promote/run, so an unbounded one is a resource lever (the confirmed case: `identity_providers` fanning out into per-entry OAuthApplication creation + org-row locks at promote). The oracle reads the schema's own JSON-Schema projection, resolves `$ref` and walks `anyOf`/`oneOf`/`allOf` so a `nullable`/union array can't slip through undetected, and asserts a FLOOR on how many array fields it finds — if the projection shape ever changes so it detects fewer, the floor fails loud instead of the oracle passing vacuously (the false-green class this exists to prevent).+generated-vocabulary-single-source: the vocabularies Django needs as data (per-trigger required secrets, approval-request states, assistant stop reasons) are authored once here and emitted as checked-in JSON that Django imports, so there is no hand-maintained Python copy to keep in lockstep. The freshness oracle welds each checked-in artifact to its TS source (parsed comparison, formatter-immune); a registry-non-empty floor keeps the guard from passing vacuously if the artifact list ever collapses. Coverage that the guard actually runs on artifact edits is enforced CI-side (`test_ci_guard_coverage.py`).+trigger-routes-single-source: the per-trigger ingress route catalogue is authored once in `TRIGGER_ROUTES` (total over `TriggerType`; `cron` explicitly empty — janitor-fired, no inbound route). The ingress trigger modules import their `path:` values from it and Django's preview-endpoint builder reads the emitted artifact, so the routes the ingress actually serves, the paths previews advertise, and the trigger-kind enumeration strings cannot drift — retiring a hand-mirror that its own comment asked readers to "keep in sync" and that contributors measurably missed.diff --git a/products/agent_platform/services/agent-shared/src/spec/mcp-credential-path.test.ts b/products/agent_platform/services/agent-shared/src/spec/mcp-credential-path.test.tsnew file mode 100644index 000000000000..1f9b8813335b--- /dev/null+++ b/products/agent_platform/services/agent-shared/src/spec/mcp-credential-path.test.ts@@ -0,0 +1,51 @@+import { describe, expect, it } from 'vitest'++import { McpRefSchema } from './spec'++/**+ * Every `McpRef` must resolve its bearer through exactly ONE of three wired paths:+ * - `connection` (kind 'agent') — shared mcp_store installation bearer+ * - `auth.provider` (kind 'principal') — per-asker linked identity+ * - `secrets`/none (kind 'agent') — bring-your-own token, or a public MCP+ *+ * The `kind` discriminator + `superRefine` pin which fields a ref may set, so a+ * fourth path can't be smuggled in via a contradictory combination. This pins the+ * accept/reject matrix; loosening the refine fails it.+ */+const base = { id: 'm', url: 'https://mcp.example.test', default_tool_approval: 'approve' as const }++const cases: { name: string; ref: Record<string, unknown>; valid: boolean }[] = [+ {+ name: 'principal + auth.provider (no connection)',+ ref: { ...base, kind: 'principal', auth: { provider: 'gh' } },+ valid: true,+ },+ { name: 'principal WITHOUT auth.provider', ref: { ...base, kind: 'principal' }, valid: false },+ {+ name: 'principal + connection (cross-path)',+ ref: { ...base, kind: 'principal', auth: { provider: 'gh' }, connection: 'inst-1' },+ valid: false,+ },+ { name: 'agent + connection', ref: { ...base, kind: 'agent', connection: 'inst-1' }, valid: true },+ {+ name: 'agent + secrets/headers (bring-your-own)',+ ref: { ...base, kind: 'agent', secrets: ['TOK'], headers: { Authorization: 'Bearer ${TOK}' } },+ valid: true,+ },+ {+ name: 'agent + auth.provider (cross-path)',+ ref: { ...base, kind: 'agent', auth: { provider: 'gh' } },+ valid: false,+ },+ { name: 'agent + nothing (public MCP, no auth)', ref: { ...base, kind: 'agent' }, valid: true },+]++describe('MCP credential-path totality', () => {+ it.each(cases)('$name → valid=$valid', ({ ref, valid }) => {+ expect(McpRefSchema.safeParse(ref).success).toBe(valid)+ })++ it('the discriminator is closed to exactly {agent, principal} — no third kind', () => {+ expect(McpRefSchema.safeParse({ ...base, kind: 'integration', connection: 'inst-1' }).success).toBe(false)+ })+})diff --git a/products/agent_platform/services/agent-shared/src/spec/spec-array-bounds.test.ts b/products/agent_platform/services/agent-shared/src/spec/spec-array-bounds.test.tsnew file mode 100644index 000000000000..f44229531614--- /dev/null+++ b/products/agent_platform/services/agent-shared/src/spec/spec-array-bounds.test.ts@@ -0,0 +1,85 @@+import { describe, expect, it } from 'vitest'+import { z } from 'zod'++import { AgentSpecSchema } from './spec'++/**+ * Fails if any top-level spec array lacks `maxItems` (an unbounded author-controlled+ * array is a resource lever at freeze/promote/run). A naive `type === 'array'`+ * filter is a false-green trap — a nullable array projects to `anyOf` and a reused+ * schema to `$ref` — so we resolve `$ref` and walk `anyOf`/`oneOf`/`allOf`, plus a+ * floor on the detected count so the check can't pass vacuously.+ */++type JsonSchema = {+ type?: string | string[]+ items?: unknown+ maxItems?: number+ $ref?: string+ anyOf?: JsonSchema[]+ oneOf?: JsonSchema[]+ allOf?: JsonSchema[]+ properties?: Record<string, JsonSchema>+ $defs?: Record<string, JsonSchema>+}++/** Every array-typed subschema reachable from `node` (through $ref + combinators). */+function arraySchemasIn(+ node: JsonSchema | undefined,+ defs: Record<string, JsonSchema>,+ seen = new Set<string>()+): JsonSchema[] {+ if (!node) {+ return []+ }+ if (node.$ref) {+ const name = node.$ref.replace('#/$defs/', '')+ if (seen.has(name)) {+ return []+ }+ seen.add(name)+ return arraySchemasIn(defs[name], defs, seen)+ }+ const out: JsonSchema[] = []+ // `type` is usually the string 'array', but a nullable array can also project+ // to `{ type: ['array', 'null'], … }` (type-as-array). Handle both.+ const isArrayType = node.type === 'array' || (Array.isArray(node.type) && (node.type as string[]).includes('array'))+ if (isArrayType) {+ out.push(node)+ }+ for (const branch of [...(node.anyOf ?? []), ...(node.oneOf ?? []), ...(node.allOf ?? [])]) {+ out.push(...arraySchemasIn(branch, defs, seen))+ }+ return out+}++const EXPECTED_MIN_ARRAY_FIELDS = 6 // triggers, tools, mcps, skills, identity_providers, secrets++describe('agent spec tenant-array bounds', () => {+ it('every top-level array field is bounded (maxItems), and we still detect them all', () => {+ const js = z.toJSONSchema(AgentSpecSchema, { io: 'input', unrepresentable: 'any' }) as JsonSchema+ const props = js.properties ?? {}+ const defs = js.$defs ?? {}++ const arrayFields: string[] = []+ const unbounded: string[] = []+ for (const [name, schema] of Object.entries(props)) {+ const arrays = arraySchemasIn(schema, defs)+ if (arrays.length === 0) {+ continue+ }+ arrayFields.push(name)+ if (arrays.some((a) => typeof a.maxItems !== 'number')) {+ unbounded.push(name)+ }+ }++ expect(unbounded, `unbounded tenant arrays — add .max(): ${unbounded.join(', ')}`).toEqual([])+ // Floor: if the projection ever stops surfacing the known arrays, fail loud+ // rather than pass vacuously (the false-green this oracle exists to prevent).+ expect(+ arrayFields.length,+ `only detected ${arrayFields.length} array fields (${arrayFields.join(', ')}); projection shape may have changed`+ ).toBeGreaterThanOrEqual(EXPECTED_MIN_ARRAY_FIELDS)+ })+})diff --git a/products/agent_platform/services/agent-shared/src/spec/spec-codegen.test.ts b/products/agent_platform/services/agent-shared/src/spec/spec-codegen.test.tsnew file mode 100644index 000000000000..2387296a05de--- /dev/null+++ b/products/agent_platform/services/agent-shared/src/spec/spec-codegen.test.ts@@ -0,0 +1,47 @@+import { readdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'+import { basename, dirname, relative } from 'node:path'+import { describe, expect, it } from 'vitest'++import { GENERATED_ARTIFACTS } from './spec-codegen'++/**+ * Asserts each checked-in artifact parses to the same data its TS source produces+ * (parsed, not bytes — formatter-immune), so a source edited without regenerating+ * goes red. Set UPDATE_GENERATED=1 to (re)write the files instead of asserting.+ */+describe('spec generated artifacts', () => {+ // Floor: `it.each([])` registers zero tests and passes green — a vacuous guard.+ // Assert the registry is populated so an emptied `GENERATED_ARTIFACTS` fails loud.+ it('the artifact registry is non-empty (guard is non-vacuous)', () => {+ expect(GENERATED_ARTIFACTS.length).toBeGreaterThanOrEqual(3)+ })++ // Registry↔disk bijection: the freshness check iterates the registry, so a file+ // dropped from it but still on disk (and imported by generated.py) drifts+ // undetected. Assert the sets match.+ it('every generated file on disk is registered, and vice versa (no orphans)', () => {+ const dir = dirname(GENERATED_ARTIFACTS[0].path)+ const onDisk = readdirSync(dir)+ .filter((f) => f.endsWith('.generated.json'))+ .sort()+ const registered = GENERATED_ARTIFACTS.map((a) => basename(a.path)).sort()+ expect(onDisk).toEqual(registered)+ })++ if (process.env.UPDATE_GENERATED) {+ for (const artifact of GENERATED_ARTIFACTS) {+ // Atomic write: an interrupted regen must not leave a half-file that+ // Django then loads at import time (see generated.py `_load`).+ const tmp = `${artifact.path}.tmp`+ writeFileSync(tmp, artifact.content())+ renameSync(tmp, artifact.path)+ }+ }++ it.each(GENERATED_ARTIFACTS.map((a) => [relative(process.cwd(), a.path), a] as const))(+ 'checked-in %s matches its TS source (regenerate with UPDATE_GENERATED=1)',+ (_name, artifact) => {+ expect(JSON.parse(readFileSync(artifact.path, 'utf-8'))).toEqual(JSON.parse(artifact.content()))+ }+ )+})diff --git a/products/agent_platform/services/agent-shared/src/spec/spec-codegen.ts b/products/agent_platform/services/agent-shared/src/spec/spec-codegen.tsnew file mode 100644index 000000000000..13b1afadad6f--- /dev/null+++ b/products/agent_platform/services/agent-shared/src/spec/spec-codegen.ts@@ -0,0 +1,51 @@+import { dirname, join } from 'node:path'+import { fileURLToPath } from 'node:url'++import { APPROVAL_REQUEST_STATES } from '../persistence/approval-store'+import { ASSISTANT_STOP_REASONS } from './spec'+import { TRIGGER_ROUTES } from './trigger-routes'+import { TRIGGER_REQUIRED_SECRETS } from './trigger-secrets'++/**+ * Cross-language bridge for spec vocabularies Django needs as data. Each value is+ * authored once in TS and *emitted* as a checked-in JSON that Python *imports*, so+ * there's no hand-maintained Python copy to keep in lockstep. Adding a vocabulary+ * is one entry in `GENERATED_ARTIFACTS`; freshness is guarded by+ * `spec-codegen.test.ts`. Regenerate after editing any source:+ *+ * UPDATE_GENERATED=1 npx vitest run src/spec/spec-codegen.test.ts+ */++export interface GeneratedArtifact {+ /** Absolute path of the emitted file — in the Django tree next to its Python+ * consumer, mirroring how generated frontend types live under `frontend/generated/`. */+ path: string+ /** Canonical bytes: 4-space indent + trailing newline to match oxfmt (the repo+ * JSON formatter), so the committed file survives lint-staged untouched and the+ * byte-for-byte freshness comparison stays meaningful. */+ content: () => string+}++const backendLogic = (name: string): string =>+ join(dirname(fileURLToPath(import.meta.url)), '../../../../backend/logic', name)++const asJson = (value: unknown): string => `${JSON.stringify(value, null, 4)}\n`++export const GENERATED_ARTIFACTS: GeneratedArtifact[] = [+ {+ path: backendLogic('trigger_required_secrets.generated.json'),+ content: () => asJson(TRIGGER_REQUIRED_SECRETS),+ },+ {+ path: backendLogic('trigger_routes.generated.json'),+ content: () => asJson(TRIGGER_ROUTES),+ },+ {+ path: backendLogic('approval_request_states.generated.json'),+ content: () => asJson(APPROVAL_REQUEST_STATES),+ },+ {+ path: backendLogic('assistant_stop_reasons.generated.json'),+ content: () => asJson(ASSISTANT_STOP_REASONS),+ },+]diff --git a/products/agent_platform/services/agent-shared/src/spec/spec.ts b/products/agent_platform/services/agent-shared/src/spec/spec.tsindex d6020c9c81e4..78a87b7dfdde 100644--- a/products/agent_platform/services/agent-shared/src/spec/spec.ts+++ b/products/agent_platform/services/agent-shared/src/spec/spec.ts@@ -343,7 +343,7 @@ export type ApprovalType = z.infer<typeof ApprovalTypeSchema>* before the principal/agent split keep parsing. `team_admins` was the owner* authority → `agent`; `session_principal` → `principal`.*/-function legacyApproversToApprovalType(approvers: unknown): ApprovalType | undefined {+export function legacyApproversToApprovalType(approvers: unknown): ApprovalType | undefined {if (!Array.isArray(approvers)) {return undefined}@@ -416,6 +416,13 @@ export const DEFAULT_APPROVAL_POLICY = {export const ToolApprovalLevelSchema = z.enum(['allow', 'approve', 'deny'])export type ToolApprovalLevel = z.infer<typeof ToolApprovalLevelSchema>+/**+ * Intrinsic authorization class a native tool declares: the `deny`-excluded subset+ * of {@link ToolApprovalLevel}. `allow` = read-only/own-footprint, `approve`+ * reaches outside. `deny` is a resolution outcome, not an intrinsic class.+ */+export type NativeApprovalClass = Exclude<ToolApprovalLevel, 'deny'>+export const ToolRefSchema = z.discriminatedUnion('kind', [z.object({kind: z.literal('native'),@@ -988,30 +995,38 @@ export const AgentSpecObjectSchema = z.object({models: ModelPolicySchema.default({ mode: 'auto', level: 'medium', optimize_for: 'cost' }),triggers: z.array(TriggerSchema)+ .max(50).describe('How sessions start. Each entry is one trigger (a discriminated union on type: slack, webhook, cron, chat, mcp); an agent can be reachable several ways. Empty = no external triggers (preview/manual runs only).').default([]),tools: z.array(ToolRefSchema)+ .max(200).describe('Tools the agent can call. kind native = @posthog/* built-ins (call the agent-native-tools-list tool for valid ids), custom = author-written TypeScript, client = fulfilled by the connecting app. Empty = no tools.').default([]),mcps: z.array(McpRefSchema)+ // Bounded so a spec write can't fan out an unbounded connection-ownership+ // `IN (...)` query / parse loop (validate runs on every spec write). 50+ // mirrors the skill-refs cap; far above any real agent's server count.+ .max(50).describe('External MCP servers the agent connects to at session start. Each remote tool is exposed to the model name-prefixed by the entry id; auth.provider links a per-user identity, secrets/headers cover bring-your-own-token.').default([]),skills: z.array(SkillRefSchema)+ .max(50).describe('Skill references (id + path) listed in the system-prompt index; the model loads one on demand. Server-derived at freeze — set these via the skill-refs endpoints, not authored inline.').default([]),identity_providers: z.array(IdentityProviderConfigSchema)+ .max(50).describe('Identity providers users can link against so the agent can act AS the user (the credential axis). kind posthog = managed (provisioned on promote), oauth2 = bring-your-own third-party app.')@@ -1035,6 +1050,7 @@ export const AgentSpecObjectSchema = z.object({.optional(),secrets: z.array(SecretRefSchema)+ .max(100).describe('Secret names this agent can resolve from its encrypted env. Bare string = resolvable but no network-egress authority; object form pins the secret to allowed_hosts so @posthog/http-request may send it there.')@@ -1429,6 +1445,10 @@ export const EMPTY_USAGE_TOTAL: SessionUsageTotal = {cost_total: 0,}+/** The session lifecycle states. Terminal: `closed`, `cancelled`, `failed`.+ * See `session-state-reaper.ts` for the totality oracle over this set. */+export type SessionState = 'queued' | 'running' | 'completed' | 'closed' | 'cancelled' | 'failed'+export interface AgentSession {id: stringapplication_id: string@@ -1466,7 +1486,7 @@ export interface AgentSession {* confused with a runtime error.* failed — error state. Terminal regardless of `allow_restart`.*/- state: 'queued' | 'running' | 'completed' | 'closed' | 'cancelled' | 'failed'+ state: SessionState/*** Principal that authenticated `/run`. Subsequent `/send` calls must* carry a principal that matches (same kind + id). Null for sessions@@ -1558,11 +1578,19 @@ export interface AssistantMessageRecord {totalTokens?: numbercost?: { input?: number; output?: number; cacheRead?: number; cacheWrite?: number; total?: number }}- stopReason?: 'stop' | 'length' | 'toolUse' | 'error' | 'aborted'+ stopReason?: AssistantStopReasonerrorMessage?: stringtimestamp: number}+/**+ * Why the model stopped a turn (mirrors pi-ai). Source of truth for the+ * vocabulary — Django's serializer `choices` derives from the emitted JSON (see+ * `spec-codegen.ts`), not a hand-copy.+ */+export const ASSISTANT_STOP_REASONS = ['stop', 'length', 'toolUse', 'error', 'aborted'] as const+export type AssistantStopReason = (typeof ASSISTANT_STOP_REASONS)[number]+export interface ToolResultMessage {role: 'toolResult'toolCallId: stringdiff --git a/products/agent_platform/services/agent-shared/src/spec/tool-approval.test.ts b/products/agent_platform/services/agent-shared/src/spec/tool-approval.test.tsnew file mode 100644index 000000000000..47c5bcc63d21--- /dev/null+++ b/products/agent_platform/services/agent-shared/src/spec/tool-approval.test.ts@@ -0,0 +1,51 @@+import { describe, expect, it } from 'vitest'++import { type NativeApprovalClass, type ToolRef, ToolRefSchema } from './spec'+import { resolveToolRefApprovalLevel } from './tool-approval'++/**+ * The tool-authorization chokepoint resolves every `ToolRef` kind, fail closed,+ * and the `assertNever` makes a new unhandled lane a compile error.+ */+const deps = {+ // Stand-in for agent-tools' `nativeToolApprovalClass`: identity-connect is an+ // intrinsic `approve` (links credentials); everything else here `allow`.+ nativeApprovalClass: (id: string): NativeApprovalClass =>+ id === '@posthog/identity-connect' ? 'approve' : 'allow',+}++const ref = (input: Record<string, unknown>): ToolRef => ToolRefSchema.parse(input)++describe('resolveToolRefApprovalLevel', () => {+ it('native: intrinsic approve ⇒ approve regardless of the ref flag', () => {+ expect(resolveToolRefApprovalLevel(ref({ kind: 'native', id: '@posthog/identity-connect' }), deps)).toBe(+ 'approve'+ )+ })++ it('native: intrinsic read-only ⇒ allow', () => {+ expect(resolveToolRefApprovalLevel(ref({ kind: 'native', id: '@posthog/memory-read' }), deps)).toBe('allow')+ })++ it('native: author may escalate a read-only tool to approve, never the reverse', () => {+ expect(+ resolveToolRefApprovalLevel(+ ref({ kind: 'native', id: '@posthog/memory-read', requires_approval: true }),+ deps+ )+ ).toBe('approve')+ })++ it('custom: gate is the author ref flag', () => {+ expect(resolveToolRefApprovalLevel(ref({ kind: 'custom', id: 't', path: 't.ts' }), deps)).toBe('allow')+ expect(+ resolveToolRefApprovalLevel(ref({ kind: 'custom', id: 't', path: 't.ts', requires_approval: true }), deps)+ ).toBe('approve')+ })++ it('client: fails closed (no spec approval field today)', () => {+ expect(resolveToolRefApprovalLevel(ref({ kind: 'client', id: 'focus', description: 'd' }), deps)).toBe(+ 'approve'+ )+ })+})diff --git a/products/agent_platform/services/agent-shared/src/spec/tool-approval.ts b/products/agent_platform/services/agent-shared/src/spec/tool-approval.tsnew file mode 100644index 000000000000..d2c1545e5a92--- /dev/null+++ b/products/agent_platform/services/agent-shared/src/spec/tool-approval.ts@@ -0,0 +1,47 @@+/**+ * Tool-authorization chokepoint. One function resolves the approval level for any+ * spec `ToolRef`, discriminating over every `kind` with a final `assertNever`, so+ * a new tool lane is a compile error here until it's explicitly gated.+ *+ * The native intrinsic class is injected (its table lives in `agent-tools`, which+ * depends on `agent-shared`, so importing it here would cycle). MCP-sourced tools+ * aren't `ToolRef`s — they're gated separately by `effectiveToolLevel`.+ */+import type { NativeApprovalClass, ToolApprovalLevel, ToolRef } from './spec'++/** Exhaustiveness guard — unreachable at runtime; a compile error if a `ToolRef`+ * kind is added without a branch above. */+function assertNever(x: never): never {+ throw new Error(`unhandled ToolRef kind: ${JSON.stringify(x)}`)+}++export interface ResolveToolApprovalDeps {+ /** Intrinsic approval class for a native tool id (fail-closed on unknown). */+ nativeApprovalClass: (id: string) => NativeApprovalClass+}++/**+ * Effective approval level for an in-spec tool ref. Fail closed: an author may+ * tighten (e.g. force `approve` on a read-only tool) but never loosen a tool+ * below its intrinsic class.+ */+export function resolveToolRefApprovalLevel(ref: ToolRef, deps: ResolveToolApprovalDeps): ToolApprovalLevel {+ switch (ref.kind) {+ case 'native': {+ const intrinsic = deps.nativeApprovalClass(ref.id)+ // Author may escalate (requires_approval) but not de-escalate below intrinsic.+ return intrinsic === 'approve' || ref.requires_approval ? 'approve' : 'allow'+ }+ case 'custom':+ // Custom (sandbox) tools run author code; the author's ref carries the+ // policy. Default in the schema is `requires_approval: false`, so the+ // gate is the author's explicit choice here.+ return ref.requires_approval ? 'approve' : 'allow'+ case 'client':+ // Client tools have no approval field in the spec today. Fail closed+ // rather than silently allow.+ return 'approve'+ default:+ return assertNever(ref)+ }+}diff --git a/products/agent_platform/services/agent-shared/src/spec/tool.ts b/products/agent_platform/services/agent-shared/src/spec/tool.tsindex 4039eabe8d42..a1c546a2e50d 100644--- a/products/agent_platform/services/agent-shared/src/spec/tool.ts+++ b/products/agent_platform/services/agent-shared/src/spec/tool.ts@@ -23,8 +23,15 @@ import type { Credential } from '../runtime/credential-broker'import type { GatewayCatalog } from '../runtime/gateway-catalog'import type { HttpFetcher } from '../runtime/http-client'import type { WebSearchProvider } from '../runtime/web-search'+import type { NativeApprovalClass } from './spec'export type { Static, TSchema }+export type { NativeApprovalClass }++/** Runner timeout-selection + authoring-UI cost annotation. One source for the+ * closed set so the type and any runtime iteration (e.g. tests) can't drift. */+export const COST_HINTS = ['cheap', 'medium', 'expensive'] as const+export type CostHint = (typeof COST_HINTS)[number]export interface NativeToolSchema {description: string@@ -40,7 +47,11 @@ export interface NativeToolSchema {provider?: { id: string; scopes: string[] }}/** Hint for runner timeout selection + authoring UI cost annotations. */- cost_hint: 'cheap' | 'medium' | 'expensive'+ cost_hint: CostHint+ /** Intrinsic authorization class (single source: {@link NativeApprovalClass}).+ * `allow` = read-only/own-footprint; `approve` reaches outside and is gated.+ * Author may escalate via `requires_approval`, not de-escalate below it. */+ approval: NativeApprovalClass}export interface ToolContext {@@ -186,6 +197,10 @@ export function defineNativeTool<TArgsSchema extends TSchema, TReturnSchema extereturns: TReturnSchemarequires?: NativeToolSchema['requires']cost_hint?: NativeToolSchema['cost_hint']+ /** Required — every tool declares its authorization class at the definition+ * site, so an unclassified tool is a compile error (totality by the type+ * system, not a separate registry + test). */+ approval: NativeApprovalClassrun: (args: Static<TArgsSchema>, ctx: ToolContext) => Promise<Static<TReturnSchema>>}): NativeTool<Static<TArgsSchema>, Static<TReturnSchema>> {return {@@ -196,6 +211,7 @@ export function defineNativeTool<TArgsSchema extends TSchema, TReturnSchema extereturns: def.returns,requires: { provider: def.requires?.provider },cost_hint: def.cost_hint ?? 'medium',+ approval: def.approval,},run: def.run,}diff --git a/products/agent_platform/services/agent-shared/src/spec/trigger-routes.ts b/products/agent_platform/services/agent-shared/src/spec/trigger-routes.tsnew file mode 100644index 000000000000..4f8fef279504--- /dev/null+++ b/products/agent_platform/services/agent-shared/src/spec/trigger-routes.ts@@ -0,0 +1,32 @@+/**+ * Per-trigger-type ingress route catalogue. Single source shared by agent-ingress+ * (each trigger module imports its `path:` values from here) and Django's+ * preview-endpoint builder (via the generated artifact), so the routes can't drift.+ * `cron` maps to `{}` — janitor-fired, no inbound route. `Record<TriggerType, …>`+ * is total: a new trigger type without an entry here fails to compile.+ */++import type { TriggerType } from './spec'++export const TRIGGER_ROUTES: Record<TriggerType, Record<string, string>> = {+ chat: {+ run: '/run',+ send: '/send',+ cancel: '/cancel',+ listen: '/listen',+ client_tool_result: '/client_tool_result',+ },+ slack: {+ events: '/slack/events',+ interactivity: '/slack/interactivity',+ },+ cron: {},+ webhook: {+ post: '/webhook',+ },+ mcp: {+ rpc: '/mcp',+ stream: '/mcp/stream',+ connect_info: '/mcp/connect-info',+ },+}diff --git a/products/agent_platform/services/agent-shared/src/storage/Storage.spec.md b/products/agent_platform/services/agent-shared/src/storage/Storage.spec.mdnew file mode 100644index 000000000000..4a311b87d392--- /dev/null+++ b/products/agent_platform/services/agent-shared/src/storage/Storage.spec.md@@ -0,0 +1,21 @@+# Storage++Content-addressed bundle storage for agent revisions — the file-tree layer+backing `AgentRevision.bundle_uri`. `S3BundleStore` is the prod backend+(SeaweedFS locally); a draft's bundle is a mutable key prefix until `freeze`+stamps a `.frozen` marker and a content hash, after which every write and+delete against that revision id must refuse.++## invariants++- bundle-freeze-immutability++## works when++- typechecks+- boundary "bundle-freeze-immutability" at S3BundleStore+- passes test "freezes and blocks further writes"++## why++bundle-freeze-immutability: `write` and `delete` both check `isFrozen(rev)` before touching S3 and throw `bundle ${rev} is frozen` when the `.frozen` marker object exists; `freeze` writes that marker holding a hash recomputed from each file's actual bytes rather than the writer-supplied `Metadata.sha256` that `list` trusts, so the frozen hash can't be spoofed by an in-cluster writer setting object metadata independently of content. This matters because `agent_revision.bundle_sha256` and every downstream consumer that reads a promoted bundle (the runner at session start, `readTypedBundle`) trust that a given revision id names one immutable set of bytes forever — without the write/delete refusal, a later write to an already-frozen revision id would silently swap content behind a promoted (and possibly already-executing) revision, breaking that promise for anyone who already has the id. `isFrozen` is also the authoritative cross-process signal ahead of `agent_revision.state` (Django stamps `state` _after_ the janitor returns), so the guard can't be raced by an in-flight promote reading a stale `draft` state. The oracle runs against a real S3-compatible backend (SeaweedFS): write, freeze, attempt a second write, assert it throws.diff --git a/products/agent_platform/services/agent-tests/src/cases/slack-identity.test.ts b/products/agent_platform/services/agent-tests/src/cases/slack-identity.test.tsindex b28a6f9075c8..8134130aacb7 100644--- a/products/agent_platform/services/agent-tests/src/cases/slack-identity.test.ts+++ b/products/agent_platform/services/agent-tests/src/cases/slack-identity.test.ts@@ -72,15 +72,18 @@ describe('slack identity: real e2e', () => {}})- it('untrusted workspace on a trusted-list agent → 403', async () => {+ it('untrusted workspace on a trusted-list agent → 200 ack + drop (never a 4xx delivery failure)', async () => {await c.deployAgent({slug: 'gated',spec: { triggers: [{ type: 'slack', config: { trusted_workspaces: ['T-OK-ONLY'] } }] },encrypted_env: SLACK_ENV,})const res = await c.slackPost('gated', 'events', slackEvent({ team: 'T-EVIL', user: 'U-EVIL' }), SLACK_SECRET)- expect(res.status).toBe(403)- expect(res.body.error).toBe('workspace_not_trusted')+ // A signed, authenticated delivery that just isn't from a trusted+ // workspace is a routing decision, not a delivery failure — Slack (and+ // any provider) retries non-2xx responses, so this must ack.+ expect(res.status).toBe(200)+ expect(res.body.dropped).toBe('workspace_not_trusted')})it('"*" accepts any workspace; distinct (workspace, user) → distinct AgentUsers', async () => {diff --git a/products/agent_platform/services/agent-tests/src/cases/slack-trigger.test.ts b/products/agent_platform/services/agent-tests/src/cases/slack-trigger.test.tsindex cb80a4e95fc6..254351c754d5 100644--- a/products/agent_platform/services/agent-tests/src/cases/slack-trigger.test.ts+++ b/products/agent_platform/services/agent-tests/src/cases/slack-trigger.test.ts@@ -250,14 +250,19 @@ describe('slack trigger: real e2e', () => {)expect(ok.status).toBe(200)expect(ok.body.session_id).toBeTruthy()- // An untrusted envelope is still rejected.- const rejected = await c.slackPost(+ // An untrusted envelope is dropped, not enqueued — but acked 200 with a+ // drop indication, never a 4xx: a signed delivery that fails the workspace+ // allowlist is a routing decision, and providers retry non-2xx (Slack+ // redelivery storms). The drop is what matters; the status is 2xx.+ const dropped = await c.slackPost('ws-fallback','events',slackEvent({ eventType: 'message', ts: '2.0', team_id: 'T-OTHER', text: 'hello' }),SLACK_SECRET)- expect(rejected.status).toBe(403)+ expect(dropped.status).toBe(200)+ expect(dropped.body.dropped).toBe('workspace_not_trusted')+ expect(dropped.body.session_id).toBeFalsy()})it('thread_ts falls back to ts when the mention is a top-level channel message', async () => {diff --git a/products/agent_platform/services/agent-tests/src/examples/seed.py b/products/agent_platform/services/agent-tests/src/examples/seed.pyindex f57594907aa2..045f64407f0b 100755--- a/products/agent_platform/services/agent-tests/src/examples/seed.py+++ b/products/agent_platform/services/agent-tests/src/examples/seed.py@@ -105,12 +105,30 @@ METADATA: dict[str, dict[str, str]] = {# auth modes. Mirrors the declarative/intrinsic split in `spec.ts`.DECLARATIVE_TRIGGERS: set[str] = {"webhook", "chat", "mcp"}-# Secret keys each trigger type requires before promote — mirrors-# TRIGGER_REQUIRED_SECRETS in products/agent_platform/backend/spec_schema.py.-# Used only by the optional SEED_DUMMY_SECRETS placeholder path below.-TRIGGER_REQUIRED_SECRETS: dict[str, list[str]] = {- "slack": ["SLACK_SIGNING_SECRET", "SLACK_BOT_TOKEN"],-}++def _load_trigger_required_secrets() -> dict[str, list[str]]:+ """Required secret keys per trigger type, read from the checked-in+ generated artifact (`trigger_required_secrets.generated.json`, emitted+ from `services/agent-shared/src/spec/trigger-secrets.ts`) rather than+ hand-copied — the same registry `backend/logic/spec_schema.py`'s promote+ gate reads via `backend/logic/generated.py`. Only `required: true`+ entries block promote, matching that gate's filter. Used only by the+ optional SEED_DUMMY_SECRETS placeholder path below."""+ backend_logic_dir = next(+ (p / "backend" / "logic" for p in EXAMPLES_ROOT.parents if (p / "backend" / "logic").is_dir()),+ None,+ )+ if backend_logic_dir is None:+ raise RuntimeError("couldn't locate products/agent_platform/backend/logic from seed.py's path")+ artifact = backend_logic_dir / "trigger_required_secrets.generated.json"+ raw: dict[str, list[dict[str, object]]] = json.loads(artifact.read_text(encoding="utf-8"))+ return {+ trigger_type: [str(r["key"]) for r in requirements if r.get("required")]+ for trigger_type, requirements in raw.items()+ }+++TRIGGER_REQUIRED_SECRETS: dict[str, list[str]] = _load_trigger_required_secrets()# Opt-in: set obviously-fake placeholder values for any secret an agent requires# (declared `spec.secrets[]` + per-trigger required keys) that isn't alreadydiff --git a/products/agent_platform/services/agent-tools/.gitignore b/products/agent_platform/services/agent-tools/.gitignoreindex 83631f817f87..20b35bdd7d6e 100644--- a/products/agent_platform/services/agent-tools/.gitignore+++ b/products/agent_platform/services/agent-tools/.gitignore@@ -1,3 +1,5 @@dist/node_modules/*.tsbuildinfo+.coherence-out/+.coherence/diff --git a/products/agent_platform/services/agent-tools/coherence.config.json b/products/agent_platform/services/agent-tools/coherence.config.jsonnew file mode 100644index 000000000000..2c5ed58c551f--- /dev/null+++ b/products/agent_platform/services/agent-tools/coherence.config.json@@ -0,0 +1,10 @@+{+ "outputDir": ".coherence-out",+ "entryDir": "src",+ "ignore": ["node_modules", "dist", ".coherence-out"],+ "codeExt": ["ts"],+ "typecheck": ["npx", "tsc", "--noEmit", "-p", "."],+ "test": ["npx", "vitest", "run", "-t"],+ "testMatch": "[1-9][0-9]* passed",+ "language": "typescript"+}diff --git a/products/agent_platform/services/agent-tools/src/Tools.spec.md b/products/agent_platform/services/agent-tools/src/Tools.spec.mdnew file mode 100644index 000000000000..56237aa29d5f--- /dev/null+++ b/products/agent_platform/services/agent-tools/src/Tools.spec.md@@ -0,0 +1,16 @@+# Tools++Native `@posthog/*` tools the runner can dispatch, plus the intrinsic approval classification that floors how dangerous each one is allowed to be.++## invariants++- native-tool-approval-floor++## works when++- typechecks+- boundary "native-tool-approval-floor" at nativeToolApprovalClass via test "native tool authorization accessor"++## why++native-tool-approval-floor: whether a native tool needs human approval is an intrinsic property of the tool (mutating/external-effect vs read-only), not something each spec author must remember — a forgotten `requires_approval` flag used to dispatch mutating tools ungated. The class is now a REQUIRED field on every tool's definition (`NativeToolSchema.approval`), so `typechecks` makes an unclassified tool a compile error — totality enforced by the type system, not a parallel map plus a runtime test. `nativeToolApprovalClass` is the single read point: it returns each tool's co-located class and fails closed to `approve` on an id no tool declares; authors may tighten an individual ref via `requires_approval` but the resolver never loosens below the intrinsic class. The `via test` oracle iterates the live registry asserting the accessor never drifts from a tool's declared class (floored so an emptied registry can't pass vacuously).diff --git a/products/agent_platform/services/agent-tools/src/index.ts b/products/agent_platform/services/agent-tools/src/index.tsindex f2498b01bdd1..52e19cb92cc7 100644--- a/products/agent_platform/services/agent-tools/src/index.ts+++ b/products/agent_platform/services/agent-tools/src/index.ts@@ -1,3 +1,4 @@export * from './registry'+export * from './tool-authorization'export { buildWebSearchProviders, type WebSearchProviderConfig } from './tools/web-search/chain'export { WEB_SEARCH_TOOL_ID } from './tools/web-search/web-search.v1'diff --git a/products/agent_platform/services/agent-tools/src/registry.test.ts b/products/agent_platform/services/agent-tools/src/registry.test.tsindex 9f272d46073f..7cb802e9b7f5 100644--- a/products/agent_platform/services/agent-tools/src/registry.test.ts+++ b/products/agent_platform/services/agent-tools/src/registry.test.ts@@ -1,3 +1,5 @@+import { COST_HINTS } from '@posthog/agent-shared'+import { getNativeTool, hasNativeTool, listNativeTools } from './registry'describe('native tool registry', () => {@@ -50,7 +52,7 @@ describe('native tool registry', () => {expect(typeof t.schema.requires.provider.id).toBe('string')expect(Array.isArray(t.schema.requires.provider.scopes)).toBe(true)}- expect(['cheap', 'medium', 'expensive']).toContain(t.schema.cost_hint)+ expect(COST_HINTS).toContain(t.schema.cost_hint)}})})diff --git a/products/agent_platform/services/agent-tools/src/registry.ts b/products/agent_platform/services/agent-tools/src/registry.tsindex e59e033fecf0..b2d6402b3dae 100644--- a/products/agent_platform/services/agent-tools/src/registry.ts+++ b/products/agent_platform/services/agent-tools/src/registry.ts@@ -83,6 +83,7 @@ import { webSearchV1 } from './tools/web-search/web-search.v1'*/export const nativeToolsCatalogV1 = defineNativeTool({id: '@posthog/agent-applications-native-tools-list',+ approval: 'allow',description: ['List every native (@posthog/*) tool available to put in an agent spec —','id, description, the credential provider + scopes it needs, and cost hint. Call this to',diff --git a/products/agent_platform/services/agent-tools/src/tool-authorization.test.ts b/products/agent_platform/services/agent-tools/src/tool-authorization.test.tsnew file mode 100644index 000000000000..f10e7cd4001b--- /dev/null+++ b/products/agent_platform/services/agent-tools/src/tool-authorization.test.ts@@ -0,0 +1,24 @@+import { describe, expect, it } from 'vitest'++import { ALL_TOOLS } from './registry'+import { FAIL_CLOSED_NATIVE_APPROVAL, nativeToolApprovalClass } from './tool-authorization'++/**+ * Accessor behavior only — totality (every tool declares `approval`) is a+ * compile error via the required field. Verifies the accessor reads that field+ * and fails closed on an id no tool owns.+ */+describe('native tool authorization accessor', () => {+ it('returns each registered tool’s own declared class (accessor can’t drift from the field)', () => {+ // Floor: an emptied registry would make the drift filter assert nothing and+ // pass vacuously — fail loud instead.+ expect(ALL_TOOLS.length).toBeGreaterThanOrEqual(40)+ const drift = ALL_TOOLS.filter((t) => nativeToolApprovalClass(t.id) !== t.schema.approval).map((t) => t.id)+ expect(drift, `accessor disagrees with the tool’s declared approval: ${drift.join(', ')}`).toEqual([])+ })++ it('fails closed on an unregistered id', () => {+ expect(nativeToolApprovalClass('@posthog/not-a-real-tool')).toBe(FAIL_CLOSED_NATIVE_APPROVAL)+ expect(FAIL_CLOSED_NATIVE_APPROVAL).toBe('approve')+ })+})diff --git a/products/agent_platform/services/agent-tools/src/tool-authorization.ts b/products/agent_platform/services/agent-tools/src/tool-authorization.tsnew file mode 100644index 000000000000..56db71724d71--- /dev/null+++ b/products/agent_platform/services/agent-tools/src/tool-authorization.ts@@ -0,0 +1,20 @@+/**+ * id→class accessor for native-tool approval, injected into the approval+ * resolver in agent-shared (which can't import the registry without a cycle).+ * The class is declared at each tool's definition site; a spec may tighten an+ * individual ref but never loosen below it.+ */+import type { NativeApprovalClass } from '@posthog/agent-shared'++import { getNativeTool, hasNativeTool } from './registry'++export type { NativeApprovalClass }++/** Unregistered native id ⇒ gated. Fail closed. */+export const FAIL_CLOSED_NATIVE_APPROVAL: NativeApprovalClass = 'approve'++/** Intrinsic approval class for a native tool id, read from its definition.+ * Fail closed on an id no registered tool declares. */+export function nativeToolApprovalClass(id: string): NativeApprovalClass {+ return hasNativeTool(id) ? getNativeTool(id).schema.approval : FAIL_CLOSED_NATIVE_APPROVAL+}diff --git a/products/agent_platform/services/agent-tools/src/tools/http-request.v1.ts b/products/agent_platform/services/agent-tools/src/tools/http-request.v1.tsindex 940328c972e3..b4c6b019bba4 100644--- a/products/agent_platform/services/agent-tools/src/tools/http-request.v1.ts+++ b/products/agent_platform/services/agent-tools/src/tools/http-request.v1.ts@@ -217,6 +217,9 @@ async function readCappedBody(export const httpRequestV1 = defineNativeTool({id: '@posthog/http-request',+ // Proxy-bound (smokescreen blocks internal SSRF) and author-opt-in — gating+ // every outbound call would make integration automation unusable, so allow.+ approval: 'allow',description: ['Make an arbitrary HTTP request (GET/POST/PUT/PATCH/DELETE) against a URL.','Use this for any service where the platform does not ship a typed tool —',diff --git a/products/agent_platform/services/agent-tools/src/tools/identity-connect.v1.ts b/products/agent_platform/services/agent-tools/src/tools/identity-connect.v1.tsindex ab7467805b61..a3b6abccb08f 100644--- a/products/agent_platform/services/agent-tools/src/tools/identity-connect.v1.ts+++ b/products/agent_platform/services/agent-tools/src/tools/identity-connect.v1.ts@@ -15,6 +15,7 @@ import { defineNativeTool, Type } from '@posthog/agent-shared'export const identityConnectV1 = defineNativeTool({id: '@posthog/identity-connect',+ approval: 'approve',description:'Generate a connect or reconnect link for an identity provider so the user can authorize ' +'(or re-authorize) their account. Call this whenever the user asks to connect, reconnect, ' +diff --git a/products/agent_platform/services/agent-tools/src/tools/identity-fetch.v1.ts b/products/agent_platform/services/agent-tools/src/tools/identity-fetch.v1.tsindex 0ee6ba315d6f..e9233c733bee 100644--- a/products/agent_platform/services/agent-tools/src/tools/identity-fetch.v1.ts+++ b/products/agent_platform/services/agent-tools/src/tools/identity-fetch.v1.ts@@ -10,6 +10,7 @@ import { defineNativeTool, Type } from '@posthog/agent-shared'export const identityFetchV1 = defineNativeTool({id: '@posthog/identity-fetch',+ approval: 'allow',description:"Call a linked identity provider's API as the current user. If the user hasn't " +'linked that provider yet, returns an `auth_required` link to send them. The URL ' +diff --git a/products/agent_platform/services/agent-tools/src/tools/load-skill.ts b/products/agent_platform/services/agent-tools/src/tools/load-skill.tsindex 8869af9387a0..d27e16c414ea 100644--- a/products/agent_platform/services/agent-tools/src/tools/load-skill.ts+++ b/products/agent_platform/services/agent-tools/src/tools/load-skill.ts@@ -48,6 +48,7 @@ export function resolveSkillFile(skillPath: string, file: string): string {export const loadSkill = defineNativeTool({id: '@posthog/load-skill',+ approval: 'allow',description:'Fetch the body of a skill from this agent\'s bundle. Use the `id` from the "Available skills" index in the system prompt. Pass `file` to fetch a companion file inside the skill folder (e.g. `references/api.md`, `scripts/run.py`) when the skill body points at one. Returns the content; treat a skill body as additional instructions for the current task.',args: Type.Object({diff --git a/products/agent_platform/services/agent-tools/src/tools/memory.ts b/products/agent_platform/services/agent-tools/src/tools/memory.tsindex 6a721d41157b..0220e51195a7 100644--- a/products/agent_platform/services/agent-tools/src/tools/memory.ts+++ b/products/agent_platform/services/agent-tools/src/tools/memory.ts@@ -82,6 +82,7 @@ function asError(thrown: unknown): string {export const memoryListV1 = defineNativeTool({id: '@posthog/memory-list',+ approval: 'allow',description:'List memory files this agent has stored. Returns one entry per file with its path and short description (no body). Optional `prefix` narrows to a sub-folder, e.g. `incidents/`.',args: Type.Object({@@ -117,6 +118,7 @@ export const memoryListV1 = defineNativeTool({export const memorySearchV1 = defineNativeTool({id: '@posthog/memory-search',+ approval: 'allow',description:"Substring + tag/path weighted search across this agent's memory files. Describe what you're looking for in plain language — the cue is tokenised and scored against descriptions, tags, paths, and bodies. Returns top matches with a one-line snippet.",args: Type.Object({@@ -145,6 +147,7 @@ export const memorySearchV1 = defineNativeTool({export const memoryReadV1 = defineNativeTool({id: '@posthog/memory-read',+ approval: 'allow',description:'Read one memory file in full — returns its description, tags, timestamps, and full markdown body. Use after `memory-list` or `memory-search` returns a path.',args: Type.Object({@@ -180,6 +183,7 @@ export const memoryReadV1 = defineNativeTool({export const memoryWriteV1 = defineNativeTool({id: '@posthog/memory-write',+ approval: 'allow',description:'Create a new memory file. `description` is a one-line summary (<= 280 chars). `content` is the full markdown body. Fails if a file already exists at `path` — use `memory-update` to overwrite. WRITE OPERATIONS ARE APPROVAL-GATED BY DEFAULT — the model will see a synthetic queued result until a human approves.',args: Type.Object({@@ -226,6 +230,7 @@ export const memoryWriteV1 = defineNativeTool({export const memoryUpdateV1 = defineNativeTool({id: '@posthog/memory-update',+ approval: 'allow',description:'Overwrite an existing memory file. Any field omitted is taken from the existing file. Fails if the file does not exist. WRITE OPERATIONS ARE APPROVAL-GATED BY DEFAULT.',args: Type.Object({@@ -267,6 +272,7 @@ export const memoryUpdateV1 = defineNativeTool({export const memoryDeleteV1 = defineNativeTool({id: '@posthog/memory-delete',+ approval: 'allow',description: 'Hard-delete a memory file. APPROVAL-GATED BY DEFAULT.',args: Type.Object({path: Type.String(),diff --git a/products/agent_platform/services/agent-tools/src/tools/meta.ts b/products/agent_platform/services/agent-tools/src/tools/meta.tsindex 7c948ffcd1a5..d59661a5be55 100644--- a/products/agent_platform/services/agent-tools/src/tools/meta.ts+++ b/products/agent_platform/services/agent-tools/src/tools/meta.ts@@ -24,6 +24,7 @@ import { defineNativeTool, Type } from '@posthog/agent-shared'export const endTurnTool = defineNativeTool({id: '@posthog/meta-end-turn',+ approval: 'allow',description:'Finish the current turn. The user can still send follow-up messages — this is the default polite stop. Use this whenever you have nothing more to add for now, including when you need the user to answer a question (write the question as your reply, then end the turn). Use meta-end-session instead only when the agent task is truly complete.',args: Type.Object({}),@@ -38,6 +39,7 @@ export const endTurnTool = defineNativeTool({export const endSessionTool = defineNativeTool({id: '@posthog/meta-end-session',+ approval: 'allow',description:'Hard close the agent session. The user can NOT send further messages unless the agent is configured with allow_restart. Only use this when the agent task is irreversibly complete; otherwise prefer meta-end-turn.',args: Type.Object({@@ -53,6 +55,7 @@ export const endSessionTool = defineNativeTool({export const emitEventTool = defineNativeTool({id: '@posthog/meta-emit-event',+ approval: 'allow',description: "Emit a structured event into the team's PostHog project.",args: Type.Object({event: Type.String(),diff --git a/products/agent_platform/services/agent-tools/src/tools/native-tools-catalog.v1.test.ts b/products/agent_platform/services/agent-tools/src/tools/native-tools-catalog.v1.test.tsindex a9784de9892a..ae0cadc5bc9d 100644--- a/products/agent_platform/services/agent-tools/src/tools/native-tools-catalog.v1.test.ts+++ b/products/agent_platform/services/agent-tools/src/tools/native-tools-catalog.v1.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from 'vitest'-import type { ToolContext } from '@posthog/agent-shared'+import { COST_HINTS, type ToolContext } from '@posthog/agent-shared'import { listNativeTools, nativeToolsCatalogV1 } from '../registry'@@ -15,7 +15,7 @@ describe('@posthog/agent-applications-native-tools-list', () => {expect(query).not.toBeUndefined()expect(typeof query!.description).toBe('string')expect(query!.requires.provider).toEqual({ id: 'posthog', scopes: ['query:read'] })- expect(['cheap', 'medium', 'expensive']).toContain(query!.cost_hint)+ expect(COST_HINTS).toContain(query!.cost_hint)// The catalog tool lists itself — it's a real available tool.expect(byId.has('@posthog/agent-applications-native-tools-list')).toBe(true)})diff --git a/products/agent_platform/services/agent-tools/src/tools/posthog-agent-management.v1.ts b/products/agent_platform/services/agent-tools/src/tools/posthog-agent-management.v1.tsindex bef95e992376..e5ece9e50c2d 100644--- a/products/agent_platform/services/agent-tools/src/tools/posthog-agent-management.v1.ts+++ b/products/agent_platform/services/agent-tools/src/tools/posthog-agent-management.v1.ts@@ -108,6 +108,7 @@ const agentRefFields = {export const posthogAgentApplicationsListV1 = defineNativeTool({id: '@posthog/agent-applications-list',+ approval: 'allow',description:"List every agent application the connected user can see in this project. Returns id, slug, name, description, live_revision. Use when the user asks 'what agents do I have?' / 'show me my agents'.",args: Type.Object({@@ -129,6 +130,7 @@ export const posthogAgentApplicationsListV1 = defineNativeTool({export const posthogAgentApplicationsRetrieveV1 = defineNativeTool({id: '@posthog/agent-applications-retrieve',+ approval: 'allow',description:'Get the full record of one agent application by slug or id. Returns its name, description, current live_revision, archived state. Use as step 1 of inspecting any agent.',args: Type.Object({ project_id: ProjectIdArg, ...agentRefFields }),@@ -163,6 +165,7 @@ const RevisionSchema = Type.Object({export const posthogAgentApplicationsRevisionsListV1 = defineNativeTool({id: '@posthog/agent-applications-revisions-list',+ approval: 'allow',description:"List every revision of one agent in chronological order — draft, ready, live, archived. Use to see the agent's edit history or to find a specific revision to inspect.",args: Type.Object({ project_id: ProjectIdArg, ...agentRefFields }),@@ -181,6 +184,7 @@ export const posthogAgentApplicationsRevisionsListV1 = defineNativeTool({export const posthogAgentApplicationsRevisionsRetrieveV1 = defineNativeTool({id: '@posthog/agent-applications-revisions-retrieve',+ approval: 'allow',description:'Get a specific revision of an agent. Returns the full spec (model, triggers, tools, skills, limits, auth) plus the bundle_sha256 + state. Use to inspect what an agent is configured to do.',args: Type.Object({@@ -202,6 +206,7 @@ export const posthogAgentApplicationsRevisionsRetrieveV1 = defineNativeTool({export const posthogAgentApplicationsRevisionsSystemPromptV1 = defineNativeTool({id: '@posthog/agent-applications-revisions-system-prompt',+ approval: 'allow',description:'Get the fully-rendered system prompt for a revision — what the model actually sees on every turn (framework preamble + agent.md + skills index). The single most informative artifact when explaining what an agent does.',args: Type.Object({@@ -236,6 +241,7 @@ const ManifestFileSchema = Type.Object({export const posthogAgentApplicationsRevisionsManifestV1 = defineNativeTool({id: '@posthog/agent-applications-revisions-manifest-retrieve',+ approval: 'allow',description:"List every file in a revision's bundle (path + size + sha256). Use to see the bundle layout before pulling specific files. Cheap — no file content returned.",args: Type.Object({@@ -262,6 +268,7 @@ export const posthogAgentApplicationsRevisionsManifestV1 = defineNativeTool({export const posthogAgentApplicationsRevisionsBundleRetrieveV1 = defineNativeTool({id: '@posthog/agent-applications-revisions-bundle-retrieve',+ approval: 'allow',description:"Read the full typed bundle for a revision. Returns `{ agent_md, skills, tools, spec }` — the agent's system prompt, every skill body + companion files, every custom tool's source + args_schema, and the author-facing spec slice. Use this when you want to inspect or edit the whole agent. Works on any revision state.",args: Type.Object({@@ -283,6 +290,7 @@ export const posthogAgentApplicationsRevisionsBundleRetrieveV1 = defineNativeTooexport const posthogAgentApplicationsRevisionsSlackManifestV1 = defineNativeTool({id: '@posthog/agent-applications-revisions-slack-manifest',+ approval: 'allow',description:"Generate the Slack app manifest for a revision that has a slack trigger. Returns `{ revision_id, manifest, notes, events_url, interactivity_url }`. `manifest` is a ready-to-paste Slack app manifest (JSON) for https://api.slack.com/apps?new_app=1 → 'From an app manifest' — its OAuth scopes and bot event subscriptions are DERIVED from the agent's slack trigger config (mention_only / auto_resume_threads / ack_reaction) and its Slack tools, so it subscribes to exactly the events the config needs. Hand the user the manifest plus the create-from-manifest link, and surface `notes` (e.g. invite the bot to its channels). Fails if the revision has no slack trigger.",args: Type.Object({@@ -327,6 +335,7 @@ const SessionSummarySchema = Type.Object({export const posthogAgentApplicationsSessionsListV1 = defineNativeTool({id: '@posthog/agent-applications-sessions-list',+ approval: 'allow',description:'List recent sessions for an agent. Returns state, created_at, usage_total per session. Use to see what an agent has been doing or to find a specific session to debug.',args: Type.Object({@@ -358,6 +367,7 @@ export const posthogAgentApplicationsSessionsListV1 = defineNativeTool({export const posthogAgentApplicationsSessionsRetrieveV1 = defineNativeTool({id: '@posthog/agent-applications-sessions-retrieve',+ approval: 'allow',description:'Get the full record of one session, including its conversation (all user/assistant/tool turns), principal, usage_total, and state. The primary tool for debugging a specific session.',args: Type.Object({@@ -387,6 +397,7 @@ export const posthogAgentApplicationsSessionsRetrieveV1 = defineNativeTool({export const posthogAgentApplicationsCreateV1 = defineNativeTool({id: '@posthog/agent-applications-create',+ approval: 'approve',description:'Mint a brand-new agent application. Body requires `name` + `slug`; description is optional. Returns the created application — no revisions until you create one with `@posthog/agent-applications-revisions-create`.',args: Type.Object({@@ -421,6 +432,7 @@ export const posthogAgentApplicationsCreateV1 = defineNativeTool({export const posthogAgentApplicationsPartialUpdateV1 = defineNativeTool({id: '@posthog/agent-applications-partial-update',+ approval: 'approve',description:'Patch the top-level fields of an agent application (`name`, `description`). To change the live revision use the freeze + promote tools; to manage env use `set-env-create`.',args: Type.Object({@@ -455,6 +467,7 @@ export const posthogAgentApplicationsPartialUpdateV1 = defineNativeTool({export const posthogAgentApplicationsRevisionsCreateV1 = defineNativeTool({id: '@posthog/agent-applications-revisions-create',+ approval: 'approve',description:'Open a fresh empty draft revision under an application. Use when starting from scratch (no parent revision). For branching the current live revision use `@posthog/agent-applications-revisions-new-draft-create` instead — that one clones the bundle in the same call.',args: Type.Object({@@ -487,6 +500,7 @@ export const posthogAgentApplicationsRevisionsCreateV1 = defineNativeTool({export const posthogAgentApplicationsRevisionsNewDraftV1 = defineNativeTool({id: '@posthog/agent-applications-revisions-new-draft-create',+ approval: 'approve',description:'One-shot helper: creates a draft revision and clones every file from `source_revision_id` into the new bundle in a single round-trip. Use for the common "edit live" workflow — branch from current live, mutate files, freeze, promote.',args: Type.Object({@@ -509,6 +523,7 @@ export const posthogAgentApplicationsRevisionsNewDraftV1 = defineNativeTool({export const posthogAgentApplicationsRevisionsPartialUpdateV1 = defineNativeTool({id: '@posthog/agent-applications-revisions-partial-update',+ approval: 'approve',description:'Replace `spec` on a draft revision. Only `state=draft` accepts spec edits — promoting flips to `ready` which freezes the spec. Validation against AgentSpec runs server-side; an invalid spec surfaces at the next session start, not here.',args: Type.Object({@@ -541,6 +556,7 @@ export const posthogAgentApplicationsRevisionsPartialUpdateV1 = defineNativeToolexport const posthogAgentApplicationsRevisionsAgentMdUpdateV1 = defineNativeTool({id: '@posthog/agent-applications-revisions-agent-md-update',+ approval: 'approve',description: "Replace the agent's system prompt (`agent.md`). Draft-only.",args: Type.Object({project_id: ProjectIdArg,@@ -568,6 +584,7 @@ export const posthogAgentApplicationsRevisionsAgentMdUpdateV1 = defineNativeTool// attach them with `@posthog/agent-applications-revisions-skill-refs-set`.export const posthogAgentApplicationsRevisionsSkillRefsSetV1 = defineNativeTool({id: '@posthog/agent-applications-revisions-skill-refs-set',+ approval: 'approve',description:"Set the complete list of store-skill references on a draft revision (full replace). Each ref is `{ from_template, alias, version? }`: `from_template` is the skill NAME in the llma-skill store, `alias` is the folder it's materialized under in the bundle (`skills/<alias>/`), `version` optionally pins a published version (omit to pin the latest at freeze). At freeze the referenced skills are resolved and baked into the bundle. Find skills with `@posthog/llm-skills-search`; author a new one with `@posthog/llm-skills-create`. Draft-only.",args: Type.Object({@@ -603,6 +620,7 @@ export const posthogAgentApplicationsRevisionsSkillRefsSetV1 = defineNativeTool(export const posthogLlmSkillsSearchV1 = defineNativeTool({id: '@posthog/llm-skills-search',+ approval: 'allow',description:'Search the llma-skill store for reusable skills in this project. Returns name, description, version, category per match. Use to find a skill to attach to an agent (via `@posthog/agent-applications-revisions-skill-refs-set`) before authoring a new one.',args: Type.Object({@@ -626,6 +644,7 @@ export const posthogLlmSkillsSearchV1 = defineNativeTool({export const posthogLlmSkillsCreateV1 = defineNativeTool({id: '@posthog/llm-skills-create',+ approval: 'approve',description:'Author a new skill in the llma-skill store — the canonical place skills live. Provide `name` (stable id across versions), `description` (when-to-load hint shown in the agent skill index), `body` (SKILL.md markdown), and optional `files` (companion docs). Returns the created skill. Attach it to an agent with `@posthog/agent-applications-revisions-skill-refs-set`.',args: Type.Object({@@ -653,6 +672,7 @@ export const posthogLlmSkillsCreateV1 = defineNativeTool({export const posthogAgentApplicationsRevisionsToolsUpdateV1 = defineNativeTool({id: '@posthog/agent-applications-revisions-tools-update',+ approval: 'approve',description:"Upsert one custom tool in a draft revision. The janitor runs an AST shape check + esbuild compile synchronously and returns 422 with structured diagnostics on failure — no half-written tool ever lands. Required source shape: `export default { actions: { default: async (args, ctx) => { ... } } }`. Do NOT include `compiled.js` — it's generated.",args: Type.Object({@@ -684,6 +704,7 @@ export const posthogAgentApplicationsRevisionsToolsUpdateV1 = defineNativeTool({export const posthogAgentApplicationsRevisionsToolsDestroyV1 = defineNativeTool({id: '@posthog/agent-applications-revisions-tools-destroy',+ approval: 'approve',description: 'Delete one custom tool (source.ts + compiled.js + schema.json). Draft-only.',args: Type.Object({project_id: ProjectIdArg,@@ -708,6 +729,7 @@ export const posthogAgentApplicationsRevisionsToolsDestroyV1 = defineNativeTool(export const posthogAgentApplicationsRevisionsValidateV1 = defineNativeTool({id: '@posthog/agent-applications-revisions-validate-create',+ approval: 'approve',description:"Pre-flight check on any revision state. Surfaces missing entrypoints, unknown tool ids, custom tools missing compiled.js / schema.json, skill paths that don't exist, declared secrets that aren't set. Always run before freeze. Returns `{ ok, errors, resolved_natives }`.",args: Type.Object({@@ -735,6 +757,7 @@ export const posthogAgentApplicationsRevisionsValidateV1 = defineNativeTool({export const posthogAgentApplicationsRevisionsFreezeV1 = defineNativeTool({id: '@posthog/agent-applications-revisions-freeze-create',+ approval: 'approve',description:'Walk the bundle, compute a manifest sha256, stamp it on the row, flip state `draft → ready`. After freeze the bundle is immutable. Idempotent — freezing a `ready` revision returns the existing sha256.',args: Type.Object({@@ -761,6 +784,7 @@ export const posthogAgentApplicationsRevisionsFreezeV1 = defineNativeTool({export const posthogAgentApplicationsRevisionsPromoteV1 = defineNativeTool({id: '@posthog/agent-applications-revisions-promote-create',+ approval: 'approve',description:"Flip a `ready` revision to `live` and set the parent application's `live_revision`. The previously-live revision is archived automatically. Requires `state=ready` and `bundle_sha256` set (call `freeze` first). Idempotent. SERVER-SIDE GATE: refuses with a clear error if trigger-required secrets (e.g. `SLACK_SIGNING_SECRET`, `SLACK_BOT_TOKEN` for slack triggers) are missing from the agent's `encrypted_env` — see `skills/setting-up-slack-app`. PER AGENT.MD HARD RULE #3: confirm with the user explicitly before calling.",args: Type.Object({@@ -782,6 +806,7 @@ export const posthogAgentApplicationsRevisionsPromoteV1 = defineNativeTool({export const posthogAgentApplicationsRevisionsArchiveV1 = defineNativeTool({id: '@posthog/agent-applications-revisions-archive-create',+ approval: 'approve',description:"Archive any revision. Clears the parent application's `live_revision` if the archived revision was live. DESTRUCTIVE per agent.md hard rule #5 — confirm with the user before calling.",args: Type.Object({@@ -821,6 +846,7 @@ const EnvKeyRowSchema = Type.Object({export const posthogAgentApplicationsEnvKeysListV1 = defineNativeTool({id: '@posthog/agent-applications-env-keys-list',+ approval: 'allow',description:'List every encrypted_env key set on an agent, with `is_set` per row. Does NOT return the values — those are encrypted at rest and never read back through this surface. Use to audit which secrets the agent has configured before freeze + promote.',args: Type.Object({ project_id: ProjectIdArg, ...agentRefFields }),@@ -838,6 +864,7 @@ export const posthogAgentApplicationsEnvKeysListV1 = defineNativeTool({export const posthogAgentApplicationsEnvKeysGetV1 = defineNativeTool({id: '@posthog/agent-applications-env-keys-get',+ approval: 'allow',description:'Probe whether a single encrypted_env key is set on an agent. Returns `{ key, is_set }`. Never returns the value. Use as the precheck before triggering the `set_secret` punch-out flow.',args: Type.Object({@@ -859,6 +886,7 @@ export const posthogAgentApplicationsEnvKeysGetV1 = defineNativeTool({export const posthogAgentApplicationsSetEnvV1 = defineNativeTool({id: '@posthog/agent-applications-set-env-create',+ approval: 'approve',description:'Replace the entire encrypted_env block. WARNING: puts secret values in the session tool-call history. Per `skills/secrets-and-integrations`, prefer the `set_secret` client tool (UI punch-out, never logs values). Use this raw API only when the user explicitly opts in (broken punch-out, CI script, etc.) — confirm before calling and warn about the trace.',args: Type.Object({@@ -884,6 +912,7 @@ export const posthogAgentApplicationsSetEnvV1 = defineNativeTool({export const posthogAgentApplicationsSessionLogsV1 = defineNativeTool({id: '@posthog/agent-applications-session-logs',+ approval: 'allow',description:"Get the structured event log for a session — session_started, turn_started, tool_call, tool_result, completed/failed events. Use after sessions-retrieve when you need turn-by-turn timing or error events the conversation doesn't carry.",args: Type.Object({diff --git a/products/agent_platform/services/agent-tools/src/tools/posthog-projects.v1.ts b/products/agent_platform/services/agent-tools/src/tools/posthog-projects.v1.tsindex d62185916c00..5ac21dce5bc1 100644--- a/products/agent_platform/services/agent-tools/src/tools/posthog-projects.v1.ts+++ b/products/agent_platform/services/agent-tools/src/tools/posthog-projects.v1.ts@@ -37,6 +37,7 @@ interface MeResponse {*/export const posthogListProjectsV1 = defineNativeTool({id: '@posthog/list-projects',+ approval: 'allow',description:"List the PostHog projects the connected user can access — id, name, and organization only. Use to resolve which project to act in when `get_context` didn't supply a `project_id` or the user's intent is ambiguous: present the list, ask the user to choose, then pass the chosen `project_id` to the other `@posthog/*` tools. Don't guess a project id.",args: Type.Object({}),diff --git a/products/agent_platform/services/agent-tools/src/tools/posthog-query.v1.ts b/products/agent_platform/services/agent-tools/src/tools/posthog-query.v1.tsindex 288909f84151..09101fafbe49 100644--- a/products/agent_platform/services/agent-tools/src/tools/posthog-query.v1.ts+++ b/products/agent_platform/services/agent-tools/src/tools/posthog-query.v1.ts@@ -15,6 +15,7 @@ interface HogQLQueryResponse {export const posthogQueryV1 = defineNativeTool({id: '@posthog/query',+ approval: 'allow',description:'Run a HogQL query against a PostHog project as the connected user (requires `posthog` auth). Returns rows and column names. Pass the `project_id` of the project to query.',args: Type.Object({diff --git a/products/agent_platform/services/agent-tools/src/tools/slack.v1.ts b/products/agent_platform/services/agent-tools/src/tools/slack.v1.tsindex 63372fe563f7..46f581f57daa 100644--- a/products/agent_platform/services/agent-tools/src/tools/slack.v1.ts+++ b/products/agent_platform/services/agent-tools/src/tools/slack.v1.ts@@ -110,6 +110,7 @@ function projectMessage(m: RawSlackMessage): {export const slackPostMessageV1 = defineNativeTool({id: '@posthog/slack-post-message',+ approval: 'allow',description: "Post a message to a Slack channel or thread using the agent's bot token.",args: Type.Object({channel: Type.String(),@@ -135,6 +136,7 @@ export const slackPostMessageV1 = defineNativeTool({export const slackUpdateMessageV1 = defineNativeTool({id: '@posthog/slack-update-message',+ approval: 'allow',description: 'Edit a previously-posted Slack message.',args: Type.Object({channel: Type.String(),@@ -153,6 +155,7 @@ export const slackUpdateMessageV1 = defineNativeTool({export const slackReadChannelV1 = defineNativeTool({id: '@posthog/slack-read-channel',+ approval: 'allow',description:'Read recent messages from a Slack channel. Returns top-level messages only (use @posthog/slack-read-thread for replies). Paginate with next_cursor; narrow with oldest/latest (slack ts).',args: Type.Object({@@ -198,6 +201,7 @@ export const slackReadChannelV1 = defineNativeTool({export const slackReadThreadV1 = defineNativeTool({id: '@posthog/slack-read-thread',+ approval: 'allow',description: 'Read a Slack thread — the parent message plus all replies. thread_ts is the parent message ts.',args: Type.Object({channel: Type.String(),@@ -239,6 +243,7 @@ export const slackReadThreadV1 = defineNativeTool({export const slackReactV1 = defineNativeTool({id: '@posthog/slack-react',+ approval: 'allow',description: 'Add an emoji reaction to a Slack message.',args: Type.Object({channel: Type.String(),diff --git a/products/agent_platform/services/agent-tools/src/tools/table.ts b/products/agent_platform/services/agent-tools/src/tools/table.tsindex 160389391e2a..de06d94294dc 100644--- a/products/agent_platform/services/agent-tools/src/tools/table.ts+++ b/products/agent_platform/services/agent-tools/src/tools/table.ts@@ -68,6 +68,7 @@ const WHERE = Type.Record(Type.String(), Type.Unknown(), {export const tableMembershipV1 = defineNativeTool({id: '@posthog/table-membership',+ approval: 'allow',description:'Partition `values` into those already present in `key_column` of the table and those not yet seen. The deterministic seen-set check: pass a batch of ids, get back only the `new` ones to process. Cheap regardless of table size; the table contents never enter your context.',args: Type.Object({@@ -93,6 +94,7 @@ export const tableMembershipV1 = defineNativeTool({export const tableAppendV1 = defineNativeTool({id: '@posthog/table-append',+ approval: 'allow',description:'Append rows (JSON objects) to a table, creating it if needed. With `dedupe_on`, rows whose value in that column already exists are skipped (returns counts). Use for seen-sets and append-only logs.',args: Type.Object({@@ -120,6 +122,7 @@ export const tableAppendV1 = defineNativeTool({export const tableQueryV1 = defineNativeTool({id: '@posthog/table-query',+ approval: 'allow',description:'Read rows from a table, filtered by `where`, optionally projected to `columns`, ordered, and limited. Returns the matching rows.',args: Type.Object({@@ -154,6 +157,7 @@ export const tableQueryV1 = defineNativeTool({export const tableCountV1 = defineNativeTool({id: '@posthog/table-count',+ approval: 'allow',description: 'Count rows in a table matching `where` (or all rows if omitted).',args: Type.Object({ table: TABLE, where: Type.Optional(WHERE) }),returns: RESULT,@@ -173,6 +177,7 @@ export const tableCountV1 = defineNativeTool({export const tableDeleteV1 = defineNativeTool({id: '@posthog/table-delete',+ approval: 'allow',description: 'Delete rows from a table matching `where` (required). Returns how many were removed.',args: Type.Object({ table: TABLE, where: WHERE }),returns: RESULT,@@ -192,6 +197,7 @@ export const tableDeleteV1 = defineNativeTool({export const tableTruncateV1 = defineNativeTool({id: '@posthog/table-truncate',+ approval: 'allow',description: 'Remove an entire table (all rows). Use to reset state.',args: Type.Object({ table: TABLE }),returns: RESULT,diff --git a/products/agent_platform/services/agent-tools/src/tools/web-search/web-search.v1.ts b/products/agent_platform/services/agent-tools/src/tools/web-search/web-search.v1.tsindex 0ed2ccfbab84..95c3c68859a9 100644--- a/products/agent_platform/services/agent-tools/src/tools/web-search/web-search.v1.ts+++ b/products/agent_platform/services/agent-tools/src/tools/web-search/web-search.v1.ts@@ -42,6 +42,7 @@ export const webSearchV1 = defineNativeTool({}),requires: {},cost_hint: 'medium',+ approval: 'allow',async run(args, ctx) {const { results, provider } = await searchWithFallback(ctx.webSearchProviders ?? [],diff --git a/products/mcp_store/backend/facade/api.py b/products/mcp_store/backend/facade/api.pyindex bf47f7b0b9aa..2616d1a80898 100644--- a/products/mcp_store/backend/facade/api.py+++ b/products/mcp_store/backend/facade/api.py@@ -4,6 +4,9 @@ Facade API for mcp_store.This is the ONLY module other apps are allowed to import."""+import uuid+from collections.abc import Iterable+from django.db.models import Qimport structlog@@ -14,6 +17,38 @@ from products.mcp_store.backend.models import MCPServerInstallationlogger = structlog.get_logger(__name__)+def unauthorized_installation_ids(team_id: int, user_id: int, candidate_ids: Iterable[str]) -> list[str]:+ """Return the subset of `candidate_ids` the caller must REJECT — installation+ ids not owned by this (team, user). Ownership is keyed by `(team_id, user_id)`+ because `MCPServerInstallation` is user-scoped: an installation's stored bearer+ belongs to the user who connected it. Callers use this to authorize a *reference*+ to a shared connection (e.g. `spec.mcps[].connection`) so a user can't point an+ agent at a teammate's stored credential by guessing its UUID.++ Ownership-only — does not filter on enabled/ready state. An id that is invalid,+ unknown, or owned by someone else is returned as unauthorized, so callers fail+ closed by rejecting any id this returns.+ """+ candidates = [str(c) for c in candidate_ids if c]+ if not candidates:+ return []+ parsed: dict[str, uuid.UUID | None] = {}+ for c in candidates:+ try:+ parsed[c] = uuid.UUID(c)+ except (ValueError, TypeError):+ parsed[c] = None+ owned = {+ str(r)+ for r in MCPServerInstallation.objects.filter(+ team_id=team_id,+ user_id=user_id,+ id__in=[u for u in parsed.values() if u is not None],+ ).values_list("id", flat=True)+ }+ return [c for c, u in parsed.items() if u is None or str(u) not in owned]++def _resolve_name(installation: MCPServerInstallation) -> str:if installation.display_name:return installation.display_namediff --git a/pyproject.toml b/pyproject.tomlindex 17d1e0a83e77..d26ac131477f 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -517,6 +517,7 @@ ignore_imports = [# TODO: existing violations — fix by routing through facade"products.agent_platform.backend.presentation.serializers -> products.agent_platform.backend.models","products.agent_platform.backend.presentation.views -> products.agent_platform.backend.db",+ "products.agent_platform.backend.presentation.views -> products.agent_platform.backend.logic.generated","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",diff --git a/tach.toml b/tach.tomlindex a5fb1c50cba8..8575adcbae6d 100644--- a/tach.toml+++ b/tach.toml@@ -151,6 +151,7 @@ layer = "modules"path = "products.agent_platform"depends_on = ["posthog",+ "products.mcp_store","products.skills",]layer = "modules"