:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(signals): add optional expires_at to scout scratchpad memories (#87491)
posthog[bot]efbdcd8e80fd
diff --git a/products/signals/ARCHITECTURE.md b/products/signals/ARCHITECTURE.mdindex c98158f2c2cd..ea2ec49e491e 100644--- a/products/signals/ARCHITECTURE.md+++ b/products/signals/ARCHITECTURE.md@@ -596,18 +596,21 @@ Thin bridge from a Tasks `TaskRun` to the scout skill that ran inside it: one scNarrow per-team scratchpad surface the scout fleet writes during runs and reads back on future runs (known issues, false positives, dedupe fingerprints, learned team quirks). Distinct from `SignalProjectProfile`: profile is _deterministic ground truth_, scratchpad is the _scout's inferred learnings_ (possibly wrong). MCP-readable across agents so PostHog AI and other scouts can see what the fleet has learned about a team.-| Field | Type | Description |-| ---------------- | ------------------------------ | ----------------------------------------------------------------------------------------- |-| `team` | FK → Team | Owning team (`related_name="signal_scratchpads"`) |-| `key` | CharField(300) | Semantic key, agent-chosen; unique per team |-| `content` | TextField | Prose for prompt injection — the agent reads this verbatim |-| `created_by_run` | FK → SignalScoutRun (SET_NULL) | The run that wrote this entry; `SET_NULL` so deleting a run row doesn't destroy the entry |-| `created_at` | DateTime | Auto-set on creation |-| `updated_at` | DateTime | Auto-set on save |+| Field | Type | Description |+| ---------------- | ------------------------------ | ------------------------------------------------------------------------------------------------ |+| `team` | FK → Team | Owning team (`related_name="signal_scratchpads"`) |+| `key` | CharField(300) | Semantic key, agent-chosen; unique per team |+| `content` | TextField | Prose for prompt injection — the agent reads this verbatim |+| `created_by_run` | FK → SignalScoutRun (SET_NULL) | The run that wrote this entry; `SET_NULL` so deleting a run row doesn't destroy the entry |+| `expires_at` | DateTime (nullable) | Optional TTL — null (the default) is durable; past expiry drops the row from `search_scratchpad` |+| `created_at` | DateTime | Auto-set on creation |+| `updated_at` | DateTime | Auto-set on save |**Constraints:** Unique on `(team, key)`.-`authority`, `tags`, and `expires_at` (with their backing GIN / expiry indexes) were dropped in the PR2 review simplification — retrieval is now plain ILIKE over `key` + `content`, and every entry is durable per-team scratchpad.+`authority` and `tags` (with their backing GIN index) were dropped in the PR2 review simplification — retrieval is now plain ILIKE over `key` + `content`.++`expires_at` was dropped in that same pass and later restored: a scout that wrote a time-boxed memory almost never came back to `forget` it, so stale entries kept loading into run prompts. Entries stay durable by default. Expiry hides a row from `search_scratchpad` (`include_expired=True` is the human audit path); it never deletes one, so the key stays taken and both `forget` and the `remember` upsert still find it. `remember` writes the whole entry, so a write that omits `expires_at` clears an expiry an earlier write set. A `followup:` key may not carry one — `remember` rejects that, since an expired follow-up would vanish from the self-validation queue before the scout could work it.### `SignalProjectProfile`diff --git a/products/signals/backend/migrations/0105_signalscratchpad_expires_at.py b/products/signals/backend/migrations/0105_signalscratchpad_expires_at.pynew file mode 100644index 000000000000..e1cf09818e6b--- /dev/null+++ b/products/signals/backend/migrations/0105_signalscratchpad_expires_at.py@@ -0,0 +1,17 @@+# Generated by Django 5.2.17 on 2026-08-22 20:28++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("signals", "0104_signalreport_suggested_prompts"),+ ]++ operations = [+ migrations.AddField(+ model_name="signalscratchpad",+ name="expires_at",+ field=models.DateTimeField(blank=True, null=True),+ ),+ ]diff --git a/products/signals/backend/migrations/max_migration.txt b/products/signals/backend/migrations/max_migration.txtindex edf6a67f966f..6db4da4013f6 100644--- a/products/signals/backend/migrations/max_migration.txt+++ b/products/signals/backend/migrations/max_migration.txt@@ -1 +1 @@-0104_signalreport_suggested_prompts+0105_signalscratchpad_expires_atdiff --git a/products/signals/backend/models.py b/products/signals/backend/models.pyindex c447e6c344fe..87b2c789fa93 100644--- a/products/signals/backend/models.py+++ b/products/signals/backend/models.py@@ -1923,6 +1923,13 @@ class SignalScratchpad(TeamScopedRootMixin, UUIDModel):embedded snippets, neither of which fits the scout's per-key cross-agentread pattern. Kept narrow to the scouts feature on purpose; not a sharedprimitive.++ Most entries are durable, so `expires_at` is nullable and unset by default. It+ exists for the memories that are true only for a while — a cooldown, a window to+ watch — which a scout would otherwise have to come back and `forget` by hand.+ Expiry hides a row from `search_scratchpad`, it does not delete it: the key stays+ taken (so the upsert keeps working) and a human auditing the fleet's memory can+ still read it back with `include_expired`."""# See SignalScoutConfig.all_teams for rationale.@@ -1946,6 +1953,9 @@ class SignalScratchpad(TeamScopedRootMixin, UUIDModel):blank=True,related_name="scratchpads_created",)+ # Null = durable (the default). Set to drop the entry out of scout searches once+ # its shelf life is up. Mirrors `SignalScoutNote.expires_at`.+ expires_at = models.DateTimeField(null=True, blank=True)created_at = models.DateTimeField(auto_now_add=True)updated_at = models.DateTimeField(auto_now=True)diff --git a/products/signals/backend/scout_harness/AGENTS.md b/products/signals/backend/scout_harness/AGENTS.mdindex ad9d001cce69..4f4266e7dd2b 100644--- a/products/signals/backend/scout_harness/AGENTS.md+++ b/products/signals/backend/scout_harness/AGENTS.md@@ -29,6 +29,10 @@ In production it is driven by `SignalsScoutCoordinatorWorkflow` (periodic tick eThe effective toolset for a run is the intersection of the skill's `allowed_tools` list with what `tools/__init__.py` re-exports — there is no separate registry module today.- `emit.py` — `emit_signal_*` tools that push findings as `cross_source_issue` signals into the standard ingestion pipeline.- `scratchpad.py` — `remember`, `forget`, and `search_scratchpad` tools backed by the `SignalScratchpad` model.+ Entries are durable by default; an optional `expires_at` (mirroring `notes.py`) retires a time-boxed memory on its own, since a scout that writes one almost never comes back to `forget` it.+ `remember` is a full-state upsert, so a write with no `expires_at` clears an expiry an earlier write set — sticky expiry would keep hiding an entry that has since become permanent, with no way for the rewriting scout to know a clock was on it.+ `search_scratchpad` drops expired rows unless `include_expired=True` (the human audit path); expiry hides a row, it never deletes one, so the key stays taken and both `forget` and the upsert still find it.+ A reader that goes to the manager rather than through `search_scratchpad` stays unfiltered on purpose — `derived_metadata._touched_followup_queue` is the one such reader, and has to be, since a `followup:` entry lapsing after a run doesn't undo the validation work that run did.- `notes.py` — `list_notes` / `leave_note` / `delete_note` backed by the `SignalScoutNote` model: steering notes humans (or other agents) leave for the fleet over the public MCP surface (`scout-notes-*` tools), the inbound counterpart to the scratchpad. A note targets one scout by `skill_name` or the whole fleet (blank), optionally expiring via `expires_at`; the run prompt's _Notes left for you_ section directs every scout to `scout-notes-list` its own notes in step 1 and treat them as advisory steering. Unlike the scratchpad there is no sandbox-only write gate, but writes still demand skill-authoring-level authorization (keys need `llm_skill:write` on top of `signal_scout:write`, and every writer must clear the `llm_skill` RBAC editor bar) — so a note-writer could already steer the fleet by editing its skills, and notes add no new steering power. Three more writers derive rows from inbox activity. `../dismissal_notes.py`: judging an inbox report with a note (dismiss, snooze, or restore) also leaves it here as an `origin=report_dismissal` note, targeted at the scout that authored the report, so a reviewer's verdict reaches the scout without it having to re-find the report. Resolving does not, since that says the report did its job rather than that filing it was wrong. `../discussion_notes.py`: opening a discussion on a report (the inbox "Discuss" action, which kicks off a Q&A task) also leaves the user's question here as an `origin=report_discussion` note, targeted at the authoring scout — framed as context to weigh or ignore, not a verdict, so the scout can fold a durable preference/correction into its scratchpad or dismiss it as noise. `../feedback_notes.py`: the thumbs rating at the end of a report body ("Was this report useful?") carries its optional note here as an `origin=report_feedback` note, targeted at the authoring scout. Unlike a dismissal it never falls back to a fleet-wide note — feedback is a verdict on one scout's own report, so with no resolvable authoring scout nothing is forwarded and the call is a no-op — and it never changes the report's state; the analytics event the client fires stays the durable record of the rating. All three paths re-check the same steering gate (token `scoped_teams`, canonical-project access, and the `llm_skill` editor bar) since the dismiss, discuss, and feedback actions need only `task:write`, and all forward only on the canonical team. The discuss and feedback paths additionally demand the `signal_scout:write` / `llm_skill:write` key scopes: a dismissal's text reaches runs anyway through the reports API, whereas the note is the only path a discussion question or feedback note takes to a scout, so a `task:write` credential must not open it alone. The discuss path is triggered from the tasks viewset (which holds the request the gate reads) through `facade/api.py:forward_report_discussion_note`, never from the tasks facade. On the read side, all three derived origins quote report content (report id, title, the note text), so `SignalScoutNoteViewSet.list` withholds them from any caller failing the reports read gate (`_may_read_reports`). The derived rows are context with a TTL; the `dismissal` artefact / discussion task / feedback analytics event stays the record of truth.- `structured_output.py` — `record_structured_output` (+ `_sync`): the structured-output channel, next to signals and reports. Opt-in via `SignalScoutConfig.structured_output_schema` (a JSON Schema describing ONE record, validated at config-write time by `validate_structured_output_schema` — which also rejects non-local `$ref`/`$dynamicRef`, and every validator here uses a no-retrieval registry, so a user-controlled schema can never make the worker fetch a URL; null = channel off, and the record endpoint fails closed). Setting the schema is skill-authoring-level steering (schema `description` fields are free prose rendered verbatim into a privileged prompt), so the config viewset gates it behind `llm_skill:write` + the `llm_skill` editor bar, like scout notes; clearing it stays on the base config scope. Records validate against the dispatch-time schema snapshot the runner stamps on the run row (`metadata["structured_output_schema"]`), so a mid-run schema edit can't reject records matching what the run was shown — while clearing the config schema mid-run still fails the channel closed (re-checked inside the capacity-reservation transaction with the config row locked, so a clear racing a submit serializes cleanly). Each submitted record is validated against the schema (all-or-nothing per call — an invalid record fails the batch with nothing written) and written into the team's own project as a `$scout_structured_output` event via one `capture_batch_internal` call (person processing off, deterministic uuid over `(run, batch index, subject, payload)` so a resubmitted batch collapses at ingestion while in-batch duplicates stay distinct). The events ARE the record — there is no Postgres row store, so past records are read like any events (insights, HogQL) and retention follows event retention — which is also why a delivery failure fails the call (`StructuredOutputDeliveryError` → 503) with an instruction to retry — the events carry a stable timestamp (the run's `created_at`) alongside the deterministic uuid, so the dedupe sorting key (`toDate(timestamp)` is part of it) stays identical across retries even past UTC midnight — and why the channel fails loudly for a dry-run `emit=False` scout, an org without AI-processing consent (mirroring `emit._preflight_emit_gates`), or a disabled `signals_scout` source instead of suppressing quietly (the runner also withholds the prompt section and schema snapshot when `emit` is off). Cardinality is the scout's call — the schema describes one record; a run may submit one, one per judged entity, or a batch (caps: `MAX_RECORDS_PER_CALL` per call, `MAX_RECORDS_PER_RUN` per run via the `structured_output_count` counter on `run.metadata`, reserved under the run-row lock before the forward — it counts accepted batches, so failed or retried forwards still spend cap). The prompt renders the exact configured schema in a per-run `# Structured output` section only when the channel is live, so the prompt and the validator can never describe two different contracts.- `profile.py` — `project_profile_*` tools that read the deterministic `SignalProjectProfile` snapshot.diff --git a/products/signals/backend/scout_harness/prompt.py b/products/signals/backend/scout_harness/prompt.pyindex 6c700273a203..37119dd6a058 100644--- a/products/signals/backend/scout_harness/prompt.py+++ b/products/signals/backend/scout_harness/prompt.py@@ -221,6 +221,8 @@ Bad: `dedupe:error_tracking:019de34e-2026-06-09`, `pattern:apm:scan-2026-06-09-0Write the `content` as **Markdown** (headings, bullet lists, `inline code` for ids/keys, links). Humans read these entries directly, so structure beats a wall of prose, and it reads verbatim into future prompts just the same.+**Time-boxed memories: set `expires_at` instead of planning to come back.** Most of what you record is durable and should stay, so leave `expires_at` unset by default. But when a memory is only true for a while — a cooldown ("don't re-flag the checkout alert before Friday"), a window you're watching, a caveat that lapses with a migration — pass `expires_at` on the `remember` call and it drops out of searches on its own. A future run that reads it after it should have lapsed is worse than not recording it at all, and the `forget` you promise yourself you'll make rarely happens. Two things to hold: each write carries the whole entry, so re-writing an entry without `expires_at` clears an expiry you set earlier (say so in the content when a memory has become permanent), and a `followup:` entry may not carry one at all — a validate-after date is when to *check* it, not when it stops mattering, so `remember` rejects the combination rather than letting the entry vanish from your queue before you get to it.+**Searching: query the entity, not just your own prefix.** The scratchpad is one keyspace shared by every scout on this team, and `scout-scratchpad-search` matches on key *and* content. Searching only your own `<domain>:` prefix finds your own past work and nothing else. Search the identity of the thing too (the issue id, flag key, page path, account id, event name) and you'll surface what a sibling recorded about the same entity under its own prefix. Each result carries `created_by_skill`, so you can tell your own memory from a sibling's."""_SCOUT_NOTES = """# Notes left for youdiff --git a/products/signals/backend/scout_harness/serializers.py b/products/signals/backend/scout_harness/serializers.pyindex 0ea0ab3ada00..7e7c8bccafd3 100644--- a/products/signals/backend/scout_harness/serializers.py+++ b/products/signals/backend/scout_harness/serializers.py@@ -624,6 +624,11 @@ class ScratchpadEntrySerializer(serializers.Serializer):)created_at = serializers.CharField(allow_null=True, help_text="ISO-8601 creation timestamp.")updated_at = serializers.CharField(allow_null=True, help_text="ISO-8601 last-write timestamp.")+ expires_at = serializers.CharField(+ allow_null=True,+ required=False,+ help_text="ISO-8601 expiry, or null for a durable memory that stays until it's forgotten.",+ )created_by_run_id = serializers.CharField(allow_null=True,help_text="Run that wrote this entry, or null if human-authored.",@@ -668,6 +673,14 @@ class SearchMemoryQuerySerializer(serializers.Serializer):"from the prior page)."),)+ include_expired = serializers.BooleanField(+ required=False,+ default=False,+ help_text=(+ "Include entries whose `expires_at` has passed. Off by default so a time-boxed memory "+ "retires itself; turn it on to audit what the fleet remembered and when it lapsed."+ ),+ )keys_only = serializers.BooleanField(required=False,help_text=(@@ -717,6 +730,21 @@ class RememberRequestSerializer(serializers.Serializer):"null), not rejected, so the memory write is never lost."),)+ expires_at = serializers.DateTimeField(+ required=False,+ allow_null=True,+ help_text=(+ "Optional ISO-8601 expiry for a memory that's only true for a while (a cooldown, a "+ "window you're watching). After this time the entry drops out of searches, so you "+ "don't have to come back and forget it. Omit for a durable memory — every write sets "+ "the whole entry, so omitting it on a later write clears an expiry set earlier."+ ),+ )++ def validate_expires_at(self, value: datetime | None) -> datetime | None:+ if value is not None and value <= timezone.now():+ raise serializers.ValidationError("expires_at must be in the future")+ return valueclass ForgetRequestSerializer(serializers.Serializer):diff --git a/products/signals/backend/scout_harness/tools/scratchpad.py b/products/signals/backend/scout_harness/tools/scratchpad.pyindex 49207682b016..b95abb03851d 100644--- a/products/signals/backend/scout_harness/tools/scratchpad.py+++ b/products/signals/backend/scout_harness/tools/scratchpad.py@@ -4,9 +4,10 @@ The scout calls `remember`/`forget` via this module. Scratchpad is the narrowper-team memory surface — MCP-readable across agents — that other scouts andPostHog AI can read to see what the scout fleet has learned about a team.-Simplified in PR 2 review: `tags`, `scope`, `expires_at`, and `authority` were-dropped (none were earning their keep on the stack). Retrieval is ILIKE on-`content` and `key` only; all entries are durable per-team memory.+Simplified in PR 2 review: `tags`, `scope`, and `authority` were dropped (none were+earning their keep on the stack). Retrieval is ILIKE on `content` and `key` only.+Entries are durable by default; `expires_at` is the opt-in TTL for the ones that+are only true for a while, mirroring `notes.py`."""from __future__ import annotations@@ -18,8 +19,10 @@ from typing import Anyfrom django.db import IntegrityError, transactionfrom django.db.models import Q, QuerySet, TextField, Valuefrom django.db.models.functions import Left+from django.utils import timezonefrom products.signals.backend.models import SignalScratchpad+from products.signals.backend.scout_harness.prompt import FOLLOWUP_KEY_PREFIXfrom products.signals.backend.scout_harness.tools.runs import _build_task_url# Defensive cap on search results.@@ -45,6 +48,7 @@ class ScratchpadEntry:content: strcreated_at: str | None = Noneupdated_at: str | None = None+ expires_at: str | None = Nonecreated_by_run_id: str | None = None# Identity + deep-link of the scout run that created the entry, resolved from `created_by_run`.created_by_skill: str | None = None@@ -64,12 +68,20 @@ def search_scratchpad(limit: int = DEFAULT_SCRATCHPAD_SEARCH_LIMIT,keys_only: bool = False,content_max_chars: int | None = None,+ include_expired: bool = False,) -> list[ScratchpadEntry]:"""Return memories the agent should consider when planning a run, newest first.`text` matches ILIKE against `content` and `key`. The previous `tags` filter+ GIN index were dropped in PR 2 review.+ Expired entries (`expires_at` in the past) are excluded by default, so a memory a+ scout wrote as time-boxed stops loading into run prompts on its own rather than+ waiting for a `forget` that rarely comes. `include_expired=True` brings them back+ for a human auditing what the fleet remembered and when it lapsed. Note this filters+ the read only — nothing deletes the row, so `forget` and the `remember` upsert still+ see an expired key.+`key` is an exact match on the unique `(team, key)` pair — at most one row, and theonly way to fetch a known entry reliably. `text` can't stand in for it: an ILIKEacross content *and* key means a key mentioned inside enough other bodies pushes the@@ -102,6 +114,8 @@ def search_scratchpad(qs = qs.filter(key=key)if text:qs = qs.filter(Q(content__icontains=text) | Q(key__icontains=text))+ if not include_expired:+ qs = qs.filter(Q(expires_at__isnull=True) | Q(expires_at__gt=timezone.now()))if date_from is not None:qs = qs.filter(updated_at__gte=date_from)if date_to is not None:@@ -116,26 +130,34 @@ def remember(key: str,content: str,run_id: str | None = None,+ expires_at: datetime | None = None,) -> ScratchpadEntry:"""Write or update a memory entry. Idempotent on `(team, key)`.+ A write carries the entry's whole state, `expires_at` included: passing one sets+ the expiry, omitting one clears it. Sticky expiry would be the worse default —+ a scout rewriting an entry that has since become permanent has no way to know an+ earlier run put a clock on it, and the entry would keep vanishing.+The previous `human_confirmed` authority guard was dropped — the human-in-the-loop write path was reserved-for-future and never landed. Re-add if it ships."""- _validate_key_content(key, content)+ _validate_entry(key=key, content=content, expires_at=expires_at)try:- row = _upsert_entry(team_id=team_id, key=key, content=content, run_id=run_id)+ row = _upsert_entry(team_id=team_id, key=key, content=content, run_id=run_id, expires_at=expires_at)except IntegrityError:# Lost the create race: our SELECT saw no row, but a concurrent request# committed an insert for the same `(team, key)` before ours, tripping the# unique constraint. The row now exists, so a single retry resolves to the# update branch and preserves the idempotent-upsert contract.- row = _upsert_entry(team_id=team_id, key=key, content=content, run_id=run_id)+ row = _upsert_entry(team_id=team_id, key=key, content=content, run_id=run_id, expires_at=expires_at)return _to_entry(row)-def _upsert_entry(*, team_id: int, key: str, content: str, run_id: str | None) -> SignalScratchpad:+def _upsert_entry(+ *, team_id: int, key: str, content: str, run_id: str | None, expires_at: datetime | None+) -> SignalScratchpad:with transaction.atomic():existing = SignalScratchpad.objects.select_for_update().filter(team_id=team_id, key=key).first()if existing is None:@@ -144,10 +166,12 @@ def _upsert_entry(*, team_id: int, key: str, content: str, run_id: str | None) -key=key,content=content,created_by_run_id=run_id,+ expires_at=expires_at,)existing.content = content+ existing.expires_at = expires_at# Don't overwrite `created_by_run` so we keep the original creator's lineage.- existing.save(update_fields=["content", "updated_at"])+ existing.save(update_fields=["content", "expires_at", "updated_at"])return existing@@ -161,7 +185,7 @@ def forget(*, team_id: int, key: str) -> bool:return True-def _validate_key_content(key: str, content: str) -> None:+def _validate_entry(*, key: str, content: str, expires_at: datetime | None) -> None:if not key or not key.strip():raise InvalidScratchpadError("memory key must be non-empty")if len(key) > MAX_SCRATCHPAD_KEY_LENGTH:@@ -172,6 +196,16 @@ def _validate_key_content(key: str, content: str) -> None:raise InvalidScratchpadError(f"memory content length {len(content)} exceeds max {MAX_SCRATCHPAD_CONTENT_LENGTH}")+ # An expiring follow-up disappears from the queue search before the scout can validate it,+ # while `derived_metadata` still reads the row off the manager and reports the run as a+ # validation pass — the queue loses work and the flag says otherwise. The run prompt tells+ # scouts not to do this, but a prompt is guidance, so the invariant is enforced here where+ # every writer passes.+ if expires_at is not None and key.startswith(FOLLOWUP_KEY_PREFIX):+ raise InvalidScratchpadError(+ f"a '{FOLLOWUP_KEY_PREFIX}' entry can't expire — its validate-after date says when to check it, "+ "not when it stops mattering. Put the date in `content` and leave `expires_at` unset."+ )def _clamp_search_limit(limit: int) -> int:@@ -198,6 +232,7 @@ def _to_entry(content=_resolve_content(row, keys_only=keys_only, content_max_chars=content_max_chars),created_at=row.created_at.isoformat() if row.created_at else None,updated_at=row.updated_at.isoformat() if row.updated_at else None,+ expires_at=row.expires_at.isoformat() if row.expires_at else None,created_by_run_id=str(run_pk) if run_pk else None,created_by_skill=run.skill_name if run is not None else None,created_by_run_url=_build_task_url(diff --git a/products/signals/backend/scout_harness/views.py b/products/signals/backend/scout_harness/views.pyindex baef1668efc6..e0dd33ecb9bb 100644--- a/products/signals/backend/scout_harness/views.py+++ b/products/signals/backend/scout_harness/views.py@@ -1216,7 +1216,8 @@ class SignalScratchpadViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):"and `key`; pass `key` instead for an exact single-entry lookup. ""`date_from` / `date_to` are a half-open window on `updated_at` (`>= date_from`, ""`< date_to`); pass `date_to` (the `updated_at` of the oldest entry seen) on subsequent calls "- "to walk past the cap. Pass `keys_only=true` to scan keys without pulling entry bodies, or "+ "to walk past the cap. Entries whose `expires_at` has passed are excluded unless "+ "`include_expired=true`. Pass `keys_only=true` to scan keys without pulling entry bodies, or ""`content_max_chars` to cap each `content` to a preview — both keep a wide orientation scan ""from returning every entry's full prose. Results capped at 1000."),@@ -1239,6 +1240,7 @@ class SignalScratchpadViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):limit=limit,keys_only=keys_only,content_max_chars=content_max_chars,+ include_expired=bool(validated.get("include_expired", False)),)return Response(ScratchpadEntrySerializer([row.as_dict() for row in rows], many=True).data)@@ -1246,10 +1248,15 @@ class SignalScratchpadViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):request_serializer=RememberRequestSerializer,responses={200: OpenApiResponse(response=ScratchpadEntrySerializer, description="Memory entry written or refreshed."),- 400: OpenApiResponse(description="Invalid memory shape (empty key/content, key too long)."),+ 400: OpenApiResponse(+ description="Invalid memory shape (empty key/content, key too long, `expires_at` in the past)."+ ),},summary="Remember a scratchpad entry",- description=("Upsert a memory keyed on `(team, key)`. Re-using a key updates the existing entry in place."),+ description=(+ "Upsert a memory keyed on `(team, key)`. Re-using a key updates the existing entry in place. "+ "A write carries the entry's whole state, so `expires_at` is set when passed and cleared when omitted."+ ),operation_id="signals_scout_scratchpad_remember",)def create(self, request: Request, *args, **kwargs) -> Response:@@ -1272,6 +1279,7 @@ class SignalScratchpadViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):key=data["key"],content=data["content"],run_id=str(run_id) if run_id is not None else None,+ expires_at=data.get("expires_at"),)except InvalidScratchpadError as exc:raise exceptions.ValidationError({"detail": str(exc)})diff --git a/products/signals/backend/test/test_scout_harness_api.py b/products/signals/backend/test/test_scout_harness_api.pyindex 771fa9cc3576..0d438e4c2d2c 100644--- a/products/signals/backend/test/test_scout_harness_api.py+++ b/products/signals/backend/test/test_scout_harness_api.py@@ -1272,6 +1272,55 @@ class TestScoutHarnessScratchpadAPI(APIBaseTest):assert response.status_code == status.HTTP_200_OKassert response.json()[0]["content"] == "abcd"+ @parameterized.expand([("default", "", ["live"]), ("include_expired", "?include_expired=true", ["live", "lapsed"])])+ def test_search_hides_expired_entries_unless_asked_for(+ self, _name: str, query: str, expected_keys: list[str]+ ) -> None:+ SignalScratchpad.objects.create(team=self.team, key="live", content="still true")+ SignalScratchpad.objects.create(+ team=self.team, key="lapsed", content="cooldown", expires_at=timezone.now() - timedelta(days=1)+ )+ response = self.client.get(f"{self._list_url()}{query}")+ assert response.status_code == status.HTTP_200_OK+ assert sorted(row["key"] for row in response.json()) == sorted(expected_keys)++ def test_remember_stores_and_returns_expires_at(self) -> None:+ expiry = timezone.now() + timedelta(days=2)+ response = self.client.post(+ self._list_url(),+ data={"key": "cooldown", "content": "hold off", "expires_at": expiry.isoformat()},+ format="json",+ )+ assert response.status_code == status.HTTP_200_OK+ assert response.json()["expires_at"] == expiry.isoformat()+ assert SignalScratchpad.objects.get(team=self.team, key="cooldown").expires_at == expiry++ def test_remember_rejects_expiry_on_a_followup_queue_entry(self) -> None:+ # Wiring guard: the invariant lives in `remember`, so the endpoint has to surface it as a+ # 400 rather than writing a follow-up that vanishes from the scout's queue.+ response = self.client.post(+ self._list_url(),+ data={+ "key": f"{FOLLOWUP_KEY_PREFIX}signals-scout-errors:checkout",+ "content": "pending",+ "expires_at": (timezone.now() + timedelta(days=3)).isoformat(),+ },+ format="json",+ )+ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert not SignalScratchpad.objects.filter(team=self.team).exists()++ def test_remember_rejects_expires_at_in_the_past(self) -> None:+ # A memory that's already lapsed on write is invisible the moment it lands, so it's a+ # mistake worth a 400 rather than a silently useless row.+ response = self.client.post(+ self._list_url(),+ data={"key": "k1", "content": "v", "expires_at": "2020-01-01T00:00:00Z"},+ format="json",+ )+ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert not SignalScratchpad.objects.filter(team=self.team, key="k1").exists()+def test_search_does_not_leak_other_teams_memory(self) -> None:other = Team.objects.create(organization=self.organization, name="Other")SignalScratchpad.objects.create(team=other, key="theirs", content="leaked?")@@ -3153,6 +3202,22 @@ class TestScoutRunDerivedMetadata(APIBaseTest):)assert self._stamp(run)["has_self_validation"] is expected+ def test_self_validation_still_counts_a_followup_entry_that_has_expired(self) -> None:+ # The follow-up queue is read straight off the manager, deliberately unfiltered: this flag+ # records that the run did the work, and an entry lapsing afterwards doesn't undo that.+ # Routing this read through `search_scratchpad` would silently start dropping such runs.+ run = _make_run(self.team)+ entry = SignalScratchpad.objects.create(+ team=self.team,+ key=f"{FOLLOWUP_KEY_PREFIX}{run.skill_name}:checkout-errors",+ content="validated",+ expires_at=timezone.now() - timedelta(days=1),+ )+ SignalScratchpad.all_teams.filter(pk=entry.pk).update(+ created_at=run.created_at - timedelta(hours=2), updated_at=run.created_at + timedelta(minutes=1)+ )+ assert self._stamp(run)["has_self_validation"] is True+def test_sibling_skills_queue_does_not_count(self) -> None:run = _make_run(self.team)entry = SignalScratchpad.objects.create(diff --git a/products/signals/backend/test/test_scout_harness_tools.py b/products/signals/backend/test/test_scout_harness_tools.pyindex 7901061334ef..796a88899274 100644--- a/products/signals/backend/test/test_scout_harness_tools.py+++ b/products/signals/backend/test/test_scout_harness_tools.py@@ -21,6 +21,7 @@ from posthog.sync import database_sync_to_asyncfrom products.signals.backend.models import SignalScoutConfig, SignalScoutEmission, SignalScoutRun, SignalScratchpadfrom products.signals.backend.report_charts import MAX_REPORT_CHARTS, ReportChartfrom products.signals.backend.report_prompts import MAX_SUGGESTED_PROMPT_LENGTH, MAX_SUGGESTED_PROMPTS+from products.signals.backend.scout_harness.prompt import FOLLOWUP_KEY_PREFIXfrom products.signals.backend.scout_harness.tools import (MAX_EVIDENCE_ENTRIES,EvidenceEntry,@@ -489,6 +490,59 @@ class TestRemember(BaseTest):assert row.content == "v2"assert str(row.created_by_run_id) == str(run.id)+ def test_stores_expires_at(self) -> None:+ expiry = timezone.now() + timedelta(days=3)++ entry = remember(team_id=self.team.id, key="cooldown", content="hold off until Friday", expires_at=expiry)++ assert entry.expires_at == expiry.isoformat()+ assert SignalScratchpad.objects.get(team_id=self.team.id, key="cooldown").expires_at == expiry++ def test_rewrite_without_expires_at_clears_the_expiry(self) -> None:+ # Full-state upsert: sticky expiry would keep retiring an entry that has since become+ # permanent, with no way for the rewriting scout to know a clock was on it.+ remember(team_id=self.team.id, key="k", content="v1", expires_at=timezone.now() + timedelta(days=3))++ remember(team_id=self.team.id, key="k", content="v2")++ assert SignalScratchpad.objects.get(team_id=self.team.id, key="k").expires_at is None++ def test_upsert_reclaims_an_expired_entry(self) -> None:+ # Expiry hides a row from search but never deletes it, so the key stays taken. The upsert+ # must find it and update in place rather than trip the `(team, key)` unique constraint.+ remember(team_id=self.team.id, key="k", content="v1")+ SignalScratchpad.objects.filter(team_id=self.team.id, key="k").update(+ expires_at=timezone.now() - timedelta(days=1)+ )++ remember(team_id=self.team.id, key="k", content="v2")++ rows = SignalScratchpad.objects.filter(team_id=self.team.id, key="k")+ assert rows.count() == 1+ assert search_scratchpad(team_id=self.team.id, key="k")[0].content == "v2"++ def test_rejects_expiry_on_a_followup_queue_entry(self) -> None:+ # An expiring follow-up drops out of the queue search before the scout can validate it,+ # while `derived_metadata` reads the row unfiltered and still reports a validation pass.+ # The prompt says don't, but a prompt isn't an enforcement boundary.+ with pytest.raises(InvalidScratchpadError, match=FOLLOWUP_KEY_PREFIX):+ remember(+ team_id=self.team.id,+ key=f"{FOLLOWUP_KEY_PREFIX}signals-scout-errors:checkout",+ content="pending",+ expires_at=timezone.now() + timedelta(days=3),+ )++ assert not SignalScratchpad.objects.filter(team_id=self.team.id).exists()++ def test_allows_a_followup_queue_entry_without_an_expiry(self) -> None:+ key = f"{FOLLOWUP_KEY_PREFIX}signals-scout-errors:checkout"++ entry = remember(team_id=self.team.id, key=key, content="pending, validate after 2026-09-01")++ assert entry.key == key+ assert entry.expires_at is None+def test_rejects_empty_key_or_content(self) -> None:with pytest.raises(InvalidScratchpadError):remember(team_id=self.team.id, key="", content="x")@@ -659,6 +713,43 @@ class TestSearchScratchpad(BaseTest):assert results[0].content == "abcdefghij"+ @parameterized.expand(+ [+ ("default", False, {"durable", "still-live"}),+ ("include_expired", True, {"durable", "still-live", "lapsed"}),+ ]+ )+ def test_expired_entries_drop_out_unless_audited(+ self, _name: str, include_expired: bool, expected_keys: set[str]+ ) -> None:+ # The whole point of the TTL: a time-boxed memory stops loading into run prompts on its+ # own, while a human auditing what the fleet remembered can still read it back.+ remember(team_id=self.team.id, key="durable", content="no expiry")+ remember(+ team_id=self.team.id,+ key="still-live",+ content="expires later",+ expires_at=timezone.now() + timedelta(days=3),+ )+ remember(team_id=self.team.id, key="lapsed", content="expired yesterday")+ SignalScratchpad.objects.filter(team=self.team, key="lapsed").update(+ expires_at=timezone.now() - timedelta(days=1)+ )++ results = search_scratchpad(team_id=self.team.id, include_expired=include_expired)++ assert {e.key for e in results} == expected_keys++ def test_exact_key_lookup_hides_an_expired_entry(self) -> None:+ # `key=` is a separate ORM branch from the unfiltered listing, and it's the lookup a scout+ # uses to re-read a memory it remembers writing — a lapsed entry must not come back there.+ remember(team_id=self.team.id, key="cooldown", content="hold off")+ SignalScratchpad.objects.filter(team=self.team, key="cooldown").update(+ expires_at=timezone.now() - timedelta(days=1)+ )++ assert search_scratchpad(team_id=self.team.id, key="cooldown") == []+def test_key_lookup_survives_newer_entries_quoting_that_key(self) -> None:remember(team_id=self.team.id, key="pattern:target", content="the body we want back")# `text` would match all of these on content and, being newer, they'd crowd out the row.diff --git a/products/signals/frontend/generated/api.schemas.ts b/products/signals/frontend/generated/api.schemas.tsindex 25af4bce3904..ce987c62ce67 100644--- a/products/signals/frontend/generated/api.schemas.ts+++ b/products/signals/frontend/generated/api.schemas.ts@@ -3736,6 +3736,11 @@ export interface ScratchpadEntryApi {* @nullable*/updated_at: string | null+ /**+ * ISO-8601 expiry, or null for a durable memory that stays until it's forgotten.+ * @nullable+ */+ expires_at?: string | null/*** Run that wrote this entry, or null if human-authored.* @nullable@@ -3772,6 +3777,11 @@ export interface RememberRequestApi {* @nullable*/run_id?: string | null+ /**+ * Optional ISO-8601 expiry for a memory that's only true for a while (a cooldown, a window you're watching). After this time the entry drops out of searches, so you don't have to come back and forget it. Omit for a durable memory — every write sets the whole entry, so omitting it on a later write clears an expiry set earlier.+ * @nullable+ */+ expires_at?: string | null}/**@@ -4251,6 +4261,10 @@ export type SignalsScoutScratchpadSearchParams = {* ISO-8601 exclusive upper bound on `updated_at`. Pass to walk back past the result cap on subsequent calls (cursor-style: set to the `updated_at` of the oldest entry from the prior page).*/date_to?: string+ /**+ * Include entries whose `expires_at` has passed. Off by default so a time-boxed memory retires itself; turn it on to audit what the fleet remembered and when it lapsed.+ */+ include_expired?: boolean/*** Exact key match — returns the single entry with this key, or nothing. Use this to re-read a known entry; `text` searches key *and* content, so it can push the row you asked for past the limit.* @minLength 1diff --git a/products/signals/frontend/generated/api.ts b/products/signals/frontend/generated/api.tsindex 248d99591b84..91d5f09c443c 100644--- a/products/signals/frontend/generated/api.ts+++ b/products/signals/frontend/generated/api.ts@@ -1356,7 +1356,7 @@ export const getSignalsScoutScratchpadSearchUrl = (projectId: string, params?: S}/**- * Return `SignalScratchpad` entries for this project, newest-first. ILIKE matches on `content` and `key`; pass `key` instead for an exact single-entry lookup. `date_from` / `date_to` are a half-open window on `updated_at` (`>= date_from`, `< date_to`); pass `date_to` (the `updated_at` of the oldest entry seen) on subsequent calls to walk past the cap. Pass `keys_only=true` to scan keys without pulling entry bodies, or `content_max_chars` to cap each `content` to a preview — both keep a wide orientation scan from returning every entry's full prose. Results capped at 1000.+ * Return `SignalScratchpad` entries for this project, newest-first. ILIKE matches on `content` and `key`; pass `key` instead for an exact single-entry lookup. `date_from` / `date_to` are a half-open window on `updated_at` (`>= date_from`, `< date_to`); pass `date_to` (the `updated_at` of the oldest entry seen) on subsequent calls to walk past the cap. Entries whose `expires_at` has passed are excluded unless `include_expired=true`. Pass `keys_only=true` to scan keys without pulling entry bodies, or `content_max_chars` to cap each `content` to a preview — both keep a wide orientation scan from returning every entry's full prose. Results capped at 1000.* @summary Search the scout scratchpad*/export const signalsScoutScratchpadSearch = async (@@ -1375,7 +1375,7 @@ export const getSignalsScoutScratchpadRememberUrl = (projectId: string) => {}/**- * Upsert a memory keyed on `(team, key)`. Re-using a key updates the existing entry in place.+ * Upsert a memory keyed on `(team, key)`. Re-using a key updates the existing entry in place. A write carries the entry's whole state, so `expires_at` is set when passed and cleared when omitted.* @summary Remember a scratchpad entry*/export const signalsScoutScratchpadRemember = async (diff --git a/products/signals/frontend/generated/api.zod.ts b/products/signals/frontend/generated/api.zod.tsindex 13139ca25376..56197fec84fe 100644--- a/products/signals/frontend/generated/api.zod.ts+++ b/products/signals/frontend/generated/api.zod.ts@@ -1329,7 +1329,7 @@ export const SignalsScoutRunsEmissionReportsBatchBody = /* @__PURE__ */ zod)/**- * Upsert a memory keyed on `(team, key)`. Re-using a key updates the existing entry in place.+ * Upsert a memory keyed on `(team, key)`. Re-using a key updates the existing entry in place. A write carries the entry's whole state, so `expires_at` is set when passed and cleared when omitted.* @summary Remember a scratchpad entry*/export const signalsScoutScratchpadRememberBodyKeyMax = 300@@ -1354,6 +1354,12 @@ export const SignalsScoutScratchpadRememberBody = /* @__PURE__ */ zod.describe("Run that authored this memory; persisted as `created_by_run_id` for lineage. Best-effort — a `run_id` that isn't a run on this project is dropped (lineage left null), not rejected, so the memory write is never lost."),+ expires_at: zod.iso+ .datetime({ offset: true })+ .nullish()+ .describe(+ "Optional ISO-8601 expiry for a memory that's only true for a while (a cooldown, a window you're watching). After this time the entry drops out of searches, so you don't have to come back and forget it. Omit for a durable memory — every write sets the whole entry, so omitting it on a later write clears an expiry set earlier."+ ),}).describe('Request body for `remember`.')diff --git a/products/signals/frontend/inbox/components/scratchpad/ScratchpadEntryCard.tsx b/products/signals/frontend/inbox/components/scratchpad/ScratchpadEntryCard.tsxindex 449dac41d827..f1d0fff3afcd 100644--- a/products/signals/frontend/inbox/components/scratchpad/ScratchpadEntryCard.tsx+++ b/products/signals/frontend/inbox/components/scratchpad/ScratchpadEntryCard.tsx@@ -107,6 +107,9 @@ export function ScratchpadEntryCard({ entry }: { entry: ScratchpadEntryApi }): J{maintainedDays >= 1 && (<span>· carried forward {maintainedDays === 1 ? '1 day' : `${maintainedDays} days`}</span>)}+ {/* Most memories are durable, so an expiry is the exception worth calling out —+ without it a reader can't tell why an entry they remember has stopped showing up. */}+ {entry.expires_at && <span>· expires {humanFriendlyDetailedTime(entry.expires_at)}</span>}<span className="flex-1" />{(scoutName || entry.created_by_run_id) && (<span className="shrink-0">diff --git a/products/signals/mcp/tools.yaml b/products/signals/mcp/tools.yamlindex c9eaa9b97fc3..fcfa93840fee 100644--- a/products/signals/mcp/tools.yaml+++ b/products/signals/mcp/tools.yaml@@ -814,6 +814,9 @@ tools:defeats dedupe). For run state, use one fixed key and keep the timestamp in `content`. Write `content` asMarkdown — humans read these entries directly, so structured Markdown (headings, bullets, inline code forids) is far easier to skim than a wall of prose. Optionally pass `run_id` to record which run wrote it.+ Optionally pass `expires_at` when the memory is only true for a while (a cooldown, a window you're watching)+ so it retires itself instead of waiting for a `scout-scratchpad-forget` you may never make. Each write+ carries the whole entry, so omitting `expires_at` on a later write clears an expiry set earlier.scout-scratchpad-search:operation: signals_scout_scratchpad_searchenabled: true@@ -829,9 +832,10 @@ tools:Return `SignalScratchpad` entries for this project, newest first. Pass `text` for a case-insensitivesubstring match on the entry's `content` and `key`. Pass `date_from` / `date_to` (ISO-8601, inclusive lower/ exclusive upper bound on `updated_at`) to scope to a window — set `date_to` to the `updated_at` of the- oldest entry from the prior page to walk past the cap. Pass `keys_only=true` to scan which memories exist- without pulling their (potentially large) bodies, or `content_max_chars` to cap each `content` to a preview- — both keep a wide orientation/dedupe scan from returning every entry's full prose. Results capped at 1000.+ oldest entry from the prior page to walk past the cap. Entries whose `expires_at` has passed are excluded+ unless `include_expired=true`. Pass `keys_only=true` to scan which memories exist without pulling their+ (potentially large) bodies, or `content_max_chars` to cap each `content` to a preview — both keep a wide+ orientation/dedupe scan from returning every entry's full prose. Results capped at 1000.signals-report-artefacts-diff:operation: signals_report_artefacts_diffenabled: falsediff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex f39d9f7cd85c..f15721887f5e 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -9282,7 +9282,7 @@}},"scout-scratchpad-remember": {- "description": "Upsert a scratchpad entry keyed on `(team, key)` — re-using a key updates the existing entry in place, so this is an upsert rather than a strict create. Keys are stable identities: key off *what* you're tracking, not *when* you saw it — never embed dates, timestamps, or run ids (that mints a new row every run and defeats dedupe). For run state, use one fixed key and keep the timestamp in `content`. Write `content` as Markdown — humans read these entries directly, so structured Markdown (headings, bullets, inline code for ids) is far easier to skim than a wall of prose. Optionally pass `run_id` to record which run wrote it.",+ "description": "Upsert a scratchpad entry keyed on `(team, key)` — re-using a key updates the existing entry in place, so this is an upsert rather than a strict create. Keys are stable identities: key off *what* you're tracking, not *when* you saw it — never embed dates, timestamps, or run ids (that mints a new row every run and defeats dedupe). For run state, use one fixed key and keep the timestamp in `content`. Write `content` as Markdown — humans read these entries directly, so structured Markdown (headings, bullets, inline code for ids) is far easier to skim than a wall of prose. Optionally pass `run_id` to record which run wrote it. Optionally pass `expires_at` when the memory is only true for a while (a cooldown, a window you're watching) so it retires itself instead of waiting for a `scout-scratchpad-forget` you may never make. Each write carries the whole entry, so omitting `expires_at` on a later write clears an expiry set earlier.","category": "Signals","feature": "signals","summary": "Remember a scratchpad entry",@@ -9296,7 +9296,7 @@}},"scout-scratchpad-search": {- "description": "Return `SignalScratchpad` entries for this project, newest first. Pass `text` for a case-insensitive substring match on the entry's `content` and `key`. Pass `date_from` / `date_to` (ISO-8601, inclusive lower / exclusive upper bound on `updated_at`) to scope to a window — set `date_to` to the `updated_at` of the oldest entry from the prior page to walk past the cap. Pass `keys_only=true` to scan which memories exist without pulling their (potentially large) bodies, or `content_max_chars` to cap each `content` to a preview — both keep a wide orientation/dedupe scan from returning every entry's full prose. Results capped at 1000.",+ "description": "Return `SignalScratchpad` entries for this project, newest first. Pass `text` for a case-insensitive substring match on the entry's `content` and `key`. Pass `date_from` / `date_to` (ISO-8601, inclusive lower / exclusive upper bound on `updated_at`) to scope to a window — set `date_to` to the `updated_at` of the oldest entry from the prior page to walk past the cap. Entries whose `expires_at` has passed are excluded unless `include_expired=true`. Pass `keys_only=true` to scan which memories exist without pulling their (potentially large) bodies, or `content_max_chars` to cap each `content` to a preview — both keep a wide orientation/dedupe scan from returning every entry's full prose. Results capped at 1000.","category": "Signals","feature": "signals","summary": "Search the scout scratchpad",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex 21ebbb171f8f..66b6c5d0dc7f 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -9823,7 +9823,7 @@}},"scout-scratchpad-remember": {- "description": "Upsert a scratchpad entry keyed on `(team, key)` — re-using a key updates the existing entry in place, so this is an upsert rather than a strict create. Keys are stable identities: key off *what* you're tracking, not *when* you saw it — never embed dates, timestamps, or run ids (that mints a new row every run and defeats dedupe). For run state, use one fixed key and keep the timestamp in `content`. Write `content` as Markdown — humans read these entries directly, so structured Markdown (headings, bullets, inline code for ids) is far easier to skim than a wall of prose. Optionally pass `run_id` to record which run wrote it.",+ "description": "Upsert a scratchpad entry keyed on `(team, key)` — re-using a key updates the existing entry in place, so this is an upsert rather than a strict create. Keys are stable identities: key off *what* you're tracking, not *when* you saw it — never embed dates, timestamps, or run ids (that mints a new row every run and defeats dedupe). For run state, use one fixed key and keep the timestamp in `content`. Write `content` as Markdown — humans read these entries directly, so structured Markdown (headings, bullets, inline code for ids) is far easier to skim than a wall of prose. Optionally pass `run_id` to record which run wrote it. Optionally pass `expires_at` when the memory is only true for a while (a cooldown, a window you're watching) so it retires itself instead of waiting for a `scout-scratchpad-forget` you may never make. Each write carries the whole entry, so omitting `expires_at` on a later write clears an expiry set earlier.","category": "Signals","feature": "signals","summary": "Remember a scratchpad entry",@@ -9837,7 +9837,7 @@}},"scout-scratchpad-search": {- "description": "Return `SignalScratchpad` entries for this project, newest first. Pass `text` for a case-insensitive substring match on the entry's `content` and `key`. Pass `date_from` / `date_to` (ISO-8601, inclusive lower / exclusive upper bound on `updated_at`) to scope to a window — set `date_to` to the `updated_at` of the oldest entry from the prior page to walk past the cap. Pass `keys_only=true` to scan which memories exist without pulling their (potentially large) bodies, or `content_max_chars` to cap each `content` to a preview — both keep a wide orientation/dedupe scan from returning every entry's full prose. Results capped at 1000.",+ "description": "Return `SignalScratchpad` entries for this project, newest first. Pass `text` for a case-insensitive substring match on the entry's `content` and `key`. Pass `date_from` / `date_to` (ISO-8601, inclusive lower / exclusive upper bound on `updated_at`) to scope to a window — set `date_to` to the `updated_at` of the oldest entry from the prior page to walk past the cap. Entries whose `expires_at` has passed are excluded unless `include_expired=true`. Pass `keys_only=true` to scan which memories exist without pulling their (potentially large) bodies, or `content_max_chars` to cap each `content` to a preview — both keep a wide orientation/dedupe scan from returning every entry's full prose. Results capped at 1000.","category": "Signals","feature": "signals","summary": "Search the scout scratchpad",diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 1eb4062961b4..4c40bcaf854a 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -71484,6 +71484,11 @@ export namespace Schemas {* @nullable*/run_id?: string | null;+ /**+ * Optional ISO-8601 expiry for a memory that's only true for a while (a cooldown, a window you're watching). After this time the entry drops out of searches, so you don't have to come back and forget it. Omit for a durable memory — every write sets the whole entry, so omitting it on a later write clears an expiry set earlier.+ * @nullable+ */+ expires_at?: string | null;}export interface RemoveOptOutRequest {@@ -73921,6 +73926,11 @@ export namespace Schemas {* @nullable*/updated_at: string | null;+ /**+ * ISO-8601 expiry, or null for a durable memory that stays until it's forgotten.+ * @nullable+ */+ expires_at?: string | null;/*** Run that wrote this entry, or null if human-authored.* @nullable@@ -94891,6 +94901,10 @@ export namespace Schemas {* ISO-8601 exclusive upper bound on `updated_at`. Pass to walk back past the result cap on subsequent calls (cursor-style: set to the `updated_at` of the oldest entry from the prior page).*/date_to?: string;+ /**+ * Include entries whose `expires_at` has passed. Off by default so a time-boxed memory retires itself; turn it on to audit what the fleet remembered and when it lapsed.+ */+ include_expired?: boolean;/*** Exact key match — returns the single entry with this key, or nothing. Use this to re-read a known entry; `text` searches key *and* content, so it can push the row you asked for past the limit.* @minLength 1diff --git a/services/mcp/src/generated/signals/api.ts b/services/mcp/src/generated/signals/api.tsindex 13f710775747..afd1f66aa8b5 100644--- a/services/mcp/src/generated/signals/api.ts+++ b/services/mcp/src/generated/signals/api.ts@@ -1751,7 +1751,7 @@ export const SignalsScoutRunsRecentEmissionsQueryParams = /* @__PURE__ */ zod.ob})/**- * Return `SignalScratchpad` entries for this project, newest-first. ILIKE matches on `content` and `key`; pass `key` instead for an exact single-entry lookup. `date_from` / `date_to` are a half-open window on `updated_at` (`>= date_from`, `< date_to`); pass `date_to` (the `updated_at` of the oldest entry seen) on subsequent calls to walk past the cap. Pass `keys_only=true` to scan keys without pulling entry bodies, or `content_max_chars` to cap each `content` to a preview — both keep a wide orientation scan from returning every entry's full prose. Results capped at 1000.+ * Return `SignalScratchpad` entries for this project, newest-first. ILIKE matches on `content` and `key`; pass `key` instead for an exact single-entry lookup. `date_from` / `date_to` are a half-open window on `updated_at` (`>= date_from`, `< date_to`); pass `date_to` (the `updated_at` of the oldest entry seen) on subsequent calls to walk past the cap. Entries whose `expires_at` has passed are excluded unless `include_expired=true`. Pass `keys_only=true` to scan keys without pulling entry bodies, or `content_max_chars` to cap each `content` to a preview — both keep a wide orientation scan from returning every entry's full prose. Results capped at 1000.* @summary Search the scout scratchpad*/export const SignalsScoutScratchpadSearchParams = /* @__PURE__ */ zod.object({@@ -1764,6 +1764,7 @@ export const SignalsScoutScratchpadSearchParams = /* @__PURE__ */ zod.object({export const signalsScoutScratchpadSearchQueryContentMaxCharsMin = 0+export const signalsScoutScratchpadSearchQueryIncludeExpiredDefault = falseexport const signalsScoutScratchpadSearchQueryLimitMax = 1000export const SignalsScoutScratchpadSearchQueryParams = /* @__PURE__ */ zod.object({@@ -1784,6 +1785,12 @@ export const SignalsScoutScratchpadSearchQueryParams = /* @__PURE__ */ zod.objec.describe('ISO-8601 exclusive upper bound on `updated_at`. Pass to walk back past the result cap on subsequent calls (cursor-style: set to the `updated_at` of the oldest entry from the prior page).'),+ include_expired: zod+ .boolean()+ .default(signalsScoutScratchpadSearchQueryIncludeExpiredDefault)+ .describe(+ 'Include entries whose `expires_at` has passed. Off by default so a time-boxed memory retires itself; turn it on to audit what the fleet remembered and when it lapsed.'+ ),key: zod.string().min(1)@@ -1810,7 +1817,7 @@ export const SignalsScoutScratchpadSearchQueryParams = /* @__PURE__ */ zod.objec})/**- * Upsert a memory keyed on `(team, key)`. Re-using a key updates the existing entry in place.+ * Upsert a memory keyed on `(team, key)`. Re-using a key updates the existing entry in place. A write carries the entry's whole state, so `expires_at` is set when passed and cleared when omitted.* @summary Remember a scratchpad entry*/export const SignalsScoutScratchpadRememberParams = /* @__PURE__ */ zod.object({@@ -1843,6 +1850,12 @@ export const SignalsScoutScratchpadRememberBody = /* @__PURE__ */ zod.describe("Run that authored this memory; persisted as `created_by_run_id` for lineage. Best-effort — a `run_id` that isn't a run on this project is dropped (lineage left null), not rejected, so the memory write is never lost."),+ expires_at: zod.iso+ .datetime({ offset: true })+ .nullish()+ .describe(+ "Optional ISO-8601 expiry for a memory that's only true for a while (a cooldown, a window you're watching). After this time the entry drops out of searches, so you don't have to come back and forget it. Omit for a durable memory — every write sets the whole entry, so omitting it on a later write clears an expiry set earlier."+ ),}).describe('Request body for `remember`.')diff --git a/services/mcp/src/tools/generated/signals.ts b/services/mcp/src/tools/generated/signals.tsindex 65593f416ac6..de0cd1265b9e 100644--- a/services/mcp/src/tools/generated/signals.ts+++ b/services/mcp/src/tools/generated/signals.ts@@ -1177,6 +1177,9 @@ const scoutScratchpadRemember = (): ToolBase<typeof ScoutScratchpadRememberSchemif (params.run_id !== undefined) {body['run_id'] = params.run_id}+ if (params.expires_at !== undefined) {+ body['expires_at'] = params.expires_at+ }const result = await context.api.request<Schemas.ScratchpadEntry>({method: 'POST',path: `/api/projects/${encodeURIComponent(String(projectId))}/signals/scout/scratchpad/`,@@ -1203,6 +1206,7 @@ const scoutScratchpadSearch = (): ToolBase<content_max_chars: params.content_max_chars,date_from: params.date_from,date_to: params.date_to,+ include_expired: params.include_expired,key: params.key,keys_only: params.keys_only,limit: params.limit,@@ -1722,6 +1726,9 @@ const signalsScoutScratchpadRemember = (): ToolBase<if (params.run_id !== undefined) {body['run_id'] = params.run_id}+ if (params.expires_at !== undefined) {+ body['expires_at'] = params.expires_at+ }const result = await context.api.request<Schemas.ScratchpadEntry>({method: 'POST',path: `/api/projects/${encodeURIComponent(String(projectId))}/signals/scout/scratchpad/`,@@ -1748,6 +1755,7 @@ const signalsScoutScratchpadSearch = (): ToolBase<content_max_chars: params.content_max_chars,date_from: params.date_from,date_to: params.date_to,+ include_expired: params.include_expired,key: params.key,keys_only: params.keys_only,limit: params.limit,diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/scout-scratchpad-search.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/scout-scratchpad-search.jsonindex b72626cf63c8..b1213b292ba5 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/scout-scratchpad-search.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/scout-scratchpad-search.json@@ -18,6 +18,11 @@"pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$","type": "string"},+ "include_expired": {+ "default": false,+ "description": "Include entries whose `expires_at` has passed. Off by default so a time-boxed memory retires itself; turn it on to audit what the fleet remembered and when it lapsed.",+ "type": "boolean"+ },"key": {"description": "Exact key match — returns the single entry with this key, or nothing. Use this to re-read a known entry; `text` searches key *and* content, so it can push the row you asked for past the limit.","minLength": 1,diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/signals-scout-scratchpad-search.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/signals-scout-scratchpad-search.jsonindex b72626cf63c8..b1213b292ba5 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/signals-scout-scratchpad-search.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/signals-scout-scratchpad-search.json@@ -18,6 +18,11 @@"pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$","type": "string"},+ "include_expired": {+ "default": false,+ "description": "Include entries whose `expires_at` has passed. Off by default so a time-boxed memory retires itself; turn it on to audit what the fleet remembered and when it lapsed.",+ "type": "boolean"+ },"key": {"description": "Exact key match — returns the single entry with this key, or nothing. Use this to re-read a known entry; `text` searches key *and* content, so it can push the row you asked for past the limit.","minLength": 1,