@serene-pub/conformance 0.6.0-pr-1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,1387 @@
1
+ /**
2
+ * The conformance kit (03 §9).
3
+ *
4
+ * This is the artifact SP Core upgrades *against*. The rest of this package is a
5
+ * reference implementation whose runtime half is placeholder — a real executor will have
6
+ * durable gate parking, a persistent run queue, transactions and four transports, none of
7
+ * which are here. What survives the port is **the contracts**, and a contract nobody can
8
+ * execute is a document.
9
+ *
10
+ * So: core implements `HostUnderTest`, runs `conform(host)`, and gets a pass/fail per
11
+ * requirement with the law it comes from. The SDK's own executor runs the same kit, which
12
+ * is what keeps the kit honest — a requirement the reference implementation cannot pass is
13
+ * a requirement stated wrong.
14
+ *
15
+ * Every check states **what would be broken if it failed**, because a red line saying
16
+ * "F13" tells an implementer nothing about what to go and look at.
17
+ */
18
+ import { actionsOf, DEFAULT_CHANNEL, parseChannel, slashFindings, slashNameOf } from '@serene-pub/sdk';
19
+ import { allDefinitions, assertHookSurface, effectsOf, sessionEvents, worldBlockFunctions } from '@serene-pub/sdk';
20
+ import { uncausedGenreEvents, unterminatedCycles } from '@serene-pub/sdk';
21
+ // One verdict per law (01 §13): C27 enumerates what is registered and holds
22
+ // the host's doors to each verdict's own sentence.
23
+ import { i18nText, verdicts } from '@serene-pub/sdk';
24
+ /**
25
+ * The plugin grant table (plans/29 R-3), imported rather than restated.
26
+ * `pluginHarness.ts` keeps it byte-for-byte with the two sandboxes' programs
27
+ * and the app's `hookCtx.ts`, and its docblock says what a further copy would
28
+ * be: the drift the install-time check exists to catch. C25 judges a host's
29
+ * endowment against this one.
30
+ */
31
+ import { hookCtxGrants, hookCtxKeysFor, HOOK_CTX_KINDS } from '@serene-pub/sdk/testing';
32
+ import { COMPONENT_PROTOCOL_FIXTURE, componentMountCase, componentParityCase, componentParitySections, componentProtocolCase, judgeComponentModule, } from './components.js';
33
+ import { probeSampleFor } from './packages.js';
34
+ import { swapFitFinding } from '@serene-pub/sdk';
35
+ import { probeBinding, probeCtxFor } from '@serene-pub/sdk/testing';
36
+ export * from './components.js';
37
+ export * from './packages.js';
38
+ /** @experimental */
39
+ export class ConformanceError extends Error {
40
+ }
41
+ const must = (cond, why) => {
42
+ if (!cond)
43
+ throw new ConformanceError(why);
44
+ };
45
+ /**
46
+ * A host that counts what it is asked to commit and hands out row ids of its
47
+ * own — the kit's write probe for F37 and F38. A run whose outlets reach this
48
+ * has written; a dry run must never reach it.
49
+ */
50
+ function writeProbe() {
51
+ const committed = [];
52
+ const host = {
53
+ async commit(_payload, node) {
54
+ const id = `probe:${node.key}#${committed.length + 1}`;
55
+ committed.push(id);
56
+ return { id };
57
+ },
58
+ };
59
+ return { host, committed };
60
+ }
61
+ /** The row ids an outlet's recorded write carries (`write-result@1`: `{ status, ids }`). */
62
+ const rowIdsOf = (n) => {
63
+ const out = n.output;
64
+ return out && typeof out === 'object' && out.ids && typeof out.ids === 'object'
65
+ ? Object.values(out.ids)
66
+ : [];
67
+ };
68
+ /** Bindings that record the ctx and input every hook was handed, then behave as before. */
69
+ function spyBindings(base, seen) {
70
+ const out = {};
71
+ for (const [id, hook] of Object.entries(base))
72
+ out[id] = async (input, ctx) => {
73
+ seen.push({ id, ctx, input });
74
+ return hook(input, ctx);
75
+ };
76
+ return out;
77
+ }
78
+ /**
79
+ * Does a value carry the sentinel anywhere a hook could read it without
80
+ * calling anything — a string, or one nested in objects and arrays? Functions
81
+ * are never invoked (a ctx's `commit` would write), and a cycle is walked once.
82
+ */
83
+ function carries(value, sentinel, seen = new Set()) {
84
+ if (typeof value === 'string')
85
+ return value.includes(sentinel);
86
+ if (!value || typeof value !== 'object')
87
+ return false;
88
+ if (seen.has(value))
89
+ return false;
90
+ seen.add(value);
91
+ const parts = Array.isArray(value) ? value : Object.values(value);
92
+ return parts.some((p) => carries(p, sentinel, seen));
93
+ }
94
+ /**
95
+ * Did `run` refuse the document at publish-time validation under one of these
96
+ * laws? Read off `findings` when the error carries them, else off the
97
+ * `[LAW]` lines `assertValid` writes — the two shapes a host's refusal takes.
98
+ */
99
+ function refusedUnder(e, laws) {
100
+ const findings = e?.findings;
101
+ if (Array.isArray(findings) && findings.some((f) => laws.includes(f?.law)))
102
+ return true;
103
+ const message = e instanceof Error ? e.message : String(e);
104
+ return laws.some((law) => message.includes(`[${law}]`));
105
+ }
106
+ /** An error's first line, and the first `[LAW]` line after it when there is one. */
107
+ const headline = (e) => {
108
+ const lines = (e instanceof Error ? e.message : String(e)).split('\n').map((l) => l.trim());
109
+ const law = lines.slice(1).find((l) => l.startsWith('['));
110
+ return law ? `${lines[0]} ${law}` : (lines[0] ?? '');
111
+ };
112
+ /** Said up front by every C18(b) failure on a refused document (U7 review, W1). */
113
+ const UNVALIDATED = 'C18(b) runs a document validate() refuses, on purpose — a host that skips validation must ' +
114
+ 'still hand out no setting; a host that cannot run an unvalidated document needs a run seam ' +
115
+ 'that skips publish-time validation';
116
+ /** Row ids compared across the string/number divide, as the executor compares them. */
117
+ const namesRow = (ids, row) => ids.some((id) => String(id) === String(row));
118
+ async function observeRun(fx, probe, go) {
119
+ const before = fx.writesSeen ? await fx.writesSeen() : undefined;
120
+ const receipt = await go();
121
+ const after = fx.writesSeen ? await fx.writesSeen() : undefined;
122
+ const delta = before !== undefined && after !== undefined ? after - before : undefined;
123
+ const seen = probe.committed.length;
124
+ return {
125
+ receipt,
126
+ writes: seen > 0 ? seen : delta,
127
+ via: seen > 0 ? 'probe' : delta !== undefined ? 'writesSeen' : 'neither',
128
+ any: seen + (delta ?? 0),
129
+ };
130
+ }
131
+ /** Why a zero cannot be read as "wrote nothing" on this host — said only when nothing showed a write. */
132
+ const unobserved = (real) => 'the kit cannot observe writes on this host: a real run of chatTurn committed nothing through ' +
133
+ 'RunOptions.host and ' +
134
+ (real.via === 'neither'
135
+ ? 'the fixtures supply no writesSeen()'
136
+ : `writesSeen() moved by ${real.writes}`) +
137
+ ' — without one of the two showing a write, "a dry run wrote nothing" cannot be told from ' +
138
+ '"the probe saw nothing"';
139
+ /**
140
+ * Does a value carry the owner's declared switch — an object with `field` at
141
+ * the planted position anywhere inside it, or (`bare`) the position itself as
142
+ * one of the value's own entries, which is what a data edge drawn from
143
+ * `<owner>.settings.<field>` would deliver to a port? Functions never called.
144
+ */
145
+ function carriesSwitch(value, field, position, bare = false, seen = new Set()) {
146
+ if (!value || typeof value !== 'object')
147
+ return false;
148
+ if (seen.has(value))
149
+ return false;
150
+ seen.add(value);
151
+ const entries = Array.isArray(value) ? value.map((v, i) => [String(i), v]) : Object.entries(value);
152
+ return entries.some(([k, v]) => (k === field && v === position) ||
153
+ (bare && v === position) ||
154
+ carriesSwitch(v, field, position, false, seen));
155
+ }
156
+ // ── The requirements ────────────────────────────────────────────────────────
157
+ /** @experimental */
158
+ export const REQUIREMENTS = [
159
+ {
160
+ id: 'C1',
161
+ law: 'F3',
162
+ title: 'import(export(doc)) is identity, and the hash is stable',
163
+ consequence: 'Rows stop being the system of record. Export/import silently mutates specs, and two pubs on the same version disagree about what they are running.',
164
+ check(host, fx) {
165
+ const doc = fx.chatTurn();
166
+ const back = host.importDocument(doc);
167
+ must(host.canonicalHash(back) === host.canonicalHash(doc), 'canonical hash changed across a round trip');
168
+ must(JSON.stringify(back) === JSON.stringify(doc), 'the document changed across a round trip');
169
+ },
170
+ },
171
+ {
172
+ id: 'C2',
173
+ law: '01 §2, F1, F7, F9, F25',
174
+ title: 'every statically checkable law is rejected at publish, with a fix',
175
+ consequence: 'Invalid specs reach runtime. A user sees "it does nothing" instead of an error, and the validator stops being the thing authors trust.',
176
+ check(host, fx) {
177
+ for (const { law, doc, because } of fx.invalid()) {
178
+ const errs = host.validate(doc).filter((f) => f.severity === 'error');
179
+ must(errs.length > 0, `${law}: ${because} — but validate() returned no errors`);
180
+ must(errs.every((e) => !!e.fix), `${law}: an error with no \`fix\` — a prohibition without a stated alternative is a bug (15 §1.3)`);
181
+ }
182
+ },
183
+ },
184
+ {
185
+ id: 'C3',
186
+ law: '01 §5',
187
+ title: 'halt ends the run as `halt`, records the node and reason, and skips downstream',
188
+ consequence: 'Halting looks like failure. Every subscriber to a hot event that correctly decides "not applicable" is counted as an error, and the health signal becomes noise.',
189
+ async check(host, fx) {
190
+ const r = await host.run(fx.haltsEarly(), { input: {}, world: fx.world, bindings: fx.bindings() });
191
+ must(r.outcome === 'halt', `outcome was '${r.outcome}', not 'halt'`);
192
+ must(!!r.haltReason, 'no halt reason recorded — "why did nothing happen" is unanswerable');
193
+ must(!r.nodes.some((n) => n.kind === 'oracle'), 'a node downstream of the halt still ran');
194
+ },
195
+ },
196
+ {
197
+ id: 'C4',
198
+ law: 'F11',
199
+ title: 'the run seed is recorded and replays identically',
200
+ consequence: 'Nondeterministic Tasks stop being replayable. A dice roll, a probability roll or a sampled choice can never be explained after the fact.',
201
+ async check(host, fx) {
202
+ const doc = fx.chatTurn();
203
+ const opts = { input: {}, world: fx.world, bindings: fx.bindings(), seed: 'seed:conformance' };
204
+ const a = await host.run(doc, opts);
205
+ const b = await host.run(doc, opts);
206
+ must(a.seed === 'seed:conformance', 'the seed is not recorded on the receipt');
207
+ must(JSON.stringify(a.nodes.map((n) => n.output)) === JSON.stringify(b.nodes.map((n) => n.output)), 'two runs with the same seed produced different outputs');
208
+ },
209
+ },
210
+ {
211
+ id: 'C5',
212
+ law: 'F16',
213
+ title: 'replay reproduces a run without calling the Provider',
214
+ consequence: 'Replay re-infers. Debugging a past run costs money, changes the answer, and cannot be done at all once a connection is gone.',
215
+ async check(host, fx) {
216
+ const doc = fx.chatTurn();
217
+ const first = await host.run(doc, { input: {}, world: fx.world, bindings: fx.bindings() });
218
+ let called = 0;
219
+ const replayed = await host.replay(doc, first, fx.bindings({
220
+ 'core:oracle/generate-text@1': async () => {
221
+ called++;
222
+ return { kind: 'ok', value: { main: 'DIFFERENT', text: 'DIFFERENT' } };
223
+ },
224
+ }));
225
+ must(called === 0, 'replay invoked the Provider');
226
+ const out = (n) => JSON.stringify(n.output);
227
+ must(replayed.nodes.map(out).join() === first.nodes.map(out).join(), 'replay produced different node outputs');
228
+ },
229
+ },
230
+ {
231
+ id: 'C6',
232
+ law: 'F13',
233
+ title: 'budgets meter consumption; waiting consumes nothing',
234
+ consequence: 'A parked review gate or a queued run bills the user for time nobody spent. Budgets become a reason not to use the review gate, which is the feature they exist to protect.',
235
+ async check(host, fx) {
236
+ const r = await host.run(fx.haltsEarly(), {
237
+ input: {},
238
+ world: fx.world,
239
+ bindings: fx.bindings(),
240
+ queuedMs: 7 * 24 * 60 * 60 * 1000,
241
+ budget: { tokens: 10 },
242
+ });
243
+ must(r.consumption.tokens === 0, `a run that called nothing consumed ${r.consumption.tokens} tokens`);
244
+ must(r.outcome !== 'err', 'a week of waiting tripped a budget');
245
+ },
246
+ },
247
+ {
248
+ id: 'C7',
249
+ law: 'F36',
250
+ title: 'timeouts bound execution, never waiting',
251
+ consequence: 'A review gate cannot be left open overnight, and a queued run dies before it starts. The whole consent model becomes unusable in practice.',
252
+ async check(host, fx) {
253
+ const r = await host.run(fx.chatTurn(), {
254
+ input: {},
255
+ world: fx.world,
256
+ bindings: fx.bindings(),
257
+ queuedMs: 7 * 24 * 60 * 60 * 1000,
258
+ timeoutCeilingMs: 1000,
259
+ });
260
+ must(!r.nodes.some((n) => n.timedOut), 'queue wait tripped a node timeout');
261
+ },
262
+ },
263
+ {
264
+ id: 'C8',
265
+ law: 'F26',
266
+ title: 'forced-sequential execution produces an identical result, and a parallel clause commits its writes in declaration order',
267
+ consequence: 'The async kill switch stops being safe. An admin disabling concurrency changes answers, so the switch can never be used to diagnose anything.',
268
+ async check(host, fx, report) {
269
+ const doc = fx.gather();
270
+ const norm = (r) => r.nodes
271
+ .map((n) => `${n.nodeKey}:${n.result}:${JSON.stringify(n.output)}`)
272
+ .sort()
273
+ .join('\n');
274
+ const par = await host.run(doc, { input: { text: 'hi' }, world: fx.world, bindings: fx.bindings() });
275
+ const seq = await host.run(doc, {
276
+ input: { text: 'hi' },
277
+ world: fx.world,
278
+ bindings: fx.bindings(),
279
+ forceSequential: true,
280
+ });
281
+ must(norm(par) === norm(seq), 'parallel and forced-sequential produced different results');
282
+ // (b) Writes in a parallel clause (W1b): the state a run leaves is
283
+ // the state a sequential run leaves, so the commits land in
284
+ // declaration order whichever chain finishes first.
285
+ const writing = fx.gatherWrites?.();
286
+ if (!writing)
287
+ return report.skip('no fixture puts writes in a parallel gather — supply `gatherWrites()` (chains ending in writes, ' +
288
+ 'the first declared finishing last) for the write-order half to be judged');
289
+ const order = async (forceSequential) => {
290
+ const probe = writeProbe();
291
+ await host.run(writing, {
292
+ input: { text: 'hi' },
293
+ world: fx.world,
294
+ bindings: fx.bindings(),
295
+ host: probe.host,
296
+ forceSequential,
297
+ });
298
+ return probe.committed.map((id) => String(id).replace(/^probe:/, '').replace(/#\d+$/, ''));
299
+ };
300
+ const parOrder = await order(false);
301
+ if (parOrder.length < 2)
302
+ return report.skip(`the host's commits for gatherWrites() did not reach RunOptions.host (${parOrder.length} seen), ` +
303
+ 'so their order could not be judged');
304
+ const seqOrder = await order(true);
305
+ must(JSON.stringify(parOrder) === JSON.stringify(seqOrder), `parallel committed ${parOrder.join(' → ')} but forced-sequential committed ${seqOrder.join(' → ')} — ` +
306
+ 'a parallel clause must commit its writes in declaration order (01 §4)');
307
+ },
308
+ },
309
+ {
310
+ id: 'C9',
311
+ law: '13 §1',
312
+ title: 'a block publishes branch-results in declaration order',
313
+ consequence: 'Downstream nodes see branches in completion order, so a spec behaves differently under load than in testing — the least reproducible class of bug there is.',
314
+ async check(host, fx) {
315
+ const r = await host.run(fx.gather(), { input: { text: 'hi' }, world: fx.world, bindings: fx.bindings() });
316
+ must(r.outcome === 'ok', `gather did not complete: ${r.haltReason ?? r.outcome}`);
317
+ },
318
+ },
319
+ {
320
+ id: 'C10',
321
+ law: '01 §4, §4a',
322
+ title: 'map and loop are bounded, and exceeding the bound is visible',
323
+ consequence: 'An unbounded repeat is the most likely source of a surprise bill in the system, and for a loop it is the only thing between a bad predicate and a run that never ends.',
324
+ async check(host, fx) {
325
+ const r = await host.run(fx.looped(2), { input: {}, world: fx.world, bindings: fx.bindings() });
326
+ must(r.outcome === 'ok', 'reaching max should not be an error — it is the bound working');
327
+ must((r.notes ?? []).some((n) => /max/.test(n)), 'a loop that hit its ceiling left no record — a truncated loop must never look like a finished one');
328
+ },
329
+ },
330
+ {
331
+ id: 'C11',
332
+ law: '13 §3',
333
+ title: 'an admin kill is `cancelled`, with the actor recorded',
334
+ consequence: '"An admin stopped it" is indistinguishable from "it broke." Error dashboards fill with deliberate actions and stop being read.',
335
+ async check(host, fx) {
336
+ const r = await host.run(fx.chatTurn(), {
337
+ input: {},
338
+ world: fx.world,
339
+ bindings: fx.bindings(),
340
+ cancelSignal: () => ({ by: 'admin:test', reason: 'killed from the queue view' }),
341
+ });
342
+ must(r.outcome === 'cancelled', `outcome was '${r.outcome}'`);
343
+ must(r.cancelledBy === 'admin:test', 'the actor was not recorded');
344
+ },
345
+ },
346
+ {
347
+ id: 'C12',
348
+ law: '13 §2',
349
+ title: 'an event-triggered halt before any effect compacts; a click does not',
350
+ consequence: 'A hot event × every subscribed pipeline × every message writes a full receipt each time. Retention becomes a per-message multiplier and the receipts table eats the disk.',
351
+ async check(host, fx) {
352
+ const doc = fx.haltsEarly();
353
+ const ev = await host.run(doc, {
354
+ input: {},
355
+ world: fx.world,
356
+ bindings: fx.bindings(),
357
+ triggerSource: 'event',
358
+ });
359
+ must(ev.compact === true, 'an event-triggered early halt was not compacted');
360
+ must(ev.nodes.length === 0 && !!ev.haltReason, 'compaction dropped the reason as well as the payloads');
361
+ const ui = await host.run(doc, { input: {}, world: fx.world, bindings: fx.bindings(), triggerSource: 'ui' });
362
+ must(ui.compact !== true, 'a user-initiated run was compacted — it happens once per click');
363
+ },
364
+ },
365
+ {
366
+ id: 'C13',
367
+ law: '16 §7',
368
+ title: 'the previewed payload is the payload that would be sent',
369
+ consequence: 'Debug mode becomes a second estimator. It drifts from reality silently and is most wrong exactly when someone opens it because something is off.',
370
+ async check(host, fx) {
371
+ const doc = fx.chatTurn();
372
+ let sent;
373
+ const previewed = await host.run(doc, {
374
+ input: {},
375
+ world: fx.world,
376
+ bindings: fx.bindings(),
377
+ preview: true,
378
+ });
379
+ must(!!previewed.preview, 'a preview run produced no preview report');
380
+ await host.run(doc, {
381
+ input: {},
382
+ world: fx.world,
383
+ bindings: fx.bindings({
384
+ 'core:oracle/generate-text@1': async (i) => {
385
+ sent = i.context;
386
+ return { kind: 'ok', value: { main: 'x', text: 'x' } };
387
+ },
388
+ }),
389
+ });
390
+ must(JSON.stringify(previewed.preview.context.rendered) === JSON.stringify(sent), 'the previewed payload differs from the one actually sent');
391
+ },
392
+ },
393
+ {
394
+ id: 'C14',
395
+ law: 'F16, F18',
396
+ title: 'no receipt in the corpus contains a credential',
397
+ consequence: 'Receipts are handed to plugin authors for debugging. A credential in one is a credential mailed to a stranger, and the material/metadata split becomes a claim nobody can rely on.',
398
+ async check(host, fx) {
399
+ const runs = [
400
+ await host.run(fx.chatTurn(), { input: {}, world: fx.world, bindings: fx.bindings() }),
401
+ await host.run(fx.gather(), { input: { text: 'hi' }, world: fx.world, bindings: fx.bindings() }),
402
+ ];
403
+ for (const r of runs) {
404
+ const body = JSON.stringify(r);
405
+ must(!/sk-|api[_-]?key"?\s*:\s*"(?!\[)/i.test(body), 'a receipt contains something shaped like a credential');
406
+ }
407
+ },
408
+ },
409
+ {
410
+ id: 'C15',
411
+ law: '15 §1.3',
412
+ title: 'every validation error states what to do instead',
413
+ consequence: 'Authors get told no without being told what yes looks like. Every prohibition becomes a support thread.',
414
+ check(host, fx) {
415
+ for (const { doc } of fx.invalid()) {
416
+ for (const e of host.validate(doc)) {
417
+ must(!!e.fix && e.fix.length > 10, `finding '${e.message}' has no usable fix`);
418
+ }
419
+ }
420
+ },
421
+ },
422
+ {
423
+ id: 'C16',
424
+ law: 'F37',
425
+ title: 'a run has one live row: two are refused at publish, the one live row is named to the host, and a dry run has no real one',
426
+ consequence: 'The composer streams into the wrong row, or two placeholders appear for one turn. Stop cannot tell which row to finalise, so a cancelled reply stays "generating" forever.',
427
+ async check(host, fx) {
428
+ // (a) At publish: two independent live-row writes are two primary
429
+ // rows. That is F7's refusal, and it is the law's first half — a
430
+ // document that reaches the executor has one row to name.
431
+ const two = fx.twoWrites();
432
+ const errs = host.validate(two).filter((e) => e.severity === 'error');
433
+ must(errs.some((e) => e.law === 'F7'), `twoWrites() places two create-message placeholders — but validate() raised no F7 error ` +
434
+ `(${errs.map((e) => e.law).join(', ') || 'no errors at all'}); two live rows reached the executor`);
435
+ must(errs.filter((e) => e.law === 'F7').every((e) => !!e.fix && e.fix.length > 10), 'two live rows were refused without saying what to do instead (15 §1.3)');
436
+ // (b) At run time, on a document the host can publish: the one
437
+ // write is the run's row, told to the host exactly once, and the
438
+ // world took exactly one write. The write is observed through the
439
+ // kit's probe when the probe saw it, else through `writesSeen` for
440
+ // a host whose commits bypass `RunOptions.host` (as C17; U7 review
441
+ // W2, delta 2).
442
+ const doc = fx.chatTurn();
443
+ const probe = writeProbe();
444
+ const ends = [];
445
+ const real = await observeRun(fx, probe, () => host.run(doc, {
446
+ input: {},
447
+ world: fx.world,
448
+ bindings: fx.bindings(),
449
+ host: probe.host,
450
+ onRunEnd: (end) => {
451
+ ends.push(end);
452
+ },
453
+ }));
454
+ const r = real.receipt;
455
+ must(r.outcome === 'ok', `the run ended '${r.outcome}': ${r.haltReason ?? ''}`);
456
+ const writes = r.nodes.filter((n) => n.kind === 'outlet' && n.result === 'ok');
457
+ must(writes.length === 1, `chatTurn() has one write outlet; ${writes.length} recorded as writes`);
458
+ must(ends.length === 1, `the host heard the run end ${ends.length} times — it is told once`);
459
+ const end = ends[0];
460
+ const write = writes[0];
461
+ must(rowIdsOf(write).length > 0, `the write ('${write.nodeKey}') was recorded with no row ids — a write publishes what it wrote`);
462
+ must(end.liveRow !== undefined, 'the run named no live row, with a placeholder committed');
463
+ must(namesRow(rowIdsOf(write), end.liveRow), `the live row (${String(end.liveRow)}) is not the write's ('${write.nodeKey}' wrote ` +
464
+ `${JSON.stringify(rowIdsOf(write))}) — the run's row is the most recent live-row outlet's`);
465
+ must(real.writes !== undefined && real.writes > 0, unobserved(real));
466
+ must(real.writes === 1, `the world took ${real.writes} write(s) from one write outlet — one live row is one commit`);
467
+ // (c) Dry: the same document commits nothing, so no real row can
468
+ // be primary — the host is told `dry`, and named nothing or the
469
+ // synthetic `dry:` row. A write on either channel counts.
470
+ const dryEnds = [];
471
+ const dryProbe = writeProbe();
472
+ const dry = await observeRun(fx, dryProbe, () => host.run(doc, {
473
+ input: {},
474
+ world: fx.world,
475
+ bindings: fx.bindings(),
476
+ host: dryProbe.host,
477
+ dry: true,
478
+ onRunEnd: (end) => {
479
+ dryEnds.push(end);
480
+ },
481
+ }));
482
+ must(dryEnds.length === 1 && dryEnds[0].dry === true, 'a dry run did not tell the host it was dry');
483
+ must(dryEnds[0].liveRow === undefined || String(dryEnds[0].liveRow).startsWith('dry:'), `a dry run named a real row as primary (${String(dryEnds[0].liveRow)}) — a preview that owns a row leaves it behind`);
484
+ must(dry.any === 0, `a dry run committed ${dry.any} row(s)`);
485
+ },
486
+ },
487
+ {
488
+ id: 'C17',
489
+ law: 'F38',
490
+ title: 'a preview writes nothing: every outlet runs and every write is synthetic',
491
+ consequence: 'A token estimate leaves a placeholder row behind every time somebody types, and a debug preview bills the user for rows they never asked for. Preview stops being safe to open.',
492
+ async check(host, fx) {
493
+ const doc = fx.chatTurn();
494
+ const probe = writeProbe();
495
+ const opts = { input: {}, world: fx.world, bindings: fx.bindings(), host: probe.host };
496
+ // Control: a write must be visible at all, or "zero" is no finding.
497
+ // The probe's count when it saw the commit; else `writesSeen` for a
498
+ // host that does not route `ctx.commit` through `RunOptions.host`;
499
+ // with neither showing a write, the gap is named.
500
+ const real = await observeRun(fx, probe, () => host.run(doc, opts));
501
+ must(real.writes !== undefined && real.writes > 0, unobserved(real));
502
+ const dryProbe = writeProbe();
503
+ const ends = [];
504
+ const dry = await observeRun(fx, dryProbe, () => host.run(doc, {
505
+ ...opts,
506
+ host: dryProbe.host,
507
+ dry: true,
508
+ onRunEnd: (end) => {
509
+ ends.push(end);
510
+ },
511
+ }));
512
+ const r = dry.receipt;
513
+ must(dry.any === 0, `a dry run reached the world: ${dry.any} write(s) committed`);
514
+ must(ends.length === 1 && ends[0].dry === true, 'the run did not report itself dry to the host');
515
+ must(r.outcome === 'ok', `a dry run still runs to the end; this one ended '${r.outcome}'`);
516
+ const outlets = r.nodes.filter((n) => n.kind === 'outlet');
517
+ must(outlets.length > 0, 'no outlet ran — a dry run runs every outlet, it just commits nothing');
518
+ for (const n of outlets) {
519
+ must(n.dry === true, `outlet '${n.nodeKey}' is not marked dry on its receipt row`);
520
+ const ids = rowIdsOf(n);
521
+ must(ids.length > 0, `outlet '${n.nodeKey}' published no ids — a downstream node reads the synthetic id as it would a real one`);
522
+ must(ids.every((id) => typeof id === 'string' && id.startsWith('dry:')), `outlet '${n.nodeKey}' recorded a real-looking id in a dry run: ${JSON.stringify(ids)}`);
523
+ }
524
+ // The event a write causes is still recorded — flagged dry, never
525
+ // dispatched — so a reader of the receipt can tell "nothing was
526
+ // caused" from "a write whose subscribers happened to be zero".
527
+ must(r.emitted.length > 0, 'a dry write caused no recorded event — the event a write would cause is recorded and flagged dry, not dropped (U7 review, S3)');
528
+ must(r.emitted.every((e) => e.dry === true), 'an event a dry write would have caused is recorded as emitted — it must be flagged dry, never dispatched');
529
+ },
530
+ },
531
+ {
532
+ id: 'C18',
533
+ law: 'F39',
534
+ title: 'settings never travel: a setting is read at its owner, and no node can read another\'s',
535
+ consequence: 'A plugin node silently depends on another node\'s review toggle or enabled switch. Configs stop being independent — flipping one switch changes a node nobody tuned — and the panel can no longer say where a value came from.',
536
+ async check(host, fx, report) {
537
+ // (a) Statically: a data edge drawn from a node's `settings` address
538
+ // is refused, under this law, with the fix.
539
+ const entries = fx.invalid().filter((e) => e.law === 'F39');
540
+ must(entries.length > 0, 'the fixtures carry no F39 document — nothing to refuse');
541
+ for (const { doc, because } of entries) {
542
+ const errs = host.validate(doc).filter((e) => e.severity === 'error');
543
+ must(errs.some((e) => e.law === 'F39'), `${because} — but validate() raised no F39 error (${errs.map((e) => e.law).join(', ') || 'no errors at all'})`);
544
+ must(errs.filter((e) => e.law === 'F39').every((e) => !!e.fix && e.fix.length > 10), `${because} — refused without saying what to do instead`);
545
+ }
546
+ // (b) At run time, on the owner's DECLARED switch (U7 delta review,
547
+ // 1). The write outlet is gated, so `settings.review` is declared
548
+ // for it; the kit sets it `on` through `world.overrides` and
549
+ // supplies a reviewer that approves and records who asked.
550
+ //
551
+ // Positive control first: the reviewer was asked for the OWNER at
552
+ // `on` — the owner received its own switch. (Its hook never sees
553
+ // the switch; that is the law. The gate is where the owner reads
554
+ // it, so the gate is where the kit looks.) A host that ignores
555
+ // overrides fails here, and never gets to pass on a leak it could
556
+ // not have made.
557
+ //
558
+ // Then nobody else: no other hook's ctx carries the owner's switch
559
+ // at its planted value, and no other hook's input does — the ctx
560
+ // being the surface a host hands out, the input the data the
561
+ // executor resolved; a data edge drawn from the address (the
562
+ // refused documents, run UNVALIDATED as an import that skipped the
563
+ // check would be) must deliver nothing. A sentinel planted beside
564
+ // the switch on the same slot is the second signal: a host that
565
+ // hands the whole settings object anywhere leaks it too. The
566
+ // sentinel and the switch are THE check (U7 review, S4): a ctx key
567
+ // that merely sounds like an accessor (`settingsOf`,
568
+ // `configuredSampling`) is a hint in the failure text, never a
569
+ // finding. A host that cannot run an unvalidated document is
570
+ // skipped on that half, with the reason on the result (W1).
571
+ const sentinel = 'F39-must-not-travel';
572
+ const accessor = /setting|config/i;
573
+ const probed = [
574
+ { doc: fx.chatTurn(), unvalidated: false },
575
+ ...entries.map((e) => ({ doc: e.doc, unvalidated: true })),
576
+ ];
577
+ for (const { doc, unvalidated } of probed) {
578
+ const preface = unvalidated ? `${UNVALIDATED}: ` : '';
579
+ const writer = doc.nodes.find((n) => n.kind === 'outlet');
580
+ must(!!writer, `'${doc.id}' has no outlet to plant a setting on`);
581
+ const owner = writer.key;
582
+ const world = {
583
+ ...(fx.world ?? {
584
+ overrides: [],
585
+ samplingConfigs: [],
586
+ connections: [],
587
+ activeConnection: {},
588
+ }),
589
+ overrides: [
590
+ ...(fx.world?.overrides ?? []),
591
+ { scopeKind: 'config', nodeKey: owner, slot: 'settings', path: 'review', value: 'on' },
592
+ { scopeKind: 'config', nodeKey: owner, slot: 'settings', path: 'probe', value: sentinel },
593
+ ],
594
+ };
595
+ const asked = [];
596
+ const reviewer = async (req) => {
597
+ asked.push({ nodeKey: req.nodeKey, position: req.position });
598
+ return { action: 'approve', by: 'conformance', at: 0 };
599
+ };
600
+ const seen = [];
601
+ let r;
602
+ try {
603
+ r = await host.run(doc, {
604
+ input: {},
605
+ world,
606
+ bindings: spyBindings(fx.bindings(), seen),
607
+ reviewer,
608
+ });
609
+ }
610
+ catch (e) {
611
+ if (unvalidated && refusedUnder(e, ['F39', 'F7'])) {
612
+ report.skip(`C18(b) on '${doc.id}': this host refused to run it (${headline(e)}). ${UNVALIDATED}.`);
613
+ continue;
614
+ }
615
+ throw e;
616
+ }
617
+ must(r.outcome === 'ok', `${preface}the probed run of '${doc.id}' ended '${r.outcome}': ${r.haltReason ?? ''}`);
618
+ must(seen.length > 0, `${preface}no hook was invoked in '${doc.id}' — nothing to inspect`);
619
+ must(asked.some((q) => q.nodeKey === owner && q.position === 'on'), `${preface}the owner never received its own switch: 'review' was set to 'on' at ` +
620
+ `'${owner}.settings' through world.overrides, and the reviewer was never asked for ` +
621
+ `'${owner}' in '${doc.id}' (asked for: ${asked.map((q) => `${q.nodeKey}@${q.position}`).join(', ') || 'nobody'}) ` +
622
+ `— a setting is read at its owner, and this one was not read at all`);
623
+ const ownerHook = `${writer.definitionId}@${writer.definitionVersion}`;
624
+ const hint = () => {
625
+ const keys = [
626
+ ...new Set(seen.flatMap((s) => Object.keys((s.ctx ?? {})).filter((k) => accessor.test(k)))),
627
+ ];
628
+ return keys.length
629
+ ? ` (ctx keys shaped like an accessor, worth a look: ${keys.join(', ')} — a name is a hint, never the finding)`
630
+ : '';
631
+ };
632
+ for (const { id, input, ctx } of seen) {
633
+ must(!carries(input, sentinel), `${preface}a setting planted at '${owner}.settings' arrived in the input of ${id} in '${doc.id}' — settings travelled as data${hint()}`);
634
+ // Its own switches are read AT the owner; the law is about
635
+ // another node's. Every other hook must be handed nothing
636
+ // planted there — not the switch, not the sentinel.
637
+ if (id === ownerHook)
638
+ continue;
639
+ must(!carriesSwitch(input, 'review', 'on', true), `${preface}the owner's declared switch ('${owner}.settings.review' = 'on') arrived in the input of ${id} in '${doc.id}' — a data edge from a settings address must deliver nothing${hint()}`);
640
+ must(!carriesSwitch(ctx, 'review', 'on'), `${preface}the owner's declared switch ('${owner}.settings.review' = 'on') is readable from the ctx handed to ${id} in '${doc.id}' — a node can read another's switches${hint()}`);
641
+ must(!carries(ctx, sentinel), `${preface}a setting planted at '${owner}.settings' is readable from the ctx handed to ${id} in '${doc.id}' — a node can read another's switches${hint()}`);
642
+ }
643
+ }
644
+ },
645
+ },
646
+ {
647
+ id: 'C19',
648
+ law: 'F40',
649
+ title: 'every enabled action is reachable: listed once in its venue, and by `/` in the composer',
650
+ consequence: 'An installed action is invisible with no way to reach it — a plugin\'s one button is hidden by prominence, or dropped from the channel it was declared for — and its author gets "it does nothing" instead of a bug.',
651
+ async check(host, fx) {
652
+ // The law is about what the HOST lists. A listing the kit computed
653
+ // for it would pass any host, so the host's own projection is the
654
+ // one judged, and a host without one is not judged at all (U7
655
+ // review, C1).
656
+ must(typeof host.listActions === 'function', 'this host supplies no `listActions` seam — C19 cannot be judged: the law is about what the host ' +
657
+ 'lists, and a listing the kit computed on its behalf would pass any host. Implement ' +
658
+ 'HostUnderTest.listActions(doc, channel) with the host\'s own venue projection');
659
+ const doc = fx.actions();
660
+ const errs = host.validate(doc).filter((e) => e.severity === 'error');
661
+ must(errs.length === 0, `the actions fixture does not validate: ${errs.map((e) => e.message).join('; ')}`);
662
+ const declared = actionsOf(doc);
663
+ must(declared.length >= 4, `the fixture declares ${declared.length} action(s); the law needs a quick one, a plain one, one on a named channel and one whose key is a core verb's`);
664
+ must(declared.some((a) => a.quick === true) && declared.some((a) => a.quick !== true), 'the fixture needs one quick action and one that is not');
665
+ must(declared.some((a) => a.venue.some((v) => !!v.channel)), 'the fixture needs an action on a named channel');
666
+ // The host's listing, read once per channel.
667
+ const listings = new Map();
668
+ const listed = async (channel) => {
669
+ let l = listings.get(channel);
670
+ if (!l) {
671
+ l = await host.listActions(doc, channel);
672
+ must(!!l && typeof l === 'object', `listActions('${channel}') returned ${String(l)} — a listing per venue kind`);
673
+ listings.set(channel, l);
674
+ }
675
+ return l;
676
+ };
677
+ // By identity — key and spec — never by object: a host decorates its entries.
678
+ const same = (a) => (x) => x.key === a.key && x.specId === a.specId;
679
+ const entriesOf = (l, kind) => [
680
+ ...(l[kind]?.primary ?? []),
681
+ ...(l[kind]?.overflow ?? []),
682
+ ];
683
+ const mainSlug = parseChannel(DEFAULT_CHANNEL).slug;
684
+ for (const a of declared)
685
+ for (const v of a.venue) {
686
+ if (v.kind === 'form')
687
+ continue; // a form venue is listed by no listing; the block reaches it
688
+ const kind = v.kind;
689
+ const channel = v.channel ?? DEFAULT_CHANNEL;
690
+ const listing = (await listed(channel))[kind];
691
+ must(!!listing, `the host's listing for '${channel}' has no '${kind}' venue — every listed venue kind is a bucket, empty or not`);
692
+ const inPrimary = listing.primary.filter(same(a)).length;
693
+ const inOverflow = listing.overflow.filter(same(a)).length;
694
+ must(inPrimary + inOverflow === 1, `'${a.key}' appears ${inPrimary + inOverflow} time(s) in the '${kind}' venue on '${channel}' — every enabled action is listed exactly once, in the primary set or the overflow`);
695
+ must((a.quick === true) === (inPrimary === 1), `'${a.key}' declares quick: ${a.quick === true} but the host listed it in ${inPrimary ? 'the primary set' : 'the overflow'} of '${kind}' on '${channel}'`);
696
+ // Declared for one channel: absent from another. Judged
697
+ // against `main` only when the declared slug is not main's
698
+ // (U7 review, W4).
699
+ if (v.channel !== undefined && parseChannel(v.channel).slug !== mainSlug) {
700
+ const elsewhere = entriesOf(await listed(DEFAULT_CHANNEL), kind);
701
+ must(!elsewhere.some(same(a)), `'${a.key}' is declared for channel '${v.channel}' but the host listed it in '${kind}' on '${DEFAULT_CHANNEL}'`);
702
+ }
703
+ }
704
+ // By `/`: the slash name the HOST lists a composer action under —
705
+ // in the grammar its spec may claim, and the declared name when
706
+ // there is one, the derived name otherwise.
707
+ for (const a of declared) {
708
+ const composer = a.venue.find((v) => v.kind === 'composer');
709
+ if (!composer)
710
+ continue;
711
+ const channel = composer.channel ?? DEFAULT_CHANNEL;
712
+ const entry = entriesOf(await listed(channel), 'composer').find(same(a));
713
+ must(!!entry, `composer action '${a.key}' is not in the host's composer listing on '${channel}'`);
714
+ must(typeof entry.slash === 'string' && entry.slash.length > 0, `the host lists composer action '${a.key}' with no slash name — it is unreachable by /`);
715
+ const slash = entry.slash;
716
+ const grammar = slashFindings(slash, a.specId);
717
+ must(grammar.length === 0, `the host lists composer action '${a.key}' under '/${slash}', which its spec may not claim: ${grammar.join('; ')}`);
718
+ const expected = slashNameOf(a, a.specId);
719
+ must(slash === expected, a.slash
720
+ ? `composer action '${a.key}' declares the slash name '/${a.slash}' but the host lists it under '/${slash}'`
721
+ : `composer action '${a.key}' declares no slash name, so it is called by the derived one '/${expected}' — the host lists it under '/${slash}'`);
722
+ }
723
+ },
724
+ },
725
+ {
726
+ id: 'C20',
727
+ law: 'F41',
728
+ title: 'the effects line: an out-of-fiction effect is owner-only and never where a character could be asked',
729
+ consequence: 'A character grants another character permission by construction: a `world` action — cards, lore, settings, connections — sits in a form or a widget where an AI-portrayed participant or a plugin can press it, or lists a participant among those who may act.',
730
+ check(host, fx) {
731
+ // The two the validator sees statically: a `world` action in a venue
732
+ // off the owner's side (`form`, `extra`, `widget` — a message's own
733
+ // ⋮ is the owner's since lair re-plan R11), and one whose `act`
734
+ // audience names a participant — each
735
+ // labelled with the line's own law, F41, so the kit keys on the
736
+ // label and never on a word (U7 review, W3). The third half of the
737
+ // line — a message block naming a `world` action — is judged at
738
+ // the write (`worldBlockFunctions`), not by `validate()`: a spec's
739
+ // `blocks` are almost always a data edge from the node that made
740
+ // them, and a literal is not inspected at publish today. Not
741
+ // checked here for that reason — C23 holds it, at the write, and
742
+ // holds the `form` venue's half at publish beside it.
743
+ const entries = fx.invalid().filter((e) => e.law === 'F41');
744
+ must(entries.length >= 2, `the fixtures carry ${entries.length} F41 document(s); the line has a venue half and an audience half`);
745
+ for (const { doc, because } of entries) {
746
+ const errs = host.validate(doc).filter((e) => e.severity === 'error');
747
+ must(errs.some((e) => e.law === 'F41'), `${because} — but validate() raised no F41 error (${errs.map((e) => e.law).join(', ') || 'no errors at all'})`);
748
+ must(errs.filter((e) => e.law === 'F41').every((e) => !!e.fix && e.fix.length > 10), `${because} — refused without a usable fix; the line is a prohibition, and a prohibition states its alternative (15 §1.3)`);
749
+ }
750
+ },
751
+ },
752
+ {
753
+ id: 'C21',
754
+ law: 'F7, 01 §4',
755
+ title: 'one live row per run, never inside a repeat, and no second message on its channel',
756
+ consequence: 'One turn leaves two reply rows behind — or N of them, one per repeat — and the session has no single row to stream into, stop or finalise; or a second message races the reply for its channel. Writes beside the reply (lore, the annex, another channel) are fine: the live row is what must be one.',
757
+ check(host, fx, report) {
758
+ // (a) Two live-row outlets in one document (R44, W1: other writes
759
+ // are unlimited — the live row is what must be one). C16 reads the
760
+ // same refusal.
761
+ const errs = host.validate(fx.twoWrites()).filter((e) => e.severity === 'error');
762
+ const f7 = errs.filter((e) => e.law === 'F7');
763
+ must(f7.length > 0, `twoWrites() places two live-row outlets — but validate() raised no F7 error ` +
764
+ `(${errs.map((e) => e.law).join(', ') || 'no errors at all'}); a run with two live rows has ` +
765
+ `no single row to stream into, stop or finalise`);
766
+ must(f7.every((e) => !!e.fix && e.fix.length > 10), 'two live rows were refused without saying what to do instead — update the first through its ' +
767
+ 'target, or write the second thing beside it (15 §1.3)');
768
+ // (b) The same law one level in: a live row inside a repeating
769
+ // clause is one reply row per pass. Other writes may repeat.
770
+ const doc = fx.writeInClause?.();
771
+ if (!doc)
772
+ return report.skip('no fixture places a live row inside a repeat — supply `writeInClause()` (an `each` or ' +
773
+ 'loop body with a live-row outlet in it) for the 01 §4 half to be judged');
774
+ const inner = host.validate(doc).filter((e) => e.severity === 'error');
775
+ must(inner.some((e) => e.law === '01 §4'), `writeInClause() puts a live row inside a repeat — but validate() raised no '01 §4' error ` +
776
+ `(${inner.map((e) => e.law).join(', ') || 'no errors at all'})`);
777
+ must(inner.filter((e) => e.law === '01 §4').every((e) => !!e.fix && e.fix.length > 10), 'a live row inside a repeat was refused without naming the spine as where it goes instead (15 §1.3)');
778
+ },
779
+ },
780
+ {
781
+ id: 'C22',
782
+ law: 'F8, F32',
783
+ title: 'no pipeline triggers another: no trigger outlet, no trigger on a hook surface, no node emits; a custom event is recorded by a write',
784
+ consequence: 'Pipelines start each other. A run nobody asked for calls a model, writes a row and appears on no receipt as anything’s consequence, and a loop between two specs has no budget and no place to break it. The one readable path — a write, the event that write causes, the pipeline a preset bound to that event — stops being the whole story. A package’s own event is on that path too: `record-event` is a write, and the event it causes is the one its config names.',
785
+ check(host, fx, report) {
786
+ // (a) Nothing published is a trigger. The registry is the evidence
787
+ // and it is the host's: whatever it registered is in here. Read by
788
+ // name, and deliberately narrower than the SDK suite's own scan
789
+ // (`authorLaws.test.ts`), because a third-party host's registry is
790
+ // full of names that suite never sees — an outlet that invokes a
791
+ // webhook is not a node that starts a pipeline.
792
+ const startsARun = /^(trigger|dispatch|invoke)(@|$)|^(trigger|dispatch|invoke|start|run)-(spec|pipeline|run|turn)(@|$)/i;
793
+ const triggers = allDefinitions().filter((d) => d.kind === 'outlet' && startsARun.test(d.id.split('/')[1] ?? ''));
794
+ must(triggers.length === 0, `the registry publishes ${triggers.map((d) => d.id).join(', ')} as an outlet — a node that starts ` +
795
+ `another pipeline is a run with no cause on any receipt; a pipeline begins at the event a write ` +
796
+ `caused and a preset that bound it`);
797
+ // (b) Nor may a hook surface hand one out (F32) — `trigger`, and
798
+ // the peer invocation beside it: `run` and `call`.
799
+ for (const member of ['trigger', 'run', 'call']) {
800
+ const found = assertHookSurface('event', { log: () => { }, [member]: () => { } });
801
+ must(found.ok === false && found.found.includes(member), `a hook surface carrying '${member}' was accepted — a hook that can start work opts out of the ` +
802
+ `receipt, the budget and the consent screen (F32)`);
803
+ }
804
+ must(assertHookSurface('event', { log: () => { } }).ok, 'a hook surface with nothing forbidden on it was refused — the line is the named members, not the shape');
805
+ // (d) A package's own event is caused the same way (E1): by the one
806
+ // write `record-event`, whose event is named by its config
807
+ // (`causesEventFrom`), never by a node declaring what it emits.
808
+ const recorders = allDefinitions().filter((d) => typeof d.causesEventFrom === 'string');
809
+ for (const d of recorders) {
810
+ const effects = d.effects;
811
+ must(d.kind === 'outlet' && effects === 'write', `${d.id} names the event it causes from its config, but is a ${d.kind} with ` +
812
+ `${String(effects ?? 'no')} effects — only a write outlet may cause an event`);
813
+ }
814
+ // (c) And a node cannot emit its way there: F8, at publish. A node
815
+ // declaring `emits` names the event another pipeline listens for,
816
+ // which is a trigger spelled sideways.
817
+ const emits = fx.invalid().filter((e) => e.law === 'F8');
818
+ if (!emits.length)
819
+ return report.skip("no fixture declares `emits` on a node — supply one under law 'F8' for the third half to be judged");
820
+ for (const { doc, because } of emits) {
821
+ const errs = host.validate(doc).filter((e) => e.severity === 'error');
822
+ must(errs.some((e) => e.law === 'F8'), `${because} — but validate() raised no F8 error ` +
823
+ `(${errs.map((e) => e.law).join(', ') || 'no errors at all'})`);
824
+ must(errs.filter((e) => e.law === 'F8').every((e) => !!e.fix && e.fix.length > 10), `${because} — refused without naming the one path: a write causes the event its outlet ` +
825
+ `declares, and a preset binds a pipeline to that event (15 §1.3)`);
826
+ }
827
+ },
828
+ },
829
+ {
830
+ id: 'C23',
831
+ law: 'F41',
832
+ title: 'A `world` action may appear only in the `composer`, `session-settings`, `admin` or `review` venue, its `act` audience is `owner` and/or `admin` only, and no message block may name it — unless that block is addressed to `owner`, who is that action’s whole audience. The `form` venue stays fiction-only: a venue is declared and an addressee is decided at run time, so the construction-time check cannot see one.',
833
+ consequence: 'A block a node wrote puts an out-of-fiction button in front of whoever is reading — "shall I add them to your contacts?" — and a character, or a participant answering a form, presses it. Permission stops being the owner’s to give, and the audit trail says a message did it. Held too widely it breaks the other way: a host that refuses an owner-addressed block refuses the owner their own action, and a genre whose world-building is a question put to the owner cannot ask it at all.',
834
+ check(host, fx, report) {
835
+ // (a) At publish, where a venue makes it visible. `form` is the one
836
+ // venue a block reaches — it is listed nowhere else
837
+ // (`LISTED_VENUE_KINDS` leaves it out) — so an action declaring
838
+ // `effects: 'world'` there is a block-carried world action the
839
+ // document itself admits to, and `validate()` refuses it under F41.
840
+ const formWorld = fx
841
+ .invalid()
842
+ .filter((e) => e.law === 'F41' &&
843
+ actionsOf(e.doc).some((a) => effectsOf(a) === 'world' && a.venue.some((v) => v.kind === 'form')));
844
+ if (!formWorld.length)
845
+ report.skip("no fixture declares a 'world' action in the 'form' venue — supply one under law 'F41' for the " +
846
+ 'publish-time half to be judged');
847
+ for (const { doc, because } of formWorld) {
848
+ const errs = host.validate(doc).filter((e) => e.severity === 'error');
849
+ must(errs.some((e) => e.law === 'F41'), `${because} — but validate() raised no F41 error ` +
850
+ `(${errs.map((e) => e.law).join(', ') || 'no errors at all'}); the form venue is a block, ` +
851
+ `and a block is the one place a character can be handed a button`);
852
+ must(errs.filter((e) => e.law === 'F41').every((e) => !!e.fix && e.fix.length > 10), `${because} — refused without a usable fix; a prohibition states its alternative (15 §1.3)`);
853
+ }
854
+ // (b) At the write, where the rest of it lives — and it is a
855
+ // runtime law rather than a publish-time one for a reason worth
856
+ // saying out loud: **no document carries a block tree.** A spec's
857
+ // blocks are a node's output, so "this block names a world action"
858
+ // can only be asked of the blocks a run produced, against the
859
+ // document that contributed the action. `worldBlockFunctions` is
860
+ // that question; the host runs it at the write and refuses when it
861
+ // answers with anything.
862
+ const doc = fx.worldAction?.();
863
+ if (!doc)
864
+ return report.skip('no fixture contributes a `world` action — supply `worldAction()` (a document with one in the ' +
865
+ 'composer, session-settings, admin or review venue) for the block half to be judged');
866
+ const world = actionsOf(doc).filter((a) => effectsOf(a) === 'world');
867
+ must(world.length > 0, `worldAction() contributes no action with \`effects: 'world'\` — the block half has nothing to name`);
868
+ const choices = (fn) => [
869
+ {
870
+ kind: 'choices',
871
+ question: 'Give them the keys?',
872
+ actions: [{ fn, label: 'Yes', choice: 'yes' }],
873
+ },
874
+ ];
875
+ const fn = world[0].key;
876
+ must(worldBlockFunctions(choices(fn), doc).includes(fn), `a choices block naming '${fn}' — a 'world' action of ${doc.id} — was not refused at the write; ` +
877
+ `the effects line holds at the block or it does not hold`);
878
+ // The negative control, because a gate that refused every block
879
+ // would pass the line above and break every message with a choice
880
+ // in it: a function no action declares is not a world action.
881
+ must(worldBlockFunctions(choices('conformance:no-such-function'), doc).length === 0, 'a block naming a function no action declares was refused as a world action — the gate reads the ' +
882
+ "document's declarations, never the block alone");
883
+ // (c) The one exception, both ways round (L1, ruled 2026-09-17).
884
+ // The line exists so that an out-of-fiction effect is never *a
885
+ // question a character could be asked*, and a block put to the
886
+ // OWNER is not that question: the owner is already the whole of
887
+ // such an action's `act` audience, so pressing the button is the
888
+ // owner acting. Two controls, because an exception needs both —
889
+ // a gate that kept refusing would leave the genres that build
890
+ // their world through an owner-addressed form with no way to ask,
891
+ // and a gate that stopped refusing would hand the button to the
892
+ // room.
893
+ const addressed = (to) => choices(fn).map((b) => ({ ...b, addressee: to }));
894
+ must(worldBlockFunctions(addressed('owner'), doc).length === 0, `a choices block addressed to 'owner' naming '${fn}' — a 'world' action of ${doc.id} — was refused at ` +
895
+ 'the write; the owner is that action’s whole audience, and the one addressee the line has always ' +
896
+ 'allowed to press it');
897
+ must(worldBlockFunctions(addressed('participant'), doc).includes(fn), `a choices block addressed to 'participant' naming '${fn}' was not refused; the exception is the owner ` +
898
+ 'and nobody else — `participant` is any member of the session, which is precisely the reader a ' +
899
+ 'world button must never reach');
900
+ },
901
+ },
902
+ {
903
+ id: 'C24',
904
+ law: 'R-15',
905
+ title: 'every genre can be addressed by a form, and every shipped preset binds the pipeline that answers one',
906
+ consequence: 'A pipeline writes a form into the session and nothing answers it: the block renders, the reader fills it in, the press reaches no run, and no error says why. The feature works in the genre it was built in and is dead in every other.',
907
+ async check(host, fx, report) {
908
+ const shipped = await host.shipped?.();
909
+ if (!shipped)
910
+ return report.skip('the host declares no catalogue — supply `shipped()` (its genres and presets) for the form ' +
911
+ 'surface to be judged; a host that ships neither has no form to leave unanswered');
912
+ must(shipped.genres.length > 0, 'the host shipped an empty catalogue — a host with no genres of its own omits `shipped()`; an ' +
913
+ 'empty one is a seam that judges nothing while looking like it did');
914
+ const EVENT = sessionEvents.formAddressed;
915
+ for (const g of shipped.genres) {
916
+ const decl = g.events?.[EVENT];
917
+ must(!!decl, `genre '${g.id}' does not declare ${EVENT} — a genre that cannot be addressed by a form has ` +
918
+ `nowhere to route an answer, so a pipeline that writes one into it has written a dead control`);
919
+ must(decl.required !== true, `genre '${g.id}' makes ${EVENT} required — the slot is offered, never demanded: a genre whose ` +
920
+ `forms are all owner-addressed still declares it, and a preset that binds nothing is still a preset`);
921
+ }
922
+ for (const p of shipped.presets) {
923
+ const bound = p.bindings?.[EVENT];
924
+ must(!!bound?.spec, `preset '${p.slug}' binds no pipeline to ${EVENT} — a shipped preset answers the forms its ` +
925
+ `genre can be addressed by, or the answer button does nothing in every session started from it`);
926
+ }
927
+ },
928
+ },
929
+ {
930
+ id: 'C25',
931
+ law: 'plans/29 R-3, F11, F32',
932
+ title: 'the plugin grant table: what a hook of each kind is handed, and what no hook is ever handed',
933
+ consequence: 'A plugin reaches through a door nobody granted: a task that was meant to be pure keeps state, a handler calls a model outside the receipt and the budget, or an outlet commits a row the consent screen never mentioned. The permissions an administrator reads stop describing what the package can do.',
934
+ async check(host, fx, report) {
935
+ // (a) The table, stated as the law rather than read as a setting.
936
+ // `hookCtxGrants` is its one implementation — the two sandboxes'
937
+ // programs and the app's `hookCtx.ts` build from it — so pinning it
938
+ // here is what makes a loosened grant a red line instead of a quiet
939
+ // change: a task that gains storage stops being pure (F11), and a
940
+ // query that gains fetch is network access with no consent surface
941
+ // (F32).
942
+ const table = [
943
+ ['task', false, false],
944
+ ['chain-link', false, false],
945
+ ['query', true, false],
946
+ ['outlet', true, false],
947
+ ['event', true, false],
948
+ ['lifecycle', true, false],
949
+ ['oracle', true, true],
950
+ ];
951
+ must(table.length === HOOK_CTX_KINDS.length, `the SDK declares ${HOOK_CTX_KINDS.length} hook ctx kinds (${HOOK_CTX_KINDS.join(', ')}) and this ` +
952
+ `requirement states the grants for ${table.length} — a kind this requirement does not state is a ` +
953
+ `grant nobody decided`);
954
+ for (const [kind, storage, fetch] of table) {
955
+ const g = hookCtxGrants(kind);
956
+ must(g.storage === storage && g.fetch === fetch, `the grant table hands a '${kind}' hook ${JSON.stringify(g)}; the law is ` +
957
+ `{ storage: ${storage}, fetch: ${fetch} }`);
958
+ }
959
+ must(hookCtxKeysFor('task').join(' ') === 'random now log signal', `a plugin task's context is random, now, log and signal — this build hands it ` +
960
+ `[${hookCtxKeysFor('task').join(', ')}]`);
961
+ // (b) What this host actually endows, kind by kind.
962
+ if (!host.hookCtxKeys)
963
+ return report.skip('the host has no plugin surface to hand a hook — supply `hookCtxKeys(kind)` (the keys a ' +
964
+ 'dispatched handler of that kind finds on its ctx) for the endowment to be judged; until then ' +
965
+ 'the table above is checked and the sandbox is proved by the host’s own tests');
966
+ const why = {
967
+ read: 'core rows — a plugin reads what its own queries and the pipeline hand it, never the database',
968
+ call: 'a model outside the receipt, the budget and the review gate (F32)',
969
+ commit: 'a write. This is also why a plugin write-class outlet is not available at all: it emits the ' +
970
+ 'event it declares and core’s own outlet does the writing (the packager refuses the ' +
971
+ 'declaration up front, `E_PLUGIN_WRITE_OUTLET`)',
972
+ };
973
+ const unjudged = [];
974
+ for (const kind of HOOK_CTX_KINDS) {
975
+ const keys = await host.hookCtxKeys(kind);
976
+ if (!keys) {
977
+ unjudged.push(kind);
978
+ continue;
979
+ }
980
+ for (const forbidden of ['read', 'call', 'commit'])
981
+ must(!keys.includes(forbidden), `a plugin ${kind} hook is handed '${forbidden}' — ${why[forbidden]}`);
982
+ must(keys.join(' ') === hookCtxKeysFor(kind).join(' '), `a plugin ${kind} hook is handed [${keys.join(', ')}]; the grant table says ` +
983
+ `[${hookCtxKeysFor(kind).join(', ')}]`);
984
+ }
985
+ if (unjudged.length)
986
+ report.skip(`the host dispatches no plugin hook of kind ${unjudged.join(', ')}, so those rows of the table ` +
987
+ `were not judged against anything it builds`);
988
+ },
989
+ },
990
+ {
991
+ id: 'C26',
992
+ law: '20 §12, F32',
993
+ title: 'a frame has no ambient authority: opaque origin, its own scripts, no forms, no external resources',
994
+ consequence: 'A package’s UI reads the session’s cookies, calls the app’s API as the signed-in user, or posts a form to an origin nobody granted. The boundary that makes third-party UI safe to install stops existing, and installing a package becomes a trust decision the user has no way to reason about.',
995
+ async check(host, fx, report) {
996
+ const mount = await host.frameMount?.();
997
+ if (!mount)
998
+ return report.skip('the host mounts no frames — supply `frameMount()` (the iframe’s sandbox attribute and the ' +
999
+ 'CSP the document is served under) for the boundary to be judged');
1000
+ // The sandbox. `allow-scripts` and nothing else: without
1001
+ // `allow-same-origin` the document is on an opaque origin, which is
1002
+ // what makes its storage, its cookies and its DOM reach its own and
1003
+ // nobody else's; without `allow-forms` a `<form>` submit does not
1004
+ // leave the frame.
1005
+ const tokens = mount.sandbox.split(/\s+/).filter(Boolean);
1006
+ must(tokens.includes('allow-scripts'), `the frame is mounted with sandbox="${mount.sandbox}" — a frame is a document that runs, and ` +
1007
+ `without allow-scripts the surface is a still image`);
1008
+ const extra = tokens.filter((t) => t !== 'allow-scripts');
1009
+ must(extra.length === 0, `the frame is mounted with ${extra.join(', ')} beside allow-scripts` +
1010
+ (extra.includes('allow-same-origin')
1011
+ ? ' — allow-same-origin gives the document the host’s origin: its cookies, its storage and its API as the signed-in user'
1012
+ : extra.includes('allow-forms')
1013
+ ? ' — allow-forms lets a submit leave the frame, which is a write the port never saw'
1014
+ : ' — the mount is allow-scripts and nothing else, because every token is authority the port already carries safely'));
1015
+ // The CSP, which is the other half: the sandbox says what the
1016
+ // browser grants the document, this says where its code and its
1017
+ // resources may come from.
1018
+ const directives = new Map(mount.csp
1019
+ .split(';')
1020
+ .map((d) => d.trim())
1021
+ .filter(Boolean)
1022
+ .map((d) => {
1023
+ const [name, ...sources] = d.split(/\s+/);
1024
+ return [name.toLowerCase(), sources];
1025
+ }));
1026
+ const shown = (name) => `${name} ${(directives.get(name) ?? []).join(' ')}`.trim();
1027
+ must(directives.has('default-src'), `the frame is served under \`${mount.csp}\` — with no default-src there is no floor, and every ` +
1028
+ `resource kind nobody thought to name is open`);
1029
+ must(directives.get('script-src')?.join(' ') === "'self'", `the frame is served under \`${shown('script-src')}\` — 'self' and nothing else: an inline ` +
1030
+ `<script> is the first thing a frame document reaches for (it is refused silently), and a script ` +
1031
+ `from anywhere else is code the package did not ship`);
1032
+ must(directives.get('form-action')?.join(' ') === "'none'", `the frame is served under \`${shown('form-action')}\` — a frame fires actions through the port it ` +
1033
+ `was handed; a form that can submit is a second door`);
1034
+ // A source a frame may name: a keyword, or one of the schemes that
1035
+ // resolve inside the document. Anything else is somewhere else —
1036
+ // an origin, a bare host, a wildcard.
1037
+ const local = (src) => /^('.*'|data:|blob:|mediastream:|filesystem:)$/.test(src);
1038
+ for (const [name, sources] of directives) {
1039
+ // `connect-src` is the one directive that names other origins,
1040
+ // and only the hosts the package declared and an administrator
1041
+ // left granted — the same grant `ctx.fetch` is metered by. The
1042
+ // reporting directives take a URL by definition.
1043
+ if (name === 'connect-src' || name === 'report-uri' || name === 'report-to')
1044
+ continue;
1045
+ const off = sources.filter((src) => !local(src));
1046
+ must(off.length === 0, `\`${name}\` names ${off.join(', ')} — a frame's resources come from the package's own files, ` +
1047
+ `or a surface becomes a beacon to whoever it fetches from`);
1048
+ must(!sources.includes("'unsafe-eval'"), `\`${name}\` allows 'unsafe-eval' — the boundary is what the document may run, and eval is ` +
1049
+ `every string it can reach`);
1050
+ must(name === 'style-src' || !sources.includes("'unsafe-inline'"), `\`${name}\` allows 'unsafe-inline' — an inline <style> is the frame's own business, an ` +
1051
+ `inline anything else is the rule the boundary is made of`);
1052
+ }
1053
+ // What the host will listen to from inside the frame. A frame
1054
+ // proposes and the host decides: it may name an action the session
1055
+ // already lists, and it writes nothing itself.
1056
+ if (!mount.accepts)
1057
+ report.skip('the host does not say which frame → host messages it answers (`FrameMount.accepts`), so ' +
1058
+ '"a frame fires actions and writes nothing" was judged only at the mount');
1059
+ else {
1060
+ must(mount.accepts.some((t) => t === 'invoke' || t === 'action'), `the host answers [${mount.accepts.join(', ')}] from a frame — a frame that cannot name an ` +
1061
+ `action can do nothing at all, and its surface is a picture of one`);
1062
+ const writes = mount.accepts.filter((t) => /^(commit|write|create-message|update-message|delete-message|save)$/.test(t));
1063
+ must(writes.length === 0, `the host answers ${writes.join(', ')} from a frame — a frame proposes and the host decides; ` +
1064
+ `the write belongs to the run the fired action starts`);
1065
+ }
1066
+ },
1067
+ },
1068
+ {
1069
+ id: 'C27',
1070
+ law: '01 §13',
1071
+ title: 'every verdict is heard at every door it declares',
1072
+ consequence: 'A person meets a different refusal depending on which door they came through — the fire says one thing, the write another, the client a third — and a rule fixed at one door stays broken at the rest. A door that re-derives a rule instead of quoting the verdict is where the next drift starts.',
1073
+ async check(host, fx, report) {
1074
+ // The law is about the host's DOORS, so the host's own doors are
1075
+ // what is judged: each entry drives the real door with the verdict's
1076
+ // failing input and answers what that door refused with. The kit
1077
+ // asking the verdict on the host's behalf would pass any host — the
1078
+ // verdict is the one function, and it agrees with itself.
1079
+ const registered = verdicts();
1080
+ must(registered.length > 0, 'no verdict is registered — nothing for a door to hear');
1081
+ if (!host.doors)
1082
+ return report.skip('the host supplies no `doors` seam — supply one entry per door it has (construction, ' +
1083
+ 'validate, publish, registry, run, fire, write, list), each driving that real door ' +
1084
+ 'with the verdict’s failing input, for the law to be judged');
1085
+ for (const v of registered) {
1086
+ // The verdict's own coherence first: a failing input that does not
1087
+ // fail would make every door below pass by refusing nothing.
1088
+ for (const door of v.doors) {
1089
+ const input = v.failing(door);
1090
+ const expected = v.judge(input);
1091
+ must(!expected.ok, `${v.id}: judge(failing('${door}')) answered ok — the input the kit feeds through the ` +
1092
+ `'${door}' door does not fail the verdict, so the door cannot be judged on it`);
1093
+ if (expected.ok)
1094
+ continue;
1095
+ const sentence = i18nText(expected.sentence, 'en');
1096
+ must(typeof sentence === 'string' && sentence.length > 0, `${v.id}: the sentence for '${door}' has no en text — a sentence is display text (R-20)`);
1097
+ const at = host.doors[door];
1098
+ if (!at) {
1099
+ report.skip(`${v.id} declares the '${door}' door and this host has none — not judged there`);
1100
+ continue;
1101
+ }
1102
+ const heard = await at(v.id, input);
1103
+ if (heard === undefined) {
1104
+ report.skip(`${v.id} at '${door}': this host's door does not hear it — not judged there`);
1105
+ continue;
1106
+ }
1107
+ must(heard !== null, `${v.id} at '${door}': the door did not refuse the verdict's failing input — the rule ` +
1108
+ `is not heard there (${v.law})`);
1109
+ must(typeof heard === 'string', `${v.id} at '${door}': the door answered with a ${typeof heard}, not the string a ` +
1110
+ `refusal's sentence is`);
1111
+ // Contained, not equal: a door may frame the sentence — a node key
1112
+ // before it, several findings under one heading, the fix after it
1113
+ // — but never reword it. A paraphrase fails here because its words
1114
+ // are not the verdict's.
1115
+ must(heard.includes(sentence), `${v.id} at '${door}': the door refused with other words than the verdict's — it ` +
1116
+ `re-derives the rule (${v.law}). Expected to hear: ${sentence} — heard: ${heard}`);
1117
+ }
1118
+ }
1119
+ },
1120
+ },
1121
+ {
1122
+ id: 'C28',
1123
+ law: 'PLAN-turn-order §B3, R33',
1124
+ title: 'every event a genre lists is caused by a write or is a declared root',
1125
+ consequence: 'A preset binds a pipeline to an event nothing ever fires: the slot looks filled, the pipeline is published, and it never runs. Nobody is told, because nothing failed.',
1126
+ async check(host, fx, report) {
1127
+ const shipped = await host.shipped?.();
1128
+ if (!shipped)
1129
+ return report.skip('the host declares no catalogue — supply `shipped()` (its genres and presets) for the genres’ ' +
1130
+ 'event surfaces to be judged');
1131
+ for (const g of shipped.genres)
1132
+ for (const f of uncausedGenreEvents(g))
1133
+ must(false, `${f.sentence}. Declare the write that causes it (causedBy), or drop it from the genre`);
1134
+ },
1135
+ },
1136
+ {
1137
+ id: 'C29',
1138
+ law: 'PLAN-turn-order §B3, §3.2',
1139
+ title: 'every loop in a genre’s event map passes through something with a termination policy',
1140
+ consequence: 'One event starts a loop — a reply completes, the completion recomputes the turn order, the turn order asks for the next reply — and nothing in it says when to stop. Runs pile up, a model is called without end, and the session never goes quiet.',
1141
+ async check(host, fx, report) {
1142
+ const shipped = await host.shipped?.();
1143
+ if (!host.eventMap || !shipped)
1144
+ return report.skip('the host supplies no `eventMap(genre)` seam or no `shipped()` catalogue — supply both (the map ' +
1145
+ 'it draws for each shipped genre, with each node’s termination policy) for loops to be judged');
1146
+ for (const g of shipped.genres) {
1147
+ const map = await host.eventMap(g.id);
1148
+ for (const f of unterminatedCycles(map, (id) => Object.hasOwn(map.terminations, id) ? map.terminations[id] : undefined))
1149
+ must(false, `genre '${g.id}': ${f.sentence}. Give a listener in the loop a cause rule and a cap, or dispatch ` +
1150
+ `the loop's events through the run caps`);
1151
+ }
1152
+ },
1153
+ },
1154
+ {
1155
+ id: 'C30',
1156
+ law: 'PLAN-sdk-1.0 §3.5, R23',
1157
+ title: 'a component is judged, mounted and mirrored the way the page runs it',
1158
+ consequence: 'A component that carries the renderer, starts its own worker or imports what the worker cannot resolve reaches a session and fails there; a host whose round trip drops a push or an invoke shows a widget that looks alive and does nothing; a remote that renders or edits differently from the native copy of the same widget is a second widget, and the cutover to it changes what people see.',
1159
+ async check(host, _fx, report) {
1160
+ const built = (await host.components?.()) ?? null;
1161
+ if (!built?.length)
1162
+ report.skip('the host lists no built components — supply `components()` for their modules to be judged');
1163
+ else
1164
+ for (const c of built)
1165
+ for (const advisory of judgeComponentModule(c.id, c.code))
1166
+ report.note(advisory);
1167
+ if (!host.mountComponent)
1168
+ report.skip('the host mounts no component for the kit — supply `mountComponent(code, sections)` for the round trip');
1169
+ else {
1170
+ const view = await host.mountComponent(COMPONENT_PROTOCOL_FIXTURE, {});
1171
+ try {
1172
+ await componentProtocolCase(view);
1173
+ }
1174
+ finally {
1175
+ await view.unmount();
1176
+ }
1177
+ }
1178
+ // The parity half judges a messages widget against its remote. A host
1179
+ // that lists its components and ships none based on core's messages
1180
+ // has no such pair: not applicable, said so, never faked with core's.
1181
+ const clones = (built ?? []).filter((c) => c.basedOn === 'messages').map((c) => `'${c.id}'`);
1182
+ if (!host.componentParity) {
1183
+ if (host.components && !clones.length)
1184
+ report.notApplicable("no component the host lists is based on core's messages widget, so there is no native/remote pair to mirror");
1185
+ else if (clones.length)
1186
+ report.skip(`${clones.join(', ')} ${clones.length === 1 ? 'is' : 'are'} based on core's messages widget and the host offers no native/remote pair — supply \`componentParity()\` for it to be judged against its remote`);
1187
+ else
1188
+ report.skip('the host offers no native/remote pair — supply `componentParity()` for its messages widget to be judged against its remote');
1189
+ }
1190
+ else {
1191
+ const { native, remote } = await host.componentParity();
1192
+ try {
1193
+ await componentParityCase(native, remote);
1194
+ }
1195
+ finally {
1196
+ await native.unmount();
1197
+ await remote.unmount();
1198
+ }
1199
+ }
1200
+ },
1201
+ },
1202
+ {
1203
+ id: 'C31',
1204
+ law: 'PLAN-sdk-1.0 §3.5, 20 §12',
1205
+ title: 'every built component mounts in a plugin’s box with nothing refused, no error, and unmounts cleanly',
1206
+ consequence: 'A widget installs, is placed on a layout, and shows an empty box: the page dropped what it placed outside the vocabulary, or it raised an error nobody reads — and the person who installed it is the first to find out.',
1207
+ async check(host, _fx, report) {
1208
+ const built = (await host.components?.()) ?? null;
1209
+ if (!built?.length)
1210
+ return report.skip('the host lists no built components — supply `components()` for each module to be mounted');
1211
+ if (!host.mountComponent)
1212
+ return report.skip('the host mounts no component for the kit — supply `mountComponent(code, sections, { grants, reads })` for each module to be mounted');
1213
+ const failed = [];
1214
+ for (const c of built) {
1215
+ try {
1216
+ const view = await host.mountComponent(c.code, c.sections ?? componentParitySections(), {
1217
+ ...(c.grants ? { grants: c.grants } : {}),
1218
+ ...(c.reads ? { reads: c.reads } : {}),
1219
+ });
1220
+ for (const n of await componentMountCase(c.id, view))
1221
+ report.note(n);
1222
+ }
1223
+ catch (e) {
1224
+ const m = e.message;
1225
+ failed.push(m.startsWith(`component '${c.id}'`) ? m : `component '${c.id}': it did not mount — ${m}`);
1226
+ }
1227
+ }
1228
+ must(!failed.length, failed.join('\n'));
1229
+ },
1230
+ },
1231
+ {
1232
+ id: 'C32',
1233
+ law: 'R28, R29, R53',
1234
+ title: 'every swap a package offers fits the node it stands in for',
1235
+ consequence: 'An admin enables the package and its option appears in the genre’s control; a person picks it and the turn order (or whatever the node decides) stops computing — the swap was seated with ports or settings the node never wires, and the run halts on the first recompute.',
1236
+ async check(host, _fx, report) {
1237
+ if (!host.swaps)
1238
+ return report.skip('the host lists no swaps — supply `swaps()` (a manifest’s: `swapsFromManifest`) for them to be fitted');
1239
+ if (!host.pinnedDefinition)
1240
+ return report.skip('the host supplies no `pinnedDefinition(spec, node)` — the kit cannot know what a swap stands in for without the host’s own spec');
1241
+ const swaps = await host.swaps();
1242
+ if (!swaps.length)
1243
+ return report.skip('the host lists no swaps to fit');
1244
+ const failed = [];
1245
+ for (const s of swaps) {
1246
+ const at = `swap '${s.definitionId}' onto '${s.spec}#${s.node}'`;
1247
+ if (!s.definition) {
1248
+ failed.push(`${at}: the package declares no definition '${s.definitionId}' — a package offers only its own (R29)`);
1249
+ continue;
1250
+ }
1251
+ const pinned = await host.pinnedDefinition(s.spec, s.node);
1252
+ if (!pinned) {
1253
+ failed.push(`${at}: this host seats nothing at '${s.node}' of '${s.spec}' — name the node the control swaps (read its strategyNode, never assume a key)`);
1254
+ continue;
1255
+ }
1256
+ const misfit = swapFitFinding(s.node, pinned, s.definition);
1257
+ if (misfit)
1258
+ failed.push(`${at}: ${misfit}`);
1259
+ }
1260
+ must(!failed.length, failed.join('\n'));
1261
+ },
1262
+ },
1263
+ {
1264
+ id: 'C33',
1265
+ law: 'F11, 13 §7h (binding probes B1–B5)',
1266
+ title: 'every definition a swap seats passes the binding probes',
1267
+ consequence: 'A strategy a person picks returns a bare value (recorded as an error), reads the clock or Math.random (a turn order nobody can replay or dispute), hangs (the recompute never finishes and the plugin is marked unhealthy), or ignores the abort an admin sends.',
1268
+ async check(host, _fx, report) {
1269
+ if (!host.swaps)
1270
+ return report.skip('the host lists no swaps — supply `swaps()` for their definitions to be probed');
1271
+ if (!host.nodeHandler)
1272
+ return report.skip('the host supplies no `nodeHandler(definitionId)` — supply the handler it would call (a bundle export)');
1273
+ const seen = new Set();
1274
+ const failed = [];
1275
+ for (const s of await host.swaps()) {
1276
+ if (!s.definition || seen.has(s.definitionId))
1277
+ continue;
1278
+ seen.add(s.definitionId);
1279
+ const d = s.definition;
1280
+ const handler = await host.nodeHandler(d.id);
1281
+ if (typeof handler !== 'function') {
1282
+ failed.push(`'${d.id}': the host has no handler for it — the bundle exports none under the name the manifest gives`);
1283
+ continue;
1284
+ }
1285
+ const given = host.probeInput?.(d);
1286
+ const sample = given ? { input: given } : probeSampleFor(d);
1287
+ if ('missing' in sample) {
1288
+ report.skip(`'${d.id}' reads shapes the kit has no sample for (${sample.missing.join(', ')}) — supply \`probeInput(d)\``);
1289
+ continue;
1290
+ }
1291
+ for (const r of await probeBinding(handler, d, probeCtxFor(d.kind, sample.input)))
1292
+ if (!r.pass)
1293
+ failed.push(`'${d.id}' ${r.id} (${r.title}): ${r.error}`);
1294
+ }
1295
+ must(!failed.length, failed.join('\n'));
1296
+ },
1297
+ },
1298
+ ];
1299
+ /**
1300
+ * The requirements a package's own declarations can fail, judged over its
1301
+ * BUILT artifact with no fixtures: what it ships (C28, C29), its component
1302
+ * modules (C30, C31), and its swaps (C32, C33). The rest judge a host's
1303
+ * executor, not a package.
1304
+ * @experimental — held back from the frozen surface until the host seams (`HostUnderTest`) settle
1305
+ */
1306
+ export const PACKAGE_REQUIREMENTS = ['C28', 'C29', 'C30', 'C31', 'C32', 'C33'];
1307
+ /**
1308
+ * `conform` over `PACKAGE_REQUIREMENTS` (or the subset `only` names) — a
1309
+ * plugin's test, carrying its artifact on the SDK's executor and harness.
1310
+ * These cases read no fixtures.
1311
+ * @experimental — held back from the frozen surface until the host seams (`HostUnderTest`) settle
1312
+ */
1313
+ export function conformPackage(host, only = PACKAGE_REQUIREMENTS) {
1314
+ const outside = only.filter((id) => !PACKAGE_REQUIREMENTS.includes(id));
1315
+ if (outside.length)
1316
+ throw new Error(`${outside.join(', ')} judge a host's executor and need fixtures — run conform(host, fixtures, { only })`);
1317
+ return conform(host, {}, { only });
1318
+ }
1319
+ /** @experimental */
1320
+ export async function conform(host, fx, opts = {}) {
1321
+ const unknown = (opts.only ?? []).filter((id) => !REQUIREMENTS.some((r) => r.id === id));
1322
+ if (unknown.length)
1323
+ throw new Error(`the kit has no requirement ${unknown.join(', ')}`);
1324
+ const out = [];
1325
+ for (const r of REQUIREMENTS) {
1326
+ if (opts.only && !opts.only.includes(r.id))
1327
+ continue;
1328
+ const skipped = [];
1329
+ const notes = [];
1330
+ const notApplicable = [];
1331
+ const report = {
1332
+ skip: (why) => {
1333
+ skipped.push(why);
1334
+ },
1335
+ note: (what) => {
1336
+ notes.push(what);
1337
+ },
1338
+ notApplicable: (why) => {
1339
+ notApplicable.push(why);
1340
+ },
1341
+ };
1342
+ try {
1343
+ await r.check(host, fx, report);
1344
+ out.push({
1345
+ id: r.id,
1346
+ law: r.law,
1347
+ title: r.title,
1348
+ pass: true,
1349
+ ...(skipped.length ? { skipped } : {}),
1350
+ ...(notes.length ? { notes } : {}),
1351
+ ...(notApplicable.length ? { notApplicable } : {}),
1352
+ });
1353
+ }
1354
+ catch (e) {
1355
+ out.push({
1356
+ id: r.id,
1357
+ law: r.law,
1358
+ title: r.title,
1359
+ pass: false,
1360
+ error: e.message,
1361
+ consequence: r.consequence,
1362
+ ...(skipped.length ? { skipped } : {}),
1363
+ ...(notes.length ? { notes } : {}),
1364
+ ...(notApplicable.length ? { notApplicable } : {}),
1365
+ });
1366
+ }
1367
+ }
1368
+ return out;
1369
+ }
1370
+ /** @experimental — held back from the frozen surface until the host seams (`HostUnderTest`) settle */
1371
+ export function renderConformance(results) {
1372
+ const failed = results.filter((r) => !r.pass);
1373
+ const lines = [
1374
+ `conformance: ${results.length - failed.length}/${results.length} passing`,
1375
+ ...results.flatMap((r) => [
1376
+ ` ${r.pass ? '✓' : '✗'} ${r.id.padEnd(4)} [${r.law}] ${r.title}`,
1377
+ ...(r.skipped ?? []).map((why) => ` ~ not judged: ${why}`),
1378
+ ...(r.notApplicable ?? []).map((why) => ` — not applicable: ${why}`),
1379
+ ...(r.notes ?? []).map((what) => ` · note: ${what}`),
1380
+ ]),
1381
+ ];
1382
+ for (const r of failed) {
1383
+ lines.push('', `✗ ${r.id} — ${r.error}`, ` what this breaks: ${r.consequence}`);
1384
+ }
1385
+ return lines.join('\n');
1386
+ }
1387
+ //# sourceMappingURL=index.js.map