diff --git a/docs/bridge.md b/docs/bridge.md index 1dc7df6..1341260 100644 --- a/docs/bridge.md +++ b/docs/bridge.md @@ -255,16 +255,16 @@ Golden bytes: `tests/fixtures/persona-chat-v5/` (`chat_pending.v3.tail` carries ### Follow (`basis` `"follow"`, `CHAT_FOLLOW=1`) -A message from someone she is in conversation with is for her even when it names no one. **It is off unless the mouth runs with `CHAT_FOLLOW=1`** (exactly `1`; default off), because Huginn's parser refuses an unknown basis until its `Basis::Follow` (and the one `is_for` line) lands. With the flag off the mouth emits no `follow`, makes no extra read, and keeps no engagement state. +A message from someone she is in conversation with is for her even when it names no one. **It is off unless the mouth runs with `CHAT_FOLLOW=1`** (exactly `1`; default off), because Huginn's parser refuses an unknown basis until its `Basis::Follow` (and the one `is_for` line) lands. With the flag off the mouth emits no `follow`, makes no extra read, and keeps no follow state. -With it on, the mouth gives a `message` the basis `follow` when it would otherwise have none or `room`, and: +With it on: -- the sender is a peer of an engagement in that room: someone her own post tagged (`m.mentions.user_ids`) or replied to (the author of the quoted `m.in_reply_to`, not a thread fallback pointer). Her post is read from /sync, so a post from any client of her account counts; -- the message is at most W = 600 s after her latest such post (event timestamps). The window anchors on her own post only: a follow delivery never extends it, and her posting again re-anchors it; -- fewer than K = 3 follows were already given for that (Mind, peer, room) in the hour before the message. Past the cap the message keeps the basis it had; -- the room is a public room: not one of her DMs, and its state has no `m.room.encryption`, `m.bridge` or `uk.half-shot.bridge` (read once per room, kept 5 minutes; unreadable is not public). A bridged sender or event (the same identifier rule as `platformEvent`) is neither a peer nor a follower. No engagement is opened from, and no follow is delivered in, such a room. +- **Anchor.** Her own post in a public room anchors that room for W = 600 s from the post. The mouth anchors at send time (the send's own time, in `send`) and also from the /sync echo of her own events, so a post from another client of her account anchors too; one event anchors once. Only her posting again re-anchors the room and re-snapshots who is counted; a follow never extends the window. +- **Counted senders** (snapshotted at the post): those who spoke in that room in the 10 minutes before the post (a per-room ring of recent senders with event times, 200 entries), plus anyone the post tagged (`m.mentions.user_ids`) or replied to (the author of the quoted `m.in_reply_to`, not a thread fallback pointer) when the event carries it. Someone who first speaks after her post is not counted. Nothing reads message text; no ids are scraped from bodies. She herself, and bridged senders (the `platformEvent` identifier rule), never count. +- **Follow.** A `message` (not an edit, not a notice) from a counted sender gets `follow` when it would otherwise have no basis or `room`; `tag`, `reply` and `direct` are never replaced. Its timestamp must lie inside the window and this process's clock must not be past the window's end by more than 60 s, so an old or forged `origin_server_ts` reuses nothing. At most K = 3 per (Mind, peer, room) in the hour before the message; past it the message keeps the basis it had. +- **"Public" means non-DM, non-encrypted, non-bridged.** The room is not one of her DMs and its state has no `m.room.encryption`, `m.bridge` or `uk.half-shot.bridge` (read once per room, kept 5 minutes; unreadable or malformed state is not public). An invite-only plaintext room counts as public. Nothing is anchored in, and no follow is delivered in, any other room. -State is two maps in memory (`room -> peer -> window end`, and follow times per `room|peer`); nothing is stored, and a restart only shortens windows. A tag or reply to her keeps `tag` or `reply`. A mouth `send` writes a plain `m.text` with no `m.mentions` or reply relation, so a post opens an engagement only when the event that comes back through /sync carries them (a post from another client, or a send that gains them). +State is in memory only (per-room anchor, sender ring, follow times), purged on every sync pass; nothing is stored, and a restart only shortens windows. ### Reply link (`chat_pending.v4`) diff --git a/tests/persona-matrix-mouth-follow.test.mjs b/tests/persona-matrix-mouth-follow.test.mjs index a541c5e..aa2ae1a 100644 --- a/tests/persona-matrix-mouth-follow.test.mjs +++ b/tests/persona-matrix-mouth-follow.test.mjs @@ -1,5 +1,5 @@ -// Follow (docs/bridge.md, "Follow"): an untagged message from someone she tagged or replied to, within W of her own post, is basis "follow", -// at most K an hour per (peer, room), public rooms only, and only with the mouth's follow flag. The homeserver is an in-process fetch port: +// Follow (docs/bridge.md, "Follow"): her own post in a public room anchors it for W; those who spoke there in the W before it (and whoever it tagged or +// replied to) are counted, and their later messages are basis "follow", at most K an hour per (peer, room), and only with the mouth's follow flag. The homeserver is an in-process fetch port: // a scripted /sync (one reply per round), the room state and the events a reply target is read from. import test from "node:test"; import assert from "node:assert/strict"; @@ -14,13 +14,14 @@ const OTHER_ROOM = "!side:gamecult.test"; const ME = `@eureka:${HS}`; const KIKO = `@kiko:${HS}`; const STRANGER = `@stranger:${HS}`; +const LENA = `@lena:${HS}`; const PLATFORM = ["disc", "ord"].join(""); const SEC = 1000, W = 600 * SEC, T0 = 1_000_000_000_000; const msg = (id, sender, ts, content = {}) => ({ type: "m.room.message", event_id: id, sender, origin_server_ts: ts, content: { msgtype: "m.text", body: `line ${id}`, ...content } }); const tagKiko = { "m.mentions": { user_ids: [KIKO] } }; // rounds: sync replies after the baseline, each { [roomId]: events }. state: room id -> state events. -function world({ rounds, state = {}, follow = true, rooms = [ALIAS, OTHER_ALIAS], direct } = {}) { +function world({ rounds, state = {}, stateStatus = {}, follow = true, rooms = [ALIAS, OTHER_ALIAS], direct } = {}) { const seen = []; const known = new Map(); let round = 0; @@ -35,7 +36,8 @@ function world({ rounds, state = {}, follow = true, rooms = [ALIAS, OTHER_ALIAS] if (p.startsWith("/directory/room/")) return reply(200, { room_id: { [ALIAS]: ROOM, [OTHER_ALIAS]: OTHER_ROOM }[p.slice(16)] }); if (p.startsWith("/presence/") || p.includes("/receipt/")) return reply(200, {}); const st = p.match(/^\/rooms\/([^/]+)\/state$/); - if (st) return reply(200, state[st[1]] ?? []); + if (st) return stateStatus[st[1]] ? reply(stateStatus[st[1]], { errcode: "M_UNKNOWN" }) : reply(200, state[st[1]] ?? []); + if (init.method === "PUT" && p.includes("/send/m.room.message/")) return reply(200, { event_id: "$sent1" }); const ev = p.match(/^\/rooms\/([^/]+)\/event\/(.+)$/); if (ev) return known.has(ev[2]) ? reply(200, known.get(ev[2])) : reply(404, { errcode: "M_NOT_FOUND" }); if (p === "/sync") { @@ -52,91 +54,144 @@ function world({ rounds, state = {}, follow = true, rooms = [ALIAS, OTHER_ALIAS] persona: "eureka", homeserver: "http://hs.test", serverName: HS, rooms, token: "tok", fetch: hsFetch, follow, state: { load: async () => null, save: async () => {} }, brake: async () => true, log: () => {}, syncTimeoutMs: 1, now: () => clock, }); - return { mouth, seen, at: t => { clock = t; }, basisOfRound: async () => (await mouth.syncOnce()).map(d => [d.eventId, d.basis]) }; + return { mouth, seen, clock: () => clock, at: t => { clock = t; }, basisOfRound: async () => (await mouth.syncOnce()).map(d => [d.eventId, d.basis]) }; } const run = async (w, n) => { await w.mouth.syncOnce(); const out = []; for (let i = 0; i < n; i++) out.push(await w.basisOfRound()); return out; }; -test("follow: a peer she tagged, untagged and within W of her post, is follow; a stranger and a peer elsewhere are not", async () => { - const w = world({ rounds: [ - { [ROOM]: [msg("$mine", ME, T0, tagKiko)] }, - { [ROOM]: [msg("$kiko", KIKO, T0 + 60 * SEC), msg("$stranger", STRANGER, T0 + 61 * SEC)], [OTHER_ROOM]: [msg("$kikoside", KIKO, T0 + 62 * SEC)] }, - ] }); - const [, second] = await run(w, 2); - assert.deepEqual(second.sort(), [["$kiko", "follow"], ["$kikoside", null], ["$stranger", null]]); -}); +const go = async (w, t) => { w.at(t); return w.basisOfRound(); }; // the process clock moves with the round +const mine = (id, ts, content = {}) => msg(id, ME, ts, content); +const MIN = 60 * SEC; -test("follow: a reply of hers makes the author of the quoted event a peer", async () => { +test("follow: a counted sender is one who spoke in the 10 minutes before her post; 9 minutes counts, 11 does not; one who first speaks after does not", async () => { const w = world({ rounds: [ - { [ROOM]: [msg("$theirs", KIKO, T0 - 5 * SEC)] }, - { [ROOM]: [msg("$mine", ME, T0, { "m.relates_to": { "m.in_reply_to": { event_id: "$theirs" } } })] }, - { [ROOM]: [msg("$next", KIKO, T0 + 30 * SEC)] }, + { [ROOM]: [msg("$old", KIKO, T0 - 11 * MIN), msg("$edge", `@edge:${HS}`, T0 - 10.5 * MIN), msg("$recent", LENA, T0 - 9 * MIN)] }, + { [ROOM]: [mine("$mine", T0)] }, + { [ROOM]: [msg("$k", KIKO, T0 + MIN), msg("$l", LENA, T0 + 2 * MIN), msg("$s", STRANGER, T0 + 3 * MIN), msg("$e", `@edge:${HS}`, T0 + 3 * MIN)] }, ] }); const out = await run(w, 3); - assert.deepEqual(out[2], [["$next", "follow"]]); + assert.deepEqual(out[2].sort(), [["$e", null], ["$k", null], ["$l", "follow"], ["$s", null]]); }); -test("follow: the chain dies when she stops speaking; a follow does not extend W; speaking again re-anchors", async () => { +test("follow: a post's tag and reply target are counted though they never spoke; she herself never is", async () => { const w = world({ rounds: [ - { [ROOM]: [msg("$mine", ME, T0, tagKiko)] }, - { [ROOM]: [msg("$a", KIKO, T0 + 9 * 60 * SEC)] }, // inside W: follow - { [ROOM]: [msg("$b", KIKO, T0 + W + SEC)] }, // after W from her post, though a follow came at 9 min: not follow - { [ROOM]: [msg("$again", ME, T0 + 11 * 60 * SEC, tagKiko)] }, - { [ROOM]: [msg("$c", KIKO, T0 + 20 * 60 * SEC)] }, // inside W of the second post: follow + { [ROOM]: [msg("$theirs", LENA, T0 - 5 * MIN)] }, + { [ROOM]: [mine("$mine", T0, { "m.mentions": { user_ids: [KIKO, ME] }, "m.relates_to": { "m.in_reply_to": { event_id: "$theirs" } } })] }, + { [ROOM]: [msg("$k", KIKO, T0 + MIN), msg("$s", STRANGER, T0 + MIN)] }, ] }); - const out = await run(w, 5); - assert.deepEqual(out.flat(), [["$a", "follow"], ["$b", null], ["$c", "follow"]]); + assert.deepEqual((await run(w, 3))[2], [["$k", "follow"], ["$s", null]]); }); -test("follow: a tag or reply to her keeps its own basis", async () => { + +test("follow: the chain dies when she stops speaking; a follow does not extend W; speaking again re-anchors and re-snapshots", async () => { const w = world({ rounds: [ - { [ROOM]: [msg("$mine", ME, T0, tagKiko)] }, - { [ROOM]: [msg("$t", KIKO, T0 + SEC, { "m.mentions": { user_ids: [ME] } })] }, + { [ROOM]: [msg("$k0", KIKO, T0 - MIN)] }, + { [ROOM]: [mine("$mine", T0)] }, + { [ROOM]: [msg("$a", KIKO, T0 + 9 * MIN)] }, // inside W: follow + { [ROOM]: [msg("$b", KIKO, T0 + 10 * MIN + SEC)] }, // past W from her post though a follow came at 9 min + { [ROOM]: [mine("$again", T0 + 11 * MIN)] }, + { [ROOM]: [msg("$c", KIKO, T0 + 20 * MIN), msg("$d", LENA, T0 + 20 * MIN)] }, ] }); - assert.deepEqual((await run(w, 2))[1], [["$t", "tag"]]); + await w.mouth.syncOnce(); + assert.deepEqual(await go(w, T0 - MIN), [["$k0", null]]); + assert.deepEqual(await go(w, T0), []); + assert.deepEqual(await go(w, T0 + 9 * MIN), [["$a", "follow"]]); + assert.deepEqual(await go(w, T0 + 10 * MIN + SEC), [["$b", null]]); + assert.deepEqual(await go(w, T0 + 11 * MIN), []); + assert.deepEqual(await go(w, T0 + 20 * MIN), [["$c", "follow"], ["$d", null]]); // lena never spoke before the second post either }); -test("follow: a DM, an encrypted room and a bridged room open nothing and receive nothing", async () => { - for (const state of [[{ type: "m.room.encryption", content: {} }], [{ type: "m.bridge", content: {} }], [{ type: "uk.half-shot.bridge", content: {} }]]) { - const w = world({ state: { [ROOM]: state }, rounds: [ - { [ROOM]: [msg("$mine", ME, T0, tagKiko)] }, - { [ROOM]: [msg("$kiko", KIKO, T0 + SEC)] }, - ] }); - assert.deepEqual((await run(w, 2))[1], [["$kiko", null]]); +test("follow: the window needs this process's clock too: a message stamped inside it but read long after is not a follow", async () => { + const w = world({ rounds: [{ [ROOM]: [msg("$k0", KIKO, T0 - MIN)] }, { [ROOM]: [mine("$mine", T0)] }, { [ROOM]: [msg("$forged", KIKO, T0 + MIN)] }] }); + await w.mouth.syncOnce(); + await go(w, T0 - MIN); await go(w, T0); + assert.deepEqual(await go(w, T0 + 30 * MIN), [["$forged", null]]); +}); + +test("follow: her mouth send anchors at send time, and its /sync echo does not anchor again", async () => { + const w = world({ rounds: [ + { [ROOM]: [msg("$k0", KIKO, T0 - MIN)] }, + { [ROOM]: [msg("$sent1", ME, T0 + 8 * MIN, { body: "echo" })] }, + { [ROOM]: [msg("$late", KIKO, T0 + 12 * MIN)] }, + ] }); + await w.mouth.syncOnce(); await w.basisOfRound(); + const sent = await w.mouth.send({ requestId: "r1", persona: "eureka", roomAlias: ALIAS, text: "hello" }); + assert.equal(sent.refusal, null); + w.at(T0 + 8 * MIN); + await w.basisOfRound(); // the echo, 8 minutes on: a second anchor would carry the window to 18 minutes + w.at(T0 + 12 * MIN); + assert.deepEqual(await w.basisOfRound(), [["$late", null]]); +}); + +test("follow: a send from the mouth anchors; a send into a DM or an unreadable room does not", async () => { + const mk = opts => world({ ...opts, rounds: [{ [ROOM]: [msg("$k0", KIKO, T0 - MIN)] }, { [ROOM]: [msg("$k1", KIKO, T0 + MIN)] }] }); + const ok = mk({}); + await ok.mouth.syncOnce(); await ok.basisOfRound(); + await ok.mouth.send({ requestId: "r1", persona: "eureka", roomAlias: ALIAS, text: "hello" }); + assert.deepEqual(await ok.basisOfRound(), [["$k1", "follow"]]); + const dm = mk({ direct: { [KIKO]: [ROOM] } }); + await dm.mouth.syncOnce(); await dm.basisOfRound(); + await dm.mouth.send({ requestId: "r1", persona: "eureka", roomAlias: ROOM, text: "hello" }); + assert.deepEqual(await dm.basisOfRound(), [["$k1", "direct"]]); +}); + +test("follow: a DM, an encrypted room and a bridged room anchor nothing; an unreadable or non-array state is not public", async () => { + const rounds = () => [{ [ROOM]: [msg("$k0", KIKO, T0 - MIN)] }, { [ROOM]: [mine("$mine", T0)] }, { [ROOM]: [msg("$k", KIKO, T0 + MIN)] }]; + for (const state of [[{ type: "m.room.encryption", content: {} }], [{ type: "m.bridge", content: {} }], [{ type: "uk.half-shot.bridge", content: {} }], { not: "an array" }]) { + assert.deepEqual((await run(world({ state: { [ROOM]: state }, rounds: rounds() }), 3))[2], [["$k", null]]); } - const dm = world({ direct: { [KIKO]: [ROOM] }, rounds: [{ [ROOM]: [msg("$mine", ME, T0, tagKiko)] }, { [ROOM]: [msg("$kiko", KIKO, T0 + SEC)] }] }); - assert.deepEqual((await run(dm, 2))[1], [["$kiko", "direct"]]); + assert.deepEqual((await run(world({ stateStatus: { [ROOM]: 500 }, rounds: rounds() }), 3))[2], [["$k", null]]); + assert.deepEqual((await run(world({ direct: { [KIKO]: [ROOM] }, rounds: rounds() }), 3))[2], [["$k", "direct"]]); + // plaintext and unbridged is public, whatever else it is (an invite-only room included): the state holds no join rule the mouth reads + assert.deepEqual((await run(world({ state: { [ROOM]: [{ type: "m.room.join_rules", content: { join_rule: "invite" } }] }, rounds: rounds() }), 3))[2], [["$k", "follow"]]); }); -test("follow: a bridged room, a bridged sender as peer, and a bridged event deliver no follow", async () => { - const w2 = world({ state: { [ROOM]: [{ type: "m.bridge", content: {} }] }, rounds: [{ [ROOM]: [msg("$mine", ME, T0, tagKiko)] }, { [ROOM]: [msg("$kiko", KIKO, T0 + SEC)] }] }); - assert.deepEqual((await run(w2, 2))[1], [["$kiko", null]]); +test("follow: a bridged sender or event is neither counted nor followed", async () => { const puppet = `@_${PLATFORM}_123:${HS}`; - const w3 = world({ rounds: [ - { [ROOM]: [msg("$mine", ME, T0, { "m.mentions": { user_ids: [puppet] } })] }, - { [ROOM]: [msg("$p", puppet, T0 + SEC)] }, - ] }); - assert.deepEqual((await run(w3, 2))[1], [["$p", null]]); - const w4 = world({ rounds: [ - { [ROOM]: [msg("$mine", ME, T0, tagKiko)] }, - { [ROOM]: [msg("$kiko", KIKO, T0 + SEC, { [`${PLATFORM}.relay`]: true })] }, - ] }); - assert.deepEqual((await run(w4, 2))[1], [["$kiko", null]]); + const w = world({ rounds: [{ [ROOM]: [msg("$p0", puppet, T0 - MIN), msg("$k0", KIKO, T0 - MIN)] }, { [ROOM]: [mine("$mine", T0, { "m.mentions": { user_ids: [puppet] } })] }, + { [ROOM]: [msg("$p", puppet, T0 + MIN), msg("$k", KIKO, T0 + MIN, { [`${PLATFORM}.relay`]: true })] }] }); + assert.deepEqual((await run(w, 3))[2].sort(), [["$k", null], ["$p", null]]); }); -test("follow: at most three an hour per peer and room; the fourth keeps its basis; an hour later it is follow again", async () => { - const posts = n => ({ [ROOM]: [msg(`$me${n}`, ME, T0 + n * 5 * 60 * SEC, tagKiko), msg(`$k${n}`, KIKO, T0 + n * 5 * 60 * SEC + SEC)] }); - const w = world({ rounds: [posts(0), posts(1), posts(2), posts(3), { [ROOM]: [msg("$me9", ME, T0 + 70 * 60 * SEC, tagKiko), msg("$k9", KIKO, T0 + 70 * 60 * SEC + SEC)] }] }); - const out = (await run(w, 5)).flat(); - assert.deepEqual(out, [["$k0", "follow"], ["$k1", "follow"], ["$k2", "follow"], ["$k3", null], ["$k9", "follow"]]); +test("follow: at most three an hour per room and peer, counted independently; a half hour does not reset it; an hour later it is follow again", async () => { + const w = world({ rounds: [ + { [ROOM]: [msg("$k0", KIKO, T0 - SEC), msg("$l0", LENA, T0 - SEC)], [OTHER_ROOM]: [msg("$ko0", KIKO, T0 - SEC)] }, + { [ROOM]: [mine("$m1", T0 + MIN)], [OTHER_ROOM]: [msg("$mo1", ME, T0 + MIN)] }, + { [ROOM]: [msg("$k1", KIKO, T0 + MIN + SEC)], [OTHER_ROOM]: [msg("$ko1", KIKO, T0 + MIN + SEC)] }, + { [ROOM]: [mine("$m2", T0 + 2 * MIN)] }, { [ROOM]: [msg("$k2", KIKO, T0 + 2 * MIN + SEC)] }, + { [ROOM]: [mine("$m3", T0 + 3 * MIN)] }, { [ROOM]: [msg("$k3", KIKO, T0 + 3 * MIN + SEC)] }, + { [ROOM]: [mine("$m4", T0 + 4 * MIN)] }, { [ROOM]: [msg("$k4", KIKO, T0 + 4 * MIN + SEC), msg("$l4", LENA, T0 + 4 * MIN + SEC)] }, + { [ROOM]: [msg("$k30", KIKO, T0 + 30 * MIN), mine("$m31", T0 + 31 * MIN)] }, { [ROOM]: [msg("$k31", KIKO, T0 + 31 * MIN + SEC)] }, + { [ROOM]: [msg("$k60", KIKO, T0 + 61 * MIN), mine("$m62", T0 + 62 * MIN)] }, { [ROOM]: [msg("$k62", KIKO, T0 + 62 * MIN + SEC)] }, + ] }); + await w.mouth.syncOnce(); + const seen = []; + const steps = [0, 1, 1, 2, 2, 3, 3, 4, 4, 31, 31, 62, 62]; + for (const m of steps) seen.push(...await go(w, T0 + m * MIN + 2 * SEC)); + const got = Object.fromEntries(seen.filter(([id]) => /^\$(k|ko|l)\d/.test(id)).map(([id, b]) => [id, b])); + assert.deepEqual(got, { $k0: null, $l0: null, $ko0: null, $k1: "follow", $ko1: "follow", $k2: "follow", $k3: "follow", $k4: null, $l4: "follow", $k30: null, $k31: null, $k60: null, $k62: "follow" }); +}); + +test("follow: an edit and a notice are never follow; a room-basis message from a counted sender is; a tag keeps its own basis", async () => { + const w = world({ rounds: [ + { [ROOM]: [msg("$k0", KIKO, T0 - MIN)] }, + { [ROOM]: [mine("$mine", T0)] }, + { [ROOM]: [ + msg("$edit", KIKO, T0 + SEC, { "m.new_content": { msgtype: "m.text", body: "x" }, "m.relates_to": { rel_type: "m.replace", event_id: "$k0" } }), + msg("$notice", KIKO, T0 + SEC, { msgtype: "m.notice" }), + msg("$room", KIKO, T0 + SEC, { "m.mentions": { room: true } }), + msg("$tag", KIKO, T0 + SEC, { "m.mentions": { user_ids: [ME] } }), + ] }, + ] }); + assert.deepEqual((await run(w, 3))[2].sort(), [["$edit", null], ["$notice", null], ["$room", "follow"], ["$tag", "tag"]]); }); test("follow: flag off emits nothing new and reads nothing extra; a fresh mouth has no engagement", async () => { - const rounds = [{ [ROOM]: [msg("$mine", ME, T0, tagKiko)] }, { [ROOM]: [msg("$kiko", KIKO, T0 + SEC)] }]; + const rounds = [{ [ROOM]: [msg("$k0", KIKO, T0 - MIN)] }, { [ROOM]: [mine("$mine", T0)] }, { [ROOM]: [msg("$k", KIKO, T0 + MIN)] }]; const off = world({ follow: false, rounds }); - assert.deepEqual((await run(off, 2))[1], [["$kiko", null]]); + assert.deepEqual((await run(off, 3))[2], [["$k", null]]); assert.ok(!off.seen.some(l => l.endsWith("/state")), "off: no state read"); - const restarted = world({ rounds: [{ [ROOM]: [msg("$kiko", KIKO, T0 + SEC)] }] }); - assert.deepEqual((await run(restarted, 1))[0], [["$kiko", null]]); + const restarted = world({ rounds: [{ [ROOM]: [msg("$k", KIKO, T0 + MIN)] }] }); + assert.deepEqual((await run(restarted, 1))[0], [["$k", null]]); assert.equal(followFromEnv({ CHAT_FOLLOW: "1" }), true); for (const v of [undefined, "0", "true", "yes", ""]) assert.equal(followFromEnv({ CHAT_FOLLOW: v }), false); }); diff --git a/tools/persona-matrix-mouth.mjs b/tools/persona-matrix-mouth.mjs index 647e4e8..67346bc 100644 --- a/tools/persona-matrix-mouth.mjs +++ b/tools/persona-matrix-mouth.mjs @@ -23,9 +23,10 @@ // reads the room's head from Matrix and answers RoomMoved, naming the messages that moved it, instead // of the PUT. A v1 send, and a v2 send with no basis, are not checked; both still pass through the gate. // -// Follow (CHAT_FOLLOW=1, default off; docs/bridge.md "Follow"): her own post that tags or replies to someone opens a 10 minute engagement -// with that peer in that public room; the peer's next untagged messages inside it carry basis "follow", at most 3 an hour per peer and room. -// Memory only. Off, no basis "follow" is ever emitted: Huginn's parser refuses it until its Basis::Follow lands. +// Follow (CHAT_FOLLOW=1, default off; docs/bridge.md "Follow"): her own send in a public room (not a DM, not encrypted, not bridged) anchors the room +// for 10 minutes; those who spoke there in the 10 minutes before it, and whoever it tagged or replied to, get basis "follow" on their later messages +// inside the window, at most 3 an hour per peer and room. Memory only. Off, no basis "follow" is ever emitted: Huginn's parser refuses it until its +// Basis::Follow lands. // // Media: an m.image/m.file/m.audio/m.video event is delivered as one typed line (see bodyText), not its bare filename. // An m.image event in a delivered message is also fetched, as this Persona and only when an image store is configured @@ -75,6 +76,9 @@ const PLATFORM = ["disc", "ord"].join(""); // the bridged platform's name, as Hu const FOLLOW_WINDOW_MS = 10 * 60 * 1000; // W: an engagement lasts this long from the Mind's own post; a follow never extends it const FOLLOW_PER_HOUR = 3; // K: follow bases given per (Mind, peer, room) in an hour; past it the message keeps the basis it had const FOLLOW_ROOM_TTL_MS = 5 * 60 * 1000; // how long a room's public verdict (not encrypted, not bridged) is kept +const FOLLOW_SLACK_MS = 60 * 1000; // clock disagreement tolerated between this process and the homeserver +const FOLLOW_HOUR_MS = 60 * 60 * 1000; +const FOLLOW_RING = 200; // recent senders kept per room const HEAD_PAGE = 50; // the room head a gated send reads; also the most ids a RoomMoved receipt names // The kind of an event for a delivery: an edit (m.replace) and an automated notice (m.notice) are not messages anyone is addressed by. @@ -311,14 +315,19 @@ export function createMouth({ return lines; } - // Follow (docs/bridge.md, "Follow"). Memory only: room id -> peer id -> the time her engagement with that peer ends, and room id|peer id -> - // the times follows were given. A restart empties both, which only shortens windows. Opened by her own post (seen in /sync, so a post from - // any client of her account counts) that tags or replies to a peer; never by a follow delivery; never in a DM, an encrypted room or a bridged room. + // Follow (docs/bridge.md, "Follow"). Memory only, bounded, purged on every sync pass. Her own send in a public room (not a DM, not encrypted, not + // bridged) anchors that room for W from the send: `engagements` room id -> { from, ends, counted }, counted being the senders who spoke there in the + // W before the send (`spoke`, a per-room ring of recent senders with event times) plus whoever the post tagged or replied to, if the event says so. + // Someone who first speaks after the send is not counted. Only her speaking again re-anchors (and re-snapshots); a follow never extends the window. + // `followsGiven` room|peer -> times follows were given. A restart empties all of it, which only shortens windows. const engagements = new Map(); + const spoke = new Map(); const followsGiven = new Map(); + const anchored = new Set(); // event ids of her own posts already anchored: the send path and its /sync echo anchor once const publicRooms = new Map(); // room id -> { ok, at } const platformId = id => platformEvent({ sender: id }); async function publicRoom(roomId) { + if (directRooms.has(roomId)) return false; const known = publicRooms.get(roomId); if (known && now() - known.at < FOLLOW_ROOM_TTL_MS) return known.ok; try { @@ -333,32 +342,53 @@ export function createMouth({ } } const eventAt = event => Number.isSafeInteger(event.origin_server_ts) && event.origin_server_ts >= 0 ? event.origin_server_ts : now(); - // Her own post: whoever it tags (m.mentions) or replies to becomes a peer for W from this post, re-anchoring one she already had. - async function noteOwnPost(roomId, event) { - if (!follow || directRooms.has(roomId) || formOf(event.content) !== "message" || platformEvent(event)) return; - const peers = new Set(Array.isArray(event.content["m.mentions"]?.user_ids) ? event.content["m.mentions"].user_ids : []); - const relates = event.content["m.relates_to"]; - const replied = relates?.["m.in_reply_to"]?.event_id; - if (typeof replied === "string" && replied !== "" && relates.is_falling_back !== true) { - const author = await authorOf(roomId, replied); - if (author !== null) peers.add(author); + function purgeFollow() { + const t = now(); + for (const [room, e] of engagements) if (e.ends + FOLLOW_SLACK_MS <= t) engagements.delete(room); + for (const [room, ring] of spoke) { + const kept = ring.filter(r => r.at > t - FOLLOW_WINDOW_MS - FOLLOW_SLACK_MS); + if (kept.length === 0) spoke.delete(room); else spoke.set(room, kept); } - const ends = eventAt(event) + FOLLOW_WINDOW_MS; - const ids = [...peers].filter(id => docs.isMatrixId("@", id) && id !== selfId && !platformId(id)).slice(0, docs.limits.mentions); - if (ids.length === 0 || ends <= now() || !(await publicRoom(roomId))) return; - const room = engagements.get(roomId) ?? new Map(); - for (const [id, until] of room) if (until <= now()) room.delete(id); - for (const id of ids) room.set(id, ends); - engagements.set(roomId, room); + for (const [key, times] of followsGiven) { + const kept = times.filter(x => t - x < FOLLOW_HOUR_MS + FOLLOW_SLACK_MS); + if (kept.length === 0) followsGiven.delete(key); else followsGiven.set(key, kept); + } + } + // Someone spoke in the room (a message from another account, not an edit or a notice): the ring behind the snapshot. + function noteSpeaker(roomId, event) { + if (!follow || directRooms.has(roomId) || formOf(event.content) !== "message" || platformEvent(event) || event.sender === selfId) return; + const ring = spoke.get(roomId) ?? []; + ring.push({ sender: event.sender, at: eventAt(event) }); + if (ring.length > FOLLOW_RING) ring.shift(); + spoke.set(roomId, ring); + } + // Her post at time `at` (the send's own time, or the echo's origin time): snapshot the room. `tagged`: ids from the event's m.mentions, `replyTo` the quoted event id. + async function anchor(roomId, eventId, at, tagged = [], replyTo = null) { + if (!follow || anchored.has(eventId) || !(await publicRoom(roomId))) return; + anchored.add(eventId); + if (anchored.size > 200) anchored.delete(anchored.values().next().value); + const counted = new Set((spoke.get(roomId) ?? []).filter(r => r.at >= at - FOLLOW_WINDOW_MS && r.at <= at).map(r => r.sender)); + for (const id of tagged) counted.add(id); + if (typeof replyTo === "string" && replyTo !== "") { const author = await authorOf(roomId, replyTo); if (author !== null) counted.add(author); } + for (const id of [...counted]) if (!docs.isMatrixId("@", id) || id === selfId || platformId(id)) counted.delete(id); + engagements.set(roomId, { from: at, ends: at + FOLLOW_WINDOW_MS, counted }); + } + // Her own event seen in /sync (a send from another client, or the echo of a mouth send, which is then not anchored twice). + async function noteOwnPost(roomId, event) { + if (!follow || formOf(event.content) !== "message" || platformEvent(event)) return; + const relates = event.content["m.relates_to"]; + const tagged = Array.isArray(event.content["m.mentions"]?.user_ids) ? event.content["m.mentions"].user_ids : []; + await anchor(roomId, event.event_id, eventAt(event), tagged.slice(0, docs.limits.mentions), relates?.is_falling_back === true ? null : relates?.["m.in_reply_to"]?.event_id); } // Whether this message is a follow, and if so spends one of the peer's K for the hour. Called only for a message that has no better basis. async function followed(roomId, event) { if (!follow || directRooms.has(roomId) || formOf(event.content) !== "message" || platformEvent(event)) return false; - const at = eventAt(event); - if (!((engagements.get(roomId)?.get(event.sender) ?? 0) > at)) return false; + const e = engagements.get(roomId), at = eventAt(event), t = now(); + // Both clocks must agree: the message's own time inside the window, and this process's time not past it (a forged or old timestamp reuses nothing). + if (!e || !e.counted.has(event.sender) || at < e.from || at >= e.ends || t >= e.ends + FOLLOW_SLACK_MS) return false; if (!(await publicRoom(roomId))) return false; const key = `${roomId}|${event.sender}`; - const recent = (followsGiven.get(key) ?? []).filter(t => at - t < 60 * 60 * 1000); + const recent = (followsGiven.get(key) ?? []).filter(x => at - x < FOLLOW_HOUR_MS); if (recent.length >= FOLLOW_PER_HOUR) { followsGiven.set(key, recent); return false; } followsGiven.set(key, [...recent, at]); return true; @@ -501,6 +531,7 @@ export function createMouth({ // One /sync round. Returns the deliveries it made. async function syncOnce() { if (!started || unjoined()) await start(); + purgeFollow(); replyReads = 0; held.clear(); const free = await released(); // the round's brake read for presence, taken before any early return @@ -535,7 +566,8 @@ export function createMouth({ const deliverable = !baseline && !freshRooms.has(roomId) && event.sender !== selfId; if (deliverable && pending.length + made.length >= maxPending) { truncated = true; break rounds; } if (deliverable && replyLink && replyReads + targetsToRead(roomId, event) > REPLY_READS_PER_ROUND) { say(`event ${event.event_id} not read: round cap on target reads, the rest of the round waits for the next`); truncated = true; break rounds; } // not processed: the next round meets it again, with its read count reset - if (!baseline && !freshRooms.has(roomId) && event.sender === selfId && event.type === "m.room.message") await noteOwnPost(roomId, event); + if (!baseline && !freshRooms.has(roomId) && event.sender === selfId) await noteOwnPost(roomId, event); + noteSpeaker(roomId, event); let basis = deliverable ? await basisOf(roomId, event) : null; if (deliverable && (basis === null || basis === "room") && await followed(roomId, event)) basis = "follow"; const replyTo = deliverable ? await replyToOf(roomId, event) : null; @@ -710,7 +742,7 @@ export function createMouth({ const sent = await matrix("PUT", `/rooms/${encodeURIComponent(roomId)}/send/m.room.message/${encodeURIComponent(requestId)}`, { msgtype: "m.text", body: text }, API, AbortSignal.timeout(sendTimeoutMs)); return { requestId, eventId: sent.event_id, refusal: null, newer: [] }; }); - if (result.refusal === null) { touch(); setPresence(true).catch(() => {}); } // outside the room gate and not awaited: a slow presence write holds neither another send nor this receipt + if (result.refusal === null) { touch(); setPresence(true).catch(() => {}); await anchor(roomId, result.eventId, now()).catch(error => say(`follow: send not anchored: ${error.message}`)); } // outside the room gate and not awaited: a slow presence write holds neither another send nor this receipt return result; } catch (error) { say(`send failed: ${error.message}`);