Skip to content

Commit fa3cfe0

Browse files
committed
feat(cli): os build says when the local dev database holds Studio customizations it leaves behind (WIP)
Claude-Session: https://claude.ai/code/session_01Utp6CbrroXG7sXSzmQs4uj Co-authored-by: Claude <noreply@anthropic.com>
1 parent 38a467f commit fa3cfe0

3 files changed

Lines changed: 217 additions & 0 deletions

File tree

‎packages/cli/src/commands/build.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,4 +4,7 @@ import Compile from './compile.js';
44

55
export default class Build extends Compile {
66
static override description = 'Compile ObjectStack configuration to JSON artifact (alias for compile)';
7+
8+
/** `os build` is what a deployment runs, so it says what the artifact leaves behind. */
9+
protected override reportsLocalCustomizations = true;
710
}

‎packages/cli/src/commands/compile.ts‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,7 @@ import { findExtensionFieldSuffixRefusals } from '../utils/extension-field-suffi
8787
// [#29051] An undeclared top-level flow cycle — the walk `os validate` step
8888
// 3a-vii runs, over the automation engine's own judge.
8989
import { findFlowCycleRefusals } from '../utils/flow-undeclared-cycle.js';
90+
import { localCustomizationNotice, readLocalCustomizations } from '../utils/local-customizations.js';
9091

9192
export default class Compile extends Command {
9293
static override description = 'Compile ObjectStack configuration to JSON artifact';
@@ -121,6 +122,13 @@ export default class Compile extends Command {
121122
}),
122123
};
123124

125+
/**
126+
* Whether the text face ends with the local-customization notice
127+
* (`utils/local-customizations.ts`). `os build` turns it on; `os compile`,
128+
* which `os dev` runs on every boot and rebuild, keeps it off.
129+
*/
130+
protected reportsLocalCustomizations = false;
131+
124132
async run(): Promise<void> {
125133
const { args, flags } = await this.parse(Compile);
126134
const timer = createTimer();
@@ -1447,6 +1455,22 @@ export default class Compile extends Command {
14471455
}
14481456
console.log('');
14491457

1458+
// A Studio customization in the local dev database is left behind by
1459+
// this artifact (ADR-0146 D2: it lives in `<base>.custom`, in the
1460+
// database). Said once, on `os build` only — the command a deployment
1461+
// runs; `os dev` compiles through `os compile` on every boot and rebuild,
1462+
// where it would be noise.
1463+
if (this.reportsLocalCustomizations) {
1464+
const notice = localCustomizationNotice(
1465+
await readLocalCustomizations({ projectRoot: process.cwd(), artifactPath }),
1466+
);
1467+
if (notice.length > 0) {
1468+
printWarning(notice[0]);
1469+
for (const line of notice.slice(1)) console.log(chalk.dim(` ${line}`));
1470+
console.log('');
1471+
}
1472+
}
1473+
14501474
} catch (error: any) {
14511475
if (isExitSignal(error)) throw error;
14521476
if (flags.json) {
Lines changed: 190 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,190 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* "Does the local dev database hold a Studio customization that this build
5+
* leaves behind?" — the question `os build` asks after it writes the artifact.
6+
*
7+
* A change saved in Studio to an item a package ships is an item of that
8+
* base's paired customization package `<base>.custom` (ADR-0146 D2, D3),
9+
* stored in the environment's database and never in `src/`. `os build` and
10+
* the scaffold's `Dockerfile` compile `src/` alone, so a developer who tuned a
11+
* view on `os dev` and then deployed lost it with no word said. ADR-0146 D2's
12+
* way to move it is the package export (`os package export`), committed and
13+
* installed on the target; this module only lets the build say so, once, at
14+
* the moment the change is left behind.
15+
*
16+
* ## Cheap, local, read-only
17+
*
18+
* No server door and no network round trip: the build reads the SQLite file
19+
* `os dev` would open — resolved by the ONE shared resolution
20+
* (`resolveProjectDatabaseUrl`, `@objectstack/runtime`), over the environment
21+
* `os dev` reads (this process's, with the project's development `.env*` files
22+
* under it, as dotenv-flow layers them, and without loading them into this
23+
* process) — opened read-only, one aggregate `SELECT` over `sys_metadata`.
24+
* A database that is not a local SQLite file (Postgres, MongoDB, libSQL, a
25+
* `:memory:` URL) is not probed: reading it would be a network round trip, so
26+
* the answer is `not_applicable` and the build prints nothing.
27+
*
28+
* ## What counts
29+
*
30+
* Every `sys_metadata` row whose `package_id` ends in the pair suffix
31+
* (`CUSTOMIZATION_PACKAGE_SUFFIX`), counted per package. Those rows are what
32+
* `os package export` carries in a pair's export; an ensured pair with no item
33+
* yet has no row here and nothing to lose, so it is not counted.
34+
*
35+
* ## Never a verdict it did not reach
36+
*
37+
* A file that cannot be read, a missing `better-sqlite3` (the optional native
38+
* driver), or a database with no `sys_metadata` table yet are told apart:
39+
* the first two answer `unknown` with the reason, the last `none` (a database
40+
* `os dev` never booted holds no customization). The build never fails on
41+
* this probe; `unknown` is printed as such, never as "nothing to export".
42+
*/
43+
44+
import { existsSync } from 'node:fs';
45+
import path from 'node:path';
46+
import dotenvFlow from 'dotenv-flow';
47+
import { CUSTOMIZATION_PACKAGE_SUFFIX } from '@objectstack/spec/kernel';
48+
49+
/** One pair package and how many stored items it holds. */
50+
export interface LocalCustomizationPackage {
51+
id: string;
52+
items: number;
53+
}
54+
55+
export type LocalCustomizationReading =
56+
/** No local SQLite file to read: a remote or in-memory database, or none created yet. */
57+
| { status: 'not_applicable' }
58+
/** Read: no stored item of any `.custom` package. */
59+
| { status: 'none'; filename: string }
60+
/** Read: these `.custom` packages hold stored items, which the build does not carry. */
61+
| { status: 'found'; filename: string; packages: LocalCustomizationPackage[] }
62+
/** The file exists but could not be read; `detail` says why. */
63+
| { status: 'unknown'; filename: string; detail: string };
64+
65+
/**
66+
* The environment `os dev` resolves its database from: this process's
67+
* variables over the project's development `.env*` files (dotenv-flow never
68+
* overrides a variable the process already has). Nothing is loaded into
69+
* `process.env`.
70+
*/
71+
export function devDatabaseEnv(
72+
projectRoot: string,
73+
processEnv: Record<string, string | undefined> = process.env,
74+
): Record<string, string | undefined> {
75+
let fromFiles: Record<string, string> = {};
76+
try {
77+
const files = dotenvFlow.listFiles({ node_env: 'development', path: projectRoot });
78+
if (files.length > 0) fromFiles = dotenvFlow.parse(files);
79+
} catch {
80+
// An unreadable `.env*` file: `os dev` loads with `silent: true` and boots
81+
// without it, so the build resolves without it too.
82+
}
83+
return { ...fromFiles, ...processEnv };
84+
}
85+
86+
/** The SQLite file a resolved database URL names, or `null` when it names none on disk. */
87+
export function localSqliteFile(
88+
url: string,
89+
sqliteFilenameFromUrl: (url: string, kind: 'sqlite' | 'sqlite-wasm') => string,
90+
): string | null {
91+
const kind = /^file:/i.test(url) ? 'sqlite' : /^wasm-sqlite:\/\//i.test(url) ? 'sqlite-wasm' : null;
92+
if (!kind) return null;
93+
let filename: string;
94+
try {
95+
filename = sqliteFilenameFromUrl(url, kind);
96+
} catch {
97+
return null;
98+
}
99+
if (!filename || filename === ':memory:' || filename.startsWith(':')) return null;
100+
return filename;
101+
}
102+
103+
/** The aggregate read: stored items per `.custom` package. */
104+
export const LOCAL_CUSTOMIZATION_QUERY =
105+
"SELECT package_id AS id, COUNT(*) AS items FROM sys_metadata WHERE package_id LIKE ? ESCAPE '\\' "
106+
+ 'GROUP BY package_id ORDER BY package_id';
107+
108+
/** `%.custom`, with LIKE's own wildcards in the suffix escaped. */
109+
function suffixPattern(): string {
110+
return `%${CUSTOMIZATION_PACKAGE_SUFFIX.replace(/[\\%_]/g, (c) => `\\${c}`)}`;
111+
}
112+
113+
/** Read the stored `.custom` items of one SQLite file. */
114+
export async function readCustomizationsFromSqlite(filename: string): Promise<LocalCustomizationReading> {
115+
if (!existsSync(filename)) return { status: 'not_applicable' };
116+
117+
let Database: any;
118+
try {
119+
Database = (await import('better-sqlite3')).default;
120+
} catch (e: any) {
121+
return { status: 'unknown', filename, detail: `better-sqlite3 is not loadable (${e?.message ?? e})` };
122+
}
123+
124+
let db: any;
125+
try {
126+
db = new Database(filename, { readonly: true, fileMustExist: true });
127+
const table = db.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'sys_metadata'").get();
128+
if (!table) return { status: 'none', filename };
129+
const rows = db.prepare(LOCAL_CUSTOMIZATION_QUERY).all(suffixPattern()) as Array<{ id: unknown; items: unknown }>;
130+
const packages = rows
131+
.filter((r) => typeof r.id === 'string' && r.id.endsWith(CUSTOMIZATION_PACKAGE_SUFFIX))
132+
.map((r) => ({ id: r.id as string, items: Number(r.items) }));
133+
return packages.length > 0 ? { status: 'found', filename, packages } : { status: 'none', filename };
134+
} catch (e: any) {
135+
return { status: 'unknown', filename, detail: e?.message ?? String(e) };
136+
} finally {
137+
try { db?.close(); } catch { /* never opened */ }
138+
}
139+
}
140+
141+
/**
142+
* Resolve the database `os dev` opens for `projectRoot` and read its stored
143+
* `.custom` items. Never throws.
144+
*/
145+
export async function readLocalCustomizations(opts: {
146+
projectRoot: string;
147+
artifactPath?: string;
148+
env?: Record<string, string | undefined>;
149+
}): Promise<LocalCustomizationReading> {
150+
let filename: string | null;
151+
try {
152+
const { resolveProjectDatabaseUrl, sqliteFilenameFromUrl } = await import('@objectstack/runtime');
153+
const { url } = resolveProjectDatabaseUrl({
154+
env: opts.env ?? devDatabaseEnv(opts.projectRoot),
155+
projectRoot: opts.projectRoot,
156+
artifactPath: opts.artifactPath,
157+
});
158+
filename = localSqliteFile(url, sqliteFilenameFromUrl);
159+
} catch {
160+
// A database selection the dev boot itself refuses: that boot reports it;
161+
// there is no file here to read.
162+
return { status: 'not_applicable' };
163+
}
164+
if (!filename) return { status: 'not_applicable' };
165+
return readCustomizationsFromSqlite(path.resolve(filename));
166+
}
167+
168+
/**
169+
* The notice lines for a reading, or `[]` when there is nothing to say. Said
170+
* once per build: what is left behind, where it lives, and the one command
171+
* that takes it out.
172+
*/
173+
export function localCustomizationNotice(reading: LocalCustomizationReading): string[] {
174+
if (reading.status === 'found') {
175+
const total = reading.packages.reduce((n, p) => n + p.items, 0);
176+
const list = reading.packages.map((p) => `${p.id} (${p.items})`).join(', ');
177+
return [
178+
`This build does not carry ${total} Studio customization${total === 1 ? '' : 's'} stored in your dev database: ${list}.`,
179+
`They live in ${reading.filename}, not in src/, so a deployment of this artifact (or the Dockerfile) does not have them.`,
180+
'Make the change in src/ to ship it with the app, or take it out as a package while `os dev` runs: `os package export`.',
181+
];
182+
}
183+
if (reading.status === 'unknown') {
184+
return [
185+
`Could not check ${reading.filename} for Studio customizations this build leaves behind (${reading.detail}).`,
186+
'A change saved in Studio is never in src/; `os package export` takes it out while `os dev` runs.',
187+
];
188+
}
189+
return [];
190+
}

0 commit comments

Comments
 (0)