@erclx/canon 5.14.1 → 5.16.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.
Files changed (77) hide show
  1. package/README.md +3 -2
  2. package/claude/.claude-plugin/plugin.json +1 -1
  3. package/claude/skills/draft-screencast/REQUIREMENT.md +2 -1
  4. package/claude/skills/draft-screencast/SKILL.md +14 -9
  5. package/claude/skills/draft-wiki/SKILL.md +1 -1
  6. package/claude/skills/plan-groundwork/SKILL.md +1 -1
  7. package/claude/skills/read-frames/SKILL.md +3 -2
  8. package/claude/skills/record-screencast/REQUIREMENT.md +3 -0
  9. package/claude/skills/record-screencast/SKILL.md +28 -5
  10. package/claude/skills/search-craft/REQUIREMENT.md +57 -0
  11. package/claude/skills/search-craft/SKILL.md +83 -0
  12. package/docs/agents/canvas.md +36 -0
  13. package/docs/agents/commands.md +3 -0
  14. package/docs/agents/demo.md +34 -7
  15. package/docs/agents/index.md +1 -0
  16. package/docs/agents/migrate.md +1 -1
  17. package/docs/agents/sandbox.md +25 -0
  18. package/docs/target/migrations.md +1 -1
  19. package/docs/workflow/ai-workflow.md +2 -3
  20. package/docs/workflow/skill-map.md +2 -1
  21. package/governance/renames.toml +7 -5
  22. package/governance/rules/canon/630-requirements.md +1 -1
  23. package/package.json +5 -2
  24. package/scripts/lib/sandbox-git.sh +2 -2
  25. package/src/canvas/address.ts +184 -0
  26. package/src/canvas/capture.ts +172 -0
  27. package/src/canvas/client/app.tsx +87 -0
  28. package/src/canvas/client/inspector.tsx +121 -0
  29. package/src/canvas/client/layers.tsx +118 -0
  30. package/src/canvas/client/main.tsx +62 -0
  31. package/src/canvas/client/pages-panel.tsx +157 -0
  32. package/src/canvas/client/shell.css +449 -0
  33. package/src/canvas/client/state.ts +372 -0
  34. package/src/canvas/client/surface.tsx +465 -0
  35. package/src/canvas/content.ts +617 -0
  36. package/src/canvas/index.html +14 -0
  37. package/src/canvas/server.ts +471 -0
  38. package/src/canvas/tokens.ts +71 -0
  39. package/src/claude/cases/misc.ts +5 -0
  40. package/src/claude/seeds.ts +0 -1
  41. package/src/cli.ts +2 -0
  42. package/src/commands/canvas.ts +522 -0
  43. package/src/commands/claude.ts +9 -14
  44. package/src/commands/demo.ts +6 -6
  45. package/src/commands/migrate.ts +1 -1
  46. package/src/commands/sandbox.ts +108 -0
  47. package/src/context/classify/prompts.ts +1 -1
  48. package/src/context/folders.ts +0 -1
  49. package/src/demo/compile.ts +8 -4
  50. package/src/demo/container.ts +1 -1
  51. package/src/gov/renames.ts +3 -2
  52. package/src/help.ts +1 -0
  53. package/src/migrate/rename.ts +5 -4
  54. package/src/record-root.ts +1 -0
  55. package/src/sandbox/equivalence.ts +847 -0
  56. package/src/serve/static.ts +25 -11
  57. package/src/surface-root.ts +0 -1
  58. package/src/teach/browser/compile.ts +44 -0
  59. package/src/teach/browser/dismiss.ts +76 -0
  60. package/src/teach/browser/focus-line.ts +19 -0
  61. package/src/teach/browser/glossary-filter.ts +44 -0
  62. package/src/teach/browser/head.ts +30 -0
  63. package/src/teach/browser/quiz.ts +19 -0
  64. package/src/teach/browser/sidebar.ts +233 -0
  65. package/src/teach/browser/theme.ts +18 -0
  66. package/src/teach/nav.ts +19 -374
  67. package/standards/architecture.md +1 -1
  68. package/standards/context.md +1 -1
  69. package/standards/design.md +1 -1
  70. package/standards/index.md +0 -1
  71. package/standards/requirements.md +4 -6
  72. package/standards/wireframes.md +2 -2
  73. package/tooling/claude/reference.md +0 -1
  74. package/tooling/claude/seeds/canon/REQUIREMENTS.md +0 -2
  75. package/governance/rules/canon/645-decisions.md +0 -12
  76. package/standards/decisions.md +0 -105
  77. package/tooling/claude/seeds/canon/decisions/index.md +0 -8
@@ -0,0 +1,617 @@
1
+ import { createHash } from 'node:crypto'
2
+ import {
3
+ closeSync,
4
+ existsSync,
5
+ mkdirSync,
6
+ openSync,
7
+ readdirSync,
8
+ readFileSync,
9
+ renameSync,
10
+ rmSync,
11
+ statSync,
12
+ unlinkSync,
13
+ writeFileSync,
14
+ } from 'node:fs'
15
+ import { join } from 'node:path'
16
+ import {
17
+ type ElementAddress,
18
+ resolveAddress,
19
+ type SourceElement,
20
+ } from '@/canvas/address'
21
+ import { recordDir } from '@/record-root'
22
+
23
+ /**
24
+ * The content format. A page is a folder under the record root's `canvas/`, a
25
+ * frame is one `.html` file in it, and `layout.json` beside them holds each
26
+ * frame's box. The HTML stays a plain file so an agent edits a frame the way it
27
+ * edits any other file, and the box lives apart from it so moving a frame never
28
+ * rewrites its markup.
29
+ */
30
+ export const CANVAS_FOLDER = 'canvas'
31
+
32
+ export const LAYOUT_FILE = 'layout.json'
33
+
34
+ /** The frame or element the operator pointed at, beside the pages it names. */
35
+ export const SELECTION_FILE = 'selection.json'
36
+
37
+ /** Suffix of the file a write goes through before it replaces its target. */
38
+ export const TEMP_SUFFIX = '.tmp'
39
+
40
+ /** Suffix of the file a writer holds while it reads, merges, and replaces. */
41
+ export const LOCK_SUFFIX = '.lock'
42
+
43
+ /** A lock older than this was left by a writer that died holding it. */
44
+ const LOCK_STALE_MS = 10_000
45
+
46
+ /** How long a writer waits on another's lock before it refuses. */
47
+ const LOCK_WAIT_MS = 2_000
48
+
49
+ const LOCK_POLL_MS = 5
50
+
51
+ const FRAME_EXTENSION = '.html'
52
+
53
+ /** The size a frame takes when nothing states one. */
54
+ export const DEFAULT_FRAME = { width: 1440, height: 900 } as const
55
+
56
+ /** Horizontal space between frames placed in a row. */
57
+ export const FRAME_GAP = 80
58
+
59
+ /**
60
+ * One path segment with no dot leading it, so a name can neither climb out of
61
+ * the canvas folder nor hide as a dotfile the listing skips.
62
+ */
63
+ const NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]*$/
64
+
65
+ export interface Box {
66
+ readonly x: number
67
+ readonly y: number
68
+ readonly width: number
69
+ readonly height: number
70
+ }
71
+
72
+ export interface Frame extends Box {
73
+ readonly name: string
74
+ /** Relative to the page folder. */
75
+ readonly file: string
76
+ /** Whether the layout stated this box, or the reader placed it in a row. */
77
+ readonly placed: boolean
78
+ }
79
+
80
+ export interface Page {
81
+ readonly name: string
82
+ readonly frames: readonly Frame[]
83
+ /** Set when `layout.json` exists and does not parse. Frames still list. */
84
+ readonly layoutIssue?: 'malformed'
85
+ }
86
+
87
+ export type ContentRefusal =
88
+ | 'invalid-name'
89
+ | 'invalid-size'
90
+ | 'exists'
91
+ | 'no-page'
92
+ | 'no-frame'
93
+ | 'invalid-position'
94
+ | 'malformed-layout'
95
+ | 'busy'
96
+ | 'invalid-address'
97
+ | 'address-mismatch'
98
+ | 'stale-address'
99
+
100
+ export interface ContentRefused {
101
+ readonly ok: false
102
+ readonly reason: ContentRefusal
103
+ readonly detail: string
104
+ }
105
+
106
+ export type PageOutcome =
107
+ | { readonly ok: true; readonly page: string }
108
+ | ContentRefused
109
+
110
+ export type FrameOutcome =
111
+ | {
112
+ readonly ok: true
113
+ readonly page: string
114
+ readonly frame: string
115
+ readonly file: string
116
+ readonly box: Box
117
+ }
118
+ | ContentRefused
119
+
120
+ export function canvasDir(root: string): string {
121
+ return recordDir(root, CANVAS_FOLDER)
122
+ }
123
+
124
+ function pagePath(root: string, page: string): string {
125
+ return join(canvasDir(root), page)
126
+ }
127
+
128
+ function refuse(reason: ContentRefusal, detail: string): ContentRefused {
129
+ return { ok: false, reason, detail }
130
+ }
131
+
132
+ function isValidName(name: string): boolean {
133
+ return NAME_PATTERN.test(name) && !name.includes('..')
134
+ }
135
+
136
+ function isDirectory(path: string): boolean {
137
+ return statSync(path, { throwIfNoEntry: false })?.isDirectory() ?? false
138
+ }
139
+
140
+ function isBox(value: unknown): value is Box {
141
+ if (typeof value !== 'object' || value === null) return false
142
+ const box = value as Record<string, unknown>
143
+ return ['x', 'y', 'width', 'height'].every(
144
+ (key) => typeof box[key] === 'number' && Number.isFinite(box[key]),
145
+ )
146
+ }
147
+
148
+ interface LayoutRead {
149
+ readonly boxes: ReadonlyMap<string, Box>
150
+ readonly malformed: boolean
151
+ }
152
+
153
+ /**
154
+ * Reads what a layout states and nothing else. An entry with a box that is not
155
+ * four finite numbers is skipped rather than refused, since one bad entry
156
+ * should cost that frame its position and not the whole page its frames.
157
+ */
158
+ function readLayout(dir: string): LayoutRead {
159
+ const path = join(dir, LAYOUT_FILE)
160
+ if (!existsSync(path)) return { boxes: new Map(), malformed: false }
161
+
162
+ let parsed: unknown
163
+ try {
164
+ parsed = JSON.parse(readFileSync(path, 'utf8'))
165
+ } catch {
166
+ return { boxes: new Map(), malformed: true }
167
+ }
168
+
169
+ const frames =
170
+ typeof parsed === 'object' && parsed !== null
171
+ ? (parsed as { frames?: unknown }).frames
172
+ : undefined
173
+ if (typeof frames !== 'object' || frames === null) {
174
+ return { boxes: new Map(), malformed: true }
175
+ }
176
+
177
+ const boxes = new Map<string, Box>()
178
+ for (const [name, box] of Object.entries(frames)) {
179
+ if (isBox(box)) {
180
+ boxes.set(name, {
181
+ x: box.x,
182
+ y: box.y,
183
+ width: box.width,
184
+ height: box.height,
185
+ })
186
+ }
187
+ }
188
+ return { boxes, malformed: false }
189
+ }
190
+
191
+ function sleep(ms: number): void {
192
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms)
193
+ }
194
+
195
+ /**
196
+ * Holds an exclusive lock file for the length of a read, merge, and write. The
197
+ * server and a CLI verb are two processes, so a synchronous step inside either
198
+ * does not keep them from reading the same layout and each replacing it with
199
+ * its own edit, which loses the other's. A refused call leaves the file as it
200
+ * found it.
201
+ */
202
+ function withLayoutLock(dir: string, run: () => FrameOutcome): FrameOutcome {
203
+ const lock = join(dir, `${LAYOUT_FILE}${LOCK_SUFFIX}`)
204
+ const deadline = Date.now() + LOCK_WAIT_MS
205
+ for (;;) {
206
+ try {
207
+ closeSync(openSync(lock, 'wx'))
208
+ break
209
+ } catch (error) {
210
+ if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error
211
+ const modified = statSync(lock, { throwIfNoEntry: false })?.mtimeMs
212
+ if (modified !== undefined && Date.now() - modified > LOCK_STALE_MS) {
213
+ rmSync(lock, { force: true })
214
+ continue
215
+ }
216
+ if (Date.now() >= deadline) {
217
+ return refuse('busy', `${LAYOUT_FILE} is being written, try again`)
218
+ }
219
+ sleep(LOCK_POLL_MS)
220
+ }
221
+ }
222
+ try {
223
+ return run()
224
+ } finally {
225
+ rmSync(lock, { force: true })
226
+ }
227
+ }
228
+
229
+ /**
230
+ * Replaces the file in one rename, so the shell reading while a CLI verb writes
231
+ * never sees half a layout and reports it as malformed. The caller holds
232
+ * `withLayoutLock`, which is what keeps two writers from losing each other.
233
+ */
234
+ function writeLayout(dir: string, boxes: ReadonlyMap<string, Box>): void {
235
+ const frames = Object.fromEntries(boxes)
236
+ const target = join(dir, LAYOUT_FILE)
237
+ const temp = `${target}.${process.pid}${TEMP_SUFFIX}`
238
+ writeFileSync(temp, `${JSON.stringify({ frames }, null, 2)}\n`)
239
+ renameSync(temp, target)
240
+ }
241
+
242
+ function frameNames(dir: string): string[] {
243
+ return readdirSync(dir)
244
+ .filter((entry) => entry.endsWith(FRAME_EXTENSION))
245
+ .map((entry) => entry.slice(0, -FRAME_EXTENSION.length))
246
+ .filter(isValidName)
247
+ .sort((a, b) => a.localeCompare(b))
248
+ }
249
+
250
+ /** The x a frame starts at when it joins the row after every box given. */
251
+ function nextX(boxes: Iterable<Box>): number {
252
+ let right: number | undefined
253
+ for (const box of boxes) {
254
+ const edge = box.x + box.width
255
+ right = right === undefined ? edge : Math.max(right, edge)
256
+ }
257
+ return right === undefined ? 0 : right + FRAME_GAP
258
+ }
259
+
260
+ export function readPage(root: string, page: string): Page | undefined {
261
+ if (!isValidName(page)) return undefined
262
+ const dir = pagePath(root, page)
263
+ if (!isDirectory(dir)) return undefined
264
+
265
+ const { boxes, malformed } = readLayout(dir)
266
+ const names = frameNames(dir)
267
+
268
+ const placed = names.filter((name) => boxes.has(name))
269
+ const frames: Frame[] = []
270
+ for (const name of placed) {
271
+ const box = boxes.get(name)
272
+ if (box) {
273
+ frames.push({
274
+ name,
275
+ file: `${name}${FRAME_EXTENSION}`,
276
+ ...box,
277
+ placed: true,
278
+ })
279
+ }
280
+ }
281
+
282
+ for (const name of names.filter((candidate) => !boxes.has(candidate))) {
283
+ frames.push({
284
+ name,
285
+ file: `${name}${FRAME_EXTENSION}`,
286
+ x: nextX(frames),
287
+ y: 0,
288
+ ...DEFAULT_FRAME,
289
+ placed: false,
290
+ })
291
+ }
292
+
293
+ frames.sort((a, b) => a.name.localeCompare(b.name))
294
+ return malformed
295
+ ? { name: page, frames, layoutIssue: 'malformed' }
296
+ : { name: page, frames }
297
+ }
298
+
299
+ export function listPages(root: string): Page[] {
300
+ const dir = canvasDir(root)
301
+ if (!isDirectory(dir)) return []
302
+
303
+ return readdirSync(dir)
304
+ .filter(isValidName)
305
+ .filter((name) => isDirectory(join(dir, name)))
306
+ .sort((a, b) => a.localeCompare(b))
307
+ .flatMap((name) => readPage(root, name) ?? [])
308
+ }
309
+
310
+ export function addPage(root: string, page: string): PageOutcome {
311
+ if (!isValidName(page)) {
312
+ return refuse('invalid-name', `${page} is not a valid page name`)
313
+ }
314
+ const dir = pagePath(root, page)
315
+ if (existsSync(dir)) return refuse('exists', `page ${page} already exists`)
316
+
317
+ mkdirSync(dir, { recursive: true })
318
+ return { ok: true, page }
319
+ }
320
+
321
+ export function renamePage(
322
+ root: string,
323
+ from: string,
324
+ to: string,
325
+ ): PageOutcome {
326
+ if (!isValidName(from) || !isValidName(to)) {
327
+ return refuse(
328
+ 'invalid-name',
329
+ `${isValidName(from) ? to : from} is not a valid page name`,
330
+ )
331
+ }
332
+ const source = pagePath(root, from)
333
+ if (!isDirectory(source))
334
+ return refuse('no-page', `page ${from} does not exist`)
335
+ const target = pagePath(root, to)
336
+ if (existsSync(target)) return refuse('exists', `page ${to} already exists`)
337
+
338
+ renameSync(source, target)
339
+ return { ok: true, page: to }
340
+ }
341
+
342
+ function frameScaffold(name: string): string {
343
+ return `<!doctype html>
344
+ <html lang="en">
345
+ <head>
346
+ <meta charset="utf-8" />
347
+ <title>${name}</title>
348
+ </head>
349
+ <body>
350
+ <main>
351
+ <h1>${name}</h1>
352
+ </main>
353
+ </body>
354
+ </html>
355
+ `
356
+ }
357
+
358
+ export interface FrameSize {
359
+ readonly width: number
360
+ readonly height: number
361
+ }
362
+
363
+ export function addFrame(
364
+ root: string,
365
+ page: string,
366
+ frame: string,
367
+ size: FrameSize,
368
+ ): FrameOutcome {
369
+ if (!isValidName(page)) {
370
+ return refuse('invalid-name', `${page} is not a valid page name`)
371
+ }
372
+ if (!isValidName(frame)) {
373
+ return refuse('invalid-name', `${frame} is not a valid frame name`)
374
+ }
375
+ const isPositive = (value: number) => Number.isFinite(value) && value > 0
376
+ if (!isPositive(size.width) || !isPositive(size.height)) {
377
+ return refuse('invalid-size', 'width and height must be positive numbers')
378
+ }
379
+
380
+ const dir = pagePath(root, page)
381
+ if (!isDirectory(dir)) return refuse('no-page', `page ${page} does not exist`)
382
+ const file = `${frame}${FRAME_EXTENSION}`
383
+ if (existsSync(join(dir, file))) {
384
+ return refuse('exists', `frame ${frame} already exists on ${page}`)
385
+ }
386
+
387
+ return withLayoutLock(dir, () => {
388
+ /*
389
+ * Placed against the boxes a reader would draw, unplaced frames included,
390
+ * so a new frame never lands under one the layout has yet to name.
391
+ */
392
+ const current = readPage(root, page)?.frames ?? []
393
+ const { boxes, malformed } = readLayout(dir)
394
+ /* Writing over a layout that does not parse would erase every box in it. */
395
+ if (malformed) {
396
+ return refuse('malformed-layout', `${page}/${LAYOUT_FILE} does not parse`)
397
+ }
398
+ const box: Box = { x: nextX(current), y: 0, ...size }
399
+
400
+ writeFileSync(join(dir, file), frameScaffold(frame))
401
+ writeLayout(dir, new Map([...boxes, [frame, box]]))
402
+ return { ok: true, page, frame, file, box }
403
+ })
404
+ }
405
+
406
+ export interface Position {
407
+ readonly x: number
408
+ readonly y: number
409
+ }
410
+
411
+ /**
412
+ * Moves one frame and keeps its size. A frame the layout never named takes the
413
+ * default size it was already drawn at, so the move does not resize it.
414
+ */
415
+ export function moveFrame(
416
+ root: string,
417
+ page: string,
418
+ frame: string,
419
+ to: Position,
420
+ ): FrameOutcome {
421
+ if (!isValidName(page)) {
422
+ return refuse('invalid-name', `${page} is not a valid page name`)
423
+ }
424
+ if (!isValidName(frame)) {
425
+ return refuse('invalid-name', `${frame} is not a valid frame name`)
426
+ }
427
+ if (!Number.isFinite(to.x) || !Number.isFinite(to.y)) {
428
+ return refuse('invalid-position', 'x and y must be numbers')
429
+ }
430
+
431
+ const dir = pagePath(root, page)
432
+ if (!isDirectory(dir)) return refuse('no-page', `page ${page} does not exist`)
433
+ const file = `${frame}${FRAME_EXTENSION}`
434
+ if (!existsSync(join(dir, file))) {
435
+ return refuse('no-frame', `frame ${frame} does not exist on ${page}`)
436
+ }
437
+
438
+ return withLayoutLock(dir, () => {
439
+ const { boxes, malformed } = readLayout(dir)
440
+ if (malformed) {
441
+ return refuse('malformed-layout', `${page}/${LAYOUT_FILE} does not parse`)
442
+ }
443
+ const size = boxes.get(frame) ?? DEFAULT_FRAME
444
+ const box: Box = {
445
+ x: to.x,
446
+ y: to.y,
447
+ width: size.width,
448
+ height: size.height,
449
+ }
450
+
451
+ writeLayout(dir, new Map([...boxes, [frame, box]]))
452
+ return { ok: true, page, frame, file, box }
453
+ })
454
+ }
455
+
456
+ export interface Selection {
457
+ readonly page: string
458
+ readonly frame: string
459
+ readonly element?: ElementAddress
460
+ }
461
+
462
+ export interface SelectedElement extends SourceElement {
463
+ readonly index: number
464
+ /**
465
+ * Whether the frame file changed since the element was picked. The address
466
+ * is an index, so an edit can shift it onto another element, and the fields
467
+ * here are what was picked rather than what sits at the index now.
468
+ */
469
+ readonly stale: boolean
470
+ }
471
+
472
+ export interface SelectedFrame {
473
+ readonly page: string
474
+ readonly frame: string
475
+ readonly file: string
476
+ readonly box: Box
477
+ readonly element?: SelectedElement
478
+ }
479
+
480
+ export type SelectionOutcome = { readonly ok: true } | ContentRefused
481
+
482
+ interface StoredElement extends SourceElement {
483
+ readonly index: number
484
+ readonly hash: string
485
+ }
486
+
487
+ function selectionPath(root: string): string {
488
+ return join(canvasDir(root), SELECTION_FILE)
489
+ }
490
+
491
+ export function contentHash(html: string | Uint8Array): string {
492
+ return createHash('sha256').update(html).digest('hex')
493
+ }
494
+
495
+ function isAddress(value: ElementAddress): boolean {
496
+ return (
497
+ Number.isInteger(value.index) &&
498
+ Number.isInteger(value.count) &&
499
+ value.index >= 0 &&
500
+ value.index < value.count &&
501
+ typeof value.tag === 'string' &&
502
+ value.tag !== ''
503
+ )
504
+ }
505
+
506
+ /**
507
+ * Records which frame, or which element in it, "this one" means, or clears it.
508
+ * Only a frame on disk can be recorded, and only an element the file holds at
509
+ * the address given, so the file never names something a reader would have to
510
+ * guess about.
511
+ */
512
+ export function writeSelection(
513
+ root: string,
514
+ selection: Selection | undefined,
515
+ ): SelectionOutcome {
516
+ if (selection === undefined) {
517
+ if (existsSync(selectionPath(root))) unlinkSync(selectionPath(root))
518
+ return { ok: true }
519
+ }
520
+
521
+ const { page, frame, element } = selection
522
+ if (!isValidName(page) || !isValidName(frame)) {
523
+ return refuse('invalid-name', `${page}/${frame} is not a valid frame`)
524
+ }
525
+ const onPage = readPage(root, page)
526
+ if (!onPage) return refuse('no-page', `page ${page} does not exist`)
527
+ const found = onPage.frames.find((candidate) => candidate.name === frame)
528
+ if (!found) {
529
+ return refuse('no-frame', `frame ${frame} does not exist on ${page}`)
530
+ }
531
+
532
+ let stored: StoredElement | undefined
533
+ if (element !== undefined) {
534
+ if (!isAddress(element)) {
535
+ return refuse(
536
+ 'invalid-address',
537
+ 'an element address needs a whole index below its count and a tag',
538
+ )
539
+ }
540
+ const bytes = readFileSync(join(pagePath(root, page), found.file))
541
+ const hash = contentHash(bytes)
542
+ const html = bytes.toString('utf8')
543
+ if (element.hash !== undefined && element.hash !== hash) {
544
+ return refuse(
545
+ 'stale-address',
546
+ `${page}/${frame} changed after the pick was made, so pick it again`,
547
+ )
548
+ }
549
+ const check = resolveAddress(html, element)
550
+ if (!check.ok) return refuse(check.reason, check.detail)
551
+ stored = { index: element.index, ...check.element, hash }
552
+ }
553
+
554
+ const target = selectionPath(root)
555
+ const temp = `${target}.${process.pid}${TEMP_SUFFIX}`
556
+ const record = stored ? { page, frame, element: stored } : { page, frame }
557
+ writeFileSync(temp, `${JSON.stringify(record)}\n`)
558
+ renameSync(temp, target)
559
+ return { ok: true }
560
+ }
561
+
562
+ function readStoredElement(value: unknown): StoredElement | undefined {
563
+ if (typeof value !== 'object' || value === null) return undefined
564
+ const { index, tag, classes, text, hash } = value as Record<string, unknown>
565
+ if (
566
+ typeof index !== 'number' ||
567
+ typeof tag !== 'string' ||
568
+ !Array.isArray(classes) ||
569
+ !classes.every((name) => typeof name === 'string') ||
570
+ typeof text !== 'string' ||
571
+ typeof hash !== 'string'
572
+ ) {
573
+ return undefined
574
+ }
575
+ return { index, tag, classes, text, hash }
576
+ }
577
+
578
+ /**
579
+ * The selected frame with its box, or undefined when nothing is selected, the
580
+ * file does not parse, or the frame it names has since been removed, so a
581
+ * reader never gets a stale name back. An element is reported as picked, with
582
+ * `stale` set once the frame file no longer matches what was picked from.
583
+ */
584
+ export function readSelection(root: string): SelectedFrame | undefined {
585
+ const path = selectionPath(root)
586
+ if (!existsSync(path)) return undefined
587
+
588
+ let parsed: unknown
589
+ try {
590
+ parsed = JSON.parse(readFileSync(path, 'utf8'))
591
+ } catch {
592
+ return undefined
593
+ }
594
+ if (typeof parsed !== 'object' || parsed === null) return undefined
595
+ const { page, frame, element } = parsed as Record<string, unknown>
596
+ if (typeof page !== 'string' || typeof frame !== 'string') return undefined
597
+
598
+ const found = readPage(root, page)?.frames.find(
599
+ (candidate) => candidate.name === frame,
600
+ )
601
+ if (!found) return undefined
602
+ const { x, y, width, height } = found
603
+ const selected = {
604
+ page,
605
+ frame,
606
+ file: found.file,
607
+ box: { x, y, width, height },
608
+ }
609
+
610
+ const stored = readStoredElement(element)
611
+ if (!stored) return selected
612
+ const { hash, ...picked } = stored
613
+ const current = contentHash(
614
+ readFileSync(join(pagePath(root, page), found.file)),
615
+ )
616
+ return { ...selected, element: { ...picked, stale: current !== hash } }
617
+ }
@@ -0,0 +1,14 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8" />
5
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
6
+ <title>Canvas</title>
7
+ <link rel="icon" href="data:," />
8
+ <link rel="stylesheet" href="./client/shell.css" />
9
+ </head>
10
+ <body>
11
+ <div id="app"></div>
12
+ <script type="module" src="./client/main.tsx"></script>
13
+ </body>
14
+ </html>