Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(sync): clear stale managed failure receipts the imported commit settles (#6288 part 2)
time-attack85151c52007a
diff --git a/docs/architecture/key-files/google-and-loops-continued.md b/docs/architecture/key-files/google-and-loops-continued.mdindex 51fda52a96..57ce84d362 100644--- a/docs/architecture/key-files/google-and-loops-continued.md+++ b/docs/architecture/key-files/google-and-loops-continued.md@@ -2,7 +2,7 @@[Subsystem index](../KEY_FILES.md) · [Previous entries](google-and-loops.md).-- `src/core/persistence/sync-failures.ts` — durable managed cursor/receipt diagnostics are the authority; JSONL is a compatibility mirror keyed by cursor and source/path. Failure observations deduplicate terminal receipts, retaining structured codes and attempts; success clears only its matching cursor. A failure records the cursor-selecting `syncOptions` and `processingOptions` of its run (falling back to its cursor's when read), and every local hint (the thrown failure line, the blocked report, the terminal write diagnostic and local doctor) renders the exact retry through `managedSyncRetryCommand` → `checkpointRetryCommand`; a failure recorded before options were kept says so instead of guessing. `sync --retry-failed` counts only failures of the cursor key its own options select (`managedSyncCursorKey`) and lists the others with their own retry command. Local CLI shows request/run/pinned target details, while remote doctor returns source-scoped aggregates without paths, raw messages or receipt IDs. Missing durable state warns rather than certifying health. Failed receipts cannot be acknowledged, auto-skipped or rewritten; explicit idle ordinary-source retry creates fresh admission, while approved company manifests remain pinned. Tests: `test/persistence-sync-failures.serial.test.ts`, `test/e2e/managed-sync-failures.test.ts`. #6402: a new observation moves the row's `updated_at`, and an observation of a different target commit restarts `first_seen` and `attempts` (a `--retry-failed` of the same target keeps counting); `sync-run.ts` does not record an `invalid_params` refusal raised while resuming (cursor-option conflicts are caller errors), so it never overwrites the real diagnosis.+- `src/core/persistence/sync-failures.ts` — durable managed cursor/receipt diagnostics are the authority; JSONL is a compatibility mirror keyed by cursor and source/path. Failure observations deduplicate terminal receipts, retaining structured codes and attempts; success clears only its matching cursor. A failure records the cursor-selecting `syncOptions` and `processingOptions` of its run (falling back to its cursor's when read), and every local hint (the thrown failure line, the blocked report, the terminal write diagnostic and local doctor) renders the exact retry through `managedSyncRetryCommand` → `checkpointRetryCommand`; a failure recorded before options were kept says so instead of guessing. `sync --retry-failed` counts only failures of the cursor key its own options select (`managedSyncCursorKey`) and lists the others with their own retry command. Local CLI shows request/run/pinned target details, while remote doctor returns source-scoped aggregates without paths, raw messages or receipt IDs. Missing durable state warns rather than certifying health. Failed receipts cannot be acknowledged, auto-skipped or rewritten; explicit idle ordinary-source retry creates fresh admission, while approved company manifests remain pinned. Tests: `test/persistence-sync-failures.serial.test.ts`, `test/e2e/managed-sync-failures.test.ts`. #6402: a new observation moves the row's `updated_at`, and an observation of a different target commit restarts `first_seen` and `attempts` (a `--retry-failed` of the same target keeps counting); `sync-run.ts` does not record an `invalid_params` refusal raised while resuming (cursor-option conflicts are caller errors), so it never overwrites the real diagnosis. #6288: after a successful managed sync (`commands/sync/perform.ts`), `clearSettledManagedSyncFailures` removes this source's failure rows under other cursor keys (a `--full` run's, never resumed by autopilot) whose cursor is finished or gone and whose file the imported commit settles (present there with a live page and no hold, or absent there with no live page), database row and JSONL mirror together; `gbrain sync --source <id> --acknowledge-managed <request_id|path>` (owner host CLI only, `readManagedSyncImported` resolves the active local binding) removes only such settled rows and refuses the rest with `managed_failure_unsettled` (`sync-managed-stale-failures.test.ts`).- `src/commands/mcp-expose-probe.ts` — the health / occupancy probes `mcp-expose.ts` runs, peeled out behind a narrow `ProbeDeps` (`fetch`, `tcpProbe`, `lookup`, `now`, `sleep`, `healthIntervalMs`) rather than the whole resolved-deps bag: `tryFetch(d, url, timeoutMs)` (one bounded fetch, `redirect: 'manual'`, never throws → `FetchOutcome { res, unresolved }`), `probeHealth` (`res.ok` — the `verify.*` / `--status` bar), `probeOccupied` (an accepted TCP connect OR any HTTP answer — the foreign-listener bar), `pollHealth` (wall-clock budget from `d.now()`, per-probe timeout `min(1500, remaining)`, attempt cap `ceil(budget / healthIntervalMs)` as the frozen-clock backstop, `unresolved` = the LAST probe's verdict), `unresolvedDetail(dnsName)`, `defaultTcpProbe` (one `node:net` connect, socket destroyed on every outcome) and `defaultLookup` (local RFC 6761 `.invalid` rejection, otherwise `dns.promises.lookup`). The name-resolution verdict is the reason the module exists: Bun's `fetch` rejects an unresolvable host with the SAME error as a refused connection ("Unable to connect. Is the computer able to access the url?", code `ConnectionRefused`), so a message match alone never fires in production. After a rejection `nameUnresolved` takes `new URL(url).hostname`, skips IP literals (`isIP`) and `localhost`, and otherwise awaits `d.lookup(host)` raced against the probe's `timeoutMs` (a lookup that does not answer in time proves nothing; the race keeps a late rejection handled); `isUnresolvedLookupError` classifies the lookup rejection by `code` — `ENOTFOUND`, `EAI_AGAIN`, `EAI_NONAME`, `EAI_NODATA`, `DNS_ENOTFOUND` (a resolver outage counts: the verdict is about THIS host) — or by those tokens in its message, and the fetch-message regex (`ENOTFOUND|getaddrinfo|EAI_AGAIN|failed to resolve|Unable to connect.*resolve`) is OR-ed in afterwards as the secondary hint. Tests inject a fake fetch, TCP probe and resolver (`test/mcp-expose.test.ts`; the fixture's default `lookup` resolves every name, reserved-name and label-boundary cases do not query external DNS, and the real `defaultLookup` resolves localhost). `statusOnlyHealthDetail(port)` reads this host's live status-only marker for the port so `verify.local` reads "status-only (<reason>)" instead of a timeout or "no answer".- `src/core/tailscale.ts` — Tailscale helpers with an injected exec seam (`CommandRunner = (argv, { inherit?, timeoutMs?, stdoutToStderr? }) => Promise<CommandResult>` where `CommandResult = { status, stdout, stderr }` and `status: null` means killed at the timeout or never spawned; `defaultCommandRunner` on `Bun.spawn` — at `timeoutMs` it sends SIGTERM and, when the child has still not exited `SIGKILL_GRACE_MS` (3s) later, SIGKILL, so a child that ignores SIGTERM never hangs the caller; both timers are cleared in a `finally` — also the runner `serve-service.ts` types against; `stdoutToStderr` sends an inherited child's stdout to fd 2 so `--json` stdout stays pure): `parseTailscaleStatus` (`BackendState` — `Running`, `NeedsLogin`, `NeedsMachineAuth`, `NoState`, `Stopped`; `Self.DNSName`, `CertDomains`, and `funnelCapable`: true/false from `Self.CapMap` keys or `Self.Capabilities` entries carrying any Funnel form — `funnel` (`NodeAttrFunnel`), `https://tailscale.com/cap/funnel-ports` with or without its `?ports=` query, or the legacy `https://tailscale.com/cap/funnel` — null when both are absent), `publicUrlFromDnsName` (strip trailing dot, lowercase, `https://`), `TAILSCALE_BINARY_CANDIDATES` + `findTailscaleBinary` (`Bun.which`, then the macOS app bundle, Homebrew and `/usr/bin` paths; the candidate list doubles as `mcp-expose.ts`'s allowlist for a binary path recorded in a receipt) + `isSystemTailscaleBinary(binary, realpath = realpathSync)` (true when the path is a candidate literally or resolves to one through symlinks; an unresolvable path is false — `mcp-expose.ts` puts `sudo` in front of the binary only when this holds), `tailscaleInstallPlan(platform, hasBrew)`, `tailscaleLoginArgv(platform, user, binary)` → `{ setOperator?, up }` (Linux: `sudo <bin> set --operator=<user>` then a flagless `sudo <bin> up` — a flagged `up` trips the CLI's settings-revert check on a node with non-default prefs; macOS: `<bin> up`), `tailscaleManualLoginCommand(binary = 'tailscale')` (the Linux login the operator runs themselves when gbrain refuses to `sudo` a non-system binary — `sudo <bin> set --operator=$USER && sudo <bin> up` with the DISCOVERED path shell-quoted through `shellQuote`, because a binary outside sudo's `secure_path` is exactly that case) and `TAILSCALE_ACCEPT_DNS_COMMAND` (`tailscale set --accept-dns=true`, the MagicDNS-off remedy) — both keep their tailscale flag literals in this module so the flag-registry scan of `mcp-expose.ts` never sees them, `tailscaleServeArgv(port, { funnel })` (`serve --bg` / `funnel --bg`) + `tailscaleServeOffArgv({ funnel })` (`serve|funnel --https=443 --set-path=/ off` — `--set-path=/` scopes `off` to OUR `/` mount; without it the CLI removes every mount under `:443` and, when more than one exists, prompts interactively — with stdin ignored the prompt reads EOF and the command exits 0 having removed nothing; never `serve reset`), `parseServeStatusStrict` (the only serve-status parser, fail-closed: background `Web` handlers, `Foreground[<session>].Web` handlers marked `foreground: true`, and `TCP['443'].TCPForward` as a non-proxy root handler; an empty document / `{}` / `null` is the legitimately empty view, but non-JSON, an array or a scalar returns `null` so `mcp-expose.ts`'s `readServeView` can tell "could not read" from "nothing configured") + `findProxiedHandler(view, port)`, `classifyTailscaleError(stderr)` (Funnel rule before the HTTPS rule; the HTTPS rule matches certificate vocabulary, never a bare `https://` URL: `funnel_not_enabled` | `https_not_enabled` | `needs_operator` | `needs_login` | `daemon_not_running` | `unknown`), and the admin/KB URL constants (`TAILSCALE_ADMIN_DNS_URL`, `TAILSCALE_ADMIN_ACL_URL`, `TAILSCALE_FUNNEL_KB_URL` = `https://tailscale.com/kb/1223/funnel`, `TAILSCALE_DOWNLOAD_URL`). The parsers and argv builders are pure; the injectable `which` / `fileExists` / runner defaults touch `existsSync`, `process.env.PATH` and `process.platform`, and tests replace them. Note `tailscale status --json` exits 0 in every `BackendState` (only the human-readable form exits 1 when logged out), and `serve`/`funnel` wait interactively rather than failing when HTTPS certificates or the Funnel attribute are off — which is why `mcp-expose.ts` pre-checks before starting them.diff --git a/src/commands/sync/args.ts b/src/commands/sync/args.tsindex 9964b31b15..1d5138aceb 100644--- a/src/commands/sync/args.ts+++ b/src/commands/sync/args.ts@@ -87,6 +87,10 @@ Options:--skip-failed Legacy sync only: acknowledge previously-recordedsync failures so the bookmark can advance. Held filesnever need it; managed sync refuses it.+ --acknowledge-managed <request_id|path>+ Managed sync, owner host only: remove a recorded+ failure (for example a --full run's) that the imported+ commit already settles; refuses anything still unsynced.--retry-failed Re-attempt previously-failed files; clear on success.Not needed for held files, which re-screen on the nextsync when they change (or with 'gbrain sourcesdiff --git a/src/commands/sync/perform.ts b/src/commands/sync/perform.tsindex 3141928757..53edfee7db 100644--- a/src/commands/sync/perform.ts+++ b/src/commands/sync/perform.ts@@ -61,6 +61,7 @@ export async function performSync(engine: BrainEngine, opts: SyncOpts): Promise<? await (await import('../../core/persistence/sync-drain.ts')).drainManagedSync(engine, opts, true): await (await import('../../core/persistence/sync-run.ts')).performManagedSync(engine, opts);if (!opts.dryRun) await recordUpstreamObservation(engine, opts.sourceId ?? 'default', opts.repoPath);+ if (!opts.dryRun && ['synced', 'first_sync', 'up_to_date'].includes(result.status)) await clearSettledFailures(engine, opts.sourceId ?? 'default');return result;}const filesystemRoot = opts.repoPath || await readSyncAnchor(engine, opts.sourceId, 'repo_path');@@ -104,3 +105,12 @@ export async function performSync(engine: BrainEngine, opts: SyncOpts): Promise<throw err;}}++/** #6288: a successful managed sync clears this source's recorded failures its imported commit already settles; best effort. */+async function clearSettledFailures(engine: BrainEngine, sourceId: string): Promise<void> {+ try {+ const { clearSettledManagedSyncFailures, readManagedSyncImported } = await import('../../core/persistence/sync-failures.ts');+ const imported = await readManagedSyncImported(engine, sourceId);+ if (imported) await clearSettledManagedSyncFailures(engine, imported);+ } catch { }+}diff --git a/src/commands/sync/run.ts b/src/commands/sync/run.tsindex 60871e5e6a..011a7931e6 100644--- a/src/commands/sync/run.ts+++ b/src/commands/sync/run.ts@@ -77,6 +77,8 @@ export async function runSyncInner(engine: BrainEngine, args: string[]) {return;}+ if (args.includes('--acknowledge-managed')) return runAcknowledgeManaged(engine, args);+const flags = parseSyncFlags(args);const { repoPath, dryRun, skipFailed, syncAll, jsonOut, breakLock, forceBreakLock, maxAgeSeconds } = flags;let { noEmbed } = flags;@@ -136,6 +138,29 @@ export async function runSyncInner(engine: BrainEngine, args: string[]) {return await runSingleSourceSync(engine, { ...flags, ...fanout }, { sourceId, companyPolicy, noEmbed, resumeCommand, args });}+/** #6288: `gbrain sync --source <id> --acknowledge-managed <request_id|path>` removes only recorded failures the imported commit settles. */+async function runAcknowledgeManaged(engine: BrainEngine, args: string[]): Promise<void> {+ const { opError } = await import('../../core/ops/contract.ts');+ const selector = args[args.indexOf('--acknowledge-managed') + 1];+ const sourceId = args.find((a, i) => args[i - 1] === '--source');+ const status = (id: string) => ({ argv: ['gbrain', 'sync', 'status', '--source', id, '--json'], consent: [], actor: 'agent' as const, requires_exclusive: false,+ why: 'Shows the recorded failure, its class and the exact sync that settles it, read-only.' });+ if (!selector || selector.startsWith('--') || !sourceId) throw opError('invalid_params', '--acknowledge-managed needs --source <id> and a request id or path.',+ 'Name the source and the recorded failure, for example gbrain sync --source <id> --acknowledge-managed <request_id|path>; gbrain sync status --source <id> --json lists them.');+ const { acknowledgeManagedSyncFailures, readManagedSyncImported } = await import('../../core/persistence/sync-failures.ts');+ const imported = await readManagedSyncImported(engine, sourceId);+ if (!imported) throw opError('managed_failure_unsettled', `Source ${sourceId} has no successful managed sync yet, so nothing can be acknowledged.`,+ `Run gbrain sync --no-pull --source ${sourceId} first; a recorded failure is acknowledged only when the imported commit settles it.`, { fix: status(sourceId) });+ const result = await acknowledgeManagedSyncFailures(engine, imported, selector);+ for (const failure of result.cleared) slog(`Acknowledged recorded failure ${failure.code} for ${failure.path} (request ${failure.request_id ?? '<not-admitted>'}): commit ${imported.target.slice(0, 12)} already imports it.`);+ if (result.refused.length || !result.cleared.length) {+ throw opError('managed_failure_unsettled', result.refused.length ? `${result.refused.length} recorded failure(s) for ${selector} are not settled by the imported state.` : `No recorded managed failure of source ${sourceId} matches ${selector}.`,+ result.refused.length ? `Refused: ${result.refused.map(r => `${r.failure.path} (${r.reason})`).join(', ')}. The file still differs from what commit ${imported.target.slice(0, 12)} imported, its run is unfinished, or it is held; nothing was removed for it. Resume or retry that sync instead.`+ : 'Check the request id or path against gbrain sync status --source <id> --json; nothing was removed.', { fix: status(sourceId) });+ }+ if (args.includes('--json')) await writeJsonDocument(JSON.stringify({ source_id: sourceId, imported_commit: imported.target, cleared: result.cleared }));+}+async function runSyncBreakLock(engine: BrainEngine,args: string[],diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex f6df2a343f..277a65361a 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -248,6 +248,7 @@ export const CODES = {lock_busy: { class: 'retryable', summary: "Another process holds the lock this command needs." },maintenance_backpressure: { class: 'retryable', summary: "Managed maintenance stopped admitting requests because this writer's outstanding requests, reserved receipt bytes or permanent request ids would pass 80% of their limit; nothing more was submitted.", why: "Each page of a maintenance run publishes as its own request under the local CLI writer the user's own CLI writes share. Stopping at 80% leaves room for those writes: reserved receipt bytes free only when receipts compact, request ids never.", docs: 'docs/guides/write-refusals.md#maintenance_backpressure', fix: { argv: ['gbrain', 'sources', 'writer', 'status', '--source', '{source_id}', '--json'], consent: [], actor: 'agent', why: "Shows the pending requests holding this writer's capacity, read-only.", requires_exclusive: false }, exit: 12 },maintenance_lock_busy: { class: 'retryable', summary: "A source-scoped dream cycle skipped its brain-wide phases because another cycle (usually autopilot maintenance) holds the shared gbrain-cycle lease; its source phases still ran.", why: 'Brain-wide phases (synthesize, patterns, embed, purge and the other mixed or global phases) must not run twice at once, so a cycle that cannot take gbrain-cycle runs only the phases its own source lease covers.', docs: 'docs/guides/cron-schedule.md#dream-beside-autopilot', suggestion: 'Nothing is lost: the holder runs those phases itself. To run one now, wait until the lease is released, then re-run `gbrain dream --phase <phase>` (LLM-backed phases spend; ask the user first).', fix: { argv: ['gbrain', 'status', '--section', 'locks', '--json'], consent: [], actor: 'agent', why: 'Shows who holds gbrain-cycle and when its lease expires, read-only.', requires_exclusive: false } },+ managed_failure_unsettled: { class: 'caller', summary: "The recorded managed sync failure is not settled by the imported state, so it was not acknowledged.", why: "Acknowledging removes a failure record only when the file it failed on is already imported unchanged (or deleted in both the commit and the brain); anything else would hide content that never reached the brain.", suggestion: 'Resume or retry the sync the failure names (gbrain sync status --source <id> --json shows it), then acknowledge again if the record remains.' },merge_recommended: { class: 'caller', retryable: false, actor: 'user',summary: "The content-repair model judged a held file and the page its frontmatter `slug:` names to be the same page, so gbrain recommends merging them instead of removing the slug line; nothing was written.",why: "A `frontmatter_slug_conflict` hold whose two sides describe the same person, company or topic is a duplicate, and the deterministic repair (delete the `slug:` line) would mint a second page for it. gbrain does not merge pages by itself yet (a lossless merge needs a coordinated two-page write with both revisions, withdrawal and metadata preservation; it ships separately), so the lane records the recommendation on the hold as codes and slugs (`meta.content_repair`: the canonical slug that keeps the page), `gbrain sync status` renders a paragraph for a person, and nothing retries it until the file changes.",diff --git a/src/core/persistence/sync-failures.ts b/src/core/persistence/sync-failures.tsindex 03b0fc169f..3c208c2203 100644--- a/src/core/persistence/sync-failures.ts+++ b/src/core/persistence/sync-failures.ts@@ -4,6 +4,8 @@ import type { WriteRequest } from './model.ts';import { checkpointRetryCommand } from './checkpoint-validation.ts';import type { SyncProcessingOptions } from './sync-authority.ts';import type { SyncCursorOptions } from './sync-prepare.ts';+import { resolveManagedSyncContext, syncGit, syncGitPath } from './sync-discovery.ts';+import { readGitHold } from './sync-holds.ts';export interface ManagedSyncFailure {source_id: string;@@ -57,6 +59,82 @@ export async function clearManagedSyncFailureAfterSuccess(engine: BrainEngine, kif (removed.length) try { clearManagedSyncFailure(key); } catch { }}+/** Where a successful managed sync of a source stands: its registered root, Git root and the commit it imported. */+export interface ManagedSyncImported { sourceId: string; incarnation: string; root: string; gitRoot: string; target: string }++/** The imported state of a managed source on its owner host; throws when this host does not own an active binding. */+export async function readManagedSyncImported(engine: BrainEngine, sourceId: string): Promise<ManagedSyncImported | null> {+ const context = await resolveManagedSyncContext(engine, { sourceId, noPull: true });+ const [source] = await engine.executeRaw<{ last_commit: string | null }>('SELECT last_commit FROM sources WHERE id=$1 AND incarnation=$2::uuid', [sourceId, context.incarnation]);+ if (!source?.last_commit) return null;+ return { sourceId, incarnation: context.incarnation, root: context.root, gitRoot: context.gitRoot, target: source.last_commit };+}++function blobAt(gitRoot: string, commit: string, path: string): string | null {+ try { return syncGit(gitRoot, ['rev-parse', '--verify', '--quiet', `${commit}:${path}`]).trim() || null; } catch { return null; }+}++/**+ * #6288: why a recorded managed failure is not settled by the imported state, or null when it is. The imported commit is+ * the source's last successful managed sync, which leaves every path it does not hold imported as of that commit; so a+ * failure is settled when its file exists there and the database holds a live page for it with no hold on the path, or+ * when the file is gone there and no live page claims it.+ */+async function unsettledReason(engine: BrainEngine, run: ManagedSyncImported, failure: ManagedSyncFailure): Promise<string | null> {+ if (failure.source_id !== run.sourceId || failure.source_incarnation !== run.incarnation) return 'source_changed';+ if (failure.path.startsWith('<')) return 'no_recorded_file';+ const gitPath = syncGitPath(run, failure.path);+ const present = blobAt(run.gitRoot, run.target, gitPath) !== null;+ const live = await engine.executeRaw('SELECT 1 FROM pages WHERE source_id=$1 AND deleted_at IS NULL AND source_path = ANY($2::text[]) LIMIT 1', [run.sourceId, [failure.path, gitPath]]);+ if (!present) return live.length ? 'not_deleted' : null;+ if (!live.length) return 'not_imported';+ return await readGitHold(engine, run.sourceId, run.incarnation, failure.path) ? 'held' : null;+}++async function deleteFailure(engine: BrainEngine, key: string, failure: ManagedSyncFailure): Promise<boolean> {+ const removed = await engine.executeRaw(`DELETE FROM op_checkpoints WHERE op='managed-sync-failure' AND fingerprint=$1+ AND completed_keys->0->>'observation_id'=$2 RETURNING fingerprint`, [key, failure.observation_id]);+ if (removed.length) try { clearManagedSyncFailure(key); } catch { }+ return removed.length > 0;+}++async function sourceFailureRows(engine: BrainEngine, sourceId: string): Promise<Array<{ key: string; failure: ManagedSyncFailure; unfinished: boolean }>> {+ const rows = await engine.executeRaw<{ key: string; failure: ManagedSyncFailure; unfinished: boolean }>(`SELECT f.fingerprint AS key,f.completed_keys->0 AS failure,+ EXISTS(SELECT 1 FROM op_checkpoints c WHERE c.op='managed-sync' AND c.fingerprint=f.fingerprint AND COALESCE(c.completed_keys->0->>'done','false')<>'true') AS unfinished+ FROM op_checkpoints f WHERE f.op='managed-sync-failure' AND f.completed_keys->0->>'source_id'=$1 ORDER BY f.fingerprint`, [sourceId]);+ return rows;+}++/**+ * #6288: after a successful managed sync, clears this source's recorded failures under other cursor keys (a `--full` run's+ * key is never resumed by autopilot) whose cursor is finished or gone and whose file the imported commit already settles.+ */+export async function clearSettledManagedSyncFailures(engine: BrainEngine, run: ManagedSyncImported): Promise<number> {+ let cleared = 0;+ for (const row of await sourceFailureRows(engine, run.sourceId)) {+ if (row.unfinished || await unsettledReason(engine, run, row.failure)) continue;+ if (await deleteFailure(engine, row.key, row.failure)) cleared++;+ }+ return cleared;+}++export interface ManagedFailureAcknowledgement { cleared: ManagedSyncFailure[]; refused: Array<{ failure: ManagedSyncFailure; reason: string }> }++/**+ * #6288: `gbrain sync --source <id> --acknowledge-managed <request_id|path>` (host CLI only). Removes the matching recorded+ * failures only when the imported state already settles them; anything else is refused by reason, so no content is skipped.+ */+export async function acknowledgeManagedSyncFailures(engine: BrainEngine, run: ManagedSyncImported, selector: string): Promise<ManagedFailureAcknowledgement> {+ const result: ManagedFailureAcknowledgement = { cleared: [], refused: [] };+ for (const row of await sourceFailureRows(engine, run.sourceId)) {+ if (row.failure.request_id !== selector && row.failure.path !== selector) continue;+ const reason = row.unfinished ? 'cursor_unfinished' : await unsettledReason(engine, run, row.failure);+ if (reason) result.refused.push({ failure: row.failure, reason });+ else if (await deleteFailure(engine, row.key, row.failure)) result.cleared.push(row.failure);+ }+ return result;+}+export async function readManagedSyncFailures(engine: BrainEngine, sourceIds?: string[]): Promise<ManagedSyncFailure[]> {const rows = await engine.executeRaw<{ cursor_key: string; value: { sourceId: string; incarnation: string; runId: string; index: number; target: string; pending?: { requestId: string };syncOptions: SyncCursorOptions | null; processingOptions: Partial<SyncProcessingOptions> | null };diff --git a/test/sync-cancelled-knock-on.test.ts b/test/sync-cancelled-knock-on.test.tsindex 6e9ec40286..fe8a83a7db 100644--- a/test/sync-cancelled-knock-on.test.ts+++ b/test/sync-cancelled-knock-on.test.ts@@ -73,7 +73,7 @@ test('sync status turns a cancelled knock-on into the retry sync prints, not a hexpect(status.needs_human).toBe(false);const [failure] = await readManagedSyncFailures(engine, [f.id]);const printed = managedSyncRetryCommand(failure!).split(' ');- expect([...status.next!.argv].sort()).toEqual([...printed].sort());+ expect([...status.next!.argv!].sort()).toEqual([...printed].sort());}), 120_000);test('a resume refused for conflicting cursor options leaves the recorded failure untouched', async () => withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home }, async () => {diff --git a/test/sync-managed-stale-failures.test.ts b/test/sync-managed-stale-failures.test.tsnew file mode 100644index 0000000000..8b88c54c7c--- /dev/null+++ b/test/sync-managed-stale-failures.test.ts@@ -0,0 +1,88 @@+/**+ * #6288 part 2: a recorded managed sync failure under a cursor key autopilot never resumes (a `--full` run's) can be cleared.+ *+ * Protects: after a successful managed sync, a failure row of that source whose cursor is gone and whose file the imported+ * commit settles (imported and not held; or absent from the commit with no live page) is removed from the database and from the JSONL mirror; a row for+ * a file that is held or never imported stays. `gbrain sync --acknowledge-managed <request_id|path>` removes only settled+ * rows and refuses the rest (unsettled, or an unfinished cursor) with `managed_failure_unsettled`.+ */+import { afterAll, beforeAll, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { execFileSync } from 'node:child_process';+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { performSync } from '../src/commands/sync.ts';+import { runSyncInner } from '../src/commands/sync/run.ts';+import { claimWorktree } from '../src/core/persistence/ownership.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { acknowledgeManagedSyncFailures, readManagedSyncImported, recordManagedSyncFailure } from '../src/core/persistence/sync-failures.ts';+import { loadSyncFailures } from '../src/core/sync-failure-ledger.ts';+import { withEnv } from './helpers/with-env.ts';++const home = mkdtempSync(join(tmpdir(), 'gbrain-6288-'));+let engine: PGLiteEngine;+const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();+const commit = (root: string) => { git(root, 'add', '.'); git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', 'change'); };+const note = (body: string) => `---\ntitle: Example\n---\n${body}\n`;+async function fixture() {+ const id = `sf-${randomUUID().replace(/-/g, '').slice(0, 20)}`, root = join(home, id);+ mkdirSync(root); git(root, 'init', '-q');+ writeFileSync(join(root, 'a.md'), note('Alpha.')); writeFileSync(join(root, 'b.md'), note('Beta.'));+ commit(root);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await engine.executeRaw("INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,'{}')", [id, root]);+ await claimWorktree(engine, id, root);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ const opts = { sourceId: id, noPull: true, noEmbed: true, noExtract: true };+ expect((await performSync(engine, opts)).status).toBe('first_sync');+ const [source] = await engine.executeRaw<{ incarnation: string }>('SELECT incarnation::text AS incarnation FROM sources WHERE id=$1', [id]);+ return { id, root, opts, incarnation: source!.incarnation };+}+/** A failure recorded under a cursor key with no cursor, as a `--full` run that stopped before saving one leaves it. */+async function staleFailure(f: { id: string; incarnation: string }, path: string, key = `full-${randomUUID()}`) {+ const requestId = randomUUID();+ await recordManagedSyncFailure(engine, { source_id: f.id, source_incarnation: f.incarnation, path, code: 'invalid_params', message: 'Invalid YAML frontmatter.',+ request_id: requestId, run_id: randomUUID(), target: 'deadbeef', cursor_key: key, phase: 'receipt', state: 'failed', observation_id: requestId });+ return { key, requestId };+}+const rows = async (id: string) => (await engine.executeRaw<{ path: string }>("SELECT completed_keys->0->>'path' AS path FROM op_checkpoints WHERE op='managed-sync-failure' AND completed_keys->0->>'source_id'=$1 ORDER BY 1", [id])).map(r => r.path);+const mirrored = (id: string) => loadSyncFailures().filter(row => row.source_id === id).map(row => row.path).sort();++beforeAll(async () => { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }, 60_000);+afterAll(async () => { await disposePersistenceConsumer(engine); await engine.disconnect(); rmSync(home, { recursive: true, force: true }); });++test('a successful managed sync clears a stale failure its imported commit settles and keeps one it does not', async () => withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home }, async () => {+ const f = await fixture();+ await staleFailure(f, 'a.md');+ await staleFailure(f, 'gone.md');+ writeFileSync(join(f.root, 'c.md'), '---\ntitle: [broken\n---\nGamma, committed but held.\n');+ commit(f.root);+ await staleFailure(f, 'c.md');+ expect(await rows(f.id)).toEqual(['a.md', 'c.md', 'gone.md']);+ expect(mirrored(f.id)).toEqual(['a.md', 'c.md', 'gone.md']);+ expect((await performSync(engine, f.opts)).status).toBe('synced');+ expect(await rows(f.id)).toEqual(['c.md']);+ expect(mirrored(f.id)).toEqual(['c.md']);+}), 120_000);++test('--acknowledge-managed removes a settled failure by request id and refuses an unsettled one or an unfinished cursor', async () => withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home }, async () => {+ const f = await fixture();+ writeFileSync(join(f.root, 'missing.md'), '---\ntitle: [broken\n---\nCommitted, held, never imported.\n');+ commit(f.root);+ expect((await performSync(engine, f.opts)).status).toBe('synced');+ const settled = await staleFailure(f, 'b.md');+ await staleFailure(f, 'missing.md');+ const imported = (await readManagedSyncImported(engine, f.id))!;+ const ack = await acknowledgeManagedSyncFailures(engine, imported, settled.requestId);+ expect(ack.cleared.map(row => row.path)).toEqual(['b.md']);+ expect(ack.refused).toEqual([]);+ await expect(runSyncInner(engine, ['--source', f.id, '--acknowledge-managed', 'missing.md'])).rejects.toMatchObject({ code: 'managed_failure_unsettled' });+ expect(await rows(f.id)).toEqual(['missing.md']);+ const unfinished = await staleFailure(f, 'a.md');+ await engine.executeRaw(`INSERT INTO op_checkpoints(op,fingerprint,completed_keys) VALUES('managed-sync',$1,'[{"done":false}]'::jsonb)`, [unfinished.key]);+ const refused = await acknowledgeManagedSyncFailures(engine, imported, 'a.md');+ expect(refused.cleared).toEqual([]);+ expect(refused.refused.map(row => row.reason)).toEqual(['cursor_unfinished']);+}), 120_000);