@skillre/dsh-plugin-sticky-wall 0.6.0 → 0.8.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/lib/index.js CHANGED
@@ -7,23 +7,58 @@
7
7
  * route, and the optional agent tool — belongs to this plugin's Fiber, so
8
8
  * stopping or updating the row releases all three with no residue.
9
9
  */
10
- import { Config, resolveConfig } from './config.js';
10
+ import { homedir } from 'node:os';
11
+ import { Config, resolveConfig, resolveNotesDir } from './config.js';
11
12
  import { StickyWallStore } from './store.js';
12
13
  import { createExecuteRoute } from './transport.js';
13
- import { LIMITS } from './types.js';
14
+ import { LEGACY_DOMAIN_NAME, LEGACY_DOMAIN_VERSION, LIMITS } from './types.js';
14
15
  export { Config, StickyWallStore };
15
16
  export const name = 'skillre-sticky-wall';
16
17
  /**
17
- * Required services. `storageDomain` provides the durable note table;
18
- * `connection` provides the authenticated Client route. Both are declared hard
19
- * dependencies so a profile missing either fails loudly instead of mounting a
20
- * wall that can never persist or be reached.
18
+ * Required services.
19
+ *
20
+ * `connection` provides the authenticated Client route and is a hard dependency:
21
+ * without it the wall could never be reached, so mounting should fail loudly.
22
+ *
23
+ * `storageDomain` is deliberately NOT listed. Notes live on disk now, and the
24
+ * domain is consulted only when a 0.7.x install still needs migrating, so it is
25
+ * read through `ctx.get()` and its absence is a normal, supported state (a fresh
26
+ * install has nothing to migrate).
21
27
  */
22
- export const inject = ['storageDomain', 'connection'];
28
+ export const inject = ['connection'];
23
29
  /** Read an optional Cordis service without declaring it required. */
24
30
  function service(ctx, key) {
25
31
  return ctx.get(key);
26
32
  }
33
+ /**
34
+ * Drain a 0.7.x install's storage-domain notes so they can be migrated.
35
+ *
36
+ * The domain's `notes` table is the ONLY thing read here: the migration writes
37
+ * `.md` files and never writes back, so a failed migration leaves the legacy
38
+ * records untouched and the next start retries. The handle is always closed,
39
+ * even when reading throws, because an open domain reserves its name for the
40
+ * whole process.
41
+ */
42
+ async function readLegacyNotes(facility) {
43
+ const domain = await facility.open({
44
+ name: LEGACY_DOMAIN_NAME,
45
+ version: LEGACY_DOMAIN_VERSION,
46
+ layout: 'per-record',
47
+ invalidRecords: 'backup-and-skip',
48
+ tables: { notes: {} },
49
+ });
50
+ try {
51
+ const notes = [];
52
+ for (const [, value] of domain.table('notes').entries()) {
53
+ if (value !== null && typeof value === 'object' && 'id' in value)
54
+ notes.push(value);
55
+ }
56
+ return notes;
57
+ }
58
+ finally {
59
+ await domain.close();
60
+ }
61
+ }
27
62
  /** Model-facing text for one tool result; short, deterministic and readable. */
28
63
  function renderWall(value) {
29
64
  const data = (value ?? {});
@@ -41,6 +76,22 @@ function renderWall(value) {
41
76
  });
42
77
  return [`${String(data.total ?? notes.length)} notes (${String(data.archived ?? 0)} archived):`, ...lines].join('\n');
43
78
  }
79
+ if (action === 'read') {
80
+ // The whole point of this action: the model gets the note's FULL text, not a
81
+ // 140-character head. Without it an agent asked to expand a note had to ask
82
+ // the user to paste it back, which is exactly the friction this removes.
83
+ const note = data.note;
84
+ if (note === undefined)
85
+ return 'No such note.';
86
+ const meta = [
87
+ `id: ${note.id}`,
88
+ note.title !== '' ? `title: ${note.title}` : '',
89
+ `color: ${note.color}${note.pinned ? ' · pinned' : ''}${note.archived ? ' · archived' : ''}`,
90
+ note.tags.length > 0 ? `tags: ${note.tags.join(', ')}` : '',
91
+ typeof data.path === 'string' ? `file: ${data.path}` : '',
92
+ ].filter((line) => line !== '');
93
+ return [...meta, '', note.body].join('\n');
94
+ }
44
95
  if (action === 'arrange') {
45
96
  const notes = Array.isArray(data.changed) ? data.changed : [];
46
97
  return notes.length === 0 ? 'The wall was already tidy.' : `Tidied ${notes.length} note${notes.length === 1 ? '' : 's'} into the shelf arrangement.`;
@@ -54,8 +105,10 @@ function renderWall(value) {
54
105
  return notes.length === 0 ? 'No note changed.' : notes.map((note) => `${note.id} ${note.archived ? 'archived' : 'restored'}`).join('\n');
55
106
  }
56
107
  const note = data.note;
57
- if (note)
58
- return `${action === 'create' ? 'Created' : 'Updated'} note ${note.id}${note.title ? ` (${note.title})` : ''}: ${note.body.replace(/\s+/g, ' ').slice(0, 140)}`;
108
+ if (note) {
109
+ const where = note.layout === null ? '' : ` at (${String(note.layout.x)}, ${String(note.layout.y)})`;
110
+ return `${action === 'create' ? 'Created' : 'Updated'} note ${note.id}${note.title ? ` (${note.title})` : ''}${where}: ${note.body.replace(/\s+/g, ' ').slice(0, 140)}`;
111
+ }
59
112
  return 'Done.';
60
113
  }
61
114
  /** Register the model-facing capture tool when the registry is present. */
@@ -66,30 +119,48 @@ function registerAgentTool(ctx, ready) {
66
119
  ctx.effect(() => {
67
120
  const disposer = tools.register({
68
121
  name: 'sticky_wall',
69
- description: "Capture and manage sticky notes on the user's DSH note wall (便签墙): quick inspiration, temporary tasks and short reminders. Use it when the user asks to note something down, list their notes, update or pin one, or clean up archived notes.",
122
+ description: "Capture and manage sticky notes on the user's DSH note wall (便签墙): quick inspiration, temporary tasks and short reminders. " +
123
+ 'Each note is a real Markdown file under the notes directory: its attributes (title, colour, tags, pin, size, canvas position) live in the YAML frontmatter block at the top, and everything after that block is the note body. ' +
124
+ "Use `read` to get a note's full text, `list` to scan titles, `create`/`update` to write attributes or text, and `move` to place a card on the canvas. " +
125
+ "To revise a note's PROSE you may edit the backing file directly with the file tools — but never modify the frontmatter between the `---` lines; change attributes with this tool's `update` action instead.",
70
126
  parameters: {
71
127
  type: 'object',
72
128
  additionalProperties: false,
73
129
  required: ['action'],
74
130
  properties: {
75
- action: { type: 'string', enum: ['list', 'create', 'update', 'archive', 'delete', 'clear-archived', 'arrange'] },
76
- id: { type: 'string', description: 'Exact note id; required by update.' },
77
- ids: { type: 'array', items: { type: 'string' }, description: 'Note ids; required by archive and delete (1–200 entries).' },
78
- body: { type: 'string', description: `The note text (1–${LIMITS.body} characters). Required by create; optional patch field for update.` },
79
- title: { type: 'string', description: `Optional short heading (max ${LIMITS.title} characters).` },
80
- tags: { type: 'array', items: { type: 'string' }, description: `Optional lowercase tags (max ${LIMITS.tags}).` },
81
- color: { type: 'string', enum: ['yellow', 'pink', 'green', 'blue', 'purple', 'orange'], description: 'Optional pastel note color.' },
131
+ action: {
132
+ type: 'string',
133
+ enum: ['list', 'read', 'create', 'update', 'move', 'archive', 'delete', 'clear-archived', 'arrange'],
134
+ description: 'list: scan notes. read: one note in full. create/update: write attributes or text. move: place one card on the canvas. archive/delete: batch state changes. clear-archived: permanent sweep. arrange: tidy the whole wall.',
135
+ },
136
+ id: { type: 'string', description: 'Exact note id; required by read, update and move.' },
137
+ ids: { type: 'array', items: { type: 'string' }, description: `Note ids; required by archive and delete (1–${LIMITS.bulk} entries).` },
138
+ body: { type: 'string', description: `The note text. Required by create; optional patch field for update. Max ${LIMITS.body} characters.` },
139
+ title: { type: 'string', description: `Short heading (max ${LIMITS.title} characters); '' clears it.` },
140
+ tags: { type: 'array', items: { type: 'string' }, description: `Lowercase tags (max ${LIMITS.tags}, each max ${LIMITS.tag} characters); [] clears them.` },
141
+ color: { type: 'string', enum: ['yellow', 'pink', 'green', 'blue', 'purple', 'orange'], description: 'Pastel note colour.' },
82
142
  pinned: { type: 'boolean', description: 'Pin the note to the top of the wall.' },
83
- archived: { type: 'boolean', description: 'Archive (true) or restore (false) one note on update.' },
84
- includeArchived: { type: 'boolean', description: 'list only: include archived notes.' },
85
- x: { type: 'number', description: 'Free-canvas horizontal position of the card, in canvas pixels. Optional on create.' },
86
- y: { type: 'number', description: 'Free-canvas vertical position of the card, in canvas pixels. Optional on create.' },
87
- limit: { type: 'integer', description: 'list only: how many notes to return (1–50, default 20).' },
143
+ archived: {
144
+ type: 'boolean',
145
+ // Required rather than defaulted: a model asked to RESTORE a note that
146
+ // merely omits this field used to re-archive it, silently doing the
147
+ // opposite of the request. A destructive flag must never default.
148
+ description: 'Required by archive: true archives, false restores. Never omitted.',
149
+ },
150
+ includeArchived: { type: 'boolean', description: 'list only: include archived notes (default false).' },
151
+ x: { type: 'number', description: 'Canvas horizontal position of the card, in canvas pixels. Used by create and move.' },
152
+ y: { type: 'number', description: 'Canvas vertical position of the card, in canvas pixels. Used by create and move.' },
153
+ width: { type: 'string', enum: ['sm', 'md', 'lg'], description: 'Card width preset. Used by create and move.' },
154
+ rotate: { type: 'number', description: 'Card tilt in degrees, clamped to ±12. Used by create and move.' },
155
+ limit: { type: 'integer', description: `list only: how many notes to return (1–${LIMITS.listLimit}, default 20).` },
88
156
  },
89
157
  },
90
158
  timeoutMs: 20_000,
91
159
  isConcurrencySafe(args) {
92
- return typeof args === 'object' && args !== null && args.action === 'list';
160
+ if (typeof args !== 'object' || args === null)
161
+ return false;
162
+ const action = args.action;
163
+ return action === 'list' || action === 'read';
93
164
  },
94
165
  output: {
95
166
  schema: { type: 'object', additionalProperties: true },
@@ -101,10 +172,31 @@ function registerAgentTool(ctx, ready) {
101
172
  execution.signal.throwIfAborted();
102
173
  const store = await ready;
103
174
  const args = (raw ?? {});
175
+ /** A complete placement from the flat coordinates, when all of them exist. */
176
+ const layoutFrom = () => {
177
+ if (typeof args.x !== 'number' || typeof args.y !== 'number')
178
+ return undefined;
179
+ const width = args.width === 'sm' || args.width === 'md' || args.width === 'lg' ? args.width : 'md';
180
+ return { x: args.x, y: args.y, rotate: typeof args.rotate === 'number' ? args.rotate : 0, width };
181
+ };
104
182
  switch (args.action) {
105
- case 'list':
106
- return { action: 'list', ...store.summary(typeof args.limit === 'number' ? args.limit : 20) };
107
- case 'create':
183
+ case 'list': {
184
+ // `includeArchived` was declared but ignored: `summary()` always read
185
+ // every note, so the tool's own description was false. Filter here so
186
+ // the flag means what it says.
187
+ const summary = store.summary(typeof args.limit === 'number' ? args.limit : 20);
188
+ const notes = args.includeArchived === true ? summary.notes : summary.notes.filter((note) => !note.archived);
189
+ return { action: 'list', ...summary, notes, archived: summary.archived, total: summary.total };
190
+ }
191
+ case 'read': {
192
+ const id = String(args.id ?? '');
193
+ const note = store.read(id);
194
+ if (note === null)
195
+ throw new Error(`No note with id ${JSON.stringify(id)}.`);
196
+ return { action: 'read', note, path: store.pathOf(id) };
197
+ }
198
+ case 'create': {
199
+ const placement = layoutFrom();
108
200
  return {
109
201
  action: 'create',
110
202
  note: await store.create({
@@ -113,11 +205,10 @@ function registerAgentTool(ctx, ready) {
113
205
  ...(Array.isArray(args.tags) ? { tags: args.tags.map(String) } : {}),
114
206
  ...(typeof args.color === 'string' ? { color: args.color } : {}),
115
207
  ...(typeof args.pinned === 'boolean' ? { pinned: args.pinned } : {}),
116
- ...(typeof args.x === 'number' && typeof args.y === 'number'
117
- ? { layout: { x: args.x, y: args.y, rotate: 0, width: 'md' } }
118
- : {}),
208
+ ...(placement === undefined ? {} : { layout: placement }),
119
209
  }),
120
210
  };
211
+ }
121
212
  case 'update':
122
213
  return {
123
214
  action: 'update',
@@ -130,8 +221,27 @@ function registerAgentTool(ctx, ready) {
130
221
  ...(typeof args.archived === 'boolean' ? { archived: args.archived } : {}),
131
222
  }),
132
223
  };
224
+ case 'move': {
225
+ const id = String(args.id ?? '');
226
+ const current = store.read(id);
227
+ if (current === null)
228
+ throw new Error(`No note with id ${JSON.stringify(id)}.`);
229
+ // A move keeps whatever the caller did not restate, so positioning a
230
+ // card does not silently change its size or straighten its tilt.
231
+ const base = current.layout;
232
+ const layout = {
233
+ x: typeof args.x === 'number' ? args.x : base?.x ?? 0,
234
+ y: typeof args.y === 'number' ? args.y : base?.y ?? 0,
235
+ rotate: typeof args.rotate === 'number' ? args.rotate : base?.rotate ?? 0,
236
+ width: args.width === 'sm' || args.width === 'md' || args.width === 'lg' ? args.width : base?.width ?? 'md',
237
+ };
238
+ return { action: 'move', note: await store.move(id, layout) };
239
+ }
133
240
  case 'archive':
134
- return { action: 'archive', notes: await store.setArchived(args.ids ?? [], args.archived === true) };
241
+ // A destructive flag must be stated, never inferred.
242
+ if (typeof args.archived !== 'boolean')
243
+ throw new Error('archive requires `archived: true` to archive or `archived: false` to restore.');
244
+ return { action: 'archive', notes: await store.setArchived(args.ids ?? [], args.archived) };
135
245
  case 'delete':
136
246
  return { action: 'delete', removed: await store.remove(args.ids ?? []) };
137
247
  case 'clear-archived':
@@ -151,17 +261,22 @@ export function apply(ctx, rawConfig = {}) {
151
261
  const connection = service(ctx, 'connection');
152
262
  if (!connection?.fetch?.register)
153
263
  throw new Error('Sticky wall requires the current DSH Connection exact Fetch-route registry.');
264
+ const notesDir = resolveNotesDir(config.notesDir, process.env, homedir());
265
+ // The legacy storage domain is now OPTIONAL: notes live on disk, and the
266
+ // domain is only opened once, to drain a 0.7.x install's records into `.md`
267
+ // files. A profile that never had the domain simply has nothing to migrate.
154
268
  const facility = service(ctx, 'storageDomain');
155
- if (!facility?.open)
156
- throw new Error('Sticky wall requires the DSH storageDomain facility.');
157
- const ready = StickyWallStore.open((spec) => facility.open(spec), {
269
+ const ready = StickyWallStore.open({
270
+ notesDir,
158
271
  maxNotes: config.maxNotes,
159
272
  seedWelcomeNote: config.seedWelcomeNote,
273
+ readLegacy: facility?.open === undefined ? undefined : () => readLegacyNotes(facility),
274
+ log: (message) => ctx.logger?.warn?.(`sticky-wall: ${message}`),
160
275
  });
161
276
  ready.catch((error) => {
162
277
  // The route and the tool both await `ready`, so the failure also reaches the
163
278
  // first caller; log it once so it is never silent in the Host log.
164
- ctx.logger?.error?.(`sticky-wall: storage domain failed to open: ${error instanceof Error ? error.message : String(error)}`);
279
+ ctx.logger?.error?.(`sticky-wall: notes directory failed to open: ${error instanceof Error ? error.message : String(error)}`);
165
280
  });
166
281
  ctx.effect(() => () => {
167
282
  void ready.then((store) => store.close()).catch(() => { });
@@ -170,13 +285,15 @@ export function apply(ctx, rawConfig = {}) {
170
285
  const store = await ready;
171
286
  return {
172
287
  list: (includeArchived, sort) => store.list(includeArchived, sort),
173
- create: (input) => store.create(input),
288
+ revisionOf: () => store.revision,
289
+ notesDir: store.notesDir,
290
+ create: (input, id, options) => store.create(input, id, options),
174
291
  update: (id, patch) => store.update(id, patch),
175
292
  setArchived: (ids, archived) => store.setArchived(ids, archived),
176
293
  remove: (ids) => store.remove(ids),
177
294
  clearArchived: () => store.clearArchived(),
178
295
  move: (id, layout) => store.move(id, layout),
179
- arrange: () => store.arrange(),
296
+ arrange: (options) => store.arrange(options),
180
297
  };
181
298
  })), 'skillre-sticky-wall client route');
182
299
  if (config.enableAgentTool)
package/lib/layout.d.ts CHANGED
@@ -20,7 +20,7 @@
20
20
  * Both halves import this module, so the geometry never drifts between the
21
21
  * value the Host persists and the value the Client previews.
22
22
  */
23
- import { type CentreReserve, type Note, type NoteLayout, type NoteWidth } from './types.js';
23
+ import { type CentreReserve, type Note, type NoteLayout, type NoteWidth, type ReserveRect } from './types.js';
24
24
  /** Clamp one layout into the declared world bounds. */
25
25
  export declare function clampLayout(layout: NoteLayout): NoteLayout;
26
26
  /** True when two layouts describe the same position (rounded comparison). */
@@ -145,7 +145,21 @@ export declare function normalizeWidth(raw: unknown): NoteWidth;
145
145
  * capped well inside the world bounds so the packer can never be asked to keep
146
146
  * a middle clear that leaves no paper for the cards.
147
147
  */
148
- export declare function normalizeReserve(raw: CentreReserve): CentreReserve;
148
+ /**
149
+ * Clamp a reserve into something the packer can actually honour.
150
+ *
151
+ * The Client sends a reserve positioned where the centrepiece currently sits in
152
+ * world space, so it can arrive with huge coordinates (a deeply zoomed-out wall)
153
+ * or as garbage. Both extremes are refused here: a non-finite coordinate becomes
154
+ * the origin, and the half-extents are capped well inside the world bounds so the
155
+ * packer can never be asked to keep a middle clear that leaves no paper for the
156
+ * cards.
157
+ *
158
+ * The position is clamped to the world bounds rather than to zero: a panned wall
159
+ * legitimately puts the field far from the origin, and snapping it back to the
160
+ * origin would reintroduce the very bug this position exists to fix.
161
+ */
162
+ export declare function normalizeReserve(raw: CentreReserve): ReserveRect;
149
163
  /**
150
164
  * The nearest free spot for one new card, in world coordinates.
151
165
  *
@@ -156,11 +170,19 @@ export declare function normalizeReserve(raw: CentreReserve): CentreReserve;
156
170
  * the user could not see it, which reads exactly like the capture silently
157
171
  * failing.
158
172
  *
159
- * This searches outward from the middle instead: the spiral is walked from just
173
+ * This searches outward from the field instead: the spiral is walked from just
160
174
  * outside the centrepiece's reserve, and the first candidate that clears every
161
175
  * existing card (plus a gap) and stays out of the reserve is the answer. The
162
- * result is therefore the gap nearest the centre of the wall, which is both
163
- * where the user is looking and where the wall has room.
176
+ * result is therefore the gap nearest the place the user is actually looking at,
177
+ * which is where the wall has room.
178
+ *
179
+ * The spiral orbits the RESERVE, not the world origin. That distinction is the
180
+ * fix for a note appearing behind the capture field: the field is a screen-space
181
+ * overlay, so on a panned wall it covers a patch of world that is nowhere near
182
+ * the origin. Orbiting the origin placed the card beside a point the user could
183
+ * not see, and the reveal then centred that point — with the field drawn on top
184
+ * of it. Orbiting the reserve puts the card next to the field, which is both
185
+ * visible and the only placement that can never be hidden by it.
164
186
  *
165
187
  * Deterministic for the same inputs, so two windows creating at once cannot
166
188
  * disagree about the free spot for the same wall.
package/lib/layout.js CHANGED
@@ -245,8 +245,7 @@ export function rotatedExtent(width, height, rotate) {
245
245
  * cards in from the sides.
246
246
  */
247
247
  export function intersectsReserve(box, reserve = CENTRE_RESERVE) {
248
- const clear = clearsReserve(box, reserve);
249
- return !clear;
248
+ return !clearsReserve(box, normalizeReserve(reserve));
250
249
  }
251
250
  /**
252
251
  * Tolerance for the reserve test, in world pixels.
@@ -258,11 +257,20 @@ export function intersectsReserve(box, reserve = CENTRE_RESERVE) {
258
257
  * far below anything visible and well above the rounding error.
259
258
  */
260
259
  const RESERVE_EPSILON = 0.05;
260
+ /**
261
+ * Whether a footprint stays out of the clear rectangle.
262
+ *
263
+ * The rectangle has a POSITION as well as a size. The centrepiece is a
264
+ * screen-space overlay, so the world patch it covers moves as the camera pans
265
+ * and zooms; a reserve that only knew its half-extents therefore described the
266
+ * world origin, and a card captured from a panned wall was placed clear of the
267
+ * wrong place — which is exactly how a fresh card ended up behind the field.
268
+ */
261
269
  function clearsReserve(box, reserve) {
262
- return !(box.x < reserve.halfWidth - RESERVE_EPSILON &&
263
- box.x + box.width > -reserve.halfWidth + RESERVE_EPSILON &&
264
- box.y < reserve.halfHeight - RESERVE_EPSILON &&
265
- box.y + box.height > -reserve.halfHeight + RESERVE_EPSILON);
270
+ return !(box.x < reserve.x + reserve.halfWidth - RESERVE_EPSILON &&
271
+ box.x + box.width > reserve.x - reserve.halfWidth + RESERVE_EPSILON &&
272
+ box.y < reserve.y + reserve.halfHeight - RESERVE_EPSILON &&
273
+ box.y + box.height > reserve.y - reserve.halfHeight + RESERVE_EPSILON);
266
274
  }
267
275
  /** Cell coordinate of one world value. */
268
276
  function cellOf(value) {
@@ -432,7 +440,20 @@ export function arrangeLayouts(notes, options = {}) {
432
440
  const extent = rotatedExtent(cardWidth, cardHeight, rotate);
433
441
  return { note, width, cardWidth, cardHeight, rotate, extent };
434
442
  });
435
- const reserve = normalizeReserve(options.centreReserve ?? CENTRE_RESERVE);
443
+ // The contour is anchored on the ORIGIN, deliberately, even when the caller
444
+ // sends a positioned reserve.
445
+ //
446
+ // Tidy ends by centring the finished wall's bounding box on the origin, and the
447
+ // Client then refits the camera so that box fills the viewport — which puts the
448
+ // centrepiece back over the origin. So the origin is where the field is going to
449
+ // be, not where it happens to be at the instant tidy was pressed. Honouring a
450
+ // transient camera position here would pack the wall around a point the refit is
451
+ // about to move away from. The SIZE is still honoured, because that is the part
452
+ // that does not change.
453
+ //
454
+ // `findFreeLayout` is the opposite case: it places one card on the CURRENT view,
455
+ // with no refit to follow, so it orbits the reserve's real position.
456
+ const reserve = { ...normalizeReserve(options.centreReserve ?? CENTRE_RESERVE), x: 0, y: 0 };
436
457
  // Largest first: the classic first-fit-decreasing heuristic. Big cards claim
437
458
  // the inner frames where there is less room to waste, and small cards fill the
438
459
  // gaps they leave. Ties break on id so the result stays deterministic across
@@ -647,6 +668,20 @@ export function normalizeWidth(raw) {
647
668
  * capped well inside the world bounds so the packer can never be asked to keep
648
669
  * a middle clear that leaves no paper for the cards.
649
670
  */
671
+ /**
672
+ * Clamp a reserve into something the packer can actually honour.
673
+ *
674
+ * The Client sends a reserve positioned where the centrepiece currently sits in
675
+ * world space, so it can arrive with huge coordinates (a deeply zoomed-out wall)
676
+ * or as garbage. Both extremes are refused here: a non-finite coordinate becomes
677
+ * the origin, and the half-extents are capped well inside the world bounds so the
678
+ * packer can never be asked to keep a middle clear that leaves no paper for the
679
+ * cards.
680
+ *
681
+ * The position is clamped to the world bounds rather than to zero: a panned wall
682
+ * legitimately puts the field far from the origin, and snapping it back to the
683
+ * origin would reintroduce the very bug this position exists to fix.
684
+ */
650
685
  export function normalizeReserve(raw) {
651
686
  const cap = LAYOUT_LIMITS.coord / 4;
652
687
  const clampHalf = (value) => {
@@ -655,7 +690,18 @@ export function normalizeReserve(raw) {
655
690
  return 0;
656
691
  return Math.min(cap, number);
657
692
  };
658
- return { halfWidth: clampHalf(raw?.halfWidth), halfHeight: clampHalf(raw?.halfHeight) };
693
+ const clampCoord = (value) => {
694
+ const number = Number(value);
695
+ if (!Number.isFinite(number))
696
+ return 0;
697
+ return Math.min(LAYOUT_LIMITS.coord, Math.max(-LAYOUT_LIMITS.coord, number));
698
+ };
699
+ return {
700
+ x: clampCoord(raw?.x ?? 0),
701
+ y: clampCoord(raw?.y ?? 0),
702
+ halfWidth: clampHalf(raw?.halfWidth),
703
+ halfHeight: clampHalf(raw?.halfHeight),
704
+ };
659
705
  }
660
706
  /**
661
707
  * The nearest free spot for one new card, in world coordinates.
@@ -667,11 +713,19 @@ export function normalizeReserve(raw) {
667
713
  * the user could not see it, which reads exactly like the capture silently
668
714
  * failing.
669
715
  *
670
- * This searches outward from the middle instead: the spiral is walked from just
716
+ * This searches outward from the field instead: the spiral is walked from just
671
717
  * outside the centrepiece's reserve, and the first candidate that clears every
672
718
  * existing card (plus a gap) and stays out of the reserve is the answer. The
673
- * result is therefore the gap nearest the centre of the wall, which is both
674
- * where the user is looking and where the wall has room.
719
+ * result is therefore the gap nearest the place the user is actually looking at,
720
+ * which is where the wall has room.
721
+ *
722
+ * The spiral orbits the RESERVE, not the world origin. That distinction is the
723
+ * fix for a note appearing behind the capture field: the field is a screen-space
724
+ * overlay, so on a panned wall it covers a patch of world that is nowhere near
725
+ * the origin. Orbiting the origin placed the card beside a point the user could
726
+ * not see, and the reveal then centred that point — with the field drawn on top
727
+ * of it. Orbiting the reserve puts the card next to the field, which is both
728
+ * visible and the only placement that can never be hidden by it.
675
729
  *
676
730
  * Deterministic for the same inputs, so two windows creating at once cannot
677
731
  * disagree about the free spot for the same wall.
@@ -702,7 +756,8 @@ export function findFreeLayout(note, existing, options = {}) {
702
756
  // Start just outside the reserve so the first candidate is the closest legal
703
757
  // ring, then walk the same golden-angle spiral the tidy pass uses. A step near
704
758
  // the card's own size keeps the search local: the answer is the first gap, not
705
- // a far-away hole.
759
+ // a far-away hole. The whole spiral is offset by the reserve's centre, because
760
+ // the field it protects is wherever the camera has put it.
706
761
  const step = Math.max(64, Math.sqrt(extent.width * extent.height) * 0.92);
707
762
  const startRadius = Math.hypot(reserve.halfWidth, reserve.halfHeight);
708
763
  const startIndex = (startRadius / step) ** 2;
@@ -711,8 +766,8 @@ export function findFreeLayout(note, existing, options = {}) {
711
766
  const radius = step * Math.sqrt(index);
712
767
  const theta = index * GOLDEN_ANGLE;
713
768
  const candidate = {
714
- x: Math.cos(theta) * radius - extent.width / 2,
715
- y: Math.sin(theta) * radius - extent.height / 2,
769
+ x: reserve.x + Math.cos(theta) * radius - extent.width / 2,
770
+ y: reserve.y + Math.sin(theta) * radius - extent.height / 2,
716
771
  width: extent.width,
717
772
  height: extent.height,
718
773
  };
@@ -731,8 +786,8 @@ export function findFreeLayout(note, existing, options = {}) {
731
786
  // than a real path: place just outside the reserve on the first ring.
732
787
  const fallbackRadius = startRadius + Math.max(extent.width, extent.height);
733
788
  return clampLayout({
734
- x: -cardWidth / 2,
735
- y: -fallbackRadius - cardHeight / 2,
789
+ x: reserve.x - cardWidth / 2,
790
+ y: reserve.y + fallbackRadius - cardHeight / 2,
736
791
  rotate,
737
792
  width,
738
793
  });
@@ -772,28 +827,30 @@ export function noteBox(note, index) {
772
827
  * collisions needs the whole ordered list, not just the first answer.
773
828
  */
774
829
  export function escapesFromReserve(note, layout, reserve = CENTRE_RESERVE) {
830
+ const rect = normalizeReserve(reserve);
775
831
  const box = footprintOf(note, layout);
776
832
  const moves = [
777
- { dx: -reserve.halfWidth - (box.x + box.width), dy: 0 },
778
- { dx: reserve.halfWidth - box.x, dy: 0 },
779
- { dx: 0, dy: -reserve.halfHeight - (box.y + box.height) },
780
- { dx: 0, dy: reserve.halfHeight - box.y },
833
+ { dx: rect.x - rect.halfWidth - (box.x + box.width), dy: 0 },
834
+ { dx: rect.x + rect.halfWidth - box.x, dy: 0 },
835
+ { dx: 0, dy: rect.y - rect.halfHeight - (box.y + box.height) },
836
+ { dx: 0, dy: rect.y + rect.halfHeight - box.y },
781
837
  ];
782
838
  return moves
783
839
  .sort((left, right) => (Math.abs(left.dx) + Math.abs(left.dy)) - (Math.abs(right.dx) + Math.abs(right.dy)))
784
840
  .map((move) => clampLayout({ ...layout, x: layout.x + move.dx, y: layout.y + move.dy }));
785
841
  }
786
842
  export function pushOutOfReserve(note, layout, reserve = CENTRE_RESERVE) {
843
+ const rect = normalizeReserve(reserve);
787
844
  const box = footprintOf(note, layout);
788
- if (!intersectsReserve(box, reserve))
845
+ if (clearsReserve(box, rect))
789
846
  return layout;
790
847
  // Four ways out, one per edge; the shortest wins so the card slides to the
791
848
  // nearest side instead of jumping around the rectangle.
792
849
  const moves = [
793
- { dx: -reserve.halfWidth - (box.x + box.width), dy: 0 },
794
- { dx: reserve.halfWidth - box.x, dy: 0 },
795
- { dx: 0, dy: -reserve.halfHeight - (box.y + box.height) },
796
- { dx: 0, dy: reserve.halfHeight - box.y },
850
+ { dx: rect.x - rect.halfWidth - (box.x + box.width), dy: 0 },
851
+ { dx: rect.x + rect.halfWidth - box.x, dy: 0 },
852
+ { dx: 0, dy: rect.y - rect.halfHeight - (box.y + box.height) },
853
+ { dx: 0, dy: rect.y + rect.halfHeight - box.y },
797
854
  ];
798
855
  let best = moves[0];
799
856
  for (const move of moves) {
@@ -0,0 +1,53 @@
1
+ /**
2
+ * One-time migration from the 0.7.x storage domain to real `.md` files.
3
+ *
4
+ * The old build kept a wall in a JSON storage domain. 0.8.0 stores one file per
5
+ * note instead, so an existing user's wall has to be carried across exactly once,
6
+ * without losing a note and without ever leaving a half-migrated directory that
7
+ * the next start would mistake for a finished one.
8
+ *
9
+ * The whole design follows from one requirement: **the notes directory must
10
+ * never be observable in a partial state.** So the notes are written into a
11
+ * sibling staging directory and published with a single `rename`, which is
12
+ * atomic within one parent directory. A crash before the rename leaves the legacy
13
+ * wall untouched and the staging directory removable; a crash after it leaves a
14
+ * complete wall that the marker then declares migrated.
15
+ *
16
+ * Nothing here is on the hot path, and nothing here runs when the directory
17
+ * already holds notes: a user who has been on 0.8.0 for months must not have a
18
+ * stale legacy domain re-imported over edits they have made since.
19
+ */
20
+ import { type Note } from './types.js';
21
+ /** What one migration attempt did, and why it did nothing when it did nothing. */
22
+ export interface MigrateResult {
23
+ /** True only when this call published the notes directory. */
24
+ migrated: boolean;
25
+ /**
26
+ * Stable outcome: `migrated`, `already-present`, `no-legacy`, or `failed`.
27
+ *
28
+ * `already-present` is the normal steady state, not an error — it is what a
29
+ * second start reports after a successful migration.
30
+ */
31
+ reason: string;
32
+ /** Notes carried across, set only when `migrated` is true. */
33
+ count?: number;
34
+ /** Human-readable cause, set only when `reason` is `failed`. */
35
+ error?: string;
36
+ }
37
+ /** Everything the migration needs; `now` is injectable for a deterministic marker. */
38
+ export interface MigrateOptions {
39
+ /** Destination directory, `<DSH_HOME>/sticky-notes`. */
40
+ notesDir: string;
41
+ /** Drains the legacy storage domain; resolves to every note it held. */
42
+ readLegacy: () => Promise<Note[]>;
43
+ /** Clock for the marker's `at` field. */
44
+ now?: (() => Date) | undefined;
45
+ }
46
+ /**
47
+ * Move the legacy notes into `notesDir`, or explain why there was nothing to do.
48
+ *
49
+ * Never throws for an expected outcome: a failed migration is reported as
50
+ * `{ migrated: false, reason: 'failed' }` with the notes directory left absent,
51
+ * so the next start retries with the legacy wall still intact.
52
+ */
53
+ export declare function migrateNotes(options: MigrateOptions): Promise<MigrateResult>;