Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix: pre-landing review fixes (#7630)

garrytan8b01b934006c
diff --git a/src/commands/brainstorm.ts b/src/commands/brainstorm.ts
index 2d021eec2e..052091ab85 100644
--- a/src/commands/brainstorm.ts
+++ b/src/commands/brainstorm.ts
@@ -491,7 +491,7 @@ export function formatSaveOutcome(
}
if (dbSaved && writeThrough.skipped === 'repo_not_found') {
return {
- stdout: `\n_Saved to DB page \`${ctx.slug}\` (\`sync.repo_path\` is not a directory — skipped file write)._`,
+ stdout: `\n_Saved to DB page \`${ctx.slug}\` (\`sync.repo_path\` is not an absolute directory — skipped file write)._`,
stderr,
exitCode: 0,
};
diff --git a/src/commands/doctor/checks/default-source-path.ts b/src/commands/doctor/checks/default-source-path.ts
index f85bc27544..f1e3938253 100644
--- a/src/commands/doctor/checks/default-source-path.ts
+++ b/src/commands/doctor/checks/default-source-path.ts
@@ -43,7 +43,7 @@ export async function defaultSourceLocalPathCheck(engine: BrainEngine): Promise<
livePages = Number(counts?.live ?? 0);
fileBackedPages = Number(counts?.file_backed ?? 0);
repoPath = (await engine.getConfig('sync.repo_path')) || null;
- if (repoPath) {
+ if (repoPath && isAbsolute(repoPath)) {
try {
repoPathIsDir = existsSync(repoPath) && statSync(repoPath).isDirectory();
} catch {
diff --git a/src/commands/sync/run.ts b/src/commands/sync/run.ts
index 4e6994133f..a811ead8a5 100644
--- a/src/commands/sync/run.ts
+++ b/src/commands/sync/run.ts
@@ -47,6 +47,9 @@ import { cliRenderContext, renderNotice } from '../../core/agent-output.ts';
/** D2: under the `--json` guard only writeStdoutFinal reaches fd 1 (writeJsonDocument). */
const emitJson = (text: string): void => { void writeJsonDocument(text); };
+/** #7630: a stored root that is not absolute names the cwd, so post-sync .gitignore upkeep skips it. */
+const absoluteStoredPath = (path: string | null): string | null => path && isAbsolute(path) ? path : null;
+
type SyncAllSourceRow = { id: string; name: string; local_path: string | null; config: Record<string, unknown>; last_commit: string | null; chunker_version: string | null };
// Per-source result accumulator for the optional --json envelope.
@@ -967,7 +970,7 @@ async function runSingleSourceSync(
result.status !== 'blocked_by_failures' &&
result.status !== 'partial'
) {
- const effectiveRepoPath = opts.repoPath ?? (await getDefaultSourcePath(engine));
+ const effectiveRepoPath = opts.repoPath ?? absoluteStoredPath(await getDefaultSourcePath(engine));
if (effectiveRepoPath && !companyPolicy) {
manageGitignoreAtGitRoot(effectiveRepoPath, engine.kind);
}
@@ -1034,7 +1037,7 @@ async function runSingleSourceSync(
result.status !== 'blocked_by_failures' &&
result.status !== 'partial'
) {
- const effectiveRepoPath = opts.repoPath ?? (await getDefaultSourcePath(engine));
+ const effectiveRepoPath = opts.repoPath ?? absoluteStoredPath(await getDefaultSourcePath(engine));
if (effectiveRepoPath) {
manageGitignoreAtGitRoot(effectiveRepoPath, engine.kind);
}
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index 6355fd8fb9..9fd24a7d6b 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -83,7 +83,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'lint': ['--abbrev-ref', '--accept-pending', '--add', '--adopt-slug-path', '--audit', '--autostash', '--background', '--brain', '--branch', '--cached', '--client', '--confirm-relocated-root', '--conflicts', '--dry-run', '--enable', '--exclude', '--expect-remote', '--expected-epoch', '--expected-revision', '--explain', '--ff-only', '--file', '--fix', '--follow', '--force', '--get', '--get-all', '--git-dir', '--git-path', '--grammar-diagnostics', '--hard', '--help', '--id', '--infer-entity', '--is-inside-work-tree', '--json', '--keep', '--keep-checkout', '--local', '--local-env-vars', '--manifest', '--max-cost-usd', '--no-accept-pending', '--no-autostash', '--no-cron', '--no-pull', '--no-tags', '--no-verify', '--older-than', '--only', '--pat-file', '--path', '--prefer', '--preview', '--probe', '--progress-interval', '--progress-json', '--provenance', '--pull', '--purge', '--push-only', '--quiet', '--rebase', '--require-clean', '--resolve', '--scopes', '--self-transfer', '--short', '--show-toplevel', '--slug', '--slugs', '--source', '--source-id', '--timeout', '--timings', '--unset-all', '--wait', '--yes'],
'loops': ['--all', '--as-of', '--brain', '--dry-run', '--fail-fast', '--help', '--json', '--note', '--source', '--stale-ok', '--status', '--tools-json', '--top', '--type'],
'lsd': ['--brain', '--force-resume', '--help', '--json', '--judge-model', '--limit', '--list-runs', '--max-cost', '--max-far-set', '--max-ideas-per-judge-call', '--max-usd', '--no-save', '--resume', '--save', '--source', '--strict-budget', '--yes'],
- 'maintain': ['--account', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--after', '--all', '--allow-outside-source-root', '--apply', '--assign-corpus', '--audit', '--background', '--brain', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--class', '--concurrency', '--conflicts', '--contacts-dir', '--content-audit', '--continue', '--conversation', '--count', '--detach', '--detail', '--dim', '--dir', '--drain', '--dry-run', '--enable', '--entity', '--expect', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--fix', '--follow', '--force', '--force-retry', '--force-schema', '--format', '--from-meetings', '--full', '--grammar', '--group-by', '--hard-deadline', '--harness', '--held', '--help', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-repairs', '--index-audit', '--infer-dates', '--input', '--install', '--json', '--keep-checkout', '--kind', '--lang', '--left-right', '--limit', '--link-source', '--link-type', '--list', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--migrate-legacy', '--migrate-only', '--multimodal', '--name', '--name-only', '--ner', '--no-autopilot-install', '--no-capture', '--no-delegate', '--no-embed', '--no-pull', '--no-renames', '--once', '--only', '--operations', '--output', '--oversized', '--pack', '--page', '--parallel', '--params', '--path', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer', '--preview', '--probe', '--probe-pglite', '--project', '--providers', '--prune-orphans', '--pull', '--purge', '--push-only', '--query', '--question', '--queue', '--quiet', '--reader-mode', '--reauth', '--rebuild', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--request-id', '--reset', '--reset-default', '--restart-only', '--resume', '--retry-failed', '--retry-held', '--retry-parked', '--reverse', '--safe', '--scope', '--scopes', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--staged', '--stale', '--stat', '--state', '--status', '--supabase', '--symbol-kind', '--takes-holders', '--target', '--target-score', '--tier', '--to', '--token', '--top-k', '--type', '--unindexed', '--url-env', '--verbose', '--verify', '--version', '--window', '--workers', '--yes'],
+ 'maintain': ['--account', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--after', '--all', '--allow-outside-source-root', '--apply', '--assign-corpus', '--audit', '--background', '--brain', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--class', '--clear', '--concurrency', '--conflicts', '--contacts-dir', '--content-audit', '--continue', '--conversation', '--count', '--detach', '--detail', '--dim', '--dir', '--drain', '--dry-run', '--enable', '--entity', '--expect', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--fix', '--follow', '--force', '--force-retry', '--force-schema', '--format', '--from-meetings', '--full', '--grammar', '--group-by', '--hard-deadline', '--harness', '--held', '--help', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-repairs', '--index-audit', '--infer-dates', '--input', '--install', '--json', '--keep-checkout', '--kind', '--lang', '--left-right', '--limit', '--link-source', '--link-type', '--list', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--migrate-legacy', '--migrate-only', '--multimodal', '--name', '--name-only', '--ner', '--no-autopilot-install', '--no-capture', '--no-delegate', '--no-embed', '--no-pull', '--no-renames', '--once', '--only', '--operations', '--output', '--oversized', '--pack', '--page', '--parallel', '--params', '--path', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer', '--preview', '--probe', '--probe-pglite', '--project', '--providers', '--prune-orphans', '--pull', '--purge', '--push-only', '--query', '--question', '--queue', '--quiet', '--reader-mode', '--reauth', '--rebuild', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--request-id', '--reset', '--reset-default', '--restart-only', '--resume', '--retry-failed', '--retry-held', '--retry-parked', '--reverse', '--safe', '--scope', '--scopes', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--staged', '--stale', '--stat', '--state', '--status', '--supabase', '--symbol-kind', '--takes-holders', '--target', '--target-score', '--tier', '--to', '--token', '--top-k', '--type', '--unindexed', '--url-env', '--verbose', '--verify', '--version', '--window', '--workers', '--yes'],
'mcp': ['--admin-token-file', '--agent', '--arg', '--bearer-token-env-var', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--client', '--credentials-file', '--credentials-out', '--delegate', '--delegated-namespace', '--delegated-slug-prefixes', '--dry-run', '--enable-dcr', '--federated-read', '--flow', '--force', '--funnel', '--harness', '--header', '--help', '--if-version', '--install', '--issuer-url', '--json', '--limit', '--mcp-only', '--mcp-url', '--no-install', '--no-service', '--no-tailscale', '--oauth-client-id', '--oauth-client-secret', '--oauth-request', '--port', '--profile', '--queue', '--redirect-uri', '--remove', '--resume', '--root', '--scope', '--scopes', '--skills', '--source', '--status', '--surface', '--timeout-ms', '--token', '--token-endpoint-auth-method', '--token-ttl', '--url', '--yes'],
'migrate': ['--accept-pending', '--admin-intent', '--all', '--apply', '--background', '--batch-size', '--brain', '--catch-up', '--dim', '--drain-timeout', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expect', '--expected-epoch', '--expected-state', '--explain', '--facts', '--follow', '--force', '--force-retry', '--harness', '--held', '--help', '--ignore-env-override', '--images', '--include-null-signature', '--json', '--locks', '--manifest', '--max-cost', '--max-cost-usd', '--max-usd', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-migrate', '--non-interactive', '--only', '--oversized', '--pace', '--pace-max-concurrency', '--path', '--pglite', '--plan', '--priority', '--probe', '--progress-interval', '--progress-json', '--quiet', '--replace', '--reranker', '--resume', '--retarget', '--rollback-to-source', '--scope', '--skip-verify', '--slugs', '--source', '--stale', '--statement-timeout', '--status', '--timeout', '--timings', '--to', '--trigger-bypass', '--trust', '--url', '--url-env', '--wait', '--yes'],
'models': ['--batch', '--brain', '--concurrent', '--cycles', '--dim', '--dimensions', '--embedding-dimensions', '--embedding-model', '--help', '--json', '--limit', '--max-tokens', '--max-usd', '--output', '--receipt-dir', '--skip', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--source', '--status', '--task', '--to', '--yes'],
diff --git a/src/core/default-source-path-check.ts b/src/core/default-source-path-check.ts
index 1335c2fa5e..901f6b5ac5 100644
--- a/src/core/default-source-path-check.ts
+++ b/src/core/default-source-path-check.ts
@@ -21,9 +21,9 @@
* nor a resolvable `sync.repo_path` names the tree they live in, so
* write-through, fence writes, and delete-reconcile cannot find them.
*
- * - RELATIVE PATH (#7630): a set `local_path` that is not absolute (a
- * legacy "."). It names whatever directory gbrain runs from, and sync
- * refuses it `sync_anchor_relative`.
+ * - RELATIVE PATH (#7630): a set `local_path`, or with a null one a
+ * `sync.repo_path`, that is not absolute (a legacy "."). It names whatever
+ * directory gbrain runs from, and sync refuses it `sync_anchor_relative`.
*
* Everything else (no pages yet, resolvable repo fallback, deliberate
* DB-only brain) reports ok. The repair for a genuinely broken pointer is
@@ -84,6 +84,16 @@ export function assessDefaultSourcePath(
message: `default source local_path is set: ${defaultSource.local_path}`,
};
}
+ if (repoPath && !isAbsolute(repoPath)) {
+ return {
+ status: 'warn',
+ message:
+ `default source has no local_path and sync.repo_path is the relative path "${repoPath}", which names whatever ` +
+ 'directory gbrain runs from, so sync refuses it (sync_anchor_relative) and default-source page writes skip the ' +
+ 'repository. Ask the user which directory holds the brain, then run ' +
+ '`gbrain config set sync.repo_path <absolute-directory>`.',
+ };
+ }
// null local_path — the designed fallback topology. Only warn when the
// fallback demonstrably fails for pages that actually route through it.
if (livePages === 0) {
diff --git a/src/core/fence-repair/census.ts b/src/core/fence-repair/census.ts
index 26e70f6cf3..da78af86a6 100644
--- a/src/core/fence-repair/census.ts
+++ b/src/core/fence-repair/census.ts
@@ -25,7 +25,7 @@
*/
import { execFileSync } from '../spawn.ts';
import { existsSync, lstatSync, readFileSync, statSync } from 'node:fs';
-import { join, relative, resolve } from 'node:path';
+import { isAbsolute, join, relative, resolve } from 'node:path';
import type { BrainEngine } from '../engine.ts';
import { parseMarkdown } from '../markdown.ts';
import { screenFenceCtx } from '../import-screen.ts';
@@ -95,7 +95,7 @@ async function censusSources(engine: Exec, sourceIds?: readonly string[]): Promi
WHERE archived IS NOT TRUE AND incarnation IS NOT NULL AND ($1::text[] IS NULL OR id=ANY($1::text[])) ORDER BY id`, [sourceIds ? [...sourceIds] : null]);
}
-const hasCheckout = (source: CensusSource) => !!source.local_path && existsSync(source.local_path) && statSync(source.local_path).isDirectory();
+const hasCheckout = (source: CensusSource) => !!source.local_path && isAbsolute(source.local_path) && existsSync(source.local_path) && statSync(source.local_path).isDirectory();
/** Where the next incremental pass starts: this moment, or the start of the oldest writer transaction still open, minus the grace. */
async function passHorizon(engine: Exec, graceMs: number): Promise<string> {
diff --git a/src/core/persistence/resolve-paths.ts b/src/core/persistence/resolve-paths.ts
index b713a06291..fed8a14aba 100644
--- a/src/core/persistence/resolve-paths.ts
+++ b/src/core/persistence/resolve-paths.ts
@@ -27,6 +27,7 @@
import type { BrainEngine } from '../engine.ts';
import type { Action } from '../agent-output.ts';
import { existsSync, realpathSync } from 'node:fs';
+import { isAbsolute } from 'node:path';
import { opError } from '../ops/contract.ts';
import { resolveSlugForPath, unsyncableReason, type SyncableReason } from '../sync.ts';
import { parseMarkdownHead } from '../markdown.ts';
@@ -114,6 +115,8 @@ export async function resolveSourcePaths(engine: BrainEngine, sourceId: string,
const status = ['gbrain', 'sources', 'status', sourceId, '--json'];
if (!source || source.archived) throw opError('not_found', `Source ${sourceId} is not registered or is archived.`, 'List the registered sources and pass one of their ids.',
{ fix: readFix('Lists the registered sources.', ['gbrain', 'sources', 'list', '--json'], ['gbrain', 'sources', 'list', '--json']) });
+ if (source.local_path && !isAbsolute(source.local_path)) throw opError('not_found', `Source ${sourceId} has the relative local_path "${source.local_path}", which names no fixed directory, so its paths cannot be resolved (sync_anchor_relative).`,
+ 'Ask the user which directory holds the checkout, then run gbrain sources set-path on the host that holds it.', { fix: readFix('Shows the source and its stored path.', status, status) });
if (!source.local_path || !existsSync(source.local_path)) throw opError('not_found', `Source ${sourceId} has no Git checkout on this host, so its paths cannot be resolved here.`,
'Run this on the host that holds the checkout (gbrain sources status names its path).', { fix: readFix('Shows where the source checkout lives.', status, status) });
const root = realpathSync(source.local_path);
diff --git a/src/core/persistence/terminal-classify.ts b/src/core/persistence/terminal-classify.ts
index 6c8d6c7593..2e3ede008c 100644
--- a/src/core/persistence/terminal-classify.ts
+++ b/src/core/persistence/terminal-classify.ts
@@ -338,12 +338,19 @@ function schemaMissingVerdict(input: TerminalInput, code: string, origin: string
why: `The write needed ${what}. Read-only: when doctor's schema_version reports the schema behind, run gbrain apply-migrations --yes as the database role that owns the gbrain tables and resubmit; when it is at head, its schema_missing_tables check names what is missing (gbrain repair missing-tables previews it).` } };
}
+/** #7630: the foreground page and memory writes a caller resubmits; no sync replays them. */
+const RESUBMITTED_WRITES = new Set(['put_page', 'put_pages', 'capture', 'delete_page', 'restore_page', 'revert_version', 'edit_page', 'append_page', 'remember', 'forget']);
+
/**
- * #7630: a sync write (and a recorded sync fault, read as one) is stored as `submit_job`; its retry is the sync. Any other
- * operation is a foreground write (`remember`, `put_page`, ...) that no sync replays: its caller resubmits it.
+ * #7630: a sync write (and a recorded sync fault, read as one) is stored as `submit_job`; its retry is the sync. A
+ * foreground write (`remember`, `put_page`, ...) is resubmitted by its caller. Any other operation (maintenance,
+ * administration) is neither: writer status names what holds it.
*/
function faultAction(code: string, input: TerminalInput): Action {
const v = classifySyncFault({ code });
+ if (v.safe_actions[0] === 'retry' && input.operation !== 'submit_job' && !RESUBMITTED_WRITES.has(input.operation)) {
+ return inspect(input.source_id, `The ${input.operation} operation ended ${code}; it was not part of a sync, so a sync does not retry it. Writer status names what holds it, read-only.`, v.human_reason);
+ }
if (v.safe_actions[0] === 'retry' && input.operation !== 'submit_job') {
return inspect(input.source_id, `The ${input.operation} write ended ${code}; it was not part of a sync, so a sync does not retry it. `
+ `Writer status names the step it stopped at and what held it, read-only. Once that clears, resubmit the same ${input.operation} with a new request_id (for a page an import or repair wrote, rerun that command).`);
diff --git a/src/core/sync-config-keys.ts b/src/core/sync-config-keys.ts
index c20de2eb18..9635e801e8 100644
--- a/src/core/sync-config-keys.ts
+++ b/src/core/sync-config-keys.ts
@@ -127,18 +127,18 @@ export function syncKeySetNotice(key: string): { writes: boolean; lines: string[
return null;
}
-/**
- * `gbrain config get|set` of a retired or rollback key. `get` prints the value in effect (stdout) and its origin
- * (stderr); `set` prints the key's notice. True when the command is done: every `get`, and the `set` of a retired key,
- * 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 `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.`;
}
+/**
+ * `gbrain config get|set` of a retired or rollback key. `get` prints the value in effect (stdout) and its origin
+ * (stderr); `set` prints the key's notice. True when the command is done: every `get`, and the `set` of a retired key,
+ * 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.
+ */
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/src/core/write-through.ts b/src/core/write-through.ts
index 6a1269b2f6..cfbd271028 100644
--- a/src/core/write-through.ts
+++ b/src/core/write-through.ts
@@ -80,7 +80,7 @@ export interface WriteThroughResult {
* or DB work.
* - no_repo_configured: the resolved target (source `local_path` or, for a
* sole-source brain, `sync.repo_path`) is unset (DB-only by design).
- * - repo_not_found: target set but missing / not a directory.
+ * - repo_not_found: target set but relative (#7630), missing, or not a directory.
* - source_repo_belongs_to_other_source: the assigned source has no
* `local_path`, and `sync.repo_path` is another source's own working tree
* — #2018: writing here would pollute that sibling's repo, so we skip.
diff --git a/test/sync-relative-anchor-refusal-7630.test.ts b/test/sync-relative-anchor-refusal-7630.test.ts
index 055ccc06f8..f54f894070 100644
--- a/test/sync-relative-anchor-refusal-7630.test.ts
+++ b/test/sync-relative-anchor-refusal-7630.test.ts
@@ -158,7 +158,7 @@ for (const backend of testBackends()) {
await engine.executeRaw("UPDATE sources SET local_path='.' WHERE id='default'");
for (let i = 0; i < 5; i++) writeFileSync(join(folder, `page-${i}.md`), `---\ntype: note\ntitle: Page ${i}\n---\n\n${'word '.repeat(200)}\n`);
configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536, env: { OPENAI_API_KEY: 'sk-test-7630' } });
- const fetchSpy = spyOn(globalThis, 'fetch');
+ const fetchSpy = spyOn(globalThis, 'fetch').mockImplementation((async () => { throw new Error('#7630 test: no provider call'); }) as never);
let result: Awaited<ReturnType<typeof runSyncCli>>, fetchCalls: number;
try {
result = await runSyncCli(['--source', 'default', '--no-pull']);
@@ -419,6 +419,62 @@ for (const backend of testBackends()) {
}
}, 120_000);
+ // /ship review fixes (GBRA-207, #7630).
+ // Value: protects=doctor names a relative legacy sync.repo_path behind a null default local_path instead of reporting the fallback healthy;
+ // fails_when=the wrapper resolves "." against the cwd (existsSync is true) and the assessor reports "write through sync.repo_path (.)";
+ // why_new=the doctor cases above set a relative local_path, never the legacy key; seam=none; no_claim=other doctor checks
+ test('doctor default_source_local_path warns on a relative sync.repo_path behind a null default local_path', async () => {
+ await engine.setConfig('sync.repo_path', '.');
+ await engine.putPage('notes/live', { type: 'note', title: 'Live', compiled_truth: 'A live default page.', timeline: '' }, { sourceId: 'default' });
+ const check = await defaultSourceLocalPathCheck(engine);
+ expect(check?.status).toBe('warn');
+ expect(check?.message).toContain('sync.repo_path is the relative path "."');
+ expect(check?.message).toContain('gbrain config set sync.repo_path <absolute-directory>');
+ }, 120_000);
+
+ // Value: protects=a successful sync of another source never runs .gitignore upkeep on the cwd's Git repo through a stored relative root;
+ // fails_when=post-sync upkeep takes getDefaultSourcePath's "." (a second non-default source keeps the cwd chain on default)
+ // and writes the managed block into the cwd repo's .gitignore;
+ // why_new=the --all case above never reaches the single-source post-sync upkeep; seam=none;
+ // no_claim=watch mode (the same expression at its second call site), parallel import workers (--workers 1)
+ test('gbrain sync --source of an absolute source leaves the cwd repo\'s .gitignore alone when default\'s local_path is "."', async () => {
+ const repo = realpathSync(mkdtempSync(join(tmpdir(), 'gbrain-7630-repo-')));
+ try {
+ execSync('git init -q && git config user.email [email protected] && git config user.name T', { cwd: repo, stdio: 'pipe' });
+ writeFileSync(join(repo, 'kept.md'), '---\ntype: note\ntitle: Kept\n---\n\nA page of the absolute source.\n');
+ execSync('git add -A && git commit -q -m initial', { cwd: repo, stdio: 'pipe' });
+ execSync('git init -q', { cwd: folder, stdio: 'pipe' });
+ writeFileSync(join(folder, 'gbrain.yml'), 'storage:\n db_only:\n - media/x/\n');
+ 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 engine.executeRaw("INSERT INTO sources (id, name, local_path) VALUES ('notes-b', 'notes-b', $1)", [join(repo, 'elsewhere')]);
+ const { exit } = await cli(async () => {
+ const { runSync } = await import('../src/commands/sync.ts');
+ await runSync(engine, ['--source', 'notes-a', '--no-pull', '--no-embed', '--workers', '1']);
+ });
+ expect(exit ?? 0).toBe(0);
+ expect(await pagesOf('notes-a')).toBe(1);
+ expect(existsSync(join(folder, '.gitignore'))).toBe(false);
+ } finally {
+ rmSync(repo, { recursive: true, force: true });
+ }
+ }, 120_000);
+
+ // Value: protects=the remote sources_resolve_path read and the fence census never treat a relative local_path as the host's cwd;
+ // fails_when=resolveSourcePaths realpaths "." (the cwd's Git repo answers) or the census walks the cwd's files;
+ // why_new=the reader cases above cover write and maintenance roots, not these two reads; seam=none; no_claim=the MCP transport
+ test('sources_resolve_path refuses and the fence census walks no files for a relative local_path', async () => {
+ execSync('git init -q && git config user.email [email protected] && git config user.name T && git add -A && git commit -q -m initial', { cwd: folder, stdio: 'pipe' });
+ await engine.executeRaw("UPDATE sources SET local_path='.' WHERE id='default'");
+ const { resolveSourcePaths } = await import('../src/core/persistence/resolve-paths.ts');
+ const refused = await resolveSourcePaths(engine, 'default', ['notes.md']).then(() => null, (error: { code?: string; message?: string }) => error);
+ expect(refused?.code).toBe('not_found');
+ expect(refused?.message).toContain('relative local_path');
+ const { runFenceCensus } = await import('../src/core/fence-repair/census.ts');
+ const [run] = await runFenceCensus(engine, { sourceIds: ['default'], deadline: Date.now() + 60_000 });
+ expect(run?.files).toBe('none');
+ }, 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');
@@ -445,6 +501,15 @@ describe('#7630: a stalled write\'s diagnosis matches its operation', () => {
});
}
+ for (const operation of ['extract_facts', 'writer_deactivate']) {
+ test(`a stalled ${operation} (maintenance or administration) inspects the writer, with no resubmit and no sync`, () => {
+ const verdict = receipt(operation);
+ expect(verdict.action.argv).toEqual(['gbrain', 'sources', 'writer', 'status', '--source', 'default', '--json']);
+ expect(verdict.action.why).not.toContain('request_id');
+ expect(renderAction(verdict.action, mcp).command).not.toContain('gbrain sync');
+ });
+ }
+
test('a recorded sync fault and a sync page receipt keep the sync retry', () => {
expect(classifyRecordedFault({ source_id: 'default', code: 'preparation_stalled' }).action.argv?.slice(0, 2)).toEqual(['gbrain', 'sync']);
expect(receipt('submit_job').action.argv?.slice(0, 2)).toEqual(['gbrain', 'sync']);