Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(dream): extract_atoms never commits a clipped response; managed batches keep their atoms and ask for an approved retry (#6260)

time-attack3b60c281ae19
diff --git a/docs/architecture/key-files/core-cycle.md b/docs/architecture/key-files/core-cycle.md
index 37295b1d1f..c62f1d7f0c 100644
--- a/docs/architecture/key-files/core-cycle.md
+++ b/docs/architecture/key-files/core-cycle.md
@@ -6,7 +6,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/cycle/dream-provenance.ts` — `stampDreamProvenance`, the unmanaged dream-output identity stamp shared by synthesize and patterns: sets `dream_generated`, a stable `dream_cycle_date` / `dream_created_cycle_date` and an optional `raw_source` in page frontmatter, and leaves a page that existed before the child's first write to it (`first_write_at`) unstamped. Managed brains stamp through maintenance writes instead. A ref's optional `seat` is stamped beside `raw_source` (the capturing agent seat, #4618).
- `src/core/cycle/extract-atoms-schema.ts` — shared atom-type vocabulary and the extraction response schema. The private model prompt requests an object containing `atoms`; the schema uses closed objects and nullable optional metadata. `extract-atoms.ts` passes it through the gateway's capability gate and existing schema-rejection fallback, while its tolerant parser still accepts legacy bare arrays. Schema submission does not replace grounding or malformed-output checks. Covered by `test/cycle/extract-atoms-structured-output.test.ts` using a local HTTP protocol fixture and isolated PGLite, without live model inference.
-- `src/core/cycle/extract-atoms-parse.ts` — extract_atoms response parsing, re-exported by `extract-atoms.ts`. `parseAtomsOutcome` returns a typed outcome (`ok: false` with a stable reason string for malformed output, `ok: true, atoms: []` for an honest zero-yield), retrying once with reasoning blocks stripped. A bounded anchor scan (`MAX_ARRAY_ANCHOR_CANDIDATES`) tries successive `[` offsets; each candidate ends at its own closing bracket (`matchingCloseBracket` in `llm-json.ts`), the first array yielding an atom-shaped element wins, a literal `[]` is zero-yield only when no earlier `[` is still open at its offset (an atom's own `"concepts": []` inside a clipped or malformed array is malformed output, `test/extract-atoms-nested-empty-array.test.ts`), and failure reasons always describe the first bracket. `atomsFromParsedArray` is the single atom shape gate.
+- `src/core/cycle/extract-atoms-parse.ts` — extract_atoms response parsing, re-exported by `extract-atoms.ts`. `parseAtomsOutcome` returns a typed outcome (`ok: false` with a stable reason string for malformed output, `ok: true, atoms: []` for an honest zero-yield), retrying once with reasoning blocks stripped. `parseAtomsOutcome(text, stopReason)` takes the gateway stop reason: `length`/`refusal`/`content_filter` are never parsed, and an empty answer under `other`/`tool_calls` is not taken as complete; both return `ok: false, stopped: true`, which `extract-atoms.ts` counts in `details.stopped_outputs` and fails like malformed output (unmanaged: the bounded streak; managed: a failure receipt that never retires earlier atoms; `test/cycle/extract-atoms-stop-reason.test.ts`, `test/managed-atoms-stop-reason.test.ts`). A bounded anchor scan (`MAX_ARRAY_ANCHOR_CANDIDATES`) tries successive `[` offsets; each candidate ends at its own closing bracket (`matchingCloseBracket` in `llm-json.ts`), the first array yielding an atom-shaped element wins, a literal `[]` is zero-yield only when no earlier `[` is still open at its offset (an atom's own `"concepts": []` inside a clipped or malformed array is malformed output, `test/extract-atoms-nested-empty-array.test.ts`), and failure reasons always describe the first bracket. `atomsFromParsedArray` is the single atom shape gate.
- `src/core/cycle/anomaly.ts` — Pure stats helpers for `find_anomalies`. `meanStddev` returns sample stddev (n-1 denominator) and (0,0) for empty input. `computeAnomaliesFromBuckets(baseline, today, sigma, limit)` takes densified daily-count buckets + today's counts per cohort, returns `AnomalyResult[]`. Zero-stddev fallback: cohort fires when `count > mean + 1`, with `sigma_observed = count - mean` as a finite sort proxy (no NaN). Brand-new cohorts (no baseline) have `mean=0, stddev=0` so the fallback fires at count >= 2. Sorted by `sigma_observed` desc, top `limit` (default 20). `page_slugs` capped at 50 per cohort.
diff --git a/docs/architecture/key-files/core-persistence.md b/docs/architecture/key-files/core-persistence.md
index 1cd94426fa..c8f4b31d71 100644
--- a/docs/architecture/key-files/core-persistence.md
+++ b/docs/architecture/key-files/core-persistence.md
@@ -16,7 +16,7 @@ Connector ingestion, item holds and checkpoint validation continue in [Core Pers
- `src/core/persistence/onboarding.ts` + `legacy-locks.ts` + `physical-root-recovery.ts` — read-only source onboarding states; exact same-host dead-lock cleanup under explicit activation opt-in; and state-bound same-owner root repair using a durable manifest and token-verified temporary stamp. `physical-root.ts` `restampPhysicalRoot` handles a filesystem device id that changed while the owner token, brain, worktree, root, inode and a non-zero birth time still match (macOS can renumber `st_dev` across reboots): under the caller's outside-root native lock, one transaction verifies owner host, brain and host binding and rewrites the recorded self-transfer copies and retained topology staging identities (each only while it still names the old device); after commit the stamp and the reservation's initial device are rewritten and the event is logged, so an interruption between the two leaves a device-only change the next locked acquisition finishes. Ownership markers inside a retained topology clone stage are not re-stamped; an interrupted clone recovery that spans a device renumbering still needs source recovery. `assertPhysicalRoot` stays read-only; zero birth time or any other difference keeps the refusal. `--self-transfer` prepare/accept requires separate fresh reviewed state, preserves original reservation owner evidence and refuses uncertain records. Tests: `test/persistence-onboarding.test.ts`, `test/persistence-admin-recovery.test.ts`, `test/persistence-container-preflight.test.ts`.
-- `src/core/persistence/{atom-maintenance,atom-retry,page-prepare,facts-maintenance,facts-prepare,prepared-maintenance}.ts` — resident dispatch for durable atom publication/completion, explicit atom retry, authorized multi-entity fact-fence/backstop append, local synthesize/patterns/consolidation, and the cycle's lint repairs on a managed brain (`runLintCore` publishes each fix through `maintenancePreflight` + `publishMaintenancePage`; #5180, `test/managed-lint.test.ts`). `page-prepare.ts` exports `fileMatchesSnapshot`, the canonical file-versus-page comparison `prepareFileTarget` applies, so lint can bind a repair to the revision it read; the uncoordinated-local-edit refusal carries detail `file_database_drift` and a `sources reconcile <src> <slug> --brain host --preview` fix. In `prepareFileTarget`, a live page whose canonical file is missing refuses `source_changed` unless it is declared or derive-phase database-only, or it is a `delete_page` (`deleting`, no content) of a page with no recorded `source_path` and no captured file URI: that delete plans no file, so it publishes database-only and its receipt reports no file or Git effect (`test/persistence-captured-file-target.test.ts`, `test/persistence-never-published-delete.test.ts`). `atomOwnerTarget` is the one owner decision for an atom session and for `atomDrainOwnerRefusal`, the auto-drain dispatch pre-check; an unbound Google/GitHub source publishes atom maintenance through the `connector_database` target (its `local_path` is connector state, not a checkout) and the publication refuses with `source_changed` when the source gained an owner after preflight. `maintenancePreflight` creates the job's `MaintenanceWriteWait` (optional `deadlineAtMs`) and `submitMaintenance` uses it for new and replayed requests.
+- `src/core/persistence/{atom-maintenance,atom-retry,page-prepare,facts-maintenance,facts-prepare,prepared-maintenance}.ts` — resident dispatch for durable atom publication/completion, explicit atom retry, authorized multi-entity fact-fence/backstop append, local synthesize/patterns/consolidation, and the cycle's lint repairs on a managed brain (`runLintCore` publishes each fix through `maintenancePreflight` + `publishMaintenancePage`; #5180, `test/managed-lint.test.ts`). `page-prepare.ts` exports `fileMatchesSnapshot`, the canonical file-versus-page comparison `prepareFileTarget` applies, so lint can bind a repair to the revision it read; the uncoordinated-local-edit refusal carries detail `file_database_drift` and a `sources reconcile <src> <slug> --brain host --preview` fix. In `prepareFileTarget`, a live page whose canonical file is missing refuses `source_changed` unless it is declared or derive-phase database-only, or it is a `delete_page` (`deleting`, no content) of a page with no recorded `source_path` and no captured file URI: that delete plans no file, so it publishes database-only and its receipt reports no file or Git effect (`test/persistence-captured-file-target.test.ts`, `test/persistence-never-published-delete.test.ts`). `atomOwnerTarget` is the one owner decision for an atom session and for `atomDrainOwnerRefusal`, the auto-drain dispatch pre-check; an unbound Google/GitHub source publishes atom maintenance through the `connector_database` target (its `local_path` is connector state, not a checkout) and the publication refuses with `source_changed` when the source gained an owner after preflight. `maintenancePreflight` creates the job's `MaintenanceWriteWait` (optional `deadlineAtMs`) and `submitMaintenance` uses it for new and replayed requests. A failed atom batch's resume refusal (`extraction_failed`) names the recorded failure reason (malformed output or a response stopped before the end) and carries a paid `fix` (`gbrain jobs submit extract-atoms-drain --params '{sourceId, retryRequestId}'`) with a read-only `gbrain write-request` verify.
- `src/core/persistence/maintenance-wait.ts` — how long a maintenance publisher waits for its accepted write to commit before the receipt reports `write_pending` (#5854). `MAINTENANCE_WRITE_WAIT_MS` is 30 s; `MaintenanceWriteWait` is one budget per job: each wait is capped by the job's remaining deadline (zero at or past it), and once one publish is still pending after its wait (`observe`) every later publish in that job waits zero and is deferred like it. A pending write keeps its request identity and commits later; it is never reported as committed. A `MaintenanceWriteWait` with no deadline also sets the replay window of a subagent tool write whose job has none (`minions/tool-write-identity.ts`). `__setMaintenanceWriteWaitForTests` replaces the base wait, those tool writes included. Tests: `test/maintenance-write-wait.test.ts`, `test/e2e/maintenance-write-wait.test.ts`.
Atom completion admits replacement and revision-pinned stale-atom deletion children together.
Each retirement stamps `retired_by`/`retired_at` into the tombstone in the same publication; `publishManagedAtoms` restores a retired atom of the same origin when an extraction produces it again, and a user-deleted atom stays deleted. Each committed retirement bumps the origin page's regeneration generation (`op_checkpoints` op `managed-atoms-generation`, part of the drain's run key only above 0, never of the explicit retry identity; the content whose extraction retired keeps the generation its accepted batch used, so that batch stays resumable) and clears that page's older `extract_atoms_page_state` rows and completed `managed-atoms` checkpoints in the same publication, so an A→B→A edit, even after a partly failed batch, re-extracts instead of replaying a retained receipt. Retirements are admitted in slug order.
diff --git a/src/core/cycle/extract-atoms-parse.ts b/src/core/cycle/extract-atoms-parse.ts
index c1df284f77..3f69b78902 100644
--- a/src/core/cycle/extract-atoms-parse.ts
+++ b/src/core/cycle/extract-atoms-parse.ts
@@ -37,9 +37,30 @@ const CONCEPT_LABEL_RE = /^[a-z0-9]+(-[a-z0-9]+)*$/;
*/
export type AtomsParseOutcome =
| { ok: true; atoms: ExtractedAtom[] }
- | { ok: false; reason: string };
+ | { ok: false; reason: string; stopped?: true };
-export function parseAtomsOutcome(raw: string): AtomsParseOutcome {
+/**
+ * #6260: the gateway stop reason decides how far a response is trusted. A
+ * response stopped by the output cap, a refusal or a content filter is never
+ * parsed; `other` and `tool_calls` (some local providers report a normal end
+ * as `other`) are parsed, but their zero-yield is never taken as a
+ * completion. Both come back `ok: false, stopped: true`, so the caller counts
+ * them like malformed output (the bounded streak; managed: a failure receipt,
+ * which never retires earlier atoms). A missing reason (legacy chat seams)
+ * reads as a normal end.
+ */
+export function parseAtomsOutcome(raw: string, stopReason?: string): AtomsParseOutcome {
+ if (stopReason === 'length' || stopReason === 'refusal' || stopReason === 'content_filter') {
+ return { ok: false, stopped: true, reason: `output stopped before the end (stopReason=${stopReason})` };
+ }
+ const outcome = parseAtomsText(raw);
+ if ((stopReason === 'other' || stopReason === 'tool_calls') && outcome.ok && outcome.atoms.length === 0) {
+ return { ok: false, stopped: true, reason: `an empty answer under stopReason=${stopReason} is not taken as complete` };
+ }
+ return outcome;
+}
+
+function parseAtomsText(raw: string): AtomsParseOutcome {
const direct = parseAtomsOutcomeInner(raw);
if (direct.ok) return direct;
// Same reasoning-block hazard as the facts extractor: `indexOf('[')` below
diff --git a/src/core/cycle/extract-atoms.ts b/src/core/cycle/extract-atoms.ts
index 94ef24c225..eafa49e0f7 100644
--- a/src/core/cycle/extract-atoms.ts
+++ b/src/core/cycle/extract-atoms.ts
@@ -976,7 +976,7 @@ export async function runPhaseExtractAtoms(
}
// ── gbrain#4148 helpers ────────────────────────────────────────────
- let malformedOutputs = 0;
+ let malformedOutputs = 0, stoppedOutputs = 0; // #6260: stopped = clipped, or empty under an unconfirmed stop
const tombstonedForFailures: string[] = [];
// v146: transcript tombstones ride a SEPARATE array. `tombstoned_for_failures`
// is a list of page SLUGS; transcripts are filesystem paths, and mixing the two
@@ -1132,11 +1132,11 @@ export async function runPhaseExtractAtoms(
// gbrain#4148: typed outcome — malformed output is a FAILURE (counted
// toward the bounded tombstone below), never a zero-yield success.
- const parseOutcome = parseAtomsOutcome(result.text);
+ const parseOutcome = parseAtomsOutcome(result.text, result.stopReason);
if (!parseOutcome.ok) {
- malformedOutputs++;
+ if (parseOutcome.stopped) stoppedOutputs++; else malformedOutputs++;
if (!opts.dryRun && managed && origin) writeRequests.push(...await publishManagedAtoms(engine, managed, origin, [], parseOutcome.reason));
- await recordDeterministicFailure(item, originLabel, `malformed model output: ${parseOutcome.reason}`);
+ await recordDeterministicFailure(item, originLabel, parseOutcome.stopped ? parseOutcome.reason : `malformed model output: ${parseOutcome.reason}`);
continue;
}
const atoms = parseOutcome.atoms;
@@ -1456,7 +1456,7 @@ export async function runPhaseExtractAtoms(
failures,
...(managed ? { write_requests: writeRequests } : {}),
...(abortedGlobalError ? { aborted_global_error: abortedGlobalError } : {}),
- malformed_outputs: malformedOutputs,
+ malformed_outputs: malformedOutputs, stopped_outputs: stoppedOutputs,
tombstoned_for_failures: tombstonedForFailures,
tombstoned_transcripts: tombstonedTranscripts,
estimated_spend_usd: estimatedSpendUsd,
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index c5d3191756..5e21a4f879 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -148,7 +148,7 @@ export const CODES = {
engine_graduated: { class: 'caller', summary: "A client opened a PGLite brain that moved to Postgres; its old path holds a tombstone.", docs: 'docs/guides/move-to-postgres.md#graduated-datastore' },
eval_suite_unwired: { class: 'caller', summary: "`gbrain eval run-all` was asked for a suite it does not run in-process (longmemeval or replay); nothing ran.", why: "run-all runs only wired suites (brainbench). Recording a skipped run and exiting 0 would read as a completed sweep with no numbers behind it.", suggestion: 'Run each requested suite with its own command (`gbrain eval longmemeval <dataset.jsonl> --mode <mode> --record`, `gbrain eval replay --mode <mode>`), once per mode, or drop it from --suites.' },
export_limit: { class: 'caller', summary: "This migration is bounded to 5,000 active pages per source; split or use a reviewed bulk export." },
- extraction_failed: { class: 'server', summary: "The accepted atom extraction produced malformed output." },
+ extraction_failed: { class: 'server', summary: "The accepted atom extraction failed (malformed output, or a response stopped before the end); a new attempt needs approval.", why: "A failed managed atom batch is recorded as a failure receipt instead of being retried automatically, so the same input is not paid for every cycle." },
extractor_identity_mismatch: { class: 'server', summary: "The approved extractor differs from the installed extractor; this receipt cannot resume or admit another revision." },
fact_already_expired: { class: 'caller', summary: "The fact had already expired before this write." },
fact_not_found: { class: 'caller', summary: "Fact not found." },
diff --git a/src/core/persistence/atom-maintenance.ts b/src/core/persistence/atom-maintenance.ts
index 004c60a50b..1b4d4ad451 100644
--- a/src/core/persistence/atom-maintenance.ts
+++ b/src/core/persistence/atom-maintenance.ts
@@ -289,8 +289,15 @@ function expiredAtomReceipt(row: WriteRequest): never {
function malformedAtomReceipt(row: WriteRequest): never {
if (row.compacted && !row.intent) expiredAtomReceipt(row);
- const error = new OperationError('extraction_failed', 'The accepted atom extraction produced malformed output.',
- `Approve one new attempt with gbrain jobs submit extract-atoms-drain --params '${JSON.stringify({ sourceId: row.source_id, retryRequestId: row.request_id })}'.`);
+ const failure = (row.outcome as { failure?: unknown } | null)?.failure;
+ const params = JSON.stringify({ sourceId: row.source_id, retryRequestId: row.request_id });
+ const error = new OperationError('extraction_failed', `The accepted atom extraction failed${typeof failure === 'string' && failure ? ` (${failure})` : ''}; a new attempt needs approval.`,
+ `Approve one new attempt with gbrain jobs submit extract-atoms-drain --params '${params}'.`);
+ error.why = 'A failed managed atom batch keeps its failure receipt instead of retrying on its own, so the same input is not paid for every cycle; the earlier atoms of the page stay as they were.';
+ error.fix = { argv: ['gbrain', 'jobs', 'submit', 'extract-atoms-drain', '--params', params], consent: ['paid'], actor: 'agent', requires_exclusive: false,
+ why: 'Runs one new paid extraction attempt for this batch; ask the user before spending.',
+ verify: { argv: ['gbrain', 'write-request', '--', row.request_id] } };
+ error.contractVersion = 1;
error.writeRequest = receiptFor(row);
throw error;
}
diff --git a/test/cycle/extract-atoms-stop-reason.test.ts b/test/cycle/extract-atoms-stop-reason.test.ts
new file mode 100644
index 0000000000..40ecc5ca6c
--- /dev/null
+++ b/test/cycle/extract-atoms-stop-reason.test.ts
@@ -0,0 +1,121 @@
+/**
+ * #6260: extract_atoms reads the gateway stop reason before it trusts a
+ * response. A response stopped by the output cap, a refusal or a content
+ * filter is never parsed: it is a counted failure (the bounded 3-strike
+ * streak), never a zero-yield stamp and never published atoms. `other` and
+ * `tool_calls` (some local providers report a normal end as `other`) are
+ * parsed, but their empty answer is a counted failure, never a zero-yield
+ * stamp.
+ */
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
+import { MAX_DETERMINISTIC_FAILURES } from '../../src/core/cycle/extract-atoms.ts';
+import { runPhaseWithStoredPageFixtures as runPhaseExtractAtoms } from '../helpers/extract-atoms-page-fixtures.ts';
+import { resetPgliteState } from '../helpers/reset-pglite.ts';
+import type { ChatOpts, ChatResult } from '../../src/core/ai/gateway.ts';
+
+let engine: PGLiteEngine;
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+}, 60000);
+afterAll(async () => { await engine.disconnect(); });
+beforeEach(async () => { await resetPgliteState(engine); });
+
+const HASH = 'c'.repeat(16);
+const ATOMS = JSON.stringify([{ title: 'A durable insight', atom_type: 'insight', body: 'The insight body prose.', concepts: [] }]);
+
+function reply(text: string, stopReason: ChatResult['stopReason']): ChatResult {
+ return {
+ text, blocks: [{ type: 'text', text }], stopReason,
+ usage: { input_tokens: 100, output_tokens: 50, cache_read_tokens: 0, cache_creation_tokens: 0 },
+ model: 'anthropic:claude-haiku-4-5', providerId: 'anthropic',
+ } as ChatResult;
+}
+
+async function seed(slug: string): Promise<void> {
+ await engine.putPage(slug, { title: slug, type: 'note', compiled_truth: 'seed body prose' } as never, { sourceId: 'default' });
+}
+
+async function state(slug: string) {
+ const [row] = await engine.executeRaw<{ fail_count: number; tombstoned: boolean }>(
+ `SELECT scan.fail_count, scan.tombstoned FROM extract_atoms_page_state scan JOIN pages p ON p.id=scan.page_id
+ WHERE p.source_id='default' AND p.slug=$1 AND scan.content_hash=p.content_hash`, [slug]);
+ return row;
+}
+
+async function atomCount(): Promise<number> {
+ const [row] = await engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM pages WHERE type='atom' AND deleted_at IS NULL`);
+ return Number(row?.n ?? 0);
+}
+
+function run(slug: string, chat: (o: ChatOpts) => Promise<ChatResult>) {
+ return runPhaseExtractAtoms(engine, {
+ sourceId: 'default', _transcripts: [],
+ _pages: [{ slug, content: 'seed body prose', contentHash: HASH }],
+ _chat: chat,
+ });
+}
+
+describe('extract_atoms stop reasons (#6260)', () => {
+ test('length: a complete-looking atom array is not published and the page is not stamped; an end rerun extracts', async () => {
+ await seed('note/clipped');
+ const first = await run('note/clipped', async () => reply(ATOMS, 'length'));
+ expect(first.details.stopped_outputs).toBe(1);
+ expect(await atomCount()).toBe(0);
+ expect((await state('note/clipped'))?.tombstoned).toBe(false);
+ expect((await state('note/clipped'))?.fail_count).toBe(1);
+ const second = await run('note/clipped', async () => reply(ATOMS, 'end'));
+ expect(second.details.pages_processed).toBe(1);
+ expect(await atomCount()).toBe(1);
+ });
+
+ test('length: an empty array is never a zero-yield stamp', async () => {
+ await seed('note/clipped-empty');
+ await run('note/clipped-empty', async () => reply('[]', 'length'));
+ expect((await state('note/clipped-empty'))?.tombstoned).toBe(false);
+ });
+
+ for (const stop of ['refusal', 'content_filter'] as const) {
+ test(`${stop}: counts toward the ${MAX_DETERMINISTIC_FAILURES}-strike bound, then tombstones`, async () => {
+ const slug = `note/${stop}`;
+ await seed(slug);
+ let calls = 0;
+ const chat = async () => { calls++; return reply('[]', stop); };
+ for (let i = 1; i < MAX_DETERMINISTIC_FAILURES; i++) {
+ const r = await run(slug, chat);
+ expect(r.details.tombstoned_for_failures).toEqual([]);
+ expect((await state(slug))?.fail_count).toBe(i);
+ }
+ const last = await run(slug, chat);
+ expect(last.details.tombstoned_for_failures).toEqual([slug]);
+ expect(calls).toBe(MAX_DETERMINISTIC_FAILURES);
+ });
+ }
+
+ for (const stop of ['other', 'tool_calls'] as const) {
+ test(`${stop}: atoms are kept, but an empty answer is a counted failure, not a zero-yield stamp`, async () => {
+ await seed(`note/${stop}-empty`);
+ const empty = await run(`note/${stop}-empty`, async () => reply('[]', stop));
+ expect(empty.details.stopped_outputs).toBe(1);
+ expect(await state(`note/${stop}-empty`)).toEqual({ fail_count: 1, tombstoned: false });
+ await seed(`note/${stop}-atoms`);
+ const full = await run(`note/${stop}-atoms`, async () => reply(ATOMS, stop));
+ expect(full.details.pages_processed).toBe(1);
+ expect(await atomCount()).toBe(1);
+ });
+ }
+
+ test('transcripts: a length stop leaves the transcript rediscoverable', async () => {
+ const r = await runPhaseExtractAtoms(engine, {
+ sourceId: 'default', _pages: [],
+ _transcripts: [{ filePath: '/synthetic/2026-01-01-chat.txt', content: 'a chat', contentHash: 'd'.repeat(64) }],
+ _chat: async () => reply('[]', 'length'),
+ });
+ expect(r.details.stopped_outputs).toBe(1);
+ expect(r.details.tombstoned_transcripts).toEqual([]);
+ const rows = await engine.executeRaw<{ tombstoned: boolean }>(`SELECT tombstoned FROM extract_atoms_transcript_state`);
+ expect(rows.every((row) => row.tombstoned === false)).toBe(true);
+ });
+});
diff --git a/test/managed-atoms-stop-reason.test.ts b/test/managed-atoms-stop-reason.test.ts
new file mode 100644
index 0000000000..fd49700571
--- /dev/null
+++ b/test/managed-atoms-stop-reason.test.ts
@@ -0,0 +1,105 @@
+/**
+ * #6260 on a managed brain: a clipped atoms response (stopReason length,
+ * refusal or content_filter) is a failure receipt. It never publishes atoms,
+ * never retires the page's earlier atoms, and the next run asks for an
+ * approved retry instead of paying again; the approved retry with a complete
+ * answer extracts.
+ */
+import { afterAll, beforeAll, beforeEach, expect, test } from 'bun:test';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { __setChatTransportForTests, configureGateway, resetGateway } from '../src/core/ai/gateway.ts';
+import type { ChatResult } from '../src/core/ai/gateway.ts';
+import { runPhaseExtractAtoms } from '../src/core/cycle/extract-atoms.ts';
+import { disposePersistenceConsumer, stopPersistenceConsumer } from '../src/core/persistence/service.ts';
+import { MinionWorker } from '../src/core/minions/worker.ts';
+import { registerBuiltinHandlers } from '../src/commands/jobs.ts';
+import type { MinionJobContext } from '../src/core/minions/types.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+let engine: PGLiteEngine;
+beforeAll(async () => {
+ configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536, env: {} });
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+}, 60_000);
+beforeEach(async () => { await stopPersistenceConsumer(engine); await resetPgliteState(engine); });
+afterAll(async () => { __setChatTransportForTests(null); await engine.disconnect(); resetGateway(); });
+
+const atomsJson = (title: string) => JSON.stringify([{ title, atom_type: 'insight', body: `Body for ${title}.` }]);
+
+async function liveAtoms(): Promise<string[]> {
+ const rows = await engine.executeRaw<{ slug: string }>("SELECT slug FROM pages WHERE type='atom' AND deleted_at IS NULL ORDER BY slug");
+ return rows.map((row) => row.slug);
+}
+
+for (const stop of ['length', 'refusal', 'content_filter'] as const) {
+ test(`managed ${stop}: failure receipt, prior atoms kept, next run asks for an approved retry`, async () => {
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-managed-atom-stop-'));
+ try {
+ await withEnv({ GBRAIN_HOME: home }, async () => {
+ const write = (rev: number) => engine.putPage('notes/example', { type: 'note', title: 'Example',
+ compiled_truth: `A careful project record at revision ${rev}. `.repeat(40) }, { sourceId: 'default' });
+ let page = await write(1);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ let calls = 0;
+ let next: { text: string; stopReason: ChatResult['stopReason'] } = { text: atomsJson('Patience compounds'), stopReason: 'end' };
+ const chat = async (): Promise<ChatResult> => {
+ calls++;
+ return { text: next.text, blocks: [], stopReason: next.stopReason,
+ usage: { input_tokens: 10, output_tokens: 10, cache_read_tokens: 0, cache_creation_tokens: 0 },
+ model: 'anthropic:claude-haiku-4-5', providerId: 'anthropic' };
+ };
+ const extract = () => runPhaseExtractAtoms(engine, { _transcripts: [],
+ _pages: [{ slug: page.slug, content: page.compiled_truth, contentHash: page.content_hash! }], _chat: chat });
+
+ expect((await extract()).status).toBe('ok');
+ const prior = await liveAtoms();
+ expect(prior).toHaveLength(1);
+
+ await disposePersistenceConsumer(engine);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ page = await write(2);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ next = { text: '[]', stopReason: stop };
+ const clipped = await extract();
+ expect(clipped.status).toBe('warn');
+ expect(clipped.details?.stopped_outputs).toBe(1);
+ expect(calls).toBe(2);
+ expect(await liveAtoms()).toEqual(prior);
+ const receipt = (clipped.details?.write_requests as Array<{ request_id: string }>).at(-1)!;
+ expect(receipt.request_id).toBeTruthy();
+
+ await disposePersistenceConsumer(engine);
+ const again = await extract();
+ expect(calls).toBe(2);
+ expect(JSON.stringify(again.details?.failures)).toContain(`stopReason=${stop}`);
+ expect(JSON.stringify(again.details?.failures)).toContain('a new attempt needs approval');
+ expect(await liveAtoms()).toEqual(prior);
+
+ await disposePersistenceConsumer(engine);
+ next = { text: atomsJson('Hire slowly'), stopReason: 'end' };
+ __setChatTransportForTests(chat);
+ const worker = new MinionWorker(engine, { queue: 'fixture' });
+ await registerBuiltinHandlers(worker, engine, { quiet: true });
+ const job: MinionJobContext = { id: 951, name: 'extract-atoms-drain', data: { sourceId: 'default', retryRequestId: receipt.request_id }, attempts_made: 0,
+ signal: new AbortController().signal, deadlineAtMs: null, shutdownSignal: new AbortController().signal,
+ updateProgress: async () => {}, updateTokens: async () => {}, log: async () => {}, isActive: async () => true, readInbox: async () => [] };
+ const retried = await worker.getHandler('extract-atoms-drain')!(job) as Record<string, unknown>;
+ expect(retried.model_rerun).toBe(true);
+ expect(calls).toBe(3);
+ const after = await liveAtoms();
+ expect(after).toHaveLength(1);
+ expect(after[0]).toContain('hire-slowly');
+ });
+ } finally {
+ __setChatTransportForTests(null);
+ await stopPersistenceConsumer(engine);
+ rmSync(home, { recursive: true, force: true });
+ }
+ }, 60_000);
+}