Skip to content

armgit / qm

Public Imported from GitHub
0

Multiplayer agent harness for work.

feat: add principal-aware core search

Joshua France01c727486301
diff --git a/src/api/agent-api-catalog.ts b/src/api/agent-api-catalog.ts
index d4db19a51..c92ae07d3 100644
--- a/src/api/agent-api-catalog.ts
+++ b/src/api/agent-api-catalog.ts
@@ -21,6 +21,19 @@ interface AgentApiFamily {
const onPath = (m: string, p: string) => (method: string, pathname: string) => method === m && pathname === p;
const FAMILIES: AgentApiFamily[] = [
+ {
+ match: onPath("POST", "/v1/search"),
+ guidance:
+ "Search uses this conversation's complete principal set as its visibility floor. Shared conversations without a complete roster fail closed.",
+ routes: [
+ {
+ method: "POST",
+ path: "/v1/search",
+ summary:
+ "search configured knowledge backends with {query, limit?}; results are visible to every person in this conversation",
+ },
+ ],
+ },
{
match: onPath("GET", "/v1/apis"),
routes: [
diff --git a/src/api/app-search.ts b/src/api/app-search.ts
new file mode 100644
index 000000000..114054df1
--- /dev/null
+++ b/src/api/app-search.ts
@@ -0,0 +1,123 @@
+import { samePerson } from "../directory/person.ts";
+import { createCoreSearch, type BackendSearchHit, type SearchBackend } from "../search/core-search.ts";
+import { createIntersectionBackend } from "../search/backends.ts";
+import { matchesSearchTerms, searchSnippet, searchTerms } from "../sessions/entry-search.ts";
+import type { Principal } from "../types.ts";
+import { collectBytes } from "../util/bytes.ts";
+import type { App, AppDeps } from "./app-types.ts";
+
+function conversationBackend(app: App): SearchBackend {
+ return createIntersectionBackend({
+ name: "conversations",
+ key: (hit) => hit.id,
+ searchForPrincipal: async (principal, query, limit) =>
+ (await app.searchSessions(principal.id, query, limit)).map((hit) => ({
+ id: `${hit.sessionId}:${hit.seq}`,
+ type: "conversation" as const,
+ ...(hit.title ? { title: hit.title } : {}),
+ snippet: hit.snippet,
+ createdAt: hit.createdAt,
+ metadata: {
+ sessionId: hit.sessionId,
+ seq: hit.seq,
+ scopeId: hit.scopeId,
+ entryType: hit.entryType,
+ ...(hit.surface ? { surface: hit.surface } : {}),
+ ...(hit.channelName ? { channelName: hit.channelName } : {}),
+ ...(hit.author ? { author: hit.author } : {}),
+ },
+ })),
+ });
+}
+function searchableFile(mimetype: string, name: string): boolean {
+ return (
+ mimetype.startsWith("text/") ||
+ /(?:json|xml|yaml|csv|markdown)/i.test(mimetype) ||
+ /\.(?:txt|md|markdown|json|jsonl|csv|tsv|xml|ya?ml)$/i.test(name)
+ );
+}
+function fileBackend(app: App): SearchBackend {
+ return {
+ name: "files",
+ async search(request) {
+ const libraries = await Promise.all(request.principals.map((p) => app.listFilesForViewer(p.id, { limit: 200 })));
+ const [first, ...rest] = libraries;
+ if (!first) return [];
+ const common = rest.map((page) => new Set([...page.owned, ...page.shared].map((file) => file.id)));
+ const files = [...first.owned, ...first.shared].filter((file) => common.every((ids) => ids.has(file.id)));
+ const terms = searchTerms(request.query);
+ const hits: BackendSearchHit[] = [];
+ for (const file of files) {
+ let text = file.name;
+ if (searchableFile(file.mimetype, file.name)) {
+ const opened = await app.openFileForViewer(file.id, request.principals[0]!.id);
+ if (opened) {
+ const collected = await collectBytes(opened.stream, { maxBytes: 512 * 1024 }).catch(() => null);
+ if (collected) text += `\n${collected.data.toString("utf8")}`;
+ }
+ }
+ if (!matchesSearchTerms(text, terms)) continue;
+ hits.push({
+ id: file.id,
+ type: "file",
+ title: file.name,
+ snippet: searchSnippet(text, terms),
+ createdAt: file.createdAt,
+ metadata: { ownerScopeId: file.ownerScopeId, sizeBytes: file.sizeBytes, direction: file.direction },
+ });
+ if (hits.length >= request.limit) break;
+ }
+ return hits;
+ },
+ };
+}
+function slackBackend(deps: AppDeps, app: App): SearchBackend | null {
+ if (!deps.surfaceCache) return null;
+ const canSee = async (principal: Principal, container: string): Promise<boolean> => {
+ const state = await deps.surfaceCache!.containerState(container);
+ if (!state) return false;
+ if (state.kind === "group") return deps.directory.groupMember(container, principal.id);
+ if (state.kind === "dm") {
+ const members = await deps.surfaceCache!.members(container);
+ return members.some((member) => samePerson(member, principal.id));
+ }
+ return app.channelVisibleTo(principal.id, container);
+ };
+ return {
+ name: "slack",
+ async search(request) {
+ const messages = await app.searchSurface(request.query, { limit: Math.min(100, request.limit * 4) });
+ const hits: BackendSearchHit[] = [];
+ for (const message of messages) {
+ const visible = await Promise.all(request.principals.map((p) => canSee(p, message.container)));
+ if (!visible.every(Boolean)) continue;
+ hits.push({
+ id: `${message.container}:${message.ts}`,
+ type: "message",
+ snippet: message.text,
+ createdAt: message.createdAt,
+ metadata: {
+ container: message.container,
+ ts: message.ts,
+ ...(message.sub ? { threadTs: message.sub } : {}),
+ ...(message.authorId ? { authorId: message.authorId } : {}),
+ ...(message.authorName ? { authorName: message.authorName } : {}),
+ },
+ });
+ if (hits.length >= request.limit) break;
+ }
+ return hits;
+ },
+ };
+}
+export function createSearchMethods(deps: AppDeps, app: App): Pick<App, "search"> {
+ const slack = slackBackend(deps, app);
+ const core = createCoreSearch(
+ [conversationBackend(app), ...(slack ? [slack] : []), fileBackend(app), ...(deps.searchBackends ?? [])],
+ {
+ onBackendError: (backend, error) =>
+ console.error(`[search] backend ${backend} failed:`, error instanceof Error ? error.message : String(error)),
+ },
+ );
+ return { search: (query, principals, limit) => core.search({ query, principals, limit }) };
+}
diff --git a/src/api/app-types.ts b/src/api/app-types.ts
index 29b284487..d722b0176 100644
--- a/src/api/app-types.ts
+++ b/src/api/app-types.ts
@@ -3,6 +3,7 @@ import type {
PendingApproval,
PendingApprovalRecord,
Permission,
+ Principal,
ScopeId,
Session,
SessionEntry,
@@ -96,6 +97,7 @@ import type { ModelProviderAvailability } from "../model/pi-models.ts";
import type { RuntimeChoice } from "../harness/harness-router.ts";
import { type ReachOpts, type ReachResolution, type ReachTarget } from "../reach/reach.ts";
import { type Project, type ProjectStore } from "../projects/project-store.ts";
+import type { SearchBackend, SearchHit } from "../search/core-search.ts";
interface DeploymentVersionView {
version: number;
@@ -287,6 +289,11 @@ export interface App {
): Promise<{ entry: SessionEntry } | null>;
listSessions(principalId: string): Promise<Session[]>;
searchSessions(principalId: string, query: string, limit?: number): Promise<SessionSearchHit[]>;
+ search(
+ query: string,
+ principals: readonly Principal[],
+ limit?: number,
+ ): Promise<{ hits: SearchHit[]; failedBackends: string[] }>;
sessionBackground(sessionId: string, viewer: string): Promise<SessionBackgroundView | null>;
readSessionBackgroundOutput(
sessionId: string,
@@ -564,6 +571,7 @@ export interface AppDeps {
modelProviders?: ModelProviderAvailability;
providerKeys?: ModelProviderAvailability;
runtimeFallback?: RuntimeChoice;
+ searchBackends?: readonly SearchBackend[];
}
export interface ContextSummary {
diff --git a/src/api/app.ts b/src/api/app.ts
index e6eec1d49..bd9a197ec 100644
--- a/src/api/app.ts
+++ b/src/api/app.ts
@@ -6,6 +6,7 @@ import { createSessionMethods } from "./app-sessions.ts";
import { createMessagingMethods } from "./app-messaging.ts";
import { createDeploymentMethods } from "./app-deployments.ts";
import { createSkillMethods } from "./app-skills.ts";
+import { createSearchMethods } from "./app-search.ts";
export type { App, AppDeps, ContextSummary, ProjectView, VisibleCron } from "./app-types.ts";
export { deploymentView, STALE_LEASE_GRACE_MS } from "./app-types.ts";
@@ -15,12 +16,13 @@ export function createApp(deps: AppDeps): App {
const app = {} as App;
const helpers = createAppHelpers(deps, app);
const ambient = createAmbientHelpers(deps, app);
- const methods: App = {
+ const methods = {
...createTurnMethods(deps, helpers, ambient),
...createSessionMethods(deps, helpers),
...createMessagingMethods(deps, helpers, ambient),
...createDeploymentMethods(deps, helpers),
...createSkillMethods(deps, helpers),
};
- return Object.assign(app, methods);
+ Object.assign(app, methods);
+ return Object.assign(app, createSearchMethods(deps, app));
}
diff --git a/src/api/routes/index.ts b/src/api/routes/index.ts
index 28503004f..7ea9ad2a6 100644
--- a/src/api/routes/index.ts
+++ b/src/api/routes/index.ts
@@ -25,6 +25,7 @@ import { contextPolicyRoutes } from "./context-policy.ts";
import { deploymentLayerRoutes } from "./deployment-layer.ts";
import { egressAuditRoutes } from "./egress-audit.ts";
import { authBrokerRoutes } from "./auth-broker.ts";
+import { searchRoutes } from "./search.ts";
import { userModelAuthRoutes } from "./user-model-auth.ts";
export const rawRoutes: ReadonlyArray<Route<BaseCtx>> = [
@@ -43,6 +44,7 @@ export const rawRoutes: ReadonlyArray<Route<BaseCtx>> = [
];
export const apiRoutes: ReadonlyArray<Route<ApiCtx>> = [
+ ...searchRoutes,
...deploymentLayerRoutes,
...turnRoutes,
...credentialRoutes,
diff --git a/src/api/routes/search.ts b/src/api/routes/search.ts
new file mode 100644
index 000000000..3a124cadb
--- /dev/null
+++ b/src/api/routes/search.ts
@@ -0,0 +1,44 @@
+import { parseScopeId, type Principal } from "../../types.ts";
+import { sendJson } from "../http.ts";
+import { isObj } from "./shared.ts";
+import type { ApiCtx, Route } from "./route.ts";
+function conversationPrincipals(ctx: ApiCtx): Principal[] | null {
+ const capability = ctx.capability!;
+ const { kind } = parseScopeId(capability.scopeId);
+ if ((kind === "channel" || kind === "group") && !capability.members?.length) return null;
+ const principals = new Map((capability.members ?? []).map((p) => [p.id.toLowerCase(), p]));
+ if (!principals.has(capability.actorId.toLowerCase()))
+ principals.set(capability.actorId.toLowerCase(), { id: capability.actorId, type: "internal" });
+ return [...principals.values()];
+}
+async function search(ctx: ApiCtx): Promise<void> {
+ if (!ctx.capability)
+ return sendJson(ctx.res, 401, { error: "capability_required", message: "agent capability token required" });
+ const body = isObj(ctx.body) ? ctx.body : {};
+ const query = typeof body.query === "string" ? body.query.trim() : "";
+ if (!query) return sendJson(ctx.res, 400, { error: "bad_request", message: "query required" });
+ const principals = conversationPrincipals(ctx);
+ if (!principals)
+ return sendJson(ctx.res, 409, {
+ error: "principal_set_unavailable",
+ message: "search requires the complete principal set for a shared conversation",
+ });
+ const result = await ctx.app.search(query, principals, typeof body.limit === "number" ? body.limit : undefined);
+ ctx.deps.auditLog?.record({
+ at: Date.now(),
+ principalId: ctx.capability.actorId,
+ action: "search.query",
+ resource: "core-search",
+ scopeLabel: ctx.capability.scopeId,
+ detail: JSON.stringify({
+ principals: principals.map((p) => p.id).sort(),
+ hitCount: result.hits.length,
+ backends: [...new Set(result.hits.map((h) => h.backend))].sort(),
+ failedBackends: result.failedBackends,
+ }),
+ });
+ return sendJson(ctx.res, 200, result);
+}
+export const searchRoutes: ReadonlyArray<Route<ApiCtx>> = [
+ { method: "POST", path: "/v1/search", auth: "either", handle: search },
+];
diff --git a/src/api/server.ts b/src/api/server.ts
index f9b1fb8d5..d9515f1ba 100644
--- a/src/api/server.ts
+++ b/src/api/server.ts
@@ -115,6 +115,7 @@ function strictPostAllowed(pathname: string, body: unknown): boolean {
pathname === "/v1/projects" ||
pathname === "/v1/conversations" ||
pathname === "/v1/memory/search" ||
+ pathname === "/v1/search" ||
pathname === "/v1/memory/restore" ||
pathname.startsWith("/v1/run-signals/") ||
/^\/v1\/conversations\/[^/]+\/fork$/.test(pathname)
diff --git a/src/search/backends.ts b/src/search/backends.ts
new file mode 100644
index 000000000..136393d4b
--- /dev/null
+++ b/src/search/backends.ts
@@ -0,0 +1,21 @@
+import type { Principal } from "../types.ts";
+import type { BackendSearchHit, SearchBackend } from "./core-search.ts";
+
+export function createIntersectionBackend(opts: {
+ name: string;
+ key: (hit: BackendSearchHit) => string;
+ searchForPrincipal: (principal: Principal, query: string, limit: number) => Promise<BackendSearchHit[]>;
+}): SearchBackend {
+ return {
+ name: opts.name,
+ async search(request) {
+ const resultSets = await Promise.all(
+ request.principals.map((principal) => opts.searchForPrincipal(principal, request.query, request.limit)),
+ );
+ const [first, ...rest] = resultSets;
+ if (!first) return [];
+ const visible = rest.map((hits) => new Set(hits.map(opts.key)));
+ return first.filter((hit) => visible.every((keys) => keys.has(opts.key(hit)))).slice(0, request.limit);
+ },
+ };
+}
diff --git a/src/search/core-search.ts b/src/search/core-search.ts
new file mode 100644
index 000000000..6e46734a1
--- /dev/null
+++ b/src/search/core-search.ts
@@ -0,0 +1,81 @@
+import type { Principal } from "../types.ts";
+
+const SEARCH_DEFAULT_LIMIT = 20;
+const SEARCH_MAX_LIMIT = 100;
+type SearchHitType = "message" | "conversation" | "file" | "page" | "external";
+export interface BackendSearchHit {
+ id: string;
+ type: SearchHitType;
+ title?: string;
+ snippet: string;
+ url?: string;
+ createdAt?: number;
+ score?: number;
+ metadata?: Record<string, unknown>;
+}
+export interface SearchHit extends BackendSearchHit {
+ backend: string;
+}
+interface SearchRequest {
+ query: string;
+ principals: readonly Principal[];
+ limit: number;
+}
+export interface SearchBackend {
+ name: string;
+ search(request: SearchRequest): Promise<BackendSearchHit[]>;
+}
+export interface CoreSearch {
+ search(input: {
+ query: string;
+ principals: readonly Principal[];
+ limit?: number;
+ }): Promise<{ hits: SearchHit[]; failedBackends: string[] }>;
+}
+function canonicalPrincipals(principals: readonly Principal[]): Principal[] {
+ const unique = new Map<string, Principal>();
+ for (const principal of principals) {
+ const id = principal.id.trim();
+ if (!id) continue;
+ const key = id.toLowerCase();
+ if (!unique.has(key)) unique.set(key, { ...principal, id });
+ }
+ return [...unique.values()].sort((a, b) => a.id.localeCompare(b.id));
+}
+function searchLimit(limit: number | undefined): number {
+ if (limit === undefined || !Number.isFinite(limit)) return SEARCH_DEFAULT_LIMIT;
+ return Math.max(1, Math.min(SEARCH_MAX_LIMIT, Math.floor(limit)));
+}
+export function createCoreSearch(
+ backends: readonly SearchBackend[],
+ opts: { onBackendError?: (backend: string, error: unknown) => void } = {},
+): CoreSearch {
+ const names = new Set<string>();
+ for (const backend of backends) {
+ if (!backend.name.trim() || names.has(backend.name))
+ throw new Error(`duplicate or empty search backend: ${backend.name}`);
+ names.add(backend.name);
+ }
+ return {
+ async search(input) {
+ const query = input.query.trim();
+ const principals = canonicalPrincipals(input.principals);
+ if (!query || !principals.length) return { hits: [], failedBackends: [] };
+ const limit = searchLimit(input.limit);
+ const settled = await Promise.allSettled(backends.map((backend) => backend.search({ query, principals, limit })));
+ const hits: SearchHit[] = [];
+ const failedBackends: string[] = [];
+ for (const [index, result] of settled.entries()) {
+ const backend = backends[index]!;
+ if (result.status === "rejected") {
+ failedBackends.push(backend.name);
+ opts.onBackendError?.(backend.name, result.reason);
+ continue;
+ }
+ for (const hit of result.value.slice(0, limit)) hits.push({ ...hit, backend: backend.name });
+ }
+ hits.sort((a, b) => (b.score ?? 0) - (a.score ?? 0) || (b.createdAt ?? 0) - (a.createdAt ?? 0));
+ return { hits: hits.slice(0, limit), failedBackends };
+ },
+ };
+}
diff --git a/src/wiring.ts b/src/wiring.ts
index d0fa40155..ed9827936 100644
--- a/src/wiring.ts
+++ b/src/wiring.ts
@@ -294,6 +294,7 @@ import { createPostgresMetricsSink } from "./admin/postgres-metrics-sink.ts";
import { errMessage, swallowAs } from "./util/errors.ts";
import { sleep } from "./util/async.ts";
import { createSlackInstallationStore, type SlackInstallationStore } from "./surfaces/slack-installation.ts";
+import type { SearchBackend } from "./search/core-search.ts";
export interface Runtime {
start(): void;
@@ -403,6 +404,7 @@ export function buildApp(
securityScreener?: SecurityScreener;
credentialBrokers?: Record<string, AwsRoleBroker>;
modelCredentialFetch?: typeof fetch;
+ searchBackends?: readonly SearchBackend[];
} = {},
): BuiltApp {
if (config.databaseUrl && !config.connectorSecretKey) {
@@ -1314,6 +1316,7 @@ export function buildApp(
providerKeys,
modelProviders: modelProviderAvailabilityFor(config.harness, providerKeys),
runWaitMs: config.runWaitMs,
+ ...(overrides.searchBackends ? { searchBackends: overrides.searchBackends } : {}),
});
const slackCore = createSlackCoreClient({
app,
diff --git a/test/core-search.test.ts b/test/core-search.test.ts
new file mode 100644
index 000000000..0f2cb5e20
--- /dev/null
+++ b/test/core-search.test.ts
@@ -0,0 +1,158 @@
+import "./support/auto-fake-sprites.ts";
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import type { AddressInfo } from "node:net";
+import { mkdtempSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { createCoreSearch, type SearchBackend } from "../src/search/core-search.ts";
+import { createIntersectionBackend } from "../src/search/backends.ts";
+import { createServer } from "../src/api/server.ts";
+import { buildApp } from "../src/wiring.ts";
+import { testConfig } from "./support/test-config.ts";
+import { CAPABILITY_TTL_MS, mintCapabilityToken } from "../src/auth/capability-token.ts";
+import { scopeId } from "../src/types.ts";
+import { artifactPath } from "../src/files/file-artifact-store.ts";
+const principals = [
+ { id: "[email protected]", type: "internal" as const },
+ { id: "[email protected]", type: "internal" as const },
+];
+test("core search canonicalizes the principal floor and isolates failures", async () => {
+ const seen: string[][] = [];
+ const backend = (name: string, fail = false): SearchBackend => ({
+ name,
+ async search(r) {
+ seen.push(r.principals.map((p) => p.id));
+ if (fail) throw new Error("down");
+ return [{ id: name, type: "page", snippet: r.query }];
+ },
+ });
+ const result = await createCoreSearch([backend("one"), backend("bad", true), backend("two")]).search({
+ query: "plan",
+ principals: [principals[1]!, principals[0]!, principals[0]!],
+ });
+ assert.deepEqual(seen, Array(3).fill(["[email protected]", "[email protected]"]));
+ assert.deepEqual(
+ result.hits.map((h) => h.backend),
+ ["one", "two"],
+ );
+ assert.deepEqual(result.failedBackends, ["bad"]);
+});
+test("intersection backend requires visibility to every principal", async () => {
+ const backend = createIntersectionBackend({
+ name: "files",
+ key: (h) => h.id,
+ searchForPrincipal: async (p) =>
+ p.id.startsWith("alice")
+ ? [
+ { id: "shared", type: "file", snippet: "x" },
+ { id: "private", type: "file", snippet: "x" },
+ ]
+ : [{ id: "shared", type: "file", snippet: "x" }],
+ });
+ assert.deepEqual(
+ (await backend.search({ query: "x", principals, limit: 20 })).map((h) => h.id),
+ ["shared"],
+ );
+});
+test("POST /v1/search derives principals from capability and shared scopes fail closed", async () => {
+ const seen: string[][] = [];
+ const external: SearchBackend = {
+ name: "external",
+ async search(r) {
+ seen.push(r.principals.map((p) => p.id));
+ return [];
+ },
+ };
+ const secret = "search-route-secret".repeat(3);
+ const built = buildApp(testConfig({ dataDir: mkdtempSync(join(tmpdir(), "search-")), signingSecret: secret }), {
+ searchBackends: [external],
+ });
+ await built.directory.replaceChannels(
+ [{ channelId: "C1", name: "private", isPrivate: true }],
+ principals.map((p) => ({ channelId: "C1", principalId: p.id })),
+ );
+ const server = createServer(built.app, { signingSecret: secret, auditLog: built.auditLog });
+ await new Promise<void>((r) => server.listen(0, "127.0.0.1", r));
+ const base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
+ const token = async (members?: typeof principals) =>
+ mintCapabilityToken(
+ {
+ actorId: principals[0]!.id,
+ scopeId: scopeId("channel", "C1"),
+ ...(members ? { members } : {}),
+ exp: Date.now() + CAPABILITY_TTL_MS,
+ },
+ secret,
+ );
+ const post = async (cap: string) =>
+ fetch(`${base}/v1/search`, {
+ method: "POST",
+ headers: { "content-type": "application/json", "x-agent-capability": cap },
+ body: JSON.stringify({ query: "plan" }),
+ });
+ try {
+ assert.equal((await post(await token(principals))).status, 200);
+ assert.deepEqual(seen, [["[email protected]", "[email protected]"]]);
+ assert.equal((await post(await token())).status, 409);
+ assert.equal(seen.length, 1);
+ const event = (await built.auditLog.events()).find((e) => e.action === "search.query");
+ assert.ok(event);
+ assert.doesNotMatch(event.detail ?? "", /plan/);
+ } finally {
+ await new Promise<void>((r) => server.close(() => r()));
+ }
+});
+
+test("file backend applies the principal visibility intersection to real file rows", async () => {
+ const built = buildApp(testConfig({ dataDir: mkdtempSync(join(tmpdir(), "search-files-")) }));
+ const id = "0123456789abcdef0123456789abcdef";
+ await built.files.put({
+ id,
+ ownerScopeId: scopeId("personal", principals[0]!.id),
+ createdBy: principals[0]!.id,
+ name: "notes.txt",
+ path: artifactPath(id, "notes.txt"),
+ mimetype: "text/plain",
+ data: Buffer.from("the launch codename is pelican"),
+ direction: "in",
+ });
+
+ const mine = await built.app.search("pelican", [principals[0]!]);
+ assert.deepEqual(
+ mine.hits.filter((hit) => hit.backend === "files").map((hit) => hit.id),
+ [id],
+ );
+
+ const shared = await built.app.search("pelican", principals);
+ assert.deepEqual(
+ shared.hits.filter((hit) => hit.backend === "files"),
+ [],
+ "a file private to one participant is excluded from a shared principal floor",
+ );
+});
+
+test("slack backend intersects private-channel visibility across all principals", async () => {
+ const built = buildApp(testConfig({ dataDir: mkdtempSync(join(tmpdir(), "search-slack-")) }));
+ await built.directory.replaceChannels(
+ [
+ { channelId: "C-SHARED", name: "shared", isPrivate: true },
+ { channelId: "C-ALICE", name: "alice-only", isPrivate: true },
+ ],
+ [
+ { channelId: "C-SHARED", principalId: principals[0]!.id },
+ { channelId: "C-SHARED", principalId: principals[1]!.id },
+ { channelId: "C-ALICE", principalId: principals[0]!.id },
+ ],
+ );
+ await built.app.ingestSurfaceEvents([
+ { container: "C-SHARED", ts: "1", text: "pelican launch shared", kind: "channel" },
+ { container: "C-ALICE", ts: "2", text: "pelican launch private", kind: "channel" },
+ ]);
+
+ const hits = await built.app.search("pelican", principals);
+ assert.deepEqual(
+ hits.hits.filter((hit) => hit.backend === "slack").map((hit) => hit.id),
+ ["C-SHARED:1"],
+ );
+});