@sema-agent/settings-schema 35.0.0 → 35.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1190 @@
1
+ #!/usr/bin/env node
2
+ // sema-profile@1 judgment-vector runner (reference draft).
3
+ //
4
+ // Package boundary note: this script is reference material handed over by the engine team. Running it
5
+ // requires source snapshots of other repositories (including a source checkout of settings-schema that
6
+ // contains `src/portable-domains.ts`, which is not shipped in the npm package) and is NOT runnable from
7
+ // the installed `@sema-agent/settings-schema` package alone. What this package guarantees is the reader
8
+ // exported from `@sema-agent/settings-schema/conformance` and the shipped files themselves.
9
+ //
10
+ // Read-only over every file root it is pointed at; writes only the --annotate file when asked. No tree root is written into
11
+ // this file: every location arrives as an argument. Each root is a directory holding source snapshots from the respective
12
+ // external repositories (in the engine, server, CLI, and schema repositories):
13
+ // --server src/config-catalog.ts · src/config-types.ts · src/env-scalar.ts · src/read-deny-entry.ts (constants the catalog
14
+ // imports into its literal column, from the server repository)
15
+ // --schema dist/ (the built package: settings-schema's exports are imported) · src/portable-domains.ts (source checkout only; not in the npm tarball)
16
+ // --core src/core/ask-origin.ts · src/tools/fs/read-deny.ts · node_modules/ajv (from the engine repository)
17
+ // --cli src/sema/settings/keyContracts.ts · src/sema/engineLifecycleManager.ts · src/sema/spawnedEngineExecLanePort.ts (from the CLI repository)
18
+ // --comms knobs.json (historical knob inventory snapshot)
19
+ // Every value judgment is delegated to the existing single judge it names: the server config catalog (parsed as text,
20
+ // never evaluated), settings-schema's published exports (layerAdmission, SAFETY_MERGE_SPEC, SETTINGS_UNITS, readSettingsUnit,
21
+ // unitTighten, tightenVerdict, RUNTIME_CAP_STRICT, DOMAIN_SCHEMAS, RETIRED_ENVS, containsSecretToken, classifyHooksConfig,
22
+ // EXECUTION_LANES, EntitlementRuntimeCaps, WEB_ADMIN_ENV), the cli shell's child-env assignments (parsed as text), and core's
23
+ // vocabularies (parsed as text). One reading is mirrored, not imported: the server's readCatalogRowLiteral (TS behind server
24
+ // imports) — see readEnvLiteral. Where this file needs a closed set it reads it from its owner; the projection checks fail when
25
+ // the schema's copy drifts.
26
+ //
27
+ // Comparators for the env segment: the server catalog's own `tighten` column (server 7.154.0 in the server repository; a row without
28
+ // it has no comparator ⇒ unequal = conflict), its two literals read through the row's `literal` facts, the comparison done by
29
+ // settings-schema tightenVerdict. The B4 authoring invariant reads the same column. The earlier proposed-tighten vector mode is
30
+ // retired and superseded by the catalog's own `tighten` column.
31
+ //
32
+ // Usage:
33
+ // node validate.mjs --design <profile dir> --server <server-files-root> --schema <settings-schema-root (with dist)>
34
+ // --core <core-files-root> --cli <cli-files-root> --comms <comms-files-root> [--knobs-fresh <knobs.json>]
35
+ // [--mutate <checkId>] [--annotate <out.md>] [--quiet] [--dump-rows <vector id | all>]
36
+ // A positive vector passes only when the loader's report equals its expectRows exactly (present rows listed, every other row
37
+ // absent) and, when given, the snapshot it writes equals expectSnapshotEnv; "no refusal" alone never passes. Every executed
38
+ // vector also checks the envelope (mode; disposition = applied for a positive, refused for a negative; the selector present exactly
39
+ // when a snapshot is written) and all-or-nothing (a refused report writes no snapshot). A loader-mutation vector (mutateLoader)
40
+ // passes when the mutated loader's report carries its expectMutantRows. A posture vector (B4) compares an expanded parent with an
41
+ // expanded child through the same function as the builtin check. --dump-rows prints report rows (with `all`, also the rows of the
42
+ // vectors this loader does not run, marked deferred).
43
+ // Exit 0 ⇔ every executed vector meets its expectation, every builtin invariant holds and every projection matches.
44
+ // Vectors whose executedBy does not name `reference` are listed as deferred and counted apart; they never pass here.
45
+
46
+ import { readFileSync, writeFileSync, existsSync } from "node:fs";
47
+ import { createHash } from "node:crypto";
48
+ import path from "node:path";
49
+ import { pathToFileURL } from "node:url";
50
+
51
+ const args = {};
52
+ for (let i = 2; i < process.argv.length; i++) {
53
+ const a = process.argv[i];
54
+ if (a.startsWith("--")) args[a.slice(2)] = process.argv[i + 1] !== undefined && !process.argv[i + 1].startsWith("--") ? process.argv[++i] : true;
55
+ }
56
+ for (const need of ["design", "server", "schema", "core", "cli", "comms"]) {
57
+ if (typeof args[need] !== "string") {
58
+ console.error(`missing --${need}`);
59
+ process.exit(2);
60
+ }
61
+ }
62
+ const MUTATE = typeof args.mutate === "string" ? args.mutate : undefined;
63
+ const on = (checkId) => MUTATE !== checkId; // a mutated check is switched off
64
+ const readText = (p) => readFileSync(p, "utf8");
65
+ const readJson = (p) => JSON.parse(readText(p));
66
+ const imp = (p) => import(pathToFileURL(p).href);
67
+
68
+ // ── owners ─────────────────────────────────────────────────────────────────────────────────────────────────────────
69
+ const SS = await imp(path.join(args.schema, "dist/index.js"));
70
+ const Ajv2020 = (await imp(path.join(args.core, "node_modules/ajv/dist/2020.js"))).default;
71
+
72
+ const catalog = parseCatalog(readText(path.join(args.server, "src/config-catalog.ts")), SS.WEB_ADMIN_ENV);
73
+ const ENUM_CONSTS = {
74
+ AUTONOMY_MODES: SS.AUTONOMY_MODES,
75
+ STORE_BACKENDS: SS.STORE_BACKENDS,
76
+ MEMORY_ENGINE_BACKENDS: SS.MEMORY_ENGINE_BACKENDS,
77
+ CONFIG_PROVIDER_WORDS: constArray(readText(path.join(args.server, "src/config-types.ts")), "CONFIG_PROVIDER_WORDS"),
78
+ ALL_EXECUTION_LANES: SS.EXECUTION_LANE_WORDS, // server execution-lane-caps.ts:412 ALL_EXECUTION_LANES = [...DECLARABLE_LANE_WORDS], imported from settings-schema EXECUTION_LANE_WORDS (:67)
79
+ };
80
+ const retiredEnvNames = new Set(SS.RETIRED_ENVS.map((e) => (Array.isArray(e) ? e[0] : e.name ?? e.old)));
81
+ const corePermissionModes = constArray(readText(path.join(args.core, "src/core/ask-origin.ts")), "PERMISSION_MODES");
82
+ const coreReadDenyTiers = constArray(readText(path.join(args.core, "src/tools/fs/read-deny.ts")), "READ_DENY_BUILTIN_TIERS");
83
+ // settings-schema 14.6.0 moved the portable-domain table into its own leaf module and no longer exports it from the package root
84
+ // (this reads a source-tree path from a settings-schema source checkout; `src/` is not shipped in the installed npm package)
85
+ const portableDomains = constArray(readText(path.join(args.schema, "src/portable-domains.ts")), "PORTABLE_DOMAINS");
86
+ const cliKeyContractsText = readText(path.join(args.cli, "src/sema/settings/keyContracts.ts"));
87
+ const childEnv = parseChildEnv(readText(path.join(args.cli, "src/sema/engineLifecycleManager.ts")), args.cli);
88
+ // the server's boolean words live with its one boolean parser (env-scalar.ts parseBoolWord), not in config.ts any more
89
+ const serverScalarText = readText(path.join(args.server, "src/env-scalar.ts"));
90
+ const serverBoolWords = { true: new Set(setWords(serverScalarText, "BOOL_TRUE_WORDS")), false: new Set(setWords(serverScalarText, "BOOL_FALSE_WORDS")) };
91
+
92
+ // ── deliverables ───────────────────────────────────────────────────────────────────────────────────────────────────
93
+ const schema = readJson(path.join(args.design, "sema-profile.schema.json"));
94
+ if (MUTATE === "L3") {
95
+ delete schema.if; // mutated: the null-only-with-a-parent rule switched off
96
+ delete schema.then;
97
+ }
98
+ const BUILTIN_NAMES = ["solo-auto", "solo-managed", "tenant-auto", "tenant-managed"];
99
+ const builtins = Object.fromEntries(BUILTIN_NAMES.map((n) => [n, readJson(path.join(args.design, "profiles", `${n}.json`))]));
100
+ applyProfileMutations(builtins);
101
+ const vectors = readJson(path.join(args.design, "vectors/vectors.json")).vectors;
102
+ // the frozen promises (check group F): a deliberate second copy of the facts a product promise rests on — builtin values, the
103
+ // channel × destination table, the keys read before the fold, the report's closed word sets. Not a source: nothing below reads a
104
+ // behaviour from it; it is only compared against.
105
+ const frozen = readJson(path.join(args.design, "vectors/frozen-promises.json"));
106
+ if (MUTATE === "F:table-row-deleted") delete frozen.builtins["tenant-managed"]["server.env"].MEMORY_CAPTURE_POLICY;
107
+ if (MUTATE === "F:table-value-changed") frozen.builtins["solo-auto"].settings["permissions.defaultMode"] = "default";
108
+
109
+ const ajv = new Ajv2020({ allErrors: true, strict: true, allowUnionTypes: true }); // union types: the recursive noNull definition
110
+ ajv.addVocabulary(["x-sema-judge", "x-sema-category", "x-sema-consumer", "x-sema-strict", "x-sema-projection"]);
111
+ const validateShape = ajv.compile(schema);
112
+
113
+ const results = [];
114
+ const record = (group, id, ok, detail) => results.push({ group, id, ok, detail });
115
+
116
+ // ── loader (the L rules) ───────────────────────────────────────────────────────────────────────────────────────────
117
+ const CHANNEL_DESTINATIONS = {
118
+ builtin: ["deploy", "policy", "user", "project", "local", "flag", "session"],
119
+ org: ["deploy", "policy"],
120
+ user: ["deploy", "user", "project", "local", "flag", "session"],
121
+ };
122
+ if (MUTATE === "F:matrix-cell") CHANNEL_DESTINATIONS.org.push("user"); // mutated: an org response may install into the user settings
123
+ const DEST_SOURCE = { policy: "policySettings", user: "userSettings", project: "projectSettings", local: "localSettings", flag: "flagSettings" };
124
+ const REF = /^\$\{([A-Za-z_][A-Za-z0-9_]*)\}$/;
125
+ // keys read before the fold — a profile cannot set them (read_before_fold). v1 = the selector only.
126
+ const READ_BEFORE_FOLD = new Set(["SEMA_PROFILE"]);
127
+
128
+ // The report and its envelope (loading-rules.md §1.1). All-or-nothing: a report with any rejected row writes nothing — the
129
+ // destination file, the snapshot and the selector stay as they were — so a refused report carries no snapshot and no selector.
130
+ function load(doc, ctx) {
131
+ const { rows, snapshot } = loadRows(doc, ctx);
132
+ const refused = rows.some((r) => r.outcome === "rejected");
133
+ const writes = snapshot !== undefined && (!refused || MUTATE === "ALL:snapshot-on-refusal");
134
+ rows.snapshot = writes ? snapshot : undefined;
135
+ rows.envelope = {
136
+ mode: ctx.mode ?? "commit",
137
+ disposition: refused && MUTATE !== "ENV:always-applied" ? "refused" : "applied",
138
+ // the selector write (user settings env.SEMA_PROFILE → the snapshot) is the landing's mechanism, not a report row
139
+ ...(writes ? { selector: { file: DEST_SOURCE.user, key: "env.SEMA_PROFILE", snapshotDigest: digest(snapshot) } } : {}),
140
+ };
141
+ return rows;
142
+ }
143
+ function digest(o) {
144
+ const canon = (x) => (x === null || typeof x !== "object" ? x : Array.isArray(x) ? x.map(canon) : sortKeys(Object.fromEntries(Object.entries(x).map(([k, v]) => [k, canon(v)]))));
145
+ return `sha256:${createHash("sha256").update(JSON.stringify(canon(o))).digest("hex")}`;
146
+ }
147
+
148
+ function loadRows(doc, ctx) {
149
+ const rows = [];
150
+ const done = () => ({ rows: finish(rows), snapshot: undefined });
151
+ const reject = (segment, key, code, detail) => rows.push({ segment, key, outcome: "rejected", code, detail });
152
+ const skip = (segment, key, code, detail) => rows.push({ segment, key, outcome: "skipped", code, detail });
153
+ const write = (segment, key, detail, value) => rows.push({ segment, key, outcome: "written", detail, value });
154
+ const same = (segment, key) => rows.push({ segment, key, outcome: "unchanged" });
155
+ const out = { reject, skip, write, same };
156
+
157
+ // L1 is unconditional: every destination, every layer of the chain (below), before any null deletion
158
+ if (on("L1")) {
159
+ const problem = docProblem(doc);
160
+ if (problem !== undefined) {
161
+ reject("*", "*", problem.code, problem.detail);
162
+ return done();
163
+ }
164
+ }
165
+ const channel = ctx.channel ?? "user";
166
+ const destination = ctx.destination ?? "user";
167
+ if (on("L2") && !CHANNEL_DESTINATIONS[channel]?.includes(destination)) {
168
+ reject("*", "*", "channel_target", `${channel} -> ${destination}`);
169
+ return done();
170
+ }
171
+ let flat;
172
+ try {
173
+ // L4: a parent resolves in the same channel's namespace or among the builtins — except at deploy, where the server fold's parent
174
+ // lookup knows the four builtins only (a missing parent refuses: server design, relayed)
175
+ const namespace = destination === "deploy" && MUTATE !== "L4:deploy-any-parent" ? {} : ctx.parents ?? {};
176
+ flat = expand(doc, { ...namespace, [doc.meta.name]: doc }, channel); // the document is part of its own namespace
177
+ } catch (e) {
178
+ reject("*", "*", e.code ?? "extends", e.message);
179
+ return done();
180
+ }
181
+ if (on("L4")) {
182
+ const problem = docProblem(flat);
183
+ if (problem !== undefined) {
184
+ reject("*", "*", problem.code, `after expansion: ${problem.detail}`);
185
+ return done();
186
+ }
187
+ }
188
+ // The destination is read INSIDE the write lock, fresh: `existingAtWrite` is what another writer left
189
+ // there after the loader's first look; comparing or merging against the earlier snapshot would drop that writer's entries.
190
+ const destinationNow = MUTATE === "L12:stale-read" ? ctx.existing : ctx.existingAtWrite ?? ctx.existing;
191
+ const jctx = {
192
+ // names the fold's env will carry (a reference must resolve against them; values never appear in a vector)
193
+ envNames: new Set(ctx.deploymentEnvNames ?? []),
194
+ configD: flat.server?.["config.d"] ?? {},
195
+ localSpawn: destination === "user",
196
+ // L12's base for the server segment at the user landing = the snapshot the user settings' selector points at (written by this
197
+ // loader's own record, digest-checked); never the settings.env block
198
+ existingEnv: destination === "user" ? destinationNow?.snapshot?.env : undefined,
199
+ // L13: what the fill-absent fold will find already set. deploy = the OS env (osEnv carries values of non-secret rows,
200
+ // deploymentEnvNames names whose value the vector does not show); user = what the shell hands the child env before the local
201
+ // engine folds the snapshot in (shellChildEnv)
202
+ ...(destination === "deploy"
203
+ ? { osEnv: { ...Object.fromEntries((ctx.deploymentEnvNames ?? []).map((n) => [n, undefined])), ...(ctx.osEnv ?? {}) }, osSource: {} }
204
+ : destination === "user"
205
+ ? shellChildEnv(destinationNow?.settings?.env)
206
+ : { osEnv: {}, osSource: {} }),
207
+ foldOverwrites: ctx.mutateLoader === "foldOverwritesOsEnv",
208
+ };
209
+
210
+ // server segment
211
+ const env = flat.server?.env ?? {};
212
+ let snapshot;
213
+ if (flat.server !== undefined) {
214
+ const serverAllowed = destination === "deploy" || jctx.localSpawn;
215
+ let segmentVerdict;
216
+ if (on("L9") && !serverAllowed) segmentVerdict = `server segment is not applied at ${destination}`;
217
+ // center delivery at the deploy fold arrives after loadConfig and center already publishes through
218
+ // domain documents: a center-delivered profile carries no server.env (one fact, one lane)
219
+ if (on("L9") && channel === "org" && destination === "deploy" && Object.keys(env).length > 0) segmentVerdict = "a center-delivered profile carries no server.env; publish the value through its config domain";
220
+ if (on("L9") && jctx.localSpawn && segmentVerdict === undefined) {
221
+ const clash = Object.entries(env).map(([k, v]) => localSpawnClash(k, v)).filter(Boolean);
222
+ if (clash.length > 0) segmentVerdict = `the local engine cannot take ${clash.join(", ")}; install it deploy-side with SEMA_PROFILE`;
223
+ }
224
+ // a selector already in the user settings that this loader's record did not write is not taken over (fail closed)
225
+ // (the reference model reads "no install record" as "no snapshot written by this loader's record" — existing.snapshot absent)
226
+ const selector = destinationNow?.settings?.env?.SEMA_PROFILE;
227
+ const ownRecord = destinationNow?.snapshot !== undefined && MUTATE !== "L12:refuse-own-selector";
228
+ if (on("L12") && jctx.localSpawn && segmentVerdict === undefined && selector !== undefined && !ownRecord) {
229
+ segmentVerdict =
230
+ MUTATE === "L12:selector-unnamed"
231
+ ? "the user settings already carry a selector that no install record of this loader wrote; it is not taken over"
232
+ : `the user settings already carry env.SEMA_PROFILE=${selector}, which no install record of this loader wrote; it is not taken over`;
233
+ }
234
+ if (segmentVerdict !== undefined) {
235
+ reject("server", "*", "segment_target", segmentVerdict);
236
+ } else {
237
+ for (const [k, v] of Object.entries(env)) judgeEngineKnob("server.env", k, k, v, out, jctx);
238
+ for (const [d, value] of Object.entries(jctx.configD)) {
239
+ const zodSchema = SS.DOMAIN_SCHEMAS[d];
240
+ if (on("L5b") && (zodSchema === undefined || !zodSchema.safeParse(value).success)) reject("server.config.d", d, "domain_shape");
241
+ else write("server.config.d", d, "lowest-priority in-memory overlay: any value already on a higher layer wins, so nothing here can loosen it");
242
+ }
243
+ // the user landing writes the expanded server segment, verbatim (references stay ${NAME}), as the snapshot the selector points at
244
+ if (jctx.localSpawn) snapshot = { env: { ...env }, ...(Object.keys(jctx.configD).length > 0 ? { "config.d": jctx.configD } : {}) };
245
+ }
246
+ }
247
+
248
+ // settings segment
249
+ if (flat.settings !== undefined) {
250
+ const units = settingsUnits(flat.settings);
251
+ if (destination === "deploy") {
252
+ for (const u of units) skip("settings", u.path, "not_applied_here");
253
+ } else {
254
+ for (const u of units) {
255
+ if (destination === "session" && !/^permissions\.(allow|deny|ask)$/.test(u.path)) {
256
+ if (on("L9")) reject("settings", u.path, "segment_target", "a session install carries only permissions.allow / deny / ask");
257
+ continue;
258
+ }
259
+ if (u.path.startsWith("env.")) {
260
+ const name = u.path.slice(4);
261
+ // the selector itself is read before any fold: more specific than the catalog-name refusal, judged first
262
+ if (on("L5") && READ_BEFORE_FOLD.has(name)) {
263
+ reject("settings", u.path, "read_before_fold", `${name} is read before the fold; a profile does not choose itself`);
264
+ continue;
265
+ }
266
+ // classified by NAME, not by segment: an engine knob is set only through server.env, at every
267
+ // destination (one lane: SEMA_PROFILE → the fold)
268
+ if (catalog[name] !== undefined && on("L9b")) {
269
+ reject("settings", u.path, "catalog_name_in_settings_env", "an engine knob is set through server.env only (SEMA_PROFILE → the fold)");
270
+ continue;
271
+ }
272
+ // the shell has no resolution stage for settings.env: a profile's settings.env takes literals only (v1)
273
+ // detail = the fixed token no_resolution_stage (the server.env arm's detail is the unresolved NAME): a machine-checkable reason
274
+ if (typeof u.value === "string" && REF.test(u.value) && on("L7")) {
275
+ reject("settings", u.path, "reference_unresolved", MUTATE === "L7:detail-prose" ? "settings.env has no resolution stage" : "no_resolution_stage");
276
+ continue;
277
+ }
278
+ if (typeof u.value === "string" && SS.containsSecretToken(u.value) && on("L6")) {
279
+ reject("settings", u.path, "secret_literal");
280
+ continue;
281
+ }
282
+ }
283
+ const source = DEST_SOURCE[destination];
284
+ if (source !== undefined && on("L11")) {
285
+ // an unknown trust reading fails closed (settings-sources.ts: a host that cannot read the decision passes "declined")
286
+ const workspace = ctx.workspace ?? (SS.settingsSourceContract(source).repoControllable ? "declined" : "no_trust_step");
287
+ const verdict = SS.layerAdmission(source, workspace, u.category, u.member, u.value);
288
+ if (verdict !== "admitted") {
289
+ reject("settings", u.path, "layer_admission", verdict);
290
+ continue;
291
+ }
292
+ }
293
+ const existing = destinationNow?.settings !== undefined ? getUnit(destinationNow.settings, u.path) : undefined;
294
+ if (existing !== undefined && u.category === "permissions") {
295
+ // contract-aware merge: a rule list joins the file's list, it never replaces it
296
+ write("settings", u.path, "joined with the destination's existing list", [...new Set([...existing, ...u.value])]);
297
+ continue;
298
+ }
299
+ if (existing !== undefined && on("L12")) {
300
+ const outcome = compareSetting(u, existing, u.value);
301
+ if (outcome === "unchanged") same("settings", u.path);
302
+ else if (outcome === "write") write("settings", u.path, undefined, u.value);
303
+ else reject("settings", u.path, outcome);
304
+ continue;
305
+ }
306
+ write("settings", u.path, undefined, u.value);
307
+ }
308
+ }
309
+ }
310
+
311
+ // entitlement segment
312
+ if (flat.entitlement !== undefined && MUTATE !== "M25:no-entitlement-report") {
313
+ for (const k of Object.keys(flat.entitlement.runtimeCaps ?? {})) {
314
+ if (destination === "deploy") skip("entitlement", k, "not_applied_here");
315
+ else if (ctx.mutateLoader === "writeEntitlementLocally" || !on("L14")) write("entitlement", k, "local entitlement file");
316
+ else skip("entitlement", k, "template", "template, not enforced locally");
317
+ }
318
+ }
319
+ return { rows: finish(rows), snapshot }; // load() applies all-or-nothing and builds the envelope
320
+ }
321
+
322
+ function sortKeys(o) {
323
+ return o === undefined ? undefined : Object.fromEntries(Object.entries(o).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)));
324
+ }
325
+
326
+ // M26 (mutation): a loader that reports only its refusals — every positive vector's exact-output assertion must catch it.
327
+ function finish(rows) {
328
+ return MUTATE === "M26:drop-success-rows" ? rows.filter((r) => r.outcome === "rejected") : rows;
329
+ }
330
+
331
+ // L1 for one document: the schema, then the hooks judge on a non-null hooks block.
332
+ function docProblem(doc) {
333
+ if (!validateShape(doc)) return { code: "shape", detail: ajv.errorsText(validateShape.errors) };
334
+ const hooks = doc.settings?.hooks;
335
+ if (hooks !== undefined && hooks !== null) {
336
+ const verdict = SS.classifyHooksConfig(hooks);
337
+ if (verdict.outcome !== "loaded") return { code: "hooks_shape", detail: JSON.stringify(verdict.rejections) };
338
+ }
339
+ return undefined;
340
+ }
341
+
342
+ // One judge for an engine knob (server.env; settings.env no longer carries engine knobs — L9b refuses them by name).
343
+ function judgeEngineKnob(segment, key, name, v, out, jctx) {
344
+ const row = catalog[name];
345
+ if (on("L5") && READ_BEFORE_FOLD.has(name)) return out.reject(segment, key, "read_before_fold", `${name} is read before the fold; a profile does not choose itself`);
346
+ if (on("L5") && retiredEnvNames.has(name)) return out.reject(segment, key, "retired_key");
347
+ if (on("L5") && row === undefined) return out.reject(segment, key, "unknown_key");
348
+ if (row === undefined) return out.write(segment, key);
349
+ if (on("L5") && row.envTiming === "inert") return out.reject(segment, key, "inert_key");
350
+ const ref = typeof v === "string" ? v.match(REF) : null;
351
+ if (on("L6") && row.type === "secret" && ref === null) return out.reject(segment, key, "secret_literal");
352
+ if (ref !== null) {
353
+ if (on("L7") && ref[1] === name) return out.reject(segment, key, "reference_self");
354
+ if (on("L7") && row.type !== "secret" && catalog[ref[1]]?.type === "secret") return out.reject(segment, key, "reference_secret", `${ref[1]} is a secret row`);
355
+ if (on("L7") && !jctx.envNames.has(ref[1])) return out.reject(segment, key, "reference_unresolved", ref[1]);
356
+ } else if (on("L5")) {
357
+ const problem = literalProblem(row, v);
358
+ if (problem !== undefined) return out.reject(segment, key, problem.code, problem.detail);
359
+ }
360
+ const seat = centerSeat(row.center);
361
+ if (on("L8") && seat?.domain !== undefined && seat.path !== undefined && getPath(jctx.configD[seat.domain], seat.path) !== undefined) {
362
+ return out.reject(segment, key, "two_lanes", `${seat.domain}.${seat.path}`);
363
+ }
364
+ if (jctx.localSpawn && childEnv.forcedLiteral[name] === v) return out.skip(segment, key, MUTATE === "F:code-renamed" ? "host_forced_equal" : "host_forced_same");
365
+ // L12 at the user landing: the snapshot already installed (the selector's target) meets the new value under the row's comparator
366
+ // (the catalog `tighten` column; a row without one ⇒ unequal = conflict). The deploy fold has no file to compare against.
367
+ let sameAsSnapshot = false;
368
+ if (jctx.existingEnv?.[name] !== undefined && on("L12")) {
369
+ const outcome = compareEnv(name, jctx.existingEnv[name], v);
370
+ if (outcome === "unchanged") sameAsSnapshot = true;
371
+ else if (outcome !== "write") return out.reject(segment, key, outcome);
372
+ }
373
+ // L13: the fold fills absent keys only. A key the fold finds set (by the owner's reading of "set": catalog literal.blank) keeps its
374
+ // value — at deploy the OS env (boot notice config.profile_key_shadowed), at the user landing whatever the shell hands the child
375
+ // env, its own defaults included (the report says so: it is not reported written; the snapshot still carries the profile's value).
376
+ // Equal by the owner's reading ⇒ unchanged, no notice. A set value this reader does not know (a computed shell default, a name
377
+ // without a value) cannot be shown equal ⇒ the set value wins.
378
+ if (on("L13") && !jctx.foldOverwrites && Object.hasOwn(jctx.osEnv, name)) {
379
+ const os = jctx.osEnv[name];
380
+ const reading = os === undefined ? { kind: "unknown" } : readEnvLiteral(name, os);
381
+ if (reading.kind !== "absent") {
382
+ const mine = readEnvLiteral(name, v);
383
+ if (reading.kind === "value" && mine.kind === "value" && JSON.stringify(reading.value) === JSON.stringify(mine.value)) return out.same(segment, key);
384
+ // L12:deploy-compare (mutation): L12's "unequal without a comparator is refused" carried onto the deploy landing
385
+ if (MUTATE === "L12:deploy-compare" && !jctx.localSpawn && catalog[name]?.tighten === undefined) return out.reject(segment, key, "conflict_no_comparator");
386
+ const why = !jctx.localSpawn
387
+ ? "the OS env value wins; boot notice config.profile_key_shadowed"
388
+ : jctx.osSource[name] === "shell-default"
389
+ ? `the shell sets ${name} in the child env itself (its default ${os === undefined ? "is computed" : JSON.stringify(os)} when nothing is inherited); the snapshot value does not take effect`
390
+ : "the user's own settings.env key wins in the child env; the snapshot value does not take effect";
391
+ return out.skip(segment, key, "os_env_wins", why);
392
+ }
393
+ }
394
+ if (sameAsSnapshot) return out.same(segment, key);
395
+ out.write(segment, key, jctx.localSpawn ? "snapshot (the local engine's SEMA_PROFILE fold)" : "process env (fill-absent fold)", v);
396
+ }
397
+
398
+ // One literal form per value (the profile format admits no second spelling): the judge is the server's own reading — a literal is
399
+ // written only when readCatalogRowLiteral reads it as a value AND marks that literal the value's one canonical spelling (its
400
+ // `canonical` bit, catalog-literal.ts:32 / :73 / :84 / :89 / :90). Boolean: only "true" / "false"; number: only String(n) (so "0.0",
401
+ // "-0", "1e3", " 5" are refused) and, on a row whose non-positive values mean "off" (literal.offAtOrBelow), only "0"; csv: items
402
+ // joined by "," with no blanks around them. Enum rows keep their own code: a word outside echoWords ?? enumValues (absence spelled
403
+ // differently, or no word at all) is enum_value.
404
+ function literalProblem(row, v) {
405
+ if (row.type === "enum") {
406
+ const domain = enumDomain(row);
407
+ if (domain === undefined) return { code: "enum_value", detail: "the row's word set is not resolvable by this loader (fail closed)" };
408
+ if (!domain.includes(v)) return { code: "enum_value", detail: `${v} not in ${domain.join("|")}` };
409
+ return undefined;
410
+ }
411
+ const r = MUTATE === "L5:regex-number" ? regexReading(row, v) : readCatalogLiteral(row, v);
412
+ if (r.kind === "value" && r.canonical) return undefined;
413
+ const why = r.kind === "absent" ? "reads as not set (omit the key instead)" : r.kind === "unreadable" ? "the server cannot read it" : `the server reads it, but its one spelling is ${JSON.stringify(r.spelling)}`;
414
+ return { code: "non_canonical", detail: `${row.type} row ${row.name}: ${JSON.stringify(v)} ${why}` };
415
+ }
416
+ // L5:regex-number (mutation): the pre-round-2 reading — a decimal regex for numbers, nothing for csv
417
+ function regexReading(row, v) {
418
+ if (row.type === "number") return /^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*[1-9])?$/.test(v) ? { kind: "value", value: Number(v), canonical: true } : { kind: "unreadable" };
419
+ if (row.type === "csv") return { kind: "value", value: v.split(","), canonical: true };
420
+ return readCatalogLiteral(row, v);
421
+ }
422
+
423
+ // Does a snapshot value for `name` collide with the shell's child-env assembly? The judge is the shell's disposition table, its
424
+ // profile column (cli has not exported it yet, G-3) — until it arrives this reference reads the assembly's source
425
+ // (parseChildEnv), class by class:
426
+ // forced to another literal / forced to a computed value ⇒ clash; forced to the same literal ⇒ host_forced_same (judgeEngineKnob);
427
+ // scrubbed = deleted UNCONDITIONALLY (whenever present, whatever anyone declared) ⇒ clash: the fill-absent fold would put back
428
+ // what the shell removes on purpose;
429
+ // deleted CONDITIONALLY (one arm of the shell's own decision: set a value, or delete) ⇒ no clash: on the delete arm the fold fills
430
+ // the key and the profile's value takes effect; on the set arm the shell's value is already there (L13 — how the report learns
431
+ // of that arm is loading-rules.md §6 G-14);
432
+ // defaulted (the inherited value, else the shell's own default) ⇒ no clash: the key is always set in the child env, so L13 reports it.
433
+ function localSpawnClash(name, value) {
434
+ if (childEnv.forcedLiteral[name] !== undefined && childEnv.forcedLiteral[name] !== value) return `${name}=${value} (the shell forces ${childEnv.forcedLiteral[name]})`;
435
+ if (childEnv.forcedDynamic.has(name)) return `${name}=${value} (the shell assigns it itself)`;
436
+ if (childEnv.scrubbed.has(name)) return `${name}=${value} (the shell removes it from the child env)`;
437
+ if (MUTATE === "L9:conditional-delete-scrubbed" && childEnv.conditionalDelete.has(name)) return `${name}=${value} (mutated: a conditional delete read as a scrub)`;
438
+ // stand-in for the table's REQUIRE_PRINCIPAL row (yield only "false"): the multi-tenant switch is not a local-engine posture
439
+ if (name === "REQUIRE_PRINCIPAL" && value !== "false") return `${name}=${value} (multi-tenant posture is deploy-side only)`;
440
+ return undefined;
441
+ }
442
+
443
+ // L12n (env half) — before ANY comparison both sides go through the owner's one literal reading: the server's readCatalogRowLiteral
444
+ // (catalog-literal.ts:50-102, server 7.154.0), mirrored here read-only for the reference run (it is TS behind server imports, so it is
445
+ // not imported): boolean = the server's word sets (env-scalar.ts BOOL_TRUE_WORDS / BOOL_FALSE_WORDS, read from source); enum = exact
446
+ // word in echoWords ?? enumValues (a word only in enumValues = absence spelled differently); csv = trimmed items, the row's
447
+ // literal.emptyWord alone = []; number = finite parse, literal.offAtOrBelow and not > 0 = +Infinity (numericLower's "no ceiling");
448
+ // blank per literal.blank (absent by default / refused = unreadable). A reference has no value before the single resolution stage.
449
+ // Returns { kind: "value", value, canonical, spelling } | { kind: "absent" } | { kind: "unreadable" } (`spelling` = the value's one
450
+ // canonical literal, for the L5 detail). A reference has no value before the single resolution stage.
451
+ function readEnvLiteral(name, raw) {
452
+ if (raw === undefined) return { kind: "absent" };
453
+ if (MUTATE === "L12n") return { kind: "value", value: raw, canonical: true }; // mutated: compare raw strings
454
+ if (typeof raw !== "string" || REF.test(raw)) return { kind: "unreadable" };
455
+ return readCatalogLiteral(catalog[name] ?? { name, type: "string" }, raw);
456
+ }
457
+ function readCatalogLiteral(row, raw) {
458
+ const lit = row.literal ?? {};
459
+ const text = lit.spelling === "trim" ? raw.trim() : raw;
460
+ if (text === "" && lit.blank !== "value") return lit.blank === "refused" ? { kind: "unreadable" } : { kind: "absent" };
461
+ if (lit.words === "on-off") return { kind: "unreadable" }; // the on/off word table is not mirrored here (no vector uses it): fail closed
462
+ const value = (v, spelling) => ({ kind: "value", value: v, canonical: raw === spelling, spelling });
463
+ switch (row.type) {
464
+ case "boolean": {
465
+ const w = text.toLowerCase();
466
+ if (serverBoolWords.true.has(w)) return value(true, "true");
467
+ if (serverBoolWords.false.has(w)) return value(false, "false");
468
+ return { kind: "unreadable" };
469
+ }
470
+ case "enum": {
471
+ if (enumDomain(row)?.includes(text)) return value(text, text);
472
+ return enumWords(row.enumValues)?.includes(text) ? { kind: "absent" } : { kind: "unreadable" };
473
+ }
474
+ case "csv": {
475
+ const items = text.split(",").map((x) => x.trim()).filter(Boolean); // server csvOf (model-route-gap.ts:110)
476
+ if (lit.emptyWord !== undefined && items.length === 1 && items[0] === lit.emptyWord) return value([], lit.emptyWord);
477
+ return value(items, items.join(","));
478
+ }
479
+ case "number": {
480
+ const n = Number(text); // server parseNumOrFail (env-scalar.ts:85): Number(), finite or refused
481
+ if (!Number.isFinite(n)) return { kind: "unreadable" };
482
+ if (lit.offAtOrBelow !== undefined && !(n > 0)) return value(Number.POSITIVE_INFINITY, "0"); // capIsOff (cap-off.ts:17)
483
+ return value(n, String(n));
484
+ }
485
+ default:
486
+ return value(text, text);
487
+ }
488
+ }
489
+
490
+ // L12 for one env key: the existing value (fresh, inside the write lock) against the profile's, through the row's own comparator —
491
+ // the catalog `tighten` column, compared by settings-schema tightenVerdict (the one implementation). No comparator ⇒ unequal = conflict.
492
+ function compareEnv(name, existing, next) {
493
+ const a = readEnvLiteral(name, existing);
494
+ const b = readEnvLiteral(name, next);
495
+ if (a.kind === "absent") return "write"; // the owner reads the existing literal as "not set": nothing to compare against
496
+ if (a.kind !== "value" || b.kind !== "value") return existing === next ? "unchanged" : "conflict_no_comparator";
497
+ if (JSON.stringify(a.value) === JSON.stringify(b.value)) return "unchanged";
498
+ const cmp = catalog[name]?.tighten;
499
+ if (cmp === undefined) return "conflict_no_comparator";
500
+ return verdictOutcome(SS.tightenVerdict(cmp, a.value, b.value));
501
+ }
502
+ function verdictOutcome(v) {
503
+ return v === "equal" ? "unchanged" : v === "stricter" ? "write" : v === "looser" ? "looser_than_existing" : "conflict_no_comparator";
504
+ }
505
+
506
+ // L12n (settings half) + L12 for one settings unit: both sides read through settings-schema readSettingsUnit (14.6.0: the kill
507
+ // switches' "disable" reads as ON, "manual" as "default"; a value outside the unit's reading is unreadable), compared by the unit's
508
+ // own comparator unitTighten (a members unit per declared member: sandbox filesystem.denyRead / denyWrite are setUnion members)
509
+ // through tightenVerdict. An unreadable side cannot be ranked (= conflict) unless the two raw values are equal.
510
+ function unitAddress(u) {
511
+ return SS.SETTINGS_UNITS[u.unit].reads === "members" ? u.member : undefined;
512
+ }
513
+ function compareSetting(u, existing, next) {
514
+ const member = unitAddress(u);
515
+ const read = (v) => (MUTATE === "L12n" ? { ok: true, value: v } : SS.readSettingsUnit(u.unit, v, member)); // mutated: compare raw values
516
+ const a = read(existing);
517
+ const b = read(next);
518
+ if (!a.ok || !b.ok) return JSON.stringify(existing) === JSON.stringify(next) ? "unchanged" : "conflict_no_comparator";
519
+ return verdictOutcome(SS.tightenVerdict(SS.unitTighten(u.unit, member), a.value, b.value));
520
+ }
521
+
522
+ function expand(doc, parents, channel, depth = 0, seen = new Set()) {
523
+ const name = doc.meta.name;
524
+ if (on("L4") && seen.has(name)) throw Object.assign(new Error(`extends cycle at ${name}`), { code: "extends" });
525
+ if (!on("L4") && depth > 16) return { $schema: doc.$schema, meta: { name: doc.meta.name, version: doc.meta.version } }; // mutated: no cycle check, stop the recursion only
526
+ if (on("L4") && depth > 0) {
527
+ // every parent passes the whole of L1 (schema AND hooks judge) before the child's nulls can delete anything from it
528
+ const problem = docProblem(doc);
529
+ if (problem !== undefined) throw Object.assign(new Error(`parent ${name}: ${problem.detail}`), { code: problem.code });
530
+ }
531
+ seen.add(name);
532
+ const parentName = doc.meta.extends;
533
+ const flatMeta = { ...doc.meta };
534
+ delete flatMeta.extends;
535
+ const own = { $schema: doc.$schema, meta: flatMeta };
536
+ for (const s of ["server", "settings", "entitlement"]) if (doc[s] !== undefined && doc[s] !== null) own[s] = doc[s];
537
+ if (parentName === undefined) return own;
538
+ if (on("L4") && depth >= 4) throw Object.assign(new Error(`extends deeper than 4 at ${name}`), { code: "extends" });
539
+ const parent = parents[parentName] ?? (BUILTIN_NAMES.includes(parentName) ? builtins[parentName] : undefined);
540
+ if (parent === undefined) throw Object.assign(new Error(`extends: parent ${parentName} not found in the ${channel} namespace or the builtins`), { code: "extends" });
541
+ const base = expand(parent, parents, channel, depth + 1, seen);
542
+ const merged = { $schema: own.$schema, meta: flatMeta };
543
+ for (const s of ["server", "settings", "entitlement"]) {
544
+ if (doc[s] === null && MUTATE !== "M24:segment-null-retains") continue; // a segment-level null deletes the inherited segment
545
+ const m = mergePatch(base[s], own[s]);
546
+ if (m !== undefined) merged[s] = m;
547
+ }
548
+ return merged;
549
+ }
550
+
551
+ function mergePatch(target, patch) {
552
+ if (patch === undefined) return target;
553
+ if (patch === null || typeof patch !== "object" || Array.isArray(patch)) return patch;
554
+ const out = target !== null && typeof target === "object" && !Array.isArray(target) ? { ...target } : {};
555
+ for (const [k, v] of Object.entries(patch)) {
556
+ if (v === null) delete out[k];
557
+ else out[k] = mergePatch(out[k], v);
558
+ }
559
+ return out;
560
+ }
561
+
562
+ // ── settings units ↔ SAFETY_MERGE_SPEC ─────────────────────────────────────────────────────────────────────────────
563
+ // The unit → category map is settings-schema's own settings unit table (`SETTINGS_UNITS`, 14.6.0); cli's UNIT_CATEGORY is
564
+ // derived from the same table (keyContracts.ts), so there is no copy here and no tolerated drift.
565
+ const UNIT_TO_CATEGORY = Object.fromEntries(Object.entries(SS.SETTINGS_UNITS).map(([unit, row]) => [unit, row.category]));
566
+
567
+ function settingsUnits(settings) {
568
+ const units = [];
569
+ const p = settings.permissions ?? {};
570
+ for (const m of ["allow", "deny", "ask"]) if (p[m] !== undefined) units.push({ path: `permissions.${m}`, unit: "permissions", category: UNIT_TO_CATEGORY.permissions, member: m, value: p[m] });
571
+ if (p.defaultMode !== undefined) units.push({ path: "permissions.defaultMode", unit: "permissionMode", category: UNIT_TO_CATEGORY.permissionMode, value: p.defaultMode });
572
+ if (p.additionalDirectories !== undefined) units.push({ path: "permissions.additionalDirectories", unit: "additionalDirectories", category: UNIT_TO_CATEGORY.additionalDirectories, value: p.additionalDirectories });
573
+ for (const m of ["disableBypassPermissionsMode", "disableAutoMode"]) if (p[m] !== undefined) units.push({ path: `permissions.${m}`, unit: m, category: UNIT_TO_CATEGORY[m], member: m, value: p[m] });
574
+ const walk = (obj, prefix) => {
575
+ for (const [k, v] of Object.entries(obj ?? {})) {
576
+ if (v !== null && typeof v === "object" && !Array.isArray(v)) walk(v, `${prefix}${k}.`);
577
+ else units.push({ path: `sandbox.${prefix}${k}`, unit: "sandbox", category: UNIT_TO_CATEGORY.sandbox, member: `${prefix}${k}`, value: v });
578
+ }
579
+ };
580
+ walk(settings.sandbox, "");
581
+ if (settings.hooks !== undefined) units.push({ path: "hooks", unit: "hooks", category: UNIT_TO_CATEGORY.hooks, value: settings.hooks });
582
+ for (const [k, v] of Object.entries(settings.env ?? {})) units.push({ path: `env.${k}`, unit: "env", category: UNIT_TO_CATEGORY.env, value: v });
583
+ if (settings.model !== undefined) units.push({ path: "model", unit: "model", category: UNIT_TO_CATEGORY.model, value: settings.model });
584
+ if (settings.outputStyle !== undefined) units.push({ path: "outputStyle", unit: "outputStyle", category: UNIT_TO_CATEGORY.outputStyle, value: settings.outputStyle });
585
+ return units;
586
+ }
587
+
588
+ function getUnit(settings, unitPath) {
589
+ if (unitPath.startsWith("env.")) return settings.env?.[unitPath.slice(4)];
590
+ return getPath(settings, unitPath);
591
+ }
592
+ function getPath(obj, dotted) {
593
+ let cur = obj;
594
+ for (const part of dotted.split(".")) {
595
+ if (cur === null || typeof cur !== "object") return undefined;
596
+ cur = cur[part];
597
+ }
598
+ return cur;
599
+ }
600
+
601
+
602
+ // ── text parses of owners (never evaluated) ────────────────────────────────────────────────────────────────────────
603
+ function parseCatalog(text, webAdminEnv) {
604
+ const rows = {};
605
+ // a row whose options object opens at the end of its line continues until the line that closes it: join it into one line
606
+ const src = text.split("\n");
607
+ const lines = [];
608
+ for (let i = 0; i < src.length; i++) {
609
+ let line = src[i];
610
+ const at = i;
611
+ if (/^\s*r\(.*\{\s*$/.test(line)) while (i + 1 < src.length && !/^\s*\}\)\s*,/.test(src[i])) line += " " + src[++i].trim();
612
+ lines[at] = line;
613
+ }
614
+ lines.forEach((line, i) => {
615
+ let m = line.match(/^\s*r\("([A-Z0-9_]+)",\s*"([A-Za-z]+)",\s*"([a-z]+)",/);
616
+ if (!m) {
617
+ const w = line.match(/^\s*r\(WEB_ADMIN_ENV\.([A-Za-z]+),\s*"([A-Za-z]+)",\s*"([a-z]+)",/);
618
+ if (!w || typeof webAdminEnv[w[1]] !== "string") return;
619
+ m = [w[0], webAdminEnv[w[1]], w[2], w[3]];
620
+ }
621
+ const opts = line.slice(afterSemantics(line, m[0].length)); // the options object only (the semantics string may itself carry braces)
622
+ const tightenRaw = rawOpt(opts, "tighten"); // the row's comparator (server 7.154.0: settings-schema TightenRule minus none / policyDenyWins)
623
+ const literalRaw = rawOpt(opts, "literal"); // the row's literal-reading facts (blank / spelling / words / unparsable / emptyWord / offAtOrBelow)
624
+ rows[m[1]] = {
625
+ name: m[1],
626
+ line: i + 1,
627
+ domain: m[2],
628
+ type: m[3],
629
+ staticDefault: strOpt(opts, "staticDefault"),
630
+ derivedDefaultNote: strOpt(opts, "derivedDefaultNote"),
631
+ enumValues: rawOpt(opts, "enumValues"),
632
+ echoWords: rawOpt(opts, "echoWords"),
633
+ envTiming: strOpt(opts, "envTiming"),
634
+ scope: strOpt(opts, "scope"),
635
+ center: rawOpt(opts, "center"),
636
+ tighten: tightenRaw === undefined ? undefined : objLiteral(tightenRaw),
637
+ literal: literalRaw === undefined ? undefined : objLiteral(literalRaw),
638
+ };
639
+ });
640
+ return rows;
641
+ }
642
+ // The index just past the row's semantics string ("…" with escapes, or a `…` template) that starts after `from`.
643
+ function afterSemantics(line, from) {
644
+ let i = from;
645
+ while (i < line.length && /\s/.test(line[i])) i++;
646
+ const q = line[i];
647
+ if (q !== '"' && q !== "`") return i;
648
+ for (i++; i < line.length; i++) {
649
+ if (line[i] === "\\") i++;
650
+ else if (line[i] === q) return i + 1;
651
+ }
652
+ return line.length;
653
+ }
654
+ // A TS object literal of the catalog (bare keys, string / number / array values, or an imported string constant) as JSON.
655
+ function objLiteral(raw) {
656
+ const resolved = raw.replace(/:\s*([A-Z][A-Z0-9_]*)(?=\s*[,}])/g, (all, ident) => {
657
+ const v = serverConst(ident);
658
+ if (v === undefined) throw new Error(`catalog literal: cannot resolve ${ident}`);
659
+ return `: ${JSON.stringify(v)}`;
660
+ });
661
+ return JSON.parse(resolved.replace(/([{,]\s*)(\w+):/g, '$1"$2":'));
662
+ }
663
+ // An imported string constant of the server catalog module: `import { X } from "./m.js"` + `export const X[: T] = "…"` in m.ts.
664
+ function serverConst(ident) {
665
+ const catalogText = readText(path.join(args.server, "src/config-catalog.ts"));
666
+ const imp = catalogText.match(new RegExp(`^import \\{[^}]*\\b${ident}\\b[^}]*\\} from "(\\./[^"]+)\\.js"`, "m"));
667
+ if (!imp) return undefined;
668
+ const p = path.join(args.server, "src", `${imp[1]}.ts`);
669
+ if (!existsSync(p)) return undefined;
670
+ const m = readText(p).match(new RegExp(`export const ${ident}(?::[^=]*)?\\s*=\\s*"([^"]*)"`));
671
+ return m ? m[1] : undefined;
672
+ }
673
+ function strOpt(line, key) {
674
+ const m = line.match(new RegExp(`\\b${key}:\\s*("(?:[^"\\\\]|\\\\.)*"|\`[^\`]*\`)`));
675
+ return m ? m[1].slice(1, -1) : undefined;
676
+ }
677
+ function rawOpt(line, key) {
678
+ const i = line.search(new RegExp(`\\b${key}:\\s*`));
679
+ if (i < 0) return undefined;
680
+ const rest = line.slice(i).replace(new RegExp(`^${key}:\\s*`), "");
681
+ let depth = 0;
682
+ let out = "";
683
+ for (const ch of rest) {
684
+ if ("([{".includes(ch)) depth++;
685
+ if (")]}".includes(ch)) {
686
+ if (depth === 0) break;
687
+ depth--;
688
+ }
689
+ if (ch === "," && depth === 0) break;
690
+ out += ch;
691
+ }
692
+ return out.trim();
693
+ }
694
+ // The words a profile may write for an enum row: the row's echo words when it declares them (a word in enumValues but not in
695
+ // echoWords is "absence spelled differently"), otherwise its enumValues.
696
+ function enumDomain(row) {
697
+ return enumWords(row.echoWords ?? row.enumValues);
698
+ }
699
+ function enumWords(raw) {
700
+ if (raw === undefined) return undefined;
701
+ if (raw.startsWith("[") && !raw.startsWith("[...")) return JSON.parse(raw);
702
+ const name = raw.replace(/^\[\.\.\./, "").replace(/\]$/, "");
703
+ return ENUM_CONSTS[name];
704
+ }
705
+ function centerSeat(raw) {
706
+ if (raw === undefined) return undefined;
707
+ const f = raw.match(/^c(Gov|Limits|Models)\("([^"]+)"/);
708
+ if (f) return { domain: { Gov: "governance", Limits: "limits", Models: "models" }[f[1]], path: f[2] };
709
+ const d = raw.match(/domain:\s*"([^"]+)"/);
710
+ const p = raw.match(/path:\s*"([^"]+)"/);
711
+ return { domain: d?.[1], path: p?.[1] };
712
+ }
713
+ function constArray(text, name) {
714
+ const m = text.match(new RegExp(`export const ${name}(?::[^=]*)?\\s*=\\s*(?:Object\\.freeze\\(|deepFreeze\\()?\\[([^\\]]*)\\]`));
715
+ if (!m) throw new Error(`cannot read ${name}`);
716
+ return [...m[1].matchAll(/"([^"]+)"/g)].map((x) => x[1]);
717
+ }
718
+ function setWords(text, name) {
719
+ const m = text.match(new RegExp(`const ${name} = new Set\\(\\[([^\\]]*)\\]\\)`));
720
+ if (!m) throw new Error(`cannot read ${name}`);
721
+ return [...m[1].matchAll(/"([^"]+)"/g)].map((x) => x[1]);
722
+ }
723
+ // The shell's child-env assembly (cli assembleChildEnv), every statement that names a key, in explicit classes:
724
+ // an unconditional assignment `env.X = <rhs>` (the statement starts the line) —
725
+ // DEFAULTED when the rhs is "the inherited value, else <default>" (`inheritedOrUnset('X') ?? d`, `inheritedLane ?? d`,
726
+ // `env.X || d`): the key is always set in the child env; the default is kept when it is a literal this reader can resolve
727
+ // ('…', an imported string constant, String(<numeric const of this file>)), else recorded as computed (undefined);
728
+ // FORCED otherwise: a resolvable literal is a known forced value, any other expression a forced value this reader cannot know;
729
+ // a conditional assignment `if (…) env.X = …` — CONDITIONAL SET (the shell's own decision from the user's settings or the inherited
730
+ // value; read before the snapshot is folded: loading-rules.md §6 G-14);
731
+ // `delete env.X` — SCRUBBED when the delete is unconditional: no enclosing condition, or the only one is the key's own presence
732
+ // (`if (env.X !== undefined) {`); CONDITIONAL DELETE when it is one arm of a decision (an `else` arm, or any other enclosing
733
+ // `if`). Deletes by a computed name (`delete env[k]`: the retired-name table, the TIDB_ / CONFIG_CENTER_ prefix scans, the memory
734
+ // sync pairing) are not classified here: retired names are refused by L5 first, no catalog row carries either prefix, and the
735
+ // memory sync names are conditional.
736
+ // The enclosing condition is found by indentation (the nearest line above with less indentation that opens a block): the file is
737
+ // formatter-laid; G-3 retires this reading when the shell exports its disposition table.
738
+ function parseChildEnv(text, cliRoot) {
739
+ const start = text.indexOf("export function assembleChildEnv");
740
+ const end = text.indexOf("\nexport function", start + 10);
741
+ const body = text.slice(start, end > 0 ? end : start + 40000);
742
+ const lines = body.split("\n");
743
+ const forcedLiteral = {};
744
+ const forcedDynamic = new Set();
745
+ const defaulted = {}; // name → the shell's default literal, or undefined when computed
746
+ const conditionalSet = new Set();
747
+ const scrubbed = new Set();
748
+ const conditionalDelete = new Set();
749
+ const resolveIdent = (ident) => {
750
+ const imp = text.match(new RegExp(`^import \\{[^}]*\\b${ident}\\b[^}]*\\} from '(\\./[^']+)\\.js'`, "m"));
751
+ if (!imp) return undefined;
752
+ const p = path.join(cliRoot, "src/sema", `${imp[1]}.ts`);
753
+ if (!existsSync(p)) return undefined;
754
+ const m = readText(p).match(new RegExp(`export const ${ident}(?::[^=]*)?\\s*=\\s*'([^']*)'`));
755
+ return m ? m[1] : undefined;
756
+ };
757
+ const numericConst = (ident) => {
758
+ const m = text.match(new RegExp(`^const ${ident}\\s*=\\s*([0-9_]+)\\s*$`, "m"));
759
+ return m ? String(Number(m[1].replace(/_/g, ""))) : undefined;
760
+ };
761
+ const literalOf = (expr) => {
762
+ const e = expr.trim();
763
+ if (/^'[^']*'$/.test(e)) return e.slice(1, -1);
764
+ const s = e.match(/^String\(([A-Z][A-Z0-9_]*)\)$/);
765
+ if (s) return numericConst(s[1]);
766
+ if (/^[A-Z][A-Z0-9_]*$/.test(e)) return resolveIdent(e);
767
+ return undefined;
768
+ };
769
+ const indentOf = (l) => l.match(/^\s*/)[0].length;
770
+ lines.forEach((line, i) => {
771
+ const set = line.match(/^\s*env\.([A-Z][A-Z0-9_]*) = (.+)$/);
772
+ if (set) {
773
+ const [, name, rhsRaw] = set;
774
+ const rhs = rhsRaw.trim();
775
+ const dflt = rhs.match(/^(?:inheritedOrUnset\('[A-Z0-9_]+'\)|inherited[A-Z]\w*|env\.[A-Z][A-Z0-9_]*)\s*(?:\?\?|\|\|)\s*(.+)$/);
776
+ if (dflt) defaulted[name] = literalOf(dflt[1]);
777
+ else if (literalOf(rhs) !== undefined) forcedLiteral[name] = literalOf(rhs);
778
+ else forcedDynamic.add(name);
779
+ return;
780
+ }
781
+ const condSet = line.match(/^\s*if \(.*\) env\.([A-Z][A-Z0-9_]*) = /);
782
+ if (condSet) conditionalSet.add(condSet[1]);
783
+ const del = line.match(/\bdelete env\.([A-Z][A-Z0-9_]*)\b/);
784
+ if (!del) return;
785
+ const name = del[1];
786
+ if (/^\s*else\b/.test(line)) return conditionalDelete.add(name);
787
+ let guard;
788
+ for (let j = i - 1; j >= 0; j--) {
789
+ const l = lines[j];
790
+ if (l.trim() === "" || /^\s*\/\//.test(l)) continue;
791
+ if (indentOf(l) < indentOf(line) && /\{\s*$/.test(l)) {
792
+ guard = l.trim();
793
+ break;
794
+ }
795
+ }
796
+ const unconditional = guard === undefined || guard === "{" || guard.startsWith("export function assembleChildEnv") || guard === `if (env.${name} !== undefined) {`;
797
+ (unconditional ? scrubbed : conditionalDelete).add(name);
798
+ });
799
+ return { forcedLiteral, forcedDynamic, defaulted, conditionalSet, scrubbed, conditionalDelete };
800
+ }
801
+ // What the shell hands the local engine before its fold (L13's "already set" at the user landing): the user's own settings.env, and
802
+ // every DEFAULTED key — the inherited value, else the shell's own default (an empty inherited value counts as not inherited:
803
+ // `inheritedOrUnset`). A computed default is set with a value this reader does not know (undefined).
804
+ function shellChildEnv(settingsEnv) {
805
+ const osEnv = { ...(settingsEnv ?? {}) };
806
+ const osSource = Object.fromEntries(Object.keys(osEnv).map((k) => [k, "settings.env"]));
807
+ if (MUTATE !== "L13:shell-defaults-absent") {
808
+ for (const [name, dflt] of Object.entries(childEnv.defaulted)) {
809
+ if (osEnv[name] !== undefined && osEnv[name] !== "") continue;
810
+ osEnv[name] = dflt;
811
+ osSource[name] = "shell-default";
812
+ }
813
+ }
814
+ return { osEnv, osSource };
815
+ }
816
+
817
+ // ── B4 / posture: the expanded parent against the expanded child, leaf by leaf (a deleted container is a deleted leaf) ──────
818
+ // A leaf the parent pins: the child keeps it equal, or at least as strict by the leaf's own comparator (env = the catalog tighten
819
+ // column through compareEnv, the L12 path; settings = unitTighten, permission buckets by union; entitlement = RUNTIME_CAP_STRICT);
820
+ // no comparator ⇒ unequal is a conflict; deleting the leaf passes only for an entitlement cap whose absent-equivalent (the non-strict
821
+ // value) is not looser. A leaf the parent does NOT pin: the child adds it — nothing to compare, no refusal. That is the comparator's
822
+ // own contract: settings-schema tightenVerdict takes two present sides only ("absence is not a value … an absent landing spot takes
823
+ // the write is the loading law's business, not the comparator's", safety-merge-spec.ts:342-345 @ 28.0.0).
824
+ // verdicts: unchanged | stricter | added | deleted | looser_than_existing | conflict_no_comparator; problems = the last three.
825
+ function postureCompare(base, kid) {
826
+ const leaves = [];
827
+ const env = (k, pv, cv) => {
828
+ if (pv === undefined) {
829
+ // B4:absent-parent-compared (mutation): an absent parent leaf read as the catalog's static default and compared
830
+ if (MUTATE === "B4:absent-parent-compared" && catalog[k]?.staticDefault !== undefined && cv !== catalog[k].staticDefault) return compareEnv(k, catalog[k].staticDefault, cv);
831
+ return "added";
832
+ }
833
+ return cv === undefined ? "deleted" : cv === pv ? "unchanged" : compareEnv(k, pv, cv);
834
+ };
835
+ const benv = base?.server?.env ?? {};
836
+ const kenv = kid?.server?.env ?? {};
837
+ for (const k of new Set([...Object.keys(benv), ...Object.keys(kenv)])) leaves.push({ leaf: `env.${k}`, from: benv[k] ?? "(absent)", to: kenv[k] ?? "(deleted)", verdict: env(k, benv[k], kenv[k]) });
838
+ const bunits = settingsUnits(base?.settings ?? {});
839
+ for (const u of bunits) {
840
+ const cv = getUnit(kid?.settings ?? {}, u.path);
841
+ const r = cv === undefined ? "deleted" : u.unit === "permissions" ? (SS.tightenVerdict({ rule: "setUnion" }, u.value, cv) === "looser" ? "looser_than_existing" : JSON.stringify(cv) === JSON.stringify(u.value) ? "unchanged" : "write") : compareSetting(u, u.value, cv);
842
+ leaves.push({ leaf: `settings.${u.path}`, from: JSON.stringify(u.value), to: JSON.stringify(cv ?? "(deleted)"), verdict: r });
843
+ }
844
+ for (const u of settingsUnits(kid?.settings ?? {})) if (!bunits.some((b) => b.path === u.path)) leaves.push({ leaf: `settings.${u.path}`, from: "(absent)", to: JSON.stringify(u.value), verdict: "added" });
845
+ const bcaps = base?.entitlement?.runtimeCaps ?? {};
846
+ const kcaps = kid?.entitlement?.runtimeCaps ?? {};
847
+ for (const [k, pv] of Object.entries(bcaps)) {
848
+ const pole = SS.RUNTIME_CAP_STRICT[k];
849
+ const cvRaw = kcaps[k];
850
+ const cv = cvRaw === undefined ? !pole : cvRaw; // a deleted cap reads as its absent-equivalent, the non-strict value
851
+ // a deleted cap is judged by its absent-equivalent: equal or stricter passes (shown as unchanged / stricter with "(deleted ≡ …)")
852
+ const r = verdictOutcome(SS.tightenVerdict({ rule: "boolStricter", strict: pole }, pv, cv));
853
+ leaves.push({ leaf: `entitlement.${k}`, from: String(pv), to: cvRaw === undefined ? `(deleted ≡ ${cv})` : String(cv), verdict: r });
854
+ }
855
+ for (const [k, cv] of Object.entries(kcaps)) if (!Object.hasOwn(bcaps, k)) leaves.push({ leaf: `entitlement.${k}`, from: "(absent)", to: String(cv), verdict: "added" });
856
+ for (const l of leaves) if (l.verdict === "write") l.verdict = "stricter";
857
+ const problems = leaves.filter((l) => l.verdict === "deleted" || l.verdict === "looser_than_existing" || l.verdict === "conflict_no_comparator");
858
+ return { leaves, problems };
859
+ }
860
+ // A posture vector's sides: a builtin name, or an inline document (an inline child's extends resolves against the inline parent).
861
+ function postureOf(parentRef, childRef) {
862
+ const parentDoc = typeof parentRef === "string" ? builtins[parentRef] : parentRef;
863
+ const childDoc = typeof childRef === "string" ? builtins[childRef] : childRef;
864
+ const parents = { [parentDoc.meta.name]: parentDoc };
865
+ return postureCompare(expand(parentDoc, parents, "builtin"), expand(childDoc, parents, "builtin"));
866
+ }
867
+
868
+ // ── mutations of the builtin files (proof that each B check bites) ─────────────────────────────────────────────────
869
+ function applyProfileMutations(b) {
870
+ if (MUTATE === "B1:rename") b["solo-auto"].meta.name = "local-solo";
871
+ if (MUTATE === "B2:cross-axis") b["tenant-auto"].meta.extends = "solo-managed";
872
+ if (MUTATE === "B3:shared-lane") b["tenant-auto"].server.env.REMOTE_EXEC = "host";
873
+ if (MUTATE === "B3:solo-lane") b["solo-auto"].server.env.REMOTE_EXEC = "ssh";
874
+ if (MUTATE === "B4:loosen") b["tenant-managed"].settings.sandbox = { enabled: false }; // the parent's strict pole turned off
875
+ if (MUTATE === "B4:no-comparator-env") b["tenant-auto"].server.env.MEMORY_CAPTURE_POLICY = "governed"; // the parent pins the comparator-less key again (retired shape)
876
+ if (MUTATE === "B4:no-comparator") b["solo-managed"].server.env.CONFIG_PROVIDER = "remote";
877
+ if (MUTATE === "B4:container-delete") {
878
+ b["tenant-managed"].settings.permissions = null;
879
+ b["tenant-managed"].entitlement.runtimeCaps = null;
880
+ }
881
+ if (MUTATE === "B6:unknown-key") b["solo-auto"].server.env.LOCAL_SOLO_MODE = "true";
882
+ // F: one value of each builtin changed in a way no other check can see (the managed tenant's memory cell has its own row)
883
+ if (MUTATE === "F:solo-auto-value") b["solo-auto"].settings.permissions.defaultMode = "acceptEdits";
884
+ if (MUTATE === "F:solo-managed-value") b["solo-managed"].server.env.DURABLE_APPROVAL = "false";
885
+ if (MUTATE === "F:tenant-auto-value") b["tenant-auto"].server.env.FORK_ENABLED = "false";
886
+ if (MUTATE === "F:tenant-managed-memory") b["tenant-managed"].server.env.MEMORY_CAPTURE_POLICY = "governed";
887
+ if (MUTATE === "F:tenant-managed-cap") b["tenant-managed"].entitlement.runtimeCaps.allowFork = true;
888
+ }
889
+
890
+ // ── 1. vectors ─────────────────────────────────────────────────────────────────────────────────────────────────────
891
+ const deferred = [];
892
+ const LOADERS = new Set(["reference", "server", "cli", "center"]);
893
+ const dumpAll = args["dump-rows"] === "all";
894
+ const rowKey = (r) => `${r.segment}|${r.key}|${r.outcome}|${r.code ?? ""}`;
895
+ const emitted = []; // every report row the executed vectors produce (checked against the frozen closed sets, group F)
896
+ const emittedEnvelopes = [];
897
+ for (const v of vectors) {
898
+ const by = Array.isArray(v.executedBy) ? v.executedBy : [];
899
+ if (by.length === 0 || by.some((l) => !LOADERS.has(l))) {
900
+ record("vector", v.id, false, `executedBy must be a non-empty subset of ${[...LOADERS].join("|")} (got ${JSON.stringify(v.executedBy)})`);
901
+ continue;
902
+ }
903
+ if (v.posture !== undefined) {
904
+ // posture vector (B4): the expanded parent against the expanded child, through the same function as the builtin check
905
+ if (!by.includes("reference")) {
906
+ deferred.push(`${v.id} → ${by.join("+")}`);
907
+ continue;
908
+ }
909
+ const { leaves, problems } = postureOf(v.posture.parent, v.posture.child);
910
+ const got = leaves.filter((l) => l.verdict !== "unchanged").map((l) => `${l.leaf}|${l.verdict}`).sort();
911
+ if (typeof args["dump-rows"] === "string" && (dumpAll || args["dump-rows"] === v.id)) console.log(`LEAVES ${v.id} ${JSON.stringify(got)}`);
912
+ const ok =
913
+ v.expect === "accept"
914
+ ? problems.length === 0 && JSON.stringify(got) === JSON.stringify([...(v.expectLeaves ?? [])].sort())
915
+ : problems.some((l) => l.leaf === v.key && l.verdict === v.code);
916
+ record("vector", v.id, ok, ok ? `${v.expect}` : `expected ${v.expect}${v.code ? ` (${v.code} at ${v.key})` : ""}, got ${JSON.stringify(got)}`);
917
+ continue;
918
+ }
919
+ const doc = v.profile ?? builtins[v.builtin];
920
+ if (!by.includes("reference")) {
921
+ // not this loader's to run; with --dump-rows all the report rows are still printed (the server-run vectors' expectRows come from here)
922
+ if (dumpAll) console.log(`ROWS ${v.id} ${JSON.stringify(load(doc, v).map(rowKey).sort())} (deferred)`);
923
+ deferred.push(`${v.id} → ${by.join("+")}`);
924
+ continue;
925
+ }
926
+ const rows = load(doc, v);
927
+ for (const r of rows) emitted.push({ id: v.id, outcome: r.outcome, code: r.code });
928
+ emittedEnvelopes.push({ id: v.id, ...rows.envelope });
929
+ const rejected = rows.filter((r) => r.outcome === "rejected");
930
+ const actualRows = rows.map(rowKey).sort();
931
+ if (typeof args["dump-rows"] === "string" && (dumpAll || args["dump-rows"] === v.id)) console.log(`ROWS ${v.id} ${JSON.stringify(actualRows)}`);
932
+ let ok;
933
+ const why = [];
934
+ if (v.mutateLoader !== undefined) {
935
+ // loader-mutation vector: run with the named loader defect; it proves the check can tell when the defect's signature rows appear
936
+ ok = Array.isArray(v.expectMutantRows) && v.expectMutantRows.length > 0 && v.expectMutantRows.every((r) => actualRows.includes(r));
937
+ } else {
938
+ if (v.expect === "accept") {
939
+ // a positive vector asserts its EXACT report (rows present and, by equality, every row absent), never only "no refusal"
940
+ ok = rejected.length === 0 && Array.isArray(v.expectRows) && JSON.stringify(actualRows) === JSON.stringify([...v.expectRows].sort());
941
+ if (ok && v.expectSnapshotEnv !== undefined && JSON.stringify(sortKeys(rows.snapshot?.env)) !== JSON.stringify(sortKeys(v.expectSnapshotEnv))) (ok = false), why.push("snapshot");
942
+ // a user-landing positive whose report carries a server row must say what snapshot it writes
943
+ if (ok && (v.destination ?? "user") === "user" && rows.some((r) => r.segment.startsWith("server")) && v.expectSnapshotEnv === undefined) (ok = false), why.push("vector lacks expectSnapshotEnv");
944
+ } else {
945
+ ok = rejected.some((r) => r.code === v.code && (v.detail === undefined || r.detail === v.detail) && (v.detailIncludes === undefined || String(r.detail ?? "").includes(v.detailIncludes)));
946
+ // all-or-nothing: a refused report writes nothing (no snapshot, no selector)
947
+ if (ok && rows.snapshot !== undefined) (ok = false), why.push("snapshot written on refusal");
948
+ }
949
+ // envelope: mode echoes the run; disposition follows the rows; the selector is present exactly when a snapshot is written
950
+ const env = rows.envelope;
951
+ const wantDisposition = v.expect === "accept" ? "applied" : "refused";
952
+ if (ok && env.mode !== (v.mode ?? "commit")) (ok = false), why.push(`envelope.mode ${env.mode}`);
953
+ if (ok && env.disposition !== wantDisposition) (ok = false), why.push(`envelope.disposition ${env.disposition}`);
954
+ if (ok && (env.selector !== undefined) !== (v.expect === "accept" && v.expectSnapshotEnv !== undefined)) (ok = false), why.push(`envelope.selector ${env.selector ? "present" : "absent"}`);
955
+ if (ok && env.selector !== undefined && env.selector.snapshotDigest !== digest(rows.snapshot)) (ok = false), why.push("envelope.selector digest");
956
+ }
957
+ if (ok && v.expectWritten !== undefined) {
958
+ for (const [k, want] of Object.entries(v.expectWritten)) {
959
+ const row = rows.find((r) => r.key === k && r.outcome === "written");
960
+ if (row === undefined || JSON.stringify(row.value) !== JSON.stringify(want)) ok = false;
961
+ }
962
+ }
963
+ record("vector", v.id, ok, ok ? `${v.expect}` : `expected ${v.expect}${v.code ? ` (${v.code})` : ""}${why.length ? ` [${why.join("; ")}]` : ""}, got ${JSON.stringify(rejected.length ? rejected : rows)}`);
964
+ }
965
+
966
+ // ── 2. builtin invariants B ───────────────────────────────────────────────────────────────────────────────────────
967
+ const flat = {};
968
+ for (const n of BUILTIN_NAMES) {
969
+ const doc = builtins[n];
970
+ const shapeOk = validateShape(doc);
971
+ let f;
972
+ try {
973
+ f = expand(doc, {}, "builtin");
974
+ } catch (e) {
975
+ f = undefined;
976
+ }
977
+ const flatOk = f !== undefined && validateShape(f);
978
+ flat[n] = f;
979
+ record("B1", n, doc.meta.name === n && shapeOk && flatOk, `name=${doc.meta.name} shape=${shapeOk} expanded=${flatOk}`);
980
+ }
981
+ {
982
+ // B2 is a rule, not a value list: an *-auto preset is a root; an *-managed preset extends the *-auto preset of its own tenant axis
983
+ // (the values themselves are frozen in group F)
984
+ for (const n of BUILTIN_NAMES) {
985
+ const want = n.endsWith("-auto") ? undefined : n.replace(/-managed$/, "-auto");
986
+ record("B2", n, builtins[n].meta.extends === want, `extends=${builtins[n].meta.extends ?? "-"}`);
987
+ }
988
+ }
989
+ {
990
+ const separating = new Set(SS.EXECUTION_LANES.filter((r) => r.tenantSeparation === "supported").map((r) => r.lane));
991
+ for (const n of BUILTIN_NAMES) {
992
+ const e = flat[n]?.server?.env ?? {};
993
+ const solo = n.startsWith("solo-");
994
+ // solo: the open read face of solo-auto is ruled for "single user AND host lane", so the solo corner pins host
995
+ const ok = solo
996
+ ? e.REQUIRE_PRINCIPAL === "false" && e.CONFIG_PROVIDER === "local" && e.REMOTE_EXEC === "host" && flat[n].entitlement === undefined
997
+ : e.REQUIRE_PRINCIPAL === "true" && e.CONFIG_PROVIDER === "remote" && separating.has(e.REMOTE_EXEC);
998
+ record("B3", n, ok, `REQUIRE_PRINCIPAL=${e.REQUIRE_PRINCIPAL} CONFIG_PROVIDER=${e.CONFIG_PROVIDER} REMOTE_EXEC=${e.REMOTE_EXEC ?? "-"} entitlement=${flat[n]?.entitlement ? "present" : "absent"}`);
999
+ }
1000
+ }
1001
+ // B4 — posture axis only tightens, one function for the builtin check and the posture vectors (postureOf / postureCompare).
1002
+ for (const [child, parent] of [["solo-managed", "solo-auto"], ["tenant-managed", "tenant-auto"]]) {
1003
+ const { leaves, problems } = postureCompare(flat[parent], flat[child]);
1004
+ const shown = leaves.filter((l) => l.verdict !== "unchanged" || l.to.startsWith("(deleted")).map((l) => `${l.leaf}:${l.from}->${l.to}:${l.verdict}`);
1005
+ record("B4", child, problems.length === 0, `${shown.join(" ; ")}${problems.length ? ` | red: ${problems.map((l) => l.leaf).join(",")}` : ""}`);
1006
+ }
1007
+ {
1008
+ const tiers = String(flat["tenant-managed"]?.server?.env?.READ_DENY_BUILTIN_TIERS ?? "").split(",").filter(Boolean);
1009
+ const vocab = MUTATE === "B5:vocab-grows" ? [...coreReadDenyTiers, "future-tier"] : coreReadDenyTiers;
1010
+ const ok = tiers.length === vocab.length && vocab.every((t) => tiers.includes(t));
1011
+ record("B5", "tenant-managed", ok, `profile=${tiers.join(",")} core=${vocab.join(",")}`);
1012
+ }
1013
+ // ── F. frozen promises (vectors/frozen-promises.json): values, not just presence ──────────────────────────────────────
1014
+ // Each builtin's EXPANDED document against its frozen section, key by key: extends, server.env, settings units, entitlement caps —
1015
+ // an extra key, a missing key or a different value is red. B4 cannot do this: it only says a child is not looser than its parent,
1016
+ // and a leaf the parent does not pin is "added" whatever its value.
1017
+ {
1018
+ const fb = frozen.builtins ?? {};
1019
+ record("F", "builtin-set", sameSetLoose(Object.keys(fb).filter((k) => !k.startsWith("$")), BUILTIN_NAMES), `frozen=${Object.keys(fb).join(",")}`);
1020
+ for (const n of BUILTIN_NAMES) {
1021
+ const want = fb[n];
1022
+ if (want === undefined) {
1023
+ record("F", n, false, "no frozen section for this builtin");
1024
+ continue;
1025
+ }
1026
+ const got = {
1027
+ extends: builtins[n].meta.extends ?? null,
1028
+ "server.env": flat[n]?.server?.env ?? {},
1029
+ settings: Object.fromEntries(settingsUnits(flat[n]?.settings ?? {}).map((u) => [u.path, u.value])),
1030
+ "entitlement.runtimeCaps": flat[n]?.entitlement?.runtimeCaps ?? {},
1031
+ };
1032
+ const diffs = [];
1033
+ if (got.extends !== want.extends) diffs.push(`extends ${JSON.stringify(got.extends)} ≠ frozen ${JSON.stringify(want.extends)}`);
1034
+ for (const part of ["server.env", "settings", "entitlement.runtimeCaps"]) {
1035
+ const g = got[part];
1036
+ const w = want[part] ?? {};
1037
+ for (const k of new Set([...Object.keys(g), ...Object.keys(w)])) {
1038
+ if (!Object.hasOwn(w, k)) diffs.push(`${part}.${k} = ${JSON.stringify(g[k])} not in the frozen table`);
1039
+ else if (!Object.hasOwn(g, k)) diffs.push(`${part}.${k} frozen ${JSON.stringify(w[k])} but absent`);
1040
+ else if (JSON.stringify(g[k]) !== JSON.stringify(w[k])) diffs.push(`${part}.${k} = ${JSON.stringify(g[k])} ≠ frozen ${JSON.stringify(w[k])}`);
1041
+ }
1042
+ }
1043
+ const keys = Object.keys(got["server.env"]).length + Object.keys(got.settings).length + Object.keys(got["entitlement.runtimeCaps"]).length;
1044
+ record("F", n, diffs.length === 0, diffs.length ? diffs.join(" ; ") : `${keys} values + extends equal the frozen table`);
1045
+ }
1046
+ const cd = Object.fromEntries(Object.entries(frozen.channelDestinations ?? {}).filter(([k]) => !k.startsWith("$")));
1047
+ const cdOk = sameSetLoose(Object.keys(cd), Object.keys(CHANNEL_DESTINATIONS)) && Object.keys(cd).every((c) => sameSetLoose(cd[c], CHANNEL_DESTINATIONS[c] ?? []));
1048
+ record("F", "channelDestinations", cdOk, cdOk ? "the loader's channel × destination table equals the frozen one" : `loader ${JSON.stringify(CHANNEL_DESTINATIONS)} ≠ frozen ${JSON.stringify(cd)}`);
1049
+ const rbf = frozen.readBeforeFold?.keys ?? [];
1050
+ record("F", "readBeforeFold", sameSetLoose(rbf, [...READ_BEFORE_FOLD]), `loader ${[...READ_BEFORE_FOLD].join(",")} / frozen ${rbf.join(",")}`);
1051
+ const cs = frozen.reportClosedSets ?? {};
1052
+ const outcomes = new Set(cs.outcomes ?? []);
1053
+ const codes = new Set(cs.codes ?? []);
1054
+ const judgement = new Set(cs.judgementWords ?? []);
1055
+ const strayRows = emitted.filter((r) => !outcomes.has(r.outcome) || (r.code !== undefined && !codes.has(r.code)));
1056
+ record("F", "closed-set:emitted-rows", strayRows.length === 0, strayRows.length ? `outside the closed sets: ${strayRows.slice(0, 5).map((r) => `${r.id}:${r.outcome}/${r.code}`).join(", ")}` : `${emitted.length} rows, all inside`);
1057
+ const strayEnv = emittedEnvelopes.filter((e) => !(cs.envelope?.mode ?? []).includes(e.mode) || !(cs.envelope?.disposition ?? []).includes(e.disposition));
1058
+ record("F", "closed-set:envelopes", strayEnv.length === 0, strayEnv.length ? `outside: ${strayEnv.slice(0, 5).map((e) => `${e.id}:${e.mode}/${e.disposition}`).join(", ")}` : `${emittedEnvelopes.length} envelopes, all inside`);
1059
+ // every vector's code: a report code, except a loader-mutation vector's judgement word (which must stay OUTSIDE the code set)
1060
+ const badCodes = vectors.filter((v) => v.code !== undefined && (v.mutateLoader !== undefined ? !judgement.has(v.code) || codes.has(v.code) : !codes.has(v.code)));
1061
+ record("F", "closed-set:vector-codes", badCodes.length === 0 && [...judgement].every((w) => !codes.has(w)), badCodes.length ? badCodes.map((v) => `${v.id}:${v.code}`).join(", ") : "every vector code is a report code; judgement words stay outside");
1062
+ // every code is exercised: some vector names it as its code or lists it in its expected rows
1063
+ const exercised = new Set(vectors.flatMap((v) => [v.code, ...(v.expectRows ?? []).map((r) => r.split("|")[3])]).filter(Boolean));
1064
+ const dead = [...codes].filter((c) => !exercised.has(c));
1065
+ record("F", "closed-set:coverage", dead.length === 0, dead.length ? `codes no vector exercises: ${dead.join(", ")}` : `${codes.size} codes, each exercised by a vector`);
1066
+ }
1067
+ function sameSetLoose(a, b) {
1068
+ return a.length === b.length && a.every((x) => b.includes(x));
1069
+ }
1070
+
1071
+ const knobsCommitted = readJson(path.join(args.comms, "knobs.json"));
1072
+ const knobsFresh = typeof args["knobs-fresh"] === "string" && existsSync(args["knobs-fresh"]) ? readJson(args["knobs-fresh"]) : undefined;
1073
+ const knobIds = (j) => new Set((j?.rows ?? []).map((r) => r.id));
1074
+ const committedIds = knobIds(knobsCommitted);
1075
+ const freshIds = knobIds(knobsFresh);
1076
+ const pins = [];
1077
+ for (const n of BUILTIN_NAMES) {
1078
+ const doc = builtins[n];
1079
+ for (const [k, v] of Object.entries(doc.server?.env ?? {})) pins.push({ profile: n, segment: "server.env", key: k, value: v, knob: `server:env:${k}` });
1080
+ for (const u of settingsUnits(doc.settings ?? {})) pins.push({ profile: n, segment: "settings", key: u.path, value: u.value, knob: `cli:settings:${u.unit}`, unitRow: u });
1081
+ for (const [k, v] of Object.entries(doc.entitlement?.runtimeCaps ?? {})) pins.push({ profile: n, segment: "entitlement", key: k, value: v, knob: `center:entitlement:${k}` });
1082
+ }
1083
+ for (const p of pins) {
1084
+ p.inCommitted = committedIds.has(p.knob);
1085
+ p.inFresh = knobsFresh === undefined ? undefined : freshIds.has(p.knob);
1086
+ if (p.segment === "server.env") {
1087
+ const row = catalog[p.key];
1088
+ p.catalog = row;
1089
+ const problem = row ? literalProblem(row, p.value) : undefined;
1090
+ record("B6", `${p.profile}:${p.key}`, row !== undefined && row.envTiming !== "inert" && problem === undefined, row ? `catalog :${row.line} ${row.type}${problem ? ` ${problem.code}` : ""}` : "not a catalog row");
1091
+ }
1092
+ }
1093
+
1094
+ // ── 3. projections (the schema's copies against their owners) ─────────────────────────────────────────────────────
1095
+ const S = schema.$defs;
1096
+ const sameSet = (a, b) => a.length === b.length && a.every((x) => b.includes(x));
1097
+ record("P", "PORTABLE_DOMAINS", sameSet(S.server.properties["config.d"].propertyNames.enum, portableDomains), portableDomains.join(","));
1098
+ {
1099
+ // a profile only ever writes settings FILES, and a file never takes bypassPermissions (SAFETY_MERGE_SPEC.permissionMode seam
1100
+ // "bypass = launch-flag only"; cli resolver refuses it from file sources) ⇒ the schema's word set is the core set minus that one
1101
+ const launchFlagOnly = ["bypassPermissions"];
1102
+ const schemaModes = S.settings.properties.permissions.properties.defaultMode.enum.filter((x) => x !== null);
1103
+ record("P", "PERMISSION_MODES-minus-launch-flag", sameSet(schemaModes, corePermissionModes.filter((m) => !launchFlagOnly.includes(m))), corePermissionModes.join(","));
1104
+ }
1105
+ {
1106
+ const schemaCaps = Object.keys(S.entitlement.properties.runtimeCaps.properties);
1107
+ const ownerCaps = Object.keys(SS.EntitlementRuntimeCaps.shape).filter((k) => k !== "allowUltracode" && k !== "allowAutoMode");
1108
+ record("P", "EntitlementRuntimeCaps-minus-2", sameSet(schemaCaps, ownerCaps), ownerCaps.join(","));
1109
+ const poles = schemaCaps.every((k) => S.entitlement.properties.runtimeCaps.properties[k]["x-sema-strict"] === SS.RUNTIME_CAP_STRICT[k]);
1110
+ record("P", "RUNTIME_CAP_STRICT-poles", poles, "x-sema-strict vs RUNTIME_CAP_STRICT");
1111
+ }
1112
+ {
1113
+ const sb = S.settings.properties.sandbox.properties;
1114
+ const leaves = [];
1115
+ for (const [k, v] of Object.entries(sb)) {
1116
+ if (v.properties !== undefined) for (const kk of Object.keys(v.properties)) leaves.push(`${k}.${kk}`);
1117
+ else leaves.push(k);
1118
+ }
1119
+ const owner = Object.keys(SS.SAFETY_MERGE_SPEC.sandboxNetwork.members);
1120
+ record("P", "sandboxNetwork.members", sameSet(leaves, owner), owner.join(","));
1121
+ }
1122
+ {
1123
+ // unit set: the schema's settings units (as this loader walks them) against settings-schema SETTINGS_UNITS; cli must READ that table,
1124
+ // not keep its own (keyContracts.ts derives UNIT_CATEGORY from Object.entries(SETTINGS_UNITS))
1125
+ const walked = ["permissions", "permissionMode", "additionalDirectories", "sandbox", "disableBypassPermissionsMode", "disableAutoMode", "hooks", "env", "model", "outputStyle"];
1126
+ record("P", "SETTINGS_UNITS", sameSet(walked, Object.keys(SS.SETTINGS_UNITS)), Object.keys(SS.SETTINGS_UNITS).join(","));
1127
+ const cliDerives = /UNIT_CATEGORY\s*=\s*Object\.freeze\(\s*Object\.fromEntries\(\s*Object\.entries\(SETTINGS_UNITS\)/.test(cliKeyContractsText);
1128
+ record("P", "cli-UNIT_CATEGORY-derived", cliDerives, `cli keyContracts.ts derives UNIT_CATEGORY from SETTINGS_UNITS=${cliDerives}`);
1129
+ }
1130
+
1131
+ // ── report ─────────────────────────────────────────────────────────────────────────────────────────────────────────
1132
+ const red = results.filter((r) => !r.ok);
1133
+ if (!args.quiet) {
1134
+ for (const r of results) console.log(`${r.ok ? "ok " : "RED"} ${r.group.padEnd(6)} ${r.id.padEnd(34)} ${r.detail ?? ""}`);
1135
+ for (const d of deferred) console.log(`DEF vector ${d}`);
1136
+ const c = childEnv;
1137
+ console.log(
1138
+ `INFO cli child env classes (L9 / L13 at the user landing): forced literal ${JSON.stringify(c.forcedLiteral)}; forced computed ${JSON.stringify([...c.forcedDynamic])}; ` +
1139
+ `shell default ${JSON.stringify(Object.fromEntries(Object.entries(c.defaulted).map(([k, v]) => [k, v ?? "(computed)"])))}; conditional set ${JSON.stringify([...c.conditionalSet])}; ` +
1140
+ `scrubbed (unconditional delete) ${JSON.stringify([...c.scrubbed])}; conditional delete ${JSON.stringify([...c.conditionalDelete])}`,
1141
+ );
1142
+ }
1143
+ console.log(`validate: ${results.length} checks, ${red.length} red, ${deferred.length} deferred (not executed here)${MUTATE ? ` (mutation ${MUTATE})` : ""}; catalog rows=${Object.keys(catalog).length}; knobs committed rows=${committedIds.size}${knobsFresh ? ` fresh rows=${freshIds.size}` : ""}`);
1144
+
1145
+ if (typeof args.annotate === "string") writeFileSync(args.annotate, annotate(pins));
1146
+ process.exit(red.length === 0 ? 0 : 1);
1147
+
1148
+ function annotate(pinsList) {
1149
+ const o = [];
1150
+ o.push("# builtin profile annotations (generated, do not hand-edit)");
1151
+ o.push("");
1152
+ o.push(`> Generated by \`tools/validate.mjs --annotate\` from the four \`profiles/*.json\` (truth) against: server catalog @ \`src/config-catalog.ts\` (${Object.keys(catalog).length} rows), comms \`knobs.json\` (slice-1 product, ${committedIds.size} rows, generated ${knobsCommitted.generatedAt}, source trees ${JSON.stringify(knobsCommitted.sources)})${knobsFresh ? `, a fresh dry run of the slice-1 generator (${freshIds.size} rows, source trees ${JSON.stringify(knobsFresh.sources)})` : ""}. A profile pins only intent values; every key it omits follows the default shown by the catalog row (the doctor projection, not the profile, makes those explicit). "today's default" quotes the catalog's own sentence; where that sentence is known to be incomplete it is listed in loading-rules.md §6. "comparator" for env rows is the catalog's own \`tighten\` column (server 7.154.0 onward); a row without one has none (unequal ⇒ conflict).`);
1153
+ o.push("");
1154
+ for (const n of BUILTIN_NAMES) {
1155
+ o.push(`## ${n}${builtins[n].meta.extends ? ` (extends ${builtins[n].meta.extends})` : ""}`);
1156
+ o.push("");
1157
+ o.push("| segment | key | pinned value | knob id | in KNOBS (09-02) | in fresh dry run | today's source | today's default | pin = static default | comparator |");
1158
+ o.push("|---|---|---|---|---|---|---|---|---|---|");
1159
+ for (const p of pinsList.filter((x) => x.profile === n)) {
1160
+ let source = "";
1161
+ let def = "";
1162
+ let eq = "";
1163
+ let cmp = "";
1164
+ if (p.segment === "server.env") {
1165
+ const r = p.catalog;
1166
+ source = r ? `server \`config-catalog.ts:${r.line}\` (${r.type})` : "**not a catalog row**";
1167
+ def = r?.staticDefault !== undefined ? `\`${r.staticDefault}\`` : r?.derivedDefaultNote ? `derived: ${r.derivedDefaultNote.replace(/\|/g, "\\|").slice(0, 140)}` : "absent";
1168
+ eq = r?.staticDefault !== undefined ? String(r.staticDefault === p.value) : r?.derivedDefaultNote ? "n/a (derived)" : "n/a (no default)";
1169
+ const t = r?.tighten;
1170
+ cmp = t ? `catalog ${t.rule}${t.order ? ` ${t.order.join("<")}` : ""}${t.strict !== undefined ? ` strict=${t.strict}` : ""}` : "none (conflict rejects)";
1171
+ } else if (p.segment === "settings") {
1172
+ const u = p.unitRow;
1173
+ source = `settings-schema \`SAFETY_MERGE_SPEC.${u.category}\`${u.member ? `.${u.member}` : ""}`;
1174
+ def = p.key === "permissions.defaultMode" ? "cli: interactive auto when its gates hold, headless `default`" : "absent";
1175
+ eq = "n/a";
1176
+ const c = u.unit === "permissions" ? { rule: "policyDenyWins" } : SS.unitTighten(u.unit, unitAddress(u));
1177
+ cmp = c ? `${c.rule}${c.order ? ` ${c.order.join("<")}` : ""}${c.strict !== undefined ? ` strict=${c.strict}` : ""}` : "none";
1178
+ } else {
1179
+ source = `settings-schema \`EntitlementRuntimeCaps.${p.key}\``;
1180
+ def = "absent (center says nothing)";
1181
+ eq = "n/a";
1182
+ cmp = `RUNTIME_CAP_STRICT ${SS.RUNTIME_CAP_STRICT[p.key]}`;
1183
+ }
1184
+ const val = p.value === null ? "`null` (delete inherited)" : `\`${JSON.stringify(p.value)}\``;
1185
+ o.push(`| ${p.segment} | \`${p.key}\` | ${val} | \`${p.knob}\` | ${p.inCommitted ? "yes" : "**no**"} | ${p.inFresh === undefined ? "-" : p.inFresh ? "yes" : "**no**"} | ${source} | ${def} | ${eq} | ${cmp} |`);
1186
+ }
1187
+ o.push("");
1188
+ }
1189
+ return o.join("\n") + "\n";
1190
+ }