Skip to content

Arena/6362b41e affinescript - #865

Merged
hyperpolymath merged 3 commits into
mainfrom
arena/6362b41e-affinescript
Dec 2, 2026
Merged

hyperpolymath merged 3 commits into
mainfrom
arena/6362b41e-affinescript

Conversation

@hyperpolymath

Copy link
Copy Markdown
Owner

Summary

Closes #

Type of change

  • 🐛 Bug fix (non-breaking change that fixes an issue)
  • ✨ New feature (non-breaking change that adds functionality)
  • 💥 Breaking change (would change existing behaviour)
  • 🕳️ Soundness fix (fixes a checker/proof false-negative)
  • 📖 Documentation
  • 🧹 Refactor / tech debt (behaviour-preserving)
  • ⚡ Performance
  • 🔧 Build / CI / tooling

How has this been verified?

Checklist

  • My commits are signed (git commit -S).
  • I ran the project's own checks/tests locally and they pass.
  • New files carry the correct SPDX-License-Identifier (code/config MPL-2.0,
    prose CC-BY-SA-4.0); I did not relicense existing files.
  • Docs are updated, and no public claim now overstates what the code does.
  • I have not introduced a soundness hole (or I have flagged where I might have).

Notes for reviewers

Arena Agent and others added 2 commits October 31, 2026 19:11
…scriptDom.affine)

Item (4) of the userscript brief, in the only form that fits the target: the
ESM runtime (packages/affine-js) cannot be bundled to an IIFE (import.meta,
dynamic import("node:fs/promises"), import("node:url")), so the reconciler is
authored in AffineScript and compiled into the same single file.

- UserscriptDom: Attr/Spec/Element/Group over opaque Node handles; create,
  patch (attribute add *and* remove, text only when changed), set_text_of,
  unmount, group/reconcile/unmount_all, member_count. A reconciler, not a vdom
  diff: an Element remembers its state, which is what makes in-place patching
  possible without get_attribute or a recursive vnode type.
- lib/codegen_userscript.ml: lower the `len` typechecker builtin to .length.
  It has no extern declaration to be lowered through, so without this any
  reachable `len` emitted a call to an undefined global.
- docs: the guide now points at UserscriptDom as the IIFE-buildable runtime.

NOTE: not compiled yet — the sandbox still cannot build (sedlex fetches
UnicodeData.txt from unicode.org); test/test_stdlib_aot.ml picks every
stdlib/*.affine up automatically, so `dune test` is its first check.

Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com>
…it exposed

The DOM runtime is no longer authored blind: the toolchain now builds here
(sedlex 3.2 install fixed, see below), so everything in this commit was
compiled and run before it was written down.

- test/e2e/userscript/dom.affine: create -> patch (attribute dropped, text
  changed) -> text-only patch -> reconcile 0->3 and 3->2 -> teardown.
- test/e2e/userscript/dom_harness.mjs: runs that artefact against a recording
  fake DOM. UserscriptDom only reaches the page through createElement/
  appendChild/removeChild/*Attribute/textContent, so no browser and no jsdom
  are needed -- 12 checks (markers, attribute add/remove sequence, empty page
  after teardown) run anywhere a compiler does.
- run.sh: compiles the fixture, holds it to the single-capsule/no-import/
  size-budget rules, then runs the harness. Suite: 57 -> 69 checks.
- lib/codegen_userscript.ml: `show` is a typechecker builtin like `len`, so
  it reached the emitter with no extern to lower through and emitted a call to
  an undefined global. Lower it to `__as_show`, matching the other JS
  backends, and define that in the runtime.
- stdlib/UserscriptDom.affine: `for`/`if` statements do not take a trailing
  semicolon -- parsing caught it, `check` now passes.
- tools/bootstrap-ocaml-toolchain.sh: `sedlex.ppx` is a public_name inside
  the `sedlex` package, not a package; naming it as an install target failed
  the sedlex step with "Unknown package sedlex.ppx".

Measured: dom.affine 7,991 B; probe 18,523 B; probe+banner 18,861 B;
reachability 4,351 B; hello 4,318 B (budget 24,576).

Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com>
@gitnotebooks

gitnotebooks Bot commented Dec 2, 2026

Copy link
Copy Markdown

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Dec 2, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-12-02T15:53:41.089060Z 5d9ca65 PR opened
🔒 Security Review ✅ Completed 2026-12-02T15:50:34.346876Z 5d9ca65 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@coderabbitai

coderabbitai Bot commented Dec 2, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

Caution

Review failed

The pull request is closed.

  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

Signed-off-by: Jonathan D.A. Jewell <6759885+hyperpolymath@users.noreply.github.com>
@hyperpolymath
hyperpolymath merged commit 2f323ac into main Dec 2, 2026
13 of 16 checks passed
@hyperpolymath
hyperpolymath deleted the arena/6362b41e-affinescript branch December 2, 2026 15:43
@sonarqubecloud

sonarqubecloud Bot commented Dec 2, 2026

Copy link
Copy Markdown

Quality Gate Failed Quality Gate failed

Failed conditions
C Security Rating on New Code (required ≥ A)

See analysis details on SonarQube Cloud

Catch issues before they fail your Quality Gate with our IDE extension SonarQube for IDE

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 5d9ca65a08

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread lib/codegen_userscript.ml
Comment on lines +454 to +456
const probe = "__affinescript_userscript_probe__";
store.setItem(probe, "1");
store.removeItem(probe);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Preserve localStorage data while probing availability

When the host page already has a value under __affinescript_userscript_probe__, every call to capabilities() overwrites that value and then deletes it. Since userscripts run against arbitrary pages and capabilities() is called by each settings operation, this can silently corrupt page-owned localStorage; preserve and restore any prior value or use a collision-resistant temporary key.

Useful? React with 👍 / 👎.

Comment thread lib/codegen_userscript.ml
Comment on lines +1012 to +1016
| Some g -> " && (" ^ gen_expr ctx g ^ ")"
| None -> ""
in
let body = gen_expr ctx arm.ma_body in
"if (" ^ cond ^ guard ^ ") { " ^ bindings ^ "return " ^ body ^ "; } else "

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Bind match variables before evaluating arm guards

For a guarded arm such as Some(x) if x > 0 => ..., the generated condition evaluates the guard before the branch emits const x = __scrut.value, causing a ReferenceError (or reading an unrelated outer binding). This affects both expression and statement matches; test the pattern first, introduce its bindings, and only then evaluate the guard before selecting the arm.

Useful? React with 👍 / 👎.

Comment thread stdlib/Userscript.affine
Comment on lines +165 to +170
let can_read = us_gm_has("getValue");
let can_write = us_gm_has("setValue");
Caps #{
manager: can_read,
gm_storage: can_read,
local_storage: us_local_available(),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Select storage capabilities per operation

With partial userscript grants, gm_storage is true solely when GM_getValue exists, while the computed can_write is ignored and GM_deleteValue is not checked at all. For example, a script granted only GM_getValue with usable localStorage routes set_setting and delete_setting to missing GM functions and returns HostRejected instead of using the documented localStorage fallback; each operation needs to check its corresponding GM capability.

Useful? React with 👍 / 👎.

Comment thread lib/codegen_userscript.ml
| ExprApp (func, args) ->
let arg_strs = List.map (gen_expr ctx) args in
(match func with
| ExprVar id when id.name = "len" && List.length arg_strs = 1 ->

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Let local definitions shadow intrinsic lowerings

When a program defines its own len, calls are still unconditionally rewritten to .length; for example, the repository's supported fn len(xs: IntList) -> Int shape would produce an invalid result under this target. The same name-only dispatch also affects show and every userscript extern name, so intrinsic lowering should be suppressed when the flattened program contains a same-named local function or constant.

Useful? React with 👍 / 👎.

Comment thread bin/main.ml
(* The default output path is a wasm module; a userscript is one .js file,
so an unspecified -o becomes out.user.js instead of silently writing a
JS source file called out.wasm. *)
let output = if userscript && output = "out.wasm" then "out.user.js" else output in

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Honor explicit output paths equal to the default

When a caller explicitly supplies -o out.wasm with the userscript target, this equality check treats the requested path as if it were an omitted option and writes out.user.js instead. Build scripts that always pass an output path will then fail to find the promised artifact; the CLI needs to retain whether -o was supplied rather than inferring omission from its value.

Useful? React with 👍 / 👎.

Comment on lines +121 to +123
pub fn patch_from(el: Element, s: Spec) -> Element {
patch(el, s.attrs, s.text)
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Replace elements when a patched spec changes the tag

patch_from discards s.html_tag, so patching an existing <p> with a Spec for <div> updates attributes and text but leaves a <p> in the page. Because the public API accepts an arbitrary Spec and documents no same-tag precondition, it must either replace the DOM node when the tag changes or reject such a patch explicitly.

Useful? React with 👍 / 👎.

Comment thread lib/codegen_userscript.ml
// here rather than awaited, because top-level `await` is not allowed in a
// non-module script.
try {
const __as_result = main();

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Reject parameterized userscript entry points

The generated capsule always invokes main() with no arguments, but the target never validates that the source main has zero parameters. A program with fn main(x: Int) therefore compiles successfully and runs with x === undefined, producing invalid values or delayed runtime failures instead of a build diagnostic.

Useful? React with 👍 / 👎.

Comment thread lib/jcs.ml
match v with
| `Null -> Buffer.add_string buf "null"; Ok ()
| `Bool b -> Buffer.add_string buf (if b then "true" else "false"); Ok ()
| `Int i -> Buffer.add_string buf (string_of_int i); Ok ()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Reject integers outside the interoperable JCS range

The Int branch emits arbitrary OCaml integers verbatim, including values such as 9007199254740993 that cannot be represented by the IEEE-754 number model required by JCS/I-JSON consumers. Such a consumer parses that value as 9007199254740992 and canonicalizes different bytes, defeating the promised cross-implementation canonical form; reject non-interoperable integers or require them to be represented as strings.

Useful? React with 👍 / 👎.

Comment thread lib/codegen_userscript.ml
Comment on lines +204 to +207
(match fd.fd_body with
| FnExpr e -> expr_unsupported e
| FnBlock blk -> block_unsupported blk
| FnExtern -> None)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Reject unbound extern methods inside impl blocks

A bodiless ImplFn is explicitly treated as supported regardless of its name, unlike top-level extern functions. An impl containing an extern method with no userscript lowering therefore passes the build-time closed-capability check and is emitted as a function that only throws at runtime; run these methods through extern_name so unsupported host access is rejected during compilation.

Useful? React with 👍 / 👎.

Comment thread stdlib/Userscript.affine
manager: can_read,
gm_storage: can_read,
local_storage: us_local_available(),
menu: us_gm_has("registerMenuCommand"),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Require unregister capability before issuing menu handles

capabilities().menu checks only GM_registerMenuCommand, so a script granted registration but not GM_unregisterMenuCommand receives a handle that the API says must be released, yet release_menu_command can only fail and leave the native menu active. Require both capabilities before registering a releasable command, or provide a release path that does not depend on the missing grant.

Useful? React with 👍 / 👎.

hyperpolymath pushed a commit that referenced this pull request Dec 5, 2026
test/test_jcs.ml, from #865, did not compile, so dune built no test
runner. main's 'build' job has been red since #865, and every later
regression was hidden behind it.

- a top-level 'let open' with no 'in' becomes 'open Affinescript',
  which is where Jcs lives;
- the canonical_inputs list was missing its ';' separators;
- 'tests' is now a flat test_case list, as test_main expects.

With the runner building again, #865's canonical key order shows up
in one older expectation: eval --json now prints
{"diagnostics":..,"success":..,"version":1}. Updated.

Two failures remain, not fixed here: #862's continued if/match tests
assert the grammar from before #863. That needs an owner call.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0136P7Zo5h4xmXVEeSeQEDvw
hyperpolymath added a commit that referenced this pull request Dec 5, 2026
… loud (#848) (#867)

Closes #848

## Summary

On core WASM a write to a `mut` parameter was lost: `fn set(mut m: Int)
{ m = 100 }` left the caller's `x` at 5, while the interpreter gives
100. Bun-ESM lost the same write. ADR-028's gate requires every backend
to either write through or fail loudly.

**Core WASM writes through (copy-out):**
- A prepass gives each `mut` parameter of a defined fn its own mutable
write-back global.
- The callee stores the parameter to that global before every `Return`,
including inside nested blocks, and at the fall-through end.
- A direct caller then copies the global into the argument: a local, or
a mutable module global.
- Parameter types don't change, so exports and the host ABI are
unchanged.

**Core WASM fails loudly (`UnsupportedFeature`, naming #848) on:**
- a field, element, tuple-index or deref argument (the message suggests
binding it to a `let mut` first);
- a `mut` parameter on an imported fn or a closure;
- any `&mut` expression. ADR-028 option E withdraws reference
expressions anyway.

**Bun-ESM fails loudly.** A JS parameter can't be written back without
changing the JS ABI of exported functions, so Bun-ESM rejects:
- `&mut` (before this, it died with an internal "Pattern matching
failed");
- any program that *calls* a function which reassigns a `mut` parameter.

Only *defining* such a function still compiles, so
`stdlib/option.affine` (`take`) keeps building; the AOT smoke test
caught this. Writes to a field of a `mut` param go through the shared
object and are untouched.

## Not covered

- **Other text backends** (JS-text, C, Julia, …) aren't audited here.
They're still open under ADR-028's every-backend gate.
- **A function value passed rather than called** (`map(take, xs)`) isn't
caught by the Bun call-site check.
- **The typed-wasm Level 7 check** (informational on `compile`) reports
the write-back read as an extra use of an ExclBorrow param. It already
flagged any `mut` param read twice on main (e.g. `m = m + 1; m`), so I
left the verifier alone.

## main is red independently

`test/test_jcs.ml` (#865) doesn't compile, so `build` can't run the
OCaml tests on any branch, this one included.
- I checked this PR with a local repair applied: 882 tests run, and the
only failures are 2 that are also on main. #862's continued-if/match
tests assert the grammar from before #863.
- The repair is pushed as branch `fix/main-test-suite-compiles`, with no
PR yet, pending the owner.

## Test plan

- `dune build @runtest --force` (with the local test_jcs repair): the
new `mut parameter write-through or loud failure (#848)` suite, 8 cases,
passes. Nothing else regresses against main.
- `bash tools/run_codegen_wasm_tests.sh`: 49 harnesses pass. The new
`test_mut_param_writeback.mjs` fails on `28d949f` (`early()=5, want
100`).
- `tools/check-soundness-ledger.sh`: all 5 properties hold. There is a
new #848 row, the stamp is advanced to `28d949f`, and the anchors are
resealed.

---
_Generated by [Claude Code](https://claude.ai/code)_

Co-authored-by: CLAUDE <355856132+HoTT-stuff@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
hyperpolymath added a commit that referenced this pull request Dec 5, 2026
## Summary

main's `build`, `lint` and `coverage-visibility` jobs have been red
since #865: `test/test_jcs.ml` doesn't compile, so dune builds no OCaml
test runner. Every regression since then has been hidden behind it. This
PR gets main's tests compiling and passing again.

**1. `test/test_jcs.ml` (#865)**
- The top-level `let open Yojson.Basic` had no `in`; it is now `open
Affinescript`, where `Jcs` lives.
- The `canonical_inputs` list was missing its `;` separators.
- `tests` is now a flat `test_case` list, as `test_main` expects.

**2. `test/test_interp_eval.ml`**
- The `eval --json` expectation now uses #865's canonical key order
(`{"diagnostics":..,"success":..,"version":1}`).

**3. `test/test_call_diagnostics.ml` (#862 vs #863; owner ruling: #863's
grammar wins)**
- #863 made a statement `if`/`match` end at its `}`, so the #644 shape
(`if c { .. }` then `(u, 2)`) type-checks. #862 still asserted that
shape was a `StatementContinued` error.
- The diagnostic is still reachable when a statement's head is a
parenthesised `if`/`match` that is then called (`(if c { () } else { ()
})(3);`). The two tests now use that shape, and a new test pins that the
old shapes type-check.
- The diagnostic's advice ("put `;` after its closing `}`") no longer
fits the remaining shape. That's filed separately, not changed here.

`docs/SOUNDNESS.adoc`: stamp advanced to `28d949f`, anchors resealed
(`test_interp_eval.ml` is an anchor).

No compiler code changes.

## Test plan

- `dune build @runtest --force`: 875 tests run, 0 failures.
- `tools/check-soundness-ledger.sh`: all 5 properties hold.

Unblocks #867 (#848), whose CI is red only because of this.

---
_Generated by [Claude Code](https://claude.ai/code)_

---------

Co-authored-by: CLAUDE <355856132+HoTT-stuff@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
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