Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(persistence): judge unplaced holds in the conversion plan, and count discards by cause (#7617)

garrytan010e12b266ee
diff --git a/src/commands/sources-canonical.ts b/src/commands/sources-canonical.ts
index ecdbdc465e..970003bf61 100644
--- a/src/commands/sources-canonical.ts
+++ b/src/commands/sources-canonical.ts
@@ -37,14 +37,18 @@ const counts = (record: Record<string, number>) => Object.entries(record).filter
const sample = (paths: string[]) => paths.map(path => ` ${path}`);
export function describeGitPreview(p: GitConversionPreview): string {
+ const { detail } = p.discard;
+ const causes = [...Object.entries(detail.git_overwrites_database).flatMap(([cls, kinds]) => Object.entries(kinds).map(([kind, n]) => `git_overwrites_database ${cls} on ${kind} ${n}`)),
+ ...(['uncommitted_edit', 'unparseable', 'export_mismatch'] as const).flatMap(category => Object.entries(detail[category]).map(([key, n]) => `${category} ${key} ${n}`))];
const lines = [`Source ${p.source_id}${p.strict ? ' (already git-canonical)' : ''} at ${p.head?.slice(0, 12) ?? 'no commit'}: ${p.pages} live page(s), ${p.equal} equal to HEAD.`,
`Adopt (write the database's page to its file and commit it through the door, ${p.adopt.groups} commit(s) of up to ${CONVERSION_GROUP_MAX}): ${p.adopt.count} (${counts(p.adopt.by)}).`, ...sample(p.adopt.sample),
`Declared database-only (nothing written, nothing deleted): ${p.declared.count} (${counts(p.declared.by)}).`,
`Git wins (the strict pass indexes the committed file): ${p.git_wins.count} (${counts(p.git_wins.by)}).`, ...sample(p.git_wins.sample),
- `Holds cleared so Git's verdict runs: ${p.holds.count} (${counts(p.holds.by)}).`,
+ `Holds cleared so Git's verdict runs: ${p.holds.count} (${counts(p.holds.by)})${p.holds.unplaced.count ? `; ${p.holds.unplaced.count} at a path nothing else placed (${counts(p.holds.unplaced.by)}), counted below by the strict pass's verdict` : ''}.`,
`Parked effects: ${p.parked_effects.count} (retry ${p.parked_effects.retry}, reclassify as declared ${p.parked_effects.reclassify}; ${counts(p.parked_effects.by_code)}).`,
`The strict pass also imports ${p.index.imports} and deletes ${p.index.deletes} page(s) where the database holds nothing Git lacks.`,
- `Database content that would be discarded: ${p.discard.count}${p.discard.count ? ` (${counts(p.discard.by)}); the apply refuses until it is 0` : ''}.`, ...sample(p.discard.sample)];
+ `Database content that would be discarded: ${p.discard.count}${p.discard.count ? ` (${counts(p.discard.by)}); the apply refuses until it is 0` : ''}.`,
+ ...(causes.length ? [` By cause: ${causes.join(', ')}.`] : []), ...sample(p.discard.sample)];
lines.push(p.remaining === 0 && p.strict ? 'Nothing is left to convert.' : `Nothing changed. To apply: ${p.apply.join(' ')}`);
return lines.join('\n');
}
diff --git a/src/commands/sources-git-gap.ts b/src/commands/sources-git-gap.ts
index 33b3ac37ec..d28dd79d43 100644
--- a/src/commands/sources-git-gap.ts
+++ b/src/commands/sources-git-gap.ts
@@ -27,7 +27,7 @@ import { GIT_HOLD_OP, readSyncImportProvenances } from '../core/persistence/sync
import { DERIVED_LINK_SOURCES } from '../core/persistence/twin-merge.ts';
import { scannerSlugRootMode, scannerSourcePath } from '../core/write-through.ts';
import { compareInlineExportFile, compareSegmentedExportBlob, DECLARED_CLASSES, declaredDatabaseOnly, ignoredPaths, readBlobs, readHeadTree, worktreeBlobOid,
- type DeclaredClass, type ExportFileComparison, type HeadTree, type TreeBlob } from '../core/persistence/git-gap.ts';
+ type DeclaredClass, type ExportFileComparison, type HeadTree, type TreeBlob, type UnparseableReason } from '../core/persistence/git-gap.ts';
const USAGE = 'Usage: gbrain sources git-gap <source-id> [--sample <n>] [--json]';
export const GIT_GAP_DOCS = 'docs/designs/GIT_CANONICAL_MEMORY.md#the-git-gap-census';
@@ -40,7 +40,7 @@ export type WorktreeState = typeof WORKTREE_STATES[number];
/** One page as the census classified it, handed to a caller that plans per page (G8 conversion, persistence/git-conversion.ts). */
export interface GitGapPage { id: string; slug: string; revision: string | null; path: string | null; state: PageState; segmented: boolean;
- declared?: DeclaredClass; worktree?: WorktreeState; headBlob?: string; databaseAlsoMoved?: boolean }
+ declared?: DeclaredClass; worktree?: WorktreeState; headBlob?: string; databaseAlsoMoved?: boolean; unparseable?: UnparseableReason }
export interface GitGapSample { slug: string; path: string; state: PageState; fields?: string[]; declared?: DeclaredClass; basis?: 'import_record' | 'no_import_record'; worktree?: WorktreeState }
@@ -225,7 +225,7 @@ async function censusBatch(tx: BrainEngine, batch: Key[], census: GitGapCensus,
census.worktree![worktree]++;
if (blob.mode !== '100644' && blob.mode !== '100755') {
census.states.unparseable++;
- ctx.collect?.(collected(key, rel, 'unparseable', { worktree, headBlob: blob.oid }));
+ ctx.collect?.(collected(key, rel, 'unparseable', { worktree, headBlob: blob.oid, unparseable: blob.mode === '120000' ? 'symlink' : 'non_regular_mode' }));
note(census, ctx.sample, { slug: key.slug, path: rel, state: 'unparseable', worktree });
continue;
}
@@ -252,7 +252,7 @@ async function compareBatch(tx: BrainEngine, compare: Array<{ key: Key; path: st
if (compared.state === 'equal') { census.states.equal++; ctx.collect?.(collected(item.key, item.rel, 'equal', { worktree: item.worktree, headBlob: item.blob.oid })); continue; }
if (compared.state === 'unparseable') {
census.states.unparseable++;
- ctx.collect?.(collected(item.key, item.rel, 'unparseable', { worktree: item.worktree, headBlob: item.blob.oid }));
+ ctx.collect?.(collected(item.key, item.rel, 'unparseable', { worktree: item.worktree, headBlob: item.blob.oid, unparseable: compared.reason }));
note(census, ctx.sample, { slug: item.key.slug, path: item.rel, state: 'unparseable', worktree: item.worktree });
continue;
}
diff --git a/src/core/persistence/git-conversion.ts b/src/core/persistence/git-conversion.ts
index e62316dbac..b1d1aa4997 100644
--- a/src/core/persistence/git-conversion.ts
+++ b/src/core/persistence/git-conversion.ts
@@ -42,12 +42,13 @@ import { currentSubmissionAuthority } from '../minions/submission-authority.ts';
import { inlineExportMarkdown, readExportPage, readExportPages, readExportWithdrawals, type ExportSnapshot } from '../export-snapshot.ts';
import { scannerSlugRootMode, scannerSourcePath } from '../write-through.ts';
import { censusGitGap, type GitGapCensus, type GitGapPage } from '../../commands/sources-git-gap.ts';
-import { compareInlineExportFile, ignoredPaths } from './git-gap.ts';
+import { compareInlineExportFile, ignoredPaths, type DeclaredClass, type ExportFileComparison } from './git-gap.ts';
import { commitThroughDoor } from './git-door.ts';
import { currentVerifiedLocalWriter, localHostId } from './identity.ts';
import { acquireWorktree, readManagedMode } from './ownership.ts';
import { resolveManagedSyncContext, type ManagedSyncContext } from './sync-discovery.ts';
import { readShadowLevel } from './sync-pass.ts';
+import { classifySyncPath } from './sync-classify.ts';
import { clearGitHold, fileDriftSide, readGitSourceHolds, readSyncImportProvenances, type GitHoldRecord } from './sync-holds.ts';
import { readDeletionProvenance } from './sync-origin-evidence.ts';
import { retryParkedEffects } from './effect-retry.ts';
@@ -75,6 +76,18 @@ export const DISCARD_CATEGORIES = ['both_moved', 'held_drift_both', 'held_drift_
export type DiscardCategory = typeof DISCARD_CATEGORIES[number];
interface Counted<K extends string> { count: number; by: Record<K, number>; sample: string[] }
+/**
+ * Counts behind some discard categories (outside the preview hash). git_overwrites_database: the class the path has on a
+ * source that is not strict (with its sub, side or state), then the page's kind (`declared:<class>`, `live`, or
+ * `tombstone_or_none`); uncommitted_edit: the working-tree state; unparseable: why the committed file cannot be read;
+ * export_mismatch: each field the page's export reads back different (`unparseable:<reason>` when it does not parse).
+ */
+export interface DiscardDetail {
+ git_overwrites_database: Record<string, Record<string, number>>;
+ uncommitted_edit: Record<string, number>;
+ unparseable: Record<string, number>;
+ export_mismatch: Record<string, number>;
+}
/** `disk`: sha256 of the working-tree bytes the preview saw (HEAD's or the export's), null when the file was absent. */
export interface AdoptItem { id: string; source_id: string; slug: string; revision: string | null; path: string; state: AdoptState; disk: string | null }
interface HoldItem { path: string; code: string; side: string | null; observed_at: string; action: 'git_wins' | 'rescreen' | 'blocked' }
@@ -92,11 +105,12 @@ export interface GitConversionPreview {
adopt: Counted<AdoptState> & { action: 'commit_through_door'; groups: number };
declared: Counted<string> & { action: 'none' };
git_wins: Counted<GitWinsReason> & { action: 'index_committed_blob' };
- holds: Counted<string> & { action: 'clear' };
+ /** `unplaced`: holds at a path no category above placed (a declared page, no live page), which the index check judges as the strict pass will see them. */
+ holds: Counted<string> & { action: 'clear'; unplaced: { count: number; by: Record<string, number> } };
parked_effects: { count: number; retry: number; reclassify: number; by_code: Record<string, number> };
/** What a strict pass would import or delete that no page row loses (files with no row, removals Git committed). */
index: { imports: number; deletes: number };
- discard: Counted<DiscardCategory>;
+ discard: Counted<DiscardCategory> & { detail: DiscardDetail };
/** Every item the apply still has to act on (adopt, git_wins, holds, parked retries, discard); 0 on a converted source. */
remaining: number;
preview_hash: string;
@@ -107,6 +121,8 @@ export interface GitConversionPreview {
export interface GitConversionPlan { preview: GitConversionPreview; context: ManagedSyncContext; adopt: AdoptItem[]; holds: HoldItem[]; parked: ParkedItem[]; settled: Set<string>; incarnation: string }
const counted = <K extends string>(keys: readonly K[]): Counted<K> => ({ count: 0, by: Object.fromEntries(keys.map(key => [key, 0])) as Record<K, number>, sample: [] });
+const bump = (into: Record<string, number>, key: string) => { into[key] = (into[key] ?? 0) + 1; };
+const emptyDiscard = () => ({ ...counted(DISCARD_CATEGORIES), detail: { git_overwrites_database: {}, uncommitted_edit: {}, unparseable: {}, export_mismatch: {} } as DiscardDetail });
function tally<K extends string>(into: Counted<K>, key: K, path: string): void {
into.count++;
into.by[key] = (into.by[key] ?? 0) + 1;
@@ -169,7 +185,7 @@ export async function planGitConversion(engine: BrainEngine, sourceId: string):
const side = hold?.code === 'file_drift' ? fileDriftSide(hold.meta) ?? null : null;
switch (page.state) {
case 'declared_database_only': tally(preview.declared, page.declared!, path); continue;
- case 'unparseable': discard('unparseable', path); continue;
+ case 'unparseable': discard('unparseable', path); bump(preview.discard.detail.unparseable, page.unparseable ?? 'unknown'); continue;
case 'unsafe_path': discard('unsafe_path', path); continue;
case 'git_ahead':
if (side === 'unknown') discard('held_drift_unknown_differs', path);
@@ -200,7 +216,12 @@ export async function planGitConversion(engine: BrainEngine, sourceId: string):
preview.parked_effects.retry = parked.filter(item => item.action === 'retry').length;
preview.parked_effects.reclassify = parked.filter(item => item.action === 'reclassify').length;
const settled = new Set([...equal, ...adopt.map(item => item.path), ...accepted]);
- await planIndex(engine, context, preview, new Set([...settled, ...held.keys(), ...discarded]), discard);
+ const placed = new Set([...settled, ...discarded]);
+ const unplaced = holds.filter(hold => !placed.has(hold.path));
+ for (const hold of unplaced) bump(preview.holds.unplaced.by, hold.side ? `${hold.code}:${hold.side}` : hold.code);
+ preview.holds.unplaced.count = unplaced.length;
+ const declared = new Map(pages.flatMap(page => page.declared ? [[page.id, page.declared] as const] : []));
+ await planIndex(engine, context, preview, placed, new Set(unplaced.map(hold => hold.path)), declared, discard);
preview.adopt.groups = Math.ceil(adopt.length / CONVERSION_GROUP_MAX);
preview.remaining = preview.adopt.count + preview.git_wins.count + preview.holds.count + preview.parked_effects.retry + preview.discard.count;
preview.preview_hash = previewHash({ source: sourceId, incarnation, to: 'git', strict: preview.strict, head: preview.head, states: census.states, declared: census.declared,
@@ -213,8 +234,8 @@ export async function planGitConversion(engine: BrainEngine, sourceId: string):
function emptyPreview(sourceId: string, context: ManagedSyncContext, census: GitGapCensus): GitConversionPreview {
return { status: 'preview', source_id: sourceId, to: 'git', strict: context.source.config?.canonical === 'git', head: census.head, pages: census.pages, equal: census.states.equal,
adopt: { ...counted(ADOPT_STATES), action: 'commit_through_door', groups: 0 }, declared: { ...counted<string>([]), action: 'none' },
- git_wins: { ...counted(GIT_WINS_REASONS), action: 'index_committed_blob' }, holds: { ...counted<string>([]), action: 'clear' },
- parked_effects: { count: 0, retry: 0, reclassify: 0, by_code: {} }, index: { imports: 0, deletes: 0 }, discard: counted(DISCARD_CATEGORIES), remaining: 0, preview_hash: '', apply: [] };
+ git_wins: { ...counted(GIT_WINS_REASONS), action: 'index_committed_blob' }, holds: { ...counted<string>([]), action: 'clear', unplaced: { count: 0, by: {} } },
+ parked_effects: { count: 0, retry: 0, reclassify: 0, by_code: {} }, index: { imports: 0, deletes: 0 }, discard: emptyDiscard(), remaining: 0, preview_hash: '', apply: [] };
}
/** A hold's fate: a held deletion or an unknown-side drift goes to Git (planGitConversion discards the drift when its row differs), a both-sides drift is database content Git would discard, the rest re-screen. */
@@ -226,14 +247,14 @@ function holdItem(hold: GitHoldRecord): HoldItem {
/**
* What the adoption plan needs of a page's export view, kept instead of the view: the sha256 of its exported bytes, and
- * whether those bytes read back equal under the census contract.
+ * how those bytes read back under the census contract.
*/
class ExportChecks {
- private readonly checks = new Map<string, { digest: string; readsBack: boolean }>();
+ private readonly checks = new Map<string, { digest: string; readBack: ExportFileComparison }>();
constructor(private readonly root: string, private readonly mode: Awaited<ReturnType<typeof scannerSlugRootMode>>) {}
add(id: string, path: string, snapshot: ExportSnapshot): void {
const bytes = Buffer.from(inlineExportMarkdown(snapshot));
- this.checks.set(id, { digest: sha256(bytes), readsBack: compareInlineExportFile(bytes, scannerSourcePath(this.root, join(this.root, path), this.mode), snapshot).state === 'equal' });
+ this.checks.set(id, { digest: sha256(bytes), readBack: compareInlineExportFile(bytes, scannerSourcePath(this.root, join(this.root, path), this.mode), snapshot) });
}
get(id: string) { return this.checks.get(id); }
}
@@ -265,9 +286,18 @@ async function planAdoption(engine: BrainEngine, sourceId: string, root: string,
if (!ignored || ignored.has(path)) { discard('ignored_target', path); continue; }
if (page.segmented) { discard('segmented_page', path); continue; }
const check = exported.get(page.id)!;
- if (!check.readsBack) { discard('export_mismatch', path); continue; }
+ const { readBack } = check;
+ if (readBack.state !== 'equal') {
+ discard('export_mismatch', path);
+ for (const field of readBack.state === 'differs' ? readBack.paths : [`unparseable:${readBack.reason}`]) bump(preview.discard.detail.export_mismatch, field);
+ continue;
+ }
const disk = diskBytes(join(root, path));
- if (page.worktree !== 'clean' && page.worktree !== 'absent' && !(disk && sha256(disk) === check.digest)) { discard('uncommitted_edit', path); continue; }
+ if (page.worktree !== 'clean' && page.worktree !== 'absent' && !(disk && sha256(disk) === check.digest)) {
+ discard('uncommitted_edit', path);
+ bump(preview.discard.detail.uncommitted_edit, page.worktree ?? 'unknown');
+ continue;
+ }
adopt.push({ id: page.id, source_id: sourceId, slug: page.slug, revision: page.revision, path, state, disk: disk ? sha256(disk) : null });
tally(preview.adopt, state, path);
}
@@ -296,19 +326,26 @@ async function readParked(engine: BrainEngine, sourceId: string): Promise<Parked
/**
* The level a strict pass reads (G3's reindex preview): what it imports or deletes, and every page version it would
- * replace that the plan has not placed (`git_overwrites_database`). `planned`: paths already placed (equal, adopted,
- * accepted, held or counted as discard).
+ * replace that the plan has not placed (`git_overwrites_database`). `placed`: paths the plan already placed (equal,
+ * adopted, accepted or counted as discard). A hold the plan did not place is cleared before the strict pass, so its path
+ * is judged as that pass will see it, without the hold. `declared`: the census's declared class by page id.
*/
-async function planIndex(engine: BrainEngine, context: ManagedSyncContext, preview: GitConversionPreview, planned: ReadonlySet<string>,
- discard: (category: DiscardCategory, path: string) => void): Promise<void> {
+async function planIndex(engine: BrainEngine, context: ManagedSyncContext, preview: GitConversionPreview, placed: ReadonlySet<string>, unplacedHolds: ReadonlySet<string>,
+ declared: ReadonlyMap<string, DeclaredClass>, discard: (category: DiscardCategory, path: string) => void): Promise<void> {
const level = await readShadowLevel(engine, { sourceId: context.sourceId, full: true, context: strictContext(context) });
if (!level) return;
for (const entry of level.paths) {
- if (entry.result.settled || entry.result.inFlight || (entry.result.action !== 'import' && entry.result.action !== 'delete')) continue;
const path = sourcePath(level.scope, entry.path);
- if (planned.has(path)) continue;
- if (entry.result.gitWins) discard('git_overwrites_database', path);
- else preview.index[entry.result.action === 'import' ? 'imports' : 'deletes']++;
+ if (placed.has(path)) continue;
+ const state = unplacedHolds.has(path) ? { ...entry.state, hold: null } : entry.state;
+ const result = state === entry.state ? entry.result : classifySyncPath(state, { strict: true });
+ if (result.settled || result.inFlight || (result.action !== 'import' && result.action !== 'delete')) continue;
+ if (!result.gitWins) { preview.index[result.action === 'import' ? 'imports' : 'deletes']++; continue; }
+ discard('git_overwrites_database', path);
+ const before = classifySyncPath(state);
+ const detail = before.cls === result.gitWins ? before.sub ?? before.side ?? before.state : undefined;
+ const kind = !state.page?.live ? 'tombstone_or_none' : declared.has(String(entry.pageId)) ? `declared:${declared.get(String(entry.pageId))}` : 'live';
+ bump(preview.discard.detail.git_overwrites_database[detail ? `${result.gitWins}:${detail}` : result.gitWins] ??= {}, kind);
}
}
@@ -345,7 +382,7 @@ export async function applyGitConversion(engine: BrainEngine, sourceId: string,
}
const parked = await settleParked(engine, sourceId, plan.parked);
const recheck = await readShadowLevel(engine, { sourceId, full: true, context: strictContext(plan.context) });
- const preview = { ...plan.preview, discard: counted(DISCARD_CATEGORIES) };
+ const preview = { ...plan.preview, discard: emptyDiscard() };
for (const entry of recheck?.paths ?? []) {
const path = sourcePath(recheck!.scope, entry.path);
if (!entry.result.settled && !entry.result.inFlight && entry.result.gitWins && !plan.settled.has(path)) tally(preview.discard, 'git_overwrites_database', path);
diff --git a/src/core/persistence/git-gap.ts b/src/core/persistence/git-gap.ts
index 6c103f4599..c1157aa323 100644
--- a/src/core/persistence/git-gap.ts
+++ b/src/core/persistence/git-gap.ts
@@ -74,7 +74,9 @@ export async function ignoredPaths(root: string, relativePaths: string[]): Promi
return result.reason === 'exit' && result.status === 1 && ignored.size === 0 ? ignored : null;
}
-export type ExportFileComparison = { state: 'equal' } | { state: 'differs'; paths: string[] } | { state: 'unparseable' };
+/** Why a committed file cannot be compared: a symlink (or another non-regular mode), bytes that are not UTF-8, or frontmatter that does not parse. */
+export type UnparseableReason = 'symlink' | 'non_regular_mode' | 'not_utf8' | 'frontmatter';
+export type ExportFileComparison = { state: 'equal' } | { state: 'differs'; paths: string[] } | { state: 'unparseable'; reason: UnparseableReason };
/**
* The equality contract for an inline page: the file, parsed the way reconcile parses a canonical file (aligned with the
@@ -84,10 +86,10 @@ export type ExportFileComparison = { state: 'equal' } | { state: 'differs'; path
export function compareInlineExportFile(raw: Buffer, importPath: string, snapshot: ExportSnapshot): ExportFileComparison {
const { page, tags } = snapshot;
const text = raw.toString('utf8');
- if (!Buffer.from(text).equals(raw)) return { state: 'unparseable' };
+ if (!Buffer.from(text).equals(raw)) return { state: 'unparseable', reason: 'not_utf8' };
const reading = reconcileFileReading(text, importPath, page);
const parsed = parseMarkdown(reading.content, `${page.slug}.md`, { validate: true, expectedSlug: page.slug });
- if (parsed.errors?.some(e => !['MISSING_OPEN', 'EMPTY_FRONTMATTER'].includes(e.code))) return { state: 'unparseable' };
+ if (parsed.errors?.some(e => !['MISSING_OPEN', 'EMPTY_FRONTMATTER'].includes(e.code))) return { state: 'unparseable', reason: 'frontmatter' };
if (parsed.slug !== page.slug) return { state: 'differs', paths: ['/slug'] };
alignWithStored(parsed, page, reading.inferred);
const file = reconcileCanonical(parsed, parsed.tags), database = reconcileCanonical(page, tags);
diff --git a/test/git-canonical-conversion-g8a.test.ts b/test/git-canonical-conversion-g8a.test.ts
index 2a93e4f4cd..7a6a1bdeb1 100644
--- a/test/git-canonical-conversion-g8a.test.ts
+++ b/test/git-canonical-conversion-g8a.test.ts
@@ -11,7 +11,7 @@
import { describe, expect, test } from 'bun:test';
import { execFileSync } from 'node:child_process';
import { randomUUID } from 'node:crypto';
-import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import type { BrainEngine } from '../src/core/engine.ts';
@@ -27,7 +27,7 @@ import { ADOPTION_BATCH, applyGitConversion, applyMixedConversion, CONVERSION_GR
import { renderFactsTable } from '../src/core/facts-fence.ts';
import { withSubmissionAuthority } from '../src/core/minions/submission-authority.ts';
import { censusGitGap } from '../src/commands/sources-git-gap.ts';
-import { runSourcesCanonical } from '../src/commands/sources-canonical.ts';
+import { describeGitPreview, runSourcesCanonical } from '../src/commands/sources-canonical.ts';
import { _resetCliExitVerdictForTests } from '../src/core/cli-force-exit.ts';
import { managedBrain, type ManagedBrain } from './helpers/managed-brain.ts';
import { isolatedSharedSkillsEngine } from './helpers/shared-skills-engine.ts';
@@ -121,6 +121,23 @@ async function dropImportRecord(engine: BrainEngine, slug: string): Promise<void
await engine.executeRaw("DELETE FROM op_checkpoints WHERE op='sync-import-provenance' AND fingerprint LIKE $1", [`default:%:${row!.id}`]);
}
+/**
+ * notes/same moved on both sides with no import record, so sync holds it (file_drift, side unknown), and then turned
+ * private in the database: a declared page whose committed file differs from its row, at a held path.
+ */
+async function heldPrivateDrift(brain: ManagedBrain): Promise<void> {
+ const { engine, root } = brain;
+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');
+ await databaseOnlyEdit(engine, 'notes/same', 'Written to the database alone: notes/same.');
+ writeFileSync(join(root, 'notes/same.md'), note('notes/same', 'The committed edit of notes/same.'));
+ git(root, 'commit', '-qam', 'edit same');
+ await dropImportRecord(engine, 'notes/same');
+ await performManagedSync(engine, OPTS);
+ expect(await holds(engine)).toEqual(['notes/same.md file_drift']);
+ await engine.transaction(tx => withCoordinatedWrite(tx, ['default'], () => tx.executeRaw(
+ `UPDATE pages SET frontmatter=frontmatter || '{"visibility":"private"}'::jsonb WHERE source_id='default' AND slug='notes/same'`), TEST_WRITE_ATTRIBUTION));
+}
+
const DRIFT_COMMITTED = 'The committed edit of notes/drift.';
/**
* Every category on one non-strict source: notes/ahead and notes/dbonly hold content Git lacks, and notes/legacy has no
@@ -316,6 +333,50 @@ for (const backend of testBackends()) describe(`[${backend}] G8a: sources canoni
expect(reads).toBeLessThanOrEqual(2 * (Math.ceil(2 * WIDE / 256) + Math.ceil(WIDE / ADOPTION_BATCH)));
}, { databaseUrl, setup: wideSetup }), 300_000);
+ test('#7618: a hold at a declared page\'s path is judged by the strict verdict, so a page Git would overwrite is a discard', () => managedBrain(async brain => {
+ const { engine, root } = brain;
+ await heldPrivateDrift(brain);
+ const base = git(root, 'rev-parse', 'HEAD');
+ const { preview } = await planGitConversion(engine, 'default');
+ expect(preview).toMatchObject({ declared: { by: { private: 1 } }, holds: { count: 1, unplaced: { count: 1, by: { 'file_drift:unknown': 1 } } },
+ discard: { count: 1, by: { git_overwrites_database: 1 }, sample: ['notes/same.md'] } });
+ expect(Object.values(preview.discard.detail.git_overwrites_database)).toEqual([{ 'declared:private': 1 }]);
+ await expect(applyGitConversion(engine, 'default', preview.preview_hash, PROCESSING)).rejects.toMatchObject({ code: 'git_conversion_blocked', detail: 'git_overwrites_database' });
+ expect(await holds(engine)).toEqual(['notes/same.md file_drift']);
+ expect(git(root, 'rev-parse', 'HEAD')).toBe(base);
+ expect((await page(engine, 'notes/same'))!.body).toContain('Written to the database alone: notes/same.');
+ }, { databaseUrl, setup }), 180_000);
+
+ test('#7618: the preview counts each discard by its cause', () => managedBrain(async brain => {
+ const { engine, root } = brain;
+ await heldPrivateDrift(brain);
+ for (const slug of ['notes/ahead', 'notes/legacy']) await databaseOnlyEdit(engine, slug, `Written to the database alone: ${slug}.`);
+ writeFileSync(join(root, 'notes/ahead.md'), note('notes/ahead', 'An uncommitted edit of notes/ahead.'));
+ rmSync(join(root, 'notes/legacy.md'));
+ await databaseOnlyPage(brain, 'notes/dbonly', note('notes/dbonly', 'Only in the database.'));
+ writeFileSync(join(root, 'notes/dbonly.md'), note('notes/dbonly', 'An untracked file that differs.'));
+ // Committed without a sync: a broken frontmatter, bytes that are not UTF-8, and a symlink where a page's file was.
+ writeFileSync(join(root, 'notes/gitmoved.md'), '---\ntitle: [unclosed\n---\nBody\n');
+ writeFileSync(join(root, 'notes/removed.md'), Buffer.from([0xff, 0xfe, 0x00]));
+ rmSync(join(root, 'notes/drift.md')); symlinkSync('same.md', join(root, 'notes/drift.md'));
+ git(root, 'add', 'notes/gitmoved.md', 'notes/removed.md', 'notes/drift.md'); git(root, 'commit', '-qm', 'unreadable files');
+ // Database-only rows whose export reads back different: a padded title, and frontmatter tags with no tag rows.
+ await engine.transaction(tx => withCoordinatedWrite(tx, ['default'], () => tx.executeRaw(`INSERT INTO pages(source_id,slug,type,title,compiled_truth,timeline,frontmatter)
+ VALUES ('default','notes/padded','concept',' Padded title ','Body.','','{}'::jsonb), ('default','notes/tagged','concept','Tagged','Body.','',$1::text::jsonb)`,
+ [JSON.stringify({ tags: ['alpha-example'] })]), TEST_WRITE_ATTRIBUTION));
+ const { preview } = await planGitConversion(engine, 'default');
+ expect(preview.discard.by).toMatchObject({ git_overwrites_database: 1, uncommitted_edit: 3, unparseable: 3, export_mismatch: 2 });
+ expect(preview.discard.detail).toMatchObject({ uncommitted_edit: { modified: 1, deleted: 1, untracked: 1 }, unparseable: { frontmatter: 1, not_utf8: 1, symlink: 1 },
+ export_mismatch: { '/title': 1, '/tags': 1 } });
+ expect(Object.values(preview.discard.detail.git_overwrites_database)).toEqual([{ 'declared:private': 1 }]);
+ const lines = describeGitPreview(preview);
+ expect(lines).toContain('uncommitted_edit deleted 1');
+ expect(lines).toContain('1 at a path nothing else placed (file_drift:unknown 1)');
+ // The hash binds the counts (discard.by), not the causes, and reading the plan again gives the same one.
+ const again = (await planGitConversion(engine, 'default')).preview;
+ expect(again.preview_hash).toBe(preview.preview_hash);
+ }, { databaseUrl, setup }), 180_000);
+
test('work that lands after the strict-equivalent pass leaves the source strict and reports incomplete', () => managedBrain(async brain => {
const { engine, root } = brain;
expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');
diff --git a/test/git-gap-census.test.ts b/test/git-gap-census.test.ts
index 70645f5c12..9de1670eb2 100644
--- a/test/git-gap-census.test.ts
+++ b/test/git-gap-census.test.ts
@@ -85,8 +85,8 @@ for (const backend of testBackends()) describe(`git-gap census (git-canonical G1
const snapshot = await snapshotOf('cmp/page');
const text = inlineExportMarkdown(snapshot);
expect(compareInlineExportFile(Buffer.from(text.replace('Original body.', 'Edited body.')), 'cmp/page.md', snapshot)).toEqual({ state: 'differs', paths: ['/compiled_truth'] });
- expect(compareInlineExportFile(Buffer.from('---\ntitle: [unclosed\n---\nBody\n'), 'cmp/page.md', snapshot)).toEqual({ state: 'unparseable' });
- expect(compareInlineExportFile(Buffer.from([0xff, 0xfe, 0x00]), 'cmp/page.md', snapshot)).toEqual({ state: 'unparseable' });
+ expect(compareInlineExportFile(Buffer.from('---\ntitle: [unclosed\n---\nBody\n'), 'cmp/page.md', snapshot)).toEqual({ state: 'unparseable', reason: 'frontmatter' });
+ expect(compareInlineExportFile(Buffer.from([0xff, 0xfe, 0x00]), 'cmp/page.md', snapshot)).toEqual({ state: 'unparseable', reason: 'not_utf8' });
expect(compareInlineExportFile(Buffer.from(text.replace('validate: false\n', '')), 'cmp/page.md', snapshot)).toEqual({ state: 'equal' });
});