@archangel70/cosmo 1.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.
- package/CHANGELOG.md +31 -0
- package/README.md +792 -0
- package/SECURITY.md +15 -0
- package/docs/AGENT-HANDOFF.md +44 -0
- package/docs/ARCHITECTURE-INTELLIGENCE.md +64 -0
- package/docs/ARCHITECTURE.md +97 -0
- package/docs/BRAND-DISCOVERY.md +12 -0
- package/docs/BROWSER-QA.md +40 -0
- package/docs/CLAUDE-LAUNCHER.md +72 -0
- package/docs/CONTENT-QA.md +62 -0
- package/docs/DELIVERY.md +40 -0
- package/docs/DEPLOYMENT.md +119 -0
- package/docs/FIRST-PARTY-CAPABILITIES.md +54 -0
- package/docs/GENERATION.md +81 -0
- package/docs/INTEGRITY.md +75 -0
- package/docs/INTELLIGENCE-PACKS.md +122 -0
- package/docs/OPERATIONS.md +7 -0
- package/docs/PAGE-PRODUCTION.md +81 -0
- package/docs/ROADMAP.md +184 -0
- package/docs/WORKFLOWS.md +71 -0
- package/package.json +97 -0
- package/packages/cli/bin/cosmo.mjs +901 -0
- package/packages/cli/lib/adoption.mjs +72 -0
- package/packages/cli/lib/audit.mjs +145 -0
- package/packages/cli/lib/brand.mjs +60 -0
- package/packages/cli/lib/browser-audit.mjs +177 -0
- package/packages/cli/lib/claude-plugin.mjs +64 -0
- package/packages/cli/lib/content-audit.mjs +184 -0
- package/packages/cli/lib/delivery.mjs +140 -0
- package/packages/cli/lib/deployment.mjs +211 -0
- package/packages/cli/lib/doctor.mjs +42 -0
- package/packages/cli/lib/file-transfer.mjs +143 -0
- package/packages/cli/lib/generation.mjs +319 -0
- package/packages/cli/lib/handoff.mjs +109 -0
- package/packages/cli/lib/integrity.mjs +315 -0
- package/packages/cli/lib/intelligence-audit.mjs +445 -0
- package/packages/cli/lib/intelligence.mjs +331 -0
- package/packages/cli/lib/page-work.mjs +154 -0
- package/packages/cli/lib/plan.mjs +229 -0
- package/packages/cli/lib/process.mjs +45 -0
- package/packages/cli/lib/project.mjs +113 -0
- package/packages/cli/lib/research.mjs +85 -0
- package/packages/cli/lib/status.mjs +46 -0
- package/packages/cli/lib/workflow.mjs +294 -0
- package/plugins/claude-code/cosmo/.claude-plugin/plugin.json +10 -0
- package/plugins/claude-code/cosmo/README.md +25 -0
- package/plugins/claude-code/cosmo/bin/cosmo +11 -0
- package/plugins/claude-code/cosmo/skills/cosmo/SKILL.md +122 -0
- package/plugins/claude-code/cosmo/skills/cosmo-help/SKILL.md +16 -0
- package/scripts/postinstall.mjs +14 -0
- package/templates/astro-site/.cosmo/brand/discovery.json +19 -0
- package/templates/astro-site/.cosmo/brand/entity-canon.json +20 -0
- package/templates/astro-site/.cosmo/brand/voice-profile.json +16 -0
- package/templates/astro-site/.cosmo/build-plan.json +75 -0
- package/templates/astro-site/.cosmo/capabilities/registry.json +21 -0
- package/templates/astro-site/.cosmo/evidence.json +11 -0
- package/templates/astro-site/.cosmo/intelligence/selection.json +5 -0
- package/templates/astro-site/.cosmo/policies/content-integrity.json +22 -0
- package/templates/astro-site/.cosmo/project.json +10 -0
- package/templates/astro-site/.cosmo/work/pages/about/brief.json +49 -0
- package/templates/astro-site/.cosmo/work/pages/home/brief.json +51 -0
- package/templates/astro-site/.cosmo/workflows/default.json +146 -0
- package/templates/astro-site/.env.example +7 -0
- package/templates/astro-site/AGENTS.md +26 -0
- package/templates/astro-site/CLAUDE.md +28 -0
- package/templates/astro-site/DESIGN-DIRECTION.md +9 -0
- package/templates/astro-site/README.md +17 -0
- package/templates/astro-site/astro.config.mjs +16 -0
- package/templates/astro-site/cosmo.config.mjs +12 -0
- package/templates/astro-site/gitignore.template +9 -0
- package/templates/astro-site/package.json +23 -0
- package/templates/astro-site/public/favicon.svg +5 -0
- package/templates/astro-site/src/components/PageView.astro +20 -0
- package/templates/astro-site/src/components/sections/Action.astro +24 -0
- package/templates/astro-site/src/components/sections/Evidence.astro +19 -0
- package/templates/astro-site/src/components/sections/Hero.astro +41 -0
- package/templates/astro-site/src/components/sections/Problem.astro +19 -0
- package/templates/astro-site/src/components/sections/Proof.astro +15 -0
- package/templates/astro-site/src/components/sections/SectionRenderer.astro +22 -0
- package/templates/astro-site/src/components/sections/Solution.astro +19 -0
- package/templates/astro-site/src/components/seo/SeoHead.astro +41 -0
- package/templates/astro-site/src/content/pages/about.md +52 -0
- package/templates/astro-site/src/content/pages/home.md +48 -0
- package/templates/astro-site/src/content.config.ts +133 -0
- package/templates/astro-site/src/env.d.ts +1 -0
- package/templates/astro-site/src/layouts/BaseLayout.astro +57 -0
- package/templates/astro-site/src/pages/[...slug].astro +22 -0
- package/templates/astro-site/src/pages/index.astro +9 -0
- package/templates/astro-site/src/pages/robots.txt.ts +6 -0
- package/templates/astro-site/src/styles/global.css +540 -0
- package/templates/astro-site/src/styles/tokens.css +27 -0
- package/templates/astro-site/tsconfig.json +9 -0
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { applyIntelligenceProfile } from './intelligence.mjs';
|
|
4
|
+
import { slugify, writeJson } from './project.mjs';
|
|
5
|
+
|
|
6
|
+
const GOVERNANCE_PATHS = [
|
|
7
|
+
'.cosmo/brand',
|
|
8
|
+
'.cosmo/capabilities',
|
|
9
|
+
'.cosmo/intelligence/selection.json',
|
|
10
|
+
'.cosmo/policies',
|
|
11
|
+
'.cosmo/workflows',
|
|
12
|
+
];
|
|
13
|
+
|
|
14
|
+
function detectsAstro(target) {
|
|
15
|
+
const config = ['astro.config.mjs', 'astro.config.js', 'astro.config.ts', 'astro.config.cjs'].some((name) => fs.existsSync(path.join(target, name)));
|
|
16
|
+
const packageFile = path.join(target, 'package.json');
|
|
17
|
+
if (!fs.existsSync(packageFile)) return config;
|
|
18
|
+
const pkg = JSON.parse(fs.readFileSync(packageFile, 'utf8'));
|
|
19
|
+
return config || Boolean(pkg.dependencies?.astro || pkg.devDependencies?.astro);
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function copyPath(templateDirectory, target, relative) {
|
|
23
|
+
const source = path.join(templateDirectory, relative);
|
|
24
|
+
if (!fs.existsSync(source)) return;
|
|
25
|
+
fs.cpSync(source, path.join(target, relative), { recursive: true, errorOnExist: true, force: false });
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function installAgentGuide(templateDirectory, target, filename) {
|
|
29
|
+
const source = path.join(templateDirectory, filename);
|
|
30
|
+
if (!fs.existsSync(source)) return null;
|
|
31
|
+
const preferred = path.join(target, filename);
|
|
32
|
+
const destination = fs.existsSync(preferred) ? path.join(target, '.cosmo', `COSMO-${filename}`) : preferred;
|
|
33
|
+
fs.copyFileSync(source, destination, fs.constants.COPYFILE_EXCL);
|
|
34
|
+
return path.relative(target, destination);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export function adoptAstroProject(templateDirectory, target, options = {}) {
|
|
38
|
+
const resolved = path.resolve(target);
|
|
39
|
+
if (!fs.existsSync(resolved) || !fs.statSync(resolved).isDirectory()) throw new Error(`Project directory not found: ${resolved}`);
|
|
40
|
+
if (fs.existsSync(path.join(resolved, '.cosmo', 'project.json'))) throw new Error(`A Cosmo project already exists at ${resolved}`);
|
|
41
|
+
if (fs.existsSync(path.join(resolved, '.cosmo'))) throw new Error(`A .cosmo directory already exists at ${resolved}; inspect or move it before adoption.`);
|
|
42
|
+
if (!detectsAstro(resolved)) throw new Error(`No Astro project detected at ${resolved}`);
|
|
43
|
+
|
|
44
|
+
const packageFile = path.join(resolved, 'package.json');
|
|
45
|
+
const packageData = fs.existsSync(packageFile) ? JSON.parse(fs.readFileSync(packageFile, 'utf8')) : {};
|
|
46
|
+
const brand = String(options.brand ?? packageData.name ?? path.basename(resolved));
|
|
47
|
+
const name = slugify(options.name ?? packageData.name ?? path.basename(resolved));
|
|
48
|
+
const site = String(options.site ?? 'https://example.com').replace(/\/$/, '');
|
|
49
|
+
const profile = String(options.profile ?? 'growth-site');
|
|
50
|
+
const designMode = String(options['design-mode'] ?? options.designMode ?? 'hybrid');
|
|
51
|
+
|
|
52
|
+
fs.mkdirSync(path.join(resolved, '.cosmo'), { recursive: false });
|
|
53
|
+
for (const relative of GOVERNANCE_PATHS) copyPath(templateDirectory, resolved, relative);
|
|
54
|
+
|
|
55
|
+
const now = new Date().toISOString();
|
|
56
|
+
writeJson(path.join(resolved, '.cosmo', 'project.json'), {
|
|
57
|
+
name, brand, site, stage: 'adoption', designMode, output: 'static', adopted: true, createdAt: now, lastActivity: now,
|
|
58
|
+
});
|
|
59
|
+
writeJson(path.join(resolved, '.cosmo', 'build-plan.json'), { version: 3, approved: false, createdAt: now, pages: [] });
|
|
60
|
+
writeJson(path.join(resolved, '.cosmo', 'evidence.json'), { version: 1, entityId: slugify(brand), claims: [], proofs: [] });
|
|
61
|
+
|
|
62
|
+
const entityFile = path.join(resolved, '.cosmo', 'brand', 'entity-canon.json');
|
|
63
|
+
const entity = JSON.parse(fs.readFileSync(entityFile, 'utf8'));
|
|
64
|
+
writeJson(entityFile, { ...entity, id: slugify(brand), officialName: brand, domain: site });
|
|
65
|
+
const voiceFile = path.join(resolved, '.cosmo', 'brand', 'voice-profile.json');
|
|
66
|
+
const voice = JSON.parse(fs.readFileSync(voiceFile, 'utf8'));
|
|
67
|
+
writeJson(voiceFile, { ...voice, entityId: slugify(brand) });
|
|
68
|
+
applyIntelligenceProfile(resolved, profile);
|
|
69
|
+
|
|
70
|
+
const guides = ['CLAUDE.md', 'AGENTS.md'].map((file) => installAgentGuide(templateDirectory, resolved, file)).filter(Boolean);
|
|
71
|
+
return { target: resolved, name, brand, site, profile, guides };
|
|
72
|
+
}
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
|
|
4
|
+
function walk(directory, suffix) {
|
|
5
|
+
if (!fs.existsSync(directory)) return [];
|
|
6
|
+
return fs.readdirSync(directory, { withFileTypes: true }).flatMap((entry) => {
|
|
7
|
+
const fullPath = path.join(directory, entry.name);
|
|
8
|
+
return entry.isDirectory() ? walk(fullPath, suffix) : fullPath.endsWith(suffix) ? [fullPath] : [];
|
|
9
|
+
});
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
function firstMatch(html, pattern) {
|
|
13
|
+
return html.match(pattern)?.[1]?.trim() ?? '';
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
function routeForFile(distDir, file) {
|
|
17
|
+
const relative = path.relative(distDir, file).split(path.sep).join('/');
|
|
18
|
+
if (relative === 'index.html') return '/';
|
|
19
|
+
if (relative.endsWith('/index.html')) return `/${relative.slice(0, -'index.html'.length)}`;
|
|
20
|
+
return `/${relative.replace(/\.html$/, '')}`;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function normalizeRoute(href) {
|
|
24
|
+
const pathname = href.split('#')[0].split('?')[0];
|
|
25
|
+
if (!pathname) return null;
|
|
26
|
+
if (pathname === '/') return '/';
|
|
27
|
+
return pathname.endsWith('/') ? pathname : `${pathname}/`;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export function auditDist(distDir) {
|
|
31
|
+
const htmlFiles = walk(distDir, '.html');
|
|
32
|
+
const routes = new Set(htmlFiles.map((file) => routeForFile(distDir, file)));
|
|
33
|
+
const pages = [];
|
|
34
|
+
const critical = [];
|
|
35
|
+
const warnings = [];
|
|
36
|
+
const seen = { title: new Map(), description: new Map(), h1: new Map() };
|
|
37
|
+
|
|
38
|
+
for (const file of htmlFiles) {
|
|
39
|
+
const route = routeForFile(distDir, file);
|
|
40
|
+
const html = fs.readFileSync(file, 'utf8');
|
|
41
|
+
const title = firstMatch(html, /<title[^>]*>([\s\S]*?)<\/title>/i);
|
|
42
|
+
const description = firstMatch(html, /<meta\s+[^>]*name=["']description["'][^>]*content=["']([^"']*)["'][^>]*>/i)
|
|
43
|
+
|| firstMatch(html, /<meta\s+[^>]*content=["']([^"']*)["'][^>]*name=["']description["'][^>]*>/i);
|
|
44
|
+
const h1s = [...html.matchAll(/<h1\b[^>]*>([\s\S]*?)<\/h1>/gi)].map((match) => match[1].replace(/<[^>]+>/g, '').trim());
|
|
45
|
+
const missingAlt = [...html.matchAll(/<img\b[^>]*>/gi)].filter((match) => !/\balt=["'][^"']*["']/i.test(match[0])).length;
|
|
46
|
+
const hasCanonical = /<link\s+[^>]*rel=["']canonical["']/i.test(html);
|
|
47
|
+
const schemaBlocks = [...html.matchAll(/<script\s+[^>]*type=["']application\/ld\+json["'][^>]*>([\s\S]*?)<\/script>/gi)].map((match) => match[1].trim());
|
|
48
|
+
const hasSchema = schemaBlocks.length > 0;
|
|
49
|
+
const hasLang = /<html\s+[^>]*lang=["'][^"']+["']/i.test(html);
|
|
50
|
+
const robots = firstMatch(html, /<meta\s+[^>]*name=["']robots["'][^>]*content=["']([^"']*)["'][^>]*>/i)
|
|
51
|
+
|| firstMatch(html, /<meta\s+[^>]*content=["']([^"']*)["'][^>]*name=["']robots["'][^>]*>/i);
|
|
52
|
+
const indexable = !robots.toLowerCase().split(',').map((value) => value.trim()).includes('noindex');
|
|
53
|
+
|
|
54
|
+
if (!title) critical.push({ route, rule: 'missing-title' });
|
|
55
|
+
if (!description) critical.push({ route, rule: 'missing-description' });
|
|
56
|
+
if (h1s.length !== 1) critical.push({ route, rule: 'h1-count', detail: h1s.length });
|
|
57
|
+
if (missingAlt) critical.push({ route, rule: 'missing-image-alt', detail: missingAlt });
|
|
58
|
+
if (!hasCanonical) critical.push({ route, rule: 'missing-canonical' });
|
|
59
|
+
if (!hasSchema) warnings.push({ route, rule: 'missing-json-ld' });
|
|
60
|
+
if (!hasLang) critical.push({ route, rule: 'missing-language' });
|
|
61
|
+
|
|
62
|
+
for (const block of schemaBlocks) {
|
|
63
|
+
try {
|
|
64
|
+
const schemas = JSON.parse(block);
|
|
65
|
+
for (const schema of Array.isArray(schemas) ? schemas : [schemas]) {
|
|
66
|
+
if (!schema || typeof schema !== 'object') {
|
|
67
|
+
critical.push({ route, rule: 'invalid-json-ld-shape' });
|
|
68
|
+
continue;
|
|
69
|
+
}
|
|
70
|
+
if (!schema['@context']) warnings.push({ route, rule: 'json-ld-missing-context' });
|
|
71
|
+
if (!schema['@type']) warnings.push({ route, rule: 'json-ld-missing-type' });
|
|
72
|
+
if (!schema.name) warnings.push({ route, rule: 'json-ld-missing-name' });
|
|
73
|
+
if (!schema.url) warnings.push({ route, rule: 'json-ld-missing-url' });
|
|
74
|
+
}
|
|
75
|
+
} catch (error) {
|
|
76
|
+
critical.push({ route, rule: 'invalid-json-ld', detail: error.message });
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
for (const [kind, value] of [['title', title], ['description', description], ['h1', h1s[0]]]) {
|
|
81
|
+
if (!value) continue;
|
|
82
|
+
const matches = seen[kind].get(value) ?? [];
|
|
83
|
+
matches.push(route);
|
|
84
|
+
seen[kind].set(value, matches);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
const hrefs = [...html.matchAll(/<a\s+[^>]*href=["']([^"']+)["']/gi)].map((match) => match[1]);
|
|
88
|
+
for (const href of hrefs) {
|
|
89
|
+
if (!href.startsWith('/') || href.startsWith('//')) continue;
|
|
90
|
+
const normalized = normalizeRoute(href);
|
|
91
|
+
if (!normalized || routes.has(normalized)) continue;
|
|
92
|
+
const assetPath = path.join(distDir, href.split('#')[0].split('?')[0].replace(/^\//, ''));
|
|
93
|
+
if (!fs.existsSync(assetPath)) critical.push({ route, rule: 'broken-internal-link', detail: href });
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
pages.push({ route, title, description, h1: h1s[0] ?? '', missingAlt, hasCanonical, hasSchema, indexable });
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
for (const [kind, values] of Object.entries(seen)) {
|
|
100
|
+
for (const [value, duplicates] of values.entries()) {
|
|
101
|
+
if (duplicates.length > 1) critical.push({ rule: `duplicate-${kind}`, detail: { value, routes: duplicates } });
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
const sitemapFiles = walk(distDir, '.xml').filter((file) => path.basename(file).startsWith('sitemap'));
|
|
106
|
+
if (!sitemapFiles.length) {
|
|
107
|
+
warnings.push({ rule: 'missing-sitemap' });
|
|
108
|
+
} else {
|
|
109
|
+
const sitemapRoutes = new Set();
|
|
110
|
+
for (const file of sitemapFiles) {
|
|
111
|
+
const xml = fs.readFileSync(file, 'utf8');
|
|
112
|
+
for (const loc of [...xml.matchAll(/<loc>([^<]+)<\/loc>/gi)].map((match) => match[1])) {
|
|
113
|
+
try {
|
|
114
|
+
const pathname = new URL(loc).pathname;
|
|
115
|
+
sitemapRoutes.add(normalizeRoute(pathname));
|
|
116
|
+
} catch {}
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
for (const page of pages) {
|
|
120
|
+
if (page.indexable && !sitemapRoutes.has(page.route)) critical.push({ route: page.route, rule: 'sitemap-missing-route' });
|
|
121
|
+
if (!page.indexable && sitemapRoutes.has(page.route)) critical.push({ route: page.route, rule: 'sitemap-includes-noindex' });
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
const robotsFile = path.join(distDir, 'robots.txt');
|
|
126
|
+
if (!fs.existsSync(robotsFile)) warnings.push({ rule: 'missing-robots' });
|
|
127
|
+
else if (!/^Sitemap:\s*https?:\/\//im.test(fs.readFileSync(robotsFile, 'utf8'))) warnings.push({ rule: 'robots-missing-sitemap' });
|
|
128
|
+
|
|
129
|
+
if (htmlFiles.length === 0) critical.push({ rule: 'no-html-output' });
|
|
130
|
+
return {
|
|
131
|
+
passed: critical.length === 0,
|
|
132
|
+
generatedAt: new Date().toISOString(),
|
|
133
|
+
summary: { pages: pages.length, critical: critical.length, warnings: warnings.length },
|
|
134
|
+
critical,
|
|
135
|
+
warnings,
|
|
136
|
+
pages,
|
|
137
|
+
};
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
export function writeAuditReport(projectDir, report) {
|
|
141
|
+
const reportFile = path.join(projectDir, '.cosmo', 'reports', 'site-check.json');
|
|
142
|
+
fs.mkdirSync(path.dirname(reportFile), { recursive: true });
|
|
143
|
+
fs.writeFileSync(reportFile, `${JSON.stringify(report, null, 2)}\n`);
|
|
144
|
+
return reportFile;
|
|
145
|
+
}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { readProject, writeJson } from './project.mjs';
|
|
4
|
+
|
|
5
|
+
export class BrandDiscoveryError extends Error {}
|
|
6
|
+
|
|
7
|
+
export const BRAND_PROMPTS = [
|
|
8
|
+
['ideal-customer', 'Who is the ideal customer, specifically?'],
|
|
9
|
+
['customer-moment', 'What is happening when they begin looking for help?'],
|
|
10
|
+
['category-fear', 'What do they distrust or fear about this category?'],
|
|
11
|
+
['alternatives', 'Which alternatives and competitors do they compare?'],
|
|
12
|
+
['differentiation', 'What can this brand credibly do or say that those alternatives cannot?'],
|
|
13
|
+
['contrary-belief', 'What useful belief does this brand hold that competitors usually do not?'],
|
|
14
|
+
['admired-brands', 'Which brands are admired, and for which precise qualities?'],
|
|
15
|
+
['brand-person', 'If this brand were a person, how would it behave and speak?'],
|
|
16
|
+
['anti-positioning', 'What should this brand never look, sound, or feel like?'],
|
|
17
|
+
['operating-values', 'Which values change real decisions rather than decorate a page?'],
|
|
18
|
+
['desired-feeling', 'What should a visitor feel in the first five seconds?'],
|
|
19
|
+
];
|
|
20
|
+
|
|
21
|
+
function discoveryFile(projectDir) {
|
|
22
|
+
return path.join(projectDir, '.cosmo', 'brand', 'discovery.json');
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export function scaffoldBrandDiscovery(projectDir, { replace = false } = {}) {
|
|
26
|
+
const project = readProject(projectDir).data;
|
|
27
|
+
const file = discoveryFile(projectDir);
|
|
28
|
+
if (fs.existsSync(file) && !replace) return { file, created: false };
|
|
29
|
+
writeJson(file, {
|
|
30
|
+
version: 1,
|
|
31
|
+
brand: project.brand ?? project.name,
|
|
32
|
+
approved: false,
|
|
33
|
+
prompts: BRAND_PROMPTS.map(([id, question]) => ({ id, question, answer: '' })),
|
|
34
|
+
synthesis: { audience: '', position: '', differentiation: '', voice: '', antiPositioning: [], values: [], desiredFeeling: '' },
|
|
35
|
+
createdAt: new Date().toISOString(),
|
|
36
|
+
});
|
|
37
|
+
return { file, created: true };
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function checkBrandDiscovery(projectDir) {
|
|
41
|
+
const file = discoveryFile(projectDir);
|
|
42
|
+
if (!fs.existsSync(file)) throw new BrandDiscoveryError(`Brand discovery not found: ${file}. Run cosmo brand discover.`);
|
|
43
|
+
let data;
|
|
44
|
+
try { data = JSON.parse(fs.readFileSync(file, 'utf8')); } catch { throw new BrandDiscoveryError(`Brand discovery is not valid JSON: ${file}`); }
|
|
45
|
+
const failures = [];
|
|
46
|
+
if (data.version !== 1) failures.push('version must be 1');
|
|
47
|
+
if (!Array.isArray(data.prompts)) failures.push('prompts must be an array');
|
|
48
|
+
for (const [id] of BRAND_PROMPTS) {
|
|
49
|
+
const prompt = data.prompts?.find((item) => item.id === id);
|
|
50
|
+
if (!prompt || typeof prompt.answer !== 'string' || !prompt.answer.trim()) failures.push(`${id} needs an answer`);
|
|
51
|
+
}
|
|
52
|
+
for (const key of ['audience', 'position', 'differentiation', 'voice', 'antiPositioning', 'values', 'desiredFeeling']) {
|
|
53
|
+
const value = data.synthesis?.[key];
|
|
54
|
+
const present = typeof value === 'string' ? value.trim() : Array.isArray(value) ? value.length : false;
|
|
55
|
+
if (!present) failures.push(`synthesis.${key} must be completed`);
|
|
56
|
+
}
|
|
57
|
+
if (data.approved !== true) failures.push('approved must be true after human review');
|
|
58
|
+
if (failures.length) throw new BrandDiscoveryError(`Brand discovery is incomplete:\n${failures.map((failure) => `- ${failure}`).join('\n')}`);
|
|
59
|
+
return { file, data, prompts: BRAND_PROMPTS.length, approved: true };
|
|
60
|
+
}
|
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
import { execFileSync } from 'node:child_process';
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import axe from 'axe-core';
|
|
5
|
+
import { launch as launchChrome } from 'chrome-launcher';
|
|
6
|
+
import lighthouse from 'lighthouse';
|
|
7
|
+
import { chromium } from 'playwright-core';
|
|
8
|
+
|
|
9
|
+
const VIEWPORTS = [
|
|
10
|
+
{ name: 'mobile', width: 320, height: 900 },
|
|
11
|
+
{ name: 'tablet', width: 768, height: 1024 },
|
|
12
|
+
{ name: 'desktop', width: 1440, height: 1000 },
|
|
13
|
+
];
|
|
14
|
+
|
|
15
|
+
function walk(directory, suffix) {
|
|
16
|
+
if (!fs.existsSync(directory)) return [];
|
|
17
|
+
return fs.readdirSync(directory, { withFileTypes: true }).flatMap((entry) => {
|
|
18
|
+
const fullPath = path.join(directory, entry.name);
|
|
19
|
+
return entry.isDirectory() ? walk(fullPath, suffix) : fullPath.endsWith(suffix) ? [fullPath] : [];
|
|
20
|
+
});
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function routeForFile(distDir, file) {
|
|
24
|
+
const relative = path.relative(distDir, file).split(path.sep).join('/');
|
|
25
|
+
if (relative === 'index.html') return '/';
|
|
26
|
+
if (relative.endsWith('/index.html')) return `/${relative.slice(0, -'index.html'.length)}`;
|
|
27
|
+
return `/${relative.replace(/\.html$/, '')}`;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function screenshotName(route, width) {
|
|
31
|
+
const slug = route === '/' ? 'home' : route.replace(/^\/|\/$/g, '').replace(/[^a-z0-9]+/gi, '-');
|
|
32
|
+
return `${slug}-${width}.png`;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function findChromeExecutable() {
|
|
36
|
+
const configured = process.env.COSMO_CHROME_PATH;
|
|
37
|
+
const candidates = [
|
|
38
|
+
configured,
|
|
39
|
+
'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
|
|
40
|
+
'/Applications/Chromium.app/Contents/MacOS/Chromium',
|
|
41
|
+
'C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe',
|
|
42
|
+
'C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe',
|
|
43
|
+
].filter(Boolean);
|
|
44
|
+
for (const candidate of candidates) if (fs.existsSync(candidate)) return candidate;
|
|
45
|
+
for (const command of ['google-chrome', 'chromium', 'chromium-browser']) {
|
|
46
|
+
try {
|
|
47
|
+
const resolved = execFileSync('which', [command], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim();
|
|
48
|
+
if (resolved) return resolved;
|
|
49
|
+
} catch {}
|
|
50
|
+
}
|
|
51
|
+
throw new Error('Chrome or Chromium was not found. Set COSMO_CHROME_PATH to its executable.');
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
async function runLighthouse(baseUrl, executablePath) {
|
|
55
|
+
const chrome = await launchChrome({ chromePath: executablePath, chromeFlags: ['--headless', '--no-sandbox', '--disable-gpu'] });
|
|
56
|
+
try {
|
|
57
|
+
const result = await lighthouse(baseUrl, {
|
|
58
|
+
port: chrome.port,
|
|
59
|
+
output: 'json',
|
|
60
|
+
logLevel: 'error',
|
|
61
|
+
onlyCategories: ['performance', 'accessibility', 'best-practices', 'seo'],
|
|
62
|
+
});
|
|
63
|
+
return Object.fromEntries(Object.entries(result.lhr.categories).map(([id, category]) => [id, {
|
|
64
|
+
score: Math.round((category.score ?? 0) * 100),
|
|
65
|
+
title: category.title,
|
|
66
|
+
}]));
|
|
67
|
+
} finally {
|
|
68
|
+
await chrome.kill();
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export async function auditBrowser(projectDir, { baseUrl, lighthouseEnabled = true } = {}) {
|
|
73
|
+
const distDir = path.join(projectDir, 'dist');
|
|
74
|
+
const routes = walk(distDir, '.html').map((file) => routeForFile(distDir, file)).sort();
|
|
75
|
+
if (!routes.length) throw new Error('No built HTML routes found for browser QA.');
|
|
76
|
+
const executablePath = findChromeExecutable();
|
|
77
|
+
const screenshotsDir = path.join(projectDir, '.cosmo', 'reports', 'screenshots');
|
|
78
|
+
fs.mkdirSync(screenshotsDir, { recursive: true });
|
|
79
|
+
const browser = await chromium.launch({ executablePath, headless: true });
|
|
80
|
+
const critical = [];
|
|
81
|
+
const warnings = [];
|
|
82
|
+
const pages = [];
|
|
83
|
+
|
|
84
|
+
try {
|
|
85
|
+
for (const route of routes) {
|
|
86
|
+
for (const viewport of VIEWPORTS) {
|
|
87
|
+
const page = await browser.newPage({ viewport });
|
|
88
|
+
const runtimeErrors = [];
|
|
89
|
+
page.on('console', (message) => {
|
|
90
|
+
if (message.type() === 'error') {
|
|
91
|
+
const location = message.location();
|
|
92
|
+
runtimeErrors.push(`console: ${message.text()}${location.url ? ` (${location.url})` : ''}`);
|
|
93
|
+
}
|
|
94
|
+
});
|
|
95
|
+
page.on('pageerror', (error) => runtimeErrors.push(`page: ${error.message}`));
|
|
96
|
+
const response = await page.goto(new URL(route, baseUrl).href, { waitUntil: 'networkidle' });
|
|
97
|
+
if (!response?.ok()) critical.push({ route, viewport: viewport.width, rule: 'navigation-failed', detail: response?.status() ?? 'no-response' });
|
|
98
|
+
await page.emulateMedia({ reducedMotion: 'reduce' });
|
|
99
|
+
const dimensions = await page.evaluate(() => ({
|
|
100
|
+
clientWidth: document.documentElement.clientWidth,
|
|
101
|
+
scrollWidth: document.documentElement.scrollWidth,
|
|
102
|
+
}));
|
|
103
|
+
if (dimensions.scrollWidth > dimensions.clientWidth) {
|
|
104
|
+
critical.push({ route, viewport: viewport.width, rule: 'horizontal-overflow', detail: dimensions });
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
await page.addScriptTag({ content: axe.source });
|
|
108
|
+
const accessibility = await page.evaluate(async () => globalThis.axe.run(document, {
|
|
109
|
+
runOnly: { type: 'tag', values: ['wcag2a', 'wcag2aa'] },
|
|
110
|
+
}));
|
|
111
|
+
for (const violation of accessibility.violations) {
|
|
112
|
+
critical.push({
|
|
113
|
+
route,
|
|
114
|
+
viewport: viewport.width,
|
|
115
|
+
rule: `accessibility-${violation.id}`,
|
|
116
|
+
detail: {
|
|
117
|
+
impact: violation.impact,
|
|
118
|
+
help: violation.help,
|
|
119
|
+
nodes: violation.nodes.map((node) => ({ target: node.target, summary: node.failureSummary })),
|
|
120
|
+
},
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
const screenshot = path.join(screenshotsDir, screenshotName(route, viewport.width));
|
|
125
|
+
await page.screenshot({ path: screenshot, fullPage: true });
|
|
126
|
+
await page.keyboard.press('Tab');
|
|
127
|
+
const focus = await page.evaluate(() => {
|
|
128
|
+
const element = document.activeElement;
|
|
129
|
+
if (!element || element === document.body) return { focused: false };
|
|
130
|
+
const style = getComputedStyle(element);
|
|
131
|
+
return {
|
|
132
|
+
focused: true,
|
|
133
|
+
tag: element.tagName.toLowerCase(),
|
|
134
|
+
text: element.textContent?.trim().slice(0, 80) ?? '',
|
|
135
|
+
visible: style.outlineStyle !== 'none' || style.boxShadow !== 'none',
|
|
136
|
+
};
|
|
137
|
+
});
|
|
138
|
+
if (!focus.focused) critical.push({ route, viewport: viewport.width, rule: 'keyboard-focus-missing' });
|
|
139
|
+
else if (!focus.visible) critical.push({ route, viewport: viewport.width, rule: 'keyboard-focus-invisible', detail: focus });
|
|
140
|
+
|
|
141
|
+
for (const detail of runtimeErrors) critical.push({ route, viewport: viewport.width, rule: 'browser-runtime-error', detail });
|
|
142
|
+
pages.push({ route, viewport, dimensions, focus, violations: accessibility.violations.length, runtimeErrors, screenshot: path.relative(projectDir, screenshot) });
|
|
143
|
+
await page.close();
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
} finally {
|
|
147
|
+
await browser.close();
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
let lighthouseScores = null;
|
|
151
|
+
if (lighthouseEnabled) {
|
|
152
|
+
lighthouseScores = await runLighthouse(baseUrl, executablePath);
|
|
153
|
+
for (const [category, result] of Object.entries(lighthouseScores)) {
|
|
154
|
+
const minimum = category === 'performance' ? 75 : 90;
|
|
155
|
+
if (result.score < minimum) warnings.push({ route: '/', rule: `lighthouse-${category}`, detail: { score: result.score, minimum } });
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
return {
|
|
160
|
+
passed: critical.length === 0,
|
|
161
|
+
generatedAt: new Date().toISOString(),
|
|
162
|
+
baseUrl,
|
|
163
|
+
viewports: VIEWPORTS,
|
|
164
|
+
summary: { routes: routes.length, renders: pages.length, critical: critical.length, warnings: warnings.length },
|
|
165
|
+
critical,
|
|
166
|
+
warnings,
|
|
167
|
+
lighthouse: lighthouseScores,
|
|
168
|
+
pages,
|
|
169
|
+
};
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
export function writeBrowserReport(projectDir, report) {
|
|
173
|
+
const file = path.join(projectDir, '.cosmo', 'reports', 'browser-check.json');
|
|
174
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
175
|
+
fs.writeFileSync(file, `${JSON.stringify(report, null, 2)}\n`);
|
|
176
|
+
return file;
|
|
177
|
+
}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import os from 'node:os';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { fileURLToPath } from 'node:url';
|
|
5
|
+
import { spawnSync } from 'node:child_process';
|
|
6
|
+
|
|
7
|
+
const moduleDirectory = path.dirname(fileURLToPath(import.meta.url));
|
|
8
|
+
const defaultSource = path.resolve(moduleDirectory, '../../../plugins/claude-code/cosmo');
|
|
9
|
+
const runtimeCli = path.resolve(moduleDirectory, '../bin/cosmo.mjs');
|
|
10
|
+
|
|
11
|
+
function shellQuote(value) {
|
|
12
|
+
return `'${String(value).replaceAll("'", `'"'"'`)}'`;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export function claudePluginTarget() {
|
|
16
|
+
const claudeDirectory = process.env.COSMO_CLAUDE_DIR
|
|
17
|
+
? path.resolve(process.env.COSMO_CLAUDE_DIR)
|
|
18
|
+
: path.join(os.homedir(), '.claude');
|
|
19
|
+
return path.join(claudeDirectory, 'skills', 'cosmo');
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function claudePluginStatus(target = claudePluginTarget()) {
|
|
23
|
+
const manifest = path.join(target, '.claude-plugin', 'plugin.json');
|
|
24
|
+
if (!fs.existsSync(manifest)) return { installed: false, target, version: null };
|
|
25
|
+
const data = JSON.parse(fs.readFileSync(manifest, 'utf8'));
|
|
26
|
+
return { installed: true, target, version: data.version ?? null };
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function uninstallClaudePlugin(target = claudePluginTarget()) {
|
|
30
|
+
const status = claudePluginStatus(target);
|
|
31
|
+
if (!status.installed) return { ...status, removed: false };
|
|
32
|
+
fs.rmSync(target, { recursive: true, force: true });
|
|
33
|
+
return { installed: false, target, version: status.version, removed: true };
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function installClaudePlugin({ target = claudePluginTarget(), source = defaultSource, replace = false, validate = true } = {}) {
|
|
37
|
+
if (!fs.existsSync(path.join(source, '.claude-plugin', 'plugin.json'))) {
|
|
38
|
+
throw new Error(`Cosmo Claude plugin source is missing: ${source}`);
|
|
39
|
+
}
|
|
40
|
+
if (fs.existsSync(target)) {
|
|
41
|
+
if (!replace) throw new Error(`Cosmo is already installed for Claude at ${target}. Pass --replace to update it.`);
|
|
42
|
+
fs.rmSync(target, { recursive: true, force: true });
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
fs.mkdirSync(path.dirname(target), { recursive: true });
|
|
46
|
+
fs.cpSync(source, target, { recursive: true });
|
|
47
|
+
const launcher = path.join(target, 'bin', 'cosmo');
|
|
48
|
+
fs.writeFileSync(launcher, `#!/bin/sh\nexec ${shellQuote(process.execPath)} ${shellQuote(runtimeCli)} "$@"\n`);
|
|
49
|
+
fs.chmodSync(launcher, 0o755);
|
|
50
|
+
|
|
51
|
+
let validation = { attempted: false, valid: null, output: '' };
|
|
52
|
+
if (validate) {
|
|
53
|
+
const result = spawnSync('claude', ['plugin', 'validate', target, '--strict'], { encoding: 'utf8' });
|
|
54
|
+
if (result.error?.code !== 'ENOENT') {
|
|
55
|
+
const output = `${result.stdout ?? ''}${result.stderr ?? ''}`.trim();
|
|
56
|
+
validation = { attempted: true, valid: result.status === 0, output };
|
|
57
|
+
if (result.status !== 0) {
|
|
58
|
+
fs.rmSync(target, { recursive: true, force: true });
|
|
59
|
+
throw new Error(`Claude rejected the Cosmo plugin: ${output || `exit ${result.status}`}`);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
return { ...claudePluginStatus(target), validation };
|
|
64
|
+
}
|