diff --git a/plugins/openclaw/extra-message-policy/README.md b/plugins/openclaw/extra-message-policy/README.md index 2f0e328..f9facb5 100644 --- a/plugins/openclaw/extra-message-policy/README.md +++ b/plugins/openclaw/extra-message-policy/README.md @@ -341,3 +341,20 @@ tool enforce mandatory admission independently of caller search filters. Protect recall accepts only new records stamped after scope admission; historical mixed records are preserved but excluded. This does not delete historical data, provide complete sender opt-out, or enforce restrictions on unrelated agents/guilds. + +Normal Discord dispatch does not invoke a global `inbound_claim`. Mandatory +admission therefore resolves missing channel ancestry independently through a +bounded Discord metadata GET using the account's existing literal token or an +approved default environment SecretRef. ID, guild, thread type and allowed parent +must match. Missing credentials, unsupported providers and failed lookup deny the +turn; unsuccessful lookups are not retained forever. Concurrent hooks share an +in-flight lookup. Unrelated guilds keep their legacy lookup behavior. + +A separate mandatory provenance cache never consumes legacy inferred model-parent +session keys. Native `parentConversationId` (channel: or bare snowflake) +is supported for plugin-owned claims, but normal delivery does not depend on that +hook. Protected archives are written only by full `message_received` events; +reduced dispatch events neither write JSONL/HTTP nor consume dedupe keys. The full +`reply_dispatch` context is gated before model/persistence, including supplemental +media omitted from the reduced dispatch projection. Do not infer ancestry from +user text, channel names or inherited model transcripts. diff --git a/plugins/openclaw/extra-message-policy/channel-scope.js b/plugins/openclaw/extra-message-policy/channel-scope.js index 4759de7..1503bc8 100644 --- a/plugins/openclaw/extra-message-policy/channel-scope.js +++ b/plugins/openclaw/extra-message-policy/channel-scope.js @@ -14,6 +14,9 @@ export function normalizeChannelScopes(raw) { return { accountId: String(scope.accountId), guildId: String(scope.guildId), channelIds: [...new Set(scope.channelIds)], agentIds: scope.agentIds || [] }; }); } +export function transportParentConversationId(input) { + return typeof input === 'string' ? /^(?:channel:)?(\d{16,22})$/.exec(input)?.[1] || '' : ''; +} export function scopeRoute(event = {}, ctx = {}) { const meta = { ...event.metadata, ...ctx.metadata }; const session = value(ctx.sessionKey, ctx.SessionKey, event.sessionKey, event.SessionKey); @@ -21,7 +24,7 @@ export function scopeRoute(event = {}, ctx = {}) { accountId: value(ctx.accountId, ctx.AccountId, event.accountId, event.AccountId, meta.accountId), guildId: value(ctx.rawGuildId, ctx.GroupSpace, ctx.guildId, event.rawGuildId, event.guildId, meta.rawGuildId, meta.guildId, meta.guild_id), channelId: snowflake(ctx.NativeChannelId, ctx.ChannelId, ctx.channelId, event.channelId, event.ChannelId, meta.channelId, meta.channel_id, ctx.conversationId, event.conversationId, session.match(/:channel:([^:]+)/)?.[1]), - parentChannelId: value(ctx.parentChannelId, ctx.ParentChannelId, ctx.ThreadParentId, event.parentChannelId, meta.parentChannelId, meta.threadParentId, meta.thread_parent_id), + parentChannelId: snowflake(ctx.parentChannelId, ctx.ParentChannelId, ctx.ThreadParentId, event.parentChannelId, meta.parentChannelId, meta.threadParentId, meta.thread_parent_id, transportParentConversationId(ctx.parentConversationId), transportParentConversationId(event.parentConversationId)), agentId: value(ctx.agentId, ctx.AgentId, event.agentId, session.match(/^agent:([^:]+):/)?.[1]) }; } @@ -36,7 +39,7 @@ export function activeChannelScope(scopes = [], event = {}, ctx = {}) { const externalKeys = new Set([ 'ReplyToId', 'ReplyToIdFull', 'ReplyToBody', 'ReplyToSender', 'ReplyToIsQuote', 'replyToId', 'replyToIdFull', 'replyToBody', 'replyToSender', 'replyToIsQuote', 'ThreadStarterBody', 'threadStarterBody', 'starterBody', 'quote', 'quotedMessage', - 'ThreadHistoryBody', 'threadHistoryBody', 'media', 'originalMedia', 'mediaStagingPending', 'MediaPath', 'MediaPaths', 'MediaUrl', 'MediaUrls', 'MediaType', 'MediaTypes', 'referenced_message', 'referencedMessage', 'message_reference', 'messageReference', + 'ThreadHistoryBody', 'threadHistoryBody', 'media', 'originalMedia', 'mediaStagingPending', 'MediaPath', 'MediaPaths', 'MediaUrl', 'MediaUrls', 'MediaType', 'MediaTypes', 'mediaPath', 'mediaPaths', 'mediaUrl', 'mediaUrls', 'mediaType', 'mediaTypes', 'referenced_message', 'referencedMessage', 'message_reference', 'messageReference', 'message_snapshots', 'messageSnapshots', 'ForwardedFrom', 'ForwardedFromId', 'forwarded', 'forwardedFrom', 'replyContext', 'replyTo', 'quotedAttachments' ]); diff --git a/plugins/openclaw/extra-message-policy/package.json b/plugins/openclaw/extra-message-policy/package.json index 3557d07..98f62ee 100644 --- a/plugins/openclaw/extra-message-policy/package.json +++ b/plugins/openclaw/extra-message-policy/package.json @@ -1,6 +1,6 @@ { "name": "@nestdevlab/openclaw-plugin-extra-message-policy", - "version": "0.1.11", + "version": "0.1.12", "private": false, "type": "module", "description": "OpenClaw plugin for cross-platform message ingest, response policy, and zero-embedding raw recall.", diff --git a/plugins/openclaw/extra-message-policy/plugin-runtime.js b/plugins/openclaw/extra-message-policy/plugin-runtime.js index 13457e4..b0b85a0 100644 --- a/plugins/openclaw/extra-message-policy/plugin-runtime.js +++ b/plugins/openclaw/extra-message-policy/plugin-runtime.js @@ -1,4 +1,4 @@ -import { admitChannelScope, activeChannelScope, scopeRoute } from "./channel-scope.js"; +import { admitChannelScope, activeChannelScope, scopeRoute, transportParentConversationId } from "./channel-scope.js"; import { createNativeOptOutGuard } from "./native-optout-guard.js"; import { mkdir, appendFile } from "node:fs/promises"; import path from "node:path"; @@ -126,6 +126,8 @@ function routeChannelId(event = {}, ctx = {}) { function routeParentChannelId(event = {}, ctx = {}) { return stripConversationPrefix(textValue( + transportParentConversationId(ctx.parentConversationId), + transportParentConversationId(event.parentConversationId), ctx.NativeParentChannelId, ctx.ParentChannelId, ctx.parentChannelId, @@ -250,6 +252,27 @@ function discordTokenForAccount(openclawConfig = {}, accountId = "") { return ""; } +async function fetchDiscordScopeChannel(channelId, scope, currentConfig) { + if (!looksLikeDiscordSnowflake(channelId) || typeof fetch !== "function") return null; + const account = discordAccountConfig(currentConfig, scope.accountId); + const binding = account?.token || currentConfig?.channels?.discord?.token; + let token = discordTokenForAccount(currentConfig, scope.accountId); + if (!token && binding?.source === "env" && binding.provider === "default" && + typeof binding.id === "string" && /^[A-Za-z_][A-Za-z0-9_]*$/.test(binding.id)) { + token = process.env[binding.id] || ""; + } + if (!token) return null; + const res = await fetch(`${DISCORD_API}/channels/${encodeURIComponent(channelId)}`, { + headers: { authorization: `Bot ${token}` }, signal: AbortSignal.timeout(5000) + }); + if (!res.ok) return null; + const json = await res.json(); + if (json?.id !== channelId || json.guild_id !== scope.guildId) return null; + if (!scope.channelIds.includes(channelId) && + (![10, 11, 12].includes(json.type) || !scope.channelIds.includes(json.parent_id))) return null; + return { guildId: json.guild_id, parentChannelId: String(json.parent_id || "") }; +} + async function fetchDiscordChannelParent(channelId, token) { if (typeof fetch !== "function" || !token || !looksLikeDiscordSnowflake(channelId)) return null; const res = await fetch(`${DISCORD_API}/channels/${encodeURIComponent(channelId)}`, { @@ -451,9 +474,9 @@ function rememberDedupe(state, key, windowSize) { function toRecord(source, event = {}, ctx = {}, policy = {}) { return { source, - ...(policy.channelScopeAdmission ? { channelScopeAdmission: 1, guildId: routeGuildId(event, ctx), parentChannelId: routeParentChannelId(event, ctx) } : {}), + ...(policy.channelScopeAdmission ? { channelScopeAdmission: 1, guildId: policy.channelScopeRoute.guildId, parentChannelId: policy.channelScopeRoute.parentChannelId } : {}), observedAt: new Date().toISOString(), - channelId: policy.channelScopeAdmission ? scopeRoute(event, ctx).channelId : (ctx.channelId ?? ctx.ChannelId ?? ctx.NativeChannelId ?? event.channelId ?? event.ChannelId ?? event.NativeChannelId ?? event.channel ?? event.from), + channelId: policy.channelScopeAdmission ? policy.channelScopeRoute.channelId : (ctx.channelId ?? ctx.ChannelId ?? ctx.NativeChannelId ?? event.channelId ?? event.ChannelId ?? event.NativeChannelId ?? event.channel ?? event.from), accountId: ctx.accountId ?? ctx.AccountId ?? event.accountId ?? event.AccountId, conversationId: ctx.conversationId ?? ctx.OriginatingTo ?? ctx.To ?? event.conversationId ?? event.OriginatingTo ?? event.To, sessionKey: ctx.sessionKey ?? ctx.SessionKey ?? event.sessionKey ?? event.SessionKey, @@ -512,6 +535,9 @@ async function postHttpSink(httpSink, record) { } async function ingest(api, cfg, state, source, event, ctx, policy) { + // Reduced dispatch projections omit supplemental media provenance. They must + // not write or consume dedupe keys before the asynchronous received hook. + if (policy.channelScopeAdmission && source !== "message_received") return; if (!shouldIngest(policy, source)) return; const id = eventMessageId(event, ctx); @@ -941,6 +967,9 @@ export function registerExtraMessagePolicy(api, options = {}) { mentionFacts: new Map(), discordRoutes: new Map(), discordChannelParents: new Map(), + scopeRoutes: new Map(), + scopeGuilds: new Map(), + scopeLookups: new Map(), traceCounter: 0, diagnosticSequence: 0, diagnosticStartedAt: process.hrtime.bigint() @@ -954,16 +983,78 @@ export function registerExtraMessagePolicy(api, options = {}) { api.on("before_message_write", createNativeOptOutGuard(cfg.privacy.discordOptOut, cfg.privacy.discordAgentAccounts), { priority: 1000 }); + // Classify native provenance synchronously: message_received is fire-and-forget + // and a reduced dispatch hook can run before any awaited work completes. This + // guild cache never uses legacy model/session parent inference. + const classifyScope = (event = {}, ctx = {}) => { + const route = scopeRoute(event, ctx); + route.guildId ||= routeGuildId(event, ctx); + const key = route.accountId && route.channelId ? `${route.accountId}:${route.channelId}` : ""; + if (key && route.guildId) { + state.scopeGuilds.set(key, route.guildId); + while (state.scopeGuilds.size > 5000) state.scopeGuilds.delete(state.scopeGuilds.keys().next().value); + } else if (key) route.guildId = state.scopeGuilds.get(key) || ""; + let scope = activeChannelScope(cfg.discordChannelScopes, event, { ...ctx, guildId: route.guildId }); + if (scope && !route.guildId) { + const accountScopes = cfg.discordChannelScopes.filter(item => item.accountId === route.accountId); + const identities = [ctx.agentId, ctx.AgentId, event.agentId, event.AgentId, + ...[ctx.sessionKey, ctx.SessionKey, event.sessionKey, event.SessionKey] + .map(session => typeof session === "string" ? session.match(/^agent:([^:]+):/)?.[1] : "")] + .filter(Boolean); + const sessions = [ctx.sessionKey, ctx.SessionKey, event.sessionKey, event.SessionKey].filter(Boolean); + const consistentChannels = sessions.every(session => { + const channelId = typeof session === "string" ? session.match(/:channel:([^:]+)/)?.[1] : ""; + return !channelId || channelId === route.channelId; + }); + const recognized = Object.hasOwn(api.config?.agents?.entries || {}, route.agentId) || + api.config?.agents?.list?.some(agent => agent.id === route.agentId); + // A configured unrelated agent may retain its legacy guildless behavior. + // Missing scope identities or conflicting native identities cannot bypass. + if (recognized && route.channelId && consistentChannels && identities.length && identities.every(id => id === route.agentId) && + accountScopes.length && accountScopes.every(item => item.agentIds.length && !item.agentIds.includes(route.agentId) && !item.channelIds.includes(route.channelId))) scope = undefined; + } + return { scope, route }; + }; + + // This cache contains only mandatory transport provenance. Legacy response + // routing may infer parents from model sessions and must never populate it. const checkScope = async (event = {}, ctx = {}) => { - const routed = withRememberedDiscordRoute(state, event, ctx); - if (!activeChannelScope(cfg.discordChannelScopes, routed.event, routed.ctx)) return { allowed: true, protected: false }; - const currentConfig = api.runtime?.config?.current?.() || api.config || {}; - const hydrated = await withHydratedDiscordParent(state, routed.event, routed.ctx, currentConfig, api.logger); - const admission = admitChannelScope(cfg.discordChannelScopes, hydrated.event, hydrated.ctx); - // Only admitted provenance is retained; a rejected quote must never poison a - // later turn's route cache or authorize recall/model execution. - if (admission.allowed) rememberDiscordRoute(state, hydrated.event, hydrated.ctx); - return admission; + const { scope, route } = classifyScope(event, ctx); + if (!scope) return { allowed: true, protected: false }; + const denied = { allowed: false, protected: true, scope, route }; + if ((scope.agentIds.length && !scope.agentIds.includes(route.agentId)) || + route.accountId !== scope.accountId || !route.channelId || + (route.guildId && route.guildId !== scope.guildId)) return denied; + const key = `${scope.accountId}:${scope.guildId}:${route.channelId}`; + const cached = state.scopeRoutes.get(key); + if (cached) { + route.guildId ||= cached.guildId; + route.parentChannelId ||= cached.parentChannelId; + } + if (!route.guildId || (!scope.channelIds.includes(route.channelId) && + !scope.channelIds.includes(route.parentChannelId))) { + const currentConfig = api.runtime?.config?.current?.() || api.config || {}; + if (!state.scopeLookups.has(key)) { + const lookup = fetchDiscordScopeChannel(route.channelId, scope, currentConfig) + .catch(() => null); + state.scopeLookups.set(key, lookup); + } + const pending = state.scopeLookups.get(key); + let verified; + try { verified = await pending; } + finally { if (state.scopeLookups.get(key) === pending) state.scopeLookups.delete(key); } + if (!verified) return denied; + route.guildId = verified.guildId; + route.parentChannelId = verified.parentChannelId; + } + const nativeCtx = { ...ctx, accountId: route.accountId, guildId: route.guildId, + channelId: route.channelId, parentChannelId: route.parentChannelId }; + const admission = admitChannelScope(cfg.discordChannelScopes, event, nativeCtx); + if (admission.allowed) { + state.scopeRoutes.set(key, { guildId: route.guildId, parentChannelId: route.parentChannelId }); + while (state.scopeRoutes.size > 5000) state.scopeRoutes.delete(state.scopeRoutes.keys().next().value); + } + return { ...admission, routed: { event, ctx: nativeCtx } }; }; api.on("before_tool_call", (event, ctx) => { @@ -984,8 +1075,8 @@ export function registerExtraMessagePolicy(api, options = {}) { }, { priority: 1000 }); const resolveEffectiveDecision = async (event = {}, ctx = {}, hook = "unknown") => { - const routed = withRememberedDiscordRoute(state, event, ctx); - const admission = await checkScope(routed.event, routed.ctx); + const admission = await checkScope(event, ctx); + const routed = admission.protected && admission.routed ? admission.routed : withRememberedDiscordRoute(state, event, ctx); if (!admission.allowed) return { hook, event: routed.event, ctx: routed.ctx, policy: { respond: false, ingestMode: "none", mentionRecall: false, matched: "mandatory:discord-channel-scope" }, @@ -1000,7 +1091,9 @@ export function registerExtraMessagePolicy(api, options = {}) { } const currentConfig = api.runtime?.config?.current?.() || api.config || {}; const currentPluginConfig = resolveCurrentPluginConfig(currentConfig, api.pluginConfig || {}); - const hydrated = await withHydratedDiscordParent(state, routed.event, routed.ctx, currentConfig, api.logger); + const hydrated = admission.protected + ? { ...routed, parentLookup: { status: "mandatory_verified", channelId: admission.route.channelId, parentChannelId: admission.route.parentChannelId } } + : await withHydratedDiscordParent(state, routed.event, routed.ctx, currentConfig, api.logger); if (hydrated !== routed) rememberDiscordRoute(state, hydrated.event, hydrated.ctx); const recalledMention = recalledMentionFact(state, hydrated.event, hydrated.ctx); let enriched = withDerivedMentionFact( @@ -1060,7 +1153,10 @@ export function registerExtraMessagePolicy(api, options = {}) { nativeStatus = null; } const policy = applyNativeMentionGatePolicy(effectivePolicy, nativeStatus, enriched.event, enriched.ctx); - if (admission.protected && admission.allowed) policy.channelScopeAdmission = 1; + if (admission.protected && admission.allowed) { + policy.channelScopeAdmission = 1; + policy.channelScopeRoute = admission.route; + } const mentionEvidence = describeMentionEvidence( hydrated.event, hydrated.ctx, @@ -1272,6 +1368,8 @@ export function registerExtraMessagePolicy(api, options = {}) { }, { priority: 1000 }); api.on("message_received", async (event, ctx) => { + const classification = classifyScope(event, ctx); + if (!classification.scope && routeGuildId(event, ctx)) rememberDiscordRoute(state, event, ctx); if (!(await checkScope(event, ctx)).allowed) return; if (isPolicyCommand(commandConfig, event, ctx) && !isDiscordOptedOut(event, ctx)) return; rememberDiscordRoute(state, event, ctx); diff --git a/plugins/openclaw/extra-message-policy/test/plugin-runtime.test.js b/plugins/openclaw/extra-message-policy/test/plugin-runtime.test.js index 5aa8500..4fb6da3 100644 --- a/plugins/openclaw/extra-message-policy/test/plugin-runtime.test.js +++ b/plugins/openclaw/extra-message-policy/test/plugin-runtime.test.js @@ -2480,3 +2480,126 @@ test('before_prompt_build scopes guidance using native agent context',async()=>{ assert.doesNotMatch(lab.appendSystemContext,/Use only search_raw_context/); assert.match(isolated.appendSystemContext,/Use only search_raw_context/); }); +test('first native thread claim admits parentConversationId with SecretRef and no route cache',async()=>{ + const accountId='public',guildId='111111111111111111',parentId='222222222222222222',threadId='333333333333333333'; + const sink=path.join(await mkdtemp(path.join(os.tmpdir(),'first-native-thread-')),'messages.jsonl'); + const harness=await createHarness({defaultPolicy:{respond:true,ingestMode:'all'},jsonlSink:{enabled:true,path:sink},discordChannelScopes:[{accountId,guildId,channelIds:[parentId],agentIds:['isolated']}]},{channels:{discord:{accounts:{public:{token:{source:'env',provider:'default',id:'TEST_TOKEN_REFERENCE'}}}}}}); + const sessionKey=`agent:isolated:discord:channel:${threadId}`; + const event={content:'first ordinary forum post',messageId:'native-first',sessionKey,threadId,metadata:{guildId,to:`channel:${threadId}`}}; + const ctx={channelId:'discord',accountId,conversationId:`channel:${threadId}`,sessionKey,agentId:'isolated'}; + await harness.emit('message_received',event,ctx); // This reduced hook has no ancestry yet. + assert.equal(await stat(sink).catch(()=>null),null); + const claimEvent={...event,parentConversationId:`channel:${parentId}`}; + const claimCtx={...ctx,parentConversationId:`channel:${parentId}`}; + assert.equal(await harness.emit('inbound_claim',claimEvent,claimCtx),undefined); + await harness.emit('message_received',event,ctx); + assert.equal(await harness.emit('before_dispatch',{content:event.content,messageId:'native-first'},ctx),undefined); + const rows=await readJsonl(sink);assert.equal(rows.length,1);assert.equal(rows[0].parentChannelId,parentId);assert.equal(rows[0].channelId,threadId);assert.equal(rows[0].channelScopeAdmission,1); + assert.equal(await harness.emit('before_agent_run',{accountId,channelId:threadId,prompt:'local'},ctx),undefined); + const outside=await createHarness({defaultPolicy:{respond:true,ingestMode:'all'},discordChannelScopes:[{accountId,guildId,channelIds:[parentId],agentIds:['isolated']}]}); + assert.deepEqual(await outside.emit('inbound_claim',{...event,parentConversationId:'channel:444444444444444444'},{...ctx,parentConversationId:'channel:444444444444444444'}),{handled:true}); +}); + +test('normal first-thread pipeline uses bounded metadata lookup without claim or prior cache',async(t)=>{ + const accountId='public',guildId='111111111111111111',parentId='222222222222222222',threadId='333333333333333333'; + const previousFetch=globalThis.fetch,previousEnv=process.env.EMP_TEST_SCOPE_TOKEN; + t.after(()=>{globalThis.fetch=previousFetch;if(previousEnv===undefined) delete process.env.EMP_TEST_SCOPE_TOKEN;else process.env.EMP_TEST_SCOPE_TOKEN=previousEnv;}); + process.env.EMP_TEST_SCOPE_TOKEN='synthetic-only';let calls=0; + globalThis.fetch=async(url,options)=>{calls++;assert.equal(url,`https://discord.com/api/v10/channels/${threadId}`);assert.equal(options.headers.authorization,'Bot synthetic-only');assert.ok(options.signal);await new Promise(r=>setTimeout(r,20));return {ok:true,json:async()=>({id:threadId,guild_id:guildId,parent_id:parentId,type:11})};}; + const sink=path.join(await mkdtemp(path.join(os.tmpdir(),'normal-native-thread-')),'messages.jsonl'); + const plugin={defaultPolicy:{respond:true,ingestMode:'all'},jsonlSink:{enabled:true,path:sink},discordChannelScopes:[{accountId,guildId,channelIds:[parentId],agentIds:['isolated']}]}; + const runtime={channels:{discord:{accounts:{public:{token:{source:'env',provider:'default',id:'EMP_TEST_SCOPE_TOKEN'}}}}}}; + const harness=await createHarness(plugin,runtime); + const sessionKey=`agent:isolated:discord:channel:${threadId}`; + const ctx={channelId:'discord',accountId,conversationId:threadId,sessionKey,agentId:'isolated'}; + const event={content:'first ordinary thread message',messageId:'normal-first',sessionKey,threadId,metadata:{guildId,to:`channel:${threadId}`}}; + const received=harness.emit('message_received',event,ctx); // Native fire-and-forget ordering. + assert.equal(await harness.emit('before_dispatch',{content:event.content,messageId:event.messageId},ctx),undefined); + assert.equal(await harness.emit('reply_dispatch',{ctx:{AccountId:accountId,GroupSpace:guildId,NativeChannelId:threadId,ThreadParentId:parentId,SessionKey:sessionKey,BodyForAgent:event.content}}),undefined); + assert.equal(await harness.emit('before_agent_run',{accountId,channelId:threadId,prompt:event.content},{accountId,channelId:threadId,sessionKey,agentId:'isolated'}),undefined); + await received; + const rows=await readJsonl(sink);assert.equal(rows.length,1);assert.equal(rows[0].source,'message_received');assert.equal(rows[0].parentChannelId,parentId);assert.equal(rows[0].channelScopeAdmission,1);assert.equal(calls,1); + // Full received/reply contexts alone expose media. Reduced dispatch must not + // write or consume dedupe before the received task has inspected it. + const mediaReceived=harness.emit('message_received',{...event,messageId:'media',media:[{path:'/synthetic-outside-media'}]},ctx); + assert.equal(await harness.emit('before_dispatch',{content:'attachment caption',messageId:'media'},ctx),undefined); + assert.equal((await harness.emit('reply_dispatch',{ctx:{AccountId:accountId,GroupSpace:guildId,NativeChannelId:threadId,ThreadParentId:parentId,SessionKey:sessionKey,BodyForAgent:'attachment caption',media:[{path:'/synthetic-outside-media'}]}})).handled,true); + await mediaReceived;assert.equal((await readJsonl(sink)).length,1); + // Legacy model-parent inference cannot promote mandatory scope provenance. + globalThis.fetch=async()=>({ok:false,status:403}); + const denied=await createHarness(plugin,runtime); + const weak={...ctx,ModelParentSessionKey:`agent:isolated:discord:channel:${parentId}`}; + assert.deepEqual(await denied.emit('before_dispatch',{content:'unverified'},weak),{handled:true}); +}); + +test('mandatory metadata lookup fails closed on identity/guild/type/parent errors and invalid SecretRefs',async(t)=>{ + const previousFetch=globalThis.fetch,previousEnv=process.env.EMP_TEST_SCOPE_TOKEN;t.after(()=>{globalThis.fetch=previousFetch;if(previousEnv===undefined) delete process.env.EMP_TEST_SCOPE_TOKEN;else process.env.EMP_TEST_SCOPE_TOKEN=previousEnv;});process.env.EMP_TEST_SCOPE_TOKEN='synthetic-only'; + const accountId='public',guildId='111111111111111111',parentId='222222222222222222',threadId='333333333333333333'; + const plugin={defaultPolicy:{respond:true,ingestMode:'all'},discordChannelScopes:[{accountId,guildId,channelIds:[parentId],agentIds:['isolated']}]}; + const valid={id:threadId,guild_id:guildId,parent_id:parentId,type:11};const ctx={accountId,channelId:'discord',conversationId:threadId,agentId:'isolated'};const event={content:'normal',metadata:{guildId}}; + const runtime=binding=>({channels:{discord:{accounts:{public:{token:binding}}}}});const binding={source:'env',provider:'default',id:'EMP_TEST_SCOPE_TOKEN'}; + for(const change of [{id:parentId},{guild_id:'444444444444444444'},{parent_id:'444444444444444444'},{type:0}]){ + globalThis.fetch=async()=>({ok:true,json:async()=>({...valid,...change})});const h=await createHarness(plugin,runtime(binding));assert.deepEqual(await h.emit('before_dispatch',event,ctx),{handled:true}); + } + let calls=0;globalThis.fetch=async()=>{calls++;throw new Error('unexpected lookup');}; + for(const change of [{provider:'other'},{source:'exec'},{id:'BAD-ID'},{id:'EMP_ABSENT_SCOPE_TOKEN'}]){const h=await createHarness(plugin,runtime({...binding,...change}));assert.deepEqual(await h.emit('before_dispatch',event,ctx),{handled:true});} + assert.equal(calls,0); + // An unrelated guild never invokes the new mandatory resolver. + const lab=await createHarness(plugin,runtime(binding));assert.equal(await lab.emit('before_dispatch',event,{...ctx,guildId:'444444444444444444',agentId:'lab'}),undefined);assert.equal(calls,0); +}); + +test('fire-and-forget Lab received preserves synchronous legacy routing for reduced dispatch',async()=>{ + const accountId='public',guildId='444444444444444444',channelId='555555555555555555'; + const plugin={defaultPolicy:{respond:false,ingestMode:'none'},policies:[{guildId,channelId,respond:true,ingestMode:'none'}],discordChannelScopes:[{accountId,guildId:'111111111111111111',channelIds:['222222222222222222'],agentIds:['isolated']}]}; + const ctx={accountId,channelId:'discord',conversationId:channelId,agentId:'lab',sessionKey:`agent:lab:discord:channel:${channelId}`}; + for(const scoped of [false,true]) for(const runtime of [{},{agents:{entries:{lab:{}}}}]){ + const harness=await createHarness({...plugin,discordChannelScopes:scoped?plugin.discordChannelScopes:[]},runtime); + const received=harness.emit('message_received',{content:'normal',messageId:'lab-native',metadata:{guildId}},ctx); + assert.equal(await harness.emit('before_dispatch',{content:'normal',messageId:'lab-native'},ctx),undefined,`scoped=${scoped}`); + await received; + } +}); + +test('uncached recognized guildless Lab dispatch matches unscoped baseline without rewriting context',async()=>{ + const accountId='public',channelId='555555555555555555'; + const scope={accountId,guildId:'111111111111111111',channelIds:['222222222222222222'],agentIds:['isolated']}; + const ctx={accountId,channelId:'discord',conversationId:channelId,agentId:'lab',sessionKey:`agent:lab:discord:channel:${channelId}`}; + for(const agents of [{entries:{lab:{}}},{list:[{id:'lab'}]}]) for(const respond of [false,true]){ + const config={defaultPolicy:{respond,ingestMode:'none'}}; + const baseline=await createHarness(config,{agents}); + const scoped=await createHarness({...config,discordChannelScopes:[scope]},{agents}); + assert.deepEqual(await scoped.emit('before_dispatch',{content:'normal'},ctx),await baseline.emit('before_dispatch',{content:'normal'},ctx)); + } +}); + +test('guildless scope classification fails closed for unknown or inconsistent identities',async()=>{ + const accountId='public',channelId='555555555555555555'; + const scope={accountId,guildId:'111111111111111111',channelIds:['222222222222222222'],agentIds:['isolated']}; + const ctx={accountId,channelId:'discord',conversationId:channelId,agentId:'lab',sessionKey:`agent:lab:discord:channel:${channelId}`}; + const config={defaultPolicy:{respond:true,ingestMode:'none'},discordChannelScopes:[scope]}; + const runtime={agents:{entries:{lab:{},isolated:{}}}}; + for(const change of [{agentId:'unknown',sessionKey:`agent:unknown:discord:channel:${channelId}`},{agentId:undefined,sessionKey:undefined},{sessionKey:`agent:isolated:discord:channel:${channelId}`},{sessionKey:'agent:lab:discord:channel:666666666666666666'},{agentId:'toString',sessionKey:`agent:toString:discord:channel:${channelId}`}]){ + const h=await createHarness(config,runtime);assert.deepEqual(await h.emit('before_dispatch',{content:'normal'},{...ctx,...change}),{handled:true}); + } + const noIds=await createHarness({...config,discordChannelScopes:[{...scope,agentIds:[]}]},runtime); + assert.deepEqual(await noIds.emit('before_dispatch',{content:'normal'},ctx),{handled:true}); + const wrongAgent=await createHarness(config,runtime); + assert.deepEqual(await wrongAgent.emit('before_dispatch',{content:'normal',metadata:{guildId:scope.guildId}},{...ctx,conversationId:scope.channelIds[0]}),{handled:true}); + const wrongAccount=await createHarness(config,runtime); + const isolated={...ctx,agentId:'isolated',sessionKey:`agent:isolated:discord:channel:${channelId}`,accountId:'other'}; + assert.deepEqual(await wrongAccount.emit('before_dispatch',{content:'normal'},isolated),{handled:true}); +}); + + +test('trusted guild classification is account-local and known protected roots reject wrong agents',async()=>{ + const accountId='public',guildId='111111111111111111',rootId='222222222222222222',channelId='555555555555555555'; + const config={defaultPolicy:{respond:true,ingestMode:'none'},discordChannelScopes:[{accountId,guildId,channelIds:[rootId],agentIds:['isolated']}]}; + const harness=await createHarness(config,{agents:{entries:{lab:{}}}}); + const ctx={accountId,channelId:'discord',conversationId:channelId,agentId:'lab',sessionKey:`agent:lab:discord:channel:${channelId}`}; + await harness.emit('message_received',{content:'lab',metadata:{guildId:'444444444444444444'}},{...ctx,accountId:'other'}); + // Neither another account's native classification nor a registered Lab identity + // can override the protected account's explicit root or protected guild. + assert.deepEqual(await harness.emit('before_dispatch',{content:'normal'},{...ctx,agentId:'unknown',sessionKey:`agent:unknown:discord:channel:${channelId}`}),{handled:true}); + assert.deepEqual(await harness.emit('before_dispatch',{content:'normal'},{...ctx,conversationId:rootId,sessionKey:`agent:lab:discord:channel:${rootId}`}),{handled:true}); + assert.deepEqual(await harness.emit('before_dispatch',{content:'normal',metadata:{guildId}},{...ctx,conversationId:rootId,sessionKey:`agent:lab:discord:channel:${rootId}`}),{handled:true}); +});