Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(migrations): init stamps fresh_install_noop migrations; others report pending_fresh_install (E8)

garrytan219165e0c766
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 6765c982d9..f658c435d7 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -25,7 +25,7 @@ src/core/postgres-engine.ts 2914 ratchet +1 System One v1 evals: search arms cla
src/core/search/hybrid.ts 1584 ratchet +2 System One v1: HybridSearchOpts.decide (search/decide-stage.ts); refactor wave 1 split target (W4 hybrid, cut line); ceiling rationale: docs/architecture/key-files/core-search-1.md entry for src/core/search/hybrid.ts; +10 #5691: per-request embedding_query_prefix read once and threaded to the embeds and cache key
src/core/types.ts 2123 ratchet +5 System One v1 retrieval lane: SearchResult injection_p/injection_suspected, HybridSearchMeta answerability, egress_denied degraded reason; +4 System One v1: SearchResult rerank_score_kind/decide_evidence, HybridSearchMeta decide/rerank; +3 wave review: PAGE_SORT_SQL.updated_asc source_id + id tiebreakers (total order under federated scopes); +5 #4881: OntologyReadOpts extends PageReadScope doc; +3 #4857: PAGE_SORT_SQL.slug total-order tiebreaker comment; grown v0.46.26.0 megawave: EvidenceOpts, pacing/usage result fields, PageFilters growth (#4352 #4218); wave-k: +9 SalienceOpts/AnomaliesOpts source scope (#3867); +20 2026-09 adversarial batch 2: keyword_relaxed_carried stage + relaxed_dropped meta field docs; +16 2026-09 fix wave: SearchResult.keyword_relaxed field + full fusion-demotion doc; (#3867); +9: #4648 rerank_passthrough degraded stage + empty_result_set/malformed_shape reasons | merged v0.48.1.0 true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); corrective release: shared internal PageReadScope and PageReadPolicy; ranker wave v0.48.4.0: HybridSearchMeta relational_rerank_pin / keyword_arm_confidence / metadata_boost_gate + SearchResult.relational_pinned (+48 over master's peel); +12: #4681 Page.updated_at_iso + keyset cursor precision docs; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: public page revision fields; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: typed vector pool and readiness metadata; merged company ingestion/schema routing changes; retired provider integration removed; +1 write-path wave: 'created' effective-date source; +3 read-path wave: rerank_failed degraded stage + budget reason (closed vocabularies) and its recall classification note; +8 fw3-search: SearchOpts.source_boosts + keyword_arm_failed/title_arm_failed stages; +2 wave-2 W4: ChunkInput.embedding_input_hash (#5553); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +2 at the merge; evidence delivery: optional SearchResult.delivered (+2; shape in search/evidence-delivery.ts); +2 eval wave N1-3: OntologyReadOpts.visibility (remote world-only ontology reads); +4 #5827: GraphNode.source_id and GraphPath from_source_id/to_source_id; +2 #5824: SearchOpts.vectorLegacyGuard rollback switch; +7 #5154: PageFilters.listColumnsOnly (interface field); +11 Foundations 1 F1b: WriteAttributionView + AttributedPageVersion (get_versions / get_write_attribution read shapes)
src/core/minions/queue.ts 2522 ratchet grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; security: durable queued authority and confined filesystem dispatch; master integration: grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: durable authority and delegated admission both enforced; typed readiness, configuration-blocked lifecycle and bounded release; +9: prune archives completed dream synthesis keys
-src/commands/init.ts 1932 ratchet grown v0.46.x keyless capability notices; grown db-availability loop: initPostgresCore typed-failure extraction + --prefer-postgres ladder hook + pgvector rethrow fix; +1 at megawave/wave-k merge; +master-merge true-up; wave-k: merge; #3753 --force re-init engine-preservation guard; +1 wave-k merge-union brace (--prefer-postgres close); +10 ambient-writeback WP8: runWritebackNudge consent ask in both engine epilogues (logic lives in core/onboard/writeback-nudge.ts); +4: v0.48.2 reranker readiness at init + test seam; +1: v0.48.2 provider normalization; +3: v0.48.2 review fixes; master integration: +2: preserve typed PGLite busy errors in schema-only init; shared-skills integration on company-ingestion base; retired provider integration removed; retain stored-vector identity on re-init
+src/commands/init.ts 1934 ratchet grown v0.46.x keyless capability notices; grown db-availability loop: initPostgresCore typed-failure extraction + --prefer-postgres ladder hook + pgvector rethrow fix; +1 at megawave/wave-k merge; +master-merge true-up; wave-k: merge; #3753 --force re-init engine-preservation guard; +1 wave-k merge-union brace (--prefer-postgres close); +10 ambient-writeback WP8: runWritebackNudge consent ask in both engine epilogues (logic lives in core/onboard/writeback-nudge.ts); +4: v0.48.2 reranker readiness at init + test seam; +1: v0.48.2 provider normalization; +3: v0.48.2 review fixes; master integration: +2: preserve typed PGLite busy errors in schema-only init; shared-skills integration on company-ingestion base; retired provider integration removed; retain stored-vector identity on re-init; +2: E8 fresh-install migration stamping in both engine epilogues (logic lives in commands/migrations/fresh-install.ts)
src/commands/integrations.ts 1739 ratchet grown v0.46.26.0 megawave (#4039 connector compat) + 1 nosemgrep dataflow annotation (path-traversal audit); wave-k: exported heartbeatPath seam (#3900)
src/core/minions/handlers/subagent.ts 1918 ratchet merged: master v131 settle rework + dream-wave C5 peel + C6 accounting + C7 lease heartbeats/lost-lease aborts + C9 oneshot dispatch + adversarial fix batches; grown by #4078 subagent-loop capability fix; +6 lines (reasoning-item replay: adaptContentBlocksToChatBlocks handles 'reasoning' blocks); +3 wave G #4514: Anthropic-via-OpenRouter allowed on the subagent loop; +36 lines (code review, same PR): isPromptTooLongError walks a bounded .cause chain so it still matches post-normalizeAIError() wrapping, plus extractPromptTooLongDetail so the dead-lettered job's error carries the matched provider detail instead of the generic normalizeAIError() wrapper text; master integration: harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; #5105: +13 call-site wiring to shared tool-write-identity helper across fresh and replay dispatch
src/commands/bootstrap.ts 2142 ratchet grandfathered at merge (grew past the 1500 cap on master); raised for #4066 HOME_WORKSPACE_GUARD_EXEMPT (status/uninstall/harness); +5 for the harnessDetect test seam (bulk lives in core/bootstrap/harness.ts); +23 for the contract subcommand dispatcher glue (#4105 absorb — bulk lives in core/bootstrap/contract.ts); +codex hooks-consent gate + mcp+hooks receipt registration + uninstall arm; +42 ambient-writeback WP8: interview-time SURFACE_MULTIUSER audience apply (pre-init ordering) + applyDeclaredAudienceFromInterview; +3 #4897 harness usage clause documenting --source ID semantics; +5 #5878: --refresh-skills dispatch and usage lines (logic in core/bootstrap/harness-skills.ts); +11 #5488: SUBCOMMAND_HELP harness entry (gate on --help / -h / help) — CLI help line, cannot move; +11 #4618 seat: --seat/--no-seat help lines and the runHooks parse (parse + notes live in core/bootstrap/hooks.ts parseSeatFlags)
diff --git a/src/commands/apply-migrations.ts b/src/commands/apply-migrations.ts
index 017bbe3151..41617b07d9 100644
--- a/src/commands/apply-migrations.ts
+++ b/src/commands/apply-migrations.ts
@@ -27,8 +27,12 @@ import { migrations, compareVersions, type Migration, type OrchestratorOpts } fr
import {
indexCompletedEntries,
statusForVersion as ledgerStatusForVersion,
+ freshInstallVersion,
+ isFreshInstallStamp,
+ isPendingFreshInstall,
MAX_CONSECUTIVE_PARTIALS,
} from '../core/migration-ledger.ts';
+import { shellQuote } from '../core/agent-output.ts';
interface ApplyMigrationsArgs {
list: boolean;
@@ -113,7 +117,11 @@ Usage:
--confirm-quiesced Attest old writers and skill servers are stopped.
--backup-confirmed Attest an operational backup was verified by you.
--acknowledge-no-backup Explicitly proceed without a verified backup.
- gbrain apply-migrations --list Show applied + pending migrations.
+ gbrain apply-migrations --list [--json]
+ Show applied + pending migrations.
+ pending_fresh_install = setup work a
+ brain created by gbrain init has not
+ run yet (expected; apply with --yes).
gbrain apply-migrations --migration vX.Y.Z
Force-run a specific migration by version.
gbrain apply-migrations --force-retry vX.Y.Z
@@ -151,13 +159,15 @@ Exit codes:
interface CompletedIndex {
byVersion: Map<string, CompletedMigrationEntry[]>;
+ /** The version whose `gbrain init` created this brain (fresh-install stamps), or null. */
+ freshVersion: string | null;
}
// Ledger status logic moved to src/core/migration-ledger.ts (shared with the
// get_health op's migrations block, TODOS:4063) — same semantics, same Bug 3
// "complete wins / trailing retry overrides / consecutive-partial cap" rules.
function indexCompleted(entries: CompletedMigrationEntry[]): CompletedIndex {
- return { byVersion: indexCompletedEntries(entries) };
+ return { byVersion: indexCompletedEntries(entries), freshVersion: freshInstallVersion(entries) };
}
function statusForVersion(
@@ -171,6 +181,8 @@ interface Plan {
applied: Migration[];
partial: Migration[];
pending: Migration[];
+ /** Never run on a brain gbrain init created at or after its version: expected setup work, not an interrupted upgrade. */
+ pending_fresh_install: Migration[];
skippedFuture: Migration[];
wedged: Migration[];
}
@@ -182,6 +194,8 @@ interface Plan {
* - partial: has only `status: "partial"` entries (stopgap wrote one) →
* orchestrator runs to finish missing phases.
* - pending: has no entries at all and migration.version ≤ installed VERSION.
+ * - pending_fresh_install: pending, on a brain `gbrain init` created at or
+ * after this version (fresh-install stamps). Runs like pending.
* - skippedFuture: migration.version > installed VERSION (binary is older
* than the migration; wait for a newer install).
*
@@ -189,7 +203,7 @@ interface Plan {
* skip v0.11.0 when running v0.11.1. Compare against completed.jsonl.
*/
function buildPlan(idx: CompletedIndex, installed: string, filterVersion?: string): Plan {
- const plan: Plan = { applied: [], partial: [], pending: [], skippedFuture: [], wedged: [] };
+ const plan: Plan = { applied: [], partial: [], pending: [], pending_fresh_install: [], skippedFuture: [], wedged: [] };
for (const m of migrations) {
if (filterVersion && m.version !== filterVersion) continue;
if (compareVersions(m.version, installed) > 0) {
@@ -200,6 +214,7 @@ function buildPlan(idx: CompletedIndex, installed: string, filterVersion?: strin
if (status === 'complete') plan.applied.push(m);
else if (status === 'partial') plan.partial.push(m);
else if (status === 'wedged') plan.wedged.push(m);
+ else if (isPendingFreshInstall(m.version, idx.freshVersion)) plan.pending_fresh_install.push(m);
else plan.pending.push(m);
}
return plan;
@@ -225,33 +240,64 @@ function formatDbProbeLine(probe: DbProbeOutcome): string {
return `Database: not probed (${probe.reason})`;
}
-function printList(plan: Plan, installed: string, dbProbe: DbProbeOutcome): void {
- console.log(`Installed gbrain version: ${installed}`);
- console.log(`${formatDbProbeLine(dbProbe)}\n`);
- console.log(' Status Version Headline');
- console.log(' ------- -------- -----------------------------------------');
- const rows: Array<{ status: string; m: Migration }> = [
+const FINISH_SETUP_ARGV = ['gbrain', 'apply-migrations', '--yes', '--no-autopilot-install'];
+
+function listRows(plan: Plan): Array<{ status: string; m: Migration }> {
+ return [
...plan.applied.map(m => ({ status: 'applied', m })),
...plan.partial.map(m => ({ status: 'partial', m })),
...plan.wedged.map(m => ({ status: 'wedged', m })),
...plan.pending.map(m => ({ status: 'pending', m })),
+ ...plan.pending_fresh_install.map(m => ({ status: 'pending_fresh_install', m })),
...plan.skippedFuture.map(m => ({ status: 'future', m })),
];
+}
+
+function printList(plan: Plan, installed: string, dbProbe: DbProbeOutcome): void {
+ console.log(`Installed gbrain version: ${installed}`);
+ console.log(`${formatDbProbeLine(dbProbe)}\n`);
+ console.log(' Status Version Headline');
+ console.log(' --------------------- -------- -----------------------------------------');
+ const rows = listRows(plan);
for (const r of rows) {
const ver = r.m.version.padEnd(8);
- const status = r.status.padEnd(7);
+ const status = r.status.padEnd(21);
console.log(` ${status} ${ver} ${r.m.featurePitch.headline}`);
}
if (rows.length === 0) console.log(' (no migrations registered)');
console.log('');
const needsWork = plan.pending.length + plan.partial.length;
- if (needsWork === 0) {
+ const setup = plan.pending_fresh_install.length;
+ if (needsWork === 0 && setup === 0) {
console.log('All migrations up to date.');
- } else {
- console.log(`${needsWork} migration(s) need action. Run \`gbrain apply-migrations --yes\` to apply.`);
+ return;
+ }
+ if (needsWork > 0) console.log(`${needsWork} migration(s) need action. Run \`gbrain apply-migrations --yes\` to apply.`);
+ if (setup > 0) {
+ console.log(`${setup} setup migration(s) are pending_fresh_install: this brain was created by gbrain init and has not run them yet. `
+ + `This is expected setup work, not a failed upgrade. Finish setup: ${shellQuote(FINISH_SETUP_ARGV)}`);
}
}
+/** `--list --json`: one row per registered migration plus the command that completes outstanding work. */
+function printListJson(plan: Plan, idx: CompletedIndex, installed: string, dbProbe: DbProbeOutcome): void {
+ const outstanding = plan.pending.length + plan.partial.length + plan.pending_fresh_install.length;
+ console.log(JSON.stringify({
+ installed,
+ database: dbProbe,
+ fresh_install_version: idx.freshVersion,
+ migrations: listRows(plan).map(r => ({
+ version: r.m.version,
+ status: r.status,
+ headline: r.m.featurePitch.headline,
+ ...(r.status === 'applied' && (idx.byVersion.get(r.m.version) ?? []).some(isFreshInstallStamp) ? { fresh_install: true } : {}),
+ })),
+ needs_action: plan.pending.length + plan.partial.length,
+ pending_fresh_install: plan.pending_fresh_install.length,
+ ...(outstanding > 0 ? { next: { argv: FINISH_SETUP_ARGV, command: shellQuote(FINISH_SETUP_ARGV) } } : {}),
+ }));
+}
+
function printDryRun(plan: Plan, installed: string, dbProbe: DbProbeOutcome): void {
console.log(`Dry run — installed gbrain version: ${installed}`);
console.log(formatDbProbeLine(dbProbe));
@@ -271,12 +317,17 @@ function printDryRun(plan: Plan, installed: string, dbProbe: DbProbeOutcome): vo
for (const m of plan.pending) console.log(` → v${m.version} — ${m.featurePitch.headline}`);
console.log('');
}
+ if (plan.pending_fresh_install.length) {
+ console.log('Would APPLY (pending_fresh_install — setup a brain created by gbrain init has not run yet; expected, not a failed upgrade):');
+ for (const m of plan.pending_fresh_install) console.log(` → v${m.version} — ${m.featurePitch.headline}`);
+ console.log('');
+ }
if (plan.skippedFuture.length) {
console.log('Skipped (newer than installed binary):');
for (const m of plan.skippedFuture) console.log(` ⧗ v${m.version}`);
console.log('');
}
- if (plan.pending.length + plan.partial.length === 0) {
+ if (plan.pending.length + plan.partial.length + plan.pending_fresh_install.length === 0) {
console.log('Nothing to do.');
} else {
console.log('Re-run without --dry-run to apply. Use --yes to skip prompts.');
@@ -546,7 +597,7 @@ async function runLockedMigrations(
// Don't exit — applied/partial/pending are still worth reporting and running.
}
- if (cli.specificMigration && plan.applied.length + plan.partial.length + plan.pending.length + plan.skippedFuture.length === 0) {
+ if (cli.specificMigration && plan.applied.length + plan.partial.length + plan.pending.length + plan.pending_fresh_install.length + plan.skippedFuture.length === 0) {
console.error(`No migration registered with version "${cli.specificMigration}". Run \`gbrain apply-migrations --list\` to see registered versions.`);
return 2;
}
@@ -554,10 +605,11 @@ async function runLockedMigrations(
// #4364: --require-db turns an unreachable DB into a hard failure instead
// of a filesystem-only plan that renders identically to a clean database.
const listExit = cli.requireDb && dbProbe.status === 'unreachable' ? 1 : 0;
+ if (cli.list && cli.json) { printListJson(plan, idx, installed, dbProbe); return listExit; }
if (cli.list) { printList(plan, installed, dbProbe); return listExit; }
if (cli.dryRun) {
const previews: Array<{ version: string; preview?: unknown; error?: string }> = [];
- for (const migration of [...plan.applied, ...plan.partial, ...plan.pending, ...plan.wedged]) {
+ for (const migration of [...plan.applied, ...plan.partial, ...plan.pending, ...plan.pending_fresh_install, ...plan.wedged]) {
if (!migration.preview) continue;
try { previews.push({ version: migration.version, preview: await migration.preview(orchestratorOptsFrom(cli)) }); }
catch (error) { previews.push({ version: migration.version, error: error instanceof Error ? error.message : 'Inventory unavailable.' }); }
@@ -579,7 +631,7 @@ async function runLockedMigrations(
// preflight above created the table, so take the lease before orchestrating.
await holdLock();
- const toRun: Migration[] = [...plan.partial, ...plan.pending, ...plan.applied.filter(migration => migration.reconcile)]
+ const toRun: Migration[] = [...plan.partial, ...plan.pending, ...plan.pending_fresh_install, ...plan.applied.filter(migration => migration.reconcile)]
.sort((left, right) => compareVersions(left.version, right.version));
if (toRun.length === 0) {
if (schemaBehind) {
@@ -592,7 +644,7 @@ async function runLockedMigrations(
console.log('All migrations up to date.');
return 0;
}
- if (!schemaBehind && plan.pending.length === 0 && plan.partial.length === 0) {
+ if (!schemaBehind && plan.pending.length === 0 && plan.pending_fresh_install.length === 0 && plan.partial.length === 0) {
console.log('All migrations up to date. This covers orchestrator checkpoints only; host publication and client activation are being rechecked.');
}
@@ -612,6 +664,7 @@ async function runLockedMigrations(
console.log(`\n=== Applying migration v${m.version}: ${m.featurePitch.headline} ===`);
try {
const result = await m.orchestrator(orchestratorOptsFrom(cli, heldLock()?.leaseToken));
+ for (const p of result.phases) if (p.argv) console.log(` ${p.name} — next step: ${shellQuote(p.argv)}`);
if (result.status === 'failed' || result.phases.some(p => p.status === 'failed')) {
console.error(result.status === 'failed'
? `Migration v${m.version} reported status=failed.`
diff --git a/src/commands/init.ts b/src/commands/init.ts
index f835e31770..e3870589a8 100644
--- a/src/commands/init.ts
+++ b/src/commands/init.ts
@@ -1239,6 +1239,7 @@ export async function initPGLite(opts: {
config.protocol_installed_at = config.protocol_installed_at ?? new Date().toISOString();
preserveConversionConfig(false);
saveConfig(config);
+ if (freshContentDatabase) (await import('./migrations/fresh-install.ts')).recordFreshInstallMigrations();
const contentReceipt = await setupSharedBrainContent({ engine, config, sourceId: await resolveSourceId(engine, undefined), remote: false, dryRun: false, logger: { info: console.error, warn: console.error, error: console.error } }, {
...opts.content, fresh: freshContentDatabase,
...(process.env.GBRAIN_IN_AGENT_SETUP === '1' && !opts.content?.root ? { root: join(dirname(configPath()), '..', 'memory') } : {}),
@@ -1582,6 +1583,7 @@ export async function initPostgresCore(opts: {
config.protocol_installed_at = config.protocol_installed_at ?? new Date().toISOString();
preserveConversionConfig(false);
saveConfig(config);
+ if (freshContentDatabase) (await import('./migrations/fresh-install.ts')).recordFreshInstallMigrations();
const contentReceipt = await setupSharedBrainContent({ engine, config, sourceId: await resolveSourceId(engine, undefined), remote: false, dryRun: false, logger: { info: console.error, warn: console.error, error: console.error } }, { ...opts.content, fresh: freshContentDatabase });
if (!opts.jsonOutput) console.error(`[init] Content: ${contentReceipt.root ?? contentReceipt.repository_kind} (${contentReceipt.repository_kind}; ${contentReceipt.status}). ${contentReceipt.pending_actions.join(' ')}`);
console.log('Config saved to ~/.gbrain/config.json');
diff --git a/src/commands/migrations/fresh-install.ts b/src/commands/migrations/fresh-install.ts
new file mode 100644
index 0000000000..ac80671457
--- /dev/null
+++ b/src/commands/migrations/fresh-install.ts
@@ -0,0 +1,54 @@
+/**
+ * Fresh-install migration stamping (agent-first operator wave, E8).
+ *
+ * A brain `gbrain init` just created is already at the current schema, so a
+ * migration that declares `fresh_install_noop: true` has nothing to do there:
+ * init records it complete with `fresh_install: true` and the creating
+ * version. Every other registered migration stays unrun and lists as
+ * `pending_fresh_install` (src/core/migration-ledger.ts), which
+ * `gbrain apply-migrations --yes` completes. Called once by init, only when
+ * the database was created by this init (never on re-init of an existing one).
+ */
+
+import { VERSION } from '../../version.ts';
+import { appendCompletedMigration } from '../../core/preferences.ts';
+import { compareVersions } from '../../core/migration-ledger.ts';
+import { migrations } from './index.ts';
+
+export interface FreshInstallStamp {
+ installed_version: string;
+ stamped: string[];
+ pending_fresh_install: string[];
+}
+
+export function stampFreshInstallMigrations(installed: string = VERSION.replace(/^v/, '').trim()): FreshInstallStamp {
+ const receipt: FreshInstallStamp = { installed_version: installed, stamped: [], pending_fresh_install: [] };
+ for (const migration of migrations) {
+ if (compareVersions(migration.version, installed) > 0) continue;
+ if (!migration.fresh_install_noop) {
+ receipt.pending_fresh_install.push(migration.version);
+ continue;
+ }
+ appendCompletedMigration({
+ version: migration.version,
+ status: 'complete',
+ fresh_install: true,
+ installed_version: installed,
+ phases: [{ name: 'fresh_install', status: 'skipped', detail: `No-op on a brain gbrain init created at v${installed}: schema current, nothing to backfill or install.` }],
+ });
+ receipt.stamped.push(migration.version);
+ }
+ return receipt;
+}
+
+/** The init seam: stamp, then print one line. Fail-open: an unwritable ledger leaves every migration pending, which apply-migrations still completes. */
+export function recordFreshInstallMigrations(): void {
+ try {
+ const receipt = stampFreshInstallMigrations();
+ const pending = receipt.pending_fresh_install;
+ console.error(`[init] Migrations: ${receipt.stamped.length} recorded as not needed on a new brain; `
+ + (pending.length ? `${pending.length} setup migration(s) pending (${pending.join(', ')}). Finish setup: gbrain apply-migrations --yes --no-autopilot-install` : 'none pending.'));
+ } catch (error) {
+ console.error(`[init] Migrations: could not record fresh-install migrations (${error instanceof Error ? error.message : String(error)}); all list as pending. Finish setup: gbrain apply-migrations --yes --no-autopilot-install`);
+ }
+}
diff --git a/src/commands/migrations/shared-content.ts b/src/commands/migrations/shared-content.ts
index fdcf1fe475..c5be6f4696 100644
--- a/src/commands/migrations/shared-content.ts
+++ b/src/commands/migrations/shared-content.ts
@@ -5,9 +5,13 @@ import type { Migration } from './types.ts';
import type { OrchestratorOpts } from './types.ts';
import { exportDatabaseContent } from '../../core/shared-skills/migration-export.ts';
import { PgliteBusyError } from '../../core/pglite-lock.ts';
+import { shellQuote } from '../../core/agent-output.ts';
export const SHARED_CONTENT_MIGRATION_VERSION = '0.53.0';
+/** Read-only: prints every source's remaining stage, its reason and the command for it (`pending_actions`). */
+export const SHARED_CONTENT_INSPECT_ARGV = ['gbrain', 'apply-migrations', '--migration', SHARED_CONTENT_MIGRATION_VERSION, '--dry-run', '--json'];
+
export async function inspectSharedContentMigration(dryRun: boolean, exportOptions?: OrchestratorOpts['dbOnlyExport']): Promise<SharedMigrationReport | null> {
const config = loadConfig();
if (!config) return null;
@@ -44,13 +48,16 @@ export const sharedContentMigration: Migration = {
const report = await inspectSharedContentMigration(options.dryRun, options.dbOnlyExport);
if (!report) return { version: SHARED_CONTENT_MIGRATION_VERSION, status: 'complete', phases: [{ name: 'inventory', status: 'skipped', detail: 'No brain configured.' }] };
const pending = report.status === 'action_required' || report.status === 'conflict';
- console.error(`[shared-skills] ${report.status}. ${report.sources.filter(source => source.status !== 'complete').length} source(s) need host action; no grants or bundle consent changed.`);
+ console.error(`[shared-skills] ${report.status}. ${report.sources.filter(source => source.status !== 'complete').length} source(s) need host action; no grants or bundle consent changed.`
+ + (pending ? ` Inspect each source's next step: ${shellQuote(SHARED_CONTENT_INSPECT_ARGV)}` : ''));
for (const source of report.sources) for (const phase of source.stages) {
if (phase.status === 'action_required' || phase.status === 'conflict') console.error(`[shared-skills] ${source.source_id}: ${phase.reason}`);
}
for (const action of report.pending_actions) console.error(`[shared-skills] ${action}`);
return { version: SHARED_CONTENT_MIGRATION_VERSION, status: report.status === 'conflict' ? 'partial' : 'complete',
- phases: [{ name: 'content-checkpoints', status: 'complete', detail: pending ? 'Mechanical inventory is durable; publication and enrollment are NOT complete. Per-source actions remain in shared_skills.migration.v1.' : 'Source checkpoints verified.' }],
+ phases: [{ name: 'content-checkpoints', status: 'complete', ...(pending
+ ? { detail: 'Mechanical inventory is durable; publication and enrollment are NOT complete. Per-source actions remain in shared_skills.migration.v1.', argv: SHARED_CONTENT_INSPECT_ARGV }
+ : { detail: 'Source checkpoints verified.' }) }],
pending_host_work: pending ? 1 : 0 };
} catch (error) {
if (error instanceof PgliteBusyError) throw error;
diff --git a/src/commands/migrations/types.ts b/src/commands/migrations/types.ts
index 3e33bba21e..6c4500cb06 100644
--- a/src/commands/migrations/types.ts
+++ b/src/commands/migrations/types.ts
@@ -46,6 +46,8 @@ export interface OrchestratorPhaseResult {
name: string;
status: 'complete' | 'skipped' | 'failed';
detail?: string;
+ /** The exact command that resolves or inspects what this phase left open; printed by the runner and kept in the ledger. */
+ argv?: string[];
}
export interface OrchestratorResult {
@@ -67,4 +69,13 @@ export interface Migration {
orchestrator: (opts: OrchestratorOpts) => Promise<OrchestratorResult>;
preview?: (opts: OrchestratorOpts) => Promise<unknown>;
reconcile?: boolean;
+ /**
+ * True only when the orchestrator changes nothing on a brain `gbrain init`
+ * just created: schema already current, no data to backfill, no files,
+ * preferences or services to write. Init records these as complete
+ * (`fresh_install: true` ledger entries, `./fresh-install.ts`); every other
+ * migration lists as `pending_fresh_install` until it runs. Each flagged
+ * migration is proven by test/migrations-fresh-install-audit.serial.test.ts.
+ */
+ fresh_install_noop?: true;
}
diff --git a/src/commands/migrations/v0_12_0.ts b/src/commands/migrations/v0_12_0.ts
index 55c3c2137d..68d353dbe3 100644
--- a/src/commands/migrations/v0_12_0.ts
+++ b/src/commands/migrations/v0_12_0.ts
@@ -11,7 +11,8 @@
*
* Phases (all idempotent; resumable from a prior status:"partial" run):
* A. Schema — gbrain init --migrate-only (applies v8/v9/v10).
- * B. Config — verify auto_link is not explicitly disabled. If it's
+ * B. Config — verify auto_link is not explicitly disabled (read
+ * in-process, file/env plane then database). If it's
* set to false, leave it alone (user intent) but warn.
* C. Backfill — gbrain extract links --source db (idempotent; the
* UNIQUE constraint on (from, to, link_type) guarantees
@@ -34,6 +35,8 @@ import { execSync } from 'child_process';
import { gbrainChildCommand, runGbrainSubprocess } from './in-process.ts';
import type { Migration, OrchestratorOpts, OrchestratorResult, OrchestratorPhaseResult } from './types.ts';
import { childGlobalFlags } from '../../core/cli-options.ts';
+import { loadConfig, toEngineConfig } from '../../core/config.ts';
+import { createEngine } from '../../core/engine-factory.ts';
// Bug 3 — ledger writes moved to the runner (apply-migrations.ts).
// ── Phase A — Schema ────────────────────────────────────────
@@ -61,18 +64,35 @@ interface ConfigCheckResult {
raw?: string;
}
-function phaseBConfigCheck(opts: OrchestratorOpts): OrchestratorPhaseResult & { autoLink: ConfigCheckResult } {
+/**
+ * Reads `auto_link` in-process the way `gbrain config get` resolves it: the
+ * file/env plane wins over the database plane. Unset means enabled
+ * (isAutoLinkEnabled's default). Never spawns a CLI child.
+ */
+async function readAutoLink(): Promise<string> {
+ const config = loadConfig();
+ if (!config) return '';
+ const fileValue = (config as unknown as Record<string, unknown>).auto_link;
+ if (fileValue !== undefined && fileValue !== null) return String(fileValue).trim();
+ const engine = await createEngine(toEngineConfig(config));
+ try {
+ await engine.connect(toEngineConfig(config));
+ return (await engine.getConfig('auto_link'))?.trim() ?? '';
+ } finally {
+ await engine.disconnect().catch(() => {});
+ }
+}
+
+async function phaseBConfigCheck(opts: OrchestratorOpts): Promise<OrchestratorPhaseResult & { autoLink: ConfigCheckResult }> {
if (opts.dryRun) {
return { name: 'config', status: 'skipped', detail: 'dry-run', autoLink: { status: 'unknown' } };
}
- // gbrain config get auto_link returns the raw value (or empty if unset).
- // Default behavior when unset = enabled (per isAutoLinkEnabled).
let raw = '';
+ let unreadable = '';
try {
- raw = execSync(gbrainChildCommand('gbrain config get auto_link'), { encoding: 'utf-8', timeout: 10_000, env: process.env }).trim();
- } catch {
- // get exits non-zero when the key isn't set — that's fine, defaults to enabled.
- raw = '';
+ raw = await readAutoLink();
+ } catch (e) {
+ unreadable = ` (could not read auto_link: ${e instanceof Error ? e.message : String(e)}; default applies)`;
}
const lc = raw.toLowerCase();
const disabled = ['false', '0', 'no', 'off'].includes(lc);
@@ -84,7 +104,7 @@ function phaseBConfigCheck(opts: OrchestratorOpts): OrchestratorPhaseResult & {
console.log(' Note: auto_link is explicitly disabled (config: auto_link=' + raw + ').');
console.log(' Skipping backfill phases. Re-enable with: gbrain config set auto_link true');
}
- return { name: 'config', status: 'complete', detail: result.status, autoLink: result };
+ return { name: 'config', status: 'complete', detail: result.status + unreadable, autoLink: result };
}
// ── Phases C/D — Backfill (links + timeline) ────────────────
@@ -197,7 +217,7 @@ async function orchestrator(opts: OrchestratorOpts): Promise<OrchestratorResult>
}
// B. Config check
- const b = phaseBConfigCheck(opts);
+ const b = await phaseBConfigCheck(opts);
phases.push({ name: b.name, status: b.status, detail: b.detail });
const autoLinkDisabled = b.autoLink.status === 'disabled';
@@ -237,6 +257,7 @@ function finalizeResult(phases: OrchestratorPhaseResult[], status: 'complete' |
export const v0_12_0: Migration = {
version: '0.12.0',
+ fresh_install_noop: true,
featurePitch: {
headline: 'Knowledge Graph wires itself — every page write extracts typed links automatically',
description:
@@ -250,3 +271,6 @@ export const v0_12_0: Migration = {
},
orchestrator,
};
+
+/** Exported for unit tests. */
+export const __testing = { phaseBConfigCheck };
diff --git a/src/commands/migrations/v0_12_2.ts b/src/commands/migrations/v0_12_2.ts
index 27ae984f95..946590aa6f 100644
--- a/src/commands/migrations/v0_12_2.ts
+++ b/src/commands/migrations/v0_12_2.ts
@@ -125,6 +125,7 @@ function finalizeResult(phases: OrchestratorPhaseResult[], status: 'complete' |
export const v0_12_2: Migration = {
version: '0.12.2',
+ fresh_install_noop: true,
featurePitch: {
headline: 'Postgres frontmatter queries now work — JSONB double-encode bug fixed and existing rows auto-repaired',
description:
diff --git a/src/commands/migrations/v0_13_0.ts b/src/commands/migrations/v0_13_0.ts
index 181b460a97..fd0f36bd7b 100644
--- a/src/commands/migrations/v0_13_0.ts
+++ b/src/commands/migrations/v0_13_0.ts
@@ -147,6 +147,7 @@ function finalizeResult(phases: OrchestratorPhaseResult[], status: 'complete' |
export const v0_13_0: Migration = {
version: '0.13.0',
+ fresh_install_noop: true,
featurePitch: {
headline: 'Frontmatter becomes a graph — company, investors, attendees now create typed edges automatically',
description:
diff --git a/src/commands/migrations/v0_13_1.ts b/src/commands/migrations/v0_13_1.ts
index 628a7e414e..0fad9d4000 100644
--- a/src/commands/migrations/v0_13_1.ts
+++ b/src/commands/migrations/v0_13_1.ts
@@ -389,6 +389,7 @@ function appendRollbackBatch(
export const v0_13_1: Migration = {
version: '0.13.1',
+ fresh_install_noop: true,
featurePitch: {
headline: 'BrainWriter integrity + grandfather protection for existing pages.',
description:
diff --git a/src/commands/migrations/v0_16_0.ts b/src/commands/migrations/v0_16_0.ts
index 66b81a1b3e..51e9396d54 100644
--- a/src/commands/migrations/v0_16_0.ts
+++ b/src/commands/migrations/v0_16_0.ts
@@ -120,6 +120,7 @@ function finalize(phases: OrchestratorPhaseResult[], status: 'complete' | 'parti
export const v0_16_0: Migration = {
version: '0.16.0',
+ fresh_install_noop: true,
featurePitch: {
headline: 'Durable LLM agents land in the brain — survive crashes, sleeps, and worker restarts.',
description:
diff --git a/src/commands/migrations/v0_18_0.ts b/src/commands/migrations/v0_18_0.ts
index 93e8751f74..4f495d127d 100644
--- a/src/commands/migrations/v0_18_0.ts
+++ b/src/commands/migrations/v0_18_0.ts
@@ -215,6 +215,7 @@ function finalize(phases: OrchestratorPhaseResult[], status: 'complete' | 'parti
export const v0_18_0: Migration = {
version: '0.18.0',
+ fresh_install_noop: true,
featurePitch: {
headline: 'Multi-source brains: one database, many knowledge repos. Federation flag keeps them from polluting each other.',
description:
diff --git a/src/commands/migrations/v0_18_1.ts b/src/commands/migrations/v0_18_1.ts
index 61f057b180..35f09c187b 100644
--- a/src/commands/migrations/v0_18_1.ts
+++ b/src/commands/migrations/v0_18_1.ts
@@ -53,6 +53,7 @@ async function orchestrator(opts: OrchestratorOpts): Promise<OrchestratorResult>
export const v0_18_1: Migration = {
version: '0.18.1',
+ fresh_install_noop: true,
featurePitch: {
headline: 'Row Level Security hardened on all public tables + escape hatch.',
description:
diff --git a/src/commands/migrations/v0_21_0.ts b/src/commands/migrations/v0_21_0.ts
index c994f7db45..7cfc9a4110 100644
--- a/src/commands/migrations/v0_21_0.ts
+++ b/src/commands/migrations/v0_21_0.ts
@@ -128,6 +128,7 @@ function finalizeResult(
export const v0_21_0: Migration = {
version: '0.21.0',
+ fresh_install_noop: true,
featurePitch: {
headline: 'Code Cathedral II — chunk-grain FTS, qualified symbols, structural edges, 165-language lazy-load',
description:
diff --git a/src/commands/migrations/v0_29_1.ts b/src/commands/migrations/v0_29_1.ts
index 2c22fb4948..46007364f8 100644
--- a/src/commands/migrations/v0_29_1.ts
+++ b/src/commands/migrations/v0_29_1.ts
@@ -147,6 +147,7 @@ function finalize(phases: OrchestratorPhaseResult[], status: 'complete' | 'parti
export const v0_29_1: Migration = {
version: '0.29.1',
+ fresh_install_noop: true,
featurePitch: {
headline: 'Recency + salience as two opt-in axes — agent in charge of when to use each',
description:
diff --git a/src/commands/migrations/v0_31_0.ts b/src/commands/migrations/v0_31_0.ts
index 5588f69b6f..e6bb2bfe66 100644
--- a/src/commands/migrations/v0_31_0.ts
+++ b/src/commands/migrations/v0_31_0.ts
@@ -116,6 +116,7 @@ async function orchestrator(opts: OrchestratorOpts): Promise<OrchestratorResult>
export const v0_31_0: Migration = {
version: '0.31.0',
+ fresh_install_noop: true,
featurePitch: {
headline: 'Hot memory ships — your brain remembers what you said today, across sessions',
description:
diff --git a/src/commands/migrations/v0_32_2.ts b/src/commands/migrations/v0_32_2.ts
index 7b4272be66..6cb3391c21 100644
--- a/src/commands/migrations/v0_32_2.ts
+++ b/src/commands/migrations/v0_32_2.ts
@@ -600,6 +600,7 @@ function finalizeResult(
export const v0_32_2: Migration = {
version: '0.32.2',
+ fresh_install_noop: true,
featurePitch: {
headline: 'Facts join the system-of-record — your hot memory now lives in markdown, indexed by the DB',
description:
diff --git a/src/commands/migrations/v0_43_0.ts b/src/commands/migrations/v0_43_0.ts
index e8c3370919..7de221cc8f 100644
--- a/src/commands/migrations/v0_43_0.ts
+++ b/src/commands/migrations/v0_43_0.ts
@@ -23,6 +23,7 @@ async function orchestrator(_opts: OrchestratorOpts): Promise<OrchestratorResult
export const v0_43_0: Migration = {
version: '0.43.0',
+ fresh_install_noop: true,
featurePitch: {
headline:
'Five memory verbs — recall, remember, entity, synthesize, forget — are now the agent-facing memory protocol (MEMORY_VERBS v1).',
diff --git a/src/commands/migrations/v0_46_3.ts b/src/commands/migrations/v0_46_3.ts
index 7e4489f637..af8c952a08 100644
--- a/src/commands/migrations/v0_46_3.ts
+++ b/src/commands/migrations/v0_46_3.ts
@@ -2,6 +2,7 @@ import type { Migration } from './types.ts';
export const v0_46_3: Migration = {
version: '0.46.3',
+ fresh_install_noop: true,
featurePitch: {
headline: 'Embedding provider migration is available with an explicit cost preview.',
description: 'Use gbrain migrate embeddings --status to inspect the stored identity and --dry-run to preview an explicit migration. No provider or vectors change automatically.',
diff --git a/src/commands/migrations/v0_60_31.ts b/src/commands/migrations/v0_60_31.ts
index 3835313666..3e154fa744 100644
--- a/src/commands/migrations/v0_60_31.ts
+++ b/src/commands/migrations/v0_60_31.ts
@@ -70,6 +70,7 @@ async function orchestrator(opts: OrchestratorOpts): Promise<OrchestratorResult>
export const v0_60_31: Migration = {
version: '0.60.31',
+ fresh_install_noop: true,
featurePitch: {
headline: 'Stored private keys no longer reach search chunks or delivered evidence, and Google connector files are written private.',
description: 'Pages whose body holds a private key are withheld from search until they are re-chunked with the key replaced by a <REDACTED:private_key_pem> token. This migration re-chunks them with no provider calls; run `gbrain embed --stale` afterwards to embed the new chunks. Stored page bodies are unchanged. '
diff --git a/src/core/migration-ledger.ts b/src/core/migration-ledger.ts
index 4336cb06ad..4b273a777c 100644
--- a/src/core/migration-ledger.ts
+++ b/src/core/migration-ledger.ts
@@ -82,6 +82,30 @@ export function statusForVersion(
return 'pending';
}
+/** A ledger entry `gbrain init` wrote for a `fresh_install_noop` migration (src/commands/migrations/fresh-install.ts). */
+export function isFreshInstallStamp(entry: CompletedMigrationEntry): boolean {
+ return entry.fresh_install === true;
+}
+
+/**
+ * The gbrain version that created this brain, read from init's fresh-install
+ * stamps; null for a brain created before stamping existed. A pending
+ * migration at or below it is `pending_fresh_install`: setup work the new
+ * brain has not run yet, never an interrupted upgrade.
+ */
+export function freshInstallVersion(entries: CompletedMigrationEntry[]): string | null {
+ let latest: string | null = null;
+ for (const entry of entries) {
+ if (!isFreshInstallStamp(entry) || typeof entry.installed_version !== 'string') continue;
+ if (latest === null || compareVersions(entry.installed_version, latest) > 0) latest = entry.installed_version;
+ }
+ return latest;
+}
+
+export function isPendingFreshInstall(version: string, freshVersion: string | null): boolean {
+ return freshVersion !== null && compareVersions(version, freshVersion) <= 0;
+}
+
export function indexCompletedEntries(
entries: CompletedMigrationEntry[],
): Map<string, CompletedMigrationEntry[]> {
@@ -95,8 +119,13 @@ export function indexCompletedEntries(
}
export interface MigrationLedgerSummary {
- /** Registered migrations ≤ installed version with no ledger completion. */
+ /** Registered migrations ≤ installed version with no ledger completion (upgrade work). */
pending: string[];
+ /**
+ * Not yet run on a brain `gbrain init` created at or after their version:
+ * expected setup work (`gbrain apply-migrations --yes`), not a broken upgrade.
+ */
+ pending_fresh_install: string[];
/** Started but unfinished (some phases recorded partial). */
partial: string[];
/** Hit the consecutive-partial cap — needs an explicit forced retry. */
@@ -118,15 +147,17 @@ export interface MigrationLedgerSummary {
* migration internals.
*/
export function migrationLedgerSummary(installedVersion: string): MigrationLedgerSummary {
- const byVersion = indexCompletedEntries(loadCompletedMigrations());
- const summary: MigrationLedgerSummary = { pending: [], partial: [], wedged: [], skipped_future: 0 };
+ const entries = loadCompletedMigrations();
+ const byVersion = indexCompletedEntries(entries);
+ const freshVersion = freshInstallVersion(entries);
+ const summary: MigrationLedgerSummary = { pending: [], pending_fresh_install: [], partial: [], wedged: [], skipped_future: 0 };
for (const version of MIGRATION_VERSIONS) {
if (compareVersions(version, installedVersion) > 0) {
summary.skipped_future += 1;
continue;
}
const status = statusForVersion(version, byVersion);
- if (status === 'pending') summary.pending.push(version);
+ if (status === 'pending') (isPendingFreshInstall(version, freshVersion) ? summary.pending_fresh_install : summary.pending).push(version);
else if (status === 'partial') summary.partial.push(version);
else if (status === 'wedged') summary.wedged.push(version);
}
diff --git a/src/core/ops/admin.ts b/src/core/ops/admin.ts
index 6278f9cf18..172735d42c 100644
--- a/src/core/ops/admin.ts
+++ b/src/core/ops/admin.ts
@@ -52,7 +52,7 @@ const get_health: Operation = {
mutating: false,
idempotent: true,
outputRedaction: 'no_stored_text',
- description: 'Brain health dashboard (embed coverage, stale pages, orphans) — remote callers see counters confined to their source grant. Includes a `migrations {pending, partial, wedged, skipped_future}` block from the host migration ledger so remote agents can detect wedged/outstanding host migrations without shelling into the brain host. `computed_at` is when the counters were read: a repeat call within `health.cache_ttl_ms` (default 30000; env GBRAIN_HEALTH_CACHE_TTL_MS; 0 disables) with no page or config change returns the memoized numbers.',
+ description: 'Brain health dashboard (embed coverage, stale pages, orphans) — remote callers see counters confined to their source grant. Includes a `migrations {pending, pending_fresh_install, partial, wedged, skipped_future}` block from the host migration ledger so remote agents can detect wedged/outstanding host migrations without shelling into the brain host (pending_fresh_install = setup a new brain has not run yet, not a broken upgrade). `computed_at` is when the counters were read: a repeat call within `health.cache_ttl_ms` (default 30000; env GBRAIN_HEALTH_CACHE_TTL_MS; 0 disables) with no page or config change returns the memoized numbers.',
params: {},
handler: async (ctx) => {
// The `migrations` block below stays GLOBAL for scoped callers by
diff --git a/src/core/types.ts b/src/core/types.ts
index 9f8c610d27..0a237fd67b 100644
--- a/src/core/types.ts
+++ b/src/core/types.ts
@@ -1785,7 +1785,7 @@ export interface BrainHealth {
*/
schema_version?: '1';
migrations?:
- | { pending: string[]; partial: string[]; wedged: string[]; skipped_future: number }
+ | { pending: string[]; pending_fresh_install: string[]; partial: string[]; wedged: string[]; skipped_future: number }
| { error: 'ledger_unreadable' };
}
diff --git a/test/migration-ledger.test.ts b/test/migration-ledger.test.ts
index 30c2915702..72315de517 100644
--- a/test/migration-ledger.test.ts
+++ b/test/migration-ledger.test.ts
@@ -126,7 +126,7 @@ describe('get_health op layer (dispatchToolCall, real PGLiteEngine)', () => {
const STDIO = { remote: true, transport: 'stdio' as const, sourceId: 'default' };
- test('migrations block carries the four ledger keys', async () => {
+ test('migrations block carries the five ledger keys', async () => {
const { dispatchToolCall } = await import('../src/mcp/dispatch.ts');
// GBRAIN_HOME is a PARENT dir — configDir() appends '.gbrain' itself.
const home = mkdtempSync(join(tmpdir(), 'gbrain-ledger-op-'));
@@ -136,9 +136,10 @@ describe('get_health op layer (dispatchToolCall, real PGLiteEngine)', () => {
expect(res.isError ?? false).toBe(false);
const body = JSON.parse(res.content[0].text) as {
page_count: number;
- migrations: { pending: string[]; partial: string[]; wedged: string[]; skipped_future: number };
+ migrations: { pending: string[]; pending_fresh_install: string[]; partial: string[]; wedged: string[]; skipped_future: number };
};
- expect(Object.keys(body.migrations).sort()).toEqual(['partial', 'pending', 'skipped_future', 'wedged'].sort());
+ expect(Object.keys(body.migrations).sort()).toEqual(['partial', 'pending', 'pending_fresh_install', 'skipped_future', 'wedged'].sort());
+ expect(Array.isArray(body.migrations.pending_fresh_install)).toBe(true);
expect(Array.isArray(body.migrations.pending)).toBe(true);
expect(Array.isArray(body.migrations.partial)).toBe(true);
expect(Array.isArray(body.migrations.wedged)).toBe(true);