Multiplayer agent harness for work.
fix: preserve Slack mirror context metadata and fresh fallback content (#1242)
Regan Bell7582de3b6c45
diff --git a/package.json b/package.jsonindex 93e7f76ea..1903789f8 100644--- a/package.json+++ b/package.json@@ -36,7 +36,7 @@"sandbox:local:build": "bash scripts/local-sandbox-build.sh","sandbox:porter:build": "docker build --platform linux/amd64 -t \"${PORTER_SANDBOX_IMAGE:?Set PORTER_SANDBOX_IMAGE to the registry tag to publish}\" porter && docker push \"$PORTER_SANDBOX_IMAGE\"","deploy:porter-runner-image": "docker build --platform linux/amd64 -t \"${PORTER_DEPLOY_RUNNER_IMAGE:?Set PORTER_DEPLOY_RUNNER_IMAGE to the registry tag to publish}\" -f deploy/porter-runner/Dockerfile . && docker push \"$PORTER_DEPLOY_RUNNER_IMAGE\"",- "test:pg": "node --test --test-concurrency=1 test/postgres-swarms.test.ts test/postgres-store.test.ts test/postgres-grant-store.test.ts test/postgres-admin-grants.test.ts test/postgres-file-artifact-store.test.ts test/postgres-file-upload-store.test.ts test/postgres-directory-store.test.ts test/postgres-map.test.ts test/deploy-store-pg.test.ts test/postgres-cron-fires.test.ts test/postgres-migration-adoption.test.ts test/postgres-migrations.test.ts test/postgres-migration-startup.test.ts test/cron-queue.test.ts test/postgres-metrics-sink.test.ts test/postgres-error-log.test.ts test/postgres-audit-log.test.ts test/postgres-budget.test.ts test/postgres-rate-limiter.test.ts test/postgres-credential-usage-sink.test.ts test/postgres-config-store.test.ts test/postgres-delivery-store.test.ts test/postgres-replay-dedupe.test.ts test/postgres-broker-sessions.test.ts test/postgres-egress-audit-sink.test.ts test/postgres-memory-service.test.ts test/run-signal-store.test.ts test/postgres-listener.test.ts test/postgres-run-activity-store.test.ts test/leader-lease.test.ts test/advisory-lock.test.ts test/persistence-init-retry.test.ts test/migrate-principals.test.ts test/postgres-surface-cache.test.ts test/postgres-instance-registry.test.ts test/run-retry-delay.test.ts test/postgres-run-stream.test.ts test/migrate-main.test.ts",+ "test:pg": "node --test --test-concurrency=1 test/postgres-swarms.test.ts test/postgres-store.test.ts test/postgres-grant-store.test.ts test/postgres-admin-grants.test.ts test/postgres-file-artifact-store.test.ts test/postgres-file-upload-store.test.ts test/postgres-directory-store.test.ts test/postgres-map.test.ts test/deploy-store-pg.test.ts test/postgres-cron-fires.test.ts test/postgres-migration-adoption.test.ts test/postgres-migrations.test.ts test/postgres-migration-startup.test.ts test/cron-queue.test.ts test/postgres-metrics-sink.test.ts test/postgres-error-log.test.ts test/postgres-audit-log.test.ts test/postgres-budget.test.ts test/postgres-rate-limiter.test.ts test/postgres-credential-usage-sink.test.ts test/postgres-config-store.test.ts test/postgres-delivery-store.test.ts test/postgres-replay-dedupe.test.ts test/postgres-broker-sessions.test.ts test/postgres-egress-audit-sink.test.ts test/postgres-memory-service.test.ts test/run-signal-store.test.ts test/postgres-listener.test.ts test/postgres-run-activity-store.test.ts test/leader-lease.test.ts test/advisory-lock.test.ts test/persistence-init-retry.test.ts test/migrate-principals.test.ts test/postgres-surface-cache.test.ts test/slack-mirror-fidelity.test.ts test/postgres-instance-registry.test.ts test/run-retry-delay.test.ts test/postgres-run-stream.test.ts test/migrate-main.test.ts","livetest": "node scripts/api-livetest.ts","bench:memory": "node --env-file-if-exists=.env scripts/memory-bench.ts","prepare": "node .husky/install.mjs",diff --git a/src/api/routes/surface-cache.ts b/src/api/routes/surface-cache.tsindex 5068f32a7..1233f1ecb 100644--- a/src/api/routes/surface-cache.ts+++ b/src/api/routes/surface-cache.ts@@ -28,7 +28,9 @@ export function toEvent(raw: unknown): IngestEvent | null {return {container: raw.container,ts: raw.ts,- ...(typeof raw.sub === "string" && raw.sub ? { sub: raw.sub } : {}),+ ...(raw.sub === null || (typeof raw.sub === "string" && raw.sub) ? { sub: raw.sub } : {}),+ ...(typeof raw.subtype === "string" ? { subtype: raw.subtype } : {}),+ ...(typeof raw.broadcast === "boolean" ? { broadcast: raw.broadcast } : {}),...(typeof raw.authorId === "string" ? { authorId: raw.authorId } : {}),...(typeof raw.authorName === "string" ? { authorName: raw.authorName } : {}),...(typeof raw.text === "string" ? { text: raw.text } : {}),diff --git a/src/slack/README.md b/src/slack/README.mdindex 3ff5aa39c..a82f4da72 100644--- a/src/slack/README.md+++ b/src/slack/README.md@@ -255,3 +255,5 @@ your per-dev name + tokens live only in your local app and your gitignored `.env- `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.++Slack mirror records preserve provider subtypes so stored context uses the same system-message filtering as live context. A missing stored subtype means legacy or unobserved metadata; an empty subtype means a verified ordinary message. Partial event updates preserve omitted subtype and thread metadata. Mirror-mode history fallback shares event content normalization and prefers fresh Slack duplicates; live and shadow reads never backfill their comparison source.diff --git a/src/slack/events.ts b/src/slack/events.tsindex 703f3c1b4..db26ed9db 100644--- a/src/slack/events.ts+++ b/src/slack/events.ts@@ -148,6 +148,7 @@ export function registerSlackEvents(userId: identity.userId,...(identity.actor ? { actor: identity.actor } : {}),rawText: content.text,+ subtype: e.subtype ?? "",files: content.files,threadTs: e.thread_ts,ts: e.ts,@@ -165,6 +166,17 @@ export function registerSlackEvents(app.message(async ({ message, body, client, context }: MessageArgs) => {try {const m = parseMessageEvent(message);+ if (+ m.channel &&+ !m.channel_type &&+ (shouldMirrorMessage(m) || m.subtype === "message_changed" || m.subtype === "message_deleted")+ ) {+ const info = await directory.getChannelInfo(client, m.channel);+ if (!info) throw new Error("Slack message channel lookup unavailable");+ if (info.is_im) m.channel_type = "im";+ else if (info.is_mpim) m.channel_type = "mpim";+ else m.channel_type = info.is_private ? "group" : "channel";+ }const eventId = parseEventId(body);const privacyChange = channelPrivacyChange(m);if (privacyChange) {@@ -213,6 +225,7 @@ export function registerSlackEvents(const editedAt = Number(m.message.edited?.ts) || (textChanged ? Number(m.ts) : 0);if (shouldMirrorMessage(m.message))await mirrorMessageEvent({ ...m.message, channel: m.channel, channel_type: m.channel_type }, client, {+ partial: true,...(!shouldProcessMessage(m.message, "", "") ? { handled: true } : {}),...(editedAt > 0 ? { editedAt: Math.round(editedAt * 1000) } : {}),...(m.channel_type === "im" ? { kind: "dm" as const } : {}),@@ -264,6 +277,7 @@ export function registerSlackEvents(...(identity.actor ? { actor: identity.actor } : {}),...(m.bot_profile?.name || m.username ? { authorName: String(m.bot_profile?.name || m.username) } : {}),rawText: content.text,+ subtype: m.subtype ?? "",files: content.files,threadTs: m.thread_ts,ts: m.ts,@@ -309,6 +323,7 @@ export function registerSlackEvents(...(identity.actor ? { actor: identity.actor } : {}),...(m.bot_profile?.name || m.username ? { authorName: String(m.bot_profile?.name || m.username) } : {}),rawText: content.text,+ subtype: m.subtype ?? "",files: content.files,threadTs: m.thread_ts,ts: m.ts,diff --git a/src/slack/history.ts b/src/slack/history.tsindex 426cd15c7..40d3b3860 100644--- a/src/slack/history.ts+++ b/src/slack/history.ts@@ -1,6 +1,7 @@+import { slackMessageToIngestEvent } from "./mirror.ts";import { messageWithForwardedContent } from "./forwards.ts";import type { SlackContextSource } from "./config.ts";-import { decodeSlackEntities, mentionsBot, resolveMentionsInText } from "./lib.ts";+import { decodeSlackEntities, 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";@@ -210,6 +211,7 @@ export function createSlackHistoryReader(deps: {.filter((m) => !m.deleted && (!before || m.ts < before)).map((m) => ({ts: m.ts,+ ...(m.subtype !== undefined ? { subtype: m.subtype } : {}),text: m.text.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">"),...(m.mentionsSelf ? { mentionsSelf: true } : {}),...(m.sub ? { thread_ts: m.sub } : {}),@@ -239,26 +241,7 @@ export function createSlackHistoryReader(deps: {.rememberSurfaceHistory(page.messages.filter((m) => m.ts)- .map((m) => ({- container: channel,- ts: m.ts!,- ...(m.thread_ts && m.thread_ts !== m.ts ? { sub: m.thread_ts } : {}),- ...(m.user ? { authorId: m.user } : {}),- ...(m.username ? { authorName: m.username } : {}),- text: decodeSlackEntities(String(m.text ?? "")),- ...(mentionsBot(String(m.text ?? ""), deps.ids.botUserId) ? { mentionsSelf: true } : {}),- ...(m.user === deps.ids.botUserId ? { self: true } : {}),- ...(m.bot_id ? { bot: true } : {}),- ...(Number(m.edited?.ts) > 0 ? { editedAt: Math.round(Number(m.edited!.ts) * 1000) } : {}),- handled: true,- ...(m.files?.length- ? {- files: m.files- .filter((f) => f.id)- .map((f) => ({ fileId: f.id!, name: f.name, mimetype: f.mimetype })),- }- : {}),- })),+ .map((m) => slackMessageToIngestEvent({ ...m, channel }, deps.ids, { handled: true })),).catch((error) => swallow("slack: history mirror ingest", error));}@@ -272,7 +255,7 @@ export function createSlackHistoryReader(deps: {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])+ for (const message of [...mirrored, ...page.messages])if (message.ts && !deleted.has(message.ts)) byTs.set(message.ts, message);return {raw: [...byTs.values()],diff --git a/src/slack/identity.ts b/src/slack/identity.tsindex b395969fa..8bcd2b1c4 100644--- a/src/slack/identity.ts+++ b/src/slack/identity.ts@@ -91,6 +91,7 @@ export function probeIdentityMode(members: SlackUser[], ownTeamId: string): Slac}export interface ChannelMeta {+ is_im?: boolean;name?: string;is_ext_shared?: boolean;is_pending_ext_shared?: boolean;diff --git a/src/slack/mirror.ts b/src/slack/mirror.tsindex e3052d4f2..bb4f18838 100644--- a/src/slack/mirror.ts+++ b/src/slack/mirror.ts@@ -13,10 +13,62 @@ export interface Mirror {mirrorMessageEvent(m: Partial<SlackMessageEvent>,client: any,- opts?: { editedAt?: number; handled?: boolean; containerName?: string; kind?: "channel" | "dm" | "group" },+ opts?: {+ partial?: boolean;+ editedAt?: number;+ handled?: boolean;+ containerName?: string;+ kind?: "channel" | "dm" | "group";+ },): Promise<void>;}+export function slackMessageToIngestEvent(+ m: Partial<SlackMessageEvent>,+ ids: BotIdentity,+ opts: {+ partial?: boolean;+ text?: string;+ mentions?: Record<string, string>;+ editedAt?: number;+ handled?: boolean;+ containerName?: string;+ kind?: "channel" | "dm" | "group";+ } = {},+): IngestEvent {+ const content = messageWithForwardedContent(m);+ const raw = content.text;+ return {+ container: m.channel!,+ ts: m.ts!,+ ...(m.subtype !== undefined || !opts.partial+ ? { subtype: m.subtype ?? "", broadcast: m.subtype === "thread_broadcast" }+ : {}),+ ...(m.subtype === "tombstone" ? { deleted: true } : {}),+ ...(m.thread_ts !== undefined || !opts.partial+ ? { sub: m.thread_ts && m.thread_ts !== m.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: opts.text ?? decodeSlackEntities(raw),+ ...((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(opts.mentions ?? {}).length ? { mentions: opts.mentions } : {}),+ ...(m.bot_id || m.bot_profile ? { bot: true } : {}),+ ...(mentionsBot(raw, ids.botUserId) ? { mentionsSelf: true } : {}),+ ...((opts.editedAt ?? Number(m.edited?.ts) * 1000) > 0+ ? { editedAt: Math.round(opts.editedAt ?? Number(m.edited?.ts) * 1000) }+ : {}),+ ...(opts.handled ? { handled: true } : {}),+ ...(opts.containerName ? { containerName: opts.containerName } : {}),+ ...(opts.kind ? { kind: opts.kind } : {}),+ };+}+export function createMirror(deps: {core: SlackCoreClient;ids: BotIdentity;@@ -54,7 +106,13 @@ export function createMirror(deps: {async function mirrorMessageEvent(m: Partial<SlackMessageEvent>,client: any,- opts: { editedAt?: number; handled?: boolean; containerName?: string; kind?: "channel" | "dm" | "group" } = {},+ opts: {+ partial?: boolean;+ editedAt?: number;+ handled?: boolean;+ containerName?: string;+ kind?: "channel" | "dm" | "group";+ } = {},): Promise<void> {const container = m.channel;const ts = m.ts;@@ -81,30 +139,7 @@ export function createMirror(deps: {const content = messageWithForwardedContent(m);const raw = content.text;const { text, mentions } = await resolveTextMentions(client, decodeSlackEntities(raw));- await pushSurfaceEvents([- {- container,- 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,- ...((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 } : {}),- ...(opts.editedAt ? { editedAt: opts.editedAt } : {}),- ...(opts.handled ? { handled: true } : {}),- ...(opts.containerName ? { containerName: opts.containerName } : {}),- kind,- },- ]);+ await pushSurfaceEvents([slackMessageToIngestEvent(m, ids, { ...opts, text, mentions, kind })]);}return { pushSurfaceEvents, resolveTextMentions, mirrorMessageEvent };diff --git a/src/slack/turn-handler.ts b/src/slack/turn-handler.tsindex 3706c5871..00fa1afba 100644--- a/src/slack/turn-handler.ts+++ b/src/slack/turn-handler.ts@@ -84,6 +84,7 @@ interface Incoming {actor?: ActorAssertion;authorName?: string;rawText: string;+ subtype?: string;files: SlackFile[];threadTs?: string;ts: string;@@ -408,13 +409,14 @@ export function createTurnHandler(deps: {channel: inc.channel,ts: inc.ts,text: inc.rawText,+ subtype: inc.subtype,files: inc.files,user: inc.userId,thread_ts: inc.threadTs,channel_type: channelType(inc.kind, conversationKind),},client,- { kind: conversationKind, handled: true, ...(containerName ? { containerName } : {}) },+ { partial: true, kind: conversationKind, handled: true, ...(containerName ? { containerName } : {}) },);}diff --git a/src/surface-cache/surface-cache.ts b/src/surface-cache/surface-cache.tsindex d3712d0d7..196df9434 100644--- a/src/surface-cache/surface-cache.ts+++ b/src/surface-cache/surface-cache.ts@@ -119,6 +119,10 @@ export function createPostgresSurfaceCache(id: "surface-cache/store/0004",statements: [`ALTER TABLE channel_messages ADD COLUMN IF NOT EXISTS broadcast BOOLEAN NOT NULL DEFAULT FALSE`],},+ {+ id: "surface-cache/store/0005",+ statements: [`ALTER TABLE channel_messages ADD COLUMN IF NOT EXISTS subtype TEXT`],+ },]);const liveFallback = opts.liveFallback;@@ -128,6 +132,7 @@ export function createPostgresSurfaceCache(container: r.container as string,ts: r.ts as string,...(r.sub != null ? { sub: r.sub as string } : {}),+ ...(r.subtype != null ? { subtype: r.subtype 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 } : {}),@@ -158,10 +163,11 @@ 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, broadcast)- VALUES ($1,$2,$3,$4,$5,$6,$7,$8::jsonb,$9,$10,$11,$12,$13,$14,$15,$16,COALESCE($18::boolean, FALSE))+ `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, subtype)+ VALUES ($1,$2,$3,$4,$5,$6,$7,$8::jsonb,$9,$10,$11,$12,$13,$14,$15,$16,COALESCE($18::boolean, FALSE),$19)ON CONFLICT (org_id, container, ts) DO UPDATE SETsub = 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,+ subtype = CASE WHEN EXCLUDED.deleted OR channel_messages.deleted OR COALESCE(EXCLUDED.edited_at, 0) < COALESCE(channel_messages.edited_at, 0) THEN channel_messages.subtype ELSE COALESCE(EXCLUDED.subtype, channel_messages.subtype) 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,@@ -197,6 +203,7 @@ export function createPostgresSurfaceCache(e.deleted ? now : null,e.sub !== undefined,e.broadcast ?? null,+ e.subtype ?? null,],);upserted += res.rowCount ?? 0;@@ -457,6 +464,7 @@ export function createMemorySurfaceCache(opts: { liveFallback?: LiveFallback } =...((e.sub === undefined ? existing?.sub : e.sub)? { sub: (e.sub === undefined ? existing?.sub : e.sub) as string }: {}),+ ...((e.subtype ?? existing?.subtype) !== undefined ? { subtype: e.subtype ?? existing?.subtype } : {}),...((e.broadcast ?? existing?.broadcast) ? { broadcast: true } : {}),...((e.authorId ?? existing?.authorId) ? { authorId: (e.authorId ?? existing?.authorId) as string } : {}),...((e.authorName ?? existing?.authorName)diff --git a/src/surface-cache/types.ts b/src/surface-cache/types.tsindex 07e481a6f..6234b2076 100644--- a/src/surface-cache/types.ts+++ b/src/surface-cache/types.ts@@ -3,6 +3,7 @@ export interface CachedMessage {ts: string;sub?: string;broadcast?: boolean;+ subtype?: string;authorId?: string;authorName?: string;text: string;@@ -50,6 +51,7 @@ export interface IngestEvent {ts: string;sub?: string | null;broadcast?: boolean;+ subtype?: string;authorId?: string;authorName?: string;text?: string;diff --git a/test/slack-mirror-fidelity.test.ts b/test/slack-mirror-fidelity.test.tsnew file mode 100644index 000000000..bce90e4da--- /dev/null+++ b/test/slack-mirror-fidelity.test.ts@@ -0,0 +1,152 @@+import { test } from "node:test";+import assert from "node:assert/strict";+import { createMemorySurfaceCache, createPostgresSurfaceCache } from "../src/surface-cache/surface-cache.ts";+import { slackMessageToIngestEvent } from "../src/slack/mirror.ts";+import { toEvent } from "../src/api/routes/surface-cache.ts";+import { createSlackHistoryReader } from "../src/slack/history.ts";+import { createConversationSerializer } from "../src/slack/conversation-view.ts";+import type { SlackCoreClient } from "../src/api/slack-core-client.ts";+import type { BotIdentity, Directory } from "../src/slack/directory.ts";++const ids = { botUserId: "UBOT", ownBotId: "BBOT" } as BotIdentity;+const directory = {+ classifyUserCached: async (_client: unknown, user: string) => ({ actor: { displayName: user } }),+} as unknown as Directory;++for (const postgres of [false, true]) {+ test(+ `subtype roundtrip and stale/partial/deleted protection (${postgres ? "postgres" : "memory"})`,+ {+ skip: postgres && !process.env.DATABASE_URL,+ },+ async () => {+ const cache = postgres ? createPostgresSurfaceCache(process.env.DATABASE_URL!) : createMemorySurfaceCache();+ const container = `fidelity-${Date.now()}-${postgres}`;+ const read = async () => (await cache.readMessages(container, { at: "1", includeDeleted: true }))[0]!;+ try {+ await cache.ingest([{ container, ts: "1", text: "legacy" }]);+ assert.equal((await read()).subtype, undefined);+ await cache.ingest([{ container, ts: "1", text: "joined", subtype: "channel_join", editedAt: 10 }]);+ await cache.ingest([{ container, ts: "1", text: "partial", editedAt: 20 }]);+ assert.equal((await read()).subtype, "channel_join");+ await cache.ingest([{ container, ts: "1", text: "stale", subtype: "", editedAt: 10, handled: true }]);+ assert.equal((await read()).subtype, "channel_join");+ await cache.ingest([{ container, ts: "1", text: "ordinary", subtype: "", editedAt: 30 }]);+ assert.equal((await read()).subtype, "");+ await cache.ingest([{ container, ts: "1", deleted: true, subtype: "tombstone" }]);+ await cache.ingest([{ container, ts: "1", text: "resurrection", subtype: "bot_message", editedAt: 40 }]);+ assert.equal((await read()).subtype, "");+ assert.equal((await read()).deleted, true);+ } finally {+ await cache.close();+ }+ },+ );+}++test("canonical snapshots cross the HTTP mapper with explicit empty files, roots and bot identity", () => {+ const event = toEvent(+ slackMessageToIngestEvent(+ { channel: "C", ts: "1", bot_id: "BBOT", bot_profile: { name: "QM" }, text: "A & B" },+ ids,+ ),+ )!;+ assert.equal(event.text, "A & B");+ assert.equal(event.sub, null);+ assert.equal(event.subtype, "");+ assert.equal(event.broadcast, false);+ assert.equal(event.authorName, "QM");+ assert.equal(event.bot, true);+ assert.equal(event.self, true);+ assert.deepEqual(event.files, []);+ const partial = slackMessageToIngestEvent({ channel: "C", ts: "1", text: "edit" }, ids, {+ partial: true,+ editedAt: 20,+ });+ assert.equal(partial.subtype, undefined);+ assert.equal(partial.broadcast, undefined);+ assert.equal(partial.sub, undefined);+});++test("mirror and live render the same allowed message subtypes", async () => {+ const raw = [+ undefined,+ "file_share",+ "bot_message",+ "thread_broadcast",+ "channel_join",+ "channel_topic",+ "tombstone",+ ].map((subtype, i) => ({ ts: `1000.00000${i}`, text: `body-${i}`, user: "U1", subtype }));+ const cache = createMemorySurfaceCache();+ await cache.ingest(raw.map((m) => toEvent(slackMessageToIngestEvent({ ...m, channel: "C" }, ids))!));+ const core = { readSurfaceMessages: cache.readMessages } as SlackCoreClient;+ const client = { conversations: { history: async () => ({ messages: raw.slice().reverse(), has_more: false }) } };+ const views = [];+ for (const source of ["live", "mirror"] as const) {+ const serializer = createConversationSerializer({+ ids,+ directory,+ externalParticipantsEnabled: async () => false,+ readHistory: createSlackHistoryReader({ core, ids, source }),+ });+ const result = await serializer.serializeSlackConversation(+ client,+ { kind: "channel", channel: "C", ts: "1000.000009", rawText: "trigger", userId: "U1", files: [] },+ { audience: [] },+ );+ views.push(result.view.messages);+ }+ assert.deepEqual(views[1], views[0]);+ assert.equal(views[0]!.filter((m) => m.text.startsWith("body-")).length, 4);+});++test("fallback prefers fresh live duplicates and replaces removed files", async () => {+ const cache = createMemorySurfaceCache();+ await cache.ingest([{ container: "C", ts: "2", sub: "1", text: "stale", files: [{ fileId: "FOLD" }] }]);+ const core = {+ readSurfaceMessages: cache.readMessages,+ rememberSurfaceHistory: async (events) => {+ await cache.ingest(events.map((e) => toEvent(e)!));+ },+ } as SlackCoreClient;+ const read = createSlackHistoryReader({ core, ids, source: "mirror" });+ const page = await read(+ {+ conversations: {+ replies: async () => ({+ messages: [+ { ts: "1", text: "parent" },+ { ts: "2", thread_ts: "1", text: "fresh", edited: { ts: "3" }, bot_profile: { name: "Author" } },+ ],+ }),+ },+ },+ "C",+ "1",+ );+ assert.equal(page.raw.find((m) => m.ts === "2")?.text, "fresh");+ const stored = (await cache.readMessages("C", { at: "2" }))[0]!;+ assert.equal(stored.authorName, "Author");+ assert.equal(stored.bot, true);+ assert.equal(stored.files?.length ?? 0, 0);+});++test("live and shadow do not repair their own comparison source", async () => {+ for (const source of ["live", "shadow"] as const) {+ let writes = 0;+ const read = createSlackHistoryReader({+ ids,+ source,+ core: {+ readSurfaceMessages: async () => [],+ rememberSurfaceHistory: async () => {+ writes++;+ },+ } as unknown as SlackCoreClient,+ });+ await read({ conversations: { history: async () => ({ messages: [{ ts: "1", text: "live" }] }) } }, "C");+ await new Promise((resolve) => setImmediate(resolve));+ assert.equal(writes, 0);+ }+});diff --git a/test/slack-mirror-ingestion.test.ts b/test/slack-mirror-ingestion.test.tsindex f2d9e0233..f6b2ca3f3 100644--- a/test/slack-mirror-ingestion.test.ts+++ b/test/slack-mirror-ingestion.test.ts@@ -5,6 +5,7 @@ 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 { toEvent } from "../src/api/routes/surface-cache.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";@@ -633,3 +634,127 @@ test("synthetic reaction turns preserve the canonical message snapshot", async ();assert.deepEqual(await cache.readMessages("D1", { at: "2" }), before);});++test("broadcast metadata survives reduced remirroring and partial edits across HTTP ingestion", async () => {+ const cache = createMemorySurfaceCache();+ const f = fixture({+ ingest: async (events) => {+ await cache.ingest(events.map((e) => toEvent(e)!));+ },+ });+ await f.fire({+ type: "message",+ subtype: "thread_broadcast",+ channel: "C1",+ channel_type: "channel",+ user: "UBOT",+ ts: "2",+ thread_ts: "1",+ text: "reply",+ });+ await f.mirror.mirrorMessageEvent(+ { channel: "C1", channel_type: "channel", user: "UBOT", ts: "2", thread_ts: "1", text: "reply" },+ {},+ { partial: true, handled: true },+ );+ await f.fire({+ type: "message",+ subtype: "message_changed",+ channel: "C1",+ channel_type: "channel",+ ts: "3",+ message: { user: "UBOT", ts: "2", text: "edited" },+ previous_message: { text: "reply" },+ });+ const rows = await cache.readMessages("C1", { channelHistory: true });+ assert.equal(rows.length, 1);+ assert.equal(rows[0]?.sub, "1");+ assert.equal(rows[0]?.subtype, "thread_broadcast");+ assert.equal(rows[0]?.broadcast, true);+ assert.equal(rows[0]?.text, "edited");+});++test("dispatch retains known ordinary and file-share subtypes for direct messages", async () => {+ for (const subtype of [undefined, "file_share"]) {+ const f = fixture();+ await f.fire({ type: "message", channel: "D1", channel_type: "im", user: "U1", ts: "10", text: "hello", subtype });+ assert.equal(f.dispatches[0]?.[1].subtype, subtype ?? "");+ }+});++test("untyped attachment-only updates and deletions resolve room kind without dispatch", async () => {+ for (const info of [{ is_im: true }, { is_mpim: true }, { is_private: true }, {}]) {+ const cache = createMemorySurfaceCache();+ const f = fixture({+ directory: {+ getChannelInfo: async () => info,+ allInternalRosters: async () => new Map([["C1", []]]),+ classifyUserCached: async () => ({ ok: true, actor: { externalId: "UBOT", displayName: "QM" } }),+ forceDirectorySync: async () => {},+ },+ ingest: async (events) => {+ await cache.ingest(events.map((e) => toEvent(e)!));+ },+ });+ await cache.ingest([{ container: "C1", ts: "1", text: "link", self: true, editedAt: 1000 }]);+ await f.fire({+ type: "message",+ subtype: "message_changed",+ hidden: true,+ channel: "C1",+ ts: "3",+ message: {+ user: "UBOT",+ ts: "1",+ text: "link",+ edited: { ts: "1" },+ attachments: [+ {+ is_msg_unfurl: true,+ text: "forwarded body",+ files: [{ id: "F1", name: "image.png", mimetype: "image/png" }],+ },+ ],+ },+ previous_message: { user: "UBOT", text: "link" },+ });+ const rows = await cache.readMessages("C1");+ assert.match(rows[0]!.text, /forwarded body/);+ assert.equal(rows[0]!.editedAt, 1000);+ assert.deepEqual(rows[0]!.files, [{ fileId: "F1", name: "image.png", mimetype: "image/png" }]);+ assert.equal(f.dispatches.length, 0);+ await f.fire({+ type: "message",+ subtype: "message_deleted",+ hidden: true,+ channel: "C1",+ ts: "4",+ deleted_ts: "1",+ previous_message: { user: "UBOT" },+ });+ assert.equal((await cache.readMessages("C1")).length, 0);+ }+});++test("untyped edit channel lookup failure withholds acknowledgement for retry", async () => {+ const f = fixture({ directory: { getChannelInfo: async () => undefined } });+ let acks = 0;+ const gate = createDeferredEnvelopeAck(+ async () => {+ acks++;+ },+ { gated: true },+ );+ await f.fire(+ {+ type: "message",+ subtype: "message_changed",+ channel: "C1",+ ts: "2",+ message: { ts: "1", text: "edit", user: "UBOT" },+ },+ gate,+ );+ assert.equal(acks, 0);+ assert.equal(f.events.length, 0);+});diff --git a/test/surface-cache-ingest-mapper.test.ts b/test/surface-cache-ingest-mapper.test.tsindex b55a959c4..fc1c6a089 100644--- a/test/surface-cache-ingest-mapper.test.ts+++ b/test/surface-cache-ingest-mapper.test.ts@@ -51,3 +51,17 @@ test("toEvent rejects a payload with no container/ts", () => {assert.equal(toEvent({ container: "C1" }), null);assert.equal(toEvent("nope"), null);});++test("toEvent preserves authoritative root, subtype and broadcast corrections", () => {+ assert.deepEqual(toEvent({ container: "C", ts: "1", sub: null, subtype: "", broadcast: false }), {+ container: "C",+ ts: "1",+ sub: null,+ subtype: "",+ broadcast: false,+ });+ assert.deepEqual(toEvent({ container: "C", ts: "1", subtype: 5, broadcast: "true" }), {+ container: "C",+ ts: "1",+ });+});