@estiva-app/interop 0.72.0 → 0.74.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@estiva-app/interop",
3
- "version": "0.72.0",
3
+ "version": "0.74.0",
4
4
  "description": "Render and act on another app's objects from its published NIP-89 manifest. The owner defines the projection; the consumer decides how it looks.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -48,11 +48,11 @@
48
48
  },
49
49
  "peerDependencies": {
50
50
  "@estiva-app/conversation": ">=0.20.0",
51
- "@estiva-app/protocol": ">=0.44.0"
51
+ "@estiva-app/protocol": ">=0.49.0"
52
52
  },
53
53
  "devDependencies": {
54
54
  "@estiva-app/conversation": ">=0.20.0",
55
- "@estiva-app/protocol": ">=0.44.0",
55
+ "@estiva-app/protocol": ">=0.49.0",
56
56
  "typescript": "~5.9.3"
57
57
  }
58
58
  }
package/src/fields.ts ADDED
@@ -0,0 +1,346 @@
1
+ /**
2
+ * A file as its fields, each kept in order by the relay — SPEC §6.2, §6.13.
3
+ *
4
+ * Two halves, both for any type the relay keeps:
5
+ *
6
+ * - **Reading** a list or one file with the relay's list read
7
+ * (`"fields": "newest"`), which answers each file's first record and, for
8
+ * each field, only its current change: a list never carries the text, and
9
+ * opening one file (`"text": true` beside `#d`) carries its current text and
10
+ * none of its history. Each change's id is that field's next `prev`.
11
+ * - **Writing** a change that names the one it follows, and answering the
12
+ * relay's `conflict:` as §6.2 says: a field set again keeps the later, and a
13
+ * text merges by §13.3's rule, or stops and asks when a block was changed by
14
+ * both or edited against a delete. It never writes over someone's newer
15
+ * words.
16
+ *
17
+ * Only for a relay whose NIP-11 advertises `file_list` (`relayFileReadsOf` in
18
+ * `@estiva-app/protocol`), and `"text"` only where it says `text`: a relay
19
+ * without them answers these reads as if they were plain ones.
20
+ *
21
+ * why: https://github.com/estiva-app/estiva-docs/blob/main/decisions/a-file-is-its-fields-each-kept-in-order-by-the-relay.md
22
+ * why: https://github.com/estiva-app/estiva-docs/blob/main/decisions/opening-a-file-reads-its-current-text-not-its-history.md
23
+ * why: https://github.com/estiva-app/estiva-docs/blob/main/decisions/merging-two-changes-to-one-text-never-loses-words.md
24
+ */
25
+ import {
26
+ CONTENT_FORMAT_TAG,
27
+ mergeTexts,
28
+ type MergeAsk,
29
+ type MergeText,
30
+ type SignedEvent,
31
+ type UnsignedEvent,
32
+ } from '@estiva-app/protocol'
33
+ import { folderOf, type QueryFn } from './projection.js'
34
+
35
+ /** The change event every Estiva app writes (SPEC §6.2). */
36
+ const KIND_CHANGE = 1851
37
+
38
+ /** The field that holds a file's text (§6.10): the one field that merges rather than re-sets. */
39
+ export const TEXT_FIELD = 'description'
40
+
41
+ /** One field's current value, and the change that set it. */
42
+ export interface CurrentField {
43
+ value: string
44
+ /** The value's `content-format`, for the text; absent for marker text. */
45
+ format?: string
46
+ /** The change's id: the field's next `prev`. */
47
+ id: string
48
+ /** Who set it. */
49
+ pubkey: string
50
+ /** When, in ms: `ts` where it agrees with `created_at` to the second (§6.2), else `created_at`. */
51
+ at: number
52
+ event: SignedEvent
53
+ }
54
+
55
+ /** A file read by its fields. */
56
+ export interface FileFields {
57
+ root: SignedEvent
58
+ /** `<kind>:<pubkey>:<d>`. */
59
+ address: string
60
+ /** Each field's current change. The text is here only when the file was opened with it. */
61
+ fields: Record<string, CurrentField>
62
+ /** The root and each current change, as signed — what a fold of every change would read the same. */
63
+ events: SignedEvent[]
64
+ }
65
+
66
+ const tagValue = (event: { tags: string[][] }, name: string) => event.tags.find((t) => t[0] === name)?.[1]
67
+
68
+ /** When a change happened, in ms, by §6.3's order. */
69
+ export function changedAt(event: SignedEvent): number {
70
+ const ts = Number(tagValue(event, 'ts'))
71
+ return Number.isFinite(ts) && Math.floor(ts / 1000) === event.created_at ? ts : event.created_at * 1000
72
+ }
73
+
74
+ /** Newer first by §6.3: time, then `created_at`, then id. */
75
+ function newer(a: SignedEvent, b: SignedEvent): boolean {
76
+ const at = changedAt(a) - changedAt(b)
77
+ if (at !== 0) return at > 0
78
+ if (a.created_at !== b.created_at) return a.created_at > b.created_at
79
+ return a.id > b.id
80
+ }
81
+
82
+ /**
83
+ * The fields one change sets, with their values: one `field`/`value`, or one
84
+ * per `set` (§6.2). A change setting the text carries its `content-format`.
85
+ */
86
+ export function fieldsSetBy(event: { tags: string[][] }): { field: string; value: string; format?: string }[] {
87
+ const format = tagValue(event, CONTENT_FORMAT_TAG)
88
+ const withFormat = (field: string, value: string) =>
89
+ field === TEXT_FIELD && format ? { field, value, format } : { field, value }
90
+ const sets = event.tags.filter((t) => t[0] === 'set' && typeof t[1] === 'string')
91
+ if (sets.length) return sets.map((t) => withFormat(t[1], t[2] ?? ''))
92
+ const field = tagValue(event, 'field')
93
+ return field === undefined ? [] : [withFormat(field, tagValue(event, 'value') ?? '')]
94
+ }
95
+
96
+ const addressOfRoot = (root: SignedEvent) => `${root.kind}:${root.pubkey}:${tagValue(root, 'd') ?? ''}`
97
+
98
+ /**
99
+ * Each file the events hold, by its first record and the current change of each
100
+ * of its fields.
101
+ *
102
+ * A change counts only where §6.2 says a reader folds it: its `a` names the
103
+ * file, its `O` (if any) is the file's id, and its `h` is the file's home. The
104
+ * text counts only when `withText`: a list never takes the text from a change
105
+ * that set several fields, since a later text-only change may have replaced it
106
+ * (§6.13).
107
+ */
108
+ export function filesOf(events: readonly SignedEvent[], options: { withText?: boolean } = {}): FileFields[] {
109
+ const roots = new Map<string, SignedEvent>()
110
+ for (const event of events) {
111
+ if (event.kind === KIND_CHANGE || tagValue(event, 'd') === undefined) continue
112
+ const address = addressOfRoot(event)
113
+ const held = roots.get(address)
114
+ if (!held || event.created_at > held.created_at) roots.set(address, event)
115
+ }
116
+ const files = new Map<string, FileFields>()
117
+ for (const [address, root] of roots) files.set(address, { root, address, fields: {}, events: [root] })
118
+
119
+ for (const event of events) {
120
+ if (event.kind !== KIND_CHANGE) continue
121
+ const file = files.get(tagValue(event, 'a') ?? '')
122
+ if (!file) continue
123
+ const O = tagValue(event, 'O')
124
+ if (O !== undefined && O !== tagValue(file.root, 'd')) continue
125
+ if (tagValue(event, 'h') !== (folderOf(file.root) ?? undefined)) continue
126
+ for (const set of fieldsSetBy(event)) {
127
+ if (set.field === TEXT_FIELD && !options.withText) continue
128
+ const held = file.fields[set.field]
129
+ if (held && !newer(event, held.event)) continue
130
+ file.fields[set.field] = { ...set, id: event.id, pubkey: event.pubkey, at: changedAt(event), event }
131
+ }
132
+ }
133
+ // The root and each change some field still points at, once.
134
+ for (const file of files.values()) {
135
+ const current = new Map(Object.values(file.fields).map((f) => [f.id, f.event]))
136
+ file.events = [file.root, ...current.values()]
137
+ }
138
+ return [...files.values()]
139
+ }
140
+
141
+ /**
142
+ * A list of files by the relay's list read: each first record the filter picks,
143
+ * with its fields' current changes and never its text (§6.13).
144
+ *
145
+ * `filter` picks first records, as §6.13 says: `#h` for a Folder's issues,
146
+ * `kinds` alone for the workspace's projects, `#d` for named ones, `search`
147
+ * for typing. Only for a relay advertising `file_list`.
148
+ */
149
+ export async function listFiles(query: QueryFn, filter: Record<string, unknown>): Promise<FileFields[]> {
150
+ if ('text' in filter) throw new Error('A list never carries text; open one file to read it.')
151
+ const events = await query([{ ...filter, fields: 'newest' }])
152
+ return filesOf(events)
153
+ }
154
+
155
+ /**
156
+ * One file, opened: its first record, its fields' current changes and, where
157
+ * the relay says `file_list.text`, its current text — one text however long
158
+ * its history (§6.13, C40). Undefined when the relay holds no such file the
159
+ * reader may read.
160
+ *
161
+ * Without `text` the answer has no text field at all, which is not "the text
162
+ * was never changed": a caller that needs it reads it the old way.
163
+ */
164
+ export async function openFile(
165
+ query: QueryFn,
166
+ file: { kind: number; pubkey: string; d: string },
167
+ options: { text: boolean },
168
+ ): Promise<FileFields | undefined> {
169
+ // By `#d` alone, the shape §6.13 names; the author is checked below.
170
+ const filter: Record<string, unknown> = { fields: 'newest', kinds: [file.kind], '#d': [file.d] }
171
+ if (options.text) filter.text = true
172
+ const events = await query([filter])
173
+ const address = `${file.kind}:${file.pubkey}:${file.d}`
174
+ return filesOf(events, { withText: options.text }).find((f) => f.address === address)
175
+ }
176
+
177
+ /**
178
+ * The text a change or first record holds: a change's `description`, or a
179
+ * first record's seed — a project's `description` tag, then its `content`
180
+ * (§6.2, §7.2).
181
+ */
182
+ export function textOf(event: SignedEvent): MergeText | undefined {
183
+ if (event.kind === KIND_CHANGE) {
184
+ const set = fieldsSetBy(event).find((f) => f.field === TEXT_FIELD)
185
+ return set ? { value: set.value, ...(set.format ? { format: set.format } : {}) } : undefined
186
+ }
187
+ const format = tagValue(event, CONTENT_FORMAT_TAG)
188
+ const value = tagValue(event, TEXT_FIELD) ?? event.content
189
+ return { value, ...(format ? { format } : {}) }
190
+ }
191
+
192
+ /** What a `conflict:` refusal says (§6.2), as the relay words it. */
193
+ export type Conflict =
194
+ | { kind: 'stale'; field: string; current?: string }
195
+ | { kind: 'sorts-before'; field: string }
196
+ | { kind: 'other' }
197
+
198
+ export function conflictOf(reason: string): Conflict | undefined {
199
+ if (!reason.startsWith('conflict:')) return undefined
200
+ const sorts = /^conflict: (\S+) does not sort after its prev\b/.exec(reason)
201
+ if (sorts) return { kind: 'sorts-before', field: sorts[1] }
202
+ const follows = /^conflict: (\S+) follows ([0-9a-f]{64})\s*$/.exec(reason)
203
+ if (follows) return { kind: 'stale', field: follows[1], current: follows[2] }
204
+ // A signer who cannot read the file's home is told only the field.
205
+ const bare = /^conflict: (\S+)\s*$/.exec(reason)
206
+ if (bare) return { kind: 'stale', field: bare[1] }
207
+ return { kind: 'other' }
208
+ }
209
+
210
+ /** What {@link writeChange} is handed. */
211
+ export interface WriteChangeArgs {
212
+ field: string
213
+ /** The value to set; for the text, mine. */
214
+ value: string
215
+ /** The text's `content-format`, when it is one. */
216
+ format?: string
217
+ /**
218
+ * The change this one follows, as the writer read it: the field's current
219
+ * change, or the first record's id for its first change. For the text it is
220
+ * also the base a merge starts from — the version the person, or the agent,
221
+ * last read.
222
+ */
223
+ prev: string
224
+ /**
225
+ * The unsigned change for this value, `prev` and time — `buildActionEvent`
226
+ * bound to the field's action, so the manifest decides its shape and every
227
+ * attempt carries the same tags.
228
+ */
229
+ build: (input: { value: string; format?: string; prev: string; createdAtMs: number }) => UnsignedEvent | string
230
+ sign: (event: UnsignedEvent) => Promise<SignedEvent>
231
+ publish: (event: SignedEvent) => Promise<{ ok: boolean; reason?: string; eventId?: string }>
232
+ /** Reads events by id, and the field's current change when a refusal names none. */
233
+ query: QueryFn
234
+ /** The field's current change, read again: {@link openFile}'s, for this field. */
235
+ current: (field: string) => Promise<SignedEvent | undefined>
236
+ /** The clock, in ms. */
237
+ now?: () => number
238
+ /** How many sends before giving up; 4 unless said. */
239
+ tries?: number
240
+ }
241
+
242
+ export type WriteChangeResult =
243
+ | {
244
+ ok: true
245
+ /** The id the relay accepted: the field's next `prev`. */
246
+ id: string
247
+ event: SignedEvent
248
+ /** Set when the text was merged onto someone's newer change, which it names. */
249
+ mergedOnto?: SignedEvent
250
+ }
251
+ | {
252
+ ok: true
253
+ /** Nothing was sent: mine, merged onto theirs, says nothing theirs does not. */
254
+ unchanged: true
255
+ id: string
256
+ mergedOnto: SignedEvent
257
+ }
258
+ | {
259
+ ok: false
260
+ /** Why nothing was saved, in the relay's words or the builder's. */
261
+ refused: string
262
+ }
263
+ | {
264
+ ok: false
265
+ /** The text asks: these blocks were changed by both, or edited against a delete. Nothing was saved. */
266
+ asks: MergeAsk[]
267
+ /** The change now current, whose words must be kept. */
268
+ theirs: SignedEvent
269
+ }
270
+
271
+ const byId = async (query: QueryFn, id: string) => (await query([{ ids: [id] }])).find((e) => e.id === id)
272
+
273
+ /**
274
+ * Write one field's change, naming the one it follows, and answer a
275
+ * `conflict:` as §6.2 says.
276
+ *
277
+ * - **Stale `prev`, a field other than the text**: read the current change
278
+ * (by the id the relay named, or {@link WriteChangeArgs.current} when it
279
+ * named none) and set the value again after it. Two setting one field is not
280
+ * a conflict to show: the later stands.
281
+ * - **Stale `prev`, the text**: merge mine onto the current text by §13.3,
282
+ * with the text `prev` named as the base, and send the merge after it. When
283
+ * a block asks, nothing is sent and the answer carries the blocks and
284
+ * theirs. Refused again, it merges again with what it last sent as mine and
285
+ * what it merged onto as the base.
286
+ * - **Does not sort after its `prev`**: the clock is behind; stamp it 1 ms
287
+ * after `prev`, `ts` and `created_at` agreeing.
288
+ * - **Anything else** (`invalid:` and the rest) is never sent again.
289
+ *
290
+ * A few tries, then it stops with the relay's last answer.
291
+ */
292
+ export async function writeChange(args: WriteChangeArgs): Promise<WriteChangeResult> {
293
+ const now = args.now ?? Date.now
294
+ const tries = args.tries ?? 4
295
+ const isText = args.field === TEXT_FIELD
296
+ let prev = args.prev
297
+ let after = 0
298
+ let mine: MergeText = { value: args.value, ...(args.format ? { format: args.format } : {}) }
299
+ let base: MergeText | undefined
300
+ let mergedOnto: SignedEvent | undefined
301
+ let last = ''
302
+
303
+ for (let attempt = 0; attempt < tries; attempt++) {
304
+ const built = args.build({ value: mine.value, format: mine.format, prev, createdAtMs: Math.max(now(), after) })
305
+ if (typeof built === 'string') return { ok: false, refused: built }
306
+ const signed = await args.sign(built)
307
+ const answer = await args.publish(signed)
308
+ if (answer.ok) return { ok: true, id: answer.eventId ?? signed.id, event: signed, ...(mergedOnto ? { mergedOnto } : {}) }
309
+ last = answer.reason ?? 'refused with no reason'
310
+ const conflict = conflictOf(last)
311
+ if (!conflict || conflict.kind === 'other' || conflict.field !== args.field) return { ok: false, refused: last }
312
+
313
+ if (conflict.kind === 'sorts-before') {
314
+ const followed = await byId(args.query, prev)
315
+ if (!followed) return { ok: false, refused: last }
316
+ after = changedAt(followed) + 1
317
+ continue
318
+ }
319
+
320
+ const head = conflict.current ? await byId(args.query, conflict.current) : await args.current(args.field)
321
+ if (!head) return { ok: false, refused: last }
322
+ after = changedAt(head) + 1
323
+ if (!isText) {
324
+ prev = head.id
325
+ continue
326
+ }
327
+
328
+ if (!base) {
329
+ const followed = await byId(args.query, prev)
330
+ base = followed && textOf(followed)
331
+ if (!base) return { ok: false, refused: `${last} (the text it followed, ${prev}, could not be read to merge onto)` }
332
+ }
333
+ const theirs = textOf(head)
334
+ if (!theirs) return { ok: false, refused: last }
335
+ const merge = mergeTexts(base, theirs, mine)
336
+ if (merge.asks) return { ok: false, asks: merge.asks, theirs: head }
337
+ mergedOnto = head
338
+ if (merge.merged.value === theirs.value && (merge.merged.format ?? '') === (theirs.format ?? '')) {
339
+ return { ok: true, unchanged: true, id: head.id, mergedOnto: head }
340
+ }
341
+ base = theirs
342
+ mine = merge.merged
343
+ prev = head.id
344
+ }
345
+ return { ok: false, refused: `still refused after ${tries} tries: ${last}` }
346
+ }
package/src/folders.ts CHANGED
@@ -50,6 +50,7 @@ import {
50
50
  buildDeleteChannel,
51
51
  buildEditChannelMetadata,
52
52
  buildFolderCommand,
53
+ KIND,
53
54
  type ChannelVisibility,
54
55
  type UnsignedEvent,
55
56
  } from '@estiva-app/protocol'
@@ -64,6 +65,12 @@ export interface FolderRef {
64
65
  * `["private"]`. Only a move *into* the Folder reads it.
65
66
  */
66
67
  private?: boolean
68
+ /**
69
+ * `FolderSummary.company`: the relay marks it the Company team (§3.4). Only
70
+ * {@link planMoveFromFolders} reads it, as the home of a topic made outside
71
+ * any team.
72
+ */
73
+ company?: boolean
67
74
  /**
68
75
  * `FolderSummary.addresses`: what its state lists. Only
69
76
  * {@link planMoveFromFolders} reads it, to know a source lists the moved
@@ -206,6 +213,8 @@ export function planArchiveFolder(
206
213
  // shape produce the same tags.
207
214
  tags: [
208
215
  ['a', args.channel],
216
+ // The file it is about, by its id (§6.2).
217
+ ...(identifierOf(args.channel) !== undefined ? [['O', identifierOf(args.channel)!]] : []),
209
218
  ['field', 'archived'],
210
219
  ['value', args.archived ? 'true' : ''],
211
220
  ['h', args.folder],
@@ -216,6 +225,11 @@ export function planArchiveFolder(
216
225
  ]
217
226
  }
218
227
 
228
+ /** The file's id, the `d` of an address `<kind>:<pubkey>:<d>`; undefined for anything else. */
229
+ export function identifierOf(address: string): string | undefined {
230
+ return /^\d+:[0-9a-f]{64}:([^]*)$/.exec(address)?.[1]
231
+ }
232
+
219
233
  /**
220
234
  * A file as a move needs it. A `ForeignObject` from `resolveFolderContents` is
221
235
  * one: `ref` is its identity, `parentRef` the file it is drawn beneath, and
@@ -237,8 +251,11 @@ export interface MovableFile {
237
251
  * `target-is-private`: the target's `kind:39000` is private and a moved file's
238
252
  * `h` names any other channel, or none. A listing never changes who can read a
239
253
  * file (§3.1), so the file would look private in the target and not be.
254
+ *
255
+ * `target-is-not-home`: a topic no team lists goes only to its home, the team
256
+ * its `h` names or else the Company team (§3.3).
240
257
  */
241
- export type MoveRefusal = 'source-has-no-state' | 'target-has-no-state' | 'target-is-private'
258
+ export type MoveRefusal = 'source-has-no-state' | 'target-has-no-state' | 'target-is-private' | 'target-is-not-home'
242
259
 
243
260
  export type MovePlan =
244
261
  | {
@@ -290,31 +307,27 @@ export function listedBeneath<T extends MovableFile>(listing: readonly T[], file
290
307
  }
291
308
 
292
309
  /**
293
- * Move a file to another Folder, with everything listed beneath it:
294
- * `[kind:1852 add to target, kind:1852 remove from source]` — SPEC §3.3.
310
+ * Move a file to another Folder, with everything listed beneath it: one
311
+ * `kind:1852 move` in the target naming the source in `from` — SPEC §3.3.
295
312
  *
296
- * **One command each way, naming the whole set.** `listing` is the source
297
- * Folder's files (`FolderContents.files`); the file moves with every file
298
- * listed beneath it ({@link listedBeneath}), so a subtree moves whole. The
299
- * relay applies every address on a command in one state write, so a failure
300
- * can never split the subtree between the two Folders. The file itself is
301
- * moved only when the source lists it — a Ship issue is listed by no Folder,
302
- * its project is. The file's `h` does not change.
313
+ * **One command, naming the whole set.** `listing` is the source Folder's
314
+ * files (`FolderContents.files`); the file moves with every file listed
315
+ * beneath it ({@link listedBeneath}), so a subtree moves whole. The file
316
+ * itself is moved only when the source lists it — a Ship issue is listed by
317
+ * no Folder, its project is. The file's `h` does not change.
303
318
  *
304
319
  * `listing` is required, and `null` says "nothing can be listed beneath this
305
320
  * file", making the file the whole set. A move that silently left its
306
321
  * sub-files behind is the bug this planner exists to end, so omitting the
307
322
  * listing is a type error rather than a quiet single-file move.
308
323
  *
309
- * **Add first.** There is no atomic move — state is per Folder — so something
310
- * can fail between the two. After the add, a failure leaves the set in both
311
- * Folders: visible, obviously wrong, fixed by moving again. Removing first and
312
- * failing would leave it in neither, which looks like files that never were.
324
+ * **Both lists or neither.** The relay changes the source's and the target's
325
+ * list in one write, after checking the mover may change each; refused,
326
+ * nothing has changed, so a topic is never on no list (record
327
+ * a-topic-always-has-a-team-and-moves-in-one-action).
313
328
  *
314
- * **Refused unless both Folders have state.** An `add` to a Folder with none
315
- * emits state listing only the moved files, and everything already filed in
316
- * it disappears; a `remove` from one emits state listing nothing, and the
317
- * whole source disappears.
329
+ * **Refused unless both Folders have state.** The relay refuses a move
330
+ * between Folders that do not both hold a listing.
318
331
  *
319
332
  * **Refused into a private Folder** when any moved file's `h` is another
320
333
  * channel or absent (`target-is-private`, §3.1).
@@ -322,6 +335,7 @@ export function listedBeneath<T extends MovableFile>(listing: readonly T[], file
322
335
  * A move to the same Folder, or of a set the source does not list, plans nothing.
323
336
  *
324
337
  * why: https://github.com/estiva-app/estiva-docs/blob/main/decisions/moving-a-file-never-changes-who-can-read-it.md
338
+ * why: https://github.com/estiva-app/estiva-docs/blob/main/decisions/a-topic-always-has-a-team-and-moves-in-one-action.md
325
339
  */
326
340
  export function planMoveFile(
327
341
  pubkey: string,
@@ -341,10 +355,7 @@ export function planMoveFile(
341
355
  if (!moved.length) return { ok: true, events: [], moved }
342
356
  return {
343
357
  ok: true,
344
- events: [
345
- buildFolderCommand(pubkey, createdAtMs, { folder: args.to.id, op: 'add', addresses: moved }),
346
- buildFolderCommand(pubkey, createdAtMs, { folder: args.from.id, op: 'remove', addresses: moved }),
347
- ],
358
+ events: [buildFolderCommand(pubkey, createdAtMs, { folder: args.to.id, op: 'move', from: args.from.id, addresses: moved })],
348
359
  moved,
349
360
  }
350
361
  }
@@ -353,33 +364,31 @@ export type MoveFromFoldersPlan =
353
364
  | {
354
365
  ok: true
355
366
  /**
356
- * The one `kind:1852 add` in the target, naming everything moved. Publish
357
- * it first: refused, nothing has changed. Absent when there is nothing to send.
358
- */
359
- add?: UnsignedEvent
360
- /**
361
- * A `remove` for each source that lists part of the set, naming what that
362
- * source lists. Publish them once the add has landed; a refused one leaves
363
- * its Folder listing the set as well, which moving again fixes.
367
+ * The commands to publish, in order, stopping at the first the relay
368
+ * refuses: a `kind:1852 move` from each source that lists part of the
369
+ * set, or one `add` when no source lists any of it. Empty when there is
370
+ * nothing to send.
364
371
  */
365
- removes: { folder: string; event: UnsignedEvent }[]
366
- /** Every address the add names. */
372
+ events: UnsignedEvent[]
373
+ /** Every address the commands put in the target. */
367
374
  moved: string[]
368
375
  }
369
376
  | { ok: false; reason: MoveRefusal }
370
377
 
371
378
  /**
372
379
  * Move a file out of every Folder that lists it, with everything listed
373
- * beneath it in each: one `kind:1852 add` in the target naming the whole set,
374
- * then a `remove` in each source — SPEC §3.3.
380
+ * beneath it in each: one `kind:1852 move` from each source into the target
381
+ * — SPEC §3.3.
375
382
  *
376
383
  * {@link planMoveFile} for each source, and what every consumer did around it
377
384
  * (Ship's "Move to Folder…", Peek's Move, the agent's `move-project`), so it is
378
385
  * done once:
379
386
  *
380
- * - **One add, not one per source.** A file two Folders list can have a
381
- * different set beneath it in each. One add naming the union lands whole or
382
- * not at all, so a refusal never leaves part of the set in the target.
387
+ * - **One move per source.** A file two Folders list can have a different set
388
+ * beneath it in each; each move names what its source lists. Each changes
389
+ * both of its lists or neither, so no step leaves the file on no list, and a
390
+ * refusal halfway leaves it where the earlier moves put it (in the target
391
+ * and the sources not yet moved from), which moving again finishes.
383
392
  * - **The file is in a source whose state names it** (`from[i].addresses`),
384
393
  * even when its row is missing from that source's listing. A row that did
385
394
  * not resolve is still what is being moved.
@@ -407,8 +416,8 @@ export function planMoveFromFolders(
407
416
  ): MoveFromFoldersPlan {
408
417
  const { file, to } = args
409
418
  const sources = args.from.filter((folder) => folder.id !== to.id)
410
- if (sources.length === 0 && args.from.length > 0) return { ok: true, removes: [], moved: [] }
411
- const removes: { folder: string; event: UnsignedEvent }[] = []
419
+ if (sources.length === 0 && args.from.length > 0) return { ok: true, events: [], moved: [] }
420
+ const events: UnsignedEvent[] = []
412
421
  const moved = new Set<string>()
413
422
  for (const from of sources) {
414
423
  const listing = args.listings.get(from.id) ?? null
@@ -423,16 +432,48 @@ export function planMoveFromFolders(
423
432
  })
424
433
  if (!plan.ok) return plan
425
434
  for (const address of plan.moved) moved.add(address)
426
- const remove = plan.events[1]
427
- if (remove) removes.push({ folder: from.id, event: remove })
435
+ events.push(...plan.events)
428
436
  }
429
437
  if (!to.hasState) return { ok: false, reason: 'target-has-no-state' }
430
438
  if (moved.size === 0) {
431
439
  if (to.private && file.scopedTo !== to.id) return { ok: false, reason: 'target-is-private' }
432
- if (!file.address) return { ok: true, removes: [], moved: [] }
433
- const [add] = planPlaceFile(pubkey, createdAtMs, { folder: to.id, address: file.address, hasState: true })
434
- return { ok: true, add, removes: [], moved: [file.address] }
440
+ if (!file.address) return { ok: true, events: [], moved: [] }
441
+ // A topic on no list goes home: its `h` team, or the Company team when its `h` is no team. Which `h`
442
+ // is a team is the relay's to know, so the Company team is let through here and the relay decides.
443
+ if (file.address.startsWith(`${KIND.FILE}:`) &&file.scopedTo !== to.id && !to.company) return { ok: false, reason: 'target-is-not-home' }
444
+ return { ok: true, events: planPlaceFile(pubkey, createdAtMs, { folder: to.id, address: file.address, hasState: true }), moved: [file.address] }
435
445
  }
436
- const addresses = [...moved]
437
- return { ok: true, add: buildFolderCommand(pubkey, createdAtMs, { folder: to.id, op: 'add', addresses }), removes, moved: addresses }
446
+ return { ok: true, events, moved: [...moved] }
447
+ }
448
+
449
+ /**
450
+ * What a refusal of `events[index]` from {@link planMoveFromFolders} means,
451
+ * so an app says it in its own words and never shows the relay's text.
452
+ *
453
+ * - `why`: `team-archived` (a team it leaves or enters is archived),
454
+ * `not-a-member` (moving a space needs a member of each team it changes),
455
+ * `changed-meanwhile` (a list changed since it was read: the team no longer
456
+ * lists it, or another team now does), or `refused`.
457
+ * - `nothingMoved`: the first command was refused, so nothing changed.
458
+ * - `notMovedFrom`: otherwise, the Folders that still list it besides the
459
+ * target — the refused command's `from` and every later one's.
460
+ */
461
+ export function readMoveRefusal(
462
+ events: readonly UnsignedEvent[],
463
+ index: number,
464
+ reason: string | undefined,
465
+ ): { why: 'team-archived' | 'not-a-member' | 'changed-meanwhile' | 'refused'; nothingMoved: boolean; notMovedFrom: string[] } {
466
+ const text = reason ?? ''
467
+ const why = /archived/i.test(text)
468
+ ? 'team-archived'
469
+ : /only the team's members/i.test(text)
470
+ ? 'not-a-member'
471
+ : /does not list|lists none of|listed by one team/i.test(text)
472
+ ? 'changed-meanwhile'
473
+ : 'refused'
474
+ const nothingMoved = index <= 0
475
+ const notMovedFrom = nothingMoved
476
+ ? []
477
+ : events.slice(index).flatMap((event) => event.tags.filter((tag) => tag[0] === 'from').map((tag) => tag[1]!))
478
+ return { why, nothingMoved, notMovedFrom }
438
479
  }
package/src/index.ts CHANGED
@@ -138,6 +138,7 @@ export {
138
138
  planUnlistFile,
139
139
  planMoveFile,
140
140
  planMoveFromFolders,
141
+ readMoveRefusal,
141
142
  planArchiveFolder,
142
143
  listedBeneath,
143
144
  type FolderRef,
@@ -169,6 +170,27 @@ export {
169
170
  type ListedFile,
170
171
  } from './topics.js'
171
172
 
173
+ /**
174
+ * A file as its fields, each kept in order by the relay (SPEC §6.2, §6.13):
175
+ * the list and open reads, and the change writer that answers `conflict:`.
176
+ */
177
+ export {
178
+ TEXT_FIELD,
179
+ changedAt,
180
+ fieldsSetBy,
181
+ filesOf,
182
+ listFiles,
183
+ openFile,
184
+ textOf,
185
+ conflictOf,
186
+ writeChange,
187
+ type CurrentField,
188
+ type FileFields,
189
+ type Conflict,
190
+ type WriteChangeArgs,
191
+ type WriteChangeResult,
192
+ } from './fields.js'
193
+
172
194
  /**
173
195
  * What an app link names, and where a file is mentioned — once for every app
174
196
  * (SPEC §7.7, §13.1, §6.8; PEEKM-7). Each app passes its relay read; none