From 577ca5a0ae84d61a00f576feed7306b6cf54949c Mon Sep 17 00:00:00 2001 From: N0zoM1z0 <161784452+N0zoM1z0@users.noreply.github.com> Date: Fri, 16 Oct 2026 21:23:04 +0000 Subject: [PATCH] feat(experiment): compose native architecture storage facts Co-authored-by: gensokyo-dev <342580529+gensokyo-dev@users.noreply.github.com> Co-authored-by: Kaoru0822 <208281322+kaoru0822-kitauji@users.noreply.github.com> --- experiments/atomic-codemode/README.md | 7 +- experiments/atomic-codemode/api-contracts.mjs | 24 ++ experiments/atomic-codemode/api.mjs | 20 +- experiments/atomic-codemode/capability-map.md | 10 +- .../atomic-codemode/kuna-native-ir.patch | 256 +++++++++++- .../atomic-codemode/native-catalog-reads.mjs | 87 ++++ .../atomic-codemode/native-contract.mjs | 4 +- experiments/atomic-codemode/native-reads.mjs | 13 +- .../atomic-codemode/native-storage-map.mjs | 245 +++++++++++ .../native-storage-map.test.mjs | 393 ++++++++++++++++++ experiments/atomic-codemode/provider.mjs | 59 +-- experiments/atomic-codemode/reference.mjs | 4 + .../atomic-codemode/reference.test.mjs | 6 +- .../storage-boundary-oracle.md | 51 +++ .../storage-boundary-question.txt | 47 +++ .../atomic-codemode/storage-contracts.mjs | 49 +++ experiments/atomic-codemode/storage-study.md | 112 +++++ .../atomic-codemode/verify-discovery.mjs | 15 +- .../atomic-codemode/verify-storage.mjs | 213 ++++++++++ 19 files changed, 1538 insertions(+), 77 deletions(-) create mode 100644 experiments/atomic-codemode/api-contracts.mjs create mode 100644 experiments/atomic-codemode/native-catalog-reads.mjs create mode 100644 experiments/atomic-codemode/native-storage-map.mjs create mode 100644 experiments/atomic-codemode/native-storage-map.test.mjs create mode 100644 experiments/atomic-codemode/storage-boundary-oracle.md create mode 100644 experiments/atomic-codemode/storage-boundary-question.txt create mode 100644 experiments/atomic-codemode/storage-contracts.mjs create mode 100644 experiments/atomic-codemode/storage-study.md create mode 100644 experiments/atomic-codemode/verify-storage.mjs diff --git a/experiments/atomic-codemode/README.md b/experiments/atomic-codemode/README.md index 4790fceae40..b1c675fb6bc 100644 --- a/experiments/atomic-codemode/README.md +++ b/experiments/atomic-codemode/README.md @@ -19,6 +19,11 @@ The [capability map](capability-map.md) distinguishes verified task coverage, experimental exporter requirements and remaining unknowns before interpreting adapter comparisons. +The [architecture storage study](storage-study.md) adds exact native register-name +and address-space queries, sharing one bounded immutable capture per lease. +It separates coordinates, widths and native map misses from hardware absence, +SSA equality or alias claims. + The [function-boundary study](function-boundary-study.md) adds independent native prototype entries and return descriptors, separated from raw input varnodes. Both real SSH models correctly distinguish these inventories and compose the @@ -154,7 +159,7 @@ the ledger now records actual model responses and client dispatch/wait calls. owner. Recovered operations use `origin_address` and blocks `origin_start`; these locations cannot be substituted for machine branch destinations. The value-origin trial demonstrates why this boundary matters. The experiment -now has seventeen fact methods, still behind the same four-tool Code Mode +now has nineteen fact methods, still behind the same four-tool Code Mode catalog. `calls` connects recovered call operations to native target specifications and diff --git a/experiments/atomic-codemode/api-contracts.mjs b/experiments/atomic-codemode/api-contracts.mjs new file mode 100644 index 00000000000..967acf6b567 --- /dev/null +++ b/experiments/atomic-codemode/api-contracts.mjs @@ -0,0 +1,24 @@ +// Shared named contract and selection vocabulary; no engine or adapter code. +import { z } from "zod"; +export const hex = z.string().regex(/^0x(?:0|[1-9a-f][0-9a-f]{0,15})$/u); +export const valueLocation = z.strictObject({ + space: z.string(), + offset: hex, + size_bytes: z.number().int().positive(), +}); +export const page = { + offset: z.number().int().nonnegative().default(0), + limit: z.number().int().min(1).max(128).default(20), +}; +export const definition = ( + { summary, description }, + input, + method, + example, +) => ({ + summary, + description, + input: z.strictObject(input), + method, + example, +}); diff --git a/experiments/atomic-codemode/api.mjs b/experiments/atomic-codemode/api.mjs index 122d36050b9..9bd918e9e3b 100644 --- a/experiments/atomic-codemode/api.mjs +++ b/experiments/atomic-codemode/api.mjs @@ -3,22 +3,14 @@ import { z } from "zod"; import { MAX_BYTE_BATCH_BYTES } from "./limits.mjs"; import { MAX_GRAPH_BLOCKS } from "./graph-limits.mjs"; import { createReference } from "./reference.mjs"; +import { definition, hex, page, valueLocation } from "./api-contracts.mjs"; +import { storageMethods } from "./storage-contracts.mjs"; -const hex = z.string().regex(/^0x(?:0|[1-9a-f][0-9a-f]{0,15})$/u); const snapshot = z.string().startsWith("snap_"); -const valueLocation = z.strictObject({ - space: z.string(), - offset: hex, - size_bytes: z.number().int().positive(), -}); const byteWindow = z.strictObject({ address: hex, length: z.number().int().min(1).max(MAX_BYTE_BATCH_BYTES).default(256), }); -const page = { - offset: z.number().int().nonnegative().default(0), - limit: z.number().int().min(1).max(128).default(20), -}; const kinds = z.enum([ "value", "load", @@ -46,13 +38,6 @@ const fields = z ]), ) .optional(); -const definition = ({ summary, description }, input, method, example) => ({ - summary, - description, - input: z.strictObject(input), - method, - example, -}); const identitySeeds = z.array(z.string()).min(1).max(128); const relationInput = z.discriminatedUnion("kind", [ z.strictObject({ @@ -84,6 +69,7 @@ const relationInput = z.discriminatedUnion("kind", [ }), ]); export const methods = { + ...storageMethods, switches: definition( { summary: diff --git a/experiments/atomic-codemode/capability-map.md b/experiments/atomic-codemode/capability-map.md index bb30e29068f..176efd6cde0 100644 --- a/experiments/atomic-codemode/capability-map.md +++ b/experiments/atomic-codemode/capability-map.md @@ -1,7 +1,7 @@ # Capability and comparison scope -The experiment has seventeen fact methods behind a shared SDK/CLI owner, exposed -as twenty direct MCP tools or four Code Mode tools. The structured IR/call/ +The experiment has nineteen fact methods behind a shared SDK/CLI owner, exposed +as twenty-two direct MCP tools or four Code Mode tools. The structured IR/call/ projection/switch facts require the explicitly pinned experimental Kuna patch; they are not capabilities added to stock Kuna or integrated REA by registration alone. Other providers are not wired to this experimental service. @@ -86,3 +86,9 @@ Complete old function fidelity is preserved except for the new facet. Actual old-native/stock checks return explicit unavailability with readable Evidence. The two completed model tasks have mixed token/time/resource costs; no stable Code Mode advantage or provider parity follows. + +The [storage study](storage-study.md) exposes native address-space descriptors +and exact varnode_xref names without function decompilation. Width-qualified +coordinates compose with prototype/value/passing-storage facts. Real x86-64 +and AArch64 OpenSSH catalog checks do not establish big-endian, alias, runtime +or full provider parity coverage. diff --git a/experiments/atomic-codemode/kuna-native-ir.patch b/experiments/atomic-codemode/kuna-native-ir.patch index 88581e13402..22d9764375a 100644 --- a/experiments/atomic-codemode/kuna-native-ir.patch +++ b/experiments/atomic-codemode/kuna-native-ir.patch @@ -1168,7 +1168,7 @@ index 6710e12a..ef90468c 100644 + ); +} diff --git a/decompiler/crates/kuna-cli/src/main.rs b/decompiler/crates/kuna-cli/src/main.rs -index 2345743c..3da94435 100644 +index 2345743c..a16abb71 100644 --- a/decompiler/crates/kuna-cli/src/main.rs +++ b/decompiler/crates/kuna-cli/src/main.rs @@ -1,6 +1,8 @@ @@ -1180,6 +1180,22 @@ index 2345743c..3da94435 100644 mod callgraph; mod catalog; mod crypto; +@@ -31,6 +33,7 @@ mod runtime_hints; + mod skill; + mod specs; + mod strings; ++mod storage_map; + mod test; + mod unpack; + mod xrefs; +@@ -52,6 +55,7 @@ const COMMANDS: &[(&str, CommandHandler)] = &[ + ("read", disassemble::run_read), + ("xrefs", xrefs::run), + ("strings", strings::run), ++ ("storage-map", storage_map::run), + ("crypto", crypto::run), + ("unpack", unpack::run), + ("docs", docs::run), diff --git a/decompiler/crates/kuna-cli/src/project_stream.rs b/decompiler/crates/kuna-cli/src/project_stream.rs index e40b18c9..b8cae233 100644 --- a/decompiler/crates/kuna-cli/src/project_stream.rs @@ -1192,6 +1208,244 @@ index e40b18c9..b8cae233 100644 want_pointer_arguments: false, }; +diff --git a/decompiler/crates/kuna-cli/src/storage_map.rs b/decompiler/crates/kuna-cli/src/storage_map.rs +new file mode 100644 +index 00000000..b2a30345 +--- /dev/null ++++ b/decompiler/crates/kuna-cli/src/storage_map.rs +@@ -0,0 +1,232 @@ ++//! Read-only architecture storage metadata without discovery or decompilation. ++use crate::decompile_all::{load_program, Args, DriverDefaults}; ++use kuna_base::space::{AddrSpaceManager, VarnodeStorage}; ++use serde::{ ++ ser::{SerializeSeq, SerializeStruct}, ++ Serialize, Serializer, ++}; ++use std::{ ++ collections::BTreeMap, ++ io::{self, Write}, ++}; ++ ++const OUTPUT_BYTES: usize = 8 * 1024 * 1024; ++struct BoundedOutput { ++ bytes: Vec, ++ limit: usize, ++} ++impl Write for BoundedOutput { ++ fn write(&mut self, bytes: &[u8]) -> io::Result { ++ let next = self ++ .bytes ++ .len() ++ .checked_add(bytes.len()) ++ .filter(|n| *n <= self.limit) ++ .ok_or_else(|| io::Error::other("storage map encoded-byte capacity exceeded"))?; ++ if next > self.bytes.capacity() { ++ let capacity = next ++ .checked_next_power_of_two() ++ .unwrap_or(self.limit) ++ .min(self.limit); ++ self.bytes ++ .try_reserve_exact(capacity - self.bytes.len()) ++ .map_err(io::Error::other)?; ++ } ++ self.bytes.extend_from_slice(bytes); ++ Ok(bytes.len()) ++ } ++ fn flush(&mut self) -> io::Result<()> { ++ Ok(()) ++ } ++} ++#[derive(Serialize)] ++struct Space<'a> { ++ native_index: i32, ++ name: &'a str, ++ kind: String, ++ address_size_bytes: u32, ++ addressable_unit_bytes: u32, ++ endianness: &'static str, ++ highest_offset: String, ++} ++struct Spaces<'a>(&'a AddrSpaceManager); ++impl Serialize for Spaces<'_> { ++ fn serialize(&self, serializer: S) -> Result { ++ let mut rows = serializer.serialize_seq(None)?; ++ for index in 0..self.0.num_spaces() { ++ if let Some(space) = self.0.get_space(index) { ++ rows.serialize_element(&Space { ++ native_index: space.get_index(), ++ name: space.get_name(), ++ kind: format!("{:?}", space.get_type()), ++ address_size_bytes: space.get_addr_size(), ++ addressable_unit_bytes: space.get_word_size(), ++ endianness: if space.is_big_endian() { ++ "big" ++ } else { ++ "little" ++ }, ++ highest_offset: format!("0x{:x}", space.get_highest()), ++ })?; ++ } ++ } ++ rows.end() ++ } ++} ++#[derive(Serialize)] ++struct Register<'a> { ++ native_row: usize, ++ space: Option<&'a str>, ++ offset: String, ++ size_bytes: u32, ++ name: Option<&'a str>, ++ name_bytes_hex: Option, ++} ++struct Registers<'a>(&'a BTreeMap>); ++impl Serialize for Registers<'_> { ++ fn serialize(&self, serializer: S) -> Result { ++ let mut rows = serializer.serialize_seq(Some(self.0.len()))?; ++ for (native_row, (location, bytes)) in self.0.iter().enumerate() { ++ let name = std::str::from_utf8(bytes).ok(); ++ let name_bytes_hex = if name.is_some() { ++ None ++ } else { ++ if bytes.len() > OUTPUT_BYTES / 2 { ++ return Err(serde::ser::Error::custom( ++ "native register name exceeds encoded budget", ++ )); ++ } ++ Some(bytes.iter().map(|b| format!("{b:02x}")).collect()) ++ }; ++ rows.serialize_element(&Register { ++ native_row, ++ space: location.space.as_ref().map(|s| s.get_name()), ++ offset: format!("0x{:x}", location.offset), ++ size_bytes: location.size, ++ name, ++ name_bytes_hex, ++ })?; ++ } ++ rows.end() ++ } ++} ++struct Catalog<'a> { ++ binary: &'a str, ++ program: &'a kuna_console::engine::ConsoleProgram, ++} ++impl Serialize for Catalog<'_> { ++ fn serialize(&self, serializer: S) -> Result { ++ let arch = self.program.arch(); ++ let sleigh = arch ++ .translate() ++ .as_sleigh() ++ .ok_or_else(|| serde::ser::Error::custom("native Sleigh register map unavailable"))?; ++ let registers = sleigh.base().get_all_registers(); ++ let manager = arch.manage(); ++ let mut doc = serializer.serialize_struct("StorageMap", 8)?; ++ doc.serialize_field("schema_version", &1)?; ++ doc.serialize_field("binary", self.binary)?; ++ doc.serialize_field( ++ "architecture", ++ &serde_json::json!({ ++ "native_id": arch.get_description(), ++ "default_code_space": manager.get_default_code_space().map(|s|s.get_name()), ++ }), ++ )?; ++ doc.serialize_field("space_index_capacity", &manager.num_spaces())?; ++ doc.serialize_field("register_count", ®isters.len())?; ++ doc.serialize_field("spaces", &Spaces(manager))?; ++ doc.serialize_field("registers", &Registers(registers))?; ++ doc.serialize_field("coverage", &serde_json::json!({ ++ "scope":"bootstrapped native architecture spaces and exact varnode_xref register-name map", ++ "native_exact_register_map":"complete", "alias_relationships":"unknown", ++ "dynamic_join_records":"not-collected", "memory_values":"not-returned", ++ "listing_discovery":false, "functions_decompiled":0, ++ }))?; ++ doc.end() ++ } ++} ++pub(crate) fn run(argv: &[String]) -> i32 { ++ if argv.len() != 2 || argv[1] != "--json" { ++ eprintln!("usage: kuna storage-map --json"); ++ return 2; ++ } ++ let embedded = match crate::embedded_specs::tree() { ++ Some(Ok(root)) => root.to_string_lossy().into_owned(), ++ Some(Err(error)) => { ++ eprintln!("error: embedded specs: {error}"); ++ return 1; ++ } ++ None => { ++ eprintln!("error: storage-map requires embedded specs"); ++ return 1; ++ } ++ }; ++ let args = Args { ++ binary: argv[0].clone(), ++ json: true, ++ sleighpath: Some(embedded), ++ options: vec![ ++ ("listing".into(), "off".into()), ++ ("fast_funcdisc".into(), "off".into()), ++ ], ++ ..Args::serial() ++ }; ++ let result = (|| { ++ let program = load_program(&args, DriverDefaults::Query)?; ++ let mut output = BoundedOutput { ++ bytes: Vec::new(), ++ limit: OUTPUT_BYTES, ++ }; ++ serde_json::to_writer( ++ &mut output, ++ &Catalog { ++ binary: &args.binary, ++ program: &program, ++ }, ++ ) ++ .map_err(|e| e.to_string())?; ++ output.write_all(b"\n").map_err(|e| e.to_string())?; ++ String::from_utf8(output.bytes).map_err(|e| e.to_string()) ++ })(); ++ match result { ++ Ok(text) => crate::output::emit_with_status(&text, 0), ++ Err(error) => { ++ eprintln!("error: {error}"); ++ 1 ++ } ++ } ++} ++#[cfg(test)] ++mod tests { ++ use super::*; ++ #[test] ++ fn output_admission_precedes_allocation_and_failed_writes_preserve_prefix() { ++ let mut output = BoundedOutput { ++ bytes: Vec::new(), ++ limit: 5, ++ }; ++ output.write_all(b"123").unwrap(); ++ assert!(output.write_all(b"456").is_err()); ++ assert_eq!(output.bytes, b"123"); ++ assert!(output.bytes.capacity() <= 5); ++ output.write_all(b"45").unwrap(); ++ assert_eq!(output.bytes, b"12345"); ++ } ++ #[test] ++ fn invalid_utf8_names_keep_exact_bytes_instead_of_lossy_text() { ++ let mut map = BTreeMap::new(); ++ map.insert( ++ VarnodeStorage { ++ space: None, ++ offset: u64::MAX, ++ size: 1, ++ }, ++ vec![0xff, 0x00], ++ ); ++ let value = serde_json::to_value(Registers(&map)).unwrap(); ++ assert!(value[0]["name"].is_null()); ++ assert_eq!(value[0]["name_bytes_hex"], "ff00"); ++ assert_eq!(value[0]["offset"], "0xffffffffffffffff"); ++ } ++} diff --git a/decompiler/crates/kuna-console/src/inspect.rs b/decompiler/crates/kuna-console/src/inspect.rs index 74024b10..9e36d55f 100644 --- a/decompiler/crates/kuna-console/src/inspect.rs diff --git a/experiments/atomic-codemode/native-catalog-reads.mjs b/experiments/atomic-codemode/native-catalog-reads.mjs new file mode 100644 index 00000000000..25b08fe3825 --- /dev/null +++ b/experiments/atomic-codemode/native-catalog-reads.mjs @@ -0,0 +1,87 @@ +// Fixed per-lease catalogs share source admission; queries do not create cache keys. +import { parseFunctionFacts, selectFunctionFacts } from "./function-facts.mjs"; +import { parseStringFacts, selectStringFacts } from "./string-facts.mjs"; +import { parseNativeStorageMap } from "./native-storage-map.mjs"; +import { sourceSummary } from "./fact-reads.mjs"; +import { FactFailure } from "./fact-error.mjs"; + +const catalogs = { + functions: { + arguments: (path) => ["functions", path, "--json"], + parse: parseFunctionFacts, + }, + strings: { + arguments: (path) => [ + "strings", + path, + "--json", + "--encoding", + "all", + "--min-length", + "5", + "--termination", + "any", + "--no-xrefs", + ], + parse: parseStringFacts, + }, + storage: { + arguments: (path) => ["storage-map", path, "--json"], + parse: parseNativeStorageMap, + }, +}; +export class NativeCatalogReads { + #loaded = new Map(); + constructor(capture, readSource, requireStorage) { + this.capture = capture; + this.readSource = readSource; + this.requireStorage = requireStorage; + } + async #load(name, signal) { + if (name === "storage") this.requireStorage(); + if (!this.#loaded.has(name)) { + const definition = catalogs[name], + capture = await this.capture(name, definition.arguments, signal); + try { + const facts = await definition.parse( + await this.readSource(capture.source.evidence_id), + capture.input, + ); + this.#loaded.set(name, { + facts, + source: Object.freeze(sourceSummary(capture.source)), + }); + } catch (error) { + throw new FactFailure( + error.code ?? "invalid_provider_output", + error.message, + { + ...error.details, + evidence_id: capture.source.evidence_id, + source_retained: true, + }, + ); + } + } + return this.#loaded.get(name); + } + async functions(input, signal) { + const { facts, source } = await this.#load("functions", signal); + return { source, ...selectFunctionFacts(facts, input) }; + } + async strings(input, signal) { + const { facts, source } = await this.#load("strings", signal); + return { source, ...selectStringFacts(facts, input) }; + } + async spaces(input, signal) { + const { facts, source } = await this.#load("storage", signal); + return { source, ...facts.spaces(input) }; + } + async registers(input, signal) { + const { facts, source } = await this.#load("storage", signal); + return { source, ...facts.registers(input) }; + } + clear() { + this.#loaded.clear(); + } +} diff --git a/experiments/atomic-codemode/native-contract.mjs b/experiments/atomic-codemode/native-contract.mjs index 3bb44c9c1eb..a9dedf383ae 100644 --- a/experiments/atomic-codemode/native-contract.mjs +++ b/experiments/atomic-codemode/native-contract.mjs @@ -6,6 +6,8 @@ export const requireFact = (condition, reason) => { if (!condition) throw new FactFailure("invalid_provider_output", reason); }; export const hex = z.string().regex(/^0x(?:0|[1-9a-f][0-9a-f]{0,15})$/u); +export const nativeLocationKey = ({ space, offset, size_bytes }) => + JSON.stringify([space, offset, size_bytes]); export const edgeId = z.string().regex(/^\d+:\d+$/u); export const ordinal = z.number().int().nonnegative().max(0x7fffffff); export const valueId = z.string().regex(/^v[0-9a-f]{1,16}$/u); @@ -66,7 +68,7 @@ export const formatFailure = (error) => { : { reason: String(error.message).slice(0, 256) }; return new FactFailure( "invalid_provider_output", - "Native IR source does not match the declared format", + "Native source does not match the declared format", details, ); }; diff --git a/experiments/atomic-codemode/native-reads.mjs b/experiments/atomic-codemode/native-reads.mjs index 72ef75970c3..8b3670653f8 100644 --- a/experiments/atomic-codemode/native-reads.mjs +++ b/experiments/atomic-codemode/native-reads.mjs @@ -1,5 +1,5 @@ import { pageFacts } from "./fact-reads.mjs"; -import { requireFact } from "./native-contract.mjs"; +import { requireFact, nativeLocationKey } from "./native-contract.mjs"; export const nativePage = ( rows, @@ -27,9 +27,6 @@ export const readNativeIdentities = (index, input, filter = () => true) => ({ : [], }); -const locationKey = ({ space, offset, size_bytes }) => - JSON.stringify([space, offset, size_bytes]); - // One owner for graph, projection and call-boundary value selection. The lazy // index contains only retained facts, never arbitrary caller query/cache keys. export function createNativeValueReader(values, coverage) { @@ -43,7 +40,7 @@ export function createNativeValueReader(values, coverage) { unknownSpaces++; continue; } - const key = locationKey(row); + const key = nativeLocationKey(row); if (!locations.has(key)) locations.set(key, []); locations.get(key).push(row); } @@ -57,7 +54,7 @@ export function createNativeValueReader(values, coverage) { const requested = input.locations === undefined ? null - : new Map(input.locations.map((row) => [locationKey(row), row])); + : new Map(input.locations.map((row) => [nativeLocationKey(row), row])); const groups = requested ? locate(requested) : null; const candidates = input.ids ? [...new Set(input.ids)].flatMap((id) => values.get(id) ?? []) @@ -68,7 +65,9 @@ export function createNativeValueReader(values, coverage) { ...nativePage( candidates.filter( (row) => - (!requested || !input.ids || requested.has(locationKey(row))) && + (!requested || + !input.ids || + requested.has(nativeLocationKey(row))) && (input.is_input === undefined || row.is_input === input.is_input), ), input, diff --git a/experiments/atomic-codemode/native-storage-map.mjs b/experiments/atomic-codemode/native-storage-map.mjs new file mode 100644 index 00000000000..9362cf52351 --- /dev/null +++ b/experiments/atomic-codemode/native-storage-map.mjs @@ -0,0 +1,245 @@ +// Parse one bounded native architecture catalog; views never reinterpret names. +import { z } from "zod"; +import { NATIVE_OUTPUT_BYTES } from "./limits.mjs"; +import { + nativeLocationKey, + hex, + ordinal, + rowParser, + requireFact, + formatFailure, +} from "./native-contract.mjs"; +import { freezeFacts } from "./fact-reads.mjs"; +import { nativePage } from "./native-reads.mjs"; + +const u32 = z.number().int().nonnegative().max(0xffffffff); +const space = z.strictObject({ + native_index: ordinal, + name: z.string().min(1), + kind: z.string().min(1), + address_size_bytes: u32, + addressable_unit_bytes: u32.positive(), + endianness: z.enum(["big", "little"]), + highest_offset: hex, +}); +const register = z.strictObject({ + native_row: ordinal, + space: z.string().min(1).nullable(), + offset: hex, + size_bytes: u32.positive(), + name: z.string().nullable(), + name_bytes_hex: z + .string() + .regex(/^(?:[0-9a-f]{2})*$/u) + .nullable(), +}); +const schema = z.strictObject({ + schema_version: z.literal(1), + binary: z.string(), + architecture: z.strictObject({ + native_id: z.string().min(1), + default_code_space: z.string().min(1).nullable(), + }), + space_index_capacity: ordinal, + register_count: ordinal, + spaces: z.array(space), + registers: z.array(register), + coverage: z.strictObject({ + scope: z.string(), + native_exact_register_map: z.literal("complete"), + alias_relationships: z.literal("unknown"), + dynamic_join_records: z.literal("not-collected"), + memory_values: z.literal("not-returned"), + listing_discovery: z.literal(false), + functions_decompiled: z.literal(0), + }), +}); +// A valid record necessarily occupies at least this many wire bytes. Admit row +// counts before mapping malformed arrays or allocating their parsed rows. +const minSpaceBytes = Buffer.byteLength( + JSON.stringify({ + native_index: 0, + name: "x", + kind: "x", + address_size_bytes: 0, + addressable_unit_bytes: 1, + endianness: "big", + highest_offset: "0x0", + }), +); +const minRegisterBytes = Buffer.byteLength( + JSON.stringify({ + native_row: 0, + space: "x", + offset: "0x0", + size_bytes: 1, + name: "", + name_bytes_hex: null, + }), +); +const parse = rowParser(schema, { + spaces: (r) => space.parse(r), + registers: (r) => register.parse(r), +}); +export function parseNativeStorageMap(text, expectedInput) { + try { + requireFact( + Buffer.byteLength(text) <= NATIVE_OUTPUT_BYTES, + "Native storage map exceeds wire budget", + ); + const raw = JSON.parse(text); + for (const [name, minimum] of [ + ["spaces", minSpaceBytes], + ["registers", minRegisterBytes], + ]) + requireFact( + Array.isArray(raw?.[name]) && + raw[name].length <= Math.floor(NATIVE_OUTPUT_BYTES / minimum), + `Native storage ${name} exceeds format-derived row capacity`, + ); + const facts = parse(raw); + requireFact( + facts.binary === expectedInput, + "Native storage map input differs from requested subject", + ); + requireFact( + facts.register_count === facts.registers.length, + "Native register count mismatch", + ); + const spacesByName = new Map(), + spacesByIndex = new Map(), + byLocation = new Map(), + byName = new Map(); + for (const row of facts.spaces) { + requireFact( + row.native_index < facts.space_index_capacity && + !spacesByName.has(row.name) && + !spacesByIndex.has(row.native_index), + "Duplicate or invalid native space identity", + ); + spacesByName.set(row.name, row); + spacesByIndex.set(row.native_index, row); + } + requireFact( + facts.architecture.default_code_space === null || + spacesByName.has(facts.architecture.default_code_space), + "Unretained native default code space", + ); + for (const [index, row] of facts.registers.entries()) { + requireFact( + row.native_row === index, + "Native register row identity mismatch", + ); + requireFact( + (row.name === null) === (row.name_bytes_hex !== null), + "Native register name/byte knowledge mismatch", + ); + requireFact( + row.space === null || spacesByName.has(row.space), + "Register references unretained native space", + ); + if (row.space !== null) { + const key = nativeLocationKey(row); + requireFact(!byLocation.has(key), "Duplicate native register location"); + byLocation.set(key, row); + } + if (row.name !== null) { + if (!byName.has(row.name)) byName.set(row.name, []); + byName.get(row.name).push(row); + } + } + freezeFacts(facts); + return createViews(facts, { + spacesByName, + spacesByIndex, + byLocation, + byName, + }); + } catch (error) { + throw formatFailure(error); + } +} +function createViews( + facts, + { spacesByName, spacesByIndex, byLocation, byName }, +) { + const metadata = freezeFacts({ + architecture: facts.architecture, + totals: { + spaces: facts.spaces.length, + space_index_capacity: facts.space_index_capacity, + registers: facts.register_count, + }, + coverage: { + ...facts.coverage, + unmatched_selectors: + "no retained exact map match; not absence of hardware storage, aliases or runtime values", + names: "native varnode_xref names; not every translator symbol/alias", + unknown_space_register_count: facts.registers.filter( + (r) => r.space === null, + ).length, + undecodable_name_count: facts.registers.filter((r) => r.name === null) + .length, + }, + }); + return Object.freeze({ + spaces(input) { + const names = input.names && [...new Set(input.names)], + indices = input.indices && [...new Set(input.indices)]; + const rows = ( + indices + ? indices.flatMap((i) => spacesByIndex.get(i) ?? []) + : names + ? names.flatMap((n) => spacesByName.get(n) ?? []) + : facts.spaces + ).filter( + (r) => + (!names || names.includes(r.name)) && + (!indices || indices.includes(r.native_index)), + ); + return { + ...metadata, + ...nativePage(rows, input, ["native_index", "name"]), + missing_names: names?.filter((n) => !spacesByName.has(n)) ?? [], + missing_indices: indices?.filter((i) => !spacesByIndex.has(i)) ?? [], + }; + }, + registers(input) { + const names = input.names && new Set(input.names), + locations = + input.locations && + new Map(input.locations.map((r) => [nativeLocationKey(r), r])); + const normalize = (s) => (input.case_sensitive ? s : s.toLowerCase()), + query = normalize(input.query ?? ""); + const rows = locations + ? [...locations.keys()].flatMap((k) => byLocation.get(k) ?? []) + : names + ? [...names].flatMap((n) => byName.get(n) ?? []) + : facts.registers; + return { + ...metadata, + ...nativePage( + rows.filter( + (r) => + (!names || names.has(r.name)) && + (!query || + (r.name !== null && normalize(r.name).includes(query))), + ), + input, + ["native_row", "space", "offset", "size_bytes"], + ), + unretained_names: names ? [...names].filter((n) => !byName.has(n)) : [], + ...(locations + ? { + unretained_locations: [...locations] + .filter(([k]) => !byLocation.has(k)) + .map(([, r]) => ({ ...r })), + unretained_space_names: [ + ...new Set([...locations.values()].map((r) => r.space)), + ].filter((n) => !spacesByName.has(n)), + } + : {}), + }; + }, + }); +} diff --git a/experiments/atomic-codemode/native-storage-map.test.mjs b/experiments/atomic-codemode/native-storage-map.test.mjs new file mode 100644 index 00000000000..592e6b658c9 --- /dev/null +++ b/experiments/atomic-codemode/native-storage-map.test.mjs @@ -0,0 +1,393 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { parseNativeStorageMap } from "./native-storage-map.mjs"; +import { NativeCatalogReads } from "./native-catalog-reads.mjs"; +import { FactFailure } from "./fact-error.mjs"; +import { methods } from "./api.mjs"; +import { NATIVE_OUTPUT_BYTES } from "./limits.mjs"; + +// Deliberately sparse spaces, duplicate names, one unknown space and raw bytes. +const fixture = () => ({ + schema_version: 1, + binary: "/selected/input", + architecture: { native_id: "test:model", default_code_space: "ram" }, + space_index_capacity: 9, + register_count: 6, + spaces: [ + { + native_index: 3, + name: "ram", + kind: "IPTR_PROCESSOR", + address_size_bytes: 8, + addressable_unit_bytes: 1, + endianness: "big", + highest_offset: "0xffffffffffffffff", + }, + { + native_index: 4, + name: "register", + kind: "IPTR_PROCESSOR", + address_size_bytes: 4, + addressable_unit_bytes: 1, + endianness: "little", + highest_offset: "0xffffffff", + }, + { + native_index: 8, + name: "stack", + kind: "IPTR_SPACEBASE", + address_size_bytes: 8, + addressable_unit_bytes: 2, + endianness: "big", + highest_offset: "0xffffffffffffffff", + }, + ], + registers: [ + { + native_row: 0, + space: "register", + offset: "0x8", + size_bytes: 8, + name: "RCX", + name_bytes_hex: null, + }, + { + native_row: 1, + space: "register", + offset: "0x8", + size_bytes: 2, + name: "CX", + name_bytes_hex: null, + }, + { + native_row: 2, + space: "register", + offset: "0x10", + size_bytes: 2, + name: "CX", + name_bytes_hex: null, + }, + { + native_row: 3, + space: null, + offset: "0xffffffffffffffff", + size_bytes: 1, + name: "", + name_bytes_hex: null, + }, + { + native_row: 4, + space: "register", + offset: "0x0", + size_bytes: 1, + name: null, + name_bytes_hex: "ff00", + }, + { + native_row: 5, + space: "register", + offset: "0x1", + size_bytes: 1, + name: "x.y", + name_bytes_hex: null, + }, + ], + coverage: { + scope: "test exact map", + native_exact_register_map: "complete", + alias_relationships: "unknown", + dynamic_join_records: "not-collected", + memory_values: "not-returned", + listing_discovery: false, + functions_decompiled: 0, + }, +}); +const parse = (doc = fixture()) => + parseNativeStorageMap(JSON.stringify(doc), "/selected/input"); +const select = (view, method, input = {}) => + view[method](methods[method].input.parse(input)); + +test("space identity, sparse indices, caller order, projection and absence before paging", () => { + const view = parse(); + const reply = select(view, "spaces", { + indices: [8, 3, 8, 7], + names: ["stack", "ram", "missing"], + fields: ["addressable_unit_bytes"], + limit: 1, + }); + assert.deepEqual(reply.items, [ + { native_index: 8, name: "stack", addressable_unit_bytes: 2 }, + ]); + assert.deepEqual(reply.missing_names, ["missing"]); + assert.deepEqual(reply.missing_indices, [7]); + assert.equal(reply.total, 2); + assert.equal(reply.next_offset, 1); + assert.equal(reply.totals.space_index_capacity, 9); + assert.equal(reply.totals.spaces, 3); + assert.deepEqual( + select(view, "spaces", { names: ["stack", "ram"], fields: [] }).items, + [ + { native_index: 8, name: "stack" }, + { native_index: 3, name: "ram" }, + ], + ); + for (const input of [{ names: [] }, { indices: [] }]) + assert.equal(select(view, "spaces", input).total, 0); +}); + +test("register lookup uses exact space/offset/width, keeps misses before filtering and does not substitute containing registers", () => { + const view = parse(), + locations = [ + { space: "register", offset: "0x8", size_bytes: 2 }, + { space: "register", offset: "0x8", size_bytes: 8 }, + { space: "register", offset: "0x8", size_bytes: 3 }, + { space: "unknown", offset: "0x8", size_bytes: 8 }, + { space: "stack", offset: "0x8", size_bytes: 8 }, + ]; + const reply = select(view, "registers", { + locations: [...locations, locations[0]], + fields: ["name"], + limit: 1, + }); + assert.deepEqual(reply.items, [ + { native_row: 1, ...locations[0], name: "CX" }, + ]); + assert.equal(reply.total, 2); + assert.deepEqual(reply.unretained_locations, locations.slice(2)); + assert.deepEqual(reply.unretained_space_names, ["unknown"]); + const intersect = select(view, "registers", { + locations, + names: ["RCX", "rcx"], + query: "cx", + }); + assert.equal(intersect.total, 1); + assert.deepEqual(intersect.unretained_names, ["rcx"]); + assert.deepEqual(intersect.unretained_locations, locations.slice(2)); + assert.equal(select(view, "registers", { locations: [] }).total, 0); +}); + +test("register names preserve multiplicity, exact-case names, substring semantics and explicit unknowns", () => { + const view = parse(); + assert.deepEqual( + select(view, "registers", { + names: ["CX", "RCX", "CX"], + fields: [], + }).items.map((r) => r.native_row), + [1, 2, 0], + ); + assert.equal(select(view, "registers", { query: "cx" }).total, 3); + assert.equal( + select(view, "registers", { query: "cx", case_sensitive: true }).total, + 0, + ); + assert.equal(select(view, "registers", { query: "." }).total, 1); + assert.equal(select(view, "registers", { names: [] }).total, 0); + const reply = select(view, "registers", { offset: 3 }); + assert.deepEqual(reply.items[0], fixture().registers[3]); + assert.deepEqual(reply.items[1], fixture().registers[4]); + assert.equal(reply.coverage.unknown_space_register_count, 1); + assert.equal(reply.coverage.undecodable_name_count, 1); + assert.equal(select(view, "registers", { names: [""] }).items[0].space, null); +}); + +test("SDK views cannot change retained storage metadata or subsequent queries", () => { + const view = parse(), + reply = select(view, "registers"); + for (const change of [ + () => { + reply.items[0].name = "foreign"; + }, + () => { + reply.architecture.native_id = "foreign"; + }, + () => { + reply.totals.registers = 0; + }, + () => { + reply.coverage.functions_decompiled = 1; + }, + ]) + assert.throws(change, TypeError); + reply.items.length = 0; + assert.equal(select(view, "registers").items.length, 6); +}); + +test("malformed source fails closed at identity, reference and knowledge boundaries", () => { + const mutations = [ + (d) => { + d.binary = "/other"; + }, + (d) => { + d.schema_version = 2; + }, + (d) => { + d.register_count++; + }, + (d) => { + d.registers[1].native_row = 0; + }, + (d) => { + d.spaces[1].native_index = 3; + }, + (d) => { + d.spaces[1].name = "ram"; + }, + (d) => { + d.spaces[0].native_index = 9; + }, + (d) => { + d.architecture.default_code_space = "missing"; + }, + (d) => { + d.registers[1].space = "missing"; + }, + (d) => { + d.registers[1].size_bytes = 8; + }, + (d) => { + d.registers[4].name_bytes_hex = null; + }, + (d) => { + d.registers[0].name_bytes_hex = "ff"; + }, + (d) => { + d.registers[0].offset = "0x08"; + }, + (d) => { + d.registers[0].size_bytes = 0; + }, + (d) => { + d.registers[4].name_bytes_hex = "f"; + }, + (d) => { + d.coverage.functions_decompiled = 1; + }, + (d) => { + d.spaces = null; + }, + (d) => { + d.registers = []; + }, + ]; + for (const mutate of mutations) { + const doc = fixture(); + mutate(doc); + assert.throws( + () => parse(doc), + (e) => e.code === "invalid_provider_output", + ); + } + assert.throws( + () => + parseNativeStorageMap( + " ".repeat(NATIVE_OUTPUT_BYTES + 1), + "/selected/input", + ), + /wire budget/, + ); + const doc = fixture(); + doc.registers = Array(100000).fill(null); + assert.throws(() => parse(doc), /format-derived row capacity/); +}); + +test("one immutable storage capture powers both catalog views; clear creates a new lease cache", async () => { + const captures = [], + source = { + evidence_id: "ev_source", + sha256: "digest", + bytes: 10, + elapsed_ms: 1, + }; + let guards = 0; + const reader = new NativeCatalogReads( + async (name, args, signal) => { + captures.push({ name, args: args("/selected/input"), signal }); + return { input: "/selected/input", source }; + }, + async (id) => { + assert.equal(id, source.evidence_id); + return JSON.stringify(fixture()); + }, + () => { + guards++; + }, + ); + const signal = new AbortController().signal; + const first = await reader.spaces({}, signal); + assert.throws(() => { + first.source.sha256 = "foreign"; + }, TypeError); + await reader.registers({ names: ["CX"] }, signal); + await reader.spaces({ names: [] }, signal); + assert.equal(captures.length, 1); + assert.deepEqual(captures[0], { + name: "storage", + args: ["storage-map", "/selected/input", "--json"], + signal, + }); + assert.equal(guards, 3); + reader.clear(); + await reader.registers({}, signal); + assert.equal(captures.length, 2); +}); + +test("catalog errors retain source and typed execution failures, never caching a failed parse", async () => { + let text = "invalid", + reads = 0, + captures = 0; + const reader = new NativeCatalogReads( + async () => { + captures++; + return { + input: "/selected/input", + source: { evidence_id: "ev_bad", sha256: "digest" }, + }; + }, + async () => { + reads++; + return text; + }, + () => {}, + ); + await assert.rejects( + reader.spaces({}), + (e) => + e.code === "invalid_provider_output" && + e.details.evidence_id === "ev_bad" && + e.details.source_retained, + ); + text = JSON.stringify(fixture()); + await reader.registers({}); + await reader.spaces({}); + assert.equal(reads, 2); + assert.equal(captures, 2); + for (const code of [ + "cancelled", + "cleanup_incomplete", + "capacity", + "command_failed", + ]) { + const expected = new FactFailure(code, "native failed", { + reason: "actual", + }); + const failing = new NativeCatalogReads( + async () => { + throw expected; + }, + () => assert.fail("must not read"), + () => {}, + ); + await assert.rejects(failing.spaces({}), (e) => e === expected); + } + const unavailable = new NativeCatalogReads( + () => assert.fail("must not launch"), + () => assert.fail("must not read"), + () => { + throw new FactFailure("capability_unavailable", "not configured"); + }, + ); + await assert.rejects( + unavailable.registers({}), + (e) => e.code === "capability_unavailable", + ); +}); diff --git a/experiments/atomic-codemode/provider.mjs b/experiments/atomic-codemode/provider.mjs index ace16251aca..7f30c66d2a1 100644 --- a/experiments/atomic-codemode/provider.mjs +++ b/experiments/atomic-codemode/provider.mjs @@ -9,13 +9,12 @@ import { referenceReader } from "./reference-reads.mjs"; import { PrivateRuntimeRoot } from "../../dist/process/PrivateRuntimeRoot.js"; import { parseNativeIR } from "./native-ir.mjs"; import { NativeEvidenceReads } from "./native-evidence-reads.mjs"; +import { NativeCatalogReads } from "./native-catalog-reads.mjs"; import { DEFAULT_NATIVE_OPERATION_FIELDS } from "./native-operation-views.mjs"; import { FactFailure, requireResult } from "./fact-error.mjs"; import { windowReaders } from "./window-readers.mjs"; import { NATIVE_OUTPUT_BYTES } from "./limits.mjs"; import { sourceSummary, projectFact, readFactBatch } from "./fact-reads.mjs"; -import { parseFunctionFacts, selectFunctionFacts } from "./function-facts.mjs"; -import { parseStringFacts, selectStringFacts } from "./string-facts.mjs"; import { parseKunaSsaDump, backwardSlice, @@ -40,8 +39,11 @@ export class KunaFactOwner { #target; #installation; #retainedBytes = 0; - #strings; - #functions; + #catalogs = new NativeCatalogReads( + (...args) => this.#native(...args), + (id) => this.#sourceText(id), + () => this.#requireNativeIR(), + ); #captureDirectory; #evidence = new NativeEvidenceReads(async (id) => ({ text: await this.#sourceText(id), @@ -104,7 +106,7 @@ export class KunaFactOwner { ? "experimental-native-ir-v3" : "diagnostic-ssa-1.833", profile: owner.#nativeIR - ? "pinned engine with embedded specs; fresh private engine cache per lease; byte reads suppress global discovery; other native CLI defaults; no annotations" + ? "pinned engine with embedded specs; fresh private engine cache per lease; byte/storage metadata reads suppress global discovery; other native CLI defaults; no annotations" : "byte reads suppress global discovery; other native CLI defaults, no annotations; external spec cache freshness is not fingerprinted", }); return owner; @@ -189,44 +191,16 @@ export class KunaFactOwner { return text; } async strings(input, signal) { - const capture = await this.#native( - "strings", - (path) => [ - "strings", - path, - "--json", - "--encoding", - "all", - "--min-length", - "5", - "--termination", - "any", - "--no-xrefs", - ], - signal, - ); - this.#strings ??= await parseStringFacts( - await this.#sourceText(capture.source.evidence_id), - capture.input, - ); - return { - source: sourceSummary(capture.source), - ...selectStringFacts(this.#strings, input), - }; + return this.#catalogs.strings(input, signal); } async functions(input, signal) { - const capture = await this.#native( - "functions", - (path) => ["functions", path, "--json"], - signal, - ); - this.#functions ??= parseFunctionFacts( - await this.#sourceText(capture.source.evidence_id), - ); - return { - source: sourceSummary(capture.source), - ...selectFunctionFacts(this.#functions, input), - }; + return this.#catalogs.functions(input, signal); + } + async spaces(input, signal) { + return this.#catalogs.spaces(input, signal); + } + async registers(input, signal) { + return this.#catalogs.registers(input, signal); } async references(input, signal) { return readFactBatch( @@ -493,8 +467,7 @@ export class KunaFactOwner { this.#sources.clear(); this.#work.clear(); this.#snapshots.clear(); - this.#strings = undefined; - this.#functions = undefined; + this.#catalogs.clear(); this.#evidence.clear(); } cancel() { diff --git a/experiments/atomic-codemode/reference.mjs b/experiments/atomic-codemode/reference.mjs index 1b15edb8eea..5f09c286c3c 100644 --- a/experiments/atomic-codemode/reference.mjs +++ b/experiments/atomic-codemode/reference.mjs @@ -11,6 +11,10 @@ export const referenceInput = z.strictObject({ // Compact return contracts let code compose before first observing a response. const returns = { + spaces: + "data:{source:{evidence_id,sha256},architecture:{native_id,default_code_space},totals:{spaces,space_index_capacity,registers},items:[{native_index,name,kind?,address_size_bytes?,addressable_unit_bytes?,endianness?,highest_offset?}],total,next_offset,missing_names,missing_indices,coverage}. Identity always stays. Counts are native catalog counts, not runtime memory or ABI truth; native indices only interpret identified space-selector operands. Default returns all descriptor fields, paged.", + registers: + "data:{source:{evidence_id,sha256},architecture,totals,items:[{native_row,space:string|null,offset,size_bytes,name?:string|null,name_bytes_hex?:string|null}],total,next_offset,unretained_names,unretained_locations?,unretained_space_names?,coverage}. Native row and exact tuple stay under projection. Name strings remain exact (including empty); null name preserves undecodable bytes in name_bytes_hex. Missing selectors describe the retained exact native map, not aliases/hardware absence; tuples include width and space. Native register names and value identities are separate facts. Complete immutable catalog Evidence is shared with spaces until lease close.", switches: "data:{items:[{id,origin_address,block,selector:{native value fields}|null,table:{partial,labelled,consumed_mask,signed_render_hint,default_raw_index,default_edge:{id,index,target}|null,default_is_folded,case_count,mapping_count,relation_count,known_label_count,missing_label_count,no_label_count,unmapped_row_count,unknown_target_count}|null}],total,next_offset,missing,evidence_id,coverage}. No case inventory is embedded. selector is the native current BRANCHIND input and can be normalized; default_raw_index=-1/default_edge:null means undefined, not proof of no default. signed_render_hint does not establish general signedness. default_edge is the native model default, not necessarily the machine out-of-range guard destination. relations kind:cases reads selected original rows and mappings, even without a full graph if the independent switch facet exists.", bytes: diff --git a/experiments/atomic-codemode/reference.test.mjs b/experiments/atomic-codemode/reference.test.mjs index 9ce8a36c0db..01ab3e40036 100644 --- a/experiments/atomic-codemode/reference.test.mjs +++ b/experiments/atomic-codemode/reference.test.mjs @@ -35,7 +35,7 @@ test("reference index discovers named methods without constructing unrequested s /Unknown reference view/, ); const all = reference("", { view: "index" }); - assert.equal(all.methods.length, 17); + assert.equal(all.methods.length, 19); assert.ok( all.methods.some( (m) => m.method === "relations" && m.description.includes("operands"), @@ -75,7 +75,7 @@ test("named reference lists preserve caller order and exact schemas across prese ["facts_values", "facts_snapshot"], ); assert.deepEqual(result.unmatched_queries, ["unknown"]); - assert.equal(result.coverage.declared_methods, 17); + assert.equal(result.coverage.declared_methods, 19); assert.equal(result.coverage.matched_methods, 2); assert.equal(result.coverage.selection, "named"); const javascript = reference("rea.values snapshot"); @@ -104,7 +104,7 @@ test("named reference lists preserve caller order and exact schemas across prese }); test("topic/all reference selection and shared schema ownership remain explicit", () => { - assert.equal(reference().methods.length, 17); + assert.equal(reference().methods.length, 19); assert.equal(reference("no-such-topic").coverage.matched_methods, 0); assert.ok( reference("memory aliases").methods.some((m) => m.method === "slice"), diff --git a/experiments/atomic-codemode/storage-boundary-oracle.md b/experiments/atomic-codemode/storage-boundary-oracle.md new file mode 100644 index 00000000000..14b716c8833 --- /dev/null +++ b/experiments/atomic-codemode/storage-boundary-oracle.md @@ -0,0 +1,51 @@ +# Architecture storage composition oracle + +Freeze this question, runtime, full catalogs and oracle before the real models. +The question extends the [function-boundary question](function-boundary-question.txt) +with exact native storage names and address-space descriptors. All correctness +criteria and independent instruction checks in the [boundary oracle](function-boundary-oracle.md) +remain required. This is a new task; old timings are not an equivalent before/after +comparison. No addresses, counts or tuple/name answers are embedded in the prompt. + +The selected artifact remains `/usr/bin/ssh`, SHA-256 +`04f2ff5f506a3f332e7adeb1478a4c551ae74acdd328e6fb5c2495664d4064e6`. +Both lanes use the same immutable experimental engine SHA-256 +`c48ad95784ce7b26beb966b054fe103b11922c8aa8cbe7c4144f3daa1d5d45fe`, +upstream `fe01d6294eb0d1053ce343c8943646df88e143fc` plus the committed overlay. +The full earlier function records must remain unchanged except the previously +added parameters facet; adding the CLI metadata operation must not alter IR. + +The bootstrapped model is `x86:LE:64:default:gcc`, default code space `ram`. +Its canonical exact register map contains 1,440 rows, and its nine populated +spaces fill nine native index slots. The required descriptors are: + +| Space | Index | Native kind | Address bytes | Unit bytes | Endianness | +| -------- | ----- | -------------- | ------------- | ---------- | ---------- | +| ram | 3 | IPTR_PROCESSOR | 8 | 1 | little | +| register | 4 | IPTR_PROCESSOR | 4 | 1 | little | +| stack | 8 | IPTR_SPACEBASE | 8 | 1 | little | + +Banner native slots 0–3 name RDI, RSI, RDX, RCX respectively. Caller slots 0–5 +name RDI, RSI, RDX, CX, R8, R9D; its four stack tuples have no retained exact +register-map match. Caller return storage names RAX. Explicit void on the +banner output is preserved; it has no return storage to name. Same-offset +caller CX (two bytes) and banner RCX (eight bytes) are different exact tuples. +No subregister/alias relation or original ABI follows from that observation. + +The selected caller value `v10000a9cf` has own storage register:0xb8/8 (R15), +whereas CALL `0x28d53:779` passes it in register:0x38/8 (RDI). Banner slot 0 and +its matched input `v30000002e` have RDI storage; the first helper call uses it +at recovered operand 1. Different snapshot-local SSA identities must remain +separate. The machine MOV/call/helper evidence stays independently required. +Native exact metadata names these coordinates; it does not establish live +memory, source signatures, runtime binding, aliasing or general stack rebasing. + +Score the complete final answer, delivered native/source identities and target +digest, the original counts/indices/flags/exact input matches, all new tuple/name +and space descriptors, selected transfer plus machine corroboration, coverage +and lease close. Record every real attempt, including failure. Both actual +MCP routes receive all nineteen methods (twenty-two direct tools or four Code +Mode tools), the same question, requested gpt-6.1-sol/high and isolated profiles. +Native caches are fresh per lease; OS/model caches and model build are unknown. +Compare whole-task tokens, outputs/reasoning, calls/retries/waits, elapsed/CPU +and kernel family memory. No native-only traditional-provider cell is invented. diff --git a/experiments/atomic-codemode/storage-boundary-question.txt b/experiments/atomic-codemode/storage-boundary-question.txt new file mode 100644 index 00000000000..358ea5d8d24 --- /dev/null +++ b/experiments/atomic-codemode/storage-boundary-question.txt @@ -0,0 +1,47 @@ +Analyze {{artifact_path}} statically from these two observed formats: +- REMOTE HOST IDENTIFICATION HAS CHANGED +- Host key for %.200s has changed and you have requested strict checking. + +Identify the function that passes the banner format to its logging/formatting +call, and the caller that owns the strict-checking diagnostic. Establish both +from real references, not guessed source names. Reuse one retained native +capture per selected function and selected structured facts. + +For both functions, inspect the native recovered function prototype separately +from raw input varnodes. Report its parameter-entry count, each native parameter +index with storage/width, return descriptor including explicit void/type/storage +knowledge, native model label, lock state and recovery-error flags. The model +label and recovered entries are not a proven original ABI or source signature. +Keep explicit unknowns and native hidden/indirect-storage flags. + +Count retained values marked is_input in each complete recovered graph. For +each native parameter storage tuple, determine whether an exact space/offset/ +width match exists among those retained input values, preserving matched value +IDs and explicitly reporting missing matches. Do not treat missing retained +matches as proof that a source parameter is absent. Do the two inventories +mean the same thing? Can either count establish original source arity? Use +the observed facts to explain the distinction, without parsing a C declaration. + +At the selected direct caller-to-banner-function call, show the target and the +passed pointer's recovered operand index, value identity, storage and width. +Relate that transfer to the callee's matching native parameter entry and its +first helper-call use. Keep the two snapshots' SSA identities separate; matching +storage is not cross-function SSA equality or a general alias proof. Verify +the selected pointer setup/call and callee helper use with focused machine +instructions, including actual call targets and passing registers. + +Return a focused answer with real Evidence IDs, target digest and necessary +coverage. Distinguish native recovered model observations, storage-based +connections and machine corroboration from original signature/ABI/runtime +claims. Preserve unresolved stack rebasing, split/join/subregister mappings, +aliases, runtime binding and feasibility. Do not return complete C/graph reports +or execute the target. Close the target lease. + +Use native architecture metadata to name each selected register storage tuple +exactly, including widths, the caller return and the transferred value's own +storage versus its call-site passing storage. Do not substitute a containing +register for an unmatched slice. For the native code, register and stack spaces, +report kind, byte order, address-size bytes and addressable-unit bytes. Keep +stack tuples without an exact register-map match explicit, without inventing +a hardware-register name. Cite the retained native catalog separately from +function facts and machine corroboration. diff --git a/experiments/atomic-codemode/storage-contracts.mjs b/experiments/atomic-codemode/storage-contracts.mjs new file mode 100644 index 00000000000..535694a2d3d --- /dev/null +++ b/experiments/atomic-codemode/storage-contracts.mjs @@ -0,0 +1,49 @@ +// Architecture metadata contracts use the same registry through every adapter. +import { z } from "zod"; +import { definition, page, valueLocation } from "./api-contracts.mjs"; +export const storageMethods = { + spaces: definition( + { + summary: + "Select native address-space descriptors by name/index, including byte order, address units and offset bounds; no function analysis.", + description: + "Inspect the leased artifact's bootstrapped native architecture spaces. Native indices are scoped to this model; use them only for an explicitly identified native space-selector operand, not arbitrary constants. Name/index filters intersect; indices set caller order, otherwise names set caller order, otherwise native order. Missing names/indices are reported before filters/paging. Returns native kind, address size, addressable-unit bytes, endianness and highest byte offset, with architecture identity/counts and complete retained catalog Evidence. Descriptors are not runtime memory, valid pointers, stack rebasing or dynamic join records. Uses embedded specs, disables listing discovery and decompiles no function. One bounded immutable catalog is shared per lease with registers; no cross-lease/live-state cache. Requires the experimental storage-map engine capability.", + }, + { + names: z.array(z.string()).max(128).optional(), + indices: z.array(z.number().int().nonnegative()).max(128).optional(), + fields: z + .array( + z.enum([ + "kind", + "address_size_bytes", + "addressable_unit_bytes", + "endianness", + "highest_offset", + ]), + ) + .optional(), + ...page, + }, + "spaces", + "await rea.spaces({indices:[spaceSelector]})", + ), + registers: definition( + { + summary: + "Select exact native register names/coordinates in batches; widths and spaces matter, unmatched slices are not storage absence.", + description: + "Select the bootstrapped native varnode_xref register-name map by exact locations, exact names or optional name substring search. Filters intersect. Locations deduplicate in caller order; otherwise names deduplicate in caller order, preserving native row order for each name; otherwise native order. Exact names are case-sensitive; query uses case_sensitive. Missing locations/names are determined before other filters, not proof of absent hardware storage, aliases or values. No containing-register substitution, subregister/alias inference, SSA equality or runtime availability claim. Null spaces stay unknown; undecodable native names retain raw bytes. Native row plus Evidence identifies an occurrence. Architecture/counts/coverage and complete source are retained; the same bounded per-lease catalog powers spaces, with no function decompilation or cross-lease reuse.", + }, + { + locations: z.array(valueLocation).max(128).optional(), + names: z.array(z.string()).max(128).optional(), + query: z.string().default(""), + case_sensitive: z.boolean().default(false), + fields: z.array(z.enum(["name", "name_bytes_hex"])).optional(), + ...page, + }, + "registers", + 'await rea.registers({locations:[{space:"register",offset:"0x38",size_bytes:8}]})', + ), +}; diff --git a/experiments/atomic-codemode/storage-study.md b/experiments/atomic-codemode/storage-study.md new file mode 100644 index 00000000000..81a1dfa4fe8 --- /dev/null +++ b/experiments/atomic-codemode/storage-study.md @@ -0,0 +1,112 @@ +# Native architecture storage facts + +An exact storage coordinate needs its space and width before it can name a +register. The previous SSH task exposed this gap: the caller uses two-byte +register:0x8 (CX), whereas the callee has eight-byte register:0x8 (RCX). +Call argument value storage and passing storage are also separate facts. + +Two shared queries, `spaces` and `registers`, expose a native architecture +catalog. Queries select names/indices/exact tuples, fields and pages; identity, +architecture, provenance and coverage remain inline. Missing exact map entries +are not absent hardware storage. No containing-register substitution, SSA +equality, stack rebase, alias or live-value inference is performed. Empty names +and null spaces survive; undecodable names retain exact bytes. Names come from +the native canonical varnode_xref map, not every translator alias or symbol. + +The exporter reads the existing native AddrSpaceManager and Sleigh register-map +owners. It bootstraps the selected binary with embedded specs and disabled +listing/fast function discovery, and decompiles no function. Bootstrap still +loads binary/metadata; this is not a header-only read. A bounded streaming writer +admits encoded growth before allocation. One immutable 8 MiB maximum source +backs both queries per lease, with parsed immutable views and no query-key or +cross-lease cache. Successful close clears it; failed cleanup retains its owner. +Existing function/string catalogs use the same fixed-key capture owner. Catalog +sources and decoded facts cannot be mutated by SDK consumers. SDK, CLI and both +MCP adapters share the same named contracts; common coordinate identity has one +owner. There are nineteen methods, twenty-two direct tools or four Code Mode +tools. Stock Kuna integration and other provider parity are not established. + +The experiment refreshed main through `f9ccacca2` before this work. Native +upstream remains `fe01d6294eb0d1053ce343c8943646df88e143fc`, with overlay SHA-256 +`d4eb3f245359f4421294e1f9c4f476ed5b58da04cc34637b5a3ca90d0e857b71`. +The copied immutable embed-specs/opt1 engine SHA-256 is +`c48ad95784ce7b26beb966b054fe103b11922c8aa8cbe7c4144f3daa1d5d45fe`. +The overlay passes forward-index and reverse-worktree application checks. +The older pinned 770ac3f2 engine returns typed `execution_failure` for the new +native command; stock 1.833 returns `capability_unavailable` before launch. +Neither failure becomes an empty register catalog. + +## Real-provider checks before models + +Both actual MCP adapters read the stripped Debian x86-64 `/usr/bin/ssh`, digest +`04f2ff5f506a3f332e7adeb1478a4c551ae74acdd328e6fb5c2495664d4064e6`. +All nine spaces and 1,440 register rows match their complete retained source +through public paging and Evidence reads, with source digest verification. +Exact batch lookup distinguishes CX/ECX/RCX, RDI/R15/R9D, an unmatched +three-byte slice and stack storage. Empty selections remain empty. Both queries +reuse exactly one catalog source without a function snapshot. An intentionally +unusable ambient SLEIGHHOME does not override embedded spec selection. + +| Selected query | Direct wall / CPU ms | Code Mode wall / CPU ms | +| -------------------------- | -------------------- | ----------------------- | +| First space capture | 432.2 / 422.2 | 509.4 / 498.5 | +| Same-lease repeated spaces | 3.5 / 3.5 | 41.4 / 41.4 | +| Same-lease register batch | 4.0 / 4.0 | 21.3 / 21.2 | + +These are actual MCP reads, not model-task measurements. CPU includes the +local verifier/client/server/native family; first captures have fresh leases +and private native caches, while OS caches are uncontrolled. Warm queries +reuse the same immutable source. Response bytes alone are not token counts. + +The [Debian AArch64 OpenSSH package](https://deb.debian.org/debian/pool/main/o/openssh/openssh-client_10.0p1-7+deb13u4_arm64.deb) +was downloaded over HTTPS, extracted and neither installed nor executed. +Package digest is `e900c13c9a5267714fc2c2c1f369fe4a667c7dd4031266b1480250320f0bfcfb`; +binary digest is `de352e4ace7028d9816fd0ee9d22936bc1b5622c400d5b0b7df660df3426b068`. +Package signatures were not verified. Independent ELF headers select AArch64/LE; +the native model reports AARCH64:LE:64:v8A:default with nine spaces and 634 +register rows. Full paging matches retained native source. Native x0/w0 use +register:0x4000 with widths eight/four, unlike x86 coordinates. This verifies +another real architecture catalog; big-endian binaries and comprehensive +architecture/register/alias coverage remain untested. + +| Executed pre-model check | Wall s | Family CPU s | Kernel family peak MiB | +| ------------------------------------------------ | ------ | ------------ | ---------------------- | +| Storage native CLI build | 26.494 | 26.104 | 538.1 | +| Two native serializer/admission tests | 43.054 | 33.317 | 483.5 | +| 87 experiment JS tests | 5.154 | 4.939 | 82.7 | +| Direct complete catalog verifier | 1.830 | 1.618 | 198.0 | +| Code complete catalog verifier | 2.132 | 1.880 | 204.6 | +| AArch64 complete catalog verifier, initial | 8.920 | 5.523 | 194.4 | +| SDK existing zlib catalog/cache regression | 4.572 | 3.203 | 129.7 | +| Public CLI storage composition | 3.660 | 2.520 | 119.6 | +| SDK injected cleanup-failure/retry | 5.080 | 3.724 | 123.0 | +| Old pinned engine failure | 2.666 | 1.675 | 54.0 | +| Stock capability failure | 2.151 | 1.328 | 47.7 | +| Real MCP prototypes/full prior-function fidelity | 28.233 | 20.870 | 305.1 | +| Both SDK-converted MCP catalogs/schemas | 1.831 | 1.573 | 137.9 | + +These resource-run receipts use one CPU, 4 GiB hard/3 GiB early-stop memory, +TasksMax192 and swap disabled. Peaks are kernel process-family accounting, +including charged file cache, not RSS. Payload-exit observations verify counters, +zero OOM events and descendant cleanup. Final whole-scope counters are unavailable. +No global repository/native corpus gate is claimed. An initial direct verifier +attempt failed at startup after moving a shared schema without its local +snapshot binding; it retained its failed receipt, was fixed before models, and +is excluded from successful-query timings. No native operation ran in that +attempt. Whole model tasks below must charge all their own attempts. + +The final repeat of all 87 JS tests passes (5.052 s wall, 4.855 s CPU, +83.0 MiB family peak). A final AArch64 run also verifies exact x0/w0 named +queries against the pinned native SLEIGH definitions at AARCH64instructions.sinc +(register definitions beginning at 0x4000), in addition to complete-source +fidelity (1.932 s wall, 1.561 s CPU, 196.2 MiB peak). Both have zero OOM +events and verified payload cleanup. + +## Frozen real-model comparison + +The [question](storage-boundary-question.txt) and [oracle](storage-boundary-oracle.md) +extend the earlier native prototype task with exact storage-name and space +metadata requirements. Both complete actual catalogs are available. Model +results will be recorded only after the real isolated Codex/MCP runs and full +answer/source checks. This capability checkpoint does not establish a Code +Mode advantage or broad complex-software superiority. diff --git a/experiments/atomic-codemode/verify-discovery.mjs b/experiments/atomic-codemode/verify-discovery.mjs index 611bdcb2292..229aaac79bd 100644 --- a/experiments/atomic-codemode/verify-discovery.mjs +++ b/experiments/atomic-codemode/verify-discovery.mjs @@ -51,6 +51,8 @@ for (const direct of [false, true]) { ); const prefix = direct ? "facts_" : "rea."; const ids = [ + "spaces", + "registers", "switches", "path", "parameters", @@ -68,7 +70,7 @@ for (const direct of [false, true]) { ids, ); assert.deepEqual(selected.unmatched_queries, []); - assert.equal(selected.coverage.declared_methods, 17); + assert.equal(selected.coverage.declared_methods, 19); const ajv = new Ajv2020({ strict: false }); for (const tool of catalog.tools) ajv.compile(tool.inputSchema); assert.equal(Object.hasOwn(selected, "limits"), !direct); @@ -116,6 +118,15 @@ for (const direct of [false, true]) { assert.ok(catalog.tools.some((tool) => tool.name === method.name)); } for (const [name, good, bad] of [ + ["spaces", { indices: [3], fields: ["kind"] }, { indices: ["3"] }], + [ + "registers", + { + locations: [{ space: "register", offset: "0x8", size_bytes: 2 }], + fields: ["name"], + }, + { locations: [{ space: null, offset: "0x8", size_bytes: 2 }] }, + ], ["snapshot", { entry: "0xea6d0" }, { snapshot: "snap_other" }], [ "switches", @@ -216,7 +227,7 @@ for (const direct of [false, true]) { ); assert.deepEqual(missing.unmatched_queries, ["unknown"]); const all = await call(""); - assert.equal(all.methods.length, 17); + assert.equal(all.methods.length, 19); for (const method of all.methods) { ajv.compile(method.input_schema); assert.equal(method.description, methods[method.method].description); diff --git a/experiments/atomic-codemode/verify-storage.mjs b/experiments/atomic-codemode/verify-storage.mjs new file mode 100644 index 00000000000..0c2f51c1cd4 --- /dev/null +++ b/experiments/atomic-codemode/verify-storage.mjs @@ -0,0 +1,213 @@ +// Real public MCP catalog reads, retained-source fidelity and cold/warm receipts. +import assert from "node:assert/strict"; +import { createHash } from "node:crypto"; +import { writeFile } from "node:fs/promises"; +import { resolve } from "node:path"; +import { Client } from "@modelcontextprotocol/client"; +import { StdioClientTransport } from "@modelcontextprotocol/client/stdio"; +import { familyCounters } from "./family-counters.mjs"; +import { + createVerifierRun, + completeVerifierRun, + assertVerifierCleanupComplete, +} from "../../scripts/lib/verifier-run.mjs"; + +const [binary, output] = process.argv.slice(2); +assert.ok(binary && output, "Usage: verify-storage.mjs BINARY OUTPUT"); +const run = createVerifierRun(), + calls = [], + phases = [], + failures = []; +const client = new Client({ name: "rea-storage-verifier", version: "0.1.0" }); +const transport = new StdioClientTransport({ + command: process.execPath, + args: [resolve("experiments/atomic-codemode/server.mjs")], + env: { ...process.env }, + stderr: "pipe", +}); +let stderr = ""; +transport.stderr?.on("data", (chunk) => { + stderr = (stderr + chunk.toString()).slice(-8192); +}); +const call = async (name, input) => { + const reply = await client.callTool( + { name, arguments: input }, + { timeout: 180000 }, + ); + const result = JSON.parse(reply.content[0].text); + calls.push({ + name, + input, + result, + response_bytes: Buffer.byteLength(reply.content[0].text), + }); + assert.equal(result.ok, true, JSON.stringify(result)); + return result; +}; +const read = async (name, input) => { + const result = + process.env.REA_ATOMIC_ADAPTER === "direct" + ? await call(`facts_${name}`, input) + : ( + await call("execute_javascript", { + code: `return await rea.${name}(${JSON.stringify(input)});`, + }) + ).value; + assert.equal(result.ok, true, JSON.stringify(result)); + return result.data; +}; +const measure = async (phase, work) => { + const before = await familyCounters(), + start = performance.now(), + first = calls.length; + const value = await work(), + after = await familyCounters(); + phases.push({ + phase, + elapsed_ms: performance.now() - start, + family_cpu_seconds: (after.cpu - before.cpu) / 1e6, + cumulative_family_memory_peak_bytes: after.peak, + mcp_calls: calls.length - first, + response_bytes: calls + .slice(first) + .reduce((sum, c) => sum + c.response_bytes, 0), + }); + return value; +}; +let report; +try { + await client.connect(transport); + const opened = await call("open_binary", { path: binary }); + const first = await measure("first-spaces-capture", () => + read("spaces", { + indices: [3, 4, 8], + fields: [ + "kind", + "endianness", + "address_size_bytes", + "addressable_unit_bytes", + ], + }), + ); + const repeat = await measure("warm-spaces", () => + read("spaces", { + indices: [3, 4, 8], + fields: [ + "kind", + "endianness", + "address_size_bytes", + "addressable_unit_bytes", + ], + }), + ); + assert.deepEqual(repeat, first); + const selected = await measure("warm-register-batch", () => + read("registers", { + locations: [ + { space: "register", offset: "0x8", size_bytes: 2 }, + { space: "register", offset: "0x8", size_bytes: 4 }, + { space: "register", offset: "0x8", size_bytes: 8 }, + { space: "register", offset: "0x38", size_bytes: 8 }, + { space: "register", offset: "0xb8", size_bytes: 8 }, + { space: "register", offset: "0x88", size_bytes: 4 }, + { space: "register", offset: "0x8", size_bytes: 3 }, + { space: "stack", offset: "0x8", size_bytes: 8 }, + ], + fields: ["name"], + }), + ); + assert.equal(selected.source.evidence_id, first.source.evidence_id); + if (first.architecture.native_id === "x86:LE:64:default:gcc") { + assert.deepEqual( + selected.items.map((r) => r.name), + ["CX", "ECX", "RCX", "RDI", "R15", "R9D"], + ); + assert.equal(selected.unretained_locations.length, 2); + assert.deepEqual( + first.items.map((r) => r.name), + ["ram", "register", "stack"], + ); + } + if (first.architecture.native_id === "AARCH64:LE:64:v8A:default") { + const named = await read("registers", { + names: ["x0", "w0"], + fields: ["name"], + }); + assert.deepEqual( + named.items.map(({ space, offset, size_bytes, name }) => ({ + space, + offset, + size_bytes, + name, + })), + [ + { space: "register", offset: "0x4000", size_bytes: 8, name: "x0" }, + { space: "register", offset: "0x4000", size_bytes: 4, name: "w0" }, + ], + ); + assert.equal(named.source.evidence_id, first.source.evidence_id); + } + for (const name of ["spaces", "registers"]) { + const empty = await read(name, { names: [] }); + assert.equal(empty.total, 0); + assert.deepEqual(empty.items, []); + } + let text = "", + offset = 0; + do { + const page = await read("evidence", { + evidence_id: first.source.evidence_id, + offset, + limit: 16384, + }); + text += page.text; + offset = page.next_offset; + } while (offset !== null); + assert.equal( + createHash("sha256").update(text).digest("hex"), + first.source.sha256, + ); + const raw = JSON.parse(text); + assert.equal(raw.register_count, first.totals.registers); + assert.equal(raw.space_index_capacity, first.totals.space_index_capacity); + assert.equal(raw.coverage.functions_decompiled, 0); + assert.equal(raw.coverage.listing_discovery, false); + for (const name of ["spaces", "registers"]) { + const rows = []; + offset = 0; + do { + const page = await read(name, { offset, limit: 128 }); + assert.equal(page.source.evidence_id, first.source.evidence_id); + rows.push(...page.items); + offset = page.next_offset; + } while (offset !== null); + assert.deepEqual(rows, raw[name]); + } + report = { + context: opened.context, + source: first.source, + architecture: first.architecture, + totals: first.totals, + phases, + selected, + all_rows_match_retained_source: true, + source_digest_verified: true, + scope: + "Native canonical exact-name map only; no model, runtime or alias-completeness claim.", + }; + await call("close_binary", {}); +} catch (error) { + failures.push(error.stack ?? String(error)); +} finally { + await client.close(); + await transport.close(); +} +const lifecycle = await completeVerifierRun(run); +assertVerifierCleanupComplete(lifecycle.process_lineage); +await writeFile( + output, + JSON.stringify({ ...report, calls, failures, lifecycle, stderr }), + { flag: "wx" }, +); +if (failures.length) process.exitCode = 1; +console.log(JSON.stringify({ output, ...report }));