Cotton code
270 lines · 18.1 KB · RustRaw
//! `ink.*` over a synthetic phone: the asks and answers, the letters, the//! marks, the waits, the kept line. The model is a stand-in that answers//! every group the same, so what is held here is the boundary's own.use serde_json::{json, Value};use crate::handle::CottonHandle;fn ask(handle: &CottonHandle, method: &str, request: Value) -> Value {    crate::methods::dispatch(handle, method, &request).unwrap_or_else(|error| panic!("{method} {request}: {error:?}"))}/// The model as a shell runs it: every group read as `letters`, the first/// most surely.fn answer(asks: &Value, letters: &[(&str, f64)]) -> Vec<Value> {    let classes = cotton_core::ink::input::CLASSES;    asks.as_array()        .unwrap()        .iter()        .map(|asked| {            assert_eq!(asked["points"].as_array().unwrap().len(), 64, "the model reads 64 samples");            assert!(asked["strokes"].as_f64().unwrap() >= 1.0);            let named: f64 = letters.iter().map(|(_, p)| p).sum();            let rest = (1.0 - named) / (62 - letters.len()) as f64;            let probabilities: Vec<f64> = classes.iter().map(|class| letters.iter().find(|(l, _)| l == class).map(|(_, p)| *p).unwrap_or(rest)).collect();            json!({"key": asked["key"], "probabilities": probabilities})        })        .collect()}/// A call, its asks answered by the stand-in until the reading comes.fn written(handle: &CottonHandle, method: &str, request: Value, letters: &[(&str, f64)]) -> Value {    let surface = request["surface"].clone();    let mut reply = ask(handle, method, request);    let mut rounds = 0;    while let Some(asks) = reply.get("asks") {        rounds += 1;        assert!(rounds < 6, "the reading converges: {reply}");        reply = ask(handle, "ink.read", json!({"surface": surface, "reads": answer(asks, letters)}));    }    reply}fn stroke(points: &[(f64, f64)], down: f64, up: f64) -> Value {    let n = points.len().max(2) - 1;    let laid: Vec<Value> = points.iter().enumerate().map(|(i, (x, y))| json!([x, y, down + (up - down) * i as f64 / n as f64])).collect();    json!({"points": laid, "down": down, "up": up})}fn dense(from: (f64, f64), to: (f64, f64)) -> Vec<(f64, f64)> {    (0..=20).map(|i| (from.0 + (to.0 - from.0) * i as f64 / 20.0, from.1 + (to.1 - from.1) * i as f64 / 20.0)).collect()}/// A bowl, as a c is written: no mark, the model's.fn bowl(x: f64) -> Vec<(f64, f64)> {    (0..=24).map(|i| {        let a = (60.0 + 240.0 * i as f64 / 24.0) * std::f64::consts::PI / 180.0;        (x + 40.0 * a.cos(), 300.0 + 40.0 * a.sin())    }).collect()}fn context() -> Value {    json!({"screen": [402, 640], "on_card": false, "tool": "person", "view": "person/all", "tier": "deck"})}/// RULE (the move into the core, 7 Nov 2026): the shell is told what it draws and gestures with — the flavours that read ink, the tap and hold, the ink's width and fade, the readout's lighter inks, how many groups the phone keeps — and the model's input, 64 samples over the 62 classes.#[test]fn the_shell_is_told_its_knobs() {    let (_dir, handle) = crate::fixture::synthetic_phone();    let knobs = ask(&handle, "ink.knobs", json!({}));    assert_eq!(knobs["flavours"], json!(cotton_core::ink::shipped().flavours), "the alphabet's own flavours, never restated");    assert_eq!(knobs["tap_travel"], 10.0);    assert_eq!(knobs["hold_seconds"], 0.3);    assert_eq!(knobs["ink_width"], 3.0);    assert_eq!(knobs["ink_fade_seconds"], 0.6);    assert_eq!(knobs["keep_groups"], 5000);    assert_eq!(knobs["samples"], 64);    assert_eq!(knobs["classes"].as_array().unwrap().len(), 62);}/// RULE: a stroke the model must read is asked of the shell, once; answered, it is the letter in progress — drawn as written, its letter provisional, nothing narrowed — and the core says how long to wait; when the wait is over the letter is read, narrows, fades, and its corpus line comes with it.#[test]fn a_letter_is_asked_shown_waited_for_and_read() {    let (_dir, handle) = crate::fixture::synthetic_phone();    let surface = "deck:a-letter";    let first = ask(&handle, "ink.stroke", json!({"surface": surface, "stroke": stroke(&bowl(200.0), 1000.0, 1000.3), "height": 600, "context": context()}));    let asks = first["asks"].as_array().expect("the bowl is the model's to read");    assert!(!asks.is_empty());    let read = ask(&handle, "ink.read", json!({"surface": surface, "reads": answer(&first["asks"], &[("s", 0.9)])}));    assert!(read.get("asks").is_none(), "{read}");    assert_eq!(read["stroke"], 1);    assert_eq!(read["groups"], json!([]));    assert_eq!(read["writing"], json!([1]), "the letter in progress, drawn as written");    assert_eq!(read["provisional"], json!(["s"]));    assert_eq!(read["letters"], "", "a letter in progress narrows nothing");    assert_eq!(read["wait_ms"], 400, "a finished letter waits group_seconds");    let done = written(&handle, "ink.due", json!({"surface": surface, "now": 1000.7, "context": context()}), &[("s", 0.9)]);    assert_eq!(done["letters"], "s");    assert_eq!(done["writing"], json!([]));    assert_eq!(done["wait_ms"], Value::Null);    let group = &done["groups"][0];    assert_eq!(group["strokes"], json!([1]));    assert_eq!(group["runs"][0]["read"], "letter");    assert_eq!(group["runs"][0]["letter"], "s");    assert_eq!(group["shows"], true);    let line: Value = serde_json::from_str(group["line"].as_str().unwrap().trim_end()).unwrap();    assert_eq!(line["read"], "s");    assert_eq!(line["letters"], "s", "the line says the letters after it");    assert_eq!(line["tool"], "person");    assert_eq!(line["where"], "ground");    assert!(group["line"].as_str().unwrap().ends_with('\n'));}/// RULE: a letter written always extends the letters; a doubtful one narrows as any other and is said doubted; the readout's tap takes the last back and its hold clears them.#[test]fn letters_extend_and_the_readout_edits_them() {    let (_dir, handle) = crate::fixture::synthetic_phone();    let surface = "deck:extend";    written(&handle, "ink.stroke", json!({"surface": surface, "stroke": stroke(&bowl(100.0), 1000.0, 1000.3), "context": context()}), &[("c", 0.9)]);    written(&handle, "ink.due", json!({"surface": surface, "now": 1001.0}), &[("c", 0.9)]);    written(&handle, "ink.stroke", json!({"surface": surface, "stroke": stroke(&bowl(300.0), 1010.0, 1010.3), "context": context()}), &[("a", 0.3)]);    let both = written(&handle, "ink.due", json!({"surface": surface, "now": 1011.0}), &[("a", 0.3)]);    assert_eq!(both["letters"], "ca", "a letter long after the last still extends them");    assert_eq!(both["doubted"], json!([false, true]), "the a was doubted");    assert_eq!(both["groups"][0]["runs"][0]["read"], "doubtful");    assert_eq!(ask(&handle, "ink.edit", json!({"surface": surface, "edit": "backspace"}))["letters"], "c");    assert_eq!(ask(&handle, "ink.edit", json!({"surface": surface, "edit": "clear"}))["letters"], "");    assert_eq!(crate::methods::dispatch(&handle, "ink.edit", &json!({"surface": surface, "edit": "undo"})).unwrap_err().code, "bad_request");}/// RULE: a scratch-out clears the letters at once, asking nothing of the model; a short level stroke to the left takes the last letter back, one to the right clears them; a long level line is the page swipe, handed back with its ends and its step (leftward the next card, past the alphabet's `page_swipe`), the letters kept.#[test]fn marks_and_lines_edit_the_letters() {    let (_dir, handle) = crate::fixture::synthetic_phone();    let surface = "deck:marks";    for (at, letter) in [(1000.0, "a"), (1010.0, "b")] {        written(&handle, "ink.stroke", json!({"surface": surface, "stroke": stroke(&bowl(200.0), at, at + 0.3), "context": context()}), &[(letter, 0.9)]);        written(&handle, "ink.due", json!({"surface": surface, "now": at + 1.0}), &[(letter, 0.9)]);    }    let back = ask(&handle, "ink.stroke", json!({"surface": surface, "stroke": stroke(&dense((200.0, 300.0), (120.0, 304.0)), 1020.0, 1020.2), "context": context()}));    assert!(back.get("asks").is_none(), "a line is no letter: {back}");    let back = written(&handle, "ink.due", json!({"surface": surface, "now": 1021.5}), &[]);    assert_eq!(back["letters"], "a");    assert_eq!(back["groups"][0]["runs"][0]["edit"], "backspace");    let swipe = written(&handle, "ink.stroke", json!({"surface": surface, "stroke": stroke(&dense((360.0, 300.0), (60.0, 306.0)), 1030.0, 1030.2), "context": context()}), &[]);    let run = &swipe["groups"][0]["runs"][0];    assert_eq!(run["read"], "line", "a long level line is read at once: {swipe}");    assert_eq!(run["from"], json!([360.0, 300.0]));    assert!(run.get("edit").is_none(), "the page swipe edits nothing");    assert_eq!(run["step"], 1, "leftward: the deck's next card");    assert!(back["groups"][0]["runs"][0].get("step").is_none(), "a line that edited the letters steps nothing");    assert_eq!(swipe["letters"], "a");    assert_eq!(swipe["groups"][0]["shows"], false, "a line's ink does not linger");    let zigzag: Vec<(f64, f64)> = [(0.0, 45.0), (100.0, 50.0), (0.0, 55.0), (100.0, 60.0), (0.0, 65.0)]        .windows(2)        .flat_map(|pair| dense((100.0 + pair[0].0 * 1.6, 300.0 + pair[0].1), (100.0 + pair[1].0 * 1.6, 300.0 + pair[1].1)))        .collect();    let cleared = ask(&handle, "ink.stroke", json!({"surface": surface, "stroke": stroke(&zigzag, 1040.0, 1040.5), "context": context()}));    assert!(cleared.get("asks").is_none(), "a scratch-out is read by rule");    assert_eq!(cleared["groups"][0]["runs"][0]["read"], "clear");    assert_eq!(cleared["letters"], "");}/// RULE (owner, 3 Nov 2026: "marking a todo as done is just having a check mark"): a check is a mark, read at its lift, handed back for the card it is drawn over; it is never a letter and the letters stay.#[test]fn a_check_is_handed_back_as_a_mark() {    let (_dir, handle) = crate::fixture::synthetic_phone();    let tick: Vec<(f64, f64)> = [dense((200.0, 354.0), (222.5, 376.5)), dense((222.5, 376.5), (290.0, 300.0))].concat();    let reply = ask(&handle, "ink.stroke", json!({"surface": "deck:check", "stroke": stroke(&tick, 1000.0, 1000.3), "context": context()}));    let run = &reply["groups"][0]["runs"][0];    assert_eq!(run["read"], "mark");    assert_eq!(run["mark"], "check");    assert_eq!(run["strokes"], json!([1]));    assert_eq!(reply["letters"], "");}/// RULE: a card opened in place holds its deck: written over it (`narrows` false), letters and marks read as ever but the letters stay as they are; a drop lets the letter in progress go and keeps the letters; a clear lets everything go.#[test]fn held_letters_stay_and_drop_and_clear_let_go() {    let (_dir, handle) = crate::fixture::synthetic_phone();    let surface = "deck:held";    written(&handle, "ink.stroke", json!({"surface": surface, "stroke": stroke(&bowl(200.0), 1000.0, 1000.3), "context": context()}), &[("m", 0.9)]);    written(&handle, "ink.due", json!({"surface": surface, "now": 1001.0}), &[("m", 0.9)]);    written(&handle, "ink.stroke", json!({"surface": surface, "narrows": false, "stroke": stroke(&bowl(200.0), 1010.0, 1010.3), "context": context()}), &[("o", 0.9)]);    let held = written(&handle, "ink.due", json!({"surface": surface, "narrows": false, "now": 1011.0}), &[("o", 0.9)]);    assert_eq!(held["groups"][0]["runs"][0]["letter"], "o", "read all the same");    assert_eq!(held["letters"], "m", "the letters held");    written(&handle, "ink.stroke", json!({"surface": surface, "stroke": stroke(&bowl(200.0), 1020.0, 1020.3), "context": context()}), &[("o", 0.9)]);    assert_eq!(ask(&handle, "ink.drop", json!({"surface": surface}))["letters"], "m");    let after = written(&handle, "ink.due", json!({"surface": surface, "now": 1021.0}), &[]);    assert_eq!(after["groups"], json!([]), "the letter in progress was let go");    assert_eq!(ask(&handle, "ink.clear", json!({"surface": surface}))["letters"], "");}/// RULE (owner, 3 Nov 2026: "I also want to include having numbers"): what the surface admits is its table's — a deck of people takes letters, so a ring the model reads 0 before o is the o there, and the same ring on no table is the 0.#[test]fn a_surface_admits_what_its_table_holds() {    let (_dir, handle) = crate::fixture::synthetic_phone();    let ring: Vec<(f64, f64)> = (0..=32).map(|i| (200.0 + 32.0 * (i as f64 / 32.0 * std::f64::consts::TAU).sin(), 300.0 - 55.0 * (i as f64 / 32.0 * std::f64::consts::TAU).cos())).collect();    let sure = [("0", 0.55), ("o", 0.4)];    written(&handle, "ink.stroke", json!({"surface": "deck:people", "table": "person", "stroke": stroke(&ring, 1000.0, 1000.3), "context": context()}), &sure);    assert_eq!(written(&handle, "ink.due", json!({"surface": "deck:people", "now": 1002.0}), &sure)["letters"], "o");    written(&handle, "ink.stroke", json!({"surface": "deck:any", "stroke": stroke(&ring, 1000.0, 1000.3), "context": context()}), &sure);    assert_eq!(written(&handle, "ink.due", json!({"surface": "deck:any", "now": 1002.0}), &sure)["letters"], "0");    written(&handle, "ink.stroke", json!({"surface": "deck:said", "admits": ["letter"], "stroke": stroke(&ring, 1000.0, 1000.3), "context": context()}), &sure);    assert_eq!(written(&handle, "ink.due", json!({"surface": "deck:said", "now": 1002.0}), &sure)["letters"], "o", "admits said outright, with no table");    let refused = crate::methods::dispatch(&handle, "ink.stroke", &json!({"surface": "deck:none", "table": "no_such_table", "stroke": stroke(&ring, 1.0, 1.3)}));    assert_eq!(refused.unwrap_err().code, "bad_request");}/// RULE: the model answers 62 probabilities or nothing is taken; answers are owed before the next stroke; an answer nobody asked for is refused; a surface is named.#[test]fn what_the_boundary_refuses() {    let (_dir, handle) = crate::fixture::synthetic_phone();    let surface = "deck:refused";    let first = ask(&handle, "ink.stroke", json!({"surface": surface, "stroke": stroke(&bowl(200.0), 1000.0, 1000.3), "context": context()}));    let key = first["asks"][0]["key"].clone();    let short = crate::methods::dispatch(&handle, "ink.read", &json!({"surface": surface, "reads": [{"key": key, "probabilities": [0.5, 0.5]}]}));    assert_eq!(short.unwrap_err().code, "bad_request");    let early = crate::methods::dispatch(&handle, "ink.stroke", &json!({"surface": surface, "stroke": stroke(&bowl(300.0), 1001.0, 1001.3)}));    assert_eq!(early.unwrap_err().code, "bad_request", "the answers are owed first");    ask(&handle, "ink.clear", json!({"surface": surface}));    let unasked = crate::methods::dispatch(&handle, "ink.read", &json!({"surface": surface, "reads": []}));    assert_eq!(unasked.unwrap_err().code, "bad_request");    assert_eq!(crate::methods::dispatch(&handle, "ink.stroke", &json!({"stroke": stroke(&bowl(1.0), 1.0, 2.0)})).unwrap_err().code, "bad_request");}/// RULE: every ink method is one this build answers.#[test]fn the_ink_methods_are_listed() {    let names = crate::methods::methods();    for method in ["ink.knobs", "ink.stroke", "ink.read", "ink.due", "ink.edit", "ink.drop", "ink.clear"] {        assert!(names.iter().any(|name| name == method), "{method}");    }}/// RULE (owner, 15 Nov 2026): Messages' stream is the one contested surface, its knobs the alphabet's; a stroke that never bent there is read at the lift — a level one of 70 points steps to the next chat (leftward) or the one before, a shorter one edits letters once some are written, and a scroll is nothing.#[test]fn a_contested_stroke_is_read_at_the_lift() {    let (_dir, handle) = crate::fixture::synthetic_phone();    let knobs = ask(&handle, "ink.knobs", json!({}));    assert_eq!(knobs["surfaces"], json!({"stream": {"bend": 22.0, "bend_ratio": 0.5, "turn_back": 1.6, "swipe": 70.0, "swipe_level": 0.5}}));    let lift = |from: [f64; 2], to: [f64; 2]| ask(&handle, "ink.contest", json!({"surface": "contested", "contest": "stream", "from": from, "to": to}));    assert_eq!(lift([300.0, 400.0], [200.0, 405.0]), json!({"step": 1}));    assert_eq!(lift([100.0, 400.0], [200.0, 405.0]), json!({"step": -1}));    assert_eq!(lift([300.0, 400.0], [260.0, 400.0]), json!({}), "too short to step, no letters to edit");    assert_eq!(lift([300.0, 400.0], [300.0, 100.0]), json!({}), "a scroll");    // A letter written: a short level stroke is the ink's now, a long one still steps.    let wrote = written(&handle, "ink.stroke", json!({"surface": "contested", "stroke": stroke(&bowl(200.0), 10.0, 10.3), "context": context()}), &[("c", 0.9)]);    let wrote = if wrote["letters"] == "c" { wrote } else { written(&handle, "ink.due", json!({"surface": "contested", "now": 12.0, "context": context()}), &[("c", 0.9)]) };    assert_eq!(wrote["letters"], "c");    assert_eq!(lift([300.0, 400.0], [200.0, 405.0]), json!({"ink": true}));    assert_eq!(lift([300.0, 400.0], [100.0, 405.0]), json!({"step": 1}));    let refused = crate::methods::dispatch(&handle, "ink.contest", &json!({"surface": "contested", "contest": "deck", "from": [0, 0], "to": [100, 0]}));    assert!(refused.is_err(), "a deck is not contested");}/// RULE (Android's ink, 15 Nov 2026): whether a stroke on a contested surface is the ink's yet is the core's, asked mid-stroke by its box and travel — it bent (its narrower side 22 points and half the longer), or a wide one turned back on itself 1.6 times its width; a straight drag stays the scroll's.#[test]fn a_contested_stroke_so_far_is_claimed_by_the_core() {    let (_dir, handle) = crate::fixture::synthetic_phone();    let claims = |size: [f64; 2], travel: f64| ask(&handle, "ink.contest", json!({"surface": "contested", "contest": "stream", "box": size, "travel": travel}));    assert_eq!(claims([4.0, 180.0], 180.0), json!({"claims": false}), "a scroll up the chat");    assert_eq!(claims([30.0, 40.0], 70.0), json!({"claims": true}), "a bowl that bent");    assert_eq!(claims([30.0, 80.0], 90.0), json!({"claims": false}), "narrow for its length: not yet");    assert_eq!(claims([60.0, 8.0], 100.0), json!({"claims": true}), "a flat scratch-out that turned back");    assert_eq!(claims([60.0, 8.0], 60.0), json!({"claims": false}), "a level stroke that did not turn back");    let refused = crate::methods::dispatch(&handle, "ink.contest", &json!({"surface": "contested", "contest": "stream", "box": [1, 2]}));    assert!(refused.is_err(), "a stroke so far says its travel");}