From 0d69df2110e5e65f2c8ac7ce349ab862b5a928f5 Mon Sep 17 00:00:00 2001 From: Steve Dempsey Date: Mon, 2 Nov 2026 19:24:09 -0500 Subject: [PATCH 1/2] Card gate: decisions on a Bot-sent job go back to the Bot that sent it In a turn another Bot opened, a Bot that is not a Main Bot can no longer show the user a question card or a plan review. ask_user is refused and exit_plan_mode is refused by a guard; both refusals name the sender and tell the Bot to send it a DECISION instead. Still allowed: Main Bots, turns the user typed, requests whose audience is the user, a 'deploy to production' card (the production guard reads only the runner's own transcript), and a job carrying CARD-IT-YOURSELF. A Main Bot message carrying PLAN-APPROVED turns plan mode off in the Bot it reaches (queued when a turn is open). DSH_CARD_GATE=off turns all of it off. Each refusal and relayed approval is one JSON line in /logs/card-gate.log. --- ds-bot/src/host/card-gate.js | 124 +++++++++++++++++++ ds-bot/src/host/delivery.js | 4 + ds-bot/src/host/tools.js | 14 +++ ds-bot/src/host/turns.js | 8 +- ds-bot/test/card-gate.test.js | 226 ++++++++++++++++++++++++++++++++++ ds-bot/test/questions.test.js | 2 +- 6 files changed, 374 insertions(+), 4 deletions(-) create mode 100644 ds-bot/src/host/card-gate.js create mode 100644 ds-bot/test/card-gate.test.js diff --git a/ds-bot/src/host/card-gate.js b/ds-bot/src/host/card-gate.js new file mode 100644 index 0000000000..e25ce3c145 --- /dev/null +++ b/ds-bot/src/host/card-gate.js @@ -0,0 +1,124 @@ +// The card gate: decisions follow the job back to the Bot that sent it. +// +// A job a Bot sends another Bot runs in a hidden turn: the user does not watch it. +// A question card or a plan review raised there lands in the sub-agent's own chat, +// away from the conversation the user started the job in, so the gate refuses it +// and sends the decision back to the sender (the manager) instead. The manager +// cards the user and relays the answer; a plan approval relayed by a Main Bot with +// 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. +// +// DSH_CARD_GATE=off turns all of it off. + +import { appendFile, mkdir } from 'node:fs/promises' +import { dirname, join } from 'node:path' + +export const CARD_IT_YOURSELF = 'CARD-IT-YOURSELF' +export const PLAN_APPROVED = 'PLAN-APPROVED' +export const EXIT_PLAN_MODE = 'exit_plan_mode' +const PRODUCTION_LABEL = /^deploy to production( \(Recommended\))?$/i +const TITLE_MAX = 200 + +export const gateOn = (env = process.env) => String(env.DSH_CARD_GATE ?? '').trim().toLowerCase() !== 'off' + +export const isProductionLabel = label => PRODUCTION_LABEL.test(String(label ?? '').trim()) + +const clip = text => { + const value = String(text ?? '').replace(/\s+/g, ' ').trim() + return value.length > TITLE_MAX ? `${value.slice(0, TITLE_MAX - 3)}...` : value +} + +/** The plan's first markdown heading, or its first line. */ +export const planTitle = (plan) => { + for (const line of String(plan ?? '').split('\n')) { + const match = /^#{1,6}\s+(.+?)\s*$/.exec(line) + if (match) return clip(match[1]) + } + return clip(String(plan ?? '').split('\n').find(line => line.trim() !== '') ?? '') +} + +// Who sent the job a trigger carries: its Bot's name, else the name on the message. +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. + */ +export function gatedTurn(rt, sessionId) { + if (!gateOn()) return undefined + const { state } = rt + const entry = rt.live?.get(sessionId) + const turn = entry?.turn + if (turn === undefined || !(state.exchangeTurns?.[sessionId] ?? []).includes(turn)) return undefined + const botId = rt.chatOwners?.get(sessionId) + if (botId === undefined || rt.isMain?.(botId)) return undefined + 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 + 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 { + bot: rt.botOf?.(botId)?.name ?? botId, + manager: senderOf(rt, info), + cardItYourself: texts.some(text => text.includes(CARD_IT_YOURSELF)), + } +} + +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.` + +/** 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) } +} + +/** Whether exit_plan_mode in this Session is refused; the refusal text, or undefined. */ +export function refusePlan(rt, sessionId) { + const gated = gatedTurn(rt, sessionId) + if (gated === undefined || gated.cardItYourself) return undefined + return { ...gated, text: planRefusal(gated.manager) } +} + +/** One JSON line in /logs/card-gate.log. Only names, the tool and a title. */ +export function logGate(rt, entry) { + if (typeof rt.home !== 'string') return Promise.resolve() + const path = join(rt.home, 'logs', 'card-gate.log') + const line = JSON.stringify({ time: new Date().toISOString(), ...entry, ...(entry.title !== undefined ? { title: clip(rt.redactSecrets?.(entry.title) ?? entry.title) } : {}) }) + return mkdir(dirname(path), { recursive: true }) + .then(() => appendFile(path, `${line}\n`, 'utf8')) + .catch(error => rt.warn?.('ds-bot: card gate log not written: %s', error?.code ?? error)) +} + +/** + * A Main Bot's message that relays a plan approval turns plan mode off in the + * Session it reaches: at once between turns, from the next step inside one. + * Returns what planMode.set said, or undefined when nothing was done. + */ +export function relayPlanApproval(rt, { fromId, toId, agent, text }) { + if (!gateOn() || !String(text ?? '').includes(PLAN_APPROVED)) return undefined + if (fromId === undefined || !rt.isMain?.(fromId) || fromId === toId) return undefined + const planMode = rt.ctx?.get?.('planMode') + if (planMode === undefined || agent === undefined) return undefined + let outcome + try { + const now = planMode.get(agent) + if (!(now.pending ?? now.active)) return undefined + outcome = planMode.set(agent, false) + } catch (error) { + rt.warn?.('ds-bot: relayed plan approval not applied: %s', error) + return undefined + } + void logGate(rt, { bot: rt.botOf?.(toId)?.name ?? toId, manager: rt.botOf?.(fromId)?.name ?? fromId, tool: 'plan-approved', outcome }) + return outcome +} diff --git a/ds-bot/src/host/delivery.js b/ds-bot/src/host/delivery.js index d8011a6563..70e72e2885 100644 --- a/ds-bot/src/host/delivery.js +++ b/ds-bot/src/host/delivery.js @@ -1,6 +1,7 @@ // Delivery: how one Bot, the user, or DS Bot itself puts a message into a Bot Session. import { randomUUID } from 'node:crypto' import { createUserMessage } from '@deepseek-ai/dsh-llm' +import { relayPlanApproval } from './card-gate.js' import { HISTORY_TIMEOUT_MS, LONG_HEAD, MESSAGE_INLINE_MAX, READ_LINE_MAX, SOURCE_KIND, TEXT_KEPT, TEXT_SHOW_MAX } from './constants.js' import { headOf, textOf } from './text.js' @@ -96,6 +97,9 @@ export function install(rt) { ], source, }) + // A Main Bot relaying a plan approval takes the Bot out of plan mode, before the + // message that carries it is read (card-gate.js). + relayPlanApproval(rt, { fromId, toId, agent, text }) if (steer) agent.steer(message) else agent.followup(message) await ctx.sessions.flush(agent.session) diff --git a/ds-bot/src/host/tools.js b/ds-bot/src/host/tools.js index 95ca21a616..a3d11d3376 100644 --- a/ds-bot/src/host/tools.js +++ b/ds-bot/src/host/tools.js @@ -3,6 +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 { COLORS, EXTRA_COLORS, MESSAGE_INLINE_MAX, ROOM_MODES, SOURCE_KIND } from './constants.js' import { within } from './folders.js' import { absoluteLinks } from './links.js' @@ -680,6 +681,12 @@ export function install(rt) { .filter(option => option.label !== '') .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 + } // 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 @@ -927,6 +934,13 @@ Reason: ${why}` : ''}` ctx.tools.guard((exec) => { if (!rt.isBotSession(exec.agent?.id)) return undefined if (exec.name === BLOCKING_QUESTION_TOOL) return `Bots cannot use ${BLOCKING_QUESTION_TOOL}. Ask with ask_user in your own chat, or ask in your reply.` + if (exec.name === EXIT_PLAN_MODE) { + // A plan for a job another Bot sent is approved through that Bot (card-gate.js). + const refused = refusePlan(rt, exec.agent?.id) + if (refused === undefined) return undefined + void logGate(rt, { bot: refused.bot, manager: refused.manager, tool: EXIT_PLAN_MODE, title: planTitle(exec.arguments?.plan) }) + return refused.text + } return DELEGATION_TOOLS.includes(exec.name) ? DELEGATION_REFUSAL : undefined }) // Creation waits for this listener, so the Agent's first step already lacks the tool. diff --git a/ds-bot/src/host/turns.js b/ds-bot/src/host/turns.js index 6d55232d4a..1d8b12c957 100644 --- a/ds-bot/src/host/turns.js +++ b/ds-bot/src/host/turns.js @@ -369,8 +369,10 @@ export function install(rt) { // A group Session is hidden as a whole, so its turns need no marking. A handoff // package that only opens a part is acknowledged with a fixed line, also hidden. - const claimTrigger = (sessionId, entry, info) => { + const claimTrigger = (sessionId, entry, info, text) => { entry.info = info + // The trigger's text without its header line, for the card gate (card-gate.js). + entry.infoText = typeof text === 'string' ? text : undefined // A turn that was stopped for a part switch brings its joined requests along. if (Array.isArray(info.joined) && info.joined.length > 0) { entry.joined = info.joined.filter(item => item?.info !== undefined && item.info !== null) @@ -599,7 +601,7 @@ export function install(rt) { if (entry.pending !== undefined) { claimedPending = entry.pending claimedPendingText = entry.pendingText - claimTrigger(id, entry, claimedPending) + claimTrigger(id, entry, claimedPending, claimedPendingText) entry.pending = undefined entry.pendingText = undefined } @@ -696,7 +698,7 @@ export function install(rt) { entry.pending = source entry.pendingText = textOf(event.data.content).replace(/^\[(?:[^\r\n]*\]\r?\n|[^\]\r\n]*\])/, '') } - else if (!opened) claimTrigger(id, entry, source) + else if (!opened) claimTrigger(id, entry, source, textOf(event.data.content).replace(/^\[(?:[^\r\n]*\]\r?\n|[^\]\r\n]*\])/, '')) else if (source.work !== undefined && source.work !== rt.workOf?.(entry.info) && !expectsReply(source)) { // A result for other work than this turn's informs it, and comes back in a // turn of its own once this one ends, which goes on with that work. diff --git a/ds-bot/test/card-gate.test.js b/ds-bot/test/card-gate.test.js new file mode 100644 index 0000000000..2faad328d1 --- /dev/null +++ b/ds-bot/test/card-gate.test.js @@ -0,0 +1,226 @@ +import assert from 'node:assert/strict' +import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { test } from 'node:test' +import { createRuntime } from '../index.js' +import { fakeContext } from './fake-ctx.js' + +const TEAM = { + version: 1, + mainBotIds: ['chief'], + bots: { + chief: { id: 'chief', name: 'Chief', role: 'Lead', sessionId: 'chief', createdAt: 1 }, + writer: { id: 'writer', name: 'Writer', role: 'Write', sessionId: 'writer', createdAt: 2 }, + coder: { id: 'coder', name: 'Coder', role: 'Code', sessionId: 'coder', createdAt: 3 }, + }, + rooms: {}, + agents: {}, + exchanges: [], + exchangeTurns: {}, + questions: {}, + prefs: {}, + revision: 0, +} + +// A plan-mode service that keeps its state per Session, like ctx.planMode. +function fakePlanMode(active = {}) { + const calls = [] + return { + calls, + active, + get: agent => ({ active: active[agent.session.id] === true }), + set(agent, value) { + calls.push([agent.session.id, value]) + if ((active[agent.session.id] === true) === value) return 'noop' + active[agent.session.id] = value + return 'committed' + }, + } +} + +async function start({ planMode } = {}) { + const home = mkdtempSync(join(tmpdir(), 'ds-bot-card-gate-')) + writeFileSync(join(home, 'state.json'), JSON.stringify(TEAM)) + const ctx = fakeContext({ services: planMode ? { planMode } : {} }) + const delivered = [] + Object.assign(ctx, { + workspaceRegistry: { get: () => undefined, resolveByPath: async () => undefined, create: async path => ({ id: 'w1', path }), archiveSession: async () => {} }, + sessionController: { + create: async () => ({ sessionId: 's1' }), + resolveAgent: async sessionId => ({ agent: { session: { id: sessionId }, followup(message) { delivered.push([sessionId, message]) }, steer(message) { delivered.push([sessionId, message]) } } }), + selectModel: async () => {}, + }, + sessionTitle: { rename: async () => {} }, + sessions: { flush: async () => {} }, + }) + const rt = createRuntime(ctx, { home }) + let seq = 0 + const emit = (id, type, data) => { + for (const listener of ctx.listeners.get('session/event') ?? []) { + if (listener.length >= 2) listener({ id }, { type, seq: ++seq, data }) + } + } + const ask = (sessionId, options = [{ label: 'Lookout' }, { label: 'Scout' }]) => rt.teamTools.find(d => d.name === 'ask_user').execute( + { question: 'Which name?', options }, + { agent: { id: sessionId }, callId: 'call-1', concludeTurn() {} }, + ) + const guard = (sessionId, name, args) => { + for (const each of ctx.guards) { + const refusal = each({ name, arguments: args, agent: { id: sessionId } }) + if (refusal !== undefined) return refusal + } + return undefined + } + // A turn a Bot opened with a request (hidden), or one the user typed (visible). + const turns = {} + const nextTurn = (sessionId) => { + if (turns[sessionId] !== undefined) emit(sessionId, 'turn/end', { turn: turns[sessionId], reason: { kind: 'completed' } }) + turns[sessionId] = (turns[sessionId] ?? 0) + 1 + emit(sessionId, 'turn/start', { turn: turns[sessionId] }) + } + const fromBot = (sessionId, sender, body, extra = {}) => { + nextTurn(sessionId) + emit(sessionId, 'user/message', { content: [{ type: 'text', text: `[Message from ${TEAM.bots[sender].name}]\n${body}` }], source: { kind: 'bot', role: 'request', senderSessionId: sender, senderName: TEAM.bots[sender].name, exchangeId: `x-${sessionId}-${turns[sessionId]}`, hop: 0, ...extra } }) + } + const fromUser = (sessionId, body) => { + nextTurn(sessionId) + emit(sessionId, 'user/message', { content: [{ type: 'text', text: body }], source: { kind: 'user' } }) + } + const log = async () => { + const path = join(home, 'logs', 'card-gate.log') + for (let i = 0; i < 50 && !existsSync(path); i++) await new Promise(resolve => setTimeout(resolve, 10)) + await new Promise(resolve => setTimeout(resolve, 20)) + return existsSync(path) ? readFileSync(path, 'utf8').split('\n').filter(Boolean).map(line => JSON.parse(line)) : [] + } + await rt.teamTools.find(d => d.name === 'list_bots').execute({}, { agent: { id: 'chief' } }) + return { rt, emit, ask, guard, fromBot, fromUser, log, delivered, stop: async () => { await ctx.dispose(); rmSync(home, { recursive: true, force: true, maxRetries: 5 }) } } +} + +test('ask_user in a job another Bot sent is refused and names the manager', async (t) => { + const { rt, ask, fromBot, log, stop } = await start() + t.after(stop) + fromBot('writer', 'chief', 'Pick a name for the new Bot') + const reply = await ask('writer') + assert.match(reply, /^This job came from Chief\. Do not card Steve: end your turn with a DECISION block for Chief/) + assert.match(reply, /Chief cards Steve and relays his answer\.$/) + assert.equal(rt.state.questions.writer, undefined) + const [entry] = await log() + assert.equal(entry.bot, 'Writer') + assert.equal(entry.manager, 'Chief') + assert.equal(entry.tool, 'ask_user') + assert.equal(entry.title, 'Which name?') + assert.ok(Date.parse(entry.time) > 0) +}) + +test('a Main Bot cards in a job another Bot sent', async (t) => { + const { rt, ask, fromBot, stop } = await start() + t.after(stop) + fromBot('chief', 'writer', 'Ask the user which name they like') + assert.match(await ask('chief'), /card is on screen/) + assert.equal(rt.state.questions.chief.question, 'Which name?') +}) + +test('a turn the user typed cards as before', async (t) => { + const { rt, ask, fromUser, stop } = await start() + t.after(stop) + fromUser('writer', 'Help me name a Bot') + assert.match(await ask('writer'), /card is on screen/) + assert.equal(rt.state.questions.writer.callId, 'call-1') +}) + +test('a request whose audience is the user cards as before', async (t) => { + const { rt, ask, fromBot, stop } = await start() + t.after(stop) + fromBot('writer', 'chief', 'Introduce yourself', { audience: 'user' }) + assert.match(await ask('writer'), /card is on screen/) + 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() + t.after(stop) + fromBot('coder', 'chief', 'Merge PR 12 when Steve approves') + 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/) +}) + +test('CARD-IT-YOURSELF in the job lets the Bot card the user', async (t) => { + const { rt, ask, fromBot, 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) +}) + +test('exit_plan_mode in a job another Bot sent is refused', async (t) => { + const { guard, fromBot, fromUser, log, stop } = await start() + t.after(stop) + fromBot('coder', 'chief', 'Build the card gate') + const refusal = guard('coder', 'exit_plan_mode', { plan: '# Card gate\n\nSteps' }) + assert.match(refusal, /^This job came from Chief\. Do not open a plan review for Steve here: send the full plan to Chief as a DECISION \(Approve plan \(Recommended\) \/ Change it \/ Hold\)\./) + assert.match(refusal, /When Chief relays approval with PLAN-APPROVED, plan mode turns off for you\.$/) + const [entry] = await log() + assert.deepEqual([entry.bot, entry.manager, entry.tool, entry.title], ['Coder', 'Chief', 'exit_plan_mode', 'Card gate']) + // In the user's own turn, and in a Main Bot's, the review goes ahead. + fromUser('coder', 'Plan the card gate') + assert.equal(guard('coder', 'exit_plan_mode', { plan: '# Card gate' }), undefined) + fromBot('chief', 'coder', 'Plan it') + assert.equal(guard('chief', 'exit_plan_mode', { plan: '# Card gate' }), undefined) +}) + +test('PLAN-APPROVED from a Main Bot turns plan mode off', async (t) => { + const planMode = fakePlanMode({ coder: true }) + const { rt, log, delivered, stop } = await start({ planMode }) + t.after(stop) + await rt.deliver({ fromId: 'chief', toId: 'coder', text: 'Steve approved. PLAN-APPROVED. Go ahead.', role: 'request' }) + assert.deepEqual(planMode.calls, [['coder', false]]) + assert.equal(planMode.active.coder, false) + assert.equal(delivered.length, 1) + const [entry] = await log() + assert.deepEqual([entry.bot, entry.manager, entry.tool, entry.outcome], ['Coder', 'Chief', 'plan-approved', 'committed']) +}) + +test('PLAN-APPROVED from a Bot that is not a Main Bot changes nothing', async (t) => { + const planMode = fakePlanMode({ coder: true }) + const { rt, stop } = await start({ planMode }) + t.after(stop) + await rt.deliver({ fromId: 'writer', toId: 'coder', text: 'PLAN-APPROVED', role: 'request' }) + assert.deepEqual(planMode.calls, []) + assert.equal(planMode.active.coder, true) + // Nor does a Main Bot message without the token, or one to a Bot not in plan mode. + await rt.deliver({ fromId: 'chief', toId: 'coder', text: 'Plan looks fine', role: 'request' }) + await rt.deliver({ fromId: 'chief', toId: 'writer', text: 'PLAN-APPROVED', role: 'request' }) + assert.deepEqual(planMode.calls, []) +}) + +test('PLAN-APPROVED does nothing when plan mode is not composed', async (t) => { + const { rt, delivered, stop } = await start() + t.after(stop) + await rt.deliver({ fromId: 'chief', toId: 'coder', text: 'PLAN-APPROVED', role: 'request' }) + assert.equal(delivered.length, 1) +}) + +test('DSH_CARD_GATE=off turns the gate off', async (t) => { + const planMode = fakePlanMode({ coder: true }) + const { rt, ask, guard, fromBot, stop } = await start({ planMode }) + const before = process.env.DSH_CARD_GATE + process.env.DSH_CARD_GATE = 'off' + t.after(async () => { + if (before === undefined) delete process.env.DSH_CARD_GATE + else process.env.DSH_CARD_GATE = before + await stop() + }) + fromBot('writer', 'chief', 'Pick a name') + assert.match(await ask('writer'), /card is on screen/) + fromBot('coder', 'chief', 'Build it') + assert.equal(guard('coder', 'exit_plan_mode', { plan: '# Plan' }), undefined) + await rt.deliver({ fromId: 'chief', toId: 'coder', text: 'PLAN-APPROVED', role: 'request' }) + assert.deepEqual(planMode.calls, []) +}) diff --git a/ds-bot/test/questions.test.js b/ds-bot/test/questions.test.js index ed9a473a82..bcf8693c1d 100644 --- a/ds-bot/test/questions.test.js +++ b/ds-bot/test/questions.test.js @@ -65,7 +65,7 @@ test('a card asked in a hidden Bot-to-Bot turn goes to the dock, without its cal const { emit, ask, questions, stop } = await start() t.after(stop) emit('writer', 'turn/start', { turn: 1 }) - emit('writer', 'user/message', { content: text('[Message from Chief]\nThe user wants a new Bot; ask them for its name'), source: { kind: 'bot', role: 'request', senderSessionId: 'chief', senderName: 'Chief', exchangeId: 'x1', hop: 0 } }) + emit('writer', 'user/message', { content: text('[Message from Chief]\nThe user wants a new Bot; ask them for its name. CARD-IT-YOURSELF'), source: { kind: 'bot', role: 'request', senderSessionId: 'chief', senderName: 'Chief', exchangeId: 'x1', hop: 0 } }) await ask('writer', 'call-1') const asked = (await questions()).writer assert.equal(asked.question, 'Which name?') From 9889b96e563001152fe9f42f9228a5259bef43bf Mon Sep 17 00:00:00 2001 From: Steve Dempsey Date: Tue, 3 Nov 2026 07:06:18 -0500 Subject: [PATCH 2/2] Plan mode: release through the preset realm, and Bot Sessions start with it off Two faults kept Bots stuck in plan mode: 1. DSH's shipped presets (standard, ptc, cordis) pin plan mode on for every new Session (defaultActive: true). DS Bot makes every Bot chat, group Session and handoff part on `standard`, so each one started in plan mode. 2. Under a preset, plan mode lives in an isolated group (isolate.planMode), so rt.ctx.get('planMode') found nothing and a relayed PLAN-APPROVED was a silent no-op. The lookup now reads agentPresets.serviceFor(agent, 'planMode') first, as parts.js already does for compaction. ensurePlanOff switches a Bot Session out of plan mode once (recorded in state.planDefaultOff), on creation, on resume and on first delivery. A later /plan in that chat stays on. A Bot with planMode 'on', or named in /plan-mode-keep.json, is left alone. DSH_PLAN_DEFAULT_OFF=off turns it off. Every attempt is logged to card-gate.log with its outcome. --- ds-bot/src/host/card-gate.js | 107 ++++++++++++++++-- ds-bot/src/host/delivery.js | 5 +- ds-bot/src/host/parts.js | 7 +- ds-bot/src/host/roster.js | 3 + ds-bot/test/card-gate.test.js | 202 ++++++++++++++++++++++++++++++++-- 5 files changed, 305 insertions(+), 19 deletions(-) diff --git a/ds-bot/src/host/card-gate.js b/ds-bot/src/host/card-gate.js index e25ce3c145..63edefc33f 100644 --- a/ds-bot/src/host/card-gate.js +++ b/ds-bot/src/host/card-gate.js @@ -14,6 +14,7 @@ // // DSH_CARD_GATE=off turns all of it off. +import { readFileSync } from 'node:fs' import { appendFile, mkdir } from 'node:fs/promises' import { dirname, join } from 'node:path' @@ -100,25 +101,115 @@ export function logGate(rt, entry) { .catch(error => rt.warn?.('ds-bot: card gate log not written: %s', error?.code ?? error)) } +// A job a Main Bot hands out opens with this line; it carries the manager's +// approval to start, so the Bot it reaches is not left waiting in plan mode. +export const ORDER_PREFIX = /^ORDER from .+? · job / +export const orderReleaseOn = (env = process.env) => String(env.DSH_ORDER_RELEASE ?? '').trim().toLowerCase() !== 'off' + +/** Which release a message carries: 'plan-approved', 'order', or undefined. */ +export function releaseKind(text, env = process.env) { + const value = String(text ?? '') + if (value.includes(PLAN_APPROVED)) return 'plan-approved' + if (orderReleaseOn(env) && ORDER_PREFIX.test(value.trimStart())) return 'order' + return undefined +} + /** - * A Main Bot's message that relays a plan approval turns plan mode off in the - * Session it reaches: at once between turns, from the next step inside one. + * A Main Bot's message that relays a plan approval (PLAN-APPROVED), or hands out a + * job (an ORDER line), turns plan mode off in the Session it reaches, whether that + * Bot is a Main Bot or not: at once between turns, from the next step inside one. + * Every attempt is logged with its outcome, so a release that did nothing says why. * Returns what planMode.set said, or undefined when nothing was done. */ export function relayPlanApproval(rt, { fromId, toId, agent, text }) { - if (!gateOn() || !String(text ?? '').includes(PLAN_APPROVED)) return undefined - if (fromId === undefined || !rt.isMain?.(fromId) || fromId === toId) return undefined - const planMode = rt.ctx?.get?.('planMode') - if (planMode === undefined || agent === undefined) return undefined + if (!gateOn()) return undefined + 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 }) + } + if (fromId !== undefined && fromId === toId) { log('self'); return undefined } + if (fromId === undefined || !rt.isMain?.(fromId)) { log('sender-not-main'); return undefined } + const planMode = planModeFor(rt, agent) + if (planMode === undefined || agent === undefined) { log('no-plan-service'); return undefined } let outcome try { const now = planMode.get(agent) - if (!(now.pending ?? now.active)) return undefined + if (!(now.pending ?? now.active)) { log('not-in-plan-mode'); return undefined } outcome = planMode.set(agent, false) } catch (error) { rt.warn?.('ds-bot: relayed plan approval not applied: %s', error) + log('error') return undefined } - void logGate(rt, { bot: rt.botOf?.(toId)?.name ?? toId, manager: rt.botOf?.(fromId)?.name ?? fromId, tool: 'plan-approved', outcome }) + log(outcome) return outcome } + +/** + * 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 + * `ctx.get('planMode')` finds nothing: the preset composition is read first. + */ +export function planModeFor(rt, agent) { + if (agent === undefined) return undefined + return rt.ctx?.get?.('agentPresets')?.serviceFor?.(agent, 'planMode') ?? rt.ctx?.get?.('planMode') +} + +/** + * Bots that keep plan mode on, by name: /plan-mode-keep.json, a JSON array of + * names. Read on each call (it is tiny), so an edit needs no restart. + */ +export function keepsPlanMode(rt, name) { + if (typeof rt.home !== 'string' || typeof name !== 'string') return false + try { + const list = JSON.parse(readFileSync(join(rt.home, 'plan-mode-keep.json'), 'utf8')) + return Array.isArray(list) && list.some(item => String(item).trim().toLowerCase() === name.trim().toLowerCase()) + } catch { + return false + } +} + +export const planDefaultOffOn = (env = process.env) => String(env.DSH_PLAN_DEFAULT_OFF ?? '').trim().toLowerCase() !== 'off' + +/** + * A Bot Session does not start in plan mode: DSH's shipped presets pin it on for + * every new Session (`defaultActive: true`), and Steve's rule is off by default. + * Each Session is switched off once, recorded in `state.planDefaultOff`, so a later + * /plan in that chat is the user's choice and stays on. A Bot with + * `planMode: 'on'` is left alone. Returns the outcome, or undefined. + */ +export function ensurePlanOff(rt, agent, why, { fresh = false } = {}) { + if (!planDefaultOffOn()) return undefined + const sessionId = agent?.session?.id ?? agent?.id + if (sessionId === undefined) return undefined + // A Session DS Bot has just made for a Bot is not yet in the owner tables. + const botId = rt.selfOf?.(sessionId) + if (botId === undefined && !fresh) return undefined + const done = rt.state?.planDefaultOff ?? (rt.state === undefined ? undefined : (rt.state.planDefaultOff = {})) + if (done === undefined || done[sessionId] !== undefined) return undefined + const bot = rt.botOf?.(botId) + const log = (outcome) => { void logGate(rt, { bot: bot?.name ?? botId ?? sessionId, tool: 'plan-default-off', why, outcome }) } + if (bot?.planMode === 'on' || keepsPlanMode(rt, bot?.name)) { done[sessionId] = 'kept'; log('kept-bot-opt-in'); void rt.save?.().catch?.(() => {}); return 'kept' } + const planMode = planModeFor(rt, agent) + if (planMode === undefined) { log('no-plan-service'); return undefined } + let outcome + try { + const now = planMode.get(agent) + outcome = (now.pending ?? now.active) ? planMode.set(agent, false) : 'already-off' + } catch (error) { + rt.warn?.('ds-bot: plan default-off not applied: %s', error) + log('error') + return undefined + } + done[sessionId] = outcome + void rt.save?.().catch?.(() => {}) + log(outcome) + return outcome +} + +/** 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' }) +} diff --git a/ds-bot/src/host/delivery.js b/ds-bot/src/host/delivery.js index 70e72e2885..92a2e2479b 100644 --- a/ds-bot/src/host/delivery.js +++ b/ds-bot/src/host/delivery.js @@ -1,12 +1,14 @@ // Delivery: how one Bot, the user, or DS Bot itself puts a message into a Bot Session. import { randomUUID } from 'node:crypto' import { createUserMessage } from '@deepseek-ai/dsh-llm' -import { relayPlanApproval } from './card-gate.js' +import { announceGate, ensurePlanOff, relayPlanApproval } from './card-gate.js' import { HISTORY_TIMEOUT_MS, LONG_HEAD, MESSAGE_INLINE_MAX, READ_LINE_MAX, SOURCE_KIND, TEXT_KEPT, TEXT_SHOW_MAX } from './constants.js' import { headOf, textOf } from './text.js' export function install(rt) { const { ctx, state } = rt + // The card gate says once that it is loaded, so its log proves which code runs. + void announceGate(rt) const resolveAgent = async (sessionId) => { const resolved = await ctx.sessionController.resolveAgent(sessionId) @@ -99,6 +101,7 @@ export function install(rt) { }) // A Main Bot relaying a plan approval takes the Bot out of plan mode, before the // message that carries it is read (card-gate.js). + ensurePlanOff(rt, agent, 'delivery') relayPlanApproval(rt, { fromId, toId, agent, text }) if (steer) agent.steer(message) else agent.followup(message) diff --git a/ds-bot/src/host/parts.js b/ds-bot/src/host/parts.js index cce1737c07..91cea9cba6 100644 --- a/ds-bot/src/host/parts.js +++ b/ds-bot/src/host/parts.js @@ -17,6 +17,7 @@ import { randomUUID } from 'node:crypto' import { BlockAssembler, createUserMessage } from '@deepseek-ai/dsh-llm' import { openTurnAt } from './btw.js' +import { ensurePlanOff } from './card-gate.js' import { HANDOFF_ACK, HISTORY_TIMEOUT_MS, REPLY_KIND, SOURCE_KIND } from './constants.js' import { parseReplies, stackReplies } from '../shared/group-replies.js' import { CHECKPOINT_PROMPT, STEWARD_SYSTEM, checkpointCount, checkpointTail, checkpointTailNote, checkpointText, linesFor, parseDecision, stewardRequest } from './steward.js' @@ -317,7 +318,11 @@ export function install(rt) { } adoptedEngines.clear() }, 'ds-bot: Bot compaction') - ctx.on('agent/created', ({ agent }) => { adoptCompaction(agent) }) + ctx.on('agent/created', ({ agent }) => { + adoptCompaction(agent) + // A Bot Session resumed after a restart leaves the plan mode DSH pinned on it, once. + ensurePlanOff(rt, agent, 'resumed') + }) // A Bot's own chat, or its Session in one group, or the group's own Session // (`botId === undefined`), as numbered parts, oldest first; the last one is diff --git a/ds-bot/src/host/roster.js b/ds-bot/src/host/roster.js index 0aa22ea14a..79ca569c29 100644 --- a/ds-bot/src/host/roster.js +++ b/ds-bot/src/host/roster.js @@ -4,6 +4,7 @@ import { mkdir } from 'node:fs/promises' import { MAX_AVATAR_IMAGE, ROOM_MAX_MEMBERS, ROOM_MODES, ROOM_NAME_MAX, ROOM_NOTICE_MAX } from './constants.js' import { currentColor, isColor, normalize, unquote } from './text.js' import { nameProblem } from '../shared/mentions.js' +import { ensurePlanOff } from './card-gate.js' const BROWSER_GRANT_KINDS = new Set(['post', 'upload', 'download', 'delete', '*']) const HOSTNAME = /^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)(?:\.(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?))*$/ @@ -89,6 +90,8 @@ export function install(rt) { const { sessionId } = await ctx.sessionController.create({ ...place, ...await botPreset() }) const agent = await rt.resolveAgent(sessionId) await ctx.sessionTitle.rename(agent.session, title) + // DSH's presets pin plan mode on for every new Session; a Bot's starts off (card-gate.js). + ensurePlanOff(rt, agent, 'new-session', { fresh: true }) return sessionId } diff --git a/ds-bot/test/card-gate.test.js b/ds-bot/test/card-gate.test.js index 2faad328d1..7ac225f5fe 100644 --- a/ds-bot/test/card-gate.test.js +++ b/ds-bot/test/card-gate.test.js @@ -39,10 +39,21 @@ function fakePlanMode(active = {}) { } } -async function start({ planMode } = {}) { +// `realm: 'preset'` serves plan mode the way DSH does under an agent preset: only +// through agentPresets.serviceFor, never from a Host-realm ctx.get('planMode'). +// `planDefault: true` keeps the start-off rule on; the relay tests turn it off so +// they see only the relay. +async function start({ planMode, team = TEAM, realm = 'host', planDefault = false, keep } = {}) { const home = mkdtempSync(join(tmpdir(), 'ds-bot-card-gate-')) - writeFileSync(join(home, 'state.json'), JSON.stringify(TEAM)) - const ctx = fakeContext({ services: planMode ? { planMode } : {} }) + writeFileSync(join(home, 'state.json'), JSON.stringify(team)) + if (keep !== undefined) writeFileSync(join(home, 'plan-mode-keep.json'), JSON.stringify(keep)) + const beforeDefault = process.env.DSH_PLAN_DEFAULT_OFF + if (!planDefault) process.env.DSH_PLAN_DEFAULT_OFF = 'off' + else delete process.env.DSH_PLAN_DEFAULT_OFF + const services = planMode === undefined ? {} + : realm === 'preset' ? { agentPresets: { list: async () => [], serviceFor: (_agent, name) => (name === 'planMode' ? planMode : undefined) } } + : { planMode } + const ctx = fakeContext({ services }) const delivered = [] Object.assign(ctx, { workspaceRegistry: { get: () => undefined, resolveByPath: async () => undefined, create: async path => ({ id: 'w1', path }), archiveSession: async () => {} }, @@ -87,14 +98,20 @@ async function start({ planMode } = {}) { nextTurn(sessionId) emit(sessionId, 'user/message', { content: [{ type: 'text', text: body }], source: { kind: 'user' } }) } - const log = async () => { + // Every line, start-up included (`all`), or only the gate's decisions. + const log = async ({ all = false } = {}) => { const path = join(home, 'logs', 'card-gate.log') for (let i = 0; i < 50 && !existsSync(path); i++) await new Promise(resolve => setTimeout(resolve, 10)) await new Promise(resolve => setTimeout(resolve, 20)) - return existsSync(path) ? readFileSync(path, 'utf8').split('\n').filter(Boolean).map(line => JSON.parse(line)) : [] + const lines = existsSync(path) ? readFileSync(path, 'utf8').split('\n').filter(Boolean).map(line => JSON.parse(line)) : [] + return all ? lines : lines.filter(line => line.tool !== 'gate-loaded') } await rt.teamTools.find(d => d.name === 'list_bots').execute({}, { agent: { id: 'chief' } }) - return { rt, emit, ask, guard, fromBot, fromUser, log, delivered, stop: async () => { await ctx.dispose(); rmSync(home, { recursive: true, force: true, maxRetries: 5 }) } } + const restoreDefault = () => { + if (beforeDefault === undefined) delete process.env.DSH_PLAN_DEFAULT_OFF + else process.env.DSH_PLAN_DEFAULT_OFF = beforeDefault + } + return { rt, home, emit, ask, guard, fromBot, fromUser, log, delivered, stop: async () => { await ctx.dispose(); restoreDefault(); rmSync(home, { recursive: true, force: true, maxRetries: 5 }) } } } test('ask_user in a job another Bot sent is refused and names the manager', async (t) => { @@ -105,7 +122,7 @@ test('ask_user in a job another Bot sent is refused and names the manager', asyn assert.match(reply, /^This job came from Chief\. Do not card Steve: end your turn with a DECISION block for Chief/) assert.match(reply, /Chief cards Steve and relays his answer\.$/) assert.equal(rt.state.questions.writer, undefined) - const [entry] = await log() + const [entry] = await anyLines(log) assert.equal(entry.bot, 'Writer') assert.equal(entry.manager, 'Chief') assert.equal(entry.tool, 'ask_user') @@ -166,7 +183,7 @@ test('exit_plan_mode in a job another Bot sent is refused', async (t) => { const refusal = guard('coder', 'exit_plan_mode', { plan: '# Card gate\n\nSteps' }) assert.match(refusal, /^This job came from Chief\. Do not open a plan review for Steve here: send the full plan to Chief as a DECISION \(Approve plan \(Recommended\) \/ Change it \/ Hold\)\./) assert.match(refusal, /When Chief relays approval with PLAN-APPROVED, plan mode turns off for you\.$/) - const [entry] = await log() + const [entry] = await anyLines(log) assert.deepEqual([entry.bot, entry.manager, entry.tool, entry.title], ['Coder', 'Chief', 'exit_plan_mode', 'Card gate']) // In the user's own turn, and in a Main Bot's, the review goes ahead. fromUser('coder', 'Plan the card gate') @@ -183,7 +200,7 @@ test('PLAN-APPROVED from a Main Bot turns plan mode off', async (t) => { assert.deepEqual(planMode.calls, [['coder', false]]) assert.equal(planMode.active.coder, false) assert.equal(delivered.length, 1) - const [entry] = await log() + const [entry] = await anyLines(log) assert.deepEqual([entry.bot, entry.manager, entry.tool, entry.outcome], ['Coder', 'Chief', 'plan-approved', 'committed']) }) @@ -200,6 +217,78 @@ test('PLAN-APPROVED from a Bot that is not a Main Bot changes nothing', async (t assert.deepEqual(planMode.calls, []) }) +test('PLAN-APPROVED from a Main Bot turns plan mode off for another Main Bot', async (t) => { + const planMode = fakePlanMode({ chief: true }) + const team = { ...TEAM, mainBotIds: ['chief', 'writer'] } + const { rt, stop } = await start({ planMode, team }) + t.after(stop) + await rt.deliver({ fromId: 'writer', toId: 'chief', text: 'PLAN-APPROVED job-1: go', role: 'request' }) + assert.deepEqual(planMode.calls, [['chief', false]]) +}) + +test('an ORDER from a Main Bot turns plan mode off', async (t) => { + const planMode = fakePlanMode({ coder: true }) + const { rt, log, stop } = await start({ planMode }) + t.after(stop) + await rt.deliver({ fromId: 'chief', toId: 'coder', text: 'ORDER from Chief · job j-1 · decisions come back to me\nBuild it.', role: 'request' }) + assert.deepEqual(planMode.calls, [['coder', false]]) + const [entry] = await anyLines(log) + assert.deepEqual([entry.bot, entry.manager, entry.tool, entry.outcome], ['Coder', 'Chief', 'order', 'committed']) +}) + +test('an ORDER from a Bot that is not a Main Bot changes nothing and says why', async (t) => { + const planMode = fakePlanMode({ coder: true }) + const { rt, log, stop } = await start({ planMode }) + t.after(stop) + 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']) +}) + +test('ORDER mid-text is not an order', async (t) => { + const planMode = fakePlanMode({ coder: true }) + const { rt, stop } = await start({ planMode }) + t.after(stop) + await rt.deliver({ fromId: 'chief', toId: 'coder', text: 'Note the ORDER from Chief · job j-3 line below', role: 'request' }) + assert.deepEqual(planMode.calls, []) +}) + +test('DSH_ORDER_RELEASE=off leaves PLAN-APPROVED working and ORDER inert', async (t) => { + const planMode = fakePlanMode({ coder: true }) + const { rt, stop } = await start({ planMode }) + const before = process.env.DSH_ORDER_RELEASE + process.env.DSH_ORDER_RELEASE = 'off' + t.after(async () => { + if (before === undefined) delete process.env.DSH_ORDER_RELEASE + else process.env.DSH_ORDER_RELEASE = before + await stop() + }) + await rt.deliver({ fromId: 'chief', toId: 'coder', text: 'ORDER from Chief · job j-4 · decisions come back to me', role: 'request' }) + assert.deepEqual(planMode.calls, []) + await rt.deliver({ fromId: 'chief', toId: 'coder', text: 'PLAN-APPROVED j-4: go', role: 'request' }) + assert.deepEqual(planMode.calls, [['coder', false]]) +}) + +test('a release on a Bot not in plan mode is logged as not-in-plan-mode', async (t) => { + const planMode = fakePlanMode({}) + const { rt, log, stop } = await start({ planMode }) + t.after(stop) + await rt.deliver({ fromId: 'chief', toId: 'coder', text: 'PLAN-APPROVED j-5: go', role: 'request' }) + assert.deepEqual(planMode.calls, []) + const [entry] = await anyLines(log) + assert.deepEqual([entry.tool, entry.outcome], ['plan-approved', 'not-in-plan-mode']) +}) + +test('the gate says it is loaded at start-up', async (t) => { + const { log, stop } = await start() + t.after(stop) + const lines = await log({ all: true }) + const loaded = lines.find(line => line.tool === 'gate-loaded') + assert.ok(loaded, 'gate-loaded line written') + assert.equal(loaded.release, 'plan-approved+order') +}) + test('PLAN-APPROVED does nothing when plan mode is not composed', async (t) => { const { rt, delivered, stop } = await start() t.after(stop) @@ -224,3 +313,98 @@ test('DSH_CARD_GATE=off turns the gate off', async (t) => { await rt.deliver({ fromId: 'chief', toId: 'coder', text: 'PLAN-APPROVED', role: 'request' }) assert.deepEqual(planMode.calls, []) }) + +// --- 2026-11-03: plan mode under an agent preset, and Bots that start with it off --- + +// The log is written asynchronously: read it until a line appears. +async function anyLines(log) { + for (let i = 0; i < 50; i++) { + const lines = await log() + if (lines.length > 0) return lines + } + return [] +} + +// The same, for one tool's lines. +async function linesFor(log, tool) { + for (let i = 0; i < 50; i++) { + const lines = (await log()).filter(line => line.tool === tool) + if (lines.length > 0) return lines + } + return [] +} + +test('PLAN-APPROVED reaches plan mode inside an agent preset (no Host-realm service)', async (t) => { + const planMode = fakePlanMode({ coder: true }) + const { rt, log, stop } = await start({ planMode, realm: 'preset' }) + t.after(stop) + await rt.deliver({ fromId: 'chief', toId: 'coder', text: 'PLAN-APPROVED j-6: deploy to production', role: 'request' }) + assert.deepEqual(planMode.calls, [['coder', false]]) + const entry = (await linesFor(log, 'plan-approved'))[0] + assert.equal(entry.outcome, 'committed') +}) + +test('a Bot Session in plan mode is switched off once on its first delivery', async (t) => { + const planMode = fakePlanMode({ coder: true }) + const { rt, log, stop } = await start({ planMode, realm: 'preset', planDefault: true }) + t.after(stop) + await rt.deliver({ fromId: 'writer', toId: 'coder', text: 'hello', role: 'request' }) + assert.deepEqual(planMode.calls, [['coder', false]]) + // The user turns plan mode back on in that chat: it is his choice and stays. + planMode.active.coder = true + await rt.deliver({ fromId: 'writer', toId: 'coder', text: 'again', role: 'request' }) + assert.deepEqual(planMode.calls, [['coder', false]]) + assert.equal(planMode.active.coder, true) + const entries = (await linesFor(log, 'plan-default-off')) + assert.equal(entries.length, 1) + assert.deepEqual([entries[0].bot, entries[0].why, entries[0].outcome], ['Coder', 'delivery', 'committed']) + assert.equal(rt.state.planDefaultOff.coder, 'committed') +}) + +test('a Bot named in plan-mode-keep.json keeps plan mode', async (t) => { + const planMode = fakePlanMode({ coder: true }) + const { rt, log, stop } = await start({ planMode, realm: 'preset', planDefault: true, keep: ['coder'] }) + t.after(stop) + await rt.deliver({ fromId: 'writer', toId: 'coder', text: 'hello', role: 'request' }) + assert.deepEqual(planMode.calls, []) + const entry = (await linesFor(log, 'plan-default-off'))[0] + assert.equal(entry.outcome, 'kept-bot-opt-in') +}) + +test('a Bot with planMode on keeps plan mode', async (t) => { + const planMode = fakePlanMode({ coder: true }) + const team = { ...TEAM, bots: { ...TEAM.bots, coder: { ...TEAM.bots.coder, planMode: 'on' } } } + const { rt, stop } = await start({ planMode, team, realm: 'preset', planDefault: true }) + t.after(stop) + await rt.deliver({ fromId: 'writer', toId: 'coder', text: 'hello', role: 'request' }) + assert.deepEqual(planMode.calls, []) +}) + +test('a Session already out of plan mode is left as it is', async (t) => { + const planMode = fakePlanMode({}) + const { rt, log, stop } = await start({ planMode, realm: 'preset', planDefault: true }) + t.after(stop) + await rt.deliver({ fromId: 'writer', toId: 'coder', text: 'hello', role: 'request' }) + assert.deepEqual(planMode.calls, []) + const entry = (await linesFor(log, 'plan-default-off'))[0] + assert.equal(entry.outcome, 'already-off') +}) + +test('a new Bot Session DS Bot makes starts out of plan mode', async (t) => { + const planMode = fakePlanMode({ s1: true }) + const { rt, log, stop } = await start({ planMode, realm: 'preset', planDefault: true }) + t.after(stop) + const id = await rt.createSession('Fresh part') + assert.equal(id, 's1') + assert.deepEqual(planMode.calls, [['s1', false]]) + const entry = (await linesFor(log, 'plan-default-off'))[0] + assert.deepEqual([entry.why, entry.outcome], ['new-session', 'committed']) +}) + +test('DSH_PLAN_DEFAULT_OFF=off leaves plan mode alone', async (t) => { + const planMode = fakePlanMode({ coder: true }) + const { rt, stop } = await start({ planMode, realm: 'preset' }) + t.after(stop) + await rt.deliver({ fromId: 'writer', toId: 'coder', text: 'hello', role: 'request' }) + assert.deepEqual(planMode.calls, []) +})