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