@wildshard/shard-format 0.86.0 → 0.87.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wildshard/shard-format",
3
- "version": "0.86.0",
3
+ "version": "0.87.1",
4
4
  "description": "The raw shardfile format: the spec, the validator and a validate CLI. The public, versioned contract every other repo builds on.",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {
@@ -315,6 +315,7 @@
315
315
  "./registeredJson": "./src/format/registeredJson.ts",
316
316
  "./returnProgramDocument": "./src/format/returnProgramDocument.ts",
317
317
  "./returnProjectionV2": "./src/format/returnProjectionV2.ts",
318
+ "./sim-reads-v2": "./src/format/sim-reads-v2.ts",
318
319
  "./riding": "./src/format/riding.ts",
319
320
  "./riggedHulls": "./src/format/riggedHulls.ts",
320
321
  "./roamingBossProjection": "./src/format/roamingBossProjection.ts",
@@ -20,6 +20,8 @@ export const HEADLESS_CONTEXT_SECTIONS = [
20
20
  'client/plan',
21
21
  // SHARD-COMPAT HS6: the server reads its feature rows (the portal ride among them) from its own plan only.
22
22
  'server/plan',
23
+ // WASM-HOST H18: what the sim reads of a body or a slot, which the server runs as project modules.
24
+ 'sim/reads',
23
25
  ] as const
24
26
 
25
27
  /** Explicit admitted decision/move context crossing the worker boundary; no ABI is inferred from bytes. */
@@ -325,6 +325,7 @@ import {
325
325
  FarSchema,
326
326
  SpawnSchema,
327
327
  } from './shardSections.ts'
328
+ import { SimReadsV2Schema } from './sim-reads-v2.ts'
328
329
  import {
329
330
  CreatureSkinClipNameSchema,
330
331
  SkinClipNameSchema,
@@ -792,6 +793,7 @@ const wireRoots: Readonly<Record<string, GenericSchema>> = {
792
793
  'practiceCourseRows.Controller': PracticeControllerSchema,
793
794
  'scalarChannel.ScalarTriplet': ScalarTripletSchema,
794
795
  'returnProjectionV2.ReturnProjectionV2': ReturnProjectionV2Schema,
796
+ 'sim-reads-v2.SimReadsV2': SimReadsV2Schema,
795
797
  'scriptContract.ReturnModules': ReturnModulesSchema,
796
798
  'nativePhysics.NativeGroundFile': NativeGroundFileSchema,
797
799
  'worldAssembly.WorldAssembly': WorldAssemblySchema,
@@ -66,6 +66,7 @@ const DATA_SECTION_NAMES: Readonly<Record<keyof PlatformDataSections, true>> = {
66
66
  "server/world": true,
67
67
  "view/modules": true,
68
68
  "sim/modules": true,
69
+ "sim/reads": true,
69
70
  "held/arms": true,
70
71
  "held/gear": true,
71
72
  "held/finishes": true,
@@ -1,6 +1,8 @@
1
1
  import * as v from 'valibot';
2
2
  import { AmbientFlockSchema, AmbientPerchesSchema, ForagerPopulationSchema } from './ambientLife.ts';
3
3
  import { CrowdWeaponTargetSchema } from './crowds.ts';
4
+ import { ReturnProjectionV2Schema } from './returnProjectionV2.ts';
5
+ import type { ReturnProjectionV2Rows, ReturnProjectionV2RowsInput } from './returnProjectionV2.ts';
4
6
 
5
7
  const id = v.pipe(v.string(), v.minLength(1), v.maxLength(128));
6
8
  const number = v.pipe(v.number(), v.finite());
@@ -8,6 +10,8 @@ const nonnegative = v.pipe(number, v.minValue(0), v.maxValue(1000000));
8
10
  const count = v.pipe(nonnegative, v.integer(), v.maxValue(256));
9
11
  const range = v.pipe(v.tuple([number, number]), v.check(([lo, hi]) => lo <= hi));
10
12
  const system = v.strictObject({ id, after: v.array(id), before: v.array(id) });
13
+ /** WASM-HOST H13: a programme may run as its v2 projection (a page-only `view` project row; Pine's ambient rules). */
14
+ const program = v.strictObject({ script: v.unknown(), bytes: v.string(), v2: v.exactOptional(ReturnProjectionV2Schema) });
11
15
  /** Client ambient ownership over actual flock, journal, tool and actor services.
12
16
  * Rules are stateless ABI-v1 projections; no executable shard ports cross rows. */
13
17
  export const PageLifeSchema: v.GenericSchema<PageLifeRowsInput, PageLifeRows> = v.strictObject({
@@ -24,7 +28,7 @@ export const PageLifeSchema: v.GenericSchema<PageLifeRowsInput, PageLifeRows> =
24
28
  combat: v.exactOptional(v.strictObject({ target: CrowdWeaponTargetSchema, preyY: number,
25
29
  hits: v.pipe(v.array(v.tuple([number, number, v.pipe(number, v.minValue(0.001), v.maxValue(20))])), v.minLength(1), v.maxLength(16)) })),
26
30
  })), v.maxLength(16)),
27
- program: v.exactOptional(v.strictObject({ script: v.unknown(), bytes: v.string() })),
31
+ program: v.exactOptional(program),
28
32
  carcasses: v.exactOptional(v.strictObject({ group: id, arrival: range, visitors: v.record(id, count),
29
33
  bodyWidths: v.record(id, nonnegative), defaultWidth: nonnegative, defaultVisitors: count,
30
34
  giveUp: nonnegative, reach: nonnegative, tint: nonnegative, untrackedAge: nonnegative, harvestDelay: nonnegative })),
@@ -104,6 +108,7 @@ interface PageLifeRowsInputFields {
104
108
  program?: {
105
109
  script: unknown;
106
110
  bytes: string;
111
+ v2?: ReturnProjectionV2RowsInput;
107
112
  };
108
113
  carcasses?: {
109
114
  group: string;
@@ -228,6 +233,7 @@ interface PageLifeRowsFields {
228
233
  program?: {
229
234
  script: unknown;
230
235
  bytes: string;
236
+ v2?: ReturnProjectionV2Rows;
231
237
  };
232
238
  carcasses?: {
233
239
  group: string;
@@ -35,6 +35,8 @@ import { WorldPhysicsSchema, type WorldPhysics } from './worldPhysics.ts';
35
35
  import { WorldTargetsSchema, type WorldTargets } from './worldTargets.ts';
36
36
  import { WorldMoversSchema } from './movers.ts';
37
37
  import { SimModulesSchema } from './numeric-frame-v2.ts';
38
+ import { SimReadsV2Schema } from './sim-reads-v2.ts';
39
+ import type { SimReadV2Row } from './sim-reads-v2.ts';
38
40
  import { ReturnModulesSchema, type ReturnModuleRow, ViewModulesSchema, type ViewModuleRow } from './scriptContract.ts';
39
41
  import { NativeRuntimePlanSchema, type NativeRuntimePlanData } from './nativeRuntimePlan.ts';
40
42
  import { TreeSetSchema, type TreeSetRows } from './treeSetRows.ts';
@@ -63,6 +65,8 @@ export interface PlatformDataSections {
63
65
  'server/world': ServerWorld;
64
66
  'view/modules': ViewModuleRow[];
65
67
  'sim/modules': v.InferOutput<typeof SimModulesSchema>;
68
+ /** WASM-HOST H18: what the sim reads of a body or slot, as project modules the server runs (simReadsV2.ts). */
69
+ 'sim/reads': SimReadV2Row[];
66
70
  'held/arms': HeldArmsRows;
67
71
  'held/gear': HeldGearRows;
68
72
  'held/finishes': HeldFinishesRows;
@@ -106,6 +110,7 @@ export const PLATFORM_DATA_SECTIONS: Readonly<{ [Name in keyof PlatformDataSecti
106
110
  'server/world': { schema: ServerWorldSchema },
107
111
  'view/modules': { schema: ViewModulesSchema },
108
112
  'sim/modules': { schema: SimModulesSchema },
113
+ 'sim/reads': { schema: SimReadsV2Schema },
109
114
  'held/arms': { schema: HeldArmsSchema },
110
115
  'held/gear': { schema: HeldGearSchema },
111
116
  'held/finishes': { schema: HeldFinishesSchema },
@@ -0,0 +1,93 @@
1
+ // WASM-HOST H13: a page-only host's programme may run a v2 return projection. Its admitted row is then the
2
+ // `actors/return-scripts` project row naming the projection's module, which must be a `view` row (the server never
3
+ // installs one); the programme's ABI-1 script is only the witness that module names.
4
+ import { propOf, textOf } from './script-view-returns.ts'
5
+
6
+ /** The ABI a project row declares. */
7
+ const PROJECTION_ABI = 2
8
+
9
+ /** A page-only host's programme, its script row and the projection it may carry. */
10
+ interface HostedProgram {
11
+ readonly kind: string
12
+ readonly file: string
13
+ readonly script: unknown
14
+ readonly v2: unknown
15
+ }
16
+
17
+ /** The `v2` of the programme whose script row sits at `host` (the row's parent). */
18
+ function programProjection(
19
+ document: unknown,
20
+ host: readonly string[],
21
+ ): unknown {
22
+ let found = document
23
+ for (const key of host.filter((name: string): boolean => name !== 'script')) {
24
+ found = propOf(found, key)
25
+ }
26
+ return propOf(found, 'v2')
27
+ }
28
+
29
+ /** The value at `keys` under `value`, or `undefined`. */
30
+ function pathOf(value: unknown, keys: readonly string[]): unknown {
31
+ let found = value
32
+ for (const key of keys) {
33
+ found = propOf(found, key)
34
+ }
35
+ return found
36
+ }
37
+
38
+ /** Whether two JSON values are equal by value, whatever their key order. */
39
+ function sameJson(left: unknown, right: unknown): boolean {
40
+ if (Array.isArray(left) || Array.isArray(right)) {
41
+ return (
42
+ Array.isArray(left) &&
43
+ Array.isArray(right) &&
44
+ left.length === right.length &&
45
+ left.every((item: unknown, at: number): boolean =>
46
+ sameJson(item, right[at]),
47
+ )
48
+ )
49
+ }
50
+ if (typeof left !== 'object' || left === null) {
51
+ return left === right
52
+ }
53
+ const keys = Object.keys(left)
54
+ return (
55
+ typeof right === 'object' &&
56
+ right !== null &&
57
+ Object.keys(right).length === keys.length &&
58
+ keys.every((key: string): boolean =>
59
+ sameJson(propOf(left, key), propOf(right, key)),
60
+ )
61
+ )
62
+ }
63
+
64
+ /** A page-only programme that runs a v2 projection, as refusal lines; `gameplay` refuses a witness that writes any. */
65
+ function pageOnlyProjectionRefusal(
66
+ hosted: HostedProgram,
67
+ returns: readonly unknown[],
68
+ gameplay: (script: unknown, file: string) => string[],
69
+ ): string[] {
70
+ const { file, kind, script, v2 } = hosted
71
+ const id = textOf(script, 'id') ?? '(no id)'
72
+ const hash = textOf(propOf(v2, 'artifact'), 'hash') ?? ''
73
+ const admitted = returns.find(
74
+ (row: unknown): boolean =>
75
+ propOf(row, 'abi') === PROJECTION_ABI &&
76
+ textOf(row, 'module') === `blobs/wasm/${hash}.wasm`,
77
+ )
78
+ if (admitted === undefined) {
79
+ return [
80
+ `${kind} program ${id} (${file}) runs a v2 module that is not an actors/return-scripts row`,
81
+ ]
82
+ }
83
+ const side =
84
+ textOf(admitted, 'side') === 'view'
85
+ ? []
86
+ : [
87
+ `sim script ${id} runs in page-only feature ${kind} (${file}), which no server host runs`,
88
+ ]
89
+ return [...side, ...gameplay(script, file)]
90
+ }
91
+
92
+ export { pageOnlyProjectionRefusal, pathOf, programProjection, sameJson }
93
+ export type { HostedProgram }
@@ -7,6 +7,12 @@
7
7
  import { CLIENT_FEATURE_SIDES } from './feature-sides.ts'
8
8
  import { parseNamedJson } from './json.ts'
9
9
  import { splitGrandfathered } from './script-side-grandfather.ts'
10
+ import {
11
+ pageOnlyProjectionRefusal,
12
+ pathOf,
13
+ programProjection,
14
+ sameJson,
15
+ } from './script-side-projections.ts'
10
16
  import {
11
17
  propOf,
12
18
  rowsOf,
@@ -17,6 +23,7 @@ import {
17
23
  import type { FeatureSide } from './feature-sides.ts'
18
24
  import type { OutputIndex } from './outputIndex.ts'
19
25
  import type { ScriptSideShardfile } from './script-side-grandfather.ts'
26
+ import type { HostedProgram } from './script-side-projections.ts'
20
27
  import type { NamedFiles } from './script-view-returns.ts'
21
28
  import type { ScriptV1CommandName } from './scriptAbiV1.ts'
22
29
  import type { V2Lane } from './scriptFuelV2.ts'
@@ -80,69 +87,46 @@ interface UncheckedFiles {
80
87
  ) => boolean
81
88
  }
82
89
 
83
- /** The value at `keys` under `value`, or `undefined`. */
84
- function pathOf(value: unknown, keys: readonly string[]): unknown {
85
- let found = value
86
- for (const key of keys) {
87
- found = propOf(found, key)
88
- }
89
- return found
90
- }
91
-
92
- /** Whether two JSON values are equal by value, whatever their key order. */
93
- function sameJson(left: unknown, right: unknown): boolean {
94
- if (Array.isArray(left) || Array.isArray(right)) {
95
- return (
96
- Array.isArray(left) &&
97
- Array.isArray(right) &&
98
- left.length === right.length &&
99
- left.every((item: unknown, at: number): boolean =>
100
- sameJson(item, right[at]),
101
- )
102
- )
103
- }
104
- if (typeof left !== 'object' || left === null) {
105
- return left === right
106
- }
107
- const keys = Object.keys(left)
108
- return (
109
- typeof right === 'object' &&
110
- right !== null &&
111
- Object.keys(right).length === keys.length &&
112
- keys.every((key: string): boolean =>
113
- sameJson(propOf(left, key), propOf(right, key)),
114
- )
115
- )
116
- }
117
-
118
- /** A page-only host feature's kind, file and the script row inside that file, or `undefined`. */
90
+ /** A page-only host feature's kind, file, the script row inside that file and the projection its programme carries
91
+ * (WASM-HOST H13), or `undefined`. */
119
92
  function hostedScript(
120
93
  feature: unknown,
121
94
  named: NamedJson,
122
- ): { kind: string; file: string; script: unknown } | undefined {
95
+ ): HostedProgram | undefined {
123
96
  const kind = textOf(feature, 'kind') ?? ''
124
97
  const host = PAGE_ONLY_PROGRAM_HOSTS.get(kind)
125
98
  const file = textOf(feature, 'file')
126
- const script =
127
- host === undefined || file === undefined
128
- ? undefined
129
- : pathOf(named(file), host)
130
- return script === undefined || file === undefined
99
+ if (host === undefined || file === undefined) {
100
+ return undefined
101
+ }
102
+ const document = named(file)
103
+ const script = pathOf(document, host)
104
+ return script === undefined
131
105
  ? undefined
132
- : { file, kind, script }
106
+ : { file, kind, script, v2: programProjection(document, host) }
107
+ }
108
+
109
+ /** A view script's refusal when it writes gameplay (any command but a timer, a cue and a channel), or nothing. */
110
+ function viewGameplayRefusal(script: unknown, file: string): string[] {
111
+ const views: readonly string[] = [...SCRIPT_V1_VIEW_COMMANDS]
112
+ const viewOnly = rowsOf(propOf(script, 'commands')).every(
113
+ (command: unknown): boolean =>
114
+ views.some((name: string): boolean => name === command),
115
+ )
116
+ return viewOnly
117
+ ? []
118
+ : [
119
+ `view script ${textOf(script, 'id') ?? '(no id)'} (${file}): ${VIEW_WRITES_GAMEPLAY}`,
120
+ ]
133
121
  }
134
122
 
135
123
  /** The script a page-only host feature runs, as refusal lines: a copy that is not its admitted `actors/return-scripts`
136
- * row (so its side and rules are the admitted row's), or a `sim` row, which no server host runs there. */
124
+ * row (so its side and rules are the admitted row's), or a `sim` row, which no server host runs there. A programme on
125
+ * a v2 projection answers to its project row instead (`script-side-projections.ts`). */
137
126
  function pageOnlyRefusal(
138
- feature: unknown,
139
- named: NamedJson,
127
+ hosted: HostedProgram,
140
128
  returns: readonly unknown[],
141
129
  ): string[] {
142
- const hosted = hostedScript(feature, named)
143
- if (hosted === undefined) {
144
- return []
145
- }
146
130
  const { file, kind, script } = hosted
147
131
  const id = textOf(script, 'id') ?? '(no id)'
148
132
  const admitted = returns.find(
@@ -160,6 +144,19 @@ function pageOnlyRefusal(
160
144
  : []
161
145
  }
162
146
 
147
+ /** A page-only host's programme, as refusal lines: on a v2 projection it answers to its project row. */
148
+ function hostedRefusal(
149
+ hosted: HostedProgram | undefined,
150
+ returns: readonly unknown[],
151
+ ): string[] {
152
+ if (hosted === undefined) {
153
+ return []
154
+ }
155
+ return hosted.v2 === undefined
156
+ ? pageOnlyRefusal(hosted, returns)
157
+ : pageOnlyProjectionRefusal(hosted, returns, viewGameplayRefusal)
158
+ }
159
+
163
160
  /** A `view` row in `sim/scripts`, as a refusal line, or nothing. */
164
161
  function serverViewRefusal(row: unknown): string[] {
165
162
  if (textOf(row, 'side') !== 'view') {
@@ -180,7 +177,7 @@ function scriptSideRefusals(
180
177
  const features = rowsOf(propOf(sections.get('client/plan'), 'features'))
181
178
  const returns = rowsOf(sections.get('actors/return-scripts'))
182
179
  const hosted = features.flatMap((feature: unknown): string[] =>
183
- pageOnlyRefusal(feature, named, returns),
180
+ hostedRefusal(hostedScript(feature, named), returns),
184
181
  )
185
182
  const decisions = rowsOf(sections.get('sim/scripts')).flatMap(
186
183
  (row: unknown): string[] => serverViewRefusal(row),
@@ -26,8 +26,10 @@ export const ViewModulesSchema: v.GenericSchema<ViewModuleRowsInput, ViewModuleR
26
26
 
27
27
  const OwnedSimModuleSchema: v.GenericSchema<OwnedSimModuleRowsInput, OwnedSimModuleRows> = v.strictObject({ ...ViewModuleSchema.entries,side: v.literal('sim'),lane: v.literal('sim') });
28
28
  /** Stateless project modules use the same persistent inventory as legacy return
29
- * policies, never view or scheduled spawn declarations. */
30
- const ProjectModuleSchema = v.strictObject({ ...ViewModuleSchema.entries,side: v.literal('sim'),lane: v.literal('project') });
29
+ * policies, never view or scheduled spawn declarations. WASM-HOST H13: a `view`
30
+ * one is a page-only projection (`page.life`'s ambient rules); the server never
31
+ * installs a `view` return row. */
32
+ const ProjectModuleSchema = v.strictObject({ ...ViewModuleSchema.entries,side: v.picklist(['sim','view']),lane: v.literal('project') });
31
33
  const ProjectReturnModulesSchema = v.pipe(v.unknown(),v.check(isJsonData,'plain JSON return modules'),
32
34
  v.array(v.union([DecisionScriptsSchema.pipe[2].item,ProjectModuleSchema])),v.maxLength(64),
33
35
  v.check(rows=>new Set(rows.map(row=>row.id)).size===rows.length,'unique return module ids'),
@@ -163,9 +165,9 @@ export type ViewModuleRowsInput = (ViewModuleRowInput)[];
163
165
  export type ViewModuleRows = (ViewModuleRow)[];
164
166
  export type ReturnModuleRowsInput = unknown;
165
167
  export type ReturnModuleRows = (v.InferOutput<typeof DecisionScriptsSchema>) | (((v.InferOutput<(typeof DecisionScriptsSchema)['pipe'][2]['item']>) | (Omit<ViewModuleRow, keyof ({
166
- side: 'sim';
168
+ side: 'sim' | 'view';
167
169
  lane: 'project';
168
170
  })> & {
169
- side: 'sim';
171
+ side: 'sim' | 'view';
170
172
  lane: 'project';
171
173
  }))[]);
@@ -14,6 +14,7 @@ import type { ServerHosts } from './server-hosts.ts';
14
14
  import type { ServerWorld } from './server-world.ts';
15
15
  import type { NativeSweptPolicyRows } from './items.ts';
16
16
  import type { OwnedSimModuleRows, ReturnModuleRow, ViewModuleRow } from './scriptContract.ts';
17
+ import type { SimReadV2Row } from './sim-reads-v2.ts';
17
18
  import type { WorldScenesSection } from './worldScenes.ts';
18
19
  import type { TreeSetRows } from './treeSetRows.ts';
19
20
  import type { Vehicles } from './vehicles.ts';
@@ -56,6 +57,8 @@ export interface PlatformSections {
56
57
  'view/modules': ViewModuleRow[];
57
58
  /** WASM-HOST H13: the ABI v2 modules numeric hosts run. */
58
59
  'sim/modules': OwnedSimModuleRows[];
60
+ /** WASM-HOST H18: what the sim reads of a body or slot, as project modules the server runs. */
61
+ 'sim/reads': SimReadV2Row[];
59
62
  /** Client-only ordered model references, ignored by simulation. */
60
63
  'explore/catalogue': ExplorerCatalogue;
61
64
  'look/toon': ToonLookRow;
@@ -0,0 +1,169 @@
1
+ /* oxlint-disable curly, no-magic-numbers, import/exports-last, import/group-exports, typescript/explicit-function-return-type, typescript/prefer-readonly-parameter-types, unicorn/max-nested-calls -- one small schema module: its bounds are its contract, named once beside their checks */
2
+ /** WASM-HOST H18 (W18): a sim read. Whatever the sim reads (a body's height, a slot's pose) runs on the server, never in
3
+ * a view module. A sim read is a stateless ABI v2 project module (a ReturnProjectionV2 row) the server runs at the sim
4
+ * rate, 10 Hz or 30 Hz with a written reason (W9), over one target:
5
+ *
6
+ * - `species`: one request per live body of that species, up to `count`. Its fields are the body's: `dt`, `alive`,
7
+ * `ground`, `x`, `y`, `z`, `yaw`, `seed`, `scale`, `attackPhase`, `mem:<key>` and `has:<key>` (its memory, and
8
+ * whether it holds that key). Its channels: `yOffset`, the body's height over its ground, which the sim reads.
9
+ * - `slot`: one request for the named slot a native owner lends (a fight's frame slot). Its fields are `dt` and
10
+ * `source:<name>`, the values the slot lends; its channels are `cell:<name>`, the cells it reads back.
11
+ *
12
+ * Both may carry state from call to call: each `carry` name is a field `carry:<name>` and a channel of the same name,
13
+ * kept per body (or for the slot) by the server and saved as a named column, never guest memory (H7). A body's carries
14
+ * start at zero; a new body (another seed) starts its own. The page runs its own view modules for what it draws. */
15
+ import {
16
+ array,
17
+ check,
18
+ exactOptional,
19
+ integer,
20
+ literal,
21
+ maxLength,
22
+ maxValue,
23
+ minLength,
24
+ minValue,
25
+ number,
26
+ picklist,
27
+ pipe,
28
+ regex,
29
+ strictObject,
30
+ string,
31
+ variant,
32
+ } from 'valibot'
33
+
34
+ import { ReturnProjectionV2Schema } from './returnProjectionV2.ts'
35
+
36
+ import type { ReturnProjectionV2Rows } from './returnProjectionV2.ts'
37
+ import type { GenericSchema } from 'valibot'
38
+
39
+ /** The most carried values one sim read keeps per body or slot. */
40
+ export const SIM_READ_CARRIES = 16
41
+ /** The most bodies one species sim read reads. */
42
+ export const SIM_READ_BODIES = 64
43
+ /** A species read's body fields, besides `mem:` and `has:` keys and carries. */
44
+ export const SIM_READ_BODY_FIELDS: readonly string[] = Object.freeze([
45
+ 'dt',
46
+ 'alive',
47
+ 'ground',
48
+ 'x',
49
+ 'y',
50
+ 'z',
51
+ 'yaw',
52
+ 'seed',
53
+ 'scale',
54
+ 'attackPhase',
55
+ ])
56
+ /** A species read's body outputs, besides carries. */
57
+ export const SIM_READ_BODY_OUTPUTS: readonly string[] = Object.freeze([
58
+ 'yOffset',
59
+ ])
60
+
61
+ const name = pipe(
62
+ string(),
63
+ minLength(1),
64
+ maxLength(128),
65
+ regex(/^[a-z][a-zA-Z0-9.-]*$/u),
66
+ )
67
+ const SpeciesTarget = strictObject({
68
+ kind: literal('species'),
69
+ species: name,
70
+ count: pipe(number(), integer(), minValue(1), maxValue(SIM_READ_BODIES)),
71
+ })
72
+ const SlotTarget = strictObject({ kind: literal('slot'), slot: name })
73
+
74
+ export interface SimReadV2Row {
75
+ readonly id: string
76
+ readonly target:
77
+ | {
78
+ readonly kind: 'species'
79
+ readonly species: string
80
+ readonly count: number
81
+ }
82
+ | { readonly kind: 'slot'; readonly slot: string }
83
+ readonly tick: 10 | 30
84
+ readonly tickReason?: string
85
+ readonly carry: readonly string[]
86
+ readonly projection: ReturnProjectionV2Rows
87
+ }
88
+
89
+ function fieldOk(row: SimReadV2Row, field: string): boolean {
90
+ if (field.startsWith('carry:'))
91
+ return row.carry.includes(field.slice('carry:'.length))
92
+ if (row.target.kind === 'slot')
93
+ return (
94
+ field === 'dt' ||
95
+ (field.startsWith('source:') && field.length > 'source:'.length)
96
+ )
97
+ return (
98
+ SIM_READ_BODY_FIELDS.includes(field) || /^(?:mem|has):[\w.-]+$/u.test(field)
99
+ )
100
+ }
101
+ function channelOk(row: SimReadV2Row, channel: string): boolean {
102
+ if (channel.startsWith('carry:'))
103
+ return row.carry.includes(channel.slice('carry:'.length))
104
+ return row.target.kind === 'slot'
105
+ ? channel.startsWith('cell:') && channel.length > 'cell:'.length
106
+ : SIM_READ_BODY_OUTPUTS.includes(channel)
107
+ }
108
+ /** Every problem with one row's names, or none. */
109
+ export function simReadProblems(row: SimReadV2Row): string[] {
110
+ const problems: string[] = [],
111
+ { fields, channels } = row.projection
112
+ for (const field of fields)
113
+ if (!fieldOk(row, field)) problems.push(`${row.id} reads no field ${field}`)
114
+ for (const channel of channels)
115
+ if (!channelOk(row, channel))
116
+ problems.push(`${row.id} writes no output ${channel}`)
117
+ for (const carry of row.carry) {
118
+ if (
119
+ !fields.includes(`carry:${carry}`) ||
120
+ !channels.includes(`carry:${carry}`)
121
+ )
122
+ problems.push(`${row.id} carries ${carry} without its field and channel`)
123
+ }
124
+ if (new Set(row.carry).size !== row.carry.length)
125
+ problems.push(`${row.id} carries a name twice`)
126
+ if ((row.tick === 30) !== (row.tickReason !== undefined))
127
+ problems.push(
128
+ `${row.id} needs a written reason exactly when it runs at 30 Hz`,
129
+ )
130
+ if (row.projection.batch !== undefined || row.projection.groups !== undefined)
131
+ problems.push(`${row.id} asks one request at a time`)
132
+ return problems
133
+ }
134
+
135
+ const SimReadV2Schema: GenericSchema<unknown, SimReadV2Row> = pipe(
136
+ strictObject({
137
+ id: name,
138
+ target: variant('kind', [SpeciesTarget, SlotTarget]),
139
+ tick: picklist([10, 30]),
140
+ tickReason: exactOptional(pipe(string(), minLength(8), maxLength(512))),
141
+ carry: pipe(array(name), maxLength(SIM_READ_CARRIES)),
142
+ projection: ReturnProjectionV2Schema,
143
+ }),
144
+ check(
145
+ row => simReadProblems(row as SimReadV2Row).length === 0,
146
+ "a sim read reads only its target's fields and writes only its outputs and carries",
147
+ ),
148
+ )
149
+
150
+ /** The `sim/reads` section: optional; ids are unique, and no two reads write one species or slot. */
151
+ export const SimReadsV2Schema: GenericSchema<unknown, SimReadV2Row[]> = pipe(
152
+ array(SimReadV2Schema),
153
+ maxLength(16),
154
+ check(
155
+ rows => new Set(rows.map(row => row.id)).size === rows.length,
156
+ 'unique sim read ids',
157
+ ),
158
+ check(
159
+ rows =>
160
+ new Set(
161
+ rows.map(row =>
162
+ row.target.kind === 'slot'
163
+ ? `slot:${row.target.slot}`
164
+ : `species:${row.target.species}`,
165
+ ),
166
+ ).size === rows.length,
167
+ 'one sim read per species or slot',
168
+ ),
169
+ )
@@ -154,6 +154,9 @@
154
154
  "shard-format admitScriptContract"
155
155
  ]
156
156
  },
157
+ "sim/reads": {
158
+ "hosts": ["server installSimReads", "shard-format SimReadsV2Schema"]
159
+ },
157
160
  "sim/plumbing": {
158
161
  "hosts": ["page installDeclaredPlumbing"]
159
162
  },