@cobola/dsh-geo 0.0.0-stage → 0.3.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/index.js ADDED
@@ -0,0 +1,381 @@
1
+ /**
2
+ * Host half of the dsh-geo bundle.
3
+ *
4
+ * Registers the two model-facing tools:
5
+ * - geo_scan: audit a site and persist the report under `<cwd>/.dsh-geo/`
6
+ * - geo_fix_plan: turn the latest (or a named) audit into a prioritized plan
7
+ *
8
+ * Tools are registered as raw JSON-Schema definitions (the registry validates
9
+ * the declared shape; argument semantics are checked in `execute`), which keeps
10
+ * the bundle free of extra runtime packages except the Config schema.
11
+ */
12
+
13
+ import path from 'node:path';
14
+
15
+ import z from '@deepseek-ai/schemastery';
16
+
17
+ import { auditSite, persistAudit, planFromReport } from './lib/audit.js';
18
+ import { summarizeReport } from './lib/report.js';
19
+ import { resolveStoreDir } from './lib/store.js';
20
+
21
+ export const name = 'dsh-geo';
22
+
23
+ /** Services the tools need; `workingDirectory` supplies the session workspace. */
24
+ export const inject = ['tools', 'workingDirectory'];
25
+
26
+ const DEFAULT_SCAN = {
27
+ maxPages: 6,
28
+ respectRobots: true,
29
+ rateLimitMs: 250,
30
+ timeoutMs: 10_000,
31
+ maxBytes: 1_500_000,
32
+ reportDir: '.dsh-geo',
33
+ permitPrivateTargets: false,
34
+ };
35
+
36
+ export const Config = z.object({
37
+ maxPages: z.number().min(1).max(50).default(DEFAULT_SCAN.maxPages).volatile()
38
+ .description('Pages to crawl per scan (1–50).'),
39
+ respectRobots: z.boolean().default(DEFAULT_SCAN.respectRobots).volatile()
40
+ .description('Honor robots.txt for every request. Leave on for public sites.'),
41
+ rateLimitMs: z.number().min(0).max(60_000).default(DEFAULT_SCAN.rateLimitMs).volatile()
42
+ .description('Minimum interval between requests to one host, in milliseconds.'),
43
+ timeoutMs: z.number().min(500).max(120_000).default(DEFAULT_SCAN.timeoutMs).volatile()
44
+ .description('Per-request timeout, in milliseconds.'),
45
+ maxBytes: z.number().min(65_536).max(20_000_000).default(DEFAULT_SCAN.maxBytes).volatile()
46
+ .description('Maximum decoded response size per request, in bytes.'),
47
+ reportDir: z.string().default(DEFAULT_SCAN.reportDir).volatile()
48
+ .description('Report directory, relative to the session workspace and confined to .dsh-geo/.'),
49
+ permitPrivateTargets: z.boolean().default(DEFAULT_SCAN.permitPrivateTargets).volatile()
50
+ .description('Allow tools to audit loopback/private targets when a call passes allow_private.'),
51
+ });
52
+
53
+ function readConfig(config = {}) {
54
+ const get = (key) => {
55
+ const value = config[key];
56
+ if (value !== null && typeof value === 'object' && typeof value.get === 'function') return value.get();
57
+ return value === undefined ? DEFAULT_SCAN[key] : value;
58
+ };
59
+ return {
60
+ maxPages: get('maxPages'),
61
+ respectRobots: get('respectRobots'),
62
+ rateLimitMs: get('rateLimitMs'),
63
+ timeoutMs: get('timeoutMs'),
64
+ maxBytes: get('maxBytes'),
65
+ reportDir: get('reportDir'),
66
+ permitPrivateTargets: get('permitPrivateTargets'),
67
+ };
68
+ }
69
+
70
+ async function sessionCwd(ctx, exec) {
71
+ if (exec.agent === undefined) {
72
+ throw new Error('geo tools need an agent session with a working directory');
73
+ }
74
+ const cwd = await ctx.workingDirectory.ensure(exec.agent, exec.signal);
75
+ if (!cwd) throw new Error('geo tools could not resolve the session working directory');
76
+ return cwd;
77
+ }
78
+
79
+ function assertHttpUrl(value) {
80
+ let url;
81
+ try {
82
+ url = new URL(value);
83
+ } catch {
84
+ throw new Error(`url must be an absolute http(s) URL, got: ${value}`);
85
+ }
86
+ if (url.protocol !== 'http:' && url.protocol !== 'https:') {
87
+ throw new Error(`url must use http or https, got: ${url.protocol}`);
88
+ }
89
+ return url.href;
90
+ }
91
+
92
+ function assertInteger(value, { name, min, max }) {
93
+ if (value === undefined) return undefined;
94
+ if (!Number.isInteger(value) || value < min || value > max) {
95
+ throw new Error(`${name} must be an integer between ${min} and ${max}`);
96
+ }
97
+ return value;
98
+ }
99
+
100
+ function assertIsoTime(value) {
101
+ if (value === undefined) return undefined;
102
+ if (typeof value !== 'string' || !Number.isFinite(Date.parse(value))) {
103
+ throw new Error(`now must be an ISO-8601 timestamp, got: ${String(value)}`);
104
+ }
105
+ return value;
106
+ }
107
+
108
+ function relative(cwd, filePath) {
109
+ return path.relative(cwd, filePath);
110
+ }
111
+
112
+ const scanParameters = {
113
+ type: 'object',
114
+ additionalProperties: false,
115
+ required: ['url'],
116
+ properties: {
117
+ url: {
118
+ type: 'string',
119
+ description: 'Absolute http(s) URL of the site entry page to audit.',
120
+ },
121
+ max_pages: {
122
+ type: 'integer',
123
+ minimum: 1,
124
+ maximum: 50,
125
+ description: 'Override the configured crawl budget for this call.',
126
+ },
127
+ now: {
128
+ type: 'string',
129
+ description: 'ISO-8601 reference time for freshness checks. Reuse the previous value to isolate code changes from time passing.',
130
+ },
131
+ allow_private: {
132
+ type: 'boolean',
133
+ description: 'Audit a loopback/private target. Only works when permitPrivateTargets is enabled in the dsh-geo settings panel.',
134
+ },
135
+ save: {
136
+ type: 'boolean',
137
+ description: 'Persist the report into .dsh-geo/ and diff it against the previous scan. Defaults to true.',
138
+ },
139
+ },
140
+ };
141
+
142
+ const planParameters = {
143
+ type: 'object',
144
+ additionalProperties: false,
145
+ properties: {
146
+ report_path: {
147
+ type: 'string',
148
+ description: 'Path to a saved report JSON inside the workspace. Defaults to latest.json in the configured report directory.',
149
+ },
150
+ },
151
+ };
152
+
153
+ const countsSchema = {
154
+ type: 'object',
155
+ additionalProperties: false,
156
+ required: ['pass', 'warn', 'fail', 'skip'],
157
+ properties: {
158
+ pass: { type: 'integer' },
159
+ warn: { type: 'integer' },
160
+ fail: { type: 'integer' },
161
+ skip: { type: 'integer' },
162
+ },
163
+ };
164
+
165
+ const scanOutputSchema = {
166
+ type: 'object',
167
+ additionalProperties: false,
168
+ required: [
169
+ 'url', 'scannedAt', 'pages', 'total', 'grade', 'gradeLabel', 'counts',
170
+ 'dimensions', 'topActions', 'platforms', 'blockedByRobots', 'paths',
171
+ ],
172
+ properties: {
173
+ url: { type: 'string' },
174
+ scannedAt: { type: 'string' },
175
+ pages: { type: 'integer' },
176
+ total: { type: 'number' },
177
+ grade: { type: 'string' },
178
+ gradeLabel: { type: 'string' },
179
+ counts: countsSchema,
180
+ dimensions: { type: 'array', items: { type: 'object', additionalProperties: true } },
181
+ topActions: { type: 'array', items: { type: 'object', additionalProperties: true } },
182
+ platforms: { type: 'array', items: { type: 'object', additionalProperties: true } },
183
+ blockedByRobots: { type: 'boolean' },
184
+ comparison: { type: 'object', additionalProperties: true },
185
+ paths: { type: 'object', additionalProperties: true },
186
+ },
187
+ };
188
+
189
+ const planOutputSchema = {
190
+ type: 'object',
191
+ additionalProperties: false,
192
+ required: ['url', 'total', 'grade', 'actionCount', 'topActions', 'planPath', 'jsonPath'],
193
+ properties: {
194
+ url: { type: 'string' },
195
+ total: { type: 'number' },
196
+ grade: { type: 'string' },
197
+ actionCount: { type: 'integer' },
198
+ topActions: { type: 'array', items: { type: 'object', additionalProperties: true } },
199
+ comparison: { type: 'object', additionalProperties: true },
200
+ planPath: { type: 'string' },
201
+ jsonPath: { type: 'string' },
202
+ },
203
+ };
204
+
205
+ function scanRender(args, value) {
206
+ const lines = [];
207
+ lines.push(`GEO score: ${value.total}/100 (${value.grade} ${value.gradeLabel}) — ${value.url}`);
208
+ lines.push(`${value.pages} page(s), ${value.counts.pass} pass / ${value.counts.warn} partial / ${value.counts.fail} fail / ${value.counts.skip} n/a`);
209
+ lines.push('');
210
+ for (const dimension of value.dimensions) {
211
+ lines.push(`- ${dimension.title}: ${dimension.score} (weight ${dimension.weight})`);
212
+ }
213
+ for (const platform of value.platforms ?? []) {
214
+ lines.push(`- ${platform.title} (platform, not in Core score): ${platform.total}`);
215
+ }
216
+ if (value.blockedByRobots) {
217
+ lines.push('');
218
+ lines.push('robots.txt refused the audit; no pages were fetched.');
219
+ }
220
+ if (value.topActions.length > 0) {
221
+ lines.push('');
222
+ lines.push('Top priorities:');
223
+ value.topActions.forEach((action, index) => {
224
+ lines.push(`${index + 1}. [${action.dimensionTitle} ${action.weight}] ${action.title} — ${action.evidence}`);
225
+ lines.push(` fix: ${action.fix}`);
226
+ });
227
+ }
228
+ if (value.comparison && typeof value.comparison.totalDelta === 'number') {
229
+ lines.push('');
230
+ lines.push(`Compared with ${value.comparison.previousScannedAt}: ${value.comparison.before} → ${value.comparison.after} (${value.comparison.totalDelta >= 0 ? '+' : ''}${value.comparison.totalDelta})`);
231
+ }
232
+ if (value.paths.latest) {
233
+ lines.push('');
234
+ lines.push(`Saved: ${value.paths.latest} (history ${value.paths.history}, summary ${value.paths.report})`);
235
+ }
236
+ lines.push('Next: run geo_fix_plan to write an ordered repair list. Review it, apply changes in your normal workflow, then run geo_scan again; the tools never edit the site.');
237
+ return [{ type: 'text', text: lines.join('\n') }];
238
+ }
239
+
240
+ function planRender(args, value) {
241
+ const lines = [];
242
+ lines.push(`GEO fix plan: ${value.url} — ${value.total}/100 (${value.grade}), ${value.actionCount} action(s)`);
243
+ lines.push(`Markdown: ${value.planPath}`);
244
+ lines.push(`JSON: ${value.jsonPath}`);
245
+ if (value.topActions.length > 0) {
246
+ lines.push('');
247
+ value.topActions.forEach((action, index) => {
248
+ lines.push(`${index + 1}. [${action.dimensionTitle} ${action.weight}] ${action.title} — ${action.evidence}`);
249
+ lines.push(` fix: ${action.fix}`);
250
+ });
251
+ }
252
+ return [{ type: 'text', text: lines.join('\n') }];
253
+ }
254
+
255
+ export function apply(ctx, config) {
256
+ const scanDefinition = {
257
+ name: 'geo_scan',
258
+ description: [
259
+ 'Read-only, reproducible audit of a public website’s crawlability, parseability, and citation-ready structure across 45 auditable checks and five dimensions.',
260
+ 'Fetches raw HTML only. By default it honors robots.txt, refuses private/cloud-metadata destinations, and rate-limits requests; robots and private-target access are configurable in Settings → Website visibility audit.',
261
+ 'Saves the full report to .dsh-geo/ in the session workspace, diffs it against the previous scan of the same site, and returns a bounded summary with evidence and fixes.',
262
+ 'It never edits the site, measures rankings or traffic, or guarantees AI citations. Review the evidence, apply changes in your normal workflow, then re-run with the same reference time to verify repairs.',
263
+ ].join(' '),
264
+ parameters: scanParameters,
265
+ output: { schema: scanOutputSchema, render: scanRender },
266
+ timeoutMs: 180_000,
267
+ async execute(args, exec) {
268
+ if (exec.signal.aborted) throw exec.signal.reason ?? new Error('scan aborted');
269
+ const input = args !== null && typeof args === 'object' ? args : {};
270
+ const url = assertHttpUrl(input.url);
271
+ const cfg = readConfig(config);
272
+ const maxPages = assertInteger(input.max_pages, { name: 'max_pages', min: 1, max: 50 }) ?? cfg.maxPages;
273
+ const now = assertIsoTime(input.now);
274
+ if (input.allow_private === true && cfg.permitPrivateTargets !== true) {
275
+ throw new Error('allow_private requires enabling "permitPrivateTargets" in the dsh-geo settings panel');
276
+ }
277
+ if (input.save !== undefined && typeof input.save !== 'boolean') throw new Error('save must be a boolean');
278
+
279
+ const cwd = await sessionCwd(ctx, exec);
280
+ // Validate the report directory before spending a crawl on a bad path.
281
+ resolveStoreDir(cwd, cfg.reportDir);
282
+ const save = input.save !== false;
283
+
284
+ const { scan, report } = await auditSite(url, {
285
+ maxPages,
286
+ respectRobots: cfg.respectRobots,
287
+ rateLimitMs: cfg.rateLimitMs,
288
+ timeoutMs: cfg.timeoutMs,
289
+ maxBytes: cfg.maxBytes,
290
+ allowPrivate: input.allow_private === true,
291
+ signal: exec.signal,
292
+ now: now ?? undefined,
293
+ });
294
+
295
+ let persisted = null;
296
+ if (save) persisted = await persistAudit(cwd, { scan, report, reportDir: cfg.reportDir });
297
+ const diff = persisted?.diff ?? null;
298
+ const summary = summarizeReport(report);
299
+ const paths = {};
300
+ if (persisted) {
301
+ paths.latest = relative(cwd, persisted.paths.latestPath);
302
+ paths.history = relative(cwd, persisted.paths.historyPath);
303
+ paths.report = relative(cwd, persisted.paths.reportPath);
304
+ }
305
+
306
+ const value = {
307
+ url: scan.startUrl,
308
+ scannedAt: scan.scannedAt,
309
+ pages: scan.stats.pages,
310
+ total: summary.total,
311
+ grade: summary.grade,
312
+ gradeLabel: summary.gradeLabel,
313
+ counts: summary.counts,
314
+ dimensions: summary.dimensions,
315
+ topActions: summary.topActions,
316
+ platforms: summary.platforms,
317
+ blockedByRobots: Boolean(scan.blockedByRobots),
318
+ paths,
319
+ };
320
+ if (diff) {
321
+ value.comparison = {
322
+ previousScannedAt: diff.previous.scannedAt,
323
+ before: diff.total.before,
324
+ after: diff.total.after,
325
+ totalDelta: diff.total.delta,
326
+ fixed: diff.fixed.length,
327
+ regressed: diff.regressed.length,
328
+ stillFailing: diff.counts.stillFailing,
329
+ };
330
+ }
331
+ return value;
332
+ },
333
+ };
334
+
335
+ const planDefinition = {
336
+ name: 'geo_fix_plan',
337
+ description: [
338
+ 'Turn the latest geo_scan report (or a named saved report) into an actionable repair plan.',
339
+ 'Groups every failed/partial rule by dimension, orders items by weighted impact, and gives evidence, the concrete change, and the verification condition for each.',
340
+ 'Writes .dsh-geo/fix-plan.md and .dsh-geo/fix-plan.json. It never edits the site; apply the changes with your own tools, then run geo_scan again.',
341
+ ].join(' '),
342
+ parameters: planParameters,
343
+ output: { schema: planOutputSchema, render: planRender },
344
+ async execute(args, exec) {
345
+ if (exec.signal.aborted) throw exec.signal.reason ?? new Error('plan aborted');
346
+ const input = args !== null && typeof args === 'object' ? args : {};
347
+ if (input.report_path !== undefined && typeof input.report_path !== 'string') {
348
+ throw new Error('report_path must be a string');
349
+ }
350
+ const cwd = await sessionCwd(ctx, exec);
351
+ const cfg = readConfig(config);
352
+ const { payload, plan, paths } = await planFromReport(cwd, {
353
+ reportPath: input.report_path,
354
+ reportDir: cfg.reportDir,
355
+ });
356
+
357
+ const value = {
358
+ url: payload.url ?? payload.score.startUrl,
359
+ total: payload.score.total,
360
+ grade: payload.score.grade,
361
+ actionCount: plan.actions.length,
362
+ topActions: plan.actions.slice(0, 5),
363
+ planPath: relative(cwd, paths.planPath),
364
+ jsonPath: relative(cwd, paths.jsonPath),
365
+ };
366
+ if (payload.diff) {
367
+ value.comparison = {
368
+ previousScannedAt: payload.diff.previous.scannedAt,
369
+ before: payload.diff.total.before,
370
+ after: payload.diff.total.after,
371
+ totalDelta: payload.diff.total.delta,
372
+ regressed: payload.diff.counts.regressed,
373
+ };
374
+ }
375
+ return value;
376
+ },
377
+ };
378
+
379
+ ctx.tools.register(scanDefinition);
380
+ ctx.tools.register(planDefinition);
381
+ }
package/lib/audit.js ADDED
@@ -0,0 +1,62 @@
1
+ /**
2
+ * High-level audit actions shared by the DSH tools and the CLI.
3
+ *
4
+ * `auditSite` is pure orchestration (scan + score); `persistAudit` and
5
+ * `planFromReport` add the workspace-local storage and diff step.
6
+ */
7
+ import { buildFixPlan, comparableSites, diffReports } from './report.js';
8
+ import { scanSite } from './scan.js';
9
+ import { scoreScan } from './score.js';
10
+ import {
11
+ readAuditFile, readLatest, resolveStoreDir, resolveWorkspaceFile, writeAudit, writeFixPlan,
12
+ } from './store.js';
13
+
14
+ /**
15
+ * Scan and score one site.
16
+ * @param {string} url
17
+ * @param {object} options scanSite options (plus `now` used for scoring).
18
+ */
19
+ export async function auditSite(url, options = {}) {
20
+ const scan = await scanSite(url, options);
21
+ const report = scoreScan(scan, { now: options.now ?? scan.scannedAt });
22
+ return { scan, report };
23
+ }
24
+
25
+ /**
26
+ * Persist one audit, diffing it against the previous scan of the same site.
27
+ * @param {string} cwd
28
+ * @param {{scan: object, report: object, reportDir?: string}} input
29
+ */
30
+ export async function persistAudit(cwd, { scan, report, reportDir = '.dsh-geo' }) {
31
+ const storeDir = resolveStoreDir(cwd, reportDir);
32
+ let previous = null;
33
+ try {
34
+ previous = await readLatest(storeDir);
35
+ } catch {
36
+ previous = null;
37
+ }
38
+ const comparable = Boolean(previous && comparableSites(previous.url, scan.startUrl));
39
+ const diff = comparable ? diffReports(previous.score, report) : null;
40
+ const paths = await writeAudit(storeDir, { scan, report, diff, previous: comparable ? previous : null });
41
+ return { storeDir, paths, diff, previous: comparable ? previous : null };
42
+ }
43
+
44
+ /**
45
+ * Build and write a fix plan from the latest audit (or a named report).
46
+ * @param {string} cwd
47
+ * @param {{reportPath?: string, reportDir?: string}} input
48
+ */
49
+ export async function planFromReport(cwd, { reportPath, reportDir = '.dsh-geo' } = {}) {
50
+ const storeDir = resolveStoreDir(cwd, reportDir);
51
+ let payload;
52
+ if (reportPath) {
53
+ payload = await readAuditFile(resolveWorkspaceFile(cwd, reportPath));
54
+ } else {
55
+ payload = await readLatest(storeDir);
56
+ if (!payload) throw new Error('No saved audit found. Run geo_scan first, or pass report_path.');
57
+ }
58
+ if (!payload.score) throw new Error('The selected report has no score payload');
59
+ const plan = buildFixPlan(payload.score, { scan: payload.scan, diff: payload.diff ?? null });
60
+ const paths = await writeFixPlan(storeDir, plan);
61
+ return { storeDir, payload, plan, paths };
62
+ }