@estiva-app/interop 0.39.0 → 0.41.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/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
@@ -1089,6 +863,22 @@ export interface ResolvedAction {
1089
863
  /** The value this field holds right now, so a control can show it. */
1090
864
  current?: string
1091
865
  field?: string
866
+ /**
867
+ * The app that declared this action, **when it is not the object's own** —
868
+ * MAN-8.
869
+ *
870
+ * Ship declares `add-project` on a Folder, and a Folder is Peek's kind: the
871
+ * object is drawn by one manifest and the action comes from another. Only a
872
+ * creation is ever borrowed like this (see {@link creatorsOn}), so this is
873
+ * set only on a `form`. Absent on every action the owning app declares.
874
+ *
875
+ * A consumer acting on it must build with the manifest named here, not the
876
+ * object's — `buildActionEvents` finds the action by id in the manifest it is
877
+ * handed, and the owner's has no `add-project`. {@link resolveActingManifest}
878
+ * is that lookup. `appName` is the declaring app's `name`, for a consumer
879
+ * that says whose action it is.
880
+ */
881
+ declaredBy?: { address: string; appName?: string }
1092
882
  }
1093
883
 
1094
884
  /** How the owning app asks one of its kinds to be drawn (RFC 0.4 §13.3). */
@@ -1333,53 +1123,6 @@ export function folderOf(root: SignedEvent): string | null {
1333
1123
  const hasTagValue = (e: SignedEvent, name: string, value: string) =>
1334
1124
  e.tags.some((t) => t[0] === name && t[1] === value)
1335
1125
 
1336
- /** The addresses a body names by `nostr:naddr…`; a pointer that will not decode is prose. */
1337
- function namedInBody(body: string): Set<string> {
1338
- const addresses = new Set<string>()
1339
- for (const naddr of findNaddrs(body)) {
1340
- try {
1341
- addresses.add(pointerToAddress(decodeNaddr(naddr)))
1342
- } catch {
1343
- // A malformed pointer is prose.
1344
- }
1345
- }
1346
- return addresses
1347
- }
1348
-
1349
- /**
1350
- * Is this event a *comment* on the address, rather than a message elsewhere
1351
- * that merely names it?
1352
- *
1353
- * Both arrive by the object's `#a` read — the `a` tag is the index of every
1354
- * reference, whichever strength — and SPEC §6.4 says an app MUST NOT present
1355
- * the two as one list: a comment is the object's own discussion, a mention is
1356
- * *Mentioned in*. Until CON-15 this package handed the raw `#a` union to
1357
- * {@link resolveForeignObject}'s `comments` and {@link conversationsOf}, and
1358
- * a widget said "3" beside an issue with one comment and two mentions. The
1359
- * rule is §6.4's per-tag one, applied per kind (CON-13, CON-14):
1360
- *
1361
- * - A `kind:1111`'s uppercase `A` is the comment — NIP-22's thread root. One
1362
- * whose `A` is another file is that file's conversation; its `a` for this
1363
- * one is the index of a reference. One with no `A` at all is read by its
1364
- * `a`, the way §6.4 says to read it rather than drop the thread.
1365
- * - Any other comment kind has no `A`, so its `a` is read against its body.
1366
- * A `kind:9` whose body names the address is the index of that reference —
1367
- * what Peek writes for every `[`-menu reference in a topic message — and a
1368
- * mention. One whose body does not is the anchor of a comment written
1369
- * before REW-10 moved comments to `1111`, which is not replaceable and so
1370
- * reads as a comment for good.
1371
- *
1372
- * `commentDecorationsOf` is deliberately not behind this: a reaction or a
1373
- * status on a comment is about the *comment*, whatever that comment is about.
1374
- */
1375
- function isCommentOn(event: SignedEvent, address: string): boolean {
1376
- if (event.kind === KIND_COMMENT) {
1377
- const roots = event.tags.filter((t) => t[0] === 'A' && t[1])
1378
- return roots.length > 0 ? roots.some((t) => t[1] === address) : hasTagValue(event, 'a', address)
1379
- }
1380
- return hasTagValue(event, 'a', address) && !namedInBody(event.content).has(address)
1381
- }
1382
-
1383
1126
  /**
1384
1127
  * A manifest event's `content`, or null when it is not parseable JSON.
1385
1128
  *
@@ -1736,21 +1479,29 @@ async function resolveAspectApp(
1736
1479
  * without `share` (hand-written, or older) keeps the old behaviour exactly:
1737
1480
  * look up, read, remember.
1738
1481
  */
1739
- async function throughCache(
1482
+ async function throughCache<T extends CachedManifests>(
1740
1483
  cache: ProjectionCache | undefined,
1741
1484
  key: string,
1742
- read: () => Promise<ResolvedManifest | null>,
1743
- ): Promise<ResolvedManifest | null> {
1485
+ read: () => Promise<T>,
1486
+ ): Promise<T> {
1744
1487
  const now = Date.now()
1745
1488
  const memo = cache?.lookup(key, now)
1746
- if (memo) return memo.value
1489
+ // Each key is written by one reader, so what it holds is that reader's `T`.
1490
+ if (memo) return memo.value as T
1747
1491
  if (!cache) return read()
1748
- if (cache.share) return cache.share(key, now, read)
1492
+ if (cache.share) return cache.share(key, now, read) as Promise<T>
1749
1493
  const answer = await read()
1750
1494
  cache.remember(key, answer, now)
1751
1495
  return answer
1752
1496
  }
1753
1497
 
1498
+ /**
1499
+ * What a {@link ProjectionCache} entry holds: one app's manifest, or none — or,
1500
+ * for {@link creatorsOn}, every manifest declaring a creation on one kind
1501
+ * (MAN-8). Still only manifests, which is the whole of the cache's promise.
1502
+ */
1503
+ type CachedManifests = ResolvedManifest | null | readonly ResolvedManifest[]
1504
+
1754
1505
  /**
1755
1506
  * A memo for the half of a resolve that does not change between refreshes.
1756
1507
  *
@@ -1775,16 +1526,16 @@ export interface ProjectionCache {
1775
1526
  /** Forget everything. Worth calling after publishing a manifest. */
1776
1527
  clear(): void
1777
1528
  /** @internal */
1778
- lookup(key: string, now: number): { value: ResolvedManifest | null } | undefined
1529
+ lookup(key: string, now: number): { value: CachedManifests } | undefined
1779
1530
  /** @internal */
1780
- remember(key: string, value: ResolvedManifest | null, now: number): void
1531
+ remember(key: string, value: CachedManifests, now: number): void
1781
1532
  /**
1782
1533
  * @internal Run `read` for `key` unless a read for it is already running, in
1783
1534
  * which case join that one; remember the answer as `remember` would. Optional
1784
1535
  * so a hand-written cache still satisfies the interface — without it, a burst
1785
1536
  * of cold resolves asks once each, which is the old behaviour.
1786
1537
  */
1787
- share?(key: string, now: number, read: () => Promise<ResolvedManifest | null>): Promise<ResolvedManifest | null>
1538
+ share?(key: string, now: number, read: () => Promise<CachedManifests>): Promise<CachedManifests>
1788
1539
  }
1789
1540
 
1790
1541
  /**
@@ -1815,8 +1566,8 @@ export const MANIFEST_TTL_MS = 5 * 60_000
1815
1566
  * for the whole window over what may have been one refused request.
1816
1567
  */
1817
1568
  export function createProjectionCache(ttlMs: number = MANIFEST_TTL_MS): ProjectionCache {
1818
- const entries = new Map<string, { at: number; value: ResolvedManifest | null }>()
1819
- const flights = new Map<string, Promise<ResolvedManifest | null>>()
1569
+ const entries = new Map<string, { at: number; value: CachedManifests }>()
1570
+ const flights = new Map<string, Promise<CachedManifests>>()
1820
1571
  // Bumped by `clear`, so a read that was in flight when a manifest was
1821
1572
  // republished does not write its stale answer back afterwards.
1822
1573
  let generation = 0
@@ -1960,30 +1711,127 @@ async function resolveManifestUncached(
1960
1711
  }
1961
1712
 
1962
1713
  /**
1963
- * Ordering key for an append-only event, per the manifest's `records.order`.
1964
- *
1965
- * The manifest declares `["ts", "created_at", "id"]` and, crucially, the
1966
- * condition under which `ts` may be believed: only when it agrees with
1967
- * `created_at` to the second. `created_at` has one-second resolution and the
1968
- * relay validates it, so a `ts` pinned inside that second inherits that
1969
- * validation and can only refine ordering *within* it.
1970
- *
1971
- * Peek enforces that bound itself rather than trusting the writer. Under the
1972
- * honour-system model nothing validates these events (RFC_UPDATES.md §3), so a
1973
- * buggy or pushy client claiming a far-future `ts` would otherwise win every
1974
- * fold forever — in Peek's rendering as much as in the owning app's.
1714
+ * Every app that declares a way to **create one of its own kinds on this one**
1715
+ * — MAN-8.
1716
+ *
1717
+ * {@link resolveManifest} answers with one manifest per kind, its owner's, and
1718
+ * the object's actions came from it alone. So an action one app declares on a
1719
+ * kind another app owns was on the relay and unreachable: Ship's `add-project`
1720
+ * says `appliesTo: "39000"`, a Folder is Peek's, and a Folder resolved with
1721
+ * Peek's `start-a-conversation` and nothing else. Measured on production
1722
+ * 2026-09-30 with Peek's own code.
1723
+ *
1724
+ * **Only a creation, and only of a kind the declaring app projects.** That is
1725
+ * the whole of what one app may say about another's kind: "one of mine can be
1726
+ * made here". A field it sets, a comment, a deletion are the owner's to
1727
+ * declare — the owner's `records` rule folds them, and a stranger declaring
1728
+ * `archived` on a Folder would be offering a change nobody folds as it says.
1729
+ * A creation needs nothing from the owner but an object to be made on, and
1730
+ * what it makes is drawn by the app that declared it.
1731
+ *
1732
+ * One read for every kind, the sweep {@link resolveAspectApp} already makes,
1733
+ * because nothing can ask for it by kind: a manifest's `k` tags name what it
1734
+ * draws, and Ship does not draw a Folder. Newest first, and **one manifest per
1735
+ * created kind**: an older manifest declaring the same kind on the same target
1736
+ * is a stale copy of the same claim, and offering both is two "New project"
1737
+ * rows. The owner is filtered out later ({@link borrowedFrom}), because who the
1738
+ * owner is depends on the object's author and this list does not.
1975
1739
  */
1976
- function orderingMs(event: SignedEvent): number {
1977
- const raw = Number.parseInt(tagValue(event, 'ts') ?? '', 10)
1978
- if (Number.isFinite(raw) && Math.abs(Math.floor(raw / 1000) - event.created_at) <= 1) return raw
1979
- return event.created_at * 1000
1740
+ async function creatorsOn(kind: number, query: QueryFn, cache?: ProjectionCache): Promise<readonly ResolvedManifest[]> {
1741
+ return throughCache(cache, `creators:${kind}`, async () => {
1742
+ const handlers = await query([{ kinds: [KIND_HANDLER_INFORMATION], limit: HANDLER_SWEEP_LIMIT }])
1743
+ const creators: ResolvedManifest[] = []
1744
+ const claimed = new Set<number>()
1745
+ for (const candidate of [...handlers].sort((a, b) => b.created_at - a.created_at)) {
1746
+ const manifest = parseManifest(candidate)
1747
+ if (!manifest) continue
1748
+ const makes = (manifest.actions ?? []).filter(
1749
+ (action) =>
1750
+ isCreationAction(action) &&
1751
+ asArray(action.appliesTo).includes(String(kind)) &&
1752
+ !!manifest.projections?.[String(action.emits.kind)] &&
1753
+ !claimed.has(action.emits.kind),
1754
+ )
1755
+ if (makes.length === 0) continue
1756
+ for (const action of makes) claimed.add(action.emits.kind)
1757
+ creators.push({
1758
+ // Only the creations: this manifest is what a consumer acts with, and
1759
+ // nothing it was not offered for must be buildable with it.
1760
+ manifest: { ...manifest, actions: makes },
1761
+ address: `${candidate.kind}:${candidate.pubkey}:${tagValue(candidate, 'd') ?? ''}`,
1762
+ viaRecommendation: false,
1763
+ webTemplate: webTemplate(candidate, 'naddr'),
1764
+ })
1765
+ }
1766
+ return creators
1767
+ })
1980
1768
  }
1981
1769
 
1982
- /** Total order, oldest first. Ties break on the lower event id (NIP-01's rule). */
1983
- function byOrder(a: SignedEvent, b: SignedEvent): number {
1984
- const [at, bt] = [orderingMs(a), orderingMs(b)]
1985
- if (at !== bt) return at - bt
1986
- return a.id < b.id ? -1 : a.id > b.id ? 1 : 0
1770
+ /**
1771
+ * {@link creatorsOn} for a read, where a failed sweep is no borrowed actions.
1772
+ *
1773
+ * The sweep is an addition to an object, not part of it: a relay that refuses
1774
+ * it (the meter is 300 reads a minute) must not take down a card whose own
1775
+ * read succeeded. Not remembered — `throughCache` never keeps a failure — so
1776
+ * the next resolve asks again. {@link resolveActingManifest} does not use
1777
+ * this: a write that cannot find its manifest should say so, not act with none.
1778
+ */
1779
+ function creatorsOrNone(kind: number, query: QueryFn, cache?: ProjectionCache): Promise<readonly ResolvedManifest[]> {
1780
+ return creatorsOn(kind, query, cache).catch(() => [])
1781
+ }
1782
+
1783
+ /**
1784
+ * {@link creatorsOn}, less the owner and less anything the owner makes itself.
1785
+ *
1786
+ * The owner's own actions are already on the object. And a kind the owner
1787
+ * creates here is the owner's to offer, so another manifest's claim to create
1788
+ * it — a staging copy of the same app, most likely — is dropped rather than
1789
+ * drawn as a second row.
1790
+ */
1791
+ function borrowedFrom(kind: number, owner: ResolvedManifest, creators: readonly ResolvedManifest[]): ResolvedManifest[] {
1792
+ const ownerMakes = new Set(
1793
+ (owner.manifest.actions ?? [])
1794
+ .filter((action) => isCreationAction(action) && asArray(action.appliesTo).includes(String(kind)))
1795
+ .map((action) => action.emits.kind),
1796
+ )
1797
+ return creators.flatMap((creator) => {
1798
+ if (creator.address === owner.address) return []
1799
+ const actions = (creator.manifest.actions ?? []).filter((action) => !ownerMakes.has(action.emits.kind))
1800
+ return actions.length ? [{ ...creator, manifest: { ...creator.manifest, actions } }] : []
1801
+ })
1802
+ }
1803
+
1804
+ /** Every borrowed creation, resolved as the owner's actions are, with its declaring app named. */
1805
+ function borrowedActions(kind: number, owner: ResolvedManifest, creators: readonly ResolvedManifest[]): ResolvedAction[] {
1806
+ return borrowedFrom(kind, owner, creators).flatMap((creator) =>
1807
+ resolveActions(creator.manifest, kind, {}).map((action) => ({
1808
+ ...action,
1809
+ declaredBy: { address: creator.address, ...(creator.manifest.name ? { appName: creator.manifest.name } : {}) },
1810
+ })),
1811
+ )
1812
+ }
1813
+
1814
+ /**
1815
+ * The manifest to build an action with — the object's own, or the one named by
1816
+ * the action's {@link ResolvedAction.declaredBy} (MAN-8).
1817
+ *
1818
+ * `declaredBy` omitted, or naming the owner, is exactly {@link resolveManifest}.
1819
+ * Otherwise the answer is that manifest **only if resolving the object would
1820
+ * have offered the action from it** — the same sweep, the same filtering — and
1821
+ * null if not. So a caller cannot act on a Folder with an arbitrary manifest by
1822
+ * naming its address; it can only act with one this module found declaring a
1823
+ * creation there. The manifest returned holds only those creations.
1824
+ */
1825
+ export async function resolveActingManifest(
1826
+ pointer: AddressPointer,
1827
+ declaredBy: string | undefined,
1828
+ query: QueryFn,
1829
+ cache?: ProjectionCache,
1830
+ ): Promise<ResolvedManifest | null> {
1831
+ const owner = await resolveManifest(pointer, query, cache)
1832
+ if (!owner || !declaredBy || declaredBy === owner.address) return owner
1833
+ const creators = await creatorsOn(pointer.kind, query, cache)
1834
+ return borrowedFrom(pointer.kind, owner, creators).find((creator) => creator.address === declaredBy) ?? null
1987
1835
  }
1988
1836
 
1989
1837
  /** Replay change events into current field values. Last write wins per field. */
@@ -3070,12 +2918,29 @@ export async function resolveForeignObject(
3070
2918
  const plan = planObject(naddr, pointer, resolved, depth)
3071
2919
  if (!plan) return null
3072
2920
 
3073
- const answered = await query(plan.filters)
2921
+ // Beside the object's own read, not after it: the sweep is cached, and cold
2922
+ // it would otherwise add a round trip to every resolve that pays for it.
2923
+ const [answered, creators] = await Promise.all([query(plan.filters), creatorsOrNone(pointer.kind, query, cache)])
3074
2924
  const followUp = childChangeFilters(plan, answered)
3075
2925
  const assembled = assembleObject(plan, answered, followUp.length ? await queryChunked(followUp, query) : [])
3076
2926
  if (assembled.object.unreachable) return assembled.object
3077
2927
  if (options.archivedWith) await markArchivedParents([{ object: assembled.object, manifest: resolved.manifest }], query)
3078
- return withPeople(assembled, await (lookupPeople ?? peopleViaRelay(query))(peopleOf(assembled)))
2928
+ return withBorrowed(
2929
+ withPeople(assembled, await (lookupPeople ?? peopleViaRelay(query))(peopleOf(assembled))),
2930
+ borrowedActions(pointer.kind, resolved, creators),
2931
+ )
2932
+ }
2933
+
2934
+ /**
2935
+ * The object's own actions, then the ones other apps declare on it (MAN-8).
2936
+ *
2937
+ * The object's only, not its children's: a child is drawn inside its parent's
2938
+ * card, and a creation offered on every issue in a project's list is a form
2939
+ * nobody opens from there. An unreachable object gets none either — it has no
2940
+ * Folder to create anything in.
2941
+ */
2942
+ function withBorrowed(object: ForeignObject, borrowed: ResolvedAction[]): ForeignObject {
2943
+ return borrowed.length ? { ...object, actions: [...object.actions, ...borrowed] } : object
3079
2944
  }
3080
2945
 
3081
2946
  /**
@@ -3161,7 +3026,14 @@ export async function resolveForeignObjects(
3161
3026
  planned.add(plan.address)
3162
3027
  filters.push(...plan.filters)
3163
3028
  }
3164
- const events = await queryChunked(filters, query)
3029
+ // Who else creates on each kind in the set (MAN-8): one sweep per kind, not
3030
+ // per object, read beside the objects themselves.
3031
+ const kinds = [...new Set(plans.map(({ plan }) => plan.pointer.kind))]
3032
+ const [events, creatorLists] = await Promise.all([
3033
+ queryChunked(filters, query),
3034
+ Promise.all(kinds.map((kind) => creatorsOrNone(kind, query, cache))),
3035
+ ])
3036
+ const creatorsByKind = new Map(kinds.map((kind, i) => [kind, creatorLists[i]]))
3165
3037
 
3166
3038
  // Every card's children's changes in one more read for the whole set, not
3167
3039
  // one per card (MAN-7) — and none at all when no card has a fold to read.
@@ -3185,7 +3057,7 @@ export async function resolveForeignObjects(
3185
3057
  const wanted = [...new Set(assembled.flatMap(({ built }) => peopleOf(built)))]
3186
3058
  const reachable = assembled.some(({ built }) => !built.object.unreachable)
3187
3059
  const people = reachable ? await (lookupPeople ?? peopleViaRelay(query))(wanted) : {}
3188
- for (const { reference, built } of assembled) {
3060
+ for (const { reference, plan, built } of assembled) {
3189
3061
  if (built.object.unreachable) {
3190
3062
  results[reference] = built.object
3191
3063
  continue
@@ -3195,7 +3067,10 @@ export async function resolveForeignObjects(
3195
3067
  // it happened to be resolved beside.
3196
3068
  const own: People = {}
3197
3069
  for (const key of peopleOf(built)) if (key in people) own[key] = people[key]
3198
- results[reference] = withPeople(built, own)
3070
+ results[reference] = withBorrowed(
3071
+ withPeople(built, own),
3072
+ borrowedActions(plan.pointer.kind, plan.resolved, creatorsByKind.get(plan.pointer.kind) ?? []),
3073
+ )
3199
3074
  }
3200
3075
  return results
3201
3076
  }
@@ -3457,10 +3332,10 @@ function assembleObject(plan: ObjectPlan, answered: SignedEvent[], childChanges:
3457
3332
 
3458
3333
  Then narrowed to §6.4's *comment* strength (CON-15): the `a` tag is also the
3459
3334
  index of a mention, and a mention is not this object's discussion. See
3460
- `isCommentOn` for the per-kind rule.
3335
+ `isCommentOn` (`@estiva-app/conversation`) for the per-kind rule.
3461
3336
  */
3462
3337
  const comments = events
3463
- .filter((e) => commentKinds.includes(e.kind) && isCommentOn(e, address))
3338
+ .filter((e) => commentKinds.includes(e.kind) && isCommentOn(e, address, commentKinds))
3464
3339
  .sort(byOrder)
3465
3340
  .map((e) => ({ id: e.id, author: e.pubkey, body: e.content, createdAt: e.created_at }))
3466
3341