Skip to content

Where agent teams gather. Cross-platform team chat where AI agents are first-class teammates — with cloud or bring-your-own (Claude Code / Codex) brains.

TypeScript

fix(agents): do not spend scanner fingerprint when wake is dropped (#213)

cicada9a0a60dbbe6e
diff --git a/server/src/__integration__/agent-scanner.test.ts b/server/src/__integration__/agent-scanner.test.ts
index f58c522..c4f078b 100644
--- a/server/src/__integration__/agent-scanner.test.ts
+++ b/server/src/__integration__/agent-scanner.test.ts
@@ -89,6 +89,7 @@ test('[integration] background scanner wakes a capability-bearing agent through
}> = []
__setBackgroundScannerWakeForTesting(async (wokenAgentId, reason, wokenConversationId, _steer, options) => {
wakes.push({ agentId: wokenAgentId, reason, conversationId: wokenConversationId ?? null, options })
+ return true
})
await runBackgroundScans()
@@ -117,3 +118,39 @@ test('[integration] background scanner wakes a capability-bearing agent through
)
assert.equal(pulledGroups, 0, 'scanner itself must not create groups; only the agent may do that with tools')
})
+
+test('[integration] background scanner does not spend fingerprint or write audit log when wake drops', async () => {
+ const { agentId } = await seedCompanyWithScannerAgent()
+ let shouldDrop = true
+ let attempts = 0
+ __setBackgroundScannerWakeForTesting(async () => {
+ attempts++
+ if (shouldDrop) return false
+ return true
+ })
+
+ // First pass: dropped by budget
+ await runBackgroundScans()
+ assert.equal(attempts, 1)
+
+ const { rows: logsFirst } = await pool.query(
+ `SELECT 1 FROM agent_log WHERE agent_id = $1 AND body LIKE 'background scan wake queued%'`,
+ [agentId],
+ )
+ assert.equal(logsFirst.length, 0, 'no audit log should be written when wake was dropped')
+
+ // Second pass: budget allows
+ shouldDrop = false
+ await runBackgroundScans()
+ assert.equal(attempts, 2, 'scanner must retry on the next pass because fingerprint was not spent')
+
+ const { rows: logsSecond } = await pool.query(
+ `SELECT 1 FROM agent_log WHERE agent_id = $1 AND body LIKE 'background scan wake queued%'`,
+ [agentId],
+ )
+ assert.equal(logsSecond.length, 1, 'audit log should be written once wake succeeds')
+
+ // Third pass: should be deduplicated now
+ await runBackgroundScans()
+ assert.equal(attempts, 2, 'scanner must not wake again after successful scan')
+})
diff --git a/server/src/__tests__/agents-scanner-budget-retry.test.ts b/server/src/__tests__/agents-scanner-budget-retry.test.ts
new file mode 100644
index 0000000..289063e
--- /dev/null
+++ b/server/src/__tests__/agents-scanner-budget-retry.test.ts
@@ -0,0 +1,100 @@
+import { after, afterEach, beforeEach, test } from 'node:test'
+import assert from 'node:assert/strict'
+process.env.CUMORA_RUNTIME_CLIENT = 'http'
+process.env.OPENAI_API_KEY ??= 'mock-key'
+
+const { pool } = await import('../db/pool.js')
+const {
+ __setBackgroundScannerWakeForTesting,
+ _resetBackgroundScannerForTests,
+ runBackgroundScans,
+} = await import('../agents/scanner.js')
+
+const originalQuery = pool.query.bind(pool)
+
+after(async () => {
+ try { await pool.end() } catch { /* ignore */ }
+ try {
+ const { redis, sub } = await import('../redis.js')
+ redis.disconnect()
+ sub.disconnect()
+ } catch { /* ignore */ }
+})
+
+beforeEach(() => {
+ _resetBackgroundScannerForTests()
+})
+
+afterEach(() => {
+ _resetBackgroundScannerForTests()
+ ;(pool as unknown as { query: typeof originalQuery }).query = originalQuery
+})
+
+test('scanner does not spend fingerprint or record audit log when wake is dropped by budget', async () => {
+ const agent = {
+ id: 'agent-1',
+ name: 'Scanner Agent',
+ role: 'Watcher',
+ bio: null,
+ company_id: 'co-1',
+ }
+ const recent = [
+ { message_id: 'm1', conversation_id: 'c1', conversation_title: 'General', author_name: 'Alice', body: 'msg 1' },
+ { message_id: 'm2', conversation_id: 'c1', conversation_title: 'General', author_name: 'Bob', body: 'msg 2' },
+ { message_id: 'm3', conversation_id: 'c1', conversation_title: 'General', author_name: 'Alice', body: 'msg 3' },
+ { message_id: 'm4', conversation_id: 'c1', conversation_title: 'General', author_name: 'Bob', body: 'msg 4' },
+ { message_id: 'm5', conversation_id: 'c1', conversation_title: 'General', author_name: 'Alice', body: 'msg 5' },
+ { message_id: 'm6', conversation_id: 'c1', conversation_title: 'General', author_name: 'Bob', body: 'msg 6' },
+ { message_id: 'm7', conversation_id: 'c1', conversation_title: 'General', author_name: 'Alice', body: 'msg 7' },
+ { message_id: 'm8', conversation_id: 'c1', conversation_title: 'General', author_name: 'Bob', body: 'msg 8' },
+ ]
+ const auditLogs: any[] = []
+
+ ;(pool as unknown as { query: (sql: string, params?: unknown[]) => Promise<any> }).query = async (sql: string, params?: unknown[]) => {
+ if (sql.includes('FROM participants p')) {
+ return { rows: [agent] }
+ }
+ if (sql.includes('SELECT EXISTS')) {
+ return { rows: [{ exists: false }] }
+ }
+ if (sql.includes('FROM messages m')) {
+ return { rows: recent }
+ }
+ if (sql.includes('FROM participants') && sql.includes('departed_at IS NULL')) {
+ return { rows: [{ id: agent.id, name: agent.name, role: agent.role, kind: 'agent' }] }
+ }
+ if (sql.includes('INSERT INTO agent_log')) {
+ auditLogs.push(params)
+ return { rows: [] }
+ }
+ return { rows: [] }
+ }
+
+ let wakeCallCount = 0
+ let shouldDropWake = true
+
+ __setBackgroundScannerWakeForTesting(async () => {
+ wakeCallCount++
+ if (shouldDropWake) {
+ return false // simulate dropped wake (budget exceeded)
+ }
+ return true // simulate accepted wake
+ })
+
+ // First pass: wake is dropped by budget
+ await runBackgroundScans()
+ assert.equal(wakeCallCount, 1, 'wakeScannerAgent should have been attempted once')
+ assert.equal(auditLogs.length, 0, 'audit log must NOT be written when wake was dropped')
+
+ // Second pass with same messages: budget now permits (shouldDropWake = false).
+ // Because fingerprint was NOT spent, the agent must be re-evaluated and woken!
+ shouldDropWake = false
+ await runBackgroundScans()
+ assert.equal(wakeCallCount, 2, 'scanner must retry dropped activity on next pass')
+ assert.equal(auditLogs.length, 1, 'audit log is recorded on successful wake')
+
+ // Third pass with same messages: already scanned and wake succeeded.
+ // Now fingerprint IS spent, so it should be skipped.
+ await runBackgroundScans()
+ assert.equal(wakeCallCount, 2, 'scanner must not wake again once fingerprint was successfully spent')
+})
diff --git a/server/src/agents/idle.ts b/server/src/agents/idle.ts
index 1fc9e92..73bf7d2 100644
--- a/server/src/agents/idle.ts
+++ b/server/src/agents/idle.ts
@@ -30,7 +30,7 @@ import {
// integration tests use them to capture wake calls without actually
// spinning up a pod, and to make the agenda classifier deterministic
// without burning real LLM credits.
-type WakeFn = typeof wakeAgent
+type WakeFn = (...args: Parameters<typeof wakeAgent>) => Promise<unknown>
let wakeIdleAgent: WakeFn = wakeAgent
export function __setIdleWakeForTesting(fn: WakeFn | null): void {
wakeIdleAgent = fn ?? wakeAgent
diff --git a/server/src/agents/scanner.ts b/server/src/agents/scanner.ts
index bab490c..c14f2f6 100644
--- a/server/src/agents/scanner.ts
+++ b/server/src/agents/scanner.ts
@@ -21,9 +21,12 @@ interface BackgroundScanAgent {
const PRECEDENT_SCANS = new Set<string>()
-let wakeScannerAgent: typeof wakeAgent = wakeAgent
+type WakeScannerAgentFn = typeof wakeAgent
-export function __setBackgroundScannerWakeForTesting(fn: typeof wakeAgent | null): void {
+let wakeScannerAgent: WakeScannerAgentFn = wakeAgent
+let scannerRunning = false
+
+export function __setBackgroundScannerWakeForTesting(fn: WakeScannerAgentFn | null): void {
wakeScannerAgent = fn ?? wakeAgent
}
const SCANNER_MIN_MESSAGES = 8
@@ -33,6 +36,7 @@ const BACKGROUND_SCAN_CAPABILITIES = ['background.scan']
export function _resetBackgroundScannerForTests(): void {
PRECEDENT_SCANS.clear()
wakeScannerAgent = wakeAgent
+ scannerRunning = false
}
async function loadBackgroundScanAgents(): Promise<BackgroundScanAgent[]> {
@@ -178,6 +182,7 @@ async function recordScanWake(agent: BackgroundScanAgent, fingerprint: string):
export async function runBackgroundScans(): Promise<void> {
const agents = await loadBackgroundScanAgents()
+ const inFlight = new Set<string>()
for (const agent of agents) {
try {
if (await agentHasUnreadInbox(agent.id)) continue
@@ -186,20 +191,30 @@ export async function runBackgroundScans(): Promise<void> {
if (recent.length < SCANNER_MIN_MESSAGES) continue
const fingerprint = `${agent.company_id}|${agent.id}|${recent.map((r) => r.message_id).sort().join('|')}`
- if (PRECEDENT_SCANS.has(fingerprint)) continue
- PRECEDENT_SCANS.add(fingerprint)
-
- const roster = await loadRoster(agent.company_id)
- const brief = buildBackgroundScanBrief({ agent, roster, recent })
- await recordScanWake(agent, fingerprint)
- const backgroundBrief: NonNullable<AgentTurnOptions['backgroundBrief']> = {
- source: 'background_scanner',
- title: 'Recent company activity scan',
- body: brief,
+ if (PRECEDENT_SCANS.has(fingerprint) || inFlight.has(fingerprint)) continue
+ inFlight.add(fingerprint)
+
+ try {
+ const roster = await loadRoster(agent.company_id)
+ const brief = buildBackgroundScanBrief({ agent, roster, recent })
+ const backgroundBrief: NonNullable<AgentTurnOptions['backgroundBrief']> = {
+ source: 'background_scanner',
+ title: 'Recent company activity scan',
+ body: brief,
+ }
+ const woken = await wakeScannerAgent(agent.id, 'background_scan', null, null, {
+ backgroundBrief,
+ })
+ if (woken === false) {
+ // Budget exceeded or wake dropped — do not record or spend the fingerprint,
+ // so the next pass can re-evaluate as intended.
+ continue
+ }
+ PRECEDENT_SCANS.add(fingerprint)
+ await recordScanWake(agent, fingerprint)
+ } finally {
+ inFlight.delete(fingerprint)
}
- await wakeScannerAgent(agent.id, 'background_scan', null, null, {
- backgroundBrief,
- })
} catch (e) {
console.warn(`[scanner] background scan failed for ${agent.id}`, e)
}
@@ -209,6 +224,15 @@ export async function runBackgroundScans(): Promise<void> {
/** Periodic kick — call from server boot. */
export function startScanner(intervalMs: number): NodeJS.Timeout {
return setInterval(() => {
- runBackgroundScans().catch((e) => console.error('[scanner]', e))
+ if (scannerRunning) {
+ console.warn('[scanner] previous background scan pass still running — skipping tick')
+ return
+ }
+ scannerRunning = true
+ runBackgroundScans()
+ .catch((e) => console.error('[scanner]', e))
+ .finally(() => {
+ scannerRunning = false
+ })
}, intervalMs)
}
diff --git a/server/src/agents/scheduler.ts b/server/src/agents/scheduler.ts
index f179700..2684d63 100644
--- a/server/src/agents/scheduler.ts
+++ b/server/src/agents/scheduler.ts
@@ -213,7 +213,7 @@ export async function wakeAgent(
conversationId: string | null = null,
steerPayload: SteerWakePayload | null = null,
options: WakeOptions = {},
-): Promise<void> {
+): Promise<boolean> {
return wakeOne(agentId, reason, conversationId, steerPayload, options)
}
@@ -334,12 +334,12 @@ async function wakeOne(
steerPayload: SteerWakePayload | null = null,
options: WakeOptions = {},
retryAttempt: number = 0,
-): Promise<void> {
+): Promise<boolean> {
// Synthetic wakes can be dropped under load — the next idle tick
// or next scanner pass will re-evaluate. Real wakes never are.
if ((reason === 'idle' || reason === 'background_scan') && !_consumeLowPriorityWakeBudget()) {
console.warn(`[scheduler] ${agentId} ${reason} wake dropped: budget ${LOW_PRIORITY_WAKE_BUDGET_PER_MIN}/min exceeded`)
- return
+ return false
}
// Execution placement is an authorization decision, not a nullable hint.
@@ -383,13 +383,13 @@ async function wakeOne(
let host: ResolvedAgentHost | null = null
if (options.placementTriage) {
host = await resolveHostForWake()
- if (!host) return
+ if (!host) return false
// BYOA daemons triage locally. Managed Agents are gated before a live-pod
// wake or a new Pod; the flag is serialized into retries so recovery cannot
// bypass the same placement + triage contract.
if (!isByoaKind(host.kind) && reason === 'message.new' && !options.triageNote) {
const verdict = await triageWakeRecipient(agentId, options.triageTarget ?? null)
- if (!verdict) return
+ if (!verdict) return false
options = { ...options, ...verdict }
}
}
@@ -462,11 +462,11 @@ async function wakeOne(
}
}
- if (delivered > 0) return
+ if (delivered > 0) return true
if (!host) {
host = await resolveHostForWake()
- if (!host) return
+ if (!host) return false
}
// BYOA agents run on a user-paired Computer (the `cumora agent computer`
@@ -477,7 +477,7 @@ async function wakeOne(
// Skip the pod path entirely; do NOT ensurePod / wake-retry kubectl.
if (isByoaKind(host.kind)) {
console.log(`[scheduler] ${agentId} is BYOA (${host.kind}); daemon offline — wake deferred to reconnect`)
- return
+ return true
}
// Free tier is BYOA-only: it must NEVER spin a managed Cumora Cloud pod. A free
@@ -490,7 +490,7 @@ async function wakeOne(
// up separately. The wake stays durable in the inbox for whenever they pair.
if (host.tier === 'free') {
console.log(`[scheduler] ${agentId} is free-tier (BYOA-only); no managed pod — wake deferred until paired`)
- return
+ return true
}
// Paid (pro/max) managed agent — spin up a Pod. The Pod will catch up on first
@@ -519,7 +519,7 @@ async function wakeOne(
r.reason,
r.code === 'placement_lookup_failed' ? 'host_resolution' : 'ensure_pod',
)
- return
+ return false
} else if (r.reason === 'already pending' || r.reason === 'already running') {
await scheduleWakeRetry(agentId, reason, conversationId, steerPayload, options, retryAttempt + 1, r.reason)
}
@@ -533,10 +533,12 @@ async function wakeOne(
while (Date.now() < deadline) {
await new Promise((resolve) => setTimeout(resolve, 500))
const replayed = await deliverWake(agentId, wakePayload).catch(() => 0)
- if (replayed > 0) return
+ if (replayed > 0) return true
}
console.warn(`[scheduler] ${agentId} synthetic wake (${reason}) was not delivered after pod start`)
+ return false
}
+ return true
}
/** Multi-instance dedup: every cumora-server replica subscribes to