Repository navigation
Expand file tree
/
Copy pathlib.rs
More file actions
271 lines (243 loc) · 10.9 KB
/
Copy pathlib.rs
File metadata and controls
271 lines (243 loc) · 10.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
//! `basic-combat` — sample Nexus compute module.
//!
//! Implements the V1 compute envelope ABI (compass Q9): a **stateless pure
//! function** that resolves one attack between two characters with simple
//! `ATK − DEF` arithmetic. Triple role: integration test, ABI validation, and
//! reference implementation for module authors (see `modules/README.md`).
//!
//! The module is authored on the official `nexus-module-sdk` (V1.170 P0,
//! AR-11): `nexus_entry!` generates the three ABI exports (`alloc`, `init`,
//! `compute`) and wires the global allocator; combat logic reads the typed
//! [`ComputeInput`] envelope and uses the SDK's key-block accessors. This file
//! contains **zero** `#[no_mangle]` code — every ABI-facing symbol lives in
//! the SDK.
//!
//! Targets `wasm32-unknown-unknown` (no WASI). `std` is available on this
//! target for `Vec`/`String`/`format!`/serde; only I/O, threads, and the wall
//! clock are absent. Exports (generated by `nexus_entry!`):
//!
//! | Export | Signature | Purpose |
//! | --- | --- | --- |
//! | `alloc` | `(len: u32) -> u32` | Allocate `len` bytes in linear memory for the host. |
//! | `init` | `() -> ()` | One-shot setup (no-op here). |
//! | `compute` | `(in_ptr, in_len, out_ptr, out_cap: u32) -> i64` | Read `ComputeInput`, write `ComputeOutput`. |
//!
//! Combatants are read from the inline `key_blocks` snapshot (the canonical
//! path — the host always bundles the relevant blocks per the schema). The
//! optional `invocation.attacker_id` / `invocation.defender_id` select the two
//! combatants; otherwise the first two character blocks are used.
//!
//! # Key-block JSON shape
//!
//! Since V1.139, `ComputeInput.key_blocks` carries **spoke `KnowledgeEntry`
//! JSON** (id field `entry_id`, type field `entry_type`, `body.attributes` as
//! an ERC721-style array of `{trait_type, value}` items). This module reads
//! that canonical shape with fallbacks to the legacy domain `KeyBlock` shape
//! (`key_block_id` / `block_type` / flat `body.attributes.<trait>` object), so
//! the module-level fixtures in `crates/nexus-wasm-host/tests/basic_combat.rs`
//! (which hand-build domain-shaped input) keep working unchanged.
use serde_json::{json, Value};
use nexus_module_sdk::key_blocks::{
entry_id_of, is_kind, read_attr_int, read_int, timeline_event_id,
};
use nexus_module_sdk::{
nexus_entry, ComputeInput, ComputeOutput, DeltaOp, ModuleError, StateDeltaOp,
};
// ===========================================================================
// Combat logic
// ===========================================================================
/// Resolve a single attack between two characters and build the output envelope.
fn run_combat(input: &ComputeInput) -> Result<ComputeOutput, ModuleError> {
let key_blocks = &input.key_blocks;
if key_blocks.is_empty() {
return Err(ModuleError::InputMalformed);
}
let (attacker, defender) = select_combatants(&input.invocation, key_blocks)?;
let attacker_id = entry_id_of(attacker).unwrap_or("attacker").to_string();
let defender_id = entry_id_of(defender).unwrap_or("defender").to_string();
let atk = read_attr_int(attacker, "base_atk")
.or_else(|| read_int(attacker, &["body", "base_atk"]))
.unwrap_or(0);
let def = read_attr_int(defender, "base_def")
.or_else(|| read_int(defender, &["body", "base_def"]))
.unwrap_or(0);
// current_hp: nested by block_type (compass Q5) -> body.state.character.current_hp
let hp_before = read_int(defender, &["body", "state", "character", "current_hp"])
.or_else(|| read_int(defender, &["body", "state", "current_hp"]))
.or_else(|| read_attr_int(defender, "max_hp"))
.unwrap_or(0);
let damage = (atk - def).max(0);
let hp_after = (hp_before - damage).max(0);
// --- state_delta -----------------------------------------------------
let mut state_delta = Vec::new();
state_delta.push(StateDeltaOp {
op: DeltaOp::Sub,
path: "character.current_hp".to_string(),
target_key_block_id: Some(defender_id.clone()),
value: Some(json!(damage)),
});
if hp_after == 0 {
state_delta.push(StateDeltaOp {
op: DeltaOp::Set,
path: "character.is_alive".to_string(),
target_key_block_id: Some(defender_id.clone()),
value: Some(json!(false)),
});
}
// world_ref inner fields are optional on the wire (schema requires
// `world_ref` itself, not its properties); keep the legacy fallbacks so
// domain-shaped fixtures keep producing the same timeline event.
let world_id = input.world_ref.world_id.as_deref().unwrap_or("world");
let branch_id = input.world_ref.branch_id.as_deref().unwrap_or("root");
// --- timeline_events -------------------------------------------------
let summary = format!(
"{attacker} struck {defender} for {damage} ({hp_before} -> {hp_after} hp)",
attacker = attacker_id,
defender = defender_id,
damage = damage,
hp_before = hp_before,
hp_after = hp_after,
);
let timeline_events = vec![json!({
"schema_version": 1,
"timeline_event_id": timeline_event_id("combat", &[&attacker_id, &defender_id]),
"world_id": world_id,
"branch_id": branch_id,
"event_type": "state_update",
"status": "canon",
"sequence_no": 1,
"title": "Combat resolved",
"summary": summary,
"affected_key_block_ids": [attacker_id.clone(), defender_id.clone()],
// Modules cannot read a wall clock on wasm32-unknown-unknown; the host
// owns authoritative timestamps when it applies the event.
"created_at": "1970-01-01T00:00:00Z",
})];
// --- battle_report ---------------------------------------------------
let battle_report = json!({
"kind": "combat",
"attacker_id": attacker_id,
"defender_id": defender_id,
"damage": damage,
"defender_hp_before": hp_before,
"defender_hp_after": hp_after,
"resolution": "atk_minus_def",
});
Ok(ComputeOutput {
schema_version: input.schema_version,
state_delta,
timeline_events,
new_key_blocks: Vec::new(),
battle_report,
})
}
/// Module entry (V1 fn form). [`nexus_entry!`] wires it to the `alloc` /
/// `init` / `compute` exports.
fn combat(input: ComputeInput) -> Result<ComputeOutput, ModuleError> {
run_combat(&input)
}
nexus_entry!(combat);
/// Pick the attacker and defender KeyBlocks.
///
/// Honors `invocation.attacker_id` / `invocation.defender_id` when present;
/// otherwise falls back to the first two character-typed blocks.
fn select_combatants<'a>(
invocation: &'a Value,
key_blocks: &'a [Value],
) -> Result<(&'a Value, &'a Value), ModuleError> {
let want_attacker = invocation.get("attacker_id").and_then(Value::as_str);
let want_defender = invocation.get("defender_id").and_then(Value::as_str);
let find = |id: &str| key_blocks.iter().find(|kb| entry_id_of(kb) == Some(id));
if let (Some(a), Some(d)) = (want_attacker, want_defender) {
if a == d {
return Err(ModuleError::InputMalformed);
}
return match (find(a), find(d)) {
(Some(att), Some(def)) => Ok((att, def)),
_ => Err(ModuleError::InputMalformed),
};
}
// Fallback: first two character blocks.
let mut chars = key_blocks.iter().filter(|kb| is_kind(kb, "character"));
let attacker = chars.next().ok_or(ModuleError::InputMalformed)?;
let defender = chars.next().ok_or(ModuleError::InputMalformed)?;
Ok((attacker, defender))
}
#[cfg(test)]
mod tests {
use super::*;
/// The `nexus-spoke-adapter` key-block conversion emits spoke attribute
/// values as f64-backed JSON numbers in the FLAT form
/// (`body.attributes.base_atk` = `20.0` — the spoke `BodyAttributeValue`
/// number variant is an f64). `read_attr_int` must accept them on the
/// flat path exactly like the array path already did (L2 review
/// Minor-1: the flat branch previously read floats as 0 → damage 0).
#[test]
fn flat_object_attributes_accept_f64_values() {
let kb = serde_json::json!({
"entry_type": "character",
"body": {
"attributes": { "max_hp": 100.0, "base_atk": 20.0, "base_def": 5.0 },
},
});
assert_eq!(read_attr_int(&kb, "base_atk"), Some(20));
assert_eq!(read_attr_int(&kb, "max_hp"), Some(100));
assert_eq!(read_attr_int(&kb, "base_def"), Some(5));
}
/// Integer-valued flat attributes keep working (legacy domain form).
#[test]
fn flat_object_attributes_accept_integer_values() {
let kb = serde_json::json!({
"entry_type": "character",
"body": {
"attributes": { "max_hp": 100, "base_atk": 20, "base_def": 5 },
},
});
assert_eq!(read_attr_int(&kb, "base_atk"), Some(20));
}
/// The canonical ERC721-array form still accepts both int and float
/// values (unchanged behavior — regression pin).
#[test]
fn array_attributes_accept_int_and_float_values() {
let kb = serde_json::json!({
"entry_type": "character",
"body": {
"attributes": [
{ "trait_type": "base_atk", "value": 20 },
{ "trait_type": "base_def", "value": 5.0 },
],
},
});
assert_eq!(read_attr_int(&kb, "base_atk"), Some(20));
assert_eq!(read_attr_int(&kb, "base_def"), Some(5));
}
/// End-to-end on the canonical fixture: `run_combat` on the typed
/// envelope must produce the wire contract the real-host fixture test
/// asserts (delta `-`/`character.current_hp`/15 on `kb_def`, one
/// `state_update` event, empty `new_key_blocks`, `kind: combat` report).
#[test]
fn run_combat_produces_four_part_output() {
let input: ComputeInput = serde_json::from_str(include_str!(
"../../nexus-module-test/fixtures/combat-input.json"
))
.expect("canonical fixture parses as ComputeInput");
let output = run_combat(&input).expect("combat resolves");
let delta = output
.state_delta
.iter()
.find(|d| d.target_key_block_id.as_deref() == Some("kb_def"))
.expect("delta targeting defender present");
assert_eq!(delta.op, DeltaOp::Sub);
assert_eq!(delta.path, "character.current_hp");
assert_eq!(delta.value, Some(json!(15)));
assert_eq!(output.timeline_events.len(), 1);
assert_eq!(output.timeline_events[0]["event_type"], "state_update");
assert_eq!(
output.timeline_events[0]["affected_key_block_ids"],
json!(["kb_atk", "kb_def"])
);
assert!(output.new_key_blocks.is_empty());
assert_eq!(output.battle_report["kind"], "combat");
assert_eq!(output.battle_report["damage"], 15);
}
}