Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(#7190): keep write replies frozen for same-ID replays; get_write_request carries the live applied block
garrytan24c689ba7170
diff --git a/docs/architecture/key-files/managed-sync-bookkeeping.md b/docs/architecture/key-files/managed-sync-bookkeeping.mdindex 6fc1f8e78f..40540675ce 100644--- a/docs/architecture/key-files/managed-sync-bookkeeping.md+++ b/docs/architecture/key-files/managed-sync-bookkeeping.md@@ -47,8 +47,8 @@ run, and the supersession of a checkpoint whose cursor another run replaced. The- `src/core/serve-head-watcher.ts` + `src/core/persistence/sync-freshness.ts` + `src/commands/doctor/checks/managed-sync-latency.ts` — #6858 ask 6: on-commit sync and its latency metric. `startServeHeadWatcher` (two call sites: `installResidentTickers` in `src/commands/serve.ts`, stopped before `shutdownDelegatedSync`, and `runServeHttp` in `src/commands/serve-http.ts`, beside `startMovementWatch` and stopped on the same shutdown path) re-reads `sync.on_commit` every 30 s; while on it polls `git rev-parse HEAD` in each managed source checkout this host owns (`GBRAIN_SERVE_HEAD_POLL_MS`, default 3 s; an `fs.watch` on the git dir only nudges the poll), debounces 3 s (`GBRAIN_SERVE_HEAD_DEBOUNCE_MS`) and starts one managed sync through the unchanged `startDelegatedSync` with this host's `cli` registration. It never starts beside a running delegated sync or a held drain lease (the move stays pending and fires once after), skips a HEAD `sources.last_commit` already has, resumes a resumable stop up to `MAX_RESUMES`, and logs each distinct error once. `readSyncFreshness` samples committed `managed_sync_import` receipts of the last 24 h (not first syncs or working-tree entries): commit time is the git committer time of `intent.target`, searchable is `completed_at`, embedded is the page's newest `content_chunks.embedded_at` once every chunk has one, sampled only from a receipt no later committed write to the same page supersedes and only at or after its `completed_at`; p50/p95 in one aggregate over the `persistence_requests_sync_watermark` predicate. `gbrain sync status` (the `freshness` block) and `gbrain status` print it; doctor `managed_sync_latency` grades p95 against `sync.freshness_target_seconds` (default 300; fail over max(1 h, target)) only with `sync.on_commit` on or a target set. Tests: `test/serve-head-watcher.test.ts`, `test/serve-head-watcher-managed.serial.test.ts`, `test/serve-http-head-watcher.serial.test.ts`, `test/sync-freshness-6858.test.ts`. #7189: each `SourceFreshness` carries `behind` (`readGitBehind`, injectable `BehindReader`: `rev-list --count <last_commit>..HEAD` and the oldest of those commits' committer age; null without a checkout or a synced commit), printed by `formatSyncFreshness`.- `src/core/persistence/sync-status.ts` (status coherence) — GBRA-150: `state: blocked` means the source cannot advance (the drain outcome's meaning); a file hold that waits on a person while the source keeps syncing reads `synced` with reason `held_needs_human`, `needs_human` and `next` unchanged (`test/sync-status-blocked-definition.test.ts`); `detail` adds `landing` / `landing_read` (`landing-gaps.ts`). #7189: a `last_error` whose cursor failure row (`op_checkpoints` `managed-sync-failure`) is older than the source's newest committed managed-sync receipt carries `superseded` and sets neither `needs_human`, `state` nor `next` (`liveError`); `needs_human_from` names the hold or the error.- `src/core/persistence/resolve-paths.ts` — GBRA-150 `resolveSourcePaths`: what gbrain did with each file path of a source, by its own rules, so a landing check stops copying them. Per path: the sync slug (`resolveSlugForPath`), presence in the last synced commit and at HEAD (Git object reads), the skip reason (`unsyncableReason`, plus `typed_frontmatter` for a skipped metafile), the open hold, the live page by origin (`source_path`) and by slug (`slug_owner` when another file owns it, so a case-folded twin never reads as this file's page), a differing frontmatter `slug:`, chunk and embedding counts (`listEmbeddingStateRows` with its `slugs` filter), and one of `RESOLVE_PATH_STATES` with `searchable` (true / 'keyword' / false), `why` and an existing-command `fix`. Bounded: at most 200 paths, indexed lookups only, nothing written. Tests: `test/sources-resolve-path.test.ts`.-- `src/core/page-searchability.ts` — #7190 `readPageSearchability`: each live page's state, `searchable: true | 'keyword' | false`, chunks, `unembedded` (visible chunks with a NULL active-column vector) and `embedding_hold`, folded from `listEmbeddingStateRows` and the budget-hold read. Shared by resolve-path and write receipts; `gbrain pages status` (#7181) can compose it with its Git view.-- `src/core/persistence/applied-watermark.ts` — #7190 `readAppliedWatermark` (sources status, MCP `sources_status`, `sync --json`) and the cheap `readWriteWatermark` (receipts): `indexed_through` is `sources.last_commit` (only a finished pass moves it), `embedded_through` reads the oldest page with a NULL vector (held pages count), `committed_through_request` is one below the oldest unsettled request of the incarnation, `pending` adds requests, files behind HEAD, held files and withheld deletes, `writer_heartbeat` is the drain-lease holder and its last progress (redacted for remote callers).-- `src/core/persistence/write-applied.ts` — #7190 `readWriteApplied` / `withWriteApplied`: the `applied` block on page-write, `remember` and `get_write_request` receipts (`searchable_yet`, state, gap, sequence, write watermark). A failed read omits the block and never fails the write.+- `src/core/page-searchability.ts` — #7190 `readPageSearchability`: each live page's state, `searchable: true | 'keyword' | false`, chunks, `unembedded` (visible chunks with a NULL active-column vector) and `embedding_hold`, folded from `listEmbeddingStateRows` and the budget-hold read. Shared by resolve-path and `get_write_request`'s `applied`; `gbrain pages status` (#7181) can compose it with its Git view.+- `src/core/persistence/applied-watermark.ts` — #7190 `readAppliedWatermark` (sources status, MCP `sources_status`, `sync --json`) and the cheap `readWriteWatermark` (`get_write_request`): `indexed_through` is `sources.last_commit` (only a finished pass moves it), `embedded_through` reads the oldest page with a NULL vector (held pages count), `committed_through_request` is one below the oldest unsettled request of the incarnation, `pending` adds requests, files behind HEAD, held files and withheld deletes, `writer_heartbeat` is the drain-lease holder and its last progress (redacted for remote callers).+- `src/core/persistence/write-applied.ts` — #7190 `readWriteApplied`: the live `applied` block on `get_write_request` (`searchable_yet`, state, gap, sequence, write watermark). Write replies stay frozen so same-request-id replays return them unchanged.- `src/core/persistence/landing-gaps.ts` — GBRA-150 `readLandingGaps`: committed managed_sync receipts of the last 24 h (at most 2,000, newest first through the watermark index, 2 s statement probe; a timeout reads `unknown`, never ok) whose page is still missing, has chunks waiting for vectors, has no chunks, or is quarantined past `sync.freshness_target_seconds`; one row per page with reason and fix. Consumers: `sync status --detail` `landing` / `landing_read` (`sync-status.ts`) and doctor `sync_landing_gaps`. Tests: `test/sync-landing-gaps.test.ts`.- `src/commands/doctor/checks/landing-gaps.ts` — GBRA-150 doctor `sync_landing_gaps` (registered after `partial_embedding`, one of `CHEAP_INCIDENT_CHECKS`): warns per source with the gap count by reason and the first fix from `readLandingGaps`; `unknown` read stays a warning, never ok. Tests: `test/doctor-sync-landing-gaps.test.ts`.diff --git a/docs/guides/resolve-paths.md b/docs/guides/resolve-paths.mdindex a903eda952..c227cd0eca 100644--- a/docs/guides/resolve-paths.md+++ b/docs/guides/resolve-paths.md@@ -67,7 +67,7 @@ keeps syncing reads `synced` with reason `held_needs_human`; `needs_human` and `## Is my write searchable yet?-Every page write receipt (`put_page`, `capture`, `remember`, `edit_page` and the other page writes, and `get_write_request`) carries `applied`, read when the reply is built:+`gbrain write-request <request_id> --json` (MCP `get_write_request`) carries `applied`, read live each time. The write's own reply stays frozen, so a same-request-id replay returns it unchanged; read the receipt for the live answer:| Field | Meaning ||---|---|@@ -79,7 +79,7 @@ Every page write receipt (`put_page`, `capture`, `remember`, `edit_page` and the| `sequence` | the request's journal sequence; the write has settled once it is at or below `watermark.committed_through_request` || `watermark` | `indexed_through`, `committed_through_request` and `requests_pending` of the source (indexed reads only) |-A receipt whose watermark read fails leaves `applied` out; the write itself is unaffected.+A receipt read whose watermark read fails leaves `applied` out.## The source watermarkdiff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 7baf1cf97d..99f58a3943 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -1050,7 +1050,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;// GBRA-150 (nested typed metafiles become pages): Garry, "take all recommendations" (2026-10-20), answering the proposal to import typed non-root index.md/README.md. `since` is stamped at the merge slot.{ since: '0.60.337.0', text: 'Sync now imports a folder-scaffolding file below a source\'s root (`index.md`, `README.md`, `log.md`, `schema.md` or `RESOLVER.md`) as a page when its frontmatter has `type:` or `title:`, for example `projects/acme-example/index.md`. A bare one at any depth and every one at the source root stay skipped. The first sync after the upgrade imports the existing typed files once and deletes or rewrites nothing else; deleting such a file later soft-deletes its page. `gbrain config set sync.metafile_pages off` restores the old skip. Default change approved by Garry, "take all recommendations", 2026-10-20.' },// #7190 (GBRA-150): per-source applied-through watermark. `since` is stamped at the merge slot.- { since: 'TBD', id: 'applied_watermark_7190', text: 'Page write receipts (`put_page`, `capture`, `remember`, `edit_page` and the other page writes) and `get_write_request` now carry `applied`: whether the write is searchable yet (`searchable_yet`, `searchable`, `state`), the gap (`requests_ahead`, `unembedded_chunks`) and the source\'s write watermark (`indexed_through`, `committed_through_request`, `requests_pending`). Each reply costs a few indexed reads more. `gbrain sources status --json`, MCP `sources_status` and `gbrain sync --json` add a `watermark` per source: `indexed_through` (the last commit a finished sync pass reached; a deadline-stopped or partial pass never moves it), `embedded_through` (held pages count as not embedded), `committed_through_request`, `pending` (requests, commits and files behind HEAD, held files, withheld deletes) and `writer_heartbeat` (the drain-lease holder and its last progress).' },+ { since: 'TBD', id: 'applied_watermark_7190', text: '`get_write_request` (`gbrain write-request <id>`) now carries `applied`, read live: whether the write is searchable yet (`searchable_yet`, `searchable`, `state`), the gap (`requests_ahead`, `unembedded_chunks`), the request `sequence` and the source\'s write watermark (`indexed_through`, `committed_through_request`, `requests_pending`); a write\'s own reply is unchanged. `gbrain sources status --json`, MCP `sources_status` and `gbrain sync --json` add a `watermark` per source: `indexed_through` (the last commit a finished sync pass reached; a deadline-stopped or partial pass never moves it), `embedded_through` (held pages count as not embedded), `committed_through_request`, `pending` (requests, commits and files behind HEAD, held files, withheld deletes) and `writer_heartbeat` (the drain-lease holder and its last progress).' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/persistence/applied-watermark.ts b/src/core/persistence/applied-watermark.tsindex de3b9c8d6a..8aa898313b 100644--- a/src/core/persistence/applied-watermark.ts+++ b/src/core/persistence/applied-watermark.ts@@ -19,7 +19,7 @@* save or a pass-row write); `stalled` after HOLDER_STALL_MS without progress. A remote caller sees the holder's* kind and times, never its host, pid or job id.*- * `readWriteWatermark` is the cheap subset a write receipt carries (indexed reads only, no git, no lease read).+ * `readWriteWatermark` is the cheap subset `get_write_request` carries (indexed reads only, no git, no lease read).* Read-only; nothing is scheduled or written.*/import type { BrainEngine } from '../engine.ts';@@ -83,7 +83,7 @@ export const readGitFilesBehind: FilesBehindReader = async (root, from) => {return diff.error ? null : diff.stdout.split('\0').filter(Boolean).length;};-/** The cheap watermark every write receipt carries: the source row, and two reads on the request journal's indexes. */+/** The cheap watermark `get_write_request` carries: the source row, and two reads on the request journal's indexes. */export async function readWriteWatermark(engine: Pick<BrainEngine, 'executeRaw'>, sourceId: string, now = Date.now()): Promise<WriteWatermark> {const [row] = await engine.executeRaw<{ last_commit: string | null; last_sync_at: unknown; pending_min: number | string | null;pending_count: number | string; pending_since: unknown }>(`SELECT s.last_commit, s.last_sync_at, p.pending_min, p.pending_count, p.pending_sincediff --git a/src/core/persistence/import-mutations.ts b/src/core/persistence/import-mutations.tsindex c3c985b4d1..afd54b13d0 100644--- a/src/core/persistence/import-mutations.ts+++ b/src/core/persistence/import-mutations.ts@@ -8,7 +8,8 @@ import { opError, OperationError, type OperationContext } from '../ops/contract.import { currentSubmissionAuthority } from '../minions/submission-authority.ts';import { currentVerifiedLocalWriter, localHostId } from './identity.ts';import { getWorktreeBinding } from './ownership.ts';-import { SCREENING_SHARED_READS, answerPageWrite, batchSharedReads, emitFenceNotice, initializeLocalPersistence, preparePageAdmission, requestPrincipalForContext, withBatchAdmission } from './page-mutations.ts';+import { SCREENING_SHARED_READS, batchSharedReads, emitFenceNotice, initializeLocalPersistence, pendingAwareResponse, preparePageAdmission, requestPrincipalForContext, withBatchAdmission,+ withLiveSearchable } from './page-mutations.ts';import { admitBatch } from './page-batch.ts';import { writeOutcomeUnknown } from './admission-retry.ts';import { assertPersistenceAccepting, waitForWrites } from './service.ts';@@ -272,7 +273,7 @@ async function submitManagedImports(ctx: OperationContext, batch: string, paramsawait Promise.all(rows.map(async (entry, position) => {try {// #7106: a new segmented page over 4 MiB replies at commit with `searchable: 'pending'`, read live here.- const response = await answerPageWrite(ctx, done[position]!, { gateHold: false });+ const response = await withLiveSearchable(ctx, pendingAwareResponse(ctx, done[position]!));if (entry.admitted) emitFenceNotice(ctx, response, done[position]!.slug);settled[entry.index] = { status: 'fulfilled', value: { ...response, ...(entry.typeWarning ? { type_warning: entry.typeWarning } : {}),...(entry.slugAdvisory ? { slug_advisory: entry.slugAdvisory } : {}) } };diff --git a/src/core/persistence/memory-mutations.ts b/src/core/persistence/memory-mutations.tsindex 13ce959fb7..e19517ccf6 100644--- a/src/core/persistence/memory-mutations.ts+++ b/src/core/persistence/memory-mutations.ts@@ -1,5 +1,4 @@import { throwIfHeld } from '../trust/gate-outcomes.ts';-import { withWriteApplied } from './write-applied.ts';import { guardRemoteForget, remoteForgetRaced, supersessionGuarded } from '../trust/supersede-handlers.ts';import { randomUUID } from 'node:crypto';import type { OperationContext } from '../ops/contract.ts';@@ -160,10 +159,7 @@ async function inferRememberTarget(ctx: OperationContext, sourceId: string, sourexport async function submitRememberMutation(ctx: OperationContext, params: Record<string, unknown>, waitMs?: number): Promise<Record<string, unknown>> {registerMutationPreparer('remember', prepareMemoryMutation);const sub = await submission(ctx, 'remember', params);- if (sub.prior) {- const prior = await waitForWrite(ctx.engine, sub.prior, ctx.config, waitMs ?? ctx.writeWaitMs);- return withWriteApplied(ctx.engine, prior, () => throwIfHeld(writeResponse(prior)));- }+ if (sub.prior) return throwIfHeld(writeResponse(await waitForWrite(ctx.engine, sub.prior, ctx.config, waitMs ?? ctx.writeWaitMs)));const { p, sourceId, principal, callerIntent, requestId, clientRequestId } = sub;const [source] = await ctx.engine.executeRaw<RememberSource>("SELECT incarnation,archived,local_path,config->>'kind' AS kind FROM sources WHERE id=$1", [sourceId]);@@ -196,8 +192,7 @@ export async function submitRememberMutation(ctx: OperationContext, params: Reco...(linked ? { entity_inferred: linked.via } : {}), ...(inference && 'warning' in inference ? { entity_warning: inference.warning } : {}),session_id: ctx.sessionId ?? null },authority, worktreeId: writeThrough ? binding?.worktree_id : null, topologyGeneration: writeThrough ? binding?.topology_generation : null });- const settled = await waitForWrite(ctx.engine, row, ctx.config, waitMs ?? ctx.writeWaitMs);- const response = await withWriteApplied(ctx.engine, settled, () => throwIfHeld(writeResponse(settled)));+ const response = throwIfHeld(writeResponse(await waitForWrite(ctx.engine, row, ctx.config, waitMs ?? ctx.writeWaitMs)));emitFenceNotice(ctx, response, row.slug);return response;}diff --git a/src/core/persistence/page-mutations.ts b/src/core/persistence/page-mutations.tsindex dd6b8cc781..5b51925e9d 100644--- a/src/core/persistence/page-mutations.ts+++ b/src/core/persistence/page-mutations.ts@@ -31,7 +31,6 @@ import { claimWorktree, getWorktreeBinding } from './ownership.ts';import { clientRequestIdOf, parseMutationPrecondition } from './preconditions.ts';import { assertPurgeParams } from './purge-params.ts';import type { Principal, WriteRequest } from './model.ts';-import { withWriteApplied } from './write-applied.ts';import { normalizeSubagentPageInput, undeclaredPageTypeWarning, type PageTypeWarning } from './page-input.ts';import { assertKnowledgePublicationAllowed } from '../shared-skills/knowledge-guard.ts';import { decideUnboundWrite, isUnboundSourcePage } from './unbound-source.ts';@@ -199,17 +198,6 @@ export async function withLiveSearchable(ctx: OperationContext, response: Recordreturn { ...settle(response), ...(receipt ? { write_request: settle(receipt) } : {}) };}-/**- * #7190: the reply to a page write, with `applied` (write-applied.ts) in the reply and its `write_request`: whether the- * write is searchable yet and the gap. A pending write's error receipt carries it too. A failed read leaves it out.- */-export async function answerPageWrite(ctx: OperationContext, row: WriteRequest, opts: { gateHold?: false } = {}): Promise<Record<string, unknown>> {- return withWriteApplied(ctx.engine, row, async () => {- const reply = pendingAwareResponse(ctx, row);- return withLiveSearchable(ctx, opts.gateHold === false ? reply : throwIfHeld(reply, false));- });-}-/** #6188 (D21): a write whose fence Tier 1 rewrote carries one `fence_normalized` coaching notice. */export function emitFenceNotice(ctx: Pick<OperationContext, 'emitNotice'>, response: Record<string, unknown>, slug?: string): void {const report = response.fences_normalized as FencesNormalized | undefined;@@ -239,7 +227,7 @@ export async function submitPageMutation(ctx: OperationContext,// cache could explain drops it and prepares the write once more, uncached, so it ends as it would without it.const cached = await preadmitReads(ctx.engine);let prepared = await preparePageAdmission(cached ? { ...ctx, engine: cached } : ctx, { ...input, params });- if (prepared.prior) return answerPageWrite(ctx, await waitForWrite(ctx.engine, prepared.prior, ctx.config, waitMs()));+ if (prepared.prior) return withLiveSearchable(ctx, throwIfHeld(pendingAwareResponse(ctx, await waitForWrite(ctx.engine, prepared.prior, ctx.config, waitMs())), false));const brainId = cached ? cachedPreadmitBrain(ctx.engine) : undefined;// Phase 4.4: the admission transaction runs on the warm single-write lane when it is free.const admit = (admission: WriteAdmission) => onPersistenceLane(ctx.engine, transaction => admitWrite(ctx.engine, admission, undefined, transaction),@@ -250,10 +238,10 @@ export async function submitPageMutation(ctx: OperationContext,if (!cached || !preadmitRecheckFailed(error)) throw error;dropPreadmitCache(ctx.engine);prepared = await preparePageAdmission(ctx, { ...input, params: { ...params, request_id: prepared.admission.requestId } });- if (prepared.prior) return answerPageWrite(ctx, await waitForWrite(ctx.engine, prepared.prior, ctx.config, waitMs()));+ if (prepared.prior) return withLiveSearchable(ctx, throwIfHeld(pendingAwareResponse(ctx, await waitForWrite(ctx.engine, prepared.prior, ctx.config, waitMs())), false));row = await admit(prepared.admission);}- const response = await answerPageWrite(ctx, await waitForWrite(ctx.engine, row, ctx.config, waitMs()));+ const response = await withLiveSearchable(ctx, throwIfHeld(pendingAwareResponse(ctx, await waitForWrite(ctx.engine, row, ctx.config, waitMs())), false));emitFenceNotice(ctx, response, row.slug);return { ...response, ...(prepared.typeWarning ? { type_warning: prepared.typeWarning } : {}), ...(prepared.slugAdvisory ? { slug_advisory: prepared.slugAdvisory } : {}) };}diff --git a/src/core/persistence/params.ts b/src/core/persistence/params.tsindex f26644717c..6f067a75ad 100644--- a/src/core/persistence/params.ts+++ b/src/core/persistence/params.ts@@ -122,6 +122,5 @@ export const WRITE_RECEIPT_SCHEMA = {next_action: { type: 'string', enum: [...WRITE_HEALTH_ACTIONS] },},},- applied: { type: 'object', description: 'Whether the write is searchable yet (searchable_yet, searchable, state), the gap and the source write watermark.' },},};diff --git a/src/core/persistence/types.ts b/src/core/persistence/types.tsindex 6a065ce647..cbfbea5f24 100644--- a/src/core/persistence/types.ts+++ b/src/core/persistence/types.ts@@ -56,8 +56,6 @@ export interface WriteReceipt {created_at?: string;updated_at?: string;diagnostic?: WriteDiagnostic;- /** #7190: whether the write is searchable yet, the gap and the source's write watermark (write-applied.ts). */- applied?: import('./write-applied.ts').WriteApplied;}/** Wire names stay separate from the engine's camelCase precondition. */@@ -151,7 +149,6 @@ export function publicWriteReceipt(receipt: WriteReceipt): WriteReceipt {} } : {}),...(receipt.created_at !== undefined ? { created_at: receipt.created_at } : {}),...(receipt.updated_at !== undefined ? { updated_at: receipt.updated_at } : {}),- ...(receipt.applied !== undefined ? { applied: receipt.applied } : {}),...(!isTerminalWriteState(receipt.state) && isWriteDiagnostic(receipt.diagnostic) ? { diagnostic: {age_ms: receipt.diagnostic.age_ms, assessment: receipt.diagnostic.assessment,reason: receipt.diagnostic.reason, next_action: receipt.diagnostic.next_action,diff --git a/src/core/persistence/write-applied.ts b/src/core/persistence/write-applied.tsindex 4279e7e640..5159ad11cb 100644--- a/src/core/persistence/write-applied.ts+++ b/src/core/persistence/write-applied.ts@@ -1,5 +1,5 @@/**- * #7190: the answer a write receipt gives to "is this write searchable yet?": the written page's state and+ * #7190: the answer `get_write_request` gives to "is this write searchable yet?": the written page's state and* `searchable` (the resolve-path vocabulary), the gap when it is not, and the source's write watermark.** - pending_write: the request has not settled; `gap.requests_ahead` counts the source's unsettled requests queued before it.@@ -7,11 +7,10 @@* - deleted: it committed and the page is gone (a delete).* - otherwise the page's state from `page-searchability.ts`; `gap.unembedded_chunks` counts chunks still waiting for a* vector and `embedding_hold` names a budget hold that waits for approval.- * `searchable_yet` is true only when search finds the page by keyword and vector.+ * `searchable_yet` is true only when search finds the page by keyword and vector. It is read live on every receipt read, never+ * frozen into the write's reply: a same-request-id replay of a write returns its first reply unchanged.*/import type { BrainEngine } from '../engine.ts';-import { OperationError } from '../ops/contract.ts';-import { isTerminalWriteState } from './types.ts';import { readPageSearchability, type PageSearchState } from '../page-searchability.ts';import { readWriteWatermark, type WriteWatermark } from './applied-watermark.ts';@@ -45,23 +44,3 @@ export async function readWriteApplied(engine: BrainEngine, row: { source_id: stgap: { requests_ahead: 0, unembedded_chunks: page.unembedded } };}-/**- * The reply `reply()` builds for `row`, with `applied` in it and in its `write_request`; a pending write's error receipt- * carries it too. A failed watermark read leaves it out and never fails the write's reply.- */-export async function withWriteApplied(engine: BrainEngine, row: Parameters<typeof readWriteApplied>[1],- reply: () => Record<string, unknown> | Promise<Record<string, unknown>>): Promise<Record<string, unknown>> {- const read = () => readWriteApplied(engine, row).catch(() => null);- let response: Record<string, unknown>;- try { response = await reply(); } catch (error) {- if (error instanceof OperationError && error.writeRequest && !isTerminalWriteState(error.writeRequest.state)) {- const pending = await read();- if (pending) error.writeRequest = { ...error.writeRequest, applied: pending };- }- throw error;- }- const applied = await read();- if (!applied) return response;- const receipt = response.write_request as Record<string, unknown> | undefined;- return { ...response, applied, ...(receipt ? { write_request: { ...receipt, applied } } : {}) };-}diff --git a/test/applied-watermark-7190.test.ts b/test/applied-watermark-7190.test.tsindex 2ed7481ff4..8445f15f9a 100644--- a/test/applied-watermark-7190.test.ts+++ b/test/applied-watermark-7190.test.ts@@ -3,7 +3,7 @@* result. Red on master (no watermark, no receipt `applied`):* - indexed_through moves only when a pass finishes: a sliced pass that stops after one page leaves it where it was;* - pending counts the commits and files on HEAD that have not synced yet;- * - a put_page receipt answers whether the write is searchable yet, with the gap, and get_write_request repeats it;+ * - get_write_request answers whether a write is searchable yet, with the gap, while the write's own reply stays frozen;* - committed_through_request never passes an unsettled request.*/import { afterAll, beforeAll, expect, test } from 'bun:test';@@ -79,22 +79,21 @@ test('indexed_through is the last finished pass, and pending counts what HEAD haexpect(done.pending.files_behind).toBe(0);}), 240_000);-test('a put_page receipt says whether the write is searchable yet, and get_write_request repeats it', () => withEnv({ GBRAIN_HOME: home }, async () => {+test('get_write_request says whether a put_page is searchable yet; the write reply stays frozen for replays', () => withEnv({ GBRAIN_HOME: home }, async () => {const { id } = await syncedSource();const ctx = { engine, config: { engine: engine.kind } as never, remote: false, sourceId: id } as never;const reply = await submitPageMutation(ctx, { operation: 'put_page', params: { slug: 'erin-example', source_id: id, content: note('Erin wrote this.') } });- const applied = reply.applied as Awaited<ReturnType<typeof readWriteApplied>>;+ expect(reply.applied).toBeUndefined();+ const { operationsByName } = await import('../src/core/operations.ts');+ const read = await operationsByName.get_write_request!.handler(ctx, { request_id: reply.request_id }) as { applied?: Awaited<ReturnType<typeof readWriteApplied>> };+ const applied = read.applied!;expect(applied).toBeDefined();- expect((reply.write_request as { applied?: unknown }).applied).toEqual(applied);expect(applied.state).not.toBe('pending_write');expect(applied.page!.slug).toBe('erin-example');expect(applied.searchable_yet).toBe(applied.searchable === true && !applied.embedding_hold);expect(applied.gap.unembedded_chunks).toBe(applied.page!.unembedded);expect(applied.watermark.committed_through_request).toBeGreaterThanOrEqual(applied.sequence);- const { operationsByName } = await import('../src/core/operations.ts');- const read = await operationsByName.get_write_request!.handler(ctx, { request_id: reply.request_id }) as { applied?: { sequence: number; state: string } };- expect(read.applied).toMatchObject({ sequence: applied.sequence, state: applied.state });}), 240_000);test('committed_through_request stops below an unsettled request, which counts the requests queued before it', () => withEnv({ GBRAIN_HOME: home }, async () => {