Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(door): report a restored stale index entry as git_index_restored on the receipt and as a notice

garrytan03683f8be225
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index 83f4e1768e..acdacdc02f 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -896,6 +896,7 @@ export const NOTICE_CODES = {
held_files: { kind: 'degraded', summary: 'Sync holds files in the read scope it cannot import (held new files are missing, pages whose newer file is held are stale), or pages in scope are held from embedding (no vectors); search and query show it when some could match the query, once per session per state. The fix is the repair preview, or gbrain embed --held --dry-run, on the brain host.' },
recovered_frontmatter: { kind: 'coaching', summary: 'Files imported only after quoting unquoted frontmatter values; the generator writing them should quote values (the fix is the repair preview).' },
page_quarantined: { kind: 'safety', summary: 'The page was quarantined by the content-quality gate (hidden from search; its facts and takes are not extracted). A read says to treat its text as untrusted scraped content and, for an untrusted reader, that its body was withheld (an admin-scoped caller may pass include_quarantined: true); a write says the page was hidden and that the operator clears a false positive with gbrain quarantine clear <slug> --force.' },
+ git_index_restored: { kind: 'info', summary: 'A strict (canonical: git) write restored index to HEAD after an interrupted door refresh: the path\'s index entry still held the version before an earlier gbrain commit, whose index update had failed, so the write replaced it. The notice names the paths; nothing was lost, the earlier version is in Git history.' },
fence_normalized: { kind: 'coaching', summary: 'A write\'s facts or takes fence was rewritten losslessly (rows and classes named, never values): the stored page differs from what was sent, so re-read it with get_page before editing; remember and takes_add write rows that never need it.' },
write_capacity_low: { kind: 'info', summary: 'A cumulative write cap (request ids or receipt bytes) is at or past 80% or runs out within `persistence.capacity.warn_days`; writes still work. Write and sync receipts carry it at most once an hour per process per scope; sync status, doctor and autopilot cycle output every time. Mute on receipts with `gbrain notices mute write_capacity_low`; doctor still reports it.' },
write_capacity_backpressure: { kind: 'degraded', summary: 'A cumulative write cap passed `persistence.capacity.background_pause_pct`, so background producers (maintenance, conversation facts, autopilot phases and catch-up syncs) pause while interactive writes keep the rest; shown once when the pause starts.' },
diff --git a/src/core/persistence/coordinator.ts b/src/core/persistence/coordinator.ts
index eb04ecd145..d298a171e5 100644
--- a/src/core/persistence/coordinator.ts
+++ b/src/core/persistence/coordinator.ts
@@ -625,7 +625,8 @@ export async function publishMutation(engine: BrainEngine, row: WriteRequest, pr
decoratePublicationOutcome(row, prepared, outcome, final, files.length, skill);
await recordPublicationFenceTrend(tx, row, outcome);
// G2: a strict source's file is committed before its row; its Git effect only pushes.
- if (door?.door) Object.assign(outcome.persistence as object, { git_state: 'committed', git_commit: await commitThroughDoor(door.door.root, [{ path: door.path, planned: door.afterHash, note: prepared.file?.commit }], lock ?? undefined) });
+ if (door?.door) Object.assign(outcome.persistence as object, { git_state: 'committed', git_commit: await commitThroughDoor(door.door.root, [{ path: door.path, planned: door.afterHash, note: prepared.file?.commit }], lock ?? undefined,
+ paths => Object.assign(outcome.persistence as object, { git_index_restored: paths })) });
await timePublicationStep('effects', row.slug, () => queuePublicationEffects(tx, row, final, outcome, prepared, { pushOnly: !!door?.door }));
if (prepared.afterEffects) await withCoordinatedWrite(tx, [row.source_id], () => prepared.afterEffects!(tx, outcome), publicationAttribution(row, prepared.trust));
await hooks.boundary?.('before_commit', row);
diff --git a/src/core/persistence/git-door.ts b/src/core/persistence/git-door.ts
index 458f5c433a..8ba3141d88 100644
--- a/src/core/persistence/git-door.ts
+++ b/src/core/persistence/git-door.ts
@@ -22,7 +22,8 @@
* `git_index_conflict`, index untouched). After the branch moves, an entry someone staged meanwhile is left as it is
* and the write reports that its commit landed. An entry still holding HEAD's first parent's version at that path counts
* as clean: it is what an interrupted refresh after the door's own commit leaves, and its bytes are in history, so the
- * next write (or a replay whose blob HEAD already holds) refreshes it; any other staged entry refuses `git_index_conflict`.
+ * next write (or a replay whose blob HEAD already holds) refreshes it and reports the paths (`onIndexRestored`, the
+ * `git_index_restored` notice); any other staged entry refuses `git_index_conflict`.
*
* Recovery inverts for those writes: the recovery record names the HEAD it was prepared against (`door`), and a
* publication that stopped after its commit landed keeps the committed file instead of restoring the prior bytes.
@@ -39,6 +40,7 @@
import { createHash } from 'node:crypto';
import { existsSync, lstatSync, mkdirSync, mkdtempSync, realpathSync, rmSync, statSync, writeFileSync } from 'node:fs';
import { join, relative, resolve, sep } from 'node:path';
+import type { Notice } from '../agent-output.ts';
import { OperationError, opError } from '../ops/contract.ts';
import { commitMessage, git, gitBytes, gitFailure, gitStepTimeoutMs, ignoredTargetError, withSession, type GitSession } from './effect-git.ts';
import type { GitCommitNote } from './effect-model.ts';
@@ -90,7 +92,7 @@ export interface DoorFile {
* its planned state or not at all. A target Git refuses, a file that no longer holds its plan, or a target with a
* staged change throws, so the publication rolls back.
*/
-export async function commitThroughDoor(root: string, files: DoorFile[], writerLock?: NativeLockHandle): Promise<string | null> {
+export async function commitThroughDoor(root: string, files: DoorFile[], writerLock?: NativeLockHandle, onIndexRestored?: (paths: string[]) => void): Promise<string | null> {
let key = resolve(root);
try { key = realpathSync(root); } catch { /* the session reports a missing checkout */ }
const prior = doorTurns.get(key) ?? Promise.resolve();
@@ -99,7 +101,7 @@ export async function commitThroughDoor(root: string, files: DoorFile[], writerL
doorTurns.set(key, turn);
await prior;
try {
- return await withSession(root, undefined, writerLock ? { writerLock } : undefined, false, session => doorCommit(session, root, files));
+ return await withSession(root, undefined, writerLock ? { writerLock } : undefined, false, session => doorCommit(session, root, files, onIndexRestored));
} catch (error) {
if (!(error instanceof OperationError) || TYPED.has(error.code) || landedFailures.has(error)) throw error;
const paths = files.map(file => relative(root, file.path).split(sep).join('/'));
@@ -186,7 +188,7 @@ function stripspace(paragraph: string): string {
return lines.join('\n');
}
-async function doorCommit(session: GitSession, root: string, files: DoorFile[]): Promise<string> {
+async function doorCommit(session: GitSession, root: string, files: DoorFile[], onIndexRestored?: (paths: string[]) => void): Promise<string> {
const symbolic = await git(session, ['symbolic-ref', '-q', 'HEAD']);
if (symbolic.code !== 0) throw opError('git_detached_head', `${root} is on a detached HEAD, so the strict source's write has no branch to commit to; nothing was published.`,
'Check out the branch the source tracks (git switch <branch>) on the brain host, then retry the write with a new request_id.');
@@ -288,8 +290,10 @@ async function doorCommit(session: GitSession, root: string, files: DoorFile[]):
const foreign = staged.filter(target => indexed.entries.get(target.rel) !== parent.get(target.rel));
if (foreign.length) throw indexConflict(root, foreign);
}
+ const restored = () => { if (staged.length) onIndexRestored?.(staged.map(target => target.rel)); };
if (!changed.length) {
if (staged.length) await syncIndex(session, root, prefix, index, [...targets.values()], head, indexed);
+ restored();
return head;
}
@@ -324,6 +328,7 @@ async function doorCommit(session: GitSession, root: string, files: DoorFile[]):
const moved = await git(session, ['update-ref', '-m', `commit: ${message[0]!.split('\n')[0]}`, branch, created, head]);
if (moved.code === 0) {
await syncIndex(session, root, prefix, index, [...targets.values()], created, indexed);
+ restored();
return created;
}
if (attempt) throw new OperationError('git_unavailable', `${branch} in ${root} moved twice while this write was being committed, so it was not committed.`,
@@ -350,6 +355,12 @@ async function refuseIgnored(session: GitSession, root: string, fresh: Target[])
});
}
+/** The notice a write carries when the door restored index entries an interrupted refresh after its own commit left behind. */
+export function indexRestoredNotice(paths: string[]): Notice {
+ return { code: 'git_index_restored', kind: 'info',
+ why: `gbrain restored index to HEAD after an interrupted door refresh for ${paths.join(', ')}: the index still held the version before an earlier gbrain commit (its update of the index had failed), so this write replaced that stale entry. Nothing was lost; the earlier version is in Git history.` };
+}
+
/** The targets whose file no longer holds its planned state (its bytes, or no file for a removal) refuse as `git_target_changed`. */
function refuseChanged(root: string, targets: Iterable<Target>): void {
const moved = [...targets].filter(target => { try { return hashFile(join(root, target.rel)) !== target.planned; } catch { return true; } }).map(target => target.rel);
diff --git a/src/core/persistence/group-publish.ts b/src/core/persistence/group-publish.ts
index babb19b051..7f4eaeafd3 100644
--- a/src/core/persistence/group-publish.ts
+++ b/src/core/persistence/group-publish.ts
@@ -33,6 +33,7 @@
* marker, so its request identity and replay are unchanged; when the group
* does not commit it takes `publishMutation` like any other member.
*/
+import { relative, sep } from 'node:path';
import type { BrainEngine } from '../engine.ts';
import { OperationError } from '../ops/contract.ts';
import { authorizeStoredRequest, storedAuthorizationReads } from './authority.ts';
@@ -415,7 +416,13 @@ export async function publishGroup(engine: BrainEngine, rows: WriteRequest[], pr
if (lane) { timed.apply?.turn(); await faultPoint('lane:applied', { requestId: head.request_id, sourceId: head.source_id, operation: head.operation }); await awaitLaneTurn(tx, lane, rows); timed.apply?.turned(); }
// G2: one path-only commit for every member's file, in commit order, before the rows commit; a shared lease never reclaims an index lock.
if (strict && recorded.size) {
- const commit = await commitThroughDoor(binding.local_path!, [...recorded].map(([i, member]) => ({ path: member.record.path, planned: member.record.afterHash, note: prepared[i]!.file?.commit })), lane || joined ? undefined : lock);
+ const commit = await commitThroughDoor(binding.local_path!, [...recorded].map(([i, member]) => ({ path: member.record.path, planned: member.record.afterHash, note: prepared[i]!.file?.commit })), lane || joined ? undefined : lock,
+ paths => {
+ for (const [i, member] of recorded) {
+ const rel = relative(binding.local_path!, member.record.path).split(sep).join('/');
+ if (paths.includes(rel)) Object.assign(outcomes[i]!.persistence as object, { git_index_restored: [rel] });
+ }
+ });
for (const i of recorded.keys()) Object.assign(outcomes[i]!.persistence as object, { git_state: 'committed', git_commit: commit });
}
const done = await completeGroup(tx, rows, outcomes);
diff --git a/src/core/persistence/page-mutations.ts b/src/core/persistence/page-mutations.ts
index aa17073e6d..e091e20ddc 100644
--- a/src/core/persistence/page-mutations.ts
+++ b/src/core/persistence/page-mutations.ts
@@ -1,5 +1,6 @@
import { randomUUID } from 'node:crypto';
import { pageQuarantinedNotice } from '../quarantine.ts';
+import { indexRestoredNotice } from './git-door.ts';
import { fenceNormalizedNotice, type FencesNormalized } from '../fence-repair/report.ts';
import { parseFenceRepairReceipt } from '../fence-repair/receipt.ts';
import { realpathSync } from 'node:fs';
@@ -198,13 +199,15 @@ export async function withLiveSearchable(ctx: OperationContext, response: Record
return { ...settle(response), ...(receipt ? { write_request: settle(receipt) } : {}) };
}
-/** #6188 (D21): a write whose fence Tier 1 rewrote carries one `fence_normalized` coaching notice. */
+/** #6188 (D21): a write whose fence Tier 1 rewrote carries one `fence_normalized` coaching notice; a strict write whose door restored a stale index entry carries `git_index_restored`. */
export function emitFenceNotice(ctx: Pick<OperationContext, 'emitNotice'>, response: Record<string, unknown>, slug?: string): void {
const report = response.fences_normalized as FencesNormalized | undefined;
if (report) ctx.emitNotice?.(fenceNormalizedNotice(report, slug));
// #6259: a write the content-quality gate quarantined says so (`quarantined` plus one safety notice).
const quarantined = response.quarantined as { reason: string; detail: string } | undefined;
if (quarantined && slug) ctx.emitNotice?.(pageQuarantinedNotice(slug, quarantined, 'write'));
+ const restored = (response.persistence as { git_index_restored?: string[] } | undefined)?.git_index_restored;
+ if (restored?.length) ctx.emitNotice?.(indexRestoredNotice(restored));
}
/** Owner-internal `put_page` kinds the trusted local file writers (import, frontmatter repair, quarantine clear) submit; every other caller is refused them. */
diff --git a/test/git-door-planned-state.test.ts b/test/git-door-planned-state.test.ts
index 66f3a9fe8b..fcf54d1337 100644
--- a/test/git-door-planned-state.test.ts
+++ b/test/git-door-planned-state.test.ts
@@ -10,6 +10,8 @@
* - D4's recovery record pauses every later write of the worktree until `gbrain repair stuck-recovery --keep disk`
* resolves it: the human's bytes stay on disk, the write ends failed, the queued write publishes, Git and the row
* keep the prior revision until the edit is committed, and a sync then imports it;
+ * - a stale entry an interrupted refresh left (the version before the door's last commit) is restored by the next
+ * write, whose receipt names the path (`persistence.git_index_restored`) and which emits the `git_index_restored` notice;
* - with no interference the planned blob commits and the index and status are clean;
* - plumbing: a file rewritten between plan and commit refuses with nothing committed or staged; a change staged
* after the pre-commit check and before the index refresh is left staged and the refusal says the commit landed; an
@@ -29,7 +31,8 @@ import { operations, type OperationContext } from '../src/core/operations.ts';
import { submissionAuthority } from '../src/core/persistence/authority.ts';
import { publishMutation, type PublicationHooks } from '../src/core/persistence/coordinator.ts';
import { sha256 } from '../src/core/persistence/digest.ts';
-import { commitThroughDoor, doorSeams } from '../src/core/persistence/git-door.ts';
+import { commitThroughDoor, doorSeams, indexRestoredNotice } from '../src/core/persistence/git-door.ts';
+import type { Notice } from '../src/core/agent-output.ts';
import { localHostId } from '../src/core/persistence/identity.ts';
import { admitWrite, claimNextWrite, getWriteRequestById } from '../src/core/persistence/journal.ts';
import { getWorktreeBinding } from '../src/core/persistence/ownership.ts';
@@ -176,6 +179,20 @@ for (const backend of testBackends()) describe(`[${backend}] the door commits on
expect(git(root, 'status', '--porcelain')).toBe('');
}, { databaseUrl, setup }), 180_000);
+ test('a stale index entry from an interrupted door refresh is restored, and the receipt and notice name the path', () => managedBrain(async ({ engine, ctx, root }) => {
+ await committedPage(engine, ctx);
+ expect(await publish(engine, ctx, page('Second'))).toMatchObject({ state: 'committed' });
+ git(root, 'update-index', '--cacheinfo', `100644,${git(root, 'rev-parse', `HEAD^:${FILE}`)},${FILE}`);
+ const notices: Notice[] = [];
+ const result = await putPage.handler({ ...ctx, emitNotice: notice => notices.push(notice) }, { slug: SLUG, content: page('Third'),
+ expected_revision: (await engine.readPageSnapshot(SLUG, { sourceId: 'default' }))!.revision, request_id: randomUUID(), wait_ms: 30_000 }) as Record<string, any>;
+ expect(result).toMatchObject({ state: 'committed', persistence: { git_state: 'committed', git_commit: git(root, 'rev-parse', 'HEAD'), git_index_restored: [FILE] } });
+ expect(notices.filter(notice => notice.code === 'git_index_restored')).toEqual([{ code: 'git_index_restored', kind: 'info',
+ why: expect.stringContaining(`restored index to HEAD after an interrupted door refresh for ${FILE}`) }]);
+ expect(await standing(engine, root)).toEqual({ row: 'Third', head: 'Third', disk: 'Third', index: git(root, 'rev-parse', `HEAD:${FILE}`) });
+ expect(git(root, 'status', '--porcelain')).toBe('');
+ }, { databaseUrl, setup }), 120_000);
+
test('with no interference the planned blob commits, and the index and status are clean', () => managedBrain(async ({ engine, ctx, root }) => {
await committedPage(engine, ctx);
const result = await publish(engine, ctx, page('Second'));
@@ -267,7 +284,11 @@ describe('door plumbing: the planned state', () => {
expect(git(root, 'rev-parse', ':notes/a.md')).toBe(git(root, 'rev-parse', 'HEAD^:notes/a.md'));
expect(git(root, 'ls-files', '--', 'notes/new.md')).toBe('');
put(root, 'notes/a.md', 'second\n'); put(root, 'notes/new.md', 'second new\n');
- const commit = await commitThroughDoor(root, ['notes/a.md', 'notes/new.md'].map(path => ({ path: join(root, path), planned: sha256(readFileSync(join(root, path))) })));
+ const restored: string[][] = [];
+ const commit = await commitThroughDoor(root, ['notes/a.md', 'notes/new.md'].map(path => ({ path: join(root, path), planned: sha256(readFileSync(join(root, path))) })), undefined, paths => restored.push(paths));
+ expect(restored).toEqual([['notes/a.md', 'notes/new.md']]);
+ expect(indexRestoredNotice(restored[0]!)).toEqual({ code: 'git_index_restored', kind: 'info',
+ why: expect.stringContaining('restored index to HEAD after an interrupted door refresh for notes/a.md, notes/new.md') });
expect(commit).toBe(git(root, 'rev-parse', 'HEAD'));
expect(git(root, 'show', 'HEAD:notes/a.md')).toBe('second');
expect(git(root, 'show', 'HEAD:notes/new.md')).toBe('second new');
@@ -278,8 +299,12 @@ describe('door plumbing: the planned state', () => {
const root = repo({ 'notes/a.md': 'a\n' });
const commit = await publishAt(root, 'notes/a.md', 'door\n');
git(root, 'update-index', '--cacheinfo', `100644,${git(root, 'rev-parse', `${commit}^:notes/a.md`)},notes/a.md`);
- expect(await commitThroughDoor(root, [{ path: join(root, 'notes/a.md'), planned: sha256('door\n') }])).toBe(commit);
+ const restored: string[][] = [];
+ expect(await commitThroughDoor(root, [{ path: join(root, 'notes/a.md'), planned: sha256('door\n') }], undefined, paths => restored.push(paths))).toBe(commit);
+ expect(restored).toEqual([['notes/a.md']]);
expect(git(root, 'status', '--porcelain')).toBe('');
+ expect(await commitThroughDoor(root, [{ path: join(root, 'notes/a.md'), planned: sha256('door\n') }], undefined, paths => restored.push(paths))).toBe(commit);
+ expect(restored).toHaveLength(1);
put(root, 'notes/a.md', 'novel\n'); git(root, 'add', 'notes/a.md');
const novel = git(root, 'rev-parse', ':notes/a.md');
put(root, 'notes/a.md', 'door\n');