@wildshard/shard-format 0.84.0 → 0.86.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wildshard/shard-format",
3
- "version": "0.84.0",
3
+ "version": "0.86.0",
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": {
@@ -26,16 +26,32 @@ for (const [kind, capacity] of Object.entries(CAPACITY)) {
26
26
  capacities.set(Number(kind), capacity)
27
27
  }
28
28
  const DECISION_V2_CAPACITIES: ReadonlyMap<number, number> = capacities
29
+ /** WASM-HOST H8: a row with `inputs` adds the player bank (8 seats, W28) and 32 input edges to the frame. */
30
+ const INPUT_CAPACITY: Readonly<Record<number, number>> = {
31
+ ...CAPACITY,
32
+ 7: 8,
33
+ 8: 32,
34
+ }
35
+ const inputCapacities = new Map<number, number>()
36
+ for (const [kind, capacity] of Object.entries(INPUT_CAPACITY)) {
37
+ inputCapacities.set(Number(kind), capacity)
38
+ }
39
+ const DECISION_V2_INPUT_CAPACITIES: ReadonlyMap<number, number> =
40
+ inputCapacities
29
41
  /** List replies are keyed `DECISION_V2_LIST_KEY + list op`, apart from read ops. */
30
42
  const DECISION_V2_LIST_KEY = 1000
31
43
  const DECISION_V2_IO = 0
32
- /** The I/O frame a decision module of `pages` pages admits under. */
33
- function decisionLayoutV2(pages: number): V2Layout {
34
- return layoutV2(DECISION_V2_IO, pages, DECISION_V2_CAPACITIES)
44
+ /** The I/O frame a decision module of `pages` pages admits under; `inputs` adds the seat and edge banks. */
45
+ function decisionLayoutV2(pages: number, inputs = false): V2Layout {
46
+ return layoutV2(
47
+ DECISION_V2_IO,
48
+ pages,
49
+ inputs ? DECISION_V2_INPUT_CAPACITIES : DECISION_V2_CAPACITIES,
50
+ )
35
51
  }
36
52
  /** A decision row's byte contract: ABI 1 by its pages, or (abi '2.0') the ABI 2 sim lane over its fixed decision frame. */
37
53
  function decisionContract(
38
- row: Readonly<Pick<DecisionScriptRow, 'abi' | 'pages'>>,
54
+ row: Readonly<Pick<DecisionScriptRow, 'abi' | 'inputs' | 'pages'>>,
39
55
  ): Extract<ScriptContract, { pages: number }> {
40
56
  if (row.abi === '1.0') {
41
57
  return { abi: 1, pages: row.pages }
@@ -44,7 +60,7 @@ function decisionContract(
44
60
  abi: 2,
45
61
  lane: 'sim',
46
62
  pages: row.pages,
47
- ioBytes: decisionLayoutV2(row.pages).bytes,
63
+ ioBytes: decisionLayoutV2(row.pages, row.inputs === true).bytes,
48
64
  compilerRevision: SCRIPT_V2_REVISIONS.compiler,
49
65
  admissionRevision: SCRIPT_V2_REVISIONS.admission,
50
66
  }
@@ -52,6 +68,7 @@ function decisionContract(
52
68
 
53
69
  export {
54
70
  DECISION_V2_CAPACITIES,
71
+ DECISION_V2_INPUT_CAPACITIES,
55
72
  DECISION_V2_IO,
56
73
  DECISION_V2_LIST_KEY,
57
74
  decisionContract,
@@ -11,6 +11,8 @@ const local = v.pipe(v.string(), v.regex(/^[A-Za-z_][A-Za-z0-9_.-]*$/u), v.maxLe
11
11
  const finite = v.pipe(v.number(), v.finite());
12
12
  const positive = v.pipe(finite, v.integer(), v.minValue(1), v.maxValue(0x7fffffff));
13
13
  const HIT_TAG_LENGTH = 64;
14
+ /** WASM-HOST H8 (W9): the sim lane's fast rate, and the most a row writes for why it needs it. */
15
+ const SIM_RATE = { fast: 30, reason: 200 } as const;
14
16
  const HIT_TAGS = 16;
15
17
  const hitTag = v.pipe(v.string(), v.regex(/^[a-z][a-z0-9_-]*(?:\.[a-z0-9_-]+)+$/u), v.maxLength(HIT_TAG_LENGTH));
16
18
  const hitTags = v.pipe(v.record(local, hitTag), v.check((value: Readonly<Record<string, string>>): boolean => Object.keys(value).length <= HIT_TAGS, 'at most 16 hit tags'));
@@ -35,7 +37,11 @@ const rowEntries = {
35
37
  binding: v.union([v.strictObject({ encounter: id }), v.strictObject({ quest: id }), v.strictObject({ zone: id }), v.strictObject({ shard: v.literal(true) }), v.strictObject({ spawnGroup: id }), v.strictObject({ brain: id })]),
36
38
  pages: v.optional(v.pipe(positive, v.maxValue(4)), 1), onFail: v.picklist(['hold', 'reset', 'skip']),
37
39
  on: v.pipe(v.array(v.picklist(keys(SCRIPT_V1_EVENTS))), v.minLength(1), v.maxLength(23), v.check(values => unique(values), 'unique subscribed events')),
38
- tick: v.optional(v.nullable(v.picklist([1, 2, 5, 10])), null),
40
+ // WASM-HOST H8 (W9): 10 Hz is the sim lane's rate; 30 Hz needs an ABI 2 row and its written reason.
41
+ tick: v.optional(v.nullable(v.picklist([1, 2, 5, 10, SIM_RATE.fast])), null),
42
+ tickReason: v.exactOptional(v.pipe(v.string(), v.nonEmpty(), v.maxLength(SIM_RATE.reason))),
43
+ // WASM-HOST H8: an ABI 2 row that reads its seats and their input edges (W28) in its v2 frame.
44
+ inputs: v.exactOptional(v.literal(true)),
39
45
  reads: v.pipe(v.array(v.picklist(readNames)), v.maxLength(readNames.length), v.check(values => unique(values), 'unique script reads')),
40
46
  commands: v.pipe(v.array(v.picklist(keys(SCRIPT_V1_COMMANDS))), v.maxLength(21), v.check(values => unique(values), 'unique script commands')),
41
47
  actors: v.optional(aliases, {}), moves: v.optional(aliases, {}), strikes: v.optional(aliases, {}), cues: v.optional(aliases, {}),
@@ -72,7 +78,9 @@ export function decisionScriptRowRules(script: DecisionScriptRow): string[] {
72
78
  const errors: string[] = [];
73
79
  if ('spawnGroup' in script.binding && (Object.keys(script.actors).length === 0 || script.state.some(slot => slot.scope !== 'actor')))
74
80
  errors.push('spawn groups declare members and actor-scoped simulation state');
75
- if ((script.tick !== null) !== script.on.includes('tick')) errors.push('tick subscription has a declared 1/2/5/10 Hz rate');
81
+ if ((script.tick !== null) !== script.on.includes('tick')) errors.push('tick subscription has a declared 1/2/5/10/30 Hz rate');
82
+ if ((script.tick === SIM_RATE.fast) !== (script.tickReason !== undefined)) { errors.push('a 30 Hz row, and only one, gives its written reason (W9)'); }
83
+ if ((script.tick === SIM_RATE.fast || script.inputs === true) && script.abi !== '2.0') { errors.push('30 Hz and input edges are ABI 2 sim rows'); }
76
84
  if ('brain' in script.binding && (!Object.values(script.actors).includes(script.binding.brain)
77
85
  || script.commands.some((name): boolean => name === 'move' || name === 'strike' || name === 'stop'))) {
78
86
  errors.push('a brain hook names its creature and leaves move, strike and stop to the brain');
@@ -228,7 +236,9 @@ interface DecisionScriptRowInputFields {
228
236
  pages?: number | undefined;
229
237
  onFail: 'hold' | 'reset' | 'skip';
230
238
  on: (keyof typeof SCRIPT_V1_EVENTS)[];
231
- tick?: (1 | 2 | 5 | 10) | null | undefined;
239
+ tick?: (1 | 2 | 5 | 10 | typeof SIM_RATE.fast) | null | undefined;
240
+ tickReason?: string;
241
+ inputs?: true;
232
242
  reads: ((typeof readNames)[number])[];
233
243
  commands: (keyof typeof SCRIPT_V1_COMMANDS)[];
234
244
  actors?: Record<string, string> | undefined;
@@ -286,7 +296,9 @@ interface DecisionScriptRowFields {
286
296
  pages: number;
287
297
  onFail: 'hold' | 'reset' | 'skip';
288
298
  on: (keyof typeof SCRIPT_V1_EVENTS)[];
289
- tick: (1 | 2 | 5 | 10) | null;
299
+ tick: (1 | 2 | 5 | 10 | typeof SIM_RATE.fast) | null;
300
+ tickReason?: string;
301
+ inputs?: true;
290
302
  reads: ((typeof readNames)[number])[];
291
303
  commands: (keyof typeof SCRIPT_V1_COMMANDS)[];
292
304
  actors: Record<string, string>;
@@ -9,18 +9,69 @@ import { layoutV2, type V2Layout } from './scriptWireV2.ts';
9
9
  const bindingName=v.pipe(v.string(),v.minLength(1),v.maxLength(512),v.regex(/^(?!__proto__$|prototype$|constructor$)/));
10
10
  const additionalNames=v.pipe(v.array(bindingName),v.maxLength(256));
11
11
  const names=v.pipe(v.array(bindingName),v.minLength(1),v.maxLength(256));
12
+ const queryNames=v.strictTuple([v.literal('groundHeight')]);
13
+ const queriesSchema=v.exactOptional(queryNames);
14
+ const MIN_BATCH_REQUESTS = 2;
15
+ const MAX_BATCH_REQUESTS = 64;
16
+ const MIN_BATCH_ROWS = 1;
17
+ const MAX_BATCH_ROWS = 8192;
18
+ const batchRequests=v.pipe(v.number(),v.integer(),v.minValue(MIN_BATCH_REQUESTS),v.maxValue(MAX_BATCH_REQUESTS));
19
+ const batchRowCount=v.pipe(v.number(),v.integer(),v.minValue(MIN_BATCH_ROWS),v.maxValue(MAX_BATCH_ROWS));
20
+ const batchRows=v.strictObject({requests:batchRequests,rows:batchRowCount});
21
+ const batchSchema=v.exactOptional(batchRows);
12
22
  export const ReturnProjectionV2Schema: v.GenericSchema<ReturnProjectionV2RowsInput, ReturnProjectionV2Rows> = v.strictObject({ artifact: v.strictObject({...ScriptArtifactV2Schema.entries,lane:v.literal('project')}),
13
- fields: names,signals: names,channels: names,additional:v.exactOptional(v.strictObject({fields:additionalNames,signals:additionalNames,channels:additionalNames})),outputCapacity:v.exactOptional(v.pipe(v.number(),v.integer(),v.minValue(1),v.maxValue(128))),bytes: v.pipe(v.string(),v.maxLength(2_000_000)),groups: v.exactOptional(GroupStepV2Schema) });
23
+ fields: names,signals: names,channels: names,additional:v.exactOptional(v.strictObject({fields:additionalNames,signals:additionalNames,channels:additionalNames})),outputCapacity:v.exactOptional(v.pipe(v.number(),v.integer(),v.minValue(1),v.maxValue(128))),queries:queriesSchema,batch:batchSchema,bytes: v.pipe(v.string(),v.maxLength(2_000_000)),groups: v.exactOptional(GroupStepV2Schema) });
14
24
 
15
25
  /** Nine detached field frames retain actor zero plus the original eight ordered
16
26
  * candidates. Missing fields remain absent and refuse only if actually read. */
17
- export function returnProjectionV2Layout(fields: number,pages = 1,outputCapacity = 32,groups?:GroupStepRowsV2): V2Layout {
27
+ /** WASM-HOST H13: a projection that declares `queries` may ask its owner host for the ground height under a point. A
28
+ * height the frame does not answer is a miss (kind 11: the query kind 3 and x, z); the host answers every miss (kind 12
29
+ * replies, each keyed in kind 13 by its kind and seven inputs, then its height) and runs the request again, up to
30
+ * RETURN_PROJECTION_V2_ROUNDS times. Without `queries` the frame is unchanged. */
31
+ const QUERY_MISSES = 16;
32
+ const QUERY_REPLIES = 32;
33
+ const QUERY_KEY = 8;
34
+ const QUERY_ROUNDS = 8;
35
+ const RETURN_PROJECTION_V2_QUERIES: Readonly<{ misses: number; replies: number; key: number; rounds: number }> = Object.freeze({ misses: QUERY_MISSES,replies: QUERY_REPLIES,key: QUERY_KEY,rounds: QUERY_ROUNDS });
36
+ /** WASM-HOST H13: a projection that declares `batch` also answers up to `requests` independent requests in one call (one
37
+ * reset, one crossing; R1-17). Each request has three parameters (kind 4: its signal, its first field row, its row count)
38
+ * and its fields as sparse rows (kind 6: actor * fields + field + 1, present, value; `rows` in all), and tags each output
39
+ * (kind 10) with its request index. Misses and replies scale with `requests`. */
40
+ interface ReturnProjectionV2Batch { readonly requests: number; readonly rows: number }
41
+ /** Region kinds of the projection frame. */
42
+ const KIND = Object.freeze({ binding: 1,parameters: 4,state: 5,fields: 6,outputs: 10,misses: 11,replies: 12,replyData: 13,rng: 21,rngOut: 22 });
43
+ /** Nine field frames per request: the observations and eight candidates; three parameters per batch request. */
44
+ const FRAMES = 9;
45
+ const REQUEST_PARAMETERS = 3;
46
+ const ONE = 1;
47
+ const NONE = 0;
48
+ function validBatch(batch: ReturnProjectionV2Batch): boolean {
49
+ const { requests,rows } = batch;
50
+ return Number.isInteger(requests) && requests >= MIN_BATCH_REQUESTS && requests <= MAX_BATCH_REQUESTS
51
+ && Number.isInteger(rows) && rows >= MIN_BATCH_ROWS && rows <= MAX_BATCH_ROWS;
52
+ }
53
+ /** The banks a request (or a batch of them) and its ground-height queries need, as [kind, capacity]. */
54
+ function projectionBanks(fields: number,outputCapacity: number,asks: { readonly queries?: readonly ['groundHeight']; readonly batch?: ReturnProjectionV2Batch }): (readonly [number,number])[] {
55
+ const { batch,queries } = asks;
56
+ const requests = batch?.requests ?? ONE;
57
+ const banks: (readonly [number,number])[] = [[KIND.binding,ONE],[KIND.state,ONE],[KIND.rng,ONE],[KIND.rngOut,ONE],
58
+ [KIND.parameters,batch === undefined ? ONE : REQUEST_PARAMETERS*requests],[KIND.fields,Math.max(fields*FRAMES,batch?.rows ?? NONE)],[KIND.outputs,outputCapacity*requests]];
59
+ if (queries !== undefined) {
60
+ banks.push([KIND.misses,QUERY_MISSES*requests],[KIND.replies,QUERY_REPLIES*requests],[KIND.replyData,QUERY_REPLIES*requests*(QUERY_KEY+ONE)]);
61
+ }
62
+ return banks;
63
+ }
64
+ export function returnProjectionV2Layout(fields: number,pages = 1,outputCapacity = 32,groups?:GroupStepRowsV2,queries?:readonly ['groundHeight'],batch?:ReturnProjectionV2Batch): V2Layout {
18
65
  if (!Number.isInteger(fields) || fields < 1 || fields > 256) throw new Error('Invalid projection field count');
19
66
  if (!Number.isInteger(outputCapacity) || outputCapacity < 1 || outputCapacity > 128) throw new Error('Invalid projection output capacity');
20
67
  if(groups!==undefined&&groups.pages!==pages)throw new Error('Shared projection pages differ');
68
+ if (batch !== undefined && (groups !== undefined || !validBatch(batch))) {
69
+ throw new Error('Invalid projection batch');
70
+ }
21
71
  const capacities=new Map(groups===undefined?[]:groupStepLayoutV2(groups).regions.map(row=>[row.kind,row.capacity]));
22
- for(const [kind,capacity]of [[1,1],[4,1],[5,1],[6,fields*9],[10,outputCapacity],[21,1],[22,1]] as const)
23
- capacities.set(kind,Math.max(capacities.get(kind)??0,capacity));
72
+ for (const [kind,capacity] of projectionBanks(fields,outputCapacity,{ ...(queries === undefined ? {} : { queries }),...(batch === undefined ? {} : { batch }) })) {
73
+ capacities.set(kind,Math.max(capacities.get(kind) ?? NONE,capacity));
74
+ }
24
75
  return layoutV2(0,pages,capacities);
25
76
  }
26
77
  export function parseReturnProjectionV2(input: unknown): ReturnProjectionV2Rows {
@@ -32,9 +83,9 @@ export function parseReturnProjectionV2(input: unknown): ReturnProjectionV2Rows
32
83
  /** Check cross-field rules after ReturnProjectionV2Schema has admitted the
33
84
  * complete shape. Unknown inputs must use parseReturnProjectionV2 instead.
34
85
  * A containing admitted schema can reuse its rows without parsing them again. */
35
- export function checkReturnProjectionV2Rows(row: ReturnProjectionV2Rows): void {
86
+ function checkReturnProjectionV2Rows(row: ReturnProjectionV2Rows): void {
36
87
  if(row.groups!==undefined)parseGroupStepV2(row.groups);
37
- if (row.artifact.ioBytes !== returnProjectionV2Layout(row.fields.length,row.artifact.pages,row.outputCapacity,row.groups).bytes
88
+ if (row.artifact.ioBytes !== returnProjectionV2Layout(row.fields.length,row.artifact.pages,row.outputCapacity,row.groups,row.queries,row.batch).bytes
38
89
  || [row.fields,row.signals,row.channels].some(list => new Set(list).size !== list.length || list.some((name,i) => i > 0 && (list[i-1] ?? '') >= name))) throw new Error('Invalid projection declaration');
39
90
  for(const kind of ['fields','signals','channels'] as const){
40
91
  const extra=row.additional?.[kind]??[],declared=row[kind],base=declared.slice(0,declared.length-extra.length);
@@ -59,6 +110,11 @@ interface ReturnProjectionV2RowsInputFields {
59
110
  channels: (string)[];
60
111
  };
61
112
  outputCapacity?: number;
113
+ queries?: ['groundHeight'];
114
+ batch?: {
115
+ requests: number;
116
+ rows: number;
117
+ };
62
118
  bytes: string;
63
119
  groups?: v.InferInput<typeof GroupStepV2Schema>;
64
120
  }
@@ -78,7 +134,13 @@ interface ReturnProjectionV2RowsFields {
78
134
  channels: (string)[];
79
135
  };
80
136
  outputCapacity?: number;
137
+ queries?: ['groundHeight'];
138
+ batch?: {
139
+ requests: number;
140
+ rows: number;
141
+ };
81
142
  bytes: string;
82
143
  groups?: v.InferOutput<typeof GroupStepV2Schema>;
83
144
  }
84
145
  export type ReturnProjectionV2Rows = { [Key in keyof ReturnProjectionV2RowsFields]: ReturnProjectionV2RowsFields[Key] };
146
+ export { checkReturnProjectionV2Rows, RETURN_PROJECTION_V2_QUERIES, type ReturnProjectionV2Batch };
@@ -1,19 +1,35 @@
1
- /* oxlint-disable capitalized-comments, complexity, curly, id-length, max-depth, max-lines-per-function, max-statements, no-magic-numbers, no-plusplus, sort-vars, typescript/explicit-function-return-type, typescript/prefer-readonly-parameter-types, unicorn/no-array-callback-reference, unicorn/number-literal-case -- the region walk of scriptFuelV2.ts's v2BlockCosts, in its form; engine test/fixtures/v2Path.ts copies it line for line until engine takes this format */
2
- /** WASM-HOST H2c: v2 fuel regions priced at their longest path. */
1
+ /* oxlint-disable complexity, curly, id-length, max-depth, max-lines-per-function, max-statements, no-continue, no-magic-numbers, no-nested-ternary, no-plusplus, sort-vars, typescript/explicit-function-return-type, typescript/prefer-readonly-parameter-types, unicorn/no-array-callback-reference, unicorn/no-array-reverse, unicorn/no-nested-ternary, unicorn/number-literal-case, import/exports-last, import/group-exports -- the region walk of scriptFuelV2.ts's v2BlockCosts, in its form; engine test/fixtures/v2Path.ts copies it line for line until engine takes this format */
2
+ /** WASM-HOST H2c: v2 fuel regions priced at their longest path, with split regions where a call may skip a big arm. */
3
3
  import type { V2Instruction } from './scriptModuleV2.ts'
4
4
 
5
- /** WASM-HOST H2c: the same regions, each priced at its longest path instead of every instruction it holds. A call that
6
- * takes one `if` arm, one `br_table` case or an early exit runs no more than that path, so the charge still covers every
7
- * instruction run and no charge is added; an if/else or a switch pays for its longest arm, not all of them (H2b read
8
- * up to 4.18x over-billing on the hot path; meta support/wasm-host/H2C-*). Edges: fall-through, `if` to its arm or
9
- * past it, `else` past its `end`, a branch to past its block's `end`, and from a nested loop to wherever its body can
10
- * leave to. A return, `unreachable`, a branch to a loop (the loop charges again) or past the region ends a path. */
11
- export function v2PathCosts(
5
+ const EXIT = -1
6
+ interface Region {
7
+ readonly start: number
8
+ readonly close: number
9
+ readonly loop: boolean
10
+ }
11
+ interface Shape {
12
+ readonly next: readonly (readonly number[])[]
13
+ readonly closes: readonly number[]
14
+ readonly loops: readonly Region[]
15
+ readonly weight: readonly number[]
16
+ }
17
+ /** WASM-HOST H2c: the smallest own longest path a split region needs, by lane. A split's charge runs on every call that
18
+ * enters it; views loop over many small arms per frame, sims and projections over few big ones (engine
19
+ * `wasm-fuel-ratio --costs=path`, meta support/wasm-host/H2C-RATIOS-2026-12-06.md). */
20
+ export const V2_SPLIT_FLOORS: Readonly<{
21
+ sim: number
22
+ project: number
23
+ view: number
24
+ }> = Object.freeze({ sim: 512, project: 512, view: 136 })
25
+
26
+ /** Each instruction's successors (EXIT for a return, `unreachable`, a branch to a loop or to the body's own label), the
27
+ * close of each instruction's structural level, the loop bodies, and each instruction's price. */
28
+ function shape(
12
29
  code: readonly V2Instruction[],
13
- constantCalls: ReadonlyMap<number, number> = new Map(),
14
- ): ReadonlyMap<number, number> {
15
- const exit = -1,
16
- ends = new Map<number, number>(),
30
+ constantCalls: ReadonlyMap<number, number>,
31
+ ): Shape {
32
+ const ends = new Map<number, number>(),
17
33
  arms = new Map<number, number>(),
18
34
  open: number[] = []
19
35
  for (let i = 0; i < code.length; i++) {
@@ -27,57 +43,147 @@ export function v2PathCosts(
27
43
  if (at !== undefined) ends.set(at, i)
28
44
  }
29
45
  }
30
- const end = (at: number): number => ends.get(at) ?? code.length - 1,
31
- next: (readonly number[])[] = [],
32
- labels: number[] = []
46
+ const end = (at: number): number => ends.get(at) ?? code.length - 1
47
+ const next: number[][] = [],
48
+ labels: number[] = [],
49
+ closes: number[] = []
33
50
  const target = (depth: number): number => {
34
51
  const at = labels[labels.length - 1 - depth]
35
- return at === undefined || code[at]?.op === 0x03 ? exit : end(at) + 1
52
+ return at === undefined || code[at]?.op === 0x03 ? EXIT : end(at) + 1
36
53
  }
37
54
  for (let i = 0; i < code.length; i++) {
55
+ const top = labels.at(-1),
56
+ arm = top === undefined ? undefined : arms.get(top)
57
+ closes.push(
58
+ top === undefined
59
+ ? code.length - 1
60
+ : arm !== undefined && i <= arm
61
+ ? arm
62
+ : end(top),
63
+ )
38
64
  const value = code[i],
39
65
  op = value?.op
40
66
  if (op === 0x0c) next.push([target(value?.args[0] ?? 0)])
41
67
  else if (op === 0x0d) next.push([i + 1, target(value?.args[0] ?? 0)])
42
68
  else if (op === 0x0e) next.push((value?.args ?? []).map(target))
43
- else if (op === 0x0f || op === 0x00) next.push([exit])
69
+ else if (op === 0x0f || op === 0x00) next.push([EXIT])
44
70
  else if (op === 0x04) next.push([i + 1, (arms.get(i) ?? end(i)) + 1])
45
- else if (op === 0x05) next.push([end(labels.at(-1) ?? -1) + 1])
71
+ else if (op === 0x05) next.push([end(top ?? -1) + 1])
46
72
  else next.push([i + 1])
47
73
  if (op === 0x02 || op === 0x03 || op === 0x04) labels.push(i)
48
74
  else if (op === 0x0b) labels.pop()
49
75
  }
50
- const costs = new Map<number, number>(),
51
- longest: number[] = []
52
- for (const [start, close] of [
53
- [0, code.length - 1],
54
- ...[...ends]
55
- .filter(([at]) => code[at]?.op === 0x03)
56
- .map(([at, last]) => [at + 1, last]),
57
- ]) {
58
- if (start === undefined || close === undefined)
59
- throw new Error('Invalid v2 region')
60
- for (let at = close; at >= start; at--) {
61
- const op = code[at]?.op
62
- let after = next[at] ?? [exit]
63
- if (op === 0x03) {
64
- // a nested loop is its own region; the path goes on wherever its body can leave to
65
- const last = end(at),
66
- out = new Set([last + 1])
67
- for (let j = at + 1; j <= last; j++)
68
- for (const to of next[j] ?? [])
69
- if (to !== exit && (to <= at || to > last + 1)) out.add(to)
70
- after = [...out]
71
- }
72
- let best = 0
73
- for (const to of after)
74
- if (to >= start && to <= close) best = Math.max(best, longest[to] ?? 0)
75
- longest[at] =
76
- 1 +
77
- (op === 0x10 ? (constantCalls.get(code[at]?.args[0] ?? -1) ?? 0) : 0) +
78
- best
76
+ const loops = [...ends]
77
+ .filter(([at]) => code[at]?.op === 0x03)
78
+ .map(([at, last]) => ({ start: at + 1, close: last, loop: true }))
79
+ const weight = code.map(
80
+ value =>
81
+ 1 +
82
+ (value.op === 0x10 ? (constantCalls.get(value.args[0] ?? -1) ?? 0) : 0),
83
+ )
84
+ return { next, closes, loops, weight }
85
+ }
86
+ /** The longest path through `region` from its start, each region in `inner` nested in it charged on its own: the path
87
+ * steps over such a region to wherever it can leave to (a loop's own op still counts here). */
88
+ function longestOf(s: Shape, region: Region, inner: readonly Region[]): number {
89
+ const nested = inner.filter(
90
+ row =>
91
+ row !== region && row.start >= region.start && row.close <= region.close,
92
+ )
93
+ const children = nested.filter(
94
+ row =>
95
+ !nested.some(
96
+ other =>
97
+ other !== row && other.start <= row.start && other.close >= row.close,
98
+ ),
99
+ )
100
+ const entry = new Map<number, Region>(),
101
+ inside = new Set<number>()
102
+ for (const child of children) {
103
+ entry.set(child.loop ? child.start - 1 : child.start, child)
104
+ for (let at = child.start; at <= child.close; at++) inside.add(at)
105
+ }
106
+ const longest = new Map<number, number>()
107
+ for (let at = region.close; at >= region.start; at--) {
108
+ const child = entry.get(at)
109
+ if (child === undefined && inside.has(at)) continue
110
+ let after: readonly number[] = s.next[at] ?? [EXIT],
111
+ weight = s.weight[at] ?? 1
112
+ if (child !== undefined) {
113
+ const out = new Set<number>()
114
+ for (let j = child.start; j <= child.close; j++)
115
+ for (const to of s.next[j] ?? [])
116
+ if (to < child.start || to > child.close) out.add(to)
117
+ after = [...out]
118
+ if (!child.loop) weight = 0
79
119
  }
80
- costs.set(start, longest[start] ?? 0)
120
+ let best = 0
121
+ for (const to of after)
122
+ if (to >= region.start && to <= region.close)
123
+ best = Math.max(best, longest.get(to) ?? 0)
124
+ longest.set(at, weight + best)
81
125
  }
82
- return costs
126
+ return longest.get(region.start) ?? 0
127
+ }
128
+ /** WASM-HOST H2c: where a charge may also stand. Each point is entered only from just before it (an `if` arm, an
129
+ * `else` arm, the fall-through of a `br_if`, the join after an `end`, where every branch to that label lands), and its
130
+ * region runs to the close of its level. */
131
+ export function v2SplitPoints(
132
+ code: readonly V2Instruction[],
133
+ ): ReadonlySet<number> {
134
+ const points = new Set<number>()
135
+ for (let i = 0; i + 1 < code.length; i++) {
136
+ const op = code[i]?.op
137
+ if (op === 0x04 || op === 0x05 || op === 0x0d || op === 0x0b)
138
+ points.add(i + 1)
139
+ }
140
+ return points
141
+ }
142
+ /** WASM-HOST H2c: the split points a compiler charges, innermost first: each whose own longest path, past the splits
143
+ * already charged inside it and its loops, is `floor` or more (`V2_SPLIT_FLOORS` by lane). */
144
+ export function v2SplitStarts(
145
+ code: readonly V2Instruction[],
146
+ constantCalls: ReadonlyMap<number, number>,
147
+ floor: number,
148
+ ): ReadonlySet<number> {
149
+ const s = shape(code, constantCalls),
150
+ chosen: Region[] = []
151
+ for (const at of [...v2SplitPoints(code)].reverse()) {
152
+ const region = {
153
+ start: at,
154
+ close: s.closes[at] ?? code.length - 1,
155
+ loop: false,
156
+ }
157
+ if (longestOf(s, region, [...s.loops, ...chosen]) >= floor)
158
+ chosen.push(region)
159
+ }
160
+ return new Set(chosen.map(region => region.start))
161
+ }
162
+ /** WASM-HOST H2c: each region (the body, each loop body, each split in `splits`) priced at its longest path, not every
163
+ * instruction it holds. A call that takes one `if` arm, one `br_table` case or an early exit runs no more than that
164
+ * path, so a charge of this price covers every instruction run; an if/else or a switch pays for its longest arm, and a
165
+ * split arm a call skips is not paid at all (H2b read up to 14x over-billing). Edges: fall-through, `if` to its arm or
166
+ * past it, `else` past its `end`, a branch to past its block's `end`, and from a nested loop or split to wherever it
167
+ * can leave to. A return, `unreachable`, a branch to a loop (the loop charges again) or past the region ends a path. */
168
+ export function v2PathCosts(
169
+ code: readonly V2Instruction[],
170
+ constantCalls: ReadonlyMap<number, number> = new Map(),
171
+ splits: ReadonlySet<number> = new Set(),
172
+ ): ReadonlyMap<number, number> {
173
+ const points = v2SplitPoints(code)
174
+ if ([...splits].some(at => !points.has(at)))
175
+ throw new Error('V2 split outside a split point')
176
+ const s = shape(code, constantCalls)
177
+ const regions: Region[] = [
178
+ { start: 0, close: code.length - 1, loop: true },
179
+ ...s.loops,
180
+ ...[...splits].map(at => ({
181
+ start: at,
182
+ close: s.closes[at] ?? code.length - 1,
183
+ loop: false,
184
+ })),
185
+ ]
186
+ return new Map(
187
+ regions.map(region => [region.start, longestOf(s, region, regions)]),
188
+ )
83
189
  }
@@ -2,7 +2,7 @@
2
2
  * not permission to instantiate an image by itself. */
3
3
  import { SCRIPT_ABI } from './scriptAbi.ts';
4
4
  import { readV2Module,type V2Instruction,type V2Module,type V2Signature } from './scriptModuleV2.ts';
5
- import { v2PathCosts } from './script-fuel-path-v2.ts';
5
+ import { v2PathCosts,v2SplitPoints } from './script-fuel-path-v2.ts';
6
6
 
7
7
  export const V2_ENTRY_SIGNATURES: Readonly<Record<string,readonly number[]>> = Object.freeze({
8
8
  ws_init: [0x7f,0x7f,0x7f], ws_step: [0x7f,0x7f], ws_project: [0x7f], ws_view: [0x7c,0x7c,0x7f],
@@ -108,8 +108,9 @@ export function inspectV2Fuel(bytes: Uint8Array,options: { readonly lane?: V2Lan
108
108
  }
109
109
  plain.push(value);
110
110
  }
111
- // H2c: each region pays at least its longest path (script-fuel-path-v2.ts); H0's whole-region price is no less
112
- const costs = v2PathCosts(plain,new Map([...getters].map(target => [target,2])));
111
+ // H2c: each region, and each split a charge stands on, pays at least its longest path (script-fuel-path-v2.ts)
112
+ const points = v2SplitPoints(plain);
113
+ const costs = v2PathCosts(plain,new Map([...getters].map(target => [target,2])),new Set([...charges.keys()].filter((at: number): boolean => points.has(at))));
113
114
  if (costs.size !== charges.size || [...costs].some(([at,cost]) => (charges.get(at) ?? Number.NEGATIVE_INFINITY) < cost)) throw new Error('Missing or underpriced v2 basic block region');
114
115
  unmetered.push(plain); calls.push(edges);
115
116
  }
@@ -1,4 +1,6 @@
1
1
  import * as v from 'valibot';
2
+ import { ReturnProjectionV2Schema } from './returnProjectionV2.ts';
3
+ import type { ReturnProjectionV2Rows, ReturnProjectionV2RowsInput } from './returnProjectionV2.ts';
2
4
  import { AudioMixExpressionSchema, type AudioMixExpr } from './audioProfiles.ts';
3
5
 
4
6
  const id = v.pipe(v.string(), v.minLength(1), v.maxLength(128));
@@ -74,6 +76,8 @@ const named = v.pipe(v.array(v.tuple([name, source])), v.maxLength(32));
74
76
  export const WeatherShelterCirclesSchema: v.GenericSchema<WeatherReactionRows['shelter']['circles']> = v.pipe(v.array(v.tuple([finite, finite, v.pipe(finite, v.minValue(0))])), v.maxLength(256));
75
77
  export const WeatherReactionsSchema: v.StrictObjectSchema<WeatherReactionEntries, undefined> = v.strictObject({
76
78
  version: v.literal(1), hz: v.pipe(finite, v.minValue(1), v.maxValue(10)), script: v.unknown(), bytes: v.string(),
79
+ /** WASM-HOST H13: the program's ABI-2 candidate beside its ABI-1 witness; the engine's return program admits both. */
80
+ v2: v.exactOptional(ReturnProjectionV2Schema),
77
81
  actions: v.exactOptional(v.strictObject({ event: id, unless: v.exactOptional(name) })),
78
82
  active: v.pipe(v.array(id), v.maxLength(32)), flash: name,
79
83
  shelter: v.strictObject({ margin: v.pipe(finite, v.minValue(0)), circles: WeatherShelterCirclesSchema }),
@@ -290,6 +294,7 @@ interface WeatherReactionRowsInputFields {
290
294
  hz: number;
291
295
  script: unknown;
292
296
  bytes: string;
297
+ v2?: ReturnProjectionV2RowsInput;
293
298
  actions?: {
294
299
  event: string;
295
300
  unless?: string;
@@ -352,6 +357,7 @@ interface WeatherReactionRowsFields {
352
357
  hz: number;
353
358
  script: unknown;
354
359
  bytes: string;
360
+ v2?: ReturnProjectionV2Rows;
355
361
  actions?: {
356
362
  event: string;
357
363
  unless?: string;
@@ -412,9 +418,10 @@ export type WeatherReactionRows = { [Key in keyof WeatherReactionRowsFields]: We
412
418
 
413
419
  /** Keep composition metadata available to inline module admission. */
414
420
  type WeatherReactionEntries = {
415
- [Key in Exclude<keyof WeatherReactionRows, 'actions' | 'hud'>]:
421
+ [Key in Exclude<keyof WeatherReactionRows, 'actions' | 'hud' | 'v2'>]:
416
422
  v.GenericSchema<WeatherReactionRowsInput[Key], WeatherReactionRows[Key]>;
417
423
  } & {
424
+ v2: v.ExactOptionalSchema<v.GenericSchema<ReturnProjectionV2RowsInput, ReturnProjectionV2Rows>, undefined>;
418
425
  actions: v.ExactOptionalSchema<v.GenericSchema<NonNullable<WeatherReactionRowsInput['actions']>,
419
426
  NonNullable<WeatherReactionRows['actions']>>, undefined>;
420
427
  hud: v.ExactOptionalSchema<v.GenericSchema<NonNullable<WeatherReactionRowsInput['hud']>,