@zero2webmaster/starter-kit 0.5.7 → 0.6.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/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # z2w-starter-kit
2
2
 
3
- **Version:** 0.5.7 | **Framework:** 2.13.0
3
+ **Version:** 0.6.0 | **Framework:** 2.13.0
4
4
 
5
5
  > Node CLI to scaffold new Z2W projects from canonical Templates + AGENTS.md.
6
6
 
@@ -99,4 +99,4 @@ For licensing inquiries: kerry@zero2webmaster.com.
99
99
  ---
100
100
 
101
101
  *Scaffolded 2026-05-28 via the [[instantiate-z2w-project]] Claude Code skill v1; reconciled against the consolidated skill v1.1.0 (brief-first + Agent Coordination block) on 2026-05-29.*
102
- *Version: 0.5.7 | Last Updated: 2026-07-27*
102
+ *Version: 0.6.0 | Last Updated: 2026-07-30*
package/dist/index.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { writeScaffold } from "./writer.js";
2
2
  import type { ScaffoldFile } from "./scaffolders/common.js";
3
3
  import type { StandardDecision } from "./standards.js";
4
- export declare const version = "0.5.7";
4
+ export declare const version = "0.6.0";
5
5
  export type ProjectType = "wp-plugin" | "cf-worker" | "cf-pages" | "nextjs" | "python-service" | "node-service" | "library" | "protocol-repo";
6
6
  export type BrandPreset = "save-the-frogs" | "bansuri-bliss" | "zero2webmaster" | "custom";
7
7
  export type DbStrategy = "none" | "neon-postgres" | "supabase" | "sqlite" | "mysql-wp" | "other";
@@ -112,6 +112,33 @@ export interface ScaffoldInputs {
112
112
  * failed silently" surface.
113
113
  */
114
114
  hasObservability?: boolean;
115
+ /**
116
+ * Whether the incoming `Host` header selects the tenant — a HOST-ROUTED
117
+ * multi-tenant app, where each tenant has its own front door (its own custom
118
+ * domain) served by one deployment. True for `org-hq`, `site-control`,
119
+ * `z2w-member-match`; false for a single-tenant app that has exactly one
120
+ * canonical domain.
121
+ *
122
+ * When `true`, the `nextjs` scaffolder changes two things:
123
+ *
124
+ * 1. **`next.config.mjs` omits the `*.vercel.app` → custom-domain alias
125
+ * redirect.** That redirect assumes ONE canonical destination, which is
126
+ * precisely what a host-routed app does not have — redirecting an alias to a
127
+ * fixed host drops visitors into some other tenant's app.
128
+ * 2. **A `middleware.ts` host guard is emitted instead**, which returns **404**
129
+ * for a production request on a known-non-canonical host. Per the 2026-07-30
130
+ * ruling (reached across `org-hq`, `site-control` and `z2w-member-match`):
131
+ * **404 on an unmapped Host, never a redirect to a fixed one.**
132
+ *
133
+ * It also emits the `CANONICAL_HOSTS` allowlist stub in `.env.example`, since a
134
+ * Host-routed app needs to know which hosts are legitimately its own.
135
+ *
136
+ * Optional and defaults to `false` (single-tenant — the alias redirect ships as
137
+ * before). Honored only by the `nextjs` type; other types have no Host-based
138
+ * routing surface. Deliberately opt-in on the `--input` / programmatic paths so
139
+ * an existing caller's output is unchanged.
140
+ */
141
+ hostRoutedTenancy?: boolean;
115
142
  /** Present only when `brand === "custom"`. */
116
143
  customBrand?: CustomBrandInputs;
117
144
  /**
package/dist/index.js CHANGED
@@ -21,7 +21,7 @@ import * as path from "node:path";
21
21
  import { Writable } from "node:stream";
22
22
  import { isValidSlug } from "./parse-brief.js";
23
23
  import { writeScaffold } from "./writer.js";
24
- export const version = "0.5.7";
24
+ export const version = "0.6.0";
25
25
  // Canonical enum value-arrays. These live here, next to the type unions they
26
26
  // enumerate, so both the CLI's confirm/wizard flows (which re-export them) and
27
27
  // the programmatic `validateScaffoldInputs` share one source of truth. Keep
@@ -238,6 +238,7 @@ export function scaffoldCfPages(inputs, opts) {
238
238
  { path: "_headers", content: sub(HEADERS_TEMPLATE, inputs, opts, spec) },
239
239
  { path: "_redirects", content: sub(REDIRECTS_TEMPLATE, inputs, opts, spec) },
240
240
  { path: "public/og-image.txt", content: OG_IMAGE_PLACEHOLDER },
241
+ { path: "health.json", content: HEALTH_JSON_TEMPLATE },
241
242
  {
242
243
  path: "SEO-CHECKLIST.md",
243
244
  content: sub(SEO_CHECKLIST_TEMPLATE, inputs, opts, spec),
@@ -245,6 +246,33 @@ export function scaffoldCfPages(inputs, opts) {
245
246
  ];
246
247
  return [...base, ...typeSpecific];
247
248
  }
249
+ /**
250
+ * Static health document for a purely static Pages deploy.
251
+ *
252
+ * `cf-pages` is a Kuma deploy target, but it has no server, so it had no
253
+ * `/health` for the Uptime Kuma standard to point at — the block said "point at
254
+ * `/health`, never the main URL" and there was nothing there. That gap is how a
255
+ * bare-`ok` keyword monitor gets invented: an agent with no health document
256
+ * points Kuma at `index.html` and picks a keyword out of the page, and `ok`
257
+ * substring-matches inside *cookie / lookup / blocked* on a 200-returning error
258
+ * page. Shipping the document makes the standard's keyword (`"status":"ok"`)
259
+ * true for all five deploy targets instead of four.
260
+ *
261
+ * Deliberately NOT substituted: the body must be byte-stable so the keyword
262
+ * match can never depend on a brand or slug value. Added 2026-07-30 alongside
263
+ * the keyword mirror from `cursor-project-templates`.
264
+ *
265
+ * ⚠️ COMPACT JSON, no space after the colon — this is load-bearing and looks
266
+ * like a formatting nit. Kuma's keyword check is a literal case-sensitive
267
+ * substring match, and the standard's keyword is `"status":"ok"`. Every OTHER
268
+ * project type gets this for free because it serializes at runtime
269
+ * (`NextResponse.json` / `c.json` / `Response.json` / FastAPI all emit compact
270
+ * JSON), but a static file is served byte-for-byte as written. Prettifying this
271
+ * to `{ "status": "ok" }` would break every monitor pointed at it — and only at
272
+ * the moment the monitor was supposed to help.
273
+ */
274
+ const HEALTH_JSON_TEMPLATE = `{"status":"ok"}
275
+ `;
248
276
  /**
249
277
  * Canonical SEO baseline file list for cf-pages. Exported for tests + the
250
278
  * Step 5 standards resolver.
@@ -764,23 +764,75 @@ export function commonDirective(inputs, opts, spec) {
764
764
  * (contact-registry, 2026-07-12). Ignoring it gives every
765
765
  * generated tree a clean `git status` — every file either
766
766
  * tracked or ignored, nothing present-but-untracked.
767
- * - `.claude/settings.local.json` — Claude Code's MACHINE-LOCAL settings
768
- * (per-machine permission allowlists, which routinely name
769
- * absolute paths and one-off commands). Its sibling
770
- * `.claude/settings.json` is the SHARED project settings file
771
- * and must stay committable — so ignore the one file, never
772
- * the whole `.claude/` directory. Added 2026-07-26 after
773
- * `audit-engine`'s first sweep found it missing in 11 of 12
774
- * Live repos. Kerry's machine happens to be covered by a
775
- * global ignore (`~/.config/git/ignore`), but a global ignore
776
- * does not travel with the repo — CI, a second machine, a
777
- * contractor, or a licensee gets no protection at all. The
778
- * repo-level line is the one that ships.
767
+ * - `.claude/settings.local.json` AND `.claude/settings.json` — BOTH of Claude
768
+ * Code's harness-written settings files. `settings.local.json`
769
+ * was added 2026-07-26 after `audit-engine`'s first sweep
770
+ * found it missing in 11 of 12 Live repos (Kerry's machine is
771
+ * covered by a global `~/.config/git/ignore`, which does not
772
+ * travel with the clone, so CI / a second machine / a
773
+ * licensee got nothing — the repo-level line is the one that
774
+ * ships).
775
+ *
776
+ * ⚠️ `settings.json` was DELIBERATELY EXCLUDED in v0.5.4 on
777
+ * the reasoning that it is "the SHARED project settings file
778
+ * and must stay committable." **That decision is reversed as
779
+ * of v0.5.8, and the reversal is evidence-driven.** Four
780
+ * independent reports in six days, from four projects:
781
+ * · `site-control` (2026-07-28) — Claude Code wrote a live
782
+ * Neon PASSWORD into it three times; they untracked it
783
+ * and ship a curated `settings.example.json` instead.
784
+ * · `file-server` (2026-07-30) — 44 entries, 42 of them
785
+ * uncommitted junk (frozen version literals, `perl -0pi`
786
+ * one-liners); left out of every commit, "only growing."
787
+ * · `z2w-crowdcommerce` (2026-07-25) — credential-shaped
788
+ * `-uroot -proot` text in the tracked file.
789
+ * · this repo (2026-07-25) — 16 junk entries discarded,
790
+ * including a standing `GH_SKIP_ACCOUNT_CHECK=1` push.
791
+ *
792
+ * The decisive fact is structural rather than statistical:
793
+ * **this scaffolder emits no `.claude/` file at all, and
794
+ * neither does any other Z2W tool.** So the file the old rule
795
+ * protected as human-curated shared config is, in every repo
796
+ * that has one, written 100% by the harness. Tracking a
797
+ * machine-mutated file guarantees a permanently dirty tree
798
+ * and invites exactly the secret-commit it was supposed to
799
+ * prevent. Ignoring it strands nothing, because nothing
800
+ * deliberate was ever put there.
801
+ *
802
+ * Both are pinned as FILES, not as `.claude/`, and that is
803
+ * load-bearing: project-scoped subagents (`.claude/agents/`),
804
+ * hooks, skills, and a hand-curated
805
+ * `.claude/settings.example.json` ARE deliberately authored
806
+ * and must keep travelling with the repo.
807
+ * - `.vscode/` — editor/extension-local settings, same class as
808
+ * `.specstory/` above and created by the same tooling (the
809
+ * file `site-control` nearly committed on 2026-07-28 was
810
+ * literally a SpecStory extension preference). Ignoring the
811
+ * directory rather than one file because there is no sibling
812
+ * that must stay tracked — contrast `.claude/` above, where
813
+ * there is, which is why that one is pinned to a single file.
814
+ * - `.env.*` + `!.env.example` — the whole OTHER-env-file family. `.env`
815
+ * (exact) and `.env*.local` match neither
816
+ * `.env.sentry-build-plugin` (where the Sentry CLI writes
817
+ * SENTRY_AUTH_TOKEN, the credential that authorises
818
+ * source-map upload) nor Next.js's own `.env.production` /
819
+ * `.env.development`. Reported by `site-control` 2026-07-29
820
+ * against the Sentry filename specifically; fixed as the
821
+ * class, because chasing one tool-written filename per
822
+ * incident is a treadmill and the next tool will pick a name
823
+ * we have not seen. `.env.example` is negated LAST so it
824
+ * stays tracked — it carries variable NAMES only.
779
825
  *
780
826
  * Per the 2026-06-11 z2w-member-match near-miss (live DATABASE_URL +
781
827
  * RESEND_API_KEY staged on a fresh repo) and matching asks from
782
828
  * videomigrator-dashboard (2026-06-07). Centralized here so no per-type body
783
829
  * can ever omit it.
830
+ *
831
+ * The load-bearing distinction when adding an entry here: **broaden to the
832
+ * family when nothing in it must stay tracked; pin to one file when a sibling
833
+ * must.** A wildcard is safer for `.env.*` (an unignored secret file is the
834
+ * failure) and actively wrong for `.claude/` (ignoring it strands the shared
835
+ * `settings.json`).
784
836
  */
785
837
  const GITIGNORE_SECRET_SCRATCH_BLOCK = `
786
838
  # Scratch / intermediates (Z2W convention) — never commit
@@ -789,9 +841,26 @@ const GITIGNORE_SECRET_SCRATCH_BLOCK = `
789
841
  .specstory/
790
842
  # Cursor's own index-management file — local, auto-created; keeps git status clean
791
843
  .cursorindexingignore
792
- # Claude Code machine-local settings (permission allowlists, absolute paths).
793
- # NOTE: .claude/settings.json is the SHARED project file — keep it committable.
844
+ # Editor/extension-local settings — created unbidden, nobody's project config.
845
+ # If a shared setting is ever genuinely wanted, force-add the ONE narrow file
846
+ # (e.g. \`git add -f .vscode/extensions.json\`).
847
+ .vscode/
848
+ # Claude Code's HARNESS-WRITTEN settings. Neither file is authored by a human
849
+ # or by the scaffolder — the harness appends one-off permission approvals to
850
+ # them all session (frozen version literals, one-off in-place edits, absolute
851
+ # per-boot paths), so a tracked copy is permanently dirty and has been observed
852
+ # receiving a live database password.
853
+ # Deliberately-authored project config under .claude/ still travels: agents/,
854
+ # hooks/, skills/, and a curated settings.example.json are NOT ignored.
855
+ .claude/settings.json
794
856
  .claude/settings.local.json
857
+ # Every OTHER .env variant holds real values — close the whole family rather
858
+ # than chasing one filename at a time. \`.env\` (exact) and \`.env*.local\` above
859
+ # do NOT match tool-written names like \`.env.sentry-build-plugin\` (where the
860
+ # Sentry CLI writes SENTRY_AUTH_TOKEN) or Next.js's \`.env.production\`.
861
+ # \`.env.example\` is re-allowed: it carries variable NAMES only, never values.
862
+ .env.*
863
+ !.env.example
795
864
  `;
796
865
  /**
797
866
  * Per-type `.gitignore` body. Sources: skill's "Inline mini-templates"
@@ -6,4 +6,4 @@ export declare function scaffoldNextjs(inputs: ScaffoldInputs, opts?: Scaffolder
6
6
  * they can assert / require the canonical SEO baseline file list without
7
7
  * hardcoding the paths in two places.
8
8
  */
9
- export declare const NEXTJS_SEO_BASELINE_PATHS: readonly ["app/layout.tsx", "app/page.tsx", "app/sitemap.ts", "app/robots.ts", "app/opengraph-image.tsx", "lib/analytics/utm.ts", "lib/analytics/Analytics.tsx", "lib/analytics/RouteTracker.tsx", "SEO-CHECKLIST.md", ".env.example"];
9
+ export declare const NEXTJS_SEO_BASELINE_PATHS: readonly ["app/layout.tsx", "app/page.tsx", "app/sitemap.ts", "app/robots.ts", "lib/seo/canonical-host.mjs", "app/opengraph-image.tsx", "lib/analytics/utm.ts", "lib/analytics/Analytics.tsx", "lib/analytics/RouteTracker.tsx", "SEO-CHECKLIST.md", ".env.example"];
@@ -11,8 +11,12 @@
11
11
  // descriptive alt where appropriate (placeholder content uses semantic
12
12
  // HTML; no decorative images at scaffold time).
13
13
  // 5. JSON-LD — `Organization` schema injected in app/layout.tsx.
14
- // 6. sitemap.xml + robots.txt — app/sitemap.ts + app/robots.ts; preview
15
- // noindex gated on `VERCEL_ENV !== 'production'`.
14
+ // 6. sitemap.xml + robots.txt — app/sitemap.ts + app/robots.ts. Indexable
15
+ // requires BOTH `VERCEL_ENV === 'production'` AND a real canonical domain
16
+ // (not the *.example.com placeholder, not *.vercel.app) — gating on
17
+ // VERCEL_ENV alone published `Allow: /` with placeholder sitemap URLs on the
18
+ // first prod deploy. Predicate lives in lib/seo/canonical-host.mjs, shared
19
+ // with next.config.mjs so robots and the alias redirect cannot disagree.
16
20
  // 7. Fathom — the three-file pattern under lib/analytics/ (utm.ts +
17
21
  // Analytics.tsx + RouteTracker.tsx), mounted as <Analytics /> in
18
22
  // app/layout.tsx, gated on `NEXT_PUBLIC_FATHOM_SITE_ID` (per
@@ -25,6 +29,18 @@
25
29
  // next.config.mjs that redirects the production *.vercel.app alias to the
26
30
  // custom domain (SEO-duplicate fix — Z2W heads-up 2026-06-29; self-disabling
27
31
  // until NEXT_PUBLIC_SITE_URL is a real custom domain).
32
+ //
33
+ // Conditional on `hostRoutedTenancy` (a HOST-ROUTED multi-tenant app, where the
34
+ // Host selects the tenant): the single-destination alias redirect is OMITTED —
35
+ // wrong shape, there is no one canonical domain — and a `middleware.ts` host
36
+ // guard is emitted that returns **404** on a known-non-canonical production host.
37
+ // Ruling 2026-07-30 across org-hq / site-control / z2w-member-match: 404 on an
38
+ // unmapped Host, never a redirect to a fixed one.
39
+ //
40
+ // Conditional on `sendsEmail` or `hostRoutedTenancy`: a `CANONICAL_HOSTS`
41
+ // allowlist stub in `.env.example`. This CLI emits no auth code, so it plants the
42
+ // seam + the pointer at [[z2w-magic-link-auth]] §0 rule 2b rather than a check —
43
+ // see CANONICAL_HOSTS_ENV_BLOCK for why that is the honest half.
28
44
  import { commonBaseFiles, EMAIL_DEPS, EMAIL_ENV_BLOCK, emailFiles, localEnvFrom, resolveBrandSpec, sub, } from "./common.js";
29
45
  const NARRATIVE = `## What this is
30
46
 
@@ -44,8 +60,9 @@ npm run build && npm start # production build
44
60
  - \`app/layout.tsx\` — root \`metadata\` with \`title.template\`, \`title.default\`, \`description\`, \`openGraph\`, \`twitter\`, \`metadataBase\`; mounts \`<Analytics />\`; JSON-LD Organization schema.
45
61
  - \`app/page.tsx\` — per-page \`metadata\` (unique title + description; never inherit defaults); exactly one \`<h1>\`; semantic HTML.
46
62
  - \`lib/analytics/{utm.ts,Analytics.tsx,RouteTracker.tsx}\` — Fathom (per [[fathom-analytics]]); the RouteTracker fires \`trackPageview()\` on route change + captures first-touch UTM. Gated on \`NEXT_PUBLIC_FATHOM_SITE_ID\`.
47
- - \`app/sitemap.ts\` — sitemap generator; lists indexable pages.
48
- - \`app/robots.ts\` — robots generator; preview/staging emits \`noindex\` (gated on \`VERCEL_ENV !== 'production'\`).
63
+ - \`app/sitemap.ts\` — sitemap generator; lists indexable pages. \`lastModified\` is deliberately omitted until you have a real content timestamp.
64
+ - \`app/robots.ts\` — robots generator. Indexable requires BOTH a production deployment AND a real canonical domain in \`NEXT_PUBLIC_SITE_URL\`; anything else emits \`Disallow: /\`. **Both files are prerendered at build time, so changing \`NEXT_PUBLIC_SITE_URL\` needs a redeploy.**
65
+ - \`lib/seo/canonical-host.mjs\` — the one canonical-host predicate, shared by \`app/robots.ts\` and \`next.config.mjs\` so the indexability gate and the alias redirect cannot disagree.
49
66
  - \`app/opengraph-image.tsx\` — default OG image (replace placeholder before launch).
50
67
  - \`SEO-CHECKLIST.md\` — per-page checklist; consult before adding new pages.
51
68
 
@@ -80,8 +97,76 @@ const PACKAGE_JSON_TEMPLATE = `{
80
97
  "homepage": "https://github.com/{{github_org}}/{{slug}}"
81
98
  }
82
99
  `;
100
+ /**
101
+ * ONE definition of "is this host a real canonical domain?", shared by
102
+ * `next.config.mjs` (the alias redirect) and `app/robots.ts` (the indexability
103
+ * gate). Emitted as `.mjs` on purpose: `next.config.mjs` is plain ESM loaded
104
+ * before any TypeScript exists, so it cannot import a `.ts` module — while the
105
+ * scaffolded `tsconfig.json` sets `allowJs: true`, so `app/robots.ts`
106
+ * type-checks this same file and picks up its JSDoc types. Two copies would let
107
+ * robots.txt say "index me" while the alias redirect is off — the single most
108
+ * invisible drift available in this file family (`site-control`, 2026-07-29).
109
+ */
110
+ const CANONICAL_HOST_MODULE_TEMPLATE = `// Shared canonical-host predicate. Imported by BOTH next.config.mjs (alias
111
+ // redirect) and app/robots.ts (indexability gate) so the two can never disagree.
112
+ //
113
+ // Emitted as .mjs deliberately: next.config.mjs is plain ESM loaded before any
114
+ // TypeScript exists and cannot import a .ts module. tsconfig.json sets
115
+ // \`allowJs: true\`, so app/robots.ts type-checks this file too.
116
+
117
+ /**
118
+ * Host suffixes that are NEVER a canonical domain.
119
+ *
120
+ * \`.vercel.app\` is in here for consistency, not as an extra rule: the alias
121
+ * redirect in next.config.mjs already 301s every production *.vercel.app host to
122
+ * the custom domain precisely so they are not crawled as duplicates. Treating one
123
+ * as canonical would contradict a redirect this project already ships.
124
+ *
125
+ * \`.example.com\` is the scaffold's own placeholder default, which is by
126
+ * definition what NEXT_PUBLIC_SITE_URL holds on day one.
127
+ */
128
+ export const NON_CANONICAL_HOST_SUFFIXES = [".vercel.app", ".example.com"];
129
+
130
+ /**
131
+ * The canonical host from a site URL, or "" when there isn't one yet.
132
+ *
133
+ * @param {string | undefined} rawSiteUrl typically process.env.NEXT_PUBLIC_SITE_URL
134
+ * @returns {string} a real custom-domain host, else ""
135
+ */
136
+ export function canonicalHost(rawSiteUrl) {
137
+ try {
138
+ const { host } = new URL(rawSiteUrl || "");
139
+ // "localhost:3000" (no scheme) parses with an EMPTY host rather than throwing.
140
+ if (!host) return "";
141
+ return NON_CANONICAL_HOST_SUFFIXES.some((s) => host.endsWith(s)) ? "" : host;
142
+ } catch {
143
+ // Not a valid absolute URL yet (blank, or a bare hostname).
144
+ return "";
145
+ }
146
+ }
147
+
148
+ /**
149
+ * Whether this deployment may be indexed by search engines.
150
+ *
151
+ * Requires BOTH a production deployment AND a real canonical domain. Gating on
152
+ * VERCEL_ENV alone means the FIRST production deploy publishes \`Allow: /\` plus a
153
+ * sitemap of placeholder URLs, because NEXT_PUBLIC_SITE_URL is unset on day one
154
+ * and the fallback is a domain this project does not own. Getting placeholder
155
+ * URLs back out of a search index is slow and awkward, so this fails toward the
156
+ * visible error: a misconfigured deploy stays \`Disallow: /\`, which one \`curl\`
157
+ * reveals and one env var fixes.
158
+ *
159
+ * @param {Record<string, string | undefined>} [env] defaults to process.env
160
+ * @returns {boolean}
161
+ */
162
+ export function isIndexableDeployment(env = process.env) {
163
+ return env.VERCEL_ENV === "production" && canonicalHost(env.NEXT_PUBLIC_SITE_URL) !== "";
164
+ }
165
+ `;
83
166
  const NEXT_CONFIG_TEMPLATE = `/** @type {import('next').NextConfig} */
84
167
 
168
+ import { canonicalHost } from "./lib/seo/canonical-host.mjs";
169
+
85
170
  // SEO: redirect EVERY auto-assigned PRODUCTION *.vercel.app alias to the custom
86
171
  // domain so none is crawled as an indexable duplicate of the whole site
87
172
  // (Z2W standing heads-up 2026-06-29; recipe = [[portable-stack]] §24).
@@ -101,25 +186,15 @@ const NEXT_CONFIG_TEMPLATE = `/** @type {import('next').NextConfig} */
101
186
  // While it is blank, the *.example.com placeholder, or itself a *.vercel.app
102
187
  // host, the redirect list is empty — so a fresh scaffold never self-redirects,
103
188
  // and the custom domain (not *.vercel.app) never matches the regex → no loop.
189
+ //
190
+ // \`canonicalHost\` is imported rather than defined here so app/robots.ts decides
191
+ // indexability from the SAME predicate. See lib/seo/canonical-host.mjs.
104
192
  const isVercelProduction = process.env.VERCEL_ENV === "production";
105
193
 
106
- function canonicalHost() {
107
- const raw = process.env.NEXT_PUBLIC_SITE_URL || "";
108
- try {
109
- const host = new URL(raw).host;
110
- if (host && !host.endsWith(".vercel.app") && !host.endsWith(".example.com")) {
111
- return host;
112
- }
113
- } catch {
114
- // NEXT_PUBLIC_SITE_URL not a valid absolute URL yet — no redirect.
115
- }
116
- return "";
117
- }
118
-
119
194
  const nextConfig = {
120
195
  reactStrictMode: true,
121
196
  async redirects() {
122
- const host = canonicalHost();
197
+ const host = canonicalHost(process.env.NEXT_PUBLIC_SITE_URL);
123
198
  // Only in production, and only once a real custom domain is configured.
124
199
  if (!host || !isVercelProduction) return [];
125
200
  return [
@@ -136,6 +211,84 @@ const nextConfig = {
136
211
 
137
212
  export default nextConfig;
138
213
  `;
214
+ /**
215
+ * The `next.config.mjs` variant for a HOST-ROUTED multi-tenant app, where the
216
+ * incoming Host selects the tenant. Emitted when `hostRoutedTenancy` is set.
217
+ *
218
+ * The single-destination alias redirect above is wrong for this shape: there is
219
+ * no one canonical domain to redirect to — every tenant has its own front door,
220
+ * so redirecting a `*.vercel.app` alias to a fixed host lands visitors in some
221
+ * other tenant's app. The ruling (2026-07-30, three projects deep: `org-hq`,
222
+ * `site-control`, `z2w-member-match`) is **404 on an unmapped Host**, never a
223
+ * redirect to a fixed one. The redirect is therefore omitted here and the guard
224
+ * lives in `middleware.ts`.
225
+ */
226
+ const NEXT_CONFIG_HOST_ROUTED_TEMPLATE = `/** @type {import('next').NextConfig} */
227
+
228
+ // HOST-ROUTED MULTI-TENANT APP — the incoming Host selects the tenant.
229
+ //
230
+ // NOTE the deliberate ABSENCE of the *.vercel.app → custom-domain alias redirect
231
+ // that single-tenant Z2W Next.js apps ship. That redirect assumes ONE canonical
232
+ // destination, which is exactly what this shape does not have: every tenant has
233
+ // its own front door, so redirecting an alias to a fixed host would drop visitors
234
+ // into some other tenant's app. The ruling is **404 on an unmapped Host, never a
235
+ // redirect to a fixed one** — enforced in middleware.ts, which is the only place
236
+ // that sees the request Host at runtime. See lib/seo/canonical-host.mjs.
237
+
238
+ const nextConfig = {
239
+ reactStrictMode: true,
240
+ };
241
+
242
+ export default nextConfig;
243
+ `;
244
+ /**
245
+ * The Host guard for a host-routed multi-tenant app: a production request
246
+ * arriving on a known-non-canonical host maps to no tenant, so it 404s.
247
+ *
248
+ * Scope is deliberately narrow — middleware cannot resolve tenant vanity domains
249
+ * without a DB read (which would burn Neon CU-hours on every request, per
250
+ * [[neon-postgres]]), so this rejects only the host classes the scaffold KNOWS
251
+ * are nobody's tenant. Resolving real tenant domains stays the app's job.
252
+ */
253
+ const MIDDLEWARE_HOST_GUARD_TEMPLATE = `// Host guard for this HOST-ROUTED multi-tenant app.
254
+ //
255
+ // A production request arriving on a known-non-canonical host (*.vercel.app, the
256
+ // *.example.com placeholder) maps to NO tenant. Per the Z2W alias ruling it gets
257
+ // a 404 — never a redirect to a fixed canonical host, because there is no single
258
+ // canonical host in a host-routed app and redirecting would drop the visitor into
259
+ // a different tenant's front door.
260
+ //
261
+ // Deliberately narrow: this does NOT resolve tenant vanity domains, because that
262
+ // needs a DB read on every request and would burn Neon's CU-hour quota
263
+ // ([[neon-postgres]]). It rejects only the host classes that are nobody's tenant.
264
+ // Your tenant resolver still has to 404 a host it cannot map.
265
+
266
+ import { NextResponse } from "next/server";
267
+ import type { NextRequest } from "next/server";
268
+ import { NON_CANONICAL_HOST_SUFFIXES } from "@/lib/seo/canonical-host.mjs";
269
+
270
+ export function middleware(request: NextRequest) {
271
+ // Only in production. Preview deployments and localhost are *.vercel.app /
272
+ // localhost by nature, and blocking them would make every preview unusable.
273
+ if (process.env.VERCEL_ENV !== "production") return NextResponse.next();
274
+
275
+ const host = (request.headers.get("x-forwarded-host") ?? request.headers.get("host") ?? "")
276
+ .toLowerCase()
277
+ .split(":")[0];
278
+
279
+ if (NON_CANONICAL_HOST_SUFFIXES.some((suffix) => host.endsWith(suffix))) {
280
+ return new NextResponse(null, { status: 404 });
281
+ }
282
+
283
+ return NextResponse.next();
284
+ }
285
+
286
+ export const config = {
287
+ // Skip Next internals and the health endpoint — an uptime monitor pointed at
288
+ // the platform alias must keep working ([[uptime-kuma-monitor]]).
289
+ matcher: ["/((?!_next/|api/health).*)"],
290
+ };
291
+ `;
139
292
  const TSCONFIG_TEMPLATE = `{
140
293
  "compilerOptions": {
141
294
  "target": "ES2022",
@@ -377,11 +530,21 @@ export function RouteTracker() {
377
530
  const APP_PAGE_TEMPLATE = `// Home page — per-page \`metadata\` is mandatory per SEO baseline. Replace
378
531
  // the title + description with intentional, page-specific copy (do NOT
379
532
  // inherit the root defaults).
533
+ //
534
+ // ⚠️ The root layout's \`title.template\` does NOT apply to this file, so this
535
+ // title must be COMPLETE — brand included. Next.js applies a template to CHILD
536
+ // segments only, and app/page.tsx shares the ROOT segment with app/layout.tsx.
537
+ // A bare fragment here (the old \`title: "Home"\`) renders literally as
538
+ // \`<title>Home</title>\` on the most-linked page on the site, and it fails
539
+ // silently: \`next build\` is happy and the metadata source reads as if it
540
+ // composes. Pages in CHILD segments DO get the suffix and should not repeat
541
+ // the brand. Do not "tidy" this back to a fragment for consistency with them.
542
+ // (Found by \`site-control\` dogfooding this scaffold, 2026-07-28.)
380
543
 
381
544
  import type { Metadata } from "next";
382
545
 
383
546
  export const metadata: Metadata = {
384
- title: "Home",
547
+ title: "{{brand_name}} — {{slug}}",
385
548
  description: "{{description}}",
386
549
  alternates: { canonical: "/" },
387
550
  };
@@ -430,25 +593,45 @@ export default function sitemap(): MetadataRoute.Sitemap {
430
593
  return [
431
594
  {
432
595
  url: siteUrl,
433
- lastModified: new Date(),
596
+ // \`lastModified\` is deliberately OMITTED rather than set to \`new Date()\`.
597
+ // An always-now value claims the page changed on every fetch of the
598
+ // sitemap; Google documents ignoring \`lastmod\` once it proves unreliable,
599
+ // so a value that is always wrong spends the signal to say nothing — worse
600
+ // than not sending it. Add it back when you have a REAL content timestamp
601
+ // (a CMS \`updated_at\`, a file mtime, a build-pinned constant).
434
602
  changeFrequency: "weekly",
435
603
  priority: 1,
436
604
  },
437
605
  ];
438
606
  }
439
607
  `;
440
- const APP_ROBOTS_TEMPLATE = `// Robots generator — production indexable, preview/staging noindex per SEO
441
- // baseline. Gated on \`VERCEL_ENV\`; for non-Vercel hosts swap in the
442
- // equivalent env var (e.g. \`CF_PAGES_BRANCH !== 'main'\`).
608
+ const APP_ROBOTS_TEMPLATE = `// Robots generator — indexable ONLY on a production deployment that also has a
609
+ // real canonical domain. Everything else (preview, staging, and a production
610
+ // deploy still on the placeholder domain) emits \`Disallow: /\`.
611
+ //
612
+ // Two conditions, not one. Gating on \`VERCEL_ENV\` ALONE means the very first
613
+ // \`vercel --prod\` — or the first push after connecting the repo, since
614
+ // auto-deploy is on by default — publishes \`Allow: /\` advertising a sitemap of
615
+ // \`{{slug}}.example.com\` URLs, a domain this project does not own.
616
+ // \`NEXT_PUBLIC_SITE_URL\` is unset on day one by definition, so the placeholder is
617
+ // what ships. (Reported by \`site-control\` 2026-07-29 after it cost two deferred
618
+ // deploys: the deploy was never the hazard, the gate was.)
619
+ //
620
+ // ⚠️ robots.txt and sitemap.xml are PRERENDERED at build time (\`○ (Static)\`), so
621
+ // setting NEXT_PUBLIC_SITE_URL later requires a REDEPLOY — editing the env var
622
+ // alone changes nothing.
623
+ //
624
+ // For non-Vercel hosts, swap the VERCEL_ENV check inside
625
+ // lib/seo/canonical-host.mjs for the equivalent (e.g. \`CF_PAGES_BRANCH === 'main'\`).
443
626
 
444
627
  import type { MetadataRoute } from "next";
628
+ import { isIndexableDeployment } from "@/lib/seo/canonical-host.mjs";
445
629
 
446
630
  // \`||\` not \`??\` — a blank NEXT_PUBLIC_SITE_URL must fall back (see app/layout.tsx).
447
631
  const siteUrl = process.env.NEXT_PUBLIC_SITE_URL || "https://{{slug}}.example.com";
448
- const isProduction = process.env.VERCEL_ENV === "production";
449
632
 
450
633
  export default function robots(): MetadataRoute.Robots {
451
- if (!isProduction) {
634
+ if (!isIndexableDeployment()) {
452
635
  return {
453
636
  rules: { userAgent: "*", disallow: "/" },
454
637
  };
@@ -528,7 +711,8 @@ Per Z2W standing org requirement 2026-05-30. Run before adding a new page AND be
528
711
  - ✅ \`app/layout.tsx\` — root metadata + JSON-LD Organization
529
712
  - ✅ \`app/page.tsx\` — per-page metadata template
530
713
  - ✅ \`app/sitemap.ts\`
531
- - ✅ \`app/robots.ts\` (preview-noindex gated on \`VERCEL_ENV\`)
714
+ - ✅ \`app/robots.ts\` (indexable requires production **and** a real canonical domain — see \`lib/seo/canonical-host.mjs\`)
715
+ - ⚠️ \`robots.txt\` + \`sitemap.xml\` are PRERENDERED at build time. Until \`NEXT_PUBLIC_SITE_URL\` is your real domain this site is \`Disallow: /\` **by design**; setting the env var requires a **redeploy** to take effect. Verify with \`curl https://your-domain/robots.txt\`.
532
716
  - ✅ \`app/opengraph-image.tsx\` (placeholder — replace before launch)
533
717
  - ✅ Fathom three-file pattern (\`lib/analytics/\`) mounted as \`<Analytics />\`; RouteTracker fires \`trackPageview()\` on route change (gated on \`NEXT_PUBLIC_FATHOM_SITE_ID\`)
534
718
  - ✅ \`NEXT_PUBLIC_SITE_URL\` env var stub for \`metadataBase\`
@@ -552,6 +736,41 @@ NEXT_PUBLIC_SITE_URL=https://{{slug}}.example.com
552
736
  # One Fathom site = one deployment.
553
737
  NEXT_PUBLIC_FATHOM_SITE_ID=
554
738
  `;
739
+ /**
740
+ * The `CANONICAL_HOSTS` allowlist seam.
741
+ *
742
+ * Appended when the project sends auth email (`sendsEmail`) or routes by Host
743
+ * (`hostRoutedTenancy`) — the two shapes that have somewhere to enforce it.
744
+ *
745
+ * Why the scaffolder plants the env var and the pointer rather than the code:
746
+ * this CLI does not emit `auth.ts` (it emits no auth code at all), so there is no
747
+ * emitted host check to patch. The gap `audit-engine` measured on 2026-07-29 —
748
+ * 10 repos with `trustHost: true`, no `AUTH_URL`, and only 2 validating the host
749
+ * — propagated through the *guidance*, not through this scaffold. So the
750
+ * scaffolder's honest half is the seam: an env var that exists on day one, and a
751
+ * pointer at the recipe, in the file the next agent actually opens.
752
+ */
753
+ const CANONICAL_HOSTS_ENV_BLOCK = `
754
+ # ── Canonical host allowlist ────────────────────────────────────────────────
755
+ # Comma-separated list of the hostnames this deployment legitimately answers on.
756
+ # Normalize to lowercase when you parse it.
757
+ #
758
+ # UNSET MUST MEAN NOBODY, NOT EVERYBODY. An env-var typo has to lock the door,
759
+ # not remove it — the same fail-closed-on-empty rule as ALLOWED_EMAILS.
760
+ #
761
+ # Magic-link auth needs this and it is not optional: \`trustHost: true\` with no
762
+ # AUTH_URL (the correct Z2W setting — a fixed AUTH_URL breaks tenant vanity
763
+ # domains) means Auth.js derives every magic-link URL from the incoming Host
764
+ # header with NOTHING validating it. An attacker can request a link for someone
765
+ # else's address on a forged Host; the victim gets a genuine, correctly-signed
766
+ # email pointing at the attacker's server. Validate inside
767
+ # sendVerificationRequest and fail CLOSED — send nothing, do not fall back to a
768
+ # canonical host (that is an enumeration oracle). Allow anything when
769
+ # NODE_ENV !== "production" so preview deployments and localhost keep working.
770
+ #
771
+ # Copy-paste recipe + the isKnownHost() helper: [[z2w-magic-link-auth]] §0 rule 2b.
772
+ CANONICAL_HOSTS=
773
+ `;
555
774
  /**
556
775
  * Merge the email SDK deps into an already-substituted package.json string.
557
776
  * Only called on the email path, so the no-email package.json stays the exact
@@ -566,15 +785,27 @@ export function scaffoldNextjs(inputs, opts) {
566
785
  const spec = resolveBrandSpec(inputs);
567
786
  const base = commonBaseFiles(inputs, opts, NARRATIVE);
568
787
  const sendsEmail = inputs.sendsEmail === true;
788
+ const hostRouted = inputs.hostRoutedTenancy === true;
569
789
  let packageJson = sub(PACKAGE_JSON_TEMPLATE, inputs, opts, spec);
570
790
  if (sendsEmail)
571
791
  packageJson = withEmailDeps(packageJson);
572
792
  let envExample = sub(ENV_EXAMPLE_TEMPLATE, inputs, opts, spec);
573
793
  if (sendsEmail)
574
794
  envExample += EMAIL_ENV_BLOCK;
795
+ // The host allowlist serves auth email (magic links derive URLs from the Host)
796
+ // and Host-routed tenancy (the Host selects the tenant). Emitted once for both.
797
+ if (sendsEmail || hostRouted)
798
+ envExample += CANONICAL_HOSTS_ENV_BLOCK;
575
799
  const typeSpecific = [
576
800
  { path: "package.json", content: packageJson },
577
- { path: "next.config.mjs", content: sub(NEXT_CONFIG_TEMPLATE, inputs, opts, spec) },
801
+ {
802
+ path: "next.config.mjs",
803
+ content: sub(hostRouted ? NEXT_CONFIG_HOST_ROUTED_TEMPLATE : NEXT_CONFIG_TEMPLATE, inputs, opts, spec),
804
+ },
805
+ {
806
+ path: "lib/seo/canonical-host.mjs",
807
+ content: sub(CANONICAL_HOST_MODULE_TEMPLATE, inputs, opts, spec),
808
+ },
578
809
  { path: "tsconfig.json", content: sub(TSCONFIG_TEMPLATE, inputs, opts, spec) },
579
810
  { path: "app/layout.tsx", content: sub(APP_LAYOUT_TEMPLATE, inputs, opts, spec) },
580
811
  { path: "app/page.tsx", content: sub(APP_PAGE_TEMPLATE, inputs, opts, spec) },
@@ -607,6 +838,12 @@ export function scaffoldNextjs(inputs, opts) {
607
838
  path: ".env.local",
608
839
  content: localEnvFrom(envExample, ".env.local", inputs.slug),
609
840
  });
841
+ if (hostRouted) {
842
+ typeSpecific.push({
843
+ path: "middleware.ts",
844
+ content: sub(MIDDLEWARE_HOST_GUARD_TEMPLATE, inputs, opts, spec),
845
+ });
846
+ }
610
847
  if (sendsEmail) {
611
848
  typeSpecific.push(...emailFiles(inputs, opts, spec, "nextjs"));
612
849
  }
@@ -622,6 +859,10 @@ export const NEXTJS_SEO_BASELINE_PATHS = [
622
859
  "app/page.tsx",
623
860
  "app/sitemap.ts",
624
861
  "app/robots.ts",
862
+ // The shared canonical-host predicate. Part of the baseline because the
863
+ // indexability gate in app/robots.ts and the alias redirect in next.config.mjs
864
+ // both read it — a scaffold missing it has no indexability gate at all.
865
+ "lib/seo/canonical-host.mjs",
625
866
  "app/opengraph-image.tsx",
626
867
  // Fathom (SEO baseline item 7) — the three-file pattern; the loader alone
627
868
  // (data-auto="false" with no RouteTracker) records zero pageviews.
package/dist/standards.js CHANGED
@@ -284,7 +284,21 @@ const FATHOM_BODY = `### Fathom analytics (web UI)
284
284
  > **Analytics:** Fathom Analytics is the single source of truth for this project. Env var name: {{fathom_env_var}}. SPA pattern: \`data-auto="false"\` on the Fathom script, then manual \`trackPageview()\` on route change. One Fathom site = one deployment. See [[fathom-analytics]] for details.`;
285
285
  const UPTIME_KUMA_BODY = `### Uptime Kuma monitor (deploy target)
286
286
 
287
- > **Uptime monitoring:** Add an HTTP(s)-Keyword monitor in Kerry's self-hosted Uptime Kuma after first deploy. Defaults: 60s heartbeat, 2 retries, 60s retry interval, 48s timeout, accepted status 200-299. Point at \`/health\` — never the main URL. See [[uptime-kuma-monitor]] for the form-by-form walkthrough.`;
287
+ > **Uptime monitoring:** Add an HTTP(s)-Keyword monitor in Kerry's self-hosted Uptime Kuma after first deploy. Defaults: 60s heartbeat, 2 retries, 60s retry interval, 48s timeout, accepted status 200-299.
288
+ >
289
+ > **Point at this project's health path — never the main URL. The path differs by stack, and the scaffold already ships a document there carrying the keyword below, so do not improvise one:**
290
+ >
291
+ > | Stack | Health path | Served by |
292
+ > |---|---|---|
293
+ > | Next.js | \`/api/health\` | \`app/api/health/route.ts\` — a bare \`/health\` **404s**, because the App Router serves route handlers under a path segment |
294
+ > | Python | \`/healthz\` | the FastAPI health route |
295
+ > | CF Worker | \`/health\` | the Worker's fetch handler |
296
+ > | Node / Hono | \`/health\` | the mounted health router |
297
+ > | CF Pages (static) | \`/health.json\` | the scaffolded \`health.json\` — a static deploy has no server, so the document IS the endpoint |
298
+ >
299
+ > Use the SAME path in CLAUDE.md / README prose as the route actually serves.
300
+ >
301
+ > **Keyword: \`"status":"ok"\` — never bare \`ok\`.** Kuma's keyword check is a case-sensitive substring match over the WHOLE response body, and \`ok\` is inside *cookie, lookup, token, booking, blocked, looking* — all of which appear in error pages that still return HTTP 200, so a bare-\`ok\` monitor stays green while the app is down. Every health document this scaffold emits already carries exactly \`{"status":"ok"}\` — compact, no space after the colon, because Kuma matches literally — so match on that rather than inventing a keyword. See [[uptime-kuma-monitor]] for the form-by-form walkthrough.`;
288
302
  const SENTRY_BODY = `### Sentry runtime-error tracking (customer-facing web app)
289
303
 
290
304
  > **Wire Sentry at instantiation — runtime error capture is the observability gap uptime monitoring can't cover.** Uptime Kuma proves \`/health\` returns 200; Sentry proves *actual user requests* are succeeding. A beta customer hits Submit, gets a 500, Kuma still sees \`/health\` 200 → no alert → nobody knows. Sentry emails + Session Replay within ~2 min. Vercel Hobby does NOT email on runtime errors (only build/deploy failures), so this is the only path to per-request error visibility. Free tier (5k errors + 10k transactions + 50 replays / mo) covers any Z2W-scale project at $0/mo. Same posture as [[fathom-analytics]] and [[uptime-kuma-monitor]]: the Z2W-sanctioned default tool for the runtime-error / APM category. **Load [[sentry-runtime-errors]] before wiring — it is the binding contract; the summary below is orientation.**
@@ -357,7 +371,7 @@ This project participates in the Z2W cross-project coordination bulletin.
357
371
  \`\`\`
358
372
  - 2026-07-25 · z2w-starter-kit · ACTION · Trim your bulletin file — it's over the 256 KB read-cap · §Open questions
359
373
  \`\`\`
360
- Applies to every inbound form: a \`[→ {them}]\` question, a heads-up you filed in their file, or a maintainer directive. **The recipient deletes the line when they handle it**, so leaving it un-deleted is the signal that the item is still live. *(Adopted 2026-07-25 from \`z2w-starter-kit\`'s 2026-07-15 proposal on Kerry's observation that finding messages addressed to a project was too hard — one session had to grep a 705 KB file across three sections to find a directive aimed at it — and \`z2w-agent-command-center\`'s independent endorsement after the same failure bit it. The Command Center renders this block as the phone-first "addressed to you" queue.)*
374
+ Applies to every inbound form: a \`[→ {them}]\` question, a heads-up you filed in their file, or a maintainer directive. **The recipient deletes the line when they handle it**, so leaving it un-deleted is the signal that the item is still live. **Two send-side rules (v0.1.22, both detailed in §8.11):** (1) **grep their file for an existing thread on your topic before you file** — you already have the file open to append, so the check is free; if a thread exists, \`↳\` co-sign it (saying what's *different* about your instance) rather than opening a second one; (2) **if you later WITHDRAW an item, delete your own triage line yourself** — post the \`↳ retracted\` reply first, then remove the line. Retraction is the only case where a sender deletes; \`ACTION\` outranks everything in the recipient's queue, so a withdrawn ACTION is not clutter, it is real work being pushed down the list. *(Adopted 2026-07-25 from \`z2w-starter-kit\`'s 2026-07-15 proposal on Kerry's observation that finding messages addressed to a project was too hard — one session had to grep a 705 KB file across three sections to find a directive aimed at it — and \`z2w-agent-command-center\`'s independent endorsement after the same failure bit it. The Command Center renders this block as the phone-first "addressed to you" queue.)*
361
375
  - **ANSWERING a \`[→ you]\` question counts as "writing something addressed to another project" — so the reply ALSO needs a \`## 📥 Needs attention\` line, in the ASKER's file (v0.1.21).** This is the case the rule above always covered in principle and that everyone (including the maintainer) reads past in practice, because replying *feels* like closing an item rather than sending one. It isn't. Per §8.2 the thread lives in **your** file, which means **the asker has nothing in their own file to tell them an answer arrived** — they filed into your file and then never look at it again. Posting the \`↳\` is not delivering it.
362
376
  \`\`\`
363
377
  - 2026-07-27 · z2w-agent-coordination · FYI · RULING on your \`## Integrations\` question — answered in full on the thread in my file · projects/z2w-agent-coordination.md §Open questions
@@ -395,6 +409,11 @@ This project participates in the Z2W cross-project coordination bulletin.
395
409
  **The trigger is "carries cross-project signal," NOT "committed code" (v0.1.15).** A decision, a heads-up, a capability→home mapping, a naming or scope change, a new build-target, an answered question, a discovered gotcha — all qualify, and **synthesis, audit, and planning sessions routinely commit zero code yet carry the highest cross-project value.** An agent that gates Tier 2 on \`git log\` says nothing exactly when it has the most to say. Skip Tier 2 only when the session genuinely produced nothing anyone else would act on (pure local exploration with no outcome) — and Tier 1 still runs even then. *(Adopted 2026-07-25 from \`z2w-starter-kit\`'s 2026-07-11 ask on Kerry's instruction, after a zero-commit \`z2w-forms\` extraction audit generated a new build-target, a Kerry decision, a delivery model, a naming fix, and heads-ups landing on three other projects — none of which a code-gated wrap-up would have published.)*
396
410
  - **Keep \`## Integrations\` + your Live status current — a never-ask standing step, exactly like \`## Current focus\` (v0.1.14).** If this session changed how this project relates to another Z2W app — it started consuming an engine/service, stopped using one, or became a provider another app now depends on — update your file's \`## Integrations\` edges. If the project's lifecycle changed — scaffolded → live in prod, went dormant, retired — update the **Live status** line and its date. This is the capture mechanism behind the ecosystem dependency map + live-status badges on \`agents.z2w.us\`; a stale edge or status silently misleads every other agent (real 2026-07-20 miss: an audit called a LIVE engine "unbuilt" because no single place recorded its status). Decide and do it — do not ask. Absent section = nothing to report yet; create it lazily the first time you have an edge or a status to record. Schema + conventions in §8.10.
397
411
  - **Size discipline (v0.1.11):** before appending, if \`projects/{this-project}.md\` is approaching ~200 KB (the point where agents can no longer \`Read\` it in one call), trim FIRST — archive old \`## Active sessions\` and \`## Recent commits\` entries and resolved \`## Open questions\` threads into \`projects/{this-project}-archive.md\` (a separate, commit-flagged operation). Keep your live file readable whole. \`## Current focus\` is rewritten in place (never appended), which is the main thing that keeps a project file from growing without bound — never let a single field accumulate a multi-session history.
412
+ - **Your project file is a COORDINATION SURFACE, not a log (v0.1.22).** The test, and it is a good one: **"would another agent load this file to answer a question?"** Session recaps, npm publish state, test counts, defect post-mortems and build narrative all fail it — that is \`STATUS.md\` / \`CHANGELOG.md\` content in your own repo, and duplicating it here makes ~40 other agents pay for it on every read while approximately none of them need it. Two bright lines:
413
+ 1. **\`## Current focus\` and \`## Active sessions\` answer "what is this project doing, and is it alive" — nothing more.** Current focus ≲1.5 KB (it renders on Kerry's phone); each Active-sessions entry ≲400 bytes — one line: what shipped, the test count, a commit SHA. The narrative goes in your own repo, where you are already writing it.
414
+ 2. **Archive a thread in the same commit that resolves it.** Not in a later sweep. If you post a closing \`↳\`, you move the thread. This is the only self-enforcing rule of the set, because the agent that knows a thread is done is the agent closing it. *(Do NOT auto-archive on "reply older than N days" — a reply is not a resolution, and several of the longest-running live threads in this bulletin have replies. Resolution is a judgment, so the action belongs at the moment of judgment.)* **"Resolved" means BOTH parties are done — never archive a thread you are the ASKER on until the answer lands.** The live-ness signal for a thread you are waiting on is a \`## 📥 Needs attention\` line in *someone else's* file, which you cannot see from your own, so "no live line in my queue" is not evidence the thread is closed. *(Found the hard way 2026-07-29: \`z2w-starter-kit\`'s own careful trim — which explicitly spared every thread with a live queue line — archived the very thread carrying its unanswered proposal, because the waiting line was in the maintainer's queue.)*
415
+
416
+ **Enforced at push, not by good intentions:** \`.github/workflows/file-size-check.yml\` runs \`scripts/check-file-sizes.sh\` on every push touching \`projects/**.md\` or \`global.md\` — hard-fail over 256 KB, warning over 200 KB, \`*-archive.md\` exempt by design. *(Adopted 2026-07-29 from \`z2w-starter-kit\`'s 2026-07-27 proposal, made after it trimmed its own file three times in one month and re-grew it ~70 KB in a single session. Its rule 3 — a per-session soft byte budget — is deliberately NOT adopted: it fails for exactly the reason the v0.1.11 rule above fails, namely that it asks an agent to measure mid-task, and agents do not measure mid-task. Push is the one moment measurement is automatic and free. The check belongs to the repo it guards, so the maintainer wrote it rather than handing the offer back.)*
398
417
  - \`git commit -m "{this-project}: {summary}"\` (see §8.2 for agent-identifier format in commit messages and session entries) and \`git push\`.
399
418
  - If push fails due to concurrent write from another session: \`git pull --rebase\`, resolve any conflicts (they should be rare — append-only within sections), retry push.
400
419
  - **Local auto-push hooks:** if your project has a post-commit hook that auto-pushes, expect it to race your explicit \`git push\` and grab the ref lock first. The commit still lands — verify with \`git log origin/main\` rather than re-pushing.
@@ -452,7 +471,11 @@ const SEO_BASELINE_BODY = `### SEO baseline (non-WP web UI)
452
471
  > **Scope:** applies to every Z2W non-WP web app with a public indexable surface. Does NOT apply to: WordPress sites (RankMath), API-only services with no HTML surface, CLI libraries, protocol repos, Cloudflare Workers without a public HTML response.`;
453
472
  const EMAIL_SERVICE_BODY = `### Email service selection (any project that will send mail)
454
473
 
455
- > **Email service:** Kerry's portfolio has FOUR sanctioned email services covering distinct sweet spots — FluentCRM (WP marketing/CRM), Amazon SES (cheap high-volume transactional), Resend (developer-friendly transactional + NextAuth magic links + React Email), Cloudflare Email Service (Workers-native send/receive). Before wiring any email feature in this project — magic-link auth, transactional notification, marketing broadcast, anything — load [[email-service-router]] and walk the decision matrix. Do NOT introduce a fifth service (SendGrid, Mailgun, Postmark, Mailchimp, MailerSend, Brevo/Sendinblue, etc.) — the router skill explains why and routes to the right one of the four.`;
474
+ > **Email service:** Kerry's portfolio has FOUR sanctioned email services covering distinct sweet spots — FluentCRM (WP marketing/CRM), Amazon SES (cheap high-volume transactional), Resend (developer-friendly transactional + NextAuth magic links + React Email), Cloudflare Email Service (Workers-native send/receive). Before wiring any email feature in this project — magic-link auth, transactional notification, marketing broadcast, anything — load [[email-service-router]] and walk the decision matrix. Do NOT introduce a fifth service (SendGrid, Mailgun, Postmark, Mailchimp, MailerSend, Brevo/Sendinblue, etc.) — the router skill explains why and routes to the right one of the four.
475
+ >
476
+ > **🔐 If this project uses magic-link auth, the Host allowlist is NOT optional — and the rule you already know is only half of it.** The Z2W rule is \`trustHost: true\` with **no** \`AUTH_URL\` (a fixed \`AUTH_URL\` breaks tenant vanity domains — that stands, do not reverse it). But "no \`AUTH_URL\`" also means **"accept ANY Host"** until you add an allowlist: Auth.js derives every magic-link URL from the incoming \`Host\` header with nothing validating it, so an attacker who requests a link for **someone else's** address on a forged Host causes that person to receive a genuine, correctly-signed email pointing at the attacker's server. **So: keep \`trustHost: true\`, keep \`AUTH_URL\` unset, AND validate the host** inside \`sendVerificationRequest\` against a \`CANONICAL_HOSTS\` env allowlist plus your DB's tenant domains. **Fail CLOSED — send nothing;** falling back to the canonical host is an enumeration oracle. **Unset \`CANONICAL_HOSTS\` must mean nobody, not everybody.** Allow anything when \`NODE_ENV !== "production"\` so preview deployments and localhost keep working. Copy-paste recipe: **[[z2w-magic-link-auth]] §0 rule 2b**.
477
+ >
478
+ > *Why this is spelled out here rather than left to the skill: \`audit-engine\` measured 10 Z2W repos on 2026-07-29 running \`trustHost: true\` with no \`AUTH_URL\` and only 2 validating the host. Several cite the rule by section number in a code comment — they followed the guidance exactly, and the guidance was missing its companion clause. **Honest scope: a guidance gap with one confirmed HIGH precedent (\`event-engine\` H-1, remediated with exactly this allowlist), not 10 confirmed vulnerabilities** — exploitability was not tested per repo.*`;
456
479
  const MODERATION_BODY = `### Moderation baseline (user-generated content)
457
480
 
458
481
  > **This project accepts user-generated content, so trust & safety is an at-instantiation decision — not a Phase-8 afterthought.** Before building the first surface where one user's input is shown to others (posts, comments, profiles, listings, direct messages), load [[moderation-system]] and follow its shape. It is battle-tested across two live Z2W apps (z2w-social shipped it Step 8; event-engine built the second reference implementation) — do NOT hand-roll a per-content-type moderation system.
package/dist/writer.js CHANGED
@@ -405,6 +405,18 @@ export function parseScaffoldInputs(json) {
405
405
  }
406
406
  inputs.hasObservability = obj["hasObservability"];
407
407
  }
408
+ // Optional: whether the incoming Host selects the tenant (a HOST-ROUTED
409
+ // multi-tenant app). Defaults to false (single-tenant). When true, the nextjs
410
+ // scaffolder omits the single-destination *.vercel.app alias redirect — wrong
411
+ // shape, there is no one canonical domain — and emits a `middleware.ts` host
412
+ // guard that 404s a known-non-canonical production host instead. Ruling
413
+ // 2026-07-30 across org-hq / site-control / z2w-member-match.
414
+ if (obj["hostRoutedTenancy"] !== undefined) {
415
+ if (typeof obj["hostRoutedTenancy"] !== "boolean") {
416
+ throw new WriterError(`--input field "hostRoutedTenancy" must be a boolean, got ${typeof obj["hostRoutedTenancy"]}.`);
417
+ }
418
+ inputs.hostRoutedTenancy = obj["hostRoutedTenancy"];
419
+ }
408
420
  // Optional: the verbatim instantiation prompt, recorded on the Airtable row.
409
421
  // The --input path has no brief to capture, so callers may supply it here;
410
422
  // when omitted, the Airtable write reminds the agent to add it by hand.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zero2webmaster/starter-kit",
3
- "version": "0.5.7",
3
+ "version": "0.6.0",
4
4
  "description": "Node CLI to scaffold new Z2W projects from canonical Templates + AGENTS.md.",
5
5
  "author": {
6
6
  "name": "Dr. Kerry Kriger",