feat(search): filters, sorting, operators & command-palette parity (#9327)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Company search is the primary way operators find issues, comments,
documents, artifacts, agents, and projects across a busy company
> - Search previously supported only a bare text query: no way to narrow
by status/assignee/project/label/date, no sort control, no typed
operators, and weak relevance/snippets meant hunting through noise
> - As companies accumulate tens of thousands of items, unfiltered
single-sort search stops scaling for day-to-day operator workflows
> - This pull request adds a full filtering model (filter bar, chips,
mobile sheet, URL state), sort modes, typed query operators (`status:`,
`assignee:`, `type:`, …) with command-palette parity,
relevance/snippet/deep-link improvements, zero-results recovery, and the
supporting shared validators, backend service work, and DB indexes
> - The benefit is that operators can go from a vague query to the exact
item in a couple of keystrokes, on desktop and mobile, with shareable
filtered-search URLs

## Linked Issues or Issue Description

No existing public GitHub issue; describing the underlying feature
request inline (per feature_request template):

- **Problem:** Company search accepted only a plain text query. Users
could not filter results by status, assignee, project, label, or
recency; could not change result ordering; and got no guidance when
filters emptied the result set.
- **Desired solution:** Structured search filters (UI controls + typed
query operators + URL parameters), selectable sort modes, better
relevance and snippets with exact deep links, and parity between the
search page and the command palette.
- **Alternatives considered:** Client-side filtering of unfiltered
results (does not scale past the fetch limit); a separate "advanced
search" page (splits the surface and duplicates state handling).

Related (not duplicate) PRs found while searching: #4848 (issue search
query planning), #8235 (search rate limiting).

## What Changed

- **Shared contract:** new search filter/sort/count/zero-results types
and validators in `packages/shared` (`validators/search.ts`, types
index).
- **Backend:** `server/src/services/company-search.ts` supports issue
filters, sort modes, per-filter option counts, snippets, artifact
visibility, and zero-results loosen suggestions; single-statement match
replaces per-scope scans and predicates are trigram-index compatible
(~3.7s → ~350ms on a live 14.8k-hit corpus).
- **DB:** migration `0142_company_search_sort_indexes.sql` adds the
supporting indexes.
- **Search page (`ui/src/pages/Search.tsx`):** filter bar, removable
chips, mobile filter sheet with result-count preview, sort menu, URL
round-tripping, zero-results recovery UI.
- **Query operators (`ui/src/lib/search-query-parser.ts`):** typed
operators parsed into filters, operator autocomplete, filter pills.
- **Command palette:** operator-aware parsing and full-search handoff.
- **Stale-operator fix (latest commit):** typed operator filters are no
longer folded into persistent URL-filter state, so deleting a token
(e.g. removing `status:blocked` from the input) actually removes the
filter from subsequent requests; filter-control edits materialize
control state and strip typed tokens so a removed chip cannot resurrect
from the input.

## Verification

- `cd ui && npx vitest run src/pages/Search.test.tsx` — 19 tests
including two new red→green regressions for the stale-operator paths
(both fail on the previous commit, pass now).
- `cd ui && npx vitest run src/components/CommandPalette.test.tsx` and
`cd server && npx vitest run
src/services/company-search-service.test.ts` — operator parity and
backend filter/sort/count coverage.
- `cd ui && npx tsc --noEmit` — clean.
- Manual: open `/search`, type `auth status:blocked`, confirm the status
filter applies; delete `status:blocked`, confirm results are unfiltered
again; drive the same filters from the filter bar/chips/mobile sheet and
confirm the URL round-trips (reload/back/forward preserves state).
- Full end-to-end QA pass (9/9 acceptance checks) against the wireframes
on desktop (1280px) and mobile (390px) with a live API and browser
automation.

## Risks

- Additive migration (indexes only, no data rewrites) — safe to roll
forward; index creation cost is paid once at migrate time.
- Search request shape gains optional parameters only; old clients keep
working.
- Behavioral shift: filter-control edits now strip typed operator tokens
from the query text (their values persist as filter state) — deliberate,
so removed filters stay removed.
- Ranking changes alter result ordering for existing queries; covered by
service tests and the QA pass.

> For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and
discuss it in `#dev` before opening the PR. Feature PRs that overlap
with planned core work may need to be redirected — check the roadmap
first. See `CONTRIBUTING.md`.

## Model Used

- Claude Fable 5 (`claude-fable-5`, Anthropic, extended thinking + tool
use) — stale-operator-filter fix, regression tests, PR preparation.
- GPT-5 Codex (`codex_local` adapter) and Claude Opus 4.6
(`claude-opus-4-6`) — earlier implementation phases (backend contract,
filter UI, operators, ranking) under agent orchestration.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [ ] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
— pre-existing branch name retained to avoid closing/reopening the PR
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes (no
user-facing docs affected)
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green (pending re-run on latest commit)
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
(pending re-review of the stale-filter fix)
- [x] I will address all Greptile and reviewer comments before
requesting merge

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
authored and GitHub committed 2026-07-09 19:32:58 -05:00
1 parent cec0fc249a
commit 606aa4f266
28 files changed
+4423 -401

No files matched your search

+159 -14
View File
@@ -1,5 +1,7 @@
import { z } from "zod";
import { COMPANY_SEARCH_SCOPES } from "../types/search.js";
import { ISSUE_PRIORITIES, ISSUE_STATUSES } from "../constants.js";
import { isUuidLike } from "../agent-url-key.js";
import { COMPANY_SEARCH_SCOPES, COMPANY_SEARCH_SORTS } from "../types/search.js";
export const COMPANY_SEARCH_MAX_QUERY_LENGTH = 200;
export const COMPANY_SEARCH_MAX_TOKENS = 8;
@@ -7,31 +9,174 @@ export const COMPANY_SEARCH_DEFAULT_LIMIT = 20;
export const COMPANY_SEARCH_MAX_LIMIT = 50;
export const COMPANY_SEARCH_MAX_OFFSET = 200;
const UPDATED_WITHIN_RE = /^[1-9]\d{0,2}(h|d|w|m)$/;
function firstQueryValue(value: unknown): unknown {
return Array.isArray(value) ? value[0] : value;
}
function clampInteger(value: unknown, fallback: number, min: number, max: number) {
function queryValues(value: unknown): unknown[] {
if (value === undefined || value === null) return [];
return Array.isArray(value) ? value : [value];
}
function parseOptionalString(value: unknown, ctx: z.RefinementCtx, field: string): string | undefined {
const raw = firstQueryValue(value);
const numeric = typeof raw === "number"
? raw
: typeof raw === "string" && raw.trim().length > 0
? Number.parseInt(raw, 10)
: Number.NaN;
if (!Number.isFinite(numeric)) return fallback;
return Math.min(max, Math.max(min, Math.floor(numeric)));
if (raw === undefined || raw === null) return undefined;
if (typeof raw !== "string" && typeof raw !== "number") {
ctx.addIssue({ code: z.ZodIssueCode.custom, message: `${field} must be a string` });
return undefined;
}
const normalized = String(raw).trim();
return normalized.length > 0 ? normalized : undefined;
}
function parseIntegerQuery(
value: unknown,
ctx: z.RefinementCtx,
field: string,
fallback: number,
min: number,
max: number,
): number {
const raw = firstQueryValue(value);
if (raw === undefined || raw === null || raw === "") return fallback;
const text = typeof raw === "number" ? String(raw) : typeof raw === "string" ? raw.trim() : "";
if (!/^-?\d+$/.test(text)) {
ctx.addIssue({ code: z.ZodIssueCode.custom, message: `${field} must be an integer` });
return fallback;
}
const numeric = Number.parseInt(text, 10);
if (!Number.isInteger(numeric) || numeric < min || numeric > max) {
const range = min === 0 ? `between 0 and ${max}` : `between ${min} and ${max}`;
ctx.addIssue({ code: z.ZodIssueCode.custom, message: `${field} must be ${range}` });
return fallback;
}
return numeric;
}
function parseEnumList<T extends string>(
value: unknown,
ctx: z.RefinementCtx,
field: string,
allowed: readonly T[],
): T[] {
const allowedSet = new Set<string>(allowed);
const values: T[] = [];
for (const rawEntry of queryValues(value)) {
if (typeof rawEntry !== "string") {
ctx.addIssue({ code: z.ZodIssueCode.custom, message: `${field} must be a comma-separated string` });
continue;
}
for (const rawItem of rawEntry.split(",")) {
const item = rawItem.trim();
if (!item) continue;
if (!allowedSet.has(item)) {
ctx.addIssue({ code: z.ZodIssueCode.custom, message: `${field} contains an unsupported value` });
continue;
}
if (!values.includes(item as T)) values.push(item as T);
}
}
return values;
}
function parseOptionalUuid(value: unknown, ctx: z.RefinementCtx, field: string): string | undefined {
const normalized = parseOptionalString(value, ctx, field);
if (normalized === undefined) return undefined;
if (!isUuidLike(normalized)) {
ctx.addIssue({ code: z.ZodIssueCode.custom, message: `${field} must be a UUID` });
return undefined;
}
return normalized;
}
function parseAssigneeAgentId(value: unknown, ctx: z.RefinementCtx): string | null | undefined {
const normalized = parseOptionalString(value, ctx, "assigneeAgentId");
if (normalized === undefined) return undefined;
if (normalized.toLowerCase() === "null") return null;
if (!isUuidLike(normalized)) {
ctx.addIssue({ code: z.ZodIssueCode.custom, message: "assigneeAgentId must be a UUID or 'null'" });
return undefined;
}
return normalized;
}
function parseUpdatedAfter(value: unknown, ctx: z.RefinementCtx): string | undefined {
const normalized = parseOptionalString(value, ctx, "updatedAfter");
if (normalized === undefined) return undefined;
const date = new Date(normalized);
if (Number.isNaN(date.getTime())) {
ctx.addIssue({ code: z.ZodIssueCode.custom, message: "updatedAfter must be a valid date" });
return undefined;
}
return date.toISOString();
}
function parseUpdatedWithin(value: unknown, ctx: z.RefinementCtx): string | undefined {
const normalized = parseOptionalString(value, ctx, "updatedWithin");
if (normalized === undefined) return undefined;
if (!UPDATED_WITHIN_RE.test(normalized)) {
ctx.addIssue({ code: z.ZodIssueCode.custom, message: "updatedWithin must be a duration like 24h, 7d, 4w, or 3m" });
return undefined;
}
return normalized;
}
export const companySearchQuerySchema = z.object({
q: z.preprocess(firstQueryValue, z.string().optional().default(""))
.transform((value) => value.slice(0, COMPANY_SEARCH_MAX_QUERY_LENGTH)),
scope: z.preprocess(firstQueryValue, z.enum(COMPANY_SEARCH_SCOPES).catch("all")).optional().default("all"),
q: z.unknown()
.optional()
.transform((value, ctx) => (parseOptionalString(value, ctx, "q") ?? "").slice(0, COMPANY_SEARCH_MAX_QUERY_LENGTH)),
scope: z.unknown()
.optional()
.transform((value, ctx) => {
const normalized = parseOptionalString(value, ctx, "scope") ?? "all";
if (!(COMPANY_SEARCH_SCOPES as readonly string[]).includes(normalized)) {
ctx.addIssue({ code: z.ZodIssueCode.custom, message: "scope must be a supported search scope" });
return "all";
}
return normalized as (typeof COMPANY_SEARCH_SCOPES)[number];
}),
limit: z.unknown()
.optional()
.transform((value) => clampInteger(value, COMPANY_SEARCH_DEFAULT_LIMIT, 1, COMPANY_SEARCH_MAX_LIMIT)),
.transform((value, ctx) => parseIntegerQuery(value, ctx, "limit", COMPANY_SEARCH_DEFAULT_LIMIT, 1, COMPANY_SEARCH_MAX_LIMIT)),
offset: z.unknown()
.optional()
.transform((value) => clampInteger(value, 0, 0, COMPANY_SEARCH_MAX_OFFSET)),
.transform((value, ctx) => parseIntegerQuery(value, ctx, "offset", 0, 0, COMPANY_SEARCH_MAX_OFFSET)),
status: z.unknown()
.optional()
.transform((value, ctx) => parseEnumList(value, ctx, "status", ISSUE_STATUSES)),
priority: z.unknown()
.optional()
.transform((value, ctx) => parseEnumList(value, ctx, "priority", ISSUE_PRIORITIES)),
assigneeAgentId: z.unknown()
.optional()
.transform((value, ctx) => parseAssigneeAgentId(value, ctx)),
assigneeUserId: z.unknown()
.optional()
.transform((value, ctx) => parseOptionalString(value, ctx, "assigneeUserId")),
projectId: z.unknown()
.optional()
.transform((value, ctx) => parseOptionalUuid(value, ctx, "projectId")),
labelId: z.unknown()
.optional()
.transform((value, ctx) => parseOptionalUuid(value, ctx, "labelId")),
updatedWithin: z.unknown()
.optional()
.transform((value, ctx) => parseUpdatedWithin(value, ctx)),
updatedAfter: z.unknown()
.optional()
.transform((value, ctx) => parseUpdatedAfter(value, ctx)),
sort: z.unknown()
.optional()
.transform((value, ctx) => {
const normalized = parseOptionalString(value, ctx, "sort") ?? "relevance";
if (!(COMPANY_SEARCH_SORTS as readonly string[]).includes(normalized)) {
ctx.addIssue({ code: z.ZodIssueCode.custom, message: "sort must be relevance, updated, created, or priority" });
return "relevance";
}
return normalized as (typeof COMPANY_SEARCH_SORTS)[number];
}),
});
export type CompanySearchQuery = z.infer<typeof companySearchQuerySchema>;