Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(sync): no reader resolves a relative stored root against the cwd (#7630)
garrytan3d65f2adeaa7
diff --git a/docs/guides/troubleshooting.md b/docs/guides/troubleshooting.mdindex f246cb8dc3..500a51df08 100644--- a/docs/guides/troubleshooting.md+++ b/docs/guides/troubleshooting.md@@ -834,8 +834,8 @@ gbrain runs from, so it cannot say which folder is the brain. Before #7630, afolder treated that folder as the brain repo: it ran `git init`, committedeverything in it and imported its markdown. Sync now refuses`sync_anchor_relative` (exit 3) before any Git probe, cost estimate or import,-and nothing is changed. Doctor's `default_source_local_path` check warns on a-relative `default` path.+and nothing is changed. Doctor's `default_source_local_path` check warns on+every source with a relative path.Ask the user which directory holds the source, then do one of:@@ -847,14 +847,21 @@ Ask the user which directory holds the source, then do one of:is set again. On a managed brain, a source with a canonical owner refuses`--clear` (`writer_transfer_required`); point it at its directory instead.-Until the path is absolute, nothing else treats the folder gbrain runs from as-the source either: page write-through skips the file (`repo_not_found`), the-dream and autopilot cycles run only their database phases, `gbrain autopilot+Until the path is absolute, the main readers do not treat the folder gbrain+runs from as the source either: page and fact writes skip the file and stay in+the database (`repo_not_found`, `no_repo_configured`), a captured file keeps+no origin path, matching a folder to its source ignores the path, fence repair+edits stored pages, managed activation refuses it (`source_changed`, detail+`source_path_missing`), the dream, autopilot, per-phase and global+maintenance cycles run only their database phases, `gbrain autopilot--install` asks for `--repo`, a remote `submit_job` for the source is-refused, import does not count the folder as a configured root, and a managed-brain does not record it as a managed root.+refused, import does not count the folder as a configured root or stamp it+fresh, and a managed brain does not record it as a managed root. A few other+local commands may still read it from the folder they run in, so set the path+first.For `sync.repo_path`: `gbrain config set sync.repo_path <absolute-directory>`.+`config set` refuses a relative value and writes nothing.If an earlier sync already initialized and imported the wrong folder, the userdecides what to undo: the folder's new `.git` directory and the pages importeddiff --git a/llms-full.txt b/llms-full.txtindex 9fadd800c5..632a34452b 100644--- a/llms-full.txt+++ b/llms-full.txt@@ -10991,8 +10991,8 @@ gbrain runs from, so it cannot say which folder is the brain. Before #7630, afolder treated that folder as the brain repo: it ran `git init`, committedeverything in it and imported its markdown. Sync now refuses`sync_anchor_relative` (exit 3) before any Git probe, cost estimate or import,-and nothing is changed. Doctor's `default_source_local_path` check warns on a-relative `default` path.+and nothing is changed. Doctor's `default_source_local_path` check warns on+every source with a relative path.Ask the user which directory holds the source, then do one of:@@ -11004,14 +11004,21 @@ Ask the user which directory holds the source, then do one of:is set again. On a managed brain, a source with a canonical owner refuses`--clear` (`writer_transfer_required`); point it at its directory instead.-Until the path is absolute, nothing else treats the folder gbrain runs from as-the source either: page write-through skips the file (`repo_not_found`), the-dream and autopilot cycles run only their database phases, `gbrain autopilot+Until the path is absolute, the main readers do not treat the folder gbrain+runs from as the source either: page and fact writes skip the file and stay in+the database (`repo_not_found`, `no_repo_configured`), a captured file keeps+no origin path, matching a folder to its source ignores the path, fence repair+edits stored pages, managed activation refuses it (`source_changed`, detail+`source_path_missing`), the dream, autopilot, per-phase and global+maintenance cycles run only their database phases, `gbrain autopilot--install` asks for `--repo`, a remote `submit_job` for the source is-refused, import does not count the folder as a configured root, and a managed-brain does not record it as a managed root.+refused, import does not count the folder as a configured root or stamp it+fresh, and a managed brain does not record it as a managed root. A few other+local commands may still read it from the folder they run in, so set the path+first.For `sync.repo_path`: `gbrain config set sync.repo_path <absolute-directory>`.+`config set` refuses a relative value and writes nothing.If an earlier sync already initialized and imported the wrong folder, the userdecides what to undo: the folder's new `.git` directory and the pages importeddiff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex 912814213b..1b3cbee985 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -45,6 +45,6 @@ src/core/search/mode.ts 1704 ratchet +53 W3 confidence-gated reranking: rerankersrc/commands/eval-longmemeval.ts 1544 ratchet new row: crossed the 1500 unlisted cap in fw3-search (#5092 benchmark-brain recycling: configureBrain split + recycler wiring + test seams; the recycler itself lives in src/eval/longmemeval/harness.ts); +1 P6: tokenmax synopsis-tier wiring (logic in eval/longmemeval/synopsis-tier.ts); +13 GBRA-81 lane A: --via-operation query|search (flags, per-call expansion pin, the run's expectExpansion, the op branch in runOneQuestion, row field, via_operation_summary and its FAIL line; logic in eval/longmemeval/via-operation.ts); +12 --call-plan FILE / --call-plan-gate CMD: two LME_FLAGS entries (CLI help lines), two ParsedArgs fields, the parseArgs pairing check and the header invariant (planner lives in eval/longmemeval/call-plan.ts; runEvalLongMemEval is one line shorter)src/commands/doctor/checks/extraction-sync.ts 1500 ratchet +7 GBRA-130 A-1: links_extraction_lag held bucket and its retry fix (logic in core/extraction-lag.ts heldExtractionReport); +1 undeclared_db_only_pages computes the source Git scope once per source (logic in core/markdown.ts sourceGitScope); new row: crossed the 1500 unlisted cap at the fix wave 9 merge: +7 lane W #5028 (extract_atoms freshness judged by the phase itself) and +3 lane F #5863 (extract_health dates a high halt rate by its last halt), each under the cap alone; +7 #5019: content_hash_duplicates fix pins the pairs' source (GBRAIN_SOURCE) and names a delete that runs; +1 fix wave 10 lane L1 #5556: links_extraction_lag denominator excludes quarantined pages (quarantineFilterFragment import); +11 fix wave 15 P2.8 (#5495): extract_health reads the 7-day halt reasons per kind (halt_reasons, top_halt_reason in details and the top reason in the warn line); the read, the unknown bucket and the ranking live in core/extract/rollup-writer.ts; +20 wave 18b lane 1: links_extraction_lag names the columns its pre-migration degrade reads (#6599 strict predicate), sync_freshness separates sync outcome from freshness for a source with no successful sync (#4960; verdict text, fixes and the attempt read live in doctor/sync-outcome.ts and core/sync-attempt.ts) and exempts read-only skill-pack catalogs (#6076; core/shared-skills/adopted-packs.ts); -51 #6803 (D1): links_extraction_lag reads its counts and verdict from core/extraction-lag.ts (shared with the sync nudge); +1 #7145: content_hash_duplicates reads one group past its list to report a floor ("at least 50")src/core/search/evidence-delivery.ts 1733 ratchet +5 W5: EvidencePlan.rankCut resolved with the plan (logic in search/page-rank-cut.ts); +20 W5 whole_pages: wholeCost prices a block as delivery would emit it whole (needs the private Block/enrichBlock internals) and the cut is wired before allocate (cutWholePages lives in search/page-rank-cut.ts); new row: crossed the 1500 unlisted cap at the #6367 merge (master 1479, its explicit-budget cap) by the C1 date header threaded through every block path, cap included; pagePlanHits (search/page-plan-hits.ts) and the header loader (evidence-date.ts blockDateHeaders) were peeled first; peel candidate: allocateCapped; +8 at the #6396 merge: page evidence text cut through the fence-chunk trust overlay and the caller minTrust floor (re-summed: our 1504 + master +8); +119 Cat 40 next wave F2: the search.long_page_unit policy (withLongPagePolicy, selectLongPages size preflight with page/byte/deadline limits) and the long-page fetch and fallback in deliverEvidence, kept in the shared seam the plan names (gbrain-evals docs/plans/2026-10-11-cat40-next-wave, F2); +17 F2 rework to the frozen-comparison policy: search.long_page_min_chars (rendered-body characters, default 20,000) read in withLongPagePolicy, a character count in the preflight, the rendered-body confirmation in deliverEvidence, and the long-page row exemption in capDeliveredSnippets (re-summed at the 0.60.225.0 merge: master 1537 + F2 136); +39 Wave B PR 2 lane 2b: planSegmentedBlock joins the windows search/segmented-evidence.ts reads around a segmented page's hits into one run-marked document (needs the private Doc/Piece/buildDoc/locateAnchor internals), planBlock's unit cut split into blockFromDoc for both, sections bounded by their run, selectionCost counts a gap between runs, and the fetch skips the whole-body fence overlay for a segmented page; +4 segmented pages read at once before planning (segmentedReads; the read is search/segmented-evidence.ts, the statements page-body/read-range.ts); +17 GBRA-156: tail trim plan flag, DeliverOptions.query, DeliveryMeta.tail_trim, the trim call and the frozen-hit score/query library fields (logic in search/evidence-tail-trim.ts; interface fields cannot move)-src/commands/config.ts 1523 ratchet new row: crossed the 1500 unlisted cap in wave 15 P7.4 #5461: set-time validation of think.pages_budget_chars / think.excerpt_ceiling_chars (range + parser live in core/think/pages-budget.ts), mirroring the cycle.consolidate.cluster_threshold hook; +1 wave 16 G5.1 (#6495): set-time refusal hook for search.keyword_statement_timeout_ms (check lives in commands/config/keyword-timeout-value.ts); +1 wave 18b lane 5 (#5012 item 6): search.contextual_retrieval prints the existing-pages hint after the write (text lives in commands/config/contextual-mode-hint.ts); +1 #6712 PR 2: retired/rollback sync key dispatch line (logic in core/sync-config-keys.ts handleSyncKeyConfig); +1 #6865: sync.slug_conflicts.auto_remove boolean validation at set time (refusal text in repair/slug-autoheal.ts); +1 #6948: sync.origin_twins.auto_resolve boolean validation at set time (refusal text in repair/origin-twins-heal.ts); +2 #6795: config set chat_model/expansion_model help line and the model-pin import (shadow report and file-pin unset live in commands/config/model-pin-shadow.ts); +1 #6712 PR 4b: sync.admission set-time hook (value logic in commands/config/sync-admission-value.ts); +4 #7130: set-time refusal hook for sync.max_deletes / sync.max_delete_ratio (and .source.<id>) / purge.retention_hours (check lives in core/sync-reconcile.ts deleteSafetyConfigRefusal); +1 GBRA-150: sync.metafile_pages set-time route (body in config/sync-metafile-pages-value.ts); re-summed at the v0.60.330.0 merge (1520 measured); +2 #7242 minions.terminal_hook file-plane key and its set branch (logic in minions/terminal-hook.ts); +1 GBRA-161: generations.* set-time route (refusal in commands/config/generations-values.ts)+src/commands/config.ts 1525 ratchet new row: crossed the 1500 unlisted cap in wave 15 P7.4 #5461: set-time validation of think.pages_budget_chars / think.excerpt_ceiling_chars (range + parser live in core/think/pages-budget.ts), mirroring the cycle.consolidate.cluster_threshold hook; +1 wave 16 G5.1 (#6495): set-time refusal hook for search.keyword_statement_timeout_ms (check lives in commands/config/keyword-timeout-value.ts); +1 wave 18b lane 5 (#5012 item 6): search.contextual_retrieval prints the existing-pages hint after the write (text lives in commands/config/contextual-mode-hint.ts); +1 #6712 PR 2: retired/rollback sync key dispatch line (logic in core/sync-config-keys.ts handleSyncKeyConfig); +1 #6865: sync.slug_conflicts.auto_remove boolean validation at set time (refusal text in repair/slug-autoheal.ts); +1 #6948: sync.origin_twins.auto_resolve boolean validation at set time (refusal text in repair/origin-twins-heal.ts); +2 #6795: config set chat_model/expansion_model help line and the model-pin import (shadow report and file-pin unset live in commands/config/model-pin-shadow.ts); +1 #6712 PR 4b: sync.admission set-time hook (value logic in commands/config/sync-admission-value.ts); +4 #7130: set-time refusal hook for sync.max_deletes / sync.max_delete_ratio (and .source.<id>) / purge.retention_hours (check lives in core/sync-reconcile.ts deleteSafetyConfigRefusal); +1 GBRA-150: sync.metafile_pages set-time route (body in config/sync-metafile-pages-value.ts); re-summed at the v0.60.330.0 merge (1520 measured); +2 #7242 minions.terminal_hook file-plane key and its set branch (logic in minions/terminal-hook.ts); +1 GBRA-161: generations.* set-time route (refusal in commands/config/generations-values.ts); +2 GBRA-207 #7630: sync.repo_path set-time refusal hook (refusal in core/sync-config-keys.ts syncRepoPathRefusal)src/commands/mcp-expose.ts 1512 ratchet hosted_option: Session carries the gbrain.io coaching notice on the first-receipt run and Tailscale/service friction exits (copy, refs and gating live in core/onboard/hosted-option.ts)src/core/behavior-change-notice.ts 1508 ratchet the BEHAVIOR_CHANGES table grows by one row per disclosed change: the GBRA-95 RLS backfill row (+2), +3 rows for #7596 pass_interrupted, #7599 read-only serve and the --access=read-only ceiling, and +3 GBRA-207 #7630 relative-anchor and stalled-write rows; the behavior-change table split (#7607) retires this rowdiff --git a/src/commands/autopilot-dispatch.ts b/src/commands/autopilot-dispatch.tsindex 4068db97b7..18a5cf812c 100644--- a/src/commands/autopilot-dispatch.ts+++ b/src/commands/autopilot-dispatch.ts@@ -406,8 +406,8 @@ export async function dispatchFreshnessSyncs(if (skip?.reason !== 'sync_disabled') reportAutomaticSyncSkip(src.id, skip, 'freshness_sync_skipped', jsonMode, (l) => process.stderr.write(l + '\n'));if (skip) decisions.push({ source_id: src.id, outcome: 'skipped' });if (skip) continue;- // A local_path this machine cannot use — relative (#3696: cwd is- // launchd's, not the registering shell's) or absent on disk and+ // A local_path this machine cannot use — relative (#3696, #7630: it+ // names whatever directory the daemon runs from) or absent on disk and// not a managed clone sync can re-create — would sync a phantom// path. Skip loudly (sourceLocalPathSkipWarning carries the// fix); under --json the skip is an NDJSON event like everydiff --git a/src/commands/autopilot.ts b/src/commands/autopilot.tsindex 75279b7ce9..d738610f3b 100644--- a/src/commands/autopilot.ts+++ b/src/commands/autopilot.ts@@ -861,9 +861,9 @@ export function writeWrapperScript(repoPath: string, target: InstallTarget, job:# or which init file the OS loaded.export PATH=${runtimePathPrefix}"$HOME/.bun/bin:$PATH"${process.env.GBRAIN_HOME ? `# Baked at install: the supervisor does not pass the installer's env, and\n# without this the daemon would read/write a different home than the\n# install that configured it.\nexport GBRAIN_HOME='${(process.env.GBRAIN_HOME).replace(/'/g, "'\\''")}'\n` : ''}-${generateSelfDisableGuard(repoPath, target, job)}# #3696: daemon cwd = the repo, so any legacy RELATIVE sources.local_path /-# sync.repo_path row resolves against it instead of a phantom path under the-# supervisor's cwd. Done HERE — after the guard has proven the repo exists —+${generateSelfDisableGuard(repoPath, target, job)}# #3696: daemon cwd = the repo. A legacy RELATIVE sources.local_path /+# sync.repo_path row is still never resolved against it (#7630: sync refuses+# it and the other daemon readers skip it). Done HERE — after the guard has proven the repo exists —# and NOT via launchd's plist WorkingDirectory: launchd chdir()s before exec,# so a deleted repo would fail every respawn and the self-disable guard above# could never run. Fail-open (|| true): a repo deleted between the guard and@@ -1006,9 +1006,9 @@ export function pgliteDaemonGuardMessage(engineKind: string, force: boolean): st// self-disable guard — would never run again, leaving a zombie KeepAlive// job that can never take itself out of rotation. $HOME exists for the// job's whole lifetime; the WRAPPER cd's into the repo AFTER the guard has-// proven it exists (writeWrapperScript), which is what makes legacy-// RELATIVE sources.local_path / sync.repo_path rows resolve against the-// repo instead of a phantom path.+// proven it exists (writeWrapperScript). Legacy RELATIVE+// sources.local_path / sync.repo_path rows are refused or skipped, never+// resolved against that cwd (#7630).export function generateLaunchdPlist(wrapperPath: string, home: string, job?: AutopilotJob): string {const logPath = job?.logPath ?? `${home}/.gbrain/autopilot.log`;const errPath = job?.errPath ?? `${home}/.gbrain/autopilot.err`;diff --git a/src/commands/config.ts b/src/commands/config.tsindex 7ea6b9cfa8..c1feb37821 100644--- a/src/commands/config.ts+++ b/src/commands/config.ts@@ -993,6 +993,8 @@ export async function runConfig(engine: BrainEngine, args: string[]) {process.exit(1);}const value = tail.find(a => !a.startsWith('-')) ?? args[2];+ const repoPathRefusal = key === 'sync.repo_path' ? (await import('../core/sync-config-keys.ts')).syncRepoPathRefusal(value) : null;+ if (repoPathRefusal) { console.error(repoPathRefusal); process.exit(1); }// Bootstrap hook-lane keys are FILE-plane canonical: they are read by// engine-free processes (the harness hook children and the detacheddiff --git a/src/commands/doctor/checks/default-source-path.ts b/src/commands/doctor/checks/default-source-path.tsindex a1226474a6..f85bc27544 100644--- a/src/commands/doctor/checks/default-source-path.ts+++ b/src/commands/doctor/checks/default-source-path.ts@@ -7,12 +7,14 @@* A null `default.local_path` is the DESIGNED fallback topology (pages nest* under sync.repo_path), so the check only warns when the fallback* demonstrably fails — see the helper's doc comment for the exact gates.+ * #7630: it also warns for every other source whose local_path is relative.** Lives in the doctor module dir per the peeled-façade rule — new code goes* here, not back into doctor.ts. Returns null for the 'skip' verdict so the* caller pushes nothing.*/import { existsSync, statSync } from 'fs';+import { isAbsolute } from 'path';import type { BrainEngine } from '../../../core/engine.ts';import type { Check } from '../../doctor.ts';import { assessDefaultSourcePath } from '../../../core/default-source-path-check.ts';@@ -71,10 +73,18 @@ export async function defaultSourceLocalPathCheck(engine: BrainEngine): Promise<collidingSourceId,sharedPages,});- if (assessment.status === 'skip') return null;+ // #7630: any other source with a relative local_path is refused by sync the same way, so name it here too.+ const relative = (await engine.executeRaw<{ id: string; local_path: string }>(+ `SELECT id, local_path FROM sources WHERE id <> 'default' AND local_path IS NOT NULL AND archived IS NOT TRUE ORDER BY id`,+ )).filter(row => !isAbsolute(row.local_path));+ if (assessment.status === 'skip' && relative.length === 0) return null;+ const relativeNote = relative.length === 0 ? '' :+ `${relative.map(row => `source "${row.id}" has the relative local_path "${row.local_path}"`).join('; ')}, which names whatever directory ` ++ 'gbrain runs from, so sync refuses it (sync_anchor_relative). Ask the user which directory holds its files, then run ' ++ '`gbrain sources set-path <id> <absolute-directory>`, or clear the pointer with `gbrain sources set-path <id> --clear`.';return {name: 'default_source_local_path',- status: assessment.status,- message: assessment.message,+ status: relative.length > 0 || assessment.status === 'skip' ? 'warn' : assessment.status,+ message: [assessment.message, relativeNote].filter(Boolean).join(' '),};}diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex cd95a64387..6f78159b62 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -1303,7 +1303,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;{ since: '0.60.460.0', text: '`gbrain repair duplicate-facts` keeps the copy that is a row of a page\'s `## Facts` table over an older database-only copy of the same fact, so the legacy copy is superseded onto the fence row instead of holding it (which left the legacy row unfenced and its page out of fact reconciliation). With no fenced copy it still keeps the oldest row. It stays preview-first and explicit.' },{ since: '0.60.460.0', text: 'Dream consolidation on a managed brain now closes a fenced fact in its page: the closing `valid_until` is written into the fact\'s row in the entity page\'s `## Facts` fence, published with the take, and the database row takes its value from that cell, so a later sync or re-import keeps the fact closed. Before, only the database row was closed and the next re-import of the page reopened it. A fact with no fence row is still closed in the database. A fenced fact whose fence row is on another page is left open. Facts an earlier release closed in the database only are not changed (GBRA-190).' },// GBRA-207 (#7630). `since` is stamped at the merge slot.- { since: 'TBD', id: 'sync_refuses_relative_anchor', text: 'A sync whose source directory (`sources.local_path`) or legacy `sync.repo_path` is a relative path such as `.` now refuses `sync_anchor_relative` (exit 3) before any Git probe or import, instead of treating whatever folder it ran from as the brain repo (Git init, a baseline commit of the whole folder, an import of its markdown). `gbrain sources set-path <id> <absolute-directory>` sets the path, `gbrain sources set-path <id> --clear` now also clears a relative path on any source, and doctor\'s `default_source_local_path` warns on a relative default path. Until then nothing else uses the folder gbrain runs from as that source: write-through skips the file, the dream and autopilot cycles run only database phases, `autopilot --install` needs `--repo`, a remote `submit_job` is refused, and a managed brain records no managed root there.' },+ { since: 'TBD', id: 'sync_refuses_relative_anchor', text: 'A sync whose source directory (`sources.local_path`) or legacy `sync.repo_path` is a relative path such as `.` now refuses `sync_anchor_relative` (exit 3) before any Git probe or import, instead of treating whatever folder it ran from as the brain repo (Git init, a baseline commit of the whole folder, an import of its markdown). `gbrain sources set-path <id> <absolute-directory>` sets the path, `gbrain sources set-path <id> --clear` now also clears a relative path on any source, and doctor\'s `default_source_local_path` warns on any source with a relative path, and `gbrain config set sync.repo_path` refuses one. Until the path is set, page and fact writes skip the file (database only), matching a folder to its source ignores it, the dream, autopilot and maintenance cycles run only database phases, fence repair edits stored pages instead of files, managed activation refuses it, `autopilot --install` needs `--repo`, a remote `submit_job` is refused and a managed brain records no managed root there. A few other local commands may still read it from the folder they run in, so set the path before relying on them.' },{ since: 'TBD', text: 'A foreground write (`remember`, `put_page` and the other non-sync operations) that ends with a retryable fault such as `preparation_stalled` now carries a diagnosis that inspects the writer read-only (`gbrain sources writer status --source <id> --json`) and says to resubmit the same write with a new request_id, instead of telling the user to run `gbrain sync`. Recorded sync faults keep their sync retry.' },// GBRA-95 RLS backfill. `since` is stamped at the merge slot.{ since: '0.60.463.0', id: 'rls_backfill_unguarded_tables', text: 'On Postgres, a schema migration now enables row-level security on every gbrain table still without it. A table could be left without RLS because its RLS came only from a full schema replay, which `gbrain apply-migrations --yes` does not run (the four incremental-derivation tables, `page_segment_derivations`, `page_derivation_spend` and the two purge tables), or only from the auto-RLS event trigger, which needs a superuser and is absent on many managed brains. Supabase gives public tables anon and authenticated grants, so with the Data API on such a table was reachable with the anon key. Only a table still without RLS changes; one with a `GBRAIN:RLS_EXEMPT` comment is left alone; no row is read or written. Under a role that does not bypass RLS or does not own a table, the migration names the table on stderr and leaves it, and `gbrain doctor` (rls) keeps naming it with the fix. `gbrain repair missing-tables` now recreates a cache table with RLS on. A role that neither owns a table nor bypasses RLS reads no rows from it and cannot insert or update it once RLS is on (a read-only reporting role or a scoped write role, for example): give that role policies before upgrading (docs/ENGINES.md has the source-scope recipe), or, to keep a table open to it on purpose, add the `GBRAIN:RLS_EXEMPT reason=...` comment to that table. A write role set up with an earlier copy of that recipe also needs its new policies on `page_derivation_spend` and the two purge tables: without them its segmented derivation writes are refused, and the derivation purge triggers its writes fire read no purge, so they do not hold back a purged claim.' },diff --git a/src/core/fence-repair/repair-io.ts b/src/core/fence-repair/repair-io.tsindex 2673b17c4f..cbdfe249f3 100644--- a/src/core/fence-repair/repair-io.ts+++ b/src/core/fence-repair/repair-io.ts@@ -25,7 +25,7 @@* Every write carries the location-only receipt (actor fence-repair).*/import { copyFileSync, existsSync, lstatSync, readFileSync, writeFileSync } from 'node:fs';-import { join } from 'node:path';+import { isAbsolute, join } from 'node:path';import { execFileSync } from '../spawn.ts';import type { BrainEngine } from '../engine.ts';import { OperationError, type OperationContext } from '../ops/contract.ts';@@ -98,7 +98,7 @@ export async function loadFenceSource(engine: BrainEngine, sourceId: string, opt}} else {const local = row.local_path ?? (sourceId === 'default' ? await engine.getConfig('sync.repo_path') : null);- root = local && existsSync(local) ? local : null;+ root = local && isAbsolute(local) && existsSync(local) ? local : null;}const busy: RepairBusySet = managed ? await loadRepairBusySet(engine, sourceId, row.incarnation) : { paths: new Set(), slugs: new Set(), unknown: null };const config = await repairScreenConfig(engine, sourceId);diff --git a/src/core/minions/handlers/autopilot-global-maintenance.ts b/src/core/minions/handlers/autopilot-global-maintenance.tsindex b9fb87e18f..3106b2229b 100644--- a/src/core/minions/handlers/autopilot-global-maintenance.ts+++ b/src/core/minions/handlers/autopilot-global-maintenance.ts@@ -1,6 +1,7 @@/*** `autopilot-global-maintenance` Minion job handler (built-in; registered by registerBuiltinHandlers in src/commands/jobs.ts).*/+import { isAbsolute } from 'node:path';import type { BrainEngine } from '../../engine.ts';import type { MinionHandler } from '../types.ts';import type { CycleReport, PhaseResult } from '../../cycle.ts';@@ -175,9 +176,11 @@ export function makeAutopilotGlobalMaintenanceHandler(engine: BrainEngine, deps:const cycle = await import('../../cycle.ts');const { MAINTENANCE_PHASES, LAST_GLOBAL_AT_KEY } = cycle;const runCycle = deps.runCycle ?? cycle.runCycle;- const repoPath: string | null = typeof job.data.repoPath === 'string'+ // #7630: a relative path names whatever directory the worker runs from, so it is no checkout.+ const configured: string | null = typeof job.data.repoPath === 'string'? job.data.repoPath: (await engine.getConfig('sync.repo_path')) ?? null;+ const repoPath = configured && isAbsolute(configured) ? configured : null;// #4250: queued maintenance payloads are machine-authored too — intersect// with MAINTENANCE_PHASES so a stale (or remote-submitted) payload can'tdiff --git a/src/core/minions/handlers/cycle-phase.ts b/src/core/minions/handlers/cycle-phase.tsindex 6e5fe40fb3..6d1b35acbc 100644--- a/src/core/minions/handlers/cycle-phase.ts+++ b/src/core/minions/handlers/cycle-phase.ts@@ -3,6 +3,7 @@* src/commands/jobs.ts for synthesize, patterns, consolidate, extract_facts,* resolve_symbol_edges and recompute_emotional_weight).*/+import { isAbsolute } from 'node:path';import type { BrainEngine } from '../../engine.ts';import type { MinionHandler } from '../types.ts';@@ -20,9 +21,11 @@ export function makeCyclePhaseHandler(engine: BrainEngine, phase: string): Minio// checkout-less postgres brain a filesystem phase (synthesize/patterns/...)// skips with reason 'no_brain_dir' instead of running against the worker cwd;// DB-only phases (resolve_symbol_edges/embed/...) ignore brainDir either way.- const repoPath: string | null = typeof job.data.repoPath === 'string'+ // #7630: a relative path names whatever directory the worker runs from, so it is no checkout either.+ const configured: string | null = typeof job.data.repoPath === 'string'? job.data.repoPath: ((await engine.getConfig('sync.repo_path')) ?? null);+ const repoPath = configured && isAbsolute(configured) ? configured : null;const report = await runCycle(engine, {brainDir: repoPath,phases: [phase as any],diff --git a/src/core/persistence/activation.ts b/src/core/persistence/activation.tsindex 5dc2d01234..eadcb5bf5c 100644--- a/src/core/persistence/activation.ts+++ b/src/core/persistence/activation.ts@@ -1,5 +1,5 @@import { existsSync, realpathSync } from 'node:fs';-import { join, resolve } from 'node:path';+import { isAbsolute, join, resolve } from 'node:path';import type { BrainEngine } from '../engine.ts';import type { Action } from '../agent-output.ts';import { opError, OperationError } from '../ops/contract.ts';@@ -118,7 +118,7 @@ async function configuredSources(engine: BrainEngine, lock = false): Promise<Sou/** #5206: a recorded source directory that vanished is a named blocker with its exits, never a bare ENOENT. */function sourcePathMissing(source: SourceRoot, claimedRoot: string | null): OperationError {const error = catalogueError('activation_source_path_missing',- `Source '${source.id}' records the local path ${source.root}, which does not exist on this host, so activation cannot verify its canonical directory.`,+ `Source '${source.id}' records the ${source.root && !isAbsolute(source.root) ? `relative local path ${source.root}, which names whatever directory gbrain runs from (#7630)` : `local path ${source.root}, which does not exist on this host`}, so activation cannot verify its canonical directory.`,`Point it at its checkout with gbrain sources set-path ${source.id} ${claimedRoot ? JSON.stringify(claimedRoot) : '<directory>'}, or remove it with gbrain sources remove ${source.id} --confirm-destructive; then rerun gbrain sources writer activate --confirm-quiesced --dry-run.`);error.detail = 'source_path_missing';return error;@@ -138,7 +138,7 @@ async function validatedBindings(engine: BrainEngine, sources: SourceRoot[], hosfor (const source of sources) {let binding = await getWorktreeBinding(engine, source.id, hostId);if ((!source.root || source.connector) && !binding) continue;- if (!binding && !source.connector && !existsSync(resolve(source.root!))) throw sourcePathMissing(source, null);+ if (!binding && !source.connector && (!isAbsolute(source.root!) || !existsSync(source.root!))) throw sourcePathMissing(source, null);// #6449: onboarding already reports this source database_only; activation agrees instead of demanding a claim.if (!binding && !writeThrough) { databaseOnly.push(source.id); continue; }if (!binding) throw unboundRootedSource(source);@@ -158,7 +158,7 @@ async function validatedBindings(engine: BrainEngine, sources: SourceRoot[], hos{ fix: writerStatusFix(`Shows source ${source.id}'s owner host and registration, read-only.`, source.id) });}if (binding.owner_host_id === hostId) {- if (source.root && !existsSync(resolve(source.root))) throw sourcePathMissing(source, binding.local_path && join(binding.local_path, binding.relative_path));+ if (source.root && (!isAbsolute(source.root) || !existsSync(source.root))) throw sourcePathMissing(source, binding.local_path && join(binding.local_path, binding.relative_path));if (!binding.local_path || !binding.coordination_path|| source.root && realpathSync(resolve(source.root)) !== realpathSync(join(binding.local_path, binding.relative_path))) {throw opError('source_changed', `Source '${source.id}' no longer matches its registered canonical directory.`,diff --git a/src/core/persistence/fact-write-target.ts b/src/core/persistence/fact-write-target.tsindex 19737b673f..5edf236ea7 100644--- a/src/core/persistence/fact-write-target.ts+++ b/src/core/persistence/fact-write-target.ts@@ -1,3 +1,4 @@+import { isAbsolute } from 'node:path';import type { BrainEngine } from '../engine.ts';import { getWorktreeBinding, type WorktreeBinding } from './ownership.ts';import { decideUnboundWrite } from './unbound-source.ts';@@ -27,7 +28,7 @@ export async function resolveFactWriteTarget(engine: BrainEngine, sourceId: striif (!writeThrough) return { kind: 'publish', binding: null, databaseOnlyReason: reason };const binding = await getWorktreeBinding(engine, sourceId);const root = source.local_path || (sourceId === 'default' ? await engine.getConfig('sync.repo_path') : null);- if (!root || binding) return { kind: 'publish', binding };+ if (!root || !isAbsolute(root) || binding) return { kind: 'publish', binding };const decision = await decideUnboundWrite(engine, { sourceId, sourceKind: source.kind, fileBacked: opts.fileBacked, path: opts.remote ? null : root });return decision.kind === 'claim' ? { kind: 'unbound', root } : { kind: 'publish', binding: null, databaseOnlyReason: decision.reason };}diff --git a/src/core/persistence/page-mutations.ts b/src/core/persistence/page-mutations.tsindex aa17073e6d..9965a6d90c 100644--- a/src/core/persistence/page-mutations.ts+++ b/src/core/persistence/page-mutations.ts@@ -160,8 +160,9 @@ async function resolveCaptureFile(ctx: OperationContext, sourceId: string, p: Redelete p.local_file;const [source] = await ctx.engine.executeRaw<{ local_path: string | null }>('SELECT local_path FROM sources WHERE id=$1', [sourceId]);const binding = await getWorktreeBinding(ctx.engine, sourceId);- const root = binding ? binding.owner_host_id === localHostId() && binding.local_path ? join(binding.local_path, binding.relative_path) : null+ let root = binding ? binding.owner_host_id === localHostId() && binding.local_path ? join(binding.local_path, binding.relative_path) : null: source?.local_path || (sourceId === 'default' ? await ctx.engine.getConfig('sync.repo_path') : null);+ if (root && !isAbsolute(root)) root = null;let origin: string | null = null;try { if (root) origin = relative(realpathSync(root), realpathSync(file)); } catch { /* unreadable or absent root */ }if (!root || !origin || isAbsolute(origin) || origin === '..' || origin.startsWith(`..${sep}`) || !/\.mdx?$/i.test(origin)) {@@ -396,7 +397,8 @@ export async function preparePageAdmission(ctx: OperationContext,const sandbox = ctx.viaSubagent === true && !(ctx.allowedSlugPrefixes?.length);const configuredWriteThrough = !/^(false|0|off|no)$/i.test(writeThroughSetting ?? 'true');const writeThrough = configuredWriteThrough && !sandbox && !input.databaseOnly;- const root = source.local_path || repoPath;+ const configuredRoot = source.local_path || repoPath;+ const root = configuredRoot && isAbsolute(configuredRoot) ? configuredRoot : null;if (sandbox) authority.databaseOnlyReason = 'subagent_sandbox';else if (input.databaseOnly) authority.databaseOnlyReason = input.databaseOnly;else if (!configuredWriteThrough) authority.databaseOnlyReason = 'disabled_by_config';diff --git a/src/core/source-resolver.ts b/src/core/source-resolver.tsindex 5fd264fce9..e7a7235884 100644--- a/src/core/source-resolver.ts+++ b/src/core/source-resolver.ts@@ -15,7 +15,7 @@import { readFileSync, lstatSync, type Stats } from 'fs';import { syncDispatchRow } from './sync-dispatch-read.ts';-import { join, dirname, resolve } from 'path';+import { join, dirname, isAbsolute, resolve } from 'path';import type { BrainEngine } from './engine.ts';import { requestSnapshotRead } from './config-snapshot.ts';import type { ExplicitReadBinding } from './ops/contract.ts';@@ -125,6 +125,7 @@ async function resolveRegisteredPathMatch(registered: RegisteredSource[],cwd: string,): Promise<{ id: string; path: string; pathLen: number } | null> {+ registered = registered.filter(r => isAbsolute(r.local_path));if (registered.length === 0) return null;const [cwdResolved, resolvedPaths] = await Promise.all([realpathOrResolveAsync(cwd),@@ -757,6 +758,7 @@ export async function resolveSourceForRepoPath(const dirResolved = realpathOrResolve(dir);let best: { id: string; path: string; pathLen: number } | null = null;for (const r of registered) {+ if (!isAbsolute(r.local_path)) continue;const p = realpathOrResolve(r.local_path);if (dirResolved === p || dirResolved.startsWith(p + '/')) {if (!best || p.length > best.pathLen) {diff --git a/src/core/sync-applicability.ts b/src/core/sync-applicability.tsindex f884a184fa..3e613c1efc 100644--- a/src/core/sync-applicability.ts+++ b/src/core/sync-applicability.ts@@ -93,7 +93,7 @@ export function syncNotApplicableError(dir: SyncContentDirectory): OperationErro* everything in it, an import of its markdown). Refused before any Git probe, cost estimate or import.*/export function syncAnchorRelativeError(sourceId: string | undefined, anchor: string): OperationError {- const why = `A relative path names whatever directory gbrain runs from (now ${process.cwd()}), not a fixed folder, so it cannot prove which folder is the brain; syncing it from an unrelated folder would Git-initialize that folder, commit everything in it and import its markdown. Nothing was changed.`;+ const why = `A relative path names whatever directory gbrain runs from, not a fixed folder, so it cannot prove which folder is the brain; syncing it from an unrelated folder would Git-initialize that folder, commit everything in it and import its markdown. Nothing was changed.`;if (!sourceId) {return opError('sync_anchor_relative', `Sync refused: sync.repo_path is the relative path "${anchor}".`,'Ask the user which directory holds the brain repo, then set it as an absolute path: gbrain config set sync.repo_path <absolute-directory>.',diff --git a/src/core/sync-config-keys.ts b/src/core/sync-config-keys.tsindex 3fa4ee7e7b..b2b480e983 100644--- a/src/core/sync-config-keys.ts+++ b/src/core/sync-config-keys.ts@@ -10,6 +10,7 @@* `config get` prints the value in effect and where it comes from, and doctor (`sync_config_keys`) reports a value* stored before the upgrade as unapplied.*/+import { isAbsolute } from 'node:path';import { CONFIG_ROLLBACK_WINDOWS, type ConfigRollbackWindow } from './wire-skew.ts';import type { BrainEngine } from './engine.ts';@@ -132,6 +133,12 @@ export function syncKeySetNotice(key: string): { writes: boolean; lines: string[* which writes nothing. A rollback key's `set` returns false so the write goes ahead; any other key returns false.* #6712 PR 4b: `get sync.admission` prints the value in effect (`normal` when unset) and when it was set.*/+/** #7630: the `config set sync.repo_path` refusal for a relative value, or null when it may be stored. */+export function syncRepoPathRefusal(value: string): string | null {+ if (isAbsolute(value)) return null;+ return `[config] sync.repo_path must be an absolute directory (got '${value}'): a relative path names whatever directory gbrain runs from, and sync refuses it (sync_anchor_relative). Nothing was written.`;+}+export async function handleSyncKeyConfig(engine: Pick<BrainEngine, 'getConfig' | 'executeRaw'>, action: 'get' | 'set', key: string): Promise<boolean> {if (action === 'get' && key === 'sync.admission') {const { readSyncAdmissionSetting } = await import('./persistence/sync-admission.ts');diff --git a/test/sync-relative-anchor-refusal-7630.test.ts b/test/sync-relative-anchor-refusal-7630.test.tsindex 3f7c7e0e38..d4e5334f2d 100644--- a/test/sync-relative-anchor-refusal-7630.test.ts+++ b/test/sync-relative-anchor-refusal-7630.test.ts@@ -13,7 +13,10 @@* legacy `sync.repo_path`; the folder gets no `.git` and nothing is imported;* - a relative anchor never proves ownership, so even an explicit absolute path to the cwd is not auto-initialized;* - `gbrain sources set-path <id> --clear` clears a relative filesystem path without SQL, and still refuses an absolute one;- * - doctor's `default_source_local_path` warns on a relative path;+ * - doctor's `default_source_local_path` warns on a relative path, on any source, and `config set sync.repo_path` refuses one;+ * - no other reader resolves a relative root against the cwd: write-through, page and fact writes, capture origins,+ * folder-to-source matching, fence repair, activation, import roots and freshness, remote submit_job, managed roots, and+ * the dream, autopilot, per-phase and global maintenance cycles;* - a stalled foreground write's diagnosis inspects the writer and says to resubmit with a new request_id, while a* recorded sync fault keeps its sync retry.*@@ -105,7 +108,8 @@ for (const backend of testBackends()) {// Value: protects=gbrain sync --all fails only the source with a relative local_path and still syncs an absolute one;// fails_when=the --all fan-out guard aborts the whole run, drops the source, or reports it ok / imports the cwd;// why_new=the performSync cases above never enter runSyncAll's fan-out or its per-source JSON envelope; seam=none;- // no_claim=the cost-gate walk ordering (--no-embed skips the gate) and the exit-3 mapping of a single-source run+ // no_claim=the cost-gate walk ordering (--no-embed skips the gate), the exit-3 mapping of a single-source run, and parallel+ // import workers (--workers 1: a worker opens the configured DATABASE_URL, not this test's isolated Postgres database)test('gbrain sync --all fails only the relative source: an absolute source still syncs and the cwd is untouched', async () => {const repo = realpathSync(mkdtempSync(join(tmpdir(), 'gbrain-7630-repo-')));try {@@ -117,7 +121,7 @@ for (const backend of testBackends()) {const before = await pagesOf('default');const { lines, exit } = await cli(async () => {const { runSync } = await import('../src/commands/sync.ts');- await runSync(engine, ['--all', '--no-pull', '--no-embed', '--json']);+ await runSync(engine, ['--all', '--no-pull', '--no-embed', '--json', '--workers', '1']);});const envelope = JSON.parse(lines.find(line => line.startsWith('{"schema_version"'))!) as { sources: Array<{ source_id: string; status: string; error?: string }>; error_count: number };const bySource = Object.fromEntries(envelope.sources.map(s => [s.source_id, s]));@@ -172,7 +176,8 @@ for (const backend of testBackends()) {// Value: protects=an explicit relative --repo that differs from the stored relative anchor is honored: that directory syncs;// fails_when=the guard starts refusing every relative repoPath instead of only the stored anchor itself;- // why_new=no other case passes a relative repoPath other than the anchor; seam=none; no_claim=none beyond protects+ // why_new=no other case passes a relative repoPath other than the anchor; seam=none; no_claim=parallel import workers+ // (--workers 1: a worker opens the configured DATABASE_URL, not this test's isolated Postgres database)test('gbrain sync --repo brain (relative, not the stored ".") is honored: brain syncs, the cwd stays untouched', async () => {await engine.executeRaw("UPDATE sources SET local_path='.' WHERE id='default'");const brain = join(folder, 'brain');@@ -180,7 +185,7 @@ for (const backend of testBackends()) {execSync('git init -q && git config user.email [email protected] && git config user.name T', { cwd: brain, stdio: 'pipe' });writeFileSync(join(brain, 'inside.md'), '---\ntype: note\ntitle: Inside\n---\n\nA page of the brain.\n');execSync('git add -A && git commit -q -m initial', { cwd: brain, stdio: 'pipe' });- const result = await runSyncCli(['--repo', 'brain', '--no-pull', '--no-embed', '--json']);+ const result = await runSyncCli(['--repo', 'brain', '--no-pull', '--no-embed', '--json', '--workers', '1']);expect(result.refused?.code).toBeUndefined();expect(result.exit).toBeUndefined();const slugs = (await engine.executeRaw<{ slug: string }>("SELECT slug FROM pages WHERE source_id='default' ORDER BY slug")).map(row => row.slug);@@ -315,6 +320,95 @@ for (const backend of testBackends()) {expect(existsSync(join(folder, '.git'))).toBe(false);expect(await pageCount()).toBe(0);}, 120_000);++ // Value: protects=a relative local_path or sync.repo_path never becomes the cwd for folder-to-source matching, fence repair,+ // page and fact write-through (including the automatic claim of an unbound PGLite source), capture origins, activation+ // or the per-phase and global maintenance jobs; fails_when=any of those readers resolves "." against process.cwd();+ // why_new=the reader test above covers write-through, install, cycle, import, submit_job and managed roots only; seam=none;+ // no_claim=readers that only test whether a root is set (atom, facts and prepared maintenance refuse without an owner)+ test('the remaining readers ignore a relative root: source matching, fence repair, page and fact writes, activation, phase and global maintenance', async () => {+ const repo = realpathSync(mkdtempSync(join(tmpdir(), 'gbrain-7630-src-')));+ try {+ mkdirSync(join(repo, 'sub'));+ await engine.executeRaw("UPDATE sources SET local_path='.' WHERE id='default'");+ await engine.executeRaw("INSERT INTO sources (id, name, local_path) VALUES ('notes-a', 'notes-a', $1)", [repo]);+ await withEnv({ GBRAIN_HOME: home, GBRAIN_SOURCE: undefined }, async () => {+ const { resolveSourceId, resolveSourceForRepoPath } = await import('../src/core/source-resolver.ts');+ process.chdir(join(repo, 'sub'));+ try {+ expect(await resolveSourceId(engine, null, join(repo, 'sub'))).toBe('notes-a');+ expect((await resolveSourceForRepoPath(engine, join(repo, 'sub')))?.source_id).toBe('notes-a');+ } finally { process.chdir(folder); }++ const { loadFenceSource } = await import('../src/core/fence-repair/repair-io.ts');+ expect((await loadFenceSource(engine, 'default'))?.root).toBeNull();++ const { resolveFactWriteTarget } = await import('../src/core/persistence/fact-write-target.ts');+ expect((await resolveFactWriteTarget(engine, 'default', { local_path: '.', kind: null }, { fileBacked: false, remote: false })).kind).toBe('publish');++ const { operations } = await import('../src/core/operations.ts');+ const ctx = { engine, config: { engine: backend }, logger: { info() {}, warn() {}, error() {} }, dryRun: false, remote: false, sourceId: 'default', deferEmbeds: true };+ await operations.find(o => o.name === 'put_page')!.handler(ctx as never, { slug: 'notes/kept-in-db', content: '---\ntype: note\ntitle: Kept\n---\n\nA page with no folder of its own.\n' });+ const { getWorktreeBinding } = await import('../src/core/persistence/ownership.ts');+ expect(await getWorktreeBinding(engine, 'default')).toBeNull();+ expect(existsSync(join(folder, 'notes'))).toBe(false);+ await operations.find(o => o.name === 'capture')!.handler(ctx as never, { slug: 'notes', content: 'A captured note.', local_file: join(folder, 'notes.md') });+ expect(await engine.executeRaw("SELECT source_uri FROM pages WHERE source_id='default' AND slug='notes'")).toEqual([{ source_uri: 'cli-file' }]);++ const { activatePersistence } = await import('../src/core/persistence/activation.ts');+ const refused = await activatePersistence(engine, { confirmQuiesced: true, dryRun: true }).then(() => ({}), (error: unknown) => error) as { detail?: string; message?: string };+ expect(refused).toMatchObject({ detail: 'source_path_missing' });+ expect(refused.message).toContain("records the relative local path .");++ await engine.setConfig('sync.repo_path', '.');+ await engine.executeRaw("UPDATE sources SET local_path=NULL WHERE id='default'");+ const { makeCyclePhaseHandler } = await import('../src/core/minions/handlers/cycle-phase.ts');+ const phase = await makeCyclePhaseHandler(engine, 'recompute_emotional_weight')({ id: 1, data: {}, signal: undefined } as never) as { report: { brain_dir: string | null } };+ expect(phase.report.brain_dir).toBeNull();+ const { makeAutopilotGlobalMaintenanceHandler } = await import('../src/core/minions/handlers/autopilot-global-maintenance.ts');+ const brainDirs: Array<string | null | undefined> = [];+ const runCycle = async (_engine: BrainEngine, opts: { phases?: string[]; brainDir?: string | null }) => {+ brainDirs.push(opts.brainDir);+ return { schema_version: '1', timestamp: new Date().toISOString(), duration_ms: 1, status: 'ok', totals: {},+ phases: [{ phase: opts.phases![0], status: 'ok', duration_ms: 1, summary: 'ok', details: {} }] };+ };+ await makeAutopilotGlobalMaintenanceHandler(engine, { runCycle: runCycle as never })({ id: 2, attempts_made: 0, signal: undefined, deadlineAtMs: null, data: { phases: ['orphans'] } } as never);+ expect(brainDirs.length).toBeGreaterThan(0);+ expect(brainDirs.every(dir => dir === null)).toBe(true);+ });+ expect(existsSync(join(folder, '.git'))).toBe(false);+ } finally {+ rmSync(repo, { recursive: true, force: true });+ }+ }, 120_000);++ test('gbrain config set sync.repo_path refuses a relative path and writes nothing; an absolute one is stored', async () => {+ const { runConfig } = await import('../src/commands/config.ts');+ const refused = await cli(() => runConfig(engine, ['set', 'sync.repo_path', '.']));+ expect(refused.exit).toBe(1);+ expect(refused.lines.join('\n')).toContain('sync.repo_path must be an absolute directory');+ expect(await engine.getConfig('sync.repo_path')).toBeNull();+ const stored = await cli(() => runConfig(engine, ['set', 'sync.repo_path', folder]));+ expect(stored.exit).toBeUndefined();+ expect(await engine.getConfig('sync.repo_path')).toBe(folder);+ }, 120_000);++ test('doctor default_source_local_path warns for any source with a relative path, not only default', async () => {+ await engine.executeRaw("INSERT INTO sources (id, name, local_path) VALUES ('notes-a', 'notes-a', 'notes')");+ const check = await defaultSourceLocalPathCheck(engine);+ expect(check?.status).toBe('warn');+ expect(check?.message).toContain('source "notes-a" has the relative local_path "notes"');+ expect(check?.message).toContain('gbrain sources set-path <id> <absolute-directory>');+ }, 120_000);++ test('gbrain import of the cwd into a source whose local_path is "." does not stamp it fresh', async () => {+ await engine.executeRaw("INSERT INTO sources (id, name, local_path) VALUES ('notes-a', 'notes-a', '.')");+ const { runImport } = await import('../src/commands/import.ts');+ await cli(() => runImport(engine, [folder, '--source', 'notes-a', '--no-embed']));+ expect(await pagesOf('notes-a')).toBe(1);+ const [row] = await engine.executeRaw<{ last_sync_at: unknown }>("SELECT last_sync_at FROM sources WHERE id='notes-a'");+ expect(row!.last_sync_at).toBeNull();+ }, 120_000);});}