@nanobpm/urban-pr-review-codefirst 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +141 -0
- package/components/review-round.json +69 -0
- package/db/migrations/001_init.sql +46 -0
- package/db/migrations/002_transcript.sql +7 -0
- package/db/migrations/003_open_escalation.sql +8 -0
- package/deno.json +22 -0
- package/deno.lock +77 -0
- package/main.ts +352 -0
- package/nano-generated/app-pages.ts +676 -0
- package/nano-generated/data-cli.ts +552 -0
- package/nano-generated/data-sdk.ts +536 -0
- package/nano-generated/domain-rows.d.ts +87 -0
- package/nano-generated/domain-types.ts +1418 -0
- package/nano-generated/domain.ts +36 -0
- package/nano-generated/llm-worker.ts +403 -0
- package/nano-generated/message-io.d.ts +17 -0
- package/nano-generated/messages.ts +26 -0
- package/nano-generated/meta.ts +18 -0
- package/nano-generated/node-deno-shim.mjs +250 -0
- package/nano-generated/node-loader.mjs +60 -0
- package/nano-generated/node-register.mjs +11 -0
- package/nano-generated/worker-io.d.ts +28 -0
- package/nano-generated/worker-sdk.ts +468 -0
- package/nano-generated/workers.ts +29 -0
- package/nano.app.json +17 -0
- package/nanobpm.project.json +22 -0
- package/package.json +28 -0
- package/pages/home.page.json +127 -0
- package/prompts/review-round.md +119 -0
- package/scripts/answer.ts +20 -0
- package/scripts/purge-db.ts +70 -0
- package/scripts/review-ready.ts +20 -0
- package/scripts/submit.ts +32 -0
- package/tsconfig.json +14 -0
- package/workflows/convergence-loop.ts +299 -0
|
@@ -0,0 +1,552 @@
|
|
|
1
|
+
// nanobpmn datasource CLI (Deno-preferred, Node-capable) — ADR 0024 phase-2
|
|
2
|
+
// (DB Manager gateway); dual-runtime per ADR 0036/0038.
|
|
3
|
+
//
|
|
4
|
+
// Materialised verbatim to <project>/nano-generated/data-cli.ts next to data-sdk.ts.
|
|
5
|
+
// The Rust console server invokes it as a one-shot subprocess to serve the
|
|
6
|
+
// console **Data** panel (Tables / SQL / Migrations). It is the panel's bridge
|
|
7
|
+
// to the datasource seam: every operation runs THROUGH `@nanobpm/data`
|
|
8
|
+
// (`./data-sdk.ts`), so the panel browses whatever the named datasource
|
|
9
|
+
// currently resolves to — embedded SQLite in the IDE, a server DB in
|
|
10
|
+
// production once a `nano-ide-data-*` driver pack is installed — never a
|
|
11
|
+
// parallel, SQLite-only path (ADR 0024 §4).
|
|
12
|
+
//
|
|
13
|
+
// Protocol: a single JSON request object is read from stdin; a single JSON
|
|
14
|
+
// response object is written to stdout and the process exits 0. Handled errors
|
|
15
|
+
// are reported as `{ ok: false, error }` (still exit 0) so the caller can parse
|
|
16
|
+
// them; only an unreadable request exits non-zero. The process cwd is the
|
|
17
|
+
// project root, so `openDataSource`/`listSources` discover `nano.app.json`
|
|
18
|
+
// there and file-backed sources resolve against it.
|
|
19
|
+
//
|
|
20
|
+
// Request: { op, source?, sql?, params?, statements? }
|
|
21
|
+
// op = "sources" | "schema" | "query" | "exec" | "script" | "migrations"
|
|
22
|
+
// | "migrate" | "domaintypes"
|
|
23
|
+
|
|
24
|
+
import { listSources, manifestTypes, manifestWorkers, openDataSource, type WorkerDecl } from "./data-sdk.ts";
|
|
25
|
+
import {
|
|
26
|
+
DOMAIN_BINDINGS,
|
|
27
|
+
DOMAIN_DTS,
|
|
28
|
+
DOMAIN_MODEL_JSON,
|
|
29
|
+
type DomainTypeDef,
|
|
30
|
+
type DomainTypeRegistry,
|
|
31
|
+
emitDomainBindings,
|
|
32
|
+
emitDomainModel,
|
|
33
|
+
emitDomainModelJson,
|
|
34
|
+
emitMessageBindings,
|
|
35
|
+
emitMessageBindingsRuntime,
|
|
36
|
+
emitMeta,
|
|
37
|
+
emitWorkerBindings,
|
|
38
|
+
emitWorkerBindingsRuntime,
|
|
39
|
+
GEN_DIR,
|
|
40
|
+
MESSAGE_BINDINGS_DTS,
|
|
41
|
+
MESSAGE_BINDINGS_TS,
|
|
42
|
+
type MessageBindingDecl,
|
|
43
|
+
META_TS,
|
|
44
|
+
type MetaDecl,
|
|
45
|
+
resolveShapes,
|
|
46
|
+
type ShapeDecl,
|
|
47
|
+
type SourceSchema,
|
|
48
|
+
WORKER_BINDINGS_DTS,
|
|
49
|
+
WORKER_BINDINGS_TS,
|
|
50
|
+
} from "./domain-types.ts";
|
|
51
|
+
|
|
52
|
+
interface Request {
|
|
53
|
+
op: string;
|
|
54
|
+
source?: string;
|
|
55
|
+
sql?: string;
|
|
56
|
+
params?: unknown[];
|
|
57
|
+
statements?: string[];
|
|
58
|
+
/** `domaintypes`: also write `nano-generated/domain-rows.d.ts` (default true). */
|
|
59
|
+
write?: boolean;
|
|
60
|
+
/**
|
|
61
|
+
* `domaintypes`: the model-derived worker-IO map (`taskType -> {in,out}`),
|
|
62
|
+
* scanned from the process models by the server (ADR 0040 slice 1 / ADR 0033
|
|
63
|
+
* §6 increment 12). When present, it is the authoritative source of each
|
|
64
|
+
* worker's envelope types; it is overlaid on the manifest `workers[]` (which
|
|
65
|
+
* still carries non-IO bindings such as `llm`). Absent → fall back to the
|
|
66
|
+
* manifest projection alone.
|
|
67
|
+
*/
|
|
68
|
+
derivedWorkers?: WorkerDecl[];
|
|
69
|
+
/**
|
|
70
|
+
* `domaintypes`: the model-derived message-payload map (`messageName ->
|
|
71
|
+
* {in,out}`), scanned from the process models' `bpmn:message` envelopes by the
|
|
72
|
+
* server (ADR 0040 slice 2). It is authoritative for the typed `publishMessage`
|
|
73
|
+
* registry (there is no manifest projection for messages, unlike `workers[]`),
|
|
74
|
+
* so it is emitted directly. Absent → no message registry is derived.
|
|
75
|
+
*/
|
|
76
|
+
derivedMessages?: MessageBindingDecl[];
|
|
77
|
+
/**
|
|
78
|
+
* `domaintypes`: the model-derived composed shapes (`nano:shape` declarations),
|
|
79
|
+
* scanned from the process models by the server (ADR 0040 §9/§10). Each is
|
|
80
|
+
* resolved through the fuse into a flat domain type and folded into the manifest
|
|
81
|
+
* `types` registry, so a composed shape becomes a first-class `DomainTypes` entry
|
|
82
|
+
* every consumer types against. Absent → no shapes are resolved.
|
|
83
|
+
*/
|
|
84
|
+
derivedShapes?: ShapeDecl[];
|
|
85
|
+
/**
|
|
86
|
+
* `domaintypes`: the model-derived model-level metadata (`nano:meta` key/value
|
|
87
|
+
* siblings of `nano:shapes`), scanned from the process models by the server (ADR
|
|
88
|
+
* 0040 §5). Folded into the typed `meta.ts` accessor (`@nanobpm/meta`) and the
|
|
89
|
+
* structured fuse (`domain.json`), tagged with `model:<processId>` provenance.
|
|
90
|
+
* Absent → no metadata is derived.
|
|
91
|
+
*/
|
|
92
|
+
derivedMeta?: MetaDecl[];
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* Overlay the model-derived worker-IO map onto the manifest `workers[]`. The
|
|
97
|
+
* model is authoritative for the envelope (`inputType`/`outputType`), so every
|
|
98
|
+
* scanned `taskType` takes its I/O from `derived` (clearing a stale manifest
|
|
99
|
+
* value when the model carries none); manifest entries the scan did not cover
|
|
100
|
+
* (e.g. a worker declared only for an `llm` binding, with no service task) are
|
|
101
|
+
* preserved. New `taskType`s seen only in the model are appended.
|
|
102
|
+
*/
|
|
103
|
+
export function overlayDerivedWorkerIo(
|
|
104
|
+
manifest: WorkerDecl[],
|
|
105
|
+
derived: WorkerDecl[],
|
|
106
|
+
): WorkerDecl[] {
|
|
107
|
+
const byType = new Map<string, WorkerDecl>();
|
|
108
|
+
for (const w of manifest) byType.set(w.taskType, { ...w });
|
|
109
|
+
for (const d of derived) {
|
|
110
|
+
const existing = byType.get(d.taskType);
|
|
111
|
+
const merged: WorkerDecl = existing
|
|
112
|
+
? { ...existing, taskType: d.taskType }
|
|
113
|
+
: { taskType: d.taskType };
|
|
114
|
+
if (d.inputType) merged.inputType = d.inputType;
|
|
115
|
+
else delete merged.inputType;
|
|
116
|
+
if (d.outputType) merged.outputType = d.outputType;
|
|
117
|
+
else delete merged.outputType;
|
|
118
|
+
// Header keys are authored on the model, so the derived set is authoritative:
|
|
119
|
+
// replace (not union) the manifest's, and clear when the model declares none.
|
|
120
|
+
if (d.headerKeys && d.headerKeys.length > 0) merged.headerKeys = [...d.headerKeys];
|
|
121
|
+
else delete merged.headerKeys;
|
|
122
|
+
byType.set(d.taskType, merged);
|
|
123
|
+
}
|
|
124
|
+
return [...byType.values()];
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
// Runtime adapter (ADR 0036/0038): the host calls that differ between Deno
|
|
128
|
+
// (`Deno.*`) and Node (`process` / `node:fs`). The DB Manager gateway runs under
|
|
129
|
+
// whichever runtime the console picked — Deno preferred, Node >= 22.6 fallback
|
|
130
|
+
// (32-bit ARM ships no Deno build). `data-sdk.ts` already carries the same shim
|
|
131
|
+
// for SQLite/`node:sqlite`; this closes the gateway's own host calls (stdin,
|
|
132
|
+
// readDir, readTextFile, exit) so the Data panel works with no Deno present.
|
|
133
|
+
interface DirEntry {
|
|
134
|
+
name: string;
|
|
135
|
+
isFile: boolean;
|
|
136
|
+
}
|
|
137
|
+
interface CliRuntime {
|
|
138
|
+
readStdin(): Promise<string>;
|
|
139
|
+
readDir(dir: string): Promise<DirEntry[]>;
|
|
140
|
+
readTextFile(path: string): Promise<string>;
|
|
141
|
+
mkdir(path: string): Promise<void>;
|
|
142
|
+
writeTextFile(path: string, data: string): Promise<void>;
|
|
143
|
+
exit(code: number): never;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
function concatDecode(chunks: Uint8Array[]): string {
|
|
147
|
+
let len = 0;
|
|
148
|
+
for (const c of chunks) len += c.length;
|
|
149
|
+
const buf = new Uint8Array(len);
|
|
150
|
+
let off = 0;
|
|
151
|
+
for (const c of chunks) {
|
|
152
|
+
buf.set(c, off);
|
|
153
|
+
off += c.length;
|
|
154
|
+
}
|
|
155
|
+
return new TextDecoder().decode(buf);
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
const RT: CliRuntime = ((): CliRuntime => {
|
|
159
|
+
const g = globalThis as unknown as {
|
|
160
|
+
Deno?: {
|
|
161
|
+
stdin: { readable: ReadableStream<Uint8Array> };
|
|
162
|
+
readDir(dir: string): AsyncIterable<{ name: string; isFile: boolean }>;
|
|
163
|
+
readTextFile(p: string): Promise<string>;
|
|
164
|
+
exit(code: number): never;
|
|
165
|
+
};
|
|
166
|
+
process?: { stdin: AsyncIterable<Uint8Array>; exit(code: number): never };
|
|
167
|
+
};
|
|
168
|
+
if (g.Deno) {
|
|
169
|
+
const d = g.Deno as typeof g.Deno & {
|
|
170
|
+
mkdir(p: string, o: { recursive: boolean }): Promise<void>;
|
|
171
|
+
writeTextFile(p: string, data: string): Promise<void>;
|
|
172
|
+
};
|
|
173
|
+
return {
|
|
174
|
+
readStdin: async () => {
|
|
175
|
+
const chunks: Uint8Array[] = [];
|
|
176
|
+
const reader = d.stdin.readable.getReader();
|
|
177
|
+
for (;;) {
|
|
178
|
+
const { done, value } = await reader.read();
|
|
179
|
+
if (done) break;
|
|
180
|
+
if (value) chunks.push(value);
|
|
181
|
+
}
|
|
182
|
+
return concatDecode(chunks);
|
|
183
|
+
},
|
|
184
|
+
readDir: async (dir) => {
|
|
185
|
+
const out: DirEntry[] = [];
|
|
186
|
+
for await (const e of d.readDir(dir)) out.push({ name: e.name, isFile: e.isFile });
|
|
187
|
+
return out;
|
|
188
|
+
},
|
|
189
|
+
readTextFile: (p) => d.readTextFile(p),
|
|
190
|
+
mkdir: (p) => d.mkdir(p, { recursive: true }),
|
|
191
|
+
writeTextFile: (p, data) => d.writeTextFile(p, data),
|
|
192
|
+
exit: (c) => d.exit(c),
|
|
193
|
+
};
|
|
194
|
+
}
|
|
195
|
+
const p = g.process!;
|
|
196
|
+
return {
|
|
197
|
+
readStdin: async () => {
|
|
198
|
+
const chunks: Uint8Array[] = [];
|
|
199
|
+
for await (const c of p.stdin) chunks.push(c as Uint8Array);
|
|
200
|
+
return concatDecode(chunks);
|
|
201
|
+
},
|
|
202
|
+
readDir: async (dir) => {
|
|
203
|
+
const { readdir } = await import("node:fs/promises");
|
|
204
|
+
const ents = await readdir(dir, { withFileTypes: true });
|
|
205
|
+
return ents.map((e) => ({ name: e.name, isFile: e.isFile() }));
|
|
206
|
+
},
|
|
207
|
+
readTextFile: async (path) => (await import("node:fs/promises")).readFile(path, "utf8"),
|
|
208
|
+
mkdir: async (path) => {
|
|
209
|
+
await (await import("node:fs/promises")).mkdir(path, { recursive: true });
|
|
210
|
+
},
|
|
211
|
+
writeTextFile: async (path, data) => {
|
|
212
|
+
await (await import("node:fs/promises")).writeFile(path, data, "utf8");
|
|
213
|
+
},
|
|
214
|
+
exit: (c) => p.exit(c),
|
|
215
|
+
};
|
|
216
|
+
})();
|
|
217
|
+
|
|
218
|
+
/// JSON can't carry a bigint (SQLite INTEGER/rowid may exceed 2^53). Coerce any
|
|
219
|
+
/// bigint a driver returns to a Number when it is safe, else a decimal string,
|
|
220
|
+
/// recursively, so the response always serialises.
|
|
221
|
+
function jsonSafe(v: unknown): unknown {
|
|
222
|
+
if (typeof v === "bigint") {
|
|
223
|
+
return v >= BigInt(Number.MIN_SAFE_INTEGER) && v <= BigInt(Number.MAX_SAFE_INTEGER)
|
|
224
|
+
? Number(v)
|
|
225
|
+
: v.toString();
|
|
226
|
+
}
|
|
227
|
+
if (v instanceof Uint8Array) return { $blob: v.length };
|
|
228
|
+
if (Array.isArray(v)) return v.map(jsonSafe);
|
|
229
|
+
if (v && typeof v === "object") {
|
|
230
|
+
const out: Record<string, unknown> = {};
|
|
231
|
+
for (const [k, val] of Object.entries(v)) out[k] = jsonSafe(val);
|
|
232
|
+
return out;
|
|
233
|
+
}
|
|
234
|
+
return v;
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/// The union of keys seen across the result rows, in first-seen order — the
|
|
238
|
+
/// column set a grid renders. SQLite's `.all()` omits a column set for an empty
|
|
239
|
+
/// result, so an empty query yields `[]`; that is honest for a table browser.
|
|
240
|
+
function columnsOf(rows: Record<string, unknown>[]): string[] {
|
|
241
|
+
const seen = new Set<string>();
|
|
242
|
+
const cols: string[] = [];
|
|
243
|
+
for (const r of rows) {
|
|
244
|
+
for (const k of Object.keys(r)) {
|
|
245
|
+
if (!seen.has(k)) {
|
|
246
|
+
seen.add(k);
|
|
247
|
+
cols.push(k);
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
return cols;
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
const MIGRATIONS_TABLE = "_nano_migrations";
|
|
255
|
+
|
|
256
|
+
/// Split a migration file into individual statements on `;` boundaries,
|
|
257
|
+
/// dropping blank and comment-only fragments. A minimal splitter for the
|
|
258
|
+
/// common DDL case (ADR 0024's "minimal dialect stance"); it does not parse
|
|
259
|
+
/// semicolons inside string literals.
|
|
260
|
+
function splitStatements(sql: string): string[] {
|
|
261
|
+
return sql
|
|
262
|
+
.split(";")
|
|
263
|
+
.map((s) => s.trim())
|
|
264
|
+
.filter((s) => s.length > 0 && !s.split("\n").every((l) => l.trim().startsWith("--")));
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
async function migrationDir(source: string): Promise<string> {
|
|
268
|
+
const { sources, default: def } = await listSources();
|
|
269
|
+
const name = source || def || sources[0]?.name;
|
|
270
|
+
const src = sources.find((s) => s.name === name);
|
|
271
|
+
return src?.migrations ?? "db/migrations";
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
/// Ordered `*.sql` files in the source's migrations directory (empty when the
|
|
275
|
+
/// directory is absent — a project may declare no migrations).
|
|
276
|
+
async function listMigrationFiles(dir: string): Promise<string[]> {
|
|
277
|
+
const names: string[] = [];
|
|
278
|
+
try {
|
|
279
|
+
for (const e of await RT.readDir(dir)) {
|
|
280
|
+
if (e.isFile && e.name.endsWith(".sql")) names.push(e.name);
|
|
281
|
+
}
|
|
282
|
+
} catch { // no migrations directory — treat as an empty set
|
|
283
|
+
}
|
|
284
|
+
names.sort();
|
|
285
|
+
return names;
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
/// Apply a source's not-yet-applied `*.sql` migrations, in filename order, each
|
|
289
|
+
/// in its own transaction, recording every applied file in the migrations
|
|
290
|
+
/// table. Returns the names applied (empty when already up to date). Idempotent.
|
|
291
|
+
///
|
|
292
|
+
/// Shared by the `migrate` op and the `domaintypes` regen: the latter introspects
|
|
293
|
+
/// the *live* schema (`db.schema()`), so on a fresh DB a regen that runs before
|
|
294
|
+
/// `migrate` would introspect zero tables and emit an empty `Domain` (only
|
|
295
|
+
/// `raw`+`close`). Ensuring the schema is migrated first keeps codegen and the DB
|
|
296
|
+
/// in step.
|
|
297
|
+
async function applyPendingMigrations(source: string | undefined): Promise<string[]> {
|
|
298
|
+
const dir = await migrationDir(source ?? "");
|
|
299
|
+
const files = await listMigrationFiles(dir);
|
|
300
|
+
const db = await openDataSource(source);
|
|
301
|
+
try {
|
|
302
|
+
await db.exec(
|
|
303
|
+
`CREATE TABLE IF NOT EXISTS ${MIGRATIONS_TABLE} (name TEXT PRIMARY KEY, applied_at TEXT NOT NULL)`,
|
|
304
|
+
);
|
|
305
|
+
const done = new Set(
|
|
306
|
+
(await db.query(`SELECT name FROM ${MIGRATIONS_TABLE}`)).map((r) =>
|
|
307
|
+
String(r.name)
|
|
308
|
+
),
|
|
309
|
+
);
|
|
310
|
+
const applied: string[] = [];
|
|
311
|
+
for (const name of files) {
|
|
312
|
+
if (done.has(name)) continue;
|
|
313
|
+
const sql = await RT.readTextFile(`${dir}/${name}`);
|
|
314
|
+
await db.tx(async (t) => {
|
|
315
|
+
for (const stmt of splitStatements(sql)) await t.exec(stmt);
|
|
316
|
+
await t.exec(
|
|
317
|
+
`INSERT INTO ${MIGRATIONS_TABLE} (name, applied_at) VALUES (?, ?)`,
|
|
318
|
+
[name, new Date().toISOString()],
|
|
319
|
+
);
|
|
320
|
+
});
|
|
321
|
+
applied.push(name);
|
|
322
|
+
}
|
|
323
|
+
return applied;
|
|
324
|
+
} finally {
|
|
325
|
+
db.close();
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
async function run(req: Request): Promise<unknown> {
|
|
330
|
+
switch (req.op) {
|
|
331
|
+
case "sources": {
|
|
332
|
+
const { sources, default: def } = await listSources();
|
|
333
|
+
return { default: def, sources };
|
|
334
|
+
}
|
|
335
|
+
case "schema": {
|
|
336
|
+
const db = await openDataSource(req.source);
|
|
337
|
+
return { tables: await db.schema() };
|
|
338
|
+
}
|
|
339
|
+
case "query": {
|
|
340
|
+
const db = await openDataSource(req.source);
|
|
341
|
+
const rows = (await db.query(req.sql ?? "", req.params ?? [])) as Record<
|
|
342
|
+
string,
|
|
343
|
+
unknown
|
|
344
|
+
>[];
|
|
345
|
+
return { columns: columnsOf(rows), rows: jsonSafe(rows) };
|
|
346
|
+
}
|
|
347
|
+
case "exec": {
|
|
348
|
+
const db = await openDataSource(req.source);
|
|
349
|
+
const r = await db.exec(req.sql ?? "", req.params ?? []);
|
|
350
|
+
return jsonSafe(r);
|
|
351
|
+
}
|
|
352
|
+
case "script": {
|
|
353
|
+
// Run several statements atomically in one transaction — the console's
|
|
354
|
+
// structure editor uses this for the SQLite 12-step table rebuild
|
|
355
|
+
// (create → copy → drop → rename), so a mid-rebuild failure rolls back
|
|
356
|
+
// and leaves the table untouched. Statements come pre-split from the
|
|
357
|
+
// caller; `?`-params are not threaded (DDL needs none).
|
|
358
|
+
const db = await openDataSource(req.source);
|
|
359
|
+
const statements = Array.isArray(req.statements)
|
|
360
|
+
? req.statements
|
|
361
|
+
: splitStatements(req.sql ?? "");
|
|
362
|
+
let changed = 0;
|
|
363
|
+
await db.tx(async (t) => {
|
|
364
|
+
for (const stmt of statements) {
|
|
365
|
+
if (stmt.trim()) changed += (await t.exec(stmt)).changed;
|
|
366
|
+
}
|
|
367
|
+
});
|
|
368
|
+
return jsonSafe({ changed });
|
|
369
|
+
}
|
|
370
|
+
case "migrations": {
|
|
371
|
+
const dir = await migrationDir(req.source ?? "");
|
|
372
|
+
const files = await listMigrationFiles(dir);
|
|
373
|
+
const db = await openDataSource(req.source);
|
|
374
|
+
await db.exec(
|
|
375
|
+
`CREATE TABLE IF NOT EXISTS ${MIGRATIONS_TABLE} (name TEXT PRIMARY KEY, applied_at TEXT NOT NULL)`,
|
|
376
|
+
);
|
|
377
|
+
const applied = new Map<string, string>(
|
|
378
|
+
(await db.query(`SELECT name, applied_at FROM ${MIGRATIONS_TABLE}`)).map((
|
|
379
|
+
r,
|
|
380
|
+
) => [String(r.name), String(r.applied_at)]),
|
|
381
|
+
);
|
|
382
|
+
return {
|
|
383
|
+
dir,
|
|
384
|
+
entries: files.map((name) => ({
|
|
385
|
+
name,
|
|
386
|
+
applied: applied.has(name),
|
|
387
|
+
appliedAt: applied.get(name) ?? null,
|
|
388
|
+
})),
|
|
389
|
+
};
|
|
390
|
+
}
|
|
391
|
+
case "migrate": {
|
|
392
|
+
const applied = await applyPendingMigrations(req.source);
|
|
393
|
+
return { applied, pending: 0 };
|
|
394
|
+
}
|
|
395
|
+
case "domaintypes": {
|
|
396
|
+
// ADR 0029 §4.1/§4.2/§6: reify the domain model into TypeScript. Union
|
|
397
|
+
// *every* declared datasource (the table spine) and fold in the manifest
|
|
398
|
+
// `types` registry (transient/non-persisted shapes) so an App with
|
|
399
|
+
// multiple databases plus declared types gets one complete domain model,
|
|
400
|
+
// emit `domain-rows.d.ts`, and (unless `write:false`) materialise it to
|
|
401
|
+
// `nano-generated/domain-rows.d.ts` next to the SDK so workers type against the live
|
|
402
|
+
// DBs. cwd is the project root, so the relative path lands in the project.
|
|
403
|
+
const { default: def, sources } = await listSources();
|
|
404
|
+
// Ensure every source's schema is migrated *before* introspecting it — the
|
|
405
|
+
// domain model is derived from the live `db.schema()`, so a regen that
|
|
406
|
+
// races ahead of `migrate` on a fresh DB would emit an empty `Domain`.
|
|
407
|
+
// Gated on a real (persisting) regen: the `write:false` composer preview is
|
|
408
|
+
// latency-sensitive and must stay read-only (no DB side-effects per
|
|
409
|
+
// keystroke).
|
|
410
|
+
const migrated: Record<string, string[]> = {};
|
|
411
|
+
if (req.write !== false) {
|
|
412
|
+
for (const s of sources) {
|
|
413
|
+
const applied = await applyPendingMigrations(s.name);
|
|
414
|
+
if (applied.length) migrated[s.name] = applied;
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
const schemas: SourceSchema[] = [];
|
|
418
|
+
for (const s of sources) {
|
|
419
|
+
const db = await openDataSource(s.name);
|
|
420
|
+
try {
|
|
421
|
+
schemas.push({ source: s.name, tables: await db.schema() });
|
|
422
|
+
} finally {
|
|
423
|
+
db.close();
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
const types = await manifestTypes() as DomainTypeRegistry;
|
|
427
|
+
// Composed motion shapes (ADR 0040 §9/§10): resolve each `nano:shape` scanned
|
|
428
|
+
// from the model against the leaf fuse (DB tables + manifest types) into a flat
|
|
429
|
+
// domain type, and fold the resolved shapes into the registry *before* it feeds
|
|
430
|
+
// the domain model and the worker/message bindings. A composed shape thus becomes
|
|
431
|
+
// a first-class `DomainTypes` entry, so envelopes/workers/messages can reference
|
|
432
|
+
// it with no extra codegen path. Broken shapes are omitted; their diagnostics are
|
|
433
|
+
// returned so the panel can surface them like the `workers[]` drift warning.
|
|
434
|
+
const shapeResolution = resolveShapes(req.derivedShapes ?? [], types, schemas);
|
|
435
|
+
// Snapshot the manifest `types` *before* folding the resolved shapes, so
|
|
436
|
+
// `domain.json` can tag each entity with its true provenance (manifest vs
|
|
437
|
+
// model) — once folded they are indistinguishable in `types`.
|
|
438
|
+
const manifestTypesSnapshot: DomainTypeRegistry = { ...types };
|
|
439
|
+
const shapeEntities: { decl: ShapeDecl; def: DomainTypeDef }[] = [];
|
|
440
|
+
const shapeDeclById = new Map((req.derivedShapes ?? []).map((s) => [s.id, s]));
|
|
441
|
+
for (const [id, def] of Object.entries(shapeResolution.types)) {
|
|
442
|
+
types[id] = def;
|
|
443
|
+
shapeEntities.push({ decl: shapeDeclById.get(id) ?? { id, ops: [] }, def });
|
|
444
|
+
}
|
|
445
|
+
const text = emitDomainModel(schemas, def, types);
|
|
446
|
+
// The typed data-object accessor (`db.orders.insert(...)`, ADR 0029 §6) is
|
|
447
|
+
// generated alongside the `.d.ts` spine so workers get both the row types
|
|
448
|
+
// and the runtime gateway from one op.
|
|
449
|
+
const bindings = emitDomainBindings(schemas, def);
|
|
450
|
+
// The model-level metadata accessor (`@nanobpm/meta`, ADR 0040 §5): the
|
|
451
|
+
// `nano:meta` key/values the models declare, folded into a typed `meta.ts`.
|
|
452
|
+
const derivedMeta = req.derivedMeta ?? [];
|
|
453
|
+
const metaAccessor = emitMeta(derivedMeta);
|
|
454
|
+
// The structured Fused Domain Model (`domain.json`, ADR 0040 §1): a fast-read
|
|
455
|
+
// cache of every fused entity + metadata + diagnostics for the IDE/codegen.
|
|
456
|
+
// Computed only when persisting: it is the largest emitted artifact (every
|
|
457
|
+
// fused entity's fields + an FNV-1a hash over the whole model) and the
|
|
458
|
+
// latency-sensitive composer preview (`write:false`) consumes only `text` +
|
|
459
|
+
// `shapeDiagnostics`, so a debounced keystroke must not pay to build it.
|
|
460
|
+
// The worker-IO map (ADR 0033 §3): `taskType → {in,out}`. The model is the
|
|
461
|
+
// source of truth for the envelope, so when the server injected the
|
|
462
|
+
// model-derived map (`derivedWorkers`) it is overlaid on the manifest
|
|
463
|
+
// `workers[]` (which still carries non-IO bindings). This retires the
|
|
464
|
+
// hand-maintained projection as the authority (ADR 0040 slice 1). The
|
|
465
|
+
// runtime wrapper (`workers.ts`) is static — written verbatim.
|
|
466
|
+
const manifestW = await manifestWorkers();
|
|
467
|
+
const workers = req.derivedWorkers
|
|
468
|
+
? overlayDerivedWorkerIo(manifestW, req.derivedWorkers)
|
|
469
|
+
: manifestW;
|
|
470
|
+
const workerBindings = emitWorkerBindings(workers, Object.keys(types));
|
|
471
|
+
const workerRuntime = emitWorkerBindingsRuntime();
|
|
472
|
+
// The message-payload registry (ADR 0040 slice 2): `messageName → {in,out}`,
|
|
473
|
+
// scanned from the process models' `bpmn:message` envelopes. There is no
|
|
474
|
+
// manifest projection for messages, so the model-derived map is authoritative
|
|
475
|
+
// and emitted directly (no overlay). Feeds the typed `publishMessage`; the
|
|
476
|
+
// runtime wrapper (`messages.ts`) is static — written verbatim.
|
|
477
|
+
const messages = req.derivedMessages ?? [];
|
|
478
|
+
const messageBindings = emitMessageBindings(messages, Object.keys(types));
|
|
479
|
+
const messageRuntime = emitMessageBindingsRuntime();
|
|
480
|
+
let path: string | null = null;
|
|
481
|
+
let bindingsPath: string | null = null;
|
|
482
|
+
let workerBindingsPath: string | null = null;
|
|
483
|
+
let messageBindingsPath: string | null = null;
|
|
484
|
+
let metaPath: string | null = null;
|
|
485
|
+
let domainModelPath: string | null = null;
|
|
486
|
+
let domainModelJson: string | null = null;
|
|
487
|
+
if (req.write !== false) {
|
|
488
|
+
await RT.mkdir(GEN_DIR);
|
|
489
|
+
path = `${GEN_DIR}/${DOMAIN_DTS}`;
|
|
490
|
+
await RT.writeTextFile(path, text);
|
|
491
|
+
bindingsPath = `${GEN_DIR}/${DOMAIN_BINDINGS}`;
|
|
492
|
+
await RT.writeTextFile(bindingsPath, bindings);
|
|
493
|
+
workerBindingsPath = `${GEN_DIR}/${WORKER_BINDINGS_DTS}`;
|
|
494
|
+
await RT.writeTextFile(workerBindingsPath, workerBindings);
|
|
495
|
+
await RT.writeTextFile(`${GEN_DIR}/${WORKER_BINDINGS_TS}`, workerRuntime);
|
|
496
|
+
messageBindingsPath = `${GEN_DIR}/${MESSAGE_BINDINGS_DTS}`;
|
|
497
|
+
await RT.writeTextFile(messageBindingsPath, messageBindings);
|
|
498
|
+
await RT.writeTextFile(`${GEN_DIR}/${MESSAGE_BINDINGS_TS}`, messageRuntime);
|
|
499
|
+
metaPath = `${GEN_DIR}/${META_TS}`;
|
|
500
|
+
await RT.writeTextFile(metaPath, metaAccessor);
|
|
501
|
+
domainModelJson = emitDomainModelJson({
|
|
502
|
+
sources: schemas,
|
|
503
|
+
default: def,
|
|
504
|
+
manifestTypes: manifestTypesSnapshot,
|
|
505
|
+
shapes: shapeEntities,
|
|
506
|
+
meta: derivedMeta,
|
|
507
|
+
diagnostics: shapeResolution.diagnostics,
|
|
508
|
+
});
|
|
509
|
+
domainModelPath = `${GEN_DIR}/${DOMAIN_MODEL_JSON}`;
|
|
510
|
+
await RT.writeTextFile(domainModelPath, domainModelJson);
|
|
511
|
+
}
|
|
512
|
+
const tables = schemas.reduce((n, s) => n + s.tables.length, 0);
|
|
513
|
+
return {
|
|
514
|
+
path,
|
|
515
|
+
text,
|
|
516
|
+
tables,
|
|
517
|
+
bindingsPath,
|
|
518
|
+
bindings,
|
|
519
|
+
workerBindingsPath,
|
|
520
|
+
workerBindings,
|
|
521
|
+
messageBindingsPath,
|
|
522
|
+
messageBindings,
|
|
523
|
+
metaPath,
|
|
524
|
+
meta: metaAccessor,
|
|
525
|
+
domainModelPath,
|
|
526
|
+
domainModel: domainModelJson,
|
|
527
|
+
migrated,
|
|
528
|
+
shapeDiagnostics: shapeResolution.diagnostics,
|
|
529
|
+
};
|
|
530
|
+
}
|
|
531
|
+
default:
|
|
532
|
+
throw new Error(`unknown op "${req.op}"`);
|
|
533
|
+
}
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
async function main(): Promise<void> {
|
|
537
|
+
let req: Request;
|
|
538
|
+
try {
|
|
539
|
+
req = JSON.parse(await RT.readStdin()) as Request;
|
|
540
|
+
} catch (e) {
|
|
541
|
+
console.log(JSON.stringify({ ok: false, error: `bad request: ${(e as Error).message}` }));
|
|
542
|
+
RT.exit(1);
|
|
543
|
+
}
|
|
544
|
+
try {
|
|
545
|
+
const result = await run(req);
|
|
546
|
+
console.log(JSON.stringify({ ok: true, ...(result as object) }));
|
|
547
|
+
} catch (e) {
|
|
548
|
+
console.log(JSON.stringify({ ok: false, error: (e as Error).message }));
|
|
549
|
+
}
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
await main();
|