Lull
Rest on one gesture or a quiet span, wake on any touch. A pure reducer over input-event-router's typed stream: one declared gesture event puts an app to rest, a declared quiet span of logical ticks does too, and any touch wakes it with the waking touch consumed, so a tap meant to wake the screen never also acts. No clock read: the caller supplies ticks and schedules its own check at restsAt(). Five fields of state, byte-identical replay. Built for a game's idle porch, a kiosk's attract screen, a viewer's just-look mode. Zero dependencies, JavaScript, browser or Node.
The honest edge
lull decides resting and waking from a typed event stream and logical ticks; it does NOT draw anything, does NOT read a clock or schedule a timer, does NOT validate the stream's order or schema (input-event-router does), and does NOT decide what a consumed waking touch would have done.
Run it
node lull.js --quiet 60 --at 300 < events.jsonl
test_lull.js (21/21: a hand-written golden log, quiet at and one tick before the span, quiet off, one gesture from every awake state, every waking touch consumed, eleven hostile events refused by name with the state untouched, a hostile payload never read, seven bad configs refused, 100,000 events at five fields, byte-identical replay, the command line and its edge) + kill sheet 10/10
JavaScript, zero dependencies, deterministic
The code — every file that ships
lull.js204 lineson GitHub →
#!/usr/bin/env node
/* lull.js — a dependency-free, deterministic reducer that decides when an app
lays its tools down and when it picks them back up.
WHY THIS EXISTS. Every app with a resting view (a game's idle camera, a
kiosk's attract screen, a viewer's "just look" mode) re-hand-rolls the same
three rules: rest after a while of no touching, rest on one gesture, wake on
any touch. Hand-rolled, those rules read a wall clock (so replay breaks), fire
in the middle of an edit (so the player is yanked away), and let the touch
that wakes the screen also act on it (so a tap meant to wake places a
building). This is those rules done once, as a pure fold over a typed event
stream, with logical ticks as data.
THE RULES (the whole contract).
* Rest by gesture: an accepted event whose type is a declared gesture puts
the app to rest. One event: "one gesture" is exactly one such event.
* Rest by quiet: when a declared quiet span of logical ticks has passed
since the last touch, the app is at rest. lull never reads a clock: the
caller asks `at(state, t)` with a tick it supplies, or schedules its own
check at `restsAt(state)`.
* Wake by touch: while at rest, ANY accepted event wakes the app, and that
waking event is CONSUMED: passThrough is false, so the app must not act
on it. A gesture is also consumed: it is lull's, not the app's.
* Quiet can be off: quietTicks null means the app rests only by gesture.
THE INPUT. The typed stream input-event-router emits ({seq, t, type,
payload}); lull reads only `t` (a non-decreasing logical tick) and `type`.
Ordering and schema are the router's job; lull refuses an event whose tick
goes backwards or whose type is not a string, and never looks at payload.
USAGE
node lull.js [--quiet N] [--gesture TYPE]... [--no-gestures] [--at T] < events.jsonl
node lull.js --help
Released under MIT. Its edge, printed in the README and --help: this decides
resting and waking from a typed event stream and logical ticks; it does NOT
draw anything, does NOT read a clock or schedule a timer, does NOT validate
the stream's order or schema (input-event-router does), and does NOT decide
what a consumed waking touch would have done.
*/
"use strict";
var EDGE = "lull decides resting and waking from a typed event stream and logical ticks; it does NOT draw " +
"anything, does NOT read a clock or schedule a timer, does NOT validate the stream's order or schema " +
"(input-event-router does), and does NOT decide what a consumed waking touch would have done.";
var DEFAULT_CONFIG = { gestures: ["rest"], quietTicks: null };
function isInt(v) {
return typeof v === "number" && isFinite(v) && Math.floor(v) === v;
}
function isPlainObject(v) {
return v !== null && typeof v === "object" && !Array.isArray(v);
}
/* checkConfig(cfg) -> { ok: true, cfg } | { ok: false, reason }
gestures: an array of distinct non-empty strings (may be empty: rest by quiet only).
quietTicks: null (rest by gesture only) or an integer >= 1. */
function checkConfig(cfg) {
var c = cfg === undefined ? DEFAULT_CONFIG : cfg;
if (!isPlainObject(c)) return { ok: false, reason: "config-not-object" };
var g = c.gestures === undefined ? DEFAULT_CONFIG.gestures : c.gestures;
if (!Array.isArray(g)) return { ok: false, reason: "gestures-not-list" };
for (var i = 0; i < g.length; i++) {
if (typeof g[i] !== "string" || g[i].length === 0) return { ok: false, reason: "gesture-not-string" };
if (g.indexOf(g[i]) !== i) return { ok: false, reason: "gesture-repeated" };
}
var q = c.quietTicks === undefined ? DEFAULT_CONFIG.quietTicks : c.quietTicks;
if (q !== null && !(isInt(q) && q >= 1)) return { ok: false, reason: "quiet-not-positive-int" };
if (g.length === 0 && q === null) return { ok: false, reason: "no-way-to-rest" };
return { ok: true, cfg: { gestures: g.slice(), quietTicks: q } };
}
/* state0(startTick) — the fold's first state. O(1) by contract: five fields, never a buffer.
mode: "awake" | "resting"; since: the tick the quiet span counts from (the last touch, or the start);
lastTick: the last tick seen (-1 before any); cause: why it rests ("gesture"), else null; count: events folded. */
function state0(startTick) {
var s = startTick === undefined ? 0 : startTick;
return { mode: "awake", since: isInt(s) && s >= 0 ? s : 0, lastTick: -1, cause: null, count: 0 };
}
/* at(state, t, cfg) -> { mode, cause, reject }
Pure: the mode at logical tick t, with no event at t. A stored rest stays a rest; an awake state is at rest
once quietTicks have passed since `since`. A tick before the last one seen is refused, never answered. */
function at(state, t, cfg) {
var c = checkConfig(cfg);
if (!c.ok) return { mode: null, cause: null, reject: c.reason };
if (!isInt(t) || t < 0) return { mode: null, cause: null, reject: "tick-not-int" };
if (t < state.lastTick) return { mode: null, cause: null, reject: "tick-decrease" };
if (state.mode === "resting") return { mode: "resting", cause: state.cause, reject: null };
var q = c.cfg.quietTicks;
if (q !== null && t - state.since >= q) return { mode: "resting", cause: "quiet", reject: null };
return { mode: "awake", cause: null, reject: null };
}
/* restsAt(state, cfg) -> the first tick at which quiet alone puts an awake state to rest, or null
(already resting, or quiet is off). The app schedules its own check there; lull holds no timer. */
function restsAt(state, cfg) {
var c = checkConfig(cfg);
if (!c.ok || state.mode === "resting" || c.cfg.quietTicks === null) return null;
return state.since + c.cfg.quietTicks;
}
/* step(state, event, cfg) -> { state, emit, reject }
The pure reducer. emit = { t, was, mode, cause, passThrough }: passThrough is true only for an ordinary touch
while awake; a gesture and a waking touch are consumed. A refused event leaves the state exactly as it was. */
function step(state, event, cfg) {
var c = checkConfig(cfg);
if (!c.ok) return { state: state, emit: null, reject: { reason: c.reason } };
if (!isPlainObject(event)) return { state: state, emit: null, reject: { reason: "event-not-object" } };
if (typeof event.type !== "string" || event.type.length === 0) {
return { state: state, emit: null, reject: { reason: "type-not-string" } };
}
var now = at(state, event.t, c.cfg);
if (now.reject) return { state: state, emit: null, reject: { reason: now.reject } };
var t = event.t;
var next, emit;
if (now.mode === "resting") {
next = { mode: "awake", since: t, lastTick: t, cause: null, count: state.count + 1 };
emit = { t: t, was: "resting", mode: "awake", cause: null, passThrough: false };
} else if (c.cfg.gestures.indexOf(event.type) !== -1) {
next = { mode: "resting", since: t, lastTick: t, cause: "gesture", count: state.count + 1 };
emit = { t: t, was: "awake", mode: "resting", cause: "gesture", passThrough: false };
} else {
next = { mode: "awake", since: t, lastTick: t, cause: null, count: state.count + 1 };
emit = { t: t, was: "awake", mode: "awake", cause: null, passThrough: true };
}
return { state: next, emit: emit, reject: null };
}
/* foldLog(events, cfg, startTick) -> { state, emits, reject } — folds in order, halting at the first refusal. */
function foldLog(events, cfg, startTick) {
var s = state0(startTick);
var emits = [];
for (var i = 0; i < events.length; i++) {
var r = step(s, events[i], cfg);
if (r.reject) return { state: s, emits: emits, reject: { index: i, reason: r.reject.reason } };
s = r.state;
emits.push(r.emit);
}
return { state: s, emits: emits, reject: null };
}
/* render(state) -> a deterministic one-line text frame (the headless surface). */
function render(state) {
return "lull mode=" + state.mode + " cause=" + (state.cause === null ? "-" : state.cause) +
" since=" + state.since + " last=" + state.lastTick + " count=" + state.count;
}
var api = { step: step, at: at, restsAt: restsAt, foldLog: foldLog, render: render, state0: state0,
checkConfig: checkConfig, DEFAULT_CONFIG: DEFAULT_CONFIG, EDGE: EDGE };
if (typeof module !== "undefined" && module.exports) module.exports = api;
if (typeof window !== "undefined") {
window.ForestGifts = window.ForestGifts || {};
window.ForestGifts.lull = api;
}
/* The CLI: fold a JSONL stream from stdin; print each emit, the final render and, with --at, the mode at T. */
if (typeof require !== "undefined" && typeof module !== "undefined" && require.main === module) {
var argv = process.argv.slice(2);
var HELP = "usage: node lull.js [--quiet N] [--gesture TYPE]... [--no-gestures] [--at T] < events.jsonl\n" +
" folds a typed event stream (input-event-router's output: one {seq,t,type,payload} per line)\n" +
" --quiet N rest after N logical ticks with no event (default: off)\n" +
" --gesture T an event type that puts the app to rest (repeatable; default: rest)\n" +
" --no-gestures rest by quiet only (needs --quiet)\n" +
" --at T after the fold, print the mode at logical tick T\n" +
" prints one JSON emit per event, then the render; refusals print 'refused <index> <reason>'\n" +
" exit 0 folded · 3 refused · 2 usage\n\n" + EDGE + "\n";
var gestures = [], quiet = null, atT = null, bad = null, none = false;
for (var a = 0; a < argv.length; a++) {
if (argv[a] === "--help" || argv[a] === "-h") { process.stdout.write(HELP); process.exit(0); }
else if (argv[a] === "--quiet") { quiet = Number(argv[++a]); }
else if (argv[a] === "--gesture") { gestures.push(String(argv[++a])); }
else if (argv[a] === "--no-gestures") { none = true; }
else if (argv[a] === "--at") { atT = Number(argv[++a]); }
else { bad = argv[a]; }
}
if (bad !== null) { process.stderr.write("lull: unknown argument " + bad + "\n" + HELP); process.exit(2); }
if (none && gestures.length) { process.stderr.write("lull: --no-gestures and --gesture together\n" + HELP); process.exit(2); }
var cfg = { gestures: none ? [] : (gestures.length ? gestures : DEFAULT_CONFIG.gestures), quietTicks: quiet };
var cc = checkConfig(cfg);
if (!cc.ok) { process.stderr.write("lull: config refused: " + cc.reason + "\n"); process.exit(2); }
var chunks = [];
process.stdin.on("data", function (d) { chunks.push(d); });
process.stdin.on("end", function () {
var lines = Buffer.concat(chunks).toString("utf8").split("\n").filter(function (l) { return l.trim() !== ""; });
var events = [];
for (var i = 0; i < lines.length; i++) {
try { events.push(JSON.parse(lines[i])); } catch (e) { events.push(null); }
}
var r = foldLog(events, cfg);
for (var j = 0; j < r.emits.length; j++) process.stdout.write(JSON.stringify(r.emits[j]) + "\n");
process.stdout.write(render(r.state) + "\n");
if (r.reject) { process.stdout.write("refused " + r.reject.index + " " + r.reject.reason + "\n"); process.exit(3); }
if (atT !== null) {
var m = at(r.state, atT, cfg);
if (m.reject) { process.stdout.write("refused at " + m.reject + "\n"); process.exit(3); }
process.stdout.write("at " + atT + " mode=" + m.mode + " cause=" + (m.cause === null ? "-" : m.cause) + "\n");
}
process.exit(0);
});
}
test_lull.js209 lineson GitHub →
#!/usr/bin/env node
/* test_lull.js — the battery for the lull gift. stdlib only (node:assert).
Every expected state and emit below was written out BY HAND from the rules in lull.js's header, before the gift
was run (the out-of-band oracle); the gift is never asked to grade itself.
Run: node test_lull.js (exit 0 all pass · 1 a failure) */
"use strict";
var assert = require("node:assert");
var path = require("node:path");
var child = require("node:child_process");
var L = require(path.join(__dirname, "lull.js"));
var passed = 0, failed = 0;
function test(name, fn) {
try { fn(); passed++; } catch (e) { failed++; process.stdout.write("FAIL " + name + "\n " + e.message + "\n"); }
}
function ev(t, type) { return { seq: 0, t: t, type: type, payload: {} }; }
var PLAT = { gestures: ["rest"], quietTicks: 60 };
// ---- 1. the golden log, by hand ---------------------------------------------------------------------------------
// quiet 60, gesture "rest". Ticks: 5 key (touch) · 40 pointer (touch) · 150 key (quiet rest since 40+60=100: wakes,
// consumed) · 151 rest (gesture: rests) · 152 pointer (wakes, consumed) · 153 key (touch, passes).
var GOLD = [ev(5, "key"), ev(40, "pointer"), ev(150, "key"), ev(151, "rest"), ev(152, "pointer"), ev(153, "key")];
var GOLD_EMITS = [
{ t: 5, was: "awake", mode: "awake", cause: null, passThrough: true },
{ t: 40, was: "awake", mode: "awake", cause: null, passThrough: true },
{ t: 150, was: "resting", mode: "awake", cause: null, passThrough: false },
{ t: 151, was: "awake", mode: "resting", cause: "gesture", passThrough: false },
{ t: 152, was: "resting", mode: "awake", cause: null, passThrough: false },
{ t: 153, was: "awake", mode: "awake", cause: null, passThrough: true }];
var GOLD_STATE = { mode: "awake", since: 153, lastTick: 153, cause: null, count: 6 };
test("golden log folds to the hand-written emits and state", function () {
var r = L.foldLog(GOLD, PLAT);
assert.strictEqual(r.reject, null);
assert.deepStrictEqual(r.emits, GOLD_EMITS);
assert.deepStrictEqual(r.state, GOLD_STATE);
});
test("the mutation bite: a wrong expected state is caught", function () {
var wrong = Object.assign({}, GOLD_STATE, { count: 5 });
assert.throws(function () { assert.deepStrictEqual(L.foldLog(GOLD, PLAT).state, wrong); });
});
// ---- 2. quiet, read at a tick (no event) -------------------------------------------------------------------------
test("quiet: awake one tick before the span, resting at it", function () {
var s = L.foldLog([ev(10, "key")], PLAT).state;
assert.deepStrictEqual(L.at(s, 69, PLAT), { mode: "awake", cause: null, reject: null });
assert.deepStrictEqual(L.at(s, 70, PLAT), { mode: "resting", cause: "quiet", reject: null });
assert.strictEqual(L.restsAt(s, PLAT), 70);
});
test("quiet counts from the start tick before any event", function () {
assert.deepStrictEqual(L.at(L.state0(0), 60, PLAT).mode, "resting");
assert.deepStrictEqual(L.at(L.state0(20), 60, PLAT).mode, "awake");
assert.strictEqual(L.restsAt(L.state0(20), PLAT), 80);
});
test("quiet off: never rests by time, only by gesture", function () {
var cfg = { gestures: ["rest"], quietTicks: null };
var s = L.foldLog([ev(1, "key")], cfg).state;
assert.strictEqual(L.at(s, 1e9, cfg).mode, "awake");
assert.strictEqual(L.restsAt(s, cfg), null);
assert.strictEqual(L.foldLog([ev(1, "key"), ev(2, "rest")], cfg).state.mode, "resting");
});
test("a stored rest has no quiet tick to wait for", function () {
var s = L.foldLog([ev(1, "rest")], PLAT).state;
assert.strictEqual(L.restsAt(s, PLAT), null);
assert.deepStrictEqual(L.at(s, 1, PLAT), { mode: "resting", cause: "gesture", reject: null });
});
// ---- 3. the porch's guarantees ----------------------------------------------------------------------------------
test("one gesture: from every awake state, one gesture event rests", function () {
var logs = [[], [ev(3, "key")], [ev(3, "rest"), ev(4, "key")], [ev(3, "key"), ev(500, "pointer")]];
logs.forEach(function (log) {
var s = L.foldLog(log, PLAT).state;
var t = Math.max(s.lastTick, 0);
if (L.at(s, t, PLAT).mode !== "awake") return;
var r = L.step(s, ev(t, "rest"), PLAT);
assert.strictEqual(r.state.mode, "resting");
assert.strictEqual(r.emit.cause, "gesture");
});
});
test("a waking touch is consumed, whatever its type", function () {
["key", "pointer", "commit", "rest"].forEach(function (type) {
var s = L.foldLog([ev(1, "rest")], PLAT).state;
var r = L.step(s, ev(2, type), PLAT);
assert.strictEqual(r.emit.passThrough, false, type);
assert.strictEqual(r.state.mode, "awake", type);
});
});
test("a touch after a quiet rest wakes and is consumed (the wake is never also a place)", function () {
var r = L.foldLog([ev(1, "key"), ev(1000, "commit")], PLAT);
assert.deepStrictEqual(r.emits[1], { t: 1000, was: "resting", mode: "awake", cause: null, passThrough: false });
});
test("passThrough is true exactly for a non-gesture touch while awake", function () {
var r = L.foldLog([ev(1, "key"), ev(2, "rest"), ev(3, "key"), ev(4, "key")], PLAT);
assert.deepStrictEqual(r.emits.map(function (e) { return e.passThrough; }), [true, false, false, true]);
});
test("a touch at exactly the quiet tick finds the app at rest", function () {
var r = L.foldLog([ev(0, "key"), ev(60, "key")], PLAT);
assert.strictEqual(r.emits[1].was, "resting");
});
test("empty gestures: rest by quiet only", function () {
var cfg = { gestures: [], quietTicks: 5 };
var r = L.foldLog([ev(0, "rest"), ev(1, "key")], cfg);
assert.deepStrictEqual(r.emits.map(function (e) { return e.passThrough; }), [true, true]);
assert.strictEqual(L.at(r.state, 6, cfg).mode, "resting");
});
// ---- 4. hostile vectors: each refused by name, the state untouched -----------------------------------------------
test("hostile events are refused with their declared reason and change nothing", function () {
var s = L.foldLog([ev(10, "key")], PLAT).state;
var frozen = JSON.stringify(s);
[[null, "event-not-object"], [[], "event-not-object"], [5, "event-not-object"],
[{ t: 11 }, "type-not-string"], [{ t: 11, type: "" }, "type-not-string"], [{ t: 11, type: 7 }, "type-not-string"],
[{ t: "11", type: "key" }, "tick-not-int"], [{ t: 1.5, type: "key" }, "tick-not-int"],
[{ t: -1, type: "key" }, "tick-not-int"], [{ t: 9, type: "key" }, "tick-decrease"],
[{ t: Infinity, type: "key" }, "tick-not-int"]].forEach(function (pair) {
var r = L.step(s, pair[0], PLAT);
assert.deepStrictEqual(r.reject, { reason: pair[1] }, JSON.stringify(pair[0]));
assert.strictEqual(r.emit, null);
assert.strictEqual(JSON.stringify(r.state), frozen);
});
});
test("a hostile payload is never read or copied", function () {
var e = JSON.parse('{"seq":0,"t":1,"type":"key","payload":{"__proto__":{"polluted":1}}}');
var r = L.step(L.state0(), e, PLAT);
assert.strictEqual(r.reject, null);
assert.strictEqual(({}).polluted, undefined);
assert.deepStrictEqual(Object.keys(r.emit).sort(), ["cause", "mode", "passThrough", "t", "was"]);
});
test("bad configs are refused by name", function () {
[[null, "config-not-object"], [{ gestures: "rest" }, "gestures-not-list"], [{ gestures: [""] }, "gesture-not-string"],
[{ gestures: ["a", "a"] }, "gesture-repeated"], [{ quietTicks: 0 }, "quiet-not-positive-int"],
[{ quietTicks: 2.5 }, "quiet-not-positive-int"], [{ gestures: [], quietTicks: null }, "no-way-to-rest"]
].forEach(function (pair) {
assert.deepStrictEqual(L.checkConfig(pair[0]), { ok: false, reason: pair[1] }, JSON.stringify(pair[0]));
assert.deepStrictEqual(L.step(L.state0(), ev(1, "key"), pair[0]).reject, { reason: pair[1] });
});
});
test("foldLog halts at the first refusal and keeps what came before", function () {
var r = L.foldLog([ev(5, "key"), ev(3, "key"), ev(9, "key")], PLAT);
assert.deepStrictEqual(r.reject, { index: 1, reason: "tick-decrease" });
assert.strictEqual(r.emits.length, 1);
assert.strictEqual(r.state.lastTick, 5);
});
// ---- 5. state bounds and replay ----------------------------------------------------------------------------------
test("state stays five fields over a long log", function () {
var log = [];
for (var i = 0; i < 100000; i++) log.push(ev(i, i % 97 === 0 ? "rest" : "key"));
var s = L.foldLog(log, PLAT).state;
assert.deepStrictEqual(Object.keys(s).sort(), ["cause", "count", "lastTick", "mode", "since"]);
assert.strictEqual(s.count, 100000);
});
test("replay: the same log folds byte-identically every time (the canonicalizer self-test)", function () {
var a = JSON.stringify(L.foldLog(GOLD, PLAT)) + L.render(L.foldLog(GOLD, PLAT).state);
for (var i = 0; i < 5; i++) assert.strictEqual(JSON.stringify(L.foldLog(GOLD, PLAT)) + L.render(L.foldLog(GOLD, PLAT).state), a);
});
test("render is the hand-written frame", function () {
assert.strictEqual(L.render(GOLD_STATE), "lull mode=awake cause=- since=153 last=153 count=6");
});
// ---- 6. the CLI (the AI People and headless surface) -------------------------------------------------------------
test("CLI folds stdin, prints emits, render and the mode at a tick", function () {
var input = GOLD.map(function (e) { return JSON.stringify(e); }).join("\n") + "\n";
var out = child.execFileSync("node", [path.join(__dirname, "lull.js"), "--quiet", "60", "--at", "300"], { input: input }).toString();
var lines = out.trim().split("\n");
assert.strictEqual(lines.length, 8);
assert.deepStrictEqual(JSON.parse(lines[2]), GOLD_EMITS[2]);
assert.strictEqual(lines[6], "lull mode=awake cause=- since=153 last=153 count=6");
assert.strictEqual(lines[7], "at 300 mode=resting cause=quiet");
});
test("CLI --help prints the edge; a refusal exits 3; a bad config exits 2", function () {
var help = child.execFileSync("node", [path.join(__dirname, "lull.js"), "--help"]).toString();
assert.ok(help.indexOf(L.EDGE) !== -1);
var r = child.spawnSync("node", [path.join(__dirname, "lull.js")], { input: '{"t":5,"type":"key"}\n{"t":2,"type":"key"}\n' });
assert.strictEqual(r.status, 3);
assert.ok(r.stdout.toString().indexOf("refused 1 tick-decrease") !== -1);
var b = child.spawnSync("node", [path.join(__dirname, "lull.js"), "--quiet", "0"], { input: "" });
assert.strictEqual(b.status, 2);
});
test("CLI --no-gestures rests by quiet only; with --gesture it is a usage error", function () {
var input = '{"t":0,"type":"rest"}\n{"t":1,"type":"key"}\n';
var out = child.execFileSync("node", [path.join(__dirname, "lull.js"), "--no-gestures", "--quiet", "5", "--at", "6"], { input: input }).toString();
var lines = out.trim().split("\n");
assert.strictEqual(JSON.parse(lines[0]).passThrough, true);
assert.strictEqual(lines[3], "at 6 mode=resting cause=quiet");
var both = child.spawnSync("node", [path.join(__dirname, "lull.js"), "--no-gestures", "--gesture", "rest", "--quiet", "5"], { input: "" });
assert.strictEqual(both.status, 2);
var neither = child.spawnSync("node", [path.join(__dirname, "lull.js"), "--no-gestures"], { input: "" });
assert.strictEqual(neither.status, 2);
});
process.stdout.write("lull battery: " + passed + " passed, " + failed + " failed\n");
process.exit(failed ? 1 : 0);