@estiva-app/conversation 0.24.0 → 0.26.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,185 @@
1
+ /**
2
+ * A list row's dot — SPEC §11.8 over a stream's messages, for a reader that
3
+ * holds only who said what and when, never the bodies.
4
+ *
5
+ * Moved here from Peek (SHIPS-2) so Peek's Topics and Ship's Topics judge a
6
+ * topic's dot by one rule: which files the viewer is a member of, read from
7
+ * the relay and folded ({@link membershipQueries}, {@link foldMemberships}),
8
+ * the terms that fold gives a stream ({@link streamTermsOf}), and whether any
9
+ * of the stream's messages is unread on them ({@link streamHasUnread}).
10
+ *
11
+ * The read state and the muted list are encrypted (NIP-44), so nothing here
12
+ * reads them: the app hands in the merged markers and the muted set it holds.
13
+ */
14
+ import { encodeNpub, type SignedEvent } from '@estiva-app/protocol'
15
+ import { candidateFilesOf, membershipFilters, membershipOf, mentions, type Membership } from './membership.js'
16
+ import { READ_STATE_HORIZON_DAYS, fileContext } from './readState.js'
17
+ import { isUnread } from './unread.js'
18
+
19
+ /** What a list holds of a message: no body. `root` is the thread root's id, the message's own when it is one. */
20
+ export interface StreamMessage {
21
+ id: string
22
+ /** Unix seconds. */
23
+ at: number
24
+ /** Author pubkey. */
25
+ by: string
26
+ root: string
27
+ }
28
+
29
+ /** What a stream is judged against besides its messages. */
30
+ export interface StreamFrontier {
31
+ /** The merged read state: context → unix seconds. */
32
+ merged: Readonly<Record<string, number>>
33
+ /** The viewer's pubkey; their own messages do not count. */
34
+ me: string | undefined
35
+ /** Now, unix seconds. */
36
+ nowSeconds: number
37
+ horizonSeconds: number
38
+ }
39
+
40
+ /** The terms a stream is told about on: SPEC §11.8's membership, join time and mute. */
41
+ export interface StreamTerms {
42
+ member: boolean
43
+ since?: number
44
+ muted: boolean
45
+ }
46
+
47
+ /**
48
+ * Is anything in this stream unread for the viewer — SPEC §11.8's four
49
+ * conditions over §11.3's markers, judged by {@link isUnread}.
50
+ *
51
+ * `context` is the stream's read-state context (§11.1): `fileContext(address)`
52
+ * for a file, `channelContext(uuid)` for a Folder's general stream. A message is
53
+ * judged against its thread's marker as well as the stream's (§11.3).
54
+ *
55
+ * The messages carry no body, so whether one *names the viewer* comes from
56
+ * `isMentioned` (the ids the membership read's `#p` filter returned) and is
57
+ * handed to the judge as the body it would have had. Without a marker, a file
58
+ * member is told from the second they joined; a Folder's own chat has no
59
+ * members here and lights only for a message that names the viewer, so
60
+ * absence there is the horizon (§11.6).
61
+ */
62
+ export function streamHasUnread(
63
+ messages: readonly StreamMessage[],
64
+ context: string,
65
+ terms: StreamTerms,
66
+ frontier: StreamFrontier,
67
+ isMentioned: (messageId: string) => boolean,
68
+ ): boolean {
69
+ const { me } = frontier
70
+ if (!me) return false
71
+ // Only for a message that names the viewer, so a viewer without a hex key judges the rest.
72
+ const named = () => `nostr:${encodeNpub(me)}`
73
+ const judge = {
74
+ stream: context,
75
+ me,
76
+ member: terms.member,
77
+ since: terms.since,
78
+ muted: terms.muted,
79
+ floor: frontier.nowSeconds - frontier.horizonSeconds,
80
+ }
81
+ for (const message of messages) {
82
+ const root = message.root === message.id ? undefined : message.root
83
+ const unread = isUnread(
84
+ { id: message.id, pubkey: message.by, kind: 1111, created_at: message.at, tags: [], content: isMentioned(message.id) ? named() : '' },
85
+ root,
86
+ frontier.merged,
87
+ judge,
88
+ )
89
+ if (unread) return true
90
+ }
91
+ return false
92
+ }
93
+
94
+ /** Per filter. Measured on production as the agent, the most-named identity there: 700 events in 90 days. */
95
+ export const MEMBERSHIP_LIMIT = 1000
96
+
97
+ /** The read horizon, in seconds: nothing before it can light a dot. */
98
+ export const HORIZON_SECONDS = READ_STATE_HORIZON_DAYS * 24 * 60 * 60
99
+
100
+ /** The three filters that find every file the viewer may be a member of (§11.8), bounded by the horizon. */
101
+ export function membershipQueries(pubkey: string, nowSeconds: number, limit = MEMBERSHIP_LIMIT): Record<string, unknown>[] {
102
+ return membershipFilters(pubkey, nowSeconds - HORIZON_SECONDS).map((filter) => ({ ...filter, limit }))
103
+ }
104
+
105
+ /** What the relay says the viewer is a member of, within the horizon. */
106
+ export interface MembershipRead {
107
+ /** Every candidate file, folded: the ones the viewer is in and the ones they left. */
108
+ files: ReadonlyMap<string, Membership>
109
+ /** Ids of the messages whose content names the viewer. */
110
+ mentioned: ReadonlySet<string>
111
+ /** Unix seconds a created file's membership starts at — the horizon's start. */
112
+ floor: number
113
+ }
114
+
115
+ /** The address's author, or undefined when it is not a file address. */
116
+ export function authorOfAddress(address: string): string | undefined {
117
+ if (fileContext(address) === undefined) return undefined
118
+ return address.split(':')[1]
119
+ }
120
+
121
+ /**
122
+ * Fold what {@link membershipQueries} returned. Pure: the clock is `nowSeconds`.
123
+ *
124
+ * A file's address names its author, so a file the viewer created needs no
125
+ * query: a candidate whose address is theirs is folded with its root added,
126
+ * dated to the horizon's start — the earliest the viewer could be told about —
127
+ * and a leave of theirs among the changes still takes them off. Membership the
128
+ * horizon hides lapses for this reader and comes back with the next event
129
+ * naming the viewer (§11.8 *The fold*).
130
+ */
131
+ export function foldMemberships(pubkey: string, events: readonly SignedEvent[], nowSeconds: number): MembershipRead {
132
+ const floor = nowSeconds - HORIZON_SECONDS
133
+ const byFile = new Map<string, SignedEvent[]>()
134
+ const mentioned = new Set<string>()
135
+ for (const event of events) {
136
+ if (mentions(event, pubkey)) mentioned.add(event.id)
137
+ for (const file of candidateFilesOf(event)) {
138
+ const list = byFile.get(file)
139
+ if (list) list.push(event)
140
+ else byFile.set(file, [event])
141
+ }
142
+ }
143
+ const files = new Map<string, Membership>()
144
+ for (const [file, held] of byFile) {
145
+ const [kind, , d] = file.split(':')
146
+ const own = authorOfAddress(file) === pubkey
147
+ // The root the viewer created, when they did — ordered before everything else for the file.
148
+ const root = own ? [{ id: '', pubkey, kind: Number(kind), created_at: floor, tags: [['d', d ?? '']], content: '', sig: '' }] : []
149
+ files.set(file, membershipOf(file, pubkey, [...root, ...held]))
150
+ }
151
+ return { files, mentioned, floor }
152
+ }
153
+
154
+ /**
155
+ * The terms a stream is judged on, from the membership read and the muted set.
156
+ *
157
+ * A file is a member by the fold, else by authorship (a file the viewer
158
+ * created is theirs unless a leave of theirs says otherwise, and a leave is
159
+ * among the files read). Anything that is not a file address — a Folder's
160
+ * general stream — has nothing to read (Miky, 2026-10-01): nobody is a member
161
+ * of it, so it lights only for a message that names the viewer.
162
+ */
163
+ export function streamTermsOf(
164
+ key: string,
165
+ read: Pick<MembershipRead, 'files' | 'floor'>,
166
+ me: string | undefined,
167
+ muted: ReadonlySet<string>,
168
+ ): StreamTerms {
169
+ const isMuted = muted.has(key)
170
+ if (fileContext(key) === undefined) return { member: false, muted: isMuted }
171
+ const folded = read.files.get(key)
172
+ if (folded) return { member: folded.member, since: folded.since, muted: isMuted }
173
+ if (me && authorOfAddress(key) === me) return { member: true, since: read.floor, muted: isMuted }
174
+ return { member: false, muted: isMuted }
175
+ }
176
+
177
+ /**
178
+ * Whether the horizon's read has a word on the viewer in this file: an event
179
+ * naming them within it, or the file is theirs. Without one, "not a member"
180
+ * may only mean they joined before the horizon; a list that must say whose a
181
+ * file is reads those over all history.
182
+ */
183
+ export function membershipJudges(key: string, read: Pick<MembershipRead, 'files'>, me: string | undefined): boolean {
184
+ return read.files.has(key) || (!!me && authorOfAddress(key) === me)
185
+ }
package/src/strength.ts CHANGED
@@ -27,7 +27,7 @@
27
27
  * reply `e` — a `kind:9` with any `e`, a `kind:1111` with a lowercase `e` that
28
28
  * differs from its `E` — is not a comment of its own, whatever `a` it carries.
29
29
  */
30
- import { decodeNaddr, decodeNpub, findNaddrs, findNostrUris, pointerToAddress, type NostrTag, type SignedEvent } from '@estiva-app/protocol'
30
+ import { decodeNaddr, decodeNpub, findNaddrs, findNostrUris, FILE_KINDS, fileIdOf, pointerToAddress, type NostrTag, type SignedEvent } from '@estiva-app/protocol'
31
31
  import { KIND_COMMENT } from './kinds.js'
32
32
 
33
33
  type Tagged = Pick<SignedEvent, 'kind' | 'tags'>
@@ -77,11 +77,76 @@ export function isReply(event: Pick<SignedEvent, 'kind' | 'tags'>): boolean {
77
77
  * test for whether the event itself lists as a comment.
78
78
  */
79
79
  export function anchorsOf(event: Tagged): string[] {
80
- if (event.kind !== KIND_COMMENT) return []
80
+ if (event.kind !== KIND_COMMENT || crossed(event)) return []
81
81
  const roots = values(event, 'A')
82
82
  return [...new Set(roots.length > 0 ? roots : values(event, 'a'))]
83
83
  }
84
84
 
85
+ /**
86
+ * The ids of the files the event's thread is about by its `O` tags (§6.4, "A
87
+ * comment in both forms"), beside {@link anchorsOf}'s addresses. Empty for a
88
+ * comment whose `A` and `O` name different files: that one is about neither.
89
+ */
90
+ export function anchorIdsOf(event: Tagged): string[] {
91
+ if (event.kind !== KIND_COMMENT || crossed(event)) return []
92
+ return [...new Set(values(event, 'O'))]
93
+ }
94
+
95
+ /**
96
+ * A comment §6.4 ignores, as a change is (§6.2): two `O`s or two `A`s, or a
97
+ * root and an `O` that name different files, or it would show under one file
98
+ * for a reader asking by address and under another for one asking `#O`. The
99
+ * root is its `A`, or its `a` when it carries no `A`, as {@link anchorsOf}
100
+ * reads it, and names the `O`'s file only as a file kind's address with that
101
+ * id. That the author is the file's is {@link isAbout}'s to check: the
102
+ * comment is about its root.
103
+ */
104
+ function crossed(event: Pick<SignedEvent, 'tags'>): boolean {
105
+ const ids = new Set(values(event, 'O'))
106
+ const roots = new Set(values(event, 'A'))
107
+ if (ids.size > 1 || roots.size > 1) return true
108
+ if (ids.size === 0) return false
109
+ const [id] = ids
110
+ return [...(roots.size > 0 ? roots : values(event, 'a'))].some(
111
+ (address) => !FILE_KINDS.includes(Number(address.split(':')[0])) || fileIdOf(address) !== id,
112
+ )
113
+ }
114
+
115
+ /** Whether the event is a comment whose root and `O` name different files: one ignored under every file (§6.4). */
116
+ export function isCrossedComment(event: Tagged): boolean {
117
+ return event.kind === KIND_COMMENT && crossed(event)
118
+ }
119
+
120
+ /**
121
+ * {@link isCrossedComment}, or a comment whose `O` has the id of the file at
122
+ * `address` under a root that is not that address (another author's): its
123
+ * root and `O` disagree for this file, so under it it is nothing, not even a
124
+ * mention (§6.4).
125
+ */
126
+ export function isCrossedCommentOn(event: Tagged, address: string): boolean {
127
+ if (event.kind !== KIND_COMMENT) return false
128
+ if (crossed(event)) return true
129
+ const roots = anchorsOf(event)
130
+ return roots.length > 0 && !roots.includes(address) && values(event, 'O').some((id) => namesById(id, address))
131
+ }
132
+
133
+ /**
134
+ * Whether a `kind:1111`'s thread is about the file at `address`: by its
135
+ * {@link anchorsOf} root when it has one, so an `O` with the file's id under
136
+ * an address of another author is not about it; by its `O` only when it
137
+ * carries neither `A` nor `a` (§6.4). A root or a reply alike;
138
+ * {@link isCommentOn} adds the root test.
139
+ */
140
+ export function isAbout(event: Tagged, address: string): boolean {
141
+ const roots = anchorsOf(event)
142
+ if (roots.length > 0) return roots.includes(address)
143
+ // No root: neither `A` nor `a`, or an ignored comment, whose `O`s are none.
144
+ return anchorIdsOf(event).some((id) => namesById(id, address))
145
+ }
146
+
147
+ /** Whether a tag naming a file by its id (`O`, `o`) names the file at `address`. */
148
+ const namesById = (id: string, address: string) => fileIdOf(address) === id
149
+
85
150
  /**
86
151
  * Is the event a **comment** on the address: a root whose thread is about it
87
152
  * (C10, C11).
@@ -98,14 +163,21 @@ export function anchorsOf(event: Tagged): string[] {
98
163
  */
99
164
  export function isCommentOn(event: Readable, address: string, declaredKinds: readonly number[] = [KIND_COMMENT]): boolean {
100
165
  if (isReply(event)) return false
101
- if (event.kind === KIND_COMMENT) return anchorsOf(event).includes(address)
166
+ if (event.kind === KIND_COMMENT) return isAbout(event, address)
102
167
  if (!declaredKinds.includes(event.kind)) return false
103
168
  return event.tags.some((t) => t[0] === 'a' && t[1] === address) && !namedInBody(event.content).has(address)
104
169
  }
105
170
 
106
- /** Does the event name the address at all — any `a` or `A`, or a `nostr:naddr…` in its body. */
171
+ /**
172
+ * Does the event name the address at all — any `a` or `A`, an `o` or `O` with
173
+ * the file's id (§6.4), or a `nostr:naddr…` in its body. A comment whose `A`
174
+ * and `O` disagree names nothing: it is ignored under every file (§6.4), and
175
+ * one whose `O` has this file's id under another address is about that one.
176
+ */
107
177
  export function referencesAddress(event: Readable, address: string): boolean {
178
+ if (isCrossedCommentOn(event, address)) return false
108
179
  if (event.tags.some((t) => (t[0] === 'a' || t[0] === 'A') && t[1] === address)) return true
180
+ if (event.tags.some((t) => (t[0] === 'o' || t[0] === 'O') && typeof t[1] === 'string' && namesById(t[1], address))) return true
109
181
  return namedInBody(event.content).has(address)
110
182
  }
111
183
 
package/src/unread.ts CHANGED
@@ -19,7 +19,7 @@
19
19
  * the caller's to decide by not asking.
20
20
  */
21
21
  import type { SignedEvent } from '@estiva-app/protocol'
22
- import { REPLY_FLOOR_CONTEXT, belowReplyFloor, effectiveReadAt, threadContext } from './readState.js'
22
+ import { REPLY_FLOOR_CONTEXT, belowReplyFloor, effectiveReadAt, streamMarkerOf, threadContext } from './readState.js'
23
23
  import { peopleNamedInBody } from './strength.js'
24
24
  import { groupThreads } from './threads.js'
25
25
 
@@ -78,7 +78,7 @@ export function isUnread(message: Message, root: string | undefined, merged: Rea
78
78
  if (!mentioned && (!judge.member || judge.muted)) return false
79
79
  if (judge.since !== undefined && message.created_at < judge.since) return false
80
80
  const thread = root === undefined ? undefined : threadContext(root)
81
- const marker = thread === undefined ? merged[judge.stream] : effectiveReadAt(merged, thread, judge.stream)
81
+ const marker = thread === undefined ? streamMarkerOf(merged, judge.stream) : effectiveReadAt(merged, thread, judge.stream)
82
82
  if (marker !== undefined) return message.created_at > marker
83
83
  if (thread !== undefined && belowReplyFloor(message.created_at, merged[REPLY_FLOOR_CONTEXT])) return false
84
84
  if (judge.since !== undefined) return true