@estiva-app/interop 0.40.0 → 0.42.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.
package/src/index.ts CHANGED
@@ -43,6 +43,7 @@ export {
43
43
  KIND_FOLDER_STATE,
44
44
  KIND_CHANNEL_METADATA,
45
45
  KIND_BARE_FILE,
46
+ MOVED_TO_TAG,
46
47
  BARE_FILE_MANIFEST_ADDRESS,
47
48
  ASPECTS,
48
49
  type Aspect,
@@ -53,13 +54,6 @@ export {
53
54
  threadsOf,
54
55
  type Threads,
55
56
  CONVERSATION_LIMIT,
56
- commentDecorationsOf,
57
- editTargetOf,
58
- REACTION_HORIZON,
59
- type CommentDecoration,
60
- type CommentDecorations,
61
- type CommentReaction,
62
- type CommentResolution,
63
57
  buildActionEvent,
64
58
  buildActionEvents,
65
59
  type ActionEventArgs,
package/src/projection.ts CHANGED
@@ -12,8 +12,8 @@
12
12
  * anything: it becomes an integration written against one app, which is the
13
13
  * thing the whole exercise argues against.
14
14
  */
15
- import { decodeNaddr, decodeNevent, encodeNaddr, encodeNevent, findNaddrs, pointerToAddress, referenceToPointer, type AddressPointer, type EventPointer } from '@estiva-app/protocol'
16
- import { imetaOf, parseProfile, type Imeta, type Profile, type SignedEvent } from '@estiva-app/protocol'
15
+ import { decodeNevent, encodeNaddr, encodeNevent, pointerToAddress, referenceToPointer, type AddressPointer, type EventPointer } from '@estiva-app/protocol'
16
+ import { parseProfile, type Profile, type SignedEvent } from '@estiva-app/protocol'
17
17
  import { MAX_FILTERS_PER_QUERY, RELAY_PAGE_CEILING } from '@estiva-app/protocol'
18
18
  import {
19
19
  attachmentsInDocument,
@@ -23,6 +23,14 @@ import {
23
23
  parseBlockDocument,
24
24
  } from '@estiva-app/protocol'
25
25
  import { planPlaceFile, planUnlistFile, type FolderRef } from './folders.js'
26
+ /*
27
+ SPEC §6.4's comment strength and §6.3's ordering are the conversation
28
+ package's (CON-5): one copy of each rule, read here for a file's `comments`,
29
+ `conversationsOf` and every change fold. Its `isCommentOn` is stricter than
30
+ the copy that lived here — a `kind:9` is never a comment (CON-20 migrated
31
+ them), a reply is never a root, and `ts` is trusted only inside its own second.
32
+ */
33
+ import { byOrder, isCommentOn, orderingMs } from '@estiva-app/conversation'
26
34
 
27
35
  /** Query the relay. Returns matching events; shape mirrors the HTTP bridge. */
28
36
  export type QueryFn = (filters: Record<string, unknown>[]) => Promise<SignedEvent[]>
@@ -347,7 +355,8 @@ function rootOf(event: SignedEvent): string {
347
355
  * on another file, a `kind:9` whose body names this one — and those are
348
356
  * *Mentioned in*, which §6.4 says MUST NOT be presented as the file's own
349
357
  * discussion. A badge counting them said "3" beside an issue with one comment.
350
- * See `isCommentOn` for the per-kind rule.
358
+ * See `@estiva-app/conversation`'s `isCommentOn` for the per-kind rule, which
359
+ * this passes the owner's declared comment kinds (§7.3).
351
360
  */
352
361
  export async function conversationsOf(
353
362
  files: ForeignObject[],
@@ -397,6 +406,7 @@ export async function conversationsOf(
397
406
  if (asked.length === 0) return {}
398
407
 
399
408
  const refOf = new Map(asked.map((a) => [a.address, a.ref]))
409
+ const kindsOf = new Map(asked.map((a) => [a.address, a.filter.kinds]))
400
410
  const conversations: Record<string, ConversationMessage[]> = {}
401
411
  for (const a of asked) conversations[a.ref] = []
402
412
 
@@ -425,7 +435,7 @@ export async function conversationsOf(
425
435
  neither when it merely mentions them. `isCommentOn` is §6.4's rule.
426
436
  */
427
437
  const ref = event.tags
428
- .filter((t) => t[0] === 'a' && t[1] && refOf.has(t[1]) && isCommentOn(event, t[1]))
438
+ .filter((t) => t[0] === 'a' && t[1] && refOf.has(t[1]) && isCommentOn(event, t[1], kindsOf.get(t[1])))
429
439
  .map((t) => refOf.get(t[1]))
430
440
  .find((found) => found !== undefined)
431
441
  if (ref !== undefined) {
@@ -528,242 +538,6 @@ export async function threadsOf(
528
538
  return { roots, replies }
529
539
  }
530
540
 
531
- /**
532
- * How many targets a reaction read asks about — SPEC §6.6, decided by CON-1.
533
- *
534
- * A `kind:7` carries no `h` and no `a`, so reactions are found only by asking
535
- * for the ids on screen, and the number asked for is a horizon every reader
536
- * shares: two apps with different N disagree about a count, legitimately and
537
- * unfixably. The value is the specification's, not this package's.
538
- */
539
- export const REACTION_HORIZON = 100
540
-
541
- /** A `kind:7` on a comment. */
542
- export interface CommentReaction {
543
- id: string
544
- emoji: string
545
- by: string
546
- at: number
547
- }
548
-
549
- /** A `kind:9101` resolution assertion on a comment (PEEK-128). */
550
- export interface CommentResolution {
551
- id: string
552
- action: 'resolved' | 'reopened'
553
- by: string
554
- at: number
555
- /** The assertion's free text, when it carried one. */
556
- message?: string
557
- /** The reply that carried the resolution, when the writer named one. */
558
- supportingEventId?: string
559
- }
560
-
561
- /** What has been done to one comment since it was written. */
562
- export interface CommentDecoration {
563
- /**
564
- * The newest `kind:40003` — the body to show, and when. RFC 0.4 §7.2.1: a
565
- * reader MUST be told the body changed, so this is kept beside the original
566
- * rather than folded over it; the consumer draws the marker.
567
- *
568
- * When the caller passes the target's `body`, `at` and `by` are those of the
569
- * last edit that **changed** the body — content not byte-identical to the
570
- * body it replaced — and `edit` is absent when none did (§7.2.1, amended
571
- * 2026-09-23, CON-5: the mark is about the body). `body` is always the newest
572
- * edit's content. Without `body` it is the newest edit, as before.
573
- */
574
- edit?: { body: string; at: number; by: string }
575
- /**
576
- * The `imeta` set of the newest edit that carries at least one — RFC 0.4
577
- * §7.2.1 as amended 2026-09-23 (CON-5). A set replaces the target's own; it
578
- * does not append. Absent when no edit carries one, in which case the
579
- * target's own attachments stand: an edit with no `imeta` means "unchanged".
580
- */
581
- attachments?: Imeta[]
582
- /** Every reaction found, in the order the relay holds them. Empty inside the horizon means none. */
583
- reactions: CommentReaction[]
584
- /** Oldest first; the last one is the current state. Empty means never resolved. */
585
- resolutions: CommentResolution[]
586
- }
587
-
588
- /** The answer of {@link commentDecorationsOf}. */
589
- export interface CommentDecorations {
590
- /** Keyed by comment id. A target nothing happened to is present, with nothing in it. */
591
- byId: Record<string, CommentDecoration>
592
- /**
593
- * How many of the targets were **not** asked about reactions, because they
594
- * fell outside the horizon. SPEC §6.6 makes reporting this a MUST: a cap
595
- * nobody can see is indistinguishable from "nobody reacted".
596
- */
597
- reactionTargetsOmitted: number
598
- }
599
-
600
- /** The three kinds a comment's decorations come in. Numbers, and here for the same reason `KIND_BARE_FILE` is. */
601
- const KIND_REACTION = 7
602
- const KIND_ASSERTION = 9101
603
- const KIND_MESSAGE_EDIT = 40003
604
-
605
- /**
606
- * The message a `kind:40003` edits: **the first `e` whose value is 64 hex,
607
- * marker ignored**, lowercased (SPEC §6.8, PEE-38). That is exactly the event
608
- * whose ownership the relay checked (`validate_edit_ownership`), and a reader
609
- * MUST NOT apply an edit to any other `e` — nothing refuses an edit carrying a
610
- * second one, so `['e', <own>, '', 'mention'], ['e', <victim>]` is accepted on
611
- * the writer's own message and must not be drawn on the victim's.
612
- *
613
- * Undefined when there is none, which the relay refuses; a reader holding one
614
- * anyway applies it nowhere.
615
- */
616
- export function editTargetOf(event: { tags: readonly (readonly string[])[] }): string | undefined {
617
- const tag = event.tags.find((t) => t[0] === 'e' && typeof t[1] === 'string' && /^[0-9a-fA-F]{64}$/.test(t[1]))
618
- return tag?.[1].toLowerCase()
619
- }
620
-
621
- /** Ids per `#e` filter. A comfortable fraction of the relay's page, so one filter's answer is never cut. */
622
- const DECORATION_TARGETS_PER_FILTER = 100
623
-
624
- /**
625
- * What has been done to a set of comments — edits, reactions, resolutions — in
626
- * one request, read by `#e`.
627
- *
628
- * **A second round trip, and that is why this is a function rather than part of
629
- * {@link resolveForeignObject}.** Everything that read returns is addressed by
630
- * `#a`, so it arrives with the root. An edit (`kind:40003`), a reaction
631
- * (`kind:7`) and a resolution (`kind:9101`) name the *comment* by `e` and not
632
- * the file, so they cannot be asked for until the comment ids are known. A
633
- * widget that never draws comments should not pay for that, so a consumer
634
- * that draws a conversation asks here with the ids it has — the roots off the
635
- * object, the replies off its thread read — and pays once for both.
636
- *
637
- * Three rules, each from the ticket that established it:
638
- *
639
- * - **Edits fold newest-wins** (CON-8). The original stays on the relay and so
640
- * does every edit; the fold is the reader's, and this is it. Attachments
641
- * fold separately (CON-5): the newest edit carrying `imeta` sets them.
642
- * - **Reactions have a horizon of {@link REACTION_HORIZON} targets** (SPEC
643
- * §6.6, CON-1) — the *newest* targets by `at`, one budget across whatever
644
- * id spaces the caller mixes, and the number left out is reported. Edits
645
- * and resolutions have no horizon: they are one event per change, not one
646
- * per reader.
647
- * - **A resolution is a `kind:9101` carrying `t=resolution`** (PEEK-128); its
648
- * `action` tag is the state, its content the rationale, and a second `e`
649
- * marked `support` names the reply that carried it.
650
- *
651
- * Nothing here checks who wrote an edit against who wrote the comment. The
652
- * relay adjudicates writes; a `40003` it stored is one it accepted — **for
653
- * the `e` it checked**, which is why an edit lands only on
654
- * {@link editTargetOf} and never on another `e` it carries.
655
- */
656
- export async function commentDecorationsOf(
657
- targets: readonly { id: string; at: number; body?: string }[],
658
- query: QueryFn,
659
- ): Promise<CommentDecorations> {
660
- const byId: Record<string, CommentDecoration> = {}
661
- const unique = new Map<string, number>()
662
- for (const t of targets) if (!unique.has(t.id)) unique.set(t.id, t.at)
663
- for (const id of unique.keys()) byId[id] = { reactions: [], resolutions: [] }
664
- if (unique.size === 0) return { byId, reactionTargetsOmitted: 0 }
665
-
666
- const ids = [...unique.keys()]
667
- // Newest first, ties on the higher id so the cut is stable between reads.
668
- const forReactions = [...unique]
669
- .sort((a, b) => b[1] - a[1] || (a[0] > b[0] ? -1 : 1))
670
- .slice(0, REACTION_HORIZON)
671
- .map(([id]) => id)
672
-
673
- const filters: Record<string, unknown>[] = []
674
- const chunked = (list: string[]) => {
675
- const out: string[][] = []
676
- for (let i = 0; i < list.length; i += DECORATION_TARGETS_PER_FILTER) {
677
- out.push(list.slice(i, i + DECORATION_TARGETS_PER_FILTER))
678
- }
679
- return out
680
- }
681
- for (const chunk of chunked(ids)) {
682
- filters.push({ kinds: [KIND_MESSAGE_EDIT, KIND_ASSERTION], '#e': chunk, limit: RELAY_PAGE_CEILING })
683
- }
684
- for (const chunk of chunked(forReactions)) {
685
- filters.push({ kinds: [KIND_REACTION], '#e': chunk, limit: RELAY_PAGE_CEILING })
686
- }
687
-
688
- const seen = new Set<string>()
689
- const edits = new Map<string, SignedEvent[]>()
690
- const bodies = new Map<string, string>()
691
- for (const t of targets) if (t.body !== undefined && !bodies.has(t.id)) bodies.set(t.id, t.body)
692
- for (let start = 0; start < filters.length; start += MAX_FILTERS_PER_QUERY) {
693
- const events = await query(filters.slice(start, start + MAX_FILTERS_PER_QUERY))
694
- for (const event of events) {
695
- if (seen.has(event.id)) continue
696
- seen.add(event.id)
697
- /*
698
- An edit's target is the one the relay checked ownership of, and no
699
- other (SPEC §6.8, PEE-38): see {@link editTargetOf}. For the rest, the
700
- `e` that names one of *our* targets — a resolution carries a second `e`
701
- for its supporting reply, so its first `e` is not necessarily the target.
702
- `hasOwn`, not `in`: an `e` of `constructor` is anybody's to write, and
703
- `in` finds it on the prototype.
704
- */
705
- const ours = (id: string | undefined): id is string => id !== undefined && Object.hasOwn(byId, id)
706
- const target =
707
- event.kind === KIND_MESSAGE_EDIT
708
- ? editTargetOf(event)
709
- : event.tags.find((t) => t[0] === 'e' && ours(t[1]) && !t[3])?.[1]
710
- if (!ours(target)) continue
711
- const into = byId[target]
712
- if (event.kind === KIND_MESSAGE_EDIT) {
713
- edits.set(target, [...(edits.get(target) ?? []), event])
714
- } else if (event.kind === KIND_REACTION) {
715
- if (!forReactions.includes(target)) continue
716
- into.reactions.push({ id: event.id, emoji: event.content, by: event.pubkey, at: event.created_at })
717
- } else if (event.kind === KIND_ASSERTION) {
718
- if (tagValue(event, 't') !== 'resolution') continue
719
- const action = tagValue(event, 'action')
720
- if (action !== 'resolved' && action !== 'reopened') continue
721
- const support = event.tags.find((t) => t[0] === 'e' && t[3] === 'support')?.[1]
722
- into.resolutions.push({
723
- id: event.id,
724
- action,
725
- by: event.pubkey,
726
- at: event.created_at,
727
- ...(event.content ? { message: event.content } : {}),
728
- ...(support ? { supportingEventId: support } : {}),
729
- })
730
- }
731
- }
732
- }
733
- for (const [target, list] of edits) {
734
- const ordered = [...list].sort(byOrder)
735
- const into = byId[target]
736
- const newest = ordered[ordered.length - 1]
737
- let body = bodies.get(target)
738
- if (body === undefined) {
739
- into.edit = { body: newest.content, at: newest.created_at, by: newest.pubkey }
740
- } else {
741
- // Replayed from the target's own body, so "byte-identical to the body it
742
- // replaces" is judged against the body as it then stood.
743
- let changed: SignedEvent | undefined
744
- for (const edit of ordered) {
745
- if (edit.content !== body) changed = edit
746
- body = edit.content
747
- }
748
- if (changed) into.edit = { body: newest.content, at: changed.created_at, by: changed.pubkey }
749
- }
750
- for (let i = ordered.length - 1; i >= 0; i--) {
751
- const set = imetaOf(ordered[i])
752
- if (set.length > 0) {
753
- into.attachments = set
754
- break
755
- }
756
- }
757
- }
758
- const oldestFirst = (a: { at: number; id: string }, b: { at: number; id: string }) =>
759
- a.at - b.at || (a.id < b.id ? -1 : 1)
760
- for (const decoration of Object.values(byId)) {
761
- decoration.reactions.sort(oldestFirst)
762
- decoration.resolutions.sort(oldestFirst)
763
- }
764
- return { byId, reactionTargetsOmitted: ids.length - forReactions.length }
765
- }
766
-
767
541
  /** How the owning app says its records should be read. */
768
542
  interface RecordsRule {
769
543
  changeKind: number
@@ -1349,53 +1123,6 @@ export function folderOf(root: SignedEvent): string | null {
1349
1123
  const hasTagValue = (e: SignedEvent, name: string, value: string) =>
1350
1124
  e.tags.some((t) => t[0] === name && t[1] === value)
1351
1125
 
1352
- /** The addresses a body names by `nostr:naddr…`; a pointer that will not decode is prose. */
1353
- function namedInBody(body: string): Set<string> {
1354
- const addresses = new Set<string>()
1355
- for (const naddr of findNaddrs(body)) {
1356
- try {
1357
- addresses.add(pointerToAddress(decodeNaddr(naddr)))
1358
- } catch {
1359
- // A malformed pointer is prose.
1360
- }
1361
- }
1362
- return addresses
1363
- }
1364
-
1365
- /**
1366
- * Is this event a *comment* on the address, rather than a message elsewhere
1367
- * that merely names it?
1368
- *
1369
- * Both arrive by the object's `#a` read — the `a` tag is the index of every
1370
- * reference, whichever strength — and SPEC §6.4 says an app MUST NOT present
1371
- * the two as one list: a comment is the object's own discussion, a mention is
1372
- * *Mentioned in*. Until CON-15 this package handed the raw `#a` union to
1373
- * {@link resolveForeignObject}'s `comments` and {@link conversationsOf}, and
1374
- * a widget said "3" beside an issue with one comment and two mentions. The
1375
- * rule is §6.4's per-tag one, applied per kind (CON-13, CON-14):
1376
- *
1377
- * - A `kind:1111`'s uppercase `A` is the comment — NIP-22's thread root. One
1378
- * whose `A` is another file is that file's conversation; its `a` for this
1379
- * one is the index of a reference. One with no `A` at all is read by its
1380
- * `a`, the way §6.4 says to read it rather than drop the thread.
1381
- * - Any other comment kind has no `A`, so its `a` is read against its body.
1382
- * A `kind:9` whose body names the address is the index of that reference —
1383
- * what Peek writes for every `[`-menu reference in a topic message — and a
1384
- * mention. One whose body does not is the anchor of a comment written
1385
- * before REW-10 moved comments to `1111`, which is not replaceable and so
1386
- * reads as a comment for good.
1387
- *
1388
- * `commentDecorationsOf` is deliberately not behind this: a reaction or a
1389
- * status on a comment is about the *comment*, whatever that comment is about.
1390
- */
1391
- function isCommentOn(event: SignedEvent, address: string): boolean {
1392
- if (event.kind === KIND_COMMENT) {
1393
- const roots = event.tags.filter((t) => t[0] === 'A' && t[1])
1394
- return roots.length > 0 ? roots.some((t) => t[1] === address) : hasTagValue(event, 'a', address)
1395
- }
1396
- return hasTagValue(event, 'a', address) && !namedInBody(event.content).has(address)
1397
- }
1398
-
1399
1126
  /**
1400
1127
  * A manifest event's `content`, or null when it is not parseable JSON.
1401
1128
  *
@@ -1523,6 +1250,21 @@ export interface ResolvedManifest {
1523
1250
  */
1524
1251
  export const KIND_BARE_FILE = 30840
1525
1252
 
1253
+ /**
1254
+ * The tag a move carries naming its new parent — SPEC §7.2 (FOL-45).
1255
+ *
1256
+ * A move is a change to the field a list declares as `movedBy`, and its new
1257
+ * parent is the change's `value`, which no relay indexes. So a move also
1258
+ * carries `["A", <new parent address>]`, after `ts`, and a list reads
1259
+ * `{ kinds: [changeKind], "#A": [parent] }` to find the children moved in.
1260
+ *
1261
+ * Uppercase because a lowercase `a` is the change's target to every reader —
1262
+ * and Folder listings match *every* `a` on a change, so a second one would
1263
+ * fold the move into the parent itself. Only on a change, never read without a
1264
+ * `kinds` filter, and only ever a hint: the child's own fold decides.
1265
+ */
1266
+ export const MOVED_TO_TAG = 'A'
1267
+
1526
1268
  /**
1527
1269
  * The field that archives a file, whatever its kind — FOL-46.
1528
1270
  *
@@ -2107,33 +1849,6 @@ export async function resolveActingManifest(
2107
1849
  return borrowedFrom(pointer.kind, owner, creators).find((creator) => creator.address === declaredBy) ?? null
2108
1850
  }
2109
1851
 
2110
- /**
2111
- * Ordering key for an append-only event, per the manifest's `records.order`.
2112
- *
2113
- * The manifest declares `["ts", "created_at", "id"]` and, crucially, the
2114
- * condition under which `ts` may be believed: only when it agrees with
2115
- * `created_at` to the second. `created_at` has one-second resolution and the
2116
- * relay validates it, so a `ts` pinned inside that second inherits that
2117
- * validation and can only refine ordering *within* it.
2118
- *
2119
- * Peek enforces that bound itself rather than trusting the writer. Under the
2120
- * honour-system model nothing validates these events (RFC_UPDATES.md §3), so a
2121
- * buggy or pushy client claiming a far-future `ts` would otherwise win every
2122
- * fold forever — in Peek's rendering as much as in the owning app's.
2123
- */
2124
- function orderingMs(event: SignedEvent): number {
2125
- const raw = Number.parseInt(tagValue(event, 'ts') ?? '', 10)
2126
- if (Number.isFinite(raw) && Math.abs(Math.floor(raw / 1000) - event.created_at) <= 1) return raw
2127
- return event.created_at * 1000
2128
- }
2129
-
2130
- /** Total order, oldest first. Ties break on the lower event id (NIP-01's rule). */
2131
- function byOrder(a: SignedEvent, b: SignedEvent): number {
2132
- const [at, bt] = [orderingMs(a), orderingMs(b)]
2133
- if (at !== bt) return at - bt
2134
- return a.id < b.id ? -1 : a.id > b.id ? 1 : 0
2135
- }
2136
-
2137
1852
  /** Replay change events into current field values. Last write wins per field. */
2138
1853
  /**
2139
1854
  * The fold rule a manifest declares, or one that folds nothing — PRO-6.
@@ -3553,6 +3268,7 @@ function planObject(
3553
3268
  ...(manifest.records ? [] : [{ kinds: [ARCHIVE_RULE.changeKind], '#a': [address], limit: 500 }]),
3554
3269
  { kinds: commentKinds, '#a': [address], limit: CONVERSATION_LIMIT },
3555
3270
  ...(childFilter ? [childFilter.filter] : []),
3271
+ ...(childFilter?.movedIn ? [childFilter.movedIn] : []),
3556
3272
  ]
3557
3273
  return { naddr, pointer, address, resolved, projection, records, commentKinds, childFilter, filters, openUrl }
3558
3274
  }
@@ -3632,10 +3348,10 @@ function assembleObject(plan: ObjectPlan, answered: SignedEvent[], childChanges:
3632
3348
 
3633
3349
  Then narrowed to §6.4's *comment* strength (CON-15): the `a` tag is also the
3634
3350
  index of a mention, and a mention is not this object's discussion. See
3635
- `isCommentOn` for the per-kind rule.
3351
+ `isCommentOn` (`@estiva-app/conversation`) for the per-kind rule.
3636
3352
  */
3637
3353
  const comments = events
3638
- .filter((e) => commentKinds.includes(e.kind) && isCommentOn(e, address))
3354
+ .filter((e) => commentKinds.includes(e.kind) && isCommentOn(e, address, commentKinds))
3639
3355
  .sort(byOrder)
3640
3356
  .map((e) => ({ id: e.id, author: e.pubkey, body: e.content, createdAt: e.created_at }))
3641
3357
 
@@ -3836,7 +3552,10 @@ function childFilterFor(args: {
3836
3552
  manifest: Manifest
3837
3553
  pointer: AddressPointer
3838
3554
  depth: number
3839
- }): { filter: Record<string, unknown>; kind: number; via: string; parent: string; movedBy?: string } | null | undefined {
3555
+ }):
3556
+ | { filter: Record<string, unknown>; kind: number; via: string; parent: string; movedBy?: string; movedIn?: Record<string, unknown> }
3557
+ | null
3558
+ | undefined {
3840
3559
  const { projection, manifest, pointer, depth } = args
3841
3560
  const children = declaredChildSpec(projection)
3842
3561
  if (!children) return undefined
@@ -3852,6 +3571,7 @@ function childFilterFor(args: {
3852
3571
  ? pointer.identifier
3853
3572
  : pointerToAddress({ ...pointer, relays: [] })
3854
3573
 
3574
+ const movedBy = children.movedBy && children.match !== 'identifier' ? children.movedBy : undefined
3855
3575
  return {
3856
3576
  filter: { kinds: [children.kind], [`#${children.via}`]: [parent], limit: children.limit ?? 100 },
3857
3577
  kind: children.kind,
@@ -3859,10 +3579,38 @@ function childFilterFor(args: {
3859
3579
  parent,
3860
3580
  // This list's own, not whichever projection declares one for the kind — and
3861
3581
  // none on an identifier list, where a move's address never names the parent.
3862
- ...(children.movedBy && children.match !== 'identifier' ? { movedBy: children.movedBy } : {}),
3582
+ ...(movedBy ? { movedBy } : {}),
3583
+ // The children moved *in*: the moves naming this parent by `MOVED_TO_TAG`
3584
+ // (SPEC §7.2, FOL-45). A `#via` read cannot see them — their parent is in a
3585
+ // `value` — so without this a child moved here was drawn under nothing.
3586
+ ...(movedBy && manifest.records
3587
+ ? { movedIn: { kinds: [manifest.records.changeKind], [`#${MOVED_TO_TAG}`]: [parent], limit: children.limit ?? 100 } }
3588
+ : {}),
3863
3589
  }
3864
3590
  }
3865
3591
 
3592
+ /**
3593
+ * The addresses of children a pooled answer says were moved in to this parent:
3594
+ * the target of every change naming it by `MOVED_TO_TAG`, of the child kind.
3595
+ *
3596
+ * **A hint, never the answer.** A later move away names the *new* parent, not
3597
+ * this one, so a change found here may be stale; the child's own fold decides
3598
+ * (`childrenFrom`), exactly as it decides for a child created here.
3599
+ */
3600
+ function movedInAddressesOf(
3601
+ events: SignedEvent[],
3602
+ childFilter: NonNullable<ReturnType<typeof childFilterFor>>,
3603
+ records: Manifest['records'],
3604
+ ): string[] {
3605
+ if (!childFilter.movedIn || !records) return []
3606
+ const prefix = `${childFilter.kind}:`
3607
+ const targets = events
3608
+ .filter((e) => e.kind === records.changeKind && hasTagValue(e, MOVED_TO_TAG, childFilter.parent))
3609
+ .map((e) => tagValue(e, records.targetTag))
3610
+ .filter((address): address is string => !!address && address.startsWith(prefix))
3611
+ return [...new Set(targets)]
3612
+ }
3613
+
3866
3614
  /**
3867
3615
  * The child objects, picked back out of the merged result set.
3868
3616
  *
@@ -3891,8 +3639,20 @@ function childrenFrom(args: {
3891
3639
  if (!childProjection) return []
3892
3640
  const records = foldRuleOf(manifest)
3893
3641
  const { movedBy } = childFilter
3894
-
3895
- return childRootsOf(events, childFilter).flatMap((event) => {
3642
+ const created = childRootsOf(events, childFilter)
3643
+ const createdAddresses = new Set(created.map(childAddressOf))
3644
+ // Moved in: the roots `childChangeFilters` read for the moves naming this parent,
3645
+ // newest version of each, and only those not already found as created here.
3646
+ const movedIn = new Set(movedInAddressesOf(events, childFilter, manifest.records).filter((a) => !createdAddresses.has(a)))
3647
+ const movedInRoots = new Map<string, SignedEvent>()
3648
+ for (const event of childChanges) {
3649
+ const address = event.kind === childFilter.kind ? childAddressOf(event) : undefined
3650
+ if (!address || !movedIn.has(address)) continue
3651
+ const current = movedInRoots.get(address)
3652
+ if (!current || event.created_at > current.created_at) movedInRoots.set(address, event)
3653
+ }
3654
+
3655
+ return [...created, ...[...movedInRoots.values()].sort(byOrder)].flatMap((event) => {
3896
3656
  const address = childAddressOf(event)
3897
3657
  /*
3898
3658
  The child's own fold — MAN-7. Until this, a card's children were built
@@ -3910,12 +3670,14 @@ function childrenFrom(args: {
3910
3670
  found the child.
3911
3671
  - **hidden** by the app's own `hiddenWhen`, or **archived** (FOL-46).
3912
3672
 
3913
- A child moved *in* is not found here and cannot be: its new parent is in
3914
- a `value`, which no relay indexes. SPEC §7.2 names the Folder listing as
3915
- the only read that sees one.
3673
+ - **moved in** and since moved on, or never really here — FOL-45. A
3674
+ child found by its move's `MOVED_TO_TAG` has no `via` naming this
3675
+ parent, so only a folded value that names it keeps it: the tag is how
3676
+ it was found, not proof that it is still here.
3916
3677
  */
3917
3678
  const folded = address ? foldOf(childChanges, address, manifest) : {}
3918
3679
  if (movedBy && folded[movedBy] && folded[movedBy].value !== childFilter.parent) return []
3680
+ if (address && movedIn.has(address) && folded[movedBy!]?.value !== childFilter.parent) return []
3919
3681
  if (records.hiddenWhen && folded[records.hiddenWhen.field]?.value === records.hiddenWhen.equals) return []
3920
3682
  if (address && manifest.records && archiveOf(childChanges, address, records)) return []
3921
3683
  return [
@@ -3972,8 +3734,21 @@ function childChangeFilters(plan: ObjectPlan, answered: SignedEvent[]): Record<s
3972
3734
  if (!answered.some((e) => e.kind === pointer.kind && e.pubkey === pointer.pubkey && tagValue(e, 'd') === pointer.identifier)) {
3973
3735
  return []
3974
3736
  }
3975
- const addresses = [...new Set(childRootsOf(answered, childFilter).flatMap((e) => childAddressOf(e) ?? []))]
3976
- return addresses.length ? archiveFilters(addresses, [records], CHILD_CHANGE_GROUP) : []
3737
+ const created = childRootsOf(answered, childFilter).flatMap((e) => childAddressOf(e) ?? [])
3738
+ // Moved in (FOL-45): found by their moves, so their roots are not in the answer
3739
+ // yet. They are read here with the changes, in the same POST, and folded the same.
3740
+ const movedIn = movedInAddressesOf(answered, childFilter, records).filter((address) => !created.includes(address))
3741
+ const addresses = [...new Set([...created, ...movedIn])]
3742
+ const roots = new Map<string, string[]>()
3743
+ for (const address of movedIn) {
3744
+ // A `d` may itself hold ':' — everything after the pubkey is the identifier.
3745
+ const [, pubkey, ...rest] = address.split(':')
3746
+ roots.set(pubkey, [...(roots.get(pubkey) ?? []), rest.join(':')])
3747
+ }
3748
+ return [
3749
+ ...(addresses.length ? archiveFilters(addresses, [records], CHILD_CHANGE_GROUP) : []),
3750
+ ...[...roots].map(([pubkey, identifiers]) => ({ kinds: [childFilter.kind], authors: [pubkey], '#d': identifiers, limit: identifiers.length })),
3751
+ ]
3977
3752
  }
3978
3753
 
3979
3754
  /** Addresses per filter when reading a card's children's changes — see {@link childChangeFilters}. */
@@ -5115,6 +4890,16 @@ function buildOneActionEvent(args: ActionEventArgs): UnsignedActionEvent | strin
5115
4890
  // depending on which app you asked (FRICTION.md A6).
5116
4891
  if (records.order?.includes('ts')) tags.push(['ts', String(args.createdAtMs)])
5117
4892
  tags.push(...files)
4893
+ // A move also names its new parent where a relay indexes it (SPEC §7.2, FOL-45):
4894
+ // `value` is not indexed, so without this no read by the new parent finds a
4895
+ // child moved in. Only for the field the kind declares as `movedBy`, and only
4896
+ // for an address of the declaring kind (any kind for a bare file) — a move to
4897
+ // the top names no parent, and a value of another kind names none either.
4898
+ const moved = declared.emits.field ? movedByOf(manifest, kind) : undefined
4899
+ const parentAddress = moved?.parentKind === undefined ? /^\d+:[0-9a-f]{64}:/ : new RegExp(`^${moved.parentKind}:[0-9a-f]{64}:`)
4900
+ if (moved?.field === declared.emits.field && typeof value === 'string' && parentAddress.test(value)) {
4901
+ tags.push([MOVED_TO_TAG, value])
4902
+ }
5118
4903
 
5119
4904
  return {
5120
4905
  pubkey: args.pubkey,