@verisource/cli 0.0.0-stage → 1.0.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/dist/logs.d.ts ADDED
@@ -0,0 +1,17 @@
1
+ import { type StoredHandleItem } from './store.js';
2
+ export type LogProviderId = 'vercel' | 'supabase' | 'cloudflare';
3
+ export interface CorrelatedLogEvent {
4
+ handle: string;
5
+ provider: LogProviderId;
6
+ timestamp: string;
7
+ level: 'error' | 'warn';
8
+ message: string;
9
+ routeOrScript?: string;
10
+ }
11
+ export declare function queryCorrelatedBackendLogs(params: {
12
+ providers?: LogProviderId[];
13
+ windowStartMs: number;
14
+ windowEndMs: number;
15
+ cwd?: string;
16
+ }): Promise<CorrelatedLogEvent[]>;
17
+ export declare function logEventsToStoredHandles(events: CorrelatedLogEvent[]): StoredHandleItem[];
package/dist/logs.js ADDED
@@ -0,0 +1,168 @@
1
+ import { loadLocalProviderConfig, } from './store.js';
2
+ export async function queryCorrelatedBackendLogs(params) {
3
+ const cfg = loadLocalProviderConfig(params.cwd);
4
+ const activeProviders = params.providers ?? [
5
+ 'vercel',
6
+ 'supabase',
7
+ 'cloudflare',
8
+ ];
9
+ const sinceMs = Math.max(0, params.windowStartMs - 1000);
10
+ const untilMs = params.windowEndMs + 2000;
11
+ const collected = [];
12
+ let counter = 0;
13
+ for (const provider of activeProviders) {
14
+ if (provider === 'vercel' && cfg.vercel?.token && cfg.vercel.projectId) {
15
+ try {
16
+ const qs = new URLSearchParams({
17
+ projectId: cfg.vercel.projectId,
18
+ since: String(sinceMs),
19
+ until: String(untilMs),
20
+ limit: '25',
21
+ });
22
+ if (cfg.vercel.teamId)
23
+ qs.set('teamId', cfg.vercel.teamId);
24
+ const res = await fetch(`https://api.vercel.com/v3/events?${qs.toString()}`, {
25
+ headers: { Authorization: `Bearer ${cfg.vercel.token}` },
26
+ });
27
+ if (res.ok) {
28
+ const json = (await res.json());
29
+ for (const ev of json.events ?? []) {
30
+ const status = ev.payload?.statusCode ?? 200;
31
+ const text = ev.payload?.message ?? ev.text ?? '';
32
+ if (status >= 400 || /error|exception|fail/i.test(text)) {
33
+ counter += 1;
34
+ collected.push({
35
+ handle: `g${counter}`,
36
+ provider: 'vercel',
37
+ timestamp: new Date(ev.created ?? Date.now()).toISOString(),
38
+ level: status >= 500 ? 'error' : 'warn',
39
+ message: text.slice(0, 260) || `HTTP ${status} runtime event`,
40
+ routeOrScript: ev.payload?.path,
41
+ });
42
+ }
43
+ }
44
+ }
45
+ }
46
+ catch {
47
+ // Non-fatal provider timeout
48
+ }
49
+ }
50
+ if (provider === 'supabase' &&
51
+ cfg.supabase?.accessToken &&
52
+ cfg.supabase.projectRef) {
53
+ try {
54
+ const qs = new URLSearchParams({
55
+ iso_timestamp_start: new Date(sinceMs).toISOString(),
56
+ iso_timestamp_end: new Date(untilMs).toISOString(),
57
+ });
58
+ const res = await fetch(`https://api.supabase.com/v1/projects/${encodeURIComponent(cfg.supabase.projectRef)}/analytics/endpoints/logs.all?${qs.toString()}`, {
59
+ headers: {
60
+ Authorization: `Bearer ${cfg.supabase.accessToken}`,
61
+ },
62
+ });
63
+ if (res.ok) {
64
+ const json = (await res.json());
65
+ for (const row of json.result ?? []) {
66
+ const msg = row.event_message ?? '';
67
+ if (/error|fatal|panic|violates|denied|422|500/i.test(msg)) {
68
+ counter += 1;
69
+ collected.push({
70
+ handle: `g${counter}`,
71
+ provider: 'supabase',
72
+ timestamp: row.timestamp
73
+ ? new Date(Math.round(row.timestamp / 1000)).toISOString()
74
+ : new Date().toISOString(),
75
+ level: 'error',
76
+ message: msg.slice(0, 260),
77
+ });
78
+ }
79
+ }
80
+ }
81
+ }
82
+ catch {
83
+ // Non-fatal provider timeout
84
+ }
85
+ }
86
+ if (provider === 'cloudflare' &&
87
+ cfg.cloudflare?.apiToken &&
88
+ cfg.cloudflare.accountId) {
89
+ try {
90
+ const query = `
91
+ query WorkerErrors($accountTag: string!, $since: Time!, $until: Time!) {
92
+ viewer {
93
+ accounts(filter: { accountTag: $accountTag }) {
94
+ workersInvocationsAdaptive(
95
+ limit: 20
96
+ filter: { datetime_geq: $since, datetime_leq: $until, status_neq: "ok" }
97
+ ) {
98
+ dimensions {
99
+ scriptName
100
+ status
101
+ datetime
102
+ }
103
+ }
104
+ }
105
+ }
106
+ }
107
+ `;
108
+ const res = await fetch('https://api.cloudflare.com/client/v4/graphql', {
109
+ method: 'POST',
110
+ headers: {
111
+ Authorization: `Bearer ${cfg.cloudflare.apiToken}`,
112
+ 'Content-Type': 'application/json',
113
+ },
114
+ body: JSON.stringify({
115
+ query,
116
+ variables: {
117
+ accountTag: cfg.cloudflare.accountId,
118
+ since: new Date(sinceMs).toISOString(),
119
+ until: new Date(untilMs).toISOString(),
120
+ },
121
+ }),
122
+ });
123
+ if (res.ok) {
124
+ const json = (await res.json());
125
+ const invocations = json.data?.viewer?.accounts?.[0]?.workersInvocationsAdaptive ?? [];
126
+ for (const inv of invocations) {
127
+ const dim = inv.dimensions;
128
+ if (!dim)
129
+ continue;
130
+ if (cfg.cloudflare.scriptName &&
131
+ dim.scriptName !== cfg.cloudflare.scriptName) {
132
+ continue;
133
+ }
134
+ counter += 1;
135
+ collected.push({
136
+ handle: `g${counter}`,
137
+ provider: 'cloudflare',
138
+ timestamp: dim.datetime ?? new Date().toISOString(),
139
+ level: 'error',
140
+ message: `Worker ${dim.scriptName ?? 'script'} exited with status "${dim.status ?? 'exception'}"`,
141
+ routeOrScript: dim.scriptName,
142
+ });
143
+ }
144
+ }
145
+ }
146
+ catch {
147
+ // Non-fatal provider timeout
148
+ }
149
+ }
150
+ }
151
+ return collected;
152
+ }
153
+ export function logEventsToStoredHandles(events) {
154
+ return events.map((ev) => ({
155
+ handle: ev.handle,
156
+ kind: 'backend_log',
157
+ severity: ev.level === 'error' ? 'critical' : 'warn',
158
+ summary: `[${ev.provider}] ${ev.message}`,
159
+ url: ev.routeOrScript,
160
+ detail: {
161
+ provider: ev.provider,
162
+ timestamp: ev.timestamp,
163
+ level: ev.level,
164
+ routeOrScript: ev.routeOrScript ?? null,
165
+ },
166
+ fixHint: 'Inspect server handler stacktrace in the correlated run timestamp window.',
167
+ }));
168
+ }
@@ -0,0 +1,36 @@
1
+ export interface MappedRouteEntry {
2
+ route: string;
3
+ kind: 'page' | 'api' | 'live_url';
4
+ sourceFile?: string;
5
+ httpMethods?: string[];
6
+ emitsJsonLd: boolean;
7
+ jsonLdTypes: string[];
8
+ clientApiCalls: string[];
9
+ httpStatus?: number | null;
10
+ visibleWordCount?: number;
11
+ }
12
+ export interface SiteMapReport {
13
+ mode: 'static_codebase' | 'live_url';
14
+ target: string;
15
+ mappedAt: string;
16
+ totalRoutes: number;
17
+ pageRoutesCount: number;
18
+ apiRoutesCount: number;
19
+ jsonLdRoutesCount: number;
20
+ routes: MappedRouteEntry[];
21
+ addedSinceLastMap?: string[];
22
+ removedSinceLastMap?: string[];
23
+ }
24
+ export declare function mapStaticCodebase(params: {
25
+ targetDir: string;
26
+ filterText?: string;
27
+ diff?: boolean;
28
+ cwd?: string;
29
+ }): SiteMapReport;
30
+ export declare function mapLiveDomain(params: {
31
+ url: string;
32
+ filterText?: string;
33
+ diff?: boolean;
34
+ skipNetwork?: boolean;
35
+ cwd?: string;
36
+ }): Promise<SiteMapReport>;
package/dist/mapper.js ADDED
@@ -0,0 +1,204 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { crawlDomainSiteHealth } from '@verisource/core-geo';
4
+ import { ensureVerisourceWorkspaceDir } from './store.js';
5
+ const IGNORED_DIRS = new Set([
6
+ 'node_modules',
7
+ '.next',
8
+ 'dist',
9
+ 'build',
10
+ '.output',
11
+ '.wxt',
12
+ '.git',
13
+ '.verisource',
14
+ 'coverage',
15
+ ]);
16
+ function walkSourceFiles(rootDir, acc = []) {
17
+ if (!fs.existsSync(rootDir))
18
+ return acc;
19
+ const entries = fs.readdirSync(rootDir, { withFileTypes: true });
20
+ for (const entry of entries) {
21
+ if (IGNORED_DIRS.has(entry.name))
22
+ continue;
23
+ const full = path.join(rootDir, entry.name);
24
+ if (entry.isDirectory()) {
25
+ walkSourceFiles(full, acc);
26
+ }
27
+ else if (/\.(?:tsx?|jsx?)$/i.test(entry.name)) {
28
+ acc.push(full);
29
+ }
30
+ }
31
+ return acc;
32
+ }
33
+ function normalizeNextAppRoute(appRoot, filePath) {
34
+ const rel = path
35
+ .relative(appRoot, path.dirname(filePath))
36
+ .split(path.sep)
37
+ .filter((seg) => seg && !(seg.startsWith('(') && seg.endsWith(')')));
38
+ return `/${rel.join('/')}`.replace(/\/+/g, '/') || '/';
39
+ }
40
+ function extractStaticSignals(sourceText) {
41
+ const emitsJsonLd = /application\/ld\+json/i.test(sourceText);
42
+ const jsonLdTypes = new Set();
43
+ const typeRegex = /['"]@type['"]\s*:\s*['"]([A-Za-z0-9_]+)['"]/g;
44
+ let tm;
45
+ while ((tm = typeRegex.exec(sourceText)) !== null) {
46
+ if (tm[1])
47
+ jsonLdTypes.add(tm[1]);
48
+ }
49
+ const clientApiCalls = new Set();
50
+ const fetchRegex = /\bfetch\(\s*[`'"]((?:\/api\/|https?:\/\/)[^`'"${]+)[`'"]/g;
51
+ let fm;
52
+ while ((fm = fetchRegex.exec(sourceText)) !== null) {
53
+ if (fm[1])
54
+ clientApiCalls.add(fm[1]);
55
+ }
56
+ const httpMethods = new Set();
57
+ const methodRegex = /export\s+(?:async\s+)?function\s+(GET|POST|PUT|PATCH|DELETE|OPTIONS|HEAD)\b/g;
58
+ let mm;
59
+ while ((mm = methodRegex.exec(sourceText)) !== null) {
60
+ if (mm[1])
61
+ httpMethods.add(mm[1]);
62
+ }
63
+ return {
64
+ emitsJsonLd,
65
+ jsonLdTypes: Array.from(jsonLdTypes),
66
+ clientApiCalls: Array.from(clientApiCalls),
67
+ httpMethods: Array.from(httpMethods),
68
+ };
69
+ }
70
+ function applyMapDiff(report, enableDiff, cwd) {
71
+ const dir = ensureVerisourceWorkspaceDir(cwd);
72
+ const mapPath = path.join(dir, 'last-map.json');
73
+ if (enableDiff && fs.existsSync(mapPath)) {
74
+ try {
75
+ const prev = JSON.parse(fs.readFileSync(mapPath, 'utf8'));
76
+ const prevSet = new Set(prev.routes.map((r) => r.route));
77
+ const currSet = new Set(report.routes.map((r) => r.route));
78
+ report.addedSinceLastMap = report.routes
79
+ .map((r) => r.route)
80
+ .filter((r) => !prevSet.has(r));
81
+ report.removedSinceLastMap = prev.routes
82
+ .map((r) => r.route)
83
+ .filter((r) => !currSet.has(r));
84
+ }
85
+ catch {
86
+ // Ignore corrupt prior map
87
+ }
88
+ }
89
+ fs.writeFileSync(mapPath, JSON.stringify(report, null, 2), 'utf8');
90
+ return report;
91
+ }
92
+ export function mapStaticCodebase(params) {
93
+ const resolvedRoot = path.resolve(params.targetDir);
94
+ const candidates = [
95
+ path.join(resolvedRoot, 'src', 'app'),
96
+ path.join(resolvedRoot, 'app'),
97
+ path.join(resolvedRoot, 'apps', 'web', 'src', 'app'),
98
+ ];
99
+ const appRoot = candidates.find((c) => fs.existsSync(c));
100
+ const routes = [];
101
+ if (appRoot) {
102
+ const files = walkSourceFiles(appRoot);
103
+ const layoutPath = files.find((f) => path.basename(f).startsWith('layout.'));
104
+ const rootLayoutSignals = layoutPath
105
+ ? extractStaticSignals(fs.readFileSync(layoutPath, 'utf8'))
106
+ : null;
107
+ for (const file of files) {
108
+ const base = path.basename(file);
109
+ const isPage = /^page\.(?:tsx?|jsx?)$/i.test(base);
110
+ const isRoute = /^route\.(?:tsx?|jsx?)$/i.test(base);
111
+ if (!isPage && !isRoute)
112
+ continue;
113
+ const route = normalizeNextAppRoute(appRoot, file);
114
+ const text = fs.readFileSync(file, 'utf8');
115
+ const sig = extractStaticSignals(text);
116
+ const mergedTypes = new Set(sig.jsonLdTypes);
117
+ let emitsJsonLd = sig.emitsJsonLd;
118
+ if (isPage && route === '/' && rootLayoutSignals?.emitsJsonLd) {
119
+ emitsJsonLd = true;
120
+ for (const t of rootLayoutSignals.jsonLdTypes)
121
+ mergedTypes.add(t);
122
+ }
123
+ routes.push({
124
+ route,
125
+ kind: isPage ? 'page' : 'api',
126
+ sourceFile: path.relative(resolvedRoot, file).replace(/\\/g, '/'),
127
+ ...(isRoute ? { httpMethods: sig.httpMethods } : {}),
128
+ emitsJsonLd,
129
+ jsonLdTypes: Array.from(mergedTypes),
130
+ clientApiCalls: sig.clientApiCalls,
131
+ });
132
+ }
133
+ }
134
+ else {
135
+ // React Router fallback (`path="/..."`)
136
+ const files = walkSourceFiles(resolvedRoot);
137
+ for (const file of files) {
138
+ const text = fs.readFileSync(file, 'utf8');
139
+ const sig = extractStaticSignals(text);
140
+ const rrRegex = /\bpath\s*=\s*['"]([^'"]+)['"]/g;
141
+ let rm;
142
+ while ((rm = rrRegex.exec(text)) !== null) {
143
+ if (!rm[1])
144
+ continue;
145
+ routes.push({
146
+ route: rm[1].startsWith('/') ? rm[1] : `/${rm[1]}`,
147
+ kind: 'page',
148
+ sourceFile: path.relative(resolvedRoot, file).replace(/\\/g, '/'),
149
+ emitsJsonLd: sig.emitsJsonLd,
150
+ jsonLdTypes: sig.jsonLdTypes,
151
+ clientApiCalls: sig.clientApiCalls,
152
+ });
153
+ }
154
+ }
155
+ }
156
+ routes.sort((a, b) => a.route.localeCompare(b.route));
157
+ const filtered = params.filterText
158
+ ? routes.filter((r) => JSON.stringify(r)
159
+ .toLowerCase()
160
+ .includes(params.filterText.toLowerCase()))
161
+ : routes;
162
+ const report = {
163
+ mode: 'static_codebase',
164
+ target: resolvedRoot,
165
+ mappedAt: new Date().toISOString(),
166
+ totalRoutes: filtered.length,
167
+ pageRoutesCount: filtered.filter((r) => r.kind === 'page').length,
168
+ apiRoutesCount: filtered.filter((r) => r.kind === 'api').length,
169
+ jsonLdRoutesCount: filtered.filter((r) => r.emitsJsonLd).length,
170
+ routes: filtered,
171
+ };
172
+ return applyMapDiff(report, Boolean(params.diff), params.cwd ?? process.cwd());
173
+ }
174
+ export async function mapLiveDomain(params) {
175
+ const crawl = await crawlDomainSiteHealth({
176
+ domainInput: params.url,
177
+ mode: 'workspace',
178
+ skipNetwork: params.skipNetwork,
179
+ });
180
+ let routes = crawl.pages.map((pg) => ({
181
+ route: pg.path,
182
+ kind: 'live_url',
183
+ emitsJsonLd: pg.jsonLdTypes.length > 0,
184
+ jsonLdTypes: pg.jsonLdTypes,
185
+ clientApiCalls: [],
186
+ httpStatus: pg.httpStatus,
187
+ visibleWordCount: pg.visibleWordCount,
188
+ }));
189
+ if (params.filterText) {
190
+ const needle = params.filterText.toLowerCase();
191
+ routes = routes.filter((r) => JSON.stringify(r).toLowerCase().includes(needle));
192
+ }
193
+ const report = {
194
+ mode: 'live_url',
195
+ target: crawl.origin,
196
+ mappedAt: crawl.scannedAt,
197
+ totalRoutes: routes.length,
198
+ pageRoutesCount: routes.length,
199
+ apiRoutesCount: 0,
200
+ jsonLdRoutesCount: routes.filter((r) => r.emitsJsonLd).length,
201
+ routes,
202
+ };
203
+ return applyMapDiff(report, Boolean(params.diff), params.cwd ?? process.cwd());
204
+ }
@@ -0,0 +1,5 @@
1
+ export type AgentSkillTarget = 'claude' | 'cursor' | 'codex' | 'antigravity' | 'all';
2
+ export declare function installAgentSkills(params: {
3
+ target: AgentSkillTarget;
4
+ cwd?: string;
5
+ }): string[];
package/dist/skills.js ADDED
@@ -0,0 +1,45 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ const COMPACT_SKILL_BODY = `---
4
+ name: verisource-verify
5
+ description: Verify live AI search schema (JSON-LD, /agents.md, /llms.txt), broken links, browser flows, and backend error logs before marking web work complete.
6
+ ---
7
+
8
+ Before declaring UI, routing, pricing, or SEO/GEO changes complete:
9
+ 1. Run \`npx @verisource/cli verify <url>\` (or \`npx @verisource/cli run\` for saved \`.verisource/workflows/*.json\`).
10
+ 2. If any handle fails (\`[h#]\`, \`[b#]\`, \`[l#]\`, \`[n#]\`, \`[g#]\`), inspect with \`npx @verisource/cli show <handle>\`, fix the root cause, and re-verify until \`PASS (exit 0)\`.
11
+ `;
12
+ export function installAgentSkills(params) {
13
+ const root = path.resolve(params.cwd ?? process.cwd());
14
+ const targets = params.target === 'all'
15
+ ? ['claude', 'cursor', 'codex', 'antigravity']
16
+ : [params.target];
17
+ const written = [];
18
+ for (const t of targets) {
19
+ if (t === 'claude') {
20
+ const p = path.join(root, '.claude', 'skills', 'verisource-verify', 'SKILL.md');
21
+ fs.mkdirSync(path.dirname(p), { recursive: true });
22
+ fs.writeFileSync(p, COMPACT_SKILL_BODY, 'utf8');
23
+ written.push(path.relative(root, p).replace(/\\/g, '/'));
24
+ }
25
+ else if (t === 'cursor') {
26
+ const p = path.join(root, '.cursor', 'rules', 'verisource-verify.mdc');
27
+ fs.mkdirSync(path.dirname(p), { recursive: true });
28
+ fs.writeFileSync(p, COMPACT_SKILL_BODY, 'utf8');
29
+ written.push(path.relative(root, p).replace(/\\/g, '/'));
30
+ }
31
+ else if (t === 'codex') {
32
+ const p = path.join(root, '.codex', 'skills', 'verisource-verify', 'SKILL.md');
33
+ fs.mkdirSync(path.dirname(p), { recursive: true });
34
+ fs.writeFileSync(p, COMPACT_SKILL_BODY, 'utf8');
35
+ written.push(path.relative(root, p).replace(/\\/g, '/'));
36
+ }
37
+ else if (t === 'antigravity') {
38
+ const p = path.join(root, '.agents', 'skills', 'verisource-verify', 'SKILL.md');
39
+ fs.mkdirSync(path.dirname(p), { recursive: true });
40
+ fs.writeFileSync(p, COMPACT_SKILL_BODY, 'utf8');
41
+ written.push(path.relative(root, p).replace(/\\/g, '/'));
42
+ }
43
+ }
44
+ return written;
45
+ }
@@ -0,0 +1,56 @@
1
+ export interface StoredHandleItem {
2
+ handle: string;
3
+ kind: 'hallucination' | 'bot_waf' | 'page_error' | 'broken_link' | 'dead_anchor' | 'broken_asset' | 'ai_readability' | 'network' | 'backend_log' | 'element' | 'xray_gap' | 'scorecard_gap' | 'matchup_gap';
4
+ severity: 'critical' | 'warn' | 'info';
5
+ summary: string;
6
+ url?: string;
7
+ httpStatus?: number | null;
8
+ detail?: Record<string, unknown>;
9
+ fixHint?: string;
10
+ }
11
+ export interface LastRunLedger {
12
+ runId: string;
13
+ command: string;
14
+ target: string;
15
+ startedAt: string;
16
+ finishedAt: string;
17
+ status: 'PASS' | 'WARN' | 'FAIL';
18
+ handles: StoredHandleItem[];
19
+ }
20
+ export interface LocalProviderConfig {
21
+ verisourceCloud?: {
22
+ apiKey: string;
23
+ apiOrigin?: string;
24
+ };
25
+ vercel?: {
26
+ token: string;
27
+ projectId?: string;
28
+ teamId?: string;
29
+ };
30
+ supabase?: {
31
+ accessToken: string;
32
+ projectRef: string;
33
+ };
34
+ cloudflare?: {
35
+ apiToken: string;
36
+ accountId: string;
37
+ scriptName?: string;
38
+ };
39
+ }
40
+ export interface ChecksPolicyFile {
41
+ domain: string;
42
+ minVisibilityScore: number;
43
+ requireLlmsTxt: boolean;
44
+ requireAgentsMd: boolean;
45
+ minJsonLdNodes: number;
46
+ allowDeadAnchors: boolean;
47
+ allowBrokenLinks: boolean;
48
+ }
49
+ export declare function ensureVerisourceWorkspaceDir(cwd?: string): string;
50
+ export declare function saveLastRunLedger(ledger: LastRunLedger, cwd?: string): void;
51
+ export declare function loadLastRunLedger(cwd?: string): LastRunLedger | null;
52
+ export declare function findStoredHandle(handleId: string, cwd?: string): StoredHandleItem | null;
53
+ export declare function queryStoredHandles(queryText: string, cwd?: string): StoredHandleItem[];
54
+ export declare function loadLocalProviderConfig(cwd?: string): LocalProviderConfig;
55
+ export declare function saveLocalProviderConfig(config: LocalProviderConfig, cwd?: string): string;
56
+ export declare function loadOrInitChecksPolicy(domain: string, initIfMissing: boolean, cwd?: string): ChecksPolicyFile;
package/dist/store.js ADDED
@@ -0,0 +1,133 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ export function ensureVerisourceWorkspaceDir(cwd = process.cwd()) {
4
+ const dir = path.resolve(cwd, '.verisource');
5
+ fs.mkdirSync(dir, { recursive: true });
6
+ fs.mkdirSync(path.join(dir, 'workflows'), { recursive: true });
7
+ fs.mkdirSync(path.join(dir, 'artifacts'), { recursive: true });
8
+ // Protect local secrets & ephemeral run logs from accidental git commits
9
+ const localGitignore = path.join(dir, '.gitignore');
10
+ if (!fs.existsSync(localGitignore)) {
11
+ fs.writeFileSync(localGitignore, [
12
+ '# Local-only Verisource secrets, cookies, and ephemeral run ledgers',
13
+ 'config.json',
14
+ 'last-run.json',
15
+ 'last-map.json',
16
+ 'browser-session.json',
17
+ 'artifacts/',
18
+ '',
19
+ ].join('\n'), 'utf8');
20
+ }
21
+ return dir;
22
+ }
23
+ export function saveLastRunLedger(ledger, cwd = process.cwd()) {
24
+ const dir = ensureVerisourceWorkspaceDir(cwd);
25
+ fs.writeFileSync(path.join(dir, 'last-run.json'), JSON.stringify(ledger, null, 2), 'utf8');
26
+ }
27
+ export function loadLastRunLedger(cwd = process.cwd()) {
28
+ const filePath = path.resolve(cwd, '.verisource', 'last-run.json');
29
+ if (!fs.existsSync(filePath))
30
+ return null;
31
+ try {
32
+ return JSON.parse(fs.readFileSync(filePath, 'utf8'));
33
+ }
34
+ catch {
35
+ return null;
36
+ }
37
+ }
38
+ export function findStoredHandle(handleId, cwd = process.cwd()) {
39
+ const ledger = loadLastRunLedger(cwd);
40
+ if (!ledger)
41
+ return null;
42
+ const clean = handleId.replace(/^\[|\]$/g, '').trim().toLowerCase();
43
+ return (ledger.handles.find((h) => h.handle.toLowerCase() === clean) ?? null);
44
+ }
45
+ export function queryStoredHandles(queryText, cwd = process.cwd()) {
46
+ const ledger = loadLastRunLedger(cwd);
47
+ if (!ledger)
48
+ return [];
49
+ const needle = queryText.trim().toLowerCase();
50
+ if (!needle)
51
+ return ledger.handles;
52
+ return ledger.handles.filter((item) => {
53
+ const haystack = JSON.stringify(item).toLowerCase();
54
+ return haystack.includes(needle);
55
+ });
56
+ }
57
+ export function loadLocalProviderConfig(cwd = process.cwd()) {
58
+ const filePath = path.resolve(cwd, '.verisource', 'config.json');
59
+ let diskConfig = {};
60
+ if (fs.existsSync(filePath)) {
61
+ try {
62
+ diskConfig = JSON.parse(fs.readFileSync(filePath, 'utf8'));
63
+ }
64
+ catch {
65
+ diskConfig = {};
66
+ }
67
+ }
68
+ return {
69
+ verisourceCloud: diskConfig.verisourceCloud ??
70
+ (process.env.VERISOURCE_API_KEY
71
+ ? {
72
+ apiKey: process.env.VERISOURCE_API_KEY,
73
+ apiOrigin: process.env.VERISOURCE_API_ORIGIN,
74
+ }
75
+ : undefined),
76
+ vercel: diskConfig.vercel ?? (process.env.VERCEL_TOKEN
77
+ ? {
78
+ token: process.env.VERCEL_TOKEN,
79
+ projectId: process.env.VERCEL_PROJECT_ID,
80
+ teamId: process.env.VERCEL_TEAM_ID,
81
+ }
82
+ : undefined),
83
+ supabase: diskConfig.supabase ?? (process.env.SUPABASE_ACCESS_TOKEN &&
84
+ process.env.SUPABASE_PROJECT_REF
85
+ ? {
86
+ accessToken: process.env.SUPABASE_ACCESS_TOKEN,
87
+ projectRef: process.env.SUPABASE_PROJECT_REF,
88
+ }
89
+ : undefined),
90
+ cloudflare: diskConfig.cloudflare ?? (process.env.CLOUDFLARE_API_TOKEN &&
91
+ process.env.CLOUDFLARE_ACCOUNT_ID
92
+ ? {
93
+ apiToken: process.env.CLOUDFLARE_API_TOKEN,
94
+ accountId: process.env.CLOUDFLARE_ACCOUNT_ID,
95
+ scriptName: process.env.CLOUDFLARE_SCRIPT_NAME,
96
+ }
97
+ : undefined),
98
+ };
99
+ }
100
+ export function saveLocalProviderConfig(config, cwd = process.cwd()) {
101
+ const dir = ensureVerisourceWorkspaceDir(cwd);
102
+ const filePath = path.join(dir, 'config.json');
103
+ fs.writeFileSync(filePath, JSON.stringify(config, null, 2), {
104
+ encoding: 'utf8',
105
+ mode: 0o600,
106
+ });
107
+ return filePath;
108
+ }
109
+ export function loadOrInitChecksPolicy(domain, initIfMissing, cwd = process.cwd()) {
110
+ const dir = ensureVerisourceWorkspaceDir(cwd);
111
+ const filePath = path.join(dir, 'checks.json');
112
+ if (fs.existsSync(filePath)) {
113
+ try {
114
+ return JSON.parse(fs.readFileSync(filePath, 'utf8'));
115
+ }
116
+ catch {
117
+ // Fall through to default
118
+ }
119
+ }
120
+ const defaults = {
121
+ domain,
122
+ minVisibilityScore: 55,
123
+ requireLlmsTxt: true,
124
+ requireAgentsMd: true,
125
+ minJsonLdNodes: 2,
126
+ allowDeadAnchors: false,
127
+ allowBrokenLinks: false,
128
+ };
129
+ if (initIfMissing) {
130
+ fs.writeFileSync(filePath, JSON.stringify(defaults, null, 2), 'utf8');
131
+ }
132
+ return defaults;
133
+ }