@skillre/dsh-plugin-sticky-wall 0.7.0 → 0.8.2

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/lib/store.js CHANGED
@@ -1,23 +1,34 @@
1
1
  /**
2
- * Durable note store over the DSH storage domain.
2
+ * Durable note store over the real `.md` files under the notes directory.
3
3
  *
4
4
  * The Host owns all data: the Client renders snapshots and submits intents, and
5
5
  * every write goes through {@link StickyWallStore} — validate, persist, then
6
- * hand back the changed records. The storage domain provides a single
7
- * per-domain write chain, so concurrent writes cannot interleave, and its
8
- * `per-record` layout keeps one file per note: one damaged record cannot take
9
- * the whole wall down.
6
+ * hand back the changed records.
10
7
  *
11
- * The domain spec is mirrored structurally instead of imported: importing
12
- * `@deepseek-ai/dsh-storage-domain` would install a second copy of the domain
13
- * package (and its zod) inside the plugin instead of resolving the host's. The
14
- * mirrored shape is the contract the live Host validates at `open()`:
15
- * `{ name, version, layout, invalidRecords, tables: { <name>: { valueSchema } } }`
16
- * with zod record schemas.
8
+ * 0.8.0 moved the notes off the storage domain and onto plain files the user can
9
+ * open in any editor: one `.md` per note, frontmatter for the attributes, the
10
+ * body being the note text itself. That shape is why this store looks the way it
11
+ * does:
12
+ *
13
+ * - **Reads are synchronous.** Every note is loaded once at `open()` into the
14
+ * in-memory map, which stays the AUTHORITATIVE cache. The wall polls with the
15
+ * cheap `revision` call, so a read must never touch the disk.
16
+ * - **Writes go to disk FIRST, then to the cache.** A resolved mutation means
17
+ * the bytes are on disk; the cache can never run ahead of the file, and a
18
+ * failed write leaves the previous state intact.
19
+ * - **Every mutation is serialised** on one chain, so a check-then-write pair —
20
+ * the `maxNotes` count followed by the write — cannot interleave with another
21
+ * request. The filesystem gives us no such guarantee on its own.
22
+ * - **One unreadable file never takes the wall down.** A file that is too large,
23
+ * misnamed or carries a broken frontmatter block is skipped, or degraded to a
24
+ * note with `metaError`, but never thrown away.
17
25
  */
18
- import { z } from 'zod';
26
+ import { mkdir, readdir, readFile, rename, rm, stat, writeFile } from 'node:fs/promises';
27
+ import { join, resolve } from 'node:path';
19
28
  import { arrangeLayouts, clampLayout, findFreeLayout, normalizeReserve, normalizeWidth, sameLayout } from './layout.js';
20
- import { CENTRE_RESERVE, COLORS, WIDTHS, DOMAIN_NAME, DOMAIN_VERSION, LIMITS, } from './types.js';
29
+ import { fileNameOf, idOfFile, isNoteId, parseNoteFile, serializeNoteFile } from './frontmatter.js';
30
+ import { migrateNotes } from './migrate.js';
31
+ import { CENTRE_RESERVE, COLORS, LIMITS, } from './types.js';
21
32
  /** Failure carrying a stable code the transport maps onto the RPC envelope. */
22
33
  export class WallError extends Error {
23
34
  code;
@@ -29,40 +40,6 @@ export class WallError extends Error {
29
40
  this.name = 'WallError';
30
41
  }
31
42
  }
32
- /** Record schema; every stored note is validated at domain open and on write. */
33
- const NoteSchema = z
34
- .object({
35
- id: z.string().min(1).max(128),
36
- title: z.string().max(LIMITS.title).default(''),
37
- body: z.string().min(1).max(LIMITS.body),
38
- tags: z.array(z.string().min(1).max(LIMITS.tag)).max(LIMITS.tags).default([]),
39
- color: z.enum(COLORS).default('yellow'),
40
- pinned: z.boolean().default(false),
41
- archived: z.boolean().default(false),
42
- createdAt: z.string().min(1),
43
- updatedAt: z.string().min(1),
44
- // `null` means "never placed": the Client derives a preview position from
45
- // the note id. A stored layout is owned by the Host, so a wall opened in
46
- // two windows shows the same arrangement.
47
- layout: z
48
- .object({
49
- x: z.number(),
50
- y: z.number(),
51
- rotate: z.number(),
52
- width: z.enum(WIDTHS),
53
- })
54
- .nullable()
55
- .default(null),
56
- })
57
- .passthrough();
58
- /** The domain declaration handed to `ctx.storageDomain.open()`. */
59
- export const DOMAIN_SPEC = {
60
- name: DOMAIN_NAME,
61
- version: DOMAIN_VERSION,
62
- layout: 'per-record',
63
- invalidRecords: 'backup-and-skip',
64
- tables: { notes: { valueSchema: NoteSchema } },
65
- };
66
43
  /** Normalize one tag: trim, lowercase, collapse inner whitespace, bound length. */
67
44
  function normalizeTag(raw) {
68
45
  const value = String(raw ?? '').trim().toLowerCase().replace(/\s+/g, ' ');
@@ -83,13 +60,47 @@ function normalizeTags(raw) {
83
60
  }
84
61
  return [...seen];
85
62
  }
86
- /** Validate and trim a note body; a live note may not be blank. */
87
- function normalizeBody(raw) {
88
- const value = String(raw ?? '').replace(/\r\n?/g, '\n').trim();
89
- if (value === '')
90
- throw new WallError('empty-body', 'A note needs some text.');
63
+ /**
64
+ * The stored body for a submitted string.
65
+ *
66
+ * Line endings are normalized, and NOTHING ELSE is touched — in particular the
67
+ * body is never trimmed. The card-height estimate walks this text line by line
68
+ * and the file round-trip has to give back exactly what was written, so a stray
69
+ * `.trim()` here would change every card's geometry and silently eat the blank
70
+ * lines a user indented with.
71
+ */
72
+ function readBody(raw) {
73
+ return String(raw ?? '').replace(/\r\n?/g, '\n');
74
+ }
75
+ /** Validate the body length against {@link LIMITS.body}. */
76
+ function assertBodyLength(value) {
91
77
  if (value.length > LIMITS.body)
92
78
  throw new WallError('body-too-long', `A note is limited to ${LIMITS.body} characters.`, { limit: LIMITS.body, length: value.length });
79
+ }
80
+ /**
81
+ * Validate a body for CREATE, where a note must actually say something.
82
+ *
83
+ * Emptiness is judged on the trimmed text so a note of three spaces is still
84
+ * refused, but the STORED value keeps every character the caller sent.
85
+ */
86
+ function normalizeBody(raw) {
87
+ const value = readBody(raw);
88
+ if (value.trim() === '')
89
+ throw new WallError('empty-body', 'A note needs some text.');
90
+ assertBodyLength(value);
91
+ return value;
92
+ }
93
+ /**
94
+ * Validate a body for an UPDATE.
95
+ *
96
+ * An existing note may be saved EMPTY. Deleting the last character of a note is
97
+ * a legitimate edit — the user is clearing the card to retype it, or keeping a
98
+ * card as a title only — and refusing it left the editor unable to save at all,
99
+ * with the old text still on disk. Length is still capped.
100
+ */
101
+ function normalizeBodyForUpdate(raw) {
102
+ const value = readBody(raw);
103
+ assertBodyLength(value);
93
104
  return value;
94
105
  }
95
106
  /** Validate and trim a title; an absent title is the empty string. */
@@ -122,19 +133,24 @@ function normalizeLayout(raw) {
122
133
  }
123
134
  return clampLayout({ x, y, rotate, width: normalizeWidth(value.width) });
124
135
  }
125
- /** Reject ids that are not plausible note keys before touching storage. */
136
+ /**
137
+ * Reject ids that cannot name a note file before anything is touched.
138
+ *
139
+ * The id is now a BASENAME, so this is also the path-traversal guard: `../x`
140
+ * must never reach `pathOf`.
141
+ */
126
142
  function assertIds(raw) {
127
143
  if (!Array.isArray(raw) || raw.length === 0)
128
144
  throw new WallError('invalid-ids', 'Select at least one note.');
129
145
  if (raw.length > LIMITS.bulk)
130
146
  throw new WallError('too-many-ids', `At most ${LIMITS.bulk} notes per request.`, { limit: LIMITS.bulk });
131
147
  const ids = [...new Set(raw.map((id) => String(id ?? '')))];
132
- if (ids.some((id) => id === '' || id.length > 128))
148
+ if (ids.some((id) => !isNoteId(id)))
133
149
  throw new WallError('invalid-ids', 'One of the selected note ids is invalid.');
134
150
  return ids;
135
151
  }
136
152
  /**
137
- * One record's sort weight: pinned first, then the requested ordering, with the
153
+ * One note's sort weight: pinned first, then the requested ordering, with the
138
154
  * id as a final tiebreaker so two notes written in the same millisecond still
139
155
  * render in a stable order.
140
156
  */
@@ -150,41 +166,84 @@ function compareNotes(sort) {
150
166
  }
151
167
  /** The store facade the Host endpoint and the agent tool share. */
152
168
  export class StickyWallStore {
153
- domain;
169
+ /** Absolute directory the notes live in. */
170
+ notesDir;
171
+ notes = new Map();
154
172
  maxNotes;
155
173
  now;
156
- notes;
174
+ log;
175
+ /** Backing counter for {@link revision}. */
176
+ counter = 0;
157
177
  closed = false;
158
178
  /**
159
179
  * Store-level mutation chain.
160
180
  *
161
- * The storage domain serializes its own writes, but a read-then-write pair
162
- * (the `maxNotes` check followed by the `put`) is two steps: two concurrent
163
- * creates at the boundary would both read the pre-write count and both
164
- * succeed. Every mutation therefore runs on this chain, so each check and its
165
- * write are one indivisible step.
181
+ * A read-then-write pair (the `maxNotes` check followed by the file write) is
182
+ * two steps, and two concurrent creates at the boundary would both read the
183
+ * pre-write count and both succeed. Every mutation therefore runs on this
184
+ * chain, so each check and its write are one indivisible step.
166
185
  */
167
186
  chain = Promise.resolve();
168
- constructor(domain, maxNotes, now = () => new Date()) {
169
- this.domain = domain;
170
- this.maxNotes = maxNotes;
171
- this.now = now;
172
- this.notes = domain.table('notes');
173
- }
174
- /** Open one domain and wrap it in a store. */
175
- static async open(open, options) {
176
- const domain = await open(DOMAIN_SPEC);
177
- const store = new StickyWallStore(domain, options.maxNotes, options.now ?? (() => new Date()));
187
+ constructor(options) {
188
+ this.notesDir = resolve(options.notesDir);
189
+ this.maxNotes = options.maxNotes;
190
+ this.now = options.now ?? (() => new Date());
191
+ this.log = options.log ?? (() => { });
192
+ }
193
+ /**
194
+ * Open the notes directory and load every note.
195
+ *
196
+ * Order matters: the one-time migration runs BEFORE the directory is created,
197
+ * because the migration publishes its result with a single atomic `rename` of
198
+ * a staging directory and would otherwise have to rename over a directory this
199
+ * method had just made. Once the directory and the cache agree, the store is
200
+ * usable; every later read is served from memory.
201
+ */
202
+ static async open(options) {
203
+ const store = new StickyWallStore(options);
204
+ if (options.readLegacy !== undefined) {
205
+ const result = await migrateNotes({
206
+ notesDir: store.notesDir,
207
+ readLegacy: options.readLegacy,
208
+ ...(options.legacyNotesDir === undefined ? {} : { legacyNotesDir: options.legacyNotesDir }),
209
+ ...(options.now === undefined ? {} : { now: options.now }),
210
+ });
211
+ if (!result.migrated && result.reason === 'failed') {
212
+ // The legacy wall is untouched and the next start retries, so the plugin
213
+ // still opens — empty rather than broken. Say so loudly enough that the
214
+ // Host log explains why the user's notes are missing.
215
+ store.log(`sticky-wall: legacy migration failed, opening an empty wall: ${result.error ?? 'unknown error'}`);
216
+ }
217
+ }
218
+ await mkdir(store.notesDir, { recursive: true });
219
+ await store.load();
178
220
  if (options.seedWelcomeNote)
179
221
  await store.seedWelcomeNote();
180
222
  return store;
181
223
  }
182
- /** Release the domain handle; later writes fail instead of silently dropping. */
224
+ /**
225
+ * Monotonic change counter; bumps once per mutation that actually changed
226
+ * something.
227
+ *
228
+ * The Client cannot be pushed to, so it polls. An unchanged number means the
229
+ * caller must not touch component state at all — that is what keeps a
230
+ * background refresh from interrupting someone mid-composition in the editor.
231
+ */
232
+ get revision() {
233
+ return this.counter;
234
+ }
235
+ /**
236
+ * Close the store: drain queued writes, then refuse new ones.
237
+ *
238
+ * Draining is the point. A mutation that started before `close()` may still be
239
+ * writing its file; dropping the chain would acknowledge a note to the Client
240
+ * and then lose it on shutdown.
241
+ */
183
242
  async close() {
184
243
  if (this.closed)
185
244
  return;
186
245
  this.closed = true;
187
- await this.domain.close();
246
+ await this.chain;
188
247
  }
189
248
  assertOpen() {
190
249
  if (this.closed)
@@ -196,9 +255,97 @@ export class StickyWallStore {
196
255
  this.chain = result.then(() => undefined, () => undefined);
197
256
  return result;
198
257
  }
258
+ /** Absolute `.md` path for a note id. */
259
+ pathOf(id) {
260
+ if (!isNoteId(id))
261
+ throw new WallError('invalid-ids', `Note id ${JSON.stringify(id)} cannot be a file name.`, { id });
262
+ return join(this.notesDir, fileNameOf(id));
263
+ }
264
+ /**
265
+ * Read every note file into the cache.
266
+ *
267
+ * The directory is the source of truth, so this is deliberately forgiving: a
268
+ * subdirectory, a file that is not named after a valid note id, a file too
269
+ * large to be a note, or one that cannot be read is skipped with a log line
270
+ * and the rest of the wall still opens.
271
+ */
272
+ async load() {
273
+ let entries;
274
+ try {
275
+ entries = await readdir(this.notesDir, { withFileTypes: true });
276
+ }
277
+ catch (error) {
278
+ // The directory was removed between `mkdir` and here; an empty wall is the
279
+ // right answer, and the first write recreates it.
280
+ if (error.code === 'ENOENT')
281
+ return;
282
+ throw error;
283
+ }
284
+ for (const entry of entries) {
285
+ if (!entry.isFile())
286
+ continue;
287
+ const id = idOfFile(entry.name);
288
+ if (id === null)
289
+ continue;
290
+ const path = join(this.notesDir, entry.name);
291
+ try {
292
+ // Size is checked BEFORE the read: the point of the cap is not to hand a
293
+ // 200 MB accidental paste to the parser at all.
294
+ const info = await stat(path);
295
+ if (info.size > LIMITS.fileBytes) {
296
+ this.log(`sticky-wall: skipping oversized note file ${entry.name} (${String(info.size)} bytes)`);
297
+ continue;
298
+ }
299
+ const parsed = parseNoteFile(await readFile(path, 'utf8'), {
300
+ fallbackId: id,
301
+ // The file's own mtime is the only honest timestamp a hand-written
302
+ // note has; a note WITH frontmatter keeps its authored `created`.
303
+ fallbackTime: info.mtime.toISOString(),
304
+ });
305
+ // The file name is the identity on disk. A frontmatter `id` that
306
+ // disagrees (a hand-copied file, a rename) must not become a second
307
+ // address for the same note: the next write would then land in a
308
+ // different file and leave the loaded one behind.
309
+ this.notes.set(id, { ...parsed.note, id });
310
+ }
311
+ catch (error) {
312
+ this.log(`sticky-wall: skipping unreadable note file ${entry.name}: ${error instanceof Error ? error.message : String(error)}`);
313
+ }
314
+ }
315
+ }
316
+ /**
317
+ * Persist one note.
318
+ *
319
+ * The bytes go to a sibling temp file and are then `rename`d over the target:
320
+ * within one directory that is atomic, so a reader — or a crash — sees either
321
+ * the old note or the new one and never a half-written file. Writing the
322
+ * target directly would truncate it first, and a crash in that window loses
323
+ * the note outright.
324
+ */
325
+ async writeNote(note) {
326
+ const target = this.pathOf(note.id);
327
+ const temporary = `${target}.tmp`;
328
+ await mkdir(this.notesDir, { recursive: true });
329
+ // The temp name never ends in `.md`, so a crash that strands one here is
330
+ // skipped by {@link load} as "not a note file" instead of being read back as
331
+ // a half-written note or a duplicate.
332
+ try {
333
+ await writeFile(temporary, serializeNoteFile(note), 'utf8');
334
+ await rename(temporary, target);
335
+ }
336
+ catch (error) {
337
+ // A failed write must not leave debris beside a note the user can see.
338
+ await rm(temporary, { force: true }).catch(() => { });
339
+ throw error;
340
+ }
341
+ }
342
+ /** Remove one note file; already gone is not an error. */
343
+ async dropFile(id) {
344
+ await rm(this.pathOf(id), { force: true });
345
+ }
199
346
  liveCount() {
200
347
  let count = 0;
201
- for (const [, note] of this.notes.entries())
348
+ for (const note of this.notes.values())
202
349
  if (!note.archived)
203
350
  count += 1;
204
351
  return count;
@@ -228,7 +375,14 @@ export class StickyWallStore {
228
375
  return;
229
376
  const stamp = this.now().toISOString();
230
377
  const note = {
231
- id: 'welcome',
378
+ // A RANDOM id, not the literal `welcome`.
379
+ //
380
+ // The seeded note used to be written as `welcome.md`, which is a legal id
381
+ // a 0.7.x wall could already own (the old seed used exactly that name). A
382
+ // migration that recovered such a note and then let the seed run would
383
+ // OVERWRITE the user's real note — which is precisely what happened during
384
+ // the 0.8.0 incident's second restart. A fresh UUID can never collide.
385
+ id: globalThis.crypto.randomUUID(),
232
386
  title: '便签墙',
233
387
  body: '随手记下一闪而过的灵感,或一件临时的工作。点右下角的 + 新建一张便签;按 ⌘/Ctrl + Enter 保存。',
234
388
  tags: ['开始'],
@@ -247,17 +401,35 @@ export class StickyWallStore {
247
401
  // the first ring keeps the invariant true from the very first note.
248
402
  layout: { x: 300, y: -420, rotate: -1.6, width: 'md' },
249
403
  };
250
- await this.notes.put(note.id, note);
404
+ await this.writeNote(note);
405
+ this.notes.set(note.id, note);
406
+ this.counter += 1;
407
+ }
408
+ /** One note by id, or `null` when the wall has no such note. */
409
+ read(id) {
410
+ this.assertOpen();
411
+ return this.notes.get(id) ?? null;
251
412
  }
252
413
  /** Every stored note, newest-relevant first; archived ones only on request. */
253
414
  list(includeArchived = false, sort = 'pinned') {
254
415
  this.assertOpen();
416
+ return this.gathered(includeArchived, sort);
417
+ }
418
+ /**
419
+ * The snapshot the store's own mutations work from.
420
+ *
421
+ * Deliberately does NOT check `closed`: {@link close} drains queued writes
422
+ * AFTER flipping the flag, so a mutation that was already acknowledged still
423
+ * has to run to completion — refusing it here would lose a note the caller
424
+ * was told was saved. It is private for exactly that reason: an outside caller
425
+ * always goes through {@link list}, which does check.
426
+ */
427
+ gathered(includeArchived, sort) {
255
428
  const notes = [];
256
- for (const [, note] of this.notes.entries()) {
257
- const value = note;
258
- if (value.archived && !includeArchived)
429
+ for (const note of this.notes.values()) {
430
+ if (note.archived && !includeArchived)
259
431
  continue;
260
- notes.push(value);
432
+ notes.push(note);
261
433
  }
262
434
  return notes.sort(compareNotes(sort));
263
435
  }
@@ -277,6 +449,21 @@ export class StickyWallStore {
277
449
  async createNow(input, id, options = {}) {
278
450
  const body = normalizeBody(input?.body);
279
451
  const title = normalizeTitle(input?.title);
452
+ // An explicit id becomes a file name, so it has to be one we would accept
453
+ // from disk as well; a generated UUID already satisfies this.
454
+ if (id !== undefined && !isNoteId(id))
455
+ throw new WallError('invalid-ids', `Note id ${JSON.stringify(id)} cannot be a file name.`, { id });
456
+ if (id !== undefined) {
457
+ // The FILE is the identity, not the cache entry: a note file big enough to
458
+ // be skipped at load, or one written by another tool while this store was
459
+ // open, is not in `notes` but is very much on disk. Overwriting it with a
460
+ // fresh note would destroy a file the user still has.
461
+ if (this.notes.has(id))
462
+ throw new WallError('duplicate-id', `A note with id ${JSON.stringify(id)} already exists.`);
463
+ const taken = await stat(this.pathOf(id)).then(() => true, () => false);
464
+ if (taken)
465
+ throw new WallError('duplicate-id', `A note file named ${JSON.stringify(fileNameOf(id))} already exists.`, { id });
466
+ }
280
467
  this.assertRoom(1);
281
468
  const stamp = this.now().toISOString();
282
469
  const note = {
@@ -291,16 +478,17 @@ export class StickyWallStore {
291
478
  updatedAt: stamp,
292
479
  layout: input?.layout === undefined ? null : normalizeLayout(input.layout),
293
480
  };
294
- if (this.notes.get(note.id) !== undefined)
295
- throw new WallError('duplicate-id', `A note with id ${JSON.stringify(note.id)} already exists.`);
296
481
  // A note with no explicit placement gets the nearest free spot on the wall,
297
482
  // not `null`. `null` means "derive a position from my index", and that spiral
298
483
  // grows outward — so the user's tenth capture could land a screen away from
299
484
  // where they were looking, which reads as the capture having failed.
300
485
  if (note.layout === null) {
301
- note.layout = findFreeLayout(note, this.list(true, 'pinned'), { centreReserve: normalizeReserve(options.centreReserve ?? CENTRE_RESERVE) });
486
+ note.layout = findFreeLayout(note, this.gathered(true, 'pinned'), { centreReserve: normalizeReserve(options.centreReserve ?? CENTRE_RESERVE) });
302
487
  }
303
- await this.notes.put(note.id, note);
488
+ // Disk first, then the cache: a resolution means the note exists as a file.
489
+ await this.writeNote(note);
490
+ this.notes.set(note.id, note);
491
+ this.counter += 1;
304
492
  return note;
305
493
  }
306
494
  /** Apply one patch; `updatedAt` moves only when a field actually changed. */
@@ -312,9 +500,12 @@ export class StickyWallStore {
312
500
  const current = this.notes.get(id);
313
501
  if (current === undefined)
314
502
  throw new WallError('not-found', `No note with id ${JSON.stringify(id)}.`, { id });
503
+ // The patch is applied OVER the current note, so `extra` (unknown
504
+ // frontmatter keys the user or a newer build owns) and `metaError` (why this
505
+ // file's frontmatter is suspect) ride through untouched.
315
506
  const next = { ...current };
316
507
  if (patch?.body !== undefined)
317
- next.body = normalizeBody(patch.body);
508
+ next.body = normalizeBodyForUpdate(patch.body);
318
509
  if (patch?.title !== undefined)
319
510
  next.title = normalizeTitle(patch.title);
320
511
  if (patch?.tags !== undefined)
@@ -330,10 +521,15 @@ export class StickyWallStore {
330
521
  this.assertRoom(1);
331
522
  const changed = ['body', 'title', 'color', 'pinned', 'archived'].some((key) => next[key] !== current[key]) ||
332
523
  JSON.stringify(next.tags) !== JSON.stringify(current.tags);
524
+ // A patch that changes nothing writes nothing: no file churn, no revision
525
+ // bump, so a polling Client sees no reason to re-render.
333
526
  if (!changed)
334
527
  return current;
335
528
  next.updatedAt = this.now().toISOString();
336
- return this.notes.update(id, () => next);
529
+ await this.writeNote(next);
530
+ this.notes.set(id, next);
531
+ this.counter += 1;
532
+ return next;
337
533
  }
338
534
  /**
339
535
  * Flip the archived flag on a batch; returns the notes that actually moved.
@@ -361,10 +557,15 @@ export class StickyWallStore {
361
557
  if (!archived)
362
558
  this.assertRoom(targets.length);
363
559
  const changed = [];
560
+ const stamp = this.now().toISOString();
364
561
  for (const current of targets) {
365
- const next = { ...current, archived, updatedAt: this.now().toISOString() };
366
- changed.push(await this.notes.update(current.id, () => next));
562
+ const next = { ...current, archived, updatedAt: stamp };
563
+ await this.writeNote(next);
564
+ this.notes.set(next.id, next);
565
+ changed.push(next);
367
566
  }
567
+ if (changed.length > 0)
568
+ this.counter += 1;
368
569
  return changed;
369
570
  }
370
571
  /**
@@ -382,14 +583,17 @@ export class StickyWallStore {
382
583
  async removeNow(ids) {
383
584
  const selected = assertIds(ids);
384
585
  for (const id of selected) {
385
- if (this.notes.get(id) === undefined)
586
+ if (!this.notes.has(id))
386
587
  throw new WallError('not-found', `No note with id ${JSON.stringify(id)}.`, { id });
387
588
  }
388
589
  const removed = [];
389
590
  for (const id of selected) {
390
- await this.notes.delete(id);
591
+ await this.dropFile(id);
592
+ this.notes.delete(id);
391
593
  removed.push(id);
392
594
  }
595
+ if (removed.length > 0)
596
+ this.counter += 1;
393
597
  return removed;
394
598
  }
395
599
  /**
@@ -409,9 +613,14 @@ export class StickyWallStore {
409
613
  if (current === undefined)
410
614
  throw new WallError('not-found', `No note with id ${JSON.stringify(id)}.`, { id });
411
615
  const next = normalizeLayout(layout);
616
+ // The same placement again is a no-op: no write, no revision bump.
412
617
  if (sameLayout(current.layout, next))
413
618
  return current;
414
- return this.notes.update(id, () => ({ ...current, layout: next }));
619
+ const moved = { ...current, layout: next };
620
+ await this.writeNote(moved);
621
+ this.notes.set(id, moved);
622
+ this.counter += 1;
623
+ return moved;
415
624
  }
416
625
  /**
417
626
  * Tidy the wall: repack every note into a deterministic shelf arrangement.
@@ -429,15 +638,20 @@ export class StickyWallStore {
429
638
  // archived-but-visible card at its dragged position, on top of the freshly
430
639
  // tidied ones — the wall has to be tidy in every filter, not just the
431
640
  // default one.
432
- const current = this.list(true, 'pinned');
641
+ const current = this.gathered(true, 'pinned');
433
642
  const planned = arrangeLayouts(current, { centreReserve: normalizeReserve(options.centreReserve ?? CENTRE_RESERVE) });
434
643
  const changed = [];
435
644
  for (const note of current) {
436
645
  const target = planned.get(note.id);
437
646
  if (target === undefined || sameLayout(note.layout, target))
438
647
  continue;
439
- changed.push(await this.notes.update(note.id, () => ({ ...note, layout: target })));
648
+ const moved = { ...note, layout: target };
649
+ await this.writeNote(moved);
650
+ this.notes.set(note.id, moved);
651
+ changed.push(moved);
440
652
  }
653
+ if (changed.length > 0)
654
+ this.counter += 1;
441
655
  return changed;
442
656
  }
443
657
  /**
@@ -452,12 +666,15 @@ export class StickyWallStore {
452
666
  return this.mutate(() => this.clearArchivedNow());
453
667
  }
454
668
  async clearArchivedNow() {
455
- const archived = this.list(true).filter((note) => note.archived).map((note) => note.id);
669
+ const archived = this.gathered(true, 'pinned').filter((note) => note.archived).map((note) => note.id);
456
670
  const removed = [];
457
671
  for (const id of archived) {
458
- await this.notes.delete(id);
672
+ await this.dropFile(id);
673
+ this.notes.delete(id);
459
674
  removed.push(id);
460
675
  }
676
+ if (removed.length > 0)
677
+ this.counter += 1;
461
678
  return removed;
462
679
  }
463
680
  /** Compact plain-text digest of the wall for the model-facing tool. */
@@ -467,7 +684,7 @@ export class StickyWallStore {
467
684
  return {
468
685
  total: all.length,
469
686
  archived: all.filter((note) => note.archived).length,
470
- notes: all.slice(0, Math.max(1, Math.min(limit, 50))),
687
+ notes: all.slice(0, Math.max(1, Math.min(limit, LIMITS.listLimit))),
471
688
  };
472
689
  }
473
690
  }
@@ -30,7 +30,13 @@ export interface HostConnection {
30
30
  /** The store operations the route dispatches onto. */
31
31
  export interface WallActions {
32
32
  list(includeArchived?: boolean, sort?: NoteSort): Note[];
33
- create(input: NoteInput): Promise<Note>;
33
+ /** The Host's current change counter, for the Client's cheap poll. */
34
+ revisionOf(): number;
35
+ /** Absolute directory the notes live in. */
36
+ readonly notesDir: string;
37
+ create(input: NoteInput, id?: string, options?: {
38
+ centreReserve?: CentreReserve | undefined;
39
+ }): Promise<Note>;
34
40
  update(id: string, patch: NotePatch): Promise<Note>;
35
41
  setArchived(ids: string[], archived: boolean): Promise<Note[]>;
36
42
  remove(ids: string[]): Promise<string[]>;
@@ -39,9 +45,6 @@ export interface WallActions {
39
45
  arrange(options?: {
40
46
  centreReserve?: CentreReserve | undefined;
41
47
  }): Promise<Note[]>;
42
- create(input: NoteInput, id?: string, options?: {
43
- centreReserve?: CentreReserve | undefined;
44
- }): Promise<Note>;
45
48
  }
46
49
  /**
47
50
  * Build the exact route Connection registers; every failure stays inside the
package/lib/transport.js CHANGED
@@ -65,12 +65,13 @@ const reserveSchema = z
65
65
  .strict();
66
66
  const requestSchema = z.discriminatedUnion('action', [
67
67
  z.object({ action: z.literal('list'), includeArchived: z.boolean().optional(), sort: sortSchema.optional() }).strict(),
68
+ z.object({ action: z.literal('revision') }).strict(),
68
69
  z
69
70
  .object({
70
71
  action: z.literal('create'),
71
72
  note: z
72
73
  .object({
73
- body: z.string().min(1).max(LIMITS.body),
74
+ body: z.string().max(LIMITS.body),
74
75
  title: z.string().max(LIMITS.title).optional(),
75
76
  tags: z.array(z.string().max(LIMITS.tag)).max(LIMITS.tags).optional(),
76
77
  color: colorSchema.optional(),
@@ -89,7 +90,10 @@ const requestSchema = z.discriminatedUnion('action', [
89
90
  id: idSchema,
90
91
  patch: z
91
92
  .object({
92
- body: z.string().min(1).max(LIMITS.body).optional(),
93
+ // An empty body is accepted on update: clearing the editor and saving
94
+ // must work instead of trapping the user in a validation error. Create
95
+ // still requires text, which the store enforces.
96
+ body: z.string().max(LIMITS.body).optional(),
93
97
  title: z.string().max(LIMITS.title).optional(),
94
98
  tags: z.array(z.string().max(LIMITS.tag)).max(LIMITS.tags).optional(),
95
99
  color: colorSchema.optional(),
@@ -125,7 +129,14 @@ function correlation(body) {
125
129
  async function dispatch(actions, request) {
126
130
  switch (request.action) {
127
131
  case 'list':
128
- return { notes: actions.list(request.includeArchived, request.sort) };
132
+ return {
133
+ notes: actions.list(request.includeArchived, request.sort),
134
+ revision: actions.revisionOf(),
135
+ notesDir: actions.notesDir,
136
+ domain: { name: 'sticky-wall', version: 2 },
137
+ };
138
+ case 'revision':
139
+ return { revision: actions.revisionOf() };
129
140
  case 'create':
130
141
  return { action: 'create', changed: [await actions.create(request.note, undefined, { centreReserve: request.centreReserve })], removed: [] };
131
142
  case 'update':