Repository navigation
Expand file tree
/
Copy pathjson-stdout-purity.e2e.test.ts
More file actions
439 lines (415 loc) · 20.6 KB
/
Copy pathjson-stdout-purity.e2e.test.ts
File metadata and controls
439 lines (415 loc) · 20.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
/**
* `--json` ⇒ stdout is EXACTLY ONE JSON DOCUMENT, for the whole
* `bootSchemaStack` family (commit 2b641ddd4).
*
* `--json` has one audience — a program — and the commands that boot a kernel
* were handing that program a stream it could not parse. `ObjectLogger` routes
* `debug`/`info`/`warn` to **stdout** and only `error`/`fatal` to stderr, so
* `os migrate recorded-by --json` shipped ~60 INFO lines above the payload and
* the two shutdown lines below it, with stderr completely empty. The consumer's
* only recourse was a "find the last lone `{` and its matching `}`" extractor —
* #4873 was forced to write one to assert its own payload — and that heuristic
* silently picks the wrong text as soon as a log line looks like JSON.
*
* ## Why the whole family, from one expectation
*
* The contract has one implementation face per command. A file that pinned
* `migrate recorded-by` alone would go green while the others stayed broken,
* and would say nothing at all about a new one. So the family is DISCOVERED
* from the source tree — every command that calls `bootSchemaStack`, itself or
* through a `src/utils` module that does, and declares a `--json` flag — and
* the discovered set is reconciled against
* {@link FAMILY} below. Add a member and this file goes red until it is listed
* here and passes; drop one and it goes red until it is removed. The seam
* itself (`bootSchemaStack`'s required `jsonOutput` option) makes the mistake a
* compile error first; this is the runtime proof that the seam actually
* delivers the invariant.
*
* ## Deliberately an UNCOMPILED fixture
*
* No `os compile` runs here, so the project has no `dist/objectstack.json` and
* the boot announces that through `console.log`:
*
* [StandaloneStack] no compiled artifact at '…' — booting without one
*
* That line never passes through the kernel logger, so it is the second,
* independent pollution source — a fix that only quieted `ObjectLogger` would
* still leave it on stdout. Compiling the fixture would make the richer command
* payloads possible and delete that coverage; the invariant matters more.
*
* ## Diagnostics are MOVED, never destroyed
*
* Route 2 of the issue (drop the kernel to `logLevel: 'silent'` under `--json`)
* would also make stdout parse — by throwing the operator's boot diagnostics,
* warnings included, on the floor. Every case therefore asserts the same lines
* are present on **stderr**, so a regression toward silencing goes red here
* too.
*
* ## The other member of this family
*
* `os serve` has no `--json` and boots no `bootSchemaStack`, so it is correctly
* outside the FAMILY below — but it holds the same invariant for a different
* consumer: its stdout is the MCP stdio transport's JSON-RPC channel (#7915).
* It reserves the stream through this same module and is pinned by
* `serve-stdio-stdout-purity.e2e.test.ts`, which asserts the same two halves —
* nothing unparseable on stdout, every diagnostic still on stderr.
*/
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
import { execFile } from 'node:child_process';
import { mkdtempSync, rmSync, writeFileSync, readFileSync, readdirSync, statSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { basename, join, resolve, relative, sep } from 'node:path';
import { fileURLToPath } from 'node:url';
import { generateEd25519KeyPair, signPayload } from '@objectstack/core';
import { maskComments } from '../../../scripts/js-comment-mask.mjs';
import { MANIFEST_FILENAME, computeIntegrity, createTarGz, type ArchiveFile } from '../src/utils/osplugin.js';
import { childEnv } from './helpers/serve-process.js';
import { CONFIG_MISS_FAMILY, discoverConfigMissFamily } from './helpers/config-miss-family.js';
const HERE = resolve(fileURLToPath(import.meta.url), '..');
const CLI = resolve(HERE, '../bin/run-dev.js');
const TSX = resolve(HERE, '../../../node_modules/.bin/tsx');
const COMMANDS_DIR = resolve(HERE, '../src/commands');
const UTILS_DIR = resolve(HERE, '../src/utils');
/**
* The family, and how to drive each member into a boot.
*
* The value is the EXTRA argv a member needs beyond `--json`; `[]` means the
* bare form already boots. `os migrate meta` migrates an authored config in
* memory and boots a kernel solely under `--stored`, which is why the issue's
* own list names it as `migrate meta --stored` rather than `migrate meta`. A
* member that needs a fixture as well as argv is prepared by {@link PREPARE}.
*/
const FAMILY: Record<string, string[]> = {
// Report-only is its DEFAULT and the only form driven here: without
// `--delete` it boots read-only, reports and writes nothing.
'db orphans': [],
// Its bare form boots: it takes the `os migrate plan` shape (`deferSchemaDdl`
// + `readOnlyProbe`), so a fixture with no database file is opened as an
// empty in-memory one rather than being brought into existence. No table
// exists there, so the face driven here is the command's REFUSAL face — the
// `emitJson(…, 1, { compact: true })` branch, which is the noisier of its two
// emit paths and therefore the one worth pinning: every driver and kernel
// diagnostic the failed scan produces is emitted before it.
'migrate account-issuer': [],
// A dry run is its DEFAULT and the only form driven here: without `--apply`
// it boots read-only (plugin-audit's objects registered), reads
// `sys_activity` and writes nothing. Its backfill logs through a sink of its
// own, which `--json` points at stderr, as `audit-metadata-bodies` does.
'migrate activity-changed-fields': [],
// [ADR-0139 E7] The same shape: a dry run by default, reading `sys_comment`
// and writing nothing, its backfill logging through a sink `--json` points at
// stderr.
'migrate comment-parent-pair': [],
'migrate apply': [],
// A dry run is its DEFAULT and the only form driven here: without `--apply`
// it boots (plugin-audit's objects registered), reads `sys_audit_log` /
// `sys_activity` and writes nothing. Its rewrite runner logs through a sink of
// its own, which `--json` points at stderr — a third pollution source beside
// the two in the header, so this member is worth driving, not only listing.
'migrate audit-metadata-bodies': [],
// [#24693] The same shape over the same two tables: a dry run by default,
// reading `sys_audit_log` / `sys_activity` and writing nothing, its rewrite
// runner logging through a sink `--json` points at stderr.
'migrate audit-mail-bodies': [],
// Its twin: the same shape over the same two tables, a dry run by default
// that writes nothing, its rewrite runner logging through a sink `--json`
// points at stderr.
'migrate audit-key-material': [],
// A dry run is its DEFAULT and the only form driven here: without `--apply`
// it boots read-only (plugin-audit's objects registered), reads
// `sys_comment` below the data door and writes nothing.
'migrate comment-reactions': [],
'migrate files-to-references': [],
'migrate meta': ['--stored'],
'migrate multi-value-columns': [],
// Its bare form — a read-only plan (`deferSchemaDdl` + `readOnlyProbe`) —
// is the one driven here; `--apply` emits through the same two `emitJson`
// paths after the same shutdown. The fixture's database holds none of the platform tables
// the ceremony inventories, so the face driven here is its REFUSAL face
// (`plan_refused`, `emitJson(…, 1, { compact: true })`), emitted after the
// stack is shut down. A refused plan writes no plan file, so the fixture
// directory gains nothing.
'migrate organization-ownership': [],
'migrate plan': [],
'migrate recorded-by': [],
'migrate resume': [],
// A preview is its DEFAULT and the only form driven here: without `--apply`
// it composes the deployment the way `os serve` does (the host config's
// plugins and the auth-gated security plugin) and boots read-only with no
// `sys_metadata` hydration, so it deletes nothing. No table exists in the
// fixture, so the face driven here is its empty listing.
'migrate security-catalog-overlays': [],
'migrate summary-nulls': [],
// One object per run, so it needs a name: the fixture's own `jp_ticket`,
// which the composed host config registers. No database file exists, so the
// face driven here is its empty-work answer for a table not there yet.
'migrate unmapped-columns': ['--object', 'jp_ticket'],
'migrate value-shapes': [],
// It boots only to read the trusted key a SIGNED artifact names (through
// `utils/plugin-trust-read.ts`, which is why the discovery follows utils),
// so it is driven with one: `PREPARE` builds and signs the artifact and
// trusts its key in this member's database, and the face driven here is the
// full install, its `installed` document emitted after the read-only boot
// has shut down. An unsigned artifact would refuse without booting at all.
'plugin install': ['purity.osplugin'],
// Its bare form is read-only (`deferSchemaDdl` + `readOnlyProbe`). No
// database file exists, so the face driven here is its empty listing.
'plugin trust list': [],
// Report-only is its DEFAULT and the only form driven here: without
// `--delete` it boots, reports and writes nothing, so the family gains a
// member without this fixture gaining a destructive run.
'secret orphans': [],
// A dry run is its DEFAULT and the only form driven here: without `--apply`
// it boots read-only and writes nothing, so the family gains a member
// without this fixture gaining a run that re-wraps anything.
'secret rewrap': [],
'storage orphans': [],
};
/** Boot lines every member emits — the diagnostics that must survive on stderr. */
const BOOT_DIAGNOSTICS = [
// `console.log`, not the kernel logger — see the header.
'[StandaloneStack] no compiled artifact',
'Bootstrap complete',
'Graceful shutdown complete',
];
/**
* Members that need a fixture beyond argv to reach the face driven here. Each
* gets the project directory and its own environment, prepares what it needs,
* and returns the extra environment its run takes. A preparation that fails
* throws: the member would otherwise reach some other face and still pass.
*/
const PREPARE: Record<string, (dir: string, env: Record<string, string>) => Promise<Record<string, string>>> = {
// An artifact built and signed the way `os plugin build` / `os plugin sign`
// make one, its key trusted by `os plugin trust add` in this member's
// database. The install materializes under OS_HOME, so it gets one of its
// own inside the fixture rather than the runner's.
'plugin install': async (dir, env) => {
const keyId = 'purity-2026';
const publisher = generateEd25519KeyPair();
const files: ArchiveFile[] = [{ path: 'dist/index.mjs', data: new TextEncoder().encode('export const id = "com.purity.e2e";\n') }];
const manifest = {
id: 'com.purity.e2e',
version: '1.0.0',
type: 'plugin',
runtime: 'node',
packaging: 'bundled',
integrity: computeIntegrity(files),
};
const artifact = join(dir, 'purity.osplugin');
writeFileSync(artifact, createTarGz([...files, { path: MANIFEST_FILENAME, data: new TextEncoder().encode(JSON.stringify(manifest)) }]));
writeFileSync(`${artifact}.sig`, signPayload(new Uint8Array(readFileSync(artifact)), publisher.privateKeyPem, keyId));
writeFileSync(join(dir, 'purity.pub.pem'), publisher.publicKeyPem);
const trusted = await runCli(['plugin', 'trust', 'add', 'purity.pub.pem', '--key-id', keyId], dir, env);
if (trusted.code !== 0) {
throw new Error(`os plugin trust add exited ${trusted.code}:\n${trusted.stdout}\n${trusted.stderr}`);
}
return { OS_HOME: join(dir, 'os-home-plugin-install') };
},
};
/** Every `.ts` under `src/commands`, excluding tests. */
function commandFiles(dir: string): string[] {
const out: string[] = [];
for (const entry of readdirSync(dir)) {
const abs = join(dir, entry);
if (statSync(abs).isDirectory()) {
out.push(...commandFiles(abs));
continue;
}
if (!entry.endsWith('.ts') || entry.endsWith('.test.ts')) continue;
out.push(abs);
}
return out;
}
/**
* The `src/utils` modules that boot the shared stack on a command's behalf:
* those that call `bootSchemaStack(` (its own definition does not count), and
* those that import one that does, to a fixed point. `os plugin install` boots
* only through `plugin-trust-read.ts`, so a probe of the command's own text
* would drop it from the family while it still boots.
*/
function bootingUtils(): Set<string> {
const sources = new Map<string, string>();
for (const abs of commandFiles(UTILS_DIR)) {
sources.set(basename(abs, '.ts'), maskComments(readFileSync(abs, 'utf-8')));
}
const booting = new Set<string>();
for (const [name, src] of sources) {
if (src.replace(/function bootSchemaStack\(/g, '').includes('bootSchemaStack(')) booting.add(name);
}
for (let grew = true; grew;) {
grew = false;
for (const [name, src] of sources) {
if (booting.has(name)) continue;
if ([...booting].some((b) => src.includes(`from './${b}.js'`))) {
booting.add(name);
grew = true;
}
}
}
return booting;
}
/**
* The family, read off the source rather than remembered: a command belongs iff
* it boots the shared stack AND offers a machine-readable mode. Both halves are
* needed — `os serve` boots a kernel with no `--json`, and `os lint --json`
* emits JSON without booting one.
*/
function discoverFamily(): string[] {
const utils = [...bootingUtils()];
const ids: string[] = [];
for (const abs of commandFiles(COMMANDS_DIR)) {
// Masked: both halves are text probes, and both are satisfiable by prose. A
// command whose only `bootSchemaStack(` is inside a docblock explaining that
// it does NOT boot one would join this family and be driven against boot
// diagnostics it never writes — a red in a tier no pull request collects,
// wearing this file's title rather than the docblock's (#18520).
const src = maskComments(readFileSync(abs, 'utf-8'));
const boots = src.includes('bootSchemaStack(')
|| utils.some((u) => new RegExp(`from '(?:\\.\\./)+utils/${u}\\.js'`).test(src));
if (!boots) continue;
if (!/\bjson:\s*Flags\.boolean\(/.test(src)) continue;
const rel = relative(COMMANDS_DIR, abs).replace(/\.ts$/, '');
const parts = rel.split(sep).filter((p) => p !== 'index');
ids.push(parts.join(' '));
}
return ids.sort();
}
interface Run {
id: string;
code: number;
stdout: string;
stderr: string;
}
function runCli(argv: string[], cwd: string, env: Record<string, string>): Promise<Omit<Run, 'id'>> {
return new Promise((resolvePromise) => {
execFile(
TSX,
[CLI, ...argv],
{ cwd, maxBuffer: 32 * 1024 * 1024, env: childEnv({ NO_COLOR: '1', ...env }) },
(err, stdout, stderr) => {
resolvePromise({
code: err ? (typeof (err as { code?: unknown }).code === 'number' ? (err as unknown as { code: number }).code : 1) : 0,
stdout: String(stdout),
stderr: String(stderr),
});
},
);
});
}
/** Minimal project — every member boots the same stack, none of them needs more. */
const CONFIG = `
export default {
name: 'json_purity_e2e',
label: 'JSON Purity E2E',
objects: [{
name: 'jp_ticket',
label: 'Ticket',
sharingModel: 'private',
fields: { title: { type: 'text', label: 'Title' } },
}],
};
`;
let dir: string;
let runs: Run[];
beforeAll(async () => {
dir = mkdtempSync(join(tmpdir(), 'os-json-purity-e2e-'));
writeFileSync(join(dir, 'objectstack.config.ts'), CONFIG);
// Sequential, each on its own database file: several members create tables,
// and a shared SQLite file would make one member's run depend on the order
// the others happened to run in. Sequential also keeps peak memory at one
// booted kernel rather than one per member.
runs = [];
for (const [id, extra] of Object.entries(FAMILY)) {
const slug = id.replace(/[^a-z0-9]+/gi, '-');
const env = { OS_DATABASE_URL: `file:${join(dir, `${slug}.db`)}` };
const prepared = PREPARE[id] ? await PREPARE[id](dir, env) : {};
const { code, stdout, stderr } = await runCli(
[...id.split(' '), '--json', ...extra],
dir,
{ ...env, ...prepared },
);
runs.push({ id, code, stdout, stderr });
}
}, 900_000);
afterAll(() => {
try { rmSync(dir, { recursive: true, force: true }); } catch { /* ignore */ }
});
describe('the family this contract has to hold across', () => {
it('is exactly the set listed here — a new member goes red until it is driven too', () => {
expect(discoverFamily()).toEqual(Object.keys(FAMILY).sort());
});
it('and the commands that fail BEFORE boot are covered too, by the sibling pin', () => {
// [#15547] THIS file's discovery is `bootSchemaStack`-based, so it is
// structurally blind to a command that refuses at `resolveConfigPath()` —
// above the kernel, with no boot to discover. Ten published `--json` faces
// sat in that gap while `--json` stdout was, on paper, pinned.
//
// ⛔ The repair is NOT to widen the discovery above: these ten emit no boot
// diagnostics, so driving them through `BOOT_DIAGNOSTICS` would assert
// lines they never write. The POPULATION is widened across the PAIR
// instead — `config-miss-stdout-purity.e2e.test.ts` drives them, this
// reconciliation names them, and the shared discovery lives in one module
// so neither file can lose the other's half silently. Delete the sibling's
// helper and this import stops resolving; shrink the discovery and this
// assertion goes red.
const preBoot = discoverConfigMissFamily();
expect(preBoot).toEqual(Object.keys(CONFIG_MISS_FAMILY).sort());
// ⛔ Not `toHaveLength(10)`. The line above already binds the SET, against a
// map a sibling nightly file drives member by member — that equality IS the
// contract, and a new member reddening it until it is driven is the point.
// The integer bound nothing that equality did not, and it bound it in a
// SECOND place that has to be hand-edited: two frozen numbers over one fact,
// in a tier where the author who moves the fact is never shown the failure.
// What it was load-bearing for is the vacuum the pair shares — a discovery
// that stops matching returns `[]`, and an emptied map would agree with it —
// so it stays as a FLOOR. Ten is the population the pre-boot family was
// measured over, not a count of today (#18520).
expect(
preBoot.length,
'the pre-boot `--json` discovery reports fewer faces than the family was measured over',
).toBeGreaterThanOrEqual(10);
// The two families are NOT disjoint, and measuring that was worth more
// than assuming it: `os migrate meta` is in both, legitimately and by
// design — it boots a kernel under `--stored` and refuses at
// `resolveConfigPath()` under `--from N`. So a shared MEMBER is fine and
// pinned; what must never happen is the two files driving the same
// INVOCATION and disagreeing about its verdict, which is an argv question.
const overlap = preBoot.filter((id) => id in FAMILY);
expect(overlap).toEqual(['migrate meta']);
for (const id of overlap) {
const bootArgv = FAMILY[id].join(' ');
const preBootMember = CONFIG_MISS_FAMILY[id];
for (const argv of [preBootMember.explicit, preBootMember.auto]) {
if (argv) expect(argv.join(' ')).not.toBe(bootArgv);
}
}
});
});
describe.each(Object.keys(FAMILY))('os %s --json', (id) => {
const runOf = () => {
const run = runs.find((r) => r.id === id);
if (!run) throw new Error(`no run captured for '${id}'`);
return run;
};
it('emits ONE JSON document on stdout — a bare JSON.parse, no extraction', () => {
const run = runOf();
// `JSON.parse(run.stdout)` directly, not a payload-hunting helper. Under
// the defect this threw `Unexpected token 'S', "[Standalone"...`.
const payload = JSON.parse(run.stdout);
expect(payload).toBeTypeOf('object');
expect(payload).not.toBeNull();
});
it('leaves no kernel-logger record on stdout', () => {
const run = runOf();
// The rendering `ObjectLogger` emits at `pretty` (the CLI's format):
// `<iso-ts> INFO …`. Asserted separately from the parse so a regression
// names its cause rather than only `Unexpected token`.
expect(run.stdout).not.toMatch(/^\d{4}-\d{2}-\d{2}T[\d:.]+Z\s+(DEBUG|INFO|WARN)\b/m);
expect(run.stdout).not.toContain('[StandaloneStack]');
});
it('still shows the operator every boot diagnostic — on stderr', () => {
const run = runOf();
for (const line of BOOT_DIAGNOSTICS) expect(run.stderr).toContain(line);
});
});