dsh-artifact-studio 0.8.0 → 0.13.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 (43) hide show
  1. package/README.md +72 -10
  2. package/THIRD_PARTY_NOTICES.md +57 -0
  3. package/assets/canvas.engine.js +72 -72
  4. package/assets/canvas.viewer.js +6415 -0
  5. package/client.canvas.js +1 -1
  6. package/client.doc.js +67 -79
  7. package/client.js +313 -291
  8. package/client.sheet.js +218 -0
  9. package/dist/contract.js +32 -5
  10. package/dist/host/lib/assets.js +12 -0
  11. package/dist/host/lib/brief.js +127 -0
  12. package/dist/host/lib/checks.js +62 -8
  13. package/dist/host/lib/design-catalog.js +149 -0
  14. package/dist/host/lib/design-render.js +37 -0
  15. package/dist/host/lib/design-system.js +1 -1
  16. package/dist/host/lib/export.js +123 -5
  17. package/dist/host/lib/fsutil.js +41 -0
  18. package/dist/host/lib/generation.js +36 -0
  19. package/dist/host/lib/guide.js +130 -0
  20. package/dist/host/lib/paths.js +2 -1
  21. package/dist/host/lib/recipes.js +224 -0
  22. package/dist/host/lib/rpc.js +20 -5
  23. package/dist/host/lib/service.js +253 -24
  24. package/dist/host/lib/skill.js +59 -18
  25. package/dist/host/lib/store.js +107 -25
  26. package/dist/host/lib/svg-model.js +85 -0
  27. package/dist/host/lib/svg-viewer.js +380 -0
  28. package/dist/host/lib/tools.js +346 -35
  29. package/dist/host/lib/validate.js +24 -0
  30. package/dist/host/lib/viewer.js +150 -0
  31. package/dist/host/lib/xlsx.js +314 -0
  32. package/dist/host/worker/design-worker.js +71 -5
  33. package/dist/host/worker/page-model.js +169 -0
  34. package/dist/html-tags.js +51 -0
  35. package/dist/kit.js +224 -0
  36. package/dist/render.js +10 -3
  37. package/dist/sheet/formula.js +475 -0
  38. package/dist/sheet/functions.js +463 -0
  39. package/dist/sheet/index.js +9 -0
  40. package/dist/sheet/model.js +695 -0
  41. package/dist/sheet/operations.js +384 -0
  42. package/dist/sheet/output.js +182 -0
  43. package/package.json +15 -3
@@ -4,7 +4,11 @@ import { AlignmentType, BorderStyle, Document, ExternalHyperlink, HeadingLevel,
4
4
  import { marked } from 'marked';
5
5
  import { FORMATS_BY_TYPE } from '../../contract.js';
6
6
  import { DOC_CSP, DOC_STYLE, PAGE_CSP, PRINT_CSP, composePage, escapeHtml } from '../../render.js';
7
+ import { effectiveTextColor, evaluateWorkbook, parseSheetWorkbook, sheetTable, sheetToCsv } from '../../sheet/index.js';
8
+ import { workbookToXlsx } from './xlsx.js';
7
9
  import { ArtifactError } from './errors.js';
10
+ import { buildSvgViewerHtml } from './svg-viewer.js';
11
+ import { buildViewerHtml } from './viewer.js';
8
12
  import { assertWithin, withLock } from './fsutil.js';
9
13
  const MEDIA_TYPES = {
10
14
  html: 'text/html',
@@ -12,8 +16,13 @@ const MEDIA_TYPES = {
12
16
  docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
13
17
  png: 'image/png',
14
18
  svg: 'image/svg+xml',
19
+ 'html-svg': 'text/html',
15
20
  fig: 'application/octet-stream',
21
+ csv: 'text/csv',
22
+ xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
16
23
  };
24
+ /** The file extension of a format whose id is not its extension. */
25
+ const EXTENSIONS = { 'html-svg': 'html' };
17
26
  const MARKED_TYPES = new Set([
18
27
  'blockquote', 'br', 'checkbox', 'code', 'codespan', 'def', 'del', 'em', 'escape', 'heading', 'hr', 'html',
19
28
  'image', 'link', 'list', 'list_item', 'paragraph', 'space', 'strong', 'table', 'tag', 'text',
@@ -41,7 +50,7 @@ function exportFileName(manifest, format, now) {
41
50
  .replace(/^-+|-+$/g, '')
42
51
  .slice(0, 60) || 'artifact';
43
52
  const stamp = now.toISOString().replace(/[-:]/g, '').replace(/\..*$/, '').replace('T', '-');
44
- return `${slug}-v${manifest.version}-${stamp}.${format}`;
53
+ return `${slug}-v${manifest.version}-${stamp}.${EXTENSIONS[format] ?? format}`;
45
54
  }
46
55
  /**
47
56
  * Printable HTML for a Markdown document, styled from the design tokens.
@@ -284,6 +293,85 @@ export async function docToDocx(title, markdown, design) {
284
293
  });
285
294
  return Packer.toBuffer(document);
286
295
  }
296
+ /** The most cells one printable sheet may cover before the copy refuses. */
297
+ const MAX_PRINT_CELLS = 20000;
298
+ /**
299
+ * A cell's inline style for a print table. The printed copy uses the artifact
300
+ * tokens for its defaults and the stored cell style for overrides, so it looks
301
+ * like the panel without depending on the panel's CSS.
302
+ * @param cell the table cell.
303
+ * @returns a style attribute value, or an empty string.
304
+ */
305
+ function printCellStyle(cell) {
306
+ const rules = [];
307
+ const style = cell.style;
308
+ if (style !== undefined) {
309
+ if (style.bold === true)
310
+ rules.push('font-weight:600');
311
+ if (style.italic === true)
312
+ rules.push('font-style:italic');
313
+ const decoration = [style.underline === true ? 'underline' : '', style.strike === true ? 'line-through' : ''].filter((part) => part !== '').join(' ');
314
+ if (decoration !== '')
315
+ rules.push('text-decoration:' + decoration);
316
+ if (style.align !== undefined)
317
+ rules.push('text-align:' + style.align);
318
+ const color = effectiveTextColor(style);
319
+ if (color !== undefined)
320
+ rules.push('color:' + color);
321
+ if (style.background !== undefined)
322
+ rules.push('background-color:' + style.background);
323
+ }
324
+ if (style?.align === undefined)
325
+ rules.push('text-align:' + (typeof cell.value === 'number' ? 'right' : 'left'));
326
+ return rules.join(';');
327
+ }
328
+ /**
329
+ * A print copy of one sheet workbook: one table per sheet under the workbook
330
+ * title. Formula cells print their computed value.
331
+ * @param workbook the workbook.
332
+ * @param designCss the resolved token CSS.
333
+ * @param title the artifact title.
334
+ * @returns a full HTML document for the print frame.
335
+ */
336
+ export function sheetToPrintableHtml(workbook, designCss, title) {
337
+ const evaluated = evaluateWorkbook(workbook);
338
+ const sections = [];
339
+ for (const sheet of workbook.sheets) {
340
+ const table = sheetTable(workbook, evaluated, sheet.name);
341
+ if (table.rows * table.columns > MAX_PRINT_CELLS) {
342
+ throw new ArtifactError('artifact/too-large', 'The sheet "' + sheet.name + '" covers ' + String(table.rows) + ' by ' + String(table.columns) + ' cells; a print copy supports up to ' + String(MAX_PRINT_CELLS) + '. Export XLSX instead.', {
343
+ sheet: sheet.name,
344
+ rows: table.rows,
345
+ columns: table.columns,
346
+ limit: MAX_PRINT_CELLS,
347
+ });
348
+ }
349
+ const byPosition = new Map();
350
+ for (const cell of table.cells)
351
+ byPosition.set(String(cell.row) + ',' + String(cell.column), cell);
352
+ const rows = [];
353
+ for (let row = 1; row <= table.rows; row += 1) {
354
+ const cells = [];
355
+ for (let column = 0; column < table.columns; column += 1) {
356
+ const cell = byPosition.get(String(row) + ',' + String(column));
357
+ const style = cell === undefined ? '' : printCellStyle(cell);
358
+ cells.push('<td' + (style === '' ? '' : ' style="' + escapeHtml(style) + '"') + '>' + escapeHtml(cell?.display ?? '') + '</td>');
359
+ }
360
+ rows.push('<tr>' + cells.join('') + '</tr>');
361
+ }
362
+ sections.push((workbook.sheets.length > 1 ? '<h2>' + escapeHtml(sheet.name) + '</h2>' : '') +
363
+ '<table><tbody>' + rows.join('') + '</tbody></table>');
364
+ }
365
+ const style = `
366
+ body { margin: 0; background: var(--artifact-color-surface); color: var(--artifact-color-text); font-family: var(--artifact-font-family); font-size: 12px; line-height: 1.45; }
367
+ main { padding: 28px 24px 40px; }
368
+ h1 { margin: 0 0 16px; font-family: var(--artifact-font-display); font-size: 22px; line-height: 1.2; }
369
+ h2 { margin: 22px 0 8px; font-size: 13px; font-weight: 600; }
370
+ table { border-collapse: collapse; margin: 0 0 24px; }
371
+ td { padding: 4px 8px; border: .5px solid color-mix(in srgb, var(--artifact-color-text) 22%, transparent); vertical-align: top; white-space: pre-wrap; }
372
+ @media print { main { padding: 0; } tr { break-inside: avoid; } }`;
373
+ return composePage('<style>' + style + '</style><main><h1>' + escapeHtml(title) + '</h1>' + sections.join('') + '</main>', designCss, PRINT_CSP, title);
374
+ }
287
375
  /**
288
376
  * Write one export into the scope's `exports/` folder.
289
377
  * @param root the scope root.
@@ -307,14 +395,44 @@ export async function writeExport(root, manifest, content, format, design, now,
307
395
  if (designs === undefined) {
308
396
  throw new ArtifactError('artifact/design-unavailable', 'The design renderer is not available.', {});
309
397
  }
310
- if (format !== 'png' && format !== 'svg' && format !== 'fig') {
398
+ if (format === 'html') {
399
+ const scene = await designs.exportContent(content, 'fig');
400
+ data = await buildViewerHtml({ title: manifest.title, fig: scene.bytes });
401
+ mediaType = 'text/html';
402
+ }
403
+ else if (format === 'html-svg') {
404
+ const model = await designs.pageModel(content);
405
+ data = await buildSvgViewerHtml({ title: manifest.title, model });
406
+ mediaType = 'text/html';
407
+ }
408
+ else if (format === 'png' || format === 'svg' || format === 'fig') {
409
+ const rendered = await designs.exportContent(content, format);
410
+ data = rendered.bytes;
411
+ mediaType = rendered.mediaType;
412
+ }
413
+ else {
311
414
  throw new ArtifactError('artifact/unsupported-format', `A design cannot be exported as ${format}.`, {
312
415
  supported: FORMATS_BY_TYPE.design,
313
416
  });
314
417
  }
315
- const rendered = await designs.exportContent(content, format);
316
- data = rendered.bytes;
317
- mediaType = rendered.mediaType;
418
+ }
419
+ else if (manifest.type === 'sheet') {
420
+ let workbook;
421
+ try {
422
+ workbook = parseSheetWorkbook(content);
423
+ }
424
+ catch {
425
+ throw new ArtifactError('artifact/corrupt', 'The saved sheet content cannot be read.', { id: manifest.id });
426
+ }
427
+ if (format === 'csv')
428
+ data = Buffer.from(sheetToCsv(workbook, evaluateWorkbook(workbook)), 'utf8');
429
+ else if (format === 'xlsx')
430
+ data = workbookToXlsx(workbook);
431
+ else {
432
+ throw new ArtifactError('artifact/unsupported-format', 'A sheet exports as csv or xlsx.', {
433
+ supported: FORMATS_BY_TYPE.sheet,
434
+ });
435
+ }
318
436
  }
319
437
  else if (format === 'docx')
320
438
  data = await docToDocx(manifest.title, content, design.tokens);
@@ -87,3 +87,44 @@ export async function assertWithin(root, target) {
87
87
  }
88
88
  }
89
89
  }
90
+ /** Reject symbolic links at every new storage boundary, including in-root links. */
91
+ export async function assertPlainPath(root, target) {
92
+ await assertWithin(root, target);
93
+ const relative = path.relative(root, target);
94
+ let current = root;
95
+ for (const part of ['', ...relative.split(path.sep).filter(Boolean)]) {
96
+ current = path.join(current, part);
97
+ try {
98
+ if ((await fs.lstat(current)).isSymbolicLink())
99
+ throw new ArtifactError('artifact/forbidden-path', 'Storage paths must not contain symbolic links.');
100
+ }
101
+ catch (error) {
102
+ if (errnoCode(error) === 'ENOENT')
103
+ return;
104
+ throw error;
105
+ }
106
+ }
107
+ }
108
+ /** Fail closed on another process's writer; stale locks need explicit manual recovery. */
109
+ export async function withWriteLock(root, key, task) {
110
+ return withLock(key, async () => {
111
+ const file = key + '.write-lock';
112
+ await assertPlainPath(root, file);
113
+ let handle;
114
+ try {
115
+ handle = await fs.open(file, 'wx', 0o600);
116
+ }
117
+ catch (error) {
118
+ if (errnoCode(error) === 'EEXIST')
119
+ throw new ArtifactError('artifact/writer-busy', 'Another writer or a stale lock owns this store. Finish that writer before retrying; after a crash, recover the lock manually.', { file });
120
+ throw error;
121
+ }
122
+ try {
123
+ return await task();
124
+ }
125
+ finally {
126
+ await handle.close();
127
+ await fs.unlink(file);
128
+ }
129
+ });
130
+ }
@@ -0,0 +1,36 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { DEFAULT_TOKENS, DIGEST_PATTERN, isDesignSystemRef } from '../../contract.js';
3
+ import { mergeTokens } from './design-system.js';
4
+ import { parseRecipe } from './recipes.js';
5
+ import { ArtifactError } from './errors.js';
6
+ export const generationHash = (text) => 'sha256:' + createHash('sha256').update(text).digest('hex');
7
+ export function parseGeneration(value) {
8
+ if (value === null || typeof value !== 'object')
9
+ throw new ArtifactError('artifact/corrupt', 'Invalid generation snapshot.');
10
+ const row = { ...value };
11
+ if (row.schemaVersion !== 1 || row.system !== null && !isDesignSystemRef(row.system)
12
+ || !['workspace', 'library', 'default'].includes(String(row.tokenSource))
13
+ || row.kit !== null && (typeof row.kit !== 'string' || row.kit.length > 20)
14
+ || typeof row.conventionsHash !== 'string' || !DIGEST_PATTERN.test(row.conventionsHash))
15
+ throw new ArtifactError('artifact/corrupt', 'Unsupported or invalid generation snapshot.');
16
+ if (row.tokenSource !== 'workspace' && row.tokenSource !== 'library' && row.tokenSource !== 'default')
17
+ throw new ArtifactError('artifact/corrupt', 'Invalid token source.');
18
+ if (row.system !== null && !isDesignSystemRef(row.system))
19
+ throw new ArtifactError('artifact/corrupt', 'Invalid system identity.');
20
+ if (row.kit !== null && typeof row.kit !== 'string')
21
+ throw new ArtifactError('artifact/corrupt', 'Invalid kit.');
22
+ const tokens = mergeTokens(DEFAULT_TOKENS, row.tokens);
23
+ if (JSON.stringify(tokens) !== JSON.stringify(row.tokens))
24
+ throw new ArtifactError('artifact/corrupt', 'Incomplete generation tokens.');
25
+ return { schemaVersion: 1, tokens, system: row.system, tokenSource: row.tokenSource, recipe: row.recipe === null ? null : parseRecipe(row.recipe), kit: row.kit, conventionsHash: row.conventionsHash };
26
+ }
27
+ export function generationText(value) {
28
+ const text = JSON.stringify(parseGeneration(value));
29
+ if (Buffer.byteLength(text) > 65536)
30
+ throw new ArtifactError('artifact/too-large', 'Generation snapshot exceeds 64 KiB.');
31
+ return text;
32
+ }
33
+ export function generationSummary(value) {
34
+ const text = generationText(value);
35
+ return { hash: generationHash(text), bytes: Buffer.byteLength(text), system: value.system, recipe: value.recipe?.id ?? null, kit: value.kit };
36
+ }
@@ -0,0 +1,130 @@
1
+ /**
2
+ * Guides: the conventions a user or a project keeps for every artifact, plus
3
+ * their own recipes. The library guide holds the user's preferences across
4
+ * projects; a workspace guide holds one project's conventions. Both live in
5
+ * guide.json beside design-system.json in their scope root.
6
+ */
7
+ import fs from 'node:fs/promises';
8
+ import path from 'node:path';
9
+ import { ArtifactError } from './errors.js';
10
+ import { assertWithin, withLock, writeAtomic } from './fsutil.js';
11
+ import { assertPlainFile } from './paths.js';
12
+ import { BUILTIN_RECIPES, MAX_RECIPES, RECIPE_ID, parseRecipe } from './recipes.js';
13
+ const FILE = 'guide.json';
14
+ export const MAX_INSTRUCTIONS = 6000;
15
+ export const EMPTY_GUIDE = { schemaVersion: 1, instructions: '', recipes: [] };
16
+ /**
17
+ * Validate a stored or proposed guide.
18
+ * @param value the candidate.
19
+ * @returns the guide.
20
+ */
21
+ export function parseGuide(value) {
22
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) {
23
+ throw new ArtifactError('artifact/invalid-guide', 'A guide must be an object.', {});
24
+ }
25
+ const fields = { ...value };
26
+ if (fields.schemaVersion !== 1)
27
+ throw new ArtifactError('artifact/invalid-guide', 'Unsupported guide schemaVersion. Expected 1.');
28
+ const instructions = fields.instructions ?? '';
29
+ if (typeof instructions !== 'string' || instructions.length > MAX_INSTRUCTIONS) {
30
+ throw new ArtifactError('artifact/invalid-guide', 'instructions must be text up to ' + String(MAX_INSTRUCTIONS) + ' characters.', { field: 'instructions' });
31
+ }
32
+ const recipes = fields.recipes ?? [];
33
+ if (!Array.isArray(recipes) || recipes.length > MAX_RECIPES) {
34
+ throw new ArtifactError('artifact/invalid-guide', 'recipes must be a list of up to ' + String(MAX_RECIPES) + ' recipes.', { field: 'recipes' });
35
+ }
36
+ const parsed = recipes.map((item, index) => parseRecipe(item, 'recipes[' + String(index) + ']'));
37
+ if (new Set(parsed.map((item) => item.id)).size !== parsed.length) {
38
+ throw new ArtifactError('artifact/invalid-guide', 'Recipe ids must be unique.', { field: 'recipes' });
39
+ }
40
+ return { schemaVersion: 1, instructions: instructions.trim(), recipes: parsed };
41
+ }
42
+ /**
43
+ * A missing guide is empty. Invalid saved data is reported rather than
44
+ * silently replaced by a partial update.
45
+ * @param root the scope root, or undefined when the workspace has no store.
46
+ * @returns the guide.
47
+ */
48
+ export async function readGuide(root) {
49
+ if (root === undefined)
50
+ return EMPTY_GUIDE;
51
+ const file = path.join(root.root, FILE);
52
+ await assertWithin(root.root, file);
53
+ if (!(await assertPlainFile(file)))
54
+ return EMPTY_GUIDE;
55
+ if ((await fs.stat(file)).size > 1024 * 1024)
56
+ throw new ArtifactError('artifact/invalid-guide', 'Guide exceeds the 1 MiB read limit.');
57
+ try {
58
+ return parseGuide(JSON.parse(await fs.readFile(file, 'utf8')));
59
+ }
60
+ catch (error) {
61
+ if (error instanceof SyntaxError) {
62
+ throw new ArtifactError('artifact/invalid-guide', 'The saved guide contains invalid JSON. Repair it before updating conventions.', { file });
63
+ }
64
+ throw error;
65
+ }
66
+ }
67
+ /**
68
+ * Apply a patch to one scope's guide under its lock.
69
+ * @param root the scope root to write.
70
+ * @param patch the change.
71
+ * @returns the saved guide.
72
+ */
73
+ export async function saveGuide(root, patch) {
74
+ const file = path.join(root.root, FILE);
75
+ return withLock(file, async () => {
76
+ const current = await readGuide(root);
77
+ let recipes = [...current.recipes];
78
+ if (patch.removeRecipe !== undefined) {
79
+ if (!recipes.some((item) => item.id === patch.removeRecipe)) {
80
+ throw new ArtifactError('artifact/not-found', 'This guide has no recipe ' + patch.removeRecipe + '.', { recipe: patch.removeRecipe });
81
+ }
82
+ recipes = recipes.filter((item) => item.id !== patch.removeRecipe);
83
+ }
84
+ if (patch.recipe !== undefined) {
85
+ const recipe = parseRecipe(patch.recipe);
86
+ recipes = [...recipes.filter((item) => item.id !== recipe.id), recipe];
87
+ }
88
+ const next = parseGuide({ schemaVersion: 1, instructions: patch.instructions ?? current.instructions, recipes });
89
+ await assertWithin(root.root, file);
90
+ await assertPlainFile(file);
91
+ await writeAtomic(file, JSON.stringify(next, null, 2) + '\n');
92
+ return next;
93
+ });
94
+ }
95
+ /**
96
+ * Every recipe available for a type, a workspace recipe first, then the
97
+ * library, then the built-in set. The same id at a narrower scope replaces
98
+ * the wider one.
99
+ * @param layers the guides.
100
+ * @param type limit to recipes for this type, when given.
101
+ * @returns the recipes.
102
+ */
103
+ export function availableRecipes(layers, type) {
104
+ const seen = new Set();
105
+ const out = [];
106
+ const add = (recipes, source) => {
107
+ for (const recipe of recipes) {
108
+ if (seen.has(recipe.id))
109
+ continue;
110
+ seen.add(recipe.id);
111
+ if (type === undefined || recipe.types.includes(type))
112
+ out.push({ ...recipe, source });
113
+ }
114
+ };
115
+ add(layers.workspace.recipes, 'workspace');
116
+ add(layers.library.recipes, 'library');
117
+ add(BUILTIN_RECIPES, 'builtin');
118
+ return out;
119
+ }
120
+ /**
121
+ * Resolve one recipe id through the layers.
122
+ * @param layers the guides.
123
+ * @param id the recipe id.
124
+ * @returns the recipe, or undefined when no layer defines it.
125
+ */
126
+ export function findRecipe(layers, id) {
127
+ if (!RECIPE_ID.test(id))
128
+ return undefined;
129
+ return availableRecipes(layers).find((item) => item.id === id);
130
+ }
@@ -138,9 +138,10 @@ export async function workspaceRoot(config, workspace) {
138
138
  export async function workspaceRootExisting(config, workspace) {
139
139
  const wanted = path.resolve(path.join(config.home, config.workspaceBase, workspaceKey(workspace.id)));
140
140
  try {
141
+ await assertNoLinkChain(wanted);
141
142
  const canonical = await fs.realpath(wanted);
142
143
  if (canonical !== wanted)
143
- return undefined;
144
+ throw new ArtifactError('artifact/forbidden-path', 'The workspace artifact root resolves through a link.');
144
145
  return { scope: 'workspace', workspaceId: workspace.id, root: canonical };
145
146
  }
146
147
  catch (error) {
@@ -0,0 +1,224 @@
1
+ /**
2
+ * Recipes: named content structures for an intent, such as a client scope of
3
+ * work or an internal feature spec. A recipe says who reads the artifact, which
4
+ * sections it has, and the content rules. It says nothing about colors or
5
+ * components; tokens and the kit own those.
6
+ */
7
+ import { RECIPE_PATTERN, isArtifactType } from '../../contract.js';
8
+ import { ArtifactError } from './errors.js';
9
+ export const RECIPE_ID = RECIPE_PATTERN;
10
+ const SECTION_KEY = /^[a-z][a-z0-9-]{0,39}$/;
11
+ export const MAX_RECIPES = 30;
12
+ function section(key, title, purpose, required = true) {
13
+ return { key, title, purpose, required };
14
+ }
15
+ export const BUILTIN_RECIPES = [
16
+ {
17
+ id: 'feature-spec',
18
+ name: 'Feature specification',
19
+ types: ['page', 'doc'],
20
+ audience: 'The engineers and reviewers who build or approve the feature.',
21
+ purpose: 'Explain a new or changed feature: current behavior, proposed behavior, rules, and what to build. Use for internal requirement docs and change proposals.',
22
+ sections: [
23
+ section('summary', 'Summary', 'What changes and why in a few sentences, and the request it answers.'),
24
+ section('current', 'Current behavior', 'What users and the system do today, naming the screens involved.'),
25
+ section('proposed', 'Proposed behavior', 'Explain the changed behavior. Include screen states or an interactive demonstration when requested or useful, using verified project UI references.'),
26
+ section('rules', 'Rules and edge cases', 'Conditions, limits, permissions, and empty and error states.'),
27
+ section('implementation', 'Implementation notes', 'Where the code changes, with file paths and the current code path.', false),
28
+ section('acceptance', 'Scope and acceptance checks', 'What is in and out of scope, and checks that can fail.'),
29
+ section('questions', 'Open questions', 'Decisions still needed, each with an owner when known.', false),
30
+ ],
31
+ rules: [
32
+ 'Feature walkthrough: name the actor and starting conditions, show the actions and alternate paths, and state the resulting behavior.',
33
+ 'Identify the request source when available. Quote only supplied or verified wording.',
34
+ 'Mark simulated actions and illustrative data.',
35
+ 'Do not invent metrics, owners, or estimates.',
36
+ ],
37
+ },
38
+ {
39
+ id: 'client-scope',
40
+ name: 'Client scope of work',
41
+ types: ['page', 'doc'],
42
+ audience: 'The client or external stakeholders approving the deliverables. Match their known technical familiarity.',
43
+ purpose: 'Agree on what will be delivered: the behavior, what users see, what the client controls, and what stays the same.',
44
+ sections: [
45
+ section('aim', 'Aim', 'One short paragraph: what will be added or changed, and the outcome.'),
46
+ section('deliverables', 'Deliverables', 'Describe the agreed outputs and observable outcomes. Choose prose, tables, or a journey view to fit the work and reader.'),
47
+ section('controls', 'What the client controls', 'Settings and admin actions, with their starting values.', false),
48
+ section('unchanged', 'What stays the same', 'Existing behavior and data this work does not change.', false),
49
+ section('assumptions', 'Assumptions and exclusions', 'What the scope depends on and what it leaves out.', false),
50
+ section('next', 'Next step', 'What the client needs to approve or answer.', false),
51
+ ],
52
+ rules: [
53
+ "Use the client's terms. Include implementation detail only when it helps the intended audience approve the scope.",
54
+ 'Distinguish agreed deliverables, assumptions, and proposed behavior. Do not invent exact UI messages.',
55
+ 'Include commercial terms, responsibilities, schedules, or acceptance conditions when requested and supported by evidence.',
56
+ 'Keep one name for each flow throughout.',
57
+ ],
58
+ },
59
+ {
60
+ id: 'investigation',
61
+ name: 'Investigation report',
62
+ types: ['page', 'doc'],
63
+ audience: 'Engineers fixing the problem and the people who reported it.',
64
+ purpose: 'Explain a bug or incident: what is wrong, the evidence, the cause, and the fix.',
65
+ sections: [
66
+ section('problem', 'Problem', 'The defect as one observable sentence, with the real numbers.'),
67
+ section('evidence', 'Evidence', 'Observations, data, and logs, kept apart from interpretation.'),
68
+ section('cause', 'Cause', 'The confirmed cause, or each hypothesis with the check that would confirm it.'),
69
+ section('fix', 'Fix', 'Explain the remedy or proposed next action. A before-and-after comparison is optional.'),
70
+ section('checks', 'Acceptance checks', 'Checks that prove the fix and can fail.'),
71
+ section('reply', 'Reply to the reporter', 'A short plain-language summary the reporter can read.', false),
72
+ ],
73
+ rules: [
74
+ 'Investigation report: separate observations, evidence, hypotheses, and unresolved checks.',
75
+ 'Do not present a hypothesis as a confirmed cause.',
76
+ ],
77
+ },
78
+ {
79
+ id: 'technical-decision',
80
+ name: 'Technical decision',
81
+ types: ['page', 'doc'],
82
+ audience: 'The engineers and leads who make or review the decision.',
83
+ purpose: 'Recommend one option among several, with evidence.',
84
+ sections: [
85
+ section('recommendation', 'Recommendation', 'The choice and the one-line reason.'),
86
+ section('context', 'Context', 'The problem and the constraints.'),
87
+ section('options', 'Options', 'Each option on the same criteria, with evidence and tradeoffs. A table works well.'),
88
+ section('consequences', 'Consequences', 'What the choice commits to, its risks, and the migration.'),
89
+ section('reversal', 'What would change the decision', 'The evidence that would reopen it.', false),
90
+ ],
91
+ rules: [
92
+ 'Technical decision: state the recommendation, compare options with evidence and tradeoffs, and name what would change the decision.',
93
+ ],
94
+ },
95
+ {
96
+ id: 'architecture',
97
+ name: 'Architecture or code walkthrough',
98
+ types: ['page', 'doc'],
99
+ audience: 'Engineers who need to understand a system before changing it.',
100
+ purpose: 'Explain how a system or code path works: its parts, one flow through it, and the risks.',
101
+ sections: [
102
+ section('overview', 'Overview', 'What the system does and its main parts, in short.'),
103
+ section('boundaries', 'Boundaries', 'Components, ownership, and dependencies.'),
104
+ section('flow', 'Flow', 'One request or data flow traced step by step, with file paths.'),
105
+ section('data', 'Data and contracts', 'Data shapes, storage, and interfaces.', false),
106
+ section('files', 'File map', 'Where each part lives.', false),
107
+ section('risks', 'Risks', 'Watch-outs for anyone changing the code.', false),
108
+ ],
109
+ rules: [
110
+ 'Architecture walkthrough: show boundaries, dependencies, and one request or data flow.',
111
+ 'Label connections and provide a textual flow beside the diagram.',
112
+ 'Use real file paths and names from code you read.',
113
+ ],
114
+ },
115
+ {
116
+ id: 'ui-proposal',
117
+ name: 'UI proposal or prototype',
118
+ types: ['page'],
119
+ audience: 'Reviewers who approve a UI before it is built.',
120
+ purpose: 'Show proposed screens and interaction states before implementation. A static canvas mockup is a design artifact instead.',
121
+ sections: [
122
+ section('summary', 'What this shows', 'The change under review and how to use the prototype.'),
123
+ section('prototype', 'Prototype', 'Only the relevant screens and interaction states, inside a product UI replica.'),
124
+ section('decisions', 'Decisions for review', 'Each open design choice with a recommendation.', false),
125
+ section('acceptance', 'Acceptance criteria', 'Checks a reviewer can try in the prototype.', false),
126
+ section('excluded', 'Not in this prototype', 'What the prototype leaves out.', false),
127
+ ],
128
+ rules: [
129
+ 'UI proposal: show only the relevant screens and interaction states. Mark simulated actions.',
130
+ "Recreate the product's real look inside the replica from its code or screenshots, and keep the page around it on the artifact theme.",
131
+ ],
132
+ },
133
+ {
134
+ id: 'dashboard',
135
+ name: 'Metrics dashboard',
136
+ types: ['page'],
137
+ audience: 'People who track the numbers and act on them.',
138
+ purpose: 'Show metrics with their sources, units, and time range.',
139
+ sections: [
140
+ section('summary', 'Summary', 'The headline numbers and what they mean.'),
141
+ section('metrics', 'Metrics', 'Charts and tables built from one dataset.'),
142
+ section('sources', 'Sources and gaps', 'Sources, units, time range, baseline, and missing data.'),
143
+ ],
144
+ rules: [
145
+ 'Metrics dashboard: name sources, units, time range, baseline, and missing data.',
146
+ 'Derive charts, tables, labels, and selection details from one dataset.',
147
+ 'Never turn missing values into zero.',
148
+ ],
149
+ },
150
+ {
151
+ id: 'general',
152
+ name: 'General',
153
+ types: ['page', 'doc', 'design'],
154
+ audience: 'Whoever the request names.',
155
+ purpose: 'Anything that matches no other recipe.',
156
+ sections: [],
157
+ rules: ['Lead with the answer, then the detail.'],
158
+ },
159
+ ];
160
+ function isFields(value) {
161
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
162
+ }
163
+ function invalid(message, field) {
164
+ return new ArtifactError('artifact/invalid-guide', message, { field });
165
+ }
166
+ function text(value, field, max, allowEmpty = false) {
167
+ if (typeof value !== 'string' || value.length > max || (!allowEmpty && value.trim() === '')) {
168
+ throw invalid(field + ' must be text of 1 to ' + String(max) + ' characters.', field);
169
+ }
170
+ return value.trim();
171
+ }
172
+ /**
173
+ * Validate one recipe from a tool call or a saved guide file.
174
+ * @param value the candidate.
175
+ * @param field the field path for errors.
176
+ * @returns the recipe.
177
+ */
178
+ export function parseRecipe(value, field = 'recipe') {
179
+ if (!isFields(value))
180
+ throw invalid(field + ' must be an object.', field);
181
+ const id = value.id;
182
+ if (typeof id !== 'string' || !RECIPE_ID.test(id)) {
183
+ throw invalid(field + '.id must be 2 to 40 lowercase letters, digits, or hyphens, starting with a letter.', field + '.id');
184
+ }
185
+ const types = value.types;
186
+ const recipeTypes = ['page', 'doc', 'design'];
187
+ if (!Array.isArray(types) || types.length === 0 || !types.every((type) => isArtifactType(type) && recipeTypes.includes(type))) {
188
+ throw invalid(field + '.types must list one or more of page, doc, design; sheets do not use recipes.', field + '.types');
189
+ }
190
+ const rawSections = value.sections ?? [];
191
+ if (!Array.isArray(rawSections) || rawSections.length > 20)
192
+ throw invalid(field + '.sections must be a list of up to 20 sections.', field + '.sections');
193
+ const keys = new Set();
194
+ const sections = rawSections.map((item, index) => {
195
+ const at = field + '.sections[' + String(index) + ']';
196
+ if (!isFields(item))
197
+ throw invalid(at + ' must be an object.', at);
198
+ const key = item.key;
199
+ if (typeof key !== 'string' || !SECTION_KEY.test(key) || keys.has(key)) {
200
+ throw invalid(at + '.key must be a unique lowercase key such as "scope".', at + '.key');
201
+ }
202
+ keys.add(key);
203
+ if (item.required !== undefined && typeof item.required !== 'boolean')
204
+ throw invalid(at + '.required must be true or false.', at + '.required');
205
+ return {
206
+ key,
207
+ title: text(item.title, at + '.title', 80),
208
+ purpose: text(item.purpose ?? '', at + '.purpose', 400, true),
209
+ required: item.required !== false,
210
+ };
211
+ });
212
+ const rawRules = value.rules ?? [];
213
+ if (!Array.isArray(rawRules) || rawRules.length > 20)
214
+ throw invalid(field + '.rules must be a list of up to 20 rules.', field + '.rules');
215
+ return {
216
+ id,
217
+ name: text(value.name, field + '.name', 80),
218
+ types: [...new Set(types)],
219
+ audience: text(value.audience ?? '', field + '.audience', 300, true),
220
+ purpose: text(value.purpose, field + '.purpose', 400),
221
+ sections,
222
+ rules: rawRules.map((rule, index) => text(rule, field + '.rules[' + String(index) + ']', 400)),
223
+ };
224
+ }