feat(routing): engage modes + sender scope + accumulate/drop + per-agent fan-out

Replaces the opaque trigger_rules JSON + response_scope enum on
messaging_group_agents with four explicit orthogonal columns:

    engage_mode            'pattern' | 'mention' | 'mention-sticky'
    engage_pattern         regex source; required when mode='pattern';
                           '.' is the "always" sentinel
    sender_scope           'all' | 'known'
    ignored_message_policy 'drop' | 'accumulate'

Inbound routing becomes a fan-out — every wired agent is evaluated
independently. A match gets its own session + container wake. A miss
with accumulate keeps the message as context-only (trigger=0) in that
agent's session, so when the agent does eventually engage it sees the
prior chatter.

## Schema

- Migration 010 (`engage-modes`): adds the 4 new columns, backfills
  from trigger_rules.pattern + requiresTrigger + response_scope, drops
  the legacy columns.
- messages_in gains `trigger INTEGER NOT NULL DEFAULT 1` (session DB
  schema + `migrateMessagesInTable` forward-compat).
- countDueMessages gates waking on `trigger = 1`.

## Routing

- `pickAgent` (returns one) → loop over all wired agents. Per agent:
  evaluate engage_mode; run access gate + sender-scope gate; on full
  match → resolveSession + writeSessionMessage(trigger=1) + wake. On
  miss with accumulate → writeSessionMessage(trigger=0), no wake. On
  miss with drop → skip.
- New `findSessionForAgent(agentGroupId, mgId, threadId)` scopes
  session lookup by agent so fan-out doesn't cross sessions.
- `messageIdForAgent` namespaces inbound message ids by agent_group_id
  so PRIMARY KEY doesn't collide across per-agent session DBs.

## Adapter layer

- `ConversationConfig` replaces `triggerPattern` + `requiresTrigger`
  with `engageMode` + `engagePattern`.
- Chat SDK bridge stores `Map<platformId, ConversationConfig[]>` (multi-
  agent per conversation) and applies union gating pre-onInbound:
    * onSubscribedMessage: engage if any wiring keeps firing in
      subscribed state (mention-sticky or pattern)
    * onNewMention: engage on mention; only subscribes the thread if
      at least one wiring is `mention-sticky`
    * onDirectMessage: engage per mode; sticky follows same rule
- Bridge no longer unconditionally calls `thread.subscribe()`.

## Sender scope

- Permissions module registers a second hook `setSenderScopeGate` that
  runs per-wiring after the existing access gate. `sender_scope='known'`
  requires canAccessAgentGroup(); `'all'` is a no-op. Not installed →
  no-op everywhere (default allow).

## Container side

- Host passes `NANOCLAW_MAX_MESSAGES_PER_PROMPT` (reuses existing
  MAX_MESSAGES_PER_PROMPT config; was dead code from v1).
- `getPendingMessages` queries `ORDER BY seq DESC LIMIT N`, reverses to
  chronological order for the prompt — accumulated context rides along
  with trigger rows up to the cap.
- `MessageInRow` gains `trigger: number` so the container can tell them
  apart in downstream code (container still processes both; only the
  host uses `trigger=0` for don't-wake).

## Defaults (per ACTION-ITEMS item 1 decision)

- DM (is_group=0): `engage_mode='pattern'`, `engage_pattern='.'` (always)
- Threaded group: `engage_mode='mention-sticky'` (seed-discord)
- Non-threaded group / CLI: pattern '.' in bootstrap scripts

## Tests

- src/host-core.test.ts: 3 new cases — fan-out (2 agents, 2 sessions,
  2 wakes), accumulate (trigger=0 + no wake), drop (no session created).
- Existing 10 host-core tests still pass.
- Migration 010 runs on an empty DB in 0-row path — verified.

Closes: ACTION-ITEMS items 1, 4.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
gavrielc
2026-04-20 01:30:04 +03:00
parent 6a815190c0
commit 16b9499532
22 changed files with 688 additions and 125 deletions

View File

@@ -199,8 +199,10 @@ describe('router', () => {
id: 'mga-1',
messaging_group_id: 'mg-1',
agent_group_id: 'ag-1',
trigger_rules: null,
response_scope: 'all',
engage_mode: 'pattern',
engage_pattern: '.',
sender_scope: 'all',
ignored_message_policy: 'drop',
session_mode: 'shared',
priority: 0,
created_at: now(),
@@ -295,6 +297,106 @@ describe('router', () => {
expect(rows).toHaveLength(2);
});
it('fans out to every matching agent, each in its own session', async () => {
const { routeInbound } = await import('./router.js');
const { wakeContainer } = await import('./container-runner.js');
(wakeContainer as unknown as ReturnType<typeof vi.fn>).mockClear();
// Wire a second agent to the same messaging group.
createAgentGroup({
id: 'ag-2',
name: 'Secondary Agent',
folder: 'secondary-agent',
agent_provider: null,
created_at: now(),
});
createMessagingGroupAgent({
id: 'mga-2',
messaging_group_id: 'mg-1',
agent_group_id: 'ag-2',
engage_mode: 'pattern',
engage_pattern: '.',
sender_scope: 'all',
ignored_message_policy: 'drop',
session_mode: 'shared',
priority: 0,
created_at: now(),
});
await routeInbound({
channelType: 'discord',
platformId: 'chan-123',
threadId: null,
message: { id: 'msg-fan', kind: 'chat', content: JSON.stringify({ text: 'hello all' }), timestamp: now() },
});
// Both agents should now have their own session and be woken.
expect(wakeContainer).toHaveBeenCalledTimes(2);
const { getSessionsByAgentGroup } = await import('./db/sessions.js');
expect(getSessionsByAgentGroup('ag-1')).toHaveLength(1);
expect(getSessionsByAgentGroup('ag-2')).toHaveLength(1);
});
it('accumulates without waking when engage fails + ignored_message_policy=accumulate', async () => {
const { routeInbound } = await import('./router.js');
const { wakeContainer } = await import('./container-runner.js');
(wakeContainer as unknown as ReturnType<typeof vi.fn>).mockClear();
// Replace the seed row with a mention-only wiring whose accumulate
// policy should store context even when the message doesn't mention us.
const { updateMessagingGroupAgent } = await import('./db/messaging-groups.js');
updateMessagingGroupAgent('mga-1', {
engage_mode: 'mention',
ignored_message_policy: 'accumulate',
});
await routeInbound({
channelType: 'discord',
platformId: 'chan-123',
threadId: null,
message: {
id: 'msg-nomatch',
kind: 'chat',
content: JSON.stringify({ text: 'no mention here' }),
timestamp: now(),
},
});
expect(wakeContainer).not.toHaveBeenCalled();
const session = findSession('mg-1', null);
expect(session).toBeDefined();
const db = new Database(inboundDbPath('ag-1', session!.id));
const rows = db.prepare('SELECT id, trigger FROM messages_in').all() as Array<{
id: string;
trigger: number;
}>;
db.close();
expect(rows).toHaveLength(1);
expect(rows[0].trigger).toBe(0);
});
it('drops silently when engage fails + ignored_message_policy=drop', async () => {
const { routeInbound } = await import('./router.js');
const { wakeContainer } = await import('./container-runner.js');
(wakeContainer as unknown as ReturnType<typeof vi.fn>).mockClear();
const { updateMessagingGroupAgent } = await import('./db/messaging-groups.js');
updateMessagingGroupAgent('mga-1', { engage_mode: 'mention' }); // drop is the default
await routeInbound({
channelType: 'discord',
platformId: 'chan-123',
threadId: null,
message: { id: 'msg-drop', kind: 'chat', content: JSON.stringify({ text: 'ignored' }), timestamp: now() },
});
expect(wakeContainer).not.toHaveBeenCalled();
// No session should have been created for this agent.
expect(findSession('mg-1', null)).toBeUndefined();
});
});
describe('delivery', () => {