@estiva-app/interop 0.41.0 → 0.43.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
@@ -1250,6 +1250,21 @@ export interface ResolvedManifest {
1250
1250
  */
1251
1251
  export const KIND_BARE_FILE = 30840
1252
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
+
1253
1268
  /**
1254
1269
  * The field that archives a file, whatever its kind — FOL-46.
1255
1270
  *
@@ -3075,6 +3090,103 @@ export async function resolveForeignObjects(
3075
3090
  return results
3076
3091
  }
3077
3092
 
3093
+ /**
3094
+ * The parent each file sits under, and nothing else — FOL-50.
3095
+ *
3096
+ * {@link resolveForeignObjects} answers this on the way to a whole object, and
3097
+ * for a caller that needs only the parent that is the wrong price: it reads
3098
+ * every object's comments and children too. Peek's Folder dots place an
3099
+ * issue's talk by its project, and on production on 2026-09-30 the 110 issues
3100
+ * the dots name cost 20 POSTs and a megabyte that way. This asks for the roots,
3101
+ * and for the changes only of a kind whose app declares a `movedBy` — a filter
3102
+ * per 100 roots and one per movable file, so a POST per ~120 files: one for the
3103
+ * set the dots held on production.
3104
+ *
3105
+ * Folded by the rule the card and the listing use (`parentRefOf`), so a moved
3106
+ * issue is under the project it was moved to here as everywhere else, and a
3107
+ * file is answered only when its app draws its kind — as it is by the object
3108
+ * readers.
3109
+ *
3110
+ * Keyed by the reference as given: the parent's address, or `null` for a file
3111
+ * at the top. **Absent** when there is nothing to tell — not an address, no
3112
+ * manifest, or a root this reader cannot see — because "at the top" and
3113
+ * "unknown" are different sentences.
3114
+ *
3115
+ * **A failed read rejects the whole call**, as {@link resolveForeignObjects}
3116
+ * does.
3117
+ */
3118
+ export async function resolveParents(
3119
+ references: readonly string[],
3120
+ query: QueryFn,
3121
+ /** See {@link ProjectionCache}. Omitting it still reads each app's manifest once per call. */
3122
+ cache?: ProjectionCache,
3123
+ ): Promise<Record<string, string | null>> {
3124
+ const results: Record<string, string | null> = {}
3125
+ const asked: { reference: string; pointer: AddressPointer }[] = []
3126
+ for (const reference of new Set(references)) {
3127
+ const pointer = addressPointerOf(reference)
3128
+ if (pointer) asked.push({ reference, pointer })
3129
+ }
3130
+ if (asked.length === 0) return results
3131
+
3132
+ const byApp = new Map<string, AddressPointer>()
3133
+ for (const { pointer } of asked) byApp.set(manifestKeyOf(pointer), pointer)
3134
+ const manifests = new Map<string, Manifest>()
3135
+ await Promise.all(
3136
+ [...byApp].map(async ([key, pointer]) => {
3137
+ const resolved = await resolveManifest(pointer, query, cache)
3138
+ if (resolved) manifests.set(key, resolved.manifest)
3139
+ }),
3140
+ )
3141
+
3142
+ // The roots by author and kind, the one filter shape that names many; the
3143
+ // moves by the app's change shape, only where the kind can be moved at all.
3144
+ const roots = new Map<string, { kind: number; pubkey: string; identifiers: Set<string> }>()
3145
+ const moves = new Map<string, { rule: RecordsRule; addresses: Set<string> }>()
3146
+ for (const { pointer } of asked) {
3147
+ const manifest = manifests.get(manifestKeyOf(pointer))
3148
+ if (!manifest?.projections?.[String(pointer.kind)]) continue
3149
+ const group = `${pointer.kind}:${pointer.pubkey}`
3150
+ const held = roots.get(group) ?? { kind: pointer.kind, pubkey: pointer.pubkey, identifiers: new Set<string>() }
3151
+ held.identifiers.add(pointer.identifier)
3152
+ roots.set(group, held)
3153
+ if (!manifest.records || !movedByOf(manifest, pointer.kind)) continue
3154
+ const shape = `${manifest.records.changeKind}:${manifest.records.targetTag}`
3155
+ const movable = moves.get(shape) ?? { rule: manifest.records, addresses: new Set<string>() }
3156
+ movable.addresses.add(pointerToAddress(pointer))
3157
+ moves.set(shape, movable)
3158
+ }
3159
+ const filters: Record<string, unknown>[] = []
3160
+ for (const { kind, pubkey, identifiers } of roots.values()) {
3161
+ const all = [...identifiers]
3162
+ for (let start = 0; start < all.length; start += PARENT_ROOT_GROUP) {
3163
+ const group = all.slice(start, start + PARENT_ROOT_GROUP)
3164
+ filters.push({ kinds: [kind], authors: [pubkey], '#d': group, limit: group.length })
3165
+ }
3166
+ }
3167
+ // One filter per file, with the object reader's own limit: a group sharing a
3168
+ // page could push an old move out of it behind newer statuses and edits, and
3169
+ // this would then disagree with `parentRef`.
3170
+ for (const { rule, addresses } of moves.values()) {
3171
+ for (const address of addresses) filters.push({ kinds: [rule.changeKind], [`#${rule.targetTag}`]: [address], limit: 500 })
3172
+ }
3173
+ if (filters.length === 0) return results
3174
+ const events = await queryChunked(filters, query)
3175
+
3176
+ for (const { reference, pointer } of asked) {
3177
+ const manifest = manifests.get(manifestKeyOf(pointer))
3178
+ if (!manifest?.projections?.[String(pointer.kind)]) continue
3179
+ const root = events
3180
+ .filter((e) => e.kind === pointer.kind && e.pubkey === pointer.pubkey && tagValue(e, 'd') === pointer.identifier)
3181
+ .sort(byOrder)
3182
+ .at(-1)
3183
+ if (!root) continue
3184
+ const folded = foldOf(events, pointerToAddress(pointer), manifest)
3185
+ results[reference] = parentRefOf(manifest, pointer.kind, root, folded) ?? null
3186
+ }
3187
+ return results
3188
+ }
3189
+
3078
3190
  /** What {@link resolveForeignObject} and {@link resolveForeignObjects} may read beyond the file itself. */
3079
3191
  export interface ArchiveReadOptions {
3080
3192
  /**
@@ -3139,6 +3251,13 @@ function relatedRuleOf(manifest: Pick<Manifest, 'records' | 'projections'> | und
3139
3251
  */
3140
3252
  const ARCHIVE_READ_GROUP = 25
3141
3253
 
3254
+ /**
3255
+ * Identifiers per root filter in {@link resolveParents}. A root read answers
3256
+ * one event per identifier, so it needs no room kept for a page — only a `#d`
3257
+ * list short enough for a relay to take.
3258
+ */
3259
+ const PARENT_ROOT_GROUP = 100
3260
+
3142
3261
  /**
3143
3262
  * The filters asking for every change naming these addresses, once per distinct
3144
3263
  * change shape among `rules` — SPEC's alone unless an app writes its own.
@@ -3253,6 +3372,7 @@ function planObject(
3253
3372
  ...(manifest.records ? [] : [{ kinds: [ARCHIVE_RULE.changeKind], '#a': [address], limit: 500 }]),
3254
3373
  { kinds: commentKinds, '#a': [address], limit: CONVERSATION_LIMIT },
3255
3374
  ...(childFilter ? [childFilter.filter] : []),
3375
+ ...(childFilter?.movedIn ? [childFilter.movedIn] : []),
3256
3376
  ]
3257
3377
  return { naddr, pointer, address, resolved, projection, records, commentKinds, childFilter, filters, openUrl }
3258
3378
  }
@@ -3536,7 +3656,10 @@ function childFilterFor(args: {
3536
3656
  manifest: Manifest
3537
3657
  pointer: AddressPointer
3538
3658
  depth: number
3539
- }): { filter: Record<string, unknown>; kind: number; via: string; parent: string; movedBy?: string } | null | undefined {
3659
+ }):
3660
+ | { filter: Record<string, unknown>; kind: number; via: string; parent: string; movedBy?: string; movedIn?: Record<string, unknown> }
3661
+ | null
3662
+ | undefined {
3540
3663
  const { projection, manifest, pointer, depth } = args
3541
3664
  const children = declaredChildSpec(projection)
3542
3665
  if (!children) return undefined
@@ -3552,6 +3675,7 @@ function childFilterFor(args: {
3552
3675
  ? pointer.identifier
3553
3676
  : pointerToAddress({ ...pointer, relays: [] })
3554
3677
 
3678
+ const movedBy = children.movedBy && children.match !== 'identifier' ? children.movedBy : undefined
3555
3679
  return {
3556
3680
  filter: { kinds: [children.kind], [`#${children.via}`]: [parent], limit: children.limit ?? 100 },
3557
3681
  kind: children.kind,
@@ -3559,10 +3683,38 @@ function childFilterFor(args: {
3559
3683
  parent,
3560
3684
  // This list's own, not whichever projection declares one for the kind — and
3561
3685
  // none on an identifier list, where a move's address never names the parent.
3562
- ...(children.movedBy && children.match !== 'identifier' ? { movedBy: children.movedBy } : {}),
3686
+ ...(movedBy ? { movedBy } : {}),
3687
+ // The children moved *in*: the moves naming this parent by `MOVED_TO_TAG`
3688
+ // (SPEC §7.2, FOL-45). A `#via` read cannot see them — their parent is in a
3689
+ // `value` — so without this a child moved here was drawn under nothing.
3690
+ ...(movedBy && manifest.records
3691
+ ? { movedIn: { kinds: [manifest.records.changeKind], [`#${MOVED_TO_TAG}`]: [parent], limit: children.limit ?? 100 } }
3692
+ : {}),
3563
3693
  }
3564
3694
  }
3565
3695
 
3696
+ /**
3697
+ * The addresses of children a pooled answer says were moved in to this parent:
3698
+ * the target of every change naming it by `MOVED_TO_TAG`, of the child kind.
3699
+ *
3700
+ * **A hint, never the answer.** A later move away names the *new* parent, not
3701
+ * this one, so a change found here may be stale; the child's own fold decides
3702
+ * (`childrenFrom`), exactly as it decides for a child created here.
3703
+ */
3704
+ function movedInAddressesOf(
3705
+ events: SignedEvent[],
3706
+ childFilter: NonNullable<ReturnType<typeof childFilterFor>>,
3707
+ records: Manifest['records'],
3708
+ ): string[] {
3709
+ if (!childFilter.movedIn || !records) return []
3710
+ const prefix = `${childFilter.kind}:`
3711
+ const targets = events
3712
+ .filter((e) => e.kind === records.changeKind && hasTagValue(e, MOVED_TO_TAG, childFilter.parent))
3713
+ .map((e) => tagValue(e, records.targetTag))
3714
+ .filter((address): address is string => !!address && address.startsWith(prefix))
3715
+ return [...new Set(targets)]
3716
+ }
3717
+
3566
3718
  /**
3567
3719
  * The child objects, picked back out of the merged result set.
3568
3720
  *
@@ -3591,8 +3743,20 @@ function childrenFrom(args: {
3591
3743
  if (!childProjection) return []
3592
3744
  const records = foldRuleOf(manifest)
3593
3745
  const { movedBy } = childFilter
3594
-
3595
- return childRootsOf(events, childFilter).flatMap((event) => {
3746
+ const created = childRootsOf(events, childFilter)
3747
+ const createdAddresses = new Set(created.map(childAddressOf))
3748
+ // Moved in: the roots `childChangeFilters` read for the moves naming this parent,
3749
+ // newest version of each, and only those not already found as created here.
3750
+ const movedIn = new Set(movedInAddressesOf(events, childFilter, manifest.records).filter((a) => !createdAddresses.has(a)))
3751
+ const movedInRoots = new Map<string, SignedEvent>()
3752
+ for (const event of childChanges) {
3753
+ const address = event.kind === childFilter.kind ? childAddressOf(event) : undefined
3754
+ if (!address || !movedIn.has(address)) continue
3755
+ const current = movedInRoots.get(address)
3756
+ if (!current || event.created_at > current.created_at) movedInRoots.set(address, event)
3757
+ }
3758
+
3759
+ return [...created, ...[...movedInRoots.values()].sort(byOrder)].flatMap((event) => {
3596
3760
  const address = childAddressOf(event)
3597
3761
  /*
3598
3762
  The child's own fold — MAN-7. Until this, a card's children were built
@@ -3610,12 +3774,14 @@ function childrenFrom(args: {
3610
3774
  found the child.
3611
3775
  - **hidden** by the app's own `hiddenWhen`, or **archived** (FOL-46).
3612
3776
 
3613
- A child moved *in* is not found here and cannot be: its new parent is in
3614
- a `value`, which no relay indexes. SPEC §7.2 names the Folder listing as
3615
- the only read that sees one.
3777
+ - **moved in** and since moved on, or never really here — FOL-45. A
3778
+ child found by its move's `MOVED_TO_TAG` has no `via` naming this
3779
+ parent, so only a folded value that names it keeps it: the tag is how
3780
+ it was found, not proof that it is still here.
3616
3781
  */
3617
3782
  const folded = address ? foldOf(childChanges, address, manifest) : {}
3618
3783
  if (movedBy && folded[movedBy] && folded[movedBy].value !== childFilter.parent) return []
3784
+ if (address && movedIn.has(address) && folded[movedBy!]?.value !== childFilter.parent) return []
3619
3785
  if (records.hiddenWhen && folded[records.hiddenWhen.field]?.value === records.hiddenWhen.equals) return []
3620
3786
  if (address && manifest.records && archiveOf(childChanges, address, records)) return []
3621
3787
  return [
@@ -3672,8 +3838,21 @@ function childChangeFilters(plan: ObjectPlan, answered: SignedEvent[]): Record<s
3672
3838
  if (!answered.some((e) => e.kind === pointer.kind && e.pubkey === pointer.pubkey && tagValue(e, 'd') === pointer.identifier)) {
3673
3839
  return []
3674
3840
  }
3675
- const addresses = [...new Set(childRootsOf(answered, childFilter).flatMap((e) => childAddressOf(e) ?? []))]
3676
- return addresses.length ? archiveFilters(addresses, [records], CHILD_CHANGE_GROUP) : []
3841
+ const created = childRootsOf(answered, childFilter).flatMap((e) => childAddressOf(e) ?? [])
3842
+ // Moved in (FOL-45): found by their moves, so their roots are not in the answer
3843
+ // yet. They are read here with the changes, in the same POST, and folded the same.
3844
+ const movedIn = movedInAddressesOf(answered, childFilter, records).filter((address) => !created.includes(address))
3845
+ const addresses = [...new Set([...created, ...movedIn])]
3846
+ const roots = new Map<string, string[]>()
3847
+ for (const address of movedIn) {
3848
+ // A `d` may itself hold ':' — everything after the pubkey is the identifier.
3849
+ const [, pubkey, ...rest] = address.split(':')
3850
+ roots.set(pubkey, [...(roots.get(pubkey) ?? []), rest.join(':')])
3851
+ }
3852
+ return [
3853
+ ...(addresses.length ? archiveFilters(addresses, [records], CHILD_CHANGE_GROUP) : []),
3854
+ ...[...roots].map(([pubkey, identifiers]) => ({ kinds: [childFilter.kind], authors: [pubkey], '#d': identifiers, limit: identifiers.length })),
3855
+ ]
3677
3856
  }
3678
3857
 
3679
3858
  /** Addresses per filter when reading a card's children's changes — see {@link childChangeFilters}. */
@@ -4815,6 +4994,16 @@ function buildOneActionEvent(args: ActionEventArgs): UnsignedActionEvent | strin
4815
4994
  // depending on which app you asked (FRICTION.md A6).
4816
4995
  if (records.order?.includes('ts')) tags.push(['ts', String(args.createdAtMs)])
4817
4996
  tags.push(...files)
4997
+ // A move also names its new parent where a relay indexes it (SPEC §7.2, FOL-45):
4998
+ // `value` is not indexed, so without this no read by the new parent finds a
4999
+ // child moved in. Only for the field the kind declares as `movedBy`, and only
5000
+ // for an address of the declaring kind (any kind for a bare file) — a move to
5001
+ // the top names no parent, and a value of another kind names none either.
5002
+ const moved = declared.emits.field ? movedByOf(manifest, kind) : undefined
5003
+ const parentAddress = moved?.parentKind === undefined ? /^\d+:[0-9a-f]{64}:/ : new RegExp(`^${moved.parentKind}:[0-9a-f]{64}:`)
5004
+ if (moved?.field === declared.emits.field && typeof value === 'string' && parentAddress.test(value)) {
5005
+ tags.push([MOVED_TO_TAG, value])
5006
+ }
4818
5007
 
4819
5008
  return {
4820
5009
  pubkey: args.pubkey,