@githolon/dsl 0.2.3 → 0.4.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.
@@ -82,6 +82,11 @@ import {
82
82
  type Mod,
83
83
  } from "./build_package.js";
84
84
  import { collectEngineRouting } from "./engine_entry.js";
85
+ import { resolveWorkspaceTypes, type WorkspaceTypeDecl } from "./workspace_type.js";
86
+ import { canonicalTaxonomyFragment, validateWorkspaceTaxonomyAndRoutes } from "./workspace_routing.js";
87
+ import { shardingLawModule, type ShardingLawSpec } from "./workspace_sharding.js";
88
+ import type { AnyExtremum } from "./extremum.js";
89
+ import type { WorkspaceInvariantDecl } from "./framework/workspace_invariant.js";
85
90
  import {
86
91
  emitLayeredDomain,
87
92
  flattenLayeredUsd,
@@ -102,9 +107,15 @@ interface DomainConfig {
102
107
  readonly queries?: readonly string[];
103
108
  readonly counts?: readonly string[];
104
109
  readonly sums?: readonly string[];
110
+ /** Maintained MIN/MAX reads (#47) — export names, config-named like sums. */
111
+ readonly mins?: readonly string[];
112
+ readonly maxes?: readonly string[];
105
113
  readonly spatials?: readonly string[];
106
114
  readonly deriveds?: readonly string[];
107
115
  readonly combineds?: readonly string[];
116
+ readonly workspaceTypes?: readonly string[];
117
+ /** Export-name escape hatch for workspace invariants (auto-discovered by shape otherwise). */
118
+ readonly workspaceInvariants?: readonly string[];
108
119
  readonly impureCapabilities?: readonly string[];
109
120
  readonly extraAggregates?: readonly string[];
110
121
  readonly readModelAggregates?: readonly string[];
@@ -176,6 +187,14 @@ function isQueryDecl(v: unknown): v is QueryDecl {
176
187
  );
177
188
  }
178
189
 
190
+ function isWorkspaceInvariantDecl(v: unknown): v is WorkspaceInvariantDecl {
191
+ return (
192
+ !!v &&
193
+ typeof v === "object" &&
194
+ (v as { __isWorkspaceInvariant?: unknown }).__isWorkspaceInvariant === true
195
+ );
196
+ }
197
+
179
198
  function isSpatialDecl(v: unknown): v is SpatialDecl {
180
199
  return (
181
200
  !!v &&
@@ -223,7 +242,9 @@ function isCountDecl(v: unknown): v is AnyCount {
223
242
  typeof o.on !== "string" && // spatial
224
243
  typeof o.fn !== "function" && // derived/combined
225
244
  !Array.isArray(o.key) && // query
226
- !("field" in o) && // sum / extremum
245
+ !("field" in o) && // extremum (wire-descriptor shape)
246
+ !("valueField" in o) && // extremum (the ExtremumDecl/Extremum-builder mark — never a count)
247
+ !("sumField" in o) && // sum (the SumDecl/Sum-builder mark — never a count)
227
248
  !("orderBy" in o) && // ordered read
228
249
  !("_existsMarker" in o) && // exists
229
250
  typeof o.refField !== "string" && // combined
@@ -233,6 +254,28 @@ function isCountDecl(v: unknown): v is AnyCount {
233
254
  );
234
255
  }
235
256
 
257
+ /**
258
+ * Scan merged exports for `workspaceType(...)` decls (sharding §10 slice 1) by the
259
+ * `__isWorkspaceType` brand — individual exports AND exported arrays. Dedupe is BY
260
+ * REFERENCE here and BY ID (divergence-refused) in `resolveWorkspaceTypes`; the
261
+ * generic `discover()`'s JSON dedupe key is unusable for these decls (they carry
262
+ * aggregate handles whose zod schemas do not stringify).
263
+ */
264
+ function discoverWorkspaceTypes(merged: Mod): WorkspaceTypeDecl[] {
265
+ const out: WorkspaceTypeDecl[] = [];
266
+ const isDecl = (v: unknown): v is WorkspaceTypeDecl =>
267
+ !!v && typeof v === "object" &&
268
+ (v as { __isWorkspaceType?: unknown }).__isWorkspaceType === true;
269
+ const push = (v: WorkspaceTypeDecl) => {
270
+ if (!out.includes(v)) out.push(v);
271
+ };
272
+ for (const v of Object.values(merged)) {
273
+ if (isDecl(v)) push(v);
274
+ else if (Array.isArray(v)) for (const el of v) if (isDecl(el)) push(el);
275
+ }
276
+ return out;
277
+ }
278
+
236
279
  /** Scan merged exports for decls matching `match`: individual exports AND exported arrays. */
237
280
  function discover<T>(merged: Mod, match: (v: unknown) => v is T): T[] {
238
281
  const seen = new Set<string>();
@@ -421,6 +464,7 @@ async function main(): Promise<void> {
421
464
  const eagerLump = process.env.NOMOS_LUMP_BOOT === "eager";
422
465
  const entryImports: string[] = [];
423
466
  const entryDomains: string[] = [];
467
+ const entryMintInstalls: string[] = []; // route-tagged in-plan mints (taxonomy packages only)
424
468
  const routingInput: Record<string, Mod[]> = {};
425
469
  const domainModules: DomainModule[] = [];
426
470
  const layered = layeredFlag || cfg.layered === true;
@@ -446,11 +490,143 @@ async function main(): Promise<void> {
446
490
  sourceExprs.push(`() => require(${JSON.stringify(abs)})`);
447
491
  }
448
492
  }
449
- entryDomains.push(` ${JSON.stringify(d.key)}: [${sourceExprs.join(", ")}],`);
450
- routingInput[d.key] = mods;
451
-
452
493
  let merged: Mod = {};
453
494
  for (const m of mods) merged = { ...merged, ...m };
495
+ let shardingSums: AnySum[] = [];
496
+ let shardingMins: AnyExtremum[] = [];
497
+ let shardingMaxes: AnyExtremum[] = [];
498
+ let shardingModForDomain: Mod | undefined;
499
+ let shardingLazyExpr: string | undefined;
500
+
501
+ // ── THE DERIVED PLACEMENT LAW (sharding slice 2): a taxonomy with PACKED axes
502
+ // appends the framework placement module (`workspace_sharding.ts`) to this
503
+ // domain — in the composed manifests (hash-bearing law) AND the generated
504
+ // entry (the plan ships in the lump). Taxonomy-free domains append NOTHING:
505
+ // their package bytes / hashes do not move (the slice-1 stability law). ──
506
+ const workspaceTypes = [
507
+ ...discoverWorkspaceTypes(merged),
508
+ ...resolveNamed<WorkspaceTypeDecl>(merged, d.workspaceTypes, "workspaceTypes"),
509
+ ];
510
+ if (workspaceTypes.length > 0) {
511
+ let spec: ShardingLawSpec | undefined;
512
+ try {
513
+ const types = resolveWorkspaceTypes(workspaceTypes, d.name ?? d.key);
514
+ const axes = [...types.values()]
515
+ .filter((t) => t.mode === "packed")
516
+ .map((p) => {
517
+ const parent = [...types.values()].find((t) => t.childIds.includes(p.id));
518
+ // SLICE-2 STATIC MAP: shard count = the parent's .pool(n), default 1 (the
519
+ // degenerate coordinator+sole-shard layout, §6's no-flag-day migration).
520
+ return { axisType: p.id, axisRoot: p.rootId, shardCount: parent?.poolSize ?? 1 };
521
+ })
522
+ .sort((a, b) => (a.axisType < b.axisType ? -1 : 1));
523
+ if (axes.length > 0) spec = { axes };
524
+ } catch (e) {
525
+ fail((e as Error).message);
526
+ }
527
+ if (spec !== undefined) {
528
+ // SLICE 3a (#41): derive the directive ROUTES over the TENANT modules (the SAME
529
+ // derivation the canonical manifest records) and feed them into the placement
530
+ // law, so it emits the per-directive HOMING INVARIANT — the wrong-home gate
531
+ // moves from the edge bailiff into THE CHAIN GATE ITSELF.
532
+ // SLICE 3 (#42): also feed the PACKED HOMING TABLE (aggregate → axis) — the
533
+ // engine-side route-tag mint wrapper tags in-plan `create(Agg)` mints of
534
+ // packed-homed aggregates with the dispatched intent's home tag (§4).
535
+ try {
536
+ const fragment = canonicalTaxonomyFragment({
537
+ name: d.name ?? d.key,
538
+ aggregates: aggregatesOf(merged),
539
+ directives: directivesOf(merged),
540
+ workspaceTypes,
541
+ });
542
+ if (fragment.routes !== undefined && fragment.routes.length > 0) {
543
+ spec = { ...spec, routes: fragment.routes };
544
+ }
545
+ const packedAxes = new Set(spec.axes.map((a) => a.axisType));
546
+ const packedHomes = Object.fromEntries(
547
+ Object.entries(fragment.homes ?? {}).filter(([, home]) => packedAxes.has(home)),
548
+ );
549
+ if (Object.keys(packedHomes).length > 0) spec = { ...spec, homes: packedHomes };
550
+ } catch (e) {
551
+ fail((e as Error).message);
552
+ }
553
+ const shardingMod = shardingLawModule(spec) as Mod;
554
+ mods.push(shardingMod);
555
+ merged = { ...merged, ...shardingMod };
556
+ shardingModForDomain = shardingMod;
557
+ // The derived sharding law's MAINTAINED SUMS (`nomosEstateSummary` — the §5.1
558
+ // estate total over subtotal rows) must reach the read manifest + identity:
559
+ // sums are config-named (never auto-discovered — hash stability for existing
560
+ // packages), so the appended module's sums thread through explicitly here.
561
+ shardingSums = Object.values(shardingMod).filter(
562
+ (v): v is AnySum =>
563
+ !!v && typeof v === "object" &&
564
+ typeof (v as { id?: unknown }).id === "string" &&
565
+ typeof (v as { of?: unknown }).of === "string" &&
566
+ typeof (v as { sumField?: unknown }).sumField === "string",
567
+ );
568
+ // SLICE 8: the derived sharding law's MAINTAINED EXTREMUMS — the estate
569
+ // min/max over subtotal rows (`nomosEstateExtremumMin/Max`, extremize over
570
+ // per-shard committed values) — thread through the same explicit lane.
571
+ const shardingExtrema = (kind: "min" | "max"): AnyExtremum[] =>
572
+ Object.values(shardingMod).filter(
573
+ (v): v is AnyExtremum =>
574
+ !!v && typeof v === "object" &&
575
+ typeof (v as { id?: unknown }).id === "string" &&
576
+ typeof (v as { of?: unknown }).of === "string" &&
577
+ typeof (v as { valueField?: unknown }).valueField === "string" &&
578
+ (v as { kind?: unknown }).kind === kind,
579
+ );
580
+ shardingMins = shardingExtrema("min");
581
+ shardingMaxes = shardingExtrema("max");
582
+ const specJson = JSON.stringify(spec);
583
+ if (eagerLump) {
584
+ if (!entryImports.some((l) => l.includes("workspace-sharding"))) {
585
+ entryImports.push(
586
+ `import { shardingLawModule as __nomosShardingLaw, installRouteTaggedMint as __nomosInstallMint } from "@githolon/dsl/workspace-sharding";`,
587
+ );
588
+ }
589
+ sourceExprs.push(`__nomosShardingLaw(${specJson})`);
590
+ } else {
591
+ shardingLazyExpr = `() => (require("@githolon/dsl/workspace-sharding") as any).shardingLawModule(${specJson})`;
592
+ sourceExprs.push(shardingLazyExpr);
593
+ }
594
+ // ROUTE-TAGGED IN-PLAN MINTS (§4, slice 3): installed AFTER registerEngine at
595
+ // the lump's top level — pre-freeze, taxonomy packages only (a taxonomy-free
596
+ // lump never imports the module: the slice-1 hash-stability law).
597
+ entryMintInstalls.push(
598
+ eagerLump
599
+ ? `__nomosInstallMint(${specJson});`
600
+ : `(require("@githolon/dsl/workspace-sharding") as any).installRouteTaggedMint(${specJson});`,
601
+ );
602
+ }
603
+ }
604
+
605
+ entryDomains.push(` ${JSON.stringify(d.key)}: [${sourceExprs.join(", ")}],`);
606
+ routingInput[d.key] = mods;
607
+ // ── THE AUX INVARIANT-ROUTING KEY (#47, sharding slice 7 — the invariant-gate
608
+ // flame pass): in a LAZY lump, the derived sharding law registers a SECOND
609
+ // time under its own domain key, and the ROUTING table points the sharding
610
+ // workspace-invariant ids at THAT key only. A per-write homing-invariant
611
+ // dispatch (`workspaceInvariantReads`/`workspaceInvariant`) then forces ONLY
612
+ // the small framework module — never the tenant domain's whole zod/module
613
+ // graph (the measured ~30 ms-per-dispatch floor on co2 estate_structures).
614
+ // Directive dispatch is untouched (the sharding directives stay registered
615
+ // under `d.key` — the wire domain every host lane already speaks); the
616
+ // canonical manifests are untouched (identity hashes do not move); eager
617
+ // lumps are untouched (no routing table — the pre-#34 equivalence shape);
618
+ // taxonomy-free packages emit NOTHING here (the slice-1 byte-stability law).
619
+ if (shardingModForDomain !== undefined && shardingLazyExpr !== undefined && !eagerLump) {
620
+ const auxKey = `${d.key}/nomos-sharding`;
621
+ if (cfg.domains.some((x) => x.key === auxKey) || routingInput[auxKey] !== undefined) {
622
+ fail(
623
+ `domain key '${auxKey}' is reserved for the derived sharding law's invariant routing — rename the domain`,
624
+ );
625
+ }
626
+ entryDomains.push(` ${JSON.stringify(auxKey)}: [${shardingLazyExpr}],`);
627
+ routingInput[d.key] = mods.filter((m) => m !== shardingModForDomain);
628
+ routingInput[auxKey] = [shardingModForDomain];
629
+ }
454
630
 
455
631
  const queries = [
456
632
  ...discover<QueryDecl>(merged, isQueryDecl),
@@ -472,7 +648,13 @@ async function main(): Promise<void> {
472
648
  ...discover<CombinedDecl>(merged, isCombinedDecl),
473
649
  ...resolveNamed<CombinedDecl>(merged, d.combineds, "combineds"),
474
650
  ];
475
- const sums = resolveNamed<AnySum>(merged, d.sums, "sums");
651
+ const workspaceInvariants = [
652
+ ...discover<WorkspaceInvariantDecl>(merged, isWorkspaceInvariantDecl),
653
+ ...resolveNamed<WorkspaceInvariantDecl>(merged, d.workspaceInvariants, "workspaceInvariants"),
654
+ ];
655
+ const sums = [...resolveNamed<AnySum>(merged, d.sums, "sums"), ...shardingSums];
656
+ const mins = [...resolveNamed<AnyExtremum>(merged, d.mins, "mins"), ...shardingMins];
657
+ const maxes = [...resolveNamed<AnyExtremum>(merged, d.maxes, "maxes"), ...shardingMaxes];
476
658
  const impureCapabilities = resolveNamed<ImpureCapabilityDecl>(
477
659
  merged,
478
660
  d.impureCapabilities,
@@ -500,6 +682,10 @@ async function main(): Promise<void> {
500
682
  ...(combineds.length > 0 ? { combineds } : {}),
501
683
  ...(impureCapabilities.length > 0 ? { impureCapabilities } : {}),
502
684
  ...(sums.length > 0 ? { sums } : {}),
685
+ ...(mins.length > 0 ? { mins } : {}),
686
+ ...(maxes.length > 0 ? { maxes } : {}),
687
+ ...(workspaceTypes.length > 0 ? { workspaceTypes } : {}),
688
+ ...(workspaceInvariants.length > 0 ? { workspaceInvariants } : {}),
503
689
  ...(spatials.length > 0 ? { spatials } : {}),
504
690
  ...(d.dartImports !== undefined && d.dartImports.length > 0
505
691
  ? { dartImports: d.dartImports }
@@ -511,6 +697,67 @@ async function main(): Promise<void> {
511
697
  }),
512
698
  );
513
699
 
700
+ // ── THE TAXONOMY GATE (sharding §10 slice 1 + slice 2; fail-closed, BEFORE
701
+ // identity emission): resolve the declared workspace types, run the homing
702
+ // walk (nearest packed axis via t.ref chains), the directive cross-home
703
+ // check, AND the slice-2 route derivation (per-directive home keys). A
704
+ // no-path / ambiguous / cross-home / unroutable law is a NAMED COMPILE
705
+ // ERROR here — never a domain silently recorded as identity-excluded.
706
+ const composed = domainModules[domainModules.length - 1]!;
707
+ if (composed.workspaceTypes !== undefined && composed.workspaceTypes.length > 0) {
708
+ try {
709
+ validateWorkspaceTaxonomyAndRoutes(composed);
710
+ } catch (e) {
711
+ fail((e as Error).message);
712
+ }
713
+ }
714
+ // ── THE SCOPE GATE (sharding §5, slice 3; fail-closed): every `scoped(read, Ws)`
715
+ // must name a DECLARED, DEDICATED workspace type of THIS domain's taxonomy
716
+ // (the coordinator type that holds the subtotal rows). A scoped read in a
717
+ // taxonomy-free domain, or scoped to a packed type, is a NAMED compile error.
718
+ {
719
+ const declaredScopes = new Map<string, string>(); // type id -> mode
720
+ const globalAggIds = new Set<string>(); // §5.4 — replicated reference data
721
+ if (workspaceTypes.length > 0) {
722
+ try {
723
+ for (const [id, ty] of resolveWorkspaceTypes(workspaceTypes, d.name ?? d.key)) {
724
+ declaredScopes.set(id, ty.mode);
725
+ for (const g of ty.globalIds) globalAggIds.add(g);
726
+ }
727
+ } catch { /* already failed above */ }
728
+ }
729
+ for (const read of [...(composed.counts ?? []), ...(composed.sums ?? []), ...(composed.mins ?? []), ...(composed.maxes ?? [])]) {
730
+ const scope = (read as { scope?: unknown }).scope;
731
+ if (scope === undefined) continue;
732
+ const id = (read as { id?: unknown }).id;
733
+ if (typeof scope !== "string" || !declaredScopes.has(scope)) {
734
+ fail(
735
+ `domain '${d.key}': read '${String(id)}' is scoped to '${String(scope)}', which is not a ` +
736
+ `declared workspace type of this domain — declare the taxonomy (workspaceType(...)) ` +
737
+ `in the same domain, or drop the scope.`,
738
+ );
739
+ }
740
+ if (declaredScopes.get(scope) !== "dedicated") {
741
+ fail(
742
+ `domain '${d.key}': read '${String(id)}' is scoped to PACKED type '${scope}' — estate ` +
743
+ `scope must name the DEDICATED coordinator type (the holon that holds the subtotal rows).`,
744
+ );
745
+ }
746
+ // §5.4 (slice 4): a `.global(...)` aggregate is coordinator-homed reference
747
+ // data REPLICATED to every shard — an estate-scoped tally over it would sum
748
+ // the SAME rows once per shard. Its home-scope read on the coordinator IS
749
+ // the estate value already.
750
+ const ofType = (read as { of?: unknown }).of;
751
+ if (typeof ofType === "string" && globalAggIds.has(ofType)) {
752
+ fail(
753
+ `domain '${d.key}': read '${String(id)}' is scoped over GLOBAL aggregate '${ofType}' — ` +
754
+ `global reference data is replicated to every shard, so an estate-scoped tally would ` +
755
+ `count it once per shard. Drop the scope: the coordinator's home-scope read IS the estate value.`,
756
+ );
757
+ }
758
+ }
759
+ }
760
+
514
761
  // ── opt-in: ONE USD LAYER PER MODULE (Φ applied per module, not once over the
515
762
  // composed fold) — the layered emission `usd_layers.ts` proves flattens back
516
763
  // to the EXACT canonical IR (asserted below, fail-closed). Per-module decls
@@ -645,6 +892,10 @@ async function main(): Promise<void> {
645
892
  ...(eagerLump ? [] : [` routing: ${JSON.stringify(routing)},`]),
646
893
  ...(zodSeedNames.length > 0 ? [` seeds: [${zodSeedNames.join(", ")}],`] : []),
647
894
  `});`,
895
+ // ROUTE-TAGGED IN-PLAN MINTS (sharding §4, slice 3): wraps globalThis.plan +
896
+ // globalThis.nomos.mint at top-level eval — pre-freeze, after registerEngine's
897
+ // own assignments. Empty (and therefore byte-absent) for taxonomy-free packages.
898
+ ...entryMintInstalls,
648
899
  ``,
649
900
  ].join("\n");
650
901
  const entryPath = path.join(outDir, ".nomos_entry.ts");
@@ -882,6 +1133,13 @@ async function main(): Promise<void> {
882
1133
  console.log(` identity ${rel(manifestsPath)} (${Object.keys(identity.manifests).length} domain(s)${identity.excluded.length ? `, ${identity.excluded.length} EXCLUDED (palette gap)` : ""})`);
883
1134
  for (const [dom, h] of Object.entries(identity.hashes)) console.log(` ${dom.padEnd(20)} ${h}`);
884
1135
  for (const ex of identity.excluded) console.log(` EXCLUDED ${ex.domain}: ${ex.reason}`);
1136
+ for (const m of domainModules) {
1137
+ if (m.workspaceTypes !== undefined && m.workspaceTypes.length > 0) {
1138
+ console.log(
1139
+ ` taxonomy ${m.domain ?? m.name}: ${m.workspaceTypes.length} workspace type(s) — homing derived from t.ref chains; birth lanes typed in the client`,
1140
+ );
1141
+ }
1142
+ }
885
1143
  console.log(` client ${rel(clientPath)} (typed TS client — payloads, read models, query accessors)`);
886
1144
  if (proofPath !== undefined) {
887
1145
  console.log(` proof ${rel(proofPath)} (a runnable e2e GENERATED from your law — run: githolon proof)`);
@@ -59,6 +59,7 @@ import type { WireEvent, WireHlc } from "./wire.js";
59
59
  import type { DerivedDecl } from "./derived.js";
60
60
  import type { CombinedDecl } from "./combined.js";
61
61
  import type { InvariantBody, InvariantEvidence, InvariantVerdict } from "./relation.js";
62
+ import type { WorkspaceInvariantDecl } from "./framework/workspace_invariant.js";
62
63
  import type { QueryRow } from "./report.js";
63
64
 
64
65
  /** One bundled domain module: a bag of named exports the entry scans by SHAPE. */
@@ -91,6 +92,8 @@ export interface EngineRouting {
91
92
  readonly combinedOf?: Record<string, readonly string[]>;
92
93
  readonly aggregateInvariantOf?: Record<string, readonly string[]>;
93
94
  readonly relationOf?: Record<string, readonly string[]>;
95
+ /** workspace-invariant id → declaring domain keys (#266 — the gate's reads/assert dispatches). */
96
+ readonly workspaceInvariantOf?: Record<string, readonly string[]>;
94
97
  }
95
98
 
96
99
  /** The one declarative input: dispatch key → ORDERED module list (later wins). */
@@ -216,6 +219,8 @@ interface DomainSlice {
216
219
  invariants: Map<string, InvariantBody>;
217
220
  /** aggregate type → aggregate-invariant body. */
218
221
  aggInvariants: Map<string, AggregateInvariantFn>;
222
+ /** workspace-invariant id → its declaration (#266 — `reads`/`assert` bodies ship HERE). */
223
+ wsInvariants: Map<string, WorkspaceInvariantDecl>;
219
224
  }
220
225
 
221
226
  /** Build one domain's slice from its merged module exports (the original scans). */
@@ -288,7 +293,28 @@ function buildDomainSlice(mod: DomainModuleExports): DomainSlice {
288
293
  }
289
294
  }
290
295
 
291
- return { registry, deriveds, combineds, invariants, aggInvariants };
296
+ // ── workspace-invariant id declaration — from the SAME exports (#266, by shape) ──
297
+ const wsInvariants = new Map<string, WorkspaceInvariantDecl>();
298
+ for (const v of Object.values(mod)) {
299
+ if (
300
+ v &&
301
+ typeof v === "object" &&
302
+ (v as { __isWorkspaceInvariant?: boolean }).__isWorkspaceInvariant === true
303
+ ) {
304
+ const w = v as WorkspaceInvariantDecl;
305
+ if (typeof w.reads !== "function" || typeof w.assert !== "function") {
306
+ // A declaration MUST ship both executable halves — fail-closed at boot, exactly
307
+ // like a relation/aggregate invariant with a missing body.
308
+ throw new Error(
309
+ `engine bundle: workspace invariant "${w.id}" declares no executable reads/assert ` +
310
+ `body — the gate would have nothing to evaluate (docs/workspace_invariant.md).`,
311
+ );
312
+ }
313
+ wsInvariants.set(w.id, w);
314
+ }
315
+ }
316
+
317
+ return { registry, deriveds, combineds, invariants, aggInvariants, wsInvariants };
292
318
  }
293
319
 
294
320
  /**
@@ -306,6 +332,7 @@ export function collectEngineRouting(
306
332
  const combinedOf: Record<string, string[]> = {};
307
333
  const aggregateInvariantOf: Record<string, string[]> = {};
308
334
  const relationOf: Record<string, string[]> = {};
335
+ const workspaceInvariantOf: Record<string, string[]> = {};
309
336
  const add = (map: Record<string, string[]>, key: string, domainName: string) => {
310
337
  const list = map[key] ?? (map[key] = []);
311
338
  if (!list.includes(domainName)) list.push(domainName);
@@ -316,8 +343,9 @@ export function collectEngineRouting(
316
343
  for (const type of slice.combineds.keys()) add(combinedOf, type, domainName);
317
344
  for (const type of slice.aggInvariants.keys()) add(aggregateInvariantOf, type, domainName);
318
345
  for (const relationId of slice.invariants.keys()) add(relationOf, relationId, domainName);
346
+ for (const wsInvariantId of slice.wsInvariants.keys()) add(workspaceInvariantOf, wsInvariantId, domainName);
319
347
  }
320
- return { derivedOf, combinedOf, aggregateInvariantOf, relationOf };
348
+ return { derivedOf, combinedOf, aggregateInvariantOf, relationOf, workspaceInvariantOf };
321
349
  }
322
350
 
323
351
  /**
@@ -458,6 +486,80 @@ export function registerEngine(config: EngineEntryConfig): RegisteredEngine {
458
486
  return JSON.stringify(verdict);
459
487
  }
460
488
 
489
+ /** Every domain key whose merged module declares a given workspace invariant (routed when lazy). */
490
+ function wsInvariantDomains(id?: string): readonly string[] {
491
+ if (routing.workspaceInvariantOf !== undefined && id !== undefined) {
492
+ return routing.workspaceInvariantOf[id] ?? [];
493
+ }
494
+ return domainNames;
495
+ }
496
+
497
+ /** Resolve ONE declared workspace invariant by id (later domain wins — the one fold order). */
498
+ function wsInvariantById(id: string): WorkspaceInvariantDecl | undefined {
499
+ let found: WorkspaceInvariantDecl | undefined;
500
+ for (const domainName of wsInvariantDomains(id)) {
501
+ const hit = sliceOf(domainName)?.wsInvariants.get(id);
502
+ if (hit !== undefined) found = hit;
503
+ }
504
+ return found;
505
+ }
506
+
507
+ // ── the three WORKSPACE-INVARIANT dispatches (#266 — wire shapes are the gate oracle's
508
+ // contract, EXACT: see admission-peer EngineWorkspaceInvariant + plan_workspace_invariant*) ──
509
+
510
+ /** `{workspaceInvariantList:{}}` → the DECLARED set `[{id,on},…]` sorted by id (discovery). */
511
+ function planWorkspaceInvariantList(): string {
512
+ const declared = new Map<string, { id: string; on: string }>();
513
+ const domains =
514
+ routing.workspaceInvariantOf !== undefined
515
+ ? [...new Set(Object.values(routing.workspaceInvariantOf).flat())]
516
+ : domainNames;
517
+ for (const domainName of domains) {
518
+ const slice = sliceOf(domainName);
519
+ if (slice === undefined) continue;
520
+ for (const w of slice.wsInvariants.values()) declared.set(w.id, { id: w.id, on: w.on });
521
+ }
522
+ return JSON.stringify([...declared.values()].sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0)));
523
+ }
524
+
525
+ /** `{workspaceInvariantReads:{id}, payload}` → the bounded ref-set `[{name,aggregate,id},…]`. */
526
+ function planWorkspaceInvariantReads(job: {
527
+ intent?: { workspaceInvariantReads?: { id?: string }; payload?: unknown };
528
+ }): string {
529
+ const id = job.intent?.workspaceInvariantReads?.id;
530
+ if (typeof id !== "string") {
531
+ throw new Error(
532
+ `engine workspaceInvariantReads: job.intent.workspaceInvariantReads must carry {id}; got ${JSON.stringify(job.intent)}`,
533
+ );
534
+ }
535
+ const decl = wsInvariantById(id);
536
+ if (decl === undefined) {
537
+ throw new Error(`engine workspaceInvariantReads: no workspace invariant registered for "${id}"`);
538
+ }
539
+ const intent = (job.intent?.payload ?? {}) as Record<string, unknown>;
540
+ return JSON.stringify(decl.reads({ intent }));
541
+ }
542
+
543
+ /** `{workspaceInvariant:{id,on}, payload?}` + priorState (named snapshots) → {accept}|{reject}. */
544
+ function planWorkspaceInvariantAssert(job: {
545
+ intent?: { workspaceInvariant?: { id?: string }; payload?: unknown };
546
+ priorState?: Record<string, unknown>;
547
+ }): string {
548
+ const id = job.intent?.workspaceInvariant?.id;
549
+ if (typeof id !== "string") {
550
+ throw new Error(
551
+ `engine workspaceInvariant: job.intent.workspaceInvariant must carry {id}; got ${JSON.stringify(job.intent)}`,
552
+ );
553
+ }
554
+ const decl = wsInvariantById(id);
555
+ if (decl === undefined) {
556
+ throw new Error(`engine workspaceInvariant: no workspace invariant registered for "${id}"`);
557
+ }
558
+ const snapshots = (job.priorState ?? {}) as Record<string, Record<string, unknown>>;
559
+ const intent = (job.intent?.payload ?? {}) as Record<string, unknown>;
560
+ return JSON.stringify(decl.assert(snapshots, { intent }));
561
+ }
562
+
461
563
  function planDerive(job: {
462
564
  intent?: { derive?: { of?: string } };
463
565
  priorState?: Record<string, unknown>;
@@ -527,8 +629,26 @@ export function registerEngine(config: EngineEntryConfig): RegisteredEngine {
527
629
  queryRows?: unknown[];
528
630
  priorState?: Record<string, unknown>;
529
631
  }): string {
530
- // Branch order mirrors emit_engine.ts: aggregateInvariant invariant derive
531
- // combine → report (the gate's most recent dispatch key wins over older fan-outs).
632
+ // Branch order mirrors emit_engine.ts: workspace-invariant trioaggregateInvariant
633
+ // invariant → derive → combine → report (the gate's most recent dispatch key wins).
634
+ const wsJob = job as {
635
+ intent?: {
636
+ workspaceInvariantList?: unknown;
637
+ workspaceInvariantReads?: { id?: string };
638
+ workspaceInvariant?: { id?: string };
639
+ payload?: unknown;
640
+ };
641
+ priorState?: Record<string, unknown>;
642
+ };
643
+ if (wsJob.intent?.workspaceInvariantList !== undefined) {
644
+ return planWorkspaceInvariantList();
645
+ }
646
+ if (wsJob.intent?.workspaceInvariantReads !== undefined) {
647
+ return planWorkspaceInvariantReads(wsJob);
648
+ }
649
+ if (wsJob.intent?.workspaceInvariant !== undefined) {
650
+ return planWorkspaceInvariantAssert(wsJob);
651
+ }
532
652
  if (job.intent?.aggregateInvariant !== undefined) {
533
653
  return planAggInvariant(
534
654
  job as { intent?: { aggregateInvariant?: { of?: string } }; priorState?: Record<string, unknown> },
@@ -75,9 +75,16 @@ export type WorkspaceInvariantReads = (ctx: { intent: Record<string, unknown> })
75
75
  /**
76
76
  * The post-apply predicate over the resolved snapshots, keyed by each ref's binding `name`.
77
77
  * PURE over the named map (no clock, no IO, no live reads) — runs in the sealed engine.
78
+ *
79
+ * The OPTIONAL second argument carries the authored intent payload (`ctx.intent`) — the
80
+ * SAME committed fact the `reads` body derived its ref-set from (never a live read), so a
81
+ * predicate may compare a payload-carried value against the resolved snapshots (the
82
+ * wrong-home homing invariant compares the payload's home key against the shard's own
83
+ * declared identity). Predicates that ignore it are unchanged (#266 signature, additive).
78
84
  */
79
85
  export type WorkspaceInvariantAssert = (
80
86
  snapshots: Record<string, Record<string, unknown>>,
87
+ ctx?: { intent: Record<string, unknown> },
81
88
  ) => WorkspaceInvariantVerdict;
82
89
 
83
90
  /** A complete, registered workspace-invariant declaration (the `.assert` terminal yields this). */
package/src/index.ts CHANGED
@@ -52,6 +52,12 @@ export {
52
52
  type StrikeOp,
53
53
  } from "./ops.js";
54
54
  export { directive, type Directive, type ReferentialMarker } from "./directive.js";
55
+ // FIRST-CLASS WORKSPACE TYPES (sharding §10 RATIFIED, slice 1) live on the SUBPATH
56
+ // `@githolon/dsl/workspace-type` (`workspaceType("estate").root(Estate).hasMany(...)`),
57
+ // NOT this runtime barrel — the barrel is bundled into EVERY tenant's engine lump, and
58
+ // a taxonomy-free domain's package bytes must not move (the hash-stability law; same
59
+ // reason `build-package` is subpath-only). The decls are compile-lane: the manifest
60
+ // lowering + homing walk + derived birth lanes consume them; the sealed engine never does.
55
61
  // THE AGGREGATE AUTHORING SURFACE (Nomos owns every birth): `create(agg)` mints + records and returns
56
62
  // a DDD-fluent `AggregateRef`; the dev `.set`/`.add`(collection)/`.setEntry`(map)/`.relate`(reference)
57
63
  // — naming no id. A directive's `.plan` calls these and returns `[]` (the recorded graph is the write