@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,184 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import matter from 'gray-matter';
|
|
4
|
+
import { checkIntegrity, readIntegrity } from './integrity.mjs';
|
|
5
|
+
import { pageParentId, pageRelatedIds, readPlan } from './plan.mjs';
|
|
6
|
+
import { readProject, writeJson } from './project.mjs';
|
|
7
|
+
|
|
8
|
+
export class ContentAuditError extends Error {}
|
|
9
|
+
|
|
10
|
+
const RICH_OWNERSHIP = new Set(['measured', 'lived', 'originated', 'accessed', 'staked', 'first', 'corrected']);
|
|
11
|
+
|
|
12
|
+
function assert(condition, message) {
|
|
13
|
+
if (!condition) throw new ContentAuditError(message);
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
function readJson(file, label) {
|
|
17
|
+
assert(fs.existsSync(file), `${label} not found: ${file}`);
|
|
18
|
+
try {
|
|
19
|
+
return JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
20
|
+
} catch {
|
|
21
|
+
throw new ContentAuditError(`${label} is not valid JSON: ${file}`);
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export function validateContentPolicy(value) {
|
|
26
|
+
assert(value && typeof value === 'object', 'Content-integrity policy must be an object.');
|
|
27
|
+
assert(value.version === 1, 'Content-integrity policy version must be 1.');
|
|
28
|
+
for (const key of ['genericPhrases', 'manipulativePhrases']) {
|
|
29
|
+
assert(Array.isArray(value[key]) && value[key].every((phrase) => typeof phrase === 'string' && phrase.trim()), `Content policy ${key} must be an array of phrases.`);
|
|
30
|
+
}
|
|
31
|
+
assert(['blocking', 'warning'].includes(value.voiceBannedSeverity), 'Content policy voiceBannedSeverity must be blocking or warning.');
|
|
32
|
+
assert(typeof value.requireVerifiedProofForIndexable === 'boolean', 'Content policy must declare requireVerifiedProofForIndexable.');
|
|
33
|
+
assert(typeof value.blockDuplicatePassages === 'boolean', 'Content policy must declare blockDuplicatePassages.');
|
|
34
|
+
return value;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function normalize(value) {
|
|
38
|
+
return String(value).toLowerCase().replace(/[^a-z0-9]+/g, ' ').trim();
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function surfaceStrings(value, key = '') {
|
|
42
|
+
if (typeof value === 'string') {
|
|
43
|
+
if (['source', 'href', 'path'].includes(key)) return [];
|
|
44
|
+
return [value];
|
|
45
|
+
}
|
|
46
|
+
if (Array.isArray(value)) return value.flatMap((item) => surfaceStrings(item, key));
|
|
47
|
+
if (value && typeof value === 'object') return Object.entries(value).flatMap(([childKey, child]) => surfaceStrings(child, childKey));
|
|
48
|
+
return [];
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function issue(pageId, code, severity, message, fix) {
|
|
52
|
+
return { pageId, code, severity, message, fix };
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function includesPhrase(surface, phrase) {
|
|
56
|
+
const normalizedPhrase = normalize(phrase);
|
|
57
|
+
return normalizedPhrase && ` ${normalize(surface)} `.includes(` ${normalizedPhrase} `);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function expectedPath(plan, id) {
|
|
61
|
+
return plan.pages.find((page) => page.id === id)?.path;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function auditPage(projectDir, plan, page, integrity, policy) {
|
|
65
|
+
const contentFile = path.resolve(projectDir, page.contentFile);
|
|
66
|
+
const findings = [];
|
|
67
|
+
if (!fs.existsSync(contentFile)) {
|
|
68
|
+
findings.push(issue(page.id, 'missing-content', 'blocking', `Content file is missing: ${page.contentFile}`, 'Create the planned typed content entry.'));
|
|
69
|
+
return { pageId: page.id, indexability: page.architecture.indexability, substanceTier: 'commodity', findings, passages: [] };
|
|
70
|
+
}
|
|
71
|
+
const frontmatter = matter(fs.readFileSync(contentFile, 'utf8')).data;
|
|
72
|
+
const strings = surfaceStrings({ description: frontmatter.description, h1: frontmatter.h1, sections: frontmatter.sections });
|
|
73
|
+
const surface = strings.join('\n');
|
|
74
|
+
const block = (code, message, fix) => findings.push(issue(page.id, code, 'blocking', message, fix));
|
|
75
|
+
const warn = (code, message, fix) => findings.push(issue(page.id, code, 'warning', message, fix));
|
|
76
|
+
|
|
77
|
+
if (frontmatter.entityId !== integrity.entity.id || frontmatter.entityId !== page.contract.strengthensEntity) block('entity-canon-drift', 'Content entityId differs from the Entity Canon or page contract.', 'Restore the canonical entity id before publishing.');
|
|
78
|
+
if (frontmatter.primaryTopic !== page.primaryTopic) block('primary-topic-drift', 'Content primaryTopic differs from Plan v3.', 'Restore the approved topic or revise and reapprove the plan.');
|
|
79
|
+
if (frontmatter.archetype !== page.architecture.archetype) block('archetype-drift', 'Content archetype differs from Plan v3.', 'Use the approved archetype or revise the plan.');
|
|
80
|
+
if (frontmatter.indexability !== page.architecture.indexability) block('indexability-drift', 'Content indexability differs from Plan v3.', 'Synchronize frontmatter with the approved indexability decision.');
|
|
81
|
+
for (const key of ['primary', 'funnel', 'awareness', 'demandConfidence']) {
|
|
82
|
+
if (frontmatter.intent?.[key] !== page.architecture.intent[key]) block(`intent-${key.toLowerCase()}-drift`, `Content intent.${key} differs from Plan v3.`, 'Restore the approved intent metadata or revise and reapprove the plan.');
|
|
83
|
+
}
|
|
84
|
+
if (JSON.stringify(frontmatter.intent?.queryPatterns) !== JSON.stringify(page.architecture.intent.queryPatterns)) block('query-pattern-drift', 'Content query patterns differ from Plan v3.', 'Restore the approved query patterns.');
|
|
85
|
+
|
|
86
|
+
const parentId = pageParentId(plan, page);
|
|
87
|
+
if (parentId && frontmatter.links?.parent !== expectedPath(plan, parentId)) block('parent-link-drift', 'Content is missing its governed parent link.', 'Restore the parent route from Plan v3.');
|
|
88
|
+
for (const relatedId of pageRelatedIds(plan, page)) {
|
|
89
|
+
if (!frontmatter.links?.related?.includes(expectedPath(plan, relatedId))) block('related-link-drift', `Content is missing governed related link ${relatedId}.`, 'Add the planned related route.');
|
|
90
|
+
}
|
|
91
|
+
for (const link of page.links.filter((item) => item.role === 'conversion')) {
|
|
92
|
+
if (!frontmatter.links?.conversion?.includes(expectedPath(plan, link.target))) block('conversion-link-drift', `Content is missing governed conversion link ${link.target}.`, 'Add the planned conversion route.');
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
const verifiedProofs = [];
|
|
96
|
+
for (const proofId of page.contract.carriesProof) {
|
|
97
|
+
const proof = integrity.evidence.proofs.find((item) => item.id === proofId);
|
|
98
|
+
const contentEvidence = frontmatter.evidence?.find((item) => item.id === proofId);
|
|
99
|
+
const severity = page.architecture.indexability === 'index' ? 'blocking' : 'warning';
|
|
100
|
+
if (!contentEvidence) {
|
|
101
|
+
findings.push(issue(page.id, 'missing-page-proof', severity, `Content does not surface planned proof ${proofId}.`, 'Add the proof entry or remove it through plan review.'));
|
|
102
|
+
continue;
|
|
103
|
+
}
|
|
104
|
+
if (proof?.status !== 'verified' || contentEvidence.status !== 'supplied') {
|
|
105
|
+
findings.push(issue(page.id, 'unverified-page-proof', severity, `Proof ${proofId} is not verified and supplied.`, 'Verify the source in the evidence ledger before indexing the page.'));
|
|
106
|
+
continue;
|
|
107
|
+
}
|
|
108
|
+
if (contentEvidence.source !== proof.source || contentEvidence.provenance !== proof.provenance) block('proof-provenance-drift', `Proof ${proofId} differs from the evidence ledger.`, 'Restore the ledger source and provenance.');
|
|
109
|
+
else verifiedProofs.push(proof);
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
for (const term of integrity.voice.bannedVocabulary) {
|
|
113
|
+
if (includesPhrase(surface, term)) findings.push(issue(page.id, 'voice-banned-term', policy.voiceBannedSeverity, `Project voice forbids the term “${term}”.`, 'Rewrite using approved project vocabulary or revise the voice profile.'));
|
|
114
|
+
}
|
|
115
|
+
for (const phrase of policy.genericPhrases) {
|
|
116
|
+
if (includesPhrase(surface, phrase)) warn('generic-language', `Generic phrase detected: “${phrase}”.`, 'Replace it with specific audience, mechanism, or evidence language.');
|
|
117
|
+
}
|
|
118
|
+
for (const phrase of policy.manipulativePhrases) {
|
|
119
|
+
if (includesPhrase(surface, phrase)) block('manipulative-language', `Manipulative phrase detected: “${phrase}”.`, 'Use a transparent CTA that preserves visitor autonomy.');
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
const hasRichProof = verifiedProofs.some((proof) => RICH_OWNERSHIP.has(proof.ownership));
|
|
123
|
+
const substanceTier = hasRichProof ? 'noncommodity' : verifiedProofs.length ? 'premium' : 'commodity';
|
|
124
|
+
if (policy.requireVerifiedProofForIndexable && page.architecture.indexability === 'index' && substanceTier === 'commodity') block('commodity-indexable-page', 'Indexable page has no verified proof.', 'Supply and verify page-specific proof or set the page to noindex until it is ready.');
|
|
125
|
+
if (page.architecture.indexability === 'noindex' && substanceTier === 'commodity') warn('commodity-draft-page', 'Noindex page remains a commodity draft without verified proof.', 'Supply differentiated proof before changing indexability to index.');
|
|
126
|
+
|
|
127
|
+
const passages = strings
|
|
128
|
+
.map((text) => ({ text, normalized: normalize(text) }))
|
|
129
|
+
.filter((entry) => entry.normalized.length >= 100);
|
|
130
|
+
return { pageId: page.id, indexability: page.architecture.indexability, substanceTier, findings, passages };
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
export function auditContent(projectDir) {
|
|
134
|
+
readProject(projectDir);
|
|
135
|
+
checkIntegrity(projectDir);
|
|
136
|
+
const plan = readPlan(projectDir, { requireApproved: false }).data;
|
|
137
|
+
assert(plan.version >= 3, 'Content QA requires Build Plan v3 or newer.');
|
|
138
|
+
const integrity = readIntegrity(projectDir);
|
|
139
|
+
const policyFile = path.join(projectDir, '.cosmo', 'policies', 'content-integrity.json');
|
|
140
|
+
const policy = validateContentPolicy(readJson(policyFile, 'Content-integrity policy'));
|
|
141
|
+
const pages = plan.pages.map((page) => auditPage(projectDir, plan, page, integrity, policy));
|
|
142
|
+
|
|
143
|
+
const passageOwners = new Map();
|
|
144
|
+
for (const page of pages) {
|
|
145
|
+
for (const passage of page.passages) {
|
|
146
|
+
const owners = passageOwners.get(passage.normalized) ?? [];
|
|
147
|
+
owners.push({ pageId: page.pageId, text: passage.text });
|
|
148
|
+
passageOwners.set(passage.normalized, owners);
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
for (const owners of passageOwners.values()) {
|
|
152
|
+
const pageIds = [...new Set(owners.map((owner) => owner.pageId))];
|
|
153
|
+
if (pageIds.length < 2) continue;
|
|
154
|
+
for (const pageId of pageIds) {
|
|
155
|
+
const target = pages.find((page) => page.pageId === pageId);
|
|
156
|
+
target.findings.push(issue(pageId, 'duplicate-passage', policy.blockDuplicatePassages ? 'blocking' : 'warning', `Long passage is duplicated across pages: ${pageIds.join(', ')}.`, 'Consolidate the passage or rewrite it for this page’s distinct intent.'));
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
const serializedPages = pages.map(({ passages, ...page }) => page);
|
|
161
|
+
const findings = serializedPages.flatMap((page) => page.findings);
|
|
162
|
+
const blocking = findings.filter((finding) => finding.severity === 'blocking');
|
|
163
|
+
const warnings = findings.filter((finding) => finding.severity === 'warning');
|
|
164
|
+
const tiers = ['commodity', 'premium', 'noncommodity'];
|
|
165
|
+
return {
|
|
166
|
+
version: 1,
|
|
167
|
+
passed: blocking.length === 0,
|
|
168
|
+
checkedAt: new Date().toISOString(),
|
|
169
|
+
summary: {
|
|
170
|
+
pages: serializedPages.length,
|
|
171
|
+
blocking: blocking.length,
|
|
172
|
+
warnings: warnings.length,
|
|
173
|
+
bySubstanceTier: Object.fromEntries(tiers.map((tier) => [tier, serializedPages.filter((page) => page.substanceTier === tier).length])),
|
|
174
|
+
},
|
|
175
|
+
policy: '.cosmo/policies/content-integrity.json',
|
|
176
|
+
pages: serializedPages,
|
|
177
|
+
};
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
export function writeContentReport(projectDir, report) {
|
|
181
|
+
const file = path.join(projectDir, '.cosmo', 'reports', 'content-check.json');
|
|
182
|
+
writeJson(file, report);
|
|
183
|
+
return file;
|
|
184
|
+
}
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
import crypto from 'node:crypto';
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { readIntelligence } from './intelligence.mjs';
|
|
5
|
+
import { readPlan } from './plan.mjs';
|
|
6
|
+
import { readProject, writeJson } from './project.mjs';
|
|
7
|
+
import { readWorkflowState } from './workflow.mjs';
|
|
8
|
+
|
|
9
|
+
const REQUIRED_REPORTS = ['integrity-check', 'content-check', 'intelligence-check', 'site-check', 'browser-check'];
|
|
10
|
+
const PLACEHOLDER_PATTERN = /complete this|replace this placeholder|hello@example\.com|\(000\) 000-0000|tel:\+10000000000/i;
|
|
11
|
+
|
|
12
|
+
function finding(code, message, fix) {
|
|
13
|
+
return { code, severity: 'blocking', message, fix };
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
function optionalJson(file) {
|
|
17
|
+
if (!fs.existsSync(file)) return null;
|
|
18
|
+
try {
|
|
19
|
+
return JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
20
|
+
} catch {
|
|
21
|
+
return { invalid: true };
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function filesBelow(root) {
|
|
26
|
+
if (!fs.existsSync(root)) return [];
|
|
27
|
+
const files = [];
|
|
28
|
+
for (const entry of fs.readdirSync(root, { withFileTypes: true })) {
|
|
29
|
+
const file = path.join(root, entry.name);
|
|
30
|
+
if (entry.isDirectory()) files.push(...filesBelow(file));
|
|
31
|
+
else files.push(file);
|
|
32
|
+
}
|
|
33
|
+
return files;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function sourceFiles(projectDir) {
|
|
37
|
+
const roots = [
|
|
38
|
+
path.join(projectDir, 'src'),
|
|
39
|
+
path.join(projectDir, 'public'),
|
|
40
|
+
path.join(projectDir, '.cosmo', 'brand'),
|
|
41
|
+
path.join(projectDir, '.cosmo', 'capabilities'),
|
|
42
|
+
path.join(projectDir, '.cosmo', 'intelligence'),
|
|
43
|
+
path.join(projectDir, '.cosmo', 'policies'),
|
|
44
|
+
path.join(projectDir, '.cosmo', 'work'),
|
|
45
|
+
];
|
|
46
|
+
const direct = ['.cosmo/project.json', '.cosmo/build-plan.json', '.cosmo/evidence.json', 'DESIGN-DIRECTION.md', 'cosmo.config.mjs', 'astro.config.mjs', 'package.json', 'package-lock.json', 'tsconfig.json']
|
|
47
|
+
.map((relative) => path.join(projectDir, relative))
|
|
48
|
+
.filter((file) => fs.existsSync(file));
|
|
49
|
+
return [...roots.flatMap(filesBelow), ...direct];
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function releaseHash(projectDir, files) {
|
|
53
|
+
const hash = crypto.createHash('sha256');
|
|
54
|
+
for (const file of [...files].sort()) {
|
|
55
|
+
hash.update(path.relative(projectDir, file));
|
|
56
|
+
hash.update(fs.readFileSync(file));
|
|
57
|
+
}
|
|
58
|
+
return hash.digest('hex').slice(0, 16);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function renderDelivery(report) {
|
|
62
|
+
const reports = report.reports.map((item) => `- \`${item.path}\`: **${item.status}**`).join('\n');
|
|
63
|
+
const blockers = report.findings.length
|
|
64
|
+
? report.findings.map((item) => `- **${item.code}:** ${item.message}\n - Fix: ${item.fix}`).join('\n')
|
|
65
|
+
: '- None.';
|
|
66
|
+
return `# Delivery Readiness\n\n- Release: \`${report.releaseId}\`\n- Checked: ${report.checkedAt}\n- Status: **${report.ready ? 'READY' : 'BLOCKED'}**\n- Brand: ${report.project.brand}\n- Site: ${report.project.site}\n- Intelligence: ${report.intelligence.profile}${report.intelligence.packs.length ? ` (${report.intelligence.packs.join(', ')})` : ' (no optional packs)'}\n- Plan: ${report.plan.approved ? 'approved' : 'not approved'}, ${report.plan.pages} pages, ${report.plan.indexable} indexable\n\n## Reports\n\n${reports}\n\n## Blocking findings\n\n${blockers}\n\nThis manifest records local readiness at one source hash. Any later source change requires the relevant checks and release evaluation to run again.\n`;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export function evaluateDelivery(projectDir) {
|
|
70
|
+
const project = readProject(projectDir).data;
|
|
71
|
+
const intelligence = readIntelligence(projectDir).data;
|
|
72
|
+
const findings = [];
|
|
73
|
+
const inputs = sourceFiles(projectDir);
|
|
74
|
+
const latestInputMtime = inputs.reduce((latest, file) => Math.max(latest, fs.statSync(file).mtimeMs), 0);
|
|
75
|
+
let plan = { approved: false, pages: 0, indexable: 0 };
|
|
76
|
+
try {
|
|
77
|
+
const value = readPlan(projectDir, { requireApproved: false }).data;
|
|
78
|
+
plan = { approved: value.approved, pages: value.pages.length, indexable: value.pages.filter((page) => page.architecture?.indexability === 'index').length };
|
|
79
|
+
if (!value.approved) findings.push(finding('plan-not-approved', 'The build plan is still a draft.', 'Approve the reviewed plan before release.'));
|
|
80
|
+
if (plan.indexable === 0) findings.push(finding('no-indexable-pages', 'The release has no indexable pages.', 'Approve evidence and explicitly index the routes intended for public discovery.'));
|
|
81
|
+
} catch (error) {
|
|
82
|
+
findings.push(finding('plan-invalid', error.message, 'Repair and approve the build plan.'));
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
if (!project.site || /example\.com/i.test(project.site)) findings.push(finding('project-site-placeholder', `Project site is still ${project.site || 'unset'}.`, 'Set the production canonical site URL.'));
|
|
86
|
+
const directionFile = path.join(projectDir, 'DESIGN-DIRECTION.md');
|
|
87
|
+
if (!fs.existsSync(directionFile) || /status:\s*unselected/i.test(fs.readFileSync(directionFile, 'utf8'))) findings.push(finding('design-direction-unapproved', 'The design direction is missing or still unselected.', 'Approve and record the project-owned visual direction before release.'));
|
|
88
|
+
const placeholderFiles = inputs.filter((file) => ['.json', '.md', '.mjs'].includes(path.extname(file))).filter((file) => PLACEHOLDER_PATTERN.test(fs.readFileSync(file, 'utf8')));
|
|
89
|
+
if (placeholderFiles.length) findings.push(finding('placeholder-content-remains', `Placeholder values remain in ${placeholderFiles.map((file) => path.relative(projectDir, file)).join(', ')}.`, 'Replace starter identity, contact, and incomplete canonical values with approved production data.'));
|
|
90
|
+
|
|
91
|
+
const workflow = readWorkflowState(projectDir, { required: false })?.data ?? null;
|
|
92
|
+
if (!workflow || workflow.status !== 'complete') findings.push(finding('workflow-incomplete', workflow ? `Workflow remains ${workflow.status} at ${workflow.currentStage}.` : 'No completed workflow exists.', 'Complete every required stage and approval.'));
|
|
93
|
+
const progress = optionalJson(path.join(projectDir, '.cosmo', 'progress.json'));
|
|
94
|
+
if (!progress || progress.invalid || progress.complete !== true) findings.push(finding('generation-incomplete', progress?.invalid ? 'Generation state is invalid.' : 'Generation is missing or incomplete.', 'Finish or reconcile every planned page through the generation pipeline.'));
|
|
95
|
+
|
|
96
|
+
const reports = REQUIRED_REPORTS.map((name) => {
|
|
97
|
+
const file = path.join(projectDir, '.cosmo', 'reports', `${name}.json`);
|
|
98
|
+
const data = optionalJson(file);
|
|
99
|
+
let status = 'missing';
|
|
100
|
+
if (data?.invalid) status = 'invalid';
|
|
101
|
+
else if (data) status = data.passed === true ? 'passed' : 'failed';
|
|
102
|
+
if (status === 'passed' && fs.statSync(file).mtimeMs < latestInputMtime) status = 'stale';
|
|
103
|
+
if (status !== 'passed') findings.push(finding(`report-${status}`, `${name}.json is ${status}.`, `Rerun the ${name.replace('-check', '')} check after the latest source changes.`));
|
|
104
|
+
return { name, path: `.cosmo/reports/${name}.json`, status, checkedAt: data?.checkedAt ?? null };
|
|
105
|
+
});
|
|
106
|
+
const intelligenceReport = optionalJson(path.join(projectDir, '.cosmo', 'reports', 'intelligence-check.json'));
|
|
107
|
+
if (intelligenceReport && !intelligenceReport.invalid && JSON.stringify(intelligenceReport.selectedPacks ?? []) !== JSON.stringify(intelligence.packs)) findings.push(finding('intelligence-selection-drift', 'The intelligence report was produced for a different pack selection.', 'Rerun cosmo intelligence check with the current selection.'));
|
|
108
|
+
|
|
109
|
+
const report = {
|
|
110
|
+
version: 1,
|
|
111
|
+
releaseId: releaseHash(projectDir, inputs),
|
|
112
|
+
ready: findings.length === 0,
|
|
113
|
+
checkedAt: new Date().toISOString(),
|
|
114
|
+
project: { name: project.name, brand: project.brand, site: project.site, stage: project.stage },
|
|
115
|
+
intelligence: { profile: intelligence.profile, packs: intelligence.packs },
|
|
116
|
+
plan,
|
|
117
|
+
workflow: workflow ? { status: workflow.status, workflowId: workflow.workflowId, currentStage: workflow.currentStage } : null,
|
|
118
|
+
generation: progress && !progress.invalid ? { complete: progress.complete, summary: progress.summary ?? null } : null,
|
|
119
|
+
reports,
|
|
120
|
+
summary: { blocking: findings.length },
|
|
121
|
+
findings,
|
|
122
|
+
};
|
|
123
|
+
return report;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
export function writeDeliveryReport(projectDir, report) {
|
|
127
|
+
const jsonFile = path.join(projectDir, '.cosmo', 'reports', 'delivery-check.json');
|
|
128
|
+
const markdownFile = path.join(projectDir, 'DELIVERY.md');
|
|
129
|
+
writeJson(jsonFile, report);
|
|
130
|
+
fs.writeFileSync(markdownFile, renderDelivery(report));
|
|
131
|
+
return { jsonFile, markdownFile };
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
export function readDelivery(projectDir) {
|
|
135
|
+
readProject(projectDir);
|
|
136
|
+
const jsonFile = path.join(projectDir, '.cosmo', 'reports', 'delivery-check.json');
|
|
137
|
+
const markdownFile = path.join(projectDir, 'DELIVERY.md');
|
|
138
|
+
if (!fs.existsSync(jsonFile) || !fs.existsSync(markdownFile)) throw new Error('No delivery evaluation exists. Run cosmo release check first.');
|
|
139
|
+
return { data: JSON.parse(fs.readFileSync(jsonFile, 'utf8')), markdown: fs.readFileSync(markdownFile, 'utf8'), jsonFile, markdownFile };
|
|
140
|
+
}
|
|
@@ -0,0 +1,211 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import crypto from 'node:crypto';
|
|
4
|
+
import { evaluateDelivery } from './delivery.mjs';
|
|
5
|
+
import { executeFileTransfer, loadDeploymentEnvironment } from './file-transfer.mjs';
|
|
6
|
+
import { runCaptured } from './process.mjs';
|
|
7
|
+
import { readProject, slugify, writeJson } from './project.mjs';
|
|
8
|
+
|
|
9
|
+
export class DeploymentError extends Error {}
|
|
10
|
+
|
|
11
|
+
const PROVIDERS = ['cloudflare-pages', 'sftp', 'ftps', 'ftp'];
|
|
12
|
+
const TRANSFER_PROVIDERS = new Set(['sftp', 'ftps', 'ftp']);
|
|
13
|
+
|
|
14
|
+
function assert(condition, message) {
|
|
15
|
+
if (!condition) throw new DeploymentError(message);
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function configFile(projectDir) {
|
|
19
|
+
return path.join(projectDir, '.cosmo', 'deploy', 'config.json');
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function historyFile(projectDir) {
|
|
23
|
+
return path.join(projectDir, '.cosmo', 'deploy', 'history.jsonl');
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function assertId(value, label) {
|
|
27
|
+
assert(typeof value === 'string' && /^[a-z0-9][a-z0-9-]*$/.test(value), `${label} must be kebab-case.`);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function assertOutputDir(value) {
|
|
31
|
+
assert(typeof value === 'string' && value && !path.isAbsolute(value) && !value.split(/[\\/]/).includes('..'), 'Deployment outputDir must be a safe project-relative directory.');
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function assertEnvName(value, label, optional = false) {
|
|
35
|
+
if (optional && !value) return;
|
|
36
|
+
assert(typeof value === 'string' && /^[A-Za-z_][A-Za-z0-9_]*$/.test(value), `${label} must name a valid environment variable.`);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function assertRemoteDir(value, label, optional = false) {
|
|
40
|
+
if (optional && !value) return;
|
|
41
|
+
assert(typeof value === 'string' && value.trim() && !/[\0\r\n]/.test(value) && !value.split('/').includes('..'), `${label} must be a safe remote path.`);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function rejectUnknownFields(value, allowed) {
|
|
45
|
+
const unknown = Object.keys(value).filter((key) => !allowed.has(key));
|
|
46
|
+
assert(unknown.length === 0, `Deployment config contains unsupported fields: ${unknown.join(', ')}.`);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export function validateDeploymentConfig(value) {
|
|
50
|
+
assert(value && typeof value === 'object' && !Array.isArray(value), 'Deployment config must be an object.');
|
|
51
|
+
assert(value.version === 1, 'Deployment config version must be 1.');
|
|
52
|
+
assert(PROVIDERS.includes(value.provider), `Deployment provider must be one of: ${PROVIDERS.join(', ')}.`);
|
|
53
|
+
assertOutputDir(value.outputDir);
|
|
54
|
+
if (value.provider === 'cloudflare-pages') {
|
|
55
|
+
rejectUnknownFields(value, new Set(['version', 'provider', 'projectName', 'productionBranch', 'previewBranchPrefix', 'outputDir']));
|
|
56
|
+
assertId(value.projectName, 'Cloudflare projectName');
|
|
57
|
+
assertId(value.productionBranch, 'Cloudflare productionBranch');
|
|
58
|
+
assertId(value.previewBranchPrefix, 'Cloudflare previewBranchPrefix');
|
|
59
|
+
return value;
|
|
60
|
+
}
|
|
61
|
+
rejectUnknownFields(value, new Set([
|
|
62
|
+
'version', 'provider', 'host', 'port', 'usernameEnv', 'passwordEnv', 'privateKeyEnv', 'passphraseEnv',
|
|
63
|
+
'hostFingerprintEnv', 'remoteDir', 'previewRemoteDir', 'outputDir', 'implicitTls', 'allowInsecure',
|
|
64
|
+
]));
|
|
65
|
+
assert(typeof value.host === 'string' && /^[A-Za-z0-9.-]+$/.test(value.host), 'Transfer host must be a hostname or IP address without a URL scheme.');
|
|
66
|
+
assert(Number.isInteger(value.port) && value.port > 0 && value.port <= 65535, 'Transfer port must be between 1 and 65535.');
|
|
67
|
+
assertEnvName(value.usernameEnv, 'usernameEnv');
|
|
68
|
+
assertEnvName(value.passwordEnv, 'passwordEnv', value.provider === 'sftp');
|
|
69
|
+
assertEnvName(value.privateKeyEnv, 'privateKeyEnv', true);
|
|
70
|
+
assertEnvName(value.passphraseEnv, 'passphraseEnv', true);
|
|
71
|
+
assertEnvName(value.hostFingerprintEnv, 'hostFingerprintEnv', value.provider !== 'sftp');
|
|
72
|
+
assertRemoteDir(value.remoteDir, 'remoteDir');
|
|
73
|
+
assertRemoteDir(value.previewRemoteDir, 'previewRemoteDir', true);
|
|
74
|
+
assert(value.provider === 'sftp' || !value.privateKeyEnv, 'Private-key authentication is only available for SFTP.');
|
|
75
|
+
assert(value.provider === 'sftp' || !value.passphraseEnv, 'Key passphrases are only available for SFTP.');
|
|
76
|
+
assert(value.provider === 'sftp' || !value.hostFingerprintEnv, 'Host fingerprints are only available for SFTP.');
|
|
77
|
+
assert(value.provider === 'ftps' || !value.implicitTls, 'Implicit TLS is only available for FTPS.');
|
|
78
|
+
assert(value.provider !== 'ftp' || value.allowInsecure === true, 'Plain FTP requires allowInsecure: true. Prefer SFTP or FTPS.');
|
|
79
|
+
assert(value.provider === 'ftp' || !value.allowInsecure, 'allowInsecure is only valid for plain FTP.');
|
|
80
|
+
return value;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export function configureDeployment(projectDir, provider, options = {}) {
|
|
84
|
+
const project = readProject(projectDir).data;
|
|
85
|
+
assert(PROVIDERS.includes(provider), `Unknown deployment provider: ${provider}`);
|
|
86
|
+
const common = { version: 1, provider, outputDir: String(options.outputDir ?? 'dist') };
|
|
87
|
+
const config = provider === 'cloudflare-pages'
|
|
88
|
+
? { ...common, projectName: slugify(options.projectName ?? project.name), productionBranch: slugify(options.productionBranch ?? 'main'), previewBranchPrefix: slugify(options.previewBranchPrefix ?? 'cosmo-preview') }
|
|
89
|
+
: {
|
|
90
|
+
...common,
|
|
91
|
+
host: String(options.host ?? ''),
|
|
92
|
+
port: Number(options.port ?? (provider === 'sftp' ? 22 : provider === 'ftps' && options.implicitTls ? 990 : 21)),
|
|
93
|
+
usernameEnv: String(options.usernameEnv ?? 'COSMO_DEPLOY_USER'),
|
|
94
|
+
passwordEnv: options.passwordEnv === false ? undefined : String(options.passwordEnv ?? 'COSMO_DEPLOY_PASSWORD'),
|
|
95
|
+
privateKeyEnv: options.privateKeyEnv ? String(options.privateKeyEnv) : undefined,
|
|
96
|
+
passphraseEnv: options.passphraseEnv ? String(options.passphraseEnv) : undefined,
|
|
97
|
+
hostFingerprintEnv: provider === 'sftp' ? String(options.hostFingerprintEnv ?? 'COSMO_DEPLOY_HOST_FINGERPRINT') : undefined,
|
|
98
|
+
remoteDir: String(options.remoteDir ?? ''),
|
|
99
|
+
previewRemoteDir: options.previewRemoteDir ? String(options.previewRemoteDir) : undefined,
|
|
100
|
+
implicitTls: provider === 'ftps' ? Boolean(options.implicitTls) : undefined,
|
|
101
|
+
allowInsecure: provider === 'ftp' ? Boolean(options.allowInsecure) : undefined,
|
|
102
|
+
};
|
|
103
|
+
for (const key of Object.keys(config)) if (config[key] === undefined) delete config[key];
|
|
104
|
+
validateDeploymentConfig(config);
|
|
105
|
+
const file = configFile(projectDir);
|
|
106
|
+
writeJson(file, config);
|
|
107
|
+
return { file, data: config };
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
export function readDeploymentConfig(projectDir) {
|
|
111
|
+
readProject(projectDir);
|
|
112
|
+
const file = configFile(projectDir);
|
|
113
|
+
assert(fs.existsSync(file), 'Deployment is not configured. Run cosmo deploy configure first.');
|
|
114
|
+
return { file, data: validateDeploymentConfig(JSON.parse(fs.readFileSync(file, 'utf8'))) };
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
export function deploymentPreflight(projectDir, environment) {
|
|
118
|
+
assert(['preview', 'production'].includes(environment), 'Deployment environment must be preview or production.');
|
|
119
|
+
const config = readDeploymentConfig(projectDir).data;
|
|
120
|
+
assert(environment !== 'preview' || !TRANSFER_PROVIDERS.has(config.provider) || config.previewRemoteDir, 'File-transfer previews require a separate previewRemoteDir. Configure --preview-remote-dir to prevent overwriting production.');
|
|
121
|
+
const output = path.resolve(projectDir, config.outputDir);
|
|
122
|
+
const root = `${path.resolve(projectDir)}${path.sep}`;
|
|
123
|
+
assert(output.startsWith(root) && fs.existsSync(output) && fs.statSync(output).isDirectory(), `Build output is missing: ${config.outputDir}. Run npm run build first.`);
|
|
124
|
+
const delivery = evaluateDelivery(projectDir);
|
|
125
|
+
if (environment === 'production') {
|
|
126
|
+
const recordedFile = path.join(projectDir, '.cosmo', 'reports', 'delivery-check.json');
|
|
127
|
+
assert(fs.existsSync(recordedFile), 'Production deployment requires a recorded READY release. Run cosmo release check.');
|
|
128
|
+
const recorded = JSON.parse(fs.readFileSync(recordedFile, 'utf8'));
|
|
129
|
+
assert(recorded.ready === true, 'Production deployment requires a READY delivery manifest.');
|
|
130
|
+
assert(delivery.ready === true, `Production release is no longer ready:\n${delivery.findings.map((item) => `- ${item.code}: ${item.message}`).join('\n')}`);
|
|
131
|
+
assert(recorded.releaseId === delivery.releaseId, `Production release drifted from ${recorded.releaseId} to ${delivery.releaseId}. Rerun QA and cosmo release check.`);
|
|
132
|
+
}
|
|
133
|
+
return { config, environment, output, releaseId: delivery.releaseId, releaseReady: delivery.ready };
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
export function createDeploymentCommand(preflight) {
|
|
137
|
+
assert(preflight.config.provider === 'cloudflare-pages', 'This provider deploys through the file-transfer adapter.');
|
|
138
|
+
const branch = preflight.environment === 'production' ? preflight.config.productionBranch : `${preflight.config.previewBranchPrefix}-${preflight.releaseId}`.slice(0, 63).replace(/-+$/g, '');
|
|
139
|
+
return { command: 'npx', args: ['wrangler', 'pages', 'deploy', preflight.config.outputDir, '--project-name', preflight.config.projectName, '--branch', branch, '--commit-hash', preflight.releaseId, '--commit-message', `Cosmo ${preflight.environment} ${preflight.releaseId}`], branch };
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
function deploymentUrl(output) {
|
|
143
|
+
const urls = String(output).match(/https:\/\/[^\s)\]]+/g) ?? [];
|
|
144
|
+
return urls.at(-1)?.replace(/[.,]+$/, '') ?? null;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
function providerDeploymentId(output) {
|
|
148
|
+
return String(output).match(/\b[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}\b/i)?.[0] ?? null;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
function appendHistory(projectDir, record) {
|
|
152
|
+
const file = historyFile(projectDir);
|
|
153
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
154
|
+
fs.appendFileSync(file, `${JSON.stringify(record)}\n`);
|
|
155
|
+
return file;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
export function readDeploymentHistory(projectDir) {
|
|
159
|
+
readProject(projectDir);
|
|
160
|
+
const file = historyFile(projectDir);
|
|
161
|
+
if (!fs.existsSync(file)) return { file, records: [] };
|
|
162
|
+
return { file, records: fs.readFileSync(file, 'utf8').trim().split('\n').filter(Boolean).map((line) => JSON.parse(line)) };
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
function previousManifest(projectDir, records, preflight, remoteDir) {
|
|
166
|
+
const prior = records.toReversed().find((record) => record.status === 'deployed'
|
|
167
|
+
&& record.provider === preflight.config.provider
|
|
168
|
+
&& record.host === preflight.config.host
|
|
169
|
+
&& record.port === preflight.config.port
|
|
170
|
+
&& record.environment === preflight.environment
|
|
171
|
+
&& record.remoteDir === remoteDir
|
|
172
|
+
&& record.manifestPath);
|
|
173
|
+
if (!prior) return null;
|
|
174
|
+
const file = path.join(projectDir, prior.manifestPath);
|
|
175
|
+
return fs.existsSync(file) ? JSON.parse(fs.readFileSync(file, 'utf8')) : null;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
export async function deployProject(projectDir, environment, { build = true, runner = runCaptured, envFile, baseEnvironment = process.env, transferClientFactory } = {}) {
|
|
179
|
+
if (build) await runner('npm', ['run', 'build'], { cwd: projectDir });
|
|
180
|
+
const preflight = deploymentPreflight(projectDir, environment);
|
|
181
|
+
const startedAt = new Date().toISOString();
|
|
182
|
+
const baseRecord = { version: 1, id: `${preflight.releaseId}-${crypto.randomUUID().slice(0, 8)}`, provider: preflight.config.provider, projectName: preflight.config.projectName ?? null, host: preflight.config.host ?? null, port: preflight.config.port ?? null, environment, releaseId: preflight.releaseId, releaseReady: preflight.releaseReady, startedAt };
|
|
183
|
+
try {
|
|
184
|
+
let details;
|
|
185
|
+
if (preflight.config.provider === 'cloudflare-pages') {
|
|
186
|
+
const invocation = createDeploymentCommand(preflight);
|
|
187
|
+
const result = await runner(invocation.command, invocation.args, { cwd: projectDir });
|
|
188
|
+
const output = `${result.stdout ?? ''}\n${result.stderr ?? ''}`;
|
|
189
|
+
details = { branch: invocation.branch, providerDeploymentId: providerDeploymentId(output), url: deploymentUrl(output), rollbackEligible: environment === 'production' };
|
|
190
|
+
} else {
|
|
191
|
+
const remoteDir = environment === 'preview' ? preflight.config.previewRemoteDir : preflight.config.remoteDir;
|
|
192
|
+
const transfer = await executeFileTransfer(preflight, {
|
|
193
|
+
environment: loadDeploymentEnvironment(projectDir, envFile, baseEnvironment),
|
|
194
|
+
previousManifest: previousManifest(projectDir, readDeploymentHistory(projectDir).records, preflight, remoteDir),
|
|
195
|
+
clientFactory: transferClientFactory,
|
|
196
|
+
});
|
|
197
|
+
const manifestPath = `.cosmo/deploy/manifests/${baseRecord.id}.json`;
|
|
198
|
+
writeJson(path.join(projectDir, manifestPath), transfer.manifest);
|
|
199
|
+
details = { branch: null, remoteDir: transfer.remoteDir, uploaded: transfer.uploaded, skipped: transfer.skipped, totalFiles: transfer.manifest.files.length, manifestPath, providerDeploymentId: null, url: null, rollbackEligible: false };
|
|
200
|
+
}
|
|
201
|
+
const record = { ...baseRecord, ...details, completedAt: new Date().toISOString(), status: 'deployed' };
|
|
202
|
+
appendHistory(projectDir, record);
|
|
203
|
+
return record;
|
|
204
|
+
} catch (error) {
|
|
205
|
+
appendHistory(projectDir, { ...baseRecord, providerDeploymentId: null, url: null, rollbackEligible: false, completedAt: new Date().toISOString(), status: 'failed', error: 'Provider command failed. Review the terminal output and authentication state.' });
|
|
206
|
+
if (TRANSFER_PROVIDERS.has(preflight.config.provider)) {
|
|
207
|
+
throw new DeploymentError('File transfer failed. Verify the target, credentials, host fingerprint, and server permissions.', { cause: error });
|
|
208
|
+
}
|
|
209
|
+
throw error;
|
|
210
|
+
}
|
|
211
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { spawnSync } from 'node:child_process';
|
|
4
|
+
import { findChromeExecutable } from './browser-audit.mjs';
|
|
5
|
+
import { readProject } from './project.mjs';
|
|
6
|
+
|
|
7
|
+
function check(id, status, message, fix) {
|
|
8
|
+
return { id, status, message, ...(fix && status !== 'pass' ? { fix } : {}) };
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
function versionAtLeast(actual, required) {
|
|
12
|
+
const left = actual.split('.').map(Number);
|
|
13
|
+
const right = required.split('.').map(Number);
|
|
14
|
+
for (let index = 0; index < Math.max(left.length, right.length); index += 1) {
|
|
15
|
+
if ((left[index] ?? 0) > (right[index] ?? 0)) return true;
|
|
16
|
+
if ((left[index] ?? 0) < (right[index] ?? 0)) return false;
|
|
17
|
+
}
|
|
18
|
+
return true;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function diagnoseProject(projectDir) {
|
|
22
|
+
const checks = [];
|
|
23
|
+
try { readProject(projectDir); checks.push(check('project', 'pass', 'Cosmo project metadata is readable.')); }
|
|
24
|
+
catch (error) { checks.push(check('project', 'fail', error.message, 'Run this command inside a Cosmo project.')); }
|
|
25
|
+
const nodeOkay = versionAtLeast(process.versions.node, '22.12.0');
|
|
26
|
+
checks.push(check('node', nodeOkay ? 'pass' : 'fail', `Node ${process.versions.node}`, nodeOkay ? undefined : 'Install Node 22.12 or newer.'));
|
|
27
|
+
const npm = spawnSync('npm', ['--version'], { encoding: 'utf8' });
|
|
28
|
+
checks.push(check('npm', npm.status === 0 ? 'pass' : 'fail', npm.status === 0 ? `npm ${npm.stdout.trim()}` : 'npm is unavailable.', 'Install npm and ensure it is on PATH.'));
|
|
29
|
+
const packageFile = path.join(projectDir, 'package.json');
|
|
30
|
+
checks.push(check('package', fs.existsSync(packageFile) ? 'pass' : 'fail', fs.existsSync(packageFile) ? 'package.json is present.' : 'package.json is missing.', 'Restore the project package.json.'));
|
|
31
|
+
const modules = path.join(projectDir, 'node_modules');
|
|
32
|
+
checks.push(check('dependencies', fs.existsSync(modules) ? 'pass' : 'warn', fs.existsSync(modules) ? 'Dependencies are installed.' : 'Dependencies are not installed.', 'Run npm install.'));
|
|
33
|
+
try { const chrome = findChromeExecutable(); checks.push(check('browser', 'pass', `Browser QA executable: ${chrome}`)); }
|
|
34
|
+
catch (error) { checks.push(check('browser', 'warn', error.message, 'Install Chrome/Chromium or set COSMO_CHROME_PATH.')); }
|
|
35
|
+
const cosmoDirectory = path.join(projectDir, '.cosmo');
|
|
36
|
+
try { fs.accessSync(cosmoDirectory, fs.constants.R_OK | fs.constants.W_OK); checks.push(check('workspace', 'pass', '.cosmo is readable and writable.')); }
|
|
37
|
+
catch { checks.push(check('workspace', 'fail', '.cosmo is not readable and writable.', 'Correct directory permissions.')); }
|
|
38
|
+
const deployFile = path.join(cosmoDirectory, 'deploy', 'config.json');
|
|
39
|
+
checks.push(check('deployment', fs.existsSync(deployFile) ? 'pass' : 'warn', fs.existsSync(deployFile) ? 'A deployment target is configured.' : 'No deployment target is configured.', 'Run cosmo deploy configure when ready.'));
|
|
40
|
+
const summary = { pass: checks.filter((item) => item.status === 'pass').length, warn: checks.filter((item) => item.status === 'warn').length, fail: checks.filter((item) => item.status === 'fail').length };
|
|
41
|
+
return { version: 1, checkedAt: new Date().toISOString(), projectDir, passed: summary.fail === 0, summary, checks };
|
|
42
|
+
}
|