Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(dream): oneshot synthesis validates against the resolved namespaces (#6160)
garrytan248a7cc5a56e
diff --git a/docs/architecture/key-files/core-minions-1.md b/docs/architecture/key-files/core-minions-1.mdindex 63a863bf38..649d3c5e8b 100644--- a/docs/architecture/key-files/core-minions-1.md+++ b/docs/architecture/key-files/core-minions-1.md@@ -52,7 +52,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/minions/handlers/subagent-audit.ts` — JSONL audit + heartbeat writer at `~/.gbrain/audit/subagent-jobs-YYYY-Www.jsonl`. Events: `submission` (one per submit) + `heartbeat` (per turn boundary: `llm_call_started | llm_call_completed | tool_called | tool_result | tool_failed`, plus the oneshot markers `oneshot_fallback | oneshot_timeout`; oneshot-path events carry `mode: 'oneshot'` and fallback events a `reason` — both rendered by `gbrain agent logs`). Never logs prompts or tool inputs. `readSubagentAuditForJob(jobId, {sinceIso})` is the readback for `gbrain agent logs`.-- `src/core/minions/handlers/subagent-oneshot.ts` — oneshot synthesis runner. ONE rate-leased tool-less `gateway.chat` call (static `ONESHOT_SYSTEM` JSON contract rides the prompt-cache prefix; sub-budget min(`ai.chat.per_turn_timeout_ms`, time left/4) with a job deadline, else 5 min, passed as the call's `timeoutMs` so the gateway's 300 s default backstop cannot cut it short → `fallback_reason: 'oneshot_timeout'`), then all-or-nothing validation BEFORE any write: JSON contract (`parseOneshotResponse`, ≤12 pages), slug grammar + `allowed_slug_prefixes` + reflections/originals task shape + the exact `oneshot_slug_suffix` (the idempotency boundary, enforced structurally), exact-match wikilink rule against existing ∪ in-batch slugs (`extractWikilinkTargets`; cold-brain relaxation: <5 pages AND no manifest accepts syntactic presence). Writes go through the SAME `brain_put_page` ToolDef the loop uses (fences/side-effects/provenance identical) with `deferEmbeds`, bracketed by standard ledger rows under invocation-scoped ids `oneshot-<inv8>-p<i>`; a post-batch `autoLinkWrittenPage` pass materializes in-batch forward wikilink edges. Ledger-first crash recovery: any prior oneshot rows → finalize from the ledger, never re-call the nondeterministic model. Transcript rows persist ONLY after success (a failed attempt is never replayable as a completed result). Every failure shape returns `{kind:'fallback', reason}` and the same job falls through to the agentic loop. Pinned by `test/minions/subagent-oneshot.test.ts` + the oneshot describes in `test/subagent-handler.test.ts` and `test/e2e/dream-synthesize-pglite.test.ts`. `ONESHOT_SYSTEM` spells out JSON string escaping (quotes, backslashes, line breaks). A parse failure whose reported output usage reaches the requested cap falls back as `length` even when the provider normalized the stop to `end`/`other`; below-cap malformed output stays `unparseable`, and valid JSON at the cap proceeds normally.+- `src/core/minions/handlers/subagent-oneshot.ts` — oneshot synthesis runner. ONE rate-leased tool-less `gateway.chat` call (static `ONESHOT_SYSTEM` JSON contract rides the prompt-cache prefix; sub-budget min(`ai.chat.per_turn_timeout_ms`, time left/4) with a job deadline, else 5 min, passed as the call's `timeoutMs` so the gateway's 300 s default backstop cannot cut it short → `fallback_reason: 'oneshot_timeout'`), then all-or-nothing validation BEFORE any write: JSON contract (`parseOneshotResponse`, ≤12 pages), slug grammar + `allowed_slug_prefixes` + reflections/originals task shape + the exact `oneshot_slug_suffix` (the idempotency boundary, enforced structurally), exact-match wikilink rule against existing ∪ in-batch slugs (`extractWikilinkTargets`; cold-brain relaxation: <5 pages AND no manifest accepts syntactic presence). Writes go through the SAME `brain_put_page` ToolDef the loop uses (fences/side-effects/provenance identical) with `deferEmbeds`, bracketed by standard ledger rows under invocation-scoped ids `oneshot-<inv8>-p<i>`; a post-batch `autoLinkWrittenPage` pass materializes in-batch forward wikilink edges. Ledger-first crash recovery: any prior oneshot rows → finalize from the ledger, never re-call the nondeterministic model. Transcript rows persist ONLY after success (a failed attempt is never replayable as a completed result). Every failure shape returns `{kind:'fallback', reason}` and the same job falls through to the agentic loop. Pinned by `test/minions/subagent-oneshot.test.ts` + the oneshot describes in `test/subagent-handler.test.ts` and `test/e2e/dream-synthesize-pglite.test.ts`. `ONESHOT_SYSTEM` spells out JSON string escaping (quotes, backslashes, line breaks). A parse failure whose reported output usage reaches the requested cap falls back as `length` even when the provider normalized the stop to `end`/`other`; below-cap malformed output stays `unparseable`, and valid JSON at the cap proceeds normally. #6160: the task shapes come from `data.oneshot_task_prefixes` (the cycle's resolved reflections and originals namespaces, set by `cycle/synthesize.ts`); jobs queued by older builds derive them from allow-list entries whose path has a `personal/reflections/` or `originals/` segment, root-level ones included.- `src/core/minions/handlers/subagent-persistence.ts` — subagent transcript + tool-execution persistence (pure peel from subagent.ts): loadPriorMessages/Tools/ToolsV2, persistMessage, persistToolExecPending/Complete/Failed (all `$N::text::jsonb` discipline), plus `finalizeWriteAccounting`: derives pages_attempted/written/failed from the job's put_page ledger rows (settled only — pending counts toward neither), merges them into every SubagentResult, and throws UnrecoverableError on require_writes jobs with no settled successful write, including zero-attempt clean finishes, unless `isLegitimateZeroWrite` accepts the zero-attempt `end_turn` finish: the oneshot explicit skip (`oneshot_skipped: true` on a `synth_mode_used: 'oneshot'` result) or, when the submitter set `allow_clean_zero_writes` (the patterns phase), a run with at least one completed tool execution in its ledger — all-attempted-failed, dirty stops, prose-only finishes and runs whose only tools failed still dead-letter (the oneshot runner banks each skip as a `oneshot-<inv8>-skip` ledger row before its transcript, so a retried job's ledger-first recovery completes as the same skip without a model call); `scopeToolUseIdPrefix` narrows the scan to the oneshot invocation family. Fresh `brain_put_page` rejects are normalized by `src/core/minions/tools/put-page-result.ts` before ledger settlement; accounting reclassifies rejected historical completed envelopes (including JSON strings) without changing the stored rows. Unchanged-page saves and persisted pages whose embedding failed still count as writes.diff --git a/src/core/cycle/synthesize.ts b/src/core/cycle/synthesize.tsindex d50114b6de..2301dcf1f8 100644--- a/src/core/cycle/synthesize.ts+++ b/src/core/cycle/synthesize.ts@@ -909,6 +909,8 @@ async function runPhaseSynthesizeInner(oneshot_slug_suffix: chunks.length > 1? `${t.contentHash.slice(0, 6)}-c${i}`: t.contentHash.slice(0, 6),+ // #6160: the task shapes oneshot validation enforces, from the resolved namespaces.+ oneshot_task_prefixes: [config.reflectionsPrefix, config.originalsPrefix],require_writes: true,// #1586: scope every child tool call to the cycle's resolved source// so put_page writes land there instead of the hardcoded 'default'.diff --git a/src/core/minions/handlers/subagent-oneshot.ts b/src/core/minions/handlers/subagent-oneshot.tsindex 901698d0f1..9cfeda7915 100644--- a/src/core/minions/handlers/subagent-oneshot.ts+++ b/src/core/minions/handlers/subagent-oneshot.ts@@ -468,9 +468,11 @@ export async function runSubagentOneshot(args: OneshotArgs): Promise<OneshotOutc// ── Validate ALL pages before ANY write ─────────────────────────────────const prefixes = data.allowed_slug_prefixes ?? [];- // CDX-9 task shapes: reflections/originals sub-trees of the allow-list.- const taskShapePrefixes = prefixes- .filter(p => p.includes('/personal/reflections/') || p.includes('/originals/'))+ // CDX-9 task shapes: the reflections/originals namespaces. #6160: the cycle+ // passes its resolved namespaces; jobs queued by older builds derive them+ // from the allow-list, root-level namespaces included.+ const taskShapePrefixes = (data.oneshot_task_prefixes ?? prefixes+ .filter(p => /(?:^|\/)(?:personal\/reflections|originals)\//.test(p))).map(p => (p.endsWith('/*') ? p.slice(0, -1) : p.endsWith('/') ? p : `${p}/`));const inBatch = new Set(parsed.pages.map(p => p.slug));// Duplicate slugs inside one batch would make the second write silentlydiff --git a/src/core/minions/types.ts b/src/core/minions/types.tsindex 82ce6761cb..947c9210fb 100644--- a/src/core/minions/types.ts+++ b/src/core/minions/types.ts@@ -605,6 +605,14 @@ export interface SubagentHandlerData {* discipline. Set by the dream fan-out alongside `mode`.*/oneshot_slug_suffix?: string;+ /**+ * #6160 — the namespaces a oneshot synthesis child may write (the cycle's+ * resolved reflections and originals prefixes). Oneshot validation uses+ * them as its task shapes instead of guessing from the allow-list's+ * spelling, so root-level and custom namespaces validate. Absent on jobs+ * queued by older builds, which keep the allow-list derivation.+ */+ oneshot_task_prefixes?: string[];/*** v0.41 Approach C: opt out of the auto-generated tool-usage preamble* that `buildSystemPrompt()` splices into `system`. Default behaviordiff --git a/test/minions/subagent-oneshot.test.ts b/test/minions/subagent-oneshot.test.tsindex 2872258400..b44dac8133 100644--- a/test/minions/subagent-oneshot.test.ts+++ b/test/minions/subagent-oneshot.test.ts@@ -346,6 +346,28 @@ describe('runSubagentOneshot', () => {expect(outcome).toEqual({ kind: 'fallback', reason: 'bad_slug', tokens: FB_TOKENS });});+ // #6160: root-level and custom namespaces are task shapes too.+ test('a root-level originals/ namespace from the allow-list validates (legacy job data)', async () => {+ const data: SubagentHandlerData = { ...DATA, allowed_slug_prefixes: [...PREFIXES, 'personal/reflections/*', 'originals/*'] };+ const ctx = await makeCtx(data);+ const slug = `originals/2026-10-04-some-idea-${SUFFIX}`;+ const resp = JSON.stringify({ pages: [{ slug, body: `An idea. [[${GOOD_SLUG_A}]]` }], skipped: false });+ const outcome = await runSubagentOneshot(makeArgs(ctx, data, resp));+ expect(outcome.kind).toBe('done');+ expect(await engine.getPage(slug)).not.toBeNull();+ });++ test('explicit oneshot_task_prefixes admit a custom namespace and still refuse people pages', async () => {+ const data: SubagentHandlerData = { ...DATA, allowed_slug_prefixes: [...PREFIXES, 'ideas/*'], oneshot_task_prefixes: ['ideas', 'wiki/personal/reflections'] };+ const ok = `ideas/2026-10-04-custom-${SUFFIX}`;+ const okCtx = await makeCtx(data);+ expect((await runSubagentOneshot(makeArgs(okCtx, data, JSON.stringify({ pages: [{ slug: ok, body: `x [[${GOOD_SLUG_A}]]` }], skipped: false })))).kind).toBe('done');+ const second = { ...data, prompt: `${data.prompt} (second job)` };+ const badCtx = await makeCtx(second);+ const bad = await runSubagentOneshot(makeArgs(badCtx, second, JSON.stringify({ pages: [{ slug: 'wiki/people/alice-example', body: `bio [[${GOOD_SLUG_A}]]` }], skipped: false })));+ expect(bad).toEqual({ kind: 'fallback', reason: 'bad_slug', tokens: FB_TOKENS });+ });+test('zero wikilinks → no_wikilink fallback', async () => {const ctx = await makeCtx(DATA);const resp = JSON.stringify({