Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(mcp): coaching reaches agents — advisor on stdio by default, writeback ask until answered, nudges and post-upgrade summary as notices (F7)

garrytana3a40341ca66
diff --git a/docs/architecture/key-files/core-services-1.md b/docs/architecture/key-files/core-services-1.md
index 963644569c..5cdf963a55 100644
--- a/docs/architecture/key-files/core-services-1.md
+++ b/docs/architecture/key-files/core-services-1.md
@@ -3,7 +3,7 @@
[Subsystem index](../KEY_FILES.md). Read only the entries relevant to your change.
Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.
-- `src/core/advisor/{types,run,render,recommended-set,history,apply,collect-*}.ts` + `src/commands/advisor.ts` — `gbrain advisor`: read-only ranked actions from brain state. `run.runAdvisor` executes the hardcoded COLLECTORS array (version [cache-only], migration, schema-pack, stalled-jobs [absent-table tolerant], usage-shape, setup-smells, uninstalled-brain-pack, uninstalled-bundled, chronicle, mcp-client-fit), each in its own try/catch; `collect-mcp-client-fit.ts` (E3) flags full-surface MCP clients whose 30d usage fits STARTER_OPS (exact `rescope-client --surface starter` fix; ≥10-call threshold; automation-shaped clients excluded per D12) plus STARTER_OPS drift (top-used ops missing; starter members unused 90d) via the shared `src/core/mcp-usage.ts` reader — starter membership is judged against the exported `ALWAYS_INCLUDED_STARTER_OPS` (surface.ts) so the always-included lane never reads as unused, and the missing-from-starter arm excludes `localOnly` ops (never proposable for a network surface, mirroring derive-starter-ops) — REMOTE runs redact client identifiers to aggregate counts (amendment 29), and its dismiss/snooze rides the nag-state engine with its own `~/.gbrain/advisor-usage-nag-state.json` (local runs only); `rankFindings` orders critical>warn>info then collector order, caps the info tail, and drops `workspace_dependent` findings when `remote` (A1). `render.ts` is the shared `=`-bar renderer used by the advisor AND `post-install-advisory.ts` (generalized to a single current-state `recommended-set.RECOMMENDED`, `install`→`scaffold`). `history.ts` appends bounded `~/.gbrain/advisor-history.jsonl` (no DB migration) for since-last-run deltas; local-only. `apply.resolveApplyTarget` is the allowlist+injection guard for `commands/advisor.ts --apply <id>` (structured argv, never a shell; local-only). The `advisor` op (`operations.ts`) is read-scoped, NOT localOnly, gated by `mcp.publish_advisor` (config.ts; default off) and strictly read-only on remote. CLI wired in `cli.ts` (`CLI_ONLY` + dispatch). Bundled skill `skills/gbrain-advisor/` + weekly cron recipe. Tests: `test/advisor-{core,apply,op-gate,ranking-eval}.test.ts`.
+- `src/core/advisor/{types,run,render,recommended-set,history,apply,collect-*}.ts` + `src/commands/advisor.ts` — `gbrain advisor`: read-only ranked actions from brain state. `run.runAdvisor` executes the hardcoded COLLECTORS array (version [cache-only], migration, schema-pack, stalled-jobs [absent-table tolerant], usage-shape, setup-smells, uninstalled-brain-pack, uninstalled-bundled, chronicle, mcp-client-fit), each in its own try/catch; `collect-mcp-client-fit.ts` (E3) flags full-surface MCP clients whose 30d usage fits STARTER_OPS (exact `rescope-client --surface starter` fix; ≥10-call threshold; automation-shaped clients excluded per D12) plus STARTER_OPS drift (top-used ops missing; starter members unused 90d) via the shared `src/core/mcp-usage.ts` reader — starter membership is judged against the exported `ALWAYS_INCLUDED_STARTER_OPS` (surface.ts) so the always-included lane never reads as unused, and the missing-from-starter arm excludes `localOnly` ops (never proposable for a network surface, mirroring derive-starter-ops) — REMOTE runs redact client identifiers to aggregate counts (amendment 29), and its dismiss/snooze rides the nag-state engine with its own `~/.gbrain/advisor-usage-nag-state.json` (local runs only); `rankFindings` orders critical>warn>info then collector order, caps the info tail, and drops `workspace_dependent` findings when `remote` (A1). `render.ts` is the shared `=`-bar renderer used by the advisor AND `post-install-advisory.ts` (generalized to a single current-state `recommended-set.RECOMMENDED`, `install`→`scaffold`). `history.ts` appends bounded `~/.gbrain/advisor-history.jsonl` (no DB migration) for since-last-run deltas; local-only. `apply.resolveApplyTarget` is the allowlist+injection guard for `commands/advisor.ts --apply <id>` (structured argv, never a shell; local-only). The `advisor` op (`operations.ts`) is read-scoped, NOT localOnly, gated by `mcp.publish_advisor` (`readPublishGate`: on by default for the owner's stdio server, off for HTTP unless set; an explicit `false` or a failed read hides it) and strictly read-only on remote. The `writeback-consent` collector reaches MCP callers and stays until the user answers (`memory.auto_writeback` set to any value). CLI wired in `cli.ts` (`CLI_ONLY` + dispatch). Bundled skill `skills/gbrain-advisor/` + weekly cron recipe. Tests: `test/advisor-{core,apply,op-gate,ranking-eval}.test.ts`.
- `src/core/audit/audit-writer.ts` — shared JSONL audit primitive behind the audit modules. Exports `createAuditWriter({kind, recordSchema})` returning `{log, readRecent}` plus shared helpers `computeIsoWeekFilename(kind, now?)` and `resolveAuditDir()` (honors `GBRAIN_AUDIT_DIR`). ISO-week file rotation; best-effort writes (stderr warn on failure, never throws); read-path scans current-week + previous-week files for boundary spans. Built on it: `src/core/rerank-audit.ts`, `src/core/audit-slug-fallback.ts`, `src/core/minions/handlers/shell-audit.ts`, `src/core/minions/handlers/supervisor-audit.ts`, `src/core/facts/phantom-audit.ts`. The `graph-signals-failures` audit (`logGraphSignalsFailure`) uses the same primitive. `src/core/skillpack/audit.ts` is the one audit that does not use it. Pinned by `test/audit/audit-writer.test.ts`.
diff --git a/docs/guides/skill-reference.md b/docs/guides/skill-reference.md
index a5ef341ded..e84a43df56 100644
--- a/docs/guides/skill-reference.md
+++ b/docs/guides/skill-reference.md
@@ -28,8 +28,8 @@ via `nag-state.ts`) and over MCP via the source-scoped `list_brain_skillpack` op
`get_skill --source_id` (gated by `mcp.publish_skills`). The bundled `gbrain-advisor` skill
+ `gbrain advisor` op compute a ranked, read-only list of high-leverage actions from brain
state (8 collectors in `src/core/advisor/`); `--json`+exit codes for CI/cron, local-only
-`--apply <id>` behind confirm, exposed over MCP behind `mcp.publish_advisor` (default off,
-read-only on remote). Thin-client binary install stays deferred to PR2 `build_skillpack`.
+`--apply <id>` behind confirm, exposed over MCP behind `mcp.publish_advisor` (read-only; on
+by default for the local stdio server, opt-in for remote HTTP; an explicit `false` hides it). Thin-client binary install stays deferred to PR2 `build_skillpack`.
**Routing-table compression (v0.32.3.0):** `skills/functional-area-resolver/` —
two-layer dispatch pattern for shrinking large AGENTS.md / RESOLVER.md files
diff --git a/docs/operations/mcp-surface-runbook.md b/docs/operations/mcp-surface-runbook.md
index a429c26e3d..aade9a6a71 100644
--- a/docs/operations/mcp-surface-runbook.md
+++ b/docs/operations/mcp-surface-runbook.md
@@ -15,8 +15,10 @@ server restart unless it says so.
Gated ops (`Operation.publishGateKey`): `list_skills` / `get_skill` /
`list_brain_skillpack` (`mcp.publish_skills`) and `advisor`
-(`mcp.publish_advisor`). Both gates default OFF: the ops are hidden from
-remote tools/list AND denied at call time.
+(`mcp.publish_advisor`). Both gates default OFF for remote HTTP callers: the
+ops are hidden from remote tools/list AND denied at call time. The read-only
+advisor defaults ON for the owner's local stdio server (an explicit `false`
+hides it there too).
```bash
gbrain config set mcp.publish_skills true # or mcp.publish_advisor
diff --git a/scripts/agent-contract-baselines/marker-literal.tsv b/scripts/agent-contract-baselines/marker-literal.tsv
index 5c93fe99e4..c4bd40f8d4 100644
--- a/scripts/agent-contract-baselines/marker-literal.tsv
+++ b/scripts/agent-contract-baselines/marker-literal.tsv
@@ -6,5 +6,4 @@ src/commands/google.ts 4
src/commands/init-mode-picker.ts 6
src/commands/upgrade.ts 5
src/core/advisor/render.ts 2
-src/core/onboard/writeback-nudge.ts 5
src/core/skillpack/brain-pack-advisory.ts 1
diff --git a/src/commands/features.ts b/src/commands/features.ts
index 4c65d2fc7c..495b575c0a 100644
--- a/src/commands/features.ts
+++ b/src/commands/features.ts
@@ -10,6 +10,8 @@ import { join } from 'path';
import type { BrainEngine } from '../core/engine.ts';
import { heartbeatPath } from './integrations.ts';
import { VERSION } from '../version.ts';
+import { cliRenderContext, renderNotice, type Notice } from '../core/agent-output.ts';
+import { writeCliNotices } from '../core/interop-notices.ts';
// --- Types ---
@@ -284,6 +286,9 @@ export async function runFeatures(engine: BrainEngine, args: string[]) {
return;
}
+ // F7: the auto-fix suggestion is a coaching notice on every surface (it was
+ // printed only on a terminal); --json carries it under `notices`.
+ const autoFixNotice = autoFix ? null : featuresAutoFixNotice(pitchable);
if (jsonMode) {
const fixResults: Record<string, { success: boolean; output: string }> = {};
if (autoFix) {
@@ -292,7 +297,8 @@ export async function runFeatures(engine: BrainEngine, args: string[]) {
offers.accepted[rec.id] = { at: new Date().toISOString().slice(0, 10), version: scan.version };
}
}
- console.log(JSON.stringify({ ...scan, recommendations: pitchable, auto_fix_results: autoFix ? fixResults : undefined }, null, 2));
+ console.log(JSON.stringify({ ...scan, recommendations: pitchable, auto_fix_results: autoFix ? fixResults : undefined,
+ ...(autoFixNotice ? { notices: [renderNotice(autoFixNotice, cliRenderContext())] } : {}) }, null, 2));
offers.lastVersion = scan.version;
offers.lastScan = scan.scan_ts;
saveOffers(offers);
@@ -330,8 +336,8 @@ export async function runFeatures(engine: BrainEngine, args: string[]) {
console.log(` ${result.success ? 'OK' : 'FAIL'}: ${rec.title} — ${result.output}`);
offers.accepted[rec.id] = { at: new Date().toISOString().slice(0, 10), version: scan.version };
}
- } else if (process.stdin.isTTY) {
- console.log(`Run 'gbrain features --auto-fix' to fix all auto-fixable issues.`);
+ } else if (autoFixNotice) {
+ writeCliNotices([autoFixNotice]);
}
offers.lastVersion = scan.version;
@@ -339,6 +345,22 @@ export async function runFeatures(engine: BrainEngine, args: string[]) {
saveOffers(offers);
}
+/** F7: the `features_auto_fix` coaching notice; null when nothing is auto-fixable. */
+function featuresAutoFixNotice(pitchable: readonly FeatureRecommendation[]): Notice | null {
+ const fixable = pitchable.filter(r => r.auto_fixable);
+ if (fixable.length === 0) return null;
+ const paid = fixable.some(r => r.id === 'missing-embeddings' || r.id === 'low-coverage');
+ return {
+ code: 'features_auto_fix', kind: 'coaching',
+ why: `${fixable.length} recommendation(s) can be fixed automatically: ${fixable.map(r => r.title).join(', ')}.`,
+ fix: {
+ argv: ['gbrain', 'features', '--auto-fix'], consent: paid ? ['paid'] : [], actor: 'agent', requires_exclusive: false,
+ why: paid ? 'Runs the fixes; refreshing embeddings calls the configured embedding provider (a small paid cost).' : 'Runs the fixes (link and timeline extraction; no paid calls).',
+ ...(paid ? { user_message: 'gbrain can fill in missing embeddings for your notes; it costs a little in embedding API calls. OK to run it?' } : {}),
+ },
+ };
+}
+
/** Lightweight features teaser for doctor output */
export async function featuresTeaserForDoctor(engine: BrainEngine): Promise<string | null> {
try {
diff --git a/src/commands/upgrade.ts b/src/commands/upgrade.ts
index 3019c3f6bc..31aa657807 100644
--- a/src/commands/upgrade.ts
+++ b/src/commands/upgrade.ts
@@ -590,9 +590,7 @@ export async function runPostUpgrade(args: string[] = []): Promise<void> {
try {
const { ensureGitignore } = await import('../core/config.ts');
ensureGitignore();
- } catch {
- // Best-effort hygiene; never block upgrade.
- }
+ } catch { /* Best-effort hygiene; never block upgrade. */ }
// v0.42 self-upgrade setup: default existing installs to NOTIFY (a nudge, no
// autonomy), inform once, and rewrite an existing systemd unit to
@@ -625,6 +623,7 @@ export async function runPostUpgrade(args: string[] = []): Promise<void> {
// Pitch printing is cosmetic — don't gate migrations on it.
}
+ (await import('../core/post-upgrade-notice.ts')).writePostUpgradeCliNotice(); // F7: safety notice ([AGENT] block for agents)
// Mechanical: run every outstanding migration. Idempotent; exits 0 quickly
// when nothing is pending. Stays inside the same process so a long Phase F
// (autopilot install) doesn't hit a subprocess boundary.
diff --git a/src/core/advisor/collect-writeback-consent.ts b/src/core/advisor/collect-writeback-consent.ts
index f16d5fe7f1..526a21d5f8 100644
--- a/src/core/advisor/collect-writeback-consent.ts
+++ b/src/core/advisor/collect-writeback-consent.ts
@@ -1,16 +1,16 @@
/**
- * collect-writeback-consent — the ambient-writeback nudge's RECURRING pull
- * surface (WP8). Reminder role only: it emits nothing until the one-time
- * init/post-upgrade ask has fired (the sentinel), so the advisor never
- * becomes the FIRST place a consent question appears. Personal brains only
- * (declaration > heuristic), local-only (`ctx.remote` drops it), and
- * deliberately NOT `--apply`-able: consent must never be automated, so there
+ * collect-writeback-consent — the ambient-writeback ask's RECURRING pull
+ * surface (WP8). It stays until the user ANSWERS (any memory.auto_writeback
+ * value, `off` included — agent contract F7), and it reaches MCP callers too
+ * (the advisor is published on stdio by default), so an agent that never saw
+ * the init/post-upgrade print still learns the decision is pending. Personal
+ * brains only (declaration > heuristic) and deliberately NOT `--apply`-able: consent must never be automated, so there
* is no `dispatch_id` and `command_argv` is null — the render footer's "ask
* before running any fix" plus `ask_user: true` carry the posture.
*/
import type { AdvisorCollector } from './types.ts';
-import { AUTO_WRITEBACK_KEY, AUTO_WRITEBACK_NOTICE_KEY } from '../facts/writeback-config.ts';
+import { AUTO_WRITEBACK_KEY } from '../facts/writeback-config.ts';
import { classifyBrainAudience } from '../facts/writeback-audience.ts';
import { isThinClient } from '../config.ts';
import { resolveBrainId } from '../brain-resolver.ts';
@@ -19,18 +19,13 @@ import { HOST_BRAIN_ID } from '../brain-registry.ts';
export const collectWritebackConsent: AdvisorCollector = {
id: 'writeback-consent',
collect: async (ctx) => {
- if (ctx.remote) return [];
if (isThinClient(ctx.config)) return [];
try {
if (resolveBrainId(undefined) !== HOST_BRAIN_ID) return [];
} catch {
return [];
}
- const [shown, mode] = await Promise.all([
- ctx.engine.getConfig(AUTO_WRITEBACK_NOTICE_KEY),
- ctx.engine.getConfig(AUTO_WRITEBACK_KEY),
- ]);
- if (shown !== 'true' || mode) return []; // first ask pending, or already decided
+ if (await ctx.engine.getConfig(AUTO_WRITEBACK_KEY)) return []; // the user answered
const audience = await classifyBrainAudience(ctx.engine, ctx.config);
if (audience.audience !== 'personal') return [];
return [{
@@ -41,7 +36,8 @@ export const collectWritebackConsent: AdvisorCollector = {
'Agents would save durable facts the user states directly (preferences, decisions, ' +
'commitments) with provenance; transient facts get a short TTL. Ask the user before ' +
'anything: enable with `gbrain config set memory.auto_writeback salient`, then ' +
- '`gbrain bootstrap harness --yes`. Off switch: `gbrain config set memory.auto_writeback off`.',
+ '`gbrain bootstrap harness --yes`. If they decline, record it with ' +
+ '`gbrain config set memory.auto_writeback off` (this finding then stops).',
fix: { command_argv: null },
collector: 'writeback-consent',
ask_user: true,
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index 61d6053916..a8c90b546b 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -293,4 +293,7 @@ export const NOTICE_CODES = {
degraded_dedup: { kind: 'info', summary: 'remember ran without an embedding provider, so only exact duplicates are detected.' },
synthesis_keyless: { kind: 'info', summary: 'think returned gathered evidence without synthesis because no chat-model key is configured (by design on a keyless brain).' },
think_not_saved: { kind: 'info', summary: 'think save/take persist only for the local CLI, so this answer was not saved.' },
+ onboard_opportunities: { kind: 'coaching', summary: 'Onboarding checks found work that would improve this brain (gbrain onboard --check lists it).' },
+ features_auto_fix: { kind: 'coaching', summary: 'gbrain features found auto-fixable gaps; the fix is the auto-fix command (it may spend on embeddings).' },
+ post_upgrade: { kind: 'safety', summary: 'gbrain was upgraded; behavior for scripts and agents changed — read the behavior table once.' },
} as const satisfies Record<string, NoticeEntry>;
diff --git a/src/core/interop-notices.ts b/src/core/interop-notices.ts
index 627e7f9e55..6de56712ca 100644
--- a/src/core/interop-notices.ts
+++ b/src/core/interop-notices.ts
@@ -7,7 +7,9 @@
* `ctx.emitNotice` (ops) or dispatch's notice list (MCP). Notices interpolate
* ids and closed-vocabulary stage names only, never page text.
*/
-import type { Action, Notice } from './agent-output.ts';
+import { cliRenderContext, renderNotice, type Action, type Notice } from './agent-output.ts';
+import { renderCliNotices } from './agent-markers.ts';
+import { isInteractive } from './interaction.ts';
import type { GBrainConfig } from './config.ts';
import type { ExplicitReadBinding } from './ops/contract.ts';
import { configReadiness } from './readiness.ts';
@@ -229,3 +231,24 @@ export function recallInteropNotices(
return [];
}
}
+
+// ── CLI emission for commands without a result document (F7) ──────────────
+
+/**
+ * Write notices from a CLI command's human path: a terminal gets readable
+ * stderr lines, a non-interactive caller (an agent) gets `[AGENT]` blocks on
+ * stdout, and a `--json` invocation keeps stdout for its document (stderr).
+ * Never throws.
+ */
+export function writeCliNotices(notices: readonly Notice[]): void {
+ try {
+ if (notices.length === 0) return;
+ const rendered = notices.map(n => renderNotice(n, cliRenderContext()));
+ const args = process.argv.slice(2);
+ const end = args.indexOf('--');
+ const json = (end < 0 ? args : args.slice(0, end)).some(a => a === '--json' || a === '--json=true');
+ const out = renderCliNotices(rendered, { json: false, tty: isInteractive(), stdoutIsData: json });
+ if (out.stdout) process.stdout.write(out.stdout);
+ if (out.stderr) process.stderr.write(out.stderr);
+ } catch { /* coaching never breaks a command */ }
+}
diff --git a/src/core/onboard/init-nudge.ts b/src/core/onboard/init-nudge.ts
index 69c2b15747..a029e6a6cf 100644
--- a/src/core/onboard/init-nudge.ts
+++ b/src/core/onboard/init-nudge.ts
@@ -10,10 +10,11 @@
// codex #7 finding's wrong shape. Cancelled queries actually stop on
// Postgres; PGLite has a documented gap.
//
-// Bypass: GBRAIN_NO_ONBOARD_NUDGE=1 short-circuits. Non-TTY default
-// also short-circuits (CI/scripted callers see nothing).
+// Bypass: GBRAIN_NO_ONBOARD_NUDGE=1 short-circuits. Non-interactive callers
+// (agents) get the same coaching as an [AGENT] block (agent contract F7).
import type { BrainEngine } from '../engine.ts';
+import { writeCliNotices } from '../interop-notices.ts';
const NUDGE_BUDGET_MS = 3000;
@@ -22,18 +23,17 @@ const NUDGE_BUDGET_MS = 3000;
*
* Returns silently when:
* - GBRAIN_NO_ONBOARD_NUDGE=1
- * - Non-TTY environment (CI, scripted)
* - All 4 onboard checks complete within 3s AND surface 0 recommendations
* - ANY error during check execution (logged to stderr, suppressed)
*
- * Prints a nudge to stderr when:
+ * Emits an `onboard_opportunities` coaching notice (stderr on a terminal,
+ * an [AGENT] block on stdout for a non-interactive caller) when:
* - Recommendations exist within budget
* - Some checks ran but budget fired (partial-results path)
*/
export async function runInitNudge(engine: BrainEngine): Promise<void> {
try {
if (process.env.GBRAIN_NO_ONBOARD_NUDGE === '1') return;
- if (!process.stderr.isTTY) return;
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), NUDGE_BUDGET_MS);
@@ -138,19 +138,17 @@ export async function runInitNudge(engine: BrainEngine): Promise<void> {
}
if (takesCount === 0) parts.push('0 takes');
- if (parts.length === 0 && partial) {
- process.stderr.write(
- `\n[onboard] Init checks incomplete (${checksRan}/${checksAttempted}) — run 'gbrain onboard --check' for full recommendations.\n`,
- );
- return;
- }
-
- process.stderr.write(
- `\n[onboard] Brain has opportunities: ${parts.join(', ')}.\n` +
- `[onboard] Run 'gbrain onboard --check' to see the plan.` +
- (partial ? ` (${checksRan}/${checksAttempted} checks complete; run gbrain onboard --check for full recommendations)` : '') +
- `\n`,
- );
+ // Agent contract v1 (F7): a coaching notice on every surface — terminal
+ // lines, an [AGENT] block for a non-interactive caller (no more silence
+ // exactly when an agent runs init).
+ const why = parts.length === 0
+ ? `Init checks incomplete (${checksRan}/${checksAttempted}) — run 'gbrain onboard --check' for full recommendations.`
+ : `Brain has opportunities: ${parts.join(', ')}. Run 'gbrain onboard --check' to see the plan.` +
+ (partial ? ` (${checksRan}/${checksAttempted} checks complete; run gbrain onboard --check for full recommendations)` : '');
+ writeCliNotices([{
+ code: 'onboard_opportunities', kind: 'coaching', why,
+ fix: { argv: ['gbrain', 'onboard', '--check'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Lists each recommendation with its command; read-only.' },
+ }]);
} catch (err) {
// A18: NEVER crash init from the nudge. Log and continue.
process.stderr.write(`[onboard] nudge skipped (${err instanceof Error ? err.message : String(err)})\n`);
@@ -164,10 +162,11 @@ export async function runInitNudge(engine: BrainEngine): Promise<void> {
export async function runUpgradeBanner(_engine: BrainEngine): Promise<void> {
try {
if (process.env.GBRAIN_NO_ONBOARD_NUDGE === '1') return;
- if (!process.stderr.isTTY) return;
- process.stderr.write(
- `\n[onboard] Upgrade complete. Run 'gbrain onboard --check' to see if the new version surfaces any new opportunities.\n`,
- );
+ writeCliNotices([{
+ code: 'onboard_opportunities', kind: 'coaching',
+ why: "Upgrade complete. Run 'gbrain onboard --check' to see if the new version surfaces any new opportunities.",
+ fix: { argv: ['gbrain', 'onboard', '--check'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Lists each recommendation with its command; read-only.' },
+ }]);
} catch {
// A18 posture for symmetry.
}
diff --git a/src/core/onboard/writeback-nudge.ts b/src/core/onboard/writeback-nudge.ts
index e463963586..1962fcde8e 100644
--- a/src/core/onboard/writeback-nudge.ts
+++ b/src/core/onboard/writeback-nudge.ts
@@ -8,8 +8,9 @@
* Discipline copied from the two proven one-shot surfaces:
* - `runPostUpgrade`'s search-mode banner (upgrade.ts): DOUBLE gate
* (sentinel + the setting still unset), whole block try/catch
- * ("cosmetic, never block"), sentinel stamped AFTER printing so a
- * decline is permanent.
+ * ("cosmetic, never block"). The fire-once sentinel is a legacy
+ * stamp only: the ask now repeats (init / post-upgrade) until the
+ * user ANSWERS by setting memory.auto_writeback (agent contract F7).
* - `runModePicker`'s non-TTY arm (init-mode-picker.ts): `[AGENT]` lines
* carry the ask — agents MUST relay them to the operator (AGENTS.md
* contract). Unlike runInitNudge this does NOT short-circuit on non-TTY:
@@ -23,6 +24,7 @@
*/
import type { BrainEngine } from '../engine.ts';
+import { agentBlock } from '../agent-markers.ts';
import { loadConfig, isThinClient } from '../config.ts';
import { resolveBrainId } from '../brain-resolver.ts';
import { HOST_BRAIN_ID } from '../brain-registry.ts';
@@ -77,17 +79,19 @@ export async function runWritebackNudge(
line('[gbrain] Off switch (anytime): gbrain config set memory.auto_writeback off,');
line('[gbrain] then gbrain bootstrap harness --yes to remove installed instruction blocks.');
line('═══════════════════════════════════════════════════════════════');
- line('[AGENT] One-time ask — relay to your operator: enable ambient memory');
- line('[AGENT] writeback for this personal brain? Recommended mode: salient.');
- line('[AGENT] If they say yes, run: gbrain config set memory.auto_writeback salient');
- line('[AGENT] then: gbrain bootstrap harness --yes');
- line('[AGENT] If they decline, do nothing — this ask never repeats.');
- line('');
-
- // Stamp AFTER printing, unconditionally: a decline is permanent (the
- // advisor keeps a quiet, non-applyable reminder; `gbrain config set
- // memory.auto_writeback salient` reopens the door at any time).
- await engine.setConfig(AUTO_WRITEBACK_NOTICE_KEY, 'true');
+ // Agent contract v1 (F7): the ask is a decision for the user; the
+ // sentinel is stamped on their ANSWER (any memory.auto_writeback value,
+ // `off` included), never on print — a non-TTY print nobody relayed must
+ // not burn the only ask.
+ line(agentBlock({
+ ask: 'Enable ambient memory writeback for this personal brain? Recommended mode: salient.',
+ why: 'Agents would save durable facts the user states directly, with provenance; nothing is enabled until the user agrees.',
+ consent: 'persistent_install',
+ actor: 'user',
+ if_yes: 'gbrain config set memory.auto_writeback salient, then gbrain bootstrap harness --yes',
+ if_no: 'gbrain config set memory.auto_writeback off (records the answer; this ask then stops)',
+ verify: 'gbrain config get memory.auto_writeback',
+ }, { showUser: 'Should I save important facts from our conversations automatically (ambient writeback, "salient" mode)? You can turn it off any time.' }));
} catch {
/* Nudge is cosmetic — init/upgrade MUST succeed even if it crashes. */
}
diff --git a/src/core/ops/request-tools.ts b/src/core/ops/request-tools.ts
index 72fc8bb141..09ac3f87e6 100644
--- a/src/core/ops/request-tools.ts
+++ b/src/core/ops/request-tools.ts
@@ -88,7 +88,7 @@ async function visibleOpsForCaller(
if (!gateExempt) {
try {
const { disabledOpsForPublishGates } = await import('../../mcp/publish-gates.ts');
- gateDisabled = await disabledOpsForPublishGates(ctx.engine, ctx.config);
+ gateDisabled = await disabledOpsForPublishGates(ctx.engine, ctx.config, { transport: ctx.transport });
} catch {
// Fail-closed: if the resolver can't even load, hide every gated op.
gateDisabled = new Set(operations.filter(o => o.publishGateKey).map(o => o.name));
diff --git a/src/core/ops/skills-catalog.ts b/src/core/ops/skills-catalog.ts
index d2bedaae8e..bbf7b1c76d 100644
--- a/src/core/ops/skills-catalog.ts
+++ b/src/core/ops/skills-catalog.ts
@@ -253,21 +253,17 @@ const advisor: Operation = {
'Ranked, read-only "what to do next" for this brain: version drift, pending migrations, ' +
'schema-pack issues, stalled jobs, usage-shape gaps, and setup smells. Each finding has a ' +
'severity, why-it-matters, and the exact fix command. Never mutates. Tell the user; ask ' +
- 'before running any fix. Gated by mcp.publish_advisor (separate from mcp.publish_skills ' +
- 'because diagnostics are not prose skills).',
+ 'before running any fix. On by default for the local stdio server; remote HTTP callers need ' +
+ 'mcp.publish_advisor (separate from mcp.publish_skills because diagnostics are not prose skills).',
publishGateKey: 'mcp.publish_advisor',
params: {},
handler: async (ctx) => {
// Publish gate: a remote caller needs mcp.publish_advisor=true. Local
// (ctx.remote === false) callers bypass — the trust boundary is the OS.
if (ctx.remote !== false) {
- let enabled = false;
- try {
- const dbVal = await ctx.engine.getConfig('mcp.publish_advisor');
- enabled = dbVal != null ? dbVal === 'true' : ctx.config?.mcp?.publish_advisor === true;
- } catch {
- enabled = ctx.config?.mcp?.publish_advisor === true;
- }
+ // F7: on by default for the owner's stdio pipe; opt-in over HTTP.
+ const { readPublishGate } = await import('../../mcp/publish-gates.ts');
+ const enabled = await readPublishGate(ctx.engine, ctx.config, 'mcp.publish_advisor', ctx.transport);
if (!enabled) {
// Same k=v detail grammar as assertPublishEnabled (WP1): honest
// catalogs hide this op at list time; the throw is the backstop.
diff --git a/src/core/post-upgrade-notice.ts b/src/core/post-upgrade-notice.ts
new file mode 100644
index 0000000000..cf3979e7c6
--- /dev/null
+++ b/src/core/post-upgrade-notice.ts
@@ -0,0 +1,78 @@
+/**
+ * The post-upgrade summary as a notice (agent operator contract v1, F7):
+ * `kind: safety`, carrying contract_version (rendered) and the behavior-table
+ * URL, emitted once by `gbrain post-upgrade` (terminal lines, or an [AGENT]
+ * block for an agent) and once per upgraded version to the first stdio MCP
+ * session (persisted under GBRAIN_HOME, so restarts do not repeat it).
+ * GBRAIN_NO_ONBOARD_NUDGE=1 silences both. Never throws.
+ */
+import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
+import { dirname, join } from 'node:path';
+import type { Notice } from './agent-output.ts';
+import { writeCliNotices } from './interop-notices.ts';
+import { gbrainPath } from './config.ts';
+import { VERSION } from '../version.ts';
+
+const BEHAVIOR_TABLE = 'CHANGELOG.md#behavior-changes-for-scripts-and-agents';
+
+export function postUpgradeNotice(from: string | undefined, to: string = VERSION): Notice {
+ return {
+ code: 'post_upgrade',
+ kind: 'safety',
+ why: `gbrain was upgraded${from ? ` from v${from}` : ''} to v${to}. Agent contract v1 is in effect: errors carry \`code\` and a structured \`fix\` (follow fix.next), notices arrive as extra blocks, and exit 3 now means confirmation_required only. Scripts and agent instructions written for the old behavior should be checked against the behavior table.`,
+ fix: {
+ argv: ['gbrain', 'errors', '--changed'], consent: [], actor: 'agent', requires_exclusive: false,
+ why: 'Lists the error codes renamed in this release (old error value → new code); read-only.',
+ docs: BEHAVIOR_TABLE,
+ },
+ };
+}
+
+/** The last upgrade gbrain recorded (`~/.gbrain/upgrade-state.json`, written by `gbrain upgrade`). */
+function lastUpgrade(): { from?: string; to?: string } | null {
+ try {
+ const path = join(process.env.HOME || '', '.gbrain', 'upgrade-state.json');
+ if (!existsSync(path)) return null;
+ const state = JSON.parse(readFileSync(path, 'utf8')) as { last_upgrade?: { from?: string; to?: string } };
+ return state.last_upgrade ?? null;
+ } catch {
+ return null;
+ }
+}
+
+const seenPath = () => gbrainPath('notices', 'post-upgrade.json');
+let checked = false;
+
+/** Test seam: re-arm the once-per-process check. */
+export function __resetPostUpgradeNoticeForTests(): void { checked = false; }
+
+/**
+ * stdio MCP: the notice for the first session after an upgrade to this
+ * version, then never again for it. Checked once per process.
+ */
+export function takePostUpgradeMcpNotice(): Notice | null {
+ if (checked) return null;
+ checked = true;
+ try {
+ if (process.env.GBRAIN_NO_ONBOARD_NUDGE === '1') return null;
+ const up = lastUpgrade();
+ if (!up?.from || up.to !== VERSION) return null;
+ const path = seenPath();
+ try {
+ if ((JSON.parse(readFileSync(path, 'utf8')) as { shown_version?: string }).shown_version === VERSION) return null;
+ } catch { /* never shown */ }
+ mkdirSync(dirname(path), { recursive: true });
+ const tmp = `${path}.tmp-${process.pid}`;
+ writeFileSync(tmp, `${JSON.stringify({ shown_version: VERSION, at: new Date().toISOString() })}\n`, { mode: 0o600 });
+ renameSync(tmp, path);
+ return postUpgradeNotice(up.from, VERSION);
+ } catch {
+ return null;
+ }
+}
+
+/** `gbrain post-upgrade`: write the summary notice once (terminal lines or an [AGENT] block). */
+export function writePostUpgradeCliNotice(): void {
+ if (process.env.GBRAIN_NO_ONBOARD_NUDGE === '1') return;
+ writeCliNotices([postUpgradeNotice(lastUpgrade()?.from)]);
+}
diff --git a/src/core/shared-skills/tool-access.ts b/src/core/shared-skills/tool-access.ts
index 88566b0203..bdffef06e4 100644
--- a/src/core/shared-skills/tool-access.ts
+++ b/src/core/shared-skills/tool-access.ts
@@ -11,7 +11,7 @@ export async function sharedSkillToolAccess(ctx: OperationContext): Promise<stri
const scopes = ctx.auth?.scopes ?? currentVerifiedLocalWriter()?.grant.scopes ?? [];
const grant = ctx.auth?.allowedOperations ?? currentVerifiedLocalWriter()?.grant.operations;
const surface = allowedOpNames(operations, ctx.auth?.effectiveSurface ?? 'full');
- const disabled = await disabledOpsForPublishGates(ctx.engine, ctx.config);
+ const disabled = await disabledOpsForPublishGates(ctx.engine, ctx.config, { transport: ctx.transport });
return operations.filter(op => {
if (op.localOnly || !surface.has(op.name) || disabled.has(op.name) || !operationScopesAllowed(scopes, op) || grant != null && !grant.includes(op.name)) return false;
try { enforceBoundClientOpAllowList(ctx.auth, op); } catch { return false; }
diff --git a/src/mcp/dispatch.ts b/src/mcp/dispatch.ts
index deb9d1db57..8772502d5f 100644
--- a/src/mcp/dispatch.ts
+++ b/src/mcp/dispatch.ts
@@ -19,6 +19,7 @@ import { mutedNoticeCodes, processNoticeLedger, __resetProcessNoticeLedgerForTes
import { logVerbUsage } from '../core/verbs/usage-log.ts';
import { recallInteropNotices } from '../core/interop-notices.ts';
import { hiddenToolHint } from './hidden-tool-hint.ts';
+import { takePostUpgradeMcpNotice } from '../core/post-upgrade-notice.ts';
import { sourceGuardBlocksWrite } from '../core/source-resolver.ts';
import { suggestNearest } from '../core/levenshtein.ts';
import {
@@ -814,6 +815,7 @@ export async function dispatchToolCall(
// transport ONLY — the WP1/D7 locality axis localOnly ops use; 'http' or
// an UNSET marker never probes (fail-closed).
maybeBackupNotice(notices, opts);
+ if (opts.transport === 'stdio' && opts.remote !== false) { const up = takePostUpgradeMcpNotice(); if (up) notices.push(up); } // F7
const out: ToolResult = toolResultWithNotices(result, admitNotices(notices, opts), dispatchRenderContext(opts));
if (opts.transport === 'stdio') {
maybeRefreshBackupStatusInProcess(engine);
diff --git a/src/mcp/publish-gates.ts b/src/mcp/publish-gates.ts
index 9c7868ed5b..3f6c40695c 100644
--- a/src/mcp/publish-gates.ts
+++ b/src/mcp/publish-gates.ts
@@ -23,22 +23,34 @@ import { operations, type Operation } from '../core/operations.ts';
export type PublishGateKey = NonNullable<Operation['publishGateKey']>;
-/** Dual-plane gate read: DB > file > false; read failure = false (hidden). */
+/**
+ * Gates that default ON for the owner's stdio pipe when neither plane sets
+ * them (agent contract v1, F7): the read-only advisor is coaching the local
+ * agent should see; remote HTTP stays opt-in. An explicit `false` wins.
+ */
+const STDIO_DEFAULT_ON: ReadonlySet<PublishGateKey> = new Set<PublishGateKey>(['mcp.publish_advisor']);
+
+/** Dual-plane gate read: DB > file > transport default (stdio advisor on; else false); read failure = false (hidden). */
export async function readPublishGate(
engine: BrainEngine,
config: GBrainConfig | null | undefined,
key: PublishGateKey,
+ transport?: string,
): Promise<boolean> {
let dbVal: string | null = null;
+ let readFailed = false;
try {
dbVal = await engine.getConfig(key);
} catch {
// Engine without a config table / transient error → file plane decides.
+ readFailed = true;
}
if (dbVal != null) return dbVal === 'true';
const mcp = config?.mcp as Record<string, unknown> | undefined;
- const fileKey = key.slice('mcp.'.length);
- return mcp?.[fileKey] === true;
+ const fileVal = mcp?.[key.slice('mcp.'.length)];
+ if (typeof fileVal === 'boolean') return fileVal;
+ // Hide-on-doubt: a failed read never takes the stdio default.
+ return !readFailed && transport === 'stdio' && STDIO_DEFAULT_ON.has(key);
}
/**
@@ -52,13 +64,14 @@ export async function readPublishGate(
export async function disabledOpsForPublishGates(
engine: BrainEngine,
config: GBrainConfig | null | undefined,
+ opts: { transport?: string } = {},
): Promise<ReadonlySet<string>> {
const gated = operations.filter(op => op.publishGateKey);
if (gated.length === 0) return new Set();
const keys = [...new Set(gated.map(op => op.publishGateKey as PublishGateKey))];
const resolved = new Map<PublishGateKey, boolean>();
await Promise.all(keys.map(async (key) => {
- resolved.set(key, await readPublishGate(engine, config, key));
+ resolved.set(key, await readPublishGate(engine, config, key, opts.transport));
}));
const disabled = new Set<string>();
for (const op of gated) {
diff --git a/src/mcp/server.ts b/src/mcp/server.ts
index 83e74aef2a..8be48f69b7 100644
--- a/src/mcp/server.ts
+++ b/src/mcp/server.ts
@@ -163,7 +163,7 @@ export async function stdioVisibleTools(
gateDisabled = new Set(surfacedOps.filter(o => o.publishGateKey).map(o => o.name));
} else {
try {
- gateDisabled = await disabledOpsForPublishGates(engine, loadConfig());
+ gateDisabled = await disabledOpsForPublishGates(engine, loadConfig(), { transport: 'stdio' });
} catch {
gateDisabled = new Set(surfacedOps.filter(o => o.publishGateKey).map(o => o.name));
}
diff --git a/test/ambient-writeback-lifecycle.serial.test.ts b/test/ambient-writeback-lifecycle.serial.test.ts
index 16f4fb538d..7a6e3b2d47 100644
--- a/test/ambient-writeback-lifecycle.serial.test.ts
+++ b/test/ambient-writeback-lifecycle.serial.test.ts
@@ -139,7 +139,7 @@ describe('ambient writeback — hermetic 5-step lifecycle', () => {
const initOut = execFileSync('bun', ['run', join(REPO, 'src/cli.ts'), 'init', '--pglite', '--no-embedding', '--non-interactive'], {
env: childEnv() as NodeJS.ProcessEnv, encoding: 'utf8', timeout: 180_000,
});
- expect(initOut).toContain('[AGENT] One-time ask');
+ expect(initOut).toContain('ask: Enable ambient memory writeback'); // F7: the [AGENT] decision block
expect(initOut).toContain('gbrain config set memory.auto_writeback salient');
// The ask fires ONCE: a second init pass over the same brain stays quiet
diff --git a/test/fixtures/goldens/cli/tools-json.json b/test/fixtures/goldens/cli/tools-json.json
index 8eb9d7c5f2..9481bad1c9 100644
--- a/test/fixtures/goldens/cli/tools-json.json
+++ b/test/fixtures/goldens/cli/tools-json.json
@@ -2,8 +2,8 @@
"golden": {
"exitCode": 0,
"stderr": "",
- "stdoutBytes": 229836,
- "stdoutSha256": "05879677743f457797f2e950a2dc1b28d33301479253bfcf8e663a4414155457",
+ "stdoutBytes": 229964,
+ "stdoutSha256": "dd329e72404ba7ca00c57ed651b3e48c3ac470a9b160cf1333f6c2b338a14e5e",
"toolNames": [
"remember",
"entity",
@@ -2097,7 +2097,7 @@
"scope": "read"
},
{
- "description": "Ranked, read-only \"what to do next\" for this brain: version drift, pending migrations, schema-pack issues, stalled jobs, usage-shape gaps, and setup smells. Each finding has a severity, why-it-matters, and the exact fix command. Never mutates. Tell the user; ask before running any fix. Gated by mcp.publish_advisor (separate from mcp.publish_skills because diagnostics are not prose skills).",
+ "description": "Ranked, read-only \"what to do next\" for this brain: version drift, pending migrations, schema-pack issues, stalled jobs, usage-shape gaps, and setup smells. Each finding has a severity, why-it-matters, and the exact fix command. Never mutates. Tell the user; ask before running any fix. On by default for the local stdio server; remote HTTP callers need mcp.publish_advisor (separate from mcp.publish_skills because diagnostics are not prose skills).",
"idempotent": true,
"local_only": false,
"mutating": false,
@@ -6226,7 +6226,9 @@
"backup_coverage",
"degraded_dedup",
"empty_retrieval",
+ "features_auto_fix",
"listing_truncated",
+ "onboard_opportunities",
"source_binding_narrowed",
"synthesis_keyless",
"think_not_saved",
diff --git a/test/init-nudge.test.ts b/test/init-nudge.test.ts
index 318aa0f92a..2710fd90d7 100644
--- a/test/init-nudge.test.ts
+++ b/test/init-nudge.test.ts
@@ -16,6 +16,7 @@
* Both isTTY and stderr.write are restored in finally.
*/
+import { withEnv } from './helpers/with-env.ts';
import { describe, test, expect } from 'bun:test';
import { runInitNudge } from '../src/core/onboard/init-nudge.ts';
import type { BrainEngine } from '../src/core/engine.ts';
@@ -60,18 +61,21 @@ function stubEngine(counts: ProbeCounts): BrainEngine {
* captured. Restores both in finally so no other test sees the patch.
*/
async function runNudgeCaptured(engine: BrainEngine): Promise<string> {
+ // Agent contract v1 (F7): the nudge is a notice on every surface — stderr
+ // lines on a terminal, an [AGENT] block on stdout otherwise — so capture both.
const origIsTTY = process.stderr.isTTY;
const origWrite = process.stderr.write;
+ const origOut = process.stdout.write;
let out = '';
+ const sink = ((chunk: unknown) => { out += String(chunk); return true; }) as typeof process.stderr.write;
try {
(process.stderr as unknown as { isTTY: boolean }).isTTY = true;
- process.stderr.write = ((chunk: unknown) => {
- out += String(chunk);
- return true;
- }) as typeof process.stderr.write;
+ process.stderr.write = sink;
+ process.stdout.write = sink as typeof process.stdout.write;
await runInitNudge(engine);
} finally {
process.stderr.write = origWrite;
+ process.stdout.write = origOut;
(process.stderr as unknown as { isTTY: boolean | undefined }).isTTY = origIsTTY;
}
return out;
@@ -138,3 +142,14 @@ describe('runInitNudge — non-empty brain opportunities', () => {
expect(out).not.toContain('checks complete');
});
});
+
+describe('runInitNudge — agents get the nudge too (F7)', () => {
+ test('a non-interactive caller gets an [AGENT] coaching block naming the command', async () => {
+ const out = await withEnv({ GBRAIN_NON_INTERACTIVE: '1', GBRAIN_INTERACTIVE: undefined }, () => runNudgeCaptured(
+ stubEngine({ stale: 0, entities: 0, linked: 0, timeline: 0, takes: 0, pages: 10 }),
+ ));
+ expect(out).toContain('[AGENT]');
+ expect(out).toContain('[onboard_opportunities]');
+ expect(out).toContain('gbrain onboard --check');
+ });
+});
diff --git a/test/mcp-notice-channels.test.ts b/test/mcp-notice-channels.test.ts
index 2ce7cc5c8e..716e0aa807 100644
--- a/test/mcp-notice-channels.test.ts
+++ b/test/mcp-notice-channels.test.ts
@@ -200,3 +200,44 @@ describe('F6 hidden-tool hint (owner stdio only)', () => {
expect(opaque.fix?.command).not.toBe('gbrain doctor --json');
});
});
+
+describe('F7 coaching reaches agents', () => {
+ test('the advisor is published on stdio by default; HTTP stays opt-in; explicit false and read failures hide it', async () => {
+ const { readPublishGate } = await import('../src/mcp/publish-gates.ts');
+ const unset = { getConfig: async () => null } as any;
+ expect(await readPublishGate(unset, {} as any, 'mcp.publish_advisor', 'stdio')).toBe(true);
+ expect(await readPublishGate(unset, {} as any, 'mcp.publish_advisor', 'http')).toBe(false);
+ expect(await readPublishGate(unset, {} as any, 'mcp.publish_skills', 'stdio')).toBe(false);
+ expect(await readPublishGate({ getConfig: async () => 'false' } as any, {} as any, 'mcp.publish_advisor', 'stdio')).toBe(false);
+ expect(await readPublishGate(unset, { mcp: { publish_advisor: false } } as any, 'mcp.publish_advisor', 'stdio')).toBe(false);
+ expect(await readPublishGate({ getConfig: async () => { throw new Error('down'); } } as any, {} as any, 'mcp.publish_advisor', 'stdio')).toBe(false);
+ });
+
+ test('post-upgrade: one safety notice per upgraded version on stdio, with contract_version and the behavior-table URL', async () => {
+ const { mkdtempSync, mkdirSync, writeFileSync, rmSync } = await import('node:fs');
+ const { join } = await import('node:path');
+ const { tmpdir } = await import('node:os');
+ const { VERSION } = await import('../src/version.ts');
+ const { takePostUpgradeMcpNotice, __resetPostUpgradeNoticeForTests } = await import('../src/core/post-upgrade-notice.ts');
+ const { renderNotice, cliRenderContext } = await import('../src/core/agent-output.ts');
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-postup-'));
+ try {
+ mkdirSync(join(home, '.gbrain'), { recursive: true });
+ writeFileSync(join(home, '.gbrain', 'upgrade-state.json'), JSON.stringify({ last_upgrade: { from: '0.0.1.0', to: VERSION } }));
+ await withEnv({ HOME: home, GBRAIN_HOME: home, GBRAIN_NO_ONBOARD_NUDGE: undefined }, async () => {
+ __resetPostUpgradeNoticeForTests();
+ const n = takePostUpgradeMcpNotice()!;
+ expect(n.code).toBe('post_upgrade');
+ expect(n.kind).toBe('safety');
+ const r = renderNotice(n, cliRenderContext());
+ expect(r.contract_version).toBe(1);
+ expect(r.fix?.docs).toMatch(/^https:\/\/.*CHANGELOG\.md#behavior-changes-for-scripts-and-agents$/);
+ __resetPostUpgradeNoticeForTests();
+ expect(takePostUpgradeMcpNotice()).toBeNull();
+ });
+ } finally {
+ rmSync(home, { recursive: true, force: true });
+ __resetPostUpgradeNoticeForTests();
+ }
+ });
+});
diff --git a/test/writeback-nudge.serial.test.ts b/test/writeback-nudge.serial.test.ts
index 86f0d6fc72..b059c5c6e7 100644
--- a/test/writeback-nudge.serial.test.ts
+++ b/test/writeback-nudge.serial.test.ts
@@ -125,18 +125,23 @@ describe('classifyBrainAudience — declaration beats heuristics', () => {
});
describe('runWritebackNudge — one-time ask, never auto-enables, never throws', () => {
- test('personal + unset → [AGENT] ask printed once, sentinel stamped, mode NOT set; second call silent', async () => {
+ test('personal + unset → [AGENT] ask with a relay; the sentinel is stamped on the ANSWER, not the print (F7)', async () => {
await withEnv({ GBRAIN_HOME: tmp, GBRAIN_NO_ONBOARD_NUDGE: undefined, GBRAIN_BRAIN_ID: undefined }, async () => {
const out = await captureLog(() => runWritebackNudge(engine, { context: 'init' }));
- expect(out).toContain('[AGENT] One-time ask');
- expect(out).toContain('gbrain config set memory.auto_writeback salient');
+ expect(out).toContain('[AGENT]');
+ expect(out).toContain('ask: Enable ambient memory writeback');
+ expect(out).toContain('if_yes: gbrain config set memory.auto_writeback salient');
+ expect(out).toContain('if_no: gbrain config set memory.auto_writeback off');
+ expect(out).toContain('[SHOW USER]');
expect(out).toContain('Off switch');
- expect(await engine.getConfig(AUTO_WRITEBACK_NOTICE_KEY)).toBe('true');
+ expect(await engine.getConfig(AUTO_WRITEBACK_NOTICE_KEY)).toBeNull();
// NEVER auto-enabled — the ask is the only output.
expect(await engine.getConfig(AUTO_WRITEBACK_KEY)).toBeNull();
- const out2 = await captureLog(() => runWritebackNudge(engine));
- expect(out2).toBe('');
+ // Unanswered → the next init/post-upgrade asks again; an answer stops it.
+ expect(await captureLog(() => runWritebackNudge(engine))).toContain('[AGENT]');
+ await engine.setConfig(AUTO_WRITEBACK_KEY, 'off');
+ expect(await captureLog(() => runWritebackNudge(engine))).toBe('');
});
});
@@ -170,7 +175,7 @@ describe('runWritebackNudge — one-time ask, never auto-enables, never throws',
});
});
-describe('collectWritebackConsent — reminder role, never the first ask, never apply-able', () => {
+describe('collectWritebackConsent — pending until answered, reaches MCP callers, never apply-able', () => {
function ctx(overrides: Partial<AdvisorContext> = {}): AdvisorContext {
return {
engine, config: { engine: 'pglite' } as GBrainConfig, version: 'test',
@@ -179,12 +184,7 @@ describe('collectWritebackConsent — reminder role, never the first ask, never
};
}
- test('before the sentinel → nothing (the advisor never fires the first consent ask)', async () => {
- expect(await collectWritebackConsent.collect(ctx())).toEqual([]);
- });
-
- test('after the sentinel, personal + unset → one info finding, ask_user, NO dispatch_id, null argv', async () => {
- await engine.setConfig(AUTO_WRITEBACK_NOTICE_KEY, 'true');
+ test('personal + unanswered → one info finding, ask_user, NO dispatch_id, null argv (sentinel not required, F7)', async () => {
const found = await collectWritebackConsent.collect(ctx());
expect(found.length).toBe(1);
expect(found[0].severity).toBe('info');
@@ -193,9 +193,8 @@ describe('collectWritebackConsent — reminder role, never the first ask, never
expect(found[0].fix.dispatch_id).toBeUndefined();
});
- test('suppressed for remote callers, decided brains, and shared brains', async () => {
- await engine.setConfig(AUTO_WRITEBACK_NOTICE_KEY, 'true');
- expect(await collectWritebackConsent.collect(ctx({ remote: true }))).toEqual([]);
+ test('returned to MCP (remote) callers; suppressed for answered and shared brains', async () => {
+ expect((await collectWritebackConsent.collect(ctx({ remote: true }))).length).toBe(1);
await engine.setConfig(AUTO_WRITEBACK_KEY, 'salient');
expect(await collectWritebackConsent.collect(ctx())).toEqual([]);
await engine.unsetConfig(AUTO_WRITEBACK_KEY);