serpkin 0.2.22 → 0.2.24

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/commands.mjs CHANGED
@@ -29,6 +29,8 @@ import {
29
29
  buildRouteMap,
30
30
  publicDir,
31
31
  routeMapFramework,
32
+ likelyWebsite,
33
+ gitRoot,
32
34
  } from "./detect.mjs";
33
35
  import {
34
36
  AGENTS, hermesBlock, hermesConfigPath, appendHermesConfig,
@@ -49,8 +51,26 @@ import {
49
51
  import { writeCursorRule, writeAgentsSection } from "./rules.mjs";
50
52
  import { DEFAULT_SERVER } from "./config.mjs";
51
53
  import { clean as cleanLine } from "../plugin/serpkin/scripts/next-line.mjs";
54
+ import { localCheck, isLocalHost } from "./local-check.mjs";
52
55
 
53
- const PREVIEW_HOSTS = /\.(vercel\.app|netlify\.app|pages\.dev)$/i;
56
+ const LANES = ["code", "content", "outreach", "research"];
57
+ /**
58
+ * --lanes code,content → ["code", "content"]; absent, empty or every lane → null (all lanes, the default).
59
+ * An unknown lane is an error, so a typo never silently gives the key every lane.
60
+ */
61
+ export function parseLanes(value) {
62
+ if (value === undefined || value === null || value === true || value === "" || value === "all") return null;
63
+ const asked = [...new Set(String(value).split(",").map((x) => x.trim().toLowerCase()).filter(Boolean))];
64
+ const bad = asked.filter((x) => !LANES.includes(x));
65
+ if (bad.length)
66
+ throw new CliError(`Unknown lane ${bad.map((x) => `"${x}"`).join(", ")}. Use any of ${LANES.join(", ")} (owner missions always stay with you), or leave --lanes out for all lanes.`);
67
+ const picked = LANES.filter((l) => asked.includes(l));
68
+ return picked.length && picked.length < LANES.length ? picked : null;
69
+ }
70
+
71
+ /** Deploy platforms' preview domains (the server's list is lib/preview-hosts.ts). */
72
+ const PREVIEW_HOSTS =
73
+ /\.(vercel\.app|netlify\.app|pages\.dev|workers\.dev|onrender\.com|fly\.dev|up\.railway\.app|web\.app|firebaseapp\.com|amplifyapp\.com|azurestaticapps\.net|ondigitalocean\.app|deno\.dev|lovable\.app|lovableproject\.com|bolt\.host|replit\.app)$/i;
54
74
  const FRAMEWORK_NAMES = {
55
75
  nextjs: "Next.js",
56
76
  "nextjs-app": "Next.js (app router)",
@@ -144,10 +164,45 @@ export function normalizeUrl(input) {
144
164
  /** `--app` as detectApps reports roots: "apps/web", or "." for the repository itself. */
145
165
  const appRoot = (dir) =>
146
166
  String(dir).replace(/\\/g, "/").replace(/^(\.\/)+/, "").replace(/\/+$/, "").replace(/^\.?$/, ".");
147
- const isLocal = (origin) =>
148
- /^(localhost|127\.|0\.0\.0\.0|\[::1\])|\.local$/i.test(
149
- new URL(origin).hostname,
167
+ const isLocal = (origin) => isLocalHost(new URL(origin).hostname);
168
+
169
+ /**
170
+ * Which detected app is the website: --app, then the app saved in .serpkin.json, then the only one. With several,
171
+ * ask (the likely website first), or without a terminal take the likely website when it is clear (a website-named
172
+ * folder such as web/ or apps/web, or the package whose homepage is the site) and say so.
173
+ */
174
+ async function pickApp(apps, flags, project, { siteOrigin = null, purpose = "the website" } = {}) {
175
+ const list = apps.map((a) => (a.root === "." ? "./" : a.root)).join(", ");
176
+ if (flags.app) {
177
+ const app = apps.find((a) => a.root === appRoot(flags.app));
178
+ if (!app)
179
+ throw new CliError(`No supported app found at ${flags.app}.${apps.length ? ` Apps here: ${list}` : ""}`);
180
+ return app;
181
+ }
182
+ const saved = project?.app ? apps.find((a) => a.root === appRoot(project.app)) : null;
183
+ if (saved) return saved;
184
+ if (apps.length <= 1) return apps[0] ?? null;
185
+ const likely = likelyWebsite(apps, siteOrigin ?? project?.origin ?? null);
186
+ if (!interactive(flags) && likely) {
187
+ out.note(`Found ${apps.length} apps (${list}); using ${likely.root} as ${purpose}. Pass --app <dir> to choose another.`);
188
+ return likely;
189
+ }
190
+ const ordered = likely ? [likely, ...apps.filter((a) => a !== likely)] : apps;
191
+ return choose(
192
+ "Which app is the website?",
193
+ ordered.map((a) => ({
194
+ value: a,
195
+ label: `${a.root} ${c.dim(`(${FRAMEWORK_NAMES[a.framework]}, ${a.name})`)}`,
196
+ })),
197
+ {
198
+ opts: flags,
199
+ def: likely ?? undefined,
200
+ needed: `Found ${apps.length} apps (${list}). Pass --app <dir> to choose one, for example --app ${apps[0].root}.`,
201
+ },
150
202
  );
203
+ }
204
+ /** File paths in route maps are relative to the repository root, even when the CLI runs in a subfolder. */
205
+ const repoBase = async (cwd) => (await gitRoot(cwd)) ?? cwd;
151
206
 
152
207
  /* ─────────────────────────────── init ─────────────────────────────── */
153
208
 
@@ -158,6 +213,8 @@ export async function init(flags, ctx = context()) {
158
213
  out.line();
159
214
 
160
215
  // 1. Sign in (device code), unless a working key is already stored.
216
+ // --lanes code,content: the new key only takes missions from those lanes (owner missions always stay with you).
217
+ const lanes = parseLanes(flags.lanes);
161
218
  let cred = flags.login ? null : await apiKeyFor(server, ctx.env);
162
219
  let api = createClient({
163
220
  server,
@@ -178,11 +235,14 @@ export async function init(flags, ctx = context()) {
178
235
  out.warn("The stored key no longer works. Signing in again.");
179
236
  cred = null;
180
237
  }
238
+ // Lanes belong to a key: a stored key keeps its own. Change them in Settings → Agents, or sign in again.
239
+ if (cred && lanes) out.note("--lanes applies to a new key: this machine already has one. Change its lanes in Settings → Agents, or add --login.");
181
240
  }
182
241
  if (!cred) {
183
242
  const token = await deviceLogin(api, {
184
243
  clientName: "Serpkin CLI",
185
244
  hostname: cleanHost(),
245
+ lanes,
186
246
  wait: ctx.wait,
187
247
  onCode: (d) => {
188
248
  // Only show/open approval pages on the server we are signing in to.
@@ -227,26 +287,10 @@ export async function init(flags, ctx = context()) {
227
287
 
228
288
  // 2. Framework and route map.
229
289
  const apps = flags["connect-only"] ? [] : await detectApps(ctx.cwd);
230
- let app = null;
231
- if (flags.app) {
232
- app = apps.find((a) => a.root === appRoot(flags.app)) ?? null;
233
- if (!app) throw new CliError(`No supported app found at ${flags.app}.`);
234
- } else if (apps.length === 1) app = apps[0];
235
- else if (apps.length > 1)
236
- app = await choose(
237
- "Which app is the website?",
238
- apps.map((a) => ({
239
- value: a,
240
- label: `${a.root} ${c.dim(`(${FRAMEWORK_NAMES[a.framework]}, ${a.name})`)}`,
241
- })),
242
- {
243
- opts: flags,
244
- needed: `Found ${apps.length} apps (${apps.map((a) => a.root).join(", ")}). Pass --app <dir> to choose one.`,
245
- },
246
- );
290
+ const app = flags["connect-only"] ? null : await pickApp(apps, flags, project, { siteOrigin: normalizeUrl(flags.url) });
247
291
  let routeMap = null;
248
292
  if (app) {
249
- routeMap = await buildRouteMap(app, ctx.cwd);
293
+ routeMap = await buildRouteMap(app, await repoBase(ctx.cwd));
250
294
  const dyn = routeMap.routes.filter((r) => r.dynamic).length;
251
295
  out.ok(
252
296
  `${FRAMEWORK_NAMES[app.framework]}${app.router ? ` (${app.router.replace("+", " + ")} router)` : ""}` +
@@ -258,7 +302,7 @@ export async function init(flags, ctx = context()) {
258
302
  );
259
303
 
260
304
  // 3. Coding agents.
261
- const { usedEnv, plugin } = await setupAgents(flags, ctx, {
305
+ const { usedEnv, plugin, connected } = await setupAgents(flags, ctx, {
262
306
  mcpUrl,
263
307
  apiKey: cred.api_key,
264
308
  });
@@ -295,12 +339,12 @@ export async function init(flags, ctx = context()) {
295
339
  let site = null,
296
340
  token = null;
297
341
  if (isLocal(origin)) {
298
- out.warn(`${origin} is on this machine, so Serpkin can't reach it.`);
342
+ out.warn(`${origin} is on this machine, so Serpkin can't scan it. Register the public site instead.`);
299
343
  out.note(
300
- "Deploy a preview (for example a vercel.app URL) and run `npx serpkin init --url <preview-url>`.",
344
+ "Run `npx serpkin init --url https://your-domain` (or a preview URL such as a vercel.app address if it isn't live yet).",
301
345
  );
302
346
  out.note(
303
- "Foundation checks work on a preview; production verification comes once the domain is live.",
347
+ "Once the site is registered, `npx serpkin check " + origin + "` compares a local build with production before you deploy (a pre-deploy check, not production verification).",
304
348
  );
305
349
  } else {
306
350
  const pkg = app
@@ -372,6 +416,8 @@ export async function init(flags, ctx = context()) {
372
416
  server,
373
417
  site_id: site.site_id,
374
418
  origin: site.origin,
419
+ // The app folder in a monorepo, so `serpkin routes` finds it again without --app.
420
+ ...(app && app.root !== "." ? { app: app.root } : {}),
375
421
  });
376
422
  out.ok(
377
423
  `Site registered: ${site.origin} ${c.dim(`(${PROJECT_FILE} saved; it holds no secrets)`)}`,
@@ -394,9 +440,15 @@ export async function init(flags, ctx = context()) {
394
440
  );
395
441
  }
396
442
 
443
+ // No plan (trial mode): missions, full scans, verification and credits come with the trial, so the ending
444
+ // shows the preview and the one offer instead of credit notes and "missions work now".
445
+ let noPlan = site
446
+ ? await api.get("/api/state?limit=1").then((s) => s?.billing?.no_plan === true, () => false)
447
+ : false;
448
+
397
449
  // 6. Ownership.
398
450
  if (site && site.ownership_status !== "verified")
399
- await ownership(flags, ctx, { server, site, token, app });
451
+ await ownership(flags, ctx, { server, site, token, app, noPlan });
400
452
  else if (site) out.ok("Ownership already verified.");
401
453
 
402
454
  // 7. Next step.
@@ -405,10 +457,31 @@ export async function init(flags, ctx = context()) {
405
457
  printKeySetup({ server, cred, plugin, ctx });
406
458
  // 8. First mission: scan now (preview scan until ownership is verified) and show what Serpkin found.
407
459
  if (site) out.note(`Search market: ${site.country || flags.country || "saved country"} / ${site.language || flags.language || "saved language"}. Review it in Settings → Business details.`);
408
- if (site) out.note(site.auto_research === false
460
+ if (site && !noPlan) out.note(site.auto_research === false
409
461
  ? "Automatic topic research is off. You can start research yourself in Serpkin."
410
462
  : "Automatic research can use plan credits (2 per keyword seed; ranking estimates use 3). Change this in Settings → Automation; new sites opt in with --auto-research.");
411
- const shown = site && !flags["no-wait"] && !flags["no-scan"] ? await firstMission(api, site, ctx) : false;
463
+ const waited = site && !flags["no-wait"] && !flags["no-scan"];
464
+ let { shown, offer } = waited ? await firstMission(api, site, ctx) : { shown: false, offer: null };
465
+ if (site && noPlan && !waited) {
466
+ // --no-wait: one quick read for the offer; the preview scan keeps running on the server.
467
+ offer = await api.tool("serpkin_next_mission", { site_id: site.site_id }).then((r) => trialOfferFrom(r?.result), () => null);
468
+ out.line();
469
+ out.note("The preview scan is running. `npx serpkin status` shows your first mission when it finishes.");
470
+ }
471
+ if (offer && !shown) {
472
+ noPlan = true;
473
+ await offerCheckout(offer, flags, ctx, server);
474
+ out.line();
475
+ }
476
+ if (site && noPlan) {
477
+ const after = offer?.trial_available === false ? "Once your plan is active" : "After you start the trial";
478
+ out.line(
479
+ connected
480
+ ? `${after}, ask your agent: ${c.violet('"Do the next Serpkin mission"')}`
481
+ : `${after}, connect your agent (Settings → Agents in Serpkin) and ask it: ${c.violet('"Do the next Serpkin mission"')}`,
482
+ );
483
+ return { server, site, routeMap, app };
484
+ }
412
485
  out.line(
413
486
  shown
414
487
  ? `${c.bold("Setup connected. First recommendation ready.")} Ask your agent to review it: ${c.violet('"What should I do for SEO?"')}${plugin ? ` or ${c.violet("/serpkin:next")}` : ""}`
@@ -445,6 +518,8 @@ const JOB_DONE = new Set(["succeeded", "partial", "failed", "cancelled"]);
445
518
  /**
446
519
  * Reuse the server's initial audit or request a scan (per-site/day key), wait for it up to
447
520
  * `ctx.scanWaitMs` (75 s) and print the first mission. Connection success is separate from audit success; failures leave an explicit recovery receipt.
521
+ * Resolves with { shown, offer }: `shown` when a mission was printed; `offer` (the trial offer) for a workspace without
522
+ * a plan, after its preview mission or clean preview was printed. init then offers checkout once.
448
523
  */
449
524
  export async function firstMission(api, site, ctx = {}) {
450
525
  const wait = ctx.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
@@ -478,23 +553,22 @@ export async function firstMission(api, site, ctx = {}) {
478
553
  }
479
554
  const context = await api.tool("serpkin_get_site_context", { site_id: site.site_id }).catch(() => null);
480
555
  const audit = context?.result?.audit;
481
- if (audit?.brief?.product) out.note(`Site understanding: ${cleanLine(audit.brief.product, 180)}`);
482
- if (audit?.scan_id) out.note(`${Number(audit.checked_pages ?? audit.inventory_count ?? 0)} pages read. ${cleanLine(audit.reason, 400)}`);
483
556
  const m = next?.result?.mission;
484
- const trial = next?.result?.upgrade?.trial_days ? next.result.upgrade : null;
485
- if (trial) {
486
- // No plan: show the preview, then one clear way forward (no obscure failure).
487
- out.line();
488
- out.warn(cleanLine(trial.message, 400));
489
- if (!m) return false;
557
+ const offer = trialOfferFrom(next?.result);
558
+ if (offer && !m) {
559
+ // No plan: the preview's first mission (or a clean preview), then one clear way forward.
560
+ printPreview(next.result, audit, scanStatus, offer);
561
+ return { shown: false, offer };
490
562
  }
563
+ if (audit?.brief?.product) out.note(`Site understanding: ${cleanLine(audit.brief.product, 180)}`);
564
+ if (audit?.scan_id) out.note(`${Number(audit.checked_pages ?? audit.inventory_count ?? 0)} pages read. ${cleanLine(audit.reason, 400)}`);
491
565
  if (!m) {
492
566
  out.note(JOB_DONE.has(scanStatus)
493
567
  ? scanStatus === "failed" || scanStatus === "cancelled"
494
568
  ? "The first scan didn't finish successfully. Check the scan in Serpkin and retry it."
495
569
  : cleanLine(next?.result?.suggested_action, 400) || "The scan finished. No evidence-backed missions need attention right now."
496
570
  : "The scan is still running. Your agent will see supported missions after assessment completes.");
497
- return false;
571
+ return { shown: false, offer: null };
498
572
  }
499
573
  const total = Number(next.result.queue_length ?? 1);
500
574
  out.line();
@@ -504,13 +578,106 @@ export async function firstMission(api, site, ctx = {}) {
504
578
  const why = cleanLine(next.result.why_now, 160);
505
579
  if (why) out.note(why);
506
580
  out.line();
507
- return true;
581
+ return { shown: true, offer: null };
508
582
  } catch {
509
583
  out.warn("The connection is saved, but the first recommendation could not be loaded. Open Serpkin to check the audit, or run npx serpkin status when the server is reachable. No mission is being claimed as ready.");
510
- return false;
584
+ return { shown: false, offer: null };
511
585
  }
512
586
  }
513
587
 
588
+ /**
589
+ * The trial offer in a serpkin_next_mission result: `trial_offer` (current servers) or the no-plan `upgrade` hint
590
+ * (older servers). Null with a plan. Only an http(s) address without credentials is kept.
591
+ */
592
+ export function trialOfferFrom(result) {
593
+ const t = result?.trial_offer ?? null;
594
+ const u = result?.upgrade?.trial_days ? result.upgrade : null;
595
+ if (!t && !u) return null;
596
+ let url = null;
597
+ try {
598
+ const parsed = new URL(String(t?.url ?? u?.checkout_url ?? u?.url ?? ""));
599
+ if (["http:", "https:"].includes(parsed.protocol) && !parsed.username && !parsed.password) url = parsed.href;
600
+ } catch {}
601
+ const num = (v) => (typeof v === "number" && Number.isFinite(v) && v >= 0 ? v : null);
602
+ const date = String(t?.first_charge_on ?? t?.first_charge_date ?? "");
603
+ return {
604
+ url,
605
+ trial_days: num(t?.trial_days ?? u?.trial_days) || 7,
606
+ trial_available: (t ?? u).trial_available !== false,
607
+ price_month: num(t?.price_month ?? t?.price ?? u?.price_month),
608
+ first_charge_on: /^\d{4}-\d{2}-\d{2}$/.test(date) ? date : null,
609
+ };
610
+ }
611
+
612
+ const plural = (n, word) => `${n} ${word}${n === 1 ? "" : "s"}`;
613
+ /**
614
+ * No plan: what the preview scan found. Site text is untrusted, so only the mission title (cleaned and clipped) is
615
+ * printed: never its page text, the site summary or the homepage title.
616
+ */
617
+ function printPreview(result, audit, scanStatus, offer) {
618
+ const pm = result?.preview_mission ?? null;
619
+ const clean = result?.preview_clean ?? null;
620
+ const unlock = offer.trial_available ? `The ${offer.trial_days}-day trial unlocks` : "A plan unlocks";
621
+ const pages = Number(audit?.checked_pages ?? audit?.inventory_count ?? clean?.pages_checked ?? 0);
622
+ out.line();
623
+ if (!pm && !clean) {
624
+ const done = JOB_DONE.has(scanStatus) || (!!audit?.scan_id && !["queued", "running"].includes(audit?.status));
625
+ if (scanStatus === "failed" || scanStatus === "cancelled" || audit?.status === "failed")
626
+ out.note("The preview scan didn't finish. Check it in Serpkin and retry it.");
627
+ else if (!done)
628
+ out.note("The preview scan is still running. `npx serpkin status` shows your first mission when it finishes.");
629
+ else {
630
+ // Finished, but no preview to show (an older server sends only the upgrade hint).
631
+ if (pages > 0) out.ok(`Preview scan: ${plural(pages, "page")} read`);
632
+ if (!offer.url) out.note(cleanLine(result?.trial_offer?.message ?? result?.upgrade?.message, 400));
633
+ }
634
+ return;
635
+ }
636
+ if (pages > 0) out.ok(`Preview scan: ${plural(pages, "page")} read`);
637
+ out.line();
638
+ if (pm) {
639
+ const pos = typeof pm.position === "number" && pm.position >= 1 ? c.dim(` (#${Math.round(pm.position)} today)`) : "";
640
+ out.line(`${c.bold("Your first mission")} ${cleanLine(pm.title, 120)}${pos}`);
641
+ out.line(`Your agent can ship it today. ${unlock} the brief, the full scan and verification.`);
642
+ return;
643
+ }
644
+ out.line(c.bold("Clean. That's the floor."));
645
+ const passed = Number(clean.checks_passed) || 0;
646
+ const unread = typeof clean.pages_not_checked === "number" && clean.pages_not_checked > 0 ? clean.pages_not_checked : 0;
647
+ out.note(`${plural(passed, "check")} passed${unread ? `, ${plural(unread, "page")} not checked yet` : ""}.`);
648
+ const topic = cleanLine(clean.opportunity?.topic, 80);
649
+ if (topic) out.note(`Opportunity: your homepage title doesn't mention "${topic}" (from your business brief, not search data).`);
650
+ out.line(`${unlock} the full scan, missions and verification.`);
651
+ }
652
+
653
+ const shortDate = (ymd) =>
654
+ new Date(`${ymd}T00:00:00Z`).toLocaleDateString("en-US", { month: "short", day: "numeric", timeZone: "UTC" });
655
+ /**
656
+ * The one trial offer: its terms, then "Open checkout in your browser?" in an interactive terminal (Enter or y opens
657
+ * it with the sign-in's browser helper; n prints the address once). Without a terminal, with --yes or --no-browser it
658
+ * prints the address and never waits. `ctx.interactive`, `ctx.confirm` and `ctx.openBrowser` are test seams.
659
+ */
660
+ export async function offerCheckout(offer, flags = {}, ctx = {}, server) {
661
+ if (!offer?.url) return false;
662
+ const price = offer.price_month != null ? `$${offer.price_month}/month` : null;
663
+ out.line();
664
+ out.note(
665
+ offer.trial_available
666
+ ? `Builder: ${offer.trial_days}-day free trial, card required${price ? `. ${price}${offer.first_charge_on ? ` from ${shortDate(offer.first_charge_on)}` : " after the trial"} unless you cancel before` : ""}.`
667
+ : `Builder${price ? `: ${price}` : ""}. The free trial was already used.`,
668
+ );
669
+ const tty = !flags.yes && (ctx.interactive ?? interactive(flags));
670
+ if (tty && flags.browser !== false) {
671
+ const yes = await (ctx.confirm ?? confirm)("Open checkout in your browser?", { opts: flags });
672
+ if (yes && (ctx.openBrowser ?? openBrowser)(offer.url, flags, server)) {
673
+ out.ok("Opened checkout in your browser.");
674
+ return true;
675
+ }
676
+ }
677
+ out.line(` Checkout: ${c.cyan(offer.url)}`);
678
+ return false;
679
+ }
680
+
514
681
  async function setupAgents(flags, ctx, { mcpUrl, apiKey }) {
515
682
  const detected = await detectAgents(ctx.cwd, ctx.env);
516
683
  let chosen;
@@ -542,10 +709,12 @@ async function setupAgents(flags, ctx, { mcpUrl, apiKey }) {
542
709
  out.note(
543
710
  "No agent configured. Settings → Agents in the web app has the snippets.",
544
711
  );
545
- return { usedEnv: false, plugin: false };
712
+ return { usedEnv: false, plugin: false, connected: 0 };
546
713
  }
547
714
  let usedEnv = false,
548
- plugin = false;
715
+ plugin = false,
716
+ // Agents configured without an error (manual grok-bot/other instructions don't count).
717
+ connected = 0;
549
718
  for (const a of chosen) {
550
719
  try {
551
720
  if (a === "claude") {
@@ -586,6 +755,7 @@ async function setupAgents(flags, ctx, { mcpUrl, apiKey }) {
586
755
  if (pinned === "bumped")
587
756
  out.ok(`Claude Code: .mcp.json now starts ${BRIDGE_PACKAGE}.`);
588
757
  plugin = true;
758
+ connected++;
589
759
  continue;
590
760
  }
591
761
  out.warn(`Claude Code plugin: ${r.message}`);
@@ -678,6 +848,7 @@ async function setupAgents(flags, ctx, { mcpUrl, apiKey }) {
678
848
  );
679
849
  } else out.note("Skipped AGENTS.md.");
680
850
  }
851
+ if (a !== "grok-bot" && a !== "other") connected++;
681
852
  } catch (e) {
682
853
  out.warn(`${AGENTS[a]}: ${e.message}`);
683
854
  out.note(
@@ -685,10 +856,10 @@ async function setupAgents(flags, ctx, { mcpUrl, apiKey }) {
685
856
  );
686
857
  }
687
858
  }
688
- return { usedEnv, plugin };
859
+ return { usedEnv, plugin, connected };
689
860
  }
690
861
 
691
- async function ownership(flags, ctx, { server, site, token, app }) {
862
+ async function ownership(flags, ctx, { server, site, token, app, noPlan = false }) {
692
863
  const method =
693
864
  flags.ownership ||
694
865
  (await choose(
@@ -725,9 +896,11 @@ async function ownership(flags, ctx, { server, site, token, app }) {
725
896
  throw new CliError(
726
897
  `Unknown ownership method "${method}". Use file, search-console or skip.`,
727
898
  );
728
- out.note(
729
- "Foundation checks and missions work now; production verification follows ownership.",
730
- );
899
+ // Without a plan, missions and verification come with the trial: the ending says so once.
900
+ if (!noPlan)
901
+ out.note(
902
+ "Foundation checks and missions work now; production verification follows ownership.",
903
+ );
731
904
  }
732
905
 
733
906
  const tilde = (p, env) => {
@@ -740,27 +913,46 @@ const tilde = (p, env) => {
740
913
  export async function check(previewUrl, flags, ctx = context()) {
741
914
  if (!previewUrl)
742
915
  throw new CliError(
743
- "Usage: serpkin check <preview-or-production-url> [--site <id>] [--paths /,/pricing] [--json]",
916
+ "Usage: serpkin check <preview-or-production-url | http://localhost:PORT> [--site <id>] [--paths /,/pricing] [--allow-host] [--json]",
744
917
  );
745
918
  const url = previewAddress(previewUrl);
746
919
  if (!url)
747
920
  throw new CliError(
748
- `"${String(previewUrl).slice(0, 120)}" isn't a preview URL. Pass the full address of the deployment, for example https://my-branch.vercel.app.`,
921
+ `"${String(previewUrl).slice(0, 120)}" isn't a preview URL. Pass the full address of the deployment, for example https://my-branch.vercel.app, or a local build such as http://localhost:3000.`,
749
922
  );
750
923
  const { project, api } = await session(flags, ctx);
751
- const siteId = flags.site || ctx.env.SERPKIN_SITE_ID || project?.site_id || (await siteForUrl(api, url));
924
+ const local = isLocal(url);
925
+ const siteId = flags.site || ctx.env.SERPKIN_SITE_ID || project?.site_id || (await siteForUrl(api, url, { local }));
752
926
  const paths = flags.paths
753
927
  ? flags.paths
754
928
  .split(",")
755
929
  .map((p) => p.trim())
756
930
  .filter(Boolean)
757
931
  : undefined;
758
- if (!flags.json) out.step(`Checking ${url} against production…`);
759
- const r = await api.post("/api/check", {
760
- site_id: siteId,
761
- preview_url: url,
762
- ...(paths ? { paths } : {}),
763
- });
932
+ if (flags["allow-host"]) {
933
+ if (local) throw new CliError("--allow-host is for public preview hosts. Local builds need no permission: they are read on this machine.");
934
+ const host = new URL(url).hostname;
935
+ const r = await api.post("/api/sites/preview-hosts", { site_id: siteId, add: host });
936
+ if (!flags.json) out.ok(`Previews on ${host} are now allowed for this site (${r.preview_hosts.join(", ")}).`);
937
+ }
938
+ let r;
939
+ if (local) {
940
+ if (!flags.json) out.step(`Reading ${new URL(url).origin} on this machine, then comparing it with production…`);
941
+ r = await localCheck(api, {
942
+ siteId,
943
+ url,
944
+ paths,
945
+ fetchImpl: ctx.localFetch ?? ctx.fetchImpl,
946
+ onRead: (n) => !flags.json && out.note(`Reading ${n} page${n === 1 ? "" : "s"} plus robots.txt and the sitemap locally.`),
947
+ });
948
+ } else {
949
+ if (!flags.json) out.step(`Checking ${url} against production…`);
950
+ r = await api.post("/api/check", {
951
+ site_id: siteId,
952
+ preview_url: url,
953
+ ...(paths ? { paths } : {}),
954
+ });
955
+ }
764
956
  if (flags.json) {
765
957
  process.stdout.write(JSON.stringify(r, null, 2) + "\n");
766
958
  return r.status === "pass" ? 0 : 1;
@@ -772,9 +964,18 @@ export async function check(previewUrl, flags, ctx = context()) {
772
964
  * Without --site or ${PROJECT_FILE}: the registered site whose origin is the checked URL (checking production
773
965
  * itself is fine), else the workspace's only site. Several sites and no match: name them.
774
966
  */
775
- async function siteForUrl(api, url) {
967
+ async function siteForUrl(api, url, { local = false } = {}) {
776
968
  const { items = [] } = await api.get("/api/records?kind=site&limit=100");
777
969
  const origin = new URL(url).origin;
970
+ // A local build has no registered origin to match: only a workspace with one site is unambiguous.
971
+ if (local) {
972
+ if (items.length === 1) return items[0].id;
973
+ throw new CliError(
974
+ items.length
975
+ ? `Which site is this local build? Pass --site <id>: ${items.slice(0, 5).map((s) => `${s.origin} (${s.id})`).join(", ")}. Or run \`npx serpkin init\` here to write ${PROJECT_FILE}.`
976
+ : "No site registered yet. Run `npx serpkin init` in this repository first.",
977
+ );
978
+ }
778
979
  const bare = (o) => String(o ?? "").replace(/^https?:\/\/(www\.)?/i, "");
779
980
  const match = items.find((s) => s.origin === origin) ?? items.find((s) => bare(s.origin) === bare(origin));
780
981
  if (match) return match.id;
@@ -790,9 +991,10 @@ export function previewAddress(input) {
790
991
  const s = String(input ?? "").trim();
791
992
  if (!s || /\s/.test(s)) return null;
792
993
  // A scheme-less "host[:port][/path]" gets https://; anything else with a scheme must be http(s).
793
- const withScheme = /^[a-z][a-z0-9+.-]*:/i.test(s) && !/^[^/:]+:\d+(\/|$)/.test(s)
794
- ? s
795
- : `https://${s}`;
994
+ const schemeless = !(/^[a-z][a-z0-9+.-]*:/i.test(s) && !/^[^/:]+:\d+(\/|$)/.test(s));
995
+ // A bare local address ("localhost:3000") is a dev or preview server: plain http.
996
+ const localBare = schemeless && /^(localhost|127\.[\d.]+|0\.0\.0\.0|\[::1\]|[^/:]+\.local(host)?)(:\d+)?(\/|$)/i.test(s);
997
+ const withScheme = schemeless ? `${localBare ? "http" : "https"}://${s}` : s;
796
998
  let u;
797
999
  try {
798
1000
  u = new URL(withScheme);
@@ -806,6 +1008,12 @@ export function previewAddress(input) {
806
1008
 
807
1009
  export function printCheck(r) {
808
1010
  out.line();
1011
+ if (r.mode === "local")
1012
+ out.line(
1013
+ c.dim(
1014
+ `Pre-deploy check: ${r.preview_origin} (read on this machine) compared with ${r.production_origin}. Not production verification.`,
1015
+ ),
1016
+ );
809
1017
  if (r.regressions.length) {
810
1018
  out.line(
811
1019
  c.bold(
@@ -836,11 +1044,18 @@ export function printCheck(r) {
836
1044
  }
837
1045
  out.line();
838
1046
  const n = r.checked_paths.length;
1047
+ const pages = `${n} page${n === 1 ? "" : "s"}`;
1048
+ if (r.mode === "local") {
1049
+ if (r.status === "pass") out.ok(`No SEO regressions on the local build across ${pages}.`);
1050
+ else out.fail(`Found regressions on the local build (${pages} checked). Fix them before deploying.`);
1051
+ out.note("After the deploy, check production (`npx serpkin check <production-url>`) and verify the mission with the environment its verify step names (\"production\" for technical fixes, \"evidence\" for links and content).");
1052
+ return;
1053
+ }
839
1054
  if (r.status === "pass")
840
- out.ok(`No SEO regressions across ${n} page${n === 1 ? "" : "s"}.`);
1055
+ out.ok(`No SEO regressions across ${pages}.`);
841
1056
  else
842
1057
  out.fail(
843
- `Found regressions on the preview (${n} page${n === 1 ? "" : "s"} checked).`,
1058
+ `Found regressions on the preview (${pages} checked).`,
844
1059
  );
845
1060
  }
846
1061
 
@@ -895,6 +1110,11 @@ export async function status(flags, ctx = context()) {
895
1110
  // CreditState {plan_total, used, reserved, remaining, resets_at} when the server exposes it.
896
1111
  const credits = state?.credits ?? null;
897
1112
  const included = state?.limits?.credits ?? null;
1113
+ // No plan (trial mode): the preview's first mission (or clean preview) and the one trial offer, shown once.
1114
+ const offer = trialOfferFrom(next);
1115
+ const preview = offer && !mission ? (next?.preview_mission ?? null) : null;
1116
+ const clean = offer && !mission && !preview ? (next?.preview_clean ?? null) : null;
1117
+ const noPlan = !!offer || state?.billing?.no_plan === true;
898
1118
  const LEVELS = {
899
1119
  search_console: "Search Console connected",
900
1120
  estimated: "Established (estimated rankings)",
@@ -917,11 +1137,18 @@ export async function status(flags, ctx = context()) {
917
1137
  : []),
918
1138
  [
919
1139
  "Next mission",
920
- mission?.title ??
921
- c.dim(
922
- next?.suggested_action ??
923
- "none ready yet; ask your agent to scan the site",
924
- ),
1140
+ mission?.title
1141
+ ? cleanLine(mission.title, 200)
1142
+ : preview
1143
+ ? `${cleanLine(preview.title, 120)}${typeof preview.position === "number" && preview.position >= 1 ? c.dim(` (#${Math.round(preview.position)} today)`) : ""} ${c.dim(`(preview; ${offer.trial_available ? `the ${offer.trial_days}-day trial` : "a plan"} unlocks the brief)`)}`
1144
+ : clean
1145
+ ? c.dim(`none: the preview found nothing to fix in ${plural(Number(clean.pages_checked) || 0, "page")}${clean.pages_not_checked ? ` (${plural(clean.pages_not_checked, "page")} not checked yet)` : ""}`)
1146
+ : offer
1147
+ ? c.dim("none yet; the preview scan picks the first one")
1148
+ : c.dim(
1149
+ cleanLine(next?.suggested_action, 600) ||
1150
+ "none ready yet; ask your agent to scan the site",
1151
+ ),
925
1152
  ],
926
1153
  [
927
1154
  "Plan",
@@ -932,7 +1159,12 @@ export async function status(flags, ctx = context()) {
932
1159
  : state.billing.plan_label
933
1160
  : (state?.project?.plan ?? "—"),
934
1161
  ],
935
- ...(credits
1162
+ ...(offer?.url
1163
+ ? [["Checkout", `${c.cyan(offer.url)} ${c.dim(offer.trial_available ? `(${offer.trial_days}-day free trial, card required)` : "(the free trial was already used)")}`]]
1164
+ : []),
1165
+ ...(noPlan
1166
+ ? []
1167
+ : credits
936
1168
  ? [
937
1169
  [
938
1170
  "Credits",
@@ -950,6 +1182,7 @@ export async function status(flags, ctx = context()) {
950
1182
  site: s,
951
1183
  level,
952
1184
  next_mission: mission,
1185
+ ...(offer ? { preview_mission: next?.preview_mission ?? null, preview_clean: next?.preview_clean ?? null, trial_offer: next?.trial_offer ?? offer } : {}),
953
1186
  credits,
954
1187
  plan: state?.project?.plan ?? null,
955
1188
  },
@@ -965,25 +1198,32 @@ export async function status(flags, ctx = context()) {
965
1198
 
966
1199
  /* ─────────────────────────────── routes ─────────────────────────────── */
967
1200
 
1201
+ /**
1202
+ * The registered site this repository serves, for a repository without .serpkin.json: the only site in the
1203
+ * workspace, or the one whose origin is the app's package.json homepage. Otherwise name them.
1204
+ */
1205
+ async function registeredSite(api, app) {
1206
+ const { items = [] } = await api.get("/api/records?kind=site&limit=100");
1207
+ const bare = (o) => String(o ?? "").replace(/^https?:\/\/(www\.)?/i, "").replace(/\/+$/, "");
1208
+ const home = app?.homepage ? normalizeUrl(app.homepage) : null;
1209
+ const match = home ? items.find((s) => bare(s.origin) === bare(home)) : null;
1210
+ if (match) return match;
1211
+ if (items.length === 1) return items[0];
1212
+ throw new CliError(
1213
+ items.length
1214
+ ? `Which site is this repository? Pass --site <id>: ${items.slice(0, 5).map((s) => `${s.origin} (${s.id})`).join(", ")}.`
1215
+ : "No site registered yet. Run `npx serpkin init` in this repository first.",
1216
+ );
1217
+ }
968
1218
  export async function routes(flags, ctx = context()) {
969
1219
  const apps = await detectApps(ctx.cwd);
970
1220
  const project = await loadProject(ctx.cwd);
971
- const app = flags.app
972
- ? apps.find((a) => a.root === appRoot(flags.app))
973
- : apps.length === 1
974
- ? apps[0]
975
- : null;
976
- if (flags.app && !app)
977
- throw new CliError(
978
- `No supported app found at ${flags.app}.${apps.length ? ` Apps here: ${apps.map((a) => (a.root === "." ? "./" : a.root)).join(", ")}` : ""}`,
979
- );
1221
+ const app = await pickApp(apps, flags, project);
980
1222
  if (!app)
981
1223
  throw new CliError(
982
- apps.length
983
- ? `Found ${apps.length} apps (${apps.map((a) => a.root).join(", ")}). Pass --app <dir>.`
984
- : "No supported framework found in this directory.",
1224
+ "No supported framework found in this directory. Run this at the repository root, or pass --app <dir> for the website's folder (Next.js, Astro, SvelteKit, Nuxt or Remix).",
985
1225
  );
986
- const map = await buildRouteMap(app, ctx.cwd);
1226
+ const map = await buildRouteMap(app, await repoBase(ctx.cwd));
987
1227
  if (flags.json) process.stdout.write(JSON.stringify(map, null, 2) + "\n");
988
1228
  else {
989
1229
  out.line(
@@ -999,12 +1239,30 @@ export async function routes(flags, ctx = context()) {
999
1239
  );
1000
1240
  }
1001
1241
  if (flags.upload) {
1002
- const { api } = await session(flags, ctx);
1003
- const siteId = siteIdFrom(flags, project, ctx.env);
1242
+ const { api, server } = await session(flags, ctx);
1243
+ // No .serpkin.json: the site is usually registered already (from the web app or MCP). Find it, so the upload
1244
+ // also links this repository.
1245
+ const known = flags.site || ctx.env.SERPKIN_SITE_ID || project?.site_id;
1246
+ const site = known ? null : await registeredSite(api, app);
1247
+ const siteId = known || site.id;
1004
1248
  const { truncated, ...body } = map;
1005
1249
  await api.post("/api/cli/sites/route-map", { site_id: siteId, ...body });
1006
- if (!flags.json) out.ok("Route map uploaded.");
1250
+ if (!project) {
1251
+ // Link the repository: .serpkin.json names the server and site (no secrets), so hooks, `serpkin check` and
1252
+ // the next `routes --upload` need no flags.
1253
+ const origin = site?.origin ?? (await api.get("/api/records?kind=site&limit=100").then((r) => r.items?.find((x) => x.id === siteId)?.origin, () => null));
1254
+ const link =
1255
+ !interactive(flags) ||
1256
+ (await confirm(`Link this repository to ${origin ?? siteId}? It writes ${PROJECT_FILE} (no secrets).`, { opts: flags }));
1257
+ if (link) {
1258
+ await saveProject(ctx.cwd, { server, site_id: siteId, ...(origin ? { origin } : {}), ...(app.root !== "." ? { app: app.root } : {}) });
1259
+ if (!flags.json) out.ok(`Linked this repository to ${origin ?? siteId} (${PROJECT_FILE} saved; commit it).`);
1260
+ }
1261
+ } else if (app.root !== "." && project.app !== app.root && project.site_id === siteId)
1262
+ // Remember the monorepo app, so the next run (and init) picks it without --app.
1263
+ await saveProject(ctx.cwd, { ...project, app: app.root });
1264
+ if (!flags.json) out.ok(`Route map uploaded (${map.routes.length} routes). Missions now name this repository's files.`);
1007
1265
  } else if (!flags.json)
1008
- out.note("Run `serpkin routes --upload` to send this to Serpkin.");
1266
+ out.note(`Run \`serpkin routes --upload${flags.app ? ` --app ${appRoot(flags.app)}` : ""}\` to send this to Serpkin.`);
1009
1267
  return 0;
1010
1268
  }