Repository navigation
Expand file tree
/
Copy pathcompile.ts
More file actions
1428 lines (1385 loc) · 81.7 KB
/
Copy pathcompile.ts
File metadata and controls
1428 lines (1385 loc) · 81.7 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 { Args, Command, Flags } from '@oclif/core';
import path from 'path';
import fs from 'fs';
import chalk from 'chalk';
import { ZodError } from 'zod';
import {
ObjectStackDefinitionSchema,
normalizeStackInput,
lintUnknownAuthoringKeys,
lintUnknownStackKeys,
formatUnknownAuthoringKey,
stackConversionsOf,
type ConversionNotice,
} from '@objectstack/spec';
import { loadConfig, namedExportRejectionHints } from '../utils/config.js';
import { collectSeedFiles, placeSeedFiles } from '../utils/bundle-seed-files.js';
import { collectConnectorSpecFiles, placeConnectorSpecFiles } from '../utils/bundle-connector-spec-files.js';
import { judgeSeedRecordValues } from '../utils/seed-record-values.js';
import { refuseUnbuiltStack } from '../utils/stack-provenance-refusal.js';
import { isExtractionRefusal, lowerCallables } from '../utils/lower-callables.js';
import { authoringRuleUnionStack } from '../utils/stack-collections.js';
import { makeDirectorySync } from '../utils/make-directory.js';
import { artifactPackages, runPerPackageAuthoringRules } from '../utils/artifact-packages.js';
import { stackFilterJudge } from '../utils/authoring-filter-judge.js';
import { buildAccessMatrix, diffAccessMatrix } from '@objectstack/lint';
import { runAuthoringRules, splitBySeverity, authoringRulesFor } from '@objectstack/lint';
import { resolveJsxGateManifest, printJsxGateNotices } from '../utils/sdui-manifest.js';
import { preflightDeclaredCapabilities, renderCapabilityMessage } from '../utils/capability-preflight.js';
import { collectAndLintDocs, placeCollectedDocs, type DocIssue } from '../utils/collect-docs.js';
import { buildRuntimeBundle, cleanupOldRuntimeBundles } from '../utils/build-runtime.js';
import {
printHeader,
printKV,
printSuccess,
printError,
printStep,
printWarning,
formatConversionNotice,
printAuthoringAdvisories,
printAuthoringRuleErrors,
printDocIssueErrors,
printBulletList,
JSON_FULL_LIST_REMEDY,
createTimer,
formatZodErrors,
collectMetadataStats,
printMetadataStats,
emitJson,
isExitSignal,
errorCodeFields,
isReportedError,
} from '../utils/format.js';
import { checkProtocolVersionGap } from '../utils/protocol-version-gap.js';
import {
checkDependencyRanges,
formatDependencyRangeDiagnostic,
type DependencyRangeDiagnostic,
} from '../utils/dependency-range-check.js';
// [#14553] The compile-time half of the navigation-contribution group ruling.
// Reports; never refuses — the runtime still relocates, deliberately.
import { findNavGroupDiagnostics } from '../utils/nav-contribution-groups.js';
import type { NavContributionGroupDiagnostic } from '@objectstack/objectql';
// [#18024] The compile-time half of the #17516 permission-set name-collision
// ruling. Reports; never refuses — the runtime still drops the set, deliberately
// (ADR-0086 D4), and what was missing was the author hearing about it.
import {
findPermissionSetNameCollisions,
formatPermissionSetNameCollisions,
} from '../utils/permission-set-name-collisions.js';
import type { PermissionSetNameCollisionDiagnostic } from '@objectstack/plugin-security';
// [#20393] The boot registrar's divergent view-container `name` refusal — the
// walk `os validate` step 2c runs, over `@objectstack/objectql`'s one judge.
import { findViewContainerNameRefusals } from '../utils/view-container-names.js';
// A field `picklist` that names no picklist the stack declares — the walk
// `os validate` step 2d runs, over the same judge.
import { judgePicklistReferences, picklistRefusalHeading, printPicklistReferenceNotices } from '../utils/picklist-references.js';
// [ADR-0146 D2, #28643] The override write gate — the walk `os validate` step
// 3a-iii runs, over the publish door's own judge (`judgeOverrideWrite`).
import { findOverrideDeclarationRefusals } from '../utils/override-declarations.js';
export default class Compile extends Command {
static override description = 'Compile ObjectStack configuration to JSON artifact';
static override args = {
config: Args.string({ description: 'Source configuration file', required: false }),
};
static override flags = {
output: Flags.string({ char: 'o', description: 'Output JSON file', default: 'dist/objectstack.json' }),
json: Flags.boolean({ description: 'Output compile result as JSON (for CI)' }),
'strict-body': Flags.boolean({
description: 'Fail the build if any hook/action callable could not be lowered into a metadata-only body (no .mjs fallback)',
default: false,
}),
'runtime-bundle': Flags.boolean({
description: 'Force-emit the legacy objectstack-runtime.{hash}.mjs shim even when every callable has a metadata body. Useful for back-compat with older runtime loaders. By default the bundle is auto-emitted only when at least one callable could not be lowered to a body.',
default: false,
allowNo: true,
}),
// Deprecated alias kept for back-compat. Auto-skip is now the default,
// so this flag is a no-op except that it forces a hard failure when any
// callable still needs the legacy bundle (same semantics as before).
'no-runtime-bundle': Flags.boolean({
description: '[deprecated] Auto-skip is now the default. Pass --no-runtime-bundle to fail loudly if any callable still requires the legacy bundle.',
default: false,
hidden: true,
}),
'update-access-matrix': Flags.boolean({
description: '[ADR-0090 D6] Rewrite access-matrix.json from the current stack instead of failing on drift. Review the resulting diff — it IS the capability change.',
default: false,
}),
};
async run(): Promise<void> {
const { args, flags } = await this.parse(Compile);
const timer = createTimer();
if (!flags.json) {
printHeader('Compile');
}
// [#11772] THE ADVISORY LISTS THIS RUN HAS COMPUTED SO FAR, hoisted out of
// the `try` so that EVERY `emitJson` exit can read them — not the terminal
// success payload alone.
//
// The defect: `warnings` lived on the success payload only (plus, for one
// list, the author-time-rules failure). The text face prints the #3786
// undeclared-authoring-key block at 3d ending `— re-run with --json for the
// full list`, and #11529's advisory printer ends the same way. A build that
// then failed at a LATER gate (access matrix 3e, package docs 3f, the
// runtime bundle, or a throw caught at the bottom) emitted that gate's
// failure payload, and none of those carried the list — so the author was
// told to re-run with `--json` and got a payload without the withheld
// entries in it. That is the "the remedy named is unreachable" shape of
// #11643 and #11391.
//
// Maintainer ruling 2026-08-25, option 1 of the three the card offered:
// every failure exit carries the lists the run has ALREADY COMPUTED, so
// `warnings` means the same thing on every exit and a machine consumer has
// exactly one way to read it. Option 2 — carry them only where the text
// face printed them, making the payload's SHAPE depend on how far the run
// got — was rejected as the hardest contract to declare. Option 3 (weaken
// the pointer) was rejected as making the product worse.
//
// ⛔ CARRYING, NOT COMPUTING. Every list stays computed at exactly the step
// that owns it; these bindings only make the value visible to the exits
// DOWNSTREAM of that step. An exit that runs before a given step therefore
// still sees that list empty, and that is the honest reading of "what the
// run has already computed": hoisting a computation earlier so an early
// exit looks fuller would be option 2 wearing option 1's clothes, and it
// would change what the command costs on its failure paths as well.
//
// ORDER IS `os validate --json`'s, stated ONCE here and read by the success
// payload too — the "one list cannot drift from itself" idiom #11643 and
// #11727 applied one list over. The spread used to be written out at the
// payload, so a tenth exit could have been added with a different order and
// nothing would have caught it.
// Typed off `splitBySeverity` and not by naming `AuthoringFinding`: the #4409
// import scan (packages/lint/src/authoring-rule-wiring.test.ts) reads every
// symbol this file names from `@objectstack/lint` and strips `type ` rather
// than exempting it, and `splitBySeverity` — which produces this list — is
// already ratcheted there. Binding the annotation to the producer is also the
// tighter statement: the list cannot disagree with the function that fills it.
let ruleAdvisories: ReturnType<typeof splitBySeverity>['advisories'] = [];
let capProviderWarnings: Array<{ token: string; message: string }> = [];
let unknownKeyWarnings: string[] = [];
let docWarnings: DocIssue[] = [];
// [#14553] A member of `warningsSoFar()`, NOT a payload key of its own.
//
// ⛔ The first cut made it a separate top-level key and two standing pins
// refused it by name — `build-json-advisory-parity` and
// `build-json-undeclared-key-parity`, both titled "adds NO new top-level
// key to the payload — this fills a declared key, it is not a new
// surface". #11643 and #11727 each faced this choice and filled
// `warnings`. `os validate` computes the same list, so the parity the
// third pin in that file asserts ("nothing rides in build that validate
// does not also report") holds rather than being weakened to fit.
let navGroupWarnings: NavContributionGroupDiagnostic[] = [];
// [#18024] The permission-set name-collision half, a member of
// `warningsSoFar()` for the same three reasons the list above it records:
// the two undeclared-key pins refuse a new top-level payload key by name,
// `os validate` computes the identical list so the residue pin holds, and
// `severity: 'warning'` is declared at the producer — this reports, it
// never refuses.
let permissionSetCollisionWarnings: PermissionSetNameCollisionDiagnostic[] = [];
// [#20113] The JSX gate's parse-level notice — empty, or ONE `info` record
// saying `kind:'html'` pages were checked at parse level only because no
// SDUI component manifest resolved. A member of `warningsSoFar()`, ⛔ not a
// payload key, for the three reasons the two lists above record: the
// undeclared-key pins refuse a new top-level key by name, `os validate`
// computes the identical record so the residue pin holds, and it reports
// without ever refusing. Appended LAST, in `os validate`'s order.
let jsxGateNotices: ReturnType<typeof resolveJsxGateManifest>['notices'] = [];
// The `info` records of a field `picklist` reference that resolves nowhere
// in the stack while the declaring package depends on packages outside it
// (step 3a-bis). A member of `warningsSoFar()`, ⛔ not a payload key, for
// the reasons the three lists above record: it reports without refusing,
// and `os validate` computes the identical records. Appended LAST, in
// `os validate`'s order.
let picklistReferenceNotices: ReturnType<typeof judgePicklistReferences>['notices'] = [];
// ADR-0141 D2 author side (step 3b-quater): the `dependencies` findings
// the install ADMITS. A member of `warningsSoFar()`, ⛔ not a payload key,
// for the reasons the lists above record: it reports without refusing, and
// `os validate` computes the identical records. Appended LAST.
let dependencyRangeWarnings: DependencyRangeDiagnostic[] = [];
const warningsSoFar = () => [
...ruleAdvisories,
...docWarnings,
...unknownKeyWarnings,
...capProviderWarnings,
...navGroupWarnings,
...permissionSetCollisionWarnings,
...jsxGateNotices,
...picklistReferenceNotices,
...dependencyRangeWarnings,
];
// [#18780] ONE rendering of the author-time advisory block, from the
// COMPLETE list — hoisted here for the same reason the lists above are.
//
// The block used to be printed inline at step 3b, BEFORE step 3b-ii
// appended the per-package survivors to `ruleAdvisories`. So on a
// multi-package stack this command's summary line counted a set strictly
// larger than the one it pointed at. Measured on
// `examples/app-multi-package` at 17.4.0: `⚠ 4 author-time warning(s) —
// see above` standing over a list of THREE, while `--json` carried all
// four and `os validate` — which renders its advisory list once, at the
// end, after the same per-package append — printed all four (#18769). The
// reader is sent back up to find a warning that was never printed, and the
// direction reads as "I must have missed it".
//
// ⛔ THE COUNT IS NOT THE SIDE THAT MOVES. #11529 settled that axis one
// list over: the summary counts the whole set and the PRINTER names what
// it withheld, because a count quietly shrunk to match a short list is the
// false-clean direction — it deletes a finding from the text face of the
// command that ships, while `--json` and `os validate` keep reporting it.
// So the list grows to the count.
//
// ⛔ AND IT STAYS ONE PRINTER CALL. A second `printAuthoringAdvisories`
// for the survivors alone would hand the 50-entry cap a second budget and
// its truncation notice a second, partial total — two locally-honest
// notices for one list, which is #11529's defect wearing its own fix.
//
// Deferring the call is what the guard below is for: every text face that
// used to be DOWNSTREAM of the old inline site flushes the block itself,
// so both author-time rule failures still print their advisories ahead of
// their error list, and the catch-all still prints them when a rule throws
// inside the per-package pass — the one window between the two sites.
let advisoriesPrinted = false;
const printAdvisoriesOnce = (): void => {
if (advisoriesPrinted || flags.json || ruleAdvisories.length === 0) return;
advisoriesPrinted = true;
console.log('');
// #11529 — rendered by ONE printer, which also names the remainder when
// the list is cut. The loop used to sit inline here and stop dead at 50
// with no notice, so a truncated report read exactly like a complete
// one. See `printAuthoringAdvisories` for the measurement.
printAuthoringAdvisories(ruleAdvisories);
};
// [commit 79cf692b0] The ADR-0087 D2 conversion notices, hoisted for the SAME reason
// and under the SAME ruling as the four lists above — one field over. The
// notices were computed at step 2 (below) and reached the terminal SUCCESS
// payload alone, so all nine failure exits dropped a list already in hand.
// #12079 added `warnings` to those nine and deliberately left this field
// untouched, which is why closing that card did not close this one.
//
// ⛔ CARRYING, NOT COMPUTING — and here that is a pure SCOPE change. This is
// the same `const` array the `onConversionNotice` sink pushes into, moved
// above the `try` only so the catch-all exit can read it. `normalizeStackInput`
// still runs at exactly step 2, so a run that throws in `loadConfig` — above
// it — reports `[]` honestly, exactly as `warningsSoFar()` does there,
// unless what it threw is a stack producer's refusal: that carries the
// conversions the producer applied before refusing, and the catch-all
// folds them (#20583) — step 1b's fold for the run whose load threw.
//
// ⛔ NOT FOLDED INTO `warningsSoFar()`, in either direction. The success
// payload keeps these separate deliberately (see its note at `conversions:`
// below), and this field is the one advisory class carrying an EXPIRY —
// `retiresIn` names the protocol major where the source stops loading, which
// is structure a flattened warning string cannot carry. Whether the two
// should become one field is an open question this change was explicitly not
// given the authority to settle, so the shape is mirrored, not merged.
const conversionNotices: ConversionNotice[] = [];
try {
// 1. Load Configuration
if (!flags.json) printStep('Loading configuration...');
const loaded = await loadConfig(args.config);
const { config, absolutePath, duration, namedExports } = loaded;
// 1a. [#20367 ruling B] One authoring shape: refuse a default export no
// stack producer built, BEFORE any other judgement — the `STACK_*`
// cross-field refusals run inside `defineStack` only, so an unbuilt
// export would otherwise pass this door unjudged. Throws into the
// catch-all below (`--json`: `error` + `code`, exit 1), the same
// envelope a `defineStack` refusal raised at load reaches.
refuseUnbuiltStack(loaded);
// 1b. The ADR-0087 D2 conversions the PRODUCER applied — the same fold
// `os validate` makes at its step 1b, for the same reason: `defineStack`
// converts at load, so step 2's pass below finds nothing of the
// default export left to convert, and `conversions` read `[]` on every
// `defineStack` config. Read by `loadConfig` off the default export
// before its named-export merge (`stackConversionsOf`). ⛔ Folded,
// never recomputed. Rendered on the text face at step 2 with the
// pass's own findings, in this one list.
conversionNotices.push(...loaded.stackConversions);
if (!flags.json) {
printKV('Config', path.relative(process.cwd(), absolutePath));
printKV('Load time', `${duration}ms`);
}
// 2. Normalize map-formatted stack definition.
// The ADR-0087 D2 conversion layer runs here (inside normalizeStackInput).
// Each rewrite emits a structured deprecation notice, and this command
// used to drop every one of them: `os validate` passed a sink and
// surfaced them, `os build` passed none. That is the #3782 parity class
// — the two surfaces disagreeing about what an author is told — and it
// bites harder than it reads, because the notice is the ONLY warning an
// old-shape author gets before the conversion retires and their metadata
// stops loading. Five conversions are live today (protocol 11 and 15),
// so the gap is real, not hypothetical. After step 1b the pass can still
// find what the producer never saw — a key `loadConfig` merged onto the
// stack from a NAMED export of the config module — and appends it to
// the same list.
if (!flags.json) printStep('Normalizing stack definition...');
// The sink is declared above the `try` (see its note there); the CALL that
// fills it stays right here, at the step that owns it.
const normalized = normalizeStackInput(config as Record<string, unknown>, {
onConversionNotice: (n) => conversionNotices.push(n),
});
if (conversionNotices.length > 0 && !flags.json) {
console.log('');
for (const n of conversionNotices) {
printWarning(formatConversionNotice(n));
}
}
// 2b. Lower inline `function` handlers (Hook.handler, top-level
// `functions`) to stable string refs BEFORE Zod parse. This
// guarantees we extract the user's real function identity (Zod's
// `z.function()` wraps callables and would otherwise break the
// mapping). The originals are bundled into a sibling ESM module
// by esbuild — without this step `JSON.stringify` would silently
// drop every handler and the production server would boot with
// all hooks disabled.
if (!flags.json) printStep('Lowering inline handlers...');
const lowering = lowerCallables(normalized);
// The callables the extractor refused, each once: the refusal rows of the
// one population every verdict below reads. ⛔ Not
// `bodyExtractionWarnings`, which records a refusal once per SLOT — a
// handler shared by two hooks, or the same callable at the top level and
// in a `packages[i].manifest` body, is in it twice.
const refusedCallables = lowering.bodylessCallables.filter(isExtractionRefusal);
// Strict-body gate: refuse to ship if any callable was not lowered into a
// metadata body, i.e. if the runtime module would still have to carry it.
// Body-only is the long-term target — `--strict-body` lets CI enforce it
// before ESM-bundle emission becomes mandatory-off.
//
// `issues` is one row per callable, each callable once, so the header's
// count and the `--json` list are the same number. ⛔ Never rebuild it
// from `count - bodyExtracted` plus the extraction warnings: those count
// different populations (`bodylessCallables`' doc says how). Summing them
// printed one more callable than it listed and published a placeholder
// row in `issues` that named no callable.
if (flags['strict-body']) {
const issues = lowering.bodylessCallables;
if (issues.length > 0) {
if (flags.json) {
await emitJson({ success: false, error: 'strict-body: missing body', issues, warnings: warningsSoFar(), conversions: conversionNotices }, 0, { compact: true });
this.exit(1);
}
console.log('');
printError(`--strict-body: ${issues.length} callable(s) lack a metadata body`);
// [#11642] Caps at 20, not 50, which is the only reason a sweep
// anchored on the literal `slice(0, 50)` could not see this one. The
// shape is the defect either way: the header states the true total
// and the body shows 20, with nothing saying the rest exist. The cap
// stays; the silence does not. The pointer is honest here — the
// `--json` branch immediately above this block publishes the whole
// list as `issues`.
printBulletList(
issues.map((w) => `${w.origin}: ${w.reason}`),
{ noun: 'callable(s)', limit: 20, remedy: JSON_FULL_LIST_REMEDY },
);
this.exit(1);
}
}
// 2c. [#10678] SURFACE the warn-and-bundle. The default (non-`--strict-body`)
// build catches every extraction failure in `lowerCallables`, records it
// in `bodyExtractionWarnings`, ships the callable through the .mjs bundle
// and exits 0. That last part is correct and stays correct — flipping the
// default to a hard failure would change what `os build` ACCEPTS, which is
// not this change. What was wrong is that the recorded warnings reached
// nobody: a hook body containing `fetch()` produced a completely silent
// success, and the only way to learn the handler had NOT become a metadata
// body was to diff the artifact. The data already existed; it just never
// got printed. Advisory only — nothing below may touch the exit code.
//
// The reason strings carry a multi-line `--- offending body source ---`
// dump for `--strict-body`'s per-callable diagnostic; on the default path
// we print the first line and point at the flag for the rest, so the
// default build stays readable while staying honest.
//
// It counts and lists `refusedCallables`, each refused handler once, so
// its number is the number of handlers the runtime module carries for
// a refusal, not the number of slots that refused one.
if (refusedCallables.length > 0 && !flags.json) {
const n = refusedCallables.length;
console.log('');
printWarning(
`${n} handler${n === 1 ? '' : 's'} could not be lowered to a metadata body — ` +
`bundled via the legacy runtime module instead (build still succeeds)`,
);
for (const w of refusedCallables.slice(0, 20)) {
console.log(` • ${w.origin}: ${String(w.reason).split('\n')[0]}`);
}
if (n > 20) console.log(chalk.dim(` … and ${n - 20} more`));
console.log(chalk.dim(' → run `os build --strict-body` for the full diagnostic, or to make this fatal'));
}
// 3. Validate the lowered (JSON-safe) stack against the Protocol.
if (!flags.json) printStep('Validating protocol compliance...');
const result = ObjectStackDefinitionSchema.safeParse(lowering.lowered);
if (!result.success) {
if (flags.json) {
await emitJson({ success: false, errors: (result.error as unknown as ZodError).issues, warnings: warningsSoFar(), conversions: conversionNotices }, 0, { compact: true });
this.exit(1);
}
console.log('');
printError('Validation failed');
formatZodErrors(result.error as unknown as ZodError);
// [#18171] …and, when one of those unrecognised top-level keys got
// there by being a NAMED EXPORT of the config module rather than a key
// the author wrote inside `defineStack()`, the rule that makes it one.
// Text face only: the `--json` branch above is untouched, so no field
// is added to a published envelope.
for (const line of namedExportRejectionHints(
(result.error as unknown as ZodError).issues,
namedExports,
)) {
console.log(chalk.dim(line));
}
this.exit(1);
}
// 3a. [#20393] The boot registrar's divergent view-container `name`
// refusal — the SAME walk `os validate` runs at its step 2c, over the
// same judge (`viewContainerNameRefusal`, `@objectstack/objectql`)
// `ObjectQL.registerMetadataCollections` throws the answer of. This
// door used to exit 0 on `{ name: 'order_line', object:
// 'my_app_order_line', list: {…} }` and WRITE an artifact carrying
// it, which `os serve` then refused at boot — the command that ships
// shipping the failure.
//
// ⛔ One judge, not a second rule, and not a second walk: the call is
// the one `validate.ts` makes, so the two doors cannot disagree about
// which `views:` entries boot registers or under which package id,
// and the message is the runtime's own, verbatim.
//
// The input is `result.data`, the parsed stack this command
// serializes: every `views:` entry the artifact carries — top level,
// or each `packages[i].manifest` body — is the one judged here
// (step 4 adds docs and `runtimeModule`, never a view). So the
// verdict is the one boot reaches on the artifact.
//
// Right after the parse, ahead of the rule table and of every
// artifact write, mirroring `os validate`: this is the runtime's own
// accept set, the same class as the schema. The `--json` face is the
// schema exit's envelope just above (`errors`, as `os validate --json`
// carries these rows); the text face is `os validate`'s. No step
// line, as on `os validate`: a passing build prints what it printed.
const containerNameRefusals = findViewContainerNameRefusals(result.data as Record<string, unknown>);
if (containerNameRefusals.length > 0) {
if (flags.json) {
await emitJson({ success: false, errors: containerNameRefusals, warnings: warningsSoFar(), conversions: conversionNotices }, 0, { compact: true });
this.exit(1);
}
const n = containerNameRefusals.length;
console.log('');
printError(`The server would refuse this stack at boot (${n} view container${n > 1 ? 's' : ''})`);
printBulletList(
containerNameRefusals.map((r) => r.message),
{ noun: 'view-container refusal(s)', remedy: JSON_FULL_LIST_REMEDY },
);
this.exit(1);
}
// 3a-bis. A field `picklist`, or a `picklistExtensions` entry's `extend`,
// that names no picklist the stack declares is REFUSED — the SAME call
// `os validate` makes at its step 2d, so the two doors cannot disagree
// about which references resolve. Without it this door wrote the
// artifact carrying the misspelt reference, and the command that ships
// shipped a choice with nothing to choose.
//
// A reference the stack cannot resolve while the declaring package
// depends on packages outside the stack is an `info` notice instead
// (see `utils/picklist-references.ts`): the list may live there, and
// this command cannot read it. Printed here, carried in
// `warningsSoFar()`, never gating.
//
// Right after the parse and ahead of every artifact write, like 3a.
// The `--json` face is 3a's envelope (`errors`); the text face is
// `os validate`'s.
const picklistJudgement = judgePicklistReferences(result.data as Record<string, unknown>);
picklistReferenceNotices = [...picklistJudgement.notices];
if (!flags.json) printPicklistReferenceNotices(picklistReferenceNotices);
if (picklistJudgement.refusals.length > 0) {
if (flags.json) {
await emitJson({ success: false, errors: picklistJudgement.refusals, warnings: warningsSoFar(), conversions: conversionNotices }, 0, { compact: true });
this.exit(1);
}
console.log('');
printError(picklistRefusalHeading(picklistJudgement.refusals));
printAuthoringRuleErrors(picklistJudgement.refusals, { remedy: JSON_FULL_LIST_REMEDY });
this.exit(1);
}
// 3b. The author-time rule registry (#4409) — one table, three commands.
// `os build` was the WEAKEST of the three authoring gates before it:
// it published stacks `os validate` or `os lint` refuse, because the
// rules each command ran were whatever its author remembered to wire.
// `validateApprovalApprovers` was the worked example — a flow whose
// expression approver does not parse built and published green while
// `os lint` rejected it. The build is the command that SHIPS, so
// "weakest gate" here means broken metadata reaching an environment.
//
// Which rules run, on which stack tier, and why any of them is scoped
// is declared in `lint/authoring-rules.ts`. Do not add a call site here.
const registered = authoringRulesFor('build');
if (!flags.json) printStep(`Running author-time rules (${registered.length})...`);
// [ADR-0130 D4 / option B, #15006] The UNION run judges the flattened
// top level. Under option B that top level is gone — `packages[]`
// carries every definition once — so this run's input would be an
// EMPTY stack and `os build` would publish green having judged
// nothing. `authoringRuleUnionStack` folds each absent collection
// back in from `packages[]`, in `resolveArtifactPackageOrder`'s
// dependency order. It changes what the rules JUDGE and nothing this
// command EMITS: the artifact is written from `lowering.lowered` /
// `result.data`, which this does not touch, and a stack that still
// carries its collections is returned by identity.
//
// The per-package run below needs no such fold — it already reads
// `packages[]`. The union run is the only one of the two that can see
// a finding spanning packages, which is exactly what an empty input
// silently stops reporting.
//
// [#20113] The SDUI manifest is resolved ONCE, and both rule runs are
// handed the same answer; its pages are counted over the union fold
// AND each package body the pass below judges — see `validate.ts`
// step 3 for the three outcomes. Printed here, at the
// gate's step, so the parse-level notice shows on the failing paths
// too; it never changes this command's exit status. A project
// manifest that exists but cannot be used is refused instead
// (already reported on stderr; the catch-all exits 1).
// [#20166] Read beside the config this run was given, never in the
// invoker's working directory.
const jsxGate = resolveJsxGateManifest(result.data as Record<string, unknown>, path.dirname(absolutePath));
jsxGateNotices = [...jsxGate.notices];
if (!flags.json) printJsxGateNotices(jsxGateNotices);
const parsedUnion = authoringRuleUnionStack(result.data as Record<string, unknown>);
// [#20158] The engine's own filter admission over this stack's objects —
// see `validate.ts` step 3 and `utils/authoring-filter-judge.ts`. One
// judge for the union run and the per-package pass.
const judgeFilter = stackFilterJudge(parsedUnion);
const findings = runAuthoringRules('build', {
normalized: authoringRuleUnionStack(normalized as Record<string, unknown>),
parsed: parsedUnion,
sduiManifest: jsxGate.sduiManifest,
judgeFilter,
// [#16546] Ref strings, not hook indices — survive the union fold and
// the per-package re-slice below unchanged (see `LoweringResult.
// loweredHookRefs`'s header for why an index would not).
loweredHookRefs: lowering.loweredHookRefs,
});
const { errors: ruleErrors, advisories } = splitBySeverity(findings);
ruleAdvisories = advisories;
if (ruleErrors.length > 0) {
// Every failing rule reports at once — see the note in `validate.ts`.
if (flags.json) {
await emitJson(
{ success: false, error: 'author-time rules failed', issues: ruleErrors, warnings: warningsSoFar(), conversions: conversionNotices },
0,
{ compact: true },
);
this.exit(1);
}
// [#18780] This exit is UPSTREAM of the per-package append below — a
// union-level `error` refuses before that pass runs — so the list
// flushed here is the union's alone, byte-for-byte what this face
// printed when the call sat inline above.
printAdvisoriesOnce();
console.log('');
printError(`Author-time rules failed (${ruleErrors.length} issue${ruleErrors.length > 1 ? 's' : ''})`);
// [#11642] `--json` on this same exit publishes every one of them as
// `issues`, so the pointer resolves to a complete view of THIS list.
printAuthoringRuleErrors(ruleErrors, { remedy: JSON_FULL_LIST_REMEDY });
this.exit(1);
}
// 3b-ii. [ADR-0130 D4] The SAME rule table, once per PACKAGE.
//
// A project is N `defineStack` packages composed with
// `composeStacks(…, { manifest: 'preserve' })`. Composition FLATTENS
// every collection to the top level, so the run above judges the
// union — which is strictly more permissive than the packages it was
// built from. A rule that asks "does this stack's app navigation
// point at an object this stack defines?" is satisfied by the union
// for a package that carries neither half; per package it is not.
// Since the artifact registers PER PACKAGE (D4/D5), the per-package
// answer is the one the runtime will live with.
//
// ⛔ The same `runAuthoringRules('build', …)` call, not a copy: which
// rules run on a build is `lint/authoring-rules.ts`' single table
// (#4409), and a second call site choosing its own subset is how
// `os build` came to be the weakest of the three authoring gates in
// the first place.
//
// DE-DUPLICATED against the union run, because the union contains
// every package's items: without this, a two-package project reports
// every finding twice and the author cannot tell a real per-package
// finding from an echo.
//
// ⚠️ [#18779] This comment used to end "What survives the filter is
// exactly the set the union could not see", and that was FALSE for
// as long as the de-duplication key carried the POSITIONAL `path`:
// a package body re-bases its collections from 0, so one finding got
// two keys and its echo survived the very filter described here. The
// sentence was quoted as authority by #18677 and #18778 without the
// definition being opened, and copied into the `os validate` and
// `os lint` doors as each was wired. `findingKey` now neutralises
// the top-level collection index, so what survives is the set of
// per-package findings no union finding already carried under the
// same rule, `where`, message and non-top-level position. ⛔ Do not
// re-inflate that to "exactly the set the union could not see" —
// `utils/artifact-packages.ts` states the bound and why it is
// narrower than that sentence.
//
// [#16611] Each package's stack is handed the artifact's `packages[]`
// as RESOLUTION CONTEXT — see `packageBodyAsStack`. The list read here
// is the one `artifactPackages` above walked, off the same parsed
// stack, so the context a package resolves against is exactly the set
// of packages this artifact will register (ADR-0130 D4/D5).
//
// ⛔ [#18677] The LOOP itself is not written here either — it is
// `runPerPackageAuthoringRules`, beside the two seams it reads, for
// the reason that module's header already gives about them: the
// `os validate` door owes the identical pass, and the thing that
// would have drifted between two hand-written copies is the VERDICT
// (the de-duplication key, the severity split, the `where` prefix),
// not the package reading. Every observable of this step — the step
// line, the advisory order, the error sentence, the `--json` envelope
// — is unchanged; only the loop moved.
//
// The count is read for the step LINE before the pass runs, so the
// line still precedes the work it announces on every path — including
// a rule that throws inside it.
const packageEntries = artifactPackages(result.data as Record<string, unknown>);
if (packageEntries.length > 0) {
if (!flags.json) {
printStep(`Running author-time rules per package (${packageEntries.length})...`);
}
const perPackage = runPerPackageAuthoringRules({
command: 'build',
parsed: result.data as Record<string, unknown>,
unionFindings: findings,
sduiManifest: jsxGate.sduiManifest,
loweredHookRefs: lowering.loweredHookRefs,
judgeFilter,
});
const perPackageErrors: Array<{ package: string } & typeof ruleErrors[number]> =
perPackage.errors;
ruleAdvisories = [...ruleAdvisories, ...perPackage.advisories];
if (perPackageErrors.length > 0) {
if (flags.json) {
await emitJson(
{
success: false,
error: 'author-time rules failed for one or more packages',
issues: perPackageErrors,
warnings: warningsSoFar(),
conversions: conversionNotices,
},
0,
{ compact: true },
);
this.exit(1);
}
// [#18780] Downstream of the append, so this flush carries the
// per-package advisories too — the same list `warningsSoFar()` has
// published on this exit's `--json` twin since #11772.
printAdvisoriesOnce();
console.log('');
printError(
`Author-time rules failed inside the artifact's packages (${perPackageErrors.length} issue${perPackageErrors.length > 1 ? 's' : ''})`,
);
printAuthoringRuleErrors(perPackageErrors, { remedy: JSON_FULL_LIST_REMEDY });
this.exit(1);
}
}
// [#18780] The continuing path — and the only one the summary line at
// the foot of this command is reachable from. `ruleAdvisories` is
// complete here on BOTH shapes: a stack with `packages[]` has just had
// the survivors appended, and one without skips the block entirely and
// arrives with the union list the summary already counted.
printAdvisoriesOnce();
// 3b-bis. [#14553] Navigation contributions whose `group` names no group
// in the target app. RUNS ON EVERY BUILD, artifact or not — the block
// above is skipped for a single-package stack, but a stack that
// declares an app AND contributes into it has the identical defect
// and `collectNavGroupInputs` reads it from the top-level manifest.
//
// ⛔ REPORTS, NEVER REFUSES. The maintainer ruled option B: the
// runtime keeps relocating the items to the app's top level (the fold
// stays order-independent, contributions into optional groups keep
// working) and the failure becomes VISIBLE instead. Making this exit
// non-zero would be option A wearing a warning's clothes, and would
// narrow what `os build` accepts — which the ruling explicitly does
// not do.
//
// A contribution whose target app is NOT in this compilation unit
// yields nothing: contributing into an app another artifact ships is
// the supported cross-artifact case, and is precisely why the merge
// is a read-time fold. Only the composed case can be judged here.
navGroupWarnings = await findNavGroupDiagnostics(result.data as Record<string, unknown>);
if (navGroupWarnings.length > 0 && !flags.json) {
console.log('');
printWarning(
`Navigation contributions aimed at a group the target app does not declare ` +
`(${navGroupWarnings.length}) — the items still install, RELOCATED to the app's top level`,
);
printBulletList(
navGroupWarnings.map((d) => `[${d.code}] ${d.message} Fix: ${d.fix}`),
{ noun: 'navigation-contribution diagnostic' },
);
}
// 3b-ter. [#18024] Permission sets declared under a name another package
// in this same artifact already owns. The RUNTIME door (#17516)
// refuses the write and says so at boot; this is the compile-time
// half of that ruling, behind the SAME predicate and the SAME
// sentence so the two cannot drift.
//
// ⛔ REPORTS, NEVER REFUSES, and ⛔ does not change what is skipped.
// Refusing a foreign set is correct under ADR-0086 D4 and stays; the
// producer declares `severity: 'warning'` and the failure direction
// is CLOSED (the set is not installed, so nothing is over-granted).
// Exiting non-zero here would narrow what `os build` accepts, which
// is a different decision from the one this card carries.
//
// Only the COMPOSED case can be judged: a name a package installed
// from some OTHER artifact owns is invisible without a database, and
// the same bound the nav check keeps one step above.
permissionSetCollisionWarnings =
await findPermissionSetNameCollisions(result.data as Record<string, unknown>);
if (permissionSetCollisionWarnings.length > 0 && !flags.json) {
console.log('');
printWarning(
`Permission sets declared under a name another package in this artifact owns ` +
`(${permissionSetCollisionWarnings.length}) — at runtime the ENTIRE declared set is ` +
`dropped, not merged (ADR-0086 D4)`,
);
printBulletList(
await formatPermissionSetNameCollisions(permissionSetCollisionWarnings),
{ noun: 'permission-set collision diagnostic' },
);
}
// 3b-iii. [ADR-0146 D2, #28643] The override write gate, at build time —
// the SAME call `os validate` makes at its step 3a-iii, over the
// walk `utils/override-declarations.ts` takes and the publish door's
// own judge (`judgeOverrideWrite`). Only the base's paired
// `<base>.custom` declares an override; a dependent's item bearing a
// name a package in its closure ships, and an `overrides` declaration
// the gate does not admit, are refused. Before this the build emitted
// such an artifact and the managed install or a publish door refused
// it later with the same judge; now the door that ships refuses it
// and writes no artifact.
//
// Beside the dependency-range check below and ahead of every artifact
// write. The `--json` face is this command's failure envelope
// (`errors`, the rows `os validate --json` carries); the text face is
// `os validate`'s. No step line, as on `os validate`.
const overrideRefusals = findOverrideDeclarationRefusals(result.data as Record<string, unknown>);
if (overrideRefusals.length > 0) {
if (flags.json) {
await emitJson({ success: false, errors: overrideRefusals, warnings: warningsSoFar(), conversions: conversionNotices }, 0, { compact: true });
this.exit(1);
}
const n = overrideRefusals.length;
console.log('');
printError(`The publish door would refuse ${n} item${n > 1 ? 's' : ''} under the override write gate (ADR-0146 D2)`);
printBulletList(
overrideRefusals.map((r) => `${r.path} [${r.code}] ${r.message}`),
{ noun: 'override refusal(s)', remedy: JSON_FULL_LIST_REMEDY },
);
this.exit(1);
}
// 3b-quater. ADR-0141 D2, author side — every `manifest.dependencies`
// range of the packages one install act would deliver, judged by the
// install's own predicate (`utils/dependency-range-check.ts`).
//
// REFUSES exactly what the install refuses whatever the target
// environment holds — an unreadable range on an out-of-artifact
// entry, which no installed version can satisfy — so the artifact
// this would emit is one no environment installs. ⛔ The in-artifact
// findings (a sibling's version outside the range, or a co-delivered
// range or version that cannot be read) are ADMITTED by the install,
// which judges a co-delivered entry for presence only; they report,
// and exiting non-zero on them would narrow what `os build` accepts.
const dependencyRanges = checkDependencyRanges(result.data);
const dependencyRangeErrors = dependencyRanges.filter((d) => d.severity === 'error');
dependencyRangeWarnings = dependencyRanges.filter((d) => d.severity !== 'error');
if (dependencyRangeErrors.length > 0) {
if (flags.json) {
await emitJson({ success: false, errors: dependencyRangeErrors, warnings: warningsSoFar(), conversions: conversionNotices }, 0, { compact: true });
this.exit(1);
}
console.log('');
printError(
`Dependency range check failed (${dependencyRangeErrors.length} issue${dependencyRangeErrors.length > 1 ? 's' : ''})`
+ ' — the install refuses every one of these',
);
for (const d of dependencyRangeErrors) console.log(chalk.red(` ✗ ${formatDependencyRangeDiagnostic(d)}`));
this.exit(1);
}
if (dependencyRangeWarnings.length > 0 && !flags.json) {
console.log('');
printWarning(
`Dependency ranges inside this artifact the install does not judge (${dependencyRangeWarnings.length})`
+ ' — a package the same artifact delivers is checked for presence only',
);
printBulletList(dependencyRangeWarnings.map(formatDependencyRangeDiagnostic), { noun: 'dependency-range diagnostic' });
}
// 3c. [#3366] Installable-provider preflight. Every capability the app
// DECLARES in `requires: [...]` must have a provider resolvable in the
// active edition. A `requires` entry whose provider has NO installable
// version in this edition (e.g. `ai` → @objectstack/service-ai,
// cloud-only since ADR-0025) otherwise slips through to a generic
// `os start` crash. Absent-but-installable is a `pnpm add` hint.
//
// Not a registry rule: it reads `node_modules`, not the stack.
//
// [#22189] Read wherever the stack declares `requires`: its top
// level, or each `packages[]` body, naming the package. A
// multi-package `preserve` artifact carries `requires` only in its
// bodies, so a top-level read passed it with exit 0.
if (!flags.json) printStep('Checking that every required capability has a provider installable in this edition...');
const capPreflight = preflightDeclaredCapabilities({
requires: (config as { requires?: unknown }).requires,
packages: packageEntries,
projectDir: path.dirname(absolutePath),
});
// [#11727] MAPPED HERE, once, and consumed by BOTH faces — the text block
// just below and the `--json` payload at the end of this command. The
// hints used to be rendered inside that print block, i.e. under
// `!flags.json`, so the payload could not reach them: computed, then
// discarded, for the one audience `--json` exists to serve. This is
// the same defect #11643 fixed one list over, and the same fix —
// hoist the formatting to the computation site so one list feeds both
// faces. `os validate --json` already maps to exactly this
// `{ token, message }` record beside its own preflight call, so
// mirroring it is what keeps the two commands from reporting
// different sets. One list cannot drift from itself.
capProviderWarnings = capPreflight.warnings.map((c) => ({
token: c.token,
message: renderCapabilityMessage(c),
}));
if (capPreflight.errors.length > 0) {
if (flags.json) {
await emitJson({
success: false,
error: 'capability provider preflight failed',
issues: capPreflight.errors.map((c) => ({ token: c.token, message: renderCapabilityMessage(c) })),
warnings: warningsSoFar(),
conversions: conversionNotices,
}, 0, { compact: true });
this.exit(1);
}
console.log('');
printError(`Capability provider check failed (${capPreflight.errors.length} issue${capPreflight.errors.length > 1 ? 's' : ''})`);
for (const c of capPreflight.errors) {
console.log(` • ${renderCapabilityMessage(c)}`);
}
this.exit(1);
}
if (capProviderWarnings.length > 0 && !flags.json) {
console.log('');
for (const w of capProviderWarnings) {
printWarning(w.message);
}
}
// 3d. [#3786] Keys `ObjectSchema` / `FieldSchema` do not declare, and so
// drop silently on the way to storage. PRE-parse, since the parse is
// what strips them. `defineStack` already warns for configs authored
// through it; this covers the ones that skip it (`strict: false`;
// a plain-object default export no longer gets this far — step 1a
// refuses it) and would otherwise emit an artifact with the key
// quietly gone. Advisory, never fatal.
//
// [#11643] FORMATTED HERE, once, and consumed by BOTH faces — the
// text block just below and the `--json` payload at the end of this
// command. The findings used to be formatted inside that print
// block, i.e. under `!flags.json`, which made them structurally
// unreachable for the payload: computed, then discarded, for the one
// audience `--json` exists to serve. `os validate --json` had this
// exact defect and fixed it this exact way —
// `.map(formatUnknownAuthoringKey)` at the computation site, beside
// its own `normalized` — so hoisting the formatting rather than
// restating it at the payload is what keeps the two faces from
// reporting different sets. One list cannot drift from itself.
//
// [#22238] The item walk reads the package-union stack, as
// `os validate`'s does; the stack-key lint stays on the envelope.
// See `validate.ts` step 2 for why each.
unknownKeyWarnings = [
...lintUnknownStackKeys(normalized as Record<string, unknown>, ObjectStackDefinitionSchema),
...lintUnknownAuthoringKeys(authoringRuleUnionStack(normalized as Record<string, unknown>), ObjectStackDefinitionSchema),
].map(formatUnknownAuthoringKey);
if (unknownKeyWarnings.length > 0 && !flags.json) {
printWarning(`Undeclared authoring keys (${unknownKeyWarnings.length}) — dropped at load; reported here, never refused`);
// [#11642] The header already states the true total, so before this
// notice the block printed two numbers that disagreed and explained
// neither. The pointer resolves because #11643 put this exact list
// into the `--json` payload (`warnings`) a few lines below; it would
// have been a dead end before that landed.
//
// [#11772] …and it resolves on EVERY exit now, which is what makes the
// pointer above unconditional. It used to resolve on the SUCCESS exit
// alone: `warnings` lived in the terminal payload, so a build that
// failed at a LATER gate (access matrix 3e, package docs 3f, the
// runtime bundle, or a throw) emitted that gate's failure payload and
// none of those carried this list — the author was told to re-run with
// `--json` and got a payload without the withheld keys in it. Every
// `emitJson` exit reads `warningsSoFar()`, so this list now survives
// whichever later gate stops the run. ⛔ If a tenth exit is added, it
// carries the lists too, or this pointer goes back to being a claim
// that holds in one branch only — the same shape as the silence
// #11642 was about. `build-json-failure-warnings.e2e.test.ts` pins it.
printBulletList(unknownKeyWarnings, {
noun: 'undeclared authoring key(s)',
remedy: JSON_FULL_LIST_REMEDY,
});
}
// 3e. [ADR-0090 D6] Access-matrix snapshot gate. Opt-in per app: when
// `access-matrix.json` sits next to the config, the (permission set
// × object) capability matrix derived from THIS build must match it
// — a drift fails the build with a SEMANTIC diff ("'crm_admin'
// gains delete on 'crm_lead'") until the snapshot is updated via
// --update-access-matrix. An unchanged matrix auto-passes, so the
// gate costs nothing until someone changes who-can-do-what.
//
// Not a registry rule: it reads (and with the flag, writes) a file
// next to the config rather than answering a question about the stack.
{
const matrixPath = path.join(path.dirname(absolutePath), 'access-matrix.json');
const currentMatrix = buildAccessMatrix(result.data as Record<string, unknown>);
if (flags['update-access-matrix']) {
// Unconditional write — creates or refreshes the snapshot.
fs.writeFileSync(matrixPath, JSON.stringify(currentMatrix, null, 2) + '\n');
if (!flags.json) printStep(`Access matrix snapshot written to ${path.relative(process.cwd(), matrixPath)} (ADR-0090 D6) — review the diff.`);
} else {
// Single read attempt (no exists-then-read TOCTOU): a missing file
// means the app has not opted into the gate; an unreadable/corrupt
// one is treated as empty so the drift report shows every entry.
let committedRaw: string | null = null;
try { committedRaw = fs.readFileSync(matrixPath, 'utf8'); } catch { committedRaw = null; }
if (committedRaw !== null) {
if (!flags.json) printStep('Checking access-matrix snapshot (ADR-0090 D6)...');
let committed: any = { version: 1, entries: [] };
try { committed = JSON.parse(committedRaw); } catch { /* corrupt = empty */ }
const drift = diffAccessMatrix(committed, currentMatrix);
if (drift.length > 0) {
if (flags.json) {
await emitJson({ success: false, error: 'access matrix drift', changes: drift, warnings: warningsSoFar(), conversions: conversionNotices }, 0, { compact: true });
this.exit(1);
}
console.log('');
printError(`Access matrix drift (${drift.length} change${drift.length > 1 ? 's' : ''}) — capability changes must be reviewed`);
// [#11642] `--json` on this same exit publishes the whole diff
// as `changes`, so the pointer resolves for this list too.
printBulletList(drift, {
noun: 'access-matrix change(s)',
remedy: JSON_FULL_LIST_REMEDY,
});
console.log(chalk.dim(' If intended, re-run with --update-access-matrix and commit the snapshot — its diff IS the review artifact.'));
this.exit(1);
}
}
}
}