Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(sync): G3, a strict source's sync pass indexes its commits alone and Git wins
garrytan0adc46a0e1d8
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.mdindex a3ef6083a0..81b48bcf12 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -2443,7 +2443,7 @@ More: [docs/guides/repair.md#rename-identity](../../docs/guides/repair.md#rename| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable ||---|---|---|---|---|---|---|-| A managed source refuses --skip-failed and --include-gitignored: managed sync keeps every failed-receipt and ignored-file guard, so the run was refused before anything ran. | --skip-failed would acknowledge a failed receipt instead of retrying it, and --include-gitignored would import files Git ignores; neither has a managed meaning. `detail` names the flag. | Rerun the same gbrain sync command without the named flag; fix a failed file and the plain sync retries it, or commit an ignored file to sync it. Run: gbrain sources status --json | agent | `gbrain sources status --json` | 1 | no |+| A managed source refuses --skip-failed and --include-gitignored, and a strict (git-canonical) source also refuses --working-tree: managed sync keeps every failed-receipt and ignored-file guard and a strict source indexes commits only, so the run was refused before anything ran. | --skip-failed would acknowledge a failed receipt instead of retrying it, and --include-gitignored would import files Git ignores; neither has a managed meaning. `detail` names the flag. | Rerun the same gbrain sync command without the named flag; fix a failed file and the plain sync retries it, or commit an ignored file to sync it. Run: gbrain sources status --json | agent | `gbrain sources status --json` | 1 | no |More: [docs/guides/write-refusals.md#managed_sync_flag_refused](../../docs/guides/write-refusals.md#managed_sync_flag_refused)diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.mdindex 0b7960234c..ffc27f9324 100644--- a/docs/guides/write-refusals.md+++ b/docs/guides/write-refusals.md@@ -92,7 +92,7 @@ of making a duplicate.| <a id="colon_slug_windows_write_through"></a>`colon_slug_windows_write_through` | `colon_slug_windows_write_through` | A page slug such as `calendar:abc` is valid, but its canonical file name would contain `:`, which Windows cannot store (it names an alternate data stream). On Windows, a write that would publish that file is refused before admission, and `gbrain sync` skips each such file with this reason instead of failing the run. Database-only writes of the same slug (no repo configured, `sync.write_through` off, an unbound source, or a [read-only mirror](multi-source-brains.md#read-only-mirror-sources) source and pages created while it was one) still succeed, and macOS and Linux are not affected. | Use a slug without `:` (the suggestion names one), or write the page from a macOS or Linux host that owns the source. For a skipped sync file, rename it without `:` on a macOS or Linux checkout, commit, then run `gbrain sync --source <source> --no-pull` on the Windows host. || <a id="embedding_auth_failed"></a>`embedding_auth_failed` | `embedding_auth_failed` | The embedding provider rejected the configured key (HTTP 401 or 403). Printed once per process on stderr, naming the key source in effect: an environment variable (for example `OPENAI_API_KEY`, which wins over the config key) or the config key in `~/.gbrain/config.json`. No key or part of one is printed. | Environment key in effect but the config key is right: remove the variable from the environment of the process that reported it (shell profile, `~/.gbrain/.env`, or a daemon's service definition) and restart that process. Environment key intended: replace it with a valid key, restart, and run `gbrain config unset openai_api_key` (or the matching key). Config key in effect: `gbrain config set openai_api_key <valid key>`. Then `gbrain embed --stale` embeds what was saved meanwhile. `gbrain doctor` (`embedding_key_source`) shows the key source in doctor's own environment. || <a id="managed_pull_skipped"></a>`managed_pull_skipped` (cycle warn); doctor `sync_freshness` "upstream unknown" or "upstream N commit(s) ahead" | `managed_pull_skipped` | A managed brain never runs `git pull` inside a cycle: Git pull needs an explicit drained maintenance window, so an explicit `gbrain sync` without `--no-pull` is refused with `writer_coordinator_required`. An unattended cycle asked to pull (autopilot passes `pull: true`, `gbrain dream --pull`) instead syncs the checkout as it is and reports it: the sync phase result carries `details.upstream_refresh` (`pulled`, `failed`, `skipped_managed` or `not_requested`), and when the checkout tracks an upstream the phase is `warn` with `details.warning` (`code`, `cause`, `fix`, `docs`). Every sync also records the checkout's last upstream observation (the upstream commit, when it was last fetched or pushed, and how many upstream commits the synced commit lacks) in the source row. Doctor `sync_freshness` reports that separately from the local projection: a source with a `remote_url` whose observation is missing or older than 24 hours is "upstream unknown", and any source whose observation saw upstream commits it has not synced is "behind"; neither is reported fresh. `details.upstream_unknown_count` and `details.upstream_behind_count` count them. | `gbrain sources refresh <source>` (the printed `fix` fills in the source). It drains writes to the source's checkout, fast-forwards it to its upstream and runs the managed sync for every source bound to that checkout; see [worktree refresh refusals](#worktree-refresh-refusals) for what it can refuse. On a brain that is not managed, `gbrain sync --source <source>` pulls and records the observation. |-| <a id="managed_sync_flag_refused"></a>`managed_sync_flag_refused` (`detail` = the flag) | `managed_sync_flag_refused` | A managed source keeps every failed-receipt and ignored-file guard, so `gbrain sync --skip-failed` and `gbrain sync --include-gitignored` have no managed meaning. The refusal names the flag and comes before anything runs: at parse in `gbrain sync` (before a legacy ledger row is acknowledged or the cost gate runs, `--all` included), before the serve-delegation ladder looks for the serve's socket, and in the managed-sync guard that sync jobs, MCP `sync_brain` and the cycle reach. Nothing is admitted and no cursor is written. | Rerun the printed `fix` (the same command without the flag). A failed file is fixed and then retried by the plain `gbrain sync --source <source> --no-pull`; an ignored file syncs once it is committed and not ignored. `gbrain sync status --source <source> --json` shows the source's failures and holds. |+| <a id="managed_sync_flag_refused"></a>`managed_sync_flag_refused` (`detail` = the flag) | `managed_sync_flag_refused` | A managed source keeps every failed-receipt and ignored-file guard, so `gbrain sync --skip-failed` and `gbrain sync --include-gitignored` have no managed meaning. A strict (git-canonical, `config.canonical = "git"`) source also refuses `gbrain sync --working-tree`, because it indexes committed bytes only; that refusal comes from the managed-sync guard, which reads the source row. The refusal names the flag and comes before anything runs: at parse in `gbrain sync` (before a legacy ledger row is acknowledged or the cost gate runs, `--all` included), before the serve-delegation ladder looks for the serve's socket, and in the managed-sync guard that sync jobs, MCP `sync_brain` and the cycle reach. Nothing is admitted and no cursor is written. | Rerun the printed `fix` (the same command without the flag). A failed file is fixed and then retried by the plain `gbrain sync --source <source> --no-pull`; an ignored file syncs once it is committed and not ignored, and an edit on a strict source syncs once it is committed (`gbrain git commit-push`). `gbrain sync status --source <source> --json` shows the source's failures and holds. || <a id="facts_absorb_write_refused"></a>`facts_absorb_write_refused (<code>)`; `ingest_log` `write_refused: <code> …` | `facts_absorb_write_refused` | A durable `facts-absorb` job extracted facts but the write path refused to store them, for example `writer_coordinator_required` because the entity's Markdown file sits in a claimed canonical worktree before `sources writer activate`, or `permission_denied`, `invalid_params` or `writer_registration_required`. These refusals do not change on retry, so the job goes straight to `dead` on its first attempt instead of re-running inference; on a brain that is not yet activated, a job whose source root is a claimed worktree is refused before extraction starts, so it makes no model call; the `facts:absorb` row in `ingest_log` (and doctor `facts_extraction_health`) records `write_refused` with the real code, not a provider failure. Two outcomes are not refusals and are logged under their own reasons, which doctor never counts toward its threshold: `write_pending_accepted`, a facts write that was accepted and whose receipt is still queued, running or recovering when the job stopped waiting (the job waits up to 30 s, bounded by its deadline; the write commits later), and `write_deferred_unadmitted`, a canonical writer that was busy before anything was admitted (`writer_lock_unavailable`, no receipt; the job retries). Doctor warns about deferrals only when they persist (see the check's `gbrain sources writer status` fix). Doctor's incident count is a historical metric: it counts the `facts:absorb` rows of a rolling 24 h window, says when they age out, and keeps counting them after the cause is fixed and the job retried, so a warning there does not by itself mean anything is still broken; the threshold (`facts.absorb_warn_threshold`) is unchanged. The current state is the check's `jobs still dead` count: facts-absorb jobs that went dead or failed in the last 24 h and that no later job for the same page completed after, each named with `gbrain jobs retry <id>`. The source page itself was already saved. | Fix the named cause first: `gbrain sources writer status <source>`, then finish the [claim and activate runbook](../architecture/topologies.md#claim-and-activate-runbook) for a claimed worktree, or fix the grant. Then `gbrain jobs retry <job id>` (the error names the id). || <a id="no_context_ceiling"></a>`no_context_ceiling` | `no_context_ceiling` | A queued job under a cost cap you set stopped before a provider call: the model has a registered price, but gbrain knows no context-token ceiling for it, so it cannot reserve the most one call could cost. OpenRouter models hit this, because that provider declares no context window per model. The message names the model, and the JSON `fix` asks you before it reruns the command without your cap. Re-registering the price does not help. | Choose one. Rerun the command without your cap (the `fix` command, which replaces `--max-usd` with `--yes`): the default cap applies and this model runs unmetered with a warning. Or keep your cap: look up the model's context window on the provider's model page (OpenRouter lists it as `context_length`) and give it to the brain-host operator. `gbrain jobs list --group <id> --json` shows the stopped job. || <a id="no_pricing"></a>`no_pricing` | `no_pricing` | A cost cap you set (`--max-cost`, `--max-usd`, `--max-cost-usd`, or an explicit cap in config such as `cycle.extract_atoms.budget_usd`) cannot be enforced, because gbrain has no price for the model the run was about to call. The run stops before that call. Under a default cap an unpriced model warns and runs instead. The message names the model, provider and kind, and JSON output carries the same guidance as fields: `code`, `model`, `provider`, `kind`, `units`, `lookup`, `register_command`, `register_scope` and `docs`. | Look up the provider's current price for the model, for example by searching the web for its pricing page. A chat model needs USD per 1M input tokens and USD per 1M output tokens; an embedding or reranker model needs USD per 1M tokens. On the brain host, run `gbrain pricing set <model> --input <usd> --output <usd> --source <pricing-page-url>` (or `--rate <usd>`), then retry. An agent connected over MCP cannot register prices: give the command to the brain's operator. See [registering a model price](../operations/spend-controls.md#registering-a-model-price). |diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex 5a7fc69010..772f846864 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -425,7 +425,7 @@ export const CODES = {docs: 'docs/guides/troubleshooting.md#managed-sync-not-moving',suggestion: 'Rerun gbrain sources writer movement <id>; if the backlog read keeps failing, run gbrain doctor --json.',fix: { argv: ['gbrain', 'sources', 'writer', 'movement', '{source_id}', '--json'], consent: [], actor: 'agent', why: 'Read-only: reads the managed sync backlog again and judges movement over one window.', requires_exclusive: false, verify: { argv: ['gbrain', 'doctor', '--only', 'managed_sync_not_moving', '--json'] } } },- managed_sync_flag_refused: { class: 'caller', summary: "A managed source refuses --skip-failed and --include-gitignored: managed sync keeps every failed-receipt and ignored-file guard, so the run was refused before anything ran.",+ managed_sync_flag_refused: { class: 'caller', summary: "A managed source refuses --skip-failed and --include-gitignored, and a strict (git-canonical) source also refuses --working-tree: managed sync keeps every failed-receipt and ignored-file guard and a strict source indexes commits only, so the run was refused before anything ran.",why: "--skip-failed would acknowledge a failed receipt instead of retrying it, and --include-gitignored would import files Git ignores; neither has a managed meaning. `detail` names the flag.",docs: 'docs/guides/write-refusals.md#managed_sync_flag_refused',suggestion: 'Rerun the same gbrain sync command without the named flag; fix a failed file and the plain sync retries it, or commit an ignored file to sync it.',diff --git a/src/core/persistence/git-door.ts b/src/core/persistence/git-door.tsindex 3242f56995..7f4b3be892 100644--- a/src/core/persistence/git-door.ts+++ b/src/core/persistence/git-door.ts@@ -26,6 +26,11 @@ export async function sourceCanonicalGit(engine: SqlEngine, sourceId: string, loreturn row?.strict === true;}+/** Whether a managed sync context's source row is strict (G3: the sync level is its commit alone, and Git wins). */+export function sourceStrict(context: { source: { config: Record<string, unknown> | null } }): boolean {+ return context.source.config?.canonical === 'git';+}+/** The door marker a strict publication's recovery record carries: the checkout it commits in and the HEAD it started from. */export async function doorMarker(root: string): Promise<NonNullable<FileRecoveryRecord['door']>> {return { root, head: await headCommit(root) };diff --git a/src/core/persistence/managed-sync-flags.ts b/src/core/persistence/managed-sync-flags.tsindex 8dca7778b3..9597ebd1eb 100644--- a/src/core/persistence/managed-sync-flags.ts+++ b/src/core/persistence/managed-sync-flags.ts@@ -1,7 +1,8 @@/*** #6696 C2: the sync flags a managed source refuses. Managed sync keeps every failed-receipt and ignored-file* guard, so `--skip-failed` (acknowledge failures and move on) and `--include-gitignored` (walk ignored files)- * have no managed meaning. `managedSyncFlagRefusal` is the one refusal for them: code `managed_sync_flag_refused`,+ * have no managed meaning. G3: a strict (git-canonical) source also refuses `--working-tree`, since it indexes commits only;+ * only the managed-sync guard reads the source row, so only it refuses that one. `managedSyncFlagRefusal` is the one refusal for them: code `managed_sync_flag_refused`,* `detail` = the flag, and a fix that reruns the same command without it. It is thrown at parse in `gbrain sync`* (`src/commands/sync/managed-no-pull.ts`), before the socket call in the serve-delegation ladder* (`src/commands/sync-delegate.ts`), and by the managed-sync guard (`resolveManagedSyncContext`) that jobs, MCP and@@ -10,16 +11,17 @@import { opError, type OperationError } from '../ops/contract.ts';import { shellQuote } from '../agent-output.ts';-export type ManagedForbiddenFlag = '--skip-failed' | '--include-gitignored';+export type ManagedForbiddenFlag = '--skip-failed' | '--include-gitignored' | '--working-tree';const WHY: Record<ManagedForbiddenFlag, string> = {'--skip-failed': 'A managed sync never acknowledges a failed receipt to move past it: fix the file, and the plain sync retries it.','--include-gitignored': 'A managed sync imports only files Git tracks and does not ignore: commit the file, or change .gitignore, to sync it.',+ '--working-tree': 'A strict (git-canonical) source indexes committed bytes only: commit the edit, through gbrain git commit-push, to sync it.',};-/** The first managed-forbidden flag these options set, or null. */-export function managedForbiddenFlag(opts: { skipFailed?: boolean; includeGitignored?: boolean }): ManagedForbiddenFlag | null {- return opts.skipFailed ? '--skip-failed' : opts.includeGitignored ? '--include-gitignored' : null;+/** The first managed-forbidden flag these options set, or null; `--working-tree` only on a strict source (G3). */+export function managedForbiddenFlag(opts: { skipFailed?: boolean; includeGitignored?: boolean; workingTree?: boolean }, strict = false): ManagedForbiddenFlag | null {+ return opts.skipFailed ? '--skip-failed' : opts.includeGitignored ? '--include-gitignored' : strict && opts.workingTree === true ? '--working-tree' : null;}/** `args` is the `gbrain sync` argv after `sync`; the fix reruns it without the flag. */diff --git a/src/core/persistence/sync-classify.ts b/src/core/persistence/sync-classify.tsindex 7f607ad932..b107b9af78 100644--- a/src/core/persistence/sync-classify.ts+++ b/src/core/persistence/sync-classify.ts@@ -9,6 +9,14 @@* its current revision, its hold, deletion marker, baseline blob and open work. Definitions (v3.1 §2.3, v3.2 §2.3):* `fileSame := L ∈ {r.blob_oid, r.disk_blob_oid}`, `dbSame := r.revision = page.revision`, `proof := dbSame ∨ att(R)`,* `obligation := ¬sameParser ∨ origin ≠ page.source_path ∨ episodeUnsatisfied`.+ *+ * G3 of git-canonical memory (docs/designs/GIT_CANONICAL_MEMORY.md): for a strict source (`config.canonical = "git"`) the+ * classifier reads the commit alone and Git wins. The working tree is invisible (every path in `T` is clean, a path absent+ * from `T` is absent), a page Git moved past or never matched imports the committed blob over the database, and a live+ * page whose file a commit removed is deleted. A page Git never held stays as the database has it. Holds keep their rows+ * (a hold at its level settles, a re-screened one re-runs Git's verdict); conversion resolves a source's holds before it+ * turns strict. `gitWins` names the class the same path gets on a source that is not strict, so a preview can list what+ * Git overwrote.*//** Candidate dirtiness of a committed-mode path in `T` (sync-git-stream.ts `probeDirtiness`). */@@ -104,6 +112,8 @@ export interface SyncClassified {heldDeletion?: { commit: string; blob_oid: string };/** GBRA-133: why that proof refused this held deletion; its hold records it at the page's revision. */heldDeletionRefused?: string;+ /** G3, a strict source: the class this path gets on a source that is not strict, when Git's verdict differs from it. */+ gitWins?: SyncClass;}const CLEAN = new Set<SyncDirtiness | null>(['clean', 'clean_eol', 'clean_lfs']);@@ -127,9 +137,9 @@ type Matched = Omit<SyncClassified, 'inFlight' | 'classAction'>;* in a class whose action says who finishes it. So a path with a hold row never settles in a later row (b2): unless the hold* is at its level and not re-screen due, the pass re-runs it (`held`, `rescreenDue`).*/-function firstMatch(s: SyncPathState): Matched {+function firstMatch(s: SyncPathState, strict = false): Matched {if (s.hold && s.hold.atLevel && !s.hold.rescreenDue && !s.hold.retried) return { cls: 'held', settled: true, action: 'none' };- const rest = afterHold(s);+ const rest = strict ? gitWins(s) : afterHold(s);// The re-run is the import the hold refused, where an import is what the level would get anyway (`import`) or changes// nothing (`matched`). A level that needs another action (a drift side, a delete proof, a reparse) keeps that class, so// its guard still applies; one that settles any other way (database ahead, a deleted page, an uncommitted edit, a legacy@@ -187,9 +197,43 @@ function afterHold(s: SyncPathState): Matched {return { cls: 'drift', settled: false, action: 'hold', side: s.record?.revision != null ? 'both' : 'unknown' };}-/** The class of one path (v3.2 §2.3), with the open-work overlay applied. */-export function classifySyncPath(s: SyncPathState): SyncClassified {- const match = firstMatch(s);+/**+ * G3: a strict source's path as the commit alone shows it. Committed mode only (a strict pass never reads a working level):+ * every path in `T` is clean with no disk bytes, a path absent from `T` is absent from disk, and keep_db does not apply.+ */+export function committedOnlyState(s: SyncPathState): SyncPathState {+ return { ...s, present: s.tree !== null, dirty: s.tree === null ? null : 'clean', diskOid: null, published: false, keepDb: false };+}++/**+ * G3: Git's verdict for a strict source, after its hold rows. Drift, a database version sync never saw (`db_ahead` that is+ * not a pending door write), keep_db and an edited tombstone import the committed blob. A live page whose file is absent+ * from `T` waits for its origin evidence (sync-pass.ts reads it for every delete candidate), then is deleted when a commit+ * held the file and left as the database has it otherwise.+ */+function gitWins(s: SyncPathState): Matched {+ const verdict = gitVerdict(committedOnlyState(s));+ const before = afterHold(s).cls;+ return verdict.cls === before ? verdict : { ...verdict, gitWins: before };+}++function gitVerdict(state: SyncPathState): Matched {+ const rest = afterHold(state);+ const wins = (match: Matched): Matched => match;+ switch (rest.cls) {+ case 'drift': case 'keep_db': case 'deleted_edited': return wins({ cls: 'import', settled: false, action: 'import' });+ case 'db_ahead': return rest.sub === 'pending' ? rest : wins({ cls: 'import', settled: false, action: 'import' });+ case 'delete': case 'delete_drift':+ if (state.originEvidence === undefined) return rest;+ if (state.originEvidence !== 'committed') return wins({ cls: 'kept', settled: true, action: 'none' });+ return rest.cls === 'delete' ? rest : wins({ cls: 'delete', settled: false, action: 'delete' });+ default: return rest;+ }+}++/** The class of one path (v3.2 §2.3), with the open-work overlay applied; `strict` is Git's verdict (G3). */+export function classifySyncPath(s: SyncPathState, opts: { strict?: boolean } = {}): SyncClassified {+ const match = firstMatch(s, opts.strict === true && s.mode === 'committed');const inFlight = !match.settled && s.openWork;const classAction: SyncClassAction = inFlight || match.rescreenDue ? 'owner' : match.cls === 'dirty' ? (match.settled ? 'none' : 'repair') : syncClassAction(match.cls);return { ...match, inFlight, classAction };diff --git a/src/core/persistence/sync-discovery.ts b/src/core/persistence/sync-discovery.tsindex a9ba86d746..b68d141a82 100644--- a/src/core/persistence/sync-discovery.ts+++ b/src/core/persistence/sync-discovery.ts@@ -45,6 +45,8 @@ export interface SyncEntry { path: string; sourcePath: string; action: 'import'identityHead?: string;/** #5565: a deleted file no page records as its origin; its slug's page keeps another origin, so the deletion is a fenced no-op. */unownedDeletion?: boolean;+ /** G3: a strict source's entry; the freeze reads its commit alone and publication never compares the working tree. */+ committedOnly?: true;/** #5988: a held rename destination whose source page changed since the rename was recorded; the freeze screen holds it as `rename_held`. */renameHeld?: SyncRename;/** #6712 PR 1: the import provenance matches the pinned blob, the frozen revision and this parser; the no-op kernel decides (sync-prescreen.ts). */@@ -230,6 +232,7 @@ export async function resolveManagedSyncContext(engine: BrainEngine, opts: SyncOconst forbidden = managedForbiddenFlag(opts);if (forbidden) throw managedSyncFlagRefusal(forbidden, sourceId, ['--source', sourceId, '--no-pull']);const [source, binding] = await (rows ?? readManagedSyncRows(engine, sourceId));+ if (source?.config?.canonical === 'git' && managedForbiddenFlag(opts, true)) throw managedSyncFlagRefusal('--working-tree', sourceId, ['--source', sourceId, '--no-pull', '--working-tree']);if (!source || source.archived || !binding || binding.source_incarnation !== source.incarnation ||binding.owner_host_id !== localHostId() || binding.state !== 'active' || !binding.local_path) {// #6449: a rooted source with no owner at all is the database-only one activation listed; the exit is a deliberate claim.diff --git a/src/core/persistence/sync-pass-run.ts b/src/core/persistence/sync-pass-run.tsindex a2fb229d02..e7ecdd2bb2 100644--- a/src/core/persistence/sync-pass-run.ts+++ b/src/core/persistence/sync-pass-run.ts@@ -31,6 +31,7 @@ import { OPEN_AT_STAMP_CAP, passFingerprint, readPassRow, SYNC_ORIGIN_DELETED_OPtype PassKind, type PassOutcome, type SyncSelection } from './sync-pass-row.ts';import { readSyncAdmission, type SyncAdmission } from './sync-admission.ts';import { faultPoint } from './fault-points.ts';+import { sourceStrict } from './git-door.ts';import { passFoldBase, passIdleProbe, readShadowLevel, workingIdleChange, type PassLevelCache, type ShadowLevel, type ShadowPath } from './sync-pass.ts';import { ownWritebackCommit, type PassFold } from './sync-pass-fold.ts';import { openPassRequests, settleCarried } from './sync-pass-carried.ts';@@ -153,7 +154,8 @@ async function batchEntries(engine: BrainEngine, level: ShadowLevel, deletes: Shidentity: Array<{ entry: ShadowPath; origin: ShadowPath | null; slug: string; ids: { page: string; file: string } }> }> {await faultPoint('sync:batch_entries', { sourceId: level.sourceId });const working = (entry: ShadowPath) => level.mode === 'working' && entry.state.level !== entry.state.tree;- const deleteEntries = new Map<string, PassEntry>(deletes.map(entry => [entry.path, { ...entryPaths(level, entry.path), action: 'delete' as const, working: level.mode === 'working',+ const committedOnly = level.strict ? { committedOnly: true as const } : {};+ const deleteEntries = new Map<string, PassEntry>(deletes.map(entry => [entry.path, { ...entryPaths(level, entry.path), ...committedOnly, action: 'delete' as const, working: level.mode === 'working',slug: entry.slug!, pageId: entry.pageId, revision: entry.revision, level: null, ...(entry.result.heldDeletion ? { heldDeletion: entry.result.heldDeletion } : {}) }]));const leaving = new Map(deletes.map(entry => [entry.path, entry]));const fresh = imports.filter(entry => !entry.state.page);@@ -205,7 +207,7 @@ async function batchEntries(engine: BrainEngine, level: ShadowLevel, deletes: Shfor (const entry of imports) {if (step.due()) await step.pause();const paths = entryPaths(level, entry.path);- const base = { ...paths, action: 'import' as const, working: working(entry), level: entry.state.level, ...(entry.result.cls === 'drift' && entry.result.side && entry.result.side !== 'deleted' ? { drift: entry.result.side, ...(driftBaseline(entry) ? { driftBaseline: driftBaseline(entry) } : {}) } : {}) };+ const base = { ...paths, ...committedOnly, action: 'import' as const, working: working(entry), level: entry.state.level, ...(entry.result.cls === 'drift' && entry.result.side && entry.result.side !== 'deleted' ? { drift: entry.result.side, ...(driftBaseline(entry) ? { driftBaseline: driftBaseline(entry) } : {}) } : {}) };if (entry.state.page) { entries.push({ ...base, slug: entry.slug!, pageId: entry.pageId, revision: entry.revision }); continue; }const slug = slugOf.get(entry.path);if (!slug) { skipped.push(entry); continue; }@@ -241,7 +243,7 @@ async function batchEntries(engine: BrainEngine, level: ShadowLevel, deletes: Shif (losers.length) collisions.push({ slug, kept: kept ?? entryPaths(level, winner!.path).sourcePath, skipped: losers.map(entry => entryPaths(level, entry.path).sourcePath) });if (!winner) continue;const paths = entryPaths(level, winner.path);- const base = { ...paths, action: 'import' as const, working: working(winner), level: winner.state.level, slug, ...legacySlugs.get(winner.path) };+ const base = { ...paths, ...committedOnly, action: 'import' as const, working: working(winner), level: winner.state.level, slug, ...legacySlugs.get(winner.path) };if (holder) {// #6729: a file whose frontmatter id differs from the page's is another document; it inherits nothing. GBRA-130 B-4: it is// held alone and the page keeps its slug (its origin's deletion waits with it); discovery still refuses the source.@@ -257,7 +259,7 @@ async function batchEntries(engine: BrainEngine, level: ShadowLevel, deletes: Sh// unbound (#5254) is not guarded: its preparation refuses the file that now occupies its path (source_changed).entries.push({ ...base, pageId: Number(holder.id), revision: holder.revision,...(holder.source_path !== null ? { renameFrom: { sourcePath: holder.source_path, slug, pageId: Number(holder.id), revision: holder.revision } } : {}),- ...(holder.source_path === null && !holder.deleted && !holder.unbound ? { drift: 'unknown' as const } : {}) });+ ...(holder.source_path === null && !holder.deleted && !holder.unbound && !level.strict ? { drift: 'unknown' as const } : {}) });if (holderPath !== null && deleteEntries.delete(holderPath)) renamed.add(holderPath);continue;}@@ -385,18 +387,20 @@ async function pinPass(engine: BrainEngine, input: SyncPassInput, lease: NonNullconst [headLine, refLine] = syncGit(context.gitRoot, ['rev-parse', 'HEAD', '--abbrev-ref', 'HEAD']).split('\n');const head = headLine!.trim();const detached = refLine?.trim() === 'HEAD';- const mode: SyncSelection['mode'] = detached || (opts.workingTree ?? configuredWorking === 'true') ? 'working' : 'committed';+ // G3: a strict source's pass reads its commit alone, a detached HEAD's too (sync-pass.ts).+ const strict = sourceStrict(context);+ const mode: SyncSelection['mode'] = !strict && (detached || (opts.workingTree ?? configuredWorking === 'true')) ? 'working' : 'committed';const selection = passSelection(patterns, opts, context, mode);const configured = !remote && !opts.exclude?.length && !opts.includeHidden?.length && opts.srcSubpath === undefined&& (opts.strategy === undefined || opts.strategy === ((context.source.config?.strategy as string | undefined) ?? 'markdown'))- && (detached || opts.workingTree === undefined || opts.workingTree === (configuredWorking === 'true'));+ && (strict || detached || opts.workingTree === undefined || opts.workingTree === (configuredWorking === 'true'));// GBRA-150: `sync.metafile_pages typed` widens the level's universe, so it joins the selection fingerprint (`off` keeps// the fingerprint an older pass stamped): the first pass after the upgrade or a flip reads the whole level once.const metafilePages = await readMetafilePagesMode(engine);// GBRA-133: so does `sync.apply_held_deletions` when on (sync-held-deletions.ts): turning it on reads the level, and its held deletions, once.// `sync.level_reuse` rides the same read (sync-tree-reuse.ts); it changes how the level is read, not what it is.const { heldDeletions, levelReuse } = await readPassSwitches(engine, sourceId);- const selectionFp = digest({ ...selection, ...(metafilePages === 'off' ? {} : { metafile_pages: metafilePages }), ...(heldDeletions ? { apply_held_deletions: true } : {}) }), parserFp = parserFingerprint();+ const selectionFp = digest({ ...selection, ...(metafilePages === 'off' ? {} : { metafile_pages: metafilePages }), ...(heldDeletions ? { apply_held_deletions: true } : {}), ...(strict ? { canonical: 'git' } : {}) }), parserFp = parserFingerprint();const obligations: ManagedSyncPassValue['obligations'] = prior ? structuredClone(prior.value.obligations): { baseline_commit: context.source.last_commit, mismatch: {}, not_converged_streak: 0, faults: {} };obligations.mismatch ??= {}; obligations.faults ??= {}; obligations.not_converged_streak ??= 0;diff --git a/src/core/persistence/sync-pass.ts b/src/core/persistence/sync-pass.tsindex 22de03f7bb..eb6cea31cd 100644--- a/src/core/persistence/sync-pass.ts+++ b/src/core/persistence/sync-pass.ts@@ -46,6 +46,7 @@ import { MANAGED_SYNC_PASS_OP, SYNC_ORIGIN_DELETED_OP, type SyncSelection } fromimport { faultPoint } from './fault-points.ts';import { filterYielding, loopYield, progressYield, sortYielding, turnYield, whileActive, type LoopYield } from './sync-yield.ts';import { countsMatch, proveConfirm, readLevelMark, type ConfirmProof, type LevelMark } from './sync-pass-confirm.ts';+import { sourceStrict } from './git-door.ts';import { domainCache, levelDomain, narrowedWalk, walkAttestations, type LevelDomainCache } from './sync-pass-narrow.ts';export { MANAGED_SYNC_PASS_OP, SYNC_ORIGIN_DELETED_OP };@@ -257,6 +258,8 @@ function levelReader(mode: 'committed' | 'working', tree: Map<string, GitTreeEntexport interface ShadowLevel {sourceId: string; incarnation: string; root: string; gitRoot: string; scope: string; slugMode: 'git-root' | 'source-root';mode: 'committed' | 'working'; head: string; baselineCommit: string | null; full: boolean;+ /** G3: the source is strict (`config.canonical = "git"`): the level is the commit alone and Git wins (sync-classify.ts). */+ strict: boolean;kind: 'idle' | 'hold_only' | 'full'; kindBlockers: SyncIdleBlocker[];paths: ShadowPath[];/** The schema pack in effect (the pass's `pack` fingerprint) and the selection the level read (design §6). */@@ -591,7 +594,7 @@ async function readUntracked(gitRoot: string, scope: string): Promise<string[]>const timer = () => { const started = performance.now(); return () => Math.round((performance.now() - started) * 10) / 10; };/** #7130: an absent file is deletion evidence only when Git once committed it (sync-origin-evidence.ts); read for those paths alone. */-async function reclassifyByOrigin(gitRoot: string, tips: Array<string | null | undefined>, paths: ShadowPath[], step: LoopYield, pass?: PassLevelInput): Promise<boolean> {+async function reclassifyByOrigin(gitRoot: string, tips: Array<string | null | undefined>, paths: ShadowPath[], step: LoopYield, strict: boolean, pass?: PassLevelInput): Promise<boolean> {const absent = await filterYielding(paths, entry => (entry.result.cls === 'delete' || entry.result.cls === 'delete_drift') && entry.state.originEvidence === undefined, step);if (!absent.length) return false;// A stopped pass leaves the shared walk running: the next pass joins it, or reads the history it cached.@@ -599,7 +602,7 @@ async function reclassifyByOrigin(gitRoot: string, tips: Array<string | null | uconst evidence = await whileActive(readOriginEvidence(gitRoot, tips, absent.map(entry => entry.path), { onCommit: pass?.onProgress }), pass?.assertActive);for (const entry of absent) {const state = { ...entry.state, originEvidence: evidence.get(entry.path) ?? 'unknown' as const };- Object.assign(entry, { state, result: classifySyncPath(state) });+ Object.assign(entry, { state, result: classifySyncPath(state, { strict }) });}return true;}@@ -628,7 +631,7 @@ export async function readShadowLevel(engine: BrainEngine, input: { sourceId: stconst settings = await readLevelSettings(engine, context, scope, input);timings.setup = t();if (!settings) return null;- const { slugMode, exclude, pack, mirror, strategy, includeHidden, keepDbPrefixes, workingConfig, metafilePages } = settings;+ const { slugMode, exclude, pack, mirror, strategy, includeHidden, keepDbPrefixes, workingConfig, metafilePages, strict } = settings;const sourceRelative = (gitPath: string) => (scope ? gitPath.slice(scope.length + 1) : gitPath);let metafilePage: (gitPath: string) => boolean = () => false;// Eligibility of a path outside the cached tree (every path of the tree is eligible); origins validate per call: a@@ -649,7 +652,8 @@ export async function readShadowLevel(engine: BrainEngine, input: { sourceId: stt = timer();const { head, detached } = await readLevelHead(gitRoot, sourceId);- const working = detached || (input.workingTree ?? workingConfig === 'true');+ // G3: a strict source's level is its commit, a detached HEAD's too; the working tree never enters it.+ const working = !strict && (detached || (input.workingTree ?? workingConfig === 'true'));const mode: 'committed' | 'working' = working ? 'working' : 'committed';timings.rev_parse = t();const levelMetafiles = levelMetafilePages(metafilePages, gitRoot, [head, context.source.last_commit], working ? nativeGitRoot : null, scope);@@ -817,7 +821,7 @@ export async function readShadowLevel(engine: BrainEngine, input: { sourceId: st}).then(found => { timings.legacy = t(); return found; }): new Map<string, string>();- const classifiedKey = JSON.stringify([treeKey, mode, input.pass?.episodeFullId ?? null, input.full === true, mirror, keepDbPrefixes, pack?.identity ?? null, baselineCommit, !!input.pass?.bootstrap, [...colonRefused].sort()]);+ const classifiedKey = JSON.stringify([treeKey, mode, strict, input.pass?.episodeFullId ?? null, input.full === true, mirror, keepDbPrefixes, pack?.identity ?? null, baselineCommit, !!input.pass?.bootstrap, [...colonRefused].sort()]);const reuse = snapshot.changed && priorClassified?.key === classifiedKey ? reusableMatched(priorClassified.paths, matchedUnchanged({ pages, tree, byOrigin, claimants, holds: holdByGitPath, markers, open,changed: confirmChangedPaths(pages, snapshot.changed, (sourcePath, slug) => gitPathOf(pageOrigin(sourcePath, slug))), indexDelta, spelled: path => twins.has(path) || legacySpelling.has(path), originOf })) : null;// A round that reuses nothing lets the previous round's paths go before it builds its own: one level held, not two.@@ -840,7 +844,7 @@ export async function readShadowLevel(engine: BrainEngine, input: { sourceId: stif (kept) { if (!keepClaims) byOrigin.delete(path); paths.push(kept); reused++; continue; }const probe = probes.get(path);const { state, at, legacyPageless } = stateOf(path, mode === 'committed' && tree.has(path) ? 'clean' : null, probe);- const result = sharedResult(classifySyncPath(state));+ const result = sharedResult(classifySyncPath(state, { strict }));// 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) && !!indexDelta?.has(path) && (indexed(path)?.oid !== tree.get(path)!.oid || (indexed(path)?.stage ?? 0) !== 0);const revision = at === undefined ? null : pages.revision[at] ?? null;@@ -859,7 +863,7 @@ export async function readShadowLevel(engine: BrainEngine, input: { sourceId: stpaths.push({ path, slug: at === undefined ? null : pages.slug[at] ?? null, pageId: at === undefined ? null : Number(pages.id[at]), revision, state, result, ...(legacyPageless ? { legacyPageless } : {}), ...(ambiguousOrigin ? { ambiguousOrigin } : {}) });}timings.classify = t();- if (candidates.length) {+ if (candidates.length && !strict) {t = timer();const candidateIndex = new Map<string, GitIndexEntry>();for (const path of candidates) { if (step.due()) await step.pause(); const entry = indexed(path); if (entry) candidateIndex.set(path, entry); }@@ -872,13 +876,13 @@ export async function readShadowLevel(engine: BrainEngine, input: { sourceId: stconst probe = probed.get(path);const i = candidateAt[k]!;const { state } = stateOf(path, (probe?.dp ?? 'unknown') as SyncPathState['dirty'], probe);- paths[i] = { ...paths[i]!, state, result: sharedResult(classifySyncPath(state)) };+ paths[i] = { ...paths[i]!, state, result: sharedResult(classifySyncPath(state, { strict })) };}timings.classify += t();}t = timer();- if (await reclassifyByOrigin(gitRoot, [head, baselineCommit], paths, step, input.pass)) timings.origin = t();+ if (await reclassifyByOrigin(gitRoot, [head, baselineCommit], paths, step, strict, input.pass)) timings.origin = t();// Adoption by hash needs the level's bytes: committed mode reads the blobs of the candidates that could adopt.const needBytes = await filterYielding(paths, entry => !['matched', 'held', 'dirty'].includes(entry.result.cls) && entry.state.levelSha256 === null && entry.state.level !== null@@ -890,7 +894,7 @@ export async function readShadowLevel(engine: BrainEngine, input: { sourceId: stconst bytes = blobs.get(entry.state.level!);if (!bytes) continue;const state = { ...entry.state, levelSha256: sha256(bytes) };- Object.assign(entry, { state, result: classifySyncPath(state) });+ Object.assign(entry, { state, result: classifySyncPath(state, { strict }) });}timings.level_bytes = t();}@@ -903,7 +907,7 @@ export async function readShadowLevel(engine: BrainEngine, input: { sourceId: stcache.classified = { key: classifiedKey, treeKey, paths };if (!colonRefused.size) cache.domain = domainCache(levelD, treeKey);}- return { sourceId, incarnation, root, gitRoot, scope, slugMode, mode, head, baselineCommit, full: input.full === true, kind: kind.kind, kindBlockers: kind.blockers,+ return { sourceId, incarnation, root, gitRoot, scope, slugMode, mode, strict, head, baselineCommit, full: input.full === true, kind: kind.kind, kindBlockers: kind.blockers,heldRenames: holds.flatMap(hold => hold.meta.rename_from ? [{ path: toGit(hold.path), rename: hold.meta.rename_from }] : []),releasableHolds: holds.filter(hold => !domain.has(toGit(hold.path))).map(hold => hold.path),deletionCandidates: deletionCandidates(holds, path => domain.has(path) && !tree.has(path)@@ -952,7 +956,7 @@ async function readLevelSettings(engine: BrainEngine, context: ManagedSyncContexconst settled = <T>(read: PromiseSettledResult<T>): T => { if (read.status === 'rejected') throw read.reason; return read.value; };if (settled(company)) return null;return { slugMode: settled(slugModeRead), exclude: settled(excludeRead), pack: settled(packRead), mirror: settled(mirrorRead), workingConfig: settled(workingRead),- metafilePages: settled(metafilePagesRead), strategy: input.pass?.strategy ?? (context.source.config?.strategy as string | undefined) ?? 'markdown',+ metafilePages: settled(metafilePagesRead), strict: sourceStrict(context), strategy: input.pass?.strategy ?? (context.source.config?.strategy as string | undefined) ?? 'markdown',includeHidden: [...new Set([...input.pass?.includeHidden ?? [], ...(settled(includeHiddenRead) ?? '').split(/[\n,]/).map(v => v.trim()).filter(Boolean)].map(v => v.endsWith('/') ? `${v}**` : v))],keepDbPrefixes: (() => { try { return loadStorageConfig(root)?.keep_db ?? []; } catch { return []; } })() };}diff --git a/src/core/persistence/sync-prepare.ts b/src/core/persistence/sync-prepare.tsindex 169a8270c5..1e307ead4f 100644--- a/src/core/persistence/sync-prepare.ts+++ b/src/core/persistence/sync-prepare.ts@@ -88,6 +88,8 @@ export interface SyncIntent extends Record<string, unknown> {unownedDeletion?: boolean;/** GBRA-133: a held committed deletion `sync.apply_held_deletions` proved: the deleting commit and the blob the page equals. */heldDeletion?: { commit: string; blob_oid: string };+ /** G3: a strict source's import or deletion, frozen from its commit alone: publication does not compare the working tree. */+ committedOnly?: true;working?: boolean;renameFrom?: SyncRename;processingOptions?: SyncProcessingOptions;@@ -736,7 +738,7 @@ async function prepareSyncMutation(unbounded: BrainEngine, row: WriteRequest, _c},async () => {// GBRA-133 S-22: a deletion whose name became a directory has no file to compare.- if (p.path !== null && !p.body_ref && (p.kind === 'managed_sync_delete' && directoryAt(root, p.path) ? null : syncRawHash(root, p.path)) !== p.rawHash) throw syncPublicationRefusal('source_changed', 'The imported file changed after sync admission.', row, p,+ if (p.path !== null && !p.body_ref && !p.committedOnly && (p.kind === 'managed_sync_delete' && directoryAt(root, p.path) ? null : syncRawHash(root, p.path)) !== p.rawHash) throw syncPublicationRefusal('source_changed', 'The imported file changed after sync admission.', row, p,`The file of ${row.slug} changed on disk after this sync was admitted; review the change and commit it.`);},async () => {diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.tsindex 29156680e9..1e59282d75 100644--- a/src/core/persistence/sync-run.ts+++ b/src/core/persistence/sync-run.ts@@ -375,7 +375,10 @@ async function freezeEntryOnce(engine: BrainEngine, cursor: Cursor, key: string,return { hold: await originFaultHold(engine, { sourceId: cursor.sourceId, incarnation: cursor.incarnation, entry, observed: snapshot, message: occupant.originFault.message }), overtaken: true };}let bytes: Buffer | null = null;- try { bytes = entry.action === 'delete' && directoryAt(cursor.root, entry.path) ? null : readSyncFile(cursor.root, entry.path); } // GBRA-133 S-22: a directory is no file+ // G3: a strict source's entry reads its commit alone (a deletion has no bytes); only a blob over the read bound takes the streamed path below.+ const committed = entry.committedOnly === true && !entry.working ? entry.action === 'delete' ? null : pinnedBlob(cursor, entry.path) : undefined;+ try { bytes = committed !== undefined && (committed === null || committed.size <= SYNC_READ_BOUND) ? committed && pinnedImageBytes(cursor, entry)+ : entry.action === 'delete' && directoryAt(cursor.root, entry.path) ? null : readSyncFile(cursor.root, entry.path); } // GBRA-133 S-22: a directory is no filecatch (error) {if (!isSyncReadBound(error)) { const held = holdsOn ? unreadableFileHold(entry, entry.slug!, entry.pageId ?? null, error, () => pinnedBlob(cursor, entry.path)) : null; if (held) return { hold: held }; throw error; } // GBRA-130 A-7// Wave B: with segmented storage on, a Markdown file over the read bound is frozen by reference and streamed by its owner.@@ -481,6 +484,7 @@ async function freezeEntryOnce(engine: BrainEngine, cursor: Cursor, key: string,return remember(frozenSnapshot, { requestId: cursor.passId ? passRequestId(cursor.passId, entry?.path ?? slug, passLevel!) : randomUUID(), slug, pageId, ...(occupantRebound ? { rebound: true as const } : {}), intent: { kind: !entry ? 'managed_sync_checkpoint' : entry.action === 'import' ? 'managed_sync_import' : 'managed_sync_delete',expected_revision: revision, sourcePath: entry?.sourcePath ?? null, path: entry?.path ?? null, rawHash, content, lineEndingOnly, ...(bodyRef ? { body_ref: bodyRef } : {}),...(entry?.unownedDeletion ? { unownedDeletion: true } : {}), ...(entry?.heldDeletion ? { heldDeletion: entry.heldDeletion } : {}),+ ...(entry?.committedOnly ? { committedOnly: true } : {}),...(entry?.renameFrom ? { renameFrom: entry.renameFrom } : {}),...(run.observedAt ? { holdObservedAt: run.observedAt } : {}), ...(blob ? { blobOid: blob.oid } : {}), ...(entry && run.embedDeferred ? { embedDeferred: true } : {}),...(!entry && cursor.releasedHolds?.length ? { releasedHolds: cursor.releasedHolds } : {}),diff --git a/test/git-canonical-indexer-g3.test.ts b/test/git-canonical-indexer-g3.test.tsnew file mode 100644index 0000000000..a255eadc31--- /dev/null+++ b/test/git-canonical-indexer-g3.test.ts@@ -0,0 +1,93 @@+/**+ * G3 of git-canonical memory (docs/designs/GIT_CANONICAL_MEMORY.md): a strict source (`sources.config.canonical = "git"`)+ * indexes its commits alone, and Git wins. The managed sync pass of such a source:+ * - imports the committed blob over a database version sync never saw (`db_ahead`), where a source that is not strict+ * keeps the database version;+ * - imports a commit over a page the database also moved (drift), where a source that is not strict holds `file_drift`;+ * - imports the committed bytes of a file whose working tree holds an uncommitted edit, and leaves the edit on disk,+ * where a source that is not strict holds `worktree_dirty`;+ * - deletes a page whose file a commit removed while an untracked copy stays on disk, as a page imported from Git does;+ * - refuses `--working-tree` with `managed_sync_flag_refused`.+ */+import { describe, expect, test } from 'bun:test';+import { execFileSync } from 'node:child_process';+import { randomUUID } from 'node:crypto';+import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import type { BrainEngine } from '../src/core/engine.ts';+import { withCoordinatedWrite } from '../src/core/persistence/context.ts';+import { performManagedSync } from '../src/core/persistence/sync-run.ts';+import { managedBrain } from './helpers/managed-brain.ts';+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';+import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';++const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, '-c', 'user.name=Example', '-c', '[email protected]',+ '-c', 'commit.gpgsign=false', ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();+const note = (slug: string, body: string) => `---\ntype: concept\ntitle: ${slug}\n---\n\n${body}\n`;+const OPTS = { sourceId: 'default', noPull: true, noEmbed: true, noExtract: true };+const SLUGS = ['notes/ahead', 'notes/drift', 'notes/dirty', 'notes/removed'];++const holds = async (engine: BrainEngine) => (await engine.executeRaw<{ r: { path: string; code: string } }>(+ "SELECT completed_keys->0 AS r FROM op_checkpoints WHERE op='sync-hold' ORDER BY fingerprint")).map(({ r }) => `${r.path} ${r.code}`);+const page = async (engine: BrainEngine, slug: string) => (await engine.executeRaw<{ body: string; deleted: boolean }>(+ "SELECT compiled_truth AS body, deleted_at IS NOT NULL AS deleted FROM pages WHERE source_id='default' AND slug=$1", [slug]))[0];+/** A database-only edit: the page moves to a revision no request and no import wrote. */+const databaseOnlyEdit = (engine: BrainEngine, slug: string, body: string) => engine.transaction(tx => withCoordinatedWrite(tx, ['default'], () => tx.executeRaw(+ `UPDATE pages SET compiled_truth=$1, knowledge_revision=$2::uuid, revision_write_request_id=NULL WHERE source_id='default' AND slug=$3`, [body, randomUUID(), slug]), TEST_WRITE_ATTRIBUTION));+const strict = (engine: BrainEngine) => engine.executeRaw(`UPDATE sources SET config = config || '{"canonical":"git"}'::jsonb WHERE id='default'`);++/**+ * From a first sync: notes/ahead moves in the database only; notes/drift moves in the database and in a commit; notes/dirty+ * gets a commit and then an uncommitted edit on top; notes/removed leaves Git in a commit while its file stays on disk.+ */+async function diverge(engine: BrainEngine, root: string): Promise<void> {+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');+ await databaseOnlyEdit(engine, 'notes/ahead', 'Written to the database alone.');+ await databaseOnlyEdit(engine, 'notes/drift', 'Written to the database alone.');+ writeFileSync(join(root, 'notes/drift.md'), note('notes/drift', 'The committed edit of notes/drift.'));+ writeFileSync(join(root, 'notes/dirty.md'), note('notes/dirty', 'The committed edit of notes/dirty.'));+ git(root, 'commit', '-qam', 'edit drift and dirty');+ git(root, 'rm', '-q', '--cached', 'notes/removed.md'); git(root, 'commit', '-qm', 'remove notes/removed from git');+ writeFileSync(join(root, 'notes/dirty.md'), note('notes/dirty', 'An uncommitted edit of notes/dirty.'));+}++for (const backend of testBackends()) describe(`[${backend}] G3: a strict source indexes its commits, and Git wins`, () => {+ const databaseUrl = backend === 'postgres' ? requirePostgresTestDatabase() : undefined;+ const setup = ({ root }: { root: string }) => {+ mkdirSync(join(root, 'notes'), { recursive: true }); git(root, 'init', '-q');+ writeFileSync(join(root, '.gitignore'), '\n');+ for (const slug of SLUGS) writeFileSync(join(root, `${slug}.md`), note(slug, `The committed body of ${slug}.`));+ git(root, 'add', '-A'); git(root, 'commit', '-qm', 'notes');+ };++ test('a source that is not strict keeps the database version and holds drift and the dirty file', () => managedBrain(async ({ engine, root }) => {+ await diverge(engine, root);+ await performManagedSync(engine, { ...OPTS, full: true });+ expect((await page(engine, 'notes/ahead'))!.body).toContain('Written to the database alone.');+ expect((await page(engine, 'notes/drift'))!.body).toContain('Written to the database alone.');+ expect(await holds(engine)).toEqual(expect.arrayContaining(['notes/drift.md file_drift', 'notes/dirty.md worktree_dirty']));+ }, { databaseUrl, setup }), 180_000);++ test('a strict source imports every committed blob over the database, deletes the removed page and holds nothing', () => managedBrain(async ({ engine, root }) => {+ await diverge(engine, root);+ await strict(engine);+ await performManagedSync(engine, OPTS);+ expect((await page(engine, 'notes/ahead'))!.body).toContain('The committed body of notes/ahead.');+ expect((await page(engine, 'notes/drift'))!.body).toContain('The committed edit of notes/drift.');+ expect((await page(engine, 'notes/dirty'))!.body).toContain('The committed edit of notes/dirty.');+ expect(readFileSync(join(root, 'notes/dirty.md'), 'utf8')).toContain('An uncommitted edit of notes/dirty.');+ expect((await page(engine, 'notes/removed'))!.deleted).toBe(true);+ expect(await holds(engine)).toEqual([]);+ const again = await performManagedSync(engine, OPTS);+ expect(again.status).toBe('up_to_date');+ expect((await page(engine, 'notes/dirty'))!.body).toContain('The committed edit of notes/dirty.');+ }, { databaseUrl, setup }), 180_000);++ test('a strict source refuses --working-tree before anything runs', () => managedBrain(async ({ engine, root }) => {+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');+ await strict(engine);+ writeFileSync(join(root, 'notes/ahead.md'), note('notes/ahead', 'An uncommitted edit.'));+ await expect(performManagedSync(engine, { ...OPTS, workingTree: true })).rejects.toMatchObject({ code: 'managed_sync_flag_refused', detail: '--working-tree' });+ expect((await page(engine, 'notes/ahead'))!.body).toContain('The committed body of notes/ahead.');+ }, { databaseUrl, setup }), 180_000);+});diff --git a/test/sync-classify-strict-g3.test.ts b/test/sync-classify-strict-g3.test.tsnew file mode 100644index 0000000000..d8e1efd8a1--- /dev/null+++ b/test/sync-classify-strict-g3.test.ts@@ -0,0 +1,96 @@+/**+ * G3 of git-canonical memory: the level classifier's strict verdict (sync-classify.ts `classifySyncPath(s, { strict: true })`).+ * A strict source reads its commit alone and Git wins: drift, a database version sync never saw, keep_db and an edited+ * tombstone import the committed blob; the working tree is invisible; a live page whose file a commit removed is deleted and+ * one Git never held is left as the database has it; holds keep their rows. A source that is not strict is unchanged.+ */+import { describe, expect, test } from 'bun:test';+import { classifySyncPath, type SyncDirtiness, type SyncPathState } from '../src/core/persistence/sync-classify.ts';++const base: SyncPathState = { mode: 'committed', tree: 'B', level: 'B', present: true, dirty: 'clean', diskOid: null,+ page: { live: true, revision: 'R1', originMatches: true }, record: { blobOids: ['B'], revision: 'R1', parserSame: true },+ attested: null, levelSha256: null, published: false, hold: null, marker: null, baseline: null, spelling: false, episodeUnsatisfied: false, keepDb: false, openWork: false };+const strict = (s: SyncPathState) => classifySyncPath(s, { strict: true });+const dbOnly = { ...base, page: { live: true, revision: 'R2', originMatches: true } };+const gitMoved = { ...base, tree: 'C', level: 'C' };++describe('G3: Git wins on a strict source', () => {+ test('a database version sync never saw imports the committed blob; a pending door write stays settled', () => {+ expect(classifySyncPath(dbOnly)).toMatchObject({ cls: 'db_ahead', sub: 'db_only', settled: true, action: 'none' });+ expect(strict(dbOnly)).toMatchObject({ cls: 'import', action: 'import', settled: false, gitWins: 'db_ahead' });+ expect(strict({ ...dbOnly, record: { ...dbOnly.record!, revision: null } })).toMatchObject({ cls: 'import', gitWins: 'db_ahead' });+ const pending = { ...dbOnly, attested: { hash: null, arm1: true } };+ expect(strict(pending)).toEqual(classifySyncPath(pending));+ });++ test('drift on either side imports the commit', () => {+ const both = { ...gitMoved, page: dbOnly.page };+ expect(classifySyncPath(both)).toMatchObject({ cls: 'drift', action: 'hold', side: 'both' });+ expect(strict(both)).toMatchObject({ cls: 'import', action: 'import', gitWins: 'drift' });+ const unknown = { ...both, record: { ...both.record!, revision: null } };+ expect(classifySyncPath(unknown)).toMatchObject({ cls: 'drift', side: 'unknown' });+ expect(strict(unknown)).toMatchObject({ cls: 'import', gitWins: 'drift' });+ });++ test('keep_db no longer applies: the commit imports', () => {+ const keep = { ...gitMoved, page: dbOnly.page, keepDb: true };+ expect(classifySyncPath(keep)).toMatchObject({ cls: 'keep_db' });+ expect(strict(keep)).toMatchObject({ cls: 'import', gitWins: 'keep_db' });+ const settledKeep = { ...dbOnly, keepDb: true };+ expect(classifySyncPath(settledKeep)).toMatchObject({ cls: 'db_ahead', keepDbWrite: true, action: 'keep_db' });+ expect(strict(settledKeep)).toMatchObject({ cls: 'import', action: 'import', gitWins: 'db_ahead' });+ });++ test('an edited tombstone imports the committed file', () => {+ const tombstone = { ...gitMoved, page: { live: false, revision: 'R1', originMatches: true } };+ expect(classifySyncPath(tombstone)).toMatchObject({ cls: 'deleted_edited', action: 'hold' });+ expect(strict(tombstone)).toMatchObject({ cls: 'import', action: 'import', gitWins: 'deleted_edited' });+ });++ test('the working tree is invisible: any dirtiness reads as the committed blob', () => {+ for (const dirty of ['modified', 'staged', 'deleted', 'untracked', 'unknown'] as SyncDirtiness[]) {+ const s = { ...base, dirty, diskOid: 'D', levelSha256: 'sha-D' };+ expect(strict(s)).toMatchObject({ cls: 'matched', settled: true, action: 'none' });+ expect(strict({ ...s, tree: 'C', level: 'C' })).toMatchObject({ cls: 'import', action: 'import' });+ }+ expect(classifySyncPath({ ...gitMoved, dirty: 'modified', diskOid: 'D' })).toMatchObject({ cls: 'dirty', action: 'hold' });+ });++ test('a live page whose file is absent from the commit waits for its origin evidence, then deletes only on a commit', () => {+ const untrackedCopy = { ...base, tree: null, level: null, present: true };+ expect(classifySyncPath(untrackedCopy)).toMatchObject({ cls: 'kept', settled: true });+ expect(strict(untrackedCopy)).toMatchObject({ cls: 'delete', action: 'delete' });+ expect(strict({ ...untrackedCopy, originEvidence: 'committed' })).toMatchObject({ cls: 'delete', action: 'delete' });+ const unproven = { ...untrackedCopy, page: dbOnly.page, present: false };+ expect(strict(unproven)).toMatchObject({ cls: 'delete_drift' });+ expect(strict({ ...unproven, originEvidence: 'committed' })).toMatchObject({ cls: 'delete', action: 'delete', gitWins: 'delete_drift' });+ for (const originEvidence of ['never_committed', 'ignored', 'unknown'] as const) {+ expect(classifySyncPath({ ...unproven, originEvidence })).toMatchObject({ cls: 'delete_drift', action: 'hold' });+ expect(strict({ ...unproven, originEvidence })).toMatchObject({ cls: 'kept', settled: true, action: 'none', gitWins: 'delete_drift' });+ }+ });++ test('holds keep their rows: one at its level settles, a re-screened one re-runs Git\'s verdict', () => {+ const hold = { atLevel: true, rescreenDue: false, retried: false };+ expect(strict({ ...gitMoved, page: dbOnly.page, hold })).toMatchObject({ cls: 'held', settled: true });+ expect(strict({ ...gitMoved, page: dbOnly.page, hold: { ...hold, rescreenDue: true } })).toMatchObject({ cls: 'held', settled: false, action: 'import' });+ });++ test('with origin evidence read, a strict committed-mode path is never held by the classifier', () => {+ const pages = [null, base.page, dbOnly.page, { live: false, revision: 'R1', originMatches: true }];+ const records = [null, base.record, { ...base.record!, revision: null }, { ...base.record!, blobOids: ['A'] }];+ const levels: Array<[string | null, string | null]> = [['B', 'B'], ['C', 'C'], [null, null]];+ const dirties: Array<SyncDirtiness | null> = ['clean', 'modified', 'untracked', null];+ for (const page of pages) for (const record of records) for (const [tree, level] of levels) for (const dirty of dirties)+ for (const keepDb of [false, true]) for (const originEvidence of ['committed', 'never_committed', 'unknown'] as const) {+ const s: SyncPathState = { ...base, page, record, tree, level, dirty, keepDb, originEvidence, present: dirty !== null };+ expect(strict(s).action).not.toBe('hold');+ }+ });++ test('a working level and a source that is not strict classify exactly as before', () => {+ const working = { ...gitMoved, mode: 'working' as const, page: dbOnly.page };+ expect(strict(working)).toEqual(classifySyncPath(working));+ for (const s of [base, dbOnly, gitMoved, { ...gitMoved, page: dbOnly.page }]) expect(classifySyncPath(s, { strict: false })).toEqual(classifySyncPath(s));+ });+});