Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix: dream and maintenance follow-ups
garrytan7d80d9380140
diff --git a/src/core/ai/invocation-guard.ts b/src/core/ai/invocation-guard.tsindex 27b749423b..8ca21d7b74 100644--- a/src/core/ai/invocation-guard.ts+++ b/src/core/ai/invocation-guard.ts@@ -34,7 +34,8 @@ export function withAIInvocationGuard<T>(guard: AIInvocationGuard, run: () => Prconst outer = await parent(call);let inner: AIInvocationPermit;try { inner = await guard(call); }- catch (error) { await outer.settle(null); throw error; }+ // #9086: nothing was dispatched, so release the outer hold at zero usage instead of keeping it as unknown.+ catch (error) { await outer.settle({ inputTokens: 0, outputTokens: 0 }); throw error; }return { settle: async usage => { await outer.settle(usage); await inner.settle(usage); } };}, run);}diff --git a/src/core/ai/providers/claude-cli-language-model.ts b/src/core/ai/providers/claude-cli-language-model.tsindex b6fd550c9c..28fd96ce9a 100644--- a/src/core/ai/providers/claude-cli-language-model.ts+++ b/src/core/ai/providers/claude-cli-language-model.ts@@ -603,6 +603,9 @@ function resolveEntryInput(e: Record<string, unknown>): unknown {return flat;}+/** The model's native tool-call elements, which this protocol never asks for and never dispatches. */+const NATIVE_TOOL_MARKUP = /<(?:antml:)?(?:invoke\s+name=|function_calls>)/;+/*** Locate and parse the `<use_tools>...</use_tools>` block in the assistant's* raw text response. Returns the parsed tool calls plus whatever prose@@ -614,6 +617,8 @@ function extractToolCalls(raw: string): {toolCalls: ParsedToolCall[];beforeText: string;afterText: string;+ /** No block parsed, but the reply holds the model's native tool-call markup (#9085). */+ nativeMarkup?: boolean;} {const openTag = '<use_tools>';const closeTag = '</use_tools>';@@ -662,7 +667,7 @@ function extractToolCalls(raw: string): {if (firstError !== null) {process.stderr.write(`[claude-cli] <use_tools> block failed to parse — tool call discarded: ${firstError}\n`);}- return { toolCalls: [], beforeText: raw.trim(), afterText: '' };+ return { toolCalls: [], beforeText: raw.trim(), afterText: '', nativeMarkup: NATIVE_TOOL_MARKUP.test(raw) };}const beforeText = raw.slice(0, openIdx).trim();@@ -778,7 +783,13 @@ export class ClaudeCliLanguageModel implements LanguageModelV2 {warnings: [],};}- const { toolCalls, beforeText, afterText } = extractToolCalls(answer.text);+ const { toolCalls, beforeText, afterText, nativeMarkup } = extractToolCalls(answer.text);+ // #9085: a turn that called tools in the model's native markup is not a clean answer; read as prose it ends the+ // loop with no writes. Fail the turn (a transient error, so the job's attempt limit bounds the retries).+ if (nativeMarkup && options.tools?.length) {+ process.stderr.write('[claude-cli] reply carried tool-call markup with no parsable <use_tools> block — turn failed for retry\n');+ throw new Error('claude-cli reply carried tool-call markup with no parsable <use_tools> block; the tool calls were not run');+ }const content: LanguageModelV2Content[] = [];if (beforeText) content.push({ type: 'text', text: beforeText });diff --git a/src/core/by-mention.ts b/src/core/by-mention.tsindex b4e291fe99..ca5fd921c8 100644--- a/src/core/by-mention.ts+++ b/src/core/by-mention.ts@@ -41,6 +41,8 @@ import { isGenericEntityToken } from './entity-name-quality.ts';import { ALWAYS_LINKABLE_TYPES, linkableTypesFor, loadSourcePack, readMentionPolicy, type MentionPolicy, type PackTypes } from './mentions/policy.ts';import { siblingVerdict, type SiblingCandidate } from './mentions/siblings.ts';import { isShortCode } from './mentions/short-codes.ts';+import { bodyBlocks } from './page-body/segment-blocks.ts';+import { OperationError } from './ops/contract.ts';/*** The four types that are always linkable, whatever the schema pack says. The@@ -910,6 +912,22 @@ export interface StaleMention {link_type: string;}+/**+ * Mentions of a segmented page: the title, then each stored block, as the mention pass reads a body it cannot reuse+ * runs for. Reads only. Null when a block is too long for any block reader (the page is left out of the scan).+ */+async function segmentedBodyMentions(engine: BrainEngine, page: { id: number; slug: string; source_id: string; title: string | null },+ gazetteer: Gazetteer, opts: FindMentionsOpts): Promise<Mention[] | null> {+ const found = findMentionedEntities(page.title ?? '', gazetteer, opts);+ try {+ for await (const block of bodyBlocks(engine, page, { separator: '\n\n' })) found.push(...findMentionedEntities(block.text, gazetteer, opts));+ } catch (error) {+ if (error instanceof OperationError && error.canonicalCode === 'page_body_segmented') return null;+ throw error;+ }+ return found;+}+export interface StaleMentionsScan {/** Live pages carrying at least one `link_source='mentions'` row. */totalPagesWithMentions: number;@@ -1000,10 +1018,10 @@ export async function scanStaleMentions()`;const bodies = await engine.executeRaw<{- id: number; slug: string; source_id: string | null; body: string;+ id: number; slug: string; source_id: string | null; body: string; title: string | null; body_storage: string | null;}>(`${scannedCte}- SELECT p.id, p.slug, p.source_id,+ SELECT p.id, p.slug, p.source_id, p.title, p.body_storage,COALESCE(p.title, '') || E'\n\n' || COALESCE(p.compiled_truth, '') || E'\n\n' || COALESCE(p.timeline, '') AS bodyFROM pages pJOIN scanned s ON s.id = p.id@@ -1043,13 +1061,13 @@ export async function scanStaleMentions(if (!stored || stored.length === 0) continue;const fromSourceId = page.source_id ?? 'default';- const produced = new Set(- findMentionedEntities(page.body, gazetteer, {- fromSlug: page.slug,- fromSourceId,- allowCrossSource,- }).map(m => `${m.source_id}::${m.slug}`),- );+ const opts = { fromSlug: page.slug, fromSourceId, allowCrossSource };+ // #9121: a segmented page's body columns are empty; scan its stored blocks (read-only) or skip a page no block reader can read.+ const mentions = page.body_storage === 'segmented'+ ? await segmentedBodyMentions(engine, { id: page.id, slug: page.slug, source_id: fromSourceId, title: page.title }, gazetteer, opts)+ : findMentionedEntities(page.body, gazetteer, opts);+ if (!mentions) continue;+ const produced = new Set(mentions.map(m => `${m.source_id}::${m.slug}`));for (const row of stored) {const key = `${row.to_source_id ?? 'default'}::${row.to_slug}`;diff --git a/src/core/generations/managed.ts b/src/core/generations/managed.tsindex c5cba546aa..7a8db3e187 100644--- a/src/core/generations/managed.ts+++ b/src/core/generations/managed.ts@@ -130,7 +130,7 @@ export async function recordActivation(tx: BrainEngine, intent: ActivationPlanInawait tx.executeRaw(`INSERT INTO derived_generation_activations (id, source_id, kind, owner_key, expected_generation, input_pin, item_set_hash, state, members)VALUES ($1,$2,$3,$4,$5,$6,$7,'pending',$8::text::jsonb) ON CONFLICT (id) DO NOTHING`,[intent.activationId, intent.key.sourceId, intent.key.kind, intent.key.ownerKey, intent.expectedGeneration, intent.input?.pin ?? null, intent.setHash,- JSON.stringify(intent.members.map(member => ({ slug: member.slug, action: member.action, identity: member.identity })))]);+ JSON.stringify(intent.members.map(member => ({ slug: member.slug, action: member.action, identity: member.identity, before: member.before })))]);}const memberFix = (sourceId: string, kind: string) => readFix('Lists pending generation members and orphan candidates, read-only.',diff --git a/src/core/minions/handlers/extract.ts b/src/core/minions/handlers/extract.tsindex 443c1830cf..330e57ab67 100644--- a/src/core/minions/handlers/extract.ts+++ b/src/core/minions/handlers/extract.ts@@ -8,6 +8,7 @@ import { MinionQueue } from '../queue.ts';export function makeExtractHandler(engine: BrainEngine): MinionHandler {return async (job) => {const { runExtractCore, extractStaleFromDB, STALE_TIME_BUDGET_MS } = await import('../../../commands/extract.ts');+ const { staleExtractionCounts } = await import('../../extraction-lag.ts');// #2849: stale mode — the durable follow-up for extraction deferred by// performSync's size gate (totalChanges > 100). Runs the same DB-source// watermark sweep as `gbrain extract --stale`, scoped to the source the@@ -26,8 +27,11 @@ export function makeExtractHandler(engine: BrainEngine): MinionHandler {// Internal 30-min budget hit with work remaining → chain a// continuation job so a very large deferred backlog converges without// waiting for the next sync. Forward-progress guard (pagesProcessed >- // 0) prevents an infinite chain if the sweep can't advance.- if (!job.data.dryRun && r.staleRemaining > 0 && (r.pagesProcessed > 0 || (r.mentions?.pages ?? 0) > 0)) {+ // 0) prevents an infinite chain if the sweep can't advance. #8672: the raw+ // stale count includes attendance-blocked and held pages, which no rerun+ // clears, so a sweep that left only those chains nothing.+ if (!job.data.dryRun && r.staleRemaining > 0 && (r.pagesProcessed > 0 || (r.mentions?.pages ?? 0) > 0)+ && !(await staleExtractionCounts(engine, sourceIdFilter)).complete) {try {const queue = new MinionQueue(engine);// NO maxWaiting: with an unscoped (NULL-sourceId) payload thediff --git a/src/core/minions/spend-authorization.ts b/src/core/minions/spend-authorization.tsindex 3ab4a5b874..54cd84e5ec 100644--- a/src/core/minions/spend-authorization.ts+++ b/src/core/minions/spend-authorization.ts@@ -111,7 +111,7 @@ const usd = (c: number) => Math.round(c) / 100;/** A group's amounts in USD, for envelopes, `jobs get` and `jobs list --group`. */export function groupAmounts(record: SpendAuthorization, spend: GroupSpend) {- const spent = spend.committedCents + spend.overdueCents;+ const held = spend.committedCents + spend.overdueCents + spend.liveCents;return {group_id: record.group_id,cap_usd: record.cap_usd,@@ -119,7 +119,7 @@ export function groupAmounts(record: SpendAuthorization, spend: GroupSpend) {spent_usd: usd(spend.committedCents),overdue_usd: usd(spend.overdueCents),reserved_usd: usd(spend.liveCents + spend.overdueCents),- remaining_usd: record.cap_usd === null ? null : usd(Math.max(0, cents(record.cap_usd) - spent)),+ remaining_usd: record.cap_usd === null ? null : usd(Math.max(0, cents(record.cap_usd) - held)),};}diff --git a/src/core/persistence/atom-maintenance.ts b/src/core/persistence/atom-maintenance.tsindex b6ff9a2508..0e3965916d 100644--- a/src/core/persistence/atom-maintenance.ts+++ b/src/core/persistence/atom-maintenance.ts@@ -338,7 +338,9 @@ export async function publishManagedAtomGeneration(engine: BrainEngine, session:approved: generation.approved, release: generation.release }, { retiredBy: ATOM_RETIRED_BY_REEXTRACT, scope: generation.approved ? null : claim.runKey, locator: generation.locator ?? (origin.kind === 'transcript' ? origin.locator : null) });if (plan.kind === 'held') return { state: 'held', reason: plan.outcome.reason, holdId: plan.outcome.holdId, receipts: [] };if (plan.kind === 'unchanged') return { state: 'unchanged', receipts: generation.approved ? [] : await publishManagedAtoms(engine, session, origin, []) };- const runKey = generation.approved ? digest(['managed-atoms-approved', plan.intent.activationId]) : claim.runKey;+ // #9079: a release is its own run; under the drain's key its completion collides with the drain's for this input.+ const runKey = generation.approved ? digest(['managed-atoms-approved', plan.intent.activationId])+ : generation.release ? digest(['managed-atoms-release', plan.intent.activationId]) : claim.runKey;const advance = !generation.approved && claim.checkpointKey ? { checkpointKey: claim.checkpointKey, expectedCheckpoint: claim.expectedCheckpoint ?? null } : {};const { activationId } = plan.intent;const bySlug = new Map(atoms.map(atom => [atom.slug, atom]));diff --git a/src/core/repair/agent-session-facts.ts b/src/core/repair/agent-session-facts.tsindex 1aff58ac22..5a5eb135e0 100644--- a/src/core/repair/agent-session-facts.ts+++ b/src/core/repair/agent-session-facts.ts@@ -63,7 +63,7 @@ import { readSessionSource } from '../context/corpus-source.ts';import { parseCorpusTurns } from '../context/corpus-turns.ts';import { DETECTED_PRINCIPAL, readSpeakerSidecar, speakerContextNote } from '../context/session-speaker.ts';import { stripPastedContent } from '../transcripts/pasted-content.ts';-import { isSegmentedPage } from '../page-body/page-shape.ts';+import { wholeBodySnapshot } from '../persistence/segmented-apply.ts';import { shellQuote } from '../shell-quote.ts';import { pruneDir } from '../sync.ts';import { CAPTURE_LANES, captureSessionId } from './captured-facts.ts';@@ -495,12 +495,13 @@ export async function prepareAgentSessionFactsWrite(engine: BrainEngine, row: Wr/*** Fenced facts: set `attributed_to: other` and append the note on each still-matching, still user-attributed active* fence row and publish the page once, bound to the revision read; the canonical projection rewrites the rows in- * place. Returns the facts that now read back as `other`. A page stored in segments is not rewritten.+ * place. Returns the facts that now read back as `other`. A page stored in segments (#9027) is read back whole, as+ * every fence write through the put path reads it, and one over 24 MiB declines `page_body_segmented`, its rows kept.*/async function rewriteFencedFacts(ctx: Parameters<RepairHandler['apply']>[0], item: RepairItem, page: ApprovedPage, facts: AgentSessionFactCandidate[]): Promise<number[]> {const engine = ctx.engine;- const snapshot = await engine.readPageSnapshot(page.slug, { sourceId: page.source_id });- if (!snapshot || isSegmentedPage(snapshot.page)) return [];+ const snapshot = await wholeBodySnapshot(engine, await engine.readPageSnapshot(page.slug, { sourceId: page.source_id }), 'repair agent-session-facts');+ if (!snapshot) return [];const rows = await engine.executeRaw<{ id: number | string; fact: string; row_num: number }>('SELECT id, fact, row_num FROM facts WHERE source_id=$1 AND id=ANY($2::bigint[]) AND expired_at IS NULL', [page.source_id, facts.map(f => f.id)]);let body = snapshot.page.compiled_truth ?? '';@@ -526,12 +527,11 @@ async function rewriteFencedFacts(ctx: Parameters<RepairHandler['apply']>[0], it/*** Takes: a take the page's takes fence holds (same row and claim, active) is struck there by one revision-bound* `put_page` (the projection sets `active = false`); the rest are retired in the database. A page stored in- * segments is not rewritten. Returns the retired takes.+ * segments is read back whole, as rewriteFencedFacts reads it. Returns the retired takes.*/async function retireTakes(ctx: Parameters<RepairHandler['apply']>[0], item: RepairItem, page: ApprovedPage, hash: string, takes: AgentSessionTake[]): Promise<number[]> {const engine = ctx.engine;- const snapshot = await engine.readPageSnapshot(page.slug, { sourceId: page.source_id });- if (snapshot && isSegmentedPage(snapshot.page)) return [];+ const snapshot = await wholeBodySnapshot(engine, await engine.readPageSnapshot(page.slug, { sourceId: page.source_id }), 'repair agent-session-facts');const body = snapshot ? serializePageToMarkdown(snapshot.page, snapshot.tags) : '';const fence = parseTakesFence(body);const fenced = takes.filter(t => fence.takes.some(row => row.rowNum === t.row_num && row.claim.trim() === t.claim.trim() && row.active));diff --git a/test/claude-cli-stop-reason.test.ts b/test/claude-cli-stop-reason.test.tsindex b91ec5ec49..ab662622fc 100644--- a/test/claude-cli-stop-reason.test.ts+++ b/test/claude-cli-stop-reason.test.ts@@ -77,3 +77,32 @@ describe('claude-cli replays earlier tool calls with their arguments (#6236)', (expect(sent).not.toContain('[object Object]');});});++describe('claude-cli native tool-call markup without a <use_tools> block (#9085)', () => {+ const generate = (result: string) => {+ writeFileSync(responsePath, JSON.stringify({+ type: 'result', subtype: 'success', is_error: false, result, stop_reason: 'end_turn',+ session_id: 's', num_turns: 1, usage: { input_tokens: 1, output_tokens: 1 },+ }));+ return withEnv({ GBRAIN_CLAUDE_CLI_BIN: stubBin }, async () => {+ const { ClaudeCliLanguageModel } = await import('../src/core/ai/providers/claude-cli-language-model.ts');+ return new ClaudeCliLanguageModel('claude-sonnet-4-6').doGenerate({+ prompt: [{ role: 'user', content: [{ type: 'text', text: 'hi' }] }],+ tools: [{ type: 'function', name: 'put_page', description: '', inputSchema: { type: 'object', properties: {} } }],+ } as LanguageModelV2CallOptions);+ });+ };++ test('native invoke markup and an orphan </use_tools> fail the turn instead of ending it clean', async () => {+ const reply = 'Writing the pattern page now.\n<invoke name="put_page">\n<parameter name="slug">patterns/acme-example</parameter>\n</invoke>\n</use_tools>';+ const error = await generate(reply).then(() => null, (e: unknown) => e);+ expect(String(error)).toContain('no parsable <use_tools> block');+ const { normalizeAIError, AITransientError } = await import('../src/core/ai/errors.ts');+ expect(normalizeAIError(error)).toBeInstanceOf(AITransientError);+ });++ test('prose that only names the protocol still ends clean', async () => {+ const out = await generate('No pattern meets the evidence bar, so I am not calling put_page or writing a <use_tools> block.');+ expect(out.finishReason).toBe('stop');+ });+});diff --git a/test/doctor-stale-mentions-segmented-9121.test.ts b/test/doctor-stale-mentions-segmented-9121.test.tsnew file mode 100644index 0000000000..c16e9c823d--- /dev/null+++ b/test/doctor-stale-mentions-segmented-9121.test.ts@@ -0,0 +1,51 @@+/**+ * #9121: doctor's stale_mentions scan read the body columns of a page stored in segments, which are empty, so every+ * mentions link on a large page read as stale and the hint told the user to unlink correct links.+ */+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import type { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { importFromContent } from '../src/core/import-file.ts';+import { scanStaleMentions } from '../src/core/by-mention.ts';+import { mentionBrain, page, resetMentionBrain } from './helpers/mention-brain.ts';++const MB = 1024 * 1024;+const LARGE = 'notes/large-log';++function largeNote(mention: string): string {+ const filler = Array.from({ length: Math.ceil((1.5 * MB) / 48) }, (_, i) => `Line ${String(i).padStart(8, '0')} of the running log.`).join('\n\n');+ return `---\ntitle: Large log\ntype: note\n---\n${filler}\n\n${mention}\n`;+}++async function linkMention(engine: PGLiteEngine, from: string, to: string): Promise<void> {+ await engine.addLinksBatch([{ from_slug: from, to_slug: to, link_type: 'mentions', link_source: 'mentions', link_kind: 'plain' }]);+}++describe('stale_mentions on a segmented page (#9121)', () => {+ let engine: PGLiteEngine;+ beforeAll(async () => { engine = await mentionBrain(); }, 120_000);+ afterAll(async () => { await engine.disconnect(); });+ beforeEach(async () => {+ await resetMentionBrain(engine);+ await engine.setConfig('pages.segmented_storage', 'on');+ await page(engine, 'companies/acme-example', 'company', 'Acme Example', 'Acme Example is a company.');+ await page(engine, 'companies/globex-example', 'company', 'Globex Example', 'Globex Example is a company.');+ }, 120_000);++ test('a segmented page whose body still mentions the target reports no stale link', async () => {+ expect((await importFromContent(engine, LARGE, largeNote('Signed with Acme Example today.'), { sourceId: 'default', noEmbed: true })).status).toBe('imported');+ expect((await engine.executeRaw<{ body_storage: string }>('SELECT body_storage FROM pages WHERE slug=$1', [LARGE]))[0]!.body_storage).toBe('segmented');+ await linkMention(engine, LARGE, 'companies/acme-example');+ const scan = await scanStaleMentions(engine);+ expect(scan.linksScanned).toBe(1);+ expect(scan.staleLinks).toBe(0);+ }, 300_000);++ test('a segmented page that no longer mentions the target still reports that link stale', async () => {+ expect((await importFromContent(engine, LARGE, largeNote('Signed with Acme Example today.'), { sourceId: 'default', noEmbed: true })).status).toBe('imported');+ await linkMention(engine, LARGE, 'companies/acme-example');+ await linkMention(engine, LARGE, 'companies/globex-example');+ const scan = await scanStaleMentions(engine);+ expect(scan.staleLinks).toBe(1);+ expect(scan.examples).toEqual([expect.objectContaining({ from: LARGE, to: 'companies/globex-example' })]);+ }, 300_000);+});diff --git a/test/e2e/spend-nested-refusal-9086-postgres.test.ts b/test/e2e/spend-nested-refusal-9086-postgres.test.tsnew file mode 100644index 0000000000..da4cffb841--- /dev/null+++ b/test/e2e/spend-nested-refusal-9086-postgres.test.ts@@ -0,0 +1,3 @@+import { registerPostgresTests } from '../helpers/test-backends.ts';++await registerPostgresTests(() => import('../spend-nested-refusal-9086.test.ts'));diff --git a/test/extract-continuation-blocked-8672.test.ts b/test/extract-continuation-blocked-8672.test.tsnew file mode 100644index 0000000000..89a5629b3f--- /dev/null+++ b/test/extract-continuation-blocked-8672.test.ts@@ -0,0 +1,36 @@+/**+ * #8672: a stale extract job that cleared every page extraction can clear chained one more job when only+ * attendance-blocked pages were left, because it read the raw stale count; that child rescanned and did nothing.+ */+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import type { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { makeExtractHandler } from '../src/core/minions/handlers/extract.ts';+import { mentionBrain, page, resetMentionBrain } from './helpers/mention-brain.ts';++const continuations = async (engine: PGLiteEngine) => Number((await engine.executeRaw<{ n: number }>(+ `SELECT count(*)::int AS n FROM minion_jobs WHERE name = 'extract' AND data ? 'continuation_of'`))[0]!.n);++async function runStaleJob(engine: PGLiteEngine) {+ return makeExtractHandler(engine)({ id: 1, data: { stale: true } } as never) as Promise<Record<string, unknown>>;+}++describe('stale extract continuation (#8672)', () => {+ let engine: PGLiteEngine;+ beforeAll(async () => { engine = await mentionBrain(); }, 120_000);+ afterAll(async () => { await engine.disconnect(); });+ beforeEach(async () => {+ await resetMentionBrain(engine);+ await engine.executeRaw('DELETE FROM minion_jobs');+ await page(engine, 'people/alice-example', 'person', 'Alice Example', 'Alice Example fixture.');+ await page(engine, 'notes/plan', 'note', 'Plan', 'See [[people/alice-example]] about the plan.');+ for (const n of [1, 2, 3]) await page(engine, `meetings/sync-${n}`, 'meeting', `Sync ${n}`, 'Attendees: [[people/bob-example]]');+ }, 120_000);++ test('a sweep that leaves only attendance-blocked pages queues no continuation', async () => {+ await engine.executeRaw("UPDATE pages SET links_attendance_blocked_revision = knowledge_revision WHERE slug LIKE 'meetings/%'");+ const r = await runStaleJob(engine);+ expect(Number(r.pagesProcessed)).toBeGreaterThan(0);+ expect(Number(r.staleRemaining)).toBeGreaterThan(0);+ expect(await continuations(engine)).toBe(0);+ }, 300_000);+});diff --git a/test/managed-atom-release-resume-9079-9275.test.ts b/test/managed-atom-release-resume-9079-9275.test.tsnew file mode 100644index 0000000000..0c76c31a28--- /dev/null+++ b/test/managed-atom-release-resume-9079-9275.test.ts@@ -0,0 +1,117 @@+/**+ * Managed atom generations, two leftovers of GBRA-161 PR 1b.+ *+ * #9079: `gbrain repair generations --mode release-held` published a released atom result under the drain's run key, so+ * its completion request collided with the completion the drain had already journaled for the same input and every+ * release ended idempotency_conflict; the held result could never publish.+ * #9275: an activation recorded its members without the identity each overwrite replaces, so a member interrupted after+ * the activation was read back with no before-identity, judged a person's edit (kept_edited) and settled; the previous+ * atom body stayed live and the new extraction was dropped.+ * Seams: the phase's _pages / _chat inputs (no paid call) and a consumer:preparing fault hook. PGLite always, Postgres+ * when DATABASE_URL is set.+ */+import { describe, expect, test } from 'bun:test';+import type { ChatOpts, ChatResult } from '../src/core/ai/gateway.ts';+import type { BrainEngine } from '../src/core/engine.ts';+import { runPhaseExtractAtoms } from '../src/core/cycle/extract-atoms.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { installFaultHook } from '../src/core/persistence/fault-points.ts';+import { operations } from '../src/core/operations.ts';+import { OperationError, type OperationContext } from '../src/core/ops/contract.ts';+import { atomOwnerKey } from '../src/core/generations/adapters/atoms.ts';+import { listPendingMembers } from '../src/core/generations/managed.ts';+import { managedAtomSession, publishManagedAtomGeneration, readAtomOrigin, resumeManagedGenerationMembers } from '../src/core/persistence/atom-maintenance.ts';+import { resolveRepairScope } from '../src/core/repair/core.ts';+import { repairRunner } from '../src/core/repair/registry.ts';+import { serializePageToMarkdown } from '../src/core/markdown.ts';+import { managedBrain, pathologicalArms } from './pathological/harness.ts';++const NOTE = 'notes/acme-example-plan';+const KEY = { kind: 'atom', sourceId: 'default', ownerKey: atomOwnerKey({ kind: 'page', slug: NOTE }) };+const body = (label: string) => '---\ntype: note\ntitle: Acme example plan\n---\n\n' + (label + ': the team ships small changes, measures each launch and reviews outcomes weekly. ').repeat(12) + '\n';+const TITLES = ['Ship small changes', 'Review outcomes weekly', 'Measure each launch', 'Pair on reviews'];++async function extract(engine: BrainEngine, atoms: Array<{ title: string; body?: string }>) {+ const chat = async (_o: ChatOpts): Promise<ChatResult> => {+ const text = JSON.stringify(atoms.map(atom => ({ title: atom.title, body: atom.body ?? atom.title + '.', atom_type: 'insight' })));+ return { text, blocks: [{ type: 'text', text }], stopReason: 'end',+ usage: { input_tokens: 10, output_tokens: 10, cache_read_tokens: 0, cache_creation_tokens: 0 }, model: 'anthropic:claude-haiku-4-5', providerId: 'anthropic' };+ };+ const page = (await engine.getPage(NOTE, { sourceId: 'default' }))!;+ const result = await runPhaseExtractAtoms(engine, { sourceId: 'default', _chat: chat, _transcripts: [],+ _pages: [{ slug: NOTE, content: page.compiled_truth, contentHash: page.content_hash! }] });+ await disposePersistenceConsumer(engine);+ return result;+}++async function edit(ctx: OperationContext, label: string) {+ const snap = await ctx.engine.readPageSnapshot(NOTE, { sourceId: 'default' });+ await operations.find(o => o.name === 'put_page')!.handler(ctx, { slug: NOTE, content: body(label), ...(snap ? { expected_revision: snap.revision } : {}) });+ await disposePersistenceConsumer(ctx.engine);+}++const atomRows = (engine: BrainEngine) => engine.executeRaw<{ slug: string; live: boolean; body: string }>(+ "SELECT slug, deleted_at IS NULL AS live, compiled_truth AS body FROM pages WHERE source_id='default' AND type='atom' AND frontmatter->>'source_slug'=$1 ORDER BY slug", [NOTE]);++for (const { backend, databaseUrl } of pathologicalArms()) {+ describe(`managed atom generations (${backend})`, () => {+ test('#9079: release-held publishes a held result past the completion the drain journaled for the same input', async () => {+ await managedBrain(async ({ engine, ctx }) => {+ await edit(ctx, 'first');+ expect((await extract(engine, TITLES.map(title => ({ title })))).status).toBe('ok');+ const live = await atomRows(engine);+ expect(live.map(row => row.live)).toEqual([true, true, true, true]);+ const session = (await managedAtomSession(engine, 'default'))!;+ const page = (await engine.getPage(NOTE, { sourceId: 'default' }))!;+ const origin = await readAtomOrigin(engine, session, { kind: 'page', slug: NOTE, content: page.compiled_truth, contentHash: page.content_hash! });+ const kept = (await engine.readPageSnapshot(live[0]!.slug, { sourceId: 'default' }))!;+ const held = await publishManagedAtomGeneration(engine, session, origin,+ [{ slug: kept.page.slug, content: serializePageToMarkdown(kept.page, kept.tags), links: [] }], { key: KEY, content: page.compiled_truth });+ expect(held).toMatchObject({ state: 'held', reason: 'shrunk' });+ await disposePersistenceConsumer(engine);++ const scope = await resolveRepairScope(engine, 'default');+ const quiet = { info: () => {}, warn: () => {}, error: () => {} };+ const selection = { kind: 'atom', mode: 'release-held' as const, held: true };+ const preview = await (await repairRunner(engine, { apply: false, logger: quiet })).run('generations', scope, { explicit: true, sourceFlag: 'default', generations: selection });+ expect(preview.listing).toEqual([expect.objectContaining({ class: 'release-held' })]);+ const apply = () => repairRunner(engine, { apply: true, noEmbed: true, logger: quiet }).then(runner => runner.run('generations', scope,+ { explicit: true, sourceFlag: 'default', generations: selection, expect: preview.preview_hash }));+ expect((await apply()).outcomes).toEqual({ released: 1 });+ await disposePersistenceConsumer(engine);+ expect((await atomRows(engine)).filter(row => row.live).map(row => row.slug)).toEqual([kept.page.slug]);+ }, { databaseUrl });+ }, 240_000);++ test('#9275: an overwrite interrupted after its activation is resubmitted, not kept as an edit', async () => {+ await managedBrain(async ({ engine, ctx }) => {+ await edit(ctx, 'first');+ expect((await extract(engine, TITLES.map(title => ({ title })))).status).toBe('ok');+ const target = (await atomRows(engine)).find(row => row.slug.includes('measure-each-launch'))!;+ await edit(ctx, 'second');+ let crashes = 0;+ installFaultHook(async (point, detail) => {+ if (crashes || point !== 'consumer:preparing' || !detail.writeId) return;+ const [row] = await engine.executeRaw<{ slug: string; phase: string | null }>("SELECT slug, intent->>'phase' AS phase FROM persistence_requests WHERE id=$1::uuid", [detail.writeId]);+ if (row?.phase !== 'overwrite' || row.slug !== target.slug) return;+ crashes++;+ throw new OperationError('revision_conflict', 'Simulated interruption: the overwrite never landed.', 'Run the atom drain again.');+ });+ try { await extract(engine, TITLES.map(title => ({ title, body: title === 'Measure each launch' ? 'Measure each launch against its stated goal.' : undefined }))).catch(() => undefined); }+ finally { installFaultHook(undefined); }+ await disposePersistenceConsumer(engine);+ expect(crashes).toBeGreaterThan(0);+ expect((await listPendingMembers(engine, ['default'], 'atom')).find(row => row.slug === target.slug)?.action).toBe('overwrite');+ expect((await atomRows(engine)).find(row => row.slug === target.slug)!.body).not.toContain('stated goal');++ const session = (await managedAtomSession(engine, 'default'))!;+ const resumed = await resumeManagedGenerationMembers(engine, session, { corpusDir: null });+ await disposePersistenceConsumer(engine);+ expect(resumed.find(row => row.slug === target.slug)?.outcome).toBe('resubmitted');+ expect(resumed.some(row => row.outcome === 'kept_edited')).toBe(false);+ expect((await atomRows(engine)).find(row => row.slug === target.slug)!.body).toContain('stated goal');+ expect(await listPendingMembers(engine, ['default'], 'atom')).toEqual([]);+ }, { databaseUrl });+ }, 240_000);+ });+}diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex 874f285734..85a4307a4d 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -312,6 +312,7 @@ test/list-pages-empty-type-notice-gbra449.test.tstest/lower-tier-label-hold.test.tstest/maintenance-lowering-7917-7918.test.tstest/maintenance-trust-marker-7905.test.ts+test/managed-atom-release-resume-9079-9275.test.tstest/managed-cycle-pull-upstream.test.tstest/managed-facts-withdrawal-recovery-6506.test.tstest/managed-facts-withdrawn-skip-6506.test.ts@@ -558,6 +559,7 @@ test/remember-segmented-entity-9213.test.tstest/remember-share-gst2243.test.tstest/remember-strict-held-gst2492.test.tstest/rename-atom-lineage-7462.test.ts+test/repair-agent-session-facts-segmented-9027.test.tstest/repair-apply-pending-6543.test.tstest/repair-atom-fence-rows.test.tstest/repair-database-stop-gbra133.test.tsdiff --git a/test/repair-agent-session-facts-segmented-9027.test.ts b/test/repair-agent-session-facts-segmented-9027.test.tsnew file mode 100644index 0000000000..cc1f631401--- /dev/null+++ b/test/repair-agent-session-facts-segmented-9027.test.ts@@ -0,0 +1,158 @@+/**+ * #9027: `gbrain repair agent-session-facts --apply` on a page stored in segments (`body_storage = 'segmented'`).+ *+ * Protects: the fenced facts of a segmented page are re-attributed (`attributed_to: other` plus the speaker note) and+ * its fenced `kind: fact` / `holder: self` takes retired, as on an inline page: the page is read back whole and+ * published by one revision-bound put_page, so the projection rewrites the rows and the page stays segmented. Covered+ * on an unmanaged repo-less brain (the put writes the database) and a managed one whose content root is a plain+ * directory (the put goes through the coordinated writer and the file).+ * Fails when: the apply skips a segmented page, so every previewed row reports changed_since_preview and stays as it was.+ * PGLite always; PostgreSQL when DATABASE_URL is set (test/postgres-unit-arms.txt).+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { BrainEngine } from '../src/core/engine.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { runRepairCommand } from '../src/commands/repair.ts';+import { speakerContextNote, writeSpeakerSidecar } from '../src/core/context/session-speaker.ts';+import { withCoordinatedWrite } from '../src/core/persistence/context.ts';+import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';+import type { OperationContext } from '../src/core/ops/contract.ts';+import { randomUUID } from 'node:crypto';+import { conversationBody } from './helpers/conversation-page.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { managedBrain } from './helpers/managed-brain.ts';+import { testBackends } from './helpers/test-backends.ts';+import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';++const ALICE = 'people/alice-example';+const FACTS = ['<!--- gbrain:facts:begin -->',+ '| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |',+ '|---|---|---|---|---|---|---|---|---|---|',+ '| 1 | Prefers terse status updates | preference | 0.9 | private | low | 2026-10-01 | | hook:writeback | |',+ '| 2 | Prefers async standups | preference | 0.9 | private | low | 2026-10-01 | | hook:writeback | |',+ '<!--- gbrain:facts:end -->'].join('\n');+const TAKES = ['<!--- gbrain:takes:begin -->', '| # | claim | kind | who | weight | since | source |', '|---|---|---|---|---|---|---|',+ '| 1 | Prefers terse async updates | fact | self | 0.8 | 2026-10-01 | hook:writeback |', '<!--- gbrain:takes:end -->'].join('\n');+const page = (fence: string) => `---\ntitle: Alice Example\ntype: person\n---\n\n# Alice Example\n\n## Notes\n\n${fence}\n\n${conversationBody(1_200_000, { seed: 9027 })}\n`;++interface RepairJson { results: Array<{ apply_command: string; residuals: Record<string, number>; outcomes?: Record<string, number> }> }+async function repair(engine: BrainEngine, args: string[]): Promise<RepairJson> {+ const lines: string[] = [];+ const original = console.log;+ console.log = (...parts: unknown[]) => { lines.push(parts.map(String).join(' ')); };+ try { await runRepairCommand(engine, ['agent-session-facts', ...args, '--json']); } finally { console.log = original; }+ return JSON.parse(lines.join('\n')) as RepairJson;+}+/** Writes the page by put_page, as an agent would; the put projects its fences (an import of the file alone does not). */+async function putPage(engine: BrainEngine, fence: string, ctx?: OperationContext) {+ await engine.setConfig('pages.segmented_storage', 'on');+ await submitPageMutation(ctx ?? { engine, config: { engine: engine.kind, embedding_disabled: true }, sourceId: 'default', remote: false, dryRun: false,+ logger: { info() {}, warn() {}, error() {} } }, { operation: 'put_page', params: { slug: ALICE, content: page(fence), request_id: randomUUID() } });+ expect(await storage(engine)).toBe('segmented');+}+const applyArgs = (json: RepairJson) => json.results[0]!.apply_command.split(' ').slice(3);+const storage = async (engine: BrainEngine) => (await engine.executeRaw<{ body_storage: string }>(+ "SELECT body_storage FROM pages WHERE source_id='default' AND slug=$1", [ALICE]))[0]!.body_storage;+const raw = (engine: BrainEngine, sql: string, params: unknown[]) =>+ engine.transaction(tx => withCoordinatedWrite(tx, ['default'], () => tx.executeRaw(sql, params), TEST_WRITE_ATTRIBUTION));+const facts = (engine: BrainEngine) => engine.executeRaw<{ id: number; fact: string; attributed_to: string | null; context: string | null; active: boolean }>(+ "SELECT id, fact, attributed_to, context, expired_at IS NULL AND superseded_by IS NULL AS active FROM facts WHERE source_id='default' AND entity_slug=$1 ORDER BY id", [ALICE]);++/** The fenced facts of the page, given the sidecar session the capture lane records. */+async function captureFacts(engine: BrainEngine): Promise<number[]> {+ const rows = (await facts(engine)).filter(f => f.active);+ expect(rows.map(f => f.fact)).toEqual(['Prefers terse status updates', 'Prefers async standups']);+ const ids = rows.map(f => Number(f.id));+ await raw(engine, "UPDATE facts SET source_session='sess-sidecar', attributed_to='user' WHERE id=ANY($1::bigint[])", [ids]);+ return ids;+}++/** The page's fenced take, consolidated from two database-only capture-lane facts of the sidecar session. */+async function consolidatedTake(engine: BrainEngine): Promise<number> {+ const [take] = await engine.executeRaw<{ id: number }>('SELECT t.id FROM takes t JOIN pages p ON p.id=t.page_id WHERE p.slug=$1 AND t.active', [ALICE]);+ expect(take).toBeDefined();+ for (const fact of ['Prefers terse updates', 'Prefers async updates']) {+ await raw(engine, `INSERT INTO facts (source_id, entity_slug, fact, kind, visibility, source, source_session, attributed_to, consolidated_into, consolidated_at)+ VALUES ('default', $1, $2, 'preference', 'private', 'hook:writeback', 'sess-sidecar', 'user', $3, now() - interval '1 minute')`, [ALICE, fact, take!.id]);+ }+ return Number(take!.id);+}++async function expectReattributed(engine: BrainEngine, ids: number[]) {+ const preview = await repair(engine, []);+ expect(preview.results[0]!.residuals).toMatchObject({ evidenced: 2 });+ const applied = await repair(engine, applyArgs(preview));+ expect(applied.results[0]!.outcomes).toEqual({ reattributed: 1 });+ for (const row of (await facts(engine)).filter(f => ids.includes(Number(f.id)))) {+ expect(row).toMatchObject({ attributed_to: 'other', active: true, context: speakerContextNote('worker-a') });+ }+ expect((await facts(engine)).filter(f => f.active && f.attributed_to !== 'other')).toEqual([]);+ expect(await storage(engine)).toBe('segmented');+}++async function expectRetired(engine: BrainEngine, take: number) {+ const preview = await repair(engine, []);+ expect(preview.results[0]!.residuals).toMatchObject({ evidenced: 2, takes_to_retire: 1 });+ const applied = await repair(engine, applyArgs(preview));+ expect(applied.results[0]!.outcomes).toEqual({ reattributed: 1, retired: 1 });+ expect((await engine.executeRaw<{ active: boolean }>('SELECT active FROM takes WHERE id=$1', [take]))[0]!.active).toBe(false);+ expect(await storage(engine)).toBe('segmented');+}++let base: string;+let corpus: string;+beforeAll(() => {+ base = mkdtempSync(join(tmpdir(), 'gbrain-agent-session-segmented-'));+ corpus = join(base, 'corpus');+ mkdirSync(join(corpus, 'sourced'), { recursive: true });+ writeFileSync(join(corpus, 'sess-sidecar.txt'), '[user]\nPlease triage the open issues for the docs lane.\n\n[assistant]\nOn it.');+ writeSpeakerSidecar(corpus, 'sess-sidecar', { principal: 'worker-a', source: 'env' }, 'claude');+});+afterAll(() => rmSync(base, { recursive: true, force: true }));++for (const kind of testBackends()) {+ describe(`repair agent-session-facts on a segmented page, unmanaged repo-less brain (${kind})`, () => {+ /** A fresh brain with segmented storage on, the corpus configured and the page imported (stored in segments). */+ const withPage = async (fence: string, run: (engine: BrainEngine) => Promise<void>) => {+ let engine: BrainEngine;+ let close: () => Promise<void>;+ if (kind === 'postgres') ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));+ else { const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema(); engine = lite; close = () => lite.disconnect(); }+ try {+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await engine.setConfig('dream.synthesize.session_corpus_dir', corpus);+ await putPage(engine, fence);+ await run(engine);+ } finally { await close(); }+ };++ test('apply re-attributes fenced facts on a segmented page', async () => {+ await withPage(FACTS, async engine => expectReattributed(engine, await captureFacts(engine)));+ }, 300_000);++ test('apply retires fenced takes on a segmented page', async () => {+ await withPage(TAKES, async engine => expectRetired(engine, await consolidatedTake(engine)));+ }, 300_000);+ });++ describe(`repair agent-session-facts on a segmented page, managed repo-less brain (${kind})`, () => {+ /** As the unmanaged arm, through the coordinated writer; the page's file then holds the repaired row (`fileHolds`). */+ const withPage = (fence: string, fileHolds: string, run: (engine: BrainEngine) => Promise<void>) => managedBrain(async ({ engine, ctx, root }) => {+ await engine.setConfig('dream.synthesize.session_corpus_dir', corpus);+ await putPage(engine, fence, ctx);+ await run(engine);+ expect(readFileSync(join(root, `${ALICE}.md`), 'utf8')).toContain(fileHolds);+ }, kind === 'postgres' ? { databaseUrl: process.env.DATABASE_URL! } : {});++ test('apply re-attributes fenced facts on a segmented page', async () => {+ await withPage(FACTS, `| ${speakerContextNote('worker-a')} |`, async engine => expectReattributed(engine, await captureFacts(engine)));+ }, 300_000);++ test('apply retires fenced takes on a segmented page', async () => {+ await withPage(TAKES, '~~Prefers terse async updates~~', async engine => expectRetired(engine, await consolidatedTake(engine)));+ }, 300_000);+ });+}diff --git a/test/safety-wave-coverage-invocation-inheritance.test.ts b/test/safety-wave-coverage-invocation-inheritance.test.tsindex 17254cba89..356922d602 100644--- a/test/safety-wave-coverage-invocation-inheritance.test.ts+++ b/test/safety-wave-coverage-invocation-inheritance.test.ts@@ -22,7 +22,7 @@ test('inherited fact authorization admits and settles both budgets for one proviexpect(events).toEqual([['migration:admit', null], ['facts:admit', null], ['migration:settle', usage], ['facts:settle', usage]]);});-test('inner authorization refusal retains the outer debit without dispatching', async () => {+test('inner authorization refusal releases the outer debit at zero usage without dispatching', async () => {const events: Array<[string, AIInvocationUsage | null]> = [];const refused = new Error('synthetic inner cap exhausted');let dispatched = false;@@ -31,7 +31,7 @@ test('inner authorization refusal retains the outer debit without dispatching',invokeAI(call, async () => { dispatched = true; }, () => usage), { inherit: true }))).rejects.toBe(refused);expect(dispatched).toBe(false);expect(isAIInvocationPolicyError(refused)).toBe(true);- expect(events).toEqual([['migration:admit', null], ['migration:settle', null]]);+ expect(events).toEqual([['migration:admit', null], ['migration:settle', { inputTokens: 0, outputTokens: 0 }]]);});test('outer authorization refusal prevents inner admission and provider dispatch', async () => {diff --git a/test/spend-nested-refusal-9086.test.ts b/test/spend-nested-refusal-9086.test.tsnew file mode 100644index 0000000000..dab43e93c9--- /dev/null+++ b/test/spend-nested-refusal-9086.test.ts@@ -0,0 +1,121 @@+/**+ * #9086: a job group's hold when a nested guard refuses (src/core/ai/invocation-guard.ts,+ * src/core/minions/spend-authorization.ts).+ *+ * Protects: an inner guard that refuses after the outer job-group guard reserved+ * dispatches nothing, so the outer hold is released at $0 instead of kept as+ * unknown usage; a dispatched call that fails still keeps its maximum against the+ * group; `remaining_usd` subtracts live holds.+ * Fails when: the inherit catch settles the outer permit as unknown usage (holds+ * pile up and the group dies cost_cap_exceeded with nothing spent), a failed+ * dispatched call is released for free, or remaining_usd ignores live holds.+ * Seams: the real budget meter on PGLite always, and on Postgres through+ * test/e2e/spend-nested-refusal-9086-postgres.test.ts.+ */+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import type { BrainEngine } from '../src/core/engine.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { MinionQueue } from '../src/core/minions/queue.ts';+import { invokeAI, withAIInvocationGuard } from '../src/core/ai/invocation-guard.ts';+import { readGroupSpend, reserveGroup, settle } from '../src/core/minions/budget-meter.ts';+import { groupAmounts, jobGroupAmounts, jobSpendAuthorization, runWithJobSpend } from '../src/core/minions/spend-authorization.ts';+import type { MinionJob, MinionJobContext } from '../src/core/minions/types.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { testBackends } from './helpers/test-backends.ts';++const MODEL = 'anthropic:claude-sonnet-5';+/** A priced chat call whose maximum is `maxCents` (claude-sonnet-5 input at $2/Mtok, reserved at 2x). */+const call = (maxCents: number) => ({ operation: 'test', kind: 'chat' as const, model: MODEL, maxInputTokens: maxCents * 2500, maxOutputTokens: 0 });+const record = (capUsd: number) => jobSpendAuthorization({ consented_effects: ['paid'], cap_usd: capUsd, cap_source: 'derived', via: 'yes' },+ { command: 'book-mirror', of: 1, argv: ['gbrain', 'book-mirror', '--slug', 'alice-example'] });+const ctxFor = (job: MinionJob) => ({ id: job.id, name: job.name, data: job.data, attempts_made: 0 }) as unknown as MinionJobContext;++for (const backend of testBackends()) {+ describe(`${backend}: #9086 nested refusal`, () => {+ let engine: BrainEngine;+ let queue: MinionQueue;+ let close: () => Promise<void> = async () => {};++ beforeAll(async () => {+ if (backend === 'pglite') {+ const pglite = new PGLiteEngine();+ await pglite.connect({});+ await pglite.initSchema();+ engine = pglite;+ close = () => pglite.disconnect();+ } else {+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!);+ engine = pg.engine;+ close = pg.close;+ }+ queue = new MinionQueue(engine);+ }, 120_000);+ afterAll(async () => { await close(); });+ beforeEach(async () => {+ for (const sql of ['DELETE FROM mcp_spend_reservations', 'DELETE FROM mcp_spend_log', 'DELETE FROM minion_jobs']) await engine.executeRaw(sql);+ });++ async function claimedJob(capUsd: number): Promise<MinionJob> {+ await queue.add('subagent', { prompt: 'x' }, {}, { allowProtectedSubmit: true, spendAuthorization: record(capUsd) });+ const job = await queue.claim('tok', 60_000, 'default', ['subagent']);+ if (!job) throw new Error('nothing claimed');+ return job;+ }+ const holds = () => engine.executeRaw<{ status: string; estimated_cents: number; actual_cents: number | null; usage_unknown_reason: string | null }>(+ 'SELECT status, estimated_cents::float8 AS estimated_cents, actual_cents::float8 AS actual_cents, usage_unknown_reason FROM mcp_spend_reservations ORDER BY created_at');++ test('an inner refusal releases the outer group hold', async () => {+ const job = await claimedJob(1);+ const budgetKey = `group:${job.spend_authorization!.group_id}`;+ let dispatched = 0;+ const errors: string[] = [];+ await runWithJobSpend(engine, job, ctxFor(job), async () => {+ for (let i = 0; i < 5; i++) {+ try {+ await withAIInvocationGuard(async () => { throw new Error('inner guard refused'); },+ () => invokeAI(call(40), async () => { dispatched++; return 'ok'; }, () => ({ inputTokens: 1, outputTokens: 0 })), { inherit: true });+ } catch (e) { errors.push((e as Error).message); }+ }+ });+ expect(dispatched).toBe(0);+ expect(errors).toEqual(Array(5).fill('inner guard refused'));+ const rows = await holds();+ expect(rows).toHaveLength(5);+ expect(rows.map(r => [r.status, Number(r.actual_cents), r.usage_unknown_reason])).toEqual(Array(5).fill(['settled', 0, null]));+ expect(await readGroupSpend(engine, budgetKey)).toEqual({ committedCents: 0, overdueCents: 0, liveCents: 0 });+ expect(await jobGroupAmounts(engine, job.spend_authorization!)).toMatchObject({ spent_usd: 0, reserved_usd: 0, remaining_usd: 1 });++ const result = await runWithJobSpend(engine, job, ctxFor(job), () =>+ invokeAI(call(40), async () => { dispatched++; return 'ok'; }, () => ({ inputTokens: 10 * 5000, outputTokens: 0 })));+ expect(result).toBe('ok');+ expect(dispatched).toBe(1);+ expect((await readGroupSpend(engine, budgetKey)).committedCents).toBe(10);+ });++ test('a dispatched inner call that fails still books against the outer hold', async () => {+ const job = await claimedJob(1);+ const budgetKey = `group:${job.spend_authorization!.group_id}`;+ let dispatched = 0;+ await expect(runWithJobSpend(engine, job, ctxFor(job), () =>+ withAIInvocationGuard(async () => ({ settle: async () => {} }),+ () => invokeAI(call(40), async () => { dispatched++; throw new Error('provider failed after send'); }, () => null), { inherit: true }),+ )).rejects.toThrow('provider failed after send');+ expect(dispatched).toBe(1);+ const rows = await holds();+ expect(rows.map(r => [r.status, Number(r.estimated_cents), r.actual_cents, r.usage_unknown_reason])).toEqual([['pending', 40, null, 'provider_usage_unknown']]);+ expect(await readGroupSpend(engine, budgetKey)).toEqual({ committedCents: 0, overdueCents: 0, liveCents: 40 });+ });++ test('remaining_usd subtracts live holds', async () => {+ const job = await claimedJob(1);+ const budgetKey = `group:${job.spend_authorization!.group_id}`;+ const spent = await reserveGroup(engine, { budgetKey, capCents: 100, estimatedCents: 20, model: MODEL, provider: 'anthropic', jobId: job.id });+ await settle(engine, spent.reservationId, 20, 'test');+ await reserveGroup(engine, { budgetKey, capCents: 100, estimatedCents: 30, model: MODEL, provider: 'anthropic', jobId: job.id });+ expect(await jobGroupAmounts(engine, job.spend_authorization!)).toMatchObject({ spent_usd: 0.2, overdue_usd: 0, reserved_usd: 0.3, remaining_usd: 0.5 });+ expect(groupAmounts(job.spend_authorization!, { committedCents: 20, overdueCents: 10, liveCents: 30 }))+ .toMatchObject({ spent_usd: 0.2, overdue_usd: 0.1, reserved_usd: 0.4, remaining_usd: 0.4 });+ expect(groupAmounts(job.spend_authorization!, { committedCents: 80, overdueCents: 0, liveCents: 50 }).remaining_usd).toBe(0);+ });+ });+}