Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(#6712 PR 4b): the pass refuses a path whose origin several pages claim (#6517 one origin rule); e2e 6517 rows held per design §2.3 rows 9, 19
garrytanc5f544e1e073
diff --git a/src/core/persistence/sync-discovery.ts b/src/core/persistence/sync-discovery.tsindex ba32f3f836..e75fb3f637 100644--- a/src/core/persistence/sync-discovery.ts+++ b/src/core/persistence/sync-discovery.ts@@ -642,7 +642,7 @@ export function incomingId(discovery: SyncDiscovery, entry: SyncEntry): string |try { return frontmatterIdentity(readSyncContent(discovery, entry)).id; } catch { return null; }}/** #6517: several live pages (the soft-delete exit is named) or several tombstones record one imported origin. */-function ambiguousOriginRefusal(sourceId: string, sourcePath: string, named: Array<{ slug: string }>, ambiguous: 'several_live' | 'several_tombstones'): OperationError {+export function ambiguousOriginRefusal(sourceId: string, sourcePath: string, named: Array<{ slug: string }>, ambiguous: 'several_live' | 'several_tombstones'): OperationError {return opError('page_identity_changed', 'Several pages claim the same imported origin.',`Pages ${named.map(page => page.slug).join(', ')} in ${sourceId} all record ${sourcePath} as their origin; nothing was written. `+ (ambiguous === 'several_live' ? `${sharedOriginExit(sourceId, named.map(page => page.slug))} Then` : 'Keep one, remove or re-point the others, then') + ` run gbrain sync --no-pull --source ${sourceId}.`,diff --git a/src/core/persistence/sync-pass-run.ts b/src/core/persistence/sync-pass-run.tsindex eba8ae35ea..00fb18547c 100644--- a/src/core/persistence/sync-pass-run.ts+++ b/src/core/persistence/sync-pass-run.ts@@ -25,7 +25,7 @@ import { getWriteRequestById } from './journal.ts';import type { WriteRequest } from './model.ts';import { managedSyncWriteDiagnostic } from './sync-write-diagnostic.ts';import { recordedStop, replaysUnchangedRefusal } from './sync-stop-class.ts';-import { adoptLegacyPage, assertTakeoverIdentity, incomingId, syncExcludePatterns, syncGit, type LegacyIdentity, type ManagedSyncContext, type SyncDiscovery, type SyncEntry, type SyncFileRefusal, type SyncSlugCollision } from './sync-discovery.ts';+import { adoptLegacyPage, ambiguousOriginRefusal, assertTakeoverIdentity, incomingId, syncExcludePatterns, syncGit, type LegacyIdentity, type ManagedSyncContext, type SyncDiscovery, type SyncEntry, type SyncFileRefusal, type SyncSlugCollision } from './sync-discovery.ts';import { assertSyncDispatchActive, type SyncAuthority, type SyncProcessingOptions } from './sync-authority.ts';import { recordPassFenceTrend, type PassStamp, type SyncCursorOptions, type SyncIntent } from './sync-prepare.ts';import { OPEN_AT_STAMP_CAP, passFingerprint, readPassRow, SYNC_ORIGIN_DELETED_OP, writePassRow, type ManagedSyncPassValue, type PassEpisode,@@ -561,6 +561,12 @@ export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): Prawait writeLegacyMarkers(engine, level);value.obligations.legacy_markers_at = new Date().toISOString();}+ // #6517, as discovery refuses a claim: several pages record the origin of a path this pass would act on (before any hold).+ const ambiguous = level.paths.find(entry => entry.ambiguousOrigin && !entry.result.settled && !entry.result.inFlight && entry.result.cls !== 'spelling');+ if (ambiguous) {+ await save('blocked', 'page_identity_changed');+ throw ambiguousOriginRefusal(sourceId, entryPaths(level, ambiguous.path).sourcePath, ambiguous.ambiguousOrigin!.slugs.map(slug => ({ slug })), ambiguous.ambiguousOrigin!.kind);+ }await applyPassRound(engine, level, { passId, observedAt: startedAt, remote, admission, fullRound: kind === 'full', obligations: value.obligations, context, processingOptions,grantPrefixes: remote ? authority.writer.slugPrefixes : null }, applied);assertActive();diff --git a/src/core/persistence/sync-pass.ts b/src/core/persistence/sync-pass.tsindex c457fe2759..0baf85c1e6 100644--- a/src/core/persistence/sync-pass.ts+++ b/src/core/persistence/sync-pass.ts@@ -34,7 +34,7 @@ import { confirmedSyncDelta } from '../sync-rename-identity.ts';import { holdBasisMoved, holdRescreenDue, readGitHoldRetryPaths, readGitSourceHolds, SYNC_IMPORT_PROVENANCE_OP, syncImportParserFor,type GitHoldRecord, type SyncImportProvenance } from './sync-holds.ts';import { movedDriftHolds, sameParser } from './sync-prescreen.ts';-import { sameSyncOrigin, syncOriginPath } from './sync-origin.ts';+import { sameSyncOrigin, selectOriginClaimant, syncOriginPath } from './sync-origin.ts';import { hashWorkingLevel, probeDirtiness, readBlobs, readIndexLevel, readTreeLevel, workingChanged, type GitTreeEntry, type WorkingStatCache } from './sync-git-stream.ts';import { classifySyncPath, syncPassKind, type SyncClassified, type SyncIdleBlocker, type SyncPathState } from './sync-classify.ts';import { buildConvergenceReceipt, readOnlySameContentScreen, type ConvergenceReceipt, type ConvergenceScreen } from './sync-convergence.ts';@@ -70,7 +70,9 @@ const SYNC_WRITE_KINDS = ['managed_sync_import', 'managed_sync_delete'];/** One classified path of the shadow level. */export interface ShadowPath { path: string; slug: string | null; pageId: number | null; revision: string | null; state: SyncPathState; result: SyncClassified;/** A page-less path unchanged since the baseline whose page a committed request deleted: the bootstrap writes it a `legacy` marker (`legacy_pageless`). */- legacyPageless?: true }+ legacyPageless?: true;+ /** #6517 (`selectOriginClaimant`): several live pages, or no live page and several tombstones, record this origin. */+ ambiguousOrigin?: { kind: 'several_live' | 'several_tombstones'; slugs: string[] } }export interface ShadowLevel {sourceId: string; incarnation: string; root: string; gitRoot: string; scope: string; slugMode: 'git-root' | 'source-root';@@ -354,10 +356,11 @@ export async function readShadowLevel(engine: BrainEngine, input: { sourceId: st// The page claiming each origin: the live one first, else the newest tombstone.t = timer();- const byOrigin = new Map<string, PageRow>();+ const byOrigin = new Map<string, PageRow>(), claimants = new Map<string, PageRow[]>();for (const row of pages) {if (isWindowsColonTarget(row.source_path)) continue;const key = gitPathOf(pageOrigin(row));+ claimants.set(key, [...claimants.get(key) ?? [], row]);const prior = byOrigin.get(key);if (!prior || (prior.deleted && !row.deleted) || (prior.deleted === row.deleted && Number(row.id) > Number(prior.id))) byOrigin.set(key, row);}@@ -499,7 +502,10 @@ export async function readShadowLevel(engine: BrainEngine, input: { sourceId: st// Rows 1-10 precede row 11 and `matched` settles either way, so only the rest are Dp candidates (design v3.2 §2.1).const staged = mode === 'committed' && tree.has(path) && (index.get(path)?.oid !== tree.get(path)!.oid || (index.get(path)?.stage ?? 0) !== 0);if (mode === 'committed' && tree.has(path) && (!settledBeforeDirtiness.has(result.cls) || staged)) candidates.push(path);- paths.push({ path, slug: row?.slug ?? null, pageId: row ? Number(row.id) : null, revision: row?.revision ?? null, state, result, ...(legacyPageless ? { legacyPageless } : {}) });+ const claimed = claimants.get(path) ?? [];+ const { ambiguous } = claimed.length > 1 ? selectOriginClaimant(claimed.map(page => ({ ...page, deleted_at: page.deleted ? true : null }))) : { ambiguous: null };+ const ambiguousOrigin = ambiguous ? { kind: ambiguous, slugs: claimed.filter(page => ambiguous === 'several_tombstones' || !page.deleted).map(page => page.slug) } : undefined;+ paths.push({ path, slug: row?.slug ?? null, pageId: row ? Number(row.id) : null, revision: row?.revision ?? null, state, result, ...(legacyPageless ? { legacyPageless } : {}), ...(ambiguousOrigin ? { ambiguousOrigin } : {}) });}timings.classify = t();if (candidates.length) {diff --git a/test/e2e/managed-sync-shared-origin-6517.test.ts b/test/e2e/managed-sync-shared-origin-6517.test.tsindex 5325d4eadc..71d85638e2 100644--- a/test/e2e/managed-sync-shared-origin-6517.test.ts+++ b/test/e2e/managed-sync-shared-origin-6517.test.ts@@ -81,7 +81,7 @@ for (const backend of testBackends()) describe(`[${backend}] #6517 managed syncrmSync(home, { recursive: true, force: true });}, 60_000);- test('two live claimants refuse the run and name the exit; after the loser is soft-deleted the file imports, edits and deletes through both guards; a single tombstone resurrects', async () => {+ test('two live claimants refuse the run and name the exit; after the loser is soft-deleted the file imports, edits and deletes through both guards; a single edited tombstone is held', async () => {const f = await twins();writeFileSync(f.file, note('Alpha, version two.')); commit(f.root, 'version two');const refused = await sync(f.opts).then(() => null, error => error as Error & { code?: string; suggestion?: string });@@ -114,13 +114,17 @@ for (const backend of testBackends()) describe(`[${backend}] #6517 managed syncconst ambiguous = await sync(f.opts).then(() => null, error => error as Error & { code?: string });expect(ambiguous?.code).toBe('page_identity_changed');expect((await page(f.id, 'alpha'))!.deleted_at).not.toBeNull();- // Point the twin tombstone elsewhere: one tombstone left, which the file resurrects (same page id).+ // Point the twin tombstone elsewhere: one tombstone left. #6712 PR 4b (design v3.2 §2.3 row 9, `deleted_edited`): the file+ // changed after its page was deleted, so the pass holds it (side deleted, state tombstone_edited) for a person's Decision+ // instead of reviving the page; repair file-drift --held --prefer file is the way back.await coordinated(f.id, 'UPDATE pages SET source_path=NULL WHERE source_id=$1 AND slug=$2', [f.id, 'alpha-twin']);- const resurrected = await sync(f.opts);- expect(resurrected.managedWrite).toBeUndefined();+ const returned = await sync(f.opts);+ expect(returned.managedWrite).toBeUndefined();+ expect((returned.held ?? []).map(item => [item.path, item.code, item.side, item.state, item.slug])).toEqual([['alpha.md', 'file_drift', 'deleted', 'tombstone_edited', 'alpha']]);const back = (await page(f.id, 'alpha'))!;- expect(back).toMatchObject({ id: survivor.id, deleted_at: null });- expect(back.compiled_truth).toContain('Alpha returns');+ expect(back.id).toBe(survivor.id);+ expect(back.deleted_at).not.toBeNull();+ expect(back.compiled_truth).toContain('version three');expect(await readManagedSyncFailures(engine, [f.id])).toEqual([]);}, 180_000);@@ -145,9 +149,14 @@ for (const backend of testBackends()) describe(`[${backend}] #6517 managed syncexpect((await page(f.id, 'alpha'))!.deleted_at).not.toBeNull();expect(error ? error.code : result!.status === 'synced' && (result!.held_count ?? 0) === 0 && !result!.managedWrite ? 'clean import' : 'refused').not.toBe('clean import');expect(existsSync(f.file)).toBe(true);- // Once the twin is the one live claimant, the next run (a new request past the frozen refusal) imports the file into it.+ // #6712 PR 4b (design v3.2 §2.3 row 19, `drift`): once the twin is the one live claimant, it has no import record and no+ // proof that the file was ever its own, so the pass holds it file_drift (side unknown) instead of importing over it, and+ // the next run leaves it held and unchanged.+ expect(error).toBeNull();+ expect((result!.held ?? []).map(item => [item.path, item.code, item.side, item.slug])).toEqual([['alpha.md', 'file_drift', 'unknown', 'alpha-twin']]);const next = await sync({ ...f.opts, retryFailed: true });expect(next.managedWrite).toBeUndefined();- expect((await page(f.id, 'alpha-twin'))!.compiled_truth).toContain('version two');+ expect(next.holds_outstanding).toBe(1);+ expect((await page(f.id, 'alpha-twin'))!.compiled_truth).toBe('A twin recording alpha.');}, 180_000);});