@estiva-app/interop 0.36.0 → 0.37.1

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
@@ -1483,6 +1483,19 @@ export interface ResolvedManifest {
1483
1483
  */
1484
1484
  export const KIND_BARE_FILE = 30840
1485
1485
 
1486
+ /**
1487
+ * The field that archives a file, whatever its kind — FOL-46.
1488
+ *
1489
+ * **One concept for every file.** A Ship project, a Ship issue, a Peek topic, a
1490
+ * bare file and a Folder are all archived the same way: a change setting
1491
+ * `archived` to `'true'` on the file's address, and an empty value to restore
1492
+ * it. That is the shape Ship has written for projects since SPEC §6.5, so
1493
+ * nothing on the relay needs migrating. It is a change, never a deletion, so it
1494
+ * is reversible, attributed, and open to anyone who may write in the Folder —
1495
+ * not only the author.
1496
+ */
1497
+ export const ARCHIVED_FIELD = 'archived'
1498
+
1486
1499
  /**
1487
1500
  * Where a `ResolvedManifest.address` would name the manifest event, this names
1488
1501
  * the section of the specification the manifest is built from. Not an address,
@@ -1594,6 +1607,23 @@ const BARE_FILE_MANIFEST: Manifest = {
1594
1607
  emits: { kind: 1851, field: 'parent' },
1595
1608
  input: { type: 'string' },
1596
1609
  },
1610
+ /*
1611
+ `archive` is the one field every file may carry (FOL-46): `true` hides the
1612
+ file and everything under it from every list, an empty value brings it
1613
+ back. A change, so anyone in the team may, and the archiving change's
1614
+ `content` is the resolution summary a person gave (`ActionEventArgs.note`).
1615
+ */
1616
+ {
1617
+ id: 'archive',
1618
+ label: 'Archive',
1619
+ description:
1620
+ 'Take this file and everything under it out of every list once nobody needs to see it, or bring it ' +
1621
+ 'back: `true` archives, an empty value restores. Nothing is deleted, and a link still opens it.',
1622
+ effect: 'writes',
1623
+ appliesTo: [String(KIND_BARE_FILE)],
1624
+ emits: { kind: 1851, field: ARCHIVED_FIELD },
1625
+ input: { type: 'string', enum: ARCHIVED_FIELD },
1626
+ },
1597
1627
  {
1598
1628
  id: 'delete',
1599
1629
  label: 'Delete',
@@ -1605,6 +1635,13 @@ const BARE_FILE_MANIFEST: Manifest = {
1605
1635
  emits: { kind: KIND_DELETION },
1606
1636
  },
1607
1637
  ],
1638
+ vocabularies: {
1639
+ // Ship's `ARCHIVED_STATES`, value for value: one field, one vocabulary.
1640
+ [ARCHIVED_FIELD]: [
1641
+ { value: '', label: 'Active', colour: 'neutral' },
1642
+ { value: 'true', label: 'Archived', colour: 'muted' },
1643
+ ],
1644
+ },
1608
1645
  }
1609
1646
 
1610
1647
  function bareFileManifest(): ResolvedManifest {
@@ -2031,6 +2068,112 @@ function foldChanges(changes: SignedEvent[], rule: RecordsRule) {
2031
2068
  return fields
2032
2069
  }
2033
2070
 
2071
+ /**
2072
+ * How an `archived` change is read when the file's kind declares no rule of its
2073
+ * own — a Folder, whose `kind:39000` no app owns, and a bare file. SPEC §7.1's
2074
+ * `kind:1851` shape, the one every Estiva app writes.
2075
+ */
2076
+ const ARCHIVE_RULE: RecordsRule = {
2077
+ changeKind: 1851,
2078
+ targetTag: 'a',
2079
+ fieldTag: 'field',
2080
+ valueTag: 'value',
2081
+ order: ['ts', 'created_at', 'id'],
2082
+ rule: 'last-write-wins-per-field',
2083
+ }
2084
+
2085
+ /** The rule an `archived` change on this file is folded by: its app's, or SPEC's. */
2086
+ function archiveRuleOf(manifest: Pick<Manifest, 'records'> | undefined): RecordsRule {
2087
+ return manifest?.records ?? ARCHIVE_RULE
2088
+ }
2089
+
2090
+ /**
2091
+ * The note Ship wrote on every archive before FOL-46, when the note was the
2092
+ * activity feed's wording rather than anything a person typed. Twelve are on
2093
+ * production (measured 2026-09-29), and none of them is a resolution.
2094
+ */
2095
+ const PLACEHOLDER_ARCHIVE_NOTE = 'archived'
2096
+
2097
+ /** A file that is archived: who did it, when, and what they said about it. */
2098
+ export interface Archive {
2099
+ /** Who wrote the archiving change. */
2100
+ by: string
2101
+ /** Its `created_at`, in seconds. */
2102
+ at: number
2103
+ /**
2104
+ * The resolution summary, when the person archiving gave one — the archiving
2105
+ * change's `content`. One event, so the summary can never land without the
2106
+ * archive or outlive the unarchive that replaces it.
2107
+ */
2108
+ resolution?: string
2109
+ /**
2110
+ * Present when the file is not archived itself but is hidden **with** an
2111
+ * archived ancestor: that ancestor's address — the project an issue belongs
2112
+ * to, the file a sub-topic sits under, the record a channel belongs to.
2113
+ *
2114
+ * Computed when reading and never written to the file (FOL-46): unarchiving
2115
+ * the ancestor restores exactly what was there before, and archiving a
2116
+ * project with two hundred issues is one event rather than two hundred.
2117
+ */
2118
+ with?: string
2119
+ }
2120
+
2121
+ /**
2122
+ * Whether a file — or a Folder — is archived, itself or with an ancestor.
2123
+ *
2124
+ * Reads the {@link Archive} a resolver put on it. A resolver leaves archived
2125
+ * files out of a Folder's contents, so this matters where a file is reached
2126
+ * directly: a link, a mention, a page opened by address.
2127
+ */
2128
+ export function isArchived(file: { archived?: Archive } | null | undefined): boolean {
2129
+ return !!file?.archived
2130
+ }
2131
+
2132
+ /**
2133
+ * The file's archive, if the last `archived` change archived it.
2134
+ *
2135
+ * `changes` may hold any events; only this rule's change kind, naming this
2136
+ * address, setting this field, is read. Last write wins, by the same order as
2137
+ * every other field.
2138
+ */
2139
+ function archiveOf(changes: SignedEvent[], address: string, rule: RecordsRule): Archive | undefined {
2140
+ let last: SignedEvent | undefined
2141
+ for (const change of changes) {
2142
+ // The target is the first target tag, as every other fold reads it: a
2143
+ // change archiving one file must not archive another it also mentions.
2144
+ if (change.kind !== rule.changeKind || tagValue(change, rule.targetTag) !== address) continue
2145
+ if (tagValue(change, rule.fieldTag) !== ARCHIVED_FIELD || tagValue(change, rule.valueTag) === undefined) continue
2146
+ if (!last || byOrder(last, change) < 0) last = change
2147
+ }
2148
+ if (!last || tagValue(last, rule.valueTag) !== 'true') return undefined
2149
+ const note = last.content.trim()
2150
+ return {
2151
+ by: last.pubkey,
2152
+ at: last.created_at,
2153
+ ...(note && note !== PLACEHOLDER_ARCHIVE_NOTE ? { resolution: last.content } : {}),
2154
+ }
2155
+ }
2156
+
2157
+ /**
2158
+ * The first archived ancestor of `address`, walking `parentOf`, with its archive.
2159
+ *
2160
+ * Stops at a cycle rather than looping: `parentRef` is written by people, and
2161
+ * two files each moved under the other is a state the relay accepts.
2162
+ */
2163
+ function archivedAncestorOf(
2164
+ address: string,
2165
+ parentOf: (address: string) => string | undefined,
2166
+ archiveAt: (address: string) => Archive | undefined,
2167
+ ): Archive | undefined {
2168
+ const seen = new Set([address])
2169
+ for (let parent = parentOf(address); parent && !seen.has(parent); parent = parentOf(parent)) {
2170
+ seen.add(parent)
2171
+ const archive = archiveAt(parent)
2172
+ if (archive) return { ...archive, with: archive.with ?? parent }
2173
+ }
2174
+ return undefined
2175
+ }
2176
+
2034
2177
  function truncate(text: string, limit?: number) {
2035
2178
  if (!limit || text.length <= limit) return text
2036
2179
  return `${text.slice(0, limit).trimEnd()}…`
@@ -2679,6 +2822,15 @@ export interface ForeignObject {
2679
2822
  * rendering nothing.
2680
2823
  */
2681
2824
  unreachable?: boolean
2825
+ /**
2826
+ * Present when the file is archived, itself or with an ancestor (FOL-46).
2827
+ *
2828
+ * A Folder's contents leave archived files out, so this is set where a file
2829
+ * is reached by address: its page draws an Archived banner with the
2830
+ * resolution and an Unarchive control rather than drawing it as live work.
2831
+ * See {@link Archive} and {@link isArchived}.
2832
+ */
2833
+ archived?: Archive
2682
2834
  }
2683
2835
 
2684
2836
 
@@ -2697,6 +2849,7 @@ function buildObject(args: {
2697
2849
  viaRecommendation: boolean
2698
2850
  webTemplate?: string
2699
2851
  comments?: ForeignObject['comments']
2852
+ archived?: Archive
2700
2853
  }): ForeignObject {
2701
2854
  const { root, pointer, manifest, projection, folded } = args
2702
2855
  const naddr = encodeNaddr(pointer)
@@ -2748,6 +2901,7 @@ function buildObject(args: {
2748
2901
  : action,
2749
2902
  ),
2750
2903
  viaRecommendation: args.viaRecommendation,
2904
+ ...(args.archived ? { archived: args.archived } : {}),
2751
2905
  }
2752
2906
  }
2753
2907
 
@@ -2855,6 +3009,7 @@ export async function resolveForeignObject(
2855
3009
  * omitting it is exactly the old behaviour.
2856
3010
  */
2857
3011
  cache?: ProjectionCache,
3012
+ options: ArchiveReadOptions = {},
2858
3013
  ): Promise<ForeignObject | null> {
2859
3014
  const pointer = addressPointerOf(naddr)
2860
3015
  if (!pointer) return null
@@ -2865,6 +3020,7 @@ export async function resolveForeignObject(
2865
3020
 
2866
3021
  const assembled = assembleObject(plan, await query(plan.filters))
2867
3022
  if (assembled.object.unreachable) return assembled.object
3023
+ if (options.archivedWith) await markArchivedParents([{ object: assembled.object, manifest: resolved.manifest }], query)
2868
3024
  return withPeople(assembled, await (lookupPeople ?? peopleViaRelay(query))(peopleOf(assembled)))
2869
3025
  }
2870
3026
 
@@ -2911,6 +3067,7 @@ export async function resolveForeignObjects(
2911
3067
  lookupPeople?: PeopleFn,
2912
3068
  /** See {@link ProjectionCache}. Omitting it still reads each app's manifest once per call. */
2913
3069
  cache?: ProjectionCache,
3070
+ options: ArchiveReadOptions = {},
2914
3071
  ): Promise<Record<string, ForeignObject | null>> {
2915
3072
  const results: Record<string, ForeignObject | null> = {}
2916
3073
  const asked: { reference: string; pointer: AddressPointer }[] = []
@@ -2956,7 +3113,10 @@ export async function resolveForeignObjects(
2956
3113
  }
2957
3114
  const events = (await Promise.all(chunks.map((chunk) => query(chunk)))).flat()
2958
3115
 
2959
- const assembled = plans.map(({ reference, plan }) => ({ reference, built: assembleObject(plan, events) }))
3116
+ const assembled = plans.map(({ reference, plan }) => ({ reference, plan, built: assembleObject(plan, events) }))
3117
+ if (options.archivedWith) {
3118
+ await markArchivedParents(assembled.map(({ plan, built }) => ({ object: built.object, manifest: plan.resolved.manifest })), query)
3119
+ }
2960
3120
  const wanted = [...new Set(assembled.flatMap(({ built }) => peopleOf(built)))]
2961
3121
  const reachable = assembled.some(({ built }) => !built.object.unreachable)
2962
3122
  const people = reachable ? await (lookupPeople ?? peopleViaRelay(query))(wanted) : {}
@@ -2975,6 +3135,100 @@ export async function resolveForeignObjects(
2975
3135
  return results
2976
3136
  }
2977
3137
 
3138
+ /** What {@link resolveForeignObject} and {@link resolveForeignObjects} may read beyond the file itself. */
3139
+ export interface ArchiveReadOptions {
3140
+ /**
3141
+ * Also read whether each file's parent is archived, and mark the file
3142
+ * archived **with** it (`archived.with`) — FOL-46. For the page a link opens,
3143
+ * which draws the banner; off by default because it is one more request
3144
+ * whenever a file has a parent, and a refresh tick that resolves an issue
3145
+ * card would pay it every time (SHI-13's one request per tick).
3146
+ */
3147
+ archivedWith?: boolean
3148
+ }
3149
+
3150
+ /**
3151
+ * Mark each object that is hidden with an archived parent — FOL-46.
3152
+ *
3153
+ * An issue whose project is archived is archived with it, and its page says so
3154
+ * rather than drawing live work. The cascade is computed here and never written
3155
+ * to the issue, so unarchiving the project restores it exactly.
3156
+ *
3157
+ * **One read for the whole set, and only when some object has a parent**, so a
3158
+ * topic page or a project page pays nothing. One level: the parent's own
3159
+ * parent is not followed, because the page is about this file and its
3160
+ * container, and a deeper walk is a round trip per level. A Folder listing
3161
+ * walks the whole chain it holds ({@link resolveFolderContents}).
3162
+ *
3163
+ * The parent is folded by the child's app's rule when that app also draws the
3164
+ * parent's kind — a project is Ship's as its issue is — and by SPEC's rule
3165
+ * otherwise, since the parent's own manifest is not in hand ({@link relatedRuleOf}).
3166
+ */
3167
+ async function markArchivedParents(
3168
+ entries: { object: ForeignObject; manifest?: Pick<Manifest, 'records' | 'projections'> }[],
3169
+ query: QueryFn,
3170
+ ): Promise<void> {
3171
+ const waiting = entries.filter(
3172
+ ({ object: o }) => !o.unreachable && !o.archived && o.parentRef && addressPointerOf(o.parentRef),
3173
+ )
3174
+ if (waiting.length === 0) return
3175
+ const rules = waiting.map(({ object, manifest }) => relatedRuleOf(manifest, object.parentRef!))
3176
+ const parents = [...new Set(waiting.map(({ object }) => object.parentRef!))]
3177
+ const changes = await readArchiveChanges(parents, query, rules)
3178
+ for (const [index, { object }] of waiting.entries()) {
3179
+ const archive = archiveOf(changes, object.parentRef!, rules[index]!)
3180
+ if (archive) object.archived = { ...archive, with: object.parentRef! }
3181
+ }
3182
+ }
3183
+
3184
+ /**
3185
+ * The rule another file's archive is read by, from an app known to hold it:
3186
+ * that app's own, when it draws the file's kind — an issue's project is Ship's,
3187
+ * a hive's inspection the hive log's — and SPEC's otherwise.
3188
+ */
3189
+ function relatedRuleOf(manifest: Pick<Manifest, 'records' | 'projections'> | undefined, address: string): RecordsRule {
3190
+ const kind = addressPointerOf(address)?.kind
3191
+ return manifest && kind !== undefined && manifest.projections?.[String(kind)] ? archiveRuleOf(manifest) : ARCHIVE_RULE
3192
+ }
3193
+
3194
+ /**
3195
+ * Addresses per filter when reading archive changes. A filter's `limit` caps
3196
+ * every change naming its addresses — titles, statuses, moves — not only the
3197
+ * archives, and a relay answers newest first, so a small group keeps the
3198
+ * archive change inside the page.
3199
+ */
3200
+ const ARCHIVE_READ_GROUP = 25
3201
+
3202
+ /**
3203
+ * The filters asking for every change naming these addresses, once per distinct
3204
+ * change shape among `rules` — SPEC's alone unless an app writes its own.
3205
+ */
3206
+ function archiveFilters(addresses: readonly string[], rules: readonly RecordsRule[] = [ARCHIVE_RULE]): Record<string, unknown>[] {
3207
+ const shapes = new Map(rules.map((rule) => [`${rule.changeKind}:${rule.targetTag}`, rule]))
3208
+ const filters: Record<string, unknown>[] = []
3209
+ for (const rule of shapes.values()) {
3210
+ for (let start = 0; start < addresses.length; start += ARCHIVE_READ_GROUP) {
3211
+ const group = addresses.slice(start, start + ARCHIVE_READ_GROUP)
3212
+ filters.push({ kinds: [rule.changeKind], [`#${rule.targetTag}`]: group, limit: RELAY_PAGE_CEILING })
3213
+ }
3214
+ }
3215
+ return filters
3216
+ }
3217
+
3218
+ /** Every change naming these addresses, in each of `rules`' shapes, in as few requests as the relay allows. */
3219
+ async function readArchiveChanges(
3220
+ addresses: readonly string[],
3221
+ query: QueryFn,
3222
+ rules?: readonly RecordsRule[],
3223
+ ): Promise<SignedEvent[]> {
3224
+ const filters = archiveFilters(addresses, rules)
3225
+ const events: SignedEvent[] = []
3226
+ for (let start = 0; start < filters.length; start += MAX_FILTERS_PER_QUERY) {
3227
+ events.push(...(await query(filters.slice(start, start + MAX_FILTERS_PER_QUERY))))
3228
+ }
3229
+ return events
3230
+ }
3231
+
2978
3232
  /** An `naddr` or a `<kind>:<pubkey>:<d>`, or null for anything else. */
2979
3233
  function addressPointerOf(reference: string): AddressPointer | null {
2980
3234
  try {
@@ -3046,6 +3300,9 @@ function planObject(
3046
3300
  { kinds: [pointer.kind], authors: [pointer.pubkey], '#d': [pointer.identifier], limit: 1 },
3047
3301
  // Only when the app actually declares a change kind — see `foldRuleOf`.
3048
3302
  ...(manifest.records ? [{ kinds: [manifest.records.changeKind], '#a': [address], limit: 500 }] : []),
3303
+ // Every file may be archived, including one whose app folds nothing
3304
+ // (FOL-46). SPEC's change kind, when the app has not named its own.
3305
+ ...(manifest.records ? [] : [{ kinds: [ARCHIVE_RULE.changeKind], '#a': [address], limit: 500 }]),
3049
3306
  { kinds: commentKinds, '#a': [address], limit: CONVERSATION_LIMIT },
3050
3307
  ...(childFilter ? [childFilter.filter] : []),
3051
3308
  ]
@@ -3147,6 +3404,7 @@ function assembleObject(plan: ObjectPlan, answered: SignedEvent[]): AssembledObj
3147
3404
  viaRecommendation,
3148
3405
  webTemplate: resolved.webTemplate,
3149
3406
  comments,
3407
+ archived: archiveOf(events, address, archiveRuleOf(manifest)),
3150
3408
  })
3151
3409
  /*
3152
3410
  The `list` slot — PRO-7.
@@ -4294,6 +4552,12 @@ export interface ActionEventArgs {
4294
4552
  * marker text, which is always correct.
4295
4553
  */
4296
4554
  contentFormat?: string
4555
+ /**
4556
+ * What the person said about a change, carried as its `content` — the
4557
+ * resolution summary of an archive (FOL-46), or any change's note. A change
4558
+ * only: a comment's text is its `value`, and a creation has its own body.
4559
+ */
4560
+ note?: string
4297
4561
  pubkey: string
4298
4562
  createdAtMs: number
4299
4563
  }
@@ -4398,6 +4662,11 @@ function buildOneActionEvent(args: ActionEventArgs): UnsignedActionEvent | strin
4398
4662
  if (args.contentFormat !== undefined && !isCreation && (!declared.emits.field || declared.emits.kind === KIND_DELETION)) {
4399
4663
  return `"${declared.label}" takes no prose value, so it takes no content format.`
4400
4664
  }
4665
+ // A note is a change's `content`. Anywhere else it would be dropped, and the
4666
+ // resolution a person typed lost without a word.
4667
+ if (args.note !== undefined && (isCreation || !declared.emits.field || declared.emits.kind === KIND_DELETION)) {
4668
+ return `"${declared.label}" is not a change, so it takes no note.`
4669
+ }
4401
4670
 
4402
4671
  // An object-creating action is a different event entirely — a new object
4403
4672
  // rather than a change to one — so it branches before the scalar path.
@@ -4516,7 +4785,7 @@ function buildOneActionEvent(args: ActionEventArgs): UnsignedActionEvent | strin
4516
4785
  created_at: Math.floor(args.createdAtMs / 1000),
4517
4786
  kind: declared.emits.kind,
4518
4787
  tags,
4519
- content: declared.emits.field ? '' : value,
4788
+ content: declared.emits.field ? (args.note ?? '') : value,
4520
4789
  }
4521
4790
  }
4522
4791
 
@@ -4604,6 +4873,25 @@ export interface FolderSummary {
4604
4873
  * another app's files resolves them with {@link resolveFolderContents}.
4605
4874
  */
4606
4875
  addresses?: string[]
4876
+ /**
4877
+ * The Folder's own address as a file — its `kind:39000`, `39000:<relay>:<id>`.
4878
+ * What a state lists when it holds this Folder, and what an `archived`
4879
+ * change on the Folder names. Absent only for a state whose channel the
4880
+ * relay did not return.
4881
+ */
4882
+ channel?: string
4883
+ /**
4884
+ * Present when the Folder is archived (FOL-46) — or, for a record's channel,
4885
+ * when the record it belongs to is (`with` names the record). See
4886
+ * {@link Archive}.
4887
+ *
4888
+ * {@link topLevelFolders} leaves an archived Folder out, and
4889
+ * {@link resolveFolderContents} leaves one out of the Folder that lists it,
4890
+ * so its subtree goes with it. What it holds stays readable: a link still
4891
+ * opens it, and a file it lists that another Folder also lists stays visible
4892
+ * there.
4893
+ */
4894
+ archived?: Archive
4607
4895
  }
4608
4896
 
4609
4897
  /**
@@ -4620,9 +4908,14 @@ export interface FolderSummary {
4620
4908
  *
4621
4909
  * Not a list of ids: a new team is a folder somebody creates, not a code
4622
4910
  * change. Moved here from Peek and Ship, which each held the same line.
4911
+ *
4912
+ * An archived Folder is not navigated by (FOL-46), and a listing that has not
4913
+ * read archives — a summary with no `archived` field — keeps every Folder.
4623
4914
  */
4624
- export function topLevelFolders<T extends Pick<FolderSummary, 'hasState' | 'listedIn'>>(folders: T[]): T[] {
4625
- return folders.filter((folder) => folder.hasState && !folder.listedIn?.length)
4915
+ export function topLevelFolders<T extends Pick<FolderSummary, 'hasState' | 'listedIn' | 'archived'>>(
4916
+ folders: T[],
4917
+ ): T[] {
4918
+ return folders.filter((folder) => folder.hasState && !folder.listedIn?.length && !folder.archived)
4626
4919
  }
4627
4920
 
4628
4921
  /** A folder and everything in it, each file drawn through its owner's manifest. */
@@ -4687,6 +4980,11 @@ export async function listFolders(query: QueryFn): Promise<FolderSummary[]> {
4687
4980
  ...(addresses.length ? { addresses } : {}),
4688
4981
  })
4689
4982
  }
4983
+ for (const event of events) {
4984
+ const id = tagValue(event, 'd')
4985
+ const folder = id && event.kind === KIND_CHANNEL ? byId.get(id) : undefined
4986
+ if (folder) folder.channel = pointerToAddress({ kind: KIND_CHANNEL, pubkey: event.pubkey, identifier: id!, relays: [] })
4987
+ }
4690
4988
  /*
4691
4989
  A folder listed in another folder's state is a file there. Read off the
4692
4990
  states already in hand: an `a` naming a `kind:39000` is a channel, and its
@@ -4707,14 +5005,202 @@ export async function listFolders(query: QueryFn): Promise<FolderSummary[]> {
4707
5005
  listedIn.set(identifier, containers)
4708
5006
  }
4709
5007
  }
4710
- await placeRecordChannels(events, byId, listedIn, query)
5008
+ const { recordsOf, archives } = await placeRecordChannels(events, byId, listedIn, query)
4711
5009
  for (const [id, containers] of listedIn) {
4712
5010
  const folder = byId.get(id)
4713
5011
  if (folder) folder.listedIn = containers
4714
5012
  }
5013
+ markArchivedFolders(byId, recordsOf, archives)
4715
5014
  return [...byId.values()].sort((a, b) => (a.name ?? a.id).localeCompare(b.name ?? b.id))
4716
5015
  }
4717
5016
 
5017
+ /**
5018
+ * Which Folders are archived — FOL-46, from the changes {@link placeRecordChannels}
5019
+ * read with the record roots.
5020
+ *
5021
+ * A Folder is archived by a change naming its channel's address, the way any
5022
+ * file is. A record's channel — a Ship project's conversation — is archived
5023
+ * with its record, so an archived project's channel stops lighting its team's
5024
+ * dot the way the project stopped being listed — only when every record naming
5025
+ * the channel is archived, since two projects may share one. Its own archive
5026
+ * wins when it has one.
5027
+ *
5028
+ * A refused read throws before this, like the reads beside it: a listing that
5029
+ * silently reported every Folder live would put archived teams back in
5030
+ * everyone's sidebar.
5031
+ */
5032
+ function markArchivedFolders(
5033
+ byId: Map<string, FolderSummary>,
5034
+ recordsOf: Map<string, string[]>,
5035
+ changes: SignedEvent[],
5036
+ ): void {
5037
+ for (const folder of byId.values()) {
5038
+ const own = folder.channel ? archiveOf(changes, folder.channel, ARCHIVE_RULE) : undefined
5039
+ if (own) {
5040
+ folder.archived = own
5041
+ continue
5042
+ }
5043
+ const records = recordsOf.get(folder.id) ?? []
5044
+ const archives = records.map((record) => archiveOf(changes, record, ARCHIVE_RULE))
5045
+ if (records.length && archives.every(Boolean)) folder.archived = { ...archives[0]!, with: records[0] }
5046
+ }
5047
+ }
5048
+
5049
+ /** How many Folders deep {@link archiveImpact} follows nested Folders. A request per Folder. */
5050
+ const MAX_ARCHIVE_DEPTH = 3
5051
+
5052
+ /** What archiving one file would hide, for the warning a person reads first — FOL-46. */
5053
+ export interface ArchiveImpact {
5054
+ /**
5055
+ * The files that would go out of every list with it, counted by kind: its
5056
+ * children, and — for a Folder — every file only that Folder lists, with
5057
+ * their children. Files already archived are not counted; they are hidden
5058
+ * already. Kinds with no files are absent.
5059
+ */
5060
+ hides: { kind: number; count: number }[]
5061
+ /**
5062
+ * Files a Folder lists that another Folder, not archived, lists too. They
5063
+ * stay visible there, and a warning that said they would be hidden would
5064
+ * make Archive look more destructive than it is. Empty for a file that is
5065
+ * not a Folder.
5066
+ */
5067
+ staysVisible: { address: string; kind: number; in: { id: string; name?: string }[] }[]
5068
+ }
5069
+
5070
+ /**
5071
+ * Count what archiving `address` would hide — the read behind the warning.
5072
+ *
5073
+ * "Hides 14 issues and 6 topics that are only here; 2 topics also in Estiva HQ
5074
+ * stay visible." The words are the app's; the counts are the same in every
5075
+ * app, which is why they are read here.
5076
+ *
5077
+ * - **A Folder** (a `kind:39000` address, `FolderSummary.channel`): what it
5078
+ * lists, split by whether another Folder lists it too, the children of what
5079
+ * would be hidden, and — three Folders deep — what a nested Folder only it
5080
+ * lists holds. Pass `folders` from the app's own `listFolders` to save that
5081
+ * read.
5082
+ * - **Any other file**: the children its kind declares (a project's issues), and
5083
+ * bare files placed under it (sub-topics), by their root's `a` tag.
5084
+ *
5085
+ * One level of children, as a listing draws them. A few requests, whatever the
5086
+ * size: the Folder, one per app's manifest (memoised by `cache`), the children,
5087
+ * and their archives.
5088
+ */
5089
+ export async function archiveImpact(
5090
+ address: string,
5091
+ query: QueryFn,
5092
+ options: { folders?: FolderSummary[]; cache?: ProjectionCache } = {},
5093
+ ): Promise<ArchiveImpact> {
5094
+ const pointer = addressPointerOf(address)
5095
+ if (!pointer) return { hides: [], staysVisible: [] }
5096
+ const counts = new Map<number, number>()
5097
+ const count = (kind: number, n = 1) => counts.set(kind, (counts.get(kind) ?? 0) + n)
5098
+ const staysVisible: ArchiveImpact['staysVisible'] = []
5099
+ let parents: { address: string; pointer: AddressPointer }[] = [{ address, pointer }]
5100
+
5101
+ if (pointer.kind === KIND_CHANNEL) {
5102
+ const folders = options.folders ?? (await listFolders(query))
5103
+ parents = []
5104
+ /*
5105
+ A nested Folder only this one lists goes out of view with it, and so does
5106
+ everything only *that* one lists — walked the same way, a Folder at a
5107
+ time, to a small depth. "Only" is judged against the live Folders outside
5108
+ the tree being archived.
5109
+ */
5110
+ const inTree = new Set([pointer.identifier])
5111
+ const walk = async (folder: string, depth: number) => {
5112
+ const contents = await resolveFolderContents(folder, query, async () => ({}), options.cache)
5113
+ for (const file of contents.files) {
5114
+ if (!file.address) continue
5115
+ const others = folders.filter(
5116
+ (other) => !inTree.has(other.id) && !other.archived && other.addresses?.includes(file.address!),
5117
+ )
5118
+ if (others.length) {
5119
+ staysVisible.push({ address: file.address, kind: file.kind, in: others.map(({ id, name }) => ({ id, name })) })
5120
+ continue
5121
+ }
5122
+ count(file.kind)
5123
+ const filePointer = addressPointerOf(file.address)
5124
+ if (!filePointer) continue
5125
+ if (filePointer.kind === KIND_CHANNEL) {
5126
+ if (depth < MAX_ARCHIVE_DEPTH && !inTree.has(filePointer.identifier)) {
5127
+ inTree.add(filePointer.identifier)
5128
+ await walk(filePointer.identifier, depth + 1)
5129
+ }
5130
+ } else {
5131
+ parents.push({ address: file.address, pointer: filePointer })
5132
+ }
5133
+ }
5134
+ }
5135
+ await walk(pointer.identifier, 0)
5136
+ }
5137
+
5138
+ // A record channel lists a project *and* its issues; each is counted once.
5139
+ const counted = new Set(parents.map((p) => p.address))
5140
+ for (const [kind, n] of await countLiveChildren(parents, counted, query, options.cache)) count(kind, n)
5141
+ return {
5142
+ hides: [...counts].map(([kind, n]) => ({ kind, count: n })),
5143
+ staysVisible,
5144
+ }
5145
+ }
5146
+
5147
+ /** The children of each parent that are not archived already, by kind. */
5148
+ async function countLiveChildren(
5149
+ parents: { address: string; pointer: AddressPointer }[],
5150
+ counted: ReadonlySet<string>,
5151
+ query: QueryFn,
5152
+ cache?: ProjectionCache,
5153
+ ): Promise<Map<number, number>> {
5154
+ const byKind = new Map<number, number>()
5155
+ if (parents.length === 0) return byKind
5156
+ const byApp = new Map<string, AddressPointer>()
5157
+ for (const { pointer } of parents) byApp.set(manifestKeyOf(pointer), pointer)
5158
+ const manifests = new Map<string, ResolvedManifest>()
5159
+ await Promise.all(
5160
+ [...byApp].map(async ([key, pointer]) => {
5161
+ const resolved = await resolveManifest(pointer, query, cache)
5162
+ if (resolved) manifests.set(key, resolved)
5163
+ }),
5164
+ )
5165
+ const filters: Record<string, unknown>[] = []
5166
+ const wanted: { kind: number; via: string; parent: string; rule: RecordsRule }[] = []
5167
+ for (const { address, pointer } of parents) {
5168
+ const manifest = manifests.get(manifestKeyOf(pointer))?.manifest
5169
+ const projection = manifest?.projections?.[String(pointer.kind)]
5170
+ const declared = projection && declaredChildSpec(projection)
5171
+ // A declared child is the parent's app's, and folds by its rule; a sub-topic is a bare file, SPEC's.
5172
+ const specs = [
5173
+ ...(declared ? [{ kind: declared.kind, via: declared.via, rule: archiveRuleOf(manifest) }] : []),
5174
+ // A sub-topic may sit under a file of any kind (SPEC §6.7).
5175
+ ...(declared?.kind === KIND_BARE_FILE && declared.via === 'a' ? [] : [{ kind: KIND_BARE_FILE, via: 'a', rule: ARCHIVE_RULE }]),
5176
+ ]
5177
+ for (const spec of specs) {
5178
+ wanted.push({ ...spec, parent: address })
5179
+ filters.push({ kinds: [spec.kind], [`#${spec.via}`]: [address], limit: RELAY_PAGE_CEILING })
5180
+ }
5181
+ }
5182
+ const events: SignedEvent[] = []
5183
+ for (let start = 0; start < filters.length; start += MAX_FILTERS_PER_QUERY) {
5184
+ events.push(...(await query(filters.slice(start, start + MAX_FILTERS_PER_QUERY))))
5185
+ }
5186
+ const children = new Map<string, { kind: number; rule: RecordsRule }>()
5187
+ for (const event of events) {
5188
+ const identifier = tagValue(event, 'd')
5189
+ if (identifier === undefined) continue
5190
+ const match = wanted.find((w) => w.kind === event.kind && hasTagValue(event, w.via, w.parent))
5191
+ if (!match) continue
5192
+ const child = pointerToAddress({ kind: event.kind, pubkey: event.pubkey, identifier, relays: [] })
5193
+ if (!counted.has(child)) children.set(child, { kind: event.kind, rule: match.rule })
5194
+ }
5195
+ if (children.size === 0) return byKind
5196
+ const changes = await readArchiveChanges([...children.keys()], query, [...children.values()].map((c) => c.rule))
5197
+ for (const [child, { kind, rule }] of children) {
5198
+ if (archiveOf(changes, child, rule)) continue
5199
+ byKind.set(kind, (byKind.get(kind) ?? 0) + 1)
5200
+ }
5201
+ return byKind
5202
+ }
5203
+
4718
5204
  /**
4719
5205
  * A record's own channel is listed wherever the record is (FOL-42).
4720
5206
  *
@@ -4763,7 +5249,7 @@ async function placeRecordChannels(
4763
5249
  byId: Map<string, FolderSummary>,
4764
5250
  listedIn: Map<string, string[]>,
4765
5251
  query: QueryFn,
4766
- ): Promise<void> {
5252
+ ): Promise<{ recordsOf: Map<string, string[]>; archives: SignedEvent[] }> {
4767
5253
  const containersOf = new Map<string, { pointer: AddressPointer; containers: string[] }>()
4768
5254
  for (const event of events) {
4769
5255
  if (event.kind !== KIND_FOLDER_STATE) continue
@@ -4784,7 +5270,18 @@ async function placeRecordChannels(
4784
5270
  containersOf.set(key, entry)
4785
5271
  }
4786
5272
  }
4787
- if (containersOf.size === 0) return
5273
+ // Every Folder's archive, and every listed record's, ride with the roots
5274
+ // (FOL-46): the channel addresses are in hand from the listing and the
5275
+ // record addresses are the keys above, so neither needs the roots first.
5276
+ const channels = [...byId.values()].flatMap((folder) => (folder.channel ? [folder.channel] : []))
5277
+ const archiveAsk = archiveFilters([...new Set([...channels, ...containersOf.keys()])])
5278
+ if (containersOf.size === 0) {
5279
+ const archives: SignedEvent[] = []
5280
+ for (let start = 0; start < archiveAsk.length; start += MAX_FILTERS_PER_QUERY) {
5281
+ archives.push(...(await query(archiveAsk.slice(start, start + MAX_FILTERS_PER_QUERY))))
5282
+ }
5283
+ return { recordsOf: new Map(), archives }
5284
+ }
4788
5285
 
4789
5286
  const groups = new Map<string, { kind: number; pubkey: string; identifiers: string[] }>()
4790
5287
  for (const { pointer } of containersOf.values()) {
@@ -4800,10 +5297,14 @@ async function placeRecordChannels(
4800
5297
  filters.push({ kinds: [kind], authors: [pubkey], '#d': chunk, limit: chunk.length })
4801
5298
  }
4802
5299
  }
4803
- const roots: SignedEvent[] = []
5300
+ filters.push(...archiveAsk)
5301
+ const answered: SignedEvent[] = []
4804
5302
  for (let start = 0; start < filters.length; start += MAX_FILTERS_PER_QUERY) {
4805
- roots.push(...(await query(filters.slice(start, start + MAX_FILTERS_PER_QUERY))))
5303
+ answered.push(...(await query(filters.slice(start, start + MAX_FILTERS_PER_QUERY))))
4806
5304
  }
5305
+ // A state lists files, never change events, so the kind tells them apart.
5306
+ const archives = answered.filter((e) => e.kind === ARCHIVE_RULE.changeKind)
5307
+ const roots = answered.filter((e) => e.kind !== ARCHIVE_RULE.changeKind)
4807
5308
 
4808
5309
  // Newest wins, as it does for any addressable event a relay has not yet replaced.
4809
5310
  const newest = new Map<string, SignedEvent>()
@@ -4812,10 +5313,14 @@ async function placeRecordChannels(
4812
5313
  const held = newest.get(key)
4813
5314
  if (!held || root.created_at > held.created_at) newest.set(key, root)
4814
5315
  }
5316
+ const recordsOf = new Map<string, string[]>()
4815
5317
  for (const [key, { containers }] of containersOf) {
4816
5318
  const root = newest.get(key)
4817
5319
  const channel = root && folderOf(root)
4818
5320
  if (!channel || byId.get(channel)?.hasState) continue
5321
+ // A file published into the Folder that lists it names that Folder, and
5322
+ // does not own it: a topic's `h` is its team's.
5323
+ if (!containers.includes(channel)) recordsOf.set(channel, [...(recordsOf.get(channel) ?? []), key])
4819
5324
  for (const container of containers) {
4820
5325
  if (container === channel) continue
4821
5326
  const placed = listedIn.get(channel) ?? []
@@ -4823,6 +5328,7 @@ async function placeRecordChannels(
4823
5328
  listedIn.set(channel, placed)
4824
5329
  }
4825
5330
  }
5331
+ return { recordsOf, archives }
4826
5332
  }
4827
5333
 
4828
5334
  /**
@@ -4875,6 +5381,14 @@ export async function resolveFolderContents(
4875
5381
  lookupPeople?: PeopleFn,
4876
5382
  /** See {@link ProjectionCache}. Omitting it is exactly the old behaviour. */
4877
5383
  cache?: ProjectionCache,
5384
+ options: {
5385
+ /**
5386
+ * Return archived files — and files hidden with an archived parent — each
5387
+ * carrying its {@link Archive}, instead of leaving them out. For a view
5388
+ * that lists what was archived; every other list wants the default.
5389
+ */
5390
+ includeArchived?: boolean
5391
+ } = {},
4878
5392
  ): Promise<FolderContents> {
4879
5393
  // 1. The folder itself. Both kinds in one trip: the state is the model and
4880
5394
  // the channel is what names a folder that has none yet.
@@ -4884,11 +5398,15 @@ export async function resolveFolderContents(
4884
5398
  ])
4885
5399
  const state = identity.find((e) => e.kind === KIND_FOLDER_STATE && tagValue(e, 'd') === folder)
4886
5400
  const channel = identity.find((e) => e.kind === KIND_CHANNEL && tagValue(e, 'd') === folder)
5401
+ const channelAddress = channel
5402
+ ? pointerToAddress({ kind: KIND_CHANNEL, pubkey: channel.pubkey, identifier: folder, relays: [] })
5403
+ : undefined
4887
5404
 
4888
5405
  const summary: FolderSummary & { address?: string } = {
4889
5406
  id: folder,
4890
5407
  name: nameOf(state) ?? nameOf(channel),
4891
5408
  hasState: !!state,
5409
+ ...(channelAddress ? { channel: channelAddress } : {}),
4892
5410
  ...(state
4893
5411
  ? { address: pointerToAddress({ kind: state.kind, pubkey: state.pubkey, identifier: folder, relays: [] }) }
4894
5412
  : {}),
@@ -4904,7 +5422,12 @@ export async function resolveFolderContents(
4904
5422
  : await addressesByContainment(folder, query)
4905
5423
 
4906
5424
  if (addresses.length === 0) {
4907
- return { ...summary, files: [], source: state ? 'state' : 'channel' }
5425
+ // Nothing listed, so no change query to ride on: the Folder's own archive
5426
+ // is one small read of its own.
5427
+ const archived = channelAddress
5428
+ ? archiveOf(await readArchiveChanges([channelAddress], query), channelAddress, ARCHIVE_RULE)
5429
+ : undefined
5430
+ return { ...summary, ...(archived ? { archived } : {}), files: [], source: state ? 'state' : 'channel' }
4908
5431
  }
4909
5432
 
4910
5433
  // 2. Group by (kind, author): one manifest answers for every file an app owns
@@ -4943,10 +5466,15 @@ export async function resolveFolderContents(
4943
5466
  // Change kinds are a set because two apps may fold differently, and a kind
4944
5467
  // is a u16 — the relay refuses an out-of-range one outright, so an app
4945
5468
  // declaring no `records` contributes no filter rather than an empty one.
5469
+ //
5470
+ // SPEC's change kind is always asked for, whatever the apps declare: any
5471
+ // file may be archived (FOL-46), a nested Folder included, and so may this
5472
+ // Folder, whose own address rides in the same filter.
4946
5473
  const changeKinds = [
4947
- ...new Set(
4948
- [...manifests.values()].flatMap((r) => (r.manifest.records ? [r.manifest.records.changeKind] : [])),
4949
- ),
5474
+ ...new Set([
5475
+ ARCHIVE_RULE.changeKind,
5476
+ ...[...manifests.values()].flatMap((r) => (r.manifest.records ? [r.manifest.records.changeKind] : [])),
5477
+ ]),
4950
5478
  ]
4951
5479
  const events = await query([
4952
5480
  ...[...groups.values()].map(({ pointer, addresses: group }) => ({
@@ -4955,13 +5483,23 @@ export async function resolveFolderContents(
4955
5483
  '#d': group.map((a) => referenceToPointer(a).identifier),
4956
5484
  limit: group.length,
4957
5485
  })),
4958
- ...(changeKinds.length
4959
- ? [{ kinds: changeKinds, '#a': addresses, limit: 500 }]
4960
- : []),
5486
+ { kinds: changeKinds, '#a': addresses, limit: 500 },
5487
+ // The archives again, in groups small enough that a busy Folder's other
5488
+ // changes cannot push them off the page — the filter above holds 500
5489
+ // changes for every file together, and one Folder has already had 688.
5490
+ // Same request.
5491
+ ...archiveFilters(channelAddress ? [...addresses, channelAddress] : addresses),
4961
5492
  ])
4962
-
4963
- // 4. Build each file, in the order the folder listed them.
4964
- const files: ForeignObject[] = []
5493
+ const ownArchive = channelAddress ? archiveOf(events, channelAddress, ARCHIVE_RULE) : undefined
5494
+ if (ownArchive) summary.archived = ownArchive
5495
+
5496
+ // 4. Build each file, in the order the folder listed them. Archived files are
5497
+ // held back until the cascade below has read their parents.
5498
+ const listed: { file: ForeignObject; archive?: Archive }[] = []
5499
+ const archiveByAddress = new Map<string, Archive | undefined>()
5500
+ const parentByAddress = new Map<string, string | undefined>()
5501
+ // How a parent outside this listing is read: its child's app's rule when that app draws it.
5502
+ const parentRuleOf = new Map<string, RecordsRule>()
4965
5503
  for (const { address, pointer } of pointers) {
4966
5504
  const resolved = manifests.get(manifestKeyOf(pointer))
4967
5505
  // No app claims this kind, so there is no projection to draw it with.
@@ -4979,11 +5517,18 @@ export async function resolveFolderContents(
4979
5517
  events.filter((e) => e.kind === records.changeKind && hasTagValue(e, records.targetTag, address)),
4980
5518
  records,
4981
5519
  )
5520
+ const archive = archiveOf(events, address, archiveRuleOf(resolved.manifest))
5521
+ archiveByAddress.set(address, archive)
5522
+ const parent = parentRefOf(resolved.manifest, pointer.kind, root, folded)
5523
+ parentByAddress.set(address, parent)
5524
+ if (parent) parentRuleOf.set(parent, relatedRuleOf(resolved.manifest, parent))
4982
5525
  // An app hiding a record from its own lists is saying it is not part of the
4983
- // folder any more. `hiddenWhen` is the app's own declaration of that.
4984
- if (records.hiddenWhen && folded[records.hiddenWhen.field]?.value === records.hiddenWhen.equals) {
4985
- continue
4986
- }
5526
+ // folder any more. `hiddenWhen` is the app's own declaration of that — the
5527
+ // archive above is the same statement for a kind whose app declared none.
5528
+ // Not reported as an archive: the app said "hidden", which may mean more.
5529
+ const hidden =
5530
+ !!records.hiddenWhen && folded[records.hiddenWhen.field]?.value === records.hiddenWhen.equals
5531
+ if (hidden && !archive) continue
4987
5532
  /*
4988
5533
  A placed file stays listed only while the placement is current.
4989
5534
 
@@ -5008,8 +5553,9 @@ export async function resolveFolderContents(
5008
5553
  })
5009
5554
  if (!current) continue
5010
5555
  }
5011
- files.push(
5012
- buildObject({
5556
+ listed.push({
5557
+ archive,
5558
+ file: buildObject({
5013
5559
  root,
5014
5560
  pointer,
5015
5561
  manifest: resolved.manifest,
@@ -5018,7 +5564,46 @@ export async function resolveFolderContents(
5018
5564
  viaRecommendation: resolved.viaRecommendation,
5019
5565
  webTemplate: resolved.webTemplate,
5020
5566
  }),
5021
- )
5567
+ })
5568
+ }
5569
+
5570
+ /*
5571
+ 5. The cascade (FOL-46): a file under an archived file is hidden with it —
5572
+ an issue with its project, a sub-topic with its topic. Computed here and
5573
+ never written to the children, so unarchiving the parent restores
5574
+ exactly what was there.
5575
+
5576
+ The chain is walked through everything this Folder lists. A parent that
5577
+ lives in another Folder is read once for all such parents, one level: a
5578
+ project whose record channel lists its issues is the case that matters,
5579
+ and there the project is listed too.
5580
+
5581
+ Only by parent. A file this Folder lists is never hidden because some
5582
+ *other* Folder that lists it is archived — that is what lets a file
5583
+ placed in two Folders stay visible in the one that is not archived.
5584
+ */
5585
+ const outside = [
5586
+ ...new Set(
5587
+ listed.flatMap(({ file }) => {
5588
+ const parent = file.address && parentByAddress.get(file.address)
5589
+ return parent && !archiveByAddress.has(parent) && addressPointerOf(parent) ? [parent] : []
5590
+ }),
5591
+ ),
5592
+ ]
5593
+ if (outside.length) {
5594
+ const ruleFor = (parent: string) => parentRuleOf.get(parent) ?? ARCHIVE_RULE
5595
+ const changes = await readArchiveChanges(outside, query, outside.map(ruleFor))
5596
+ for (const parent of outside) archiveByAddress.set(parent, archiveOf(changes, parent, ruleFor(parent)))
5597
+ }
5598
+ const files: ForeignObject[] = []
5599
+ for (const { file, archive } of listed) {
5600
+ const effective =
5601
+ archive ??
5602
+ (file.address
5603
+ ? archivedAncestorOf(file.address, (a) => parentByAddress.get(a), (a) => archiveByAddress.get(a))
5604
+ : undefined)
5605
+ if (!effective) files.push(file)
5606
+ else if (options.includeArchived) files.push({ ...file, archived: effective })
5022
5607
  }
5023
5608
 
5024
5609
  const people = await (lookupPeople ?? peopleViaRelay(query))([