@goosetools/goose-tools 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/README.md +98 -2
  2. package/bin/goose-tools.js +61 -0
  3. package/lib/check/src/agent.js +90 -0
  4. package/lib/check/src/analyze.js +311 -0
  5. package/lib/check/src/client.js +136 -0
  6. package/lib/check/src/copy.js +355 -0
  7. package/lib/check/src/fixes.js +153 -0
  8. package/lib/check/src/frame.js +92 -0
  9. package/lib/check/src/guard.js +441 -0
  10. package/lib/check/src/index.js +18 -0
  11. package/lib/check/src/mcp-http.js +169 -0
  12. package/lib/check/src/mcp.js +153 -0
  13. package/lib/check/src/scan.js +55 -0
  14. package/lib/check/src/stack.js +61 -0
  15. package/lib/check/src/tlds.js +3 -0
  16. package/lib/check/src/view.js +130 -0
  17. package/lib/check/src/worker.js +257 -0
  18. package/lib/engine/src/bots.js +146 -0
  19. package/lib/engine/src/directives.js +131 -0
  20. package/lib/engine/src/exposure.js +70 -0
  21. package/lib/engine/src/frontend.js +157 -0
  22. package/lib/engine/src/headers.js +76 -0
  23. package/lib/engine/src/hidden-text.js +425 -0
  24. package/lib/engine/src/html.js +794 -0
  25. package/lib/engine/src/index.js +20 -0
  26. package/lib/engine/src/php.js +316 -0
  27. package/lib/engine/src/policies.js +234 -0
  28. package/lib/engine/src/reach.js +199 -0
  29. package/lib/engine/src/robots.js +275 -0
  30. package/lib/engine/src/secrets.js +142 -0
  31. package/lib/engine/src/signals.js +144 -0
  32. package/lib/rules/data/bots.json.js +1 -0
  33. package/lib/rules/data/exposure.json.js +1 -0
  34. package/lib/rules/data/frontend.json.js +1 -0
  35. package/lib/rules/data/headers.json.js +1 -0
  36. package/lib/rules/data/secrets.json.js +1 -0
  37. package/lib/ui/LICENSE-Inter.txt +93 -0
  38. package/lib/ui/assets.js +5 -0
  39. package/package.json +37 -4
  40. package/src/local.js +61 -0
  41. package/src/mcp.js +61 -0
  42. package/src/setup.js +395 -0
  43. package/src/site/auth.js +287 -0
  44. package/src/site/beacon.js +462 -0
  45. package/src/site/collect.js +484 -0
  46. package/src/site/handler.js +405 -0
  47. package/src/site/index.js +88 -0
  48. package/src/site/limits.js +48 -0
  49. package/src/site/pages.js +75 -0
  50. package/src/site/qr.js +318 -0
  51. package/src/site/reports.js +1117 -0
  52. package/src/site/source.js +68 -0
  53. package/src/site/store-pg.js +225 -0
  54. package/src/site/store.js +249 -0
package/package.json CHANGED
@@ -1,6 +1,39 @@
1
1
  {
2
2
  "name": "@goosetools/goose-tools",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Check your site for search, AI answers and security. From the terminal or from your AI agent over MCP.",
5
+ "keywords": [
6
+ "seo",
7
+ "aeo",
8
+ "ai-crawlers",
9
+ "security-headers",
10
+ "mcp",
11
+ "claude-code",
12
+ "cursor"
13
+ ],
14
+ "homepage": "https://goosetools.app",
15
+ "license": "GPL-2.0-or-later",
16
+ "type": "module",
17
+ "bin": {
18
+ "goose-tools": "bin/goose-tools.js"
19
+ },
20
+ "files": [
21
+ "bin",
22
+ "src",
23
+ "lib",
24
+ "README.md"
25
+ ],
26
+ "engines": {
27
+ "node": ">=22.13"
28
+ },
29
+ "scripts": {
30
+ "sync": "node scripts/sync.mjs",
31
+ "prepack": "node scripts/sync.mjs",
32
+ "test": "node scripts/sync.mjs && node --test test/",
33
+ "test:pg": "node --test --test-concurrency=1 test/"
34
+ },
35
+ "exports": {
36
+ "./site": "./src/site/index.js",
37
+ "./package.json": "./package.json"
38
+ }
39
+ }
package/src/local.js ADDED
@@ -0,0 +1,61 @@
1
+ // The free check, run on this machine: the same code as goosetools.app/check (lib/, from scripts/sync.mjs). The
2
+ // check page's client calls the Worker's handler in-process instead of over the network, so every guard rule
3
+ // still applies: public http and https addresses only, redirects checked hop by hop, 2 MB per file, 10 seconds,
4
+ // at most 45 requests. Requests name the check in their User-Agent (GooseToolsCheck/1.0) and never pose as a
5
+ // crawler. Nothing is sent to goosetools.app.
6
+ import http from 'node:http';
7
+ import https from 'node:https';
8
+ import dns from 'node:dns';
9
+ import { Readable } from 'node:stream';
10
+ import { runCheck } from '../lib/check/src/client.js';
11
+ import { handle } from '../lib/check/src/worker.js';
12
+ import { isBlockedIPv4, isBlockedIPv6 } from '../lib/check/src/guard.js';
13
+
14
+ /**
15
+ * A DNS lookup that refuses any name resolving to a private, local or reserved address. It runs when each
16
+ * connection opens, so a name that changes its answer between checks (DNS rebinding) is caught too.
17
+ * @type {import('node:net').LookupFunction}
18
+ */
19
+ export function safeLookup(hostname, options, callback) {
20
+ dns.lookup(hostname, options, (err, address, family) => {
21
+ if (err) return callback(err, address, family);
22
+ const list = Array.isArray(address) ? address : [{ address, family }];
23
+ const bad = list.find((a) => (a.family === 6 ? isBlockedIPv6(a.address) : isBlockedIPv4(a.address)));
24
+ if (bad) return callback(Object.assign(new Error('The address points to a private network.'), { code: 'EPRIVATE' }), address, family);
25
+ return callback(null, address, family);
26
+ });
27
+ }
28
+
29
+ /**
30
+ * fetch() for the guard, over node:http and node:https with safeLookup. GET only, redirects not followed (the guard
31
+ * follows them), no compression asked for. Returns a web Response.
32
+ * @param {string} url
33
+ * @param {{method?: string, headers?: Record<string, string>, signal?: AbortSignal}} [init]
34
+ * @returns {Promise<Response>}
35
+ */
36
+ export function nodeFetch(url, init = {}) {
37
+ return new Promise((resolve, reject) => {
38
+ const u = new URL(url);
39
+ const lib = u.protocol === 'https:' ? https : u.protocol === 'http:' ? http : null;
40
+ if (!lib) return reject(new Error('Only http and https.'));
41
+ const req = lib.request(u, { method: init.method ?? 'GET', headers: init.headers ?? {}, lookup: safeLookup, signal: init.signal }, (res) => {
42
+ const headers = new Headers();
43
+ for (let i = 0; i < res.rawHeaders.length; i += 2) headers.append(res.rawHeaders[i], res.rawHeaders[i + 1]);
44
+ const empty = res.statusCode === 204 || res.statusCode === 304 || init.method === 'HEAD';
45
+ resolve(new Response(empty ? null : /** @type {ReadableStream} */ (Readable.toWeb(res)), { status: res.statusCode, headers }));
46
+ });
47
+ req.on('error', reject);
48
+ req.end();
49
+ });
50
+ }
51
+
52
+ /**
53
+ * Run the free check on one page from this machine.
54
+ * @param {string} input What the person or agent typed, for example "yourproduct.dev".
55
+ * @param {{fetchImpl?: typeof fetch, now?: () => number}} [opts] fetchImpl replaces the network (tests).
56
+ */
57
+ export function checkPage(input, opts = {}) {
58
+ const site = opts.fetchImpl ?? nodeFetch;
59
+ const endpoint = async (path, init) => handle(new Request('http://local' + path, init), {}, {}, { fetchImpl: site, cache: null });
60
+ return runCheck(input, { fetchImpl: endpoint, endpoint: '/check/fetch', now: opts.now });
61
+ }
package/src/mcp.js ADDED
@@ -0,0 +1,61 @@
1
+ // `npx @goosetools/goose-tools mcp`: the check's MCP server (check/src/mcp.js) over stdio, running the check from this machine.
2
+ // Newline-delimited JSON-RPC 2.0 on stdin and stdout, logs on stderr only. No dependencies.
3
+ import readline from 'node:readline';
4
+ import { checkPage } from './local.js';
5
+ import { answer, fail } from '../lib/check/src/mcp.js';
6
+
7
+ export { TOOL, MODERN, LEGACY } from '../lib/check/src/mcp.js';
8
+
9
+ /**
10
+ * One stdio session: the legacy version negotiated by initialize, and cancelled requests.
11
+ * @param {{version: string, send: (msg: object) => void, check?: (url: string) => Promise<any>, log?: (s: string) => void}} o
12
+ */
13
+ export function createServer({ version, send, check = checkPage, log = () => {} }) {
14
+ /** @type {string | null} */
15
+ let legacy = null;
16
+ const cancelled = new Set();
17
+ const opts = () => ({ version, check, legacy, cancelled: (id) => cancelled.has(id) });
18
+
19
+ return {
20
+ /** @param {string} line One line from stdin. */
21
+ async line(line) {
22
+ if (!line.trim()) return;
23
+ let msg;
24
+ try {
25
+ msg = JSON.parse(line);
26
+ } catch {
27
+ send(fail(null, -32700, 'Parse error'));
28
+ return;
29
+ }
30
+ if (msg && msg.method === 'notifications/cancelled' && msg.id === undefined && msg.params) cancelled.add(msg.params.requestId);
31
+ try {
32
+ const res = await answer(msg, opts());
33
+ if (msg && msg.method === 'initialize' && res && res.result) legacy = res.result.protocolVersion;
34
+ if (res) send(res);
35
+ } catch (e) {
36
+ log(`goose-tools mcp: ${e && e.stack ? e.stack : e}`);
37
+ if (msg && msg.id !== undefined) send(fail(msg.id, -32603, 'Internal error'));
38
+ }
39
+ },
40
+ };
41
+ }
42
+
43
+ /** Serve on this process's stdin and stdout until stdin closes. */
44
+ export function serveStdio(version) {
45
+ const server = createServer({
46
+ version,
47
+ send: (m) => process.stdout.write(JSON.stringify(m) + '\n'),
48
+ log: (s) => process.stderr.write(s + '\n'),
49
+ });
50
+ const pending = new Set();
51
+ const rl = readline.createInterface({ input: process.stdin, crlfDelay: Infinity });
52
+ rl.on('line', (l) => {
53
+ const p = server.line(l);
54
+ pending.add(p);
55
+ p.finally(() => pending.delete(p));
56
+ });
57
+ rl.on('close', async () => {
58
+ await Promise.allSettled([...pending]);
59
+ process.exit(0);
60
+ });
61
+ }
package/src/setup.js ADDED
@@ -0,0 +1,395 @@
1
+ // `npx goose-tools setup`: adds the /_gt/ dashboard to the owner's site. Shows every change before writing it
2
+ // (spec section 4): the route file, the script tag, .gitignore and the AGENTS.md section. For a stack it does not
3
+ // know, it writes the same steps to GOOSE-TOOLS-SETUP.md for the owner's coding agent instead.
4
+ //
5
+ // The setup code (owner, 2026-11-24): printed once here, and only its SHA-256 goes into the route file.
6
+ //
7
+ // All text approved by the owner, 2026-11-24: the terminal text, the AGENTS.md section and the
8
+ // GOOSE-TOOLS-SETUP.md steps, then --new-code, the host and middleware lines.
9
+ import fs from 'node:fs';
10
+ import path from 'node:path';
11
+ import readline from 'node:readline/promises';
12
+ import { newSetupCode, hashSetupCode } from './site/auth.js';
13
+
14
+ const SCRIPT_TAG = '<script src="/_gt/s.js" defer></script>';
15
+ const AGENTS_MARK = '<!-- goose-tools -->';
16
+ /** The setup value in a route file or the steps file. */
17
+ const SETUP_VALUE = /setup: '[0-9a-f]{64}'/;
18
+ /** Files that show a host which cannot keep the data file yet (README, "Where it runs"). */
19
+ const PLANNED_HOSTS = [
20
+ ['Vercel', ['vercel.json', '.vercel/project.json']],
21
+ ['Cloudflare', ['wrangler.toml', 'wrangler.json', 'wrangler.jsonc', 'open-next.config.ts']],
22
+ ['AWS Amplify', ['amplify.yml']],
23
+ ['Google App Engine', ['app.yaml']],
24
+ ['Firebase App Hosting', ['apphosting.yaml']],
25
+ ];
26
+ /** Approved by the owner, 2026-11-25 (the README's "Where it runs", step 5 of spec/standalone-database.md). */
27
+ const WHERE_IT_RUNS = `Where it runs
28
+
29
+ On a server with a disk, the data is a SQLite file on a persistent local disk. Network file shares don't work. This
30
+ covers your own server or VPS (AWS EC2 and Lightsail, Azure Virtual Machines, Google Compute Engine, DigitalOcean
31
+ Droplets, Hetzner and others), Docker with a volume, Render with a persistent disk, Railway with a volume, and Fly.io
32
+ with a volume on one machine. If your site runs on several servers, each keeps its own file, so run one instance for
33
+ full totals.
34
+
35
+ On Vercel, the data goes in your own Postgres database, such as Supabase or Neon.
36
+
37
+ Planned:
38
+ - Setup for other hosts with no persistent disk: AWS Lambda, Amplify and App Runner, Google Cloud Run and App Engine,
39
+ Azure App Service, Heroku and DigitalOcean App Platform.
40
+ - The Cloudflare plugin, for Cloudflare Workers.
41
+ `;
42
+ /**
43
+ * Hosts with no disk that lasts: the data goes in the site's own Postgres (spec/standalone-database.md section 2).
44
+ * The other hosts above still print WHERE_IT_RUNS.
45
+ */
46
+ const DB_HOSTS = new Set(['Vercel']);
47
+ /**
48
+ * The Postgres clients the route can use, in the order setup picks one: [package, its import, the line that opens it
49
+ * with `url`].
50
+ */
51
+ const CLIENTS = /** @type {const} */ ([
52
+ ['postgres', `import postgres from 'postgres';`, `// prepare: false for Supabase's transaction pooler. One connection per function instance.\nconst db = postgres(url, { prepare: false, max: 1 });`],
53
+ ['pg', `import pg from 'pg';`, `// One connection per function instance.\nconst db = new pg.Pool({ connectionString: url, max: 1 });`],
54
+ ['@neondatabase/serverless', `import { neon } from '@neondatabase/serverless';`, `const db = neon(url);`],
55
+ ]);
56
+ /**
57
+ * With no name in the .env files, the route reads the first of these that is set: Vercel's database integrations set
58
+ * their variables for Production and Preview only, so `vercel env pull` brings none (step 4 test, 2026-11-25). Neon's
59
+ * sets DATABASE_URL, Supabase's POSTGRES_URL. GOOSE_TOOLS_DATABASE_URL always comes first, as setup says.
60
+ */
61
+ const RUNTIME_VARS = { Vercel: ['GOOSE_TOOLS_DATABASE_URL', 'DATABASE_URL', 'POSTGRES_URL'] };
62
+ /**
63
+ * Connection string names, in the order setup picks one: a database just for Goose Tools (the owner's choice, so
64
+ * first), Neon's integration on Vercel (pooled), Supabase's on Vercel (its pooler), then Neon's names with a custom
65
+ * prefix.
66
+ */
67
+ const DB_VARS = ['GOOSE_TOOLS_DATABASE_URL', 'DATABASE_URL', 'POSTGRES_URL'];
68
+ const ENV_FILES = ['.env', '.env.local', '.env.production', '.env.production.local', '.env.development', '.env.development.local'];
69
+ /** The default daily limit on counted views on these hosts (spec/standalone-database.md section 5). */
70
+ const CAP = 10000;
71
+ const NEW_CODE_WHY = 'A new setup code. Signing in with it replaces your password and two-factor sign-in.';
72
+
73
+ /**
74
+ * Variable names set in the project's .env files. Only the names are read: a value never leaves this function.
75
+ * @param {string} root
76
+ * @returns {Set<string>}
77
+ */
78
+ export function envNames(root) {
79
+ const names = new Set();
80
+ for (const f of ENV_FILES) {
81
+ let text = '';
82
+ try {
83
+ text = fs.readFileSync(path.join(root, f), 'utf8');
84
+ } catch {
85
+ continue;
86
+ }
87
+ for (const line of text.split(/\r?\n/)) {
88
+ const m = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=/.exec(line);
89
+ if (m) names.add(m[1]);
90
+ }
91
+ }
92
+ return names;
93
+ }
94
+
95
+ /** @param {Set<string>} names @returns {string | undefined} */
96
+ function pickVar(names) {
97
+ return DB_VARS.find((v) => names.has(v)) ?? [...names].sort().find((v) => /^[A-Z0-9_]+_DATABASE_URL$/.test(v));
98
+ }
99
+
100
+ /**
101
+ * What setup would change in a project, without writing anything.
102
+ * @param {string} root
103
+ * @param {string} hash
104
+ * @param {{newCode?: boolean}} [o] newCode: put a new setup code in place of the old one (a lost password or data file).
105
+ * @returns {{stack: string, host?: [string, string], db?: {client: string, env: string, found: boolean, names: string[]}, needsClient?: boolean, changes: {file: string, action: 'create' | 'edit' | 'append', content: string, why: string}[], manual: string[]}}
106
+ */
107
+ export function plan(root, hash, o = {}) {
108
+ const pkg = readJson(path.join(root, 'package.json'));
109
+ if (!pkg) return { stack: 'none', changes: [], manual: ['There is no package.json here. Run setup in the folder of your site.'] };
110
+ const deps = { ...pkg.dependencies, ...pkg.devDependencies };
111
+ const changes = [];
112
+ const manual = [];
113
+ // The host: one that cannot keep the data file is [name, the file that shows it].
114
+ /** @type {[string, string] | undefined} */
115
+ let host;
116
+ for (const [name, files] of PLANNED_HOSTS) {
117
+ const f = files.find((x) => fs.existsSync(path.join(root, x)));
118
+ if (f) {
119
+ host = [name, f];
120
+ break;
121
+ }
122
+ }
123
+ /** @type {{client: string, env: string, found: boolean, names: string[]} | undefined} */
124
+ let db;
125
+ if (host && DB_HOSTS.has(host[0])) {
126
+ const client = CLIENTS.find(([name]) => deps[name])?.[0];
127
+ // No Postgres client: setup names the one to add and stops. It installs nothing in the owner's project.
128
+ if (!client) return { stack: 'unknown', host, needsClient: true, changes: [], manual: [] };
129
+ const env = pickVar(envNames(root));
130
+ // Approved by the owner, 2026-11-25: the route reads GOOSE_TOOLS_DATABASE_URL first at run time, then the name found
131
+ // in the .env files, or with none found, the names the host's database integrations set.
132
+ const names = env ? [...new Set(['GOOSE_TOOLS_DATABASE_URL', env])] : RUNTIME_VARS[/** @type {'Vercel'} */ (host[0])];
133
+ db = { client, env: env ?? 'DATABASE_URL', found: Boolean(env), names };
134
+ if (!env) manual.push(`If none of them is set, set DATABASE_URL on ${host[0]} to your database's connection string. On Supabase, use the transaction pooler (port 6543).`);
135
+ // Approved by the owner, 2026-11-24: postgres and pg use SSL only when the connection string asks for it, and the
136
+ // route cannot set it without weakening a string that already checks the certificate (step 3 review).
137
+ manual.push('Check that the connection string has sslmode=require. Sign-in data then travels encrypted.');
138
+ // Approved by the owner, 2026-11-24: before 1.2.0, neon() throws when the route loads if the variable is not set.
139
+ if (client === '@neondatabase/serverless') {
140
+ const v = String(readJson(path.join(root, 'node_modules', '@neondatabase', 'serverless', 'package.json'))?.version ?? '');
141
+ const [major, minor] = v.split('.').map(Number);
142
+ if (v && (major < 1 || (major === 1 && minor < 2))) manual.push('Update the Neon client to version 1.2 or later: npm install @neondatabase/serverless@latest');
143
+ }
144
+ }
145
+ if (!pkg.dependencies || !pkg.dependencies['@goosetools/goose-tools']) manual.push('Run npm install @goosetools/goose-tools, so the route can load it.');
146
+ let stack = 'unknown';
147
+
148
+ const appDir = ['app', 'src/app'].map((d) => path.join(root, d)).find((d) => fs.existsSync(d) && fs.statSync(d).isDirectory());
149
+ if (deps.next && appDir) {
150
+ stack = 'next';
151
+ const rel = path.relative(root, appDir);
152
+ const route = path.join(rel, '%5Fgt', '[[...path]]', 'route.js');
153
+ // Already set up: the route and its setup code stay as they are, unless a new code is asked for.
154
+ const old = fs.existsSync(path.join(root, route)) ? fs.readFileSync(path.join(root, route), 'utf8') : null;
155
+ const oldValue = old && SETUP_VALUE.exec(old);
156
+ if (old === null) {
157
+ changes.push({ file: route, action: 'create', why: 'The dashboard at /_gt/ and the page-view counter.', content: nextRoute(hash, db) });
158
+ } else if (db && oldValue && !/\bdb\b/.test(old)) {
159
+ // Approved by the owner, 2026-11-25 (step 6 review): a data file route on a host with no persistent disk, written
160
+ // before the host was known (a site linked to Vercel through Git only), switches to the database. It keeps its
161
+ // setup value, so the setup code already given still works, unless a new code is asked for.
162
+ changes.push({ file: route, action: 'edit', why: 'Keeps the data in your Postgres database.', content: nextRoute(o.newCode ? hash : oldValue[0].slice(8, -1), db) });
163
+ } else if (o.newCode) {
164
+ if (oldValue) changes.push({ file: route, action: 'edit', why: NEW_CODE_WHY, content: old.replace(SETUP_VALUE, `setup: '${hash}'`) });
165
+ else manual.push(`Put this setup value in your server code, in place of the old one: ${hash}`);
166
+ }
167
+ const layout = ['layout.tsx', 'layout.jsx', 'layout.js', 'layout.ts'].map((f) => path.join(appDir, f)).find((f) => fs.existsSync(f));
168
+ const source = layout ? fs.readFileSync(layout, 'utf8') : '';
169
+ // Middleware that runs on every path (an i18n or auth matcher) would redirect /_gt/. Next.js 16 calls it proxy.
170
+ if (['middleware', 'src/middleware', 'proxy', 'src/proxy'].flatMap((f) => [f + '.ts', f + '.js']).some((f) => fs.existsSync(path.join(root, f)))) {
171
+ manual.push('Leave /_gt/ out of your middleware or proxy matcher, so page views and the dashboard reach it.');
172
+ }
173
+ if (source.includes('/_gt/s.js')) {
174
+ // Already added.
175
+ } else if (layout && /<\/body>/.test(source)) {
176
+ changes.push({ file: path.relative(root, layout), action: 'edit', why: 'Counts each page view.', content: source.replace(/(\s*)<\/body>/, `$1 ${SCRIPT_TAG}$1</body>`) });
177
+ } else {
178
+ manual.push(`Add this line inside <body> in your root layout: ${SCRIPT_TAG}`);
179
+ }
180
+ } else if (deps.next) {
181
+ stack = 'next-pages';
182
+ manual.push('This site uses the Next.js Pages Router. Setup supports the App Router for now.');
183
+ } else {
184
+ stack = deps.express ? 'express' : 'node';
185
+ }
186
+
187
+ const ignore = path.join(root, '.gitignore');
188
+ const ignored = fs.existsSync(ignore) ? fs.readFileSync(ignore, 'utf8') : '';
189
+ // With the site's own database there is no data file to keep out of git.
190
+ if (!db && !/^\/?\.goose-tools\/?$/m.test(ignored)) {
191
+ changes.push({ file: '.gitignore', action: fs.existsSync(ignore) ? 'append' : 'create', why: 'Keeps the data file out of git.', content: `${ignored && !ignored.endsWith('\n') ? '\n' : ''}.goose-tools/\n` });
192
+ }
193
+
194
+ const agents = path.join(root, 'AGENTS.md');
195
+ const agentsText = fs.existsSync(agents) ? fs.readFileSync(agents, 'utf8') : '';
196
+ if (!agentsText.includes(AGENTS_MARK)) {
197
+ changes.push({ file: 'AGENTS.md', action: fs.existsSync(agents) ? 'append' : 'create', why: 'Tells your coding agent about Goose Tools.', content: (agentsText && !agentsText.endsWith('\n') ? '\n' : '') + (agentsText ? '\n' : '') + agentsSection() });
198
+ }
199
+
200
+ // Already set up: the steps file and its setup code stay as they are, unless a new code is asked for.
201
+ const steps = path.join(root, 'GOOSE-TOOLS-SETUP.md');
202
+ if ((stack === 'express' || stack === 'node') && fs.existsSync(steps) && o.newCode) {
203
+ const old = fs.readFileSync(steps, 'utf8');
204
+ if (SETUP_VALUE.test(old)) changes.push({ file: 'GOOSE-TOOLS-SETUP.md', action: 'edit', why: NEW_CODE_WHY, content: old.replace(SETUP_VALUE, `setup: '${hash}'`) });
205
+ manual.push(`Put this setup value in your server code, in place of the old one: ${hash}`);
206
+ } else if ((stack === 'express' || stack === 'node') && !fs.existsSync(steps)) {
207
+ changes.push({ file: 'GOOSE-TOOLS-SETUP.md', action: 'create', why: 'The steps for your coding agent, since setup cannot edit your server code itself.', content: nodeSteps(hash, stack, db) });
208
+ // The steps file was deleted after setup: the server code still holds the old value.
209
+ if (o.newCode) manual.push(`Put this setup value in your server code, in place of the old one: ${hash}`);
210
+ }
211
+ return { stack, host, db, changes, manual };
212
+ }
213
+
214
+ /**
215
+ * The route's database lines and its site() options.
216
+ * @param {string} hash @param {{client: string, env: string, names?: string[]} | undefined} db @param {boolean} [inline]
217
+ */
218
+ function siteParts(hash, db, inline = false) {
219
+ if (!db) return { lines: '', options: `{ setup: '${hash}' }` };
220
+ const [, imp, open] = /** @type {readonly [string, string, string]} */ (CLIENTS.find(([name]) => name === db.client));
221
+ const url = (db.names ?? [db.env]).map((n) => `process.env.${n}`).join(' || ');
222
+ // Inline in the steps for the owner's own server file, where a `url` of its own may already be declared.
223
+ const lines = inline ? `${imp}\n\n${open.replace(/\burl\b/, url)}\n` : `${imp}\n\nconst url = ${url};\n${open}\n`;
224
+ return { lines, options: `{ setup: '${hash}', db, dailyLimit: ${CAP} }` };
225
+ }
226
+
227
+ /** @param {string} hash @param {{client: string, env: string, names?: string[]}} [db] */
228
+ export function nextRoute(hash, db) {
229
+ const { lines, options } = siteParts(hash, db);
230
+ const cap = db ? `// The data goes in your own Postgres, in its own goose_tools tables. dailyLimit: at most ${CAP.toLocaleString('en-US')} counted views a day.\n` : '';
231
+ return `// Goose Tools: the dashboard at /_gt/ and the page-view counter. Written by \`npx goose-tools setup\`.
232
+ // The setup value is the SHA-256 of a one-time code. It is safe to commit.
233
+ ${cap}import { site } from '@goosetools/goose-tools/site';
234
+ ${lines}
235
+ export const runtime = 'nodejs';
236
+ export const dynamic = 'force-dynamic';
237
+ export const { GET, POST, HEAD } = site(${options});
238
+ `;
239
+ }
240
+
241
+ /** @param {string} hash @param {string} stack @param {{client: string, env: string, names?: string[]}} [db] */
242
+ function nodeSteps(hash, stack, db) {
243
+ const mount = stack === 'express' ? "app.use(gt); // before your other routes" : 'http.createServer(async (req, res) => {\n if (await gt(req, res)) return;\n // ...your server\n});';
244
+ const { lines, options } = siteParts(hash, db, true);
245
+ return `# Add Goose Tools to this site
246
+
247
+ 1. In the server's entry file, add:
248
+
249
+ \`\`\`js
250
+ import { site, nodeHandler } from '@goosetools/goose-tools/site';
251
+ ${lines ? lines + '\n' : '\n'}const gt = nodeHandler(site(${options}));
252
+ ${mount}
253
+ \`\`\`
254
+
255
+ 2. In every page's HTML, add this line inside \`<body>\`:
256
+
257
+ \`\`\`html
258
+ ${SCRIPT_TAG}
259
+ \`\`\`
260
+
261
+ 3. Deploy. Then open /_gt/ on the live site and enter the setup code.
262
+ `;
263
+ }
264
+
265
+ export function agentsSection() {
266
+ return `${AGENTS_MARK}
267
+ ## Goose Tools
268
+
269
+ This site uses Goose Tools (https://goosetools.app). The dashboard is at /_gt/.
270
+
271
+ - Check the live site: \`npx @goosetools/goose-tools check <url> --json\`. Each finding includes its fix for this stack.
272
+ - Apply fixes in the code. The owner reviews and deploys them. Then check again to confirm.
273
+ - Do not edit app/%5Fgt/ or remove the /_gt/s.js script tag.
274
+ `;
275
+ }
276
+
277
+ /** @param {string} file */
278
+ function readJson(file) {
279
+ try {
280
+ return JSON.parse(fs.readFileSync(file, 'utf8'));
281
+ } catch {
282
+ return null;
283
+ }
284
+ }
285
+
286
+ /**
287
+ * Write the planned changes.
288
+ * @param {string} root
289
+ * @param {ReturnType<typeof plan>['changes']} changes
290
+ */
291
+ export function apply(root, changes) {
292
+ for (const c of changes) {
293
+ const file = path.join(root, c.file);
294
+ fs.mkdirSync(path.dirname(file), { recursive: true });
295
+ if (c.action === 'append') fs.appendFileSync(file, c.content);
296
+ else fs.writeFileSync(file, c.content, { flag: c.action === 'create' ? 'wx' : 'w' });
297
+ }
298
+ }
299
+
300
+ /**
301
+ * @param {{root?: string, yes?: boolean, newCode?: boolean, out?: (s: string) => void, ask?: (q: string) => Promise<string>}} [o]
302
+ * @returns {Promise<number>} Exit code.
303
+ */
304
+ export async function runSetup(o = {}) {
305
+ const root = o.root ?? process.cwd();
306
+ const out = o.out ?? ((s) => process.stdout.write(s + '\n'));
307
+ const code = newSetupCode();
308
+ const hash = await hashSetupCode(code);
309
+ const p = plan(root, hash, { newCode: o.newCode });
310
+
311
+ out('Goose Tools setup\n');
312
+ if (p.needsClient && p.host) {
313
+ // Approved by the owner, 2026-11-24 (step 3 of spec/standalone-database.md).
314
+ out(`This project deploys to ${p.host[0]} (${p.host[1]}). ${p.host[0]} has no disk for the data file.`);
315
+ out('The data can go in your own Postgres database instead, such as Supabase or Neon.\n');
316
+ out('Add a Postgres client to your site first:');
317
+ out(' npm install postgres');
318
+ out('Then run setup again.');
319
+ return 1;
320
+ }
321
+ out('Before you install:');
322
+ out('- No install scripts and no dependencies.');
323
+ if (p.db && p.host) {
324
+ // Approved by the owner, 2026-11-24 (step 3 of spec/standalone-database.md).
325
+ out('- Your data stays in your own Postgres database, in its own goose_tools tables. Nothing is sent to us.');
326
+ out('- Each page view is one small write to your database.');
327
+ out(`- Counting stops at ${CAP.toLocaleString('en-US')} views a day. It starts again at midnight UTC.`);
328
+ out('- You can change the limit in the route file.');
329
+ } else {
330
+ out('- Your data stays in your site: a SQLite file in .goose-tools/. Nothing is sent to us.');
331
+ out('- Your host must keep that file between deploys.');
332
+ out('- Each page view is one small write to that file.');
333
+ }
334
+ out('- /_gt/ needs your password and an authenticator code.\n');
335
+ const told = p.manual.some((m) => m.includes(hash));
336
+ if (!p.changes.length && !told) {
337
+ if (p.stack === 'none' || p.stack === 'next-pages') {
338
+ p.manual.forEach((m) => out(m));
339
+ return 1;
340
+ }
341
+ out('Goose Tools is already set up here.');
342
+ out('For a new setup code, run: npx goose-tools setup --new-code');
343
+ for (const m of p.manual) out(` You: ${m}`);
344
+ return 0;
345
+ }
346
+ if (p.db && p.host) {
347
+ // Approved by the owner, 2026-11-24 (step 3 of spec/standalone-database.md).
348
+ out(`This project deploys to ${p.host[0]} (${p.host[1]}).`);
349
+ // Approved by the owner, 2026-11-25 (the line with no name found).
350
+ out(p.db.found ? `The route connects with ${p.db.client} and ${p.db.env}, found in your .env files.` : `The route connects with ${p.db.client} and the first of these set on ${p.host[0]}: ${p.db.names.join(', ')}.`);
351
+ // Two sites on one database share one sign-in: a claim from either replaces the other's (step 3 review).
352
+ out('Each site needs its own database. Two sites on one database share one sign-in.');
353
+ out('For a database just for Goose Tools, set GOOSE_TOOLS_DATABASE_URL. It is used first when set.\n');
354
+ } else if (p.host) {
355
+ // Approved by the owner, 2026-11-24.
356
+ out(`This project deploys to ${p.host[0]} (${p.host[1]}). ${p.host[0]} can't keep the data file yet.\n`);
357
+ out(WHERE_IT_RUNS);
358
+ }
359
+ if (p.changes.length) out('Setup will make these changes:');
360
+ for (const c of p.changes) out(` ${c.action === 'create' ? 'Create' : c.action === 'edit' ? 'Edit ' : 'Add to'} ${c.file} (${c.why})`);
361
+ for (const m of p.manual) out(` You: ${m}`);
362
+ out('');
363
+
364
+ let yes = o.yes || !p.changes.length;
365
+ if (!yes) {
366
+ const ask = o.ask ?? (async (q) => {
367
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
368
+ // Input that ends with no answer (an agent's shell, a pipe) is a "no": the question never resolves on its own.
369
+ const a = await new Promise((resolve) => {
370
+ rl.once('close', () => resolve(''));
371
+ rl.question(q).then(resolve, () => resolve(''));
372
+ });
373
+ rl.close();
374
+ return a;
375
+ });
376
+ yes = /^y(es)?$/i.test((await ask('Make these changes? (y/N) ')).trim());
377
+ }
378
+ if (!yes) {
379
+ out('Nothing was changed.');
380
+ return 1;
381
+ }
382
+ apply(root, p.changes);
383
+ if (p.changes.length) out('Done.\n');
384
+ // The code is shown only when its hash was just written, or the owner was told where to put it.
385
+ if (p.changes.some((c) => c.content.includes(hash)) || told) {
386
+ out('Your setup code (shown once, keep it until you sign in):');
387
+ out(` ${code}\n`);
388
+ }
389
+ // Approved by the owner, 2026-11-24: when the steps file was written, the agent step comes first.
390
+ const next = ['Deploy your site.', 'Open /_gt/ on the live site.', 'Enter the setup code. Pick a password and add your authenticator app.'];
391
+ if (p.changes.some((c) => c.file === 'GOOSE-TOOLS-SETUP.md')) next.unshift('Ask your coding agent to follow GOOSE-TOOLS-SETUP.md.');
392
+ out('Next:');
393
+ next.forEach((line, i) => out(`${i + 1}. ${line}`));
394
+ return 0;
395
+ }