@luci-dev/cli 0.5.8 → 0.7.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/dist/commands/capture.d.ts +1 -1
  2. package/dist/commands/capture.d.ts.map +1 -1
  3. package/dist/commands/capture.js +16 -5
  4. package/dist/commands/capture.js.map +1 -1
  5. package/dist/commands/init.d.ts.map +1 -1
  6. package/dist/commands/init.js +74 -19
  7. package/dist/commands/init.js.map +1 -1
  8. package/dist/commands/intake.d.ts.map +1 -1
  9. package/dist/commands/intake.js +5 -3
  10. package/dist/commands/intake.js.map +1 -1
  11. package/dist/commands/packs.d.ts.map +1 -1
  12. package/dist/commands/packs.js +10 -8
  13. package/dist/commands/packs.js.map +1 -1
  14. package/dist/commands/serve.d.ts.map +1 -1
  15. package/dist/commands/serve.js +38 -8
  16. package/dist/commands/serve.js.map +1 -1
  17. package/dist/commands/skills.d.ts +1 -1
  18. package/dist/commands/skills.d.ts.map +1 -1
  19. package/dist/commands/skills.js +29 -10
  20. package/dist/commands/skills.js.map +1 -1
  21. package/dist/commands/spec.d.ts +4 -0
  22. package/dist/commands/spec.d.ts.map +1 -0
  23. package/dist/commands/spec.js +210 -0
  24. package/dist/commands/spec.js.map +1 -0
  25. package/dist/commands/startUpdate.d.ts +1 -1
  26. package/dist/commands/startUpdate.d.ts.map +1 -1
  27. package/dist/commands/startUpdate.js +18 -7
  28. package/dist/commands/startUpdate.js.map +1 -1
  29. package/dist/commands/toolbar.d.ts.map +1 -1
  30. package/dist/commands/toolbar.js +50 -18
  31. package/dist/commands/toolbar.js.map +1 -1
  32. package/dist/commands/upgrade.d.ts +14 -0
  33. package/dist/commands/upgrade.d.ts.map +1 -0
  34. package/dist/commands/upgrade.js +219 -0
  35. package/dist/commands/upgrade.js.map +1 -0
  36. package/dist/context.d.ts +20 -0
  37. package/dist/context.d.ts.map +1 -1
  38. package/dist/context.js.map +1 -1
  39. package/dist/onboarding.d.ts +5 -1
  40. package/dist/onboarding.d.ts.map +1 -1
  41. package/dist/onboarding.js +35 -7
  42. package/dist/onboarding.js.map +1 -1
  43. package/dist/run.d.ts.map +1 -1
  44. package/dist/run.js +6 -0
  45. package/dist/run.js.map +1 -1
  46. package/dist/serve/bridge.d.ts +19 -4
  47. package/dist/serve/bridge.d.ts.map +1 -1
  48. package/dist/serve/bridge.js +373 -29
  49. package/dist/serve/bridge.js.map +1 -1
  50. package/dist/toolbarSetup.d.ts +32 -6
  51. package/dist/toolbarSetup.d.ts.map +1 -1
  52. package/dist/toolbarSetup.js +187 -35
  53. package/dist/toolbarSetup.js.map +1 -1
  54. package/package.json +6 -6
@@ -4,18 +4,22 @@
4
4
  * .luci/design/, the same files luci-mcp serves to the agent. It also serves the toolbar script.
5
5
  *
6
6
  * Safety: it listens on 127.0.0.1 only; the Host header must name it (no DNS rebinding); browsers
7
- * may call it only from a page on this machine (localhost, 127.0.0.1, [::1], *.localhost); every
7
+ * may call it only from a page on this machine (localhost, 127.0.0.1, [::1], *.localhost) or from
8
+ * Luci's own extension (other extension IDs only with --allow-extension); every
8
9
  * write needs a JSON body and the X-Luci header, which a page can only send after the CORS check.
9
10
  * It reads and writes nothing outside .luci/feedback/ and .luci/design/.
10
11
  */
12
+ import { execFileSync } from 'node:child_process';
13
+ import fs from 'node:fs';
11
14
  import http from 'node:http';
12
15
  import path from 'node:path';
13
16
  import { z } from 'zod';
14
- import { CheckStore, DesignError, DesignStore, FeedbackError, FeedbackStore, findStylesheets, proposeCaptureRule } from '@luci-dev/brain';
15
- import { buildBaseline, checkRunSchema } from '@luci-dev/format/capture';
17
+ import { CheckStore, DesignError, DesignStore, FeedbackError, FeedbackStore, SpecError, SpecStore, ensureLuciIgnore, findStylesheets, getUpdateStatus, installAgentHooks, installedAgentHooks, projectAgents, proposeCaptureRule, readOnSpecConfig, readUserProfile, readUserRole, runCliUpgrade, writeOnSpecConfig, writeUpdatePreferences, writeUserRole } from '@luci-dev/brain';
18
+ import { buildBaseline, checkRunSchema, onSpecConfigSchema, specComponentSchema } from '@luci-dev/format/capture';
16
19
  import { serverResolver } from './resolve.js';
20
+ import { cliVersion } from '../version.js';
17
21
  import { PRODUCT } from '@luci-dev/format';
18
- import { DETAIL_LEVELS, FEEDBACK_INTENTS, FEEDBACK_PRIORITIES, designCheckSchema, feedbackItemSchema, formatFeedbackPrompt, layoutSchema, wireframeSchema } from '@luci-dev/format/feedback';
22
+ import { DETAIL_LEVELS, FEEDBACK_INTENTS, FEEDBACK_PRIORITIES, REVIEWER_ROLES, designCheckSchema, feedbackItemSchema, formatFeedbackPrompt, layoutSchema, wireframeSchema } from '@luci-dev/format/feedback';
19
23
  export const DEFAULT_PORT = 4545;
20
24
  /** The header every write must carry (a page cannot send it without passing the CORS check). */
21
25
  export const BRIDGE_HEADER = 'x-luci';
@@ -33,19 +37,30 @@ export function isLoopbackOrigin(origin) {
33
37
  return false;
34
38
  }
35
39
  }
36
- /** An origin of a browser extension: chrome-extension:, moz-extension:, or safari-web-extension:. */
37
- export function isExtensionOrigin(origin) {
40
+ /**
41
+ * Luci's own extension: its Chrome Web Store ID (Chrome and Edge install it from there). Another
42
+ * extension, or a copy someone built and loaded unpacked (it gets an ID of its own), is answered only
43
+ * when `luci serve --allow-extension <id>` names it.
44
+ */
45
+ export const LUCI_EXTENSION_IDS = ['hjgfoiecmdjankhmifdicejiolnfkfmn'];
46
+ /** An extension ID as browsers write them: Chrome's 32 letters a-p, or Firefox and Safari's UUIDs. */
47
+ export const EXTENSION_ID = /^(?:[a-p]{32}|[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/i;
48
+ /** An origin of one of the allowed browser extensions (chrome-extension:, moz-extension: or safari-web-extension:). */
49
+ export function isExtensionOrigin(origin, allowedIds = LUCI_EXTENSION_IDS) {
38
50
  try {
39
51
  const u = new URL(origin);
40
- return u.protocol === 'chrome-extension:' || u.protocol === 'moz-extension:' || u.protocol === 'safari-web-extension:';
52
+ if (u.protocol !== 'chrome-extension:' && u.protocol !== 'moz-extension:' && u.protocol !== 'safari-web-extension:')
53
+ return false;
54
+ const id = u.hostname.toLowerCase();
55
+ return allowedIds.some(a => a.toLowerCase() === id);
41
56
  }
42
57
  catch {
43
58
  return false;
44
59
  }
45
60
  }
46
- /** An origin allowed to call the bridge: local pages or browser extensions. */
47
- export function isAllowedOrigin(origin) {
48
- return isLoopbackOrigin(origin) || isExtensionOrigin(origin);
61
+ /** An origin allowed to call the bridge: local pages, or Luci's extension (and any extension IDs allowed). */
62
+ export function isAllowedOrigin(origin, allowedIds = LUCI_EXTENSION_IDS) {
63
+ return isLoopbackOrigin(origin) || isExtensionOrigin(origin, allowedIds);
49
64
  }
50
65
  /**
51
66
  * A source path as the project knows it: an absolute path inside the project becomes relative
@@ -65,6 +80,7 @@ const newItemSchema = z.object({
65
80
  layout: layoutSchema.optional(),
66
81
  wireframe: wireframeSchema.optional(),
67
82
  check: designCheckSchema.optional(),
83
+ reviewerRoles: z.array(z.enum(REVIEWER_ROLES)).min(1).optional(),
68
84
  intent: z.enum(FEEDBACK_INTENTS),
69
85
  priority: z.enum(FEEDBACK_PRIORITIES)
70
86
  });
@@ -80,6 +96,42 @@ const resolveSchema = z.object({
80
96
  });
81
97
  const designSchema = z.object({ fileName: z.string().min(1), markdown: z.string().min(1) });
82
98
  const ruleSchema = z.object({ file: z.string().min(1).max(200) });
99
+ const specVerdictsSchema = z.object({
100
+ components: z.array(specComponentSchema).max(500),
101
+ widths: z.array(z.number().int().positive()).min(1).max(4).optional(),
102
+ replace: z.boolean().optional()
103
+ });
104
+ const specExcuseBodySchema = z.object({
105
+ componentId: z.string().min(1).max(1200),
106
+ reason: z.string().trim().min(1).max(2000),
107
+ role: z.enum(REVIEWER_ROLES).optional(),
108
+ property: z.string().max(200).optional()
109
+ });
110
+ const specUpdateRuleBodySchema = z.object({
111
+ componentId: z.string().min(1).max(1200).optional(),
112
+ ruleFile: z.string().min(1).max(1000),
113
+ markdown: z.string().min(1),
114
+ role: z.enum(REVIEWER_ROLES).optional(),
115
+ note: z.string().max(2000).optional()
116
+ });
117
+ const specReviewedBodySchema = z.object({
118
+ ruleFile: z.string().min(1).max(1000),
119
+ role: z.enum(REVIEWER_ROLES).optional(),
120
+ note: z.string().max(2000).optional()
121
+ });
122
+ const specSendBackBodySchema = z.object({
123
+ componentId: z.string().min(1).max(1200),
124
+ note: z.string().max(2000).optional(),
125
+ role: z.enum(REVIEWER_ROLES).optional()
126
+ });
127
+ const updateSettingsBodySchema = z.object({
128
+ check: z.boolean().optional(),
129
+ auto: z.boolean().optional(),
130
+ dismissedVersion: z.string().max(40).nullable().optional()
131
+ });
132
+ const profileBodySchema = z.object({
133
+ role: z.enum(REVIEWER_ROLES)
134
+ });
83
135
  class HttpError extends Error {
84
136
  status;
85
137
  constructor(status, message) {
@@ -87,20 +139,30 @@ class HttpError extends Error {
87
139
  this.status = status;
88
140
  }
89
141
  }
90
- function readBody(req) {
142
+ function readBody(req, res) {
91
143
  return new Promise((resolve, reject) => {
92
144
  const chunks = [];
93
145
  let size = 0;
146
+ let tooLarge = false;
94
147
  req.on('data', (c) => {
148
+ if (tooLarge)
149
+ return;
95
150
  size += c.length;
96
151
  if (size > MAX_BODY_BYTES) {
152
+ tooLarge = true;
153
+ req.pause();
154
+ if (res && !res.headersSent) {
155
+ res.writeHead(413, { 'content-type': 'application/json', 'connection': 'close' });
156
+ res.end(JSON.stringify({ error: 'The request is too large.' }));
157
+ }
97
158
  reject(new HttpError(413, 'The request is too large.'));
98
- req.destroy();
99
159
  return;
100
160
  }
101
161
  chunks.push(c);
102
162
  });
103
163
  req.on('end', () => {
164
+ if (tooLarge)
165
+ return;
104
166
  const text = Buffer.concat(chunks).toString('utf8');
105
167
  try {
106
168
  resolve(text ? JSON.parse(text) : {});
@@ -109,7 +171,10 @@ function readBody(req) {
109
171
  reject(new HttpError(400, 'The body is not valid JSON.'));
110
172
  }
111
173
  });
112
- req.on('error', reject);
174
+ req.on('error', err => {
175
+ if (!tooLarge)
176
+ reject(err);
177
+ });
113
178
  });
114
179
  }
115
180
  const parse = (schema, value) => {
@@ -118,21 +183,93 @@ const parse = (schema, value) => {
118
183
  throw new HttpError(400, z.prettifyError(r.error));
119
184
  return r.data;
120
185
  };
186
+ const SKIP_MTIME_DIRS = new Set(['node_modules', '.git', '.luci', 'dist', 'build', '.next', '.nuxt', '.output', 'coverage']);
187
+ /**
188
+ * Best-effort timestamp of the project's latest change, for Team Feedback staleness checks:
189
+ * uses the latest git commit time in a git repo; otherwise checks a shallow slice of files
190
+ * (capped so `/health` never scans a whole repo).
191
+ */
192
+ function readProjectLastModified(projectDir) {
193
+ if (fs.existsSync(path.join(projectDir, '.git'))) {
194
+ try {
195
+ const out = execFileSync('git', ['log', '-1', '--format=%cI'], {
196
+ cwd: projectDir,
197
+ encoding: 'utf8',
198
+ timeout: 1500,
199
+ stdio: ['ignore', 'pipe', 'ignore']
200
+ }).trim();
201
+ if (out && !Number.isNaN(Date.parse(out)))
202
+ return new Date(out).toISOString();
203
+ }
204
+ catch {
205
+ // empty repo or git unavailable; fall through to cheap shallow scan
206
+ }
207
+ }
208
+ let newest = 0;
209
+ let seen = 0;
210
+ const MAX_ENTRIES = 60;
211
+ const scan = (dir, depth) => {
212
+ if (depth > 2 || seen >= MAX_ENTRIES)
213
+ return;
214
+ let entries;
215
+ try {
216
+ entries = fs.readdirSync(dir, { withFileTypes: true });
217
+ }
218
+ catch {
219
+ return;
220
+ }
221
+ for (const entry of entries) {
222
+ if (seen >= MAX_ENTRIES)
223
+ break;
224
+ if (SKIP_MTIME_DIRS.has(entry.name))
225
+ continue;
226
+ seen++;
227
+ const full = path.join(dir, entry.name);
228
+ try {
229
+ const st = fs.statSync(full);
230
+ if (st.isFile() && st.mtimeMs > newest)
231
+ newest = st.mtimeMs;
232
+ else if (st.isDirectory() && depth < 2 && /^(src|app|pages|components|public|styles)$/i.test(entry.name)) {
233
+ scan(full, depth + 1);
234
+ }
235
+ }
236
+ catch { /* ignore unreadable entries */ }
237
+ }
238
+ };
239
+ scan(projectDir, 0);
240
+ return newest > 0 ? new Date(newest).toISOString() : undefined;
241
+ }
121
242
  export function startBridge(options) {
243
+ // Keep Tailwind v4 / content scanners from watching .luci/design/ and triggering Vite full-reloads on save
244
+ try {
245
+ ensureLuciIgnore(options.projectDir);
246
+ }
247
+ catch { /* read-only or uninitialized */ }
122
248
  const feedback = new FeedbackStore(options.projectDir);
123
249
  const design = new DesignStore(options.projectDir);
124
250
  const checks = new CheckStore(options.projectDir);
251
+ const spec = new SpecStore(options.projectDir);
125
252
  const resolveServer = serverResolver(options.projectDir);
253
+ const extensionIds = [...LUCI_EXTENSION_IDS, ...(options.extensionIds ?? [])];
254
+ const allowed = (o) => isAllowedOrigin(o, extensionIds);
126
255
  let port = options.port ?? DEFAULT_PORT;
256
+ let cachedModified = null;
257
+ const lastModifiedAt = () => {
258
+ const now = Date.now();
259
+ if (!cachedModified || now - cachedModified.at > 10_000) {
260
+ cachedModified = { at: now, value: readProjectLastModified(options.projectDir) };
261
+ }
262
+ return cachedModified.value;
263
+ };
127
264
  const server = http.createServer((req, res) => {
128
265
  const origin = req.headers.origin;
129
266
  const send = (status, body, type = 'application/json; charset=utf-8') => {
130
267
  const headers = { 'content-type': type, 'cache-control': 'no-store', 'x-content-type-options': 'nosniff' };
131
- if (origin && isAllowedOrigin(origin)) {
268
+ if (origin && allowed(origin)) {
132
269
  Object.assign(headers, {
133
270
  'access-control-allow-origin': origin,
134
271
  vary: 'Origin',
135
- 'access-control-allow-methods': 'GET, POST, PATCH, DELETE, OPTIONS',
272
+ 'access-control-allow-methods': 'GET, POST, PUT, PATCH, DELETE, OPTIONS',
136
273
  'access-control-allow-headers': `content-type, ${BRIDGE_HEADER}`,
137
274
  'access-control-allow-private-network': 'true',
138
275
  'access-control-max-age': '600'
@@ -145,8 +282,11 @@ export function startBridge(options) {
145
282
  const host = (req.headers.host ?? '').toLowerCase();
146
283
  if (host !== `127.0.0.1:${port}` && host !== `localhost:${port}`)
147
284
  throw new HttpError(403, 'Unknown host.');
148
- if (origin && !isAllowedOrigin(origin))
149
- throw new HttpError(403, `${PRODUCT.name} only answers pages on this machine or browser extensions.`);
285
+ if (origin && !allowed(origin)) {
286
+ throw new HttpError(403, isExtensionOrigin(origin, [new URL(origin).hostname])
287
+ ? `${PRODUCT.name} only answers its own browser extension. For a build you loaded yourself, start \`${PRODUCT.command} serve --allow-extension ${new URL(origin).hostname}\`.`
288
+ : `${PRODUCT.name} only answers pages on this machine and its own browser extension.`);
289
+ }
150
290
  if (req.method === 'OPTIONS') {
151
291
  send(204, '');
152
292
  return;
@@ -161,7 +301,8 @@ export function startBridge(options) {
161
301
  throw new HttpError(415, 'Send JSON.');
162
302
  }
163
303
  if (req.method === 'GET' && route === '/health') {
164
- send(200, { ok: true, product: PRODUCT.name, version: options.version ?? '', project: options.projectDir, initialized: feedback.available });
304
+ const modified = lastModifiedAt();
305
+ send(200, { ok: true, product: PRODUCT.name, version: options.version ?? '', project: options.projectDir, initialized: feedback.available, ...(modified ? { lastModifiedAt: modified } : {}) });
165
306
  return;
166
307
  }
167
308
  if (req.method === 'GET' && route === '/toolbar.js') {
@@ -173,7 +314,7 @@ export function startBridge(options) {
173
314
  }
174
315
  // Server components' positions (read only: source maps inside the project)
175
316
  if (route === '/resolve' && req.method === 'POST') {
176
- const body = parse(resolveSchema, await readBody(req));
317
+ const body = parse(resolveSchema, await readBody(req, res));
177
318
  send(200, { locations: body.frames.map(f => resolveServer(f)) });
178
319
  return;
179
320
  }
@@ -184,7 +325,7 @@ export function startBridge(options) {
184
325
  return;
185
326
  }
186
327
  if (route === '/feedback' && req.method === 'POST') {
187
- const body = parse(newItemSchema, await readBody(req));
328
+ const body = parse(newItemSchema, await readBody(req, res));
188
329
  const rel = (file) => relativeSource(options.projectDir, file);
189
330
  const item = feedback.add({
190
331
  ...body,
@@ -195,7 +336,7 @@ export function startBridge(options) {
195
336
  return;
196
337
  }
197
338
  if (route === '/feedback/prompt' && req.method === 'POST') {
198
- const body = parse(promptSchema, await readBody(req));
339
+ const body = parse(promptSchema, await readBody(req, res));
199
340
  const open = body.includeSent ? feedback.open() : feedback.list({ status: ['pending'] });
200
341
  const items = body.refs ? open.filter(i => body.refs.includes(i.ref)) : open;
201
342
  if (!items.length) {
@@ -208,12 +349,12 @@ export function startBridge(options) {
208
349
  return;
209
350
  }
210
351
  if (route === '/feedback/clear' && req.method === 'POST') {
211
- send(200, { removed: feedback.clear(parse(clearSchema, await readBody(req)).which) });
352
+ send(200, { removed: feedback.clear(parse(clearSchema, await readBody(req, res)).which) });
212
353
  return;
213
354
  }
214
355
  const one = /^\/feedback\/(P\d+-A\d+)$/.exec(route)?.[1];
215
356
  if (one && req.method === 'PATCH') {
216
- const body = parse(patchSchema, await readBody(req));
357
+ const body = parse(patchSchema, await readBody(req, res));
217
358
  const item = body.action === 'done' ? feedback.markDone(one)
218
359
  : body.action === 'reopen' ? feedback.reopen(one)
219
360
  : feedback.edit(one, { ...(body.comment ? { comment: body.comment } : {}), ...(body.intent ? { intent: body.intent } : {}), ...(body.priority ? { priority: body.priority } : {}) });
@@ -238,7 +379,7 @@ export function startBridge(options) {
238
379
  if (route === '/checks' && req.method === 'POST') {
239
380
  if (!checks.available)
240
381
  throw new HttpError(409, `No ${PRODUCT.projectDir}/ in this project yet: run \`${PRODUCT.command} init\` there.`);
241
- const run = parse(checkRunSchema, await readBody(req));
382
+ const run = parse(checkRunSchema, await readBody(req, res));
242
383
  checks.save(run);
243
384
  const { resolved, updated } = feedback.reconcileWithCheck(run);
244
385
  if (resolved.length) {
@@ -256,29 +397,232 @@ export function startBridge(options) {
256
397
  // One saved file's text (a design check reads its design file); only names in .luci/design/
257
398
  const designFile = /^\/design\/([^/]+)$/.exec(route)?.[1];
258
399
  if (designFile && req.method === 'GET') {
259
- const file = decodeURIComponent(designFile);
400
+ let file;
401
+ try {
402
+ file = decodeURIComponent(designFile);
403
+ }
404
+ catch {
405
+ throw new HttpError(400, `Malformed URI encoding in design file path: ${designFile}`);
406
+ }
260
407
  const markdown = design.read(file);
261
408
  if (markdown === null)
262
409
  throw new HttpError(404, `No design file ${file} in ${PRODUCT.projectDir}/design/.`);
263
410
  send(200, { file, markdown });
264
411
  return;
265
412
  }
413
+ if (designFile && req.method === 'DELETE') {
414
+ let file;
415
+ try {
416
+ file = decodeURIComponent(designFile);
417
+ }
418
+ catch {
419
+ throw new HttpError(400, `Malformed URI encoding in design file path: ${designFile}`);
420
+ }
421
+ const removed = design.remove(file);
422
+ if (!removed)
423
+ throw new HttpError(404, `No design file ${file} in ${PRODUCT.projectDir}/design/.`);
424
+ send(200, { removed: true, file });
425
+ return;
426
+ }
266
427
  // Capture to rule (v0.3.2): a saved component capture becomes a proposed rule (never rules.md itself)
267
428
  if (route === '/rule' && req.method === 'POST') {
268
- const body = parse(ruleSchema, await readBody(req));
429
+ const body = parse(ruleSchema, await readBody(req, res));
269
430
  const rule = proposeCaptureRule(options.projectDir, body.file);
270
431
  send(rule.existed ? 200 : 201, { path: rule.path, existed: rule.existed, rule: rule.proposal.proposed });
271
432
  return;
272
433
  }
273
434
  if (route === '/design' && req.method === 'POST') {
274
- const body = parse(designSchema, await readBody(req));
275
- send(201, design.save(body.fileName, body.markdown));
435
+ const body = parse(designSchema, await readBody(req, res));
436
+ const saved = design.save(body.fileName, body.markdown);
437
+ if (!body.fileName.includes('.collection.')) {
438
+ spec.recordRuleCreated(body.fileName, {
439
+ origin: 'capture',
440
+ role: readUserRole(),
441
+ note: saved.replaced ? 'Replaced from Capture toolbar' : 'Saved from Capture toolbar'
442
+ });
443
+ }
444
+ send(201, saved);
445
+ return;
446
+ }
447
+ // On spec (v0.7): verdicts, human decisions (Excuse, Update rule, Send back, Reviewed), profile & settings
448
+ if (route === '/spec' && req.method === 'GET') {
449
+ const state = spec.readState();
450
+ const rulesMeta = spec.listRulesMeta();
451
+ send(200, { state, rulesMeta, report: spec.formatReport(), settings: readOnSpecConfig(options.projectDir) });
452
+ return;
453
+ }
454
+ if (route === '/spec/verdicts' && req.method === 'POST') {
455
+ const body = parse(specVerdictsSchema, await readBody(req, res));
456
+ const state = spec.saveVerdicts({
457
+ components: body.components,
458
+ ...(body.widths ? { widths: body.widths } : {}),
459
+ ...(body.replace !== undefined ? { replace: body.replace } : {})
460
+ });
461
+ const rulesMeta = spec.listRulesMeta();
462
+ send(200, { state, rulesMeta, report: spec.formatReport(), settings: readOnSpecConfig(options.projectDir) });
463
+ return;
464
+ }
465
+ if (route === '/spec/excuse' && req.method === 'POST') {
466
+ const body = parse(specExcuseBodySchema, await readBody(req, res));
467
+ const role = body.role ?? readUserRole();
468
+ const resExcuse = spec.excuse({
469
+ componentId: body.componentId,
470
+ reason: body.reason,
471
+ role,
472
+ ...(body.property ? { property: body.property } : {})
473
+ });
474
+ const rulesMeta = spec.listRulesMeta();
475
+ send(200, {
476
+ state: resExcuse.state,
477
+ meta: resExcuse.meta,
478
+ challenge: resExcuse.challenge,
479
+ rulesMeta,
480
+ report: spec.formatReport(),
481
+ settings: readOnSpecConfig(options.projectDir)
482
+ });
483
+ return;
484
+ }
485
+ if (route === '/spec/update-rule' && req.method === 'POST') {
486
+ const body = parse(specUpdateRuleBodySchema, await readBody(req, res));
487
+ const role = body.role ?? readUserRole();
488
+ const resUpdate = spec.updateRule({
489
+ ...(body.componentId ? { componentId: body.componentId } : {}),
490
+ ruleFile: body.ruleFile,
491
+ markdown: body.markdown,
492
+ role,
493
+ ...(body.note ? { note: body.note } : {})
494
+ });
495
+ const rulesMeta = spec.listRulesMeta();
496
+ send(200, {
497
+ saved: resUpdate.saved,
498
+ state: resUpdate.state,
499
+ meta: resUpdate.meta,
500
+ rulesMeta,
501
+ report: spec.formatReport(),
502
+ settings: readOnSpecConfig(options.projectDir)
503
+ });
504
+ return;
505
+ }
506
+ if (route === '/spec/reviewed' && req.method === 'POST') {
507
+ const body = parse(specReviewedBodySchema, await readBody(req, res));
508
+ const role = body.role ?? readUserRole();
509
+ const resReviewed = spec.markRuleReviewed({
510
+ ruleFile: body.ruleFile,
511
+ role,
512
+ ...(body.note ? { note: body.note } : {})
513
+ });
514
+ const rulesMeta = spec.listRulesMeta();
515
+ send(200, {
516
+ meta: resReviewed.meta,
517
+ challenge: resReviewed.challenge,
518
+ rulesMeta,
519
+ report: spec.formatReport()
520
+ });
521
+ return;
522
+ }
523
+ if (route === '/spec/send-back' && req.method === 'POST') {
524
+ const body = parse(specSendBackBodySchema, await readBody(req, res));
525
+ const role = body.role ?? readUserRole();
526
+ const resBack = spec.sendBack({
527
+ componentId: body.componentId,
528
+ ...(body.note ? { note: body.note } : {}),
529
+ role
530
+ });
531
+ const rulesMeta = spec.listRulesMeta();
532
+ send(200, {
533
+ state: resBack.state,
534
+ feedbackRef: resBack.feedbackRef,
535
+ rulesMeta,
536
+ report: spec.formatReport(),
537
+ settings: readOnSpecConfig(options.projectDir)
538
+ });
539
+ return;
540
+ }
541
+ if (route === '/profile' && req.method === 'GET') {
542
+ send(200, readUserProfile());
543
+ return;
544
+ }
545
+ if (route === '/profile' && req.method === 'PUT') {
546
+ const body = parse(profileBodySchema, await readBody(req, res));
547
+ const saved = writeUserRole(body.role);
548
+ send(200, { role: saved.role, saved: true });
549
+ return;
550
+ }
551
+ if (route === '/spec/settings' && req.method === 'GET') {
552
+ send(200, { ...readOnSpecConfig(options.projectDir), hooks: installedAgentHooks(options.projectDir) });
553
+ return;
554
+ }
555
+ if (route === '/spec/settings' && req.method === 'PATCH') {
556
+ const body = parse(onSpecConfigSchema, await readBody(req, res));
557
+ const settings = writeOnSpecConfig(options.projectDir, body);
558
+ if (body.blockDone === true) {
559
+ installAgentHooks(options.projectDir, projectAgents(options.projectDir));
560
+ }
561
+ send(200, { ...settings, hooks: installedAgentHooks(options.projectDir) });
562
+ return;
563
+ }
564
+ // Update checker & opt-in CLI upgrader (v0.7): works with ~/.luci/ even before project init
565
+ const currentVersion = options.version || cliVersion();
566
+ if (route === '/updates' && req.method === 'GET') {
567
+ const status = await getUpdateStatus({
568
+ currentVersion,
569
+ ...(options.fetchImpl ? { fetchImpl: options.fetchImpl } : {}),
570
+ ...(options.entryFile ? { entryFile: options.entryFile } : {})
571
+ });
572
+ send(200, status);
573
+ return;
574
+ }
575
+ if (route === '/updates/check' && req.method === 'POST') {
576
+ const status = await getUpdateStatus({
577
+ currentVersion,
578
+ force: true,
579
+ ...(options.fetchImpl ? { fetchImpl: options.fetchImpl } : {}),
580
+ ...(options.entryFile ? { entryFile: options.entryFile } : {})
581
+ });
582
+ send(200, status);
583
+ return;
584
+ }
585
+ if (route === '/updates/settings' && req.method === 'PATCH') {
586
+ const body = parse(updateSettingsBodySchema, await readBody(req, res));
587
+ writeUpdatePreferences({
588
+ ...(body.check !== undefined ? { check: body.check } : {}),
589
+ ...(body.auto !== undefined ? { auto: body.auto } : {}),
590
+ ...(body.dismissedVersion !== undefined ? { dismissedVersion: body.dismissedVersion } : {})
591
+ });
592
+ const status = await getUpdateStatus({
593
+ currentVersion,
594
+ cacheOnly: true,
595
+ ...(options.entryFile ? { entryFile: options.entryFile } : {})
596
+ });
597
+ send(200, status);
598
+ return;
599
+ }
600
+ if (route === '/updates/apply' && req.method === 'POST') {
601
+ const current = await getUpdateStatus({
602
+ currentVersion,
603
+ cacheOnly: true,
604
+ ...(options.entryFile ? { entryFile: options.entryFile } : {})
605
+ });
606
+ const result = runCliUpgrade({
607
+ targetVersion: current.latestVersion,
608
+ ...(options.entryFile ? { entryFile: options.entryFile } : {}),
609
+ ...(options.upgradeRunner ? { runner: options.upgradeRunner } : {})
610
+ });
611
+ send(200, result);
276
612
  return;
277
613
  }
278
614
  throw new HttpError(404, 'Not found.');
279
615
  };
280
616
  handle().catch((err) => {
281
- const status = err instanceof HttpError ? err.status : err instanceof FeedbackError ? (/No feedback item/.test(err.message) ? 404 : 409) : err instanceof DesignError ? 400 : 500;
617
+ const status = err instanceof HttpError
618
+ ? err.status
619
+ : err instanceof FeedbackError
620
+ ? (/No feedback item/.test(err.message) ? 404 : 409)
621
+ : err instanceof SpecError
622
+ ? (/not found/i.test(err.message) ? 404 : 400)
623
+ : err instanceof DesignError || err instanceof URIError
624
+ ? 400
625
+ : 500;
282
626
  if (!res.headersSent)
283
627
  send(status, { error: err instanceof Error ? err.message : String(err) });
284
628
  });