@estiva-app/interop 0.45.0 → 0.47.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
@@ -1244,7 +1244,7 @@ export interface ResolvedManifest {
1244
1244
  /**
1245
1245
  * The bare file — `kind:30840`, SPEC §6.7, decided in RFC 0.5 §10.7.
1246
1246
  *
1247
- * A file **no app owns**: a `d`, a `title`, the `h` of the team it lives in, at
1247
+ * A file **no app owns**: a `d`, a `title`, the `h` of the Folder it lives in, at
1248
1248
  * most one `a` naming the file it sits under, and a §13.3 block document (or
1249
1249
  * nothing) for content. A Peek topic is one. Typed kinds — a project, an issue
1250
1250
  * — add properties on top of this; the bare file adds none, which is exactly
@@ -1374,7 +1374,7 @@ const BARE_FILE_MANIFEST: Manifest = {
1374
1374
 
1375
1375
  `rename` is a `kind:1851` change to the `title` field, not a re-publish of
1376
1376
  the `30840`. The title slot already folds `title`, so a rename by anyone in
1377
- the team lands for every reader the way a re-parent does; a re-publish
1377
+ the Folder lands for every reader the way a re-parent does; a re-publish
1378
1378
  could only ever be the author's, because a `30840` from another pubkey is a
1379
1379
  different address and not a refusal. `delete` is NIP-09's `kind:5` naming
1380
1380
  the address — the relay decides who may (the author, or the owner of an
@@ -1386,7 +1386,7 @@ const BARE_FILE_MANIFEST: Manifest = {
1386
1386
  id: 'comment',
1387
1387
  label: 'Comment',
1388
1388
  description:
1389
- 'Say something about this file. The comment lands in the team Folder the file lives in, ' +
1389
+ 'Say something about this file. The comment lands in the Folder the file lives in, ' +
1390
1390
  'and is what every reader of the file sees under it.',
1391
1391
  effect: 'writes',
1392
1392
  appliesTo: [String(KIND_BARE_FILE)],
@@ -1397,7 +1397,7 @@ const BARE_FILE_MANIFEST: Manifest = {
1397
1397
  id: 'rename',
1398
1398
  label: 'Rename',
1399
1399
  description:
1400
- 'Give this file a new title. A change event, so anyone in the team may, and every app ' +
1400
+ 'Give this file a new title. A change event, so anyone in the Folder may, and every app ' +
1401
1401
  'reading the file folds it into the title.',
1402
1402
  effect: 'writes',
1403
1403
  appliesTo: [String(KIND_BARE_FILE)],
@@ -1407,16 +1407,16 @@ const BARE_FILE_MANIFEST: Manifest = {
1407
1407
  /*
1408
1408
  `move` is the `parent` field SPEC §6.7 already defines, declared so a
1409
1409
  consumer draws the control from here as it draws Rename (FOL-4). The value
1410
- is the new parent's address, or empty for the top of the team. A move
1410
+ is the new parent's address, or empty for the top of the Folder. A move
1411
1411
  never changes `h`: nesting organises and never grants access, so a file
1412
- moved under another stays readable by exactly the team it was.
1412
+ moved under another stays readable by exactly the people it was.
1413
1413
  */
1414
1414
  {
1415
1415
  id: 'move',
1416
1416
  label: 'Move',
1417
1417
  description:
1418
- "Put this file under another file in the same team, or back at the top. A change event, so anyone in " +
1419
- 'the team may; who can read the file does not change.',
1418
+ "Put this file under another file in the same Folder, or back at the top. A change event, so anyone in " +
1419
+ 'the Folder may; who can read the file does not change.',
1420
1420
  effect: 'writes',
1421
1421
  appliesTo: [String(KIND_BARE_FILE)],
1422
1422
  emits: { kind: 1851, field: 'parent' },
@@ -1425,7 +1425,7 @@ const BARE_FILE_MANIFEST: Manifest = {
1425
1425
  /*
1426
1426
  `archive` is the one field every file may carry (FOL-46): `true` hides the
1427
1427
  file and everything under it from every list, an empty value brings it
1428
- back. A change, so anyone in the team may, and the archiving change's
1428
+ back. A change, so anyone in the Folder may, and the archiving change's
1429
1429
  `content` is the resolution summary a person gave (`ActionEventArgs.note`).
1430
1430
  */
1431
1431
  {
@@ -2093,8 +2093,24 @@ export function isArchived(file: { archived?: Archive } | null | undefined): boo
2093
2093
  * `changes` may hold any events; only this rule's change kind, naming this
2094
2094
  * address, setting this field, is read. Last write wins, by the same order as
2095
2095
  * every other field.
2096
+ *
2097
+ * **A Folder is the exception** (SPEC §3.2): on a `kind:39000` address only a
2098
+ * change in the Folder's own `h` by one of `folderAdmins` — the owners and
2099
+ * admins on its relay-signed `kind:39001` — counts. A caller that has not read
2100
+ * the admin list passes none, and then no change counts: a Folder shown live
2101
+ * when it is archived is recoverable, one any member could hide is not.
2096
2102
  */
2097
- function archiveOf(changes: SignedEvent[], address: string, rule: RecordsRule): Archive | undefined {
2103
+ function archiveOf(
2104
+ changes: SignedEvent[],
2105
+ address: string,
2106
+ rule: RecordsRule,
2107
+ folderAdmins?: ReadonlySet<string>,
2108
+ ): Archive | undefined {
2109
+ const [kind, , folderId] = address.split(':')
2110
+ if (Number(kind) === KIND_CHANNEL) {
2111
+ if (!folderAdmins?.size) return undefined
2112
+ changes = changes.filter((change) => tagValue(change, 'h') === folderId && folderAdmins.has(change.pubkey))
2113
+ }
2098
2114
  let last: SignedEvent | undefined
2099
2115
  for (const change of changes) {
2100
2116
  // The target is the first target tag, as every other fold reads it: a
@@ -3243,6 +3259,60 @@ export function projectEvents(
3243
3259
  })
3244
3260
  }
3245
3261
 
3262
+ /**
3263
+ * The objects at a set of addresses, as their roots and changes alone draw
3264
+ * them — PEE-21.
3265
+ *
3266
+ * For a reader that needs what a file *is* now (its folded title, status,
3267
+ * parent, own archive) and not what is said about it: {@link projectEvents}
3268
+ * over each address's root and change filters — the same two
3269
+ * {@link resolveForeignObjects} sends — without the comments, children and
3270
+ * people that make up most of that call's bytes. `[` reads a search answer's
3271
+ * hits through this on every pause in typing.
3272
+ *
3273
+ * An address whose root the reader is not handed is simply absent, so a file
3274
+ * in a Folder they cannot read never comes back. A failed read rejects.
3275
+ */
3276
+ export async function resolveForeignRoots(
3277
+ references: readonly string[],
3278
+ query: QueryFn,
3279
+ cache?: ProjectionCache,
3280
+ ): Promise<ForeignObject[]> {
3281
+ const pointers = new Map<string, AddressPointer>()
3282
+ for (const reference of references) {
3283
+ const pointer = addressPointerOf(reference)
3284
+ if (pointer) pointers.set(`${pointer.kind}:${pointer.pubkey}:${pointer.identifier}`, pointer)
3285
+ }
3286
+ if (pointers.size === 0) return []
3287
+
3288
+ const manifests = new Map<string, ResolvedManifest>()
3289
+ const byApp = new Map<string, AddressPointer>()
3290
+ for (const pointer of pointers.values()) byApp.set(manifestKeyOf(pointer), pointer)
3291
+ await Promise.all(
3292
+ [...byApp].map(async ([key, pointer]) => {
3293
+ const resolved = await resolveManifest(pointer, query, cache)
3294
+ if (resolved) manifests.set(key, resolved)
3295
+ }),
3296
+ )
3297
+
3298
+ const filters: Record<string, unknown>[] = []
3299
+ for (const [address, pointer] of pointers) {
3300
+ const resolved = manifests.get(manifestKeyOf(pointer))
3301
+ if (!resolved?.manifest.projections?.[String(pointer.kind)]) continue
3302
+ // A manifest without `records` folds by a placeholder kind 0, never sent.
3303
+ const changeKinds = new Set(
3304
+ [foldRuleOf(resolved.manifest).changeKind, archiveRuleOf(resolved.manifest).changeKind].filter((k) => k !== 0),
3305
+ )
3306
+ filters.push(
3307
+ { kinds: [pointer.kind], authors: [pointer.pubkey], '#d': [pointer.identifier], limit: 1 },
3308
+ { kinds: [...changeKinds], '#a': [address], limit: 500 },
3309
+ )
3310
+ }
3311
+ if (filters.length === 0) return []
3312
+ const events = await queryChunked(filters, query)
3313
+ return projectEvents(events, (pointer) => manifests.get(manifestKeyOf(pointer)))
3314
+ }
3315
+
3246
3316
  /**
3247
3317
  * The parent each file sits under, and nothing else — FOL-50.
3248
3318
  *
@@ -4236,6 +4306,17 @@ function isDone(stage: Stage | undefined, raw: string | undefined, label: string
4236
4306
  return isDoneStatusByLabel(raw, label)
4237
4307
  }
4238
4308
 
4309
+ /**
4310
+ * Is a resolved `status` slot finished work — done or dropped — by its words?
4311
+ *
4312
+ * For a consumer holding only the object, not its manifest: the declared stage
4313
+ * is not on a {@link ResolvedSlot}, so this is the word-list fallback alone.
4314
+ * `[` uses it to put a closed issue after an open one (PEE-21).
4315
+ */
4316
+ export function isClosedStatus(slot: ResolvedSlot | undefined): boolean {
4317
+ return slot !== undefined && isDoneStatusByLabel(slot.value, slot.label)
4318
+ }
4319
+
4239
4320
  function isOpen(stage: Stage | undefined, raw: string | undefined, label: string | undefined) {
4240
4321
  if (stage) return stage === 'open' || stage === 'started'
4241
4322
  return isOpenStatusByLabel(raw, label)
@@ -5207,15 +5288,46 @@ export const KIND_FOLDER_STATE = 30890
5207
5288
  /**
5208
5289
  * NIP-29 group metadata — the Folder's channel.
5209
5290
  *
5210
- * Named here for two unrelated jobs: it carries the folder's `name` before any
5211
- * folder state exists, and its own address is what makes a Peek topic a file
5212
- * like any other (§5.2).
5291
+ * Named here for two unrelated jobs: it carries the Folder's title — its
5292
+ * `name`, and only that (SPEC §3.2) — and its own address is what makes a Peek
5293
+ * topic a file like any other (§5.2).
5213
5294
  */
5214
5295
  const KIND_CHANNEL = 39000
5215
5296
 
5297
+ /** NIP-29 group admins — the relay's list of who holds which role in a channel. */
5298
+ const KIND_CHANNEL_ADMINS = 39001
5299
+
5300
+ /** The roles on a `kind:39001` that may rename a Folder, and so archive it (SPEC §3.2). */
5301
+ const FOLDER_ADMIN_ROLES = new Set(['owner', 'admin'])
5302
+
5216
5303
  /** The `name` tag, when there is an event to read it off at all. */
5217
5304
  const nameOf = (event: SignedEvent | undefined) => (event ? tagValue(event, 'name') : undefined)
5218
5305
 
5306
+ /**
5307
+ * The owners and admins a `kind:39001` lists — kept only when the channel's own
5308
+ * signer, the relay, signed it: anybody can publish an event of that shape.
5309
+ */
5310
+ function folderAdminsOf(admins: SignedEvent | undefined, channel: SignedEvent | undefined): string[] {
5311
+ if (!admins || !channel || admins.pubkey !== channel.pubkey) return []
5312
+ return [
5313
+ ...new Set(
5314
+ admins.tags
5315
+ .filter((tag) => tag[0] === 'p' && tag[1] && tag.slice(2).some((role) => FOLDER_ADMIN_ROLES.has(role)))
5316
+ .map((tag) => tag[1]),
5317
+ ),
5318
+ ]
5319
+ }
5320
+
5321
+ /**
5322
+ * A Folder's own archive (SPEC §3.2): the `archived` changes on its channel's
5323
+ * address, counting only one carrying the Folder's own `h` whose author the
5324
+ * relay lists as its owner or admin. From anybody else the relay accepts the
5325
+ * change, and it means nothing.
5326
+ */
5327
+ function folderArchiveOf(changes: SignedEvent[], folder: Pick<FolderSummary, 'id' | 'channel' | 'admins'>): Archive | undefined {
5328
+ return folder.channel ? archiveOf(changes, folder.channel, ARCHIVE_RULE, new Set(folder.admins ?? [])) : undefined
5329
+ }
5330
+
5219
5331
  /** One folder, enough to draw a sidebar row. */
5220
5332
  export interface FolderSummary {
5221
5333
  /**
@@ -5224,17 +5336,33 @@ export interface FolderSummary {
5224
5336
  * measured across all of production's channels).
5225
5337
  */
5226
5338
  id: string
5339
+ /**
5340
+ * The title: its `kind:39000`'s `name`, and only that (SPEC §3.2). A `name`
5341
+ * an older `kind:1852` left on the state is never read — any member may send
5342
+ * one, and only owners and admins may rename the channel.
5343
+ */
5227
5344
  name?: string
5228
5345
  /** True once the relay maintains state for it, rather than it being a bare channel. */
5229
5346
  hasState: boolean
5347
+ /**
5348
+ * Present when the Folder's relay-signed `kind:39000` carries `["private"]`
5349
+ * (NIP-29). What `planMoveFile` reads as `FolderRef.private`.
5350
+ */
5351
+ private?: true
5352
+ /**
5353
+ * Who may rename and archive it: the owners and admins on its relay-signed
5354
+ * `kind:39001`. Offer Archive only to them — a reader ignores an archive from
5355
+ * anybody else (§3.2). Absent when the relay returned no admin list.
5356
+ */
5357
+ admins?: string[]
5230
5358
  /**
5231
5359
  * The folders whose state lists this one as a file — present only when there
5232
5360
  * are any.
5233
5361
  *
5234
5362
  * A channel is addressable (§5.2), so a folder can be placed inside another
5235
5363
  * the way any file is, and Peek's topics are (FOL-22): each is a channel
5236
- * listed by its team's state. A sidebar that drew every channel as a top-level
5237
- * folder would show the team and, beside it, every topic in it. This is what
5364
+ * listed by its Folder's state. A sidebar that drew every channel as a top-level
5365
+ * folder would show the Folder and, beside it, every topic in it. This is what
5238
5366
  * lets a consumer tell the two apart without reading any folder's contents:
5239
5367
  * `listFolders` already holds every state, so the answer is free.
5240
5368
  */
@@ -5246,7 +5374,7 @@ export interface FolderSummary {
5246
5374
  * `listedIn` in the other direction, and free for the same reason: the
5247
5375
  * states are already in hand. It is the unresolved list — a row that names
5248
5376
  * an archived or unreachable record is still here — so a consumer that
5249
- * draws one app's own records under a folder (Ship's projects under a team,
5377
+ * draws one app's own records under a folder (Ship's projects under a Folder,
5250
5378
  * FOL-5) intersects it with the records it holds, and a consumer that draws
5251
5379
  * another app's files resolves them with {@link resolveFolderContents}.
5252
5380
  */
@@ -5284,7 +5412,7 @@ export interface FolderSummary {
5284
5412
  * never gets; and a folder another one lists (`listedIn`) is a row inside
5285
5413
  * that one, not a section beside it.
5286
5414
  *
5287
- * Not a list of ids: a new team is a folder somebody creates, not a code
5415
+ * Not a list of ids: a new Folder is a folder somebody creates, not a code
5288
5416
  * change. Moved here from Peek and Ship, which each held the same line.
5289
5417
  *
5290
5418
  * An archived Folder is not navigated by (FOL-46), and a listing that has not
@@ -5329,8 +5457,8 @@ export interface FolderContents extends FolderSummary {
5329
5457
  * Every folder this identity can see, for a sidebar.
5330
5458
  *
5331
5459
  * Both shapes in one pass: folders the relay maintains state for, and bare
5332
- * channels that have none yet. A channel with state appears once, named by its
5333
- * state — the folder's name is the folder's to say.
5460
+ * channels that have none yet. A channel with state appears once, titled by its
5461
+ * `kind:39000` (SPEC §3.2), with the owners and admins its `kind:39001` lists.
5334
5462
  *
5335
5463
  * **A direct route, deliberately.** §4.2's post-mortem on REW-11 is that
5336
5464
  * discovering children only through their parent loses them when the parent
@@ -5341,27 +5469,36 @@ export async function listFolders(query: QueryFn): Promise<FolderSummary[]> {
5341
5469
  const events = await query([
5342
5470
  { kinds: [KIND_FOLDER_STATE], limit: 500 },
5343
5471
  { kinds: [KIND_CHANNEL], limit: 500 },
5472
+ { kinds: [KIND_CHANNEL_ADMINS], limit: 500 },
5344
5473
  ])
5345
5474
  const byId = new Map<string, FolderSummary>()
5475
+ const channelOf = new Map<string, SignedEvent>()
5476
+ const adminsOf = new Map<string, SignedEvent>()
5346
5477
  for (const event of events) {
5347
5478
  const id = tagValue(event, 'd')
5348
5479
  if (!id) continue
5480
+ if (event.kind === KIND_CHANNEL) channelOf.set(id, event)
5481
+ if (event.kind === KIND_CHANNEL_ADMINS) adminsOf.set(id, event)
5482
+ if (event.kind !== KIND_FOLDER_STATE && event.kind !== KIND_CHANNEL) continue
5349
5483
  const state = event.kind === KIND_FOLDER_STATE
5350
5484
  const existing = byId.get(id)
5351
- // State wins over the channel for the name, whichever order they arrived.
5352
- if (existing && !state) continue
5353
- const addresses = state ? event.tags.filter((tag) => tag[0] === 'a' && tag[1]).map((tag) => tag[1]) : []
5485
+ const addresses = state ? event.tags.filter((tag) => tag[0] === 'a' && tag[1]).map((tag) => tag[1]) : (existing?.addresses ?? [])
5354
5486
  byId.set(id, {
5355
5487
  id,
5356
- name: tagValue(event, 'name') ?? existing?.name,
5357
5488
  hasState: state || (existing?.hasState ?? false),
5358
5489
  ...(addresses.length ? { addresses } : {}),
5359
5490
  })
5360
5491
  }
5361
- for (const event of events) {
5362
- const id = tagValue(event, 'd')
5363
- const folder = id && event.kind === KIND_CHANNEL ? byId.get(id) : undefined
5364
- if (folder) folder.channel = pointerToAddress({ kind: KIND_CHANNEL, pubkey: event.pubkey, identifier: id!, relays: [] })
5492
+ // The title, privacy and admins are the channel's (§3.2), whichever order the events arrived.
5493
+ for (const [id, folder] of byId) {
5494
+ const channel = channelOf.get(id)
5495
+ if (!channel) continue
5496
+ const name = nameOf(channel)
5497
+ if (name !== undefined) folder.name = name
5498
+ if (channel.tags.some((tag) => tag[0] === 'private')) folder.private = true
5499
+ const admins = folderAdminsOf(adminsOf.get(id), channel)
5500
+ if (admins.length) folder.admins = admins
5501
+ folder.channel = pointerToAddress({ kind: KIND_CHANNEL, pubkey: channel.pubkey, identifier: id, relays: [] })
5365
5502
  }
5366
5503
  /*
5367
5504
  A folder listed in another folder's state is a file there. Read off the
@@ -5398,13 +5535,13 @@ export async function listFolders(query: QueryFn): Promise<FolderSummary[]> {
5398
5535
  *
5399
5536
  * A Folder is archived by a change naming its channel's address, the way any
5400
5537
  * file is. A record's channel — a Ship project's conversation — is archived
5401
- * with its record, so an archived project's channel stops lighting its team's
5538
+ * with its record, so an archived project's channel stops lighting its Folder's
5402
5539
  * dot the way the project stopped being listed — only when every record naming
5403
5540
  * the channel is archived, since two projects may share one. Its own archive
5404
5541
  * wins when it has one.
5405
5542
  *
5406
5543
  * A refused read throws before this, like the reads beside it: a listing that
5407
- * silently reported every Folder live would put archived teams back in
5544
+ * silently reported every Folder live would put archived Folders back in
5408
5545
  * everyone's sidebar.
5409
5546
  */
5410
5547
  function markArchivedFolders(
@@ -5413,7 +5550,7 @@ function markArchivedFolders(
5413
5550
  changes: SignedEvent[],
5414
5551
  ): void {
5415
5552
  for (const folder of byId.values()) {
5416
- const own = folder.channel ? archiveOf(changes, folder.channel, ARCHIVE_RULE) : undefined
5553
+ const own = folderArchiveOf(changes, folder)
5417
5554
  if (own) {
5418
5555
  folder.archived = own
5419
5556
  continue
@@ -5586,13 +5723,13 @@ async function countLiveChildren(
5586
5723
  * names the channel its conversation lives in with {@link folderOf}'s tags. No
5587
5724
  * state lists that channel, so without this `listFolders` reports it placed
5588
5725
  * nowhere, and a consumer folding an unread verdict into the containers of a
5589
- * channel (Peek's team dot) has nowhere to fold it: correct, and drawn
5726
+ * channel (Peek's Folder dot) has nowhere to fold it: correct, and drawn
5590
5727
  * nowhere. Measured on production 2026-09-22: of the 43 records the six
5591
5728
  * states list, 23 name a channel other than the state's own and no state lists
5592
5729
  * any of them. This places 21 channels and moves no top-level Folder.
5593
5730
  *
5594
5731
  * Derived rather than published, so it cannot drift: a `kind:1852` adding each
5595
- * channel to its team would have to be repeated by every app that places a
5732
+ * channel to its Folder would have to be repeated by every app that places a
5596
5733
  * record, and would stay wrong the first time one did not.
5597
5734
  *
5598
5735
  * Both of `folderOf`'s spellings, because production has both — about half of
@@ -5617,7 +5754,7 @@ async function countLiveChildren(
5617
5754
  * production that was the bug it was meant to prevent: Peek reads the listing
5618
5755
  * once per page load, the load is when the relay's budget is most contested,
5619
5756
  * and one refused read on 2026-09-22 left a project's channel unplaced for the
5620
- * whole session — the team's dot dark, and nothing anywhere saying why. A
5757
+ * whole session — the Folder's dot dark, and nothing anywhere saying why. A
5621
5758
  * listing missing placements looks exactly like a correct one, so only the
5622
5759
  * caller can recover, and only if it is told. Keeping the last good listing
5623
5760
  * and retrying is the caller's to do.
@@ -5697,7 +5834,7 @@ async function placeRecordChannels(
5697
5834
  const channel = root && folderOf(root)
5698
5835
  if (!channel || byId.get(channel)?.hasState) continue
5699
5836
  // A file published into the Folder that lists it names that Folder, and
5700
- // does not own it: a topic's `h` is its team's.
5837
+ // does not own it: a topic's `h` is its Folder's.
5701
5838
  if (!containers.includes(channel)) recordsOf.set(channel, [...(recordsOf.get(channel) ?? []), key])
5702
5839
  for (const container of containers) {
5703
5840
  if (container === channel) continue
@@ -5773,17 +5910,24 @@ export async function resolveFolderContents(
5773
5910
  const identity = await query([
5774
5911
  { kinds: [KIND_FOLDER_STATE], '#d': [folder], limit: 1 },
5775
5912
  { kinds: [KIND_CHANNEL], '#d': [folder], limit: 1 },
5913
+ { kinds: [KIND_CHANNEL_ADMINS], '#d': [folder], limit: 1 },
5776
5914
  ])
5777
5915
  const state = identity.find((e) => e.kind === KIND_FOLDER_STATE && tagValue(e, 'd') === folder)
5778
5916
  const channel = identity.find((e) => e.kind === KIND_CHANNEL && tagValue(e, 'd') === folder)
5917
+ const admins = folderAdminsOf(
5918
+ identity.find((e) => e.kind === KIND_CHANNEL_ADMINS && tagValue(e, 'd') === folder),
5919
+ channel,
5920
+ )
5779
5921
  const channelAddress = channel
5780
5922
  ? pointerToAddress({ kind: KIND_CHANNEL, pubkey: channel.pubkey, identifier: folder, relays: [] })
5781
5923
  : undefined
5782
5924
 
5783
5925
  const summary: FolderSummary & { address?: string } = {
5784
5926
  id: folder,
5785
- name: nameOf(state) ?? nameOf(channel),
5927
+ name: nameOf(channel),
5786
5928
  hasState: !!state,
5929
+ ...(channel?.tags.some((tag) => tag[0] === 'private') ? { private: true as const } : {}),
5930
+ ...(admins.length ? { admins } : {}),
5787
5931
  ...(channelAddress ? { channel: channelAddress } : {}),
5788
5932
  ...(state
5789
5933
  ? { address: pointerToAddress({ kind: state.kind, pubkey: state.pubkey, identifier: folder, relays: [] }) }
@@ -5802,9 +5946,7 @@ export async function resolveFolderContents(
5802
5946
  if (addresses.length === 0) {
5803
5947
  // Nothing listed, so no change query to ride on: the Folder's own archive
5804
5948
  // is one small read of its own.
5805
- const archived = channelAddress
5806
- ? archiveOf(await readArchiveChanges([channelAddress], query), channelAddress, ARCHIVE_RULE)
5807
- : undefined
5949
+ const archived = channelAddress ? folderArchiveOf(await readArchiveChanges([channelAddress], query), summary) : undefined
5808
5950
  return { ...summary, ...(archived ? { archived } : {}), files: [], source: state ? 'state' : 'channel' }
5809
5951
  }
5810
5952
 
@@ -5854,6 +5996,7 @@ export async function resolveFolderContents(
5854
5996
  ...[...manifests.values()].flatMap((r) => (r.manifest.records ? [r.manifest.records.changeKind] : [])),
5855
5997
  ]),
5856
5998
  ]
5999
+ const nestedFolderIds = pointers.filter(({ pointer }) => pointer.kind === KIND_CHANNEL).map(({ pointer }) => pointer.identifier)
5857
6000
  const events = await query([
5858
6001
  ...[...groups.values()].map(({ pointer, addresses: group }) => ({
5859
6002
  kinds: [pointer.kind],
@@ -5867,8 +6010,10 @@ export async function resolveFolderContents(
5867
6010
  // changes for every file together, and one Folder has already had 688.
5868
6011
  // Same request.
5869
6012
  ...archiveFilters(channelAddress ? [...addresses, channelAddress] : addresses),
6013
+ // A Folder listed here counts its archive only from its own admins (§3.2). Same request.
6014
+ ...(nestedFolderIds.length ? [{ kinds: [KIND_CHANNEL_ADMINS], '#d': nestedFolderIds, limit: nestedFolderIds.length }] : []),
5870
6015
  ])
5871
- const ownArchive = channelAddress ? archiveOf(events, channelAddress, ARCHIVE_RULE) : undefined
6016
+ const ownArchive = folderArchiveOf(events, summary)
5872
6017
  if (ownArchive) summary.archived = ownArchive
5873
6018
 
5874
6019
  // 4. Build each file, in the order the folder listed them. Archived files are
@@ -5895,7 +6040,16 @@ export async function resolveFolderContents(
5895
6040
  events.filter((e) => e.kind === records.changeKind && hasTagValue(e, records.targetTag, address)),
5896
6041
  records,
5897
6042
  )
5898
- const archive = archiveOf(events, address, archiveRuleOf(resolved.manifest))
6043
+ const nestedAdmins =
6044
+ pointer.kind === KIND_CHANNEL
6045
+ ? new Set(
6046
+ folderAdminsOf(
6047
+ events.find((e) => e.kind === KIND_CHANNEL_ADMINS && tagValue(e, 'd') === pointer.identifier),
6048
+ root,
6049
+ ),
6050
+ )
6051
+ : undefined
6052
+ const archive = archiveOf(events, address, archiveRuleOf(resolved.manifest), nestedAdmins)
5899
6053
  archiveByAddress.set(address, archive)
5900
6054
  const parent = parentRefOf(resolved.manifest, pointer.kind, root, folded)
5901
6055
  parentByAddress.set(address, parent)
@@ -5916,7 +6070,7 @@ export async function resolveFolderContents(
5916
6070
  the file is here; if the fold has moved on, somebody has since placed it
5917
6071
  somewhere else and this folder is holding a statement that has been
5918
6072
  superseded, which an append-only stream cannot retract. Ship linking a
5919
- project to a second team is the case: the first team's Folder keeps the
6073
+ project to a second Folder is the case: the first Folder keeps the
5920
6074
  old statement for ever, and without this check would list the project
5921
6075
  for ever.
5922
6076
 
@@ -6016,17 +6170,17 @@ export async function resolveFolderContents(
6016
6170
  *
6017
6171
  * A folder lists the files whose `h` it is **and** the files placed in it.
6018
6172
  * An event cannot change its own `h`, so a project filed in one Folder and
6019
- * later linked to a team keeps the `h` it was born with, and the only thing
6173
+ * later linked to a Folder keeps the `h` it was born with, and the only thing
6020
6174
  * that can say "it belongs over there now" is a change event. Ship publishes
6021
6175
  * that change twice — into the record's own Folder, and *into the Folder
6022
- * being linked*: a `kind:1851` carried by the team's `h`, targeting the
6023
- * project, whose value is the team Folder itself. The second copy is the
6176
+ * being linked*: a `kind:1851` carried by the Folder's `h`, targeting the
6177
+ * project, whose value is the Folder itself. The second copy is the
6024
6178
  * placement, and it is what this reads.
6025
6179
  *
6026
6180
  * {@link resolveFolderProject} has read the same statement since PEEK-24 to
6027
6181
  * answer "which project is this topic paired with". This is the listing's
6028
- * half of it, and it is the rule the tidy-up rests on: five team Folders,
6029
- * fourteen projects linked into them and none re-created, so a team Folder
6182
+ * half of it, and it is the rule the tidy-up rests on: five Folders,
6183
+ * fourteen projects linked into them and none re-created, so a Folder
6030
6184
  * whose `h` is on nothing lists its projects anyway.
6031
6185
  *
6032
6186
  * App-neutral by the same discipline as everything else here. The change
@@ -0,0 +1,154 @@
1
+ /**
2
+ * The files `[` offers, as @estiva-app/conversation ranks them (PEE-21).
3
+ *
4
+ * conversation's `rankReferences` orders candidates and knows nothing of a
5
+ * relay; this is the half that turns what a relay holds into candidates — a
6
+ * resolved object into a row, and typed text into the search tier — so Peek
7
+ * and Ship draw the same rows from the same reads.
8
+ *
9
+ * A row is the type word and the current title; an issue is captioned with its
10
+ * project's title, and nothing names a Folder (Miky, 2026-10-03). Only what the
11
+ * reader resolved is offered: an object the relay did not hand back to them is
12
+ * never a row, so nothing unreadable is offered. An archived file is offered
13
+ * at the lowest priority, and so is an issue in an archived project.
14
+ */
15
+ import {
16
+ FILE_TIER,
17
+ fileReference,
18
+ KIND_CHANGE,
19
+ referenceMatch,
20
+ type ReferenceCandidate,
21
+ type ReferenceType,
22
+ } from '@estiva-app/conversation'
23
+ import {
24
+ isClosedStatus,
25
+ KIND_BARE_FILE,
26
+ resolveForeignRoots,
27
+ type ForeignObject,
28
+ type ProjectionCache,
29
+ type QueryFn,
30
+ } from './projection.js'
31
+
32
+ const KIND_PROJECT = 30850
33
+ const KIND_ISSUE = 30851
34
+
35
+ /** The kinds `[` offers as files, and the type word each draws as. */
36
+ export const REFERENCE_FILE_TYPES: Readonly<Record<number, ReferenceType>> = {
37
+ [KIND_PROJECT]: 'project',
38
+ [KIND_ISSUE]: 'issue',
39
+ [KIND_BARE_FILE]: 'topic',
40
+ }
41
+
42
+ const typeOf = (kind: number): ReferenceType | undefined => REFERENCE_FILE_TYPES[kind]
43
+
44
+ type Addressed = ForeignObject & { address: string }
45
+
46
+ /** An object `[` may offer: a file kind it knows, resolved, with a title. */
47
+ const offerable = (object: ForeignObject | null | undefined): object is Addressed =>
48
+ !!object &&
49
+ !!object.address &&
50
+ !object.unreachable &&
51
+ typeOf(object.kind) !== undefined &&
52
+ !!object.slots.title?.value.trim()
53
+
54
+ export interface FileCandidatesOptions {
55
+ cache?: ProjectionCache
56
+ /** When each address was last written or read, in seconds — newer first within a tier. */
57
+ at?: ReadonlyMap<string, number>
58
+ }
59
+
60
+ /**
61
+ * Rows for resolved files, all in one tier.
62
+ *
63
+ * An issue's caption is its project's title, and an issue in an archived
64
+ * project is archived with it: the project is taken from `objects` when it is
65
+ * among them, and otherwise read in one more batch for every missing project
66
+ * at once (roots and changes only). A project that cannot be read leaves the
67
+ * caption empty rather than dropping the issue. Objects that are not
68
+ * offerable — unreachable, untitled, or of a kind `[` does not offer — are
69
+ * left out.
70
+ */
71
+ export async function fileCandidates(
72
+ objects: readonly (ForeignObject | null | undefined)[],
73
+ tier: number,
74
+ query: QueryFn,
75
+ { cache, at }: FileCandidatesOptions = {},
76
+ ): Promise<ReferenceCandidate[]> {
77
+ const files = objects.filter(offerable)
78
+ const parents = new Map<string, ForeignObject>()
79
+ for (const o of objects) if (o?.address && !o.unreachable) parents.set(o.address, o)
80
+ const missing = [
81
+ ...new Set(files.flatMap((o) => (o.kind === KIND_ISSUE && o.parentRef && !parents.has(o.parentRef) ? [o.parentRef] : []))),
82
+ ]
83
+ if (missing.length) {
84
+ const read = await resolveForeignRoots(missing, query, cache).catch(() => [])
85
+ for (const parent of read) if (parent.address) parents.set(parent.address, parent)
86
+ }
87
+ return files.map((o) => {
88
+ const parent = o.kind === KIND_ISSUE && o.parentRef ? parents.get(o.parentRef) : undefined
89
+ return {
90
+ id: o.address,
91
+ uri: fileReference(o.address),
92
+ type: typeOf(o.kind)!,
93
+ kind: o.kind,
94
+ title: o.slots.title!.value,
95
+ caption: parent?.slots.title?.value ?? '',
96
+ tier,
97
+ ...(isClosedStatus(o.slots.status) ? { closed: true } : {}),
98
+ ...(o.archived || parent?.archived ? { archived: true } : {}),
99
+ ...(at?.has(o.address) ? { at: at.get(o.address) } : {}),
100
+ }
101
+ })
102
+ }
103
+
104
+ export interface SearchFileReferencesOptions extends Omit<FileCandidatesOptions, 'at'> {
105
+ /** How many roots, and separately how many renames, the relay is asked for. Default 32. */
106
+ limit?: number
107
+ }
108
+
109
+ const tagOf = (event: { tags: string[][] }, name: string) => event.tags.find((t) => t[0] === name)?.[1]
110
+
111
+ /**
112
+ * The files whose **current** title holds `text`, as the search tier.
113
+ *
114
+ * The relay indexes a root's `title` and a rename's `value` (relay ticket
115
+ * 6fea004e); neither is the current title on its own — a root keeps the name
116
+ * it was created with, and a rename found by an old word may since have been
117
+ * renamed again. So a hit is only an address: each is read back as its root
118
+ * and changes, folded through its app's manifest, and kept only when what it
119
+ * is called now matches what was typed.
120
+ *
121
+ * Roots and renames are asked for separately, so a burst of renames cannot
122
+ * crowd every root out of the answer, and with buzz's prefix mode, so the word
123
+ * being typed matches before it is finished. A relay that indexes none of these
124
+ * kinds answers nothing, and so does this. A failed read rejects, for
125
+ * `referenceSearch` to answer no hits for a while.
126
+ */
127
+ export async function searchFileReferences(
128
+ text: string,
129
+ query: QueryFn,
130
+ { limit = 32, ...options }: SearchFileReferencesOptions = {},
131
+ ): Promise<ReferenceCandidate[]> {
132
+ const wanted = text.trim()
133
+ if (!wanted) return []
134
+ const asked = { search: wanted, search_mode: 'prefix', limit }
135
+ const hits = await query([
136
+ { kinds: Object.keys(REFERENCE_FILE_TYPES).map(Number), ...asked },
137
+ { kinds: [KIND_CHANGE], ...asked },
138
+ ])
139
+ const at = new Map<string, number>()
140
+ for (const hit of hits) {
141
+ const address =
142
+ hit.kind === KIND_CHANGE
143
+ ? tagOf(hit, 'field') === 'title'
144
+ ? tagOf(hit, 'a')
145
+ : undefined
146
+ : typeOf(hit.kind) && `${hit.kind}:${hit.pubkey}:${tagOf(hit, 'd') ?? ''}`
147
+ if (!address || !typeOf(Number(address.split(':')[0]))) continue
148
+ at.set(address, Math.max(at.get(address) ?? 0, hit.created_at))
149
+ }
150
+ if (at.size === 0) return []
151
+ const objects = await resolveForeignRoots([...at.keys()], query, options.cache)
152
+ const matching = objects.filter((o) => o.slots.title && referenceMatch(o.slots.title.value, wanted) > 0)
153
+ return fileCandidates(matching, FILE_TIER.search, query, { ...options, at })
154
+ }