Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(wave5): cross-lane fixes from the integration review

garrytan064629e8a18f
diff --git a/src/commands/projections.ts b/src/commands/projections.ts
index b65552f450..e3674cdf8c 100644
--- a/src/commands/projections.ts
+++ b/src/commands/projections.ts
@@ -18,8 +18,8 @@ import {
projectionBacklog, rebuildPendingPageProjections, type ProjectionRebuildFailure,
} from '../core/page-state/projections.ts';
import { SERVE_LAUNCHD_LABEL, SERVE_SYSTEMD_UNIT } from '../core/serve-service.ts';
-import { AUTOPILOT_SYSTEMD_UNIT } from './autopilot.ts';
-import { autopilotLaunchdLabel } from '../core/autopilot-paths.ts';
+import { resolveAutopilotJob } from '../core/autopilot-paths.ts';
+import { detectInstalledJob } from './autopilot/jobs.ts';
export const PROJECTION_DRAIN_DOCS = 'docs/guides/repair.md#projection-drain';
const BATCH = 100;
@@ -98,14 +98,19 @@ export function projectionFailureNextAction(failure: ProjectionRebuildFailure):
*/
export function residentDrainSteps(pid: number | undefined, brain = 'host'): string {
const uid = '$(id -u)';
+ // #5195: this brain's own autopilot job, or the shared job an older install still runs it from.
+ const job = resolveAutopilotJob();
+ const installed = detectInstalledJob(job).installed;
+ const launchd = installed?.target === 'macos' ? installed.name : job.launchdLabel;
+ const systemd = installed?.target === 'linux-systemd' ? installed.name : job.systemdUnit;
const drain = `gbrain projections drain${brain === 'host' ? '' : ` --brain ${brain}`}`;
const cycle = (stop: string, start: string) => `${stop} && { ${drain}; ${start}; }`;
return [
`To drain faster, stop the owner, drain, then restart it:`,
` serve service (launchd): ${cycle(`launchctl bootout gui/${uid}/${SERVE_LAUNCHD_LABEL}`, `launchctl bootstrap gui/${uid} ~/Library/LaunchAgents/${SERVE_LAUNCHD_LABEL}.plist`)}`,
` serve service (systemd): ${cycle(`systemctl --user stop ${SERVE_SYSTEMD_UNIT}`, `systemctl --user start ${SERVE_SYSTEMD_UNIT}`)}`,
- ` autopilot (launchd): ${cycle(`launchctl bootout gui/${uid}/${autopilotLaunchdLabel()}`, `launchctl bootstrap gui/${uid} ~/Library/LaunchAgents/${autopilotLaunchdLabel()}.plist`)}`,
- ` autopilot (systemd): ${cycle(`systemctl --user stop ${AUTOPILOT_SYSTEMD_UNIT}`, `systemctl --user start ${AUTOPILOT_SYSTEMD_UNIT}`)}`,
+ ` autopilot (launchd): ${cycle(`launchctl bootout gui/${uid}/${launchd}`, `launchctl bootstrap gui/${uid} ~/Library/LaunchAgents/${launchd}.plist`)}`,
+ ` autopilot (systemd): ${cycle(`systemctl --user stop ${systemd}`, `systemctl --user start ${systemd}`)}`,
` a manual gbrain serve: stop it${pid ? ` (kill ${pid})` : ''}, run ${drain}, then start gbrain serve again`,
].join('\n');
}
diff --git a/src/core/persistence/page-mutations.ts b/src/core/persistence/page-mutations.ts
index 73413e04e5..64e361505d 100644
--- a/src/core/persistence/page-mutations.ts
+++ b/src/core/persistence/page-mutations.ts
@@ -22,6 +22,7 @@ import { assertKnowledgePublicationAllowed } from '../shared-skills/knowledge-gu
import { isUnboundSourcePage, readUnboundWritePolicy, unboundSourceError } from './unbound-source.ts';
import { colonSlugWindowsRefusal, isWindowsColonTarget } from './native-file-target.ts';
import { publishesDatabaseOnly } from './page-prepare.ts';
+import { isMirrorOnlyPage, sourceMirrorReadOnly } from './mirror-read-only.ts';
import { isConnectorSourceKind } from './connector-identity.ts';
export async function requestPrincipalForContext(ctx: OperationContext): Promise<Principal> {
@@ -183,9 +184,12 @@ export async function submitPageMutation(ctx: OperationContext,
}
}
// #5032: this host publishes the canonical file, and on Windows a ':' in its
- // name cannot be stored; refuse before admission. Database-only writes pass.
+ // name cannot be stored; refuse before admission. Database-only writes pass,
+ // including read-only mirror sources and pages created while one (#5409).
if (writeThrough && binding?.owner_host_id === localHostId() && binding.local_path && isWindowsColonTarget(snapshot?.page.source_path ?? `${slug}.md`)
&& !(snapshot && !snapshot.page.source_path && await isUnboundSourcePage(ctx.engine, sourceId, slug))
+ && !await sourceMirrorReadOnly(ctx.engine, sourceId)
+ && !(snapshot && !snapshot.page.source_path && await isMirrorOnlyPage(ctx.engine, sourceId, slug))
&& !publishesDatabaseOnly(join(binding.local_path, binding.relative_path), slug, snapshot)) {
throw colonSlugWindowsRefusal(slug, sourceId);
}
diff --git a/test/colon-slug-windows-5032.test.ts b/test/colon-slug-windows-5032.test.ts
index e9fae45914..f6ae089ddf 100644
--- a/test/colon-slug-windows-5032.test.ts
+++ b/test/colon-slug-windows-5032.test.ts
@@ -123,6 +123,21 @@ describe('#5032 put_page with a colon slug', () => {
expect((await engine.getPage('atoms/cal:abc', { sourceId }))?.compiled_truth).toContain('An updated event.');
}), 60_000);
+ test('Windows: a read-only mirror source stores a colon slug database-only instead of refusing (#5409)', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ const engine = engines[0];
+ const root = join(home, `mirror-${randomUUID()}`); mkdirSync(root);
+ const sourceId = await addSource(engine, root);
+ await claimWorktree(engine, sourceId, root);
+ await engine.executeRaw(`UPDATE sources SET config = config || '{"mirror_read_only":true}'::jsonb WHERE id=$1`, [sourceId]);
+ await asWindows(() => putPage.handler(ctxOf(engine, sourceId), { slug: 'calendar:abc', content: CONTENT }));
+ expect((await engine.getPage('calendar:abc', { sourceId }))?.compiled_truth).toContain('A calendar event.');
+ await engine.executeRaw(`UPDATE sources SET config = config || '{"mirror_read_only":false}'::jsonb WHERE id=$1`, [sourceId]);
+ await asWindows(() => putPage.handler(ctxOf(engine, sourceId), {
+ slug: 'calendar:abc', content: CONTENT.replace('A calendar event.', 'An updated event.'), force: true,
+ }));
+ expect((await engine.getPage('calendar:abc', { sourceId }))?.compiled_truth).toContain('An updated event.');
+ }), 60_000);
+
test('Windows: publication refuses a colon file target admitted elsewhere', async () => withEnv({ GBRAIN_HOME: home }, async () => {
const engine = engines[0];
const root = join(home, `pub-${randomUUID()}`); mkdirSync(root);
diff --git a/test/fixtures/goldens/doctor/early-stop-connection-failure.json b/test/fixtures/goldens/doctor/early-stop-connection-failure.json
index 495bdfd6c1..aa09127094 100644
--- a/test/fixtures/goldens/doctor/early-stop-connection-failure.json
+++ b/test/fixtures/goldens/doctor/early-stop-connection-failure.json
@@ -237,6 +237,21 @@
"name": "pglite_leftovers",
"status": "ok"
},
+ {
+ "details": {
+ "docs": "docs/guides/repair.md#embedding-key-source",
+ "embedding_key": {
+ "config_key": "voyage_api_key",
+ "kind": "missing",
+ "variable": "VOYAGE_API_KEY"
+ },
+ "embedding_model": "voyage:voyage-4",
+ "shadows": []
+ },
+ "message": "No embedding key is set here (VOYAGE_API_KEY or voyage_api_key). No environment variable overrides a different config-plane provider key. This check sees only the environment `gbrain doctor` runs in; a daemon (gbrain serve, autopilot) has its own, and reports a mismatch in its log with a startup warning or embedding_auth_failed.",
+ "name": "embedding_key_source",
+ "status": "ok"
+ },
{
"message": "Prepared statements disabled (PgBouncer-safe)",
"name": "pgbouncer_prepare",
diff --git a/test/fixtures/goldens/doctor/early-stop-null-engine-connect-error.json b/test/fixtures/goldens/doctor/early-stop-null-engine-connect-error.json
index 4770c0052d..486c7e104a 100644
--- a/test/fixtures/goldens/doctor/early-stop-null-engine-connect-error.json
+++ b/test/fixtures/goldens/doctor/early-stop-null-engine-connect-error.json
@@ -169,6 +169,21 @@
"name": "pglite_leftovers",
"status": "ok"
},
+ {
+ "details": {
+ "docs": "docs/guides/repair.md#embedding-key-source",
+ "embedding_key": {
+ "config_key": "voyage_api_key",
+ "kind": "missing",
+ "variable": "VOYAGE_API_KEY"
+ },
+ "embedding_model": "voyage:voyage-4",
+ "shadows": []
+ },
+ "message": "No embedding key is set here (VOYAGE_API_KEY or voyage_api_key). No environment variable overrides a different config-plane provider key. This check sees only the environment `gbrain doctor` runs in; a daemon (gbrain serve, autopilot) has its own, and reports a mismatch in its log with a startup warning or embedding_auth_failed.",
+ "name": "embedding_key_source",
+ "status": "ok"
+ },
{
"details": {
"fix_hint": "Connection refused. If this is a Supabase direct URL (db.<ref>...:5432), switch to the transaction pooler (port 6543): gbrain db-repair can rewrite it. Run: gbrain db-repair",
diff --git a/test/fixtures/goldens/doctor/early-stop-null-engine-fast.json b/test/fixtures/goldens/doctor/early-stop-null-engine-fast.json
index 16de835e8e..09ed790f38 100644
--- a/test/fixtures/goldens/doctor/early-stop-null-engine-fast.json
+++ b/test/fixtures/goldens/doctor/early-stop-null-engine-fast.json
@@ -169,6 +169,21 @@
"name": "pglite_leftovers",
"status": "ok"
},
+ {
+ "details": {
+ "docs": "docs/guides/repair.md#embedding-key-source",
+ "embedding_key": {
+ "config_key": "voyage_api_key",
+ "kind": "missing",
+ "variable": "VOYAGE_API_KEY"
+ },
+ "embedding_model": "voyage:voyage-4",
+ "shadows": []
+ },
+ "message": "No embedding key is set here (VOYAGE_API_KEY or voyage_api_key). No environment variable overrides a different config-plane provider key. This check sees only the environment `gbrain doctor` runs in; a daemon (gbrain serve, autopilot) has its own, and reports a mismatch in its log with a startup warning or embedding_auth_failed.",
+ "name": "embedding_key_source",
+ "status": "ok"
+ },
{
"message": "Skipping DB checks (--fast mode, URL present from config-file)",
"name": "connection",
diff --git a/test/fixtures/goldens/doctor/early-stop-null-engine-no-config.json b/test/fixtures/goldens/doctor/early-stop-null-engine-no-config.json
index 10fa8b615c..95fca59fbf 100644
--- a/test/fixtures/goldens/doctor/early-stop-null-engine-no-config.json
+++ b/test/fixtures/goldens/doctor/early-stop-null-engine-no-config.json
@@ -164,6 +164,21 @@
"name": "home_dir_in_worktree",
"status": "ok"
},
+ {
+ "details": {
+ "docs": "docs/guides/repair.md#embedding-key-source",
+ "embedding_key": {
+ "config_key": "voyage_api_key",
+ "kind": "missing",
+ "variable": "VOYAGE_API_KEY"
+ },
+ "embedding_model": "voyage:voyage-4",
+ "shadows": []
+ },
+ "message": "No embedding key is set here (VOYAGE_API_KEY or voyage_api_key). No environment variable overrides a different config-plane provider key. This check sees only the environment `gbrain doctor` runs in; a daemon (gbrain serve, autopilot) has its own, and reports a mismatch in its log with a startup warning or embedding_auth_failed.",
+ "name": "embedding_key_source",
+ "status": "ok"
+ },
{
"message": "No database configured (filesystem checks only). Set GBRAIN_DATABASE_URL or run `gbrain init`.",
"name": "connection",
diff --git a/test/projection-drain-autopilot-names.test.ts b/test/projection-drain-autopilot-names.test.ts
new file mode 100644
index 0000000000..a64bc3b147
--- /dev/null
+++ b/test/projection-drain-autopilot-names.test.ts
@@ -0,0 +1,56 @@
+/**
+ * #5401 x #5195: the projection drain's stop/drain/restart steps name the
+ * autopilot job that runs THIS brain, not the shared default job, so following
+ * them never stops another brain's autopilot and leaves this owner running.
+ */
+
+import { describe, test, expect } from 'bun:test';
+import { mkdirSync, mkdtempSync, realpathSync, rmSync } from 'fs';
+import { spawnSync } from 'child_process';
+import { join, resolve } from 'path';
+import { tmpdir } from 'os';
+
+const REPO = resolve(import.meta.dir, '..');
+
+/** Bun fixes os.homedir() at process start, so each case runs in a child with the HOME under test. */
+function stepsIn(env: Record<string, string>, mint: boolean): { steps: string; suffix: string | null } {
+ const script = `import { ensureAutopilotInstallId, resolveAutopilotJob } from ${JSON.stringify(join(REPO, 'src/core/autopilot-paths.ts'))};\n`
+ + `import { residentDrainSteps } from ${JSON.stringify(join(REPO, 'src/commands/projections.ts'))};\n`
+ + `if (${mint}) ensureAutopilotInstallId();\n`
+ + `process.stdout.write(JSON.stringify({ steps: residentDrainSteps(4242), suffix: resolveAutopilotJob().suffix }));\n`;
+ const childEnv: Record<string, string> = {};
+ for (const [k, v] of Object.entries({ ...process.env, ...env })) if (v !== undefined) childEnv[k] = v;
+ delete childEnv.GBRAIN_AUTOPILOT_LABEL;
+ const r = spawnSync(process.execPath, ['-e', script], { env: childEnv, encoding: 'utf-8' });
+ if (r.status !== 0) throw new Error(`child failed: ${r.stderr}`);
+ return JSON.parse(r.stdout);
+}
+
+describe('projection drain steps name this brain\'s autopilot job', () => {
+ test('a non-default GBRAIN_HOME brain gets its own suffixed launchd label and systemd unit', () => {
+ const root = realpathSync(mkdtempSync(join(tmpdir(), 'gbrain-drain-names-')));
+ try {
+ mkdirSync(join(root, 'home'), { recursive: true });
+ mkdirSync(join(root, 'brain-b'), { recursive: true });
+ const { steps, suffix } = stepsIn({ HOME: join(root, 'home'), GBRAIN_HOME: join(root, 'brain-b') }, true);
+ expect(suffix).toMatch(/^[0-9a-f]{8}$/);
+ expect(steps).toContain(`systemctl --user stop gbrain-autopilot-${suffix}.service`);
+ expect(steps).toContain(`launchctl bootout gui/$(id -u)/com.gbrain.autopilot.${suffix}`);
+ expect(steps).not.toContain('systemctl --user stop gbrain-autopilot.service');
+ } finally {
+ rmSync(root, { recursive: true, force: true });
+ }
+ });
+
+ test('the default brain keeps the shared names', () => {
+ const root = realpathSync(mkdtempSync(join(tmpdir(), 'gbrain-drain-names-')));
+ try {
+ mkdirSync(join(root, 'home'), { recursive: true });
+ const { steps } = stepsIn({ HOME: join(root, 'home'), GBRAIN_HOME: '' }, false);
+ expect(steps).toContain('systemctl --user stop gbrain-autopilot.service');
+ expect(steps).toContain('launchctl bootout gui/$(id -u)/com.gbrain.autopilot ');
+ } finally {
+ rmSync(root, { recursive: true, force: true });
+ }
+ });
+});