shapewall 0.2.3 → 0.3.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 (110) hide show
  1. package/CHANGELOG.md +48 -0
  2. package/README.md +35 -1
  3. package/dist/agent/package-lock.json +2 -2
  4. package/dist/client/assets/BoardChat-CupOxioV.js +27 -0
  5. package/dist/client/assets/{BuzzDialog-CZdwIQLF.js → BuzzDialog-Ds7Thpfe.js} +1 -1
  6. package/dist/client/assets/ChecksPanel-BqrS02Ih.js +1 -0
  7. package/dist/client/assets/History-CQG3NQOC.js +1 -0
  8. package/dist/client/assets/{LocalSettings-CvlVtNY_.js → LocalSettings-CSNMhNyV.js} +1 -1
  9. package/dist/client/assets/{Management-DOJkFY_o.js → Management-CJVNAqAW.js} +1 -1
  10. package/dist/client/assets/QuickConnect-B-4pUgXH.js +1 -0
  11. package/dist/client/assets/{ShareDialog-CdVAreaw.js → ShareDialog-BouvNraR.js} +2 -2
  12. package/dist/client/assets/{app-update-dialog-Dox9-LWv.js → app-update-dialog-rhaw0MRk.js} +1 -1
  13. package/dist/client/assets/{circle-x-BmT6vHKl.js → circle-x-PRxj7kPi.js} +1 -1
  14. package/dist/client/assets/index-CXtuJi1K.css +2 -0
  15. package/dist/client/assets/index-DKOCIQiq.js +37 -0
  16. package/dist/client/assets/{refresh-cw-ugt3cWKH.js → refresh-cw-aeOBDuGQ.js} +1 -1
  17. package/dist/client/assets/{square-_KG6tM5A.js → shield-check-DuPBJ6H_.js} +1 -1
  18. package/dist/client/assets/ui-Cg4TTrec.js +41 -0
  19. package/dist/client/build-info.json +1 -1
  20. package/dist/client/index.html +3 -3
  21. package/dist/client/sw.js +2 -2
  22. package/dist/console/assets/LocalAccountsApp-DOKZI6Lt.js +1 -0
  23. package/dist/console/assets/LocalConsole-DXzldLW9.js +1 -0
  24. package/dist/console/assets/app-update-dialog-CrqIMEwN.js +1 -0
  25. package/dist/console/assets/console-76WovHlh.js +55 -0
  26. package/dist/console/assets/console-Fp4k9iyx.css +2 -0
  27. package/dist/console/build-info.json +1 -1
  28. package/dist/console/console.html +2 -2
  29. package/docs/agent-hardening.md +19 -0
  30. package/docs/agent-workflow.md +33 -0
  31. package/docs/agents.md +112 -0
  32. package/docs/config.md +41 -0
  33. package/docs/deployment.md +3 -0
  34. package/docs/design-system.md +13 -5
  35. package/docs/hosted.md +10 -0
  36. package/docs/journeys.md +13 -1
  37. package/docs/pull-requests.md +192 -0
  38. package/package.json +2 -1
  39. package/src/agent/backends/acp.js +35 -6
  40. package/src/agent/batch-fixes.js +45 -0
  41. package/src/agent/batch-queue.js +204 -0
  42. package/src/agent/branch-mode.js +753 -0
  43. package/src/agent/config.js +6 -0
  44. package/src/agent/fix-prompt.js +5 -0
  45. package/src/agent/manage.js +1 -1
  46. package/src/agent/routes.js +901 -186
  47. package/src/agent/run.js +8 -1
  48. package/src/agent/settings-events.js +103 -0
  49. package/src/agent/settings-routes.js +92 -2
  50. package/src/agent/starter/worktree.js +254 -25
  51. package/src/agent/threads.js +2 -7
  52. package/src/agent/tools.js +51 -0
  53. package/src/agent/user-settings.js +33 -2
  54. package/src/ci/capture.js +103 -0
  55. package/src/ci/compare.js +267 -0
  56. package/src/ci/github.js +307 -0
  57. package/src/ci/images.js +76 -0
  58. package/src/ci/settings.js +211 -0
  59. package/src/ci/start.js +148 -0
  60. package/src/ci/summary.js +262 -0
  61. package/src/ci/workflow.js +238 -0
  62. package/src/cli/args.js +24 -1
  63. package/src/cli/ci.js +229 -0
  64. package/src/cli/help.js +23 -1
  65. package/src/cli/init.js +33 -1
  66. package/src/cli.js +6 -2
  67. package/src/comment-drawing.js +161 -0
  68. package/src/comment-fields.js +51 -0
  69. package/src/comment-media.js +528 -0
  70. package/src/config.js +7 -0
  71. package/src/doctor.js +23 -0
  72. package/src/export.js +8 -0
  73. package/src/feedback.js +89 -12
  74. package/src/github.js +3 -3
  75. package/src/hosted/admin.js +36 -4
  76. package/src/hosted/app.js +5 -0
  77. package/src/hosted/board-routes.js +63 -7
  78. package/src/hosted/clean-worker.js +22 -4
  79. package/src/hosted/cleaner.js +4 -1
  80. package/src/hosted/comment-files.js +200 -0
  81. package/src/hosted/comments.js +68 -15
  82. package/src/hosted/db.js +32 -0
  83. package/src/hosted/guest-view.js +9 -0
  84. package/src/hosted/import.js +213 -18
  85. package/src/hosted/operator.js +3 -1
  86. package/src/hosted/projects.js +3 -2
  87. package/src/hosted/push.js +6 -3
  88. package/src/hosted/retention.js +18 -0
  89. package/src/hosted/tenancy.js +1 -0
  90. package/src/hosted/token-api.js +110 -9
  91. package/src/image-sniff.js +11 -0
  92. package/src/mcp.js +48 -3
  93. package/src/remote/remote-mcp.js +2 -2
  94. package/src/remote/remote.js +6 -2
  95. package/src/remote/share.js +77 -7
  96. package/src/server/app.js +18 -1
  97. package/src/store.js +119 -33
  98. package/src/watch.js +4 -0
  99. package/dist/client/assets/BoardChat-C88k4s-W.js +0 -28
  100. package/dist/client/assets/ChecksPanel-B54chcLA.js +0 -1
  101. package/dist/client/assets/History-CVVuuxUK.js +0 -1
  102. package/dist/client/assets/QuickConnect-D40mj4Ry.js +0 -1
  103. package/dist/client/assets/index-CwvFfwU0.js +0 -29
  104. package/dist/client/assets/index-UIYSPHoh.css +0 -2
  105. package/dist/client/assets/ui-BAGBTB_P.js +0 -41
  106. package/dist/console/assets/LocalAccountsApp-4MtW1QlZ.js +0 -1
  107. package/dist/console/assets/LocalConsole-CgKqYa8i.js +0 -1
  108. package/dist/console/assets/app-update-dialog-S2Yyc7Pw.js +0 -1
  109. package/dist/console/assets/console-BPmBRIoz.js +0 -51
  110. package/dist/console/assets/console-DgVrGRMD.css +0 -2
package/src/cli/args.js CHANGED
@@ -59,6 +59,9 @@ const BOOLEAN_FLAGS = new Set([
59
59
  'run',
60
60
  'check',
61
61
  'recapture',
62
+ 'ci',
63
+ 'fail-on-change',
64
+ 'allow-start',
62
65
  ])
63
66
  const REPEATABLE = new Set(['only', 'allowed-host', 'exclude', 'allow-host', 'trusted'])
64
67
  // Flags that take a value but also work alone ("init --sitemap": the base
@@ -73,7 +76,7 @@ export const COMMAND_FLAGS = {
73
76
  'buzz-bridge': ['bridge-config'],
74
77
  settings: ['port', 'open'],
75
78
  auth: AUTH_FLAGS,
76
- init: ['base-url', 'sitemap', 'no-discover', 'force', 'limit', 'group', 'exclude'],
79
+ init: ['base-url', 'sitemap', 'no-discover', 'force', 'limit', 'group', 'exclude', 'ci'],
77
80
  sitemap: ['limit', 'group', 'exclude', 'board', 'dry-run', 'json'],
78
81
  capture: ['board', 'only', 'env', 'json', 'yes', 'check-external'],
79
82
  checks: ['board', 'only', 'env', 'seo', 'no-seo', 'limit', 'source-build', 'json', 'flow-file', 'viewport'],
@@ -165,6 +168,26 @@ export const COMMAND_FLAGS = {
165
168
  ...REMOTE_FLAGS,
166
169
  ],
167
170
  github: ['board', 'json'],
171
+ ci: [
172
+ 'base-url',
173
+ 'head-url',
174
+ 'base-dir',
175
+ 'head-dir',
176
+ 'out',
177
+ 'threshold',
178
+ 'max-pages',
179
+ 'fail-on-change',
180
+ 'url',
181
+ 'allow-start',
182
+ 'checkout',
183
+ 'timeout',
184
+ 'dir',
185
+ 'artifact-url',
186
+ 'repo',
187
+ 'pull',
188
+ 'board',
189
+ 'json',
190
+ ],
168
191
  mcp: ['read-only', 'no-capture', ...REMOTE_FLAGS],
169
192
  notify: ['json', 'to', 'board'],
170
193
  doctor: ['install-browser', 'port', 'agent-acp', 'json', 'no-launch'],
package/src/cli/ci.js ADDED
@@ -0,0 +1,229 @@
1
+ // `shapewall ci`: capture on every pull request (docs/pull-requests.md).
2
+ //
3
+ // ci enabled is it on for this pull request? (writes enabled=true|false to $GITHUB_OUTPUT)
4
+ // ci wait wait until a URL answers (a deploy preview)
5
+ // ci capture capture one side into a folder (a URL, or ci.start with --allow-start)
6
+ // ci capture-compare capture or read both sides, compare, write the result folder
7
+ // ci comment post or update the one pull request comment from a result folder
8
+
9
+ import fs from 'node:fs'
10
+ import path from 'node:path'
11
+ import { CONFIG_FILE, findConfigFile, getBoard, loadConfig } from '../config.js'
12
+ import { CI_DEFAULTS } from '../ci/settings.js'
13
+ import { captureSide, ciPages } from '../ci/capture.js'
14
+ import { compareCaptures } from '../ci/compare.js'
15
+ import { headline } from '../ci/summary.js'
16
+ import { commentFromResult, prContext, skipRequested } from '../ci/github.js'
17
+ import { startRefusal, startSite, waitForUrl } from '../ci/start.js'
18
+
19
+ const ACTIONS = ['enabled', 'wait', 'capture', 'capture-compare', 'comment']
20
+ const isHttp = (value) => typeof value === 'string' && /^https?:\/\//i.test(value)
21
+ // "--base-url ''" from a workflow variable left empty means "not given".
22
+ const given = (value) => (typeof value === 'string' ? value.trim() || null : value === true ? null : (value ?? null))
23
+
24
+ const ciOf = (config) => config?.ci || { ...CI_DEFAULTS, pages: null, viewports: null, ignore: [], start: null }
25
+
26
+ function thresholdFlag(value, config) {
27
+ if (given(value) === null) return ciOf(config).threshold
28
+ const number = Number(value)
29
+ if (!Number.isFinite(number) || number < 0 || number > 1) throw new Error('--threshold: a share of pixels from 0 to 1, such as 0.001')
30
+ return number
31
+ }
32
+
33
+ function maxPagesFlag(value, config) {
34
+ if (given(value) === null) return ciOf(config).maxPages
35
+ const number = Number(value)
36
+ if (!Number.isInteger(number) || number < 1 || number > 500) throw new Error('--max-pages: a whole number from 1 to 500')
37
+ return number
38
+ }
39
+
40
+ function urlFlag(value, name) {
41
+ const url = given(value)
42
+ if (url !== null && !isHttp(url)) throw new Error(`--${name}: an http(s) URL (got ${JSON.stringify(String(value).slice(0, 80))})`)
43
+ return url
44
+ }
45
+
46
+ // Why the comparison is off for this run, or null.
47
+ function offReason(config, env) {
48
+ if (config && ciOf(config).enabled === false) return 'turned off in the config ("ci": { "enabled": false })'
49
+ if (skipRequested(prContext(env).title)) return 'the pull request title has [skip shapewall]'
50
+ return null
51
+ }
52
+
53
+ function setOutput(env, values) {
54
+ if (!env.GITHUB_OUTPUT) return
55
+ try {
56
+ fs.appendFileSync(
57
+ env.GITHUB_OUTPUT,
58
+ Object.entries(values)
59
+ .map(([key, value]) => `${key}=${String(value).replace(/[\r\n]+/g, ' ')}\n`)
60
+ .join(''),
61
+ )
62
+ } catch {
63
+ /* not in a job */
64
+ }
65
+ }
66
+
67
+ function optionalConfig(flags) {
68
+ const file = findConfigFile(flags.config)
69
+ if (!fs.existsSync(file)) return null
70
+ return loadConfig(flags.config)
71
+ }
72
+
73
+ async function enabled(flags, out, env) {
74
+ const config = optionalConfig(flags)
75
+ const reason = config ? offReason(config, env) : `no ${CONFIG_FILE} here (run "shapewall init" first)`
76
+ setOutput(env, { enabled: !reason, reason: reason || '' })
77
+ out(reason ? `Shapewall is off for this pull request: ${reason}.` : 'Shapewall is on for this pull request.')
78
+ if (flags.json) out(JSON.stringify({ enabled: !reason, reason }))
79
+ return 0
80
+ }
81
+
82
+ async function wait(flags, out) {
83
+ const url = urlFlag(flags.url, 'url')
84
+ if (!url) throw new Error('ci wait needs --url URL')
85
+ const seconds = given(flags.timeout) === null ? 600 : Number(flags.timeout)
86
+ if (!Number.isInteger(seconds) || seconds < 1 || seconds > 3600) throw new Error('--timeout: whole seconds from 1 to 3600')
87
+ out(`Waiting for ${url} (up to ${seconds} s) ...`)
88
+ const status = await waitForUrl(url, { timeout: seconds * 1000, interval: 5000 })
89
+ out(`${url} answered (HTTP ${status}).`)
90
+ return 0
91
+ }
92
+
93
+ // One side: --url, or ci.start (--allow-start, in CI only) and its url.
94
+ async function captureOne({ config, board, url, flags, out, env, dir }) {
95
+ const maxPages = maxPagesFlag(flags['max-pages'], config)
96
+ if (url) return captureSide({ config, board, baseUrl: url, dir, maxPages, log: out })
97
+ const start = ciOf(config).start
98
+ const refusal = startRefusal({ allowStart: Boolean(flags['allow-start']), env, start })
99
+ if (refusal) throw new Error(`ci capture: give --url URL, or ${refusal}.`)
100
+ const siteUrl = start.url || board.baseUrl
101
+ if (!/^https?:\/\/(127\.0\.0\.1|localhost|\[::1\])(:\d+)?(\/|$)/i.test(siteUrl))
102
+ throw new Error(`ci.start.url: the local address the serve command listens on (the board's baseUrl ${siteUrl} is not local)`)
103
+ const checkout = path.resolve(given(flags.checkout) || config.dir)
104
+ if (!fs.existsSync(checkout) || !fs.statSync(checkout).isDirectory()) throw new Error(`--checkout: ${checkout} is not a folder`)
105
+ let site = null
106
+ try {
107
+ site = await startSite(start, { cwd: checkout, url: siteUrl, env, log: out })
108
+ } catch (error) {
109
+ // Recorded like a failed capture, so the comment says what went wrong.
110
+ const target = path.resolve(dir)
111
+ fs.rmSync(target, { recursive: true, force: true })
112
+ fs.mkdirSync(target, { recursive: true })
113
+ const pages = ciPages(config, board, { maxPages }).pages.map((page) => ({ id: page.id, title: page.title, path: page.path }))
114
+ const side = { source: siteUrl, board: board.id, pages, error: `ci.start: ${error.message}`.slice(0, 300) }
115
+ fs.writeFileSync(path.join(target, 'side.json'), `${JSON.stringify(side, null, 2)}\n`)
116
+ out(side.error)
117
+ return { ok: false, dir: target, error: side.error }
118
+ }
119
+ try {
120
+ return await captureSide({ config, board, baseUrl: siteUrl, dir, maxPages, log: out })
121
+ } finally {
122
+ await site.stop()
123
+ }
124
+ }
125
+
126
+ async function capture(flags, out, env) {
127
+ const config = loadConfig(flags.config)
128
+ const reason = offReason(config, env)
129
+ if (reason) {
130
+ out(`Shapewall is off for this pull request: ${reason}. Nothing captured.`)
131
+ return 0
132
+ }
133
+ const out_ = given(flags.out)
134
+ if (!out_) throw new Error('ci capture needs --out DIR')
135
+ const board = getBoard(config, flags.board)
136
+ const result = await captureOne({ config, board, url: urlFlag(flags.url, 'url'), flags, out, env, dir: out_ })
137
+ if (flags.json) out(JSON.stringify(result, null, 2))
138
+ else out(result.ok ? `Captured into ${result.dir}` : `Capture failed: ${result.error} (recorded in ${result.dir}/side.json)`)
139
+ return 0
140
+ }
141
+
142
+ async function captureCompare(flags, out, env) {
143
+ const baseDir = given(flags['base-dir'])
144
+ const headDir = given(flags['head-dir'])
145
+ const usesDirs = Boolean(baseDir || headDir)
146
+ const config = usesDirs ? optionalConfig(flags) : loadConfig(flags.config)
147
+ const reason = offReason(config, env)
148
+ if (reason) {
149
+ out(`Shapewall is off for this pull request: ${reason}. Nothing compared.`)
150
+ return 0
151
+ }
152
+ const target = path.resolve(given(flags.out) || 'shapewall-ci')
153
+ const threshold = thresholdFlag(flags.threshold, config)
154
+ const maxPages = maxPagesFlag(flags['max-pages'], config)
155
+ const board = config ? getBoard(config, flags.board) : null
156
+ let base
157
+ let head
158
+ let sources = {}
159
+ if (usesDirs) {
160
+ if (!baseDir || !headDir) throw new Error('capture-compare: give both --base-dir and --head-dir (or --base-url and --head-url)')
161
+ if (given(flags['base-url']) || given(flags['head-url'])) throw new Error('capture-compare: use either folders or URLs, not both')
162
+ for (const [name, dir] of [
163
+ ['--base-dir', baseDir],
164
+ ['--head-dir', headDir],
165
+ ])
166
+ if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory()) throw new Error(`${name}: ${path.resolve(dir)} is not a folder`)
167
+ base = path.resolve(baseDir)
168
+ head = path.resolve(headDir)
169
+ } else {
170
+ const headUrl = urlFlag(flags['head-url'], 'head-url')
171
+ const baseUrl = urlFlag(flags['base-url'], 'base-url') || board.baseUrl
172
+ if (!headUrl)
173
+ throw new Error(
174
+ "capture-compare: give --head-url URL (and --base-url URL, default the config's baseUrl), or --base-dir and --head-dir",
175
+ )
176
+ const work = path.join(target, '.captures')
177
+ out(`Before: ${baseUrl}`)
178
+ const before = await captureSide({ config, board, baseUrl, dir: path.join(work, 'base'), maxPages, log: out })
179
+ out(`After: ${headUrl}`)
180
+ const after = await captureSide({ config, board, baseUrl: headUrl, dir: path.join(work, 'head'), maxPages, log: out })
181
+ base = before.dir
182
+ head = after.dir
183
+ sources = { base: baseUrl, head: headUrl }
184
+ }
185
+ const summary = compareCaptures({ baseDir: base, headDir: head, out: target, threshold, board, maxPages, ...sources })
186
+ if (flags.json) out(JSON.stringify(summary, null, 2))
187
+ else {
188
+ out(headline(summary))
189
+ for (const shot of summary.shots.filter((item) => item.changed))
190
+ out(` ${shot.page} ${shot.viewport}: ${shot.status === 'changed' ? `${(shot.ratio * 100).toFixed(2)}% of pixels` : shot.status}`)
191
+ for (const failure of summary.failures)
192
+ out(` not captured: ${failure.page ? `${failure.page} ${failure.viewport} ` : ''}(${failure.side || 'compare'}) ${failure.error}`)
193
+ out(`Result in ${target} (summary.json, summary.md, images/)`)
194
+ }
195
+ // Never fails the pull request unless asked to.
196
+ return flags['fail-on-change'] && summary.totals.changedShots ? 3 : 0
197
+ }
198
+
199
+ async function comment(flags, out, env, fetchImpl) {
200
+ const config = optionalConfig(flags)
201
+ const reason = offReason(config, env)
202
+ if (reason) {
203
+ out(`Shapewall is off for this pull request: ${reason}. No comment.`)
204
+ return 0
205
+ }
206
+ const dir = path.resolve(given(flags.dir) || 'shapewall-ci')
207
+ const result = await commentFromResult({
208
+ dir,
209
+ config,
210
+ env,
211
+ repo: given(flags.repo),
212
+ pull: given(flags.pull),
213
+ artifactUrl: given(flags['artifact-url']),
214
+ fetchImpl,
215
+ log: out,
216
+ })
217
+ if (flags.json) out(JSON.stringify(result, null, 2))
218
+ return 0
219
+ }
220
+
221
+ export async function ciCommand(positional, flags, out, { env = process.env, fetch: fetchImpl = globalThis.fetch } = {}) {
222
+ const action = positional[0]
223
+ if (!ACTIONS.includes(action)) throw new Error(`ci: use one of ${ACTIONS.join(', ')} ("shapewall ci --help")`)
224
+ if (action === 'enabled') return enabled(flags, out, env)
225
+ if (action === 'wait') return wait(flags, out)
226
+ if (action === 'capture') return capture(flags, out, env)
227
+ if (action === 'capture-compare') return captureCompare(flags, out, env)
228
+ return comment(flags, out, env, fetchImpl)
229
+ }
package/src/cli/help.js CHANGED
@@ -26,7 +26,9 @@ export const SECTIONS = {
26
26
  (alone: <base URL>/sitemap.xml)
27
27
  (with --limit, --group, --exclude as for sitemap)
28
28
  --no-discover do not look for pages: write the home page only
29
- --force overwrite an existing config`,
29
+ --force overwrite an existing config
30
+ --ci write .github/workflows/shapewall.yml (capture on every pull request) beside
31
+ the config; an existing config is kept, --force replaces only the workflow`,
30
32
  sitemap: ` sitemap [URL|FILE] add the pages of a sitemap.xml (or sitemap index) to the config
31
33
  (default: the board's "sitemap" setting)
32
34
  --limit N at most N new pages, the shallowest first (default ${SITEMAP_LIMIT_DEFAULT})
@@ -154,6 +156,26 @@ export const SECTIONS = {
154
156
  github sync link pull requests that name a comment; resolve comments whose PR merged
155
157
  (repo: "github.repo" in the config; token: $SHAPEWALL_GITHUB_TOKEN or $GITHUB_TOKEN,
156
158
  else a signed-in GitHub CLI ("gh auth token"))`,
159
+ ci: ` ci capture-compare capture before and after, compare every page and viewport, write a result
160
+ folder: summary.json, summary.md (the comment), images of changed shots
161
+ --base-url URL before (default: the board's baseUrl) --head-url URL after
162
+ --base-dir DIR or compare two capture folders --head-dir DIR
163
+ --out DIR the result folder (default shapewall-ci)
164
+ --threshold RATIO share of pixels below which a shot is unchanged (default ci.threshold, 0.001)
165
+ --max-pages N compare at most N pages (default ci.maxPages, 50)
166
+ --fail-on-change exit 3 when something changed (default: always 0, never fails the pull request)
167
+ ci capture --out DIR capture one side into a folder, from --url URL, or with --allow-start
168
+ --allow-start run ci.start (install, build, serve; argv arrays, no shell) in --checkout DIR
169
+ and capture its url; only inside a CI job (GITHUB_ACTIONS or CI is "true")
170
+ ci comment post or update the one pull request comment from a result folder
171
+ --dir DIR the result folder (default shapewall-ci)
172
+ --artifact-url URL link to the workflow artifact with the images
173
+ --repo OWNER/NAME | --pull N default: from the pull_request event
174
+ token: $GITHUB_TOKEN; a fork's pull request gets the job summary instead
175
+ ci enabled is it on for this pull request (ci.enabled, [skip shapewall] in the title)?
176
+ writes enabled=true|false to $GITHUB_OUTPUT
177
+ ci wait --url URL wait until a deploy preview answers [--timeout SECONDS (default 600)]
178
+ --board ID | --json (docs/pull-requests.md)`,
157
179
  mcp: ` mcp MCP server on stdio for coding agents
158
180
  --read-only | --no-capture`,
159
181
  notify: ` notify list notification channels, their events and what each still needs [--json]
package/src/cli/init.js CHANGED
@@ -7,6 +7,7 @@ import { writeFileAtomic } from '../store.js'
7
7
  import { addPagesToRaw, defaultSitemapUrl, formatImport, importSitemap, sitemapPages } from '../sitemap.js'
8
8
  import { DISCOVER_DEFAULTS, cutTitle, describeFetchError, discoverPages, pageTitle } from '../discover.js'
9
9
  import { cliCommand } from '../invocation.js'
10
+ import { WORKFLOW_FILE, workflowYaml } from '../ci/workflow.js'
10
11
 
11
12
  const isHttp = (value) => /^https?:\/\//i.test(String(value))
12
13
 
@@ -139,7 +140,9 @@ export async function init(flags, out, { fetch }) {
139
140
  out(`Wrote ${path.relative(process.cwd(), file) || file}`)
140
141
  // Captures, comments and auth files stay out of git.
141
142
  const gitignore = path.join(path.dirname(file), '.gitignore')
142
- const wanted = ['.shapewall/', 'shapewall-export/', '*.auth.json']
143
+ // .shapewall/agent-worktrees/ is inside .shapewall/; named too so it stays
144
+ // ignored if someone narrows the first line (agent branch mode's checkouts).
145
+ const wanted = ['.shapewall/', 'shapewall-export/', '*.auth.json', '.shapewall/agent-worktrees/']
143
146
  const current = fs.existsSync(gitignore) ? fs.readFileSync(gitignore, 'utf8') : ''
144
147
  const missing = wanted.filter((line) => !current.split(/\r?\n/).includes(line))
145
148
  if (missing.length) {
@@ -149,6 +152,35 @@ export async function init(flags, out, { fetch }) {
149
152
  out(initNextHint({ baseUrl, givenBaseUrl, fromSitemap, found, file: path.basename(file) }))
150
153
  }
151
154
 
155
+ // `init --ci`: the pull request workflow, .github/workflows/shapewall.yml
156
+ // beside the config (docs/pull-requests.md). Writes the config first when
157
+ // there is none; an existing config is never touched, and --force only
158
+ // replaces an existing workflow.
159
+ export async function initCi(flags, out, { fetch }) {
160
+ const configFile = path.resolve(flags.config || CONFIG_FILE)
161
+ if (!fs.existsSync(configFile)) await init({ ...flags, force: false }, out, { fetch })
162
+ const file = path.join(path.dirname(configFile), WORKFLOW_FILE)
163
+ const shown = path.relative(process.cwd(), file) || file
164
+ if (fs.existsSync(file) && !flags.force) throw new Error(`${shown} already exists (use --ci --force to replace it)`)
165
+ fs.mkdirSync(path.dirname(file), { recursive: true })
166
+ fs.writeFileSync(file, workflowYaml())
167
+ out(`Wrote ${shown}: on every pull request it captures the pages before and after, and keeps one comment up to date.`)
168
+ let hasStart = false
169
+ try {
170
+ hasStart = Boolean(JSON.parse(fs.readFileSync(configFile, 'utf8'))?.ci?.start)
171
+ } catch {
172
+ hasStart = false
173
+ }
174
+ if (!hasStart)
175
+ out(
176
+ 'Next: either add "ci": { "start": { "install": [...], "build": [...], "serve": [...], "url": "http://127.0.0.1:PORT" } } to the config (build and serve mode), or set SHAPEWALL_PREVIEW_URL in the workflow (preview URL mode). Then commit the workflow.',
177
+ )
178
+ else out('Next: commit the workflow; the next pull request gets a comment.')
179
+ out(
180
+ `Turn it off any time: delete ${WORKFLOW_FILE}, set "ci": { "enabled": false } in the config, or put [skip shapewall] in a pull request title.`,
181
+ )
182
+ }
183
+
152
184
  // The "Next:" line after init: only the steps still left to do. found is
153
185
  // how discovery went ('sitemap', 'links', 'none'), or null without it.
154
186
  export function initNextHint({ baseUrl, givenBaseUrl, fromSitemap, found = null, file = CONFIG_FILE }) {
package/src/cli.js CHANGED
@@ -5,7 +5,7 @@ import { devicesCommand } from './devices-cli.js'
5
5
  import { loadConfig } from './config.js'
6
6
  import { HELP, SECTIONS, VERSION, commandHelp } from './cli/help.js'
7
7
  import { parseArgs } from './cli/args.js'
8
- import { init, sitemap } from './cli/init.js'
8
+ import { init, initCi, sitemap } from './cli/init.js'
9
9
  import { serve } from './cli/serve.js'
10
10
  import { notify } from './cli/notify.js'
11
11
  import { comments } from './cli/comments.js'
@@ -34,7 +34,7 @@ const COMMANDS = {
34
34
  return authCommand(loadConfig(flags.config), positional, flags, out)
35
35
  },
36
36
  init: async ({ flags, out, fetch }) => {
37
- await init(flags, out, { fetch })
37
+ await (flags.ci ? initCi : init)(flags, out, { fetch })
38
38
  return 0
39
39
  },
40
40
  sitemap: async ({ positional, flags, out, fetch }) => {
@@ -83,6 +83,10 @@ const COMMANDS = {
83
83
  const { agentCommand } = await import('./agent/starter/cli.js')
84
84
  return agentCommand(positional, flags, out, err)
85
85
  },
86
+ ci: async ({ positional, flags, out, fetch }) => {
87
+ const { ciCommand } = await import('./cli/ci.js')
88
+ return ciCommand(positional, flags, out, { fetch })
89
+ },
86
90
  mcp: ({ flags, err }) => mcp(flags, err),
87
91
  doctor: ({ flags, out }) => doctor(flags, out),
88
92
  export: ({ flags, out }) => exportCommand(flags, out),
@@ -0,0 +1,161 @@
1
+ // A drawing made on a page as part of a comment or reply: boxes, arrows and
2
+ // pen strokes over the page frame the comment is pinned to. Vector and
3
+ // resolution independent: every point is frame-relative (0 to 1 of the
4
+ // captured frame's width and height), so it draws the same at any zoom and
5
+ // renders to a PNG for agents (src/comment-media.js renderMarkup).
6
+ //
7
+ // Pure, with no imports, so the server (src/store.js), the hosted server
8
+ // (src/hosted/comments.js), the demo's in-browser backend and the board
9
+ // share one set of rules, like the anchor rules in comment-fields.js.
10
+ //
11
+ // Stored shape: { shapes: [{ tool, ink, width, points: [[x, y], ...] }],
12
+ // captureVersion } where captureVersion is the capture it was drawn on (set
13
+ // by the server, never by the client).
14
+
15
+ export const DRAWING_TOOLS = ['box', 'arrow', 'pen']
16
+ // Ink names are token names (client/src/styles.css): the pin colour first.
17
+ export const DRAWING_INKS = ['accent', 'bad', 'warn']
18
+ // What a drawing renders with outside the browser (the default light theme).
19
+ export const INK_RGB = { accent: [15, 118, 110], bad: [185, 28, 28], warn: [161, 74, 7] }
20
+ export const DRAWING_SHAPES_MAX = 40
21
+ export const DRAWING_STROKE_POINTS_MAX = 2000
22
+ // All points of one drawing, after simplification.
23
+ export const DRAWING_POINTS_MAX = 4000
24
+ export const DRAWING_WIDTH_MIN = 1
25
+ export const DRAWING_WIDTH_MAX = 12
26
+ // Pen strokes are simplified to this tolerance (a share of the frame).
27
+ export const SIMPLIFY_TOLERANCE = 0.0008
28
+
29
+ export class DrawingError extends Error {
30
+ constructor(message) {
31
+ super(message)
32
+ this.statusCode = 400
33
+ this.code = 'invalid_drawing'
34
+ }
35
+ }
36
+
37
+ const round = (value) => Math.round(value * 10000) / 10000
38
+
39
+ function cleanPoint(point) {
40
+ if (!Array.isArray(point) || point.length !== 2) throw new DrawingError('A point is two numbers.')
41
+ const [x, y] = point
42
+ if (typeof x !== 'number' || typeof y !== 'number' || !Number.isFinite(x) || !Number.isFinite(y)) {
43
+ throw new DrawingError('A point is two numbers.')
44
+ }
45
+ // A little outside the frame (a fast stroke off the edge) is clamped; far
46
+ // outside is not a drawing Shapewall makes.
47
+ if (x < -0.05 || x > 1.05 || y < -0.05 || y > 1.05) throw new DrawingError('A point must sit on the page (0 to 1).')
48
+ return [round(Math.min(1, Math.max(0, x))), round(Math.min(1, Math.max(0, y)))]
49
+ }
50
+
51
+ function distanceToSegment([px, py], [ax, ay], [bx, by]) {
52
+ const dx = bx - ax
53
+ const dy = by - ay
54
+ const length = dx * dx + dy * dy
55
+ const t = length ? Math.max(0, Math.min(1, ((px - ax) * dx + (py - ay) * dy) / length)) : 0
56
+ const x = ax + t * dx - px
57
+ const y = ay + t * dy - py
58
+ return Math.sqrt(x * x + y * y)
59
+ }
60
+
61
+ // Ramer-Douglas-Peucker, iterative (no recursion depth to blow up).
62
+ export function simplifyStroke(points, tolerance = SIMPLIFY_TOLERANCE) {
63
+ if (points.length <= 2) return points.slice()
64
+ const keep = new Uint8Array(points.length)
65
+ keep[0] = 1
66
+ keep[points.length - 1] = 1
67
+ const stack = [[0, points.length - 1]]
68
+ while (stack.length) {
69
+ const [first, last] = stack.pop()
70
+ let worst = -1
71
+ let index = -1
72
+ for (let i = first + 1; i < last; i += 1) {
73
+ const distance = distanceToSegment(points[i], points[first], points[last])
74
+ if (distance > worst) {
75
+ worst = distance
76
+ index = i
77
+ }
78
+ }
79
+ if (index !== -1 && worst > tolerance) {
80
+ keep[index] = 1
81
+ stack.push([first, index], [index, last])
82
+ }
83
+ }
84
+ const out = points.filter((_, i) => keep[i])
85
+ // Consecutive duplicates (rounding) carry nothing.
86
+ return out.filter((point, i) => i === 0 || point[0] !== out[i - 1][0] || point[1] !== out[i - 1][1])
87
+ }
88
+
89
+ // Checks and cleans a drawing from a client. null or undefined: no drawing.
90
+ // Returns { shapes } (the caller adds captureVersion) or null when it has no
91
+ // shapes. Throws DrawingError.
92
+ export function validateDrawing(drawing) {
93
+ if (drawing === undefined || drawing === null) return null
94
+ if (typeof drawing !== 'object' || Array.isArray(drawing)) throw new DrawingError('A drawing is an object with shapes.')
95
+ const raw = drawing.shapes
96
+ if (!Array.isArray(raw)) throw new DrawingError('A drawing is an object with shapes.')
97
+ if (raw.length > DRAWING_SHAPES_MAX) throw new DrawingError(`A drawing holds at most ${DRAWING_SHAPES_MAX} shapes.`)
98
+ let total = 0
99
+ const shapes = raw.map((shape) => {
100
+ if (!shape || typeof shape !== 'object' || Array.isArray(shape)) throw new DrawingError('A shape is an object.')
101
+ if (!DRAWING_TOOLS.includes(shape.tool)) throw new DrawingError('A shape is a box, an arrow or a pen stroke.')
102
+ const ink = shape.ink === undefined ? DRAWING_INKS[0] : shape.ink
103
+ if (!DRAWING_INKS.includes(ink)) throw new DrawingError(`Ink is one of ${DRAWING_INKS.join(', ')}.`)
104
+ const width = shape.width === undefined ? 3 : shape.width
105
+ if (!Number.isInteger(width) || width < DRAWING_WIDTH_MIN || width > DRAWING_WIDTH_MAX) {
106
+ throw new DrawingError(`A line is ${DRAWING_WIDTH_MIN} to ${DRAWING_WIDTH_MAX} pixels wide.`)
107
+ }
108
+ if (!Array.isArray(shape.points)) throw new DrawingError('A shape has points.')
109
+ const limit = shape.tool === 'pen' ? DRAWING_STROKE_POINTS_MAX : 2
110
+ if (shape.points.length > limit) {
111
+ throw new DrawingError(
112
+ shape.tool === 'pen' ? `A pen stroke has at most ${DRAWING_STROKE_POINTS_MAX} points.` : 'A box or an arrow has two points.',
113
+ )
114
+ }
115
+ let points = shape.points.map(cleanPoint)
116
+ if (shape.tool === 'pen') {
117
+ if (points.length < 2) throw new DrawingError('A pen stroke has at least two points.')
118
+ points = simplifyStroke(points)
119
+ if (points.length < 2) points = [points[0], points[0]]
120
+ } else if (points.length !== 2) throw new DrawingError('A box or an arrow has two points.')
121
+ total += points.length
122
+ if (total > DRAWING_POINTS_MAX) throw new DrawingError(`A drawing holds at most ${DRAWING_POINTS_MAX} points.`)
123
+ return { tool: shape.tool, ink, width, points }
124
+ })
125
+ return shapes.length ? { shapes } : null
126
+ }
127
+
128
+ // A stored drawing as everyone reads it: cleaned again, so a hand-edited
129
+ // file never reaches the board or an agent unchecked. Bad: null.
130
+ export function readDrawing(stored) {
131
+ try {
132
+ const clean = validateDrawing(stored)
133
+ if (!clean) return null
134
+ // The capture version grammar of src/store.js (VERSION_RE).
135
+ const version =
136
+ typeof stored.captureVersion === 'string' && /^\d{8}T\d{9}Z(?:-[a-f0-9]{4})?$/.test(stored.captureVersion)
137
+ ? stored.captureVersion
138
+ : null
139
+ return { ...clean, captureVersion: version }
140
+ } catch {
141
+ return null
142
+ }
143
+ }
144
+
145
+ // The frame-relative box around every shape: { x, y, width, height }.
146
+ export function drawingBounds(drawing) {
147
+ let left = 1
148
+ let top = 1
149
+ let right = 0
150
+ let bottom = 0
151
+ for (const shape of drawing?.shapes || []) {
152
+ for (const [x, y] of shape.points) {
153
+ left = Math.min(left, x)
154
+ top = Math.min(top, y)
155
+ right = Math.max(right, x)
156
+ bottom = Math.max(bottom, y)
157
+ }
158
+ }
159
+ if (right < left || bottom < top) return null
160
+ return { x: left, y: top, width: right - left, height: bottom - top }
161
+ }
@@ -74,3 +74,54 @@ export function cleanFixRef(value) {
74
74
  if (ref.length > FIX_REF_MAX) throw new CommentError(400, 'invalid_fix_ref', `The fix reference is limited to ${FIX_REF_MAX} characters.`)
75
75
  return ref || null
76
76
  }
77
+
78
+ // A comment's agent status: queued (handed to an agent), working, done (the
79
+ // agent thinks it is fixed; a person still resolves) or needs-human (the
80
+ // agent stopped and asked). These are the ones agents and people set (CLI,
81
+ // MCP, the API). Shapewall also stores branch-ready: an agent in branch mode
82
+ // committed its fix on a branch, waiting to be applied to the checkout
83
+ // (src/agent/branch-mode.js). Every reader and validator takes all five.
84
+ export const AGENT_STATUSES = ['queued', 'working', 'done', 'needs-human']
85
+ export const BRANCH_READY = 'branch-ready'
86
+ export const STORED_AGENT_STATUSES = [...AGENT_STATUSES, BRANCH_READY]
87
+
88
+ // Images on comments and replies: the chat's attachment limits
89
+ // (src/agent/threads.js ATTACHMENTS_MAX, ATTACHMENT_BYTES_MAX), checked on
90
+ // the server by src/comment-media.js and in the demo's backend.
91
+ export const COMMENT_IMAGES_MAX = 4
92
+ export const COMMENT_IMAGE_BYTES_MAX = 5 * 1024 * 1024
93
+ export const COMMENT_IMAGE_TYPES = { 'image/png': 'png', 'image/jpeg': 'jpg', 'image/webp': 'webp', 'image/gif': 'gif' }
94
+ // A stored image's file name: 24 hex characters and its type's extension.
95
+ export const COMMENT_FILE_RE = /^[a-f0-9]{24}\.(png|jpg|webp|gif)$/
96
+ const IMAGE_NAME_MAX = 120
97
+
98
+ // An image's display name: one line, no markup characters.
99
+ export const cleanImageName = (value, fallback) =>
100
+ String(value || '')
101
+ // eslint-disable-next-line no-control-regex
102
+ .replace(/[\u0000-\u001f\u007f<>"'`\\/]/g, '')
103
+ .trim()
104
+ .slice(0, IMAGE_NAME_MAX) || fallback
105
+
106
+ // A stored image record as everyone reads it ({ id, file, name, mediaType,
107
+ // bytes, width, height }); anything else (a hand-edited file) is dropped.
108
+ export function readImages(list) {
109
+ if (!Array.isArray(list)) return []
110
+ return list
111
+ .filter((item) => item && typeof item === 'object' && COMMENT_FILE_RE.test(String(item.file || '')))
112
+ .slice(0, COMMENT_IMAGES_MAX)
113
+ .map((item) => {
114
+ const ext = item.file.split('.').pop()
115
+ const mediaType = Object.keys(COMMENT_IMAGE_TYPES).find((type) => COMMENT_IMAGE_TYPES[type] === ext)
116
+ const size = (value) => (Number.isSafeInteger(value) && value > 0 ? value : null)
117
+ return {
118
+ id: item.file.split('.')[0],
119
+ file: item.file,
120
+ name: cleanImageName(item.name, `image.${ext}`),
121
+ mediaType,
122
+ bytes: size(item.bytes),
123
+ width: size(item.width),
124
+ height: size(item.height),
125
+ }
126
+ })
127
+ }