specdx 0.2.0-alpha.2 → 0.3.0-alpha.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.
Files changed (49) hide show
  1. package/.claude-plugin/plugin.json +6 -0
  2. package/dist/changelog-NPN34DIO.js +86 -0
  3. package/dist/changelog-NPN34DIO.js.map +1 -0
  4. package/dist/{chunk-NTNH2EPU.js → chunk-276J7LR6.js} +22 -18
  5. package/dist/chunk-276J7LR6.js.map +1 -0
  6. package/dist/{lint-3WMYPOU4.js → chunk-6DTOYCZ6.js} +4 -102
  7. package/dist/chunk-6DTOYCZ6.js.map +1 -0
  8. package/dist/chunk-AO3ZQKLJ.js +1147 -0
  9. package/dist/chunk-AO3ZQKLJ.js.map +1 -0
  10. package/dist/chunk-GAM4MXPC.js +15 -0
  11. package/dist/chunk-GAM4MXPC.js.map +1 -0
  12. package/dist/{chunk-CV2CHFFG.js → chunk-XLEN6ZYM.js} +29 -5
  13. package/dist/chunk-XLEN6ZYM.js.map +1 -0
  14. package/dist/diff-GWJONALU.js +100 -0
  15. package/dist/diff-GWJONALU.js.map +1 -0
  16. package/dist/explain-YXUILNEA.js +102 -0
  17. package/dist/explain-YXUILNEA.js.map +1 -0
  18. package/dist/{graph-GOJ4EJED.js → graph-OWQJWVSN.js} +7 -5
  19. package/dist/{graph-GOJ4EJED.js.map → graph-OWQJWVSN.js.map} +1 -1
  20. package/dist/index.js +1593 -11
  21. package/dist/index.js.map +1 -1
  22. package/dist/lint-CHWVBUV5.js +111 -0
  23. package/dist/lint-CHWVBUV5.js.map +1 -0
  24. package/dist/main.js +10 -6
  25. package/dist/main.js.map +1 -1
  26. package/dist/{pack-T4SVXU5B.js → pack-OJAC7JF2.js} +40 -8
  27. package/dist/pack-OJAC7JF2.js.map +1 -0
  28. package/dist/skills/spec-type-reference.md +57 -0
  29. package/dist/skills/{specdx-author-spec/SKILL.md → specdx-author-spec.md} +15 -1
  30. package/dist/skills/specdx-onboard.md +49 -0
  31. package/dist/skills/specdx-plan-from-spec.md +72 -0
  32. package/dist/skills/specdx-pre-commit.md +56 -0
  33. package/dist/skills/specdx-sprint-review.md +69 -0
  34. package/dist/skills/{specdx-start-task/SKILL.md → specdx-start-task.md} +1 -1
  35. package/dist/{skills-FVSFWYHN.js → skills-XJYTWGDK.js} +15 -9
  36. package/dist/skills-XJYTWGDK.js.map +1 -0
  37. package/dist/status-VMALGNS5.js +145 -0
  38. package/dist/status-VMALGNS5.js.map +1 -0
  39. package/dist/{validate-TGMAJAPX.js → validate-DOZZEZFC.js} +7 -5
  40. package/dist/{validate-TGMAJAPX.js.map → validate-DOZZEZFC.js.map} +1 -1
  41. package/hooks/hooks.json +8 -0
  42. package/hooks/run-hook.cmd +46 -0
  43. package/hooks/session-start +77 -0
  44. package/package.json +6 -3
  45. package/dist/chunk-CV2CHFFG.js.map +0 -1
  46. package/dist/chunk-NTNH2EPU.js.map +0 -1
  47. package/dist/lint-3WMYPOU4.js.map +0 -1
  48. package/dist/pack-T4SVXU5B.js.map +0 -1
  49. package/dist/skills-FVSFWYHN.js.map +0 -1
package/dist/index.js CHANGED
@@ -80,7 +80,8 @@ var config_default = {
80
80
  path: { type: "string" },
81
81
  type: { type: "string", enum: ["prd", "technical-design", "user-story", "test-plan", "adr", "api-contract"] },
82
82
  required: { type: "boolean", default: false },
83
- requires: { type: "array", items: { type: "string" } }
83
+ requires: { type: "array", items: { type: "string" } },
84
+ owner: { type: "string" }
84
85
  },
85
86
  required: ["path", "type"],
86
87
  additionalProperties: false
@@ -89,7 +90,7 @@ var config_default = {
89
90
  lint: {
90
91
  type: "object",
91
92
  properties: {
92
- extends: { type: "string", enum: ["minimal", "recommended", "strict"] },
93
+ extends: { type: "string" },
93
94
  rules: { type: "object" },
94
95
  ignore: { type: "array", items: { type: "string" } }
95
96
  },
@@ -116,8 +117,31 @@ var config_default = {
116
117
  },
117
118
  additionalProperties: false
118
119
  },
119
- diff: { type: "object" },
120
- ci: { type: "object" }
120
+ diff: {
121
+ type: "object",
122
+ properties: {
123
+ baseline_ref: { type: "string", default: "main" },
124
+ staleness_threshold_days: { type: "integer", minimum: 1, default: 14 },
125
+ ignore_paths: { type: "array", items: { type: "string" } }
126
+ },
127
+ additionalProperties: false
128
+ },
129
+ ci: {
130
+ type: "object",
131
+ properties: {
132
+ block_on: {
133
+ type: "array",
134
+ items: { type: "string", enum: ["error", "warn", "info"] }
135
+ },
136
+ post_comment: { type: "boolean", default: true },
137
+ update_badge: { type: "boolean", default: true },
138
+ trigger_paths: {
139
+ type: "array",
140
+ items: { type: "string" }
141
+ }
142
+ },
143
+ additionalProperties: false
144
+ }
121
145
  },
122
146
  required: ["version", "specs"],
123
147
  additionalProperties: false
@@ -427,11 +451,14 @@ async function parseSpec(filePath) {
427
451
  } catch {
428
452
  throw new ParseError(`Cannot read spec file: ${filePath}`);
429
453
  }
454
+ return parseSpecFromString(raw, filePath);
455
+ }
456
+ function parseSpecFromString(content, filePath) {
430
457
  const ext = extname(filePath).toLowerCase();
431
458
  if (ext === ".yaml" || ext === ".yml") {
432
- return parseYamlSpec(filePath, raw);
459
+ return Promise.resolve(parseYamlSpec(filePath, content));
433
460
  }
434
- return parseMarkdownSpec(filePath, raw);
461
+ return Promise.resolve(parseMarkdownSpec(filePath, content));
435
462
  }
436
463
  function parseMarkdownSpec(filePath, raw) {
437
464
  const { data, content } = matter(raw);
@@ -464,14 +491,22 @@ function parseYamlSpec(filePath, raw) {
464
491
  valid = result.valid;
465
492
  validationErrors = result.errors;
466
493
  }
467
- return { filePath, frontmatter, content: "", sections: [], parsedSections: [], valid, validationErrors };
494
+ return {
495
+ filePath,
496
+ frontmatter,
497
+ content: "",
498
+ sections: [],
499
+ parsedSections: [],
500
+ valid,
501
+ validationErrors
502
+ };
468
503
  }
469
504
  function extractParsedSections(markdown) {
470
505
  const tree = unified().use(remarkParse).parse(markdown);
471
506
  const h2s = [];
472
507
  visit(tree, "heading", (node) => {
473
508
  if (node.depth === 2) {
474
- const text = node.children.filter((c) => c.type === "text").map((c) => c.value).join("");
509
+ const text = node.children.filter((c) => c.type === "text").map((c) => c.value ?? "").join("");
475
510
  h2s.push({
476
511
  heading: text,
477
512
  startOffset: node.position.start.offset,
@@ -605,6 +640,10 @@ function createLogger(options) {
605
640
  return createConsola({ level });
606
641
  }
607
642
 
643
+ // ../core/dist/preset.js
644
+ import { readFile as readFile3 } from "fs/promises";
645
+ import { resolve, isAbsolute as isAbsolute2 } from "path";
646
+
608
647
  // ../lint/dist/engine.js
609
648
  function createLintEngine(options) {
610
649
  return {
@@ -1466,6 +1505,21 @@ function pack(specs, options, packConfig, graph) {
1466
1505
 
1467
1506
  // src/commands/pack.ts
1468
1507
  import { writeFile as writeFile2 } from "fs/promises";
1508
+ import { execSync } from "child_process";
1509
+ function copyToClipboard(text) {
1510
+ const platform = process.platform;
1511
+ let cmd;
1512
+ if (platform === "darwin") {
1513
+ cmd = "pbcopy";
1514
+ } else if (platform === "linux") {
1515
+ cmd = "xclip -selection clipboard";
1516
+ } else if (platform === "win32") {
1517
+ cmd = "clip";
1518
+ } else {
1519
+ throw new Error(`Clipboard not supported on platform: ${platform}`);
1520
+ }
1521
+ execSync(cmd, { input: text, stdio: ["pipe", "ignore", "ignore"] });
1522
+ }
1469
1523
  async function runPack(options) {
1470
1524
  const config = await loadConfig(void 0, options.configDir);
1471
1525
  const allSpecs = [];
@@ -1509,8 +1563,12 @@ var pack_default = defineCommand3({
1509
1563
  default: "xml"
1510
1564
  },
1511
1565
  out: { type: "string", description: "Write output to file instead of stdout" },
1566
+ copy: { type: "boolean", description: "Copy output to system clipboard" },
1512
1567
  full: { type: "boolean", description: "Include all specs without budget trimming" },
1513
- "dry-run": { type: "boolean", description: "Preview what would be packed without writing output" }
1568
+ "dry-run": {
1569
+ type: "boolean",
1570
+ description: "Preview what would be packed without writing output"
1571
+ }
1514
1572
  },
1515
1573
  async run({ args }) {
1516
1574
  const logger = createLogger({ quiet: args.quiet, verbose: args.verbose });
@@ -1518,6 +1576,10 @@ var pack_default = defineCommand3({
1518
1576
  console.error("\n \u2717 --task and --specs are mutually exclusive\n");
1519
1577
  process.exit(1);
1520
1578
  }
1579
+ if (args.copy && args["dry-run"]) {
1580
+ console.error("\n \u2717 --copy and --dry-run are mutually exclusive\n");
1581
+ process.exit(1);
1582
+ }
1521
1583
  let budget;
1522
1584
  if (args.budget) {
1523
1585
  budget = Number(args.budget);
@@ -1556,7 +1618,9 @@ var pack_default = defineCommand3({
1556
1618
  }
1557
1619
  console.log(`
1558
1620
  Budget: ${stats.used} / ${stats.budget} tokens`);
1559
- console.log(` Included: ${stats.specsIncluded} / ${stats.specsIncluded + stats.specsExcluded} specs`);
1621
+ console.log(
1622
+ ` Included: ${stats.specsIncluded} / ${stats.specsIncluded + stats.specsExcluded} specs`
1623
+ );
1560
1624
  console.log(` Sections compressed: ${stats.sectionsCompressed}
1561
1625
  `);
1562
1626
  return;
@@ -1564,7 +1628,12 @@ var pack_default = defineCommand3({
1564
1628
  if (args.out) {
1565
1629
  await writeFile2(args.out, result.output, "utf-8");
1566
1630
  logger.info(`Output written to ${args.out}`);
1567
- } else {
1631
+ }
1632
+ if (args.copy) {
1633
+ copyToClipboard(result.output);
1634
+ logger.info("Output copied to clipboard");
1635
+ }
1636
+ if (!args.out && !args.copy) {
1568
1637
  process.stdout.write(result.output);
1569
1638
  }
1570
1639
  const total = stats.specsIncluded + stats.specsExcluded;
@@ -1580,9 +1649,1522 @@ var pack_default = defineCommand3({
1580
1649
  }
1581
1650
  }
1582
1651
  });
1652
+
1653
+ // src/commands/diff.ts
1654
+ import { defineCommand as defineCommand4 } from "citty";
1655
+ import { join as join5 } from "path";
1656
+
1657
+ // ../diff/dist/types.js
1658
+ var DEFAULT_DIFF_CONFIG = {
1659
+ baseline_ref: "main",
1660
+ staleness_threshold_days: 14
1661
+ };
1662
+ var DiffError = class extends Error {
1663
+ constructor(message) {
1664
+ super(message);
1665
+ this.name = "DiffError";
1666
+ }
1667
+ };
1668
+
1669
+ // ../../node_modules/.pnpm/diff@7.0.0/node_modules/diff/lib/index.mjs
1670
+ function Diff() {
1671
+ }
1672
+ Diff.prototype = {
1673
+ diff: function diff(oldString, newString) {
1674
+ var _options$timeout;
1675
+ var options = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {};
1676
+ var callback = options.callback;
1677
+ if (typeof options === "function") {
1678
+ callback = options;
1679
+ options = {};
1680
+ }
1681
+ var self = this;
1682
+ function done(value) {
1683
+ value = self.postProcess(value, options);
1684
+ if (callback) {
1685
+ setTimeout(function() {
1686
+ callback(value);
1687
+ }, 0);
1688
+ return true;
1689
+ } else {
1690
+ return value;
1691
+ }
1692
+ }
1693
+ oldString = this.castInput(oldString, options);
1694
+ newString = this.castInput(newString, options);
1695
+ oldString = this.removeEmpty(this.tokenize(oldString, options));
1696
+ newString = this.removeEmpty(this.tokenize(newString, options));
1697
+ var newLen = newString.length, oldLen = oldString.length;
1698
+ var editLength = 1;
1699
+ var maxEditLength = newLen + oldLen;
1700
+ if (options.maxEditLength != null) {
1701
+ maxEditLength = Math.min(maxEditLength, options.maxEditLength);
1702
+ }
1703
+ var maxExecutionTime = (_options$timeout = options.timeout) !== null && _options$timeout !== void 0 ? _options$timeout : Infinity;
1704
+ var abortAfterTimestamp = Date.now() + maxExecutionTime;
1705
+ var bestPath = [{
1706
+ oldPos: -1,
1707
+ lastComponent: void 0
1708
+ }];
1709
+ var newPos = this.extractCommon(bestPath[0], newString, oldString, 0, options);
1710
+ if (bestPath[0].oldPos + 1 >= oldLen && newPos + 1 >= newLen) {
1711
+ return done(buildValues(self, bestPath[0].lastComponent, newString, oldString, self.useLongestToken));
1712
+ }
1713
+ var minDiagonalToConsider = -Infinity, maxDiagonalToConsider = Infinity;
1714
+ function execEditLength() {
1715
+ for (var diagonalPath = Math.max(minDiagonalToConsider, -editLength); diagonalPath <= Math.min(maxDiagonalToConsider, editLength); diagonalPath += 2) {
1716
+ var basePath = void 0;
1717
+ var removePath = bestPath[diagonalPath - 1], addPath = bestPath[diagonalPath + 1];
1718
+ if (removePath) {
1719
+ bestPath[diagonalPath - 1] = void 0;
1720
+ }
1721
+ var canAdd = false;
1722
+ if (addPath) {
1723
+ var addPathNewPos = addPath.oldPos - diagonalPath;
1724
+ canAdd = addPath && 0 <= addPathNewPos && addPathNewPos < newLen;
1725
+ }
1726
+ var canRemove = removePath && removePath.oldPos + 1 < oldLen;
1727
+ if (!canAdd && !canRemove) {
1728
+ bestPath[diagonalPath] = void 0;
1729
+ continue;
1730
+ }
1731
+ if (!canRemove || canAdd && removePath.oldPos < addPath.oldPos) {
1732
+ basePath = self.addToPath(addPath, true, false, 0, options);
1733
+ } else {
1734
+ basePath = self.addToPath(removePath, false, true, 1, options);
1735
+ }
1736
+ newPos = self.extractCommon(basePath, newString, oldString, diagonalPath, options);
1737
+ if (basePath.oldPos + 1 >= oldLen && newPos + 1 >= newLen) {
1738
+ return done(buildValues(self, basePath.lastComponent, newString, oldString, self.useLongestToken));
1739
+ } else {
1740
+ bestPath[diagonalPath] = basePath;
1741
+ if (basePath.oldPos + 1 >= oldLen) {
1742
+ maxDiagonalToConsider = Math.min(maxDiagonalToConsider, diagonalPath - 1);
1743
+ }
1744
+ if (newPos + 1 >= newLen) {
1745
+ minDiagonalToConsider = Math.max(minDiagonalToConsider, diagonalPath + 1);
1746
+ }
1747
+ }
1748
+ }
1749
+ editLength++;
1750
+ }
1751
+ if (callback) {
1752
+ (function exec() {
1753
+ setTimeout(function() {
1754
+ if (editLength > maxEditLength || Date.now() > abortAfterTimestamp) {
1755
+ return callback();
1756
+ }
1757
+ if (!execEditLength()) {
1758
+ exec();
1759
+ }
1760
+ }, 0);
1761
+ })();
1762
+ } else {
1763
+ while (editLength <= maxEditLength && Date.now() <= abortAfterTimestamp) {
1764
+ var ret = execEditLength();
1765
+ if (ret) {
1766
+ return ret;
1767
+ }
1768
+ }
1769
+ }
1770
+ },
1771
+ addToPath: function addToPath(path, added, removed, oldPosInc, options) {
1772
+ var last = path.lastComponent;
1773
+ if (last && !options.oneChangePerToken && last.added === added && last.removed === removed) {
1774
+ return {
1775
+ oldPos: path.oldPos + oldPosInc,
1776
+ lastComponent: {
1777
+ count: last.count + 1,
1778
+ added,
1779
+ removed,
1780
+ previousComponent: last.previousComponent
1781
+ }
1782
+ };
1783
+ } else {
1784
+ return {
1785
+ oldPos: path.oldPos + oldPosInc,
1786
+ lastComponent: {
1787
+ count: 1,
1788
+ added,
1789
+ removed,
1790
+ previousComponent: last
1791
+ }
1792
+ };
1793
+ }
1794
+ },
1795
+ extractCommon: function extractCommon(basePath, newString, oldString, diagonalPath, options) {
1796
+ var newLen = newString.length, oldLen = oldString.length, oldPos = basePath.oldPos, newPos = oldPos - diagonalPath, commonCount = 0;
1797
+ while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(oldString[oldPos + 1], newString[newPos + 1], options)) {
1798
+ newPos++;
1799
+ oldPos++;
1800
+ commonCount++;
1801
+ if (options.oneChangePerToken) {
1802
+ basePath.lastComponent = {
1803
+ count: 1,
1804
+ previousComponent: basePath.lastComponent,
1805
+ added: false,
1806
+ removed: false
1807
+ };
1808
+ }
1809
+ }
1810
+ if (commonCount && !options.oneChangePerToken) {
1811
+ basePath.lastComponent = {
1812
+ count: commonCount,
1813
+ previousComponent: basePath.lastComponent,
1814
+ added: false,
1815
+ removed: false
1816
+ };
1817
+ }
1818
+ basePath.oldPos = oldPos;
1819
+ return newPos;
1820
+ },
1821
+ equals: function equals(left, right, options) {
1822
+ if (options.comparator) {
1823
+ return options.comparator(left, right);
1824
+ } else {
1825
+ return left === right || options.ignoreCase && left.toLowerCase() === right.toLowerCase();
1826
+ }
1827
+ },
1828
+ removeEmpty: function removeEmpty(array) {
1829
+ var ret = [];
1830
+ for (var i = 0; i < array.length; i++) {
1831
+ if (array[i]) {
1832
+ ret.push(array[i]);
1833
+ }
1834
+ }
1835
+ return ret;
1836
+ },
1837
+ castInput: function castInput(value) {
1838
+ return value;
1839
+ },
1840
+ tokenize: function tokenize2(value) {
1841
+ return Array.from(value);
1842
+ },
1843
+ join: function join4(chars) {
1844
+ return chars.join("");
1845
+ },
1846
+ postProcess: function postProcess(changeObjects) {
1847
+ return changeObjects;
1848
+ }
1849
+ };
1850
+ function buildValues(diff2, lastComponent, newString, oldString, useLongestToken) {
1851
+ var components = [];
1852
+ var nextComponent;
1853
+ while (lastComponent) {
1854
+ components.push(lastComponent);
1855
+ nextComponent = lastComponent.previousComponent;
1856
+ delete lastComponent.previousComponent;
1857
+ lastComponent = nextComponent;
1858
+ }
1859
+ components.reverse();
1860
+ var componentPos = 0, componentLen = components.length, newPos = 0, oldPos = 0;
1861
+ for (; componentPos < componentLen; componentPos++) {
1862
+ var component = components[componentPos];
1863
+ if (!component.removed) {
1864
+ if (!component.added && useLongestToken) {
1865
+ var value = newString.slice(newPos, newPos + component.count);
1866
+ value = value.map(function(value2, i) {
1867
+ var oldValue = oldString[oldPos + i];
1868
+ return oldValue.length > value2.length ? oldValue : value2;
1869
+ });
1870
+ component.value = diff2.join(value);
1871
+ } else {
1872
+ component.value = diff2.join(newString.slice(newPos, newPos + component.count));
1873
+ }
1874
+ newPos += component.count;
1875
+ if (!component.added) {
1876
+ oldPos += component.count;
1877
+ }
1878
+ } else {
1879
+ component.value = diff2.join(oldString.slice(oldPos, oldPos + component.count));
1880
+ oldPos += component.count;
1881
+ }
1882
+ }
1883
+ return components;
1884
+ }
1885
+ var characterDiff = new Diff();
1886
+ function longestCommonPrefix(str1, str2) {
1887
+ var i;
1888
+ for (i = 0; i < str1.length && i < str2.length; i++) {
1889
+ if (str1[i] != str2[i]) {
1890
+ return str1.slice(0, i);
1891
+ }
1892
+ }
1893
+ return str1.slice(0, i);
1894
+ }
1895
+ function longestCommonSuffix(str1, str2) {
1896
+ var i;
1897
+ if (!str1 || !str2 || str1[str1.length - 1] != str2[str2.length - 1]) {
1898
+ return "";
1899
+ }
1900
+ for (i = 0; i < str1.length && i < str2.length; i++) {
1901
+ if (str1[str1.length - (i + 1)] != str2[str2.length - (i + 1)]) {
1902
+ return str1.slice(-i);
1903
+ }
1904
+ }
1905
+ return str1.slice(-i);
1906
+ }
1907
+ function replacePrefix(string, oldPrefix, newPrefix) {
1908
+ if (string.slice(0, oldPrefix.length) != oldPrefix) {
1909
+ throw Error("string ".concat(JSON.stringify(string), " doesn't start with prefix ").concat(JSON.stringify(oldPrefix), "; this is a bug"));
1910
+ }
1911
+ return newPrefix + string.slice(oldPrefix.length);
1912
+ }
1913
+ function replaceSuffix(string, oldSuffix, newSuffix) {
1914
+ if (!oldSuffix) {
1915
+ return string + newSuffix;
1916
+ }
1917
+ if (string.slice(-oldSuffix.length) != oldSuffix) {
1918
+ throw Error("string ".concat(JSON.stringify(string), " doesn't end with suffix ").concat(JSON.stringify(oldSuffix), "; this is a bug"));
1919
+ }
1920
+ return string.slice(0, -oldSuffix.length) + newSuffix;
1921
+ }
1922
+ function removePrefix(string, oldPrefix) {
1923
+ return replacePrefix(string, oldPrefix, "");
1924
+ }
1925
+ function removeSuffix(string, oldSuffix) {
1926
+ return replaceSuffix(string, oldSuffix, "");
1927
+ }
1928
+ function maximumOverlap(string1, string2) {
1929
+ return string2.slice(0, overlapCount(string1, string2));
1930
+ }
1931
+ function overlapCount(a, b) {
1932
+ var startA = 0;
1933
+ if (a.length > b.length) {
1934
+ startA = a.length - b.length;
1935
+ }
1936
+ var endB = b.length;
1937
+ if (a.length < b.length) {
1938
+ endB = a.length;
1939
+ }
1940
+ var map = Array(endB);
1941
+ var k = 0;
1942
+ map[0] = 0;
1943
+ for (var j = 1; j < endB; j++) {
1944
+ if (b[j] == b[k]) {
1945
+ map[j] = map[k];
1946
+ } else {
1947
+ map[j] = k;
1948
+ }
1949
+ while (k > 0 && b[j] != b[k]) {
1950
+ k = map[k];
1951
+ }
1952
+ if (b[j] == b[k]) {
1953
+ k++;
1954
+ }
1955
+ }
1956
+ k = 0;
1957
+ for (var i = startA; i < a.length; i++) {
1958
+ while (k > 0 && a[i] != b[k]) {
1959
+ k = map[k];
1960
+ }
1961
+ if (a[i] == b[k]) {
1962
+ k++;
1963
+ }
1964
+ }
1965
+ return k;
1966
+ }
1967
+ var extendedWordChars = "a-zA-Z0-9_\\u{C0}-\\u{FF}\\u{D8}-\\u{F6}\\u{F8}-\\u{2C6}\\u{2C8}-\\u{2D7}\\u{2DE}-\\u{2FF}\\u{1E00}-\\u{1EFF}";
1968
+ var tokenizeIncludingWhitespace = new RegExp("[".concat(extendedWordChars, "]+|\\s+|[^").concat(extendedWordChars, "]"), "ug");
1969
+ var wordDiff = new Diff();
1970
+ wordDiff.equals = function(left, right, options) {
1971
+ if (options.ignoreCase) {
1972
+ left = left.toLowerCase();
1973
+ right = right.toLowerCase();
1974
+ }
1975
+ return left.trim() === right.trim();
1976
+ };
1977
+ wordDiff.tokenize = function(value) {
1978
+ var options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
1979
+ var parts;
1980
+ if (options.intlSegmenter) {
1981
+ if (options.intlSegmenter.resolvedOptions().granularity != "word") {
1982
+ throw new Error('The segmenter passed must have a granularity of "word"');
1983
+ }
1984
+ parts = Array.from(options.intlSegmenter.segment(value), function(segment) {
1985
+ return segment.segment;
1986
+ });
1987
+ } else {
1988
+ parts = value.match(tokenizeIncludingWhitespace) || [];
1989
+ }
1990
+ var tokens = [];
1991
+ var prevPart = null;
1992
+ parts.forEach(function(part) {
1993
+ if (/\s/.test(part)) {
1994
+ if (prevPart == null) {
1995
+ tokens.push(part);
1996
+ } else {
1997
+ tokens.push(tokens.pop() + part);
1998
+ }
1999
+ } else if (/\s/.test(prevPart)) {
2000
+ if (tokens[tokens.length - 1] == prevPart) {
2001
+ tokens.push(tokens.pop() + part);
2002
+ } else {
2003
+ tokens.push(prevPart + part);
2004
+ }
2005
+ } else {
2006
+ tokens.push(part);
2007
+ }
2008
+ prevPart = part;
2009
+ });
2010
+ return tokens;
2011
+ };
2012
+ wordDiff.join = function(tokens) {
2013
+ return tokens.map(function(token, i) {
2014
+ if (i == 0) {
2015
+ return token;
2016
+ } else {
2017
+ return token.replace(/^\s+/, "");
2018
+ }
2019
+ }).join("");
2020
+ };
2021
+ wordDiff.postProcess = function(changes, options) {
2022
+ if (!changes || options.oneChangePerToken) {
2023
+ return changes;
2024
+ }
2025
+ var lastKeep = null;
2026
+ var insertion = null;
2027
+ var deletion = null;
2028
+ changes.forEach(function(change) {
2029
+ if (change.added) {
2030
+ insertion = change;
2031
+ } else if (change.removed) {
2032
+ deletion = change;
2033
+ } else {
2034
+ if (insertion || deletion) {
2035
+ dedupeWhitespaceInChangeObjects(lastKeep, deletion, insertion, change);
2036
+ }
2037
+ lastKeep = change;
2038
+ insertion = null;
2039
+ deletion = null;
2040
+ }
2041
+ });
2042
+ if (insertion || deletion) {
2043
+ dedupeWhitespaceInChangeObjects(lastKeep, deletion, insertion, null);
2044
+ }
2045
+ return changes;
2046
+ };
2047
+ function dedupeWhitespaceInChangeObjects(startKeep, deletion, insertion, endKeep) {
2048
+ if (deletion && insertion) {
2049
+ var oldWsPrefix = deletion.value.match(/^\s*/)[0];
2050
+ var oldWsSuffix = deletion.value.match(/\s*$/)[0];
2051
+ var newWsPrefix = insertion.value.match(/^\s*/)[0];
2052
+ var newWsSuffix = insertion.value.match(/\s*$/)[0];
2053
+ if (startKeep) {
2054
+ var commonWsPrefix = longestCommonPrefix(oldWsPrefix, newWsPrefix);
2055
+ startKeep.value = replaceSuffix(startKeep.value, newWsPrefix, commonWsPrefix);
2056
+ deletion.value = removePrefix(deletion.value, commonWsPrefix);
2057
+ insertion.value = removePrefix(insertion.value, commonWsPrefix);
2058
+ }
2059
+ if (endKeep) {
2060
+ var commonWsSuffix = longestCommonSuffix(oldWsSuffix, newWsSuffix);
2061
+ endKeep.value = replacePrefix(endKeep.value, newWsSuffix, commonWsSuffix);
2062
+ deletion.value = removeSuffix(deletion.value, commonWsSuffix);
2063
+ insertion.value = removeSuffix(insertion.value, commonWsSuffix);
2064
+ }
2065
+ } else if (insertion) {
2066
+ if (startKeep) {
2067
+ insertion.value = insertion.value.replace(/^\s*/, "");
2068
+ }
2069
+ if (endKeep) {
2070
+ endKeep.value = endKeep.value.replace(/^\s*/, "");
2071
+ }
2072
+ } else if (startKeep && endKeep) {
2073
+ var newWsFull = endKeep.value.match(/^\s*/)[0], delWsStart = deletion.value.match(/^\s*/)[0], delWsEnd = deletion.value.match(/\s*$/)[0];
2074
+ var newWsStart = longestCommonPrefix(newWsFull, delWsStart);
2075
+ deletion.value = removePrefix(deletion.value, newWsStart);
2076
+ var newWsEnd = longestCommonSuffix(removePrefix(newWsFull, newWsStart), delWsEnd);
2077
+ deletion.value = removeSuffix(deletion.value, newWsEnd);
2078
+ endKeep.value = replacePrefix(endKeep.value, newWsFull, newWsEnd);
2079
+ startKeep.value = replaceSuffix(startKeep.value, newWsFull, newWsFull.slice(0, newWsFull.length - newWsEnd.length));
2080
+ } else if (endKeep) {
2081
+ var endKeepWsPrefix = endKeep.value.match(/^\s*/)[0];
2082
+ var deletionWsSuffix = deletion.value.match(/\s*$/)[0];
2083
+ var overlap = maximumOverlap(deletionWsSuffix, endKeepWsPrefix);
2084
+ deletion.value = removeSuffix(deletion.value, overlap);
2085
+ } else if (startKeep) {
2086
+ var startKeepWsSuffix = startKeep.value.match(/\s*$/)[0];
2087
+ var deletionWsPrefix = deletion.value.match(/^\s*/)[0];
2088
+ var _overlap = maximumOverlap(startKeepWsSuffix, deletionWsPrefix);
2089
+ deletion.value = removePrefix(deletion.value, _overlap);
2090
+ }
2091
+ }
2092
+ var wordWithSpaceDiff = new Diff();
2093
+ wordWithSpaceDiff.tokenize = function(value) {
2094
+ var regex = new RegExp("(\\r?\\n)|[".concat(extendedWordChars, "]+|[^\\S\\n\\r]+|[^").concat(extendedWordChars, "]"), "ug");
2095
+ return value.match(regex) || [];
2096
+ };
2097
+ var lineDiff = new Diff();
2098
+ lineDiff.tokenize = function(value, options) {
2099
+ if (options.stripTrailingCr) {
2100
+ value = value.replace(/\r\n/g, "\n");
2101
+ }
2102
+ var retLines = [], linesAndNewlines = value.split(/(\n|\r\n)/);
2103
+ if (!linesAndNewlines[linesAndNewlines.length - 1]) {
2104
+ linesAndNewlines.pop();
2105
+ }
2106
+ for (var i = 0; i < linesAndNewlines.length; i++) {
2107
+ var line = linesAndNewlines[i];
2108
+ if (i % 2 && !options.newlineIsToken) {
2109
+ retLines[retLines.length - 1] += line;
2110
+ } else {
2111
+ retLines.push(line);
2112
+ }
2113
+ }
2114
+ return retLines;
2115
+ };
2116
+ lineDiff.equals = function(left, right, options) {
2117
+ if (options.ignoreWhitespace) {
2118
+ if (!options.newlineIsToken || !left.includes("\n")) {
2119
+ left = left.trim();
2120
+ }
2121
+ if (!options.newlineIsToken || !right.includes("\n")) {
2122
+ right = right.trim();
2123
+ }
2124
+ } else if (options.ignoreNewlineAtEof && !options.newlineIsToken) {
2125
+ if (left.endsWith("\n")) {
2126
+ left = left.slice(0, -1);
2127
+ }
2128
+ if (right.endsWith("\n")) {
2129
+ right = right.slice(0, -1);
2130
+ }
2131
+ }
2132
+ return Diff.prototype.equals.call(this, left, right, options);
2133
+ };
2134
+ function diffLines(oldStr, newStr, callback) {
2135
+ return lineDiff.diff(oldStr, newStr, callback);
2136
+ }
2137
+ var sentenceDiff = new Diff();
2138
+ sentenceDiff.tokenize = function(value) {
2139
+ return value.split(/(\S.+?[.!?])(?=\s+|$)/);
2140
+ };
2141
+ var cssDiff = new Diff();
2142
+ cssDiff.tokenize = function(value) {
2143
+ return value.split(/([{}:;,]|\s+)/);
2144
+ };
2145
+ function ownKeys(e, r) {
2146
+ var t = Object.keys(e);
2147
+ if (Object.getOwnPropertySymbols) {
2148
+ var o = Object.getOwnPropertySymbols(e);
2149
+ r && (o = o.filter(function(r2) {
2150
+ return Object.getOwnPropertyDescriptor(e, r2).enumerable;
2151
+ })), t.push.apply(t, o);
2152
+ }
2153
+ return t;
2154
+ }
2155
+ function _objectSpread2(e) {
2156
+ for (var r = 1; r < arguments.length; r++) {
2157
+ var t = null != arguments[r] ? arguments[r] : {};
2158
+ r % 2 ? ownKeys(Object(t), true).forEach(function(r2) {
2159
+ _defineProperty(e, r2, t[r2]);
2160
+ }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function(r2) {
2161
+ Object.defineProperty(e, r2, Object.getOwnPropertyDescriptor(t, r2));
2162
+ });
2163
+ }
2164
+ return e;
2165
+ }
2166
+ function _toPrimitive(t, r) {
2167
+ if ("object" != typeof t || !t) return t;
2168
+ var e = t[Symbol.toPrimitive];
2169
+ if (void 0 !== e) {
2170
+ var i = e.call(t, r || "default");
2171
+ if ("object" != typeof i) return i;
2172
+ throw new TypeError("@@toPrimitive must return a primitive value.");
2173
+ }
2174
+ return ("string" === r ? String : Number)(t);
2175
+ }
2176
+ function _toPropertyKey(t) {
2177
+ var i = _toPrimitive(t, "string");
2178
+ return "symbol" == typeof i ? i : i + "";
2179
+ }
2180
+ function _typeof(o) {
2181
+ "@babel/helpers - typeof";
2182
+ return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o2) {
2183
+ return typeof o2;
2184
+ } : function(o2) {
2185
+ return o2 && "function" == typeof Symbol && o2.constructor === Symbol && o2 !== Symbol.prototype ? "symbol" : typeof o2;
2186
+ }, _typeof(o);
2187
+ }
2188
+ function _defineProperty(obj, key, value) {
2189
+ key = _toPropertyKey(key);
2190
+ if (key in obj) {
2191
+ Object.defineProperty(obj, key, {
2192
+ value,
2193
+ enumerable: true,
2194
+ configurable: true,
2195
+ writable: true
2196
+ });
2197
+ } else {
2198
+ obj[key] = value;
2199
+ }
2200
+ return obj;
2201
+ }
2202
+ function _toConsumableArray(arr) {
2203
+ return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();
2204
+ }
2205
+ function _arrayWithoutHoles(arr) {
2206
+ if (Array.isArray(arr)) return _arrayLikeToArray(arr);
2207
+ }
2208
+ function _iterableToArray(iter) {
2209
+ if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
2210
+ }
2211
+ function _unsupportedIterableToArray(o, minLen) {
2212
+ if (!o) return;
2213
+ if (typeof o === "string") return _arrayLikeToArray(o, minLen);
2214
+ var n = Object.prototype.toString.call(o).slice(8, -1);
2215
+ if (n === "Object" && o.constructor) n = o.constructor.name;
2216
+ if (n === "Map" || n === "Set") return Array.from(o);
2217
+ if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
2218
+ }
2219
+ function _arrayLikeToArray(arr, len) {
2220
+ if (len == null || len > arr.length) len = arr.length;
2221
+ for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
2222
+ return arr2;
2223
+ }
2224
+ function _nonIterableSpread() {
2225
+ throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
2226
+ }
2227
+ var jsonDiff = new Diff();
2228
+ jsonDiff.useLongestToken = true;
2229
+ jsonDiff.tokenize = lineDiff.tokenize;
2230
+ jsonDiff.castInput = function(value, options) {
2231
+ var undefinedReplacement = options.undefinedReplacement, _options$stringifyRep = options.stringifyReplacer, stringifyReplacer = _options$stringifyRep === void 0 ? function(k, v) {
2232
+ return typeof v === "undefined" ? undefinedReplacement : v;
2233
+ } : _options$stringifyRep;
2234
+ return typeof value === "string" ? value : JSON.stringify(canonicalize(value, null, null, stringifyReplacer), stringifyReplacer, " ");
2235
+ };
2236
+ jsonDiff.equals = function(left, right, options) {
2237
+ return Diff.prototype.equals.call(jsonDiff, left.replace(/,([\r\n])/g, "$1"), right.replace(/,([\r\n])/g, "$1"), options);
2238
+ };
2239
+ function canonicalize(obj, stack, replacementStack, replacer, key) {
2240
+ stack = stack || [];
2241
+ replacementStack = replacementStack || [];
2242
+ if (replacer) {
2243
+ obj = replacer(key, obj);
2244
+ }
2245
+ var i;
2246
+ for (i = 0; i < stack.length; i += 1) {
2247
+ if (stack[i] === obj) {
2248
+ return replacementStack[i];
2249
+ }
2250
+ }
2251
+ var canonicalizedObj;
2252
+ if ("[object Array]" === Object.prototype.toString.call(obj)) {
2253
+ stack.push(obj);
2254
+ canonicalizedObj = new Array(obj.length);
2255
+ replacementStack.push(canonicalizedObj);
2256
+ for (i = 0; i < obj.length; i += 1) {
2257
+ canonicalizedObj[i] = canonicalize(obj[i], stack, replacementStack, replacer, key);
2258
+ }
2259
+ stack.pop();
2260
+ replacementStack.pop();
2261
+ return canonicalizedObj;
2262
+ }
2263
+ if (obj && obj.toJSON) {
2264
+ obj = obj.toJSON();
2265
+ }
2266
+ if (_typeof(obj) === "object" && obj !== null) {
2267
+ stack.push(obj);
2268
+ canonicalizedObj = {};
2269
+ replacementStack.push(canonicalizedObj);
2270
+ var sortedKeys = [], _key;
2271
+ for (_key in obj) {
2272
+ if (Object.prototype.hasOwnProperty.call(obj, _key)) {
2273
+ sortedKeys.push(_key);
2274
+ }
2275
+ }
2276
+ sortedKeys.sort();
2277
+ for (i = 0; i < sortedKeys.length; i += 1) {
2278
+ _key = sortedKeys[i];
2279
+ canonicalizedObj[_key] = canonicalize(obj[_key], stack, replacementStack, replacer, _key);
2280
+ }
2281
+ stack.pop();
2282
+ replacementStack.pop();
2283
+ } else {
2284
+ canonicalizedObj = obj;
2285
+ }
2286
+ return canonicalizedObj;
2287
+ }
2288
+ var arrayDiff = new Diff();
2289
+ arrayDiff.tokenize = function(value) {
2290
+ return value.slice();
2291
+ };
2292
+ arrayDiff.join = arrayDiff.removeEmpty = function(value) {
2293
+ return value;
2294
+ };
2295
+ function structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) {
2296
+ if (!options) {
2297
+ options = {};
2298
+ }
2299
+ if (typeof options === "function") {
2300
+ options = {
2301
+ callback: options
2302
+ };
2303
+ }
2304
+ if (typeof options.context === "undefined") {
2305
+ options.context = 4;
2306
+ }
2307
+ if (options.newlineIsToken) {
2308
+ throw new Error("newlineIsToken may not be used with patch-generation functions, only with diffing functions");
2309
+ }
2310
+ if (!options.callback) {
2311
+ return diffLinesResultToPatch(diffLines(oldStr, newStr, options));
2312
+ } else {
2313
+ var _options = options, _callback = _options.callback;
2314
+ diffLines(oldStr, newStr, _objectSpread2(_objectSpread2({}, options), {}, {
2315
+ callback: function callback(diff2) {
2316
+ var patch = diffLinesResultToPatch(diff2);
2317
+ _callback(patch);
2318
+ }
2319
+ }));
2320
+ }
2321
+ function diffLinesResultToPatch(diff2) {
2322
+ if (!diff2) {
2323
+ return;
2324
+ }
2325
+ diff2.push({
2326
+ value: "",
2327
+ lines: []
2328
+ });
2329
+ function contextLines(lines) {
2330
+ return lines.map(function(entry) {
2331
+ return " " + entry;
2332
+ });
2333
+ }
2334
+ var hunks = [];
2335
+ var oldRangeStart = 0, newRangeStart = 0, curRange = [], oldLine = 1, newLine = 1;
2336
+ var _loop = function _loop2() {
2337
+ var current = diff2[i], lines = current.lines || splitLines(current.value);
2338
+ current.lines = lines;
2339
+ if (current.added || current.removed) {
2340
+ var _curRange;
2341
+ if (!oldRangeStart) {
2342
+ var prev = diff2[i - 1];
2343
+ oldRangeStart = oldLine;
2344
+ newRangeStart = newLine;
2345
+ if (prev) {
2346
+ curRange = options.context > 0 ? contextLines(prev.lines.slice(-options.context)) : [];
2347
+ oldRangeStart -= curRange.length;
2348
+ newRangeStart -= curRange.length;
2349
+ }
2350
+ }
2351
+ (_curRange = curRange).push.apply(_curRange, _toConsumableArray(lines.map(function(entry) {
2352
+ return (current.added ? "+" : "-") + entry;
2353
+ })));
2354
+ if (current.added) {
2355
+ newLine += lines.length;
2356
+ } else {
2357
+ oldLine += lines.length;
2358
+ }
2359
+ } else {
2360
+ if (oldRangeStart) {
2361
+ if (lines.length <= options.context * 2 && i < diff2.length - 2) {
2362
+ var _curRange2;
2363
+ (_curRange2 = curRange).push.apply(_curRange2, _toConsumableArray(contextLines(lines)));
2364
+ } else {
2365
+ var _curRange3;
2366
+ var contextSize = Math.min(lines.length, options.context);
2367
+ (_curRange3 = curRange).push.apply(_curRange3, _toConsumableArray(contextLines(lines.slice(0, contextSize))));
2368
+ var _hunk = {
2369
+ oldStart: oldRangeStart,
2370
+ oldLines: oldLine - oldRangeStart + contextSize,
2371
+ newStart: newRangeStart,
2372
+ newLines: newLine - newRangeStart + contextSize,
2373
+ lines: curRange
2374
+ };
2375
+ hunks.push(_hunk);
2376
+ oldRangeStart = 0;
2377
+ newRangeStart = 0;
2378
+ curRange = [];
2379
+ }
2380
+ }
2381
+ oldLine += lines.length;
2382
+ newLine += lines.length;
2383
+ }
2384
+ };
2385
+ for (var i = 0; i < diff2.length; i++) {
2386
+ _loop();
2387
+ }
2388
+ for (var _i = 0, _hunks = hunks; _i < _hunks.length; _i++) {
2389
+ var hunk = _hunks[_i];
2390
+ for (var _i2 = 0; _i2 < hunk.lines.length; _i2++) {
2391
+ if (hunk.lines[_i2].endsWith("\n")) {
2392
+ hunk.lines[_i2] = hunk.lines[_i2].slice(0, -1);
2393
+ } else {
2394
+ hunk.lines.splice(_i2 + 1, 0, "\");
2395
+ _i2++;
2396
+ }
2397
+ }
2398
+ }
2399
+ return {
2400
+ oldFileName,
2401
+ newFileName,
2402
+ oldHeader,
2403
+ newHeader,
2404
+ hunks
2405
+ };
2406
+ }
2407
+ }
2408
+ function formatPatch(diff2) {
2409
+ if (Array.isArray(diff2)) {
2410
+ return diff2.map(formatPatch).join("\n");
2411
+ }
2412
+ var ret = [];
2413
+ if (diff2.oldFileName == diff2.newFileName) {
2414
+ ret.push("Index: " + diff2.oldFileName);
2415
+ }
2416
+ ret.push("===================================================================");
2417
+ ret.push("--- " + diff2.oldFileName + (typeof diff2.oldHeader === "undefined" ? "" : " " + diff2.oldHeader));
2418
+ ret.push("+++ " + diff2.newFileName + (typeof diff2.newHeader === "undefined" ? "" : " " + diff2.newHeader));
2419
+ for (var i = 0; i < diff2.hunks.length; i++) {
2420
+ var hunk = diff2.hunks[i];
2421
+ if (hunk.oldLines === 0) {
2422
+ hunk.oldStart -= 1;
2423
+ }
2424
+ if (hunk.newLines === 0) {
2425
+ hunk.newStart -= 1;
2426
+ }
2427
+ ret.push("@@ -" + hunk.oldStart + "," + hunk.oldLines + " +" + hunk.newStart + "," + hunk.newLines + " @@");
2428
+ ret.push.apply(ret, hunk.lines);
2429
+ }
2430
+ return ret.join("\n") + "\n";
2431
+ }
2432
+ function createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) {
2433
+ var _options2;
2434
+ if (typeof options === "function") {
2435
+ options = {
2436
+ callback: options
2437
+ };
2438
+ }
2439
+ if (!((_options2 = options) !== null && _options2 !== void 0 && _options2.callback)) {
2440
+ var patchObj = structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options);
2441
+ if (!patchObj) {
2442
+ return;
2443
+ }
2444
+ return formatPatch(patchObj);
2445
+ } else {
2446
+ var _options3 = options, _callback2 = _options3.callback;
2447
+ structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, _objectSpread2(_objectSpread2({}, options), {}, {
2448
+ callback: function callback(patchObj2) {
2449
+ if (!patchObj2) {
2450
+ _callback2();
2451
+ } else {
2452
+ _callback2(formatPatch(patchObj2));
2453
+ }
2454
+ }
2455
+ }));
2456
+ }
2457
+ }
2458
+ function createPatch(fileName, oldStr, newStr, oldHeader, newHeader, options) {
2459
+ return createTwoFilesPatch(fileName, fileName, oldStr, newStr, oldHeader, newHeader, options);
2460
+ }
2461
+ function splitLines(text) {
2462
+ var hasTrailingNl = text.endsWith("\n");
2463
+ var result = text.split("\n").map(function(line) {
2464
+ return line + "\n";
2465
+ });
2466
+ if (hasTrailingNl) {
2467
+ result.pop();
2468
+ } else {
2469
+ result.push(result.pop().slice(0, -1));
2470
+ }
2471
+ return result;
2472
+ }
2473
+
2474
+ // ../diff/dist/diff-specs.js
2475
+ function diffSpecs(before, after) {
2476
+ const frontmatter = diffFrontmatter(before.frontmatter, after.frontmatter);
2477
+ const sections = diffSections(before.parsedSections, after.parsedSections);
2478
+ const specId = after.frontmatter.id;
2479
+ const parts = [];
2480
+ if (frontmatter.length > 0)
2481
+ parts.push(`${frontmatter.length} field(s) changed`);
2482
+ if (sections.length > 0)
2483
+ parts.push(`${sections.length} section(s) changed`);
2484
+ const summary = parts.length > 0 ? `${specId}: ${parts.join(", ")}` : `${specId}: no changes`;
2485
+ return { specId, filePath: after.filePath, frontmatter, sections, summary };
2486
+ }
2487
+ function diffFrontmatter(before, after) {
2488
+ const changes = [];
2489
+ const allKeys = /* @__PURE__ */ new Set([...Object.keys(before), ...Object.keys(after)]);
2490
+ for (const key of allKeys) {
2491
+ const inBefore = Object.prototype.hasOwnProperty.call(before, key);
2492
+ const inAfter = Object.prototype.hasOwnProperty.call(after, key);
2493
+ if (inBefore && !inAfter) {
2494
+ changes.push({ field: key, type: "removed", before: before[key] });
2495
+ } else if (!inBefore && inAfter) {
2496
+ changes.push({ field: key, type: "added", after: after[key] });
2497
+ } else if (inBefore && inAfter) {
2498
+ const bVal = before[key];
2499
+ const aVal = after[key];
2500
+ if (JSON.stringify(bVal) !== JSON.stringify(aVal)) {
2501
+ changes.push({ field: key, type: "modified", before: bVal, after: aVal });
2502
+ }
2503
+ }
2504
+ }
2505
+ return changes;
2506
+ }
2507
+ function diffSections(before, after) {
2508
+ const changes = [];
2509
+ const beforeMap = /* @__PURE__ */ new Map();
2510
+ for (const section of before) {
2511
+ beforeMap.set(section.heading, section);
2512
+ }
2513
+ const afterMap = /* @__PURE__ */ new Map();
2514
+ for (const section of after) {
2515
+ afterMap.set(section.heading, section);
2516
+ }
2517
+ for (const [heading, _section] of beforeMap) {
2518
+ if (!afterMap.has(heading)) {
2519
+ changes.push({ heading, type: "removed" });
2520
+ }
2521
+ }
2522
+ for (const [heading, afterSection] of afterMap) {
2523
+ const beforeSection = beforeMap.get(heading);
2524
+ if (!beforeSection) {
2525
+ changes.push({ heading, type: "added" });
2526
+ } else if (beforeSection.content !== afterSection.content) {
2527
+ const contentDiff = createPatch(heading, beforeSection.content, afterSection.content, "before", "after");
2528
+ changes.push({ heading, type: "modified", contentDiff });
2529
+ }
2530
+ }
2531
+ return changes;
2532
+ }
2533
+
2534
+ // ../diff/dist/impact.js
2535
+ var STRUCTURAL_SECTIONS = /* @__PURE__ */ new Set([
2536
+ "Goals",
2537
+ "Architecture",
2538
+ "Features",
2539
+ "Endpoints",
2540
+ "Data Model",
2541
+ "API Design",
2542
+ "Problem Statement"
2543
+ ]);
2544
+ function bfsDistances(startId, graph) {
2545
+ const distances = /* @__PURE__ */ new Map();
2546
+ const queue = [];
2547
+ for (const edge of graph.edges) {
2548
+ if (edge.from === startId) {
2549
+ if (!distances.has(edge.to)) {
2550
+ distances.set(edge.to, 1);
2551
+ queue.push({ id: edge.to, distance: 1 });
2552
+ }
2553
+ }
2554
+ }
2555
+ while (queue.length > 0) {
2556
+ const item = queue.shift();
2557
+ const currentDist = item.distance;
2558
+ for (const edge of graph.edges) {
2559
+ if (edge.from === item.id && !distances.has(edge.to)) {
2560
+ distances.set(edge.to, currentDist + 1);
2561
+ queue.push({ id: edge.to, distance: currentDist + 1 });
2562
+ }
2563
+ }
2564
+ }
2565
+ return distances;
2566
+ }
2567
+ function daysBetween(dateStr) {
2568
+ const then = new Date(dateStr).getTime();
2569
+ const now = Date.now();
2570
+ return Math.max(0, (now - then) / (1e3 * 60 * 60 * 24));
2571
+ }
2572
+ function clamp(min, max, value) {
2573
+ return Math.min(max, Math.max(min, value));
2574
+ }
2575
+ function analyzeImpact(changedSpecId, diff2, graph, allSpecs, thresholdDays = 14) {
2576
+ const distanceMap = bfsDistances(changedSpecId, graph);
2577
+ if (distanceMap.size === 0) {
2578
+ return {
2579
+ changedSpec: changedSpecId,
2580
+ downstream: [],
2581
+ totalAffected: 0
2582
+ };
2583
+ }
2584
+ const totalSections = Math.max(1, diff2.sections.length);
2585
+ const structuralSectionsChanged = diff2.sections.filter((s) => STRUCTURAL_SECTIONS.has(s.heading)).length;
2586
+ const specById = /* @__PURE__ */ new Map();
2587
+ for (const spec of allSpecs) {
2588
+ const id = spec.frontmatter.id;
2589
+ if (id)
2590
+ specById.set(id, spec);
2591
+ }
2592
+ const downstream = [];
2593
+ for (const [specId, distance] of distanceMap) {
2594
+ const spec = specById.get(specId);
2595
+ const lastUpdated = spec?.frontmatter.updated ?? spec?.frontmatter.created ?? null;
2596
+ const filePath = spec?.filePath ?? `specs/${specId}.md`;
2597
+ let staleness = 0;
2598
+ if (lastUpdated) {
2599
+ const daysSinceUpdate = daysBetween(lastUpdated);
2600
+ staleness = clamp(0, 1, daysSinceUpdate / thresholdDays * 0.5 + structuralSectionsChanged / totalSections * 0.3 + 1 / distance * 0.2);
2601
+ } else {
2602
+ staleness = clamp(0, 1, structuralSectionsChanged / totalSections * 0.3 + 1 / distance * 0.2);
2603
+ }
2604
+ const parts = [];
2605
+ parts.push(`depends on ${changedSpecId} (distance ${distance})`);
2606
+ if (structuralSectionsChanged > 0) {
2607
+ parts.push(`${structuralSectionsChanged} structural section(s) changed`);
2608
+ }
2609
+ if (lastUpdated) {
2610
+ const days = Math.round(daysBetween(lastUpdated));
2611
+ parts.push(`last updated ${days} day(s) ago`);
2612
+ }
2613
+ const reason = parts.join("; ");
2614
+ downstream.push({
2615
+ specId,
2616
+ filePath,
2617
+ distance,
2618
+ lastUpdated,
2619
+ staleness,
2620
+ reason
2621
+ });
2622
+ }
2623
+ downstream.sort((a, b) => a.distance - b.distance || b.staleness - a.staleness);
2624
+ return {
2625
+ changedSpec: changedSpecId,
2626
+ downstream,
2627
+ totalAffected: downstream.length
2628
+ };
2629
+ }
2630
+
2631
+ // ../diff/dist/cross-refs.js
2632
+ function checkCrossReferences(allSpecs, removedIds) {
2633
+ const validIds = new Set(allSpecs.map((s) => s.frontmatter.id));
2634
+ for (const id of removedIds) {
2635
+ validIds.delete(id);
2636
+ }
2637
+ const broken = [];
2638
+ for (const spec of allSpecs) {
2639
+ const references = spec.frontmatter.references;
2640
+ if (!references || references.length === 0) {
2641
+ continue;
2642
+ }
2643
+ for (const ref of references) {
2644
+ if (!validIds.has(ref.id)) {
2645
+ broken.push({
2646
+ specId: spec.frontmatter.id,
2647
+ field: "references",
2648
+ type: "broken-reference",
2649
+ referencedId: ref.id
2650
+ });
2651
+ }
2652
+ }
2653
+ }
2654
+ return broken;
2655
+ }
2656
+
2657
+ // ../diff/dist/git.js
2658
+ import { execSync as execSync2 } from "child_process";
2659
+ import { realpathSync } from "fs";
2660
+ import { dirname as dirname2, relative, resolve as resolve2 } from "path";
2661
+ function getRepoRoot(cwd) {
2662
+ const root = execSync2("git rev-parse --show-toplevel", {
2663
+ cwd,
2664
+ encoding: "utf-8",
2665
+ stdio: "pipe"
2666
+ }).trim();
2667
+ return realpathSync(root);
2668
+ }
2669
+ function validateRef(ref, cwd) {
2670
+ try {
2671
+ execSync2(`git rev-parse --verify ${ref}`, { cwd, encoding: "utf-8", stdio: "pipe" });
2672
+ } catch {
2673
+ throw new DiffError(`Invalid git ref: "${ref}"`);
2674
+ }
2675
+ }
2676
+ function gitShow(ref, filePath, projectRoot, repoRoot) {
2677
+ const relPath = relative(repoRoot, resolve2(projectRoot, filePath));
2678
+ try {
2679
+ return execSync2(`git show ${ref}:${relPath}`, {
2680
+ cwd: repoRoot,
2681
+ encoding: "utf-8",
2682
+ stdio: "pipe"
2683
+ });
2684
+ } catch {
2685
+ throw new DiffError(`Cannot read "${filePath}" at ref "${ref}"`);
2686
+ }
2687
+ }
2688
+ function getChangedSpecFiles(baseRef, headRef, specPaths, projectRoot, repoRoot) {
2689
+ const repoRelToProjectRel = /* @__PURE__ */ new Map();
2690
+ for (const p of specPaths) {
2691
+ const repoRel = relative(repoRoot, resolve2(projectRoot, p));
2692
+ repoRelToProjectRel.set(repoRel, p);
2693
+ }
2694
+ let diffOutput;
2695
+ try {
2696
+ diffOutput = execSync2(`git diff --name-status ${baseRef} ${headRef}`, {
2697
+ cwd: repoRoot,
2698
+ encoding: "utf-8",
2699
+ stdio: "pipe"
2700
+ });
2701
+ } catch {
2702
+ throw new DiffError(`Failed to run git diff between "${baseRef}" and "${headRef}"`);
2703
+ }
2704
+ const result = { modified: [], added: [], deleted: [] };
2705
+ for (const line of diffOutput.trim().split("\n")) {
2706
+ if (!line)
2707
+ continue;
2708
+ const parts = line.split(" ");
2709
+ const status = parts[0];
2710
+ const filePath = parts[1];
2711
+ if (!status || !filePath)
2712
+ continue;
2713
+ const projectRelPath = repoRelToProjectRel.get(filePath);
2714
+ if (projectRelPath === void 0)
2715
+ continue;
2716
+ if (status === "M") {
2717
+ result.modified.push(projectRelPath);
2718
+ } else if (status === "A") {
2719
+ result.added.push(projectRelPath);
2720
+ } else if (status === "D") {
2721
+ result.deleted.push(projectRelPath);
2722
+ }
2723
+ }
2724
+ return result;
2725
+ }
2726
+ async function diffBetweenRefs(configPath, baseRef, headRef) {
2727
+ const projectRoot = realpathSync(dirname2(resolve2(configPath)));
2728
+ const repoRoot = getRepoRoot(projectRoot);
2729
+ validateRef(baseRef, projectRoot);
2730
+ validateRef(headRef, projectRoot);
2731
+ const config = await loadConfig(configPath);
2732
+ const specPaths = [];
2733
+ const specIdByPath = /* @__PURE__ */ new Map();
2734
+ for (const [specId, entry] of Object.entries(config.specs)) {
2735
+ specPaths.push(entry.path);
2736
+ specIdByPath.set(entry.path, specId);
2737
+ }
2738
+ const changed = getChangedSpecFiles(baseRef, headRef, specPaths, projectRoot, repoRoot);
2739
+ const diffs = [];
2740
+ for (const filePath of changed.modified) {
2741
+ const beforeContent = gitShow(baseRef, filePath, projectRoot, repoRoot);
2742
+ const afterContent = gitShow(headRef, filePath, projectRoot, repoRoot);
2743
+ const beforeSpec = await parseSpecFromString(beforeContent, filePath);
2744
+ const afterSpec = await parseSpecFromString(afterContent, filePath);
2745
+ const diff2 = diffSpecs(beforeSpec, afterSpec);
2746
+ diffs.push(diff2);
2747
+ }
2748
+ const added = changed.added.map((p) => specIdByPath.get(p)).filter((id) => id !== void 0);
2749
+ const removed = changed.deleted.map((p) => specIdByPath.get(p)).filter((id) => id !== void 0);
2750
+ const graph = buildGraph(config);
2751
+ const impact = [];
2752
+ const allSpecs = [];
2753
+ for (const entry of Object.values(config.specs)) {
2754
+ try {
2755
+ const content = gitShow(headRef, entry.path, projectRoot, repoRoot);
2756
+ const parsed = await parseSpecFromString(content, entry.path);
2757
+ allSpecs.push(parsed);
2758
+ } catch {
2759
+ }
2760
+ }
2761
+ const thresholdDays = config.diff?.staleness_threshold_days ?? 14;
2762
+ for (const diff2 of diffs) {
2763
+ const analysis = analyzeImpact(diff2.specId, diff2, graph, allSpecs, thresholdDays);
2764
+ if (analysis.totalAffected > 0) {
2765
+ impact.push(analysis);
2766
+ }
2767
+ }
2768
+ const _brokenRefs = checkCrossReferences(allSpecs, removed);
2769
+ const summaryParts = [];
2770
+ if (diffs.length > 0) {
2771
+ summaryParts.push(`${diffs.length} spec(s) modified`);
2772
+ }
2773
+ if (added.length > 0) {
2774
+ summaryParts.push(`${added.length} spec(s) added`);
2775
+ }
2776
+ if (removed.length > 0) {
2777
+ summaryParts.push(`${removed.length} spec(s) removed`);
2778
+ }
2779
+ if (impact.length > 0) {
2780
+ const totalDownstream = impact.reduce((sum, i) => sum + i.totalAffected, 0);
2781
+ summaryParts.push(`${totalDownstream} downstream spec(s) potentially affected`);
2782
+ }
2783
+ if (_brokenRefs.length > 0) {
2784
+ summaryParts.push(`${_brokenRefs.length} broken reference(s)`);
2785
+ }
2786
+ const summary = summaryParts.length > 0 ? summaryParts.join("; ") : "No changes detected";
2787
+ return { diffs, added, removed, impact, summary };
2788
+ }
2789
+
2790
+ // src/commands/diff.ts
2791
+ async function runDiff(options) {
2792
+ const configDir = process.cwd();
2793
+ const config = await loadConfig(void 0, configDir);
2794
+ const baseRef = options.base ?? config.diff?.baseline_ref ?? DEFAULT_DIFF_CONFIG.baseline_ref;
2795
+ const headRef = options.head ?? "HEAD";
2796
+ const configPath = join5(configDir, "spec.config.yaml");
2797
+ const result = await diffBetweenRefs(configPath, baseRef, headRef);
2798
+ if (options.spec) {
2799
+ result.diffs = result.diffs.filter((d) => d.specId === options.spec);
2800
+ result.impact = result.impact.filter((i) => i.changedSpec === options.spec);
2801
+ }
2802
+ return result;
2803
+ }
2804
+ var diff_default = defineCommand4({
2805
+ meta: { name: "diff", description: "Show spec changes and downstream impact" },
2806
+ args: {
2807
+ base: { type: "string", description: "Base git ref (default: from config or 'main')" },
2808
+ head: { type: "string", description: "Head git ref (default: HEAD)" },
2809
+ spec: { type: "string", description: "Scope to a single spec ID" },
2810
+ format: {
2811
+ type: "string",
2812
+ description: "Output format: pretty, json",
2813
+ default: "pretty"
2814
+ }
2815
+ },
2816
+ async run({ args }) {
2817
+ try {
2818
+ const result = await runDiff({
2819
+ base: args.base,
2820
+ head: args.head,
2821
+ spec: args.spec,
2822
+ format: args.format
2823
+ });
2824
+ if (args.format === "json") {
2825
+ console.log(JSON.stringify(result, null, 2));
2826
+ return;
2827
+ }
2828
+ if (result.diffs.length === 0 && result.added.length === 0 && result.removed.length === 0) {
2829
+ console.log(" \u2713 No spec changes detected.");
2830
+ return;
2831
+ }
2832
+ console.log(result.summary);
2833
+ console.log();
2834
+ for (const diff2 of result.diffs) {
2835
+ console.log(` ${diff2.specId}:`);
2836
+ for (const fc of diff2.frontmatter) {
2837
+ const detail = fc.before !== void 0 || fc.after !== void 0 ? ` (${String(fc.before)} \u2192 ${String(fc.after)})` : "";
2838
+ console.log(` ${fc.type}: ${fc.field}${detail}`);
2839
+ }
2840
+ for (const sc of diff2.sections) {
2841
+ console.log(` ${sc.type}: ${sc.heading}`);
2842
+ }
2843
+ }
2844
+ if (result.added.length > 0) {
2845
+ console.log(`
2846
+ Added: ${result.added.join(", ")}`);
2847
+ }
2848
+ if (result.removed.length > 0) {
2849
+ console.log(`
2850
+ Removed: ${result.removed.join(", ")}`);
2851
+ }
2852
+ if (result.impact.length > 0) {
2853
+ console.log("\n Downstream Impact:");
2854
+ for (const impact of result.impact) {
2855
+ for (const d of impact.downstream) {
2856
+ console.log(
2857
+ ` ${d.specId} \u2014 staleness: ${d.staleness.toFixed(2)} \u2014 ${d.reason}`
2858
+ );
2859
+ }
2860
+ }
2861
+ }
2862
+ } catch (err) {
2863
+ if (err instanceof DiffError) {
2864
+ console.error(`
2865
+ \u2717 ${err.message}
2866
+ `);
2867
+ process.exit(1);
2868
+ }
2869
+ throw err;
2870
+ }
2871
+ }
2872
+ });
2873
+
2874
+ // src/commands/status.ts
2875
+ import { defineCommand as defineCommand5 } from "citty";
2876
+ async function runStatus(_options = {}) {
2877
+ const configDir = process.cwd();
2878
+ const config = await loadConfig(void 0, configDir);
2879
+ const specs = [];
2880
+ for (const [, entry] of Object.entries(config.specs)) {
2881
+ const paths = await resolveGlob(entry.path, configDir);
2882
+ for (const p of paths) {
2883
+ const spec = await parseSpec(p);
2884
+ specs.push({ spec, entry });
2885
+ }
2886
+ }
2887
+ const byStatus = {};
2888
+ for (const { spec } of specs) {
2889
+ const status = spec.frontmatter.status || "unknown";
2890
+ byStatus[status] = (byStatus[status] ?? 0) + 1;
2891
+ }
2892
+ const presetName = config.lint?.extends ?? "recommended";
2893
+ const rules = getPreset(presetName);
2894
+ let graph;
2895
+ let graphError;
2896
+ try {
2897
+ graph = buildGraph(config);
2898
+ } catch (err) {
2899
+ graphError = err.message;
2900
+ }
2901
+ const engine = createLintEngine({ rules, config, graph });
2902
+ const lintResults = engine.lint(specs.map((s) => s.spec));
2903
+ if (graphError) {
2904
+ lintResults.diagnostics.push({
2905
+ ruleId: "structure/no-circular-deps",
2906
+ severity: "error",
2907
+ message: graphError,
2908
+ filePath: "spec.config.yaml"
2909
+ });
2910
+ lintResults.hasErrors = true;
2911
+ }
2912
+ const errors = lintResults.diagnostics.filter((d) => d.severity === "error").length;
2913
+ const warnings = lintResults.diagnostics.filter((d) => d.severity === "warn").length;
2914
+ const thresholdDays = config.diff?.staleness_threshold_days ?? DEFAULT_DIFF_CONFIG.staleness_threshold_days;
2915
+ const now = Date.now();
2916
+ const staleSpecs = [];
2917
+ for (const { spec, entry } of specs) {
2918
+ const dateStr = spec.frontmatter.updated || spec.frontmatter.created;
2919
+ if (dateStr) {
2920
+ const daysSinceUpdate = Math.floor(
2921
+ (now - new Date(dateStr).getTime()) / (1e3 * 60 * 60 * 24)
2922
+ );
2923
+ if (daysSinceUpdate > thresholdDays) {
2924
+ staleSpecs.push({
2925
+ specId: spec.frontmatter.id,
2926
+ daysSinceUpdate,
2927
+ owner: entry.owner
2928
+ });
2929
+ }
2930
+ }
2931
+ }
2932
+ const integrityIssues = [];
2933
+ if (graphError) {
2934
+ integrityIssues.push(graphError);
2935
+ }
2936
+ const refErrors = lintResults.diagnostics.filter(
2937
+ (d) => d.ruleId === "structure/valid-references"
2938
+ );
2939
+ for (const d of refErrors) {
2940
+ integrityIssues.push(d.message);
2941
+ }
2942
+ let verdict = "healthy";
2943
+ if (errors > 0) verdict = "errors";
2944
+ else if (warnings > 0 || staleSpecs.length > 0) verdict = "warnings";
2945
+ return {
2946
+ project: config.project?.name ?? "unknown",
2947
+ specCount: specs.length,
2948
+ byStatus,
2949
+ lintHealth: { errors, warnings, passing: specs.length - errors },
2950
+ staleSpecs,
2951
+ integrityIssues,
2952
+ verdict
2953
+ };
2954
+ }
2955
+ var status_default = defineCommand5({
2956
+ meta: { name: "status", description: "Show spec suite health overview" },
2957
+ args: {
2958
+ format: {
2959
+ type: "string",
2960
+ description: "Output format: pretty, json, github",
2961
+ default: "pretty"
2962
+ }
2963
+ },
2964
+ async run({ args }) {
2965
+ const result = await runStatus({ format: args.format });
2966
+ if (args.format === "json") {
2967
+ console.log(JSON.stringify(result, null, 2));
2968
+ return;
2969
+ }
2970
+ if (args.format === "github") {
2971
+ for (const s of result.staleSpecs) {
2972
+ console.log(
2973
+ `::warning::Spec "${s.specId}" is stale (${s.daysSinceUpdate} days since update)`
2974
+ );
2975
+ }
2976
+ for (const issue of result.integrityIssues) {
2977
+ console.log(`::error::${issue}`);
2978
+ }
2979
+ return;
2980
+ }
2981
+ const icon = result.verdict === "healthy" ? "\u2713" : result.verdict === "warnings" ? "\u26A0" : "\u2717";
2982
+ console.log(`
2983
+ ${icon} ${result.project} \u2014 ${result.verdict}`);
2984
+ console.log(
2985
+ ` ${result.specCount} specs: ${Object.entries(result.byStatus).map(([k, v]) => `${v} ${k}`).join(", ")}`
2986
+ );
2987
+ console.log(` Lint: ${result.lintHealth.errors} errors, ${result.lintHealth.warnings} warnings`);
2988
+ if (result.staleSpecs.length > 0) {
2989
+ console.log(
2990
+ ` Stale: ${result.staleSpecs.map((s) => `${s.specId} (${s.daysSinceUpdate}d)`).join(", ")}`
2991
+ );
2992
+ }
2993
+ if (result.integrityIssues.length > 0) {
2994
+ console.log(` Issues: ${result.integrityIssues.join("; ")}`);
2995
+ }
2996
+ console.log();
2997
+ }
2998
+ });
2999
+
3000
+ // src/commands/changelog.ts
3001
+ import { defineCommand as defineCommand6 } from "citty";
3002
+ import { join as join6 } from "path";
3003
+ async function runChangelog(options) {
3004
+ const configDir = process.cwd();
3005
+ const config = await loadConfig(void 0, configDir);
3006
+ const fromRef = options.from ?? config.diff?.baseline_ref ?? DEFAULT_DIFF_CONFIG.baseline_ref;
3007
+ const toRef = options.to ?? "HEAD";
3008
+ const configPath = join6(configDir, "spec.config.yaml");
3009
+ const result = await diffBetweenRefs(configPath, fromRef, toRef);
3010
+ const lines = [];
3011
+ lines.push(`## Spec Changes (${fromRef}..${toRef})
3012
+ `);
3013
+ if (result.diffs.length > 0) {
3014
+ lines.push("### Modified");
3015
+ for (const diff2 of result.diffs) {
3016
+ const sections = diff2.sections.map((s) => s.heading).join(", ");
3017
+ const versionChange = diff2.frontmatter.find((f) => f.field === "version");
3018
+ const versionStr = versionChange ? ` (${String(versionChange.before)} \u2192 ${String(versionChange.after)})` : "";
3019
+ lines.push(`- **${diff2.specId}**${versionStr} \u2014 ${sections || "frontmatter only"}`);
3020
+ }
3021
+ lines.push("");
3022
+ }
3023
+ if (result.added.length > 0) {
3024
+ lines.push("### Added");
3025
+ for (const id of result.added) {
3026
+ lines.push(`- **${id}**`);
3027
+ }
3028
+ lines.push("");
3029
+ }
3030
+ if (result.removed.length > 0) {
3031
+ lines.push("### Removed");
3032
+ for (const id of result.removed) {
3033
+ lines.push(`- **${id}**`);
3034
+ }
3035
+ lines.push("");
3036
+ }
3037
+ const allDownstream = result.impact.flatMap((i) => i.downstream);
3038
+ if (allDownstream.length > 0) {
3039
+ lines.push("### Downstream Impact");
3040
+ for (const d of allDownstream) {
3041
+ lines.push(`- ${d.specId} may be stale (${d.reason})`);
3042
+ }
3043
+ lines.push("");
3044
+ }
3045
+ if (result.diffs.length === 0 && result.added.length === 0 && result.removed.length === 0) {
3046
+ lines.push("No spec changes detected.\n");
3047
+ }
3048
+ return lines.join("\n");
3049
+ }
3050
+ var changelog_default = defineCommand6({
3051
+ meta: { name: "changelog", description: "Generate changelog of spec changes between git refs" },
3052
+ args: {
3053
+ from: { type: "string", description: "Start git ref (default: from config or 'main')" },
3054
+ to: { type: "string", description: "End git ref (default: HEAD)" }
3055
+ },
3056
+ async run({ args }) {
3057
+ try {
3058
+ const output = await runChangelog(args);
3059
+ console.log(output);
3060
+ } catch (err) {
3061
+ if (err instanceof DiffError) {
3062
+ console.error(`
3063
+ \u2717 ${err.message}
3064
+ `);
3065
+ process.exit(1);
3066
+ }
3067
+ throw err;
3068
+ }
3069
+ }
3070
+ });
3071
+
3072
+ // src/commands/explain.ts
3073
+ import { defineCommand as defineCommand7 } from "citty";
3074
+ async function runExplain(_options = {}) {
3075
+ const configDir = process.cwd();
3076
+ const config = await loadConfig(void 0, configDir);
3077
+ const specs = [];
3078
+ for (const [, entry] of Object.entries(config.specs)) {
3079
+ const paths = await resolveGlob(entry.path, configDir);
3080
+ for (const p of paths) {
3081
+ specs.push(await parseSpec(p));
3082
+ }
3083
+ }
3084
+ const byType = {};
3085
+ const byStatus = {};
3086
+ for (const spec of specs) {
3087
+ const type = spec.frontmatter.type || "unknown";
3088
+ const status = spec.frontmatter.status || "unknown";
3089
+ byType[type] = (byType[type] ?? 0) + 1;
3090
+ byStatus[status] = (byStatus[status] ?? 0) + 1;
3091
+ }
3092
+ const specSummaries = specs.map((spec) => {
3093
+ const firstSection = spec.parsedSections[0];
3094
+ const firstLine = firstSection?.content?.split("\n").find((l) => l.trim().length > 0)?.trim() ?? "";
3095
+ const truncated = firstLine.slice(0, 120) + (firstLine.length > 120 ? "..." : "");
3096
+ return {
3097
+ id: spec.frontmatter.id,
3098
+ type: spec.frontmatter.type,
3099
+ title: spec.frontmatter.title,
3100
+ status: spec.frontmatter.status,
3101
+ firstLine: truncated
3102
+ };
3103
+ });
3104
+ const graph = buildGraph(config);
3105
+ const graphLines = [];
3106
+ for (const node of graph.nodes) {
3107
+ const downstream = graph.edges.filter((e) => e.from === node).map((e) => e.to);
3108
+ if (downstream.length > 0) {
3109
+ graphLines.push(`${node} \u2192 ${downstream.join(", ")}`);
3110
+ } else {
3111
+ graphLines.push(node);
3112
+ }
3113
+ }
3114
+ return {
3115
+ project: config.project?.name ?? "unknown",
3116
+ description: config.project?.description,
3117
+ specCount: specs.length,
3118
+ byType,
3119
+ byStatus,
3120
+ specs: specSummaries,
3121
+ graph: graphLines
3122
+ };
3123
+ }
3124
+ var explain_default = defineCommand7({
3125
+ meta: { name: "explain", description: "Explain the spec suite for onboarding" },
3126
+ args: {
3127
+ format: { type: "string", description: "Output format: pretty, json", default: "pretty" }
3128
+ },
3129
+ async run({ args }) {
3130
+ const result = await runExplain({ format: args.format });
3131
+ if (args.format === "json") {
3132
+ console.log(JSON.stringify(result, null, 2));
3133
+ return;
3134
+ }
3135
+ console.log(`
3136
+ ${result.project}`);
3137
+ if (result.description) {
3138
+ console.log(` ${result.description}`);
3139
+ }
3140
+ console.log(
3141
+ `
3142
+ ${result.specCount} specs: ${Object.entries(result.byType).map(([k, v]) => `${v} ${k}`).join(", ")}`
3143
+ );
3144
+ console.log(
3145
+ ` Status: ${Object.entries(result.byStatus).map(([k, v]) => `${v} ${k}`).join(", ")}`
3146
+ );
3147
+ console.log("\n Specs:");
3148
+ for (const spec of result.specs) {
3149
+ console.log(` ${spec.id} (${spec.type}, ${spec.status}) \u2014 ${spec.title}`);
3150
+ if (spec.firstLine) {
3151
+ console.log(` ${spec.firstLine}`);
3152
+ }
3153
+ }
3154
+ console.log("\n Dependencies:");
3155
+ for (const line of result.graph) {
3156
+ console.log(` ${line}`);
3157
+ }
3158
+ console.log();
3159
+ }
3160
+ });
1583
3161
  export {
3162
+ runChangelog,
3163
+ runDiff,
3164
+ runExplain,
1584
3165
  runLint,
1585
3166
  runPack,
3167
+ runStatus,
1586
3168
  scaffoldProject
1587
3169
  };
1588
3170
  //# sourceMappingURL=index.js.map