@inneranimalmedia/primetech-procedures 0.0.0-stage → 2.6.19

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 (76) hide show
  1. package/.codex-plugin/plugin.json +39 -0
  2. package/LICENSE +110 -0
  3. package/README.md +181 -2
  4. package/agents/openai.yaml +6 -0
  5. package/agentsam.package.json +80 -0
  6. package/assets/architect-icon.svg +10 -0
  7. package/assets/primetech-design-studio.svg +7 -0
  8. package/companion.json +40 -0
  9. package/package.json +56 -4
  10. package/plugin.README.md +37 -0
  11. package/plugin.json +43 -0
  12. package/procedures/arch.assembly.calculate/procedure.json +83 -0
  13. package/procedures/cad.motor-bearing-end-plate/README.md +21 -0
  14. package/procedures/cad.motor-bearing-end-plate/build_freecad.py +514 -0
  15. package/procedures/cad.motor-bearing-end-plate/finalize_bundle.py +26 -0
  16. package/procedures/cad.motor-bearing-end-plate/generate_assets.py +284 -0
  17. package/procedures/cad.motor-bearing-end-plate/generate_toolpaths.py +715 -0
  18. package/procedures/cad.motor-bearing-end-plate/package_artifacts.py +154 -0
  19. package/procedures/cad.motor-bearing-end-plate/parameters.json +51 -0
  20. package/procedures/cad.motor-bearing-end-plate/procedure.json +101 -0
  21. package/procedures/cad.motor-bearing-end-plate/render_preview.py +98 -0
  22. package/procedures/cad.motor-bearing-end-plate/run.py +214 -0
  23. package/procedures/cad.motor-bearing-end-plate/test_generate_toolpaths.py +50 -0
  24. package/procedures/media.asset.preflight/procedure.json +85 -0
  25. package/procedures/media.image.optimize-asset/procedure.json +102 -0
  26. package/procedures/primetech.assets.package/procedure.json +63 -0
  27. package/procedures/primetech.design-system.package/procedure.json +58 -0
  28. package/procedures/primetech.ebook.package/procedure.json +53 -0
  29. package/procedures/primetech.icon-family.build/procedure.json +101 -0
  30. package/procedures/primetech.production-board.manage/procedure.json +156 -0
  31. package/procedures/primetech.sprite-atlas.build/procedure.json +86 -0
  32. package/procedures/primetech.typeface.package/procedure.json +61 -0
  33. package/procedures/primetech.visuals.compare/procedure.json +74 -0
  34. package/procedures/repo.asset.inventory/procedure.json +65 -0
  35. package/procedures/repo.asset.inventory/run.py +116 -0
  36. package/procedures/repo.asset.inventory/run.sh +11 -0
  37. package/procedures/repo.git.status/procedure.json +58 -0
  38. package/procedures/repo.git.status/run.sh +10 -0
  39. package/profiles/PRIMETECH_PROCEDURE_ENGINEER.md +25 -0
  40. package/scripts/generate-procedures.py +112 -0
  41. package/scripts/generate-skills.py +425 -0
  42. package/scripts/package-openai-plugin.py +94 -0
  43. package/skills/primetech-brand-kit/SKILL.md +40 -0
  44. package/skills/primetech-brand-kit/agentsam.skill.json +64 -0
  45. package/skills/primetech-character-sprites/SKILL.md +40 -0
  46. package/skills/primetech-character-sprites/agentsam.skill.json +64 -0
  47. package/skills/primetech-creative-delivery/SKILL.md +39 -0
  48. package/skills/primetech-creative-delivery/agentsam.skill.json +57 -0
  49. package/skills/primetech-design-systems/SKILL.md +43 -0
  50. package/skills/primetech-design-systems/agentsam.skill.json +57 -0
  51. package/skills/primetech-digital-publishing/SKILL.md +39 -0
  52. package/skills/primetech-digital-publishing/agentsam.skill.json +52 -0
  53. package/skills/primetech-iconography/SKILL.md +40 -0
  54. package/skills/primetech-iconography/agentsam.skill.json +53 -0
  55. package/skills/primetech-type-design/SKILL.md +40 -0
  56. package/skills/primetech-type-design/agentsam.skill.json +53 -0
  57. package/skills/primetech-ui-ux-prototypes/SKILL.md +43 -0
  58. package/skills/primetech-ui-ux-prototypes/agentsam.skill.json +64 -0
  59. package/skills/primetech-visual-qa/SKILL.md +39 -0
  60. package/skills/primetech-visual-qa/agentsam.skill.json +56 -0
  61. package/src/creative/asset-package.js +42 -0
  62. package/src/creative/design-system.js +107 -0
  63. package/src/creative/ebook.js +88 -0
  64. package/src/creative/icon-family.js +125 -0
  65. package/src/creative/index.d.ts +157 -0
  66. package/src/creative/index.js +7 -0
  67. package/src/creative/paths.js +64 -0
  68. package/src/creative/sprite-atlas.js +100 -0
  69. package/src/creative/typeface.js +154 -0
  70. package/src/creative/visual-qa.js +88 -0
  71. package/src/index.d.ts +160 -0
  72. package/src/index.js +656 -0
  73. package/src/production-board.d.ts +103 -0
  74. package/src/production-board.js +181 -0
  75. package/src/skills.d.ts +48 -0
  76. package/src/skills.js +101 -0
@@ -0,0 +1,157 @@
1
+ /** TypeScript declarations for PrimeTech creative-production builders. */
2
+ export interface CreativeOperationResult { ok: true; [key: string]: unknown; }
3
+ export type IconColorwayId = 'technical-slate' | 'lagoon' | 'industrial-ember' | 'alloy-blue' | 'prime-electric' | 'prime-spectrum' | 'reverse' | 'core-mono';
4
+ export interface IconColorway {
5
+ id: IconColorwayId;
6
+ foreground: string;
7
+ background: string;
8
+ sourceColorMap?: Record<string, string>;
9
+ markInset?: number;
10
+ }
11
+ export interface IconFamilyOutput {
12
+ path: string;
13
+ contentType: 'image/svg+xml' | 'image/png';
14
+ bytes: number;
15
+ sha256: string;
16
+ colorway: IconColorwayId;
17
+ shape: 'bare' | 'circle' | 'squircle';
18
+ size?: number;
19
+ quality?: { transparentCorners: boolean; visiblePixelCount: number };
20
+ }
21
+ export interface IconFamilyResult extends CreativeOperationResult {
22
+ schema: 'primetech.icon-family.v1';
23
+ outputDir: string;
24
+ variantCount: number;
25
+ outputCount: number;
26
+ sourceSha256: string;
27
+ manifestPath: string;
28
+ manifestSha256: string;
29
+ outputs: IconFamilyOutput[];
30
+ }
31
+ export interface BuildIconFamilyOptions {
32
+ projectRoot: string;
33
+ sourceSvgPath: string;
34
+ outputDir?: string;
35
+ colorways: IconColorway[];
36
+ sizes?: number[];
37
+ }
38
+ export interface BuildTypefacePackageOptions {
39
+ projectRoot: string;
40
+ sourcePath: string;
41
+ outputDir?: string;
42
+ licenseText?: string | null;
43
+ specimenText?: string | null;
44
+ }
45
+ export interface TypefacePackageResult extends CreativeOperationResult {
46
+ schema: 'agentsam.typeface-package.v1';
47
+ family: string;
48
+ style: string;
49
+ glyphCount: number;
50
+ format: 'ttf';
51
+ variableFont: false;
52
+ fontPath: string;
53
+ packagePath: string;
54
+ packageBytes: number;
55
+ packageSha256: string;
56
+ manifestPath: string;
57
+ license: 'included' | 'not-supplied';
58
+ }
59
+ export interface BuildSpriteAtlasOptions {
60
+ projectRoot: string;
61
+ framePaths: string[];
62
+ outputDir?: string;
63
+ columns?: number | null;
64
+ cellWidth?: number | null;
65
+ cellHeight?: number | null;
66
+ padding?: number;
67
+ fps?: number;
68
+ loop?: boolean;
69
+ pivot?: [number, number];
70
+ }
71
+ export interface SpriteAtlasResult extends CreativeOperationResult {
72
+ schema: string;
73
+ frameCount: number;
74
+ fps: number;
75
+ atlasPath: string;
76
+ atlasSha256: string;
77
+ manifestPath: string;
78
+ previewPath: string;
79
+ width: number;
80
+ height: number;
81
+ quality: Record<string, unknown>;
82
+ }
83
+ export interface CompareVisualsOptions {
84
+ projectRoot: string;
85
+ referencePath: string;
86
+ renderedPath: string;
87
+ outputDir?: string;
88
+ pixelThreshold?: number;
89
+ maxMeanAbsoluteError?: number;
90
+ maxChangedPixelRatio?: number;
91
+ }
92
+ export interface VisualComparisonResult extends CreativeOperationResult {
93
+ status: string;
94
+ metrics: Record<string, number>;
95
+ reportPath: string;
96
+ diffPath: string;
97
+ overlayPath: string;
98
+ report: Record<string, unknown>;
99
+ }
100
+ export interface BuildDesignSystemPackageOptions {
101
+ projectRoot: string;
102
+ tokensPath: string;
103
+ outputDir?: string;
104
+ projectName?: string;
105
+ }
106
+ export interface DesignSystemPackageResult extends CreativeOperationResult {
107
+ status: string;
108
+ outputDir: string;
109
+ tokenCount: number;
110
+ warnings: string[];
111
+ cssPath: string;
112
+ normalizedPath: string;
113
+ tailwindPath: string;
114
+ manifestPath: string;
115
+ }
116
+ export interface CreativeDeliveryFile { path: string; archivePath?: string; role?: string; }
117
+ export interface PackageCreativeAssetsOptions {
118
+ projectRoot: string;
119
+ name: string;
120
+ files: CreativeDeliveryFile[];
121
+ outputDir?: string;
122
+ metadata?: Record<string, unknown>;
123
+ includeReadme?: boolean;
124
+ }
125
+ export interface CreativeAssetPackageResult extends CreativeOperationResult {
126
+ packageName: string;
127
+ fileCount: number;
128
+ totalBytes: number;
129
+ packagePath: string;
130
+ packageBytes: number;
131
+ packageSha256: string;
132
+ manifestPath: string;
133
+ files: Array<Record<string, unknown>>;
134
+ }
135
+ export interface BuildEpubPackageOptions { projectRoot: string; sourcePath: string; outputDir?: string; }
136
+ export interface EpubPackageResult extends CreativeOperationResult {
137
+ format: 'epub-3';
138
+ title: string;
139
+ author: string;
140
+ chapterCount: number;
141
+ epubPath: string;
142
+ epubBytes: number;
143
+ epubSha256: string;
144
+ previewPath: string;
145
+ manifestPath: string;
146
+ validation: { mimetype: true; container: boolean; packageDocument: true; navigation: true };
147
+ }
148
+ export const PRIMETECH_ICON_COLORWAY_IDS: readonly IconColorwayId[];
149
+ export const PRIMETECH_ICON_SHAPES: readonly ('bare' | 'circle' | 'squircle')[];
150
+ export const PRIMETECH_ICON_SIZES: readonly number[];
151
+ export function buildIconFamily(options: BuildIconFamilyOptions): Promise<IconFamilyResult>;
152
+ export function buildTypefacePackage(options: BuildTypefacePackageOptions): Promise<TypefacePackageResult>;
153
+ export function buildSpriteAtlas(options: BuildSpriteAtlasOptions): Promise<SpriteAtlasResult>;
154
+ export function compareVisuals(options: CompareVisualsOptions): Promise<VisualComparisonResult>;
155
+ export function buildDesignSystemPackage(options: BuildDesignSystemPackageOptions): Promise<DesignSystemPackageResult>;
156
+ export function packageCreativeAssets(options: PackageCreativeAssetsOptions): Promise<CreativeAssetPackageResult>;
157
+ export function buildEpubPackage(options: BuildEpubPackageOptions): Promise<EpubPackageResult>;
@@ -0,0 +1,7 @@
1
+ export { buildIconFamily, PRIMETECH_ICON_COLORWAY_IDS, PRIMETECH_ICON_SHAPES, PRIMETECH_ICON_SIZES } from './icon-family.js';
2
+ export { buildTypefacePackage } from './typeface.js';
3
+ export { buildSpriteAtlas } from './sprite-atlas.js';
4
+ export { compareVisuals } from './visual-qa.js';
5
+ export { buildDesignSystemPackage } from './design-system.js';
6
+ export { packageCreativeAssets } from './asset-package.js';
7
+ export { buildEpubPackage } from './ebook.js';
@@ -0,0 +1,64 @@
1
+ import fs from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import crypto from 'node:crypto';
4
+
5
+ export function sha256(bytes) {
6
+ return crypto.createHash('sha256').update(bytes).digest('hex');
7
+ }
8
+
9
+ export function safeSlug(value, label = 'value') {
10
+ const slug = String(value || '').trim().toLowerCase();
11
+ if (!/^[a-z0-9][a-z0-9-]{0,79}$/.test(slug)) {
12
+ const error = new Error(`${label}_invalid`);
13
+ error.code = `${label}_invalid`;
14
+ throw error;
15
+ }
16
+ return slug;
17
+ }
18
+
19
+ export function resolveProjectPath(projectRoot, relativePath) {
20
+ if (typeof projectRoot !== 'string' || !path.isAbsolute(projectRoot)) throw new Error('absolute_project_root_required');
21
+ if (typeof relativePath !== 'string' || !relativePath.trim() || path.isAbsolute(relativePath)) throw new Error('project_relative_path_required');
22
+ const root = path.resolve(projectRoot);
23
+ const candidate = path.resolve(root, relativePath);
24
+ const rel = path.relative(root, candidate);
25
+ if (!rel || rel.startsWith('..') || path.isAbsolute(rel)) throw new Error('project_path_outside_root');
26
+ return candidate;
27
+ }
28
+
29
+ export async function readProjectFile(projectRoot, relativePath, maxBytes = 64 * 1024 * 1024) {
30
+ const candidate = resolveProjectPath(projectRoot, relativePath);
31
+ const realRoot = await fs.realpath(projectRoot);
32
+ const realPath = await fs.realpath(candidate);
33
+ const rel = path.relative(realRoot, realPath);
34
+ if (!rel || rel.startsWith('..') || path.isAbsolute(rel)) throw new Error('project_path_symlink_escape');
35
+ const stat = await fs.stat(realPath);
36
+ if (!stat.isFile() || stat.size < 1 || stat.size > maxBytes) throw new Error('project_file_invalid_or_oversized');
37
+ return { path: realPath, bytes: await fs.readFile(realPath), stat };
38
+ }
39
+
40
+ export async function ensureProjectDirectory(projectRoot, relativePath) {
41
+ const candidate = resolveProjectPath(projectRoot, relativePath);
42
+ await fs.mkdir(candidate, { recursive: true, mode: 0o700 });
43
+ const realRoot = await fs.realpath(projectRoot);
44
+ const realPath = await fs.realpath(candidate);
45
+ const rel = path.relative(realRoot, realPath);
46
+ if (!rel || rel.startsWith('..') || path.isAbsolute(rel)) throw new Error('project_output_path_symlink_escape');
47
+ return realPath;
48
+ }
49
+
50
+ export async function writeFileAtomic(targetPath, bytes, mode = 0o600) {
51
+ const dir = path.dirname(targetPath);
52
+ await fs.mkdir(dir, { recursive: true, mode: 0o700 });
53
+ const temp = `${targetPath}.${crypto.randomUUID()}.tmp`;
54
+ try {
55
+ await fs.writeFile(temp, bytes, { flag: 'wx', mode });
56
+ await fs.rename(temp, targetPath);
57
+ } finally {
58
+ await fs.rm(temp, { force: true }).catch(() => {});
59
+ }
60
+ }
61
+
62
+ export async function writeJsonAtomic(targetPath, value) {
63
+ await writeFileAtomic(targetPath, `${JSON.stringify(value, null, 2)}\n`, 0o600);
64
+ }
@@ -0,0 +1,100 @@
1
+ import fs from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import sharp from 'sharp';
4
+ import { ensureProjectDirectory, readProjectFile, sha256, writeJsonAtomic } from './paths.js';
5
+
6
+ function htmlEscape(value) {
7
+ return String(value).replace(/[&<>"']/g, char => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[char]);
8
+ }
9
+
10
+ export async function buildSpriteAtlas({
11
+ projectRoot,
12
+ framePaths,
13
+ outputDir = '.agentsam/primetech/companions/sprite-atlas',
14
+ columns = null,
15
+ cellWidth = null,
16
+ cellHeight = null,
17
+ padding = 0,
18
+ fps = 12,
19
+ loop = true,
20
+ pivot = [0.5, 0.5],
21
+ } = {}) {
22
+ if (!Array.isArray(framePaths) || framePaths.length < 2 || framePaths.length > 256) throw new Error('sprite_atlas_frame_count_invalid');
23
+ if (!Number.isInteger(fps) || fps < 1 || fps > 60) throw new Error('sprite_atlas_fps_invalid');
24
+ if (!Number.isInteger(padding) || padding < 0 || padding > 64) throw new Error('sprite_atlas_padding_invalid');
25
+ if (!Array.isArray(pivot) || pivot.length !== 2 || pivot.some(value => !Number.isFinite(value) || value < 0 || value > 1)) throw new Error('sprite_atlas_pivot_invalid');
26
+ const sources = [];
27
+ for (const framePath of framePaths) {
28
+ const row = await readProjectFile(projectRoot, framePath, 32 * 1024 * 1024);
29
+ const metadata = await sharp(row.bytes, { failOn: 'warning' }).metadata();
30
+ if (!metadata.width || !metadata.height || metadata.width > 8192 || metadata.height > 8192) throw new Error(`sprite_frame_dimensions_invalid:${framePath}`);
31
+ sources.push({ path: framePath, bytes: row.bytes, width: metadata.width, height: metadata.height, sha256: sha256(row.bytes) });
32
+ }
33
+ const maxWidth = Math.max(...sources.map(frame => frame.width));
34
+ const maxHeight = Math.max(...sources.map(frame => frame.height));
35
+ const cw = cellWidth ?? maxWidth;
36
+ const ch = cellHeight ?? maxHeight;
37
+ if (!Number.isInteger(cw) || !Number.isInteger(ch) || cw < 16 || ch < 16 || cw > 2048 || ch > 2048) throw new Error('sprite_atlas_cell_dimensions_invalid');
38
+ const colCount = columns ?? Math.ceil(Math.sqrt(sources.length));
39
+ if (!Number.isInteger(colCount) || colCount < 1 || colCount > sources.length) throw new Error('sprite_atlas_columns_invalid');
40
+ const rowCount = Math.ceil(sources.length / colCount);
41
+ const width = colCount * cw + (colCount + 1) * padding;
42
+ const height = rowCount * ch + (rowCount + 1) * padding;
43
+ if (width > 8192 || height > 8192 || width * height > 64_000_000) throw new Error('sprite_atlas_output_dimensions_exceeded');
44
+ const composites = [];
45
+ const frames = [];
46
+ for (let index = 0; index < sources.length; index += 1) {
47
+ const source = sources[index];
48
+ const x = padding + (index % colCount) * (cw + padding);
49
+ const y = padding + Math.floor(index / colCount) * (ch + padding);
50
+ const normalized = await sharp(source.bytes, { failOn: 'warning' })
51
+ .rotate()
52
+ .resize(cw, ch, { fit: 'contain', background: { r: 0, g: 0, b: 0, alpha: 0 } })
53
+ .png({ compressionLevel: 9 })
54
+ .toBuffer();
55
+ composites.push({ input: normalized, left: x, top: y });
56
+ frames.push({
57
+ index,
58
+ sourcePath: source.path,
59
+ sourceSha256: source.sha256,
60
+ x, y, width: cw, height: ch,
61
+ durationMs: Math.round(1000 / fps),
62
+ pivot: { x: pivot[0], y: pivot[1] },
63
+ });
64
+ }
65
+ const root = await ensureProjectDirectory(projectRoot, outputDir);
66
+ const atlasPath = path.join(root, 'atlas.png');
67
+ const atlasBytes = await sharp({ create: { width, height, channels: 4, background: { r: 0, g: 0, b: 0, alpha: 0 } } })
68
+ .composite(composites)
69
+ .png({ compressionLevel: 9, adaptiveFiltering: true })
70
+ .toBuffer();
71
+ await fs.writeFile(atlasPath, atlasBytes, { mode: 0o600 });
72
+ const manifest = {
73
+ schema: 'agentsam.sprite-atlas.v1',
74
+ frameCount: frames.length,
75
+ fps,
76
+ loop: Boolean(loop),
77
+ atlas: { path: 'atlas.png', width, height, bytes: atlasBytes.length, sha256: sha256(atlasBytes) },
78
+ cell: { width: cw, height: ch, padding },
79
+ grid: { columns: colCount, rows: rowCount },
80
+ frames,
81
+ quality: { allFramesPlaced: frames.length === sources.length, frameOverflow: false, sourceFramesPreserved: true },
82
+ };
83
+ const manifestPath = path.join(root, 'atlas.json');
84
+ await writeJsonAtomic(manifestPath, manifest);
85
+ const preview = `<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Sprite atlas preview</title><style>body{font:14px system-ui;background:#171a1d;color:#e9ecef;padding:24px}canvas{image-rendering:pixelated;max-width:min(80vw,640px);background:repeating-conic-gradient(#252a30 0 25%,#1e2328 0 50%) 50%/24px 24px;border:1px solid #50575f}button{padding:8px 12px;margin:8px 6px 8px 0}</style><h1>${htmlEscape(path.basename(root))}</h1><canvas id="view" width="${cw}" height="${ch}"></canvas><p><button id="play">Pause</button><button id="step">Next frame</button><span id="status"></span></p><script>const atlas=new Image();atlas.src='atlas.png';const data=${JSON.stringify({ frames, cw, ch, fps, loop, width, height })};const canvas=document.querySelector('#view'),ctx=canvas.getContext('2d');let index=0,playing=true,last=0;function draw(){const f=data.frames[index];ctx.clearRect(0,0,canvas.width,canvas.height);ctx.drawImage(atlas,f.x,f.y,f.width,f.height,0,0,canvas.width,canvas.height);document.querySelector('#status').textContent='Frame '+(index+1)+' / '+data.frames.length;}function tick(t){if(playing&&t-last>=1000/data.fps){index++;if(index>=data.frames.length)index=data.loop?0:data.frames.length-1;last=t;draw();}requestAnimationFrame(tick);}atlas.onload=()=>{draw();requestAnimationFrame(tick);};document.querySelector('#play').onclick=()=>{playing=!playing;document.querySelector('#play').textContent=playing?'Pause':'Play';};document.querySelector('#step').onclick=()=>{index=(index+1)%data.frames.length;draw();};</script></html>`;
86
+ const previewPath = path.join(root, 'preview.html');
87
+ await fs.writeFile(previewPath, preview, { mode: 0o600 });
88
+ return {
89
+ ok: true,
90
+ schema: manifest.schema,
91
+ frameCount: frames.length,
92
+ fps,
93
+ atlasPath: path.relative(projectRoot, atlasPath),
94
+ atlasSha256: sha256(atlasBytes),
95
+ manifestPath: path.relative(projectRoot, manifestPath),
96
+ previewPath: path.relative(projectRoot, previewPath),
97
+ width, height,
98
+ quality: manifest.quality,
99
+ };
100
+ }
@@ -0,0 +1,154 @@
1
+ import fs from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import opentype from 'opentype.js';
4
+ import { zipSync } from 'fflate';
5
+ import { ensureProjectDirectory, readProjectFile, sha256, writeJsonAtomic } from './paths.js';
6
+
7
+ function signedArea(points) {
8
+ return points.reduce((sum, point, index) => {
9
+ const next = points[(index + 1) % points.length];
10
+ return sum + point[0] * next[1] - next[0] * point[1];
11
+ }, 0) / 2;
12
+ }
13
+
14
+ function validateTypefaceDocument(doc) {
15
+ if (!doc || typeof doc !== 'object' || doc.schemaVersion !== 1) throw new Error('typeface_document_schema_invalid');
16
+ if (typeof doc.familyName !== 'string' || !doc.familyName.trim() || doc.familyName.length > 80) throw new Error('typeface_family_name_invalid');
17
+ if (typeof doc.styleName !== 'string' || !doc.styleName.trim() || doc.styleName.length > 40) throw new Error('typeface_style_name_invalid');
18
+ if (!Number.isInteger(doc.unitsPerEm) || doc.unitsPerEm < 256 || doc.unitsPerEm > 4096) throw new Error('typeface_units_per_em_invalid');
19
+ if (!doc.metrics || !Number.isFinite(doc.metrics.ascender) || !Number.isFinite(doc.metrics.descender) || doc.metrics.ascender <= 0 || doc.metrics.descender >= 0) throw new Error('typeface_metrics_invalid');
20
+ if (!doc.glyphs || typeof doc.glyphs !== 'object' || Array.isArray(doc.glyphs)) throw new Error('typeface_glyphs_required');
21
+ const glyphs = Object.values(doc.glyphs);
22
+ if (!glyphs.length || glyphs.length > 2048) throw new Error('typeface_glyph_count_invalid');
23
+ const unicodes = new Set();
24
+ for (const glyph of glyphs) {
25
+ if (!glyph || typeof glyph.name !== 'string' || !/^[A-Za-z0-9_.-]{1,40}$/.test(glyph.name)) throw new Error('typeface_glyph_name_invalid');
26
+ if (!Number.isInteger(glyph.unicode) || glyph.unicode < 1 || glyph.unicode > 0x10ffff || unicodes.has(glyph.unicode)) throw new Error('typeface_glyph_unicode_invalid');
27
+ unicodes.add(glyph.unicode);
28
+ if (!Number.isFinite(glyph.advanceWidth) || glyph.advanceWidth < 1 || glyph.advanceWidth > doc.unitsPerEm * 8) throw new Error(`typeface_glyph_advance_invalid:${glyph.name}`);
29
+ if (!Array.isArray(glyph.contours)) throw new Error(`typeface_glyph_contours_invalid:${glyph.name}`);
30
+ for (const contour of glyph.contours) {
31
+ if (!Array.isArray(contour.points) || contour.points.length < 3 || contour.points.length > 4096) throw new Error(`typeface_contour_invalid:${glyph.name}`);
32
+ for (const point of contour.points) {
33
+ if (!Array.isArray(point) || point.length !== 2 || point.some(value => !Number.isFinite(value) || Math.abs(value) > doc.unitsPerEm * 8)) throw new Error(`typeface_point_invalid:${glyph.name}`);
34
+ }
35
+ }
36
+ }
37
+ return { glyphCount: glyphs.length, unicodes: [...unicodes].sort((a, b) => a - b) };
38
+ }
39
+
40
+ function makeGlyphPath(contours) {
41
+ const path = new opentype.Path();
42
+ for (const contour of contours || []) {
43
+ if (contour.points.length < 3) continue;
44
+ const positive = Boolean(contour.hole);
45
+ const points = (signedArea(contour.points) > 0) === positive ? contour.points : [...contour.points].reverse();
46
+ path.moveTo(points[0][0], points[0][1]);
47
+ for (const [x, y] of points.slice(1)) path.lineTo(x, y);
48
+ path.close();
49
+ }
50
+ return path;
51
+ }
52
+
53
+ function buildFont(doc) {
54
+ const notdef = new opentype.Path();
55
+ const em = doc.unitsPerEm;
56
+ notdef.moveTo(em * 0.08, 0); notdef.lineTo(em * 0.08, em * 0.72);
57
+ notdef.lineTo(em * 0.62, em * 0.72); notdef.lineTo(em * 0.62, 0); notdef.close();
58
+ notdef.moveTo(em * 0.17, em * 0.09); notdef.lineTo(em * 0.53, em * 0.09);
59
+ notdef.lineTo(em * 0.53, em * 0.63); notdef.lineTo(em * 0.17, em * 0.63); notdef.close();
60
+ const glyphs = [new opentype.Glyph({ name: '.notdef', unicode: 0, advanceWidth: Math.round(em * 0.72), path: notdef })];
61
+ for (const glyph of Object.values(doc.glyphs).sort((a, b) => a.unicode - b.unicode)) {
62
+ glyphs.push(new opentype.Glyph({
63
+ name: glyph.name,
64
+ unicode: glyph.unicode,
65
+ advanceWidth: Math.max(1, Math.round(glyph.advanceWidth)),
66
+ path: makeGlyphPath(glyph.contours),
67
+ }));
68
+ }
69
+ return new opentype.Font({
70
+ familyName: doc.familyName,
71
+ styleName: doc.styleName,
72
+ unitsPerEm: doc.unitsPerEm,
73
+ ascender: Math.round(doc.metrics.ascender),
74
+ descender: Math.round(doc.metrics.descender),
75
+ glyphs,
76
+ });
77
+ }
78
+
79
+ function escapeHtml(value) {
80
+ return String(value).replace(/[&<>"']/g, char => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[char]);
81
+ }
82
+
83
+ export async function buildTypefacePackage({ projectRoot, sourcePath, outputDir = '.agentsam/primetech/typefaces', licenseText = null, specimenText = null } = {}) {
84
+ const source = await readProjectFile(projectRoot, sourcePath, 32 * 1024 * 1024);
85
+ let doc;
86
+ try { doc = JSON.parse(source.bytes.toString('utf8')); } catch { throw new Error('typeface_source_json_invalid'); }
87
+ const validation = validateTypefaceDocument(doc);
88
+ const font = buildFont(doc);
89
+ const fontBytes = Buffer.from(font.toArrayBuffer());
90
+ const parsed = opentype.parse(fontBytes.buffer.slice(fontBytes.byteOffset, fontBytes.byteOffset + fontBytes.byteLength));
91
+ if (parsed.glyphs.length !== validation.glyphCount + 1) throw new Error('typeface_ttf_glyph_count_mismatch');
92
+ for (const unicode of validation.unicodes) {
93
+ const glyph = parsed.charToGlyph(String.fromCodePoint(unicode));
94
+ if (!glyph || glyph.index < 1) throw new Error(`typeface_ttf_cmap_missing:${unicode}`);
95
+ }
96
+ const root = await ensureProjectDirectory(projectRoot, outputDir);
97
+ const slug = doc.familyName.trim().toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '') || 'custom-typeface';
98
+ const fontName = `${slug}-${doc.styleName.toLowerCase().replace(/[^a-z0-9]+/g, '-')}.ttf`;
99
+ const fontRel = `fonts/${fontName}`;
100
+ const sourceRel = 'source/typeface.source.json';
101
+ const specimenRel = 'specimen.html';
102
+ const fontDir = path.join(root, 'fonts');
103
+ const sourceDir = path.join(root, 'source');
104
+ await fs.mkdir(fontDir, { recursive: true, mode: 0o700 });
105
+ await fs.mkdir(sourceDir, { recursive: true, mode: 0o700 });
106
+ await fs.writeFile(path.join(root, fontRel), fontBytes, { mode: 0o600 });
107
+ await fs.writeFile(path.join(root, sourceRel), source.bytes, { mode: 0o600 });
108
+ const characters = validation.unicodes.map(code => String.fromCodePoint(code)).join('');
109
+ const sample = specimenText || `${doc.familyName} ${doc.styleName}\n${characters}`;
110
+ const specimen = `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>${escapeHtml(doc.familyName)} specimen</title><style>@font-face{font-family:PrimeTechSpecimen;src:url('${fontRel}') format('truetype')}body{margin:48px;background:#f4f4f1;color:#171a18;font-family:PrimeTechSpecimen,serif}h1{font-size:48px;font-weight:400}pre{white-space:pre-wrap;font:inherit;font-size:28px;line-height:1.5}</style></head><body><h1>${escapeHtml(doc.familyName)} · ${escapeHtml(doc.styleName)}</h1><pre>${escapeHtml(sample)}</pre></body></html>`;
111
+ await fs.writeFile(path.join(root, specimenRel), specimen, { mode: 0o600 });
112
+ const files = {
113
+ [fontRel]: new Uint8Array(fontBytes),
114
+ [sourceRel]: new Uint8Array(source.bytes),
115
+ [specimenRel]: new TextEncoder().encode(specimen),
116
+ };
117
+ if (typeof licenseText === 'string' && licenseText.trim()) files['LICENSE.txt'] = new TextEncoder().encode(licenseText);
118
+ const manifest = {
119
+ schema: 'agentsam.typeface-package.v1',
120
+ family: doc.familyName,
121
+ style: doc.styleName,
122
+ version: doc.version || '1.0.0',
123
+ format: 'static-truetype',
124
+ variableFont: false,
125
+ glyphCount: validation.glyphCount,
126
+ unicodeCoverage: validation.unicodes,
127
+ unitsPerEm: doc.unitsPerEm,
128
+ metrics: doc.metrics,
129
+ source: { path: sourcePath, sha256: sha256(source.bytes), preserved: true },
130
+ font: { path: fontRel, bytes: fontBytes.length, sha256: sha256(fontBytes) },
131
+ specimen: specimenRel,
132
+ license: typeof licenseText === 'string' && licenseText.trim() ? 'included' : 'not-supplied',
133
+ };
134
+ files['manifest.json'] = new TextEncoder().encode(JSON.stringify(manifest, null, 2) + '\n');
135
+ const zipBytes = zipSync(files, { level: 8 });
136
+ const packagePath = path.join(root, `${slug}-${doc.styleName.toLowerCase().replace(/[^a-z0-9]+/g, '-')}-typeface.zip`);
137
+ await fs.writeFile(packagePath, zipBytes, { mode: 0o600 });
138
+ await writeJsonAtomic(path.join(root, 'manifest.json'), manifest);
139
+ return {
140
+ ok: true,
141
+ schema: manifest.schema,
142
+ family: doc.familyName,
143
+ style: doc.styleName,
144
+ glyphCount: validation.glyphCount,
145
+ format: 'ttf',
146
+ variableFont: false,
147
+ fontPath: path.relative(projectRoot, path.join(root, fontRel)),
148
+ packagePath: path.relative(projectRoot, packagePath),
149
+ packageBytes: zipBytes.length,
150
+ packageSha256: sha256(zipBytes),
151
+ manifestPath: path.relative(projectRoot, path.join(root, 'manifest.json')),
152
+ license: manifest.license,
153
+ };
154
+ }
@@ -0,0 +1,88 @@
1
+ import fs from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import sharp from 'sharp';
4
+ import { ensureProjectDirectory, readProjectFile, sha256, writeJsonAtomic } from './paths.js';
5
+
6
+ export async function compareVisuals({
7
+ projectRoot,
8
+ referencePath,
9
+ renderedPath,
10
+ outputDir = '.agentsam/primetech/qa/visual-comparison',
11
+ pixelThreshold = 24,
12
+ maxMeanAbsoluteError = 6,
13
+ maxChangedPixelRatio = 0.02,
14
+ } = {}) {
15
+ if (!Number.isInteger(pixelThreshold) || pixelThreshold < 1 || pixelThreshold > 255) throw new Error('visual_qa_pixel_threshold_invalid');
16
+ if (!Number.isFinite(maxMeanAbsoluteError) || maxMeanAbsoluteError < 0 || maxMeanAbsoluteError > 255) throw new Error('visual_qa_mae_threshold_invalid');
17
+ if (!Number.isFinite(maxChangedPixelRatio) || maxChangedPixelRatio < 0 || maxChangedPixelRatio > 1) throw new Error('visual_qa_changed_ratio_threshold_invalid');
18
+ const reference = await readProjectFile(projectRoot, referencePath, 64 * 1024 * 1024);
19
+ const rendered = await readProjectFile(projectRoot, renderedPath, 64 * 1024 * 1024);
20
+ const referenceMeta = await sharp(reference.bytes).metadata();
21
+ const renderedMeta = await sharp(rendered.bytes).metadata();
22
+ if (referenceMeta.width !== renderedMeta.width || referenceMeta.height !== renderedMeta.height) {
23
+ throw new Error(`visual_qa_dimensions_mismatch:${referenceMeta.width}x${referenceMeta.height}:${renderedMeta.width}x${renderedMeta.height}`);
24
+ }
25
+ const width = referenceMeta.width;
26
+ const height = referenceMeta.height;
27
+ if (!width || !height || width * height > 40_000_000) throw new Error('visual_qa_dimensions_invalid');
28
+ const ref = await sharp(reference.bytes).ensureAlpha().raw().toBuffer();
29
+ const out = await sharp(rendered.bytes).ensureAlpha().raw().toBuffer();
30
+ const diff = Buffer.alloc(width * height * 4);
31
+ let absoluteTotal = 0;
32
+ let squaredTotal = 0;
33
+ let changedPixels = 0;
34
+ const pixelErrors = new Array(width * height);
35
+ for (let pixel = 0; pixel < width * height; pixel += 1) {
36
+ const offset = pixel * 4;
37
+ const dr = Math.abs(ref[offset] - out[offset]);
38
+ const dg = Math.abs(ref[offset + 1] - out[offset + 1]);
39
+ const db = Math.abs(ref[offset + 2] - out[offset + 2]);
40
+ const da = Math.abs(ref[offset + 3] - out[offset + 3]);
41
+ const error = Math.max(dr, dg, db, da);
42
+ pixelErrors[pixel] = error;
43
+ absoluteTotal += dr + dg + db + da;
44
+ squaredTotal += dr * dr + dg * dg + db * db + da * da;
45
+ if (error >= pixelThreshold) {
46
+ changedPixels += 1;
47
+ diff[offset] = 255;
48
+ diff[offset + 1] = 24;
49
+ diff[offset + 2] = 24;
50
+ diff[offset + 3] = 210;
51
+ }
52
+ }
53
+ pixelErrors.sort((a, b) => a - b);
54
+ const channelCount = width * height * 4;
55
+ const mae = absoluteTotal / channelCount;
56
+ const rmse = Math.sqrt(squaredTotal / channelCount);
57
+ const changedRatio = changedPixels / (width * height);
58
+ const p95 = pixelErrors[Math.min(pixelErrors.length - 1, Math.floor(pixelErrors.length * 0.95))] || 0;
59
+ const diffPng = await sharp(diff, { raw: { width, height, channels: 4 } }).png().toBuffer();
60
+ const root = await ensureProjectDirectory(projectRoot, outputDir);
61
+ const diffPath = path.join(root, 'diff.png');
62
+ const overlayPath = path.join(root, 'overlay.png');
63
+ await fs.writeFile(diffPath, diffPng, { mode: 0o600 });
64
+ const overlay = await sharp(reference.bytes).ensureAlpha().composite([{ input: diffPng, blend: 'over' }]).png().toBuffer();
65
+ await fs.writeFile(overlayPath, overlay, { mode: 0o600 });
66
+ const passed = mae <= maxMeanAbsoluteError && changedRatio <= maxChangedPixelRatio;
67
+ const report = {
68
+ schema: 'agentsam.visual-qa-report.v1',
69
+ status: passed ? 'pass' : 'review',
70
+ reference: { path: referencePath, sha256: sha256(reference.bytes), width, height },
71
+ rendered: { path: renderedPath, sha256: sha256(rendered.bytes), width, height },
72
+ metrics: {
73
+ meanAbsoluteError: Number(mae.toFixed(4)),
74
+ rootMeanSquareError: Number(rmse.toFixed(4)),
75
+ changedPixelRatio: Number(changedRatio.toFixed(6)),
76
+ changedPixels,
77
+ totalPixels: width * height,
78
+ p95PixelError: p95,
79
+ pixelThreshold,
80
+ },
81
+ thresholds: { maxMeanAbsoluteError, maxChangedPixelRatio },
82
+ evidence: { diffPath: 'diff.png', diffSha256: sha256(diffPng), overlayPath: 'overlay.png', overlaySha256: sha256(overlay) },
83
+ interpretation: 'Pixel comparison only. It does not judge semantic quality, typography, layout intent, or accessibility.',
84
+ };
85
+ const reportPath = path.join(root, 'report.json');
86
+ await writeJsonAtomic(reportPath, report);
87
+ return { ok: true, status: report.status, metrics: report.metrics, reportPath: path.relative(projectRoot, reportPath), diffPath: path.relative(projectRoot, diffPath), overlayPath: path.relative(projectRoot, overlayPath), report };
88
+ }