Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(reconcile): report git_dirty for agreeing files Git shows as modified (#6138)
garrytana47cfb06c750
diff --git a/docs/architecture/key-files/canonical-reconciliation.md b/docs/architecture/key-files/canonical-reconciliation.mdindex d05c09c074..e9e33586c6 100644--- a/docs/architecture/key-files/canonical-reconciliation.md+++ b/docs/architecture/key-files/canonical-reconciliation.md@@ -2,7 +2,7 @@- `src/commands/sync-diagnostics.ts` + `src/core/persistence/{sync-run,verb-errors}.ts` — bounded source/slug/path/reason diagnostics derive from immutable managed-sync receipts, including when the local failure ledger is unavailable. Direct and resident-owner JSON carry the same receipt; human memory errors lead with the specific write reason without widening frozen v1 error codes. Pending requests retain their original UUID, terminal corrections require a new UUID, and neither retry nor line-ending diagnostics bypasses raw-byte or skip guards.-- `src/core/persistence/reconcile*.ts` — trusted-local exact-page reconciliation: loss-preserving semantic preview, explicit JSON Pointer choices, pinned identity/revision/raw-file/policy checks, durable private preimages and same-ID replay through the existing coordinator. Normal overwrite protection stays unchanged. The bounded audit reports source-scoped drift without repair or checkpoint changes; a database-only page (`isDatabaseOnlyPage`, with no file at its slug-derived path) counts as `database_only` with no reconcile suggestion, never as drift, while a legacy row that merely lacks `source_path` is audited as usual. `src/commands/source-reconcile.ts` provides strict CLI parsing, private artifact I/O, brain routing and resident-owner delegation; the operations stay outside public MCP. Operator flow: `docs/guides/concurrent-writes.md`. Tests cover merge choices, both engines, grants, stale previews, read-only audit, and private files. A database-only page (no `source_path`, no `source_uri`; `isDatabaseOnlyPage` in `src/core/persistence/unbound-pages.ts`) is matched to the canonical file at its slug-derived path (`ReconcileState.origin: 'slug_derived'`), and apply records that path as its `source_path` (the #5254 unbound collision; `test/reconcile-unbound-collision.test.ts`).+- `src/core/persistence/reconcile*.ts` — trusted-local exact-page reconciliation: loss-preserving semantic preview, explicit JSON Pointer choices, pinned identity/revision/raw-file/policy checks, durable private preimages and same-ID replay through the existing coordinator. Normal overwrite protection stays unchanged. The bounded audit reports source-scoped drift without repair or checkpoint changes; a database-only page (`isDatabaseOnlyPage`, with no file at its slug-derived path) counts as `database_only` with no reconcile suggestion, never as drift, while a legacy row that merely lacks `source_path` is audited as usual. `src/commands/source-reconcile.ts` provides strict CLI parsing, private artifact I/O, brain routing and resident-owner delegation; the operations stay outside public MCP. Operator flow: `docs/guides/concurrent-writes.md`. Tests cover merge choices, both engines, grants, stale previews, read-only audit, and private files. A database-only page (no `source_path`, no `source_uri`; `isDatabaseOnlyPage` in `src/core/persistence/unbound-pages.ts`) is matched to the canonical file at its slug-derived path (`ReconcileState.origin: 'slug_derived'`), and apply records that path as its `source_path` (the #5254 unbound collision; `test/reconcile-unbound-collision.test.ts`). #6138: an `--auto-additive` preview classified `no_drift` asks Git (`hardened-git.ts`, `git status --porcelain -z -- <file>` in the source root) whether the canonical file differs from its last commit and returns `git_dirty`; a dirty file's `next_action` says the content agrees, the difference is only how it is written, reconcile does not commit, and names `git -C <root> diff -- <file>` (committing it is the user's decision; the managed commit path is deferred, D5). The "retry the original write" step is conditional on the preview coming from a refused write. Tests: `test/persistence-reconcile-git-dirty-6138.test.ts`.- `src/core/persistence/reconcile-additive.ts` (#5974) — pure structural drift classifier over the complete file/database delta: inserted whole lines (two-pointer subsequence, CRLF-normalized; fence, heading and table insertions excluded) are `suggested`; an append-only `contacts` list, an allowlisted activity date moving forward, and one-sided ordinary fields are `auto`; policy/privacy/identity/tag changes and everything else are `review`. `--auto-additive` previews write `take_file` only for `auto` (and `suggested` with `--accept-suggested`), recorded as format-2 `auto_decisions` with an evidence digest that apply and owner preparation recheck. `--audit --classify` reports per-page verdicts and counts, never values.diff --git a/src/core/persistence/reconcile.ts b/src/core/persistence/reconcile.tsindex 6d972a2e48..a3b24bfdfd 100644--- a/src/core/persistence/reconcile.ts+++ b/src/core/persistence/reconcile.ts@@ -1,4 +1,6 @@import { randomUUID } from 'node:crypto';+import { relative } from 'node:path';+import { hardenedGitSync } from '../hardened-git.ts';import type { BrainEngine } from '../engine.ts';import { loadConfig, loadConfigWithEngine, type GBrainConfig } from '../config.ts';import { OperationError, opError, type OperationContext } from '../ops/contract.ts';@@ -62,8 +64,14 @@ function assertPreimages(artifact: ReconcileArtifact, state: ReconcileState): vodigest(artifact.preimages.stored_page) !== digest(state.storedPage)) staleReconcile('preimages changed or were edited');}/** Agent-facing next step for an --auto-additive preview. */-function additiveNextAction(classification: DriftClassification, status: string): string {- if (classification.verdict === 'no_drift') return 'No drift: the file and database agree. Retry the original write with a new request ID.';+function additiveNextAction(classification: DriftClassification, status: string, git: { dirty: boolean | null; root: string; path: string }): string {+ // #6138: agreeing content can still be a modified file in Git (the same content written differently, such as YAML quoting).+ if (classification.verdict === 'no_drift') return git.dirty+ ? `No drift in content: the file and database agree, but Git reports ${git.path} as modified, because its bytes differ from the last commit only in how the same content is written (for example YAML quoting). `+ + `Reconcile does not commit files, so there is nothing to apply here. Show the difference with git -C ${git.root} diff -- ${git.path}; leaving it uncommitted is safe, and committing it by hand is the user's decision. `+ + 'If this preview came from a refused write, retry that write with a new request ID.'+ : 'No drift: the file and database agree' + (git.dirty === false ? ' and Git shows the file unchanged' : '')+ + '. Nothing needs reconciling; if this preview came from a refused write, retry that write with a new request ID.';if (classification.verdict === 'review_required') return 'Some paths are not structurally additive (see drift_paths with class review). Do not apply this preview; '+ 'show the user the private preview file\'s conflicts and result, then resolve with --from <preview> --decisions <file> after they decide.';if (status === 'ready') return `Apply with --apply <preview file> --request-id <new uuid>, then retry the original write with a new request ID.`;@@ -71,6 +79,11 @@ function additiveNextAction(classification: DriftClassification, status: string)return 'Inserted text is structurally additive but can still contradict existing text. Read the inserted lines in the private preview file '+ '(or show them to the user if the page is private or the claims matter), then rerun the preview with --auto-additive --accept-suggested.';}+/** #6138: whether Git reports the canonical file as changed from its last commit; null when Git cannot say (not a Git checkout). */+function canonicalFileGitDirty(root: string, path: string): boolean | null {+ const status = hardenedGitSync(root, ['status', '--porcelain', '-z', '--', relative(root, path)], { timeoutMs: 10_000, maxBytes: 1024 * 1024 });+ return status.ok ? status.stdout.length > 0 : null;+}async function config(engine: BrainEngine): Promise<GBrainConfig> {return await loadConfigWithEngine(engine, loadConfig()) ?? { engine: engine.kind } as GBrainConfig;}@@ -114,9 +127,11 @@ export async function runReconcilePreview(engine: BrainEngine, params: Record<stdecisions, conflicts: prepared.conflicts, result: prepared.result, result_digest: digest(prepared.result),status: prepared.conflicts.length || reviewRequired ? 'needs_resolution' : 'ready', ...(autoDecisions.length ? { auto_decisions: autoDecisions } : {}) };await assertReconcileSize(engine, preview);+ const git = { dirty: classification?.verdict === 'no_drift' ? canonicalFileGitDirty(state.root, state.path) : null, root: state.root, path: relative(state.root, state.path) };return { source_id: sourceId, slug, preview_id: preview.preview_id, status: preview.status,...(classification ? { classification: classification.verdict, drift_paths: classification.paths,- auto_decided_paths: autoDecisions.map(d => d.path), next_action: additiveNextAction(classification, preview.status) } : {}),+ auto_decided_paths: autoDecisions.map(d => d.path), next_action: additiveNextAction(classification, preview.status, git),+ ...(git.dirty === null ? {} : { git_dirty: git.dirty }) } : {}),conflict_paths: prepared.conflicts.map(c => c.path), protected_paths: prepared.protectedPaths,migrated_scan_paths: prepared.scanPaths, relative_path: state.pins.relative_path,line_endings: state.raw.includes(Buffer.from('\r\n')) ? 'crlf' : 'lf',diff --git a/test/persistence-reconcile-git-dirty-6138.test.ts b/test/persistence-reconcile-git-dirty-6138.test.tsnew file mode 100644index 0000000000..049f7a34b4--- /dev/null+++ b/test/persistence-reconcile-git-dirty-6138.test.ts@@ -0,0 +1,69 @@+/**+ * #6138: a managed canonical file whose content agrees with the database but whose bytes differ from its last+ * commit (only YAML quoting changed) was previewed as `no_drift` with "Retry the original write with a new+ * request ID", which tells the agent nothing about the modified file Git shows. The preview now reports+ * `git_dirty` and a truthful next step; the managed commit path itself is deferred (D5).+ */+import { afterAll, beforeAll, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { execFileSync } from 'node:child_process';+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import type { BrainEngine } from '../src/core/engine.ts';+import { importFromContent } from '../src/core/import-file.ts';+import { serializePageToMarkdown } from '../src/core/markdown.ts';+import { claimWorktree } from '../src/core/persistence/ownership.ts';+import { registerLocalWriter, withVerifiedLocalRegistration } from '../src/core/persistence/identity.ts';+import { runReconcilePreview } from '../src/core/persistence/reconcile.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { withEnv } from './helpers/with-env.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';++const home = mkdtempSync(join(tmpdir(), 'gbrain-reconcile-git-dirty-'));+const engines: BrainEngine[] = [];+let closePostgres: (() => Promise<void>) | undefined;+beforeAll(async () => {+ const engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); engines.push(engine);+ if (process.env.DATABASE_URL) { const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL); engines.push(pg.engine); closePostgres = pg.close; }+}, 120_000);+afterAll(async () => {+ await withEnv({ GBRAIN_HOME: home }, async () => { for (const engine of engines) { await disposePersistenceConsumer(engine); await engine.disconnect(); } });+ await closePostgres?.(); rmSync(home, { recursive: true, force: true });+});+const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();+const commit = (root: string) => { git(root, 'add', '.'); git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', 'notes'); };++test('a git-dirty file that agrees with the database reports git_dirty and a truthful next step', () => withEnv({ GBRAIN_HOME: home, OPENAI_API_KEY: undefined, ANTHROPIC_API_KEY: undefined }, async () => {+ for (const engine of engines) {+ await disposePersistenceConsumer(engine);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ const id = `dirty-${randomUUID().slice(0, 12)}`, root = join(home, id), slug = 'people/alice-example', file = join(root, `${slug}.md`);+ mkdirSync(join(root, 'people'), { recursive: true });+ git(root, 'init', '-q');+ await engine.executeRaw('INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,\'{}\')', [id, root]);+ await importFromContent(engine, slug, '---\ntype: person\ntitle: Alice Example\n---\nWorks at [[companies/acme-example]].\n', { sourceId: id, sourcePath: `${slug}.md`, noEmbed: true });+ const snapshot = (await engine.readPageSnapshot(slug, { sourceId: id }))!;+ writeFileSync(file, serializePageToMarkdown(snapshot.page, snapshot.tags));+ commit(root);+ // Same content, different bytes: only the YAML quoting of the title changes.+ const committed = readFileSync(file, 'utf8');+ expect(committed).toContain('title: Alice Example');+ writeFileSync(file, committed.replace('title: Alice Example', "title: 'Alice Example'"));+ expect(git(root, 'status', '--porcelain')).toContain(`${slug}.md`);+ await claimWorktree(engine, id, root);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ const registration = await registerLocalWriter(engine, 'cli');+ await withVerifiedLocalRegistration(engine, registration, async () => {+ const dirty = await runReconcilePreview(engine, { source_id: id, slug, auto_additive: true });+ expect(dirty).toMatchObject({ classification: 'no_drift', git_dirty: true });+ expect(String(dirty.next_action)).toContain(`git -C ${root} diff -- ${slug}.md`);+ expect(String(dirty.next_action)).not.toStartWith('No drift: the file and database agree. Retry');+ git(root, 'checkout', '--', `${slug}.md`);+ const clean = await runReconcilePreview(engine, { source_id: id, slug, auto_additive: true });+ expect(clean).toMatchObject({ classification: 'no_drift', git_dirty: false });+ expect(String(clean.next_action)).toContain('Git shows the file unchanged');+ });+ }+}), 120_000);