Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
sources: refresh runs inside the resident PGLite owner over persistence IPC
garrytanfd33b65646db
diff --git a/docs/architecture/key-files/core-persistence.md b/docs/architecture/key-files/core-persistence.mdindex a13f08269b..84096e7fd5 100644--- a/docs/architecture/key-files/core-persistence.md+++ b/docs/architecture/key-files/core-persistence.md@@ -56,7 +56,7 @@ Connector ingestion, item holds and checkpoint validation continue in [Core Pers- `src/core/persistence/{source-lifecycle,managed-sources,topology-schema,topology-locks,topology-receipts,topology-clone,topology-clone-model,topology-filesystem,topology-recovery}.ts` — migration 157 coordinates source add/claim/archive/restore/remove/purge/rebind/reclone. Native root locks precede topology/source/grant/counter/request guards; a shared root advances every membership and permanently conflicts accepted old-topology requests. Withdrawal mirrors and running publication must settle first. Administrative UUIDs share the page journal's principal-scoped conflict domain and permanent capacity counters. Directory replacement reserves the configured recovery budget before provider/staging work, records a verified manifest and physical identity, and recovers only known bytes; clone failure retains the original checkout and a replayable failure receipt. Rebinding accepts a fresh candidate with exactly matching canonical content, including deletions. Stored worktree manifests and clone recovery records keep `digest`, `file_count`, `canonical_stamp` and `self_transfer` but no per-file map (#5790), so their size is independent of the worktree; `compactStoredManifest` drops a legacy map on rewrite, and transfer prepare/accept hash under the native lock before their transaction. Large-repo tests: `test/persistence-large-manifest.test.ts` (12k files, both engines via `test/e2e/persistence-large-manifest-postgres.test.ts`) and `test/e2e/persistence-large-manifest-50k.test.ts`. Old root refusal records remain. Metadata deletion retains local storage. Restart recovery rotates a bounded root scan so one conflict cannot starve other roots. Tests: `test/persistence-source-lifecycle.test.ts` on PGLite and guarded isolated Postgres.-- `src/core/persistence/{worktree-refresh,worktree-refresh-schema}.ts` — `gbrain sources refresh` (F0), the one sanctioned managed Git writer. `persistence_worktree_refreshes` holds one row per refresh with a partial unique index (one active refresh per worktree; its 23505 maps to `refresh_in_progress`). `refreshWorktree` prechecks with no database state (managed, owner host, upstream, no active refresh, no recovery, no unexhausted managed-sync cursor, hardened `git fetch` bounded by `sources.refresh_fetch_timeout_ms`, ancestry, dirty paths intersected with the incoming diff), then: `draining` (inserted under `withTopologyLocks` + `lockTopologyRows`; admission in `journal.ts` refuses `worktree_refreshing` for every request with that `worktree_id`, and `assertManagedSyncAllowed` refuses a managed sync before discovery), poll until no queued/running/recovering request, no queued/running `git`/`withdrawal-mirror` effect and no recovery record remain (else `refresh_drain_timeout`, aborted), `fenced` (both native locks held, rechecked in one transaction; `refreshFenceClear` stops request and effect claims), HEAD verified, dirt rechecked, `git merge --ff-only`, HEAD verified again, then one transaction `merged` + upstream observation + `syncing`; native locks are released and the managed `--no-pull` sync runs per member (only `managed_sync_*` `submit_job` admissions pass during `syncing`); `completed` when every member's `last_commit` is the target, or with `outcome.sync_blocked` when a member sync blocks. A per-worktree `refresh-<worktree>.lock` held for the whole run proves liveness: `resumeWorktreeRefreshes` (called from `recoverSourceTopologies`, so on owner start) touches only interrupted `draining`/`fenced`/`merged` rows whose lock is free and applies the section 1.5 table (draining or fenced at the old HEAD abort; HEAD at the verified target moves to `syncing`; anything else is `recovery_required`, which admission refuses with `refresh_recovery_required`). Admission also completes a `syncing` row whose members all reached the target. `--resume` converges and runs the member syncs; `--abandon` lifts a fence only with HEAD back at the start commit. `gbrain sources writer status` lists active refreshes as `worktree_refreshes` (state, heads, the next command), which the refusal hints point at. Doctor `worktree_refresh_stuck` lists rows active over 15 minutes. CLI body: `src/commands/sources-refresh.ts`. Tests: `test/persistence-worktree-refresh.test.ts`, `test/persistence-worktree-refresh-restart.test.ts` (child-process crash after merge), Postgres via `test/e2e/worktree-refresh-postgres.test.ts`.+- `src/core/persistence/{worktree-refresh,worktree-refresh-schema}.ts` — `gbrain sources refresh` (F0), the one sanctioned managed Git writer. `persistence_worktree_refreshes` holds one row per refresh with a partial unique index (one active refresh per worktree; its 23505 maps to `refresh_in_progress`). `refreshWorktree` prechecks with no database state (managed, owner host, upstream, no active refresh, no recovery, no unexhausted managed-sync cursor, hardened `git fetch` bounded by `sources.refresh_fetch_timeout_ms`, ancestry, dirty paths intersected with the incoming diff), then: `draining` (inserted under `withTopologyLocks` + `lockTopologyRows`; admission in `journal.ts` refuses `worktree_refreshing` for every request with that `worktree_id`, and `assertManagedSyncAllowed` refuses a managed sync before discovery), poll until no queued/running/recovering request, no queued/running `git`/`withdrawal-mirror` effect and no recovery record remain (else `refresh_drain_timeout`, aborted), `fenced` (both native locks held, rechecked in one transaction; `refreshFenceClear` stops request and effect claims), HEAD verified, dirt rechecked, `git merge --ff-only`, HEAD verified again, then one transaction `merged` + upstream observation + `syncing`; native locks are released and the managed `--no-pull` sync runs per member (only `managed_sync_*` `submit_job` admissions pass during `syncing`); `completed` when every member's `last_commit` is the target, or with `outcome.sync_blocked` when a member sync blocks. A per-worktree `refresh-<worktree>.lock` held for the whole run proves liveness: `resumeWorktreeRefreshes` (called from `recoverSourceTopologies`, so on owner start) touches only interrupted `draining`/`fenced`/`merged` rows whose lock is free and applies the section 1.5 table (draining or fenced at the old HEAD abort; HEAD at the verified target moves to `syncing`; anything else is `recovery_required`, which admission refuses with `refresh_recovery_required`). Admission also completes a `syncing` row whose members all reached the target. `--resume` converges and runs the member syncs; `--abandon` lifts a fence only with HEAD back at the start commit. `gbrain sources writer status` lists active refreshes as `worktree_refreshes` (state, heads, the next command), which the refusal hints point at. Doctor `worktree_refresh_stuck` lists rows active over 15 minutes. CLI body: `src/commands/sources-refresh.ts`; while a resident PGLite owner (`gbrain serve`, stdio MCP) holds the database, `src/commands/sources-refresh-delegate.ts` runs the refresh inside it through the `writer_refresh` administration operation (trusted CLI registration only) and prints the same result or refusal. The consumer's idle probe applies `refreshFenceClear` to effects like the claims, so a fenced worktree's queued effects do not wake it. Tests: `test/persistence-worktree-refresh.test.ts`, `test/persistence-worktree-refresh-restart.test.ts` (child-process crash after merge), Postgres via `test/e2e/worktree-refresh-postgres.test.ts`, owner delegation in `test/persistence-sync-stdio-owner.serial.test.ts`.- `src/core/persistence/{types,params,preconditions,verb-errors}.ts` — public mutation receipt states, error reasons and revision/idempotency parameter contracts. Receipt serialization explicitly selects public fields; queued content and execution credentials stay internal. `frozenVerbWriteError` uses MEMORY_VERBS v1's existing error enum with additive `write_request`/`write_error`; `committedVerbOutcome` refuses pending or failed receipts. `OperationError` and the thin MCP client preserve this metadata, including when a timeout races an already-received receipt. The registry-safe parameter/schema leaf never imports operation values. Pinned by `test/persistence-write-contracts.test.ts`, `test/mcp-client-hardening.test.ts` and a real HTTP envelope in `test/mcp-client.test.ts`.- `src/core/persistence/{database-write,manual-links}.ts` — `coordinatedDatabaseWrite` is the managed path for rows with no canonical file; `coordinatedManualLinkWrite` (`add_link` / `remove_link`) and `ontology_propose` (one entity page key) use it. On a managed brain it checks the caller's durable write authority for the authority page (`submissionAuthority`, then `authorizeWrite` FOR SHARE inside the transaction), revalidates the source incarnation and commits inside `withCoordinatedWrite` holding the given page keys (both link endpoints). Unmanaged brains keep the engine calls. Manual edges (`link_source` `manual` or a custom tag) survive re-derivation and republication because automatic reconciliation only replaces derived provenances. Tests: `test/managed-writers-w3.test.ts`, `test/managed-ontology-propose.test.ts`.diff --git a/docs/architecture/key-files/google-and-loops-continued.md b/docs/architecture/key-files/google-and-loops-continued.mdindex cab0f99526..34b6299f05 100644--- a/docs/architecture/key-files/google-and-loops-continued.md+++ b/docs/architecture/key-files/google-and-loops-continued.md@@ -26,7 +26,7 @@- **`src/core/persistence/sync-authority.ts`** — trusted CLI or original remote generic job authority; rejects stdio bulk privilege promotion and runtime option expansion, intersects original grants with current principal/source policy.- `src/core/facts/withdrawal-overlay.ts` — pure legacy-fence enumeration and withdrawal rendering shared by coherent snapshots, stale imports and physical forget mirrors. The shared snapshot overlay and import pre-publication validator recognize canonical prefixed/inline markers and distinguish malformed live segments. Discovery refuses matching ambiguous claims before mutation. Fingerprints match independently in each fence, including inactive history, against both the folded (v174) and exact legacy hashes; parser-recognized markers precede preserved evidence context and earlier expiry remains intact. Regression: `test/withdrawal-overlay-concurrency.test.ts` on both engines.-- **`src/commands/sync-persistence-delegate.ts` + `src/core/persistence/{sync-wire,sync-administration}.ts`** — pre-connect authenticated CLI sync ingress for any resident PGLite owner, including stdio MCP. The CLI JSON renderer shares the direct sync envelope. Strict options preserve source/brain selection and filtering; only current CLI credentials can advance bounded durable cursor slices. Unactivated delegation also forces import-only work and queues the owner embed drain, preserving the inline cost gate; backlogs are per-engine source sets and shutdown waits for actual provider settlement before releasing datastore ownership; the real serve E2E observes a committed receipt before SIGKILL and proves same-ID cursor recovery without breaking locks. Legacy shared-secret sync refuses managed brains. `test/persistence-sync-stdio-owner.serial.test.ts` starts a real stdio owner and exercises CLI import/read/admin, remote-lane denial and revocation without a competing datastore open.+- **`src/commands/sync-persistence-delegate.ts` + `src/core/persistence/{sync-wire,sync-administration}.ts`** — pre-connect authenticated CLI sync ingress for any resident PGLite owner, including stdio MCP. The CLI JSON renderer shares the direct sync envelope. Strict options preserve source/brain selection and filtering; only current CLI credentials can advance bounded durable cursor slices. Unactivated delegation also forces import-only work and queues the owner embed drain, preserving the inline cost gate; backlogs are per-engine source sets and shutdown waits for actual provider settlement before releasing datastore ownership; the real serve E2E observes a committed receipt before SIGKILL and proves same-ID cursor recovery without breaking locks. The env and default deadlines stay progress-aware across slices (`DelegatedSyncDeadline`): past the deadline the client keeps re-entering while a slice advanced the managed cursor within one progress window, and each slice gets at least one window; `--timeout` and `--hard-deadline` stay strict. Legacy shared-secret sync refuses managed brains. `test/persistence-sync-stdio-owner.serial.test.ts` starts a real stdio owner and exercises CLI import/read/admin, remote-lane denial and revocation without a competing datastore open.- `src/core/facts/backstop.ts` + `src/core/entities/resolve-on-save.ts` — saved facts retain their content and provenance but use a NULL entity target when resolution falls back to slugification. Legacy extraction uses the shared exact source/entity/visibility fingerprint decision before identity-gated cosine candidates, so old facts without vector provenance still deduplicate identical text without relabeling their vectors. The conversation save caller also clears the target on ordinary resolution errors, preserves diagnostic counters, and propagates abort/budget failures. It never treats an invented slug as a verified page. #5836: `src/core/facts/subject-infer-write.ts` `inferMissingSubjects` links facts with no or fallback-only entity via `inferFactSubject` (remote callers: written page only, readable pages, caller fences, managed grant), never on the unmanaged DB-only branch, marks `entity_inferred` (context note; exact-text dedup only in both writers); `test/facts-backstop-entity-inference.test.ts`, `test/managed-facts-entity-inference.test.ts`.- `src/commands/migrations/v0_32_2.ts` — fences live legacy facts only onto an existing source-scoped page and its recorded canonical file. Missing pages/files are counted as `skipped_no_page`, never materialized as stubs. Dirty-tree checks stay inside the source subdirectory; fence row allocation respects both database-owned row numbers and the parsed fence, preserving idempotent recovery without collisions. Dry runs use the same eligibility checks, and historical drift remains visible rather than silently repaired.diff --git a/docs/architecture/topologies.md b/docs/architecture/topologies.mdindex 3a8bbe0c4b..eba5c427e3 100644--- a/docs/architecture/topologies.md+++ b/docs/architecture/topologies.md@@ -519,7 +519,8 @@ gbrain sources writer activate --brain host --confirm-quiesced \```After activation, managed sync requires `--no-pull` (new upstream commits come in-through `gbrain sources refresh <source>`, the drained worktree-wide fast-forward;+through `gbrain sources refresh <source>`, the drained worktree-wide fast-forward,+which runs inside a resident PGLite owner such as `gbrain serve` when one holds the brain;see [worktree refresh refusals](../guides/write-refusals.md#worktree-refresh-refusals)) and refuses `--skip-failed` and`--include-gitignored`; after fixing a failed item run`gbrain sync --no-pull --retry-failed` with the same source and options. Resumediff --git a/src/cli.ts b/src/cli.tsindex fe6c148187..4afadc9070 100755--- a/src/cli.ts+++ b/src/cli.ts@@ -2444,6 +2444,8 @@ async function prepareConnectedDispatch(command: string, args: string[]): Promis}}+ if (command === 'sources' && args[0] === 'refresh' && !hasHelpFlag(args)+ && await (await import('./commands/sources-refresh-delegate.ts')).maybeDelegateSourcesRefresh(loadConfig(), args.slice(1))) return null;if (command === 'reindex-code') {if (await (await import('./commands/reindex-code-delegate.ts')).maybeDelegateReindexCode(loadConfig(), args)) return null;}diff --git a/src/commands/sources-refresh-delegate.ts b/src/commands/sources-refresh-delegate.tsnew file mode 100644index 0000000000..5b542bbf2d--- /dev/null+++ b/src/commands/sources-refresh-delegate.ts@@ -0,0 +1,39 @@+import type { GBrainConfig } from '../core/config.ts';+import { loadMounts } from '../core/brain-registry.ts';+import { resolveBrainId } from '../core/brain-resolver.ts';+import { getCliOptions } from '../core/cli-options.ts';+import { maybeDelegateLocalAdministration, persistenceConfigForBrain } from '../core/persistence/local-client.ts';+import { inspectLockHolder } from '../core/pglite-lock.ts';+import { OperationError } from '../core/ops/contract.ts';+import type { WorktreeRefreshResult } from '../core/persistence/worktree-refresh.ts';+import { reportPersistenceCliError } from './persistence-delegate.ts';+import { parseRefreshArgs, printRefreshOutcome } from './sources-refresh.ts';++/**+ * A live PGLite owner (`gbrain serve`) holds the database and its writer+ * lock; `gbrain sources refresh` runs inside that owner over the local+ * persistence socket instead of waiting on or failing at the lock. Output and+ * refusals print exactly as a local refresh's do.+ */+export async function maybeDelegateSourcesRefresh(hostConfig: GBrainConfig | null, args: string[]): Promise<boolean> {+ const brainId = resolveBrainId(getCliOptions().brain, process.cwd());+ const config = persistenceConfigForBrain(hostConfig, brainId, brainId === 'host' ? [] : loadMounts());+ if (config?.engine !== 'pglite' || !config.database_path || config.database_url || !inspectLockHolder(config.database_path).held) return false;+ const json = args.includes('--json');+ try {+ const { sourceId, options } = parseRefreshArgs(args);+ const delegated = await maybeDelegateLocalAdministration('writer_refresh', {+ source_id: sourceId, dry_run: options.dryRun === true, resume: options.resume === true, abandon: options.abandon === true,+ ...(options.waitDrainMs !== undefined ? { wait_drain_ms: options.waitDrainMs } : {}),+ ...(options.fetchTimeoutMs !== undefined ? { fetch_timeout_ms: options.fetchTimeoutMs } : {}),+ }, config, { timeoutMs: 86_400_000 });+ if (!delegated.handled) throw new OperationError('owner_unavailable', 'The registered PGLite owner stopped before the refresh started.',+ 'Run the same gbrain sources refresh command again; nothing was fetched or merged.');+ printRefreshOutcome({ result: delegated.result as WorktreeRefreshResult }, json);+ return true;+ } catch (error) {+ if (error instanceof OperationError) { printRefreshOutcome({ error }, json); return true; }+ if (await reportPersistenceCliError(error, json)) return true;+ throw error;+ }+}diff --git a/src/commands/sources-refresh.ts b/src/commands/sources-refresh.tsindex 3d708d79af..bbacf3803d 100644--- a/src/commands/sources-refresh.ts+++ b/src/commands/sources-refresh.ts@@ -61,22 +61,31 @@ function describe(result: WorktreeRefreshResult): string {return lines.join('\n');}+/** Print a refresh result, or a refusal with its filled fix; both go to stdout (one JSON object with --json). */+export function printRefreshOutcome(outcome: { result: WorktreeRefreshResult } | { error: OperationError }, json: boolean): void {+ if ('result' in outcome) {+ console.log(json ? JSON.stringify(outcome.result) : describe(outcome.result));+ if (['sync_blocked', 'syncing'].includes(outcome.result.status)) setCliExitVerdict(1);+ return;+ }+ const error = outcome.error;+ // F0's legacy refusal keys stay (its `fix` is the stored command string); the v1 envelope keys ride beside them (D1).+ const env = toAgentError(error, { transport: 'cli', command: 'sources refresh', render: cliRenderContext() });+ const refusal = { status: 'refused', code: error.code, cause: error.message, fix: error.suggestion ?? null, docs: error.docs ?? null,+ ...(error.detail ? { detail: error.detail } : {}),+ error: env.error, message: env.message, suggestion: env.suggestion, docs_cmd: env.docs_cmd, class: env.class, retryable: env.retryable,+ contract_version: env.contract_version };+ console.log(json ? JSON.stringify(refusal) : `Refresh refused (${error.code}): ${error.message}\nFix: ${error.suggestion ?? USAGE}${error.docs ? `\nDocs: ${error.docs}` : ''}`);+ setCliExitVerdict(1);+}+export async function runSourcesRefresh(engine: BrainEngine, args: string[]): Promise<void> {const json = args.includes('--json');try {const parsed = parseRefreshArgs(args);- const result = await refreshWorktree(engine, parsed.sourceId, parsed.options);- console.log(json ? JSON.stringify(result) : describe(result));- if (['sync_blocked', 'syncing'].includes(result.status)) setCliExitVerdict(1);+ printRefreshOutcome({ result: await refreshWorktree(engine, parsed.sourceId, parsed.options) }, json);} catch (error) {if (!(error instanceof OperationError)) throw error;- // F0's legacy refusal keys stay (its `fix` is the stored command string); the v1 envelope keys ride beside them (D1).- const env = toAgentError(error, { transport: 'cli', command: 'sources refresh', render: cliRenderContext() });- const refusal = { status: 'refused', code: error.code, cause: error.message, fix: error.suggestion ?? null, docs: error.docs ?? null,- ...(error.detail ? { detail: error.detail } : {}),- error: env.error, message: env.message, suggestion: env.suggestion, docs_cmd: env.docs_cmd, class: env.class, retryable: env.retryable,- contract_version: env.contract_version };- console.log(json ? JSON.stringify(refusal) : `Refresh refused (${error.code}): ${error.message}\nFix: ${error.suggestion ?? USAGE}${error.docs ? `\nDocs: ${error.docs}` : ''}`);- setCliExitVerdict(1);+ printRefreshOutcome({ error }, json);}}diff --git a/src/core/persistence/admin-contract.ts b/src/core/persistence/admin-contract.tsindex e9dbcd9d25..d151f647a5 100644--- a/src/core/persistence/admin-contract.ts+++ b/src/core/persistence/admin-contract.ts@@ -2,7 +2,7 @@/** Reserved brain-level config key set only by `gbrain sources writer lock|unlock`; generic config writes refuse it. */export const WRITER_ADMIN_LOCK_KEY = 'persistence.writer_admin_lock';export const PERSISTENCE_ADMIN_OPERATIONS = [- 'writer_status', 'writer_sync', 'writer_extract_stale', 'writer_reindex_code', 'writer_retry_effects', 'writer_embed_facts', 'writer_claim', 'writer_activate', 'writer_transfer_prepare', 'writer_transfer_accept',+ 'writer_status', 'writer_sync', 'writer_refresh', 'writer_extract_stale', 'writer_reindex_code', 'writer_retry_effects', 'writer_embed_facts', 'writer_claim', 'writer_activate', 'writer_transfer_prepare', 'writer_transfer_accept','writer_deactivate', 'writer_lock', 'writer_unlock','local_writer_list', 'local_writer_register', 'local_writer_revoke','source_lifecycle', 'source_add', 'company_brain_preview', 'company_brain_connect', 'company_brain_resume',diff --git a/src/core/persistence/administration.ts b/src/core/persistence/administration.tsindex d8ccac259c..5147e40519 100644--- a/src/core/persistence/administration.ts+++ b/src/core/persistence/administration.ts@@ -100,6 +100,21 @@ export async function runPersistenceAdministration(engine: BrainEngine, operatio// Early refusal before any native lock or preview; the checks inside each transaction stay authoritative.if (['writer_claim', 'writer_activate', 'writer_transfer_prepare', 'writer_transfer_accept'].includes(operation)) await assertWriterAdminUnlocked(engine);if (operation === 'writer_sync') return (await import('./sync-administration.ts')).runAuthenticatedSyncSlice(engine, params);+ if (operation === 'writer_refresh') {+ keys(params, ['source_id', 'dry_run', 'resume', 'abandon', 'wait_drain_ms', 'fetch_timeout_ms']);+ const writer = currentVerifiedLocalWriter();+ if (!writer || writer.remote || writer.principal.kind !== 'local_cli') throw trustedCliRequired('Worktree refresh requires a trusted CLI registration.');+ const ms = (value: unknown, name: string) => {+ if (value === undefined) return undefined;+ if (typeof value !== 'number' || !Number.isFinite(value) || value < 0) throw invalid(`${name} must be a non-negative number of milliseconds.`);+ return value;+ };+ const waitDrainMs = ms(params.wait_drain_ms, 'wait_drain_ms');+ const fetchTimeoutMs = ms(params.fetch_timeout_ms, 'fetch_timeout_ms');+ return { ...await (await import('./worktree-refresh.ts')).refreshWorktree(engine, source(params.source_id), {+ dryRun: params.dry_run === true, resume: params.resume === true, abandon: params.abandon === true,+ ...(waitDrainMs !== undefined ? { waitDrainMs } : {}), ...(fetchTimeoutMs !== undefined ? { fetchTimeoutMs } : {}) }) };+ }if (operation === 'writer_extract_stale') {keys(params, ['source_id', 'dry_run']);const writer = currentVerifiedLocalWriter();diff --git a/test/persistence-sync-stdio-owner.serial.test.ts b/test/persistence-sync-stdio-owner.serial.test.tsindex 02ed13ac0c..7143405ed6 100644--- a/test/persistence-sync-stdio-owner.serial.test.ts+++ b/test/persistence-sync-stdio-owner.serial.test.ts@@ -187,6 +187,25 @@ test('a delegated sync past its progress-aware deadline keeps going while the owexpect(JSON.parse(page.out).compiled_truth).toContain('Bulk delegated observation 299');},180000);+// gbrain sources refresh needs the writer lock the resident owner holds; it runs inside the owner over the persistence socket.+test('sources refresh delegates to the resident owner, fast-forwards the checkout and syncs the new page',async()=>{+ const remote=join(home,'origin.git'),pusher=join(home,'pusher');+ const g=(cwd:string,...args:string[])=>execFileSync('git',['-C',cwd,'-c','user.name=Example','-c','[email protected]',...args],{stdio:'pipe'}).toString().trim();+ execFileSync('git',['init','-q','--bare',remote]);+ const branch=g(root,'rev-parse','--abbrev-ref','HEAD');+ g(root,'remote','add','origin',remote);g(root,'push','-q','-u','origin',branch);+ execFileSync('git',['clone','-q',remote,pusher],{stdio:'ignore'});+ writeFileSync(join(pusher,'upstream-note.md'),'A zebracorn observation pushed upstream for the resident owner.\n');+ g(pusher,'add','.');g(pusher,'commit','-qm','upstream note');g(pusher,'push','-q','origin',`HEAD:${branch}`);+ const target=g(pusher,'rev-parse','HEAD');+ const refreshed=await cli(['sources','refresh','workspace','--json'],home,{},120000);+ expect({code:refreshed.code,err:refreshed.err.slice(-2000)}).toMatchObject({code:0});+ expect(JSON.parse(refreshed.out)).toMatchObject({status:'completed',target_head:target});+ expect(inspectLockHolder(databasePath).pid).toBe(owner!.pid);+ const page=await cli(['call','get_page',JSON.stringify({slug:'upstream-note',source_id:'workspace'})]);+ expect(JSON.parse(page.out).compiled_truth).toContain('zebracorn');+},150000);+test('strict sync parsing retains filtering options and rejects runtime authority fields',async()=>{await withEnv(env,async()=>{expect((await parsePersistenceSyncArgs(['--source','workspace','--no-pull','--working-tree','--exclude','draft/**','--include-hidden','.notes/**','--no-hard-deadline'],home)).options)