: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
chore(signals): raise scout scratchpad search cap to 1000 (#72296)
Andrew Maguireb8cd21b63551
diff --git a/frontend/src/scenes/inbox/components/scratchpad/ScratchpadEntryCard.tsx b/frontend/src/scenes/inbox/components/scratchpad/ScratchpadEntryCard.tsxindex 5a675a0eb187..8b3b14d25541 100644--- a/frontend/src/scenes/inbox/components/scratchpad/ScratchpadEntryCard.tsx+++ b/frontend/src/scenes/inbox/components/scratchpad/ScratchpadEntryCard.tsx@@ -1,14 +1,17 @@-import { type ComponentProps, useState } from 'react'+import { useActions, useValues } from 'kea'+import { type ComponentProps } from 'react'import { IconChevronDown, IconClock } from '@posthog/icons'import { LemonTag, Link } from '@posthog/lemon-ui'import { dayjs } from 'lib/dayjs'import { LemonMarkdown } from 'lib/lemon-ui/LemonMarkdown'+import { LemonSkeleton } from 'lib/lemon-ui/LemonSkeleton'import { humanFriendlyDetailedTime } from 'lib/utils/datetime'import type { ScratchpadEntryApi } from 'products/signals/frontend/generated/api.schemas'+import { scratchpadLogic } from '../../logics/scratchpadLogic'import { stripScoutPrefix } from '../../utils/scoutRunsWindow'type LemonTagType = ComponentProps<typeof LemonTag>['type']@@ -39,9 +42,18 @@ function splitKey(key: string): { kind: string | null; body: string } {* grammar of the scout emission cards: a header (chevron · kind · key · updated time) that stays* visible, a 2-line markdown preview when collapsed, the full body plus an attribution footer* (which scout created it, when, and how long it's been carried forward) when open.+ *+ * The list only carries previews, so a long note's tail arrives on expand — until it lands, the+ * preview stays on screen with a skeleton under it rather than the card going blank.*/export function ScratchpadEntryCard({ entry }: { entry: ScratchpadEntryApi }): JSX.Element {- const [expanded, setExpanded] = useState(false)+ const { expandedKeys, fullContentByKey, loadingContentKeys } = useValues(scratchpadLogic)+ const { toggleEntry } = useActions(scratchpadLogic)++ const expanded = expandedKeys.includes(entry.key)+ const isLoadingContent = loadingContentKeys.includes(entry.key)+ // `hasOwn` guards against a key like `constructor` resolving to an inherited prototype value.+ const content = Object.hasOwn(fullContentByKey, entry.key) ? fullContentByKey[entry.key] : entry.contentconst { kind, body } = splitKey(entry.key)const scoutName = entry.created_by_skill ? stripScoutPrefix(entry.created_by_skill) : null@@ -55,7 +67,7 @@ export function ScratchpadEntryCard({ entry }: { entry: ScratchpadEntryApi }): J<div className="flex flex-col rounded border border-primary bg-bg-light"><buttontype="button"- onClick={() => setExpanded((value) => !value)}+ onClick={() => toggleEntry(entry.key)}className="flex items-center gap-2 px-3 py-2 text-left"aria-expanded={expanded}>@@ -82,9 +94,11 @@ export function ScratchpadEntryCard({ entry }: { entry: ScratchpadEntryApi }): JdisableImagesclassName={expanded ? 'text-sm text-primary' : 'text-sm text-primary line-clamp-2'}>- {entry.content || '_No content._'}+ {content || '_No content._'}</LemonMarkdown>+ {expanded && isLoadingContent && <LemonSkeleton className="h-4 w-2/3 mt-1" />}+{expanded && (entry.created_at || scoutName || entry.created_by_run_id) && (<div className="flex flex-wrap items-center gap-x-3 gap-y-1 border-t pt-2 mt-2 text-xs text-tertiary">{entry.created_at && <span>Created {humanFriendlyDetailedTime(entry.created_at)}</span>}diff --git a/frontend/src/scenes/inbox/logics/scratchpadLogic.test.ts b/frontend/src/scenes/inbox/logics/scratchpadLogic.test.tsnew file mode 100644index 000000000000..9cfd4b35c3b3--- /dev/null+++ b/frontend/src/scenes/inbox/logics/scratchpadLogic.test.ts@@ -0,0 +1,129 @@+/* oxlint-disable react-hooks/rules-of-hooks -- useMocks is a test helper, not a React hook */+import { expectLogic } from 'kea-test-utils'++import { useMocks } from '~/mocks/jest'+import { initKeaTests } from '~/test/init'++import type { ScratchpadEntryApi } from 'products/signals/frontend/generated/api.schemas'++import { SCRATCHPAD_PREVIEW_CHARS, scratchpadLogic } from './scratchpadLogic'++const SCRATCHPAD_URL = '/api/projects/:team_id/signals/scout/scratchpad/'++const entry = (key: string, content: string): ScratchpadEntryApi =>+ ({+ key,+ content,+ created_at: '2026-07-01T00:00:00Z',+ updated_at: '2026-07-02T00:00:00Z',+ }) as ScratchpadEntryApi++// A body that fills the preview window exactly is what a truncated note looks like on the wire —+// the API slices without leaving a marker.+const TRUNCATED = entry('pattern:long', 'x'.repeat(SCRATCHPAD_PREVIEW_CHARS))+const ALSO_TRUNCATED = entry('pattern:also-long', 'y'.repeat(SCRATCHPAD_PREVIEW_CHARS))+const WHOLE = entry('pattern:short', 'a short note')+const fullBodyFor = (key: string): string => `${key} full body, tail included`++describe('scratchpadLogic', () => {+ let logic: ReturnType<typeof scratchpadLogic.build>+ let searchRequests: URLSearchParams[]++ beforeEach(async () => {+ searchRequests = []+ useMocks({+ get: {+ [SCRATCHPAD_URL]: ({ request }) => {+ const params = new URL(request.url).searchParams+ searchRequests.push(params)+ // The expand-time lookup is an exact `key` match; everything else is the list read.+ const key = params.get('key')+ if (key) {+ return [200, [entry(key, fullBodyFor(key))]]+ }+ return [200, [TRUNCATED, ALSO_TRUNCATED, WHOLE]]+ },+ },+ })+ initKeaTests()+ logic = scratchpadLogic()+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()+ searchRequests = []+ })++ afterEach(() => {+ logic.unmount()+ })++ it('asks for previews rather than full bodies on the list read', async () => {+ logic.unmount()+ searchRequests = []+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()++ expect(searchRequests[0].get('content_max_chars')).toEqual(String(SCRATCHPAD_PREVIEW_CHARS))+ })++ it('fetches the full body by exact key when a truncated entry is expanded', async () => {+ logic.actions.toggleEntry(TRUNCATED.key)+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.fullContentByKey[TRUNCATED.key]).toEqual(fullBodyFor(TRUNCATED.key))+ expect(logic.values.loadingContentKeys).toEqual([])+ // Not `text`: that is an ILIKE over key and content, so entries merely quoting this key+ // can crowd the row we asked for out of the window.+ expect(searchRequests[0].get('key')).toEqual(TRUNCATED.key)+ expect(searchRequests[0].get('text')).toBeNull()+ })++ // A shared per-action breakpoint would unwind the first request when the second starts,+ // leaving the first key stuck in `loadingContentKeys` behind a skeleton forever — and+ // `toggleEntry` skips keys already loading, so it could never recover.+ it('resolves both bodies when two notes are expanded back to back', async () => {+ logic.actions.toggleEntry(TRUNCATED.key)+ logic.actions.toggleEntry(ALSO_TRUNCATED.key)+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.fullContentByKey).toEqual({+ [TRUNCATED.key]: fullBodyFor(TRUNCATED.key),+ [ALSO_TRUNCATED.key]: fullBodyFor(ALSO_TRUNCATED.key),+ })+ expect(logic.values.loadingContentKeys).toEqual([])+ })++ // The whole point of the preview projection is that opening a note that already arrived+ // complete costs nothing. Dropping the truncation guard would put a request behind every+ // expand — the regression this change exists to avoid.+ it.each([+ ['an entry that arrived whole', WHOLE.key, false],+ ['a truncated entry', TRUNCATED.key, true],+ ])('expanding %s issues a lookup: %s', async (_name, key, expectedRequest) => {+ logic.actions.toggleEntry(key)+ await expectLogic(logic).toFinishAllListeners()++ expect(searchRequests.length).toEqual(expectedRequest ? 1 : 0)+ })++ it('does not re-fetch a body it already has, or fetch on collapse', async () => {+ logic.actions.toggleEntry(TRUNCATED.key)+ await expectLogic(logic).toFinishAllListeners()+ logic.actions.toggleEntry(TRUNCATED.key)+ logic.actions.toggleEntry(TRUNCATED.key)+ await expectLogic(logic).toFinishAllListeners()++ expect(searchRequests.length).toEqual(1)+ expect(logic.values.expandedKeys).toEqual([TRUNCATED.key])+ })++ it('keeps the card usable when the body lookup fails', async () => {+ useMocks({ get: { [SCRATCHPAD_URL]: () => [500, {}] } })++ logic.actions.toggleEntry(TRUNCATED.key)+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.loadingContentKeys).toEqual([])+ expect(logic.values.fullContentByKey).toEqual({})+ expect(logic.values.expandedKeys).toEqual([TRUNCATED.key])+ })+})diff --git a/frontend/src/scenes/inbox/logics/scratchpadLogic.ts b/frontend/src/scenes/inbox/logics/scratchpadLogic.tsindex f64ba5d33298..b352b3467474 100644--- a/frontend/src/scenes/inbox/logics/scratchpadLogic.ts+++ b/frontend/src/scenes/inbox/logics/scratchpadLogic.ts@@ -13,11 +13,16 @@ export type ScratchpadGrouping = 'recent' | 'topic'// Search reruns the server-side ILIKE on every keystroke; debounce so typing doesn't// fire a request per character.const SEARCH_DEBOUNCE_MS = 300-// `list` caps at 500 newest-first with no pagination wrapper — pull the whole window in+// `list` caps at 1000 newest-first with no pagination wrapper — pull the whole window in// one read and group/search client-side. The endpoint exposes a `date_to` cursor for-// walking past the cap; a team that routinely exceeds 500 wants that wired into a "load+// walking past the cap; a team that routinely exceeds 1000 wants that wired into a "load// more" here, not a bigger single read.-const SCRATCHPAD_FETCH_LIMIT = 500+const SCRATCHPAD_FETCH_LIMIT = 1000+// Bodies are an unbounded TextField clamped at 50k chars on write, so a full-fat window of+// 1000 entries is a payload nobody needs: the card renders a 2-line clamp until you open it.+// Pull previews for the list and fetch the one body you expand. Sized well past two lines so+// the overwhelming majority of notes arrive complete and never need the second read.+export const SCRATCHPAD_PREVIEW_CHARS = 1200/** One namespace cluster in the "By topic" view: the raw prefix, a friendly label, and its entries. */export interface ScratchpadNamespaceGroup {@@ -40,15 +45,26 @@ export function humanizeNamespace(namespace: string): string {return namespace.replace(/[-_]/g, ' ').replace(/\b\w/g, (char) => char.toUpperCase())}+/** Whether a listed entry's body may have been cut short by the preview projection. The API+ * truncates with a bare slice and sends no "there's more" marker, so preview-length is the only+ * signal available. A body sitting exactly on the boundary re-fetches once and resolves to the+ * same text, which is why this is the cheap direction to be wrong in. */+export function isPreviewTruncated(content: string | null | undefined): boolean {+ return (content?.length ?? 0) >= SCRATCHPAD_PREVIEW_CHARS+}+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface scratchpadLogicValues {entries: ScratchpadEntryApi[] | nullentriesLoading: boolean+ expandedKeys: string[]expandedNamespaces: string[]+ fullContentByKey: Record<string, string>grouping: ScratchpadGroupinggroups: ScratchpadNamespaceGroup[]lastUpdatedAt: string | nullloadFailed: boolean+ loadingContentKeys: string[]searchText: stringtotalCount: number | null}@@ -70,12 +86,28 @@ export interface scratchpadLogicActions {entries: ScratchpadEntryApi[]payload?: void}+ loadFullContent: (key: string) => {+ key: string+ }+ loadFullContentFailure: (key: string) => {+ key: string+ }+ loadFullContentSuccess: (+ key: string,+ content: string+ ) => {+ content: string+ key: string+ }setGrouping: (grouping: ScratchpadGrouping) => {grouping: ScratchpadGrouping}setSearchText: (searchText: string) => {searchText: string}+ toggleEntry: (key: string) => {+ key: string+ }toggleNamespace: (namespace: string) => {namespace: string}@@ -110,6 +142,10 @@ export const scratchpadLogic = kea<scratchpadLogicType>([setSearchText: (searchText: string) => ({ searchText }),setGrouping: (grouping: ScratchpadGrouping) => ({ grouping }),toggleNamespace: (namespace: string) => ({ namespace }),+ toggleEntry: (key: string) => ({ key }),+ loadFullContent: (key: string) => ({ key }),+ loadFullContentSuccess: (key: string, content: string) => ({ key, content }),+ loadFullContentFailure: (key: string) => ({ key }),}),loaders(({ values }) => ({@@ -125,6 +161,7 @@ export const scratchpadLogic = kea<scratchpadLogicType>([const results = await signalsScoutScratchpadSearch(String(teamId), {text: text || undefined,limit: SCRATCHPAD_FETCH_LIMIT,+ content_max_chars: SCRATCHPAD_PREVIEW_CHARS,})// Drop a stale response if the search moved on while this request was in flight.breakpoint()@@ -157,6 +194,33 @@ export const scratchpadLogic = kea<scratchpadLogicType>([setGrouping: () => [],},],+ // Which entry cards are open. Lives here rather than in the card's own state so the+ // listener below can hang the full-body fetch off the same toggle.+ expandedKeys: [+ [] as string[],+ {+ toggleEntry: (state, { key }) =>+ state.includes(key) ? state.filter((k) => k !== key) : [...state, key],+ },+ ],+ // Full bodies fetched on expand, keyed by entry key. Dropped on every reload since a new+ // search returns a different set of entries (and possibly newer bodies for the same keys).+ fullContentByKey: [+ {} as Record<string, string>,+ {+ loadFullContentSuccess: (state, { key, content }) => ({ ...state, [key]: content }),+ loadEntriesSuccess: () => ({}),+ },+ ],+ loadingContentKeys: [+ [] as string[],+ {+ loadFullContent: (state, { key }) => (state.includes(key) ? state : [...state, key]),+ loadFullContentSuccess: (state, { key }) => state.filter((k) => k !== key),+ loadFullContentFailure: (state, { key }) => state.filter((k) => k !== key),+ loadEntriesSuccess: () => [],+ },+ ],}),selectors({@@ -195,11 +259,57 @@ export const scratchpadLogic = kea<scratchpadLogicType>([],}),- listeners(({ actions }) => ({+ listeners(({ actions, values }) => ({setSearchText: async (_, breakpoint) => {await breakpoint(SEARCH_DEBOUNCE_MS)actions.loadEntries()},++ // Opening a card is the only moment a full body is worth fetching — and only when the+ // preview actually cut one off. Collapsing, re-opening a cached entry, or opening a note+ // that arrived whole all stay local.+ toggleEntry: ({ key }) => {+ if (!values.expandedKeys.includes(key)) {+ return+ }+ // `hasOwn`, not `in`: keys are scout-authored, and `'toString' in {}` is true.+ if (Object.hasOwn(values.fullContentByKey, key) || values.loadingContentKeys.includes(key)) {+ return+ }+ const entry = values.entries?.find((e) => e.key === key)+ if (entry && isPreviewTruncated(entry.content)) {+ actions.loadFullContent(key)+ }+ },++ // Deliberately no `breakpoint()`: kea's is per-action, not per-key, so opening a second+ // note would unwind the first request mid-flight and strand its key in+ // `loadingContentKeys` — a card stuck on a skeleton that `toggleEntry` then refuses to+ // retry. Every result is keyed, so a late response is written to its own entry and a+ // superseded one is harmless.+ loadFullContent: async ({ key }) => {+ const teamId = teamLogic.values.currentTeamId+ if (!teamId) {+ actions.loadFullContentFailure(key)+ return+ }+ try {+ // `key` is an exact match on the unique (team, key) pair. `text` would be an ILIKE+ // across key *and* content, which can bury the row we asked for under newer+ // entries that merely mention it.+ const results = await signalsScoutScratchpadSearch(String(teamId), { key })+ const match = results.find((entry) => entry.key === key)+ if (match) {+ actions.loadFullContentSuccess(key, match.content ?? '')+ return+ }+ actions.loadFullContentFailure(key)+ } catch {+ // The preview stays on screen, so a failure costs the reader the tail of one note+ // rather than the whole card.+ actions.loadFullContentFailure(key)+ }+ },})),afterMount(({ actions }) => {diff --git a/products/signals/backend/scout_harness/serializers.py b/products/signals/backend/scout_harness/serializers.pyindex 5ec99ce69986..287d6e08a31d 100644--- a/products/signals/backend/scout_harness/serializers.py+++ b/products/signals/backend/scout_harness/serializers.py@@ -428,6 +428,14 @@ class SearchMemoryQuerySerializer(serializers.Serializer):allow_blank=True,help_text="ILIKE substring match against `content`. Omit to return the most recent entries.",)+ key = serializers.CharField(+ required=False,+ help_text=(+ "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."+ ),+ )date_from = serializers.DateTimeField(required=False,help_text="ISO-8601 inclusive lower bound on `updated_at`. Omit to skip the lower bound.",@@ -459,8 +467,8 @@ class SearchMemoryQuerySerializer(serializers.Serializer):limit = serializers.IntegerField(required=False,min_value=1,- max_value=500,- help_text="Max rows to return (default 20, hard cap 500).",+ max_value=1000,+ help_text="Max rows to return (default 20, hard cap 1000).",)diff --git a/products/signals/backend/scout_harness/tools/scratchpad.py b/products/signals/backend/scout_harness/tools/scratchpad.pyindex 49f2f02718fb..49207682b016 100644--- a/products/signals/backend/scout_harness/tools/scratchpad.py+++ b/products/signals/backend/scout_harness/tools/scratchpad.py@@ -16,13 +16,15 @@ from datetime import datetimefrom typing import Anyfrom django.db import IntegrityError, transaction+from django.db.models import Q, QuerySet, TextField, Value+from django.db.models.functions import Leftfrom products.signals.backend.models import SignalScratchpadfrom products.signals.backend.scout_harness.tools.runs import _build_task_url# Defensive cap on search results.DEFAULT_SCRATCHPAD_SEARCH_LIMIT = 20-MAX_SCRATCHPAD_SEARCH_LIMIT = 500+MAX_SCRATCHPAD_SEARCH_LIMIT = 1000# Keys/content are agent-chosen prose. Match the model's column lengths so callers# get a clean error before hitting the DB.@@ -56,6 +58,7 @@ def search_scratchpad(*,team_id: int,text: str | None = None,+ key: str | None = None,date_from: datetime | None = None,date_to: datetime | None = None,limit: int = DEFAULT_SCRATCHPAD_SEARCH_LIMIT,@@ -67,6 +70,11 @@ def search_scratchpad(`text` matches ILIKE against `content` and `key`. The previous `tags` filter+ GIN index were dropped in PR 2 review.+ `key` is an exact match on the unique `(team, key)` pair — at most one row, and the+ only way to fetch a known entry reliably. `text` can't stand in for it: an ILIKE+ across content *and* key means a key mentioned inside enough other bodies pushes the+ row you wanted past the limit.+`date_from` / `date_to` are a half-open window on `updated_at` (the entry'ssort key) — `updated_at >= date_from` and `updated_at < date_to`. Pass `date_to`(the `updated_at` of the oldest entry seen) to walk backwards past the result@@ -80,14 +88,19 @@ def search_scratchpad(pick the entries worth a full read, then re-query the chosen ones.- `content_max_chars=N` truncates each `content` to the first `N` characters(a preview). Ignored when `keys_only=True`, which already drops the body.++ Both projections are applied in SQL, not after the fact: a preview that Postgres+ trims still costs the full row to fetch and hand to Django, which defeats the point+ on exactly the wide scans these exist for."""clamped_limit = _clamp_search_limit(limit)# Join the creating run (and its task_run) so per-row skill/url resolution in `_to_entry`# stays a single query rather than an N+1 across the result window.qs = SignalScratchpad.objects.filter(team_id=team_id).select_related("created_by_run", "created_by_run__task_run")+ qs = _project_content_in_sql(qs, keys_only=keys_only, content_max_chars=content_max_chars)+ if key:+ qs = qs.filter(key=key)if text:- from django.db.models import Q-qs = qs.filter(Q(content__icontains=text) | Q(key__icontains=text))if date_from is not None:qs = qs.filter(updated_at__gte=date_from)@@ -182,7 +195,7 @@ def _to_entry(task_run = getattr(run, "task_run", None) if run is not None else Nonereturn ScratchpadEntry(key=row.key,- content=_project_content(row.content, keys_only=keys_only, content_max_chars=content_max_chars),+ 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,created_by_run_id=str(run_pk) if run_pk else None,@@ -195,6 +208,36 @@ def _to_entry()+def _project_content_in_sql(+ qs: QuerySet[SignalScratchpad], *, keys_only: bool, content_max_chars: int | None+) -> QuerySet[SignalScratchpad]:+ """Push the body projection into the query so Postgres never ships prose we drop.++ `content` is unbounded (50k chars by the write clamp), so a 1000-row scan that trims+ in Python still moves ~50 MB through the driver first. `defer` keeps the column out+ of the SELECT; the annotation carries whatever slice the caller actually asked for.+ """+ # `Left` rejects a length below 1, and a zero-char preview is a blank body anyway.+ if keys_only or (content_max_chars is not None and content_max_chars <= 0):+ return qs.defer("content").annotate(projected_content=Value("", output_field=TextField()))+ if content_max_chars is None:+ return qs+ # Clamp to the write cap: a preview longer than the longest storable body is a no-op, and an+ # unbounded value would reach Postgres as an out-of-range `LEFT()` length and 500.+ return qs.defer("content").annotate(+ projected_content=Left("content", min(content_max_chars, MAX_SCRATCHPAD_CONTENT_LENGTH))+ )+++def _resolve_content(row: SignalScratchpad, *, keys_only: bool, content_max_chars: int | None) -> str:+ # Present only on the search path, where the projection was pushed into SQL above.+ # The write path returns whole rows and falls through to the in-memory projection.+ projected = getattr(row, "projected_content", None)+ if projected is not None:+ return projected+ return _project_content(row.content, keys_only=keys_only, content_max_chars=content_max_chars)++def _project_content(content: str, *, keys_only: bool, content_max_chars: int | None) -> str:"""Apply the search projection to a row's `content`: blank it for `keys_only`,or truncate to a preview for `content_max_chars`. A negative max clamps to 0."""diff --git a/products/signals/backend/scout_harness/views.py b/products/signals/backend/scout_harness/views.pyindex 8d046244e5d9..8c29bd648a9f 100644--- a/products/signals/backend/scout_harness/views.py+++ b/products/signals/backend/scout_harness/views.py@@ -964,7 +964,7 @@ class SignalScratchpadViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):authentication_classes = [SessionAuthentication, PersonalAPIKeyAuthentication, OAuthAccessTokenAuthentication]permission_classes = [IsAuthenticated, APIScopePermission]scope_object = "signal_scout"- # `list` returns a raw newest-first array (capped at limit=500 by the query serializer),+ # `list` returns a raw newest-first array (capped at limit=1000 by the query serializer),# not a paginated wrapper. See SignalScoutRunViewSet for the same rationale.pagination_class = None@@ -988,11 +988,12 @@ class SignalScratchpadViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):summary="Search the scout scratchpad",description=("Return `SignalScratchpad` entries for this project, newest-first. ILIKE matches on `content` "- "and `key`. `date_from` / `date_to` are a half-open window on `updated_at` (`>= date_from`, "+ "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 500."+ "from returning every entry's full prose. Results capped at 1000."),operation_id="signals_scout_scratchpad_search",)@@ -1007,6 +1008,7 @@ class SignalScratchpadViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):rows = search_scratchpad(team_id=_canonical_team_id(self),text=text,+ key=validated.get("key") or None,date_from=date_from,date_to=date_to,limit=limit,diff --git a/products/signals/backend/test/test_scout_harness_tools.py b/products/signals/backend/test/test_scout_harness_tools.pyindex 28fcdddec405..60cf1e0a3134 100644--- a/products/signals/backend/test/test_scout_harness_tools.py+++ b/products/signals/backend/test/test_scout_harness_tools.py@@ -515,6 +515,33 @@ class TestSearchScratchpad(BaseTest):assert results[0].content == "abcdefghij"+ @parameterized.expand([(0,), (-5,)])+ def test_non_positive_content_max_chars_blanks_the_body(self, content_max_chars: int) -> None:+ remember(team_id=self.team.id, key="k1", content="abcdefghij")++ results = search_scratchpad(team_id=self.team.id, content_max_chars=content_max_chars)++ assert results[0].content == ""++ def test_oversized_content_max_chars_returns_the_whole_body(self) -> None:+ remember(team_id=self.team.id, key="k1", content="abcdefghij")++ # Unclamped this reaches Postgres as an out-of-range LEFT() length and 500s.+ results = search_scratchpad(team_id=self.team.id, content_max_chars=2**40)++ assert results[0].content == "abcdefghij"++ 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.+ for i in range(5):+ remember(team_id=self.team.id, key=f"noise:{i}", content="see pattern:target for context")++ results = search_scratchpad(team_id=self.team.id, key="pattern:target", limit=1)++ assert [e.key for e in results] == ["pattern:target"]+ assert results[0].content == "the body we want back"+# --- emit adapter tests ---diff --git a/products/signals/frontend/generated/api.schemas.ts b/products/signals/frontend/generated/api.schemas.tsindex cbd0b884d53b..f16a9bd43eec 100644--- a/products/signals/frontend/generated/api.schemas.ts+++ b/products/signals/frontend/generated/api.schemas.ts@@ -3211,14 +3211,19 @@ 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+ /**+ * 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+ */+ key?: string/*** When true, blank each entry's `content` and return only keys + metadata. Use to scan which memories exist without pulling their (potentially large) bodies, then re-query the ones worth a full read. Takes precedence over `content_max_chars`.*/keys_only?: boolean/**- * Max rows to return (default 20, hard cap 500).+ * Max rows to return (default 20, hard cap 1000).* @minimum 1- * @maximum 500+ * @maximum 1000*/limit?: number/**diff --git a/products/signals/frontend/generated/api.ts b/products/signals/frontend/generated/api.tsindex a449344c5775..b44c48289e4c 100644--- a/products/signals/frontend/generated/api.ts+++ b/products/signals/frontend/generated/api.ts@@ -960,7 +960,7 @@ export const getSignalsScoutScratchpadSearchUrl = (projectId: string, params?: S}/**- * Return `SignalScratchpad` entries for this project, newest-first. ILIKE matches on `content` and `key`. `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 500.+ * 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.* @summary Search the scout scratchpad*/export const signalsScoutScratchpadSearch = async (diff --git a/products/signals/mcp/tools.yaml b/products/signals/mcp/tools.yamlindex 46ef395ce931..943a6035064f 100644--- a/products/signals/mcp/tools.yaml+++ b/products/signals/mcp/tools.yaml@@ -705,7 +705,7 @@ tools:/ exclusive upper bound on `updated_at`) to scope to a window — set `date_to` to the `updated_at` of theoldest entry from the prior page to walk past the cap. Pass `keys_only=true` to scan which memories existwithout 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 500.+ — 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 cf4180253991..dc76523e1cdc 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -7919,7 +7919,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 500.",+ "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.","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 1431a7c82d71..e19c1fd22408 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -8454,7 +8454,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 500.",+ "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.","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 cb08580f9462..2bc5d46fd7de 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -79043,14 +79043,19 @@ 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;+ /**+ * 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+ */+ key?: string;/*** When true, blank each entry's `content` and return only keys + metadata. Use to scan which memories exist without pulling their (potentially large) bodies, then re-query the ones worth a full read. Takes precedence over `content_max_chars`.*/keys_only?: boolean;/**- * Max rows to return (default 20, hard cap 500).+ * Max rows to return (default 20, hard cap 1000).* @minimum 1- * @maximum 500+ * @maximum 1000*/limit?: number;/**diff --git a/services/mcp/src/generated/signals/api.ts b/services/mcp/src/generated/signals/api.tsindex 63b311656ffb..518d014a8095 100644--- a/services/mcp/src/generated/signals/api.ts+++ b/services/mcp/src/generated/signals/api.ts@@ -1025,7 +1025,7 @@ export const SignalsScoutRunsRecentEmissionsQueryParams = /* @__PURE__ */ zod.ob})/**- * Return `SignalScratchpad` entries for this project, newest-first. ILIKE matches on `content` and `key`. `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 500.+ * 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.* @summary Search the scout scratchpad*/export const SignalsScoutScratchpadSearchParams = /* @__PURE__ */ zod.object({@@ -1038,7 +1038,7 @@ export const SignalsScoutScratchpadSearchParams = /* @__PURE__ */ zod.object({export const signalsScoutScratchpadSearchQueryContentMaxCharsMin = 0-export const signalsScoutScratchpadSearchQueryLimitMax = 500+export const signalsScoutScratchpadSearchQueryLimitMax = 1000export const SignalsScoutScratchpadSearchQueryParams = /* @__PURE__ */ zod.object({content_max_chars: zod@@ -1058,6 +1058,13 @@ 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).'),+ key: zod+ .string()+ .min(1)+ .optional()+ .describe(+ '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.'+ ),keys_only: zod.boolean().optional()@@ -1069,7 +1076,7 @@ export const SignalsScoutScratchpadSearchQueryParams = /* @__PURE__ */ zod.objec.min(1).max(signalsScoutScratchpadSearchQueryLimitMax).optional()- .describe('Max rows to return (default 20, hard cap 500).'),+ .describe('Max rows to return (default 20, hard cap 1000).'),text: zod.string().optional()diff --git a/services/mcp/src/tools/generated/signals.ts b/services/mcp/src/tools/generated/signals.tsindex cec441e99452..b0b30b48319e 100644--- a/services/mcp/src/tools/generated/signals.ts+++ b/services/mcp/src/tools/generated/signals.ts@@ -947,6 +947,7 @@ const scoutScratchpadSearch = (): ToolBase<content_max_chars: params.content_max_chars,date_from: params.date_from,date_to: params.date_to,+ key: params.key,keys_only: params.keys_only,limit: params.limit,text: params.text,@@ -1435,6 +1436,7 @@ const signalsScoutScratchpadSearch = (): ToolBase<content_max_chars: params.content_max_chars,date_from: params.date_from,date_to: params.date_to,+ key: params.key,keys_only: params.keys_only,limit: params.limit,text: params.text,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 c372f12e3b10..b72626cf63c8 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,13 +18,18 @@"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"},+ "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,+ "type": "string"+ },"keys_only": {"description": "When true, blank each entry's `content` and return only keys + metadata. Use to scan which memories exist without pulling their (potentially large) bodies, then re-query the ones worth a full read. Takes precedence over `content_max_chars`.","type": "boolean"},"limit": {- "description": "Max rows to return (default 20, hard cap 500).",- "maximum": 500,+ "description": "Max rows to return (default 20, hard cap 1000).",+ "maximum": 1000,"minimum": 1,"type": "number"},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 c372f12e3b10..b72626cf63c8 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,13 +18,18 @@"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"},+ "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,+ "type": "string"+ },"keys_only": {"description": "When true, blank each entry's `content` and return only keys + metadata. Use to scan which memories exist without pulling their (potentially large) bodies, then re-query the ones worth a full read. Takes precedence over `content_max_chars`.","type": "boolean"},"limit": {- "description": "Max rows to return (default 20, hard cap 500).",- "maximum": 500,+ "description": "Max rows to return (default 20, hard cap 1000).",+ "maximum": 1000,"minimum": 1,"type": "number"},