@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.
package/dist/index.js CHANGED
@@ -1,10 +1,159 @@
1
1
  // z2w-starter-kit programmatic API.
2
2
  //
3
- // This module exports the same scaffolding logic the CLI uses, so callers
4
- // (e.g., the future Tier B SaaS, integration tests, or other Z2W tools) can
5
- // invoke it without spawning a subprocess.
3
+ // This module is the package's public entry point. It exports the same
4
+ // scaffolding logic the CLI uses so callers — the future Tier B web UI
5
+ // (`project-creator`, see _project-briefs/z2w-project-creator-brief.md),
6
+ // integration tests, or any other Z2W tool — can invoke it in-process without
7
+ // spawning `npx`. Two entry points cover the common needs:
6
8
  //
7
- export const version = "0.2.1";
8
- export async function scaffold(_inputs) {
9
- throw new Error("scaffold() is not yet implemented. See ROADMAP.md (Step 3+).");
9
+ // • `scaffold(inputs, opts?)` — write a full project to disk.
10
+ // • `previewScaffold(inputs, opts?)` — compose the same file list WITHOUT
11
+ // touching disk or writing to stdout,
12
+ // returning the files as data (what a
13
+ // web preview / server consumer wants).
14
+ //
15
+ // plus `validateScaffoldInputs(inputs)` for cheap structural validation before
16
+ // either, and re-exports of the lower-level building blocks (`writeScaffold`,
17
+ // `resolveStandards`, `scaffoldByType`, `parseScaffoldInputs`, …) so consumers
18
+ // import from the package root instead of deep-importing dist internals.
19
+ //
20
+ import * as path from "node:path";
21
+ import { Writable } from "node:stream";
22
+ import { isValidSlug } from "./parse-brief.js";
23
+ import { writeScaffold } from "./writer.js";
24
+ export const version = "0.3.0";
25
+ // Canonical enum value-arrays. These live here, next to the type unions they
26
+ // enumerate, so both the CLI's confirm/wizard flows (which re-export them) and
27
+ // the programmatic `validateScaffoldInputs` share one source of truth. Keep
28
+ // each array in sync with its union above.
29
+ export const PROJECT_TYPES = [
30
+ "wp-plugin",
31
+ "cf-worker",
32
+ "cf-pages",
33
+ "nextjs",
34
+ "python-service",
35
+ "node-service",
36
+ "library",
37
+ "protocol-repo",
38
+ ];
39
+ export const BRANDS = [
40
+ "save-the-frogs",
41
+ "bansuri-bliss",
42
+ "zero2webmaster",
43
+ "custom",
44
+ ];
45
+ export const DB_STRATEGIES = [
46
+ "none",
47
+ "neon-postgres",
48
+ "supabase",
49
+ "sqlite",
50
+ "mysql-wp",
51
+ "other",
52
+ ];
53
+ function toResult(r) {
54
+ return { files: r.filesWritten, decisions: r.decisions, targetPath: r.targetPath };
55
+ }
56
+ /**
57
+ * Scaffold a full project to disk and return the composed result.
58
+ *
59
+ * The high-level programmatic equivalent of `npx @zero2webmaster/starter-kit
60
+ * init` for a caller that already has validated {@link ScaffoldInputs} (e.g.
61
+ * from {@link parseScaffoldInputs} + {@link validateScaffoldInputs}). Delegates
62
+ * to {@link writeScaffold}; the canonical AGENTS body + standards are read and
63
+ * composed exactly as the CLI does. Throws `WriterError` on a non-absolute or
64
+ * (by default) non-empty target, or if any template marker / `{{placeholder}}`
65
+ * survives composition.
66
+ */
67
+ export async function scaffold(inputs, opts = {}) {
68
+ const result = await writeScaffold(inputs, opts.targetPath ?? inputs.targetPath, {
69
+ dryRun: false,
70
+ refuseNonEmpty: opts.refuseNonEmpty,
71
+ templatesPath: opts.templatesPath,
72
+ date: opts.date,
73
+ withProSeo: opts.withProSeo,
74
+ });
75
+ return toResult(result);
76
+ }
77
+ /**
78
+ * Compose the exact same file list {@link scaffold} would write, but WITHOUT
79
+ * touching the filesystem and without printing anything — the files are
80
+ * returned as data. This is the entry point a web UI / server consumer wants:
81
+ * show the user what they'll get (file tree, standards inserted) before they
82
+ * commit to creating a repo.
83
+ *
84
+ * The only I/O is reading the Templates folder (needed to fill the AGENTS
85
+ * body). `inputs.targetPath` (or `opts.targetPath`) must still be an absolute
86
+ * path — it's used only to validate that every generated file resolves inside
87
+ * it; nothing is created there. `refuseNonEmpty` is not consulted.
88
+ */
89
+ export async function previewScaffold(inputs, opts = {}) {
90
+ // Discard the dry-run banner/file-list writeScaffold emits — we return the
91
+ // files as structured data instead of printing them.
92
+ const sink = new Writable({ write(_chunk, _enc, cb) { cb(); } });
93
+ const result = await writeScaffold(inputs, opts.targetPath ?? inputs.targetPath, {
94
+ dryRun: true,
95
+ templatesPath: opts.templatesPath,
96
+ date: opts.date,
97
+ withProSeo: opts.withProSeo,
98
+ output: sink,
99
+ });
100
+ return toResult(result);
101
+ }
102
+ /**
103
+ * Structurally validate a {@link ScaffoldInputs} without touching the
104
+ * filesystem, collecting ALL problems (not just the first). Complements
105
+ * {@link parseScaffoldInputs}, which checks primitive types + required-field
106
+ * presence but deliberately does NOT check the slug regex, enum membership, or
107
+ * that `targetPath` is absolute — this does, so a server can reject a bad form
108
+ * submission with a complete error list before attempting a scaffold.
109
+ *
110
+ * Note: does not check that `targetPath` is empty/writable on disk — that's an
111
+ * async filesystem concern the CLI's confirm flow owns, and `scaffold` enforces
112
+ * it at write time via `refuseNonEmpty`.
113
+ */
114
+ export function validateScaffoldInputs(inputs) {
115
+ const errors = [];
116
+ if (typeof inputs.slug !== "string" || !isValidSlug(inputs.slug)) {
117
+ errors.push(`slug ${JSON.stringify(inputs.slug)} is invalid: must match ^[a-z][a-z0-9-]{2,49}$ with no -v<n> version suffix.`);
118
+ }
119
+ if (typeof inputs.description !== "string" || inputs.description.trim().length === 0) {
120
+ errors.push(`description must be a non-empty string.`);
121
+ }
122
+ if (!PROJECT_TYPES.includes(inputs.projectType)) {
123
+ errors.push(`projectType ${JSON.stringify(inputs.projectType)} is invalid: expected one of ${PROJECT_TYPES.join(", ")}.`);
124
+ }
125
+ if (!BRANDS.includes(inputs.brand)) {
126
+ errors.push(`brand ${JSON.stringify(inputs.brand)} is invalid: expected one of ${BRANDS.join(", ")}.`);
127
+ }
128
+ if (!DB_STRATEGIES.includes(inputs.dbStrategy)) {
129
+ errors.push(`dbStrategy ${JSON.stringify(inputs.dbStrategy)} is invalid: expected one of ${DB_STRATEGIES.join(", ")}.`);
130
+ }
131
+ if (typeof inputs.githubOrg !== "string" || inputs.githubOrg.trim().length === 0) {
132
+ errors.push(`githubOrg must be a non-empty string.`);
133
+ }
134
+ if (typeof inputs.targetPath !== "string" || !path.isAbsolute(inputs.targetPath)) {
135
+ errors.push(`targetPath must be an absolute path. Got: ${JSON.stringify(inputs.targetPath)}.`);
136
+ }
137
+ if (inputs.brand === "custom") {
138
+ const cb = inputs.customBrand;
139
+ if (!cb || typeof cb !== "object") {
140
+ errors.push(`brand is "custom" but customBrand is missing.`);
141
+ }
142
+ else {
143
+ for (const k of ["brandName", "brandNameRule", "primaryColor", "accentColor"]) {
144
+ if (typeof cb[k] !== "string" || cb[k].trim().length === 0) {
145
+ errors.push(`customBrand.${k} must be a non-empty string when brand is "custom".`);
146
+ }
147
+ }
148
+ }
149
+ }
150
+ return { ok: errors.length === 0, errors };
10
151
  }
152
+ // ── Public re-exports ────────────────────────────────────────────────────────
153
+ // The building blocks the CLI composes, surfaced at the package root so
154
+ // programmatic consumers import from one place rather than deep-importing
155
+ // `dist/` internals.
156
+ export { writeScaffold };
157
+ export { parseScaffoldInputs, loadScaffoldInputs, WriterError } from "./writer.js";
158
+ export { resolveStandards, applyStandardsBlock, fathomEnvVarFor } from "./standards.js";
159
+ export { scaffoldByType } from "./scaffolders/index.js";
@@ -0,0 +1,137 @@
1
+ import { type ScaffoldInputs } from "./index.js";
2
+ /** The Neon `projects` table the inventory rows live in. */
3
+ export declare const INVENTORY_TABLE = "projects";
4
+ /** The conflict key — the `projects/{slug}.md` filename the cron keys on. */
5
+ export declare const INVENTORY_CONFLICT_KEY = "slug";
6
+ export interface InventoryConfig {
7
+ /** Postgres connection string (Neon pooled "Connection String"). */
8
+ databaseUrl: string;
9
+ }
10
+ /**
11
+ * Resolve the Neon inventory config from the environment. Returns null when no
12
+ * Z2W_INVENTORY_DATABASE_URL is set — the signal that the Neon write is disabled
13
+ * for this caller (every CLI user who isn't Kerry). Mirrors
14
+ * `resolveAirtableConfig`'s no-op gate exactly.
15
+ */
16
+ export declare function resolveInventoryConfig(env?: NodeJS.ProcessEnv): InventoryConfig | null;
17
+ /** A single column's value. The `projects` columns we write are text or boolean. */
18
+ export type ProjectRowValue = string | boolean;
19
+ /** A row's CLI-owned columns, keyed by their snake_case Neon column name. */
20
+ export type ProjectRow = Record<string, ProjectRowValue>;
21
+ export interface BuildProjectRowOptions {
22
+ /**
23
+ * Whether the freshly-written scaffold was confirmed to carry the
24
+ * coordination block (see `scaffoldCarriesCoordinationBlock`). Same semantics
25
+ * as the Airtable mapper: a boolean gates the `agent_coordination = Registered`
26
+ * assertion ("verify, don't assert"); `undefined` (could not verify — dry-run
27
+ * or a direct unit-test call) falls back to the `participateInBulletin` flag.
28
+ */
29
+ coordinationVerified?: boolean;
30
+ }
31
+ /**
32
+ * Pure mapping from ScaffoldInputs to the Neon `projects` row. Mirrors the
33
+ * decisions in src/airtable.ts `buildProjectFields`, mapped to the FINAL 23-column
34
+ * snake_case schema (column audit executed 2026-06-22). Only columns the CLI can
35
+ * auto-fill at scaffold time are written — manually-curated columns (technology,
36
+ * licensing, notes, research_url, …) are intentionally omitted so the UPSERT's
37
+ * DO UPDATE never clobbers Kerry's hand-entered values.
38
+ *
39
+ * Difference from the Airtable mapper: `project_type` IS written here (the Neon
40
+ * column is plain text and the CLI knows the value, so it earns its place per the
41
+ * column-audit principle "a column earns its place only if the CLI can auto-fill
42
+ * it"). The Airtable mapper omitted it only because that base's Project Type is a
43
+ * single-select whose option names could 422 on first use. `skill_vault_aware` is
44
+ * a real boolean here (Neon column type), not the Airtable "Yes" string.
45
+ */
46
+ export declare function buildProjectRow(inputs: ScaffoldInputs, opts?: BuildProjectRowOptions): ProjectRow;
47
+ /**
48
+ * A well-formed inventory slug: lowercase letters, digits, and hyphens only.
49
+ * This mirrors the coordination bulletin's `projects/{slug}.md` filename
50
+ * convention (the slug IS the filename), and rejects the historical CSV-imported
51
+ * junk the 2026-07-05 registry data-hygiene sweep found — e.g. `"Skill Vault"`
52
+ * (space + capitals) or `"Website - VimeoBunny"`. The CLI's input-side
53
+ * `project_slug` rule is stricter still (`^[a-z][a-z0-9-]{2,49}$`); this is the
54
+ * looser floor the inventory row must clear before it is written.
55
+ */
56
+ export declare const INVENTORY_SLUG_RE: RegExp;
57
+ /**
58
+ * A well-formed GitHub URL: exactly `https://github.com/{owner}/{repo}` with no
59
+ * trailing slash or path. Rejects the malformed values the hygiene sweep found —
60
+ * a missing scheme (`github.com/owner/repo`, `owner/repo`) or a trailing slash
61
+ * (`.../website-aharon/`). Owner/repo allow the GitHub-legal set `[A-Za-z0-9_.-]`.
62
+ */
63
+ export declare const INVENTORY_GITHUB_URL_RE: RegExp;
64
+ /**
65
+ * Validate the CLI-owned fields of a would-be inventory row. Returns a list of
66
+ * human-readable problems (empty = valid). Called before every write so a
67
+ * malformed `slug` / `github_url` can never be UPSERTed into the registry — the
68
+ * prevention half of the 2026-07-05 `z2w-agent-coordination` data-hygiene ask.
69
+ */
70
+ export declare function validateProjectRow(row: ProjectRow): string[];
71
+ export interface UpsertStatement {
72
+ /** The parameterized SQL (column names are code-controlled — injection-safe). */
73
+ sql: string;
74
+ /** Positional parameter values, in $1..$n order. */
75
+ params: ProjectRowValue[];
76
+ /** The columns written, in order — for a secret-free dry-run preview. */
77
+ columns: string[];
78
+ }
79
+ /**
80
+ * Build the INSERT … ON CONFLICT (slug) DO UPDATE statement from a row. Column
81
+ * names come from `buildProjectRow` (our own code, never user input), so string
82
+ * interpolation of column names is injection-safe; all VALUES are parameterized.
83
+ * The DO UPDATE set list excludes `slug` (the conflict key) and touches only the
84
+ * columns present in `row`, so columns the CLI doesn't manage are never altered.
85
+ * `updated_at` is left to the table's auto-touch trigger.
86
+ */
87
+ export declare function buildUpsert(row: ProjectRow): UpsertStatement;
88
+ export type NeonOutcome = "upserted" | "dry-run" | "skipped" | "failed";
89
+ export interface RegisterNeonResult {
90
+ outcome: NeonOutcome;
91
+ /** The row that was (or would be) written. */
92
+ row: ProjectRow;
93
+ /** The UPSERT SQL (column names only — never contains the connection string). */
94
+ sql?: string;
95
+ /** The created/updated row id, when outcome === "upserted". */
96
+ recordId?: string | number;
97
+ /** Human-readable, secret-free line for the CLI to surface. */
98
+ message: string;
99
+ /**
100
+ * Result of the on-disk coordination-block check, when it ran. `undefined`
101
+ * when verification was not attempted (dry-run / no targetPath / non-participant).
102
+ */
103
+ coordinationVerified?: boolean;
104
+ }
105
+ /** Query seam: run parameterized SQL, resolve to the RETURNING rows. */
106
+ export type QueryFn = (sql: string, params: ProjectRowValue[]) => Promise<Array<Record<string, unknown>>>;
107
+ export interface RegisterNeonOptions {
108
+ env?: NodeJS.ProcessEnv;
109
+ /** Build the statement but do not execute — for `init --dry-run`. */
110
+ dryRun?: boolean;
111
+ /**
112
+ * Override config explicitly (tests). When provided (including `null`),
113
+ * bypasses env resolution. `null` forces the "skipped" path.
114
+ */
115
+ config?: InventoryConfig | null;
116
+ /** Test/override seam for the DB client. Defaults to the Neon HTTP driver. */
117
+ queryImpl?: QueryFn;
118
+ /**
119
+ * Absolute path to the freshly-written scaffold. When provided (and not a
120
+ * dry-run) for a participating project, the coordination block is grep-verified
121
+ * on disk before `agent_coordination = Registered` is asserted.
122
+ */
123
+ targetPath?: string;
124
+ /** Test seam for the filesystem read used by coordination verification. */
125
+ readFileImpl?: (path: string) => Promise<string>;
126
+ }
127
+ /**
128
+ * UPSERT the inventory row for a freshly-scaffolded project into Neon.
129
+ * Warn-and-proceed: always resolves (never rejects); the CLI surfaces `message`
130
+ * and continues.
131
+ *
132
+ * - No Z2W_INVENTORY_DATABASE_URL → outcome "skipped" (silent for normal users).
133
+ * - opts.dryRun → outcome "dry-run" (prints the would-be SQL).
134
+ * - success → outcome "upserted" (+ recordId).
135
+ * - query error → outcome "failed" (+ a diagnostic; row NOT written).
136
+ */
137
+ export declare function registerProjectRowNeon(inputs: ScaffoldInputs, opts?: RegisterNeonOptions): Promise<RegisterNeonResult>;
@@ -0,0 +1,258 @@
1
+ // z2w-starter-kit Neon inventory write-path (project-inventory migration P3).
2
+ //
3
+ // The project inventory is migrating off Airtable onto Neon Postgres (the Neon
4
+ // project "software-projects" / project_id super-feather-66275632, table
5
+ // `projects`, keyed UNIQUE on `slug`). When a project is scaffolded, write its
6
+ // row to Neon so the coordination drift/gap cron and the agents.z2w.us command
7
+ // center can read it without Kerry maintaining an Airtable base. This runs
8
+ // ALONGSIDE the Airtable write during the transition (dual-write); the Airtable
9
+ // write is dropped later at migration phase P6.
10
+ //
11
+ // SAFETY / public-distribution posture: this is a PUBLIC npm package; the
12
+ // inventory DB is Kerry's PRIVATE Neon project. The write is gated entirely on
13
+ // the presence of Z2W_INVENTORY_DATABASE_URL in the environment — a customer
14
+ // who has no connection string never writes anything (resolveInventoryConfig
15
+ // returns null → outcome "skipped", silent). This mirrors the AIRTABLE_WRITE_PAT
16
+ // gate in src/airtable.ts exactly. The call NEVER blocks or fails a scaffold
17
+ // (warn-and-proceed): the row can always be added later, and the READ-side
18
+ // consumers pick it up on their next sweep regardless.
19
+ //
20
+ // Driver: @neondatabase/serverless `neon()` — one-shot HTTP queries, NO
21
+ // connection pooling, so a single scaffold opens no long-lived connection and
22
+ // Neon stays scaled to zero ([[neon-postgres]] discipline). The connection
23
+ // string is never printed.
24
+ //
25
+ // Patterns mirror src/airtable.ts: a pure mapper (buildProjectRow), an env
26
+ // resolver (resolveInventoryConfig), and an orchestrator (registerProjectRowNeon)
27
+ // with a queryImpl / config test seam that never throws. The on-disk
28
+ // "verify, don't assert" coordination check is shared with the Airtable path
29
+ // (scaffoldCarriesCoordinationBlock, imported from ./airtable.js).
30
+ import { neon } from "@neondatabase/serverless";
31
+ import { scaffoldCarriesCoordinationBlock, displayNameFromSlug } from "./airtable.js";
32
+ /** The Neon `projects` table the inventory rows live in. */
33
+ export const INVENTORY_TABLE = "projects";
34
+ /** The conflict key — the `projects/{slug}.md` filename the cron keys on. */
35
+ export const INVENTORY_CONFLICT_KEY = "slug";
36
+ /**
37
+ * Resolve the Neon inventory config from the environment. Returns null when no
38
+ * Z2W_INVENTORY_DATABASE_URL is set — the signal that the Neon write is disabled
39
+ * for this caller (every CLI user who isn't Kerry). Mirrors
40
+ * `resolveAirtableConfig`'s no-op gate exactly.
41
+ */
42
+ export function resolveInventoryConfig(env = process.env) {
43
+ const databaseUrl = (env["Z2W_INVENTORY_DATABASE_URL"] ?? "").trim();
44
+ if (!databaseUrl)
45
+ return null;
46
+ return { databaseUrl };
47
+ }
48
+ /**
49
+ * Pure mapping from ScaffoldInputs to the Neon `projects` row. Mirrors the
50
+ * decisions in src/airtable.ts `buildProjectFields`, mapped to the FINAL 23-column
51
+ * snake_case schema (column audit executed 2026-06-22). Only columns the CLI can
52
+ * auto-fill at scaffold time are written — manually-curated columns (technology,
53
+ * licensing, notes, research_url, …) are intentionally omitted so the UPSERT's
54
+ * DO UPDATE never clobbers Kerry's hand-entered values.
55
+ *
56
+ * Difference from the Airtable mapper: `project_type` IS written here (the Neon
57
+ * column is plain text and the CLI knows the value, so it earns its place per the
58
+ * column-audit principle "a column earns its place only if the CLI can auto-fill
59
+ * it"). The Airtable mapper omitted it only because that base's Project Type is a
60
+ * single-select whose option names could 422 on first use. `skill_vault_aware` is
61
+ * a real boolean here (Neon column type), not the Airtable "Yes" string.
62
+ */
63
+ export function buildProjectRow(inputs, opts = {}) {
64
+ const row = {
65
+ slug: inputs.slug,
66
+ project_name: displayNameFromSlug(inputs.slug),
67
+ status: "Active",
68
+ creation_method: "Z2W Starter Kit",
69
+ project_type: inputs.projectType,
70
+ // Write the conventional URL even if `gh repo create` is deferred — the
71
+ // inventory's slug-resolution needs it.
72
+ github_url: `https://github.com/${inputs.githubOrg}/${inputs.slug}`,
73
+ // skill-vault is an always-on standard in every scaffold (ROADMAP Step 15);
74
+ // the Neon column is a real boolean.
75
+ skill_vault_aware: true,
76
+ };
77
+ // Only assert agent_coordination = Registered when the scaffold actually
78
+ // carries the coordination block; otherwise leave it unset for Kerry. When the
79
+ // caller verified the scaffold on disk (coordinationVerified is a boolean),
80
+ // honor it; when it couldn't (undefined), trust the input flag.
81
+ if (inputs.participateInBulletin && (opts.coordinationVerified ?? true)) {
82
+ row["agent_coordination"] = "Registered";
83
+ }
84
+ // Kerry's standing rule: every inventory row carries its instantiation prompt.
85
+ const prompt = inputs.instantiationPrompt?.trim();
86
+ if (prompt) {
87
+ row["project_instantiation_prompt"] = prompt;
88
+ }
89
+ return row;
90
+ }
91
+ /**
92
+ * A well-formed inventory slug: lowercase letters, digits, and hyphens only.
93
+ * This mirrors the coordination bulletin's `projects/{slug}.md` filename
94
+ * convention (the slug IS the filename), and rejects the historical CSV-imported
95
+ * junk the 2026-07-05 registry data-hygiene sweep found — e.g. `"Skill Vault"`
96
+ * (space + capitals) or `"Website - VimeoBunny"`. The CLI's input-side
97
+ * `project_slug` rule is stricter still (`^[a-z][a-z0-9-]{2,49}$`); this is the
98
+ * looser floor the inventory row must clear before it is written.
99
+ */
100
+ export const INVENTORY_SLUG_RE = /^[a-z0-9-]+$/;
101
+ /**
102
+ * A well-formed GitHub URL: exactly `https://github.com/{owner}/{repo}` with no
103
+ * trailing slash or path. Rejects the malformed values the hygiene sweep found —
104
+ * a missing scheme (`github.com/owner/repo`, `owner/repo`) or a trailing slash
105
+ * (`.../website-aharon/`). Owner/repo allow the GitHub-legal set `[A-Za-z0-9_.-]`.
106
+ */
107
+ export const INVENTORY_GITHUB_URL_RE = /^https:\/\/github\.com\/[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/;
108
+ /**
109
+ * Validate the CLI-owned fields of a would-be inventory row. Returns a list of
110
+ * human-readable problems (empty = valid). Called before every write so a
111
+ * malformed `slug` / `github_url` can never be UPSERTed into the registry — the
112
+ * prevention half of the 2026-07-05 `z2w-agent-coordination` data-hygiene ask.
113
+ */
114
+ export function validateProjectRow(row) {
115
+ const problems = [];
116
+ const slug = row["slug"];
117
+ if (typeof slug !== "string" || slug.length === 0) {
118
+ problems.push("slug is missing.");
119
+ }
120
+ else if (!INVENTORY_SLUG_RE.test(slug)) {
121
+ problems.push(`slug "${slug}" is malformed (expected ${INVENTORY_SLUG_RE} — lowercase letters, digits, and hyphens only).`);
122
+ }
123
+ const githubUrl = row["github_url"];
124
+ if (githubUrl !== undefined) {
125
+ if (typeof githubUrl !== "string" || !INVENTORY_GITHUB_URL_RE.test(githubUrl)) {
126
+ problems.push(`github_url "${String(githubUrl)}" is malformed (expected https://github.com/{owner}/{repo}, no trailing slash).`);
127
+ }
128
+ }
129
+ return problems;
130
+ }
131
+ /**
132
+ * Build the INSERT … ON CONFLICT (slug) DO UPDATE statement from a row. Column
133
+ * names come from `buildProjectRow` (our own code, never user input), so string
134
+ * interpolation of column names is injection-safe; all VALUES are parameterized.
135
+ * The DO UPDATE set list excludes `slug` (the conflict key) and touches only the
136
+ * columns present in `row`, so columns the CLI doesn't manage are never altered.
137
+ * `updated_at` is left to the table's auto-touch trigger.
138
+ */
139
+ export function buildUpsert(row) {
140
+ const columns = Object.keys(row);
141
+ const placeholders = columns.map((_, i) => `$${i + 1}`);
142
+ const updates = columns
143
+ .filter((col) => col !== INVENTORY_CONFLICT_KEY)
144
+ .map((col) => `${col} = EXCLUDED.${col}`);
145
+ // A row may carry only `slug` in pathological cases; guard the empty SET.
146
+ const conflictClause = updates.length > 0
147
+ ? `ON CONFLICT (${INVENTORY_CONFLICT_KEY}) DO UPDATE SET ${updates.join(", ")}`
148
+ : `ON CONFLICT (${INVENTORY_CONFLICT_KEY}) DO NOTHING`;
149
+ const sql = `INSERT INTO ${INVENTORY_TABLE} (${columns.join(", ")}) ` +
150
+ `VALUES (${placeholders.join(", ")}) ` +
151
+ `${conflictClause} ` +
152
+ `RETURNING id, (xmax = 0) AS inserted`;
153
+ const params = columns.map((col) => row[col]);
154
+ return { sql, params, columns };
155
+ }
156
+ /** Build a one-shot HTTP query function from a connection string. */
157
+ function defaultQuery(databaseUrl) {
158
+ const sql = neon(databaseUrl);
159
+ return (text, params) => sql.query(text, params);
160
+ }
161
+ /**
162
+ * UPSERT the inventory row for a freshly-scaffolded project into Neon.
163
+ * Warn-and-proceed: always resolves (never rejects); the CLI surfaces `message`
164
+ * and continues.
165
+ *
166
+ * - No Z2W_INVENTORY_DATABASE_URL → outcome "skipped" (silent for normal users).
167
+ * - opts.dryRun → outcome "dry-run" (prints the would-be SQL).
168
+ * - success → outcome "upserted" (+ recordId).
169
+ * - query error → outcome "failed" (+ a diagnostic; row NOT written).
170
+ */
171
+ export async function registerProjectRowNeon(inputs, opts = {}) {
172
+ // "Verify, don't assert": for a participating project with a real scaffold on
173
+ // disk, confirm the coordination block is present before claiming Registered.
174
+ // Skipped for dry-runs (nothing written) and when no targetPath is supplied.
175
+ let coordinationVerified;
176
+ if (inputs.participateInBulletin && opts.targetPath && !opts.dryRun) {
177
+ coordinationVerified = await scaffoldCarriesCoordinationBlock(opts.targetPath, {
178
+ readFileImpl: opts.readFileImpl,
179
+ });
180
+ }
181
+ const row = buildProjectRow(inputs, { coordinationVerified });
182
+ const coordNote = coordinationVerified === false
183
+ ? " Note: the coordination block was not found in the scaffold, so " +
184
+ "agent_coordination was left unset for you to fill by hand."
185
+ : "";
186
+ const promptNote = row["project_instantiation_prompt"]
187
+ ? ""
188
+ : " Note: no Project Instantiation Prompt was captured for this project — " +
189
+ "add it to the row's project_instantiation_prompt column by hand " +
190
+ "(every inventory row should carry its instantiation prompt).";
191
+ // Prevention half of the 2026-07-05 registry data-hygiene ask: refuse to write
192
+ // a row whose slug or github_url is malformed, so the junk the sweep cleaned up
193
+ // (a `"Skill Vault"` slug, a scheme-less `github.com/...` URL) can never
194
+ // re-accumulate. Warn-and-proceed: this NEVER throws or fails the scaffold —
195
+ // it just declines the bad write and surfaces exactly what to fix. Checked
196
+ // before the dry-run preview too, so a dry-run flags the problem early.
197
+ const problems = validateProjectRow(row);
198
+ if (problems.length > 0) {
199
+ return {
200
+ outcome: "failed",
201
+ row,
202
+ coordinationVerified,
203
+ message: `Neon inventory write skipped — the row failed validation and was NOT ` +
204
+ `written: ${problems.join(" ")} Fix the input and re-run; the scaffold ` +
205
+ `completed normally.`,
206
+ };
207
+ }
208
+ const config = opts.config !== undefined ? opts.config : resolveInventoryConfig(opts.env);
209
+ if (config === null) {
210
+ return {
211
+ outcome: "skipped",
212
+ row,
213
+ coordinationVerified,
214
+ message: "Neon inventory write skipped (no Z2W_INVENTORY_DATABASE_URL set).",
215
+ };
216
+ }
217
+ const { sql, params, columns } = buildUpsert(row);
218
+ if (opts.dryRun) {
219
+ return {
220
+ outcome: "dry-run",
221
+ row,
222
+ sql,
223
+ coordinationVerified,
224
+ message: `Neon inventory (dry-run): would UPSERT 1 row into ` +
225
+ `${INVENTORY_TABLE}(${columns.join(", ")}) ON CONFLICT (${INVENTORY_CONFLICT_KEY}) ` +
226
+ `DO UPDATE.\n SQL: ${sql}`,
227
+ };
228
+ }
229
+ try {
230
+ const query = opts.queryImpl ?? defaultQuery(config.databaseUrl);
231
+ const rows = await query(sql, params);
232
+ const first = rows[0] ?? {};
233
+ const recordId = first["id"];
234
+ // (xmax = 0) is the standard "was this row inserted vs updated" probe;
235
+ // best-effort — purely for a friendlier message.
236
+ const action = first["inserted"] === true ? "created" : "updated";
237
+ return {
238
+ outcome: "upserted",
239
+ row,
240
+ sql,
241
+ recordId,
242
+ coordinationVerified,
243
+ message: `Neon inventory row ${action}${recordId !== undefined ? ` (id ${recordId})` : ""}.` +
244
+ coordNote +
245
+ promptNote,
246
+ };
247
+ }
248
+ catch (err) {
249
+ return {
250
+ outcome: "failed",
251
+ row,
252
+ sql,
253
+ coordinationVerified,
254
+ message: `Neon inventory write failed (${err.message}); the row was ` +
255
+ `NOT written. Scaffold completed normally — add the row by hand or re-run later.`,
256
+ };
257
+ }
258
+ }
package/dist/license.js CHANGED
@@ -1,12 +1,14 @@
1
1
  // z2w-starter-kit runtime license check.
2
2
  //
3
3
  // Implements the contract in directives/license-check.md. v0.3.0 introduction.
4
- // The CLI phones home to the z2w-license-server WordPress plugin on
5
- // zero2webmaster.com to validate paid-tier licenses, gates paid features
6
- // (--with-init, Pro SEO baseline) on the result, and respects the
7
- // snapshot-permanence client mapping table that lets cancelled subscribers
4
+ // The CLI phones home to the portable license-engine (Node + Hono + Neon on
5
+ // Cloud Run, live at https://licenses.z2w.us/v1) to validate paid-tier
6
+ // licenses, gates paid features (Pro SEO baseline) on the result, and respects
7
+ // the snapshot-permanence client mapping table that lets cancelled subscribers
8
8
  // keep using the AGENTS snapshot they paid for without pulling Templates
9
- // updates.
9
+ // updates. (The license authority moved off the z2w-license-server WordPress
10
+ // plugin to license-engine per the 2026-06-20 two-repo-split decision; the
11
+ // engine reproduces the same z2w/v1 `/license/*` contract byte-compatibly.)
10
12
  //
11
13
  // Three patterns the rest of the file is built around:
12
14
  //
@@ -27,7 +29,7 @@ import * as path from "node:path";
27
29
  import * as os from "node:os";
28
30
  import { randomUUID } from "node:crypto";
29
31
  export const DEFAULT_LICENSE_API_BASE = process.env["Z2W_LICENSE_API_BASE"] ??
30
- "https://zero2webmaster.com/wp-json/z2w/v1";
32
+ "https://licenses.z2w.us/v1";
31
33
  export const PRODUCT_SLUG = "z2w-starter-kit";
32
34
  export const DEFAULT_CONFIG_DIR = path.join(os.homedir(), ".config", "z2w");
33
35
  export const LICENSE_FILE_NAME = "license";
@@ -10,6 +10,26 @@ export interface ParsedBrief {
10
10
  hasWebUi: boolean | null;
11
11
  hasCron: boolean | null;
12
12
  participateInBulletin: boolean | null;
13
+ /**
14
+ * Whether the project sends transactional / auth email. Not nullable — absent
15
+ * signal means `false` (no mailer emitted), which is the safe default (the
16
+ * mailer pulls in the AWS/Resend SDKs). Honored only by nextjs / node-service.
17
+ */
18
+ sendsEmail: boolean;
19
+ /**
20
+ * Whether the project accepts user-generated content. Not nullable — absent
21
+ * signal means `false` (no moderation standard inserted), the safe default.
22
+ * Gates the [[moderation-system]] standard for non-WP app types.
23
+ */
24
+ hasUserContent: boolean;
25
+ /**
26
+ * Whether to wire Sentry runtime-error/APM observability. Not nullable — the
27
+ * inference resolves a definite boolean by applying the smart default (ON for
28
+ * customer-facing nextjs / cf-pages web apps) when the brief gives no explicit
29
+ * signal. Gates the [[sentry-runtime-errors]] standard; only inserted for the
30
+ * nextjs / cf-pages types downstream.
31
+ */
32
+ hasObservability: boolean;
13
33
  /** Free-text planning sections lifted verbatim from the brief, if any. */
14
34
  briefSections: BriefSections | undefined;
15
35
  raw: string;
@@ -33,8 +53,14 @@ export declare function githubOrgForBrand(brand: BrandPreset): string | null;
33
53
  /**
34
54
  * Lift the free-text planning sections out of the brief so they can flow into
35
55
  * the scaffolded ROADMAP.md + README.md (per [[instantiate-z2w-project]]
36
- * SKILL Step 1a.4) instead of being discarded after field inference. Only
37
- * sections actually present in the brief appear in the result; returns
56
+ * SKILL Step 1a.4) instead of being discarded after field inference.
57
+ *
58
+ * Scans EVERY markdown heading (ATX `## Foo` and standalone bold `**Foo**`),
59
+ * classifies each by alias keyword, and bounds a section's body at the next
60
+ * heading of ANY kind. This tolerates real-world brief heading vocabulary
61
+ * rather than demanding the exact canonical words, and prevents one section's
62
+ * body from bleeding into the next when an unrecognized heading sits between
63
+ * them. Only sections actually present appear in the result; returns
38
64
  * `undefined` when none are found (the wizard/`--input` shape).
39
65
  */
40
66
  export declare function extractBriefSections(brief: string): BriefSections | undefined;