Skip to content

armgit / qm

Public Imported from GitHub
0

Multiplayer agent harness for work.

Keep Slack context live while qualifying the mirror (#1214)

Regan Bell4802f461a2a7
diff --git a/.env.example b/.env.example
index 123196108..1ce66b9cf 100644
--- a/.env.example
+++ b/.env.example
@@ -45,3 +45,4 @@ BUDGET_WINDOW_MS=86400000
# Defaults resolved once for each new swarm; initial spawn may override these.
# SWARM_DEFAULTS={"agents":32,"turnMs":600000}
+SLACK_CONTEXT_SOURCE=live
diff --git a/src/config.ts b/src/config.ts
index 2d3dfcd7f..0353426bf 100644
--- a/src/config.ts
+++ b/src/config.ts
@@ -22,7 +22,12 @@ import { validateCoreSecretEnv } from "./deployment/secret-schema.ts";
import { DEFAULT_CAPTURE_QUIET_MS } from "./memory/strategies/per-turn.ts";
import { parseSecurityPosture, type SecurityPosture } from "./security/security-posture.ts";
import { parseSharingPosture, type SharingPosture } from "./resolution/sharing-posture.ts";
-import { slackPluginConfigFromEnv, type SlackPluginConfig } from "./slack/config.ts";
+import {
+ parseSlackContextSource,
+ type SlackContextSource,
+ slackPluginConfigFromEnv,
+ type SlackPluginConfig,
+} from "./slack/config.ts";
import { codexAuthFileForEnv, readCodexOAuthAuthFile } from "./harness/codex-auth-file.ts";
import {
MODEL_PROVIDERS,
@@ -36,6 +41,7 @@ import {
import { resolveSwarmSettings, type SwarmSettings } from "./swarms/swarm-settings.ts";
export interface Config {
+ slackContextSource?: SlackContextSource;
suggestedActivitiesEnabled?: boolean;
suggestedActivitiesContext?: string;
swarmDefaults?: SwarmSettings;
@@ -1367,6 +1373,7 @@ export function loadConfig(env: NodeJS.ProcessEnv = process.env): Config {
...(env.PUBLIC_WEB_URL ? { publicWebUrl: env.PUBLIC_WEB_URL } : {}),
...(env.FLY_APP_NAME ? { flyAppName: env.FLY_APP_NAME } : {}),
...(slack ? { slack } : {}),
+ slackContextSource: parseSlackContextSource(env.SLACK_CONTEXT_SOURCE),
runStore,
...(env.SKILL_SIGNING_SECRET ? { skillSigningSecret: env.SKILL_SIGNING_SECRET } : {}),
seedSkills: boolEnvStrict("SEED_SKILLS", env.SEED_SKILLS) ?? true,
diff --git a/src/core/orchestrator/surface-tools.ts b/src/core/orchestrator/surface-tools.ts
index f15d20884..6d2dc92a2 100644
--- a/src/core/orchestrator/surface-tools.ts
+++ b/src/core/orchestrator/surface-tools.ts
@@ -178,6 +178,7 @@ export function createSurfaceToolDeps(ctx: SurfaceToolsContext): SurfaceToolDeps
let coverageChecked = false;
let coverageSince: string | undefined;
const coverageForTurn = async (): Promise<string | undefined> => {
+ if (deps.slackContextSource !== "mirror") return undefined;
if (coverageChecked) return coverageSince;
coverageChecked = true;
const container = currentDestination.target ?? conversation.channelRef ?? conversation.threadRef;
@@ -343,7 +344,8 @@ export function createSurfaceToolDeps(ctx: SurfaceToolsContext): SurfaceToolDeps
const coverage = await coverageForTurn();
const withCoverage = (r: SurfaceSearchResult): SurfaceSearchResult =>
coverage ? { ...r, coverageSince: coverage } : r;
- if (!q) return withCoverage({ ok: true, hits: [], source: deps.surfaceSearch ? "cache" : "live" });
+ if (!q)
+ return withCoverage({ ok: true, hits: [], source: deps.slackContextSource === "mirror" ? "cache" : "live" });
const limit = Math.max(1, Math.min(SURFACE_SEARCH_MAX, opts?.limit ?? SURFACE_SEARCH_DEFAULT));
const dest = currentDestination;
const shapeHits = (messages: unknown[], prefiltered = false) =>
@@ -382,10 +384,15 @@ export function createSurfaceToolDeps(ctx: SurfaceToolsContext): SurfaceToolDeps
"on an autonomous turn just say what you couldn't search]",
};
if (result.note && !result.messages?.length) return { ok: false, message: result.note };
- return withCoverage({ ok: true, hits: shapeHits(result.messages ?? [], true), source: "slack" });
+ return withCoverage({
+ ok: true,
+ hits: shapeHits(result.messages ?? [], true),
+ source: "slack",
+ ...(result.note ? { message: result.note } : {}),
+ });
}
const container = dest.target ?? conversation.channelRef ?? conversation.threadRef;
- if (deps.surfaceCache && dest.type === "slack" && container) {
+ if (deps.slackContextSource === "mirror" && deps.surfaceCache && dest.type === "slack" && container) {
const channel = container.split(":")[0]!;
const hits = await deps.surfaceCache.search(q, { container: channel, limit });
return withCoverage({
@@ -400,10 +407,16 @@ export function createSurfaceToolDeps(ctx: SurfaceToolsContext): SurfaceToolDeps
message: "Search covers stored Slack events only; older or missed messages may be absent.",
});
}
+ if (opts?.source === "mirror" && deps.slackContextSource !== "mirror") {
+ return {
+ ok: false,
+ message: "Mirror reads are disabled until verification is complete. Use the default live source.",
+ };
+ }
if (opts?.source === "mirror" && !deps.surfaceSearch) {
return { ok: false, message: "Stored Slack message search is unavailable; no live search was performed." };
}
- if (deps.surfaceSearch) {
+ if (deps.surfaceSearch && (dest.type !== "slack" || deps.slackContextSource === "mirror")) {
const hits = await deps.surfaceSearch.search({
surface: input.surface ?? "unknown",
container,
@@ -422,7 +435,12 @@ export function createSurfaceToolDeps(ctx: SurfaceToolsContext): SurfaceToolDeps
});
if (!result) return { ok: false, message: "the surface didn't answer in time" };
if (result.note && !result.messages?.length) return { ok: false, message: result.note };
- return withCoverage({ ok: true, hits: shapeHits(result.messages ?? []), source: "live" });
+ return withCoverage({
+ ok: true,
+ hits: shapeHits(result.messages ?? []),
+ source: "live",
+ ...(result.note ? { message: result.note } : {}),
+ });
},
readMembers: async () => {
const roster = (conversation.publishMembers ?? conversation.audience).filter((p) => p.type === "internal");
diff --git a/src/core/orchestrator/types.ts b/src/core/orchestrator/types.ts
index ef265d241..f45346130 100644
--- a/src/core/orchestrator/types.ts
+++ b/src/core/orchestrator/types.ts
@@ -194,6 +194,7 @@ export interface OrchestratorDeps {
surfaceContext?: SurfaceContextPuller;
surfaceSearch?: SurfaceSearchStore;
surfaceCache?: SurfaceCache;
+ slackContextSource?: "live" | "shadow" | "mirror";
channelPolicy?: ChannelPolicyStore;
surfaceDebugFooter?: boolean;
}
diff --git a/src/slack/README.md b/src/slack/README.md
index 02b0c2298..3ff5aa39c 100644
--- a/src/slack/README.md
+++ b/src/slack/README.md
@@ -245,3 +245,13 @@ your per-dev name + tokens live only in your local app and your gitignored `.env
- Channel audience is enumerated per-member: `computeChannelAudience` (lib.ts) resolves
the full member list (with a Slack-Connect / guest external marker, and an actor-only
fallback when membership is unreadable) so the core's audience-floor is fine-grained.
+
+## Mirror qualification
+
+`SLACK_CONTEXT_SOURCE` controls conversation context and default Slack tool reads:
+
+- `live` (default) keeps Slack history as the source, including automatic channel thread expansion.
+- `shadow` returns the same live context while comparing stored events in the background. It logs `slack_mirror_shadow` counts for missing messages, text differences, and missing thread parents. It does not log message text or channel identifiers, backfill history, or wait for comparison before returning context. At most one comparison runs per Slack client; concurrent reads are not all sampled.
+- `mirror` explicitly enables stored context and mirror search, with the documented partial coverage and bounded live fallback. Keep this opt-in until shadow evidence and development qualification are satisfactory.
+
+Ingestion continues in every mode. Shadow mismatch counts describe the sampled live window, not complete channel coverage. Compare channel and thread samples, edits/deletes, and normal agent turns before enabling mirror reads. No automatic mode promotion occurs.
diff --git a/src/slack/config.ts b/src/slack/config.ts
index 69b99e143..44f439d79 100644
--- a/src/slack/config.ts
+++ b/src/slack/config.ts
@@ -6,7 +6,17 @@ import { normalizeAllowFrom, parseAllowFrom } from "./allow-from.ts";
export const NO_RETRY = { retryConfig: { retries: 0 } } as const;
export const HISTORY_NO_RETRY = { ...NO_RETRY, rejectRateLimitedCalls: true } as const;
+export type SlackContextSource = "live" | "shadow" | "mirror";
+
+export function parseSlackContextSource(value: string | undefined): SlackContextSource {
+ const source = value?.trim() || "live";
+ if (source !== "live" && source !== "shadow" && source !== "mirror")
+ throw new Error("SLACK_CONTEXT_SOURCE must be live, shadow, or mirror");
+ return source;
+}
+
export interface SlackPluginConfig {
+ contextSource?: SlackContextSource;
installationId?: string;
receiverFactory?: (staging?: EnvelopeStaging) => Receiver;
botToken: string;
@@ -64,6 +74,7 @@ export function slackPluginConfigFromEnv(
): Partial<SlackPluginConfig> => (value === undefined ? {} : ({ [key]: value } as Partial<SlackPluginConfig>));
return {
botToken: env.SLACK_BOT_TOKEN,
+ ...(env.SLACK_CONTEXT_SOURCE ? { contextSource: parseSlackContextSource(env.SLACK_CONTEXT_SOURCE) } : {}),
...(receiverFactory ? { receiverFactory } : {}),
...opt("appToken", env.SLACK_APP_TOKEN),
...opt("apiUrl", env.SLACK_API_URL),
@@ -130,6 +141,7 @@ export function slackAccountConfigsFromEnv(env: Record<string, string | undefine
SLACK_API_URL: str(a.apiUrl),
SLACK_IDENTITY_EMAIL: str(a.identityEmail) ?? "1",
SLACK_LOG_LEVEL: env.SLACK_LOG_LEVEL,
+ SLACK_CONTEXT_SOURCE: env.SLACK_CONTEXT_SOURCE,
WEB_UI_PUBLIC_URL: env.WEB_UI_PUBLIC_URL,
};
const config = slackPluginConfigFromEnv(accountEnv);
diff --git a/src/slack/conversation-view.ts b/src/slack/conversation-view.ts
index 4a1a7f578..fe0b2a3e5 100644
--- a/src/slack/conversation-view.ts
+++ b/src/slack/conversation-view.ts
@@ -192,7 +192,7 @@ export function createConversationSerializer(deps: {
const slackId = ctx.slackIdsByPrincipal?.get(a.externalId);
if (slackId) nameById.set(slackId, a.displayName);
}
- const page = await deps.readHistory(client, inc.channel, inc.threadTs).catch((error) => {
+ const page = await deps.readHistory(client, inc.channel, inc.threadTs, undefined, true).catch((error) => {
swallow("slack: conversation context", error);
return {
raw: [] as SlackHistoryMessage[],
diff --git a/src/slack/history.ts b/src/slack/history.ts
index 725b3ebeb..d4d3533dd 100644
--- a/src/slack/history.ts
+++ b/src/slack/history.ts
@@ -1,4 +1,6 @@
-import { decodeSlackEntities, mentionsBot } from "./lib.ts";
+import { messageWithForwardedContent } from "./forwards.ts";
+import type { SlackContextSource } from "./config.ts";
+import { decodeSlackEntities, mentionsBot, resolveMentionsInText } from "./lib.ts";
import { slackHistoryRateLimitMessage } from "./history-rate-limit.ts";
import type { SlackCoreClient } from "../api/slack-core-client.ts";
import type { BotIdentity } from "./directory.ts";
@@ -17,6 +19,7 @@ export type SlackHistoryReader = (
channel: string,
threadTs?: string,
before?: string,
+ expandThreads?: boolean,
) => Promise<SlackHistoryPage>;
const MIRROR_CONTEXT_NOTE =
@@ -24,12 +27,110 @@ const MIRROR_CONTEXT_NOTE =
export function createSlackHistoryReader(deps: {
core: SlackCoreClient;
+ source?: SlackContextSource;
ids: BotIdentity;
managed?: boolean;
setupUrl?: string;
historyClient?: { conversations: { history(args: any): Promise<unknown>; replies(args: any): Promise<unknown> } };
}): SlackHistoryReader {
- return async (client, channel, threadTs, before) => {
+ async function liveHistory(
+ client: any,
+ channel: string,
+ threadTs?: string,
+ before?: string,
+ expandThreads = false,
+ ): Promise<SlackHistoryPage> {
+ const historyClient = deps.historyClient ?? client;
+ const paging = { channel, limit: 200, ...(before ? { latest: before, inclusive: false } : {}) };
+ const page = parseMessageList(
+ threadTs
+ ? await historyClient.conversations.replies({ ...paging, ts: threadTs })
+ : await historyClient.conversations.history(paging),
+ );
+ const raw = threadTs ? page.messages : page.messages.slice().reverse();
+ if (!threadTs && expandThreads) {
+ const parents = raw.filter((m) => m.ts && Number(m.reply_count) > 0).slice(-5);
+ const expanded = await Promise.all(
+ parents.map(async (m) => {
+ try {
+ return parseMessageList(await historyClient.conversations.replies({ channel, ts: m.ts, limit: 200 }))
+ .messages;
+ } catch {
+ return [];
+ }
+ }),
+ );
+ const byTs = new Map<string, SlackHistoryMessage>();
+ for (const m of [...raw, ...expanded.flat()]) if (m.ts) byTs.set(m.ts, m);
+ return { raw: [...byTs.values()], hasMore: page.hasMore };
+ }
+ return { raw, hasMore: page.hasMore };
+ }
+
+ async function compareShadow(
+ live: SlackHistoryPage,
+ channel: string,
+ threadTs?: string,
+ before?: string,
+ ): Promise<void> {
+ if (!deps.core.readSurfaceMessages) return;
+ try {
+ const options = { limit: 200, noFallback: true, ...(before ? { before } : {}) };
+ const rows = threadTs
+ ? (
+ await Promise.all([
+ deps.core.readSurfaceMessages(channel, { ...options, sub: threadTs }),
+ deps.core.readSurfaceMessages(channel, { at: threadTs, noFallback: true }),
+ ])
+ ).flat()
+ : await deps.core.readSurfaceMessages(channel, options);
+ const timestamps = new Set(rows.filter((m) => !m.deleted && (!before || m.ts < before)).map((m) => m.ts));
+ const liveTimestamps = new Set(live.raw.flatMap((m) => (m.ts ? [m.ts] : [])));
+ const byTs = new Map(rows.map((m) => [m.ts, m]));
+ let textMismatches = 0;
+ let staleEditedMessages = 0;
+ for (const message of live.raw) {
+ const stored = message.ts ? byTs.get(message.ts) : undefined;
+ if (!stored || stored.deleted) continue;
+ const liveText = resolveMentionsInText(
+ decodeSlackEntities(messageWithForwardedContent(message).text),
+ (id) => stored.mentions?.[id],
+ );
+ if (stored.text !== liveText) textMismatches++;
+ if (Number(message.edited?.ts) * 1000 > (stored.editedAt ?? 0)) staleEditedMessages++;
+ }
+ console.info(
+ JSON.stringify({
+ event: "slack_mirror_shadow",
+ thread: Boolean(threadTs),
+ conversationKind: channel.startsWith("D") ? "dm" : "channel_or_group",
+ staleEditedMessages,
+ liveMessages: liveTimestamps.size,
+ mirroredMessages: timestamps.size,
+ textMismatches,
+ liveMessagesMissingFromMirror: [...liveTimestamps].filter((ts) => !timestamps.has(ts)).length,
+ mirrorMessagesOutsideLiveWindow: [...timestamps].filter((ts) => !liveTimestamps.has(ts)).length,
+ missingThreadParent: Boolean(threadTs && !timestamps.has(threadTs)),
+ liveHasMore: live.hasMore,
+ }),
+ );
+ } catch {
+ console.info(JSON.stringify({ event: "slack_mirror_shadow", outcome: "read_failed", thread: Boolean(threadTs) }));
+ }
+ }
+
+ let shadowPending = false;
+ return async (client, channel, threadTs, before, expandThreads) => {
+ if (deps.source !== "mirror") {
+ const live = await liveHistory(client, channel, threadTs, before, expandThreads);
+ if (deps.source === "shadow" && !shadowPending) {
+ shadowPending = true;
+ void compareShadow(live, channel, threadTs, before).finally(() => {
+ shadowPending = false;
+ });
+ }
+ return live;
+ }
const historyClient = deps.historyClient ?? client;
let mirrored: SlackHistoryMessage[] = [];
const deleted = new Set<string>();
diff --git a/src/slack/index.ts b/src/slack/index.ts
index 8716ce39c..16e005536 100644
--- a/src/slack/index.ts
+++ b/src/slack/index.ts
@@ -213,7 +213,13 @@ export async function startSlackPlugin(
...(cfg.webUiPublicUrl ? { setupUrl: `${cfg.webUiPublicUrl.replace(/\/$/, "")}/admin/?setup=slack` } : {}),
};
const historyClient = new WebClient(BOT_TOKEN, { ...CLIENT_OPTIONS, ...HISTORY_NO_RETRY });
- const readHistory = createSlackHistoryReader({ core, ids, historyClient, ...historyRateLimitOptions });
+ const readHistory = createSlackHistoryReader({
+ core,
+ ids,
+ historyClient,
+ source: cfg.contextSource ?? "live",
+ ...historyRateLimitOptions,
+ });
const serializer = createConversationSerializer({
readHistory,
historyRateLimitOptions,
diff --git a/src/wiring.ts b/src/wiring.ts
index 67dedbc79..6c41b95f5 100644
--- a/src/wiring.ts
+++ b/src/wiring.ts
@@ -1930,6 +1930,7 @@ export function buildApp(
);
orchestratorDeps.channelPolicy = channelPolicy;
orchestratorDeps.surfaceCache = surfaceCache;
+ orchestratorDeps.slackContextSource = config.slackContextSource ?? "live";
const askResolution = keychain
? (ask: KeychainAsk, grant?: KeychainGrant) =>
fireAskResolution(
diff --git a/test/slack-mirror-context.test.ts b/test/slack-mirror-context.test.ts
index 3d28ca803..1e9bd8f31 100644
--- a/test/slack-mirror-context.test.ts
+++ b/test/slack-mirror-context.test.ts
@@ -23,6 +23,7 @@ function fixture() {
const readHistory = createSlackHistoryReader({
core,
ids,
+ source: "mirror",
managed: true,
setupUrl: "https://qm.test/admin/?setup=slack",
});
@@ -168,6 +169,7 @@ test("read_thread, whats_new and mirror search retain coverage notes and contain
deps: {
deliveries: {},
surfaceCache: cache,
+ slackContextSource: "mirror",
surfaceContext: {
pull: async () => ({
messages: [{ ts: "2.000000", threadTs: "1.000000", text: "reply" }],
diff --git a/test/slack-mirror-soak.test.ts b/test/slack-mirror-soak.test.ts
new file mode 100644
index 000000000..c77fc735d
--- /dev/null
+++ b/test/slack-mirror-soak.test.ts
@@ -0,0 +1,160 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { createSlackHistoryReader } from "../src/slack/history.ts";
+import { parseSlackContextSource, slackAccountConfigsFromEnv } from "../src/slack/config.ts";
+import { createSurfaceToolDeps, type SurfaceToolsContext } from "../src/core/orchestrator/surface-tools.ts";
+import type { SlackCoreClient } from "../src/api/slack-core-client.ts";
+import type { BotIdentity } from "../src/slack/directory.ts";
+
+const ids = { botUserId: "UBOT", ownBotId: "BBOT" } as BotIdentity;
+
+test("context source defaults live and invalid modes fail closed", () => {
+ assert.equal(parseSlackContextSource(undefined), "live");
+ assert.equal(parseSlackContextSource(""), "live");
+ for (const source of ["live", "shadow", "mirror"]) assert.equal(parseSlackContextSource(source), source);
+ assert.throws(() => parseSlackContextSource("miror"));
+});
+
+test("default live context never reads or writes mirror and expands recent channel threads", async () => {
+ const calls: string[] = [];
+ const core = {
+ readSurfaceMessages: async () => {
+ throw new Error("must not read mirror");
+ },
+ rememberSurfaceHistory: async () => {
+ throw new Error("must not backfill");
+ },
+ } as unknown as SlackCoreClient;
+ const client = {
+ conversations: {
+ history: async () => {
+ calls.push("history");
+ return {
+ messages: [
+ { ts: "2", text: "new" },
+ { ts: "1", text: "parent", reply_count: 1 },
+ ],
+ };
+ },
+ replies: async () => {
+ calls.push("replies");
+ return {
+ messages: [
+ { ts: "1", text: "parent" },
+ { ts: "1.5", thread_ts: "1", text: "live reply" },
+ ],
+ };
+ },
+ },
+ };
+ const result = await createSlackHistoryReader({ core, ids })(client, "C1", undefined, undefined, true);
+ assert.deepEqual(calls, ["history", "replies"]);
+ assert.ok(result.raw.some((message) => message.text === "live reply"));
+ assert.equal(result.note, undefined);
+});
+
+test("shadow compares counts and text but returns live context without waiting for the mirror", async (t) => {
+ let release!: (value: unknown) => void;
+ const pending = new Promise((resolve) => {
+ release = resolve;
+ });
+ const logs: string[] = [];
+ let mirrorReads = 0;
+ t.mock.method(console, "info", (line: string) => {
+ logs.push(line);
+ });
+ const core = {
+ readSurfaceMessages: async () => {
+ mirrorReads++;
+ return pending;
+ },
+ rememberSurfaceHistory: async () => {
+ throw new Error("must not backfill");
+ },
+ } as unknown as SlackCoreClient;
+ const client = {
+ conversations: {
+ history: async () => ({
+ messages: [
+ { ts: "1", text: "live secret text" },
+ { ts: "2", text: "second secret" },
+ ],
+ }),
+ },
+ };
+ const read = createSlackHistoryReader({ core, ids, source: "shadow" });
+ const result = await read(client, "C-secret");
+ await read(client, "C-secret");
+ assert.equal(mirrorReads, 1);
+ assert.equal(result.raw[0]?.text, "second secret");
+ assert.equal(logs.length, 0);
+ release([{ ts: "1", text: "stale secret text" }]);
+ await new Promise((resolve) => setImmediate(resolve));
+ const comparison = JSON.parse(logs[0]!);
+ assert.equal(comparison.liveMessagesMissingFromMirror, 1);
+ assert.equal(comparison.textMismatches, 1);
+ assert.ok(logs.every((line) => !line.includes("secret")));
+});
+
+test("shadow failures never replace or fail the live result", async (t) => {
+ const logs: string[] = [];
+ t.mock.method(console, "info", (line: string) => {
+ logs.push(line);
+ });
+ const core = {
+ readSurfaceMessages: async () => {
+ throw new Error("private error details");
+ },
+ } as unknown as SlackCoreClient;
+ const client = { conversations: { replies: async () => ({ messages: [{ ts: "1", text: "live" }] }) } };
+ assert.equal(
+ (await createSlackHistoryReader({ core, ids, source: "shadow" })(client, "C1", "1")).raw[0]?.text,
+ "live",
+ );
+ await new Promise((resolve) => setImmediate(resolve));
+ assert.ok(logs.some((line) => line.includes("read_failed")));
+ assert.ok(logs.every((line) => !line.includes("private error")));
+});
+
+test("live and shadow default search cannot source mirror data", async () => {
+ for (const source of [undefined, "live", "shadow"] as const) {
+ let cacheReads = 0;
+ const tools = createSurfaceToolDeps({
+ deps: {
+ deliveries: {},
+ slackContextSource: source,
+ surfaceCache: {
+ containerState: async () => null,
+ search: async () => {
+ cacheReads++;
+ return [{ text: "mirror secret" }];
+ },
+ },
+ surfaceContext: {
+ pull: async () => ({
+ messages: [{ ts: "1", text: "live match" }],
+ note: "Retry in 60 seconds; setup at https://qm.test/admin/?setup=slack",
+ }),
+ },
+ },
+ input: { surface: "slack", surfaceTools: true },
+ actor: { id: "U1" },
+ conversation: { kind: "channel" },
+ defaultDestination: { type: "slack", target: "C1:1" },
+ } as unknown as SurfaceToolsContext)!;
+ const result = await tools.search("match");
+ assert.equal(result.source, "live");
+ assert.equal(result.hits?.[0]?.snippet, "live match");
+ assert.match(result.message!, /60 seconds.*setup=slack/);
+ assert.equal((await tools.search("match", { source: "mirror" })).ok, false);
+ assert.equal(cacheReads, 0);
+ }
+});
+
+test("secondary Slack accounts inherit the explicitly selected shadow mode", () => {
+ const [account] = slackAccountConfigsFromEnv({
+ SLACK_CONTEXT_SOURCE: "shadow",
+ SLACK_ACCOUNTS: JSON.stringify([{ id: "secondary", botToken: "xoxb-test", appToken: "xapp-test" }]),
+ });
+ assert.equal(account?.contextSource, "shadow");
+});
diff --git a/test/surface-read-tools.test.ts b/test/surface-read-tools.test.ts
index 71a674c90..868e113cb 100644
--- a/test/surface-read-tools.test.ts
+++ b/test/surface-read-tools.test.ts
@@ -12,9 +12,9 @@ import { createAgentTools, type ToolContextRef } from "../src/harness/agent-tool
const sleep = (ms: number): Promise<void> => new Promise((r) => setTimeout(r, ms));
-function freshApp() {
+function freshApp(slackContextSource?: "live" | "shadow" | "mirror") {
const dataDir = mkdtempSync(join(tmpdir(), "ap-readtools-"));
- return buildApp(testConfig({ dataDir }));
+ return buildApp(testConfig({ dataDir, ...(slackContextSource ? { slackContextSource } : {}) }));
}
const actor = { externalId: "U1", displayName: "Ada" };
@@ -83,8 +83,8 @@ test("whats_new returns POINTERS (counts of new-here + other active threads), ne
}
});
-test("search defaults to the current channel mirror and returns author/snippet pointers without a live pull", async () => {
- const built = freshApp();
+test("enabled mirror search uses the current channel and returns author/snippet pointers without a live pull", async () => {
+ const built = freshApp("mirror");
built.runtime.start();
const root = "C11:1100.1";
await built.surfaceCache.ingest([
@@ -221,7 +221,7 @@ test("whats_new action appends the mirror-coverage window when known", async ()
});
test("search/whats_new surface the mirror coverage window end-to-end once the mirror has ingested history (§4.1/§4.2)", async () => {
- const built = freshApp();
+ const built = freshApp("mirror");
built.runtime.start();
const root = "C30:3000.1";
await built.app.ingestSurfaceEvents(