@estiva-app/interop 0.35.0 → 0.37.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
@@ -15,6 +15,14 @@
15
15
  import { decodeNaddr, decodeNevent, encodeNaddr, encodeNevent, findNaddrs, pointerToAddress, referenceToPointer, type AddressPointer, type EventPointer } from '@estiva-app/protocol'
16
16
  import { imetaOf, parseProfile, type Imeta, type Profile, type SignedEvent } from '@estiva-app/protocol'
17
17
  import { MAX_FILTERS_PER_QUERY, RELAY_PAGE_CEILING } from '@estiva-app/protocol'
18
+ import {
19
+ attachmentsInDocument,
20
+ BLOCK_DOCUMENT_FORMAT,
21
+ CONTENT_FORMAT_TAG,
22
+ imetaTag,
23
+ parseBlockDocument,
24
+ } from '@estiva-app/protocol'
25
+ import { planPlaceFile, planUnlistFile, type FolderRef } from './folders.js'
18
26
 
19
27
  /** Query the relay. Returns matching events; shape mirrors the HTTP bridge. */
20
28
  export type QueryFn = (filters: Record<string, unknown>[]) => Promise<SignedEvent[]>
@@ -833,6 +841,17 @@ interface SlotSpec {
833
841
  * written before this reading exactly as it did.
834
842
  */
835
843
  match?: 'address' | 'identifier'
844
+ /**
845
+ * The field on the child whose change moves it to another parent — SPEC
846
+ * §7.2, MAN-1. `project` on Ship's issues, `parent` on a bare file.
847
+ *
848
+ * The `via` tag is written once, by the child's author, on a root only
849
+ * they may replace; a move is therefore a change event, and this names the
850
+ * field it sets. The folded value wins over the tag, and an empty one is a
851
+ * move to no parent. Ignored with `match: 'identifier'`, because a move's
852
+ * value is an address.
853
+ */
854
+ movedBy?: string
836
855
  }
837
856
  }
838
857
 
@@ -911,11 +930,38 @@ export interface ManifestAction {
911
930
  * published, this is what also gets fetched. See `commentKindsOf`.
912
931
  */
913
932
  alsoRead?: number[]
933
+ /**
934
+ * On a creation: the tag the new root names its Folder with — `h`, the
935
+ * default, or `buzz-channel` (SPEC §7.3, MAN-1).
936
+ *
937
+ * `buzz-channel` is how a Ship project is written: the relay stores the
938
+ * record globally, so anybody can discover the project, while its changes
939
+ * and comments keep `h`. Any other value is refused when building, because
940
+ * a Folder named in a tag nothing reads is no Folder.
941
+ */
942
+ placement?: string
943
+ /**
944
+ * That objects this action writes are named in their Folder's state, so a
945
+ * creation is followed by a `kind:1852` add and a deletion by a remove from
946
+ * each Folder listing it (SPEC §7.3, MAN-1; FOL-48).
947
+ *
948
+ * Only {@link buildActionEvents} builds one, because only its caller can
949
+ * say whether a Folder has state — a read, never a guess.
950
+ */
951
+ listed?: boolean
914
952
  }
915
953
  input?: {
916
954
  type: string
917
955
  /** For a scalar input: the vocabulary its value must come from. */
918
956
  enum?: string
957
+ /**
958
+ * For a scalar change: the richest content model the owner accepts for the
959
+ * value — SPEC §7.3's `format`, MAN-1. `estiva-blocks-1` is a block
960
+ * document (§13.3). A format on the declaration, not a new type, because
961
+ * the wire value is a string either way; a plain value is still accepted,
962
+ * written untagged as marker text (§13.4).
963
+ */
964
+ format?: string
919
965
  /**
920
966
  * For `type: 'object'`: the fields a consumer draws, and which are required.
921
967
  *
@@ -935,8 +981,12 @@ export interface ManifestAction {
935
981
  * At most one property may do it. Two would be two writers of one field,
936
982
  * and the second silently winning is exactly the shape of bug this
937
983
  * vocabulary exists to make impossible.
984
+ *
985
+ * **A property targeting `content` may declare a `format`** — MAN-1, the
986
+ * same field a scalar input declares. Meaningless on a property written to
987
+ * a tag, which is a scalar, and ignored there.
938
988
  */
939
- properties?: Record<string, { type?: string; enum?: string; target?: 'content' }>
989
+ properties?: Record<string, { type?: string; enum?: string; target?: 'content'; format?: string }>
940
990
  required?: string[]
941
991
  }
942
992
  }
@@ -965,10 +1015,31 @@ export interface ActionFormField {
965
1015
  * have to, and one that ignores it still publishes the right event.
966
1016
  */
967
1017
  target?: 'content'
1018
+ /**
1019
+ * That the field is prose the owner accepts as a block document — MAN-1.
1020
+ *
1021
+ * Set only for a content field declaring a format this version writes, so a
1022
+ * consumer that sees it may draw a block editor and pass
1023
+ * `contentFormat: 'estiva-blocks-1'` to {@link buildActionEvent}. A consumer
1024
+ * that draws a text box instead still publishes a correct event (§7.3).
1025
+ */
1026
+ format?: ProseFormat
968
1027
  /** When the property names a vocabulary, its entries, already looked up. */
969
1028
  options?: { value: string; label: string; colour?: string }[]
970
1029
  }
971
1030
 
1031
+ /**
1032
+ * The content formats a declaration may name and this version writes — only
1033
+ * SPEC §13.3's block document. An unknown format is not surfaced, so no
1034
+ * consumer draws an editor for a model nothing here can tag correctly.
1035
+ */
1036
+ export type ProseFormat = typeof BLOCK_DOCUMENT_FORMAT
1037
+
1038
+ /** The declared format, when it is one this version writes. */
1039
+ function proseFormatOf(declared: unknown): ProseFormat | undefined {
1040
+ return declared === BLOCK_DOCUMENT_FORMAT ? BLOCK_DOCUMENT_FORMAT : undefined
1041
+ }
1042
+
972
1043
  export interface ResolvedAction {
973
1044
  id: string
974
1045
  label: string
@@ -1003,6 +1074,18 @@ export interface ResolvedAction {
1003
1074
  * properties would publish an orphan.
1004
1075
  */
1005
1076
  createsUnder?: string
1077
+ /**
1078
+ * For a `text` change: that the value is prose the owner accepts as a block
1079
+ * document (MAN-1). See {@link ActionFormField.format} — the same rule for a
1080
+ * field of a form.
1081
+ */
1082
+ format?: ProseFormat
1083
+ /**
1084
+ * That building this action needs to know the Folder's state: whether it has
1085
+ * any, for a creation, or which Folders name the object, for a deletion
1086
+ * (`emits.listed`, MAN-1). Pass it to {@link buildActionEvents}.
1087
+ */
1088
+ listed?: true
1006
1089
  /** The value this field holds right now, so a control can show it. */
1007
1090
  current?: string
1008
1091
  field?: string
@@ -1062,7 +1145,7 @@ function resolveActions(
1062
1145
  */
1063
1146
  const isChange = !!action.emits.field
1064
1147
  const isComment = action.emits.scope === 'address'
1065
- const isCreation = action.input?.type === 'object' && !!action.input.properties
1148
+ const isCreation = isCreationAction(action)
1066
1149
  // Four, since 0.25.0. Decided by the kind before the other three, so a
1067
1150
  // manifest that put `scope: 'address'` on its deletion — the target *is*
1068
1151
  // an address — is not mistaken for a comment.
@@ -1076,6 +1159,7 @@ function resolveActions(
1076
1159
  ...(action.description ? { description: action.description } : {}),
1077
1160
  ...(action.effect ? { effect: action.effect } : {}),
1078
1161
  control: 'confirm',
1162
+ ...(action.emits.listed === true ? { listed: true as const } : {}),
1079
1163
  })
1080
1164
  continue
1081
1165
  }
@@ -1103,6 +1187,8 @@ function resolveActions(
1103
1187
  a one-line input and drawing prose.
1104
1188
  */
1105
1189
  ...(spec.target ? { target: spec.target } : {}),
1190
+ // Prose only where the value is `content` — a tag is a scalar (§7.3).
1191
+ ...(spec.target === 'content' && proseFormatOf(spec.format) ? { format: proseFormatOf(spec.format) } : {}),
1106
1192
  ...(spec.enum && manifest.vocabularies?.[spec.enum]
1107
1193
  ? {
1108
1194
  options: manifest.vocabularies[spec.enum].map((v) => ({
@@ -1117,17 +1203,23 @@ function resolveActions(
1117
1203
  // comes from `emits`, and a form that omitted it would publish an
1118
1204
  // orphan the owning app cannot show anywhere.
1119
1205
  ...(action.emits.toAddressOf ? { createsUnder: action.emits.toAddressOf } : {}),
1206
+ ...(action.emits.listed === true ? { listed: true as const } : {}),
1120
1207
  })
1121
1208
  continue
1122
1209
  }
1123
1210
 
1124
1211
  const vocab = action.input?.enum ? manifest.vocabularies?.[action.input.enum] : undefined
1212
+ const control = vocab ? 'select' : action.input?.type === 'pubkey' ? 'pubkey' : 'text'
1213
+ // A change only: a comment's body is §13.2 marker text, and a format on
1214
+ // one is nothing this version writes (`buildActionEvent` refuses it).
1215
+ const format = control === 'text' && isChange ? proseFormatOf(action.input?.format) : undefined
1125
1216
  out.push({
1126
1217
  id: action.id,
1127
1218
  label: action.label,
1128
1219
  ...(action.description ? { description: action.description } : {}),
1129
1220
  ...(action.effect ? { effect: action.effect } : {}),
1130
- control: vocab ? 'select' : action.input?.type === 'pubkey' ? 'pubkey' : 'text',
1221
+ control,
1222
+ ...(format ? { format } : {}),
1131
1223
  options: vocab?.map((v) => ({ value: v.value, label: v.label, colour: v.colour })),
1132
1224
  current: action.emits.field ? folded[action.emits.field]?.value : undefined,
1133
1225
  field: action.emits.field,
@@ -1391,6 +1483,19 @@ export interface ResolvedManifest {
1391
1483
  */
1392
1484
  export const KIND_BARE_FILE = 30840
1393
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
+
1394
1499
  /**
1395
1500
  * Where a `ResolvedManifest.address` would name the manifest event, this names
1396
1501
  * the section of the specification the manifest is built from. Not an address,
@@ -1399,9 +1504,6 @@ export const KIND_BARE_FILE = 30840
1399
1504
  */
1400
1505
  export const BARE_FILE_MANIFEST_ADDRESS = 'spec:6.7'
1401
1506
 
1402
- /** The field a bare file's `kind:1851` re-parent sets (SPEC §6.7). */
1403
- const BARE_FILE_PARENT_FIELD = 'parent'
1404
-
1405
1507
  const BARE_FILE_MANIFEST: Manifest = {
1406
1508
  name: 'File',
1407
1509
  about: 'A file no app owns. Its conversation is what every file has; its type adds nothing.',
@@ -1424,7 +1526,11 @@ const BARE_FILE_MANIFEST: Manifest = {
1424
1526
  // of *other* kinds are found the other way round, by their own `a`
1425
1527
  // (`parentRefOf` below), which is FOL-4's generic direction; this slot
1426
1528
  // is the one the existing `list` machinery can draw today.
1427
- list: { children: { kind: KIND_BARE_FILE, via: 'a', limit: 200 } },
1529
+ //
1530
+ // `movedBy` is SPEC §6.7's `parent` field, declared rather than
1531
+ // hard-coded since MAN-1, so a bare file moves by the rule every other
1532
+ // kind does — the move action below sets the same field.
1533
+ list: { children: { kind: KIND_BARE_FILE, via: 'a', limit: 200, movedBy: 'parent' } },
1428
1534
  },
1429
1535
  },
1430
1536
  /*
@@ -1498,9 +1604,26 @@ const BARE_FILE_MANIFEST: Manifest = {
1498
1604
  'the team may; who can read the file does not change.',
1499
1605
  effect: 'writes',
1500
1606
  appliesTo: [String(KIND_BARE_FILE)],
1501
- emits: { kind: 1851, field: BARE_FILE_PARENT_FIELD },
1607
+ emits: { kind: 1851, field: 'parent' },
1502
1608
  input: { type: 'string' },
1503
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
+ },
1504
1627
  {
1505
1628
  id: 'delete',
1506
1629
  label: 'Delete',
@@ -1512,6 +1635,13 @@ const BARE_FILE_MANIFEST: Manifest = {
1512
1635
  emits: { kind: KIND_DELETION },
1513
1636
  },
1514
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
+ },
1515
1645
  }
1516
1646
 
1517
1647
  function bareFileManifest(): ResolvedManifest {
@@ -1938,6 +2068,112 @@ function foldChanges(changes: SignedEvent[], rule: RecordsRule) {
1938
2068
  return fields
1939
2069
  }
1940
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
+
1941
2177
  function truncate(text: string, limit?: number) {
1942
2178
  if (!limit || text.length <= limit) return text
1943
2179
  return `${text.slice(0, limit).trimEnd()}…`
@@ -2116,6 +2352,48 @@ export function actionProblems(declared: unknown): string[] {
2116
2352
  }
2117
2353
  }
2118
2354
 
2355
+ /*
2356
+ MAN-1's three declarations, each of which fails quietly on the consumer's
2357
+ side: an unknown placement or format is refused or ignored at the button,
2358
+ and a `listed` on a change is simply never acted on.
2359
+ */
2360
+ const emits = (action as { emits?: { kind?: unknown; field?: unknown; placement?: unknown; listed?: unknown } }).emits
2361
+ const input = (action as { input?: { type?: unknown; format?: unknown } }).input
2362
+ const creates = input?.type === 'object' && !!properties
2363
+ if (emits?.placement !== undefined && !(creates && PLACEMENTS.includes(emits.placement as string))) {
2364
+ problems.push(
2365
+ creates
2366
+ ? `${name} places its object with ${JSON.stringify(emits.placement)}, and a Folder is named by ${PLACEMENTS.join(' or ')} — a consumer refuses the action.`
2367
+ : `${name} declares a placement and creates nothing; only a new root names its Folder, so it is ignored.`,
2368
+ )
2369
+ }
2370
+ if (emits?.listed !== undefined && emits.listed !== true) {
2371
+ problems.push(`${name} declares listed ${JSON.stringify(emits.listed)}; the only value is true.`)
2372
+ } else if (emits?.listed === true && !creates && emits.kind !== KIND_DELETION) {
2373
+ problems.push(`${name} declares listed on an action that neither creates nor deletes, so no Folder command follows it.`)
2374
+ }
2375
+ const formats: [string, unknown, boolean][] = [
2376
+ // A scalar format means something on a change only: a comment's body is
2377
+ // marker text, and a deletion takes no value.
2378
+ ...(input?.format !== undefined
2379
+ ? [['its input', input.format, !creates && !!emits?.field && emits.kind !== KIND_DELETION] as [string, unknown, boolean]]
2380
+ : []),
2381
+ ...Object.entries(properties && typeof properties === 'object' ? properties : {})
2382
+ .filter(([, spec]) => (spec as { format?: unknown } | null)?.format !== undefined)
2383
+ .map(([property, spec]): [string, unknown, boolean] => [
2384
+ `"${property}"`,
2385
+ (spec as { format?: unknown }).format,
2386
+ (spec as { target?: unknown }).target === 'content',
2387
+ ]),
2388
+ ]
2389
+ for (const [where, format, applies] of formats) {
2390
+ if (!applies) {
2391
+ problems.push(`${name} declares a format on ${where}, which is neither a creation's content nor a change's value, so it is ignored.`)
2392
+ } else if (!proseFormatOf(format)) {
2393
+ problems.push(`${name} declares format ${JSON.stringify(format)} on ${where}, and the only format is ${BLOCK_DOCUMENT_FORMAT}. A consumer draws it as plain text.`)
2394
+ }
2395
+ }
2396
+
2119
2397
  return problems
2120
2398
  }
2121
2399
 
@@ -2454,8 +2732,10 @@ export interface ForeignObject {
2454
2732
  */
2455
2733
  parentRef?: string
2456
2734
  /**
2457
- * The folded field that re-parents this object, when there is one — `parent`
2458
- * on a bare file (SPEC §6.7), absent for every other kind today (FOL-4).
2735
+ * The folded field that re-parents this object, when its owner declares one
2736
+ * — SPEC §7.2's `movedBy`: `parent` on a bare file (§6.7), `project` on an
2737
+ * issue whose app declares it (MAN-1). Hard-coded to the bare file before
2738
+ * 0.36.0.
2459
2739
  *
2460
2740
  * **For a consumer that draws field-setting actions as property rows.** The
2461
2741
  * action setting this field is a move, and its value is an address: drawn as
@@ -2464,6 +2744,14 @@ export interface ForeignObject {
2464
2744
  * title's rename takes, matched on the field for the same reason.
2465
2745
  */
2466
2746
  parentField?: string
2747
+ /**
2748
+ * The kind a move may name — the kind whose projection declares the
2749
+ * `movedBy` (MAN-1): `30850` for a Ship issue, so a move control offers
2750
+ * projects and not other issues. Absent with `parentField` on a bare file,
2751
+ * which may sit under any kind (§6.7). {@link nestingOf}'s `moveTargetsOf`
2752
+ * reads it.
2753
+ */
2754
+ parentKind?: number
2467
2755
  kind: number
2468
2756
  /**
2469
2757
  * The layout hint the owner declared — **a type or an ordered chain of them.**
@@ -2534,6 +2822,15 @@ export interface ForeignObject {
2534
2822
  * rendering nothing.
2535
2823
  */
2536
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
2537
2834
  }
2538
2835
 
2539
2836
 
@@ -2552,6 +2849,7 @@ function buildObject(args: {
2552
2849
  viaRecommendation: boolean
2553
2850
  webTemplate?: string
2554
2851
  comments?: ForeignObject['comments']
2852
+ archived?: Archive
2555
2853
  }): ForeignObject {
2556
2854
  const { root, pointer, manifest, projection, folded } = args
2557
2855
  const naddr = encodeNaddr(pointer)
@@ -2592,7 +2890,7 @@ function buildObject(args: {
2592
2890
  comments: args.comments ?? [],
2593
2891
  listsChildren: listsChildrenOf(projection, manifest),
2594
2892
  parentRef: parentRefOf(manifest, pointer.kind, root, folded),
2595
- ...(pointer.kind === KIND_BARE_FILE ? { parentField: BARE_FILE_PARENT_FIELD } : {}),
2893
+ ...parentFieldsOf(manifest, pointer.kind),
2596
2894
  folder: tagValue(root, 'h'),
2597
2895
  // Substituted here rather than in the component: `<bech32>` is a NIP-89
2598
2896
  // detail, and the widget's job is to draw a link, not to know the spec.
@@ -2603,6 +2901,7 @@ function buildObject(args: {
2603
2901
  : action,
2604
2902
  ),
2605
2903
  viaRecommendation: args.viaRecommendation,
2904
+ ...(args.archived ? { archived: args.archived } : {}),
2606
2905
  }
2607
2906
  }
2608
2907
 
@@ -2710,6 +3009,7 @@ export async function resolveForeignObject(
2710
3009
  * omitting it is exactly the old behaviour.
2711
3010
  */
2712
3011
  cache?: ProjectionCache,
3012
+ options: ArchiveReadOptions = {},
2713
3013
  ): Promise<ForeignObject | null> {
2714
3014
  const pointer = addressPointerOf(naddr)
2715
3015
  if (!pointer) return null
@@ -2720,6 +3020,7 @@ export async function resolveForeignObject(
2720
3020
 
2721
3021
  const assembled = assembleObject(plan, await query(plan.filters))
2722
3022
  if (assembled.object.unreachable) return assembled.object
3023
+ if (options.archivedWith) await markArchivedParents([assembled.object], query)
2723
3024
  return withPeople(assembled, await (lookupPeople ?? peopleViaRelay(query))(peopleOf(assembled)))
2724
3025
  }
2725
3026
 
@@ -2766,6 +3067,7 @@ export async function resolveForeignObjects(
2766
3067
  lookupPeople?: PeopleFn,
2767
3068
  /** See {@link ProjectionCache}. Omitting it still reads each app's manifest once per call. */
2768
3069
  cache?: ProjectionCache,
3070
+ options: ArchiveReadOptions = {},
2769
3071
  ): Promise<Record<string, ForeignObject | null>> {
2770
3072
  const results: Record<string, ForeignObject | null> = {}
2771
3073
  const asked: { reference: string; pointer: AddressPointer }[] = []
@@ -2812,6 +3114,7 @@ export async function resolveForeignObjects(
2812
3114
  const events = (await Promise.all(chunks.map((chunk) => query(chunk)))).flat()
2813
3115
 
2814
3116
  const assembled = plans.map(({ reference, plan }) => ({ reference, built: assembleObject(plan, events) }))
3117
+ if (options.archivedWith) await markArchivedParents(assembled.map(({ built }) => built.object), query)
2815
3118
  const wanted = [...new Set(assembled.flatMap(({ built }) => peopleOf(built)))]
2816
3119
  const reachable = assembled.some(({ built }) => !built.object.unreachable)
2817
3120
  const people = reachable ? await (lookupPeople ?? peopleViaRelay(query))(wanted) : {}
@@ -2830,6 +3133,73 @@ export async function resolveForeignObjects(
2830
3133
  return results
2831
3134
  }
2832
3135
 
3136
+ /** What {@link resolveForeignObject} and {@link resolveForeignObjects} may read beyond the file itself. */
3137
+ export interface ArchiveReadOptions {
3138
+ /**
3139
+ * Also read whether each file's parent is archived, and mark the file
3140
+ * archived **with** it (`archived.with`) — FOL-46. For the page a link opens,
3141
+ * which draws the banner; off by default because it is one more request
3142
+ * whenever a file has a parent, and a refresh tick that resolves an issue
3143
+ * card would pay it every time (SHI-13's one request per tick).
3144
+ */
3145
+ archivedWith?: boolean
3146
+ }
3147
+
3148
+ /**
3149
+ * Mark each object that is hidden with an archived parent — FOL-46.
3150
+ *
3151
+ * An issue whose project is archived is archived with it, and its page says so
3152
+ * rather than drawing live work. The cascade is computed here and never written
3153
+ * to the issue, so unarchiving the project restores it exactly.
3154
+ *
3155
+ * **One read for the whole set, and only when some object has a parent**, so a
3156
+ * topic page or a project page pays nothing. One level: the parent's own
3157
+ * parent is not followed, because the page is about this file and its
3158
+ * container, and a deeper walk is a round trip per level. A Folder listing
3159
+ * walks the whole chain it holds ({@link resolveFolderContents}).
3160
+ *
3161
+ * The parent is folded by SPEC's rule, which every Estiva app writes: the
3162
+ * parent may belong to another app, whose manifest is not in hand.
3163
+ */
3164
+ async function markArchivedParents(objects: ForeignObject[], query: QueryFn): Promise<void> {
3165
+ const waiting = objects.filter((o) => !o.unreachable && !o.archived && o.parentRef && addressPointerOf(o.parentRef))
3166
+ if (waiting.length === 0) return
3167
+ const parents = [...new Set(waiting.map((o) => o.parentRef!))]
3168
+ const changes = await readArchiveChanges(parents, query)
3169
+ for (const object of waiting) {
3170
+ const archive = archiveOf(changes, object.parentRef!, ARCHIVE_RULE)
3171
+ if (archive) object.archived = { ...archive, with: object.parentRef! }
3172
+ }
3173
+ }
3174
+
3175
+ /**
3176
+ * Addresses per filter when reading archive changes. A filter's `limit` caps
3177
+ * every change naming its addresses — titles, statuses, moves — not only the
3178
+ * archives, and a relay answers newest first, so a small group keeps the
3179
+ * archive change inside the page.
3180
+ */
3181
+ const ARCHIVE_READ_GROUP = 25
3182
+
3183
+ /** The filters asking for every SPEC-shaped change naming these addresses. */
3184
+ function archiveFilters(addresses: readonly string[]): Record<string, unknown>[] {
3185
+ const filters: Record<string, unknown>[] = []
3186
+ for (let start = 0; start < addresses.length; start += ARCHIVE_READ_GROUP) {
3187
+ const group = addresses.slice(start, start + ARCHIVE_READ_GROUP)
3188
+ filters.push({ kinds: [ARCHIVE_RULE.changeKind], '#a': group, limit: RELAY_PAGE_CEILING })
3189
+ }
3190
+ return filters
3191
+ }
3192
+
3193
+ /** Every SPEC-shaped change naming these addresses, in as few requests as the relay allows. */
3194
+ async function readArchiveChanges(addresses: readonly string[], query: QueryFn): Promise<SignedEvent[]> {
3195
+ const filters = archiveFilters(addresses)
3196
+ const events: SignedEvent[] = []
3197
+ for (let start = 0; start < filters.length; start += MAX_FILTERS_PER_QUERY) {
3198
+ events.push(...(await query(filters.slice(start, start + MAX_FILTERS_PER_QUERY))))
3199
+ }
3200
+ return events
3201
+ }
3202
+
2833
3203
  /** An `naddr` or a `<kind>:<pubkey>:<d>`, or null for anything else. */
2834
3204
  function addressPointerOf(reference: string): AddressPointer | null {
2835
3205
  try {
@@ -2901,6 +3271,9 @@ function planObject(
2901
3271
  { kinds: [pointer.kind], authors: [pointer.pubkey], '#d': [pointer.identifier], limit: 1 },
2902
3272
  // Only when the app actually declares a change kind — see `foldRuleOf`.
2903
3273
  ...(manifest.records ? [{ kinds: [manifest.records.changeKind], '#a': [address], limit: 500 }] : []),
3274
+ // Every file may be archived, including one whose app folds nothing
3275
+ // (FOL-46). SPEC's change kind, when the app has not named its own.
3276
+ ...(manifest.records ? [] : [{ kinds: [ARCHIVE_RULE.changeKind], '#a': [address], limit: 500 }]),
2904
3277
  { kinds: commentKinds, '#a': [address], limit: CONVERSATION_LIMIT },
2905
3278
  ...(childFilter ? [childFilter.filter] : []),
2906
3279
  ]
@@ -3002,6 +3375,7 @@ function assembleObject(plan: ObjectPlan, answered: SignedEvent[]): AssembledObj
3002
3375
  viaRecommendation,
3003
3376
  webTemplate: resolved.webTemplate,
3004
3377
  comments,
3378
+ archived: archiveOf(events, address, archiveRuleOf(manifest)),
3005
3379
  })
3006
3380
  /*
3007
3381
  The `list` slot — PRO-7.
@@ -3073,7 +3447,7 @@ function withPeople({ object, children }: AssembledObject, people: People): Fore
3073
3447
  */
3074
3448
  function declaredChildSpec(projection: {
3075
3449
  slots: Record<string, SlotSpec | SlotSpec[]>
3076
- }): { kind: number; via: string; limit?: number; match?: string } | undefined {
3450
+ }): { kind: number; via: string; limit?: number; match?: string; movedBy?: string } | undefined {
3077
3451
  const spec = projection.slots.list
3078
3452
  return !Array.isArray(spec) ? spec?.children : undefined
3079
3453
  }
@@ -3108,15 +3482,24 @@ function parentRefOf(
3108
3482
  direction lets Ship's project list its issues without an issue knowing what
3109
3483
  a project is; this one lets a topic sit under a project, an issue, or a kind
3110
3484
  nobody has met, without that kind's owner declaring bare files as children.
3111
- Re-parenting is a `parent` change event, seeded by the root tag, the way an
3112
- issue's `project` field works (SPEC §6.7).
3485
+ Re-parenting is a change to the declared `movedBy` field, seeded by the
3486
+ root tag — `parent` on a bare file, `project` on a Ship issue (SPEC §7.2).
3113
3487
  */
3114
- if (kind === KIND_BARE_FILE) {
3488
+ const movedBy = movedByOf(manifest, kind)
3489
+ if (movedBy) {
3115
3490
  // A folded empty value is a move to the top, not an absence: falling back
3116
3491
  // to the root tag would put the file straight back under the parent it
3117
3492
  // was moved out of (FOL-4).
3118
- const moved = folded[BARE_FILE_PARENT_FIELD]
3119
- if (moved) return moved.value || undefined
3493
+ // A value that is not an address of the declared parent kind names nothing
3494
+ // this object can sit under, so it is a move to nowhere rather than a ref a
3495
+ // consumer might try to fetch.
3496
+ const moved = folded[movedBy.field]
3497
+ if (moved) {
3498
+ const prefix = movedBy.parentKind === undefined ? /^\d+:[0-9a-f]{64}:/ : new RegExp(`^${movedBy.parentKind}:[0-9a-f]{64}:`)
3499
+ return prefix.test(moved.value) ? moved.value : undefined
3500
+ }
3501
+ }
3502
+ if (kind === KIND_BARE_FILE) {
3120
3503
  return root.tags.find((t) => t[0] === 'a' && t[1] && /^\d+:[0-9a-f]{64}:/.test(t[1]))?.[1]
3121
3504
  }
3122
3505
  for (const [parentKind, projection] of Object.entries(manifest.projections ?? {})) {
@@ -3137,6 +3520,34 @@ function parentRefOf(
3137
3520
  return undefined
3138
3521
  }
3139
3522
 
3523
+ /**
3524
+ * The field that moves a `kind` object to another parent, and the kind of
3525
+ * parent it names — SPEC §7.2's `movedBy`, read off whichever projection lists
3526
+ * `kind` as its children (MAN-1).
3527
+ *
3528
+ * `parentKind` is absent for a bare file: §6.7 lets one sit under a file of any
3529
+ * kind, so its own list naming bare files is not a limit on where it may go.
3530
+ * Absent too for `match: 'identifier'`, where `movedBy` is ignored because a
3531
+ * move's value is an address and that list compares identifiers.
3532
+ */
3533
+ function movedByOf(manifest: Manifest, kind: number): { field: string; parentKind?: number } | undefined {
3534
+ for (const [parentKind, projection] of Object.entries(manifest.projections ?? {})) {
3535
+ const children = declaredChildSpec(projection as { slots: Record<string, SlotSpec | SlotSpec[]> })
3536
+ if (!children || children.kind !== kind || !children.movedBy || children.match === 'identifier') continue
3537
+ return kind === KIND_BARE_FILE ? { field: children.movedBy } : { field: children.movedBy, parentKind: Number(parentKind) }
3538
+ }
3539
+ return undefined
3540
+ }
3541
+
3542
+ /** {@link movedByOf} as the two `ForeignObject` fields, both builders' shape. */
3543
+ function parentFieldsOf(manifest: Manifest, kind: number): { parentField?: string; parentKind?: number } {
3544
+ const moved = movedByOf(manifest, kind)
3545
+ if (!moved) return {}
3546
+ return moved.parentKind === undefined
3547
+ ? { parentField: moved.field }
3548
+ : { parentField: moved.field, parentKind: moved.parentKind }
3549
+ }
3550
+
3140
3551
  /** Both halves of the question a disclosure control asks. */
3141
3552
  function listsChildrenOf(
3142
3553
  projection: { slots: Record<string, SlotSpec | SlotSpec[]> },
@@ -3270,7 +3681,7 @@ function buildChildObject(args: {
3270
3681
  // an inconsistent shape is what makes a consumer defensive about a value it
3271
3682
  // should be able to trust.
3272
3683
  parentRef: parentRefOf(manifest, root.kind, root),
3273
- ...(root.kind === KIND_BARE_FILE ? { parentField: BARE_FILE_PARENT_FIELD } : {}),
3684
+ ...parentFieldsOf(manifest, root.kind),
3274
3685
  folder: tagValue(root, 'h'),
3275
3686
  /*
3276
3687
  `<bech32>` is whichever form this object actually has.
@@ -3910,6 +4321,51 @@ export async function resolveFolderProject(
3910
4321
  */
3911
4322
  const isAddressableKind = (kind: number) => kind >= 30000 && kind < 40000
3912
4323
 
4324
+ /**
4325
+ * The tags a new root may name its Folder with — SPEC §7.3's `placement`.
4326
+ *
4327
+ * The two a relay indexes for a Folder's containment read and {@link folderOf}
4328
+ * reads. Closed, because a root placed in any other tag belongs to no Folder
4329
+ * and nothing would say so.
4330
+ */
4331
+ const PLACEMENTS: readonly string[] = ['h', 'buzz-channel']
4332
+
4333
+ /**
4334
+ * The tags a prose value carries — SPEC §7.3's `format`, MAN-1.
4335
+ *
4336
+ * **Tagged only when the caller says the value is in the declared format**, and
4337
+ * then checked, because a reader decides the model by the tag alone (§13.4): a
4338
+ * `content-format` on marker text renders nothing, and one on a document the
4339
+ * relay cannot parse renders JSON at a person. Without `contentFormat` the value
4340
+ * is marker text and carries nothing, which every reader must accept — so a
4341
+ * consumer that draws a text box for a prose field still publishes correctly.
4342
+ *
4343
+ * A document's attachments are named again as `imeta`, which §13.3 requires of
4344
+ * every event holding one and which ingest verifies against stored blobs.
4345
+ */
4346
+ function proseTags(args: {
4347
+ label: string
4348
+ declared: string | undefined
4349
+ contentFormat: string | undefined
4350
+ value: string
4351
+ }): string[][] | string {
4352
+ const { label, declared, contentFormat, value } = args
4353
+ if (contentFormat === undefined) return []
4354
+ if (proseFormatOf(declared) !== contentFormat) {
4355
+ return proseFormatOf(declared)
4356
+ ? `"${label}" takes ${proseFormatOf(declared)}, not ${contentFormat}.`
4357
+ : `"${label}" declares no ${contentFormat} value, so it is written as plain text.`
4358
+ }
4359
+ // Clearing a field is not a document; an empty value says nothing to tag.
4360
+ if (value === '') return []
4361
+ try {
4362
+ parseBlockDocument(value)
4363
+ } catch (e) {
4364
+ return `"${label}" was handed ${contentFormat} that is ${(e as Error).message}.`
4365
+ }
4366
+ return [[CONTENT_FORMAT_TAG, contentFormat], ...attachmentsInDocument(value, contentFormat).map(imetaTag)]
4367
+ }
4368
+
3913
4369
  /**
3914
4370
  * The event an object-creating action publishes.
3915
4371
  *
@@ -3929,6 +4385,7 @@ function buildCreationEvent(args: {
3929
4385
  folder: string
3930
4386
  value: string | Record<string, string>
3931
4387
  newId?: string
4388
+ contentFormat?: string
3932
4389
  pubkey: string
3933
4390
  createdAtMs: number
3934
4391
  }): UnsignedActionEvent | string {
@@ -3982,6 +4439,20 @@ function buildCreationEvent(args: {
3982
4439
  }
3983
4440
  const bodyField = bodyFields[0]
3984
4441
 
4442
+ const placement = declared.emits.placement ?? 'h'
4443
+ if (!PLACEMENTS.includes(placement)) {
4444
+ return `"${declared.label}" places its object with "${placement}", and a Folder is named by ${PLACEMENTS.join(' or ')}.`
4445
+ }
4446
+
4447
+ // Only the content field can be prose, so only its value is ever tagged.
4448
+ const prose = proseTags({
4449
+ label: declared.label,
4450
+ declared: bodyField ? properties[bodyField]?.format : undefined,
4451
+ contentFormat: args.contentFormat,
4452
+ value: bodyField ? (value[bodyField] ?? '') : '',
4453
+ })
4454
+ if (typeof prose === 'string') return prose
4455
+
3985
4456
  const tags: string[][] = []
3986
4457
  if (isAddressableKind(declared.emits.kind)) tags.push(['d', newId!])
3987
4458
  // A property's name is the tag it writes, unless it declared `content`. See
@@ -3995,7 +4466,7 @@ function buildCreationEvent(args: {
3995
4466
  if (declared.emits.setTag && declared.emits.toAddressOf === 'self') {
3996
4467
  tags.push([declared.emits.setTag, address])
3997
4468
  }
3998
- tags.push(['h', folder])
4469
+ tags.push([placement, folder], ...prose)
3999
4470
 
4000
4471
  return {
4001
4472
  pubkey: args.pubkey,
@@ -4006,7 +4477,8 @@ function buildCreationEvent(args: {
4006
4477
  }
4007
4478
  }
4008
4479
 
4009
- export function buildActionEvent(args: {
4480
+ /** What {@link buildActionEvent} and {@link buildActionEvents} are handed. */
4481
+ export interface ActionEventArgs {
4010
4482
  manifest: { records?: RecordsRule; actions?: ManifestAction[]; vocabularies?: Manifest['vocabularies'] }
4011
4483
  kind: number
4012
4484
  /** Address of the object being acted on. */
@@ -4041,9 +4513,103 @@ export function buildActionEvent(args: {
4041
4513
  * Refused on any action that is not a comment: nothing else has a parent.
4042
4514
  */
4043
4515
  replyTo?: { id: string; kind: number; author: string }
4516
+ /**
4517
+ * The format the action's prose value is in, when it is not marker text —
4518
+ * `'estiva-blocks-1'` for a block document (SPEC §7.3's `format`, MAN-1).
4519
+ *
4520
+ * The value of a scalar change, or of a creation's `content` field. Only a
4521
+ * format the action declares for that value is accepted, and the value is
4522
+ * parsed before it is tagged. Omitted, the value is written untagged as
4523
+ * marker text, which is always correct.
4524
+ */
4525
+ contentFormat?: string
4526
+ /**
4527
+ * What the person said about a change, carried as its `content` — the
4528
+ * resolution summary of an archive (FOL-46), or any change's note. A change
4529
+ * only: a comment's text is its `value`, and a creation has its own body.
4530
+ */
4531
+ note?: string
4044
4532
  pubkey: string
4045
4533
  createdAtMs: number
4046
- }): UnsignedActionEvent | string {
4534
+ }
4535
+
4536
+ /**
4537
+ * Build the event that performs a manifest-declared action — one event.
4538
+ *
4539
+ * **Refuses an action declaring `emits.listed`**, which is more than one event
4540
+ * (SPEC §7.3): building the root alone would publish an object its Folder does
4541
+ * not show, and report success. {@link buildActionEvents} builds those.
4542
+ */
4543
+ export function buildActionEvent(args: ActionEventArgs): UnsignedActionEvent | string {
4544
+ const declared = args.manifest.actions?.find((a) => a.id === args.actionId)
4545
+ if (declared?.emits.listed === true && (declared.emits.kind === KIND_DELETION || isCreationAction(declared))) {
4546
+ return `"${declared.label}" is followed by a Folder command, so it is built with buildActionEvents.`
4547
+ }
4548
+ return buildOneActionEvent(args)
4549
+ }
4550
+
4551
+ /** An action that makes a new object rather than changing one — a form. */
4552
+ function isCreationAction(declared: ManifestAction): boolean {
4553
+ return declared.input?.type === 'object' && !!declared.input.properties
4554
+ }
4555
+
4556
+ /**
4557
+ * Every event an action publishes, **in publish order** — SPEC §7.3, MAN-1.
4558
+ *
4559
+ * The first is what {@link buildActionEvent} builds. An action declaring
4560
+ * `emits.listed` is followed by the Folder commands that keep its Folder's
4561
+ * listing true, planned by `planPlaceFile` / `planUnlistFile`:
4562
+ *
4563
+ * - a creation: `kind:1852 add` naming the new address in the Folder it was
4564
+ * placed in, when `folderHasState` — none when the Folder has no state, where
4565
+ * a command would hide everything else filed there;
4566
+ * - a deletion: `kind:1852 remove` from each of `listedIn` that has state.
4567
+ *
4568
+ * Both facts come from the caller's read of `kind:30890` and are required
4569
+ * rather than defaulted, because a guess here is silent loss. Publish in order
4570
+ * and stop at the first refusal: each event assumes the ones before it landed.
4571
+ */
4572
+ export function buildActionEvents(
4573
+ args: ActionEventArgs & {
4574
+ /** For a `listed` creation: whether the Folder has state — from a read. */
4575
+ folderHasState?: boolean
4576
+ /** For a `listed` deletion: every Folder that lists the object, with `hasState` — from a read. */
4577
+ listedIn?: readonly FolderRef[]
4578
+ },
4579
+ ): UnsignedActionEvent[] | string {
4580
+ const first = buildOneActionEvent(args)
4581
+ if (typeof first === 'string') return first
4582
+ const declared = args.manifest.actions!.find((a) => a.id === args.actionId)!
4583
+ if (declared.emits.listed !== true) return [first]
4584
+
4585
+ if (declared.emits.kind === KIND_DELETION) {
4586
+ if (!args.listedIn) return `"${declared.label}" unlists what it deletes, and needs the Folders that list it.`
4587
+ // One remove per Folder, however many reads it came back from.
4588
+ const folders = [...new Map(args.listedIn.map((listing) => [listing.id, listing])).values()]
4589
+ return [
4590
+ first,
4591
+ ...folders.flatMap((listing) =>
4592
+ planUnlistFile(args.pubkey, args.createdAtMs, { folder: listing.id, address: args.address, hasState: listing.hasState }),
4593
+ ),
4594
+ ]
4595
+ }
4596
+ if (isCreationAction(declared)) {
4597
+ if (args.folderHasState === undefined) {
4598
+ return `"${declared.label}" lists what it creates, and needs to know whether the Folder has state.`
4599
+ }
4600
+ // A listing names addresses, and an object with no `d` has none.
4601
+ const identifier = first.tags.find((t) => t[0] === 'd')?.[1]
4602
+ if (identifier === undefined) {
4603
+ return `"${declared.label}" lists what it creates, and a kind ${first.kind} has no address to list.`
4604
+ }
4605
+ const created = pointerToAddress({ kind: first.kind, pubkey: first.pubkey, identifier, relays: [] })
4606
+ return [first, ...planPlaceFile(args.pubkey, args.createdAtMs, { folder: args.folder, address: created, hasState: args.folderHasState })]
4607
+ }
4608
+ // A change or a comment adds nothing to a Folder and removes nothing from it.
4609
+ return [first]
4610
+ }
4611
+
4612
+ function buildOneActionEvent(args: ActionEventArgs): UnsignedActionEvent | string {
4047
4613
  const { manifest, kind, address, folder, actionId, value, replyTo } = args
4048
4614
  const records = manifest.records
4049
4615
  const declared = manifest.actions?.find((a) => a.id === actionId)
@@ -4054,7 +4620,7 @@ export function buildActionEvent(args: {
4054
4620
  return `"${declared.label}" does not apply to a kind ${kind}.`
4055
4621
  }
4056
4622
 
4057
- const isCreation = declared.input?.type === 'object' && !!declared.input.properties
4623
+ const isCreation = isCreationAction(declared)
4058
4624
 
4059
4625
  // A reply is a comment with a parent — what the scalar path below builds for
4060
4626
  // an action that is neither a deletion nor a change. Refused here, before any
@@ -4062,6 +4628,16 @@ export function buildActionEvent(args: {
4062
4628
  if (replyTo && (isCreation || declared.emits.kind === KIND_DELETION || declared.emits.field)) {
4063
4629
  return `"${declared.label}" is not a comment, so it cannot reply to one.`
4064
4630
  }
4631
+ // Prose is a creation's content or a change's value (§7.3). A deletion has
4632
+ // no value, and a comment's body is §13.2 marker text.
4633
+ if (args.contentFormat !== undefined && !isCreation && (!declared.emits.field || declared.emits.kind === KIND_DELETION)) {
4634
+ return `"${declared.label}" takes no prose value, so it takes no content format.`
4635
+ }
4636
+ // A note is a change's `content`. Anywhere else it would be dropped, and the
4637
+ // resolution a person typed lost without a word.
4638
+ if (args.note !== undefined && (isCreation || !declared.emits.field || declared.emits.kind === KIND_DELETION)) {
4639
+ return `"${declared.label}" is not a change, so it takes no note.`
4640
+ }
4065
4641
 
4066
4642
  // An object-creating action is a different event entirely — a new object
4067
4643
  // rather than a change to one — so it branches before the scalar path.
@@ -4129,12 +4705,21 @@ export function buildActionEvent(args: {
4129
4705
  }
4130
4706
  }
4131
4707
 
4708
+ // A prose value's `content-format` and `imeta` — a change only, per the
4709
+ // refusal above. Ship's order: the tag before `ts`, the files after it.
4710
+ const prose = declared.emits.field
4711
+ ? proseTags({ label: declared.label, declared: declared.input?.format, contentFormat: args.contentFormat, value })
4712
+ : []
4713
+ if (typeof prose === 'string') return prose
4714
+ const [formatTag, ...files] = prose
4715
+
4132
4716
  const tags: string[][] = declared.emits.field
4133
4717
  ? [
4134
4718
  [records.targetTag, address],
4135
4719
  [records.fieldTag, declared.emits.field],
4136
4720
  [records.valueTag, value],
4137
4721
  ['h', folder],
4722
+ ...(formatTag ? [formatTag] : []),
4138
4723
  ]
4139
4724
  : // NIP-22 comment. Built from the ratified NIP rather than from the
4140
4725
  // manifest, which is legitimate precisely because no app owns kind:1111 —
@@ -4164,13 +4749,14 @@ export function buildActionEvent(args: {
4164
4749
  // second would be separated by event id — arbitrarily, and differently
4165
4750
  // depending on which app you asked (FRICTION.md A6).
4166
4751
  if (records.order?.includes('ts')) tags.push(['ts', String(args.createdAtMs)])
4752
+ tags.push(...files)
4167
4753
 
4168
4754
  return {
4169
4755
  pubkey: args.pubkey,
4170
4756
  created_at: Math.floor(args.createdAtMs / 1000),
4171
4757
  kind: declared.emits.kind,
4172
4758
  tags,
4173
- content: declared.emits.field ? '' : value,
4759
+ content: declared.emits.field ? (args.note ?? '') : value,
4174
4760
  }
4175
4761
  }
4176
4762
 
@@ -4258,6 +4844,25 @@ export interface FolderSummary {
4258
4844
  * another app's files resolves them with {@link resolveFolderContents}.
4259
4845
  */
4260
4846
  addresses?: string[]
4847
+ /**
4848
+ * The Folder's own address as a file — its `kind:39000`, `39000:<relay>:<id>`.
4849
+ * What a state lists when it holds this Folder, and what an `archived`
4850
+ * change on the Folder names. Absent only for a state whose channel the
4851
+ * relay did not return.
4852
+ */
4853
+ channel?: string
4854
+ /**
4855
+ * Present when the Folder is archived (FOL-46) — or, for a record's channel,
4856
+ * when the record it belongs to is (`with` names the record). See
4857
+ * {@link Archive}.
4858
+ *
4859
+ * {@link topLevelFolders} leaves an archived Folder out, and
4860
+ * {@link resolveFolderContents} leaves one out of the Folder that lists it,
4861
+ * so its subtree goes with it. What it holds stays readable: a link still
4862
+ * opens it, and a file it lists that another Folder also lists stays visible
4863
+ * there.
4864
+ */
4865
+ archived?: Archive
4261
4866
  }
4262
4867
 
4263
4868
  /**
@@ -4274,9 +4879,14 @@ export interface FolderSummary {
4274
4879
  *
4275
4880
  * Not a list of ids: a new team is a folder somebody creates, not a code
4276
4881
  * change. Moved here from Peek and Ship, which each held the same line.
4882
+ *
4883
+ * An archived Folder is not navigated by (FOL-46), and a listing that has not
4884
+ * read archives — a summary with no `archived` field — keeps every Folder.
4277
4885
  */
4278
- export function topLevelFolders<T extends Pick<FolderSummary, 'hasState' | 'listedIn'>>(folders: T[]): T[] {
4279
- return folders.filter((folder) => folder.hasState && !folder.listedIn?.length)
4886
+ export function topLevelFolders<T extends Pick<FolderSummary, 'hasState' | 'listedIn' | 'archived'>>(
4887
+ folders: T[],
4888
+ ): T[] {
4889
+ return folders.filter((folder) => folder.hasState && !folder.listedIn?.length && !folder.archived)
4280
4890
  }
4281
4891
 
4282
4892
  /** A folder and everything in it, each file drawn through its owner's manifest. */
@@ -4341,6 +4951,11 @@ export async function listFolders(query: QueryFn): Promise<FolderSummary[]> {
4341
4951
  ...(addresses.length ? { addresses } : {}),
4342
4952
  })
4343
4953
  }
4954
+ for (const event of events) {
4955
+ const id = tagValue(event, 'd')
4956
+ const folder = id && event.kind === KIND_CHANNEL ? byId.get(id) : undefined
4957
+ if (folder) folder.channel = pointerToAddress({ kind: KIND_CHANNEL, pubkey: event.pubkey, identifier: id!, relays: [] })
4958
+ }
4344
4959
  /*
4345
4960
  A folder listed in another folder's state is a file there. Read off the
4346
4961
  states already in hand: an `a` naming a `kind:39000` is a channel, and its
@@ -4361,14 +4976,199 @@ export async function listFolders(query: QueryFn): Promise<FolderSummary[]> {
4361
4976
  listedIn.set(identifier, containers)
4362
4977
  }
4363
4978
  }
4364
- await placeRecordChannels(events, byId, listedIn, query)
4979
+ const { recordsOf, archives } = await placeRecordChannels(events, byId, listedIn, query)
4365
4980
  for (const [id, containers] of listedIn) {
4366
4981
  const folder = byId.get(id)
4367
4982
  if (folder) folder.listedIn = containers
4368
4983
  }
4984
+ markArchivedFolders(byId, recordsOf, archives)
4369
4985
  return [...byId.values()].sort((a, b) => (a.name ?? a.id).localeCompare(b.name ?? b.id))
4370
4986
  }
4371
4987
 
4988
+ /**
4989
+ * Which Folders are archived — FOL-46, from the changes {@link placeRecordChannels}
4990
+ * read with the record roots.
4991
+ *
4992
+ * A Folder is archived by a change naming its channel's address, the way any
4993
+ * file is. A record's channel — a Ship project's conversation — is archived
4994
+ * with its record, so an archived project's channel stops lighting its team's
4995
+ * dot the way the project stopped being listed — only when every record naming
4996
+ * the channel is archived, since two projects may share one. Its own archive
4997
+ * wins when it has one.
4998
+ *
4999
+ * A refused read throws before this, like the reads beside it: a listing that
5000
+ * silently reported every Folder live would put archived teams back in
5001
+ * everyone's sidebar.
5002
+ */
5003
+ function markArchivedFolders(
5004
+ byId: Map<string, FolderSummary>,
5005
+ recordsOf: Map<string, string[]>,
5006
+ changes: SignedEvent[],
5007
+ ): void {
5008
+ for (const folder of byId.values()) {
5009
+ const own = folder.channel ? archiveOf(changes, folder.channel, ARCHIVE_RULE) : undefined
5010
+ if (own) {
5011
+ folder.archived = own
5012
+ continue
5013
+ }
5014
+ const records = recordsOf.get(folder.id) ?? []
5015
+ const archives = records.map((record) => archiveOf(changes, record, ARCHIVE_RULE))
5016
+ if (records.length && archives.every(Boolean)) folder.archived = { ...archives[0]!, with: records[0] }
5017
+ }
5018
+ }
5019
+
5020
+ /** How many Folders deep {@link archiveImpact} follows nested Folders. A request per Folder. */
5021
+ const MAX_ARCHIVE_DEPTH = 3
5022
+
5023
+ /** What archiving one file would hide, for the warning a person reads first — FOL-46. */
5024
+ export interface ArchiveImpact {
5025
+ /**
5026
+ * The files that would go out of every list with it, counted by kind: its
5027
+ * children, and — for a Folder — every file only that Folder lists, with
5028
+ * their children. Files already archived are not counted; they are hidden
5029
+ * already. Kinds with no files are absent.
5030
+ */
5031
+ hides: { kind: number; count: number }[]
5032
+ /**
5033
+ * Files a Folder lists that another Folder, not archived, lists too. They
5034
+ * stay visible there, and a warning that said they would be hidden would
5035
+ * make Archive look more destructive than it is. Empty for a file that is
5036
+ * not a Folder.
5037
+ */
5038
+ staysVisible: { address: string; kind: number; in: { id: string; name?: string }[] }[]
5039
+ }
5040
+
5041
+ /**
5042
+ * Count what archiving `address` would hide — the read behind the warning.
5043
+ *
5044
+ * "Hides 14 issues and 6 topics that are only here; 2 topics also in Estiva HQ
5045
+ * stay visible." The words are the app's; the counts are the same in every
5046
+ * app, which is why they are read here.
5047
+ *
5048
+ * - **A Folder** (a `kind:39000` address, `FolderSummary.channel`): what it
5049
+ * lists, split by whether another Folder lists it too, the children of what
5050
+ * would be hidden, and — three Folders deep — what a nested Folder only it
5051
+ * lists holds. Pass `folders` from the app's own `listFolders` to save that
5052
+ * read.
5053
+ * - **Any other file**: the children its kind declares (a project's issues), and
5054
+ * bare files placed under it (sub-topics), by their root's `a` tag.
5055
+ *
5056
+ * One level of children, as a listing draws them. A few requests, whatever the
5057
+ * size: the Folder, one per app's manifest (memoised by `cache`), the children,
5058
+ * and their archives.
5059
+ */
5060
+ export async function archiveImpact(
5061
+ address: string,
5062
+ query: QueryFn,
5063
+ options: { folders?: FolderSummary[]; cache?: ProjectionCache } = {},
5064
+ ): Promise<ArchiveImpact> {
5065
+ const pointer = addressPointerOf(address)
5066
+ if (!pointer) return { hides: [], staysVisible: [] }
5067
+ const counts = new Map<number, number>()
5068
+ const count = (kind: number, n = 1) => counts.set(kind, (counts.get(kind) ?? 0) + n)
5069
+ const staysVisible: ArchiveImpact['staysVisible'] = []
5070
+ let parents: { address: string; pointer: AddressPointer }[] = [{ address, pointer }]
5071
+
5072
+ if (pointer.kind === KIND_CHANNEL) {
5073
+ const folders = options.folders ?? (await listFolders(query))
5074
+ parents = []
5075
+ /*
5076
+ A nested Folder only this one lists goes out of view with it, and so does
5077
+ everything only *that* one lists — walked the same way, a Folder at a
5078
+ time, to a small depth. "Only" is judged against the live Folders outside
5079
+ the tree being archived.
5080
+ */
5081
+ const inTree = new Set([pointer.identifier])
5082
+ const walk = async (folder: string, depth: number) => {
5083
+ const contents = await resolveFolderContents(folder, query, async () => ({}), options.cache)
5084
+ for (const file of contents.files) {
5085
+ if (!file.address) continue
5086
+ const others = folders.filter(
5087
+ (other) => !inTree.has(other.id) && !other.archived && other.addresses?.includes(file.address!),
5088
+ )
5089
+ if (others.length) {
5090
+ staysVisible.push({ address: file.address, kind: file.kind, in: others.map(({ id, name }) => ({ id, name })) })
5091
+ continue
5092
+ }
5093
+ count(file.kind)
5094
+ const filePointer = addressPointerOf(file.address)
5095
+ if (!filePointer) continue
5096
+ if (filePointer.kind === KIND_CHANNEL) {
5097
+ if (depth < MAX_ARCHIVE_DEPTH && !inTree.has(filePointer.identifier)) {
5098
+ inTree.add(filePointer.identifier)
5099
+ await walk(filePointer.identifier, depth + 1)
5100
+ }
5101
+ } else {
5102
+ parents.push({ address: file.address, pointer: filePointer })
5103
+ }
5104
+ }
5105
+ }
5106
+ await walk(pointer.identifier, 0)
5107
+ }
5108
+
5109
+ // A record channel lists a project *and* its issues; each is counted once.
5110
+ const counted = new Set(parents.map((p) => p.address))
5111
+ for (const [kind, n] of await countLiveChildren(parents, counted, query, options.cache)) count(kind, n)
5112
+ return {
5113
+ hides: [...counts].map(([kind, n]) => ({ kind, count: n })),
5114
+ staysVisible,
5115
+ }
5116
+ }
5117
+
5118
+ /** The children of each parent that are not archived already, by kind. */
5119
+ async function countLiveChildren(
5120
+ parents: { address: string; pointer: AddressPointer }[],
5121
+ counted: ReadonlySet<string>,
5122
+ query: QueryFn,
5123
+ cache?: ProjectionCache,
5124
+ ): Promise<Map<number, number>> {
5125
+ const byKind = new Map<number, number>()
5126
+ if (parents.length === 0) return byKind
5127
+ const byApp = new Map<string, AddressPointer>()
5128
+ for (const { pointer } of parents) byApp.set(manifestKeyOf(pointer), pointer)
5129
+ const manifests = new Map<string, ResolvedManifest>()
5130
+ await Promise.all(
5131
+ [...byApp].map(async ([key, pointer]) => {
5132
+ const resolved = await resolveManifest(pointer, query, cache)
5133
+ if (resolved) manifests.set(key, resolved)
5134
+ }),
5135
+ )
5136
+ const filters: Record<string, unknown>[] = []
5137
+ const wanted: { kind: number; via: string; parent: string }[] = []
5138
+ for (const { address, pointer } of parents) {
5139
+ const projection = manifests.get(manifestKeyOf(pointer))?.manifest.projections?.[String(pointer.kind)]
5140
+ const declared = projection && declaredChildSpec(projection)
5141
+ const specs = [
5142
+ ...(declared ? [{ kind: declared.kind, via: declared.via }] : []),
5143
+ // A sub-topic may sit under a file of any kind (SPEC §6.7).
5144
+ ...(declared?.kind === KIND_BARE_FILE && declared.via === 'a' ? [] : [{ kind: KIND_BARE_FILE, via: 'a' }]),
5145
+ ]
5146
+ for (const spec of specs) {
5147
+ wanted.push({ ...spec, parent: address })
5148
+ filters.push({ kinds: [spec.kind], [`#${spec.via}`]: [address], limit: RELAY_PAGE_CEILING })
5149
+ }
5150
+ }
5151
+ const events: SignedEvent[] = []
5152
+ for (let start = 0; start < filters.length; start += MAX_FILTERS_PER_QUERY) {
5153
+ events.push(...(await query(filters.slice(start, start + MAX_FILTERS_PER_QUERY))))
5154
+ }
5155
+ const children = new Map<string, number>()
5156
+ for (const event of events) {
5157
+ const identifier = tagValue(event, 'd')
5158
+ if (identifier === undefined) continue
5159
+ if (!wanted.some((w) => w.kind === event.kind && hasTagValue(event, w.via, w.parent))) continue
5160
+ const child = pointerToAddress({ kind: event.kind, pubkey: event.pubkey, identifier, relays: [] })
5161
+ if (!counted.has(child)) children.set(child, event.kind)
5162
+ }
5163
+ if (children.size === 0) return byKind
5164
+ const changes = await readArchiveChanges([...children.keys()], query)
5165
+ for (const [child, kind] of children) {
5166
+ if (archiveOf(changes, child, ARCHIVE_RULE)) continue
5167
+ byKind.set(kind, (byKind.get(kind) ?? 0) + 1)
5168
+ }
5169
+ return byKind
5170
+ }
5171
+
4372
5172
  /**
4373
5173
  * A record's own channel is listed wherever the record is (FOL-42).
4374
5174
  *
@@ -4417,7 +5217,7 @@ async function placeRecordChannels(
4417
5217
  byId: Map<string, FolderSummary>,
4418
5218
  listedIn: Map<string, string[]>,
4419
5219
  query: QueryFn,
4420
- ): Promise<void> {
5220
+ ): Promise<{ recordsOf: Map<string, string[]>; archives: SignedEvent[] }> {
4421
5221
  const containersOf = new Map<string, { pointer: AddressPointer; containers: string[] }>()
4422
5222
  for (const event of events) {
4423
5223
  if (event.kind !== KIND_FOLDER_STATE) continue
@@ -4438,7 +5238,18 @@ async function placeRecordChannels(
4438
5238
  containersOf.set(key, entry)
4439
5239
  }
4440
5240
  }
4441
- if (containersOf.size === 0) return
5241
+ // Every Folder's archive, and every listed record's, ride with the roots
5242
+ // (FOL-46): the channel addresses are in hand from the listing and the
5243
+ // record addresses are the keys above, so neither needs the roots first.
5244
+ const channels = [...byId.values()].flatMap((folder) => (folder.channel ? [folder.channel] : []))
5245
+ const archiveAsk = archiveFilters([...new Set([...channels, ...containersOf.keys()])])
5246
+ if (containersOf.size === 0) {
5247
+ const archives: SignedEvent[] = []
5248
+ for (let start = 0; start < archiveAsk.length; start += MAX_FILTERS_PER_QUERY) {
5249
+ archives.push(...(await query(archiveAsk.slice(start, start + MAX_FILTERS_PER_QUERY))))
5250
+ }
5251
+ return { recordsOf: new Map(), archives }
5252
+ }
4442
5253
 
4443
5254
  const groups = new Map<string, { kind: number; pubkey: string; identifiers: string[] }>()
4444
5255
  for (const { pointer } of containersOf.values()) {
@@ -4454,10 +5265,14 @@ async function placeRecordChannels(
4454
5265
  filters.push({ kinds: [kind], authors: [pubkey], '#d': chunk, limit: chunk.length })
4455
5266
  }
4456
5267
  }
4457
- const roots: SignedEvent[] = []
5268
+ filters.push(...archiveAsk)
5269
+ const answered: SignedEvent[] = []
4458
5270
  for (let start = 0; start < filters.length; start += MAX_FILTERS_PER_QUERY) {
4459
- roots.push(...(await query(filters.slice(start, start + MAX_FILTERS_PER_QUERY))))
5271
+ answered.push(...(await query(filters.slice(start, start + MAX_FILTERS_PER_QUERY))))
4460
5272
  }
5273
+ // A state lists files, never change events, so the kind tells them apart.
5274
+ const archives = answered.filter((e) => e.kind === ARCHIVE_RULE.changeKind)
5275
+ const roots = answered.filter((e) => e.kind !== ARCHIVE_RULE.changeKind)
4461
5276
 
4462
5277
  // Newest wins, as it does for any addressable event a relay has not yet replaced.
4463
5278
  const newest = new Map<string, SignedEvent>()
@@ -4466,10 +5281,14 @@ async function placeRecordChannels(
4466
5281
  const held = newest.get(key)
4467
5282
  if (!held || root.created_at > held.created_at) newest.set(key, root)
4468
5283
  }
5284
+ const recordsOf = new Map<string, string[]>()
4469
5285
  for (const [key, { containers }] of containersOf) {
4470
5286
  const root = newest.get(key)
4471
5287
  const channel = root && folderOf(root)
4472
5288
  if (!channel || byId.get(channel)?.hasState) continue
5289
+ // A file published into the Folder that lists it names that Folder, and
5290
+ // does not own it: a topic's `h` is its team's.
5291
+ if (!containers.includes(channel)) recordsOf.set(channel, [...(recordsOf.get(channel) ?? []), key])
4473
5292
  for (const container of containers) {
4474
5293
  if (container === channel) continue
4475
5294
  const placed = listedIn.get(channel) ?? []
@@ -4477,6 +5296,7 @@ async function placeRecordChannels(
4477
5296
  listedIn.set(channel, placed)
4478
5297
  }
4479
5298
  }
5299
+ return { recordsOf, archives }
4480
5300
  }
4481
5301
 
4482
5302
  /**
@@ -4529,6 +5349,14 @@ export async function resolveFolderContents(
4529
5349
  lookupPeople?: PeopleFn,
4530
5350
  /** See {@link ProjectionCache}. Omitting it is exactly the old behaviour. */
4531
5351
  cache?: ProjectionCache,
5352
+ options: {
5353
+ /**
5354
+ * Return archived files — and files hidden with an archived parent — each
5355
+ * carrying its {@link Archive}, instead of leaving them out. For a view
5356
+ * that lists what was archived; every other list wants the default.
5357
+ */
5358
+ includeArchived?: boolean
5359
+ } = {},
4532
5360
  ): Promise<FolderContents> {
4533
5361
  // 1. The folder itself. Both kinds in one trip: the state is the model and
4534
5362
  // the channel is what names a folder that has none yet.
@@ -4538,11 +5366,15 @@ export async function resolveFolderContents(
4538
5366
  ])
4539
5367
  const state = identity.find((e) => e.kind === KIND_FOLDER_STATE && tagValue(e, 'd') === folder)
4540
5368
  const channel = identity.find((e) => e.kind === KIND_CHANNEL && tagValue(e, 'd') === folder)
5369
+ const channelAddress = channel
5370
+ ? pointerToAddress({ kind: KIND_CHANNEL, pubkey: channel.pubkey, identifier: folder, relays: [] })
5371
+ : undefined
4541
5372
 
4542
5373
  const summary: FolderSummary & { address?: string } = {
4543
5374
  id: folder,
4544
5375
  name: nameOf(state) ?? nameOf(channel),
4545
5376
  hasState: !!state,
5377
+ ...(channelAddress ? { channel: channelAddress } : {}),
4546
5378
  ...(state
4547
5379
  ? { address: pointerToAddress({ kind: state.kind, pubkey: state.pubkey, identifier: folder, relays: [] }) }
4548
5380
  : {}),
@@ -4558,7 +5390,12 @@ export async function resolveFolderContents(
4558
5390
  : await addressesByContainment(folder, query)
4559
5391
 
4560
5392
  if (addresses.length === 0) {
4561
- return { ...summary, files: [], source: state ? 'state' : 'channel' }
5393
+ // Nothing listed, so no change query to ride on: the Folder's own archive
5394
+ // is one small read of its own.
5395
+ const archived = channelAddress
5396
+ ? archiveOf(await readArchiveChanges([channelAddress], query), channelAddress, ARCHIVE_RULE)
5397
+ : undefined
5398
+ return { ...summary, ...(archived ? { archived } : {}), files: [], source: state ? 'state' : 'channel' }
4562
5399
  }
4563
5400
 
4564
5401
  // 2. Group by (kind, author): one manifest answers for every file an app owns
@@ -4597,10 +5434,15 @@ export async function resolveFolderContents(
4597
5434
  // Change kinds are a set because two apps may fold differently, and a kind
4598
5435
  // is a u16 — the relay refuses an out-of-range one outright, so an app
4599
5436
  // declaring no `records` contributes no filter rather than an empty one.
5437
+ //
5438
+ // SPEC's change kind is always asked for, whatever the apps declare: any
5439
+ // file may be archived (FOL-46), a nested Folder included, and so may this
5440
+ // Folder, whose own address rides in the same filter.
4600
5441
  const changeKinds = [
4601
- ...new Set(
4602
- [...manifests.values()].flatMap((r) => (r.manifest.records ? [r.manifest.records.changeKind] : [])),
4603
- ),
5442
+ ...new Set([
5443
+ ARCHIVE_RULE.changeKind,
5444
+ ...[...manifests.values()].flatMap((r) => (r.manifest.records ? [r.manifest.records.changeKind] : [])),
5445
+ ]),
4604
5446
  ]
4605
5447
  const events = await query([
4606
5448
  ...[...groups.values()].map(({ pointer, addresses: group }) => ({
@@ -4609,13 +5451,21 @@ export async function resolveFolderContents(
4609
5451
  '#d': group.map((a) => referenceToPointer(a).identifier),
4610
5452
  limit: group.length,
4611
5453
  })),
4612
- ...(changeKinds.length
4613
- ? [{ kinds: changeKinds, '#a': addresses, limit: 500 }]
4614
- : []),
5454
+ { kinds: changeKinds, '#a': addresses, limit: 500 },
5455
+ // The archives again, in groups small enough that a busy Folder's other
5456
+ // changes cannot push them off the page — the filter above holds 500
5457
+ // changes for every file together, and one Folder has already had 688.
5458
+ // Same request.
5459
+ ...archiveFilters(channelAddress ? [...addresses, channelAddress] : addresses),
4615
5460
  ])
4616
-
4617
- // 4. Build each file, in the order the folder listed them.
4618
- const files: ForeignObject[] = []
5461
+ const ownArchive = channelAddress ? archiveOf(events, channelAddress, ARCHIVE_RULE) : undefined
5462
+ if (ownArchive) summary.archived = ownArchive
5463
+
5464
+ // 4. Build each file, in the order the folder listed them. Archived files are
5465
+ // held back until the cascade below has read their parents.
5466
+ const listed: { file: ForeignObject; archive?: Archive }[] = []
5467
+ const archiveByAddress = new Map<string, Archive | undefined>()
5468
+ const parentByAddress = new Map<string, string | undefined>()
4619
5469
  for (const { address, pointer } of pointers) {
4620
5470
  const resolved = manifests.get(manifestKeyOf(pointer))
4621
5471
  // No app claims this kind, so there is no projection to draw it with.
@@ -4633,11 +5483,16 @@ export async function resolveFolderContents(
4633
5483
  events.filter((e) => e.kind === records.changeKind && hasTagValue(e, records.targetTag, address)),
4634
5484
  records,
4635
5485
  )
5486
+ const archive = archiveOf(events, address, archiveRuleOf(resolved.manifest))
5487
+ archiveByAddress.set(address, archive)
5488
+ parentByAddress.set(address, parentRefOf(resolved.manifest, pointer.kind, root, folded))
4636
5489
  // An app hiding a record from its own lists is saying it is not part of the
4637
- // folder any more. `hiddenWhen` is the app's own declaration of that.
4638
- if (records.hiddenWhen && folded[records.hiddenWhen.field]?.value === records.hiddenWhen.equals) {
4639
- continue
4640
- }
5490
+ // folder any more. `hiddenWhen` is the app's own declaration of that — the
5491
+ // archive above is the same statement for a kind whose app declared none.
5492
+ // Not reported as an archive: the app said "hidden", which may mean more.
5493
+ const hidden =
5494
+ !!records.hiddenWhen && folded[records.hiddenWhen.field]?.value === records.hiddenWhen.equals
5495
+ if (hidden && !archive) continue
4641
5496
  /*
4642
5497
  A placed file stays listed only while the placement is current.
4643
5498
 
@@ -4662,8 +5517,9 @@ export async function resolveFolderContents(
4662
5517
  })
4663
5518
  if (!current) continue
4664
5519
  }
4665
- files.push(
4666
- buildObject({
5520
+ listed.push({
5521
+ archive,
5522
+ file: buildObject({
4667
5523
  root,
4668
5524
  pointer,
4669
5525
  manifest: resolved.manifest,
@@ -4672,7 +5528,45 @@ export async function resolveFolderContents(
4672
5528
  viaRecommendation: resolved.viaRecommendation,
4673
5529
  webTemplate: resolved.webTemplate,
4674
5530
  }),
4675
- )
5531
+ })
5532
+ }
5533
+
5534
+ /*
5535
+ 5. The cascade (FOL-46): a file under an archived file is hidden with it —
5536
+ an issue with its project, a sub-topic with its topic. Computed here and
5537
+ never written to the children, so unarchiving the parent restores
5538
+ exactly what was there.
5539
+
5540
+ The chain is walked through everything this Folder lists. A parent that
5541
+ lives in another Folder is read once for all such parents, one level: a
5542
+ project whose record channel lists its issues is the case that matters,
5543
+ and there the project is listed too.
5544
+
5545
+ Only by parent. A file this Folder lists is never hidden because some
5546
+ *other* Folder that lists it is archived — that is what lets a file
5547
+ placed in two Folders stay visible in the one that is not archived.
5548
+ */
5549
+ const outside = [
5550
+ ...new Set(
5551
+ listed.flatMap(({ file }) => {
5552
+ const parent = file.address && parentByAddress.get(file.address)
5553
+ return parent && !archiveByAddress.has(parent) && addressPointerOf(parent) ? [parent] : []
5554
+ }),
5555
+ ),
5556
+ ]
5557
+ if (outside.length) {
5558
+ const changes = await readArchiveChanges(outside, query)
5559
+ for (const parent of outside) archiveByAddress.set(parent, archiveOf(changes, parent, ARCHIVE_RULE))
5560
+ }
5561
+ const files: ForeignObject[] = []
5562
+ for (const { file, archive } of listed) {
5563
+ const effective =
5564
+ archive ??
5565
+ (file.address
5566
+ ? archivedAncestorOf(file.address, (a) => parentByAddress.get(a), (a) => archiveByAddress.get(a))
5567
+ : undefined)
5568
+ if (!effective) files.push(file)
5569
+ else if (options.includeArchived) files.push({ ...file, archived: effective })
4676
5570
  }
4677
5571
 
4678
5572
  const people = await (lookupPeople ?? peopleViaRelay(query))([