Skip to content

Craft Anything: understand how any software works, and craft your own.

Rust

Compare WebAssembly exported tag parameter types (R0.5) (#441)

Afloatfa4aae2e7919
diff --git a/crates/engine/src/tools/wasm_compare_tools.rs b/crates/engine/src/tools/wasm_compare_tools.rs
index 768aadd6..a1edcebd 100644
--- a/crates/engine/src/tools/wasm_compare_tools.rs
+++ b/crates/engine/src/tools/wasm_compare_tools.rs
@@ -80,6 +80,7 @@ fn export_signature(r: &WasmReport, kind: &str, index: u32) -> String {
.find(|t| t.index == index)
.map(|t| format!("{} {}..{}", t.element_type, t.initial, t.maximum.map(|x| x.to_string()).unwrap_or_default())),
"global" => r.globals.iter().find(|g| g.index == index).map(|g| format!("{}{}", if g.mutable { "mut " } else { "" }, g.value_type)),
+ "tag" => r.tags.iter().find(|t| t.index == index).map(|t| t.signature.clone()),
_ => None,
};
found.unwrap_or_else(|| format!("unresolved {kind} #{index}"))
@@ -193,6 +194,7 @@ fn formats_wasm_compare(ctx: &mut Ctx<'_>, params: Value) -> Result<ToolOutput,
mod tests {
use super::super::native_common::test_support::{call, call_err};
use crate::Engine;
+ use craft_anything_formats::wasm;
use craft_anything_testkit::{formats as fx, temp_file};
use serde_json::json;
@@ -212,6 +214,165 @@ mod tests {
m
}
+ fn tag_module(imported_parameter: Option<u8>, defined_parameter: Option<u8>) -> Vec<u8> {
+ let mut module = b"\0asm\x01\0\0\0".to_vec();
+ let section = |id: u8, body: &[u8], bytes: &mut Vec<u8>| {
+ assert!(body.len() < 128);
+ bytes.extend_from_slice(&[id, body.len() as u8]);
+ bytes.extend_from_slice(body);
+ };
+ let parameters: Vec<u8> = imported_parameter.into_iter().chain(defined_parameter).collect();
+ let mut types = vec![parameters.len() as u8];
+ for parameter in parameters {
+ types.extend_from_slice(&[0x60, 1, parameter, 0]);
+ }
+ section(1, &types, &mut module);
+ let imported = u8::from(imported_parameter.is_some());
+ if imported_parameter.is_some() {
+ // env.incoming is a tag with function type 0.
+ section(2, &[1, 3, b'e', b'n', b'v', 8, b'i', b'n', b'c', b'o', b'm', b'i', b'n', b'g', 4, 0, 0], &mut module);
+ }
+ if defined_parameter.is_some() {
+ section(13, &[1, 0, imported], &mut module);
+ }
+ let mut exports = vec![imported + u8::from(defined_parameter.is_some())];
+ if imported_parameter.is_some() {
+ exports.extend_from_slice(&[8, b'i', b'n', b'c', b'o', b'm', b'i', b'n', b'g', 4, 0]);
+ }
+ if defined_parameter.is_some() {
+ exports.extend_from_slice(&[5, b'l', b'o', b'c', b'a', b'l', 4, imported]);
+ }
+ section(7, &exports, &mut module);
+ assert!(wasm::inspect(&module).unwrap().validation.valid);
+ module
+ }
+
+ fn tag_index_module(function_imports: usize, tag_imports: usize, export_indices: &[u32]) -> Vec<u8> {
+ fn leb(mut n: u32, bytes: &mut Vec<u8>) {
+ loop {
+ let byte = (n & 0x7f) as u8;
+ n >>= 7;
+ bytes.push(byte | if n == 0 { 0 } else { 0x80 });
+ if n == 0 {
+ break;
+ }
+ }
+ }
+ fn section(id: u8, body: &[u8], bytes: &mut Vec<u8>) {
+ bytes.push(id);
+ leb(body.len().try_into().unwrap(), bytes);
+ bytes.extend_from_slice(body);
+ }
+ let mut module = b"\0asm\x01\0\0\0".to_vec();
+ section(1, &[2, 0x60, 1, 0x7f, 0, 0x60, 1, 0x7e, 0], &mut module);
+ let mut imports = Vec::new();
+ leb((function_imports + tag_imports).try_into().unwrap(), &mut imports);
+ for _ in 0..function_imports {
+ imports.extend_from_slice(&[0, 0, 0, 0]); // Empty module/name, function type 0.
+ }
+ for _ in 0..tag_imports {
+ imports.extend_from_slice(&[0, 0, 4, 0, 0]); // Empty module/name, tag type 0.
+ }
+ section(2, &imports, &mut module);
+ section(13, &[1, 0, 1], &mut module); // Defined tag has the distinct i64 parameter.
+ let mut exports = Vec::new();
+ leb(export_indices.len().try_into().unwrap(), &mut exports);
+ for index in export_indices {
+ let name = format!("tag{index}");
+ leb(name.len().try_into().unwrap(), &mut exports);
+ exports.extend_from_slice(name.as_bytes());
+ exports.push(4);
+ leb(*index, &mut exports);
+ }
+ section(7, &exports, &mut module);
+ module
+ }
+
+ #[test]
+ fn tag_indices_survive_the_import_list_cap() {
+ let report = wasm::inspect(&tag_index_module(wasm::MAX_ITEMS, 1, &[0, 1])).unwrap();
+ assert!(report.validation.valid && report.parse_error.is_none(), "{report:?}");
+ assert!(report.truncated);
+ assert_eq!(report.imports.len(), wasm::MAX_ITEMS);
+ assert_eq!(super::export_signature(&report, "tag", 0), "(i32) -> ()");
+ assert_eq!(super::export_signature(&report, "tag", 1), "(i64) -> ()");
+ }
+
+ #[test]
+ fn capped_tag_indices_are_never_filled_by_defined_tags() {
+ let cap = u32::try_from(wasm::MAX_ITEMS).unwrap();
+ let module = tag_index_module(0, wasm::MAX_ITEMS + 1, &[cap - 1, cap, cap + 1]);
+ let report = wasm::inspect(&module).unwrap();
+ assert!(report.validation.valid && report.parse_error.is_none(), "{report:?}");
+ assert!(report.truncated);
+ assert_eq!(super::export_signature(&report, "tag", cap - 1), "(i32) -> ()");
+ assert_eq!(super::export_signature(&report, "tag", cap), format!("unresolved tag #{cap}"));
+ assert_eq!(super::export_signature(&report, "tag", cap + 1), format!("unresolved tag #{}", cap + 1));
+ let path = temp_file("capped-tags.wasm", &module);
+ let e = Engine::new(crate::testing::session());
+ let result = call(&e, "formats_wasm_compare", json!({"left_path": path, "right_path": path, "scope": "exports"}));
+ for code in ["left_partial", "right_partial"] {
+ assert!(result["limitations"].as_array().unwrap().iter().any(|l| l["code"] == code));
+ }
+ }
+
+ #[test]
+ fn invalid_tag_references_stay_diagnostic() {
+ for (types, type_index, expected) in [(vec![1, 0x60, 0, 0], 1, "type 1 (missing)"), (vec![1, 0x5f, 0], 0, "type 0 (not a function type)")] {
+ let mut module = b"\0asm\x01\0\0\0".to_vec();
+ module.extend_from_slice(&[1, types.len() as u8]);
+ module.extend_from_slice(&types);
+ module.extend_from_slice(&[13, 3, 1, 0, type_index, 7, 5, 1, 1, b'e', 4, 0]);
+ let report = wasm::inspect(&module).unwrap();
+ assert!(!report.validation.valid);
+ assert_eq!(super::export_signature(&report, "tag", 0), expected);
+ assert_eq!(super::export_signature(&report, "tag", 99), "unresolved tag #99");
+ let path = temp_file("invalid-tag.wasm", &module);
+ let e = Engine::new(crate::testing::session());
+ let result = call(&e, "formats_wasm_compare", json!({"left_path": path, "right_path": path}));
+ for code in ["left_invalid", "right_invalid"] {
+ assert!(result["limitations"].as_array().unwrap().iter().any(|l| l["code"] == code));
+ }
+ }
+ }
+
+ #[test]
+ fn defined_tag_parameter_changes_are_reported() {
+ let e = Engine::new(crate::testing::session());
+ let left = temp_file("left-tag.wasm", &tag_module(None, Some(0x7f)));
+ let right = temp_file("right-tag.wasm", &tag_module(None, Some(0x7e)));
+ let v = call(&e, "formats_wasm_compare", json!({"left_path": left, "right_path": right}));
+ assert_eq!(v["result"]["counts"], json!({"added": 0, "removed": 0, "changed": 1, "unchanged": 0}));
+ let row = &v["result"]["changes"][0];
+ assert_eq!(row["name"], "local");
+ assert_eq!(row["left"][0]["signature"], "(i32) -> ()");
+ assert_eq!(row["right"][0]["signature"], "(i64) -> ()");
+ let same = call(&e, "formats_wasm_compare", json!({"left_path": left, "right_path": left}));
+ assert_eq!(same["result"]["counts"], json!({"added": 0, "removed": 0, "changed": 0, "unchanged": 1}));
+ }
+
+ #[test]
+ fn reexported_imported_tags_are_resolved() {
+ let e = Engine::new(crate::testing::session());
+ let left = temp_file("left-import-tag.wasm", &tag_module(Some(0x7f), None));
+ let right = temp_file("right-import-tag.wasm", &tag_module(Some(0x7e), None));
+ for scope in ["exports", "imports"] {
+ let v = call(&e, "formats_wasm_compare", json!({"left_path": left, "right_path": right, "scope": scope}));
+ assert_eq!(v["result"]["counts"], json!({"added": 0, "removed": 0, "changed": 1, "unchanged": 0}), "{scope}: {v}");
+ assert_eq!(v["result"]["changes"][0]["left"][0]["signature"], "(i32) -> ()");
+ }
+ }
+
+ #[test]
+ fn defined_tags_follow_imported_tags_in_the_index_space() {
+ let e = Engine::new(crate::testing::session());
+ let left = temp_file("left-mixed-tags.wasm", &tag_module(Some(0x7f), Some(0x7f)));
+ let right = temp_file("right-mixed-tags.wasm", &tag_module(Some(0x7f), Some(0x7e)));
+ let v = call(&e, "formats_wasm_compare", json!({"left_path": left, "right_path": right, "scope": "exports"}));
+ assert_eq!(v["result"]["counts"], json!({"added": 0, "removed": 0, "changed": 1, "unchanged": 1}));
+ assert_eq!(v["result"]["changes"][0]["name"], "local");
+ }
+
#[test]
fn reports_added_removed_changed() {
let e = Engine::new(crate::testing::session());
diff --git a/crates/formats/src/wasm.rs b/crates/formats/src/wasm.rs
index 9d95476b..d1dcee4c 100644
--- a/crates/formats/src/wasm.rs
+++ b/crates/formats/src/wasm.rs
@@ -1,5 +1,5 @@
//! WebAssembly modules: validation, sections, imports, exports, functions with their signatures
-//! and names, memories, tables, globals, custom sections (names, producers, target features,
+//! and names, memories, tables, globals, tags, custom sections (names, producers, target features,
//! source map URL) and a text (WAT) rendering. Built on the pure-Rust `wasmparser` and
//! `wasmprinter` crates; never executes anything.
@@ -82,6 +82,15 @@ pub struct WasmGlobal {
pub imported: bool,
}
+#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
+pub struct WasmTag {
+ /// Index in the tag index space (imports first).
+ pub index: u32,
+ pub type_index: u32,
+ pub signature: String,
+ pub imported: bool,
+}
+
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct WasmCustom {
pub name: String,
@@ -127,6 +136,7 @@ pub struct WasmReport {
pub memories: Vec<WasmMemory>,
pub tables: Vec<WasmTable>,
pub globals: Vec<WasmGlobal>,
+ pub tags: Vec<WasmTag>,
pub start_function: Option<u32>,
pub data_segments: u32,
pub element_segments: u32,
@@ -236,6 +246,7 @@ pub fn inspect(data: &[u8]) -> Result<WasmReport, FormatError> {
memories: Vec::new(),
tables: Vec::new(),
globals: Vec::new(),
+ tags: Vec::new(),
start_function: None,
data_segments: 0,
element_segments: 0,
@@ -255,6 +266,7 @@ pub fn inspect(data: &[u8]) -> Result<WasmReport, FormatError> {
let mut imported_tables = 0u32;
let mut imported_memories = 0u32;
let mut imported_globals = 0u32;
+ let mut imported_tags = 0u32;
let mut code_index = 0u32;
let type_sig = |types: &[Option<FuncType>], t: u32| -> String {
match types.get(t as usize) {
@@ -354,7 +366,16 @@ pub fn inspect(data: &[u8]) -> Result<WasmReport, FormatError> {
imported_globals = imported_globals.saturating_add(1);
("global", None, format!("{}{}", if g.mutable { "mut " } else { "" }, g.content_type))
}
- TypeRef::Tag(t) => ("tag", Some(t.func_type_idx), type_sig(&types, t.func_type_idx)),
+ TypeRef::Tag(t) => {
+ let keep_tag = cap(rep.tags.len(), &mut rep.truncated);
+ let signature = if keep_tag || rep.imports.len() < MAX_ITEMS { type_sig(&types, t.func_type_idx) } else { String::new() };
+ if keep_tag {
+ rep.tags.push(WasmTag { index: imported_tags, type_index: t.func_type_idx, signature: signature.clone(), imported: true });
+ }
+ // The import list and tag list are capped independently.
+ imported_tags = imported_tags.saturating_add(1);
+ ("tag", Some(t.func_type_idx), signature)
+ }
};
if cap(rep.imports.len(), &mut rep.truncated) {
rep.imports.push(WasmImport { module: imp.module.to_string(), name: imp.name.to_string(), kind, type_index, signature });
@@ -401,6 +422,20 @@ pub fn inspect(data: &[u8]) -> Result<WasmReport, FormatError> {
});
}
}
+ Payload::TagSection(r) => {
+ for (i, t) in r.into_iter().enumerate() {
+ let t = t?;
+ if !cap(rep.tags.len(), &mut rep.truncated) {
+ break;
+ }
+ rep.tags.push(WasmTag {
+ index: imported_tags.saturating_add(u32::try_from(i).unwrap_or(u32::MAX)),
+ type_index: t.func_type_idx,
+ signature: type_sig(&types, t.func_type_idx),
+ imported: false,
+ });
+ }
+ }
Payload::GlobalSection(r) => {
for (i, g) in r.into_iter().enumerate() {
let g = g?;
diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md
index 1719bc31..a07d9912 100644
--- a/docs/ROADMAP.md
+++ b/docs/ROADMAP.md
@@ -166,6 +166,7 @@ Owner: open · Status: done (branch chore/r0.5-cleanups)
wrapped reads were thrown away, since the entry's first field was already out of range); an
entry that starts past the end of the file is now skipped
- [x] `cargo xtask layers` also scans `apps/`
+- [x] WebAssembly interface comparisons resolve exported tag parameter types (#309).
- [x] Engines in `KNOWN` without a `ToolPaths` override (tshark, objdump, rizin, java)
- [x] Class-usage search includes the component class of multidimensional object arrays (#325).
- [x] Missing `database` icon for SQLite in the UI (`kind_icon`)
diff --git a/docs/STATUS.md b/docs/STATUS.md
index 0c5752cc..fcff6476 100644
--- a/docs/STATUS.md
+++ b/docs/STATUS.md
@@ -28,6 +28,7 @@ workspace clippy, layers, fmt and the secret scan of all history were clean. Chi
| Claude Code builder | Runs the person's own `claude` in headless mode (Opus 5.5, high effort unless configured) with our MCP server, a permission-prompt tool and `core_person_ask`; preflights for our CLI (a build stops plainly if it's missing or won't start) and sign-in | Argument and stream-parser tests; live preflight; live builder turns; see [claude-code.md](claude-code.md) |
| Agents over ACP | Opt-in per backend (`acp = true`): Gemini CLI, Qwen Code, opencode, goose, Hermes and Maki in their ACP mode, one agent process per chat or build with our MCP server; Maki's ACP mode takes the backend's model (`cli_model`). In chat, permission requests become consent questions; in builds they go through the same approval policy as Claude Code's (inbox, Auto mode) | Protocol unit tests against scripted agent messages and an approval-policy test. Run live with Maki 0.7.0 only (2026-11-02, Linux, headless CLI): a static page built to Ready in 38 s, a follow-up continued the same session with `session/load`, and with Auto mode off its command and tool requests were refused in an unattended run. Turns report 0 tokens over ACP, and a continued session shows the earlier conversation again |
| WASM plugins | With `--features wasm-plugins`: `[[plugins.wasm]]` components exporting `craft-anything:plugin/tools` add tools, and ones exporting `craft-anything:plugin/checks` add checks run after each kind's own (they get the build's file list as JSON) (added, listed, turned on or off and removed in Settings → Plugins or with `plugins_add`/`plugins_remove`/`plugins_list`); no imports, fresh instance per call, fuel and memory limits | Tests with components written in WAT (describe, call, checks, a looping call stopped, imports refused, end to end through the engine); `examples/wasm-plugin-wordcount` built from Rust and loaded |
+| WebAssembly tag interfaces | `formats_wasm_compare` resolves retained imported and defined tag exports to their declared parameter types. Identical unresolved or invalid diagnostics may still count as unchanged; those counts do not establish interface compatibility, and invalid/partial limitations remain present | Synthetic core modules with tag changes and re-exports, mixed index spaces, import/tag limits, and missing or non-function type references; formats and engine tests. No real module corpus or WebAssembly execution was used for this correction |
| Questions and approvals | A file inbox per project; `core_person_ask`, `core_action_approve` and MCP consent requests become cards in the app | Cross-handle round-trip tests, a full approval round trip through the engine |
| Desktop app | Simple mode: sidebar with New project and the project history (kept across restarts); New project either makes something or just looks inside an app or file, a website or a game's files; a Game files screen (a game's archives; pictures from Unreal paks, Unity .assets files and Unity bundles saved as PNG after the person confirms they may unpack the game; uncompressed textures and the block formats DXT1, DXT5 and BC4–BC7), make prompt with picture attachments and, for anything recreated, a Clean room / Deep choice (also in the title bar; in Clean room, Just look inside, Game files, opening a file and the workbench ask for Deep mode instead), project screen (steps with the time spent and the AI cost and tokens of every build, saved in the project's usage.json by the run (a coding agent's figure is shown as an estimate at API prices, not the bill), what the build is on now and its activity as it arrives (kept in `build-activity.log`), pinned builder checklist, feed, question and approval cards, a Continue card when a build was paused or stopped part-way (the app or computer closed; the project shows Interrupted) that carries on the builder's own session instead of starting over, and "It's done" beside Continue or Try again to keep the build as it is (`project_build_finish`), checks with screenshots and the requirements not met yet, the builder's open questions, preview, play, folder, follow-ups while it builds, which Claude Code takes at its next step; Up in the prompt box takes back the last note still waiting). Projects can start in a folder the person picks, whose files are either the app, edited in place, or material to start from (asked, or the answer remembered in Settings), and are listed from any number of folders (`project_folders`, `project_list`, `rebuild --project-folder`). Make says which AI builds ("Built by": automatic, or any AI that can build, by name); a pick stays with the project and builds its later changes. With nothing to build with, Start offers the coding agents found on the computer. Settings → AI turns an AI off or removes it, and sets how hard the Claude API or Claude Code thinks (every Claude level, low to max; also `ai effort` in the CLI). In the prompt box, Up at the very start and Down at the very end go through earlier prompts when no note is waiting. Questions about a build ("Just ask" under the prompt box, or a message starting with `/btw`, the first slash command; `rebuild_question_ask`) are answered in the conversation, where each folds away and is kept in the project, without a build or a round and changing nothing: Claude Code answers from a read-only copy of the builder's own session. Under each project's prompt box, "Builder's questions: Ask me / Decide yourself" chooses whether the builder's questions come to the person as cards or are decided by the builder, which says what it chose (`project_questions_set`; the default is in Settings and follows Auto mode until picked). Projects can be renamed, duplicated and deleted (right-click in the sidebar, or the project's page; a delete keeps the person's own files). A build can be pinned (Pin this build on its page, or `project_pin_*` from the CLI and MCP): a frozen copy in the project's pinned/ folder (the default) or a light one that shares dependencies and media with the project through hard links (each one's size shown first), opened from the sidebar's collapsible Pinned section (icons with a running dot when folded); a pin or Play runs once per folder unless another copy is asked for, and a start that quits at once says so with its last output. Typed drafts survive a restart. In a narrow window the sidebar folds to icons and the project's details move above its feed; messages float over the screen and errors stay until dismissed. Advanced mode: workbench with every panel wired to real tools, as a screen beside the projects (builds and their questions stay a click away) | UI unit and smoke tests (egui_kittest), offscreen snapshots of every screen |
| CLI | Every tool, `--deep` or `--clean-room` for one run (never saved), `rebuild` (including `--continue-in`, and `--resume` to carry on a stopped build), `mcp --inbox`, `ai`, `setup`, `doctor`, `report` | CLI integration tests |