contentbit 0.6.0 → 0.7.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.
Files changed (46) hide show
  1. package/README.md +14 -0
  2. package/dist/bin.js +1652 -318
  3. package/dist/commands/adopt.d.ts +13 -0
  4. package/dist/commands/adopt.d.ts.map +1 -0
  5. package/dist/commands/agents.d.ts +1 -0
  6. package/dist/commands/agents.d.ts.map +1 -1
  7. package/dist/commands/brief.d.ts.map +1 -1
  8. package/dist/commands/docs.d.ts.map +1 -1
  9. package/dist/commands/doctor.d.ts +1 -0
  10. package/dist/commands/doctor.d.ts.map +1 -1
  11. package/dist/commands/init-targets.d.ts.map +1 -1
  12. package/dist/commands/init.d.ts.map +1 -1
  13. package/dist/commands/instructions.d.ts.map +1 -1
  14. package/dist/commands/links.d.ts.map +1 -1
  15. package/dist/commands/render.d.ts.map +1 -1
  16. package/dist/commands/stats.d.ts.map +1 -1
  17. package/dist/commands/studio.d.ts.map +1 -1
  18. package/dist/commands/validate.d.ts.map +1 -1
  19. package/dist/content-project.d.ts +2 -2
  20. package/dist/content-project.d.ts.map +1 -1
  21. package/dist/project-config.d.ts +8 -0
  22. package/dist/project-config.d.ts.map +1 -0
  23. package/dist/run.d.ts +1 -1
  24. package/dist/run.d.ts.map +1 -1
  25. package/dist/run.js +1652 -318
  26. package/dist/script-defaults.d.ts +14 -0
  27. package/dist/script-defaults.d.ts.map +1 -0
  28. package/package.json +6 -7
  29. package/dist/cli-format.js +0 -63
  30. package/dist/commands/agents.js +0 -64
  31. package/dist/commands/brief.js +0 -52
  32. package/dist/commands/docs.js +0 -12
  33. package/dist/commands/doctor.js +0 -173
  34. package/dist/commands/init-targets.js +0 -280
  35. package/dist/commands/init.js +0 -382
  36. package/dist/commands/instructions.js +0 -15
  37. package/dist/commands/links.js +0 -84
  38. package/dist/commands/render.js +0 -33
  39. package/dist/commands/stats.js +0 -38
  40. package/dist/commands/studio.js +0 -65
  41. package/dist/commands/validate.js +0 -49
  42. package/dist/content-project.js +0 -25
  43. package/dist/link-options.js +0 -31
  44. package/dist/links-io.js +0 -14
  45. package/dist/load-registry.js +0 -1
  46. package/dist/seo-config.js +0 -21
package/dist/bin.js CHANGED
@@ -3487,11 +3487,12 @@ var init_cli_format = __esm({
3487
3487
  });
3488
3488
 
3489
3489
  // ../core/dist/props.js
3490
- function parseProps(raw, position) {
3490
+ function parseProps(raw, position, rawStart = position.start) {
3491
3491
  const props = {};
3492
+ const propPositions = {};
3492
3493
  const diagnostics = [];
3493
3494
  if (raw === null)
3494
- return { props, diagnostics };
3495
+ return { props, propPositions, diagnostics };
3495
3496
  const err = (message) => diagnostics.push({
3496
3497
  code: "CB_PROPS_SYNTAX",
3497
3498
  severity: "error",
@@ -3502,6 +3503,7 @@ function parseProps(raw, position) {
3502
3503
  if (!raw.endsWith("}")) {
3503
3504
  return {
3504
3505
  props: {},
3506
+ propPositions,
3505
3507
  diagnostics: [
3506
3508
  {
3507
3509
  code: "CB_PROPS_SYNTAX",
@@ -3514,6 +3516,8 @@ function parseProps(raw, position) {
3514
3516
  };
3515
3517
  }
3516
3518
  const inner = raw.slice(1, -1);
3519
+ const innerOffset = rawStart.offset + 1;
3520
+ const innerColumn = rawStart.column + 1;
3517
3521
  let i = 0;
3518
3522
  while (i < inner.length) {
3519
3523
  while (i < inner.length && /\s/.test(inner[i]))
@@ -3523,9 +3527,22 @@ function parseProps(raw, position) {
3523
3527
  const keyMatch = inner.slice(i).match(KEY_RE);
3524
3528
  if (!keyMatch) {
3525
3529
  err(`Unexpected character "${inner[i]}" in props.`);
3526
- return { props, diagnostics };
3530
+ return { props, propPositions, diagnostics };
3527
3531
  }
3532
+ const keyStart = i;
3528
3533
  const key = keyMatch[0];
3534
+ propPositions[key] = {
3535
+ start: {
3536
+ line: rawStart.line,
3537
+ column: innerColumn + keyStart,
3538
+ offset: innerOffset + keyStart
3539
+ },
3540
+ end: {
3541
+ line: rawStart.line,
3542
+ column: innerColumn + keyStart + key.length,
3543
+ offset: innerOffset + keyStart + key.length
3544
+ }
3545
+ };
3529
3546
  i += key.length;
3530
3547
  if (inner[i] !== "=") {
3531
3548
  props[key] = true;
@@ -3552,7 +3569,7 @@ function parseProps(raw, position) {
3552
3569
  }
3553
3570
  if (!closed) {
3554
3571
  err(`Unterminated string for prop "${key}".`);
3555
- return { props, diagnostics };
3572
+ return { props, propPositions, diagnostics };
3556
3573
  }
3557
3574
  props[key] = value;
3558
3575
  continue;
@@ -3560,7 +3577,7 @@ function parseProps(raw, position) {
3560
3577
  const valMatch = inner.slice(i).match(/^[^\s]+/);
3561
3578
  if (!valMatch) {
3562
3579
  err(`Missing value for prop "${key}".`);
3563
- return { props, diagnostics };
3580
+ return { props, propPositions, diagnostics };
3564
3581
  }
3565
3582
  const rawVal = valMatch[0];
3566
3583
  i += rawVal.length;
@@ -3575,7 +3592,7 @@ function parseProps(raw, position) {
3575
3592
  else
3576
3593
  err(`Invalid value "${rawVal}" for prop "${key}".`);
3577
3594
  }
3578
- return { props, diagnostics };
3595
+ return { props, propPositions, diagnostics };
3579
3596
  }
3580
3597
  var KEY_RE, NUMBER_RE, IDENT_RE;
3581
3598
  var init_props = __esm({
@@ -3637,9 +3654,9 @@ function parseDocument(source) {
3637
3654
  }
3638
3655
  mdStartLine = null;
3639
3656
  }
3640
- function openBlock(i, fence, name, rawProps) {
3657
+ function openBlock(i, fence, name, rawProps, rawPropsStartColumn) {
3641
3658
  const openPosition = lineRange(i);
3642
- const parsed = parseProps(rawProps, openPosition);
3659
+ const parsed = parseProps(rawProps, openPosition, rawPropsStartColumn === null ? openPosition.start : point(i + 1, rawPropsStartColumn, lineStart[i] + rawPropsStartColumn - 1));
3643
3660
  for (const d of parsed.diagnostics)
3644
3661
  diagnostics.push({ ...d, blockName: name });
3645
3662
  const node = {
@@ -3647,6 +3664,7 @@ function parseDocument(source) {
3647
3664
  name,
3648
3665
  fence,
3649
3666
  props: parsed.props,
3667
+ propPositions: parsed.propPositions,
3650
3668
  rawProps,
3651
3669
  children: [],
3652
3670
  body: "",
@@ -3728,7 +3746,9 @@ function parseDocument(source) {
3728
3746
  const open = trimmed.match(OPEN_RE);
3729
3747
  if (open) {
3730
3748
  flushMarkdown(i);
3731
- openBlock(i, open[1].length, open[2], open[3] ?? null);
3749
+ const indent = lines[i].indexOf(trimmed);
3750
+ const rawPropsStartColumn = open[3] === void 0 ? null : indent + open[1].length + open[2].length + 1;
3751
+ openBlock(i, open[1].length, open[2], open[3] ?? null, rawPropsStartColumn);
3732
3752
  continue;
3733
3753
  }
3734
3754
  const child = trimmed.match(CHILD_RE);
@@ -3747,7 +3767,9 @@ function parseDocument(source) {
3747
3767
  }
3748
3768
  popChildIfOpen(i);
3749
3769
  flushMarkdown(i);
3750
- openBlock(i, 2, child[1], child[2] ?? null);
3770
+ const indent = lines[i].indexOf(trimmed);
3771
+ const rawPropsStartColumn = child[2] === void 0 ? null : indent + 2 + child[1].length + 1;
3772
+ openBlock(i, 2, child[1], child[2] ?? null, rawPropsStartColumn);
3751
3773
  continue;
3752
3774
  }
3753
3775
  if (mdStartLine === null)
@@ -4179,6 +4201,234 @@ var init_analyze = __esm({
4179
4201
  }
4180
4202
  });
4181
4203
 
4204
+ // ../core/dist/validate.js
4205
+ function isValidatedDocument(document) {
4206
+ return document.__contentbitValidatedDocument === true;
4207
+ }
4208
+ function isProcessedDocument(document) {
4209
+ return document.__contentbitProcessedDocument === true;
4210
+ }
4211
+ function isValidatedBlock(node) {
4212
+ return node.type === "block" && "data" in node && "definition" in node;
4213
+ }
4214
+ function checkUrls(value, position, allowed, report) {
4215
+ for (const match of value.matchAll(LINK_URL_RE)) {
4216
+ const url2 = match[1];
4217
+ const scheme = url2.match(HAS_SCHEME_RE);
4218
+ if (!scheme)
4219
+ continue;
4220
+ const protocol = `${scheme[0].slice(0, -1).toLowerCase()}:`;
4221
+ if (!allowed.includes(protocol)) {
4222
+ report({
4223
+ code: "CB_URL_PROTOCOL",
4224
+ severity: "error",
4225
+ message: `URL protocol "${protocol}" is not allowed.`,
4226
+ hint: `Allowed: ${allowed.join(", ")}. Configure via validateDocument options.allowedProtocols.`,
4227
+ position
4228
+ });
4229
+ }
4230
+ }
4231
+ }
4232
+ function knownPropNames(schema) {
4233
+ if (!schema)
4234
+ return [];
4235
+ const root = schema.def;
4236
+ if (root.type !== "object" || !root.shape)
4237
+ return void 0;
4238
+ if (root.catchall && root.catchall.def.type !== "never")
4239
+ return void 0;
4240
+ return Object.keys(root.shape);
4241
+ }
4242
+ function knownItems(label, names) {
4243
+ return names.length > 0 ? `Known ${label}: ${names.join(", ")}.` : `No ${label} are registered.`;
4244
+ }
4245
+ function unknownPropHint(prop, known) {
4246
+ const suggestion = closest(prop, known);
4247
+ const knownHint = known.length > 0 ? `Known props: ${known.join(", ")}.` : "This block does not accept props.";
4248
+ return suggestion ? `Did you mean "${suggestion}"? ${knownHint}` : knownHint;
4249
+ }
4250
+ function reportUnknownProps(node, def, report) {
4251
+ const known = knownPropNames(def.props);
4252
+ if (!known)
4253
+ return true;
4254
+ let valid = true;
4255
+ for (const prop of Object.keys(node.props)) {
4256
+ if (known.includes(prop))
4257
+ continue;
4258
+ valid = false;
4259
+ report({
4260
+ code: "CB_UNKNOWN_PROP",
4261
+ severity: "error",
4262
+ message: `${node.name}: unknown prop "${prop}".`,
4263
+ hint: unknownPropHint(prop, known),
4264
+ blockName: node.name,
4265
+ position: node.propPositions?.[prop] ?? node.openPosition
4266
+ });
4267
+ }
4268
+ return valid;
4269
+ }
4270
+ function editDistance2(a, b) {
4271
+ const dp = Array.from({ length: a.length + 1 }, (_, i) => [i, ...Array(b.length).fill(0)]);
4272
+ for (let j = 0; j <= b.length; j++)
4273
+ dp[0][j] = j;
4274
+ for (let i = 1; i <= a.length; i++) {
4275
+ for (let j = 1; j <= b.length; j++) {
4276
+ const cost = a[i - 1] === b[j - 1] ? 0 : 1;
4277
+ dp[i][j] = Math.min(dp[i - 1][j] + 1, dp[i][j - 1] + 1, dp[i - 1][j - 1] + cost);
4278
+ }
4279
+ }
4280
+ return dp[a.length][b.length];
4281
+ }
4282
+ function closest(target, candidates) {
4283
+ let best;
4284
+ let bestD = Infinity;
4285
+ for (const candidate of candidates) {
4286
+ const distance = editDistance2(target, candidate);
4287
+ if (distance < bestD) {
4288
+ bestD = distance;
4289
+ best = candidate;
4290
+ }
4291
+ }
4292
+ return best && bestD <= Math.max(2, Math.floor(target.length / 3)) ? best : void 0;
4293
+ }
4294
+ function validateDocument(parsed, registry2, options = {}) {
4295
+ const opts = {
4296
+ unknownBlocks: options.unknownBlocks ?? "error",
4297
+ maxDepth: options.maxDepth ?? 4,
4298
+ allowedProtocols: options.allowedProtocols ?? ["http:", "https:", "mailto:"]
4299
+ };
4300
+ const diagnostics = [...parsed.diagnostics];
4301
+ const report = (d) => diagnostics.push(d);
4302
+ function walk(nodes, parent, depth) {
4303
+ for (const node of nodes) {
4304
+ if (node.type === "markdown") {
4305
+ checkUrls(node.value, node.position, opts.allowedProtocols, report);
4306
+ continue;
4307
+ }
4308
+ if (depth > opts.maxDepth) {
4309
+ report({
4310
+ code: "CB_NESTING_DEPTH",
4311
+ severity: "error",
4312
+ message: `Block "${node.name}" exceeds the maximum nesting depth of ${opts.maxDepth}.`,
4313
+ blockName: node.name,
4314
+ position: node.openPosition
4315
+ });
4316
+ continue;
4317
+ }
4318
+ const def = registry2.get(node.name);
4319
+ if (!def) {
4320
+ const knownBlocks = registry2.all().map((d) => d.name);
4321
+ const suggestion = closest(node.name, knownBlocks);
4322
+ report({
4323
+ code: "CB_UNKNOWN_BLOCK",
4324
+ severity: opts.unknownBlocks,
4325
+ message: `Unknown block "${node.name}".`,
4326
+ hint: suggestion ? `Did you mean "${suggestion}"? ${knownItems("blocks", knownBlocks)}` : knownItems("blocks", knownBlocks),
4327
+ blockName: node.name,
4328
+ position: node.openPosition
4329
+ });
4330
+ continue;
4331
+ }
4332
+ let valid = true;
4333
+ if (def.childOnly && parent === null) {
4334
+ valid = false;
4335
+ report({
4336
+ code: "CB_CHILD_ONLY",
4337
+ severity: "error",
4338
+ message: `"${node.name}" is a child block and cannot be used at the top level.`,
4339
+ blockName: node.name,
4340
+ position: node.openPosition
4341
+ });
4342
+ }
4343
+ if (!reportUnknownProps(node, def, report))
4344
+ valid = false;
4345
+ if (def.props) {
4346
+ const result = def.props.safeParse(node.props);
4347
+ if (result.success) {
4348
+ node.props = result.data;
4349
+ } else {
4350
+ valid = false;
4351
+ for (const issue2 of result.error.issues) {
4352
+ if (issue2.code === "unrecognized_keys")
4353
+ continue;
4354
+ const prop = typeof issue2.path[0] === "string" && issue2.path[0].length > 0 ? issue2.path[0] : void 0;
4355
+ report({
4356
+ code: "CB_PROPS_INVALID",
4357
+ severity: "error",
4358
+ message: `${node.name}: prop "${issue2.path.join(".") || "(root)"}" ${issue2.message}`,
4359
+ blockName: node.name,
4360
+ position: (prop ? node.propPositions?.[prop] : void 0) ?? node.openPosition
4361
+ });
4362
+ }
4363
+ }
4364
+ }
4365
+ const before = diagnostics.length;
4366
+ const data = def.content.parse(node, report);
4367
+ let contentError = false;
4368
+ for (let j = before; j < diagnostics.length; j++) {
4369
+ if (diagnostics[j].severity === "error") {
4370
+ contentError = true;
4371
+ break;
4372
+ }
4373
+ }
4374
+ if (contentError)
4375
+ valid = false;
4376
+ if (valid) {
4377
+ ;
4378
+ node.data = data;
4379
+ node.definition = def;
4380
+ }
4381
+ walk(node.children, node, depth + 1);
4382
+ }
4383
+ }
4384
+ walk(parsed.document.children, null, 1);
4385
+ const ok = !diagnostics.some((d) => d.severity === "error");
4386
+ if (ok)
4387
+ return { ok: true, document: markValidatedDocument(parsed.document), diagnostics };
4388
+ return { ok: false, document: markProcessedDocument(parsed.document), diagnostics };
4389
+ }
4390
+ function markValidatedDocument(document) {
4391
+ markProcessedDocument(document);
4392
+ if (!isValidatedDocument(document)) {
4393
+ Object.defineProperty(document, "__contentbitValidatedDocument", {
4394
+ value: true,
4395
+ enumerable: false
4396
+ });
4397
+ }
4398
+ return document;
4399
+ }
4400
+ function markProcessedDocument(document) {
4401
+ if (!isProcessedDocument(document)) {
4402
+ Object.defineProperty(document, "__contentbitProcessedDocument", {
4403
+ value: true,
4404
+ enumerable: false
4405
+ });
4406
+ }
4407
+ return document;
4408
+ }
4409
+ var LINK_URL_RE, HAS_SCHEME_RE;
4410
+ var init_validate = __esm({
4411
+ "../core/dist/validate.js"() {
4412
+ "use strict";
4413
+ LINK_URL_RE = /\]\(([^)\s]+)/g;
4414
+ HAS_SCHEME_RE = /^[a-zA-Z][a-zA-Z0-9+.-]*:/;
4415
+ }
4416
+ });
4417
+
4418
+ // ../core/dist/compile.js
4419
+ function compileDocument(source, registry2, options = {}) {
4420
+ const { preserveFrontmatter = false, ...validateOptions } = options;
4421
+ return validateDocument(parseDocument(preserveFrontmatter ? source : stripFrontmatter(source)), registry2, validateOptions);
4422
+ }
4423
+ var init_compile = __esm({
4424
+ "../core/dist/compile.js"() {
4425
+ "use strict";
4426
+ init_frontmatter();
4427
+ init_parser();
4428
+ init_validate();
4429
+ }
4430
+ });
4431
+
4182
4432
  // ../core/dist/link-graph.js
4183
4433
  function createLinkGraphView(index, diagnostics = []) {
4184
4434
  const pages = [...index.pages.values()];
@@ -19567,7 +19817,7 @@ function validateLinks(inputs, options = {}) {
19567
19817
  out.push(diag(page.path, "CB_LINK_LOCALE_MISSING", "error", `linksTo "${resolved.target}" exists in another locale but not "${page.locale ?? "default"}"`, void 0, resolved.target));
19568
19818
  continue;
19569
19819
  }
19570
- const hint = closest(resolved.target, candidatesFor(page.locale, lookup, resolvedOptions));
19820
+ const hint = closest2(resolved.target, candidatesFor(page.locale, lookup, resolvedOptions));
19571
19821
  out.push(diag(page.path, "CB_LINK_UNRESOLVED", "error", `linksTo "${resolved.target}" does not resolve to any page`, hint ? `Did you mean "${hint}"?` : void 0, resolved.target));
19572
19822
  }
19573
19823
  }
@@ -19755,7 +20005,7 @@ function inputForPage(page, inputs, options) {
19755
20005
  function diag(file2, code2, severity, message, hint, target) {
19756
20006
  return { file: file2, diagnostic: { code: code2, severity, message, hint, position: FM_POSITION }, target };
19757
20007
  }
19758
- function editDistance2(a, b) {
20008
+ function editDistance3(a, b) {
19759
20009
  const dp = Array.from({ length: a.length + 1 }, (_, i) => [i, ...Array(b.length).fill(0)]);
19760
20010
  for (let j = 0; j <= b.length; j++)
19761
20011
  dp[0][j] = j;
@@ -19767,11 +20017,11 @@ function editDistance2(a, b) {
19767
20017
  }
19768
20018
  return dp[a.length][b.length];
19769
20019
  }
19770
- function closest(target, candidates) {
20020
+ function closest2(target, candidates) {
19771
20021
  let best;
19772
20022
  let bestD = Infinity;
19773
20023
  for (const c of candidates) {
19774
- const d = editDistance2(target, c);
20024
+ const d = editDistance3(target, c);
19775
20025
  if (d < bestD) {
19776
20026
  bestD = d;
19777
20027
  best = c;
@@ -19946,9 +20196,11 @@ function normalizeSeoPages(config2, files, linkIndex, linkOptions = {}) {
19946
20196
  for (const file2 of files) {
19947
20197
  const facts = readContentPageFacts(file2.frontmatter, linkOptions);
19948
20198
  const fm = facts.frontmatter;
19949
- const id = contentPageIdentity(facts, file2.path);
20199
+ const identity = contentPageIdentity(facts, file2.path);
20200
+ const id = seoPageId(facts, identity);
19950
20201
  const defaults = pageDefaultsForPath(config2.pageDefaults, file2.path);
19951
- const planned = byId.get(id) ?? (facts.slug ? byId.get(facts.slug) : void 0) ?? findPlannedByPath(byConfigId, file2.path);
20202
+ const planned = byId.get(id) ?? (facts.key ? byId.get(facts.key) : void 0) ?? (facts.slug ? byId.get(facts.slug) : void 0) ?? findPlannedByPath(byConfigId, file2.path);
20203
+ const pageId = planned && !facts.locale ? planned.id : id;
19952
20204
  const linkPage = linkPageByPath.get(file2.path);
19953
20205
  const page = {
19954
20206
  ...planned ?? {
@@ -19958,7 +20210,7 @@ function normalizeSeoPages(config2, files, linkIndex, linkOptions = {}) {
19958
20210
  linkedFrom: [],
19959
20211
  frontmatter: {}
19960
20212
  },
19961
- id: planned?.id ?? id,
20213
+ id: pageId,
19962
20214
  source: "existing",
19963
20215
  path: file2.path,
19964
20216
  key: facts.key ?? planned?.key,
@@ -20112,6 +20364,9 @@ function pathMatches(configId, filePath) {
20112
20364
  function normalizePath(path2) {
20113
20365
  return path2.replaceAll("\\", "/").replace(/^\.\/+/, "");
20114
20366
  }
20367
+ function seoPageId(facts, identity) {
20368
+ return facts.locale ? `${identity}:${facts.locale}` : identity;
20369
+ }
20115
20370
  function plannedLinks(page) {
20116
20371
  return stringArray2(page.frontmatter.linksTo) ?? [];
20117
20372
  }
@@ -20205,139 +20460,282 @@ var init_seo = __esm({
20205
20460
  }
20206
20461
  });
20207
20462
 
20208
- // ../core/dist/validate.js
20209
- function isValidatedDocument(document) {
20210
- return document.__contentbitValidatedDocument === true;
20211
- }
20212
- function isValidatedBlock(node) {
20213
- return node.type === "block" && "data" in node && "definition" in node;
20214
- }
20215
- function checkUrls(value, position, allowed, report) {
20216
- for (const match of value.matchAll(LINK_URL_RE)) {
20217
- const url2 = match[1];
20218
- const scheme = url2.match(HAS_SCHEME_RE);
20219
- if (!scheme)
20220
- continue;
20221
- const protocol = `${scheme[0].slice(0, -1).toLowerCase()}:`;
20222
- if (!allowed.includes(protocol)) {
20223
- report({
20224
- code: "CB_URL_PROTOCOL",
20225
- severity: "error",
20226
- message: `URL protocol "${protocol}" is not allowed.`,
20227
- hint: `Allowed: ${allowed.join(", ")}. Configure via validateDocument options.allowedProtocols.`,
20228
- position
20229
- });
20230
- }
20463
+ // ../core/dist/content-integrity.js
20464
+ function scanContentIntegrity(files, options = {}) {
20465
+ const findings = [];
20466
+ const byPath = new Map(files.map((file2) => [normalizePath2(file2.path), file2]));
20467
+ const byRoute = routeIndex(files, options);
20468
+ const titles = /* @__PURE__ */ new Map();
20469
+ const descriptions = /* @__PURE__ */ new Map();
20470
+ for (const file2 of files) {
20471
+ addDuplicateFinding(findings, titles, file2, "title", "CB_TITLE_DUPLICATE");
20472
+ addDuplicateFinding(findings, descriptions, file2, "description", "CB_DESCRIPTION_DUPLICATE");
20473
+ findings.push(...documentStructureFindings(file2));
20231
20474
  }
20232
- }
20233
- function validateDocument(parsed, registry2, options = {}) {
20234
- const opts = {
20235
- unknownBlocks: options.unknownBlocks ?? "error",
20236
- maxDepth: options.maxDepth ?? 4,
20237
- allowedProtocols: options.allowedProtocols ?? ["http:", "https:", "mailto:"]
20238
- };
20239
- const diagnostics = [...parsed.diagnostics];
20240
- const report = (d) => diagnostics.push(d);
20241
- function walk(nodes, parent, depth) {
20242
- for (const node of nodes) {
20243
- if (node.type === "markdown") {
20244
- checkUrls(node.value, node.position, opts.allowedProtocols, report);
20245
- continue;
20246
- }
20247
- if (depth > opts.maxDepth) {
20248
- report({
20249
- code: "CB_NESTING_DEPTH",
20250
- severity: "error",
20251
- message: `Block "${node.name}" exceeds the maximum nesting depth of ${opts.maxDepth}.`,
20252
- blockName: node.name,
20253
- position: node.openPosition
20254
- });
20475
+ findings.push(...localeKeyFindings(files, options));
20476
+ for (const file2 of files) {
20477
+ for (const link of file2.stats.links.items) {
20478
+ const target = resolveContentLink(link.url, file2.path, byRoute);
20479
+ if (!target)
20255
20480
  continue;
20256
- }
20257
- const def = registry2.get(node.name);
20258
- if (!def) {
20259
- report({
20260
- code: "CB_UNKNOWN_BLOCK",
20261
- severity: opts.unknownBlocks,
20262
- message: `Unknown block "${node.name}".`,
20263
- hint: `Known blocks: ${registry2.all().map((d) => d.name).join(", ")}.`,
20264
- blockName: node.name,
20265
- position: node.openPosition
20481
+ const destination = byPath.get(target.path);
20482
+ if (!destination) {
20483
+ const code2 = target.kind === "route" ? "CB_INTERNAL_URL_UNRESOLVED" : "CB_MARKDOWN_LINK_UNRESOLVED";
20484
+ const label = target.kind === "route" ? "Internal URL" : "Markdown link";
20485
+ findings.push({
20486
+ severity: "warning",
20487
+ code: code2,
20488
+ file: file2.path,
20489
+ line: link.line,
20490
+ column: 1,
20491
+ message: `${label} "${link.url}" does not match a scanned content page`,
20492
+ hint: "Use a known page slug, a relative .md/.mdx path, or update the link target."
20266
20493
  });
20267
20494
  continue;
20268
20495
  }
20269
- let valid = true;
20270
- if (def.childOnly && parent === null) {
20271
- valid = false;
20272
- report({
20273
- code: "CB_CHILD_ONLY",
20274
- severity: "error",
20275
- message: `"${node.name}" is a child block and cannot be used at the top level.`,
20276
- blockName: node.name,
20277
- position: node.openPosition
20496
+ if (target.anchor && !headingAnchors(destination.stats).has(target.anchor)) {
20497
+ findings.push({
20498
+ severity: "warning",
20499
+ code: "CB_MARKDOWN_ANCHOR_UNRESOLVED",
20500
+ file: file2.path,
20501
+ line: link.line,
20502
+ column: 1,
20503
+ message: `Markdown link "${link.url}" points to a missing heading anchor`,
20504
+ hint: `Add a heading with the "${target.anchor}" anchor or update the link.`
20278
20505
  });
20279
20506
  }
20280
- if (def.props) {
20281
- const result = def.props.safeParse(node.props);
20282
- if (result.success) {
20283
- node.props = result.data;
20284
- } else {
20285
- valid = false;
20286
- for (const issue2 of result.error.issues) {
20287
- report({
20288
- code: "CB_PROPS_INVALID",
20289
- severity: "error",
20290
- message: `${node.name}: prop "${issue2.path.join(".") || "(root)"}" ${issue2.message}`,
20291
- blockName: node.name,
20292
- position: node.openPosition
20293
- });
20294
- }
20295
- }
20296
- }
20297
- const before = diagnostics.length;
20298
- const data = def.content.parse(node, report);
20299
- let contentError = false;
20300
- for (let j = before; j < diagnostics.length; j++) {
20301
- if (diagnostics[j].severity === "error") {
20302
- contentError = true;
20303
- break;
20304
- }
20305
- }
20306
- if (contentError)
20307
- valid = false;
20308
- if (valid) {
20309
- ;
20310
- node.data = data;
20311
- node.definition = def;
20312
- }
20313
- walk(node.children, node, depth + 1);
20314
20507
  }
20315
20508
  }
20316
- walk(parsed.document.children, null, 1);
20317
- const ok = !diagnostics.some((d) => d.severity === "error");
20318
- return { ok, document: markValidatedDocument(parsed.document), diagnostics };
20509
+ return findings;
20319
20510
  }
20320
- function markValidatedDocument(document) {
20321
- if (!isValidatedDocument(document)) {
20322
- Object.defineProperty(document, "__contentbitValidatedDocument", {
20323
- value: true,
20324
- enumerable: false
20511
+ function localeKeyFindings(files, options) {
20512
+ const localeField = options.localeField ?? "locale";
20513
+ const keyField = options.keyField ?? "key";
20514
+ const slugField = options.slugField ?? "slug";
20515
+ const locales = new Set(files.map((file2) => normalizedFrontmatterString(file2.frontmatter[localeField])).filter(isDefined));
20516
+ if (locales.size < 2)
20517
+ return [];
20518
+ const findings = [];
20519
+ const coverage = /* @__PURE__ */ new Map();
20520
+ for (const file2 of files) {
20521
+ const locale = normalizedFrontmatterString(file2.frontmatter[localeField]);
20522
+ if (!locale || !normalizedFrontmatterString(file2.frontmatter[slugField]))
20523
+ continue;
20524
+ const key = normalizedFrontmatterString(file2.frontmatter[keyField]);
20525
+ if (!key) {
20526
+ findings.push({
20527
+ severity: "warning",
20528
+ code: "CB_LOCALE_KEY_MISSING",
20529
+ file: file2.path,
20530
+ line: 1,
20531
+ column: 1,
20532
+ message: `localized page for "${locale}" is missing a stable ${keyField}`,
20533
+ hint: `Add ${keyField} so translations can share a stable identity across locales.`
20534
+ });
20535
+ continue;
20536
+ }
20537
+ const entry = coverage.get(key) ?? { file: file2, locales: /* @__PURE__ */ new Set() };
20538
+ entry.locales.add(locale);
20539
+ coverage.set(key, entry);
20540
+ }
20541
+ for (const [key, entry] of coverage) {
20542
+ if (entry.locales.size === locales.size)
20543
+ continue;
20544
+ const missing = [...locales].filter((locale) => !entry.locales.has(locale)).sort();
20545
+ findings.push({
20546
+ severity: "warning",
20547
+ code: "CB_LOCALE_KEY_INCOMPLETE",
20548
+ file: entry.file.path,
20549
+ line: 1,
20550
+ column: 1,
20551
+ message: `key "${key}" is missing locale variant(s): ${missing.join(", ")}`,
20552
+ hint: "Add the missing translations or give intentionally locale-specific pages a distinct key."
20325
20553
  });
20326
20554
  }
20327
- return document;
20555
+ return findings;
20328
20556
  }
20329
- var LINK_URL_RE, HAS_SCHEME_RE;
20330
- var init_validate = __esm({
20331
- "../core/dist/validate.js"() {
20557
+ function addDuplicateFinding(findings, seen, file2, field, code2) {
20558
+ const value = normalizedFrontmatterString(file2.frontmatter[field]);
20559
+ if (!value)
20560
+ return;
20561
+ const prior = seen.get(value);
20562
+ if (!prior) {
20563
+ seen.set(value, file2.path);
20564
+ return;
20565
+ }
20566
+ findings.push({
20567
+ severity: "warning",
20568
+ code: code2,
20569
+ file: file2.path,
20570
+ line: 1,
20571
+ column: 1,
20572
+ message: `${field} "${String(file2.frontmatter[field]).trim()}" also appears in ${prior}`,
20573
+ hint: `Give each content page a distinct ${field}.`
20574
+ });
20575
+ }
20576
+ function documentStructureFindings(file2) {
20577
+ const findings = [];
20578
+ const headings = file2.stats.outline;
20579
+ const h1s = headings.filter((heading) => heading.level === 1);
20580
+ const isPage = typeof file2.frontmatter.slug === "string" && file2.frontmatter.slug.trim() !== "";
20581
+ if (isPage && h1s.length === 0) {
20582
+ findings.push({
20583
+ severity: "warning",
20584
+ code: "CB_H1_MISSING",
20585
+ file: file2.path,
20586
+ line: 1,
20587
+ column: 1,
20588
+ message: "page has no level-one heading",
20589
+ hint: "Add one # heading that names the page."
20590
+ });
20591
+ }
20592
+ if (h1s.length > 1) {
20593
+ findings.push({
20594
+ severity: "warning",
20595
+ code: "CB_H1_MULTIPLE",
20596
+ file: file2.path,
20597
+ line: h1s[1].line,
20598
+ column: 1,
20599
+ message: `page has ${h1s.length} level-one headings`,
20600
+ hint: "Keep one # heading and use ## for top-level sections."
20601
+ });
20602
+ }
20603
+ for (let index = 1; index < headings.length; index++) {
20604
+ const previous = headings[index - 1];
20605
+ const current = headings[index];
20606
+ if (current.level <= previous.level + 1)
20607
+ continue;
20608
+ findings.push({
20609
+ severity: "warning",
20610
+ code: "CB_HEADING_LEVEL_SKIPPED",
20611
+ file: file2.path,
20612
+ line: current.line,
20613
+ column: 1,
20614
+ message: `heading "${current.text}" jumps from h${previous.level} to h${current.level}`,
20615
+ hint: `Insert an h${previous.level + 1} heading or lower this heading level.`
20616
+ });
20617
+ }
20618
+ return findings;
20619
+ }
20620
+ function resolveContentLink(url2, sourcePath, byRoute) {
20621
+ if (url2 === "" || /^[a-z][a-z\d+.-]*:/i.test(url2) || url2.startsWith("//")) {
20622
+ return void 0;
20623
+ }
20624
+ const hash2 = url2.indexOf("#");
20625
+ const rawPath = (hash2 === -1 ? url2 : url2.slice(0, hash2)).split("?", 1)[0];
20626
+ const rawAnchor = hash2 === -1 ? void 0 : url2.slice(hash2 + 1).split("?", 1)[0];
20627
+ const anchor = rawAnchor ? decodeUriComponent(rawAnchor) : void 0;
20628
+ if (rawPath === "") {
20629
+ return { path: normalizePath2(sourcePath), ...anchor ? { anchor } : {}, kind: "markdown" };
20630
+ }
20631
+ if (isRelativeMarkdownPath(rawPath)) {
20632
+ return {
20633
+ path: joinPath(dirname(sourcePath), rawPath),
20634
+ ...anchor ? { anchor } : {},
20635
+ kind: "markdown"
20636
+ };
20637
+ }
20638
+ if (hasFileExtension(rawPath))
20639
+ return void 0;
20640
+ const destination = routeTarget(rawPath, byRoute);
20641
+ return {
20642
+ path: destination?.path ?? `\0${normalizeRoute(rawPath)}`,
20643
+ ...anchor ? { anchor } : {},
20644
+ kind: "route"
20645
+ };
20646
+ }
20647
+ function isRelativeMarkdownPath(value) {
20648
+ return value.startsWith("./") || value.startsWith("../") || /\.mdx?$/i.test(value);
20649
+ }
20650
+ function hasFileExtension(value) {
20651
+ return /\/[^/]+\.[a-z\d]+$/i.test(`/${value}`);
20652
+ }
20653
+ function routeIndex(files, options) {
20654
+ const slugField = options.slugField ?? "slug";
20655
+ const keyField = options.keyField ?? "key";
20656
+ const out = /* @__PURE__ */ new Map();
20657
+ for (const file2 of files) {
20658
+ for (const field of [slugField, keyField]) {
20659
+ const value = normalizedFrontmatterString(file2.frontmatter[field]);
20660
+ if (value)
20661
+ out.set(normalizeRoute(value), file2);
20662
+ }
20663
+ }
20664
+ return out;
20665
+ }
20666
+ function routeTarget(rawPath, byRoute) {
20667
+ const route = normalizeRoute(rawPath);
20668
+ if (!route)
20669
+ return void 0;
20670
+ return byRoute.get(route) ?? byRoute.get(route.slice(route.lastIndexOf("/") + 1));
20671
+ }
20672
+ function normalizeRoute(value) {
20673
+ return decodeUriComponent(value).replace(/^\.\//, "").replace(/^\/+|\/+$/g, "");
20674
+ }
20675
+ function headingAnchors(stats) {
20676
+ const anchors = /* @__PURE__ */ new Set();
20677
+ const occurrences = /* @__PURE__ */ new Map();
20678
+ for (const heading of stats.outline) {
20679
+ const base = headingAnchor(heading.text);
20680
+ if (!base)
20681
+ continue;
20682
+ const count = occurrences.get(base) ?? 0;
20683
+ occurrences.set(base, count + 1);
20684
+ anchors.add(count === 0 ? base : `${base}-${count}`);
20685
+ }
20686
+ return anchors;
20687
+ }
20688
+ function headingAnchor(value) {
20689
+ return value.normalize("NFKD").replace(/[\u0300-\u036f]/g, "").toLowerCase().replace(/[^\p{L}\p{N}\s-]/gu, "").trim().replace(/\s+/g, "-");
20690
+ }
20691
+ function normalizedFrontmatterString(value) {
20692
+ if (typeof value !== "string")
20693
+ return void 0;
20694
+ const normalized = value.trim().replace(/\s+/g, " ").toLocaleLowerCase();
20695
+ return normalized || void 0;
20696
+ }
20697
+ function dirname(path2) {
20698
+ const normalized = normalizePath2(path2);
20699
+ const index = normalized.lastIndexOf("/");
20700
+ return index <= 0 ? normalized.startsWith("/") ? "/" : "" : normalized.slice(0, index);
20701
+ }
20702
+ function joinPath(base, target) {
20703
+ const absolute = target.startsWith("/");
20704
+ const parts = `${base}/${target}`.split("/");
20705
+ const normalized = [];
20706
+ for (const part of parts) {
20707
+ if (part === "" || part === ".")
20708
+ continue;
20709
+ if (part === "..")
20710
+ normalized.pop();
20711
+ else
20712
+ normalized.push(part);
20713
+ }
20714
+ return `${absolute || base.startsWith("/") ? "/" : ""}${normalized.join("/")}`;
20715
+ }
20716
+ function normalizePath2(path2) {
20717
+ return joinPath("", path2.replaceAll("\\", "/"));
20718
+ }
20719
+ function decodeUriComponent(value) {
20720
+ try {
20721
+ return decodeURIComponent(value);
20722
+ } catch {
20723
+ return value;
20724
+ }
20725
+ }
20726
+ function isDefined(value) {
20727
+ return value !== void 0;
20728
+ }
20729
+ var init_content_integrity = __esm({
20730
+ "../core/dist/content-integrity.js"() {
20332
20731
  "use strict";
20333
- LINK_URL_RE = /\]\(([^)\s]+)/g;
20334
- HAS_SCHEME_RE = /^[a-zA-Z][a-zA-Z0-9+.-]*:/;
20335
20732
  }
20336
20733
  });
20337
20734
 
20338
20735
  // ../core/dist/project-scan.js
20339
20736
  function scanContentProject(files, registry2, options = {}) {
20340
20737
  const includeStatsFindings = options.includeStatsFindings ?? true;
20738
+ const includeIntegrityFindings = options.includeIntegrityFindings ?? true;
20341
20739
  const minSectionWords = options.minSectionWords ?? DEFAULT_MIN_SECTION_WORDS;
20342
20740
  const scannedFiles = [];
20343
20741
  const findings = [];
@@ -20345,7 +20743,7 @@ function scanContentProject(files, registry2, options = {}) {
20345
20743
  for (const file2 of files) {
20346
20744
  const frontmatter = extractFrontmatter(file2.source)?.data ?? {};
20347
20745
  linkInputs.push({ path: file2.path, data: frontmatter });
20348
- const validation = validateDocument(parseDocument(stripFrontmatter(file2.source)), registry2);
20746
+ const validation = compileDocument(file2.source, registry2);
20349
20747
  const fileFindings = validation.diagnostics.map((diagnostic) => findingFromDiagnostic("validation", file2.path, diagnostic));
20350
20748
  const stats = analyzeDocument(file2.source, { path: file2.path });
20351
20749
  if (includeStatsFindings) {
@@ -20376,6 +20774,15 @@ function scanContentProject(files, registry2, options = {}) {
20376
20774
  linkIndex = buildLinkIndex(linkInputs, options.linkOptions);
20377
20775
  linkGraph = createLinkGraphView(linkIndex, linkDiagnostics).summary;
20378
20776
  }
20777
+ if (includeIntegrityFindings) {
20778
+ for (const integrity of scanContentIntegrity(scannedFiles, options.linkOptions)) {
20779
+ const finding2 = { source: "integrity", ...integrity };
20780
+ findings.push(finding2);
20781
+ const scanned = scannedFiles.find((item) => item.path === finding2.file);
20782
+ if (scanned)
20783
+ scanned.findings.push(finding2);
20784
+ }
20785
+ }
20379
20786
  const seo = options.seoConfig ? evaluateSeoProject({
20380
20787
  config: options.seoConfig,
20381
20788
  configPath: options.seoConfigPath,
@@ -20495,12 +20902,12 @@ var init_project_scan = __esm({
20495
20902
  "../core/dist/project-scan.js"() {
20496
20903
  "use strict";
20497
20904
  init_analyze();
20905
+ init_compile();
20498
20906
  init_frontmatter();
20499
20907
  init_link_graph();
20500
20908
  init_links();
20501
- init_parser();
20502
20909
  init_seo();
20503
- init_validate();
20910
+ init_content_integrity();
20504
20911
  DEFAULT_MIN_SECTION_WORDS = 25;
20505
20912
  BLOCKLESS_WORDS = 250;
20506
20913
  }
@@ -20826,6 +21233,12 @@ var init_content_models = __esm({
20826
21233
  });
20827
21234
 
20828
21235
  // ../core/dist/render-markdown.js
21236
+ function defineMarkdownBlockRenderer(_definition, renderer) {
21237
+ return renderer;
21238
+ }
21239
+ function defineMarkdownRenderers(_definitions, renderers) {
21240
+ return renderers;
21241
+ }
20829
21242
  function renderToMarkdown(document, opts = {}) {
20830
21243
  const ctx = {
20831
21244
  renderNodes(nodes) {
@@ -20852,7 +21265,6 @@ var init_render_markdown = __esm({
20852
21265
  var init_dist = __esm({
20853
21266
  "../core/dist/index.js"() {
20854
21267
  "use strict";
20855
- init_parser();
20856
21268
  init_frontmatter();
20857
21269
  init_analyze();
20858
21270
  init_project_scan();
@@ -20861,6 +21273,7 @@ var init_dist = __esm({
20861
21273
  init_registry();
20862
21274
  init_content_models();
20863
21275
  init_validate();
21276
+ init_compile();
20864
21277
  init_render_markdown();
20865
21278
  init_links();
20866
21279
  }
@@ -20896,11 +21309,11 @@ var init_callout = __esm({
20896
21309
  example: ':::callout{type="tip" title="Worth knowing"}\nAlways weigh flour \u2014 volume measures drift by 20%.\n:::'
20897
21310
  }
20898
21311
  });
20899
- calloutMarkdown = (node) => {
21312
+ calloutMarkdown = defineMarkdownBlockRenderer(calloutBlock, (node) => {
20900
21313
  const data = node.data;
20901
- const title = node.props.title ?? String(node.props.type ?? "note");
21314
+ const title = node.props.title ?? node.props.type;
20902
21315
  return `> **${title}:** ${data.markdown}`;
20903
- };
21316
+ });
20904
21317
  }
20905
21318
  });
20906
21319
 
@@ -20928,16 +21341,16 @@ var init_comparison = __esm({
20928
21341
  example: ':::comparison{left="Option A" right="Option B"}\n- Speed | Fast | Slow\n- Setup | Simple | Advanced\n:::'
20929
21342
  }
20930
21343
  });
20931
- comparisonMarkdown = (node) => {
21344
+ comparisonMarkdown = defineMarkdownBlockRenderer(comparisonBlock, (node) => {
20932
21345
  const data = node.data;
20933
21346
  const esc2 = (s) => s.replace(/\|/g, "\\|");
20934
- const left = esc2(String(node.props.left));
20935
- const right = esc2(String(node.props.right));
21347
+ const left = esc2(node.props.left);
21348
+ const right = esc2(node.props.right);
20936
21349
  const lines = [`| | ${left} | ${right} |`, "|---|---|---|"];
20937
21350
  for (const row of data.rows)
20938
21351
  lines.push(`| ${esc2(row.label)} | ${esc2(row.left)} | ${esc2(row.right)} |`);
20939
21352
  return lines.join("\n");
20940
- };
21353
+ });
20941
21354
  }
20942
21355
  });
20943
21356
 
@@ -20971,7 +21384,7 @@ var init_faq = __esm({
20971
21384
  example: ':::faq\n::faq-item{question="Can I freeze it?"}\nYes, up to 3 months.\n:::'
20972
21385
  }
20973
21386
  });
20974
- faqMarkdown = (node) => {
21387
+ faqMarkdown = defineMarkdownBlockRenderer(faqBlock, (node) => {
20975
21388
  const data = node.data;
20976
21389
  return data.blocks.map((item) => {
20977
21390
  const body = isValidatedBlock(item) ? item.data.markdown : item.body.trim();
@@ -20979,7 +21392,7 @@ var init_faq = __esm({
20979
21392
 
20980
21393
  ${body}`;
20981
21394
  }).join("\n\n");
20982
- };
21395
+ });
20983
21396
  }
20984
21397
  });
20985
21398
 
@@ -20999,10 +21412,10 @@ var init_key_metrics = __esm({
20999
21412
  example: ":::key-metrics\n- 42% | Conversion lift\n- 18ms | Median parse time\n:::"
21000
21413
  }
21001
21414
  });
21002
- keyMetricsMarkdown = (node) => {
21415
+ keyMetricsMarkdown = defineMarkdownBlockRenderer(keyMetricsBlock, (node) => {
21003
21416
  const data = node.data;
21004
21417
  return data.rows.map((row) => `- **${row.value}** \u2014 ${row.label}`).join("\n");
21005
- };
21418
+ });
21006
21419
  }
21007
21420
  });
21008
21421
 
@@ -21028,7 +21441,7 @@ var init_pros_cons = __esm({
21028
21441
  example: ":::pros-cons\n+ Cheap to run\n+ Fast setup\n- No offline mode\n:::"
21029
21442
  }
21030
21443
  });
21031
- prosConsMarkdown = (node) => {
21444
+ prosConsMarkdown = defineMarkdownBlockRenderer(prosConsBlock, (node) => {
21032
21445
  const { pros, cons } = splitProsCons(node.data);
21033
21446
  const parts = [];
21034
21447
  if (pros.length > 0)
@@ -21039,7 +21452,7 @@ var init_pros_cons = __esm({
21039
21452
  parts.push("**Cons**", "", ...cons.map((c) => `- ${c}`));
21040
21453
  }
21041
21454
  return parts.join("\n");
21042
- };
21455
+ });
21043
21456
  }
21044
21457
  });
21045
21458
 
@@ -21062,10 +21475,10 @@ var init_quick_ref = __esm({
21062
21475
  example: ":::quick-ref\n- Hydration | 65%\n- Proof time | 2h at 24\xB0C\n:::"
21063
21476
  }
21064
21477
  });
21065
- quickRefMarkdown = (node) => {
21478
+ quickRefMarkdown = defineMarkdownBlockRenderer(quickRefBlock, (node) => {
21066
21479
  const data = node.data;
21067
21480
  return data.rows.map((row) => `- **${row.key}:** ${row.value}`).join("\n");
21068
- };
21481
+ });
21069
21482
  }
21070
21483
  });
21071
21484
 
@@ -21085,10 +21498,10 @@ var init_steps = __esm({
21085
21498
  example: ":::steps\n1. Combine flour and water\n2. Rest 20 minutes\n3. Add salt and mix\n:::"
21086
21499
  }
21087
21500
  });
21088
- stepsMarkdown = (node) => {
21501
+ stepsMarkdown = defineMarkdownBlockRenderer(stepsBlock, (node) => {
21089
21502
  const data = node.data;
21090
21503
  return data.items.map((item, i) => `${i + 1}. ${item.text}`).join("\n");
21091
- };
21504
+ });
21092
21505
  }
21093
21506
  });
21094
21507
 
@@ -21125,7 +21538,7 @@ var init_tabs = __esm({
21125
21538
  example: ':::tabs\n::tab{title="Fast"}\nUse this when time matters.\n::tab{title="Cheap"}\nUse this when budget matters.\n:::'
21126
21539
  }
21127
21540
  });
21128
- tabsMarkdown = (node) => {
21541
+ tabsMarkdown = defineMarkdownBlockRenderer(tabsBlock, (node) => {
21129
21542
  const data = node.data;
21130
21543
  return data.blocks.map((tab) => {
21131
21544
  const body = isValidatedBlock(tab) ? tab.data.markdown : tab.body.trim();
@@ -21133,29 +21546,19 @@ var init_tabs = __esm({
21133
21546
 
21134
21547
  ${body}`;
21135
21548
  }).join("\n\n");
21136
- };
21549
+ });
21137
21550
  }
21138
21551
  });
21139
21552
 
21140
21553
  // ../blocks/dist/index.js
21141
21554
  function genericBlocks() {
21142
- return [
21143
- calloutBlock,
21144
- stepsBlock,
21145
- keyMetricsBlock,
21146
- quickRefBlock,
21147
- comparisonBlock,
21148
- prosConsBlock,
21149
- tabsBlock,
21150
- tabBlock,
21151
- faqBlock,
21152
- faqItemBlock
21153
- ];
21555
+ return [...genericBlockDefinitions];
21154
21556
  }
21155
- var genericMarkdownRenderers;
21557
+ var genericBlockDefinitions, genericMarkdownRenderers;
21156
21558
  var init_dist2 = __esm({
21157
21559
  "../blocks/dist/index.js"() {
21158
21560
  "use strict";
21561
+ init_dist();
21159
21562
  init_callout();
21160
21563
  init_comparison();
21161
21564
  init_faq();
@@ -21172,7 +21575,19 @@ var init_dist2 = __esm({
21172
21575
  init_quick_ref();
21173
21576
  init_steps();
21174
21577
  init_tabs();
21175
- genericMarkdownRenderers = {
21578
+ genericBlockDefinitions = [
21579
+ calloutBlock,
21580
+ stepsBlock,
21581
+ keyMetricsBlock,
21582
+ quickRefBlock,
21583
+ comparisonBlock,
21584
+ prosConsBlock,
21585
+ tabsBlock,
21586
+ tabBlock,
21587
+ faqBlock,
21588
+ faqItemBlock
21589
+ ];
21590
+ genericMarkdownRenderers = defineMarkdownRenderers(genericBlockDefinitions, {
21176
21591
  callout: calloutMarkdown,
21177
21592
  steps: stepsMarkdown,
21178
21593
  "key-metrics": keyMetricsMarkdown,
@@ -21181,7 +21596,7 @@ var init_dist2 = __esm({
21181
21596
  "pros-cons": prosConsMarkdown,
21182
21597
  tabs: tabsMarkdown,
21183
21598
  faq: faqMarkdown
21184
- };
21599
+ });
21185
21600
  }
21186
21601
  });
21187
21602
 
@@ -21272,7 +21687,7 @@ var init_load_registry = __esm({
21272
21687
  var AGENTS_default;
21273
21688
  var init_AGENTS = __esm({
21274
21689
  "src/commands/agent-templates/AGENTS.md?raw"() {
21275
- AGENTS_default = '<!-- contentbit:start -->\n\n## contentbit content (generated \u2014 edits inside this block are overwritten)\n\nThis project validates Markdown content with contentbit. Documents are plain\nMarkdown plus directive blocks (`:::name{props} ... :::`), each with a schema.\nThe `content:check` script in package.json holds the canonical validate\ncommand \u2014 the content glob plus any `--registry` and `--no-generic-blocks`\nflags \u2014 reuse its arguments.\nIf the project has a `content:links` script, use it to build the internal-link\nindex; otherwise run `contentbit links <content glob>`.\nIf `contentbit.seo.config.ts` exists and the user is creating or revising a\nsearch-targeted page, run `contentbit brief <key-or-slug> [content glob]` first\nand treat the brief as the structure contract for the writer.\n\nWhen writing or editing content:\n\n1. Fetch the live authoring guide first \u2014 never guess block syntax:\n `contentbit instructions --audience llm [--registry <path>] [--no-generic-blocks]`\n2. For SEO-planned pages, fetch the page brief:\n `contentbit brief <key-or-slug> [content glob] [--registry <path>] [--no-generic-blocks]`\n3. Write plain Markdown; use blocks where the guide\'s use-when guidance fits\n and satisfy any brief acceptance checks.\n4. If sibling documents use `slug` / `linksTo`, read\n `.contentbit/link-index.json` from `contentbit links <content glob>` and\n author frontmatter links with existing slugs. When creating a linked page,\n include `keywords.primary` and `keywords.secondary` with search-intent\n phrases future agents can use to choose related pages.\n5. Validate until clean (exit 0): `contentbit validate <file> [--registry <path>] [--no-generic-blocks]`.\n Diagnostics print as `file:line:col severity CODE message` with fix hints.\n For link frontmatter, validate the full content glob so cross-file checks run.\n\nWhen auditing content health:\n\n- `contentbit doctor "content/**/*.md" [--registry <path>] [--no-generic-blocks]` prints a ranked,\n read-only repair plan: validation issues, link issues, thin sections,\n block-less long documents, and missing image alt text.\n- `contentbit doctor "content/**/*.md" [--registry <path>] [--no-generic-blocks] --json` prints the\n same findings as structured JSON for agents and CI.\n- `contentbit stats "content/**/*.md" [--registry <path>] [--no-generic-blocks]` prints raw JSON\n stats: outline word counts, block usage, link domains, and validation\n error/warning counts.\n- `contentbit links "content/**/*.md" [--fix]` builds\n `.contentbit/link-index.json`, reports dangling links/orphans, and rewrites\n alias references in `linksTo` when `--fix` is used.\n\nIf `contentbit` is unavailable, suggest `npx contentbit@latest init` instead\nof inventing block syntax.\n\n<!-- contentbit:end -->\n';
21690
+ AGENTS_default = "<!-- contentbit:start -->\n\n## contentbit content (generated \u2014 edits inside this block are overwritten)\n\nThis project validates Markdown content with contentbit. Documents are plain\nMarkdown plus directive blocks (`:::name{props} ... :::`), each with a schema.\nFind the nearest `contentbit.config.*` or workspace package that declares\ncontentbit (it may be nested in a monorepo), and run commands from that\ndirectory. The config holds the canonical content glob, registry, link fields,\nand SEO config, so commands normally need no repeated project flags.\nIf the project has a `content:links` script, use it to build the internal-link\nindex; otherwise run `contentbit links <content glob>`.\nIf `contentbit.seo.config.ts` exists and the user is creating or revising a\nsearch-targeted page, run `contentbit brief <key-or-slug> [content glob]` first\nand treat the brief as the structure contract for the writer.\n\nWhen writing or editing content:\n\n1. Fetch the live authoring guide first \u2014 never guess block syntax:\n `contentbit instructions --audience llm`\n2. For SEO-planned pages, fetch the page brief:\n `contentbit brief <key-or-slug>`\n3. Write plain Markdown; use blocks where the guide's use-when guidance fits\n and satisfy any brief acceptance checks.\n4. If sibling documents use `slug` / `linksTo`, read\n `.contentbit/link-index.json` from `contentbit links <content glob>` and\n author frontmatter links with existing slugs. When creating a linked page,\n include `keywords.primary` and `keywords.secondary` with search-intent\n phrases future agents can use to choose related pages.\n5. Validate until clean (exit 0): `contentbit validate <file>`.\n Diagnostics print as `file:line:col severity CODE message` with fix hints.\n For link frontmatter, validate the full content glob so cross-file checks run.\n\nWhen auditing content health:\n\n- `contentbit doctor` prints a ranked,\n read-only repair plan: validation issues, link issues, thin sections,\n block-less long documents, and missing image alt text.\n- `contentbit doctor --json` prints the\n same findings as structured JSON for agents and CI.\n- `contentbit stats` prints raw JSON\n stats: outline word counts, block usage, link domains, and validation\n error/warning counts.\n- `contentbit links [--fix]` builds\n `.contentbit/link-index.json`, reports dangling links/orphans, and rewrites\n alias references in `linksTo` when `--fix` is used.\n\nIf `contentbit` is unavailable, suggest `npx contentbit@latest init` instead\nof inventing block syntax.\n\n<!-- contentbit:end -->\n";
21276
21691
  }
21277
21692
  });
21278
21693
 
@@ -21280,7 +21695,7 @@ var init_AGENTS = __esm({
21280
21695
  var SKILL_default;
21281
21696
  var init_SKILL = __esm({
21282
21697
  "src/commands/agent-templates/contentbit-audit/SKILL.md?raw"() {
21283
- SKILL_default = '---\nname: contentbit-audit\ndescription: |\n Audit contentbit Markdown content health using document stats. Use when asked\n to audit, review, or find improvements across content \u2014 thin pages, missing\n structure, validation issues \u2014 in a project that uses contentbit.\nversion: 5\n---\n\n# Auditing contentbit content\n\n`contentbit doctor` is the first audit command. It reads content once, runs\nblock validation, link validation, and document stats, then prints a ranked\nrepair plan. It is read-only: it does not write the link index and never edits\nsource files. `contentbit stats` remains useful when you need raw JSON metrics.\n`contentbit links` builds the frontmatter-authored internal-link graph and can\nheal alias references with `--fix`.\nWhen `contentbit.seo.config.ts` exists, `doctor` also reports SEO contract\nfindings, and `contentbit brief <key-or-slug> [content glob]` gives page-level\nstructure requirements for an agent or human writer.\n\n## Gather\n\nCheck `package.json` for `content:doctor` first. If it exists, run it. If it\ndoes not, use `content:check` to find this project\'s content glob and\n`--registry` / `--no-generic-blocks` flags, then run:\n\n```sh\ncontentbit doctor "content/**/*.md" [--registry <path>] [--no-generic-blocks]\ncontentbit doctor "content/**/*.md" [--registry <path>] [--no-generic-blocks] --json\ncontentbit stats "content/**/*.md" [--registry <path>] [--no-generic-blocks]\ncontentbit links "content/**/*.md"\n```\n\n`doctor --json` prints a stable report with summary counts and ranked\nfindings. `stats` prints per-file metrics: frontmatter data, a heading\n`outline` with per-section word counts, `blocks.byName` usage counts,\n`links.domains`, and a `validation` summary (`errors`/`warnings`).\n`contentbit links` writes `.contentbit/link-index.json`, whose pages contain\n`slug`, resolved `linksTo`, derived `linkedFrom`, `aliases`, and\n`keywords`.\n\n## Interpret\n\nPrioritize findings in the order `doctor` reports them:\n\n1. **Validation errors and warnings** \u2014 broken content ships broken pages.\n2. **Internal-link errors** \u2014 unresolved links, duplicate slugs, and alias\n conflicts from `contentbit links`.\n3. **Orphans and self-links** \u2014 link warnings that point to isolated or noisy\n pages.\n4. **Thin documents** \u2014 outline sections with very low word counts.\n5. **Block-less documents** \u2014 `blocks.byName` empty where sibling documents\n use blocks; structure (steps, callouts, comparisons, faq) may be missing.\n6. **Missing or inconsistent frontmatter** compared to sibling documents.\n7. **Structural imbalance** \u2014 skipped heading levels, single-section walls of text.\n8. **SEO contract findings** \u2014 missing page type, required sections, required\n blocks, required link targets, or brief acceptance checks when SEO config is\n present.\n\n## Report\n\nReport findings per file with concrete suggestions, ordered by priority. Do not\nedit files during the audit. To fix a finding, follow the contentbit-author\nskill (fetch the guide, edit, validate until clean) \u2014 offer that as a follow-up.\n';
21698
+ SKILL_default = "---\nname: contentbit-audit\ndescription: |\n Audit contentbit Markdown content health using document stats. Use when asked\n to audit, review, or find improvements across content \u2014 thin pages, missing\n structure, validation issues \u2014 in a project that uses contentbit.\nversion: 7\n---\n\n# Auditing contentbit content\n\n`contentbit doctor` is the first audit command. It reads content once, runs\nblock validation, link validation, and document stats, then prints a ranked\nrepair plan. It is read-only: it does not write the link index and never edits\nsource files. `contentbit stats` remains useful when you need raw JSON metrics.\n`contentbit links` builds the frontmatter-authored internal-link graph and can\nheal alias references with `--fix`.\nWhen `contentbit.seo.config.ts` exists, `doctor` also reports SEO contract\nfindings, and `contentbit brief <key-or-slug> [content glob]` gives page-level\nstructure requirements for an agent or human writer.\n\n## Gather\n\nFind the nearest `contentbit.config.*` or workspace package that declares\ncontentbit (it may be nested in a monorepo), and run commands from that\ndirectory. Project configuration supplies the content glob, registry, link\nfields, and SEO config, so run:\n\n```sh\ncontentbit doctor\ncontentbit doctor --json\ncontentbit stats\ncontentbit links\n```\n\n`doctor --json` prints a stable report with summary counts and ranked\nfindings. `stats` prints per-file metrics: frontmatter data, a heading\n`outline` with per-section word counts, `blocks.byName` usage counts,\n`links.domains`, and a `validation` summary (`errors`/`warnings`).\n`contentbit links` writes `.contentbit/link-index.json`, whose pages contain\n`slug`, resolved `linksTo`, derived `linkedFrom`, `aliases`, and\n`keywords`.\n\n## Interpret\n\nPrioritize findings in the order `doctor` reports them:\n\n1. **Validation errors and warnings** \u2014 broken content ships broken pages.\n2. **Internal-link errors** \u2014 unresolved links, duplicate slugs, and alias\n conflicts from `contentbit links`.\n3. **Orphans and self-links** \u2014 link warnings that point to isolated or noisy\n pages.\n4. **Thin documents** \u2014 outline sections with very low word counts.\n5. **Block-less documents** \u2014 `blocks.byName` empty where sibling documents\n use blocks; structure (steps, callouts, comparisons, faq) may be missing.\n6. **Missing or inconsistent frontmatter** compared to sibling documents.\n7. **Structural imbalance** \u2014 skipped heading levels, single-section walls of text.\n8. **SEO contract findings** \u2014 missing page type, required sections, required\n blocks, required link targets, or brief acceptance checks when SEO config is\n present.\n\n## Report\n\nReport findings per file with concrete suggestions, ordered by priority. Do not\nedit files during the audit. To fix a finding, follow the contentbit-author\nskill (fetch the guide, edit, validate until clean) \u2014 offer that as a follow-up.\n";
21284
21699
  }
21285
21700
  });
21286
21701
 
@@ -21288,7 +21703,7 @@ var init_SKILL = __esm({
21288
21703
  var SKILL_default2;
21289
21704
  var init_SKILL2 = __esm({
21290
21705
  "src/commands/agent-templates/contentbit-author/SKILL.md?raw"() {
21291
- SKILL_default2 = "---\nname: contentbit-author\ndescription: |\n Write or edit contentbit Markdown content (directive blocks like :::callout).\n Use when asked to create or modify content documents in a project that uses\n contentbit \u2014 blog posts, docs pages, changelogs, any Markdown covered by\n `contentbit validate`.\nversion: 5\n---\n\n# Writing contentbit content\n\ncontentbit documents are plain Markdown plus directive blocks\n(`:::name{props} ... :::`). Every block has a schema. Never guess block names,\nprops, or body shapes \u2014 fetch the live guide from the project's registry first.\n\n## Find the project conventions\n\nCheck `package.json` for a `content:check` script. It holds the canonical\nvalidate invocation for this project: the content glob and, if present, the\n`--registry <path>` and `--no-generic-blocks` flags. Reuse those arguments\nbelow. No script? Default to `content/**/*.md` with no `--registry` flag.\nIf the project has a `content:links` script, use it for the internal-link\nindex; otherwise run `contentbit links <content glob>` directly.\nIf `contentbit.seo.config.ts` exists and the request names a page `key` or\n`slug`, run `contentbit brief <key-or-slug> [content glob]` before writing.\n\n## The loop\n\n1. **Fetch the authoring guide** (always \u2014 it covers this project's custom blocks):\n\n ```sh\n contentbit instructions --audience llm [--registry <path from content:check>] [--no-generic-blocks]\n ```\n\n Read it before writing. It documents every available block: props, body\n shape, and when to use or avoid it.\n\n2. **Fetch the SEO brief when present.** If the project has SEO config and the\n target page has a known `key` or `slug`, run:\n\n ```sh\n contentbit brief <key-or-slug> [content glob] [--registry <path>] [--no-generic-blocks]\n ```\n\n Treat the brief as the structure contract: page type, required sections,\n required/recommended blocks, internal links, and acceptance checks.\n\n3. **Write the document.** Plain Markdown everywhere; blocks only where the\n guide's use-when guidance fits. Keep frontmatter consistent with sibling\n documents in the same folder. If sibling documents use `slug`, `linksTo`,\n `aliases`, or `keywords`, run the link index first:\n\n ```sh\n contentbit links <content glob>\n ```\n\n Read `.contentbit/link-index.json` to pick existing slugs and related\n pages. Author only `slug`, `linksTo`, `aliases`, and `keywords` in\n frontmatter; never write derived `linkedFrom` into source files. When\n creating a linked page, include `keywords.primary` and\n `keywords.secondary` with search-intent phrases that would help future\n agents choose this page as a `linksTo` target.\n\n4. **Validate and fix until clean:**\n\n ```sh\n contentbit validate <file> [--registry <path>] [--no-generic-blocks]\n ```\n\n Diagnostics print to stderr as `file:line:col severity CODE message`, often\n with a `hint:` line suggesting the fix. Exit 0 means clean; exit 1 means\n errors remain. If the document has link frontmatter, validate the full\n content glob so cross-file links are checked against the whole graph. Fix\n every diagnostic and re-run. Never finish with a failing validate.\n\n5. **Refresh internal links when present:**\n\n ```sh\n contentbit links <content glob> --fix\n ```\n\n `--fix` only rewrites `linksTo` values that point at known aliases. It\n does not invent links, remove aliases, or write backlinks. Re-run validate\n after it changes files.\n\n## Failure modes\n\n- `contentbit` not found or no registry resolvable: the project is not set up.\n Say so and suggest `npx contentbit@latest init` \u2014 do not invent block syntax.\n- A block you want does not exist: use plain Markdown, or ask whether to define\n a custom block in the registry. Never emit an unregistered block name.\n";
21706
+ SKILL_default2 = "---\nname: contentbit-author\ndescription: |\n Write or edit contentbit Markdown content (directive blocks like :::callout).\n Use when asked to create or modify content documents in a project that uses\n contentbit \u2014 blog posts, docs pages, changelogs, any Markdown covered by\n `contentbit validate`.\nversion: 7\n---\n\n# Writing contentbit content\n\ncontentbit documents are plain Markdown plus directive blocks\n(`:::name{props} ... :::`). Every block has a schema. Never guess block names,\nprops, or body shapes \u2014 fetch the live guide from the project's registry first.\n\n## Find the project conventions\n\nFind the nearest `contentbit.config.*` or workspace package that declares\ncontentbit (it may be nested in a monorepo), and run commands from that\ndirectory. The config holds the content glob, registry, link fields, and SEO\nconfig; command-line flags only override it for one invocation.\nIf the project has a `content:links` script, use it for the internal-link\nindex; otherwise run `contentbit links <content glob>` directly.\nIf `contentbit.seo.config.ts` exists and the request names a page `key` or\n`slug`, run `contentbit brief <key-or-slug> [content glob]` before writing.\n\n## The loop\n\n1. **Fetch the authoring guide** (always \u2014 it covers this project's custom blocks):\n\n ```sh\n contentbit instructions --audience llm\n ```\n\n Read it before writing. It documents every available block: props, body\n shape, and when to use or avoid it.\n\n2. **Fetch the SEO brief when present.** If the project has SEO config and the\n target page has a known `key` or `slug`, run:\n\n ```sh\n contentbit brief <key-or-slug>\n ```\n\n Treat the brief as the structure contract: page type, required sections,\n required/recommended blocks, internal links, and acceptance checks.\n\n3. **Write the document.** Plain Markdown everywhere; blocks only where the\n guide's use-when guidance fits. Keep frontmatter consistent with sibling\n documents in the same folder. If sibling documents use `slug`, `linksTo`,\n `aliases`, or `keywords`, run the link index first:\n\n ```sh\n contentbit links\n ```\n\n Read `.contentbit/link-index.json` to pick existing slugs and related\n pages. Author only `slug`, `linksTo`, `aliases`, and `keywords` in\n frontmatter; never write derived `linkedFrom` into source files. When\n creating a linked page, include `keywords.primary` and\n `keywords.secondary` with search-intent phrases that would help future\n agents choose this page as a `linksTo` target.\n\n4. **Validate and fix until clean:**\n\n ```sh\n contentbit validate <file>\n ```\n\n Diagnostics print to stderr as `file:line:col severity CODE message`, often\n with a `hint:` line suggesting the fix. Exit 0 means clean; exit 1 means\n errors remain. If the document has link frontmatter, validate the full\n content glob so cross-file links are checked against the whole graph. Fix\n every diagnostic and re-run. Never finish with a failing validate.\n\n5. **Refresh internal links when present:**\n\n ```sh\n contentbit links --fix\n ```\n\n `--fix` only rewrites `linksTo` values that point at known aliases. It\n does not invent links, remove aliases, or write backlinks. Re-run validate\n after it changes files.\n\n## Failure modes\n\n- `contentbit` not found or no registry resolvable: the project is not set up.\n Say so and suggest `npx contentbit@latest init` \u2014 do not invent block syntax.\n- A block you want does not exist: use plain Markdown, or ask whether to define\n a custom block in the registry. Never emit an unregistered block name.\n";
21292
21707
  }
21293
21708
  });
21294
21709
 
@@ -21298,60 +21713,183 @@ __export(agents_exports, {
21298
21713
  agentsCommand: () => agentsCommand,
21299
21714
  installAgentIntegration: () => installAgentIntegration
21300
21715
  });
21301
- import { existsSync } from "node:fs";
21716
+ import { existsSync, readFileSync } from "node:fs";
21302
21717
  import { mkdir, readFile as readFile2, writeFile } from "node:fs/promises";
21303
- import { join as join2 } from "node:path";
21304
- function upsertBlock(existing) {
21718
+ import { dirname as dirname2, join as join2, relative as relative2, resolve, sep } from "node:path";
21719
+ function upsertBlock(existing, block = AGENTS_MD_BLOCK) {
21305
21720
  const start = existing.indexOf(START);
21306
21721
  const end = existing.indexOf(END);
21307
21722
  if (start !== -1 && end !== -1) {
21308
- return existing.slice(0, start) + AGENTS_MD_BLOCK + existing.slice(end + END.length);
21723
+ return existing.slice(0, start) + block + existing.slice(end + END.length);
21309
21724
  }
21310
- if (existing.trim() === "") return `${AGENTS_MD_BLOCK}
21725
+ if (existing.trim() === "") return `${block}
21311
21726
  `;
21312
- return `${existing.replace(/\n*$/, "\n\n")}${AGENTS_MD_BLOCK}
21727
+ return `${existing.replace(/\n*$/, "\n\n")}${block}
21313
21728
  `;
21314
21729
  }
21730
+ function rootPointerBlock(packagePath) {
21731
+ return [
21732
+ START,
21733
+ "",
21734
+ "## contentbit content (generated \u2014 edits inside this block are overwritten)",
21735
+ "",
21736
+ `content lives in ${packagePath}; run contentbit commands from there.`,
21737
+ "",
21738
+ END
21739
+ ].join("\n");
21740
+ }
21741
+ async function readTextIfExists(path2) {
21742
+ try {
21743
+ return await readFile2(path2, "utf8");
21744
+ } catch {
21745
+ return "";
21746
+ }
21747
+ }
21748
+ function isWorkspaceRoot(path2) {
21749
+ if (existsSync(join2(path2, "pnpm-workspace.yaml"))) return true;
21750
+ if (existsSync(join2(path2, "lerna.json"))) return true;
21751
+ if (existsSync(join2(path2, "nx.json"))) return true;
21752
+ try {
21753
+ const pkg = JSON.parse(readFileSync(join2(path2, "package.json"), "utf8"));
21754
+ return Array.isArray(pkg.workspaces) || typeof pkg.workspaces === "object";
21755
+ } catch {
21756
+ return false;
21757
+ }
21758
+ }
21759
+ function findMonorepoRoot(cwd) {
21760
+ if (!existsSync(join2(cwd, "package.json"))) return void 0;
21761
+ let current = dirname2(cwd);
21762
+ while (current !== dirname2(current)) {
21763
+ if (isWorkspaceRoot(current)) return current;
21764
+ current = dirname2(current);
21765
+ }
21766
+ return void 0;
21767
+ }
21768
+ function displayRelative(from, to) {
21769
+ const rel = relative2(from, to) || ".";
21770
+ return rel.split(sep).join("/");
21771
+ }
21772
+ async function writeRootPointerIfNeeded(cwd, io) {
21773
+ const root = findMonorepoRoot(cwd);
21774
+ if (!root) return;
21775
+ const packagePath = displayRelative(root, cwd);
21776
+ const rootAgentsPath = join2(root, "AGENTS.md");
21777
+ const existing = await readTextIfExists(rootAgentsPath);
21778
+ const created = existing === "";
21779
+ await writeFile(rootAgentsPath, upsertBlock(existing, rootPointerBlock(packagePath)), "utf8");
21780
+ io.stdout(
21781
+ `${created ? "created" : "updated"}: ${displayRelative(cwd, rootAgentsPath)} (contentbit root pointer)`
21782
+ );
21783
+ }
21784
+ async function checkBlockStatus(path2, block, label, io) {
21785
+ const existing = await readTextIfExists(path2);
21786
+ if (existing === "") {
21787
+ io.stdout(`would create: ${label}`);
21788
+ return;
21789
+ }
21790
+ if (upsertBlock(existing, block) === existing) {
21791
+ io.stdout(`up-to-date: ${label}`);
21792
+ return;
21793
+ }
21794
+ io.stdout(`stale: ${label}`);
21795
+ }
21796
+ async function checkRootPointerIfNeeded(cwd, io) {
21797
+ const root = findMonorepoRoot(cwd);
21798
+ if (!root) return;
21799
+ const packagePath = displayRelative(root, cwd);
21800
+ await checkBlockStatus(
21801
+ join2(root, "AGENTS.md"),
21802
+ rootPointerBlock(packagePath),
21803
+ `${displayRelative(cwd, join2(root, "AGENTS.md"))} (contentbit root pointer)`,
21804
+ io
21805
+ );
21806
+ }
21807
+ async function checkAgentIntegration(cwd, options, io) {
21808
+ const claudeDir = join2(cwd, ".claude");
21809
+ const claudeDirExists = existsSync(claudeDir);
21810
+ const claude = options.claude ?? claudeDirExists;
21811
+ const agentsMd = options.agentsMd ?? true;
21812
+ if (agentsMd) {
21813
+ await checkBlockStatus(
21814
+ join2(cwd, "AGENTS.md"),
21815
+ AGENTS_MD_BLOCK,
21816
+ "AGENTS.md (contentbit block)",
21817
+ io
21818
+ );
21819
+ await checkRootPointerIfNeeded(cwd, io);
21820
+ }
21821
+ if (claude) {
21822
+ for (const [name, content] of SKILLS) {
21823
+ const path2 = join2(cwd, ".claude/skills", name, "SKILL.md");
21824
+ const installed = await readTextIfExists(path2);
21825
+ const shippedVersion = skillVersion(content) ?? "unknown";
21826
+ if (installed === "") {
21827
+ io.stdout(`would install: .claude/skills/${name}/SKILL.md (version ${shippedVersion})`);
21828
+ continue;
21829
+ }
21830
+ const installedVersion = skillVersion(installed) ?? "unknown";
21831
+ if (installed === content) {
21832
+ io.stdout(`up-to-date: .claude/skills/${name}/SKILL.md (version ${installedVersion})`);
21833
+ } else {
21834
+ io.stdout(
21835
+ `stale: .claude/skills/${name}/SKILL.md (installed ${installedVersion}, package ${shippedVersion})`
21836
+ );
21837
+ }
21838
+ }
21839
+ if (!claudeDirExists) {
21840
+ io.stdout("would create: .claude/ (restart Claude Code after installing skills)");
21841
+ }
21842
+ } else {
21843
+ io.stdout("skipped: .claude/skills (no .claude directory \u2014 pass --claude to create it)");
21844
+ }
21845
+ }
21846
+ function skillVersion(content) {
21847
+ for (const line of content.split(/\r?\n/)) {
21848
+ const match = line.match(/^version:\s*['"]?([^'"\s]+)['"]?\s*$/);
21849
+ if (match) return match[1];
21850
+ }
21851
+ return void 0;
21852
+ }
21315
21853
  async function installAgentIntegration(cwd, options, io) {
21316
- const claude = options.claude ?? existsSync(join2(cwd, ".claude"));
21854
+ const claudeDir = join2(cwd, ".claude");
21855
+ const claudeDirExists = existsSync(claudeDir);
21856
+ const claude = options.claude ?? claudeDirExists;
21317
21857
  const agentsMd = options.agentsMd ?? true;
21318
21858
  if (agentsMd) {
21319
21859
  const path2 = join2(cwd, "AGENTS.md");
21320
- let existing = "";
21321
- try {
21322
- existing = await readFile2(path2, "utf8");
21323
- } catch {
21324
- }
21860
+ const existing = await readTextIfExists(path2);
21325
21861
  const created = existing === "";
21326
21862
  await writeFile(path2, upsertBlock(existing), "utf8");
21327
21863
  io.stdout(`${created ? "created" : "updated"}: AGENTS.md (contentbit block)`);
21864
+ await writeRootPointerIfNeeded(cwd, io);
21328
21865
  }
21329
21866
  if (claude) {
21330
- const skills = [
21331
- ["contentbit-author", AUTHOR_SKILL],
21332
- ["contentbit-audit", AUDIT_SKILL]
21333
- ];
21334
- for (const [name, content] of skills) {
21867
+ for (const [name, content] of SKILLS) {
21335
21868
  const dir = join2(cwd, ".claude/skills", name);
21336
21869
  await mkdir(dir, { recursive: true });
21337
21870
  await writeFile(join2(dir, "SKILL.md"), content, "utf8");
21338
21871
  io.stdout(`installed: .claude/skills/${name}/SKILL.md`);
21339
21872
  }
21873
+ if (!claudeDirExists) {
21874
+ io.stdout("restart your Claude Code session so skills are picked up.");
21875
+ }
21876
+ } else {
21877
+ io.stdout("skipped: .claude/skills (no .claude directory \u2014 pass --claude to create it)");
21340
21878
  }
21341
21879
  }
21342
21880
  async function agentsCommand(input, io) {
21343
- await installAgentIntegration(
21344
- input.cwd ?? process.cwd(),
21345
- {
21346
- claude: input.claude || void 0,
21347
- // false means "detect", not "skip"
21348
- agentsMd: !input.noAgentsMd
21349
- },
21350
- io
21351
- );
21881
+ const cwd = resolve(input.cwd ?? process.cwd());
21882
+ const options = {
21883
+ claude: input.claude || void 0,
21884
+ // false means "detect", not "skip"
21885
+ agentsMd: !input.noAgentsMd
21886
+ };
21887
+ if (input.check) await checkAgentIntegration(cwd, options, io);
21888
+ else await installAgentIntegration(cwd, options, io);
21889
+ io.stdout(`Guide: ${AGENTS_GUIDE_URL}`);
21352
21890
  return 0;
21353
21891
  }
21354
- var AUTHOR_SKILL, AUDIT_SKILL, AGENTS_MD_BLOCK, START, END;
21892
+ var AUTHOR_SKILL, AUDIT_SKILL, AGENTS_MD_BLOCK, SKILLS, START, END, AGENTS_GUIDE_URL;
21355
21893
  var init_agents = __esm({
21356
21894
  "src/commands/agents.ts"() {
21357
21895
  "use strict";
@@ -21361,8 +21899,13 @@ var init_agents = __esm({
21361
21899
  AUTHOR_SKILL = SKILL_default2;
21362
21900
  AUDIT_SKILL = SKILL_default;
21363
21901
  AGENTS_MD_BLOCK = AGENTS_default.trimEnd();
21902
+ SKILLS = [
21903
+ ["contentbit-author", AUTHOR_SKILL],
21904
+ ["contentbit-audit", AUDIT_SKILL]
21905
+ ];
21364
21906
  START = "<!-- contentbit:start -->";
21365
21907
  END = "<!-- contentbit:end -->";
21908
+ AGENTS_GUIDE_URL = "https://contentbit.dev/docs/guides/agents";
21366
21909
  }
21367
21910
  });
21368
21911
 
@@ -21387,19 +21930,21 @@ function blockComponentsTemplate(styled) {
21387
21930
  </figcaption>
21388
21931
  </figure>
21389
21932
  )`;
21390
- return `import type { BlockComponent, BlockComponentProps } from '@contentbit/react'
21933
+ return `import { defineBlockComponent, defineBlockComponents } from '@contentbit/react'
21934
+
21935
+ import { quote } from './registry'
21391
21936
 
21392
21937
  // One React component per custom block, keyed by block name. Definitions
21393
21938
  // live in ./registry.ts \u2014 add a block there, add its component here, and
21394
21939
  // the rest of the app never changes.
21395
- function QuoteBlock({ node, ctx }: BlockComponentProps) {
21396
- const data = node.data as { markdown: string }
21940
+ const QuoteBlock = defineBlockComponent(quote, ({ node, ctx }) => {
21941
+ const data = node.data
21397
21942
  ${body}
21398
- }
21943
+ })
21399
21944
 
21400
- export const blockComponents: Record<string, BlockComponent> = {
21945
+ export const blockComponents = defineBlockComponents([quote], {
21401
21946
  quote: QuoteBlock,
21402
- }
21947
+ })
21403
21948
  `;
21404
21949
  }
21405
21950
  function reactComponent(styled, mdWired, blocksImport) {
@@ -21416,7 +21961,7 @@ import { ContentRenderer } from '@/components/content-blocks/content-renderer'`
21416
21961
  return `'use client'
21417
21962
 
21418
21963
  import { genericBlocks } from '@contentbit/blocks'
21419
- import { createBlockRegistry, parseDocument, stripFrontmatter, validateDocument } from '@contentbit/core'
21964
+ import { compileDocument, createBlockRegistry } from '@contentbit/core'
21420
21965
  ${reactImport}${mdImport}${rendererImport}
21421
21966
  // Everything block-related lives in the blocks/ folder: definitions in
21422
21967
  // registry.ts (shared with the validate CLI), components in components.tsx.
@@ -21426,7 +21971,7 @@ import { blockComponents } from '${blocksImport}/components'
21426
21971
  const registry = createBlockRegistry().use(genericBlocks()).use(customBlocks)
21427
21972
 
21428
21973
  export function Content({ source }: { source: string }) {
21429
- const result = validateDocument(parseDocument(stripFrontmatter(source)), registry)
21974
+ const result = compileDocument(source, registry)
21430
21975
  return (
21431
21976
  <${renderer}
21432
21977
  document={result.document}
@@ -21461,7 +22006,7 @@ function astroPage(styled) {
21461
22006
  const renderer = styled ? "ContentRenderer" : "ContentBlocks";
21462
22007
  return `---
21463
22008
  import { genericBlocks } from '@contentbit/blocks'
21464
- import { createBlockRegistry, parseDocument, validateDocument } from '@contentbit/core'
22009
+ import { assertValidDocument, compileDocument, createBlockRegistry } from '@contentbit/core'
21465
22010
  import { getEntry } from 'astro:content'
21466
22011
 
21467
22012
  ${importLine}
@@ -21476,11 +22021,11 @@ if (!entry?.body) throw new Error('Entry "example" not found in the articles col
21476
22021
 
21477
22022
  const registry = createBlockRegistry().use(genericBlocks()).use(customBlocks)
21478
22023
  // Static pages render at build time, so invalid blocks fail the build here.
21479
- const result = validateDocument(parseDocument(entry.body), registry)
22024
+ const document = assertValidDocument(compileDocument(entry.body, registry), entry.id)
21480
22025
  ---
21481
22026
 
21482
22027
  <main style="max-width: 42rem; margin: 0 auto; padding: 3rem 1.5rem;">
21483
- <${renderer} document={result.document} components={{ quote: QuoteBlock }} />
22028
+ <${renderer} document={document} components={{ quote: QuoteBlock }} />
21484
22029
  </main>
21485
22030
  `;
21486
22031
  }
@@ -21641,6 +22186,16 @@ import { spawn } from "node:child_process";
21641
22186
  import { existsSync as existsSync3 } from "node:fs";
21642
22187
  import { mkdir as mkdir2, readFile as readFile3, writeFile as writeFile2 } from "node:fs/promises";
21643
22188
  import { join as join4 } from "node:path";
22189
+ function contentConfigTemplate(seo) {
22190
+ return `import { defineContentConfig } from '@contentbit/core'
22191
+
22192
+ export default defineContentConfig({
22193
+ content: 'content/**/*.md',
22194
+ registry: './blocks/registry.ts',
22195
+ genericBlocks: true,${seo ? "\n seo: './contentbit.seo.config.ts'," : ""}
22196
+ })
22197
+ `;
22198
+ }
21644
22199
  function detectPackageManager(cwd) {
21645
22200
  const locks = [
21646
22201
  ["pnpm-lock.yaml", "pnpm"],
@@ -21669,10 +22224,10 @@ function dlxCommand(pm) {
21669
22224
  return ["npx", ["--yes"]];
21670
22225
  }
21671
22226
  function runInstall(pm, args, cwd) {
21672
- return new Promise((resolve) => {
22227
+ return new Promise((resolve4) => {
21673
22228
  const child = spawn(pm, args, { cwd, stdio: "inherit", shell: process.platform === "win32" });
21674
- child.on("close", (code2) => resolve(code2 ?? 1));
21675
- child.on("error", () => resolve(1));
22229
+ child.on("close", (code2) => resolve4(code2 ?? 1));
22230
+ child.on("error", () => resolve4(1));
21676
22231
  });
21677
22232
  }
21678
22233
  async function installStyledPack(cwd, pack, noInstall, io) {
@@ -21767,7 +22322,7 @@ async function initCommand(input, io) {
21767
22322
  }
21768
22323
  const runtime = adapter.runtimeDependencies(md);
21769
22324
  if (input.noInstall) {
21770
- io.stdout(`skipped install: ${runtime.join(" ")} + contentbit (dev)`);
22325
+ io.stdout(`skipped install: ${runtime.join(" ")} + contentbit @contentbit/studio (dev)`);
21771
22326
  } else {
21772
22327
  const pm2 = detectPackageManager(cwd);
21773
22328
  io.stdout(`installing with ${pm2}: ${runtime.join(" ")}`);
@@ -21775,7 +22330,7 @@ async function initCommand(input, io) {
21775
22330
  io.stderr("install failed");
21776
22331
  return 1;
21777
22332
  }
21778
- if (await runInstall(pm2, installArgs(pm2, true, ["contentbit"]), cwd) !== 0) {
22333
+ if (await runInstall(pm2, installArgs(pm2, true, ["contentbit", "@contentbit/studio"]), cwd) !== 0) {
21779
22334
  io.stderr("install failed");
21780
22335
  return 1;
21781
22336
  }
@@ -21790,6 +22345,7 @@ async function initCommand(input, io) {
21790
22345
  installStyledPack: (pack) => installStyledPack(cwd, pack, Boolean(input.noInstall), io)
21791
22346
  });
21792
22347
  const files = [
22348
+ ["contentbit.config.ts", contentConfigTemplate(Boolean(input.seo))],
21793
22349
  ["blocks/registry.ts", REGISTRY_TEMPLATE],
21794
22350
  ["content/example.md", EXAMPLE_CONTENT],
21795
22351
  ["content/related.md", RELATED_CONTENT],
@@ -21803,19 +22359,19 @@ async function initCommand(input, io) {
21803
22359
  const fresh = JSON.parse(await readFile3(pkgPath, "utf8"));
21804
22360
  fresh.scripts ??= {};
21805
22361
  if (!fresh.scripts["content:check"]) {
21806
- fresh.scripts["content:check"] = 'contentbit validate "content/**/*.md" --registry ./blocks/registry.ts';
22362
+ fresh.scripts["content:check"] = "contentbit validate";
21807
22363
  io.stdout("added script: content:check");
21808
22364
  }
21809
22365
  if (!fresh.scripts["content:links"]) {
21810
- fresh.scripts["content:links"] = 'contentbit links "content/**/*.md"';
22366
+ fresh.scripts["content:links"] = "contentbit links";
21811
22367
  io.stdout("added script: content:links");
21812
22368
  }
21813
22369
  if (!fresh.scripts["content:doctor"]) {
21814
- fresh.scripts["content:doctor"] = 'contentbit doctor "content/**/*.md" --registry ./blocks/registry.ts';
22370
+ fresh.scripts["content:doctor"] = "contentbit doctor";
21815
22371
  io.stdout("added script: content:doctor");
21816
22372
  }
21817
22373
  if (!fresh.scripts.studio) {
21818
- fresh.scripts.studio = 'contentbit studio "content/**/*.md" --registry ./blocks/registry.ts';
22374
+ fresh.scripts.studio = "contentbit studio";
21819
22375
  io.stdout("added script: studio");
21820
22376
  }
21821
22377
  if (!pkg.scripts?.["content:check"] || !pkg.scripts?.["content:links"] || !pkg.scripts?.["content:doctor"] || !pkg.scripts?.studio) {
@@ -21857,7 +22413,7 @@ var init_init = __esm({
21857
22413
  REGISTRY_TEMPLATE = `// Custom block definitions for this project. The CLI and your app share
21858
22414
  // this module \u2014 Node 22.18+ imports TypeScript directly:
21859
22415
  //
21860
- // contentbit validate "content/**/*.md" --registry ./blocks/registry.ts
22416
+ // contentbit validate
21861
22417
  //
21862
22418
  // Definitions stay framework-free (the CLI and every render target use
21863
22419
  // them); render components live next door in blocks/components.tsx or
@@ -21904,7 +22460,7 @@ Run the validate script and you will get file:line:col diagnostics.
21904
22460
 
21905
22461
  :::steps
21906
22462
  1. Edit this file and add or break a block.
21907
- 2. Run \`contentbit validate "content/**/*.md"\`.
22463
+ 2. Run \`contentbit validate\`.
21908
22464
  3. Render it with the target you picked at init.
21909
22465
  :::
21910
22466
 
@@ -21932,7 +22488,7 @@ graph is authored once with \`slug\` and \`linksTo\`, then contentbit derives
21932
22488
  \`linkedFrom\` in \`.contentbit/link-index.json\`.
21933
22489
 
21934
22490
  :::callout{type="note"}
21935
- Run \`contentbit links "content/**/*.md" --fix\` after renaming a page. Alias
22491
+ Run \`contentbit links --fix\` after renaming a page. Alias
21936
22492
  references in \`linksTo\` are rewritten to the current slug, while \`aliases\`
21937
22493
  stays as the rename record.
21938
22494
  :::
@@ -21992,8 +22548,8 @@ export default defineSeoConfig({
21992
22548
  });
21993
22549
 
21994
22550
  // src/content-project.ts
21995
- async function resolveContentFiles2(positionals, cmd) {
21996
- return withCliErrors(() => resolveContentFiles(positionals, cmd));
22551
+ async function resolveContentFiles2(positionals, cmd, options = {}) {
22552
+ return withCliErrors(() => resolveContentFiles(positionals, cmd, options));
21997
22553
  }
21998
22554
  async function loadContentProject2(input) {
21999
22555
  return withCliErrors(() => loadContentProject(input));
@@ -22014,25 +22570,262 @@ var init_content_project = __esm({
22014
22570
  }
22015
22571
  });
22016
22572
 
22573
+ // src/commands/adopt.ts
22574
+ var adopt_exports = {};
22575
+ __export(adopt_exports, {
22576
+ adoptCommand: () => adoptCommand
22577
+ });
22578
+ async function adoptCommand(input, io) {
22579
+ const globs = input.globs.length > 0 ? input.globs : DEFAULT_ADOPT_GLOBS;
22580
+ const project = await loadContentProject2({
22581
+ cmd: "adopt",
22582
+ positionals: globs,
22583
+ registry: input.registry,
22584
+ includeGenericBlocks: !input.noGenericBlocks
22585
+ });
22586
+ const frontmatters = project.scan.files.map((file2) => file2.frontmatter);
22587
+ const linkResolve = inferLinkResolution(frontmatters);
22588
+ const scan = scanContentProject(project.sources, project.registry, {
22589
+ linkOptions: { resolve: linkResolve }
22590
+ });
22591
+ const report = createAdoptionReport(globs, project.files.length, scan.findings, scan.files);
22592
+ if (input.json) io.stdout(JSON.stringify(report, null, 2));
22593
+ else io.stdout(formatAdoptionReport(report));
22594
+ return 0;
22595
+ }
22596
+ function createAdoptionReport(globs, files, findings, scannedFiles) {
22597
+ const frontmatters = scannedFiles.map((file2) => file2.frontmatter);
22598
+ const frontmatter = countFrontmatter(frontmatters);
22599
+ const links = inferLinkResolution(frontmatters);
22600
+ const pageTypes = valuesForField(frontmatters, "type");
22601
+ const contracts = inferContracts(scannedFiles, pageTypes);
22602
+ const localeCoverage = coverageByKey(frontmatters);
22603
+ const contentbitConfig = contentbitConfigProposal(globs, links);
22604
+ const seoConfig = contracts.length > 0 ? seoConfigProposal(contracts) : void 0;
22605
+ return {
22606
+ schemaVersion: ADOPTION_SCHEMA_VERSION,
22607
+ dryRun: true,
22608
+ files,
22609
+ frontmatter,
22610
+ inferred: { content: globs, links: { resolve: links }, pageTypes, contracts },
22611
+ localeCoverage,
22612
+ findings,
22613
+ proposals: {
22614
+ contentbitConfig,
22615
+ frontmatter: frontmatterProposals(scannedFiles),
22616
+ ...seoConfig ? { seoConfig } : {}
22617
+ }
22618
+ };
22619
+ }
22620
+ function countFrontmatter(frontmatters) {
22621
+ const fields = [
22622
+ "slug",
22623
+ "key",
22624
+ "locale",
22625
+ "title",
22626
+ "description",
22627
+ "linksTo"
22628
+ ];
22629
+ const out = Object.fromEntries(fields.map((field) => [field, 0]));
22630
+ for (const fm of frontmatters) {
22631
+ for (const field of fields) if (fm[field] !== void 0) out[field]++;
22632
+ }
22633
+ return out;
22634
+ }
22635
+ function inferLinkResolution(frontmatters) {
22636
+ const locales = valuesForField(frontmatters, "locale");
22637
+ const hasKeys = frontmatters.some((fm) => stringValue2(fm.key) !== void 0);
22638
+ if (locales.length > 1 && hasKeys) return "prefer-same-locale-key-fallback-slug";
22639
+ if (locales.length > 1) return "same-locale-slug";
22640
+ return "global-slug";
22641
+ }
22642
+ function coverageByKey(frontmatters) {
22643
+ const coverage = /* @__PURE__ */ new Map();
22644
+ for (const fm of frontmatters) {
22645
+ const key = stringValue2(fm.key);
22646
+ const locale = stringValue2(fm.locale);
22647
+ if (!key || !locale) continue;
22648
+ const locales = coverage.get(key) ?? /* @__PURE__ */ new Set();
22649
+ locales.add(locale);
22650
+ coverage.set(key, locales);
22651
+ }
22652
+ return [...coverage].map(([key, locales]) => ({ key, locales: [...locales].sort() })).sort((a, b) => a.key.localeCompare(b.key));
22653
+ }
22654
+ function valuesForField(frontmatters, field) {
22655
+ return [
22656
+ ...new Set(
22657
+ frontmatters.map((fm) => stringValue2(fm[field])).filter((value) => value !== void 0)
22658
+ )
22659
+ ].sort();
22660
+ }
22661
+ function inferContracts(files, pageTypes) {
22662
+ return pageTypes.map((type) => {
22663
+ const members = files.filter((file2) => stringValue2(file2.frontmatter.type) === type);
22664
+ const requiredFrontmatter = ["type"];
22665
+ if (members.every((file2) => stringValue2(file2.frontmatter.intent)))
22666
+ requiredFrontmatter.push("intent");
22667
+ if (members.every((file2) => primaryKeyword(file2.frontmatter))) {
22668
+ requiredFrontmatter.push("keywords.primary");
22669
+ }
22670
+ const sectionSets = members.map(
22671
+ (file2) => new Set(
22672
+ file2.stats.outline.filter((heading) => heading.level === 2).map((heading) => heading.text)
22673
+ )
22674
+ );
22675
+ const requiredSections = sectionSets.length === 0 ? [] : [...sectionSets[0]].filter((section2) => sectionSets.every((set2) => set2.has(section2))).sort();
22676
+ return { type, files: members.length, requiredFrontmatter, requiredSections };
22677
+ });
22678
+ }
22679
+ function primaryKeyword(frontmatter) {
22680
+ const keywords = frontmatter.keywords;
22681
+ if (!keywords || typeof keywords !== "object" || Array.isArray(keywords)) return void 0;
22682
+ return stringValue2(keywords.primary);
22683
+ }
22684
+ function frontmatterProposals(files) {
22685
+ const proposals = [];
22686
+ for (const file2 of files) {
22687
+ const add = {};
22688
+ if (!stringValue2(file2.frontmatter.slug)) add.slug = slugFromPath(file2.path);
22689
+ if (!stringValue2(file2.frontmatter.title)) {
22690
+ add.title = file2.stats.outline[0]?.text ?? titleFromPath(file2.path);
22691
+ }
22692
+ if (Object.keys(add).length > 0) proposals.push({ path: file2.path, add });
22693
+ }
22694
+ return proposals;
22695
+ }
22696
+ function slugFromPath(path2) {
22697
+ return titleFromPath(path2).toLocaleLowerCase().normalize("NFKD").replace(/[\u0300-\u036f]/g, "").replace(/[^\p{L}\p{N}]+/gu, "-").replace(/^-+|-+$/g, "");
22698
+ }
22699
+ function titleFromPath(path2) {
22700
+ const filename = path2.slice(path2.lastIndexOf("/") + 1).replace(/\.mdx?$/i, "");
22701
+ return filename.replace(/[-_]+/g, " ").replace(/\b\p{L}/gu, (letter) => letter.toUpperCase());
22702
+ }
22703
+ function stringValue2(value) {
22704
+ return typeof value === "string" && value.trim() !== "" ? value.trim() : void 0;
22705
+ }
22706
+ function contentbitConfigProposal(globs, resolve4) {
22707
+ const content = globs.length === 1 ? singleQuoted(globs[0]) : `[${globs.map(singleQuoted).join(", ")}]`;
22708
+ return `import { defineContentConfig } from '@contentbit/core'
22709
+
22710
+ export default defineContentConfig({
22711
+ content: ${content},
22712
+ links: {
22713
+ resolve: '${resolve4}',
22714
+ },
22715
+ })
22716
+ `;
22717
+ }
22718
+ function seoConfigProposal(contracts) {
22719
+ const pageTypes = contracts.map((contract) => {
22720
+ const fields = [`requiredFrontmatter: ${JSON.stringify(contract.requiredFrontmatter)}`];
22721
+ if (contract.requiredSections.length > 0) {
22722
+ const sections = contract.requiredSections.map((heading) => ({
22723
+ id: heading.toLocaleLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, ""),
22724
+ headings: [heading]
22725
+ }));
22726
+ fields.push(`requiredSections: ${JSON.stringify(sections)}`);
22727
+ }
22728
+ return ` ${JSON.stringify(contract.type)}: { ${fields.join(", ")} },`;
22729
+ }).join("\n");
22730
+ return `import { defineSeoConfig } from '@contentbit/core'
22731
+
22732
+ export default defineSeoConfig({
22733
+ // Generated from existing page types. Review each contract before enabling it in CI.
22734
+ pageTypes: {
22735
+ ${pageTypes}
22736
+ },
22737
+ pages: {},
22738
+ })
22739
+ `;
22740
+ }
22741
+ function singleQuoted(value) {
22742
+ return `'${value.replaceAll("'", "\\'")}'`;
22743
+ }
22744
+ function formatAdoptionReport(report) {
22745
+ const lines = [
22746
+ section("contentbit adopt"),
22747
+ "",
22748
+ color("Read-only adoption report \u2014 no files were changed.", "info"),
22749
+ "",
22750
+ section("Inventory"),
22751
+ ...formatRows([
22752
+ { label: "Files", value: report.files },
22753
+ { label: "Slugs", value: report.frontmatter.slug },
22754
+ { label: "Keys", value: report.frontmatter.key },
22755
+ { label: "Locales", value: report.frontmatter.locale },
22756
+ { label: "Links", value: report.frontmatter.linksTo },
22757
+ {
22758
+ label: "Findings",
22759
+ value: report.findings.length,
22760
+ tone: report.findings.length > 0 ? "warning" : "success"
22761
+ }
22762
+ ]),
22763
+ "",
22764
+ section("Inferred Link Strategy"),
22765
+ ` ${report.inferred.links.resolve}`
22766
+ ];
22767
+ if (report.localeCoverage.length > 0) {
22768
+ lines.push("", section("Locale Coverage"));
22769
+ for (const item of report.localeCoverage)
22770
+ lines.push(` ${item.key}: ${item.locales.join(", ")}`);
22771
+ }
22772
+ if (report.proposals.frontmatter.length > 0) {
22773
+ lines.push("", section("Suggested Frontmatter Repairs"));
22774
+ for (const proposal of report.proposals.frontmatter) {
22775
+ const fields = Object.entries(proposal.add).map(([key, value]) => `${key}: ${JSON.stringify(value)}`).join(", ");
22776
+ lines.push(` ${proposal.path}: ${fields}`);
22777
+ }
22778
+ }
22779
+ lines.push(
22780
+ "",
22781
+ section("Suggested contentbit.config.ts"),
22782
+ "```ts",
22783
+ report.proposals.contentbitConfig.trimEnd(),
22784
+ "```"
22785
+ );
22786
+ if (report.proposals.seoConfig) {
22787
+ lines.push(
22788
+ "",
22789
+ section("Suggested contentbit.seo.config.ts"),
22790
+ "```ts",
22791
+ report.proposals.seoConfig.trimEnd(),
22792
+ "```"
22793
+ );
22794
+ }
22795
+ lines.push("", "Copy, adapt, and review these proposals before creating files.");
22796
+ return lines.join("\n");
22797
+ }
22798
+ var DEFAULT_ADOPT_GLOBS, ADOPTION_SCHEMA_VERSION;
22799
+ var init_adopt = __esm({
22800
+ "src/commands/adopt.ts"() {
22801
+ "use strict";
22802
+ init_dist();
22803
+ init_cli_format();
22804
+ init_content_project();
22805
+ DEFAULT_ADOPT_GLOBS = ["content/**/*.{md,mdx}"];
22806
+ ADOPTION_SCHEMA_VERSION = "contentbit.adoption.v1";
22807
+ }
22808
+ });
22809
+
22017
22810
  // src/link-options.ts
22018
22811
  function linkResolverOptions(values) {
22019
22812
  const out = {};
22020
- const resolve = stringValue2(values.linkResolve ?? values["link-resolve"]);
22021
- if (resolve) {
22022
- if (!isResolveMode(resolve)) throw new Error(`invalid --link-resolve ${resolve}`);
22023
- out.resolve = resolve;
22024
- }
22025
- const localeField = stringValue2(values.localeField ?? values["locale-field"]);
22026
- const slugField = stringValue2(values.slugField ?? values["slug-field"]);
22027
- const keyField = stringValue2(values.keyField ?? values["key-field"]);
22028
- const defaultLocale = stringValue2(values.defaultLocale ?? values["default-locale"]);
22813
+ const resolve4 = stringValue3(values.linkResolve ?? values["link-resolve"]);
22814
+ if (resolve4) {
22815
+ if (!isResolveMode(resolve4)) throw new Error(`invalid --link-resolve ${resolve4}`);
22816
+ out.resolve = resolve4;
22817
+ }
22818
+ const localeField = stringValue3(values.localeField ?? values["locale-field"]);
22819
+ const slugField = stringValue3(values.slugField ?? values["slug-field"]);
22820
+ const keyField = stringValue3(values.keyField ?? values["key-field"]);
22821
+ const defaultLocale = stringValue3(values.defaultLocale ?? values["default-locale"]);
22029
22822
  if (localeField) out.localeField = localeField;
22030
22823
  if (slugField) out.slugField = slugField;
22031
22824
  if (keyField) out.keyField = keyField;
22032
22825
  if (defaultLocale) out.defaultLocale = defaultLocale;
22033
22826
  return out;
22034
22827
  }
22035
- function stringValue2(value) {
22828
+ function stringValue3(value) {
22036
22829
  return typeof value === "string" && value.length > 0 ? value : void 0;
22037
22830
  }
22038
22831
  function isResolveMode(value) {
@@ -22044,19 +22837,261 @@ var init_link_options = __esm({
22044
22837
  }
22045
22838
  });
22046
22839
 
22840
+ // src/project-config.ts
22841
+ import { existsSync as existsSync4 } from "node:fs";
22842
+ import { dirname as dirname3, isAbsolute as isAbsolute3, join as join5, resolve as resolve2 } from "node:path";
22843
+ import { pathToFileURL as pathToFileURL2 } from "node:url";
22844
+ async function loadContentbitConfig(startDir = process.cwd(), explicitPath) {
22845
+ const path2 = explicitPath ? isAbsolute3(explicitPath) ? explicitPath : resolve2(startDir, explicitPath) : findConfig(startDir);
22846
+ if (!path2) return void 0;
22847
+ const mod = await import(pathToFileURL2(path2).href);
22848
+ if (!mod.default || typeof mod.default !== "object") {
22849
+ throw new Error(`Contentbit config must default-export a config object: ${path2}`);
22850
+ }
22851
+ const content = normalizeContent(mod.default.content, path2);
22852
+ return {
22853
+ config: { ...mod.default, content },
22854
+ cwd: dirname3(path2),
22855
+ path: path2
22856
+ };
22857
+ }
22858
+ function findConfig(startDir) {
22859
+ let current = resolve2(startDir);
22860
+ while (true) {
22861
+ for (const name of CONFIG_FILES) {
22862
+ const candidate = join5(current, name);
22863
+ if (existsSync4(candidate)) return candidate;
22864
+ }
22865
+ const parent = dirname3(current);
22866
+ if (parent === current) return void 0;
22867
+ current = parent;
22868
+ }
22869
+ }
22870
+ function normalizeContent(value, path2) {
22871
+ const content = typeof value === "string" ? [value] : value;
22872
+ if (!Array.isArray(content) || content.length === 0 || content.some((item) => typeof item !== "string" || item.length === 0)) {
22873
+ throw new Error(
22874
+ `Contentbit config "content" must be a non-empty string or string array: ${path2}`
22875
+ );
22876
+ }
22877
+ return content;
22878
+ }
22879
+ var CONFIG_FILES;
22880
+ var init_project_config = __esm({
22881
+ "src/project-config.ts"() {
22882
+ "use strict";
22883
+ CONFIG_FILES = [
22884
+ "contentbit.config.ts",
22885
+ "contentbit.config.mts",
22886
+ "contentbit.config.mjs",
22887
+ "contentbit.config.js"
22888
+ ];
22889
+ }
22890
+ });
22891
+
22892
+ // src/script-defaults.ts
22893
+ import { existsSync as existsSync5 } from "node:fs";
22894
+ import { readFile as readFile4 } from "node:fs/promises";
22895
+ import { dirname as dirname4, isAbsolute as isAbsolute4, join as join6, resolve as resolve3 } from "node:path";
22896
+ async function discoverContentCommandDefaults(command, explicitGlobs, startDir = process.cwd()) {
22897
+ const loadedConfig = await loadContentbitConfig(startDir);
22898
+ const configDefaults = loadedConfig ? {
22899
+ cwd: loadedConfig.cwd,
22900
+ registry: resolveConfigPath(loadedConfig.cwd, loadedConfig.config.registry),
22901
+ noGenericBlocks: loadedConfig.config.genericBlocks === false ? true : void 0,
22902
+ seoConfig: typeof loadedConfig.config.seo === "string" ? resolveConfigPath(loadedConfig.cwd, loadedConfig.config.seo) : void 0,
22903
+ noSeo: loadedConfig.config.seo === false ? true : void 0,
22904
+ linkResolve: loadedConfig.config.links?.resolve,
22905
+ localeField: loadedConfig.config.links?.localeField,
22906
+ slugField: loadedConfig.config.links?.slugField,
22907
+ keyField: loadedConfig.config.links?.keyField,
22908
+ defaultLocale: loadedConfig.config.links?.defaultLocale,
22909
+ source: loadedConfig.path
22910
+ } : {};
22911
+ if (explicitGlobs.length > 0) return { ...configDefaults, cwd: void 0, globs: explicitGlobs };
22912
+ if (loadedConfig) return { ...configDefaults, globs: loadedConfig.config.content };
22913
+ const found = await findPackageScript(command, startDir);
22914
+ if (!found) return { globs: [] };
22915
+ const parsed = parseContentbitScript(found.script);
22916
+ if (!parsed) return { globs: [] };
22917
+ return {
22918
+ ...flagsFromArgs(parsed.args),
22919
+ cwd: found.cwd,
22920
+ globs: positionalsFromArgs(parsed.args),
22921
+ source: `${found.packageJson}#scripts.${found.scriptName}`
22922
+ };
22923
+ }
22924
+ function resolveConfigPath(cwd, path2) {
22925
+ if (!path2) return void 0;
22926
+ return isAbsolute4(path2) ? path2 : resolve3(cwd, path2);
22927
+ }
22928
+ async function findPackageScript(command, startDir) {
22929
+ let current = resolve3(startDir);
22930
+ while (true) {
22931
+ const packageJson = join6(current, "package.json");
22932
+ if (existsSync5(packageJson)) {
22933
+ const scripts = await packageScripts(packageJson);
22934
+ for (const name of SCRIPT_CANDIDATES[command]) {
22935
+ const script = scripts[name];
22936
+ if (!script) continue;
22937
+ const parsed = parseContentbitScript(script);
22938
+ if (!parsed) continue;
22939
+ if (parsed.command === command || name === "content:check" && parsed.command === "validate") {
22940
+ return { cwd: current, packageJson, scriptName: name, script };
22941
+ }
22942
+ }
22943
+ }
22944
+ const parent = dirname4(current);
22945
+ if (parent === current) return void 0;
22946
+ current = parent;
22947
+ }
22948
+ }
22949
+ async function packageScripts(path2) {
22950
+ try {
22951
+ const pkg = JSON.parse(await readFile4(path2, "utf8"));
22952
+ const out = {};
22953
+ for (const [name, value] of Object.entries(pkg.scripts ?? {})) {
22954
+ if (typeof value === "string") out[name] = value;
22955
+ }
22956
+ return out;
22957
+ } catch {
22958
+ return {};
22959
+ }
22960
+ }
22961
+ function parseContentbitScript(script) {
22962
+ const tokens = splitShellArgs(script);
22963
+ const bin = tokens.findIndex((token) => token === "contentbit" || token.endsWith("/contentbit"));
22964
+ if (bin === -1) return void 0;
22965
+ const command = tokens[bin + 1];
22966
+ if (!command) return void 0;
22967
+ const args = [];
22968
+ for (const token of tokens.slice(bin + 2)) {
22969
+ if (token === "&&" || token === ";") break;
22970
+ args.push(token);
22971
+ }
22972
+ return { command, args };
22973
+ }
22974
+ function positionalsFromArgs(args) {
22975
+ const out = [];
22976
+ for (let i = 0; i < args.length; i++) {
22977
+ const arg = args[i];
22978
+ if (arg === "--") {
22979
+ out.push(...args.slice(i + 1));
22980
+ break;
22981
+ }
22982
+ if (arg.startsWith("-")) {
22983
+ if (flagTakesValue(arg) && !arg.includes("=")) i++;
22984
+ continue;
22985
+ }
22986
+ out.push(arg);
22987
+ }
22988
+ return out;
22989
+ }
22990
+ function flagsFromArgs(args) {
22991
+ const out = {};
22992
+ for (let i = 0; i < args.length; i++) {
22993
+ const raw = args[i];
22994
+ const [flag, inlineValue] = raw.split(/=(.*)/s, 2);
22995
+ const value = inlineValue ?? args[i + 1];
22996
+ if (flag === "--registry" && value) out.registry = value;
22997
+ else if (flag === "--no-generic-blocks") out.noGenericBlocks = true;
22998
+ else if (flag === "--seo-config" && value) out.seoConfig = value;
22999
+ else if (flag === "--no-seo") out.noSeo = true;
23000
+ else if (flag === "--link-resolve" && value) out.linkResolve = value;
23001
+ else if (flag === "--locale-field" && value) out.localeField = value;
23002
+ else if (flag === "--slug-field" && value) out.slugField = value;
23003
+ else if (flag === "--key-field" && value) out.keyField = value;
23004
+ else if (flag === "--default-locale" && value) out.defaultLocale = value;
23005
+ if (flagTakesValue(flag) && inlineValue === void 0) i++;
23006
+ }
23007
+ return out;
23008
+ }
23009
+ function flagTakesValue(flag) {
23010
+ return [
23011
+ "--registry",
23012
+ "--seo-config",
23013
+ "--link-resolve",
23014
+ "--locale-field",
23015
+ "--slug-field",
23016
+ "--key-field",
23017
+ "--default-locale"
23018
+ ].includes(flag);
23019
+ }
23020
+ function splitShellArgs(input) {
23021
+ const args = [];
23022
+ let current = "";
23023
+ let quote = null;
23024
+ let escaped = false;
23025
+ for (const ch of input) {
23026
+ if (escaped) {
23027
+ current += ch;
23028
+ escaped = false;
23029
+ continue;
23030
+ }
23031
+ if (ch === "\\") {
23032
+ escaped = true;
23033
+ continue;
23034
+ }
23035
+ if (quote) {
23036
+ if (ch === quote) quote = null;
23037
+ else current += ch;
23038
+ continue;
23039
+ }
23040
+ if (ch === '"' || ch === "'") {
23041
+ quote = ch;
23042
+ continue;
23043
+ }
23044
+ if (/\s/.test(ch)) {
23045
+ if (current !== "") {
23046
+ args.push(current);
23047
+ current = "";
23048
+ }
23049
+ continue;
23050
+ }
23051
+ current += ch;
23052
+ }
23053
+ if (escaped) current += "\\";
23054
+ if (current !== "") args.push(current);
23055
+ return args;
23056
+ }
23057
+ var SCRIPT_CANDIDATES;
23058
+ var init_script_defaults = __esm({
23059
+ "src/script-defaults.ts"() {
23060
+ "use strict";
23061
+ init_project_config();
23062
+ SCRIPT_CANDIDATES = {
23063
+ validate: ["content:check", "content:validate"],
23064
+ doctor: ["content:doctor", "content:check"],
23065
+ studio: ["studio", "content:studio", "content:check"],
23066
+ links: ["content:links", "content:check"],
23067
+ stats: ["content:stats", "content:check"],
23068
+ brief: ["content:brief", "content:check"]
23069
+ };
23070
+ }
23071
+ });
23072
+
22047
23073
  // src/commands/validate.ts
22048
23074
  var validate_exports = {};
22049
23075
  __export(validate_exports, {
22050
23076
  validateCommand: () => validateCommand
22051
23077
  });
22052
23078
  async function validateCommand(input, io) {
23079
+ const defaults = await discoverContentCommandDefaults("validate", input.globs);
23080
+ const linkOptions = linkResolverOptions({
23081
+ linkResolve: input.linkResolve ?? defaults.linkResolve,
23082
+ localeField: input.localeField ?? defaults.localeField,
23083
+ slugField: input.slugField ?? defaults.slugField,
23084
+ keyField: input.keyField ?? defaults.keyField,
23085
+ defaultLocale: input.defaultLocale ?? defaults.defaultLocale
23086
+ });
22053
23087
  const { files, scan } = await loadContentProject2({
22054
23088
  cmd: "validate",
22055
- positionals: input.globs,
22056
- registry: input.registry,
22057
- includeGenericBlocks: !input.noGenericBlocks,
22058
- linkOptions: linkResolverOptions(input),
22059
- scan: { includeStatsFindings: false }
23089
+ positionals: defaults.globs,
23090
+ cwd: defaults.cwd,
23091
+ registry: input.registry ?? defaults.registry,
23092
+ includeGenericBlocks: !(input.noGenericBlocks || defaults.noGenericBlocks),
23093
+ linkOptions,
23094
+ scan: { includeStatsFindings: false, includeIntegrityFindings: false }
22060
23095
  });
22061
23096
  let errors = 0;
22062
23097
  let warnings = 0;
@@ -22099,19 +23134,20 @@ var init_validate2 = __esm({
22099
23134
  init_cli_format();
22100
23135
  init_content_project();
22101
23136
  init_link_options();
23137
+ init_script_defaults();
22102
23138
  }
22103
23139
  });
22104
23140
 
22105
23141
  // src/seo-config.ts
22106
- import { existsSync as existsSync4 } from "node:fs";
22107
- import { isAbsolute as isAbsolute3, join as join5 } from "node:path";
22108
- import { pathToFileURL as pathToFileURL2 } from "node:url";
23142
+ import { existsSync as existsSync6 } from "node:fs";
23143
+ import { isAbsolute as isAbsolute5, join as join7 } from "node:path";
23144
+ import { pathToFileURL as pathToFileURL3 } from "node:url";
22109
23145
  async function loadSeoConfig(input = {}) {
22110
23146
  if (input.noSeo) return {};
22111
23147
  const cwd = input.cwd ?? process.cwd();
22112
- const path2 = input.seoConfig ? isAbsolute3(input.seoConfig) ? input.seoConfig : join5(cwd, input.seoConfig) : join5(cwd, DEFAULT_SEO_CONFIG);
22113
- if (!input.seoConfig && !existsSync4(path2)) return {};
22114
- const mod = await import(pathToFileURL2(path2).href);
23148
+ const path2 = input.seoConfig ? isAbsolute5(input.seoConfig) ? input.seoConfig : join7(cwd, input.seoConfig) : join7(cwd, DEFAULT_SEO_CONFIG);
23149
+ if (!input.seoConfig && !existsSync6(path2)) return {};
23150
+ const mod = await import(pathToFileURL3(path2).href);
22115
23151
  if (mod.default === void 0) {
22116
23152
  throw new Error(`SEO config must default-export a config object: ${path2}`);
22117
23153
  }
@@ -22130,19 +23166,44 @@ var doctor_exports = {};
22130
23166
  __export(doctor_exports, {
22131
23167
  doctorCommand: () => doctorCommand
22132
23168
  });
23169
+ import { existsSync as existsSync7, watch as watchDirectory } from "node:fs";
23170
+ import { readFile as readFile5, readdir } from "node:fs/promises";
23171
+ import { homedir } from "node:os";
23172
+ import { dirname as dirname5, join as join8, sep as sep2 } from "node:path";
22133
23173
  async function doctorCommand(input, io) {
23174
+ if (input.watch && input.json) {
23175
+ io.stderr("doctor: --watch cannot be combined with --json.");
23176
+ return 2;
23177
+ }
23178
+ const first = await doctorOnce(input, io);
23179
+ if (!input.watch) return first.exitCode;
23180
+ return watchDoctor(input, io, first.files);
23181
+ }
23182
+ async function doctorOnce(input, io) {
23183
+ const defaults = await discoverContentCommandDefaults("doctor", input.globs);
22134
23184
  const minSectionWords = parseMinSectionWords(input.minSectionWords);
22135
23185
  if (minSectionWords === null) {
22136
23186
  io.stderr("doctor: --min-section-words must be a non-negative integer.");
22137
- return 2;
22138
- }
22139
- const includeGenericBlocks = !input.noGenericBlocks;
22140
- const linkOptions = linkResolverOptions(input);
22141
- const seoConfig = await loadSeoConfig({ seoConfig: input.seoConfig, noSeo: input.noSeo });
23187
+ return { exitCode: 2, files: [] };
23188
+ }
23189
+ const includeGenericBlocks = !(input.noGenericBlocks || defaults.noGenericBlocks);
23190
+ const linkOptions = linkResolverOptions({
23191
+ linkResolve: input.linkResolve ?? defaults.linkResolve,
23192
+ localeField: input.localeField ?? defaults.localeField,
23193
+ slugField: input.slugField ?? defaults.slugField,
23194
+ keyField: input.keyField ?? defaults.keyField,
23195
+ defaultLocale: input.defaultLocale ?? defaults.defaultLocale
23196
+ });
23197
+ const seoConfig = await loadSeoConfig({
23198
+ cwd: defaults.cwd,
23199
+ seoConfig: input.seoConfig ?? defaults.seoConfig,
23200
+ noSeo: input.noSeo ?? defaults.noSeo
23201
+ });
22142
23202
  const { files, scan } = await loadContentProject2({
22143
23203
  cmd: "doctor",
22144
- positionals: input.globs,
22145
- registry: input.registry,
23204
+ positionals: defaults.globs,
23205
+ cwd: defaults.cwd,
23206
+ registry: input.registry ?? defaults.registry,
22146
23207
  includeGenericBlocks,
22147
23208
  linkOptions,
22148
23209
  scan: { minSectionWords, seoConfig: seoConfig.config, seoConfigPath: seoConfig.path }
@@ -22158,26 +23219,121 @@ async function doctorCommand(input, io) {
22158
23219
  findings: scan.seo.findings
22159
23220
  }
22160
23221
  } : {},
22161
- findings: scan.findings
23222
+ findings: []
22162
23223
  };
23224
+ report.findings = [...scan.findings, ...await skillDriftFindings(files)];
23225
+ report.summary = summarizeFindings(report.findings);
22163
23226
  if (input.json) io.stdout(JSON.stringify(report, null, 2));
22164
23227
  else
22165
23228
  io.stdout(
22166
23229
  formatReport(
22167
23230
  report,
22168
- input.globs,
22169
- input.registry,
23231
+ defaults.globs,
23232
+ input.registry ?? defaults.registry,
22170
23233
  includeGenericBlocks,
22171
23234
  linkOptions,
22172
23235
  hasAliases(scan.linkInputs)
22173
23236
  )
22174
23237
  );
22175
- if (report.summary.errors > 0) return 1;
22176
- if (report.summary.warnings > 0 && input.strictWarnings) return 1;
23238
+ if (report.summary.errors > 0) return { exitCode: 1, files };
23239
+ if (report.summary.warnings > 0 && input.strictWarnings) return { exitCode: 1, files };
22177
23240
  if (input.strictSeo && report.seo?.findings.some((finding2) => finding2.severity === "warning")) {
22178
- return 1;
23241
+ return { exitCode: 1, files };
22179
23242
  }
22180
- return 0;
23243
+ return { exitCode: 0, files };
23244
+ }
23245
+ async function watchDoctor(input, io, initialFiles) {
23246
+ const directories = [...new Set(initialFiles.map(dirname5))];
23247
+ const watchers = [];
23248
+ const watchedDirectories = /* @__PURE__ */ new Set();
23249
+ const fallbackRoots = [];
23250
+ let pending;
23251
+ let stopped = false;
23252
+ const close = () => {
23253
+ if (stopped) return;
23254
+ stopped = true;
23255
+ if (pending) clearTimeout(pending);
23256
+ for (const watcher of watchers) watcher.close();
23257
+ };
23258
+ const rerun = () => {
23259
+ if (pending || stopped) return;
23260
+ pending = setTimeout(() => {
23261
+ pending = void 0;
23262
+ void doctorOnce(input, io).then(async () => {
23263
+ await Promise.all(fallbackRoots.map((root) => addFallbackWatchers(root)));
23264
+ io.stdout("\nWatching for changes\u2026");
23265
+ }).catch(
23266
+ (error51) => io.stderr(
23267
+ `doctor: watch scan failed: ${error51 instanceof Error ? error51.message : String(error51)}`
23268
+ )
23269
+ );
23270
+ }, 100);
23271
+ };
23272
+ const watchRoots = recursiveWatchRoots(directories);
23273
+ for (const root of watchRoots) {
23274
+ try {
23275
+ watchers.push(createWatcher(root, true, rerun, io));
23276
+ watchedDirectories.add(root);
23277
+ } catch {
23278
+ fallbackRoots.push(root);
23279
+ await addFallbackWatchers(root);
23280
+ break;
23281
+ }
23282
+ }
23283
+ io.stdout("\nWatching for changes\u2026 Press Ctrl+C to stop.");
23284
+ return new Promise((resolve4) => {
23285
+ const stop = () => {
23286
+ close();
23287
+ process.off("SIGINT", stop);
23288
+ process.off("SIGTERM", stop);
23289
+ resolve4(0);
23290
+ };
23291
+ process.once("SIGINT", stop);
23292
+ process.once("SIGTERM", stop);
23293
+ });
23294
+ async function addFallbackWatchers(root) {
23295
+ for (const directory of await nestedDirectories(root)) {
23296
+ if (watchedDirectories.has(directory)) continue;
23297
+ watchers.push(createWatcher(directory, false, rerun, io));
23298
+ watchedDirectories.add(directory);
23299
+ }
23300
+ }
23301
+ }
23302
+ function createWatcher(directory, recursive, rerun, io) {
23303
+ const watcher = watchDirectory(directory, { persistent: true, recursive }, rerun);
23304
+ watcher.on(
23305
+ "error",
23306
+ (error51) => io.stderr(`doctor: watch failed for ${directory}: ${error51.message}`)
23307
+ );
23308
+ return watcher;
23309
+ }
23310
+ function recursiveWatchRoots(directories) {
23311
+ if (directories.length <= 1) return directories;
23312
+ const parts = directories.map((directory) => directory.split(sep2));
23313
+ const first = parts[0];
23314
+ const shared = [];
23315
+ for (let index = 0; index < first.length; index++) {
23316
+ if (parts.some((items) => items[index] !== first[index])) break;
23317
+ shared.push(first[index]);
23318
+ }
23319
+ const root = shared.join(sep2) || sep2;
23320
+ return [root];
23321
+ }
23322
+ async function nestedDirectories(root) {
23323
+ const directories = [root];
23324
+ for (let index = 0; index < directories.length; index++) {
23325
+ let entries;
23326
+ try {
23327
+ entries = await readdir(directories[index], { withFileTypes: true });
23328
+ } catch {
23329
+ continue;
23330
+ }
23331
+ for (const entry of entries) {
23332
+ if (!entry.isDirectory() || entry.isSymbolicLink()) continue;
23333
+ directories.push(join8(directories[index], entry.name));
23334
+ }
23335
+ }
23336
+ return directories;
22181
23337
  }
22182
23338
  function parseMinSectionWords(value) {
22183
23339
  if (value === void 0) return DEFAULT_MIN_SECTION_WORDS;
@@ -22187,6 +23343,66 @@ function parseMinSectionWords(value) {
22187
23343
  function hasAliases(inputs) {
22188
23344
  return inputs.some((input) => Array.isArray(input.data.aliases) && input.data.aliases.length > 0);
22189
23345
  }
23346
+ async function skillDriftFindings(files) {
23347
+ const root = findInstalledSkillRoot(files);
23348
+ if (!root) return [];
23349
+ const findings = [];
23350
+ for (const skill of SHIPPED_SKILLS) {
23351
+ const shipped = skillVersion2(skill.content);
23352
+ if (!shipped.value) continue;
23353
+ const path2 = join8(root, ".claude/skills", skill.name, "SKILL.md");
23354
+ if (!existsSync7(path2)) continue;
23355
+ const installedContent = await readFile5(path2, "utf8");
23356
+ const installed = skillVersion2(installedContent);
23357
+ if (installed.value === shipped.value) continue;
23358
+ findings.push({
23359
+ severity: "warning",
23360
+ source: "agents",
23361
+ code: "CB_SKILL_DRIFT",
23362
+ file: path2,
23363
+ line: installed.line ?? 1,
23364
+ column: 1,
23365
+ message: `${skill.name} skill is stale (installed version ${installed.value ?? "unknown"}, package ships ${shipped.value}).`,
23366
+ hint: "Re-run contentbit agents from this project to refresh Claude Code skills."
23367
+ });
23368
+ }
23369
+ return findings;
23370
+ }
23371
+ function findInstalledSkillRoot(files) {
23372
+ const home = homedir();
23373
+ for (const file2 of files) {
23374
+ let current = dirname5(file2);
23375
+ while (true) {
23376
+ if (current === home) break;
23377
+ if (hasInstalledContentbitSkill(current)) return current;
23378
+ if (existsSync7(join8(current, "package.json"))) break;
23379
+ const parent = dirname5(current);
23380
+ if (parent === current) break;
23381
+ current = parent;
23382
+ }
23383
+ }
23384
+ return void 0;
23385
+ }
23386
+ function hasInstalledContentbitSkill(root) {
23387
+ return SHIPPED_SKILLS.some(
23388
+ (skill) => existsSync7(join8(root, ".claude/skills", skill.name, "SKILL.md"))
23389
+ );
23390
+ }
23391
+ function skillVersion2(content) {
23392
+ const lines = content.split(/\r?\n/);
23393
+ for (let i = 0; i < lines.length; i++) {
23394
+ const match = lines[i].match(/^version:\s*['"]?([^'"\s]+)['"]?\s*$/);
23395
+ if (match) return { value: match[1], line: i + 1 };
23396
+ }
23397
+ return {};
23398
+ }
23399
+ function summarizeFindings(findings) {
23400
+ return {
23401
+ errors: findings.filter((finding2) => finding2.severity === "error").length,
23402
+ warnings: findings.filter((finding2) => finding2.severity === "warning").length,
23403
+ suggestions: findings.filter((finding2) => finding2.severity === "info").length
23404
+ };
23405
+ }
22190
23406
  function formatReport(report, globs, registryPath, includeGenericBlocks, linkOptions, aliasFixMayApply) {
22191
23407
  const lines = [];
22192
23408
  lines.push(section("contentbit doctor"));
@@ -22278,7 +23494,7 @@ function formatGlobs(globs) {
22278
23494
  return globs.map(formatArg).join(" ");
22279
23495
  }
22280
23496
  function formatArg(value) {
22281
- return /\s/.test(value) ? JSON.stringify(value) : value;
23497
+ return /\s/.test(value) || value.includes("*") || value.includes("?") || value.includes("[") ? JSON.stringify(value) : value;
22282
23498
  }
22283
23499
  function formatRegistryArgs(registryPath, includeGenericBlocks) {
22284
23500
  const args = [];
@@ -22295,6 +23511,7 @@ function formatLinkArgs(options) {
22295
23511
  if (options.defaultLocale) args.push("--default-locale", formatArg(options.defaultLocale));
22296
23512
  return args.length > 0 ? ` ${args.join(" ")}` : "";
22297
23513
  }
23514
+ var SHIPPED_SKILLS;
22298
23515
  var init_doctor = __esm({
22299
23516
  "src/commands/doctor.ts"() {
22300
23517
  "use strict";
@@ -22303,6 +23520,13 @@ var init_doctor = __esm({
22303
23520
  init_content_project();
22304
23521
  init_link_options();
22305
23522
  init_seo_config();
23523
+ init_script_defaults();
23524
+ init_SKILL();
23525
+ init_SKILL2();
23526
+ SHIPPED_SKILLS = [
23527
+ { name: "contentbit-author", content: SKILL_default2 },
23528
+ { name: "contentbit-audit", content: SKILL_default }
23529
+ ];
22306
23530
  }
22307
23531
  });
22308
23532
 
@@ -22313,24 +23537,35 @@ __export(brief_exports, {
22313
23537
  });
22314
23538
  import { glob as glob2 } from "tinyglobby";
22315
23539
  async function briefCommand(input, io) {
22316
- const seoConfig = await loadSeoConfig({ seoConfig: input.seoConfig });
23540
+ const defaults = await discoverContentCommandDefaults("brief", input.globs);
23541
+ const seoConfig = await loadSeoConfig({
23542
+ cwd: defaults.cwd,
23543
+ seoConfig: input.seoConfig ?? defaults.seoConfig,
23544
+ noSeo: defaults.noSeo
23545
+ });
22317
23546
  if (!seoConfig.config) {
22318
23547
  io.stderr(
22319
23548
  "brief: no SEO config found. Add contentbit.seo.config.ts or pass --seo-config <path>."
22320
23549
  );
22321
23550
  return 2;
22322
23551
  }
22323
- const includeGenericBlocks = !input.noGenericBlocks;
22324
- const explicitGlobs = input.globs.length > 0;
22325
- const globs = explicitGlobs ? input.globs : await defaultBriefGlobs();
23552
+ const includeGenericBlocks = !(input.noGenericBlocks || defaults.noGenericBlocks);
23553
+ const globs = defaults.globs.length > 0 ? defaults.globs : await defaultBriefGlobs(defaults.cwd);
22326
23554
  const { scan } = await loadContentProject2({
22327
23555
  cmd: "brief",
22328
23556
  positionals: globs,
22329
- registry: input.registry,
23557
+ cwd: defaults.cwd,
23558
+ registry: input.registry ?? defaults.registry,
22330
23559
  includeGenericBlocks,
22331
- linkOptions: linkResolverOptions(input),
23560
+ linkOptions: linkResolverOptions({
23561
+ linkResolve: input.linkResolve ?? defaults.linkResolve,
23562
+ localeField: input.localeField ?? defaults.localeField,
23563
+ slugField: input.slugField ?? defaults.slugField,
23564
+ keyField: input.keyField ?? defaults.keyField,
23565
+ defaultLocale: input.defaultLocale ?? defaults.defaultLocale
23566
+ }),
22332
23567
  scan: { seoConfig: seoConfig.config, seoConfigPath: seoConfig.path },
22333
- allowEmpty: !explicitGlobs && globs.length === 0
23568
+ allowEmpty: globs.length === 0
22334
23569
  });
22335
23570
  if (!scan.seo) {
22336
23571
  io.stderr("brief: SEO scan did not produce a result.");
@@ -22352,8 +23587,8 @@ async function briefCommand(input, io) {
22352
23587
  else io.stdout(formatSeoBriefMarkdown(brief));
22353
23588
  return 0;
22354
23589
  }
22355
- async function defaultBriefGlobs() {
22356
- const matches = await glob2(DEFAULT_BRIEF_GLOBS);
23590
+ async function defaultBriefGlobs(cwd) {
23591
+ const matches = await glob2(DEFAULT_BRIEF_GLOBS, { cwd });
22357
23592
  return matches.length > 0 ? DEFAULT_BRIEF_GLOBS : [];
22358
23593
  }
22359
23594
  var DEFAULT_BRIEF_GLOBS;
@@ -22364,6 +23599,7 @@ var init_brief = __esm({
22364
23599
  init_content_project();
22365
23600
  init_link_options();
22366
23601
  init_seo_config();
23602
+ init_script_defaults();
22367
23603
  DEFAULT_BRIEF_GLOBS = ["content/**/*.{md,mdx}"];
22368
23604
  }
22369
23605
  });
@@ -22374,6 +23610,7 @@ __export(studio_exports, {
22374
23610
  studioCommand: () => studioCommand
22375
23611
  });
22376
23612
  async function studioCommand(input, io) {
23613
+ const defaults = await discoverContentCommandDefaults("studio", input.globs);
22377
23614
  const port = parsePort(input.port);
22378
23615
  if (port === null) {
22379
23616
  io.stderr("studio: --port must be an integer between 0 and 65535.");
@@ -22384,17 +23621,39 @@ async function studioCommand(input, io) {
22384
23621
  io.stderr("studio: --min-section-words must be a non-negative integer.");
22385
23622
  return 2;
22386
23623
  }
22387
- await resolveContentFiles2(input.globs, "studio");
22388
- const seoConfig = await loadSeoConfig({ seoConfig: input.seoConfig, noSeo: input.noSeo });
22389
- const { startStudio } = await import("@contentbit/studio");
23624
+ await resolveContentFiles2(defaults.globs, "studio", { cwd: defaults.cwd });
23625
+ const seoConfig = await loadSeoConfig({
23626
+ cwd: defaults.cwd,
23627
+ seoConfig: input.seoConfig ?? defaults.seoConfig,
23628
+ noSeo: input.noSeo ?? defaults.noSeo
23629
+ });
23630
+ let startStudio;
23631
+ try {
23632
+ ;
23633
+ ({ startStudio } = await import("@contentbit/studio"));
23634
+ } catch (error51) {
23635
+ if (isMissingStudio(error51)) {
23636
+ throw new Error(
23637
+ "Studio is installed separately to keep the base CLI lightweight. Install it with your package manager, for example: pnpm add -D @contentbit/studio"
23638
+ );
23639
+ }
23640
+ throw error51;
23641
+ }
22390
23642
  const studioOptions = {
22391
- globs: input.globs,
22392
- registryPath: input.registry,
22393
- includeGenericBlocks: !input.noGenericBlocks,
23643
+ globs: defaults.globs,
23644
+ cwd: defaults.cwd,
23645
+ registryPath: input.registry ?? defaults.registry,
23646
+ includeGenericBlocks: !(input.noGenericBlocks || defaults.noGenericBlocks),
22394
23647
  host: input.host,
22395
23648
  ...port !== void 0 ? { port } : {},
22396
23649
  open: !input.noOpen,
22397
- linkOptions: linkResolverOptions(input),
23650
+ linkOptions: linkResolverOptions({
23651
+ linkResolve: input.linkResolve ?? defaults.linkResolve,
23652
+ localeField: input.localeField ?? defaults.localeField,
23653
+ slugField: input.slugField ?? defaults.slugField,
23654
+ keyField: input.keyField ?? defaults.keyField,
23655
+ defaultLocale: input.defaultLocale ?? defaults.defaultLocale
23656
+ }),
22398
23657
  minSectionWords,
22399
23658
  seoConfig: seoConfig.config,
22400
23659
  seoConfigPath: seoConfig.path
@@ -22419,6 +23678,9 @@ async function studioCommand(input, io) {
22419
23678
  process.off("SIGTERM", close);
22420
23679
  return 0;
22421
23680
  }
23681
+ function isMissingStudio(error51) {
23682
+ return error51 instanceof Error && "code" in error51 && error51.code === "ERR_MODULE_NOT_FOUND" && error51.message.includes("@contentbit/studio");
23683
+ }
22422
23684
  function parsePort(value) {
22423
23685
  if (value === void 0) return void 0;
22424
23686
  if (!/^\d+$/.test(value)) return null;
@@ -22437,6 +23699,7 @@ var init_studio = __esm({
22437
23699
  init_content_project();
22438
23700
  init_link_options();
22439
23701
  init_seo_config();
23702
+ init_script_defaults();
22440
23703
  }
22441
23704
  });
22442
23705
 
@@ -22445,9 +23708,17 @@ var stats_exports = {};
22445
23708
  __export(stats_exports, {
22446
23709
  statsCommand: () => statsCommand
22447
23710
  });
22448
- import { readFile as readFile4 } from "node:fs/promises";
23711
+ import { readFile as readFile6 } from "node:fs/promises";
22449
23712
  async function statsCommand(input, io) {
22450
- const all = input.noValidate ? await statsOnly(input.globs) : await statsWithValidation(input, input.globs);
23713
+ const defaults = await discoverContentCommandDefaults("stats", input.globs);
23714
+ const all = input.noValidate ? await statsOnly(defaults.globs, defaults.cwd) : await statsWithValidation(
23715
+ {
23716
+ registry: input.registry ?? defaults.registry,
23717
+ noGenericBlocks: input.noGenericBlocks || defaults.noGenericBlocks,
23718
+ cwd: defaults.cwd
23719
+ },
23720
+ defaults.globs
23721
+ );
22451
23722
  io.stdout(JSON.stringify(all.length === 1 ? all[0] : all, null, 2));
22452
23723
  return 0;
22453
23724
  }
@@ -22455,6 +23726,7 @@ async function statsWithValidation(input, positionals) {
22455
23726
  const { scan } = await loadContentProject2({
22456
23727
  cmd: "stats",
22457
23728
  positionals,
23729
+ cwd: input.cwd,
22458
23730
  registry: input.registry,
22459
23731
  includeGenericBlocks: !input.noGenericBlocks,
22460
23732
  linkOptions: {}
@@ -22469,10 +23741,10 @@ async function statsWithValidation(input, positionals) {
22469
23741
  return { ...file2.stats, validation: { errors, warnings } };
22470
23742
  });
22471
23743
  }
22472
- async function statsOnly(positionals) {
22473
- const files = await resolveContentFiles2(positionals, "stats");
23744
+ async function statsOnly(positionals, cwd) {
23745
+ const files = await resolveContentFiles2(positionals, "stats", { cwd });
22474
23746
  return Promise.all(
22475
- files.map(async (file2) => analyzeDocument(await readFile4(file2, "utf8"), { path: file2 }))
23747
+ files.map(async (file2) => analyzeDocument(await readFile6(file2, "utf8"), { path: file2 }))
22476
23748
  );
22477
23749
  }
22478
23750
  var init_stats = __esm({
@@ -22480,6 +23752,7 @@ var init_stats = __esm({
22480
23752
  "use strict";
22481
23753
  init_dist();
22482
23754
  init_content_project();
23755
+ init_script_defaults();
22483
23756
  }
22484
23757
  });
22485
23758
 
@@ -22488,7 +23761,7 @@ var render_exports = {};
22488
23761
  __export(render_exports, {
22489
23762
  renderCommand: () => renderCommand
22490
23763
  });
22491
- import { readFile as readFile5 } from "node:fs/promises";
23764
+ import { readFile as readFile7 } from "node:fs/promises";
22492
23765
  async function renderCommand(input, io) {
22493
23766
  if (!input.file || (input.target ?? "markdown") !== "markdown") {
22494
23767
  io.stderr(
@@ -22496,10 +23769,14 @@ async function renderCommand(input, io) {
22496
23769
  );
22497
23770
  return 2;
22498
23771
  }
22499
- const includeGenericBlocks = !input.noGenericBlocks;
22500
- const registry2 = await loadRegistry(input.registry, { includeGenericBlocks });
22501
- const source = await readFile5(input.file, "utf8");
22502
- const result = validateDocument(parseDocument(stripFrontmatter(source)), registry2);
23772
+ const loadedConfig = await loadContentbitConfig();
23773
+ const includeGenericBlocks = !(input.noGenericBlocks || loadedConfig?.config.genericBlocks === false);
23774
+ const registry2 = await loadRegistry(input.registry ?? loadedConfig?.config.registry, {
23775
+ cwd: loadedConfig?.cwd,
23776
+ includeGenericBlocks
23777
+ });
23778
+ const source = await readFile7(input.file, "utf8");
23779
+ const result = compileDocument(source, registry2);
22503
23780
  if (!result.ok) {
22504
23781
  for (const d of result.diagnostics) io.stderr(formatDiagnosticForCli(d, input.file));
22505
23782
  return 1;
@@ -22519,6 +23796,7 @@ var init_render = __esm({
22519
23796
  init_dist();
22520
23797
  init_cli_format();
22521
23798
  init_load_registry();
23799
+ init_project_config();
22522
23800
  genericMarkdownFallbackRenderers = Object.fromEntries(
22523
23801
  Object.keys(genericMarkdownRenderers).map((name) => [
22524
23802
  name,
@@ -22535,8 +23813,10 @@ __export(instructions_exports, {
22535
23813
  instructionsCommand: () => instructionsCommand
22536
23814
  });
22537
23815
  async function instructionsCommand(input, io) {
22538
- const registry2 = await loadRegistry(input.registry, {
22539
- includeGenericBlocks: !input.noGenericBlocks
23816
+ const loadedConfig = await loadContentbitConfig();
23817
+ const registry2 = await loadRegistry(input.registry ?? loadedConfig?.config.registry, {
23818
+ cwd: loadedConfig?.cwd,
23819
+ includeGenericBlocks: !(input.noGenericBlocks || loadedConfig?.config.genericBlocks === false)
22540
23820
  });
22541
23821
  const guide = registry2.toAuthoringGuide({
22542
23822
  audience: input.audience === "human" ? "human" : "llm",
@@ -22550,6 +23830,7 @@ var init_instructions = __esm({
22550
23830
  "src/commands/instructions.ts"() {
22551
23831
  "use strict";
22552
23832
  init_load_registry();
23833
+ init_project_config();
22553
23834
  }
22554
23835
  });
22555
23836
 
@@ -22559,8 +23840,10 @@ __export(docs_exports, {
22559
23840
  docsCommand: () => docsCommand
22560
23841
  });
22561
23842
  async function docsCommand(input, io) {
22562
- const registry2 = await loadRegistry(input.registry, {
22563
- includeGenericBlocks: !input.noGenericBlocks
23843
+ const loadedConfig = await loadContentbitConfig();
23844
+ const registry2 = await loadRegistry(input.registry ?? loadedConfig?.config.registry, {
23845
+ cwd: loadedConfig?.cwd,
23846
+ includeGenericBlocks: !(input.noGenericBlocks || loadedConfig?.config.genericBlocks === false)
22564
23847
  });
22565
23848
  const guide = registry2.toAuthoringGuide({ audience: "human", includeExamples: true });
22566
23849
  if (input.out) await io.writeFile(input.out, guide);
@@ -22571,15 +23854,16 @@ var init_docs = __esm({
22571
23854
  "src/commands/docs.ts"() {
22572
23855
  "use strict";
22573
23856
  init_load_registry();
23857
+ init_project_config();
22574
23858
  }
22575
23859
  });
22576
23860
 
22577
23861
  // src/links-io.ts
22578
- import { readFile as readFile6 } from "node:fs/promises";
23862
+ import { readFile as readFile8 } from "node:fs/promises";
22579
23863
  async function collectLinkInputs(files) {
22580
23864
  const inputs = [];
22581
23865
  for (const path2 of files) {
22582
- const source = await readFile6(path2, "utf8");
23866
+ const source = await readFile8(path2, "utf8");
22583
23867
  const fm = extractFrontmatter(source);
22584
23868
  inputs.push({ path: path2, data: fm?.data ?? {} });
22585
23869
  }
@@ -22597,12 +23881,19 @@ var links_exports = {};
22597
23881
  __export(links_exports, {
22598
23882
  linksCommand: () => linksCommand
22599
23883
  });
22600
- import { mkdir as mkdir3, readFile as readFile7 } from "node:fs/promises";
22601
- import { dirname, join as join6 } from "node:path";
23884
+ import { mkdir as mkdir3, readFile as readFile9 } from "node:fs/promises";
23885
+ import { dirname as dirname6, join as join9 } from "node:path";
22602
23886
  async function linksCommand(input, io) {
22603
- const files = await resolveContentFiles2(input.globs, "links");
23887
+ const defaults = await discoverContentCommandDefaults("links", input.globs);
23888
+ const files = await resolveContentFiles2(defaults.globs, "links", { cwd: defaults.cwd });
22604
23889
  const inputs = await collectLinkInputs(files);
22605
- const linkOptions = linkResolverOptions(input);
23890
+ const linkOptions = linkResolverOptions({
23891
+ linkResolve: input.linkResolve ?? defaults.linkResolve,
23892
+ localeField: input.localeField ?? defaults.localeField,
23893
+ slugField: input.slugField ?? defaults.slugField,
23894
+ keyField: input.keyField ?? defaults.keyField,
23895
+ defaultLocale: input.defaultLocale ?? defaults.defaultLocale
23896
+ });
22606
23897
  let errors = 0;
22607
23898
  let warnings = 0;
22608
23899
  for (const { file: file2, diagnostic } of validateLinks(inputs, linkOptions)) {
@@ -22615,7 +23906,7 @@ async function linksCommand(input, io) {
22615
23906
  io.stderr("links: --fix skipped because link errors must be resolved first.");
22616
23907
  } else if (input.fix && index.aliases.size > 0) {
22617
23908
  for (const file2 of files) {
22618
- const source = await readFile7(file2, "utf8");
23909
+ const source = await readFile9(file2, "utf8");
22619
23910
  const fm = extractFrontmatter(source);
22620
23911
  if (!fm) continue;
22621
23912
  const lines = source.split("\n");
@@ -22642,8 +23933,8 @@ async function linksCommand(input, io) {
22642
23933
  }
22643
23934
  }
22644
23935
  }
22645
- const outPath = input.out ?? join6(process.cwd(), ".contentbit", "link-index.json");
22646
- await mkdir3(dirname(outPath), { recursive: true });
23936
+ const outPath = input.out ?? join9(defaults.cwd ?? process.cwd(), ".contentbit", "link-index.json");
23937
+ await mkdir3(dirname6(outPath), { recursive: true });
22647
23938
  await io.writeFile(outPath, JSON.stringify(serializeLinkIndex(index), null, 2) + "\n");
22648
23939
  const graph = linkGraphSummary(index);
22649
23940
  io.stdout(
@@ -22674,6 +23965,7 @@ var init_links2 = __esm({
22674
23965
  init_content_project();
22675
23966
  init_link_options();
22676
23967
  init_links_io();
23968
+ init_script_defaults();
22677
23969
  }
22678
23970
  });
22679
23971
 
@@ -22704,7 +23996,7 @@ async function run(argv, io) {
22704
23996
  ` ${color("error", "error")} ${stripCommanderError(err.message)}`
22705
23997
  ].join("\n")
22706
23998
  );
22707
- return err.code === "commander.unknownCommand" ? 2 : 1;
23999
+ return err.code === "commander.unknownCommand" || err.code === "commander.invalidArgument" ? 2 : 1;
22708
24000
  }
22709
24001
  io.stderr(
22710
24002
  [
@@ -22725,7 +24017,18 @@ function createProgram(io, setExitCode) {
22725
24017
  outputError: () => {
22726
24018
  }
22727
24019
  });
22728
- program2.command("init").description("scaffold Content Blocks into a project").option("-t, --target <target>").option("--md <library>").option("-y, --yes").option("--cwd <path>").option("--no-install").option("--no-page").option("--no-styled").option("--no-agents").option("--seo").action(async (rawOptions) => {
24020
+ program2.command("init").description("scaffold Content Blocks into a project").addOption(
24021
+ new Option("-t, --target <target>", "Render adapter to scaffold").choices([
24022
+ "react",
24023
+ "markdown",
24024
+ "astro"
24025
+ ])
24026
+ ).addOption(
24027
+ new Option("--md <library>", "Markdown prose adapter to wire").choices([
24028
+ "react-markdown",
24029
+ "none"
24030
+ ])
24031
+ ).option("-y, --yes", "Accept detected defaults without prompting").option("--cwd <path>", "Project directory to initialize").option("--no-install", "Scaffold files without installing packages").option("--no-page", "Skip the example route or page").option("--no-styled", "Skip installing the editable styled block pack").option("--no-agents", "Skip AGENTS.md and Claude Code guidance").option("--seo", "Scaffold SEO contracts and connect them in project config").action(async (rawOptions) => {
22729
24032
  const options = optionsFrom(rawOptions);
22730
24033
  const { initCommand: initCommand2 } = await Promise.resolve().then(() => (init_init(), init_exports));
22731
24034
  setExitCode(
@@ -22745,7 +24048,23 @@ function createProgram(io, setExitCode) {
22745
24048
  )
22746
24049
  );
22747
24050
  });
22748
- const validate = program2.command("validate").description("check Markdown blocks and internal links").argument("[globs...]").option("--registry <module>").option("--no-generic-blocks").option("--strict-warnings");
24051
+ program2.command("adopt").description("inspect an existing Markdown library without changing it").argument("[globs...]", "Content files or quoted globs; defaults to content/**/*.{md,mdx}").option("--registry <module>", "Load custom block definitions from this module").option("--no-generic-blocks", "Do not include the built-in generic block pack").option("--dry-run", "Explicitly confirm the read-only adoption report").option("--json", "Print stable machine-readable JSON").action(async (globs, rawOptions) => {
24052
+ const options = optionsFrom(rawOptions);
24053
+ const { adoptCommand: adoptCommand2 } = await Promise.resolve().then(() => (init_adopt(), adopt_exports));
24054
+ setExitCode(
24055
+ await adoptCommand2(
24056
+ {
24057
+ globs,
24058
+ registry: options.registry,
24059
+ noGenericBlocks: options.genericBlocks === false,
24060
+ dryRun: Boolean(options.dryRun),
24061
+ json: Boolean(options.json)
24062
+ },
24063
+ io
24064
+ )
24065
+ );
24066
+ });
24067
+ const validate = program2.command("validate").description("check Markdown blocks and internal links").argument("[globs...]", "Content files or quoted globs; defaults to project config").option("--registry <module>", "Load custom block definitions from this module").option("--no-generic-blocks", "Do not include the built-in generic block pack").option("--strict-warnings", "Exit 1 when validation warnings are present");
22749
24068
  addLinkOptions(validate);
22750
24069
  validate.action(async (globs, rawOptions) => {
22751
24070
  const options = optionsFrom(rawOptions);
@@ -22763,7 +24082,7 @@ function createProgram(io, setExitCode) {
22763
24082
  )
22764
24083
  );
22765
24084
  });
22766
- const doctor = program2.command("doctor").description("inspect content health and repair suggestions").argument("[globs...]").option("--registry <module>").option("--no-generic-blocks").option("--strict-warnings").option("--strict-seo").option("--json").option("--min-section-words <n>").option("--seo-config <module>").option("--no-seo");
24085
+ const doctor = program2.command("doctor").description("inspect content health and repair suggestions").argument("[globs...]", "Content files or quoted globs; defaults to project config").option("--registry <module>", "Load custom block definitions from this module").option("--no-generic-blocks", "Do not include the built-in generic block pack").option("--strict-warnings", "Exit 1 when validation warnings are present").option("--strict-seo", "Treat required SEO findings as errors").option("--watch", "Re-run when a scanned content directory changes").option("--json", "Print stable machine-readable JSON").option("--min-section-words <n>", "Set the thin-section suggestion threshold").option("--seo-config <module>", "Load SEO contracts from this module").option("--no-seo", "Disable SEO config discovery and findings");
22767
24086
  addLinkOptions(doctor);
22768
24087
  doctor.action(async (globs, rawOptions) => {
22769
24088
  const options = optionsFrom(rawOptions);
@@ -22776,17 +24095,18 @@ function createProgram(io, setExitCode) {
22776
24095
  noGenericBlocks: options.genericBlocks === false,
22777
24096
  strictWarnings: Boolean(options.strictWarnings),
22778
24097
  strictSeo: Boolean(options.strictSeo),
24098
+ watch: Boolean(options.watch),
22779
24099
  json: Boolean(options.json),
22780
24100
  minSectionWords: options.minSectionWords,
22781
24101
  seoConfig: options.seoConfig,
22782
- noSeo: options.seo === false,
24102
+ noSeo: options.seo === false ? true : void 0,
22783
24103
  ...linkOptionsFrom(options)
22784
24104
  },
22785
24105
  io
22786
24106
  )
22787
24107
  );
22788
24108
  });
22789
- const brief = program2.command("brief").description("print an agent-ready SEO brief").argument("<key-or-slug>").argument("[globs...]").option("--registry <module>").option("--no-generic-blocks").option("--seo-config <module>").option("--json");
24109
+ const brief = program2.command("brief").description("print an agent-ready SEO brief").argument("<key-or-slug>", "Configured page key or existing content slug").argument("[globs...]", "Content files or quoted globs; defaults to project config").option("--registry <module>", "Load custom block definitions from this module").option("--no-generic-blocks", "Do not include the built-in generic block pack").option("--seo-config <module>", "Load SEO contracts from this module").option("--json", "Print stable machine-readable JSON");
22790
24110
  addLinkOptions(brief);
22791
24111
  brief.action(async (target, globs, rawOptions) => {
22792
24112
  const options = optionsFrom(rawOptions);
@@ -22806,7 +24126,7 @@ function createProgram(io, setExitCode) {
22806
24126
  )
22807
24127
  );
22808
24128
  });
22809
- const studio = program2.command("studio").description("browse content locally").argument("[globs...]").option("--registry <module>").option("--port <n>").option("--host <host>").option("--no-open").option("--no-generic-blocks").option("--min-section-words <n>").option("--seo-config <module>").option("--no-seo");
24129
+ const studio = program2.command("studio").description("browse content locally").argument("[globs...]", "Content files or quoted globs; defaults to project config").option("--registry <module>", "Load custom block definitions from this module").option("--port <n>", "First local port to try; defaults to 4377").option("--host <host>", "Host interface to bind; defaults to 127.0.0.1").option("--no-open", "Do not open Studio in the default browser").option("--no-generic-blocks", "Do not include generic blocks or previews").option("--min-section-words <n>", "Set the thin-section suggestion threshold").option("--seo-config <module>", "Load SEO contracts from this module").option("--no-seo", "Disable SEO config discovery and findings");
22810
24130
  addLinkOptions(studio);
22811
24131
  studio.action(async (globs, rawOptions) => {
22812
24132
  const options = optionsFrom(rawOptions);
@@ -22822,14 +24142,14 @@ function createProgram(io, setExitCode) {
22822
24142
  noGenericBlocks: options.genericBlocks === false,
22823
24143
  minSectionWords: options.minSectionWords,
22824
24144
  seoConfig: options.seoConfig,
22825
- noSeo: options.seo === false,
24145
+ noSeo: options.seo === false ? true : void 0,
22826
24146
  ...linkOptionsFrom(options)
22827
24147
  },
22828
24148
  io
22829
24149
  )
22830
24150
  );
22831
24151
  });
22832
- program2.command("stats").description("print document stats as JSON").argument("[globs...]").option("--registry <module>").option("--no-generic-blocks").option("--no-validate").action(async (globs, rawOptions) => {
24152
+ program2.command("stats").description("print document stats as JSON").argument("[globs...]", "Content files or quoted globs; defaults to project config").option("--registry <module>", "Load custom block definitions from this module").option("--no-generic-blocks", "Do not include the built-in generic block pack").option("--no-validate", "Analyze Markdown without loading or validating blocks").action(async (globs, rawOptions) => {
22833
24153
  const options = optionsFrom(rawOptions);
22834
24154
  const { statsCommand: statsCommand2 } = await Promise.resolve().then(() => (init_stats(), stats_exports));
22835
24155
  setExitCode(
@@ -22844,7 +24164,9 @@ function createProgram(io, setExitCode) {
22844
24164
  )
22845
24165
  );
22846
24166
  });
22847
- program2.command("render").description("render one file to plain Markdown").argument("[file]").option("--target <target>", void 0, "markdown").option("--registry <module>").option("--no-generic-blocks").option("--out <file>").action(async (file2, rawOptions) => {
24167
+ program2.command("render").description("render one file to plain Markdown").argument("[file]", "One source Markdown file").addOption(
24168
+ new Option("--target <target>", "Output adapter").choices(["markdown"]).default("markdown")
24169
+ ).option("--registry <module>", "Load custom block definitions from this module").option("--no-generic-blocks", "Do not include the built-in generic block pack").option("--out <file>", "Write output to a file instead of stdout").action(async (file2, rawOptions) => {
22848
24170
  const options = optionsFrom(rawOptions);
22849
24171
  const { renderCommand: renderCommand2 } = await Promise.resolve().then(() => (init_render(), render_exports));
22850
24172
  setExitCode(
@@ -22860,7 +24182,9 @@ function createProgram(io, setExitCode) {
22860
24182
  )
22861
24183
  );
22862
24184
  });
22863
- program2.command("instructions").description("print LLM authoring instructions").option("--audience <audience>", void 0, "llm").option("--no-examples").option("--registry <module>").option("--no-generic-blocks").option("--out <file>").action(async (rawOptions) => {
24185
+ program2.command("instructions").description("print LLM authoring instructions").addOption(
24186
+ new Option("--audience <audience>", "Guide style").choices(["llm", "human"]).default("llm")
24187
+ ).option("--no-examples", "Omit block syntax examples").option("--registry <module>", "Load custom block definitions from this module").option("--no-generic-blocks", "Do not include the built-in generic block pack").option("--out <file>", "Write the guide to a file instead of stdout").action(async (rawOptions) => {
22864
24188
  const options = optionsFrom(rawOptions);
22865
24189
  const { instructionsCommand: instructionsCommand2 } = await Promise.resolve().then(() => (init_instructions(), instructions_exports));
22866
24190
  setExitCode(
@@ -22876,7 +24200,7 @@ function createProgram(io, setExitCode) {
22876
24200
  )
22877
24201
  );
22878
24202
  });
22879
- program2.command("docs").description("print human authoring docs").option("--registry <module>").option("--no-generic-blocks").option("--out <file>").action(async (rawOptions) => {
24203
+ program2.command("docs").description("print human authoring docs").option("--registry <module>", "Load custom block definitions from this module").option("--no-generic-blocks", "Do not include the built-in generic block pack").option("--out <file>", "Write the guide to a file instead of stdout").action(async (rawOptions) => {
22880
24204
  const options = optionsFrom(rawOptions);
22881
24205
  const { docsCommand: docsCommand2 } = await Promise.resolve().then(() => (init_docs(), docs_exports));
22882
24206
  setExitCode(
@@ -22890,13 +24214,14 @@ function createProgram(io, setExitCode) {
22890
24214
  )
22891
24215
  );
22892
24216
  });
22893
- program2.command("agents").description("install coding-agent guidance").option("--claude").option("--no-agents-md").option("--cwd <path>").action(async (rawOptions) => {
24217
+ program2.command("agents").description("install coding-agent guidance").option("--claude", "create .claude/ if needed and install Claude Code skills").option("--check", "show agent integration status without writing files").option("--dry-run", "alias for --check").option("--no-agents-md", "skip writing the AGENTS.md contentbit block").option("--cwd <path>", "install guidance in another directory").action(async (rawOptions) => {
22894
24218
  const options = optionsFrom(rawOptions);
22895
24219
  const { agentsCommand: agentsCommand2 } = await Promise.resolve().then(() => (init_agents(), agents_exports));
22896
24220
  setExitCode(
22897
24221
  await agentsCommand2(
22898
24222
  {
22899
24223
  claude: Boolean(options.claude),
24224
+ check: Boolean(options.check || options.dryRun),
22900
24225
  noAgentsMd: options.agentsMd === false,
22901
24226
  cwd: options.cwd
22902
24227
  },
@@ -22904,7 +24229,7 @@ function createProgram(io, setExitCode) {
22904
24229
  )
22905
24230
  );
22906
24231
  });
22907
- const links = program2.command("links").description("build or fix the internal link index").argument("[globs...]").option("--fix").option("--out <file>");
24232
+ const links = program2.command("links").description("build or fix the internal link index").argument("[globs...]", "Content files or quoted globs; defaults to project config").option("--fix", "Rewrite references that still use known aliases").option("--out <file>", "Write the link index to a custom path");
22908
24233
  addLinkOptions(links);
22909
24234
  links.action(async (globs, rawOptions) => {
22910
24235
  const options = optionsFrom(rawOptions);
@@ -22927,7 +24252,14 @@ function optionsFrom(raw) {
22927
24252
  return typeof raw.opts === "function" ? raw.opts() : raw;
22928
24253
  }
22929
24254
  function addLinkOptions(command) {
22930
- command.option("--link-resolve <mode>").option("--locale-field <name>").option("--slug-field <name>").option("--key-field <name>").option("--default-locale <locale>");
24255
+ command.addOption(
24256
+ new Option("--link-resolve <mode>", "Internal-link identity strategy").choices([
24257
+ "global-slug",
24258
+ "same-locale-slug",
24259
+ "same-locale-key",
24260
+ "prefer-same-locale-key-fallback-slug"
24261
+ ])
24262
+ ).option("--locale-field <name>", "Frontmatter field containing the locale").option("--slug-field <name>", "Frontmatter field containing the page slug").option("--key-field <name>", "Frontmatter field containing the stable page key").option("--default-locale <locale>", "Locale assumed when frontmatter omits one");
22931
24263
  }
22932
24264
  function linkOptionsFrom(options) {
22933
24265
  return {
@@ -22967,6 +24299,7 @@ Usage:
22967
24299
 
22968
24300
  Commands:
22969
24301
  init scaffold Content Blocks into a project
24302
+ adopt inspect an existing Markdown library without changing it
22970
24303
  validate check Markdown blocks and internal links
22971
24304
  brief print an agent-ready SEO brief
22972
24305
  doctor inspect content health and repair suggestions
@@ -22980,18 +24313,19 @@ Commands:
22980
24313
 
22981
24314
  Setup:
22982
24315
  init [-t react|markdown|astro] [--md ...] [-y] [--seo] [--no-install] [--no-page] [--no-agents]
22983
- agents [--claude] [--no-agents-md]
24316
+ adopt [globs...] [--dry-run] [--registry <module.ts>] [--no-generic-blocks] [--json]
24317
+ agents [--claude] [--check|--dry-run] [--no-agents-md]
22984
24318
 
22985
24319
  Common:
22986
- validate <globs...> [--registry <module.ts>] [--no-generic-blocks] [--strict-warnings] [--link-resolve <mode>]
24320
+ validate [globs...] [--registry <module.ts>] [--no-generic-blocks] [--strict-warnings] [--link-resolve <mode>]
22987
24321
  brief <key-or-slug> [globs...] [--registry <module.ts>] [--no-generic-blocks] [--seo-config <module.ts>] [--json]
22988
- doctor <globs...> [--registry <module.ts>] [--no-generic-blocks] [--strict-warnings] [--strict-seo] [--seo-config <module.ts>] [--no-seo] [--json] [--min-section-words <n>] [--link-resolve <mode>]
22989
- studio <globs...> [--registry <module.ts>] [--port <n>] [--host <host>] [--no-open] [--no-generic-blocks] [--seo-config <module.ts>] [--no-seo] [--link-resolve <mode>]
24322
+ doctor [globs...] [--watch] [--registry <module.ts>] [--no-generic-blocks] [--strict-warnings] [--strict-seo] [--seo-config <module.ts>] [--no-seo] [--json] [--min-section-words <n>] [--link-resolve <mode>]
24323
+ studio [globs...] [--registry <module.ts>] [--port <n>] [--host <host>] [--no-open] [--no-generic-blocks] [--seo-config <module.ts>] [--no-seo] [--link-resolve <mode>]
22990
24324
  stats <globs...> [--registry <module.ts>] [--no-generic-blocks] [--no-validate]
22991
24325
  render <file> [--target markdown] [--registry <module.ts>] [--no-generic-blocks] [--out <file>]
22992
24326
  instructions [--audience llm|human] [--no-examples] [--registry <module.ts>] [--no-generic-blocks] [--out <file>]
22993
24327
  docs [--registry <module.ts>] [--no-generic-blocks] [--out <file>]
22994
- links <globs...> [--fix] [--out <file>] [--link-resolve <mode>]`;
24328
+ links [globs...] [--fix] [--out <file>] [--link-resolve <mode>]`;
22995
24329
  }
22996
24330
  });
22997
24331