Skip to content

armgit / qm

Public Imported from GitHub
0

Multiplayer agent harness for work.

Match mirror context to live Slack page selection (#1254)

Regan Bell41b38efa38e6
diff --git a/src/slack/README.md b/src/slack/README.md
index c942ede5b..b348da43f 100644
--- a/src/slack/README.md
+++ b/src/slack/README.md
@@ -251,7 +251,7 @@ your per-dev name + tokens live only in your local app and your gitignored `.env
`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. The live page is snapshotted before callers add trigger context, and shadow uses the same stored-message selection as mirror mode. Long threads may differ from Slack’s oldest page; these differences remain visible. Counts cover raw message fields, not complete rendered context or author/subtype fidelity. At most one comparison runs per Slack client; concurrent reads are not all sampled.
+- `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. The live page is snapshotted before callers add trigger context, and shadow uses the same stored-message selection as mirror mode. Thread selection matches Slack’s first page, including its limitation that newer replies beyond that page may be absent. Channel roots use the newest page, and thread expansion truncation is tracked separately from root-page truncation. An extra stored row distinguishes exactly full pages from truncated pages; it does not prove complete Slack coverage. Counts cover raw message fields, not complete rendered context or author/subtype fidelity. 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/history.ts b/src/slack/history.ts
index 691baf3a3..d68526aff 100644
--- a/src/slack/history.ts
+++ b/src/slack/history.ts
@@ -83,21 +83,28 @@ export function createSlackHistoryReader(deps: {
threadTs?: string,
before?: string,
expandThreads = false,
- ): Promise<CachedMessage[]> {
+ ): Promise<{ rows: CachedMessage[]; hasMore: boolean; truncatedExpansions?: number }> {
const read = deps.core.readSurfaceMessages!;
- const options = { limit: 200, noFallback: true, ...(before ? { before } : {}) };
+ const options = { limit: 201, noFallback: true, ...(before ? { before } : {}) };
if (threadTs) {
const [parents, replies] = await Promise.all([
read(channel, { at: threadTs, noFallback: true, ...(before ? { before } : {}) }),
- read(channel, { ...options, sub: threadTs }),
+ read(channel, { ...options, sub: threadTs, oldestFirst: true }),
]);
- return [...parents, ...replies.slice(-(200 - parents.length))];
+ const rows = [...parents, ...replies];
+ return { rows: rows.slice(0, 200), hasMore: rows.length > 200 };
}
- const roots = await read(channel, { ...options, channelHistory: true });
- if (!expandThreads) return roots;
+ const rootPage = await read(channel, { ...options, channelHistory: true });
+ const roots = rootPage.slice(-200);
+ const hasMore = rootPage.length > 200;
+ if (!expandThreads) return { rows: roots, hasMore };
const parents = roots.filter((m) => (m.replyCount ?? 0) > 0).slice(-5);
const expanded = await Promise.all(parents.map((m) => mirrorHistory(channel, m.ts)));
- return [...new Map([...roots, ...expanded.flat()].map((m) => [m.ts, m])).values()];
+ return {
+ rows: [...new Map([...roots, ...expanded.flatMap((page) => page.rows)].map((m) => [m.ts, m])).values()],
+ hasMore,
+ truncatedExpansions: expanded.filter((page) => page.hasMore).length,
+ };
}
async function compareShadow(
@@ -109,7 +116,8 @@ export function createSlackHistoryReader(deps: {
): Promise<void> {
if (!deps.core.readSurfaceMessages) return;
try {
- const rows = await mirrorHistory(channel, threadTs, before, expandThreads);
+ const mirrorPage = await mirrorHistory(channel, threadTs, before, expandThreads);
+ const rows = mirrorPage.rows;
const timestamps = new Set(rows.map((m) => m.ts));
const liveTimestamps = new Set(live.raw.flatMap((m) => (m.ts ? [m.ts] : [])));
const ids = [...liveTimestamps];
@@ -164,6 +172,8 @@ export function createSlackHistoryReader(deps: {
staleEditedMessages,
liveMessages: liveTimestamps.size,
mirroredMessages: timestamps.size,
+ mirrorHasMore: mirrorPage.hasMore,
+ mirrorTruncatedExpansions: mirrorPage.truncatedExpansions ?? 0,
storedMessages,
matchingMessages,
textMismatches,
@@ -203,7 +213,8 @@ export function createSlackHistoryReader(deps: {
const deleted = new Set<string>();
if (deps.core.readSurfaceMessages) {
try {
- const rows = await mirrorHistory(channel, threadTs, before, expandThreads);
+ const mirrorPage = await mirrorHistory(channel, threadTs, before, expandThreads);
+ const rows = mirrorPage.rows;
mirrored = rows
.filter((m) => !m.deleted && (!before || m.ts < before))
.map((m) => ({
@@ -228,7 +239,14 @@ export function createSlackHistoryReader(deps: {
: {}),
}));
if (mirrored.length && (!threadTs || rows.some((m) => m.ts === threadTs) || before)) {
- return { raw: mirrored, hasMore: rows.length >= 200, note: MIRROR_CONTEXT_NOTE };
+ return {
+ raw: mirrored,
+ hasMore: mirrorPage.hasMore,
+ ...(mirrorPage.truncatedExpansions !== undefined
+ ? { truncatedExpansions: mirrorPage.truncatedExpansions }
+ : {}),
+ note: MIRROR_CONTEXT_NOTE,
+ };
}
} catch (error) {
swallow("slack: mirror context read", error);
diff --git a/test/slack-mirror-pagination.test.ts b/test/slack-mirror-pagination.test.ts
new file mode 100644
index 000000000..7ce9aef7e
--- /dev/null
+++ b/test/slack-mirror-pagination.test.ts
@@ -0,0 +1,109 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { createMemorySurfaceCache } from "../src/surface-cache/surface-cache.ts";
+import { createSlackHistoryReader } from "../src/slack/history.ts";
+import type { BotIdentity } from "../src/slack/directory.ts";
+import type { SlackCoreClient } from "../src/api/slack-core-client.ts";
+
+const ids: BotIdentity = {
+ botUserId: "UBOT",
+ ownBotId: "BBOT",
+ ownTeamId: "T1",
+ botHandle: "qm",
+ ownWorkspaceUrl: "https://example.slack.com",
+ identityMode: "slack-id",
+};
+const ts = (n: number) => `1000.${String(n).padStart(6, "0")}`;
+
+for (const size of [199, 200, 201]) {
+ test(`thread pagination includes parent in the ${size}-message boundary`, async () => {
+ const cache = createMemorySurfaceCache();
+ await cache.ingest(
+ Array.from({ length: size }, (_, i) => ({
+ container: "C1",
+ ts: ts(i),
+ text: `message ${i}`,
+ ...(i ? { sub: ts(0) } : {}),
+ })),
+ );
+ const core = { readSurfaceMessages: cache.readMessages } as unknown as SlackCoreClient;
+ const page = await createSlackHistoryReader({ core, ids, source: "mirror" })({}, "C1", ts(0));
+ assert.deepEqual(
+ page.raw.map((m) => m.ts),
+ Array.from({ length: Math.min(size, 200) }, (_, i) => ts(i)),
+ );
+ assert.equal(page.hasMore, size > 200);
+ await cache.close();
+ });
+}
+
+test("before excludes future replies and a parent outside the requested window", async () => {
+ const cache = createMemorySurfaceCache();
+ await cache.ingest(
+ Array.from({ length: 205 }, (_, i) => ({
+ container: "C1",
+ ts: ts(i),
+ text: "message",
+ ...(i ? { sub: ts(0) } : {}),
+ })),
+ );
+ const core = { readSurfaceMessages: cache.readMessages } as unknown as SlackCoreClient;
+ const read = createSlackHistoryReader({ core, ids, source: "mirror" });
+ const bounded = await read({}, "C1", ts(0), ts(199));
+ assert.equal(bounded.raw.length, 199);
+ assert.equal(bounded.raw.at(-1)?.ts, ts(198));
+ assert.equal(bounded.hasMore, false);
+ const empty = await read({ conversations: { replies: async () => ({ messages: [] }) } }, "C1", ts(0), ts(0));
+ assert.deepEqual(empty.raw, []);
+ await cache.close();
+});
+
+test("missing parent does not consume a reply slot when a bounded read permits mirror use", async () => {
+ const cache = createMemorySurfaceCache();
+ await cache.ingest(
+ Array.from({ length: 201 }, (_, i) => ({ container: "C1", ts: ts(i + 1), sub: ts(0), text: "reply" })),
+ );
+ const core = { readSurfaceMessages: cache.readMessages } as unknown as SlackCoreClient;
+ const page = await createSlackHistoryReader({ core, ids, source: "mirror" })({}, "C1", ts(0), ts(999));
+ assert.equal(page.raw.length, 200);
+ assert.equal(page.raw[0]?.ts, ts(1));
+ assert.equal(page.raw.at(-1)?.ts, ts(200));
+ assert.equal(page.hasMore, true);
+ await cache.close();
+});
+
+test("channel pagination counts roots before expanding a truncated thread", async () => {
+ const cache = createMemorySurfaceCache();
+ await cache.ingest([{ container: "C1", ts: ts(0), text: "root" }]);
+ await cache.ingest(
+ Array.from({ length: 201 }, (_, i) => ({ container: "C1", ts: ts(i + 1), sub: ts(0), text: "reply" })),
+ );
+ const core = { readSurfaceMessages: cache.readMessages } as unknown as SlackCoreClient;
+ const page = await createSlackHistoryReader({ core, ids, source: "mirror" })({}, "C1", undefined, undefined, true);
+ assert.equal(page.raw.length, 200);
+ assert.equal(page.hasMore, false);
+ assert.equal(page.truncatedExpansions, 1);
+ await cache.close();
+});
+
+test("channel overflow keeps newest roots, excludes deletions and preserves visible system entries", async () => {
+ const cache = createMemorySurfaceCache();
+ await cache.ingest(
+ Array.from({ length: 202 }, (_, i) => ({
+ container: "C1",
+ ts: ts(i),
+ text: "root",
+ ...(i === 2 ? { subtype: "channel_topic" } : {}),
+ })),
+ );
+ await cache.ingest([{ container: "C1", ts: ts(201), deleted: true }]);
+ const core = { readSurfaceMessages: cache.readMessages } as unknown as SlackCoreClient;
+ const page = await createSlackHistoryReader({ core, ids, source: "mirror" })({}, "C1");
+ assert.equal(page.hasMore, true);
+ assert.deepEqual(
+ page.raw.map((m) => m.ts),
+ Array.from({ length: 200 }, (_, i) => ts(i + 1)),
+ );
+ assert.equal(page.raw[1]?.subtype, "channel_topic");
+ await cache.close();
+});
diff --git a/test/slack-mirror-soak.test.ts b/test/slack-mirror-soak.test.ts
index 3fdda6104..6c301d009 100644
--- a/test/slack-mirror-soak.test.ts
+++ b/test/slack-mirror-soak.test.ts
@@ -241,7 +241,7 @@ test("shadow compares canonical mention IDs without erasing literal entity or at
assert.equal(result.liveMessagesMissingFromStorage, 0);
});
-test("mirror selects channel roots and retains newest thread replies", async () => {
+test("mirror selects newest channel roots and the first thread page", async () => {
const { createMemorySurfaceCache } = await import("../src/surface-cache/surface-cache.ts");
const cache = createMemorySurfaceCache();
const ts = (n: number) => String(n).padStart(6, "0");
@@ -261,10 +261,10 @@ test("mirror selects channel roots and retains newest thread replies", async ()
const thread = await read({}, "C1", ts(204));
assert.equal(thread.raw.length, 200);
assert.equal(thread.raw[0]?.ts, ts(204));
- assert.equal(thread.raw.at(-1)?.ts, ts(549));
+ assert.equal(thread.raw.at(-1)?.ts, ts(498));
const expanded = await read({}, "C1", undefined, undefined, true);
assert.equal(expanded.raw.length, 399);
- assert.equal(expanded.raw.at(-1)?.ts, ts(549));
+ assert.equal(expanded.raw.at(-1)?.ts, ts(498));
});
test("shadow never certifies failed or truncated live thread expansion as complete", async (t) => {
@@ -303,7 +303,7 @@ test("shadow never certifies failed or truncated live thread expansion as comple
}
});
-test("shadow measures the same recent long-thread selection as mirror without fallback", async (t) => {
+test("shadow and mirror use the live first-page thread contract without fallback", async (t) => {
const logs: string[] = [];
t.mock.method(console, "info", (line: string) => logs.push(line));
const cache = createMemorySurfaceCache();
@@ -333,7 +333,7 @@ test("shadow measures the same recent long-thread selection as mirror without fa
const mirrored = await createSlackHistoryReader({ core, ids, source: "mirror" })(client, "C1", "1000.000000");
assert.deepEqual(
mirrored.raw.map((message) => message.ts),
- [messages[0]!, ...messages.slice(-199)].map((message) => message.ts),
+ messages.slice(0, 200).map((message) => message.ts),
);
const live = await createSlackHistoryReader({ core, ids, source: "shadow" })(client, "C1", "1000.000000");
assert.deepEqual(live.raw, messages.slice(0, 200));
@@ -341,9 +341,9 @@ test("shadow measures the same recent long-thread selection as mirror without fa
const comparison = JSON.parse(logs[0]!);
assert.equal(comparison.liveMessages, 200);
assert.equal(comparison.mirroredMessages, 200);
- assert.equal(comparison.liveMessagesMissingFromMirror, 20);
- assert.equal(comparison.mirrorMessagesOutsideLiveWindow, 20);
- assert.equal(comparison.matchingMessages, 180);
+ assert.equal(comparison.liveMessagesMissingFromMirror, 0);
+ assert.equal(comparison.mirrorMessagesOutsideLiveWindow, 0);
+ assert.equal(comparison.matchingMessages, 200);
assert.equal(comparison.liveComplete, false);
await cache.close();
});