Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(extract_atoms): partial disposition for an item cut at max_input_chars (#6503)
garrytan4b0886489fff
diff --git a/docs/architecture/key-files/core-cycle.md b/docs/architecture/key-files/core-cycle.mdindex 5b88376ba9..0f935ec235 100644--- a/docs/architecture/key-files/core-cycle.md+++ b/docs/architecture/key-files/core-cycle.md@@ -21,7 +21,8 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/cycle/extract-atoms-budget-notice.ts` — #6425: `drainBudgetNotice(result)` renders the `atom_drain_budget` notice a `budget`-stopped drain carries in `gbrain dream --drain --json` (spend, per-run cap, pages left; paid fix `gbrain config set cycle.extract_atoms.budget_usd <USD>`, verify `gbrain config get`), and `usd` formats the amounts for the stderr stop line. Dynamically imported by `dream.ts` so its notice-rendering imports stay out of the CLI flag scan. Tests: `test/dream-drain-failure-summary.serial.test.ts`.-- `src/core/cycle/extract-atoms.ts` — the extract_atoms lens phase: mines eligible pages into `atoms/<date>/<stem>-<hash>` pages. Transcript input is paste-stripped before the cut (#5812); discovery skips self-captures (#5820). Discovery and the backlog count append `connectorAtomExclusionSql` (`connector-atoms.ts`), so connector `email`/`meeting` pages stay out only when `cycle.extract_atoms.connector_pages` is false. The type allowlist is `unionExtractableTypes(packExtractable, packExcluded)`: the legacy floor (meeting, source, article, video, book, original) minus the floor types the active pack declares not extractable (`nonExtractableTypesFromPack`, #5756; a declared type without `extractable: true` is a pack decision, an undeclared type keeps the floor), plus the pack's `extractable: true` types, minus synthesis outputs; gbrain-base is unchanged, gbrain-recommended's `source: false` now holds for atoms as it did for facts. Pinned by `test/pack-extractable-floor-5756.test.ts`. A drain attempt passes `opts.attempt` (`budgetTracker`, `writeWait`) so its batches share one budget and one maintenance publish wait. Eligibility reads source-incarnation/page/full-hash-keyed derived scan state; scan and failure markers do not mutate canonical frontmatter. Managed extraction checks source-wide local authority and owner readiness before provider work, admits outputs plus a completion request together, and replays retained output without another model call. A failed managed batch is retried by the next run instead (#6325, `resumeManagedAtoms` in `persistence/atom-maintenance.ts`); an origin held after `MAX_DETERMINISTIC_FAILURES` (now defined in `extract-atoms-page-state.ts`, re-exported here) is skipped with no model call and counted in `details.held_failed`, never in `failures`. Managed atom files keep provisional source hashes; only the source-incarnation/page/full-hash durable completion receipt excludes an item from discovery and backlog counts. Unmanaged atom completion flips and their cardinality check share a transaction after provenance links persist, so a partial match rolls back and stays retryable. A page-derived atom upserts at its locator-folded slug, else a compatible legacy title-only slug; when both miss, the source page's live bound atoms are loaded once per page per run and exactly one JS-lowercased title match is adopted (a case-only title change never mints a duplicate; zero or several matches mint the new slug). Response parsing lives in `extract-atoms-parse.ts`. An undated source dates its atoms by the source page's creation date (`undated` for transcripts), never the run date. After an unmanaged item completes, `retireStaleAtoms` soft-deletes that source's atoms from earlier extractions (other or provisional `source_hash`) that this extraction did not re-produce. Hard `opts.signal` (chat call, pacing, checks before each item and commit) leaves no strike, receipt or rollup; soft `opts.stopSignal` stops before the next item.+- `src/core/cycle/extract-atoms-input.ts` — #6503 the input cap and the partial disposition. `resolveExtractAtomsInputCap` reads `cycle.extract_atoms.max_input_chars` (floor 1000; the older `max_source_chars`, floor 500, loses when both are set; default 50 000) before discovery. `extractAtomsInput(item, cap)` binds the cut once: paste-stripped for a transcript (#5812), UTF-8-safe, with `truncated` measured on the text the cap applied to. A cut item is extracted once from its head and gets a partial disposition instead of a completion: `input_truncated` counts it on the phase result (and the drain sums it into `input_truncated`, with one `[drain]` line), `inputTruncatedLine` is written to stderr naming the knob, the head atoms publish, no completion stamp is written and nothing is retired. `recordPartialDisposition` stores the cap under (content hash, cap) in `extract_atoms_page_state` / `extract_atoms_transcript_state.partial_input_chars` (migration v240; the page row is pinned to the identity discovery read), and on a managed brain the origin carries `partialInputChars`, which enters the run key, keeps the completion's checkpoint `partial`, skips the page-state stamp and the retirement, and marks the completion outcome `status: 'partial'`. Discovery and the backlog count skip a partial row like a tombstone (`PAGE_SCAN_STATE_EXCLUSION_SQL`, `tombstonedTranscriptsForHashes`, the partial checkpoint); `releasePartialDispositions` runs before discovery with the current cap and clears the rows and checkpoints a raised cap supersedes, so the item is eligible again with zero model calls in between; a content change is a new row. Resumed and budget-skipped items are not counted. `stampTranscriptTombstone` (v146) lives here too. Tests: `test/extract-atoms-input-truncated-6503.test.ts` (PGLite and Postgres, page and transcript, managed and unmanaged).+- `src/core/cycle/extract-atoms.ts` — the extract_atoms lens phase: mines eligible pages into `atoms/<date>/<stem>-<hash>` pages. The input cap, the cut and the partial disposition of a cut item are in `extract-atoms-input.ts` (#6503). Transcript input is paste-stripped before the cut (#5812); discovery skips self-captures (#5820). Discovery and the backlog count append `connectorAtomExclusionSql` (`connector-atoms.ts`), so connector `email`/`meeting` pages stay out only when `cycle.extract_atoms.connector_pages` is false. The type allowlist is `unionExtractableTypes(packExtractable, packExcluded)`: the legacy floor (meeting, source, article, video, book, original) minus the floor types the active pack declares not extractable (`nonExtractableTypesFromPack`, #5756; a declared type without `extractable: true` is a pack decision, an undeclared type keeps the floor), plus the pack's `extractable: true` types, minus synthesis outputs; gbrain-base is unchanged, gbrain-recommended's `source: false` now holds for atoms as it did for facts. Pinned by `test/pack-extractable-floor-5756.test.ts`. A drain attempt passes `opts.attempt` (`budgetTracker`, `writeWait`) so its batches share one budget and one maintenance publish wait. Eligibility reads source-incarnation/page/full-hash-keyed derived scan state; scan and failure markers do not mutate canonical frontmatter. Managed extraction checks source-wide local authority and owner readiness before provider work, admits outputs plus a completion request together, and replays retained output without another model call. A failed managed batch is retried by the next run instead (#6325, `resumeManagedAtoms` in `persistence/atom-maintenance.ts`); an origin held after `MAX_DETERMINISTIC_FAILURES` (now defined in `extract-atoms-page-state.ts`, re-exported here) is skipped with no model call and counted in `details.held_failed`, never in `failures`. Managed atom files keep provisional source hashes; only the source-incarnation/page/full-hash durable completion receipt excludes an item from discovery and backlog counts. Unmanaged atom completion flips and their cardinality check share a transaction after provenance links persist, so a partial match rolls back and stays retryable. A page-derived atom upserts at its locator-folded slug, else a compatible legacy title-only slug; when both miss, the source page's live bound atoms are loaded once per page per run and exactly one JS-lowercased title match is adopted (a case-only title change never mints a duplicate; zero or several matches mint the new slug). Response parsing lives in `extract-atoms-parse.ts`. An undated source dates its atoms by the source page's creation date (`undated` for transcripts), never the run date. After an unmanaged item completes (`completeUnmanagedItem`), `retireStaleAtoms` soft-deletes that source's atoms from earlier extractions (other or provisional `source_hash`) that this extraction did not re-produce; a cut item neither completes nor retires. Hard `opts.signal` (chat call, pacing, checks before each item and commit) leaves no strike, receipt or rollup; soft `opts.stopSignal` stops before the next item.Managed completion admits revision-pinned `managed_atom_delete` children alongside replacement pages, removes canonical files through the page deletion path, and commits its checkpoint only after every publication and retirement commits.Both paths prevent LLM-chosen titles that drift between extractions from piling up.Atom identity: page-derived atoms fold the source-page slug into the slug hash (8 chars, NUL-separated) so two same-date pages emitting the same title get DISTINCT slugs; the source CONTENT hash is deliberately NOT folded (a reworded source still upserts rather than duping); transcript atoms keep the legacy title-only 6-char hash. `resolvePageAtomSlug` adopts a legacy-slug atom with a compatible binding in place on re-extraction (upgrade idempotency — no migration, no duplicate), while `assertAtomImportBinding` fail-closed refuses to reuse a slug bound to a DIFFERENT source locator. Both share `isCompatibleAtomBinding(frontmatter, sourcePageSlug)` — the ONE definition of compatible: bound to THIS source page, or carrying no `source_slug`/`source_path` at all (pre-binding-era adoption, not a clobber); a `source_path`-bound legacy transcript atom or a different `source_slug` is a different origin, and a non-atom page squatting on the slug is refused. `source_quote` is verified at extraction time against the exact `truncateUtf8` prompt prefix the model saw (`locateQuote` advances by full code points): located quotes persist original characters + [start,end) offsets + `source_quote_verified`; unlocatable quotes are dropped with the atom kept. Edges write before the completion flip; per-item drain failures stay typed (bounded, sanitized, reconcilable). Transcript items carry the same failure-count/tombstone machinery as pages, in the `extract_atoms_transcript_state` table (keyed `(source_id, file_path, content_hash)`, 16-char hash prefix, so an edit is a new row): `recordItemFailureCount` counts a transcript's malformed output or prompt-level provider block (`providerContentBlockReason`; never feeds the outage halt) toward `MAX_DETERMINISTIC_FAILURES`, a zero-yield transcript tombstones immediately (as pages do), and `tombstonedTranscriptsForHashes` is the batch read-side gate mirroring `atomsExistingForHashes` (fail-open on error). Reported as `tombstoned_transcripts` (paths), separate from the page-slug `tombstoned_for_failures`. Malformed managed output requires a newly approved protected-job retry identity; publication retry reuses retained output and original/current grants.diff --git a/docs/operations/spend-controls.md b/docs/operations/spend-controls.mdindex 1f806061ca..a4b380ecdf 100644--- a/docs/operations/spend-controls.md+++ b/docs/operations/spend-controls.md@@ -319,7 +319,10 @@ thread or calendar event (message bodies, subjects, participants as rendered onthe page, up to `cycle.extract_atoms.max_input_chars`) is sent to theconfigured `extract_atoms` chat model (`models.dream.extract_atoms`, autility-tier model by default), under the caps above. Atoms already extracted-stay; opting out only stops new extraction.+stay; opting out only stops new extraction. A page longer than that cap is read+once up to the cap: its head atoms are kept, the phase reports it under+`input_truncated` with a stderr line, and the page is not marked complete; it+is skipped (not re-spent) until you raise the cap or the page changes.### Life Chronicle: automatic event extractiondiff --git a/src/commands/dream.ts b/src/commands/dream.tsindex a31f1241c4..2c2eac73d1 100644--- a/src/commands/dream.ts+++ b/src/commands/dream.ts@@ -657,6 +657,13 @@ async function runDrain(`[drain] ${result.failure_count} item failure(s)${omitted}${result.last_error ? `; last error: ${result.last_error}` : ''}\n`,);}+ // #6503: cut items are not failures and not complete; say so once per drain.+ if ((result.input_truncated ?? 0) > 0) {+ process.stderr.write(+ `[drain] ${result.input_truncated} item(s) cut at cycle.extract_atoms.max_input_chars: the model did not read their tail; ` ++ 'head atoms are kept, the items are not marked complete and are skipped until the cap rises (gbrain config set cycle.extract_atoms.max_input_chars <n>)\n',+ );+ }const { drainBudgetNotice, usd } = await import('../core/cycle/extract-atoms-budget-notice.ts');const budgetNotice = result.stopped === 'budget' ? drainBudgetNotice(result) : null;if (opts.json) {diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 3ff6430f39..a362ee9541 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -475,6 +475,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }{ since: '0.60.182.0', text: 'On a multimodal install, plain `gbrain embed --stale` now runs the image sweep (`--images`) before its text pass and reports it as `images` in `--json`; `gbrain embed --stale --images` works on managed brains, finds an image page with no recorded `source_path` by its slug, and exits non-zero naming the path it tried when no candidate has a file (it used to exit 0); the folded sweep only reports fileless pages. Doctor gains `image_embedding_coverage`.' },// wave 16 (GBRA-79){ since: '0.60.183.0', text: 'On a managed brain, automatic fact extraction (sync import, `put_page`, `extract_facts`, the sweep) now skips a candidate whose exact claim was forgotten in that source and visibility and publishes the other facts of the same entity, counting the skips as `withdrawn_skipped` on the entity and completion write receipts and the extraction result; before, one forgotten claim refused the entity\'s whole group with `fact_withdrawn`. Explicitly remembering the forgotten claim still refuses, and a purge tombstone still refuses the whole write. A claim forgotten after the facts were prepared refuses that entity\'s write with `revision_conflict` and a detail naming the withdrawal, publishing nothing. An extraction keyed by its input alone (no request id) recovers from such a refusal, and from a batch an older release refused for a forgotten claim, on its next run: the retained facts are re-admitted as a follow-up batch with no model call, at most three times per batch, and the refused receipts stay as they were. An extraction admitted under a request id replays its receipt; a new request_id extracts again.' },+ { since: '0.60.183.0', text: 'Atom extraction (`extract_atoms`, `gbrain dream --drain`) no longer marks an item complete when its text was cut at `cycle.extract_atoms.max_input_chars` (default 50,000 characters). The model reads the head once and its atoms are kept, but no completion stamp is written, no atom from an earlier extraction is retired, the phase result and the drain count the item under `input_truncated` with a stderr line naming the knob, and the item is skipped with no model call until the cap is raised or its content changes; raising the cap makes every such item eligible again on the next run. Before, a cut item was certified complete on its full content and a re-extraction could retire the atoms a larger cap had produced from its tail.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/cycle/extract-atoms-drain.ts b/src/core/cycle/extract-atoms-drain.tsindex a6a0373ddf..215d27f0fe 100644--- a/src/core/cycle/extract-atoms-drain.ts+++ b/src/core/cycle/extract-atoms-drain.ts@@ -114,6 +114,8 @@ export interface ExtractAtomsDrainDeps {failures?: Array<{ source: string; reason: string }>;budgetSkipped?: number;budget?: { spentUsd: number; capUsd: number };+ /** #6503: items the batch cut at `cycle.extract_atoms.max_input_chars` (partial disposition, not complete). */+ inputTruncated?: number;}>;/*** Count remaining eligible-but-unextracted pages, or null on query error.@@ -213,6 +215,8 @@ export interface ExtractAtomsDrainResult {/** #6425: on a `budget` stop, the attempt's spend and its per-run cap (`cycle.extract_atoms.budget_usd`). */spent_usd?: number;budget_usd?: number;+ /** #6503: items cut at the input cap across every batch; the model did not read their tails and they are not marked complete. */+ input_truncated?: number;}/**@@ -255,6 +259,7 @@ export async function runExtractAtomsDrain(let lastCount: number | null = null;let lockSignal: AbortSignal | null = null;let budget: { spentUsd: number; capUsd: number } | undefined;+ let inputTruncated = 0;const result = (stopped: DrainStop, remaining: number | null): ExtractAtomsDrainResult => ({phase: 'extract_atoms',status: providerFailure ? 'provider_failure' : 'ok',@@ -268,6 +273,7 @@ export async function runExtractAtomsDrain(omitted_failure_count: failureCount - failures.length,last_error: lastError,...(stopped === 'budget' && budget ? { spent_usd: budget.spentUsd, budget_usd: budget.capUsd } : {}),+ input_truncated: inputTruncated,});try {return await deps.withLock(async (signal) => {@@ -322,6 +328,7 @@ export async function runExtractAtomsDrain(const r = await deps.runBatch({ signal: hard.signal, stopSignal: soft.signal });extracted += r.extracted;skipped += r.skipped;+ inputTruncated += Math.max(0, Math.floor(Number(r.inputTruncated ?? 0)) || 0);batches++;// #4730: preserve typed per-item records (bounded, sanitized) while// keeping failure_count exact and reconcilable — count-only adapters@@ -533,6 +540,7 @@ export async function runExtractAtomsDrainForSource(failures: typedFailures,budgetSkipped: Number(d.pages_skipped_budget ?? 0) + Number(d.transcripts_skipped_budget ?? 0),budget: { spentUsd: Number(d.estimated_spend_usd ?? 0), capUsd: Number(d.budget_usd ?? 0) },+ inputTruncated: Number(d.input_truncated ?? 0),};},countRemaining: (signal) => countExtractAtomsBacklog(engine, extractionSourceId, { signal }),diff --git a/src/core/cycle/extract-atoms-input.ts b/src/core/cycle/extract-atoms-input.tsnew file mode 100644index 0000000000..ef0a024b21--- /dev/null+++ b/src/core/cycle/extract-atoms-input.ts@@ -0,0 +1,151 @@+/**+ * #6503: the extract_atoms input cap and what a cut item becomes.+ *+ * The model reads at most `cycle.extract_atoms.max_input_chars` characters of+ * an item (`cycle.extract_atoms.max_source_chars` is the older spelling of the+ * same knob). Before this module the cut was silent and the item was then+ * stamped complete on its full content hash, so the tail was never read and a+ * re-extraction could retire the atoms an earlier, larger-cap extraction had+ * produced from it. A cut item now gets a *partial disposition*: its head is+ * extracted once and the atoms are published, but no completion stamp is+ * written and no absent atom is retired. The disposition is recorded under+ * (content hash, cap) in `extract_atoms_page_state` /+ * `extract_atoms_transcript_state` (`partial_input_chars`) or, on a managed+ * brain, in the item's `managed-atoms` checkpoint (`partial`), so discovery+ * skips the item (it is not re-spent) until the cap rises or the content+ * changes. `releasePartialDispositions` runs before discovery with the current+ * cap and clears the records a raised cap supersedes.+ */+import type { BrainEngine } from '../engine.ts';+import type { SqlEngine } from '../persistence/model.ts';+import { truncateUtf8 } from '../text-safe.ts';+import { corpusTextForExtraction } from '../context/corpus-segments.ts';+import { AtomPageStateError, type AtomPageInput } from './extract-atoms-page-state.ts';++export const DEFAULT_EXTRACT_MAX_INPUT_CHARS = 50_000;+export const EXTRACT_MAX_INPUT_CHARS_KEY = 'cycle.extract_atoms.max_input_chars';++/**+ * The input cap: `max_source_chars` (floor 500) is read first so the newer+ * `max_input_chars` (floor 1000: below that the extractor sees a fragment too+ * small to yield atoms and every item burns budget for nothing) wins when both+ * are set. Fail-soft to the default on any config-read failure.+ */+export async function resolveExtractAtomsInputCap(engine: BrainEngine): Promise<number> {+ let cap = DEFAULT_EXTRACT_MAX_INPUT_CHARS;+ try {+ const legacy = Number(await engine.getConfig('cycle.extract_atoms.max_source_chars'));+ if (Number.isFinite(legacy) && legacy >= 500) cap = Math.floor(legacy);+ const configured = Number(await engine.getConfig(EXTRACT_MAX_INPUT_CHARS_KEY));+ if (Number.isFinite(configured) && configured >= 1_000) cap = Math.floor(configured);+ } catch { /* keep the default */ }+ return cap;+}++export type ExtractAtomsItem =+ | { kind: 'transcript'; filePath: string; content: string; contentHash: string }+ | ({ kind: 'page' } & AtomPageInput);++export interface ExtractAtomsInput {+ /** Exactly the text the model receives; quote provenance verifies against it. */+ promptContent: string;+ /** The text was longer than the cap: the model does not read its tail. */+ truncated: boolean;+ /** Characters of the text the cap applied to (post paste-strip for a transcript). */+ inputChars: number;+}++/**+ * Bind the cut once. Pastes are stripped from a transcript first (#5812), the+ * cap is applied UTF-8-safely (#4529/#4540: a bare slice can split a+ * surrogate pair), and `truncated` is measured on the text the cap applied to.+ */+export function extractAtomsInput(item: ExtractAtomsItem, maxInputChars: number): ExtractAtomsInput {+ const text = item.kind === 'transcript' ? corpusTextForExtraction(item.filePath, item.content) : item.content;+ const promptContent = truncateUtf8(text, maxInputChars);+ return { promptContent, truncated: promptContent.length < text.length, inputChars: text.length };+}++/** The one stderr line per cut item; names the knob that raises the cap. */+export function inputTruncatedLine(originLabel: string, input: ExtractAtomsInput, maxInputChars: number): string {+ return `[extract_atoms] ${originLabel}: input truncated to ${maxInputChars} of ${input.inputChars} chars; the model did not read the tail. ` ++ `Atoms from the head are kept, the item is not marked complete and is skipped until the cap rises: gbrain config set ${EXTRACT_MAX_INPUT_CHARS_KEY} <n>`;+}++/**+ * Clear the partial dispositions a raised cap supersedes, so the items they+ * covered are offered again by this run's discovery. Rows recorded at or+ * above the current cap stay (the model would read the same text again).+ * Fail-soft: a failed release leaves the items skipped, never re-spent.+ */+export async function releasePartialDispositions(engine: BrainEngine, sourceId: string, maxInputChars: number): Promise<void> {+ try {+ await engine.executeRaw(+ `UPDATE extract_atoms_page_state scan SET partial_input_chars=NULL, updated_at=now()+ FROM sources s WHERE s.id=$1 AND scan.source_incarnation=s.incarnation AND scan.partial_input_chars < $2`,+ [sourceId, maxInputChars]);+ await engine.executeRaw(+ `UPDATE extract_atoms_transcript_state SET partial_input_chars=NULL, updated_at=now()+ WHERE source_id=$1 AND partial_input_chars < $2`,+ [sourceId, maxInputChars]);+ await engine.executeRaw(+ `DELETE FROM op_checkpoints WHERE op='managed-atoms' AND completed_keys->0->>'sourceId'=$1+ AND (completed_keys->0->>'partial')::integer < $2`,+ [sourceId, maxInputChars]);+ } catch (err) {+ console.error(`[extract_atoms] partial-disposition release failed (cut items stay skipped): ${err instanceof Error ? err.message : String(err)}`);+ }+}++/**+ * Stamp the transcript-side tombstone (v146). The file-backed mirror of the+ * page scan state: transcripts have no frontmatter, and their discovery is+ * gated only by `atomsExistingForHashes` and this table, so a transcript that+ * yields no atom row has nothing else to mark it done and would be+ * re-attempted every cycle. The row is (source_id, file_path, content_hash)-+ * keyed, so an edited transcript is a different row and re-eligibilizes.+ * Fail-soft: the transcript stays rediscoverable.+ */+export async function stampTranscriptTombstone(engine: BrainEngine, sourceId: string, filePath: string, contentHash: string): Promise<void> {+ try {+ await engine.executeRaw(+ `INSERT INTO extract_atoms_transcript_state (source_id, file_path, content_hash, fail_count, tombstoned, updated_at)+ VALUES ($1, $2, $3, 0, TRUE, now())+ ON CONFLICT (source_id, file_path, content_hash) DO UPDATE SET tombstoned = TRUE, updated_at = now()`,+ [sourceId, filePath, contentHash.slice(0, 16)]);+ } catch { /* fail-soft: transcript stays rediscoverable */ }+}++/**+ * Record an unmanaged item's partial disposition under its current content+ * and the cap it was read under. The page row is pinned to the page identity+ * discovery read (the same predicate `writeAtomPageState` uses), so a page+ * that changed under the run records nothing and stays retryable.+ */+export async function recordPartialDisposition(engine: SqlEngine, sourceId: string, item: ExtractAtomsItem, maxInputChars: number): Promise<void> {+ if (item.kind === 'transcript') {+ await engine.executeRaw(+ `INSERT INTO extract_atoms_transcript_state (source_id, file_path, content_hash, fail_count, tombstoned, partial_input_chars, updated_at)+ VALUES ($1, $2, $3, 0, FALSE, $4, now())+ ON CONFLICT (source_id, file_path, content_hash) DO UPDATE SET partial_input_chars=EXCLUDED.partial_input_chars, updated_at=now()`,+ [sourceId, item.filePath, item.contentHash.slice(0, 16), maxInputChars]);+ return;+ }+ if (!item.identity) throw new AtomPageStateError('unpinned');+ const rows = await engine.executeRaw(+ `INSERT INTO extract_atoms_page_state (source_incarnation, page_id, content_hash, fail_count, tombstoned, partial_input_chars)+ SELECT s.incarnation, p.id, p.content_hash, 0, false, $8::integer+ FROM pages p JOIN sources s ON s.id=p.source_id+ WHERE p.id=$1 AND s.incarnation=$2::uuid AND p.source_id=$3 AND p.slug=$4+ AND p.content_hash=$5 AND p.knowledge_revision=$6::uuid AND p.compiled_truth=$7 AND p.deleted_at IS NULL+ FOR SHARE OF p, s+ ON CONFLICT (source_incarnation, page_id, content_hash) DO UPDATE+ SET partial_input_chars=EXCLUDED.partial_input_chars, updated_at=now()+ RETURNING page_id`,+ [item.identity.pageId, item.identity.sourceIncarnation, sourceId, item.slug, item.contentHash, item.identity.revision, item.content, maxInputChars])+ .catch((error: unknown) => {+ const code = error && typeof error === 'object' && 'code' in error ? error.code : undefined;+ throw new AtomPageStateError(code === '42P01' ? 'schema' : code === '42501' ? 'denied' : 'storage');+ });+ if (!rows.length) throw new AtomPageStateError('changed');+}diff --git a/src/core/cycle/extract-atoms.ts b/src/core/cycle/extract-atoms.tsindex 876492a832..f36f7e3243 100644--- a/src/core/cycle/extract-atoms.ts+++ b/src/core/cycle/extract-atoms.ts@@ -69,8 +69,7 @@ import { createGlobalLlmHaltTracker, haltedClassOf, providerContentBlockReason,import { importFromContent } from '../import-file.ts';import { derivedWriteThrough } from './derived-write-through.ts';import { serializeMarkdown } from '../markdown.ts';-import { truncateUtf8 } from '../text-safe.ts';-import { corpusTextForExtraction } from '../context/corpus-segments.ts';+import { DEFAULT_EXTRACT_MAX_INPUT_CHARS, extractAtomsInput, inputTruncatedLine, recordPartialDisposition, releasePartialDispositions, resolveExtractAtomsInputCap, stampTranscriptTombstone } from './extract-atoms-input.ts';import { claudeCliSelfSessionIds } from '../ai/providers/claude-cli-scratch.ts';import { BudgetExhausted, BudgetTracker, loadPricingOverrides } from '../budget/budget-tracker.ts';import type { MaintenanceWriteWait } from '../persistence/maintenance-wait.ts';@@ -105,7 +104,8 @@ const DEFAULT_BUDGET_USD = 0.3;// cycle.extract_atoms.* config keys (max_input_chars — with the #4529// legacy alias max_source_chars — plus max_output_tokens / pacing_ms).// Exported so tests pin the defaults instead of re-hardcoding the literals.-export const DEFAULT_EXTRACT_MAX_INPUT_CHARS = 50_000;+// The input cap and the cut live in extract-atoms-input.ts (#6503).+export { DEFAULT_EXTRACT_MAX_INPUT_CHARS };export const DEFAULT_EXTRACT_MAX_OUTPUT_TOKENS = 4096;export { MAX_DETERMINISTIC_FAILURES };@@ -148,10 +148,12 @@ const minCompiledTruthChars = (param: string) =>const RAW_SOURCE_HOLDER_EXCLUSION_SQL =`AND NOT (p.type = 'source' AND COALESCE(p.frontmatter ? 'raw', false))`;+// #6503: a partial row (the page was cut at the input cap) is skipped like a+// tombstone until releasePartialDispositions clears it under a raised cap.const PAGE_SCAN_STATE_EXCLUSION_SQL = `AND NOT EXISTS (SELECT 1 FROM extract_atoms_page_state scanWHERE scan.source_incarnation=(SELECT s.incarnation FROM sources s WHERE s.id=p.source_id)- AND scan.page_id=p.id AND scan.content_hash=p.content_hash AND scan.tombstoned+ AND scan.page_id=p.id AND scan.content_hash=p.content_hash AND (scan.tombstoned OR scan.partial_input_chars IS NOT NULL))`;/**@@ -609,7 +611,8 @@ export function transcriptStateKey(filePath: string, contentHash16: string): str* per-file probes, same fail-soft posture (on error return empty, i.e. treat* everything as live and re-attempt, which is the pre-v146 behaviour).*- * Only TOMBSTONED rows are returned. A row carrying an in-progress failure+ * Only TOMBSTONED rows and partial rows (#6503: cut at the input cap, skipped+ * until the cap rises) are returned. A row carrying an in-progress failure* streak (fail_count 1 or 2) is deliberately still live: those items must keep* being retried until the streak reaches MAX_DETERMINISTIC_FAILURES, exactly as* a page with `atoms_fail_count` below the bound stays in the page backlog.@@ -625,7 +628,7 @@ export async function tombstonedTranscriptsForHashes(`SELECT file_path, content_hashFROM extract_atoms_transcript_stateWHERE source_id = $1- AND tombstoned+ AND (tombstoned OR partial_input_chars IS NOT NULL)AND content_hash = ANY($2::text[])`,[sourceId, contentHash16s],);@@ -736,6 +739,11 @@ export async function runPhaseExtractAtoms(}}+ // #6503: the input cap is read before discovery so the partial dispositions+ // a raised cap supersedes are released and their items offered in this run.+ const maxInputChars = await resolveExtractAtomsInputCap(engine);+ if (!opts.dryRun) await releasePartialDispositions(engine, sourceId, maxInputChars);+// 1b. Get pages (test seam OR production discovery).// _pages === undefined triggers discovery; _pages: [] suppresses it// deliberately (transcript-only regression tests).@@ -894,10 +902,10 @@ export async function runPhaseExtractAtoms(const dateGrounding = await isConsumerDateGroundingOn(engine, 'atoms');let budgetCap = DEFAULT_BUDGET_USD;let explicitBudget = false; // operator SET cycle.extract_atoms.budget_usd- // #4529/#4540: the per-item input/output caps were hardcoded (slice(0, 50_000) +- // maxTokens: 4096). Operators on small-context or thinking models need to- // shrink/grow both without a code change; defaults are unchanged.- let maxInputChars = DEFAULT_EXTRACT_MAX_INPUT_CHARS;+ // #4529/#4540: the per-item output cap was hardcoded (maxTokens: 4096).+ // Operators on small-context or thinking models need to shrink/grow it+ // without a code change; the default is unchanged. The input cap was read+ // above (extract-atoms-input.ts).let maxOutputTokens = DEFAULT_EXTRACT_MAX_OUTPUT_TOKENS;let pacingMs = 0;try {@@ -907,21 +915,6 @@ export async function runPhaseExtractAtoms(const n = Number(configuredBudget);if (Number.isFinite(n) && n > 0) { budgetCap = n; explicitBudget = true; }}- // #4529: legacy input-cap key (its own floor of 500 chars, as landed).- // Read FIRST so the newer #4540 max_input_chars key below wins when- // both are set — they name the same knob.- const configuredMaxSourceChars = await engine.getConfig('cycle.extract_atoms.max_source_chars');- if (configuredMaxSourceChars) {- const n = Number(configuredMaxSourceChars);- if (Number.isFinite(n) && n >= 500) maxInputChars = Math.floor(n);- }- const configuredMaxInput = await engine.getConfig('cycle.extract_atoms.max_input_chars');- if (configuredMaxInput) {- const n = Number(configuredMaxInput);- // Floor of 1000 chars: below that the extractor sees a fragment too- // small to yield atoms and every page burns budget for nothing.- if (Number.isFinite(n) && n >= 1_000) maxInputChars = Math.floor(n);- }const configuredMaxOutput = await engine.getConfig('cycle.extract_atoms.max_output_tokens');if (configuredMaxOutput) {const n = Number(configuredMaxOutput);@@ -938,7 +931,7 @@ export async function runPhaseExtractAtoms(}} catch {// Keep safe defaults on any config-read failure: key-aware utility-tier- // model, $0.30 cap, default input cap (max_input_chars).+ // model, $0.30 cap, default output cap.}// A cap is enforceable only when the tracker can price every call under it:// the extraction chat model AND the embed route importFromContent calls.@@ -998,32 +991,12 @@ export async function runPhaseExtractAtoms(let hardFailureCount = 0;let writesPending = 0; // #5601: accepted atom batches still publishing (progress, not failures)let heldFailed = 0;+ let inputTruncated = 0; // #6503: items cut at the input cap this run (partial disposition, see extract-atoms-input.ts)async function stampAtomsScanHash(item: AtomPageInput): Promise<void> {await writeAtomPageState(engine, sourceId, item, 'complete');}- /**- * Stamp the transcript-side tombstone (v146). The file-backed mirror of- * `stampAtomsScanHash`: transcripts have no frontmatter, and their discovery- * is gated ONLY by `atomsExistingForHashes`, so a transcript that yields no- * atom row has nothing to mark it done and is re-attempted every cycle.- * Row is (source_id, file_path, content_hash)-keyed, so an edited transcript- * is a different row and re-eligibilizes automatically.- */- async function stampTranscriptTombstone(filePath: string, contentHash: string): Promise<void> {- try {- await engine.executeRaw(- `INSERT INTO extract_atoms_transcript_state- (source_id, file_path, content_hash, fail_count, tombstoned, updated_at)- VALUES ($1, $2, $3, 0, TRUE, now())- ON CONFLICT (source_id, file_path, content_hash)- DO UPDATE SET tombstoned = TRUE, updated_at = now()`,- [sourceId, filePath, contentHash.slice(0, 16)],- );- } catch { /* fail-soft: transcript stays rediscoverable */ }- }-/*** Durable per-item failure count, keyed to the CURRENT content hash so a* content edit resets the streak. Returns the new consecutive count, or@@ -1084,7 +1057,7 @@ export async function runPhaseExtractAtoms(await stampAtomsScanHash(item);tombstonedForFailures.push(item.slug);} else {- await stampTranscriptTombstone(item.filePath, item.contentHash);+ await stampTranscriptTombstone(engine, sourceId, item.filePath, item.contentHash);tombstonedTranscripts.push(item.filePath);}}@@ -1104,17 +1077,19 @@ export async function runPhaseExtractAtoms(// #4706: bind the cut ONCE. This is the exact text the model receives,// and quote provenance is verified against THIS rather than the full// item, so a quote can only verify against text the model actually saw.- // #4529/#4540: configurable input cap, cut UTF-8-safely (a bare .slice()- // can split a surrogate pair at the boundary); #5812 strips pastes first.- const promptContent = truncateUtf8(item.kind === 'transcript' ? corpusTextForExtraction(item.filePath, item.content) : item.content, maxInputChars);+ // #6503: a cut item is extracted once from its head and gets a partial+ // disposition instead of a completion stamp (extract-atoms-input.ts).+ const input = extractAtomsInput(item, maxInputChars);+ const { promptContent, truncated } = input;try {- const origin: AtomOrigin | null = managed ? await readAtomOrigin(engine, managed, item) : null;+ const origin: AtomOrigin | null = managed ? { ...await readAtomOrigin(engine, managed, item), ...(truncated ? { partialInputChars: maxInputChars } : {}) } : null;const visibility = origin?.visibility ?? effectiveVisibility(item.kind === 'transcript' ? { kind: 'transcript' } // #5525: { kind: 'page', page: await engine.getPage(item.slug, { sourceId }) });throwIfAborted(opts.signal, 'extract_atoms');const resumed = !opts.dryRun && managed && origin ? await resumeManagedAtoms(engine, managed, origin) : 'run';if (resumed === 'done') { duplicatesSkipped++; continue; }if (resumed === 'held') { heldFailed++; continue; } // #6325: settled after repeated failures; doctor lists it+ if (truncated) { inputTruncated++; console.error(inputTruncatedLine(originLabel, input, maxInputChars)); } // counted only for a model callconst result = await chat({model: extractModel,@@ -1165,8 +1140,9 @@ export async function runPhaseExtractAtoms(// file re-eligibilizes it — which is what makes the permanence safe.if (!opts.dryRun) {if (managed && origin) writeRequests.push(...await publishManagedAtoms(engine, managed, origin, []));+ else if (truncated) await recordPartialDisposition(engine, sourceId, item, maxInputChars);else if (item.kind === 'page') await stampAtomsScanHash(item);- else await stampTranscriptTombstone(item.filePath, item.contentHash);+ else await stampTranscriptTombstone(engine, sourceId, item.filePath, item.contentHash);}if (item.kind === 'transcript') transcriptsProcessed++;else pagesProcessed++;@@ -1313,16 +1289,12 @@ export async function runPhaseExtractAtoms(// source page. A crash between flip and stamp degrades to the legacy// atom-rows-mean-done semantics — safe, not lossy.throwIfAborted(opts.signal, 'extract_atoms');- await completeAtomReceipts(engine, sourceId, importedSlugs, hash16, item.kind === 'page' ? item : undefined);- // C-14: atoms are keyed by LLM-chosen titles, which drift between- // extractions. Once this extraction is complete, retire the atoms an- // earlier extraction of the same source produced that this one did not.- const retired = await retireStaleAtoms(engine, sourceId, item.kind === 'page'- ? { key: 'source_slug', value: item.slug } : { key: 'source_path', value: item.filePath }, hash16, importedSlugs);+ // #6503: a cut item keeps its atoms provisional (`pending:<hash>`, the upsert path when it runs+ // again), retires nothing and records its partial disposition instead of a completion stamp.+ const retired = truncated ? [] : await completeUnmanagedItem(engine, sourceId, item, hash16, importedSlugs);await atomFiles?.(importedSlugs, retired);- if (item.kind === 'page') {- await stampAtomsScanHash(item);- }+ if (truncated) await recordPartialDisposition(engine, sourceId, item, maxInputChars);+ else if (item.kind === 'page') await stampAtomsScanHash(item);}} else {totalAtomsExtracted += atoms.length; // count for dry-run reporting@@ -1445,7 +1417,8 @@ export async function runPhaseExtractAtoms((failures.length > 0 ? ` (${failures.length} failed)` : '') +(transcriptsSkipped + pagesSkipped > 0? ` (${transcriptsSkipped + pagesSkipped} budget-skipped)`- : ''),+ : '') ++ (inputTruncated > 0 ? ` (${inputTruncated} input-truncated: the model did not read the tail)` : ''),details: {atoms_extracted: totalAtomsExtracted,transcripts_processed: transcriptsProcessed,@@ -1457,6 +1430,7 @@ export async function runPhaseExtractAtoms(duplicates_skipped: duplicatesSkipped,write_pending: writesPending,held_failed: heldFailed,+ input_truncated: inputTruncated,failures,...(managed ? { write_requests: writeRequests } : {}),...(abortedGlobalError ? { aborted_global_error: abortedGlobalError } : {}),@@ -1473,6 +1447,20 @@ export async function runPhaseExtractAtoms(};}+/**+ * Completion receipt: flip provisional → real in one statement (only after+ * every atom AND provenance edge persisted). C-14: atoms are keyed by+ * LLM-chosen titles, which drift between extractions, so once this extraction+ * is complete, retire the atoms an earlier extraction of the same source+ * produced that this one did not. Returns the retired slugs.+ */+async function completeUnmanagedItem(engine: BrainEngine, sourceId: string,+ item: { kind: 'transcript'; filePath: string } | ({ kind: 'page' } & AtomPageInput), hash16: string, importedSlugs: string[]): Promise<string[]> {+ await completeAtomReceipts(engine, sourceId, importedSlugs, hash16, item.kind === 'page' ? item : undefined);+ return retireStaleAtoms(engine, sourceId, item.kind === 'page'+ ? { key: 'source_slug', value: item.slug } : { key: 'source_path', value: item.filePath }, hash16, importedSlugs);+}+/*** Soft-delete a source's atoms from earlier extractions (a different or* provisional source_hash) that the current, completed extraction did notdiff --git a/src/core/persistence/atom-maintenance.ts b/src/core/persistence/atom-maintenance.tsindex 1bab21c16e..494ded8e2d 100644--- a/src/core/persistence/atom-maintenance.ts+++ b/src/core/persistence/atom-maintenance.ts@@ -32,6 +32,8 @@ export interface AtomOrigin {revision: string | null;visibility: 'private' | 'world';generation?: number;+ /** #6503: the model read only the first `partialInputChars` characters; the batch records a partial disposition, not a completion. */+ partialInputChars?: number;}export interface ManagedAtomSession {sourceId: string;@@ -47,8 +49,8 @@ export interface ManagedAtomSession {}/** The run key a batch is admitted under and, for a retry, the checkpoint it advances (compare-and-set). */interface AtomClaim { runKey: string; checkpointKey?: string; expectedCheckpoint?: unknown }-/** One `managed-atoms` checkpoint row. `attempts` counts completed failures of its content; `held` marks the bound. */-interface AtomCheckpoint { requestId?: string; failure?: string; attempts?: number; held?: boolean }+/** One `managed-atoms` checkpoint row. `attempts` counts completed failures of its content; `held` marks the bound; `partial` the input cap a cut item was read under (#6503). */+interface AtomCheckpoint { requestId?: string; failure?: string; attempts?: number; held?: boolean; partial?: number }export type AtomResume = 'run' | 'done' | 'held';export interface AtomIntent extends Record<string, unknown> {kind: 'managed_atom_page' | 'managed_atom_delete' | 'managed_atom_complete';@@ -237,7 +239,9 @@ export async function bumpAtomGeneration(tx: BrainEngine, sourceId: string, inca* the drain and for an explicit retry (#5699).*/function atomInput(session: ManagedAtomSession, origin: AtomOrigin): unknown[] {- return ['managed-atoms-v1', session.incarnation, origin.kind, origin.locator, origin.pageId, origin.contentHash];+ // #6503: a cut item's run is keyed by the cap it was read under, so a raised cap is a new run (the partial checkpoint is released first).+ return ['managed-atoms-v1', session.incarnation, origin.kind, origin.locator, origin.pageId, origin.contentHash,+ ...(origin.partialInputChars ? ['partial', origin.partialInputChars] : [])];}/** A retirement's regeneration generation enters the drain's key above 0, so earlier receipts are not replayed. */@@ -407,7 +411,8 @@ export async function publishManagedAtoms(engine: BrainEngine, session: ManagedA...(target.revision ? { expected_revision: target.revision } : {}), content: atom.content, links: atom.links } as AtomIntent });}const originKey = origin.kind === 'page' ? 'source_slug' : 'source_path';- const retirements = failure ? [] : reviewedRetirements ?? await engine.executeRaw<ManagedAtomRetirement>(+ // #6503: a partial extraction read only the head, so it retires nothing an earlier extraction produced.+ const retirements = failure || origin.partialInputChars ? [] : reviewedRetirements ?? await engine.executeRaw<ManagedAtomRetirement>(`SELECT slug,id AS "pageId",knowledge_revision::text AS revision FROM pagesWHERE source_id=$1 AND type='atom' AND deleted_at IS NULLAND frontmatter->>'${originKey}'=$2@@ -526,7 +531,8 @@ export async function prepareManagedAtomMutation(engine: BrainEngine, row: Writeif (!snapshot) throw opError('revision_conflict', 'The accepted atom source page changed.',`Page ${p.origin.locator} in source ${row.source_id} is gone since atom batch ${row.request_id} was accepted, so the batch was not marked complete. Read the page to confirm; nothing more is extracted from a removed page.`,{ fix: pageFix(row.source_id, p.origin.locator) });- await writeAtomPageState(tx, row.source_id, { slug: p.origin.locator, content: snapshot.page.compiled_truth,+ // #6503: a partial batch stamps nothing; its checkpoint below carries the disposition.+ if (p.failure || !p.origin.partialInputChars) await writeAtomPageState(tx, row.source_id, { slug: p.origin.locator, content: snapshot.page.compiled_truth,contentHash: p.origin.contentHash, identity: { pageId: p.origin.pageId!, sourceIncarnation: row.source_incarnation,revision: p.origin.revision! } }, p.failure ? 'failure' : 'complete');}@@ -535,7 +541,8 @@ export async function prepareManagedAtomMutation(engine: BrainEngine, row: Writeconst attempts = (prior?.failure ? Number(prior.attempts ?? 1) : 0) + 1;const checkpoint = JSON.stringify([{ sourceId: row.source_id, incarnation: row.source_incarnation, requestId: row.request_id,kind: p.origin.kind, locator: p.origin.locator, pageId: p.origin.pageId, contentHash: p.origin.contentHash,- ...(p.failure ? { failure: p.failure, attempts, ...(attempts >= MAX_DETERMINISTIC_FAILURES ? { held: true } : {}) } : {}) }]);+ ...(p.failure ? { failure: p.failure, attempts, ...(attempts >= MAX_DETERMINISTIC_FAILURES ? { held: true } : {}) }+ : p.origin.partialInputChars ? { partial: p.origin.partialInputChars } : {}) }]);await tx.executeRaw(`INSERT INTO op_checkpoints(op,fingerprint,completed_keys) VALUES('managed-atoms',$1,$2::text::jsonb)ON CONFLICT(op,fingerprint) DO NOTHING`, [p.runKey, checkpoint]);if (p.checkpointKey) {@@ -547,7 +554,8 @@ export async function prepareManagedAtomMutation(engine: BrainEngine, row: Write`Another atom run completed source ${row.source_id}'s atom checkpoint after retry ${row.request_id} was accepted, so the retry was not recorded. Read the retry receipt; the later run's atoms stand.`,{ fix: receiptFix(row.request_id) });}- return { status: p.failure ? 'failed' : 'completed',+ return { status: p.failure ? 'failed' : p.origin.partialInputChars ? 'partial' : 'completed',+ ...(p.origin.partialInputChars && !p.failure ? { partial_input_chars: p.origin.partialInputChars } : {}),atoms: committed.filter(child => child.kind === 'managed_atom_page').length,retired: committed.filter(child => child.kind === 'managed_atom_delete').length,...(p.failure ? { failure: p.failure } : {}) };diff --git a/src/core/pglite-schema.generated.ts b/src/core/pglite-schema.generated.tsindex 0daa221e71..b7a88ae47f 100644--- a/src/core/pglite-schema.generated.ts+++ b/src/core/pglite-schema.generated.ts@@ -539,6 +539,7 @@ CREATE TABLE IF NOT EXISTS extract_atoms_transcript_state (fail_count INTEGER NOT NULL DEFAULT 0,tombstoned BOOLEAN NOT NULL DEFAULT FALSE,updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ partial_input_chars INTEGER,PRIMARY KEY (source_id, file_path, content_hash));CREATE INDEX IF NOT EXISTS extract_atoms_transcript_state_tombstoned_idx@@ -1184,6 +1185,7 @@ CREATE TABLE IF NOT EXISTS extract_atoms_page_state (fail_count INTEGER NOT NULL DEFAULT 0 CHECK (fail_count >= 0),tombstoned BOOLEAN NOT NULL DEFAULT false,updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ partial_input_chars INTEGER,PRIMARY KEY (source_incarnation, page_id, content_hash));CREATE INDEX IF NOT EXISTS extract_atoms_page_state_tombstoned_idxdiff --git a/src/core/schema-embedded.generated.ts b/src/core/schema-embedded.generated.tsindex e59fc584fa..0c7af87148 100644--- a/src/core/schema-embedded.generated.ts+++ b/src/core/schema-embedded.generated.ts@@ -997,6 +997,9 @@ CREATE TABLE IF NOT EXISTS extract_atoms_transcript_state (fail_count INTEGER NOT NULL DEFAULT 0,tombstoned BOOLEAN NOT NULL DEFAULT FALSE,updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ -- #6503 (migration v240): the max_input_chars cap a cut transcript was read+ -- under; discovery skips it until the cap rises. NULL when not partial.+ partial_input_chars INTEGER,PRIMARY KEY (source_id, file_path, content_hash));CREATE INDEX IF NOT EXISTS extract_atoms_transcript_state_tombstoned_idx@@ -1894,6 +1897,9 @@ CREATE TABLE IF NOT EXISTS extract_atoms_page_state (fail_count INTEGER NOT NULL DEFAULT 0 CHECK (fail_count >= 0),tombstoned BOOLEAN NOT NULL DEFAULT false,updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ -- #6503 (migration v240): the max_input_chars cap a cut page was read under;+ -- discovery skips it until the cap rises. NULL when not partial.+ partial_input_chars INTEGER,PRIMARY KEY (source_incarnation, page_id, content_hash));CREATE INDEX IF NOT EXISTS extract_atoms_page_state_tombstoned_idxdiff --git a/src/core/schema-migrations/latest.generated.ts b/src/core/schema-migrations/latest.generated.tsindex 2f887f8c54..e5b395aed4 100644--- a/src/core/schema-migrations/latest.generated.ts+++ b/src/core/schema-migrations/latest.generated.ts@@ -4,4 +4,4 @@// The highest schema migration version (migrate.ts LATEST_VERSION), importable without// loading the migrations themselves.-export const LATEST_SCHEMA_VERSION = 239;+export const LATEST_SCHEMA_VERSION = 240;diff --git a/src/core/schema-migrations/registry.generated.ts b/src/core/schema-migrations/registry.generated.tsindex f2297d1e85..a1c03e24f4 100644--- a/src/core/schema-migrations/registry.generated.ts+++ b/src/core/schema-migrations/registry.generated.ts@@ -240,6 +240,7 @@ import { v236 } from './v236-open-loops-counterparty-source.ts';import { v237 } from './v237-facts-question-recall-indexes.ts';import { v238 } from './v238-persistence-client-request-id.ts';import { v239 } from './v239-extract-rollup-halt-reasons.ts';+import { v240 } from './v240-extract-atoms-partial-input.ts';// Array order is historical (see HISTORICAL_ARRAY_ORDER in the generator); the// runner sorts by version before applying.@@ -478,4 +479,5 @@ export const MIGRATIONS: Migration[] = [v237,v238,v239,+ v240,];diff --git a/src/core/schema-migrations/v240-extract-atoms-partial-input.ts b/src/core/schema-migrations/v240-extract-atoms-partial-input.tsnew file mode 100644index 0000000000..47f2e08e84--- /dev/null+++ b/src/core/schema-migrations/v240-extract-atoms-partial-input.ts@@ -0,0 +1,23 @@+import type { Migration } from './types.ts';++// Applied by src/core/migrate.ts on the next initSchema(); the fresh-install+// copies of both tables in src/schema.sql carry the same column.+export const v240: Migration = {+ version: 240,+ name: 'extract_atoms_partial_input',+ // #6503: an item cut at `cycle.extract_atoms.max_input_chars` is no longer+ // stamped complete. Its row records the cap the model read it under+ // (`partial_input_chars`): discovery skips the item while the cap is at+ // or below that value and offers it again once the cap rises (the phase+ // clears rows under the new cap before discovery) or the content changes+ // (a new content_hash is a new row). NULL on complete and failed rows.+ // DDL only: a metadata-only ADD COLUMN under migrate.ts's lock timeout,+ // no row rewritten, nothing to backfill.+ idempotent: true,+ sql: `+ ALTER TABLE extract_atoms_page_state+ ADD COLUMN IF NOT EXISTS partial_input_chars INTEGER;+ ALTER TABLE extract_atoms_transcript_state+ ADD COLUMN IF NOT EXISTS partial_input_chars INTEGER;+ `,+};diff --git a/src/schema.sql b/src/schema.sqlindex dd1d2724de..44fc8846f2 100644--- a/src/schema.sql+++ b/src/schema.sql@@ -993,6 +993,9 @@ CREATE TABLE IF NOT EXISTS extract_atoms_transcript_state (fail_count INTEGER NOT NULL DEFAULT 0,tombstoned BOOLEAN NOT NULL DEFAULT FALSE,updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ -- #6503 (migration v240): the max_input_chars cap a cut transcript was read+ -- under; discovery skips it until the cap rises. NULL when not partial.+ partial_input_chars INTEGER,PRIMARY KEY (source_id, file_path, content_hash));CREATE INDEX IF NOT EXISTS extract_atoms_transcript_state_tombstoned_idx@@ -1890,6 +1893,9 @@ CREATE TABLE IF NOT EXISTS extract_atoms_page_state (fail_count INTEGER NOT NULL DEFAULT 0 CHECK (fail_count >= 0),tombstoned BOOLEAN NOT NULL DEFAULT false,updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ -- #6503 (migration v240): the max_input_chars cap a cut page was read under;+ -- discovery skips it until the cap rises. NULL when not partial.+ partial_input_chars INTEGER,PRIMARY KEY (source_incarnation, page_id, content_hash));CREATE INDEX IF NOT EXISTS extract_atoms_page_state_tombstoned_idxdiff --git a/test/extract-atoms-input-truncated-6503.test.ts b/test/extract-atoms-input-truncated-6503.test.tsnew file mode 100644index 0000000000..3bc684bea3--- /dev/null+++ b/test/extract-atoms-input-truncated-6503.test.ts@@ -0,0 +1,272 @@+/**+ * #6503 (wave 16 G2.4, UC2): an extract_atoms item longer than+ * `cycle.extract_atoms.max_input_chars` is cut silently and then certified+ * complete. The model never reads the tail, the completion stamp lands on the+ * full content hash, and the unmanaged path retires every atom an earlier,+ * larger-cap extraction produced from that tail (the managed path publishes+ * the same retirement against the full origin).+ *+ * After the fix a cut item gets a *partial disposition*: `input_truncated`+ * counts it on the phase result (and the drain sums it), one stderr line+ * names the knob, the head is extracted once and its atoms published, no+ * completion stamp is written, nothing is retired, and the item is skipped+ * with zero model calls until the cap rises or the content changes. A 10k+ * item under the cap still completes as before.+ *+ * Every case drives the real `runPhaseExtractAtoms` with a stub model, on+ * PGLite and Postgres, unmanaged (page discovery + the transcript seam) and+ * managed (origin publication through the coordinator). The truncation+ * assertions come first in each case so the master failure is the missing+ * counter / the false completion, never the schema the fix adds.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { createHash } from 'node:crypto';+import type { BrainEngine } from '../src/core/engine.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import type { ChatOpts, ChatResult } from '../src/core/ai/gateway.ts';+import { runPhaseExtractAtoms } from '../src/core/cycle/extract-atoms.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { managedBrain } from './helpers/managed-brain.ts';+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';++const CAP = 2_000;+const KNOB = 'cycle.extract_atoms.max_input_chars';+const sha = (text: string) => createHash('sha256').update(text).digest('hex');++/** Prose with a surrogate pair straddling the cut so the UTF-8-safe boundary is exercised. */+function longText(label: string, chars = 3_000): string {+ const head = `${label}: the team decided to measure every launch against clear exit criteria. `.repeat(40).slice(0, CAP - 1);+ return (head + '😀' + ` ${label} tail: the model must never see this tail sentence about the hidden decision. `.repeat(40)).slice(0, chars);+}+const shortText = (label: string) => `${label}: a short page that fits under the cap and completes as before. `.repeat(20).slice(0, 1_200);++function stubChat(atoms: Array<{ title: string; body: string }> | (() => Array<{ title: string; body: string }>)) {+ const calls: string[] = [];+ const chat = async (opts: ChatOpts): Promise<ChatResult> => {+ const last = opts.messages[opts.messages.length - 1];+ calls.push(typeof last.content === 'string' ? last.content : JSON.stringify(last.content));+ const list = typeof atoms === 'function' ? atoms() : atoms;+ const text = JSON.stringify(list.map(atom => ({ ...atom, 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' };+ };+ return { calls, chat };+}++async function captureStderr<T>(run: () => Promise<T>): Promise<{ value: T; lines: string[] }> {+ const lines: string[] = [];+ const original = console.error;+ console.error = (...args: unknown[]) => { lines.push(args.map(String).join(' ')); };+ try { return { value: await run(), lines }; } finally { console.error = original; }+}++const atomRows = (engine: BrainEngine, sourceId: string, originKey: 'source_slug' | 'source_path', origin: string) =>+ engine.executeRaw<{ slug: string; source_hash: string; deleted: boolean }>(+ `SELECT slug, frontmatter->>'source_hash' AS source_hash, deleted_at IS NOT NULL AS deleted FROM pages+ WHERE source_id=$1 AND type='atom' AND frontmatter->>$2=$3 ORDER BY slug`, [sourceId, originKey, origin]);++const pageState = (engine: BrainEngine, sourceId: string, slug: string) =>+ engine.executeRaw<{ tombstoned: boolean; partial_input_chars: number | null }>(+ `SELECT scan.tombstoned, scan.partial_input_chars FROM extract_atoms_page_state scan+ JOIN pages p ON p.id=scan.page_id AND scan.content_hash=p.content_hash WHERE p.source_id=$1 AND p.slug=$2`, [sourceId, slug]);++const transcriptState = (engine: BrainEngine, sourceId: string, filePath: string) =>+ engine.executeRaw<{ tombstoned: boolean; partial_input_chars: number | null }>(+ 'SELECT tombstoned, partial_input_chars FROM extract_atoms_transcript_state WHERE source_id=$1 AND file_path=$2', [sourceId, filePath]);++/** An atom an earlier, larger-cap extraction derived from the item's tail: another source_hash, same origin. */+async function seedTailAtom(engine: BrainEngine, sourceId: string, originKey: 'source_slug' | 'source_path', origin: string, slug: string, managed: boolean) {+ await engine.putPage(slug, { type: 'atom', title: 'Hidden decision from the tail', compiled_truth: 'The tail decision was recorded by an earlier extraction.',+ frontmatter: { atom_type: 'insight', [originKey]: origin, source_hash: 'earlier0000cap00', dream_generated: true, ...(managed ? { managed_extraction: true } : {}) } }, { sourceId });+}++describe('extract_atoms partial disposition for items cut at max_input_chars (#6503)', () => {+ const engines: Array<{ backend: string; engine: BrainEngine; databaseUrl?: string }> = [];+ let closePostgres: (() => Promise<void>) | undefined;++ beforeAll(async () => {+ for (const backend of testBackends()) {+ if (backend === 'pglite') {+ const engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ engines.push({ backend, engine });+ } else {+ const databaseUrl = requirePostgresTestDatabase();+ const isolated = await isolatedPersistencePostgres(databaseUrl);+ engines.push({ backend, engine: isolated.engine, databaseUrl });+ closePostgres = isolated.close;+ }+ }+ }, 120_000);+ afterAll(async () => {+ for (const { engine } of engines) { await disposePersistenceConsumer(engine); await engine.disconnect(); }+ await closePostgres?.();+ });++ test('the counter, the stderr line and the post-filter measurement: a cut page and transcript count, a short page and a paste-only overflow do not', async () => {+ for (const { backend, engine } of engines) {+ await engine.setConfig(KNOB, String(CAP));+ const sourceId = `cut-count-${backend}`;+ await engine.executeRaw('INSERT INTO sources(id,name) VALUES($1,$1)', [sourceId]);+ await engine.putPage('notes/long-page', { type: 'note', title: 'Long', compiled_truth: longText('page'), timeline: '' }, { sourceId });+ await engine.putPage('notes/short-page', { type: 'note', title: 'Short', compiled_truth: shortText('short'), timeline: '' }, { sourceId });+ const cutTranscript = `[user]\n${longText('transcript')}\n`;+ const pasteTranscript = `[user]\nKeep this: <pasted_content id="1">\n${'x'.repeat(5_000)}\n</pasted_content>\n${shortText('after paste')}\n`;+ const { calls, chat } = stubChat([]);+ const { value: result, lines } = await captureStderr(() => runPhaseExtractAtoms(engine, {+ sourceId, _chat: chat,+ _transcripts: [+ { filePath: `/corpus/${sourceId}/cut.txt`, content: cutTranscript, contentHash: sha(cutTranscript) },+ { filePath: `/corpus/${sourceId}/paste.txt`, content: pasteTranscript, contentHash: sha(pasteTranscript) },+ ],+ }));+ expect(result.details.input_truncated, backend).toBe(2);+ expect(result.summary, backend).toContain('2 input-truncated');+ const truncatedLines = lines.filter(line => line.includes('input truncated'));+ expect(truncatedLines, backend).toHaveLength(2);+ for (const line of truncatedLines) expect(line, backend).toContain(KNOB);+ expect(truncatedLines.some(line => line.includes('notes/long-page')), backend).toBe(true);+ expect(truncatedLines.some(line => line.includes('/cut.txt')), backend).toBe(true);+ expect(calls, backend).toHaveLength(4);+ for (const sent of calls) {+ expect(sent, backend).not.toContain('tail sentence');+ expect(sent, backend).not.toMatch(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])/);+ }+ expect(calls.some(sent => sent.includes('x'.repeat(100))), backend).toBe(false);+ expect((await pageState(engine, sourceId, 'notes/long-page'))[0], backend).toEqual({ tombstoned: false, partial_input_chars: CAP });+ expect((await pageState(engine, sourceId, 'notes/short-page'))[0], backend).toMatchObject({ tombstoned: true, partial_input_chars: null });+ expect((await transcriptState(engine, sourceId, `/corpus/${sourceId}/cut.txt`))[0], backend).toEqual({ tombstoned: false, partial_input_chars: CAP });+ expect((await transcriptState(engine, sourceId, `/corpus/${sourceId}/paste.txt`))[0], backend).toMatchObject({ tombstoned: true, partial_input_chars: null });+ }+ }, 120_000);++ test('unmanaged page: head atoms publish, the tail atom survives, no completion stamp, skipped until the cap rises', async () => {+ for (const { backend, engine } of engines) {+ await engine.setConfig(KNOB, String(CAP));+ const sourceId = `cut-page-${backend}`;+ await engine.executeRaw('INSERT INTO sources(id,name) VALUES($1,$1)', [sourceId]);+ const slug = 'notes/long-decision';+ await engine.putPage(slug, { type: 'note', title: 'Long decision', compiled_truth: longText('decision'), timeline: '' }, { sourceId });+ await seedTailAtom(engine, sourceId, 'source_slug', slug, 'atoms/tail-decision', false);+ const first = stubChat([{ title: 'Measure every launch', body: 'Measure every launch against clear exit criteria.' }]);+ const result = await runPhaseExtractAtoms(engine, { sourceId, _chat: first.chat, _transcripts: [] });+ expect(result.details.input_truncated, backend).toBe(1);+ expect(first.calls, backend).toHaveLength(1);+ let atoms = await atomRows(engine, sourceId, 'source_slug', slug);+ expect(atoms.find(atom => atom.slug === 'atoms/tail-decision'), backend).toMatchObject({ deleted: false, source_hash: 'earlier0000cap00' });+ const head = atoms.filter(atom => atom.slug !== 'atoms/tail-decision');+ expect(head, backend).toHaveLength(1);+ expect(head[0].source_hash, backend).toMatch(/^pending:/);+ expect((await pageState(engine, sourceId, slug))[0], backend).toEqual({ tombstoned: false, partial_input_chars: CAP });++ const second = stubChat([]);+ const again = await runPhaseExtractAtoms(engine, { sourceId, _chat: second.chat, _transcripts: [] });+ expect(second.calls, backend).toHaveLength(0);+ expect(again.details.pages_total ?? 0, backend).toBe(0);++ await engine.setConfig(KNOB, String(CAP * 2));+ const third = stubChat([{ title: 'Measure every launch', body: 'Measure every launch against clear exit criteria.' }]);+ const released = await runPhaseExtractAtoms(engine, { sourceId, _chat: third.chat, _transcripts: [] });+ expect(third.calls, backend).toHaveLength(1);+ expect(third.calls[0], backend).toContain('tail sentence');+ expect(released.details.input_truncated, backend).toBe(0);+ atoms = await atomRows(engine, sourceId, 'source_slug', slug);+ expect(atoms.find(atom => atom.slug === 'atoms/tail-decision')?.deleted, backend).toBe(true);+ const page = (await engine.getPage(slug, { sourceId }))!;+ expect(atoms.filter(atom => !atom.deleted).map(atom => atom.source_hash), backend).toEqual([page.content_hash!.slice(0, 16)]);+ expect((await pageState(engine, sourceId, slug))[0], backend).toMatchObject({ tombstoned: true, partial_input_chars: null });+ }+ }, 120_000);++ test('unmanaged transcript: the same disposition through the transcript seam', async () => {+ for (const { backend, engine } of engines) {+ await engine.setConfig(KNOB, String(CAP));+ const sourceId = `cut-transcript-${backend}`;+ await engine.executeRaw('INSERT INTO sources(id,name) VALUES($1,$1)', [sourceId]);+ const filePath = `/corpus/${sourceId}/session.txt`;+ const content = `[user]\n${longText('session')}\n`;+ const transcripts = [{ filePath, content, contentHash: sha(content) }];+ await seedTailAtom(engine, sourceId, 'source_path', filePath, 'atoms/tail-session', false);+ const first = stubChat([{ title: 'Exit criteria first', body: 'Set exit criteria before measuring.' }]);+ const result = await runPhaseExtractAtoms(engine, { sourceId, _chat: first.chat, _transcripts: transcripts, _pages: [] });+ expect(result.details.input_truncated, backend).toBe(1);+ expect(first.calls, backend).toHaveLength(1);+ let atoms = await atomRows(engine, sourceId, 'source_path', filePath);+ expect(atoms.find(atom => atom.slug === 'atoms/tail-session'), backend).toMatchObject({ deleted: false });+ expect(atoms.filter(atom => atom.slug !== 'atoms/tail-session').map(atom => atom.source_hash), backend).toEqual([`pending:${sha(content).slice(0, 16)}`]);+ expect((await transcriptState(engine, sourceId, filePath))[0], backend).toEqual({ tombstoned: false, partial_input_chars: CAP });++ const second = stubChat([]);+ const again = await runPhaseExtractAtoms(engine, { sourceId, _chat: second.chat, _transcripts: transcripts, _pages: [] });+ expect(second.calls, backend).toHaveLength(0);+ expect(again.details.duplicates_skipped, backend).toBe(1);+ expect(again.details.input_truncated, backend).toBe(0);++ await engine.setConfig(KNOB, String(CAP * 2));+ const third = stubChat([{ title: 'Exit criteria first', body: 'Set exit criteria before measuring.' }]);+ await runPhaseExtractAtoms(engine, { sourceId, _chat: third.chat, _transcripts: transcripts, _pages: [] });+ expect(third.calls, backend).toHaveLength(1);+ expect(third.calls[0], backend).toContain('tail sentence');+ atoms = await atomRows(engine, sourceId, 'source_path', filePath);+ expect(atoms.find(atom => atom.slug === 'atoms/tail-session')?.deleted, backend).toBe(true);+ expect(atoms.filter(atom => !atom.deleted).map(atom => atom.source_hash), backend).toEqual([sha(content).slice(0, 16)]);+ expect((await transcriptState(engine, sourceId, filePath))[0], backend).toMatchObject({ partial_input_chars: null });+ }+ }, 120_000);++ test('managed page: the origin publishes head atoms with no retirement and a partial checkpoint; a raised cap is a new run', async () => {+ for (const backend of testBackends()) {+ const databaseUrl = backend === 'postgres' ? requirePostgresTestDatabase() : undefined;+ const slug = 'notes/managed-long-decision';+ await managedBrain(async ({ engine }) => {+ const page = (await engine.getPage(slug, { sourceId: 'default' }))!;+ const item = { slug, content: page.compiled_truth, contentHash: page.content_hash! };+ const first = stubChat([{ title: 'Measure every launch', body: 'Measure every launch against clear exit criteria.' }]);+ const result = await runPhaseExtractAtoms(engine, { sourceId: 'default', _chat: first.chat, _transcripts: [], _pages: [item] });+ await disposePersistenceConsumer(engine);+ expect(result.details.input_truncated, backend).toBe(1);+ expect(result.status, backend).toBe('ok');+ expect(first.calls, backend).toHaveLength(1);+ const atoms = await atomRows(engine, 'default', 'source_slug', slug);+ expect(atoms.find(atom => atom.slug === 'atoms/managed-tail-decision'), backend).toMatchObject({ deleted: false });+ expect(atoms.filter(atom => atom.slug !== 'atoms/managed-tail-decision' && !atom.deleted), backend).toHaveLength(1);+ const checkpoints = await engine.executeRaw<{ partial: string | null; failure: string | null }>(+ `SELECT completed_keys->0->>'partial' AS partial, completed_keys->0->>'failure' AS failure FROM op_checkpoints+ WHERE op='managed-atoms' AND completed_keys->0->>'locator'=$1`, [slug]);+ expect(checkpoints, backend).toEqual([{ partial: String(CAP), failure: null }]);+ expect(await pageState(engine, 'default', slug), backend).toEqual([]);+ const completions = await engine.executeRaw<{ outcome: { status: string; retired: number } }>(+ "SELECT outcome FROM persistence_requests WHERE slug='__managed_atom_complete__' ORDER BY sequence");+ expect(completions.map(row => row.outcome.status), backend).toEqual(['partial']);+ expect(completions[0].outcome.retired, backend).toBe(0);++ const second = stubChat([]);+ const again = await runPhaseExtractAtoms(engine, { sourceId: 'default', _chat: second.chat, _transcripts: [], _pages: [item] });+ await disposePersistenceConsumer(engine);+ expect(second.calls, backend).toHaveLength(0);+ expect(again.details.duplicates_skipped, backend).toBe(1);+ expect(again.details.input_truncated, backend).toBe(0);++ await engine.setConfig(KNOB, String(CAP * 2));+ const third = stubChat([{ title: 'Measure every launch', body: 'Measure every launch against clear exit criteria.' }]);+ const released = await runPhaseExtractAtoms(engine, { sourceId: 'default', _chat: third.chat, _transcripts: [], _pages: [item] });+ await disposePersistenceConsumer(engine);+ expect(third.calls, backend).toHaveLength(1);+ expect(third.calls[0], backend).toContain('tail sentence');+ expect(released.details.input_truncated, backend).toBe(0);+ const after = await atomRows(engine, 'default', 'source_slug', slug);+ expect(after.find(atom => atom.slug === 'atoms/managed-tail-decision')?.deleted, backend).toBe(true);+ expect((await engine.executeRaw<{ status: string }>(+ "SELECT outcome->>'status' AS status FROM persistence_requests WHERE slug='__managed_atom_complete__' ORDER BY sequence")).map(row => row.status), backend)+ .toEqual(['partial', 'completed']);+ expect((await pageState(engine, 'default', slug))[0], backend).toMatchObject({ tombstoned: true });+ }, { databaseUrl, setup: async ({ engine }) => {+ await engine.setConfig(KNOB, String(CAP));+ await engine.putPage(slug, { type: 'note', title: 'Managed long decision', compiled_truth: longText('managed'), timeline: '' }, { sourceId: 'default' });+ await seedTailAtom(engine, 'default', 'source_slug', slug, 'atoms/managed-tail-decision', true);+ } });+ }+ }, 180_000);+});diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-default.json b/test/fixtures/goldens/catalog/pglite-engine-init-default.jsonindex cbf296ad1e..04b31896ac 100644--- a/test/fixtures/goldens/catalog/pglite-engine-init-default.json+++ b/test/fixtures/goldens/catalog/pglite-engine-init-default.json@@ -1914,7 +1914,8 @@"3 content_hash text/text NOT NULL","4 fail_count integer/int4 NOT NULL DEFAULT 0","5 tombstoned boolean/bool NOT NULL DEFAULT false",- "6 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"+ "6 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",+ "7 partial_input_chars integer/int4 NULL"],"flags": "relkind=r rls=true force_rls=false"},@@ -1925,7 +1926,8 @@"3 content_hash text/text NOT NULL","4 fail_count integer/int4 NOT NULL DEFAULT 0","5 tombstoned boolean/bool NOT NULL DEFAULT false",- "6 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"+ "6 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",+ "7 partial_input_chars integer/int4 NULL"],"flags": "relkind=r rls=false force_rls=false"},diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.jsonindex 152c1ca406..57f2a4b9d0 100644--- a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json+++ b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json@@ -1914,7 +1914,8 @@"3 content_hash text/text NOT NULL","4 fail_count integer/int4 NOT NULL DEFAULT 0","5 tombstoned boolean/bool NOT NULL DEFAULT false",- "6 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"+ "6 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",+ "7 partial_input_chars integer/int4 NULL"],"flags": "relkind=r rls=true force_rls=false"},@@ -1925,7 +1926,8 @@"3 content_hash text/text NOT NULL","4 fail_count integer/int4 NOT NULL DEFAULT 0","5 tombstoned boolean/bool NOT NULL DEFAULT false",- "6 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"+ "6 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",+ "7 partial_input_chars integer/int4 NULL"],"flags": "relkind=r rls=false force_rls=false"},diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.jsonindex e856bc2caa..f43c5c04f7 100644--- a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json+++ b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json@@ -1910,7 +1910,8 @@"3 content_hash text/text NOT NULL","4 fail_count integer/int4 NOT NULL DEFAULT 0","5 tombstoned boolean/bool NOT NULL DEFAULT false",- "6 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"+ "6 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",+ "7 partial_input_chars integer/int4 NULL"],"flags": "relkind=r rls=true force_rls=false"},@@ -1921,7 +1922,8 @@"3 content_hash text/text NOT NULL","4 fail_count integer/int4 NOT NULL DEFAULT 0","5 tombstoned boolean/bool NOT NULL DEFAULT false",- "6 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"+ "6 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",+ "7 partial_input_chars integer/int4 NULL"],"flags": "relkind=r rls=false force_rls=false"},diff --git a/test/fixtures/goldens/catalog/pglite-schema-blob-default.json b/test/fixtures/goldens/catalog/pglite-schema-blob-default.jsonindex 0f36bcf4cf..e143d172ef 100644--- a/test/fixtures/goldens/catalog/pglite-schema-blob-default.json+++ b/test/fixtures/goldens/catalog/pglite-schema-blob-default.json@@ -1406,7 +1406,8 @@"3 content_hash text/text NOT NULL","4 fail_count integer/int4 NOT NULL DEFAULT 0","5 tombstoned boolean/bool NOT NULL DEFAULT false",- "6 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"+ "6 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",+ "7 partial_input_chars integer/int4 NULL"],"flags": "relkind=r rls=false force_rls=false"},@@ -1417,7 +1418,8 @@"3 content_hash text/text NOT NULL","4 fail_count integer/int4 NOT NULL DEFAULT 0","5 tombstoned boolean/bool NOT NULL DEFAULT false",- "6 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"+ "6 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",+ "7 partial_input_chars integer/int4 NULL"],"flags": "relkind=r rls=false force_rls=false"},diff --git a/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json b/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.jsonindex 00ecc19cf1..f63bd4bc31 100644--- a/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json+++ b/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json@@ -1406,7 +1406,8 @@"3 content_hash text/text NOT NULL","4 fail_count integer/int4 NOT NULL DEFAULT 0","5 tombstoned boolean/bool NOT NULL DEFAULT false",- "6 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"+ "6 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",+ "7 partial_input_chars integer/int4 NULL"],"flags": "relkind=r rls=false force_rls=false"},@@ -1417,7 +1418,8 @@"3 content_hash text/text NOT NULL","4 fail_count integer/int4 NOT NULL DEFAULT 0","5 tombstoned boolean/bool NOT NULL DEFAULT false",- "6 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"+ "6 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",+ "7 partial_input_chars integer/int4 NULL"],"flags": "relkind=r rls=false force_rls=false"},diff --git a/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json b/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.jsonindex 113a0c3928..3208a2f918 100644--- a/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json+++ b/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json@@ -1405,7 +1405,8 @@"3 content_hash text/text NOT NULL","4 fail_count integer/int4 NOT NULL DEFAULT 0","5 tombstoned boolean/bool NOT NULL DEFAULT false",- "6 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"+ "6 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",+ "7 partial_input_chars integer/int4 NULL"],"flags": "relkind=r rls=false force_rls=false"},@@ -1416,7 +1417,8 @@"3 content_hash text/text NOT NULL","4 fail_count integer/int4 NOT NULL DEFAULT 0","5 tombstoned boolean/bool NOT NULL DEFAULT false",- "6 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"+ "6 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",+ "7 partial_input_chars integer/int4 NULL"],"flags": "relkind=r rls=false force_rls=false"},diff --git a/test/fixtures/goldens/migrations/records.json b/test/fixtures/goldens/migrations/records.jsonindex 21e023ce33..7e9c59d9ae 100644--- a/test/fixtures/goldens/migrations/records.json+++ b/test/fixtures/goldens/migrations/records.json@@ -1,6 +1,6 @@{"golden": {- "count": 234,+ "count": 235,"gaps": [17,18,@@ -52,7 +52,7 @@"sqlQueryForEngine": "71fb1ccec1b22cdc1662876dbd8c17ed81e9ab83485c6965cdf5caa4fc4a4ab5","verifyProjectionStatistics": "0d231b04ecfbc5a4109d6fca9567bf4e8c9e9db6c3fbbb35212e026579ed6f67"},- "latest": 239,+ "latest": 240,"records": [{"handler": {@@ -3623,6 +3623,19 @@"transaction": "absent","verify": "absent","version": 239+ },+ {+ "handler": "absent",+ "idempotent": true,+ "name": "extract_atoms_partial_input",+ "sql": {+ "length": 211,+ "sha256": "fca4778c549c2441c058f76d9b4dd756dbe4568c8d478d9485dca342b3d45bb7"+ },+ "sqlFor": "absent",+ "transaction": "absent",+ "verify": "absent",+ "version": 240}],"versions": [@@ -3859,7 +3872,8 @@236,237,238,- 239+ 239,+ 240]},"normalizer": "migrations-record-v1"diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex 11b2570a83..eff284878b 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -33,6 +33,7 @@ test/embed-stale-images-managed-6529.test.tstest/embedding-completion-atomic.serial.test.tstest/engine-sql-facts-keyset.test.tstest/extract-all-stamp-intersection.serial.test.ts+test/extract-atoms-input-truncated-6503.test.tstest/extract-endpoint-revision.serial.test.tstest/extract-entities-managed.test.tstest/extract-timeline-from-meetings-managed.test.ts