@marktiderman/genesis-cli 1.2.0 → 1.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/README.md CHANGED
@@ -51,6 +51,14 @@ from the live database.
51
51
 
52
52
  The output is deterministic: a re-run with no schema change writes the same bytes.
53
53
 
54
+ ```bash
55
+ npx @marktiderman/genesis-cli features build # or: features check (for CI)
56
+ ```
57
+
58
+ Writes the marked feature block in `AGENTS.md` (and a JSON copy with `--json <file>`) from the
59
+ repo's `src/features.ts`; `check` exits 1 when that output is stale or a feature's `links.code`
60
+ path doesn't exist. See [genesis-features](../features/README.md) for the registry and the options.
61
+
54
62
  ## Settings in comments
55
63
 
56
64
  Put labels and widgets next to the schema, in table and column comments:
package/dist/cli.js CHANGED
@@ -1,9 +1,12 @@
1
1
  #!/usr/bin/env node
2
- import { spawnSync } from 'child_process';
3
- import { readFileSync, existsSync, statSync, readdirSync } from 'fs';
2
+ import { execFileSync, spawnSync } from 'child_process';
3
+ import { existsSync, readFileSync, statSync, readdirSync } from 'fs';
4
4
  import * as path3 from 'path';
5
5
  import { createRequire } from 'module';
6
6
  import { pathToFileURL } from 'url';
7
+ import { createJiti } from 'jiti';
8
+ import { buildFeatureOutputs, checkFeatureOutputs, summarizeCheck } from '@marktiderman/genesis-features/node';
9
+ import { findFeatures } from '@marktiderman/genesis-features';
7
10
  import { studioSetupSql } from '@marktiderman/genesis-studio-server';
8
11
  import { Command } from 'commander';
9
12
  import * as fs from 'fs/promises';
@@ -34,15 +37,15 @@ function parse(comment, keys, where) {
34
37
  if (!value || typeof value !== "object" || Array.isArray(value)) {
35
38
  throw new CommentSettingsError(`${where}: the text after ${MARKER} must be one JSON object.`);
36
39
  }
37
- const settings = {};
40
+ const settings2 = {};
38
41
  for (const [key, v] of Object.entries(value)) {
39
42
  if (!keys.includes(key)) {
40
43
  throw new CommentSettingsError(`${where}: unknown ${MARKER} setting "${key}". Allowed: ${keys.join(", ")}.`);
41
44
  }
42
45
  if (typeof v !== "string") throw new CommentSettingsError(`${where}: ${MARKER} "${key}" must be a string.`);
43
- settings[key] = v;
46
+ settings2[key] = v;
44
47
  }
45
- return { ...description ? { description } : {}, ...Object.keys(settings).length ? { settings } : {} };
48
+ return { ...description ? { description } : {}, ...Object.keys(settings2).length ? { settings: settings2 } : {} };
46
49
  }
47
50
  function parseTableComment(comment, table) {
48
51
  return parse(comment, TABLE_KEYS, table);
@@ -532,7 +535,7 @@ function globToRegExp(glob) {
532
535
  }
533
536
  function globMatcher(globs) {
534
537
  const res = (globs ?? []).filter((g) => g.trim()).map(globToRegExp);
535
- return (path10) => res.some((re) => re.test(path10));
538
+ return (path11) => res.some((re) => re.test(path11));
536
539
  }
537
540
  var init_glob = __esm({
538
541
  "src/doctor/glob.ts"() {
@@ -1426,6 +1429,117 @@ var init_doctor = __esm({
1426
1429
  }
1427
1430
  });
1428
1431
 
1432
+ // src/features.ts
1433
+ var features_exports = {};
1434
+ __export(features_exports, {
1435
+ formatFeature: () => formatFeature,
1436
+ gatherPrEvidence: () => gatherPrEvidence,
1437
+ loadRegistry: () => loadRegistry,
1438
+ runFeaturesBuild: () => runFeaturesBuild,
1439
+ runFeaturesCheck: () => runFeaturesCheck,
1440
+ runFeaturesFind: () => runFeaturesFind
1441
+ });
1442
+ function isObject2(value) {
1443
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1444
+ }
1445
+ function settings(root, options) {
1446
+ let fromPackage = {};
1447
+ try {
1448
+ const pkg = JSON.parse(readFileSync(path3.join(root, "package.json"), "utf-8"));
1449
+ if (isObject2(pkg.genesisFeatures)) fromPackage = pkg.genesisFeatures;
1450
+ } catch {
1451
+ }
1452
+ const given = Object.fromEntries(Object.entries(options).filter(([, v]) => v !== void 0));
1453
+ return { ...fromPackage, ...given };
1454
+ }
1455
+ async function loadRegistry(input) {
1456
+ const root = path3.resolve(input.dir);
1457
+ const options = settings(root, input);
1458
+ const registry = options.registry ?? DEFAULT_REGISTRIES.find((p) => existsSync(path3.join(root, p)));
1459
+ if (!registry || !existsSync(path3.join(root, registry))) {
1460
+ throw new Error(`No feature registry found. Looked for ${options.registry ?? DEFAULT_REGISTRIES.join(" and ")}; pass --registry.`);
1461
+ }
1462
+ const jiti = createJiti(path3.join(root, "package.json"), { moduleCache: false });
1463
+ const load = async (file) => await jiti.import(path3.join(root, file));
1464
+ const mod = await load(registry);
1465
+ const features2 = mod.features ?? mod.default;
1466
+ if (!isObject2(features2)) throw new Error(`${registry} must export \`features\` (from defineFeatures).`);
1467
+ const flags = options.flagsFile ? (await load(options.flagsFile)).flags : mod.flags;
1468
+ if (flags !== void 0 && !isObject2(flags)) {
1469
+ throw new Error(`${options.flagsFile ?? registry}'s \`flags\` export must be an object (from defineFlags).`);
1470
+ }
1471
+ const { dir: _dir, registry: _registry, flagsFile: _flagsFile, prs: _prs, gh: _gh, ...rest } = options;
1472
+ const project = {
1473
+ ...rest,
1474
+ root,
1475
+ source: options.source ?? registry.split(path3.sep).join("/"),
1476
+ features: features2,
1477
+ flags
1478
+ };
1479
+ return project;
1480
+ }
1481
+ async function runFeaturesBuild(options) {
1482
+ return buildFeatureOutputs(await loadRegistry(options));
1483
+ }
1484
+ function ghFailure(error) {
1485
+ const e = error;
1486
+ if (e?.code === "ENOENT") return "gh is not installed";
1487
+ if (e?.code === "ETIMEDOUT" || e?.signal === "SIGTERM") return "gh timed out";
1488
+ const stderr = e?.stderr?.toString().trim();
1489
+ return (stderr || String(error instanceof Error ? error.message : error)).split("\n")[0];
1490
+ }
1491
+ function gatherPrEvidence(project, gh = runGh) {
1492
+ const prs = {};
1493
+ const names = Object.entries(project.features).filter(([, f]) => f.status === "planned").flatMap(([id, f]) => [id, ...f.aliases ?? []]);
1494
+ for (let i = 0; i < names.length; i += LABELS_PER_SEARCH) {
1495
+ const batch = names.slice(i, i + LABELS_PER_SEARCH);
1496
+ const search = `label:${batch.map((n) => `"feature:${n}"`).join(",")}`;
1497
+ try {
1498
+ const out = gh(["pr", "list", "--state", "merged", "--search", search, "--limit", "1000", "--json", "number,title,labels"], project.root);
1499
+ for (const { number, title, labels } of JSON.parse(out)) {
1500
+ for (const { name: label } of labels) {
1501
+ const name = label.startsWith("feature:") ? label.slice("feature:".length) : null;
1502
+ if (name && batch.includes(name)) (prs[name] ??= []).push({ number, title });
1503
+ }
1504
+ }
1505
+ } catch (error) {
1506
+ return { prs, warning: `--prs: couldn't read merged PRs with gh (${ghFailure(error)}), so only changesets were checked for shipped work` };
1507
+ }
1508
+ }
1509
+ return { prs };
1510
+ }
1511
+ async function runFeaturesCheck(options) {
1512
+ const project = await loadRegistry(options);
1513
+ const evidence = options.prs ? gatherPrEvidence(project, options.gh) : void 0;
1514
+ const result = checkFeatureOutputs({ ...project, evidence: evidence && { prs: evidence.prs } });
1515
+ let summary = summarizeCheck(result, project.features);
1516
+ if (evidence?.warning) {
1517
+ result.warnings.push(evidence.warning);
1518
+ summary = `${summarizeCheck(result, project.features)}
1519
+ - ${evidence.warning}.`;
1520
+ }
1521
+ return { ...result, summary };
1522
+ }
1523
+ async function runFeaturesFind(options, term) {
1524
+ const project = await loadRegistry(options);
1525
+ return findFeatures(project.features, term, project.flags);
1526
+ }
1527
+ function formatFeature(r) {
1528
+ const lines = [`${r.id} \u2014 ${r.name} [${r.status}${r.horizon ? `, ${r.horizon}` : ""}] (${r.owner})`, ` ${r.summary}`];
1529
+ if (r.links?.code?.length) lines.push(` code: ${r.links.code.join(", ")}`);
1530
+ if (r.flags.length) lines.push(` flags: ${r.flags.join(", ")}`);
1531
+ if (r.claimedBy) lines.push(` being built by ${r.claimedBy}`);
1532
+ return lines.join("\n");
1533
+ }
1534
+ var DEFAULT_REGISTRIES, runGh, LABELS_PER_SEARCH;
1535
+ var init_features = __esm({
1536
+ "src/features.ts"() {
1537
+ DEFAULT_REGISTRIES = ["src/features.ts", "features.ts"];
1538
+ runGh = (args, cwd) => execFileSync("gh", args, { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], timeout: 15e3 });
1539
+ LABELS_PER_SEARCH = 10;
1540
+ }
1541
+ });
1542
+
1429
1543
  // src/studio/wire-route.ts
1430
1544
  function routeTags(source) {
1431
1545
  const tags = [];
@@ -1910,9 +2024,9 @@ async function runScaffold(opts, fs2) {
1910
2024
  function joinPath(...parts) {
1911
2025
  return parts.filter(Boolean).join("/").replace(/\/+/g, "/");
1912
2026
  }
1913
- function dirname(path10) {
1914
- const idx = path10.lastIndexOf("/");
1915
- return idx === -1 ? "." : path10.slice(0, idx);
2027
+ function dirname(path11) {
2028
+ const idx = path11.lastIndexOf("/");
2029
+ return idx === -1 ? "." : path11.slice(0, idx);
1916
2030
  }
1917
2031
  function brandPackageJson(consumer, genesisVersion) {
1918
2032
  return JSON.stringify(
@@ -2256,12 +2370,43 @@ program.command("doctor").description("Check this app against the installed Gene
2256
2370
  process.exitCode = 2;
2257
2371
  }
2258
2372
  });
2373
+ var features = program.command("features").description('The feature registry: one typed features.ts, everything else generated from it. Settings: package.json "genesisFeatures"');
2374
+ function featureOptions(command) {
2375
+ return command.option("-d, --dir <dir>", "The repo root", process.cwd()).option("-r, --registry <file>", "The registry (default: src/features.ts, then features.ts)").option("--flags-file <file>", "A flags file exporting `flags` (default: the registry's own `flags` export)").option("--agents <file>", "The AGENTS.md that holds the pointer block (default AGENTS.md)").option("--json <file>", "The JSON copy, also the record of every id (default features.json)").option("--command <text>", "How people run this CLI here, named in generated files (default `genesis features`)");
2376
+ }
2377
+ featureOptions(features.command("build").description("Write the AGENTS.md block, features.json, flags.json, the skill and the marketing block")).action(
2378
+ async (opts) => {
2379
+ const { runFeaturesBuild: runFeaturesBuild2 } = await Promise.resolve().then(() => (init_features(), features_exports));
2380
+ const changed = await runFeaturesBuild2(opts);
2381
+ console.log(changed.length ? changed.map((f) => `~ ${f}`).join("\n") : "\u2714 Generated feature files are up to date.");
2382
+ }
2383
+ );
2384
+ featureOptions(features.command("check").description("Errors fail (stale output, missing code paths, flag rules, removed ids, bad tags); warnings don't")).option("--labels <list>", "The PR's labels, comma-separated, to check feature:<id> labels").option("--prs", "Also read merged PRs labelled feature:<id> with gh, to warn about planned features that shipped", false).option("--summary", "Print a short summary and always exit 0 (for a SessionStart hook)", false).action(async (opts) => {
2385
+ const { runFeaturesCheck: runFeaturesCheck2 } = await Promise.resolve().then(() => (init_features(), features_exports));
2386
+ const { summary, labels, ...rest } = opts;
2387
+ const result = await runFeaturesCheck2({ ...rest, labels: labels?.split(",").map((l) => l.trim()).filter(Boolean) });
2388
+ if (summary) {
2389
+ console.log(result.summary);
2390
+ return;
2391
+ }
2392
+ for (const warning of result.warnings) console.warn(`! ${warning}`);
2393
+ for (const error of result.errors) console.error(`\u2717 ${error}`);
2394
+ if (result.ok) console.log(`\u2714 The feature registry and the repo agree${result.warnings.length ? ` (${result.warnings.length} warning${result.warnings.length === 1 ? "" : "s"})` : ""}.`);
2395
+ process.exitCode = result.ok ? 0 : 1;
2396
+ });
2397
+ featureOptions(features.command("find").description("Search features by id, alias, name, summary, flag or code path").argument("<term>", "What to look for")).action(
2398
+ async (term, opts) => {
2399
+ const { runFeaturesFind: runFeaturesFind2, formatFeature: formatFeature2 } = await Promise.resolve().then(() => (init_features(), features_exports));
2400
+ const hits = await runFeaturesFind2(opts, term);
2401
+ console.log(hits.length ? hits.map(formatFeature2).join("\n\n") : `No feature matches "${term}". If this is new work, add it to the registry first.`);
2402
+ }
2403
+ );
2259
2404
  var studio = program.command("studio").description("The Genesis Data Studio");
2260
2405
  studio.command("init").description("Turn the Data Studio on in this app: a server for every table, a page, and one migration to review").option("-d, --dir <dir>", "The app's folder", process.cwd()).option("--host <host>", "next, tanstack-start or supabase-function (default: detected)").option("--route <path>", "Where the page lives", "/admin/data").option("--login-role <name>", "The studio's database login", "genesis_studio_login").option("--force", "Overwrite files that already exist", false).action(async (opts) => {
2261
2406
  const { planStudioInit: planStudioInit2 } = await Promise.resolve().then(() => (init_init(), init_exports));
2262
2407
  const root = path3.resolve(opts.dir);
2263
2408
  const packageJson = JSON.parse(await fs.readFile(path3.join(root, "package.json"), "utf-8").catch(() => "{}"));
2264
- const existsSync7 = (await import('fs')).existsSync;
2409
+ const existsSync8 = (await import('fs')).existsSync;
2265
2410
  const readSync = (await import('fs')).readFileSync;
2266
2411
  const readdirSync3 = (await import('fs')).readdirSync;
2267
2412
  if (opts.host && !["next", "tanstack-start", "supabase-function"].includes(opts.host)) {
@@ -2270,8 +2415,8 @@ studio.command("init").description("Turn the Data Studio on in this app: a serve
2270
2415
  const plan = planStudioInit2(
2271
2416
  {
2272
2417
  packageJson,
2273
- exists: (p) => existsSync7(path3.join(root, p)),
2274
- read: (p) => existsSync7(path3.join(root, p)) ? readSync(path3.join(root, p), "utf-8") : null,
2418
+ exists: (p) => existsSync8(path3.join(root, p)),
2419
+ read: (p) => existsSync8(path3.join(root, p)) ? readSync(path3.join(root, p), "utf-8") : null,
2275
2420
  timestamp: (/* @__PURE__ */ new Date()).toISOString().replace(/\D/g, "").slice(0, 14),
2276
2421
  listDeep: (p) => {
2277
2422
  const out = [];
@@ -2311,14 +2456,14 @@ studio.command("init").description("Turn the Data Studio on in this app: a serve
2311
2456
  console.log(`+ ${file.path} (appended)`);
2312
2457
  continue;
2313
2458
  }
2314
- if (existsSync7(target) && !opts.force) {
2459
+ if (existsSync8(target) && !opts.force) {
2315
2460
  console.log(`= ${file.path} exists; left as it is (--force to replace)`);
2316
2461
  continue;
2317
2462
  }
2318
2463
  await fs.writeFile(target, file.content, "utf-8");
2319
2464
  console.log(`+ ${file.path}`);
2320
2465
  }
2321
- const pm = existsSync7(path3.join(root, "pnpm-lock.yaml")) ? "pnpm add" : existsSync7(path3.join(root, "yarn.lock")) ? "yarn add" : existsSync7(path3.join(root, "bun.lock")) || existsSync7(path3.join(root, "bun.lockb")) ? "bun add" : "npm install";
2466
+ const pm = existsSync8(path3.join(root, "pnpm-lock.yaml")) ? "pnpm add" : existsSync8(path3.join(root, "yarn.lock")) ? "yarn add" : existsSync8(path3.join(root, "bun.lock")) || existsSync8(path3.join(root, "bun.lockb")) ? "bun add" : "npm install";
2322
2467
  console.log("");
2323
2468
  console.log(`\u2714 The Data Studio is set up for ${{ next: "Next.js", "tanstack-start": "TanStack Start", "supabase-function": "a Supabase Edge Function" }[plan.host]}. To finish:`);
2324
2469
  console.log(` 1. ${pm} ${plan.install.join(" ")}`);