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(byoa): carry Kanban briefs through wakes (#104)

OKNOTOK5b3a7bab330c
diff --git a/server/src/__integration__/agent-cli-side-effects.test.ts b/server/src/__integration__/agent-cli-side-effects.test.ts
index 903b433..96d965e 100644
--- a/server/src/__integration__/agent-cli-side-effects.test.ts
+++ b/server/src/__integration__/agent-cli-side-effects.test.ts
@@ -1,10 +1,11 @@
-import { test, before, beforeEach, after } from 'node:test'
+import { test, before, beforeEach, afterEach, after } from 'node:test'
import assert from 'node:assert/strict'
import { pool } from '../db/pool.js'
import {
ensureSchemaOnce, resetAllTables, seedCompanyWithAgent, teardownAll,
} from './_helpers.js'
import { runCli } from '../agents/cli.js'
+import { __setKanbanWakeAgentForTesting } from '../agents/kanban-wake.js'
before(async () => {
await ensureSchemaOnce()
@@ -14,6 +15,10 @@ beforeEach(async () => {
await resetAllTables()
})
+afterEach(() => {
+ __setKanbanWakeAgentForTesting(null)
+})
+
after(async () => {
await teardownAll()
})
@@ -240,3 +245,85 @@ test('[integration] kanban board/column/comment parity emits typed CLI side effe
visibleToUser: true,
}])
})
+
+test('[integration] every agent CLI Kanban wake carries its card brief', async () => {
+ const { companyId, agentId: actorId } = await seedCompanyWithAgent()
+ const targetId = `target-${Date.now().toString(36)}`
+ await pool.query(
+ `INSERT INTO participants (id, company_id, kind, name, role, initial, avatar_bg, status)
+ VALUES ($1, $2, 'agent', 'Target Agent', 'tester', 'T', '#abcdef', 'avail')`,
+ [targetId, companyId],
+ )
+
+ const wakes: Array<{
+ agentId: string
+ reason: string
+ conversationId: string | null
+ brief: { source?: string; title: string; body: string }
+ }> = []
+ __setKanbanWakeAgentForTesting(async (agentId, reason, conversationId, _steer, options) => {
+ wakes.push({ agentId, reason, conversationId, brief: options.backgroundBrief })
+ })
+ const waitForWakes = async (count: number): Promise<void> => {
+ for (let i = 0; i < 100 && wakes.length < count; i++) {
+ await new Promise((resolve) => setTimeout(resolve, 10))
+ }
+ assert.equal(wakes.length, count, `expected ${count} Kanban wake(s), got ${wakes.length}`)
+ }
+
+ const board = await runCli(['--as', actorId, 'kanban', 'create', 'Wake Board'])
+ assert.equal(board.ok, true, board.text)
+ const boardId = String(board.sideEffects?.[0]?.boardId ?? '')
+ const { rows: columns } = await pool.query<{ id: string }>(
+ `SELECT id FROM board_columns WHERE board_id = $1 ORDER BY position ASC LIMIT 1`,
+ [boardId],
+ )
+ const columnId = columns[0].id
+
+ const mentioned = await runCli([
+ '--as', actorId, 'card', 'add', boardId, `@${targetId} investigate`, '--column', columnId,
+ ])
+ assert.equal(mentioned.ok, true, mentioned.text)
+ const cardId = String(mentioned.sideEffects?.[0]?.cardId ?? '')
+ await waitForWakes(1)
+
+ const assigned = await runCli(['--as', actorId, 'card', 'assign', cardId, targetId])
+ assert.equal(assigned.ok, true, assigned.text)
+ await waitForWakes(2)
+
+ const edited = await runCli([
+ '--as', actorId, 'card', 'edit', cardId, '--description', `@${targetId} please revisit`,
+ ])
+ assert.equal(edited.ok, true, edited.text)
+ await waitForWakes(3)
+
+ const commented = await runCli([
+ '--as', actorId, 'card', 'comment', cardId, `@${targetId} new evidence`,
+ ])
+ assert.equal(commented.ok, true, commented.text)
+ await waitForWakes(4)
+
+ const createdAssigned = await runCli([
+ '--as', actorId, 'card', 'add', boardId, 'Assigned directly', '--column', columnId,
+ '--assign', targetId,
+ ])
+ assert.equal(createdAssigned.ok, true, createdAssigned.text)
+ await waitForWakes(5)
+
+ assert.deepEqual(wakes.map((wake) => ({
+ agentId: wake.agentId,
+ reason: wake.reason,
+ conversationId: wake.conversationId,
+ source: wake.brief.source,
+ })), Array.from({ length: 5 }, () => ({
+ agentId: targetId,
+ reason: 'manual',
+ conversationId: null,
+ source: 'kanban',
+ })))
+ for (const wake of wakes) {
+ assert.match(wake.brief.body, /card id: card-/)
+ assert.match(wake.brief.body, /board id: board-/)
+ assert.match(wake.brief.body, /cumora card claim card-/)
+ }
+})
diff --git a/server/src/__tests__/agents-wake-classify.test.ts b/server/src/__tests__/agents-wake-classify.test.ts
index 3106393..ee35c66 100644
--- a/server/src/__tests__/agents-wake-classify.test.ts
+++ b/server/src/__tests__/agents-wake-classify.test.ts
@@ -15,7 +15,7 @@
import { test } from 'node:test'
import assert from 'node:assert/strict'
-import { classifyWake } from '../agents/turn-wake.js'
+import { classifyWake, renderBriefedManualWakeContext } from '../agents/turn-wake.js'
const brief = { source: 'kanban', title: 'A board card was assigned to you', body: 'card id: card-1' }
@@ -66,3 +66,20 @@ test('a non-empty inbox runs regardless of how it was woken', () => {
// The guard only fires on an empty inbox; classification must not change that.
assert.equal(classifyWake({ trigger: 'message.new' }, 5).survivesEmptyInbox, false)
})
+
+test('a coalesced manual brief keeps unread conversation context visible', () => {
+ const context = renderBriefedManualWakeContext(
+ brief,
+ 'Conversation direct-1\n Pat: Please send the result',
+ 1,
+ )
+ assert.match(context, /card id: card-1/)
+ assert.match(context, /Pat: Please send the result/)
+ assert.doesNotMatch(context, /chat inbox is empty/i)
+})
+
+test('a brief-only manual wake explicitly acts without chat', () => {
+ const context = renderBriefedManualWakeContext(brief, '', 0)
+ assert.match(context, /chat inbox is empty/i)
+ assert.match(context, /act on THAT/i)
+})
diff --git a/server/src/__tests__/agents-wake-options.test.ts b/server/src/__tests__/agents-wake-options.test.ts
new file mode 100644
index 0000000..47a3161
--- /dev/null
+++ b/server/src/__tests__/agents-wake-options.test.ts
@@ -0,0 +1,132 @@
+/**
+ * Shared wake payload contract for managed Pods and BYOA daemons.
+ *
+ * Run: node --import tsx --test server/src/__tests__/agents-wake-options.test.ts
+ */
+import { test } from 'node:test'
+import assert from 'node:assert/strict'
+
+import { buildKanbanWakeBrief } from '../agents/kanban-wake.js'
+import {
+ mergeWakeBackgroundBriefs,
+ mergeWakeTurnOptions,
+ parseWakeData,
+ wakeHasActionableInput,
+} from '../agents/runtime/wake-options.js'
+
+test('manual Kanban wake preserves its brief and transport metadata', () => {
+ const parsed = parseWakeData(JSON.stringify({
+ kind: 'wake',
+ reason: 'manual',
+ conversationId: null,
+ at: 1234,
+ backgroundBrief: {
+ source: 'kanban',
+ title: 'A board card was assigned to you',
+ body: 'card id: card-1',
+ },
+ }))
+
+ assert.equal(parsed.conversationId, null)
+ assert.equal(parsed.at, 1234)
+ assert.equal(parsed.options.trigger, 'manual')
+ assert.deepEqual(parsed.options.backgroundBrief, {
+ source: 'kanban',
+ title: 'A board card was assigned to you',
+ body: 'card id: card-1',
+ })
+})
+
+test('a manual brief is actionable without any unread chat message', () => {
+ const brief = {
+ source: 'kanban',
+ title: 'A board card was assigned to you',
+ body: 'card id: card-1',
+ }
+ assert.equal(wakeHasActionableInput(false, brief), true)
+ assert.equal(wakeHasActionableInput(false, null), false)
+ assert.equal(wakeHasActionableInput(true, null), true)
+})
+
+test('coalesced manual wakes retain every assigned card', () => {
+ const first = {
+ source: 'kanban',
+ title: 'A board card was assigned to you',
+ body: 'card id: card-1',
+ }
+ const second = {
+ source: 'kanban',
+ title: 'You were mentioned in a board card comment',
+ body: 'card id: card-2',
+ }
+ const merged = mergeWakeBackgroundBriefs(first, second)
+ assert.ok(merged)
+ assert.equal(merged.source, 'kanban')
+ assert.match(merged.body, /card-1/)
+ assert.match(merged.body, /card-2/)
+})
+
+test('a manual card wake outranks message metadata in either coalescing order', () => {
+ const manual = {
+ trigger: 'manual' as const,
+ backgroundBrief: {
+ source: 'kanban',
+ title: 'A board card was assigned to you',
+ body: 'card id: card-1',
+ },
+ }
+ const message = { trigger: 'message.new' as const, triageNote: 'new direct message' }
+ for (const merged of [
+ mergeWakeTurnOptions(message, manual),
+ mergeWakeTurnOptions(manual, message),
+ ]) {
+ assert.equal(merged?.trigger, 'manual')
+ assert.equal(merged?.backgroundBrief?.body, 'card id: card-1')
+ assert.equal(merged?.triageNote, 'new direct message')
+ }
+})
+
+test('shared Kanban brief names the card and actionable CLI commands', () => {
+ const brief = buildKanbanWakeBrief({
+ boardId: 'board-1',
+ cardId: 'card-1',
+ columnId: 'todo',
+ title: 'Ship the migration',
+ what: 'A board card was assigned to you',
+ })
+
+ assert.equal(brief.source, 'kanban')
+ assert.match(brief.body, /Ship the migration/)
+ assert.match(brief.body, /card id: card-1/)
+ assert.match(brief.body, /board id: board-1/)
+ assert.match(brief.body, /column id: todo/)
+ assert.match(brief.body, /cumora card claim card-1/)
+ assert.match(brief.body, /cumora card comment card-1/)
+ assert.match(brief.body, /cumora card move card-1/)
+})
+
+test('malformed or oversized wake payloads cannot manufacture work', () => {
+ assert.deepEqual(parseWakeData('{broken'), {
+ conversationId: null,
+ at: null,
+ options: {},
+ })
+ assert.deepEqual(parseWakeData('x'.repeat(16_385)), {
+ conversationId: null,
+ at: null,
+ options: {},
+ })
+ const missingBody = parseWakeData(JSON.stringify({
+ reason: 'manual',
+ backgroundBrief: { title: 'not enough' },
+ }))
+ assert.equal(missingBody.options.trigger, 'manual')
+ assert.equal(missingBody.options.backgroundBrief, undefined)
+
+ const emptyBrief = parseWakeData(JSON.stringify({
+ reason: 'manual',
+ backgroundBrief: { title: ' ', body: '\n\t' },
+ }))
+ assert.equal(emptyBrief.options.backgroundBrief, undefined)
+ assert.equal(wakeHasActionableInput(false, { title: '', body: '' }), false)
+})
diff --git a/server/src/agents/cli.ts b/server/src/agents/cli.ts
index 6315fbf..920e782 100644
--- a/server/src/agents/cli.ts
+++ b/server/src/agents/cli.ts
@@ -22,6 +22,7 @@ import {
parseMemoryPath,
} from './memory-scope.js'
import { memoryMetaForWrite, resolveMemoryWriteSource } from './memory-write.js'
+import { wakeKanbanAgents } from './kanban-wake.js'
// Every CLI result flows through ok()/err(), so scrubbing lone UTF-16 surrogates
// here means CLI output (read by agents as tool results) can never carry a split
@@ -4629,43 +4630,6 @@ async function publishBoardCli(args: {
})
}
-/** Same shape + intent as the REST helper: wake every agent in
- * `mentions` who lives in `companyId` and isn't the actor. Best-effort. */
-async function wakeMentionedAgentsCli(args: {
- companyId: string
- mentions: string[] | undefined
- actorId: string
-}): Promise<void> {
- // This function is invoked as `void wakeMentionedAgentsCli(...)` from
- // CLI command handlers (kanban/card/doc/calendar). Any throw here
- // becomes an unhandled rejection on the cumora-server process. Wrap
- // the whole body so a transient pool.query failure can't crash the
- // server — the CLI command itself has already succeeded; the wakes
- // are a best-effort side effect.
- try {
- if (!args.mentions || args.mentions.length === 0) return
- const targets = args.mentions.filter((id) => id !== args.actorId)
- if (targets.length === 0) return
- const { rows } = await pool.query<{ id: string }>(
- `SELECT id FROM participants
- WHERE kind = 'agent'
- AND company_id = $1
- AND id = ANY($2::text[])
- AND departed_at IS NULL`,
- [args.companyId, targets],
- )
- if (rows.length === 0) return
- const { wakeAgent } = await import('./scheduler.js')
- for (const r of rows) {
- wakeAgent(r.id, 'manual', null).catch((e) => {
- console.warn(`[kanban-cli] wake ${r.id} failed`, e instanceof Error ? e.message : e)
- })
- }
- } catch (err) {
- console.warn('[kanban-cli] wakeMentionedAgentsCli failed:', err instanceof Error ? err.message : err)
- }
-}
-
async function cmdBoard(parsed: ParsedArgs): Promise<CliResult> {
const op = parsed.positional[0] ?? 'ls'
const me = resolveAs(parsed)
@@ -5087,15 +5051,15 @@ async function cmdCard(parsed: ParsedArgs): Promise<CliResult> {
/** Look up the boardId behind a cardId AND verify it's in our tenant.
* Returns null if the card doesn't exist or is cross-tenant. */
- async function resolveCardBoard(cardId: string): Promise<{ boardId: string; columnId: string } | null> {
- const r = await pool.query<{ board_id: string; column_id: string; company_id: string }>(
- `SELECT c.board_id, c.column_id, b.company_id
+ async function resolveCardBoard(cardId: string): Promise<{ boardId: string; columnId: string; title: string } | null> {
+ const r = await pool.query<{ board_id: string; column_id: string; title: string; company_id: string }>(
+ `SELECT c.board_id, c.column_id, c.title, b.company_id
FROM board_cards c JOIN boards b ON b.id = c.board_id
WHERE c.id = $1 LIMIT 1`,
[cardId],
)
if (r.rows.length === 0 || r.rows[0].company_id !== companyId) return null
- return { boardId: r.rows[0].board_id, columnId: r.rows[0].column_id }
+ return { boardId: r.rows[0].board_id, columnId: r.rows[0].column_id, title: r.rows[0].title }
}
if (op === 'ls' || op === 'list') {
@@ -5204,9 +5168,21 @@ async function cmdCard(parsed: ParsedArgs): Promise<CliResult> {
await publishBoardCli({
companyId, kind: 'card.created', boardId, cardId: id, columnId, mentions, actorId: me,
})
- void wakeMentionedAgentsCli({ companyId, mentions, actorId: me })
+ void wakeKanbanAgents({
+ companyId, mentions, actorId: me,
+ card: {
+ boardId, cardId: id, columnId, title,
+ what: 'You were mentioned on a new board card',
+ },
+ })
if (assignee && assignee !== me) {
- void wakeMentionedAgentsCli({ companyId, mentions: [assignee], actorId: me })
+ void wakeKanbanAgents({
+ companyId, mentions: [assignee], actorId: me,
+ card: {
+ boardId, cardId: id, columnId, title,
+ what: 'A board card was assigned to you',
+ },
+ })
}
return ok(`added card ${id}: ${title}${mentions.length > 0 ? ` · mentions: ${mentions.map((m) => '@' + m).join(' ')}` : ''}`, [{
event: 'kanban.card_created',
@@ -5274,7 +5250,13 @@ async function cmdCard(parsed: ParsedArgs): Promise<CliResult> {
companyId, kind: 'card.updated', boardId: home.boardId, cardId, actorId: me,
})
if (assignee && assignee !== me) {
- void wakeMentionedAgentsCli({ companyId, mentions: [assignee], actorId: me })
+ void wakeKanbanAgents({
+ companyId, mentions: [assignee], actorId: me,
+ card: {
+ boardId: home.boardId, cardId, columnId: home.columnId, title: home.title,
+ what: 'A board card was assigned to you',
+ },
+ })
}
return ok(assignee ? `assigned card ${cardId} → @${assignee}` : `unassigned card ${cardId}`, [{
event: 'kanban.card_assigned',
@@ -5373,7 +5355,13 @@ async function cmdCard(parsed: ParsedArgs): Promise<CliResult> {
await publishBoardCli({
companyId, kind: 'card.updated', boardId: home.boardId, cardId, mentions, actorId: me,
})
- void wakeMentionedAgentsCli({ companyId, mentions, actorId: me })
+ void wakeKanbanAgents({
+ companyId, mentions, actorId: me,
+ card: {
+ boardId: home.boardId, cardId, columnId: home.columnId, title: nextTitle,
+ what: 'You were mentioned on a board card',
+ },
+ })
return ok(`updated card ${cardId}${mentions.length > 0 ? ` · mentions: ${mentions.map((m) => '@' + m).join(' ')}` : ''}`, [{
event: 'kanban.card_updated',
command: op === 'rename' ? 'card rename' : 'card edit',
@@ -5406,7 +5394,13 @@ async function cmdCard(parsed: ParsedArgs): Promise<CliResult> {
await publishBoardCli({
companyId, kind: 'comment.created', boardId: home.boardId, cardId, commentId: id, mentions, actorId: me,
})
- void wakeMentionedAgentsCli({ companyId, mentions, actorId: me })
+ void wakeKanbanAgents({
+ companyId, mentions, actorId: me,
+ card: {
+ boardId: home.boardId, cardId, columnId: home.columnId, title: home.title,
+ what: 'You were mentioned in a board card comment',
+ },
+ })
return ok(`commented on ${cardId}${mentions.length > 0 ? ` · mentions: ${mentions.map((m) => '@' + m).join(' ')}` : ''}`, [{
event: 'kanban.comment_created',
command: 'card comment',
diff --git a/server/src/agents/computer/daemon.ts b/server/src/agents/computer/daemon.ts
index 5aeee5a..5802341 100644
--- a/server/src/agents/computer/daemon.ts
+++ b/server/src/agents/computer/daemon.ts
@@ -27,6 +27,12 @@ import { promisify } from 'node:util'
const execFileP = promisify(execFile)
import { parseSseStream, wakeStreamWasStable } from '../runtime/sse-parse.js'
+import {
+ mergeWakeBackgroundBriefs,
+ parseWakeData,
+ wakeHasActionableInput,
+ type WakeBackgroundBrief,
+} from '../runtime/wake-options.js'
import { detectEnginesWithStatus, snapshotDetectedEngines, getAdapter, ENGINE_IDS, runEngineDoctor, type EngineId, type EngineSession, type EngineRunResult, type EngineUsage, type EngineHopReport } from './engine.js'
import { usageFromClaude, type TokenUsage } from '../cost.js'
import { parseTriage, finalizeTriage, isRateLimited } from '../triage-core.js'
@@ -1043,6 +1049,10 @@ class AgentRunner {
private engineBackoffUntil = 0
private stopped = false
private lastWakeConvo: string | null = null
+ /** Synthetic work delivered with a wake has no durable chat row. Preserve it
+ * across debounce/coalescing so a brief-only Kanban assignment can drive the
+ * next turn instead of falling into the empty-inbox cost gate. */
+ private pendingBackgroundBrief: WakeBackgroundBrief | null = null
/** Pre-turn debounce timer (see WAKE_DEBOUNCE_MS). Non-null = a turn is already
* scheduled to start shortly; further wakes fold into it instead of stacking. */
private wakeDebounceTimer: ReturnType<typeof setTimeout> | null = null
@@ -1733,6 +1743,31 @@ class AgentRunner {
).trimEnd()
}
+ /** Per-turn delta for a deliberate manual wake carrying its own work brief.
+ * Unlike a background agenda scan, this is already an actionable user/team
+ * assignment and must run even when there is no unread chat row. */
+ private manualBriefDelta(
+ brief: WakeBackgroundBrief,
+ memoryDigest: string,
+ inboxDigest: string,
+ roster?: string,
+ ): string {
+ return (
+ `Current time (UTC): ${new Date().toISOString()} — use this for any --at / deadline math.\n\n` +
+ `Someone just put this work on you directly. This is a deliberate manual action, not a scan or heartbeat, ` +
+ `so ACT on the brief even when the chat inbox is empty. Handle the work, or state plainly why you are not ` +
+ `the right owner; do not silently drop it.\n\n` +
+ `Brief: ${brief.title}\n` +
+ `Source: ${brief.source ?? 'manual'}\n\n` +
+ `${brief.body}\n\n` +
+ (inboxDigest
+ ? `Unread messages that arrived with this wake (also handle anything addressed to you):\n${inboxDigest}\n\n`
+ : '') +
+ (memoryDigest ? `Your memory index (global \`memory/MEMORY.md\` + current project, if any):\n${memoryDigest}\n\n` : '') +
+ (roster ? `Your team (use these ids for @mentions):\n${roster}\n` : '')
+ ).trimEnd()
+ }
+
/** Per-turn AGENDA delta — dynamic bits for a proactive board-work wake; the
* invariant mechanics live in the standing prompt. */
private agendaDelta(brief: string, memoryDigest: string, roster?: string): string {
@@ -1902,8 +1937,16 @@ class AgentRunner {
* wake ARMS a short timer; subsequent wakes within the window fold in (return
* early). When it fires we run ONE turn that snapshots ALL unread — so a burst
* becomes a single big-engine spawn. The poll path and SSE wakes route here. */
- private scheduleWake(reason: string, convo?: string | null): void {
+ private scheduleWake(
+ reason: string,
+ convo?: string | null,
+ backgroundBrief?: WakeBackgroundBrief | null,
+ ): void {
if (this.stopped) return
+ this.pendingBackgroundBrief = mergeWakeBackgroundBriefs(
+ this.pendingBackgroundBrief,
+ backgroundBrief,
+ )
if (this.busy) {
// A turn is already running. Coalesce as usual (the rerun re-reads the inbox),
// BUT if this wake is a DIRECT ping, STEER it into the running turn so the
@@ -1992,6 +2035,7 @@ class AgentRunner {
return
}
this.busy = true
+ let activeBackgroundBrief: WakeBackgroundBrief | null = null
try {
do {
this.pendingRerun = false
@@ -2023,6 +2067,8 @@ class AgentRunner {
// can't go stale the way a leftover wake value could.)
const wakeConvo = this.lastWakeConvo
this.lastWakeConvo = null
+ activeBackgroundBrief = this.pendingBackgroundBrief
+ this.pendingBackgroundBrief = null
// Snapshot what's unread BEFORE triaging, so triage provably sees a
// superset of what we may ack — a real task that lands during/after
// triage keeps a higher id, stays out of `seen`, and so survives to
@@ -2042,15 +2088,11 @@ class AgentRunner {
// the agent reads as dead: it can work for minutes — engine spawned, turn
// running — while the room shows nothing at all.
const convo = typingConversation(wakeConvo, seen)
- // HARD COST GATE (content-blind, fail-closed): if nothing unread is a
- // real human/agent message — empty, or system-only relays/status/
- // membership notices — NEVER run triage and NEVER spawn the big engine.
- // System chatter is not a task. Ack it so it stops re-triggering, go
- // available, and wait for genuine content. This is the daemon-side
- // backstop against the "stale-wake storm" (a recurring system message
- // that otherwise woke opus on every ~20s poll). The big brain is for
- // real content only — under no circumstances spend it on system noise.
- if (!hasReal) {
+ // HARD COST GATE (content-blind, fail-closed): system-only inbox noise
+ // is not a task. A validated manual backgroundBrief IS a task, though:
+ // Kanban assignment/mention wakes deliberately have no chat row, and
+ // dropping that SSE payload here was why BYOA cards stayed in Todo.
+ if (!wakeHasActionableInput(hasReal, activeBackgroundBrief)) {
await this.ackSeen(token, seen)
await runtimeBest(this.cfg.serverUrl, '/status', token, { status: 'avail' })
// No per-tick log: this is the idle steady state (every poll × agent),
@@ -2060,7 +2102,10 @@ class AgentRunner {
await this.maybeAgendaTurn(token)
continue
}
- const triage = await this.inboxTriage(token)
+ // A deliberate manual brief is already actionable, just like the cloud
+ // `briefedManual` path. Only ordinary inbox wakes need the small-brain
+ // triage decision.
+ const triage = activeBackgroundBrief ? null : await this.inboxTriage(token)
const triageMs = Date.now() - turnStart // ensureToken + snapshot + triage
// Triage was rate-limited → STOP. Do NOT retry, do NOT wake the big brain,
// do NOT ack (the message is retried after the cooldown). Back off
@@ -2117,7 +2162,10 @@ class AgentRunner {
// routing, one-of-us claimReply, mechanical direct-post, relay turn-claim —
// was the divergence that broke chains and is GONE. Cost backstops remain:
// the actionable gate above + the per-minute activation rate floor.
- console.log(`[computer] ${this.agent.id} turn START (${reason}) — triage ${triageMs}ms, spawning ${this.adapter.id}${convo ? ` for ${convo}` : ''}`)
+ const gateLabel = activeBackgroundBrief
+ ? `manual brief ${activeBackgroundBrief.source ?? 'unknown'}`
+ : `triage ${triageMs}ms`
+ console.log(`[computer] ${this.agent.id} turn START (${reason}) — ${gateLabel}, spawning ${this.adapter.id}${convo ? ` for ${convo}` : ''}`)
await runtimeBest(this.cfg.serverUrl, '/status', token, { status: 'thinking' })
// "<agent> is typing…" in the conversation that woke us, refreshed
// while the engine works (BYOA runs can be long), cleared at the end.
@@ -2146,7 +2194,18 @@ class AgentRunner {
// first poster's message; preflight previously saw "nothing newer."
}
const run = (await runtimeBest(this.cfg.serverUrl, '/runs', token, {
- trigger: { source: 'byoa', engine: this.adapter.id },
+ trigger: {
+ source: activeBackgroundBrief ? 'byoa-manual' : 'byoa',
+ engine: this.adapter.id,
+ ...(activeBackgroundBrief
+ ? {
+ backgroundBrief: {
+ source: activeBackgroundBrief.source ?? 'manual',
+ title: activeBackgroundBrief.title,
+ },
+ }
+ : {}),
+ },
})) as { runId?: string } | null
// Pin runId so per-hop ledger rows link back to this turn (see
// maybeAgendaTurn for the same hook).
@@ -2171,6 +2230,7 @@ class AgentRunner {
console.log(`[computer] ${this.agent.id} big-brain sem acquired (queue depth was ${semQueueDepth + 1} including self)`)
}
try {
+ const turnBackgroundBrief = activeBackgroundBrief
const [memoryDigest, triageNote, roster] = await Promise.all([
this.memoryDigest(projectIds),
Promise.resolve(this.formatTriageNote(triage)),
@@ -2186,7 +2246,10 @@ class AgentRunner {
const session = this.ensureEngineSession()
// Standing scaffold rides the session's system-prompt file; send only the
// small per-turn delta when it does (else inline it — see turnPrompt).
- const prompt = this.turnPrompt(session, this.chatDelta(memoryDigest, triageNote, digest, roster))
+ const delta = turnBackgroundBrief
+ ? this.manualBriefDelta(turnBackgroundBrief, memoryDigest, digest, roster)
+ : this.chatDelta(memoryDigest, triageNote, digest, roster)
+ const prompt = this.turnPrompt(session, delta)
if (session) {
// PERSISTENT path: feed this turn into the long-lived process — no cold
// start (the first turn paid it; turns 2..N reuse the booted process).
@@ -2293,6 +2356,13 @@ class AgentRunner {
usage: turnUsage ? usageFromClaude(turnUsage) : null,
})
}
+ if (engineError && activeBackgroundBrief) {
+ this.pendingBackgroundBrief = mergeWakeBackgroundBriefs(
+ activeBackgroundBrief,
+ this.pendingBackgroundBrief,
+ )
+ }
+ activeBackgroundBrief = null
// Clean turn → ack everything this turn saw. If the engine replied it
// already advanced these cursors (monotonic ack is a no-op then); if it
// read the room and chose silence, this is what stops the same inbox
@@ -2308,6 +2378,13 @@ class AgentRunner {
reason = 'rerun (coalesced wake)'
} while (this.pendingRerun && !this.stopped)
} catch (err) {
+ if (activeBackgroundBrief) {
+ this.pendingBackgroundBrief = mergeWakeBackgroundBriefs(
+ activeBackgroundBrief,
+ this.pendingBackgroundBrief,
+ )
+ activeBackgroundBrief = null
+ }
// A turn-level failure — token mint 502 (e.g. a server pod rolling), a
// runtime hiccup, a transient network drop — must NEVER escape and crash
// the daemon, which would take EVERY hosted agent offline at once. Log it
@@ -2345,20 +2422,20 @@ class AgentRunner {
// sees the relay with full memory of its place — so it continues
// the sequence instead of racing on a stale snapshot. A steer that
// lands while busy is coalesced into exactly one rerun (pendingRerun).
- let convo: string | null = null
- let deliveryMs: number | null = null
- try {
- const d = evt.data ? (JSON.parse(evt.data) as { conversationId?: string; at?: number }) : {}
- convo = typeof d.conversationId === 'string' ? d.conversationId : null
- // evt.at = server's publish time. The gap to now is the
- // server→daemon delivery latency (the first place to look when
- // "receiving a message is slow"). Includes any client/server clock
- // skew, so read it as a trend, not an absolute.
- if (typeof d.at === 'number') deliveryMs = Date.now() - d.at
- if (convo) this.lastWakeConvo = convo
- } catch { /* malformed payload — ignore */ }
- console.log(`[computer] ${this.agent.id} SSE ${evt.event} received${convo ? ` convo=${convo}` : ''}${deliveryMs != null ? ` deliveryLatency=${deliveryMs}ms` : ''}`)
- this.scheduleWake(`sse-${evt.event}`, convo)
+ const wake = parseWakeData(evt.data)
+ const convo = wake.conversationId
+ const backgroundBrief = evt.event === 'wake' && wake.options.trigger === 'manual'
+ ? wake.options.backgroundBrief ?? null
+ : null
+ // evt.at = server's publish time. The gap to now is the
+ // server→daemon delivery latency (the first place to look when
+ // "receiving a message is slow"). Includes any client/server clock
+ // skew, so read it as a trend, not an absolute.
+ const deliveryMs = wake.at === null ? null : Date.now() - wake.at
+ if (convo) this.lastWakeConvo = convo
+ const trigger = wake.options.trigger ? `:${wake.options.trigger}` : ''
+ console.log(`[computer] ${this.agent.id} SSE ${evt.event}${trigger} received${convo ? ` convo=${convo}` : ''}${backgroundBrief ? ` brief=${backgroundBrief.source ?? 'manual'}` : ''}${deliveryMs != null ? ` deliveryLatency=${deliveryMs}ms` : ''}`)
+ this.scheduleWake(`sse-${evt.event}${trigger}`, convo, backgroundBrief)
}
// 'ready' is a no-op keepalive.
}
diff --git a/server/src/agents/kanban-wake.ts b/server/src/agents/kanban-wake.ts
new file mode 100644
index 0000000..d48049d
--- /dev/null
+++ b/server/src/agents/kanban-wake.ts
@@ -0,0 +1,83 @@
+import type { WakeBackgroundBrief } from './runtime/wake-options.js'
+
+export interface KanbanWakeCard {
+ boardId: string
+ cardId: string
+ columnId?: string | null
+ title?: string | null
+ what: string
+}
+
+export function buildKanbanWakeBrief(card: KanbanWakeCard): WakeBackgroundBrief {
+ const title = card.title?.slice(0, 200) || null
+ return {
+ source: 'kanban',
+ title: card.what.slice(0, 200),
+ body: [
+ title ? `Card: ${title}` : null,
+ `card id: ${card.cardId}`,
+ `board id: ${card.boardId}`,
+ card.columnId ? `column id: ${card.columnId}` : null,
+ '',
+ 'Drive it with the board tools rather than only replying in chat:',
+ ` cumora card claim ${card.cardId}`,
+ ` cumora card comment ${card.cardId} "<progress / evidence>"`,
+ ` cumora card move ${card.cardId} <column_id>`,
+ '',
+ 'If the work finishes here, leave the card in a state that says so — a board that still reads Todo while the work is done is worse than no board.',
+ ].filter((line) => line !== null).join('\n').slice(0, 12_000),
+ }
+}
+
+type KanbanWakeAgent = (
+ agentId: string,
+ reason: 'manual',
+ conversationId: null,
+ steerPayload: null,
+ options: { backgroundBrief: WakeBackgroundBrief },
+) => Promise<void>
+
+let wakeAgentForTesting: KanbanWakeAgent | null = null
+
+/** Test seam for proving CLI/REST actions reach the scheduler with the complete
+ * brief. Production always leaves this null and dynamically loads scheduler. */
+export function __setKanbanWakeAgentForTesting(fn: KanbanWakeAgent | null): void {
+ wakeAgentForTesting = fn
+}
+
+/** Wake every active agent named by a Kanban action. Both the REST router and
+ * agent CLI use this chokepoint so neither path can accidentally emit a bare
+ * manual wake: `card` is required and always becomes a background brief. */
+export async function wakeKanbanAgents(args: {
+ companyId: string
+ mentions: string[] | undefined
+ actorId: string
+ card: KanbanWakeCard
+}): Promise<void> {
+ try {
+ if (!args.mentions || args.mentions.length === 0) return
+ const targets = [...new Set(args.mentions)].filter((id) => id !== args.actorId)
+ if (targets.length === 0) return
+ const { pool } = await import('../db/pool.js')
+ const { rows } = await pool.query<{ id: string }>(
+ `SELECT id FROM participants
+ WHERE kind = 'agent'
+ AND company_id = $1
+ AND id = ANY($2::text[])
+ AND departed_at IS NULL`,
+ [args.companyId, targets],
+ )
+ if (rows.length === 0) return
+ const wakeAgent = wakeAgentForTesting ?? (await import('./scheduler.js')).wakeAgent
+ const backgroundBrief = buildKanbanWakeBrief(args.card)
+ for (const row of rows) {
+ void wakeAgent(row.id, 'manual', null, null, { backgroundBrief }).catch((err) => {
+ console.warn(`[kanban] wake ${row.id} failed`, err instanceof Error ? err.message : err)
+ })
+ }
+ } catch (err) {
+ // The board mutation has already committed. Wake delivery is best-effort,
+ // and a transient DB/Redis failure must not become an unhandled rejection.
+ console.warn('[kanban] wake agents failed:', err instanceof Error ? err.message : err)
+ }
+}
diff --git a/server/src/agents/runtime/pod-agent.ts b/server/src/agents/runtime/pod-agent.ts
index b42a1e0..678ebd7 100644
--- a/server/src/agents/runtime/pod-agent.ts
+++ b/server/src/agents/runtime/pod-agent.ts
@@ -35,6 +35,7 @@ import { notifyAlert } from '../../alerting.js'
import { pushSteer } from '../steer.js'
import { parseSseStream, wakeStreamWasStable } from './sse-parse.js'
import { decidePodExit } from './pod-agent-exit.js'
+import { mergeWakeTurnOptions, parseWakeData } from './wake-options.js'
interface RunnerState {
busy: boolean
@@ -61,102 +62,7 @@ const state: RunnerState = {
let pendingTurnOptions: AgentTurnOptions | null = null
function mergeTurnOptions(next: AgentTurnOptions | null): void {
- if (!next || Object.keys(next).length === 0) return
- if (next.trigger === 'background_scan') {
- pendingTurnOptions = next
- return
- }
- if (!pendingTurnOptions) {
- pendingTurnOptions = next
- return
- }
- pendingTurnOptions = { ...pendingTurnOptions, ...next }
-}
-
-function turnOptionsFromWakeData(raw: string | undefined): AgentTurnOptions {
- if (!raw || raw.length > 16_384) return {}
- try {
- const parsed = JSON.parse(raw) as {
- reason?: unknown
- idleReason?: unknown
- triageNote?: unknown
- backgroundBrief?: unknown
- pollBrief?: unknown
- }
- const reason = parsed.reason
- if (
- reason !== 'message.new' &&
- reason !== 'idle' &&
- reason !== 'manual' &&
- reason !== 'background_scan' &&
- reason !== 'poll.updated'
- ) return {}
- const out: AgentTurnOptions = { trigger: reason }
- if (reason === 'idle' && typeof parsed.idleReason === 'string') {
- out.idleReason = parsed.idleReason.slice(0, 500)
- }
- if (reason === 'message.new' && typeof parsed.triageNote === 'string') {
- out.triageNote = parsed.triageNote.slice(0, 1800)
- }
- if (reason === 'background_scan' && parsed.backgroundBrief && typeof parsed.backgroundBrief === 'object') {
- const brief = parsed.backgroundBrief as { title?: unknown; body?: unknown; source?: unknown }
- if (typeof brief.title === 'string' && typeof brief.body === 'string') {
- out.backgroundBrief = {
- title: brief.title.slice(0, 200),
- body: brief.body.slice(0, 12_000),
- source: typeof brief.source === 'string' ? brief.source.slice(0, 128) : undefined,
- }
- }
- }
- if (reason === 'poll.updated' && parsed.pollBrief && typeof parsed.pollBrief === 'object') {
- const brief = parsed.pollBrief as Record<string, unknown>
- const tallies = Array.isArray(brief.tallies) ? brief.tallies.slice(0, 20).flatMap((t) => {
- if (!t || typeof t !== 'object') return []
- const tt = t as Record<string, unknown>
- if (typeof tt.optionId !== 'string' || typeof tt.text !== 'string' || typeof tt.count !== 'number') return []
- const voters = Array.isArray(tt.voters) ? tt.voters.slice(0, 50).flatMap((v) => {
- if (!v || typeof v !== 'object') return []
- const vv = v as Record<string, unknown>
- if (typeof vv.id !== 'string') return []
- return [{ id: vv.id, name: typeof vv.name === 'string' ? vv.name : vv.id }]
- }) : []
- return [{ optionId: tt.optionId, text: tt.text.slice(0, 200), count: tt.count, voters }]
- }) : []
- const pending = Array.isArray(brief.pending) ? brief.pending.slice(0, 50).flatMap((p) => {
- if (!p || typeof p !== 'object') return []
- const pp = p as Record<string, unknown>
- if (typeof pp.id !== 'string') return []
- return [{ id: pp.id, name: typeof pp.name === 'string' ? pp.name : pp.id }]
- }) : []
- const actor = brief.actor && typeof brief.actor === 'object'
- ? brief.actor as Record<string, unknown>
- : { id: null, name: null }
- const phase = brief.phase === 'close' ? 'close' as const : 'vote' as const
- const status = brief.status === 'closed' ? 'closed' as const : 'open' as const
- if (typeof brief.messageId === 'string' && typeof brief.question === 'string') {
- out.pollBrief = {
- messageId: brief.messageId,
- conversationId: typeof brief.conversationId === 'string' ? brief.conversationId : '',
- question: brief.question.slice(0, 500),
- mode: brief.mode === 'multi' ? 'multi' : 'single',
- status,
- closedReason: brief.closedReason === 'expired' || brief.closedReason === 'manual' ? brief.closedReason : null,
- expiresAt: typeof brief.expiresAt === 'string' ? brief.expiresAt : null,
- totalVotes: typeof brief.totalVotes === 'number' ? brief.totalVotes : 0,
- tallies,
- pending,
- actor: {
- id: typeof actor.id === 'string' ? actor.id : null,
- name: typeof actor.name === 'string' ? actor.name : null,
- },
- phase,
- }
- }
- }
- return out
- } catch {
- return {}
- }
+ pendingTurnOptions = mergeWakeTurnOptions(pendingTurnOptions, next)
}
async function drain(agentId: string, options: AgentTurnOptions | null = null): Promise<void> {
@@ -221,7 +127,7 @@ async function connectStream(agentId: string, url: string, token: string): Promi
// Fire-and-forget: drain() handles re-entrancy + serialization.
// We don't `await` here because the stream itself must keep
// pulling so we don't miss subsequent events while a turn runs.
- void drain(agentId, turnOptionsFromWakeData(evt.data))
+ void drain(agentId, parseWakeData(evt.data).options)
continue
}
if (evt.event === 'steer') {
diff --git a/server/src/agents/runtime/wake-options.ts b/server/src/agents/runtime/wake-options.ts
new file mode 100644
index 0000000..b1c5efe
--- /dev/null
+++ b/server/src/agents/runtime/wake-options.ts
@@ -0,0 +1,200 @@
+import type { AgentTurnOptions } from '../turn.js'
+
+const MAX_WAKE_PAYLOAD_CHARS = 16_384
+const MAX_BRIEF_TITLE_CHARS = 200
+const MAX_BRIEF_BODY_CHARS = 12_000
+const MAX_BRIEF_SOURCE_CHARS = 128
+
+export type WakeBackgroundBrief = NonNullable<AgentTurnOptions['backgroundBrief']>
+
+export interface ParsedWakeData {
+ conversationId: string | null
+ at: number | null
+ options: AgentTurnOptions
+}
+
+export function parseWakeBackgroundBrief(value: unknown): WakeBackgroundBrief | null {
+ if (!value || typeof value !== 'object') return null
+ const brief = value as { title?: unknown; body?: unknown; source?: unknown }
+ if (typeof brief.title !== 'string' || typeof brief.body !== 'string') return null
+ const title = brief.title.trim()
+ const body = brief.body.trim()
+ if (!title || !body) return null
+ return {
+ title: title.slice(0, MAX_BRIEF_TITLE_CHARS),
+ body: body.slice(0, MAX_BRIEF_BODY_CHARS),
+ source: typeof brief.source === 'string'
+ ? brief.source.trim().slice(0, MAX_BRIEF_SOURCE_CHARS) || undefined
+ : undefined,
+ }
+}
+
+/** Parse the shared SSE wake envelope once for both managed Pods and BYOA
+ * daemons. Keeping this at the transport boundary prevents one runner from
+ * silently dropping fields that the scheduler already delivered. */
+export function parseWakeData(raw: string | undefined): ParsedWakeData {
+ const empty: ParsedWakeData = { conversationId: null, at: null, options: {} }
+ if (!raw || raw.length > MAX_WAKE_PAYLOAD_CHARS) return empty
+ try {
+ const parsed = JSON.parse(raw) as {
+ reason?: unknown
+ conversationId?: unknown
+ at?: unknown
+ idleReason?: unknown
+ triageNote?: unknown
+ backgroundBrief?: unknown
+ pollBrief?: unknown
+ }
+ const envelope = {
+ conversationId: typeof parsed.conversationId === 'string'
+ ? parsed.conversationId.slice(0, 256)
+ : null,
+ at: typeof parsed.at === 'number' && Number.isFinite(parsed.at) ? parsed.at : null,
+ }
+ const reason = parsed.reason
+ if (
+ reason !== 'message.new' &&
+ reason !== 'idle' &&
+ reason !== 'manual' &&
+ reason !== 'background_scan' &&
+ reason !== 'poll.updated'
+ ) return { ...envelope, options: {} }
+
+ const options: AgentTurnOptions = { trigger: reason }
+ if (reason === 'idle' && typeof parsed.idleReason === 'string') {
+ options.idleReason = parsed.idleReason.slice(0, 500)
+ }
+ if (reason === 'message.new' && typeof parsed.triageNote === 'string') {
+ options.triageNote = parsed.triageNote.slice(0, 1800)
+ }
+ if (reason === 'manual' || reason === 'background_scan') {
+ const backgroundBrief = parseWakeBackgroundBrief(parsed.backgroundBrief)
+ if (backgroundBrief) options.backgroundBrief = backgroundBrief
+ }
+ if (reason === 'poll.updated' && parsed.pollBrief && typeof parsed.pollBrief === 'object') {
+ const brief = parsed.pollBrief as Record<string, unknown>
+ const tallies = Array.isArray(brief.tallies) ? brief.tallies.slice(0, 20).flatMap((t) => {
+ if (!t || typeof t !== 'object') return []
+ const tt = t as Record<string, unknown>
+ if (typeof tt.optionId !== 'string' || typeof tt.text !== 'string' || typeof tt.count !== 'number') return []
+ const voters = Array.isArray(tt.voters) ? tt.voters.slice(0, 50).flatMap((v) => {
+ if (!v || typeof v !== 'object') return []
+ const vv = v as Record<string, unknown>
+ if (typeof vv.id !== 'string') return []
+ return [{ id: vv.id, name: typeof vv.name === 'string' ? vv.name : vv.id }]
+ }) : []
+ return [{ optionId: tt.optionId, text: tt.text.slice(0, 200), count: tt.count, voters }]
+ }) : []
+ const pending = Array.isArray(brief.pending) ? brief.pending.slice(0, 50).flatMap((p) => {
+ if (!p || typeof p !== 'object') return []
+ const pp = p as Record<string, unknown>
+ if (typeof pp.id !== 'string') return []
+ return [{ id: pp.id, name: typeof pp.name === 'string' ? pp.name : pp.id }]
+ }) : []
+ const actor = brief.actor && typeof brief.actor === 'object'
+ ? brief.actor as Record<string, unknown>
+ : { id: null, name: null }
+ const phase = brief.phase === 'close' ? 'close' as const : 'vote' as const
+ const status = brief.status === 'closed' ? 'closed' as const : 'open' as const
+ if (typeof brief.messageId === 'string' && typeof brief.question === 'string') {
+ options.pollBrief = {
+ messageId: brief.messageId,
+ conversationId: typeof brief.conversationId === 'string' ? brief.conversationId : '',
+ question: brief.question.slice(0, 500),
+ mode: brief.mode === 'multi' ? 'multi' : 'single',
+ status,
+ closedReason: brief.closedReason === 'expired' || brief.closedReason === 'manual' ? brief.closedReason : null,
+ expiresAt: typeof brief.expiresAt === 'string' ? brief.expiresAt : null,
+ totalVotes: typeof brief.totalVotes === 'number' ? brief.totalVotes : 0,
+ tallies,
+ pending,
+ actor: {
+ id: typeof actor.id === 'string' ? actor.id : null,
+ name: typeof actor.name === 'string' ? actor.name : null,
+ },
+ phase,
+ }
+ }
+ }
+
+ return { ...envelope, options }
+ } catch {
+ return empty
+ }
+}
+
+/** Coalesce bursts without losing one assigned card. The debounce/rerun paths
+ * carry only one pending turn payload, so multiple briefs are folded into one
+ * bounded brief instead of letting the last wake overwrite the first. */
+export function mergeWakeBackgroundBriefs(
+ current: WakeBackgroundBrief | null | undefined,
+ next: WakeBackgroundBrief | null | undefined,
+): WakeBackgroundBrief | null {
+ if (!current) return next ?? null
+ if (!next) return current
+ if (
+ current.title === next.title &&
+ current.body === next.body &&
+ current.source === next.source
+ ) return current
+
+ const currentSection = `## ${current.title}\n${current.body}`
+ const nextSection = `## ${next.title}\n${next.body}`
+ const separator = '\n\n'
+ // Keep room for both sides even when one producer reaches the transport cap.
+ // Card/board ids are at the start of each generated section, so neither wake
+ // becomes unidentifiable after truncation.
+ const nextBudget = Math.min(
+ nextSection.length,
+ Math.floor((MAX_BRIEF_BODY_CHARS - separator.length) / 2),
+ )
+ const currentBudget = MAX_BRIEF_BODY_CHARS - separator.length - nextBudget
+ return {
+ title: current.title === next.title ? current.title : 'Multiple assigned board updates',
+ body: `${currentSection.slice(0, currentBudget)}${separator}${nextSection.slice(0, nextBudget)}`,
+ source: current.source === next.source ? current.source : undefined,
+ }
+}
+
+/** Merge wake options through the Pod's debounce/rerun slot. A manual card
+ * brief outranks message/scanner metadata because it has no durable inbox row;
+ * conversation activity is still loaded by the turn and rendered alongside it. */
+export function mergeWakeTurnOptions(
+ current: AgentTurnOptions | null,
+ next: AgentTurnOptions | null,
+): AgentTurnOptions | null {
+ if (!next || Object.keys(next).length === 0) return current
+ if (!current) return next
+ if (current.trigger === 'manual' || next.trigger === 'manual') {
+ const backgroundBrief = mergeWakeBackgroundBriefs(
+ current.trigger === 'manual' ? current.backgroundBrief : null,
+ next.trigger === 'manual' ? next.backgroundBrief : null,
+ )
+ return {
+ ...current,
+ ...next,
+ trigger: 'manual',
+ ...(backgroundBrief ? { backgroundBrief } : {}),
+ }
+ }
+ if (next.trigger === 'background_scan') return next
+ const backgroundBrief = mergeWakeBackgroundBriefs(
+ current.backgroundBrief,
+ next.backgroundBrief,
+ )
+ return {
+ ...current,
+ ...next,
+ ...(backgroundBrief ? { backgroundBrief } : {}),
+ }
+}
+
+/** A manual board brief is itself real work even when chat has no unread row. */
+export function wakeHasActionableInput(
+ hasRealInboxMessage: boolean,
+ backgroundBrief: WakeBackgroundBrief | null | undefined,
+): boolean {
+ return hasRealInboxMessage || Boolean(
+ backgroundBrief?.title.trim() && backgroundBrief.body.trim(),
+ )
+}
diff --git a/server/src/agents/turn-wake.ts b/server/src/agents/turn-wake.ts
index cbe9eb3..bd6aaa5 100644
--- a/server/src/agents/turn-wake.ts
+++ b/server/src/agents/turn-wake.ts
@@ -40,3 +40,26 @@ export function classifyWake(options: AgentTurnOptions, inboxCount: number): {
survivesEmptyInbox: idle || backgroundScan || pollUpdate || briefedManual,
}
}
+
+/** Render a deliberate manual brief without hiding chat that happened to arrive
+ * in the same debounce window. The old empty-inbox-only copy said the inbox was
+ * empty unconditionally, which could make a valid DM disappear behind a card
+ * assignment when both wakes coalesced. */
+export function renderBriefedManualWakeContext(
+ brief: NonNullable<AgentTurnOptions['backgroundBrief']>,
+ renderedConversationContext: string,
+ inboxCount: number,
+): string {
+ const inboxContext = inboxCount > 0
+ ? `This wake also contains unread conversation activity. Handle both the assignment and anything addressed to you:\n\n${renderedConversationContext}`
+ : 'Your chat inbox is empty; this wake exists because of the action above, so act on THAT rather than looking for a message to answer.'
+ return `Someone just put this on you directly — it is a deliberate human or teammate action, not a scan or a heartbeat.
+
+${brief.title || 'Assigned work'}
+
+${brief.body}
+
+${inboxContext}
+
+Handle the work, or say plainly why you are not the right owner. If you genuinely have nothing to do here, call set_turn_status({ status: "done", reason: "...", next_step: "" }) and explain — do not silently drop it.`
+}
diff --git a/server/src/agents/turn.ts b/server/src/agents/turn.ts
index b214a2d..917f834 100644
--- a/server/src/agents/turn.ts
+++ b/server/src/agents/turn.ts
@@ -114,7 +114,7 @@ interface InboxRow {
quoted: QuotedSummary | null
}
-import { classifyWake } from './turn-wake.js'
+import { classifyWake, renderBriefedManualWakeContext } from './turn-wake.js'
import { mentionedAgentIds } from './scheduler.js'
export interface AgentTurnOptions {
@@ -1858,7 +1858,7 @@ export async function runAgentTurn(agentId: string, options: AgentTurnOptions =
messageIds: inbox.map((m) => m.id),
messages: inbox.map(traceInboxMessage),
idleReason: isIdleWake ? options.idleReason ?? 'idle heartbeat' : undefined,
- backgroundBrief: isBackgroundScanWake
+ backgroundBrief: (isBackgroundScanWake || isBriefedManualWake)
? {
source: options.backgroundBrief?.source ?? 'scanner',
title: options.backgroundBrief?.title ?? 'Background scan',
@@ -2125,14 +2125,8 @@ export async function runAgentTurn(agentId: string, options: AgentTurnOptions =
const renderedConversationContext = renderContext(context, inbox.length, convoIds.length, textExcerpts, agentId)
const wakeContext = isPollUpdateWake && options.pollBrief
? renderPollUpdateWakeContext(options.pollBrief, renderedConversationContext)
- : isBriefedManualWake
- ? `Someone just put this on you directly — it is a deliberate human action, not a scan or a heartbeat.
-
-${options.backgroundBrief?.title ?? 'Assigned work'}
-
-${options.backgroundBrief?.body ?? ''}
-
-Your chat inbox is empty; this wake exists because of the action above, so act on THAT rather than looking for a message to answer. Handle the work, or say plainly why you are not the right owner. If you genuinely have nothing to do here, call set_turn_status({ status: "done", reason: "...", next_step: "" }) and explain — do not silently drop it.`
+ : isBriefedManualWake && options.backgroundBrief
+ ? renderBriefedManualWakeContext(options.backgroundBrief, renderedConversationContext, inbox.length)
: isBackgroundScanWake
? `You just got an internal background scan brief. This is not a user chat message, and there is no obligation to interrupt anyone.
diff --git a/server/src/api/router.ts b/server/src/api/router.ts
index 369c98e..134547f 100644
--- a/server/src/api/router.ts
+++ b/server/src/api/router.ts
@@ -10,6 +10,7 @@ import { env } from '../env.js'
import { startConvene, getActiveConvene } from '../agents/convene.js'
import { fetchImageBytes } from '../agents/image-fetcher.js'
import { getTriageEconomics, getWakeEconomics } from '../agents/observability.js'
+import { wakeKanbanAgents } from '../agents/kanban-wake.js'
import { BUSY_STATUS_LEASE_MS } from '../status.js'
import { notifyMessage, computeMessageRecipients } from '../push.js'
import { randomUUID, randomBytes, createHash, timingSafeEqual } from 'node:crypto'
@@ -4976,62 +4977,6 @@ async function publishBoardEvent(args: {
})
}
-/** For each id in `mentions` that resolves to an agent participant in
- * this workspace (and isn't the actor themselves), wake their pod. The
- * human side of the @-list is left alone — humans pick up mentions via
- * the WS event + the Boards UI chip. Best-effort: a failed wake just
- * logs and moves on; the agent's NEXT natural wake catches up. */
-async function wakeMentionedAgents(args: {
- companyId: string
- mentions: string[] | undefined
- actorId: string
- /** What on the board caused this wake. Without it the agent is woken with an
- * empty chat inbox and `runAgentTurn` returns before it looks at anything —
- * which is why an assigned card could sit in Todo while the work itself was
- * reported done in chat. The brief is what gives the turn something to act
- * on, and it names the ids so the agent can drive the card with
- * `cumora card …` rather than guess. */
- card?: { boardId: string; cardId: string; columnId?: string | null; title?: string | null; what: string }
-}): Promise<void> {
- if (!args.mentions || args.mentions.length === 0) return
- const targets = args.mentions.filter((id) => id !== args.actorId)
- if (targets.length === 0) return
- const { rows } = await pool.query<{ id: string }>(
- `SELECT id FROM participants
- WHERE kind = 'agent'
- AND company_id = $1
- AND id = ANY($2::text[])
- AND departed_at IS NULL`,
- [args.companyId, targets],
- )
- if (rows.length === 0) return
- const { wakeAgent } = await import('../agents/scheduler.js')
- const brief = args.card
- ? {
- source: 'kanban',
- title: args.card.what,
- body: [
- args.card.title ? `Card: ${args.card.title}` : null,
- `card id: ${args.card.cardId}`,
- `board id: ${args.card.boardId}`,
- args.card.columnId ? `column id: ${args.card.columnId}` : null,
- '',
- 'Drive it with the board tools rather than only replying in chat:',
- ` cumora card claim ${args.card.cardId}`,
- ` cumora card comment ${args.card.cardId} "<progress / evidence>"`,
- ` cumora card move ${args.card.cardId} <column_id>`,
- '',
- 'If the work finishes here, leave the card in a state that says so — a board that still reads Todo while the work is done is worse than no board.',
- ].filter((l) => l !== null).join('\n'),
- }
- : undefined
- for (const r of rows) {
- void wakeAgent(r.id, 'manual', null, null, brief ? { backgroundBrief: brief } : {}).catch((e) => {
- console.warn(`[boards] wake ${r.id} failed`, e)
- })
- }
-}
-
/** GET /boards — list every board in the active workspace. */
api.get('/boards', async (req, res) => {
const { companyId } = await requireCompany(req)
@@ -5356,14 +5301,14 @@ api.post('/boards/:id/cards', async (req, res) => {
await publishBoardEvent({
companyId, kind: 'card.created', boardId, cardId: id, columnId, mentions, actorId: me,
})
- void wakeMentionedAgents({
+ void wakeKanbanAgents({
companyId, mentions, actorId: me,
card: { boardId, cardId: id, columnId, title, what: 'You were mentioned on a new board card' },
})
// Assignment counts as a mention even without an @-token in prose:
// when you `assignee_id = someone`, that someone should know about it.
if (assigneeId && assigneeId !== me) {
- void wakeMentionedAgents({
+ void wakeKanbanAgents({
companyId, mentions: [assigneeId], actorId: me,
card: { boardId, cardId: id, columnId, title, what: 'A board card was assigned to you' },
})
@@ -5392,6 +5337,7 @@ api.patch('/boards/:bid/cards/:cid', async (req, res) => {
const params: unknown[] = []
let nextTitle = cur[0].title
let nextDesc = cur[0].description
+ let nextColumnId = cur[0].column_id
let columnChanged = false
if (typeof req.body?.title === 'string') {
nextTitle = req.body.title.trim().slice(0, 200)
@@ -5417,6 +5363,7 @@ api.patch('/boards/:bid/cards/:cid', async (req, res) => {
)
if (colCheck.rows.length === 0) throw new HttpError(404, 'column not found')
params.push(newCol); sets.push(`column_id = $${params.length}`)
+ nextColumnId = newCol
columnChanged = true
}
}
@@ -5440,17 +5387,23 @@ api.patch('/boards/:bid/cards/:cid', async (req, res) => {
kind: columnChanged ? 'card.moved' : 'card.updated',
boardId, cardId, mentions, actorId: me,
})
- void wakeMentionedAgents({
+ void wakeKanbanAgents({
companyId, mentions, actorId: me,
- card: { boardId, cardId, what: 'You were mentioned on a board card' },
+ card: {
+ boardId, cardId, columnId: nextColumnId, title: nextTitle,
+ what: 'You were mentioned on a board card',
+ },
})
// A re-assignment also wakes the new assignee.
if (typeof req.body?.assigneeId === 'string') {
const newAssignee = String(req.body.assigneeId).trim()
if (newAssignee && newAssignee !== me) {
- void wakeMentionedAgents({
+ void wakeKanbanAgents({
companyId, mentions: [newAssignee], actorId: me,
- card: { boardId, cardId, what: 'A board card was assigned to you' },
+ card: {
+ boardId, cardId, columnId: nextColumnId, title: nextTitle,
+ what: 'A board card was assigned to you',
+ },
})
}
}
@@ -5505,8 +5458,8 @@ api.post('/boards/:bid/cards/:cid/comments', async (req, res) => {
const { userId: me, companyId } = await requireBoardAccess(req, boardId)
const body = String(req.body?.body ?? '').trim().slice(0, 8000)
if (!body) throw new HttpError(400, 'body required')
- const card = await pool.query(
- `SELECT 1 FROM board_cards WHERE id = $1 AND board_id = $2 LIMIT 1`,
+ const card = await pool.query<{ title: string; column_id: string }>(
+ `SELECT title, column_id FROM board_cards WHERE id = $1 AND board_id = $2 LIMIT 1`,
[cardId, boardId],
)
if (card.rows.length === 0) throw new HttpError(404, 'not found')
@@ -5522,7 +5475,13 @@ api.post('/boards/:bid/cards/:cid/comments', async (req, res) => {
await publishBoardEvent({
companyId, kind: 'comment.created', boardId, cardId, commentId: id, mentions, actorId: me,
})
- void wakeMentionedAgents({ companyId, mentions, actorId: me })
+ void wakeKanbanAgents({
+ companyId, mentions, actorId: me,
+ card: {
+ boardId, cardId, columnId: card.rows[0].column_id, title: card.rows[0].title,
+ what: 'You were mentioned in a board card comment',
+ },
+ })
res.json({ id, mentions })
})