Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(notices): the behavior-change notice no longer repeats on every upgrade (v0.60.76.0)
garrytanc2eb02f7d2ce
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.jsonindex 32657e8527..b3bcb50ddb 100644--- a/.claude-plugin/plugin.json+++ b/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain",- "version": "0.60.74.0",+ "version": "0.60.76.0","description": "Personal knowledge brain for your coding agent — hybrid search, synthesis, graph traversal, and durable cross-session memory over Postgres/PGLite with pgvector, plus a curated brain-first skill set.","author": {"name": "Garry Tan",diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.jsonindex 0ad620afc9..fa2c3d0d4f 100644--- a/.codex-plugin/plugin.json+++ b/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain",- "version": "0.60.74.0",+ "version": "0.60.76.0","description": "Personal knowledge brain for your coding agent — hybrid search, synthesis, graph traversal, and durable cross-session memory over Postgres/PGLite with pgvector, plus a curated brain-first skill set.","author": {"name": "Garry Tan",diff --git a/BOOTSTRAP_FOR_AGENTS.md b/BOOTSTRAP_FOR_AGENTS.mdindex 921598b203..00e5c092d3 100644--- a/BOOTSTRAP_FOR_AGENTS.md+++ b/BOOTSTRAP_FOR_AGENTS.md@@ -1,4 +1,4 @@-<!-- gbrain-runbook-stamp: 0.60.74.0 -->+<!-- gbrain-runbook-stamp: 0.60.76.0 --><!-- This stamp must equal the VERSION file at every release; CI enforces it(scripts/check-bootstrap-tag.sh). `gbrain bootstrap status` compares it tothe installed binary and warns on skew. -->diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 32d7487352..4055a0dd74 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,27 @@ credits are retained; no result has been reassigned to another provider. Originaidentifiers and attribution are available in the pre-removal Git revision`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).+## [0.60.76.0] - 2026-10-06++**The behavior-change notice no longer repeats on every upgrade.**++Since v0.60.68.0 an upgraded brain gets a one-time notice listing the behaviors that release turned on. The notice was keyed to the running gbrain version, so every later release showed the whole list again as "gbrain v<new version> changed N behaviors", including changes from releases the brain had already been told about. Each change now carries the release that introduced it (v0.60.68.0 for the chat fallback chain, autopilot lint repairs, transcript re-ingest and the mention linker; v0.60.74.0 for fix wave 9's six). A brain sees only the changes introduced after the last notice it was shown, or after the brain was created if it was never shown one, once per channel and once per HTTP client.++| After upgrading | Before | Now |+| --- | --- | --- |+| A brain that saw the full notice upgrades to a release with no new behavior changes | the whole notice again, under the new version | nothing |+| A brain that saw the v0.60.68.0 notice upgrades to v0.60.74.0 or later | all changes again, labeled as the new version's | only fix wave 9's six changes, labeled v0.60.74.0, once |+| A brain older than v0.60.68.0 | every change, labeled with the running version | every change, labeled v0.60.68.0 and v0.60.74.0, once |+| A brain created on this or a later release | nothing, until its next upgrade showed every change | nothing |+| `gbrain doctor --only behavior_changes` | every change, labeled with the running version | every change newer than the brain's baseline, labeled by release, whether or not the notice was shown |++## To take advantage of v0.60.76.0++`gbrain upgrade` does this automatically. There is no schema migration; existing notice markers and the HTTP per-client record are read as they are, so nothing already shown is shown again.++1. **Verify:** `gbrain doctor --only behavior_changes --json` lists each change with the release that introduced it, and `details.shown` says whether this brain's CLI and stdio channels have seen the newest notice.+2. **If any step fails,** file an issue at https://github.com/garrytan/gbrain/issues with the output of `gbrain doctor`.+## [0.60.74.0] - 2026-10-05**Fix wave 9: cost caps hold under concurrency and bound what DeepSeek really bills, stopping a job supervisor no longer leaves work running, the nightly quality probe uses your models and tells the truth, email threads and synced fact sections reach your facts, long filenames and images stop blocking writes and sync, and OAuth access tokens can no longer live forever.**diff --git a/VERSION b/VERSIONindex 795c8cf3e7..cc6b70f88a 100644--- a/VERSION+++ b/VERSION@@ -1 +1 @@-0.60.74.0+0.60.76.0diff --git a/docs/architecture/key-files/agent-contract.md b/docs/architecture/key-files/agent-contract.mdindex d6307154dc..155cffd6fa 100644--- a/docs/architecture/key-files/agent-contract.md+++ b/docs/architecture/key-files/agent-contract.md@@ -25,7 +25,7 @@ Spec: `docs/designs/AGENT_OPERATOR_WAVE.md`; wire goldens: `test/fixtures/agent-- `src/mcp/initialize-context.ts` — per-initialize inputs for the generated instructions (`httpInstructionTools`: the tools/list filters with publish gates read on initialize; `instructionReadiness`: config plane + probed tier within 250 ms, HTTP view redacted) and `stdioCapabilityReadiness` (F2). Test: `test/mcp-capabilities-readiness.test.ts`.- `src/mcp/hidden-tool-hint.ts` + `src/core/ops/cli-equivalent.ts` — F6: on the owner's stdio pipe a real tool outside the surface/read-only access gets `unknown_tool` naming itself and its CLI equivalent (`cliEquivalent`: `cliOnly` argv, curated overrides, `cliHints.name`, else `gbrain call`). Where `request_tools` is callable and session widening is on, the fix is `request_tools {surface:'full'}` (`next: run`, argv kept); otherwise the CLI equivalent with actor `user` and a `user_message`; `why` names the lasting route (`GBRAIN_SURFACE=full` in the harness's per-server env, or a `--surface full` re-registration) and that an inherited `GBRAIN_SURFACE` overrides a pinned `--surface`. Read-only access never offers a widen. HTTP stays opaque. `scripts/generate-plugin-tree.ts` appends the same map as a per-skill note to generated starter-gap skills. Test: `test/hidden-tool-hint.test.ts`.- `Operation.cliOnly` + `cliOnlyRefusal` (`src/core/ops/callable.ts`) — F5: owner-only ops (they refuse every MCP caller) are never listed on MCP; a call gets `trusted_local_only` (error `permission_denied`) with the exact CLI command.-- `src/core/behavior-change-notice.ts` — the one-time `behavior_changes` safety notice: a live `chat_fallback_chain` (local view: entries, providers, refusal behavior, removal fix; HTTP view: only that a chain is configured), managed-brain lint repairs (`cycle.lint_fix`), smaller transcript parts re-embedded once (`TRANSCRIPT_REINGEST_MULTIPLIER`), a mention-linker rescan. `BEHAVIOR_NOTICE_SINCE` (default `VERSION`) names the first release carrying it. Eligibility: the brain's baseline under `GBRAIN_HOME/notices/behavior-changes/<brainKey>.baseline` (`gbrain init` stamps a database it creates; otherwise the first look records `0` when `upgrade-state.json` shows an upgrade from an older release or the oldest `sources.created_at` is past `FRESH_BRAIN_GRACE_MS`). Markers: CLI and stdio claim a `wx` file per notice × brain × channel (an unwritable home still delivers, once per process); HTTP keeps up to `HTTP_SHOWN_CAP` client ids in the `notices.behavior_changes.http` config row (no migration; a failed write still delivers). Delivery: `completeEngineStartup` in `src/cli.ts` (stderr; not `serve` or `doctor`), and `sessionSafetyNotices` in `src/mcp/dispatch.ts` on success and failure results. `gbrain doctor --only behavior_changes` reads it without writing. Pinned by `test/behavior-change-notice.test.ts` (both engines) and `test/behavior-change-notice-cli.test.ts`.+- `src/core/behavior-change-notice.ts` — the one-time `behavior_changes` safety notice: a live `chat_fallback_chain` (local view: entries, providers, refusal behavior, removal fix; HTTP view: only that a chain is configured), managed-brain lint repairs (`cycle.lint_fix`), smaller transcript parts re-embedded once (`TRANSCRIPT_REINGEST_MULTIPLIER`), a mention-linker rescan (v0.60.68.0), and fix wave 9's six upgrade-visible changes (v0.60.74.0). `BEHAVIOR_CHANGES` is the one table of disclosed changes, each with the release that introduced it; `BEHAVIOR_NOTICE_SINCE` is the newest row's release (never `VERSION`), so the notice id `behavior_changes@<since>` moves only when a release appends rows. Content: the rows newer than the last notice release this brain × channel (× HTTP client) was shown, or than its baseline when never shown. Baseline: the brain's baseline under `GBRAIN_HOME/notices/behavior-changes/<brainKey>.baseline` (`gbrain init` stamps a database it creates; otherwise the first look records `0` when `upgrade-state.json` shows an upgrade from an older release or the oldest `sources.created_at` is past `FRESH_BRAIN_GRACE_MS`). Markers: CLI and stdio claim a `wx` file per notice × brain × channel (an unwritable home still delivers, once per process); the newest marker names the last release shown; HTTP keeps up to `HTTP_SHOWN_CAP` client ids, each with the release it was shown, in the `notices.behavior_changes.http` config row (a row from an older build counts its clients as shown its id's release) (no migration; a failed write still delivers). Delivery: `completeEngineStartup` in `src/cli.ts` (stderr; not `serve` or `doctor`), and `sessionSafetyNotices` in `src/mcp/dispatch.ts` on success and failure results. `gbrain doctor --only behavior_changes` reads every row newer than the baseline without writing. Pinned by `test/behavior-change-notice.test.ts` (both engines, plus upgrade steps in processes pinned to a `VERSION`) and `test/behavior-change-notice-cli.test.ts`.- `src/core/post-upgrade-notice.ts` — F7 `post_upgrade` safety notice (contract_version + behavior-table URL): `gbrain post-upgrade` writes it once; the first stdio MCP session per upgraded version gets it (persisted under GBRAIN_HOME). `src/cli/op-notices.ts` renders op notices on the local CLI (`--json` objects gain `notices`; human output on stderr).- `src/core/ops/op-fix.ts` — Lane B builders for filled, surface-correct op errors (type-only agent-output import: ops sit in the snapshot-schema closure). `opTransport(ctx)` (cli/stdio/http from `remote`+`transport`), `paramUse(ctx, param, value?)` (`--no-pull` vs `no_pull: true`), `readFix` (diagnostic step, `mcp` + `argv`), `hostFix`/`hostOnlyError` (B6: host-only command, actor agent on CLI / user on stdio / host_admin on http with relay `user_message`), `invalidParam` (B2/B3: param, choices or type+description, one example; never echoes the raw value), `scopeDeniedError` (B5: `insufficient_scope`, frozen `error` via `legacy_error`, client id + current scopes in `why`, the exact `gbrain auth rescope`/`rescope-token` command, consent `credentials`). Test: `test/op-fix.test.ts`, `test/scope-denial-contract.test.ts`.- `src/core/persistence/page-identity.ts` — B4: `pageIdentityError(present, msg)` (a deleted page throws canonical `page_not_found` with the frozen wire/journal `error` `page_identity_changed`; a replaced page keeps `page_identity_changed`), `isMissingPageMessage` (replays recover the distinction from the stored message; no schema change), `yamlLocator` (content-free ` at line L, column C`). Replays (`writeResponse` in `persistence/service.ts`) set `OperationError.receiptFields` (never serialized); `toAgentError` fills the registry fix template (`{slug}`/`{source_id}`/`{request_id}`/`{operation}`, strict per-field patterns, unfillable → dropped) and applies the principal-aware receipt rule (CLI principal → `gbrain write-request`; same-principal MCP → `get_write_request` when callable; otherwise host inspection, actor host_admin). Test: `test/write-receipt-remediation.test.ts`.diff --git a/docs/architecture/key-files/commands-2.md b/docs/architecture/key-files/commands-2.mdindex 87d5b31ebc..c196a246ac 100644--- a/docs/architecture/key-files/commands-2.md+++ b/docs/architecture/key-files/commands-2.md@@ -6,7 +6,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGELDoctor's embedding-dimension warning treats existing chunks as existing data even when every vector is missing. It directs the operator to a verified database backup and a brain-wide migration preview, followed only by explicitly approved total spending authorization; it never recommends forced reinitialization for that case. `test/doctor.test.ts` pins this recovery guidance.- `src/commands/doctor/checks/chat-fallback.ts` — `chat_fallback_chain` (OPS, registered after `embedding_env_override` so `--only` connects the brain, and in `doctorReportRemote`): the effective chain, its plane, shadowed values, providers and refusal behavior from `src/core/ai/chat-fallback-planes.ts`. An active, healthy chain is `ok` with the optional per-plane removal fix (never `next: run`); an unreadable plane value or a malformed / unknown-provider / no-chat entry warns with the removal fix, a missing credential with a `credentials` fix, an unpriced model under a user cap with `noPricingFix`. Remote (`remote !== false`): only that a chain is configured and its problem count, `host_admin` fix. Pinned by `test/doctor-chat-fallback-chain.test.ts`.-- `src/commands/doctor/checks/behavior-changes.ts` — `behavior_changes` (META, after `chat_fallback_chain`): the `behavior_changes` disclosure read again (`src/core/behavior-change-notice.ts`), always `ok`; reads the baseline and markers without recording either, and reports which channels were shown.+- `src/commands/doctor/checks/behavior-changes.ts` — `behavior_changes` (META, after `chat_fallback_chain`): the `behavior_changes` disclosure read again (`src/core/behavior-change-notice.ts`): every change newer than the brain's baseline, labeled by release, whether or not the notice was shown; always `ok`; reads the baseline and markers without recording either, and reports which channels were shown.- `src/commands/doctor/checks/vector-plan.ts` — `vector_plan` (#5824, OPS, wave check with operator resolution). Postgres only: EXPLAINs (no ANALYZE) the statement `searchVector` emits for the active embedding column with a zero vector through `PostgresEngine.explainVectorSearch` (same builder, scoped read transaction and scan settings) and warns when an HNSW-indexed column's plan does not use its HNSW index, naming the observed scans, whether the index exists and is valid (`pg_index.indisvalid`, with the create/reindex command), the 8 s candidate-budget risk and the legacy guard as rollback. Skipped on PGLite, on columns wider than the HNSW cap, and below 10,000 embedded chunks (`pg_class.reltuples` x `pg_stats.null_frac`, a bounded count when never analyzed). A configured legacy guard warns "active after restarting the owning service". Details carry a sampled stale-text fraction and point to `gbrain embed --stale` above 5%. Tested in `test/e2e/vector-plan-real-column-postgres.test.ts` (empty, small, ok, unused valid index, INVALID index, guard via env and config).- `src/commands/doctor/checks/persistence-requests.ts` — two wave checks (OPS, registered in `wave-checks.ts`). `persistence_request_indexes` (#5762) reports each managed sync request index missing, INVALID or still building (with progress) and names `gbrain repair request-indexes --apply`. `persistence_request_growth` reports the request-table row count (a `reltuples` estimate on Postgres), each scope's admission rate over the last 7 days (the newest 10,000 admissions per scope, one bounded index read), lifetime IDs against `persistence.limits.*` and the projected exhaustion date within ten years; it warns under 90 days with the `oneYearCapacity` `gbrain config set` value and the doctor re-check. Tests: `test/persistence-request-indexes.test.ts`, `test/e2e/persistence-request-indexes-postgres.test.ts`.- `src/commands/doctor/checks/{persistence-capacity,parked-effects}.ts` — `persistence_capacity` (OPS) warns when a principal or the brain reaches 80% of permanent request IDs or receipt bytes (via `capacityDiagnostics`) and prints one `gbrain config set <key> <value>` per brain-wide key, using the largest value any scope needs for about one more year; transient caps never warn. `parked_effects` (BRAIN) reads the partial parked-effect index, counts exactly, samples 20, and names each parked page with its `retry-effects ... --dry-run` command. Both report `exact`/`inspected`/`truncated` details; an unreadable state is warn, never clean. Tests: `test/persistence-capacity.test.ts`, `test/persistence-effect-parking.test.ts`.diff --git a/openclaw.plugin.json b/openclaw.plugin.jsonindex c9ce3efddf..589cd195b1 100644--- a/openclaw.plugin.json+++ b/openclaw.plugin.json@@ -1,7 +1,7 @@{"id": "gbrain-context-engine","name": "gbrain",- "version": "0.60.74.0",+ "version": "0.60.76.0","description": "Personal knowledge brain with Postgres + pgvector hybrid search","family": "bundle-plugin","kind": "context-engine",diff --git a/package.json b/package.jsonindex 547c71d906..efdb2d9d68 100644--- a/package.json+++ b/package.json@@ -221,7 +221,7 @@"bun": ">=1.4.0"},"license": "MIT",- "version": "0.60.74.0",+ "version": "0.60.76.0","overrides": {"@ai-sdk/provider-utils": "4.0.56","@hono/node-server": "^2.0.5",diff --git a/plugin-variants/gbrain-coding/.claude-plugin/plugin.json b/plugin-variants/gbrain-coding/.claude-plugin/plugin.jsonindex a31e5ec86d..c385e327d5 100644--- a/plugin-variants/gbrain-coding/.claude-plugin/plugin.json+++ b/plugin-variants/gbrain-coding/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain-coding",- "version": "0.60.74.0",+ "version": "0.60.76.0","description": "Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant. (persona variant of the gbrain plugin — 21 skills)","author": {"name": "Garry Tan",diff --git a/plugin-variants/gbrain-coding/.codex-plugin/plugin.json b/plugin-variants/gbrain-coding/.codex-plugin/plugin.jsonindex 491ddaf7c4..6beb2c4bab 100644--- a/plugin-variants/gbrain-coding/.codex-plugin/plugin.json+++ b/plugin-variants/gbrain-coding/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain-coding",- "version": "0.60.74.0",+ "version": "0.60.76.0","description": "Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant. (persona variant of the gbrain plugin — 21 skills)","author": {"name": "Garry Tan",diff --git a/plugin-variants/gbrain-coding/README.md b/plugin-variants/gbrain-coding/README.mdindex 6affc77c47..aeec56eaad 100644--- a/plugin-variants/gbrain-coding/README.md+++ b/plugin-variants/gbrain-coding/README.md@@ -1,4 +1,4 @@-<!-- gbrain-plugin-tree-stamp: 0.60.74.0 -->+<!-- gbrain-plugin-tree-stamp: 0.60.76.0 --># gbrain-coding (generated persona variant — do not hand-edit)Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant.diff --git a/plugin-variants/gbrain-daily/.claude-plugin/plugin.json b/plugin-variants/gbrain-daily/.claude-plugin/plugin.jsonindex 33d3feefb2..23f7fb013d 100644--- a/plugin-variants/gbrain-daily/.claude-plugin/plugin.json+++ b/plugin-variants/gbrain-daily/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain-daily",- "version": "0.60.74.0",+ "version": "0.60.76.0","description": "Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant. (persona variant of the gbrain plugin — 20 skills)","author": {"name": "Garry Tan",diff --git a/plugin-variants/gbrain-daily/.codex-plugin/plugin.json b/plugin-variants/gbrain-daily/.codex-plugin/plugin.jsonindex 1ac6773b45..07a799bb92 100644--- a/plugin-variants/gbrain-daily/.codex-plugin/plugin.json+++ b/plugin-variants/gbrain-daily/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain-daily",- "version": "0.60.74.0",+ "version": "0.60.76.0","description": "Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant. (persona variant of the gbrain plugin — 20 skills)","author": {"name": "Garry Tan",diff --git a/plugin-variants/gbrain-daily/README.md b/plugin-variants/gbrain-daily/README.mdindex 98a6c8d3fa..03aa68c23a 100644--- a/plugin-variants/gbrain-daily/README.md+++ b/plugin-variants/gbrain-daily/README.md@@ -1,4 +1,4 @@-<!-- gbrain-plugin-tree-stamp: 0.60.74.0 -->+<!-- gbrain-plugin-tree-stamp: 0.60.76.0 --># gbrain-daily (generated persona variant — do not hand-edit)Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant.diff --git a/plugin/README.md b/plugin/README.mdindex beb9218638..1d12ee9373 100644--- a/plugin/README.md+++ b/plugin/README.md@@ -1,4 +1,4 @@-<!-- gbrain-plugin-tree-stamp: 0.60.74.0 -->+<!-- gbrain-plugin-tree-stamp: 0.60.76.0 --># gbrain plugin skill tree (generated — do not hand-edit)This tree is the curated skill set for the gbrain Codex and Claude Codediff --git a/src/commands/doctor/checks/behavior-changes.ts b/src/commands/doctor/checks/behavior-changes.tsindex cc357d8db6..af13c30e0b 100644--- a/src/commands/doctor/checks/behavior-changes.ts+++ b/src/commands/doctor/checks/behavior-changes.ts@@ -1,6 +1,8 @@/*** `behavior_changes` doctor check: the one-time `behavior_changes` safety- * notice, readable again (src/core/behavior-change-notice.ts). Read-only: it+ * notice, readable again (src/core/behavior-change-notice.ts): every change+ * newer than the brain's baseline, whatever the notice already showed,+ * labeled with the release that introduced it. Read-only: it* neither records the brain's baseline nor writes a shown marker, so the* notice itself is still delivered once per channel. Always `ok`: the changes* are on by design and the fix is the optional chain-removal guidance.@@ -12,7 +14,7 @@ import {behaviorBrainKey,behaviorChangesNotice,behaviorNoticeShown,- brainPredatesRelease,+ brainBaseline,chainDisclosure,currentBrainId,} from '../../../core/behavior-change-notice.ts';@@ -26,13 +28,14 @@ export async function checkBehaviorChanges(engine: BrainEngine | null, opts: { clet cfg = opts.cfg;if (cfg === undefined) { try { cfg = loadConfig(); } catch { cfg = null; } }const brainKey = opts.brainKey ?? behaviorBrainKey(cfg, await currentBrainId());- if (!(await brainPredatesRelease(engine, brainKey, { persist: false }))) {- return { name: 'behavior_changes', status: 'ok', message: `Nothing to disclose: this brain is a fresh install at v${BEHAVIOR_NOTICE_SINCE} or later, so the one-time behavior-change notice does not apply.` };+ const baseline = await brainBaseline(engine, brainKey, { persist: false });+ const notice = behaviorChangesNotice(await chainDisclosure(engine, cfg), { after: baseline });+ if (!notice) {+ return { name: 'behavior_changes', status: 'ok', message: `Nothing to disclose: this brain is a fresh install at v${baseline}, after every disclosed behavior change, so the one-time behavior-change notice does not apply.` };}- const notice = behaviorChangesNotice(await chainDisclosure(engine, cfg));return {name: 'behavior_changes', status: 'ok', message: notice.why, ...(notice.fix ? { fix: notice.fix } : {}),- details: { since: BEHAVIOR_NOTICE_SINCE, shown: { cli: behaviorNoticeShown(brainKey, 'cli'), stdio: behaviorNoticeShown(brainKey, 'stdio') } },+ details: { since: BEHAVIOR_NOTICE_SINCE, baseline, shown: { cli: behaviorNoticeShown(brainKey, 'cli'), stdio: behaviorNoticeShown(brainKey, 'stdio') } },};} catch (e) {return checkError('behavior_changes', 'read the behavior-change disclosure', e);diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 7801730d1a..82675bb30c 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -4,45 +4,49 @@* every change stays on, nothing waits for an answer, and delivery is never* recorded as the user's consent.*- * (a) a non-empty `chat_fallback_chain` is walked on every non-pinned chat- * call, on errors and (unless `chat_fallback_on_refusal=false`) on- * refusals: the entries, the providers that receive traffic and the- * per-plane removal guidance. Only when a chain is set; a remote- * (HTTP) caller sees only that a chain is configured.- * (b) managed-brain autopilot lint writes its repairs- * (`gbrain config set cycle.lint_fix false` opts out).- * (c) transcript re-ingest makes smaller parts and re-embeds once- * (`TRANSCRIPT_REINGEST_MULTIPLIER`).- * (d) the mention linker rebuilds its resume state once.- * (e) fix wave 9: shell jobs reap leftover processes, the declaring-pack- * extract_atoms auto-drain, the 90-day OAuth access-token cap, the- * writer-status `local_process_ingress` rename, `jobs work` exit codes- * and the longer retention of unextracted corpus files.+ * BEHAVIOR_CHANGES is the one table of disclosed changes, each with the+ * release that introduced it:+ * 0.60.68.0 a non-empty `chat_fallback_chain` is walked on every non-pinned+ * chat call (only when a chain is set; a remote (HTTP) caller+ * sees only that a chain is configured), managed-brain autopilot+ * lint writes its repairs, transcript re-ingest makes smaller+ * parts, the mention linker rebuilds its resume state once.+ * 0.60.74.0 fix wave 9: shell jobs reap leftover processes, the+ * declaring-pack extract_atoms auto-drain, the 90-day OAuth+ * access-token cap, the writer-status `local_process_ingress`+ * rename, `jobs work` exit codes, the longer retention of+ * unextracted corpus files.+ * A release that changes behavior appends its rows; a shipped row's release+ * never changes.*- * Identity: notice id (`behavior_changes@<BEHAVIOR_NOTICE_SINCE>`) × brain ×- * channel, plus the authenticated client on HTTP. Eligibility: a brain that- * predates BEHAVIOR_NOTICE_SINCE. Its baseline (the first gbrain version- * that saw it, `0` when it already existed) is recorded once under- * GBRAIN_HOME: `gbrain init` stamps a database it creates with this version;- * otherwise the first look decides from the recorded upgrade history- * (`upgrade-state.json` `from` below the release) or the brain's own+ * Identity: notice id (`behavior_changes@<BEHAVIOR_NOTICE_SINCE>`, the newest+ * row's release, never the running VERSION) × brain × channel, plus the+ * authenticated client on HTTP. A release with no new rows re-notifies+ * nobody. Content: only the rows introduced after the last notice release+ * this brain × channel (× client) was shown, or after the brain's baseline+ * when it was never shown one. The baseline (the first gbrain version that+ * saw it, `0` when it already existed) is recorded once under GBRAIN_HOME:+ * `gbrain init` stamps a database it creates with this version; otherwise+ * the first look decides from the recorded upgrade history+ * (`upgrade-state.json` `from` below the newest row) or the brain's own* creation time (its oldest `sources.created_at` more than* FRESH_BRAIN_GRACE_MS ago). A fresh install sees no notice.** Markers:* - CLI and stdio: one file per notice × brain × channel under* GBRAIN_HOME/notices/behavior-changes/, created exclusively (`wx`), so- * concurrent processes deliver it once. A home that cannot be written- * still gets the notice (once per process).+ * concurrent processes deliver it once; the newest marker names the last+ * release shown. A home that cannot be written still gets the notice+ * (once per process).* - HTTP: one bounded `config` row in the brain DB- * (`notices.behavior_changes.http`: the notice id and up to- * HTTP_SHOWN_CAP client ids, oldest dropped first). No migration: the+ * (`notices.behavior_changes.http`: up to HTTP_SHOWN_CAP client ids, each+ * with the release it was shown, oldest dropped first). No migration: the* row reuses the key/value table every brain has.- * `gbrain doctor --only behavior_changes` reads the disclosure again and- * writes nothing.+ * `gbrain doctor --only behavior_changes` reads every row newer than the+ * brain's baseline again and writes nothing.*/import { createHash } from 'node:crypto';-import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';+import { mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';import { dirname, join } from 'node:path';import type { BrainEngine } from './engine.ts';import type { Action, Notice } from './agent-output.ts';@@ -57,12 +61,9 @@ import {} from './ai/chat-fallback-planes.ts';import { mergedProviderEnv } from './ai/provider-env.ts';-/** The first release that carries this notice. Set once, here, at ship time. */-export const BEHAVIOR_NOTICE_SINCE: string = VERSION;-/** The measured re-ingest page multiplier for (c), as prose (scripts/measure-transcript-split-cost.ts: 4 → 27 pages on a 1 MB session). */+/** The measured re-ingest page multiplier, as prose (scripts/measure-transcript-split-cost.ts: 4 → 27 pages on a 1 MB session). */export const TRANSCRIPT_REINGEST_MULTIPLIER = 'about 6.75x';export const BEHAVIOR_NOTICE_CODE = 'behavior_changes';-export const BEHAVIOR_NOTICE_ID = `${BEHAVIOR_NOTICE_CODE}@${BEHAVIOR_NOTICE_SINCE}`;/** A brain created this recently, with no recorded baseline, counts as a fresh install. */export const FRESH_BRAIN_GRACE_MS = 60 * 60 * 1000;export const HTTP_SHOWN_KEY = 'notices.behavior_changes.http';@@ -70,6 +71,7 @@ export const HTTP_SHOWN_CAP = 500;const CLIENT_ID_MAX = 128;/** The baseline recorded for a brain that existed before baselines were kept. */const PREDATES = '0';+const RELEASE = /^\d+(\.\d+)*$/;export type BehaviorChannel = 'cli' | 'stdio' | 'http';@@ -119,7 +121,7 @@ const baselinePath = (brainKey: string) => join(noticeDir(), `${brainKey}.baselifunction readBaseline(brainKey: string): string | null {try {const v = readFileSync(baselinePath(brainKey), 'utf8').trim();- return /^\d+(\.\d+)*$/.test(v) ? v : null;+ return RELEASE.test(v) ? v : null;} catch {return null;}@@ -138,7 +140,7 @@ export function stampFreshBrainBaseline(brainKey: string): void {writeBaseline(brainKey, VERSION, false);}-/** `gbrain upgrade` recorded an upgrade from a release older than this notice. */+/** `gbrain upgrade` recorded an upgrade from a release older than the newest disclosed change. */function upgradedAcrossRelease(): boolean {try {const state = JSON.parse(readFileSync(gbrainPath('upgrade-state.json'), 'utf8')) as { last_upgrade?: { from?: unknown } };@@ -162,28 +164,28 @@ async function brainCreatedBefore(engine: BrainEngine, cutoffMs: number): Promis}/**- * Does this brain predate BEHAVIOR_NOTICE_SINCE? Reads the recorded baseline;- * without one, derives it and (when `persist`) records it, so a fresh brain- * stays fresh after the grace window. `persist: false` (doctor) writes nothing.+ * The brain's baseline release (`0` when it predates baselines). Reads the+ * recorded baseline; without one, derives it and (when `persist`) records it,+ * so a fresh brain stays fresh after the grace window. `persist: false`+ * (doctor) writes nothing.*/-export async function brainPredatesRelease(+export async function brainBaseline(engine: BrainEngine | null,brainKey: string,opts: { persist: boolean; now?: number },-): Promise<boolean> {- let since = readBaseline(brainKey);- if (!since) {- const now = opts.now ?? Date.now();- const predates = upgradedAcrossRelease() || (engine !== null && await brainCreatedBefore(engine, now - FRESH_BRAIN_GRACE_MS));- since = predates ? PREDATES : VERSION;- if (opts.persist) {- writeBaseline(brainKey, since, true);- since = readBaseline(brainKey) ?? since;- }- }- return compareReleases(since, BEHAVIOR_NOTICE_SINCE) < 0;+): Promise<string> {+ const recorded = readBaseline(brainKey);+ if (recorded) return recorded;+ const now = opts.now ?? Date.now();+ const predates = upgradedAcrossRelease() || (engine !== null && await brainCreatedBefore(engine, now - FRESH_BRAIN_GRACE_MS));+ const since = predates ? PREDATES : VERSION;+ if (!opts.persist) return since;+ writeBaseline(brainKey, since, true);+ return readBaseline(brainKey) ?? since;}+const laterRelease = (a: string, b: string) => (compareReleases(a, b) >= 0 ? a : b);+// ── content ─────────────────────────────────────────────────────────────────export interface ChainDisclosure {@@ -211,31 +213,57 @@ export async function chainDisclosure(engine: BrainEngine | null, cfg: GBrainConconst DOCTOR_ARGV = ['gbrain', 'doctor', '--only', BEHAVIOR_NOTICE_CODE, '--json'];-/** The disclosure. `remote` (HTTP) names only that a chain is configured; entries and providers stay on the host. */-export function behaviorChangesNotice(chain: ChainDisclosure | null, opts: { remote?: boolean } = {}): Notice {- const items: string[] = [];- if (chain && opts.remote) {- items.push('A chat fallback chain is configured on this brain host: when a chat call\'s own model fails it is retried on other models. Its entries and providers are visible to the brain host operator in gbrain doctor --only chat_fallback_chain.');- } else if (chain) {- items.push(`chat_fallback_chain is live (set in ${CHAT_FALLBACK_PLANE_LABEL[chain.plane]}): when a chat call's own model fails${chain.onRefusal ? ' or refuses' : ''}, gbrain retries it on ${chain.entries.join(', ')}, so ${chain.providers.length ? chain.providers.join(', ') : 'those providers'} receive that traffic. ` ++type ChangeText = string | ((chain: ChainDisclosure | null, remote: boolean) => string | null);++/** Every disclosed behavior change, with the release that introduced it. Append new rows; never edit a shipped `since`. */+export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }> = [+ { since: '0.60.68.0', text: (chain, remote) => {+ if (!chain) return null;+ if (remote) return 'A chat fallback chain is configured on this brain host: when a chat call\'s own model fails it is retried on other models. Its entries and providers are visible to the brain host operator in gbrain doctor --only chat_fallback_chain.';+ return `chat_fallback_chain is live (set in ${CHAT_FALLBACK_PLANE_LABEL[chain.plane]}): when a chat call's own model fails${chain.onRefusal ? ' or refuses' : ''}, gbrain retries it on ${chain.entries.join(', ')}, so ${chain.providers.length ? chain.providers.join(', ') : 'those providers'} receive that traffic. ` +(chain.onRefusal? 'It falls back on refusals as well as errors, so content one provider refused is sent to the next; `gbrain config set chat_fallback_on_refusal false` keeps outage fallback only.': 'chat_fallback_on_refusal is false, so it falls back on errors only.') +- ' Removing the chain is optional; ask the user (gbrain doctor --only chat_fallback_chain has the per-plane steps).');+ ' Removing the chain is optional; ask the user (gbrain doctor --only chat_fallback_chain has the per-plane steps).';+ } },+ { since: '0.60.68.0', text: 'On a managed brain, autopilot\'s lint phase now writes its repairs instead of only reporting them; `gbrain config set cycle.lint_fix false` turns that off.' },+ { since: '0.60.68.0', text: `Transcript re-ingest now splits transcripts into smaller parts (45,000-byte target, previously 300,000 bytes): ${TRANSCRIPT_REINGEST_MULTIPLIER} as many part pages and about 9% more embedding tokens (measured on a 1 MB session), and each re-ingested transcript re-embeds once.` },+ { since: '0.60.68.0', text: 'The mention linker rebuilds its gazetteer resume state once, so the first mention-extraction run after upgrading rescans pages.' },+ { since: '0.60.74.0', text: 'A shell job\'s leftover processes (`cmd &` with no `wait`) are now terminated when the job ends; start long-lived processes under a service manager or detach them with `setsid`.' },+ { since: '0.60.74.0', text: 'On Postgres autopilot, a brain whose schema pack declares extract_atoms now gets the daily atom auto-drain, spending within autopilot.auto_drain.max_usd_per_day (default $2); `gbrain config set autopilot.auto_drain.enabled false` opts out.' },+ { since: '0.60.74.0', text: 'OAuth access tokens now last at most 90 days: stored client lifetimes were clamped and already-issued access tokens shortened to 90 days after issue, so a client with no refresh token reconnects; restart any running `gbrain serve --http`.' },+ { since: '0.60.74.0', text: '`gbrain sources writer status --json` renamed `ingress` to `local_process_ingress`; it describes only the process that answered.' },+ { since: '0.60.74.0', text: '`gbrain jobs work` exits 0 after a SIGTERM drain (was 143) and 17 when running claims had to be handed back.' },+ { since: '0.60.74.0', text: 'Captured session files nothing has extracted are kept up to 3x dream.synthesize.corpus_retention_days (90 days by default, was 30), so the corpus directory can use more disk; `gbrain sweep --once --budget-ms 600000` clears that backlog.' },+];++/** The newest disclosed change's release: the notice id moves only when a release adds rows. */+export const BEHAVIOR_NOTICE_SINCE: string = BEHAVIOR_CHANGES.reduce((v, c) => laterRelease(v, c.since), PREDATES);+export const BEHAVIOR_NOTICE_ID = `${BEHAVIOR_NOTICE_CODE}@${BEHAVIOR_NOTICE_SINCE}`;++/**+ * The disclosure of the changes introduced after release `after` (default:+ * all of them), grouped by release; null when none apply. `remote` (HTTP)+ * names only that a chain is configured; entries and providers stay on the host.+ */+export function behaviorChangesNotice(chain: ChainDisclosure | null, opts: { remote?: boolean; after?: string } = {}): Notice | null {+ const byRelease = new Map<string, string[]>();+ let namesChain = false;+ for (const change of BEHAVIOR_CHANGES) {+ if (compareReleases(change.since, opts.after ?? PREDATES) <= 0) continue;+ const text = typeof change.text === 'string' ? change.text : change.text(chain, !!opts.remote);+ if (!text) continue;+ namesChain ||= typeof change.text !== 'string';+ byRelease.set(change.since, [...(byRelease.get(change.since) ?? []), text]);}- items.push('On a managed brain, autopilot\'s lint phase now writes its repairs instead of only reporting them; `gbrain config set cycle.lint_fix false` turns that off.');- items.push(`Transcript re-ingest now splits transcripts into smaller parts (45,000-byte target, previously 300,000 bytes): ${TRANSCRIPT_REINGEST_MULTIPLIER} as many part pages and about 9% more embedding tokens (measured on a 1 MB session), and each re-ingested transcript re-embeds once.`);- items.push('The mention linker rebuilds its gazetteer resume state once, so the first mention-extraction run after upgrading rescans pages.');- items.push('A shell job\'s leftover processes (`cmd &` with no `wait`) are now terminated when the job ends; start long-lived processes under a service manager or detach them with `setsid`.');- items.push('On Postgres autopilot, a brain whose schema pack declares extract_atoms now gets the daily atom auto-drain, spending within autopilot.auto_drain.max_usd_per_day (default $2); `gbrain config set autopilot.auto_drain.enabled false` opts out.');- items.push('OAuth access tokens now last at most 90 days: stored client lifetimes were clamped and already-issued access tokens shortened to 90 days after issue, so a client with no refresh token reconnects; restart any running `gbrain serve --http`.');- items.push('`gbrain sources writer status --json` renamed `ingress` to `local_process_ingress`; it describes only the process that answered.');- items.push('`gbrain jobs work` exits 0 after a SIGTERM drain (was 143) and 17 when running claims had to be handed back.');- items.push('Captured session files nothing has extracted are kept up to 3x dream.synthesize.corpus_retention_days (90 days by default, was 30), so the corpus directory can use more disk; `gbrain sweep --once --budget-ms 600000` clears that backlog.');- const why = `gbrain v${BEHAVIOR_NOTICE_SINCE} changed ${items.length} behaviors on this brain. All stay on; this is a one-time disclosure, not a request for consent. ` +- items.map((t, i) => `(${i + 1}) ${t}`).join(' ') ++ if (byRelease.size === 0) return null;+ const releases = [...byRelease.keys()].map(v => `v${v}`);+ const count = [...byRelease.values()].reduce((n, texts) => n + texts.length, 0);+ let n = 0;+ const why = `gbrain ${releases.length > 1 ? `${releases.slice(0, -1).join(', ')} and ${releases.at(-1)}` : releases[0]} changed ${count} behavior${count === 1 ? '' : 's'} on this brain. All stay on; this is a one-time disclosure, not a request for consent. ` ++ [...byRelease].map(([since, texts]) => (byRelease.size > 1 ? `v${since}: ` : '') + texts.map(t => `(${++n}) ${t}`).join(' ')).join(' ') +' gbrain doctor --only behavior_changes shows this again.';- const fix: Action = chain && !opts.remote+ const fix: Action = chain && namesChain && !opts.remote? chatFallbackRemovalFix(chain.plane, chain.filePath): { argv: DOCTOR_ARGV, consent: [], actor: opts.remote ? 'host_admin' : 'agent', requires_exclusive: false,why: 'Shows this disclosure again; read-only.', docs: 'docs/guides/chat-fallback.md' };@@ -260,9 +288,12 @@ export function __resetBehaviorNoticeForTests(): void {handled.clear();}-/** Claim the per-channel marker. `unwritable` still delivers (conservative). */+const markerPrefix = safe(`${BEHAVIOR_NOTICE_CODE}@`);+const markerSuffix = (brainKey: string, channel: 'cli' | 'stdio') => `.${brainKey}.${channel}.shown`;++/** Claim the per-channel marker for the current notice id. `unwritable` still delivers (conservative). */function claimMarker(brainKey: string, channel: 'cli' | 'stdio'): 'claimed' | 'shown' | 'unwritable' {- const path = join(noticeDir(), `${safe(BEHAVIOR_NOTICE_ID)}.${brainKey}.${channel}.shown`);+ const path = join(noticeDir(), `${safe(BEHAVIOR_NOTICE_ID)}${markerSuffix(brainKey, channel)}`);try {mkdirSync(dirname(path), { recursive: true });writeFileSync(path, `${new Date().toISOString()}\n`, { mode: 0o600, flag: 'wx' });@@ -272,19 +303,29 @@ function claimMarker(brainKey: string, channel: 'cli' | 'stdio'): 'claimed' | 's}}-/** Has this channel's marker been written for this brain? (doctor; read-only) */-export function behaviorNoticeShown(brainKey: string, channel: 'cli' | 'stdio'): boolean {+/** The newest notice release this brain × channel was shown (any build's marker), `0` when none. */+function localShownThrough(brainKey: string, channel: 'cli' | 'stdio'): string {+ const suffix = markerSuffix(brainKey, channel);+ let through = PREDATES;try {- readFileSync(join(noticeDir(), `${safe(BEHAVIOR_NOTICE_ID)}.${brainKey}.${channel}.shown`));- return true;- } catch {- return false;- }+ for (const name of readdirSync(noticeDir())) {+ if (!name.startsWith(markerPrefix) || !name.endsWith(suffix)) continue;+ const release = name.slice(markerPrefix.length, -suffix.length);+ if (RELEASE.test(release)) through = laterRelease(through, release);+ }+ } catch { /* no markers yet, or an unreadable home */ }+ return through;+}++/** Has this channel been shown the newest notice for this brain? (doctor; read-only) */+export function behaviorNoticeShown(brainKey: string, channel: 'cli' | 'stdio'): boolean {+ return compareReleases(localShownThrough(brainKey, channel), BEHAVIOR_NOTICE_SINCE) >= 0;}/**- * CLI and stdio: the notice once per notice × brain × channel, or null.- * Never throws; a fault returns null and the next call looks again.+ * CLI and stdio: the changes this brain × channel has not been shown, once+ * per notice, or null. Never throws; a fault returns null and the next call+ * looks again.*/export async function takeLocalBehaviorNotice(engine: BrainEngine,@@ -296,37 +337,45 @@ export async function takeLocalBehaviorNotice(const brainKey = opts.brainKey ?? behaviorBrainKey(opts.cfg, await currentBrainId());key = `${BEHAVIOR_NOTICE_ID}|${brainKey}|${channel}`;if (!markHandled(key)) return null;- if (!(await brainPredatesRelease(engine, brainKey, { persist: true, now: opts.now }))) return null;+ const after = laterRelease(await brainBaseline(engine, brainKey, { persist: true, now: opts.now }), localShownThrough(brainKey, channel));+ if (compareReleases(BEHAVIOR_NOTICE_SINCE, after) <= 0) return null;if (claimMarker(brainKey, channel) === 'shown') return null;- return behaviorChangesNotice(await chainDisclosure(engine, opts.cfg));+ return behaviorChangesNotice(await chainDisclosure(engine, opts.cfg), { after });} catch {if (key) handled.delete(key);return null;}}-interface HttpShown { id: string; clients: Record<string, string> }+type HttpShown = Record<string, { since: string; at: string }>;+/** Clients and the notice release each was shown. A row from an older build (`clients` mapping to a time) was shown its row id's release. */function readHttpShown(raw: string | null): HttpShown {+ const shown: HttpShown = {};try {- const v = raw ? JSON.parse(raw) as Partial<HttpShown> : null;- if (v && v.id === BEHAVIOR_NOTICE_ID && v.clients && typeof v.clients === 'object') return { id: v.id, clients: v.clients };+ const v = raw ? JSON.parse(raw) as { id?: unknown; clients?: Record<string, unknown> } : null;+ const rowRelease = typeof v?.id === 'string' && v.id.startsWith(`${BEHAVIOR_NOTICE_CODE}@`) ? v.id.slice(BEHAVIOR_NOTICE_CODE.length + 1) : '';+ for (const [client, entry] of Object.entries(v?.clients && typeof v.clients === 'object' ? v.clients : {})) {+ const e = entry as { since?: unknown; at?: unknown } | string;+ if (typeof e === 'string' && RELEASE.test(rowRelease)) shown[client] = { since: rowRelease, at: e };+ else if (typeof e === 'object' && e && typeof e.since === 'string' && RELEASE.test(e.since) && typeof e.at === 'string') shown[client] = { since: e.since, at: e.at };+ }} catch { /* unreadable: start over */ }- return { id: BEHAVIOR_NOTICE_ID, clients: {} };+ return shown;}-/** Add a client, keeping the newest HTTP_SHOWN_CAP. */+/** Record a client as shown the current notice, keeping the newest HTTP_SHOWN_CAP. */export function recordHttpShown(raw: string | null, clientId: string, at: string): string {const shown = readHttpShown(raw);- shown.clients[clientId] = at;- const kept = Object.entries(shown.clients).sort((a, b) => (a[1] < b[1] ? 1 : a[1] > b[1] ? -1 : 0)).slice(0, HTTP_SHOWN_CAP);+ shown[clientId] = { since: BEHAVIOR_NOTICE_SINCE, at };+ const kept = Object.entries(shown).sort((a, b) => (a[1].at < b[1].at ? 1 : a[1].at > b[1].at ? -1 : 0)).slice(0, HTTP_SHOWN_CAP);return JSON.stringify({ id: BEHAVIOR_NOTICE_ID, clients: Object.fromEntries(kept) });}/**- * HTTP: the notice once per authenticated client (remote view: no entries or- * providers). The per-client record lives in the brain's `config` table; a- * failed write still delivers. Never throws.+ * HTTP: the changes each authenticated client has not been shown, once per+ * notice (remote view: no entries or providers). The per-client record lives+ * in the brain's `config` table; a failed write still delivers. Never throws.*/export async function takeHttpBehaviorNotice(engine: BrainEngine,@@ -340,11 +389,12 @@ export async function takeHttpBehaviorNotice(const brainKey = opts.brainKey ?? behaviorBrainKey(opts.cfg, await currentBrainId());key = `${BEHAVIOR_NOTICE_ID}|${brainKey}|http|${client}`;if (!markHandled(key)) return null;- if (!(await brainPredatesRelease(engine, brainKey, { persist: true, now: opts.now }))) return null;+ const baseline = await brainBaseline(engine, brainKey, { persist: true, now: opts.now });const raw = await engine.getConfig(HTTP_SHOWN_KEY).catch(() => null);- if (readHttpShown(raw).clients[client]) return null;+ const after = laterRelease(baseline, readHttpShown(raw)[client]?.since ?? PREDATES);+ if (compareReleases(BEHAVIOR_NOTICE_SINCE, after) <= 0) return null;try { await engine.setConfig(HTTP_SHOWN_KEY, recordHttpShown(raw, client, new Date(opts.now ?? Date.now()).toISOString())); } catch { /* deliver anyway */ }- return behaviorChangesNotice(await chainDisclosure(engine, opts.cfg), { remote: true });+ return behaviorChangesNotice(await chainDisclosure(engine, opts.cfg), { remote: true, after });} catch {if (key) handled.delete(key);return null;diff --git a/templates/bootstrap/template-repo/README.md b/templates/bootstrap/template-repo/README.mdindex 0c54c38d6c..2788a750ae 100644--- a/templates/bootstrap/template-repo/README.md+++ b/templates/bootstrap/template-repo/README.md@@ -1,6 +1,6 @@# gbrain agent workspace — template-<!-- gbrain-template-stamp: 0.60.74.0 -->+<!-- gbrain-template-stamp: 0.60.76.0 -->This repository is the **"Use this template"** distribution artifact for a[gbrain](https://github.com/garrytan/gbrain) personal-agent workspace — the samediff --git a/test/behavior-change-notice.test.ts b/test/behavior-change-notice.test.tsindex 5adf9bc1ce..8b315ad67d 100644--- a/test/behavior-change-notice.test.ts+++ b/test/behavior-change-notice.test.ts@@ -22,16 +22,20 @@ import { tmpdir } from 'node:os';import type { BrainEngine } from '../src/core/engine.ts';import { PGLiteEngine } from '../src/core/pglite-engine.ts';import {+ BEHAVIOR_CHANGES,BEHAVIOR_NOTICE_ID,BEHAVIOR_NOTICE_SINCE,HTTP_SHOWN_CAP,HTTP_SHOWN_KEY,__resetBehaviorNoticeForTests,behaviorBrainKey,+ behaviorChangesNotice,+ compareReleases,recordHttpShown,takeHttpBehaviorNotice,takeLocalBehaviorNotice,} from '../src/core/behavior-change-notice.ts';+import { VERSION } from '../src/version.ts';import { checkBehaviorChanges } from '../src/commands/doctor/checks/behavior-changes.ts';import { dispatchToolCall } from '../src/mcp/dispatch.ts';import { NoticeLedger, __resetProcessNoticeLedgerForTests } from '../src/core/notice-ledger.ts';@@ -87,7 +91,7 @@ for (const backend of testBackends()) {const home = freshHome();await withEnv({ GBRAIN_HOME: home, ...NO_CHAIN }, async () => {expect(await takeLocalBehaviorNotice(engine, 'cli', { cfg: null, brainKey: 'fresh' })).toBeNull();- expect(readFileSync(join(noticeDir(home), 'fresh.baseline'), 'utf8').trim()).toBe(BEHAVIOR_NOTICE_SINCE);+ expect(readFileSync(join(noticeDir(home), 'fresh.baseline'), 'utf8').trim()).toBe(VERSION);await setCreated(engine, 2 * DAY);__resetBehaviorNoticeForTests();expect(await takeLocalBehaviorNotice(engine, 'stdio', { cfg: null, brainKey: 'fresh' })).toBeNull();@@ -223,7 +227,9 @@ for (const backend of testBackends()) {expect(c.details).toMatchObject({ shown: { cli: false, stdio: false } });expect(existsSync(noticeDir(home))).toBe(false);expect(await takeLocalBehaviorNotice(engine, 'cli', { cfg: null, brainKey: 'doctor' })).not.toBeNull();- expect((await checkBehaviorChanges(engine, { cfg: null, brainKey: 'doctor' })).details).toMatchObject({ shown: { cli: true, stdio: false } });+ const again = await checkBehaviorChanges(engine, { cfg: null, brainKey: 'doctor' });+ expect(again.details).toMatchObject({ shown: { cli: true, stdio: false } });+ expect(again.message).toContain('gbrain v0.60.68.0 and v0.60.74.0 changed 9 behaviors');});});@@ -264,7 +270,7 @@ for (const backend of testBackends()) {}describe('HTTP per-client store', () => {- test('keeps the newest HTTP_SHOWN_CAP clients and resets for a new notice id', () => {+ test('keeps the newest HTTP_SHOWN_CAP clients', () => {let raw: string | null = JSON.stringify({ id: '[email protected]', clients: { stale: '2020-01-01T00:00:00.000Z' } });for (let i = 0; i < HTTP_SHOWN_CAP + 25; i++) raw = recordHttpShown(raw, `client-${i}`, new Date(Date.UTC(2026, 0, 1, 0, 0, i)).toISOString());const stored = JSON.parse(raw!) as { id: string; clients: Record<string, string> };@@ -276,6 +282,29 @@ describe('HTTP per-client store', () => {});});+describe('per-release content', () => {+ test('a client from an older build\'s row keeps the release it was shown', () => {+ const raw = recordHttpShown(JSON.stringify({ id: '[email protected]', clients: { old: '2026-10-05T00:00:00.000Z' } }), 'new', '2026-10-06T00:00:00.000Z');+ const stored = JSON.parse(raw) as { id: string; clients: Record<string, { since: string; at: string }> };+ expect(stored.id).toBe(BEHAVIOR_NOTICE_ID);+ expect(stored.clients.old).toEqual({ since: '0.60.68.0', at: '2026-10-05T00:00:00.000Z' });+ expect(stored.clients.new).toEqual({ since: BEHAVIOR_NOTICE_SINCE, at: '2026-10-06T00:00:00.000Z' });+ });++ test('the notice id is the newest change\'s release, and only newer changes are listed', () => {+ expect(BEHAVIOR_NOTICE_SINCE).toBe(BEHAVIOR_CHANGES.map(c => c.since).sort(compareReleases).at(-1)!);+ expect(BEHAVIOR_NOTICE_ID).toBe(`behavior_changes@${BEHAVIOR_NOTICE_SINCE}`);+ expect(behaviorChangesNotice(null, { after: BEHAVIOR_NOTICE_SINCE })).toBeNull();+ const chain = { plane: 'env' as const, entries: ['openai:gpt-5.6-luna'], providers: ['openai'], onRefusal: true, filePath: '' };+ const later = behaviorChangesNotice(chain, { after: '0.60.68.0' })!;+ expect(later.why).not.toContain('chat_fallback_chain is live');+ expect(later.fix?.argv).toEqual(['gbrain', 'doctor', '--only', 'behavior_changes', '--json']);+ const all = behaviorChangesNotice(chain)!;+ expect(all.why).toContain('gbrain v0.60.68.0 and v0.60.74.0 changed 10 behaviors');+ expect(all.fix?.argv).toEqual(['unset', 'GBRAIN_CHAT_FALLBACK_CHAIN']);+ });+});+describe('concurrent initializations', () => {test('processes racing on one brain and channel deliver it exactly once', async () => {const home = freshHome();@@ -296,3 +325,86 @@ describe('concurrent initializations', () => {expect(readFileSync(join(noticeDir(home), 'race.baseline'), 'utf8').trim()).toBe('0');}, 60_000);});++describe('upgrades across releases (each step a new process pinned to a gbrain VERSION)', () => {+ const modulePath = join(import.meta.dir, '..', 'src', 'core', 'behavior-change-notice.ts');+ const WAVE9 = '`setsid`';+ const V68 = 'cycle.lint_fix false';++ /** One gbrain process at `version`: takes the notice on `channel` (`http:<client>` for an HTTP client) for brain `key`. */+ async function runAt(home: string, version: string, key: string, channel: string, opts: { createdAgoMs?: number } = {}): Promise<string | null> {+ const script = join(home, `step-${++seq}.ts`);+ writeFileSync(script, `+ Bun.plugin({ setup(b) { b.onLoad({ filter: /[\\\\/]src[\\\\/]version\\.ts$/ }, () => ({ contents: ${JSON.stringify(`export const VERSION = '${version}';`)}, loader: 'ts' })); } });+ const { existsSync, readFileSync, writeFileSync } = await import('node:fs');+ const { takeLocalBehaviorNotice, takeHttpBehaviorNotice } = await import(${JSON.stringify(modulePath)});+ const storePath = ${JSON.stringify(join(home, 'brain-config.json'))};+ const store = existsSync(storePath) ? JSON.parse(readFileSync(storePath, 'utf8')) : {};+ const created = new Date(Date.now() - ${opts.createdAgoMs ?? 3 * DAY}).toISOString();+ const engine = {+ executeRaw: async () => [{ at: created }],+ getConfig: async (k) => store[k] ?? null,+ setConfig: async (k, v) => { store[k] = v; writeFileSync(storePath, JSON.stringify(store)); },+ };+ const channel = ${JSON.stringify(channel)};+ const n = channel.startsWith('http:')+ ? await takeHttpBehaviorNotice(engine, channel.slice(5), { cfg: null, brainKey: ${JSON.stringify(key)} })+ : await takeLocalBehaviorNotice(engine, channel, { cfg: null, brainKey: ${JSON.stringify(key)} });+ console.log(JSON.stringify({ why: n?.why ?? null }));+ `);+ const env = { ...process.env, GBRAIN_HOME: home, GBRAIN_CHAT_FALLBACK_CHAIN: '' } as Record<string, string>;+ const p = Bun.spawn(['bun', script], { env, stdout: 'pipe', stderr: 'pipe' });+ const [out, err] = await Promise.all([new Response(p.stdout).text(), new Response(p.stderr).text(), p.exited]);+ const last = out.trim().split('\n').pop();+ if (!last) throw new Error(`step at ${version} printed nothing: ${err}`);+ return JSON.parse(last).why as string | null;+ }++ test('a brain that saw the notice gets nothing from a later release that adds no behavior changes', async () => {+ const home = freshHome();+ for (const channel of ['cli', 'http:client-a']) {+ expect(await runAt(home, '0.60.74.0', 'seen', channel)).toContain(WAVE9);+ expect(await runAt(home, '0.60.74.0', 'seen', channel)).toBeNull();+ expect(await runAt(home, '0.60.99.0', 'seen', channel)).toBeNull();+ }+ }, 60_000);++ test('a brain at baseline 0.60.68 that saw the 0.60.68 notice sees only the 0.60.74 items, once', async () => {+ const home = freshHome();+ mkdirSync(noticeDir(home), { recursive: true });+ writeFileSync(join(noticeDir(home), 'b68.baseline'), '0.60.68.0\n');+ writeFileSync(join(noticeDir(home), 'behavior_changes_0.60.68.0.b68.cli.shown'), '2026-10-05T00:00:00.000Z\n');+ writeFileSync(join(home, 'brain-config.json'), JSON.stringify({ [HTTP_SHOWN_KEY]: JSON.stringify({ id: '[email protected]', clients: { 'client-a': '2026-10-05T00:00:00.000Z' } }) }));+ for (const channel of ['cli', 'http:client-a']) {+ const why = await runAt(home, '0.60.74.0', 'b68', channel);+ expect(why).toContain('gbrain v0.60.74.0 changed 6 behaviors');+ expect(why).toContain(WAVE9);+ expect(why).not.toContain(V68);+ expect(why).not.toContain('v0.60.68.0');+ expect(await runAt(home, '0.60.74.0', 'b68', channel)).toBeNull();+ expect(await runAt(home, '0.60.75.0', 'b68', channel)).toBeNull();+ }+ }, 60_000);++ test('a brain older than 0.60.68 sees every item, labeled with its release, once', async () => {+ const home = freshHome();+ for (const channel of ['cli', 'stdio', 'http:client-a']) {+ const why = await runAt(home, '0.60.74.0', 'old', channel);+ expect(why).toContain('gbrain v0.60.68.0 and v0.60.74.0 changed 9 behaviors');+ expect(why).toContain(`v0.60.68.0: (1) On a managed brain`);+ expect(why).toContain(`v0.60.74.0: (4) A shell job`);+ expect(await runAt(home, '0.60.74.0', 'old', channel)).toBeNull();+ expect(await runAt(home, '0.60.99.0', 'old', channel)).toBeNull();+ }+ expect(readFileSync(join(noticeDir(home), 'old.baseline'), 'utf8').trim()).toBe('0');+ }, 60_000);++ test('a fresh brain sees nothing, then or after later upgrades', async () => {+ const home = freshHome();+ for (const channel of ['cli', 'http:client-a']) {+ expect(await runAt(home, '0.60.74.0', 'new', channel, { createdAgoMs: 0 })).toBeNull();+ expect(await runAt(home, '0.60.99.0', 'new', channel, { createdAgoMs: 2 * DAY })).toBeNull();+ }+ expect(readFileSync(join(noticeDir(home), 'new.baseline'), 'utf8').trim()).toBe('0.60.74.0');+ }, 60_000);+});diff --git a/test/fixtures/goldens/doctor/json-pglite-degraded.json b/test/fixtures/goldens/doctor/json-pglite-degraded.jsonindex 322e5bf7f4..1e43f00ce9 100644--- a/test/fixtures/goldens/doctor/json-pglite-degraded.json+++ b/test/fixtures/goldens/doctor/json-pglite-degraded.json@@ -562,7 +562,7 @@},{"category": "meta",- "message": "Nothing to disclose: this brain is a fresh install at v<version> or later, so the one-time behavior-change notice does not apply.",+ "message": "Nothing to disclose: this brain is a fresh install at v<version>, after every disclosed behavior change, so the one-time behavior-change notice does not apply.","name": "behavior_changes","status": "ok"},diff --git a/test/fixtures/goldens/doctor/json-pglite-fresh.json b/test/fixtures/goldens/doctor/json-pglite-fresh.jsonindex 73103ac286..bcd31bc98d 100644--- a/test/fixtures/goldens/doctor/json-pglite-fresh.json+++ b/test/fixtures/goldens/doctor/json-pglite-fresh.json@@ -650,7 +650,7 @@},{"category": "meta",- "message": "Nothing to disclose: this brain is a fresh install at v<version> or later, so the one-time behavior-change notice does not apply.",+ "message": "Nothing to disclose: this brain is a fresh install at v<version>, after every disclosed behavior change, so the one-time behavior-change notice does not apply.","name": "behavior_changes","status": "ok"},diff --git a/test/fixtures/goldens/doctor/json-postgres-fresh.json b/test/fixtures/goldens/doctor/json-postgres-fresh.jsonindex 997a865047..20cf5348aa 100644--- a/test/fixtures/goldens/doctor/json-postgres-fresh.json+++ b/test/fixtures/goldens/doctor/json-postgres-fresh.json@@ -639,7 +639,7 @@},{"category": "meta",- "message": "Nothing to disclose: this brain is a fresh install at v<version> or later, so the one-time behavior-change notice does not apply.",+ "message": "Nothing to disclose: this brain is a fresh install at v<version>, after every disclosed behavior change, so the one-time behavior-change notice does not apply.","name": "behavior_changes","status": "ok"},