Repository navigation
Expand file tree
/
Copy pathformat.ts
More file actions
2377 lines (2274 loc) · 114 KB
/
Copy pathformat.ts
File metadata and controls
2377 lines (2274 loc) · 114 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
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
import chalk from 'chalk';
import type { ZodError } from 'zod';
import { formatZodIssue, type ConversionNotice } from '@objectstack/spec';
import type { TenancyPosture } from '@objectstack/spec/security';
// #17329 — the published settlement contract's own shape. Read, never restated:
// a second local copy of `{ pending, inFlight, suppressed }` would be free to
// drift the day a suppression reason is added, and the whole point of asking
// through the contract is that the two sides cannot disagree.
import type { SeedSettlementSnapshot } from '@objectstack/spec/contracts';
import type { DevLogin } from '@objectstack/spec/system';
import { explainRule } from '@objectstack/lint/rule-explanations';
// #22255 — the deployment's scheduled-work sentence, read as an IDENTITY: the
// Flows section tells the policy class apart by equality with it, never by its
// words. See `isDeploymentPolicyClass`.
import { SCHEDULED_WORK_DISABLED_REASON } from '@objectstack/types';
import { writeStdoutDirect } from './json-stdout.js';
import { authoringRuleUnionStack } from './stack-collections.js';
import { stripAnsi } from './boot-log-capture.js';
// ─── Constants ──────────────────────────────────────────────────────
export const CLI_NAME = 'objectstack';
export const CLI_ALIAS = 'os';
// ─── Machine-readable output ────────────────────────────────────────
/**
* The only two exit codes this CLI has: `0` success, `1` failure.
*
* Deliberately a narrow union rather than `number`, and that narrowness is the
* whole point. The value it types sits in the SECOND POSITIONAL slot of
* {@link emitJson} / {@link emitText} — immediately after a payload — where
* `number` accepted whatever numeric the caller happened to be holding.
* `os migrate recorded-by --json` and `os migrate resume --json` were holding
* `timer.elapsed()`, a DURATION in milliseconds, and passed it there (#4873).
*
* The result was invisible in every way an author checks: correct JSON on
* stdout, `✅ Graceful shutdown complete`, empty stderr — and
* `process.exitCode = 531`, which the shell reports as `531 & 0xFF` = 19. A
* different non-zero code on every run, because the code WAS the run's
* duration, so every caller that judges success by exit status (CI steps,
* `set -e`, Makefiles, container entrypoints) saw a random failure from a
* command that had just succeeded — the one audience `--json` exists for.
*
* Every other `--json` site in this CLI reports its duration INSIDE the
* payload (`{ ...report, duration: timer.elapsed() }` — `os lint`,
* `os migrate meta`, `os migrate summary-nulls`), which is
* what those two meant to do as well. With this union a duration in the exit
* slot is a compile error, so the mistake cannot be made silently again.
*
* Widening it is a deliberate act: a third code needs a meaning first.
*/
export type CliExitCode = 0 | 1;
export interface EmitJsonOptions {
/**
* Emit on a single line instead of 2-space-indented.
*
* Exists so the sweep onto `emitJson` could be a pure truncation fix with no
* observable output change: roughly half the CLI's `--json` sites were
* already compact and half indented, and this preserves whichever each one
* emitted.
*
* This comment used to cite `os login --json` — a compact payload followed by
* an indented one in the same run — as proof the split was accidental. That
* was true, and worse than a formatting inconsistency: two documents on one
* stdout parse as neither a single document nor as NDJSON. #6531 fixed it,
* and in doing so gave `compact` its one *designed* use. `os login` is the
* CLI's sole declared NDJSON command, because its device flow is genuinely
* two events over time and the first one has to reach an automation consumer
* before the user authorizes; there, one line per document IS the contract,
* enforced through a single emitter in `commands/login.ts` and pinned by
* `test/login-json-ndjson.e2e.test.ts`.
*
* Everywhere else `--json` still means exactly one JSON document on stdout
* (commit 2b641ddd4), so the remaining compact call sites are still only preserving
* historical formatting and unifying them stays worth doing on its own.
* New code should use the default.
*/
compact?: boolean;
}
/**
* Emit a `--json` payload and record the exit code, without truncating.
*
* `console.log(big)` followed by `process.exit(1)` looks correct and is not:
* when stdout is a **pipe**, Node buffers the write asynchronously and
* `process.exit` tears the process down with the buffer only partly drained.
* `os lint packages/platform-objects/scripts/i18n-extract.config.ts --json`
* came out of a pipe at exactly 65536 bytes — one pipe buffer — so every
* scripted consumer got invalid JSON while an interactive run (stdout is a TTY,
* written synchronously) looked perfect. Silent, and invisible to the author.
*
* The exit does not have to be an explicit `process.exit` to bite. oclif's
* `handle()` ends every failing command with `Exit.exit()` → `process.exit()`
* and performs no flush on that path, so a plain `this.exit(1)` — or any
* thrown error — truncates exactly the same way. `flush()` runs only on the
* SUCCESS path of `execute()`. That is why the fix belongs at the write, not
* at the exit: awaiting the write callback drains the buffer before any of
* those paths can tear the process down.
*
* Deliberately NOT fixed by forcing stdout into blocking mode process-wide
* (`process.stdout._handle.setBlocking(true)`), which would cover every
* command in one line: the same binary runs `os serve` / `os dev`, and a
* blocking write to a pipe whose reader is slow blocks the event loop — it
* would trade truncated JSON for a server that stalls on its own logs.
*
* Setting `process.exitCode` rather than calling `process.exit` lets Node exit
* on its own once nothing is pending. Callers that must unwind immediately can
* still `this.exit(n)` after awaiting this — the buffer is already drained by
* then.
*/
export async function emitJson(
payload: unknown,
exitCode: CliExitCode = 0,
opts: EmitJsonOptions = {},
): Promise<void> {
const text = opts.compact ? JSON.stringify(payload) : JSON.stringify(payload, null, 2);
await emitText(text, exitCode);
}
/**
* True for the `ExitError` oclif's `this.exit(n)` throws.
*
* A command whose whole body sits in one `try` has a problem the truncation
* masked: `this.exit(1)` does not exit, it THROWS, so an inner "report the
* failure and stop" unwinds into the outer `catch`, which reports a second
* time. `os validate --json` on a bad config emitted two JSON documents back
* to back — unparseable as either one document or as JSONL. Nobody noticed
* because the payload was being cut off at 64 KiB before the second one could
* appear; draining the write is what made it visible.
*
* A catch that reports failures must re-throw this first — it is a
* control-flow signal from our own code, not a failure to describe:
*
* } catch (error: any) {
* if (isExitSignal(error)) throw error;
* …
* }
*/
export function isExitSignal(error: unknown): boolean {
const e = error as { code?: unknown; oclif?: { exit?: unknown } } | null | undefined;
return e?.code === 'EEXIT' || typeof e?.oclif?.exit === 'number';
}
/**
* True for an error whose diagnostic was ALREADY written to stderr by the code
* that threw it — so a command's TEXT face must not render it a second time.
*
* `resolveConfigPath()` is the case this exists for (#15547). It refuses with a
* sentence plus hint lines no catch-all could reconstruct — the hints are the
* helper's, not the command's — so it writes them itself, on stderr, and
* throws. Without this predicate the text face would then print the same
* sentence again through `printError`, on **stdout**, and the operator would
* read one refusal twice across two streams.
*
* ⚠️ It gates the TEXT branch only. The `--json` branch sits above it and is
* unaffected: the envelope is the machine's copy of that failure and the prose
* on stderr is the human's, which is the split #15692 established and #15547
* kept.
*
* Structural, like {@link isExitSignal}, and deliberately not `instanceof`:
* this CLI runs from `dist/` in production and from `src/` under `tsx` in the
* gates, and a marker that depends on which copy of a class the error came from
* fails silently in exactly the tree the pins run in.
*/
export function isReportedError(error: unknown): boolean {
return (error as { reportedToStderr?: unknown } | null | undefined)?.reportedToStderr === true;
}
/**
* [commit 098a08ffa] The ADR-0112 carriers a `--format json` failure envelope adds
* beside its `error` sentence — `{ code, httpStatus }`, and only the ones the
* thrown error actually carries.
*
* ## The defect this closes
*
* Every machine-readable failure this CLI emits was built the same way:
*
* await emitJson({ success: false, error: error.message });
*
* — 48 sites under `commands/`, and the payload carried the human sentence and
* nothing else. The error reaching those `catch` blocks from
* `@objectstack/client` is not a bare `Error`: the SDK's `fetch` wrapper
* attaches `err.code` (the semantic ADR-0112 string, normalized to the SAME
* spelling across the flat `@objectstack/rest` envelope and the wrapped
* runtime-dispatcher one — #3842 / #4007) and `err.httpStatus`. Both were
* dropped at the CLI boundary, so the one outcome a script most needs to
* branch on — *someone else edited it, re-read and retry* vs *you are not
* allowed* vs *the server is down* — was separable only by substring-matching
* an English sentence that no contract pins.
*
* ## Why the keys are OMITTED rather than emitted as `undefined`
*
* `JSON.stringify` drops an `undefined` value, so `{ code: undefined }` and an
* absent `code` are byte-identical on `emitJson`'s own output — which is
* exactly why building the former is unsafe: the difference is invisible where
* an author would look for it, and NOT invisible everywhere.
*
* Measured, rather than assumed. `yaml.stringify` drops it too (checked: both
* `{ success, error, code: undefined }` and `{ success, error }` serialize to
* `success: false\nerror: boom\n`). `formatOutput`'s `table` branch does not:
* `printKeyValue` walks `Object.entries`, which yields the key, and its
* `value === undefined` arm prints `code: null` outright; `printTable` derives
* its columns from `Object.keys` and grows an empty `code` column the same way.
* A payload meaning "this failure carried no code" would there assert a code
* whose value is null.
*
* So this returns a partial object with the keys ABSENT — the spread adds
* nothing at all when there is nothing to add — and the pin asserts the
* emitted BYTES rather than the object, because on two of the three emitters
* the object's own shape is what the bytes cannot show.
*
* ## What counts as "carrying" one — per key, not as a pair
*
* The two keys are decided INDEPENDENTLY, and that is a measurement rather
* than a preference: the SDK sets `error.httpStatus = res.status` on every
* non-2xx, while `error.code` comes from `asSemanticCode(...)` and is
* `undefined` whenever the server sent no code. Coupling them ("emit both or
* neither") would therefore discard a status that IS in hand, on exactly the
* responses whose envelope is thinnest.
*
* - `code` — a non-empty STRING. A numeric `code` is deliberately rejected
* rather than coerced: the pre-#3842 wrapped envelope parked the HTTP
* STATUS in `error.code`, and re-publishing a number under the name the
* semantic vocabulary uses would reintroduce, at this boundary, the exact
* confusion that producer-side fix removed.
* - `httpStatus` — a finite integer. `NaN` and fractional values are not
* statuses.
*
* ⛔ No value is INVENTED. A locally-thrown plain `Error` — every one of this
* CLI's own input refusals — carries neither key and gets neither key. That
* was option **B** of the card and it was not chosen: ADR-0112's ledger is the
* authority on who may mint a code, and this card mints nothing. The accepted
* cost, recorded so it is not re-opened as a defect: the payload is
* POLYMORPHIC — a consumer cannot distinguish "this failure carried no code"
* from "an older CLI". That was weighed against breaking every existing
* consumer and the non-breaking side won.
*
* ⛔ Nor is the value FILTERED against a catalog. The codes actually in flight
* here are broader than `StandardErrorCode`'s enum — `METADATA_CONFLICT`,
* `FORBIDDEN` and `VALIDATION_FAILED` are all absent from it — so a membership
* check would drop precisely the code this card exists to surface. Passing a
* producer's code through is not minting one; narrowing the field to a
* vocabulary no ledger declares would be.
*
* ## The one exclusion, and why it is not a filter
*
* oclif's `this.exit(n)` THROWS an `ExitError` whose `code` is the string
* `'EEXIT'`. It is a control-flow signal from our own code, not a failure with
* a vocabulary, and several of these `catch` blocks do not re-throw it first
* (`os migrate meta` carries a comment about the "EEXIT: 1" it would otherwise
* report). Publishing `code: "EEXIT"` into a machine-readable envelope would
* hand consumers a branch on our own stack unwinding. {@link isExitSignal} is
* reused rather than re-spelled so the judgement "this is a signal, not an
* error" stays single-sourced.
*
* @example
* } catch (error: any) {
* if (flags.format === 'json') {
* await emitJson({ success: false, error: error.message, ...errorCodeFields(error) });
* this.exit(1);
* }
*/
export interface ErrorCodeFields {
/**
* The machine code the failure carried, when it carried one — passed
* through, never minted or filtered. For wire failures this is the semantic
* ADR-0112 string the SDK attached (`METADATA_CONFLICT`, `FORBIDDEN`, …);
* for local I/O failures it is the Node errno (`ENOENT`, `ENOTDIR`, …),
* which `os validate` / `os compile` / `os lint` really do throw from
* inside the same `try`. The two vocabularies are disjoint (errnos are
* `E`-prefixed OS names), so an ADR-0112 branch cannot false-match an
* errno — but a consumer must not assume every `code` is ledger-owned.
* Declared honestly here per the 2026-08-31 contract review: narrowing
* this field to ADR-0112-only later would be breaking.
*/
code?: string;
/** The HTTP status the failure carried, when it carried one. */
httpStatus?: number;
}
export function errorCodeFields(error: unknown): ErrorCodeFields {
const fields: ErrorCodeFields = {};
if (isExitSignal(error)) return fields;
const e = error as { code?: unknown; httpStatus?: unknown } | null | undefined;
if (typeof e?.code === 'string' && e.code !== '') fields.code = e.code;
if (typeof e?.httpStatus === 'number' && Number.isInteger(e.httpStatus)) {
fields.httpStatus = e.httpStatus;
}
return fields;
}
/**
* The drain-aware write `emitJson` is built on, for machine payloads that are
* not JSON — `formatOutput`'s `--format yaml` truncates on a pipe exactly like
* the JSON one, and for the same reason.
*
* Appends the trailing newline. Everything in `emitJson`'s doc comment about
* why this cannot be fixed at the exit, or globally via blocking stdout,
* applies here too.
*/
export async function emitText(text: string, exitCode: CliExitCode = 0): Promise<void> {
// `writeStdoutDirect`, not `process.stdout.write`: a `--json` command that
// boots a kernel reserves stdout so the kernel's INFO stream goes to stderr
// (commit 2b641ddd4), and the payload is the one thing that must still reach the real
// stdout. Outside a reservation this is `process.stdout.write` verbatim.
await writeStdoutDirect(text + '\n');
if (exitCode !== 0) process.exitCode = exitCode;
}
// ─── Banner ─────────────────────────────────────────────────────────
export function printBanner(version: string) {
console.log('');
console.log(chalk.bold.cyan(' ╔═══════════════════════════════════╗'));
console.log(chalk.bold.cyan(' ║') + chalk.bold(' ◆ ObjectStack CLI ') + chalk.dim(`v${version}`) + chalk.bold.cyan(' ║'));
console.log(chalk.bold.cyan(' ╚═══════════════════════════════════╝'));
console.log('');
}
// ─── Section Header ─────────────────────────────────────────────────
export function printHeader(title: string) {
console.log(chalk.bold(`\n◆ ${title}`));
console.log(chalk.dim('─'.repeat(40)));
}
// ─── Key-Value Line ─────────────────────────────────────────────────
export function printKV(key: string, value: string | number, icon?: string) {
const prefix = icon ? `${icon} ` : ' ';
console.log(`${prefix}${chalk.dim(key + ':')} ${chalk.white(String(value))}`);
}
// ─── Status Line ────────────────────────────────────────────────────
export function printSuccess(msg: string) {
console.log(chalk.green(` ✓ ${msg}`));
}
/** The ` ⚠ <msg>` line both warning printers render — one glyph, one source. */
function warningLine(msg: string): string {
return chalk.yellow(` ⚠ ${msg}`);
}
export function printWarning(msg: string) {
console.log(warningLine(msg));
}
/**
* {@link printWarning}'s line, on **stderr** — the advisory counterpart of
* {@link printErrorToStderr}, for the same reason and the same callers.
*
* A shared helper that drops authored input has to say so, and it has no flag
* to branch on: `loadConfig()` is handed no `--json` (its own header says so),
* so the choice is stdout — which `--json` reserves for the machine — or
* stderr. A non-fatal finding cannot take {@link printErrorToStderr}'s `✗`
* without reading as a failed run, so the warning severity gets its own door
* rather than borrowing the error one.
*
* ⚠️ Not a general replacement for {@link printWarning}: a command that has
* already decided it is rendering the text face keeps writing to stdout.
*/
export function printWarningToStderr(msg: string) {
console.error(warningLine(msg));
}
/** The ` ✗ <msg>` line both error printers render — one glyph, one source. */
function errorLine(msg: string): string {
return chalk.red(` ✗ ${msg}`);
}
export function printError(msg: string) {
console.log(errorLine(msg));
}
/**
* `printError`'s line, on **stderr**.
*
* For a diagnostic printed by code that CANNOT see whether the run is a
* `--json` run. `printError` writes to stdout, which is correct for a command
* rendering its own text face and wrong for a shared helper: stdout is what
* `--json` reserves for the machine (`utils/json-stdout.ts`), and a helper
* called by both faces has no flag to branch on.
*
* `resolveConfigPath()` is the measured case (#15547). It printed this line
* plus two hints to stdout and then `process.exit(1)`, so ten `--json` faces
* answered a missing config file with human text on the machine's channel and
* an empty stderr — bytes that `JSON.parse` rejects, and no `catch` anywhere
* downstream could intervene because nothing was thrown.
*
* ⚠️ Not a general replacement for `printError`. A command that has already
* decided it is rendering the text face should keep writing to stdout; this is
* for the shared paths that cannot make that decision.
*/
export function printErrorToStderr(msg: string) {
console.error(errorLine(msg));
}
export function printInfo(msg: string) {
console.log(chalk.blue(` ℹ ${msg}`));
}
export function printStep(msg: string) {
console.log(chalk.yellow(` → ${msg}`));
}
// ─── Timer ──────────────────────────────────────────────────────────
export function createTimer() {
const start = Date.now();
return {
elapsed: () => Date.now() - start,
display: () => `${Date.now() - start}ms`,
};
}
// ─── Zod Error Formatting ───────────────────────────────────────────
/**
* How far the nested lines of an expanded issue are pushed to sit UNDER the
* `code: message` line this file prints for the issue itself.
*
* `formatZodIssue` indents its own depth-0 line by 2 spaces and each nested
* level by 2 more; this file's per-issue block is at 4/6. Adding 4 puts the
* first nested level at 8 — one step below the `invalid_union: Invalid input`
* line it explains — and keeps every deeper level nested relative to it.
*/
const NESTED_ISSUE_REINDENT = ' ';
/**
* [#5389] The issue codes whose real diagnosis is nested one level down, and
* which `formatZodIssue` therefore renders as more than one line.
*
* `invalid_union` puts each candidate branch on `issue.errors[]`; `invalid_key`
* / `invalid_element` put the key/element schema's own issues on
* `issue.issues[]`. Same defect, two property names — and the gate below has to
* name both, or the terminal keeps printing `invalid_key: Invalid key in
* record` with the prescription stranded in the payload.
*
* Kept in step with `CONTAINER_ISSUE_CODES` in `@objectstack/spec`'s
* `error-map.zod.ts`, which is where the descent itself lives.
*/
const EXPANDABLE_ISSUE_CODES: ReadonlySet<string> = new Set([
'invalid_union',
'invalid_key',
'invalid_element',
]);
/**
* The lines that explain an expandable issue, or nothing at all.
*
* Zod folds every branch of a failed union into ONE issue whose own `message`
* is the literal `"Invalid input"`; each branch's real rejection sits in
* `issue.errors[]`, with paths relative to the union's own. A consumer that
* walks only the top level therefore prints `invalid_union: Invalid input` and
* drops the branch that says WHICH key is wrong — which is what `os validate`,
* `os build` and `os plugin build` did until #5341, so every curated
* prescription the #4001 campaign wrote for a strict shape behind a union was
* produced and never delivered to the author's terminal.
*
* The branch SELECTION (drop branches that only say "wrong kind of value",
* prefer the branch complaining least so one stray key is not reported once per
* branch, break ties on `unrecognized_keys`, absolute paths, bounded depth) is
* `@objectstack/spec`'s, reused rather than re-derived: this is the third
* consumer of the same defect after `formatZodError` (#4971, PR #5342) and the
* REST wire's `zodIssuesToFields` (#5014, PR #5362), and one mistake must not
* get three different prescriptions depending on which surface the author hit.
* Unlike the wire — which needs structured `{field, code, message}` entries and
* so had to re-implement the ranking — the terminal needs exactly the STRING
* that spec already exports, so here the reuse is a plain import.
*
* [#5389] The same import now also covers `invalid_key` / `invalid_element`,
* whose diagnosis hangs on `issue.issues[]` instead. Widening the gate is the
* WHOLE of this file's share of that fix — the descent is spec's, so the
* terminal inherits it the moment it stops refusing to ask.
*
* Line 0 of that render is the issue's own verdict, which the caller has
* already printed in this file's own idiom; only the explanation is returned,
* so the change is strictly ADDITIVE — nothing that printed before #5341 stops
* printing. An issue with nothing nested renders as a single line, hence never
* reaches here and could not add one anyway.
*/
function nestedIssueLines(issue: unknown): string[] {
const code = (issue as { code?: unknown } | null)?.code;
if (typeof code !== 'string' || !EXPANDABLE_ISSUE_CODES.has(code)) return [];
return formatZodIssue(issue as Parameters<typeof formatZodIssue>[0])
.split('\n')
.slice(1)
.map((line) => `${NESTED_ISSUE_REINDENT}${line}`);
}
export function formatZodErrors(error: ZodError) {
const issues = error.issues || (error as any).errors || [];
if (issues.length === 0) {
console.log(chalk.red(' Unknown validation error'));
return;
}
// Group by top-level path
const grouped = new Map<string, typeof issues>();
for (const issue of issues) {
const topPath = (issue as any).path?.[0] || '_root';
if (!grouped.has(String(topPath))) {
grouped.set(String(topPath), []);
}
grouped.get(String(topPath))!.push(issue);
}
for (const [section, sectionIssues] of grouped) {
console.log(chalk.bold.red(`\n ${section}:`));
for (const issue of sectionIssues) {
const path = (issue as any).path?.join('.') || '';
const code = (issue as any).code || '';
const msg = (issue as any).message || '';
console.log(chalk.red(` ✗ ${path}`));
console.log(chalk.dim(` ${code}: ${msg}`));
// Show expected/received for type errors
if ((issue as any).expected) {
console.log(chalk.dim(` expected: ${chalk.green((issue as any).expected)}`));
}
if ((issue as any).received) {
console.log(chalk.dim(` received: ${chalk.red((issue as any).received)}`));
}
// [#5341] …and, for a union — [#5389] or a record key / map element —
// the nested issues that actually explain it.
for (const line of nestedIssueLines(issue)) {
console.log(chalk.dim(line));
}
}
}
console.log('');
console.log(chalk.dim(` ${issues.length} validation error(s) total`));
}
// ─── Metadata Statistics ────────────────────────────────────────────
/**
* Every field here is rendered by {@link printMetadataStats}.
*
* Until commit 05181e8cc, `translations: number` sat in this interface, collected by
* {@link collectMetadataStats} (`count(config.translations)`) on every
* `os validate` / `os info` / `os compile` run and then read by nothing: the
* printer had no `translations` fragment at any value, so a stack with 40
* translation bundles reported them nowhere. The maintainer ruled
* implementation-first (2026-08-23) — delete the unread field rather than
* invent a row for it; an `i18n:` summary row was explicitly NOT approved.
*
* The invariant that replaces it: this struct carries no metric the summary
* does not print. It is enforced from both ends — TypeScript requires
* `collectMetadataStats` to populate every field declared here, and the
* pin commit 05181e8cc added to `print-metadata-stats-zero-row.test.ts` requires every
* collected field to reach the rendered output. A metric that is declared but
* never rendered cannot satisfy both.
*/
export interface MetadataStats {
objects: number;
objectExtensions: number;
fields: number;
picklists: number;
views: number;
pages: number;
apps: number;
dashboards: number;
reports: number;
actions: number;
flows: number;
workflows: number;
agents: number;
apis: number;
positions: number;
permissions: number;
datasources: number;
plugins: number;
devPlugins: number;
}
/**
* The metadata summary `os validate`, `os build`/`os compile` and `os info` all
* print — counted over the stack the author actually declared, in either
* ADR-0130 D4 shape.
*
* ## Why the fold is INSIDE this function and not at the three call sites
*
* Until #17527 every member here was `count(config.KEY)` against the TOP LEVEL
* alone. On an option-B project — every definition inside `packages[]`, none
* flattened up — all three commands reported `Data: 0 Objects`, and
* `os validate` raised `No objects defined — this stack has no data model` on a
* stack that declares a data model. Under `--strict` that warning is not
* cosmetic: it is the gating error, so a CONFORMING project could not pass its
* own validator, and the sentence it died on was false on its face.
*
* Folding at the call sites would have fixed the three commands and left the
* reader itself still top-level-only — and the reader is what
* `test/option-b-reader-acceptance.pin.test.ts` measures. That pin's probe
* CALLS readers; a row can only attach to a callable, and a row shaped like
* "assert `config.objects` is non-empty" is explicitly forbidden there because
* it is a second copy of the read it watches. So the fold lives here, the probe
* calls this function, and the pin goes red if it ever stops resolving
* `packages[]`.
*
* ## Why {@link authoringRuleUnionStack} and not a second fold
*
* `stack-collections.ts` is the ONE place this package resolves a
* package-owned collection, and its rule is strictly additive: a key the top
* level already carries WINS, because in today's additive shape that array
* already IS the union (`composeStacks` flattened it). That property is exactly
* what this reader needs — an object reachable from both the top level and a
* `packages[]` entry is counted ONCE, so the corrected number is the union and
* never the sum. A second fold written here could not have that property
* without re-deriving it, and two folds that disagree is a worse defect than
* the one being removed.
*
* The seam also derives the folded key set from the two schemas rather than a
* hand-list, so a metadata family added to the stack schema next month is
* folded without anyone remembering to come back here.
*
* ## What this DOES change beyond the counts
*
* `authoringRuleUnionStack` resolves package order through
* `resolveArtifactPackageOrder`, whose ADR-0112 refusals (a duplicate package
* id, a malformed entry) are deliberately not swallowed. `os validate` and
* `os compile` already drive that same seam on the same config well above their
* `collectMetadataStats` call, so their behaviour on a malformed `packages` is
* unchanged. `os info` did not, so it now reports such a stack as a named `422`
* through its own `catch` instead of printing `Data: 0 Objects` for an artifact
* it could not read — the "absence must be loud" direction, and the reason the
* duplicate-id case cannot double-count either.
*
* A stack whose top level carries its collections — every stack the platform
* emits today — is returned by IDENTITY from the seam, so this function's
* answer for it is byte-identical to the pre-#17527 one.
*/
export function collectMetadataStats(config: any): MetadataStats {
// The stack as DECLARED, whichever shape it arrived in. ⛔ Never re-read
// `config.KEY` below this line — a member that skipped the fold is exactly
// the defect #17527 removed, and it would be invisible in every other member.
const stack: any = authoringRuleUnionStack(config);
const count = (val: any) => {
if (Array.isArray(val)) return val.length;
if (val && typeof val === 'object') return Object.keys(val).length;
return 0;
};
// Count total fields across all objects
let fields = 0;
const objects = Array.isArray(stack.objects) ? stack.objects :
(stack.objects && typeof stack.objects === 'object' ? Object.values(stack.objects) : []);
for (const obj of objects as any[]) {
if (obj.fields && typeof obj.fields === 'object') {
fields += Object.keys(obj.fields).length;
}
}
return {
objects: count(stack.objects),
objectExtensions: count(stack.objectExtensions),
fields,
picklists: count(stack.picklists),
views: count(stack.views),
pages: count(stack.pages),
apps: count(stack.apps),
dashboards: count(stack.dashboards),
reports: count(stack.reports),
actions: count(stack.actions),
flows: count(stack.flows),
workflows: count(stack.workflows),
agents: count(stack.agents),
apis: count(stack.apis),
positions: count(stack.positions),
permissions: count(stack.permissions),
datasources: count(stack.datasources),
plugins: count(stack.plugins),
devPlugins: count(stack.devPlugins),
};
}
// ─── Server Ready Banner ────────────────────────────────────────────
/**
* Whether this boot serves HTTP at all — the fact every address row in the
* ready banner rests on (#23623).
*
* - `'composed'`: the kernel holds an `http.server` service. That is serve's
* own transport, or one the config mounts itself, which `--no-server` does
* not skip.
* - `'skipped-by-no-server'`: none is registered, and `--no-server` is what
* skipped serve's own.
* - `'not-composed'`: none is registered although the flag asked for one (the
* transport plugin did not load).
*
* Read off the booted kernel, never off the `--server` flag: the flag says
* whether SERVE composes one, not whether the boot has one.
*/
export type HttpServerComposition = 'composed' | 'skipped-by-no-server' | 'not-composed';
export interface ServerReadyOptions {
/**
* Whether an HTTP server is composed on this boot (#23623) — see
* {@link HttpServerComposition}.
*
* `'composed'` prints the address rows: `API:`, `Console:`, `MCP:` with its
* connect hint, and the paths-only note. Anything else prints none of them
* and ONE line saying no HTTP server is served. A `--no-server` boot used to
* print `API:` and an MCP connect URL for a port nothing listened on, and an
* operator, or an AI client configured from the banner, was sent to connect
* to a server the flag had deliberately not started.
*
* Required on purpose, like {@link externalBaseOrigin}: an omitted field must
* not be able to mean "a server is listening" by default, which is the
* defect itself.
*/
httpServer: HttpServerComposition;
/**
* The origin an operator can actually reach this deployment on — the base
* every absolute URL in the banner is built from — or `null` when none could
* be determined.
*
* ## Why this is handed in, and why the port is not
*
* This field replaced a `port: number` that the banner turned into
* `http://localhost:${port}` itself. That address is the one the process
* BINDS, which is not the one a human can open the moment anything sits in
* front of it. Measured on the EE 4.1.0 compose stack (#10646): the app
* container `expose`s `:3000` with no `ports:` mapping — unreachable from the
* host, and more so under `--scale app=N` — while the published entry point
* is Caddy on `:80` and `OS_AUTH_URL` is already resolved to
* `http://localhost`. The banner printed `http://localhost:3000/_console/`
* anyway: a Console link that fails outright, and an `MCP:` line that is the
* address customers paste into an AI client, where a wrong absolute URL never
* fails loudly — it just never connects.
*
* So the banner no longer knows the port at all. It cannot compose an address
* from one, which makes the old defect a COMPILE error rather than a
* plausible-looking line of output. The caller resolves the origin through
* the runtime's own chain (`resolveAuthBaseUrl` in `serve`: `OS_AUTH_URL` →
* legacy `BETTER_AUTH_URL` → `OS_BASE_URL` → `http://localhost:<port>`) and
* hands the answer here. That is the same value the CSRF allow-list and
* first-party auth redirects key off, so the banner and the runtime cannot
* disagree about where this deployment lives — a second, banner-local notion
* of "external base" is exactly the drift this field exists to prevent.
*
* ## `null` means "say nothing", never "guess"
*
* `null` is what the resolver reports when the chain produced something that
* will not parse — a set-but-empty `OS_AUTH_URL=` (which does NOT fall
* through to the rest of the chain), or a value with no scheme. The banner
* then prints the PATHS with no origin in front of them. A missing address
* sends the operator to look one up; a confidently wrong one gets copied.
*
* Required on purpose: an absent field must not be able to mean
* `http://localhost:<port>` again by omission.
*/
externalBaseOrigin: string | null;
/**
* The authored config file, relative to cwd — printed in the `Config:`
* row. Omit it when the boot did not actually read a config (#8978): on
* every artifact-fallback boot (`OS_ARTIFACT_URL`, `OS_ARTIFACT_PATH`, or
* the plain `<cwd>/dist/objectstack.json` convention) the caller derives
* this path before deciding which source to boot from, so passing it
* unconditionally named a file that was either never read or does not
* exist on disk — on the SAME screen that just said so. See
* {@link artifactSource} for the OS_ARTIFACT_URL row this slot takes
* instead; the other artifact-fallback paths have no safely-redacted
* display to show here, so the row is omitted rather than fabricated.
*/
configFile?: string;
/**
* Set on an `OS_ARTIFACT_URL` boot (#8368) — the resolver's already
* redacted `display` string (pre-signed URL query strings stripped),
* printed in the `Config:` row's place. When present it takes priority
* over {@link configFile}: this is what actually booted (#8978).
*/
artifactSource?: string;
/**
* #21501 — the compiled artifact a CONFIG boot loaded as its app bundle (a
* non-host config's standalone stack), relative to cwd or redacted. Printed
* as a plain `Artifact:` row in the `Config:` row's place: the metadata
* served came from that file, so naming the config instead would name a
* file that is not what loaded. A host config never sets it.
*/
bundleSource?: string;
isDev: boolean;
pluginCount: number;
pluginNames?: string[];
/**
* [ADR-0025 §3.5 M1] Installed plugins (`os plugin install`) the boot-time
* loader refused, each already printed by name as a `✗` line. `0` or absent:
* no row.
*/
installedPluginsRefused?: number;
uiEnabled?: boolean;
consolePath?: string;
/** Resolved storage driver display name (e.g. "MongoDBDriver", "SqlDriver(pg)"). */
driverLabel?: string;
/** Resolved DB URL with credentials redacted. */
databaseUrl?: string;
/**
* [ADR-0105 D1] The deployment's resolved tenancy posture — printed verbatim.
*
* This is the SAME fact serve wires the runtime from: it must be
* `resolveTenancyPosture()` (`@objectstack/types`), never a re-derivation.
* The banner used to take a boolean `multiTenant` sourced from
* `resolveMultiOrgEnabled()`, i.e. from `OS_MULTI_ORG_ENABLED` — the knob
* `OS_TENANCY_POSTURE` superseded, and which `resolveTenancyPosture()` now
* consults only as a fallback when the posture is unset. So a deployment
* booted with `OS_TENANCY_POSTURE=isolated` alone printed
* `Tenancy: single-tenant` while the organization wall was actually up and
* `Organizations` was in the plugin table one line below (framework#4801,
* observed in cloud#1020). Two sources for one fact, drifting.
*
* The field is the posture, not a boolean, for the same reason: tenancy is a
* three-valued spectrum (`single` | `group` | `isolated`), and a boolean
* cannot say `group` at all — it would have to lie, and the flattening is
* where the drift hides. Typing it as {@link TenancyPosture} also makes the
* old wiring a COMPILE error rather than a wrong-but-plausible line of
* output: `resolveMultiOrgEnabled()` returns `boolean` and no longer fits.
*
* Omitted → no `Tenancy:` row (unchanged: a caller with nothing to say says
* nothing, rather than guessing a posture).
*/
tenancyPosture?: TenancyPosture;
/**
* Credentials of the dev admin seeded on an empty DB this boot (dev only).
* When present, the banner surfaces them so backend debugging never has to
* guess the login. Absent when nothing was seeded.
*
* [commit f721ef0ff] The banner also says what this account SEES, because it is the
* only credential a first-run operator is given and it holds no app-declared
* capability — in an app that gates navigation on `requiredPermissions` it is
* the account that renders an empty menu. See the render site in
* {@link printServerReady} for the wording and the restraints on it.
*/
seededAdmin?: { email: string; password: string };
/**
* First-run credentials the BOOTED APPLICATION contributes (#17556) — the
* parsed `devLogins` of the stack definition `serve`/`dev` loaded.
*
* The platform cannot supply these. {@link seededAdmin} is the one credential
* a first-run operator is handed, and it holds every platform capability and
* no app-declared one — so in an application that gates navigation on
* `requiredPermissions` it is by construction the account that renders an
* empty menu (disclosed since commit f721ef0ff). Which of an application's audiences shows something is
* a fact only the application has, and this is the channel it hands it over
* through.
*
* ADDITIVE: rendered BENEATH the seeded-admin block, never instead of it. An
* application-controlled key that could suppress a platform disclosure would
* be a posture regression, not a feature — the seeded account exists whether
* or not the application mentions it.
*
* Absent or empty → no block, and the banner is byte-identical to one that
* declares nothing. Printed only when {@link isDev}.
*/
devLogins?: readonly DevLogin[];
/**
* One sentence the booted application contributes (#17556) — the parsed
* `devHint` of the stack definition.
*
* The free-form half of the same channel, for what a credential list cannot
* say: "run `pnpm seed:demo` first", "sign in through the local IdP". Absent
* → no row. Printed only when {@link isDev}.
*/
devHint?: string;
/**
* Automation wiring summary (2026-07-17 third-party eval). The engine's own
* `info` narration while binding flows to triggers sits under the default
* `warn` level and never prints, and a flow that armed logs nothing either
* way — so a log line is the wrong instrument here regardless. This reports
* live binding STATE, read off the engine after runtime.start(), which is
* what "did my flows actually arm?" actually asks. (Boot-phase warnings the
* engine does emit now reach the terminal too — see {@link BootDiagnostics},
* #4012 — but absence of a warning was never evidence of a bound flow.)
*/
automation?: AutomationReadySummary;
/**
* Per-source seed outcomes for this boot (#3415/#3430). SeedLoader's own
* logs sit under the default warn level (and the boot-quiet window hid them
* at every level until #4012), so without this line a fixture can silently
* lose most of its rows (the showcase shipped 1 of 5 projects for weeks) and a marketplace
* package can rehydrate onto a fresh DB with zero rows. Each config app and
* each rehydrated/healed marketplace package contributes one entry;
* rejections and empty installs are loud, a clean seed prints one dim line.
*/
seeds?: SeedSourceSummary[];
/**
* The kernel's live seed-settlement tally as of the instant the banner prints
* (#17329) — `undefined` when no seed pipeline registered on this kernel.
*
* ## The omission this closes
*
* {@link seeds} is fed by the `seed-summary` service, and a source only
* records its outcome when its load FINISHES. Past the inline seed budget the
* load has not finished when the banner prints, so `seeds` is `undefined` and
* the `Seeds:` row is ABSENT — making the transcript of a boot that is still
* writing byte-indistinguishable from one that declared no seeds at all:
*
* ```text
* ✓ Server is ready
* …
* Press Ctrl+C to stop ← and 82 seconds later, 120 ERROR lines
* ```
*
* A reader who sees `Press Ctrl+C to stop` reasonably believes nothing more
* is coming. They believe it because the banner in front of them says, by
* omission, that seeding is not part of this boot.
*
* ⛔ Human-facing only. It does NOT replace the `objectstack:seed-settled`
* IPC message a parent process waits on — a shell script still cannot wait on
* prose, which is why holding the banner was refused as the repair.
*/
seedSettlement?: SeedSettlementSnapshot;
/**
* Boot-phase kernel-logger diagnostics replayed from the boot-quiet stdout
* window (#4012). `ObjectLogger` writes `warn` to stdout, so that window
* used to discard every warning a plugin emitted while booting — the
* ADR-0110 D5 `[action-governance]` inventory, degraded-boot notices, flow
* binding failures — even though the CLI defaults the kernel to `warn`
* expressly so they surface (ADR-0032). `serve` now buffers them and hands
* them here, so they land under the banner instead of nowhere.
*/
bootDiagnostics?: BootDiagnostics;
/**
* The core services the KERNEL concluded were missing on this boot (#16630).
*
* This is `ObjectKernel.validateSystemRequirements()`'s OWN list — the very
* array behind its `System started with degraded capabilities. Missing core
* services: …` warning — carried here over the kernel's service registry and
* read by `readMissingCoreServices` in `./degraded-capabilities.ts`.
*
* ## Why the banner takes the list instead of working it out
*
* Until this field there was no data path at all between the two statements:
* `✓ Server is ready` is printed here, in `@objectstack/cli`; the degraded
* conclusion is reached in `@objectstack/core`. So the ready line could not
* report the failure — it never learned of it — and printed a green tick over
* a boot the kernel had just called degraded. Measured on objectui CI run
* `34056438855`, and again on this repo's own published-artifact canary (run
* `34084559243`), where the tick printed directly ABOVE four boot warnings
* saying the opposite.
*
* ⛔ Never re-derive it here. Which services count as `core` is
* `ServiceRequirementDef`'s judgement (`@objectstack/spec/system`), and a
* second implementation of it on this side would be free to disagree with the
* kernel's — replacing one wrong line with two contradictory ones.
*
* ## What it changes, and what it must not
*
* Non-empty ⇒ the ready line says what state the server is ready IN, and the
* unconditional `✓` is not printed. Absent or empty ⇒ the ready block is
* byte-for-byte what it has always been. That asymmetry is the design, not an
* optimisation: readiness itself is UNCHANGED (a machine deliberately booted
* without auth still boots, still prints ready, still exits 0), and an
* implementation that always appended a status line would have reported the
* degradation while rewriting every healthy boot's output as well.
*/
missingCoreServices?: string[];
/**
* Whether the MCP server surface (`/api/v1/mcp`) is on (#3167). Default-on
* core capability, but nothing in the dev loop surfaces it — an AI client
* (Claude Code, Cursor, …) can operate the running app the instant a
* developer knows the endpoint is there. The banner is where they look, so
* print the URL + the SKILL.md pointer when it's live.
*
* It says whether the MCP surface is switched on AND the route's owner (the
* runtime dispatcher) is composed (#23743) — `serve` passes both — not
* whether a transport serves it: the row also needs {@link httpServer} to
* be `'composed'` (#23623).
*/
mcpEnabled?: boolean;
}
export interface SeedSourceSummary {
/** Display label — the config app id / marketplace manifest id that seeded. */
source: string;
/** True when the source is a marketplace package (vs a config-declared app). */
marketplace?: boolean;
inserted: number;
updated: number;
skipped: number;
/** Records dropped by validation/reference errors — the silent-loss case. */
rejected: number;
/**
* Reference FIELDS dropped from rows that WERE written (#3932). The row
* count stays healthy — the association is what went missing — so unless
* this is said out loud, nothing on this line hints at it.
*/
droppedRefs?: number;
/**
* Rows were (re)seeded onto a fresh/empty database during rehydrate — the
* "swap the DB out from under an installed package" self-heal (#3430).
*/