diff --git a/docs/bridge.md b/docs/bridge.md index d66f9a5..1dc7df6 100644 --- a/docs/bridge.md +++ b/docs/bridge.md @@ -206,7 +206,7 @@ A client asks for the facts by the kind it polls with: `gamecult.persona.chat_pe | Field | Type | Meaning | |---|---|---| -| 12 `basis` | `"direct"`, `"tag"`, `"reply"`, `"room"` or nil | Why the message is for this Persona, by what Matrix says, first that holds: `direct` the room is one of her DMs; `tag` `m.mentions.user_ids` lists her id, or the client sent no `m.mentions` at all and an `` in the HTML body is exactly her `matrix.to` link; `reply` it replies to, or is in a thread under, an event her account wrote (her Self run speaks as her account, so its words count; any member's message in a thread under one of her events is a `reply` too, and the target is read once per room and event and kept for a minute, hit or failure); `room` an `@room` mention. A `notice` or an `edit` costs no reply lookup. Known limit: lookups run one at a time inside the `/sync` round (10 s each, at most two per reply), so a slow homeserver slows the round; they are not parallelised or capped per round. | +| 12 `basis` | `"direct"`, `"tag"`, `"reply"`, `"room"`, `"follow"` (only with `CHAT_FOLLOW=1`, see Follow) or nil | Why the message is for this Persona, by what Matrix says, first that holds: `direct` the room is one of her DMs; `tag` `m.mentions.user_ids` lists her id, or the client sent no `m.mentions` at all and an `` in the HTML body is exactly her `matrix.to` link; `reply` it replies to, or is in a thread under, an event her account wrote (her Self run speaks as her account, so its words count; any member's message in a thread under one of her events is a `reply` too, and the target is read once per room and event and kept for a minute, hit or failure); `room` an `@room` mention. A `notice` or an `edit` costs no reply lookup. Known limit: lookups run one at a time inside the `/sync` round (10 s each, at most two per reply), so a slow homeserver slows the round; they are not parallelised or capped per round. | | 13 `form` | `"message"`, `"notice"` or `"edit"` | `m.notice` is an automated line; `m.replace` is an edit of an earlier message. Only a `message` can address anyone. | What the mouth cannot know, and so what a nil `basis` means: **unproven, not "not for her"**. Her handle and public name in the text (any casing, with or without `@`, `'s`), the names her stewardships list, a project's repo name, and whether the sender is the operator or a Mind are all matched by Huginn, not here. A reply whose target the homeserver will not give is nil and logged. The mouth also cannot see whether a message was meant for her without naming her. Every delivery is still delivered, claimed tags included: nothing is dropped in the mouth, so the Huginn rule cannot lose a message the mouth had no way to judge. @@ -253,6 +253,19 @@ A line a delivery already shows and a room she cannot speak in change nothing he Golden bytes: `tests/fixtures/persona-chat-v5/` (`chat_pending.v3.tail` carries two lines and no gap, `chat_pending.v3.tail-gaps` one line and two gap rooms; the earlier v3 samples gain an empty fourth element); Huginn pins the same bytes. +### 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. + +With it on, the mouth gives a `message` the basis `follow` when it would otherwise have none or `room`, and: + +- 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. + +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). + ### Reply link (`chat_pending.v4`) A reply to anyone but the Persona arrives bare in v3: `basis` is `reply` only when the quoted author is her account. v4 adds what the message quotes. **It is off unless the mouth runs with `CHAT_PENDING_V4=1`** (exactly `1`; default off), because Huginn pins the tuple bytes and must read v4 first. With the flag off, `gamecult.persona.chat_pending_request.v3` is not a served kind: it is refused as any unknown kind is (`chat_refusal` `UnknownKind`, logged), byte for byte, and v1/v2/v3 requests are answered as before. With it on, that request kind (the v1 tuple `[persona, after_seq]` again; the kind asked by names the answer) is answered with `gamecult.persona.chat_pending.v4`. diff --git a/tests/persona-matrix-mouth-follow.test.mjs b/tests/persona-matrix-mouth-follow.test.mjs new file mode 100644 index 0000000..a541c5e --- /dev/null +++ b/tests/persona-matrix-mouth-follow.test.mjs @@ -0,0 +1,148 @@ +// 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: +// 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"; +import { createMouth, followFromEnv } from "../tools/persona-matrix-mouth.mjs"; +import * as docs from "../tools/persona-chat-documents.mjs"; + +const HS = "gamecult.test"; +const ALIAS = `#swarm:${HS}`; +const ROOM = "!swarm:gamecult.test"; +const OTHER_ALIAS = `#side:${HS}`; +const OTHER_ROOM = "!side:gamecult.test"; +const ME = `@eureka:${HS}`; +const KIKO = `@kiko:${HS}`; +const STRANGER = `@stranger:${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 } = {}) { + const seen = []; + const known = new Map(); + let round = 0; + const reply = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } }); + const hsFetch = async (url, init = {}) => { + const u = new URL(url); + const p = decodeURIComponent(u.pathname).replace(/^\/_matrix\/client\/v[13]/, ""); + seen.push(`${init.method ?? "GET"} ${p}`); + if (p === "/account/whoami") return reply(200, { user_id: ME }); + if (p === "/joined_rooms") return reply(200, { joined_rooms: [ROOM, OTHER_ROOM] }); + if (p.includes("/account_data/m.direct")) return direct ? reply(200, direct) : reply(404, { errcode: "M_NOT_FOUND" }); + 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]] ?? []); + 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") { + if (u.searchParams.get("since") === null) return reply(200, { next_batch: "b0" }); + const events = rounds[round++] ?? {}; + for (const list of Object.values(events)) for (const e of list) known.set(e.event_id, e); + return reply(200, { next_batch: `b${round}`, rooms: { join: Object.fromEntries(Object.entries(events).map(([r, list]) => [r, { timeline: { events: list } }])) } }); + } + if (p.includes("/messages")) return reply(200, { chunk: [] }); + return reply(404, { errcode: "M_NOT_FOUND" }); + }; + let clock = T0; + const mouth = createMouth({ + 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]) }; +} +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]]); +}); + +test("follow: a reply of hers makes the author of the quoted event a peer", 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)] }, + ] }); + const out = await run(w, 3); + assert.deepEqual(out[2], [["$next", "follow"]]); +}); + +test("follow: the chain dies when she stops speaking; a follow does not extend W; speaking again re-anchors", 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 + ] }); + const out = await run(w, 5); + assert.deepEqual(out.flat(), [["$a", "follow"], ["$b", null], ["$c", "follow"]]); +}); + +test("follow: a tag or reply to her keeps its own basis", async () => { + const w = world({ rounds: [ + { [ROOM]: [msg("$mine", ME, T0, tagKiko)] }, + { [ROOM]: [msg("$t", KIKO, T0 + SEC, { "m.mentions": { user_ids: [ME] } })] }, + ] }); + assert.deepEqual((await run(w, 2))[1], [["$t", "tag"]]); +}); + +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]]); + } + 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"]]); +}); + +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]]); + 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]]); +}); + +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: 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 off = world({ follow: false, rounds }); + assert.deepEqual((await run(off, 2))[1], [["$kiko", 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]]); + assert.equal(followFromEnv({ CHAT_FOLLOW: "1" }), true); + for (const v of [undefined, "0", "true", "yes", ""]) assert.equal(followFromEnv({ CHAT_FOLLOW: v }), false); +}); + +test("follow: the basis is a name the delivery document accepts", () => { + assert.ok(docs.bases.includes("follow")); + const d = { seq: 1, roomAlias: ALIAS, roomId: ROOM, eventId: "$e", sender: KIKO, senderDisplay: "kiko", text: "x", atUnixMs: 1, context: [], image: null, mentions: [], isDirect: false, basis: "follow", form: "message" }; + assert.equal(docs.parseDeliveryV3(docs.deliveryV3Tuple(d)).basis, "follow"); +}); diff --git a/tools/persona-chat-documents.mjs b/tools/persona-chat-documents.mjs index 059e595..afdc7f3 100644 --- a/tools/persona-chat-documents.mjs +++ b/tools/persona-chat-documents.mjs @@ -68,8 +68,8 @@ export function parsePendingRequest(t) { // What the mouth can establish about a delivery from Matrix alone, for the Persona it is delivered to (see docs/bridge.md, "Addressing facts"). // `basis` is why the message is for her, or null when the mouth has no proof (not that it is not for her: her names, her projects' names and -// the sender's role are not the mouth's to know). `form` is the event's kind: only a "message" can address anyone. -export const bases = Object.freeze(["direct", "tag", "reply", "room"]); +// the sender's role are not the mouth's to know). "follow" is emitted only under the mouth's CHAT_FOLLOW flag. `form` is the event's kind: only a "message" can address anyone. +export const bases = Object.freeze(["direct", "tag", "reply", "room", "follow"]); export const forms = Object.freeze(["message", "notice", "edit"]); export function ackTuple({ persona, throughSeq }) { diff --git a/tools/persona-matrix-mouth.mjs b/tools/persona-matrix-mouth.mjs index 10af28a..647e4e8 100644 --- a/tools/persona-matrix-mouth.mjs +++ b/tools/persona-matrix-mouth.mjs @@ -6,7 +6,7 @@ // its m.mentions user ids and whether the room is a DM. The /sync position // (next_batch) is persisted only when an ack covers it, so a restart before the // ack re-delivers instead of losing. A v3 delivery also carries what Matrix proves about why it is for her (basis: direct, tag, -// reply, room; form: message, notice, edit); names and roles are the heartbeat's to match, not the mouth's (docs/bridge.md, +// reply, room, and with CHAT_FOLLOW=1 follow; form: message, notice, edit); names and roles are the heartbeat's to match, not the mouth's (docs/bridge.md, // "Addressing facts"). Reading wakes nothing: the heartbeat polls // with a non-consuming chat_pending_request and decides who runs. An ack posts nothing to Matrix. Her public // m.read receipt follows a chat_read document from Huginn, sent when a delivery has gone into the model's @@ -23,6 +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. +// // 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 // (persona-chat-images.mjs): the delivery then carries a reference to the stored file, or the line says why not. @@ -68,6 +72,9 @@ const FETCH_DEADLINE_MS = 15000; // one fetch, whole: it ends before Huginn's 20 const FETCH_PER_HOUR = 30; // fetches one Persona may ask in an hour const RELATION_PAGES = 3; // pages of a receipt target's relations read before the answer is called unproven const PLATFORM = ["disc", "ord"].join(""); // the bridged platform's name, as Huginn's room_scope spells it: never written out whole +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 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. @@ -126,6 +133,7 @@ export function createMouth({ persona, homeserver, serverName, rooms, token, fetch: httpFetch = globalThis.fetch, state, brake, now = Date.now, log = () => {}, syncTimeoutMs = 30000, maxPending = MAX_PENDING, gate = createRoomGate(), sendTimeoutMs = SEND_TIMEOUT_MS, presenceGraceMs = PRESENCE_GRACE_MS, fetchDeadlineMs = FETCH_DEADLINE_MS, + follow = false, // the follow basis (CHAT_FOLLOW): an untagged message from someone she tagged or replied to, within FOLLOW_WINDOW_MS of her own post, is for her replyLink = false, // resolve each reply's quoted event into delivery.replyTo (the v4 answer; one more event read per reply to a non-Mind) images = null, // this Persona's image store (createImageStore), or null: images stay the typed text line isServed = async () => false, // (async) whether a Matrix user id is an account this process speaks for: a Mind is not a person to open a DM with @@ -303,6 +311,59 @@ 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. + const engagements = new Map(); + const followsGiven = new Map(); + const publicRooms = new Map(); // room id -> { ok, at } + const platformId = id => platformEvent({ sender: id }); + async function publicRoom(roomId) { + const known = publicRooms.get(roomId); + if (known && now() - known.at < FOLLOW_ROOM_TTL_MS) return known.ok; + try { + const state = await matrix("GET", `/rooms/${encodeURIComponent(roomId)}/state`, undefined, API, AbortSignal.timeout(sendTimeoutMs)); + if (!Array.isArray(state)) return false; + const ok = !state.some(e => e?.type === "m.room.encryption" || e?.type === "m.bridge" || e?.type === "uk.half-shot.bridge"); + publicRooms.set(roomId, { ok, at: now() }); + return ok; + } catch (error) { + say(`follow: room ${roomId} state not read: ${error.message}`); + return false; // unknown is not public + } + } + 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); + } + 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); + } + // 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; + if (!(await publicRoom(roomId))) return false; + const key = `${roomId}|${event.sender}`; + const recent = (followsGiven.get(key) ?? []).filter(t => at - t < 60 * 60 * 1000); + if (recent.length >= FOLLOW_PER_HOUR) { followsGiven.set(key, recent); return false; } + followsGiven.set(key, [...recent, at]); + return true; + } + // Why a delivered event is for this Persona, from what Matrix says and nothing else: "direct" (a DM), "tag" (m.mentions lists her // id, or, from a client that sends no m.mentions at all, the body links her matrix.to pill), "reply" (it replies to, or sits in a // thread under, an event her account wrote, so her Self run's words count as hers), "room" (an @room mention). In that order; null @@ -474,7 +535,9 @@ 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 - const basis = deliverable ? await basisOf(roomId, event) : null; + if (!baseline && !freshRooms.has(roomId) && event.sender === selfId && event.type === "m.room.message") await noteOwnPost(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; processed.add(event.event_id); if (deliverable) { @@ -1074,6 +1137,8 @@ export function loadRuntime(cultRoot) { export const replyLinkFromEnv = env => env.CHAT_PENDING_V4 === "1"; // The fetch flag, the same way: on only for exactly "1". Off, the fetch request kind is an unknown kind. export const fetchFromEnv = env => env.CHAT_FETCH === "1"; +// The follow flag, the same way. Off, the mouth never emits basis "follow" (Huginn's parser refuses an unknown basis until its Basis::Follow lands). +export const followFromEnv = env => env.CHAT_FOLLOW === "1"; function required(env, name) { if (!env[name]) throw new Error(`${name} is required`); @@ -1127,7 +1192,7 @@ export async function main(env = process.env) { const mouths = new Map(personas.map(persona => { mkdirSync(join(stateRoot, persona), { recursive: true }); return [persona, createMouth({ - persona, homeserver, serverName, rooms: roomsByPersona.get(persona), token: tokens.get(persona), gate, replyLink, isServed: async id => { await Promise.all([...mouths.values()].map(m => m.start().catch(() => {}))); return [...mouths.values()].some(m => m.userId === id); }, log: line => log(`${persona}: ${line}`), + persona, homeserver, serverName, rooms: roomsByPersona.get(persona), token: tokens.get(persona), gate, replyLink, follow: followFromEnv(env), isServed: async id => { await Promise.all([...mouths.values()].map(m => m.start().catch(() => {}))); return [...mouths.values()].some(m => m.userId === id); }, log: line => log(`${persona}: ${line}`), images: imageRoot ? createImageStore({ root: join(imageRoot, persona), log: line => log(`${persona}: ${line}`) }) : null, state: cultcacheState({ runtime, path: join(stateRoot, persona, "cursor.cc") }), brake: createBrakeReader({ controlPath: join(controlRoot, persona, "control.cc"), readStore: runtime.readSingleFileStore, decode: runtime.msgpack.decode }),