Skip to content

Commit b2ec661

Browse files
committed
refactor(state): inline canonical database schemas at build
1 parent 56ffa2b commit b2ec661

26 files changed

Lines changed: 141 additions & 2885 deletions

‎docs/refactor/database-first.md‎

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -183,7 +183,7 @@ without exceptions outside doctor/import/export/debug boundaries.
183183
- [x] Keep Kysely generated types aligned after any schema change.
184184
Files: `src/state/openclaw-state-schema.sql`,
185185
`src/state/openclaw-agent-schema.sql`,
186-
`src/state/*generated*`.
186+
`src/state/*-db.generated.d.ts`.
187187
Proof: no schema change in this pass; `pnpm db:kysely:check`;
188188
`pnpm lint:kysely`.
189189
- [x] Re-run focused tests for touched stores, commands, and scripts.
@@ -296,12 +296,12 @@ The branch already has a real shared SQLite base:
296296
macOS runtime locator, CI, and public install docs all agree.
297297
- `src/state/openclaw-state-db.ts` opens `openclaw.sqlite`, sets WAL,
298298
`synchronous=NORMAL`, `busy_timeout=30000`, `foreign_keys=ON`, and applies
299-
the generated schema module derived from
299+
the build-inlined schema bytes derived from
300300
`src/state/openclaw-state-schema.sql`.
301-
- Kysely table types and runtime schema modules are generated from disposable
302-
SQLite databases created from the committed `.sql` files; runtime code no
303-
longer keeps copy-pasted schema strings for global, per-agent, or proxy
304-
capture databases.
301+
- Kysely table types are generated from disposable SQLite databases created
302+
from the committed `.sql` files. Source runs read those canonical files;
303+
packaged builds inline the same bytes, so runtime code keeps no committed
304+
copy-pasted schema strings or packaged SQL assets.
305305
- Runtime stores derive selected and inserted row types from those generated
306306
Kysely `DB` interfaces instead of shadowing SQLite row shapes by hand. Raw SQL
307307
remains limited to schema application, pragmas, and migration-only DDL.

‎scripts/build-all.mjs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ const TSDOWN_SOURCE_EXTENSIONS = [
3131
".json5",
3232
".mjs",
3333
".mts",
34+
".sql",
3435
".ts",
3536
".tsx",
3637
".yaml",

‎scripts/generate-kysely-types.mjs‎

Lines changed: 0 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -10,15 +10,11 @@ const SCHEMAS = [
1010
name: "openclaw-state",
1111
schema: "src/state/openclaw-state-schema.sql",
1212
outFile: "src/state/openclaw-state-db.generated.d.ts",
13-
schemaOutFile: "src/state/openclaw-state-schema.generated.ts",
14-
schemaExport: "OPENCLAW_STATE_SCHEMA_SQL",
1513
},
1614
{
1715
name: "openclaw-agent",
1816
schema: "src/state/openclaw-agent-schema.sql",
1917
outFile: "src/state/openclaw-agent-db.generated.d.ts",
20-
schemaOutFile: "src/state/openclaw-agent-schema.generated.ts",
21-
schemaExport: "OPENCLAW_AGENT_SCHEMA_SQL",
2218
},
2319
];
2420

@@ -118,39 +114,19 @@ function readUtf8(file) {
118114
return fs.readFileSync(file, "utf8");
119115
}
120116

121-
function generatedSchemaModule(schema) {
122-
const source = readUtf8(schema.schema).trimEnd();
123-
const literal = source.replaceAll("\\", "\\\\").replaceAll("`", "\\`").replaceAll("${", "\\${");
124-
return [
125-
"/**",
126-
" * This file was generated from the SQLite schema source.",
127-
" * Please do not edit it manually.",
128-
" */",
129-
"",
130-
`export const ${schema.schemaExport} = \`${literal}\\n\`;`,
131-
"",
132-
].join("\n");
133-
}
134-
135117
function generate(schema) {
136118
const db = new DatabaseSync(":memory:");
137119
try {
138120
db.exec(readUtf8(schema.schema));
139121
const typesSource = generateTypes(db);
140-
const schemaSource = generatedSchemaModule(schema);
141122

142123
if (verify) {
143124
if (typesSource !== readUtf8(schema.outFile)) {
144125
console.error(`${schema.outFile} is out of date. Run pnpm db:kysely:gen.`);
145126
process.exitCode = 1;
146127
}
147-
if (schemaSource !== readUtf8(schema.schemaOutFile)) {
148-
console.error(`${schema.schemaOutFile} is out of date. Run pnpm db:kysely:gen.`);
149-
process.exitCode = 1;
150-
}
151128
} else {
152129
fs.writeFileSync(schema.outFile, typesSource);
153-
fs.writeFileSync(schema.schemaOutFile, schemaSource);
154130
}
155131
} finally {
156132
db.close();

‎src/commands/backup-sqlite.test.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,10 @@ import type { RuntimeEnv } from "../runtime.js";
77
import { createLocalSqliteSnapshotProvider } from "../snapshot/local-repository.js";
88
import { OPENCLAW_AGENT_SCHEMA_VERSION } from "../state/openclaw-agent-db.js";
99
import { resolveOpenClawAgentSqlitePath } from "../state/openclaw-agent-db.paths.js";
10-
import { OPENCLAW_AGENT_SCHEMA_SQL } from "../state/openclaw-agent-schema.generated.js";
10+
import { OPENCLAW_AGENT_SCHEMA_SQL } from "../state/openclaw-agent-schema.js";
1111
import { OPENCLAW_STATE_SCHEMA_VERSION } from "../state/openclaw-state-db.js";
1212
import { resolveOpenClawStateSqlitePath } from "../state/openclaw-state-db.paths.js";
13-
import { OPENCLAW_STATE_SCHEMA_SQL } from "../state/openclaw-state-schema.generated.js";
13+
import { OPENCLAW_STATE_SCHEMA_SQL } from "../state/openclaw-state-schema.js";
1414
import {
1515
backupSqliteCreateCommand,
1616
backupSqliteListCommand,

‎src/commands/doctor-session-sqlite-recover-report.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ import {
1212
clearOpenClawAgentDatabaseOpenFailure,
1313
migrateOpenClawAgentDatabaseForMaintenance,
1414
} from "../state/openclaw-agent-db.js";
15-
import { OPENCLAW_AGENT_SCHEMA_SQL } from "../state/openclaw-agent-schema.generated.js";
15+
import { OPENCLAW_AGENT_SCHEMA_SQL } from "../state/openclaw-agent-schema.js";
1616
import { OPENCLAW_SQLITE_BUSY_TIMEOUT_MS } from "../state/openclaw-state-db.js";
1717
import {
1818
createSessionSqliteMigrationFailureIssue,

‎src/commands/doctor-state-sqlite-compact.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ import {
1414
OPENCLAW_STATE_SCHEMA_VERSION,
1515
} from "../state/openclaw-state-db.js";
1616
import { resolveOpenClawStateSqlitePath } from "../state/openclaw-state-db.paths.js";
17-
import { OPENCLAW_STATE_SCHEMA_SQL } from "../state/openclaw-state-schema.generated.js";
17+
import { OPENCLAW_STATE_SCHEMA_SQL } from "../state/openclaw-state-schema.js";
1818
import { runDoctorStateSqliteCompact } from "./doctor-state-sqlite-compact.js";
1919

2020
const tempDirs = useAutoCleanupTempDirTracker((cleanup) => {

‎src/infra/state-migrations.media-persistence.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ import {
3434
OPENCLAW_AGENT_SCHEMA_VERSION,
3535
type OpenClawAgentDatabase,
3636
} from "../state/openclaw-agent-db.js";
37-
import { OPENCLAW_AGENT_SCHEMA_SQL } from "../state/openclaw-agent-schema.generated.js";
37+
import { OPENCLAW_AGENT_SCHEMA_SQL } from "../state/openclaw-agent-schema.js";
3838
import { OPENCLAW_SQLITE_BUSY_TIMEOUT_MS } from "../state/openclaw-state-db.js";
3939
import { VERSION } from "../version.js";
4040
import { repairGatewayAgentMediaMigrationStartupFailures } from "./gateway-boot-lifecycle.js";

‎src/infra/tsdown-config.test.ts‎

Lines changed: 55 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,14 @@
11
// Covers bundling rules encoded in the root tsdown config.
22
import { readFileSync } from "node:fs";
3+
import path from "node:path";
34
import { bundledPluginRoot } from "openclaw/plugin-sdk/test-fixtures";
45
import { describe, expect, it } from "vitest";
5-
import tsdownConfig from "../../tsdown.config.ts";
6+
import tsdownConfig, {
7+
createStateSchemaInlinePlugin,
8+
STATE_SCHEMA_INLINE_PLUGIN_NAME,
9+
} from "../../tsdown.config.ts";
10+
import { OPENCLAW_AGENT_SCHEMA_SQL } from "../state/openclaw-agent-schema.js";
11+
import { OPENCLAW_STATE_SCHEMA_SQL } from "../state/openclaw-state-schema.js";
612

713
type TsdownConfigEntry = {
814
deps?: {
@@ -12,6 +18,7 @@ type TsdownConfigEntry = {
1218
entry?: Record<string, string> | string[];
1319
inputOptions?: TsdownInputOptions;
1420
outDir?: string;
21+
plugins?: Array<{ name?: string }>;
1522
};
1623

1724
type TsdownLog = {
@@ -87,6 +94,53 @@ function readAgentAuthDiscoverySource(): string {
8794
}
8895

8996
describe("tsdown config", () => {
97+
it.each([
98+
{
99+
exportName: "OPENCLAW_STATE_SCHEMA_SQL",
100+
modulePath: "src/state/openclaw-state-schema.ts",
101+
schemaPath: "src/state/openclaw-state-schema.sql",
102+
sourceValue: OPENCLAW_STATE_SCHEMA_SQL,
103+
},
104+
{
105+
exportName: "OPENCLAW_AGENT_SCHEMA_SQL",
106+
modulePath: "src/state/openclaw-agent-schema.ts",
107+
schemaPath: "src/state/openclaw-agent-schema.sql",
108+
sourceValue: OPENCLAW_AGENT_SCHEMA_SQL,
109+
},
110+
])("inlines canonical schema bytes for $modulePath", (schema) => {
111+
const rootDir = process.cwd();
112+
const watchedPaths: string[] = [];
113+
const plugin = createStateSchemaInlinePlugin(rootDir);
114+
const result = plugin.load.call(
115+
{ addWatchFile: (filePath: string) => watchedPaths.push(filePath) },
116+
path.resolve(rootDir, schema.modulePath),
117+
);
118+
const schemaPath = path.resolve(rootDir, schema.schemaPath);
119+
const canonicalSql = readFileSync(schemaPath, "utf8");
120+
121+
expect(result).not.toBeNull();
122+
const match = result?.code.match(
123+
new RegExp(`^export const ${schema.exportName} = (.*);\\n$`, "su"),
124+
);
125+
expect(match?.[1]).toBeDefined();
126+
expect(JSON.parse(match?.[1] ?? "null")).toBe(canonicalSql);
127+
expect(schema.sourceValue).toBe(canonicalSql);
128+
expect(watchedPaths).toEqual([schemaPath]);
129+
});
130+
131+
it("installs schema inlining only on the unified runtime graph", () => {
132+
const unifiedGraph = requireUnifiedDistGraph();
133+
const inlinePlugins = asConfigArray(tsdownConfig).flatMap(
134+
(config) =>
135+
config.plugins?.filter((plugin) => plugin.name === STATE_SCHEMA_INLINE_PLUGIN_NAME) ?? [],
136+
);
137+
138+
expect(unifiedGraph.plugins).toContainEqual(
139+
expect.objectContaining({ name: STATE_SCHEMA_INLINE_PLUGIN_NAME }),
140+
);
141+
expect(inlinePlugins).toHaveLength(1);
142+
});
143+
90144
it("keeps core, plugin runtime, plugin-sdk, bundled root plugins, and bundled hooks in one dist graph", () => {
91145
const distGraph = requireUnifiedDistGraph();
92146

‎src/snapshot/local-repository.test.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,9 +8,9 @@ import { requireNodeSqlite } from "../infra/node-sqlite.js";
88
import { createPrivateSqliteDirectory } from "../infra/sqlite-private-directory.js";
99
import { runExec } from "../process/exec.js";
1010
import { OPENCLAW_AGENT_SCHEMA_VERSION } from "../state/openclaw-agent-db.js";
11-
import { OPENCLAW_AGENT_SCHEMA_SQL } from "../state/openclaw-agent-schema.generated.js";
11+
import { OPENCLAW_AGENT_SCHEMA_SQL } from "../state/openclaw-agent-schema.js";
1212
import { OPENCLAW_STATE_SCHEMA_VERSION } from "../state/openclaw-state-db.js";
13-
import { OPENCLAW_STATE_SCHEMA_SQL } from "../state/openclaw-state-schema.generated.js";
13+
import { OPENCLAW_STATE_SCHEMA_SQL } from "../state/openclaw-state-schema.js";
1414
import { hashSnapshotArtifact, readSnapshotManifest } from "./manifest.js";
1515
import {
1616
SNAPSHOT_MANIFEST_FILENAME,

‎src/state/openclaw-agent-board-schema.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import type { DatabaseSync } from "node:sqlite";
2-
import { OPENCLAW_AGENT_SCHEMA_SQL } from "./openclaw-agent-schema.generated.js";
2+
import { OPENCLAW_AGENT_SCHEMA_SQL } from "./openclaw-agent-schema.js";
33

44
const BOARD_SCHEMA_START = "CREATE TABLE IF NOT EXISTS board_tabs (";
55
const BOARD_SCHEMA_END = "CREATE TABLE IF NOT EXISTS heartbeat_outcomes (";

0 commit comments

Comments
 (0)