@archangel70/cosmo 1.13.1 → 1.14.1

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 CHANGED
@@ -2,6 +2,20 @@
2
2
 
3
3
  All notable Cosmo changes are recorded here.
4
4
 
5
+ ## 1.14.1 — Wikimedia-safe EntityMap enrichment
6
+
7
+ - Throttled serial Wikidata searches to avoid request spikes on sites with many entities.
8
+ - Added a versioned, descriptive Wikimedia User-Agent with a public support URL and an optional operator-specific contact override.
9
+ - Added bounded HTTP 429 and 503 retries that honor `Retry-After` and otherwise use a Wikimedia-compatible exponential backoff.
10
+ - Added regression coverage for recovery after repeated rate limits and for the bounded failure path.
11
+
12
+ ## 1.14.0 — Native EntityMap and resilient browser signals
13
+
14
+ - Classified browser console messages explicitly marked as report-only CSP observations as visible, non-blocking warnings while keeping enforced CSP failures critical.
15
+ - Added a project-owned browser QA policy for narrow, case-insensitive console-message allowlist patterns without allowing uncaught page errors to be suppressed.
16
+ - Added native Astro EntityMap compilation from the approved route inventory and built HTML without requiring Cosmo Markdown pages or changing preserved source.
17
+ - Added native route classification, noindex filtering, per-route name/type overrides, native enrichment subjects, and build-before-compile command ordering.
18
+
5
19
  ## 1.13.1 — Resilient adopted-site QA
6
20
 
7
21
  - Changed browser navigation from open-ended network-idle waiting to bounded load navigation, with a short settle period for lazy scripts.
package/README.md CHANGED
@@ -4,7 +4,7 @@ Cosmo helps an AI coding assistant build a complete, original Astro website for
4
4
 
5
5
  You do **not** need to know how to code. Cosmo supports Claude Code, Codex, and Google Antigravity.
6
6
 
7
- Current version: **1.13.1**
7
+ Current version: **1.14.1**
8
8
 
9
9
  ## Quick install
10
10
 
@@ -82,7 +82,7 @@ This is the only part of the beginner setup that uses a terminal. It is one inst
82
82
  cosmo --version
83
83
  ```
84
84
 
85
- You should see `1.13.1` or a newer version. Cosmo automatically installs its Claude, Codex, and Antigravity launchers.
85
+ You should see `1.14.1` or a newer version. Cosmo automatically installs its Claude, Codex, and Antigravity launchers.
86
86
 
87
87
  ### On Windows
88
88
 
@@ -99,7 +99,7 @@ You should see `1.13.1` or a newer version. Cosmo automatically installs its Cla
99
99
  cosmo --version
100
100
  ```
101
101
 
102
- You should see `1.13.1` or a newer version. Cosmo automatically installs its Claude, Codex, and Antigravity launchers.
102
+ You should see `1.14.1` or a newer version. Cosmo automatically installs its Claude, Codex, and Antigravity launchers.
103
103
 
104
104
  ## Step 4: create your website folder
105
105
 
@@ -436,8 +436,12 @@ During setup, Cosmo can ask whether you want an EntityMap. If you say yes, it cr
436
436
 
437
437
  No paid service is required. Wikidata can suggest public identifiers; Google Knowledge Graph, Google Places, and TextRazor can be enabled later with your own keys. Suggestions stay private and never change or publish business information until a named person accepts them.
438
438
 
439
+ Wikidata requests are automatically serialized and throttled. Cosmo identifies itself with a public support URL, honors Wikimedia's `Retry-After` response, and retries temporary rate limits twice. You can optionally set `COSMO_WIKIMEDIA_CONTACT` in your ignored environment file to identify the site's operator with a current email address or full URL.
440
+
439
441
  Cosmo publishes `/entitymap.json` and `/entitymap.html`, adds the discovery links, and checks the files during release QA. Automated output remains clearly marked as a draft until you review it. EntityMap complements the site's Schema.org JSON-LD and does not promise higher rankings.
440
442
 
443
+ On an adopted Astro site, EntityMap uses the approved native route inventory and the site's built HTML. It does not require `src/content/pages`, replace hand-authored `.astro` pages, or change the existing design. Home and about represent the Organization, service and service-area routes become Services and Places, and other routes become Concepts unless a reviewed route override supplies a different name or core type.
444
+
441
445
  Advanced users can run:
442
446
 
443
447
  ```bash
@@ -537,6 +541,8 @@ The checks cover:
537
541
 
538
542
  Use `--no-build` when a current `dist` already exists. Use `--no-lighthouse` to skip Lighthouse during a browser-only diagnostic. If Chrome is in a non-standard location, set `COSMO_CHROME_PATH` to its executable.
539
543
 
544
+ Browser console and page errors normally block release. CSP messages explicitly marked `Report Only` are retained as non-blocking warnings, while enforced CSP failures remain critical. If a reviewed third-party tool emits another harmless diagnostic, add a narrow identifying substring to `.cosmo/policies/browser-audit.json`; Cosmo will keep the message visible as a warning instead of silently discarding it. See [Browser QA](docs/BROWSER-QA.md) for the policy format and safety guidance.
545
+
540
546
  ## Release readiness
541
547
 
542
548
  After workflow, generation, approvals, and QA are complete:
@@ -12,6 +12,21 @@ Every generated HTML route is rendered at:
12
12
 
13
13
  Each render checks successful navigation, horizontal overflow, console and page errors, WCAG 2 A/AA violations, and whether the first keyboard tab reaches an element with a visible focus treatment. Reduced-motion preference is enabled during the run.
14
14
 
15
+ Genuine JavaScript console errors and uncaught page errors are critical. Content Security Policy messages explicitly marked `Report Only` are preserved as `browser-console-allowed` warnings because the browser is reporting an observation rather than an enforced failure. An enforced CSP failure remains critical.
16
+
17
+ Projects can classify another known, reviewed console message as non-blocking by adding a distinctive substring to `.cosmo/policies/browser-audit.json`:
18
+
19
+ ```json
20
+ {
21
+ "version": 1,
22
+ "allowedConsolePatterns": [
23
+ "distinctive text from the reviewed third-party diagnostic"
24
+ ]
25
+ }
26
+ ```
27
+
28
+ Matching is case-insensitive and uses literal substrings, not regular expressions. Allowed messages remain visible in the JSON report as warnings, including the pattern that matched. Keep patterns narrow: broad entries such as `error`, a provider name, or a URL could hide unrelated failures. Page errors cannot be allowlisted.
29
+
15
30
  Navigation waits for the page load event for at most 45 seconds, then allows a short settle period for lazy scripts. It does not wait for network idle because maps, analytics, and other long-lived third-party requests may never become idle. A timed-out route is recorded as a critical finding for that viewport; Cosmo closes that page and continues checking the remaining routes so the JSON report always contains the partial run and every timeout observed.
16
31
 
17
32
  Normal-state full-page screenshots are written before the keyboard interaction. This keeps the reference captures useful for visual review while still testing the focus path independently.
@@ -18,6 +18,34 @@ When beginning a site, the assistant asks whether the user wants an EntityMap. I
18
18
 
19
19
  Only indexable pages are included by default. Set `includeNoindex` only after deciding that publicly accessible noindex pages should be represented.
20
20
 
21
+ ## Existing Astro sites
22
+
23
+ EntityMap supports adopted `native-astro` projects without converting them to Cosmo Markdown pages or changing their components and design. The approved `.cosmo/adoption/route-inventory.json` remains the route authority. Cosmo builds the existing site, then reads each inventoried route from `dist` and extracts its title, meta description, canonical URL, robots directive, H1, and first substantive paragraph.
24
+
25
+ Native routes are classified conservatively:
26
+
27
+ - `/` and `/about` (or `/about-us`) represent the canonical Organization.
28
+ - Routes below `/services/` become Services.
29
+ - Routes below `/service-areas/` become Places.
30
+ - Other routes, including guides, roof types, and calculators, become Concepts.
31
+
32
+ Noindex routes remain excluded unless `includeNoindex` is deliberately enabled. Missing built HTML for an approved route is a clear build/inventory error rather than silently producing an incomplete map.
33
+
34
+ When route structure alone is not specific enough, add a reviewed name or EntityMap v1.0 type override to `.cosmo/entities/config.json`:
35
+
36
+ ```json
37
+ {
38
+ "routeOverrides": {
39
+ "/calculators/roof-cost": {
40
+ "name": "Roof Cost Estimator",
41
+ "type": "Metric"
42
+ }
43
+ }
44
+ }
45
+ ```
46
+
47
+ Override keys are normalized site routes. Names must be non-empty and types must come from the EntityMap v1.0 core vocabulary. Organization routes always retain the approved Entity Canon name and identifier. The same native subjects are used by Wikidata, Google Knowledge Graph, Google Places, and TextRazor enrichment.
48
+
21
49
  ## Commands for advanced users
22
50
 
23
51
  ```bash
@@ -33,12 +61,15 @@ Approval records the reviewer and time, then changes the public status to `self-
33
61
 
34
62
  Wikidata is enabled by default and does not require a key. Google Knowledge Graph, Google Places, and TextRazor are available but disabled until the user chooses them.
35
63
 
64
+ Cosmo sends Wikidata searches serially with a short delay and identifies the client with its version and public support URL. If Wikidata responds with HTTP 429 or 503, Cosmo honors `Retry-After` and retries twice with exponential backoff when no delay is supplied. For installations that need an operator-specific contact, set `COSMO_WIKIMEDIA_CONTACT` to a current email address or full URL in the local environment; the public Cosmo issue tracker is the safe default.
65
+
36
66
  Provider settings live in `.cosmo/entities/config.json`. Keys belong in a local ignored environment file:
37
67
 
38
68
  ```dotenv
39
69
  COSMO_GOOGLE_KG_API_KEY=
40
70
  COSMO_GOOGLE_PLACES_API_KEY=
41
71
  COSMO_TEXTRAZOR_API_KEY=
72
+ COSMO_WIKIMEDIA_CONTACT=
42
73
  ```
43
74
 
44
75
  Run one provider at a time:
@@ -78,7 +109,7 @@ An absent Google or Wikidata result is never treated as proof that a business, p
78
109
 
79
110
  | Path | Purpose |
80
111
  | --- | --- |
81
- | `.cosmo/entities/config.json` | Feature status, review record, accepted matches, and provider settings. |
112
+ | `.cosmo/entities/config.json` | Feature status, review record, native route overrides, accepted matches, and provider settings. |
82
113
  | `.cosmo/entities/candidates.json` | Private enrichment suggestions and their review state. |
83
114
  | `.cosmo/reports/entity-check.json` | Deterministic conformance and integrity report. |
84
115
  | `public/entitymap.json` | Generated machine-readable publication. |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@archangel70/cosmo",
3
- "version": "1.13.1",
3
+ "version": "1.14.1",
4
4
  "description": "Local-first, multi-agent Astro website builder for Claude, Codex, Antigravity, and the command line.",
5
5
  "license": "UNLICENSED",
6
6
  "type": "module",
@@ -65,7 +65,7 @@ import {
65
65
  workflowSummary,
66
66
  } from '../lib/workflow.mjs';
67
67
 
68
- const VERSION = '1.13.1';
68
+ const VERSION = '1.14.1';
69
69
  const cliDirectory = path.dirname(fileURLToPath(import.meta.url));
70
70
  const templateDirectory = path.resolve(cliDirectory, '../../../templates/astro-site');
71
71
  const [command = 'start', ...rawArgs] = process.argv.slice(2);
@@ -344,18 +344,31 @@ function prepareEntityMap(target) {
344
344
  return result;
345
345
  }
346
346
 
347
+ function usesNativeEntityMap(target) {
348
+ const project = readProject(target).data;
349
+ const config = readEntityMapConfig(target, { required: false }).data;
350
+ return project.sourceModel === 'native-astro' && config?.enabled === true;
351
+ }
352
+
353
+ async function prepareAndBuild(target, shouldBuild = true) {
354
+ const nativeEntityMap = usesNativeEntityMap(target);
355
+ if (shouldBuild && nativeEntityMap) await run('npm', ['run', 'build'], { cwd: target });
356
+ prepareEntityMap(target);
357
+ if (shouldBuild && !nativeEntityMap) await run('npm', ['run', 'build'], { cwd: target });
358
+ }
359
+
347
360
  async function build(args) {
348
361
  const { positional } = parseOptions(args);
349
362
  const target = projectDirectory(positional[0] ?? '.');
350
363
  readProject(target);
351
- prepareEntityMap(target);
352
- await run('npm', ['run', 'build'], { cwd: target });
364
+ await prepareAndBuild(target);
353
365
  }
354
366
 
355
367
  async function dev(args) {
356
368
  const { positional } = parseOptions(args);
357
369
  const target = projectDirectory(positional[0] ?? '.');
358
370
  readProject(target);
371
+ if (usesNativeEntityMap(target)) await run('npm', ['run', 'build'], { cwd: target });
359
372
  prepareEntityMap(target);
360
373
  await run('npm', ['run', 'dev'], { cwd: target });
361
374
  }
@@ -364,8 +377,7 @@ async function check(args) {
364
377
  const { options, positional } = parseOptions(args);
365
378
  const target = projectDirectory(positional[0] ?? '.');
366
379
  readProject(target);
367
- prepareEntityMap(target);
368
- if (!options['no-build']) await run('npm', ['run', 'build'], { cwd: target });
380
+ await prepareAndBuild(target, !options['no-build']);
369
381
  const report = auditDist(path.join(target, 'dist'));
370
382
  const reportFile = writeAuditReport(target, report);
371
383
  console.log(`Cosmo QA: ${report.summary.pages} pages, ${report.summary.critical} critical, ${report.summary.warnings} warnings`);
@@ -470,8 +482,7 @@ async function browserCheck(args) {
470
482
  const { options, positional } = parseOptions(args);
471
483
  const target = projectDirectory(positional[0] ?? '.');
472
484
  readProject(target);
473
- prepareEntityMap(target);
474
- if (!options['no-build']) await run('npm', ['run', 'build'], { cwd: target });
485
+ await prepareAndBuild(target, !options['no-build']);
475
486
  const server = await staticServer(target);
476
487
  const port = server.address().port;
477
488
  const baseUrl = `http://127.0.0.1:${port}/`;
@@ -575,6 +586,7 @@ async function entityCommand(args) {
575
586
  if (subcommand === 'build' || subcommand === 'check') {
576
587
  const { positional } = parseOptions(rest);
577
588
  const target = projectDirectory(positional[0] ?? '.');
589
+ if (usesNativeEntityMap(target)) await run('npm', ['run', 'build'], { cwd: target });
578
590
  const result = writeEntityMap(target);
579
591
  console.log(`EntityMap: ${result.report.enabled ? `${result.report.summary.entities} entities, ${result.report.summary.chunks} chunks` : 'disabled'}, ${result.report.summary.blocking} blocking, ${result.report.summary.warnings} warnings`);
580
592
  console.log(`Report: ${result.reportFile}`);
@@ -1056,14 +1068,14 @@ async function deployCommand(args) {
1056
1068
  const { options, positional } = parseOptions(rest);
1057
1069
  const target = projectDirectory(positional[0] ?? '.');
1058
1070
  readProject(target);
1059
- prepareEntityMap(target);
1060
- if (!options['no-build']) await run('npm', ['run', 'build'], { cwd: target });
1071
+ await prepareAndBuild(target, !options['no-build']);
1061
1072
  await run('npm', ['run', 'preview', '--', '--host', '127.0.0.1'], { cwd: target });
1062
1073
  return;
1063
1074
  }
1064
1075
  if (['preview', 'production'].includes(subcommand)) {
1065
1076
  const { options, positional } = parseOptions(rest);
1066
1077
  const target = projectDirectory(positional[0] ?? '.');
1078
+ if (!options['no-build'] && usesNativeEntityMap(target)) await run('npm', ['run', 'build'], { cwd: target });
1067
1079
  prepareEntityMap(target);
1068
1080
  const record = await deployProject(target, subcommand, { build: !options['no-build'], envFile: options['env-file'] });
1069
1081
  console.log(`${subcommand === 'production' ? 'Production' : 'Preview'} deployed: ${record.url ?? record.remoteDir ?? 'URL unavailable in provider output'}`);
@@ -14,6 +14,30 @@ const VIEWPORTS = [
14
14
  ];
15
15
  const NAVIGATION_TIMEOUT_MS = 45_000;
16
16
  const PAGE_SETTLE_MS = 250;
17
+ const REPORT_ONLY_CSP = /(?:\[report[ -]?only\]|report[ -]?only).*content security policy|content security policy.*report[ -]?only/i;
18
+
19
+ function browserAuditPolicy(projectDir) {
20
+ const file = path.join(projectDir, '.cosmo', 'policies', 'browser-audit.json');
21
+ if (!fs.existsSync(file)) return { allowedConsolePatterns: [] };
22
+ let policy;
23
+ try {
24
+ policy = JSON.parse(fs.readFileSync(file, 'utf8'));
25
+ } catch (error) {
26
+ throw new Error(`Invalid browser-audit policy at ${file}: ${error.message}`);
27
+ }
28
+ if (!Array.isArray(policy.allowedConsolePatterns) || policy.allowedConsolePatterns.some((item) => typeof item !== 'string' || !item.trim())) {
29
+ throw new Error(`Browser-audit policy allowedConsolePatterns must be an array of non-empty strings: ${file}`);
30
+ }
31
+ return { allowedConsolePatterns: policy.allowedConsolePatterns.map((item) => item.trim()) };
32
+ }
33
+
34
+ export function classifyConsoleError(message, allowedConsolePatterns = []) {
35
+ const text = String(message);
36
+ if (REPORT_ONLY_CSP.test(text)) return { allowed: true, matchedBy: 'built-in:report-only-csp' };
37
+ const normalized = text.toLowerCase();
38
+ const matched = allowedConsolePatterns.find((pattern) => normalized.includes(String(pattern).trim().toLowerCase()));
39
+ return matched ? { allowed: true, matchedBy: `project:${matched}` } : { allowed: false, matchedBy: null };
40
+ }
17
41
 
18
42
  function walk(directory, suffix) {
19
43
  if (!fs.existsSync(directory)) return [];
@@ -69,6 +93,7 @@ export async function auditBrowser(projectDir, { baseUrl, lighthouseEnabled = tr
69
93
  const distDir = path.join(projectDir, 'dist');
70
94
  const routes = walk(distDir, '.html').map((file) => routeForFile(distDir, file)).sort();
71
95
  if (!routes.length) throw new Error('No built HTML routes found for browser QA.');
96
+ const policy = browserAuditPolicy(projectDir);
72
97
  const screenshotsDir = path.join(projectDir, '.cosmo', 'reports', 'screenshots');
73
98
  fs.mkdirSync(screenshotsDir, { recursive: true });
74
99
  const browser = await browserType.launch({ executablePath, headless: true });
@@ -81,13 +106,17 @@ export async function auditBrowser(projectDir, { baseUrl, lighthouseEnabled = tr
81
106
  for (const viewport of VIEWPORTS) {
82
107
  let page = null;
83
108
  const runtimeErrors = [];
109
+ const allowedConsoleErrors = [];
84
110
  let stage = 'page-create';
85
111
  try {
86
112
  page = await browser.newPage({ viewport });
87
113
  page.on('console', (message) => {
88
114
  if (message.type() === 'error') {
89
115
  const location = message.location();
90
- runtimeErrors.push(`console: ${message.text()}${location.url ? ` (${location.url})` : ''}`);
116
+ const detail = `console: ${message.text()}${location.url ? ` (${location.url})` : ''}`;
117
+ const classification = classifyConsoleError(message.text(), policy.allowedConsolePatterns);
118
+ if (classification.allowed) allowedConsoleErrors.push({ detail, matchedBy: classification.matchedBy });
119
+ else runtimeErrors.push(detail);
91
120
  }
92
121
  });
93
122
  page.on('pageerror', (error) => runtimeErrors.push(`page: ${error.message}`));
@@ -140,7 +169,8 @@ export async function auditBrowser(projectDir, { baseUrl, lighthouseEnabled = tr
140
169
  else if (!focus.visible) critical.push({ route, viewport: viewport.width, rule: 'keyboard-focus-invisible', detail: focus });
141
170
 
142
171
  for (const detail of runtimeErrors) critical.push({ route, viewport: viewport.width, rule: 'browser-runtime-error', detail });
143
- pages.push({ route, viewport, dimensions, focus, violations: accessibility.violations.length, runtimeErrors, screenshot: path.relative(projectDir, screenshot) });
172
+ for (const detail of allowedConsoleErrors) warnings.push({ route, viewport: viewport.width, rule: 'browser-console-allowed', detail });
173
+ pages.push({ route, viewport, dimensions, focus, violations: accessibility.violations.length, runtimeErrors, allowedConsoleErrors, screenshot: path.relative(projectDir, screenshot) });
144
174
  } catch (error) {
145
175
  critical.push({
146
176
  route,
@@ -3,11 +3,19 @@ import fs from 'node:fs';
3
3
  import path from 'node:path';
4
4
  import matter from 'gray-matter';
5
5
  import { readProject, slugify, writeJson } from './project.mjs';
6
+ import { normalizeRoute, routeForFile } from './routes.mjs';
6
7
 
7
8
  const SPEC = 'https://entitymap.org/spec/v1.0';
8
9
  const TYPES = new Set(['Concept', 'ProprietaryTerm', 'Methodology', 'Metric', 'Taxonomy', 'Person', 'Organization', 'SoftwareProduct', 'PhysicalProduct', 'Service', 'Platform', 'Place', 'Event', 'Standard', 'Regulation']);
9
10
  const PREDICATES = new Set(['INSTANCE_OF', 'PART_OF', 'INCLUDES', 'DEPENDS_ON', 'REQUIRES', 'MEASURES', 'PRODUCED_BY', 'REGULATED_BY', 'AUTHORED_BY', 'AFFILIATED_WITH', 'COVERS', 'RELATES_TO', 'PRECEDES', 'ENABLES', 'PREVENTS', 'CONFLICTS_WITH', 'DESCRIBED_BY', 'OFFERS', 'IMPROVES', 'DEGRADES', 'LEADS_TO', 'SUITED_FOR', 'TARGETS', 'ACHIEVES']);
10
11
  const TIER_THREE = new Set(['IMPROVES', 'DEGRADES', 'LEADS_TO', 'SUITED_FOR', 'TARGETS', 'ACHIEVES']);
12
+ const WIKIDATA_REQUEST_INTERVAL_MS = 500;
13
+ const WIKIDATA_MAX_RETRIES = 2;
14
+ const WIKIDATA_CONTACT = 'https://github.com/ArchAngel70/cosmo/issues';
15
+ const COSMO_VERSION = (() => {
16
+ try { return JSON.parse(fs.readFileSync(new URL('../../../package.json', import.meta.url), 'utf8')).version; }
17
+ catch { return 'unknown'; }
18
+ })();
11
19
 
12
20
  export const DEFAULT_ENTITY_MAP_CONFIG = {
13
21
  version: 1,
@@ -16,6 +24,7 @@ export const DEFAULT_ENTITY_MAP_CONFIG = {
16
24
  verificationStatus: 'generator-draft',
17
25
  review: { reviewedBy: null, reviewedAt: null },
18
26
  approvedMatches: [],
27
+ routeOverrides: {},
19
28
  providers: {
20
29
  wikidata: { enabled: true },
21
30
  googleKnowledgeGraph: { enabled: false, apiKeyEnv: 'COSMO_GOOGLE_KG_API_KEY' },
@@ -51,6 +60,13 @@ export function readEntityMapConfig(projectDir, { required = true } = {}) {
51
60
  if (!['generator-draft', 'self-declared'].includes(data.verificationStatus)) throw new Error('EntityMap verificationStatus must be generator-draft or self-declared.');
52
61
  if (data.verificationStatus === 'self-declared' && (!data.review?.reviewedBy || !data.review?.reviewedAt)) throw new Error('A self-declared EntityMap requires an explicit human review record.');
53
62
  if (!Array.isArray(data.approvedMatches)) throw new Error('EntityMap approvedMatches must be an array.');
63
+ if (data.routeOverrides !== undefined && (!data.routeOverrides || typeof data.routeOverrides !== 'object' || Array.isArray(data.routeOverrides))) throw new Error('EntityMap routeOverrides must be an object keyed by route.');
64
+ for (const [route, override] of Object.entries(data.routeOverrides ?? {})) {
65
+ if (!route.startsWith('/') || !normalizeRoute(route) || !override || typeof override !== 'object' || Array.isArray(override)) throw new Error(`EntityMap route override is invalid: ${route}`);
66
+ if (override.name !== undefined && (typeof override.name !== 'string' || !override.name.trim())) throw new Error(`EntityMap route override name must be a non-empty string: ${route}`);
67
+ if (override.type !== undefined && !TYPES.has(override.type)) throw new Error(`EntityMap route override type is unsupported for ${route}: ${override.type}`);
68
+ }
69
+ data.routeOverrides ??= {};
54
70
  return { file, data };
55
71
  }
56
72
 
@@ -101,6 +117,116 @@ function contentPages(projectDir, includeNoindex) {
101
117
  }).filter((page) => page.data.path && page.data.title && page.data.description && (includeNoindex || page.data.indexability !== 'noindex'));
102
118
  }
103
119
 
120
+ function walkHtml(directory) {
121
+ if (!fs.existsSync(directory)) return [];
122
+ return fs.readdirSync(directory, { withFileTypes: true }).flatMap((entry) => {
123
+ const file = path.join(directory, entry.name);
124
+ return entry.isDirectory() ? walkHtml(file) : file.endsWith('.html') ? [file] : [];
125
+ });
126
+ }
127
+
128
+ function decodeHtml(value) {
129
+ const named = { amp: '&', apos: "'", gt: '>', lt: '<', nbsp: ' ', quot: '"' };
130
+ return String(value ?? '').replace(/&(#x[\da-f]+|#\d+|[a-z]+);/gi, (match, entity) => {
131
+ if (entity[0] === '#') {
132
+ const hexadecimal = entity[1]?.toLowerCase() === 'x';
133
+ const code = Number.parseInt(entity.slice(hexadecimal ? 2 : 1), hexadecimal ? 16 : 10);
134
+ return Number.isFinite(code) && code >= 0 && code <= 0x10ffff ? String.fromCodePoint(code) : match;
135
+ }
136
+ return named[entity.toLowerCase()] ?? match;
137
+ });
138
+ }
139
+
140
+ function plainText(value) {
141
+ return decodeHtml(String(value ?? '').replace(/<[^>]*>/g, ' ')).replace(/\s+/g, ' ').trim();
142
+ }
143
+
144
+ function attribute(tag, name) {
145
+ return tag.match(new RegExp(`\\b${name}\\s*=\\s*["']([^"']*)["']`, 'i'))?.[1]?.trim() ?? '';
146
+ }
147
+
148
+ function metaContent(html, name) {
149
+ const tag = [...html.matchAll(/<meta\b[^>]*>/gi)].map((match) => match[0]).find((item) => attribute(item, 'name').toLowerCase() === name);
150
+ return tag ? decodeHtml(attribute(tag, 'content')) : '';
151
+ }
152
+
153
+ function canonicalUrl(html) {
154
+ const tag = [...html.matchAll(/<link\b[^>]*>/gi)].map((match) => match[0]).find((item) => attribute(item, 'rel').toLowerCase().split(/\s+/).includes('canonical'));
155
+ return tag ? decodeHtml(attribute(tag, 'href')) : '';
156
+ }
157
+
158
+ function substantivePassage(html, fallback) {
159
+ const main = html.match(/<main\b[^>]*>([\s\S]*?)<\/main>/i)?.[1] ?? html.match(/<body\b[^>]*>([\s\S]*?)<\/body>/i)?.[1] ?? html;
160
+ const surface = main.replace(/<(?:script|style|noscript|svg|nav|header|footer|form)\b[^>]*>[\s\S]*?<\/(?:script|style|noscript|svg|nav|header|footer|form)>/gi, ' ');
161
+ const passages = [...surface.matchAll(/<p\b[^>]*>([\s\S]*?)<\/p>/gi)].map((match) => plainText(match[1])).filter((value) => value.length >= 40);
162
+ const selected = passages[0] ?? fallback;
163
+ if (selected.length <= 600) return selected;
164
+ const shortened = selected.slice(0, 600);
165
+ const boundary = shortened.lastIndexOf(' ');
166
+ return shortened.slice(0, boundary > 0 ? boundary : 600).trim();
167
+ }
168
+
169
+ function inferredNativeType(route) {
170
+ if (route === '/' || /^\/(?:about|about-us)$/.test(route)) return 'Organization';
171
+ if (route.startsWith('/services/')) return 'Service';
172
+ if (route.startsWith('/service-areas/')) return 'Place';
173
+ return 'Concept';
174
+ }
175
+
176
+ function nativePages(projectDir, project, config) {
177
+ const inventoryFile = path.join(projectDir, '.cosmo', 'adoption', 'route-inventory.json');
178
+ const inventory = readJson(inventoryFile, 'Native route inventory');
179
+ if (!Array.isArray(inventory.routes)) throw new Error(`Native route inventory routes must be an array: ${inventoryFile}`);
180
+ const distDir = path.join(projectDir, 'dist');
181
+ if (!fs.existsSync(distDir)) throw new Error('Native EntityMap requires built HTML in dist. Run the project build before EntityMap compilation.');
182
+ const htmlByRoute = new Map(walkHtml(distDir).map((file) => [normalizeRoute(routeForFile(distDir, file)), file]));
183
+ const overrides = new Map(Object.entries(config.routeOverrides ?? {}).map(([route, value]) => [normalizeRoute(route), value]));
184
+ const pages = [];
185
+ for (const [index, routeRecord] of inventory.routes.entries()) {
186
+ if (typeof routeRecord.path !== 'string' || !routeRecord.path.trim()) continue;
187
+ const route = normalizeRoute(routeRecord.path);
188
+ const file = htmlByRoute.get(route);
189
+ if (!file) throw new Error(`Native EntityMap could not find built HTML for ${routeRecord.path}. Run the project build and verify the approved route inventory.`);
190
+ const html = fs.readFileSync(file, 'utf8');
191
+ const title = plainText(html.match(/<title\b[^>]*>([\s\S]*?)<\/title>/i)?.[1]);
192
+ const description = metaContent(html, 'description');
193
+ const h1 = plainText(html.match(/<h1\b[^>]*>([\s\S]*?)<\/h1>/i)?.[1]);
194
+ const robots = metaContent(html, 'robots').toLowerCase().split(',').map((item) => item.trim());
195
+ const indexability = routeRecord.indexability === 'noindex' || robots.includes('noindex') ? 'noindex' : 'index';
196
+ if (!config.includeNoindex && indexability === 'noindex') continue;
197
+ if (!title || !description) throw new Error(`Native EntityMap route ${routeRecord.path} requires a built title and meta description.`);
198
+ const canonical = canonicalUrl(html);
199
+ const sourcePath = canonical || new URL(routeRecord.path, project.site).toString();
200
+ const override = overrides.get(route) ?? {};
201
+ const nativeType = override.type ?? inferredNativeType(route);
202
+ pages.push({
203
+ id: routeRecord.id || (route === '/' ? 'home' : slugify(route ?? routeRecord.source ?? `native-route-${index + 1}`)),
204
+ file,
205
+ native: true,
206
+ data: {
207
+ path: sourcePath,
208
+ route,
209
+ title,
210
+ description,
211
+ h1,
212
+ primaryTopic: override.name?.trim() || h1 || title,
213
+ pageType: nativeType === 'Service' ? 'service' : nativeType === 'Place' ? 'location' : 'native',
214
+ indexability,
215
+ nativeType,
216
+ nativeName: override.name?.trim() || null,
217
+ sections: [substantivePassage(html, description)],
218
+ },
219
+ });
220
+ }
221
+ return pages;
222
+ }
223
+
224
+ function entityPages(projectDir, project, config) {
225
+ return project.sourceModel === 'native-astro'
226
+ ? nativePages(projectDir, project, config)
227
+ : contentPages(projectDir, config.includeNoindex === true);
228
+ }
229
+
104
230
  function strings(value, key = '') {
105
231
  if (typeof value === 'string') return ['href', 'label', 'heading', 'eyebrow', 'title'].includes(key) ? [] : [value.trim()].filter(Boolean);
106
232
  if (Array.isArray(value)) return value.flatMap((item) => strings(item, key));
@@ -115,6 +241,13 @@ function chunkText(page) {
115
241
  }
116
242
 
117
243
  function entityIdentity(page, publisher) {
244
+ if (page.native) {
245
+ const type = page.data.nativeType;
246
+ if (type === 'Organization') return { entityId: publisher.id, '@type': 'Organization', name: publisher.officialName, description: publisher.descriptions.short };
247
+ const name = page.data.nativeName || page.data.h1 || page.data.title;
248
+ const prefixes = { Service: 'service', Place: 'place', Concept: 'topic' };
249
+ return { entityId: `${prefixes[type] ?? slugify(type)}-${slugify(name)}`, '@type': type, name, description: page.data.description };
250
+ }
118
251
  if ((['home', 'standard'].includes(page.data.pageType) && page.data.path === '/') || page.data.schemaType === 'AboutPage') {
119
252
  return { entityId: publisher.id, '@type': 'Organization', name: publisher.officialName, description: publisher.descriptions.short };
120
253
  }
@@ -147,7 +280,7 @@ export function compileEntityMap(projectDir) {
147
280
  const config = readEntityMapConfig(projectDir).data;
148
281
  if (!config.enabled) throw new Error('EntityMap is disabled for this project. Run cosmo entity init . --enable.');
149
282
  const publisher = readJson(path.join(projectDir, '.cosmo', 'brand', 'entity-canon.json'), 'Entity Canon');
150
- const pages = contentPages(projectDir, config.includeNoindex === true);
283
+ const pages = entityPages(projectDir, project, config);
151
284
  const grouped = new Map();
152
285
  for (const page of pages) {
153
286
  const identity = entityIdentity(page, publisher);
@@ -285,10 +418,31 @@ function candidateId(value) {
285
418
  return `candidate-${crypto.createHash('sha256').update([value.provider, value.entityId, value.externalId, value.uri].join('|')).digest('hex').slice(0, 16)}`;
286
419
  }
287
420
 
421
+ function sleep(milliseconds) {
422
+ return new Promise((resolve) => setTimeout(resolve, milliseconds));
423
+ }
424
+
425
+ function wikidataUserAgent() {
426
+ const configured = process.env.COSMO_WIKIMEDIA_CONTACT?.trim();
427
+ const contact = configured && !/[\r\n]/.test(configured) ? configured.slice(0, 500) : WIKIDATA_CONTACT;
428
+ return `Cosmo-EntityMap/${COSMO_VERSION} (${contact})`;
429
+ }
430
+
431
+ function retryAfterMilliseconds(response, attempt) {
432
+ const value = response.headers.get('retry-after')?.trim();
433
+ if (value && /^\d+$/.test(value)) return Number(value) * 1000;
434
+ if (value) {
435
+ const date = Date.parse(value);
436
+ if (Number.isFinite(date)) return Math.max(0, date - Date.now());
437
+ }
438
+ return 5000 * (2 ** attempt);
439
+ }
440
+
288
441
  function entitySubjects(projectDir) {
442
+ const project = readProject(projectDir).data;
289
443
  const publisher = readJson(path.join(projectDir, '.cosmo', 'brand', 'entity-canon.json'), 'Entity Canon');
290
444
  const config = readEntityMapConfig(projectDir).data;
291
- const pages = contentPages(projectDir, config.includeNoindex === true);
445
+ const pages = entityPages(projectDir, project, config);
292
446
  const subjects = new Map([[publisher.id, { entityId: publisher.id, name: publisher.officialName, type: 'Organization' }]]);
293
447
  for (const page of pages) {
294
448
  const identity = entityIdentity(page, publisher);
@@ -297,12 +451,23 @@ function entitySubjects(projectDir) {
297
451
  return { subjects: [...subjects.values()], pages, config };
298
452
  }
299
453
 
300
- async function enrichWikidata(subjects, fetchImpl) {
454
+ async function enrichWikidata(subjects, fetchImpl, {
455
+ sleepImpl = sleep,
456
+ requestIntervalMs = WIKIDATA_REQUEST_INTERVAL_MS,
457
+ maxRetries = WIKIDATA_MAX_RETRIES,
458
+ } = {}) {
301
459
  const values = [];
302
- for (const subject of subjects) {
460
+ for (const [index, subject] of subjects.entries()) {
461
+ if (index > 0 && requestIntervalMs > 0) await sleepImpl(requestIntervalMs);
303
462
  const url = new URL('https://www.wikidata.org/w/api.php');
304
463
  for (const [key, value] of Object.entries({ action: 'wbsearchentities', search: subject.name, language: 'en', uselang: 'en', format: 'json', limit: '5', origin: '*' })) url.searchParams.set(key, value);
305
- const response = await fetchImpl(url, { headers: { 'user-agent': 'Cosmo EntityMap Builder/1.0' } });
464
+ let response;
465
+ for (let attempt = 0; attempt <= maxRetries; attempt += 1) {
466
+ response = await fetchImpl(url, { headers: { 'user-agent': wikidataUserAgent() } });
467
+ if (![429, 503].includes(response.status)) break;
468
+ if (attempt === maxRetries) throw new Error(`Wikidata returned HTTP ${response.status} after ${maxRetries + 1} attempts. Wait before running enrichment again.`);
469
+ await sleepImpl(retryAfterMilliseconds(response, attempt));
470
+ }
306
471
  if (!response.ok) throw new Error(`Wikidata returned HTTP ${response.status}.`);
307
472
  const body = await response.json();
308
473
  for (const item of body.search ?? []) values.push({ provider: 'wikidata', entityId: subject.entityId, matchedName: item.label, externalId: item.id, uri: item.concepturi ?? `https://www.wikidata.org/wiki/${item.id}`, description: item.description ?? '', score: null });
@@ -353,7 +518,12 @@ async function enrichTextRazor(subjects, pages, key, fetchImpl) {
353
518
  return values;
354
519
  }
355
520
 
356
- export async function enrichEntityMap(projectDir, provider, { fetchImpl = fetch } = {}) {
521
+ export async function enrichEntityMap(projectDir, provider, {
522
+ fetchImpl = fetch,
523
+ sleepImpl = sleep,
524
+ wikidataRequestIntervalMs = WIKIDATA_REQUEST_INTERVAL_MS,
525
+ wikidataMaxRetries = WIKIDATA_MAX_RETRIES,
526
+ } = {}) {
357
527
  const { subjects, pages, config } = entitySubjects(projectDir);
358
528
  const providerConfig = config.providers?.[provider];
359
529
  if (!providerConfig) throw new Error(`Unknown EntityMap provider: ${provider}`);
@@ -361,7 +531,7 @@ export async function enrichEntityMap(projectDir, provider, { fetchImpl = fetch
361
531
  const key = providerConfig.apiKeyEnv ? process.env[providerConfig.apiKeyEnv] : null;
362
532
  if (providerConfig.apiKeyEnv && !key) throw new Error(`Missing ${providerConfig.apiKeyEnv}. Put it in a local environment file; never commit it.`);
363
533
  let raw = [];
364
- if (provider === 'wikidata') raw = await enrichWikidata(subjects, fetchImpl);
534
+ if (provider === 'wikidata') raw = await enrichWikidata(subjects, fetchImpl, { sleepImpl, requestIntervalMs: wikidataRequestIntervalMs, maxRetries: wikidataMaxRetries });
365
535
  if (provider === 'googleKnowledgeGraph') raw = await enrichGoogleKnowledgeGraph(subjects, key, fetchImpl);
366
536
  if (provider === 'googlePlaces') raw = await enrichGooglePlaces(subjects, key, fetchImpl);
367
537
  if (provider === 'textRazor') raw = await enrichTextRazor(subjects, pages, key, fetchImpl);
@@ -1,4 +1,4 @@
1
1
  {
2
2
  "name": "cosmo",
3
- "version": "1.13.1"
3
+ "version": "1.14.1"
4
4
  }
@@ -1,4 +1,4 @@
1
- <!-- cosmo-agent-version: 1.13.1 -->
1
+ <!-- cosmo-agent-version: 1.14.1 -->
2
2
  # Cosmo
3
3
 
4
4
  Use the Cosmo website-building workflow in the current workspace.
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cosmo",
3
- "version": "1.13.1",
3
+ "version": "1.14.1",
4
4
  "description": "Conversational launcher for starting, adopting, and resuming local-first Cosmo Astro website builds.",
5
5
  "author": {
6
6
  "name": "Cosmo"
@@ -8,6 +8,7 @@
8
8
  "reviewedAt": null
9
9
  },
10
10
  "approvedMatches": [],
11
+ "routeOverrides": {},
11
12
  "providers": {
12
13
  "wikidata": {
13
14
  "enabled": true
@@ -0,0 +1,4 @@
1
+ {
2
+ "version": 1,
3
+ "allowedConsolePatterns": []
4
+ }
@@ -7,6 +7,7 @@ COSMO_DEPLOY_PASSWORD=
7
7
  # COSMO_DEPLOY_HOST_FINGERPRINT=SHA256:replace-with-server-fingerprint
8
8
 
9
9
  # Optional EntityMap enrichment. Wikidata works without a key.
10
+ COSMO_WIKIMEDIA_CONTACT=
10
11
  # Enable a provider in .cosmo/entities/config.json before using it.
11
12
  # COSMO_GOOGLE_KG_API_KEY=
12
13
  # COSMO_GOOGLE_PLACES_API_KEY=
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cosmo/astro-starter",
3
- "version": "1.13.1",
3
+ "version": "1.14.1",
4
4
  "private": true,
5
5
  "type": "module",
6
6
  "scripts": {