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