Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(scanner leftovers): mcp expose consent through requireConsent; prompt reads via interaction.ts; stream/TUI reads allowlisted
garrytan75dbad0e72a5
diff --git a/scripts/agent-contract-baselines/interactive-io.tsv b/scripts/agent-contract-baselines/interactive-io.tsvindex 034967bee6..8dc95b4a56 100644--- a/scripts/agent-contract-baselines/interactive-io.tsv+++ b/scripts/agent-contract-baselines/interactive-io.tsv@@ -1,6 +1 @@# shrink-only baseline for scripts/check-agent-contract.ts rule interactive-io: path<TAB>count-src/commands/hook.ts 3-src/commands/jobs-watch.ts 2-src/commands/upgrade.ts 1-src/commands/watch.ts 1-src/mcp/server.ts 2diff --git a/scripts/agent-contract-baselines/yes-rerun-string.tsv b/scripts/agent-contract-baselines/yes-rerun-string.tsvindex a130ae4209..4fad70f8b6 100644--- a/scripts/agent-contract-baselines/yes-rerun-string.tsv+++ b/scripts/agent-contract-baselines/yes-rerun-string.tsv@@ -1,6 +1,5 @@# shrink-only baseline for scripts/check-agent-contract.ts rule yes-rerun-string: path<TAB>countsrc/commands/db-repair.ts 1-src/commands/mcp-expose.ts 3src/core/page-state/credential-reseal.ts 1src/core/schema-migrations/v039-multimodal-dual-column-v0-27-1.ts 2src/core/schema-migrations/v045-facts-hot-memory-v0-31.ts 1diff --git a/scripts/check-agent-contract.ts b/scripts/check-agent-contract.tsindex 5a9b4f0cbc..0df1900963 100644--- a/scripts/check-agent-contract.ts+++ b/scripts/check-agent-contract.ts@@ -14,7 +14,7 @@* throw-new-error-in-ops `throw new Error` in src/core/ops/**, src/mcp/** or an op `handler:` body* hand-built-command a `fix` / `next_action` value written as a 'gbrain …' string (build argv; shellQuote renders)* legacy-advice-key a legacy advice key (next_action, fix_argv, hint, docs_url, …) outside the alias allowlist- * interactive-io raw stdin/readline/raw-mode reads outside interaction.ts / consent.ts+ * interactive-io raw stdin/readline/raw-mode reads outside interaction.ts / consent.ts and INTERACTIVE_IO_ALLOW (streams/TUI, with a reason)* yes-rerun-string a raw "re-run with --yes" string outside consent.ts* stdio-inherit `stdio: 'inherit'` outside spawnCliChild (cli-force-exit.ts)* marker-literal [AGENT] / [SHOW USER] / "ACTION FOR THE AGENT:" outside agent-output.ts / agent-markers.ts@@ -54,6 +54,27 @@ export const BASELINED_RULES: readonly Rule[] = [export interface Hit { rule: Rule; file: string; line: number; text: string }+/**+ * interactive-io reads that are data streams or terminal UI, not prompts:+ * path → call → one-line reason. A prompt (a question the user answers) never+ * belongs here; it goes through interaction.ts (readLine / promptYesNo).+ */+export const INTERACTIVE_IO_ALLOW: Readonly<Record<string, Readonly<Record<string, string>>>> = {+ 'src/commands/hook.ts': {+ 'process.stdin.on': 'harness hook payload: bounded, fail-open stream read with its own hard timeout (a hook never blocks the agent)',+ },+ 'src/commands/watch.ts': {+ createInterface: 'stdin IS the data: transcript turns streamed line by line until EOF or SIGINT',+ },+ 'src/commands/jobs-watch.ts': {+ 'process.stdin.setRawMode': "TTY-only dashboard: raw mode so a single 'q' keypress quits",+ 'process.stdin.on': "TTY-only dashboard: the 'q' / Ctrl-C keypress listener",+ },+ 'src/mcp/server.ts': {+ 'process.stdin.on': 'stdio MCP transport lifecycle: shut down when the client closes stdin',+ },+};+const LEGACY_ADVICE_KEYS = new Set(['next_action', 'fix_argv', 'agent_action', 'recovery_action', 'docs_url', 'hint', 'remediation', 'next_step']);const MARKER_RE = /\[\/?AGENT\]|\[\/?SHOW USER\]|ACTION FOR THE AGENT:/;const YES_RERUN_RE = /re-?run\b[^.\n]{0,40}--yes/i;@@ -241,7 +262,8 @@ export function scan(root: string = ROOT): Hit[] {if (!ioExempt) {if (ts.isCallExpression(n)) {const callee = n.expression.getText(sf);- if (/(^|\.)createInterface$/.test(callee) || /^process\.stdin\.(on|once)$/.test(callee) || /\.setRawMode$/.test(callee)) add('interactive-io', n);+ if ((/(^|\.)createInterface$/.test(callee) || /^process\.stdin\.(on|once)$/.test(callee) || /\.setRawMode$/.test(callee))+ && !INTERACTIVE_IO_ALLOW[path]?.[callee]) add('interactive-io', n);if (/(^|\.)readFileSync$/.test(callee) && n.arguments[0] && stringText(n.arguments[0]) === '/dev/stdin') add('interactive-io', n);}if (ts.isForOfStatement(n) && n.awaitModifier && n.expression.getText(sf) === 'process.stdin') add('interactive-io', n);diff --git a/src/commands/mcp-expose.ts b/src/commands/mcp-expose.tsindex c663e6306c..77f2348503 100644--- a/src/commands/mcp-expose.ts+++ b/src/commands/mcp-expose.ts@@ -19,6 +19,8 @@ import { existsSync, unlinkSync } from 'node:fs';import { dirname, resolve as resolvePath } from 'node:path';import { homedir, userInfo } from 'node:os';import { promptLineStderr } from '../core/cli-util.ts';+import { isConsentRefusal, renderConsentRefusal, requireConsent } from '../core/consent.ts';+import type { Effect } from '../core/agent-output.ts';import { gbrainPath, isThinClient, loadConfig, type GBrainConfig } from '../core/config.ts';import { detectExecutionEnvironment, type ExecutionEnvironment } from '../core/execution-env.ts';import { validateHarnessArguments } from '../core/harness/arguments.ts';@@ -307,12 +309,13 @@ class Session {this.checks.push(c);return c;}- finish(status: ExposeStatus, code: number, extra: { receipt?: ExposeReceipt | null; reason?: string; message?: string; plan?: string[] } = {}): number {+ finish(status: ExposeStatus, code: number, extra: { receipt?: ExposeReceipt | null; reason?: string; message?: string; plan?: string[]; consent?: Record<string, unknown> } = {}): number {if (extra.message) this.say(`${status}: ${extra.message}`);if (this.json) {this.d.out(JSON.stringify({status, receipt: extra.receipt ?? null, checks: this.checks, next_actions: this.nextActions,...(extra.reason ? { reason: extra.reason } : {}), ...(extra.message ? { message: extra.message } : {}), ...(extra.plan ? { plan: extra.plan } : {}),+ ...(extra.consent ?? {}),}));}return code;@@ -440,29 +443,49 @@ interface ConsentExtra {confirmationMessage: string;/** Pushed to `next_actions` on a non-TTY run without `--yes`. */nextAction?: string;+ /** The command that runs once approved, without `--yes` (consentFix adds it). */+ argv: string[];+ effects: Effect[];+ what: string;+ why: string;+ risk: string;+ user_message: string;}/**- * The `consent` check. Returns the exit code to hand back when the run must- * stop (non-TTY without `--yes` → `pending` / 2 / `confirmation_required`;- * declined at the prompt → `pending` / 2 / `declined`), or null to proceed.+ * The `consent` check, through the consent primitive (requireConsent). Returns+ * the exit code to hand back when the run must stop, or null to proceed.+ * Under contract v1 `mcp expose` keeps its documented exit 2 for a refusal+ * (non-TTY without `--yes` → `pending` / `confirmation_required`; declined at+ * the prompt → `pending` / `declined`); the document gains the consent+ * payload's agent fields (`code`, `effects`, `user_message`, `fix`, …) and+ * human output prints its `[AGENT]` block.*/async function confirmOrFinish(d: Resolved, s: Session, question: string, extra: ConsentExtra): Promise<number | null> {- if (extra.yes) {- s.check('consent', 'ok', '--yes');- return null;- }- if (!d.isTTY) {- s.check('consent', 'pending', 'not a TTY and --yes not passed');- if (extra.nextAction) s.nextActions.push(extra.nextAction);- return s.finish('pending', 2, { receipt: extra.receipt, reason: 'confirmation_required', message: extra.confirmationMessage });- }- const answer = await d.prompt(question);- if (!answer || !/^y(es)?$/i.test(answer.trim())) {- s.check('consent', 'pending', 'declined');- return s.finish('pending', 2, { receipt: extra.receipt, reason: 'declined', message: 'Nothing changed. Re-run with --yes to confirm.' });+ try {+ await requireConsent({+ command: 'mcp expose', effects: extra.effects, actor: 'agent', what: extra.what, why: extra.why, risk: extra.risk,+ user_message: extra.user_message, argv: extra.argv, args: extra.yes ? ['--yes'] : [],+ }, {+ interactive: d.isTTY,+ readLine: async () => {+ const answer = await d.prompt(question);+ return answer === null ? { kind: 'eof' } : { kind: 'line', text: answer.trim() };+ },+ });+ } catch (e) {+ if (!isConsentRefusal(e)) throw e;+ const declined = d.isTTY && !extra.yes;+ s.check('consent', 'pending', declined ? 'declined' : 'not a TTY and --yes not passed');+ if (!declined && extra.nextAction) s.nextActions.push(extra.nextAction);+ const { status: _status, error: _error, message: _message, suggestion: _suggestion, ...payload } = e.consent;+ if (!declined && !s.json) s.say(renderConsentRefusal(e.consent, { json: false }).stdout?.trimEnd() ?? '');+ return s.finish('pending', 2, {+ receipt: extra.receipt, reason: declined ? 'declined' : 'confirmation_required',+ message: declined ? 'Nothing changed: the confirmation was declined.' : extra.confirmationMessage, consent: payload,+ });}- s.check('consent', 'ok', 'confirmed interactively');+ s.check('consent', 'ok', extra.yes ? '--yes' : 'confirmed interactively');return null;}@@ -615,7 +638,7 @@ async function runPublish(d: Resolved, s: Session, opts: ExposeOptions): Promisefor (const line of plan) s.say(` ${line}`);if (opts.dryRun) {s.say('');- s.say('Dry run: nothing changed. Re-run without --dry-run (add --yes to skip the prompt).');+ s.say('Dry run: nothing changed. To apply, run the same command without --dry-run; it asks for confirmation first.');return s.finish('planned', 0, { receipt: existing, plan });}if (noBrain) {@@ -645,6 +668,12 @@ async function runPublish(d: Resolved, s: Session, opts: ExposeOptions): Promiseconst consent = await confirmOrFinish(d, s, 'Proceed with the plan above? [y/N] ', {yes: opts.yes, nextAction: rerunCommand(opts),confirmationMessage: 'These are system-state changes (Tailscale, serve config, a user service). Pass --yes to confirm.',+ argv: ['gbrain', 'mcp', 'expose', ...publishFlags(opts)],+ effects: ['persistent_install', 'egress'],+ what: 'mcp expose',+ why: `Publishes this brain's MCP server ${opts.noTailscale ? 'on loopback' : opts.funnel ? 'to the public internet (Tailscale Funnel)' : 'on your tailnet (Tailscale serve)'}${opts.noService ? '' : ' and installs a user service that keeps it running'}, so authorized agents on other machines can reach it.`,+ risk: 'Changes system state (Tailscale serve config, a user service, files under the serve directory); `gbrain mcp expose --remove` undoes it.',+ user_message: `I'd like to publish your gbrain MCP server ${opts.noTailscale ? 'on this machine' : opts.funnel ? 'on the public internet through Tailscale Funnel' : 'on your Tailscale network'}${opts.noService ? '' : ' and install a background service for it'}. OK?`,});if (consent !== null) return consent;@@ -1000,16 +1029,21 @@ async function runPublish(d: Resolved, s: Session, opts: ExposeOptions): Promisereturn s.finish(pending ? 'pending' : 'exposed', pending ? 2 : 0, { receipt, ...(pending ? { reason: tailnetHealth === 'pending' ? 'tailnet_health_pending' : 'local_health_timeout' } : {}) });}-/** Re-render the user's publish flags for a re-run hint (never --yes/--json/--dry-run). */-function args2(opts: ExposeOptions): string {+/** The user's publish flags, for a re-run hint or the approved command (never --yes/--json/--dry-run). */+function publishFlags(opts: ExposeOptions): string[] {const parts: string[] = [];- if (opts.port !== DEFAULT_EXPOSE_PORT) parts.push(`--port ${opts.port}`);+ if (opts.port !== DEFAULT_EXPOSE_PORT) parts.push('--port', String(opts.port));if (opts.funnel) parts.push('--funnel');- if (opts.surface !== 'full') parts.push(`--surface ${opts.surface}`);+ if (opts.surface !== 'full') parts.push('--surface', opts.surface);if (opts.enableDcr) parts.push('--enable-dcr');if (opts.noTailscale) parts.push('--no-tailscale');if (opts.noService) parts.push('--no-service');if (opts.noInstall) parts.push('--no-install');+ return parts;+}++function args2(opts: ExposeOptions): string {+ const parts = publishFlags(opts);return parts.length ? ` ${parts.join(' ')}` : '';}@@ -1275,7 +1309,14 @@ async function runRemove(d: Resolved, s: Session, opts: ExposeOptions): Promise<s.check('plan', 'ok', plan.join(' | '));s.say('Remove plan');for (const line of plan) s.say(` ${line}`);- const consent = await confirmOrFinish(d, s, 'Remove the published server? [y/N] ', { yes: opts.yes, receipt, confirmationMessage: 'Pass --yes to confirm the removal.' });+ const consent = await confirmOrFinish(d, s, 'Remove the published server? [y/N] ', {+ yes: opts.yes, receipt, confirmationMessage: 'Pass --yes to confirm the removal.',+ argv: ['gbrain', 'mcp', 'expose', '--remove', ...(opts.force ? ['--force'] : [])],+ effects: ['persistent_install'], what: 'mcp expose --remove',+ why: 'Stops and removes the published server: the user service, the Tailscale handler and the files listed in the remove plan.',+ risk: 'Agents connected through the published URL lose access until it is published again.',+ user_message: 'I\'d like to unpublish your gbrain MCP server (stop its service and remove its Tailscale handler). OK?',+ });if (consent !== null) return consent;const left: string[] = [];// service — the receipt may say `skipped` (a `--no-service` run) while a@@ -1320,7 +1361,7 @@ async function runRemove(d: Resolved, s: Session, opts: ExposeOptions): Promise<s.check('receipt', 'skipped', 'kept (the tailscale serve status could not be read; re-run --remove once it can)');s.nextActions.push('tailscale serve status --json', 'gbrain mcp expose --remove --yes');s.say('');- s.say('Stopped here: could not read `tailscale serve status`, so the handler, the wrapper and the receipt were left in place. Fix Tailscale, then re-run `gbrain mcp expose --remove --yes`.');+ s.say('Stopped here: could not read `tailscale serve status`, so the handler, the wrapper and the receipt were left in place. Fix Tailscale, then run the removal again (the user already approved it: `gbrain mcp expose --remove --yes`).');return s.finish('error', 1, { receipt, reason: 'tailscale_serve_status_unreadable', message: 'could not read tailscale serve status; handler left as is' });}const ours = findProxiedHandler(read.view, receipt.port);@@ -1398,7 +1439,14 @@ async function runRemoveWithoutReceipt(d: Resolved, s: Session, opts: ExposeOptis.say(`Recovering without a receipt (an interrupted \`gbrain mcp expose\` left these behind; port ${opts.port}):`);for (const line of plan) s.say(` ${line}`);const rerun = recoveryCommand(opts.port, opts.force);- const consent = await confirmOrFinish(d, s, 'Remove these leftovers? [y/N] ', { yes: opts.yes, receipt: null, confirmationMessage: 'Pass --yes to confirm the removal.', nextAction: rerun });+ const consent = await confirmOrFinish(d, s, 'Remove these leftovers? [y/N] ', {+ yes: opts.yes, receipt: null, confirmationMessage: 'Pass --yes to confirm the removal.', nextAction: rerun,+ argv: ['gbrain', 'mcp', 'expose', '--remove', ...(opts.force ? ['--force'] : []), ...(opts.port !== DEFAULT_EXPOSE_PORT ? ['--port', String(opts.port)] : [])],+ effects: ['persistent_install'], what: 'mcp expose --remove',+ why: `Removes what an interrupted \`gbrain mcp expose\` left behind on port ${opts.port} (the service, a Tailscale handler, the wrapper), as listed in the plan.`,+ risk: 'Anything still using that server loses it.',+ user_message: 'An interrupted gbrain publish left a server behind. I\'d like to remove those leftovers. OK?',+ });if (consent !== null) return consent;const left: string[] = [];let serviceNote = 'no service was found';diff --git a/src/commands/upgrade.ts b/src/commands/upgrade.tsindex 51519023c1..210d62ffba 100644--- a/src/commands/upgrade.ts+++ b/src/commands/upgrade.ts@@ -6,6 +6,7 @@ import { jsonRequested, setCliExitVerdict, writeJsonDocument } from '../core/cliimport { opError, type OperationError } from '../core/ops/contract.ts';import { writeCliError } from '../cli/cli-error.ts';import { VERSION } from '../version.ts';+import type { InteractiveProbe } from '../core/interaction.ts';import { migrationLedgerSummary } from '../core/migration-ledger.ts';import { MIGRATIONS_RUNNING_EXIT_CODE, readMigrationLockHolder } from '../core/migration-orchestration-lock.ts';import {@@ -753,29 +754,11 @@ export async function runPostUpgrade(args: string[] = []): Promise<void> {console.log('[gbrain] remote MCP callers you have authorized. Source code is NOT exposed.');console.log('[gbrain] Following updates, bundle bytes and skill editing require separate approval.');console.log('═══════════════════════════════════════════════════════════════');- const isTty = Boolean(process.stdin.isTTY && process.stdout.isTTY);+ const { isInteractive } = await import('../core/interaction.ts');+ const isTty = isInteractive();let enabled = false;if (isTty) {- const { createInterface } = await import('readline');- // #4318 residual: rl.close() must not run before the answer's- // resolveAns() — the unguarded rl.on('close', ...) below would- // otherwise settle the promise `false` first (the close event- // fires synchronously during rl.close()), so an operator- // pressing Enter to accept this [Y/n]-default-yes prompt would- // always land on "declined" regardless of what they typed.- enabled = await new Promise<boolean>((resolveAns) => {- const rl = createInterface({ input: process.stdin, output: process.stdout });- let answered = false;- rl.question('[gbrain] Enable skill publishing now? (recommended) [Y/n] ', (answer) => {- answered = true;- const a = answer.trim().toLowerCase();- resolveAns(a === '' || a === 'y' || a === 'yes');- rl.close();- });- rl.on('close', () => {- if (!answered) resolveAns(false);- });- });+ enabled = await promptEnableSkillPublishing();} else {console.log('[AGENT] Relay this to your operator. Recommended: enable it.');console.log('[AGENT] Enable with: gbrain config set mcp.publish_skills true');@@ -1196,3 +1179,19 @@ function printSquatterRecovery(): void {console.warn(' See docs/INSTALL_FOR_AGENTS.md for the canonical install paths.');console.warn('');}++/**+ * The one-time "Enable skill publishing now? (recommended) [Y/n]" prompt+ * (#4318 residual). Default yes: an empty line (Enter), `y` or `yes`+ * accepts; anything else, EOF, the prompt timeout or a non-interactive+ * caller declines (A5: never hang on a silent stdin). Seams for tests.+ */+export async function promptEnableSkillPublishing(+ opts: { input?: NodeJS.ReadableStream; output?: NodeJS.WritableStream; probe?: InteractiveProbe; timeoutMs?: number } = {},+): Promise<boolean> {+ const { readLine } = await import('../core/interaction.ts');+ const answer = await readLine({ prompt: '[gbrain] Enable skill publishing now? (recommended) [Y/n] ', ...opts });+ if (answer.kind !== 'line') return false;+ const a = answer.text.toLowerCase();+ return a === '' || a === 'y' || a === 'yes';+}diff --git a/test/mcp-expose.test.ts b/test/mcp-expose.test.tsindex 279b0b6259..836fb3aa12 100644--- a/test/mcp-expose.test.ts+++ b/test/mcp-expose.test.ts@@ -285,6 +285,20 @@ describe('plan + consent', () => {const doc = jsonDoc(f);expect(doc).toMatchObject({ status: 'pending', reason: 'confirmation_required' });expect(doc.next_actions).toContain('gbrain mcp expose --yes');+ // The consent payload's agent fields ride the legacy document (exit 2 stays under contract v1).+ expect(doc).toMatchObject({+ code: 'confirmation_required', effects: ['persistent_install', 'egress'], actor: 'agent', contract_version: 1,+ fix: { argv: ['gbrain', 'mcp', 'expose', '--yes'], next: 'ask_user' },+ });+ expect(doc.user_message).toContain('publish your gbrain MCP server');+ expect(doc.error).toBeUndefined();+ const human = fakeTailnet();+ expect(await runMcpExpose([], human.deps)).toBe(2);+ const out = human.stdout.join('\n');+ expect(out).toContain('[AGENT]');+ expect(out).toContain('next: ask_user');+ expect(out).toContain('if_yes: gbrain mcp expose --yes');+ expect(out).not.toMatch(/re-?run[^.\n]{0,40}--yes/i);expect(existsSync(f.serveDir)).toBe(false);expect(joinedCalls(f).some(c => c.includes('--bg'))).toBe(false);});@@ -294,7 +308,7 @@ describe('plan + consent', () => {f.deps.prompt = async () => 'n';expect(await runMcpExpose(['--json'], f.deps)).toBe(2);const doc = jsonDoc(f);- expect(doc).toMatchObject({ status: 'pending', reason: 'declined', message: 'Nothing changed. Re-run with --yes to confirm.' });+ expect(doc).toMatchObject({ status: 'pending', reason: 'declined', message: 'Nothing changed: the confirmation was declined.', code: 'confirmation_required' });expect(checkOf(doc, 'consent')?.status).toBe('pending');expect(existsSync(f.serveDir)).toBe(false);expect(joinedCalls(f).some(c => c.includes('--bg'))).toBe(false);@@ -999,7 +1013,7 @@ describe('--remove', () => {f.deps.prompt = async () => 'no';expect(await runMcpExpose(['--remove', '--json'], f.deps)).toBe(2);const doc = jsonDoc(f);- expect(doc).toMatchObject({ status: 'pending', reason: 'declined', message: 'Nothing changed. Re-run with --yes to confirm.' });+ expect(doc).toMatchObject({ status: 'pending', reason: 'declined', message: 'Nothing changed: the confirmation was declined.', code: 'confirmation_required' });expect(checkOf(doc, 'consent')?.status).toBe('pending');expect(existsSync(receiptPath(f.serveDir))).toBe(true);expect(joinedCalls(f).some(c => c.includes('disable') || c.includes('off'))).toBe(false);@@ -1793,7 +1807,7 @@ describe('tailscale serve status fails closed', () => {expect(existsSync(receiptPath(f.serveDir))).toBe(true);expect(existsSync(wrapperPath(f.serveDir))).toBe(true);expect((await inner([TS, 'serve', 'status', '--json'])).stdout).toContain('127.0.0.1:3131');- expect(f.stderr.join('\n')).toContain('re-run `gbrain mcp expose --remove --yes`');+ expect(f.stderr.join('\n')).toContain('run the removal again (the user already approved it: `gbrain mcp expose --remove --yes`)');// Tailscale is back → the same command completes the removalbroken = false;f.calls.length = 0;diff --git a/test/upgrade-skill-publish-prompt-race.test.ts b/test/upgrade-skill-publish-prompt-race.test.tsindex 5994d990ea..3ff2dbc511 100644--- a/test/upgrade-skill-publish-prompt-race.test.ts+++ b/test/upgrade-skill-publish-prompt-race.test.ts@@ -1,62 +1,49 @@/*** `gbrain upgrade`'s one-time "Enable skill publishing now? (recommended)- * [Y/n]" prompt (#4318 residual) — same close-before-resolve race the shared- * `src/core/confirm-prompt.ts` helper was written to fix, but this inline- * confirm in upgrade.ts predates that helper and was never migrated: it- * called `rl.close()` inside the answer callback BEFORE resolving, while an- * unguarded `rl.on('close', () => resolveAns(false))` listener fired- * synchronously during that close and settled the promise first — so- * pressing Enter (or typing "y") on this default-YES prompt always resolved- * `false`, silently leaving skill publishing disabled regardless of what the- * operator answered.- *- * The prompt is inline inside a large, side-effecting `runUpgrade()` flow- * (DB writes, network) rather than an exported, injectable function, so this- * pins the fix at the source level: a regression back to the close-before-- * resolve shape fails here even though `test/confirm-prompt.test.ts` (which- * only covers the shared helper) cannot see this file at all.+ * [Y/n]" prompt (#4318 residual). The inline readline confirm used to call+ * `rl.close()` before resolving while an unguarded close listener settled the+ * promise `false` first, so pressing Enter on this default-YES prompt always+ * declined. The prompt now reads through interaction.ts `readLine` (one+ * settle, EOF/timeout = decline) behind `promptEnableSkillPublishing`, so the+ * contract is pinned by executing it against a real stream.*/import { describe, test, expect } from 'bun:test';-import { readFileSync } from 'node:fs';-import { join } from 'node:path';+import { PassThrough } from 'node:stream';+import { promptEnableSkillPublishing } from '../src/commands/upgrade.ts';-describe('gbrain upgrade — skill-publish prompt wiring (#4318 residual)', () => {- // test-reads-source-ok[structural]: the prompt is inline inside a large, side-effecting,- // non-exported runUpgrade() with no injectable stdin — resolve/close- // ordering is only observable in source text, not an executable boundary.- const src = readFileSync(join(import.meta.dir, '../src/commands/upgrade.ts'), 'utf8');+const TTY = { env: {}, stdinIsTTY: true, stdoutIsTTY: true };- test('the close listener is guarded by an `answered` flag, not unconditional', () => {- // The buggy shape was `rl.on('close', () => resolveAns(false));` with no- // guard. The fixed shape checks `answered` before declining on close.- const idx = src.indexOf('[gbrain] Enable skill publishing now?');- expect(idx).toBeGreaterThan(-1);- const promptRegion = src.slice(idx - 100, idx + 700);- expect(promptRegion).toContain('let answered = false;');- expect(promptRegion).toContain('answered = true;');- expect(promptRegion).toMatch(/rl\.on\('close',\s*\(\)\s*=>\s*\{\s*if \(!answered\) resolveAns\(false\);/);- // The regression this guards against: an unconditional decline-on-close.- expect(promptRegion).not.toMatch(/rl\.on\('close',\s*\(\)\s*=>\s*resolveAns\(false\)\);/);+async function answer(text: string | null, probe = TTY): Promise<{ enabled: boolean; prompt: string }> {+ const input = new PassThrough();+ const output = new PassThrough();+ let prompt = '';+ output.on('data', (c) => { prompt += String(c); });+ const pending = promptEnableSkillPublishing({ input, output, probe, timeoutMs: 2_000 });+ if (text === null) input.end(); else input.write(text);+ return { enabled: await pending, prompt };+}++describe('gbrain upgrade — skill-publish prompt (#4318 residual)', () => {+ test('Enter alone accepts the [Y/n] default (the race used to decline it)', async () => {+ const r = await answer('\n');+ expect(r.enabled).toBe(true);+ expect(r.prompt).toContain('Enable skill publishing now? (recommended) [Y/n]');+ });++ test('y / yes accept; n and anything else decline', async () => {+ expect((await answer('y\n')).enabled).toBe(true);+ expect((await answer('YES\n')).enabled).toBe(true);+ expect((await answer('n\n')).enabled).toBe(false);+ expect((await answer('maybe\n')).enabled).toBe(false);});- test('resolveAns for the answer is called strictly before rl.close() in the question callback', () => {- const idx = src.indexOf('[gbrain] Enable skill publishing now?');- const promptRegion = src.slice(idx - 100, idx + 700);- const resolveIdx = promptRegion.indexOf('resolveAns(a === ');- const closeIdx = promptRegion.indexOf('rl.close();');- expect(resolveIdx).toBeGreaterThan(-1);- expect(closeIdx).toBeGreaterThan(-1);- expect(resolveIdx).toBeLessThan(closeIdx);+ test('EOF declines instead of hanging', async () => {+ expect((await answer(null)).enabled).toBe(false);});- test('the [Y/n] default-yes contract is preserved: an empty (Enter-only) answer resolves true', () => {- // The prompt reads "(recommended) [Y/n]" — pressing Enter with no text- // must accept the recommendation. A fix that only reordered- // resolve/close without preserving this branch (e.g. narrowing to- // `a === 'y' || a === 'yes'`) would still pass the two tests above while- // silently flipping this prompt's default from accept to decline.- const idx = src.indexOf('[gbrain] Enable skill publishing now?');- const promptRegion = src.slice(idx - 100, idx + 700);- expect(promptRegion).toContain("resolveAns(a === '' || a === 'y' || a === 'yes');");+ test('a non-interactive caller (agent marker) declines without reading', async () => {+ const r = await answer('y\n', { env: { CLAUDECODE: '1' }, stdinIsTTY: true, stdoutIsTTY: true });+ expect(r.enabled).toBe(false);+ expect(r.prompt).toBe('');});});