@erclx/canon 5.14.1 → 5.15.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 (54) 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/read-frames/SKILL.md +3 -2
  6. package/claude/skills/record-screencast/REQUIREMENT.md +3 -0
  7. package/claude/skills/record-screencast/SKILL.md +28 -5
  8. package/docs/agents/commands.md +3 -0
  9. package/docs/agents/demo.md +34 -7
  10. package/docs/agents/migrate.md +1 -1
  11. package/docs/agents/sandbox.md +25 -0
  12. package/docs/target/migrations.md +1 -1
  13. package/docs/workflow/ai-workflow.md +2 -3
  14. package/docs/workflow/skill-map.md +1 -1
  15. package/governance/renames.toml +7 -5
  16. package/governance/rules/canon/630-requirements.md +1 -1
  17. package/package.json +5 -2
  18. package/src/canvas/client/app.tsx +85 -0
  19. package/src/canvas/client/main.tsx +62 -0
  20. package/src/canvas/client/pages-panel.tsx +123 -0
  21. package/src/canvas/client/shell.css +319 -0
  22. package/src/canvas/client/state.ts +186 -0
  23. package/src/canvas/client/surface.tsx +213 -0
  24. package/src/canvas/content.ts +326 -0
  25. package/src/canvas/index.html +14 -0
  26. package/src/canvas/server.ts +302 -0
  27. package/src/canvas/tokens.ts +71 -0
  28. package/src/claude/seeds.ts +0 -1
  29. package/src/cli.ts +2 -0
  30. package/src/commands/canvas.ts +325 -0
  31. package/src/commands/claude.ts +9 -14
  32. package/src/commands/demo.ts +6 -6
  33. package/src/commands/sandbox.ts +108 -0
  34. package/src/context/classify/prompts.ts +1 -1
  35. package/src/context/folders.ts +0 -1
  36. package/src/demo/compile.ts +8 -4
  37. package/src/demo/container.ts +1 -1
  38. package/src/gov/renames.ts +3 -2
  39. package/src/help.ts +1 -0
  40. package/src/record-root.ts +1 -0
  41. package/src/sandbox/equivalence.ts +847 -0
  42. package/src/serve/static.ts +25 -11
  43. package/src/surface-root.ts +0 -1
  44. package/standards/architecture.md +1 -1
  45. package/standards/context.md +1 -1
  46. package/standards/design.md +1 -1
  47. package/standards/index.md +0 -1
  48. package/standards/requirements.md +4 -6
  49. package/standards/wireframes.md +2 -2
  50. package/tooling/claude/reference.md +0 -1
  51. package/tooling/claude/seeds/canon/REQUIREMENTS.md +0 -2
  52. package/governance/rules/canon/645-decisions.md +0 -12
  53. package/standards/decisions.md +0 -105
  54. package/tooling/claude/seeds/canon/decisions/index.md +0 -8
@@ -0,0 +1,302 @@
1
+ import { type FSWatcher, mkdirSync, watch } from 'node:fs'
2
+ import { canvasDir, listPages } from '@/canvas/content'
3
+ import { resolveFrameTokens, type TokenOptions } from '@/canvas/tokens'
4
+ import { buildDesignCss } from '@/design/css'
5
+ import {
6
+ bindFirstFree,
7
+ PORT_ATTEMPTS,
8
+ respond,
9
+ SERVE_HOST,
10
+ type ServeRefusal,
11
+ } from '@/serve/static'
12
+
13
+ /** Clear of `canon serve`'s default, so a lesson preview and the canvas both open. */
14
+ export const CANVAS_PORT = 8790
15
+
16
+ /** The URL prefix a frame and the files beside it are served under. */
17
+ export const FRAMES_PREFIX = '/frames/'
18
+
19
+ /**
20
+ * How long a burst of watch events for one file waits before it is sent. One
21
+ * editor save raises several, and each would otherwise reload the frame again.
22
+ */
23
+ const SETTLE_MS = 40
24
+
25
+ export interface CanvasStarted {
26
+ readonly ok: true
27
+ readonly root: string
28
+ readonly content: string
29
+ readonly host: string
30
+ readonly port: number
31
+ readonly url: string
32
+ readonly stop: () => Promise<void>
33
+ }
34
+
35
+ export interface CanvasRefused {
36
+ readonly ok: false
37
+ readonly reason: Extract<ServeRefusal, 'no-port' | 'bind-failed'>
38
+ readonly detail: string
39
+ }
40
+
41
+ export type CanvasOutcome = CanvasStarted | CanvasRefused
42
+
43
+ export interface CanvasOptions {
44
+ readonly port?: number
45
+ /**
46
+ * What answers `/`. The command passes the HTML import of `index.html`, which
47
+ * `Bun.serve` bundles on request, and a test passes a plain response, since
48
+ * the test runner cannot load an HTML module.
49
+ */
50
+ readonly shell: Bun.HTMLBundle | Response
51
+ readonly tokens?: TokenOptions
52
+ }
53
+
54
+ export interface ChangeEvent {
55
+ readonly page: string
56
+ /**
57
+ * The path under the page folder, or empty when the change is to the
58
+ * top-level entry itself, being a page folder added, renamed, or removed.
59
+ * An empty file names no frame, so a reader rereads the page list alone.
60
+ */
61
+ readonly file: string
62
+ }
63
+
64
+ /** Escapes the one sequence that would end the injected element early. */
65
+ function styleElement(css: string): string {
66
+ return `<style data-canvas-tokens>${css.replaceAll('</style', '<\\/style')}</style>`
67
+ }
68
+
69
+ /**
70
+ * Puts the tokens first in the head, so a stylesheet the frame links itself
71
+ * still wins the cascade. A frame with no head gets the element ahead of
72
+ * everything, which a browser hoists into the head it builds.
73
+ */
74
+ export function injectTokens(html: string, css: string): string {
75
+ if (css === '') return html
76
+ const element = styleElement(css)
77
+ const head = html.match(/<head(?:\s[^>]*)?>/i)
78
+ if (head?.index === undefined) return `${element}${html}`
79
+ const at = head.index + head[0].length
80
+ return `${html.slice(0, at)}${element}${html.slice(at)}`
81
+ }
82
+
83
+ /**
84
+ * Whether a request names this server by a loopback name and its own port.
85
+ * The bind keeps other machines out, and this keeps out a page the operator
86
+ * visits whose domain was rebound to 127.0.0.1, which reaches the socket with
87
+ * its own name in the Host header.
88
+ */
89
+ export function isLoopbackHost(host: string | null, port: number): boolean {
90
+ return host === `${SERVE_HOST}:${port}` || host === `localhost:${port}`
91
+ }
92
+
93
+ type Handler = (
94
+ request: Request,
95
+ server: Bun.Server<undefined>,
96
+ ) => Response | Promise<Response>
97
+
98
+ function guarded(handler: Handler): Handler {
99
+ return (request, server) =>
100
+ isLoopbackHost(request.headers.get('host'), server.port ?? 0)
101
+ ? handler(request, server)
102
+ : new Response('Forbidden\n', {
103
+ status: 403,
104
+ headers: { 'content-type': 'text/plain; charset=utf-8' },
105
+ })
106
+ }
107
+
108
+ function json(body: unknown): Response {
109
+ return new Response(JSON.stringify(body), {
110
+ headers: {
111
+ 'content-type': 'application/json; charset=utf-8',
112
+ 'cache-control': 'no-store',
113
+ },
114
+ })
115
+ }
116
+
117
+ async function serveFrame(
118
+ root: string,
119
+ content: string,
120
+ request: Request,
121
+ tokens: TokenOptions,
122
+ ): Promise<Response> {
123
+ const url = new URL(request.url)
124
+ url.pathname = `/${url.pathname.slice(FRAMES_PREFIX.length)}`
125
+ const file = await respond(content, new Request(url))
126
+
127
+ const type = file.headers.get('content-type') ?? ''
128
+ if (file.status !== 200 || !type.startsWith('text/html')) return file
129
+
130
+ const { css } = resolveFrameTokens(root, tokens)
131
+ return new Response(injectTokens(await file.text(), css), {
132
+ headers: { 'content-type': type, 'cache-control': 'no-store' },
133
+ })
134
+ }
135
+
136
+ /**
137
+ * Fans each change under the canvas folder out to every open shell. The first
138
+ * segment names the page and the rest names the file within it, so a
139
+ * top-level entry goes out with an empty file. Only an empty path is skipped.
140
+ */
141
+ class ChangeStream {
142
+ private readonly clients = new Set<ReadableStreamDefaultController<string>>()
143
+ private readonly pending = new Map<string, ReturnType<typeof setTimeout>>()
144
+ private readonly watcher: FSWatcher
145
+
146
+ constructor(content: string) {
147
+ this.watcher = watch(content, { recursive: true }, (_event, filename) => {
148
+ if (filename) this.queue(filename.toString())
149
+ })
150
+ }
151
+
152
+ /**
153
+ * A one-segment path is kept because the recursive watch reports a page
154
+ * folder appearing, going, or being renamed under its bare name with nothing
155
+ * beneath it. A stray file beside the pages goes out the same way, which
156
+ * costs the shell one page-list reread.
157
+ */
158
+ private queue(path: string): void {
159
+ const [page, ...rest] = path.split(/[\\/]/)
160
+ if (page === undefined || page === '') return
161
+ clearTimeout(this.pending.get(path))
162
+ this.pending.set(
163
+ path,
164
+ setTimeout(() => {
165
+ this.pending.delete(path)
166
+ this.send({ page, file: rest.join('/') })
167
+ }, SETTLE_MS),
168
+ )
169
+ }
170
+
171
+ private send(change: ChangeEvent): void {
172
+ const frame = `data: ${JSON.stringify(change)}\n\n`
173
+ for (const client of this.clients) client.enqueue(frame)
174
+ }
175
+
176
+ open(): Response {
177
+ let self: ReadableStreamDefaultController<string> | undefined
178
+ const stream = new ReadableStream<string>({
179
+ start: (controller) => {
180
+ self = controller
181
+ this.clients.add(controller)
182
+ controller.enqueue(': open\n\n')
183
+ },
184
+ cancel: () => {
185
+ if (self) this.clients.delete(self)
186
+ },
187
+ })
188
+ return new Response(stream, {
189
+ headers: {
190
+ 'content-type': 'text/event-stream',
191
+ 'cache-control': 'no-store',
192
+ },
193
+ })
194
+ }
195
+
196
+ close(): void {
197
+ this.watcher.close()
198
+ for (const timer of this.pending.values()) clearTimeout(timer)
199
+ for (const client of this.clients) {
200
+ try {
201
+ client.close()
202
+ } catch {
203
+ /* Already closed by the browser going away. */
204
+ }
205
+ }
206
+ this.clients.clear()
207
+ }
208
+ }
209
+
210
+ export function startCanvas(
211
+ root: string,
212
+ options: CanvasOptions,
213
+ ): CanvasOutcome {
214
+ const content = canvasDir(root)
215
+ /* Created up front, since the change stream has to watch something. */
216
+ mkdirSync(content, { recursive: true })
217
+
218
+ const tokens = options.tokens ?? {}
219
+ /*
220
+ * Fonts embedded, so the chrome renders in its own face on a machine that
221
+ * never installed it rather than in whatever the fallback stack finds.
222
+ */
223
+ const chromeCss = buildDesignCss(undefined, {
224
+ components: false,
225
+ embedFonts: true,
226
+ })
227
+ const changes = new ChangeStream(content)
228
+ const first = options.port ?? CANVAS_PORT
229
+
230
+ let bound: ReturnType<typeof bindFirstFree>
231
+ try {
232
+ bound = bindFirstFree(first, (port) =>
233
+ Bun.serve({
234
+ hostname: SERVE_HOST,
235
+ port,
236
+ development: false,
237
+ /* The change stream stays open for as long as the shell does. */
238
+ idleTimeout: 0,
239
+ routes: {
240
+ /*
241
+ * The shell and the chunks it bundles carry toolkit code and no
242
+ * project content, so they are the one route left unguarded.
243
+ */
244
+ '/': options.shell,
245
+ '/api/pages': guarded(() => {
246
+ const resolved = resolveFrameTokens(root, tokens)
247
+ const { css: _css, ...source } = resolved
248
+ return json({ pages: listPages(root), tokens: source })
249
+ }),
250
+ '/api/chrome.css': guarded(
251
+ () =>
252
+ new Response(chromeCss, {
253
+ headers: {
254
+ 'content-type': 'text/css; charset=utf-8',
255
+ 'cache-control': 'no-store',
256
+ },
257
+ }),
258
+ ),
259
+ '/api/events': guarded(() => changes.open()),
260
+ },
261
+ fetch: guarded((request) => {
262
+ const { pathname } = new URL(request.url)
263
+ if (pathname.startsWith(FRAMES_PREFIX)) {
264
+ return serveFrame(root, content, request, tokens)
265
+ }
266
+ return new Response('Not found\n', { status: 404 })
267
+ }),
268
+ }),
269
+ )
270
+ } catch (error) {
271
+ changes.close()
272
+ const code = (error as NodeJS.ErrnoException).code ?? 'unknown'
273
+ return {
274
+ ok: false,
275
+ reason: 'bind-failed',
276
+ detail: `could not bind ${SERVE_HOST}:${first} (${code})`,
277
+ }
278
+ }
279
+
280
+ if (!bound) {
281
+ changes.close()
282
+ return {
283
+ ok: false,
284
+ reason: 'no-port',
285
+ detail: `no free port between ${first} and ${first + PORT_ATTEMPTS - 1}`,
286
+ }
287
+ }
288
+
289
+ const { server, port } = bound
290
+ return {
291
+ ok: true,
292
+ root,
293
+ content,
294
+ host: SERVE_HOST,
295
+ port,
296
+ url: `http://${SERVE_HOST}:${port}/`,
297
+ stop: async () => {
298
+ changes.close()
299
+ await server.stop(true)
300
+ },
301
+ }
302
+ }
@@ -0,0 +1,71 @@
1
+ import { existsSync, readdirSync, readFileSync } from 'node:fs'
2
+ import { join } from 'node:path'
3
+ import { DESIGN_INSTALL_DIR, DESIGN_PROJECT_SUBDIR } from '@/design/adapter'
4
+ import { buildDesignCss } from '@/design/css'
5
+ import { isOwnCheckout } from '@/project-root'
6
+
7
+ /**
8
+ * The stylesheet injected into every frame, so a frame drawn with
9
+ * `var(--color-*)` shows the project's own values. Parsing a `DESIGN.md` into
10
+ * custom properties is left out, since no such mapping exists, and a frame can
11
+ * always link a stylesheet of its own.
12
+ */
13
+ export type FrameTokens =
14
+ | { readonly source: 'toolkit'; readonly css: string }
15
+ | {
16
+ readonly source: 'installed'
17
+ readonly css: string
18
+ /** Relative to the root, in the order the stylesheet concatenates them. */
19
+ readonly files: readonly string[]
20
+ }
21
+ | { readonly source: 'none'; readonly css: ''; readonly notice: string }
22
+
23
+ export interface TokenOptions {
24
+ /** Overrides the checkout test, which reads this package's own name. */
25
+ readonly isOwnCheckout?: boolean
26
+ }
27
+
28
+ const BASE_FILE = 'base.css'
29
+
30
+ const NONE_NOTICE = `No token stylesheet, so frames render unstyled. Run canon design install to add ${join(DESIGN_INSTALL_DIR, BASE_FILE)}, put overrides under ${join(DESIGN_INSTALL_DIR, DESIGN_PROJECT_SUBDIR)}/, or link a stylesheet from the frame.`
31
+
32
+ /** The installed files in cascade order: the base first, then each override. */
33
+ function installedFiles(root: string): string[] {
34
+ const files: string[] = []
35
+ const base = join(DESIGN_INSTALL_DIR, BASE_FILE)
36
+ if (existsSync(join(root, base))) files.push(base)
37
+
38
+ const projectDir = join(DESIGN_INSTALL_DIR, DESIGN_PROJECT_SUBDIR)
39
+ if (existsSync(join(root, projectDir))) {
40
+ const overrides = readdirSync(join(root, projectDir))
41
+ .filter((name) => name.endsWith('.css'))
42
+ .sort((a, b) => a.localeCompare(b))
43
+ .map((name) => join(projectDir, name))
44
+ files.push(...overrides)
45
+ }
46
+ return files
47
+ }
48
+
49
+ /**
50
+ * The toolkit's own module where the root is this checkout, else the installed
51
+ * base plus its project overrides, else nothing with a notice naming where
52
+ * tokens would come from.
53
+ */
54
+ export function resolveFrameTokens(
55
+ root: string,
56
+ options: TokenOptions = {},
57
+ ): FrameTokens {
58
+ if (options.isOwnCheckout ?? isOwnCheckout(root)) {
59
+ return { source: 'toolkit', css: buildDesignCss() }
60
+ }
61
+
62
+ const files = installedFiles(root)
63
+ if (files.length > 0) {
64
+ const css = files
65
+ .map((file) => `/* ${file} */\n${readFileSync(join(root, file), 'utf8')}`)
66
+ .join('\n')
67
+ return { source: 'installed', css, files }
68
+ }
69
+
70
+ return { source: 'none', css: '', notice: NONE_NOTICE }
71
+ }
@@ -20,7 +20,6 @@ const HOOKS = 'hooks'
20
20
  export const SUBDIRS: readonly string[] = [
21
21
  HOOKS,
22
22
  'context',
23
- 'decisions',
24
23
  'diagrams',
25
24
  'memory',
26
25
  'tasks',
package/src/cli.ts CHANGED
@@ -23,6 +23,7 @@ import { register as transcripts } from '@/commands/transcripts'
23
23
  import { register as tasks } from '@/commands/tasks'
24
24
  import { register as intake } from '@/commands/intake'
25
25
  import { register as teach } from '@/commands/teach'
26
+ import { register as canvas } from '@/commands/canvas'
26
27
  import { register as comments } from '@/commands/comments'
27
28
  import { register as context } from '@/commands/context'
28
29
  import { register as markdown } from '@/commands/markdown'
@@ -84,6 +85,7 @@ transcripts(program)
84
85
  tasks(program)
85
86
  intake(program)
86
87
  teach(program)
88
+ canvas(program)
87
89
  comments(program)
88
90
  context(program)
89
91
  markdown(program)