@zero2webmaster/starter-kit 0.2.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,320 @@
1
+ // Scaffolder: `node-service` — Node + Hono API service for Cloud Run.
2
+ //
3
+ // A portable, runtime-agnostic HTTP API: Hono on @hono/node-server, listening
4
+ // on `process.env.PORT` (Cloud Run injects this; 8080 is the default), with a
5
+ // DB-free `/health` route and a vitest smoke test that passes on first
6
+ // `npm test`. Containerized via the included Dockerfile.
7
+ //
8
+ // When `dbStrategy === "neon-postgres"` the scaffolder also lays down a
9
+ // lazy/import-safe Drizzle + Neon data layer (`src/db/`) plus a `drizzle.config.ts`
10
+ // — the DB handle reads `DATABASE_URL` on first use, never at import time, so
11
+ // the DB-free `/health` path and the tests never require the secret (per
12
+ // [[portable-stack]] §15 + [[neon-postgres]]).
13
+ //
14
+ // NOT subject to the SEO baseline (API-only service, no public HTML surface)
15
+ // and NOT to Fathom (no web UI). IS a deploy target, so the standards resolver
16
+ // inserts the Uptime Kuma + (when applicable) Neon-careful disciplines.
17
+ import { commonBaseFiles, EMAIL_DEPS, EMAIL_ENV_BLOCK, emailFiles, localEnvFrom, resolveBrandSpec, sub, } from "./common.js";
18
+ function buildNarrative(usesNeon) {
19
+ const dbParagraph = usesNeon
20
+ ? `
21
+
22
+ **Database:** Neon Postgres via Drizzle (\`src/db/\`). The handle is lazy and import-safe — \`db()\` in \`src/db/index.ts\` reads \`DATABASE_URL\` on first use, never at module load, so the DB-free \`/health\` path and the tests never require the secret (per [[portable-stack]] §15). Migrations: \`npm run db:generate\` then \`npm run db:push\` (drizzle-kit). Keep to standard Postgres types so the schema ports to any Postgres host.`
23
+ : "";
24
+ return `## What this is
25
+
26
+ \`{{slug}}\` is a Node + Hono API service scaffolded under the {{brand_name}} brand, built to deploy on **Cloud Run** (or any Node host — Fly, Render, Railway). API-only — no public HTML surface, no SEO baseline.
27
+
28
+ **Quick start for contributors:**
29
+
30
+ \`\`\`bash
31
+ npm install
32
+ # .env was scaffolded for you — fill in the values it lists
33
+ npm run dev # local server (tsx watch) on http://localhost:8080
34
+ npm test # vitest
35
+ npm run build # compile to dist/
36
+ npm start # node dist/index.js (what the container runs)
37
+ \`\`\`
38
+
39
+ **Health endpoint:** \`GET /health\` returns \`{ "status": "ok" }\`. **Do NOT** make this endpoint touch the database — per [[neon-postgres]], routine uptime probes (per [[uptime-kuma-monitor]]) would burn Neon Free's CU-hour quota and break scale-to-zero. Add a separate \`/health/deep\` with an explicit budget if a real readiness check is ever needed.
40
+
41
+ **Runtime:** Node 20+, listening on \`process.env.PORT\` (Cloud Run injects this; 8080 is the local default). The app is built in \`src/app.ts\` (importable by tests without starting a server) and served by \`src/index.ts\`.
42
+
43
+ **Deployment:** containerized via the included \`Dockerfile\` (multi-stage, \`node:20-slim\`). Per [[portable-stack]], the service avoids host-branded SDKs so it moves between Node hosts with no rewrite.${dbParagraph}
44
+ `;
45
+ }
46
+ function buildPackageJson(usesNeon, sendsEmail) {
47
+ const pkg = {
48
+ name: "{{slug}}",
49
+ version: "{{version}}",
50
+ description: "{{description}}",
51
+ private: true,
52
+ type: "module",
53
+ engines: { node: ">=20" },
54
+ main: "dist/index.js",
55
+ scripts: {
56
+ dev: "tsx watch src/index.ts",
57
+ build: "tsc -p tsconfig.json",
58
+ start: "node dist/index.js",
59
+ typecheck: "tsc --noEmit",
60
+ test: "vitest run",
61
+ ...(usesNeon
62
+ ? {
63
+ "db:generate": "drizzle-kit generate",
64
+ "db:push": "drizzle-kit push",
65
+ }
66
+ : {}),
67
+ },
68
+ dependencies: {
69
+ "@hono/node-server": "^1.13.0",
70
+ hono: "^4.6.0",
71
+ ...(usesNeon
72
+ ? {
73
+ "@neondatabase/serverless": "^0.10.0",
74
+ // >=0.45.2 — clears GHSA-gpj5-g38j-94v9 (SQL injection via
75
+ // improperly-escaped identifiers in drizzle-orm <0.45.2).
76
+ "drizzle-orm": "^0.45.2",
77
+ }
78
+ : {}),
79
+ ...(sendsEmail ? EMAIL_DEPS : {}),
80
+ },
81
+ devDependencies: {
82
+ "@types/node": "^22.0.0",
83
+ tsx: "^4.20.0",
84
+ typescript: "^5.6.0",
85
+ // vitest 4 (vite 6.x) — vitest <=3.2.5 pulls a vulnerable vite/esbuild
86
+ // (GHSA-67mh-4wv8-2f99). 4.x ships a clean tree (matches the starter-kit's
87
+ // own vitest-2→4 audit fix, its ROADMAP Step 11).
88
+ vitest: "^4.1.0",
89
+ ...(usesNeon ? { "drizzle-kit": "^0.31.0" } : {}),
90
+ },
91
+ };
92
+ return JSON.stringify(pkg, null, 2) + "\n";
93
+ }
94
+ const TSCONFIG_TEMPLATE = `{
95
+ "compilerOptions": {
96
+ "target": "ES2022",
97
+ "module": "NodeNext",
98
+ "moduleResolution": "NodeNext",
99
+ "lib": ["ES2022"],
100
+ "types": ["node"],
101
+ "outDir": "dist",
102
+ "rootDir": "src",
103
+ "strict": true,
104
+ "esModuleInterop": true,
105
+ "skipLibCheck": true,
106
+ "forceConsistentCasingInFileNames": true,
107
+ "resolveJsonModule": true,
108
+ "declaration": false,
109
+ "sourceMap": false
110
+ },
111
+ "include": ["src/**/*"],
112
+ "exclude": ["node_modules", "dist"]
113
+ }
114
+ `;
115
+ const VITEST_CONFIG_TEMPLATE = `import { defineConfig } from "vitest/config";
116
+
117
+ export default defineConfig({
118
+ test: {
119
+ include: ["src/**/*.test.ts"],
120
+ },
121
+ });
122
+ `;
123
+ const SRC_INDEX_TEMPLATE = `// {{slug}} — server entry point.
124
+ //
125
+ // {{description}}
126
+ //
127
+ // Listens on process.env.PORT (Cloud Run injects this at runtime; 8080 is the
128
+ // local default). The Hono app itself lives in ./app.ts so tests can import it
129
+ // without binding a port.
130
+
131
+ import { serve } from "@hono/node-server";
132
+
133
+ import { app } from "./app.js";
134
+
135
+ // \`||\` not \`??\` — the scaffolded .env seeds PORT="" until filled in, and
136
+ // \`Number("" ?? 8080)\` is \`Number("")\` = 0 (binds a random port). \`||\` falls back.
137
+ const port = Number(process.env.PORT || 8080);
138
+
139
+ serve({ fetch: app.fetch, port }, (info) => {
140
+ // eslint-disable-next-line no-console
141
+ console.log(\`{{slug}} listening on http://localhost:\${info.port}\`);
142
+ });
143
+ `;
144
+ const SRC_APP_TEMPLATE = `// {{slug}} — Hono application.
145
+ //
146
+ // Exported separately from the server entry (index.ts) so tests and other
147
+ // callers can exercise routes via \`app.request(...)\` without starting a server.
148
+
149
+ import { Hono } from "hono";
150
+
151
+ import { health } from "./routes/health.js";
152
+
153
+ export const app = new Hono();
154
+
155
+ app.route("/health", health);
156
+
157
+ app.get("/", (c) => c.json({ service: "{{slug}}", status: "ok" }));
158
+ `;
159
+ const SRC_ROUTES_HEALTH_TEMPLATE = `// DB-free health endpoint for {{slug}}.
160
+ //
161
+ // Per [[neon-postgres]], do NOT add a database roundtrip here. Routine probes
162
+ // from uptime monitors (per [[uptime-kuma-monitor]]) would burn through Neon
163
+ // Free's 100 CU-hour monthly quota and defeat scale-to-zero. If a deeper
164
+ // readiness check is needed, add a separate /health/deep with explicit budget.
165
+
166
+ import { Hono } from "hono";
167
+
168
+ export const health = new Hono();
169
+
170
+ health.get("/", (c) => c.json({ status: "ok" }));
171
+ `;
172
+ const SRC_ROUTES_HEALTH_TEST_TEMPLATE = `import { describe, expect, it } from "vitest";
173
+
174
+ import { app } from "../app.js";
175
+
176
+ describe("GET /health", () => {
177
+ it("returns 200 {status: ok} without touching the database", async () => {
178
+ const res = await app.request("/health");
179
+ expect(res.status).toBe(200);
180
+ expect(await res.json()).toEqual({ status: "ok" });
181
+ });
182
+ });
183
+ `;
184
+ const DOCKERFILE_TEMPLATE = `# {{slug}} — Cloud Run container.
185
+ #
186
+ # Cloud Run injects the PORT environment variable at runtime (default 8080);
187
+ # src/index.ts listens on it. Multi-stage build keeps the runtime image small
188
+ # (no dev dependencies, no TypeScript sources).
189
+
190
+ FROM node:20-slim AS build
191
+ WORKDIR /app
192
+ COPY package*.json ./
193
+ RUN npm ci
194
+ COPY tsconfig.json ./
195
+ COPY src ./src
196
+ RUN npm run build
197
+
198
+ FROM node:20-slim AS runtime
199
+ WORKDIR /app
200
+ ENV NODE_ENV=production
201
+ COPY package*.json ./
202
+ RUN npm ci --omit=dev
203
+ COPY --from=build /app/dist ./dist
204
+ EXPOSE 8080
205
+ CMD ["node", "dist/index.js"]
206
+ `;
207
+ const DOCKERIGNORE_TEMPLATE = `node_modules
208
+ dist
209
+ .env
210
+ .env.local
211
+ .git
212
+ *.log
213
+ .tmp
214
+ .specstory
215
+ `;
216
+ function buildEnvExample(usesNeon, sendsEmail) {
217
+ const dbLine = usesNeon
218
+ ? `# Neon Postgres pooled connection string (required). Per [[neon-postgres]],
219
+ # use the POOLED URL and keep /health DB-free so the compute scales to zero.
220
+ DATABASE_URL=postgresql://user:pass@host/db?sslmode=require
221
+ `
222
+ : `# Database URL (only if this service uses a database). For Neon Postgres, use
223
+ # the pooled connection string per [[neon-postgres]].
224
+ # DATABASE_URL=postgresql://user:pass@host/db?sslmode=require
225
+ `;
226
+ return `# {{slug}} — example environment variables.
227
+ # Copy to \`.env\` (gitignored) and fill in real values. Do NOT commit \`.env\`.
228
+
229
+ # Port the service listens on. Cloud Run overrides this at runtime; 8080 is the
230
+ # Cloud Run default and a sensible local default.
231
+ PORT=8080
232
+
233
+ ${dbLine}${sendsEmail ? EMAIL_ENV_BLOCK : ""}`;
234
+ }
235
+ const DRIZZLE_CONFIG_TEMPLATE = `import { defineConfig } from "drizzle-kit";
236
+
237
+ export default defineConfig({
238
+ schema: "./src/db/schema.ts",
239
+ out: "./drizzle",
240
+ dialect: "postgresql",
241
+ dbCredentials: {
242
+ url: process.env.DATABASE_URL!,
243
+ },
244
+ });
245
+ `;
246
+ const DB_INDEX_TEMPLATE = `// {{slug}} — Drizzle + Neon data layer.
247
+ //
248
+ // Lazy, import-safe DB handle. Per [[portable-stack]] §15, NEVER read
249
+ // DATABASE_URL at module-evaluation time — doing so crashes any import of this
250
+ // module (including the tests and the DB-free /health path) whenever the secret
251
+ // is absent. The client is built on first use and memoized.
252
+
253
+ import { neon } from "@neondatabase/serverless";
254
+ import { drizzle } from "drizzle-orm/neon-http";
255
+
256
+ import * as schema from "./schema.js";
257
+
258
+ let cached: ReturnType<typeof drizzle<typeof schema>> | undefined;
259
+
260
+ export function db(): ReturnType<typeof drizzle<typeof schema>> {
261
+ if (cached) return cached;
262
+ const url = process.env.DATABASE_URL;
263
+ if (!url) {
264
+ throw new Error(
265
+ "DATABASE_URL is not set. Set it in .env (local) or the Cloud Run service environment.",
266
+ );
267
+ }
268
+ cached = drizzle(neon(url), { schema });
269
+ return cached;
270
+ }
271
+ `;
272
+ const DB_SCHEMA_TEMPLATE = `// Drizzle schema for {{slug}}.
273
+ //
274
+ // Replace this placeholder table with the real schema as the service takes
275
+ // shape. Per [[portable-stack]], keep to standard Postgres types so the schema
276
+ // ports to any Postgres host (no Neon-/host-specific column types).
277
+
278
+ import { pgTable, serial, text, timestamp } from "drizzle-orm/pg-core";
279
+
280
+ export const example = pgTable("example", {
281
+ id: serial("id").primaryKey(),
282
+ name: text("name").notNull(),
283
+ createdAt: timestamp("created_at", { withTimezone: true })
284
+ .defaultNow()
285
+ .notNull(),
286
+ });
287
+ `;
288
+ export function scaffoldNodeService(inputs, opts) {
289
+ const spec = resolveBrandSpec(inputs);
290
+ const usesNeon = inputs.dbStrategy === "neon-postgres";
291
+ const sendsEmail = inputs.sendsEmail === true;
292
+ const base = commonBaseFiles(inputs, opts, buildNarrative(usesNeon));
293
+ const envExample = sub(buildEnvExample(usesNeon, sendsEmail), inputs, opts, spec);
294
+ const typeSpecific = [
295
+ { path: "package.json", content: sub(buildPackageJson(usesNeon, sendsEmail), inputs, opts, spec) },
296
+ { path: "tsconfig.json", content: sub(TSCONFIG_TEMPLATE, inputs, opts, spec) },
297
+ { path: "vitest.config.ts", content: sub(VITEST_CONFIG_TEMPLATE, inputs, opts, spec) },
298
+ { path: "src/index.ts", content: sub(SRC_INDEX_TEMPLATE, inputs, opts, spec) },
299
+ { path: "src/app.ts", content: sub(SRC_APP_TEMPLATE, inputs, opts, spec) },
300
+ {
301
+ path: "src/routes/health.ts",
302
+ content: sub(SRC_ROUTES_HEALTH_TEMPLATE, inputs, opts, spec),
303
+ },
304
+ {
305
+ path: "src/routes/health.test.ts",
306
+ content: sub(SRC_ROUTES_HEALTH_TEST_TEMPLATE, inputs, opts, spec),
307
+ },
308
+ { path: "Dockerfile", content: sub(DOCKERFILE_TEMPLATE, inputs, opts, spec) },
309
+ { path: ".dockerignore", content: DOCKERIGNORE_TEMPLATE },
310
+ { path: ".env.example", content: envExample },
311
+ { path: ".env", content: localEnvFrom(envExample, ".env", inputs.slug) },
312
+ ];
313
+ if (usesNeon) {
314
+ typeSpecific.push({ path: "drizzle.config.ts", content: sub(DRIZZLE_CONFIG_TEMPLATE, inputs, opts, spec) }, { path: "src/db/index.ts", content: sub(DB_INDEX_TEMPLATE, inputs, opts, spec) }, { path: "src/db/schema.ts", content: sub(DB_SCHEMA_TEMPLATE, inputs, opts, spec) });
315
+ }
316
+ if (sendsEmail) {
317
+ typeSpecific.push(...emailFiles(inputs, opts, spec, "node-service"));
318
+ }
319
+ return [...base, ...typeSpecific];
320
+ }
@@ -777,6 +777,6 @@ Crawls internal links starting at the root URL. Pass \`--external\` to also chec
777
777
 
778
778
  ---
779
779
 
780
- *Generated by \`@zero2webmaster/starter-kit --with-pro-seo\`. Updates ship via the Templates mirror at \`templates.z2w.us\` while your subscription is active.*
780
+ *Generated by \`@zero2webmaster/starter-kit --with-pro-seo\`. Updates ship with new releases of \`@zero2webmaster/starter-kit\` while your subscription is active.*
781
781
  `;
782
782
  }
@@ -29,7 +29,7 @@ name = "{{slug}}"
29
29
  version = "{{version}}"
30
30
  description = "{{description}}"
31
31
  authors = [
32
- { name = "{{author}}", url = "{{author_url}}" },
32
+ { name = "{{author}}" },
33
33
  ]
34
34
  readme = "README.md"
35
35
  requires-python = ">=3.11"
@@ -44,6 +44,9 @@ dev = [
44
44
  "httpx>=0.27",
45
45
  ]
46
46
 
47
+ [project.urls]
48
+ Homepage = "{{author_url}}"
49
+
47
50
  [build-system]
48
51
  requires = ["setuptools>=68", "wheel"]
49
52
  build-backend = "setuptools.build_meta"
@@ -142,7 +145,7 @@ export function scaffoldPythonService(inputs, opts) {
142
145
  // Python's local-env convention is `.env` (gitignored), not `.env.local`.
143
146
  typeSpecific.push({
144
147
  path: ".env",
145
- content: localEnvFrom(sub(ENV_EXAMPLE_TEMPLATE, inputs, opts, spec), ".env"),
148
+ content: localEnvFrom(sub(ENV_EXAMPLE_TEMPLATE, inputs, opts, spec), ".env", inputs.slug),
146
149
  });
147
150
  return [...base, ...typeSpecific];
148
151
  }
@@ -1,6 +1,6 @@
1
1
  import type { ProjectType, ScaffoldInputs } from "./index.js";
2
2
  import { type SubstitutionOptions } from "./substitute.js";
3
- export type StandardKey = "skill-vault" | "portable-stack" | "fathom" | "uptime-kuma" | "neon-careful" | "agent-coordination" | "seo-baseline" | "email-service" | "text-size";
3
+ export type StandardKey = "skill-vault" | "portable-stack" | "fathom" | "uptime-kuma" | "sentry" | "neon-careful" | "agent-coordination" | "seo-baseline" | "email-service" | "moderation" | "text-size" | "test-count";
4
4
  export type StandardDecisionState = "inserted-inline" | "skipped-not-applicable";
5
5
  export interface StandardDecision {
6
6
  key: StandardKey;
package/dist/standards.js CHANGED
@@ -16,12 +16,23 @@
16
16
  // more important issues exist")
17
17
  // - portable-stack — always for non-WP types
18
18
  // - fathom — if hasWebUi=true
19
- // - uptime-kuma — any deploy target (cf-worker, cf-pages, nextjs, python-service)
19
+ // - uptime-kuma — any deploy target (cf-worker, cf-pages, nextjs, python-service, node-service)
20
+ // - sentry — if hasObservability=true AND type is nextjs / cf-pages;
21
+ // the Sentry runtime-error/APM baseline per
22
+ // [[sentry-runtime-errors]] (requested by
23
+ // videomigrator-dashboard on the bulletin 2026-06-11)
20
24
  // - neon-careful — if dbStrategy=neon-postgres
21
25
  // - agent-coordination — if participateInBulletin=true
22
26
  // - seo-baseline — non-WP web UI with indexable surface (nextjs, cf-pages)
23
27
  // - email-service — every project that may send mail (skip library + protocol-repo)
28
+ // - moderation — if hasUserContent=true (skip wp-plugin + library + protocol-repo);
29
+ // the two-layer UGC-moderation baseline per [[moderation-system]]
30
+ // (requested by event-engine on the bulletin 2026-07-08)
24
31
  // - text-size — always (Z2W standing org rule)
32
+ // - test-count — always (Z2W standing org rule, 2026-06-20): every
33
+ // session reports its test count at session end in a
34
+ // stable greppable `Tests: {n} passing` line so the
35
+ // command center can tally a portfolio-wide total
25
36
  //
26
37
  // Pure-functional: no filesystem reads, no template lookups, no side effects.
27
38
  // The Step 6 writer composes this resolver's output with the per-type scaffolder
@@ -38,31 +49,54 @@ const STANDARD_ORDER = [
38
49
  "portable-stack",
39
50
  "fathom",
40
51
  "uptime-kuma",
52
+ "sentry",
41
53
  "neon-careful",
42
54
  "agent-coordination",
43
55
  "seo-baseline",
44
56
  "email-service",
57
+ "moderation",
45
58
  "text-size",
59
+ "test-count",
46
60
  ];
47
61
  const TITLES = {
48
62
  "skill-vault": "Skill Vault awareness",
49
63
  "portable-stack": "Portable-stack defaults (non-WP)",
50
64
  fathom: "Fathom analytics",
51
65
  "uptime-kuma": "Uptime Kuma monitor",
66
+ sentry: "Sentry runtime-error tracking (web app)",
52
67
  "neon-careful": "Neon-careful (Neon Postgres)",
53
68
  "agent-coordination": "Agent Coordination (cross-project bulletin)",
54
69
  "seo-baseline": "SEO baseline (non-WP web UI)",
55
70
  "email-service": "Email service selection",
71
+ moderation: "Moderation baseline (user-generated content)",
56
72
  "text-size": "Text size (readability)",
73
+ "test-count": "Test-count reporting (session end)",
57
74
  };
58
75
  const DEPLOY_TARGETS = [
59
76
  "cf-worker",
60
77
  "cf-pages",
61
78
  "nextjs",
62
79
  "python-service",
80
+ "node-service",
63
81
  ];
64
82
  const SEO_BASELINE_TYPES = ["nextjs", "cf-pages"];
83
+ // Types that get the Sentry runtime-error/APM baseline. Same set as the SEO
84
+ // baseline — a public/customer-facing HTML app is exactly where a per-user 500
85
+ // can fail silently (uptime monitoring only proves `/health` is 200). WordPress
86
+ // uses Admin Suite Diagnostics; Workers / node-service / python-service are
87
+ // API-only or non-JS-runtime and out of scope for the Next.js Sentry wizard;
88
+ // CLI libraries and protocol repos have no runtime request surface.
89
+ const OBSERVABILITY_TYPES = ["nextjs", "cf-pages"];
65
90
  const NO_EMAIL_TYPES = ["library", "protocol-repo"];
91
+ // Types with no user-generated-content surface to moderate. wp-plugin is
92
+ // excluded because WordPress moderates comments natively (and via Akismet), so
93
+ // the [[moderation-system]] pattern — a Next.js + Neon report→queue model —
94
+ // doesn't fit; library / protocol-repo have no content surface at all.
95
+ const NO_MODERATION_TYPES = [
96
+ "wp-plugin",
97
+ "library",
98
+ "protocol-repo",
99
+ ];
66
100
  function checkPortableStack(inputs) {
67
101
  if (inputs.projectType === "wp-plugin") {
68
102
  return {
@@ -106,6 +140,27 @@ function checkUptimeKuma(inputs) {
106
140
  reason: `${inputs.projectType} is a deploy target — Kuma monitor needed post-deploy`,
107
141
  };
108
142
  }
143
+ function checkSentry(inputs) {
144
+ // Explicit opt-in (or the interactive-flow smart default) gates the standard;
145
+ // an omitted flag reads as false so the programmatic API / --input path stay
146
+ // opt-in. Then narrow to the web-app types the Sentry wizard targets.
147
+ if (inputs.hasObservability !== true) {
148
+ return {
149
+ applies: false,
150
+ reason: "hasObservability=false — Sentry runtime-error tracking not wired at instantiation",
151
+ };
152
+ }
153
+ if (!OBSERVABILITY_TYPES.includes(inputs.projectType)) {
154
+ return {
155
+ applies: false,
156
+ reason: `${inputs.projectType} has no per-user request surface — Sentry runtime-error tracking N/A (WordPress uses Admin Suite Diagnostics)`,
157
+ };
158
+ }
159
+ return {
160
+ applies: true,
161
+ reason: `hasObservability=true on ${inputs.projectType} — Sentry runtime-error/APM baseline per [[sentry-runtime-errors]]`,
162
+ };
163
+ }
109
164
  function checkNeonCareful(inputs) {
110
165
  if (inputs.dbStrategy !== "neon-postgres") {
111
166
  return {
@@ -160,9 +215,33 @@ function checkEmailService(inputs) {
160
215
  reason: "any type that may send mail — route through [[email-service-router]]",
161
216
  };
162
217
  }
218
+ function checkModeration(inputs) {
219
+ if (!inputs.hasUserContent) {
220
+ return {
221
+ applies: false,
222
+ reason: "hasUserContent=false — no user-generated-content surface to moderate",
223
+ };
224
+ }
225
+ if (NO_MODERATION_TYPES.includes(inputs.projectType)) {
226
+ return {
227
+ applies: false,
228
+ reason: `${inputs.projectType} moderates content natively / has no UGC surface — [[moderation-system]] N/A`,
229
+ };
230
+ }
231
+ return {
232
+ applies: true,
233
+ reason: `hasUserContent=true on ${inputs.projectType} — two-layer moderation baseline per [[moderation-system]]`,
234
+ };
235
+ }
163
236
  function checkTextSize() {
164
237
  return { applies: true, reason: "Z2W standing org rule — applies to every project" };
165
238
  }
239
+ function checkTestCount() {
240
+ return {
241
+ applies: true,
242
+ reason: "Z2W standing org rule (2026-06-20) — every session reports its test count for the portfolio-wide tally",
243
+ };
244
+ }
166
245
  function checkSkillVault() {
167
246
  return {
168
247
  applies: true,
@@ -206,9 +285,28 @@ const FATHOM_BODY = `### Fathom analytics (web UI)
206
285
  const UPTIME_KUMA_BODY = `### Uptime Kuma monitor (deploy target)
207
286
 
208
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.`;
288
+ const SENTRY_BODY = `### Sentry runtime-error tracking (customer-facing web app)
289
+
290
+ > **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.**
291
+ >
292
+ > **The load-bearing decisions (summary — [[sentry-runtime-errors]] is authoritative):**
293
+ >
294
+ > 1. **Wire via the wizard, once:** \`npx @sentry/wizard@latest -i nextjs\` (add \`--saas --org <z2w-org> --project {{slug}}\` to skip prompts). It writes the client/server/edge config, the \`instrumentation.ts\` hook, and the build-time source-map upload.
295
+ > 2. **DSN lives in config, NOT an env var.** The DSN is a publishable identifier (not a secret) — hard-code it in the Sentry config files the wizard generates; do NOT introduce a \`NEXT_PUBLIC_SENTRY_DSN\`. The one real secret is \`SENTRY_AUTH_TOKEN\` (build-time source-map upload) — scope it **Production-only** in Vercel and keep it out of the client bundle.
296
+ > 3. **Feature-flag defaults:** Tracing sample rate 1.0 (100%) at Z2W volume; Session Replay 10% of sessions / 100% of sessions-with-errors; Logs on; \`sendDefaultPii: true\` — with the caveat that a Sentry payload then carries user IP + request headers, so never forward it verbatim into a shared surface (e.g. the bulletin \`## Incidents\` pipe strips to summary + link + timestamp).
297
+ > 4. **Smoke it, then delete the smoke.** Add a throwaway auth-gated server-throw route (\`/api/boom\` style), confirm the error + replay land in Sentry and the alert email fires, then DELETE the route and the wizard's noisy example page (it's a honeypot that inflates your error count). Ship this cleanup as its own small commit.
298
+ > 5. **2025 Sentry-UI quirks that waste time:** issue **alert rules** live at \`/alerts/rules/\` (NOT \`/monitors/alerts/\`); the "Test Notification" button does NOT auto-save the rule (save explicitly or it evaporates); the wizard's example page throws on every load until you remove it.
299
+ >
300
+ > **When to SKIP (do not wire Sentry):** WordPress sites (error tracking via Z2W Admin Suite Diagnostics + FluentSMTP logs); CLI libraries and protocol repos (no request surface); Cloudflare Workers / node-service / python-service that are API-only (the \`-i nextjs\` wizard doesn't fit — revisit per-runtime later); internal-only admin tools with a single operator who sees errors directly. The rule of thumb: wire it for any public-or-customer-facing Next.js / CF-Pages app that will have real users.
301
+ >
302
+ > See [[sentry-runtime-errors]] for the wizard answers, the config-file layout, the alert-rule setup, and the smoke-route pattern. Companion: [[uptime-kuma-monitor]] (liveness — the other half of observability), [[fathom-analytics]] (analytics, not errors).`;
209
303
  const NEON_CAREFUL_BODY = `### Neon-careful (Neon Postgres)
210
304
 
211
- > **Neon discipline:** \`/health\` must NOT touch the database (Neon Free has a 100 CU-hour monthly quota; routine probes burn through it). Pool size 1 for monitoring contexts. No scheduled jobs querying DB more than absolutely necessary. See [[neon-postgres]] for the full discipline.`;
305
+ > **Neon discipline:** \`/health\` must NOT touch the database (Neon Free has a 100 CU-hour monthly quota; routine probes burn through it). Pool size 1 for monitoring contexts. No scheduled jobs querying DB more than absolutely necessary.
306
+ >
307
+ > **Queue/outbox drain — inline, never a frequent poll:** if a queue or outbox is fed by this app's OWN writes, drain it INLINE on the compute the write already woke (Cloudflare Workers: \`ctx.waitUntil(drain())\` after the response is sent; a Node/long-running service: a fire-and-forget drain after the write commits) — a DB-touching cron's cost is its WAKE-UPS, not its row volume, so riding an existing wake costs zero extra CU-hours and ships the row in seconds. Any cron drainer stays a LOW-frequency backstop (daily, not minutes) that only sweeps rows whose send failed; keep per-row claims under \`FOR UPDATE SKIP LOCKED\` so an inline drain and a backstop tick can't double-send. (financial-engine cut an outbox from ~15 → ~0.6 CU-hr/mo/tenant — ~25× — this way.)
308
+ >
309
+ > See [[neon-postgres]] for the full discipline (§4.4 covers the inline-drain pattern).`;
212
310
  const AGENT_COORDINATION_BODY = `### Agent Coordination (cross-project bulletin participation)
213
311
 
214
312
  > **Cross-project coordination:** This project participates in the Z2W cross-project coordination bulletin at \`zero2webmaster/z2w-agent-coordination\`. The canonical protocol body lives in that repo's \`AGENT_PROTOCOL.md\` — read it at session start for the current version and section list. Reference conventions by NAME — the §-numbers below are parenthetical breadcrumbs that may renumber upstream.
@@ -277,32 +375,54 @@ const SEO_BASELINE_BODY = `### SEO baseline (non-WP web UI)
277
375
  const EMAIL_SERVICE_BODY = `### Email service selection (any project that will send mail)
278
376
 
279
377
  > **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.`;
378
+ const MODERATION_BODY = `### Moderation baseline (user-generated content)
379
+
380
+ > **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.
381
+ >
382
+ > **The load-bearing decisions (summary — [[moderation-system]] is the binding contract):**
383
+ >
384
+ > 1. **One entity-agnostic queue, not per-type tables.** Key everything on \`{entity_type, entity_id}\`: a shared \`moderation_items\` queue (one row per flagged entity, \`UNIQUE (tenant_id, entity_type, entity_id)\`) plus a \`reports\` table where reports AND AI flags COALESCE into that one item (idempotent per reporter so nobody inflates the count). Adding a new content type is a CHECK edit, not a new set of tables + UI.
385
+ > 2. **Reporting is a SAFETY action, not tier-gated.** Any signed-in member may report (like blocking) regardless of membership tier; only the queue + staff actions are admin-only. **Public / anonymous UGC surface?** Use the public variant — no auth on the report action, resolve the tenant from the Host, key idempotency on \`reporter_email\` instead of a user id.
386
+ > 3. **Enforcement REUSES existing gates — don't invent new ones.** Hide = the soft-delete (\`deletedAt\`) already on your content tables; restrict (read-only) = the membership/tier resolver (make that check FAIL-OPEN so a DB blip never locks the community out of writing); ban = the existing \`is_active\` session gate.
387
+ > 4. **The AI content scan is a FAIL-OPEN SEAM.** Run it out-of-band (Next.js \`after()\`), never blocking or slowing a write; keep it DORMANT until an API key is set; make it one swappable call (the Anthropic SDK today, z2w-ai-engine's content-moderation capability later). A scan outage must never block posting.
388
+ > 5. **Optional pre-publish gate.** For content with a \`draft → published\` lifecycle, an unresolved flag blocks publish — turning the AI scan into a mandatory pre-publication gate.
389
+ >
390
+ > **Cross-app note:** for a future shared moderation package, map the tenant key at the boundary (event-engine keys on \`org_id\`, z2w-social on \`tenant_id\` — same idea, rename where they meet). See [[moderation-system]] for the data model, the coalescing pattern, the entity-resolver seam, and the verification checklist. Companion skills: [[async-action-feedback]] (the Report button + dashboard feedback), [[neon-postgres]] (run the scan out-of-band so it doesn't pin compute), [[per-tenant-credential-vault]] (where the scan API key lives long-term).`;
280
391
  const TEXT_SIZE_BODY = `### Text size (always)
281
392
 
282
393
  > **Readability:** per Z2W standing org rule, all public-facing pages and documents use large, easy-to-read type. Body text 18px+ baseline; headings proportionally larger; line-height ≥ 1.5.`;
394
+ const TEST_COUNT_BODY = `### Test-count reporting (always — at session end)
395
+
396
+ > **Report your test count at session end.** Per Zero2Webmaster standing org rule (2026-06-20), every session that touches code states how many tests pass on a stable, machine-greppable line: \`Tests: {n} passing\` — use the literal word \`Tests:\`, the running total your suite reports, and the word \`passing\`. Put that line in your session-end recap AND, if this project participates in the cross-project bulletin, in the \`## Recent commits\` entry you append (e.g. **\`Tests: 534 passing\`**). The phone-first command center greps this line across every project to display a portfolio-wide tally ("we've run N tests across the portfolio") — a real sales asset, and the uniform one-line format is what makes the total cheap to compute. If this project has no test suite yet, say so explicitly with \`Tests: none yet\` rather than omitting the line.`;
283
397
  const BODIES = {
284
398
  "skill-vault": SKILL_VAULT_BODY,
285
399
  "portable-stack": PORTABLE_STACK_BODY,
286
400
  fathom: FATHOM_BODY,
287
401
  "uptime-kuma": UPTIME_KUMA_BODY,
402
+ sentry: SENTRY_BODY,
288
403
  "neon-careful": NEON_CAREFUL_BODY,
289
404
  "agent-coordination": AGENT_COORDINATION_BODY,
290
405
  "seo-baseline": SEO_BASELINE_BODY,
291
406
  "email-service": EMAIL_SERVICE_BODY,
407
+ moderation: MODERATION_BODY,
292
408
  "text-size": TEXT_SIZE_BODY,
409
+ "test-count": TEST_COUNT_BODY,
293
410
  };
294
411
  const APPLICABILITY = {
295
412
  "skill-vault": checkSkillVault,
296
413
  "portable-stack": checkPortableStack,
297
414
  fathom: checkFathom,
298
415
  "uptime-kuma": checkUptimeKuma,
416
+ sentry: checkSentry,
299
417
  "neon-careful": checkNeonCareful,
300
418
  "agent-coordination": checkAgentCoordination,
301
419
  "seo-baseline": checkSeoBaseline,
302
420
  "email-service": checkEmailService,
421
+ moderation: checkModeration,
303
422
  "text-size": checkTextSize,
423
+ "test-count": checkTestCount,
304
424
  };
305
- const PREAMBLE = `The following organization standards apply to {{slug}}. Each was selected at instantiation per the conditional rules in [[instantiate-z2w-project]] v1.1.0 Step 6. See each standard's wiki-style link for the full discipline; the inline summaries below are the binding contract for this project.`;
425
+ const PREAMBLE = `The following organization standards apply to {{slug}}. Each was selected at instantiation per the conditional rules in the [[instantiate-z2w-project]] skill (Step 6). See each standard's wiki-style link for the full discipline; the inline summaries below are the binding contract for this project.`;
306
426
  const NO_APPLICABLE_FALLBACK = `*(No conditional standards apply to this project.)*`;
307
427
  /**
308
428
  * Render one standard's body with substitutions applied. The `fathom_env_var`
@@ -9,6 +9,14 @@ export interface SubstitutionOptions {
9
9
  date?: string;
10
10
  /** Override the brand spec resolution (used by tests + callers that already resolved it). */
11
11
  brandSpec?: BrandPresetSpec;
12
+ /**
13
+ * Framework version to stamp into `{{framework_version}}`. The writer resolves
14
+ * this from the canonical AGENTS body's *filename* (the single source of truth)
15
+ * and passes it through. When omitted, falls back to
16
+ * {@link frameworkVersionForType} so callers that don't read a template (tests,
17
+ * standalone substitution) still get a sensible value.
18
+ */
19
+ frameworkVersion?: string;
12
20
  }
13
21
  /** Today's date as `YYYY-MM-DD` in the local timezone. */
14
22
  export declare function todayISODate(): string;
@@ -25,9 +33,12 @@ export declare function pascalCaseFromSlug(slug: string): string;
25
33
  */
26
34
  export declare function upperSnakeFromSlug(slug: string): string;
27
35
  /**
28
- * Framework version embedded in the scaffolded CLAUDE.md header. WordPress
29
- * plugins inherit from the WP AGENTS template (v3.1.0); everything else
30
- * inherits from the generic AGENTS template (v2.13.0).
36
+ * Fallback framework version embedded in the scaffolded CLAUDE.md header when
37
+ * no `frameworkVersion` is supplied. The writer normally derives the real
38
+ * version from the resolved AGENTS body's filename and passes it via
39
+ * {@link SubstitutionOptions.frameworkVersion}; this hardcoded mapping only
40
+ * applies to callers that don't read a template (e.g. tests). WordPress plugins
41
+ * map to the WP AGENTS line; everything else to the generic line.
31
42
  */
32
43
  export declare function frameworkVersionForType(projectType: ProjectType): string;
33
44
  /**
@@ -44,12 +44,15 @@ export function upperSnakeFromSlug(slug) {
44
44
  return underscoredSlug(slug).toUpperCase();
45
45
  }
46
46
  /**
47
- * Framework version embedded in the scaffolded CLAUDE.md header. WordPress
48
- * plugins inherit from the WP AGENTS template (v3.1.0); everything else
49
- * inherits from the generic AGENTS template (v2.13.0).
47
+ * Fallback framework version embedded in the scaffolded CLAUDE.md header when
48
+ * no `frameworkVersion` is supplied. The writer normally derives the real
49
+ * version from the resolved AGENTS body's filename and passes it via
50
+ * {@link SubstitutionOptions.frameworkVersion}; this hardcoded mapping only
51
+ * applies to callers that don't read a template (e.g. tests). WordPress plugins
52
+ * map to the WP AGENTS line; everything else to the generic line.
50
53
  */
51
54
  export function frameworkVersionForType(projectType) {
52
- return projectType === "wp-plugin" ? "3.1.0" : "2.13.0";
55
+ return projectType === "wp-plugin" ? "3.2.0" : "2.14.0";
53
56
  }
54
57
  function resolveDate(opts) {
55
58
  const supplied = opts.date;
@@ -89,7 +92,7 @@ export function buildSubstitutionMap(inputs, opts = {}) {
89
92
  date,
90
93
  year: date.slice(0, 4),
91
94
  version: SCAFFOLD_VERSION,
92
- framework_version: frameworkVersionForType(inputs.projectType),
95
+ framework_version: opts.frameworkVersion ?? frameworkVersionForType(inputs.projectType),
93
96
  };
94
97
  }
95
98
  /**