Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

feat(sdk): the schedule can say which systems' order nobody decided

esengine5bbf36bdc2bc
diff --git a/desktop/tests/api-baseline.test.ts b/desktop/tests/api-baseline.test.ts
index 78afcd216..3612df021 100644
--- a/desktop/tests/api-baseline.test.ts
+++ b/desktop/tests/api-baseline.test.ts
@@ -8,7 +8,7 @@
*/
import { describe, it, expect } from 'vitest';
// @ts-expect-error — a repo tool, shipped as .mjs with no declarations
-import { parseSnapshot, baselineFindings, UNCLAIMED } from '../../tools/lib/apiSnapshot.mjs';
+import { parseSnapshot, baselineFindings, isAdditiveMembers, UNCLAIMED } from '../../tools/lib/apiSnapshot.mjs';
type Entry = { kind: string; tier: string; deprecated: boolean; body: string };
@@ -106,3 +106,36 @@ describe('baselineFindings', () => {
]);
});
});
+
+describe('an interface that gains an optional member', () => {
+ const was = snapshot(sig('Options — interface @public', 'name: string | undefined'));
+
+ it('is not a broken promise: nothing that compiled stops compiling', () => {
+ const now = snapshot(sig('Options — interface @public',
+ 'name: string | undefined\ntouches: Touches | undefined'));
+ const { failures, notes } = baselineFindings(was, now);
+ expect(failures).toEqual([]);
+ expect(notes.join()).toMatch(/optional member/);
+ });
+
+ it('still fails when the added member is required', () => {
+ const now = snapshot(sig('Options — interface @public',
+ 'name: string | undefined\ntouches: Touches'));
+ expect(baselineFindings(was, now).failures).toHaveLength(1);
+ });
+
+ it('still fails when an existing member changed', () => {
+ const now = snapshot(sig('Options — interface @public',
+ 'name: number | undefined\ntouches: Touches | undefined'));
+ expect(baselineFindings(was, now).failures).toHaveLength(1);
+ });
+
+ it('still fails when a member was dropped', () => {
+ const now = snapshot(sig('Options — interface @public', 'touches: Touches | undefined'));
+ expect(baselineFindings(was, now).failures).toHaveLength(1);
+ });
+
+ it('is not additive when nothing was added', () => {
+ expect(isAdditiveMembers('a: string | undefined', 'a: string | undefined')).toBe(false);
+ });
+});
diff --git a/docs/astro/src/data/apiStability.generated.json b/docs/astro/src/data/apiStability.generated.json
index 04fb75512..5f4321eac 100644
--- a/docs/astro/src/data/apiStability.generated.json
+++ b/docs/astro/src/data/apiStability.generated.json
@@ -1,12 +1,12 @@
{
"note": "Generated by tools/api-stability.mjs from sdk/etc/*.api.md — do not edit.",
"counts": {
- "public": 112,
+ "public": 113,
"beta": 60,
- "experimental": 1507,
+ "experimental": 1508,
"deprecated": 3
},
- "total": 1679,
+ "total": 1681,
"subsystems": [
{
"id": "ecs",
@@ -1298,6 +1298,18 @@
"minigame"
]
},
+ {
+ "name": "SystemTouches",
+ "kind": "interface",
+ "deprecated": false,
+ "entries": [
+ "index",
+ "index.node",
+ "index.native",
+ "wechat",
+ "minigame"
+ ]
+ },
{
"name": "Text",
"kind": "const",
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index cb49fb73b..18b862cdb 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 112 public · 53 beta · 1392 experimental · 3 deprecated
+Symbols: 113 public · 53 beta · 1393 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
@@ -258,6 +258,13 @@ Start = 1
Stretch = 4
```
+## Ambiguity — interface @experimental
+```
+a: string
+b: string
+over: string[]
+```
+
## AnchorAxis — enum @experimental
```
Center = 1
@@ -542,6 +549,8 @@ quit: (options?: { keepRenderer?: boolean; }) => void
registerScene: (config: SceneConfig) => App
removeSystem: (systemId: symbol) => boolean
run: () => Promise<void>
+scheduleAmbiguities: (schedule: Schedule) => Ambiguity[]
+scheduleBatches: (schedule: Schedule) => string[][]
setFixedTimestep: (timestep: number) => App
setInitialScene: (name: string) => App
setMaxDeltaTime: (v: number) => App
@@ -6992,6 +7001,7 @@ query: QueryCost | undefined
@internal _params: readonly SystemParam[]
@internal _runAfter: readonly string[] | undefined
@internal _runBefore: readonly string[] | undefined
+@internal _touches: SystemTouches | undefined
```
## SystemOptions — interface @public
@@ -6999,6 +7009,7 @@ query: QueryCost | undefined
name: string | undefined
runAfter: string[] | undefined
runBefore: string[] | undefined
+touches: SystemTouches | undefined
```
## SystemParam — type @public
@@ -7044,6 +7055,12 @@ runIf: RunCondition | undefined
systems: SystemDef[]
```
+## SystemTouches — interface @public
+```
+reads: readonly string[] | undefined
+writes: readonly string[] | undefined
+```
+
## TB_E — const @experimental
```
2
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index 236eb45c5..5f8913fbd 100644
--- a/sdk/etc/index.native.api.md
+++ b/sdk/etc/index.native.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index.native
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 112 public · 58 beta · 1411 experimental · 3 deprecated
+Symbols: 113 public · 58 beta · 1412 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
@@ -258,6 +258,13 @@ Start = 1
Stretch = 4
```
+## Ambiguity — interface @experimental
+```
+a: string
+b: string
+over: string[]
+```
+
## AnchorAxis — enum @experimental
```
Center = 1
@@ -542,6 +549,8 @@ quit: (options?: { keepRenderer?: boolean; }) => void
registerScene: (config: SceneConfig) => App
removeSystem: (systemId: symbol) => boolean
run: () => Promise<void>
+scheduleAmbiguities: (schedule: Schedule) => Ambiguity[]
+scheduleBatches: (schedule: Schedule) => string[][]
setFixedTimestep: (timestep: number) => App
setInitialScene: (name: string) => App
setMaxDeltaTime: (v: number) => App
@@ -7185,6 +7194,7 @@ query: QueryCost | undefined
@internal _params: readonly SystemParam[]
@internal _runAfter: readonly string[] | undefined
@internal _runBefore: readonly string[] | undefined
+@internal _touches: SystemTouches | undefined
```
## SystemOptions — interface @public
@@ -7192,6 +7202,7 @@ query: QueryCost | undefined
name: string | undefined
runAfter: string[] | undefined
runBefore: string[] | undefined
+touches: SystemTouches | undefined
```
## SystemParam — type @public
@@ -7237,6 +7248,12 @@ runIf: RunCondition | undefined
systems: SystemDef[]
```
+## SystemTouches — interface @public
+```
+reads: readonly string[] | undefined
+writes: readonly string[] | undefined
+```
+
## TB_E — const @experimental
```
2
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index 4ecff6ebe..cbb3d258c 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index.node
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 112 public · 55 beta · 1391 experimental · 3 deprecated
+Symbols: 113 public · 55 beta · 1392 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -253,6 +253,13 @@ Start = 1
Stretch = 4
```
+## Ambiguity — interface @experimental
+```
+a: string
+b: string
+over: string[]
+```
+
## AnchorAxis — enum @experimental
```
Center = 1
@@ -537,6 +544,8 @@ quit: (options?: { keepRenderer?: boolean; }) => void
registerScene: (config: SceneConfig) => App
removeSystem: (systemId: symbol) => boolean
run: () => Promise<void>
+scheduleAmbiguities: (schedule: Schedule) => Ambiguity[]
+scheduleBatches: (schedule: Schedule) => string[][]
setFixedTimestep: (timestep: number) => App
setInitialScene: (name: string) => App
setMaxDeltaTime: (v: number) => App
@@ -6987,6 +6996,7 @@ query: QueryCost | undefined
@internal _params: readonly SystemParam[]
@internal _runAfter: readonly string[] | undefined
@internal _runBefore: readonly string[] | undefined
+@internal _touches: SystemTouches | undefined
```
## SystemOptions — interface @public
@@ -6994,6 +7004,7 @@ query: QueryCost | undefined
name: string | undefined
runAfter: string[] | undefined
runBefore: string[] | undefined
+touches: SystemTouches | undefined
```
## SystemParam — type @public
@@ -7039,6 +7050,12 @@ runIf: RunCondition | undefined
systems: SystemDef[]
```
+## SystemTouches — interface @public
+```
+reads: readonly string[] | undefined
+writes: readonly string[] | undefined
+```
+
## TB_E — const @experimental
```
2
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index 726bd3824..3acc32680 100644
--- a/sdk/etc/minigame.api.md
+++ b/sdk/etc/minigame.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/minigame
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 112 public · 53 beta · 1412 experimental · 3 deprecated
+Symbols: 113 public · 53 beta · 1413 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -253,6 +253,13 @@ Start = 1
Stretch = 4
```
+## Ambiguity — interface @experimental
+```
+a: string
+b: string
+over: string[]
+```
+
## AnchorAxis — enum @experimental
```
Center = 1
@@ -537,6 +544,8 @@ quit: (options?: { keepRenderer?: boolean; }) => void
registerScene: (config: SceneConfig) => App
removeSystem: (systemId: symbol) => boolean
run: () => Promise<void>
+scheduleAmbiguities: (schedule: Schedule) => Ambiguity[]
+scheduleBatches: (schedule: Schedule) => string[][]
setFixedTimestep: (timestep: number) => App
setInitialScene: (name: string) => App
setMaxDeltaTime: (v: number) => App
@@ -7232,6 +7241,7 @@ query: QueryCost | undefined
@internal _params: readonly SystemParam[]
@internal _runAfter: readonly string[] | undefined
@internal _runBefore: readonly string[] | undefined
+@internal _touches: SystemTouches | undefined
```
## SystemOptions — interface @public
@@ -7239,6 +7249,7 @@ query: QueryCost | undefined
name: string | undefined
runAfter: string[] | undefined
runBefore: string[] | undefined
+touches: SystemTouches | undefined
```
## SystemParam — type @public
@@ -7284,6 +7295,12 @@ runIf: RunCondition | undefined
systems: SystemDef[]
```
+## SystemTouches — interface @public
+```
+reads: readonly string[] | undefined
+writes: readonly string[] | undefined
+```
+
## TB_E — const @experimental
```
2
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index 2db1e094f..8294fa2c0 100644
--- a/sdk/etc/wechat.api.md
+++ b/sdk/etc/wechat.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/wechat
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 112 public · 53 beta · 1402 experimental · 3 deprecated
+Symbols: 113 public · 53 beta · 1403 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -253,6 +253,13 @@ Start = 1
Stretch = 4
```
+## Ambiguity — interface @experimental
+```
+a: string
+b: string
+over: string[]
+```
+
## AnchorAxis — enum @experimental
```
Center = 1
@@ -537,6 +544,8 @@ quit: (options?: { keepRenderer?: boolean; }) => void
registerScene: (config: SceneConfig) => App
removeSystem: (systemId: symbol) => boolean
run: () => Promise<void>
+scheduleAmbiguities: (schedule: Schedule) => Ambiguity[]
+scheduleBatches: (schedule: Schedule) => string[][]
setFixedTimestep: (timestep: number) => App
setInitialScene: (name: string) => App
setMaxDeltaTime: (v: number) => App
@@ -6994,6 +7003,7 @@ query: QueryCost | undefined
@internal _params: readonly SystemParam[]
@internal _runAfter: readonly string[] | undefined
@internal _runBefore: readonly string[] | undefined
+@internal _touches: SystemTouches | undefined
```
## SystemOptions — interface @public
@@ -7001,6 +7011,7 @@ query: QueryCost | undefined
name: string | undefined
runAfter: string[] | undefined
runBefore: string[] | undefined
+touches: SystemTouches | undefined
```
## SystemParam — type @public
@@ -7046,6 +7057,12 @@ runIf: RunCondition | undefined
systems: SystemDef[]
```
+## SystemTouches — interface @public
+```
+reads: readonly string[] | undefined
+writes: readonly string[] | undefined
+```
+
## TB_E — const @experimental
```
2
diff --git a/sdk/src/ai/bt/BtPlugin.ts b/sdk/src/ai/bt/BtPlugin.ts
index 2df170bcf..c3e078ef3 100644
--- a/sdk/src/ai/bt/BtPlugin.ts
+++ b/sdk/src/ai/bt/BtPlugin.ts
@@ -138,6 +138,8 @@ export class BtPlugin implements Plugin {
app.addSystemToSchedule(
Schedule.Update,
+ // system-access: steps a project's behaviour tree, whose nodes read and
+ // write whatever that project's tree names.
defineSystem(
[Res(Time), Commands(), GetWorld()],
(time: TimeData, commands: CommandsInstance, world) => {
diff --git a/sdk/src/ai/fsm/FsmPlugin.ts b/sdk/src/ai/fsm/FsmPlugin.ts
index fe9e63887..77bcf5fb9 100644
--- a/sdk/src/ai/fsm/FsmPlugin.ts
+++ b/sdk/src/ai/fsm/FsmPlugin.ts
@@ -145,6 +145,8 @@ export class FsmPlugin implements Plugin {
app.addSystemToSchedule(
Schedule.Update,
+ // system-access: steps a project's state machine, whose states read and
+ // write whatever that project's graph names.
defineSystem(
[Res(Time), Commands(), GetWorld()],
(time: TimeData, commands: CommandsInstance, world) => {
diff --git a/sdk/src/ai/nav/NavPlugin.ts b/sdk/src/ai/nav/NavPlugin.ts
index 6f764690a..16da723d2 100644
--- a/sdk/src/ai/nav/NavPlugin.ts
+++ b/sdk/src/ai/nav/NavPlugin.ts
@@ -116,6 +116,8 @@ export class NavPlugin implements Plugin {
app.addSystemToSchedule(
Schedule.Update,
+ // system-access: moves agents whose components are registered by the
+ // project, through the same World view the editor steps.
defineSystem(
[Res(Nav), Res(Time), GetWorld()],
(nav: Navigation, time: TimeData, world) => {
diff --git a/sdk/src/ai/perception/PerceptionPlugin.ts b/sdk/src/ai/perception/PerceptionPlugin.ts
index 657c1fb83..33440e4d1 100644
--- a/sdk/src/ai/perception/PerceptionPlugin.ts
+++ b/sdk/src/ai/perception/PerceptionPlugin.ts
@@ -97,6 +97,7 @@ export class PerceptionPlugin implements Plugin {
build(app: App): void {
app.addSystemToSchedule(
Schedule.PreUpdate,
+ // system-access: senses whatever a project's perception graph names.
defineSystem(
[GetWorld()],
world => {
diff --git a/sdk/src/app/access.ts b/sdk/src/app/access.ts
new file mode 100644
index 000000000..0fa5b027d
--- /dev/null
+++ b/sdk/src/app/access.ts
@@ -0,0 +1,137 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file What a system touches, read off the parameters it already declares.
+ *
+ * `Query(Mut(Transform))` says "I write Transform" and `Res(Time)` says
+ * "I read Time" — the schedule has held that information all along and
+ * only ever used it to look up values. Reading it as a set makes two
+ * questions answerable: whether two systems can run at the same time, and
+ * whether the order they DO run in was ever decided by anyone.
+ */
+import type { SystemDef, SystemParam } from '../ecs/system';
+import type { AnyComponentDef } from '../ecs/component';
+import type { QueryDescriptor, QueryArg } from '../ecs/query';
+
+/** Everything one system reads and writes, by name. */
+export interface SystemAccess {
+ readsComponents: ReadonlySet<string>;
+ writesComponents: ReadonlySet<string>;
+ readsResources: ReadonlySet<string>;
+ writesResources: ReadonlySet<string>;
+ /**
+ * The system asked for the World itself, so nothing about it is declared.
+ * Treated as touching everything — the price of the escape hatch.
+ */
+ opaque: boolean;
+}
+
+type MutWrapper = { readonly _type: 'mut'; readonly _component: AnyComponentDef };
+type WrappedArg = { readonly _component?: AnyComponentDef };
+
+const componentName = (c: AnyComponentDef): string => c._name;
+
+/** The component a query argument is about, whatever it is wrapped in. Anything
+ * that is not one — a nested array from a mis-spelled `Query([...])` — is not
+ * access, and guessing at it would put `undefined` in the set. */
+function argComponent(arg: QueryArg): AnyComponentDef | null {
+ const wrapped = (arg as WrappedArg)._component;
+ const comp = wrapped ?? (arg as AnyComponentDef | null);
+ return typeof (comp as { _name?: unknown } | null)?._name === 'string' ? comp : null;
+}
+
+const isMut = (arg: QueryArg): boolean => (arg as MutWrapper)._type === 'mut';
+
+/** A resource's declared name — what `defineResource` stamped on it. */
+const resourceName = (r: unknown): string => (r as { _name?: string })?._name ?? String(r);
+
+/** Read a system's declared access. Cheap and pure — the caller may cache it. */
+export function accessOf(system: SystemDef): SystemAccess {
+ const readsComponents = new Set<string>();
+ const writesComponents = new Set<string>();
+ const readsResources = new Set<string>();
+ const writesResources = new Set<string>();
+ let opaque = false;
+
+ for (const param of system._params as readonly SystemParam[]) {
+ switch (param._type) {
+ case 'query': {
+ const q = param as QueryDescriptor<readonly QueryArg[]>;
+ q._components.forEach((arg) => {
+ const comp = argComponent(arg);
+ if (!comp) return;
+ (isMut(arg) ? writesComponents : readsComponents).add(componentName(comp));
+ });
+ // A filter decides which entities match, so it is read access:
+ // whoever writes that component changes this query's result.
+ for (const comp of [...q._with, ...q._without]) readsComponents.add(componentName(comp));
+ break;
+ }
+ case 'removed':
+ readsComponents.add(componentName((param as { _component: AnyComponentDef })._component));
+ break;
+ case 'res':
+ readsResources.add(resourceName((param as { _resource: unknown })._resource));
+ break;
+ case 'res_mut':
+ writesResources.add(resourceName((param as { _resource: unknown })._resource));
+ break;
+ case 'get_world':
+ opaque = true;
+ break;
+ // Commands are applied after the system returns, and an event
+ // channel is its own buffered storage — neither races the other
+ // systems of the same batch.
+ default:
+ break;
+ }
+ }
+
+ // A system that says what it reaches for through the World is no longer
+ // opaque: its claim IS the declaration, and it is named by component name
+ // because the reason to use the hatch is usually a type registered later.
+ const touches = system._touches;
+ if (touches) {
+ for (const name of touches.reads ?? []) readsComponents.add(name);
+ for (const name of touches.writes ?? []) writesComponents.add(name);
+ if (opaque) opaque = false;
+ }
+
+ return { readsComponents, writesComponents, readsResources, writesResources, opaque };
+}
+
+const intersects = (a: ReadonlySet<string>, b: ReadonlySet<string>): boolean => {
+ const [small, large] = a.size <= b.size ? [a, b] : [b, a];
+ for (const x of small) if (large.has(x)) return true;
+ return false;
+};
+
+/**
+ * Whether two systems touch the same data in a way that makes their order
+ * matter: one writes what the other reads or writes.
+ */
+export function conflicts(a: SystemAccess, b: SystemAccess): boolean {
+ if (a.opaque || b.opaque) return true;
+ return intersects(a.writesComponents, b.writesComponents)
+ || intersects(a.writesComponents, b.readsComponents)
+ || intersects(a.readsComponents, b.writesComponents)
+ || intersects(a.writesResources, b.writesResources)
+ || intersects(a.writesResources, b.readsResources)
+ || intersects(a.readsResources, b.writesResources);
+}
+
+/** What two conflicting systems disagree over, for a message that names it. */
+export function conflictBetween(a: SystemAccess, b: SystemAccess): string[] {
+ if (a.opaque || b.opaque) return ['the World itself'];
+ const shared = new Set<string>();
+ const add = (x: ReadonlySet<string>, y: ReadonlySet<string>): void => {
+ for (const n of x) if (y.has(n)) shared.add(n);
+ };
+ add(a.writesComponents, b.writesComponents);
+ add(a.writesComponents, b.readsComponents);
+ add(a.readsComponents, b.writesComponents);
+ add(a.writesResources, b.writesResources);
+ add(a.writesResources, b.readsResources);
+ add(a.readsResources, b.writesResources);
+ return [...shared].sort();
+}
diff --git a/sdk/src/app/ambiguity.ts b/sdk/src/app/ambiguity.ts
new file mode 100644
index 000000000..268520201
--- /dev/null
+++ b/sdk/src/app/ambiguity.ts
@@ -0,0 +1,144 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file Systems whose order nobody decided.
+ *
+ * A schedule runs its systems in topological order, and for two systems
+ * with no edge between them that order falls out of registration and a
+ * depth-first walk. That is fine while they touch different data. When
+ * one writes what the other reads, the result depends on which happened
+ * to come first — so adding a third system, or moving a plugin in the
+ * build list, can change what the game does with nothing to point at.
+ *
+ * Naming those pairs is also the prerequisite for ever running them at
+ * the same time: a pair that must not be reordered cannot be a batch.
+ */
+import type { SystemDef } from '../ecs/system';
+import { accessOf, conflicts, conflictBetween, type SystemAccess } from './access';
+
+/** A system with the ordering it declared, as a schedule holds it. */
+export interface OrderedSystem {
+ system: SystemDef;
+ runBefore?: readonly string[];
+ runAfter?: readonly string[];
+}
+
+/** Resolves an ordering name to the indices it refers to (a system, or a set). */
+export type ResolveTargets = (name: string) => readonly number[];
+
+/**
+ * `edges[i]` lists the indices that must run BEFORE `i`. `runBefore` is folded
+ * in symmetrically, so both spellings of one relationship produce one edge.
+ */
+export function dependencyEdges(
+ systems: readonly OrderedSystem[],
+ resolveTargets: ResolveTargets,
+): number[][] {
+ const edges: number[][] = systems.map(() => []);
+ const addEdge = (from: number, to: number): void => {
+ if (from === to) return;
+ const list = edges[to];
+ if (!list.includes(from)) list.push(from);
+ };
+ for (let i = 0; i < systems.length; i++) {
+ for (const name of systems[i].runAfter ?? []) {
+ for (const j of resolveTargets(name)) addEdge(j, i);
+ }
+ for (const name of systems[i].runBefore ?? []) {
+ for (const j of resolveTargets(name)) addEdge(i, j);
+ }
+ }
+ return edges;
+}
+
+/** Two systems that touch the same data with nothing saying which goes first. */
+export interface Ambiguity {
+ /** The two system names, in registration order. */
+ a: string;
+ b: string;
+ /** The components and resources they disagree over. */
+ over: string[];
+}
+
+/** Everything that must run before each index, transitively. */
+function ancestors(edges: readonly number[][]): Set<number>[] {
+ const out: Set<number>[] = edges.map(() => new Set<number>());
+ const done = new Uint8Array(edges.length);
+ const visit = (i: number, stack: Set<number>): void => {
+ if (done[i] || stack.has(i)) return;
+ stack.add(i);
+ for (const dep of edges[i]) {
+ visit(dep, stack);
+ out[i].add(dep);
+ for (const t of out[dep]) out[i].add(t);
+ }
+ stack.delete(i);
+ done[i] = 1;
+ };
+ for (let i = 0; i < edges.length; i++) visit(i, new Set<number>());
+ return out;
+}
+
+/**
+ * Every pair of systems in one schedule that conflicts and is unordered.
+ *
+ * Reported in registration order and deduplicated, so a schedule's ambiguities
+ * are a stable list something can be held to.
+ */
+export function detectAmbiguities(
+ systems: readonly OrderedSystem[],
+ resolveTargets: ResolveTargets,
+): Ambiguity[] {
+ if (systems.length < 2) return [];
+ const edges = dependencyEdges(systems, resolveTargets);
+ const before = ancestors(edges);
+ const access: SystemAccess[] = systems.map((s) => accessOf(s.system));
+
+ const found: Ambiguity[] = [];
+ for (let i = 0; i < systems.length; i++) {
+ for (let j = i + 1; j < systems.length; j++) {
+ if (before[i].has(j) || before[j].has(i)) continue;
+ if (!conflicts(access[i], access[j])) continue;
+ found.push({
+ a: systems[i].system._name,
+ b: systems[j].system._name,
+ over: conflictBetween(access[i], access[j]),
+ });
+ }
+ }
+ return found;
+}
+
+/**
+ * Systems grouped into batches that could run at the same time: a batch is free
+ * of conflicts within itself and its dependencies are met by the batches before
+ * it. The schedule still runs them one after another — this measures how much of
+ * one is inherently sequential.
+ */
+export function parallelBatches(
+ systems: readonly OrderedSystem[],
+ resolveTargets: ResolveTargets,
+): string[][] {
+ const edges = dependencyEdges(systems, resolveTargets);
+ const access: SystemAccess[] = systems.map((s) => accessOf(s.system));
+ const placed = new Int32Array(systems.length).fill(-1);
+ const batches: number[][] = [];
+
+ let remaining = systems.length;
+ while (remaining > 0) {
+ const batch: number[] = [];
+ for (let i = 0; i < systems.length; i++) {
+ if (placed[i] >= 0) continue;
+ if (edges[i].some((dep) => placed[dep] < 0)) continue;
+ if (batch.some((k) => conflicts(access[i], access[k]))) continue;
+ batch.push(i);
+ }
+ // A cycle in the edges would leave nothing runnable; the sort reports
+ // that with the path, so here it only has to stop.
+ if (batch.length === 0) break;
+ for (const i of batch) placed[i] = batches.length;
+ batches.push(batch);
+ remaining -= batch.length;
+ }
+ return batches.map((b) => b.map((i) => systems[i].system._name));
+}
diff --git a/sdk/src/app/app.ts b/sdk/src/app/app.ts
index 20a488976..c7ef1ff90 100644
--- a/sdk/src/app/app.ts
+++ b/sdk/src/app/app.ts
@@ -6,7 +6,7 @@
*/
import { World } from '../ecs/world';
-import { Schedule, SystemDef, SystemRunner, SystemSet, mergeOrderingEdges, type RunCondition } from '../ecs/system';
+import { Schedule, SystemDef, SystemRunner, SystemSet, mergeOrderingEdges, rescopeSystem, type RunCondition } from '../ecs/system';
import { ResourceStorage, Time, TimeData, type ResourceDef } from '../ecs/resource';
import { EventRegistry, type EventDef } from '../ecs/event';
import type { ESEngineModule, CppRegistry } from '../wasm';
@@ -17,6 +17,13 @@ import { assetPlugin } from '../asset';
import { prefabsPlugin } from '../prefab/prefabServer';
import { setWasmErrorHandler } from '../wasm/wasmError';
import { corePlugin, DEFAULT_UI_CAMERA_INFO } from './corePlugin';
+import {
+ dependencyEdges,
+ detectAmbiguities,
+ parallelBatches,
+ type Ambiguity,
+ type ResolveTargets,
+} from './ambiguity';
import { platformNow } from '../platform';
import { RenderPipeline } from '../render/renderPipeline';
import type { SceneConfig } from '../scene/sceneManager';
@@ -322,14 +329,7 @@ export class App {
options?: { runBefore?: string[]; runAfter?: string[]; runIf?: RunCondition }
): this {
const name = system._name || `System_${++this.systemCounter_}`;
- const scoped: SystemDef = {
- _id: Symbol(`System_${name}`),
- _params: system._params,
- _fn: system._fn,
- _name: name,
- _runBefore: system._runBefore,
- _runAfter: system._runAfter,
- };
+ const scoped = rescopeSystem(system, name);
this.templateToRuntime_.set(system._id, scoped._id);
this.scheduleBucket_(schedule, name).push({
@@ -473,14 +473,7 @@ export class App {
// Use the scoped system name the App would generate so ordering
// lookups match. Mirrors addSystemToSchedule's naming path.
- const scoped: SystemDef = {
- _id: Symbol(`System_${name}`),
- _params: sys._params,
- _fn: sys._fn,
- _name: name,
- _runBefore: sys._runBefore,
- _runAfter: sys._runAfter,
- };
+ const scoped = rescopeSystem(sys, name);
this.templateToRuntime_.set(sys._id, scoped._id);
this.scheduleBucket_(schedule, name).push({
@@ -1120,20 +1113,18 @@ export class App {
return sorted;
}
- private sortSystems(systems: SystemEntry[]): SystemEntry[] {
- if (systems.length <= 1) {
- return systems;
- }
-
+ /**
+ * Expands an ordering name to the indices it refers to — a system, or every
+ * member of a set that is also in this schedule. A name matching neither
+ * resolves to nothing, which is how ordering against a system that was never
+ * registered stays a no-op rather than an error.
+ */
+ private resolverFor(systems: readonly SystemEntry[]): ResolveTargets {
const nameToIndex = new Map<string, number>();
for (let i = 0; i < systems.length; i++) {
nameToIndex.set(systems[i].system._name, i);
}
-
- // Expand a name that may refer to a SystemSet into the indices of
- // every member of the set that is also in this schedule. Returns
- // empty when the name matches neither a system nor a known set.
- const resolveTargets = (name: string): number[] => {
+ return (name: string): number[] => {
const direct = nameToIndex.get(name);
if (direct !== undefined) return [direct];
const members = this.setMembership_.get(name);
@@ -1145,34 +1136,43 @@ export class App {
}
return out;
};
+ }
- // Build a local dependency graph: `adj[i]` lists indices that must run
- // *before* system `i`. Both runBefore and runAfter feed into the same
- // structure — runBefore is translated symmetrically into
- // "target depends on me" without mutating the caller's SystemEntry
- // objects (the old path appended to target.runAfter, leaving duplicated
- // edges across repeat sorts).
- const adj: number[][] = systems.map(() => []);
- const addEdge = (from: number, to: number) => {
- if (from === to) return;
- const list = adj[to];
- if (!list.includes(from)) list.push(from);
- };
+ /**
+ * Pairs of systems in `schedule` that touch the same data with nothing
+ * saying which runs first, so their order is whatever registration and the
+ * sort happened to produce.
+ *
+ * @beta
+ */
+ scheduleAmbiguities(schedule: Schedule): Ambiguity[] {
+ const systems = this.systems_.get(schedule) ?? [];
+ return detectAmbiguities(systems, this.resolverFor(systems));
+ }
- for (let i = 0; i < systems.length; i++) {
- const e = systems[i];
- if (e.runAfter) {
- for (const depName of e.runAfter) {
- for (const j of resolveTargets(depName)) addEdge(j, i);
- }
- }
- if (e.runBefore) {
- for (const targetName of e.runBefore) {
- for (const j of resolveTargets(targetName)) addEdge(i, j);
- }
- }
+ /**
+ * `schedule` grouped into batches that could run at the same time — how much
+ * of it is inherently sequential. The schedule still runs them in order.
+ *
+ * @beta
+ */
+ scheduleBatches(schedule: Schedule): string[][] {
+ const systems = this.systems_.get(schedule) ?? [];
+ return parallelBatches(systems, this.resolverFor(systems));
+ }
+
+ private sortSystems(systems: SystemEntry[]): SystemEntry[] {
+ if (systems.length <= 1) {
+ return systems;
}
+ const resolveTargets = this.resolverFor(systems);
+
+ // `adj[i]` lists indices that must run *before* system `i` — the same
+ // edges the ambiguity check reads, so what orders a schedule and what
+ // judges its order can never be two answers.
+ const adj = dependencyEdges(systems, resolveTargets);
+
// DFS topological sort with path-aware cycle reporting.
// color: 0 = unvisited, 1 = in the current DFS stack (GRAY), 2 = done.
const GRAY = 1, BLACK = 2;
diff --git a/sdk/src/behavior.ts b/sdk/src/behavior.ts
index 05c94cf92..ebb510abd 100644
--- a/sdk/src/behavior.ts
+++ b/sdk/src/behavior.ts
@@ -133,6 +133,8 @@ export function defineBehavior<S extends object>(name: string, def: BehaviorDef<
const { start, update, destroy } = def;
+ // system-access: runs a behaviour a project wrote, which may read or write
+ // any component it names.
const system = defineSystem(
[Query(Mut(Comp)), Res(Time), Res(Input), Commands(), GetWorld()],
(q, time, input, commands, world) => {
diff --git a/sdk/src/core-runtime.ts b/sdk/src/core-runtime.ts
index 9ca707631..2056dba22 100644
--- a/sdk/src/core-runtime.ts
+++ b/sdk/src/core-runtime.ts
@@ -363,12 +363,21 @@ export {
type SystemDef,
type SystemParam,
type SystemOptions,
+ type SystemTouches,
type SystemSet,
type SystemSetOptions,
type InferParam,
type InferParams,
} from './ecs/system';
+/**
+ * What the schedule can say about itself: which systems' order nobody decided,
+ * and how much of it is inherently sequential.
+ *
+ * @beta
+ */
+export type { Ambiguity } from './app/ambiguity';
+
// =============================================================================
// Behavior (per-entity scripted behavior → one ECS system)
// =============================================================================
diff --git a/sdk/src/ecs/system.ts b/sdk/src/ecs/system.ts
index d493aec7c..ba2210bbf 100644
--- a/sdk/src/ecs/system.ts
+++ b/sdk/src/ecs/system.ts
@@ -155,6 +155,8 @@ export interface SystemDef {
readonly _runBefore?: readonly string[];
/** @internal */
readonly _runAfter?: readonly string[];
+ /** @internal */
+ readonly _touches?: SystemTouches;
}
let templateCounter_ = 0;
@@ -173,6 +175,21 @@ export interface SystemOptions {
runBefore?: string[];
/** This system runs after each of these names (a system or a set). */
runAfter?: string[];
+ /** What the system reaches for through {@link GetWorld}. See {@link SystemTouches}. */
+ touches?: SystemTouches;
+}
+
+/**
+ * What a system reaches for outside its declared parameters — a {@link GetWorld}
+ * user's claim about the escape hatch, without which the scheduler assumes it
+ * touches everything. By component NAME: the reason to reach through the World
+ * is usually a type registered later than the system.
+ *
+ * @public
+ */
+export interface SystemTouches {
+ reads?: readonly string[];
+ writes?: readonly string[];
}
/**
@@ -199,6 +216,22 @@ export function defineSystem<P extends readonly SystemParam[]>(
_name: options?.name ?? '',
_runBefore: options?.runBefore,
_runAfter: options?.runAfter,
+ _touches: options?.touches,
+ };
+}
+
+/**
+ * The same system under a scheduler-owned identity and name.
+ *
+ * Registration gives a template its own id so the same definition can be added
+ * twice, and copying the fields by hand at each site is how a field added to
+ * SystemDef silently stops travelling with it.
+ */
+export function rescopeSystem(system: SystemDef, name: string): SystemDef {
+ return {
+ ...system,
+ _id: Symbol(`System_${name}`),
+ _name: name,
};
}
diff --git a/sdk/src/physics/CharacterController.ts b/sdk/src/physics/CharacterController.ts
index 0c4a25263..7f31228d3 100644
--- a/sdk/src/physics/CharacterController.ts
+++ b/sdk/src/physics/CharacterController.ts
@@ -309,6 +309,8 @@ export function registerCharacterControllerSystem(app: App): void {
warnedNonFiniteMove = false;
app.addSystemToSchedule(
Schedule.FixedUpdate,
+ // system-access: reads and writes the Transform of whatever a character is
+ // standing on, which the solver decides per contact.
defineSystem(
[Query(Mut(CharacterController)), Res(Time), Res(Physics), GetWorld()],
(
diff --git a/sdk/src/scene/scenePlugin.ts b/sdk/src/scene/scenePlugin.ts
index c764d619a..4b1773ba7 100644
--- a/sdk/src/scene/scenePlugin.ts
+++ b/sdk/src/scene/scenePlugin.ts
@@ -37,7 +37,9 @@ const sceneStreamingSystem = defineSystem(
}
streaming.update();
},
- { name: 'SceneStreamingSystem' }
+ // The World is here to read one entity's Transform — the focus the streaming
+ // controller follows, which is chosen at runtime rather than queried.
+ { name: 'SceneStreamingSystem', touches: { reads: ['Transform'] } }
);
export const sceneManagerPlugin: Plugin = {
diff --git a/sdk/src/stats.ts b/sdk/src/stats.ts
index b481f1815..3010f3465 100644
--- a/sdk/src/stats.ts
+++ b/sdk/src/stats.ts
@@ -179,6 +179,7 @@ export class StatsPlugin implements Plugin {
const collector = this.collector_;
const overlay = this.overlay_;
+ // system-access: counts what the world holds, whatever that is.
const statsCollectSystem = defineSystem(
[Res(Time), GetWorld()],
(time, world) => {
diff --git a/sdk/src/velocity.ts b/sdk/src/velocity.ts
index a69de0804..93900edde 100644
--- a/sdk/src/velocity.ts
+++ b/sdk/src/velocity.ts
@@ -60,7 +60,13 @@ export const velocitySystem = defineSystem(
}
}
},
- { name: 'VelocitySystem' }
+ {
+ name: 'VelocitySystem',
+ // The World is here for one question — does this entity have a physics
+ // body — and RigidBody cannot be named as a query filter because the
+ // physics module may never have registered it.
+ touches: { reads: ['RigidBody'] },
+ }
);
export const velocityPlugin: Plugin = {
diff --git a/sdk/tests/schedule-ambiguity.test.ts b/sdk/tests/schedule-ambiguity.test.ts
new file mode 100644
index 000000000..4ceff80a4
--- /dev/null
+++ b/sdk/tests/schedule-ambiguity.test.ts
@@ -0,0 +1,151 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file Which systems' order was never decided, read off what they declare.
+ * Two systems that touch the same data with no edge between them run in
+ * whatever order registration produced.
+ */
+import { describe, it, expect } from 'vitest';
+import { App } from '../src/app/app';
+import { Schedule, defineSystem } from '../src/ecs/system';
+import type { SystemTouches } from '../src/index';
+import { Query, Mut } from '../src/ecs/query';
+import { Res, ResMut, defineResource } from '../src/ecs/resource';
+import { defineComponent } from '../src/ecs/component';
+import { GetWorld } from '../src/ecs/system';
+
+const Position = defineComponent('AmbigPosition', { x: 0, y: 0 });
+const Velocity = defineComponent('AmbigVelocity', { x: 0, y: 0 });
+const Health = defineComponent('AmbigHealth', { hp: 100 });
+
+const ScoreRes = defineResource({ value: 0 }, 'Score');
+
+const noop = (): void => { };
+
+describe('scheduleAmbiguities', () => {
+ it('says nothing about systems that touch different components', () => {
+ const app = App.new();
+ app.addSystemToSchedule(Schedule.Update,
+ defineSystem([Query(Mut(Position))], noop, { name: 'MovePos' }));
+ app.addSystemToSchedule(Schedule.Update,
+ defineSystem([Query(Mut(Health))], noop, { name: 'Regen' }));
+ expect(app.scheduleAmbiguities(Schedule.Update)).toEqual([]);
+ });
+
+ it('names a pair where one writes what the other reads', () => {
+ const app = App.new();
+ app.addSystemToSchedule(Schedule.Update,
+ defineSystem([Query(Mut(Position), Velocity)], noop, { name: 'Move' }));
+ app.addSystemToSchedule(Schedule.Update,
+ defineSystem([Query(Position)], noop, { name: 'Cull' }));
+ const found = app.scheduleAmbiguities(Schedule.Update);
+ expect(found).toHaveLength(1);
+ expect(found[0]).toMatchObject({ a: 'Move', b: 'Cull', over: ['AmbigPosition'] });
+ });
+
+ it('stays quiet once the pair is ordered', () => {
+ const app = App.new();
+ app.addSystemToSchedule(Schedule.Update,
+ defineSystem([Query(Mut(Position))], noop, { name: 'Move' }));
+ app.addSystemToSchedule(Schedule.Update,
+ defineSystem([Query(Position)], noop, { name: 'Cull' }), { runAfter: ['Move'] });
+ expect(app.scheduleAmbiguities(Schedule.Update)).toEqual([]);
+ });
+
+ it('counts an order that only holds transitively', () => {
+ const app = App.new();
+ app.addSystemToSchedule(Schedule.Update,
+ defineSystem([Query(Mut(Position))], noop, { name: 'A' }));
+ app.addSystemToSchedule(Schedule.Update,
+ defineSystem([Query(Mut(Velocity))], noop, { name: 'B' }), { runAfter: ['A'] });
+ app.addSystemToSchedule(Schedule.Update,
+ defineSystem([Query(Position)], noop, { name: 'C' }), { runAfter: ['B'] });
+ expect(app.scheduleAmbiguities(Schedule.Update)).toEqual([]);
+ });
+
+ it('sees a resource written by one and read by another', () => {
+ const app = App.new();
+ app.addSystemToSchedule(Schedule.Update,
+ defineSystem([ResMut(ScoreRes)], noop, { name: 'Award' }));
+ app.addSystemToSchedule(Schedule.Update,
+ defineSystem([Res(ScoreRes)], noop, { name: 'ShowScore' }));
+ expect(app.scheduleAmbiguities(Schedule.Update).map((x) => x.over)).toEqual([['Score']]);
+ });
+
+ it('two readers of the same data are not ambiguous', () => {
+ const app = App.new();
+ app.addSystemToSchedule(Schedule.Update,
+ defineSystem([Query(Position)], noop, { name: 'DrawA' }));
+ app.addSystemToSchedule(Schedule.Update,
+ defineSystem([Query(Position)], noop, { name: 'DrawB' }));
+ expect(app.scheduleAmbiguities(Schedule.Update)).toEqual([]);
+ });
+
+ it('treats a system that takes the World as touching everything', () => {
+ const app = App.new();
+ app.addSystemToSchedule(Schedule.Update,
+ defineSystem([GetWorld()], noop, { name: 'Escape' }));
+ app.addSystemToSchedule(Schedule.Update,
+ defineSystem([Query(Health)], noop, { name: 'Read' }));
+ expect(app.scheduleAmbiguities(Schedule.Update)[0].over).toEqual(['the World itself']);
+ });
+
+ it('reads a with()/without() filter as data the system depends on', () => {
+ const app = App.new();
+ app.addSystemToSchedule(Schedule.Update,
+ defineSystem([Query(Mut(Health))], noop, { name: 'Damage' }));
+ app.addSystemToSchedule(Schedule.Update,
+ defineSystem([Query(Position).with(Health)], noop, { name: 'DrawLiving' }));
+ expect(app.scheduleAmbiguities(Schedule.Update)[0].over).toEqual(['AmbigHealth']);
+ });
+
+ it('takes a declared reach through the World over assuming everything', () => {
+ const app = App.new();
+ const touches: SystemTouches = { reads: ['AmbigVelocity'] };
+ app.addSystemToSchedule(Schedule.Update,
+ defineSystem([GetWorld()], noop, { name: 'Declared', touches }));
+ app.addSystemToSchedule(Schedule.Update,
+ defineSystem([Query(Mut(Health))], noop, { name: 'Damage' }));
+ expect(app.scheduleAmbiguities(Schedule.Update)).toEqual([]);
+ });
+
+ it('still catches a declared reach that collides', () => {
+ const app = App.new();
+ app.addSystemToSchedule(Schedule.Update, defineSystem([GetWorld()], noop, {
+ name: 'Declared',
+ touches: { writes: ['AmbigHealth'] },
+ }));
+ app.addSystemToSchedule(Schedule.Update,
+ defineSystem([Query(Health)], noop, { name: 'Draw' }));
+ expect(app.scheduleAmbiguities(Schedule.Update)[0].over).toEqual(['AmbigHealth']);
+ });
+});
+
+describe('scheduleBatches', () => {
+ it('puts systems that touch nothing in common in one batch', () => {
+ const app = App.new();
+ app.addSystemToSchedule(Schedule.Update,
+ defineSystem([Query(Mut(Position))], noop, { name: 'A' }));
+ app.addSystemToSchedule(Schedule.Update,
+ defineSystem([Query(Mut(Health))], noop, { name: 'B' }));
+ expect(app.scheduleBatches(Schedule.Update)).toEqual([['A', 'B']]);
+ });
+
+ it('splits a batch where one system writes what the next reads', () => {
+ const app = App.new();
+ app.addSystemToSchedule(Schedule.Update,
+ defineSystem([Query(Mut(Position))], noop, { name: 'Move' }));
+ app.addSystemToSchedule(Schedule.Update,
+ defineSystem([Query(Position)], noop, { name: 'Cull' }));
+ expect(app.scheduleBatches(Schedule.Update)).toEqual([['Move'], ['Cull']]);
+ });
+
+ it('keeps a declared order across batches', () => {
+ const app = App.new();
+ app.addSystemToSchedule(Schedule.Update,
+ defineSystem([Query(Mut(Position))], noop, { name: 'First' }));
+ app.addSystemToSchedule(Schedule.Update,
+ defineSystem([Query(Mut(Health))], noop, { name: 'Second' }), { runAfter: ['First'] });
+ expect(app.scheduleBatches(Schedule.Update)).toEqual([['First'], ['Second']]);
+ });
+});
diff --git a/tools/check-system-access.mjs b/tools/check-system-access.mjs
new file mode 100644
index 000000000..e925271c0
--- /dev/null
+++ b/tools/check-system-access.mjs
@@ -0,0 +1,96 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file check-system-access.mjs — the escape hatch says what it reaches for.
+ *
+ * A system's parameters are also its declaration of what it touches, and the
+ * schedule reads them to answer two questions: whether the order of two systems
+ * was ever decided by anyone, and whether they could ever run at the same time.
+ * `GetWorld()` answers neither — a system holding the World may touch anything,
+ * so it conflicts with everything and takes those questions off the table.
+ *
+ * That is a fair price for an escape hatch and a bad default for a subsystem. A
+ * system that uses it either declares `touches` (the claim it makes about what
+ * it reaches for) or is listed here with the reason it cannot yet.
+ *
+ * node tools/check-system-access.mjs
+ */
+import { readdirSync, readFileSync } from 'node:fs';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
+const SRC = path.join(ROOT, 'sdk', 'src');
+
+/** A system whose reach genuinely cannot be named says so above itself:
+ * `// system-access: <why>` on one of the lines before `defineSystem(`. */
+const OPT_OUT = /system-access:\s*\S/;
+
+function walk(dir, out = []) {
+ for (const e of readdirSync(dir, { withFileTypes: true })) {
+ if (e.name === 'node_modules') continue;
+ const abs = path.join(dir, e.name);
+ if (e.isDirectory()) walk(abs, out);
+ else if (e.name.endsWith('.ts') && !e.name.endsWith('.generated.ts')) out.push(abs);
+ }
+ return out;
+}
+
+/** The text of each `defineSystem(...)` call in `src`, parentheses balanced. */
+function defineSystemCalls(src) {
+ const calls = [];
+ const re = /\bdefineSystem\s*\(/g;
+ let m;
+ while ((m = re.exec(src)) !== null) {
+ let depth = 0;
+ let i = m.index + m[0].length - 1;
+ for (; i < src.length; i++) {
+ const c = src[i];
+ if (c === '(') depth++;
+ else if (c === ')') {
+ depth--;
+ if (depth === 0) break;
+ }
+ }
+ calls.push({ text: src.slice(m.index, i + 1), index: m.index });
+ }
+ return calls;
+}
+
+const nameOf = (call) => /\bname:\s*['"]([^'"]+)['"]/.exec(call)?.[1] ?? null;
+const lineOf = (src, index) => src.slice(0, index).split('\n').length;
+
+/** Whether the three lines above the call carry the opt-out and its reason. */
+function optedOut(lines, callLine) {
+ return lines.slice(Math.max(0, callLine - 4), callLine - 1).some((l) => OPT_OUT.test(l));
+}
+
+const findings = [];
+let declared = 0;
+let excused = 0;
+
+for (const file of walk(SRC)) {
+ const src = readFileSync(file, 'utf8');
+ if (!src.includes('GetWorld()')) continue;
+ const lines = src.split('\n');
+ for (const { text, index } of defineSystemCalls(src)) {
+ if (!text.includes('GetWorld()')) continue;
+ const line = lineOf(src, index);
+ if (/\btouches\s*:/.test(text)) { declared++; continue; }
+ if (optedOut(lines, line)) { excused++; continue; }
+ findings.push({
+ where: `${path.relative(ROOT, file)}:${line}`,
+ name: nameOf(text) ?? '(unnamed)',
+ });
+ }
+}
+
+if (findings.length === 0) {
+ console.log(`check-system-access: ${declared} declared, ${excused} opted out — no system holds the World without saying so.`);
+ process.exit(0);
+}
+for (const f of findings) {
+ console.error(`${f.where} ${f.name} takes GetWorld() without saying what it reaches for.`);
+}
+console.error('\nDeclare it with `touches`, or write `// system-access: <why>` above the call.');
+process.exit(1);
diff --git a/tools/gates.mjs b/tools/gates.mjs
index 325fa3637..5ee696dfb 100644
--- a/tools/gates.mjs
+++ b/tools/gates.mjs
@@ -65,6 +65,9 @@ export const GATES = [
{ id: 'headless-export', run: 'node tools/check-headless-export.mjs' },
{ id: 'cycles', run: 'node tools/check-cycles.mjs' },
{ id: 'layers', run: 'node tools/check-layers.mjs' },
+ // A system's parameters are what the schedule knows about it; the World
+ // escape hatch has to say what it reaches for or the schedule knows nothing.
+ { id: 'system-access', run: 'node tools/check-system-access.mjs' },
{ id: 'project-settings', run: 'node tools/check-project-settings.mjs' },
{ id: 'workflows', run: 'node tools/check-workflows.mjs' },
{ id: 'tool-calls', run: 'node tools/check-tool-calls.mjs' },
diff --git a/tools/lib/apiSnapshot.mjs b/tools/lib/apiSnapshot.mjs
index c5d3bfa2b..9d10e080b 100644
--- a/tools/lib/apiSnapshot.mjs
+++ b/tools/lib/apiSnapshot.mjs
@@ -46,6 +46,21 @@ export function promisedBody(body) {
return body.split('\n').filter((l) => !l.startsWith('@internal ')).join('\n');
}
+
+/**
+ * Whether `after` only ADDS optional members to `before` — an addition that
+ * breaks nobody, since existing code constructs the value without the field.
+ * A snapshot renders an optional member as `name: T | undefined`, and that
+ * spelling is what makes the addition safe, so it is what this looks for.
+ */
+export function isAdditiveMembers(before, after) {
+ const was = before.split('\n').filter(Boolean);
+ const now = new Set(after.split('\n').filter(Boolean));
+ if (was.some((line) => !now.has(line))) return false;
+ const added = [...now].filter((line) => !was.includes(line));
+ return added.length > 0 && added.every((line) => /:\s.*\|\s*undefined$/.test(line));
+}
+
/**
* Compare one entry against its released self. Only @public carries a promise,
* so only @public produces a failure; @beta is noted because "may adjust" should
@@ -66,7 +81,12 @@ export function baselineFindings(was, now) {
} else if (after.kind !== before.kind) {
failures.push(`${name} — @public ${before.kind} became a ${after.kind}`);
} else if (promisedBody(after.body) !== promisedBody(before.body)) {
- failures.push(`${name} — @public signature changed`);
+ if (before.kind === 'interface'
+ && isAdditiveMembers(promisedBody(before.body), promisedBody(after.body))) {
+ notes.push(`${name} — @public interface gained an optional member`);
+ } else {
+ failures.push(`${name} — @public signature changed`);
+ }
}
} else if (before.tier === 'beta') {
if (!after) notes.push(`${name} — @beta removed`);