@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.
Files changed (92) hide show
  1. package/CHANGELOG.md +31 -0
  2. package/README.md +792 -0
  3. package/SECURITY.md +15 -0
  4. package/docs/AGENT-HANDOFF.md +44 -0
  5. package/docs/ARCHITECTURE-INTELLIGENCE.md +64 -0
  6. package/docs/ARCHITECTURE.md +97 -0
  7. package/docs/BRAND-DISCOVERY.md +12 -0
  8. package/docs/BROWSER-QA.md +40 -0
  9. package/docs/CLAUDE-LAUNCHER.md +72 -0
  10. package/docs/CONTENT-QA.md +62 -0
  11. package/docs/DELIVERY.md +40 -0
  12. package/docs/DEPLOYMENT.md +119 -0
  13. package/docs/FIRST-PARTY-CAPABILITIES.md +54 -0
  14. package/docs/GENERATION.md +81 -0
  15. package/docs/INTEGRITY.md +75 -0
  16. package/docs/INTELLIGENCE-PACKS.md +122 -0
  17. package/docs/OPERATIONS.md +7 -0
  18. package/docs/PAGE-PRODUCTION.md +81 -0
  19. package/docs/ROADMAP.md +184 -0
  20. package/docs/WORKFLOWS.md +71 -0
  21. package/package.json +97 -0
  22. package/packages/cli/bin/cosmo.mjs +901 -0
  23. package/packages/cli/lib/adoption.mjs +72 -0
  24. package/packages/cli/lib/audit.mjs +145 -0
  25. package/packages/cli/lib/brand.mjs +60 -0
  26. package/packages/cli/lib/browser-audit.mjs +177 -0
  27. package/packages/cli/lib/claude-plugin.mjs +64 -0
  28. package/packages/cli/lib/content-audit.mjs +184 -0
  29. package/packages/cli/lib/delivery.mjs +140 -0
  30. package/packages/cli/lib/deployment.mjs +211 -0
  31. package/packages/cli/lib/doctor.mjs +42 -0
  32. package/packages/cli/lib/file-transfer.mjs +143 -0
  33. package/packages/cli/lib/generation.mjs +319 -0
  34. package/packages/cli/lib/handoff.mjs +109 -0
  35. package/packages/cli/lib/integrity.mjs +315 -0
  36. package/packages/cli/lib/intelligence-audit.mjs +445 -0
  37. package/packages/cli/lib/intelligence.mjs +331 -0
  38. package/packages/cli/lib/page-work.mjs +154 -0
  39. package/packages/cli/lib/plan.mjs +229 -0
  40. package/packages/cli/lib/process.mjs +45 -0
  41. package/packages/cli/lib/project.mjs +113 -0
  42. package/packages/cli/lib/research.mjs +85 -0
  43. package/packages/cli/lib/status.mjs +46 -0
  44. package/packages/cli/lib/workflow.mjs +294 -0
  45. package/plugins/claude-code/cosmo/.claude-plugin/plugin.json +10 -0
  46. package/plugins/claude-code/cosmo/README.md +25 -0
  47. package/plugins/claude-code/cosmo/bin/cosmo +11 -0
  48. package/plugins/claude-code/cosmo/skills/cosmo/SKILL.md +122 -0
  49. package/plugins/claude-code/cosmo/skills/cosmo-help/SKILL.md +16 -0
  50. package/scripts/postinstall.mjs +14 -0
  51. package/templates/astro-site/.cosmo/brand/discovery.json +19 -0
  52. package/templates/astro-site/.cosmo/brand/entity-canon.json +20 -0
  53. package/templates/astro-site/.cosmo/brand/voice-profile.json +16 -0
  54. package/templates/astro-site/.cosmo/build-plan.json +75 -0
  55. package/templates/astro-site/.cosmo/capabilities/registry.json +21 -0
  56. package/templates/astro-site/.cosmo/evidence.json +11 -0
  57. package/templates/astro-site/.cosmo/intelligence/selection.json +5 -0
  58. package/templates/astro-site/.cosmo/policies/content-integrity.json +22 -0
  59. package/templates/astro-site/.cosmo/project.json +10 -0
  60. package/templates/astro-site/.cosmo/work/pages/about/brief.json +49 -0
  61. package/templates/astro-site/.cosmo/work/pages/home/brief.json +51 -0
  62. package/templates/astro-site/.cosmo/workflows/default.json +146 -0
  63. package/templates/astro-site/.env.example +7 -0
  64. package/templates/astro-site/AGENTS.md +26 -0
  65. package/templates/astro-site/CLAUDE.md +28 -0
  66. package/templates/astro-site/DESIGN-DIRECTION.md +9 -0
  67. package/templates/astro-site/README.md +17 -0
  68. package/templates/astro-site/astro.config.mjs +16 -0
  69. package/templates/astro-site/cosmo.config.mjs +12 -0
  70. package/templates/astro-site/gitignore.template +9 -0
  71. package/templates/astro-site/package.json +23 -0
  72. package/templates/astro-site/public/favicon.svg +5 -0
  73. package/templates/astro-site/src/components/PageView.astro +20 -0
  74. package/templates/astro-site/src/components/sections/Action.astro +24 -0
  75. package/templates/astro-site/src/components/sections/Evidence.astro +19 -0
  76. package/templates/astro-site/src/components/sections/Hero.astro +41 -0
  77. package/templates/astro-site/src/components/sections/Problem.astro +19 -0
  78. package/templates/astro-site/src/components/sections/Proof.astro +15 -0
  79. package/templates/astro-site/src/components/sections/SectionRenderer.astro +22 -0
  80. package/templates/astro-site/src/components/sections/Solution.astro +19 -0
  81. package/templates/astro-site/src/components/seo/SeoHead.astro +41 -0
  82. package/templates/astro-site/src/content/pages/about.md +52 -0
  83. package/templates/astro-site/src/content/pages/home.md +48 -0
  84. package/templates/astro-site/src/content.config.ts +133 -0
  85. package/templates/astro-site/src/env.d.ts +1 -0
  86. package/templates/astro-site/src/layouts/BaseLayout.astro +57 -0
  87. package/templates/astro-site/src/pages/[...slug].astro +22 -0
  88. package/templates/astro-site/src/pages/index.astro +9 -0
  89. package/templates/astro-site/src/pages/robots.txt.ts +6 -0
  90. package/templates/astro-site/src/styles/global.css +540 -0
  91. package/templates/astro-site/src/styles/tokens.css +27 -0
  92. package/templates/astro-site/tsconfig.json +9 -0
@@ -0,0 +1,143 @@
1
+ import crypto from 'node:crypto';
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import { parseEnv } from 'node:util';
5
+
6
+ function assert(condition, message) {
7
+ if (!condition) throw new Error(message);
8
+ }
9
+
10
+ function safeRemotePath(value, label) {
11
+ assert(typeof value === 'string' && value.trim(), `${label} is required.`);
12
+ assert(!/[\0\r\n]/.test(value) && !value.split('/').includes('..'), `${label} contains an unsafe path.`);
13
+ return value.replace(/\/+$/g, '') || '/';
14
+ }
15
+
16
+ function remoteJoin(root, relative) {
17
+ const base = safeRemotePath(root, 'Remote directory');
18
+ return `${base === '/' ? '' : base}/${relative.split(path.sep).join('/')}`;
19
+ }
20
+
21
+ export function loadDeploymentEnvironment(projectDir, envFile, baseEnvironment = process.env) {
22
+ if (!envFile) return { ...baseEnvironment };
23
+ const file = path.resolve(projectDir, envFile);
24
+ assert(fs.existsSync(file) && fs.statSync(file).isFile(), `Environment file does not exist: ${file}`);
25
+ const parsed = parseEnv(fs.readFileSync(file, 'utf8'));
26
+ return { ...parsed, ...baseEnvironment };
27
+ }
28
+
29
+ function requireEnvironment(environment, name, label, { optional = false } = {}) {
30
+ const value = environment[name];
31
+ if (optional && !value) return null;
32
+ assert(typeof value === 'string' && value.length > 0, `${label} is missing. Set ${name} in the environment or supplied env file.`);
33
+ return value;
34
+ }
35
+
36
+ export function resolveTransferCredentials(config, environment) {
37
+ const username = requireEnvironment(environment, config.usernameEnv, 'Deployment username');
38
+ const password = config.passwordEnv ? requireEnvironment(environment, config.passwordEnv, 'Deployment password', { optional: config.provider === 'sftp' }) : null;
39
+ const privateKey = config.privateKeyEnv ? requireEnvironment(environment, config.privateKeyEnv, 'SFTP private key', { optional: true }) : null;
40
+ assert(config.provider !== 'sftp' || password || privateKey, 'SFTP requires a password or private key in the configured environment variables.');
41
+ const hostFingerprint = config.hostFingerprintEnv ? requireEnvironment(environment, config.hostFingerprintEnv, 'SFTP host fingerprint') : null;
42
+ assert(!hostFingerprint || /^(?:SHA256:[A-Za-z0-9+/]+={0,2}|[A-Fa-f0-9]{64}|(?:[A-Fa-f0-9]{2}:){31}[A-Fa-f0-9]{2})$/.test(hostFingerprint), 'SFTP host fingerprint must be an OpenSSH SHA256 fingerprint or a SHA256 hex digest.');
43
+ return {
44
+ username,
45
+ password,
46
+ privateKey,
47
+ passphrase: config.passphraseEnv ? requireEnvironment(environment, config.passphraseEnv, 'SFTP key passphrase', { optional: true }) : null,
48
+ hostFingerprint,
49
+ };
50
+ }
51
+
52
+ export function collectUploadManifest(outputDir) {
53
+ const files = [];
54
+ function visit(directory) {
55
+ for (const entry of fs.readdirSync(directory, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
56
+ const absolute = path.join(directory, entry.name);
57
+ if (entry.isDirectory()) visit(absolute);
58
+ else if (entry.isFile()) {
59
+ const relative = path.relative(outputDir, absolute).split(path.sep).join('/');
60
+ const content = fs.readFileSync(absolute);
61
+ files.push({ path: relative, size: content.length, sha256: crypto.createHash('sha256').update(content).digest('hex') });
62
+ }
63
+ }
64
+ }
65
+ visit(outputDir);
66
+ return { version: 1, files };
67
+ }
68
+
69
+ export function changedUploadFiles(manifest, previousManifest) {
70
+ const prior = new Map((previousManifest?.files ?? []).map((file) => [file.path, file.sha256]));
71
+ return manifest.files.filter((file) => prior.get(file.path) !== file.sha256);
72
+ }
73
+
74
+ function fingerprintVerifier(expected) {
75
+ if (!expected) return undefined;
76
+ const normalizedExpected = expected.trim().startsWith('SHA256:')
77
+ ? Buffer.from(expected.trim().slice(7), 'base64').toString('hex')
78
+ : expected.trim().replaceAll(':', '').toLowerCase();
79
+ return (actual) => {
80
+ const left = Buffer.from(actual.trim().toLowerCase());
81
+ const right = Buffer.from(normalizedExpected);
82
+ return left.length === right.length && crypto.timingSafeEqual(left, right);
83
+ };
84
+ }
85
+
86
+ async function sftpClientFactory() {
87
+ const { default: SftpClient } = await import('ssh2-sftp-client');
88
+ const client = new SftpClient('cosmo-deploy');
89
+ return {
90
+ async connect(config, credentials) {
91
+ await client.connect({
92
+ host: config.host,
93
+ port: config.port,
94
+ username: credentials.username,
95
+ password: credentials.password ?? undefined,
96
+ privateKey: credentials.privateKey ?? undefined,
97
+ passphrase: credentials.passphrase ?? undefined,
98
+ hostHash: credentials.hostFingerprint ? 'sha256' : undefined,
99
+ hostVerifier: fingerprintVerifier(credentials.hostFingerprint),
100
+ });
101
+ },
102
+ mkdir: (remoteDir) => client.mkdir(remoteDir, true),
103
+ upload: (localFile, remoteFile) => client.fastPut(localFile, remoteFile),
104
+ close: () => client.end(),
105
+ };
106
+ }
107
+
108
+ async function ftpClientFactory() {
109
+ const { Client } = await import('basic-ftp');
110
+ const client = new Client();
111
+ return {
112
+ async connect(config, credentials) {
113
+ await client.access({ host: config.host, port: config.port, user: credentials.username, password: credentials.password, secure: config.provider === 'ftps' ? (config.implicitTls ? 'implicit' : true) : false });
114
+ },
115
+ mkdir: (remoteDir) => client.ensureDir(remoteDir),
116
+ upload: async (localFile, remoteFile) => {
117
+ const directory = remoteFile.slice(0, remoteFile.lastIndexOf('/')) || '/';
118
+ await client.ensureDir(directory);
119
+ await client.uploadFrom(localFile, remoteFile.slice(remoteFile.lastIndexOf('/') + 1));
120
+ },
121
+ close: async () => client.close(),
122
+ };
123
+ }
124
+
125
+ export async function executeFileTransfer(preflight, { environment, previousManifest = null, clientFactory } = {}) {
126
+ const credentials = resolveTransferCredentials(preflight.config, environment);
127
+ const remoteDir = safeRemotePath(preflight.environment === 'preview' ? preflight.config.previewRemoteDir : preflight.config.remoteDir, preflight.environment === 'preview' ? 'Preview remote directory' : 'Production remote directory');
128
+ const manifest = collectUploadManifest(preflight.output);
129
+ const changed = changedUploadFiles(manifest, previousManifest);
130
+ const factory = clientFactory ?? (preflight.config.provider === 'sftp' ? sftpClientFactory : ftpClientFactory);
131
+ const client = await factory();
132
+ try {
133
+ await client.connect(preflight.config, credentials);
134
+ await client.mkdir(remoteDir);
135
+ for (const file of changed) {
136
+ const localFile = path.join(preflight.output, ...file.path.split('/'));
137
+ await client.upload(localFile, remoteJoin(remoteDir, file.path));
138
+ }
139
+ } finally {
140
+ await client.close().catch(() => {});
141
+ }
142
+ return { manifest, remoteDir, uploaded: changed.length, skipped: manifest.files.length - changed.length };
143
+ }
@@ -0,0 +1,319 @@
1
+ import crypto from 'node:crypto';
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import { checkIntelligenceStage } from './intelligence.mjs';
5
+ import matter from 'gray-matter';
6
+ import { checkIntegrity, readIntegrity } from './integrity.mjs';
7
+ import { readPageWork } from './page-work.mjs';
8
+ import { pageParentId, pageRelatedIds, readPlan } from './plan.mjs';
9
+ import { writeJson } from './project.mjs';
10
+
11
+ export class GenerationError extends Error {}
12
+ export const PRODUCTION_STATES = ['planned', 'briefed', 'sourced', 'outlined', 'drafted', 'edited', 'verified', 'done'];
13
+
14
+ function assert(condition, message) {
15
+ if (!condition) throw new GenerationError(message);
16
+ }
17
+
18
+ function progressFile(projectDir) {
19
+ return path.join(projectDir, '.cosmo', 'progress.json');
20
+ }
21
+
22
+ function eventFile(projectDir) {
23
+ return path.join(projectDir, '.cosmo', 'generation.jsonl');
24
+ }
25
+
26
+ function hashPlan(file) {
27
+ return crypto.createHash('sha256').update(fs.readFileSync(file)).digest('hex');
28
+ }
29
+
30
+ function assertPlanUnchanged(plan, progress) {
31
+ assert(progress.planHash === hashPlan(plan.file), 'Build plan changed after generation started. Reconcile or restart generation before continuing.');
32
+ }
33
+
34
+ function assertWithinPageCap(plan, progress, pageId) {
35
+ if (!progress.maxPages) return;
36
+ const index = plan.data.pages.findIndex((page) => page.id === pageId);
37
+ assert(index >= 0 && index < progress.maxPages, `Page ${pageId} is outside the active generation cap (${progress.maxPages}).`);
38
+ }
39
+
40
+ function appendEvent(projectDir, event) {
41
+ fs.appendFileSync(eventFile(projectDir), `${JSON.stringify({ at: new Date().toISOString(), ...event })}\n`);
42
+ }
43
+
44
+ function refresh(progress) {
45
+ const values = Object.values(progress.pages);
46
+ const activeStatuses = progress.version >= 2 ? PRODUCTION_STATES.filter((status) => status !== 'done') : ['pending'];
47
+ progress.summary = {
48
+ total: values.length,
49
+ pending: values.filter((page) => activeStatuses.includes(page.status)).length,
50
+ done: values.filter((page) => page.status === 'done').length,
51
+ failed: values.filter((page) => page.status === 'failed').length,
52
+ ...(progress.version >= 2 ? { byState: Object.fromEntries(PRODUCTION_STATES.map((status) => [status, values.filter((page) => page.status === status).length])) } : {}),
53
+ };
54
+ progress.complete = progress.summary.pending === 0 && progress.summary.failed === 0;
55
+ progress.updatedAt = new Date().toISOString();
56
+ return progress;
57
+ }
58
+
59
+ function save(projectDir, progress, event) {
60
+ refresh(progress);
61
+ writeJson(progressFile(projectDir), progress);
62
+ if (event) appendEvent(projectDir, event);
63
+ return progress;
64
+ }
65
+
66
+ export function readProgress(projectDir) {
67
+ const file = progressFile(projectDir);
68
+ assert(fs.existsSync(file), 'Generation has not started. Run cosmo generate start.');
69
+ const data = JSON.parse(fs.readFileSync(file, 'utf8'));
70
+ assert([1, 2].includes(data.version), 'Generation progress version is unsupported.');
71
+ return { file, data };
72
+ }
73
+
74
+ export function startGeneration(projectDir, { maxPages = null } = {}) {
75
+ const plan = readPlan(projectDir);
76
+ for (const stage of ['brand', 'design', 'plan']) checkIntelligenceStage(projectDir, stage);
77
+ if (plan.data.version >= 2) checkIntegrity(projectDir);
78
+ if (maxPages !== null) assert(Number.isInteger(maxPages) && maxPages > 0, 'maxPages must be a positive integer.');
79
+ const existing = fs.existsSync(progressFile(projectDir)) ? readProgress(projectDir).data : null;
80
+ assert(!existing || existing.complete, 'Generation progress already exists and is incomplete. Use cosmo generate status or resume it.');
81
+ const now = new Date().toISOString();
82
+ const progressVersion = plan.data.version >= 3 ? 2 : 1;
83
+ const progress = {
84
+ version: progressVersion,
85
+ planHash: hashPlan(plan.file),
86
+ startedAt: now,
87
+ updatedAt: now,
88
+ maxPages,
89
+ failureStreak: 0,
90
+ stoppedReason: null,
91
+ complete: false,
92
+ pages: Object.fromEntries(plan.data.pages.map((page) => [page.id, {
93
+ status: progressVersion >= 2 ? 'planned' : 'pending',
94
+ contentFile: page.contentFile,
95
+ attempts: 0,
96
+ ...(progressVersion >= 2 ? { repairAttempts: 0, failedFrom: null } : {}),
97
+ updatedAt: now,
98
+ reason: null,
99
+ }])),
100
+ };
101
+ return save(projectDir, progress, { event: 'generation.started', pages: plan.data.pages.length, maxPages });
102
+ }
103
+
104
+ export function nextPage(projectDir) {
105
+ const plan = readPlan(projectDir);
106
+ const progress = readProgress(projectDir).data;
107
+ assertPlanUnchanged(plan, progress);
108
+ assert(!progress.complete, 'Generation is complete.');
109
+ if (progress.failureStreak >= 3) {
110
+ progress.stoppedReason = 'three-consecutive-failures';
111
+ save(projectDir, progress, { event: 'generation.stopped', reason: progress.stoppedReason });
112
+ throw new GenerationError('Generation stopped after three consecutive failures. Fix the systemic issue, then retry a page.');
113
+ }
114
+ const attempted = progress.summary.done + progress.summary.failed;
115
+ if (progress.maxPages && attempted >= progress.maxPages) {
116
+ progress.stoppedReason = 'page-cap-reached';
117
+ save(projectDir, progress, { event: 'generation.stopped', reason: progress.stoppedReason });
118
+ throw new GenerationError(`Generation page cap reached (${progress.maxPages}).`);
119
+ }
120
+ const activeStatuses = progress.version >= 2 ? PRODUCTION_STATES.filter((status) => status !== 'done') : ['pending'];
121
+ const page = plan.data.pages.find((candidate) => activeStatuses.includes(progress.pages[candidate.id].status));
122
+ assert(page, 'No active pages remain. Retry failed pages or inspect generation status.');
123
+ const production = progress.pages[page.id];
124
+ return {
125
+ ...page,
126
+ parentPage: pageParentId(plan.data, page) ? plan.data.pages.find((candidate) => candidate.id === pageParentId(plan.data, page)) : null,
127
+ relatedPages: pageRelatedIds(plan.data, page).map((id) => plan.data.pages.find((candidate) => candidate.id === id)),
128
+ ...(progress.version >= 2 ? { production: { status: production.status, nextState: nextProductionState(production.status), repairAttempts: production.repairAttempts, ...productionRequirement(page, production.status) } } : {}),
129
+ };
130
+ }
131
+
132
+ function nextProductionState(status) {
133
+ const index = PRODUCTION_STATES.indexOf(status);
134
+ return index >= 0 && index < PRODUCTION_STATES.length - 1 ? PRODUCTION_STATES[index + 1] : null;
135
+ }
136
+
137
+ function productionRequirement(page, status) {
138
+ const requirements = {
139
+ planned: { action: 'Validate the plan-derived page brief.', artifact: `.cosmo/work/pages/${page.id}/brief.json` },
140
+ briefed: { action: 'Complete and validate the source manifest.', artifact: `.cosmo/work/pages/${page.id}/sources.json` },
141
+ sourced: { action: 'Complete the claim-and-proof-aware outline.', artifact: `.cosmo/work/pages/${page.id}/outline.json` },
142
+ outlined: { action: 'Write the typed content entry.', artifact: page.contentFile },
143
+ drafted: { action: 'Complete the editorial review report.', artifact: `.cosmo/work/pages/${page.id}/editorial-report.json` },
144
+ edited: { action: 'Run deterministic page verification.', artifact: page.contentFile },
145
+ verified: { action: 'Record final page completion.', artifact: page.contentFile },
146
+ };
147
+ return requirements[status] ?? { action: null, artifact: null };
148
+ }
149
+
150
+ function contentExists(projectDir, page) {
151
+ const contentFile = path.resolve(projectDir, page.contentFile);
152
+ assert(fs.existsSync(contentFile) && fs.statSync(contentFile).isFile() && fs.statSync(contentFile).size > 0, `Content file is missing or empty: ${page.contentFile}`);
153
+ return contentFile;
154
+ }
155
+
156
+ function validatePageContent(projectDir, plan, page) {
157
+ const integrity = plan.version >= 2 ? readIntegrity(projectDir) : null;
158
+ if (plan.version >= 2) checkIntegrity(projectDir);
159
+ const pageId = page.id;
160
+ const contentFile = contentExists(projectDir, page);
161
+ const frontmatter = matter(fs.readFileSync(contentFile, 'utf8')).data;
162
+ if (plan.version >= 2) assert(frontmatter.entityId === page.contract.strengthensEntity, `Content for ${pageId} entityId does not match the plan.`);
163
+ assert(frontmatter.path === page.path, `Content path ${frontmatter.path} does not match planned path ${page.path}.`);
164
+ assert(frontmatter.pageType === page.type, `Content pageType ${frontmatter.pageType} does not match planned type ${page.type}.`);
165
+ const parentId = pageParentId(plan, page);
166
+ const parentPath = parentId ? plan.pages.find((candidate) => candidate.id === parentId)?.path : null;
167
+ if (parentPath) assert(frontmatter.links?.parent === parentPath, `Content for ${pageId} must link to parent ${parentPath}.`);
168
+ const relatedPaths = pageRelatedIds(plan, page).map((id) => plan.pages.find((candidate) => candidate.id === id)?.path);
169
+ for (const relatedPath of relatedPaths) {
170
+ assert(frontmatter.links?.related?.includes(relatedPath), `Content for ${pageId} is missing planned related link ${relatedPath}.`);
171
+ }
172
+ if (plan.version >= 3) {
173
+ assert(frontmatter.archetype === page.architecture.archetype, `Content for ${pageId} archetype does not match the plan.`);
174
+ assert(frontmatter.indexability === page.architecture.indexability, `Content for ${pageId} indexability does not match the plan.`);
175
+ assert(frontmatter.intent?.primary === page.architecture.intent.primary, `Content for ${pageId} primary intent does not match the plan.`);
176
+ assert(frontmatter.intent?.funnel === page.architecture.intent.funnel, `Content for ${pageId} funnel stage does not match the plan.`);
177
+ assert(frontmatter.intent?.awareness === page.architecture.intent.awareness, `Content for ${pageId} awareness stage does not match the plan.`);
178
+ assert(frontmatter.intent?.demandConfidence === page.architecture.intent.demandConfidence, `Content for ${pageId} demand confidence does not match the plan.`);
179
+ assert(JSON.stringify(frontmatter.intent?.queryPatterns) === JSON.stringify(page.architecture.intent.queryPatterns), `Content for ${pageId} query patterns do not match the plan.`);
180
+ for (const link of page.links.filter((item) => item.role === 'conversion')) {
181
+ const targetPath = plan.pages.find((candidate) => candidate.id === link.target)?.path;
182
+ assert(frontmatter.links?.conversion?.includes(targetPath), `Content for ${pageId} is missing planned conversion link ${targetPath}.`);
183
+ }
184
+ }
185
+ const requirements = plan.version >= 2 ? page.contract.carriesProof : page.evidenceRequired;
186
+ for (const requirement of requirements) {
187
+ const evidence = frontmatter.evidence?.find((item) => plan.version >= 2 ? item.id === requirement : item.claim === requirement);
188
+ assert(evidence?.status === 'supplied', `Content for ${pageId} is missing supplied evidence: ${requirement}`);
189
+ if (plan.version >= 2) {
190
+ assert(typeof evidence.source === 'string' && evidence.source.trim(), `Content for ${pageId} evidence ${requirement} needs a source.`);
191
+ assert(['owned', 'attributed', 'public'].includes(evidence.provenance), `Content for ${pageId} evidence ${requirement} needs valid provenance.`);
192
+ const proof = integrity.evidence.proofs.find((item) => item.id === requirement);
193
+ assert(proof?.status === 'verified', `Content for ${pageId} cannot use unverified ledger proof: ${requirement}`);
194
+ assert(evidence.source === proof.source, `Content for ${pageId} evidence ${requirement} source drifted from the evidence ledger.`);
195
+ assert(evidence.provenance === proof.provenance, `Content for ${pageId} evidence ${requirement} provenance drifted from the evidence ledger.`);
196
+ }
197
+ }
198
+ return contentFile;
199
+ }
200
+
201
+ function validateProductionWorkspace(projectDir, pageId, repairAttempt) {
202
+ readPageWork(projectDir, pageId, 'sources');
203
+ readPageWork(projectDir, pageId, 'outline');
204
+ readPageWork(projectDir, pageId, 'editorial', { repairAttempt });
205
+ }
206
+
207
+ export function advancePage(projectDir, pageId) {
208
+ const planResult = readPlan(projectDir);
209
+ const plan = planResult.data;
210
+ const progress = readProgress(projectDir).data;
211
+ assert(progress.version >= 2, 'Production-state advancement requires generation progress v2.');
212
+ assertPlanUnchanged(planResult, progress);
213
+ assertWithinPageCap(planResult, progress, pageId);
214
+ const page = plan.pages.find((candidate) => candidate.id === pageId);
215
+ assert(page, `Unknown planned page: ${pageId}`);
216
+ const record = progress.pages[pageId];
217
+ assert(PRODUCTION_STATES.includes(record.status) && record.status !== 'done', `Page ${pageId} cannot advance from ${record.status}.`);
218
+ const from = record.status;
219
+ const to = nextProductionState(from);
220
+ if (from === 'planned') checkIntegrity(projectDir);
221
+ if (from === 'briefed') readPageWork(projectDir, pageId, 'sources');
222
+ if (from === 'sourced') readPageWork(projectDir, pageId, 'outline');
223
+ if (from === 'outlined') contentExists(projectDir, page);
224
+ if (from === 'drafted') readPageWork(projectDir, pageId, 'editorial', { repairAttempt: record.repairAttempts });
225
+ if (from === 'edited') {
226
+ validateProductionWorkspace(projectDir, pageId, record.repairAttempts);
227
+ validatePageContent(projectDir, plan, page);
228
+ }
229
+ assert(to !== 'done', `Page ${pageId} is verified. Use cosmo generate complete ${pageId}.`);
230
+ record.status = to;
231
+ record.updatedAt = new Date().toISOString();
232
+ record.reason = null;
233
+ progress.failureStreak = 0;
234
+ progress.stoppedReason = null;
235
+ return save(projectDir, progress, { event: 'page.advanced', pageId, from, to });
236
+ }
237
+
238
+ export function completePage(projectDir, pageId) {
239
+ const planResult = readPlan(projectDir);
240
+ const plan = planResult.data;
241
+ const progress = readProgress(projectDir).data;
242
+ assertPlanUnchanged(planResult, progress);
243
+ assertWithinPageCap(planResult, progress, pageId);
244
+ const page = plan.pages.find((candidate) => candidate.id === pageId);
245
+ assert(page, `Unknown planned page: ${pageId}`);
246
+ const expectedStatus = progress.version >= 2 ? 'verified' : 'pending';
247
+ assert(progress.pages[pageId].status === expectedStatus, `Page ${pageId} is ${progress.pages[pageId].status}, not ${expectedStatus}.`);
248
+ if (progress.version >= 2) validateProductionWorkspace(projectDir, pageId, progress.pages[pageId].repairAttempts);
249
+ validatePageContent(projectDir, plan, page);
250
+ progress.pages[pageId] = {
251
+ ...progress.pages[pageId],
252
+ status: 'done',
253
+ attempts: progress.pages[pageId].attempts + 1,
254
+ updatedAt: new Date().toISOString(),
255
+ reason: null,
256
+ };
257
+ progress.failureStreak = 0;
258
+ progress.stoppedReason = null;
259
+ return save(projectDir, progress, { event: 'page.completed', pageId, contentFile: page.contentFile });
260
+ }
261
+
262
+ export function failPage(projectDir, pageId, reason) {
263
+ const plan = readPlan(projectDir);
264
+ const progress = readProgress(projectDir).data;
265
+ assertPlanUnchanged(plan, progress);
266
+ assert(progress.pages[pageId], `Unknown planned page: ${pageId}`);
267
+ const currentStatus = progress.pages[pageId].status;
268
+ const canFail = progress.version >= 2 ? PRODUCTION_STATES.includes(currentStatus) && currentStatus !== 'done' : currentStatus === 'pending';
269
+ assert(canFail, `Page ${pageId} cannot fail from ${currentStatus}.`);
270
+ assert(typeof reason === 'string' && reason.trim(), 'A failure reason is required.');
271
+ progress.pages[pageId] = {
272
+ ...progress.pages[pageId],
273
+ status: 'failed',
274
+ ...(progress.version >= 2 ? { failedFrom: currentStatus } : {}),
275
+ attempts: progress.pages[pageId].attempts + 1,
276
+ updatedAt: new Date().toISOString(),
277
+ reason: reason.trim(),
278
+ };
279
+ progress.failureStreak += 1;
280
+ return save(projectDir, progress, { event: 'page.failed', pageId, reason: reason.trim(), failureStreak: progress.failureStreak });
281
+ }
282
+
283
+ export function retryPage(projectDir, pageId) {
284
+ const plan = readPlan(projectDir);
285
+ const progress = readProgress(projectDir).data;
286
+ assertPlanUnchanged(plan, progress);
287
+ assert(progress.pages[pageId], `Unknown planned page: ${pageId}`);
288
+ assert(progress.pages[pageId].status === 'failed', `Page ${pageId} is not failed.`);
289
+ progress.pages[pageId].status = progress.version >= 2 ? progress.pages[pageId].failedFrom ?? 'planned' : 'pending';
290
+ if (progress.version >= 2) progress.pages[pageId].failedFrom = null;
291
+ progress.pages[pageId].reason = null;
292
+ progress.pages[pageId].updatedAt = new Date().toISOString();
293
+ progress.failureStreak = 0;
294
+ progress.stoppedReason = null;
295
+ return save(projectDir, progress, { event: 'page.retried', pageId });
296
+ }
297
+
298
+ export function recordRepair(projectDir, pageId, reason) {
299
+ const plan = readPlan(projectDir);
300
+ const progress = readProgress(projectDir).data;
301
+ assert(progress.version >= 2, 'Repair tracking requires generation progress v2.');
302
+ assertPlanUnchanged(plan, progress);
303
+ const record = progress.pages[pageId];
304
+ assert(record, `Unknown planned page: ${pageId}`);
305
+ assert(['drafted', 'edited', 'verified'].includes(record.status), `Page ${pageId} can record a repair only after drafting.`);
306
+ assert(typeof reason === 'string' && reason.trim(), 'A repair reason is required.');
307
+ if (record.repairAttempts >= 2) {
308
+ record.failedFrom = 'drafted';
309
+ record.status = 'failed';
310
+ record.reason = `human-review-required: ${reason.trim()}`;
311
+ record.updatedAt = new Date().toISOString();
312
+ return save(projectDir, progress, { event: 'page.human_review_required', pageId, reason: reason.trim(), repairAttempts: record.repairAttempts });
313
+ }
314
+ record.repairAttempts += 1;
315
+ record.status = 'drafted';
316
+ record.reason = reason.trim();
317
+ record.updatedAt = new Date().toISOString();
318
+ return save(projectDir, progress, { event: 'page.repair_recorded', pageId, reason: reason.trim(), repairAttempt: record.repairAttempts });
319
+ }
@@ -0,0 +1,109 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { readDeploymentHistory } from './deployment.mjs';
4
+ import { readIntelligence } from './intelligence.mjs';
5
+ import { planSummary, readPlan } from './plan.mjs';
6
+ import { readProject, writeJson } from './project.mjs';
7
+ import { readWorkflowState } from './workflow.mjs';
8
+
9
+ function optionalJson(file) {
10
+ if (!fs.existsSync(file)) return null;
11
+ try {
12
+ return JSON.parse(fs.readFileSync(file, 'utf8'));
13
+ } catch {
14
+ return { invalid: true };
15
+ }
16
+ }
17
+
18
+ function reportState(projectDir, name) {
19
+ const relative = `.cosmo/reports/${name}.json`;
20
+ const data = optionalJson(path.join(projectDir, relative));
21
+ if (!data) return { path: relative, status: 'missing' };
22
+ if (data.invalid) return { path: relative, status: 'invalid' };
23
+ return {
24
+ path: relative,
25
+ status: data.passed === true || data.ready === true ? 'passed' : 'failed',
26
+ critical: data.summary?.critical ?? data.summary?.blocking ?? null,
27
+ warnings: data.summary?.warnings ?? null,
28
+ };
29
+ }
30
+
31
+ function nextAction(workflow, generation) {
32
+ if (workflow?.status === 'active') return `Resume the ${workflow.currentStage} workflow stage.`;
33
+ if (generation && !generation.complete) {
34
+ if (generation.stoppedReason) return `Resolve generation stop: ${generation.stoppedReason}.`;
35
+ return 'Continue the next pending page in the generation queue.';
36
+ }
37
+ if (!workflow) return 'Start the local workflow and confirm project intake.';
38
+ return 'Review the requested change against the approved design and completed workflow.';
39
+ }
40
+
41
+ function renderMarkdown(handoff) {
42
+ const workflow = handoff.workflow
43
+ ? `${handoff.workflow.status}${handoff.workflow.currentStage ? ` at **${handoff.workflow.currentStage}**` : ''}`
44
+ : 'not started';
45
+ const generation = handoff.generation
46
+ ? `${handoff.generation.done}/${handoff.generation.total} complete, ${handoff.generation.failed} failed${handoff.generation.byState ? ` (${Object.entries(handoff.generation.byState).filter(([, count]) => count).map(([state, count]) => `${state}=${count}`).join(', ')})` : ''}`
47
+ : 'not started';
48
+ const deployment = handoff.deployment
49
+ ? `${handoff.deployment.status} ${handoff.deployment.environment} ${handoff.deployment.url ?? handoff.deployment.remoteDir ?? 'target unavailable'} (${handoff.deployment.releaseId})${handoff.deployment.totalFiles === null ? '' : `; ${handoff.deployment.uploaded} uploaded, ${handoff.deployment.totalFiles} total`}`
50
+ : 'not attempted';
51
+ const reports = handoff.reports.map((report) => `- \`${report.path}\`: **${report.status}**${report.critical === null ? '' : ` (${report.critical} critical, ${report.warnings} warnings)`}`).join('\n');
52
+ return `# Project Handoff\n\nCreated ${handoff.createdAt} from **${handoff.from}** to **${handoff.to}**.\n\n## Project\n\n- Brand: ${handoff.project.brand}\n- Site: ${handoff.project.site}\n- Project stage: ${handoff.project.stage}\n- Workflow: ${workflow}\n- Intelligence: ${handoff.intelligence.profile}${handoff.intelligence.packs.length ? ` (${handoff.intelligence.packs.join(', ')})` : ' (no optional packs)'}\n- Generation: ${generation}\n- Approved plan: ${handoff.plan ? `v${handoff.plan.version}, ${handoff.plan.pages} pages and ${handoff.plan.links} graph edges` : 'unavailable'}\n- Release: ${handoff.delivery ? `${handoff.delivery.ready ? 'ready' : 'blocked'} (${handoff.delivery.releaseId})` : 'not evaluated'}\n- Deployment: ${deployment}\n\n## Next action\n\n${handoff.nextAction}\n\n## Handoff note\n\n${handoff.note || 'No additional note was supplied.'}\n\n## Latest QA\n\n${reports}\n\n## Repository truth\n\nRead \`BRAND-BRIEF.md\`, \`.cosmo/brand/entity-canon.json\`, \`.cosmo/brand/voice-profile.json\`, \`.cosmo/evidence.json\`, \`.cosmo/intelligence/selection.json\`, every selected pack manifest and artifact, the relevant page brief, \`DESIGN-DIRECTION.md\`, \`.cosmo/build-plan.json\`, \`.cosmo/progress.json\`, \`DELIVERY.md\`, and deployment history when present. Do not infer approval or evidence from this summary; the underlying artifacts remain authoritative.\n`;
53
+ }
54
+
55
+ export function createHandoff(projectDir, { from = 'claude', to = 'codex', note = '' } = {}) {
56
+ const project = readProject(projectDir).data;
57
+ const workflow = readWorkflowState(projectDir, { required: false })?.data ?? null;
58
+ const generation = optionalJson(path.join(projectDir, '.cosmo', 'progress.json'));
59
+ const intelligence = readIntelligence(projectDir).data;
60
+ const delivery = optionalJson(path.join(projectDir, '.cosmo', 'reports', 'delivery-check.json'));
61
+ const deployment = readDeploymentHistory(projectDir).records.at(-1) ?? null;
62
+ let plan = null;
63
+ try {
64
+ plan = planSummary(readPlan(projectDir).data);
65
+ } catch {}
66
+ const handoff = {
67
+ version: 1,
68
+ createdAt: new Date().toISOString(),
69
+ from: String(from).trim() || 'claude',
70
+ to: String(to).trim() || 'codex',
71
+ note: String(note).trim(),
72
+ project: {
73
+ name: project.name,
74
+ brand: project.brand,
75
+ site: project.site,
76
+ stage: project.stage,
77
+ designMode: project.designMode,
78
+ },
79
+ workflow: workflow ? { status: workflow.status, currentStage: workflow.currentStage, workflowId: workflow.workflowId } : null,
80
+ intelligence: { profile: intelligence.profile, packs: intelligence.packs },
81
+ delivery: delivery && !delivery.invalid ? { ready: delivery.ready, releaseId: delivery.releaseId, checkedAt: delivery.checkedAt } : null,
82
+ deployment: deployment ? { provider: deployment.provider, status: deployment.status, environment: deployment.environment, releaseId: deployment.releaseId, url: deployment.url, remoteDir: deployment.remoteDir ?? null, uploaded: deployment.uploaded ?? null, totalFiles: deployment.totalFiles ?? null, completedAt: deployment.completedAt } : null,
83
+ generation: generation && !generation.invalid ? {
84
+ complete: generation.complete,
85
+ done: generation.summary?.done ?? 0,
86
+ total: generation.summary?.total ?? Object.keys(generation.pages ?? {}).length,
87
+ failed: generation.summary?.failed ?? 0,
88
+ byState: generation.summary?.byState ?? null,
89
+ stoppedReason: generation.stoppedReason ?? null,
90
+ } : null,
91
+ plan,
92
+ reports: [reportState(projectDir, 'integrity-check'), reportState(projectDir, 'intelligence-check'), reportState(projectDir, 'content-check'), reportState(projectDir, 'site-check'), reportState(projectDir, 'browser-check'), reportState(projectDir, 'delivery-check')],
93
+ };
94
+ handoff.nextAction = nextAction(handoff.workflow, handoff.generation);
95
+ const jsonFile = path.join(projectDir, '.cosmo', 'handoff.json');
96
+ const markdownFile = path.join(projectDir, 'HANDOFF.md');
97
+ writeJson(jsonFile, handoff);
98
+ fs.writeFileSync(markdownFile, renderMarkdown(handoff));
99
+ fs.appendFileSync(path.join(projectDir, '.cosmo', 'activity.jsonl'), `${JSON.stringify({ at: handoff.createdAt, event: 'handoff.created', from: handoff.from, to: handoff.to })}\n`);
100
+ return { data: handoff, jsonFile, markdownFile };
101
+ }
102
+
103
+ export function readHandoff(projectDir) {
104
+ readProject(projectDir);
105
+ const jsonFile = path.join(projectDir, '.cosmo', 'handoff.json');
106
+ const markdownFile = path.join(projectDir, 'HANDOFF.md');
107
+ if (!fs.existsSync(jsonFile) || !fs.existsSync(markdownFile)) throw new Error('No handoff exists. Run cosmo handoff create first.');
108
+ return { data: JSON.parse(fs.readFileSync(jsonFile, 'utf8')), markdown: fs.readFileSync(markdownFile, 'utf8'), jsonFile, markdownFile };
109
+ }