@cobola/dsh-geo 0.0.0-stage → 0.2.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/lib/score.js ADDED
@@ -0,0 +1,143 @@
1
+ /**
2
+ * Score a scan artifact against the fixed GEO rubric.
3
+ *
4
+ * Deterministic by construction: pure function of (artifact, rubric, now).
5
+ * Dimension scores are percentages of the applicable rule weight; the total is
6
+ * the weighted mean of the five dimensions using the product's fixed weights
7
+ * (25/20/25/15/15). `warn` earns half weight, `skip` is removed from the
8
+ * denominator. Numbers are rounded to one decimal place.
9
+ */
10
+
11
+ import { DIMENSIONS, RULES, RUBRIC_VERSION, evaluateRules } from './rules.js';
12
+
13
+ export const SCORE_VERSION = 'score@1';
14
+
15
+ const STATUS_FACTOR = { pass: 1, warn: 0.5, fail: 0, skip: 0 };
16
+
17
+ const GRADES = [
18
+ { min: 90, grade: 'A+', label: '优秀' },
19
+ { min: 80, grade: 'A', label: '良好' },
20
+ { min: 70, grade: 'B', label: '可用' },
21
+ { min: 55, grade: 'C', label: '待改进' },
22
+ { min: 40, grade: 'D', label: '薄弱' },
23
+ { min: 0, grade: 'F', label: '不可用' },
24
+ ];
25
+
26
+ export function gradeFor(total) {
27
+ return GRADES.find((entry) => total >= entry.min) ?? GRADES[GRADES.length - 1];
28
+ }
29
+
30
+ function round1(value) {
31
+ return Math.round(value * 10) / 10;
32
+ }
33
+
34
+ function toTime(value) {
35
+ if (value instanceof Date) return value.getTime();
36
+ if (typeof value === 'number') return value;
37
+ const parsed = Date.parse(String(value ?? ''));
38
+ if (!Number.isFinite(parsed)) {
39
+ throw new TypeError(`scoreScan needs a valid reference time, got: ${String(value)}`);
40
+ }
41
+ return parsed;
42
+ }
43
+
44
+ /**
45
+ * @param {object} scan Artifact from scanSite().
46
+ * @param {{now?: Date|string|number}} [options] Reference time for freshness.
47
+ * @returns {object} JSON-serialisable score report.
48
+ */
49
+ export function scoreScan(scan, options = {}) {
50
+ if (!scan || !Array.isArray(scan.pages)) {
51
+ throw new TypeError('scoreScan expects a scan artifact produced by scanSite()');
52
+ }
53
+ const nowMs = toTime(options.now ?? scan.scannedAt);
54
+ const primary = scan.pages.find((page) => page.depth === 0 && page.facts)
55
+ ?? scan.pages.find((page) => page.facts)
56
+ ?? null;
57
+ const factsPages = scan.pages.filter((page) => page.facts);
58
+
59
+ const findings = evaluateRules({
60
+ scan,
61
+ primary,
62
+ pages: scan.pages,
63
+ factsPages,
64
+ now: new Date(nowMs),
65
+ nowMs,
66
+ });
67
+
68
+ const dimensionOrder = new Map(DIMENSIONS.map((dimension, index) => [dimension.id, index]));
69
+ const ruleOrder = new Map(RULES.map((rule, index) => [rule.id, index]));
70
+ findings.sort((a, b) => (dimensionOrder.get(a.dimension) ?? 99) - (dimensionOrder.get(b.dimension) ?? 99)
71
+ || (ruleOrder.get(a.id) ?? 999) - (ruleOrder.get(b.id) ?? 999));
72
+
73
+ const dimensions = DIMENSIONS.map((dimension) => {
74
+ const own = findings.filter((finding) => finding.dimension === dimension.id);
75
+ const applicable = own.reduce((sum, finding) => sum + (finding.status === 'skip' ? 0 : finding.weight), 0);
76
+ const earned = own.reduce((sum, finding) => sum + finding.weight * (STATUS_FACTOR[finding.status] ?? 0), 0);
77
+ const score = applicable > 0 ? round1((earned / applicable) * 100) : 0;
78
+ return {
79
+ id: dimension.id,
80
+ title: dimension.title,
81
+ summary: dimension.summary,
82
+ weight: dimension.weight,
83
+ score,
84
+ scored: applicable > 0,
85
+ earnedWeight: round1(earned),
86
+ applicableWeight: applicable,
87
+ counts: {
88
+ pass: own.filter((finding) => finding.status === 'pass').length,
89
+ warn: own.filter((finding) => finding.status === 'warn').length,
90
+ fail: own.filter((finding) => finding.status === 'fail').length,
91
+ skip: own.filter((finding) => finding.status === 'skip').length,
92
+ },
93
+ };
94
+ });
95
+
96
+ const scoredDimensions = dimensions.filter((dimension) => dimension.scored);
97
+ const totalWeight = scoredDimensions.reduce((sum, dimension) => sum + dimension.weight, 0);
98
+ const total = round1(totalWeight > 0
99
+ ? scoredDimensions.reduce((sum, dimension) => sum + dimension.score * dimension.weight, 0) / totalWeight
100
+ : 0);
101
+ const grade = gradeFor(total);
102
+
103
+ const counts = {
104
+ pass: findings.filter((finding) => finding.status === 'pass').length,
105
+ warn: findings.filter((finding) => finding.status === 'warn').length,
106
+ fail: findings.filter((finding) => finding.status === 'fail').length,
107
+ skip: findings.filter((finding) => finding.status === 'skip').length,
108
+ };
109
+
110
+ const dimensionWeight = new Map(DIMENSIONS.map((dimension) => [dimension.id, dimension.weight]));
111
+ const actions = findings
112
+ .filter((finding) => finding.status === 'fail' || finding.status === 'warn')
113
+ .map((finding) => ({
114
+ ruleId: finding.id,
115
+ dimension: finding.dimension,
116
+ dimensionTitle: DIMENSIONS.find((dimension) => dimension.id === finding.dimension)?.title ?? finding.dimension,
117
+ title: finding.title,
118
+ status: finding.status,
119
+ weight: finding.weight,
120
+ evidence: finding.evidence,
121
+ fix: finding.fix,
122
+ impact: round1((finding.status === 'fail' ? 1 : 0.5) * finding.weight * (dimensionWeight.get(finding.dimension) ?? 0)),
123
+ }))
124
+ .sort((a, b) => b.impact - a.impact || (a.ruleId < b.ruleId ? -1 : a.ruleId > b.ruleId ? 1 : 0))
125
+ .slice(0, 10);
126
+
127
+ return {
128
+ version: SCORE_VERSION,
129
+ rubricVersion: RUBRIC_VERSION,
130
+ scannedAt: scan.scannedAt,
131
+ startUrl: scan.startUrl,
132
+ origin: scan.origin,
133
+ total,
134
+ grade: grade.grade,
135
+ gradeLabel: grade.label,
136
+ dimensions,
137
+ counts,
138
+ findings,
139
+ actions,
140
+ blockedByRobots: Boolean(scan.blockedByRobots),
141
+ stats: scan.stats ?? { pages: factsPages.length, requested: 0, bytes: 0 },
142
+ };
143
+ }
package/lib/store.js ADDED
@@ -0,0 +1,277 @@
1
+ /**
2
+ * Workspace-local audit storage.
3
+ *
4
+ * The plugin never writes outside `<cwd>/.dsh-geo/` (and subdirectories of it).
5
+ * Layout:
6
+ *
7
+ * .dsh-geo/latest.json full { scan, score, diff } for the last run
8
+ * .dsh-geo/history/<scannedAt>.json one payload per run (bounded to 50)
9
+ * .dsh-geo/report.md human-readable summary
10
+ * .dsh-geo/fix-plan.md/.json latest generated fix plan
11
+ */
12
+ import fs from 'node:fs/promises';
13
+ import path from 'node:path';
14
+
15
+ import { REPORT_FORMAT_VERSION, renderAuditMarkdown } from './report.js';
16
+
17
+ export const STORE_DIRNAME = '.dsh-geo';
18
+ export const FORMAT_VERSION = REPORT_FORMAT_VERSION;
19
+ export const HISTORY_LIMIT = 50;
20
+ export const DASHBOARD_TREND_LIMIT = 24;
21
+
22
+ /**
23
+ * Resolve the configured report directory, refusing anything outside `.dsh-geo/`.
24
+ * @param {string} cwd Session workspace root.
25
+ * @param {string} [configured]
26
+ */
27
+ export function resolveStoreDir(cwd, configured = STORE_DIRNAME) {
28
+ const root = path.resolve(cwd);
29
+ const allowed = path.join(root, STORE_DIRNAME);
30
+ const candidate = path.resolve(root, configured || STORE_DIRNAME);
31
+ if (candidate !== allowed && !candidate.startsWith(`${allowed}${path.sep}`)) {
32
+ throw new Error(`reportDir must stay inside ${STORE_DIRNAME}/ (got: ${configured})`);
33
+ }
34
+ return candidate;
35
+ }
36
+
37
+ /** Resolve a user-supplied report path, confined to the workspace. */
38
+ export function resolveWorkspaceFile(cwd, filePath) {
39
+ const root = path.resolve(cwd);
40
+ const resolved = path.resolve(root, filePath);
41
+ if (resolved !== root && !resolved.startsWith(`${root}${path.sep}`)) {
42
+ throw new Error(`report path must stay inside the workspace (got: ${filePath})`);
43
+ }
44
+ return resolved;
45
+ }
46
+
47
+ async function ensureDir(dir) {
48
+ await fs.mkdir(dir, { recursive: true });
49
+ }
50
+
51
+ async function writeFileAtomic(file, content) {
52
+ const temp = `${file}.tmp`;
53
+ await fs.writeFile(temp, content, 'utf8');
54
+ await fs.rename(temp, file);
55
+ }
56
+
57
+ async function writeJsonAtomic(file, value) {
58
+ await writeFileAtomic(file, `${JSON.stringify(value, null, 2)}\n`);
59
+ }
60
+
61
+ function historyName(scannedAt) {
62
+ const base = String(scannedAt ?? new Date(0).toISOString()).replace(/[:.]/g, '-');
63
+ return `${base}.json`;
64
+ }
65
+
66
+ async function readJson(file) {
67
+ try {
68
+ return JSON.parse(await fs.readFile(file, 'utf8'));
69
+ } catch (error) {
70
+ if (error?.code === 'ENOENT') return null;
71
+ throw new Error(`Cannot read ${file}: ${error.message}`);
72
+ }
73
+ }
74
+
75
+ /**
76
+ * Read the last audit payload.
77
+ * @param {string} storeDir
78
+ */
79
+ export async function readLatest(storeDir) {
80
+ return readJson(path.join(storeDir, 'latest.json'));
81
+ }
82
+
83
+ /**
84
+ * Persist one audit, its Markdown summary, and (bounded) history entry.
85
+ * @param {string} storeDir
86
+ * @param {{scan: object, report: object, diff?: object|null, previous?: object|null}} audit
87
+ */
88
+ export async function writeAudit(storeDir, { scan, report, diff = null, previous = null }) {
89
+ await ensureDir(storeDir);
90
+ const historyDir = path.join(storeDir, 'history');
91
+ await ensureDir(historyDir);
92
+
93
+ const payload = {
94
+ formatVersion: FORMAT_VERSION,
95
+ savedAt: scan.scannedAt,
96
+ url: scan.startUrl,
97
+ origin: scan.origin,
98
+ scan,
99
+ score: report,
100
+ diff,
101
+ previous: previous
102
+ ? {
103
+ scannedAt: previous.savedAt ?? previous.scan?.scannedAt ?? null,
104
+ total: previous.score?.total ?? null,
105
+ grade: previous.score?.grade ?? null,
106
+ }
107
+ : null,
108
+ };
109
+
110
+ const latestPath = path.join(storeDir, 'latest.json');
111
+ const historyPath = path.join(historyDir, historyName(scan.scannedAt));
112
+ const reportPath = path.join(storeDir, 'report.md');
113
+ const dashboardPath = path.join(storeDir, 'dashboard.json');
114
+
115
+ await writeJsonAtomic(latestPath, payload);
116
+ await writeJsonAtomic(historyPath, payload);
117
+ await writeFileAtomic(reportPath, renderAuditMarkdown(report, { scan, diff }));
118
+ await pruneHistory(historyDir);
119
+
120
+ const previousDashboard = await readDashboard(storeDir);
121
+ const dashboard = buildDashboard(scan, report, diff, previousDashboard);
122
+ await writeJsonAtomic(dashboardPath, dashboard);
123
+
124
+ return { latestPath, historyPath, reportPath, dashboardPath };
125
+ }
126
+
127
+ function dimensionSummary(dimensions) {
128
+ return dimensions.map((dimension) => ({
129
+ id: dimension.id,
130
+ title: dimension.title,
131
+ weight: dimension.weight,
132
+ score: dimension.score,
133
+ scored: dimension.scored !== false,
134
+ }));
135
+ }
136
+
137
+ function buildDashboard(scan, report, diff, previousDashboard) {
138
+ const priorTrend = Array.isArray(previousDashboard?.trend) ? previousDashboard.trend : [];
139
+ const trend = [...priorTrend, {
140
+ scannedAt: scan.scannedAt,
141
+ total: report.total,
142
+ grade: report.grade,
143
+ url: scan.startUrl,
144
+ }]
145
+ .filter((entry) => entry && typeof entry.total === 'number' && entry.scannedAt)
146
+ .slice(-DASHBOARD_TREND_LIMIT);
147
+
148
+ return {
149
+ formatVersion: FORMAT_VERSION,
150
+ generatedAt: scan.scannedAt,
151
+ url: scan.startUrl,
152
+ origin: scan.origin,
153
+ current: {
154
+ total: report.total,
155
+ grade: report.grade,
156
+ gradeLabel: report.gradeLabel,
157
+ counts: report.counts,
158
+ dimensions: dimensionSummary(report.dimensions),
159
+ },
160
+ previous: diff
161
+ ? {
162
+ scannedAt: diff.previous.scannedAt,
163
+ total: diff.previous.total,
164
+ grade: diff.previous.grade,
165
+ dimensions: diff.dimensions.map((dimension) => ({
166
+ id: dimension.id,
167
+ before: dimension.before,
168
+ after: dimension.after,
169
+ delta: dimension.delta,
170
+ })),
171
+ }
172
+ : null,
173
+ delta: diff
174
+ ? {
175
+ total: diff.total.delta,
176
+ fixed: diff.fixed.map((entry) => entry.ruleId),
177
+ regressed: diff.regressed.map((entry) => entry.ruleId),
178
+ stillFailing: diff.counts.stillFailing,
179
+ dimensions: diff.dimensions,
180
+ }
181
+ : null,
182
+ trend,
183
+ actions: report.actions.slice(0, 5).map((action) => ({
184
+ ruleId: action.ruleId,
185
+ dimensionTitle: action.dimensionTitle,
186
+ title: action.title,
187
+ status: action.status,
188
+ weight: action.weight,
189
+ evidence: action.evidence,
190
+ fix: action.fix,
191
+ })),
192
+ };
193
+ }
194
+
195
+ /** Read the latest dashboard payload, or null. */
196
+ export async function readDashboard(storeDir) {
197
+ return readJson(path.join(storeDir, 'dashboard.json'));
198
+ }
199
+
200
+ async function pruneHistory(historyDir) {
201
+ const names = (await fs.readdir(historyDir))
202
+ .filter((name) => name.endsWith('.json'))
203
+ .sort()
204
+ .reverse();
205
+ const stale = names.slice(HISTORY_LIMIT);
206
+ await Promise.all(stale.map((name) => fs.rm(path.join(historyDir, name), { force: true })));
207
+ }
208
+
209
+ /**
210
+ * List saved audits, newest first.
211
+ * @param {string} storeDir
212
+ * @param {number} [limit]
213
+ */
214
+ export async function listAudits(storeDir, limit = 20) {
215
+ const historyDir = path.join(storeDir, 'history');
216
+ let names;
217
+ try {
218
+ names = (await fs.readdir(historyDir)).filter((name) => name.endsWith('.json')).sort().reverse();
219
+ } catch (error) {
220
+ if (error?.code === 'ENOENT') return [];
221
+ throw error;
222
+ }
223
+ const entries = [];
224
+ for (const name of names.slice(0, limit)) {
225
+ const payload = await readJson(path.join(historyDir, name));
226
+ if (!payload?.score) continue;
227
+ entries.push({
228
+ file: name,
229
+ path: path.join(historyDir, name),
230
+ savedAt: payload.savedAt ?? null,
231
+ url: payload.url ?? null,
232
+ total: payload.score.total,
233
+ grade: payload.score.grade,
234
+ });
235
+ }
236
+ return entries;
237
+ }
238
+
239
+ /**
240
+ * Read one audit payload file.
241
+ * @param {string} file
242
+ */
243
+ export async function readAuditFile(file) {
244
+ const payload = await readJson(file);
245
+ if (!payload) throw new Error(`Audit file not found: ${file}`);
246
+ if (!payload.score) throw new Error(`Not an audit payload: ${file}`);
247
+ return payload;
248
+ }
249
+
250
+ /**
251
+ * Write the generated fix plan.
252
+ * @param {string} storeDir
253
+ * @param {{markdown: string, json: object}} plan
254
+ */
255
+ export async function writeFixPlan(storeDir, plan) {
256
+ await ensureDir(storeDir);
257
+ const planPath = path.join(storeDir, 'fix-plan.md');
258
+ const jsonPath = path.join(storeDir, 'fix-plan.json');
259
+ await writeFileAtomic(planPath, plan.markdown);
260
+ await writeJsonAtomic(jsonPath, plan.json);
261
+ return { planPath, jsonPath };
262
+ }
263
+
264
+ /**
265
+ * Read the last fix plan, when one exists.
266
+ * @param {string} storeDir
267
+ */
268
+ export async function readFixPlan(storeDir) {
269
+ try {
270
+ const markdown = await fs.readFile(path.join(storeDir, 'fix-plan.md'), 'utf8');
271
+ const json = await readJson(path.join(storeDir, 'fix-plan.json'));
272
+ return { markdown, json };
273
+ } catch (error) {
274
+ if (error?.code === 'ENOENT') return null;
275
+ throw error;
276
+ }
277
+ }
package/locale/en.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "Website visibility audit",
4
+ "description": "A read-only, reproducible GEO/SEO readiness audit: 45 auditable checks across five dimensions, with evidence and prioritized fixes. It never edits your site; re-run with the same reference time to verify changes."
5
+ }
6
+ }
package/locale/zh.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "网站可见性体检",
4
+ "description": "只读、可复现的生成式搜索与 SEO 结构体检:45 条可审计检查、五维评分、证据和按影响排序的修复清单。扫描不改站点;改动后可用同一参考时间复扫验证。"
5
+ }
6
+ }
package/package.json CHANGED
@@ -1,6 +1,68 @@
1
1
  {
2
2
  "name": "@cobola/dsh-geo",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "description": "Read-only, reproducible GEO/SEO website audits for DeepSeek Harness: inspect crawlability and citation-ready structure, return evidence and prioritized fixes, and never edit the site or promise rankings.",
5
+ "license": "Apache-2.0",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/cobola/dsh-geo.git"
9
+ },
10
+ "homepage": "https://github.com/cobola/dsh-geo#readme",
11
+ "bugs": {
12
+ "url": "https://github.com/cobola/dsh-geo/issues"
13
+ },
14
+ "type": "module",
15
+ "exports": {
16
+ ".": "./index.js",
17
+ "./client": "./client.js",
18
+ "./scan": "./lib/scan.js",
19
+ "./score": "./lib/score.js",
20
+ "./rules": "./lib/rules.js",
21
+ "./locale/*.json": "./locale/*.json",
22
+ "./icon": "./icon.svg"
23
+ },
24
+ "bin": {
25
+ "dsh-geo": "bin/dsh-geo.js"
26
+ },
27
+ "files": [
28
+ "index.js",
29
+ "client.js",
30
+ "cordis.patch.yml",
31
+ "lib",
32
+ "bin",
33
+ "locale/*.json",
34
+ "docs",
35
+ "icon.svg",
36
+ "README.md",
37
+ "LICENSE",
38
+ "NOTICE",
39
+ "SECURITY.md",
40
+ "CONTRIBUTING.md",
41
+ "CHANGELOG.md",
42
+ ".github/workflows/publish.yml",
43
+ "docs/NPM-TRUSTED-PUBLISHING.md"
44
+ ],
45
+ "engines": {
46
+ "dsh": ">=0.2.2-rc.5 <0.3.0"
47
+ },
48
+ "dsh": {
49
+ "bundle": {
50
+ "patch": "./cordis.patch.yml"
51
+ },
52
+ "client": {
53
+ "platform": "web",
54
+ "immediately": true,
55
+ "inject": [
56
+ "@deepseek-ai/dsh-client-ui-settings"
57
+ ]
58
+ }
59
+ },
60
+ "scripts": {
61
+ "test": "node --test test/*.test.js",
62
+ "test:fixtures": "node --test test/fixtures.test.js",
63
+ "docs": "node scripts/gen-docs.mjs"
64
+ },
65
+ "dependencies": {
66
+ "@deepseek-ai/schemastery": "^3.19.0"
67
+ }
68
+ }