Multiplayer agent harness for work.
Repair Slack mirror ingestion and qualify context agreement (#1223)
Regan Bellc5472eba9028
diff --git a/src/core/message-revisions.ts b/src/core/message-revisions.tsindex 1df077011..cc9ff9c5b 100644--- a/src/core/message-revisions.ts+++ b/src/core/message-revisions.ts@@ -156,7 +156,9 @@ export async function recordMessageRevisions(retry: IdleRetry = DEFAULT_IDLE_RETRY,): Promise<void> {for (const event of events.filter(isRevisionEvent)) {- const refs = await sessions.sessionsByThreadRefs(slackThreadRefCandidates(event.container, event.ts, event.sub));+ const refs = await sessions.sessionsByThreadRefs(+ slackThreadRefCandidates(event.container, event.ts, event.sub ?? undefined),+ );for (const ref of refs) await recordWhenIdle(sessions, ref, event, retry);}}diff --git a/src/slack/deliveries.ts b/src/slack/deliveries.tsindex aa6b9fbba..6b2755fa8 100644--- a/src/slack/deliveries.ts+++ b/src/slack/deliveries.ts@@ -23,7 +23,6 @@ import {import type { SlackCoreClient } from "../api/slack-core-client.ts";import type { Delivery } from "../types.ts";import type { TurnFlow } from "./turn-flow.ts";-import type { Mirror } from "./mirror.ts";import { cleanAgentReplyForSlack, stripSlackDirectives } from "./messaging.ts";import { cronIdOf } from "../sessions/session-store.ts";import { slackErrorCode } from "./payloads.ts";@@ -54,19 +53,17 @@ export function createDeliveryPoller(deps: {core: SlackCoreClient;webUiPublicUrl?: string;flow: TurnFlow;- mirror: Mirror;threads: ReturnType<typeof createThreadTracker>;clientForIdentity(identity: string): any;claimMs?: number;slowDrainMs?: number;}): { pollDeliveries(client: any): Promise<boolean> } {- const { core, flow, mirror, threads, clientForIdentity } = deps;+ const { core, flow, threads, clientForIdentity } = deps;const claimMs = deps.claimMs ?? DELIVERY_CLAIM_MS;const slowDrainMs = deps.slowDrainMs ?? SLOW_DRAIN_ALARM_MS;const claimMargin = Math.min(DELIVERY_CLAIM_MARGIN_MS, Math.floor(claimMs / 3));const recoveredRow = (d: Delivery): boolean => typeof d.createdAt === "number" && Date.now() - d.createdAt > claimMs;const { inFlightRuns } = flow;- const { mirrorSelfPost } = mirror;async function drainClaimed(types: string[],@@ -274,17 +271,15 @@ export function createDeliveryPoller(deps: {...botIdentityArgs(),});preserved = true;- mirrorSelfPost(channel, d.destination.editRef, taskList, { sub: threadTs, editedAt: Date.now() });} catch (error) {swallow("slack: preserve recovered task list", error);}}if (!preserved) {- const posted = await client.chat.postMessage({+ await client.chat.postMessage({...slackReplyArgs(channel, taskList, threadTs, { threadOnly: Boolean(threadTs) }),blocks: [{ type: "section", text: { type: "mrkdwn", text: taskList } }],});- mirrorSelfPost(channel, posted?.ts, taskList, { sub: threadTs });}} else if (d.destination.editRef) {await client.chat@@ -319,7 +314,6 @@ export function createDeliveryPoller(deps: {...(unfurlLinks !== undefined ? { unfurl_links: unfurlLinks, unfurl_media: unfurlLinks } : {}),});if (threadTs) threads.mark(channel, threadTs, true);- mirrorSelfPost(channel, d.destination.editRef, text, { sub: threadTs, editedAt: Date.now() });if (!alreadyDelivered) await replayAttachments(threadTs);return undefined;} catch (e) {@@ -339,11 +333,6 @@ export function createDeliveryPoller(deps: {);const root = threadTs ?? (res?.ts ? String(res.ts) : undefined);if (root) threads.mark(channel, root, true);- if (!d.destination.identity) {- for (const part of res.parts ?? [{ ts: res?.ts, text }]) {- mirrorSelfPost(channel, part.ts, part.text, { sub: threadTs });- }- }if (!res.reused) await replayAttachments(root);return undefined;} finally {@@ -392,9 +381,6 @@ export function createDeliveryPoller(deps: {: undefined,);reused = Boolean(posted.reused);- for (const part of posted.parts ?? [{ ts: posted?.ts, text }]) {- mirrorSelfPost(channel, part.ts, part.text, { kind: "dm", sub: threadTs });- }}if (d.attachments?.length && !reused) {try {diff --git a/src/slack/directory.ts b/src/slack/directory.tsindex cd8117201..72529f7ce 100644--- a/src/slack/directory.ts+++ b/src/slack/directory.ts@@ -56,7 +56,7 @@ interface ChannelRef {info: ChannelMeta;}-type RosterKind = { plural: string; authz: string; item: string; limit?: number };+type RosterKind = { plural: string; authz: string; item: string; limit?: number; requireComplete?: boolean };const MEMBERS_PAGE_LIMIT = 200;const ROSTER_FETCH_CONCURRENCY = 4;@@ -258,6 +258,7 @@ export function createDirectory(deps: {try {memberIds = await fetchChannelMemberIds(client, ref.id);} catch (err) {+ if (kind.requireComplete) throw err;console.error("%s",`[slack-plugin] members fetch failed for ${kind.item} ${ref.id}:`,@@ -270,7 +271,10 @@ export function createDirectory(deps: {for (const id of memberIds) {const { actor, ok } = await classifyUserCached(client, id);actors.push(actor);- if (!ok) complete = false;+ if (!ok) {+ if (kind.requireComplete) throw new Error("Slack mirror member classification unavailable");+ complete = false;+ }}rosters.set(ref.id, { actors, complete });}diff --git a/src/slack/events.ts b/src/slack/events.tsindex a99677501..183136e87 100644--- a/src/slack/events.ts+++ b/src/slack/events.ts@@ -65,7 +65,8 @@ export function registerSlackEvents(if (!allowActor) return true;if (!userId) return false;if (userId === ids.botUserId) return true;- const { actor } = await directory.classifyUserCached(client, userId);+ const { actor, ok } = await directory.classifyUserCached(client, userId);+ if (ok === false) throw new Error("Slack event actor lookup unavailable");return allowActor(actor);};const denyDirectApproach = async (@@ -117,187 +118,207 @@ export function registerSlackEvents(};app.event("app_mention", async ({ event, body, client, context }: EventArgs) => {- const e = parseMessageEvent(event);- const identity = await eventIdentity(client, e);- if (allowActor && !(await actorAllowed(client, identity.userId))) {- if (deduper.seen(dedupeKey({ event_id: parseEventId(body), channel: e.channel, ts: e.ts }))) return;- await denyDirectApproach(client, {- channel: e.channel,- userId: identity.userId,- kind: "channel",- isBot: Boolean(e.bot_id || identity.actor?.isBot),- });- return;- }- const key = dedupeKey({- event_id: parseEventId(body),- client_msg_id: e.client_msg_id,- channel: e.channel,- ts: e.ts,- });- const content = messageWithForwardedContent(e);- await dispatch(- key,- {- kind: "channel",- channel: e.channel,- userId: identity.userId,- ...(identity.actor ? { actor: identity.actor } : {}),- rawText: content.text,- files: content.files,- threadTs: e.thread_ts,- ts: e.ts,- ...(e.bot_id || e.subtype === "bot_message" ? { botAuthored: true } : {}),- ackGate: context.ackGate,- },- client,- );- });-- app.message(async ({ message, body, client, context }: MessageArgs) => {- const m = parseMessageEvent(message);- const eventId = parseEventId(body);- const privacyChange = channelPrivacyChange(m);- if (privacyChange) {- await forceDirectorySync(client, privacyChange.channel);- return;- }- if (isGroupMembershipMessage(m)) {- await forceDirectorySync(client);- return;- }- const ackGate = context.ackGate;- if (m.channel && m.ts && !m.subtype && !(m.bot_id || m.subtype === "bot_message")) {- deps.inboxMessage?.(client, {- channel: m.channel,- ts: m.ts,- ...(m.thread_ts ? { threadTs: m.thread_ts } : {}),- ...(typeof m.text === "string" && m.text ? { text: m.text } : {}),- ...(m.user ? { senderSlackId: m.user } : {}),- });- }- if (m.subtype === "message_changed" && m.message?.subtype === "tombstone" && m.message.ts && m.channel) {- await pushSurfaceEvents([{ container: m.channel, ts: m.message.ts, deleted: true }]);- return;- }- if (!(await actorAllowed(client, m.user ?? m.message?.user ?? m.previous_message?.user))) {- if (m.channel_type === "im" && shouldProcessMessage(m, ids.botUserId, ids.ownBotId)) {+ try {+ const e = parseMessageEvent(event);+ if (!shouldProcessMessage(e, ids.botUserId, ids.ownBotId)) return;+ const identity = await eventIdentity(client, e);+ if (allowActor && !(await actorAllowed(client, identity.userId))) {+ if (deduper.seen(dedupeKey({ event_id: parseEventId(body), channel: e.channel, ts: e.ts }))) return;await denyDirectApproach(client, {- channel: m.channel,- userId: m.user,- kind: "dm",- threadTs: m.thread_ts,- isBot: Boolean(m.bot_id || m.subtype === "bot_message"),+ channel: e.channel,+ userId: identity.userId,+ kind: "channel",+ isBot: Boolean(e.bot_id || identity.actor?.isBot),});+ return;}- return;- }- if (m.subtype === "message_changed" && m.message) {- const textChanged = m.previous_message?.text === undefined || m.previous_message.text !== m.message.text;- if (shouldProcessMessage(m.message, ids.botUserId, ids.ownBotId))- await mirrorMessageEvent({ ...m.message, channel: m.channel, channel_type: m.channel_type }, client, {- ...(textChanged- ? {- editedAt:- Number(m.message.edited?.ts) > 0 ? Math.round(Number(m.message.edited!.ts) * 1000) : Date.now(),- }- : {}),- ...(m.channel_type === "im" ? { kind: "dm" as const } : {}),- });- return;- }- if (m.subtype === "message_deleted" && m.deleted_ts) {- const type = m.channel_type;- const prev = m.previous_message;- const selfDelete = Boolean(- prev && ((ids.botUserId && prev.user === ids.botUserId) || (ids.ownBotId && prev.bot_id === ids.ownBotId)),- );- if (m.channel && (type === "channel" || type === "group" || type === "mpim" || type === "im"))- await pushSurfaceEvents([- {- container: m.channel,- ts: m.deleted_ts,- deleted: true,- ...(prev?.thread_ts && prev.thread_ts !== m.deleted_ts ? { sub: prev.thread_ts } : {}),- ...(selfDelete ? { self: true } : {}),- },- ]);- return;- }- if (!shouldProcessMessage(m, ids.botUserId, ids.ownBotId)) return;-- if (m.channel_type === "im") {- const identity = await eventIdentity(client, m);const key = dedupeKey({- event_id: eventId,- client_msg_id: m.client_msg_id,- channel: m.channel,- ts: m.ts,+ event_id: parseEventId(body),+ client_msg_id: e.client_msg_id,+ channel: e.channel,+ ts: e.ts,});- const content = messageWithForwardedContent(m);+ const content = messageWithForwardedContent(e);await dispatch(key,{- kind: "dm",- channel: m.channel,+ kind: "channel",+ channel: e.channel,userId: identity.userId,...(identity.actor ? { actor: identity.actor } : {}),- ...(m.bot_profile?.name || m.username ? { authorName: String(m.bot_profile?.name || m.username) } : {}),rawText: content.text,files: content.files,- threadTs: m.thread_ts,- ts: m.ts,- ...(m.bot_id || m.subtype === "bot_message" ? { botAuthored: true } : {}),- ackGate,+ threadTs: e.thread_ts,+ ts: e.ts,+ ...(e.bot_id || e.subtype === "bot_message" ? { botAuthored: true } : {}),+ ackGate: context.ackGate,},client,);- return;+ } catch (error) {+ context.ackGate?.failed("Slack mention processing failed");+ throw error;}+ });- if (m.channel_type === "channel" || m.channel_type === "group" || m.channel_type === "mpim") {- if (m.channel_type === "mpim" && m.channel) syncForUnseenGroup(client, m.channel);- const threadReply = isThreadReply(m);- const isMention = mentionsBot(m.text ?? "", ids.botUserId);- const threadTs = m.thread_ts;- const willDispatch = Boolean(- threadReply && !isMention && threadTs && (await botHasStakeInThread(client, m.channel, threadTs)),- );- await mirrorMessageEvent(m, client, willDispatch ? { handled: true } : {});- if (!threadReply) return;- if (isMention) return;- if (!willDispatch) {- console.error(- `[slack-plugin] thread-follow skipped: no bot stake detected in thread ch=${m.channel} thread_ts=${m.thread_ts} ts=${m.ts}`,+ app.message(async ({ message, body, client, context }: MessageArgs) => {+ try {+ const m = parseMessageEvent(message);+ const eventId = parseEventId(body);+ const privacyChange = channelPrivacyChange(m);+ if (privacyChange) {+ await forceDirectorySync(client, privacyChange.channel);+ return;+ }+ if (isGroupMembershipMessage(m)) {+ await forceDirectorySync(client);+ return;+ }+ const ackGate = context.ackGate;+ if (m.channel && m.ts && !m.subtype && !(m.bot_id || m.subtype === "bot_message")) {+ deps.inboxMessage?.(client, {+ channel: m.channel,+ ts: m.ts,+ ...(m.thread_ts ? { threadTs: m.thread_ts } : {}),+ ...(typeof m.text === "string" && m.text ? { text: m.text } : {}),+ ...(m.user ? { senderSlackId: m.user } : {}),+ });+ }+ if (m.subtype === "message_changed" && m.message?.subtype === "tombstone" && m.message.ts && m.channel) {+ await pushSurfaceEvents([{ container: m.channel, ts: m.message.ts, deleted: true }]);+ return;+ }+ const ownMessage = (event: { user?: string; bot_id?: string }): boolean =>+ Boolean((ids.botUserId && event.user === ids.botUserId) || (ids.ownBotId && event.bot_id === ids.ownBotId));+ if (+ !(await actorAllowed(+ client,+ ownMessage(m.message ?? m.previous_message ?? m)+ ? ids.botUserId+ : (m.user ?? m.message?.user ?? m.previous_message?.user),+ ))+ ) {+ if (m.channel_type === "im" && shouldProcessMessage(m, ids.botUserId, ids.ownBotId)) {+ await denyDirectApproach(client, {+ channel: m.channel,+ userId: m.user,+ kind: "dm",+ threadTs: m.thread_ts,+ isBot: Boolean(m.bot_id || m.subtype === "bot_message"),+ });+ }+ return;+ }+ if (m.subtype === "message_changed" && m.message) {+ const textChanged = m.previous_message?.text === undefined || m.previous_message.text !== m.message.text;+ const editedAt = Number(m.message.edited?.ts) || (textChanged ? Number(m.ts) : 0);+ if (shouldProcessMessage(m.message, "", ""))+ await mirrorMessageEvent({ ...m.message, channel: m.channel, channel_type: m.channel_type }, client, {+ ...(editedAt > 0 ? { editedAt: Math.round(editedAt * 1000) } : {}),+ ...(m.channel_type === "im" ? { kind: "dm" as const } : {}),+ });+ return;+ }+ if (m.subtype === "message_deleted" && m.deleted_ts) {+ const type = m.channel_type;+ const prev = m.previous_message;+ const selfDelete = Boolean(+ prev && ((ids.botUserId && prev.user === ids.botUserId) || (ids.ownBotId && prev.bot_id === ids.ownBotId)),);+ if (m.channel && (type === "channel" || type === "group" || type === "mpim" || type === "im"))+ await pushSurfaceEvents([+ {+ container: m.channel,+ ts: m.deleted_ts,+ deleted: true,+ ...(prev?.thread_ts && prev.thread_ts !== m.deleted_ts ? { sub: prev.thread_ts } : {}),+ ...(selfDelete ? { self: true } : {}),+ },+ ]);return;}- const key = dedupeKey({- event_id: eventId,- client_msg_id: m.client_msg_id,- channel: m.channel,- ts: m.ts,- });- const identity = await eventIdentity(client, m);- const content = messageWithForwardedContent(m);- await dispatch(- key,- {- kind: "channel",+ if (ownMessage(m) && shouldProcessMessage(m, "", "")) {+ await mirrorMessageEvent(m, client, m.channel_type === "im" ? { kind: "dm" } : {});+ return;+ }+ if (!shouldProcessMessage(m, ids.botUserId, ids.ownBotId)) return;++ if (m.channel_type === "im") {+ const identity = await eventIdentity(client, m);+ const key = dedupeKey({+ event_id: eventId,+ client_msg_id: m.client_msg_id,channel: m.channel,- userId: identity.userId,- ...(identity.actor ? { actor: identity.actor } : {}),- ...(m.bot_profile?.name || m.username ? { authorName: String(m.bot_profile?.name || m.username) } : {}),- rawText: content.text,- files: content.files,- threadTs: m.thread_ts,ts: m.ts,- unprompted: true,- ...(m.bot_id || m.subtype === "bot_message" ? { botAuthored: true } : {}),- ackGate,- },- client,- );+ });+ const content = messageWithForwardedContent(m);+ await dispatch(+ key,+ {+ kind: "dm",+ channel: m.channel,+ userId: identity.userId,+ ...(identity.actor ? { actor: identity.actor } : {}),+ ...(m.bot_profile?.name || m.username ? { authorName: String(m.bot_profile?.name || m.username) } : {}),+ rawText: content.text,+ files: content.files,+ threadTs: m.thread_ts,+ ts: m.ts,+ ...(m.bot_id || m.subtype === "bot_message" ? { botAuthored: true } : {}),+ ackGate,+ },+ client,+ );+ return;+ }++ if (m.channel_type === "channel" || m.channel_type === "group" || m.channel_type === "mpim") {+ if (m.channel_type === "mpim" && m.channel) syncForUnseenGroup(client, m.channel);+ const threadReply = isThreadReply(m);+ const isMention = mentionsBot(m.text ?? "", ids.botUserId);+ const threadTs = m.thread_ts;+ const willDispatch = Boolean(+ threadReply && !isMention && threadTs && (await botHasStakeInThread(client, m.channel, threadTs, m.ts)),+ );+ await mirrorMessageEvent(m, client, willDispatch ? { handled: true } : {});+ if (!threadReply) return;+ if (isMention) return;+ if (!willDispatch) {+ console.error(+ `[slack-plugin] thread-follow skipped: no bot stake detected in thread ch=${m.channel} thread_ts=${m.thread_ts} ts=${m.ts}`,+ );+ return;+ }+ const key = dedupeKey({+ event_id: eventId,+ client_msg_id: m.client_msg_id,+ channel: m.channel,+ ts: m.ts,+ });+ const identity = await eventIdentity(client, m);+ const content = messageWithForwardedContent(m);+ await dispatch(+ key,+ {+ kind: "channel",+ channel: m.channel,+ userId: identity.userId,+ ...(identity.actor ? { actor: identity.actor } : {}),+ ...(m.bot_profile?.name || m.username ? { authorName: String(m.bot_profile?.name || m.username) } : {}),+ rawText: content.text,+ files: content.files,+ threadTs: m.thread_ts,+ ts: m.ts,+ unprompted: true,+ ...(m.bot_id || m.subtype === "bot_message" ? { botAuthored: true } : {}),+ ackGate,+ },+ client,+ );+ }+ } catch (error) {+ context.ackGate?.failed("Slack message processing failed");+ throw error;}});@@ -349,9 +370,13 @@ export function registerSlackEvents(app.event("assistant_thread_context_changed", async () => {});app.event("reaction_added", async ({ event, body, client }: EventArgs) => {- await handleReactionEvent(parseReactionEvent(event), parseEventId(body), client, true);+ const reaction = parseReactionEvent(event);+ if (reaction.user === ids.botUserId) return;+ await handleReactionEvent(reaction, parseEventId(body), client, true);});app.event("reaction_removed", async ({ event, body, client }: EventArgs) => {- await handleReactionEvent(parseReactionEvent(event), parseEventId(body), client, false);+ const reaction = parseReactionEvent(event);+ if (reaction.user === ids.botUserId) return;+ await handleReactionEvent(reaction, parseEventId(body), client, false);});}diff --git a/src/slack/history.ts b/src/slack/history.tsindex d4d3533dd..9033a0ff5 100644--- a/src/slack/history.ts+++ b/src/slack/history.ts@@ -3,6 +3,7 @@ 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 { CachedMessage } from "../surface-cache/types.ts";import type { BotIdentity } from "./directory.ts";import type { SlackHistoryMessage } from "./payloads.ts";import { parseMessageList } from "./payloads.ts";@@ -11,6 +12,8 @@ import { swallow } from "../util/errors.ts";interface SlackHistoryPage {raw: SlackHistoryMessage[];hasMore: boolean;+ expansionFailures?: number;+ truncatedExpansions?: number;note?: string;}@@ -53,69 +56,133 @@ export function createSlackHistoryReader(deps: {const expanded = await Promise.all(parents.map(async (m) => {try {- return parseMessageList(await historyClient.conversations.replies({ channel, ts: m.ts, limit: 200 }))- .messages;+ return {+ page: parseMessageList(await historyClient.conversations.replies({ channel, ts: m.ts, limit: 200 })),+ failed: false,+ };} catch {- return [];+ return { page: { messages: [] as SlackHistoryMessage[], hasMore: false }, failed: true };}}),);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 };+ for (const m of [...raw, ...expanded.flatMap((result) => result.page.messages)]) if (m.ts) byTs.set(m.ts, m);+ return {+ raw: [...byTs.values()],+ hasMore: page.hasMore,+ expansionFailures: expanded.filter((result) => result.failed).length,+ truncatedExpansions: expanded.filter((result) => result.page.hasMore).length,+ };}return { raw, hasMore: page.hasMore };}+ async function mirrorHistory(+ channel: string,+ threadTs?: string,+ before?: string,+ expandThreads = false,+ ): Promise<CachedMessage[]> {+ const read = deps.core.readSurfaceMessages!;+ const options = { limit: 200, 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, oldestFirst: true }),+ ]);+ return [...parents, ...replies].slice(0, 200);+ }+ const roots = await read(channel, { ...options, channelHistory: true });+ if (!expandThreads) return roots;+ 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()];+ }+async function compareShadow(live: SlackHistoryPage,channel: string,threadTs?: string,before?: string,+ expandThreads = false,): 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 rows = await mirrorHistory(channel, threadTs, before, expandThreads);+ const timestamps = new Set(rows.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]));+ const ids = [...liveTimestamps];+ const storedRows: CachedMessage[] = [];+ for (let i = 0; i < ids.length; i += 500) {+ storedRows.push(+ ...(await deps.core.readSurfaceMessages(channel, {+ timestamps: ids.slice(i, i + 500),+ limit: 500,+ noFallback: true,+ includeDeleted: true,+ })),+ );+ }+ const byTs = new Map(storedRows.map((m) => [m.ts, m]));let textMismatches = 0;let staleEditedMessages = 0;+ let threadParentMismatches = 0;+ let fileMismatches = 0;+ let matchingMessages = 0;+ let storedMessages = 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++;+ storedMessages++;+ const content = messageWithForwardedContent(message);+ const normalize = (text: string) => resolveMentionsInText(text, (id) => stored.mentions?.[id]);+ const textMatches = normalize(stored.text) === normalize(decodeSlackEntities(content.text));+ const parentMatches =+ stored.sub === (message.thread_ts && message.thread_ts !== message.ts ? message.thread_ts : undefined);+ const files = (values: Array<{ id?: string; name?: string; mimetype?: string }>) =>+ JSON.stringify(+ values+ .filter((f) => f.id)+ .map((f) => [f.id, f.name ?? null, f.mimetype ?? null])+ .sort((a, b) => String(a[0]).localeCompare(String(b[0]))),+ );+ const filesMatch = files(content.files) === files((stored.files ?? []).map((f) => ({ ...f, id: f.fileId })));+ const stale = Math.round(Number(message.edited?.ts) * 1000) > (stored.editedAt ?? 0);+ if (!textMatches) textMismatches++;+ if (!parentMatches) threadParentMismatches++;+ if (!filesMatch) fileMismatches++;+ if (stale) staleEditedMessages++;+ if (textMatches && parentMatches && filesMatch && !stale && timestamps.has(stored.ts)) matchingMessages++;}console.info(JSON.stringify({event: "slack_mirror_shadow",+ version: 2,thread: Boolean(threadTs),+ expandThreads,conversationKind: channel.startsWith("D") ? "dm" : "channel_or_group",staleEditedMessages,liveMessages: liveTimestamps.size,mirroredMessages: timestamps.size,+ storedMessages,+ matchingMessages,textMismatches,- liveMessagesMissingFromMirror: [...liveTimestamps].filter((ts) => !timestamps.has(ts)).length,+ threadParentMismatches,+ fileMismatches,+ liveMessagesMissingFromStorage: ids.filter((ts) => !byTs.has(ts) || byTs.get(ts)!.deleted).length,+ liveMessagesMissingFromMirror: ids.filter((ts) => !timestamps.has(ts)).length,mirrorMessagesOutsideLiveWindow: [...timestamps].filter((ts) => !liveTimestamps.has(ts)).length,missingThreadParent: Boolean(threadTs && !timestamps.has(threadTs)),liveHasMore: live.hasMore,+ liveExpansionFailures: live.expansionFailures ?? 0,+ liveTruncatedExpansions: live.truncatedExpansions ?? 0,+ liveComplete: !live.hasMore && !live.expansionFailures && !live.truncatedExpansions,}),);} catch {- console.info(JSON.stringify({ event: "slack_mirror_shadow", outcome: "read_failed", thread: Boolean(threadTs) }));+ console.info(+ JSON.stringify({ event: "slack_mirror_shadow", version: 2, outcome: "read_failed", thread: Boolean(threadTs) }),+ );}}@@ -125,7 +192,7 @@ export function createSlackHistoryReader(deps: {const live = await liveHistory(client, channel, threadTs, before, expandThreads);if (deps.source === "shadow" && !shadowPending) {shadowPending = true;- void compareShadow(live, channel, threadTs, before).finally(() => {+ void compareShadow(live, channel, threadTs, before, expandThreads).finally(() => {shadowPending = false;});}@@ -136,16 +203,7 @@ export function createSlackHistoryReader(deps: {const deleted = new Set<string>();if (deps.core.readSurfaceMessages) {try {- const options = { limit: 200, includeDeleted: true, ...(before ? { before } : {}) };- const rows = threadTs- ? (- await Promise.all([- deps.core.readSurfaceMessages(channel, { ...options, sub: threadTs }),- deps.core.readSurfaceMessages(channel, { at: threadTs, includeDeleted: true }),- ])- ).flat()- : await deps.core.readSurfaceMessages(channel, options);- for (const row of rows) if (row.deleted) deleted.add(row.ts);+ const rows = await mirrorHistory(channel, threadTs, before, expandThreads);mirrored = rows.filter((m) => !m.deleted && (!before || m.ts < before)).map((m) => ({@@ -202,6 +260,15 @@ export function createSlackHistoryReader(deps: {).catch((error) => swallow("slack: history mirror ingest", error));}+ if (deps.core.readSurfaceMessages && page.messages.length) {+ const stored = await deps.core.readSurfaceMessages(channel, {+ timestamps: page.messages.flatMap((m) => (m.ts ? [m.ts] : [])),+ limit: 500,+ includeDeleted: true,+ noFallback: true,+ });+ for (const row of stored) if (row.deleted) deleted.add(row.ts);+ }const byTs = new Map<string, SlackHistoryMessage>();for (const message of [...page.messages, ...mirrored])if (message.ts && !deleted.has(message.ts)) byTs.set(message.ts, message);diff --git a/src/slack/index.ts b/src/slack/index.tsindex 16e005536..73cb1ce79 100644--- a/src/slack/index.ts+++ b/src/slack/index.ts@@ -165,6 +165,7 @@ export async function startSlackPlugin(};const app = new App({token: BOT_TOKEN,+ ignoreSelf: false,receiver: receiver(),logLevel: parseLogLevel(cfg.logLevel),clientOptions: { ...CLIENT_OPTIONS },@@ -342,7 +343,6 @@ export async function startSlackPlugin(const deliveries = createDeliveryPoller({core,flow,- mirror,threads,clientForIdentity,webUiPublicUrl: cfg.webUiPublicUrl,diff --git a/src/slack/mirror.ts b/src/slack/mirror.tsindex d91d4464d..e3052d4f2 100644--- a/src/slack/mirror.ts+++ b/src/slack/mirror.ts@@ -9,12 +9,6 @@ import { MAX_NAME_LOOKUPS } from "./conversation-view.ts";export interface Mirror {pushSurfaceEvents(events: IngestEvent[]): Promise<void>;- mirrorSelfPost(- container: string,- ts: unknown,- text: string,- opts?: { sub?: string; editedAt?: number; kind?: "channel" | "dm" | "group" },- ): void;resolveTextMentions(client: any, text: string): Promise<{ text: string; mentions: Record<string, string> }>;mirrorMessageEvent(m: Partial<SlackMessageEvent>,@@ -34,31 +28,7 @@ export function createMirror(deps: {async function pushSurfaceEvents(events: IngestEvent[]): Promise<void> {if (!events.length) return;- try {- await core.ingestSurfaceEvents(events, { name: ids.botHandle, mentionId: ids.botUserId });- } catch (e) {- swallow("slack: surface-cache ingest", e);- }- }-- function mirrorSelfPost(- container: string,- ts: unknown,- text: string,- opts: { sub?: string; editedAt?: number; kind?: "channel" | "dm" | "group" } = {},- ): void {- if (!ts) return;- void pushSurfaceEvents([- {- container,- ts: String(ts),- ...(opts.sub ? { sub: opts.sub } : {}),- self: true,- text,- ...(opts.editedAt ? { editedAt: opts.editedAt } : {}),- ...(opts.kind ? { kind: opts.kind } : {}),- },- ]);+ await core.ingestSurfaceEvents(events, { name: ids.botHandle, mentionId: ids.botUserId });}async function resolveTextMentions(@@ -96,10 +66,12 @@ export function createMirror(deps: {let gate = ambientRoomGate.get(container);if (!gate || Date.now() - gate.at > 5_000) {const info = kind === "group" ? undefined : await directory.getChannelInfo(client, container);+ if (kind !== "group" && !info) throw new Error("Slack mirror room lookup unavailable");const rosters = await directory.allInternalRosters(client, [{ id: container, ...(info ? { info } : {}) }], {plural: "ambient rooms",authz: "ambient-work",item: "room",+ requireComplete: true,});gate = { allowed: rosters.has(container), at: Date.now() };ambientRoomGate.set(container, gate);@@ -113,17 +85,17 @@ export function createMirror(deps: {{container,ts,- ...(m.thread_ts && m.thread_ts !== ts ? { sub: String(m.thread_ts) } : {}),+ ...(m.subtype === "thread_broadcast" ? { broadcast: true } : {}),+ sub: m.thread_ts && m.thread_ts !== ts ? String(m.thread_ts) : null,...(m.user ? { authorId: String(m.user) } : {}),...(m.bot_profile?.name || m.username ? { authorName: String(m.bot_profile?.name || m.username) } : {}),text,- ...(content.files.length- ? {- files: content.files- .filter((f) => f.id)- .map((f) => ({ fileId: f.id!, name: f.name, mimetype: f.mimetype })),- }+ ...((ids.botUserId && m.user === ids.botUserId) || (ids.ownBotId && m.bot_id === ids.ownBotId)+ ? { self: true, handled: true }: {}),+ files: content.files+ .filter((file) => file.id)+ .map((file) => ({ fileId: file.id!, name: file.name, mimetype: file.mimetype })),...(Object.keys(mentions).length ? { mentions } : {}),...(m.bot_id || m.bot_profile ? { bot: true } : {}),...(mentionsBot(raw, ids.botUserId) ? { mentionsSelf: true } : {}),@@ -135,5 +107,5 @@ export function createMirror(deps: {]);}- return { pushSurfaceEvents, mirrorSelfPost, resolveTextMentions, mirrorMessageEvent };+ return { pushSurfaceEvents, resolveTextMentions, mirrorMessageEvent };}diff --git a/src/slack/turn-handler.ts b/src/slack/turn-handler.tsindex 5485e1111..62c04fba6 100644--- a/src/slack/turn-handler.ts+++ b/src/slack/turn-handler.ts@@ -107,7 +107,7 @@ export interface TurnHandler {handleIncoming(inc: Incoming, client: any): Promise<void>;dispatch(key: string, inc: Incoming, client: any): Promise<void>;handleReactionEvent(evt: SlackReactionEvent, eventId: string | undefined, client: any, added: boolean): Promise<void>;- botHasStakeInThread(client: any, channel: string, threadTs: string): Promise<boolean>;+ botHasStakeInThread(client: any, channel: string, threadTs: string, before?: string): Promise<boolean>;}function channelType(kind: SlackConversationKind, conversationKind: SlackConversationKind): string {@@ -164,18 +164,30 @@ export function createTurnHandler(deps: {externalParticipantsEnabled,} = deps;const { classifyUserCached, classifyActor, getChannelInfo, channelMembership } = directory;- const { mirrorSelfPost, mirrorMessageEvent } = mirror;+ const { mirrorMessageEvent } = mirror;const { callCore, inFlightRuns, inFlightRunByThread, ackRunDelivery } = flow;const reactionsInFlight = new Set<string>();- async function botHasStakeInThread(client: any, channel: string, threadTs: string): Promise<boolean> {+ async function botHasStakeInThread(+ client: any,+ channel: string,+ threadTs: string,+ before?: string,+ ): Promise<boolean> {const cached = threads.get(channel, threadTs);if (cached !== undefined) return cached;try {const messages = deps.readHistory- ? (await deps.readHistory(client, channel, threadTs)).raw- : ((await client.conversations.replies({ channel, ts: threadTs, limit: 200 })).messages ?? []);+ ? (await deps.readHistory(client, channel, threadTs, before)).raw+ : ((+ await client.conversations.replies({+ channel,+ ts: threadTs,+ limit: 200,+ ...(before ? { latest: before, inclusive: false } : {}),+ })+ ).messages ?? []);const present = threadHasBotStake(messages, ids.botUserId, ids.ownBotId);threads.mark(channel, threadTs, present);return present;@@ -228,16 +240,12 @@ export function createTurnHandler(deps: {});if (idempotencyKey) {const res = await postWithVerify(client, replyArgs(msg, true) as PostMessageArgs, idempotencyKey);- for (const part of res.parts ?? [{ ts: res.ts, text: msg }]) {- mirrorSelfPost(inc.channel, part.ts, part.text, { sub: replyThreadTs });- }return res.ts;}const parts = blocks ? [msg] : safeChunks(msg, SLACK_POST_SPLIT_LIMIT);let firstTs: string | undefined;for (const [i, part] of parts.entries()) {const ts = (await client.chat.postMessage(replyArgs(part, parts.length === 1))).ts as string | undefined;- mirrorSelfPost(inc.channel, ts, part, { sub: replyThreadTs });if (i === 0) firstTs = ts;}return firstTs;@@ -370,9 +378,7 @@ export function createTurnHandler(deps: {...(metadata ? { metadata } : {}),...botIdentityArgs(),})- .then(() => {- mirrorSelfPost(inc.channel, ts, text, { sub: replyThreadTs, editedAt: Date.now() });- }),+ .then(() => {}),checkpoint: async (ts) => {if (queuedRunId) await core.reportRunEditRef(queuedRunId, ts);},@@ -385,9 +391,7 @@ export function createTurnHandler(deps: {goalNotice = createGoalNoticePresenter({post: (text, blocks) => postReply(text, blocks),update: (ts, text, blocks) =>- client.chat.update({ channel: inc.channel, ts, text, blocks, ...botIdentityArgs() }).then(() => {- mirrorSelfPost(inc.channel, ts, text, { sub: replyThreadTs, editedAt: Date.now() });- }),+ client.chat.update({ channel: inc.channel, ts, text, blocks, ...botIdentityArgs() }).then(() => {}),onError: (error) => console.error("[slack-plugin] goal notice update failed:", (error as Error).message),});}@@ -402,6 +406,7 @@ export function createTurnHandler(deps: {channel: inc.channel,ts: inc.ts,text: inc.rawText,+ files: inc.files,user: inc.userId,thread_ts: inc.threadTs,channel_type: channelType(inc.kind, conversationKind),diff --git a/src/surface-cache/surface-cache.ts b/src/surface-cache/surface-cache.tsindex b5e7c56e9..d3712d0d7 100644--- a/src/surface-cache/surface-cache.ts+++ b/src/surface-cache/surface-cache.ts@@ -115,6 +115,10 @@ export function createPostgresSurfaceCache(ON channel_messages(org_id, container, deleted_at) WHERE deleted_at > 0`,],},+ {+ id: "surface-cache/store/0004",+ statements: [`ALTER TABLE channel_messages ADD COLUMN IF NOT EXISTS broadcast BOOLEAN NOT NULL DEFAULT FALSE`],+ },]);const liveFallback = opts.liveFallback;@@ -124,9 +128,11 @@ export function createPostgresSurfaceCache(container: r.container as string,ts: r.ts as string,...(r.sub != null ? { sub: r.sub as string } : {}),+ ...(r.broadcast ? { broadcast: true } : {}),...(r.author_id != null ? { authorId: r.author_id as string } : {}),...(r.author_name != null ? { authorName: r.author_name as string } : {}),text: (r.text as string) ?? "",+ ...(r.reply_count != null ? { replyCount: Number(r.reply_count) } : {}),...(r.mentions != null ? { mentions: r.mentions as Record<string, string> } : {}),...(r.self ? { self: true } : {}),...(r.bot ? { bot: true } : {}),@@ -152,24 +158,26 @@ export function createPostgresSurfaceCache(const e = normalizeEvent(event);if (!e.container || !e.ts) continue;const res = await client.query(- `INSERT INTO channel_messages(org_id, container, ts, sub, author_id, author_name, text, mentions, self, bot, mentions_self, edited_at, deleted, handled, created_at, deleted_at)- VALUES ($1,$2,$3,$4,$5,$6,$7,$8::jsonb,$9,$10,$11,$12,$13,$14,$15,$16)+ `INSERT INTO channel_messages(org_id, container, ts, sub, author_id, author_name, text, mentions, self, bot, mentions_self, edited_at, deleted, handled, created_at, deleted_at, broadcast)+ VALUES ($1,$2,$3,$4,$5,$6,$7,$8::jsonb,$9,$10,$11,$12,$13,$14,$15,$16,COALESCE($18::boolean, FALSE))ON CONFLICT (org_id, container, ts) DO UPDATE SET- sub = COALESCE(EXCLUDED.sub, channel_messages.sub),- author_id = COALESCE(EXCLUDED.author_id, channel_messages.author_id),- author_name = COALESCE(EXCLUDED.author_name, channel_messages.author_name),- text = CASE WHEN EXCLUDED.deleted OR COALESCE(EXCLUDED.edited_at, 0) < COALESCE(channel_messages.edited_at, 0) THEN channel_messages.text ELSE EXCLUDED.text END,- mentions = CASE WHEN EXCLUDED.deleted OR COALESCE(EXCLUDED.edited_at, 0) < COALESCE(channel_messages.edited_at, 0) THEN channel_messages.mentions ELSE COALESCE(EXCLUDED.mentions, channel_messages.mentions) END,- self = channel_messages.self OR EXCLUDED.self,- bot = channel_messages.bot OR EXCLUDED.bot,- mentions_self = channel_messages.mentions_self OR EXCLUDED.mentions_self,- edited_at = GREATEST(COALESCE(EXCLUDED.edited_at, 0), COALESCE(channel_messages.edited_at, 0)),+ sub = CASE WHEN EXCLUDED.deleted OR channel_messages.deleted OR COALESCE(EXCLUDED.edited_at, 0) < COALESCE(channel_messages.edited_at, 0) OR NOT $17 THEN channel_messages.sub ELSE EXCLUDED.sub END,+ broadcast = CASE WHEN EXCLUDED.deleted OR channel_messages.deleted OR COALESCE(EXCLUDED.edited_at, 0) < COALESCE(channel_messages.edited_at, 0) OR $18::boolean IS NULL THEN channel_messages.broadcast ELSE EXCLUDED.broadcast END,+ author_id = CASE WHEN EXCLUDED.deleted OR channel_messages.deleted OR COALESCE(EXCLUDED.edited_at, 0) < COALESCE(channel_messages.edited_at, 0) THEN channel_messages.author_id ELSE COALESCE(EXCLUDED.author_id, channel_messages.author_id) END,+ author_name = CASE WHEN EXCLUDED.deleted OR channel_messages.deleted OR COALESCE(EXCLUDED.edited_at, 0) < COALESCE(channel_messages.edited_at, 0) THEN channel_messages.author_name ELSE COALESCE(EXCLUDED.author_name, channel_messages.author_name) END,+ text = CASE WHEN EXCLUDED.deleted OR channel_messages.deleted OR COALESCE(EXCLUDED.edited_at, 0) < COALESCE(channel_messages.edited_at, 0) THEN channel_messages.text ELSE EXCLUDED.text END,+ mentions = CASE WHEN EXCLUDED.deleted OR channel_messages.deleted OR COALESCE(EXCLUDED.edited_at, 0) < COALESCE(channel_messages.edited_at, 0) THEN channel_messages.mentions ELSE COALESCE(EXCLUDED.mentions, channel_messages.mentions) END,+ self = channel_messages.self OR (NOT (EXCLUDED.deleted OR channel_messages.deleted OR COALESCE(EXCLUDED.edited_at, 0) < COALESCE(channel_messages.edited_at, 0)) AND EXCLUDED.self),+ bot = channel_messages.bot OR (NOT (EXCLUDED.deleted OR channel_messages.deleted OR COALESCE(EXCLUDED.edited_at, 0) < COALESCE(channel_messages.edited_at, 0)) AND EXCLUDED.bot),+ mentions_self = channel_messages.mentions_self OR (NOT (EXCLUDED.deleted OR channel_messages.deleted OR COALESCE(EXCLUDED.edited_at, 0) < COALESCE(channel_messages.edited_at, 0)) AND EXCLUDED.mentions_self),+ edited_at = CASE WHEN channel_messages.deleted OR EXCLUDED.deleted THEN channel_messages.edited_at ELSE GREATEST(COALESCE(EXCLUDED.edited_at, 0), COALESCE(channel_messages.edited_at, 0)) END,deleted = channel_messages.deleted OR EXCLUDED.deleted,deleted_at = COALESCE(channel_messages.deleted_at, EXCLUDED.deleted_at),handled = channel_messages.handled OR EXCLUDED.handledWHERE EXCLUDED.deletedOR COALESCE(EXCLUDED.edited_at, 0) >= COALESCE(channel_messages.edited_at, 0)- OR EXCLUDED.handled`,+ OR EXCLUDED.handled+ RETURNING NOT deleted AND COALESCE(edited_at, 0) = COALESCE($12::bigint, 0) AS content_accepted`,[orgId,e.container,@@ -187,17 +195,26 @@ export function createPostgresSurfaceCache(e.handled ?? false,e.createdAt ?? now,e.deleted ? now : null,+ e.sub !== undefined,+ e.broadcast ?? null,],);upserted += res.rowCount ?? 0;- for (const f of e.files ?? []) {- if (!f.fileId) continue;- await client.query(- `INSERT INTO channel_files(org_id, container, ts, file_id, name, mimetype, created_at)+ if (res.rows[0]?.content_accepted && e.files !== undefined) {+ await client.query("DELETE FROM channel_files WHERE org_id = $1 AND container = $2 AND ts = $3", [+ orgId,+ e.container,+ e.ts,+ ]);+ for (const f of e.files) {+ if (!f.fileId) continue;+ await client.query(+ `INSERT INTO channel_files(org_id, container, ts, file_id, name, mimetype, created_at)VALUES ($1,$2,$3,$4,$5,$6,$7)ON CONFLICT (org_id, container, ts, file_id) DO UPDATE SET name = EXCLUDED.name, mimetype = EXCLUDED.mimetype`,- [orgId, e.container, e.ts, f.fileId, f.name ?? null, f.mimetype ?? null, e.createdAt ?? now],- );+ [orgId, e.container, e.ts, f.fileId, f.name ?? null, f.mimetype ?? null, e.createdAt ?? now],+ );+ }}await client.query(`INSERT INTO channel_state(org_id, container, last_ts, oldest_ts, name, kind, members, updated_at)@@ -241,7 +258,15 @@ export function createPostgresSurfaceCache(args.push(opts.at);conds.push(`ts = $${args.length}`);}- if (opts.sub) {+ if (opts.timestamps !== undefined) {+ if (opts.timestamps.length > MAX_READ_LIMIT) throw new RangeError("At most 500 message timestamps are allowed");+ if (!opts.timestamps.length) return [];+ args.push(opts.timestamps);+ conds.push(`ts = ANY($${args.length}::text[])`);+ }+ if (opts.channelHistory) conds.push("(sub IS NULL OR broadcast = TRUE)");+ if (opts.sub === null) conds.push("sub IS NULL");+ else if (opts.sub !== undefined) {args.push(opts.sub);conds.push(`sub = $${args.length}`);}@@ -256,10 +281,11 @@ export function createPostgresSurfaceCache(if (!opts.includeDeleted) conds.push("deleted = FALSE");args.push(limit);const rows = await q(- `SELECT channel_messages.*, (SELECT json_agg(json_build_object('fileId', f.file_id, 'name', f.name, 'mimetype', f.mimetype)) FROM channel_files f WHERE f.org_id = channel_messages.org_id AND f.container = channel_messages.container AND f.ts = channel_messages.ts) AS files FROM channel_messages WHERE ${conds.join(" AND ")} ORDER BY ts DESC LIMIT $${args.length}`,+ `SELECT channel_messages.*, (SELECT COUNT(*) FROM channel_messages replies WHERE replies.org_id = channel_messages.org_id AND replies.container = channel_messages.container AND replies.sub = channel_messages.ts AND replies.ts <> channel_messages.ts AND replies.deleted = FALSE) AS reply_count, (SELECT json_agg(json_build_object('fileId', f.file_id, 'name', f.name, 'mimetype', f.mimetype)) FROM channel_files f WHERE f.org_id = channel_messages.org_id AND f.container = channel_messages.container AND f.ts = channel_messages.ts) AS files FROM channel_messages WHERE ${conds.join(" AND ")} ORDER BY ts ${opts.oldestFirst ? "ASC" : "DESC"} LIMIT $${args.length}`,args,);- const hit = rows.map(rowToMessage).reverse();+ const hit = rows.map(rowToMessage);+ if (!opts.oldestFirst) hit.reverse();if (hit.length === 0 && liveFallback && !opts.noFallback && !opts.before) {const live = await liveFallback(container, opts);if (live) return live;@@ -423,11 +449,15 @@ export function createMemorySurfaceCache(opts: { liveFallback?: LiveFallback } =const m = containerMsgs(e.container);const existing = m.get(e.ts);const deleted = (existing?.deleted ?? false) || (e.deleted ?? false);- if (!existing || e.deleted || (e.editedAt ?? 0) >= (existing.editedAt ?? 0)) {+ const accepted = !existing?.deleted && !e.deleted && (e.editedAt ?? 0) >= (existing?.editedAt ?? 0);+ if (accepted || !existing) {m.set(e.ts, {container: e.container,ts: e.ts,- ...((e.sub ?? existing?.sub) ? { sub: (e.sub ?? existing?.sub) as string } : {}),+ ...((e.sub === undefined ? existing?.sub : e.sub)+ ? { sub: (e.sub === undefined ? existing?.sub : e.sub) as string }+ : {}),+ ...((e.broadcast ?? existing?.broadcast) ? { broadcast: true } : {}),...((e.authorId ?? existing?.authorId) ? { authorId: (e.authorId ?? existing?.authorId) as string } : {}),...((e.authorName ?? existing?.authorName)? { authorName: (e.authorName ?? existing?.authorName) as string }@@ -449,24 +479,25 @@ export function createMemorySurfaceCache(opts: { liveFallback?: LiveFallback } =});upserted++;}+ if (existing && e.deleted)+ m.set(e.ts, { ...m.get(e.ts)!, deleted: true, deletedAt: existing.deletedAt ?? now });if (existing && e.handled && !existing.handled) m.set(e.ts, { ...m.get(e.ts)!, handled: true });- if (e.files?.length) {+ if (accepted && e.files !== undefined) {const k = key(e.container);- const arr = files.get(k) ?? [];- for (const f of e.files) {- if (!f.fileId) continue;- if (!arr.some((x) => x.ts === e.ts && x.fileId === f.fileId)) {- arr.push({- container: e.container,- ts: e.ts,- fileId: f.fileId,- ...(f.name ? { name: f.name } : {}),- ...(f.mimetype ? { mimetype: f.mimetype } : {}),- createdAt: e.createdAt ?? now,- });- }- }- files.set(k, arr);+ const attached = new Map(+ e.files+ .filter((f) => f.fileId)+ .map((f) => [+ f.fileId,+ {+ container: e.container,+ ts: e.ts,+ ...f,+ createdAt: e.createdAt ?? now,+ },+ ]),+ );+ files.set(k, [...(files.get(k) ?? []).filter((f) => f.ts !== e.ts), ...attached.values()]);}const k = key(e.container);const st = state.get(k) ?? { container: e.container, members: [], updatedAt: now };@@ -492,16 +523,30 @@ export function createMemorySurfaceCache(opts: { liveFallback?: LiveFallback } =const limit = clampLimit(o.limit, DEFAULT_READ_LIMIT);let all = [...containerMsgs(container).values()];if (o.at) all = all.filter((x) => x.ts === o.at);- if (o.sub) all = all.filter((x) => x.sub === o.sub);+ if (o.timestamps !== undefined) {+ if (o.timestamps.length > MAX_READ_LIMIT) throw new RangeError("At most 500 message timestamps are allowed");+ if (!o.timestamps.length) return [];+ const selected = new Set(o.timestamps);+ all = all.filter((x) => selected.has(x.ts));+ }+ if (o.channelHistory) all = all.filter((x) => x.sub === undefined || x.broadcast);+ if (o.sub === null) all = all.filter((x) => x.sub === undefined);+ else if (o.sub !== undefined) all = all.filter((x) => x.sub === o.sub);if (o.after) all = all.filter((x) => x.ts > o.after!);if (o.before) all = all.filter((x) => x.ts < o.before!);if (!o.includeDeleted) all = all.filter((x) => !x.deleted);all.sort(compareTs);- const hit = all.slice(-limit).map((m) => {+ const hit = (o.oldestFirst ? all.slice(0, limit) : all.slice(-limit)).map((m) => {const attached = (files.get(key(container)) ?? []).filter((f) => f.ts === m.ts);- return attached.length- ? { ...m, files: attached.map(({ fileId, name, mimetype }) => ({ fileId, name, mimetype })) }- : m;+ return {+ ...m,+ replyCount: [...containerMsgs(container).values()].filter(+ (reply) => reply.sub === m.ts && reply.ts !== m.ts && !reply.deleted,+ ).length,+ ...(attached.length+ ? { files: attached.map(({ fileId, name, mimetype }) => ({ fileId, name, mimetype })) }+ : {}),+ };});if (hit.length === 0 && liveFallback && !o.noFallback && !o.before) {const live = await liveFallback(container, o);diff --git a/src/surface-cache/types.ts b/src/surface-cache/types.tsindex 3f82c9050..07e481a6f 100644--- a/src/surface-cache/types.ts+++ b/src/surface-cache/types.ts@@ -2,9 +2,11 @@ export interface CachedMessage {container: string;ts: string;sub?: string;+ broadcast?: boolean;authorId?: string;authorName?: string;text: string;+ replyCount?: number;files?: Array<{ fileId: string; name?: string; mimetype?: string }>;mentions?: Record<string, string>;self?: boolean;@@ -46,7 +48,8 @@ export interface ActiveThread {export interface IngestEvent {container: string;ts: string;- sub?: string;+ sub?: string | null;+ broadcast?: boolean;authorId?: string;authorName?: string;text?: string;@@ -71,7 +74,10 @@ export interface ContainerSummary extends ContainerState {export interface ReadMessagesOpts {at?: string;- sub?: string;+ sub?: string | null;+ timestamps?: string[];+ oldestFirst?: boolean;+ channelHistory?: boolean;limit?: number;after?: string;before?: string;diff --git a/test/postgres-surface-cache.test.ts b/test/postgres-surface-cache.test.tsindex eb7a75efb..bfdcb314b 100644--- a/test/postgres-surface-cache.test.ts+++ b/test/postgres-surface-cache.test.ts@@ -303,3 +303,141 @@ test("pg mirror reads sanitize NUL, retain files and preserve newer text on a haawait cache.close();}});++test("cache revisions preserve attachments and parent against stale handled events", { skip }, async () => {+ const cache = createPostgresSurfaceCache(URL!);+ try {+ const base = { container: "CSNAPSHOT", ts: "2.0" };+ await cache.ingest([{ ...base, sub: "1.0", text: "latest", editedAt: 20, files: [{ fileId: "F1", name: "one" }] }]);+ await cache.ingest([+ { ...base, sub: "wrong", text: "stale", editedAt: 10, handled: true, files: [{ fileId: "F2" }] },+ ]);+ let [message] = await cache.readMessages(base.container, { at: base.ts });+ assert.equal(message?.text, "latest");+ assert.equal(message?.sub, "1.0");+ assert.equal(message?.handled, true);+ assert.deepEqual(+ message?.files?.map((f) => f.fileId),+ ["F1"],+ );+ await cache.ingest([{ ...base, sub: null, text: "root corrected", editedAt: 30 }]);+ [message] = await cache.readMessages(base.container, { at: base.ts });+ assert.equal(message?.sub, undefined);+ assert.deepEqual(+ message?.files?.map((f) => f.fileId),+ ["F1"],+ );+ await cache.ingest([{ ...base, text: "replacement", editedAt: 40, files: [{ fileId: "F2", name: "renamed" }] }]);+ [message] = await cache.readMessages(base.container, { at: base.ts });+ assert.equal(message?.sub, undefined);+ assert.deepEqual(+ message?.files?.map((f) => [f.fileId, f.name]),+ [["F2", "renamed"]],+ );+ await cache.ingest([{ ...base, text: "empty", editedAt: 50, files: [] }]);+ await cache.ingest([{ ...base, text: "stale", editedAt: 40, files: [{ fileId: "F2" }] }]);+ [message] = await cache.readMessages(base.container, { at: base.ts });+ assert.equal(message?.text, "empty");+ assert.equal(message?.files?.length ?? 0, 0);+ await cache.ingest([{ ...base, deleted: true }]);+ await cache.ingest([{ ...base, sub: "wrong", text: "revive", editedAt: 60, files: [{ fileId: "F3" }] }]);+ [message] = await cache.readMessages(base.container, { at: base.ts, includeDeleted: true });+ assert.equal(message?.deleted, true);+ assert.equal(message?.text, "empty");+ assert.equal(message?.sub, undefined);+ assert.equal(message?.files?.length ?? 0, 0);+ } finally {+ await cache.close();+ }+});++test("cache selects exact timestamps and oldest pages with live reply counts", { skip }, async () => {+ const cache = createPostgresSurfaceCache(URL!);+ try {+ const container = "CSELECT";+ await cache.ingest([+ { container, ts: "1.0", sub: null, text: "first" },+ { container, ts: "2.0", sub: "1.0", text: "reply" },+ { container, ts: "3.0", sub: "1.0", text: "deleted reply", deleted: true },+ { container, ts: "4.0", sub: null, text: "second root" },+ { container: "OTHER", ts: "5.0", sub: "1.0", text: "other container" },+ ]);+ assert.deepEqual(+ (await cache.readMessages(container, { timestamps: ["4.0", "1.0", "missing"] })).map((m) => m.ts),+ ["1.0", "4.0"],+ );+ assert.deepEqual(await cache.readMessages(container, { timestamps: [] }), []);+ await assert.rejects(cache.readMessages(container, { timestamps: Array(501).fill("1.0") }), /500/);+ const [oldest] = await cache.readMessages(container, { sub: null, oldestFirst: true, limit: 1 });+ assert.equal(oldest?.ts, "1.0");+ assert.equal(oldest?.replyCount, 1);+ assert.deepEqual(+ (await cache.readMessages(container, { sub: null, limit: 1 })).map((m) => m.ts),+ ["4.0"],+ );+ assert.deepEqual(+ (await cache.readMessages(container, { sub: "1.0", oldestFirst: true })).map((m) => m.ts),+ ["2.0"],+ );+ await cache.ingest([{ container, ts: "2.0", sub: null, text: "corrected" }]);+ assert.equal((await cache.readMessages(container, { at: "1.0" }))[0]?.replyCount, 0);+ } finally {+ await cache.close();+ }+});++test("pg attachment snapshots roll back with a failed ingestion transaction", { skip }, async () => {+ const cache = createPostgresSurfaceCache(URL!);+ try {+ const base = { container: "CATOMIC", ts: "1.0" };+ await cache.ingest([{ ...base, text: "original", files: [{ fileId: "F1" }], editedAt: 10 }]);+ await assert.rejects(+ cache.ingest([+ { ...base, text: "replacement", files: [], editedAt: 20 },+ { container: base.container, ts: "invalid timestamp", text: "invalid" },+ ]),+ );+ const [message] = await cache.readMessages(base.container, { at: base.ts });+ assert.equal(message?.text, "original");+ assert.deepEqual(+ message?.files?.map((f) => f.fileId),+ ["F1"],+ );+ } finally {+ await cache.close();+ }+});++test("channel history includes broadcasts while exact roots exclude them", { skip }, async () => {+ const cache = createPostgresSurfaceCache(URL!);+ try {+ const container = "CBROADCAST";+ await cache.ingest([+ { container, ts: "1.0", sub: null, text: "root" },+ { container, ts: "2.0", sub: "1.0", text: "ordinary reply" },+ { container, ts: "3.0", sub: "1.0", text: "broadcast", broadcast: true, editedAt: 20 },+ ]);+ await cache.ingest([+ { container, ts: "3.0", sub: "1.0", text: "stale", broadcast: false, editedAt: 10, handled: true },+ ]);+ await cache.ingest([{ container, ts: "3.0", sub: "1.0", text: "edit without subtype", editedAt: 30 }]);+ assert.deepEqual(+ (await cache.readMessages(container, { channelHistory: true })).map((m) => m.ts),+ ["1.0", "3.0"],+ );+ assert.deepEqual(+ (await cache.readMessages(container, { sub: null })).map((m) => m.ts),+ ["1.0"],+ );+ assert.equal((await cache.readMessages(container, { at: "3.0" }))[0]?.broadcast, true);+ await cache.ingest([+ { container, ts: "3.0", sub: "1.0", text: "corrected subtype", broadcast: false, editedAt: 40 },+ ]);+ assert.deepEqual(+ (await cache.readMessages(container, { channelHistory: true })).map((m) => m.ts),+ ["1.0"],+ );+ } finally {+ await cache.close();+ }+});diff --git a/test/slack-deliveries.test.ts b/test/slack-deliveries.test.tsindex e1527aaa4..c85d2a39e 100644--- a/test/slack-deliveries.test.ts+++ b/test/slack-deliveries.test.ts@@ -33,7 +33,6 @@ async function deliver(const acknowledgements: string[] = [];const uploads: Record<string, unknown>[] = [];const posts: Record<string, unknown>[] = [];- const mirrors: Array<{ ts?: string; text: string }> = [];const marks: Array<{ channel: string; ts: string }> = [];const probes: Record<string, unknown>[] = [];const history = row.history ?? [];@@ -78,15 +77,12 @@ async function deliver(fetchBlobFromCore: async (id: string) => Buffer.from(id),fetchFileArtifactFromCore: async () => Buffer.from("artifact"),} as never,- mirror: {- mirrorSelfPost: (_channel: string, ts: string | undefined, text: string) => void mirrors.push({ ts, text }),- } as never,threads: { mark: (channel: string, ts: string) => void marks.push({ channel, ts }) } as never,clientForIdentity: () => client,});await poller.pollDeliveries(client);- return { acknowledgements, uploads, posts, mirrors, marks, probes };+ return { acknowledgements, uploads, posts, marks, probes };}for (const type of ["slack", "group", "principal"]) {@@ -141,7 +137,7 @@ test("cron deliveries omit settings when the web UI is unavailable", async () =>for (const type of ["slack", "group", "principal"]) {test(`${type} deliveries mark text for recovery and batch mixed attachments`, async () => {- const { acknowledgements, uploads, posts, mirrors, marks } = await deliver({ type });+ const { acknowledgements, uploads, posts, marks } = await deliver({ type });assert.equal(uploads.length, 1);assert.equal(posts.length, 1);@@ -154,7 +150,6 @@ for (const type of ["slack", "group", "principal"]) {assert.equal(uploads[0]!.initial_comment, undefined);assert.deepEqual(uploadedNames(uploads), ["first.png", "second.jpg", "notes.pdf"]);assert.deepEqual(acknowledgements, ["D1"]);- assert.deepEqual(mirrors, [{ ts: "separate-message", text: "two screenshots and the notes" }]);assert.deepEqual(marks, type === "principal" ? [] : [{ channel: "C1", ts: "100.200" }]);});@@ -260,14 +255,7 @@ for (const type of ["group", "principal"]) {for (const type of ["group", "principal"]) {test(`${type} long relays split within Slack's block limit and keep the footer last`, async () => {const text = "x".repeat(145_000);- const { posts, mirrors } = await deliver({ type, relaySender: "josh" }, undefined, undefined, text);- assert.equal(- mirrors- .map((mirror) => mirror.text)- .join("")- .replaceAll("\n", ""),- text,- );+ const { posts } = await deliver({ type, relaySender: "josh" }, undefined, undefined, text);assert.equal(posts.length, 2);const blocks = posts.flatMap((post) => {const batch = post.blocks as Array<{ type: string; text?: { text: string }; elements?: unknown[] }>;diff --git a/test/slack-delivery-claim-race.test.ts b/test/slack-delivery-claim-race.test.tsindex dc190dd75..150fd331c 100644--- a/test/slack-delivery-claim-race.test.ts+++ b/test/slack-delivery-claim-race.test.ts@@ -68,7 +68,6 @@ function harness() {},} as never,flow: { inFlightRuns: { add() {}, delete() {}, has: () => false } } as never,- mirror: { mirrorSelfPost() {} } as never,threads: createThreadTracker(),clientForIdentity: () => makeClient("identity"),claimMs: CLAIM_MS,@@ -142,7 +141,6 @@ test("a transient claim failure at re-claim time does not strand an owned row",holdDeliveryDispatch: (fn: (lost: Promise<void>) => Promise<unknown>) => fn(new Promise<void>(() => {})),} as never,flow: { inFlightRuns: { add() {}, delete() {}, has: () => false } } as never,- mirror: { mirrorSelfPost() {} } as never,threads: createThreadTracker(),clientForIdentity: () => makeClient("identity"),claimMs: CLAIM_MS,@@ -190,7 +188,6 @@ test("with a shared dispatch lease, a second relay never posts at all (single diholdDeliveryDispatch: lease,} as never,flow: { inFlightRuns: { add() {}, delete() {}, has: () => false } } as never,- mirror: { mirrorSelfPost() {} } as never,threads: createThreadTracker(),clientForIdentity: () => makeClient("identity"),claimMs: CLAIM_MS,@@ -228,7 +225,6 @@ test("lease loss mid-drain stops posting; rows recover via the claim TTL", asyncholdDeliveryDispatch: (fn: (lost: Promise<void>) => Promise<unknown>) => fn(lostPromise),} as never,flow: { inFlightRuns: { add() {}, delete() {}, has: () => false } } as never,- mirror: { mirrorSelfPost() {} } as never,threads: createThreadTracker(),clientForIdentity: () => makeClient("identity"),claimMs: CLAIM_MS,diff --git a/test/slack-mirror-context.test.ts b/test/slack-mirror-context.test.tsindex 1e9bd8f31..fc6a52135 100644--- a/test/slack-mirror-context.test.ts+++ b/test/slack-mirror-context.test.ts@@ -272,3 +272,26 @@ test("surface context keeps a successful channel page when an empty thread is thassert.match(outcome.result.note, /60/);assert.match(outcome.result.note, /setup=slack/);});++test("deleted messages do not consume context page slots or reappear through fallback", async () => {+ const { cache, readHistory, client } = fixture();+ const ts = (n: number) => String(n).padStart(6, "0");+ await cache.ingest(Array.from({ length: 205 }, (_, i) => ({ container: "C1", ts: ts(i), text: "message" })));+ await cache.ingest([{ container: "C1", ts: ts(204), deleted: true }]);+ const page = await readHistory(client, "C1");+ assert.equal(page.raw.length, 200);+ assert.equal(page.raw[0]?.ts, ts(4));+ assert.equal(page.raw.at(-1)?.ts, ts(203));+ await cache.ingest([{ container: "C2", ts: "2.0", sub: "1.0", deleted: true }]);+ client.conversations.replies = async () =>+ ({+ messages: [+ { ts: "1.0", text: "parent" },+ { ts: "2.0", thread_ts: "1.0", text: "deleted reply" },+ ],+ }) as never;+ assert.deepEqual(+ (await readHistory(client, "C2", "1.0")).raw.map((m) => m.ts),+ ["1.0"],+ );+});diff --git a/test/slack-mirror-ingestion.test.ts b/test/slack-mirror-ingestion.test.tsnew file mode 100644index 000000000..8ba5331be--- /dev/null+++ b/test/slack-mirror-ingestion.test.ts@@ -0,0 +1,444 @@+import { test } from "node:test";+import assert from "node:assert/strict";+import bolt from "@slack/bolt";+import { createMirror } from "../src/slack/mirror.ts";+import { registerSlackEvents } from "../src/slack/events.ts";+import { createDirectory, type BotIdentity } from "../src/slack/directory.ts";+import { createTurnHandler, type TurnHandler } from "../src/slack/turn-handler.ts";+import { createSlackHistoryReader } from "../src/slack/history.ts";+import { createMemorySurfaceCache } from "../src/surface-cache/surface-cache.ts";+import { createDeduper, createThreadTracker } from "../src/slack/lib.ts";+import { createDeferredEnvelopeAck } from "../src/slack/deferred-ack.ts";++const ids: BotIdentity = {+ botUserId: "UBOT",+ ownBotId: "BBOT",+ ownTeamId: "T1",+ botHandle: "qm",+ ownWorkspaceUrl: "",+ identityMode: "slack-id",+};++function fixture(+ options: {+ ingest?: (events: any[]) => Promise<void>;+ external?: boolean;+ directory?: any;+ stake?: TurnHandler["botHasStakeInThread"];+ } = {},+) {+ const events: any[] = [];+ const dispatches: any[] = [];+ const directory = options.directory ?? {+ getChannelInfo: async () => ({ id: "C1" }),+ allInternalRosters: async () =>+ new Map([+ ["C1", []],+ ["D1", []],+ ]),+ classifyUserCached: async (_client: unknown, id: string) => ({+ ok: true,+ actor: { externalId: id, displayName: "Teammate" },+ }),+ };+ const mirror = createMirror({+ core: {+ ingestSurfaceEvents:+ options.ingest ??+ (async (batch: any[]) => {+ events.push(...batch);+ }),+ } as any,+ ids,+ directory,+ externalParticipantsEnabled: async () => options.external ?? false,+ });+ const app = new bolt.App({+ receiver: { init() {}, async start() {}, async stop() {} } as any,+ authorize: async () => ({+ botToken: "xoxb-test",+ botId: ids.ownBotId,+ botUserId: ids.botUserId,+ teamId: ids.ownTeamId,+ }),+ ignoreSelf: false,+ });+ app.error(async () => {});+ registerSlackEvents(app, {+ ids,+ mirror,+ directory,+ deduper: createDeduper(),+ handler: {+ dispatch: async (...args: any[]) => {+ dispatches.push(args);+ },+ botHasStakeInThread: options.stake ?? (async () => false),+ handleReactionEvent: async (...args: any[]) => {+ dispatches.push(args);+ },+ } as any,+ });+ async function fire(event: Record<string, unknown>, gate?: ReturnType<typeof createDeferredEnvelopeAck>) {+ await app.processEvent({+ body: { type: "event_callback", team_id: "T1", event_id: "Ev1", event },+ ack: gate?.ack ?? (async () => {}),+ customProperties: { ackGate: gate?.gate },+ });+ gate?.gate.persisted();+ }+ return { mirror, events, dispatches, fire };+}++test("real Bolt ingests own channel/DM messages and edits without responses or self reactions", async () => {+ const f = fixture();+ for (const channel of ["C1", "D1"]) {+ const base = {+ type: "message",+ channel,+ channel_type: channel === "D1" ? "im" : "channel",+ ts: "2.000001",+ thread_ts: "1.000001",+ user: "UBOT",+ bot_id: "BBOT",+ subtype: "bot_message",+ text: "reply",+ files: [{ id: "F1", name: "report" }],+ };+ await f.fire(base);+ await f.fire({+ type: "message",+ channel,+ channel_type: base.channel_type,+ subtype: "message_changed",+ message: { ...base, text: "edited", files: [], edited: { ts: "3.000001" } },+ previous_message: base,+ });+ }+ await f.fire({ type: "app_mention", user: "UBOT", bot_id: "BBOT", channel: "C1", ts: "4", text: "<@UBOT>" });+ await f.fire({+ type: "reaction_added",+ user: "UBOT",+ reaction: "eyes",+ item: { type: "message", channel: "C1", ts: "4" },+ });+ assert.equal(f.events.length, 4);+ assert.equal(f.dispatches.length, 0);+ assert.ok(f.events.every((e) => e.self && e.handled && e.sub === "1.000001"));+ assert.equal(f.events[1].editedAt, 3000);+ assert.deepEqual(f.events[1].files, []);+ assert.equal(f.events[0].files[0].fileId, "F1");+});++test("canonical root snapshots clear parent", async () => {+ const f = fixture();+ await f.fire({+ type: "message",+ channel: "C1",+ channel_type: "channel",+ user: "UBOT",+ ts: "2",+ thread_ts: "2",+ text: "canonical",+ });+ assert.equal(f.events.length, 1);+ assert.equal(f.events[0].sub, null);+ assert.equal(f.events[0].text, "canonical");+});++test("actual Bolt swallowed listener errors still withhold ack and preserve staged replay", async () => {+ let fail = true;+ let acknowledged = 0;+ let withheld = 0;+ let cleared = 0;+ const f = fixture({+ ingest: async () => {+ if (fail) throw new Error("database unavailable");+ },+ });+ const event = { type: "message", channel: "C1", channel_type: "channel", user: "UBOT", ts: "2", text: "reply" };+ const gate = createDeferredEnvelopeAck(+ async () => {+ acknowledged++;+ },+ {+ gated: true,+ onWithhold: () => {+ withheld++;+ },+ staging: {+ stage: async () => true,+ accepted: () => {+ cleared++;+ },+ },+ },+ );+ await f.fire(event, gate);+ assert.equal(acknowledged, 0);+ assert.equal(withheld, 1);+ assert.equal(cleared, 0);+ fail = false;+ const retry = createDeferredEnvelopeAck(+ async () => {+ acknowledged++;+ },+ { gated: true },+ );+ await f.fire(event, retry);+ assert.equal(acknowledged, 1);+});++test("unavailable room authorization retries; genuine room denial never ingests", async () => {+ for (const unavailable of [true, false]) {+ let withheld = 0;+ const f = fixture({+ directory: {+ getChannelInfo: async () => (unavailable ? undefined : {}),+ allInternalRosters: async () => new Map(),+ },+ });+ const gate = createDeferredEnvelopeAck(async () => {}, {+ gated: true,+ onWithhold: () => {+ withheld++;+ },+ });+ await f.fire(+ { type: "message", channel: "C1", channel_type: "channel", user: "UBOT", ts: "2", text: "reply" },+ gate,+ );+ assert.equal(f.events.length, 0);+ assert.equal(withheld, Number(unavailable));+ }+});++test("strict directory roster distinguishes unavailable members from denied rooms", async () => {+ const directory = createDirectory({ core: {} as any, ids });+ const client = {+ conversations: { members: {} },+ paginate: async function* () {+ yield await Promise.reject(new Error("rate limited"));+ },+ };+ await assert.rejects(+ directory.allInternalRosters(client, [{ id: "C1" }], {+ plural: "rooms",+ authz: "mirror",+ item: "room",+ requireComplete: true,+ }),+ /rate limited/,+ );+});++test("late ingestion failure keeps an already staged envelope for replay", async () => {+ let acknowledged = 0;+ let staged = 0;+ let cleared = 0;+ const f = fixture({+ ingest: async () => {+ await new Promise((resolve) => setTimeout(resolve, 20));+ throw new Error("database unavailable");+ },+ });+ const gate = createDeferredEnvelopeAck(+ async () => {+ acknowledged++;+ },+ {+ gated: true,+ capMs: 1,+ staging: {+ stage: async () => {+ staged++;+ return true;+ },+ accepted: () => {+ cleared++;+ },+ },+ },+ );+ await f.fire({ type: "message", channel: "C1", channel_type: "channel", user: "UBOT", ts: "2", text: "reply" }, gate);+ assert.equal(staged, 1);+ assert.equal(acknowledged, 1);+ assert.equal(cleared, 0);+});++test("self message deletions reach the mirror without dispatch", async () => {+ const f = fixture();+ await f.fire({+ type: "message",+ subtype: "message_deleted",+ channel: "D1",+ channel_type: "im",+ deleted_ts: "2",+ previous_message: { user: "UBOT", bot_id: "BBOT", thread_ts: "1" },+ });+ assert.deepEqual(f.events, [{ container: "D1", ts: "2", deleted: true, sub: "1", self: true }]);+ assert.equal(f.dispatches.length, 0);+});++test("strict roster rejects incomplete user classification rather than treating it as denied", async () => {+ const directory = createDirectory({ core: {} as any, ids });+ const client = {+ conversations: { members: {} },+ users: {+ info: async () => {+ throw new Error("unavailable");+ },+ },+ paginate: async function* () {+ yield { members: ["U1"] };+ },+ };+ await assert.rejects(+ directory.allInternalRosters(client, [{ id: "C1" }], {+ plural: "rooms",+ authz: "mirror",+ item: "room",+ requireComplete: true,+ }),+ /classification unavailable/,+ );+});++test("file-only changes keep Slack edit version and missing edit versions use envelope time", async () => {+ const f = fixture();+ const message = { user: "UBOT", bot_id: "BBOT", ts: "2", text: "unchanged", edited: { ts: "3.500" }, files: [] };+ await f.fire({+ type: "message",+ subtype: "message_changed",+ channel: "C1",+ channel_type: "channel",+ ts: "4",+ message,+ previous_message: { text: "unchanged" },+ });+ assert.equal(f.events[0].editedAt, 3500);+ assert.deepEqual(f.events[0].files, []);+ await f.fire({+ type: "message",+ subtype: "message_changed",+ channel: "C1",+ channel_type: "channel",+ ts: "5.500",+ message: { ...message, edited: undefined, text: "changed" },+ previous_message: { text: "unchanged" },+ });+ assert.equal(f.events[1].editedAt, 5500);+});++test("thread broadcast snapshots retain broadcast membership through metadata updates", async () => {+ const f = fixture();+ await f.fire({+ type: "message",+ subtype: "thread_broadcast",+ channel: "C1",+ channel_type: "channel",+ user: "UBOT",+ ts: "2",+ thread_ts: "1",+ text: "reply",+ });+ assert.equal(f.events[0].broadcast, true);+ await f.fire({+ type: "message",+ subtype: "message_changed",+ channel: "C1",+ channel_type: "channel",+ ts: "3",+ message: { user: "UBOT", ts: "2", thread_ts: "1", text: "edited" },+ previous_message: { text: "reply" },+ });+ assert.equal(f.events[1].broadcast, undefined);+});++test("real message handler checks prior stake before ingesting the current reply without a shadow miss", async (t) => {+ const cache = createMemorySurfaceCache();+ await cache.ingest([+ { container: "C1", ts: "1.000001", text: "root", authorId: "U1" },+ { container: "C1", ts: "2.000001", sub: "1.000001", text: "prior reply", authorId: "UBOT", self: true },+ ]);+ const calls: any[] = [];+ const records: any[] = [];+ t.mock.method(console, "info", (text: string) => {+ records.push(JSON.parse(text));+ });+ const currentTs = "3.000001";+ const client = {+ conversations: {+ replies: async (args: any) => {+ calls.push(args);+ assert.deepEqual(args, { channel: "C1", ts: "1.000001", limit: 200, latest: currentTs, inclusive: false });+ assert.equal((await cache.readMessages("C1", { at: currentTs })).length, 0);+ return {+ messages: [+ { ts: "1.000001", user: "U1", text: "root" },+ { ts: "2.000001", thread_ts: "1.000001", user: "UBOT", text: "prior reply" },+ ],+ has_more: false,+ };+ },+ },+ };+ const reader = createSlackHistoryReader({+ source: "shadow",+ ids,+ core: { readSurfaceMessages: (channel: string, opts: any) => cache.readMessages(channel, opts) } as any,+ historyClient: client as never,+ });+ const threads = createThreadTracker();+ const handler = createTurnHandler({ directory: {}, mirror: {}, flow: {}, ids, threads, readHistory: reader } as any);+ const f = fixture({+ stake: handler.botHasStakeInThread,+ ingest: async (events) => {+ await cache.ingest(events);+ },+ });+ await f.fire({+ type: "message",+ channel: "C1",+ channel_type: "channel",+ user: "U1",+ ts: currentTs,+ thread_ts: "1.000001",+ text: "follow-up",+ });+ await new Promise((resolve) => setImmediate(resolve));+ assert.equal(f.dispatches.length, 1);+ assert.equal(calls.length, 1);+ assert.equal(records.length, 1);+ assert.equal(records[0].liveMessages, 2);+ assert.equal(records[0].matchingMessages, 2);+ assert.equal(records[0].liveMessagesMissingFromStorage, 0);+ assert.equal(records[0].liveMessagesMissingFromMirror, 0);+ assert.equal(await handler.botHasStakeInThread(client, "C1", "1.000001", "4.000001"), true);+ assert.equal(calls.length, 1);+});++test("stake fallback bounds Slack replies while omitted cutoff and negative tracking remain unchanged", async () => {+ const calls: any[] = [];+ const client = {+ conversations: {+ replies: async (args: any) => {+ calls.push(args);+ return { messages: [] };+ },+ },+ };+ const handler = createTurnHandler({+ directory: {},+ mirror: {},+ flow: {},+ ids,+ threads: createThreadTracker(),+ } as any);+ assert.equal(await handler.botHasStakeInThread(client, "C1", "1", "3"), false);+ assert.deepEqual(calls[0], { channel: "C1", ts: "1", limit: 200, latest: "3", inclusive: false });+ assert.equal(await handler.botHasStakeInThread(client, "C1", "1", "4"), false);+ assert.equal(calls.length, 1);+ assert.equal(await handler.botHasStakeInThread(client, "C1", "5"), false);+ assert.deepEqual(calls[1], { channel: "C1", ts: "5", limit: 200 });+});diff --git a/test/slack-mirror-soak.test.ts b/test/slack-mirror-soak.test.tsindex c77fc735d..aca0cb33c 100644--- a/test/slack-mirror-soak.test.ts+++ b/test/slack-mirror-soak.test.ts@@ -158,3 +158,145 @@ test("secondary Slack accounts inherit the explicitly selected shadow mode", ()});assert.equal(account?.contextSource, "shadow");});++test("shadow distinguishes stored messages with wrong parents from ingestion loss", async (t) => {+ const { createMemorySurfaceCache } = await import("../src/surface-cache/surface-cache.ts");+ const cache = createMemorySurfaceCache();+ await cache.ingest([+ { container: "C1", ts: "1", text: "root" },+ { container: "C1", ts: "2", sub: "wrong", text: "reply" },+ ]);+ const logs: string[] = [];+ t.mock.method(console, "info", (line: string) => logs.push(line));+ const reader = createSlackHistoryReader({+ ids,+ source: "shadow",+ core: {+ readSurfaceMessages: cache.readMessages,+ rememberSurfaceHistory: async () => {+ throw new Error("shadow must never repair what it measures");+ },+ } as unknown as SlackCoreClient,+ });+ await reader(+ {+ conversations: {+ replies: async () => ({+ messages: [+ { ts: "1", text: "root" },+ { ts: "2", thread_ts: "1", text: "reply" },+ { ts: "3", thread_ts: "1", text: "absent" },+ ],+ }),+ },+ },+ "C1",+ "1",+ );+ await new Promise((resolve) => setImmediate(resolve));+ const result = JSON.parse(logs[0]!);+ assert.equal(result.liveMessagesMissingFromStorage, 1);+ assert.equal(result.liveMessagesMissingFromMirror, 2);+ assert.equal(result.threadParentMismatches, 1);+ assert.equal(result.storedMessages, 2);+ assert.equal(result.matchingMessages, 1);+});++test("shadow normalizes mentions without erasing literal entity or attachment differences", async (t) => {+ const { createMemorySurfaceCache } = await import("../src/surface-cache/surface-cache.ts");+ const cache = createMemorySurfaceCache();+ await cache.ingest([+ { container: "C1", ts: "1", text: "Hi <@U1> <", mentions: { U1: "Alice" } },+ { container: "C1", ts: "2", text: "<" },+ { container: "C1", ts: "3", text: "file", files: [{ fileId: "old" }] },+ ]);+ const logs: string[] = [];+ t.mock.method(console, "info", (line: string) => logs.push(line));+ const reader = createSlackHistoryReader({+ ids,+ source: "shadow",+ core: { readSurfaceMessages: cache.readMessages } as unknown as SlackCoreClient,+ });+ await reader(+ {+ conversations: {+ history: async () => ({+ messages: [+ { ts: "3", text: "file", files: [{ id: "new" }] },+ { ts: "2", text: "&lt;" },+ { ts: "1", text: "Hi <@U1> &lt;" },+ ],+ }),+ },+ },+ "C1",+ );+ await new Promise((resolve) => setImmediate(resolve));+ const result = JSON.parse(logs[0]!);+ assert.equal(result.textMismatches, 1);+ assert.equal(result.fileMismatches, 1);+ assert.equal(result.matchingMessages, 1);+ assert.equal(result.liveMessagesMissingFromStorage, 0);+});++test("mirror selects channel roots and expands five recent threads with Slack page ordering", async () => {+ const { createMemorySurfaceCache } = await import("../src/surface-cache/surface-cache.ts");+ const cache = createMemorySurfaceCache();+ const ts = (n: number) => String(n).padStart(6, "0");+ await cache.ingest(Array.from({ length: 205 }, (_, i) => ({ container: "C1", ts: ts(i), text: "root" })));+ await cache.ingest(+ Array.from({ length: 250 }, (_, i) => ({ container: "C1", ts: ts(300 + i), sub: ts(204), text: "reply" })),+ );+ const read = createSlackHistoryReader({+ ids,+ source: "mirror",+ core: { readSurfaceMessages: cache.readMessages } as unknown as SlackCoreClient,+ });+ const roots = await read({}, "C1");+ assert.equal(roots.raw.length, 200);+ assert.equal(roots.raw[0]?.ts, ts(5));+ assert.equal(roots.raw.at(-1)?.ts, ts(204));+ 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(498));+ const expanded = await read({}, "C1", undefined, undefined, true);+ assert.equal(expanded.raw.length, 399);+ assert.equal(expanded.raw.at(-1)?.ts, ts(498));+});++test("shadow never certifies failed or truncated live thread expansion as complete", async (t) => {+ const { createMemorySurfaceCache } = await import("../src/surface-cache/surface-cache.ts");+ const cache = createMemorySurfaceCache();+ await cache.ingest([{ container: "C1", ts: "1", text: "root" }]);+ const logs: string[] = [];+ t.mock.method(console, "info", (line: string) => logs.push(line));+ for (const fail of [true, false]) {+ const reader = createSlackHistoryReader({+ ids,+ source: "shadow",+ core: { readSurfaceMessages: cache.readMessages } as unknown as SlackCoreClient,+ });+ await reader(+ {+ conversations: {+ history: async () => ({ messages: [{ ts: "1", text: "root", reply_count: 1 }] }),+ replies: async () => {+ if (fail) throw new Error("rate limited");+ return { messages: [{ ts: "1", text: "root" }], has_more: true };+ },+ },+ },+ "C1",+ undefined,+ undefined,+ true,+ );+ await new Promise((resolve) => setImmediate(resolve));+ const result = JSON.parse(logs.at(-1)!);+ assert.equal(result.matchingMessages, 1);+ assert.equal(result.liveComplete, false);+ assert.equal(result.liveExpansionFailures, fail ? 1 : 0);+ assert.equal(result.liveTruncatedExpansions, fail ? 0 : 1);+ }+});diff --git a/test/slack-principal-thread-delivery.test.ts b/test/slack-principal-thread-delivery.test.tsindex 453ff3f3d..32b976b08 100644--- a/test/slack-principal-thread-delivery.test.ts+++ b/test/slack-principal-thread-delivery.test.ts@@ -36,7 +36,6 @@ test("a threaded principal delivery posts and records the DM thread", async () =ackDelivery: async (id: string, body: unknown) => void acks.push({ id, body }),} as any,flow: { inFlightRuns: { add() {}, delete() {}, has: () => false } } as never,- mirror: { mirrorSelfPost: () => undefined } as any,threads: { mark: () => undefined } as any,clientForIdentity: () => client,});diff --git a/test/surface-cache.test.ts b/test/surface-cache.test.tsindex 8383dd5ea..9d1fbfa4c 100644--- a/test/surface-cache.test.ts+++ b/test/surface-cache.test.ts@@ -369,3 +369,119 @@ test("revisedSince skips the bot's own edits and can be scoped to one thread", a["2.0"],);});++test("cache revisions preserve attachments and parent against stale handled events", async () => {+ const cache = createMemorySurfaceCache();+ try {+ const base = { container: "CSNAPSHOT", ts: "2.0" };+ await cache.ingest([{ ...base, sub: "1.0", text: "latest", editedAt: 20, files: [{ fileId: "F1", name: "one" }] }]);+ await cache.ingest([+ { ...base, sub: "wrong", text: "stale", editedAt: 10, handled: true, files: [{ fileId: "F2" }] },+ ]);+ let [message] = await cache.readMessages(base.container, { at: base.ts });+ assert.equal(message?.text, "latest");+ assert.equal(message?.sub, "1.0");+ assert.equal(message?.handled, true);+ assert.deepEqual(+ message?.files?.map((f) => f.fileId),+ ["F1"],+ );+ await cache.ingest([{ ...base, sub: null, text: "root corrected", editedAt: 30 }]);+ [message] = await cache.readMessages(base.container, { at: base.ts });+ assert.equal(message?.sub, undefined);+ assert.deepEqual(+ message?.files?.map((f) => f.fileId),+ ["F1"],+ );+ await cache.ingest([{ ...base, text: "replacement", editedAt: 40, files: [{ fileId: "F2", name: "renamed" }] }]);+ [message] = await cache.readMessages(base.container, { at: base.ts });+ assert.equal(message?.sub, undefined);+ assert.deepEqual(+ message?.files?.map((f) => [f.fileId, f.name]),+ [["F2", "renamed"]],+ );+ await cache.ingest([{ ...base, text: "empty", editedAt: 50, files: [] }]);+ await cache.ingest([{ ...base, text: "stale", editedAt: 40, files: [{ fileId: "F2" }] }]);+ [message] = await cache.readMessages(base.container, { at: base.ts });+ assert.equal(message?.text, "empty");+ assert.equal(message?.files?.length ?? 0, 0);+ await cache.ingest([{ ...base, deleted: true }]);+ await cache.ingest([{ ...base, sub: "wrong", text: "revive", editedAt: 60, files: [{ fileId: "F3" }] }]);+ [message] = await cache.readMessages(base.container, { at: base.ts, includeDeleted: true });+ assert.equal(message?.deleted, true);+ assert.equal(message?.text, "empty");+ assert.equal(message?.sub, undefined);+ assert.equal(message?.files?.length ?? 0, 0);+ } finally {+ await cache.close();+ }+});++test("cache selects exact timestamps and oldest pages with live reply counts", async () => {+ const cache = createMemorySurfaceCache();+ try {+ const container = "CSELECT";+ await cache.ingest([+ { container, ts: "1.0", sub: null, text: "first" },+ { container, ts: "2.0", sub: "1.0", text: "reply" },+ { container, ts: "3.0", sub: "1.0", text: "deleted reply", deleted: true },+ { container, ts: "4.0", sub: null, text: "second root" },+ { container: "OTHER", ts: "5.0", sub: "1.0", text: "other container" },+ ]);+ assert.deepEqual(+ (await cache.readMessages(container, { timestamps: ["4.0", "1.0", "missing"] })).map((m) => m.ts),+ ["1.0", "4.0"],+ );+ assert.deepEqual(await cache.readMessages(container, { timestamps: [] }), []);+ await assert.rejects(cache.readMessages(container, { timestamps: Array(501).fill("1.0") }), /500/);+ const [oldest] = await cache.readMessages(container, { sub: null, oldestFirst: true, limit: 1 });+ assert.equal(oldest?.ts, "1.0");+ assert.equal(oldest?.replyCount, 1);+ assert.deepEqual(+ (await cache.readMessages(container, { sub: null, limit: 1 })).map((m) => m.ts),+ ["4.0"],+ );+ assert.deepEqual(+ (await cache.readMessages(container, { sub: "1.0", oldestFirst: true })).map((m) => m.ts),+ ["2.0"],+ );+ await cache.ingest([{ container, ts: "2.0", sub: null, text: "corrected" }]);+ assert.equal((await cache.readMessages(container, { at: "1.0" }))[0]?.replyCount, 0);+ } finally {+ await cache.close();+ }+});++test("channel history includes broadcasts while exact roots exclude them", async () => {+ const cache = createMemorySurfaceCache();+ try {+ const container = "CBROADCAST";+ await cache.ingest([+ { container, ts: "1.0", sub: null, text: "root" },+ { container, ts: "2.0", sub: "1.0", text: "ordinary reply" },+ { container, ts: "3.0", sub: "1.0", text: "broadcast", broadcast: true, editedAt: 20 },+ ]);+ await cache.ingest([+ { container, ts: "3.0", sub: "1.0", text: "stale", broadcast: false, editedAt: 10, handled: true },+ ]);+ await cache.ingest([{ container, ts: "3.0", sub: "1.0", text: "edit without subtype", editedAt: 30 }]);+ assert.deepEqual(+ (await cache.readMessages(container, { channelHistory: true })).map((m) => m.ts),+ ["1.0", "3.0"],+ );+ assert.deepEqual(+ (await cache.readMessages(container, { sub: null })).map((m) => m.ts),+ ["1.0"],+ );+ assert.equal((await cache.readMessages(container, { at: "3.0" }))[0]?.broadcast, true);+ await cache.ingest([+ { container, ts: "3.0", sub: "1.0", text: "corrected subtype", broadcast: false, editedAt: 40 },+ ]);+ assert.deepEqual(+ (await cache.readMessages(container, { channelHistory: true })).map((m) => m.ts),+ ["1.0"],+ );+ } finally {+ await cache.close();+ }+});