Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix: adversarial review fixes

garrytand81373e74b73
diff --git a/docs/guides/repair.md b/docs/guides/repair.md
index 5bdac9f887..f462d19f6c 100644
--- a/docs/guides/repair.md
+++ b/docs/guides/repair.md
@@ -221,7 +221,7 @@ work behind exits 0, so scripts should also check `results[].complete`.
| `contextual-mode` | `contextual_retrieval_coverage` (pages with no recorded mode) | Stamps the contextual retrieval mode on markdown pages imported without one (for example by a large `--no-embed` sync, or by a connector source on an older gbrain), exactly as a fresh import of the page would: the page, source and brain settings decide, and the per-chunk synopsis tier lands at the free title tier. It rebuilds projections only: no page write, no new page version and no request ID. A page whose stored vectors already match the stamped convention keeps them and queues no re-embedding; a page whose embedding input changes has only those vectors cleared and is re-embedded once, unless you pass `--no-embed`. | `unsealed_projection`: pages whose chunks lag their text; `gbrain embed --stale` or `safe-chunks` seals them first, and the next run stamps them. `embed_skip`: pages marked to skip embedding keep their stored vectors and are not stamped. |
| `file-drift` | `maintenance_write_drift` | Explicit-only, preview-bound. Resolves pages whose canonical file differs from the database copy (`source_changed` / `file_database_drift`) through canonical reconciliation, preferring the file or the database copy within reconcile's protections. `--all-drifted` refuses mixed drift classes unless `--class` keeps one; `--only`/`--skip` narrow by canonical file path glob. Opt-in `storage.keep_db` lets the owner host's resident consumer resolve drift under declared prefixes with the database copy. A page whose file is gone from the last commit: `--prefer database` recreates the file, `--prefer file` soft-deletes the page ([deleted canonical files](#deleted-canonical-files)). See [file drift](#file-drift). | Protected metadata, the tag union and protected takes or private fact rows, listed per page as `exceptions`; pages changed after the preview (`changed_since_preview`). |
| `ghost-pages` | `ghost_pages` | Explicit-only, preview-bound, destructive consent. Soft-deletes live pages whose canonical file is missing on the owner host (ghost pages: every write refuses `canonical_file_missing` and no sync can import a file that is not there), through `delete_page` bound to the previewed owner, path and revision. `--apply --expect <hash> --yes`. See [ghost pages](#ghost-pages). | Declared db_only and never-filed derived pages (never listed); a page whose file came back before the apply (`file_restored`); pages changed after the preview (`changed_since_preview`). |
-| `moved-pages` | `ghost_pages` | Explicit-only, preview-bound, destructive consent. Folds a page left behind by a file that moved into the page the moved file imported as (GST-2584): when sync held the old page's deletion (`file_gone`), the new path imported as a fresh page. A page folds only on proof read from Git: its old path's last committed content is what one new path took at the move (or in that path's first commit), and the old page still holds it. Its links, relationship dates, timeline, raw data, files, user tags, aliases, facts and saved versions move to the moved page, its slug becomes an alias, its hold is cleared and it is soft-deleted (restorable for 72 h); no file is written. `--apply --expect <hash> --yes`. See [moved pages](#moved-pages). | Every other page whose file is gone, listed `held:<reason>`: `several_candidates`, `shared_survivor` (another old page with the same content claims the same moved page), `segmented_versions` (the page or a saved version is stored in segments, over 1 MiB), `both_changed` (edited in the database after the move), `first_blob_differs`, `same_id_body_differs`, `evidence_conflicts`, `history_shallow`, `history_unknown`, `deletion_not_committed`, `not_moved`. |
+| `moved-pages` | `ghost_pages` | Explicit-only, preview-bound, destructive consent. Folds a page left behind by a file that moved into the page the moved file imported as (GST-2584): when sync held the old page's deletion (`file_gone`), the new path imported as a fresh page. A page folds only on proof read from Git: its old path's last committed content is what one new path took at the move (or in that path's first commit), and the old page still holds it. Its links, relationship dates, timeline, raw data, files, user tags, aliases, facts and saved versions move to the moved page, its slug becomes an alias, its hold is cleared and it is soft-deleted (restorable for 72 h); no file is written. `--apply --expect <hash> --yes`. See [moved pages](#moved-pages). | Every other page whose file is gone, listed `held:<reason>`: `several_candidates`, `shared_survivor` (another old page with the same content claims the same moved page), `segmented_versions` (the page or a saved version is stored in segments, over 1 MiB), `access_differs` (the two pages differ in readers, folder rules or privacy label), `both_changed` (edited in the database after the move), `first_blob_differs`, `same_id_body_differs`, `evidence_conflicts`, `history_shallow`, `history_unknown`, `deletion_not_committed`, `not_moved`. |
| `uncommitted-deletions` | `uncommitted_sync_deletions` | Explicit-only, preview-bound, consent. Restores soft-deleted pages a managed sync removed before #7130 although Git never held their recorded file (`.gitignore` excludes it, or no commit holds it and it is not on the disk), one `restore_page` with `detach` each, published database-only: the page comes back live, forgets its recorded file, and no file is written. `--apply --expect <hash> --yes`. See [uncommitted deletions](#uncommitted-deletions). | Pages another writer deleted (listed, restored only with `--include-ambiguous`); tombstones whose file Git once committed or that is on the disk again; paths Git could not answer for (`unknown`); purged pages (only a backup brings them back). |
| `rows-behind` | `sync_rows_behind_checkpoint` | Explicit-only, preview-bound. Re-imports live pages of a managed source whose row holds an older version of its file than the sync checkpoint (`sources.last_commit`) says was imported, with no hold (#8071), from the file as committed at the checkpoint, through the managed file repair (no file is written). A file whose import is refused, or that is over the sync read bound, is held with that code instead. `--source <id>`, then `--apply --expect <hash>`. See [rows behind the checkpoint](#rows-behind). | Rows with no import record (`excluded:unproven`, joined with `--include-ambiguous`; one whose older version equals its committed file, so the database moved since, never joins: `excluded:database_moved`, nor one whose page and file both moved: `excluded:both_moved`), rows with an uncommitted working-tree edit (`excluded:worktree_differs`), rows whose import would keep page data the file does not carry (`excluded:import_overlay`); rows that moved after the preview (`changed_since_preview`). |
| `receipt-compaction` | `persistence_capacity` (terminal bytes) | Explicit-only, preview-bound, destructive consent. Compacts terminal write receipts now instead of on the idle maintenance tick (#6696): the intent and error message are dropped, the outcome, error code and detail stay, and the unused reservation returns to the receipt-bytes counters. `--older-than <72h\|30d>` is floored at the configured retention unless `--force`; committed receipts only unless `--include-failures`. No admission, so it runs at a full cap. See [receipt compaction](#receipt-compaction). | `failures_kept`: failed, conflict and cancelled receipts left without `--include-failures`. Receipts of a run whose sync cursor is still open, and the newest sync receipt of each worktree, are never listed. |
@@ -1912,7 +1912,9 @@ is gone is listed with why it is kept: `several_candidates`, `shared_survivor` (
same content each still back a live page and claim one moved page: the user picks which one moved, and the others are
retired with `gbrain repair ghost-pages`; the preview then folds the one left), `segmented_versions` (the old page or one
of its saved versions is stored in segments, over 1 MiB; segmented versions name their own page's body, so this repair
-does not move them and the page stays as it is), `both_changed` (the old page was edited in the database
+does not move them and the page stays as it is), `access_differs` (the old and the moved page differ in who may read
+them: `readable_by`, a folder rule or the privacy label; a fold would put the old page's database-only evidence under the
+moved page's access, so decide with the user), `both_changed` (the old page was edited in the database
after the move: decide with the user), `first_blob_differs` (a page with the same file name started from other content),
`same_id_body_differs`, `evidence_conflicts` (a manual link or timeline entry that differs from the moved page's),
`history_shallow` (run `git fetch --unshallow` and preview again), `history_unknown`, `deletion_not_committed` and
diff --git a/src/core/ghost-pages.ts b/src/core/ghost-pages.ts
index 1efcade833..14761c3030 100644
--- a/src/core/ghost-pages.ts
+++ b/src/core/ghost-pages.ts
@@ -272,6 +272,12 @@ export async function ghostPageNow(engine: BrainEngine, sourceId: string, slug:
return result.kind === 'ghost' ? { ghost: result.ghost, owner: context.owner } : { ghost: null, reason: result.reason, owner: context.owner };
}
+/** A named page, checked now: the ghost it is, as the scan classifies it (a shared skillpack member is never one, #6910), or null. */
+export async function ghostPageNamed(engine: BrainEngine, sourceId: string, slug: string): Promise<GhostPage | null> {
+ const now = await ghostPageNow(engine, sourceId, slug);
+ return now.ghost && !await sharedPackMemberGhost(engine, now.owner, now.ghost) ? now.ghost : null;
+}
+
/** Every selected (default: every active) source's ghost count, bounded samples and coverage; the doctor and health reader. */
export async function readGhostPages(engine: BrainEngine, opts: { sourceIds?: string[]; sampleLimit?: number }): Promise<GhostPagesSummary> {
const sourceIds = opts.sourceIds ?? (await engine.executeRaw<{ id: string }>('SELECT id FROM sources WHERE archived IS NOT TRUE ORDER BY id')).map(row => row.id);
diff --git a/src/core/persistence/moved-pages.ts b/src/core/persistence/moved-pages.ts
index 45407d074c..461f9aa449 100644
--- a/src/core/persistence/moved-pages.ts
+++ b/src/core/persistence/moved-pages.ts
@@ -12,10 +12,11 @@
* gbrain's own database-only artefacts as derived: `alignWithStored`). A page edited in the database after the move
* is `both_changed`.
* Exactly one live page of the source may descend from the blob; two or more are `several_candidates`, and a moved page that
- * another old page with the same content also claims is `shared_survivor`. A first commit counts only after the old path existed. The file name
+ * another old page with the same content also claims is `shared_survivor`. A first commit counts only between the old path's add and its deletion. The file name
* only explains a result with no candidate (a move can rename the file too), and a frontmatter `id` alone never pairs
* two pages. A page stored in segments (over 1 MiB) is `segmented_versions`: its versions name body generations of their
- * own page, so they cannot move to another. A history too shallow to read the move, or one Git cannot answer, keeps the page held and says so.
+ * own page, so they cannot move to another. Pages whose readers, folder rules or privacy label differ are `access_differs`: a
+ * fold would put the old page's database-only evidence under the moved page's access. A history too shallow to read the move, or one Git cannot answer, keeps the page held and says so.
*/
import { basename } from 'node:path';
import type { BrainEngine } from '../engine.ts';
@@ -24,11 +25,12 @@ import { readDeletionProvenance, type DeletionProvenance } from './sync-origin-e
import { fileMatchesSnapshot } from './page-prepare.ts';
import { twinMergeConflicts } from './twin-merge.ts';
import { literalPathspecs } from '../git-env.ts';
+import { privateSnapshotFilterFragment } from '../search/private-visibility.ts';
export interface MovedPageRef { page_id: number; slug: string; revision: string; path: string }
export type MovedEvidence = 'same_commit' | 'first_commit';
export const MOVED_HELD_REASONS = ['not_moved', 'several_candidates', 'shared_survivor', 'both_changed', 'first_blob_differs', 'same_id_body_differs', 'evidence_conflicts',
- 'segmented_versions', 'history_shallow', 'history_unknown', 'deletion_not_committed'] as const;
+ 'segmented_versions', 'access_differs', 'history_shallow', 'history_unknown', 'deletion_not_committed'] as const;
export type MovedHeldReason = typeof MOVED_HELD_REASONS[number];
export type MovedPageVerdict =
| { verdict: 'moved'; survivor: MovedPageRef; old_blob: string; move_commit: string; evidence: MovedEvidence; evidence_commit: string; detail: string }
@@ -106,14 +108,15 @@ export async function readMovedPage(engine: BrainEngine, input: { sourceId: stri
for (const [path, at] of first.first) {
if (path === old.path || at === added) continue;
const base: string | undefined = git(root, ['merge-base', added, at])?.trim();
- if (!base) return held('history_unknown', `Git could not order ${path}'s first commit ${short(at)} against the commit that added ${old.path}`);
- if (base === added) evidence.set(path, { evidence: 'first_commit', commit: at });
+ const until: string | undefined = git(root, ['merge-base', at, commit])?.trim();
+ if (!base || !until) return held('history_unknown', `Git could not order ${path}'s first commit ${short(at)} against the commits that added and deleted ${old.path}`);
+ if (base === added && until === at) evidence.set(path, { evidence: 'first_commit', commit: at });
}
for (const path of same) if (path !== old.path) evidence.set(path, { evidence: 'same_commit', commit });
const present = inHead(root, [...evidence.keys()]);
const rows = present.size ? await engine.executeRaw<{ id: number; slug: string; revision: string; source_path: string }>(`SELECT id, slug, knowledge_revision::text AS revision, source_path
FROM pages WHERE source_id=$1 AND deleted_at IS NULL AND id<>$2 AND source_path=ANY($3::text[]) ORDER BY id`, [sourceId, old.page_id, [...present]]) : [];
- if (rows.length > 1) return held('several_candidates', `${rows.length} live pages (${rows.map(row => row.slug).join(', ')}) started from ${old.path}'s last committed content (blob ${short(blob)}), so which one it moved to is a person's decision`,
+ if (present.size > 1) return held('several_candidates', `${present.size} paths in HEAD (${[...present].sort().join(', ')}) started from ${old.path}'s last committed content (blob ${short(blob)}), so which one it moved to is a person's decision`,
rows.map(row => row.slug));
if (!rows.length) {
const name = basename(old.path);
@@ -136,7 +139,11 @@ export async function readMovedPage(engine: BrainEngine, input: { sourceId: stri
if (others.length) return held('shared_survivor', `${[old.path, ...others.map(other => other.source_path)].join(', ')} were deleted holding the same content (blob ${short(blob)}) and each still backs a live page, so which of them moved to ${row.source_path} is a person's decision`, [row.slug]);
const [storage] = await engine.executeRaw<{ segmented: boolean }>(`SELECT EXISTS (SELECT 1 FROM pages WHERE id=$1 AND body_storage<>'inline')
OR EXISTS (SELECT 1 FROM page_versions WHERE page_id=$1 AND body_storage<>'inline') AS segmented`, [old.page_id]);
- if (storage?.segmented) return held('segmented_versions', `${old.path} moved to ${row.source_path}, but page ${old.slug} or one of its saved versions is stored in segments (over 1 MiB), whose body generations belong to ${old.slug} and cannot move to ${row.slug}; fold it by hand with the user`, [row.slug]);
+ if (storage?.segmented) return held('segmented_versions', `${old.path} moved to ${row.source_path}, but page ${old.slug} or one of its saved versions is stored in segments (over 1 MiB), whose body generations belong to ${old.slug} and cannot move to ${row.slug}, so it stays as it is`, [row.slug]);
+ const access = await engine.executeRaw<{ id: number; readers: unknown; folder: unknown; readable_by: unknown; world: boolean }>(`SELECT p.id, p.page_readers AS readers, p.folder_rule_ids AS folder,
+ p.frontmatter->'readable_by' AS readable_by, ${privateSnapshotFilterFragment('p')} AS world FROM pages p WHERE p.id=ANY($1::int[])`, [[old.page_id, Number(row.id)]]);
+ const key = (id: number) => { const page = access.find(entry => Number(entry.id) === id); return page ? JSON.stringify([page.readers, page.folder, page.readable_by, page.world]) : null; };
+ if (key(old.page_id) !== key(Number(row.id))) return held('access_differs', `${old.path} moved to ${row.source_path}, but the two pages differ in who may read them (readers, folder rules or privacy label), so a fold would put ${old.slug}'s database-only evidence under ${row.slug}'s access; decide with the user`, [row.slug]);
const survivor: MovedPageRef = { page_id: Number(row.id), slug: row.slug, revision: String(row.revision), path: row.source_path };
const proof = evidence.get(row.source_path)!;
const snapshot = await engine.readPageSnapshot(old.slug, { sourceId });
diff --git a/src/core/repair/moved-pages.ts b/src/core/repair/moved-pages.ts
index 1189e5eeef..b9c88bbeef 100644
--- a/src/core/repair/moved-pages.ts
+++ b/src/core/repair/moved-pages.ts
@@ -34,7 +34,7 @@ import { mergeTwinInto } from '../persistence/twin-merge.ts';
import { readMovedPage, type MovedEvidence, type MovedHeldReason, type MovedPageRef } from '../persistence/moved-pages.ts';
import { readDeletionProvenance } from '../persistence/sync-origin-evidence.ts';
import { clearGitHold, movedPagesPreviewArgv } from '../persistence/sync-holds.ts';
-import { ghostPageNow, scanGhostSource, sourceContext, type GhostOwner } from '../ghost-pages.ts';
+import { ghostPageNamed, ghostPageNow, scanGhostSource, sourceContext, type GhostOwner } from '../ghost-pages.ts';
import { MASS_RECONCILE_MIN_PAGES, MASS_RECONCILE_RATIO, massReconcileAllowed } from '../sync-reconcile.ts';
import { ghostScanRefusal, GHOST_PURGE_FUSE_HOURS, GHOST_REPAIR_LIMIT } from './ghost-pages.ts';
import { afterCursor, repairRequestId, type RepairHandler, type RepairItem, type RepairItemOutcome, type RepairPlan, type RepairScope } from './core.ts';
@@ -96,7 +96,8 @@ export const movedPagesRepair: RepairHandler = {
const refusal = ghostScanRefusal(scan);
if (refusal) throw refusal;
const owner = scan.owner!, root = scan.root!;
- const ghosts = scan.ghosts.filter(ghost => !slugs || slugs.includes(ghost.slug)).slice(0, GHOST_REPAIR_LIMIT);
+ const named = slugs ? await Promise.all(slugs.map(slug => ghostPageNamed(engine, sourceId, slug))) : [];
+ const ghosts = slugs ? named.filter(ghost => ghost !== null) : scan.ghosts.slice(0, GHOST_REPAIR_LIMIT);
const provenance = await readDeletionProvenance(root, ghosts.map(ghost => ghost.path));
const observedAt = new Date().toISOString();
const pairs: MovedPair[] = [], held: HeldPage[] = [];
@@ -120,9 +121,9 @@ export const movedPagesRepair: RepairHandler = {
const hash = previewHash(hashParts(scope, slugs, owner, pairs, held));
if (pairs.length) await saveApprovedSet<ApprovedPair>(engine, { command: 'moved-pages', hash }, pairs.map(pair => ({ ...pair, owner, selection: scope.source_ids })));
const warnings = [
- ...(missing.length ? [`Not a live page whose file is gone in source ${sourceId}${scan.truncated ? ` among the first ${GHOST_REPAIR_LIMIT} checked (preview the whole source after applying)` : ''}, so nothing to fold: ${missing.join(', ')}.`] : []),
+ ...(missing.length ? [`Not a live page whose file is gone in source ${sourceId}, so nothing to fold: ${missing.join(', ')}.`] : []),
...(mass ? [`${pairs.length} fold(s) against ${scan.file_backed} file-backed page(s) (more than ${Math.round(MASS_RECONCILE_RATIO * 100)}%): the apply refuses unless GBRAIN_ALLOW_MASS_RECONCILE=1; check the source first.`] : []),
- ...((scan.truncated || scan.ghosts.length > ghosts.length) && !slugs ? [`More pages whose file is gone may exist past the first ${GHOST_REPAIR_LIMIT} checked; apply this set, then preview again.`] : []),
+ ...((scan.truncated || scan.ghosts.length > ghosts.length) && !slugs ? [`More pages whose file is gone may exist past the first ${GHOST_REPAIR_LIMIT} checked; apply this set, or name pages with --slug (repair file-drift --held lists each moved page's command), then preview again.`] : []),
...(held.length ? [`${held.length} page(s) whose file is gone are not proven moved and are never folded by this apply; each lists why.`] : []),
...(pairs.length ? [MOVED_PAGES_CONSENT_TEXT.risk] : []),
...(!scan.ghosts.length ? [`Source ${sourceId} has no live page whose file is gone; nothing to fold.`] : []),
@@ -181,7 +182,7 @@ export async function movedPairNow(engine: BrainEngine, pair: MovedPair, owner:
return verdict.survivor.page_id === pair.survivor.page_id && verdict.old_blob === pair.old_blob ? null : 'another page is now the moved one';
}
-/** Under both page keys: why the locked pair is no longer the approved one, or null. */
+/** Under both page keys: why the locked pair is no longer the approved one, or null; the old file must still be gone. */
async function pairLocked(tx: BrainEngine, pair: MovedPair): Promise<string | null> {
const rows = await tx.executeRaw<{ id: number; slug: string; revision: string; source_path: string | null }>(`SELECT id, slug, knowledge_revision::text AS revision, source_path FROM pages
WHERE source_id=$1 AND id=ANY($2::int[]) AND deleted_at IS NULL`, [pair.source_id, [pair.old.page_id, pair.survivor.page_id]]);
@@ -189,7 +190,8 @@ async function pairLocked(tx: BrainEngine, pair: MovedPair): Promise<string | nu
const row = rows.find(candidate => Number(candidate.id) === page.page_id);
if (!row || row.slug !== page.slug || String(row.revision) !== page.revision || row.source_path !== page.path) return `${page.slug} changed`;
}
- return null;
+ const now = await ghostPageNow(tx, pair.source_id, pair.old.slug);
+ return now.ghost ? null : `${pair.old.path} is back or no longer gone (${now.reason})`;
}
/** The write itself, inside the caller's transaction with both page keys held. */
diff --git a/test/moved-pages-gst2584.test.ts b/test/moved-pages-gst2584.test.ts
index 3499415394..857ca5b2f7 100644
--- a/test/moved-pages-gst2584.test.ts
+++ b/test/moved-pages-gst2584.test.ts
@@ -344,4 +344,20 @@ for (const backend of testBackends()) {
const after = await runner(engine, 'moved-pages', {});
expect(listed(after, 'notes/alpha')).toMatchObject({ class: 'moved_to' });
}, opts(backend, { 'notes/alpha.md': ALPHA, 'notes/alpha-copy.md': ALPHA, 'notes/beta.md': BETA })), 240_000);
+
+ test(`${backend}: a moved page whose readers were widened at the new path stays held (access differs)`, () => managedBrain(async ({ engine, root }) => {
+ await movedAway(engine, root, () => { mv(root, 'archive/alpha.md')();
+ writeFileSync(join(root, 'archive/alpha.md'), readFileSync(join(root, 'archive/alpha.md'), 'utf8').replace('readable_by: [alice-example]\n', '')); git(root, 'commit', '-qam', 'open it up'); });
+ const preview = await runner(engine, 'moved-pages', {});
+ expect(preview.affected).toBe(0);
+ expect(listed(preview, 'notes/alpha')).toMatchObject({ class: 'held:access_differs' });
+ }, opts(backend, { 'notes/alpha.md': '---\ntitle: Alpha\nreadable_by: [alice-example]\n---\n\nThe alpha body, kept word for word through the move.\n', 'notes/beta.md': BETA })), 240_000);
+
+ test(`${backend}: a file created from the same content after the old one was deleted is not where it moved`, () => managedBrain(async ({ engine, root }) => {
+ await movedAway(engine, root, () => { git(root, 'rm', '-q', 'notes/alpha.md'); git(root, 'commit', '-qm', 'delete');
+ mkdirSync(join(root, 'archive'), { recursive: true }); writeFileSync(join(root, 'archive/recreated.md'), ALPHA); git(root, 'add', '-A'); git(root, 'commit', '-qm', 'recreate later'); });
+ const preview = await runner(engine, 'moved-pages', {});
+ expect(preview.affected).toBe(0);
+ expect(listed(preview, 'notes/alpha')).toMatchObject({ class: 'held:not_moved' });
+ }, opts(backend)), 240_000);
}