Skip to content

impl(027): increment 6, the native package's JavaScript layer - #135

Merged
bartekus merged 1 commit into
mainfrom
impl/027-node-js
Oct 21, 2026
Merged

bartekus merged 1 commit into
mainfrom
impl/027-node-js

Conversation

@bartekus

@bartekus bartekus commented Oct 21, 2026 •

Copy link
Copy Markdown
Contributor

Spec 027, increment 6 (second change): the native package's JavaScript layer. Stacked on #131, split from it because its AI review was cancelled at the 15-minute limit twice. About 10,000 of its lines are the generated document declarations, byte-identical to the WebAssembly package's.

  • integrations/rustev-node/index.js and index.d.ts: the API of 3.3 over the native crate (impl(027): increment 6, the native crate #131): Engine.create, compile/compileSync (exactly one of a definition and a plan), the pure commands, PlanHandle.decide with AbortSignal (already aborted is CancelledBeforeAdmission), the typed RustevError subclasses and codes of 3.4, onGauges through a bounded drop-oldest subscription, shutdown (drain, then cancel, bounded), and a loader that names a missing platform package, types an unloadable one, and downloads nothing.
  • types/rustev-documents.d.ts: the generated document declarations; gen-types.mjs now writes both packages' copies, keeps a field's own description where it references a type, and states in its header that the types describe what each parser accepts.
  • package.json (private until spec 031 publishes it; optional platform packages; Node 20 or later).
  • test/negative.test.mjs: each section 5 row of the native package, deterministic on a manual clock (23 tests).
  • tools/rustev-conformance/js/copy-addon.mjs and make bindings steps: copy the local build beside the package, type-check the declarations, run the tests.

The review rounds of the unsplit #131 that concerned these files are recorded in #131's body.

Review round 1 (3 findings, fixed): (1) the unused readFileSync import is gone from index.js. (2) the unloadable-build test first asserts that a local build sits beside the package, so it fails saying so rather than writing a file named undefined. (3) an engine's in-flight cancellation handles live in a module-private WeakMap, out of reach of code using the engine, so nothing can drop one before shutdown raises it.

Review round 2 (1 finding, fixed): the copy script checks that the diagnostic report exists before reading it, as index.js does, and refuses with a message naming the missing capability.

Review round 3 (1 finding): the native layer reads cancel by its string value (an absent or undefined one is not_requested), so nothing was misread; still, a successful answer never carries a cancellation, so the success path no longer passes the field at all.

Restacked on #131's last round, with a test that advancing an engine on the system clock is refused with not_a_manual_clock (24 tests).

Review round 4 (4 findings): (1) fixed: SeamFailure's declaration carries its failureClass, charge, remote and cancel. (2) Not so: the native layer returns delivery as a JSON string (DecideResult.delivery: String in #131), so JSON.parse reads it directly; the code says so. (3) fixed: compile refuses anything but exactly one of a definition and a plan before any native call, as compileSync does. (4) fixed: an engine without a runtime configuration is refused (ConfigRefused, missing_runtime) instead of passing undefined bounds on; tested (25 tests).

Review round 5 (2 findings, fixed): (1) an engine's native binding lives in a module-private WeakMap, like its in-flight handles, so code using the engine cannot replace what its plans decide through. (2) the tests find the host backend's gauges by seam name (backend:...), never by position.

Review round 6 (3 findings, fixed): (1) an engine without a sink is refused (ConfigRefused, missing_sink), as one without a runtime configuration is; tested. (2) creating a decision's cancellation handle runs under the error wrapper, so a native failure there (an engine shut down) arrives typed. (3) the declarations state the thread defaults: 2 workers and 4 blocking threads when omitted (26 tests).

Review round 7 (3 findings): (1) fixed: an abort and its attempt's call reach JavaScript through separate queues, so an abort that arrives first is remembered and the attempt starts with its signal already aborted. (2) fixed: the C-library probe restores process.report.excludeNetwork after reading the report, here and in the copy script, so other code's reports are unaffected. (3) By design: every test in the file loads the local build, so without one the suite cannot run at all and its absence fails rather than skips; the code says so.

Review round 8 (3 findings, fixed): (1) compile and compileSync treat null as absent, so { definition: null } meets the exactly-one guard; tested. (2) shutdown's lateDiscarded counts the late settlements discarded during that shutdown, not the engine's lifetime total. (3) a context source that resolves with nothing fails as ContextUnavailable with a message saying so, instead of a TypeError from encoding undefined; tested (27 tests).

Review round 9 (3 findings, fixed): (1) an early abort is kept with its time and pruned after a minute, so one that crossed with an already finished attempt never accumulates. (2) a missing platform package is decided by require.resolve alone, not by Node's message text; a package that resolves but does not load is platform_package_unloadable. (3) the test decodes the record bytes explicitly as UTF-8. (27 tests)

Review round 10 (2 findings): (1) fixed: early aborts are pruned whenever an attempt starts as well as when an abort arrives, so a stale entry never outlives a minute of activity. (2) excludeNetwork is an own accessor of process.report (checked: own, with a setter), so writing it back calls the setter and shadows nothing; the check now reads Object.hasOwn, which says so.

Review round 11 (3 findings, fixed): (1) every abort prunes the early-abort list first. (2) ContextSource.queueCapacity states its bound (1 to 65,536, no default), as the other seams' do. (3) the spec record counts the tests as they are (27). Rebased on main after #131 merged.

@github-actions

Copy link
Copy Markdown

AI review (findings)

Review

1. Unused import — integrations/rustev-node/index.js

Line 3 imports readFileSync from node:fs, but that symbol is never referenced anywhere in index.js. Only existsSync is used (inside load()).

const { readFileSync, existsSync } = require('node:fs');
//      ^^^^^^^^^^^^ imported but never used

Minor, but a dead import in a handwritten file is worth fixing before the package ships.


2. built can be undefined, silently breaking a test — integrations/rustev-node/test/negative.test.mjs line ~356

const built = readdirSync(pkg).find((f) => /^rustev\..+\.node$/.test(f));
// …
writeFileSync(join(dir, built), 'not a shared library');

If no .node file has been copied yet (i.e., the test is run outside the full make bindings flow), built is undefined. join(dir, undefined) resolves to <dir>/undefined, so a file literally named undefined is created. The index.js under test then looks for rustev.<platform>.node, finds nothing locally, and tries the platform package instead, throwing PlatformPackageMissing — not InternalError / local_build_unloadable. The test assertion silently fails with a confusing error rather than the expected one. A simple guard (if (!built) throw new Error(...)) would make the precondition explicit.


3. Engine.running is public and mutable — integrations/rustev-node/index.js line ~267

class Engine {
  /** The cancellation handles of decisions in flight (3.9.2). */
  running = new Set();

running is a publicly writable instance property. The TypeScript declaration (correctly) omits it, so the type surface is clean. But any code that holds an Engine reference can clear or mutate the set, causing shutdown() to miss cancel handles:

engine.running.clear(); // cancel loop in shutdown() now raises nothing

Using #running (private class field) would close this gap without breaking the public API.


{
  "head": "0c60c12edb39b2c271c41d8b29db0a933b9bf076",
  "verdict": "findings",
  "findings": [
    {
      "path": "integrations/rustev-node/index.js",
      "line": 3,
      "summary": "`readFileSync` is destructured from `node:fs` but never used anywhere in the file."
    },
    {
      "path": "integrations/rustev-node/test/negative.test.mjs",
      "line": 356,
      "summary": "`built` is `undefined` when no `.node` file exists in the package directory, causing `writeFileSync` to create a file literally named `undefined` and the test to throw `PlatformPackageMissing` instead of the expected `InternalError / local_build_unloadable`."
    },
    {
      "path": "integrations/rustev-node/index.js",
      "line": 267,
      "summary": "`Engine.running` is a public, mutable `Set`; external code can clear it before `shutdown()` iterates it to raise cancellation handles, silently skipping cancellation of in-flight decisions."
    }
  ]
}

Subject: e28fb80...0c60c12, diff digest dfc581d413a5ef5d25d7fb2d136649bf6700fb3562d8685430cb0685e53ef704, 1 call(s). An AI comment is not an approval.

@github-actions

Copy link
Copy Markdown

AI review (findings)

Review

The PR introduces the JavaScript layer for the Node-API native addon (index.js, type declarations, tests, and a helper script). Overall the code is well-structured. One real finding:

tools/rustev-conformance/js/copy-addon.mjs:29 — On Linux, process.report.getReport() is called without the null-safe optional chaining that index.js uses for the same detection:

// index.js (safe)
const glibc = process.report?.getReport?.().header?.glibcVersionRuntime;

// copy-addon.mjs (unsafe path)
if (platform === 'linux' && 'excludeNetwork' in process.report) process.report.excludeNetwork = true;
const libc = platform === 'linux'
  ? process.report.getReport().header.glibcVersionRuntime   // ← no optional chaining
  ...

The excludeNetwork guard only protects the assignment above it; process.report.getReport() is called unconditionally on Linux regardless of whether that guard fired. In any Node.js 20+ build process.report.getReport is always present, so this is safe in practice, but it is inconsistent with the defensive style used in index.js and would throw an unhelpful TypeError on an atypical runtime.

Everything else looks correct:

  • The typed() error bridge, class registry, and SinkFailure.record extraction are implemented consistently with the documented JSON wire format.
  • begin()/end() keepalive, the shutdown drain/cancellation loop, and the running WeakMap teardown are race-free under Node.js single-threaded event loop semantics.
  • The backendSeam controllers map cleanup in finally is correct; SeamFailure is intercepted and converted to a return value before it reaches the native boundary.
  • The compileSync mutual-exclusion check (definition === undefined) === (plan === undefined) correctly enforces "exactly one of".
  • The gen-types.mjs change (removing the early-continue for rustev-node) is correct now that the files exist.
{"head": "21bb55ff6c07fb4608c6ae1b707ddcfed15ece6e", "verdict": "findings", "findings": [{"path": "tools/rustev-conformance/js/copy-addon.mjs", "line": 29, "summary": "On Linux, process.report.getReport() is called without optional chaining, unlike the identical detection in index.js; if process.report.getReport is absent (atypical builds) this throws an unhandled TypeError rather than a clean error."}]}

Subject: 69ec266...21bb55f, diff digest 15a70d4b2a1efb813ef7b24bfe1fb9c3fbbfdff738fcb76d7713b3679d0af35b, 1 call(s). An AI comment is not an approval.

@bartekus
bartekus had a problem deploying to statecraft-review-exception October 21, 2026 01:06 — with GitHub Actions Error
@github-actions

Copy link
Copy Markdown

AI review (findings)

Reviewing the new JavaScript layer, I focused on the seam adapters in index.js, the error classification logic, the shutdown/lifecycle management, and the test coverage.

Finding: spurious cancel field in backendSeam success return

In integrations/rustev-node/index.js, the backendSeam adapter's infer function returns, on the success path:

return {
  output: answer.output,
  charge: answer.charge,
  remote: answer.remote ?? 'finished',
  cancel: answer.cancel,          // ← InferAnswer has no cancel field
};

InferAnswer (declared in index.d.ts) has no cancel member, so answer.cancel is always undefined. The NAPI layer therefore always sees { cancel: undefined } in the success object. If the Rust side discriminates by key presence (e.g. obj.has_own_property("cancel")) rather than by value, it would see an affirmative cancel signal on every successful infer call. The cancel field belongs exclusively to the SeamFailure cancellation path (where it is handled correctly in the catch branch). The stray field in the success branch should be removed.

No other issues found. The loading heuristic (__dirname-local .node → npm package), the typed() error mapping, the shutdown drain-then-cancel flow, the onGauges drop-oldest subscription, and the decide AbortSignal wiring all look correct.

{"head": "295f466abfac0b38eb14959f69d3f652a6705b5e", "verdict": "findings", "findings": [{"path": "integrations/rustev-node/index.js", "line": 213, "summary": "backendSeam.infer success-path includes `cancel: answer.cancel`, but InferAnswer has no cancel field so this always passes undefined; if the native layer checks key presence rather than value, it would misinterpret every successful infer as a cancelled attempt."}]}

Subject: 69ec266...295f466, diff digest 6262fc9680b1d1b5c31a0f04101e074c1631de05243140b60d3c376836b607df, 1 call(s). An AI comment is not an approval.

@github-actions

Copy link
Copy Markdown

AI review (findings)

{"head": "2fdea99c6f05bcd99cc1ee813b60607c8f9b8252", "verdict": "findings", "findings": [{"path": "integrations/rustev-node/index.js", "line": 333, "summary": "setInterval callback calls this.gauges() without a try/catch; an unexpected throw produces an uncaught exception that terminates the process in modern Node.js."}, {"path": "integrations/rustev-node/index.js", "line": 337, "summary": "drain() is an async function called without await (floating promise); currently safe because all errors are caught internally, but any future addition of a top-level await before the inner try/catch would silently swallow rejections."}, {"path": "integrations/rustev-node/test/negative.test.mjs", "line": 263, "summary": "JSON.parse(Buffer.from(err.record)) relies on implicit Buffer-to-string coercion; should be JSON.parse(Buffer.from(err.record).toString('utf8')) for clarity and correctness guarantees."}]}

Subject: 915b13b...2fdea99, diff digest 3d818f36d5dab221895d9df85f9a9dc38befcb4107167a017afff21273a3912d, 1 call(s). An AI comment is not an approval.

@github-actions

Copy link
Copy Markdown

AI review (findings)

Reviewing the PR, which introduces the JavaScript layer (index.js, index.d.ts, tests, and tooling) for the Node-API binding.

integrations/rustev-node/index.d.ts — SeamFailure missing instance properties

The SeamFailure class declaration omits the instance properties (failureClass, charge, remote, cancel) that the implementation sets (this.failureClass = failureClass, etc.) and that backendSeam reads back via e.failureClass, e.charge, e.remote, e.cancel. TypeScript users who construct a SeamFailure in their infer callback and then inspect it elsewhere (e.g., in a test helper) will get type errors even though the properties are present at runtime.

integrations/rustev-node/index.js — compile() vs compileSync() mutual-exclusivity validation

compileSync() (line ~372) validates (definition === undefined) === (plan === undefined) in JS and throws InvalidDocument immediately. The async compile() (line ~358) passes both to native.prepareAsync() and relies on Rust to reject. The test confirms Rust does produce InvalidDocument with "exactly one", but the validation site differs: one is a JS error, one is a Rust error propagated via typed(). The inconsistency means the async path silently sends both to Rust even when the caller clearly misused the API, which is a minor behavioral asymmetry but not a correctness bug.

integrations/rustev-node/index.js line ~243 — delivery decoded differently from evidence/judgment

evidence and judgment are decoded with Buffer.from(r.x).toString('utf8') before JSON.parse. delivery is passed to JSON.parse(r.delivery) directly. If the native layer returns delivery as a Uint8Array (rather than a Buffer subclass or a plain string), String(Uint8Array) yields comma-separated decimal byte values — not UTF-8 — which would silently misparse. Since the existing tests pass this path, the native layer presumably returns delivery as a string or Buffer, but the inconsistent treatment is latent risk if the return type ever changes.

integrations/rustev-node/index.js — Engine.create passes undefined required runtime fields when options.runtime is absent

const rt = options.runtime ?? {} means an absent runtime sends undefined for maxInFlight, maxQueued, maxParallelRequests, and sinkTimeoutMs to native. The TypeScript declaration marks runtime as required, so legitimate TypeScript callers are protected, but JavaScript callers get a potentially opaque native-layer error instead of a typed ConfigRefused. Minor, but the compileSync validation pattern shows the codebase does prefer early JS-layer checks.

{"head": "c995e24fba034256aa1b87b729ba00cb7839c73c", "verdict": "findings", "findings": [{"path": "integrations/rustev-node/index.d.ts", "line": 182, "summary": "SeamFailure class declaration omits the instance properties (failureClass, charge, remote, cancel) that the implementation sets and that backendSeam reads back; TypeScript callers cannot access them in a type-safe way."}, {"path": "integrations/rustev-node/index.js", "line": 243, "summary": "delivery is passed directly to JSON.parse while evidence and judgment are first decoded via Buffer.from().toString('utf8'); a Uint8Array return from native would silently yield comma-separated bytes, not the JSON object."}, {"path": "integrations/rustev-node/index.js", "line": 358, "summary": "async compile() defers mutual-exclusivity validation of definition/plan to Rust, while compileSync() validates in JS; the asymmetry means callers passing both receive a Rust-originated error rather than an immediate typed JS refusal."}, {"path": "integrations/rustev-node/index.js", "line": 306, "summary": "options.runtime ?? {} silently defaults to an empty object, passing undefined for all required runtime fields (maxInFlight, maxQueued, etc.) to native when the caller omits runtime, producing an opaque native error instead of a typed ConfigRefused."}]}

Subject: 9a44413...c995e24, diff digest b51a370c6404090c4d134cf3003b57199ea97415eb2c003b0ce41eb703563a41, 1 call(s). An AI comment is not an approval.

@bartekus
bartekus had a problem deploying to statecraft-review-exception October 21, 2026 01:46 — with GitHub Actions Error
@github-actions

Copy link
Copy Markdown

AI review (findings)

Reviewing the new Node-API binding layer in this PR.

integrations/rustev-node/index.js

Public native field on Engine (line ~291):

class Engine {
  constructor(nativeEngine) {
    this.native = nativeEngine;   // public, writable

PlanHandle.decide reaches into this via this.#engine.native.cancelHandle(). Because native is a plain public property, any caller with an Engine reference can replace it (engine.native = null), silently breaking all subsequent decide calls with opaque errors. The TypeScript declarations correctly omit it, but that only protects TypeScript callers. A private field #native paired with a module-internal accessor (WeakMap or getter) would close this.

typed() fallback detail leakage (line ~87):

return new classes.InternalError('internal', e.message);

When the native side produces a non-JSON error message, the raw message string lands in detail. This is probably intentional for debugging, but it means arbitrary native-side strings reach application error handlers. Low severity, but worth acknowledging.

integrations/rustev-node/test/negative.test.mjs

Hardcoded seam index (lines ~123, ~132, and implicitly later):

await until(() => held.length === 1 && e.gauges().seams[1].refusedFull >= 2);
const depth = e.gauges().seams[1].queueDepth;

Index 1 implicitly assumes the sink is at seams[0] and the host backend is at seams[1]. If native seam ordering ever changes, these assertions silently evaluate metrics on the wrong seam without failing. The later test at line ~358 uses the more robust Object.values(e.gauges().backendInFlight) form; the same pattern should be applied here, or the test should assert the seam's identity before indexing.

Minor / no-issue items

  • load() MODULE_NOT_FOUND detection via startsWith is the standard Node.js ecosystem pattern and handles the dependency-missing vs. package-missing distinction correctly.
  • backendSeam abort/controller lifecycle is correct in single-threaded JS.
  • begin()/end() balance in decide is maintained through finally.
  • copy-addon.mjs platform extension mapping and index.js platformName() are consistent with each other.
  • gen-types.mjs removal of the rustev-node skip guard is correct now that the file is added.
{"head": "99aececf006d5dc3cc35507b0de4506ecf493b75", "verdict": "findings", "findings": [{"path": "integrations/rustev-node/index.js", "line": 291, "summary": "Engine stores the native binding as a public writable property `this.native`; any caller can overwrite it, silently breaking PlanHandle.decide which reads `this.#engine.native` — should be a private field with a module-internal accessor."},{"path": "integrations/rustev-node/test/negative.test.mjs", "line": 123, "summary": "Test accesses `e.gauges().seams[1]` by hardcoded positional index, silently checking the wrong seam if native seam ordering changes; later tests use the more robust named-field form."}]}

Subject: 9a44413...99aecec, diff digest da13287a302d0e842ed636bbec62c41eec2fd976441be34d80bcd045d2154392, 1 call(s). An AI comment is not an approval.

@bartekus
bartekus had a problem deploying to statecraft-review-exception October 21, 2026 01:54 — with GitHub Actions Error
@github-actions

Copy link
Copy Markdown

AI review (findings)

Review findings:

1. Missing sink null/undefined guard in Engine.create

index.js line ~330:

sinkSeam(options.sink),

options.runtime has an explicit null check and throws ConfigRefused, but options.sink (also required — "there is no default sink") does not. A missing sink causes sinkSeam(undefined) to throw a TypeError at .queueCapacity, which wrap() catches and re-emits as InternalError('internal', ...) rather than ConfigRefused. Inconsistent with the documented behavior and the runtime precedent.

2. cancelHandle() called outside the try/catch in PlanHandle.decide

index.js line ~284:

const cancel = natives.get(this.#engine).cancelHandle();
running.get(this.#engine).add(cancel);
// ...
begin();
try {
  const r = await this.#native.decide(...);
  ...
} catch (e) {
  throw typed(e);    // ← cancelHandle() errors never reach here
}

If the native layer raises an error from cancelHandle() (e.g., the engine is shut down), it escapes typed() entirely and reaches the caller as an untyped raw Error. For the test 'a call after shutdown is EngineShutDown' to pass, the native design must ensure cancelHandle() never throws — but the JS layer provides no defensive guarantee. If a native refactoring moves the shutdown check into cancelHandle(), the typed-error contract silently breaks.

3. Engine.create applies undocumented defaults for workerThreads / blockingThreads

index.js line ~321:

workerThreads: rt.workerThreads ?? 2,
blockingThreads: rt.blockingThreads ?? 4,

index.d.ts declares both fields as optional (workerThreads?: number; blockingThreads?: number;) with no mention of a default. The behavior when the fields are omitted (2 workers, 4 blocking threads) is undocumented in both the TypeScript declaration and the spec excerpt for this increment.

{
  "head": "cf50b2040caec24c74af9b52ed2926bd88df477a",
  "verdict": "findings",
  "findings": [
    {
      "path": "integrations/rustev-node/index.js",
      "line": 330,
      "summary": "options.sink has no null/undefined guard before sinkSeam() is called, so a missing sink produces InternalError instead of ConfigRefused, inconsistent with the options.runtime check."
    },
    {
      "path": "integrations/rustev-node/index.js",
      "line": 284,
      "summary": "cancelHandle() is called outside the try/catch that wraps this.#native.decide(), so a native error thrown there (e.g. EngineShutDown) bypasses typed() and reaches the caller as a raw untyped Error."
    },
    {
      "path": "integrations/rustev-node/index.js",
      "line": 321,
      "summary": "workerThreads and blockingThreads receive hardcoded defaults (?? 2, ?? 4) that are not documented in index.d.ts or the spec, making the behaviour when those fields are omitted invisible to callers."
    }
  ]
}

Subject: 9a44413...cf50b20, diff digest 209f46c9e3475a1213ccb25045e2ba66211ce43b9913df032b391254e18f52a9, 1 call(s). An AI comment is not an approval.

@bartekus
bartekus had a problem deploying to statecraft-review-exception October 21, 2026 01:59 — with GitHub Actions Error
@bartekus
bartekus had a problem deploying to statecraft-review-exception October 21, 2026 02:16 — with GitHub Actions Error
@github-actions

Copy link
Copy Markdown

AI review (no-findings)

Reading through the diff carefully, covering the JavaScript wrapper (index.js), type declarations (index.d.ts), test suite (negative.test.mjs), the copy helper (copy-addon.mjs), and the generator update (gen-types.mjs).

integrations/rustev-node/index.js

  • typed() (line 87): the guard if (!(e instanceof Error) || e instanceof RustevError) return e passes SeamFailure through the JSON-parse branch if one somehow escapes a seam without being caught by the backend wrapper — but every surface where SeamFailure is documented is guarded by the catch(e) in backendSeam, so this is harmless in practice.
  • load() (line 142): the MODULE_NOT_FOUND message-prefix check to distinguish "package absent" from "package unloadable" is a well-known Node.js pattern and correctly implemented. The error restoration of report.excludeNetwork in platformName() (and its mirror in copy-addon.mjs) correctly uses had !== undefined rather than a truthiness check, preserving false and other falsy values.
  • begin()/end() balance in decide() (lines 264–339): begin() is placed immediately before try {; argument construction (including bytes(request.snapshot)) is inside the try block, so any exception there still reaches the finally and end() is called — balance is maintained.
  • abortedEarly in backendSeam() (line 226): entries whose matching infer() never fires would persist, but the protocol guarantees abort() is only called for dispatched attempts, so no practical leak.
  • shutdown() (lines 432–466): active captures the pre-cancellation count for the drained return value; remaining captures the post-settle count for stillRunning. The semantics match the test expectation.
  • onGauges() (lines 413–430): busy = true is set synchronously before the first await cb(g), so the single-threaded event loop guarantees no concurrent drain invocations.

integrations/rustev-node/test/negative.test.mjs — all assertions align with the specified error classes and codes. The module-cache isolation for the "missing platform package" and "local build unloadable" tests (fresh mkdtempSync + separate createRequire) is correct.

tools/rustev-conformance/js/copy-addon.mjs — platform/arch naming convention matches index.js's platformName(). The Windows library name rustev_node (no lib prefix) is correct for Rust cdylib on Windows.

tools/rustev-conformance/js/gen-types.mjs — removal of the early-continue for non-existent rustev-node targets is correct now that the package lands in this increment.

integrations/rustev-node/index.d.ts vs index.js — all sync/async signatures are consistent; check/show declare CommandResult (sync), the rest declare Promise<CommandResult>, matching commandSync and command calls respectively.

No bugs, security issues, or material inconsistencies found.

{"head": "d6d837e85641373d6054c5c350930ab3d271052e", "verdict": "no-findings", "findings": []}

Subject: 9a44413...d6d837e, diff digest 94c43df983dd2fbff3a0cf9f3a240532a9ee695e572e7f95626304bdc2c3f13a, 1 call(s). An AI comment is not an approval.

@github-actions

Copy link
Copy Markdown

AI review (findings)

Review

integrations/rustev-node/index.js

abortedEarly memory leak in backendSeam

The abortedEarly set (line ~225) is cleaned up only when infer runs and finds the ID there. If the native runtime calls abort(attemptId) after infer has already returned (i.e., the controller was already deleted in the finally block at line ~268), the ID is added to abortedEarly but never removed because attempt IDs are unique and infer will never be called again for that ID. Over the lifetime of a busy engine, abortedEarly accumulates stale entries. In normal operation the native layer should only abort in-flight attempts, so this is unlikely to matter in practice, but the invariant is not enforced in JS.

Fragile MODULE_NOT_FOUND heuristic in load()

if (e?.code === 'MODULE_NOT_FOUND' && String(e.message).startsWith(`Cannot find module '${pkg}'`))

The startsWith check on e.message relies on Node.js's undocumented error message format to distinguish "the package itself is absent" from "the package is installed but one of its dependencies is missing." If Node.js ever changes this message (it has in the past — e.g., between v14 and v16 it added a hint suffix), a missing package would be misclassified as InternalError('platform_package_unloadable', ...) instead of PlatformPackageMissing. The test for this case at line ~367 of the test file only checks the happy path that the current Node prints; it doesn't test the boundary.

A more robust check would inspect e.requireStack or check whether require.resolve(pkg) throws before attempting require(pkg).

integrations/rustev-node/test/negative.test.mjs

JSON.parse(Buffer.from(err.record)) at line 272

JSON.parse accepts a string, not a Buffer. This works in Node.js because JSON.parse calls String() on non-string arguments, and Buffer.toString() defaults to UTF-8 — but it's relying on implicit coercion. If the record bytes are ever invalid UTF-8 at this position (unlikely but possible), the coercion silently produces a corrupted string rather than throwing clearly. The correct form is JSON.parse(Buffer.from(err.record).toString('utf8')).

No issues found in

  • .gitignore, Makefile, package.json, copy-addon.mjs, spec changes, or gen-types.mjs — these all look correct and consistent.
  • The index.d.ts declarations are consistent with the implementation.
  • The generated rustev-documents.d.ts (node) is byte-identical to the wasm one as stated.
  • The TRACEPARENT regex, keep-alive logic, onGauges drop-oldest queue, and shutdown drain/settle loops are all correct.
{"head": "c6315bbf5c613f4f093ad1a9474a452e7c4de939", "verdict": "findings", "findings": [{"path": "integrations/rustev-node/index.js", "line": 225, "summary": "abortedEarly Set accumulates stale attempt IDs when abort() is called after infer() has already completed, since those IDs are never removed."},{"path": "integrations/rustev-node/index.js", "line": 154, "summary": "MODULE_NOT_FOUND classification relies on an undocumented Node.js error message prefix that could change across versions, misclassifying a missing package as InternalError."},{"path": "integrations/rustev-node/test/negative.test.mjs", "line": 272, "summary": "JSON.parse(Buffer.from(err.record)) coerces Buffer to string via undocumented implicit coercion rather than explicit .toString('utf8')."}]}

Subject: 36dfdcb...c6315bb, diff digest 3c9a03090b82faa33df89567ff6e0efd3b36b082671ddf85343986be5926187b, 1 call(s). An AI comment is not an approval.

@bartekus
bartekus had a problem deploying to statecraft-review-exception October 21, 2026 03:12 — with GitHub Actions Error
@github-actions

Copy link
Copy Markdown

AI review (findings)

Reviewing the PR which adds the JavaScript layer (index.js, index.d.ts) for the Node.js native addon, along with the copy-addon.mjs build helper, negative.test.mjs tests, and spec/type-generation updates.

integrations/rustev-node/index.js — backendSeam, abortedEarly map pruning

prune() is only called from inside the abort function's else branch, which executes when an abort arrives for an attempt that has no active controller. Entries in abortedEarly that were added because an abort crossed with an already-completed attempt (the "never consumed" case documented in the comment) accumulate without bound until the next abort call for an unknown attempt ID triggers a prune. In a workload with frequent late-abort events but infrequent subsequent aborts for unknown IDs, the map grows indefinitely. The comment says "pruned after a minute" but that describes the staleness threshold, not a guaranteed prune schedule.

integrations/rustev-node/index.js — platformName, process.report access on Linux (minor)

const had = report && 'excludeNetwork' in report ? report.excludeNetwork : undefined;

in checks the prototype chain. If excludeNetwork lives only on the prototype of process.report (not an own property), had would be set to a prototype value and subsequently restored with report.excludeNetwork = had as an own property, silently shadowing the prototype. Extremely unlikely with Node.js internals but technically unsafe; Object.prototype.hasOwnProperty.call(report, 'excludeNetwork') would be the safe form.

tools/rustev-conformance/js/copy-addon.mjs — macOS extension

The mapping darwin → 'dylib' is correct for Rust cdylib on macOS. The .dylib → .node rename works because Node.js loads .node files as native modules regardless of the on-disk format. No issue.

integrations/rustev-node/index.js — Engine.create using synchronous wrap

native.Engine.create is called synchronously inside wrap, which is safe because NAPI-based engine construction is synchronous; the outer async just wraps the result in a resolved Promise. Consistent with the tests succeeding.

gen-types.mjs — removal of rustev-node skip

The removal of the continue guard for the node package is correct now that integrations/rustev-node/types/rustev-documents.d.ts exists. The regeneration check will now enforce the file stays in sync. ✓

index.d.ts vs index.js consistency

check and show are synchronous in both declaration and implementation. replay, evaluate, gate, calibrateFit, calibrateQualify are async in both. shutdown, compile, command align. No mismatches found.

{"head": "237ac54489c46f04359c742aec31cf4cd531eca6", "verdict": "findings", "findings": [{"path": "integrations/rustev-node/index.js", "line": 247, "summary": "abortedEarly map is only pruned when abort() is called for an attempt with no active controller; in workloads with frequent late-abort events followed by few unknown-ID aborts, stale entries accumulate indefinitely rather than being cleared on a fixed schedule as the comment implies."}, {"path": "integrations/rustev-node/index.js", "line": 124, "summary": "platformName() uses 'excludeNetwork' in report (prototype-chain search) to decide whether to save/restore the property; if the property exists only on the prototype, the restore writes an own property that shadows it rather than leaving no trace."}]}

Subject: 36dfdcb...237ac54, diff digest 5a388d7d63635a46c3289d52c0055378522974b8902b9a77b9c8465efa011a0a, 1 call(s). An AI comment is not an approval.

@bartekus
bartekus had a problem deploying to statecraft-review-exception October 21, 2026 03:24 — with GitHub Actions Error
@bartekus
bartekus force-pushed the impl/027-node branch 4 times, most recently from 0140a6c to 49c1e26 Compare October 21, 2026 04:09
Base automatically changed from impl/027-node to main October 21, 2026 04:24
bartekus added a commit that referenced this pull request Oct 21, 2026
Spec 027, increment 6 (first change): the native Node-API package.
Stacked on #130.

- `integrations/rustev-node` (napi 3.14.2, Node-API 8; `publish =
false`, excluded from the crates.io release set): an `Engine` owning one
sized Tokio runtime, rules-program and host backends, a host sink and
optional context source; `compile` (or load a compiled plan) and the
pure commands on the blocking pool, with sync variants; `decide` on the
engine's runtime with `AbortSignal`, deadline, principal handle and
`traceparent`; manual clock; gauges; shutdown.
- Host seams (3.6) via weak threadsafe functions: bounded per-seam
queues refused at once, remaining time, attempt identity, abort,
reserved bound and trace context on every call, late settlements
discarded and counted, non-`SeamFailure` rejections mapped to permanent
/ unknown charge / possibly continuing. Context source once before
admission; `ContextUnavailable` on failure, nothing defaulted.
- JavaScript layer (`index.js`, `index.d.ts`, generated document
declarations byte-identical to the wasm package's): the 3.3 API, typed
`RustevError` subclasses and codes (3.4), `onGauges` drop-oldest
subscription, drain-then-cancel `shutdown`, platform-package loader
naming a missing package.
- `unsafe`: napi-rs's generated glue needs it, so this crate sets
`unsafe_code = "deny"` (reason in the manifest); `tests/no_unsafe.rs`
fails on hand-written `unsafe`.
- `test/negative.test.mjs`: each section 5 row of the native package (20
tests, deterministic on a manual clock). A decision through the binding
produces the CLI's golden run-record bytes.
- `ManualClock::pending_delays` (additive, spec 003's crate) for
deterministic clock driving; the conformance adapter that uses it
follows in the second change.
- Two owner findings, recorded in the spec: a host backend's
cancellation answer is always `not_observed` (the runtime polls a
cancelled attempt once; a host seam answers across threads), and section
5's "output failing the bounded parse" row disagrees with 3.6.5; the
binding follows 3.6.5.

Review round 1 (5 findings): (1) Under `node -e`, `process.argv[1]` is
the first argument after the code (there is no script path), so the copy
reads the target directory; it ran that way in local verification, and
the Makefile now says so. (2) fixed: a decision is counted in flight by
a guard dropped when its task ends, panic included, so shutdown never
waits on a panicked task. (3) fixed: `compile` takes exactly one of a
definition and a plan, otherwise `InvalidDocument`; declared and tested.
(4, 5) The generated types state what each bounded parser accepts
(3.2.2: the schema describes the parser), while a field's description
can state a compiler rule beyond it (`AddressOverride.to` is never
`caller`, `RemediationDecl.for` never `none`: the compiler refuses
both). The generated header now says so; both packages' copies
regenerated and identical. Restacked on #130.

Review round 2 (5 findings): (1) fixed: the no-unsafe check reads source
files only and fails on anything else in `src/` rather than panicking.
(2) fixed: compiles and commands on the blocking pool are counted, and
shutdown waits for them as for decisions. (3) fixed: after raising
cancellation, shutdown waits at most 30 seconds and reports what still
runs (`stillRunning`). (4) fixed: a local build that does not load is a
typed `InternalError` (`local_build_unloadable`) naming it; tested. (5)
Repeated: the generated types state what each bounded parser accepts and
the generated header says a field's description can state a compile rule
beyond that; `compile` refuses `caller` for `AddressOverride.to` in
every plan.

Review round 3 (6 findings): (1) Repeated, and wrong: under `node -e`
the first argument after the code is `process.argv[1]` (`node -e
'console.log(process.argv.slice(1))' x` prints `["x"]`). To leave no
doubt, the copy is now a script,
`tools/rustev-conformance/js/copy-addon.mjs <target> <package>`, run by
`make bindings` and locally. (2) fixed: shutdown's local count is
`active`, no longer shadowing the module's `inFlight`. (3) fixed: a seam
failure with an empty reason records the status instead (`the host seam
failed without a reason (...)`). (4) Repeated: the generated
declarations' header states that the types describe what each parser
accepts and that a description can state a compile rule beyond it (the
compiler refuses `caller` for `AddressOverride.to`); each emitted schema
now says the same in a root `$comment` (#126), which the type generator
does not copy. (5, 6) These are the two owner findings already recorded
in this spec's implementation record (the host backend's cancellation
recorded `not_observed`, and section 5 against 3.6.5 for an unparseable
answer); they need the owner's reading or an amendment, not a code
change here. Restacked on #130.

Review round 4 (5 findings): (1) fixed, and it exposed a real defect:
`compileSync` takes exactly one of a definition and a plan, refusing
otherwise with `InvalidDocument`; the layer's error wrapper also
re-typed errors it had thrown itself as `InternalError`, and now passes
a `RustevError` through unchanged. Tested. (2) fixed: the no-unsafe
check strips a `//` comment only outside string literals; tested. (3)
The diagnostic report is the C-library test napi-rs uses; it runs once,
on Linux only, and now without the network section where Node allows
leaving it out. (4) fixed: `copy-addon.mjs` refuses a platform it has no
package for. (5) fixed at the source (#130): the generator gave plan
fields the referenced type's description; now every field keeps its own
(`AddressOverride.to`: never `caller`), and this package's declarations
are regenerated, byte-identical to the WebAssembly package's.

Review round 5 (2 findings, fixed): (1) an installed platform package
that does not load is `InternalError` (`platform_package_unloadable`,
naming it), and only an absent one is `PlatformPackageMissing`. (2) the
no-unsafe check blanks `/* */` block comments across lines as well as
`//` comments, string literals staying code; tested.

Review round 6 (3 findings, fixed): (1) a command is counted before the
shutdown check (both sequentially consistent), so either shutdown waits
for it or it refuses; it never runs unseen. (2) the no-unsafe check
reads raw strings (`r#"…"#`, `br"…"`), escaped strings and char literals
(`'"'`) as code, with lifetimes left alone; tested. (3) a package is
missing only when Node cannot find the package itself (`Cannot find
module '<package>'`); a missing dependency of an installed package makes
it unloadable.

Review round 7 (3 findings, fixed): (1) a decision is counted in flight
before the shutdown check, as a command is, so shutdown either waits for
it or it refuses. (2) shutdown's count saturates at `u32::MAX` instead
of truncating. (3) the no-unsafe check reads an escaped char literal
(`'\''`) whole; tested.

Review round 8 (4 findings, fixed): (1) the no-unsafe check blanks
string contents (plain, byte and raw) as it blanks comments, so text
inside a string is not code; a real `unsafe` block is still found;
tested. (2) the missing-package test first asserts that no platform
package resolves from its directory (Node also searches ancestors), so
it fails rather than passes if one does. (3) `advanceClock` takes any
integral, non-negative number up to 2^53 - 1 and refuses the rest
instead of truncating to 32 bits; tested. (4) the build-time copy script
leaves out the report's network section too.

Review round 9 (2 findings, fixed): (1) `clockDelays` reports each
pending delay as a JavaScript number, exact to 2^53 - 1 ms, the range
`advanceClock` accepts, instead of capping at 32 bits. (2) the no-unsafe
check matches the keyword `unsafe`, not a longer identifier such as
`unsafe_code`; tested.

Split (the AI review was cancelled at its 15-minute limit twice): this
PR is now increment 6's first change, the native crate (Rust: engine,
seams, commands, errors, the no-unsafe check, the manual clock's pending
delays); the JavaScript layer (`index.js`, declarations, generated
types, package, tests, copy script) moves to a PR stacked on this one,
and #132 is restacked on that.

Review round 10 (2 findings, fixed): (1) every usage refusal states the
requirement (`must be a string`, `must be a list`, `must list strings`).
(2) a compile on the blocking pool is counted and then checked against
shutdown before it reaches the pool, as a command is, so both paths
behave alike: shutdown waits for it, or it refuses.

Review round 11 (2 findings, fixed): (1) `"failure": null` in a host's
answer is no failure; only an object is one. (2) the context source's
fetch runs on its own task, as a backend's attempt does, so a settlement
that arrives after its decision was dropped is discarded and counted
(3.6.4). The 23 native tests (#135) and the 34 native conformance cases
(#132) pass against this build.

Review round 12 (2 findings, fixed): (1) a host answer's `cancel`, when
present, must be `stopped` or `unconfirmed`; any other value is refused
like an unknown charge or remote end, and only an absent one means not
requested. (2) `compile` and `load` on the blocking pool run under
`guard`, so a panic crosses as `InternalError` with its message, as a
command's does. Rebased on main after #134 merged.

Review round 13 (1 finding, fixed): advancing an engine on the system
clock is refused with its own code, `not_a_manual_clock`, instead of
`out_of_range`, which stays for numbers outside the accepted range; #135
tests both.

Review round 14 (1 finding, fixed): the synchronous `command`, `compile`
and `load` are counted and then checked against shutdown, as their
blocking-pool forms are, so a synchronous call (from a worker thread
too) is one shutdown waits for. The native tests (#135, 27) and native
conformance (#132, 34) pass against this build.

Review round 15 (1 finding, fixed): a compile given neither a definition
nor a plan says so (`neither was given`), and one given both says `not
both`.

Review round 16 (2 findings, fixed): (1) `compile` and `load` count
themselves and then call uncounted forms (`compile_uncounted`,
`load_uncounted`), which `prepare_async`, already counted, calls
directly, so nothing is counted twice. (2) `clockSleepers` saturates at
`u32::MAX` instead of truncating. The native tests (#135, 27) and native
conformance (#132, 34) pass against this build.

Review round 17 (2 findings): (1) Nothing is dropped: the workspace's
only lint is `unsafe_code` (`[workspace.lints.rust]`), which this crate
overrides to `deny`; Cargo cannot inherit the workspace table and
override one lint, so the manifest now says the table restates the
workspace's and must mirror any lint it gains. (2) fixed: a host answer
missing its charge or its remote end is refused naming the one that is
missing.
@bartekus
bartekus enabled auto-merge (squash) October 21, 2026 04:25
@github-actions

Copy link
Copy Markdown

AI review (findings)

Review

integrations/rustev-node/index.js

backendSeam abort + prune asymmetry (low severity)

prune() is called in abort() only in the else branch (unknown attempt IDs), and in infer() at attempt start. When abort() fires for a known controller (the common cancellation path), prune() is never called. Stale entries in abortedEarly accumulate until the next infer() or unknown-attempt abort — eventually cleared by the 60-second TTL. The comments acknowledge this, and in practice infer() is called frequently enough. Minor but worth noting: index.js line ~175 in the abort handler.

shutdown() final lateCount() call

return { drained: active === 0, cancelled, lateDiscarded: lateCount() - lateBefore, stillRunning: remaining };

lateCount() invokes this.gauges().seams after the settle loop has completed. The Engine JS object still holds the native engine reference through natives (WeakMap), so the NAPI object is not freed. This works as long as the native gauges() accepts calls after shutdown() has drained all activity — an implicit contract with the Rust layer not made explicit in the JS declarations. Not a bug given how NAPI lifetimes work, but the assumption is invisible from the JS side.

integrations/rustev-node/index.d.ts

Missing bounds comment on ContextSource.queueCapacity (line 77)

EvidenceSink.queueCapacity and DecisionBackend.queueCapacity both carry the doc comment /** 1 to 65,536; there is no default. */, but ContextSource.queueCapacity has no such annotation. The native layer enforces the same range (ConfigRefused/out_of_range) but the type declaration gives no hint of the constraint.

tools/rustev-conformance/js/copy-addon.mjs

Object.hasOwn guard is correct but conservative (line 30)

const had = Object.hasOwn(process.report, 'excludeNetwork') ? process.report.excludeNetwork : undefined;

If excludeNetwork is only an inherited property (older Node), had stays undefined, excludeNetwork is never set to true, and getReport() may include the costly network section. The corresponding check in index.js:load() uses the same pattern. Behaviorally safe — the fallback is just slower — but worth documenting since it's a subtle Node version dependency.

specs/027-node-and-wasm-bindings/spec.md

Test count discrepancy

The newly added paragraph states the test file "tests each section 5 row of the native package (20 tests)", but the test file contains 27 test() calls. If "section 5" of the spec has 20 rows and the remaining 7 cover other sections, the count is still confusing for readers.


Overall the code is well-structured, the typed-error hierarchy is correct, the AbortSignal wiring and the keepalive mechanism are sound, and the platform-detection path is adequately guarded.

{"head": "6a591434431ff4469b949cefa915097fa5d8eee1", "verdict": "findings", "findings": [{"path": "integrations/rustev-node/index.js", "line": null, "summary": "In backendSeam, prune() is not called in the abort() path for known controllers, so stale abortedEarly entries may linger until the next infer() call rather than being cleaned up immediately on each abort invocation."}, {"path": "integrations/rustev-node/index.d.ts", "line": 77, "summary": "ContextSource.queueCapacity is missing the '1 to 65,536; there is no default' bound comment present on EvidenceSink.queueCapacity and DecisionBackend.queueCapacity, leaving callers unaware of the enforced range."}, {"path": "specs/027-node-and-wasm-bindings/spec.md", "line": null, "summary": "The added spec paragraph claims 20 tests, but the test file contains 27 test() calls, creating a misleading mismatch in the documentation."}]}

Subject: 7fb74d3...6a59143, diff digest 9583fbf4e81a163f2a496dfdd7e73d1ce445751dcf7df37fd01a21ac8fde3a25, 1 call(s). An AI comment is not an approval.

@bartekus
bartekus had a problem deploying to statecraft-review-exception October 21, 2026 04:34 — with GitHub Actions Error
@github-actions

Copy link
Copy Markdown

AI review (no-findings)

Reviewing the PR, which adds the JavaScript layer for the Node-API package (index.js, index.d.ts, type declarations, tests, and a build helper script) over the previously-landed native Rust crate.

.gitignore — clean, correctly scoped to *.node artifacts.

Makefile — four lines follow the existing wasm pattern; CARGO_TARGET empty-string expansion is caught by the script's argv check.

tools/rustev-conformance/js/copy-addon.mjs — glibc detection logic (read/restore excludeNetwork) is slightly different from index.js but functionally equivalent for Node 20+. No path-traversal risk: platform and arch come from Node runtime constants.

integrations/rustev-node/index.js — detailed analysis below:

  • platformName() / load(): Object.hasOwn(report, 'excludeNetwork') correctly targets the own accessor on Node 20+; safe fallback to musl. Module-level load() call at require-time is intentional (typed failure on load).
  • bytes(): Buffer.from(JSON.stringify(null)) would produce "null" bytes for a null snapshot (TypeScript types exclude null from DocumentInput, so a user bug, not a library bug).
  • backendSeam: early-abort map (abortedEarly) and pruning are consistent with JavaScript's single-threaded event model—no actual race is possible between controllers.set and abortedEarly.delete.
  • decide(): begin()/end() balance is maintained: if cancelHandle() throws, wrap re-throws before begin() is ever called. { once: true } + removeEventListener in finally is harmless double-cleanup.
  • onGauges(): drop-oldest via busy/pending is correct for the single-threaded JS model; timer.unref() prevents keeping the process alive.
  • shutdown(): 5 ms polling loops and 30-second settle bound look intentional. lateCount() via .reduce could yield NaN if the native side ever omits lateResolutionsDiscarded, but that's a native contract issue.
  • TRACEPARENT regex: lookaheads correctly reject all-zero trace-ID and parent-ID per W3C spec.

integrations/rustev-node/test/negative.test.mjs — 27 tests match section 5 rows; precondition checks (platform package unreachability, local build existence) are correctly guarded. The until polling helper with 100 k setImmediate ticks is appropriate for cross-thread state observation.

integrations/rustev-node/index.d.ts — synchronous methods (check, show, compileSync, commandSync) are typed without Promise<>, matching the implementation. readonly record? on SinkFailure matches runtime assignment in typed().

tools/rustev-conformance/js/gen-types.mjs — removal of the rustev-node skip guard is correct now that the type file is present; the regeneration check will now enforce it stays in sync.

integrations/rustev-wasm/types/rustev-documents.d.ts — comment-only addition, no semantic change.

No bugs, security problems, or inconsistencies found.

{"head": "3864be622911dd3078003ca0af10a490a24a7d72", "verdict": "no-findings", "findings": []}

Subject: 7fb74d3...3864be6, diff digest ff7edde954158d06cdc571e4f0a10e48a66eb2cd698b0535b4bd0094bc371c8b, 1 call(s). An AI comment is not an approval.

@bartekus
bartekus merged commit ba225e8 into main Oct 21, 2026
7 checks passed
@bartekus
bartekus deleted the impl/027-node-js branch October 21, 2026 04:50
bartekus added a commit that referenced this pull request Oct 21, 2026
Spec 027, increment 6 (second change): the native conformance adapter.
Stacked on #131.

- `tools/rustev-conformance/js/run.mjs` gains the `native` adapter:
every CLI case runs natively (pure commands compared whole with exit
codes; `run` compared on the judgment and the run record, the envelope's
paths, receipt and exit code being CLI presentation), and every runtime
case runs with TypeScript scripted seams driven on a manual clock. All
34 native cases produce their expected bytes, repeatedly; the 23
WebAssembly cases still pass.
- The manifest names each case's surfaces explicitly (pure commands
`cli`/`native`/`wasm`, `run` `cli`/`native`, runtime cases
`rust-api`/`native`).
- The runtime-case driver is now deterministic for asynchronous host
seams: `advance_timer { delay_ms }` advances only when that retry delay
is pending and no attempt is in flight (via
`ManualClock::pending_delays`, #131). Both runners use it.
- The cancellation case shared by both runners mirrors
`cancel.rs::no_answer_means_local_waiting_stopped_and_nothing_more`; the
confirmed-stop case stays Rust-only (`runtime.cancel-stop`), because the
runtime polls a cancelled attempt once and a host seam can never answer
within that poll (recorded in the spec as an owner finding).
- `make bindings` runs the native conformance after the native tests.

Review round 1 (3 findings, fixed): (1) `rawMember` walks the document's
structure and matches only a top-level key, never a nested key or text
inside a string. (2) The sink's records are now checked: a `run` case
requires the sink to have received exactly the bytes the result carries.
(3) An attempt whose scripted backend ignores cancellation is settled
when its case ends, as the late resolution the engine discards, so no
promise is left pending. Restacked on #131; native 34/34 (three runs)
and wasm 23/23.

Review round 2 (2 findings, fixed): (1) `rawMember` tolerates whitespace
around the colon and before the value (canonical goldens are compact,
but nothing depends on it); checked on nested keys, spaced JSON and a
key inside a string. (2) An attempt whose scripted backend ignored
cancellation is settled after its case by resolving, never rejecting, so
a discarded late settlement cannot surface as an unhandled rejection.
Restacked after #133 merged; native 34/34 (twice), wasm 23/23.

Review round 3 (3 findings, fixed): (1) an unknown `on_cancel` value
rejects at once as a script error instead of leaving the attempt
waiting. (2) the sink check runs for every `run` case, whatever outputs
it pins: the sink must have received exactly the result's record bytes.
(3) `rawMember`'s string scans are bounded by the text's length, so
malformed JSON ends the scan. Native 34/34 (twice), wasm 23/23.

Review round 4 (1 finding): by design: the native package links the
rules backend (3.3.2) and reads a rules program itself, as the CLI does,
so the native adapter passes the program's own bytes and every check and
compile case with a rules program produces the CLI's bytes natively
(34/34); only the WebAssembly adapter, which cannot read a rules program
(3.10.1), substitutes the derived descriptor. The code now says so.

Restacked after #130 stopped recording derived descriptors on `run`
cases: this PR now records them for `run` cases itself (the harvest
gives them to pure and `run` cases; the native runner prepares a
compiled plan against them), restored byte-identical to the descriptors
the pure cases carry. Native 34/34, wasm 23/23.

Review round 5 (3 findings): (1) `ManualClock::pending_delays` is in
`crates/rustev-runtime/src/clock.rs` from #131, this PR's base, so it is
in the tree this PR builds on; the workspace compiles and the Rust
runner uses it. (2) fixed: `valueAt` has one exit per kind of value: a
container ends at its matching bracket, a scalar before the delimiter
after it; checked on nested, spaced, string and number members. (3)
fixed: each runtime case keeps its own list of ignored attempts and
settles it when the case ends, however it ends, so none reaches a later
case. Native 34/34 (twice), wasm 23/23.

Review round 6 (1 finding, fixed): a record output is compared byte for
byte, and every normalization its case declares must already hold:
`timing` requires the record's timings to be the normalized zeros (they
are, under the manual clock), and any other normalization fails the
case, so none passes unchecked. Native 34/34 (twice), wasm 23/23.

Review round 7 (2 findings, both verified against #131):
`DecideResult.completion` is the declared field (`index.d.ts`), and the
native gauges object's key is `backendInFlight` (`src/lib.rs` builds it
in camelCase for JavaScript); every runtime case drives `advance_timer`
through it, and native passes 34/34.

Review round 8 (1 finding, fixed): the WebAssembly adapter's store
resolver returns an item that exists but is empty; only an absent item
is null. Restacked after #129 was split (#134 holds the runtime cases).

Review round 9 (1 finding): the late settlement's value is never read:
the native seam (`integrations/rustev-node/src/seams.rs`, #131) takes a
host's settlement as plain JSON, and when the attempt has already
finished it discards and counts it before anything parses it, so no
shape can cause a rejection; the runner's comment now says so.
Restacked; native 34/34 (twice), wasm 23/23.

Restacked on #134's fixes: the native runner gains the `wait_sleeper`
step (the deadline case now waits for the runtime's timer) and fails a
`release_all` that frees nothing, as the Rust runner does. Native 34/34
(twice), wasm 23/23.

CI `code` failed on the previous head: this PR had removed the Rust
runner's `wait_sleeper` step (its retry case moved to `advance_timer`)
while #134 now uses it in the deadline case. Restored, with both runners
supporting it; verified from a clean build of `rustev-runtime` and
`rustev-conformance` (an earlier local run had used a stale shared
build). Native 34/34 (twice).

Restacked on #130's last round: the runner's pure-command comparison
(`comparePure`) checks written outputs against the published artifact
(never skipping one), and the WebAssembly path requires its commands'
flags by name. Native 34/34 (twice), wasm 23/23.

Review round 10 (2 findings): (1) The record goldens hold the normalized
form (timings zero, written by the CLI tests through the shared
normalization), and a decision under the manual clock produces exactly
those bytes, so the byte comparison is the right one; native passes
34/34. The comment says so. (2) fixed: the pure-command engine decides
nothing, so its sink now throws if ever delivered to, failing the case,
instead of answering a placeholder receipt.

Restacked on #135 after #131 was split: this PR is now increment 6's
third change, on the JavaScript layer. Native 34/34 (twice), wasm 23/23.

Rebased after #130 merged: the harvest keeps main's staleness checks
(inputs, derived descriptors, surfaces) with this PR's surfaces
(`native` on every CLI case) and derived descriptors on `run` cases; the
runner keeps its scope object with main's required fields. A re-harvest
reproduces every case file (the wall-clock replay bundle aside). Native
34/34 (twice), wasm 23/23.

Review round 11 (3 findings): (1) fixed: the attempt loop no longer
shadows the flags object. (2) Not so: the native `command` takes its
arguments as a JSON value and deserializes `scope` from an object
(`integrations/rustev-node/src/commands.rs`, `replay_config`), and the
native replay cases pass; the comment says why it differs from the
WebAssembly call, which takes a string. (3) Repeated:
`ManualClock::pending_delays` is in #131, this PR's base.

Review round 12 (1 finding, raised before): the record goldens are
written in their normalized form by the CLI tests (timings zero), so
normalizing them would change nothing; the runner now checks that on the
golden too, failing with a message naming it if a golden were ever
stored unnormalized, as it checks the record. Native 34/34 (twice).

Split (the AI review was cancelled at its 15-minute limit twice): this
PR is now increment 6's third change, the native conformance cases
(surfaces, derived descriptors on `run` cases, the runtime driver's
corrections and the Rust-only cancel-stop case); the JavaScript runner's
native adapter (`run.mjs` and its `make bindings` step) moves to a PR
stacked on this one.

Review round 13 (1 finding, raised before):
`ManualClock::pending_delays` is on main
(`crates/rustev-runtime/src/clock.rs`, from #131, increment 6's first
change), so this PR does not change that file and the crate builds; the
spec record now names where the accessor comes from rather than reading
as if this change adds it.
bartekus added a commit that referenced this pull request Oct 21, 2026
Spec 027 increment 7, first change: the native package's platform
packages (3.13.1, 3.13.2).

- `integrations/rustev-node/npm/<platform>/package.json` for the seven
platforms the main package's `optionalDependencies` name
(`linux-x64-gnu`, `linux-x64-musl`, `linux-arm64-gnu`,
`linux-arm64-musl`, `darwin-arm64`, `darwin-x64`, `win32-x64-msvc`):
`@statecrafting/rustev-<platform>` at the main package's version,
license and engines; `os`, `cpu` and, on Linux, `libc` as the name says;
`main` and `files` the addon `rustev.<platform>.node` alone; no scripts;
`private` until spec 031's release.
- `tools/rustev-conformance/js/platform-packages.mjs`:
- `check`: every optional dependency has its package and they agree as
above; no stray platform directory; no script in a platform package and
no install-time script (`preinstall`, `install`, `postinstall`,
`prepare`) in the main package;
- `stage <target>`: copies this host's release addon into its platform
package;
- `fresh <dir>`: `npm pack`s the main package and this host's platform
package and installs both into a fresh project from the tarballs
(`--omit=optional --ignore-scripts`), so nothing is fetched for another
platform, and fails if the main package's tarball carries an addon.
- `copy-addon.mjs` exports the addon naming it already had (`addonName`,
`builtAddon`) for that reuse; its command line is unchanged.
- `make bindings` runs `check`, `stage`, `fresh`, then the native
conformance suite on the fresh install, so the suite exercises the
loader's platform-package path (3.13.2), not only the local build.
- Spec 027: implementation record.

Building and smoke-testing each of the seven targets in CI is a later
change of this increment (the `bindings` job).

Local verification (macOS arm64, clean build of the changed crates):
`make bindings` passes end to end (`npm audit signatures`, WebAssembly
conformance 23/23, 27 native tests, native conformance 34/34 on the
local build and 34/34 on the fresh install); `make gate`; `bash
scripts/check-authored-content.sh`.

Review round 1 (3 findings, fixed):
1. `check` refused any `scripts` on the main package. 3.13.2 forbids
install-time code, so it now refuses only npm's install lifecycle
scripts there (`preinstall`, `install`, `postinstall`, `prepare`); a
platform package still has no script at all. Seeded locally: a `build`
script on the main package passes, a `postinstall` fails naming it.
2. `stage` and `fresh` let `addonName()`'s throw on an unsupported
platform escape as a stack trace; both now go through `hostPlatform()`,
which exits with the message.
3. npm ran with `shell: true` on Windows, so cmd.exe parsed the paths.
npm now runs without a shell everywhere: on Windows its entry point
(`node_modules/npm/bin/npm-cli.js` beside `node.exe`) runs under the
current Node, and a missing one fails by name.

Review round 2 (2 findings, fixed):
1. `fresh` deleted its target directory unconditionally. It now writes a
marker (`.rustev-fresh`) into the directory it makes and replaces only a
directory carrying it; any other existing path is refused by name and
left alone (seeded locally: a scratch directory holding a file was
refused and kept). In `make bindings` the path is under the cargo target
directory, which the target already refuses to be empty.
2. `pack` joined npm's reported file name unchecked. A response that is
not JSON, or a name that is not one plain `.tgz` file name, or a tarball
that is not there, now fails with a message naming the package.

Review round 3 (1 finding, answered in the diff, no behavior change):
`addonName()` skips `excludeNetwork` when `process.report` has no such
own property. That is deliberate and unchanged from #135's loader: only
a Node that supports leaving the network section out exposes the
property, and assigning it elsewhere would add a plain property the
report never reads. The comment at the call now says so; the report then
runs whole, slower but correct.

Rebased onto `main` after #138 and #139 merged. Local `make bindings` on
the rebased branch, after `cargo clean -p` of every crate #139 changed:
WebAssembly conformance 23/23, 27 native tests, native conformance
34/34; its `fresh` step refused a `native-fresh` directory left by a run
from before the round-2 marker existed (the guard working as intended).
With that directory removed, the fresh install's suite passed 34/34.

Review round 4 (2 findings, fixed):
1. `builtAddon()` produced a path ending in `.undefined` on an
unsupported platform; it now throws naming the platform, and `stage`
reports it cleanly.
2. `check` counted any entry under `npm/` as a platform directory, so
macOS's `.DS_Store` failed it; only non-hidden directories count now
(seeded locally with a `.DS_Store`: `check` passes).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant