Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

v0.47.3.0 fix: wave-L — wave-k close-out (stricter sources_list confinement #4433, memory writeback contract #4105, reference docs) (#4663)

Garry Tan17eff27cf046
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json
index 1aa8356351..6d5a4d002a 100644
--- a/.claude-plugin/plugin.json
+++ b/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "gbrain",
- "version": "0.47.0.0",
+ "version": "0.47.3.0",
"description": "Personal knowledge brain for your coding agent \u2014 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.json
index e6802dfb30..5b8610b26e 100644
--- a/.codex-plugin/plugin.json
+++ b/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "gbrain",
- "version": "0.47.0.0",
+ "version": "0.47.3.0",
"description": "Personal knowledge brain for your coding agent \u2014 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.md
index d0f70d9d01..3bbae2cad8 100644
--- a/BOOTSTRAP_FOR_AGENTS.md
+++ b/BOOTSTRAP_FOR_AGENTS.md
@@ -1,4 +1,4 @@
-<!-- gbrain-runbook-stamp: 0.47.0.0 -->
+<!-- gbrain-runbook-stamp: 0.47.3.0 -->
<!-- This stamp must equal the VERSION file at every release; CI enforces it
(scripts/check-bootstrap-tag.sh). `gbrain bootstrap status` compares it to
the installed binary and warns on skew. -->
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 2a9255bd6a..797395cb07 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,39 @@
All notable changes to GBrain will be documented in this file.
+## [0.47.3.0] - 2026-08-27
+
+**Wave L: the wave-k close-out.** Three held-back items from the wave-k triage,
+each resolved with the maintainer's explicit call, plus reference docs for
+three surfaces that shipped without a home.
+
+### Behavior changes
+- **Security (#4433): `sources_list` is now confined to the caller's resolved
+ source scope for ALL remote callers**, not just those with a federated read
+ grant. Remote clients on the scalar default-source floor (legacy bearer
+ tokens, pre-`federated_read` OAuth clients) now see only their bound source
+ instead of the full source registry; a remote `__all__` scope yields an
+ empty listing (fail-closed). Local CLI (`gbrain sources list`) keeps the
+ full operator listing. Need the wider listing remotely? Widen the grant:
+ `gbrain auth rescope-client <id> --federated-read src1,src2,…`. This
+ supersedes wave-g's softer posture by maintainer decision.
+
+### Added
+- Same-turn memory write-back is now part of the install contract: `verify`
+ gains a `writeback_contract` check and `gbrain bootstrap contract [--repair]`
+ audits AGENTS.md, appending an additive, backed-up gate for pre-bootstrap or
+ custom workspaces (never overwrites; refuses symlinks). Templates route
+ atomic facts through `remember` with explicit provenance. (#4105 by
+ @garrytan-agents)
+ **Say to your agent:** "check my workspace's memory write-back contract" /
+ "run gbrain bootstrap contract --repair"
+- Reference docs for three previously undocumented surfaces:
+ `apply-migrations --list/--dry-run/--require-db` + the DB-probe line
+ (docs/GBRAIN_VERIFY.md), the bulk-embed failure knobs
+ `GBRAIN_EMBED_QUARANTINE_AFTER` / `GBRAIN_EMBED_MAX_BATCH_TOKENS`
+ (docs/integrations/embedding-providers.md), and `config get` redaction +
+ `--raw` (docs/INSTALL.md).
+
## [0.47.0.0] - 2026-08-25
The Gmail-first open-loop engine. Connect your Google account once and gbrain
diff --git a/VERSION b/VERSION
index e779ab1407..f9d4c14f92 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-0.47.0.0
\ No newline at end of file
+0.47.3.0
diff --git a/docs/GBRAIN_VERIFY.md b/docs/GBRAIN_VERIFY.md
index e5f049b04c..62d2037eae 100644
--- a/docs/GBRAIN_VERIFY.md
+++ b/docs/GBRAIN_VERIFY.md
@@ -36,6 +36,44 @@ gbrain doctor --json
**If it fails:** The doctor output includes specific fix instructions for each
check. See `skills/setup/SKILL.md` Error Recovery table.
+### 1a. Migration Plan and DB Probe
+
+**Command:**
+
+```bash
+gbrain apply-migrations --list # per-version status: applied / partial / wedged / pending / future
+gbrain apply-migrations --dry-run # what a real run would apply or resume
+```
+
+Both surfaces are read-only — they never run orchestrators or schema
+migrations, even when combined with `--yes`. Each prints a `Database:` probe
+line above the plan, so an unreachable database is distinguishable from a
+clean one (the two used to render the identical all-pending plan):
+
+- `Database: connected, schema vN (latest M)` — the pre-flight probe
+ connected. N behind M means schema migrations are pending; a plain run with
+ `--yes` applies them.
+- `Database: UNREACHABLE (<reason>)` — the pre-flight connect failed. The
+ reason is scrubbed through both credential redactors (URL userinfo +
+ connection-info), so it is safe to paste into issues and CI logs.
+- `Database: not probed (<reason>)` — no probe was attempted. Normal on
+ PGLite (`pglite manages schema in-process`): the orchestrators handle the
+ schema lifecycle internally there, and the probe would briefly hold the
+ single-writer lock.
+
+**Expected:** `Database: connected, schema vN (latest N)` on Postgres, or
+`Database: not probed (pglite manages schema in-process)` on PGLite, followed
+by `All migrations up to date.`
+
+**If it fails:** an unreachable database does not stop a default run —
+orchestrator migrations still run their filesystem-only phases. Scripts and
+CI that need a hard signal add `--require-db`: with it, `--list` and
+`--dry-run` exit 1 when the probe failed, and a real run prints the probe
+line and aborts with exit 1 before any orchestrator runs. The observational
+sibling is `gbrain doctor --no-migrate`, which connects probe-only so a
+clean-or-behind schema is reported on as-is instead of being auto-migrated
+before the health checks run.
+
---
## 2. Skillpack Loaded
diff --git a/docs/INSTALL.md b/docs/INSTALL.md
index b297cdccdc..57731fb13a 100644
--- a/docs/INSTALL.md
+++ b/docs/INSTALL.md
@@ -64,6 +64,8 @@ export OPENAI_API_KEY=sk-... # alternative embeddings; also powers auto
export ANTHROPIC_API_KEY=sk-ant-... # automatic fact extraction + chat models; also improves search via query expansion
```
+Reading a value back: `gbrain config get <key>` prints redacted by default — sensitive keys (any `key`/`secret`/`token`/`password`-segmented name) print `***`, and a `postgres://` / `postgresql://` value like `database_url` has its `user:password` userinfo replaced with `***` (host, port, database, and query string preserved) — because `get` output lands in agent transcripts and shell history. Scripts that need the real value pass `--raw` (accepted before or after the key). `config show` and the `Set <key> = ...` confirmation that `config set` prints redact the same way. `get` keeps stdout a bare value and reports which plane answered (file/env or DB) on stderr.
+
Chat-shaped features (automatic fact extraction, enrichment, synthesis, query
expansion) route to whichever supported chat key is present (Anthropic or
OpenAI) — Anthropic when both are set, OpenAI when it is the only one; other
diff --git a/docs/integrations/embedding-providers.md b/docs/integrations/embedding-providers.md
index 8936ad3048..b127fa0287 100644
--- a/docs/integrations/embedding-providers.md
+++ b/docs/integrations/embedding-providers.md
@@ -195,6 +195,15 @@ Three numbers matter:
For most users: **stay at 1024 or 1536**. Bigger isn't better below the noise floor; smaller saves disk + RAM with marginal recall loss on Matryoshka providers.
+## Bulk-embed failure knobs
+
+Two env vars tune how bulk embeds (`gbrain embed --stale` and the autopilot/minion cycles that ride the same stale path) behave under sustained failures. Both matter most against local serial servers (Ollama at `-np 1`, llama-server), where re-sending doomed requests compounds into congestion collapse:
+
+| Env var | Default | What it does |
+|---|---|---|
+| `GBRAIN_EMBED_QUARANTINE_AFTER` | 3 | Consecutive zero-progress attempts (no chunk embedded) before a page is quarantined for the rest of the process. An attempt that embeds ANY chunk resets the page's counter — partial progress shrinks the stale set, so the next pass sends a smaller request, not the identical doomed one. Quarantine is keyed per page (`source_id::slug`) and announced once on stderr; later passes skip quarantined pages with a count. Process-lifetime by design: restarting retries deliberately, and `frontmatter.embed_skip` is the permanent block. Non-numeric or non-positive values fall back to 3. |
+| `GBRAIN_EMBED_MAX_BATCH_TOKENS` | (unset) | Token cap per embedding request for recipes that ship without one — ollama, llama-server, and litellm declare `no_batch_cap` because real capacity depends on the operator's server. When set, chunk texts are pre-split into sub-batches within `cap × safety_factor` (default 0.8) tokens, estimated via the recipe's `chars_per_token` (default 4). A recipe-declared cap always wins; invalid values are ignored. Read once from the environment at process start, never at call time. Without it, `no_batch_cap` recipes still get a conservative 16-item sub-batch cap so the per-call embed timeout bounds a fixed amount of work. |
+
## My provider isn't listed
Four options:
diff --git a/llms-full.txt b/llms-full.txt
index d2a4c66e35..aa812204a3 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -5610,6 +5610,44 @@ gbrain doctor --json
**If it fails:** The doctor output includes specific fix instructions for each
check. See `skills/setup/SKILL.md` Error Recovery table.
+### 1a. Migration Plan and DB Probe
+
+**Command:**
+
+```bash
+gbrain apply-migrations --list # per-version status: applied / partial / wedged / pending / future
+gbrain apply-migrations --dry-run # what a real run would apply or resume
+```
+
+Both surfaces are read-only — they never run orchestrators or schema
+migrations, even when combined with `--yes`. Each prints a `Database:` probe
+line above the plan, so an unreachable database is distinguishable from a
+clean one (the two used to render the identical all-pending plan):
+
+- `Database: connected, schema vN (latest M)` — the pre-flight probe
+ connected. N behind M means schema migrations are pending; a plain run with
+ `--yes` applies them.
+- `Database: UNREACHABLE (<reason>)` — the pre-flight connect failed. The
+ reason is scrubbed through both credential redactors (URL userinfo +
+ connection-info), so it is safe to paste into issues and CI logs.
+- `Database: not probed (<reason>)` — no probe was attempted. Normal on
+ PGLite (`pglite manages schema in-process`): the orchestrators handle the
+ schema lifecycle internally there, and the probe would briefly hold the
+ single-writer lock.
+
+**Expected:** `Database: connected, schema vN (latest N)` on Postgres, or
+`Database: not probed (pglite manages schema in-process)` on PGLite, followed
+by `All migrations up to date.`
+
+**If it fails:** an unreachable database does not stop a default run —
+orchestrator migrations still run their filesystem-only phases. Scripts and
+CI that need a hard signal add `--require-db`: with it, `--list` and
+`--dry-run` exit 1 when the probe failed, and a real run prints the probe
+line and aborts with exit 1 before any orchestrator runs. The observational
+sibling is `gbrain doctor --no-migrate`, which connects probe-only so a
+clean-or-behind schema is reported on as-is instead of being auto-migrated
+before the health checks run.
+
---
## 2. Skillpack Loaded
diff --git a/openclaw.plugin.json b/openclaw.plugin.json
index b2cd793082..8a2c5fd275 100644
--- a/openclaw.plugin.json
+++ b/openclaw.plugin.json
@@ -1,7 +1,7 @@
{
"id": "gbrain-context-engine",
"name": "gbrain",
- "version": "0.47.0.0",
+ "version": "0.47.3.0",
"description": "Personal knowledge brain with Postgres + pgvector hybrid search",
"family": "bundle-plugin",
"configSchema": {
diff --git a/package.json b/package.json
index 130c36acc0..19791dc0af 100644
--- a/package.json
+++ b/package.json
@@ -171,7 +171,7 @@
"bun": ">=1.3.10"
},
"license": "MIT",
- "version": "0.47.0.0",
+ "version": "0.47.3.0",
"overrides": {
"@hono/node-server": "^2.0.5",
"fast-uri": "^3.1.5",
diff --git a/plugin-variants/gbrain-coding/.claude-plugin/plugin.json b/plugin-variants/gbrain-coding/.claude-plugin/plugin.json
index 683ccfe743..ded31ea76a 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.47.0.0",
+ "version": "0.47.3.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 — 20 skills)",
"author": {
"name": "Garry Tan",
diff --git a/plugin-variants/gbrain-coding/.codex-plugin/plugin.json b/plugin-variants/gbrain-coding/.codex-plugin/plugin.json
index c278ea65d0..83d20a48c8 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.47.0.0",
+ "version": "0.47.3.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 — 20 skills)",
"author": {
"name": "Garry Tan",
diff --git a/plugin-variants/gbrain-coding/README.md b/plugin-variants/gbrain-coding/README.md
index 8b1b804f58..c5db6b9be4 100644
--- a/plugin-variants/gbrain-coding/README.md
+++ b/plugin-variants/gbrain-coding/README.md
@@ -1,4 +1,4 @@
-<!-- gbrain-plugin-tree-stamp: 0.47.0.0 -->
+<!-- gbrain-plugin-tree-stamp: 0.47.3.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-coding/skills/_AGENT_README.md b/plugin-variants/gbrain-coding/skills/_AGENT_README.md
index da5d232414..d0a0bb7642 100644
--- a/plugin-variants/gbrain-coding/skills/_AGENT_README.md
+++ b/plugin-variants/gbrain-coding/skills/_AGENT_README.md
@@ -50,6 +50,25 @@ carries the disambiguation rules for overlapping matches. If the two disagree,
frontmatter wins. (There is no machine-managed block inside `RESOLVER.md` or
`AGENTS.md`; that pattern was retired.)
+## The always-on memory loop
+
+Routing a requested skill is only half the job. On every inbound message,
+apply the bundled `signal-detector` contract directly (or through a host-native
+background lane when the user has authorized delegation), then close the turn
+with same-turn write-back:
+
+1. Read relevant entity/project context before answering.
+2. Detect durable new facts, preferences, decisions, commitments, relationships,
+ and original thinking in the user's message and in the resulting discussion.
+3. Write atomic facts with GBrain's `remember` verb and explicit provenance.
+ Route richer knowledge through `brain-ops` (`put_page`, timeline, links).
+4. Verify with `recall`, `entity`, or `get_page` before claiming the write landed.
+
+Context injection is read-side automation; it does not, by itself, capture what
+the agent just learned. A turn that learned something durable and recorded
+nothing is incomplete. Skip only transient logistics, acknowledgments, and facts
+already verified as present.
+
## When the user invokes a skill
Read the entire `skills/<slug>/SKILL.md` file. Follow its `## Phases`,
diff --git a/plugin-variants/gbrain-daily/.claude-plugin/plugin.json b/plugin-variants/gbrain-daily/.claude-plugin/plugin.json
index 7515be27bd..f61fc3c0d6 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.47.0.0",
+ "version": "0.47.3.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 — 19 skills)",
"author": {
"name": "Garry Tan",
diff --git a/plugin-variants/gbrain-daily/.codex-plugin/plugin.json b/plugin-variants/gbrain-daily/.codex-plugin/plugin.json
index 11738ef09a..f236f46cd9 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.47.0.0",
+ "version": "0.47.3.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 — 19 skills)",
"author": {
"name": "Garry Tan",
diff --git a/plugin-variants/gbrain-daily/README.md b/plugin-variants/gbrain-daily/README.md
index 8b61c6d40b..1a6aff9351 100644
--- a/plugin-variants/gbrain-daily/README.md
+++ b/plugin-variants/gbrain-daily/README.md
@@ -1,4 +1,4 @@
-<!-- gbrain-plugin-tree-stamp: 0.47.0.0 -->
+<!-- gbrain-plugin-tree-stamp: 0.47.3.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-variants/gbrain-daily/skills/_AGENT_README.md b/plugin-variants/gbrain-daily/skills/_AGENT_README.md
index da5d232414..d0a0bb7642 100644
--- a/plugin-variants/gbrain-daily/skills/_AGENT_README.md
+++ b/plugin-variants/gbrain-daily/skills/_AGENT_README.md
@@ -50,6 +50,25 @@ carries the disambiguation rules for overlapping matches. If the two disagree,
frontmatter wins. (There is no machine-managed block inside `RESOLVER.md` or
`AGENTS.md`; that pattern was retired.)
+## The always-on memory loop
+
+Routing a requested skill is only half the job. On every inbound message,
+apply the bundled `signal-detector` contract directly (or through a host-native
+background lane when the user has authorized delegation), then close the turn
+with same-turn write-back:
+
+1. Read relevant entity/project context before answering.
+2. Detect durable new facts, preferences, decisions, commitments, relationships,
+ and original thinking in the user's message and in the resulting discussion.
+3. Write atomic facts with GBrain's `remember` verb and explicit provenance.
+ Route richer knowledge through `brain-ops` (`put_page`, timeline, links).
+4. Verify with `recall`, `entity`, or `get_page` before claiming the write landed.
+
+Context injection is read-side automation; it does not, by itself, capture what
+the agent just learned. A turn that learned something durable and recorded
+nothing is incomplete. Skip only transient logistics, acknowledgments, and facts
+already verified as present.
+
## When the user invokes a skill
Read the entire `skills/<slug>/SKILL.md` file. Follow its `## Phases`,
diff --git a/plugin/README.md b/plugin/README.md
index d4fd45423f..a96ecb6a92 100644
--- a/plugin/README.md
+++ b/plugin/README.md
@@ -1,4 +1,4 @@
-<!-- gbrain-plugin-tree-stamp: 0.47.0.0 -->
+<!-- gbrain-plugin-tree-stamp: 0.47.3.0 -->
# gbrain plugin skill tree (generated — do not hand-edit)
This tree is the curated skill set for the gbrain Codex and Claude Code
diff --git a/plugin/skills/_AGENT_README.md b/plugin/skills/_AGENT_README.md
index da5d232414..d0a0bb7642 100644
--- a/plugin/skills/_AGENT_README.md
+++ b/plugin/skills/_AGENT_README.md
@@ -50,6 +50,25 @@ carries the disambiguation rules for overlapping matches. If the two disagree,
frontmatter wins. (There is no machine-managed block inside `RESOLVER.md` or
`AGENTS.md`; that pattern was retired.)
+## The always-on memory loop
+
+Routing a requested skill is only half the job. On every inbound message,
+apply the bundled `signal-detector` contract directly (or through a host-native
+background lane when the user has authorized delegation), then close the turn
+with same-turn write-back:
+
+1. Read relevant entity/project context before answering.
+2. Detect durable new facts, preferences, decisions, commitments, relationships,
+ and original thinking in the user's message and in the resulting discussion.
+3. Write atomic facts with GBrain's `remember` verb and explicit provenance.
+ Route richer knowledge through `brain-ops` (`put_page`, timeline, links).
+4. Verify with `recall`, `entity`, or `get_page` before claiming the write landed.
+
+Context injection is read-side automation; it does not, by itself, capture what
+the agent just learned. A turn that learned something durable and recorded
+nothing is incomplete. Skip only transient logistics, acknowledgments, and facts
+already verified as present.
+
## When the user invokes a skill
Read the entire `skills/<slug>/SKILL.md` file. Follow its `## Phases`,
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index ccbc0f4a8a..9d312bd1e6 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -27,7 +27,7 @@ src/core/minions/queue.ts 2442 ratchet grown #4078 + megawave probe-liveness unl
src/commands/init.ts 2026 ratchet grown v0.46.x keyless capability notices; grown db-availability loop: initPostgresCore typed-failure extraction + --prefer-postgres ladder hook + pgvector rethrow fix; +1 at megawave/wave-k merge; +master-merge true-up; wave-k: merge; #3753 --force re-init engine-preservation guard; +1 wave-k merge-union brace (--prefer-postgres close)
src/commands/integrations.ts 1739 ratchet grown v0.46.26.0 megawave (#4039 connector compat) + 1 nosemgrep dataflow annotation (path-traversal audit); wave-k: exported heartbeatPath seam (#3900)
src/core/minions/handlers/subagent.ts 1834 ratchet merged: master v131 settle rework + dream-wave C5 peel + C6 accounting + C7 lease heartbeats/lost-lease aborts + C9 oneshot dispatch + adversarial fix batches; grown by #4078 subagent-loop capability fix; +6 lines (reasoning-item replay: adaptContentBlocksToChatBlocks handles 'reasoning' blocks); +3 wave G #4514: Anthropic-via-OpenRouter allowed on the subagent loop
-src/commands/bootstrap.ts 2015 ratchet grandfathered at merge (grew past the 1500 cap on master); raised for #4066 HOME_WORKSPACE_GUARD_EXEMPT (status/uninstall/harness); +5 for the harnessDetect test seam (bulk lives in core/bootstrap/harness.ts)
+src/commands/bootstrap.ts 2038 ratchet grandfathered at merge (grew past the 1500 cap on master); raised for #4066 HOME_WORKSPACE_GUARD_EXEMPT (status/uninstall/harness); +5 for the harnessDetect test seam (bulk lives in core/bootstrap/harness.ts); +23 for the contract subcommand dispatcher glue (#4105 absorb — bulk lives in core/bootstrap/contract.ts)
src/core/minions/worker.ts 1560 ratchet grandfathered at merge (grew past the 1500 cap on master, #4170); grown v0.46.11.0 five-issue wave
src/commands/sources.ts 1926 ratchet grown v0.46.22.0 phone wave: github source kind (#4104); +129 v0.47 gmail-loops: google source-kind flags + vault preflight + duplicate-account warn + access-mode validation
src/core/link-extraction.ts 1718 ratchet grown v0.46.26.0 megawave: link-aware timeline split + delimiter-outside-links (#3957 #4062 #3737); +37 wave-k #3908 reimpl: isCrossSourceLinksEnabled config ladder
diff --git a/scripts/structural-suites.tsv b/scripts/structural-suites.tsv
index 23228e5bd9..fea79514d6 100644
--- a/scripts/structural-suites.tsv
+++ b/scripts/structural-suites.tsv
@@ -31,6 +31,7 @@ test/backup-cli.serial.test.ts runBackupCli — PGLite lock fallback 3 readFileS
test/backup-invalidation.serial.test.ts bootstrap repo — recordRepoInReceipt contract (source-text pin) 2 readFileSync
test/book-mirror.test.ts gbrain book-mirror — source file invariants 7 readFileSync
test/bootstrap-codex-door.test.ts Codex door — rendered AGENTS.md pull protocol (Gate 3) 2 readFileSync
+test/bootstrap-contract.test.ts bootstrap same-turn write-back contract 6 readFileSync
test/bootstrap-opencode-door.serial.test.ts opencode door — rendered AGENTS.md pull protocol 1 readFileSync
test/brain-repo-durability.serial.test.ts hardenBrainRepo 16 readFileSync
test/brain-score-breakdown.test.ts Bug 11 — BrainHealth type shape 1 bun-file
diff --git a/skills/_AGENT_README.md b/skills/_AGENT_README.md
index da5d232414..d0a0bb7642 100644
--- a/skills/_AGENT_README.md
+++ b/skills/_AGENT_README.md
@@ -50,6 +50,25 @@ carries the disambiguation rules for overlapping matches. If the two disagree,
frontmatter wins. (There is no machine-managed block inside `RESOLVER.md` or
`AGENTS.md`; that pattern was retired.)
+## The always-on memory loop
+
+Routing a requested skill is only half the job. On every inbound message,
+apply the bundled `signal-detector` contract directly (or through a host-native
+background lane when the user has authorized delegation), then close the turn
+with same-turn write-back:
+
+1. Read relevant entity/project context before answering.
+2. Detect durable new facts, preferences, decisions, commitments, relationships,
+ and original thinking in the user's message and in the resulting discussion.
+3. Write atomic facts with GBrain's `remember` verb and explicit provenance.
+ Route richer knowledge through `brain-ops` (`put_page`, timeline, links).
+4. Verify with `recall`, `entity`, or `get_page` before claiming the write landed.
+
+Context injection is read-side automation; it does not, by itself, capture what
+the agent just learned. A turn that learned something durable and recorded
+nothing is incomplete. Skip only transient logistics, acknowledgments, and facts
+already verified as present.
+
## When the user invokes a skill
Read the entire `skills/<slug>/SKILL.md` file. Follow its `## Phases`,
diff --git a/skills/skills.lock.json b/skills/skills.lock.json
index 252350aeae..94eaf01ff1 100644
--- a/skills/skills.lock.json
+++ b/skills/skills.lock.json
@@ -1,6 +1,6 @@
{
"RESOLVER.md": "032fcc8131d8a7458dcc47c4a3f521eaa753ef6cf8734e5b66d699f3599903b7",
- "_AGENT_README.md": "62613f7f1e061576b6c1b18844f59bd35f2df96ca5c45c8c41fae0772b9ce4d3",
+ "_AGENT_README.md": "cd61adb06fcd93928e4b565e14430b88cfe6879c57536ff6d15c3cad2f27a92f",
"_brain-filing-rules.json": "cf850df6a7425464c6d63b3ace71991cc93497fa0cc8cd21acd31883e17939c6",
"_brain-filing-rules.md": "2d2d75b7c76081c56f41b2c0a5a978c355ce957300f9b0a5575dc4079ef1f877",
"_friction-protocol.md": "51353207240142024ff1facc25f225712275ecdb4a034ffffdd83740c8d328e3",
diff --git a/src/commands/bootstrap.ts b/src/commands/bootstrap.ts
index 1d01c06edc..7b02a69d7a 100644
--- a/src/commands/bootstrap.ts
+++ b/src/commands/bootstrap.ts
@@ -101,6 +101,7 @@ import {
type StatusReport,
} from '../core/bootstrap/status.ts';
import { verifyWorkspace, resolveVerifySourceId, deriveWorkspaceSourceId } from '../core/bootstrap/verify.ts';
+import { auditWritebackContract, repairWritebackContract } from '../core/bootstrap/contract.ts';
export const BOOTSTRAP_HELP = `gbrain bootstrap — paste-in agent install (Claude Code / Codex / opencode)
@@ -118,6 +119,8 @@ Subcommands (run \`gbrain bootstrap status\` first — it is the resume entrypoi
render [--force] [--only F] [--minimal]
Render identity files from the confirmed answers.
Never clobbers; --force backs up first.
+ contract [--repair] Audit the same-turn GBrain write-back contract.
+ --repair appends it additively and backs up AGENTS.md.
hooks [--harness claude-code|codex|opencode] [--repair] [--no-hooks] [--gbrain-bin <path>]
Register MCP (+ per-turn hooks on Claude Code,
ON by default; --no-hooks opts out, GBRAIN_HOOKS=0
@@ -174,6 +177,9 @@ const SUBCOMMAND_HELP: Record<string, string> = {
render:
'gbrain bootstrap render [--force] [--only F] [--minimal]\n' +
' Render identity files from the confirmed interview answers. Never clobbers; --force backs up first.',
+ contract:
+ 'gbrain bootstrap contract [--repair]\n' +
+ ' Audit AGENTS.md for the same-turn GBrain write-back contract. --repair appends a marker-owned block and backs up the original.',
repo:
'gbrain bootstrap repo\n' +
' Create the dedicated PRIVATE GitHub repo (or adopt an EMPTY private repo you created\n' +
@@ -689,6 +695,20 @@ async function runStatus(ws: string, rest: string[], home: string): Promise<numb
return 0;
}
+async function runContract(ws: string, rest: string[]): Promise<number> {
+ const repair = rest.includes('--repair');
+ if (!repair) {
+ const audit = auditWritebackContract(ws);
+ console.log(JSON.stringify(audit, null, 2));
+ return audit.ok ? 0 : 1;
+ }
+ return withLock(ws, async () => {
+ const result = repairWritebackContract(ws);
+ console.log(JSON.stringify(result, null, 2));
+ return result.ok ? 0 : 1;
+ });
+}
+
/** One copy of the A8 invalidation warning — shared by --set and --skip so
* the operator-facing instructions cannot drift between the two branches. */
function warnInvalidatedConfirmation(): void {
@@ -1882,7 +1902,7 @@ export async function runBootstrap(args: string[], opts: RunBootstrapOpts = {}):
}
const rest = args.slice(1);
- const KNOWN = new Set(['status', 'interview', 'render', 'repo', 'hooks', 'verify', 'attach', 'uninstall', 'harness', 'cloud-setup-script']);
+ const KNOWN = new Set(['status', 'interview', 'render', 'contract', 'repo', 'hooks', 'verify', 'attach', 'uninstall', 'harness', 'cloud-setup-script']);
if (!KNOWN.has(sub)) {
console.error(`unknown subcommand: ${sub}`);
console.error(BOOTSTRAP_HELP);
@@ -1963,6 +1983,9 @@ export async function runBootstrap(args: string[], opts: RunBootstrapOpts = {}):
case 'render':
code = await runRender(ws, rest, home);
break;
+ case 'contract':
+ code = await runContract(ws, rest);
+ break;
case 'repo':
code = await runRepo(ws, rest, home, runner);
break;
diff --git a/src/core/bootstrap/contract.ts b/src/core/bootstrap/contract.ts
new file mode 100644
index 0000000000..887abe557b
--- /dev/null
+++ b/src/core/bootstrap/contract.ts
@@ -0,0 +1,117 @@
+/**
+ * Additive bootstrap contract repair for legacy and custom agent workspaces.
+ *
+ * Fresh workspaces render the integrated write-back gate from
+ * templates/bootstrap/AGENTS.md.template. Existing workspaces are user-owned,
+ * so upgrades must never overwrite their AGENTS.md. This module audits for the
+ * integrated gate and, on explicit --repair, appends one small marker-owned
+ * block after backing up the original.
+ */
+
+import { existsSync, lstatSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
+import { dirname, join } from 'node:path';
+
+export const WRITEBACK_CONTRACT_BEGIN = '<!-- gbrain:writeback-contract:begin -->';
+export const WRITEBACK_CONTRACT_END = '<!-- gbrain:writeback-contract:end -->';
+
+const INTEGRATED_HARD_GATE = 'WRITE IT DOWN — SAME TURN, THROUGH THE BRAIN';
+const INTEGRATED_TURN_GATE = 'Gate 7 — Write-back';
+
+export const WRITEBACK_CONTRACT_BLOCK = `${WRITEBACK_CONTRACT_BEGIN}
+
+## GBrain same-turn write-back
+
+Context injection is the read side of memory. Before ending any turn where
+something durable was learned, write it through GBrain in the same turn:
+
+- Atomic facts, preferences, decisions, and commitments → \`remember\` with
+ explicit provenance.
+- Richer entity or project knowledge → \`put_page\` / \`add_timeline_entry\`
+ through the brain tools; never edit indexed brain files behind GBrain's back.
+- Verify the write with \`recall\`, \`entity\`, or \`get_page\` before claiming it
+ was stored.
+
+Skip only transient logistics, acknowledgments, and facts already verified as
+present. A turn that learned something durable and recorded nothing is
+incomplete.
+
+${WRITEBACK_CONTRACT_END}`;
+
+export interface WritebackContractAudit {
+ ok: boolean;
+ agentsPath: string;
+ mode: 'integrated' | 'managed' | 'missing' | 'agents_missing';
+ detail: string;
+}
+
+export interface WritebackContractRepair extends WritebackContractAudit {
+ changed: boolean;
+ backupPath: string | null;
+}
+
+function hasIntegratedWritebackContract(content: string): boolean {
+ if (content.includes(INTEGRATED_HARD_GATE) && content.includes(INTEGRATED_TURN_GATE)) return true;
+ const normalized = content.toLowerCase();
+ return (
+ /same[- ]turn/.test(normalized) &&
+ /write[- ]back/.test(normalized) &&
+ (normalized.includes('gbrain remember') || normalized.includes('`remember`')) &&
+ normalized.includes('provenance')
+ );
+}
+
+export function hasWritebackContract(content: string): boolean {
+ const integrated = hasIntegratedWritebackContract(content);
+ const managed = content.includes(WRITEBACK_CONTRACT_BEGIN) && content.includes(WRITEBACK_CONTRACT_END);
+ return integrated || managed;
+}
+
+export function auditWritebackContract(workspaceDir: string): WritebackContractAudit {
+ const agentsPath = join(workspaceDir, 'AGENTS.md');
+ if (!existsSync(agentsPath)) {
+ return {
+ ok: false,
+ agentsPath,
+ mode: 'agents_missing',
+ detail: 'AGENTS.md is missing; render the bootstrap contract before wiring the agent',
+ };
+ }
+ const content = readFileSync(agentsPath, 'utf8');
+ if (hasIntegratedWritebackContract(content)) {
+ return { ok: true, agentsPath, mode: 'integrated', detail: 'integrated same-turn write-back gate present' };
+ }
+ if (content.includes(WRITEBACK_CONTRACT_BEGIN) && content.includes(WRITEBACK_CONTRACT_END)) {
+ return { ok: true, agentsPath, mode: 'managed', detail: 'additive same-turn write-back contract present' };
+ }
+ return {
+ ok: false,
+ agentsPath,
+ mode: 'missing',
+ detail: 'same-turn write-back contract missing; context can be injected without durable capture',
+ };
+}
+
+export function repairWritebackContract(workspaceDir: string): WritebackContractRepair {
+ const audit = auditWritebackContract(workspaceDir);
+ if (audit.ok) return { ...audit, changed: false, backupPath: null };
+ if (audit.mode === 'agents_missing') {
+ throw new Error(`${audit.detail}: ${audit.agentsPath}`);
+ }
+ if (lstatSync(audit.agentsPath).isSymbolicLink()) {
+ throw new Error(`refusing to replace symlinked AGENTS.md: ${audit.agentsPath}`);
+ }
+
+ const original = readFileSync(audit.agentsPath, 'utf8');
+ const stamp = new Date().toISOString().replace(/[:.]/g, '-');
+ const backupPath = join(workspaceDir, '.gbrain-bootstrap-backups', stamp, 'AGENTS.md');
+ mkdirSync(dirname(backupPath), { recursive: true });
+ writeFileSync(backupPath, original, { flag: 'wx' });
+
+ const next = `${original.trimEnd()}\n\n${WRITEBACK_CONTRACT_BLOCK}\n`;
+ const tmp = `${audit.agentsPath}.tmp-${process.pid}`;
+ writeFileSync(tmp, next, 'utf8');
+ renameSync(tmp, audit.agentsPath);
+
+ const repaired = auditWritebackContract(workspaceDir);
+ return { ...repaired, changed: true, backupPath };
+}
diff --git a/src/core/bootstrap/verify.ts b/src/core/bootstrap/verify.ts
index fc4ee69dc0..7453c1b66c 100644
--- a/src/core/bootstrap/verify.ts
+++ b/src/core/bootstrap/verify.ts
@@ -49,6 +49,7 @@ import { readManifest, writeManifest } from './format.ts';
import { status as interviewStatus } from './interview.ts';
import { gitOriginUrl, hooksInstalled } from './status.ts';
import { resolveSourceId } from '../source-resolver.ts';
+import { auditWritebackContract } from './contract.ts';
import {
ensureIpcSecret,
resolveSocketPath,
@@ -271,6 +272,21 @@ function checkByteFloors(ws: string): VerifyCheck {
}
}
+/** A healthy retrieval surface without a same-turn write-back contract is a
+ * one-way memory: useful now, stale later. Fresh bootstrap renders this gate;
+ * the check catches pre-bootstrap/custom workspaces and points at the
+ * additive repair command rather than overwriting their AGENTS.md. */
+export function checkWritebackContract(ws: string): VerifyCheck {
+ const audit = auditWritebackContract(ws);
+ return audit.ok
+ ? { id: 'writeback_contract', ok: true, detail: audit.detail }
+ : {
+ id: 'writeback_contract',
+ ok: false,
+ detail: `${audit.detail}. Fix: run \`gbrain bootstrap contract --repair\` from the workspace (or pass --workspace explicitly).`,
+ };
+}
+
/** Tracked files via git; falls back to the rendered file set + state/ when
* the workspace is not (yet) a git repo. */
function trackedWorkspaceFiles(ws: string): { files: string[]; via: 'git' | 'fallback' } {
@@ -1093,6 +1109,7 @@ export async function verifyWorkspace(
checks.push(checkTokenSweep(ws));
checks.push(checkByteFloors(ws));
+ checks.push(checkWritebackContract(ws));
checks.push(checkSecretScan(ws));
checks.push(checkDenyGlobs(ws));
checks.push(await checkRepoPrivacy(ws));
diff --git a/src/core/ops/sources.ts b/src/core/ops/sources.ts
index 15cbbd2015..3bb31adee8 100644
--- a/src/core/ops/sources.ts
+++ b/src/core/ops/sources.ts
@@ -8,6 +8,7 @@
import type { Operation } from './contract.ts';
import { OperationError } from './contract.ts';
+import { sourceScopeOpts } from './context.ts';
// --- v0.28: whoami + sources management ---
@@ -163,17 +164,19 @@ const sources_list: Operation = {
scope: 'read',
handler: async (ctx, p) => {
const { listSources } = await import('../sources-ops.ts');
- // #4433: row-filter the listing to the caller's federated source grant —
- // a client whose grant excludes a source must not learn that source's
- // id, name, or page_count. The filter mirrors EXACTLY the boundary
- // resolveRequestedScope enforces on explicit per-call `source_id` reads
- // (a non-empty ctx.auth.allowedSources array): the listing shows
- // precisely the sources the caller could actually read. Trusted local
- // CLI and remote callers WITHOUT such a grant (the scalar
- // default-source floor, which today may read any source by naming it
- // explicitly) keep the full listing.
- const granted = ctx.remote !== false ? ctx.auth?.allowedSources : undefined;
- const allowedSourceIds = granted && granted.length > 0 ? granted : undefined;
+ // #4433: row-filter the listing to the caller's source scope — a client
+ // whose scope excludes a source must not learn that source's id, name,
+ // or page_count. Wave-L posture (maintainer decision, supersedes the
+ // wave-g "scalar callers keep the full listing" carve-out): EVERY
+ // untrusted caller (anything not strictly remote === false) is confined
+ // through the canonical sourceScopeOpts ladder, matching the rest of
+ // the read-op surface — federated grant > scalar bound source >
+ // fail-closed '__all__' (the sentinel passes through as a literal that
+ // matches no real source id, so it yields an empty listing rather than
+ // the whole registry). Trusted local CLI keeps the full operator view.
+ const scope = ctx.remote === false ? {} : sourceScopeOpts(ctx);
+ const allowedSourceIds =
+ scope.sourceIds ?? (scope.sourceId !== undefined ? [scope.sourceId] : undefined);
return {
sources: await listSources(ctx.engine, {
includeArchived: (p.include_archived as boolean) === true,
diff --git a/src/core/sources-ops.ts b/src/core/sources-ops.ts
index b5a3b110d9..3c63a87b35 100644
--- a/src/core/sources-ops.ts
+++ b/src/core/sources-ops.ts
@@ -815,12 +815,13 @@ export async function listSources(
// who shouldn't see soft-deleted state. Filter at the SQL level so the
// archived rows never reach the wire by default.
//
- // #4433: `allowedSourceIds` row-filters to the caller's source grant —
+ // #4433: `allowedSourceIds` row-filters to the caller's source scope —
// a scoped remote MCP caller must not enumerate other sources' ids,
// local_paths, or remote_urls. Row-filter (not field redaction) so
- // out-of-grant rows never reach the wire; undefined = unscoped (trusted
- // local CLI, or a remote caller with no source grant — matching the
- // fail-open posture of every other unscoped read).
+ // out-of-scope rows never reach the wire; an explicit empty array matches
+ // nothing (fail-closed); undefined = unscoped (trusted local CLI and
+ // internal callers — since wave-L, remote scalar/no-grant callers pass
+ // their resolved scope here too instead of arriving unscoped).
const conds: string[] = [];
const params: unknown[] = [];
if (!opts.includeArchived) conds.push('archived IS NOT TRUE');
diff --git a/templates/bootstrap/AGENTS.md.template b/templates/bootstrap/AGENTS.md.template
index ca7d7ce382..58641923dc 100644
--- a/templates/bootstrap/AGENTS.md.template
+++ b/templates/bootstrap/AGENTS.md.template
@@ -33,9 +33,10 @@ session death. Anything worth remembering is recorded in the turn it is learned:
`add_timeline_entry` via the gbrain tools. On this machine the brain database is
single-writer: **write through the brain tools, never by editing `brain/` files
directly** — a file edited by hand is invisible to search until a sync can run.
-- Facts worth recalling ("X prefers Y", "deadline moved to Z") → write a `## Facts`
- fence on the relevant page (each line one fact). The brain ingests these
- deterministically — no API key required.
+- Atomic facts worth recalling ("X prefers Y", "deadline moved to Z") →
+ `remember` with explicit provenance. For facts maintained inside a richer
+ entity page, write a `## Facts` fence (each line one fact); the brain ingests
+ these deterministically — no API key required.
- Operational state (open commitments, corrections, active context) → `MEMORY.md`
and `memory/YYYY-MM-DD.md` (file edits are correct for these two — they are loaded
by path, not by search).
diff --git a/templates/bootstrap/template-repo/AGENTS.md b/templates/bootstrap/template-repo/AGENTS.md
index 6660d0fb48..3880532c53 100644
--- a/templates/bootstrap/template-repo/AGENTS.md
+++ b/templates/bootstrap/template-repo/AGENTS.md
@@ -37,9 +37,10 @@ session death. Anything worth remembering is recorded in the turn it is learned:
`add_timeline_entry` via the gbrain tools. On this machine the brain database is
single-writer: **write through the brain tools, never by editing `brain/` files
directly** — a file edited by hand is invisible to search until a sync can run.
-- Facts worth recalling ("X prefers Y", "deadline moved to Z") → write a `## Facts`
- fence on the relevant page (each line one fact). The brain ingests these
- deterministically — no API key required.
+- Atomic facts worth recalling ("X prefers Y", "deadline moved to Z") →
+ `remember` with explicit provenance. For facts maintained inside a richer
+ entity page, write a `## Facts` fence (each line one fact); the brain ingests
+ these deterministically — no API key required.
- Operational state (open commitments, corrections, active context) → `MEMORY.md`
and `memory/YYYY-MM-DD.md` (file edits are correct for these two — they are loaded
by path, not by search).
diff --git a/templates/bootstrap/template-repo/README.md b/templates/bootstrap/template-repo/README.md
index acb5ddf694..ef240b4751 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.47.0.0 -->
+<!-- gbrain-template-stamp: 0.47.3.0 -->
This repository is the **"Use this template"** distribution artifact for a
[gbrain](https://github.com/garrytan/gbrain) personal-agent workspace — the same
diff --git a/test/bootstrap-contract.test.ts b/test/bootstrap-contract.test.ts
new file mode 100644
index 0000000000..390695e4d2
--- /dev/null
+++ b/test/bootstrap-contract.test.ts
@@ -0,0 +1,90 @@
+import { afterEach, describe, expect, test } from 'bun:test';
+import { existsSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+
+import {
+ auditWritebackContract,
+ repairWritebackContract,
+ WRITEBACK_CONTRACT_BEGIN,
+} from '../src/core/bootstrap/contract.ts';
+import { checkWritebackContract } from '../src/core/bootstrap/verify.ts';
+
+const created: string[] = [];
+afterEach(() => {
+ while (created.length) rmSync(created.pop()!, { recursive: true, force: true });
+});
+
+function workspace(agents = '# AGENTS\n\n## Per-message gates\n\n**Gate 3 — Entity lookup (brain first).**\n'): string {
+ const ws = mkdtempSync(join(tmpdir(), 'gbrain-writeback-contract-'));
+ created.push(ws);
+ writeFileSync(join(ws, 'AGENTS.md'), agents);
+ return ws;
+}
+
+describe('bootstrap same-turn write-back contract', () => {
+ test('the default skill bundle carries the memory loop contract', () => {
+ const root = join(import.meta.dir, '..');
+ const plugin = JSON.parse(readFileSync(join(root, 'openclaw.plugin.json'), 'utf8')) as {
+ shared_deps: string[];
+ };
+ expect(plugin.shared_deps).toContain('skills/_AGENT_README.md');
+ const onboarding = readFileSync(join(root, 'skills', '_AGENT_README.md'), 'utf8');
+ expect(onboarding).toContain('## The always-on memory loop');
+ expect(onboarding).toContain("GBrain's `remember` verb");
+ expect(onboarding).toContain('Context injection is read-side automation');
+ });
+
+ test('audits a legacy one-way contract as missing', () => {
+ const ws = workspace();
+ expect(auditWritebackContract(ws).ok).toBe(false);
+ const check = checkWritebackContract(ws);
+ expect(check.ok).toBe(false);
+ expect(check.detail).toContain('bootstrap contract --repair');
+ });
+
+ test('repair is additive, backed up, and idempotent', () => {
+ const ws = workspace('# custom agent rules\n');
+ const first = repairWritebackContract(ws);
+ expect(first.ok).toBe(true);
+ expect(first.changed).toBe(true);
+ expect(first.backupPath).not.toBeNull();
+ expect(existsSync(first.backupPath!)).toBe(true);
+ expect(readFileSync(first.backupPath!, 'utf8')).toBe('# custom agent rules\n');
+
+ const repaired = readFileSync(join(ws, 'AGENTS.md'), 'utf8');
+ expect(repaired).toContain('# custom agent rules');
+ expect(repaired).toContain(WRITEBACK_CONTRACT_BEGIN);
+
+ const second = repairWritebackContract(ws);
+ expect(second.changed).toBe(false);
+ expect(second.backupPath).toBeNull();
+ expect(readFileSync(join(ws, 'AGENTS.md'), 'utf8')).toBe(repaired);
+ });
+
+ test('repair refuses to replace a symlinked AGENTS.md', () => {
+ const ws = mkdtempSync(join(tmpdir(), 'gbrain-writeback-contract-'));
+ created.push(ws);
+ const target = join(ws, 'custom-rules.md');
+ writeFileSync(target, '# custom agent rules\n');
+ symlinkSync(target, join(ws, 'AGENTS.md'));
+ expect(() => repairWritebackContract(ws)).toThrow('refusing to replace symlinked AGENTS.md');
+ expect(readFileSync(target, 'utf8')).toBe('# custom agent rules\n');
+ });
+
+ test('accepts the integrated fresh-bootstrap gate', () => {
+ const ws = workspace(
+ '⛔ **WRITE IT DOWN — SAME TURN, THROUGH THE BRAIN.**\n\n' +
+ '**Gate 7 — Write-back.** Before ending the turn, persist durable learning.\n',
+ );
+ expect(auditWritebackContract(ws)).toMatchObject({ ok: true, mode: 'integrated' });
+ });
+
+ test('accepts a semantically equivalent custom workspace gate', () => {
+ const ws = workspace(
+ '## Durable write-back\n\n' +
+ 'Use same-turn GBrain write-back for durable learning. Run `gbrain remember` with provenance, then verify it.\n',
+ );
+ expect(auditWritebackContract(ws)).toMatchObject({ ok: true, mode: 'integrated' });
+ });
+});
diff --git a/test/bootstrap-verify.serial.test.ts b/test/bootstrap-verify.serial.test.ts
index 0c397a5fdd..277514b7cc 100644
--- a/test/bootstrap-verify.serial.test.ts
+++ b/test/bootstrap-verify.serial.test.ts
@@ -90,6 +90,11 @@ beforeAll(async () => {
expect(confirm(ws, h.hash).ok).toBe(true);
const floors = byteFloors(required.length);
+ writeFileSync(
+ join(ws, 'AGENTS.md'),
+ '⛔ **WRITE IT DOWN — SAME TURN, THROUGH THE BRAIN.**\n\n' +
+ '**Gate 7 — Write-back.** Before ending the turn, persist durable learning.\n',
+ );
writeFileSync(join(ws, 'SOUL.md'), pad('# Soul\n\nIdentity rendered from answers.\n', floors['SOUL.md'] + 200));
writeFileSync(join(ws, 'USER.md'), pad('# User\n\nTheir literal words are ground truth.\n', floors['USER.md'] + 100));
mkdirSync(join(ws, 'brain'), { recursive: true });
@@ -140,6 +145,7 @@ describe('verifyWorkspace — keyless pass', () => {
expect(check(res.checks, 'doctor_green')[0].ok).toBe(true);
expect(check(res.checks, 'token_sweep')[0].ok).toBe(true);
expect(check(res.checks, 'byte_floors')[0].ok).toBe(true);
+ expect(check(res.checks, 'writeback_contract')[0].ok).toBe(true);
expect(check(res.checks, 'secret_scan')[0].ok).toBe(true);
expect(check(res.checks, 'deny_globs')[0].ok).toBe(true);
expect(check(res.checks, 'repo_privacy')[0].ok).toBe(true); // local-only
@@ -470,6 +476,13 @@ describe('verifyWorkspace — workspace source registration (#4328)', () => {
const floors0 = byteFloors(0);
writeFileSync(join(ws2, 'SOUL.md'), pad('# Soul\n\nMinimal identity.\n', floors0['SOUL.md'] + 200));
writeFileSync(join(ws2, 'USER.md'), pad('# User\n\nMinimal user notes.\n', floors0['USER.md'] + 100));
+ // The writeback_contract check requires the integrated gate; this test
+ // exercises source resolution, not the contract audit.
+ writeFileSync(
+ join(ws2, 'AGENTS.md'),
+ '⛔ **WRITE IT DOWN — SAME TURN, THROUGH THE BRAIN.**\n\n' +
+ '**Gate 7 — Write-back.** Before ending the turn, persist durable learning.\n',
+ );
// No manifest at all — the pre-fix hardcoded 'workspace' fallback made
// put_page fail its sources FK on any brain that never registered it.
const resolved = await resolveVerifySourceId(e2, ws2);
diff --git a/test/sources-list-scalar-confinement.test.ts b/test/sources-list-scalar-confinement.test.ts
new file mode 100644
index 0000000000..ee6d109159
--- /dev/null
+++ b/test/sources-list-scalar-confinement.test.ts
@@ -0,0 +1,115 @@
+/**
+ * #4433 wave-L — sources_list confines remote scalar/no-grant callers too.
+ *
+ * Wave-g row-filtered the listing only for callers WITH a federated grant
+ * and deliberately left the scalar default-source floor unfiltered ("that
+ * caller may read any source by naming it"). The maintainer has since
+ * adopted the stricter posture: EVERY untrusted caller (anything not
+ * strictly `ctx.remote === false`) is confined through the canonical
+ * sourceScopeOpts ladder, matching the rest of the read-op surface —
+ * federated grant > scalar bound source > fail-closed `__all__`. A scalar
+ * caller's listing now shows exactly its resolved scope; enumerating the
+ * rest of the registry (id, name, page_count) requires naming a source,
+ * which is an audit-visible act rather than a bulk disclosure.
+ *
+ * The trusted local CLI (`ctx.remote === false`) keeps the full operator
+ * listing — sources management is its surface.
+ */
+import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { operations, type OperationContext } from '../src/core/operations.ts';
+
+let engine: PGLiteEngine;
+
+const op = operations.find((o) => o.name === 'sources_list')!;
+
+function ctxOf(overrides: Partial<OperationContext> = {}): OperationContext {
+ return {
+ engine: engine as unknown as OperationContext['engine'],
+ config: {} as OperationContext['config'],
+ logger: console as unknown as OperationContext['logger'],
+ dryRun: false,
+ remote: true,
+ ...overrides,
+ } as OperationContext;
+}
+
+function authOf(allowedSources?: string[]): OperationContext['auth'] {
+ return {
+ token: 'gbrain_at_test',
+ clientId: 'gbrain_cl_test',
+ clientName: 'token-b',
+ scopes: ['read'],
+ ...(allowedSources ? { allowedSources } : {}),
+ } as OperationContext['auth'];
+}
+
+async function listedIds(
+ ctx: OperationContext,
+ params: Record<string, unknown> = {},
+): Promise<string[]> {
+ const res = (await op.handler(ctx, params)) as { sources: Array<{ id: string }> };
+ return res.sources.map((s) => s.id);
+}
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ await engine.executeRaw(
+ `INSERT INTO sources (id, name) VALUES ('wiki', 'Wiki'), ('restricted', 'Restricted')
+ ON CONFLICT (id) DO NOTHING`,
+ );
+});
+
+afterAll(async () => {
+ await engine.disconnect();
+});
+
+describe('sources_list — scalar/no-grant remote confinement (#4433 wave-L)', () => {
+ test('remote scalar default-source floor sees ONLY its resolved source', async () => {
+ const ids = await listedIds(ctxOf({ remote: true, sourceId: 'default', auth: authOf() }));
+ expect(ids).toEqual(['default']);
+ });
+
+ test('remote scalar caller bound to a non-default source sees only that source', async () => {
+ const ids = await listedIds(ctxOf({ remote: true, sourceId: 'wiki', auth: authOf() }));
+ expect(ids).toEqual(['wiki']);
+ });
+
+ test('empty allowedSources falls to the scalar floor, never widens to all', async () => {
+ const ids = await listedIds(ctxOf({ remote: true, sourceId: 'default', auth: authOf([]) }));
+ expect(ids).toEqual(['default']);
+ });
+
+ test('legacy bearer shape (no auth object, transport sourceId) is confined too', async () => {
+ const ids = await listedIds(ctxOf({ remote: true, sourceId: 'default' }));
+ expect(ids).toEqual(['default']);
+ });
+
+ test("remote '__all__' sentinel fail-closes to an empty listing", async () => {
+ // '__all__' can never match a real source id (underscores are rejected
+ // at creation), so the ladder's literal pass-through yields zero rows
+ // rather than widening past the caller's scope.
+ const ids = await listedIds(ctxOf({ remote: true, sourceId: '__all__' }));
+ expect(ids).toEqual([]);
+ });
+
+ test('scalar confinement composes with include_archived (no resurrection outside scope)', async () => {
+ await engine.executeRaw(
+ `INSERT INTO sources (id, name, archived) VALUES
+ ('wiki-archived', 'WA', true), ('restricted-archived', 'RA', true)
+ ON CONFLICT (id) DO NOTHING`,
+ );
+ const ctx = ctxOf({ remote: true, sourceId: 'wiki-archived', auth: authOf() });
+ expect(await listedIds(ctx)).toEqual([]);
+ expect(await listedIds(ctx, { include_archived: true })).toEqual(['wiki-archived']);
+ });
+
+ test("trusted local CLI keeps the full operator listing (even via '__all__')", async () => {
+ const ids = await listedIds(ctxOf({ remote: false, sourceId: '__all__' }));
+ expect(ids).toContain('default');
+ expect(ids).toContain('wiki');
+ expect(ids).toContain('restricted');
+ });
+});
diff --git a/test/sources-list-scope.test.ts b/test/sources-list-scope.test.ts
index f651eefa86..85f574b117 100644
--- a/test/sources-list-scope.test.ts
+++ b/test/sources-list-scope.test.ts
@@ -8,18 +8,22 @@
* get_page/search/list_pages/resolve_slugs, with existence-of-a-source as
* the leak instead of pages.
*
- * The filter mirrors EXACTLY the boundary resolveRequestedScope enforces on
- * explicit per-call `source_id` reads — a non-empty ctx.auth.allowedSources
- * array — so the listing shows precisely the sources the caller could read.
- * Pins (row-filter, not field redaction):
+ * Wave-L (maintainer posture decision, supersedes the wave-g rationale that
+ * scalar callers keep the full listing "because they can read any source by
+ * naming it"): EVERY untrusted caller — anything not strictly
+ * `ctx.remote === false` — is confined through the canonical sourceScopeOpts
+ * ladder, matching the rest of the read-op surface. Pins (row-filter, not
+ * field redaction):
*
* 1. trusted local CLI stays UNSCOPED (sources management surface);
* 2. a remote federated grant sees only its granted rows;
- * 3. a remote scalar default-source floor (no allowedSources) keeps the
- * full listing — that caller may read any source by naming it, so
- * hiding rows would break discovery without adding any boundary;
- * 4. an empty allowedSources array behaves like no grant (same as
- * resolveRequestedScope's `allowed.length > 0` gate).
+ * 3. a remote scalar default-source floor (no allowedSources) sees only
+ * its resolved source — enumeration now requires naming a source;
+ * 4. an empty allowedSources array falls to the scalar floor (same as
+ * sourceScopeOpts' `allowed.length > 0` gate), never to "all".
+ *
+ * The deeper scalar/no-grant/`__all__` matrix lives in
+ * test/sources-list-scalar-confinement.test.ts.
*/
import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
@@ -101,21 +105,27 @@ describe('sources_list — caller source grant (#4433)', () => {
expect(ids).not.toContain('restricted');
});
- test('remote scalar default-source floor (no grant) keeps the full listing', async () => {
- // This caller may read any source by explicit source_id — the listing
- // must match its actual read reach, not invent a boundary reads lack.
+ test('remote scalar default-source floor (no grant) is confined to its source', async () => {
+ // Wave-L maintainer posture decision (supersedes the wave-g rationale
+ // that this caller keeps the full listing because it can read any source
+ // by naming it): scalar/no-grant remote callers are confined to their
+ // resolved scope like every other read op — bulk enumeration of the
+ // registry is gone; reading another source stays an explicit, named act.
const ids = await listedIds(ctxOf({ remote: true, sourceId: 'default', auth: authOf() }));
- expect(ids).toContain('default');
- expect(ids).toContain('wiki');
- expect(ids).toContain('restricted');
+ expect(ids).toEqual(['default']);
+ expect(ids).not.toContain('wiki');
+ expect(ids).not.toContain('restricted');
});
- test('empty allowedSources behaves like no grant (resolveRequestedScope parity)', async () => {
+ test('empty allowedSources falls to the scalar floor (sourceScopeOpts parity)', async () => {
+ // Wave-L: `[]` must not widen to "no filter" — it defers to ctx.sourceId,
+ // so the listing is the caller's single resolved source, never the table.
const ids = await listedIds(ctxOf({
remote: true,
sourceId: 'default',
auth: authOf([]),
}));
- expect(ids).toContain('restricted');
+ expect(ids).toEqual(['default']);
+ expect(ids).not.toContain('restricted');
});
});
diff --git a/test/sources-mcp.test.ts b/test/sources-mcp.test.ts
index f894593583..77dbd12db8 100644
--- a/test/sources-mcp.test.ts
+++ b/test/sources-mcp.test.ts
@@ -80,13 +80,14 @@ function findOp(name: string): Operation {
return op;
}
-function ctxRemote(scopes: string[]): OperationContext {
+function ctxRemote(scopes: string[], allowedSources?: string[]): OperationContext {
const auth: AuthInfo = {
token: 'gbrain_at_xxx',
clientId: 'gbrain_cl_test',
clientName: 'test-client',
scopes,
expiresAt: Math.floor(Date.now() / 1000) + 3600,
+ ...(allowedSources ? { allowedSources } : {}),
};
return {
engine: engine as any,
@@ -154,7 +155,9 @@ describe('sources_* handlers — happy path', () => {
url: 'https://github.com/example/repo',
});
const listOp = findOp('sources_list');
- const result = (await listOp.handler(ctxRemote(['read']), {})) as any;
+ // #4433 wave-L: sources_list confines remote callers to their scope,
+ // so the listing caller needs a grant covering the source it asserts on.
+ const result = (await listOp.handler(ctxRemote(['read'], ['mcp-list-test']), {})) as any;
expect(Array.isArray(result.sources)).toBe(true);
const found = result.sources.find((s: any) => s.id === 'mcp-list-test');
expect(found).toBeDefined();
@@ -339,7 +342,9 @@ describe('sources_list — include_archived honored (was silently leaking)', ()
);
const listOp = findOp('sources_list');
- const result = (await listOp.handler(ctxRemote(['read']), {})) as any;
+ // #4433 wave-L: grant covers the archived source, so the absence below
+ // pins the archived filter itself rather than the scope confinement.
+ const result = (await listOp.handler(ctxRemote(['read'], ['archived-src']), {})) as any;
const found = result.sources.find((s: any) => s.id === 'archived-src');
expect(found).toBeUndefined();
});
@@ -358,7 +363,7 @@ describe('sources_list — include_archived honored (was silently leaking)', ()
);
const listOp = findOp('sources_list');
- const result = (await listOp.handler(ctxRemote(['read']), {
+ const result = (await listOp.handler(ctxRemote(['read'], ['archived-included']), {
include_archived: true,
})) as any;
const found = result.sources.find((s: any) => s.id === 'archived-included');