contentbit 0.6.1 → 0.7.1

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