diff --git a/ds-bot/src/host/card-gate.js b/ds-bot/src/host/card-gate.js index b07b57eb01..2b5b902c05 100644 --- a/ds-bot/src/host/card-gate.js +++ b/ds-bot/src/host/card-gate.js @@ -8,9 +8,15 @@ // PLAN-APPROVED turns the sub-agent's plan mode off with no card. // // What stays open: a Main Bot's own cards, every turn the user typed, a request -// whose audience is the user, a card whose option is the production approval -// (the production guard only reads the transcript of the Bot that runs the -// command), and a job whose text carries CARD-IT-YOURSELF. +// whose audience is the user, and a job whose text carries CARD-IT-YOURSELF. A +// card whose option is the production approval is never opened by that token: +// deploy approval always goes back to the manager, who cards Steve and mints the +// approval for the Bot that runs the merge. Interactive show_view cards follow +// the same rules as ask_user. Every card decided in a Bot's Session is logged +// with the reason that decided it. +// +// A plan release (PLAN-APPROVED, an ORDER line) is honoured from a Main Bot, or +// from the admin of a group the receiving Bot is a member of. // // DSH_CARD_GATE=off turns all of it off. @@ -45,42 +51,92 @@ export const planTitle = (plan) => { const senderOf = (rt, info) => rt.botOf?.(info?.senderSessionId)?.name ?? info?.senderName ?? 'the Bot that sent this job' /** - * The gate's view of the turn running in a Session: undefined when the turn is not - * one a Bot opened (no gate), else who runs it, who sent it, and whether it may card. + * Why the turn running in a Session is or is not gated: `reason` is gate-off, + * not-bot-turn, main-bot, audience-user or gated; a gated turn also carries who + * runs it, who sent it, and whether it may card. */ -export function gatedTurn(rt, sessionId) { - if (!gateOn()) return undefined +export function turnGate(rt, sessionId) { + if (!gateOn()) return { reason: 'gate-off' } const { state } = rt const entry = rt.live?.get(sessionId) const turn = entry?.turn - if (turn === undefined || !(state.exchangeTurns?.[sessionId] ?? []).includes(turn)) return undefined + if (turn === undefined || !(state.exchangeTurns?.[sessionId] ?? []).includes(turn)) return { reason: 'not-bot-turn' } const botId = rt.chatOwners?.get(sessionId) - if (botId === undefined || rt.isMain?.(botId)) return undefined + if (botId === undefined) return { reason: 'not-bot-turn' } + if (rt.isMain?.(botId)) return { reason: 'main-bot' } const info = entry.info // A request the user sees answered here is the user's turn as much as the Bot's. - if (info?.audience === 'user') return undefined + if (info?.audience === 'user') return { reason: 'audience-user' } const triggers = [{ info, text: entry.infoText }, ...(entry.joined ?? [])] const texts = triggers.flatMap(({ info: item, text }) => { const record = (state.exchanges ?? []).find(other => other.id === item?.exchangeId) return [text, record?.text].filter(value => typeof value === 'string') }) return { + reason: 'gated', bot: rt.botOf?.(botId)?.name ?? botId, manager: senderOf(rt, info), cardItYourself: texts.some(text => text.includes(CARD_IT_YOURSELF)), } } +/** The gated turn (see turnGate), or undefined when the gate does not apply. */ +export function gatedTurn(rt, sessionId) { + const gate = turnGate(rt, sessionId) + if (gate.reason !== 'gated') return undefined + const { reason: _reason, ...gated } = gate + return gated +} + export const cardRefusal = manager => `This job came from ${manager}. Do not card Steve: end your turn with a DECISION block for ${manager} (question, 2 to 4 options, the recommended one marked with its reason, Hold). ${manager} cards Steve and relays his answer.` export const planRefusal = manager => `This job came from ${manager}. Do not open a plan review for Steve here: send the full plan to ${manager} as a DECISION (Approve plan (Recommended) / Change it / Hold). When ${manager} relays approval with ${PLAN_APPROVED}, plan mode turns off for you.` +export const productionRefusal = manager => `This job came from ${manager}. A deploy approval never goes to Steve from here: send the deploy DECISION to ${manager}, naming the repo and the PR as #N. ${manager} cards Steve and mints the approval; then run gh pr merge --repo alone.` + +/** + * How the gate decides a card in this Session: `allowed`, `because` (the reason + * that decided it), the production label when one is offered, who runs the turn + * and who sent it, and the refusal text when it is refused. + */ +export function judgeCard(rt, sessionId, options) { + const label = (options ?? []).map(option => option?.label).find(isProductionLabel) + const gate = turnGate(rt, sessionId) + const botId = rt.chatOwners?.get(sessionId) + const named = { bot: gate.bot ?? rt.botOf?.(botId)?.name ?? botId ?? sessionId, ...(gate.manager !== undefined ? { manager: gate.manager } : {}), ...(label !== undefined ? { label } : {}) } + if (gate.reason !== 'gated') return { allowed: true, because: gate.reason, ...named } + if (label !== undefined) return { allowed: false, because: 'production-label', ...named, text: productionRefusal(gate.manager) } + if (gate.cardItYourself) return { allowed: true, because: 'card-it-yourself', ...named } + return { allowed: false, because: 'gated', ...named, text: cardRefusal(gate.manager) } +} + /** Whether ask_user in this Session is refused; the refusal text, or undefined. */ export function refuseCard(rt, sessionId, options) { - const gated = gatedTurn(rt, sessionId) - if (gated === undefined || gated.cardItYourself) return undefined - if ((options ?? []).some(option => isProductionLabel(option?.label))) return undefined - return { ...gated, text: cardRefusal(gated.manager) } + const judged = judgeCard(rt, sessionId, options) + return judged.allowed ? undefined : judged +} + +/** The labels a view offers the user, read from its options, confirm and submit parts. */ +export function viewLabels(view) { + const labels = [] + const walk = (node, depth = 0) => { + if (depth > 8 || node === null || typeof node !== 'object') return + if (Array.isArray(node)) { for (const item of node) walk(item, depth + 1); return } + if (node.type === 'options') for (const option of node.options ?? []) labels.push({ label: String(option?.label ?? '') }) + if (node.type === 'confirm') labels.push({ label: String(node.confirmLabel ?? '') }) + if (node.type === 'submit') labels.push({ label: String(node.label ?? '') }) + if (node.type === 'form') labels.push({ label: String(node.submitLabel ?? '') }) + for (const child of node.children ?? []) walk(child, depth + 1) + } + walk(view) + return labels +} + +/** Logs a card decision, so an allowed card can be traced as well as a refused one. */ +export function logCard(rt, tool, judged, title) { + if (!gateOn()) return + const { text: _text, ...entry } = judged + void logGate(rt, { ...entry, tool, title: String(title ?? '') }) } /** Whether exit_plan_mode in this Session is refused; the refusal text, or undefined. */ @@ -133,10 +189,12 @@ export function relayPlanApproval(rt, { fromId, toId, agent, text }) { const kind = releaseKind(text) if (kind === undefined) return undefined const log = (outcome) => { - void logGate(rt, { bot: rt.botOf?.(toId)?.name ?? toId, manager: rt.botOf?.(fromId)?.name ?? fromId ?? 'unknown', tool: kind, outcome }) + void logGate(rt, { bot: rt.botOf?.(toId)?.name ?? toId, manager: rt.botOf?.(fromId)?.name ?? fromId ?? 'unknown', tool: kind, outcome, ...(authority !== undefined ? { authority } : {}) }) } + let authority if (fromId !== undefined && fromId === toId) { log('self'); return undefined } - if (fromId === undefined || !rt.isMain?.(fromId)) { log('sender-not-main'); return undefined } + authority = releaseAuthority(rt, fromId, toId) + if (authority === undefined) { log('sender-not-manager'); return undefined } const planMode = planModeFor(rt, agent) if (planMode === undefined || agent === undefined) { log('no-plan-service'); return undefined } let outcome @@ -153,6 +211,19 @@ export function relayPlanApproval(rt, { fromId, toId, agent, text }) { return outcome } +/** + * Who may release a Bot's plan mode: 'main' for a Main Bot, 'group-admin' for the + * admin of a group the receiving Bot is a member of (a group admin is the manager + * Steve's routing names for that group's work), else undefined. + */ +export function releaseAuthority(rt, fromId, toId) { + if (fromId === undefined) return undefined + if (rt.isMain?.(fromId)) return 'main' + const rooms = Object.values(rt.state?.rooms ?? {}) + if (rooms.some(room => room?.admin === fromId && (room.members ?? []).includes(toId))) return 'group-admin' + return undefined +} + /** * The plan-mode service that serves this agent. Under an agent preset, plan mode * lives in the preset's isolated group (`isolate: planMode: true`), so a Host-realm @@ -218,5 +289,5 @@ export function ensurePlanOff(rt, agent, why, { fresh = false } = {}) { /** One line at start-up, so the log proves this code is the code that is running. */ export function announceGate(rt) { if (!gateOn()) return Promise.resolve() - return logGate(rt, { tool: 'gate-loaded', release: 'plan-approved+order', orderRelease: orderReleaseOn(), planDefaultOff: planDefaultOffOn(), lookup: 'agentPresets.serviceFor' }) + return logGate(rt, { tool: 'gate-loaded', release: 'plan-approved+order', releaseFrom: 'main+group-admin', cards: 'judged+logged', orderRelease: orderReleaseOn(), planDefaultOff: planDefaultOffOn(), lookup: 'agentPresets.serviceFor' }) } diff --git a/ds-bot/src/host/tools.js b/ds-bot/src/host/tools.js index 1d618f08b1..52e7264c91 100644 --- a/ds-bot/src/host/tools.js +++ b/ds-bot/src/host/tools.js @@ -3,7 +3,7 @@ import { randomUUID } from 'node:crypto' import { defineTool } from '@deepseek-ai/dsh-tools' import { readAvatar } from './avatar.js' -import { EXIT_PLAN_MODE, logGate, planTitle, refuseCard, refusePlan } from './card-gate.js' +import { EXIT_PLAN_MODE, judgeCard, logCard, logGate, planTitle, refusePlan, viewLabels } from './card-gate.js' import { COLORS, EXTRA_COLORS, MESSAGE_INLINE_MAX, ROOM_MODES, SOURCE_KIND } from './constants.js' import { within } from './folders.js' import { absoluteLinks } from './links.js' @@ -685,11 +685,9 @@ export function install(rt) { .slice(0, 6) if (options.length === 0) return 'Give at least one option.' // A job another Bot sent is decided by that Bot, in its own chat (card-gate.js). - const refused = refuseCard(rt, id, options) - if (refused !== undefined) { - void logGate(rt, { bot: refused.bot, manager: refused.manager, tool: 'ask_user', title: String(args.question ?? '') }) - return refused.text - } + const judged = judgeCard(rt, id, options) + logCard(rt, 'ask_user', judged, args.question) + if (!judged.allowed) return judged.text // A hidden Bot-to-Bot turn shows none of its calls, so its card goes to the // composer dock, which takes questions without a call. const turn = rt.live.get(id)?.turn @@ -763,6 +761,10 @@ Reason: ${why}` : ''}` if (checked.interactive && args.await_reply === false) return 'This view has controls to submit, so it waits for the user\'s answer; call show_view without await_reply: false.' const awaitReply = args.await_reply ?? checked.interactive if (!awaitReply) return 'The view is on screen.' + // An interactive view is a card like ask_user's, so the same gate decides it. + const judged = judgeCard(rt, id, viewLabels(view)) + logCard(rt, 'show_view', judged, title) + if (!judged.allowed) return judged.text // A hidden Bot-to-Bot turn shows none of its calls, so its card goes to the // composer dock, which takes a card without a call. const turn = rt.live.get(id)?.turn diff --git a/ds-bot/test/card-gate.test.js b/ds-bot/test/card-gate.test.js index 7ac225f5fe..c2ef3fd088 100644 --- a/ds-bot/test/card-gate.test.js +++ b/ds-bot/test/card-gate.test.js @@ -154,26 +154,44 @@ test('a request whose audience is the user cards as before', async (t) => { assert.equal(rt.state.questions.writer.question, 'Which name?') }) -test('the production approval card stays with the Bot that runs it', async (t) => { - const { rt, ask, fromBot, stop } = await start() +test('a production approval card in a job another Bot sent goes back to the manager', async (t) => { + const { rt, ask, fromBot, log, stop } = await start() t.after(stop) fromBot('coder', 'chief', 'Merge PR 12 when Steve approves') + const reply = await ask('coder', [{ label: 'deploy to production (Recommended)' }, { label: 'Hold' }]) + assert.match(reply, /^This job came from Chief. A deploy approval never goes to Steve from here: send the deploy DECISION to Chief, naming the repo and the PR as #N./) + assert.match(reply, /Chief cards Steve and mints the approval; then run gh pr merge --repo alone\.$/) + assert.equal(rt.state.questions.coder, undefined) + const [entry] = await anyLines(log) + assert.deepEqual([entry.tool, entry.allowed, entry.because, entry.label, entry.manager], ['ask_user', false, 'production-label', 'deploy to production (Recommended)', 'Chief']) + // CARD-IT-YOURSELF opens ordinary cards, never the production one. + fromBot('writer', 'chief', 'Ship it. CARD-IT-YOURSELF') + assert.match(await ask('writer', [{ label: 'Deploy to production' }, { label: 'Hold' }]), /^This job came from Chief. A deploy approval/) + assert.equal(rt.state.questions.writer, undefined) + // A look-alike label is an ordinary card: refused with the ordinary text. + fromBot('writer', 'chief', 'Ship it again') + assert.match(await ask('writer', [{ label: 'deploy to production now' }, { label: 'Hold' }]), /^This job came from Chief. Do not card Steve/) +}) + +test('the production approval card in a turn the user typed shows, and the log says why', async (t) => { + const { rt, ask, fromUser, log, stop } = await start() + t.after(stop) + fromUser('coder', 'Merge PR 12 when you are ready') assert.match(await ask('coder', [{ label: 'deploy to production (Recommended)' }, { label: 'Hold' }]), /card is on screen/) assert.ok(rt.state.questions.coder) - delete rt.state.questions.coder - fromBot('writer', 'chief', 'Ship it') - assert.match(await ask('writer', [{ label: 'Deploy to production' }, { label: 'Hold' }]), /card is on screen/) - // A look-alike label is not the approval. - fromBot('writer', 'chief', 'Ship it again') - assert.match(await ask('writer', [{ label: 'deploy to production now' }, { label: 'Hold' }]), /^This job came from Chief/) + const [entry] = await anyLines(log) + assert.deepEqual([entry.bot, entry.tool, entry.allowed, entry.because, entry.label], ['Coder', 'ask_user', true, 'not-bot-turn', 'deploy to production (Recommended)']) + assert.equal(entry.text, undefined) }) -test('CARD-IT-YOURSELF in the job lets the Bot card the user', async (t) => { - const { rt, ask, fromBot, stop } = await start() +test('CARD-IT-YOURSELF in the job lets the Bot card the user, and the log says so', async (t) => { + const { rt, ask, fromBot, log, stop } = await start() t.after(stop) fromBot('writer', 'chief', 'Ask the user for the name yourself. CARD-IT-YOURSELF') assert.match(await ask('writer'), /card is on screen/) assert.ok(rt.state.questions.writer) + const [entry] = await anyLines(log) + assert.deepEqual([entry.bot, entry.manager, entry.allowed, entry.because, entry.title], ['Writer', 'Chief', true, 'card-it-yourself', 'Which name?']) }) test('exit_plan_mode in a job another Bot sent is refused', async (t) => { @@ -201,7 +219,7 @@ test('PLAN-APPROVED from a Main Bot turns plan mode off', async (t) => { assert.equal(planMode.active.coder, false) assert.equal(delivered.length, 1) const [entry] = await anyLines(log) - assert.deepEqual([entry.bot, entry.manager, entry.tool, entry.outcome], ['Coder', 'Chief', 'plan-approved', 'committed']) + assert.deepEqual([entry.bot, entry.manager, entry.tool, entry.outcome, entry.authority], ['Coder', 'Chief', 'plan-approved', 'committed', 'main']) }) test('PLAN-APPROVED from a Bot that is not a Main Bot changes nothing', async (t) => { @@ -243,7 +261,7 @@ test('an ORDER from a Bot that is not a Main Bot changes nothing and says why', await rt.deliver({ fromId: 'writer', toId: 'coder', text: 'ORDER from Writer · job j-2 · decisions come back to me', role: 'request' }) assert.deepEqual(planMode.calls, []) const [entry] = await anyLines(log) - assert.deepEqual([entry.tool, entry.outcome], ['order', 'sender-not-main']) + assert.deepEqual([entry.tool, entry.outcome], ['order', 'sender-not-manager']) }) test('ORDER mid-text is not an order', async (t) => { @@ -408,3 +426,68 @@ test('DSH_PLAN_DEFAULT_OFF=off leaves plan mode alone', async (t) => { await rt.deliver({ fromId: 'writer', toId: 'coder', text: 'hello', role: 'request' }) assert.deepEqual(planMode.calls, []) }) + +// --- 2026-11-03: card routing to the manager (dsbot-card-routing-overlord) --- + +const PICK = { type: 'options', id: 'pick', options: [{ label: 'A' }, { label: 'B' }] } +const DEPLOY = { type: 'confirm', id: 'go', confirmLabel: 'deploy to production' } + +const showView = (rt, sessionId, args) => rt.teamTools.find(d => d.name === 'show_view').execute(args, { agent: { id: sessionId }, callId: 'view-1', concludeTurn() {} }) + +test('an interactive show_view in a job another Bot sent is refused like ask_user', async (t) => { + const { rt, fromBot, log, stop } = await start() + t.after(stop) + fromBot('writer', 'chief', 'Pick a layout') + assert.match(await showView(rt, 'writer', { title: 'Layout', view: PICK }), /^This job came from Chief. Do not card Steve/) + assert.equal(rt.state.views?.writer, undefined) + const [entry] = await anyLines(log) + assert.deepEqual([entry.bot, entry.manager, entry.tool, entry.allowed, entry.because, entry.title], ['Writer', 'Chief', 'show_view', false, 'gated', 'Layout']) + // A display-only view is no card and is not gated. + fromBot('writer', 'chief', 'Show the numbers') + assert.equal(await showView(rt, 'writer', { title: 'Meter', view: { type: 'metric', label: 'Done', value: '70%' } }), 'The view is on screen.') +}) + +test('a show_view whose confirm is the production approval is refused even with CARD-IT-YOURSELF', async (t) => { + const { rt, fromBot, stop } = await start() + t.after(stop) + fromBot('coder', 'chief', 'Ask Steve yourself. CARD-IT-YOURSELF') + assert.match(await showView(rt, 'coder', { title: 'Ship', view: DEPLOY }), /^This job came from Chief. A deploy approval never goes to Steve from here/) + assert.equal(rt.state.views?.coder, undefined) + // An ordinary interactive view is opened by the token. + assert.match(await showView(rt, 'coder', { title: 'Layout', view: PICK }), /view is on screen; the user's answer/) + assert.ok(rt.state.views.coder) +}) + +test('an interactive show_view in a turn the user typed shows as before', async (t) => { + const { rt, fromUser, stop } = await start() + t.after(stop) + fromUser('writer', 'Show me the layouts') + assert.match(await showView(rt, 'writer', { title: 'Layout', view: PICK }), /view is on screen; the user's answer/) + assert.ok(rt.state.views.writer) +}) + +const ADMIN_TEAM = { ...TEAM, rooms: { seo: { id: 'seo', name: 'SEO', members: ['writer', 'coder'], mode: 'admin', admin: 'writer', named: true, sessions: {} } } } + +test('PLAN-APPROVED from the admin of a group the Bot is in turns plan mode off', async (t) => { + const planMode = fakePlanMode({ coder: true }) + const { rt, log, stop } = await start({ planMode, team: ADMIN_TEAM }) + t.after(stop) + await rt.deliver({ fromId: 'writer', toId: 'coder', text: 'PLAN-APPROVED seo-1: go', role: 'request' }) + assert.deepEqual(planMode.calls, [['coder', false]]) + const [entry] = await anyLines(log) + assert.deepEqual([entry.bot, entry.manager, entry.tool, entry.outcome, entry.authority], ['Coder', 'Writer', 'plan-approved', 'committed', 'group-admin']) +}) + +test('a group admin cannot release a Bot outside its group, nor a plain member', async (t) => { + const planMode = fakePlanMode({ chief: true, writer: true }) + const team = { ...ADMIN_TEAM, mainBotIds: ['chief'] } + const { rt, log, stop } = await start({ planMode, team }) + t.after(stop) + // Chief is not in the SEO group: its admin is not Chief's manager. + await rt.deliver({ fromId: 'writer', toId: 'chief', text: 'PLAN-APPROVED x-1: go', role: 'request' }) + // Coder is a member, not the admin: it cannot release the admin. + await rt.deliver({ fromId: 'coder', toId: 'writer', text: 'PLAN-APPROVED x-2: go', role: 'request' }) + assert.deepEqual(planMode.calls, []) + const lines = await anyLines(log) + assert.deepEqual(lines.map(line => line.outcome), ['sender-not-manager', 'sender-not-manager']) +}) diff --git a/ds-bot/test/view-reply.test.js b/ds-bot/test/view-reply.test.js index 6b22b5f3fe..db2d0862ba 100644 --- a/ds-bot/test/view-reply.test.js +++ b/ds-bot/test/view-reply.test.js @@ -133,10 +133,11 @@ test('show_view registers an interactive card, refuses a group and a display-onl assert.equal(typeof open.views['writer-now'].askedAt, 'number') assert.deepEqual(open.views['writer-now'].view, CHOICES) - // A hidden Bot-to-Bot turn keeps the card but not the call. + // A hidden Bot-to-Bot turn keeps the card but not the call (the job opts in to + // carding the user; without it the card gate sends the card to Chief). emit('writer-now', 'turn/end', { turn: 1, reason: { kind: 'completed' } }) emit('writer-now', 'turn/start', { turn: 2 }) - emit('writer-now', 'user/message', { content: text('[Message from Chief]\nAsk them'), source: { kind: 'bot', role: 'request', senderSessionId: 'chief', senderName: 'Chief', exchangeId: 'x1', hop: 0 } }) + emit('writer-now', 'user/message', { content: text('[Message from Chief]\nAsk them. CARD-IT-YOURSELF'), source: { kind: 'bot', role: 'request', senderSessionId: 'chief', senderName: 'Chief', exchangeId: 'x1', hop: 0 } }) const hidden = await show('writer-now', { title: 'Pick', view: CHOICES }, 'call-hidden') assert.equal(hidden.concluded, true) assert.equal((await team()).views['writer-now'].callId, undefined)