specdx 0.4.0-alpha.22 → 0.4.0-alpha.24

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/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../node_modules/.pnpm/picomatch@4.0.3/node_modules/picomatch/lib/constants.js","../../../node_modules/.pnpm/picomatch@4.0.3/node_modules/picomatch/lib/utils.js","../../../node_modules/.pnpm/picomatch@4.0.3/node_modules/picomatch/lib/scan.js","../../../node_modules/.pnpm/picomatch@4.0.3/node_modules/picomatch/lib/parse.js","../../../node_modules/.pnpm/picomatch@4.0.3/node_modules/picomatch/lib/picomatch.js","../../../node_modules/.pnpm/picomatch@4.0.3/node_modules/picomatch/index.js","../src/commands/core/init.ts","../../schema/src/types.ts","../../schema/src/sections.ts","../../schema/src/validator.ts","../../schema/dist/schemas/base-spec.json","../../schema/dist/schemas/config.json","../../schema/dist/schemas/prd.json","../../schema/dist/schemas/technical-design.json","../../schema/dist/schemas/user-story.json","../../schema/dist/schemas/test-plan.json","../../schema/dist/schemas/adr.json","../../schema/dist/schemas/api-contract.json","../../schema/dist/schemas/epic.json","../../schema/dist/schemas/quick-spec.json","../../schema/dist/schemas/project-context.json","../src/commands/core/lint.ts","../../core/src/config.ts","../../core/src/parser.ts","../../core/src/tokens.ts","../../core/src/graph.ts","../../core/src/relations.ts","../../core/src/glob.ts","../../core/src/logger.ts","../../core/src/preset.ts","../../lint/src/engine.ts","../../lint/src/rules/valid-frontmatter.ts","../../lint/src/rules/required-sections.ts","../../lint/src/rules/valid-references.ts","../../lint/src/rules/no-circular-deps.ts","../../lint/src/rules/story-coverage.ts","../../lint/src/rules/staleness-check.ts","../../lint/src/rules/no-vague-language.ts","../../lint/src/rules/single-project-context.ts","../../lint/src/rules/terminology.ts","../../lint/src/rules/edge-case-coverage.ts","../../lint/src/rules/naming-conventions.ts","../../lint/src/rules/threat-coverage.ts","../../lint/src/rules/ambiguity-score-ai.ts","../../lint/src/rules/no-placeholder-sections.ts","../../lint/src/rules/id-matches-config-key.ts","../../lint/src/rules/index.ts","../../lint/src/presets.ts","../../lint/src/custom-rule-loader.ts","../src/shared-args.ts","../src/output.ts","../src/formatters/pretty.ts","../src/formatters/json.ts","../src/formatters/github.ts","../src/commands/core/pack.ts","../../pack/src/resolver.ts","../../pack/src/compressor.ts","../../pack/src/allocator.ts","../../pack/src/formatters/xml.ts","../../pack/src/formatters/markdown.ts","../../pack/src/formatters/json.ts","../../pack/src/index.ts","../src/commands/core/diff.ts","../../diff/src/types.ts","../../../node_modules/.pnpm/diff@7.0.0/node_modules/diff/lib/index.mjs","../../diff/src/diff-specs.ts","../../diff/src/impact.ts","../../diff/src/cross-refs.ts","../../diff/src/git.ts","../src/formatters/changelog.ts","../src/commands/core/status.ts","../src/commands/core/validate.ts"],"sourcesContent":["'use strict';\n\nconst WIN_SLASH = '\\\\\\\\/';\nconst WIN_NO_SLASH = `[^${WIN_SLASH}]`;\n\n/**\n * Posix glob regex\n */\n\nconst DOT_LITERAL = '\\\\.';\nconst PLUS_LITERAL = '\\\\+';\nconst QMARK_LITERAL = '\\\\?';\nconst SLASH_LITERAL = '\\\\/';\nconst ONE_CHAR = '(?=.)';\nconst QMARK = '[^/]';\nconst END_ANCHOR = `(?:${SLASH_LITERAL}|$)`;\nconst START_ANCHOR = `(?:^|${SLASH_LITERAL})`;\nconst DOTS_SLASH = `${DOT_LITERAL}{1,2}${END_ANCHOR}`;\nconst NO_DOT = `(?!${DOT_LITERAL})`;\nconst NO_DOTS = `(?!${START_ANCHOR}${DOTS_SLASH})`;\nconst NO_DOT_SLASH = `(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`;\nconst NO_DOTS_SLASH = `(?!${DOTS_SLASH})`;\nconst QMARK_NO_DOT = `[^.${SLASH_LITERAL}]`;\nconst STAR = `${QMARK}*?`;\nconst SEP = '/';\n\nconst POSIX_CHARS = {\n DOT_LITERAL,\n PLUS_LITERAL,\n QMARK_LITERAL,\n SLASH_LITERAL,\n ONE_CHAR,\n QMARK,\n END_ANCHOR,\n DOTS_SLASH,\n NO_DOT,\n NO_DOTS,\n NO_DOT_SLASH,\n NO_DOTS_SLASH,\n QMARK_NO_DOT,\n STAR,\n START_ANCHOR,\n SEP\n};\n\n/**\n * Windows glob regex\n */\n\nconst WINDOWS_CHARS = {\n ...POSIX_CHARS,\n\n SLASH_LITERAL: `[${WIN_SLASH}]`,\n QMARK: WIN_NO_SLASH,\n STAR: `${WIN_NO_SLASH}*?`,\n DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`,\n NO_DOT: `(?!${DOT_LITERAL})`,\n NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,\n NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`,\n NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,\n QMARK_NO_DOT: `[^.${WIN_SLASH}]`,\n START_ANCHOR: `(?:^|[${WIN_SLASH}])`,\n END_ANCHOR: `(?:[${WIN_SLASH}]|$)`,\n SEP: '\\\\'\n};\n\n/**\n * POSIX Bracket Regex\n */\n\nconst POSIX_REGEX_SOURCE = {\n alnum: 'a-zA-Z0-9',\n alpha: 'a-zA-Z',\n ascii: '\\\\x00-\\\\x7F',\n blank: ' \\\\t',\n cntrl: '\\\\x00-\\\\x1F\\\\x7F',\n digit: '0-9',\n graph: '\\\\x21-\\\\x7E',\n lower: 'a-z',\n print: '\\\\x20-\\\\x7E ',\n punct: '\\\\-!\"#$%&\\'()\\\\*+,./:;<=>?@[\\\\]^_`{|}~',\n space: ' \\\\t\\\\r\\\\n\\\\v\\\\f',\n upper: 'A-Z',\n word: 'A-Za-z0-9_',\n xdigit: 'A-Fa-f0-9'\n};\n\nmodule.exports = {\n MAX_LENGTH: 1024 * 64,\n POSIX_REGEX_SOURCE,\n\n // regular expressions\n REGEX_BACKSLASH: /\\\\(?![*+?^${}(|)[\\]])/g,\n REGEX_NON_SPECIAL_CHARS: /^[^@![\\].,$*+?^{}()|\\\\/]+/,\n REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\\]]/,\n REGEX_SPECIAL_CHARS_BACKREF: /(\\\\?)((\\W)(\\3*))/g,\n REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\\]])/g,\n REGEX_REMOVE_BACKSLASH: /(?:\\[.*?[^\\\\]\\]|\\\\(?=.))/g,\n\n // Replace globs with equivalent patterns to reduce parsing time.\n REPLACEMENTS: {\n __proto__: null,\n '***': '*',\n '**/**': '**',\n '**/**/**': '**'\n },\n\n // Digits\n CHAR_0: 48, /* 0 */\n CHAR_9: 57, /* 9 */\n\n // Alphabet chars.\n CHAR_UPPERCASE_A: 65, /* A */\n CHAR_LOWERCASE_A: 97, /* a */\n CHAR_UPPERCASE_Z: 90, /* Z */\n CHAR_LOWERCASE_Z: 122, /* z */\n\n CHAR_LEFT_PARENTHESES: 40, /* ( */\n CHAR_RIGHT_PARENTHESES: 41, /* ) */\n\n CHAR_ASTERISK: 42, /* * */\n\n // Non-alphabetic chars.\n CHAR_AMPERSAND: 38, /* & */\n CHAR_AT: 64, /* @ */\n CHAR_BACKWARD_SLASH: 92, /* \\ */\n CHAR_CARRIAGE_RETURN: 13, /* \\r */\n CHAR_CIRCUMFLEX_ACCENT: 94, /* ^ */\n CHAR_COLON: 58, /* : */\n CHAR_COMMA: 44, /* , */\n CHAR_DOT: 46, /* . */\n CHAR_DOUBLE_QUOTE: 34, /* \" */\n CHAR_EQUAL: 61, /* = */\n CHAR_EXCLAMATION_MARK: 33, /* ! */\n CHAR_FORM_FEED: 12, /* \\f */\n CHAR_FORWARD_SLASH: 47, /* / */\n CHAR_GRAVE_ACCENT: 96, /* ` */\n CHAR_HASH: 35, /* # */\n CHAR_HYPHEN_MINUS: 45, /* - */\n CHAR_LEFT_ANGLE_BRACKET: 60, /* < */\n CHAR_LEFT_CURLY_BRACE: 123, /* { */\n CHAR_LEFT_SQUARE_BRACKET: 91, /* [ */\n CHAR_LINE_FEED: 10, /* \\n */\n CHAR_NO_BREAK_SPACE: 160, /* \\u00A0 */\n CHAR_PERCENT: 37, /* % */\n CHAR_PLUS: 43, /* + */\n CHAR_QUESTION_MARK: 63, /* ? */\n CHAR_RIGHT_ANGLE_BRACKET: 62, /* > */\n CHAR_RIGHT_CURLY_BRACE: 125, /* } */\n CHAR_RIGHT_SQUARE_BRACKET: 93, /* ] */\n CHAR_SEMICOLON: 59, /* ; */\n CHAR_SINGLE_QUOTE: 39, /* ' */\n CHAR_SPACE: 32, /* */\n CHAR_TAB: 9, /* \\t */\n CHAR_UNDERSCORE: 95, /* _ */\n CHAR_VERTICAL_LINE: 124, /* | */\n CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279, /* \\uFEFF */\n\n /**\n * Create EXTGLOB_CHARS\n */\n\n extglobChars(chars) {\n return {\n '!': { type: 'negate', open: '(?:(?!(?:', close: `))${chars.STAR})` },\n '?': { type: 'qmark', open: '(?:', close: ')?' },\n '+': { type: 'plus', open: '(?:', close: ')+' },\n '*': { type: 'star', open: '(?:', close: ')*' },\n '@': { type: 'at', open: '(?:', close: ')' }\n };\n },\n\n /**\n * Create GLOB_CHARS\n */\n\n globChars(win32) {\n return win32 === true ? WINDOWS_CHARS : POSIX_CHARS;\n }\n};\n","/*global navigator*/\n'use strict';\n\nconst {\n REGEX_BACKSLASH,\n REGEX_REMOVE_BACKSLASH,\n REGEX_SPECIAL_CHARS,\n REGEX_SPECIAL_CHARS_GLOBAL\n} = require('./constants');\n\nexports.isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val);\nexports.hasRegexChars = str => REGEX_SPECIAL_CHARS.test(str);\nexports.isRegexChar = str => str.length === 1 && exports.hasRegexChars(str);\nexports.escapeRegex = str => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, '\\\\$1');\nexports.toPosixSlashes = str => str.replace(REGEX_BACKSLASH, '/');\n\nexports.isWindows = () => {\n if (typeof navigator !== 'undefined' && navigator.platform) {\n const platform = navigator.platform.toLowerCase();\n return platform === 'win32' || platform === 'windows';\n }\n\n if (typeof process !== 'undefined' && process.platform) {\n return process.platform === 'win32';\n }\n\n return false;\n};\n\nexports.removeBackslashes = str => {\n return str.replace(REGEX_REMOVE_BACKSLASH, match => {\n return match === '\\\\' ? '' : match;\n });\n};\n\nexports.escapeLast = (input, char, lastIdx) => {\n const idx = input.lastIndexOf(char, lastIdx);\n if (idx === -1) return input;\n if (input[idx - 1] === '\\\\') return exports.escapeLast(input, char, idx - 1);\n return `${input.slice(0, idx)}\\\\${input.slice(idx)}`;\n};\n\nexports.removePrefix = (input, state = {}) => {\n let output = input;\n if (output.startsWith('./')) {\n output = output.slice(2);\n state.prefix = './';\n }\n return output;\n};\n\nexports.wrapOutput = (input, state = {}, options = {}) => {\n const prepend = options.contains ? '' : '^';\n const append = options.contains ? '' : '$';\n\n let output = `${prepend}(?:${input})${append}`;\n if (state.negated === true) {\n output = `(?:^(?!${output}).*$)`;\n }\n return output;\n};\n\nexports.basename = (path, { windows } = {}) => {\n const segs = path.split(windows ? /[\\\\/]/ : '/');\n const last = segs[segs.length - 1];\n\n if (last === '') {\n return segs[segs.length - 2];\n }\n\n return last;\n};\n","'use strict';\n\nconst utils = require('./utils');\nconst {\n CHAR_ASTERISK, /* * */\n CHAR_AT, /* @ */\n CHAR_BACKWARD_SLASH, /* \\ */\n CHAR_COMMA, /* , */\n CHAR_DOT, /* . */\n CHAR_EXCLAMATION_MARK, /* ! */\n CHAR_FORWARD_SLASH, /* / */\n CHAR_LEFT_CURLY_BRACE, /* { */\n CHAR_LEFT_PARENTHESES, /* ( */\n CHAR_LEFT_SQUARE_BRACKET, /* [ */\n CHAR_PLUS, /* + */\n CHAR_QUESTION_MARK, /* ? */\n CHAR_RIGHT_CURLY_BRACE, /* } */\n CHAR_RIGHT_PARENTHESES, /* ) */\n CHAR_RIGHT_SQUARE_BRACKET /* ] */\n} = require('./constants');\n\nconst isPathSeparator = code => {\n return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH;\n};\n\nconst depth = token => {\n if (token.isPrefix !== true) {\n token.depth = token.isGlobstar ? Infinity : 1;\n }\n};\n\n/**\n * Quickly scans a glob pattern and returns an object with a handful of\n * useful properties, like `isGlob`, `path` (the leading non-glob, if it exists),\n * `glob` (the actual pattern), `negated` (true if the path starts with `!` but not\n * with `!(`) and `negatedExtglob` (true if the path starts with `!(`).\n *\n * ```js\n * const pm = require('picomatch');\n * console.log(pm.scan('foo/bar/*.js'));\n * { isGlob: true, input: 'foo/bar/*.js', base: 'foo/bar', glob: '*.js' }\n * ```\n * @param {String} `str`\n * @param {Object} `options`\n * @return {Object} Returns an object with tokens and regex source string.\n * @api public\n */\n\nconst scan = (input, options) => {\n const opts = options || {};\n\n const length = input.length - 1;\n const scanToEnd = opts.parts === true || opts.scanToEnd === true;\n const slashes = [];\n const tokens = [];\n const parts = [];\n\n let str = input;\n let index = -1;\n let start = 0;\n let lastIndex = 0;\n let isBrace = false;\n let isBracket = false;\n let isGlob = false;\n let isExtglob = false;\n let isGlobstar = false;\n let braceEscaped = false;\n let backslashes = false;\n let negated = false;\n let negatedExtglob = false;\n let finished = false;\n let braces = 0;\n let prev;\n let code;\n let token = { value: '', depth: 0, isGlob: false };\n\n const eos = () => index >= length;\n const peek = () => str.charCodeAt(index + 1);\n const advance = () => {\n prev = code;\n return str.charCodeAt(++index);\n };\n\n while (index < length) {\n code = advance();\n let next;\n\n if (code === CHAR_BACKWARD_SLASH) {\n backslashes = token.backslashes = true;\n code = advance();\n\n if (code === CHAR_LEFT_CURLY_BRACE) {\n braceEscaped = true;\n }\n continue;\n }\n\n if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE) {\n braces++;\n\n while (eos() !== true && (code = advance())) {\n if (code === CHAR_BACKWARD_SLASH) {\n backslashes = token.backslashes = true;\n advance();\n continue;\n }\n\n if (code === CHAR_LEFT_CURLY_BRACE) {\n braces++;\n continue;\n }\n\n if (braceEscaped !== true && code === CHAR_DOT && (code = advance()) === CHAR_DOT) {\n isBrace = token.isBrace = true;\n isGlob = token.isGlob = true;\n finished = true;\n\n if (scanToEnd === true) {\n continue;\n }\n\n break;\n }\n\n if (braceEscaped !== true && code === CHAR_COMMA) {\n isBrace = token.isBrace = true;\n isGlob = token.isGlob = true;\n finished = true;\n\n if (scanToEnd === true) {\n continue;\n }\n\n break;\n }\n\n if (code === CHAR_RIGHT_CURLY_BRACE) {\n braces--;\n\n if (braces === 0) {\n braceEscaped = false;\n isBrace = token.isBrace = true;\n finished = true;\n break;\n }\n }\n }\n\n if (scanToEnd === true) {\n continue;\n }\n\n break;\n }\n\n if (code === CHAR_FORWARD_SLASH) {\n slashes.push(index);\n tokens.push(token);\n token = { value: '', depth: 0, isGlob: false };\n\n if (finished === true) continue;\n if (prev === CHAR_DOT && index === (start + 1)) {\n start += 2;\n continue;\n }\n\n lastIndex = index + 1;\n continue;\n }\n\n if (opts.noext !== true) {\n const isExtglobChar = code === CHAR_PLUS\n || code === CHAR_AT\n || code === CHAR_ASTERISK\n || code === CHAR_QUESTION_MARK\n || code === CHAR_EXCLAMATION_MARK;\n\n if (isExtglobChar === true && peek() === CHAR_LEFT_PARENTHESES) {\n isGlob = token.isGlob = true;\n isExtglob = token.isExtglob = true;\n finished = true;\n if (code === CHAR_EXCLAMATION_MARK && index === start) {\n negatedExtglob = true;\n }\n\n if (scanToEnd === true) {\n while (eos() !== true && (code = advance())) {\n if (code === CHAR_BACKWARD_SLASH) {\n backslashes = token.backslashes = true;\n code = advance();\n continue;\n }\n\n if (code === CHAR_RIGHT_PARENTHESES) {\n isGlob = token.isGlob = true;\n finished = true;\n break;\n }\n }\n continue;\n }\n break;\n }\n }\n\n if (code === CHAR_ASTERISK) {\n if (prev === CHAR_ASTERISK) isGlobstar = token.isGlobstar = true;\n isGlob = token.isGlob = true;\n finished = true;\n\n if (scanToEnd === true) {\n continue;\n }\n break;\n }\n\n if (code === CHAR_QUESTION_MARK) {\n isGlob = token.isGlob = true;\n finished = true;\n\n if (scanToEnd === true) {\n continue;\n }\n break;\n }\n\n if (code === CHAR_LEFT_SQUARE_BRACKET) {\n while (eos() !== true && (next = advance())) {\n if (next === CHAR_BACKWARD_SLASH) {\n backslashes = token.backslashes = true;\n advance();\n continue;\n }\n\n if (next === CHAR_RIGHT_SQUARE_BRACKET) {\n isBracket = token.isBracket = true;\n isGlob = token.isGlob = true;\n finished = true;\n break;\n }\n }\n\n if (scanToEnd === true) {\n continue;\n }\n\n break;\n }\n\n if (opts.nonegate !== true && code === CHAR_EXCLAMATION_MARK && index === start) {\n negated = token.negated = true;\n start++;\n continue;\n }\n\n if (opts.noparen !== true && code === CHAR_LEFT_PARENTHESES) {\n isGlob = token.isGlob = true;\n\n if (scanToEnd === true) {\n while (eos() !== true && (code = advance())) {\n if (code === CHAR_LEFT_PARENTHESES) {\n backslashes = token.backslashes = true;\n code = advance();\n continue;\n }\n\n if (code === CHAR_RIGHT_PARENTHESES) {\n finished = true;\n break;\n }\n }\n continue;\n }\n break;\n }\n\n if (isGlob === true) {\n finished = true;\n\n if (scanToEnd === true) {\n continue;\n }\n\n break;\n }\n }\n\n if (opts.noext === true) {\n isExtglob = false;\n isGlob = false;\n }\n\n let base = str;\n let prefix = '';\n let glob = '';\n\n if (start > 0) {\n prefix = str.slice(0, start);\n str = str.slice(start);\n lastIndex -= start;\n }\n\n if (base && isGlob === true && lastIndex > 0) {\n base = str.slice(0, lastIndex);\n glob = str.slice(lastIndex);\n } else if (isGlob === true) {\n base = '';\n glob = str;\n } else {\n base = str;\n }\n\n if (base && base !== '' && base !== '/' && base !== str) {\n if (isPathSeparator(base.charCodeAt(base.length - 1))) {\n base = base.slice(0, -1);\n }\n }\n\n if (opts.unescape === true) {\n if (glob) glob = utils.removeBackslashes(glob);\n\n if (base && backslashes === true) {\n base = utils.removeBackslashes(base);\n }\n }\n\n const state = {\n prefix,\n input,\n start,\n base,\n glob,\n isBrace,\n isBracket,\n isGlob,\n isExtglob,\n isGlobstar,\n negated,\n negatedExtglob\n };\n\n if (opts.tokens === true) {\n state.maxDepth = 0;\n if (!isPathSeparator(code)) {\n tokens.push(token);\n }\n state.tokens = tokens;\n }\n\n if (opts.parts === true || opts.tokens === true) {\n let prevIndex;\n\n for (let idx = 0; idx < slashes.length; idx++) {\n const n = prevIndex ? prevIndex + 1 : start;\n const i = slashes[idx];\n const value = input.slice(n, i);\n if (opts.tokens) {\n if (idx === 0 && start !== 0) {\n tokens[idx].isPrefix = true;\n tokens[idx].value = prefix;\n } else {\n tokens[idx].value = value;\n }\n depth(tokens[idx]);\n state.maxDepth += tokens[idx].depth;\n }\n if (idx !== 0 || value !== '') {\n parts.push(value);\n }\n prevIndex = i;\n }\n\n if (prevIndex && prevIndex + 1 < input.length) {\n const value = input.slice(prevIndex + 1);\n parts.push(value);\n\n if (opts.tokens) {\n tokens[tokens.length - 1].value = value;\n depth(tokens[tokens.length - 1]);\n state.maxDepth += tokens[tokens.length - 1].depth;\n }\n }\n\n state.slashes = slashes;\n state.parts = parts;\n }\n\n return state;\n};\n\nmodule.exports = scan;\n","'use strict';\n\nconst constants = require('./constants');\nconst utils = require('./utils');\n\n/**\n * Constants\n */\n\nconst {\n MAX_LENGTH,\n POSIX_REGEX_SOURCE,\n REGEX_NON_SPECIAL_CHARS,\n REGEX_SPECIAL_CHARS_BACKREF,\n REPLACEMENTS\n} = constants;\n\n/**\n * Helpers\n */\n\nconst expandRange = (args, options) => {\n if (typeof options.expandRange === 'function') {\n return options.expandRange(...args, options);\n }\n\n args.sort();\n const value = `[${args.join('-')}]`;\n\n try {\n /* eslint-disable-next-line no-new */\n new RegExp(value);\n } catch (ex) {\n return args.map(v => utils.escapeRegex(v)).join('..');\n }\n\n return value;\n};\n\n/**\n * Create the message for a syntax error\n */\n\nconst syntaxError = (type, char) => {\n return `Missing ${type}: \"${char}\" - use \"\\\\\\\\${char}\" to match literal characters`;\n};\n\n/**\n * Parse the given input string.\n * @param {String} input\n * @param {Object} options\n * @return {Object}\n */\n\nconst parse = (input, options) => {\n if (typeof input !== 'string') {\n throw new TypeError('Expected a string');\n }\n\n input = REPLACEMENTS[input] || input;\n\n const opts = { ...options };\n const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;\n\n let len = input.length;\n if (len > max) {\n throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);\n }\n\n const bos = { type: 'bos', value: '', output: opts.prepend || '' };\n const tokens = [bos];\n\n const capture = opts.capture ? '' : '?:';\n\n // create constants based on platform, for windows or posix\n const PLATFORM_CHARS = constants.globChars(opts.windows);\n const EXTGLOB_CHARS = constants.extglobChars(PLATFORM_CHARS);\n\n const {\n DOT_LITERAL,\n PLUS_LITERAL,\n SLASH_LITERAL,\n ONE_CHAR,\n DOTS_SLASH,\n NO_DOT,\n NO_DOT_SLASH,\n NO_DOTS_SLASH,\n QMARK,\n QMARK_NO_DOT,\n STAR,\n START_ANCHOR\n } = PLATFORM_CHARS;\n\n const globstar = opts => {\n return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;\n };\n\n const nodot = opts.dot ? '' : NO_DOT;\n const qmarkNoDot = opts.dot ? QMARK : QMARK_NO_DOT;\n let star = opts.bash === true ? globstar(opts) : STAR;\n\n if (opts.capture) {\n star = `(${star})`;\n }\n\n // minimatch options support\n if (typeof opts.noext === 'boolean') {\n opts.noextglob = opts.noext;\n }\n\n const state = {\n input,\n index: -1,\n start: 0,\n dot: opts.dot === true,\n consumed: '',\n output: '',\n prefix: '',\n backtrack: false,\n negated: false,\n brackets: 0,\n braces: 0,\n parens: 0,\n quotes: 0,\n globstar: false,\n tokens\n };\n\n input = utils.removePrefix(input, state);\n len = input.length;\n\n const extglobs = [];\n const braces = [];\n const stack = [];\n let prev = bos;\n let value;\n\n /**\n * Tokenizing helpers\n */\n\n const eos = () => state.index === len - 1;\n const peek = state.peek = (n = 1) => input[state.index + n];\n const advance = state.advance = () => input[++state.index] || '';\n const remaining = () => input.slice(state.index + 1);\n const consume = (value = '', num = 0) => {\n state.consumed += value;\n state.index += num;\n };\n\n const append = token => {\n state.output += token.output != null ? token.output : token.value;\n consume(token.value);\n };\n\n const negate = () => {\n let count = 1;\n\n while (peek() === '!' && (peek(2) !== '(' || peek(3) === '?')) {\n advance();\n state.start++;\n count++;\n }\n\n if (count % 2 === 0) {\n return false;\n }\n\n state.negated = true;\n state.start++;\n return true;\n };\n\n const increment = type => {\n state[type]++;\n stack.push(type);\n };\n\n const decrement = type => {\n state[type]--;\n stack.pop();\n };\n\n /**\n * Push tokens onto the tokens array. This helper speeds up\n * tokenizing by 1) helping us avoid backtracking as much as possible,\n * and 2) helping us avoid creating extra tokens when consecutive\n * characters are plain text. This improves performance and simplifies\n * lookbehinds.\n */\n\n const push = tok => {\n if (prev.type === 'globstar') {\n const isBrace = state.braces > 0 && (tok.type === 'comma' || tok.type === 'brace');\n const isExtglob = tok.extglob === true || (extglobs.length && (tok.type === 'pipe' || tok.type === 'paren'));\n\n if (tok.type !== 'slash' && tok.type !== 'paren' && !isBrace && !isExtglob) {\n state.output = state.output.slice(0, -prev.output.length);\n prev.type = 'star';\n prev.value = '*';\n prev.output = star;\n state.output += prev.output;\n }\n }\n\n if (extglobs.length && tok.type !== 'paren') {\n extglobs[extglobs.length - 1].inner += tok.value;\n }\n\n if (tok.value || tok.output) append(tok);\n if (prev && prev.type === 'text' && tok.type === 'text') {\n prev.output = (prev.output || prev.value) + tok.value;\n prev.value += tok.value;\n return;\n }\n\n tok.prev = prev;\n tokens.push(tok);\n prev = tok;\n };\n\n const extglobOpen = (type, value) => {\n const token = { ...EXTGLOB_CHARS[value], conditions: 1, inner: '' };\n\n token.prev = prev;\n token.parens = state.parens;\n token.output = state.output;\n const output = (opts.capture ? '(' : '') + token.open;\n\n increment('parens');\n push({ type, value, output: state.output ? '' : ONE_CHAR });\n push({ type: 'paren', extglob: true, value: advance(), output });\n extglobs.push(token);\n };\n\n const extglobClose = token => {\n let output = token.close + (opts.capture ? ')' : '');\n let rest;\n\n if (token.type === 'negate') {\n let extglobStar = star;\n\n if (token.inner && token.inner.length > 1 && token.inner.includes('/')) {\n extglobStar = globstar(opts);\n }\n\n if (extglobStar !== star || eos() || /^\\)+$/.test(remaining())) {\n output = token.close = `)$))${extglobStar}`;\n }\n\n if (token.inner.includes('*') && (rest = remaining()) && /^\\.[^\\\\/.]+$/.test(rest)) {\n // Any non-magical string (`.ts`) or even nested expression (`.{ts,tsx}`) can follow after the closing parenthesis.\n // In this case, we need to parse the string and use it in the output of the original pattern.\n // Suitable patterns: `/!(*.d).ts`, `/!(*.d).{ts,tsx}`, `**/!(*-dbg).@(js)`.\n //\n // Disabling the `fastpaths` option due to a problem with parsing strings as `.ts` in the pattern like `**/!(*.d).ts`.\n const expression = parse(rest, { ...options, fastpaths: false }).output;\n\n output = token.close = `)${expression})${extglobStar})`;\n }\n\n if (token.prev.type === 'bos') {\n state.negatedExtglob = true;\n }\n }\n\n push({ type: 'paren', extglob: true, value, output });\n decrement('parens');\n };\n\n /**\n * Fast paths\n */\n\n if (opts.fastpaths !== false && !/(^[*!]|[/()[\\]{}\"])/.test(input)) {\n let backslashes = false;\n\n let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc, chars, first, rest, index) => {\n if (first === '\\\\') {\n backslashes = true;\n return m;\n }\n\n if (first === '?') {\n if (esc) {\n return esc + first + (rest ? QMARK.repeat(rest.length) : '');\n }\n if (index === 0) {\n return qmarkNoDot + (rest ? QMARK.repeat(rest.length) : '');\n }\n return QMARK.repeat(chars.length);\n }\n\n if (first === '.') {\n return DOT_LITERAL.repeat(chars.length);\n }\n\n if (first === '*') {\n if (esc) {\n return esc + first + (rest ? star : '');\n }\n return star;\n }\n return esc ? m : `\\\\${m}`;\n });\n\n if (backslashes === true) {\n if (opts.unescape === true) {\n output = output.replace(/\\\\/g, '');\n } else {\n output = output.replace(/\\\\+/g, m => {\n return m.length % 2 === 0 ? '\\\\\\\\' : (m ? '\\\\' : '');\n });\n }\n }\n\n if (output === input && opts.contains === true) {\n state.output = input;\n return state;\n }\n\n state.output = utils.wrapOutput(output, state, options);\n return state;\n }\n\n /**\n * Tokenize input until we reach end-of-string\n */\n\n while (!eos()) {\n value = advance();\n\n if (value === '\\u0000') {\n continue;\n }\n\n /**\n * Escaped characters\n */\n\n if (value === '\\\\') {\n const next = peek();\n\n if (next === '/' && opts.bash !== true) {\n continue;\n }\n\n if (next === '.' || next === ';') {\n continue;\n }\n\n if (!next) {\n value += '\\\\';\n push({ type: 'text', value });\n continue;\n }\n\n // collapse slashes to reduce potential for exploits\n const match = /^\\\\+/.exec(remaining());\n let slashes = 0;\n\n if (match && match[0].length > 2) {\n slashes = match[0].length;\n state.index += slashes;\n if (slashes % 2 !== 0) {\n value += '\\\\';\n }\n }\n\n if (opts.unescape === true) {\n value = advance();\n } else {\n value += advance();\n }\n\n if (state.brackets === 0) {\n push({ type: 'text', value });\n continue;\n }\n }\n\n /**\n * If we're inside a regex character class, continue\n * until we reach the closing bracket.\n */\n\n if (state.brackets > 0 && (value !== ']' || prev.value === '[' || prev.value === '[^')) {\n if (opts.posix !== false && value === ':') {\n const inner = prev.value.slice(1);\n if (inner.includes('[')) {\n prev.posix = true;\n\n if (inner.includes(':')) {\n const idx = prev.value.lastIndexOf('[');\n const pre = prev.value.slice(0, idx);\n const rest = prev.value.slice(idx + 2);\n const posix = POSIX_REGEX_SOURCE[rest];\n if (posix) {\n prev.value = pre + posix;\n state.backtrack = true;\n advance();\n\n if (!bos.output && tokens.indexOf(prev) === 1) {\n bos.output = ONE_CHAR;\n }\n continue;\n }\n }\n }\n }\n\n if ((value === '[' && peek() !== ':') || (value === '-' && peek() === ']')) {\n value = `\\\\${value}`;\n }\n\n if (value === ']' && (prev.value === '[' || prev.value === '[^')) {\n value = `\\\\${value}`;\n }\n\n if (opts.posix === true && value === '!' && prev.value === '[') {\n value = '^';\n }\n\n prev.value += value;\n append({ value });\n continue;\n }\n\n /**\n * If we're inside a quoted string, continue\n * until we reach the closing double quote.\n */\n\n if (state.quotes === 1 && value !== '\"') {\n value = utils.escapeRegex(value);\n prev.value += value;\n append({ value });\n continue;\n }\n\n /**\n * Double quotes\n */\n\n if (value === '\"') {\n state.quotes = state.quotes === 1 ? 0 : 1;\n if (opts.keepQuotes === true) {\n push({ type: 'text', value });\n }\n continue;\n }\n\n /**\n * Parentheses\n */\n\n if (value === '(') {\n increment('parens');\n push({ type: 'paren', value });\n continue;\n }\n\n if (value === ')') {\n if (state.parens === 0 && opts.strictBrackets === true) {\n throw new SyntaxError(syntaxError('opening', '('));\n }\n\n const extglob = extglobs[extglobs.length - 1];\n if (extglob && state.parens === extglob.parens + 1) {\n extglobClose(extglobs.pop());\n continue;\n }\n\n push({ type: 'paren', value, output: state.parens ? ')' : '\\\\)' });\n decrement('parens');\n continue;\n }\n\n /**\n * Square brackets\n */\n\n if (value === '[') {\n if (opts.nobracket === true || !remaining().includes(']')) {\n if (opts.nobracket !== true && opts.strictBrackets === true) {\n throw new SyntaxError(syntaxError('closing', ']'));\n }\n\n value = `\\\\${value}`;\n } else {\n increment('brackets');\n }\n\n push({ type: 'bracket', value });\n continue;\n }\n\n if (value === ']') {\n if (opts.nobracket === true || (prev && prev.type === 'bracket' && prev.value.length === 1)) {\n push({ type: 'text', value, output: `\\\\${value}` });\n continue;\n }\n\n if (state.brackets === 0) {\n if (opts.strictBrackets === true) {\n throw new SyntaxError(syntaxError('opening', '['));\n }\n\n push({ type: 'text', value, output: `\\\\${value}` });\n continue;\n }\n\n decrement('brackets');\n\n const prevValue = prev.value.slice(1);\n if (prev.posix !== true && prevValue[0] === '^' && !prevValue.includes('/')) {\n value = `/${value}`;\n }\n\n prev.value += value;\n append({ value });\n\n // when literal brackets are explicitly disabled\n // assume we should match with a regex character class\n if (opts.literalBrackets === false || utils.hasRegexChars(prevValue)) {\n continue;\n }\n\n const escaped = utils.escapeRegex(prev.value);\n state.output = state.output.slice(0, -prev.value.length);\n\n // when literal brackets are explicitly enabled\n // assume we should escape the brackets to match literal characters\n if (opts.literalBrackets === true) {\n state.output += escaped;\n prev.value = escaped;\n continue;\n }\n\n // when the user specifies nothing, try to match both\n prev.value = `(${capture}${escaped}|${prev.value})`;\n state.output += prev.value;\n continue;\n }\n\n /**\n * Braces\n */\n\n if (value === '{' && opts.nobrace !== true) {\n increment('braces');\n\n const open = {\n type: 'brace',\n value,\n output: '(',\n outputIndex: state.output.length,\n tokensIndex: state.tokens.length\n };\n\n braces.push(open);\n push(open);\n continue;\n }\n\n if (value === '}') {\n const brace = braces[braces.length - 1];\n\n if (opts.nobrace === true || !brace) {\n push({ type: 'text', value, output: value });\n continue;\n }\n\n let output = ')';\n\n if (brace.dots === true) {\n const arr = tokens.slice();\n const range = [];\n\n for (let i = arr.length - 1; i >= 0; i--) {\n tokens.pop();\n if (arr[i].type === 'brace') {\n break;\n }\n if (arr[i].type !== 'dots') {\n range.unshift(arr[i].value);\n }\n }\n\n output = expandRange(range, opts);\n state.backtrack = true;\n }\n\n if (brace.comma !== true && brace.dots !== true) {\n const out = state.output.slice(0, brace.outputIndex);\n const toks = state.tokens.slice(brace.tokensIndex);\n brace.value = brace.output = '\\\\{';\n value = output = '\\\\}';\n state.output = out;\n for (const t of toks) {\n state.output += (t.output || t.value);\n }\n }\n\n push({ type: 'brace', value, output });\n decrement('braces');\n braces.pop();\n continue;\n }\n\n /**\n * Pipes\n */\n\n if (value === '|') {\n if (extglobs.length > 0) {\n extglobs[extglobs.length - 1].conditions++;\n }\n push({ type: 'text', value });\n continue;\n }\n\n /**\n * Commas\n */\n\n if (value === ',') {\n let output = value;\n\n const brace = braces[braces.length - 1];\n if (brace && stack[stack.length - 1] === 'braces') {\n brace.comma = true;\n output = '|';\n }\n\n push({ type: 'comma', value, output });\n continue;\n }\n\n /**\n * Slashes\n */\n\n if (value === '/') {\n // if the beginning of the glob is \"./\", advance the start\n // to the current index, and don't add the \"./\" characters\n // to the state. This greatly simplifies lookbehinds when\n // checking for BOS characters like \"!\" and \".\" (not \"./\")\n if (prev.type === 'dot' && state.index === state.start + 1) {\n state.start = state.index + 1;\n state.consumed = '';\n state.output = '';\n tokens.pop();\n prev = bos; // reset \"prev\" to the first token\n continue;\n }\n\n push({ type: 'slash', value, output: SLASH_LITERAL });\n continue;\n }\n\n /**\n * Dots\n */\n\n if (value === '.') {\n if (state.braces > 0 && prev.type === 'dot') {\n if (prev.value === '.') prev.output = DOT_LITERAL;\n const brace = braces[braces.length - 1];\n prev.type = 'dots';\n prev.output += value;\n prev.value += value;\n brace.dots = true;\n continue;\n }\n\n if ((state.braces + state.parens) === 0 && prev.type !== 'bos' && prev.type !== 'slash') {\n push({ type: 'text', value, output: DOT_LITERAL });\n continue;\n }\n\n push({ type: 'dot', value, output: DOT_LITERAL });\n continue;\n }\n\n /**\n * Question marks\n */\n\n if (value === '?') {\n const isGroup = prev && prev.value === '(';\n if (!isGroup && opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {\n extglobOpen('qmark', value);\n continue;\n }\n\n if (prev && prev.type === 'paren') {\n const next = peek();\n let output = value;\n\n if ((prev.value === '(' && !/[!=<:]/.test(next)) || (next === '<' && !/<([!=]|\\w+>)/.test(remaining()))) {\n output = `\\\\${value}`;\n }\n\n push({ type: 'text', value, output });\n continue;\n }\n\n if (opts.dot !== true && (prev.type === 'slash' || prev.type === 'bos')) {\n push({ type: 'qmark', value, output: QMARK_NO_DOT });\n continue;\n }\n\n push({ type: 'qmark', value, output: QMARK });\n continue;\n }\n\n /**\n * Exclamation\n */\n\n if (value === '!') {\n if (opts.noextglob !== true && peek() === '(') {\n if (peek(2) !== '?' || !/[!=<:]/.test(peek(3))) {\n extglobOpen('negate', value);\n continue;\n }\n }\n\n if (opts.nonegate !== true && state.index === 0) {\n negate();\n continue;\n }\n }\n\n /**\n * Plus\n */\n\n if (value === '+') {\n if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {\n extglobOpen('plus', value);\n continue;\n }\n\n if ((prev && prev.value === '(') || opts.regex === false) {\n push({ type: 'plus', value, output: PLUS_LITERAL });\n continue;\n }\n\n if ((prev && (prev.type === 'bracket' || prev.type === 'paren' || prev.type === 'brace')) || state.parens > 0) {\n push({ type: 'plus', value });\n continue;\n }\n\n push({ type: 'plus', value: PLUS_LITERAL });\n continue;\n }\n\n /**\n * Plain text\n */\n\n if (value === '@') {\n if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {\n push({ type: 'at', extglob: true, value, output: '' });\n continue;\n }\n\n push({ type: 'text', value });\n continue;\n }\n\n /**\n * Plain text\n */\n\n if (value !== '*') {\n if (value === '$' || value === '^') {\n value = `\\\\${value}`;\n }\n\n const match = REGEX_NON_SPECIAL_CHARS.exec(remaining());\n if (match) {\n value += match[0];\n state.index += match[0].length;\n }\n\n push({ type: 'text', value });\n continue;\n }\n\n /**\n * Stars\n */\n\n if (prev && (prev.type === 'globstar' || prev.star === true)) {\n prev.type = 'star';\n prev.star = true;\n prev.value += value;\n prev.output = star;\n state.backtrack = true;\n state.globstar = true;\n consume(value);\n continue;\n }\n\n let rest = remaining();\n if (opts.noextglob !== true && /^\\([^?]/.test(rest)) {\n extglobOpen('star', value);\n continue;\n }\n\n if (prev.type === 'star') {\n if (opts.noglobstar === true) {\n consume(value);\n continue;\n }\n\n const prior = prev.prev;\n const before = prior.prev;\n const isStart = prior.type === 'slash' || prior.type === 'bos';\n const afterStar = before && (before.type === 'star' || before.type === 'globstar');\n\n if (opts.bash === true && (!isStart || (rest[0] && rest[0] !== '/'))) {\n push({ type: 'star', value, output: '' });\n continue;\n }\n\n const isBrace = state.braces > 0 && (prior.type === 'comma' || prior.type === 'brace');\n const isExtglob = extglobs.length && (prior.type === 'pipe' || prior.type === 'paren');\n if (!isStart && prior.type !== 'paren' && !isBrace && !isExtglob) {\n push({ type: 'star', value, output: '' });\n continue;\n }\n\n // strip consecutive `/**/`\n while (rest.slice(0, 3) === '/**') {\n const after = input[state.index + 4];\n if (after && after !== '/') {\n break;\n }\n rest = rest.slice(3);\n consume('/**', 3);\n }\n\n if (prior.type === 'bos' && eos()) {\n prev.type = 'globstar';\n prev.value += value;\n prev.output = globstar(opts);\n state.output = prev.output;\n state.globstar = true;\n consume(value);\n continue;\n }\n\n if (prior.type === 'slash' && prior.prev.type !== 'bos' && !afterStar && eos()) {\n state.output = state.output.slice(0, -(prior.output + prev.output).length);\n prior.output = `(?:${prior.output}`;\n\n prev.type = 'globstar';\n prev.output = globstar(opts) + (opts.strictSlashes ? ')' : '|$)');\n prev.value += value;\n state.globstar = true;\n state.output += prior.output + prev.output;\n consume(value);\n continue;\n }\n\n if (prior.type === 'slash' && prior.prev.type !== 'bos' && rest[0] === '/') {\n const end = rest[1] !== void 0 ? '|$' : '';\n\n state.output = state.output.slice(0, -(prior.output + prev.output).length);\n prior.output = `(?:${prior.output}`;\n\n prev.type = 'globstar';\n prev.output = `${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`;\n prev.value += value;\n\n state.output += prior.output + prev.output;\n state.globstar = true;\n\n consume(value + advance());\n\n push({ type: 'slash', value: '/', output: '' });\n continue;\n }\n\n if (prior.type === 'bos' && rest[0] === '/') {\n prev.type = 'globstar';\n prev.value += value;\n prev.output = `(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`;\n state.output = prev.output;\n state.globstar = true;\n consume(value + advance());\n push({ type: 'slash', value: '/', output: '' });\n continue;\n }\n\n // remove single star from output\n state.output = state.output.slice(0, -prev.output.length);\n\n // reset previous token to globstar\n prev.type = 'globstar';\n prev.output = globstar(opts);\n prev.value += value;\n\n // reset output with globstar\n state.output += prev.output;\n state.globstar = true;\n consume(value);\n continue;\n }\n\n const token = { type: 'star', value, output: star };\n\n if (opts.bash === true) {\n token.output = '.*?';\n if (prev.type === 'bos' || prev.type === 'slash') {\n token.output = nodot + token.output;\n }\n push(token);\n continue;\n }\n\n if (prev && (prev.type === 'bracket' || prev.type === 'paren') && opts.regex === true) {\n token.output = value;\n push(token);\n continue;\n }\n\n if (state.index === state.start || prev.type === 'slash' || prev.type === 'dot') {\n if (prev.type === 'dot') {\n state.output += NO_DOT_SLASH;\n prev.output += NO_DOT_SLASH;\n\n } else if (opts.dot === true) {\n state.output += NO_DOTS_SLASH;\n prev.output += NO_DOTS_SLASH;\n\n } else {\n state.output += nodot;\n prev.output += nodot;\n }\n\n if (peek() !== '*') {\n state.output += ONE_CHAR;\n prev.output += ONE_CHAR;\n }\n }\n\n push(token);\n }\n\n while (state.brackets > 0) {\n if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ']'));\n state.output = utils.escapeLast(state.output, '[');\n decrement('brackets');\n }\n\n while (state.parens > 0) {\n if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ')'));\n state.output = utils.escapeLast(state.output, '(');\n decrement('parens');\n }\n\n while (state.braces > 0) {\n if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', '}'));\n state.output = utils.escapeLast(state.output, '{');\n decrement('braces');\n }\n\n if (opts.strictSlashes !== true && (prev.type === 'star' || prev.type === 'bracket')) {\n push({ type: 'maybe_slash', value: '', output: `${SLASH_LITERAL}?` });\n }\n\n // rebuild the output if we had to backtrack at any point\n if (state.backtrack === true) {\n state.output = '';\n\n for (const token of state.tokens) {\n state.output += token.output != null ? token.output : token.value;\n\n if (token.suffix) {\n state.output += token.suffix;\n }\n }\n }\n\n return state;\n};\n\n/**\n * Fast paths for creating regular expressions for common glob patterns.\n * This can significantly speed up processing and has very little downside\n * impact when none of the fast paths match.\n */\n\nparse.fastpaths = (input, options) => {\n const opts = { ...options };\n const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;\n const len = input.length;\n if (len > max) {\n throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);\n }\n\n input = REPLACEMENTS[input] || input;\n\n // create constants based on platform, for windows or posix\n const {\n DOT_LITERAL,\n SLASH_LITERAL,\n ONE_CHAR,\n DOTS_SLASH,\n NO_DOT,\n NO_DOTS,\n NO_DOTS_SLASH,\n STAR,\n START_ANCHOR\n } = constants.globChars(opts.windows);\n\n const nodot = opts.dot ? NO_DOTS : NO_DOT;\n const slashDot = opts.dot ? NO_DOTS_SLASH : NO_DOT;\n const capture = opts.capture ? '' : '?:';\n const state = { negated: false, prefix: '' };\n let star = opts.bash === true ? '.*?' : STAR;\n\n if (opts.capture) {\n star = `(${star})`;\n }\n\n const globstar = opts => {\n if (opts.noglobstar === true) return star;\n return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;\n };\n\n const create = str => {\n switch (str) {\n case '*':\n return `${nodot}${ONE_CHAR}${star}`;\n\n case '.*':\n return `${DOT_LITERAL}${ONE_CHAR}${star}`;\n\n case '*.*':\n return `${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;\n\n case '*/*':\n return `${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`;\n\n case '**':\n return nodot + globstar(opts);\n\n case '**/*':\n return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`;\n\n case '**/*.*':\n return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;\n\n case '**/.*':\n return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`;\n\n default: {\n const match = /^(.*?)\\.(\\w+)$/.exec(str);\n if (!match) return;\n\n const source = create(match[1]);\n if (!source) return;\n\n return source + DOT_LITERAL + match[2];\n }\n }\n };\n\n const output = utils.removePrefix(input, state);\n let source = create(output);\n\n if (source && opts.strictSlashes !== true) {\n source += `${SLASH_LITERAL}?`;\n }\n\n return source;\n};\n\nmodule.exports = parse;\n","'use strict';\n\nconst scan = require('./scan');\nconst parse = require('./parse');\nconst utils = require('./utils');\nconst constants = require('./constants');\nconst isObject = val => val && typeof val === 'object' && !Array.isArray(val);\n\n/**\n * Creates a matcher function from one or more glob patterns. The\n * returned function takes a string to match as its first argument,\n * and returns true if the string is a match. The returned matcher\n * function also takes a boolean as the second argument that, when true,\n * returns an object with additional information.\n *\n * ```js\n * const picomatch = require('picomatch');\n * // picomatch(glob[, options]);\n *\n * const isMatch = picomatch('*.!(*a)');\n * console.log(isMatch('a.a')); //=> false\n * console.log(isMatch('a.b')); //=> true\n * ```\n * @name picomatch\n * @param {String|Array} `globs` One or more glob patterns.\n * @param {Object=} `options`\n * @return {Function=} Returns a matcher function.\n * @api public\n */\n\nconst picomatch = (glob, options, returnState = false) => {\n if (Array.isArray(glob)) {\n const fns = glob.map(input => picomatch(input, options, returnState));\n const arrayMatcher = str => {\n for (const isMatch of fns) {\n const state = isMatch(str);\n if (state) return state;\n }\n return false;\n };\n return arrayMatcher;\n }\n\n const isState = isObject(glob) && glob.tokens && glob.input;\n\n if (glob === '' || (typeof glob !== 'string' && !isState)) {\n throw new TypeError('Expected pattern to be a non-empty string');\n }\n\n const opts = options || {};\n const posix = opts.windows;\n const regex = isState\n ? picomatch.compileRe(glob, options)\n : picomatch.makeRe(glob, options, false, true);\n\n const state = regex.state;\n delete regex.state;\n\n let isIgnored = () => false;\n if (opts.ignore) {\n const ignoreOpts = { ...options, ignore: null, onMatch: null, onResult: null };\n isIgnored = picomatch(opts.ignore, ignoreOpts, returnState);\n }\n\n const matcher = (input, returnObject = false) => {\n const { isMatch, match, output } = picomatch.test(input, regex, options, { glob, posix });\n const result = { glob, state, regex, posix, input, output, match, isMatch };\n\n if (typeof opts.onResult === 'function') {\n opts.onResult(result);\n }\n\n if (isMatch === false) {\n result.isMatch = false;\n return returnObject ? result : false;\n }\n\n if (isIgnored(input)) {\n if (typeof opts.onIgnore === 'function') {\n opts.onIgnore(result);\n }\n result.isMatch = false;\n return returnObject ? result : false;\n }\n\n if (typeof opts.onMatch === 'function') {\n opts.onMatch(result);\n }\n return returnObject ? result : true;\n };\n\n if (returnState) {\n matcher.state = state;\n }\n\n return matcher;\n};\n\n/**\n * Test `input` with the given `regex`. This is used by the main\n * `picomatch()` function to test the input string.\n *\n * ```js\n * const picomatch = require('picomatch');\n * // picomatch.test(input, regex[, options]);\n *\n * console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\\/([^/]*?))$/));\n * // { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' }\n * ```\n * @param {String} `input` String to test.\n * @param {RegExp} `regex`\n * @return {Object} Returns an object with matching info.\n * @api public\n */\n\npicomatch.test = (input, regex, options, { glob, posix } = {}) => {\n if (typeof input !== 'string') {\n throw new TypeError('Expected input to be a string');\n }\n\n if (input === '') {\n return { isMatch: false, output: '' };\n }\n\n const opts = options || {};\n const format = opts.format || (posix ? utils.toPosixSlashes : null);\n let match = input === glob;\n let output = (match && format) ? format(input) : input;\n\n if (match === false) {\n output = format ? format(input) : input;\n match = output === glob;\n }\n\n if (match === false || opts.capture === true) {\n if (opts.matchBase === true || opts.basename === true) {\n match = picomatch.matchBase(input, regex, options, posix);\n } else {\n match = regex.exec(output);\n }\n }\n\n return { isMatch: Boolean(match), match, output };\n};\n\n/**\n * Match the basename of a filepath.\n *\n * ```js\n * const picomatch = require('picomatch');\n * // picomatch.matchBase(input, glob[, options]);\n * console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true\n * ```\n * @param {String} `input` String to test.\n * @param {RegExp|String} `glob` Glob pattern or regex created by [.makeRe](#makeRe).\n * @return {Boolean}\n * @api public\n */\n\npicomatch.matchBase = (input, glob, options) => {\n const regex = glob instanceof RegExp ? glob : picomatch.makeRe(glob, options);\n return regex.test(utils.basename(input));\n};\n\n/**\n * Returns true if **any** of the given glob `patterns` match the specified `string`.\n *\n * ```js\n * const picomatch = require('picomatch');\n * // picomatch.isMatch(string, patterns[, options]);\n *\n * console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true\n * console.log(picomatch.isMatch('a.a', 'b.*')); //=> false\n * ```\n * @param {String|Array} str The string to test.\n * @param {String|Array} patterns One or more glob patterns to use for matching.\n * @param {Object} [options] See available [options](#options).\n * @return {Boolean} Returns true if any patterns match `str`\n * @api public\n */\n\npicomatch.isMatch = (str, patterns, options) => picomatch(patterns, options)(str);\n\n/**\n * Parse a glob pattern to create the source string for a regular\n * expression.\n *\n * ```js\n * const picomatch = require('picomatch');\n * const result = picomatch.parse(pattern[, options]);\n * ```\n * @param {String} `pattern`\n * @param {Object} `options`\n * @return {Object} Returns an object with useful properties and output to be used as a regex source string.\n * @api public\n */\n\npicomatch.parse = (pattern, options) => {\n if (Array.isArray(pattern)) return pattern.map(p => picomatch.parse(p, options));\n return parse(pattern, { ...options, fastpaths: false });\n};\n\n/**\n * Scan a glob pattern to separate the pattern into segments.\n *\n * ```js\n * const picomatch = require('picomatch');\n * // picomatch.scan(input[, options]);\n *\n * const result = picomatch.scan('!./foo/*.js');\n * console.log(result);\n * { prefix: '!./',\n * input: '!./foo/*.js',\n * start: 3,\n * base: 'foo',\n * glob: '*.js',\n * isBrace: false,\n * isBracket: false,\n * isGlob: true,\n * isExtglob: false,\n * isGlobstar: false,\n * negated: true }\n * ```\n * @param {String} `input` Glob pattern to scan.\n * @param {Object} `options`\n * @return {Object} Returns an object with\n * @api public\n */\n\npicomatch.scan = (input, options) => scan(input, options);\n\n/**\n * Compile a regular expression from the `state` object returned by the\n * [parse()](#parse) method.\n *\n * @param {Object} `state`\n * @param {Object} `options`\n * @param {Boolean} `returnOutput` Intended for implementors, this argument allows you to return the raw output from the parser.\n * @param {Boolean} `returnState` Adds the state to a `state` property on the returned regex. Useful for implementors and debugging.\n * @return {RegExp}\n * @api public\n */\n\npicomatch.compileRe = (state, options, returnOutput = false, returnState = false) => {\n if (returnOutput === true) {\n return state.output;\n }\n\n const opts = options || {};\n const prepend = opts.contains ? '' : '^';\n const append = opts.contains ? '' : '$';\n\n let source = `${prepend}(?:${state.output})${append}`;\n if (state && state.negated === true) {\n source = `^(?!${source}).*$`;\n }\n\n const regex = picomatch.toRegex(source, options);\n if (returnState === true) {\n regex.state = state;\n }\n\n return regex;\n};\n\n/**\n * Create a regular expression from a parsed glob pattern.\n *\n * ```js\n * const picomatch = require('picomatch');\n * const state = picomatch.parse('*.js');\n * // picomatch.compileRe(state[, options]);\n *\n * console.log(picomatch.compileRe(state));\n * //=> /^(?:(?!\\.)(?=.)[^/]*?\\.js)$/\n * ```\n * @param {String} `state` The object returned from the `.parse` method.\n * @param {Object} `options`\n * @param {Boolean} `returnOutput` Implementors may use this argument to return the compiled output, instead of a regular expression. This is not exposed on the options to prevent end-users from mutating the result.\n * @param {Boolean} `returnState` Implementors may use this argument to return the state from the parsed glob with the returned regular expression.\n * @return {RegExp} Returns a regex created from the given pattern.\n * @api public\n */\n\npicomatch.makeRe = (input, options = {}, returnOutput = false, returnState = false) => {\n if (!input || typeof input !== 'string') {\n throw new TypeError('Expected a non-empty string');\n }\n\n let parsed = { negated: false, fastpaths: true };\n\n if (options.fastpaths !== false && (input[0] === '.' || input[0] === '*')) {\n parsed.output = parse.fastpaths(input, options);\n }\n\n if (!parsed.output) {\n parsed = parse(input, options);\n }\n\n return picomatch.compileRe(parsed, options, returnOutput, returnState);\n};\n\n/**\n * Create a regular expression from the given regex source string.\n *\n * ```js\n * const picomatch = require('picomatch');\n * // picomatch.toRegex(source[, options]);\n *\n * const { output } = picomatch.parse('*.js');\n * console.log(picomatch.toRegex(output));\n * //=> /^(?:(?!\\.)(?=.)[^/]*?\\.js)$/\n * ```\n * @param {String} `source` Regular expression source string.\n * @param {Object} `options`\n * @return {RegExp}\n * @api public\n */\n\npicomatch.toRegex = (source, options) => {\n try {\n const opts = options || {};\n return new RegExp(source, opts.flags || (opts.nocase ? 'i' : ''));\n } catch (err) {\n if (options && options.debug === true) throw err;\n return /$^/;\n }\n};\n\n/**\n * Picomatch constants.\n * @return {Object}\n */\n\npicomatch.constants = constants;\n\n/**\n * Expose \"picomatch\"\n */\n\nmodule.exports = picomatch;\n","'use strict';\n\nconst pico = require('./lib/picomatch');\nconst utils = require('./lib/utils');\n\nfunction picomatch(glob, options, returnState = false) {\n // default to os.platform()\n if (options && (options.windows === null || options.windows === undefined)) {\n // don't mutate the original options object\n options = { ...options, windows: utils.isWindows() };\n }\n\n return pico(glob, options, returnState);\n}\n\nObject.assign(picomatch, pico);\nmodule.exports = picomatch;\n","import { defineCommand } from \"citty\";\nimport { mkdir, writeFile } from \"node:fs/promises\";\nimport { join, basename, resolve } from \"node:path\";\nimport { REQUIRED_SECTIONS } from \"@specdx/schema\";\n\nexport type Template = \"lightweight\" | \"bmad\" | \"api-first\" | \"quick\" | \"context\";\n\nexport interface ScaffoldOptions {\n projectName: string;\n template: Template;\n targetDir: string;\n}\n\nconst TEMPLATE_SPECS: Record<\n Template,\n Array<{ filename: string; type: keyof typeof REQUIRED_SECTIONS }>\n> = {\n lightweight: [\n { filename: \"prd.md\", type: \"prd\" },\n { filename: \"technical-design.md\", type: \"technical-design\" },\n ],\n bmad: [\n { filename: \"prd.md\", type: \"prd\" },\n { filename: \"technical-design.md\", type: \"technical-design\" },\n { filename: \"test-plan.md\", type: \"test-plan\" },\n ],\n \"api-first\": [\n { filename: \"technical-design.md\", type: \"technical-design\" },\n { filename: \"api-contract.md\", type: \"api-contract\" },\n { filename: \"test-plan.md\", type: \"test-plan\" },\n ],\n quick: [{ filename: \"quick-spec.md\", type: \"quick-spec\" }],\n context: [{ filename: \"project-context.md\", type: \"project-context\" }],\n};\n\nconst TEMPLATE_EXTRA_DIRS: Record<Template, string[]> = {\n lightweight: [],\n bmad: [\"specs/stories\", \"specs/adr\"],\n \"api-first\": [],\n quick: [],\n context: [],\n};\n\nfunction specIdFromFilename(filename: string): string {\n return filename.replace(/\\.md$/, \"\");\n}\n\nfunction specTitleFromType(type: string): string {\n return type\n .split(\"-\")\n .map((w) => w.charAt(0).toUpperCase() + w.slice(1))\n .join(\" \");\n}\n\nfunction buildSpecFile(\n filename: string,\n type: keyof typeof REQUIRED_SECTIONS,\n projectName: string,\n today: string,\n): string {\n const id = specIdFromFilename(filename);\n const title = `${specTitleFromType(type)} — ${projectName}`;\n const sections = REQUIRED_SECTIONS[type];\n\n const frontmatter = [\n \"---\",\n `id: ${id}`,\n `type: ${type}`,\n `title: \"${title}\"`,\n `status: draft`,\n `version: \"0.1\"`,\n `created: \"${today}\"`,\n `authors: [\"author\"]`,\n \"---\",\n ].join(\"\\n\");\n\n const body = sections.map((section) => `\\n## ${section}\\n\\n<!-- placeholder -->`).join(\"\\n\");\n\n return `${frontmatter}\\n${body}\\n`;\n}\n\nfunction buildConfigYaml(\n projectName: string,\n specs: Array<{ filename: string; type: string }>,\n): string {\n const specEntries = specs\n .map(({ filename, type }) => {\n const key = specIdFromFilename(filename);\n return ` ${key}:\\n path: specs/${filename}\\n type: ${type}`;\n })\n .join(\"\\n\");\n\n return (\n [`version: \"1.0\"`, `project:`, ` name: \"${projectName}\"`, `specs:`, specEntries].join(\"\\n\") +\n \"\\n\"\n );\n}\n\nexport async function scaffoldProject({\n projectName,\n template,\n targetDir,\n}: ScaffoldOptions): Promise<void> {\n if (!targetDir) {\n throw new TypeError(\"scaffoldProject requires `targetDir` — where to create the project.\");\n }\n const today = new Date().toISOString().slice(0, 10);\n const specsDir = join(targetDir, \"specs\");\n\n // Create specs/ directory\n await mkdir(specsDir, { recursive: true });\n\n // Create extra template dirs (e.g., bmad needs stories/ and adr/)\n for (const extraDir of TEMPLATE_EXTRA_DIRS[template]) {\n await mkdir(join(targetDir, extraDir), { recursive: true });\n }\n\n const specs = TEMPLATE_SPECS[template];\n\n // Write spec files\n for (const { filename, type } of specs) {\n const content = buildSpecFile(filename, type, projectName, today);\n await writeFile(join(specsDir, filename), content, \"utf-8\");\n }\n\n // Write spec.config.yaml\n const configContent = buildConfigYaml(projectName, specs);\n await writeFile(join(targetDir, \"spec.config.yaml\"), configContent, \"utf-8\");\n}\n\n/**\n * The project name to use when `--name` is absent: the target directory's own\n * name, resolved so that `.` becomes the current directory rather than a dot.\n */\nexport function defaultProjectName(dir: string): string {\n return basename(resolve(dir)) || \"my-project\";\n}\n\nexport default defineCommand({\n meta: {\n name: \"init\",\n description: \"Initialize a new specdx project with spec scaffolding\",\n },\n args: {\n name: {\n type: \"string\",\n description: \"Project name (default: the target directory's name)\",\n },\n template: {\n type: \"string\",\n description: \"Template to use (lightweight, bmad, api-first)\",\n default: \"lightweight\",\n },\n dir: {\n type: \"string\",\n description: \"Target directory\",\n default: \".\",\n },\n },\n async run({ args }) {\n const { template, dir } = args;\n const validTemplates: Template[] = [\"lightweight\", \"bmad\", \"api-first\", \"quick\", \"context\"];\n if (!validTemplates.includes(template as Template)) {\n console.error(`Unknown template: ${template}. Choose from: ${validTemplates.join(\", \")}`);\n process.exit(1);\n }\n\n // The first command anyone runs should not fail on a missing flag when the\n // answer is sitting in the path. `--name` still wins where they differ.\n const name = args.name || defaultProjectName(dir);\n\n console.log(`Scaffolding \"${name}\" with template \"${template}\" in ${dir}...`);\n await scaffoldProject({ projectName: name, template: template as Template, targetDir: dir });\n console.log(`Done! Project \"${name}\" scaffolded successfully.`);\n },\n});\n","/**\n * The `version` a `spec.config.yaml` is expected to declare.\n *\n * The field was accepted with any value at all, so `migrate` printed whatever\n * it read and then said \"no migration needed\" regardless -- a config claiming\n * `0.9` passed as readily as a current one. A version field nothing checks is\n * a field that cannot do its job when a real migration arrives.\n */\nexport const SUPPORTED_CONFIG_VERSION = \"1.0\";\n\nexport const SPEC_TYPES = [\n \"prd\",\n \"technical-design\",\n \"user-story\",\n \"test-plan\",\n \"adr\",\n \"api-contract\",\n \"epic\",\n \"quick-spec\",\n \"project-context\",\n] as const;\nexport type SpecType = (typeof SPEC_TYPES)[number];\n\nexport const SPEC_STATUSES = [\"draft\", \"review\", \"approved\", \"superseded\"] as const;\nexport type SpecStatus = (typeof SPEC_STATUSES)[number];\n\n/**\n * Every relationship kind a spec may declare in frontmatter `references`.\n * Single source of truth — `base-spec.json`'s enum is drift-tested against it.\n */\nexport const SPEC_RELATIONSHIPS = [\n \"implemented-by\",\n \"decomposed-into\",\n \"depends-on\",\n \"supersedes\",\n \"related-to\",\n] as const;\nexport type SpecRelationship = (typeof SPEC_RELATIONSHIPS)[number];\n\n/**\n * Which relationship kinds imply a build dependency, and in which direction.\n *\n * Structural kinds are deliberately absent: `decomposed-into` describes a\n * parent/child split and `supersedes` describes lineage — neither means the\n * target depends on the source (issue #13). Declared here rather than in\n * `@specdx/core` so the taxonomy is versioned with the schema it belongs to\n * (ADR: references/requires unification).\n */\nexport const DEPENDENCY_RELATIONSHIPS: Partial<\n Record<SpecRelationship, \"self-requires-target\" | \"target-requires-self\">\n> = {\n \"depends-on\": \"self-requires-target\",\n \"implemented-by\": \"target-requires-self\",\n};\n\nexport interface SpecReference {\n id: string;\n relationship: SpecRelationship;\n}\n\n/** A checkable implementation artifact declared by a spec (issue #15). */\nexport interface SpecArtifact {\n /** Project-root-relative file path that must exist. */\n path: string;\n /** Names that must be exported from the file. */\n exports?: string[];\n}\n\nexport interface BaseSpec {\n id: string;\n type: SpecType;\n title: string;\n status: SpecStatus;\n version: string;\n created: string;\n updated?: string;\n authors: string[];\n tags?: string[];\n references?: SpecReference[];\n artifacts?: SpecArtifact[];\n}\n\nexport interface PrdSpec extends BaseSpec {\n type: \"prd\";\n}\nexport interface TechnicalDesignSpec extends BaseSpec {\n type: \"technical-design\";\n}\nexport interface UserStorySpec extends BaseSpec {\n type: \"user-story\";\n story_id: string;\n priority: \"critical\" | \"high\" | \"medium\" | \"low\";\n estimate: string;\n}\nexport interface TestPlanSpec extends BaseSpec {\n type: \"test-plan\";\n}\nexport interface AdrSpec extends BaseSpec {\n type: \"adr\";\n}\nexport interface ApiContractSpec extends BaseSpec {\n type: \"api-contract\";\n}\n\nexport interface EpicSpec extends BaseSpec {\n type: \"epic\";\n epic_id: string;\n priority: \"critical\" | \"high\" | \"medium\" | \"low\";\n}\n\nexport interface QuickSpecSpec extends BaseSpec {\n type: \"quick-spec\";\n}\n\nexport interface ProjectContextSpec extends BaseSpec {\n type: \"project-context\";\n}\n\nexport type Spec =\n | PrdSpec\n | TechnicalDesignSpec\n | UserStorySpec\n | TestPlanSpec\n | AdrSpec\n | ApiContractSpec\n | EpicSpec\n | QuickSpecSpec\n | ProjectContextSpec;\n\nexport interface SpecEntry {\n path: string;\n type: SpecType;\n required?: boolean;\n requires?: string[];\n owner?: string;\n}\n\nexport interface PackCompressionConfig {\n strip_boilerplate?: boolean;\n stable_days?: number;\n collapse_resolved_adrs?: boolean;\n}\n\nexport interface PackConfig {\n max_tokens?: number;\n format?: \"xml\" | \"markdown\" | \"json\";\n compression?: PackCompressionConfig;\n boilerplate_sections?: string[];\n}\n\nexport interface SdxConfig {\n version: string;\n project?: { name?: string; description?: string };\n specs: Record<string, SpecEntry>;\n lint?: {\n extends?: string;\n rules?: Record<string, unknown>;\n ignore?: string[];\n };\n pack?: PackConfig;\n diff?: {\n baseline_ref?: string;\n staleness_threshold_days?: number;\n ignore_paths?: string[];\n };\n ci?: {\n block_on?: (\"error\" | \"warn\" | \"info\")[];\n post_comment?: boolean;\n update_badge?: boolean;\n trigger_paths?: string[];\n };\n check?: {\n framework?: \"auto\" | \"express\" | \"hono\" | \"nextjs\";\n routes_dir?: string;\n app_dir?: string;\n types_dir?: string;\n tests_dir?: string;\n ignore?: string[];\n };\n}\n","import type { SpecType } from \"./types.js\";\n\nexport const REQUIRED_SECTIONS: Record<SpecType, string[]> = {\n prd: [\"Problem Statement\", \"Goals\", \"Non-Goals\", \"Features\", \"Success Criteria\"],\n \"technical-design\": [\n \"Overview\",\n \"Architecture\",\n \"Data Model\",\n \"API Design\",\n \"Dependencies\",\n \"Risks\",\n \"Open Questions\",\n ],\n \"user-story\": [\"Description\", \"Acceptance Criteria\", \"Dependencies\", \"Notes\"],\n \"test-plan\": [\"Scope\", \"Test Cases\", \"Coverage Matrix\", \"Edge Cases\"],\n adr: [\"Context\", \"Decision\", \"Status\", \"Consequences\"],\n \"api-contract\": [\"Endpoints\", \"Request/Response Schemas\", \"Auth\", \"Error Codes\"],\n epic: [\"Overview\", \"Stories\", \"Acceptance Criteria\", \"Dependencies\"],\n \"quick-spec\": [\"Intent\", \"Boundaries\", \"Tasks\"],\n \"project-context\": [\"Technology Stack\", \"Critical Implementation Rules\", \"Coding Patterns\"],\n};\n","import { Ajv as AjvClass, type ErrorObject } from \"ajv\";\nimport { SPEC_TYPES, type SpecType } from \"./types.js\";\n\nimport baseSpecSchema from \"./schemas/base-spec.json\" with { type: \"json\" };\nimport configSchema from \"./schemas/config.json\" with { type: \"json\" };\nimport prdSchema from \"./schemas/prd.json\" with { type: \"json\" };\nimport technicalDesignSchema from \"./schemas/technical-design.json\" with { type: \"json\" };\nimport userStorySchema from \"./schemas/user-story.json\" with { type: \"json\" };\nimport testPlanSchema from \"./schemas/test-plan.json\" with { type: \"json\" };\nimport adrSchema from \"./schemas/adr.json\" with { type: \"json\" };\nimport apiContractSchema from \"./schemas/api-contract.json\" with { type: \"json\" };\nimport epicSchema from \"./schemas/epic.json\" with { type: \"json\" };\nimport quickSpecSchema from \"./schemas/quick-spec.json\" with { type: \"json\" };\nimport projectContextSchema from \"./schemas/project-context.json\" with { type: \"json\" };\n\n// addFormats is CJS-only; access via the namespace default at runtime\n// The type cast is needed because TypeScript's NodeNext resolution exposes\n// the CJS module as a namespace without a callable default signature.\nimport * as addFormatsNs from \"ajv-formats\";\ntype AddFormatsPlugin = (ajv: AjvClass, formats?: unknown) => AjvClass;\nconst addFormats = ((addFormatsNs as unknown as { default?: AddFormatsPlugin }).default ??\n (addFormatsNs as unknown as AddFormatsPlugin)) as AddFormatsPlugin;\n\nexport interface ValidationResult {\n valid: boolean;\n errors: ErrorObject[] | null;\n}\n\n// The JSON schemas duplicate the spec-type enum for editor and schema-store\n// consumers. At runtime SPEC_TYPES is the single source of truth: the enums are\n// overwritten before compilation so the JSON copies can never drift from the\n// TypeScript types (see issue #2 — a stale enum shipped in 0.4.0-alpha.2).\nconst runtimeBaseSpecSchema = structuredClone(baseSpecSchema);\nruntimeBaseSpecSchema.properties.type.enum = [...SPEC_TYPES];\nconst runtimeConfigSchema = structuredClone(configSchema);\nruntimeConfigSchema.properties.specs.additionalProperties.properties.type.enum = [...SPEC_TYPES];\n\nconst ajv = new AjvClass({ allErrors: true, strict: true });\naddFormats(ajv, [\"date\"]);\najv.addSchema(runtimeBaseSpecSchema);\n\nconst specValidators: Record<string, ReturnType<typeof ajv.compile>> = {\n prd: ajv.compile(prdSchema),\n \"technical-design\": ajv.compile(technicalDesignSchema),\n \"user-story\": ajv.compile(userStorySchema),\n \"test-plan\": ajv.compile(testPlanSchema),\n adr: ajv.compile(adrSchema),\n \"api-contract\": ajv.compile(apiContractSchema),\n epic: ajv.compile(epicSchema),\n \"quick-spec\": ajv.compile(quickSpecSchema),\n \"project-context\": ajv.compile(projectContextSchema),\n};\n\nconst configValidator = ajv.compile(runtimeConfigSchema);\n\nexport function validateSpec(type: SpecType, data: Record<string, unknown>): ValidationResult {\n const validate = specValidators[type];\n if (!validate) {\n return { valid: false, errors: [{ message: `Unknown spec type: \"${type}\"` } as ErrorObject] };\n }\n const valid = validate(data);\n return { valid: !!valid, errors: valid ? null : (validate.errors ?? null) };\n}\n\nexport function validateConfig(data: Record<string, unknown>): ValidationResult {\n const valid = configValidator(data);\n return { valid: !!valid, errors: valid ? null : (configValidator.errors ?? null) };\n}\n","{\n \"$id\": \"base-spec\",\n \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n \"type\": \"object\",\n \"properties\": {\n \"id\": {\n \"type\": \"string\",\n \"minLength\": 1\n },\n \"type\": {\n \"type\": \"string\",\n \"enum\": [\n \"prd\",\n \"technical-design\",\n \"user-story\",\n \"test-plan\",\n \"adr\",\n \"api-contract\",\n \"epic\",\n \"quick-spec\",\n \"project-context\"\n ]\n },\n \"title\": {\n \"type\": \"string\",\n \"minLength\": 1\n },\n \"status\": {\n \"type\": \"string\",\n \"enum\": [\n \"draft\",\n \"review\",\n \"approved\",\n \"superseded\"\n ]\n },\n \"version\": {\n \"type\": \"string\"\n },\n \"created\": {\n \"type\": \"string\",\n \"format\": \"date\"\n },\n \"updated\": {\n \"type\": \"string\",\n \"format\": \"date\"\n },\n \"authors\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\"\n },\n \"minItems\": 1\n },\n \"tags\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\"\n },\n \"default\": []\n },\n \"references\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"object\",\n \"properties\": {\n \"id\": {\n \"type\": \"string\"\n },\n \"relationship\": {\n \"type\": \"string\",\n \"enum\": [\n \"implemented-by\",\n \"decomposed-into\",\n \"depends-on\",\n \"supersedes\",\n \"related-to\"\n ]\n }\n },\n \"required\": [\n \"id\",\n \"relationship\"\n ],\n \"additionalProperties\": false\n },\n \"default\": []\n },\n \"artifacts\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"object\",\n \"properties\": {\n \"path\": {\n \"type\": \"string\",\n \"minLength\": 1\n },\n \"exports\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\",\n \"minLength\": 1\n }\n }\n },\n \"required\": [\n \"path\"\n ],\n \"additionalProperties\": false\n },\n \"default\": []\n }\n },\n \"required\": [\n \"id\",\n \"type\",\n \"title\",\n \"status\",\n \"version\",\n \"created\",\n \"authors\"\n ],\n \"additionalProperties\": true\n}\n","{\n \"$id\": \"specdx-config\",\n \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n \"type\": \"object\",\n \"properties\": {\n \"version\": { \"type\": \"string\" },\n \"project\": {\n \"type\": \"object\",\n \"properties\": {\n \"name\": { \"type\": \"string\" },\n \"description\": { \"type\": \"string\" }\n },\n \"additionalProperties\": false\n },\n \"specs\": {\n \"type\": \"object\",\n \"additionalProperties\": {\n \"type\": \"object\",\n \"properties\": {\n \"path\": { \"type\": \"string\" },\n \"type\": { \"type\": \"string\", \"enum\": [\"prd\", \"technical-design\", \"user-story\", \"test-plan\", \"adr\", \"api-contract\", \"epic\", \"quick-spec\", \"project-context\"] },\n \"required\": { \"type\": \"boolean\", \"default\": false },\n \"requires\": { \"type\": \"array\", \"items\": { \"type\": \"string\" } },\n \"owner\": { \"type\": \"string\" }\n },\n \"required\": [\"path\", \"type\"],\n \"additionalProperties\": false\n }\n },\n \"lint\": {\n \"type\": \"object\",\n \"properties\": {\n \"extends\": { \"type\": \"string\" },\n \"rules\": { \"type\": \"object\" },\n \"ignore\": { \"type\": \"array\", \"items\": { \"type\": \"string\" } }\n },\n \"additionalProperties\": false\n },\n \"pack\": {\n \"type\": \"object\",\n \"properties\": {\n \"max_tokens\": { \"type\": \"integer\", \"minimum\": 1 },\n \"format\": { \"type\": \"string\", \"enum\": [\"xml\", \"markdown\", \"json\"] },\n \"compression\": {\n \"type\": \"object\",\n \"properties\": {\n \"strip_boilerplate\": { \"type\": \"boolean\" },\n \"stable_days\": { \"type\": \"integer\", \"minimum\": 0 },\n \"collapse_resolved_adrs\": { \"type\": \"boolean\" }\n },\n \"additionalProperties\": false\n },\n \"boilerplate_sections\": {\n \"type\": \"array\",\n \"items\": { \"type\": \"string\" }\n }\n },\n \"additionalProperties\": false\n },\n \"diff\": {\n \"type\": \"object\",\n \"properties\": {\n \"baseline_ref\": { \"type\": \"string\", \"default\": \"main\" },\n \"staleness_threshold_days\": { \"type\": \"integer\", \"minimum\": 1, \"default\": 14 },\n \"ignore_paths\": { \"type\": \"array\", \"items\": { \"type\": \"string\" } }\n },\n \"additionalProperties\": false\n },\n \"ci\": {\n \"type\": \"object\",\n \"properties\": {\n \"block_on\": {\n \"type\": \"array\",\n \"items\": { \"type\": \"string\", \"enum\": [\"error\", \"warn\", \"info\"] }\n },\n \"post_comment\": { \"type\": \"boolean\", \"default\": true },\n \"update_badge\": { \"type\": \"boolean\", \"default\": true },\n \"trigger_paths\": {\n \"type\": \"array\",\n \"items\": { \"type\": \"string\" }\n }\n },\n \"additionalProperties\": false\n },\n \"check\": {\n \"type\": \"object\",\n \"properties\": {\n \"framework\": {\n \"type\": \"string\",\n \"enum\": [\"auto\", \"express\", \"hono\", \"nextjs\"]\n },\n \"routes_dir\": { \"type\": \"string\" },\n \"app_dir\": { \"type\": \"string\" },\n \"types_dir\": { \"type\": \"string\" },\n \"tests_dir\": { \"type\": \"string\" },\n \"ignore\": {\n \"type\": \"array\",\n \"items\": { \"type\": \"string\" }\n }\n },\n \"additionalProperties\": false\n }\n },\n \"required\": [\"version\", \"specs\"],\n \"additionalProperties\": false\n}\n","{\n \"$id\": \"prd\",\n \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n \"allOf\": [\n { \"$ref\": \"base-spec\" },\n { \"type\": \"object\", \"properties\": { \"type\": { \"const\": \"prd\" } }, \"required\": [\"type\"] }\n ]\n}\n","{\n \"$id\": \"technical-design\",\n \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n \"allOf\": [\n { \"$ref\": \"base-spec\" },\n { \"type\": \"object\", \"properties\": { \"type\": { \"const\": \"technical-design\" } }, \"required\": [\"type\"] }\n ]\n}\n","{\n \"$id\": \"user-story\",\n \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n \"allOf\": [\n { \"$ref\": \"base-spec\" },\n {\n \"type\": \"object\",\n \"properties\": {\n \"type\": { \"const\": \"user-story\" },\n \"story_id\": { \"type\": \"string\", \"minLength\": 1 },\n \"priority\": { \"type\": \"string\", \"enum\": [\"critical\", \"high\", \"medium\", \"low\"] },\n \"estimate\": { \"type\": \"string\" }\n },\n \"required\": [\"type\", \"story_id\", \"priority\", \"estimate\"]\n }\n ]\n}\n","{\n \"$id\": \"test-plan\",\n \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n \"allOf\": [\n { \"$ref\": \"base-spec\" },\n { \"type\": \"object\", \"properties\": { \"type\": { \"const\": \"test-plan\" } }, \"required\": [\"type\"] }\n ]\n}\n","{\n \"$id\": \"adr\",\n \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n \"allOf\": [\n { \"$ref\": \"base-spec\" },\n { \"type\": \"object\", \"properties\": { \"type\": { \"const\": \"adr\" } }, \"required\": [\"type\"] }\n ]\n}\n","{\n \"$id\": \"api-contract\",\n \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n \"allOf\": [\n { \"$ref\": \"base-spec\" },\n { \"type\": \"object\", \"properties\": { \"type\": { \"const\": \"api-contract\" } }, \"required\": [\"type\"] }\n ]\n}\n","{\n \"$id\": \"epic\",\n \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n \"allOf\": [\n { \"$ref\": \"base-spec\" },\n {\n \"type\": \"object\",\n \"properties\": {\n \"type\": { \"const\": \"epic\" },\n \"epic_id\": { \"type\": \"string\", \"minLength\": 1 },\n \"priority\": { \"type\": \"string\", \"enum\": [\"critical\", \"high\", \"medium\", \"low\"] }\n },\n \"required\": [\"type\", \"epic_id\", \"priority\"]\n }\n ]\n}\n","{\n \"$id\": \"quick-spec\",\n \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n \"allOf\": [\n { \"$ref\": \"base-spec\" },\n {\n \"type\": \"object\",\n \"properties\": {\n \"type\": { \"const\": \"quick-spec\" }\n },\n \"required\": [\"type\"]\n }\n ]\n}\n","{\n \"$id\": \"project-context\",\n \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n \"allOf\": [\n { \"$ref\": \"base-spec\" },\n {\n \"type\": \"object\",\n \"properties\": {\n \"type\": { \"const\": \"project-context\" }\n },\n \"required\": [\"type\"]\n }\n ]\n}\n","import { defineCommand } from \"citty\";\nimport { loadConfig, parseSpec, resolveGlob, buildGraph, createLogger } from \"@specdx/core\";\nimport { createLintEngine, getPreset, type LintResults } from \"@specdx/lint\";\nimport type { ParsedSpec } from \"@specdx/core\";\nimport { sharedArgs, resolveFormat } from \"../../shared-args.js\";\nimport { createOutput } from \"../../output.js\";\nimport { formatPretty } from \"../../formatters/pretty.js\";\nimport { formatJson } from \"../../formatters/json.js\";\nimport { formatGithub } from \"../../formatters/github.js\";\n\nconst FORMATS = [\"pretty\", \"json\", \"github\"] as const;\n\nexport interface RunLintOptions {\n configDir: string;\n specPath?: string;\n preset?: \"minimal\" | \"recommended\" | \"strict\";\n}\n\n/** Lint results plus whether anything was actually linted (vacuous-pass audit). */\nexport interface RunLintResults extends LintResults {\n /** Number of spec files linted. Named for what it counts, not \"count\". */\n specFiles: number;\n /** False when no specs resolved — \"no diagnostics\" is then not a pass. */\n assessed: boolean;\n}\n\nexport async function runLint(options: RunLintOptions): Promise<RunLintResults> {\n // A JS caller omitting the option otherwise dies as ERR_INVALID_ARG_TYPE\n // deep inside path.join, with no mention of what was missing.\n if (!options.configDir) {\n throw new TypeError(\"runLint requires `configDir` — the directory holding spec.config.yaml.\");\n }\n const config = await loadConfig(undefined, options.configDir);\n const preset = options.preset ?? config.lint?.extends ?? \"recommended\";\n const rules = getPreset(preset);\n\n // Always parse the full suite so cross-reference rules have complete\n // context; a single-file lint filters the *diagnostics*, not the suite.\n const specs: ParsedSpec[] = [];\n for (const [, entry] of Object.entries(config.specs)) {\n const files = await resolveGlob(entry.path, options.configDir);\n for (const file of files) {\n specs.push(await parseSpec(file));\n }\n }\n\n let graph;\n let graphError: string | undefined;\n try {\n graph = buildGraph(config);\n } catch (err) {\n graphError = (err as Error).message;\n }\n\n const engine = createLintEngine({ rules, config, graph });\n const results = engine.lint(specs);\n\n if (options.specPath) {\n const specPath = options.specPath;\n results.diagnostics = results.diagnostics.filter((d) => d.filePath.includes(specPath));\n results.hasErrors = results.diagnostics.some((d) => d.severity === \"error\");\n results.hasWarnings = results.diagnostics.some((d) => d.severity === \"warn\");\n }\n\n if (graphError) {\n results.diagnostics.push({\n ruleId: \"structure/no-circular-deps\",\n severity: \"error\",\n message: graphError,\n filePath: \"spec.config.yaml\",\n });\n results.hasErrors = true;\n }\n\n return { ...results, specFiles: specs.length, assessed: specs.length > 0 };\n}\n\nexport default defineCommand({\n meta: { name: \"lint\", description: \"Lint all specs in the suite\" },\n args: {\n ...sharedArgs(FORMATS),\n fix: { type: \"boolean\", description: \"Auto-fix issues where possible\" },\n path: { type: \"positional\", description: \"Lint a specific spec file\", required: false },\n preset: { type: \"string\", description: \"Lint preset (minimal, recommended, strict)\" },\n },\n async run({ args }) {\n const logger = createLogger({ quiet: args.quiet, verbose: args.verbose });\n const output = createOutput({ quiet: args.quiet });\n\n const format = resolveFormat(args.format, FORMATS);\n if (!format.ok) {\n console.error(`\\n ✗ ${format.message}\\n`);\n process.exit(1);\n }\n\n if (args.fix) {\n logger.info(\"No auto-fixable issues supported yet.\");\n }\n\n try {\n const results = await runLint({\n configDir: process.cwd(),\n specPath: args.path,\n preset: args.preset as \"minimal\" | \"recommended\" | \"strict\" | undefined,\n });\n\n const formatter =\n format.format === \"json\"\n ? formatJson\n : format.format === \"github\"\n ? formatGithub\n : formatPretty;\n // \"No diagnostics\" over an empty suite is not a pass (vacuous-pass audit)\n if (!results.assessed) {\n console.error(\n \"\\n ⚠ No specs found — nothing was linted. Check the spec paths in spec.config.yaml.\\n\",\n );\n process.exit(3);\n }\n\n const rendered = formatter(results.diagnostics);\n // A clean pretty run is chrome; diagnostics and machine formats are not.\n if (format.format === \"pretty\" && results.diagnostics.length === 0) {\n output.info(rendered);\n } else {\n output.out(rendered);\n }\n\n if (results.hasErrors) process.exit(1);\n } catch (err) {\n console.error(`\\n ✗ ${(err as Error).message}\\n`);\n process.exit(1);\n }\n },\n});\n","import { readFile } from \"node:fs/promises\";\nimport { join, dirname } from \"node:path\";\nimport { parse as parseYaml } from \"yaml\";\nimport { validateConfig, type SdxConfig } from \"@specdx/schema\";\n\nexport class ConfigError extends Error {\n constructor(\n message: string,\n public readonly errors?: unknown[],\n ) {\n super(message);\n this.name = \"ConfigError\";\n }\n}\n\nconst CONFIG_FILENAME = \"spec.config.yaml\";\n\nexport async function loadConfig(filePath?: string, searchFrom?: string): Promise<SdxConfig> {\n const resolvedPath = filePath ?? (await findConfig(searchFrom ?? process.cwd()));\n if (!resolvedPath) {\n throw new ConfigError(`No ${CONFIG_FILENAME} found. Run 'specdx init' to create one.`);\n }\n\n let raw: string;\n try {\n raw = await readFile(resolvedPath, \"utf-8\");\n } catch {\n throw new ConfigError(`Cannot read config file: ${resolvedPath}`);\n }\n\n let data: Record<string, unknown>;\n try {\n data = parseYaml(raw) as Record<string, unknown>;\n } catch (err) {\n throw new ConfigError(`Invalid YAML in ${resolvedPath}: ${(err as Error).message}`);\n }\n\n const result = validateConfig(data);\n if (!result.valid) {\n throw new ConfigError(`Invalid config in ${resolvedPath}`, result.errors ?? undefined);\n }\n\n return data as unknown as SdxConfig;\n}\n\nasync function findConfig(from: string): Promise<string | undefined> {\n let dir = from;\n while (true) {\n const candidate = join(dir, CONFIG_FILENAME);\n try {\n await readFile(candidate, \"utf-8\");\n return candidate;\n } catch {\n const parent = dirname(dir);\n if (parent === dir) return undefined;\n dir = parent;\n }\n }\n}\n","import { readFile } from \"node:fs/promises\";\nimport { extname } from \"node:path\";\nimport * as grayMatterNs from \"gray-matter\";\nimport { parse as parseYaml } from \"yaml\";\nimport { unified } from \"unified\";\nimport remarkParse from \"remark-parse\";\nimport { visit } from \"unist-util-visit\";\nimport { validateSpec, type ValidationResult } from \"@specdx/schema\";\nimport type { BaseSpec, SpecType } from \"@specdx/schema\";\nimport { countTokens } from \"./tokens.js\";\n\n// gray-matter is CJS — its callable default is exposed via .default in an ESM context\ntype GrayMatterFn = (input: string) => { data: Record<string, unknown>; content: string };\nconst matter = ((grayMatterNs as unknown as { default?: GrayMatterFn }).default ??\n (grayMatterNs as unknown as GrayMatterFn)) as GrayMatterFn;\n\nexport class ParseError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"ParseError\";\n }\n}\n\nexport interface ParsedSection {\n heading: string;\n content: string;\n tokens: number;\n}\n\nexport interface ParsedSpec {\n filePath: string;\n frontmatter: BaseSpec & Record<string, unknown>;\n content: string;\n sections: string[];\n parsedSections: ParsedSection[];\n valid: boolean;\n validationErrors: ValidationResult[\"errors\"];\n}\n\nexport async function parseSpec(filePath: string): Promise<ParsedSpec> {\n let raw: string;\n try {\n raw = await readFile(filePath, \"utf-8\");\n } catch {\n throw new ParseError(`Cannot read spec file: ${filePath}`);\n }\n\n return parseSpecFromString(raw, filePath);\n}\n\nexport function parseSpecFromString(content: string, filePath: string): Promise<ParsedSpec> {\n const ext = extname(filePath).toLowerCase();\n if (ext === \".yaml\" || ext === \".yml\") {\n return Promise.resolve(parseYamlSpec(filePath, content));\n }\n return Promise.resolve(parseMarkdownSpec(filePath, content));\n}\n\nfunction parseMarkdownSpec(filePath: string, raw: string): ParsedSpec {\n const { data, content } = matter(raw);\n const parsedSections = extractParsedSections(content);\n const sections = parsedSections.map((s) => s.heading).filter(Boolean);\n const frontmatter = data as BaseSpec & Record<string, unknown>;\n const specType = frontmatter.type as SpecType | undefined;\n\n let valid = false;\n let validationErrors: ValidationResult[\"errors\"] = null;\n if (specType) {\n const result = validateSpec(specType, data);\n valid = result.valid;\n validationErrors = result.errors;\n }\n\n return { filePath, frontmatter, content, sections, parsedSections, valid, validationErrors };\n}\n\nfunction parseYamlSpec(filePath: string, raw: string): ParsedSpec {\n let data: Record<string, unknown>;\n try {\n data = parseYaml(raw) as Record<string, unknown>;\n } catch (err) {\n throw new ParseError(`Invalid YAML in ${filePath}: ${(err as Error).message}`);\n }\n\n const frontmatter = data as BaseSpec & Record<string, unknown>;\n const specType = frontmatter.type as SpecType | undefined;\n\n let valid = false;\n let validationErrors: ValidationResult[\"errors\"] = null;\n if (specType) {\n const result = validateSpec(specType, data);\n valid = result.valid;\n validationErrors = result.errors;\n }\n\n return {\n filePath,\n frontmatter,\n content: \"\",\n sections: [],\n parsedSections: [],\n valid,\n validationErrors,\n };\n}\n\nfunction extractParsedSections(markdown: string): ParsedSection[] {\n const tree = unified().use(remarkParse).parse(markdown);\n\n const h2s: { heading: string; startOffset: number; endOffset: number }[] = [];\n\n visit(tree, \"heading\", (node) => {\n if (node.depth === 2) {\n const text = (node.children as Array<{ type: string; value?: string }>)\n .filter((c) => c.type === \"text\")\n .map((c) => c.value ?? \"\")\n .join(\"\");\n h2s.push({\n heading: text,\n startOffset: node.position!.start.offset as number,\n endOffset: node.position!.end.offset as number,\n });\n }\n });\n\n const sections: ParsedSection[] = [];\n\n // Preamble: content before first H2\n const firstH2 = h2s[0];\n const firstOffset = firstH2 ? firstH2.startOffset : markdown.length;\n const preamble = markdown.slice(0, firstOffset).trim();\n if (preamble) {\n sections.push({ heading: \"\", content: preamble, tokens: countTokens(preamble) });\n }\n\n // Each H2 section: content AFTER the heading line, up to the next H2 (or end)\n for (let i = 0; i < h2s.length; i++) {\n const current = h2s[i]!;\n const next = h2s[i + 1];\n const end = next ? next.startOffset : markdown.length;\n const content = markdown.slice(current.endOffset, end).trim();\n sections.push({\n heading: current.heading,\n content,\n tokens: countTokens(content),\n });\n }\n\n return sections;\n}\n","import { encodingForModel } from \"js-tiktoken\";\n\nlet encoder: ReturnType<typeof encodingForModel> | undefined;\n\nfunction getEncoder() {\n if (!encoder) encoder = encodingForModel(\"gpt-4o\");\n return encoder;\n}\n\nexport function countTokens(text: string): number {\n if (!text) return 0;\n return getEncoder().encode(text).length;\n}\n","import type { SdxConfig } from \"@specdx/schema\";\nimport { DEPENDENCY_RELATIONSHIPS } from \"@specdx/schema\";\n\nexport class GraphError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"GraphError\";\n }\n}\n\nexport interface Edge {\n from: string;\n to: string;\n}\n\nexport interface DependencyGraph {\n nodes: string[];\n edges: Edge[];\n topologicalSort(): string[];\n getDownstream(nodeId: string): string[];\n getUpstream(nodeId: string): string[];\n}\n\nexport function buildGraph(config: SdxConfig): DependencyGraph {\n const specNames = Object.keys(config.specs);\n const adjacency = new Map<string, string[]>();\n const reverseAdj = new Map<string, string[]>();\n const edges: Edge[] = [];\n\n for (const name of specNames) {\n adjacency.set(name, []);\n reverseAdj.set(name, []);\n }\n\n for (const [name, entry] of Object.entries(config.specs)) {\n if (!entry.requires) continue;\n for (const dep of entry.requires) {\n if (!adjacency.has(dep)) {\n throw new GraphError(\n `Spec \"${name}\" requires \"${dep}\", which does not exist in the config.`,\n );\n }\n adjacency.get(dep)!.push(name);\n reverseAdj.get(name)!.push(dep);\n edges.push({ from: dep, to: name });\n }\n }\n\n // Kahn's algorithm for cycle detection + topological sort\n const inDegree = new Map<string, number>();\n for (const name of specNames) inDegree.set(name, reverseAdj.get(name)!.length);\n\n const queue: string[] = [];\n for (const [name, degree] of inDegree) {\n if (degree === 0) queue.push(name);\n }\n\n const sorted: string[] = [];\n while (queue.length > 0) {\n const node = queue.shift()!;\n sorted.push(node);\n for (const neighbor of adjacency.get(node)!) {\n const newDegree = inDegree.get(neighbor)! - 1;\n inDegree.set(neighbor, newDegree);\n if (newDegree === 0) queue.push(neighbor);\n }\n }\n\n if (sorted.length !== specNames.length) {\n const remaining = specNames.filter((n) => !sorted.includes(n));\n throw new GraphError(`Circular dependency detected involving: ${remaining.join(\", \")}`);\n }\n\n return {\n nodes: specNames,\n edges,\n topologicalSort: () => [...sorted],\n getDownstream(nodeId: string): string[] {\n const visited = new Set<string>();\n const stack = [nodeId];\n while (stack.length > 0) {\n const current = stack.pop()!;\n for (const neighbor of adjacency.get(current) ?? []) {\n if (!visited.has(neighbor)) {\n visited.add(neighbor);\n stack.push(neighbor);\n }\n }\n }\n return [...visited];\n },\n getUpstream(nodeId: string): string[] {\n const visited = new Set<string>();\n const stack = [nodeId];\n while (stack.length > 0) {\n const current = stack.pop()!;\n for (const dep of reverseAdj.get(current) ?? []) {\n if (!visited.has(dep)) {\n visited.add(dep);\n stack.push(dep);\n }\n }\n }\n return [...visited];\n },\n };\n}\n\n/** A relationship edge declared in a spec's frontmatter `references`. */\nexport interface ReferenceEdge {\n fromId: string;\n toId: string;\n relationship: string;\n}\n\n// The dependency-implying taxonomy lives in @specdx/schema so it is versioned\n// with the schema it describes, rather than hardcoded here (ADR:\n// references/requires unification).\n\n/**\n * Collect relationship edges declared in spec frontmatter `references` fields.\n * Edges point from the declaring spec's id to the referenced spec's id.\n */\nexport function collectReferenceEdges(\n specs: { frontmatter: Record<string, unknown> }[],\n): ReferenceEdge[] {\n const edges: ReferenceEdge[] = [];\n for (const spec of specs) {\n const fromId = spec.frontmatter.id;\n if (typeof fromId !== \"string\") continue;\n const refs = spec.frontmatter.references;\n if (!Array.isArray(refs)) continue;\n for (const ref of refs) {\n if (ref && typeof ref === \"object\" && \"id\" in ref) {\n const r = ref as { id: unknown; relationship?: unknown };\n if (typeof r.id === \"string\") {\n edges.push({\n fromId,\n toId: r.id,\n relationship: typeof r.relationship === \"string\" ? r.relationship : \"related-to\",\n });\n }\n }\n }\n }\n return edges;\n}\n\n/**\n * Find dependency-implying frontmatter references that the config-level\n * `requires` graph does not reflect. `idToEntry` maps spec frontmatter ids to\n * config entry keys. References within the same entry (e.g. story-to-story\n * under one glob) and references to unmapped ids are skipped — reference\n * existence itself is the `structure/valid-references` lint rule's concern.\n */\nexport interface UnreflectedReference {\n edge: ReferenceEdge;\n requiringEntry: string;\n requiredEntry: string;\n /** True when adding the suggested requires edge would create a cycle. */\n createsCycle: boolean;\n}\n\nexport function findUnreflectedReferences(\n referenceEdges: ReferenceEdge[],\n idToEntry: Map<string, string>,\n graph: DependencyGraph,\n): UnreflectedReference[] {\n const configEdges = new Set(graph.edges.map((e) => `${e.from}→${e.to}`));\n const missing: UnreflectedReference[] = [];\n\n for (const edge of referenceEdges) {\n const direction = DEPENDENCY_RELATIONSHIPS[edge.relationship as never];\n if (!direction) continue;\n\n const selfEntry = idToEntry.get(edge.fromId);\n const targetEntry = idToEntry.get(edge.toId);\n if (!selfEntry || !targetEntry || selfEntry === targetEntry) continue;\n\n const requiringEntry = direction === \"self-requires-target\" ? selfEntry : targetEntry;\n const requiredEntry = direction === \"self-requires-target\" ? targetEntry : selfEntry;\n\n // Config edges point dependency → dependent\n if (!configEdges.has(`${requiredEntry}→${requiringEntry}`)) {\n // The suggested edge closes a cycle when the required entry is already\n // downstream of the requiring one (issue #13) — never recommend it.\n const createsCycle = graph.getDownstream(requiringEntry).includes(requiredEntry);\n missing.push({ edge, requiringEntry, requiredEntry, createsCycle });\n }\n }\n\n return missing;\n}\n","import type { SdxConfig } from \"@specdx/schema\";\nimport { DEPENDENCY_RELATIONSHIPS } from \"@specdx/schema\";\n\n/** Where a relation edge was declared. */\nexport type RelationSource = \"requires\" | \"references\" | \"both\";\n\n/** A dependency edge in **spec id** space, pointing upstream → downstream. */\nexport interface RelationEdge {\n /** Spec id of the dependency. */\n from: string;\n /** Spec id of the dependent. */\n to: string;\n /** Which declaration(s) produced this edge. */\n source: RelationSource;\n}\n\n/**\n * Answers \"what is upstream / downstream of this spec?\" in spec id space.\n *\n * specdx declares relationships two ways: config `requires` (keyed by config\n * entry, glob-aware, cheap) and frontmatter `references` (keyed by spec id,\n * typed). Consumers used to read one or the other, so the same question got\n * different answers — `freshness/staleness-check` saw only references, while\n * impact analysis saw only the config graph. This resolver unions both at\n * query time so every consumer agrees, without changing which source owns\n * graph topology (ADR: references/requires unification, Option B).\n */\nexport interface RelationResolver {\n /** All dependency edges, in spec id space, deduplicated. */\n edges: RelationEdge[];\n /** Spec ids this spec depends on, transitively. */\n getUpstream(specId: string): string[];\n /** Spec ids that depend on this spec, transitively. */\n getDownstream(specId: string): string[];\n}\n\ninterface SpecLike {\n frontmatter: Record<string, unknown>;\n}\n\n/** Map each config entry key to the spec ids its path resolved to. */\nfunction mapEntriesToIds(\n config: SdxConfig,\n specsByEntry: Map<string, SpecLike[]>,\n): Map<string, string[]> {\n const entryIds = new Map<string, string[]>();\n for (const key of Object.keys(config.specs)) {\n const ids: string[] = [];\n for (const spec of specsByEntry.get(key) ?? []) {\n const id = spec.frontmatter.id;\n if (typeof id === \"string\") ids.push(id);\n }\n entryIds.set(key, ids);\n }\n return entryIds;\n}\n\n/** Every spec id present, regardless of which entry it came from. */\nfunction collectKnownIds(specsByEntry: Map<string, SpecLike[]>): Set<string> {\n const ids = new Set<string>();\n for (const specs of specsByEntry.values()) {\n for (const spec of specs) {\n const id = spec.frontmatter.id;\n if (typeof id === \"string\") ids.add(id);\n }\n }\n return ids;\n}\n\nfunction walk(specId: string, adjacency: Map<string, string[]>): string[] {\n const visited = new Set<string>();\n const stack = [specId];\n while (stack.length > 0) {\n const current = stack.pop()!;\n for (const next of adjacency.get(current) ?? []) {\n if (!visited.has(next)) {\n visited.add(next);\n stack.push(next);\n }\n }\n }\n visited.delete(specId);\n return [...visited];\n}\n\n/**\n * Build a resolver from config `requires` and dependency-implying frontmatter\n * `references`.\n *\n * A glob entry is one config entry but many spec ids, so one `requires` edge\n * between entries expands to the cross-product of their spec ids. Structural\n * reference kinds (`decomposed-into`, `supersedes`, `related-to`) are not\n * dependency-implying and are excluded — see DEPENDENCY_RELATIONSHIPS.\n *\n * @param config - Spec config. When undefined, only frontmatter references\n * contribute edges — useful for callers that have specs but no config.\n * @param specsByEntry - Parsed specs grouped by the config entry key they resolved from.\n */\nexport function buildRelationResolver(\n config: SdxConfig | undefined,\n specsByEntry: Map<string, SpecLike[]>,\n): RelationResolver {\n const entryIds = config ? mapEntriesToIds(config, specsByEntry) : new Map<string, string[]>();\n const knownIds = collectKnownIds(specsByEntry);\n\n // key \"from→to\" -> source, so a relation declared both ways is one edge\n const edgeSources = new Map<string, RelationSource>();\n const addEdge = (from: string, to: string, source: \"requires\" | \"references\"): void => {\n if (from === to) return;\n const key = `${from}\u0000${to}`;\n const existing = edgeSources.get(key);\n if (!existing) {\n edgeSources.set(key, source);\n } else if (existing !== source) {\n edgeSources.set(key, \"both\");\n }\n };\n\n // 1. Config requires: entry-level edges expand across the entries' spec ids\n for (const [key, entry] of Object.entries(config?.specs ?? {})) {\n const requires = (entry as { requires?: string[] }).requires ?? [];\n for (const dep of requires) {\n for (const from of entryIds.get(dep) ?? []) {\n for (const to of entryIds.get(key) ?? []) {\n addEdge(from, to, \"requires\");\n }\n }\n }\n }\n\n // 2. Frontmatter references, already in spec id space\n for (const specs of specsByEntry.values()) {\n for (const spec of specs) {\n const selfId = spec.frontmatter.id;\n if (typeof selfId !== \"string\") continue;\n const refs = spec.frontmatter.references;\n if (!Array.isArray(refs)) continue;\n\n for (const ref of refs) {\n if (!ref || typeof ref !== \"object\") continue;\n const { id: targetId, relationship } = ref as { id?: unknown; relationship?: unknown };\n if (typeof targetId !== \"string\" || typeof relationship !== \"string\") continue;\n // Referencing a spec outside the suite is valid-references' concern.\n if (!knownIds.has(targetId)) continue;\n\n const direction = DEPENDENCY_RELATIONSHIPS[relationship as never];\n if (direction === \"self-requires-target\") {\n addEdge(targetId, selfId, \"references\");\n } else if (direction === \"target-requires-self\") {\n addEdge(selfId, targetId, \"references\");\n }\n }\n }\n }\n\n const edges: RelationEdge[] = [];\n const downstreamAdj = new Map<string, string[]>();\n const upstreamAdj = new Map<string, string[]>();\n\n for (const [key, source] of edgeSources) {\n const [from, to] = key.split(\"\u0000\") as [string, string];\n edges.push({ from, to, source });\n downstreamAdj.set(from, [...(downstreamAdj.get(from) ?? []), to]);\n upstreamAdj.set(to, [...(upstreamAdj.get(to) ?? []), from]);\n }\n\n return {\n edges,\n getUpstream: (specId) => walk(specId, upstreamAdj),\n getDownstream: (specId) => walk(specId, downstreamAdj),\n };\n}\n","import { glob } from \"tinyglobby\";\nimport { join, isAbsolute } from \"node:path\";\n\nexport async function resolveGlob(pattern: string, baseDir: string): Promise<string[]> {\n const absolutePattern = isAbsolute(pattern) ? pattern : join(baseDir, pattern);\n return glob([absolutePattern], { absolute: true });\n}\n","import { createConsola, type ConsolaInstance } from \"consola\";\n\nexport type LogLevel = \"debug\" | \"info\" | \"warn\" | \"error\";\n\nexport interface LoggerOptions {\n quiet?: boolean;\n verbose?: boolean;\n}\n\nexport interface Logger extends ConsolaInstance {\n level: number;\n}\n\nexport function createLogger(options?: LoggerOptions): Logger {\n let level = 3; // info\n if (options?.quiet) level = 1; // only errors\n if (options?.verbose) level = 4; // debug\n return createConsola({ level }) as Logger;\n}\n","import { readFile } from \"node:fs/promises\";\nimport { resolve, isAbsolute } from \"node:path\";\nimport { ConfigError } from \"./config.js\";\n\nconst BUILTINS = [\"minimal\", \"recommended\", \"strict\"];\n\n/**\n * Resolve a preset name to its config content.\n * Returns null for built-in presets (handled by @specdx/lint).\n * Resolves local file paths and npm package names.\n */\nexport async function resolvePreset(\n name: string,\n cwd = process.cwd(),\n): Promise<Record<string, unknown> | null> {\n if (BUILTINS.includes(name)) {\n return null;\n }\n\n // Try local file path\n const localPath = isAbsolute(name) ? name : resolve(cwd, name);\n try {\n const content = await readFile(localPath, \"utf-8\");\n const { default: yaml } = await import(\"yaml\");\n return yaml.parse(content) as Record<string, unknown>;\n } catch {\n // Not a local file, try npm\n }\n\n // Try npm package\n try {\n const mod = (await import(name)) as { default?: Record<string, unknown> };\n return (mod.default ?? mod) as Record<string, unknown>;\n } catch {\n throw new ConfigError(`Could not resolve preset \"${name}\" as a local file or npm package`);\n }\n}\n","import type { ParsedSpec, DependencyGraph } from \"@specdx/core\";\nimport type { SdxConfig } from \"@specdx/schema\";\nimport type { LintRule, LintResults, Diagnostic } from \"./types.js\";\n\nexport interface LintEngineOptions {\n rules: LintRule[];\n config?: SdxConfig;\n graph?: DependencyGraph;\n}\n\nexport interface LintEngine {\n lint(specs: ParsedSpec[]): LintResults;\n}\n\nexport function createLintEngine(options: LintEngineOptions): LintEngine {\n return {\n lint(specs: ParsedSpec[]): LintResults {\n const diagnostics: Diagnostic[] = [];\n for (const spec of specs) {\n for (const rule of options.rules) {\n const results = rule.run({\n spec,\n allSpecs: specs,\n config: options.config,\n graph: options.graph,\n });\n // The rule object's `severity` is the authority, not the severity a\n // rule happens to write into the diagnostic it returns.\n //\n // Every built-in rule emits exactly one severity -- its own -- but ten\n // of them hardcoded it as a literal in the diagnostic. Presets rewrite\n // `rule.severity`, so nothing downstream read what `strict` set, and\n // `--preset strict` produced output byte-identical to `recommended` on\n // the CLI, in `extends:`, in the Action's `preset` input and in\n // `runLint({ preset })`. Stamping it here is what makes a preset mean\n // anything.\n for (const diagnostic of results) {\n diagnostics.push({ ...diagnostic, severity: rule.severity });\n }\n }\n }\n return {\n diagnostics,\n hasErrors: diagnostics.some((d) => d.severity === \"error\"),\n hasWarnings: diagnostics.some((d) => d.severity === \"warn\"),\n };\n },\n };\n}\n","import type { LintRule } from \"../types.js\";\n\n/**\n * The shape of an ajv error, described structurally.\n *\n * Typed here rather than imported so the lint package does not take a\n * dependency on ajv for a single type.\n */\ninterface ValidationError {\n instancePath?: string;\n message?: string;\n params?: Record<string, unknown>;\n}\n\n/** `/references/0/relationship` -> `references[0].relationship`. */\nfunction readablePath(instancePath: string): string {\n return instancePath\n .split(\"/\")\n .filter(Boolean)\n .map((segment) => (/^\\d+$/.test(segment) ? `[${segment}]` : `.${segment}`))\n .join(\"\")\n .replace(/^\\./, \"\");\n}\n\n/**\n * Turn one ajv error into something a spec author can act on.\n *\n * ajv only names the offending field inside `message` for `required`\n * violations. For `enum`, `const` and `type` the field lives in `instancePath`\n * and the acceptable values in `params`, so a bare `err.message` reads\n * \"must be equal to one of the allowed values\" and identifies nothing -- which\n * is what every `references:` entry produced.\n */\nexport function describeValidationError(err: ValidationError): string {\n const path = readablePath(err.instancePath ?? \"\");\n const allowed = (err.params as { allowedValues?: unknown[] } | undefined)?.allowedValues;\n\n let detail = err.message ?? JSON.stringify(err);\n if (Array.isArray(allowed) && allowed.length > 0) {\n detail += `: ${allowed.map((v) => JSON.stringify(v)).join(\", \")}`;\n }\n\n return path ? `${path} ${detail}` : detail;\n}\n\nexport const validFrontmatterRule: LintRule = {\n id: \"structure/valid-frontmatter\",\n description: \"Frontmatter matches the schema for the declared spec type\",\n severity: \"error\",\n run(context) {\n if (context.spec.valid) return [];\n const errors = context.spec.validationErrors ?? [];\n return errors.map((err) => ({\n ruleId: \"structure/valid-frontmatter\",\n severity: \"error\" as const,\n message: `Invalid frontmatter: ${describeValidationError(err)}`,\n filePath: context.spec.filePath,\n }));\n },\n};\n","import type { LintRule } from \"../types.js\";\nimport { REQUIRED_SECTIONS } from \"@specdx/schema\";\nimport type { SpecType } from \"@specdx/schema\";\n\nexport const requiredSectionsRule: LintRule = {\n id: \"structure/required-sections\",\n description: \"Spec body contains all required sections for its type\",\n severity: \"error\",\n run(context) {\n // Skip YAML specs (no markdown body)\n const ext = context.spec.filePath.split(\".\").pop()?.toLowerCase();\n if (ext === \"yaml\" || ext === \"yml\") return [];\n\n const specType = context.spec.frontmatter.type as SpecType;\n const required = REQUIRED_SECTIONS[specType];\n if (!required) return [];\n\n const missing = required.filter((s) => !context.spec.sections.includes(s));\n return missing.map((section) => ({\n ruleId: \"structure/required-sections\",\n severity: \"error\" as const,\n message: `Missing required section: \"${section}\"`,\n filePath: context.spec.filePath,\n section,\n }));\n },\n};\n","import type { LintRule } from \"../types.js\";\n\nexport const validReferencesRule: LintRule = {\n id: \"structure/valid-references\",\n description: \"All references in frontmatter point to specs that exist in the suite\",\n severity: \"error\",\n run(context) {\n const refs = context.spec.frontmatter.references;\n if (!refs || refs.length === 0) return [];\n const allIds = new Set(context.allSpecs.map((s) => s.frontmatter.id));\n return refs\n .filter((ref) => !allIds.has(ref.id))\n .map((ref) => ({\n ruleId: \"structure/valid-references\",\n severity: \"error\" as const,\n message: `Reference \"${ref.id}\" does not match any spec in the suite`,\n filePath: context.spec.filePath,\n }));\n },\n};\n","import type { LintRule } from \"../types.js\";\n\nexport const noCircularDepsRule: LintRule = {\n id: \"structure/no-circular-deps\",\n description: \"The dependency graph has no cycles\",\n severity: \"error\",\n run() {\n // Cycle detection happens in buildGraph() — if graph construction succeeds, it's acyclic.\n // GraphErrors are surfaced as diagnostics by the lint command, not by this rule.\n return [];\n },\n};\n","import type { LintRule } from \"../types.js\";\nimport type { ParsedSpec } from \"@specdx/core\";\n\n/** Words carrying no signal about what a feature is. */\nconst STOPWORDS = new Set([\n \"a\",\n \"an\",\n \"the\",\n \"and\",\n \"or\",\n \"of\",\n \"to\",\n \"for\",\n \"with\",\n \"its\",\n \"it\",\n \"in\",\n \"on\",\n \"at\",\n \"by\",\n \"from\",\n \"into\",\n \"every\",\n \"each\",\n \"that\",\n \"this\",\n \"be\",\n \"is\",\n \"are\",\n \"as\",\n \"can\",\n \"will\",\n \"must\",\n \"so\",\n \"their\",\n \"them\",\n \"when\",\n \"which\",\n \"who\",\n]);\n\n/** Share of a feature's words a story must echo to count as covering it. */\nconst OVERLAP_THRESHOLD = 0.5;\n\n/** Lower bar for a story that explicitly references the PRD. */\nconst REFERENCED_THRESHOLD = 0.34;\n\nfunction tokenise(text: string): Set<string> {\n const words = text\n .toLowerCase()\n .replace(/[^a-z0-9\\s-]/g, \" \")\n .split(/\\s+/)\n .filter((w) => w.length > 2 && !STOPWORDS.has(w))\n // Crude singularisation, so \"actions\" matches \"action\".\n .map((w) => (w.length > 3 && w.endsWith(\"s\") && !w.endsWith(\"ss\") ? w.slice(0, -1) : w));\n return new Set(words);\n}\n\nfunction extractFeatureSection(content: string): string | null {\n // Scanned line by line rather than with one regex: `$` and `\\Z` behave\n // differently enough across multiline modes to make the regex form a trap.\n const lines = content.split(\"\\n\");\n const start = lines.findIndex((l) => /^##\\s+Features\\s*$/.test(l.trim()));\n if (start === -1) return null;\n const body: string[] = [];\n for (let i = start + 1; i < lines.length; i++) {\n if (/^##\\s/.test(lines[i]!)) break;\n body.push(lines[i]!);\n }\n return body.join(\"\\n\");\n}\n\n/**\n * Feature descriptions from a PRD's Features section.\n *\n * Previously only `- **F1**: text` was recognised, so a PRD written any other\n * way parsed to zero features and the rule passed vacuously -- which `ready`\n * then reported as \"all features have stories\" over an empty set.\n */\nexport function parseFeatures(content: string): string[] {\n return parseFeatureEntries(content).map((f) => f.text);\n}\n\n/** A PRD feature, with its `F<N>` number when the author gave it one. */\nexport interface FeatureEntry {\n /** The feature description, with any ID prefix removed. */\n text: string;\n /** The `N` from `**F<N>**:`, when present. */\n num?: string;\n}\n\n/**\n * The single source of truth for what counts as a feature in a PRD.\n *\n * `generate story` used to carry its own regex requiring `**F<N>**:`, so on a\n * PRD without those IDs the lint rule reported three features and the generator\n * reported none -- two commands in the same suite contradicting each other over\n * one file. Anything that needs to know what a PRD's features are calls this.\n */\nexport function parseFeatureEntries(content: string): FeatureEntry[] {\n const section = extractFeatureSection(content);\n if (section === null) return [];\n\n /** `**F1**:`, `F1:`, `F1 -` — an optional feature ID prefix. */\n const ID_PREFIX = /^\\*{0,2}F(\\d+)\\*{0,2}\\s*[:.-]\\s*/i;\n\n const features: FeatureEntry[] = [];\n for (const rawLine of section.split(\"\\n\")) {\n const line = rawLine.trim();\n if (!line) continue;\n\n const bullet = /^[-*]\\s+(.*)$/.exec(line);\n // A bullet is a feature whether or not it carries an ID. A non-bullet line\n // counts only when it does, so ordinary prose in the section is not\n // mistaken for a feature list.\n const text = bullet ? (bullet[1] ?? \"\").trim() : ID_PREFIX.test(line) ? line : \"\";\n if (!text) continue;\n\n const idMatch = ID_PREFIX.exec(text);\n const stripped = text.replace(ID_PREFIX, \"\").trim();\n if (stripped) features.push({ text: stripped, num: idMatch?.[1] });\n }\n return features;\n}\n\nfunction overlap(featureTokens: Set<string>, storyTokens: Set<string>): number {\n if (featureTokens.size === 0) return 0;\n let shared = 0;\n for (const token of featureTokens) if (storyTokens.has(token)) shared++;\n return shared / featureTokens.size;\n}\n\nfunction referencesSpec(story: ParsedSpec, specId: unknown): boolean {\n const refs = story.frontmatter.references;\n if (!Array.isArray(refs)) return false;\n return refs.some((r) => (r as { id?: unknown })?.id === specId);\n}\n\n/**\n * Features from `features` that no story in `stories` appears to cover.\n *\n * Exported so the linter and `generate story` share one definition of\n * \"covered\". They had two, which is why the rule warned about features that\n * had stories while the generator re-stubbed features that already had them.\n */\nexport function uncoveredFeatures(\n features: string[],\n stories: ParsedSpec[],\n prdId: unknown,\n): string[] {\n const scored = stories.map((story) => ({\n tokens: tokenise(`${String(story.frontmatter.title ?? \"\")} ${story.content}`),\n threshold: referencesSpec(story, prdId) ? REFERENCED_THRESHOLD : OVERLAP_THRESHOLD,\n }));\n\n const tokenised = features.map(tokenise);\n\n return features.filter((_feature, i) => {\n const featureTokens = tokenised[i]!;\n // What makes *this* feature different from its siblings. Share of words\n // alone is not enough: \"Export the payroll report as PDF\" and \"Export the\n // invoice report as CSV\" agree on half their words, so a story covering one\n // was read as covering both -- and `ready` then asserted that every feature\n // had a story while one plainly had none. A story only covers a feature if\n // it also mentions something that sets that feature apart.\n const distinctive = distinctiveTokens(featureTokens, tokenised, i);\n return !scored.some(\n (s) =>\n overlap(featureTokens, s.tokens) >= s.threshold &&\n covers(distinctive, featureTokens, s.tokens),\n );\n });\n}\n\n/**\n * Whether a story picks up more than half of what sets a feature apart from its\n * siblings.\n *\n * One distinctive word is not enough on its own. \"List customers for the\n * finance console\" is set apart by *finance* and *console*, and a story about\n * amending invoices that opens \"as a member of finance\" hits one of the two —\n * enough to be waved through by a \"matches something distinctive\" test, and\n * plainly not a story about the finance console.\n *\n * Two cases hand the decision back to the overlap threshold alone, because in\n * both of them distinctiveness carries no information:\n *\n * - Nothing is distinctive. Two features written in near-identical words are\n * genuinely indistinguishable to a word-overlap rule.\n * - Everything is distinctive. No sibling shares a word, so no sibling's\n * vocabulary inflated the overlap score in the first place — and demanding\n * half of a long feature description would reject the short, accurate story\n * titles this rule exists to accept.\n */\nfunction covers(\n distinctive: Set<string>,\n featureTokens: Set<string>,\n storyTokens: Set<string>,\n): boolean {\n if (distinctive.size === 0 || distinctive.size === featureTokens.size) return true;\n let matched = 0;\n for (const token of distinctive) if (storyTokens.has(token)) matched++;\n return matched > distinctive.size / 2;\n}\n\n/**\n * The tokens of `features[index]` that no sibling feature uses.\n */\nfunction distinctiveTokens(\n featureTokens: Set<string>,\n allFeatureTokens: Set<string>[],\n index: number,\n): Set<string> {\n const distinctive = new Set(featureTokens);\n for (let i = 0; i < allFeatureTokens.length; i++) {\n if (i === index) continue;\n for (const token of allFeatureTokens[i]!) distinctive.delete(token);\n }\n return distinctive;\n}\n\nexport const storyCoverageRule: LintRule = {\n id: \"completeness/story-coverage\",\n description: \"Every feature listed in a PRD has at least one corresponding user story\",\n severity: \"warn\",\n run(context) {\n if (context.spec.frontmatter.type !== \"prd\") return [];\n\n const features = parseFeatures(context.spec.content);\n if (features.length === 0) return [];\n\n const stories = context.allSpecs.filter((s) => s.frontmatter.type === \"user-story\");\n\n return uncoveredFeatures(features, stories, context.spec.frontmatter.id).map((feature) => ({\n ruleId: \"completeness/story-coverage\",\n severity: \"warn\" as const,\n message: `Feature \"${feature}\" has no corresponding user story`,\n filePath: context.spec.filePath,\n }));\n },\n};\n","import { buildRelationResolver } from \"@specdx/core\";\nimport type { ParsedSpec } from \"@specdx/core\";\nimport type { SdxConfig } from \"@specdx/schema\";\nimport type { LintRule } from \"../types.js\";\n\n/**\n * Group specs by the config entry whose glob they came from, so config\n * `requires` edges can be mapped into spec id space. Matching is by the entry\n * path's directory prefix, which is enough for the resolver: an id that maps\n * to no entry simply contributes no `requires` edges.\n */\nfunction groupByEntry(config: SdxConfig, specs: ParsedSpec[]): Map<string, ParsedSpec[]> {\n const byEntry = new Map<string, ParsedSpec[]>();\n for (const key of Object.keys(config.specs)) byEntry.set(key, []);\n\n for (const spec of specs) {\n let bestKey: string | undefined;\n let bestLen = -1;\n for (const [key, entry] of Object.entries(config.specs)) {\n const prefix = entry.path.split(\"*\")[0] ?? \"\";\n const normalized = spec.filePath.replace(/\\\\/g, \"/\");\n if (normalized.includes(prefix) && prefix.length > bestLen) {\n bestKey = key;\n bestLen = prefix.length;\n }\n }\n if (bestKey) byEntry.get(bestKey)!.push(spec);\n }\n return byEntry;\n}\n\nfunction lastUpdated(spec: ParsedSpec): string {\n return (\n (spec.frontmatter.updated as string | undefined) ?? (spec.frontmatter.created as string) ?? \"\"\n );\n}\n\nexport const stalenessCheckRule: LintRule = {\n id: \"freshness/staleness-check\",\n description: \"Warns if a spec hasn't been updated since its upstream dependency changed\",\n severity: \"warn\",\n run(context) {\n const specId = context.spec.frontmatter.id;\n if (typeof specId !== \"string\") return [];\n\n const specUpdated = lastUpdated(context.spec);\n if (!specUpdated) return [];\n const specDate = new Date(specUpdated);\n\n // Upstream comes from config `requires` and frontmatter `references`\n // unioned, so a suite declaring dependencies either way gets the same\n // answer (ADR: references/requires unification).\n const byEntry = context.config\n ? groupByEntry(context.config, context.allSpecs)\n : new Map([[\"\", context.allSpecs]]);\n const relations = buildRelationResolver(context.config, byEntry);\n const upstreamIds = relations.getUpstream(specId);\n\n const diagnostics = [];\n for (const upstreamId of upstreamIds) {\n const upstream = context.allSpecs.find((s) => s.frontmatter.id === upstreamId);\n if (!upstream) continue;\n const upstreamUpdated = lastUpdated(upstream);\n if (!upstreamUpdated) continue;\n\n if (new Date(upstreamUpdated) > specDate) {\n diagnostics.push({\n ruleId: \"freshness/staleness-check\",\n severity: \"warn\" as const,\n message: `Potentially stale: upstream \"${upstreamId}\" was updated on ${upstreamUpdated}, but this spec was last updated on ${specUpdated}`,\n filePath: context.spec.filePath,\n });\n }\n }\n return diagnostics;\n },\n};\n","import type { LintRule } from \"../types.js\";\n\nconst DEFAULT_VAGUE_PATTERNS = [\n \"as appropriate\",\n \"handle edge cases\",\n \"as needed\",\n \"etc\\\\.\",\n \"TBD\",\n \"TODO\",\n \"and so on\",\n \"various\",\n \"somehow\",\n \"straightforward\",\n \"obviously\",\n \"simply\",\n \"just need to\",\n];\n\nexport const noVagueLanguageRule: LintRule = {\n id: \"clarity/no-vague-language\",\n description: \"Flags known ambiguous phrases\",\n severity: \"warn\",\n run(context) {\n if (!context.spec.content) return [];\n const diagnostics = [];\n for (const pattern of DEFAULT_VAGUE_PATTERNS) {\n const regex = new RegExp(`\\\\b${pattern}`, \"gi\");\n let match;\n while ((match = regex.exec(context.spec.content)) !== null) {\n diagnostics.push({\n ruleId: \"clarity/no-vague-language\",\n severity: \"warn\" as const,\n message: `Vague language: \"${match[0]}\"`,\n filePath: context.spec.filePath,\n });\n }\n }\n return diagnostics;\n },\n};\n","import type { LintRule } from \"../types.js\";\n\nexport const singleProjectContextRule: LintRule = {\n id: \"structure/single-project-context\",\n description: \"Only one project-context spec should exist per suite\",\n severity: \"warn\",\n run(context) {\n if (context.spec.frontmatter.type !== \"project-context\") return [];\n\n const contextSpecs = context.allSpecs.filter((s) => s.frontmatter.type === \"project-context\");\n\n if (contextSpecs.length > 1) {\n return [\n {\n ruleId: \"structure/single-project-context\",\n severity: \"warn\" as const,\n message: `Multiple project-context specs found (${contextSpecs.length}). Only one should exist per suite.`,\n filePath: context.spec.filePath,\n },\n ];\n }\n\n return [];\n },\n};\n","import type { LintRule } from \"../types.js\";\n\nfunction normalizeCompound(term: string): string {\n // Split camelCase: \"UserProfile\" → \"user profile\"\n // Split hyphens/underscores: \"user-profile\" → \"user profile\"\n return term\n .replace(/([a-z])([A-Z])/g, \"$1 $2\")\n .replace(/[-_]/g, \" \")\n .toLowerCase()\n .trim();\n}\n\nfunction extractCompoundTerms(content: string): string[] {\n const terms: string[] = [];\n\n // Extract camelCase words (e.g., UserProfile, userProfile)\n const camelCaseRegex = /\\b[a-zA-Z]*[a-z][A-Z][a-zA-Z]*\\b/g;\n let match;\n while ((match = camelCaseRegex.exec(content)) !== null) {\n terms.push(match[0]);\n }\n\n // Extract hyphenated words (e.g., user-profile, my-component)\n const hyphenatedRegex = /\\b[a-z][a-z0-9]*(?:-[a-z][a-z0-9]*)+\\b/g;\n while ((match = hyphenatedRegex.exec(content)) !== null) {\n terms.push(match[0]);\n }\n\n return terms;\n}\n\nexport const terminologyRule: LintRule = {\n id: \"consistency/terminology\",\n description:\n \"Detects terminology drift (e.g., user-profile vs UserProfile vs user profile) across specs\",\n severity: \"warn\",\n run(context) {\n // Only run on the first spec to avoid duplicate diagnostics\n if (context.spec !== context.allSpecs[0]) return [];\n\n // Build a map: normalized form → Set of original forms found across all specs\n const termMap = new Map<string, Set<string>>();\n\n for (const spec of context.allSpecs) {\n if (!spec.content) continue;\n const terms = extractCompoundTerms(spec.content);\n for (const term of terms) {\n const normalized = normalizeCompound(term);\n // Only track multi-word normalized forms (skip single words)\n if (!normalized.includes(\" \")) continue;\n if (!termMap.has(normalized)) {\n termMap.set(normalized, new Set());\n }\n termMap.get(normalized)!.add(term);\n }\n }\n\n const diagnostics = [];\n\n for (const [normalized, variants] of termMap) {\n if (variants.size >= 2) {\n const variantList = [...variants].join(\", \");\n diagnostics.push({\n ruleId: \"consistency/terminology\",\n severity: \"warn\" as const,\n message: `Inconsistent terminology for \"${normalized}\": found variants [${variantList}]. Standardize terminology across specs.`,\n filePath: context.spec.filePath,\n });\n }\n }\n\n return diagnostics;\n },\n};\n","import type { LintRule } from \"../types.js\";\n\nconst EDGE_CASE_KEYWORDS = [\n \"error\",\n \"invalid\",\n \"empty\",\n \"timeout\",\n \"fails\",\n \"failure\",\n \"boundary\",\n \"edge case\",\n \"null\",\n \"undefined\",\n \"reject\",\n \"unauthorized\",\n \"forbidden\",\n \"missing\",\n \"malformed\",\n \"overflow\",\n \"duplicate\",\n \"graceful\",\n \"fall back\",\n \"fallback\",\n \"crash\",\n \"nonexistent\",\n \"corrupt\",\n // Vocabulary that names a failure without using any of the words above.\n \"conflict\",\n \"denied\",\n \"expired\",\n \"not found\",\n \"retry\",\n \"rate limit\",\n \"unavailable\",\n \"unprocessable\",\n];\n\n/**\n * Any 4xx or 5xx status code counts as naming an error path.\n *\n * The list above held `404` and `500` and no other code, so a story whose only\n * error case was a 409 read as having no error handling at all -- changing that\n * one token to 404 silenced the warning with nothing else altered. Enumerating\n * codes was always going to be arbitrary; matching the class is not.\n */\nconst ERROR_STATUS_CODE = /\\b[45]\\d{2}\\b/;\n\n/** The section a test plan is required to carry, and where its cases belong. */\nconst EDGE_CASE_SECTION = \"edge cases\";\n\n/** Bodies that say \"nothing has been written here yet\". */\nconst PLACEHOLDER_BODIES = /^(todo|tbd|fixme|n\\/a|na|none|xxx|\\.{2,}|-|\\*)$/i;\n\n/** Bodies that answer the question with \"there aren't any\", which is not coverage. */\nconst DISCLAIMED_BODIES = /^(none|no|nothing|n\\/a)\\b[\\s\\S]{0,40}$/i;\n\n/** Strip HTML comments, list bullets and separators to expose the real body. */\nfunction meaningfulContent(content: string): string {\n return content\n .replace(/<!--[\\s\\S]*?-->/g, \"\")\n .split(\"\\n\")\n .map((line) => line.replace(/^\\s*[-*+]\\s+/, \"\").trim())\n .filter((line) => line.length > 0 && !/^-{3,}$/.test(line))\n .join(\"\\n\")\n .trim();\n}\n\nexport const edgeCaseCoverageRule: LintRule = {\n id: \"completeness/edge-case-coverage\",\n description: \"Flag user stories or test plans that don't mention error states or edge cases\",\n severity: \"warn\",\n run(context) {\n const type = context.spec.frontmatter.type as string;\n if (type !== \"user-story\" && type !== \"test-plan\") return [];\n\n // A test plan is *required* to carry an `## Edge Cases` heading, so scanning\n // the whole document for the words \"edge case\" matched the scaffolding and\n // nothing else -- the rule could never fire on the half of its scope that\n // has a dedicated home for the answer. Judge that section's body instead.\n const section = context.spec.parsedSections.find(\n (s) => s.heading.trim().toLowerCase() === EDGE_CASE_SECTION,\n );\n if (type === \"test-plan\" && section) {\n const body = meaningfulContent(section.content);\n const written =\n body !== \"\" && !PLACEHOLDER_BODIES.test(body) && !DISCLAIMED_BODIES.test(body);\n if (written) return [];\n\n return [\n {\n ruleId: \"completeness/edge-case-coverage\",\n severity: \"warn\" as const,\n message: `The \"${section.heading}\" section lists no cases — describe the boundary conditions and failure modes this plan covers, or the plan asserts only the happy path.`,\n filePath: context.spec.filePath,\n section: section.heading,\n },\n ];\n }\n\n // No dedicated section (a user story, or a test plan missing the heading —\n // `structure/required-sections` owns that): judge the document as a whole.\n const content = context.spec.content.toLowerCase();\n const hasEdgeCases =\n EDGE_CASE_KEYWORDS.some((kw) => content.includes(kw)) || ERROR_STATUS_CODE.test(content);\n\n if (hasEdgeCases) return [];\n\n return [\n {\n ruleId: \"completeness/edge-case-coverage\",\n severity: \"warn\" as const,\n message:\n \"No error states or edge cases mentioned. Consider adding error handling, boundary conditions, or failure mode scenarios.\",\n filePath: context.spec.filePath,\n },\n ];\n },\n};\n","import type { LintRule } from \"../types.js\";\n\nexport const namingConventionsRule: LintRule = {\n id: \"consistency/naming-conventions\",\n description: \"Enforce consistent naming conventions across specs\",\n severity: \"warn\",\n run(context) {\n const { spec } = context;\n const type = spec.frontmatter.type as string;\n const diagnostics = [];\n\n if (type === \"prd\") {\n // Split content into sections and find the Features section\n const sectionParts = spec.content.split(/^(?=## )/m);\n const featuresSection = sectionParts.find((p) => /^## Features\\b/.test(p));\n if (featuresSection) {\n const bullets = featuresSection.match(/^- .+$/gm) ?? [];\n for (const bullet of bullets) {\n if (bullet.match(/^- \\*\\*F\\d+\\*\\*:/) === null && bullet.trim().length > 2) {\n diagnostics.push({\n ruleId: \"consistency/naming-conventions\",\n severity: \"warn\" as const,\n message: `PRD feature missing feature ID pattern (**F<N>**:): \"${bullet.slice(0, 60)}\"`,\n filePath: spec.filePath,\n });\n }\n }\n }\n }\n\n if (type === \"user-story\") {\n const id = spec.frontmatter.id as string;\n if (!id.startsWith(\"story-\")) {\n diagnostics.push({\n ruleId: \"consistency/naming-conventions\",\n severity: \"warn\" as const,\n message: `User story ID \"${id}\" should start with \"story-\" (e.g., \"story-${id}\")`,\n filePath: spec.filePath,\n });\n }\n }\n\n if (type === \"api-contract\") {\n // Check endpoints for camelCase path segments\n const endpointRe = /^###\\s+(GET|POST|PUT|PATCH|DELETE)\\s+(\\S+)/gm;\n let match;\n while ((match = endpointRe.exec(spec.content)) !== null) {\n const path = match[2]!;\n if (/\\/[a-z]+[A-Z]/.test(path)) {\n diagnostics.push({\n ruleId: \"consistency/naming-conventions\",\n severity: \"warn\" as const,\n message: `Endpoint path \"${path}\" uses camelCase — use kebab-case instead (e.g., \"${path.replace(/([a-z])([A-Z])/g, \"$1-$2\").toLowerCase()}\")`,\n filePath: spec.filePath,\n });\n }\n }\n }\n\n return diagnostics;\n },\n};\n","import type { LintRule } from \"../types.js\";\n\nconst STOPWORDS = new Set([\"the\", \"and\", \"for\", \"with\", \"from\", \"that\", \"this\", \"into\", \"via\"]);\n\nfunction extractThreats(content: string): string[] {\n // Split into sections at each ## heading, then filter for Threats/Security\n const parts = content.split(/^(?=## )/m);\n const threats: string[] = [];\n for (const part of parts) {\n if (!/^##\\s+(Threats|Security)\\b/i.test(part)) continue;\n const bullets = part.match(/^- .+$/gm) ?? [];\n threats.push(...bullets.map((b) => b.slice(2).trim()));\n }\n return threats;\n}\n\nfunction extractKeyTerms(text: string): string[] {\n return text\n .toLowerCase()\n .split(/\\W+/)\n .filter((w) => w.length > 3)\n .filter((w) => !STOPWORDS.has(w));\n}\n\nexport const threatCoverageRule: LintRule = {\n id: \"security/threat-coverage\",\n description: \"Technical design specs must address threats identified in other specs\",\n severity: \"warn\",\n run(context) {\n if (context.spec.frontmatter.type !== \"technical-design\") return [];\n\n const allThreats: string[] = [];\n for (const spec of context.allSpecs) {\n if (spec.filePath === context.spec.filePath) continue;\n allThreats.push(...extractThreats(spec.content));\n }\n\n if (allThreats.length === 0) return [];\n\n const techContent = context.spec.content.toLowerCase();\n const diagnostics = [];\n\n for (const threat of allThreats) {\n const keyTerms = extractKeyTerms(threat);\n const covered = keyTerms.some((term) => techContent.includes(term));\n if (!covered) {\n diagnostics.push({\n ruleId: \"security/threat-coverage\",\n severity: \"warn\" as const,\n message: `Threat not addressed in technical design: \"${threat}\". Ensure the design covers this threat.`,\n filePath: context.spec.filePath,\n });\n }\n }\n\n return diagnostics;\n },\n};\n","import type { LintRule } from \"../types.js\";\n\nexport const ambiguityScoreAiRule: LintRule = {\n id: \"clarity/ambiguity-score-ai\",\n description: \"AI-powered ambiguity detection (requires ANTHROPIC_API_KEY)\",\n severity: \"info\",\n run(context) {\n if (!process.env[\"ANTHROPIC_API_KEY\"]) return [];\n\n return [\n {\n ruleId: \"clarity/ambiguity-score-ai\",\n severity: \"info\" as const,\n message:\n \"AI ambiguity analysis available — run `specdx check --ai` for LLM-powered ambiguity detection\",\n filePath: context.spec.filePath,\n },\n ];\n },\n};\n","import type { LintRule } from \"../types.js\";\n\n/**\n * Bodies that say \"nothing has been written here yet\".\n *\n * Matched against the whole section body, never as a substring: prose that\n * mentions a TODO is real content, a body that *is* \"TODO\" is not.\n */\nconst PLACEHOLDER_BODIES = /^(todo|tbd|fixme|n\\/a|na|none|xxx|\\.{2,}|-|\\*)$/i;\n\n/** Strip HTML comments, list bullets and separators to expose the real body. */\nfunction meaningfulContent(content: string): string {\n return content\n .replace(/<!--[\\s\\S]*?-->/g, \"\")\n .split(\"\\n\")\n .map((line) => line.replace(/^\\s*[-*+]\\s+/, \"\").trim())\n .filter((line) => line.length > 0 && !/^-{3,}$/.test(line))\n .join(\"\\n\")\n .trim();\n}\n\n/**\n * Flags sections that exist only as scaffolding.\n *\n * `structure/required-sections` checks that a heading is present, never that\n * anything was written under it. Without this rule a freshly scaffolded suite\n * of `<!-- placeholder -->` stubs lints clean, reports healthy, and is declared\n * ready for implementation -- the vacuous-pass failure mode, reached on a new\n * user's first command.\n *\n * Warning rather than error: an untouched scaffold should be visibly incomplete\n * without failing the very first `specdx lint` a user runs. `ready` enforces\n * the harder gate.\n */\nexport const noPlaceholderSectionsRule: LintRule = {\n id: \"completeness/no-placeholder-sections\",\n description: \"Spec sections contain content, not scaffolding placeholders\",\n severity: \"warn\",\n run(context) {\n return (\n context.spec.parsedSections\n // The preamble carries no heading and is not a section a user must fill.\n .filter((section) => section.heading !== \"\")\n .filter((section) => {\n const body = meaningfulContent(section.content);\n return body === \"\" || PLACEHOLDER_BODIES.test(body);\n })\n .map((section) => ({\n ruleId: \"completeness/no-placeholder-sections\",\n severity: \"warn\" as const,\n message: `Section \"${section.heading}\" is still a placeholder — write its content or remove the section`,\n filePath: context.spec.filePath,\n section: section.heading,\n }))\n );\n },\n};\n","import { basename } from \"node:path\";\nimport type { LintRule } from \"../types.js\";\n\n/**\n * A spec's frontmatter `id` must match the key it is registered under.\n *\n * When they disagree, nothing used to say so. `validate` passed, because the\n * config itself is well-formed and the file exists. `lint` reported dangling\n * references -- but blamed every spec that referenced the id, none of which was\n * at fault. And `graph` listed nodes by config key while drawing edges by\n * frontmatter id, so it rendered a node with no edges beside edges from a node\n * that did not exist.\n *\n * One diagnostic on the spec that actually diverged replaces all of that.\n *\n * A warning rather than an error: both names resolve, in different places --\n * frontmatter `references` match the id, config `requires` match the key -- so\n * a suite that keeps them apart still works. What it cannot do is produce a\n * coherent graph, or a useful message when a reference goes stale.\n */\nexport const idMatchesConfigKeyRule: LintRule = {\n id: \"structure/id-matches-config-key\",\n description: \"A spec's frontmatter id should match the key it is registered under in the config\",\n severity: \"warn\",\n run(context) {\n const { spec, config } = context;\n if (!config) return [];\n\n const id = spec.frontmatter.id;\n if (typeof id !== \"string\" || id.length === 0) return [];\n\n // Find the entry this file was loaded from. Paths may be globs, so match on\n // the filename the config points at rather than re-resolving every glob.\n const specFile = basename(spec.filePath);\n const candidates = Object.entries(config.specs).filter(([, entry]) => {\n const target = basename(entry.path);\n // A glob entry (`specs/stories/*.md`) claims a directory, not a filename,\n // and cannot be checked this way -- its key names a group, not a spec.\n return !target.includes(\"*\") && target === specFile;\n });\n\n if (candidates.length !== 1) return [];\n const key = candidates[0]![0];\n if (key === id) return [];\n\n return [\n {\n ruleId: \"structure/id-matches-config-key\",\n severity: \"warn\" as const,\n message:\n `Spec declares id \"${id}\" but is registered in spec.config.yaml as \"${key}\". ` +\n `Frontmatter references resolve against \"${id}\" and config requires against \"${key}\", ` +\n \"so the dependency graph shows them as two things. Rename one so they agree.\",\n filePath: spec.filePath,\n },\n ];\n },\n};\n","import { validFrontmatterRule } from \"./valid-frontmatter.js\";\nimport { requiredSectionsRule } from \"./required-sections.js\";\nimport { validReferencesRule } from \"./valid-references.js\";\nimport { noCircularDepsRule } from \"./no-circular-deps.js\";\nimport { storyCoverageRule } from \"./story-coverage.js\";\nimport { stalenessCheckRule } from \"./staleness-check.js\";\nimport { noVagueLanguageRule } from \"./no-vague-language.js\";\nimport { singleProjectContextRule } from \"./single-project-context.js\";\nimport { terminologyRule } from \"./terminology.js\";\nimport { edgeCaseCoverageRule } from \"./edge-case-coverage.js\";\nimport { namingConventionsRule } from \"./naming-conventions.js\";\nimport { threatCoverageRule } from \"./threat-coverage.js\";\nimport { ambiguityScoreAiRule } from \"./ambiguity-score-ai.js\";\nimport { noPlaceholderSectionsRule } from \"./no-placeholder-sections.js\";\nimport { idMatchesConfigKeyRule } from \"./id-matches-config-key.js\";\nimport type { LintRule } from \"../types.js\";\n\nexport const structureRules: LintRule[] = [\n validFrontmatterRule,\n requiredSectionsRule,\n validReferencesRule,\n noCircularDepsRule,\n singleProjectContextRule,\n idMatchesConfigKeyRule,\n];\n\nexport const contentRules: LintRule[] = [\n storyCoverageRule,\n stalenessCheckRule,\n noVagueLanguageRule,\n terminologyRule,\n edgeCaseCoverageRule,\n namingConventionsRule,\n threatCoverageRule,\n ambiguityScoreAiRule,\n noPlaceholderSectionsRule,\n];\n\nexport const allBuiltinRules: LintRule[] = [...structureRules, ...contentRules];\n\nexport {\n validFrontmatterRule,\n requiredSectionsRule,\n validReferencesRule,\n noCircularDepsRule,\n storyCoverageRule,\n stalenessCheckRule,\n noVagueLanguageRule,\n singleProjectContextRule,\n terminologyRule,\n edgeCaseCoverageRule,\n namingConventionsRule,\n threatCoverageRule,\n ambiguityScoreAiRule,\n noPlaceholderSectionsRule,\n idMatchesConfigKeyRule,\n};\n","import type { LintRule } from \"./types.js\";\nimport { structureRules, allBuiltinRules } from \"./rules/index.js\";\n\nexport function getPreset(name: string): LintRule[] {\n switch (name) {\n case \"minimal\":\n return structureRules;\n case \"recommended\":\n return allBuiltinRules;\n case \"strict\":\n // Promote warnings only. An info-class rule is an advisory the author\n // cannot satisfy by editing specs (ambiguity-score-ai fires whenever\n // ANTHROPIC_API_KEY is set), so promoting it would fail every suite\n // linted in an environment that carries the key.\n return allBuiltinRules.map((rule) =>\n rule.severity === \"warn\" ? { ...rule, severity: \"error\" as const } : rule,\n );\n default:\n throw new Error(\n `Unknown preset: \"${name}\". Use \"minimal\", \"recommended\", or \"strict\", or resolve external presets via resolvePreset() from @specdx/core.`,\n );\n }\n}\n","import { pathToFileURL } from \"node:url\";\nimport type { LintRule } from \"./types.js\";\n\nexport async function loadCustomRule(filePath: string): Promise<LintRule> {\n const module = await import(pathToFileURL(filePath).href);\n const rule = module.default ?? module.rule;\n if (!rule || !rule.id || !rule.run) {\n throw new Error(\n `Custom rule at ${filePath} must export a default LintRule with id and run function`,\n );\n }\n return rule as LintRule;\n}\n","/**\n * Args every reporting command shares.\n *\n * `--format` is declared per command, not globally. Spreading one blanket\n * `format` arg put the value `github` in every `--help` while only two\n * commands implemented it, and an unknown value fell through to pretty output\n * with exit 0 — a CI step could ask for annotations, get none, and still go\n * green (audit run 5, F2). A command now names the formats it renders, the\n * help text is generated from that list, and anything else is an error.\n */\n\n/** The single source of truth for a command's `--format` values. */\nexport type FormatArg = {\n type: \"string\";\n description: string;\n default: string;\n};\n\nexport const quietArg = {\n type: \"boolean\" as const,\n description: \"Suppress success and summary output; problems still print\",\n alias: [\"q\"],\n};\n\nexport const verboseArg = {\n type: \"boolean\" as const,\n description: \"Enable debug output\",\n alias: [\"V\"],\n};\n\n/**\n * Build the `--format` arg from the formats a command actually implements.\n * The first entry is the default.\n */\nexport function formatArg(formats: readonly string[]): FormatArg {\n const [fallback] = formats;\n if (!fallback) throw new Error(\"formatArg requires at least one format\");\n return {\n type: \"string\",\n description: `Output format (${formats.join(\", \")})`,\n default: fallback,\n };\n}\n\n/** `--quiet`, `--verbose`, and a `--format` limited to what the command renders. */\nexport function sharedArgs(formats: readonly string[]): {\n quiet: typeof quietArg;\n verbose: typeof verboseArg;\n format: FormatArg;\n} {\n return { quiet: quietArg, verbose: verboseArg, format: formatArg(formats) };\n}\n\n/**\n * Narrow a user-supplied `--format` to one the command renders.\n *\n * Returns null when the value is unsupported, so the caller can print and pick\n * its own exit code. Silently falling back to pretty is the defect this\n * replaces: the user asked for a machine-readable payload and got prose.\n */\nexport function resolveFormat<T extends string>(\n value: string | undefined,\n formats: readonly T[],\n): { ok: true; format: T } | { ok: false; message: string } {\n const [fallback] = formats;\n if (!fallback) throw new Error(\"resolveFormat requires at least one format\");\n if (value === undefined) return { ok: true, format: fallback };\n if ((formats as readonly string[]).includes(value)) return { ok: true, format: value as T };\n return {\n ok: false,\n message: `unknown --format \"${value}\". This command renders: ${formats.join(\", \")}.`,\n };\n}\n","/**\n * Quiet-aware console output.\n *\n * `--quiet` used to only lower a consola log level while every user-facing\n * line went out through `console.log`, so the flag changed nothing a user\n * could see (audit run 5, F2). Routing the pretty renderers through this\n * splits output into two classes and gives the flag something to suppress.\n */\nexport interface Output {\n /** Banners, verdicts, summaries — chrome. Suppressed by `--quiet`. */\n info(line?: string): void;\n /** Diagnostics, findings, payloads. Always printed. */\n out(line?: string): void;\n /** Errors and warnings, on stderr. Always printed. */\n error(line?: string): void;\n}\n\nexport function createOutput(options: { quiet?: boolean } = {}): Output {\n const quiet = options.quiet === true;\n return {\n info(line = \"\") {\n if (!quiet) console.log(line);\n },\n out(line = \"\") {\n console.log(line);\n },\n error(line = \"\") {\n console.error(line);\n },\n };\n}\n","import type { Diagnostic } from \"@specdx/lint\";\n\nexport function formatPretty(diagnostics: Diagnostic[]): string {\n if (diagnostics.length === 0) return \" ✓ All specs pass lint checks.\\n\";\n return diagnostics\n .map((d) => {\n const icon = d.severity === \"error\" ? \"✗\" : d.severity === \"warn\" ? \"⚠\" : \"ℹ\";\n return ` ${icon} ${d.severity} ${d.message} (${d.ruleId})\\n ${d.filePath}${d.line ? `:${d.line}` : \"\"}`;\n })\n .join(\"\\n\");\n}\n","import type { Diagnostic } from \"@specdx/lint\";\nexport function formatJson(diagnostics: Diagnostic[]): string {\n return JSON.stringify(diagnostics, null, 2);\n}\n","import type { Diagnostic } from \"@specdx/lint\";\n\n/**\n * GitHub workflow-command annotations.\n *\n * Info-severity diagnostics map to `::notice`, not `::warning`. Rendering an\n * advisory as a warning put five warnings in the Actions log for a suite that\n * was clean and exited 0 — the ambiguity advisory in particular, which is info\n * precisely so it cannot fail a build (audit run 5, F5).\n */\nexport function formatGithub(diagnostics: Diagnostic[]): string {\n return diagnostics\n .map((d) => {\n const level = d.severity === \"error\" ? \"error\" : d.severity === \"warn\" ? \"warning\" : \"notice\";\n const line = d.line ? `,line=${d.line}` : \"\";\n return `::${level} file=${d.filePath}${line}::${d.message} (${d.ruleId})`;\n })\n .join(\"\\n\");\n}\n","import { defineCommand } from \"citty\";\nimport { loadConfig, parseSpec, resolveGlob, buildGraph, createLogger } from \"@specdx/core\";\nimport { pack, type PackResult } from \"@specdx/pack\";\nimport type { ParsedSpec } from \"@specdx/core\";\nimport { quietArg, verboseArg } from \"../../shared-args.js\";\nimport { writeFile } from \"node:fs/promises\";\nimport { execSync } from \"node:child_process\";\n\nfunction copyToClipboard(text: string): void {\n const platform = process.platform;\n let cmd: string;\n if (platform === \"darwin\") {\n cmd = \"pbcopy\";\n } else if (platform === \"linux\") {\n cmd = \"xclip -selection clipboard\";\n } else if (platform === \"win32\") {\n cmd = \"clip\";\n } else {\n throw new Error(`Clipboard not supported on platform: ${platform}`);\n }\n execSync(cmd, { input: text, stdio: [\"pipe\", \"ignore\", \"ignore\"] });\n}\n\n/**\n * Why a pack produced no context, if it produced none.\n *\n * An empty `<context>` on stdout with exit 0 reads as \"here is your context\"\n * to whatever consumes it. `lint` and `check` already use exit 3 for\n * \"nothing was assessed\"; packing nothing is the same claim.\n */\nexport function emptyPackReason(\n stats: { specsIncluded: number; specsExcluded: number },\n specsResolved: number,\n): string | undefined {\n if (stats.specsIncluded > 0) return undefined;\n if (specsResolved === 0) {\n return \"no specs resolved from spec.config.yaml — check the paths in your config\";\n }\n // The relevance resolver drops sub-threshold specs before allocation, so\n // stats.specsExcluded counts only allocator-level exclusions. Reporting the\n // resolved total instead keeps the message from blaming the config.\n if (stats.specsExcluded === 0) {\n return `none of the ${specsResolved} resolved spec(s) scored above the relevance threshold for this task — try different --task wording, name specs with --specs, or use --full`;\n }\n return `all ${stats.specsExcluded} candidate spec(s) were excluded — widen --specs or raise --budget`;\n}\n\nexport interface RunPackOptions {\n configDir: string;\n task?: string;\n specs?: string[];\n budget?: number;\n format?: \"xml\" | \"markdown\" | \"json\";\n full?: boolean;\n dryRun?: boolean;\n}\n\nexport async function runPack(\n options: RunPackOptions,\n): Promise<PackResult & { specsResolved: number }> {\n if (!options.configDir) {\n throw new TypeError(\"runPack requires `configDir` — the directory holding spec.config.yaml.\");\n }\n const config = await loadConfig(undefined, options.configDir);\n\n const allSpecs: ParsedSpec[] = [];\n for (const [, entry] of Object.entries(config.specs)) {\n const files = await resolveGlob(entry.path, options.configDir);\n for (const file of files) {\n allSpecs.push(await parseSpec(file));\n }\n }\n\n let graph;\n try {\n graph = buildGraph(config);\n } catch {\n // non-fatal: proceed without graph\n }\n\n const result = pack(\n allSpecs,\n {\n task: options.task,\n specs: options.specs,\n budget: options.budget,\n format: options.format,\n full: options.full,\n dryRun: options.dryRun,\n },\n config.pack,\n graph,\n );\n\n return { ...result, specsResolved: allSpecs.length };\n}\n\nexport default defineCommand({\n meta: { name: \"pack\", description: \"Pack specs into AI-ready context\" },\n args: {\n quiet: quietArg,\n verbose: verboseArg,\n task: { type: \"string\", description: \"Task or context to optimise relevance for\" },\n specs: { type: \"string\", description: \"Comma-separated spec IDs or glob patterns to include\" },\n budget: { type: \"string\", description: \"Maximum token budget for the output\" },\n format: {\n type: \"string\",\n description: \"Output format (xml, markdown, json)\",\n default: \"xml\",\n },\n out: { type: \"string\", description: \"Write output to file instead of stdout\" },\n copy: { type: \"boolean\", description: \"Copy output to system clipboard\" },\n full: { type: \"boolean\", description: \"Include all specs without budget trimming\" },\n \"dry-run\": {\n type: \"boolean\",\n description: \"Preview what would be packed without writing output\",\n },\n },\n async run({ args }) {\n const logger = createLogger({ quiet: args.quiet, verbose: args.verbose });\n\n // Validate: --task and --specs are mutually exclusive\n if (args.task && args.specs) {\n console.error(\"\\n \\u2717 --task and --specs are mutually exclusive\\n\");\n process.exit(1);\n }\n\n // Validate: --copy and --dry-run are mutually exclusive\n if (args.copy && args[\"dry-run\"]) {\n console.error(\"\\n \\u2717 --copy and --dry-run are mutually exclusive\\n\");\n process.exit(1);\n }\n\n // Validate: --budget is a valid number\n let budget: number | undefined;\n if (args.budget) {\n budget = Number(args.budget);\n if (Number.isNaN(budget)) {\n console.error(\"\\n \\u2717 --budget must be a valid number\\n\");\n process.exit(1);\n }\n }\n\n // Validate: --format is valid\n const format = args.format as string;\n if (format && ![\"xml\", \"markdown\", \"json\"].includes(format)) {\n console.error(`\\n \\u2717 --format must be one of: xml, markdown, json\\n`);\n process.exit(1);\n }\n\n try {\n const specsList = args.specs ? args.specs.split(\",\").map((s: string) => s.trim()) : undefined;\n\n const result = await runPack({\n configDir: process.cwd(),\n task: args.task,\n specs: specsList,\n budget,\n format: format as \"xml\" | \"markdown\" | \"json\" | undefined,\n full: args.full,\n dryRun: args[\"dry-run\"],\n });\n\n const { stats } = result;\n\n // Dry-run: print plan to stdout\n if (args[\"dry-run\"]) {\n console.log(\"\\n Dry Run Summary:\\n\");\n for (const alloc of stats.allocations) {\n const status = alloc.included ? \"\\u2713\" : \"\\u2717\";\n const compressed = alloc.compressed ? \" (compressed)\" : \"\";\n console.log(\n ` ${status} ${alloc.specId} relevance=${alloc.relevance.toFixed(2)} tokens=${alloc.tokens}${compressed}`,\n );\n }\n console.log(`\\n Budget: ${stats.used} / ${stats.budget} tokens`);\n console.log(` Included: ${stats.specsIncluded} / ${result.specsResolved} specs`);\n console.log(` Sections compressed: ${stats.sectionsCompressed}`);\n console.log(` Sections omitted: ${stats.sectionsOmitted}\\n`);\n // A dry run that plans nothing is as misleading as an empty payload.\n const dryReason = emptyPackReason(stats, result.specsResolved);\n if (dryReason) {\n console.log(` ⚠ Nothing would be packed: ${dryReason}\\n`);\n process.exit(3);\n }\n return;\n }\n\n // Write output\n if (args.out) {\n await writeFile(args.out, result.output, \"utf-8\");\n logger.info(`Output written to ${args.out}`);\n }\n if (args.copy) {\n copyToClipboard(result.output);\n logger.info(\"Output copied to clipboard\");\n }\n if (!args.out && !args.copy) {\n process.stdout.write(result.output);\n }\n\n // Token report to stderr\n const total = stats.specsIncluded + stats.specsExcluded;\n process.stderr.write(\n `Packed ${stats.specsIncluded}/${total} specs \\u2022 ${stats.used} / ${stats.budget} tokens \\u2022 ${stats.sectionsCompressed} sections compressed \\u2022 ${stats.sectionsOmitted} sections omitted\\n`,\n );\n\n // Never let an empty payload leave looking like a successful pack.\n const emptyReason = emptyPackReason(stats, result.specsResolved);\n if (emptyReason) {\n process.stderr.write(`\\n \\u26a0 No context packed: ${emptyReason}\\n\\n`);\n process.exit(3);\n }\n } catch (err) {\n console.error(`\\n \\u2717 ${(err as Error).message}\\n`);\n process.exit(1);\n }\n },\n});\n","import type { ParsedSpec, DependencyGraph } from \"@specdx/core\";\nimport type { RelevanceScore } from \"./types.js\";\n\n/**\n * Common English stopwords to filter from task tokenization.\n */\nconst STOPWORDS = new Set([\n \"a\",\n \"an\",\n \"and\",\n \"are\",\n \"as\",\n \"at\",\n \"be\",\n \"but\",\n \"by\",\n \"do\",\n \"for\",\n \"from\",\n \"had\",\n \"has\",\n \"have\",\n \"he\",\n \"her\",\n \"his\",\n \"how\",\n \"i\",\n \"if\",\n \"in\",\n \"into\",\n \"is\",\n \"it\",\n \"its\",\n \"just\",\n \"me\",\n \"my\",\n \"no\",\n \"nor\",\n \"not\",\n \"of\",\n \"on\",\n \"or\",\n \"our\",\n \"out\",\n \"own\",\n \"say\",\n \"she\",\n \"so\",\n \"some\",\n \"such\",\n \"than\",\n \"that\",\n \"the\",\n \"their\",\n \"them\",\n \"then\",\n \"there\",\n \"these\",\n \"they\",\n \"this\",\n \"to\",\n \"too\",\n \"up\",\n \"us\",\n \"very\",\n \"was\",\n \"we\",\n \"were\",\n \"what\",\n \"when\",\n \"where\",\n \"which\",\n \"while\",\n \"who\",\n \"whom\",\n \"why\",\n \"will\",\n \"with\",\n \"would\",\n \"you\",\n \"your\",\n]);\n\n/** Tokenize a task string into lowercase keywords, dropping stopwords and short tokens. */\nfunction tokenize(task: string): string[] {\n return task\n .split(/[\\s\\-_/.,;:!?()[\\]{}'\"]+/)\n .map((t) => t.toLowerCase())\n .filter((t) => t.length > 1 && !STOPWORDS.has(t));\n}\n\n/** Field weights for keyword matching. */\nconst WEIGHT_TAGS = 3;\nconst WEIGHT_TITLE = 3;\nconst WEIGHT_SECTIONS = 2;\nconst WEIGHT_BODY = 1;\n\n/** Minimum id length considered for verbatim matching (avoids ids like \"a\"). */\nconst ID_MATCH_MIN_LENGTH = 3;\n\n/** Graph propagation factor for immediate neighbors. */\nconst GRAPH_BOOST_FACTOR = 0.5;\n\n/** Minimum normalized score to include a spec. */\nconst SCORE_THRESHOLD = 0.1;\n\n/**\n * Score specs by keyword relevance to a task string with graph propagation.\n *\n * - If no task or empty keywords after stopword removal, all specs get score 1.0.\n * - Keywords are matched with substring includes across weighted fields.\n * - Immediate graph neighbors of matching specs receive a boost.\n * - Results are normalized 0-1 and filtered by threshold.\n */\nexport function scoreSpecs(\n specs: Map<string, ParsedSpec>,\n task: string | undefined,\n graph: DependencyGraph,\n): RelevanceScore[] {\n const keywords = task ? tokenize(task) : [];\n\n // No keywords: all specs equally relevant\n if (keywords.length === 0) {\n const results: RelevanceScore[] = [];\n for (const specId of specs.keys()) {\n results.push({\n specId,\n score: 1.0,\n rawScore: 1.0,\n matchedKeywords: [],\n graphBoosted: false,\n });\n }\n return results;\n }\n\n // Score each spec by keyword hits across weighted fields\n const rawScores = new Map<string, number>();\n const matchedMap = new Map<string, Set<string>>();\n const idMatchedSet = new Set<string>();\n const taskLower = (task ?? \"\").toLowerCase();\n\n for (const [specId, spec] of specs) {\n let weightedHits = 0;\n const matched = new Set<string>();\n\n // Verbatim id match: a task that names a spec dominates keyword scoring\n const idLower = specId.toLowerCase();\n if (idLower.length >= ID_MATCH_MIN_LENGTH && taskLower.includes(idLower)) {\n idMatchedSet.add(specId);\n }\n\n for (const keyword of keywords) {\n let hit = false;\n\n // Tags (3x)\n const tags: unknown[] = (spec.frontmatter.tags as unknown[] | undefined) ?? [];\n for (const tag of tags) {\n if (typeof tag === \"string\" && tag.toLowerCase().includes(keyword)) {\n weightedHits += WEIGHT_TAGS;\n hit = true;\n break;\n }\n }\n\n // Title (3x)\n const title = spec.frontmatter.title;\n if (typeof title === \"string\" && title.toLowerCase().includes(keyword)) {\n weightedHits += WEIGHT_TITLE;\n hit = true;\n }\n\n // Sections (2x)\n for (const heading of spec.sections) {\n if (heading.toLowerCase().includes(keyword)) {\n weightedHits += WEIGHT_SECTIONS;\n hit = true;\n break;\n }\n }\n\n // Body content (1x)\n if (spec.content.toLowerCase().includes(keyword)) {\n weightedHits += WEIGHT_BODY;\n hit = true;\n }\n\n if (hit) {\n matched.add(keyword);\n }\n }\n\n const raw = weightedHits / keywords.length;\n rawScores.set(specId, raw);\n matchedMap.set(specId, matched);\n }\n\n // Graph propagation: boost immediate neighbors\n const boostScores = new Map<string, number>();\n const boostedSet = new Set<string>();\n\n for (const [specId, rawScore] of rawScores) {\n if (rawScore <= 0) continue;\n\n const boostAmount = rawScore * GRAPH_BOOST_FACTOR;\n\n // Find immediate neighbors from graph edges\n for (const edge of graph.edges) {\n let neighborId: string | undefined;\n if (edge.from === specId) {\n neighborId = edge.to;\n } else if (edge.to === specId) {\n neighborId = edge.from;\n }\n\n if (neighborId !== undefined && specs.has(neighborId)) {\n const existing = boostScores.get(neighborId) ?? 0;\n boostScores.set(neighborId, Math.max(existing, boostAmount));\n }\n }\n }\n\n // Combine raw + boost scores\n const finalRawScores = new Map<string, number>();\n for (const specId of specs.keys()) {\n const raw = rawScores.get(specId) ?? 0;\n const boost = boostScores.get(specId) ?? 0;\n const combined = raw + boost;\n finalRawScores.set(specId, combined);\n if (boost > 0 && raw === 0) {\n boostedSet.add(specId);\n }\n }\n\n // Find max for normalization\n let maxScore = 0;\n for (const score of finalRawScores.values()) {\n if (score > maxScore) maxScore = score;\n }\n\n // Build results, normalize, and filter. A spec the task names verbatim is\n // clamped to 1.0 — an explicit mention always outranks keyword inference —\n // without distorting the normalization of the other specs' scores.\n const results: RelevanceScore[] = [];\n for (const [specId] of specs) {\n const combined = finalRawScores.get(specId) ?? 0;\n const idMatched = idMatchedSet.has(specId);\n const normalized = idMatched ? 1.0 : maxScore > 0 ? combined / maxScore : 0;\n\n if (normalized < SCORE_THRESHOLD) continue;\n\n results.push({\n specId,\n score: normalized,\n rawScore: rawScores.get(specId) ?? 0,\n matchedKeywords: [...(matchedMap.get(specId) ?? [])],\n graphBoosted: boostedSet.has(specId),\n idMatched,\n });\n }\n\n // Sort descending by score; ties prefer specs the task named explicitly\n results.sort(\n (a, b) => b.score - a.score || Number(b.idMatched ?? false) - Number(a.idMatched ?? false),\n );\n\n return results;\n}\n\n/**\n * Score specs by explicit IDs. Named specs get 1.0, their transitive\n * upstream dependencies get 0.5.\n *\n * Throws if any specId is not found in the specs map.\n */\nexport function scoreSpecsByIds(\n specs: Map<string, ParsedSpec>,\n specIds: string[],\n graph: DependencyGraph,\n): RelevanceScore[] {\n // Validate all IDs exist\n for (const id of specIds) {\n if (!specs.has(id)) {\n const available = [...specs.keys()].join(\", \");\n throw new Error(`Unknown spec: \"${id}\". Available specs: ${available}`);\n }\n }\n\n const scoreMap = new Map<string, number>();\n\n // Named specs get 1.0\n for (const id of specIds) {\n scoreMap.set(id, 1.0);\n }\n\n // Upstream deps get 0.5 (unless already named at 1.0)\n for (const id of specIds) {\n const upstream = graph.getUpstream(id);\n for (const depId of upstream) {\n if (!scoreMap.has(depId) && specs.has(depId)) {\n scoreMap.set(depId, 0.5);\n }\n }\n }\n\n const results: RelevanceScore[] = [];\n for (const [specId, score] of scoreMap) {\n results.push({\n specId,\n score,\n rawScore: score,\n matchedKeywords: [],\n graphBoosted: score < 1.0,\n });\n }\n\n // Sort descending by score\n results.sort((a, b) => b.score - a.score);\n\n return results;\n}\n","import { countTokens } from \"@specdx/core\";\nimport type { ParsedSection } from \"@specdx/core\";\nimport type { CompressedSpec, CompressedSection, CompressionOptions } from \"./types.js\";\n\n/**\n * Returns true when `dateStr` is more than `days` days before now.\n * Returns false for invalid / missing dates (treat as fresh).\n */\nfunction isOlderThanDays(dateStr: string | undefined, days: number): boolean {\n if (!dateStr) return false;\n const ms = Date.parse(dateStr);\n if (Number.isNaN(ms)) return false;\n const diffMs = Date.now() - ms;\n return diffMs > days * 24 * 60 * 60 * 1000;\n}\n\n/**\n * Compress a single spec according to the provided options.\n */\nexport function compressSpec(\n specId: string,\n type: string,\n title: string,\n status: string | undefined,\n updatedDate: string | undefined,\n parsedSections: ParsedSection[],\n options: CompressionOptions,\n): CompressedSpec {\n // 1. Collapse superseded ADRs\n if (type === \"adr\" && status === \"superseded\" && options.collapseResolvedAdrs) {\n return {\n specId,\n type,\n title,\n sections: [],\n collapsed: true,\n collapsedSummary: `[ADR] ${title} — superseded`,\n };\n }\n\n // 2. Determine staleness\n const stale = options.stableDays > 0 && isOlderThanDays(updatedDate, options.stableDays);\n\n // 3. Process sections\n const boilerplateSet = new Set(options.boilerplateSections.map((s) => s.toLowerCase()));\n\n const sections: CompressedSection[] = [];\n\n for (const section of parsedSections) {\n // 3a. Strip boilerplate\n if (\n options.stripBoilerplate &&\n section.heading &&\n boilerplateSet.has(section.heading.toLowerCase())\n ) {\n continue;\n }\n\n // 3b. Collapse stale headed sections (preserve preamble)\n if (stale && section.heading) {\n const stub = `[Unchanged since ${updatedDate} — ${section.tokens} tokens omitted]`;\n sections.push({\n heading: section.heading,\n content: stub,\n tokens: countTokens(stub),\n compressed: true,\n originalTokens: section.tokens,\n });\n continue;\n }\n\n // 3c. Pass through unchanged\n sections.push({\n heading: section.heading,\n content: section.content,\n tokens: section.tokens,\n compressed: false,\n originalTokens: section.tokens,\n });\n }\n\n return {\n specId,\n type,\n title,\n sections,\n collapsed: false,\n };\n}\n","import { countTokens } from \"@specdx/core\";\nimport type { ParsedSpec } from \"@specdx/core\";\nimport { compressSpec } from \"./compressor.js\";\nimport type {\n CompressedSpec,\n CompressionOptions,\n PackStats,\n RelevanceScore,\n SpecAllocation,\n} from \"./types.js\";\n\n/** Options for the token allocator. */\nexport interface AllocatorOptions {\n /** Maximum token budget. */\n budget: number;\n /** When true, include full spec content without compression. */\n full: boolean;\n /** Compression settings (used when `full` is false). */\n compression: CompressionOptions;\n}\n\n/** Result of the allocation pass. */\nexport interface AllocationResult {\n /** Compressed specs that fit within the budget. */\n specs: CompressedSpec[];\n /** Statistics about how the budget was spent. */\n stats: PackStats;\n}\n\n/** Relevance at or above which a spec is trimmed to fit rather than excluded. */\nconst HIGH_RELEVANCE = 0.75;\n\n/** Minimum remaining budget worth trimming into. */\nconst MIN_TRIM_BUDGET = 150;\n\n/** Build the marker text for a contiguous run of omitted sections. */\nfunction omissionMarker(sections: CompressedSpec[\"sections\"]): string {\n const names = sections.map((s) => s.heading || \"(untitled)\");\n const noun = names.length === 1 ? \"section\" : \"sections\";\n return `[${names.length} ${noun} omitted to fit token budget: ${names.join(\", \")}]`;\n}\n\n/**\n * Produce a variant of `compressed` that fits within `budget` by keeping\n * sections in order while they fit and replacing each contiguous run of\n * omitted sections with an explicit marker naming them. Marker cost is\n * reserved out of the budget before sections are kept, so markers are always\n * emitted — a trimmed spec must never read as complete (issue #12).\n * Returns null when not even one real section fits.\n */\nfunction trimToBudget(\n compressed: CompressedSpec,\n budget: number,\n): { spec: CompressedSpec; tokens: number } | null {\n const sections = compressed.sections;\n let reserve = 0;\n\n // The kept set only shrinks as the reserve grows, so this converges.\n for (;;) {\n const effective = budget - reserve;\n const keep: boolean[] = new Array(sections.length).fill(false);\n let used = 0;\n let keptReal = false;\n\n for (let i = 0; i < sections.length; i++) {\n if (used + sections[i]!.tokens <= effective) {\n keep[i] = true;\n used += sections[i]!.tokens;\n keptReal = true;\n }\n }\n\n if (!keptReal) return null;\n\n // Group omitted sections into contiguous runs and price their markers.\n interface OmittedRun {\n start: number;\n sections: CompressedSpec[\"sections\"];\n marker: string;\n markerTokens: number;\n }\n const runs: OmittedRun[] = [];\n for (let i = 0; i < sections.length; i++) {\n if (keep[i]) continue;\n const start = i;\n const run: CompressedSpec[\"sections\"] = [];\n while (i < sections.length && !keep[i]) {\n run.push(sections[i]!);\n i++;\n }\n i--;\n const marker = omissionMarker(run);\n runs.push({ start, sections: run, marker, markerTokens: countTokens(marker) });\n }\n\n const markerTokens = runs.reduce((sum, r) => sum + r.markerTokens, 0);\n if (markerTokens > reserve) {\n reserve = markerTokens;\n continue;\n }\n\n // Assemble output: kept sections in order, markers at each cut.\n const out: CompressedSpec[\"sections\"] = [];\n for (let i = 0; i < sections.length; i++) {\n const run = runs.find((r) => r.start === i);\n if (run) {\n out.push({\n heading: \"\",\n content: run.marker,\n tokens: run.markerTokens,\n compressed: true,\n originalTokens: run.sections.reduce((sum, s) => sum + s.tokens, 0),\n omittedSections: run.sections.length,\n });\n i += run.sections.length - 1;\n continue;\n }\n out.push(sections[i]!);\n }\n\n return { spec: { ...compressed, sections: out }, tokens: used + markerTokens };\n }\n}\n\n/**\n * Allocate a token budget across specs, sorted by relevance.\n *\n * 1. Build specId -> ParsedSpec map\n * 2. Compress each spec (or pass through in full mode)\n * 3. Calculate token counts\n * 4. Sort by relevance descending\n * 5. Greedily include specs until budget is exhausted\n * 6. Build stats\n */\nexport function allocate(\n specs: ParsedSpec[],\n scores: RelevanceScore[],\n options: AllocatorOptions,\n): AllocationResult {\n // 1. Build specId -> ParsedSpec map\n const specMap = new Map<string, ParsedSpec>();\n for (const spec of specs) {\n specMap.set(spec.frontmatter.id, spec);\n }\n\n // 2. Compress each scored spec and compute token counts\n interface ScoredCompressed {\n compressed: CompressedSpec;\n relevance: number;\n tokens: number;\n idMatched: boolean;\n /**\n * Staleness-collapsed variant, spent only under budget pressure (issue #33).\n * Undefined when there is nothing to collapse, or in full mode.\n */\n stale?: { spec: CompressedSpec; tokens: number };\n }\n\n function tokensOf(compressed: CompressedSpec): number {\n if (compressed.collapsed) return countTokens(compressed.collapsedSummary ?? \"\");\n return compressed.sections.reduce((sum, section) => sum + section.tokens, 0);\n }\n\n const items: ScoredCompressed[] = [];\n\n for (const score of scores) {\n const spec = specMap.get(score.specId);\n if (!spec) continue;\n\n let compressed: CompressedSpec;\n let stale: ScoredCompressed[\"stale\"];\n\n if (options.full) {\n // No compression: pass through sections unchanged\n compressed = {\n specId: score.specId,\n type: String(spec.frontmatter.type),\n title: String(spec.frontmatter.title),\n sections: spec.parsedSections.map((s) => ({\n heading: s.heading,\n content: s.content,\n tokens: s.tokens,\n compressed: false,\n originalTokens: s.tokens,\n })),\n collapsed: false,\n };\n } else {\n const compress = (compression: CompressionOptions): CompressedSpec =>\n compressSpec(\n score.specId,\n String(spec.frontmatter.type),\n String(spec.frontmatter.title),\n spec.frontmatter.status as string | undefined,\n spec.frontmatter.updated as string | undefined,\n spec.parsedSections,\n compression,\n );\n\n // Boilerplate stripping and superseded-ADR collapse are hygiene, not\n // budget management -- they apply either way. Only the staleness collapse\n // is held back until the budget actually needs it.\n compressed = compress({ ...options.compression, stableDays: 0 });\n\n if (options.compression.stableDays > 0) {\n const collapsed = compress(options.compression);\n const collapsedTokens = tokensOf(collapsed);\n if (collapsedTokens < tokensOf(compressed)) {\n stale = { spec: collapsed, tokens: collapsedTokens };\n }\n }\n }\n\n items.push({\n compressed,\n relevance: score.score,\n tokens: tokensOf(compressed),\n idMatched: score.idMatched ?? false,\n stale,\n });\n }\n\n // 4. Sort by relevance descending; ties prefer specs the task named explicitly\n items.sort((a, b) => b.relevance - a.relevance || Number(b.idMatched) - Number(a.idMatched));\n\n // 4b. Collapse stale specs only while the budget is short, least relevant\n // first. Compression is a response to pressure: applied without it, the\n // caller asked for context and got stubs against a barely-touched budget.\n let projected = items.reduce((sum, item) => sum + item.tokens, 0);\n for (let i = items.length - 1; i >= 0 && projected > options.budget; i--) {\n const item = items[i]!;\n if (!item.stale) continue;\n projected -= item.tokens - item.stale.tokens;\n item.compressed = item.stale.spec;\n item.tokens = item.stale.tokens;\n }\n\n // 5. Greedy selection within budget\n const totalTokens = items.reduce((sum, item) => sum + item.tokens, 0);\n const withinBudget = totalTokens <= options.budget;\n\n const included: ScoredCompressed[] = [];\n const excluded: ScoredCompressed[] = [];\n let usedTokens = 0;\n\n if (withinBudget) {\n // Everything fits\n for (const item of items) {\n included.push(item);\n usedTokens += item.tokens;\n }\n } else {\n // Greedy: include from highest to lowest relevance. High-relevance specs\n // that don't fit are trimmed into the remaining budget before being\n // excluded — a task-named spec should never silently drop out.\n for (const item of items) {\n if (usedTokens + item.tokens <= options.budget) {\n included.push(item);\n usedTokens += item.tokens;\n continue;\n }\n const remaining = options.budget - usedTokens;\n if (\n (item.idMatched || item.relevance >= HIGH_RELEVANCE) &&\n remaining >= MIN_TRIM_BUDGET &&\n !item.compressed.collapsed\n ) {\n const trimmed = trimToBudget(item.compressed, remaining);\n if (trimmed) {\n included.push({ ...item, compressed: trimmed.spec, tokens: trimmed.tokens });\n usedTokens += trimmed.tokens;\n continue;\n }\n }\n excluded.push(item);\n }\n }\n\n // 6. Build stats\n let sectionsCompressed = 0;\n let sectionsOmitted = 0;\n for (const item of included) {\n for (const section of item.compressed.sections) {\n if (section.compressed) {\n sectionsCompressed++;\n }\n sectionsOmitted += section.omittedSections ?? 0;\n }\n }\n\n const allocations: SpecAllocation[] = [];\n\n // Add included specs\n for (const item of included) {\n allocations.push({\n specId: item.compressed.specId,\n type: item.compressed.type,\n relevance: item.relevance,\n tokens: item.tokens,\n compressed: item.compressed.collapsed || item.compressed.sections.some((s) => s.compressed),\n included: true,\n });\n }\n\n // Add excluded specs\n for (const item of excluded) {\n allocations.push({\n specId: item.compressed.specId,\n type: item.compressed.type,\n relevance: item.relevance,\n tokens: item.tokens,\n compressed: item.compressed.collapsed || item.compressed.sections.some((s) => s.compressed),\n included: false,\n });\n }\n\n const stats: PackStats = {\n budget: options.budget,\n used: usedTokens,\n specsIncluded: included.length,\n specsExcluded: excluded.length,\n sectionsCompressed,\n sectionsOmitted,\n allocations,\n };\n\n return {\n specs: included.map((item) => item.compressed),\n stats,\n };\n}\n","import type { CompressedSpec, PackStats } from \"../types.js\";\n\nfunction escapeXml(text: string): string {\n return text\n .replace(/&/g, \"&amp;\")\n .replace(/</g, \"&lt;\")\n .replace(/>/g, \"&gt;\")\n .replace(/\"/g, \"&quot;\");\n}\n\n/**\n * Format compressed specs as XML.\n *\n * @param specs - Compressed specs to render.\n * @param stats - Pack statistics with allocation details.\n * @returns An XML string representing the packed context.\n */\nexport function formatXml(specs: CompressedSpec[], stats: PackStats): string {\n const lines: string[] = [];\n\n lines.push(\n `<context budget=\"${stats.budget}\" used=\"${stats.used}\" specs=\"${stats.specsIncluded}\" compressed=\"${stats.sectionsCompressed}\" omitted=\"${stats.sectionsOmitted}\">`,\n );\n\n for (const spec of specs) {\n const alloc = stats.allocations.find((a) => a.specId === spec.specId);\n const relevance = alloc?.relevance ?? 0;\n const tokens = alloc?.tokens ?? 0;\n\n if (spec.collapsed) {\n lines.push(\n ` <spec id=\"${escapeXml(spec.specId)}\" type=\"${escapeXml(spec.type)}\" relevance=\"${relevance}\" tokens=\"${tokens}\" collapsed=\"true\">`,\n );\n lines.push(` ${escapeXml(spec.collapsedSummary ?? \"\")}`);\n lines.push(\" </spec>\");\n } else {\n lines.push(\n ` <spec id=\"${escapeXml(spec.specId)}\" type=\"${escapeXml(spec.type)}\" relevance=\"${relevance}\" tokens=\"${tokens}\">`,\n );\n for (const section of spec.sections) {\n const compressedAttr = section.compressed ? ' compressed=\"true\"' : \"\";\n lines.push(` <section name=\"${escapeXml(section.heading)}\"${compressedAttr}>`);\n lines.push(` ${escapeXml(section.content)}`);\n lines.push(\" </section>\");\n }\n lines.push(\" </spec>\");\n }\n }\n\n lines.push(\"</context>\");\n\n return lines.join(\"\\n\");\n}\n","import type { CompressedSpec, PackStats } from \"../types.js\";\n\n/**\n * Format compressed specs as Markdown.\n *\n * @param specs - Compressed specs to render.\n * @param stats - Pack statistics with allocation details.\n * @returns A Markdown string representing the packed context.\n */\nexport function formatMarkdown(specs: CompressedSpec[], stats: PackStats): string {\n const parts: string[] = [];\n\n for (let i = 0; i < specs.length; i++) {\n const spec = specs[i]!;\n const alloc = stats.allocations.find((a) => a.specId === spec.specId);\n const relevance = alloc?.relevance ?? 0;\n\n if (i > 0) {\n parts.push(\"---\");\n parts.push(\"\");\n }\n\n parts.push(`# ${spec.specId} (${spec.type}) [relevance: ${relevance}]`);\n parts.push(\"\");\n\n if (spec.collapsed) {\n parts.push(spec.collapsedSummary ?? \"\");\n parts.push(\"\");\n } else {\n for (const section of spec.sections) {\n if (section.heading) {\n parts.push(`## ${section.heading}`);\n parts.push(\"\");\n }\n parts.push(section.content);\n parts.push(\"\");\n }\n }\n }\n\n return parts.join(\"\\n\");\n}\n","import type { CompressedSpec, PackStats } from \"../types.js\";\n\ninterface JsonSection {\n name: string;\n content: string;\n compressed: boolean;\n}\n\ninterface JsonSpec {\n id: string;\n type: string;\n relevance: number;\n tokens: number;\n collapsed: boolean;\n summary?: string;\n sections: JsonSection[];\n}\n\ninterface JsonOutput {\n budget: number;\n used: number;\n sectionsOmitted: number;\n specs: JsonSpec[];\n}\n\n/**\n * Format compressed specs as a JSON string.\n *\n * @param specs - Compressed specs to render.\n * @param stats - Pack statistics with allocation details.\n * @returns A pretty-printed JSON string representing the packed context.\n */\nexport function formatJson(specs: CompressedSpec[], stats: PackStats): string {\n const output: JsonOutput = {\n budget: stats.budget,\n used: stats.used,\n sectionsOmitted: stats.sectionsOmitted,\n specs: specs.map((spec) => {\n const alloc = stats.allocations.find((a) => a.specId === spec.specId);\n const relevance = alloc?.relevance ?? 0;\n const tokens = alloc?.tokens ?? 0;\n\n const jsonSpec: JsonSpec = {\n id: spec.specId,\n type: spec.type,\n relevance,\n tokens,\n collapsed: spec.collapsed,\n sections: spec.sections.map((s) => ({\n name: s.heading,\n content: s.content,\n compressed: s.compressed,\n })),\n };\n\n if (spec.collapsed) {\n jsonSpec.summary = spec.collapsedSummary ?? \"\";\n }\n\n return jsonSpec;\n }),\n };\n\n return JSON.stringify(output, null, 2);\n}\n","import type { ParsedSpec, DependencyGraph } from \"@specdx/core\";\nimport type { PackConfig } from \"@specdx/schema\";\nimport type {\n PackOptions,\n PackResult,\n CompressionOptions,\n CompressedSpec,\n RelevanceScore,\n} from \"./types.js\";\nimport { scoreSpecs, scoreSpecsByIds } from \"./resolver.js\";\nimport { allocate } from \"./allocator.js\";\nimport { formatXml } from \"./formatters/xml.js\";\nimport { formatMarkdown } from \"./formatters/markdown.js\";\nimport { formatJson } from \"./formatters/json.js\";\n\nexport type {\n PackOptions,\n PackResult,\n PackStats,\n SpecAllocation,\n RelevanceScore,\n CompressedSpec,\n CompressedSection,\n CompressionOptions,\n} from \"./types.js\";\n\nexport { scoreSpecs, scoreSpecsByIds } from \"./resolver.js\";\nexport { allocate, type AllocatorOptions, type AllocationResult } from \"./allocator.js\";\nexport { compressSpec } from \"./compressor.js\";\nexport { formatXml } from \"./formatters/xml.js\";\nexport { formatMarkdown } from \"./formatters/markdown.js\";\nexport { formatJson } from \"./formatters/json.js\";\n\n/**\n * Default empty dependency graph used when none is provided.\n */\nfunction emptyGraph(): DependencyGraph {\n return {\n nodes: [],\n edges: [],\n topologicalSort: () => [],\n getDownstream: () => [],\n getUpstream: () => [],\n };\n}\n\n/**\n * Build CompressionOptions from PackConfig with sensible defaults.\n */\nfunction buildCompressionOptions(packConfig: PackConfig | undefined): CompressionOptions {\n const compression = packConfig?.compression;\n return {\n stripBoilerplate: compression?.strip_boilerplate ?? true,\n stableDays: compression?.stable_days ?? 7,\n collapseResolvedAdrs: compression?.collapse_resolved_adrs ?? true,\n boilerplateSections: packConfig?.boilerplate_sections ?? [\n \"Changelog\",\n \"Revision History\",\n \"Document History\",\n ],\n };\n}\n\n/**\n * Pack specs into a formatted context string within a token budget.\n *\n * Pipeline:\n * 1. Resolve relevance scores\n * 2. Allocate token budget across specs\n * 3. Format output in the requested format\n */\nexport function pack(\n specs: ParsedSpec[],\n options: PackOptions,\n packConfig: PackConfig | undefined,\n graph: DependencyGraph | undefined,\n): PackResult {\n // 1. Resolve defaults\n const budget = options.budget ?? packConfig?.max_tokens ?? 12000;\n const format = options.format ?? packConfig?.format ?? \"xml\";\n const full = options.full ?? false;\n const compression = buildCompressionOptions(packConfig);\n const resolvedGraph = graph ?? emptyGraph();\n\n // 2. Extract project-context specs and reserve budget\n const projectContextSpecs: ParsedSpec[] = [];\n const regularSpecs: ParsedSpec[] = [];\n for (const spec of specs) {\n if (spec.frontmatter.type === \"project-context\") {\n projectContextSpecs.push(spec);\n } else {\n regularSpecs.push(spec);\n }\n }\n\n let reservedTokens = 0;\n let reservedCompressed: CompressedSpec[] = [];\n if (projectContextSpecs.length > 0) {\n const maxReserved = Math.min(budget, 2000);\n const ctxScores: RelevanceScore[] = projectContextSpecs.map((s) => ({\n specId: s.frontmatter.id,\n score: 1.0,\n rawScore: 1.0,\n matchedKeywords: [],\n graphBoosted: false,\n }));\n const ctxResult = allocate(projectContextSpecs, ctxScores, {\n budget: maxReserved,\n full: true,\n compression,\n });\n reservedCompressed = ctxResult.specs;\n reservedTokens = ctxResult.stats.used;\n }\n\n const regularBudget = Math.max(0, budget - reservedTokens);\n\n // 3. Build spec map for resolver (regular specs only)\n const specMap = new Map<string, ParsedSpec>();\n for (const spec of regularSpecs) {\n specMap.set(spec.frontmatter.id, spec);\n }\n\n // 4. Stage 1 - Resolve\n const scores = options.specs\n ? scoreSpecsByIds(specMap, options.specs, resolvedGraph)\n : scoreSpecs(specMap, options.task, resolvedGraph);\n\n // 5. Stage 2 - Allocate\n const { specs: compressedSpecs, stats } = allocate(regularSpecs, scores, {\n budget: regularBudget,\n full,\n compression,\n });\n\n // 6. Combine project-context and regular specs\n const allCompressed = [...reservedCompressed, ...compressedSpecs];\n\n // Update stats to include reserved specs\n stats.budget = budget;\n stats.used += reservedTokens;\n stats.specsIncluded += reservedCompressed.length;\n for (const ctx of reservedCompressed) {\n stats.allocations.unshift({\n specId: ctx.specId,\n type: ctx.type,\n relevance: 1.0,\n tokens: reservedTokens,\n compressed: false,\n included: true,\n });\n }\n\n // 7. Dry run: return stats without output\n if (options.dryRun) {\n return { output: \"\", stats };\n }\n\n // 8. Stage 3 - Format\n let output: string;\n switch (format) {\n case \"markdown\":\n output = formatMarkdown(allCompressed, stats);\n break;\n case \"json\":\n output = formatJson(allCompressed, stats);\n break;\n default:\n output = formatXml(allCompressed, stats);\n break;\n }\n\n return { output, stats };\n}\n","import { defineCommand } from \"citty\";\nimport { join } from \"node:path\";\nimport { diffBetweenRefs, DEFAULT_DIFF_CONFIG, DiffError } from \"@specdx/diff\";\nimport { loadConfig } from \"@specdx/core\";\nimport { formatChangelog } from \"../../formatters/changelog.js\";\nimport type { DiffResult } from \"@specdx/diff\";\nimport { sharedArgs, resolveFormat } from \"../../shared-args.js\";\nimport { createOutput } from \"../../output.js\";\n\nconst FORMATS = [\"pretty\", \"json\", \"changelog\"] as const;\n\nexport interface RunDiffOptions {\n base?: string;\n head?: string;\n spec?: string;\n format?: string;\n /** Compare the base ref against the working tree instead of a head ref. */\n working?: boolean;\n /**\n * Directory holding spec.config.yaml. Defaults to the process cwd; a library\n * consumer needs to point it elsewhere (audit run 5, F8).\n */\n configDir?: string;\n}\n\nexport async function runDiff(options: RunDiffOptions): Promise<DiffResult> {\n const configDir = options.configDir ?? process.cwd();\n const config = await loadConfig(undefined, configDir);\n\n const baseRef = options.base ?? config.diff?.baseline_ref ?? DEFAULT_DIFF_CONFIG.baseline_ref;\n const headRef = options.head ?? \"HEAD\";\n\n const configPath = join(configDir, \"spec.config.yaml\");\n\n const result = await diffBetweenRefs(configPath, baseRef, headRef, {\n working: options.working ?? false,\n });\n\n if (options.spec) {\n result.diffs = result.diffs.filter((d) => d.specId === options.spec);\n result.impact = result.impact.filter((i) => i.changedSpec === options.spec);\n }\n\n return result;\n}\n\nexport default defineCommand({\n meta: { name: \"diff\", description: \"Show spec changes and downstream impact\" },\n args: {\n base: { type: \"string\", description: \"Base git ref (default: from config or 'main')\" },\n head: { type: \"string\", description: \"Head git ref (default: HEAD)\" },\n working: {\n type: \"boolean\",\n description: \"Compare the base ref against the working tree (includes uncommitted specs)\",\n default: false,\n },\n spec: { type: \"string\", description: \"Scope to a single spec ID\" },\n ...sharedArgs(FORMATS),\n },\n async run({ args }) {\n const format = resolveFormat(args.format, FORMATS);\n if (!format.ok) {\n console.error(`\\n ✗ ${format.message}\\n`);\n process.exit(1);\n }\n const output = createOutput({ quiet: args.quiet });\n\n try {\n try {\n const result = await runDiff({\n base: args.base,\n head: args.head,\n spec: args.spec,\n format: args.format,\n working: args.working,\n });\n\n if (format.format === \"json\") {\n console.log(JSON.stringify(result, null, 2));\n return;\n }\n\n if (format.format === \"changelog\") {\n const baseRef =\n args.base ?? (await loadConfig(undefined, process.cwd())).diff?.baseline_ref ?? \"main\";\n console.log(\n formatChangelog(result, baseRef, args.working ? \"working tree\" : (args.head ?? \"HEAD\")),\n );\n return;\n }\n\n // A ref-to-ref comparison cannot see the working tree, so an unqualified\n // \"no changes\" would be a false all-clear for anyone about to commit.\n const printUncommittedWarning = (): void => {\n if (result.uncommittedSpecFiles.length === 0) return;\n const count = result.uncommittedSpecFiles.length;\n console.log(\n `\\n \\u26a0 ${count} spec file(s) changed in the working tree are not covered by this comparison:`,\n );\n for (const file of result.uncommittedSpecFiles) {\n console.log(` ${file}`);\n }\n console.log(\" Run with --working to include them.\");\n };\n\n // Pretty format\n if (result.diffs.length === 0 && result.added.length === 0 && result.removed.length === 0) {\n output.info(\" \\u2713 No spec changes detected.\");\n printUncommittedWarning();\n return;\n }\n\n console.log(result.summary);\n console.log();\n\n for (const diff of result.diffs) {\n console.log(` ${diff.specId}:`);\n for (const fc of diff.frontmatter) {\n const detail =\n fc.before !== undefined || fc.after !== undefined\n ? ` (${String(fc.before)} \\u2192 ${String(fc.after)})`\n : \"\";\n console.log(` ${fc.type}: ${fc.field}${detail}`);\n }\n for (const sc of diff.sections) {\n console.log(` ${sc.type}: ${sc.heading}`);\n }\n }\n\n if (result.added.length > 0) {\n console.log(`\\n Added: ${result.added.join(\", \")}`);\n }\n if (result.removed.length > 0) {\n console.log(`\\n Removed: ${result.removed.join(\", \")}`);\n }\n\n if (result.impact.length > 0) {\n console.log(\"\\n Downstream Impact:\");\n for (const impact of result.impact) {\n for (const d of impact.downstream) {\n console.log(\n ` ${d.specId} \\u2014 staleness: ${d.staleness.toFixed(2)} \\u2014 ${d.reason}`,\n );\n }\n }\n }\n\n printUncommittedWarning();\n } catch (err) {\n if (err instanceof DiffError) {\n console.error(`\\n \\u2717 ${err.message}\\n`);\n process.exit(1);\n }\n throw err;\n }\n } catch (err) {\n console.error(`\\n ✗ ${(err as Error).message}\\n`);\n process.exit(1);\n }\n },\n});\n","export type FieldChangeType = \"added\" | \"removed\" | \"modified\" | \"broken-reference\";\n\nexport interface FieldChange {\n field: string;\n type: FieldChangeType;\n before?: unknown;\n after?: unknown;\n}\n\nexport interface SectionChange {\n heading: string;\n type: \"added\" | \"removed\" | \"modified\";\n contentDiff?: string;\n}\n\nexport interface SpecDiff {\n specId: string;\n filePath: string;\n frontmatter: FieldChange[];\n sections: SectionChange[];\n summary: string;\n}\n\nexport interface DownstreamImpact {\n specId: string;\n filePath: string;\n distance: number;\n lastUpdated: string | null;\n staleness: number;\n reason: string;\n}\n\nexport interface ImpactAnalysis {\n changedSpec: string;\n downstream: DownstreamImpact[];\n totalAffected: number;\n}\n\nexport interface DiffResult {\n diffs: SpecDiff[];\n added: string[];\n removed: string[];\n impact: ImpactAnalysis[];\n summary: string;\n /**\n * Spec files changed in the working tree but not covered by the comparison.\n *\n * A ref-to-ref diff cannot see uncommitted work, so reporting \"no changes\"\n * without this would be a false all-clear. Always empty in working mode,\n * where those changes are part of the comparison.\n */\n uncommittedSpecFiles: string[];\n}\n\nexport interface DiffOptions {\n /**\n * Compare the base ref against the working tree instead of a head ref.\n * Includes staged, unstaged, and untracked spec files.\n */\n working?: boolean;\n}\n\nexport interface StatusResult {\n project: string;\n /**\n * Spec *files* resolved, not config entries — one glob entry can resolve to\n * many files. The old name `specCount` did not say which, and meant the\n * other thing in `runValidate` (audit run 5, F4).\n */\n specFiles: number;\n byStatus: Record<string, number>;\n lintHealth: { errors: number; warnings: number; passing: number };\n staleSpecs: { specId: string; daysSinceUpdate: number; owner?: string }[];\n integrityIssues: string[];\n /** \"unassessed\" when the suite resolved to zero specs — never a vacuous \"healthy\". */\n verdict: \"healthy\" | \"warnings\" | \"errors\" | \"unassessed\";\n}\n\nexport interface DiffConfig {\n baseline_ref: string;\n staleness_threshold_days: number;\n ignore_paths?: string[];\n}\n\nexport const DEFAULT_DIFF_CONFIG: DiffConfig = {\n baseline_ref: \"main\",\n staleness_threshold_days: 14,\n};\n\nexport class DiffError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"DiffError\";\n }\n}\n","function Diff() {}\nDiff.prototype = {\n diff: function diff(oldString, newString) {\n var _options$timeout;\n var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};\n var callback = options.callback;\n if (typeof options === 'function') {\n callback = options;\n options = {};\n }\n var self = this;\n function done(value) {\n value = self.postProcess(value, options);\n if (callback) {\n setTimeout(function () {\n callback(value);\n }, 0);\n return true;\n } else {\n return value;\n }\n }\n\n // Allow subclasses to massage the input prior to running\n oldString = this.castInput(oldString, options);\n newString = this.castInput(newString, options);\n oldString = this.removeEmpty(this.tokenize(oldString, options));\n newString = this.removeEmpty(this.tokenize(newString, options));\n var newLen = newString.length,\n oldLen = oldString.length;\n var editLength = 1;\n var maxEditLength = newLen + oldLen;\n if (options.maxEditLength != null) {\n maxEditLength = Math.min(maxEditLength, options.maxEditLength);\n }\n var maxExecutionTime = (_options$timeout = options.timeout) !== null && _options$timeout !== void 0 ? _options$timeout : Infinity;\n var abortAfterTimestamp = Date.now() + maxExecutionTime;\n var bestPath = [{\n oldPos: -1,\n lastComponent: undefined\n }];\n\n // Seed editLength = 0, i.e. the content starts with the same values\n var newPos = this.extractCommon(bestPath[0], newString, oldString, 0, options);\n if (bestPath[0].oldPos + 1 >= oldLen && newPos + 1 >= newLen) {\n // Identity per the equality and tokenizer\n return done(buildValues(self, bestPath[0].lastComponent, newString, oldString, self.useLongestToken));\n }\n\n // Once we hit the right edge of the edit graph on some diagonal k, we can\n // definitely reach the end of the edit graph in no more than k edits, so\n // there's no point in considering any moves to diagonal k+1 any more (from\n // which we're guaranteed to need at least k+1 more edits).\n // Similarly, once we've reached the bottom of the edit graph, there's no\n // point considering moves to lower diagonals.\n // We record this fact by setting minDiagonalToConsider and\n // maxDiagonalToConsider to some finite value once we've hit the edge of\n // the edit graph.\n // This optimization is not faithful to the original algorithm presented in\n // Myers's paper, which instead pointlessly extends D-paths off the end of\n // the edit graph - see page 7 of Myers's paper which notes this point\n // explicitly and illustrates it with a diagram. This has major performance\n // implications for some common scenarios. For instance, to compute a diff\n // where the new text simply appends d characters on the end of the\n // original text of length n, the true Myers algorithm will take O(n+d^2)\n // time while this optimization needs only O(n+d) time.\n var minDiagonalToConsider = -Infinity,\n maxDiagonalToConsider = Infinity;\n\n // Main worker method. checks all permutations of a given edit length for acceptance.\n function execEditLength() {\n for (var diagonalPath = Math.max(minDiagonalToConsider, -editLength); diagonalPath <= Math.min(maxDiagonalToConsider, editLength); diagonalPath += 2) {\n var basePath = void 0;\n var removePath = bestPath[diagonalPath - 1],\n addPath = bestPath[diagonalPath + 1];\n if (removePath) {\n // No one else is going to attempt to use this value, clear it\n bestPath[diagonalPath - 1] = undefined;\n }\n var canAdd = false;\n if (addPath) {\n // what newPos will be after we do an insertion:\n var addPathNewPos = addPath.oldPos - diagonalPath;\n canAdd = addPath && 0 <= addPathNewPos && addPathNewPos < newLen;\n }\n var canRemove = removePath && removePath.oldPos + 1 < oldLen;\n if (!canAdd && !canRemove) {\n // If this path is a terminal then prune\n bestPath[diagonalPath] = undefined;\n continue;\n }\n\n // Select the diagonal that we want to branch from. We select the prior\n // path whose position in the old string is the farthest from the origin\n // and does not pass the bounds of the diff graph\n if (!canRemove || canAdd && removePath.oldPos < addPath.oldPos) {\n basePath = self.addToPath(addPath, true, false, 0, options);\n } else {\n basePath = self.addToPath(removePath, false, true, 1, options);\n }\n newPos = self.extractCommon(basePath, newString, oldString, diagonalPath, options);\n if (basePath.oldPos + 1 >= oldLen && newPos + 1 >= newLen) {\n // If we have hit the end of both strings, then we are done\n return done(buildValues(self, basePath.lastComponent, newString, oldString, self.useLongestToken));\n } else {\n bestPath[diagonalPath] = basePath;\n if (basePath.oldPos + 1 >= oldLen) {\n maxDiagonalToConsider = Math.min(maxDiagonalToConsider, diagonalPath - 1);\n }\n if (newPos + 1 >= newLen) {\n minDiagonalToConsider = Math.max(minDiagonalToConsider, diagonalPath + 1);\n }\n }\n }\n editLength++;\n }\n\n // Performs the length of edit iteration. Is a bit fugly as this has to support the\n // sync and async mode which is never fun. Loops over execEditLength until a value\n // is produced, or until the edit length exceeds options.maxEditLength (if given),\n // in which case it will return undefined.\n if (callback) {\n (function exec() {\n setTimeout(function () {\n if (editLength > maxEditLength || Date.now() > abortAfterTimestamp) {\n return callback();\n }\n if (!execEditLength()) {\n exec();\n }\n }, 0);\n })();\n } else {\n while (editLength <= maxEditLength && Date.now() <= abortAfterTimestamp) {\n var ret = execEditLength();\n if (ret) {\n return ret;\n }\n }\n }\n },\n addToPath: function addToPath(path, added, removed, oldPosInc, options) {\n var last = path.lastComponent;\n if (last && !options.oneChangePerToken && last.added === added && last.removed === removed) {\n return {\n oldPos: path.oldPos + oldPosInc,\n lastComponent: {\n count: last.count + 1,\n added: added,\n removed: removed,\n previousComponent: last.previousComponent\n }\n };\n } else {\n return {\n oldPos: path.oldPos + oldPosInc,\n lastComponent: {\n count: 1,\n added: added,\n removed: removed,\n previousComponent: last\n }\n };\n }\n },\n extractCommon: function extractCommon(basePath, newString, oldString, diagonalPath, options) {\n var newLen = newString.length,\n oldLen = oldString.length,\n oldPos = basePath.oldPos,\n newPos = oldPos - diagonalPath,\n commonCount = 0;\n while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(oldString[oldPos + 1], newString[newPos + 1], options)) {\n newPos++;\n oldPos++;\n commonCount++;\n if (options.oneChangePerToken) {\n basePath.lastComponent = {\n count: 1,\n previousComponent: basePath.lastComponent,\n added: false,\n removed: false\n };\n }\n }\n if (commonCount && !options.oneChangePerToken) {\n basePath.lastComponent = {\n count: commonCount,\n previousComponent: basePath.lastComponent,\n added: false,\n removed: false\n };\n }\n basePath.oldPos = oldPos;\n return newPos;\n },\n equals: function equals(left, right, options) {\n if (options.comparator) {\n return options.comparator(left, right);\n } else {\n return left === right || options.ignoreCase && left.toLowerCase() === right.toLowerCase();\n }\n },\n removeEmpty: function removeEmpty(array) {\n var ret = [];\n for (var i = 0; i < array.length; i++) {\n if (array[i]) {\n ret.push(array[i]);\n }\n }\n return ret;\n },\n castInput: function castInput(value) {\n return value;\n },\n tokenize: function tokenize(value) {\n return Array.from(value);\n },\n join: function join(chars) {\n return chars.join('');\n },\n postProcess: function postProcess(changeObjects) {\n return changeObjects;\n }\n};\nfunction buildValues(diff, lastComponent, newString, oldString, useLongestToken) {\n // First we convert our linked list of components in reverse order to an\n // array in the right order:\n var components = [];\n var nextComponent;\n while (lastComponent) {\n components.push(lastComponent);\n nextComponent = lastComponent.previousComponent;\n delete lastComponent.previousComponent;\n lastComponent = nextComponent;\n }\n components.reverse();\n var componentPos = 0,\n componentLen = components.length,\n newPos = 0,\n oldPos = 0;\n for (; componentPos < componentLen; componentPos++) {\n var component = components[componentPos];\n if (!component.removed) {\n if (!component.added && useLongestToken) {\n var value = newString.slice(newPos, newPos + component.count);\n value = value.map(function (value, i) {\n var oldValue = oldString[oldPos + i];\n return oldValue.length > value.length ? oldValue : value;\n });\n component.value = diff.join(value);\n } else {\n component.value = diff.join(newString.slice(newPos, newPos + component.count));\n }\n newPos += component.count;\n\n // Common case\n if (!component.added) {\n oldPos += component.count;\n }\n } else {\n component.value = diff.join(oldString.slice(oldPos, oldPos + component.count));\n oldPos += component.count;\n }\n }\n return components;\n}\n\nvar characterDiff = new Diff();\nfunction diffChars(oldStr, newStr, options) {\n return characterDiff.diff(oldStr, newStr, options);\n}\n\nfunction longestCommonPrefix(str1, str2) {\n var i;\n for (i = 0; i < str1.length && i < str2.length; i++) {\n if (str1[i] != str2[i]) {\n return str1.slice(0, i);\n }\n }\n return str1.slice(0, i);\n}\nfunction longestCommonSuffix(str1, str2) {\n var i;\n\n // Unlike longestCommonPrefix, we need a special case to handle all scenarios\n // where we return the empty string since str1.slice(-0) will return the\n // entire string.\n if (!str1 || !str2 || str1[str1.length - 1] != str2[str2.length - 1]) {\n return '';\n }\n for (i = 0; i < str1.length && i < str2.length; i++) {\n if (str1[str1.length - (i + 1)] != str2[str2.length - (i + 1)]) {\n return str1.slice(-i);\n }\n }\n return str1.slice(-i);\n}\nfunction replacePrefix(string, oldPrefix, newPrefix) {\n if (string.slice(0, oldPrefix.length) != oldPrefix) {\n throw Error(\"string \".concat(JSON.stringify(string), \" doesn't start with prefix \").concat(JSON.stringify(oldPrefix), \"; this is a bug\"));\n }\n return newPrefix + string.slice(oldPrefix.length);\n}\nfunction replaceSuffix(string, oldSuffix, newSuffix) {\n if (!oldSuffix) {\n return string + newSuffix;\n }\n if (string.slice(-oldSuffix.length) != oldSuffix) {\n throw Error(\"string \".concat(JSON.stringify(string), \" doesn't end with suffix \").concat(JSON.stringify(oldSuffix), \"; this is a bug\"));\n }\n return string.slice(0, -oldSuffix.length) + newSuffix;\n}\nfunction removePrefix(string, oldPrefix) {\n return replacePrefix(string, oldPrefix, '');\n}\nfunction removeSuffix(string, oldSuffix) {\n return replaceSuffix(string, oldSuffix, '');\n}\nfunction maximumOverlap(string1, string2) {\n return string2.slice(0, overlapCount(string1, string2));\n}\n\n// Nicked from https://stackoverflow.com/a/60422853/1709587\nfunction overlapCount(a, b) {\n // Deal with cases where the strings differ in length\n var startA = 0;\n if (a.length > b.length) {\n startA = a.length - b.length;\n }\n var endB = b.length;\n if (a.length < b.length) {\n endB = a.length;\n }\n // Create a back-reference for each index\n // that should be followed in case of a mismatch.\n // We only need B to make these references:\n var map = Array(endB);\n var k = 0; // Index that lags behind j\n map[0] = 0;\n for (var j = 1; j < endB; j++) {\n if (b[j] == b[k]) {\n map[j] = map[k]; // skip over the same character (optional optimisation)\n } else {\n map[j] = k;\n }\n while (k > 0 && b[j] != b[k]) {\n k = map[k];\n }\n if (b[j] == b[k]) {\n k++;\n }\n }\n // Phase 2: use these references while iterating over A\n k = 0;\n for (var i = startA; i < a.length; i++) {\n while (k > 0 && a[i] != b[k]) {\n k = map[k];\n }\n if (a[i] == b[k]) {\n k++;\n }\n }\n return k;\n}\n\n/**\n * Returns true if the string consistently uses Windows line endings.\n */\nfunction hasOnlyWinLineEndings(string) {\n return string.includes('\\r\\n') && !string.startsWith('\\n') && !string.match(/[^\\r]\\n/);\n}\n\n/**\n * Returns true if the string consistently uses Unix line endings.\n */\nfunction hasOnlyUnixLineEndings(string) {\n return !string.includes('\\r\\n') && string.includes('\\n');\n}\n\n// Based on https://en.wikipedia.org/wiki/Latin_script_in_Unicode\n//\n// Ranges and exceptions:\n// Latin-1 Supplement, 0080–00FF\n// - U+00D7 × Multiplication sign\n// - U+00F7 ÷ Division sign\n// Latin Extended-A, 0100–017F\n// Latin Extended-B, 0180–024F\n// IPA Extensions, 0250–02AF\n// Spacing Modifier Letters, 02B0–02FF\n// - U+02C7 ˇ &#711; Caron\n// - U+02D8 ˘ &#728; Breve\n// - U+02D9 ˙ &#729; Dot Above\n// - U+02DA ˚ &#730; Ring Above\n// - U+02DB ˛ &#731; Ogonek\n// - U+02DC ˜ &#732; Small Tilde\n// - U+02DD ˝ &#733; Double Acute Accent\n// Latin Extended Additional, 1E00–1EFF\nvar 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}\";\n\n// Each token is one of the following:\n// - A punctuation mark plus the surrounding whitespace\n// - A word plus the surrounding whitespace\n// - Pure whitespace (but only in the special case where this the entire text\n// is just whitespace)\n//\n// We have to include surrounding whitespace in the tokens because the two\n// alternative approaches produce horribly broken results:\n// * If we just discard the whitespace, we can't fully reproduce the original\n// text from the sequence of tokens and any attempt to render the diff will\n// get the whitespace wrong.\n// * If we have separate tokens for whitespace, then in a typical text every\n// second token will be a single space character. But this often results in\n// the optimal diff between two texts being a perverse one that preserves\n// the spaces between words but deletes and reinserts actual common words.\n// See https://github.com/kpdecker/jsdiff/issues/160#issuecomment-1866099640\n// for an example.\n//\n// Keeping the surrounding whitespace of course has implications for .equals\n// and .join, not just .tokenize.\n\n// This regex does NOT fully implement the tokenization rules described above.\n// Instead, it gives runs of whitespace their own \"token\". The tokenize method\n// then handles stitching whitespace tokens onto adjacent word or punctuation\n// tokens.\nvar tokenizeIncludingWhitespace = new RegExp(\"[\".concat(extendedWordChars, \"]+|\\\\s+|[^\").concat(extendedWordChars, \"]\"), 'ug');\nvar wordDiff = new Diff();\nwordDiff.equals = function (left, right, options) {\n if (options.ignoreCase) {\n left = left.toLowerCase();\n right = right.toLowerCase();\n }\n return left.trim() === right.trim();\n};\nwordDiff.tokenize = function (value) {\n var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n var parts;\n if (options.intlSegmenter) {\n if (options.intlSegmenter.resolvedOptions().granularity != 'word') {\n throw new Error('The segmenter passed must have a granularity of \"word\"');\n }\n parts = Array.from(options.intlSegmenter.segment(value), function (segment) {\n return segment.segment;\n });\n } else {\n parts = value.match(tokenizeIncludingWhitespace) || [];\n }\n var tokens = [];\n var prevPart = null;\n parts.forEach(function (part) {\n if (/\\s/.test(part)) {\n if (prevPart == null) {\n tokens.push(part);\n } else {\n tokens.push(tokens.pop() + part);\n }\n } else if (/\\s/.test(prevPart)) {\n if (tokens[tokens.length - 1] == prevPart) {\n tokens.push(tokens.pop() + part);\n } else {\n tokens.push(prevPart + part);\n }\n } else {\n tokens.push(part);\n }\n prevPart = part;\n });\n return tokens;\n};\nwordDiff.join = function (tokens) {\n // Tokens being joined here will always have appeared consecutively in the\n // same text, so we can simply strip off the leading whitespace from all the\n // tokens except the first (and except any whitespace-only tokens - but such\n // a token will always be the first and only token anyway) and then join them\n // and the whitespace around words and punctuation will end up correct.\n return tokens.map(function (token, i) {\n if (i == 0) {\n return token;\n } else {\n return token.replace(/^\\s+/, '');\n }\n }).join('');\n};\nwordDiff.postProcess = function (changes, options) {\n if (!changes || options.oneChangePerToken) {\n return changes;\n }\n var lastKeep = null;\n // Change objects representing any insertion or deletion since the last\n // \"keep\" change object. There can be at most one of each.\n var insertion = null;\n var deletion = null;\n changes.forEach(function (change) {\n if (change.added) {\n insertion = change;\n } else if (change.removed) {\n deletion = change;\n } else {\n if (insertion || deletion) {\n // May be false at start of text\n dedupeWhitespaceInChangeObjects(lastKeep, deletion, insertion, change);\n }\n lastKeep = change;\n insertion = null;\n deletion = null;\n }\n });\n if (insertion || deletion) {\n dedupeWhitespaceInChangeObjects(lastKeep, deletion, insertion, null);\n }\n return changes;\n};\nfunction diffWords(oldStr, newStr, options) {\n // This option has never been documented and never will be (it's clearer to\n // just call `diffWordsWithSpace` directly if you need that behavior), but\n // has existed in jsdiff for a long time, so we retain support for it here\n // for the sake of backwards compatibility.\n if ((options === null || options === void 0 ? void 0 : options.ignoreWhitespace) != null && !options.ignoreWhitespace) {\n return diffWordsWithSpace(oldStr, newStr, options);\n }\n return wordDiff.diff(oldStr, newStr, options);\n}\nfunction dedupeWhitespaceInChangeObjects(startKeep, deletion, insertion, endKeep) {\n // Before returning, we tidy up the leading and trailing whitespace of the\n // change objects to eliminate cases where trailing whitespace in one object\n // is repeated as leading whitespace in the next.\n // Below are examples of the outcomes we want here to explain the code.\n // I=insert, K=keep, D=delete\n // 1. diffing 'foo bar baz' vs 'foo baz'\n // Prior to cleanup, we have K:'foo ' D:' bar ' K:' baz'\n // After cleanup, we want: K:'foo ' D:'bar ' K:'baz'\n //\n // 2. Diffing 'foo bar baz' vs 'foo qux baz'\n // Prior to cleanup, we have K:'foo ' D:' bar ' I:' qux ' K:' baz'\n // After cleanup, we want K:'foo ' D:'bar' I:'qux' K:' baz'\n //\n // 3. Diffing 'foo\\nbar baz' vs 'foo baz'\n // Prior to cleanup, we have K:'foo ' D:'\\nbar ' K:' baz'\n // After cleanup, we want K'foo' D:'\\nbar' K:' baz'\n //\n // 4. Diffing 'foo baz' vs 'foo\\nbar baz'\n // Prior to cleanup, we have K:'foo\\n' I:'\\nbar ' K:' baz'\n // After cleanup, we ideally want K'foo' I:'\\nbar' K:' baz'\n // but don't actually manage this currently (the pre-cleanup change\n // objects don't contain enough information to make it possible).\n //\n // 5. Diffing 'foo bar baz' vs 'foo baz'\n // Prior to cleanup, we have K:'foo ' D:' bar ' K:' baz'\n // After cleanup, we want K:'foo ' D:' bar ' K:'baz'\n //\n // Our handling is unavoidably imperfect in the case where there's a single\n // indel between keeps and the whitespace has changed. For instance, consider\n // diffing 'foo\\tbar\\nbaz' vs 'foo baz'. Unless we create an extra change\n // object to represent the insertion of the space character (which isn't even\n // a token), we have no way to avoid losing information about the texts'\n // original whitespace in the result we return. Still, we do our best to\n // output something that will look sensible if we e.g. print it with\n // insertions in green and deletions in red.\n\n // Between two \"keep\" change objects (or before the first or after the last\n // change object), we can have either:\n // * A \"delete\" followed by an \"insert\"\n // * Just an \"insert\"\n // * Just a \"delete\"\n // We handle the three cases separately.\n if (deletion && insertion) {\n var oldWsPrefix = deletion.value.match(/^\\s*/)[0];\n var oldWsSuffix = deletion.value.match(/\\s*$/)[0];\n var newWsPrefix = insertion.value.match(/^\\s*/)[0];\n var newWsSuffix = insertion.value.match(/\\s*$/)[0];\n if (startKeep) {\n var commonWsPrefix = longestCommonPrefix(oldWsPrefix, newWsPrefix);\n startKeep.value = replaceSuffix(startKeep.value, newWsPrefix, commonWsPrefix);\n deletion.value = removePrefix(deletion.value, commonWsPrefix);\n insertion.value = removePrefix(insertion.value, commonWsPrefix);\n }\n if (endKeep) {\n var commonWsSuffix = longestCommonSuffix(oldWsSuffix, newWsSuffix);\n endKeep.value = replacePrefix(endKeep.value, newWsSuffix, commonWsSuffix);\n deletion.value = removeSuffix(deletion.value, commonWsSuffix);\n insertion.value = removeSuffix(insertion.value, commonWsSuffix);\n }\n } else if (insertion) {\n // The whitespaces all reflect what was in the new text rather than\n // the old, so we essentially have no information about whitespace\n // insertion or deletion. We just want to dedupe the whitespace.\n // We do that by having each change object keep its trailing\n // whitespace and deleting duplicate leading whitespace where\n // present.\n if (startKeep) {\n insertion.value = insertion.value.replace(/^\\s*/, '');\n }\n if (endKeep) {\n endKeep.value = endKeep.value.replace(/^\\s*/, '');\n }\n // otherwise we've got a deletion and no insertion\n } else if (startKeep && endKeep) {\n var newWsFull = endKeep.value.match(/^\\s*/)[0],\n delWsStart = deletion.value.match(/^\\s*/)[0],\n delWsEnd = deletion.value.match(/\\s*$/)[0];\n\n // Any whitespace that comes straight after startKeep in both the old and\n // new texts, assign to startKeep and remove from the deletion.\n var newWsStart = longestCommonPrefix(newWsFull, delWsStart);\n deletion.value = removePrefix(deletion.value, newWsStart);\n\n // Any whitespace that comes straight before endKeep in both the old and\n // new texts, and hasn't already been assigned to startKeep, assign to\n // endKeep and remove from the deletion.\n var newWsEnd = longestCommonSuffix(removePrefix(newWsFull, newWsStart), delWsEnd);\n deletion.value = removeSuffix(deletion.value, newWsEnd);\n endKeep.value = replacePrefix(endKeep.value, newWsFull, newWsEnd);\n\n // If there's any whitespace from the new text that HASN'T already been\n // assigned, assign it to the start:\n startKeep.value = replaceSuffix(startKeep.value, newWsFull, newWsFull.slice(0, newWsFull.length - newWsEnd.length));\n } else if (endKeep) {\n // We are at the start of the text. Preserve all the whitespace on\n // endKeep, and just remove whitespace from the end of deletion to the\n // extent that it overlaps with the start of endKeep.\n var endKeepWsPrefix = endKeep.value.match(/^\\s*/)[0];\n var deletionWsSuffix = deletion.value.match(/\\s*$/)[0];\n var overlap = maximumOverlap(deletionWsSuffix, endKeepWsPrefix);\n deletion.value = removeSuffix(deletion.value, overlap);\n } else if (startKeep) {\n // We are at the END of the text. Preserve all the whitespace on\n // startKeep, and just remove whitespace from the start of deletion to\n // the extent that it overlaps with the end of startKeep.\n var startKeepWsSuffix = startKeep.value.match(/\\s*$/)[0];\n var deletionWsPrefix = deletion.value.match(/^\\s*/)[0];\n var _overlap = maximumOverlap(startKeepWsSuffix, deletionWsPrefix);\n deletion.value = removePrefix(deletion.value, _overlap);\n }\n}\nvar wordWithSpaceDiff = new Diff();\nwordWithSpaceDiff.tokenize = function (value) {\n // Slightly different to the tokenizeIncludingWhitespace regex used above in\n // that this one treats each individual newline as a distinct tokens, rather\n // than merging them into other surrounding whitespace. This was requested\n // in https://github.com/kpdecker/jsdiff/issues/180 &\n // https://github.com/kpdecker/jsdiff/issues/211\n var regex = new RegExp(\"(\\\\r?\\\\n)|[\".concat(extendedWordChars, \"]+|[^\\\\S\\\\n\\\\r]+|[^\").concat(extendedWordChars, \"]\"), 'ug');\n return value.match(regex) || [];\n};\nfunction diffWordsWithSpace(oldStr, newStr, options) {\n return wordWithSpaceDiff.diff(oldStr, newStr, options);\n}\n\nfunction generateOptions(options, defaults) {\n if (typeof options === 'function') {\n defaults.callback = options;\n } else if (options) {\n for (var name in options) {\n /* istanbul ignore else */\n if (options.hasOwnProperty(name)) {\n defaults[name] = options[name];\n }\n }\n }\n return defaults;\n}\n\nvar lineDiff = new Diff();\nlineDiff.tokenize = function (value, options) {\n if (options.stripTrailingCr) {\n // remove one \\r before \\n to match GNU diff's --strip-trailing-cr behavior\n value = value.replace(/\\r\\n/g, '\\n');\n }\n var retLines = [],\n linesAndNewlines = value.split(/(\\n|\\r\\n)/);\n\n // Ignore the final empty token that occurs if the string ends with a new line\n if (!linesAndNewlines[linesAndNewlines.length - 1]) {\n linesAndNewlines.pop();\n }\n\n // Merge the content and line separators into single tokens\n for (var i = 0; i < linesAndNewlines.length; i++) {\n var line = linesAndNewlines[i];\n if (i % 2 && !options.newlineIsToken) {\n retLines[retLines.length - 1] += line;\n } else {\n retLines.push(line);\n }\n }\n return retLines;\n};\nlineDiff.equals = function (left, right, options) {\n // If we're ignoring whitespace, we need to normalise lines by stripping\n // whitespace before checking equality. (This has an annoying interaction\n // with newlineIsToken that requires special handling: if newlines get their\n // own token, then we DON'T want to trim the *newline* tokens down to empty\n // strings, since this would cause us to treat whitespace-only line content\n // as equal to a separator between lines, which would be weird and\n // inconsistent with the documented behavior of the options.)\n if (options.ignoreWhitespace) {\n if (!options.newlineIsToken || !left.includes('\\n')) {\n left = left.trim();\n }\n if (!options.newlineIsToken || !right.includes('\\n')) {\n right = right.trim();\n }\n } else if (options.ignoreNewlineAtEof && !options.newlineIsToken) {\n if (left.endsWith('\\n')) {\n left = left.slice(0, -1);\n }\n if (right.endsWith('\\n')) {\n right = right.slice(0, -1);\n }\n }\n return Diff.prototype.equals.call(this, left, right, options);\n};\nfunction diffLines(oldStr, newStr, callback) {\n return lineDiff.diff(oldStr, newStr, callback);\n}\n\n// Kept for backwards compatibility. This is a rather arbitrary wrapper method\n// that just calls `diffLines` with `ignoreWhitespace: true`. It's confusing to\n// have two ways to do exactly the same thing in the API, so we no longer\n// document this one (library users should explicitly use `diffLines` with\n// `ignoreWhitespace: true` instead) but we keep it around to maintain\n// compatibility with code that used old versions.\nfunction diffTrimmedLines(oldStr, newStr, callback) {\n var options = generateOptions(callback, {\n ignoreWhitespace: true\n });\n return lineDiff.diff(oldStr, newStr, options);\n}\n\nvar sentenceDiff = new Diff();\nsentenceDiff.tokenize = function (value) {\n return value.split(/(\\S.+?[.!?])(?=\\s+|$)/);\n};\nfunction diffSentences(oldStr, newStr, callback) {\n return sentenceDiff.diff(oldStr, newStr, callback);\n}\n\nvar cssDiff = new Diff();\ncssDiff.tokenize = function (value) {\n return value.split(/([{}:;,]|\\s+)/);\n};\nfunction diffCss(oldStr, newStr, callback) {\n return cssDiff.diff(oldStr, newStr, callback);\n}\n\nfunction ownKeys(e, r) {\n var t = Object.keys(e);\n if (Object.getOwnPropertySymbols) {\n var o = Object.getOwnPropertySymbols(e);\n r && (o = o.filter(function (r) {\n return Object.getOwnPropertyDescriptor(e, r).enumerable;\n })), t.push.apply(t, o);\n }\n return t;\n}\nfunction _objectSpread2(e) {\n for (var r = 1; r < arguments.length; r++) {\n var t = null != arguments[r] ? arguments[r] : {};\n r % 2 ? ownKeys(Object(t), !0).forEach(function (r) {\n _defineProperty(e, r, t[r]);\n }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) {\n Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r));\n });\n }\n return e;\n}\nfunction _toPrimitive(t, r) {\n if (\"object\" != typeof t || !t) return t;\n var e = t[Symbol.toPrimitive];\n if (void 0 !== e) {\n var i = e.call(t, r || \"default\");\n if (\"object\" != typeof i) return i;\n throw new TypeError(\"@@toPrimitive must return a primitive value.\");\n }\n return (\"string\" === r ? String : Number)(t);\n}\nfunction _toPropertyKey(t) {\n var i = _toPrimitive(t, \"string\");\n return \"symbol\" == typeof i ? i : i + \"\";\n}\nfunction _typeof(o) {\n \"@babel/helpers - typeof\";\n\n return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) {\n return typeof o;\n } : function (o) {\n return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o;\n }, _typeof(o);\n}\nfunction _defineProperty(obj, key, value) {\n key = _toPropertyKey(key);\n if (key in obj) {\n Object.defineProperty(obj, key, {\n value: value,\n enumerable: true,\n configurable: true,\n writable: true\n });\n } else {\n obj[key] = value;\n }\n return obj;\n}\nfunction _toConsumableArray(arr) {\n return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();\n}\nfunction _arrayWithoutHoles(arr) {\n if (Array.isArray(arr)) return _arrayLikeToArray(arr);\n}\nfunction _iterableToArray(iter) {\n if (typeof Symbol !== \"undefined\" && iter[Symbol.iterator] != null || iter[\"@@iterator\"] != null) return Array.from(iter);\n}\nfunction _unsupportedIterableToArray(o, minLen) {\n if (!o) return;\n if (typeof o === \"string\") return _arrayLikeToArray(o, minLen);\n var n = Object.prototype.toString.call(o).slice(8, -1);\n if (n === \"Object\" && o.constructor) n = o.constructor.name;\n if (n === \"Map\" || n === \"Set\") return Array.from(o);\n if (n === \"Arguments\" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);\n}\nfunction _arrayLikeToArray(arr, len) {\n if (len == null || len > arr.length) len = arr.length;\n for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];\n return arr2;\n}\nfunction _nonIterableSpread() {\n throw new TypeError(\"Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\");\n}\n\nvar jsonDiff = new Diff();\n// Discriminate between two lines of pretty-printed, serialized JSON where one of them has a\n// dangling comma and the other doesn't. Turns out including the dangling comma yields the nicest output:\njsonDiff.useLongestToken = true;\njsonDiff.tokenize = lineDiff.tokenize;\njsonDiff.castInput = function (value, options) {\n var undefinedReplacement = options.undefinedReplacement,\n _options$stringifyRep = options.stringifyReplacer,\n stringifyReplacer = _options$stringifyRep === void 0 ? function (k, v) {\n return typeof v === 'undefined' ? undefinedReplacement : v;\n } : _options$stringifyRep;\n return typeof value === 'string' ? value : JSON.stringify(canonicalize(value, null, null, stringifyReplacer), stringifyReplacer, ' ');\n};\njsonDiff.equals = function (left, right, options) {\n return Diff.prototype.equals.call(jsonDiff, left.replace(/,([\\r\\n])/g, '$1'), right.replace(/,([\\r\\n])/g, '$1'), options);\n};\nfunction diffJson(oldObj, newObj, options) {\n return jsonDiff.diff(oldObj, newObj, options);\n}\n\n// This function handles the presence of circular references by bailing out when encountering an\n// object that is already on the \"stack\" of items being processed. Accepts an optional replacer\nfunction canonicalize(obj, stack, replacementStack, replacer, key) {\n stack = stack || [];\n replacementStack = replacementStack || [];\n if (replacer) {\n obj = replacer(key, obj);\n }\n var i;\n for (i = 0; i < stack.length; i += 1) {\n if (stack[i] === obj) {\n return replacementStack[i];\n }\n }\n var canonicalizedObj;\n if ('[object Array]' === Object.prototype.toString.call(obj)) {\n stack.push(obj);\n canonicalizedObj = new Array(obj.length);\n replacementStack.push(canonicalizedObj);\n for (i = 0; i < obj.length; i += 1) {\n canonicalizedObj[i] = canonicalize(obj[i], stack, replacementStack, replacer, key);\n }\n stack.pop();\n replacementStack.pop();\n return canonicalizedObj;\n }\n if (obj && obj.toJSON) {\n obj = obj.toJSON();\n }\n if (_typeof(obj) === 'object' && obj !== null) {\n stack.push(obj);\n canonicalizedObj = {};\n replacementStack.push(canonicalizedObj);\n var sortedKeys = [],\n _key;\n for (_key in obj) {\n /* istanbul ignore else */\n if (Object.prototype.hasOwnProperty.call(obj, _key)) {\n sortedKeys.push(_key);\n }\n }\n sortedKeys.sort();\n for (i = 0; i < sortedKeys.length; i += 1) {\n _key = sortedKeys[i];\n canonicalizedObj[_key] = canonicalize(obj[_key], stack, replacementStack, replacer, _key);\n }\n stack.pop();\n replacementStack.pop();\n } else {\n canonicalizedObj = obj;\n }\n return canonicalizedObj;\n}\n\nvar arrayDiff = new Diff();\narrayDiff.tokenize = function (value) {\n return value.slice();\n};\narrayDiff.join = arrayDiff.removeEmpty = function (value) {\n return value;\n};\nfunction diffArrays(oldArr, newArr, callback) {\n return arrayDiff.diff(oldArr, newArr, callback);\n}\n\nfunction unixToWin(patch) {\n if (Array.isArray(patch)) {\n return patch.map(unixToWin);\n }\n return _objectSpread2(_objectSpread2({}, patch), {}, {\n hunks: patch.hunks.map(function (hunk) {\n return _objectSpread2(_objectSpread2({}, hunk), {}, {\n lines: hunk.lines.map(function (line, i) {\n var _hunk$lines;\n return line.startsWith('\\\\') || line.endsWith('\\r') || (_hunk$lines = hunk.lines[i + 1]) !== null && _hunk$lines !== void 0 && _hunk$lines.startsWith('\\\\') ? line : line + '\\r';\n })\n });\n })\n });\n}\nfunction winToUnix(patch) {\n if (Array.isArray(patch)) {\n return patch.map(winToUnix);\n }\n return _objectSpread2(_objectSpread2({}, patch), {}, {\n hunks: patch.hunks.map(function (hunk) {\n return _objectSpread2(_objectSpread2({}, hunk), {}, {\n lines: hunk.lines.map(function (line) {\n return line.endsWith('\\r') ? line.substring(0, line.length - 1) : line;\n })\n });\n })\n });\n}\n\n/**\n * Returns true if the patch consistently uses Unix line endings (or only involves one line and has\n * no line endings).\n */\nfunction isUnix(patch) {\n if (!Array.isArray(patch)) {\n patch = [patch];\n }\n return !patch.some(function (index) {\n return index.hunks.some(function (hunk) {\n return hunk.lines.some(function (line) {\n return !line.startsWith('\\\\') && line.endsWith('\\r');\n });\n });\n });\n}\n\n/**\n * Returns true if the patch uses Windows line endings and only Windows line endings.\n */\nfunction isWin(patch) {\n if (!Array.isArray(patch)) {\n patch = [patch];\n }\n return patch.some(function (index) {\n return index.hunks.some(function (hunk) {\n return hunk.lines.some(function (line) {\n return line.endsWith('\\r');\n });\n });\n }) && patch.every(function (index) {\n return index.hunks.every(function (hunk) {\n return hunk.lines.every(function (line, i) {\n var _hunk$lines2;\n return line.startsWith('\\\\') || line.endsWith('\\r') || ((_hunk$lines2 = hunk.lines[i + 1]) === null || _hunk$lines2 === void 0 ? void 0 : _hunk$lines2.startsWith('\\\\'));\n });\n });\n });\n}\n\nfunction parsePatch(uniDiff) {\n var diffstr = uniDiff.split(/\\n/),\n list = [],\n i = 0;\n function parseIndex() {\n var index = {};\n list.push(index);\n\n // Parse diff metadata\n while (i < diffstr.length) {\n var line = diffstr[i];\n\n // File header found, end parsing diff metadata\n if (/^(\\-\\-\\-|\\+\\+\\+|@@)\\s/.test(line)) {\n break;\n }\n\n // Diff index\n var header = /^(?:Index:|diff(?: -r \\w+)+)\\s+(.+?)\\s*$/.exec(line);\n if (header) {\n index.index = header[1];\n }\n i++;\n }\n\n // Parse file headers if they are defined. Unified diff requires them, but\n // there's no technical issues to have an isolated hunk without file header\n parseFileHeader(index);\n parseFileHeader(index);\n\n // Parse hunks\n index.hunks = [];\n while (i < diffstr.length) {\n var _line = diffstr[i];\n if (/^(Index:\\s|diff\\s|\\-\\-\\-\\s|\\+\\+\\+\\s|===================================================================)/.test(_line)) {\n break;\n } else if (/^@@/.test(_line)) {\n index.hunks.push(parseHunk());\n } else if (_line) {\n throw new Error('Unknown line ' + (i + 1) + ' ' + JSON.stringify(_line));\n } else {\n i++;\n }\n }\n }\n\n // Parses the --- and +++ headers, if none are found, no lines\n // are consumed.\n function parseFileHeader(index) {\n var fileHeader = /^(---|\\+\\+\\+)\\s+(.*)\\r?$/.exec(diffstr[i]);\n if (fileHeader) {\n var keyPrefix = fileHeader[1] === '---' ? 'old' : 'new';\n var data = fileHeader[2].split('\\t', 2);\n var fileName = data[0].replace(/\\\\\\\\/g, '\\\\');\n if (/^\".*\"$/.test(fileName)) {\n fileName = fileName.substr(1, fileName.length - 2);\n }\n index[keyPrefix + 'FileName'] = fileName;\n index[keyPrefix + 'Header'] = (data[1] || '').trim();\n i++;\n }\n }\n\n // Parses a hunk\n // This assumes that we are at the start of a hunk.\n function parseHunk() {\n var chunkHeaderIndex = i,\n chunkHeaderLine = diffstr[i++],\n chunkHeader = chunkHeaderLine.split(/@@ -(\\d+)(?:,(\\d+))? \\+(\\d+)(?:,(\\d+))? @@/);\n var hunk = {\n oldStart: +chunkHeader[1],\n oldLines: typeof chunkHeader[2] === 'undefined' ? 1 : +chunkHeader[2],\n newStart: +chunkHeader[3],\n newLines: typeof chunkHeader[4] === 'undefined' ? 1 : +chunkHeader[4],\n lines: []\n };\n\n // Unified Diff Format quirk: If the chunk size is 0,\n // the first number is one lower than one would expect.\n // https://www.artima.com/weblogs/viewpost.jsp?thread=164293\n if (hunk.oldLines === 0) {\n hunk.oldStart += 1;\n }\n if (hunk.newLines === 0) {\n hunk.newStart += 1;\n }\n var addCount = 0,\n removeCount = 0;\n for (; i < diffstr.length && (removeCount < hunk.oldLines || addCount < hunk.newLines || (_diffstr$i = diffstr[i]) !== null && _diffstr$i !== void 0 && _diffstr$i.startsWith('\\\\')); i++) {\n var _diffstr$i;\n var operation = diffstr[i].length == 0 && i != diffstr.length - 1 ? ' ' : diffstr[i][0];\n if (operation === '+' || operation === '-' || operation === ' ' || operation === '\\\\') {\n hunk.lines.push(diffstr[i]);\n if (operation === '+') {\n addCount++;\n } else if (operation === '-') {\n removeCount++;\n } else if (operation === ' ') {\n addCount++;\n removeCount++;\n }\n } else {\n throw new Error(\"Hunk at line \".concat(chunkHeaderIndex + 1, \" contained invalid line \").concat(diffstr[i]));\n }\n }\n\n // Handle the empty block count case\n if (!addCount && hunk.newLines === 1) {\n hunk.newLines = 0;\n }\n if (!removeCount && hunk.oldLines === 1) {\n hunk.oldLines = 0;\n }\n\n // Perform sanity checking\n if (addCount !== hunk.newLines) {\n throw new Error('Added line count did not match for hunk at line ' + (chunkHeaderIndex + 1));\n }\n if (removeCount !== hunk.oldLines) {\n throw new Error('Removed line count did not match for hunk at line ' + (chunkHeaderIndex + 1));\n }\n return hunk;\n }\n while (i < diffstr.length) {\n parseIndex();\n }\n return list;\n}\n\n// Iterator that traverses in the range of [min, max], stepping\n// by distance from a given start position. I.e. for [0, 4], with\n// start of 2, this will iterate 2, 3, 1, 4, 0.\nfunction distanceIterator (start, minLine, maxLine) {\n var wantForward = true,\n backwardExhausted = false,\n forwardExhausted = false,\n localOffset = 1;\n return function iterator() {\n if (wantForward && !forwardExhausted) {\n if (backwardExhausted) {\n localOffset++;\n } else {\n wantForward = false;\n }\n\n // Check if trying to fit beyond text length, and if not, check it fits\n // after offset location (or desired location on first iteration)\n if (start + localOffset <= maxLine) {\n return start + localOffset;\n }\n forwardExhausted = true;\n }\n if (!backwardExhausted) {\n if (!forwardExhausted) {\n wantForward = true;\n }\n\n // Check if trying to fit before text beginning, and if not, check it fits\n // before offset location\n if (minLine <= start - localOffset) {\n return start - localOffset++;\n }\n backwardExhausted = true;\n return iterator();\n }\n\n // We tried to fit hunk before text beginning and beyond text length, then\n // hunk can't fit on the text. Return undefined\n };\n}\n\nfunction applyPatch(source, uniDiff) {\n var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};\n if (typeof uniDiff === 'string') {\n uniDiff = parsePatch(uniDiff);\n }\n if (Array.isArray(uniDiff)) {\n if (uniDiff.length > 1) {\n throw new Error('applyPatch only works with a single input.');\n }\n uniDiff = uniDiff[0];\n }\n if (options.autoConvertLineEndings || options.autoConvertLineEndings == null) {\n if (hasOnlyWinLineEndings(source) && isUnix(uniDiff)) {\n uniDiff = unixToWin(uniDiff);\n } else if (hasOnlyUnixLineEndings(source) && isWin(uniDiff)) {\n uniDiff = winToUnix(uniDiff);\n }\n }\n\n // Apply the diff to the input\n var lines = source.split('\\n'),\n hunks = uniDiff.hunks,\n compareLine = options.compareLine || function (lineNumber, line, operation, patchContent) {\n return line === patchContent;\n },\n fuzzFactor = options.fuzzFactor || 0,\n minLine = 0;\n if (fuzzFactor < 0 || !Number.isInteger(fuzzFactor)) {\n throw new Error('fuzzFactor must be a non-negative integer');\n }\n\n // Special case for empty patch.\n if (!hunks.length) {\n return source;\n }\n\n // Before anything else, handle EOFNL insertion/removal. If the patch tells us to make a change\n // to the EOFNL that is redundant/impossible - i.e. to remove a newline that's not there, or add a\n // newline that already exists - then we either return false and fail to apply the patch (if\n // fuzzFactor is 0) or simply ignore the problem and do nothing (if fuzzFactor is >0).\n // If we do need to remove/add a newline at EOF, this will always be in the final hunk:\n var prevLine = '',\n removeEOFNL = false,\n addEOFNL = false;\n for (var i = 0; i < hunks[hunks.length - 1].lines.length; i++) {\n var line = hunks[hunks.length - 1].lines[i];\n if (line[0] == '\\\\') {\n if (prevLine[0] == '+') {\n removeEOFNL = true;\n } else if (prevLine[0] == '-') {\n addEOFNL = true;\n }\n }\n prevLine = line;\n }\n if (removeEOFNL) {\n if (addEOFNL) {\n // This means the final line gets changed but doesn't have a trailing newline in either the\n // original or patched version. In that case, we do nothing if fuzzFactor > 0, and if\n // fuzzFactor is 0, we simply validate that the source file has no trailing newline.\n if (!fuzzFactor && lines[lines.length - 1] == '') {\n return false;\n }\n } else if (lines[lines.length - 1] == '') {\n lines.pop();\n } else if (!fuzzFactor) {\n return false;\n }\n } else if (addEOFNL) {\n if (lines[lines.length - 1] != '') {\n lines.push('');\n } else if (!fuzzFactor) {\n return false;\n }\n }\n\n /**\n * Checks if the hunk can be made to fit at the provided location with at most `maxErrors`\n * insertions, substitutions, or deletions, while ensuring also that:\n * - lines deleted in the hunk match exactly, and\n * - wherever an insertion operation or block of insertion operations appears in the hunk, the\n * immediately preceding and following lines of context match exactly\n *\n * `toPos` should be set such that lines[toPos] is meant to match hunkLines[0].\n *\n * If the hunk can be applied, returns an object with properties `oldLineLastI` and\n * `replacementLines`. Otherwise, returns null.\n */\n function applyHunk(hunkLines, toPos, maxErrors) {\n var hunkLinesI = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0;\n var lastContextLineMatched = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : true;\n var patchedLines = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : [];\n var patchedLinesLength = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : 0;\n var nConsecutiveOldContextLines = 0;\n var nextContextLineMustMatch = false;\n for (; hunkLinesI < hunkLines.length; hunkLinesI++) {\n var hunkLine = hunkLines[hunkLinesI],\n operation = hunkLine.length > 0 ? hunkLine[0] : ' ',\n content = hunkLine.length > 0 ? hunkLine.substr(1) : hunkLine;\n if (operation === '-') {\n if (compareLine(toPos + 1, lines[toPos], operation, content)) {\n toPos++;\n nConsecutiveOldContextLines = 0;\n } else {\n if (!maxErrors || lines[toPos] == null) {\n return null;\n }\n patchedLines[patchedLinesLength] = lines[toPos];\n return applyHunk(hunkLines, toPos + 1, maxErrors - 1, hunkLinesI, false, patchedLines, patchedLinesLength + 1);\n }\n }\n if (operation === '+') {\n if (!lastContextLineMatched) {\n return null;\n }\n patchedLines[patchedLinesLength] = content;\n patchedLinesLength++;\n nConsecutiveOldContextLines = 0;\n nextContextLineMustMatch = true;\n }\n if (operation === ' ') {\n nConsecutiveOldContextLines++;\n patchedLines[patchedLinesLength] = lines[toPos];\n if (compareLine(toPos + 1, lines[toPos], operation, content)) {\n patchedLinesLength++;\n lastContextLineMatched = true;\n nextContextLineMustMatch = false;\n toPos++;\n } else {\n if (nextContextLineMustMatch || !maxErrors) {\n return null;\n }\n\n // Consider 3 possibilities in sequence:\n // 1. lines contains a *substitution* not included in the patch context, or\n // 2. lines contains an *insertion* not included in the patch context, or\n // 3. lines contains a *deletion* not included in the patch context\n // The first two options are of course only possible if the line from lines is non-null -\n // i.e. only option 3 is possible if we've overrun the end of the old file.\n return lines[toPos] && (applyHunk(hunkLines, toPos + 1, maxErrors - 1, hunkLinesI + 1, false, patchedLines, patchedLinesLength + 1) || applyHunk(hunkLines, toPos + 1, maxErrors - 1, hunkLinesI, false, patchedLines, patchedLinesLength + 1)) || applyHunk(hunkLines, toPos, maxErrors - 1, hunkLinesI + 1, false, patchedLines, patchedLinesLength);\n }\n }\n }\n\n // Before returning, trim any unmodified context lines off the end of patchedLines and reduce\n // toPos (and thus oldLineLastI) accordingly. This allows later hunks to be applied to a region\n // that starts in this hunk's trailing context.\n patchedLinesLength -= nConsecutiveOldContextLines;\n toPos -= nConsecutiveOldContextLines;\n patchedLines.length = patchedLinesLength;\n return {\n patchedLines: patchedLines,\n oldLineLastI: toPos - 1\n };\n }\n var resultLines = [];\n\n // Search best fit offsets for each hunk based on the previous ones\n var prevHunkOffset = 0;\n for (var _i = 0; _i < hunks.length; _i++) {\n var hunk = hunks[_i];\n var hunkResult = void 0;\n var maxLine = lines.length - hunk.oldLines + fuzzFactor;\n var toPos = void 0;\n for (var maxErrors = 0; maxErrors <= fuzzFactor; maxErrors++) {\n toPos = hunk.oldStart + prevHunkOffset - 1;\n var iterator = distanceIterator(toPos, minLine, maxLine);\n for (; toPos !== undefined; toPos = iterator()) {\n hunkResult = applyHunk(hunk.lines, toPos, maxErrors);\n if (hunkResult) {\n break;\n }\n }\n if (hunkResult) {\n break;\n }\n }\n if (!hunkResult) {\n return false;\n }\n\n // Copy everything from the end of where we applied the last hunk to the start of this hunk\n for (var _i2 = minLine; _i2 < toPos; _i2++) {\n resultLines.push(lines[_i2]);\n }\n\n // Add the lines produced by applying the hunk:\n for (var _i3 = 0; _i3 < hunkResult.patchedLines.length; _i3++) {\n var _line = hunkResult.patchedLines[_i3];\n resultLines.push(_line);\n }\n\n // Set lower text limit to end of the current hunk, so next ones don't try\n // to fit over already patched text\n minLine = hunkResult.oldLineLastI + 1;\n\n // Note the offset between where the patch said the hunk should've applied and where we\n // applied it, so we can adjust future hunks accordingly:\n prevHunkOffset = toPos + 1 - hunk.oldStart;\n }\n\n // Copy over the rest of the lines from the old text\n for (var _i4 = minLine; _i4 < lines.length; _i4++) {\n resultLines.push(lines[_i4]);\n }\n return resultLines.join('\\n');\n}\n\n// Wrapper that supports multiple file patches via callbacks.\nfunction applyPatches(uniDiff, options) {\n if (typeof uniDiff === 'string') {\n uniDiff = parsePatch(uniDiff);\n }\n var currentIndex = 0;\n function processIndex() {\n var index = uniDiff[currentIndex++];\n if (!index) {\n return options.complete();\n }\n options.loadFile(index, function (err, data) {\n if (err) {\n return options.complete(err);\n }\n var updatedContent = applyPatch(data, index, options);\n options.patched(index, updatedContent, function (err) {\n if (err) {\n return options.complete(err);\n }\n processIndex();\n });\n });\n }\n processIndex();\n}\n\nfunction structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) {\n if (!options) {\n options = {};\n }\n if (typeof options === 'function') {\n options = {\n callback: options\n };\n }\n if (typeof options.context === 'undefined') {\n options.context = 4;\n }\n if (options.newlineIsToken) {\n throw new Error('newlineIsToken may not be used with patch-generation functions, only with diffing functions');\n }\n if (!options.callback) {\n return diffLinesResultToPatch(diffLines(oldStr, newStr, options));\n } else {\n var _options = options,\n _callback = _options.callback;\n diffLines(oldStr, newStr, _objectSpread2(_objectSpread2({}, options), {}, {\n callback: function callback(diff) {\n var patch = diffLinesResultToPatch(diff);\n _callback(patch);\n }\n }));\n }\n function diffLinesResultToPatch(diff) {\n // STEP 1: Build up the patch with no \"\\" lines and with the arrays\n // of lines containing trailing newline characters. We'll tidy up later...\n\n if (!diff) {\n return;\n }\n diff.push({\n value: '',\n lines: []\n }); // Append an empty value to make cleanup easier\n\n function contextLines(lines) {\n return lines.map(function (entry) {\n return ' ' + entry;\n });\n }\n var hunks = [];\n var oldRangeStart = 0,\n newRangeStart = 0,\n curRange = [],\n oldLine = 1,\n newLine = 1;\n var _loop = function _loop() {\n var current = diff[i],\n lines = current.lines || splitLines(current.value);\n current.lines = lines;\n if (current.added || current.removed) {\n var _curRange;\n // If we have previous context, start with that\n if (!oldRangeStart) {\n var prev = diff[i - 1];\n oldRangeStart = oldLine;\n newRangeStart = newLine;\n if (prev) {\n curRange = options.context > 0 ? contextLines(prev.lines.slice(-options.context)) : [];\n oldRangeStart -= curRange.length;\n newRangeStart -= curRange.length;\n }\n }\n\n // Output our changes\n (_curRange = curRange).push.apply(_curRange, _toConsumableArray(lines.map(function (entry) {\n return (current.added ? '+' : '-') + entry;\n })));\n\n // Track the updated file position\n if (current.added) {\n newLine += lines.length;\n } else {\n oldLine += lines.length;\n }\n } else {\n // Identical context lines. Track line changes\n if (oldRangeStart) {\n // Close out any changes that have been output (or join overlapping)\n if (lines.length <= options.context * 2 && i < diff.length - 2) {\n var _curRange2;\n // Overlapping\n (_curRange2 = curRange).push.apply(_curRange2, _toConsumableArray(contextLines(lines)));\n } else {\n var _curRange3;\n // end the range and output\n var contextSize = Math.min(lines.length, options.context);\n (_curRange3 = curRange).push.apply(_curRange3, _toConsumableArray(contextLines(lines.slice(0, contextSize))));\n var _hunk = {\n oldStart: oldRangeStart,\n oldLines: oldLine - oldRangeStart + contextSize,\n newStart: newRangeStart,\n newLines: newLine - newRangeStart + contextSize,\n lines: curRange\n };\n hunks.push(_hunk);\n oldRangeStart = 0;\n newRangeStart = 0;\n curRange = [];\n }\n }\n oldLine += lines.length;\n newLine += lines.length;\n }\n };\n for (var i = 0; i < diff.length; i++) {\n _loop();\n }\n\n // Step 2: eliminate the trailing `\\n` from each line of each hunk, and, where needed, add\n // \"\\".\n for (var _i = 0, _hunks = hunks; _i < _hunks.length; _i++) {\n var hunk = _hunks[_i];\n for (var _i2 = 0; _i2 < hunk.lines.length; _i2++) {\n if (hunk.lines[_i2].endsWith('\\n')) {\n hunk.lines[_i2] = hunk.lines[_i2].slice(0, -1);\n } else {\n hunk.lines.splice(_i2 + 1, 0, '\\\');\n _i2++; // Skip the line we just added, then continue iterating\n }\n }\n }\n return {\n oldFileName: oldFileName,\n newFileName: newFileName,\n oldHeader: oldHeader,\n newHeader: newHeader,\n hunks: hunks\n };\n }\n}\nfunction formatPatch(diff) {\n if (Array.isArray(diff)) {\n return diff.map(formatPatch).join('\\n');\n }\n var ret = [];\n if (diff.oldFileName == diff.newFileName) {\n ret.push('Index: ' + diff.oldFileName);\n }\n ret.push('===================================================================');\n ret.push('--- ' + diff.oldFileName + (typeof diff.oldHeader === 'undefined' ? '' : '\\t' + diff.oldHeader));\n ret.push('+++ ' + diff.newFileName + (typeof diff.newHeader === 'undefined' ? '' : '\\t' + diff.newHeader));\n for (var i = 0; i < diff.hunks.length; i++) {\n var hunk = diff.hunks[i];\n // Unified Diff Format quirk: If the chunk size is 0,\n // the first number is one lower than one would expect.\n // https://www.artima.com/weblogs/viewpost.jsp?thread=164293\n if (hunk.oldLines === 0) {\n hunk.oldStart -= 1;\n }\n if (hunk.newLines === 0) {\n hunk.newStart -= 1;\n }\n ret.push('@@ -' + hunk.oldStart + ',' + hunk.oldLines + ' +' + hunk.newStart + ',' + hunk.newLines + ' @@');\n ret.push.apply(ret, hunk.lines);\n }\n return ret.join('\\n') + '\\n';\n}\nfunction createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) {\n var _options2;\n if (typeof options === 'function') {\n options = {\n callback: options\n };\n }\n if (!((_options2 = options) !== null && _options2 !== void 0 && _options2.callback)) {\n var patchObj = structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options);\n if (!patchObj) {\n return;\n }\n return formatPatch(patchObj);\n } else {\n var _options3 = options,\n _callback2 = _options3.callback;\n structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, _objectSpread2(_objectSpread2({}, options), {}, {\n callback: function callback(patchObj) {\n if (!patchObj) {\n _callback2();\n } else {\n _callback2(formatPatch(patchObj));\n }\n }\n }));\n }\n}\nfunction createPatch(fileName, oldStr, newStr, oldHeader, newHeader, options) {\n return createTwoFilesPatch(fileName, fileName, oldStr, newStr, oldHeader, newHeader, options);\n}\n\n/**\n * Split `text` into an array of lines, including the trailing newline character (where present)\n */\nfunction splitLines(text) {\n var hasTrailingNl = text.endsWith('\\n');\n var result = text.split('\\n').map(function (line) {\n return line + '\\n';\n });\n if (hasTrailingNl) {\n result.pop();\n } else {\n result.push(result.pop().slice(0, -1));\n }\n return result;\n}\n\nfunction arrayEqual(a, b) {\n if (a.length !== b.length) {\n return false;\n }\n return arrayStartsWith(a, b);\n}\nfunction arrayStartsWith(array, start) {\n if (start.length > array.length) {\n return false;\n }\n for (var i = 0; i < start.length; i++) {\n if (start[i] !== array[i]) {\n return false;\n }\n }\n return true;\n}\n\nfunction calcLineCount(hunk) {\n var _calcOldNewLineCount = calcOldNewLineCount(hunk.lines),\n oldLines = _calcOldNewLineCount.oldLines,\n newLines = _calcOldNewLineCount.newLines;\n if (oldLines !== undefined) {\n hunk.oldLines = oldLines;\n } else {\n delete hunk.oldLines;\n }\n if (newLines !== undefined) {\n hunk.newLines = newLines;\n } else {\n delete hunk.newLines;\n }\n}\nfunction merge(mine, theirs, base) {\n mine = loadPatch(mine, base);\n theirs = loadPatch(theirs, base);\n var ret = {};\n\n // For index we just let it pass through as it doesn't have any necessary meaning.\n // Leaving sanity checks on this to the API consumer that may know more about the\n // meaning in their own context.\n if (mine.index || theirs.index) {\n ret.index = mine.index || theirs.index;\n }\n if (mine.newFileName || theirs.newFileName) {\n if (!fileNameChanged(mine)) {\n // No header or no change in ours, use theirs (and ours if theirs does not exist)\n ret.oldFileName = theirs.oldFileName || mine.oldFileName;\n ret.newFileName = theirs.newFileName || mine.newFileName;\n ret.oldHeader = theirs.oldHeader || mine.oldHeader;\n ret.newHeader = theirs.newHeader || mine.newHeader;\n } else if (!fileNameChanged(theirs)) {\n // No header or no change in theirs, use ours\n ret.oldFileName = mine.oldFileName;\n ret.newFileName = mine.newFileName;\n ret.oldHeader = mine.oldHeader;\n ret.newHeader = mine.newHeader;\n } else {\n // Both changed... figure it out\n ret.oldFileName = selectField(ret, mine.oldFileName, theirs.oldFileName);\n ret.newFileName = selectField(ret, mine.newFileName, theirs.newFileName);\n ret.oldHeader = selectField(ret, mine.oldHeader, theirs.oldHeader);\n ret.newHeader = selectField(ret, mine.newHeader, theirs.newHeader);\n }\n }\n ret.hunks = [];\n var mineIndex = 0,\n theirsIndex = 0,\n mineOffset = 0,\n theirsOffset = 0;\n while (mineIndex < mine.hunks.length || theirsIndex < theirs.hunks.length) {\n var mineCurrent = mine.hunks[mineIndex] || {\n oldStart: Infinity\n },\n theirsCurrent = theirs.hunks[theirsIndex] || {\n oldStart: Infinity\n };\n if (hunkBefore(mineCurrent, theirsCurrent)) {\n // This patch does not overlap with any of the others, yay.\n ret.hunks.push(cloneHunk(mineCurrent, mineOffset));\n mineIndex++;\n theirsOffset += mineCurrent.newLines - mineCurrent.oldLines;\n } else if (hunkBefore(theirsCurrent, mineCurrent)) {\n // This patch does not overlap with any of the others, yay.\n ret.hunks.push(cloneHunk(theirsCurrent, theirsOffset));\n theirsIndex++;\n mineOffset += theirsCurrent.newLines - theirsCurrent.oldLines;\n } else {\n // Overlap, merge as best we can\n var mergedHunk = {\n oldStart: Math.min(mineCurrent.oldStart, theirsCurrent.oldStart),\n oldLines: 0,\n newStart: Math.min(mineCurrent.newStart + mineOffset, theirsCurrent.oldStart + theirsOffset),\n newLines: 0,\n lines: []\n };\n mergeLines(mergedHunk, mineCurrent.oldStart, mineCurrent.lines, theirsCurrent.oldStart, theirsCurrent.lines);\n theirsIndex++;\n mineIndex++;\n ret.hunks.push(mergedHunk);\n }\n }\n return ret;\n}\nfunction loadPatch(param, base) {\n if (typeof param === 'string') {\n if (/^@@/m.test(param) || /^Index:/m.test(param)) {\n return parsePatch(param)[0];\n }\n if (!base) {\n throw new Error('Must provide a base reference or pass in a patch');\n }\n return structuredPatch(undefined, undefined, base, param);\n }\n return param;\n}\nfunction fileNameChanged(patch) {\n return patch.newFileName && patch.newFileName !== patch.oldFileName;\n}\nfunction selectField(index, mine, theirs) {\n if (mine === theirs) {\n return mine;\n } else {\n index.conflict = true;\n return {\n mine: mine,\n theirs: theirs\n };\n }\n}\nfunction hunkBefore(test, check) {\n return test.oldStart < check.oldStart && test.oldStart + test.oldLines < check.oldStart;\n}\nfunction cloneHunk(hunk, offset) {\n return {\n oldStart: hunk.oldStart,\n oldLines: hunk.oldLines,\n newStart: hunk.newStart + offset,\n newLines: hunk.newLines,\n lines: hunk.lines\n };\n}\nfunction mergeLines(hunk, mineOffset, mineLines, theirOffset, theirLines) {\n // This will generally result in a conflicted hunk, but there are cases where the context\n // is the only overlap where we can successfully merge the content here.\n var mine = {\n offset: mineOffset,\n lines: mineLines,\n index: 0\n },\n their = {\n offset: theirOffset,\n lines: theirLines,\n index: 0\n };\n\n // Handle any leading content\n insertLeading(hunk, mine, their);\n insertLeading(hunk, their, mine);\n\n // Now in the overlap content. Scan through and select the best changes from each.\n while (mine.index < mine.lines.length && their.index < their.lines.length) {\n var mineCurrent = mine.lines[mine.index],\n theirCurrent = their.lines[their.index];\n if ((mineCurrent[0] === '-' || mineCurrent[0] === '+') && (theirCurrent[0] === '-' || theirCurrent[0] === '+')) {\n // Both modified ...\n mutualChange(hunk, mine, their);\n } else if (mineCurrent[0] === '+' && theirCurrent[0] === ' ') {\n var _hunk$lines;\n // Mine inserted\n (_hunk$lines = hunk.lines).push.apply(_hunk$lines, _toConsumableArray(collectChange(mine)));\n } else if (theirCurrent[0] === '+' && mineCurrent[0] === ' ') {\n var _hunk$lines2;\n // Theirs inserted\n (_hunk$lines2 = hunk.lines).push.apply(_hunk$lines2, _toConsumableArray(collectChange(their)));\n } else if (mineCurrent[0] === '-' && theirCurrent[0] === ' ') {\n // Mine removed or edited\n removal(hunk, mine, their);\n } else if (theirCurrent[0] === '-' && mineCurrent[0] === ' ') {\n // Their removed or edited\n removal(hunk, their, mine, true);\n } else if (mineCurrent === theirCurrent) {\n // Context identity\n hunk.lines.push(mineCurrent);\n mine.index++;\n their.index++;\n } else {\n // Context mismatch\n conflict(hunk, collectChange(mine), collectChange(their));\n }\n }\n\n // Now push anything that may be remaining\n insertTrailing(hunk, mine);\n insertTrailing(hunk, their);\n calcLineCount(hunk);\n}\nfunction mutualChange(hunk, mine, their) {\n var myChanges = collectChange(mine),\n theirChanges = collectChange(their);\n if (allRemoves(myChanges) && allRemoves(theirChanges)) {\n // Special case for remove changes that are supersets of one another\n if (arrayStartsWith(myChanges, theirChanges) && skipRemoveSuperset(their, myChanges, myChanges.length - theirChanges.length)) {\n var _hunk$lines3;\n (_hunk$lines3 = hunk.lines).push.apply(_hunk$lines3, _toConsumableArray(myChanges));\n return;\n } else if (arrayStartsWith(theirChanges, myChanges) && skipRemoveSuperset(mine, theirChanges, theirChanges.length - myChanges.length)) {\n var _hunk$lines4;\n (_hunk$lines4 = hunk.lines).push.apply(_hunk$lines4, _toConsumableArray(theirChanges));\n return;\n }\n } else if (arrayEqual(myChanges, theirChanges)) {\n var _hunk$lines5;\n (_hunk$lines5 = hunk.lines).push.apply(_hunk$lines5, _toConsumableArray(myChanges));\n return;\n }\n conflict(hunk, myChanges, theirChanges);\n}\nfunction removal(hunk, mine, their, swap) {\n var myChanges = collectChange(mine),\n theirChanges = collectContext(their, myChanges);\n if (theirChanges.merged) {\n var _hunk$lines6;\n (_hunk$lines6 = hunk.lines).push.apply(_hunk$lines6, _toConsumableArray(theirChanges.merged));\n } else {\n conflict(hunk, swap ? theirChanges : myChanges, swap ? myChanges : theirChanges);\n }\n}\nfunction conflict(hunk, mine, their) {\n hunk.conflict = true;\n hunk.lines.push({\n conflict: true,\n mine: mine,\n theirs: their\n });\n}\nfunction insertLeading(hunk, insert, their) {\n while (insert.offset < their.offset && insert.index < insert.lines.length) {\n var line = insert.lines[insert.index++];\n hunk.lines.push(line);\n insert.offset++;\n }\n}\nfunction insertTrailing(hunk, insert) {\n while (insert.index < insert.lines.length) {\n var line = insert.lines[insert.index++];\n hunk.lines.push(line);\n }\n}\nfunction collectChange(state) {\n var ret = [],\n operation = state.lines[state.index][0];\n while (state.index < state.lines.length) {\n var line = state.lines[state.index];\n\n // Group additions that are immediately after subtractions and treat them as one \"atomic\" modify change.\n if (operation === '-' && line[0] === '+') {\n operation = '+';\n }\n if (operation === line[0]) {\n ret.push(line);\n state.index++;\n } else {\n break;\n }\n }\n return ret;\n}\nfunction collectContext(state, matchChanges) {\n var changes = [],\n merged = [],\n matchIndex = 0,\n contextChanges = false,\n conflicted = false;\n while (matchIndex < matchChanges.length && state.index < state.lines.length) {\n var change = state.lines[state.index],\n match = matchChanges[matchIndex];\n\n // Once we've hit our add, then we are done\n if (match[0] === '+') {\n break;\n }\n contextChanges = contextChanges || change[0] !== ' ';\n merged.push(match);\n matchIndex++;\n\n // Consume any additions in the other block as a conflict to attempt\n // to pull in the remaining context after this\n if (change[0] === '+') {\n conflicted = true;\n while (change[0] === '+') {\n changes.push(change);\n change = state.lines[++state.index];\n }\n }\n if (match.substr(1) === change.substr(1)) {\n changes.push(change);\n state.index++;\n } else {\n conflicted = true;\n }\n }\n if ((matchChanges[matchIndex] || '')[0] === '+' && contextChanges) {\n conflicted = true;\n }\n if (conflicted) {\n return changes;\n }\n while (matchIndex < matchChanges.length) {\n merged.push(matchChanges[matchIndex++]);\n }\n return {\n merged: merged,\n changes: changes\n };\n}\nfunction allRemoves(changes) {\n return changes.reduce(function (prev, change) {\n return prev && change[0] === '-';\n }, true);\n}\nfunction skipRemoveSuperset(state, removeChanges, delta) {\n for (var i = 0; i < delta; i++) {\n var changeContent = removeChanges[removeChanges.length - delta + i].substr(1);\n if (state.lines[state.index + i] !== ' ' + changeContent) {\n return false;\n }\n }\n state.index += delta;\n return true;\n}\nfunction calcOldNewLineCount(lines) {\n var oldLines = 0;\n var newLines = 0;\n lines.forEach(function (line) {\n if (typeof line !== 'string') {\n var myCount = calcOldNewLineCount(line.mine);\n var theirCount = calcOldNewLineCount(line.theirs);\n if (oldLines !== undefined) {\n if (myCount.oldLines === theirCount.oldLines) {\n oldLines += myCount.oldLines;\n } else {\n oldLines = undefined;\n }\n }\n if (newLines !== undefined) {\n if (myCount.newLines === theirCount.newLines) {\n newLines += myCount.newLines;\n } else {\n newLines = undefined;\n }\n }\n } else {\n if (newLines !== undefined && (line[0] === '+' || line[0] === ' ')) {\n newLines++;\n }\n if (oldLines !== undefined && (line[0] === '-' || line[0] === ' ')) {\n oldLines++;\n }\n }\n });\n return {\n oldLines: oldLines,\n newLines: newLines\n };\n}\n\nfunction reversePatch(structuredPatch) {\n if (Array.isArray(structuredPatch)) {\n return structuredPatch.map(reversePatch).reverse();\n }\n return _objectSpread2(_objectSpread2({}, structuredPatch), {}, {\n oldFileName: structuredPatch.newFileName,\n oldHeader: structuredPatch.newHeader,\n newFileName: structuredPatch.oldFileName,\n newHeader: structuredPatch.oldHeader,\n hunks: structuredPatch.hunks.map(function (hunk) {\n return {\n oldLines: hunk.newLines,\n oldStart: hunk.newStart,\n newLines: hunk.oldLines,\n newStart: hunk.oldStart,\n lines: hunk.lines.map(function (l) {\n if (l.startsWith('-')) {\n return \"+\".concat(l.slice(1));\n }\n if (l.startsWith('+')) {\n return \"-\".concat(l.slice(1));\n }\n return l;\n })\n };\n })\n });\n}\n\n// See: http://code.google.com/p/google-diff-match-patch/wiki/API\nfunction convertChangesToDMP(changes) {\n var ret = [],\n change,\n operation;\n for (var i = 0; i < changes.length; i++) {\n change = changes[i];\n if (change.added) {\n operation = 1;\n } else if (change.removed) {\n operation = -1;\n } else {\n operation = 0;\n }\n ret.push([operation, change.value]);\n }\n return ret;\n}\n\nfunction convertChangesToXML(changes) {\n var ret = [];\n for (var i = 0; i < changes.length; i++) {\n var change = changes[i];\n if (change.added) {\n ret.push('<ins>');\n } else if (change.removed) {\n ret.push('<del>');\n }\n ret.push(escapeHTML(change.value));\n if (change.added) {\n ret.push('</ins>');\n } else if (change.removed) {\n ret.push('</del>');\n }\n }\n return ret.join('');\n}\nfunction escapeHTML(s) {\n var n = s;\n n = n.replace(/&/g, '&amp;');\n n = n.replace(/</g, '&lt;');\n n = n.replace(/>/g, '&gt;');\n n = n.replace(/\"/g, '&quot;');\n return n;\n}\n\nexport { Diff, applyPatch, applyPatches, canonicalize, convertChangesToDMP, convertChangesToXML, createPatch, createTwoFilesPatch, diffArrays, diffChars, diffCss, diffJson, diffLines, diffSentences, diffTrimmedLines, diffWords, diffWordsWithSpace, formatPatch, merge, parsePatch, reversePatch, structuredPatch };\n","import type { ParsedSpec, ParsedSection } from \"@specdx/core\";\nimport { createPatch } from \"diff\";\nimport type { SpecDiff, FieldChange, SectionChange } from \"./types.js\";\n\nexport function diffSpecs(before: ParsedSpec, after: ParsedSpec): SpecDiff {\n const frontmatter = diffFrontmatter(before.frontmatter, after.frontmatter);\n const sections = diffSections(before.parsedSections, after.parsedSections);\n const specId = after.frontmatter.id as string;\n\n const parts: string[] = [];\n if (frontmatter.length > 0) parts.push(`${frontmatter.length} field(s) changed`);\n if (sections.length > 0) parts.push(`${sections.length} section(s) changed`);\n const summary = parts.length > 0 ? `${specId}: ${parts.join(\", \")}` : `${specId}: no changes`;\n\n return { specId, filePath: after.filePath, frontmatter, sections, summary };\n}\n\nfunction diffFrontmatter(\n before: Record<string, unknown>,\n after: Record<string, unknown>,\n): FieldChange[] {\n const changes: FieldChange[] = [];\n const allKeys = new Set([...Object.keys(before), ...Object.keys(after)]);\n\n for (const key of allKeys) {\n const inBefore = Object.prototype.hasOwnProperty.call(before, key);\n const inAfter = Object.prototype.hasOwnProperty.call(after, key);\n\n if (inBefore && !inAfter) {\n changes.push({ field: key, type: \"removed\", before: before[key] });\n } else if (!inBefore && inAfter) {\n changes.push({ field: key, type: \"added\", after: after[key] });\n } else if (inBefore && inAfter) {\n const bVal = before[key];\n const aVal = after[key];\n if (JSON.stringify(bVal) !== JSON.stringify(aVal)) {\n changes.push({ field: key, type: \"modified\", before: bVal, after: aVal });\n }\n }\n }\n\n return changes;\n}\n\nfunction diffSections(before: ParsedSection[], after: ParsedSection[]): SectionChange[] {\n const changes: SectionChange[] = [];\n\n const beforeMap = new Map<string, ParsedSection>();\n for (const section of before) {\n beforeMap.set(section.heading, section);\n }\n\n const afterMap = new Map<string, ParsedSection>();\n for (const section of after) {\n afterMap.set(section.heading, section);\n }\n\n // Removed sections: in before but not in after\n for (const [heading] of beforeMap) {\n if (!afterMap.has(heading)) {\n changes.push({ heading, type: \"removed\" });\n }\n }\n\n // Added or modified sections\n for (const [heading, afterSection] of afterMap) {\n const beforeSection = beforeMap.get(heading);\n if (!beforeSection) {\n changes.push({ heading, type: \"added\" });\n } else if (beforeSection.content !== afterSection.content) {\n const contentDiff = createPatch(\n heading,\n beforeSection.content,\n afterSection.content,\n \"before\",\n \"after\",\n );\n changes.push({ heading, type: \"modified\", contentDiff });\n }\n }\n\n return changes;\n}\n","import type { RelationResolver, ParsedSpec } from \"@specdx/core\";\nimport type { SpecDiff, ImpactAnalysis, DownstreamImpact } from \"./types.js\";\n\nconst STRUCTURAL_SECTIONS = new Set([\n \"Goals\",\n \"Architecture\",\n \"Features\",\n \"Endpoints\",\n \"Data Model\",\n \"API Design\",\n \"Problem Statement\",\n]);\n\n/**\n * Calculate BFS distances from a starting spec id using relation edges.\n * Returns a map of specId -> shortest distance from the start spec.\n */\nfunction bfsDistances(startId: string, relations: RelationResolver): Map<string, number> {\n const distances = new Map<string, number>();\n const queue: Array<{ id: string; distance: number }> = [];\n\n // Seed queue with direct downstream neighbors (distance 1)\n for (const edge of relations.edges) {\n if (edge.from === startId) {\n if (!distances.has(edge.to)) {\n distances.set(edge.to, 1);\n queue.push({ id: edge.to, distance: 1 });\n }\n }\n }\n\n while (queue.length > 0) {\n const item = queue.shift()!;\n const currentDist = item.distance;\n\n for (const edge of relations.edges) {\n if (edge.from === item.id && !distances.has(edge.to)) {\n distances.set(edge.to, currentDist + 1);\n queue.push({ id: edge.to, distance: currentDist + 1 });\n }\n }\n }\n\n return distances;\n}\n\nfunction daysBetween(dateStr: string): number {\n const then = new Date(dateStr).getTime();\n const now = Date.now();\n return Math.max(0, (now - then) / (1000 * 60 * 60 * 24));\n}\n\nfunction clamp(min: number, max: number, value: number): number {\n return Math.min(max, Math.max(min, value));\n}\n\nexport function analyzeImpact(\n changedSpecId: string,\n diff: SpecDiff,\n relations: RelationResolver,\n allSpecs: ParsedSpec[],\n thresholdDays = 14,\n): ImpactAnalysis {\n // 1. BFS to get downstream spec IDs with their distances\n const distanceMap = bfsDistances(changedSpecId, relations);\n\n if (distanceMap.size === 0) {\n return {\n changedSpec: changedSpecId,\n downstream: [],\n totalAffected: 0,\n };\n }\n\n // 2. Pre-compute diff section metrics (same for all downstream specs)\n const totalSections = Math.max(1, diff.sections.length);\n const structuralSectionsChanged = diff.sections.filter((s) =>\n STRUCTURAL_SECTIONS.has(s.heading),\n ).length;\n\n // 3. Build a lookup map for specs\n const specById = new Map<string, ParsedSpec>();\n for (const spec of allSpecs) {\n const id = spec.frontmatter.id as string | undefined;\n if (id) specById.set(id, spec);\n }\n\n // 4. Build downstream impacts\n const downstream: DownstreamImpact[] = [];\n\n for (const [specId, distance] of distanceMap) {\n const spec = specById.get(specId);\n\n // Determine lastUpdated: use `updated` field if present, fall back to `created`\n const lastUpdated =\n (spec?.frontmatter.updated as string | undefined) ??\n (spec?.frontmatter.created as string | undefined) ??\n null;\n\n const filePath = spec?.filePath ?? `specs/${specId}.md`;\n\n // 5. Staleness formula\n let staleness: number;\n if (lastUpdated) {\n const daysSinceUpdate = daysBetween(lastUpdated);\n staleness = clamp(\n 0,\n 1,\n (daysSinceUpdate / thresholdDays) * 0.5 +\n (structuralSectionsChanged / totalSections) * 0.3 +\n (1 / distance) * 0.2,\n );\n } else {\n // No date info — use structural + distance terms only\n staleness = clamp(\n 0,\n 1,\n (structuralSectionsChanged / totalSections) * 0.3 + (1 / distance) * 0.2,\n );\n }\n\n // 6. Generate reason string\n const parts: string[] = [];\n parts.push(`depends on ${changedSpecId} (distance ${distance})`);\n if (structuralSectionsChanged > 0) {\n parts.push(`${structuralSectionsChanged} structural section(s) changed`);\n }\n if (lastUpdated) {\n const days = Math.round(daysBetween(lastUpdated));\n parts.push(`last updated ${days} day(s) ago`);\n }\n const reason = parts.join(\"; \");\n\n downstream.push({\n specId,\n filePath,\n distance,\n lastUpdated,\n staleness,\n reason,\n });\n }\n\n // Sort by distance ascending, then by staleness descending for stable output\n downstream.sort((a, b) => a.distance - b.distance || b.staleness - a.staleness);\n\n return {\n changedSpec: changedSpecId,\n downstream,\n totalAffected: downstream.length,\n };\n}\n","import type { ParsedSpec } from \"@specdx/core\";\n\nexport interface BrokenReference {\n specId: string;\n field: string;\n type: \"broken-reference\";\n referencedId: string;\n}\n\nexport function checkCrossReferences(\n allSpecs: ParsedSpec[],\n removedIds: string[],\n): BrokenReference[] {\n // Build set of all valid spec IDs, then remove any that were deleted\n const validIds = new Set(allSpecs.map((s) => s.frontmatter.id));\n for (const id of removedIds) {\n validIds.delete(id);\n }\n\n const broken: BrokenReference[] = [];\n\n for (const spec of allSpecs) {\n const references = spec.frontmatter.references;\n if (!references || references.length === 0) {\n continue;\n }\n\n for (const ref of references) {\n if (!validIds.has(ref.id)) {\n broken.push({\n specId: spec.frontmatter.id,\n field: \"references\",\n type: \"broken-reference\",\n referencedId: ref.id,\n });\n }\n }\n }\n\n return broken;\n}\n","import { execSync } from \"node:child_process\";\nimport { readFileSync, realpathSync } from \"node:fs\";\nimport { dirname, relative, resolve, sep } from \"node:path\";\nimport picomatch from \"picomatch\";\nimport { loadConfig, parseSpecFromString, buildRelationResolver } from \"@specdx/core\";\nimport type { ParsedSpec } from \"@specdx/core\";\nimport { diffSpecs } from \"./diff-specs.js\";\nimport { analyzeImpact } from \"./impact.js\";\nimport { checkCrossReferences } from \"./cross-refs.js\";\nimport { DiffError } from \"./types.js\";\nimport type { DiffResult, DiffOptions, SpecDiff, ImpactAnalysis } from \"./types.js\";\n\n/**\n * Get the real (symlink-resolved) git repo root for the given directory.\n */\nfunction getRepoRoot(cwd: string): string {\n let root: string;\n try {\n root = execSync(\"git rev-parse --show-toplevel\", {\n cwd,\n encoding: \"utf-8\",\n stdio: \"pipe\",\n }).trim();\n } catch {\n // Without this the raw git invocation and its \"fatal:\" output reach the\n // user, which reads as a crash rather than a precondition they can meet.\n throw new DiffError(\n \"diff compares specs across git history, and this directory is not inside a git repository. \" +\n \"Run `git init` first, or run diff from a checked-out project.\",\n );\n }\n return realpathSync(root);\n}\n\n/**\n * Validate that a git ref exists in the repository.\n */\nfunction validateRef(ref: string, cwd: string): void {\n try {\n execSync(`git rev-parse --verify ${ref}`, { cwd, encoding: \"utf-8\", stdio: \"pipe\" });\n } catch {\n throw new DiffError(`Invalid git ref: \"${ref}\"`);\n }\n}\n\n/**\n * Get file content at a specific git ref.\n * filePath should be relative to projectRoot.\n */\nfunction gitShow(ref: string, filePath: string, projectRoot: string, repoRoot: string): string {\n const relPath = relative(repoRoot, resolve(projectRoot, filePath));\n try {\n return execSync(`git show ${ref}:${relPath}`, {\n cwd: repoRoot,\n encoding: \"utf-8\",\n stdio: \"pipe\",\n });\n } catch {\n throw new DiffError(`Cannot read \"${filePath}\" at ref \"${ref}\"`);\n }\n}\n\n/** Git reports paths with forward slashes regardless of platform. */\nfunction toPosix(p: string): string {\n return sep === \"/\" ? p : p.split(sep).join(\"/\");\n}\n\ninterface EntryMatcher {\n /** Config entry key (may cover many spec files when the path is a glob). */\n key: string;\n /** Matches repo-relative, posix-separated paths against the entry's path. */\n isMatch: (repoRelPath: string) => boolean;\n}\n\n/**\n * Build one matcher per config entry.\n *\n * A config entry's `path` may be a glob (`specs/stories/*.md`), so it cannot be\n * compared to git's output by string equality -- the literal pattern is never\n * itself a changed path. Matching by pattern is what makes globbed specs\n * visible to diff at all.\n */\nfunction buildEntryMatchers(\n specPathsByKey: Map<string, string>,\n projectRoot: string,\n repoRoot: string,\n): EntryMatcher[] {\n return [...specPathsByKey].map(([key, specPath]) => ({\n key,\n isMatch: picomatch(toPosix(relative(repoRoot, resolve(projectRoot, specPath)))),\n }));\n}\n\n/** A spec file that changed between two refs, with the entry it belongs to. */\ninterface ChangedSpecFile {\n /** Project-relative path, as the rest of the pipeline expects. */\n path: string;\n entryKey: string;\n}\n\ninterface ChangedFiles {\n modified: ChangedSpecFile[];\n added: ChangedSpecFile[];\n deleted: ChangedSpecFile[];\n}\n\n/**\n * Get list of changed files between two refs, filtered to files that belong to\n * a configured spec entry.\n */\nfunction getChangedSpecFiles(\n baseRef: string,\n headRef: string,\n matchers: EntryMatcher[],\n projectRoot: string,\n repoRoot: string,\n): ChangedFiles {\n let diffOutput: string;\n try {\n diffOutput = execSync(`git diff --name-status ${baseRef} ${headRef}`, {\n cwd: repoRoot,\n encoding: \"utf-8\",\n stdio: \"pipe\",\n });\n } catch {\n throw new DiffError(`Failed to run git diff between \"${baseRef}\" and \"${headRef}\"`);\n }\n\n const result: ChangedFiles = { modified: [], added: [], deleted: [] };\n\n for (const line of diffOutput.trim().split(\"\\n\")) {\n if (!line) continue;\n const parts = line.split(\"\\t\");\n const status = parts[0];\n const filePath = parts[1];\n if (!status || !filePath) continue;\n\n const entry = matchers.find((m) => m.isMatch(filePath));\n if (!entry) continue;\n\n const changed: ChangedSpecFile = {\n path: relative(projectRoot, resolve(repoRoot, filePath)),\n entryKey: entry.key,\n };\n\n if (status === \"M\") {\n result.modified.push(changed);\n } else if (status === \"A\") {\n result.added.push(changed);\n } else if (status === \"D\") {\n result.deleted.push(changed);\n }\n }\n\n return result;\n}\n\n/**\n * List every spec file present at a ref, grouped by config entry key.\n *\n * Expanding globs against the ref rather than the working tree keeps impact\n * analysis accurate for specs that were added or deleted in the range.\n */\nfunction listSpecFilesAtRef(\n ref: string,\n matchers: EntryMatcher[],\n projectRoot: string,\n repoRoot: string,\n): Map<string, string[]> {\n const byEntry = new Map<string, string[]>(matchers.map((m) => [m.key, []]));\n\n let listing: string;\n try {\n listing = execSync(`git ls-tree -r --name-only ${ref}`, {\n cwd: repoRoot,\n encoding: \"utf-8\",\n stdio: \"pipe\",\n });\n } catch {\n throw new DiffError(`Failed to list files at ref \"${ref}\"`);\n }\n\n for (const filePath of listing.trim().split(\"\\n\")) {\n if (!filePath) continue;\n const entry = matchers.find((m) => m.isMatch(filePath));\n if (!entry) continue;\n byEntry.get(entry.key)?.push(relative(projectRoot, resolve(repoRoot, filePath)));\n }\n\n return byEntry;\n}\n\n/**\n * List every spec file in the working tree, grouped by config entry key.\n *\n * Uses git rather than a filesystem glob so ignored files are excluded the same\n * way they are on the ref side -- a file git cannot see is not a spec that can\n * be committed.\n */\nfunction listSpecFilesInWorktree(\n matchers: EntryMatcher[],\n projectRoot: string,\n repoRoot: string,\n): Map<string, string[]> {\n const byEntry = new Map<string, string[]>(matchers.map((m) => [m.key, []]));\n\n let listing: string;\n try {\n listing = execSync(\"git ls-files --cached --others --exclude-standard\", {\n cwd: repoRoot,\n encoding: \"utf-8\",\n stdio: \"pipe\",\n });\n } catch {\n throw new DiffError(\"Failed to list files in the working tree\");\n }\n\n for (const filePath of listing.trim().split(\"\\n\")) {\n if (!filePath) continue;\n const entry = matchers.find((m) => m.isMatch(filePath));\n if (!entry) continue;\n byEntry.get(entry.key)?.push(relative(projectRoot, resolve(repoRoot, filePath)));\n }\n\n return byEntry;\n}\n\n/** One side of a comparison: either a git ref or the working tree. */\ninterface ComparisonSide {\n /** Read a spec file's content on this side. Throws if absent. */\n read: (path: string) => string;\n /** Spec files present on this side, grouped by config entry key. */\n list: () => Map<string, string[]>;\n}\n\nfunction refSide(\n ref: string,\n matchers: EntryMatcher[],\n projectRoot: string,\n repoRoot: string,\n): ComparisonSide {\n return {\n read: (path) => gitShow(ref, path, projectRoot, repoRoot),\n list: () => listSpecFilesAtRef(ref, matchers, projectRoot, repoRoot),\n };\n}\n\nfunction worktreeSide(\n matchers: EntryMatcher[],\n projectRoot: string,\n repoRoot: string,\n): ComparisonSide {\n return {\n read: (path) => {\n try {\n return readFileSync(resolve(projectRoot, path), \"utf-8\");\n } catch {\n throw new DiffError(`Cannot read \"${path}\" in the working tree`);\n }\n },\n list: () => listSpecFilesInWorktree(matchers, projectRoot, repoRoot),\n };\n}\n\n/**\n * Get spec files that differ between a ref and the working tree.\n *\n * `git diff --name-status <ref>` covers tracked files, staged or not, but says\n * nothing about untracked ones -- and a brand new spec is untracked until the\n * commit this comparison exists to inform. Untracked spec files are therefore\n * folded in as additions.\n */\nfunction getChangedSpecFilesInWorktree(\n baseRef: string,\n matchers: EntryMatcher[],\n projectRoot: string,\n repoRoot: string,\n): ChangedFiles {\n let diffOutput: string;\n try {\n diffOutput = execSync(`git diff --name-status ${baseRef}`, {\n cwd: repoRoot,\n encoding: \"utf-8\",\n stdio: \"pipe\",\n });\n } catch {\n throw new DiffError(`Failed to diff \"${baseRef}\" against the working tree`);\n }\n\n const result: ChangedFiles = { modified: [], added: [], deleted: [] };\n const seen = new Set<string>();\n\n const record = (status: string, filePath: string): void => {\n const entry = matchers.find((m) => m.isMatch(filePath));\n if (!entry) return;\n if (seen.has(filePath)) return;\n seen.add(filePath);\n\n const changed: ChangedSpecFile = {\n path: relative(projectRoot, resolve(repoRoot, filePath)),\n entryKey: entry.key,\n };\n if (status === \"M\") result.modified.push(changed);\n else if (status === \"A\") result.added.push(changed);\n else if (status === \"D\") result.deleted.push(changed);\n };\n\n for (const line of diffOutput.trim().split(\"\\n\")) {\n if (!line) continue;\n const parts = line.split(\"\\t\");\n const status = parts[0];\n const filePath = parts[1];\n if (!status || !filePath) continue;\n record(status, filePath);\n }\n\n let untracked: string;\n try {\n untracked = execSync(\"git ls-files --others --exclude-standard\", {\n cwd: repoRoot,\n encoding: \"utf-8\",\n stdio: \"pipe\",\n });\n } catch {\n throw new DiffError(\"Failed to list untracked files\");\n }\n\n for (const filePath of untracked.trim().split(\"\\n\")) {\n if (!filePath) continue;\n record(\"A\", filePath);\n }\n\n return result;\n}\n\n/**\n * Spec files with uncommitted changes in the working tree.\n *\n * Reported alongside a ref-to-ref comparison so \"no spec changes\" is never\n * mistaken for \"nothing is about to change\".\n */\nfunction listUncommittedSpecFiles(\n matchers: EntryMatcher[],\n projectRoot: string,\n repoRoot: string,\n): string[] {\n let statusOutput: string;\n try {\n statusOutput = execSync(\"git status --porcelain\", {\n cwd: repoRoot,\n encoding: \"utf-8\",\n stdio: \"pipe\",\n });\n } catch {\n // Status is advisory -- never fail the diff over it.\n return [];\n }\n\n const files: string[] = [];\n for (const line of statusOutput.split(\"\\n\")) {\n if (!line.trim()) continue;\n // Porcelain v1: two status columns, a space, then the path. A rename reads\n // \"old -> new\"; the new path is the one that exists now. Paths containing\n // unusual characters are quoted.\n const rawPath = line.slice(3);\n const renamed = rawPath.includes(\" -> \") ? rawPath.split(\" -> \")[1] : undefined;\n const filePath = (renamed ?? rawPath).replace(/^\"|\"$/g, \"\");\n if (!matchers.some((m) => m.isMatch(filePath))) continue;\n files.push(relative(projectRoot, resolve(repoRoot, filePath)));\n }\n\n return files;\n}\n\n/**\n * Resolve the spec ids of files that only exist on one side of the range.\n *\n * The config entry key is not usable as a spec id: one glob entry covers many\n * specs, so the id has to come from each file's own frontmatter.\n */\nasync function specIdsFrom(\n files: ChangedSpecFile[],\n read: (path: string) => string,\n): Promise<string[]> {\n const ids: string[] = [];\n for (const file of files) {\n try {\n const parsed = await parseSpecFromString(read(file.path), file.path);\n ids.push(parsed.frontmatter.id);\n } catch {\n // Unparseable or unreadable on that side -- fall back to the entry key so\n // the spec is still reported as added/removed rather than dropped.\n ids.push(file.entryKey);\n }\n }\n return ids;\n}\n\n/**\n * Compare specs between two git refs, producing a full DiffResult with\n * structural diffs, impact analysis, and cross-reference checks.\n */\nexport async function diffBetweenRefs(\n configPath: string,\n baseRef: string,\n headRef: string,\n options: DiffOptions = {},\n): Promise<DiffResult> {\n const projectRoot = realpathSync(dirname(resolve(configPath)));\n const repoRoot = getRepoRoot(projectRoot);\n\n // Validate refs. In working mode the head side is the working tree, which is\n // not a ref and has nothing to validate.\n validateRef(baseRef, projectRoot);\n if (!options.working) validateRef(headRef, projectRoot);\n\n // Load config from filesystem (current version)\n const config = await loadConfig(configPath);\n\n // Collect all spec paths from config, keyed by entry. A path may be a glob,\n // so entries are matched by pattern rather than by string equality.\n const specPathsByKey = new Map<string, string>();\n for (const [key, entry] of Object.entries(config.specs)) {\n specPathsByKey.set(key, entry.path);\n }\n const matchers = buildEntryMatchers(specPathsByKey, projectRoot, repoRoot);\n\n const base = refSide(baseRef, matchers, projectRoot, repoRoot);\n const head = options.working\n ? worktreeSide(matchers, projectRoot, repoRoot)\n : refSide(headRef, matchers, projectRoot, repoRoot);\n\n // Determine which spec files changed\n const changed = options.working\n ? getChangedSpecFilesInWorktree(baseRef, matchers, projectRoot, repoRoot)\n : getChangedSpecFiles(baseRef, headRef, matchers, projectRoot, repoRoot);\n\n // Build diffs for modified specs\n const diffs: SpecDiff[] = [];\n\n for (const file of changed.modified) {\n const beforeSpec = await parseSpecFromString(base.read(file.path), file.path);\n const afterSpec = await parseSpecFromString(head.read(file.path), file.path);\n\n const diff = diffSpecs(beforeSpec, afterSpec);\n diffs.push(diff);\n }\n\n // Added and removed spec IDs, read from the frontmatter on the side of the\n // range where the file exists.\n const added = await specIdsFrom(changed.added, head.read);\n const removed = await specIdsFrom(changed.deleted, base.read);\n\n const impact: ImpactAnalysis[] = [];\n\n // Parse all specs present on the head side for impact analysis, keeping the\n // config entry each came from so requires edges can be mapped to spec ids.\n const allSpecs: ParsedSpec[] = [];\n const specsByEntry = new Map<string, ParsedSpec[]>();\n const filesAtHead = head.list();\n for (const [key, paths] of filesAtHead) {\n const forEntry: ParsedSpec[] = [];\n for (const path of paths) {\n try {\n const parsed = await parseSpecFromString(head.read(path), path);\n forEntry.push(parsed);\n allSpecs.push(parsed);\n } catch {\n // Unparseable on this side -- skip\n }\n }\n specsByEntry.set(key, forEntry);\n }\n\n // Impact works in spec id space: config requires and frontmatter references\n // unioned, so downstream is found whether entry keys match spec ids or not\n // (ADR: references/requires unification).\n const relations = buildRelationResolver(config, specsByEntry);\n\n const thresholdDays = config.diff?.staleness_threshold_days ?? 14;\n\n for (const diff of diffs) {\n const analysis = analyzeImpact(diff.specId, diff, relations, allSpecs, thresholdDays);\n if (analysis.totalAffected > 0) {\n impact.push(analysis);\n }\n }\n\n // Check cross-references for removed specs\n const _brokenRefs = checkCrossReferences(allSpecs, removed);\n\n // Generate summary\n const summaryParts: string[] = [];\n if (diffs.length > 0) {\n summaryParts.push(`${diffs.length} spec(s) modified`);\n }\n if (added.length > 0) {\n summaryParts.push(`${added.length} spec(s) added`);\n }\n if (removed.length > 0) {\n summaryParts.push(`${removed.length} spec(s) removed`);\n }\n if (impact.length > 0) {\n const totalDownstream = impact.reduce((sum, i) => sum + i.totalAffected, 0);\n summaryParts.push(`${totalDownstream} downstream spec(s) potentially affected`);\n }\n if (_brokenRefs.length > 0) {\n summaryParts.push(`${_brokenRefs.length} broken reference(s)`);\n }\n const summary = summaryParts.length > 0 ? summaryParts.join(\"; \") : \"No changes detected\";\n\n // Working mode already covers the working tree, so nothing there is missed.\n const uncommittedSpecFiles = options.working\n ? []\n : listUncommittedSpecFiles(matchers, projectRoot, repoRoot);\n\n return { diffs, added, removed, impact, summary, uncommittedSpecFiles };\n}\n","import type { DiffResult } from \"@specdx/diff\";\n\n/**\n * Render a diff as a markdown changelog.\n *\n * Formerly the `specdx changelog` command, which ran the same comparison as\n * `diff` and differed only in presentation. It is a format, not a second\n * question, so it lives as `diff --format changelog`.\n */\nexport function formatChangelog(result: DiffResult, baseRef: string, headRef: string): string {\n const lines: string[] = [];\n lines.push(`## Spec Changes (${baseRef}..${headRef})\\n`);\n\n if (result.diffs.length > 0) {\n lines.push(\"### Modified\");\n for (const diff of result.diffs) {\n const sections = diff.sections.map((s) => s.heading).join(\", \");\n const versionChange = diff.frontmatter.find((f) => f.field === \"version\");\n const versionStr = versionChange\n ? ` (${String(versionChange.before)} → ${String(versionChange.after)})`\n : \"\";\n lines.push(`- **${diff.specId}**${versionStr} — ${sections || \"frontmatter only\"}`);\n }\n lines.push(\"\");\n }\n\n if (result.added.length > 0) {\n lines.push(\"### Added\");\n for (const id of result.added) {\n lines.push(`- **${id}**`);\n }\n lines.push(\"\");\n }\n\n if (result.removed.length > 0) {\n lines.push(\"### Removed\");\n for (const id of result.removed) {\n lines.push(`- **${id}**`);\n }\n lines.push(\"\");\n }\n\n const allDownstream = result.impact.flatMap((i) => i.downstream);\n if (allDownstream.length > 0) {\n lines.push(\"### Downstream Impact\");\n for (const d of allDownstream) {\n lines.push(`- ${d.specId} may be stale (${d.reason})`);\n }\n lines.push(\"\");\n }\n\n if (result.diffs.length === 0 && result.added.length === 0 && result.removed.length === 0) {\n lines.push(\"No spec changes detected.\\n\");\n }\n\n // The uncommitted warning matters most here: a changelog is usually written\n // at release time, when unstaged spec edits are easy to miss.\n if (result.uncommittedSpecFiles.length > 0) {\n lines.push(\n `> ⚠ ${result.uncommittedSpecFiles.length} spec file(s) changed in the working tree are not covered by this range.\\n`,\n );\n }\n\n return lines.join(\"\\n\");\n}\n","import { defineCommand } from \"citty\";\nimport { loadConfig, parseSpec, buildGraph, resolveGlob } from \"@specdx/core\";\nimport { createLintEngine, getPreset } from \"@specdx/lint\";\nimport { DEFAULT_DIFF_CONFIG } from \"@specdx/diff\";\nimport type { StatusResult } from \"@specdx/diff\";\nimport type { ParsedSpec } from \"@specdx/core\";\nimport { sharedArgs, resolveFormat } from \"../../shared-args.js\";\nimport { createOutput } from \"../../output.js\";\n\nconst FORMATS = [\"pretty\", \"json\", \"github\"] as const;\n\nexport interface RunStatusOptions {\n /**\n * Directory holding spec.config.yaml. Defaults to the process cwd, which is\n * right for the CLI and useless to a library consumer — `runLint` and\n * `runPack` take one, so this does too (audit run 5, F8).\n */\n configDir?: string;\n}\n\nexport async function runStatus(options: RunStatusOptions = {}): Promise<StatusResult> {\n const configDir = options.configDir ?? process.cwd();\n const config = await loadConfig(undefined, configDir);\n\n // Resolve and parse all specs\n const specs: { spec: ParsedSpec; entry: { path: string; owner?: string } }[] = [];\n for (const [, entry] of Object.entries(config.specs)) {\n const paths = await resolveGlob(entry.path, configDir);\n for (const p of paths) {\n const spec = await parseSpec(p);\n specs.push({ spec, entry: entry as { path: string; owner?: string } });\n }\n }\n\n // Count by status\n const byStatus: Record<string, number> = {};\n for (const { spec } of specs) {\n const status = (spec.frontmatter.status as string) || \"unknown\";\n byStatus[status] = (byStatus[status] ?? 0) + 1;\n }\n\n // Lint health\n const presetName = config.lint?.extends ?? \"recommended\";\n const rules = getPreset(presetName);\n\n let graph;\n let graphError: string | undefined;\n try {\n graph = buildGraph(config);\n } catch (err) {\n graphError = (err as Error).message;\n }\n\n const engine = createLintEngine({ rules, config, graph });\n const lintResults = engine.lint(specs.map((s) => s.spec));\n\n if (graphError) {\n lintResults.diagnostics.push({\n ruleId: \"structure/no-circular-deps\",\n severity: \"error\",\n message: graphError,\n filePath: \"spec.config.yaml\",\n });\n lintResults.hasErrors = true;\n }\n\n const errors = lintResults.diagnostics.filter((d) => d.severity === \"error\").length;\n const warnings = lintResults.diagnostics.filter((d) => d.severity === \"warn\").length;\n\n // Staleness\n const thresholdDays =\n config.diff?.staleness_threshold_days ?? DEFAULT_DIFF_CONFIG.staleness_threshold_days;\n const now = Date.now();\n const staleSpecs: { specId: string; daysSinceUpdate: number; owner?: string }[] = [];\n for (const { spec, entry } of specs) {\n const dateStr =\n (spec.frontmatter.updated as string | undefined) ||\n (spec.frontmatter.created as string | undefined);\n if (dateStr) {\n const daysSinceUpdate = Math.floor(\n (now - new Date(dateStr).getTime()) / (1000 * 60 * 60 * 24),\n );\n if (daysSinceUpdate > thresholdDays) {\n staleSpecs.push({\n specId: spec.frontmatter.id as string,\n daysSinceUpdate,\n owner: entry.owner,\n });\n }\n }\n }\n\n // Integrity issues\n const integrityIssues: string[] = [];\n if (graphError) {\n integrityIssues.push(graphError);\n }\n const refErrors = lintResults.diagnostics.filter(\n (d) => d.ruleId === \"structure/valid-references\",\n );\n for (const d of refErrors) {\n integrityIssues.push(d.message);\n }\n\n // Verdict — an empty suite is unassessed, never a vacuous \"healthy\"\n let verdict: StatusResult[\"verdict\"] = \"healthy\";\n if (errors > 0) verdict = \"errors\";\n else if (warnings > 0 || staleSpecs.length > 0) verdict = \"warnings\";\n else if (specs.length === 0) verdict = \"unassessed\";\n\n return {\n project: config.project?.name ?? \"unknown\",\n specFiles: specs.length,\n byStatus,\n lintHealth: { errors, warnings, passing: specs.length - errors },\n staleSpecs,\n integrityIssues,\n verdict,\n };\n}\n\nexport default defineCommand({\n meta: { name: \"status\", description: \"Show spec suite health overview\" },\n args: { ...sharedArgs(FORMATS) },\n async run({ args }) {\n const format = resolveFormat(args.format, FORMATS);\n if (!format.ok) {\n console.error(`\\n ✗ ${format.message}\\n`);\n process.exit(1);\n }\n const output = createOutput({ quiet: args.quiet });\n\n try {\n const result = await runStatus();\n\n if (format.format === \"json\") {\n console.log(JSON.stringify(result, null, 2));\n return;\n }\n\n if (format.format === \"github\") {\n for (const s of result.staleSpecs) {\n console.log(\n `::warning::Spec \"${s.specId}\" is stale (${s.daysSinceUpdate} days since update)`,\n );\n }\n for (const issue of result.integrityIssues) {\n console.log(`::error::${issue}`);\n }\n return;\n }\n\n // Pretty format\n const icon =\n result.verdict === \"healthy\"\n ? \"✓\"\n : result.verdict === \"warnings\" || result.verdict === \"unassessed\"\n ? \"⚠\"\n : \"✗\";\n const healthy = result.verdict === \"healthy\";\n const headline = `\\n ${icon} ${result.project} — ${result.verdict}`;\n if (healthy) output.info(headline);\n else output.out(headline);\n\n if (result.verdict === \"unassessed\") {\n output.out(\n \" No specs resolved — nothing was assessed. Check the spec paths in spec.config.yaml.\",\n );\n }\n output.info(\n ` ${result.specFiles} specs: ${Object.entries(result.byStatus)\n .map(([k, v]) => `${v} ${k}`)\n .join(\", \")}`,\n );\n output.info(\n ` Lint: ${result.lintHealth.errors} errors, ${result.lintHealth.warnings} warnings`,\n );\n\n if (result.staleSpecs.length > 0) {\n output.out(\n ` Stale: ${result.staleSpecs.map((s) => `${s.specId} (${s.daysSinceUpdate}d)`).join(\", \")}`,\n );\n }\n if (result.integrityIssues.length > 0) {\n output.out(` Issues: ${result.integrityIssues.join(\"; \")}`);\n }\n output.info();\n } catch (err) {\n console.error(`\\n ✗ ${(err as Error).message}\\n`);\n process.exit(1);\n }\n },\n});\n","import { defineCommand } from \"citty\";\nimport { loadConfig, buildGraph, resolveGlob, ConfigError, GraphError } from \"@specdx/core\";\nimport { sharedArgs, resolveFormat } from \"../../shared-args.js\";\nimport { createOutput } from \"../../output.js\";\n\nconst FORMATS = [\"pretty\", \"json\"] as const;\n\nexport interface ValidateResult {\n valid: boolean;\n /** Number of spec entries declared in the config. */\n specEntries?: number;\n /** Number of spec files those entries actually resolve to. */\n specFiles?: number;\n /** Non-fatal honesty notes: entries resolving to nothing, empty suite. */\n warnings: string[];\n error?: string;\n details?: unknown[];\n}\n\n/**\n * Validate spec.config.yaml: a schema-valid config, a buildable dependency\n * graph (issue #13), and declared spec paths that actually resolve. An entry\n * that matches no files makes every downstream verdict vacuous, so it is\n * reported here rather than silently flowing into lint/status/ready.\n */\nexport async function runValidate(configDir: string): Promise<ValidateResult> {\n const warnings: string[] = [];\n try {\n const config = await loadConfig(undefined, configDir);\n buildGraph(config);\n\n let specFiles = 0;\n const missingRequired: string[] = [];\n for (const [key, entry] of Object.entries(config.specs)) {\n const files = await resolveGlob(entry.path, configDir);\n specFiles += files.length;\n if (files.length > 0) continue;\n\n if ((entry as { required?: boolean }).required) {\n missingRequired.push(`\"${key}\" (${entry.path})`);\n } else {\n warnings.push(`spec entry \"${key}\" resolves to no files: ${entry.path}`);\n }\n }\n\n if (missingRequired.length > 0) {\n return {\n valid: false,\n specEntries: Object.keys(config.specs).length,\n specFiles,\n warnings,\n error: `required spec entry resolves to no files: ${missingRequired.join(\", \")}`,\n };\n }\n\n if (specFiles === 0) {\n warnings.push(\n \"no spec files found — every downstream check (lint, status, ready) would pass vacuously\",\n );\n }\n\n return {\n valid: true,\n specEntries: Object.keys(config.specs).length,\n specFiles,\n warnings,\n };\n } catch (err) {\n if (err instanceof ConfigError) {\n return { valid: false, warnings, error: err.message, details: err.errors ?? undefined };\n }\n if (err instanceof GraphError) {\n return { valid: false, warnings, error: err.message };\n }\n throw err;\n }\n}\n\nexport default defineCommand({\n meta: { name: \"validate\", description: \"Validate spec.config.yaml\" },\n args: { ...sharedArgs(FORMATS) },\n async run({ args }) {\n const format = resolveFormat(args.format, FORMATS);\n if (!format.ok) {\n console.error(`\\n ✗ ${format.message}\\n`);\n process.exit(1);\n }\n const output = createOutput({ quiet: args.quiet });\n\n const result = await runValidate(process.cwd());\n\n if (format.format === \"json\") {\n console.log(JSON.stringify(result, null, 2));\n if (!result.valid) process.exit(1);\n return;\n }\n\n if (result.valid) {\n output.info(\n ` ✓ Config valid. ${result.specEntries} spec entries, ${result.specFiles} spec files.`,\n );\n for (const w of result.warnings) output.out(` ⚠ ${w}`);\n return;\n }\n\n console.error(` ✗ Config invalid: ${result.error}`);\n for (const w of result.warnings) console.error(` ⚠ ${w}`);\n if (result.details) {\n for (const e of result.details) console.error(` - ${JSON.stringify(e)}`);\n }\n process.exit(1);\n },\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAEA,QAAM,YAAY;AAClB,QAAM,eAAe,KAAK,SAAS;AAMnC,QAAM,cAAc;AACpB,QAAM,eAAe;AACrB,QAAM,gBAAgB;AACtB,QAAM,gBAAgB;AACtB,QAAM,WAAW;AACjB,QAAM,QAAQ;AACd,QAAM,aAAa,MAAM,aAAa;AACtC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zD,QAAI,OAAO,SAAS;AAClB,iBAAW,KAAK,OAAO,QAAS,SAAQ,MAAM,SAAS,KAAK,UAAU,CAAC,CAAC,EAAE;AAAA,IAC5E;AACA,YAAQ,KAAK,CAAC;AAAA,EAChB;AACF,CAAC;","names":["glob","opts","value","rest","source","picomatch","glob","state","require_picomatch","picomatch","glob","defineCommand","join","join","readFile","parseYaml","readFile","parseYaml","join","readFile","resolve","isAbsolute","STOPWORDS","PLACEHOLDER_BODIES","meaningfulContent","basename","defineCommand","defineCommand","STOPWORDS","results","formatJson","formatJson","writeFile","defineCommand","defineCommand","join","tokenize","join","diff","value","overlap","r","o","diff","_loop","patchObj","diff","lastUpdated","execSync","dirname","resolve","execSync","resolve","picomatch","dirname","diff","diff","FORMATS","join","defineCommand","diff","defineCommand","FORMATS","defineCommand","defineCommand","FORMATS","defineCommand"]}
1
+ {"version":3,"sources":["../../../node_modules/.pnpm/picomatch@4.0.3/node_modules/picomatch/lib/constants.js","../../../node_modules/.pnpm/picomatch@4.0.3/node_modules/picomatch/lib/utils.js","../../../node_modules/.pnpm/picomatch@4.0.3/node_modules/picomatch/lib/scan.js","../../../node_modules/.pnpm/picomatch@4.0.3/node_modules/picomatch/lib/parse.js","../../../node_modules/.pnpm/picomatch@4.0.3/node_modules/picomatch/lib/picomatch.js","../../../node_modules/.pnpm/picomatch@4.0.3/node_modules/picomatch/index.js","../src/commands/core/init.ts","../../schema/src/types.ts","../../schema/src/sections.ts","../../schema/src/validator.ts","../../schema/dist/schemas/base-spec.json","../../schema/dist/schemas/config.json","../../schema/dist/schemas/prd.json","../../schema/dist/schemas/technical-design.json","../../schema/dist/schemas/user-story.json","../../schema/dist/schemas/test-plan.json","../../schema/dist/schemas/adr.json","../../schema/dist/schemas/api-contract.json","../../schema/dist/schemas/epic.json","../../schema/dist/schemas/quick-spec.json","../../schema/dist/schemas/project-context.json","../src/commands/core/lint.ts","../../core/src/config.ts","../../core/src/parser.ts","../../core/src/tokens.ts","../../core/src/graph.ts","../../core/src/relations.ts","../../core/src/glob.ts","../../core/src/logger.ts","../../core/src/preset.ts","../../lint/src/engine.ts","../../lint/src/rules/valid-frontmatter.ts","../../lint/src/rules/required-sections.ts","../../lint/src/rules/valid-references.ts","../../lint/src/rules/no-circular-deps.ts","../../lint/src/rules/story-coverage.ts","../../lint/src/rules/staleness-check.ts","../../lint/src/rules/no-vague-language.ts","../../lint/src/rules/single-project-context.ts","../../lint/src/rules/terminology.ts","../../lint/src/rules/edge-case-coverage.ts","../../lint/src/rules/naming-conventions.ts","../../lint/src/rules/threat-coverage.ts","../../lint/src/rules/ambiguity-score-ai.ts","../../lint/src/rules/no-placeholder-sections.ts","../../lint/src/rules/id-matches-config-key.ts","../../lint/src/rules/index.ts","../../lint/src/presets.ts","../../lint/src/custom-rule-loader.ts","../src/shared-args.ts","../src/output.ts","../src/formatters/pretty.ts","../src/formatters/json.ts","../src/formatters/github.ts","../src/commands/core/pack.ts","../../pack/src/resolver.ts","../../pack/src/compressor.ts","../../pack/src/allocator.ts","../../pack/src/formatters/xml.ts","../../pack/src/formatters/markdown.ts","../../pack/src/formatters/json.ts","../../pack/src/index.ts","../src/commands/core/diff.ts","../../diff/src/types.ts","../../../node_modules/.pnpm/diff@7.0.0/node_modules/diff/lib/index.mjs","../../diff/src/diff-specs.ts","../../diff/src/impact.ts","../../diff/src/cross-refs.ts","../../diff/src/git.ts","../src/formatters/changelog.ts","../src/commands/core/status.ts","../src/commands/core/validate.ts"],"sourcesContent":["'use strict';\n\nconst WIN_SLASH = '\\\\\\\\/';\nconst WIN_NO_SLASH = `[^${WIN_SLASH}]`;\n\n/**\n * Posix glob regex\n */\n\nconst DOT_LITERAL = '\\\\.';\nconst PLUS_LITERAL = '\\\\+';\nconst QMARK_LITERAL = '\\\\?';\nconst SLASH_LITERAL = '\\\\/';\nconst ONE_CHAR = '(?=.)';\nconst QMARK = '[^/]';\nconst END_ANCHOR = `(?:${SLASH_LITERAL}|$)`;\nconst START_ANCHOR = `(?:^|${SLASH_LITERAL})`;\nconst DOTS_SLASH = `${DOT_LITERAL}{1,2}${END_ANCHOR}`;\nconst NO_DOT = `(?!${DOT_LITERAL})`;\nconst NO_DOTS = `(?!${START_ANCHOR}${DOTS_SLASH})`;\nconst NO_DOT_SLASH = `(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`;\nconst NO_DOTS_SLASH = `(?!${DOTS_SLASH})`;\nconst QMARK_NO_DOT = `[^.${SLASH_LITERAL}]`;\nconst STAR = `${QMARK}*?`;\nconst SEP = '/';\n\nconst POSIX_CHARS = {\n DOT_LITERAL,\n PLUS_LITERAL,\n QMARK_LITERAL,\n SLASH_LITERAL,\n ONE_CHAR,\n QMARK,\n END_ANCHOR,\n DOTS_SLASH,\n NO_DOT,\n NO_DOTS,\n NO_DOT_SLASH,\n NO_DOTS_SLASH,\n QMARK_NO_DOT,\n STAR,\n START_ANCHOR,\n SEP\n};\n\n/**\n * Windows glob regex\n */\n\nconst WINDOWS_CHARS = {\n ...POSIX_CHARS,\n\n SLASH_LITERAL: `[${WIN_SLASH}]`,\n QMARK: WIN_NO_SLASH,\n STAR: `${WIN_NO_SLASH}*?`,\n DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`,\n NO_DOT: `(?!${DOT_LITERAL})`,\n NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,\n NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`,\n NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,\n QMARK_NO_DOT: `[^.${WIN_SLASH}]`,\n START_ANCHOR: `(?:^|[${WIN_SLASH}])`,\n END_ANCHOR: `(?:[${WIN_SLASH}]|$)`,\n SEP: '\\\\'\n};\n\n/**\n * POSIX Bracket Regex\n */\n\nconst POSIX_REGEX_SOURCE = {\n alnum: 'a-zA-Z0-9',\n alpha: 'a-zA-Z',\n ascii: '\\\\x00-\\\\x7F',\n blank: ' \\\\t',\n cntrl: '\\\\x00-\\\\x1F\\\\x7F',\n digit: '0-9',\n graph: '\\\\x21-\\\\x7E',\n lower: 'a-z',\n print: '\\\\x20-\\\\x7E ',\n punct: '\\\\-!\"#$%&\\'()\\\\*+,./:;<=>?@[\\\\]^_`{|}~',\n space: ' \\\\t\\\\r\\\\n\\\\v\\\\f',\n upper: 'A-Z',\n word: 'A-Za-z0-9_',\n xdigit: 'A-Fa-f0-9'\n};\n\nmodule.exports = {\n MAX_LENGTH: 1024 * 64,\n POSIX_REGEX_SOURCE,\n\n // regular expressions\n REGEX_BACKSLASH: /\\\\(?![*+?^${}(|)[\\]])/g,\n REGEX_NON_SPECIAL_CHARS: /^[^@![\\].,$*+?^{}()|\\\\/]+/,\n REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\\]]/,\n REGEX_SPECIAL_CHARS_BACKREF: /(\\\\?)((\\W)(\\3*))/g,\n REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\\]])/g,\n REGEX_REMOVE_BACKSLASH: /(?:\\[.*?[^\\\\]\\]|\\\\(?=.))/g,\n\n // Replace globs with equivalent patterns to reduce parsing time.\n REPLACEMENTS: {\n __proto__: null,\n '***': '*',\n '**/**': '**',\n '**/**/**': '**'\n },\n\n // Digits\n CHAR_0: 48, /* 0 */\n CHAR_9: 57, /* 9 */\n\n // Alphabet chars.\n CHAR_UPPERCASE_A: 65, /* A */\n CHAR_LOWERCASE_A: 97, /* a */\n CHAR_UPPERCASE_Z: 90, /* Z */\n CHAR_LOWERCASE_Z: 122, /* z */\n\n CHAR_LEFT_PARENTHESES: 40, /* ( */\n CHAR_RIGHT_PARENTHESES: 41, /* ) */\n\n CHAR_ASTERISK: 42, /* * */\n\n // Non-alphabetic chars.\n CHAR_AMPERSAND: 38, /* & */\n CHAR_AT: 64, /* @ */\n CHAR_BACKWARD_SLASH: 92, /* \\ */\n CHAR_CARRIAGE_RETURN: 13, /* \\r */\n CHAR_CIRCUMFLEX_ACCENT: 94, /* ^ */\n CHAR_COLON: 58, /* : */\n CHAR_COMMA: 44, /* , */\n CHAR_DOT: 46, /* . */\n CHAR_DOUBLE_QUOTE: 34, /* \" */\n CHAR_EQUAL: 61, /* = */\n CHAR_EXCLAMATION_MARK: 33, /* ! */\n CHAR_FORM_FEED: 12, /* \\f */\n CHAR_FORWARD_SLASH: 47, /* / */\n CHAR_GRAVE_ACCENT: 96, /* ` */\n CHAR_HASH: 35, /* # */\n CHAR_HYPHEN_MINUS: 45, /* - */\n CHAR_LEFT_ANGLE_BRACKET: 60, /* < */\n CHAR_LEFT_CURLY_BRACE: 123, /* { */\n CHAR_LEFT_SQUARE_BRACKET: 91, /* [ */\n CHAR_LINE_FEED: 10, /* \\n */\n CHAR_NO_BREAK_SPACE: 160, /* \\u00A0 */\n CHAR_PERCENT: 37, /* % */\n CHAR_PLUS: 43, /* + */\n CHAR_QUESTION_MARK: 63, /* ? */\n CHAR_RIGHT_ANGLE_BRACKET: 62, /* > */\n CHAR_RIGHT_CURLY_BRACE: 125, /* } */\n CHAR_RIGHT_SQUARE_BRACKET: 93, /* ] */\n CHAR_SEMICOLON: 59, /* ; */\n CHAR_SINGLE_QUOTE: 39, /* ' */\n CHAR_SPACE: 32, /* */\n CHAR_TAB: 9, /* \\t */\n CHAR_UNDERSCORE: 95, /* _ */\n CHAR_VERTICAL_LINE: 124, /* | */\n CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279, /* \\uFEFF */\n\n /**\n * Create EXTGLOB_CHARS\n */\n\n extglobChars(chars) {\n return {\n '!': { type: 'negate', open: '(?:(?!(?:', close: `))${chars.STAR})` },\n '?': { type: 'qmark', open: '(?:', close: ')?' },\n '+': { type: 'plus', open: '(?:', close: ')+' },\n '*': { type: 'star', open: '(?:', close: ')*' },\n '@': { type: 'at', open: '(?:', close: ')' }\n };\n },\n\n /**\n * Create GLOB_CHARS\n */\n\n globChars(win32) {\n return win32 === true ? WINDOWS_CHARS : POSIX_CHARS;\n }\n};\n","/*global navigator*/\n'use strict';\n\nconst {\n REGEX_BACKSLASH,\n REGEX_REMOVE_BACKSLASH,\n REGEX_SPECIAL_CHARS,\n REGEX_SPECIAL_CHARS_GLOBAL\n} = require('./constants');\n\nexports.isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val);\nexports.hasRegexChars = str => REGEX_SPECIAL_CHARS.test(str);\nexports.isRegexChar = str => str.length === 1 && exports.hasRegexChars(str);\nexports.escapeRegex = str => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, '\\\\$1');\nexports.toPosixSlashes = str => str.replace(REGEX_BACKSLASH, '/');\n\nexports.isWindows = () => {\n if (typeof navigator !== 'undefined' && navigator.platform) {\n const platform = navigator.platform.toLowerCase();\n return platform === 'win32' || platform === 'windows';\n }\n\n if (typeof process !== 'undefined' && process.platform) {\n return process.platform === 'win32';\n }\n\n return false;\n};\n\nexports.removeBackslashes = str => {\n return str.replace(REGEX_REMOVE_BACKSLASH, match => {\n return match === '\\\\' ? '' : match;\n });\n};\n\nexports.escapeLast = (input, char, lastIdx) => {\n const idx = input.lastIndexOf(char, lastIdx);\n if (idx === -1) return input;\n if (input[idx - 1] === '\\\\') return exports.escapeLast(input, char, idx - 1);\n return `${input.slice(0, idx)}\\\\${input.slice(idx)}`;\n};\n\nexports.removePrefix = (input, state = {}) => {\n let output = input;\n if (output.startsWith('./')) {\n output = output.slice(2);\n state.prefix = './';\n }\n return output;\n};\n\nexports.wrapOutput = (input, state = {}, options = {}) => {\n const prepend = options.contains ? '' : '^';\n const append = options.contains ? '' : '$';\n\n let output = `${prepend}(?:${input})${append}`;\n if (state.negated === true) {\n output = `(?:^(?!${output}).*$)`;\n }\n return output;\n};\n\nexports.basename = (path, { windows } = {}) => {\n const segs = path.split(windows ? /[\\\\/]/ : '/');\n const last = segs[segs.length - 1];\n\n if (last === '') {\n return segs[segs.length - 2];\n }\n\n return last;\n};\n","'use strict';\n\nconst utils = require('./utils');\nconst {\n CHAR_ASTERISK, /* * */\n CHAR_AT, /* @ */\n CHAR_BACKWARD_SLASH, /* \\ */\n CHAR_COMMA, /* , */\n CHAR_DOT, /* . */\n CHAR_EXCLAMATION_MARK, /* ! */\n CHAR_FORWARD_SLASH, /* / */\n CHAR_LEFT_CURLY_BRACE, /* { */\n CHAR_LEFT_PARENTHESES, /* ( */\n CHAR_LEFT_SQUARE_BRACKET, /* [ */\n CHAR_PLUS, /* + */\n CHAR_QUESTION_MARK, /* ? */\n CHAR_RIGHT_CURLY_BRACE, /* } */\n CHAR_RIGHT_PARENTHESES, /* ) */\n CHAR_RIGHT_SQUARE_BRACKET /* ] */\n} = require('./constants');\n\nconst isPathSeparator = code => {\n return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH;\n};\n\nconst depth = token => {\n if (token.isPrefix !== true) {\n token.depth = token.isGlobstar ? Infinity : 1;\n }\n};\n\n/**\n * Quickly scans a glob pattern and returns an object with a handful of\n * useful properties, like `isGlob`, `path` (the leading non-glob, if it exists),\n * `glob` (the actual pattern), `negated` (true if the path starts with `!` but not\n * with `!(`) and `negatedExtglob` (true if the path starts with `!(`).\n *\n * ```js\n * const pm = require('picomatch');\n * console.log(pm.scan('foo/bar/*.js'));\n * { isGlob: true, input: 'foo/bar/*.js', base: 'foo/bar', glob: '*.js' }\n * ```\n * @param {String} `str`\n * @param {Object} `options`\n * @return {Object} Returns an object with tokens and regex source string.\n * @api public\n */\n\nconst scan = (input, options) => {\n const opts = options || {};\n\n const length = input.length - 1;\n const scanToEnd = opts.parts === true || opts.scanToEnd === true;\n const slashes = [];\n const tokens = [];\n const parts = [];\n\n let str = input;\n let index = -1;\n let start = 0;\n let lastIndex = 0;\n let isBrace = false;\n let isBracket = false;\n let isGlob = false;\n let isExtglob = false;\n let isGlobstar = false;\n let braceEscaped = false;\n let backslashes = false;\n let negated = false;\n let negatedExtglob = false;\n let finished = false;\n let braces = 0;\n let prev;\n let code;\n let token = { value: '', depth: 0, isGlob: false };\n\n const eos = () => index >= length;\n const peek = () => str.charCodeAt(index + 1);\n const advance = () => {\n prev = code;\n return str.charCodeAt(++index);\n };\n\n while (index < length) {\n code = advance();\n let next;\n\n if (code === CHAR_BACKWARD_SLASH) {\n backslashes = token.backslashes = true;\n code = advance();\n\n if (code === CHAR_LEFT_CURLY_BRACE) {\n braceEscaped = true;\n }\n continue;\n }\n\n if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE) {\n braces++;\n\n while (eos() !== true && (code = advance())) {\n if (code === CHAR_BACKWARD_SLASH) {\n backslashes = token.backslashes = true;\n advance();\n continue;\n }\n\n if (code === CHAR_LEFT_CURLY_BRACE) {\n braces++;\n continue;\n }\n\n if (braceEscaped !== true && code === CHAR_DOT && (code = advance()) === CHAR_DOT) {\n isBrace = token.isBrace = true;\n isGlob = token.isGlob = true;\n finished = true;\n\n if (scanToEnd === true) {\n continue;\n }\n\n break;\n }\n\n if (braceEscaped !== true && code === CHAR_COMMA) {\n isBrace = token.isBrace = true;\n isGlob = token.isGlob = true;\n finished = true;\n\n if (scanToEnd === true) {\n continue;\n }\n\n break;\n }\n\n if (code === CHAR_RIGHT_CURLY_BRACE) {\n braces--;\n\n if (braces === 0) {\n braceEscaped = false;\n isBrace = token.isBrace = true;\n finished = true;\n break;\n }\n }\n }\n\n if (scanToEnd === true) {\n continue;\n }\n\n break;\n }\n\n if (code === CHAR_FORWARD_SLASH) {\n slashes.push(index);\n tokens.push(token);\n token = { value: '', depth: 0, isGlob: false };\n\n if (finished === true) continue;\n if (prev === CHAR_DOT && index === (start + 1)) {\n start += 2;\n continue;\n }\n\n lastIndex = index + 1;\n continue;\n }\n\n if (opts.noext !== true) {\n const isExtglobChar = code === CHAR_PLUS\n || code === CHAR_AT\n || code === CHAR_ASTERISK\n || code === CHAR_QUESTION_MARK\n || code === CHAR_EXCLAMATION_MARK;\n\n if (isExtglobChar === true && peek() === CHAR_LEFT_PARENTHESES) {\n isGlob = token.isGlob = true;\n isExtglob = token.isExtglob = true;\n finished = true;\n if (code === CHAR_EXCLAMATION_MARK && index === start) {\n negatedExtglob = true;\n }\n\n if (scanToEnd === true) {\n while (eos() !== true && (code = advance())) {\n if (code === CHAR_BACKWARD_SLASH) {\n backslashes = token.backslashes = true;\n code = advance();\n continue;\n }\n\n if (code === CHAR_RIGHT_PARENTHESES) {\n isGlob = token.isGlob = true;\n finished = true;\n break;\n }\n }\n continue;\n }\n break;\n }\n }\n\n if (code === CHAR_ASTERISK) {\n if (prev === CHAR_ASTERISK) isGlobstar = token.isGlobstar = true;\n isGlob = token.isGlob = true;\n finished = true;\n\n if (scanToEnd === true) {\n continue;\n }\n break;\n }\n\n if (code === CHAR_QUESTION_MARK) {\n isGlob = token.isGlob = true;\n finished = true;\n\n if (scanToEnd === true) {\n continue;\n }\n break;\n }\n\n if (code === CHAR_LEFT_SQUARE_BRACKET) {\n while (eos() !== true && (next = advance())) {\n if (next === CHAR_BACKWARD_SLASH) {\n backslashes = token.backslashes = true;\n advance();\n continue;\n }\n\n if (next === CHAR_RIGHT_SQUARE_BRACKET) {\n isBracket = token.isBracket = true;\n isGlob = token.isGlob = true;\n finished = true;\n break;\n }\n }\n\n if (scanToEnd === true) {\n continue;\n }\n\n break;\n }\n\n if (opts.nonegate !== true && code === CHAR_EXCLAMATION_MARK && index === start) {\n negated = token.negated = true;\n start++;\n continue;\n }\n\n if (opts.noparen !== true && code === CHAR_LEFT_PARENTHESES) {\n isGlob = token.isGlob = true;\n\n if (scanToEnd === true) {\n while (eos() !== true && (code = advance())) {\n if (code === CHAR_LEFT_PARENTHESES) {\n backslashes = token.backslashes = true;\n code = advance();\n continue;\n }\n\n if (code === CHAR_RIGHT_PARENTHESES) {\n finished = true;\n break;\n }\n }\n continue;\n }\n break;\n }\n\n if (isGlob === true) {\n finished = true;\n\n if (scanToEnd === true) {\n continue;\n }\n\n break;\n }\n }\n\n if (opts.noext === true) {\n isExtglob = false;\n isGlob = false;\n }\n\n let base = str;\n let prefix = '';\n let glob = '';\n\n if (start > 0) {\n prefix = str.slice(0, start);\n str = str.slice(start);\n lastIndex -= start;\n }\n\n if (base && isGlob === true && lastIndex > 0) {\n base = str.slice(0, lastIndex);\n glob = str.slice(lastIndex);\n } else if (isGlob === true) {\n base = '';\n glob = str;\n } else {\n base = str;\n }\n\n if (base && base !== '' && base !== '/' && base !== str) {\n if (isPathSeparator(base.charCodeAt(base.length - 1))) {\n base = base.slice(0, -1);\n }\n }\n\n if (opts.unescape === true) {\n if (glob) glob = utils.removeBackslashes(glob);\n\n if (base && backslashes === true) {\n base = utils.removeBackslashes(base);\n }\n }\n\n const state = {\n prefix,\n input,\n start,\n base,\n glob,\n isBrace,\n isBracket,\n isGlob,\n isExtglob,\n isGlobstar,\n negated,\n negatedExtglob\n };\n\n if (opts.tokens === true) {\n state.maxDepth = 0;\n if (!isPathSeparator(code)) {\n tokens.push(token);\n }\n state.tokens = tokens;\n }\n\n if (opts.parts === true || opts.tokens === true) {\n let prevIndex;\n\n for (let idx = 0; idx < slashes.length; idx++) {\n const n = prevIndex ? prevIndex + 1 : start;\n const i = slashes[idx];\n const value = input.slice(n, i);\n if (opts.tokens) {\n if (idx === 0 && start !== 0) {\n tokens[idx].isPrefix = true;\n tokens[idx].value = prefix;\n } else {\n tokens[idx].value = value;\n }\n depth(tokens[idx]);\n state.maxDepth += tokens[idx].depth;\n }\n if (idx !== 0 || value !== '') {\n parts.push(value);\n }\n prevIndex = i;\n }\n\n if (prevIndex && prevIndex + 1 < input.length) {\n const value = input.slice(prevIndex + 1);\n parts.push(value);\n\n if (opts.tokens) {\n tokens[tokens.length - 1].value = value;\n depth(tokens[tokens.length - 1]);\n state.maxDepth += tokens[tokens.length - 1].depth;\n }\n }\n\n state.slashes = slashes;\n state.parts = parts;\n }\n\n return state;\n};\n\nmodule.exports = scan;\n","'use strict';\n\nconst constants = require('./constants');\nconst utils = require('./utils');\n\n/**\n * Constants\n */\n\nconst {\n MAX_LENGTH,\n POSIX_REGEX_SOURCE,\n REGEX_NON_SPECIAL_CHARS,\n REGEX_SPECIAL_CHARS_BACKREF,\n REPLACEMENTS\n} = constants;\n\n/**\n * Helpers\n */\n\nconst expandRange = (args, options) => {\n if (typeof options.expandRange === 'function') {\n return options.expandRange(...args, options);\n }\n\n args.sort();\n const value = `[${args.join('-')}]`;\n\n try {\n /* eslint-disable-next-line no-new */\n new RegExp(value);\n } catch (ex) {\n return args.map(v => utils.escapeRegex(v)).join('..');\n }\n\n return value;\n};\n\n/**\n * Create the message for a syntax error\n */\n\nconst syntaxError = (type, char) => {\n return `Missing ${type}: \"${char}\" - use \"\\\\\\\\${char}\" to match literal characters`;\n};\n\n/**\n * Parse the given input string.\n * @param {String} input\n * @param {Object} options\n * @return {Object}\n */\n\nconst parse = (input, options) => {\n if (typeof input !== 'string') {\n throw new TypeError('Expected a string');\n }\n\n input = REPLACEMENTS[input] || input;\n\n const opts = { ...options };\n const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;\n\n let len = input.length;\n if (len > max) {\n throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);\n }\n\n const bos = { type: 'bos', value: '', output: opts.prepend || '' };\n const tokens = [bos];\n\n const capture = opts.capture ? '' : '?:';\n\n // create constants based on platform, for windows or posix\n const PLATFORM_CHARS = constants.globChars(opts.windows);\n const EXTGLOB_CHARS = constants.extglobChars(PLATFORM_CHARS);\n\n const {\n DOT_LITERAL,\n PLUS_LITERAL,\n SLASH_LITERAL,\n ONE_CHAR,\n DOTS_SLASH,\n NO_DOT,\n NO_DOT_SLASH,\n NO_DOTS_SLASH,\n QMARK,\n QMARK_NO_DOT,\n STAR,\n START_ANCHOR\n } = PLATFORM_CHARS;\n\n const globstar = opts => {\n return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;\n };\n\n const nodot = opts.dot ? '' : NO_DOT;\n const qmarkNoDot = opts.dot ? QMARK : QMARK_NO_DOT;\n let star = opts.bash === true ? globstar(opts) : STAR;\n\n if (opts.capture) {\n star = `(${star})`;\n }\n\n // minimatch options support\n if (typeof opts.noext === 'boolean') {\n opts.noextglob = opts.noext;\n }\n\n const state = {\n input,\n index: -1,\n start: 0,\n dot: opts.dot === true,\n consumed: '',\n output: '',\n prefix: '',\n backtrack: false,\n negated: false,\n brackets: 0,\n braces: 0,\n parens: 0,\n quotes: 0,\n globstar: false,\n tokens\n };\n\n input = utils.removePrefix(input, state);\n len = input.length;\n\n const extglobs = [];\n const braces = [];\n const stack = [];\n let prev = bos;\n let value;\n\n /**\n * Tokenizing helpers\n */\n\n const eos = () => state.index === len - 1;\n const peek = state.peek = (n = 1) => input[state.index + n];\n const advance = state.advance = () => input[++state.index] || '';\n const remaining = () => input.slice(state.index + 1);\n const consume = (value = '', num = 0) => {\n state.consumed += value;\n state.index += num;\n };\n\n const append = token => {\n state.output += token.output != null ? token.output : token.value;\n consume(token.value);\n };\n\n const negate = () => {\n let count = 1;\n\n while (peek() === '!' && (peek(2) !== '(' || peek(3) === '?')) {\n advance();\n state.start++;\n count++;\n }\n\n if (count % 2 === 0) {\n return false;\n }\n\n state.negated = true;\n state.start++;\n return true;\n };\n\n const increment = type => {\n state[type]++;\n stack.push(type);\n };\n\n const decrement = type => {\n state[type]--;\n stack.pop();\n };\n\n /**\n * Push tokens onto the tokens array. This helper speeds up\n * tokenizing by 1) helping us avoid backtracking as much as possible,\n * and 2) helping us avoid creating extra tokens when consecutive\n * characters are plain text. This improves performance and simplifies\n * lookbehinds.\n */\n\n const push = tok => {\n if (prev.type === 'globstar') {\n const isBrace = state.braces > 0 && (tok.type === 'comma' || tok.type === 'brace');\n const isExtglob = tok.extglob === true || (extglobs.length && (tok.type === 'pipe' || tok.type === 'paren'));\n\n if (tok.type !== 'slash' && tok.type !== 'paren' && !isBrace && !isExtglob) {\n state.output = state.output.slice(0, -prev.output.length);\n prev.type = 'star';\n prev.value = '*';\n prev.output = star;\n state.output += prev.output;\n }\n }\n\n if (extglobs.length && tok.type !== 'paren') {\n extglobs[extglobs.length - 1].inner += tok.value;\n }\n\n if (tok.value || tok.output) append(tok);\n if (prev && prev.type === 'text' && tok.type === 'text') {\n prev.output = (prev.output || prev.value) + tok.value;\n prev.value += tok.value;\n return;\n }\n\n tok.prev = prev;\n tokens.push(tok);\n prev = tok;\n };\n\n const extglobOpen = (type, value) => {\n const token = { ...EXTGLOB_CHARS[value], conditions: 1, inner: '' };\n\n token.prev = prev;\n token.parens = state.parens;\n token.output = state.output;\n const output = (opts.capture ? '(' : '') + token.open;\n\n increment('parens');\n push({ type, value, output: state.output ? '' : ONE_CHAR });\n push({ type: 'paren', extglob: true, value: advance(), output });\n extglobs.push(token);\n };\n\n const extglobClose = token => {\n let output = token.close + (opts.capture ? ')' : '');\n let rest;\n\n if (token.type === 'negate') {\n let extglobStar = star;\n\n if (token.inner && token.inner.length > 1 && token.inner.includes('/')) {\n extglobStar = globstar(opts);\n }\n\n if (extglobStar !== star || eos() || /^\\)+$/.test(remaining())) {\n output = token.close = `)$))${extglobStar}`;\n }\n\n if (token.inner.includes('*') && (rest = remaining()) && /^\\.[^\\\\/.]+$/.test(rest)) {\n // Any non-magical string (`.ts`) or even nested expression (`.{ts,tsx}`) can follow after the closing parenthesis.\n // In this case, we need to parse the string and use it in the output of the original pattern.\n // Suitable patterns: `/!(*.d).ts`, `/!(*.d).{ts,tsx}`, `**/!(*-dbg).@(js)`.\n //\n // Disabling the `fastpaths` option due to a problem with parsing strings as `.ts` in the pattern like `**/!(*.d).ts`.\n const expression = parse(rest, { ...options, fastpaths: false }).output;\n\n output = token.close = `)${expression})${extglobStar})`;\n }\n\n if (token.prev.type === 'bos') {\n state.negatedExtglob = true;\n }\n }\n\n push({ type: 'paren', extglob: true, value, output });\n decrement('parens');\n };\n\n /**\n * Fast paths\n */\n\n if (opts.fastpaths !== false && !/(^[*!]|[/()[\\]{}\"])/.test(input)) {\n let backslashes = false;\n\n let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc, chars, first, rest, index) => {\n if (first === '\\\\') {\n backslashes = true;\n return m;\n }\n\n if (first === '?') {\n if (esc) {\n return esc + first + (rest ? QMARK.repeat(rest.length) : '');\n }\n if (index === 0) {\n return qmarkNoDot + (rest ? QMARK.repeat(rest.length) : '');\n }\n return QMARK.repeat(chars.length);\n }\n\n if (first === '.') {\n return DOT_LITERAL.repeat(chars.length);\n }\n\n if (first === '*') {\n if (esc) {\n return esc + first + (rest ? star : '');\n }\n return star;\n }\n return esc ? m : `\\\\${m}`;\n });\n\n if (backslashes === true) {\n if (opts.unescape === true) {\n output = output.replace(/\\\\/g, '');\n } else {\n output = output.replace(/\\\\+/g, m => {\n return m.length % 2 === 0 ? '\\\\\\\\' : (m ? '\\\\' : '');\n });\n }\n }\n\n if (output === input && opts.contains === true) {\n state.output = input;\n return state;\n }\n\n state.output = utils.wrapOutput(output, state, options);\n return state;\n }\n\n /**\n * Tokenize input until we reach end-of-string\n */\n\n while (!eos()) {\n value = advance();\n\n if (value === '\\u0000') {\n continue;\n }\n\n /**\n * Escaped characters\n */\n\n if (value === '\\\\') {\n const next = peek();\n\n if (next === '/' && opts.bash !== true) {\n continue;\n }\n\n if (next === '.' || next === ';') {\n continue;\n }\n\n if (!next) {\n value += '\\\\';\n push({ type: 'text', value });\n continue;\n }\n\n // collapse slashes to reduce potential for exploits\n const match = /^\\\\+/.exec(remaining());\n let slashes = 0;\n\n if (match && match[0].length > 2) {\n slashes = match[0].length;\n state.index += slashes;\n if (slashes % 2 !== 0) {\n value += '\\\\';\n }\n }\n\n if (opts.unescape === true) {\n value = advance();\n } else {\n value += advance();\n }\n\n if (state.brackets === 0) {\n push({ type: 'text', value });\n continue;\n }\n }\n\n /**\n * If we're inside a regex character class, continue\n * until we reach the closing bracket.\n */\n\n if (state.brackets > 0 && (value !== ']' || prev.value === '[' || prev.value === '[^')) {\n if (opts.posix !== false && value === ':') {\n const inner = prev.value.slice(1);\n if (inner.includes('[')) {\n prev.posix = true;\n\n if (inner.includes(':')) {\n const idx = prev.value.lastIndexOf('[');\n const pre = prev.value.slice(0, idx);\n const rest = prev.value.slice(idx + 2);\n const posix = POSIX_REGEX_SOURCE[rest];\n if (posix) {\n prev.value = pre + posix;\n state.backtrack = true;\n advance();\n\n if (!bos.output && tokens.indexOf(prev) === 1) {\n bos.output = ONE_CHAR;\n }\n continue;\n }\n }\n }\n }\n\n if ((value === '[' && peek() !== ':') || (value === '-' && peek() === ']')) {\n value = `\\\\${value}`;\n }\n\n if (value === ']' && (prev.value === '[' || prev.value === '[^')) {\n value = `\\\\${value}`;\n }\n\n if (opts.posix === true && value === '!' && prev.value === '[') {\n value = '^';\n }\n\n prev.value += value;\n append({ value });\n continue;\n }\n\n /**\n * If we're inside a quoted string, continue\n * until we reach the closing double quote.\n */\n\n if (state.quotes === 1 && value !== '\"') {\n value = utils.escapeRegex(value);\n prev.value += value;\n append({ value });\n continue;\n }\n\n /**\n * Double quotes\n */\n\n if (value === '\"') {\n state.quotes = state.quotes === 1 ? 0 : 1;\n if (opts.keepQuotes === true) {\n push({ type: 'text', value });\n }\n continue;\n }\n\n /**\n * Parentheses\n */\n\n if (value === '(') {\n increment('parens');\n push({ type: 'paren', value });\n continue;\n }\n\n if (value === ')') {\n if (state.parens === 0 && opts.strictBrackets === true) {\n throw new SyntaxError(syntaxError('opening', '('));\n }\n\n const extglob = extglobs[extglobs.length - 1];\n if (extglob && state.parens === extglob.parens + 1) {\n extglobClose(extglobs.pop());\n continue;\n }\n\n push({ type: 'paren', value, output: state.parens ? ')' : '\\\\)' });\n decrement('parens');\n continue;\n }\n\n /**\n * Square brackets\n */\n\n if (value === '[') {\n if (opts.nobracket === true || !remaining().includes(']')) {\n if (opts.nobracket !== true && opts.strictBrackets === true) {\n throw new SyntaxError(syntaxError('closing', ']'));\n }\n\n value = `\\\\${value}`;\n } else {\n increment('brackets');\n }\n\n push({ type: 'bracket', value });\n continue;\n }\n\n if (value === ']') {\n if (opts.nobracket === true || (prev && prev.type === 'bracket' && prev.value.length === 1)) {\n push({ type: 'text', value, output: `\\\\${value}` });\n continue;\n }\n\n if (state.brackets === 0) {\n if (opts.strictBrackets === true) {\n throw new SyntaxError(syntaxError('opening', '['));\n }\n\n push({ type: 'text', value, output: `\\\\${value}` });\n continue;\n }\n\n decrement('brackets');\n\n const prevValue = prev.value.slice(1);\n if (prev.posix !== true && prevValue[0] === '^' && !prevValue.includes('/')) {\n value = `/${value}`;\n }\n\n prev.value += value;\n append({ value });\n\n // when literal brackets are explicitly disabled\n // assume we should match with a regex character class\n if (opts.literalBrackets === false || utils.hasRegexChars(prevValue)) {\n continue;\n }\n\n const escaped = utils.escapeRegex(prev.value);\n state.output = state.output.slice(0, -prev.value.length);\n\n // when literal brackets are explicitly enabled\n // assume we should escape the brackets to match literal characters\n if (opts.literalBrackets === true) {\n state.output += escaped;\n prev.value = escaped;\n continue;\n }\n\n // when the user specifies nothing, try to match both\n prev.value = `(${capture}${escaped}|${prev.value})`;\n state.output += prev.value;\n continue;\n }\n\n /**\n * Braces\n */\n\n if (value === '{' && opts.nobrace !== true) {\n increment('braces');\n\n const open = {\n type: 'brace',\n value,\n output: '(',\n outputIndex: state.output.length,\n tokensIndex: state.tokens.length\n };\n\n braces.push(open);\n push(open);\n continue;\n }\n\n if (value === '}') {\n const brace = braces[braces.length - 1];\n\n if (opts.nobrace === true || !brace) {\n push({ type: 'text', value, output: value });\n continue;\n }\n\n let output = ')';\n\n if (brace.dots === true) {\n const arr = tokens.slice();\n const range = [];\n\n for (let i = arr.length - 1; i >= 0; i--) {\n tokens.pop();\n if (arr[i].type === 'brace') {\n break;\n }\n if (arr[i].type !== 'dots') {\n range.unshift(arr[i].value);\n }\n }\n\n output = expandRange(range, opts);\n state.backtrack = true;\n }\n\n if (brace.comma !== true && brace.dots !== true) {\n const out = state.output.slice(0, brace.outputIndex);\n const toks = state.tokens.slice(brace.tokensIndex);\n brace.value = brace.output = '\\\\{';\n value = output = '\\\\}';\n state.output = out;\n for (const t of toks) {\n state.output += (t.output || t.value);\n }\n }\n\n push({ type: 'brace', value, output });\n decrement('braces');\n braces.pop();\n continue;\n }\n\n /**\n * Pipes\n */\n\n if (value === '|') {\n if (extglobs.length > 0) {\n extglobs[extglobs.length - 1].conditions++;\n }\n push({ type: 'text', value });\n continue;\n }\n\n /**\n * Commas\n */\n\n if (value === ',') {\n let output = value;\n\n const brace = braces[braces.length - 1];\n if (brace && stack[stack.length - 1] === 'braces') {\n brace.comma = true;\n output = '|';\n }\n\n push({ type: 'comma', value, output });\n continue;\n }\n\n /**\n * Slashes\n */\n\n if (value === '/') {\n // if the beginning of the glob is \"./\", advance the start\n // to the current index, and don't add the \"./\" characters\n // to the state. This greatly simplifies lookbehinds when\n // checking for BOS characters like \"!\" and \".\" (not \"./\")\n if (prev.type === 'dot' && state.index === state.start + 1) {\n state.start = state.index + 1;\n state.consumed = '';\n state.output = '';\n tokens.pop();\n prev = bos; // reset \"prev\" to the first token\n continue;\n }\n\n push({ type: 'slash', value, output: SLASH_LITERAL });\n continue;\n }\n\n /**\n * Dots\n */\n\n if (value === '.') {\n if (state.braces > 0 && prev.type === 'dot') {\n if (prev.value === '.') prev.output = DOT_LITERAL;\n const brace = braces[braces.length - 1];\n prev.type = 'dots';\n prev.output += value;\n prev.value += value;\n brace.dots = true;\n continue;\n }\n\n if ((state.braces + state.parens) === 0 && prev.type !== 'bos' && prev.type !== 'slash') {\n push({ type: 'text', value, output: DOT_LITERAL });\n continue;\n }\n\n push({ type: 'dot', value, output: DOT_LITERAL });\n continue;\n }\n\n /**\n * Question marks\n */\n\n if (value === '?') {\n const isGroup = prev && prev.value === '(';\n if (!isGroup && opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {\n extglobOpen('qmark', value);\n continue;\n }\n\n if (prev && prev.type === 'paren') {\n const next = peek();\n let output = value;\n\n if ((prev.value === '(' && !/[!=<:]/.test(next)) || (next === '<' && !/<([!=]|\\w+>)/.test(remaining()))) {\n output = `\\\\${value}`;\n }\n\n push({ type: 'text', value, output });\n continue;\n }\n\n if (opts.dot !== true && (prev.type === 'slash' || prev.type === 'bos')) {\n push({ type: 'qmark', value, output: QMARK_NO_DOT });\n continue;\n }\n\n push({ type: 'qmark', value, output: QMARK });\n continue;\n }\n\n /**\n * Exclamation\n */\n\n if (value === '!') {\n if (opts.noextglob !== true && peek() === '(') {\n if (peek(2) !== '?' || !/[!=<:]/.test(peek(3))) {\n extglobOpen('negate', value);\n continue;\n }\n }\n\n if (opts.nonegate !== true && state.index === 0) {\n negate();\n continue;\n }\n }\n\n /**\n * Plus\n */\n\n if (value === '+') {\n if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {\n extglobOpen('plus', value);\n continue;\n }\n\n if ((prev && prev.value === '(') || opts.regex === false) {\n push({ type: 'plus', value, output: PLUS_LITERAL });\n continue;\n }\n\n if ((prev && (prev.type === 'bracket' || prev.type === 'paren' || prev.type === 'brace')) || state.parens > 0) {\n push({ type: 'plus', value });\n continue;\n }\n\n push({ type: 'plus', value: PLUS_LITERAL });\n continue;\n }\n\n /**\n * Plain text\n */\n\n if (value === '@') {\n if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {\n push({ type: 'at', extglob: true, value, output: '' });\n continue;\n }\n\n push({ type: 'text', value });\n continue;\n }\n\n /**\n * Plain text\n */\n\n if (value !== '*') {\n if (value === '$' || value === '^') {\n value = `\\\\${value}`;\n }\n\n const match = REGEX_NON_SPECIAL_CHARS.exec(remaining());\n if (match) {\n value += match[0];\n state.index += match[0].length;\n }\n\n push({ type: 'text', value });\n continue;\n }\n\n /**\n * Stars\n */\n\n if (prev && (prev.type === 'globstar' || prev.star === true)) {\n prev.type = 'star';\n prev.star = true;\n prev.value += value;\n prev.output = star;\n state.backtrack = true;\n state.globstar = true;\n consume(value);\n continue;\n }\n\n let rest = remaining();\n if (opts.noextglob !== true && /^\\([^?]/.test(rest)) {\n extglobOpen('star', value);\n continue;\n }\n\n if (prev.type === 'star') {\n if (opts.noglobstar === true) {\n consume(value);\n continue;\n }\n\n const prior = prev.prev;\n const before = prior.prev;\n const isStart = prior.type === 'slash' || prior.type === 'bos';\n const afterStar = before && (before.type === 'star' || before.type === 'globstar');\n\n if (opts.bash === true && (!isStart || (rest[0] && rest[0] !== '/'))) {\n push({ type: 'star', value, output: '' });\n continue;\n }\n\n const isBrace = state.braces > 0 && (prior.type === 'comma' || prior.type === 'brace');\n const isExtglob = extglobs.length && (prior.type === 'pipe' || prior.type === 'paren');\n if (!isStart && prior.type !== 'paren' && !isBrace && !isExtglob) {\n push({ type: 'star', value, output: '' });\n continue;\n }\n\n // strip consecutive `/**/`\n while (rest.slice(0, 3) === '/**') {\n const after = input[state.index + 4];\n if (after && after !== '/') {\n break;\n }\n rest = rest.slice(3);\n consume('/**', 3);\n }\n\n if (prior.type === 'bos' && eos()) {\n prev.type = 'globstar';\n prev.value += value;\n prev.output = globstar(opts);\n state.output = prev.output;\n state.globstar = true;\n consume(value);\n continue;\n }\n\n if (prior.type === 'slash' && prior.prev.type !== 'bos' && !afterStar && eos()) {\n state.output = state.output.slice(0, -(prior.output + prev.output).length);\n prior.output = `(?:${prior.output}`;\n\n prev.type = 'globstar';\n prev.output = globstar(opts) + (opts.strictSlashes ? ')' : '|$)');\n prev.value += value;\n state.globstar = true;\n state.output += prior.output + prev.output;\n consume(value);\n continue;\n }\n\n if (prior.type === 'slash' && prior.prev.type !== 'bos' && rest[0] === '/') {\n const end = rest[1] !== void 0 ? '|$' : '';\n\n state.output = state.output.slice(0, -(prior.output + prev.output).length);\n prior.output = `(?:${prior.output}`;\n\n prev.type = 'globstar';\n prev.output = `${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`;\n prev.value += value;\n\n state.output += prior.output + prev.output;\n state.globstar = true;\n\n consume(value + advance());\n\n push({ type: 'slash', value: '/', output: '' });\n continue;\n }\n\n if (prior.type === 'bos' && rest[0] === '/') {\n prev.type = 'globstar';\n prev.value += value;\n prev.output = `(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`;\n state.output = prev.output;\n state.globstar = true;\n consume(value + advance());\n push({ type: 'slash', value: '/', output: '' });\n continue;\n }\n\n // remove single star from output\n state.output = state.output.slice(0, -prev.output.length);\n\n // reset previous token to globstar\n prev.type = 'globstar';\n prev.output = globstar(opts);\n prev.value += value;\n\n // reset output with globstar\n state.output += prev.output;\n state.globstar = true;\n consume(value);\n continue;\n }\n\n const token = { type: 'star', value, output: star };\n\n if (opts.bash === true) {\n token.output = '.*?';\n if (prev.type === 'bos' || prev.type === 'slash') {\n token.output = nodot + token.output;\n }\n push(token);\n continue;\n }\n\n if (prev && (prev.type === 'bracket' || prev.type === 'paren') && opts.regex === true) {\n token.output = value;\n push(token);\n continue;\n }\n\n if (state.index === state.start || prev.type === 'slash' || prev.type === 'dot') {\n if (prev.type === 'dot') {\n state.output += NO_DOT_SLASH;\n prev.output += NO_DOT_SLASH;\n\n } else if (opts.dot === true) {\n state.output += NO_DOTS_SLASH;\n prev.output += NO_DOTS_SLASH;\n\n } else {\n state.output += nodot;\n prev.output += nodot;\n }\n\n if (peek() !== '*') {\n state.output += ONE_CHAR;\n prev.output += ONE_CHAR;\n }\n }\n\n push(token);\n }\n\n while (state.brackets > 0) {\n if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ']'));\n state.output = utils.escapeLast(state.output, '[');\n decrement('brackets');\n }\n\n while (state.parens > 0) {\n if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ')'));\n state.output = utils.escapeLast(state.output, '(');\n decrement('parens');\n }\n\n while (state.braces > 0) {\n if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', '}'));\n state.output = utils.escapeLast(state.output, '{');\n decrement('braces');\n }\n\n if (opts.strictSlashes !== true && (prev.type === 'star' || prev.type === 'bracket')) {\n push({ type: 'maybe_slash', value: '', output: `${SLASH_LITERAL}?` });\n }\n\n // rebuild the output if we had to backtrack at any point\n if (state.backtrack === true) {\n state.output = '';\n\n for (const token of state.tokens) {\n state.output += token.output != null ? token.output : token.value;\n\n if (token.suffix) {\n state.output += token.suffix;\n }\n }\n }\n\n return state;\n};\n\n/**\n * Fast paths for creating regular expressions for common glob patterns.\n * This can significantly speed up processing and has very little downside\n * impact when none of the fast paths match.\n */\n\nparse.fastpaths = (input, options) => {\n const opts = { ...options };\n const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;\n const len = input.length;\n if (len > max) {\n throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);\n }\n\n input = REPLACEMENTS[input] || input;\n\n // create constants based on platform, for windows or posix\n const {\n DOT_LITERAL,\n SLASH_LITERAL,\n ONE_CHAR,\n DOTS_SLASH,\n NO_DOT,\n NO_DOTS,\n NO_DOTS_SLASH,\n STAR,\n START_ANCHOR\n } = constants.globChars(opts.windows);\n\n const nodot = opts.dot ? NO_DOTS : NO_DOT;\n const slashDot = opts.dot ? NO_DOTS_SLASH : NO_DOT;\n const capture = opts.capture ? '' : '?:';\n const state = { negated: false, prefix: '' };\n let star = opts.bash === true ? '.*?' : STAR;\n\n if (opts.capture) {\n star = `(${star})`;\n }\n\n const globstar = opts => {\n if (opts.noglobstar === true) return star;\n return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;\n };\n\n const create = str => {\n switch (str) {\n case '*':\n return `${nodot}${ONE_CHAR}${star}`;\n\n case '.*':\n return `${DOT_LITERAL}${ONE_CHAR}${star}`;\n\n case '*.*':\n return `${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;\n\n case '*/*':\n return `${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`;\n\n case '**':\n return nodot + globstar(opts);\n\n case '**/*':\n return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`;\n\n case '**/*.*':\n return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;\n\n case '**/.*':\n return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`;\n\n default: {\n const match = /^(.*?)\\.(\\w+)$/.exec(str);\n if (!match) return;\n\n const source = create(match[1]);\n if (!source) return;\n\n return source + DOT_LITERAL + match[2];\n }\n }\n };\n\n const output = utils.removePrefix(input, state);\n let source = create(output);\n\n if (source && opts.strictSlashes !== true) {\n source += `${SLASH_LITERAL}?`;\n }\n\n return source;\n};\n\nmodule.exports = parse;\n","'use strict';\n\nconst scan = require('./scan');\nconst parse = require('./parse');\nconst utils = require('./utils');\nconst constants = require('./constants');\nconst isObject = val => val && typeof val === 'object' && !Array.isArray(val);\n\n/**\n * Creates a matcher function from one or more glob patterns. The\n * returned function takes a string to match as its first argument,\n * and returns true if the string is a match. The returned matcher\n * function also takes a boolean as the second argument that, when true,\n * returns an object with additional information.\n *\n * ```js\n * const picomatch = require('picomatch');\n * // picomatch(glob[, options]);\n *\n * const isMatch = picomatch('*.!(*a)');\n * console.log(isMatch('a.a')); //=> false\n * console.log(isMatch('a.b')); //=> true\n * ```\n * @name picomatch\n * @param {String|Array} `globs` One or more glob patterns.\n * @param {Object=} `options`\n * @return {Function=} Returns a matcher function.\n * @api public\n */\n\nconst picomatch = (glob, options, returnState = false) => {\n if (Array.isArray(glob)) {\n const fns = glob.map(input => picomatch(input, options, returnState));\n const arrayMatcher = str => {\n for (const isMatch of fns) {\n const state = isMatch(str);\n if (state) return state;\n }\n return false;\n };\n return arrayMatcher;\n }\n\n const isState = isObject(glob) && glob.tokens && glob.input;\n\n if (glob === '' || (typeof glob !== 'string' && !isState)) {\n throw new TypeError('Expected pattern to be a non-empty string');\n }\n\n const opts = options || {};\n const posix = opts.windows;\n const regex = isState\n ? picomatch.compileRe(glob, options)\n : picomatch.makeRe(glob, options, false, true);\n\n const state = regex.state;\n delete regex.state;\n\n let isIgnored = () => false;\n if (opts.ignore) {\n const ignoreOpts = { ...options, ignore: null, onMatch: null, onResult: null };\n isIgnored = picomatch(opts.ignore, ignoreOpts, returnState);\n }\n\n const matcher = (input, returnObject = false) => {\n const { isMatch, match, output } = picomatch.test(input, regex, options, { glob, posix });\n const result = { glob, state, regex, posix, input, output, match, isMatch };\n\n if (typeof opts.onResult === 'function') {\n opts.onResult(result);\n }\n\n if (isMatch === false) {\n result.isMatch = false;\n return returnObject ? result : false;\n }\n\n if (isIgnored(input)) {\n if (typeof opts.onIgnore === 'function') {\n opts.onIgnore(result);\n }\n result.isMatch = false;\n return returnObject ? result : false;\n }\n\n if (typeof opts.onMatch === 'function') {\n opts.onMatch(result);\n }\n return returnObject ? result : true;\n };\n\n if (returnState) {\n matcher.state = state;\n }\n\n return matcher;\n};\n\n/**\n * Test `input` with the given `regex`. This is used by the main\n * `picomatch()` function to test the input string.\n *\n * ```js\n * const picomatch = require('picomatch');\n * // picomatch.test(input, regex[, options]);\n *\n * console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\\/([^/]*?))$/));\n * // { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' }\n * ```\n * @param {String} `input` String to test.\n * @param {RegExp} `regex`\n * @return {Object} Returns an object with matching info.\n * @api public\n */\n\npicomatch.test = (input, regex, options, { glob, posix } = {}) => {\n if (typeof input !== 'string') {\n throw new TypeError('Expected input to be a string');\n }\n\n if (input === '') {\n return { isMatch: false, output: '' };\n }\n\n const opts = options || {};\n const format = opts.format || (posix ? utils.toPosixSlashes : null);\n let match = input === glob;\n let output = (match && format) ? format(input) : input;\n\n if (match === false) {\n output = format ? format(input) : input;\n match = output === glob;\n }\n\n if (match === false || opts.capture === true) {\n if (opts.matchBase === true || opts.basename === true) {\n match = picomatch.matchBase(input, regex, options, posix);\n } else {\n match = regex.exec(output);\n }\n }\n\n return { isMatch: Boolean(match), match, output };\n};\n\n/**\n * Match the basename of a filepath.\n *\n * ```js\n * const picomatch = require('picomatch');\n * // picomatch.matchBase(input, glob[, options]);\n * console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true\n * ```\n * @param {String} `input` String to test.\n * @param {RegExp|String} `glob` Glob pattern or regex created by [.makeRe](#makeRe).\n * @return {Boolean}\n * @api public\n */\n\npicomatch.matchBase = (input, glob, options) => {\n const regex = glob instanceof RegExp ? glob : picomatch.makeRe(glob, options);\n return regex.test(utils.basename(input));\n};\n\n/**\n * Returns true if **any** of the given glob `patterns` match the specified `string`.\n *\n * ```js\n * const picomatch = require('picomatch');\n * // picomatch.isMatch(string, patterns[, options]);\n *\n * console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true\n * console.log(picomatch.isMatch('a.a', 'b.*')); //=> false\n * ```\n * @param {String|Array} str The string to test.\n * @param {String|Array} patterns One or more glob patterns to use for matching.\n * @param {Object} [options] See available [options](#options).\n * @return {Boolean} Returns true if any patterns match `str`\n * @api public\n */\n\npicomatch.isMatch = (str, patterns, options) => picomatch(patterns, options)(str);\n\n/**\n * Parse a glob pattern to create the source string for a regular\n * expression.\n *\n * ```js\n * const picomatch = require('picomatch');\n * const result = picomatch.parse(pattern[, options]);\n * ```\n * @param {String} `pattern`\n * @param {Object} `options`\n * @return {Object} Returns an object with useful properties and output to be used as a regex source string.\n * @api public\n */\n\npicomatch.parse = (pattern, options) => {\n if (Array.isArray(pattern)) return pattern.map(p => picomatch.parse(p, options));\n return parse(pattern, { ...options, fastpaths: false });\n};\n\n/**\n * Scan a glob pattern to separate the pattern into segments.\n *\n * ```js\n * const picomatch = require('picomatch');\n * // picomatch.scan(input[, options]);\n *\n * const result = picomatch.scan('!./foo/*.js');\n * console.log(result);\n * { prefix: '!./',\n * input: '!./foo/*.js',\n * start: 3,\n * base: 'foo',\n * glob: '*.js',\n * isBrace: false,\n * isBracket: false,\n * isGlob: true,\n * isExtglob: false,\n * isGlobstar: false,\n * negated: true }\n * ```\n * @param {String} `input` Glob pattern to scan.\n * @param {Object} `options`\n * @return {Object} Returns an object with\n * @api public\n */\n\npicomatch.scan = (input, options) => scan(input, options);\n\n/**\n * Compile a regular expression from the `state` object returned by the\n * [parse()](#parse) method.\n *\n * @param {Object} `state`\n * @param {Object} `options`\n * @param {Boolean} `returnOutput` Intended for implementors, this argument allows you to return the raw output from the parser.\n * @param {Boolean} `returnState` Adds the state to a `state` property on the returned regex. Useful for implementors and debugging.\n * @return {RegExp}\n * @api public\n */\n\npicomatch.compileRe = (state, options, returnOutput = false, returnState = false) => {\n if (returnOutput === true) {\n return state.output;\n }\n\n const opts = options || {};\n const prepend = opts.contains ? '' : '^';\n const append = opts.contains ? '' : '$';\n\n let source = `${prepend}(?:${state.output})${append}`;\n if (state && state.negated === true) {\n source = `^(?!${source}).*$`;\n }\n\n const regex = picomatch.toRegex(source, options);\n if (returnState === true) {\n regex.state = state;\n }\n\n return regex;\n};\n\n/**\n * Create a regular expression from a parsed glob pattern.\n *\n * ```js\n * const picomatch = require('picomatch');\n * const state = picomatch.parse('*.js');\n * // picomatch.compileRe(state[, options]);\n *\n * console.log(picomatch.compileRe(state));\n * //=> /^(?:(?!\\.)(?=.)[^/]*?\\.js)$/\n * ```\n * @param {String} `state` The object returned from the `.parse` method.\n * @param {Object} `options`\n * @param {Boolean} `returnOutput` Implementors may use this argument to return the compiled output, instead of a regular expression. This is not exposed on the options to prevent end-users from mutating the result.\n * @param {Boolean} `returnState` Implementors may use this argument to return the state from the parsed glob with the returned regular expression.\n * @return {RegExp} Returns a regex created from the given pattern.\n * @api public\n */\n\npicomatch.makeRe = (input, options = {}, returnOutput = false, returnState = false) => {\n if (!input || typeof input !== 'string') {\n throw new TypeError('Expected a non-empty string');\n }\n\n let parsed = { negated: false, fastpaths: true };\n\n if (options.fastpaths !== false && (input[0] === '.' || input[0] === '*')) {\n parsed.output = parse.fastpaths(input, options);\n }\n\n if (!parsed.output) {\n parsed = parse(input, options);\n }\n\n return picomatch.compileRe(parsed, options, returnOutput, returnState);\n};\n\n/**\n * Create a regular expression from the given regex source string.\n *\n * ```js\n * const picomatch = require('picomatch');\n * // picomatch.toRegex(source[, options]);\n *\n * const { output } = picomatch.parse('*.js');\n * console.log(picomatch.toRegex(output));\n * //=> /^(?:(?!\\.)(?=.)[^/]*?\\.js)$/\n * ```\n * @param {String} `source` Regular expression source string.\n * @param {Object} `options`\n * @return {RegExp}\n * @api public\n */\n\npicomatch.toRegex = (source, options) => {\n try {\n const opts = options || {};\n return new RegExp(source, opts.flags || (opts.nocase ? 'i' : ''));\n } catch (err) {\n if (options && options.debug === true) throw err;\n return /$^/;\n }\n};\n\n/**\n * Picomatch constants.\n * @return {Object}\n */\n\npicomatch.constants = constants;\n\n/**\n * Expose \"picomatch\"\n */\n\nmodule.exports = picomatch;\n","'use strict';\n\nconst pico = require('./lib/picomatch');\nconst utils = require('./lib/utils');\n\nfunction picomatch(glob, options, returnState = false) {\n // default to os.platform()\n if (options && (options.windows === null || options.windows === undefined)) {\n // don't mutate the original options object\n options = { ...options, windows: utils.isWindows() };\n }\n\n return pico(glob, options, returnState);\n}\n\nObject.assign(picomatch, pico);\nmodule.exports = picomatch;\n","import { defineCommand } from \"citty\";\nimport { mkdir, writeFile } from \"node:fs/promises\";\nimport { join, basename, resolve } from \"node:path\";\nimport { REQUIRED_SECTIONS } from \"@specdx/schema\";\n\nexport type Template = \"lightweight\" | \"bmad\" | \"api-first\" | \"quick\" | \"context\";\n\nexport interface ScaffoldOptions {\n projectName: string;\n template: Template;\n targetDir: string;\n}\n\nconst TEMPLATE_SPECS: Record<\n Template,\n Array<{ filename: string; type: keyof typeof REQUIRED_SECTIONS }>\n> = {\n lightweight: [\n { filename: \"prd.md\", type: \"prd\" },\n { filename: \"technical-design.md\", type: \"technical-design\" },\n ],\n bmad: [\n { filename: \"prd.md\", type: \"prd\" },\n { filename: \"technical-design.md\", type: \"technical-design\" },\n { filename: \"test-plan.md\", type: \"test-plan\" },\n ],\n \"api-first\": [\n { filename: \"technical-design.md\", type: \"technical-design\" },\n { filename: \"api-contract.md\", type: \"api-contract\" },\n { filename: \"test-plan.md\", type: \"test-plan\" },\n ],\n quick: [{ filename: \"quick-spec.md\", type: \"quick-spec\" }],\n context: [{ filename: \"project-context.md\", type: \"project-context\" }],\n};\n\nconst TEMPLATE_EXTRA_DIRS: Record<Template, string[]> = {\n lightweight: [],\n bmad: [\"specs/stories\", \"specs/adr\"],\n \"api-first\": [],\n quick: [],\n context: [],\n};\n\nfunction specIdFromFilename(filename: string): string {\n return filename.replace(/\\.md$/, \"\");\n}\n\nfunction specTitleFromType(type: string): string {\n return type\n .split(\"-\")\n .map((w) => w.charAt(0).toUpperCase() + w.slice(1))\n .join(\" \");\n}\n\nfunction buildSpecFile(\n filename: string,\n type: keyof typeof REQUIRED_SECTIONS,\n projectName: string,\n today: string,\n): string {\n const id = specIdFromFilename(filename);\n const title = `${specTitleFromType(type)} — ${projectName}`;\n const sections = REQUIRED_SECTIONS[type];\n\n const frontmatter = [\n \"---\",\n `id: ${id}`,\n `type: ${type}`,\n `title: \"${title}\"`,\n `status: draft`,\n `version: \"0.1\"`,\n `created: \"${today}\"`,\n `authors: [\"author\"]`,\n \"---\",\n ].join(\"\\n\");\n\n const body = sections.map((section) => `\\n## ${section}\\n\\n<!-- placeholder -->`).join(\"\\n\");\n\n return `${frontmatter}\\n${body}\\n`;\n}\n\nfunction buildConfigYaml(\n projectName: string,\n specs: Array<{ filename: string; type: string }>,\n): string {\n const specEntries = specs\n .map(({ filename, type }) => {\n const key = specIdFromFilename(filename);\n return ` ${key}:\\n path: specs/${filename}\\n type: ${type}`;\n })\n .join(\"\\n\");\n\n return (\n [`version: \"1.0\"`, `project:`, ` name: \"${projectName}\"`, `specs:`, specEntries].join(\"\\n\") +\n \"\\n\"\n );\n}\n\nexport async function scaffoldProject({\n projectName,\n template,\n targetDir,\n}: ScaffoldOptions): Promise<void> {\n if (!targetDir) {\n throw new TypeError(\"scaffoldProject requires `targetDir` — where to create the project.\");\n }\n const today = new Date().toISOString().slice(0, 10);\n const specsDir = join(targetDir, \"specs\");\n\n // Create specs/ directory\n await mkdir(specsDir, { recursive: true });\n\n // Create extra template dirs (e.g., bmad needs stories/ and adr/)\n for (const extraDir of TEMPLATE_EXTRA_DIRS[template]) {\n await mkdir(join(targetDir, extraDir), { recursive: true });\n }\n\n const specs = TEMPLATE_SPECS[template];\n\n // Write spec files\n for (const { filename, type } of specs) {\n const content = buildSpecFile(filename, type, projectName, today);\n await writeFile(join(specsDir, filename), content, \"utf-8\");\n }\n\n // Write spec.config.yaml\n const configContent = buildConfigYaml(projectName, specs);\n await writeFile(join(targetDir, \"spec.config.yaml\"), configContent, \"utf-8\");\n}\n\n/**\n * The project name to use when `--name` is absent: the target directory's own\n * name, resolved so that `.` becomes the current directory rather than a dot.\n */\nexport function defaultProjectName(dir: string): string {\n return basename(resolve(dir)) || \"my-project\";\n}\n\nexport default defineCommand({\n meta: {\n name: \"init\",\n description: \"Initialize a new specdx project with spec scaffolding\",\n },\n args: {\n name: {\n type: \"string\",\n description: \"Project name (default: the target directory's name)\",\n },\n template: {\n type: \"string\",\n description: \"Template to use (lightweight, bmad, api-first)\",\n default: \"lightweight\",\n },\n dir: {\n type: \"string\",\n description: \"Target directory\",\n default: \".\",\n },\n },\n async run({ args }) {\n const { template, dir } = args;\n const validTemplates: Template[] = [\"lightweight\", \"bmad\", \"api-first\", \"quick\", \"context\"];\n if (!validTemplates.includes(template as Template)) {\n console.error(`Unknown template: ${template}. Choose from: ${validTemplates.join(\", \")}`);\n process.exit(1);\n }\n\n // The first command anyone runs should not fail on a missing flag when the\n // answer is sitting in the path. `--name` still wins where they differ.\n const name = args.name || defaultProjectName(dir);\n\n console.log(`Scaffolding \"${name}\" with template \"${template}\" in ${dir}...`);\n await scaffoldProject({ projectName: name, template: template as Template, targetDir: dir });\n console.log(`Done! Project \"${name}\" scaffolded successfully.`);\n },\n});\n","/**\n * The `version` a `spec.config.yaml` is expected to declare.\n *\n * The field was accepted with any value at all, so `migrate` printed whatever\n * it read and then said \"no migration needed\" regardless -- a config claiming\n * `0.9` passed as readily as a current one. A version field nothing checks is\n * a field that cannot do its job when a real migration arrives.\n */\nexport const SUPPORTED_CONFIG_VERSION = \"1.0\";\n\nexport const SPEC_TYPES = [\n \"prd\",\n \"technical-design\",\n \"user-story\",\n \"test-plan\",\n \"adr\",\n \"api-contract\",\n \"epic\",\n \"quick-spec\",\n \"project-context\",\n] as const;\nexport type SpecType = (typeof SPEC_TYPES)[number];\n\nexport const SPEC_STATUSES = [\"draft\", \"review\", \"approved\", \"superseded\"] as const;\nexport type SpecStatus = (typeof SPEC_STATUSES)[number];\n\n/**\n * Every relationship kind a spec may declare in frontmatter `references`.\n * Single source of truth — `base-spec.json`'s enum is drift-tested against it.\n */\nexport const SPEC_RELATIONSHIPS = [\n \"implemented-by\",\n \"decomposed-into\",\n \"depends-on\",\n \"supersedes\",\n \"related-to\",\n] as const;\nexport type SpecRelationship = (typeof SPEC_RELATIONSHIPS)[number];\n\n/**\n * Which relationship kinds imply a build dependency, and in which direction.\n *\n * Structural kinds are deliberately absent: `decomposed-into` describes a\n * parent/child split and `supersedes` describes lineage — neither means the\n * target depends on the source (issue #13). Declared here rather than in\n * `@specdx/core` so the taxonomy is versioned with the schema it belongs to\n * (ADR: references/requires unification).\n */\nexport const DEPENDENCY_RELATIONSHIPS: Partial<\n Record<SpecRelationship, \"self-requires-target\" | \"target-requires-self\">\n> = {\n \"depends-on\": \"self-requires-target\",\n \"implemented-by\": \"target-requires-self\",\n};\n\nexport interface SpecReference {\n id: string;\n relationship: SpecRelationship;\n}\n\n/** A checkable implementation artifact declared by a spec (issue #15). */\nexport interface SpecArtifact {\n /** Project-root-relative file path that must exist. */\n path: string;\n /** Names that must be exported from the file. */\n exports?: string[];\n}\n\nexport interface BaseSpec {\n id: string;\n type: SpecType;\n title: string;\n status: SpecStatus;\n version: string;\n created: string;\n updated?: string;\n authors: string[];\n tags?: string[];\n references?: SpecReference[];\n artifacts?: SpecArtifact[];\n}\n\nexport interface PrdSpec extends BaseSpec {\n type: \"prd\";\n}\nexport interface TechnicalDesignSpec extends BaseSpec {\n type: \"technical-design\";\n}\nexport interface UserStorySpec extends BaseSpec {\n type: \"user-story\";\n story_id: string;\n priority: \"critical\" | \"high\" | \"medium\" | \"low\";\n estimate: string;\n}\nexport interface TestPlanSpec extends BaseSpec {\n type: \"test-plan\";\n}\nexport interface AdrSpec extends BaseSpec {\n type: \"adr\";\n}\nexport interface ApiContractSpec extends BaseSpec {\n type: \"api-contract\";\n}\n\nexport interface EpicSpec extends BaseSpec {\n type: \"epic\";\n epic_id: string;\n priority: \"critical\" | \"high\" | \"medium\" | \"low\";\n}\n\nexport interface QuickSpecSpec extends BaseSpec {\n type: \"quick-spec\";\n}\n\nexport interface ProjectContextSpec extends BaseSpec {\n type: \"project-context\";\n}\n\nexport type Spec =\n | PrdSpec\n | TechnicalDesignSpec\n | UserStorySpec\n | TestPlanSpec\n | AdrSpec\n | ApiContractSpec\n | EpicSpec\n | QuickSpecSpec\n | ProjectContextSpec;\n\nexport interface SpecEntry {\n path: string;\n type: SpecType;\n required?: boolean;\n requires?: string[];\n owner?: string;\n}\n\nexport interface PackCompressionConfig {\n strip_boilerplate?: boolean;\n stable_days?: number;\n collapse_resolved_adrs?: boolean;\n}\n\nexport interface PackConfig {\n max_tokens?: number;\n format?: \"xml\" | \"markdown\" | \"json\";\n compression?: PackCompressionConfig;\n boilerplate_sections?: string[];\n}\n\nexport interface SdxConfig {\n version: string;\n project?: { name?: string; description?: string };\n specs: Record<string, SpecEntry>;\n lint?: {\n extends?: string;\n rules?: Record<string, unknown>;\n ignore?: string[];\n };\n pack?: PackConfig;\n diff?: {\n baseline_ref?: string;\n staleness_threshold_days?: number;\n ignore_paths?: string[];\n };\n ci?: {\n block_on?: (\"error\" | \"warn\" | \"info\")[];\n post_comment?: boolean;\n update_badge?: boolean;\n trigger_paths?: string[];\n };\n check?: {\n framework?: \"auto\" | \"express\" | \"hono\" | \"nextjs\";\n routes_dir?: string;\n app_dir?: string;\n types_dir?: string;\n tests_dir?: string;\n ignore?: string[];\n };\n}\n","import type { SpecType } from \"./types.js\";\n\nexport const REQUIRED_SECTIONS: Record<SpecType, string[]> = {\n prd: [\"Problem Statement\", \"Goals\", \"Non-Goals\", \"Features\", \"Success Criteria\"],\n \"technical-design\": [\n \"Overview\",\n \"Architecture\",\n \"Data Model\",\n \"API Design\",\n \"Dependencies\",\n \"Risks\",\n \"Open Questions\",\n ],\n \"user-story\": [\"Description\", \"Acceptance Criteria\", \"Dependencies\", \"Notes\"],\n \"test-plan\": [\"Scope\", \"Test Cases\", \"Coverage Matrix\", \"Edge Cases\"],\n adr: [\"Context\", \"Decision\", \"Status\", \"Consequences\"],\n \"api-contract\": [\"Endpoints\", \"Request/Response Schemas\", \"Auth\", \"Error Codes\"],\n epic: [\"Overview\", \"Stories\", \"Acceptance Criteria\", \"Dependencies\"],\n \"quick-spec\": [\"Intent\", \"Boundaries\", \"Tasks\"],\n \"project-context\": [\"Technology Stack\", \"Critical Implementation Rules\", \"Coding Patterns\"],\n};\n","import { Ajv as AjvClass, type ErrorObject } from \"ajv\";\nimport { SPEC_TYPES, type SpecType } from \"./types.js\";\n\nimport baseSpecSchema from \"./schemas/base-spec.json\" with { type: \"json\" };\nimport configSchema from \"./schemas/config.json\" with { type: \"json\" };\nimport prdSchema from \"./schemas/prd.json\" with { type: \"json\" };\nimport technicalDesignSchema from \"./schemas/technical-design.json\" with { type: \"json\" };\nimport userStorySchema from \"./schemas/user-story.json\" with { type: \"json\" };\nimport testPlanSchema from \"./schemas/test-plan.json\" with { type: \"json\" };\nimport adrSchema from \"./schemas/adr.json\" with { type: \"json\" };\nimport apiContractSchema from \"./schemas/api-contract.json\" with { type: \"json\" };\nimport epicSchema from \"./schemas/epic.json\" with { type: \"json\" };\nimport quickSpecSchema from \"./schemas/quick-spec.json\" with { type: \"json\" };\nimport projectContextSchema from \"./schemas/project-context.json\" with { type: \"json\" };\n\n// addFormats is CJS-only; access via the namespace default at runtime\n// The type cast is needed because TypeScript's NodeNext resolution exposes\n// the CJS module as a namespace without a callable default signature.\nimport * as addFormatsNs from \"ajv-formats\";\ntype AddFormatsPlugin = (ajv: AjvClass, formats?: unknown) => AjvClass;\nconst addFormats = ((addFormatsNs as unknown as { default?: AddFormatsPlugin }).default ??\n (addFormatsNs as unknown as AddFormatsPlugin)) as AddFormatsPlugin;\n\nexport interface ValidationResult {\n valid: boolean;\n errors: ErrorObject[] | null;\n}\n\n// The JSON schemas duplicate the spec-type enum for editor and schema-store\n// consumers. At runtime SPEC_TYPES is the single source of truth: the enums are\n// overwritten before compilation so the JSON copies can never drift from the\n// TypeScript types (see issue #2 — a stale enum shipped in 0.4.0-alpha.2).\nconst runtimeBaseSpecSchema = structuredClone(baseSpecSchema);\nruntimeBaseSpecSchema.properties.type.enum = [...SPEC_TYPES];\nconst runtimeConfigSchema = structuredClone(configSchema);\nruntimeConfigSchema.properties.specs.additionalProperties.properties.type.enum = [...SPEC_TYPES];\n\nconst ajv = new AjvClass({ allErrors: true, strict: true });\naddFormats(ajv, [\"date\"]);\najv.addSchema(runtimeBaseSpecSchema);\n\nconst specValidators: Record<string, ReturnType<typeof ajv.compile>> = {\n prd: ajv.compile(prdSchema),\n \"technical-design\": ajv.compile(technicalDesignSchema),\n \"user-story\": ajv.compile(userStorySchema),\n \"test-plan\": ajv.compile(testPlanSchema),\n adr: ajv.compile(adrSchema),\n \"api-contract\": ajv.compile(apiContractSchema),\n epic: ajv.compile(epicSchema),\n \"quick-spec\": ajv.compile(quickSpecSchema),\n \"project-context\": ajv.compile(projectContextSchema),\n};\n\nconst configValidator = ajv.compile(runtimeConfigSchema);\n\nexport function validateSpec(type: SpecType, data: Record<string, unknown>): ValidationResult {\n const validate = specValidators[type];\n if (!validate) {\n return { valid: false, errors: [{ message: `Unknown spec type: \"${type}\"` } as ErrorObject] };\n }\n const valid = validate(data);\n return { valid: !!valid, errors: valid ? null : (validate.errors ?? null) };\n}\n\nexport function validateConfig(data: Record<string, unknown>): ValidationResult {\n const valid = configValidator(data);\n return { valid: !!valid, errors: valid ? null : (configValidator.errors ?? null) };\n}\n","{\n \"$id\": \"base-spec\",\n \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n \"type\": \"object\",\n \"properties\": {\n \"id\": {\n \"type\": \"string\",\n \"minLength\": 1\n },\n \"type\": {\n \"type\": \"string\",\n \"enum\": [\n \"prd\",\n \"technical-design\",\n \"user-story\",\n \"test-plan\",\n \"adr\",\n \"api-contract\",\n \"epic\",\n \"quick-spec\",\n \"project-context\"\n ]\n },\n \"title\": {\n \"type\": \"string\",\n \"minLength\": 1\n },\n \"status\": {\n \"type\": \"string\",\n \"enum\": [\n \"draft\",\n \"review\",\n \"approved\",\n \"superseded\"\n ]\n },\n \"version\": {\n \"type\": \"string\"\n },\n \"created\": {\n \"type\": \"string\",\n \"format\": \"date\"\n },\n \"updated\": {\n \"type\": \"string\",\n \"format\": \"date\"\n },\n \"authors\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\"\n },\n \"minItems\": 1\n },\n \"tags\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\"\n },\n \"default\": []\n },\n \"references\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"object\",\n \"properties\": {\n \"id\": {\n \"type\": \"string\"\n },\n \"relationship\": {\n \"type\": \"string\",\n \"enum\": [\n \"implemented-by\",\n \"decomposed-into\",\n \"depends-on\",\n \"supersedes\",\n \"related-to\"\n ]\n }\n },\n \"required\": [\n \"id\",\n \"relationship\"\n ],\n \"additionalProperties\": false\n },\n \"default\": []\n },\n \"artifacts\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"object\",\n \"properties\": {\n \"path\": {\n \"type\": \"string\",\n \"minLength\": 1\n },\n \"exports\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\",\n \"minLength\": 1\n }\n }\n },\n \"required\": [\n \"path\"\n ],\n \"additionalProperties\": false\n },\n \"default\": []\n }\n },\n \"required\": [\n \"id\",\n \"type\",\n \"title\",\n \"status\",\n \"version\",\n \"created\",\n \"authors\"\n ],\n \"additionalProperties\": true\n}\n","{\n \"$id\": \"specdx-config\",\n \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n \"type\": \"object\",\n \"properties\": {\n \"version\": { \"type\": \"string\" },\n \"project\": {\n \"type\": \"object\",\n \"properties\": {\n \"name\": { \"type\": \"string\" },\n \"description\": { \"type\": \"string\" }\n },\n \"additionalProperties\": false\n },\n \"specs\": {\n \"type\": \"object\",\n \"additionalProperties\": {\n \"type\": \"object\",\n \"properties\": {\n \"path\": { \"type\": \"string\" },\n \"type\": { \"type\": \"string\", \"enum\": [\"prd\", \"technical-design\", \"user-story\", \"test-plan\", \"adr\", \"api-contract\", \"epic\", \"quick-spec\", \"project-context\"] },\n \"required\": { \"type\": \"boolean\", \"default\": false },\n \"requires\": { \"type\": \"array\", \"items\": { \"type\": \"string\" } },\n \"owner\": { \"type\": \"string\" }\n },\n \"required\": [\"path\", \"type\"],\n \"additionalProperties\": false\n }\n },\n \"lint\": {\n \"type\": \"object\",\n \"properties\": {\n \"extends\": { \"type\": \"string\" },\n \"rules\": { \"type\": \"object\" },\n \"ignore\": { \"type\": \"array\", \"items\": { \"type\": \"string\" } }\n },\n \"additionalProperties\": false\n },\n \"pack\": {\n \"type\": \"object\",\n \"properties\": {\n \"max_tokens\": { \"type\": \"integer\", \"minimum\": 1 },\n \"format\": { \"type\": \"string\", \"enum\": [\"xml\", \"markdown\", \"json\"] },\n \"compression\": {\n \"type\": \"object\",\n \"properties\": {\n \"strip_boilerplate\": { \"type\": \"boolean\" },\n \"stable_days\": { \"type\": \"integer\", \"minimum\": 0 },\n \"collapse_resolved_adrs\": { \"type\": \"boolean\" }\n },\n \"additionalProperties\": false\n },\n \"boilerplate_sections\": {\n \"type\": \"array\",\n \"items\": { \"type\": \"string\" }\n }\n },\n \"additionalProperties\": false\n },\n \"diff\": {\n \"type\": \"object\",\n \"properties\": {\n \"baseline_ref\": { \"type\": \"string\", \"default\": \"main\" },\n \"staleness_threshold_days\": { \"type\": \"integer\", \"minimum\": 1, \"default\": 14 },\n \"ignore_paths\": { \"type\": \"array\", \"items\": { \"type\": \"string\" } }\n },\n \"additionalProperties\": false\n },\n \"ci\": {\n \"type\": \"object\",\n \"properties\": {\n \"block_on\": {\n \"type\": \"array\",\n \"items\": { \"type\": \"string\", \"enum\": [\"error\", \"warn\", \"info\"] }\n },\n \"post_comment\": { \"type\": \"boolean\", \"default\": true },\n \"update_badge\": { \"type\": \"boolean\", \"default\": true },\n \"trigger_paths\": {\n \"type\": \"array\",\n \"items\": { \"type\": \"string\" }\n }\n },\n \"additionalProperties\": false\n },\n \"check\": {\n \"type\": \"object\",\n \"properties\": {\n \"framework\": {\n \"type\": \"string\",\n \"enum\": [\"auto\", \"express\", \"hono\", \"nextjs\"]\n },\n \"routes_dir\": { \"type\": \"string\" },\n \"app_dir\": { \"type\": \"string\" },\n \"types_dir\": { \"type\": \"string\" },\n \"tests_dir\": { \"type\": \"string\" },\n \"ignore\": {\n \"type\": \"array\",\n \"items\": { \"type\": \"string\" }\n }\n },\n \"additionalProperties\": false\n }\n },\n \"required\": [\"version\", \"specs\"],\n \"additionalProperties\": false\n}\n","{\n \"$id\": \"prd\",\n \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n \"allOf\": [\n { \"$ref\": \"base-spec\" },\n { \"type\": \"object\", \"properties\": { \"type\": { \"const\": \"prd\" } }, \"required\": [\"type\"] }\n ]\n}\n","{\n \"$id\": \"technical-design\",\n \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n \"allOf\": [\n { \"$ref\": \"base-spec\" },\n { \"type\": \"object\", \"properties\": { \"type\": { \"const\": \"technical-design\" } }, \"required\": [\"type\"] }\n ]\n}\n","{\n \"$id\": \"user-story\",\n \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n \"allOf\": [\n { \"$ref\": \"base-spec\" },\n {\n \"type\": \"object\",\n \"properties\": {\n \"type\": { \"const\": \"user-story\" },\n \"story_id\": { \"type\": \"string\", \"minLength\": 1 },\n \"priority\": { \"type\": \"string\", \"enum\": [\"critical\", \"high\", \"medium\", \"low\"] },\n \"estimate\": { \"type\": \"string\" }\n },\n \"required\": [\"type\", \"story_id\", \"priority\", \"estimate\"]\n }\n ]\n}\n","{\n \"$id\": \"test-plan\",\n \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n \"allOf\": [\n { \"$ref\": \"base-spec\" },\n { \"type\": \"object\", \"properties\": { \"type\": { \"const\": \"test-plan\" } }, \"required\": [\"type\"] }\n ]\n}\n","{\n \"$id\": \"adr\",\n \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n \"allOf\": [\n { \"$ref\": \"base-spec\" },\n { \"type\": \"object\", \"properties\": { \"type\": { \"const\": \"adr\" } }, \"required\": [\"type\"] }\n ]\n}\n","{\n \"$id\": \"api-contract\",\n \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n \"allOf\": [\n { \"$ref\": \"base-spec\" },\n { \"type\": \"object\", \"properties\": { \"type\": { \"const\": \"api-contract\" } }, \"required\": [\"type\"] }\n ]\n}\n","{\n \"$id\": \"epic\",\n \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n \"allOf\": [\n { \"$ref\": \"base-spec\" },\n {\n \"type\": \"object\",\n \"properties\": {\n \"type\": { \"const\": \"epic\" },\n \"epic_id\": { \"type\": \"string\", \"minLength\": 1 },\n \"priority\": { \"type\": \"string\", \"enum\": [\"critical\", \"high\", \"medium\", \"low\"] }\n },\n \"required\": [\"type\", \"epic_id\", \"priority\"]\n }\n ]\n}\n","{\n \"$id\": \"quick-spec\",\n \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n \"allOf\": [\n { \"$ref\": \"base-spec\" },\n {\n \"type\": \"object\",\n \"properties\": {\n \"type\": { \"const\": \"quick-spec\" }\n },\n \"required\": [\"type\"]\n }\n ]\n}\n","{\n \"$id\": \"project-context\",\n \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n \"allOf\": [\n { \"$ref\": \"base-spec\" },\n {\n \"type\": \"object\",\n \"properties\": {\n \"type\": { \"const\": \"project-context\" }\n },\n \"required\": [\"type\"]\n }\n ]\n}\n","import { defineCommand } from \"citty\";\nimport { loadConfig, parseSpec, resolveGlob, buildGraph, createLogger } from \"@specdx/core\";\nimport { createLintEngine, getPreset, type LintResults } from \"@specdx/lint\";\nimport type { ParsedSpec } from \"@specdx/core\";\nimport { sharedArgs, resolveFormat } from \"../../shared-args.js\";\nimport { createOutput } from \"../../output.js\";\nimport { formatPretty } from \"../../formatters/pretty.js\";\nimport { formatJson } from \"../../formatters/json.js\";\nimport { formatGithub } from \"../../formatters/github.js\";\n\nconst FORMATS = [\"pretty\", \"json\", \"github\"] as const;\n\nexport interface RunLintOptions {\n configDir: string;\n specPath?: string;\n preset?: \"minimal\" | \"recommended\" | \"strict\";\n}\n\n/** Lint results plus whether anything was actually linted (vacuous-pass audit). */\nexport interface RunLintResults extends LintResults {\n /** Number of spec files linted. Named for what it counts, not \"count\". */\n specFiles: number;\n /** False when no specs resolved — \"no diagnostics\" is then not a pass. */\n assessed: boolean;\n}\n\nexport async function runLint(options: RunLintOptions): Promise<RunLintResults> {\n // A JS caller omitting the option otherwise dies as ERR_INVALID_ARG_TYPE\n // deep inside path.join, with no mention of what was missing.\n if (!options.configDir) {\n throw new TypeError(\"runLint requires `configDir` — the directory holding spec.config.yaml.\");\n }\n const config = await loadConfig(undefined, options.configDir);\n const preset = options.preset ?? config.lint?.extends ?? \"recommended\";\n const rules = getPreset(preset);\n\n // Always parse the full suite so cross-reference rules have complete\n // context; a single-file lint filters the *diagnostics*, not the suite.\n const specs: ParsedSpec[] = [];\n for (const [, entry] of Object.entries(config.specs)) {\n const files = await resolveGlob(entry.path, options.configDir);\n for (const file of files) {\n specs.push(await parseSpec(file));\n }\n }\n\n let graph;\n let graphError: string | undefined;\n try {\n graph = buildGraph(config);\n } catch (err) {\n graphError = (err as Error).message;\n }\n\n const engine = createLintEngine({ rules, config, graph });\n const results = engine.lint(specs);\n\n if (options.specPath) {\n const specPath = options.specPath;\n results.diagnostics = results.diagnostics.filter((d) => d.filePath.includes(specPath));\n results.hasErrors = results.diagnostics.some((d) => d.severity === \"error\");\n results.hasWarnings = results.diagnostics.some((d) => d.severity === \"warn\");\n }\n\n if (graphError) {\n results.diagnostics.push({\n ruleId: \"structure/no-circular-deps\",\n severity: \"error\",\n message: graphError,\n filePath: \"spec.config.yaml\",\n });\n results.hasErrors = true;\n }\n\n return { ...results, specFiles: specs.length, assessed: specs.length > 0 };\n}\n\nexport default defineCommand({\n meta: { name: \"lint\", description: \"Lint all specs in the suite\" },\n args: {\n ...sharedArgs(FORMATS),\n fix: { type: \"boolean\", description: \"Auto-fix issues where possible\" },\n path: { type: \"positional\", description: \"Lint a specific spec file\", required: false },\n preset: { type: \"string\", description: \"Lint preset (minimal, recommended, strict)\" },\n },\n async run({ args }) {\n const logger = createLogger({ quiet: args.quiet, verbose: args.verbose });\n const output = createOutput({ quiet: args.quiet });\n\n const format = resolveFormat(args.format, FORMATS);\n if (!format.ok) {\n console.error(`\\n ✗ ${format.message}\\n`);\n process.exit(1);\n }\n\n if (args.fix) {\n logger.info(\"No auto-fixable issues supported yet.\");\n }\n\n try {\n const results = await runLint({\n configDir: process.cwd(),\n specPath: args.path,\n preset: args.preset as \"minimal\" | \"recommended\" | \"strict\" | undefined,\n });\n\n const formatter =\n format.format === \"json\"\n ? formatJson\n : format.format === \"github\"\n ? formatGithub\n : formatPretty;\n // \"No diagnostics\" over an empty suite is not a pass (vacuous-pass audit)\n if (!results.assessed) {\n console.error(\n \"\\n ⚠ No specs found — nothing was linted. Check the spec paths in spec.config.yaml.\\n\",\n );\n process.exit(3);\n }\n\n const rendered = formatter(results.diagnostics);\n // A clean pretty run is chrome; diagnostics and machine formats are not.\n if (format.format === \"pretty\" && results.diagnostics.length === 0) {\n output.info(rendered);\n } else {\n output.out(rendered);\n }\n\n if (results.hasErrors) process.exit(1);\n } catch (err) {\n console.error(`\\n ✗ ${(err as Error).message}\\n`);\n process.exit(1);\n }\n },\n});\n","import { readFile } from \"node:fs/promises\";\nimport { join, dirname } from \"node:path\";\nimport { parse as parseYaml } from \"yaml\";\nimport { validateConfig, type SdxConfig } from \"@specdx/schema\";\n\nexport class ConfigError extends Error {\n constructor(\n message: string,\n public readonly errors?: unknown[],\n ) {\n super(message);\n this.name = \"ConfigError\";\n }\n}\n\nconst CONFIG_FILENAME = \"spec.config.yaml\";\n\nexport async function loadConfig(filePath?: string, searchFrom?: string): Promise<SdxConfig> {\n const resolvedPath = filePath ?? (await findConfig(searchFrom ?? process.cwd()));\n if (!resolvedPath) {\n throw new ConfigError(`No ${CONFIG_FILENAME} found. Run 'specdx init' to create one.`);\n }\n\n let raw: string;\n try {\n raw = await readFile(resolvedPath, \"utf-8\");\n } catch {\n throw new ConfigError(`Cannot read config file: ${resolvedPath}`);\n }\n\n let data: Record<string, unknown>;\n try {\n data = parseYaml(raw) as Record<string, unknown>;\n } catch (err) {\n throw new ConfigError(`Invalid YAML in ${resolvedPath}: ${(err as Error).message}`);\n }\n\n const result = validateConfig(data);\n if (!result.valid) {\n throw new ConfigError(`Invalid config in ${resolvedPath}`, result.errors ?? undefined);\n }\n\n return data as unknown as SdxConfig;\n}\n\nasync function findConfig(from: string): Promise<string | undefined> {\n let dir = from;\n while (true) {\n const candidate = join(dir, CONFIG_FILENAME);\n try {\n await readFile(candidate, \"utf-8\");\n return candidate;\n } catch {\n const parent = dirname(dir);\n if (parent === dir) return undefined;\n dir = parent;\n }\n }\n}\n","import { readFile } from \"node:fs/promises\";\nimport { extname } from \"node:path\";\nimport * as grayMatterNs from \"gray-matter\";\nimport { parse as parseYaml } from \"yaml\";\nimport { unified } from \"unified\";\nimport remarkParse from \"remark-parse\";\nimport { visit } from \"unist-util-visit\";\nimport { validateSpec, type ValidationResult } from \"@specdx/schema\";\nimport type { BaseSpec, SpecType } from \"@specdx/schema\";\nimport { countTokens } from \"./tokens.js\";\n\n// gray-matter is CJS — its callable default is exposed via .default in an ESM context\ntype GrayMatterFn = (input: string) => { data: Record<string, unknown>; content: string };\nconst matter = ((grayMatterNs as unknown as { default?: GrayMatterFn }).default ??\n (grayMatterNs as unknown as GrayMatterFn)) as GrayMatterFn;\n\nexport class ParseError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"ParseError\";\n }\n}\n\nexport interface ParsedSection {\n heading: string;\n content: string;\n tokens: number;\n}\n\nexport interface ParsedSpec {\n filePath: string;\n frontmatter: BaseSpec & Record<string, unknown>;\n content: string;\n sections: string[];\n parsedSections: ParsedSection[];\n valid: boolean;\n validationErrors: ValidationResult[\"errors\"];\n}\n\nexport async function parseSpec(filePath: string): Promise<ParsedSpec> {\n let raw: string;\n try {\n raw = await readFile(filePath, \"utf-8\");\n } catch {\n throw new ParseError(`Cannot read spec file: ${filePath}`);\n }\n\n return parseSpecFromString(raw, filePath);\n}\n\nexport function parseSpecFromString(content: string, filePath: string): Promise<ParsedSpec> {\n const ext = extname(filePath).toLowerCase();\n if (ext === \".yaml\" || ext === \".yml\") {\n return Promise.resolve(parseYamlSpec(filePath, content));\n }\n return Promise.resolve(parseMarkdownSpec(filePath, content));\n}\n\nfunction parseMarkdownSpec(filePath: string, raw: string): ParsedSpec {\n const { data, content } = matter(raw);\n const parsedSections = extractParsedSections(content);\n const sections = parsedSections.map((s) => s.heading).filter(Boolean);\n const frontmatter = data as BaseSpec & Record<string, unknown>;\n const specType = frontmatter.type as SpecType | undefined;\n\n let valid = false;\n let validationErrors: ValidationResult[\"errors\"] = null;\n if (specType) {\n const result = validateSpec(specType, data);\n valid = result.valid;\n validationErrors = result.errors;\n }\n\n return { filePath, frontmatter, content, sections, parsedSections, valid, validationErrors };\n}\n\nfunction parseYamlSpec(filePath: string, raw: string): ParsedSpec {\n let data: Record<string, unknown>;\n try {\n data = parseYaml(raw) as Record<string, unknown>;\n } catch (err) {\n throw new ParseError(`Invalid YAML in ${filePath}: ${(err as Error).message}`);\n }\n\n const frontmatter = data as BaseSpec & Record<string, unknown>;\n const specType = frontmatter.type as SpecType | undefined;\n\n let valid = false;\n let validationErrors: ValidationResult[\"errors\"] = null;\n if (specType) {\n const result = validateSpec(specType, data);\n valid = result.valid;\n validationErrors = result.errors;\n }\n\n return {\n filePath,\n frontmatter,\n content: \"\",\n sections: [],\n parsedSections: [],\n valid,\n validationErrors,\n };\n}\n\nfunction extractParsedSections(markdown: string): ParsedSection[] {\n const tree = unified().use(remarkParse).parse(markdown);\n\n const h2s: { heading: string; startOffset: number; endOffset: number }[] = [];\n\n visit(tree, \"heading\", (node) => {\n if (node.depth === 2) {\n const text = (node.children as Array<{ type: string; value?: string }>)\n .filter((c) => c.type === \"text\")\n .map((c) => c.value ?? \"\")\n .join(\"\");\n h2s.push({\n heading: text,\n startOffset: node.position!.start.offset as number,\n endOffset: node.position!.end.offset as number,\n });\n }\n });\n\n const sections: ParsedSection[] = [];\n\n // Preamble: content before first H2\n const firstH2 = h2s[0];\n const firstOffset = firstH2 ? firstH2.startOffset : markdown.length;\n const preamble = markdown.slice(0, firstOffset).trim();\n if (preamble) {\n sections.push({ heading: \"\", content: preamble, tokens: countTokens(preamble) });\n }\n\n // Each H2 section: content AFTER the heading line, up to the next H2 (or end)\n for (let i = 0; i < h2s.length; i++) {\n const current = h2s[i]!;\n const next = h2s[i + 1];\n const end = next ? next.startOffset : markdown.length;\n const content = markdown.slice(current.endOffset, end).trim();\n sections.push({\n heading: current.heading,\n content,\n tokens: countTokens(content),\n });\n }\n\n return sections;\n}\n","import { encodingForModel } from \"js-tiktoken\";\n\nlet encoder: ReturnType<typeof encodingForModel> | undefined;\n\nfunction getEncoder() {\n if (!encoder) encoder = encodingForModel(\"gpt-4o\");\n return encoder;\n}\n\nexport function countTokens(text: string): number {\n if (!text) return 0;\n return getEncoder().encode(text).length;\n}\n","import type { SdxConfig } from \"@specdx/schema\";\nimport { DEPENDENCY_RELATIONSHIPS } from \"@specdx/schema\";\n\nexport class GraphError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"GraphError\";\n }\n}\n\nexport interface Edge {\n from: string;\n to: string;\n}\n\nexport interface DependencyGraph {\n nodes: string[];\n edges: Edge[];\n topologicalSort(): string[];\n getDownstream(nodeId: string): string[];\n getUpstream(nodeId: string): string[];\n}\n\nexport function buildGraph(config: SdxConfig): DependencyGraph {\n const specNames = Object.keys(config.specs);\n const adjacency = new Map<string, string[]>();\n const reverseAdj = new Map<string, string[]>();\n const edges: Edge[] = [];\n\n for (const name of specNames) {\n adjacency.set(name, []);\n reverseAdj.set(name, []);\n }\n\n for (const [name, entry] of Object.entries(config.specs)) {\n if (!entry.requires) continue;\n for (const dep of entry.requires) {\n if (!adjacency.has(dep)) {\n throw new GraphError(\n `Spec \"${name}\" requires \"${dep}\", which does not exist in the config.`,\n );\n }\n adjacency.get(dep)!.push(name);\n reverseAdj.get(name)!.push(dep);\n edges.push({ from: dep, to: name });\n }\n }\n\n // Kahn's algorithm for cycle detection + topological sort\n const inDegree = new Map<string, number>();\n for (const name of specNames) inDegree.set(name, reverseAdj.get(name)!.length);\n\n const queue: string[] = [];\n for (const [name, degree] of inDegree) {\n if (degree === 0) queue.push(name);\n }\n\n const sorted: string[] = [];\n while (queue.length > 0) {\n const node = queue.shift()!;\n sorted.push(node);\n for (const neighbor of adjacency.get(node)!) {\n const newDegree = inDegree.get(neighbor)! - 1;\n inDegree.set(neighbor, newDegree);\n if (newDegree === 0) queue.push(neighbor);\n }\n }\n\n if (sorted.length !== specNames.length) {\n const remaining = specNames.filter((n) => !sorted.includes(n));\n throw new GraphError(`Circular dependency detected involving: ${remaining.join(\", \")}`);\n }\n\n return {\n nodes: specNames,\n edges,\n topologicalSort: () => [...sorted],\n getDownstream(nodeId: string): string[] {\n const visited = new Set<string>();\n const stack = [nodeId];\n while (stack.length > 0) {\n const current = stack.pop()!;\n for (const neighbor of adjacency.get(current) ?? []) {\n if (!visited.has(neighbor)) {\n visited.add(neighbor);\n stack.push(neighbor);\n }\n }\n }\n return [...visited];\n },\n getUpstream(nodeId: string): string[] {\n const visited = new Set<string>();\n const stack = [nodeId];\n while (stack.length > 0) {\n const current = stack.pop()!;\n for (const dep of reverseAdj.get(current) ?? []) {\n if (!visited.has(dep)) {\n visited.add(dep);\n stack.push(dep);\n }\n }\n }\n return [...visited];\n },\n };\n}\n\n/** A relationship edge declared in a spec's frontmatter `references`. */\nexport interface ReferenceEdge {\n fromId: string;\n toId: string;\n relationship: string;\n}\n\n// The dependency-implying taxonomy lives in @specdx/schema so it is versioned\n// with the schema it describes, rather than hardcoded here (ADR:\n// references/requires unification).\n\n/**\n * Collect relationship edges declared in spec frontmatter `references` fields.\n * Edges point from the declaring spec's id to the referenced spec's id.\n */\nexport function collectReferenceEdges(\n specs: { frontmatter: Record<string, unknown> }[],\n): ReferenceEdge[] {\n const edges: ReferenceEdge[] = [];\n for (const spec of specs) {\n const fromId = spec.frontmatter.id;\n if (typeof fromId !== \"string\") continue;\n const refs = spec.frontmatter.references;\n if (!Array.isArray(refs)) continue;\n for (const ref of refs) {\n if (ref && typeof ref === \"object\" && \"id\" in ref) {\n const r = ref as { id: unknown; relationship?: unknown };\n if (typeof r.id === \"string\") {\n edges.push({\n fromId,\n toId: r.id,\n relationship: typeof r.relationship === \"string\" ? r.relationship : \"related-to\",\n });\n }\n }\n }\n }\n return edges;\n}\n\n/**\n * Find dependency-implying frontmatter references that the config-level\n * `requires` graph does not reflect. `idToEntry` maps spec frontmatter ids to\n * config entry keys. References within the same entry (e.g. story-to-story\n * under one glob) and references to unmapped ids are skipped — reference\n * existence itself is the `structure/valid-references` lint rule's concern.\n */\nexport interface UnreflectedReference {\n edge: ReferenceEdge;\n requiringEntry: string;\n requiredEntry: string;\n /** True when adding the suggested requires edge would create a cycle. */\n createsCycle: boolean;\n}\n\nexport function findUnreflectedReferences(\n referenceEdges: ReferenceEdge[],\n idToEntry: Map<string, string>,\n graph: DependencyGraph,\n): UnreflectedReference[] {\n const configEdges = new Set(graph.edges.map((e) => `${e.from}→${e.to}`));\n const missing: UnreflectedReference[] = [];\n\n for (const edge of referenceEdges) {\n const direction = DEPENDENCY_RELATIONSHIPS[edge.relationship as never];\n if (!direction) continue;\n\n const selfEntry = idToEntry.get(edge.fromId);\n const targetEntry = idToEntry.get(edge.toId);\n if (!selfEntry || !targetEntry || selfEntry === targetEntry) continue;\n\n const requiringEntry = direction === \"self-requires-target\" ? selfEntry : targetEntry;\n const requiredEntry = direction === \"self-requires-target\" ? targetEntry : selfEntry;\n\n // Config edges point dependency → dependent\n if (!configEdges.has(`${requiredEntry}→${requiringEntry}`)) {\n // The suggested edge closes a cycle when the required entry is already\n // downstream of the requiring one (issue #13) — never recommend it.\n const createsCycle = graph.getDownstream(requiringEntry).includes(requiredEntry);\n missing.push({ edge, requiringEntry, requiredEntry, createsCycle });\n }\n }\n\n return missing;\n}\n","import type { SdxConfig } from \"@specdx/schema\";\nimport { DEPENDENCY_RELATIONSHIPS } from \"@specdx/schema\";\n\n/** Where a relation edge was declared. */\nexport type RelationSource = \"requires\" | \"references\" | \"both\";\n\n/** A dependency edge in **spec id** space, pointing upstream → downstream. */\nexport interface RelationEdge {\n /** Spec id of the dependency. */\n from: string;\n /** Spec id of the dependent. */\n to: string;\n /** Which declaration(s) produced this edge. */\n source: RelationSource;\n}\n\n/**\n * Answers \"what is upstream / downstream of this spec?\" in spec id space.\n *\n * specdx declares relationships two ways: config `requires` (keyed by config\n * entry, glob-aware, cheap) and frontmatter `references` (keyed by spec id,\n * typed). Consumers used to read one or the other, so the same question got\n * different answers — `freshness/staleness-check` saw only references, while\n * impact analysis saw only the config graph. This resolver unions both at\n * query time so every consumer agrees, without changing which source owns\n * graph topology (ADR: references/requires unification, Option B).\n */\nexport interface RelationResolver {\n /** All dependency edges, in spec id space, deduplicated. */\n edges: RelationEdge[];\n /** Spec ids this spec depends on, transitively. */\n getUpstream(specId: string): string[];\n /** Spec ids that depend on this spec, transitively. */\n getDownstream(specId: string): string[];\n}\n\ninterface SpecLike {\n frontmatter: Record<string, unknown>;\n}\n\n/** Map each config entry key to the spec ids its path resolved to. */\nfunction mapEntriesToIds(\n config: SdxConfig,\n specsByEntry: Map<string, SpecLike[]>,\n): Map<string, string[]> {\n const entryIds = new Map<string, string[]>();\n for (const key of Object.keys(config.specs)) {\n const ids: string[] = [];\n for (const spec of specsByEntry.get(key) ?? []) {\n const id = spec.frontmatter.id;\n if (typeof id === \"string\") ids.push(id);\n }\n entryIds.set(key, ids);\n }\n return entryIds;\n}\n\n/** Every spec id present, regardless of which entry it came from. */\nfunction collectKnownIds(specsByEntry: Map<string, SpecLike[]>): Set<string> {\n const ids = new Set<string>();\n for (const specs of specsByEntry.values()) {\n for (const spec of specs) {\n const id = spec.frontmatter.id;\n if (typeof id === \"string\") ids.add(id);\n }\n }\n return ids;\n}\n\nfunction walk(specId: string, adjacency: Map<string, string[]>): string[] {\n const visited = new Set<string>();\n const stack = [specId];\n while (stack.length > 0) {\n const current = stack.pop()!;\n for (const next of adjacency.get(current) ?? []) {\n if (!visited.has(next)) {\n visited.add(next);\n stack.push(next);\n }\n }\n }\n visited.delete(specId);\n return [...visited];\n}\n\n/**\n * Build a resolver from config `requires` and dependency-implying frontmatter\n * `references`.\n *\n * A glob entry is one config entry but many spec ids, so one `requires` edge\n * between entries expands to the cross-product of their spec ids. Structural\n * reference kinds (`decomposed-into`, `supersedes`, `related-to`) are not\n * dependency-implying and are excluded — see DEPENDENCY_RELATIONSHIPS.\n *\n * @param config - Spec config. When undefined, only frontmatter references\n * contribute edges — useful for callers that have specs but no config.\n * @param specsByEntry - Parsed specs grouped by the config entry key they resolved from.\n */\nexport function buildRelationResolver(\n config: SdxConfig | undefined,\n specsByEntry: Map<string, SpecLike[]>,\n): RelationResolver {\n const entryIds = config ? mapEntriesToIds(config, specsByEntry) : new Map<string, string[]>();\n const knownIds = collectKnownIds(specsByEntry);\n\n // key \"from→to\" -> source, so a relation declared both ways is one edge\n const edgeSources = new Map<string, RelationSource>();\n const addEdge = (from: string, to: string, source: \"requires\" | \"references\"): void => {\n if (from === to) return;\n const key = `${from}\u0000${to}`;\n const existing = edgeSources.get(key);\n if (!existing) {\n edgeSources.set(key, source);\n } else if (existing !== source) {\n edgeSources.set(key, \"both\");\n }\n };\n\n // 1. Config requires: entry-level edges expand across the entries' spec ids\n for (const [key, entry] of Object.entries(config?.specs ?? {})) {\n const requires = (entry as { requires?: string[] }).requires ?? [];\n for (const dep of requires) {\n for (const from of entryIds.get(dep) ?? []) {\n for (const to of entryIds.get(key) ?? []) {\n addEdge(from, to, \"requires\");\n }\n }\n }\n }\n\n // 2. Frontmatter references, already in spec id space\n for (const specs of specsByEntry.values()) {\n for (const spec of specs) {\n const selfId = spec.frontmatter.id;\n if (typeof selfId !== \"string\") continue;\n const refs = spec.frontmatter.references;\n if (!Array.isArray(refs)) continue;\n\n for (const ref of refs) {\n if (!ref || typeof ref !== \"object\") continue;\n const { id: targetId, relationship } = ref as { id?: unknown; relationship?: unknown };\n if (typeof targetId !== \"string\" || typeof relationship !== \"string\") continue;\n // Referencing a spec outside the suite is valid-references' concern.\n if (!knownIds.has(targetId)) continue;\n\n const direction = DEPENDENCY_RELATIONSHIPS[relationship as never];\n if (direction === \"self-requires-target\") {\n addEdge(targetId, selfId, \"references\");\n } else if (direction === \"target-requires-self\") {\n addEdge(selfId, targetId, \"references\");\n }\n }\n }\n }\n\n const edges: RelationEdge[] = [];\n const downstreamAdj = new Map<string, string[]>();\n const upstreamAdj = new Map<string, string[]>();\n\n for (const [key, source] of edgeSources) {\n const [from, to] = key.split(\"\u0000\") as [string, string];\n edges.push({ from, to, source });\n downstreamAdj.set(from, [...(downstreamAdj.get(from) ?? []), to]);\n upstreamAdj.set(to, [...(upstreamAdj.get(to) ?? []), from]);\n }\n\n return {\n edges,\n getUpstream: (specId) => walk(specId, upstreamAdj),\n getDownstream: (specId) => walk(specId, downstreamAdj),\n };\n}\n","import { glob } from \"tinyglobby\";\nimport { join, isAbsolute } from \"node:path\";\n\nexport async function resolveGlob(pattern: string, baseDir: string): Promise<string[]> {\n const absolutePattern = isAbsolute(pattern) ? pattern : join(baseDir, pattern);\n return glob([absolutePattern], { absolute: true });\n}\n","import { createConsola, type ConsolaInstance } from \"consola\";\n\nexport type LogLevel = \"debug\" | \"info\" | \"warn\" | \"error\";\n\nexport interface LoggerOptions {\n quiet?: boolean;\n verbose?: boolean;\n}\n\nexport interface Logger extends ConsolaInstance {\n level: number;\n}\n\nexport function createLogger(options?: LoggerOptions): Logger {\n let level = 3; // info\n if (options?.quiet) level = 1; // only errors\n if (options?.verbose) level = 4; // debug\n return createConsola({ level }) as Logger;\n}\n","import { readFile } from \"node:fs/promises\";\nimport { resolve, isAbsolute } from \"node:path\";\nimport { ConfigError } from \"./config.js\";\n\nconst BUILTINS = [\"minimal\", \"recommended\", \"strict\"];\n\n/**\n * Resolve a preset name to its config content.\n * Returns null for built-in presets (handled by @specdx/lint).\n * Resolves local file paths and npm package names.\n */\nexport async function resolvePreset(\n name: string,\n cwd = process.cwd(),\n): Promise<Record<string, unknown> | null> {\n if (BUILTINS.includes(name)) {\n return null;\n }\n\n // Try local file path\n const localPath = isAbsolute(name) ? name : resolve(cwd, name);\n try {\n const content = await readFile(localPath, \"utf-8\");\n const { default: yaml } = await import(\"yaml\");\n return yaml.parse(content) as Record<string, unknown>;\n } catch {\n // Not a local file, try npm\n }\n\n // Try npm package\n try {\n const mod = (await import(name)) as { default?: Record<string, unknown> };\n return (mod.default ?? mod) as Record<string, unknown>;\n } catch {\n throw new ConfigError(`Could not resolve preset \"${name}\" as a local file or npm package`);\n }\n}\n","import type { ParsedSpec, DependencyGraph } from \"@specdx/core\";\nimport type { SdxConfig } from \"@specdx/schema\";\nimport type { LintRule, LintResults, Diagnostic } from \"./types.js\";\n\nexport interface LintEngineOptions {\n rules: LintRule[];\n config?: SdxConfig;\n graph?: DependencyGraph;\n}\n\nexport interface LintEngine {\n lint(specs: ParsedSpec[]): LintResults;\n}\n\nexport function createLintEngine(options: LintEngineOptions): LintEngine {\n return {\n lint(specs: ParsedSpec[]): LintResults {\n const diagnostics: Diagnostic[] = [];\n for (const spec of specs) {\n for (const rule of options.rules) {\n const results = rule.run({\n spec,\n allSpecs: specs,\n config: options.config,\n graph: options.graph,\n });\n // The rule object's `severity` is the authority, not the severity a\n // rule happens to write into the diagnostic it returns.\n //\n // Every built-in rule emits exactly one severity -- its own -- but ten\n // of them hardcoded it as a literal in the diagnostic. Presets rewrite\n // `rule.severity`, so nothing downstream read what `strict` set, and\n // `--preset strict` produced output byte-identical to `recommended` on\n // the CLI, in `extends:`, in the Action's `preset` input and in\n // `runLint({ preset })`. Stamping it here is what makes a preset mean\n // anything.\n for (const diagnostic of results) {\n diagnostics.push({ ...diagnostic, severity: rule.severity });\n }\n }\n }\n return {\n diagnostics,\n hasErrors: diagnostics.some((d) => d.severity === \"error\"),\n hasWarnings: diagnostics.some((d) => d.severity === \"warn\"),\n };\n },\n };\n}\n","import type { LintRule } from \"../types.js\";\n\n/**\n * The shape of an ajv error, described structurally.\n *\n * Typed here rather than imported so the lint package does not take a\n * dependency on ajv for a single type.\n */\ninterface ValidationError {\n instancePath?: string;\n message?: string;\n params?: Record<string, unknown>;\n}\n\n/** `/references/0/relationship` -> `references[0].relationship`. */\nfunction readablePath(instancePath: string): string {\n return instancePath\n .split(\"/\")\n .filter(Boolean)\n .map((segment) => (/^\\d+$/.test(segment) ? `[${segment}]` : `.${segment}`))\n .join(\"\")\n .replace(/^\\./, \"\");\n}\n\n/**\n * Turn one ajv error into something a spec author can act on.\n *\n * ajv only names the offending field inside `message` for `required`\n * violations. For `enum`, `const` and `type` the field lives in `instancePath`\n * and the acceptable values in `params`, so a bare `err.message` reads\n * \"must be equal to one of the allowed values\" and identifies nothing -- which\n * is what every `references:` entry produced.\n */\nexport function describeValidationError(err: ValidationError): string {\n const path = readablePath(err.instancePath ?? \"\");\n const allowed = (err.params as { allowedValues?: unknown[] } | undefined)?.allowedValues;\n\n let detail = err.message ?? JSON.stringify(err);\n if (Array.isArray(allowed) && allowed.length > 0) {\n detail += `: ${allowed.map((v) => JSON.stringify(v)).join(\", \")}`;\n }\n\n return path ? `${path} ${detail}` : detail;\n}\n\nexport const validFrontmatterRule: LintRule = {\n id: \"structure/valid-frontmatter\",\n description: \"Frontmatter matches the schema for the declared spec type\",\n severity: \"error\",\n run(context) {\n if (context.spec.valid) return [];\n const errors = context.spec.validationErrors ?? [];\n return errors.map((err) => ({\n ruleId: \"structure/valid-frontmatter\",\n severity: \"error\" as const,\n message: `Invalid frontmatter: ${describeValidationError(err)}`,\n filePath: context.spec.filePath,\n }));\n },\n};\n","import type { LintRule } from \"../types.js\";\nimport { REQUIRED_SECTIONS } from \"@specdx/schema\";\nimport type { SpecType } from \"@specdx/schema\";\n\nexport const requiredSectionsRule: LintRule = {\n id: \"structure/required-sections\",\n description: \"Spec body contains all required sections for its type\",\n severity: \"error\",\n run(context) {\n // Skip YAML specs (no markdown body)\n const ext = context.spec.filePath.split(\".\").pop()?.toLowerCase();\n if (ext === \"yaml\" || ext === \"yml\") return [];\n\n const specType = context.spec.frontmatter.type as SpecType;\n const required = REQUIRED_SECTIONS[specType];\n if (!required) return [];\n\n const missing = required.filter((s) => !context.spec.sections.includes(s));\n return missing.map((section) => ({\n ruleId: \"structure/required-sections\",\n severity: \"error\" as const,\n message: `Missing required section: \"${section}\"`,\n filePath: context.spec.filePath,\n section,\n }));\n },\n};\n","import type { LintRule } from \"../types.js\";\n\nexport const validReferencesRule: LintRule = {\n id: \"structure/valid-references\",\n description: \"All references in frontmatter point to specs that exist in the suite\",\n severity: \"error\",\n run(context) {\n const refs = context.spec.frontmatter.references;\n if (!refs || refs.length === 0) return [];\n const allIds = new Set(context.allSpecs.map((s) => s.frontmatter.id));\n return refs\n .filter((ref) => !allIds.has(ref.id))\n .map((ref) => ({\n ruleId: \"structure/valid-references\",\n severity: \"error\" as const,\n message: `Reference \"${ref.id}\" does not match any spec in the suite`,\n filePath: context.spec.filePath,\n }));\n },\n};\n","import type { LintRule } from \"../types.js\";\n\nexport const noCircularDepsRule: LintRule = {\n id: \"structure/no-circular-deps\",\n description: \"The dependency graph has no cycles\",\n severity: \"error\",\n run() {\n // Cycle detection happens in buildGraph() — if graph construction succeeds, it's acyclic.\n // GraphErrors are surfaced as diagnostics by the lint command, not by this rule.\n return [];\n },\n};\n","import type { LintRule } from \"../types.js\";\nimport type { ParsedSpec } from \"@specdx/core\";\n\n/** Words carrying no signal about what a feature is. */\nconst STOPWORDS = new Set([\n \"a\",\n \"an\",\n \"the\",\n \"and\",\n \"or\",\n \"of\",\n \"to\",\n \"for\",\n \"with\",\n \"its\",\n \"it\",\n \"in\",\n \"on\",\n \"at\",\n \"by\",\n \"from\",\n \"into\",\n \"every\",\n \"each\",\n \"that\",\n \"this\",\n \"be\",\n \"is\",\n \"are\",\n \"as\",\n \"can\",\n \"will\",\n \"must\",\n \"so\",\n \"their\",\n \"them\",\n \"when\",\n \"which\",\n \"who\",\n]);\n\n/** Share of a feature's words a story must echo to count as covering it. */\nconst OVERLAP_THRESHOLD = 0.5;\n\n/** Lower bar for a story that explicitly references the PRD. */\nconst REFERENCED_THRESHOLD = 0.34;\n\nfunction tokenise(text: string): Set<string> {\n const words = text\n .toLowerCase()\n .replace(/[^a-z0-9\\s-]/g, \" \")\n .split(/\\s+/)\n .filter((w) => w.length > 2 && !STOPWORDS.has(w))\n // Crude singularisation, so \"actions\" matches \"action\".\n .map((w) => (w.length > 3 && w.endsWith(\"s\") && !w.endsWith(\"ss\") ? w.slice(0, -1) : w));\n return new Set(words);\n}\n\nfunction extractFeatureSection(content: string): string | null {\n // Scanned line by line rather than with one regex: `$` and `\\Z` behave\n // differently enough across multiline modes to make the regex form a trap.\n const lines = content.split(\"\\n\");\n const start = lines.findIndex((l) => /^##\\s+Features\\s*$/.test(l.trim()));\n if (start === -1) return null;\n const body: string[] = [];\n for (let i = start + 1; i < lines.length; i++) {\n if (/^##\\s/.test(lines[i]!)) break;\n body.push(lines[i]!);\n }\n return body.join(\"\\n\");\n}\n\n/**\n * Feature descriptions from a PRD's Features section.\n *\n * Previously only `- **F1**: text` was recognised, so a PRD written any other\n * way parsed to zero features and the rule passed vacuously -- which `ready`\n * then reported as \"all features have stories\" over an empty set.\n */\nexport function parseFeatures(content: string): string[] {\n return parseFeatureEntries(content).map((f) => f.text);\n}\n\n/** A PRD feature, with its `F<N>` number when the author gave it one. */\nexport interface FeatureEntry {\n /** The feature description, with any ID prefix removed. */\n text: string;\n /** The `N` from `**F<N>**:`, when present. */\n num?: string;\n}\n\n/**\n * The single source of truth for what counts as a feature in a PRD.\n *\n * `generate story` used to carry its own regex requiring `**F<N>**:`, so on a\n * PRD without those IDs the lint rule reported three features and the generator\n * reported none -- two commands in the same suite contradicting each other over\n * one file. Anything that needs to know what a PRD's features are calls this.\n */\nexport function parseFeatureEntries(content: string): FeatureEntry[] {\n const section = extractFeatureSection(content);\n if (section === null) return [];\n\n /** `**F1**:`, `F1:`, `F1 -` — an optional feature ID prefix. */\n const ID_PREFIX = /^\\*{0,2}F(\\d+)\\*{0,2}\\s*[:.-]\\s*/i;\n\n const features: FeatureEntry[] = [];\n for (const rawLine of section.split(\"\\n\")) {\n const line = rawLine.trim();\n if (!line) continue;\n\n const bullet = /^[-*]\\s+(.*)$/.exec(line);\n // A bullet is a feature whether or not it carries an ID. A non-bullet line\n // counts only when it does, so ordinary prose in the section is not\n // mistaken for a feature list.\n const text = bullet ? (bullet[1] ?? \"\").trim() : ID_PREFIX.test(line) ? line : \"\";\n if (!text) continue;\n\n const idMatch = ID_PREFIX.exec(text);\n const stripped = text.replace(ID_PREFIX, \"\").trim();\n if (stripped) features.push({ text: stripped, num: idMatch?.[1] });\n }\n return features;\n}\n\nfunction overlap(featureTokens: Set<string>, storyTokens: Set<string>): number {\n if (featureTokens.size === 0) return 0;\n let shared = 0;\n for (const token of featureTokens) if (storyTokens.has(token)) shared++;\n return shared / featureTokens.size;\n}\n\nfunction referencesSpec(story: ParsedSpec, specId: unknown): boolean {\n const refs = story.frontmatter.references;\n if (!Array.isArray(refs)) return false;\n return refs.some((r) => (r as { id?: unknown })?.id === specId);\n}\n\n/**\n * Features from `features` that no story in `stories` appears to cover.\n *\n * Exported so the linter and `generate story` share one definition of\n * \"covered\". They had two, which is why the rule warned about features that\n * had stories while the generator re-stubbed features that already had them.\n */\nexport function uncoveredFeatures(\n features: string[],\n stories: ParsedSpec[],\n prdId: unknown,\n): string[] {\n const scored = stories.map((story) => ({\n tokens: tokenise(`${String(story.frontmatter.title ?? \"\")} ${story.content}`),\n threshold: referencesSpec(story, prdId) ? REFERENCED_THRESHOLD : OVERLAP_THRESHOLD,\n }));\n\n const tokenised = features.map(tokenise);\n\n return features.filter((_feature, i) => {\n const featureTokens = tokenised[i]!;\n // What makes *this* feature different from its siblings. Share of words\n // alone is not enough: \"Export the payroll report as PDF\" and \"Export the\n // invoice report as CSV\" agree on half their words, so a story covering one\n // was read as covering both -- and `ready` then asserted that every feature\n // had a story while one plainly had none. A story only covers a feature if\n // it also mentions something that sets that feature apart.\n const distinctive = distinctiveTokens(featureTokens, tokenised, i);\n return !scored.some(\n (s) =>\n overlap(featureTokens, s.tokens) >= s.threshold &&\n covers(distinctive, featureTokens, s.tokens),\n );\n });\n}\n\n/**\n * Whether a story picks up more than half of what sets a feature apart from its\n * siblings.\n *\n * One distinctive word is not enough on its own. \"List customers for the\n * finance console\" is set apart by *finance* and *console*, and a story about\n * amending invoices that opens \"as a member of finance\" hits one of the two —\n * enough to be waved through by a \"matches something distinctive\" test, and\n * plainly not a story about the finance console.\n *\n * Two cases hand the decision back to the overlap threshold alone, because in\n * both of them distinctiveness carries no information:\n *\n * - Nothing is distinctive. Two features written in near-identical words are\n * genuinely indistinguishable to a word-overlap rule.\n * - Everything is distinctive. No sibling shares a word, so no sibling's\n * vocabulary inflated the overlap score in the first place — and demanding\n * half of a long feature description would reject the short, accurate story\n * titles this rule exists to accept.\n */\nfunction covers(\n distinctive: Set<string>,\n featureTokens: Set<string>,\n storyTokens: Set<string>,\n): boolean {\n if (distinctive.size === 0 || distinctive.size === featureTokens.size) return true;\n let matched = 0;\n for (const token of distinctive) if (storyTokens.has(token)) matched++;\n return matched > distinctive.size / 2;\n}\n\n/**\n * The tokens of `features[index]` that no sibling feature uses.\n */\nfunction distinctiveTokens(\n featureTokens: Set<string>,\n allFeatureTokens: Set<string>[],\n index: number,\n): Set<string> {\n const distinctive = new Set(featureTokens);\n for (let i = 0; i < allFeatureTokens.length; i++) {\n if (i === index) continue;\n for (const token of allFeatureTokens[i]!) distinctive.delete(token);\n }\n return distinctive;\n}\n\nexport const storyCoverageRule: LintRule = {\n id: \"completeness/story-coverage\",\n description: \"Every feature listed in a PRD has at least one corresponding user story\",\n severity: \"warn\",\n run(context) {\n if (context.spec.frontmatter.type !== \"prd\") return [];\n\n const features = parseFeatures(context.spec.content);\n if (features.length === 0) return [];\n\n const stories = context.allSpecs.filter((s) => s.frontmatter.type === \"user-story\");\n\n return uncoveredFeatures(features, stories, context.spec.frontmatter.id).map((feature) => ({\n ruleId: \"completeness/story-coverage\",\n severity: \"warn\" as const,\n message: `Feature \"${feature}\" has no corresponding user story`,\n filePath: context.spec.filePath,\n }));\n },\n};\n","import { buildRelationResolver } from \"@specdx/core\";\nimport type { ParsedSpec } from \"@specdx/core\";\nimport type { SdxConfig } from \"@specdx/schema\";\nimport type { LintRule } from \"../types.js\";\n\n/**\n * Group specs by the config entry whose glob they came from, so config\n * `requires` edges can be mapped into spec id space. Matching is by the entry\n * path's directory prefix, which is enough for the resolver: an id that maps\n * to no entry simply contributes no `requires` edges.\n */\nfunction groupByEntry(config: SdxConfig, specs: ParsedSpec[]): Map<string, ParsedSpec[]> {\n const byEntry = new Map<string, ParsedSpec[]>();\n for (const key of Object.keys(config.specs)) byEntry.set(key, []);\n\n for (const spec of specs) {\n let bestKey: string | undefined;\n let bestLen = -1;\n for (const [key, entry] of Object.entries(config.specs)) {\n const prefix = entry.path.split(\"*\")[0] ?? \"\";\n const normalized = spec.filePath.replace(/\\\\/g, \"/\");\n if (normalized.includes(prefix) && prefix.length > bestLen) {\n bestKey = key;\n bestLen = prefix.length;\n }\n }\n if (bestKey) byEntry.get(bestKey)!.push(spec);\n }\n return byEntry;\n}\n\nfunction lastUpdated(spec: ParsedSpec): string {\n return (\n (spec.frontmatter.updated as string | undefined) ?? (spec.frontmatter.created as string) ?? \"\"\n );\n}\n\nexport const stalenessCheckRule: LintRule = {\n id: \"freshness/staleness-check\",\n description: \"Warns if a spec hasn't been updated since its upstream dependency changed\",\n severity: \"warn\",\n run(context) {\n const specId = context.spec.frontmatter.id;\n if (typeof specId !== \"string\") return [];\n\n const specUpdated = lastUpdated(context.spec);\n if (!specUpdated) return [];\n const specDate = new Date(specUpdated);\n\n // Upstream comes from config `requires` and frontmatter `references`\n // unioned, so a suite declaring dependencies either way gets the same\n // answer (ADR: references/requires unification).\n const byEntry = context.config\n ? groupByEntry(context.config, context.allSpecs)\n : new Map([[\"\", context.allSpecs]]);\n const relations = buildRelationResolver(context.config, byEntry);\n const upstreamIds = relations.getUpstream(specId);\n\n const diagnostics = [];\n for (const upstreamId of upstreamIds) {\n const upstream = context.allSpecs.find((s) => s.frontmatter.id === upstreamId);\n if (!upstream) continue;\n const upstreamUpdated = lastUpdated(upstream);\n if (!upstreamUpdated) continue;\n\n if (new Date(upstreamUpdated) > specDate) {\n diagnostics.push({\n ruleId: \"freshness/staleness-check\",\n severity: \"warn\" as const,\n message: `Potentially stale: upstream \"${upstreamId}\" was updated on ${upstreamUpdated}, but this spec was last updated on ${specUpdated}`,\n filePath: context.spec.filePath,\n });\n }\n }\n return diagnostics;\n },\n};\n","import type { LintRule } from \"../types.js\";\n\nconst DEFAULT_VAGUE_PATTERNS = [\n \"as appropriate\",\n \"handle edge cases\",\n \"as needed\",\n \"etc\\\\.\",\n \"TBD\",\n \"TODO\",\n \"and so on\",\n \"various\",\n \"somehow\",\n \"straightforward\",\n \"obviously\",\n \"simply\",\n \"just need to\",\n];\n\nexport const noVagueLanguageRule: LintRule = {\n id: \"clarity/no-vague-language\",\n description: \"Flags known ambiguous phrases\",\n severity: \"warn\",\n run(context) {\n if (!context.spec.content) return [];\n const diagnostics = [];\n for (const pattern of DEFAULT_VAGUE_PATTERNS) {\n const regex = new RegExp(`\\\\b${pattern}`, \"gi\");\n let match;\n while ((match = regex.exec(context.spec.content)) !== null) {\n diagnostics.push({\n ruleId: \"clarity/no-vague-language\",\n severity: \"warn\" as const,\n message: `Vague language: \"${match[0]}\"`,\n filePath: context.spec.filePath,\n });\n }\n }\n return diagnostics;\n },\n};\n","import type { LintRule } from \"../types.js\";\n\nexport const singleProjectContextRule: LintRule = {\n id: \"structure/single-project-context\",\n description: \"Only one project-context spec should exist per suite\",\n severity: \"warn\",\n run(context) {\n if (context.spec.frontmatter.type !== \"project-context\") return [];\n\n const contextSpecs = context.allSpecs.filter((s) => s.frontmatter.type === \"project-context\");\n\n if (contextSpecs.length > 1) {\n return [\n {\n ruleId: \"structure/single-project-context\",\n severity: \"warn\" as const,\n message: `Multiple project-context specs found (${contextSpecs.length}). Only one should exist per suite.`,\n filePath: context.spec.filePath,\n },\n ];\n }\n\n return [];\n },\n};\n","import type { LintRule } from \"../types.js\";\n\nfunction normalizeCompound(term: string): string {\n // Split camelCase: \"UserProfile\" → \"user profile\"\n // Split hyphens/underscores: \"user-profile\" → \"user profile\"\n return term\n .replace(/([a-z])([A-Z])/g, \"$1 $2\")\n .replace(/[-_]/g, \" \")\n .toLowerCase()\n .trim();\n}\n\nfunction extractCompoundTerms(content: string): string[] {\n const terms: string[] = [];\n\n // Extract camelCase words (e.g., UserProfile, userProfile)\n const camelCaseRegex = /\\b[a-zA-Z]*[a-z][A-Z][a-zA-Z]*\\b/g;\n let match;\n while ((match = camelCaseRegex.exec(content)) !== null) {\n terms.push(match[0]);\n }\n\n // Extract hyphenated words (e.g., user-profile, my-component)\n const hyphenatedRegex = /\\b[a-z][a-z0-9]*(?:-[a-z][a-z0-9]*)+\\b/g;\n while ((match = hyphenatedRegex.exec(content)) !== null) {\n terms.push(match[0]);\n }\n\n return terms;\n}\n\nexport const terminologyRule: LintRule = {\n id: \"consistency/terminology\",\n description:\n \"Detects terminology drift (e.g., user-profile vs UserProfile vs user profile) across specs\",\n severity: \"warn\",\n run(context) {\n // Only run on the first spec to avoid duplicate diagnostics\n if (context.spec !== context.allSpecs[0]) return [];\n\n // Build a map: normalized form → Set of original forms found across all specs\n const termMap = new Map<string, Set<string>>();\n\n for (const spec of context.allSpecs) {\n if (!spec.content) continue;\n const terms = extractCompoundTerms(spec.content);\n for (const term of terms) {\n const normalized = normalizeCompound(term);\n // Only track multi-word normalized forms (skip single words)\n if (!normalized.includes(\" \")) continue;\n if (!termMap.has(normalized)) {\n termMap.set(normalized, new Set());\n }\n termMap.get(normalized)!.add(term);\n }\n }\n\n const diagnostics = [];\n\n for (const [normalized, variants] of termMap) {\n if (variants.size >= 2) {\n const variantList = [...variants].join(\", \");\n diagnostics.push({\n ruleId: \"consistency/terminology\",\n severity: \"warn\" as const,\n message: `Inconsistent terminology for \"${normalized}\": found variants [${variantList}]. Standardize terminology across specs.`,\n filePath: context.spec.filePath,\n });\n }\n }\n\n return diagnostics;\n },\n};\n","import type { LintRule } from \"../types.js\";\n\nconst EDGE_CASE_KEYWORDS = [\n \"error\",\n \"invalid\",\n \"empty\",\n \"timeout\",\n \"fails\",\n \"failure\",\n \"boundary\",\n \"edge case\",\n \"null\",\n \"undefined\",\n \"reject\",\n \"unauthorized\",\n \"forbidden\",\n \"missing\",\n \"malformed\",\n \"overflow\",\n \"duplicate\",\n \"graceful\",\n \"fall back\",\n \"fallback\",\n \"crash\",\n \"nonexistent\",\n \"corrupt\",\n // Vocabulary that names a failure without using any of the words above.\n \"conflict\",\n \"denied\",\n \"expired\",\n \"not found\",\n \"retry\",\n \"rate limit\",\n \"unavailable\",\n \"unprocessable\",\n];\n\n/**\n * Any 4xx or 5xx status code counts as naming an error path.\n *\n * The list above held `404` and `500` and no other code, so a story whose only\n * error case was a 409 read as having no error handling at all -- changing that\n * one token to 404 silenced the warning with nothing else altered. Enumerating\n * codes was always going to be arbitrary; matching the class is not.\n */\nconst ERROR_STATUS_CODE = /\\b[45]\\d{2}\\b/;\n\n/** The section a test plan is required to carry, and where its cases belong. */\nconst EDGE_CASE_SECTION = \"edge cases\";\n\n/** Bodies that say \"nothing has been written here yet\". */\nconst PLACEHOLDER_BODIES = /^(todo|tbd|fixme|n\\/a|na|none|xxx|\\.{2,}|-|\\*)$/i;\n\n/** Bodies that answer the question with \"there aren't any\", which is not coverage. */\nconst DISCLAIMED_BODIES = /^(none|no|nothing|n\\/a)\\b[\\s\\S]{0,40}$/i;\n\n/** Strip HTML comments, list bullets and separators to expose the real body. */\nfunction meaningfulContent(content: string): string {\n return content\n .replace(/<!--[\\s\\S]*?-->/g, \"\")\n .split(\"\\n\")\n .map((line) => line.replace(/^\\s*[-*+]\\s+/, \"\").trim())\n .filter((line) => line.length > 0 && !/^-{3,}$/.test(line))\n .join(\"\\n\")\n .trim();\n}\n\nexport const edgeCaseCoverageRule: LintRule = {\n id: \"completeness/edge-case-coverage\",\n description: \"Flag user stories or test plans that don't mention error states or edge cases\",\n severity: \"warn\",\n run(context) {\n const type = context.spec.frontmatter.type as string;\n if (type !== \"user-story\" && type !== \"test-plan\") return [];\n\n // A test plan is *required* to carry an `## Edge Cases` heading, so scanning\n // the whole document for the words \"edge case\" matched the scaffolding and\n // nothing else -- the rule could never fire on the half of its scope that\n // has a dedicated home for the answer. Judge that section's body instead.\n const section = context.spec.parsedSections.find(\n (s) => s.heading.trim().toLowerCase() === EDGE_CASE_SECTION,\n );\n if (type === \"test-plan\" && section) {\n const body = meaningfulContent(section.content);\n const written =\n body !== \"\" && !PLACEHOLDER_BODIES.test(body) && !DISCLAIMED_BODIES.test(body);\n if (written) return [];\n\n return [\n {\n ruleId: \"completeness/edge-case-coverage\",\n severity: \"warn\" as const,\n message: `The \"${section.heading}\" section lists no cases — describe the boundary conditions and failure modes this plan covers, or the plan asserts only the happy path.`,\n filePath: context.spec.filePath,\n section: section.heading,\n },\n ];\n }\n\n // No dedicated section (a user story, or a test plan missing the heading —\n // `structure/required-sections` owns that): judge the document as a whole.\n const content = context.spec.content.toLowerCase();\n const hasEdgeCases =\n EDGE_CASE_KEYWORDS.some((kw) => content.includes(kw)) || ERROR_STATUS_CODE.test(content);\n\n if (hasEdgeCases) return [];\n\n return [\n {\n ruleId: \"completeness/edge-case-coverage\",\n severity: \"warn\" as const,\n message:\n \"No error states or edge cases mentioned. Consider adding error handling, boundary conditions, or failure mode scenarios.\",\n filePath: context.spec.filePath,\n },\n ];\n },\n};\n","import type { LintRule } from \"../types.js\";\n\nexport const namingConventionsRule: LintRule = {\n id: \"consistency/naming-conventions\",\n description: \"Enforce consistent naming conventions across specs\",\n severity: \"warn\",\n run(context) {\n const { spec } = context;\n const type = spec.frontmatter.type as string;\n const diagnostics = [];\n\n if (type === \"prd\") {\n // Split content into sections and find the Features section\n const sectionParts = spec.content.split(/^(?=## )/m);\n const featuresSection = sectionParts.find((p) => /^## Features\\b/.test(p));\n if (featuresSection) {\n const bullets = featuresSection.match(/^- .+$/gm) ?? [];\n for (const bullet of bullets) {\n if (bullet.match(/^- \\*\\*F\\d+\\*\\*:/) === null && bullet.trim().length > 2) {\n diagnostics.push({\n ruleId: \"consistency/naming-conventions\",\n severity: \"warn\" as const,\n message: `PRD feature missing feature ID pattern (**F<N>**:): \"${bullet.slice(0, 60)}\"`,\n filePath: spec.filePath,\n });\n }\n }\n }\n }\n\n if (type === \"user-story\") {\n const id = spec.frontmatter.id as string;\n if (!id.startsWith(\"story-\")) {\n diagnostics.push({\n ruleId: \"consistency/naming-conventions\",\n severity: \"warn\" as const,\n message: `User story ID \"${id}\" should start with \"story-\" (e.g., \"story-${id}\")`,\n filePath: spec.filePath,\n });\n }\n }\n\n if (type === \"api-contract\") {\n // Check endpoints for camelCase path segments\n const endpointRe = /^###\\s+(GET|POST|PUT|PATCH|DELETE)\\s+(\\S+)/gm;\n let match;\n while ((match = endpointRe.exec(spec.content)) !== null) {\n const path = match[2]!;\n if (/\\/[a-z]+[A-Z]/.test(path)) {\n diagnostics.push({\n ruleId: \"consistency/naming-conventions\",\n severity: \"warn\" as const,\n message: `Endpoint path \"${path}\" uses camelCase — use kebab-case instead (e.g., \"${path.replace(/([a-z])([A-Z])/g, \"$1-$2\").toLowerCase()}\")`,\n filePath: spec.filePath,\n });\n }\n }\n }\n\n return diagnostics;\n },\n};\n","import type { LintRule } from \"../types.js\";\n\nconst STOPWORDS = new Set([\"the\", \"and\", \"for\", \"with\", \"from\", \"that\", \"this\", \"into\", \"via\"]);\n\nfunction extractThreats(content: string): string[] {\n // Split into sections at each ## heading, then filter for Threats/Security\n const parts = content.split(/^(?=## )/m);\n const threats: string[] = [];\n for (const part of parts) {\n if (!/^##\\s+(Threats|Security)\\b/i.test(part)) continue;\n const bullets = part.match(/^- .+$/gm) ?? [];\n threats.push(...bullets.map((b) => b.slice(2).trim()));\n }\n return threats;\n}\n\nfunction extractKeyTerms(text: string): string[] {\n return text\n .toLowerCase()\n .split(/\\W+/)\n .filter((w) => w.length > 3)\n .filter((w) => !STOPWORDS.has(w));\n}\n\nexport const threatCoverageRule: LintRule = {\n id: \"security/threat-coverage\",\n description: \"Technical design specs must address threats identified in other specs\",\n severity: \"warn\",\n run(context) {\n if (context.spec.frontmatter.type !== \"technical-design\") return [];\n\n const allThreats: string[] = [];\n for (const spec of context.allSpecs) {\n if (spec.filePath === context.spec.filePath) continue;\n allThreats.push(...extractThreats(spec.content));\n }\n\n if (allThreats.length === 0) return [];\n\n const techContent = context.spec.content.toLowerCase();\n const diagnostics = [];\n\n for (const threat of allThreats) {\n const keyTerms = extractKeyTerms(threat);\n const covered = keyTerms.some((term) => techContent.includes(term));\n if (!covered) {\n diagnostics.push({\n ruleId: \"security/threat-coverage\",\n severity: \"warn\" as const,\n message: `Threat not addressed in technical design: \"${threat}\". Ensure the design covers this threat.`,\n filePath: context.spec.filePath,\n });\n }\n }\n\n return diagnostics;\n },\n};\n","import type { LintRule } from \"../types.js\";\n\nexport const ambiguityScoreAiRule: LintRule = {\n id: \"clarity/ambiguity-score-ai\",\n description: \"AI-powered ambiguity detection (requires ANTHROPIC_API_KEY)\",\n severity: \"info\",\n run(context) {\n if (!process.env[\"ANTHROPIC_API_KEY\"]) return [];\n\n return [\n {\n ruleId: \"clarity/ambiguity-score-ai\",\n severity: \"info\" as const,\n message:\n \"AI ambiguity analysis available — run `specdx check --ai` for LLM-powered ambiguity detection\",\n filePath: context.spec.filePath,\n },\n ];\n },\n};\n","import type { LintRule } from \"../types.js\";\n\n/**\n * Bodies that say \"nothing has been written here yet\".\n *\n * Matched against the whole section body, never as a substring: prose that\n * mentions a TODO is real content, a body that *is* \"TODO\" is not.\n */\nconst PLACEHOLDER_BODIES = /^(todo|tbd|fixme|n\\/a|na|none|xxx|\\.{2,}|-|\\*)$/i;\n\n/** Strip HTML comments, list bullets and separators to expose the real body. */\nfunction meaningfulContent(content: string): string {\n return content\n .replace(/<!--[\\s\\S]*?-->/g, \"\")\n .split(\"\\n\")\n .map((line) => line.replace(/^\\s*[-*+]\\s+/, \"\").trim())\n .filter((line) => line.length > 0 && !/^-{3,}$/.test(line))\n .join(\"\\n\")\n .trim();\n}\n\n/**\n * Flags sections that exist only as scaffolding.\n *\n * `structure/required-sections` checks that a heading is present, never that\n * anything was written under it. Without this rule a freshly scaffolded suite\n * of `<!-- placeholder -->` stubs lints clean, reports healthy, and is declared\n * ready for implementation -- the vacuous-pass failure mode, reached on a new\n * user's first command.\n *\n * Warning rather than error: an untouched scaffold should be visibly incomplete\n * without failing the very first `specdx lint` a user runs. `ready` enforces\n * the harder gate.\n */\nexport const noPlaceholderSectionsRule: LintRule = {\n id: \"completeness/no-placeholder-sections\",\n description: \"Spec sections contain content, not scaffolding placeholders\",\n severity: \"warn\",\n run(context) {\n return (\n context.spec.parsedSections\n // The preamble carries no heading and is not a section a user must fill.\n .filter((section) => section.heading !== \"\")\n .filter((section) => {\n const body = meaningfulContent(section.content);\n return body === \"\" || PLACEHOLDER_BODIES.test(body);\n })\n .map((section) => ({\n ruleId: \"completeness/no-placeholder-sections\",\n severity: \"warn\" as const,\n message: `Section \"${section.heading}\" is still a placeholder — write its content or remove the section`,\n filePath: context.spec.filePath,\n section: section.heading,\n }))\n );\n },\n};\n","import { basename } from \"node:path\";\nimport type { LintRule } from \"../types.js\";\n\n/**\n * A spec's frontmatter `id` must match the key it is registered under.\n *\n * When they disagree, nothing used to say so. `validate` passed, because the\n * config itself is well-formed and the file exists. `lint` reported dangling\n * references -- but blamed every spec that referenced the id, none of which was\n * at fault. And `graph` listed nodes by config key while drawing edges by\n * frontmatter id, so it rendered a node with no edges beside edges from a node\n * that did not exist.\n *\n * One diagnostic on the spec that actually diverged replaces all of that.\n *\n * A warning rather than an error: both names resolve, in different places --\n * frontmatter `references` match the id, config `requires` match the key -- so\n * a suite that keeps them apart still works. What it cannot do is produce a\n * coherent graph, or a useful message when a reference goes stale.\n */\nexport const idMatchesConfigKeyRule: LintRule = {\n id: \"structure/id-matches-config-key\",\n description: \"A spec's frontmatter id should match the key it is registered under in the config\",\n severity: \"warn\",\n run(context) {\n const { spec, config } = context;\n if (!config) return [];\n\n const id = spec.frontmatter.id;\n if (typeof id !== \"string\" || id.length === 0) return [];\n\n // Find the entry this file was loaded from. Paths may be globs, so match on\n // the filename the config points at rather than re-resolving every glob.\n const specFile = basename(spec.filePath);\n const candidates = Object.entries(config.specs).filter(([, entry]) => {\n const target = basename(entry.path);\n // A glob entry (`specs/stories/*.md`) claims a directory, not a filename,\n // and cannot be checked this way -- its key names a group, not a spec.\n return !target.includes(\"*\") && target === specFile;\n });\n\n if (candidates.length !== 1) return [];\n const key = candidates[0]![0];\n if (key === id) return [];\n\n return [\n {\n ruleId: \"structure/id-matches-config-key\",\n severity: \"warn\" as const,\n message:\n `Spec declares id \"${id}\" but is registered in spec.config.yaml as \"${key}\". ` +\n `Frontmatter references resolve against \"${id}\" and config requires against \"${key}\", ` +\n \"so the dependency graph shows them as two things. Rename one so they agree.\",\n filePath: spec.filePath,\n },\n ];\n },\n};\n","import { validFrontmatterRule } from \"./valid-frontmatter.js\";\nimport { requiredSectionsRule } from \"./required-sections.js\";\nimport { validReferencesRule } from \"./valid-references.js\";\nimport { noCircularDepsRule } from \"./no-circular-deps.js\";\nimport { storyCoverageRule } from \"./story-coverage.js\";\nimport { stalenessCheckRule } from \"./staleness-check.js\";\nimport { noVagueLanguageRule } from \"./no-vague-language.js\";\nimport { singleProjectContextRule } from \"./single-project-context.js\";\nimport { terminologyRule } from \"./terminology.js\";\nimport { edgeCaseCoverageRule } from \"./edge-case-coverage.js\";\nimport { namingConventionsRule } from \"./naming-conventions.js\";\nimport { threatCoverageRule } from \"./threat-coverage.js\";\nimport { ambiguityScoreAiRule } from \"./ambiguity-score-ai.js\";\nimport { noPlaceholderSectionsRule } from \"./no-placeholder-sections.js\";\nimport { idMatchesConfigKeyRule } from \"./id-matches-config-key.js\";\nimport type { LintRule } from \"../types.js\";\n\nexport const structureRules: LintRule[] = [\n validFrontmatterRule,\n requiredSectionsRule,\n validReferencesRule,\n noCircularDepsRule,\n singleProjectContextRule,\n idMatchesConfigKeyRule,\n];\n\nexport const contentRules: LintRule[] = [\n storyCoverageRule,\n stalenessCheckRule,\n noVagueLanguageRule,\n terminologyRule,\n edgeCaseCoverageRule,\n namingConventionsRule,\n threatCoverageRule,\n ambiguityScoreAiRule,\n noPlaceholderSectionsRule,\n];\n\nexport const allBuiltinRules: LintRule[] = [...structureRules, ...contentRules];\n\nexport {\n validFrontmatterRule,\n requiredSectionsRule,\n validReferencesRule,\n noCircularDepsRule,\n storyCoverageRule,\n stalenessCheckRule,\n noVagueLanguageRule,\n singleProjectContextRule,\n terminologyRule,\n edgeCaseCoverageRule,\n namingConventionsRule,\n threatCoverageRule,\n ambiguityScoreAiRule,\n noPlaceholderSectionsRule,\n idMatchesConfigKeyRule,\n};\n","import type { LintRule } from \"./types.js\";\nimport { structureRules, allBuiltinRules } from \"./rules/index.js\";\n\nexport function getPreset(name: string): LintRule[] {\n switch (name) {\n case \"minimal\":\n return structureRules;\n case \"recommended\":\n return allBuiltinRules;\n case \"strict\":\n // Promote warnings only. An info-class rule is an advisory the author\n // cannot satisfy by editing specs (ambiguity-score-ai fires whenever\n // ANTHROPIC_API_KEY is set), so promoting it would fail every suite\n // linted in an environment that carries the key.\n return allBuiltinRules.map((rule) =>\n rule.severity === \"warn\" ? { ...rule, severity: \"error\" as const } : rule,\n );\n default:\n throw new Error(\n `Unknown preset: \"${name}\". Use \"minimal\", \"recommended\", or \"strict\", or resolve external presets via resolvePreset() from @specdx/core.`,\n );\n }\n}\n","import { pathToFileURL } from \"node:url\";\nimport type { LintRule } from \"./types.js\";\n\nexport async function loadCustomRule(filePath: string): Promise<LintRule> {\n const module = await import(pathToFileURL(filePath).href);\n const rule = module.default ?? module.rule;\n if (!rule || !rule.id || !rule.run) {\n throw new Error(\n `Custom rule at ${filePath} must export a default LintRule with id and run function`,\n );\n }\n return rule as LintRule;\n}\n","/**\n * Args every reporting command shares.\n *\n * `--format` is declared per command, not globally. Spreading one blanket\n * `format` arg put the value `github` in every `--help` while only two\n * commands implemented it, and an unknown value fell through to pretty output\n * with exit 0 — a CI step could ask for annotations, get none, and still go\n * green (audit run 5, F2). A command now names the formats it renders, the\n * help text is generated from that list, and anything else is an error.\n */\n\n/** The single source of truth for a command's `--format` values. */\nexport type FormatArg = {\n type: \"string\";\n description: string;\n default: string;\n};\n\nexport const quietArg = {\n type: \"boolean\" as const,\n description: \"Suppress success and summary output; problems still print\",\n alias: [\"q\"],\n};\n\nexport const verboseArg = {\n type: \"boolean\" as const,\n description: \"Enable debug output\",\n alias: [\"V\"],\n};\n\n/**\n * Build the `--format` arg from the formats a command actually implements.\n * The first entry is the default.\n */\nexport function formatArg(formats: readonly string[]): FormatArg {\n const [fallback] = formats;\n if (!fallback) throw new Error(\"formatArg requires at least one format\");\n return {\n type: \"string\",\n description: `Output format (${formats.join(\", \")})`,\n default: fallback,\n };\n}\n\n/** `--quiet`, `--verbose`, and a `--format` limited to what the command renders. */\nexport function sharedArgs(formats: readonly string[]): {\n quiet: typeof quietArg;\n verbose: typeof verboseArg;\n format: FormatArg;\n} {\n return { quiet: quietArg, verbose: verboseArg, format: formatArg(formats) };\n}\n\n/**\n * Narrow a user-supplied `--format` to one the command renders.\n *\n * Returns null when the value is unsupported, so the caller can print and pick\n * its own exit code. Silently falling back to pretty is the defect this\n * replaces: the user asked for a machine-readable payload and got prose.\n */\nexport function resolveFormat<T extends string>(\n value: string | undefined,\n formats: readonly T[],\n): { ok: true; format: T } | { ok: false; message: string } {\n const [fallback] = formats;\n if (!fallback) throw new Error(\"resolveFormat requires at least one format\");\n if (value === undefined) return { ok: true, format: fallback };\n if ((formats as readonly string[]).includes(value)) return { ok: true, format: value as T };\n return {\n ok: false,\n message: `unknown --format \"${value}\". This command renders: ${formats.join(\", \")}.`,\n };\n}\n","/**\n * Quiet-aware console output.\n *\n * `--quiet` used to only lower a consola log level while every user-facing\n * line went out through `console.log`, so the flag changed nothing a user\n * could see (audit run 5, F2). Routing the pretty renderers through this\n * splits output into two classes and gives the flag something to suppress.\n */\nexport interface Output {\n /** Banners, verdicts, summaries — chrome. Suppressed by `--quiet`. */\n info(line?: string): void;\n /** Diagnostics, findings, payloads. Always printed. */\n out(line?: string): void;\n /** Errors and warnings, on stderr. Always printed. */\n error(line?: string): void;\n}\n\nexport function createOutput(options: { quiet?: boolean } = {}): Output {\n const quiet = options.quiet === true;\n return {\n info(line = \"\") {\n if (!quiet) console.log(line);\n },\n out(line = \"\") {\n console.log(line);\n },\n error(line = \"\") {\n console.error(line);\n },\n };\n}\n","import type { Diagnostic } from \"@specdx/lint\";\n\nexport function formatPretty(diagnostics: Diagnostic[]): string {\n if (diagnostics.length === 0) return \" ✓ All specs pass lint checks.\\n\";\n return diagnostics\n .map((d) => {\n const icon = d.severity === \"error\" ? \"✗\" : d.severity === \"warn\" ? \"⚠\" : \"ℹ\";\n return ` ${icon} ${d.severity} ${d.message} (${d.ruleId})\\n ${d.filePath}${d.line ? `:${d.line}` : \"\"}`;\n })\n .join(\"\\n\");\n}\n","import type { Diagnostic } from \"@specdx/lint\";\nexport function formatJson(diagnostics: Diagnostic[]): string {\n return JSON.stringify(diagnostics, null, 2);\n}\n","import type { Diagnostic } from \"@specdx/lint\";\n\n/**\n * GitHub workflow-command annotations.\n *\n * Info-severity diagnostics map to `::notice`, not `::warning`. Rendering an\n * advisory as a warning put five warnings in the Actions log for a suite that\n * was clean and exited 0 — the ambiguity advisory in particular, which is info\n * precisely so it cannot fail a build (audit run 5, F5).\n */\nexport function formatGithub(diagnostics: Diagnostic[]): string {\n return diagnostics\n .map((d) => {\n const level = d.severity === \"error\" ? \"error\" : d.severity === \"warn\" ? \"warning\" : \"notice\";\n const line = d.line ? `,line=${d.line}` : \"\";\n return `::${level} file=${d.filePath}${line}::${d.message} (${d.ruleId})`;\n })\n .join(\"\\n\");\n}\n","import { defineCommand } from \"citty\";\nimport { loadConfig, parseSpec, resolveGlob, buildGraph, createLogger } from \"@specdx/core\";\nimport { pack, type PackResult } from \"@specdx/pack\";\nimport type { ParsedSpec } from \"@specdx/core\";\nimport { quietArg, verboseArg } from \"../../shared-args.js\";\nimport { writeFile } from \"node:fs/promises\";\nimport { execSync } from \"node:child_process\";\n\nfunction copyToClipboard(text: string): void {\n const platform = process.platform;\n let cmd: string;\n if (platform === \"darwin\") {\n cmd = \"pbcopy\";\n } else if (platform === \"linux\") {\n cmd = \"xclip -selection clipboard\";\n } else if (platform === \"win32\") {\n cmd = \"clip\";\n } else {\n throw new Error(`Clipboard not supported on platform: ${platform}`);\n }\n execSync(cmd, { input: text, stdio: [\"pipe\", \"ignore\", \"ignore\"] });\n}\n\n/**\n * Why a pack produced no context, if it produced none.\n *\n * An empty `<context>` on stdout with exit 0 reads as \"here is your context\"\n * to whatever consumes it. `lint` and `check` already use exit 3 for\n * \"nothing was assessed\"; packing nothing is the same claim.\n */\nexport function emptyPackReason(\n stats: { specsIncluded: number; specsExcluded: number },\n specsResolved: number,\n): string | undefined {\n if (stats.specsIncluded > 0) return undefined;\n if (specsResolved === 0) {\n return \"no specs resolved from spec.config.yaml — check the paths in your config\";\n }\n // The relevance resolver drops sub-threshold specs before allocation, so\n // stats.specsExcluded counts only allocator-level exclusions. Reporting the\n // resolved total instead keeps the message from blaming the config.\n if (stats.specsExcluded === 0) {\n return `none of the ${specsResolved} resolved spec(s) scored above the relevance threshold for this task — try different --task wording, name specs with --specs, or use --full`;\n }\n return `all ${stats.specsExcluded} candidate spec(s) were excluded — widen --specs or raise --budget`;\n}\n\nexport interface RunPackOptions {\n configDir: string;\n task?: string;\n specs?: string[];\n budget?: number;\n format?: \"xml\" | \"markdown\" | \"json\";\n full?: boolean;\n dryRun?: boolean;\n}\n\nexport async function runPack(\n options: RunPackOptions,\n): Promise<PackResult & { specsResolved: number }> {\n if (!options.configDir) {\n throw new TypeError(\"runPack requires `configDir` — the directory holding spec.config.yaml.\");\n }\n const config = await loadConfig(undefined, options.configDir);\n\n const allSpecs: ParsedSpec[] = [];\n for (const [, entry] of Object.entries(config.specs)) {\n const files = await resolveGlob(entry.path, options.configDir);\n for (const file of files) {\n allSpecs.push(await parseSpec(file));\n }\n }\n\n let graph;\n try {\n graph = buildGraph(config);\n } catch {\n // non-fatal: proceed without graph\n }\n\n const result = pack(\n allSpecs,\n {\n task: options.task,\n specs: options.specs,\n budget: options.budget,\n format: options.format,\n full: options.full,\n dryRun: options.dryRun,\n },\n config.pack,\n graph,\n );\n\n return { ...result, specsResolved: allSpecs.length };\n}\n\nexport default defineCommand({\n meta: { name: \"pack\", description: \"Pack specs into AI-ready context\" },\n args: {\n quiet: quietArg,\n verbose: verboseArg,\n task: { type: \"string\", description: \"Task or context to optimise relevance for\" },\n specs: { type: \"string\", description: \"Comma-separated spec IDs or glob patterns to include\" },\n budget: { type: \"string\", description: \"Maximum token budget for the output\" },\n format: {\n type: \"string\",\n description: \"Output format (xml, markdown, json)\",\n default: \"xml\",\n },\n out: { type: \"string\", description: \"Write output to file instead of stdout\" },\n copy: { type: \"boolean\", description: \"Copy output to system clipboard\" },\n full: { type: \"boolean\", description: \"Include all specs without budget trimming\" },\n \"dry-run\": {\n type: \"boolean\",\n description: \"Preview what would be packed without writing output\",\n },\n },\n async run({ args }) {\n const logger = createLogger({ quiet: args.quiet, verbose: args.verbose });\n\n // Validate: --task and --specs are mutually exclusive\n if (args.task && args.specs) {\n console.error(\"\\n \\u2717 --task and --specs are mutually exclusive\\n\");\n process.exit(1);\n }\n\n // Validate: --copy and --dry-run are mutually exclusive\n if (args.copy && args[\"dry-run\"]) {\n console.error(\"\\n \\u2717 --copy and --dry-run are mutually exclusive\\n\");\n process.exit(1);\n }\n\n // Validate: --budget is a valid number\n let budget: number | undefined;\n if (args.budget) {\n budget = Number(args.budget);\n if (Number.isNaN(budget)) {\n console.error(\"\\n \\u2717 --budget must be a valid number\\n\");\n process.exit(1);\n }\n }\n\n // Validate: --format is valid\n const format = args.format as string;\n if (format && ![\"xml\", \"markdown\", \"json\"].includes(format)) {\n console.error(`\\n \\u2717 --format must be one of: xml, markdown, json\\n`);\n process.exit(1);\n }\n\n try {\n const specsList = args.specs ? args.specs.split(\",\").map((s: string) => s.trim()) : undefined;\n\n const result = await runPack({\n configDir: process.cwd(),\n task: args.task,\n specs: specsList,\n budget,\n format: format as \"xml\" | \"markdown\" | \"json\" | undefined,\n full: args.full,\n dryRun: args[\"dry-run\"],\n });\n\n const { stats } = result;\n\n // Dry-run: print plan to stdout\n if (args[\"dry-run\"]) {\n console.log(\"\\n Dry Run Summary:\\n\");\n for (const alloc of stats.allocations) {\n const status = alloc.included ? \"\\u2713\" : \"\\u2717\";\n const compressed = alloc.compressed ? \" (compressed)\" : \"\";\n console.log(\n ` ${status} ${alloc.specId} relevance=${alloc.relevance.toFixed(2)} tokens=${alloc.tokens}${compressed}`,\n );\n }\n console.log(`\\n Budget: ${stats.used} / ${stats.budget} tokens`);\n console.log(` Included: ${stats.specsIncluded} / ${result.specsResolved} specs`);\n console.log(` Sections compressed: ${stats.sectionsCompressed}`);\n console.log(` Sections omitted: ${stats.sectionsOmitted}\\n`);\n // A dry run that plans nothing is as misleading as an empty payload.\n const dryReason = emptyPackReason(stats, result.specsResolved);\n if (dryReason) {\n console.log(` ⚠ Nothing would be packed: ${dryReason}\\n`);\n process.exit(3);\n }\n return;\n }\n\n // Write output\n if (args.out) {\n await writeFile(args.out, result.output, \"utf-8\");\n logger.info(`Output written to ${args.out}`);\n }\n if (args.copy) {\n copyToClipboard(result.output);\n logger.info(\"Output copied to clipboard\");\n }\n if (!args.out && !args.copy) {\n process.stdout.write(result.output);\n }\n\n // Token report to stderr\n const total = stats.specsIncluded + stats.specsExcluded;\n process.stderr.write(\n `Packed ${stats.specsIncluded}/${total} specs \\u2022 ${stats.used} / ${stats.budget} tokens \\u2022 ${stats.sectionsCompressed} sections compressed \\u2022 ${stats.sectionsOmitted} sections omitted\\n`,\n );\n\n // Never let an empty payload leave looking like a successful pack.\n const emptyReason = emptyPackReason(stats, result.specsResolved);\n if (emptyReason) {\n process.stderr.write(`\\n \\u26a0 No context packed: ${emptyReason}\\n\\n`);\n process.exit(3);\n }\n } catch (err) {\n console.error(`\\n \\u2717 ${(err as Error).message}\\n`);\n process.exit(1);\n }\n },\n});\n","import type { ParsedSpec, DependencyGraph } from \"@specdx/core\";\nimport type { RelevanceScore } from \"./types.js\";\n\n/**\n * Common English stopwords to filter from task tokenization.\n */\nconst STOPWORDS = new Set([\n \"a\",\n \"an\",\n \"and\",\n \"are\",\n \"as\",\n \"at\",\n \"be\",\n \"but\",\n \"by\",\n \"do\",\n \"for\",\n \"from\",\n \"had\",\n \"has\",\n \"have\",\n \"he\",\n \"her\",\n \"his\",\n \"how\",\n \"i\",\n \"if\",\n \"in\",\n \"into\",\n \"is\",\n \"it\",\n \"its\",\n \"just\",\n \"me\",\n \"my\",\n \"no\",\n \"nor\",\n \"not\",\n \"of\",\n \"on\",\n \"or\",\n \"our\",\n \"out\",\n \"own\",\n \"say\",\n \"she\",\n \"so\",\n \"some\",\n \"such\",\n \"than\",\n \"that\",\n \"the\",\n \"their\",\n \"them\",\n \"then\",\n \"there\",\n \"these\",\n \"they\",\n \"this\",\n \"to\",\n \"too\",\n \"up\",\n \"us\",\n \"very\",\n \"was\",\n \"we\",\n \"were\",\n \"what\",\n \"when\",\n \"where\",\n \"which\",\n \"while\",\n \"who\",\n \"whom\",\n \"why\",\n \"will\",\n \"with\",\n \"would\",\n \"you\",\n \"your\",\n]);\n\n/** Tokenize a task string into lowercase keywords, dropping stopwords and short tokens. */\nfunction tokenize(task: string): string[] {\n return task\n .split(/[\\s\\-_/.,;:!?()[\\]{}'\"]+/)\n .map((t) => t.toLowerCase())\n .filter((t) => t.length > 1 && !STOPWORDS.has(t));\n}\n\n/** Field weights for keyword matching. */\nconst WEIGHT_TAGS = 3;\nconst WEIGHT_TITLE = 3;\nconst WEIGHT_SECTIONS = 2;\nconst WEIGHT_BODY = 1;\n\n/** Minimum id length considered for verbatim matching (avoids ids like \"a\"). */\nconst ID_MATCH_MIN_LENGTH = 3;\n\n/** Graph propagation factor for immediate neighbors. */\nconst GRAPH_BOOST_FACTOR = 0.5;\n\n/** Minimum normalized score to include a spec. */\nconst SCORE_THRESHOLD = 0.1;\n\n/**\n * Score specs by keyword relevance to a task string with graph propagation.\n *\n * - If no task or empty keywords after stopword removal, all specs get score 1.0.\n * - Keywords are matched with substring includes across weighted fields.\n * - Immediate graph neighbors of matching specs receive a boost.\n * - Results are normalized 0-1 and filtered by threshold.\n */\nexport function scoreSpecs(\n specs: Map<string, ParsedSpec>,\n task: string | undefined,\n graph: DependencyGraph,\n): RelevanceScore[] {\n const keywords = task ? tokenize(task) : [];\n\n // No keywords: all specs equally relevant\n if (keywords.length === 0) {\n const results: RelevanceScore[] = [];\n for (const specId of specs.keys()) {\n results.push({\n specId,\n score: 1.0,\n rawScore: 1.0,\n matchedKeywords: [],\n graphBoosted: false,\n });\n }\n return results;\n }\n\n // Score each spec by keyword hits across weighted fields\n const rawScores = new Map<string, number>();\n const matchedMap = new Map<string, Set<string>>();\n const idMatchedSet = new Set<string>();\n const taskLower = (task ?? \"\").toLowerCase();\n\n for (const [specId, spec] of specs) {\n let weightedHits = 0;\n const matched = new Set<string>();\n\n // Verbatim id match: a task that names a spec dominates keyword scoring\n const idLower = specId.toLowerCase();\n if (idLower.length >= ID_MATCH_MIN_LENGTH && taskLower.includes(idLower)) {\n idMatchedSet.add(specId);\n }\n\n for (const keyword of keywords) {\n let hit = false;\n\n // Tags (3x)\n const tags: unknown[] = (spec.frontmatter.tags as unknown[] | undefined) ?? [];\n for (const tag of tags) {\n if (typeof tag === \"string\" && tag.toLowerCase().includes(keyword)) {\n weightedHits += WEIGHT_TAGS;\n hit = true;\n break;\n }\n }\n\n // Title (3x)\n const title = spec.frontmatter.title;\n if (typeof title === \"string\" && title.toLowerCase().includes(keyword)) {\n weightedHits += WEIGHT_TITLE;\n hit = true;\n }\n\n // Sections (2x)\n for (const heading of spec.sections) {\n if (heading.toLowerCase().includes(keyword)) {\n weightedHits += WEIGHT_SECTIONS;\n hit = true;\n break;\n }\n }\n\n // Body content (1x)\n if (spec.content.toLowerCase().includes(keyword)) {\n weightedHits += WEIGHT_BODY;\n hit = true;\n }\n\n if (hit) {\n matched.add(keyword);\n }\n }\n\n const raw = weightedHits / keywords.length;\n rawScores.set(specId, raw);\n matchedMap.set(specId, matched);\n }\n\n // Graph propagation: boost immediate neighbors\n const boostScores = new Map<string, number>();\n const boostedSet = new Set<string>();\n\n for (const [specId, rawScore] of rawScores) {\n if (rawScore <= 0) continue;\n\n const boostAmount = rawScore * GRAPH_BOOST_FACTOR;\n\n // Find immediate neighbors from graph edges\n for (const edge of graph.edges) {\n let neighborId: string | undefined;\n if (edge.from === specId) {\n neighborId = edge.to;\n } else if (edge.to === specId) {\n neighborId = edge.from;\n }\n\n if (neighborId !== undefined && specs.has(neighborId)) {\n const existing = boostScores.get(neighborId) ?? 0;\n boostScores.set(neighborId, Math.max(existing, boostAmount));\n }\n }\n }\n\n // Combine raw + boost scores\n const finalRawScores = new Map<string, number>();\n for (const specId of specs.keys()) {\n const raw = rawScores.get(specId) ?? 0;\n const boost = boostScores.get(specId) ?? 0;\n const combined = raw + boost;\n finalRawScores.set(specId, combined);\n if (boost > 0 && raw === 0) {\n boostedSet.add(specId);\n }\n }\n\n // Find max for normalization\n let maxScore = 0;\n for (const score of finalRawScores.values()) {\n if (score > maxScore) maxScore = score;\n }\n\n // Build results, normalize, and filter. A spec the task names verbatim is\n // clamped to 1.0 — an explicit mention always outranks keyword inference —\n // without distorting the normalization of the other specs' scores.\n const results: RelevanceScore[] = [];\n for (const [specId] of specs) {\n const combined = finalRawScores.get(specId) ?? 0;\n const idMatched = idMatchedSet.has(specId);\n const normalized = idMatched ? 1.0 : maxScore > 0 ? combined / maxScore : 0;\n\n if (normalized < SCORE_THRESHOLD) continue;\n\n results.push({\n specId,\n score: normalized,\n rawScore: rawScores.get(specId) ?? 0,\n matchedKeywords: [...(matchedMap.get(specId) ?? [])],\n graphBoosted: boostedSet.has(specId),\n idMatched,\n });\n }\n\n // Sort descending by score; ties prefer specs the task named explicitly\n results.sort(\n (a, b) => b.score - a.score || Number(b.idMatched ?? false) - Number(a.idMatched ?? false),\n );\n\n return results;\n}\n\n/**\n * Score specs by explicit IDs. Named specs get 1.0, their transitive\n * upstream dependencies get 0.5.\n *\n * Throws if any specId is not found in the specs map.\n */\nexport function scoreSpecsByIds(\n specs: Map<string, ParsedSpec>,\n specIds: string[],\n graph: DependencyGraph,\n): RelevanceScore[] {\n // Validate all IDs exist\n for (const id of specIds) {\n if (!specs.has(id)) {\n const available = [...specs.keys()].join(\", \");\n throw new Error(`Unknown spec: \"${id}\". Available specs: ${available}`);\n }\n }\n\n const scoreMap = new Map<string, number>();\n\n // Named specs get 1.0\n for (const id of specIds) {\n scoreMap.set(id, 1.0);\n }\n\n // Upstream deps get 0.5 (unless already named at 1.0)\n for (const id of specIds) {\n const upstream = graph.getUpstream(id);\n for (const depId of upstream) {\n if (!scoreMap.has(depId) && specs.has(depId)) {\n scoreMap.set(depId, 0.5);\n }\n }\n }\n\n const results: RelevanceScore[] = [];\n for (const [specId, score] of scoreMap) {\n results.push({\n specId,\n score,\n rawScore: score,\n matchedKeywords: [],\n graphBoosted: score < 1.0,\n });\n }\n\n // Sort descending by score\n results.sort((a, b) => b.score - a.score);\n\n return results;\n}\n","import { countTokens } from \"@specdx/core\";\nimport type { ParsedSection } from \"@specdx/core\";\nimport type { CompressedSpec, CompressedSection, CompressionOptions } from \"./types.js\";\n\n/**\n * Returns true when `dateStr` is more than `days` days before now.\n * Returns false for invalid / missing dates (treat as fresh).\n */\nfunction isOlderThanDays(dateStr: string | undefined, days: number): boolean {\n if (!dateStr) return false;\n const ms = Date.parse(dateStr);\n if (Number.isNaN(ms)) return false;\n const diffMs = Date.now() - ms;\n return diffMs > days * 24 * 60 * 60 * 1000;\n}\n\n/**\n * Compress a single spec according to the provided options.\n */\nexport function compressSpec(\n specId: string,\n type: string,\n title: string,\n status: string | undefined,\n updatedDate: string | undefined,\n parsedSections: ParsedSection[],\n options: CompressionOptions,\n): CompressedSpec {\n // 1. Collapse superseded ADRs\n if (type === \"adr\" && status === \"superseded\" && options.collapseResolvedAdrs) {\n return {\n specId,\n type,\n title,\n sections: [],\n collapsed: true,\n collapsedSummary: `[ADR] ${title} — superseded`,\n };\n }\n\n // 2. Determine staleness\n const stale = options.stableDays > 0 && isOlderThanDays(updatedDate, options.stableDays);\n\n // 3. Process sections\n const boilerplateSet = new Set(options.boilerplateSections.map((s) => s.toLowerCase()));\n\n const sections: CompressedSection[] = [];\n\n for (const section of parsedSections) {\n // 3a. Strip boilerplate\n if (\n options.stripBoilerplate &&\n section.heading &&\n boilerplateSet.has(section.heading.toLowerCase())\n ) {\n continue;\n }\n\n // 3b. Collapse stale headed sections (preserve preamble)\n if (stale && section.heading) {\n const stub = `[Unchanged since ${updatedDate} — ${section.tokens} tokens omitted]`;\n sections.push({\n heading: section.heading,\n content: stub,\n tokens: countTokens(stub),\n compressed: true,\n originalTokens: section.tokens,\n });\n continue;\n }\n\n // 3c. Pass through unchanged\n sections.push({\n heading: section.heading,\n content: section.content,\n tokens: section.tokens,\n compressed: false,\n originalTokens: section.tokens,\n });\n }\n\n return {\n specId,\n type,\n title,\n sections,\n collapsed: false,\n };\n}\n","import { countTokens } from \"@specdx/core\";\nimport type { ParsedSpec } from \"@specdx/core\";\nimport { compressSpec } from \"./compressor.js\";\nimport type {\n CompressedSpec,\n CompressionOptions,\n PackStats,\n RelevanceScore,\n SpecAllocation,\n} from \"./types.js\";\n\n/** Options for the token allocator. */\nexport interface AllocatorOptions {\n /** Maximum token budget. */\n budget: number;\n /** When true, include full spec content without compression. */\n full: boolean;\n /** Compression settings (used when `full` is false). */\n compression: CompressionOptions;\n}\n\n/** Result of the allocation pass. */\nexport interface AllocationResult {\n /** Compressed specs that fit within the budget. */\n specs: CompressedSpec[];\n /** Statistics about how the budget was spent. */\n stats: PackStats;\n}\n\n/** Relevance at or above which a spec is trimmed to fit rather than excluded. */\nconst HIGH_RELEVANCE = 0.75;\n\n/** Minimum remaining budget worth trimming into. */\nconst MIN_TRIM_BUDGET = 150;\n\n/** Build the marker text for a contiguous run of omitted sections. */\nfunction omissionMarker(sections: CompressedSpec[\"sections\"]): string {\n const names = sections.map((s) => s.heading || \"(untitled)\");\n const noun = names.length === 1 ? \"section\" : \"sections\";\n return `[${names.length} ${noun} omitted to fit token budget: ${names.join(\", \")}]`;\n}\n\n/**\n * Produce a variant of `compressed` that fits within `budget` by keeping\n * sections in order while they fit and replacing each contiguous run of\n * omitted sections with an explicit marker naming them. Marker cost is\n * reserved out of the budget before sections are kept, so markers are always\n * emitted — a trimmed spec must never read as complete (issue #12).\n * Returns null when not even one real section fits.\n */\nfunction trimToBudget(\n compressed: CompressedSpec,\n budget: number,\n): { spec: CompressedSpec; tokens: number } | null {\n const sections = compressed.sections;\n let reserve = 0;\n\n // The kept set only shrinks as the reserve grows, so this converges.\n for (;;) {\n const effective = budget - reserve;\n const keep: boolean[] = new Array(sections.length).fill(false);\n let used = 0;\n let keptReal = false;\n\n for (let i = 0; i < sections.length; i++) {\n if (used + sections[i]!.tokens <= effective) {\n keep[i] = true;\n used += sections[i]!.tokens;\n keptReal = true;\n }\n }\n\n if (!keptReal) return null;\n\n // Group omitted sections into contiguous runs and price their markers.\n interface OmittedRun {\n start: number;\n sections: CompressedSpec[\"sections\"];\n marker: string;\n markerTokens: number;\n }\n const runs: OmittedRun[] = [];\n for (let i = 0; i < sections.length; i++) {\n if (keep[i]) continue;\n const start = i;\n const run: CompressedSpec[\"sections\"] = [];\n while (i < sections.length && !keep[i]) {\n run.push(sections[i]!);\n i++;\n }\n i--;\n const marker = omissionMarker(run);\n runs.push({ start, sections: run, marker, markerTokens: countTokens(marker) });\n }\n\n const markerTokens = runs.reduce((sum, r) => sum + r.markerTokens, 0);\n if (markerTokens > reserve) {\n reserve = markerTokens;\n continue;\n }\n\n // Assemble output: kept sections in order, markers at each cut.\n const out: CompressedSpec[\"sections\"] = [];\n for (let i = 0; i < sections.length; i++) {\n const run = runs.find((r) => r.start === i);\n if (run) {\n out.push({\n heading: \"\",\n content: run.marker,\n tokens: run.markerTokens,\n compressed: true,\n originalTokens: run.sections.reduce((sum, s) => sum + s.tokens, 0),\n omittedSections: run.sections.length,\n });\n i += run.sections.length - 1;\n continue;\n }\n out.push(sections[i]!);\n }\n\n return { spec: { ...compressed, sections: out }, tokens: used + markerTokens };\n }\n}\n\n/**\n * Allocate a token budget across specs, sorted by relevance.\n *\n * 1. Build specId -> ParsedSpec map\n * 2. Compress each spec (or pass through in full mode)\n * 3. Calculate token counts\n * 4. Sort by relevance descending\n * 5. Greedily include specs until budget is exhausted\n * 6. Build stats\n */\nexport function allocate(\n specs: ParsedSpec[],\n scores: RelevanceScore[],\n options: AllocatorOptions,\n): AllocationResult {\n // 1. Build specId -> ParsedSpec map\n const specMap = new Map<string, ParsedSpec>();\n for (const spec of specs) {\n specMap.set(spec.frontmatter.id, spec);\n }\n\n // 2. Compress each scored spec and compute token counts\n interface ScoredCompressed {\n compressed: CompressedSpec;\n relevance: number;\n tokens: number;\n idMatched: boolean;\n /**\n * Staleness-collapsed variant, spent only under budget pressure (issue #33).\n * Undefined when there is nothing to collapse, or in full mode.\n */\n stale?: { spec: CompressedSpec; tokens: number };\n }\n\n function tokensOf(compressed: CompressedSpec): number {\n if (compressed.collapsed) return countTokens(compressed.collapsedSummary ?? \"\");\n return compressed.sections.reduce((sum, section) => sum + section.tokens, 0);\n }\n\n const items: ScoredCompressed[] = [];\n\n for (const score of scores) {\n const spec = specMap.get(score.specId);\n if (!spec) continue;\n\n let compressed: CompressedSpec;\n let stale: ScoredCompressed[\"stale\"];\n\n if (options.full) {\n // No compression: pass through sections unchanged\n compressed = {\n specId: score.specId,\n type: String(spec.frontmatter.type),\n title: String(spec.frontmatter.title),\n sections: spec.parsedSections.map((s) => ({\n heading: s.heading,\n content: s.content,\n tokens: s.tokens,\n compressed: false,\n originalTokens: s.tokens,\n })),\n collapsed: false,\n };\n } else {\n const compress = (compression: CompressionOptions): CompressedSpec =>\n compressSpec(\n score.specId,\n String(spec.frontmatter.type),\n String(spec.frontmatter.title),\n spec.frontmatter.status as string | undefined,\n spec.frontmatter.updated as string | undefined,\n spec.parsedSections,\n compression,\n );\n\n // Boilerplate stripping and superseded-ADR collapse are hygiene, not\n // budget management -- they apply either way. Only the staleness collapse\n // is held back until the budget actually needs it.\n compressed = compress({ ...options.compression, stableDays: 0 });\n\n if (options.compression.stableDays > 0) {\n const collapsed = compress(options.compression);\n const collapsedTokens = tokensOf(collapsed);\n if (collapsedTokens < tokensOf(compressed)) {\n stale = { spec: collapsed, tokens: collapsedTokens };\n }\n }\n }\n\n items.push({\n compressed,\n relevance: score.score,\n tokens: tokensOf(compressed),\n idMatched: score.idMatched ?? false,\n stale,\n });\n }\n\n // 4. Sort by relevance descending; ties prefer specs the task named explicitly\n items.sort((a, b) => b.relevance - a.relevance || Number(b.idMatched) - Number(a.idMatched));\n\n // 4b. Collapse stale specs only while the budget is short, least relevant\n // first. Compression is a response to pressure: applied without it, the\n // caller asked for context and got stubs against a barely-touched budget.\n let projected = items.reduce((sum, item) => sum + item.tokens, 0);\n for (let i = items.length - 1; i >= 0 && projected > options.budget; i--) {\n const item = items[i]!;\n if (!item.stale) continue;\n projected -= item.tokens - item.stale.tokens;\n item.compressed = item.stale.spec;\n item.tokens = item.stale.tokens;\n }\n\n // 5. Greedy selection within budget\n const totalTokens = items.reduce((sum, item) => sum + item.tokens, 0);\n const withinBudget = totalTokens <= options.budget;\n\n const included: ScoredCompressed[] = [];\n const excluded: ScoredCompressed[] = [];\n let usedTokens = 0;\n\n if (withinBudget) {\n // Everything fits\n for (const item of items) {\n included.push(item);\n usedTokens += item.tokens;\n }\n } else {\n // Greedy: include from highest to lowest relevance. High-relevance specs\n // that don't fit are trimmed into the remaining budget before being\n // excluded — a task-named spec should never silently drop out.\n for (const item of items) {\n if (usedTokens + item.tokens <= options.budget) {\n included.push(item);\n usedTokens += item.tokens;\n continue;\n }\n const remaining = options.budget - usedTokens;\n if (\n (item.idMatched || item.relevance >= HIGH_RELEVANCE) &&\n remaining >= MIN_TRIM_BUDGET &&\n !item.compressed.collapsed\n ) {\n const trimmed = trimToBudget(item.compressed, remaining);\n if (trimmed) {\n included.push({ ...item, compressed: trimmed.spec, tokens: trimmed.tokens });\n usedTokens += trimmed.tokens;\n continue;\n }\n }\n excluded.push(item);\n }\n }\n\n // 6. Build stats\n let sectionsCompressed = 0;\n let sectionsOmitted = 0;\n for (const item of included) {\n for (const section of item.compressed.sections) {\n if (section.compressed) {\n sectionsCompressed++;\n }\n sectionsOmitted += section.omittedSections ?? 0;\n }\n }\n\n const allocations: SpecAllocation[] = [];\n\n // Add included specs\n for (const item of included) {\n allocations.push({\n specId: item.compressed.specId,\n type: item.compressed.type,\n relevance: item.relevance,\n tokens: item.tokens,\n compressed: item.compressed.collapsed || item.compressed.sections.some((s) => s.compressed),\n included: true,\n });\n }\n\n // Add excluded specs\n for (const item of excluded) {\n allocations.push({\n specId: item.compressed.specId,\n type: item.compressed.type,\n relevance: item.relevance,\n tokens: item.tokens,\n compressed: item.compressed.collapsed || item.compressed.sections.some((s) => s.compressed),\n included: false,\n });\n }\n\n const stats: PackStats = {\n budget: options.budget,\n used: usedTokens,\n specsIncluded: included.length,\n specsExcluded: excluded.length,\n sectionsCompressed,\n sectionsOmitted,\n allocations,\n };\n\n return {\n specs: included.map((item) => item.compressed),\n stats,\n };\n}\n","import type { CompressedSpec, PackStats } from \"../types.js\";\n\nfunction escapeXml(text: string): string {\n return text\n .replace(/&/g, \"&amp;\")\n .replace(/</g, \"&lt;\")\n .replace(/>/g, \"&gt;\")\n .replace(/\"/g, \"&quot;\");\n}\n\n/**\n * Format compressed specs as XML.\n *\n * @param specs - Compressed specs to render.\n * @param stats - Pack statistics with allocation details.\n * @returns An XML string representing the packed context.\n */\nexport function formatXml(specs: CompressedSpec[], stats: PackStats): string {\n const lines: string[] = [];\n\n lines.push(\n `<context budget=\"${stats.budget}\" used=\"${stats.used}\" specs=\"${stats.specsIncluded}\" compressed=\"${stats.sectionsCompressed}\" omitted=\"${stats.sectionsOmitted}\">`,\n );\n\n for (const spec of specs) {\n const alloc = stats.allocations.find((a) => a.specId === spec.specId);\n const relevance = alloc?.relevance ?? 0;\n const tokens = alloc?.tokens ?? 0;\n\n if (spec.collapsed) {\n lines.push(\n ` <spec id=\"${escapeXml(spec.specId)}\" type=\"${escapeXml(spec.type)}\" relevance=\"${relevance}\" tokens=\"${tokens}\" collapsed=\"true\">`,\n );\n lines.push(` ${escapeXml(spec.collapsedSummary ?? \"\")}`);\n lines.push(\" </spec>\");\n } else {\n lines.push(\n ` <spec id=\"${escapeXml(spec.specId)}\" type=\"${escapeXml(spec.type)}\" relevance=\"${relevance}\" tokens=\"${tokens}\">`,\n );\n for (const section of spec.sections) {\n const compressedAttr = section.compressed ? ' compressed=\"true\"' : \"\";\n lines.push(` <section name=\"${escapeXml(section.heading)}\"${compressedAttr}>`);\n lines.push(` ${escapeXml(section.content)}`);\n lines.push(\" </section>\");\n }\n lines.push(\" </spec>\");\n }\n }\n\n lines.push(\"</context>\");\n\n return lines.join(\"\\n\");\n}\n","import type { CompressedSpec, PackStats } from \"../types.js\";\n\n/**\n * Format compressed specs as Markdown.\n *\n * @param specs - Compressed specs to render.\n * @param stats - Pack statistics with allocation details.\n * @returns A Markdown string representing the packed context.\n */\nexport function formatMarkdown(specs: CompressedSpec[], stats: PackStats): string {\n const parts: string[] = [];\n\n for (let i = 0; i < specs.length; i++) {\n const spec = specs[i]!;\n const alloc = stats.allocations.find((a) => a.specId === spec.specId);\n const relevance = alloc?.relevance ?? 0;\n\n if (i > 0) {\n parts.push(\"---\");\n parts.push(\"\");\n }\n\n parts.push(`# ${spec.specId} (${spec.type}) [relevance: ${relevance}]`);\n parts.push(\"\");\n\n if (spec.collapsed) {\n parts.push(spec.collapsedSummary ?? \"\");\n parts.push(\"\");\n } else {\n for (const section of spec.sections) {\n if (section.heading) {\n parts.push(`## ${section.heading}`);\n parts.push(\"\");\n }\n parts.push(section.content);\n parts.push(\"\");\n }\n }\n }\n\n return parts.join(\"\\n\");\n}\n","import type { CompressedSpec, PackStats } from \"../types.js\";\n\ninterface JsonSection {\n name: string;\n content: string;\n compressed: boolean;\n}\n\ninterface JsonSpec {\n id: string;\n type: string;\n relevance: number;\n tokens: number;\n collapsed: boolean;\n summary?: string;\n sections: JsonSection[];\n}\n\ninterface JsonOutput {\n budget: number;\n used: number;\n sectionsOmitted: number;\n specs: JsonSpec[];\n}\n\n/**\n * Format compressed specs as a JSON string.\n *\n * @param specs - Compressed specs to render.\n * @param stats - Pack statistics with allocation details.\n * @returns A pretty-printed JSON string representing the packed context.\n */\nexport function formatJson(specs: CompressedSpec[], stats: PackStats): string {\n const output: JsonOutput = {\n budget: stats.budget,\n used: stats.used,\n sectionsOmitted: stats.sectionsOmitted,\n specs: specs.map((spec) => {\n const alloc = stats.allocations.find((a) => a.specId === spec.specId);\n const relevance = alloc?.relevance ?? 0;\n const tokens = alloc?.tokens ?? 0;\n\n const jsonSpec: JsonSpec = {\n id: spec.specId,\n type: spec.type,\n relevance,\n tokens,\n collapsed: spec.collapsed,\n sections: spec.sections.map((s) => ({\n name: s.heading,\n content: s.content,\n compressed: s.compressed,\n })),\n };\n\n if (spec.collapsed) {\n jsonSpec.summary = spec.collapsedSummary ?? \"\";\n }\n\n return jsonSpec;\n }),\n };\n\n return JSON.stringify(output, null, 2);\n}\n","import type { ParsedSpec, DependencyGraph } from \"@specdx/core\";\nimport type { PackConfig } from \"@specdx/schema\";\nimport type {\n PackOptions,\n PackResult,\n CompressionOptions,\n CompressedSpec,\n RelevanceScore,\n} from \"./types.js\";\nimport { scoreSpecs, scoreSpecsByIds } from \"./resolver.js\";\nimport { allocate } from \"./allocator.js\";\nimport { formatXml } from \"./formatters/xml.js\";\nimport { formatMarkdown } from \"./formatters/markdown.js\";\nimport { formatJson } from \"./formatters/json.js\";\n\nexport type {\n PackOptions,\n PackResult,\n PackStats,\n SpecAllocation,\n RelevanceScore,\n CompressedSpec,\n CompressedSection,\n CompressionOptions,\n} from \"./types.js\";\n\nexport { scoreSpecs, scoreSpecsByIds } from \"./resolver.js\";\nexport { allocate, type AllocatorOptions, type AllocationResult } from \"./allocator.js\";\nexport { compressSpec } from \"./compressor.js\";\nexport { formatXml } from \"./formatters/xml.js\";\nexport { formatMarkdown } from \"./formatters/markdown.js\";\nexport { formatJson } from \"./formatters/json.js\";\n\n/**\n * Default empty dependency graph used when none is provided.\n */\nfunction emptyGraph(): DependencyGraph {\n return {\n nodes: [],\n edges: [],\n topologicalSort: () => [],\n getDownstream: () => [],\n getUpstream: () => [],\n };\n}\n\n/**\n * Build CompressionOptions from PackConfig with sensible defaults.\n */\nfunction buildCompressionOptions(packConfig: PackConfig | undefined): CompressionOptions {\n const compression = packConfig?.compression;\n return {\n stripBoilerplate: compression?.strip_boilerplate ?? true,\n stableDays: compression?.stable_days ?? 7,\n collapseResolvedAdrs: compression?.collapse_resolved_adrs ?? true,\n boilerplateSections: packConfig?.boilerplate_sections ?? [\n \"Changelog\",\n \"Revision History\",\n \"Document History\",\n ],\n };\n}\n\n/**\n * Pack specs into a formatted context string within a token budget.\n *\n * Pipeline:\n * 1. Resolve relevance scores\n * 2. Allocate token budget across specs\n * 3. Format output in the requested format\n */\nexport function pack(\n specs: ParsedSpec[],\n options: PackOptions,\n packConfig: PackConfig | undefined,\n graph: DependencyGraph | undefined,\n): PackResult {\n // 1. Resolve defaults\n const budget = options.budget ?? packConfig?.max_tokens ?? 12000;\n const format = options.format ?? packConfig?.format ?? \"xml\";\n const full = options.full ?? false;\n const compression = buildCompressionOptions(packConfig);\n const resolvedGraph = graph ?? emptyGraph();\n\n // 2. Extract project-context specs and reserve budget\n const projectContextSpecs: ParsedSpec[] = [];\n const regularSpecs: ParsedSpec[] = [];\n for (const spec of specs) {\n if (spec.frontmatter.type === \"project-context\") {\n projectContextSpecs.push(spec);\n } else {\n regularSpecs.push(spec);\n }\n }\n\n let reservedTokens = 0;\n let reservedCompressed: CompressedSpec[] = [];\n if (projectContextSpecs.length > 0) {\n const maxReserved = Math.min(budget, 2000);\n const ctxScores: RelevanceScore[] = projectContextSpecs.map((s) => ({\n specId: s.frontmatter.id,\n score: 1.0,\n rawScore: 1.0,\n matchedKeywords: [],\n graphBoosted: false,\n }));\n const ctxResult = allocate(projectContextSpecs, ctxScores, {\n budget: maxReserved,\n full: true,\n compression,\n });\n reservedCompressed = ctxResult.specs;\n reservedTokens = ctxResult.stats.used;\n }\n\n const regularBudget = Math.max(0, budget - reservedTokens);\n\n // 3. Build spec map for resolver (regular specs only)\n const specMap = new Map<string, ParsedSpec>();\n for (const spec of regularSpecs) {\n specMap.set(spec.frontmatter.id, spec);\n }\n\n // 4. Stage 1 - Resolve\n const scores = options.specs\n ? scoreSpecsByIds(specMap, options.specs, resolvedGraph)\n : scoreSpecs(specMap, options.task, resolvedGraph);\n\n // 5. Stage 2 - Allocate\n const { specs: compressedSpecs, stats } = allocate(regularSpecs, scores, {\n budget: regularBudget,\n full,\n compression,\n });\n\n // 6. Combine project-context and regular specs\n const allCompressed = [...reservedCompressed, ...compressedSpecs];\n\n // Update stats to include reserved specs\n stats.budget = budget;\n stats.used += reservedTokens;\n stats.specsIncluded += reservedCompressed.length;\n for (const ctx of reservedCompressed) {\n stats.allocations.unshift({\n specId: ctx.specId,\n type: ctx.type,\n relevance: 1.0,\n tokens: reservedTokens,\n compressed: false,\n included: true,\n });\n }\n\n // 7. Dry run: return stats without output\n if (options.dryRun) {\n return { output: \"\", stats };\n }\n\n // 8. Stage 3 - Format\n let output: string;\n switch (format) {\n case \"markdown\":\n output = formatMarkdown(allCompressed, stats);\n break;\n case \"json\":\n output = formatJson(allCompressed, stats);\n break;\n default:\n output = formatXml(allCompressed, stats);\n break;\n }\n\n return { output, stats };\n}\n","import { defineCommand } from \"citty\";\nimport { join } from \"node:path\";\nimport { diffBetweenRefs, DEFAULT_DIFF_CONFIG, DiffError } from \"@specdx/diff\";\nimport { loadConfig } from \"@specdx/core\";\nimport { formatChangelog } from \"../../formatters/changelog.js\";\nimport type { DiffResult } from \"@specdx/diff\";\nimport { sharedArgs, resolveFormat } from \"../../shared-args.js\";\nimport { createOutput } from \"../../output.js\";\n\nconst FORMATS = [\"pretty\", \"json\", \"changelog\"] as const;\n\nexport interface RunDiffOptions {\n base?: string;\n head?: string;\n spec?: string;\n format?: string;\n /** Compare the base ref against the working tree instead of a head ref. */\n working?: boolean;\n /**\n * Directory holding spec.config.yaml. Defaults to the process cwd; a library\n * consumer needs to point it elsewhere (audit run 5, F8).\n */\n configDir?: string;\n}\n\nexport async function runDiff(options: RunDiffOptions): Promise<DiffResult> {\n const configDir = options.configDir ?? process.cwd();\n const config = await loadConfig(undefined, configDir);\n\n const baseRef = options.base ?? config.diff?.baseline_ref ?? DEFAULT_DIFF_CONFIG.baseline_ref;\n const headRef = options.head ?? \"HEAD\";\n\n const configPath = join(configDir, \"spec.config.yaml\");\n\n const result = await diffBetweenRefs(configPath, baseRef, headRef, {\n working: options.working ?? false,\n });\n\n if (options.spec) {\n result.diffs = result.diffs.filter((d) => d.specId === options.spec);\n result.impact = result.impact.filter((i) => i.changedSpec === options.spec);\n }\n\n return result;\n}\n\nexport default defineCommand({\n meta: { name: \"diff\", description: \"Show spec changes and downstream impact\" },\n args: {\n base: { type: \"string\", description: \"Base git ref (default: from config or 'main')\" },\n head: { type: \"string\", description: \"Head git ref (default: HEAD)\" },\n working: {\n type: \"boolean\",\n description: \"Compare the base ref against the working tree (includes uncommitted specs)\",\n default: false,\n },\n spec: { type: \"string\", description: \"Scope to a single spec ID\" },\n ...sharedArgs(FORMATS),\n },\n async run({ args }) {\n const format = resolveFormat(args.format, FORMATS);\n if (!format.ok) {\n console.error(`\\n ✗ ${format.message}\\n`);\n process.exit(1);\n }\n const output = createOutput({ quiet: args.quiet });\n\n try {\n try {\n const result = await runDiff({\n base: args.base,\n head: args.head,\n spec: args.spec,\n format: args.format,\n working: args.working,\n });\n\n if (format.format === \"json\") {\n console.log(JSON.stringify(result, null, 2));\n return;\n }\n\n if (format.format === \"changelog\") {\n const baseRef =\n args.base ?? (await loadConfig(undefined, process.cwd())).diff?.baseline_ref ?? \"main\";\n console.log(\n formatChangelog(result, baseRef, args.working ? \"working tree\" : (args.head ?? \"HEAD\")),\n );\n return;\n }\n\n // A ref-to-ref comparison cannot see the working tree, so an unqualified\n // \"no changes\" would be a false all-clear for anyone about to commit.\n const printUncommittedWarning = (): void => {\n if (result.uncommittedSpecFiles.length === 0) return;\n const count = result.uncommittedSpecFiles.length;\n console.log(\n `\\n \\u26a0 ${count} spec file(s) changed in the working tree are not covered by this comparison:`,\n );\n for (const file of result.uncommittedSpecFiles) {\n console.log(` ${file}`);\n }\n console.log(\" Run with --working to include them.\");\n };\n\n // Pretty format\n if (result.diffs.length === 0 && result.added.length === 0 && result.removed.length === 0) {\n output.info(\" \\u2713 No spec changes detected.\");\n printUncommittedWarning();\n return;\n }\n\n console.log(result.summary);\n console.log();\n\n for (const diff of result.diffs) {\n console.log(` ${diff.specId}:`);\n for (const fc of diff.frontmatter) {\n const detail =\n fc.before !== undefined || fc.after !== undefined\n ? ` (${String(fc.before)} \\u2192 ${String(fc.after)})`\n : \"\";\n console.log(` ${fc.type}: ${fc.field}${detail}`);\n }\n for (const sc of diff.sections) {\n console.log(` ${sc.type}: ${sc.heading}`);\n }\n }\n\n if (result.added.length > 0) {\n console.log(`\\n Added: ${result.added.join(\", \")}`);\n }\n if (result.removed.length > 0) {\n console.log(`\\n Removed: ${result.removed.join(\", \")}`);\n }\n\n if (result.impact.length > 0) {\n console.log(\"\\n Downstream Impact:\");\n for (const impact of result.impact) {\n for (const d of impact.downstream) {\n console.log(\n ` ${d.specId} \\u2014 staleness: ${d.staleness.toFixed(2)} \\u2014 ${d.reason}`,\n );\n }\n }\n }\n\n printUncommittedWarning();\n } catch (err) {\n if (err instanceof DiffError) {\n console.error(`\\n \\u2717 ${err.message}\\n`);\n process.exit(1);\n }\n throw err;\n }\n } catch (err) {\n console.error(`\\n ✗ ${(err as Error).message}\\n`);\n process.exit(1);\n }\n },\n});\n","export type FieldChangeType = \"added\" | \"removed\" | \"modified\" | \"broken-reference\";\n\nexport interface FieldChange {\n field: string;\n type: FieldChangeType;\n before?: unknown;\n after?: unknown;\n}\n\nexport interface SectionChange {\n heading: string;\n type: \"added\" | \"removed\" | \"modified\";\n contentDiff?: string;\n}\n\nexport interface SpecDiff {\n specId: string;\n filePath: string;\n frontmatter: FieldChange[];\n sections: SectionChange[];\n summary: string;\n}\n\nexport interface DownstreamImpact {\n specId: string;\n filePath: string;\n distance: number;\n lastUpdated: string | null;\n staleness: number;\n reason: string;\n}\n\nexport interface ImpactAnalysis {\n changedSpec: string;\n downstream: DownstreamImpact[];\n totalAffected: number;\n}\n\nexport interface DiffResult {\n diffs: SpecDiff[];\n added: string[];\n removed: string[];\n impact: ImpactAnalysis[];\n summary: string;\n /**\n * Spec files changed in the working tree but not covered by the comparison.\n *\n * A ref-to-ref diff cannot see uncommitted work, so reporting \"no changes\"\n * without this would be a false all-clear. Always empty in working mode,\n * where those changes are part of the comparison.\n */\n uncommittedSpecFiles: string[];\n}\n\nexport interface DiffOptions {\n /**\n * Compare the base ref against the working tree instead of a head ref.\n * Includes staged, unstaged, and untracked spec files.\n */\n working?: boolean;\n}\n\nexport interface StatusResult {\n project: string;\n /**\n * Spec *files* resolved, not config entries — one glob entry can resolve to\n * many files. The old name `specCount` did not say which, and meant the\n * other thing in `runValidate` (audit run 5, F4).\n */\n specFiles: number;\n byStatus: Record<string, number>;\n lintHealth: { errors: number; warnings: number; passing: number };\n staleSpecs: { specId: string; daysSinceUpdate: number; owner?: string }[];\n integrityIssues: string[];\n /** \"unassessed\" when the suite resolved to zero specs — never a vacuous \"healthy\". */\n verdict: \"healthy\" | \"warnings\" | \"errors\" | \"unassessed\";\n}\n\nexport interface DiffConfig {\n baseline_ref: string;\n staleness_threshold_days: number;\n ignore_paths?: string[];\n}\n\nexport const DEFAULT_DIFF_CONFIG: DiffConfig = {\n baseline_ref: \"main\",\n staleness_threshold_days: 14,\n};\n\nexport class DiffError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"DiffError\";\n }\n}\n","function Diff() {}\nDiff.prototype = {\n diff: function diff(oldString, newString) {\n var _options$timeout;\n var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};\n var callback = options.callback;\n if (typeof options === 'function') {\n callback = options;\n options = {};\n }\n var self = this;\n function done(value) {\n value = self.postProcess(value, options);\n if (callback) {\n setTimeout(function () {\n callback(value);\n }, 0);\n return true;\n } else {\n return value;\n }\n }\n\n // Allow subclasses to massage the input prior to running\n oldString = this.castInput(oldString, options);\n newString = this.castInput(newString, options);\n oldString = this.removeEmpty(this.tokenize(oldString, options));\n newString = this.removeEmpty(this.tokenize(newString, options));\n var newLen = newString.length,\n oldLen = oldString.length;\n var editLength = 1;\n var maxEditLength = newLen + oldLen;\n if (options.maxEditLength != null) {\n maxEditLength = Math.min(maxEditLength, options.maxEditLength);\n }\n var maxExecutionTime = (_options$timeout = options.timeout) !== null && _options$timeout !== void 0 ? _options$timeout : Infinity;\n var abortAfterTimestamp = Date.now() + maxExecutionTime;\n var bestPath = [{\n oldPos: -1,\n lastComponent: undefined\n }];\n\n // Seed editLength = 0, i.e. the content starts with the same values\n var newPos = this.extractCommon(bestPath[0], newString, oldString, 0, options);\n if (bestPath[0].oldPos + 1 >= oldLen && newPos + 1 >= newLen) {\n // Identity per the equality and tokenizer\n return done(buildValues(self, bestPath[0].lastComponent, newString, oldString, self.useLongestToken));\n }\n\n // Once we hit the right edge of the edit graph on some diagonal k, we can\n // definitely reach the end of the edit graph in no more than k edits, so\n // there's no point in considering any moves to diagonal k+1 any more (from\n // which we're guaranteed to need at least k+1 more edits).\n // Similarly, once we've reached the bottom of the edit graph, there's no\n // point considering moves to lower diagonals.\n // We record this fact by setting minDiagonalToConsider and\n // maxDiagonalToConsider to some finite value once we've hit the edge of\n // the edit graph.\n // This optimization is not faithful to the original algorithm presented in\n // Myers's paper, which instead pointlessly extends D-paths off the end of\n // the edit graph - see page 7 of Myers's paper which notes this point\n // explicitly and illustrates it with a diagram. This has major performance\n // implications for some common scenarios. For instance, to compute a diff\n // where the new text simply appends d characters on the end of the\n // original text of length n, the true Myers algorithm will take O(n+d^2)\n // time while this optimization needs only O(n+d) time.\n var minDiagonalToConsider = -Infinity,\n maxDiagonalToConsider = Infinity;\n\n // Main worker method. checks all permutations of a given edit length for acceptance.\n function execEditLength() {\n for (var diagonalPath = Math.max(minDiagonalToConsider, -editLength); diagonalPath <= Math.min(maxDiagonalToConsider, editLength); diagonalPath += 2) {\n var basePath = void 0;\n var removePath = bestPath[diagonalPath - 1],\n addPath = bestPath[diagonalPath + 1];\n if (removePath) {\n // No one else is going to attempt to use this value, clear it\n bestPath[diagonalPath - 1] = undefined;\n }\n var canAdd = false;\n if (addPath) {\n // what newPos will be after we do an insertion:\n var addPathNewPos = addPath.oldPos - diagonalPath;\n canAdd = addPath && 0 <= addPathNewPos && addPathNewPos < newLen;\n }\n var canRemove = removePath && removePath.oldPos + 1 < oldLen;\n if (!canAdd && !canRemove) {\n // If this path is a terminal then prune\n bestPath[diagonalPath] = undefined;\n continue;\n }\n\n // Select the diagonal that we want to branch from. We select the prior\n // path whose position in the old string is the farthest from the origin\n // and does not pass the bounds of the diff graph\n if (!canRemove || canAdd && removePath.oldPos < addPath.oldPos) {\n basePath = self.addToPath(addPath, true, false, 0, options);\n } else {\n basePath = self.addToPath(removePath, false, true, 1, options);\n }\n newPos = self.extractCommon(basePath, newString, oldString, diagonalPath, options);\n if (basePath.oldPos + 1 >= oldLen && newPos + 1 >= newLen) {\n // If we have hit the end of both strings, then we are done\n return done(buildValues(self, basePath.lastComponent, newString, oldString, self.useLongestToken));\n } else {\n bestPath[diagonalPath] = basePath;\n if (basePath.oldPos + 1 >= oldLen) {\n maxDiagonalToConsider = Math.min(maxDiagonalToConsider, diagonalPath - 1);\n }\n if (newPos + 1 >= newLen) {\n minDiagonalToConsider = Math.max(minDiagonalToConsider, diagonalPath + 1);\n }\n }\n }\n editLength++;\n }\n\n // Performs the length of edit iteration. Is a bit fugly as this has to support the\n // sync and async mode which is never fun. Loops over execEditLength until a value\n // is produced, or until the edit length exceeds options.maxEditLength (if given),\n // in which case it will return undefined.\n if (callback) {\n (function exec() {\n setTimeout(function () {\n if (editLength > maxEditLength || Date.now() > abortAfterTimestamp) {\n return callback();\n }\n if (!execEditLength()) {\n exec();\n }\n }, 0);\n })();\n } else {\n while (editLength <= maxEditLength && Date.now() <= abortAfterTimestamp) {\n var ret = execEditLength();\n if (ret) {\n return ret;\n }\n }\n }\n },\n addToPath: function addToPath(path, added, removed, oldPosInc, options) {\n var last = path.lastComponent;\n if (last && !options.oneChangePerToken && last.added === added && last.removed === removed) {\n return {\n oldPos: path.oldPos + oldPosInc,\n lastComponent: {\n count: last.count + 1,\n added: added,\n removed: removed,\n previousComponent: last.previousComponent\n }\n };\n } else {\n return {\n oldPos: path.oldPos + oldPosInc,\n lastComponent: {\n count: 1,\n added: added,\n removed: removed,\n previousComponent: last\n }\n };\n }\n },\n extractCommon: function extractCommon(basePath, newString, oldString, diagonalPath, options) {\n var newLen = newString.length,\n oldLen = oldString.length,\n oldPos = basePath.oldPos,\n newPos = oldPos - diagonalPath,\n commonCount = 0;\n while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(oldString[oldPos + 1], newString[newPos + 1], options)) {\n newPos++;\n oldPos++;\n commonCount++;\n if (options.oneChangePerToken) {\n basePath.lastComponent = {\n count: 1,\n previousComponent: basePath.lastComponent,\n added: false,\n removed: false\n };\n }\n }\n if (commonCount && !options.oneChangePerToken) {\n basePath.lastComponent = {\n count: commonCount,\n previousComponent: basePath.lastComponent,\n added: false,\n removed: false\n };\n }\n basePath.oldPos = oldPos;\n return newPos;\n },\n equals: function equals(left, right, options) {\n if (options.comparator) {\n return options.comparator(left, right);\n } else {\n return left === right || options.ignoreCase && left.toLowerCase() === right.toLowerCase();\n }\n },\n removeEmpty: function removeEmpty(array) {\n var ret = [];\n for (var i = 0; i < array.length; i++) {\n if (array[i]) {\n ret.push(array[i]);\n }\n }\n return ret;\n },\n castInput: function castInput(value) {\n return value;\n },\n tokenize: function tokenize(value) {\n return Array.from(value);\n },\n join: function join(chars) {\n return chars.join('');\n },\n postProcess: function postProcess(changeObjects) {\n return changeObjects;\n }\n};\nfunction buildValues(diff, lastComponent, newString, oldString, useLongestToken) {\n // First we convert our linked list of components in reverse order to an\n // array in the right order:\n var components = [];\n var nextComponent;\n while (lastComponent) {\n components.push(lastComponent);\n nextComponent = lastComponent.previousComponent;\n delete lastComponent.previousComponent;\n lastComponent = nextComponent;\n }\n components.reverse();\n var componentPos = 0,\n componentLen = components.length,\n newPos = 0,\n oldPos = 0;\n for (; componentPos < componentLen; componentPos++) {\n var component = components[componentPos];\n if (!component.removed) {\n if (!component.added && useLongestToken) {\n var value = newString.slice(newPos, newPos + component.count);\n value = value.map(function (value, i) {\n var oldValue = oldString[oldPos + i];\n return oldValue.length > value.length ? oldValue : value;\n });\n component.value = diff.join(value);\n } else {\n component.value = diff.join(newString.slice(newPos, newPos + component.count));\n }\n newPos += component.count;\n\n // Common case\n if (!component.added) {\n oldPos += component.count;\n }\n } else {\n component.value = diff.join(oldString.slice(oldPos, oldPos + component.count));\n oldPos += component.count;\n }\n }\n return components;\n}\n\nvar characterDiff = new Diff();\nfunction diffChars(oldStr, newStr, options) {\n return characterDiff.diff(oldStr, newStr, options);\n}\n\nfunction longestCommonPrefix(str1, str2) {\n var i;\n for (i = 0; i < str1.length && i < str2.length; i++) {\n if (str1[i] != str2[i]) {\n return str1.slice(0, i);\n }\n }\n return str1.slice(0, i);\n}\nfunction longestCommonSuffix(str1, str2) {\n var i;\n\n // Unlike longestCommonPrefix, we need a special case to handle all scenarios\n // where we return the empty string since str1.slice(-0) will return the\n // entire string.\n if (!str1 || !str2 || str1[str1.length - 1] != str2[str2.length - 1]) {\n return '';\n }\n for (i = 0; i < str1.length && i < str2.length; i++) {\n if (str1[str1.length - (i + 1)] != str2[str2.length - (i + 1)]) {\n return str1.slice(-i);\n }\n }\n return str1.slice(-i);\n}\nfunction replacePrefix(string, oldPrefix, newPrefix) {\n if (string.slice(0, oldPrefix.length) != oldPrefix) {\n throw Error(\"string \".concat(JSON.stringify(string), \" doesn't start with prefix \").concat(JSON.stringify(oldPrefix), \"; this is a bug\"));\n }\n return newPrefix + string.slice(oldPrefix.length);\n}\nfunction replaceSuffix(string, oldSuffix, newSuffix) {\n if (!oldSuffix) {\n return string + newSuffix;\n }\n if (string.slice(-oldSuffix.length) != oldSuffix) {\n throw Error(\"string \".concat(JSON.stringify(string), \" doesn't end with suffix \").concat(JSON.stringify(oldSuffix), \"; this is a bug\"));\n }\n return string.slice(0, -oldSuffix.length) + newSuffix;\n}\nfunction removePrefix(string, oldPrefix) {\n return replacePrefix(string, oldPrefix, '');\n}\nfunction removeSuffix(string, oldSuffix) {\n return replaceSuffix(string, oldSuffix, '');\n}\nfunction maximumOverlap(string1, string2) {\n return string2.slice(0, overlapCount(string1, string2));\n}\n\n// Nicked from https://stackoverflow.com/a/60422853/1709587\nfunction overlapCount(a, b) {\n // Deal with cases where the strings differ in length\n var startA = 0;\n if (a.length > b.length) {\n startA = a.length - b.length;\n }\n var endB = b.length;\n if (a.length < b.length) {\n endB = a.length;\n }\n // Create a back-reference for each index\n // that should be followed in case of a mismatch.\n // We only need B to make these references:\n var map = Array(endB);\n var k = 0; // Index that lags behind j\n map[0] = 0;\n for (var j = 1; j < endB; j++) {\n if (b[j] == b[k]) {\n map[j] = map[k]; // skip over the same character (optional optimisation)\n } else {\n map[j] = k;\n }\n while (k > 0 && b[j] != b[k]) {\n k = map[k];\n }\n if (b[j] == b[k]) {\n k++;\n }\n }\n // Phase 2: use these references while iterating over A\n k = 0;\n for (var i = startA; i < a.length; i++) {\n while (k > 0 && a[i] != b[k]) {\n k = map[k];\n }\n if (a[i] == b[k]) {\n k++;\n }\n }\n return k;\n}\n\n/**\n * Returns true if the string consistently uses Windows line endings.\n */\nfunction hasOnlyWinLineEndings(string) {\n return string.includes('\\r\\n') && !string.startsWith('\\n') && !string.match(/[^\\r]\\n/);\n}\n\n/**\n * Returns true if the string consistently uses Unix line endings.\n */\nfunction hasOnlyUnixLineEndings(string) {\n return !string.includes('\\r\\n') && string.includes('\\n');\n}\n\n// Based on https://en.wikipedia.org/wiki/Latin_script_in_Unicode\n//\n// Ranges and exceptions:\n// Latin-1 Supplement, 0080–00FF\n// - U+00D7 × Multiplication sign\n// - U+00F7 ÷ Division sign\n// Latin Extended-A, 0100–017F\n// Latin Extended-B, 0180–024F\n// IPA Extensions, 0250–02AF\n// Spacing Modifier Letters, 02B0–02FF\n// - U+02C7 ˇ &#711; Caron\n// - U+02D8 ˘ &#728; Breve\n// - U+02D9 ˙ &#729; Dot Above\n// - U+02DA ˚ &#730; Ring Above\n// - U+02DB ˛ &#731; Ogonek\n// - U+02DC ˜ &#732; Small Tilde\n// - U+02DD ˝ &#733; Double Acute Accent\n// Latin Extended Additional, 1E00–1EFF\nvar 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}\";\n\n// Each token is one of the following:\n// - A punctuation mark plus the surrounding whitespace\n// - A word plus the surrounding whitespace\n// - Pure whitespace (but only in the special case where this the entire text\n// is just whitespace)\n//\n// We have to include surrounding whitespace in the tokens because the two\n// alternative approaches produce horribly broken results:\n// * If we just discard the whitespace, we can't fully reproduce the original\n// text from the sequence of tokens and any attempt to render the diff will\n// get the whitespace wrong.\n// * If we have separate tokens for whitespace, then in a typical text every\n// second token will be a single space character. But this often results in\n// the optimal diff between two texts being a perverse one that preserves\n// the spaces between words but deletes and reinserts actual common words.\n// See https://github.com/kpdecker/jsdiff/issues/160#issuecomment-1866099640\n// for an example.\n//\n// Keeping the surrounding whitespace of course has implications for .equals\n// and .join, not just .tokenize.\n\n// This regex does NOT fully implement the tokenization rules described above.\n// Instead, it gives runs of whitespace their own \"token\". The tokenize method\n// then handles stitching whitespace tokens onto adjacent word or punctuation\n// tokens.\nvar tokenizeIncludingWhitespace = new RegExp(\"[\".concat(extendedWordChars, \"]+|\\\\s+|[^\").concat(extendedWordChars, \"]\"), 'ug');\nvar wordDiff = new Diff();\nwordDiff.equals = function (left, right, options) {\n if (options.ignoreCase) {\n left = left.toLowerCase();\n right = right.toLowerCase();\n }\n return left.trim() === right.trim();\n};\nwordDiff.tokenize = function (value) {\n var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n var parts;\n if (options.intlSegmenter) {\n if (options.intlSegmenter.resolvedOptions().granularity != 'word') {\n throw new Error('The segmenter passed must have a granularity of \"word\"');\n }\n parts = Array.from(options.intlSegmenter.segment(value), function (segment) {\n return segment.segment;\n });\n } else {\n parts = value.match(tokenizeIncludingWhitespace) || [];\n }\n var tokens = [];\n var prevPart = null;\n parts.forEach(function (part) {\n if (/\\s/.test(part)) {\n if (prevPart == null) {\n tokens.push(part);\n } else {\n tokens.push(tokens.pop() + part);\n }\n } else if (/\\s/.test(prevPart)) {\n if (tokens[tokens.length - 1] == prevPart) {\n tokens.push(tokens.pop() + part);\n } else {\n tokens.push(prevPart + part);\n }\n } else {\n tokens.push(part);\n }\n prevPart = part;\n });\n return tokens;\n};\nwordDiff.join = function (tokens) {\n // Tokens being joined here will always have appeared consecutively in the\n // same text, so we can simply strip off the leading whitespace from all the\n // tokens except the first (and except any whitespace-only tokens - but such\n // a token will always be the first and only token anyway) and then join them\n // and the whitespace around words and punctuation will end up correct.\n return tokens.map(function (token, i) {\n if (i == 0) {\n return token;\n } else {\n return token.replace(/^\\s+/, '');\n }\n }).join('');\n};\nwordDiff.postProcess = function (changes, options) {\n if (!changes || options.oneChangePerToken) {\n return changes;\n }\n var lastKeep = null;\n // Change objects representing any insertion or deletion since the last\n // \"keep\" change object. There can be at most one of each.\n var insertion = null;\n var deletion = null;\n changes.forEach(function (change) {\n if (change.added) {\n insertion = change;\n } else if (change.removed) {\n deletion = change;\n } else {\n if (insertion || deletion) {\n // May be false at start of text\n dedupeWhitespaceInChangeObjects(lastKeep, deletion, insertion, change);\n }\n lastKeep = change;\n insertion = null;\n deletion = null;\n }\n });\n if (insertion || deletion) {\n dedupeWhitespaceInChangeObjects(lastKeep, deletion, insertion, null);\n }\n return changes;\n};\nfunction diffWords(oldStr, newStr, options) {\n // This option has never been documented and never will be (it's clearer to\n // just call `diffWordsWithSpace` directly if you need that behavior), but\n // has existed in jsdiff for a long time, so we retain support for it here\n // for the sake of backwards compatibility.\n if ((options === null || options === void 0 ? void 0 : options.ignoreWhitespace) != null && !options.ignoreWhitespace) {\n return diffWordsWithSpace(oldStr, newStr, options);\n }\n return wordDiff.diff(oldStr, newStr, options);\n}\nfunction dedupeWhitespaceInChangeObjects(startKeep, deletion, insertion, endKeep) {\n // Before returning, we tidy up the leading and trailing whitespace of the\n // change objects to eliminate cases where trailing whitespace in one object\n // is repeated as leading whitespace in the next.\n // Below are examples of the outcomes we want here to explain the code.\n // I=insert, K=keep, D=delete\n // 1. diffing 'foo bar baz' vs 'foo baz'\n // Prior to cleanup, we have K:'foo ' D:' bar ' K:' baz'\n // After cleanup, we want: K:'foo ' D:'bar ' K:'baz'\n //\n // 2. Diffing 'foo bar baz' vs 'foo qux baz'\n // Prior to cleanup, we have K:'foo ' D:' bar ' I:' qux ' K:' baz'\n // After cleanup, we want K:'foo ' D:'bar' I:'qux' K:' baz'\n //\n // 3. Diffing 'foo\\nbar baz' vs 'foo baz'\n // Prior to cleanup, we have K:'foo ' D:'\\nbar ' K:' baz'\n // After cleanup, we want K'foo' D:'\\nbar' K:' baz'\n //\n // 4. Diffing 'foo baz' vs 'foo\\nbar baz'\n // Prior to cleanup, we have K:'foo\\n' I:'\\nbar ' K:' baz'\n // After cleanup, we ideally want K'foo' I:'\\nbar' K:' baz'\n // but don't actually manage this currently (the pre-cleanup change\n // objects don't contain enough information to make it possible).\n //\n // 5. Diffing 'foo bar baz' vs 'foo baz'\n // Prior to cleanup, we have K:'foo ' D:' bar ' K:' baz'\n // After cleanup, we want K:'foo ' D:' bar ' K:'baz'\n //\n // Our handling is unavoidably imperfect in the case where there's a single\n // indel between keeps and the whitespace has changed. For instance, consider\n // diffing 'foo\\tbar\\nbaz' vs 'foo baz'. Unless we create an extra change\n // object to represent the insertion of the space character (which isn't even\n // a token), we have no way to avoid losing information about the texts'\n // original whitespace in the result we return. Still, we do our best to\n // output something that will look sensible if we e.g. print it with\n // insertions in green and deletions in red.\n\n // Between two \"keep\" change objects (or before the first or after the last\n // change object), we can have either:\n // * A \"delete\" followed by an \"insert\"\n // * Just an \"insert\"\n // * Just a \"delete\"\n // We handle the three cases separately.\n if (deletion && insertion) {\n var oldWsPrefix = deletion.value.match(/^\\s*/)[0];\n var oldWsSuffix = deletion.value.match(/\\s*$/)[0];\n var newWsPrefix = insertion.value.match(/^\\s*/)[0];\n var newWsSuffix = insertion.value.match(/\\s*$/)[0];\n if (startKeep) {\n var commonWsPrefix = longestCommonPrefix(oldWsPrefix, newWsPrefix);\n startKeep.value = replaceSuffix(startKeep.value, newWsPrefix, commonWsPrefix);\n deletion.value = removePrefix(deletion.value, commonWsPrefix);\n insertion.value = removePrefix(insertion.value, commonWsPrefix);\n }\n if (endKeep) {\n var commonWsSuffix = longestCommonSuffix(oldWsSuffix, newWsSuffix);\n endKeep.value = replacePrefix(endKeep.value, newWsSuffix, commonWsSuffix);\n deletion.value = removeSuffix(deletion.value, commonWsSuffix);\n insertion.value = removeSuffix(insertion.value, commonWsSuffix);\n }\n } else if (insertion) {\n // The whitespaces all reflect what was in the new text rather than\n // the old, so we essentially have no information about whitespace\n // insertion or deletion. We just want to dedupe the whitespace.\n // We do that by having each change object keep its trailing\n // whitespace and deleting duplicate leading whitespace where\n // present.\n if (startKeep) {\n insertion.value = insertion.value.replace(/^\\s*/, '');\n }\n if (endKeep) {\n endKeep.value = endKeep.value.replace(/^\\s*/, '');\n }\n // otherwise we've got a deletion and no insertion\n } else if (startKeep && endKeep) {\n var newWsFull = endKeep.value.match(/^\\s*/)[0],\n delWsStart = deletion.value.match(/^\\s*/)[0],\n delWsEnd = deletion.value.match(/\\s*$/)[0];\n\n // Any whitespace that comes straight after startKeep in both the old and\n // new texts, assign to startKeep and remove from the deletion.\n var newWsStart = longestCommonPrefix(newWsFull, delWsStart);\n deletion.value = removePrefix(deletion.value, newWsStart);\n\n // Any whitespace that comes straight before endKeep in both the old and\n // new texts, and hasn't already been assigned to startKeep, assign to\n // endKeep and remove from the deletion.\n var newWsEnd = longestCommonSuffix(removePrefix(newWsFull, newWsStart), delWsEnd);\n deletion.value = removeSuffix(deletion.value, newWsEnd);\n endKeep.value = replacePrefix(endKeep.value, newWsFull, newWsEnd);\n\n // If there's any whitespace from the new text that HASN'T already been\n // assigned, assign it to the start:\n startKeep.value = replaceSuffix(startKeep.value, newWsFull, newWsFull.slice(0, newWsFull.length - newWsEnd.length));\n } else if (endKeep) {\n // We are at the start of the text. Preserve all the whitespace on\n // endKeep, and just remove whitespace from the end of deletion to the\n // extent that it overlaps with the start of endKeep.\n var endKeepWsPrefix = endKeep.value.match(/^\\s*/)[0];\n var deletionWsSuffix = deletion.value.match(/\\s*$/)[0];\n var overlap = maximumOverlap(deletionWsSuffix, endKeepWsPrefix);\n deletion.value = removeSuffix(deletion.value, overlap);\n } else if (startKeep) {\n // We are at the END of the text. Preserve all the whitespace on\n // startKeep, and just remove whitespace from the start of deletion to\n // the extent that it overlaps with the end of startKeep.\n var startKeepWsSuffix = startKeep.value.match(/\\s*$/)[0];\n var deletionWsPrefix = deletion.value.match(/^\\s*/)[0];\n var _overlap = maximumOverlap(startKeepWsSuffix, deletionWsPrefix);\n deletion.value = removePrefix(deletion.value, _overlap);\n }\n}\nvar wordWithSpaceDiff = new Diff();\nwordWithSpaceDiff.tokenize = function (value) {\n // Slightly different to the tokenizeIncludingWhitespace regex used above in\n // that this one treats each individual newline as a distinct tokens, rather\n // than merging them into other surrounding whitespace. This was requested\n // in https://github.com/kpdecker/jsdiff/issues/180 &\n // https://github.com/kpdecker/jsdiff/issues/211\n var regex = new RegExp(\"(\\\\r?\\\\n)|[\".concat(extendedWordChars, \"]+|[^\\\\S\\\\n\\\\r]+|[^\").concat(extendedWordChars, \"]\"), 'ug');\n return value.match(regex) || [];\n};\nfunction diffWordsWithSpace(oldStr, newStr, options) {\n return wordWithSpaceDiff.diff(oldStr, newStr, options);\n}\n\nfunction generateOptions(options, defaults) {\n if (typeof options === 'function') {\n defaults.callback = options;\n } else if (options) {\n for (var name in options) {\n /* istanbul ignore else */\n if (options.hasOwnProperty(name)) {\n defaults[name] = options[name];\n }\n }\n }\n return defaults;\n}\n\nvar lineDiff = new Diff();\nlineDiff.tokenize = function (value, options) {\n if (options.stripTrailingCr) {\n // remove one \\r before \\n to match GNU diff's --strip-trailing-cr behavior\n value = value.replace(/\\r\\n/g, '\\n');\n }\n var retLines = [],\n linesAndNewlines = value.split(/(\\n|\\r\\n)/);\n\n // Ignore the final empty token that occurs if the string ends with a new line\n if (!linesAndNewlines[linesAndNewlines.length - 1]) {\n linesAndNewlines.pop();\n }\n\n // Merge the content and line separators into single tokens\n for (var i = 0; i < linesAndNewlines.length; i++) {\n var line = linesAndNewlines[i];\n if (i % 2 && !options.newlineIsToken) {\n retLines[retLines.length - 1] += line;\n } else {\n retLines.push(line);\n }\n }\n return retLines;\n};\nlineDiff.equals = function (left, right, options) {\n // If we're ignoring whitespace, we need to normalise lines by stripping\n // whitespace before checking equality. (This has an annoying interaction\n // with newlineIsToken that requires special handling: if newlines get their\n // own token, then we DON'T want to trim the *newline* tokens down to empty\n // strings, since this would cause us to treat whitespace-only line content\n // as equal to a separator between lines, which would be weird and\n // inconsistent with the documented behavior of the options.)\n if (options.ignoreWhitespace) {\n if (!options.newlineIsToken || !left.includes('\\n')) {\n left = left.trim();\n }\n if (!options.newlineIsToken || !right.includes('\\n')) {\n right = right.trim();\n }\n } else if (options.ignoreNewlineAtEof && !options.newlineIsToken) {\n if (left.endsWith('\\n')) {\n left = left.slice(0, -1);\n }\n if (right.endsWith('\\n')) {\n right = right.slice(0, -1);\n }\n }\n return Diff.prototype.equals.call(this, left, right, options);\n};\nfunction diffLines(oldStr, newStr, callback) {\n return lineDiff.diff(oldStr, newStr, callback);\n}\n\n// Kept for backwards compatibility. This is a rather arbitrary wrapper method\n// that just calls `diffLines` with `ignoreWhitespace: true`. It's confusing to\n// have two ways to do exactly the same thing in the API, so we no longer\n// document this one (library users should explicitly use `diffLines` with\n// `ignoreWhitespace: true` instead) but we keep it around to maintain\n// compatibility with code that used old versions.\nfunction diffTrimmedLines(oldStr, newStr, callback) {\n var options = generateOptions(callback, {\n ignoreWhitespace: true\n });\n return lineDiff.diff(oldStr, newStr, options);\n}\n\nvar sentenceDiff = new Diff();\nsentenceDiff.tokenize = function (value) {\n return value.split(/(\\S.+?[.!?])(?=\\s+|$)/);\n};\nfunction diffSentences(oldStr, newStr, callback) {\n return sentenceDiff.diff(oldStr, newStr, callback);\n}\n\nvar cssDiff = new Diff();\ncssDiff.tokenize = function (value) {\n return value.split(/([{}:;,]|\\s+)/);\n};\nfunction diffCss(oldStr, newStr, callback) {\n return cssDiff.diff(oldStr, newStr, callback);\n}\n\nfunction ownKeys(e, r) {\n var t = Object.keys(e);\n if (Object.getOwnPropertySymbols) {\n var o = Object.getOwnPropertySymbols(e);\n r && (o = o.filter(function (r) {\n return Object.getOwnPropertyDescriptor(e, r).enumerable;\n })), t.push.apply(t, o);\n }\n return t;\n}\nfunction _objectSpread2(e) {\n for (var r = 1; r < arguments.length; r++) {\n var t = null != arguments[r] ? arguments[r] : {};\n r % 2 ? ownKeys(Object(t), !0).forEach(function (r) {\n _defineProperty(e, r, t[r]);\n }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) {\n Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r));\n });\n }\n return e;\n}\nfunction _toPrimitive(t, r) {\n if (\"object\" != typeof t || !t) return t;\n var e = t[Symbol.toPrimitive];\n if (void 0 !== e) {\n var i = e.call(t, r || \"default\");\n if (\"object\" != typeof i) return i;\n throw new TypeError(\"@@toPrimitive must return a primitive value.\");\n }\n return (\"string\" === r ? String : Number)(t);\n}\nfunction _toPropertyKey(t) {\n var i = _toPrimitive(t, \"string\");\n return \"symbol\" == typeof i ? i : i + \"\";\n}\nfunction _typeof(o) {\n \"@babel/helpers - typeof\";\n\n return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) {\n return typeof o;\n } : function (o) {\n return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o;\n }, _typeof(o);\n}\nfunction _defineProperty(obj, key, value) {\n key = _toPropertyKey(key);\n if (key in obj) {\n Object.defineProperty(obj, key, {\n value: value,\n enumerable: true,\n configurable: true,\n writable: true\n });\n } else {\n obj[key] = value;\n }\n return obj;\n}\nfunction _toConsumableArray(arr) {\n return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();\n}\nfunction _arrayWithoutHoles(arr) {\n if (Array.isArray(arr)) return _arrayLikeToArray(arr);\n}\nfunction _iterableToArray(iter) {\n if (typeof Symbol !== \"undefined\" && iter[Symbol.iterator] != null || iter[\"@@iterator\"] != null) return Array.from(iter);\n}\nfunction _unsupportedIterableToArray(o, minLen) {\n if (!o) return;\n if (typeof o === \"string\") return _arrayLikeToArray(o, minLen);\n var n = Object.prototype.toString.call(o).slice(8, -1);\n if (n === \"Object\" && o.constructor) n = o.constructor.name;\n if (n === \"Map\" || n === \"Set\") return Array.from(o);\n if (n === \"Arguments\" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);\n}\nfunction _arrayLikeToArray(arr, len) {\n if (len == null || len > arr.length) len = arr.length;\n for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];\n return arr2;\n}\nfunction _nonIterableSpread() {\n throw new TypeError(\"Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\");\n}\n\nvar jsonDiff = new Diff();\n// Discriminate between two lines of pretty-printed, serialized JSON where one of them has a\n// dangling comma and the other doesn't. Turns out including the dangling comma yields the nicest output:\njsonDiff.useLongestToken = true;\njsonDiff.tokenize = lineDiff.tokenize;\njsonDiff.castInput = function (value, options) {\n var undefinedReplacement = options.undefinedReplacement,\n _options$stringifyRep = options.stringifyReplacer,\n stringifyReplacer = _options$stringifyRep === void 0 ? function (k, v) {\n return typeof v === 'undefined' ? undefinedReplacement : v;\n } : _options$stringifyRep;\n return typeof value === 'string' ? value : JSON.stringify(canonicalize(value, null, null, stringifyReplacer), stringifyReplacer, ' ');\n};\njsonDiff.equals = function (left, right, options) {\n return Diff.prototype.equals.call(jsonDiff, left.replace(/,([\\r\\n])/g, '$1'), right.replace(/,([\\r\\n])/g, '$1'), options);\n};\nfunction diffJson(oldObj, newObj, options) {\n return jsonDiff.diff(oldObj, newObj, options);\n}\n\n// This function handles the presence of circular references by bailing out when encountering an\n// object that is already on the \"stack\" of items being processed. Accepts an optional replacer\nfunction canonicalize(obj, stack, replacementStack, replacer, key) {\n stack = stack || [];\n replacementStack = replacementStack || [];\n if (replacer) {\n obj = replacer(key, obj);\n }\n var i;\n for (i = 0; i < stack.length; i += 1) {\n if (stack[i] === obj) {\n return replacementStack[i];\n }\n }\n var canonicalizedObj;\n if ('[object Array]' === Object.prototype.toString.call(obj)) {\n stack.push(obj);\n canonicalizedObj = new Array(obj.length);\n replacementStack.push(canonicalizedObj);\n for (i = 0; i < obj.length; i += 1) {\n canonicalizedObj[i] = canonicalize(obj[i], stack, replacementStack, replacer, key);\n }\n stack.pop();\n replacementStack.pop();\n return canonicalizedObj;\n }\n if (obj && obj.toJSON) {\n obj = obj.toJSON();\n }\n if (_typeof(obj) === 'object' && obj !== null) {\n stack.push(obj);\n canonicalizedObj = {};\n replacementStack.push(canonicalizedObj);\n var sortedKeys = [],\n _key;\n for (_key in obj) {\n /* istanbul ignore else */\n if (Object.prototype.hasOwnProperty.call(obj, _key)) {\n sortedKeys.push(_key);\n }\n }\n sortedKeys.sort();\n for (i = 0; i < sortedKeys.length; i += 1) {\n _key = sortedKeys[i];\n canonicalizedObj[_key] = canonicalize(obj[_key], stack, replacementStack, replacer, _key);\n }\n stack.pop();\n replacementStack.pop();\n } else {\n canonicalizedObj = obj;\n }\n return canonicalizedObj;\n}\n\nvar arrayDiff = new Diff();\narrayDiff.tokenize = function (value) {\n return value.slice();\n};\narrayDiff.join = arrayDiff.removeEmpty = function (value) {\n return value;\n};\nfunction diffArrays(oldArr, newArr, callback) {\n return arrayDiff.diff(oldArr, newArr, callback);\n}\n\nfunction unixToWin(patch) {\n if (Array.isArray(patch)) {\n return patch.map(unixToWin);\n }\n return _objectSpread2(_objectSpread2({}, patch), {}, {\n hunks: patch.hunks.map(function (hunk) {\n return _objectSpread2(_objectSpread2({}, hunk), {}, {\n lines: hunk.lines.map(function (line, i) {\n var _hunk$lines;\n return line.startsWith('\\\\') || line.endsWith('\\r') || (_hunk$lines = hunk.lines[i + 1]) !== null && _hunk$lines !== void 0 && _hunk$lines.startsWith('\\\\') ? line : line + '\\r';\n })\n });\n })\n });\n}\nfunction winToUnix(patch) {\n if (Array.isArray(patch)) {\n return patch.map(winToUnix);\n }\n return _objectSpread2(_objectSpread2({}, patch), {}, {\n hunks: patch.hunks.map(function (hunk) {\n return _objectSpread2(_objectSpread2({}, hunk), {}, {\n lines: hunk.lines.map(function (line) {\n return line.endsWith('\\r') ? line.substring(0, line.length - 1) : line;\n })\n });\n })\n });\n}\n\n/**\n * Returns true if the patch consistently uses Unix line endings (or only involves one line and has\n * no line endings).\n */\nfunction isUnix(patch) {\n if (!Array.isArray(patch)) {\n patch = [patch];\n }\n return !patch.some(function (index) {\n return index.hunks.some(function (hunk) {\n return hunk.lines.some(function (line) {\n return !line.startsWith('\\\\') && line.endsWith('\\r');\n });\n });\n });\n}\n\n/**\n * Returns true if the patch uses Windows line endings and only Windows line endings.\n */\nfunction isWin(patch) {\n if (!Array.isArray(patch)) {\n patch = [patch];\n }\n return patch.some(function (index) {\n return index.hunks.some(function (hunk) {\n return hunk.lines.some(function (line) {\n return line.endsWith('\\r');\n });\n });\n }) && patch.every(function (index) {\n return index.hunks.every(function (hunk) {\n return hunk.lines.every(function (line, i) {\n var _hunk$lines2;\n return line.startsWith('\\\\') || line.endsWith('\\r') || ((_hunk$lines2 = hunk.lines[i + 1]) === null || _hunk$lines2 === void 0 ? void 0 : _hunk$lines2.startsWith('\\\\'));\n });\n });\n });\n}\n\nfunction parsePatch(uniDiff) {\n var diffstr = uniDiff.split(/\\n/),\n list = [],\n i = 0;\n function parseIndex() {\n var index = {};\n list.push(index);\n\n // Parse diff metadata\n while (i < diffstr.length) {\n var line = diffstr[i];\n\n // File header found, end parsing diff metadata\n if (/^(\\-\\-\\-|\\+\\+\\+|@@)\\s/.test(line)) {\n break;\n }\n\n // Diff index\n var header = /^(?:Index:|diff(?: -r \\w+)+)\\s+(.+?)\\s*$/.exec(line);\n if (header) {\n index.index = header[1];\n }\n i++;\n }\n\n // Parse file headers if they are defined. Unified diff requires them, but\n // there's no technical issues to have an isolated hunk without file header\n parseFileHeader(index);\n parseFileHeader(index);\n\n // Parse hunks\n index.hunks = [];\n while (i < diffstr.length) {\n var _line = diffstr[i];\n if (/^(Index:\\s|diff\\s|\\-\\-\\-\\s|\\+\\+\\+\\s|===================================================================)/.test(_line)) {\n break;\n } else if (/^@@/.test(_line)) {\n index.hunks.push(parseHunk());\n } else if (_line) {\n throw new Error('Unknown line ' + (i + 1) + ' ' + JSON.stringify(_line));\n } else {\n i++;\n }\n }\n }\n\n // Parses the --- and +++ headers, if none are found, no lines\n // are consumed.\n function parseFileHeader(index) {\n var fileHeader = /^(---|\\+\\+\\+)\\s+(.*)\\r?$/.exec(diffstr[i]);\n if (fileHeader) {\n var keyPrefix = fileHeader[1] === '---' ? 'old' : 'new';\n var data = fileHeader[2].split('\\t', 2);\n var fileName = data[0].replace(/\\\\\\\\/g, '\\\\');\n if (/^\".*\"$/.test(fileName)) {\n fileName = fileName.substr(1, fileName.length - 2);\n }\n index[keyPrefix + 'FileName'] = fileName;\n index[keyPrefix + 'Header'] = (data[1] || '').trim();\n i++;\n }\n }\n\n // Parses a hunk\n // This assumes that we are at the start of a hunk.\n function parseHunk() {\n var chunkHeaderIndex = i,\n chunkHeaderLine = diffstr[i++],\n chunkHeader = chunkHeaderLine.split(/@@ -(\\d+)(?:,(\\d+))? \\+(\\d+)(?:,(\\d+))? @@/);\n var hunk = {\n oldStart: +chunkHeader[1],\n oldLines: typeof chunkHeader[2] === 'undefined' ? 1 : +chunkHeader[2],\n newStart: +chunkHeader[3],\n newLines: typeof chunkHeader[4] === 'undefined' ? 1 : +chunkHeader[4],\n lines: []\n };\n\n // Unified Diff Format quirk: If the chunk size is 0,\n // the first number is one lower than one would expect.\n // https://www.artima.com/weblogs/viewpost.jsp?thread=164293\n if (hunk.oldLines === 0) {\n hunk.oldStart += 1;\n }\n if (hunk.newLines === 0) {\n hunk.newStart += 1;\n }\n var addCount = 0,\n removeCount = 0;\n for (; i < diffstr.length && (removeCount < hunk.oldLines || addCount < hunk.newLines || (_diffstr$i = diffstr[i]) !== null && _diffstr$i !== void 0 && _diffstr$i.startsWith('\\\\')); i++) {\n var _diffstr$i;\n var operation = diffstr[i].length == 0 && i != diffstr.length - 1 ? ' ' : diffstr[i][0];\n if (operation === '+' || operation === '-' || operation === ' ' || operation === '\\\\') {\n hunk.lines.push(diffstr[i]);\n if (operation === '+') {\n addCount++;\n } else if (operation === '-') {\n removeCount++;\n } else if (operation === ' ') {\n addCount++;\n removeCount++;\n }\n } else {\n throw new Error(\"Hunk at line \".concat(chunkHeaderIndex + 1, \" contained invalid line \").concat(diffstr[i]));\n }\n }\n\n // Handle the empty block count case\n if (!addCount && hunk.newLines === 1) {\n hunk.newLines = 0;\n }\n if (!removeCount && hunk.oldLines === 1) {\n hunk.oldLines = 0;\n }\n\n // Perform sanity checking\n if (addCount !== hunk.newLines) {\n throw new Error('Added line count did not match for hunk at line ' + (chunkHeaderIndex + 1));\n }\n if (removeCount !== hunk.oldLines) {\n throw new Error('Removed line count did not match for hunk at line ' + (chunkHeaderIndex + 1));\n }\n return hunk;\n }\n while (i < diffstr.length) {\n parseIndex();\n }\n return list;\n}\n\n// Iterator that traverses in the range of [min, max], stepping\n// by distance from a given start position. I.e. for [0, 4], with\n// start of 2, this will iterate 2, 3, 1, 4, 0.\nfunction distanceIterator (start, minLine, maxLine) {\n var wantForward = true,\n backwardExhausted = false,\n forwardExhausted = false,\n localOffset = 1;\n return function iterator() {\n if (wantForward && !forwardExhausted) {\n if (backwardExhausted) {\n localOffset++;\n } else {\n wantForward = false;\n }\n\n // Check if trying to fit beyond text length, and if not, check it fits\n // after offset location (or desired location on first iteration)\n if (start + localOffset <= maxLine) {\n return start + localOffset;\n }\n forwardExhausted = true;\n }\n if (!backwardExhausted) {\n if (!forwardExhausted) {\n wantForward = true;\n }\n\n // Check if trying to fit before text beginning, and if not, check it fits\n // before offset location\n if (minLine <= start - localOffset) {\n return start - localOffset++;\n }\n backwardExhausted = true;\n return iterator();\n }\n\n // We tried to fit hunk before text beginning and beyond text length, then\n // hunk can't fit on the text. Return undefined\n };\n}\n\nfunction applyPatch(source, uniDiff) {\n var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};\n if (typeof uniDiff === 'string') {\n uniDiff = parsePatch(uniDiff);\n }\n if (Array.isArray(uniDiff)) {\n if (uniDiff.length > 1) {\n throw new Error('applyPatch only works with a single input.');\n }\n uniDiff = uniDiff[0];\n }\n if (options.autoConvertLineEndings || options.autoConvertLineEndings == null) {\n if (hasOnlyWinLineEndings(source) && isUnix(uniDiff)) {\n uniDiff = unixToWin(uniDiff);\n } else if (hasOnlyUnixLineEndings(source) && isWin(uniDiff)) {\n uniDiff = winToUnix(uniDiff);\n }\n }\n\n // Apply the diff to the input\n var lines = source.split('\\n'),\n hunks = uniDiff.hunks,\n compareLine = options.compareLine || function (lineNumber, line, operation, patchContent) {\n return line === patchContent;\n },\n fuzzFactor = options.fuzzFactor || 0,\n minLine = 0;\n if (fuzzFactor < 0 || !Number.isInteger(fuzzFactor)) {\n throw new Error('fuzzFactor must be a non-negative integer');\n }\n\n // Special case for empty patch.\n if (!hunks.length) {\n return source;\n }\n\n // Before anything else, handle EOFNL insertion/removal. If the patch tells us to make a change\n // to the EOFNL that is redundant/impossible - i.e. to remove a newline that's not there, or add a\n // newline that already exists - then we either return false and fail to apply the patch (if\n // fuzzFactor is 0) or simply ignore the problem and do nothing (if fuzzFactor is >0).\n // If we do need to remove/add a newline at EOF, this will always be in the final hunk:\n var prevLine = '',\n removeEOFNL = false,\n addEOFNL = false;\n for (var i = 0; i < hunks[hunks.length - 1].lines.length; i++) {\n var line = hunks[hunks.length - 1].lines[i];\n if (line[0] == '\\\\') {\n if (prevLine[0] == '+') {\n removeEOFNL = true;\n } else if (prevLine[0] == '-') {\n addEOFNL = true;\n }\n }\n prevLine = line;\n }\n if (removeEOFNL) {\n if (addEOFNL) {\n // This means the final line gets changed but doesn't have a trailing newline in either the\n // original or patched version. In that case, we do nothing if fuzzFactor > 0, and if\n // fuzzFactor is 0, we simply validate that the source file has no trailing newline.\n if (!fuzzFactor && lines[lines.length - 1] == '') {\n return false;\n }\n } else if (lines[lines.length - 1] == '') {\n lines.pop();\n } else if (!fuzzFactor) {\n return false;\n }\n } else if (addEOFNL) {\n if (lines[lines.length - 1] != '') {\n lines.push('');\n } else if (!fuzzFactor) {\n return false;\n }\n }\n\n /**\n * Checks if the hunk can be made to fit at the provided location with at most `maxErrors`\n * insertions, substitutions, or deletions, while ensuring also that:\n * - lines deleted in the hunk match exactly, and\n * - wherever an insertion operation or block of insertion operations appears in the hunk, the\n * immediately preceding and following lines of context match exactly\n *\n * `toPos` should be set such that lines[toPos] is meant to match hunkLines[0].\n *\n * If the hunk can be applied, returns an object with properties `oldLineLastI` and\n * `replacementLines`. Otherwise, returns null.\n */\n function applyHunk(hunkLines, toPos, maxErrors) {\n var hunkLinesI = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0;\n var lastContextLineMatched = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : true;\n var patchedLines = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : [];\n var patchedLinesLength = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : 0;\n var nConsecutiveOldContextLines = 0;\n var nextContextLineMustMatch = false;\n for (; hunkLinesI < hunkLines.length; hunkLinesI++) {\n var hunkLine = hunkLines[hunkLinesI],\n operation = hunkLine.length > 0 ? hunkLine[0] : ' ',\n content = hunkLine.length > 0 ? hunkLine.substr(1) : hunkLine;\n if (operation === '-') {\n if (compareLine(toPos + 1, lines[toPos], operation, content)) {\n toPos++;\n nConsecutiveOldContextLines = 0;\n } else {\n if (!maxErrors || lines[toPos] == null) {\n return null;\n }\n patchedLines[patchedLinesLength] = lines[toPos];\n return applyHunk(hunkLines, toPos + 1, maxErrors - 1, hunkLinesI, false, patchedLines, patchedLinesLength + 1);\n }\n }\n if (operation === '+') {\n if (!lastContextLineMatched) {\n return null;\n }\n patchedLines[patchedLinesLength] = content;\n patchedLinesLength++;\n nConsecutiveOldContextLines = 0;\n nextContextLineMustMatch = true;\n }\n if (operation === ' ') {\n nConsecutiveOldContextLines++;\n patchedLines[patchedLinesLength] = lines[toPos];\n if (compareLine(toPos + 1, lines[toPos], operation, content)) {\n patchedLinesLength++;\n lastContextLineMatched = true;\n nextContextLineMustMatch = false;\n toPos++;\n } else {\n if (nextContextLineMustMatch || !maxErrors) {\n return null;\n }\n\n // Consider 3 possibilities in sequence:\n // 1. lines contains a *substitution* not included in the patch context, or\n // 2. lines contains an *insertion* not included in the patch context, or\n // 3. lines contains a *deletion* not included in the patch context\n // The first two options are of course only possible if the line from lines is non-null -\n // i.e. only option 3 is possible if we've overrun the end of the old file.\n return lines[toPos] && (applyHunk(hunkLines, toPos + 1, maxErrors - 1, hunkLinesI + 1, false, patchedLines, patchedLinesLength + 1) || applyHunk(hunkLines, toPos + 1, maxErrors - 1, hunkLinesI, false, patchedLines, patchedLinesLength + 1)) || applyHunk(hunkLines, toPos, maxErrors - 1, hunkLinesI + 1, false, patchedLines, patchedLinesLength);\n }\n }\n }\n\n // Before returning, trim any unmodified context lines off the end of patchedLines and reduce\n // toPos (and thus oldLineLastI) accordingly. This allows later hunks to be applied to a region\n // that starts in this hunk's trailing context.\n patchedLinesLength -= nConsecutiveOldContextLines;\n toPos -= nConsecutiveOldContextLines;\n patchedLines.length = patchedLinesLength;\n return {\n patchedLines: patchedLines,\n oldLineLastI: toPos - 1\n };\n }\n var resultLines = [];\n\n // Search best fit offsets for each hunk based on the previous ones\n var prevHunkOffset = 0;\n for (var _i = 0; _i < hunks.length; _i++) {\n var hunk = hunks[_i];\n var hunkResult = void 0;\n var maxLine = lines.length - hunk.oldLines + fuzzFactor;\n var toPos = void 0;\n for (var maxErrors = 0; maxErrors <= fuzzFactor; maxErrors++) {\n toPos = hunk.oldStart + prevHunkOffset - 1;\n var iterator = distanceIterator(toPos, minLine, maxLine);\n for (; toPos !== undefined; toPos = iterator()) {\n hunkResult = applyHunk(hunk.lines, toPos, maxErrors);\n if (hunkResult) {\n break;\n }\n }\n if (hunkResult) {\n break;\n }\n }\n if (!hunkResult) {\n return false;\n }\n\n // Copy everything from the end of where we applied the last hunk to the start of this hunk\n for (var _i2 = minLine; _i2 < toPos; _i2++) {\n resultLines.push(lines[_i2]);\n }\n\n // Add the lines produced by applying the hunk:\n for (var _i3 = 0; _i3 < hunkResult.patchedLines.length; _i3++) {\n var _line = hunkResult.patchedLines[_i3];\n resultLines.push(_line);\n }\n\n // Set lower text limit to end of the current hunk, so next ones don't try\n // to fit over already patched text\n minLine = hunkResult.oldLineLastI + 1;\n\n // Note the offset between where the patch said the hunk should've applied and where we\n // applied it, so we can adjust future hunks accordingly:\n prevHunkOffset = toPos + 1 - hunk.oldStart;\n }\n\n // Copy over the rest of the lines from the old text\n for (var _i4 = minLine; _i4 < lines.length; _i4++) {\n resultLines.push(lines[_i4]);\n }\n return resultLines.join('\\n');\n}\n\n// Wrapper that supports multiple file patches via callbacks.\nfunction applyPatches(uniDiff, options) {\n if (typeof uniDiff === 'string') {\n uniDiff = parsePatch(uniDiff);\n }\n var currentIndex = 0;\n function processIndex() {\n var index = uniDiff[currentIndex++];\n if (!index) {\n return options.complete();\n }\n options.loadFile(index, function (err, data) {\n if (err) {\n return options.complete(err);\n }\n var updatedContent = applyPatch(data, index, options);\n options.patched(index, updatedContent, function (err) {\n if (err) {\n return options.complete(err);\n }\n processIndex();\n });\n });\n }\n processIndex();\n}\n\nfunction structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) {\n if (!options) {\n options = {};\n }\n if (typeof options === 'function') {\n options = {\n callback: options\n };\n }\n if (typeof options.context === 'undefined') {\n options.context = 4;\n }\n if (options.newlineIsToken) {\n throw new Error('newlineIsToken may not be used with patch-generation functions, only with diffing functions');\n }\n if (!options.callback) {\n return diffLinesResultToPatch(diffLines(oldStr, newStr, options));\n } else {\n var _options = options,\n _callback = _options.callback;\n diffLines(oldStr, newStr, _objectSpread2(_objectSpread2({}, options), {}, {\n callback: function callback(diff) {\n var patch = diffLinesResultToPatch(diff);\n _callback(patch);\n }\n }));\n }\n function diffLinesResultToPatch(diff) {\n // STEP 1: Build up the patch with no \"\\" lines and with the arrays\n // of lines containing trailing newline characters. We'll tidy up later...\n\n if (!diff) {\n return;\n }\n diff.push({\n value: '',\n lines: []\n }); // Append an empty value to make cleanup easier\n\n function contextLines(lines) {\n return lines.map(function (entry) {\n return ' ' + entry;\n });\n }\n var hunks = [];\n var oldRangeStart = 0,\n newRangeStart = 0,\n curRange = [],\n oldLine = 1,\n newLine = 1;\n var _loop = function _loop() {\n var current = diff[i],\n lines = current.lines || splitLines(current.value);\n current.lines = lines;\n if (current.added || current.removed) {\n var _curRange;\n // If we have previous context, start with that\n if (!oldRangeStart) {\n var prev = diff[i - 1];\n oldRangeStart = oldLine;\n newRangeStart = newLine;\n if (prev) {\n curRange = options.context > 0 ? contextLines(prev.lines.slice(-options.context)) : [];\n oldRangeStart -= curRange.length;\n newRangeStart -= curRange.length;\n }\n }\n\n // Output our changes\n (_curRange = curRange).push.apply(_curRange, _toConsumableArray(lines.map(function (entry) {\n return (current.added ? '+' : '-') + entry;\n })));\n\n // Track the updated file position\n if (current.added) {\n newLine += lines.length;\n } else {\n oldLine += lines.length;\n }\n } else {\n // Identical context lines. Track line changes\n if (oldRangeStart) {\n // Close out any changes that have been output (or join overlapping)\n if (lines.length <= options.context * 2 && i < diff.length - 2) {\n var _curRange2;\n // Overlapping\n (_curRange2 = curRange).push.apply(_curRange2, _toConsumableArray(contextLines(lines)));\n } else {\n var _curRange3;\n // end the range and output\n var contextSize = Math.min(lines.length, options.context);\n (_curRange3 = curRange).push.apply(_curRange3, _toConsumableArray(contextLines(lines.slice(0, contextSize))));\n var _hunk = {\n oldStart: oldRangeStart,\n oldLines: oldLine - oldRangeStart + contextSize,\n newStart: newRangeStart,\n newLines: newLine - newRangeStart + contextSize,\n lines: curRange\n };\n hunks.push(_hunk);\n oldRangeStart = 0;\n newRangeStart = 0;\n curRange = [];\n }\n }\n oldLine += lines.length;\n newLine += lines.length;\n }\n };\n for (var i = 0; i < diff.length; i++) {\n _loop();\n }\n\n // Step 2: eliminate the trailing `\\n` from each line of each hunk, and, where needed, add\n // \"\\".\n for (var _i = 0, _hunks = hunks; _i < _hunks.length; _i++) {\n var hunk = _hunks[_i];\n for (var _i2 = 0; _i2 < hunk.lines.length; _i2++) {\n if (hunk.lines[_i2].endsWith('\\n')) {\n hunk.lines[_i2] = hunk.lines[_i2].slice(0, -1);\n } else {\n hunk.lines.splice(_i2 + 1, 0, '\\\');\n _i2++; // Skip the line we just added, then continue iterating\n }\n }\n }\n return {\n oldFileName: oldFileName,\n newFileName: newFileName,\n oldHeader: oldHeader,\n newHeader: newHeader,\n hunks: hunks\n };\n }\n}\nfunction formatPatch(diff) {\n if (Array.isArray(diff)) {\n return diff.map(formatPatch).join('\\n');\n }\n var ret = [];\n if (diff.oldFileName == diff.newFileName) {\n ret.push('Index: ' + diff.oldFileName);\n }\n ret.push('===================================================================');\n ret.push('--- ' + diff.oldFileName + (typeof diff.oldHeader === 'undefined' ? '' : '\\t' + diff.oldHeader));\n ret.push('+++ ' + diff.newFileName + (typeof diff.newHeader === 'undefined' ? '' : '\\t' + diff.newHeader));\n for (var i = 0; i < diff.hunks.length; i++) {\n var hunk = diff.hunks[i];\n // Unified Diff Format quirk: If the chunk size is 0,\n // the first number is one lower than one would expect.\n // https://www.artima.com/weblogs/viewpost.jsp?thread=164293\n if (hunk.oldLines === 0) {\n hunk.oldStart -= 1;\n }\n if (hunk.newLines === 0) {\n hunk.newStart -= 1;\n }\n ret.push('@@ -' + hunk.oldStart + ',' + hunk.oldLines + ' +' + hunk.newStart + ',' + hunk.newLines + ' @@');\n ret.push.apply(ret, hunk.lines);\n }\n return ret.join('\\n') + '\\n';\n}\nfunction createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) {\n var _options2;\n if (typeof options === 'function') {\n options = {\n callback: options\n };\n }\n if (!((_options2 = options) !== null && _options2 !== void 0 && _options2.callback)) {\n var patchObj = structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options);\n if (!patchObj) {\n return;\n }\n return formatPatch(patchObj);\n } else {\n var _options3 = options,\n _callback2 = _options3.callback;\n structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, _objectSpread2(_objectSpread2({}, options), {}, {\n callback: function callback(patchObj) {\n if (!patchObj) {\n _callback2();\n } else {\n _callback2(formatPatch(patchObj));\n }\n }\n }));\n }\n}\nfunction createPatch(fileName, oldStr, newStr, oldHeader, newHeader, options) {\n return createTwoFilesPatch(fileName, fileName, oldStr, newStr, oldHeader, newHeader, options);\n}\n\n/**\n * Split `text` into an array of lines, including the trailing newline character (where present)\n */\nfunction splitLines(text) {\n var hasTrailingNl = text.endsWith('\\n');\n var result = text.split('\\n').map(function (line) {\n return line + '\\n';\n });\n if (hasTrailingNl) {\n result.pop();\n } else {\n result.push(result.pop().slice(0, -1));\n }\n return result;\n}\n\nfunction arrayEqual(a, b) {\n if (a.length !== b.length) {\n return false;\n }\n return arrayStartsWith(a, b);\n}\nfunction arrayStartsWith(array, start) {\n if (start.length > array.length) {\n return false;\n }\n for (var i = 0; i < start.length; i++) {\n if (start[i] !== array[i]) {\n return false;\n }\n }\n return true;\n}\n\nfunction calcLineCount(hunk) {\n var _calcOldNewLineCount = calcOldNewLineCount(hunk.lines),\n oldLines = _calcOldNewLineCount.oldLines,\n newLines = _calcOldNewLineCount.newLines;\n if (oldLines !== undefined) {\n hunk.oldLines = oldLines;\n } else {\n delete hunk.oldLines;\n }\n if (newLines !== undefined) {\n hunk.newLines = newLines;\n } else {\n delete hunk.newLines;\n }\n}\nfunction merge(mine, theirs, base) {\n mine = loadPatch(mine, base);\n theirs = loadPatch(theirs, base);\n var ret = {};\n\n // For index we just let it pass through as it doesn't have any necessary meaning.\n // Leaving sanity checks on this to the API consumer that may know more about the\n // meaning in their own context.\n if (mine.index || theirs.index) {\n ret.index = mine.index || theirs.index;\n }\n if (mine.newFileName || theirs.newFileName) {\n if (!fileNameChanged(mine)) {\n // No header or no change in ours, use theirs (and ours if theirs does not exist)\n ret.oldFileName = theirs.oldFileName || mine.oldFileName;\n ret.newFileName = theirs.newFileName || mine.newFileName;\n ret.oldHeader = theirs.oldHeader || mine.oldHeader;\n ret.newHeader = theirs.newHeader || mine.newHeader;\n } else if (!fileNameChanged(theirs)) {\n // No header or no change in theirs, use ours\n ret.oldFileName = mine.oldFileName;\n ret.newFileName = mine.newFileName;\n ret.oldHeader = mine.oldHeader;\n ret.newHeader = mine.newHeader;\n } else {\n // Both changed... figure it out\n ret.oldFileName = selectField(ret, mine.oldFileName, theirs.oldFileName);\n ret.newFileName = selectField(ret, mine.newFileName, theirs.newFileName);\n ret.oldHeader = selectField(ret, mine.oldHeader, theirs.oldHeader);\n ret.newHeader = selectField(ret, mine.newHeader, theirs.newHeader);\n }\n }\n ret.hunks = [];\n var mineIndex = 0,\n theirsIndex = 0,\n mineOffset = 0,\n theirsOffset = 0;\n while (mineIndex < mine.hunks.length || theirsIndex < theirs.hunks.length) {\n var mineCurrent = mine.hunks[mineIndex] || {\n oldStart: Infinity\n },\n theirsCurrent = theirs.hunks[theirsIndex] || {\n oldStart: Infinity\n };\n if (hunkBefore(mineCurrent, theirsCurrent)) {\n // This patch does not overlap with any of the others, yay.\n ret.hunks.push(cloneHunk(mineCurrent, mineOffset));\n mineIndex++;\n theirsOffset += mineCurrent.newLines - mineCurrent.oldLines;\n } else if (hunkBefore(theirsCurrent, mineCurrent)) {\n // This patch does not overlap with any of the others, yay.\n ret.hunks.push(cloneHunk(theirsCurrent, theirsOffset));\n theirsIndex++;\n mineOffset += theirsCurrent.newLines - theirsCurrent.oldLines;\n } else {\n // Overlap, merge as best we can\n var mergedHunk = {\n oldStart: Math.min(mineCurrent.oldStart, theirsCurrent.oldStart),\n oldLines: 0,\n newStart: Math.min(mineCurrent.newStart + mineOffset, theirsCurrent.oldStart + theirsOffset),\n newLines: 0,\n lines: []\n };\n mergeLines(mergedHunk, mineCurrent.oldStart, mineCurrent.lines, theirsCurrent.oldStart, theirsCurrent.lines);\n theirsIndex++;\n mineIndex++;\n ret.hunks.push(mergedHunk);\n }\n }\n return ret;\n}\nfunction loadPatch(param, base) {\n if (typeof param === 'string') {\n if (/^@@/m.test(param) || /^Index:/m.test(param)) {\n return parsePatch(param)[0];\n }\n if (!base) {\n throw new Error('Must provide a base reference or pass in a patch');\n }\n return structuredPatch(undefined, undefined, base, param);\n }\n return param;\n}\nfunction fileNameChanged(patch) {\n return patch.newFileName && patch.newFileName !== patch.oldFileName;\n}\nfunction selectField(index, mine, theirs) {\n if (mine === theirs) {\n return mine;\n } else {\n index.conflict = true;\n return {\n mine: mine,\n theirs: theirs\n };\n }\n}\nfunction hunkBefore(test, check) {\n return test.oldStart < check.oldStart && test.oldStart + test.oldLines < check.oldStart;\n}\nfunction cloneHunk(hunk, offset) {\n return {\n oldStart: hunk.oldStart,\n oldLines: hunk.oldLines,\n newStart: hunk.newStart + offset,\n newLines: hunk.newLines,\n lines: hunk.lines\n };\n}\nfunction mergeLines(hunk, mineOffset, mineLines, theirOffset, theirLines) {\n // This will generally result in a conflicted hunk, but there are cases where the context\n // is the only overlap where we can successfully merge the content here.\n var mine = {\n offset: mineOffset,\n lines: mineLines,\n index: 0\n },\n their = {\n offset: theirOffset,\n lines: theirLines,\n index: 0\n };\n\n // Handle any leading content\n insertLeading(hunk, mine, their);\n insertLeading(hunk, their, mine);\n\n // Now in the overlap content. Scan through and select the best changes from each.\n while (mine.index < mine.lines.length && their.index < their.lines.length) {\n var mineCurrent = mine.lines[mine.index],\n theirCurrent = their.lines[their.index];\n if ((mineCurrent[0] === '-' || mineCurrent[0] === '+') && (theirCurrent[0] === '-' || theirCurrent[0] === '+')) {\n // Both modified ...\n mutualChange(hunk, mine, their);\n } else if (mineCurrent[0] === '+' && theirCurrent[0] === ' ') {\n var _hunk$lines;\n // Mine inserted\n (_hunk$lines = hunk.lines).push.apply(_hunk$lines, _toConsumableArray(collectChange(mine)));\n } else if (theirCurrent[0] === '+' && mineCurrent[0] === ' ') {\n var _hunk$lines2;\n // Theirs inserted\n (_hunk$lines2 = hunk.lines).push.apply(_hunk$lines2, _toConsumableArray(collectChange(their)));\n } else if (mineCurrent[0] === '-' && theirCurrent[0] === ' ') {\n // Mine removed or edited\n removal(hunk, mine, their);\n } else if (theirCurrent[0] === '-' && mineCurrent[0] === ' ') {\n // Their removed or edited\n removal(hunk, their, mine, true);\n } else if (mineCurrent === theirCurrent) {\n // Context identity\n hunk.lines.push(mineCurrent);\n mine.index++;\n their.index++;\n } else {\n // Context mismatch\n conflict(hunk, collectChange(mine), collectChange(their));\n }\n }\n\n // Now push anything that may be remaining\n insertTrailing(hunk, mine);\n insertTrailing(hunk, their);\n calcLineCount(hunk);\n}\nfunction mutualChange(hunk, mine, their) {\n var myChanges = collectChange(mine),\n theirChanges = collectChange(their);\n if (allRemoves(myChanges) && allRemoves(theirChanges)) {\n // Special case for remove changes that are supersets of one another\n if (arrayStartsWith(myChanges, theirChanges) && skipRemoveSuperset(their, myChanges, myChanges.length - theirChanges.length)) {\n var _hunk$lines3;\n (_hunk$lines3 = hunk.lines).push.apply(_hunk$lines3, _toConsumableArray(myChanges));\n return;\n } else if (arrayStartsWith(theirChanges, myChanges) && skipRemoveSuperset(mine, theirChanges, theirChanges.length - myChanges.length)) {\n var _hunk$lines4;\n (_hunk$lines4 = hunk.lines).push.apply(_hunk$lines4, _toConsumableArray(theirChanges));\n return;\n }\n } else if (arrayEqual(myChanges, theirChanges)) {\n var _hunk$lines5;\n (_hunk$lines5 = hunk.lines).push.apply(_hunk$lines5, _toConsumableArray(myChanges));\n return;\n }\n conflict(hunk, myChanges, theirChanges);\n}\nfunction removal(hunk, mine, their, swap) {\n var myChanges = collectChange(mine),\n theirChanges = collectContext(their, myChanges);\n if (theirChanges.merged) {\n var _hunk$lines6;\n (_hunk$lines6 = hunk.lines).push.apply(_hunk$lines6, _toConsumableArray(theirChanges.merged));\n } else {\n conflict(hunk, swap ? theirChanges : myChanges, swap ? myChanges : theirChanges);\n }\n}\nfunction conflict(hunk, mine, their) {\n hunk.conflict = true;\n hunk.lines.push({\n conflict: true,\n mine: mine,\n theirs: their\n });\n}\nfunction insertLeading(hunk, insert, their) {\n while (insert.offset < their.offset && insert.index < insert.lines.length) {\n var line = insert.lines[insert.index++];\n hunk.lines.push(line);\n insert.offset++;\n }\n}\nfunction insertTrailing(hunk, insert) {\n while (insert.index < insert.lines.length) {\n var line = insert.lines[insert.index++];\n hunk.lines.push(line);\n }\n}\nfunction collectChange(state) {\n var ret = [],\n operation = state.lines[state.index][0];\n while (state.index < state.lines.length) {\n var line = state.lines[state.index];\n\n // Group additions that are immediately after subtractions and treat them as one \"atomic\" modify change.\n if (operation === '-' && line[0] === '+') {\n operation = '+';\n }\n if (operation === line[0]) {\n ret.push(line);\n state.index++;\n } else {\n break;\n }\n }\n return ret;\n}\nfunction collectContext(state, matchChanges) {\n var changes = [],\n merged = [],\n matchIndex = 0,\n contextChanges = false,\n conflicted = false;\n while (matchIndex < matchChanges.length && state.index < state.lines.length) {\n var change = state.lines[state.index],\n match = matchChanges[matchIndex];\n\n // Once we've hit our add, then we are done\n if (match[0] === '+') {\n break;\n }\n contextChanges = contextChanges || change[0] !== ' ';\n merged.push(match);\n matchIndex++;\n\n // Consume any additions in the other block as a conflict to attempt\n // to pull in the remaining context after this\n if (change[0] === '+') {\n conflicted = true;\n while (change[0] === '+') {\n changes.push(change);\n change = state.lines[++state.index];\n }\n }\n if (match.substr(1) === change.substr(1)) {\n changes.push(change);\n state.index++;\n } else {\n conflicted = true;\n }\n }\n if ((matchChanges[matchIndex] || '')[0] === '+' && contextChanges) {\n conflicted = true;\n }\n if (conflicted) {\n return changes;\n }\n while (matchIndex < matchChanges.length) {\n merged.push(matchChanges[matchIndex++]);\n }\n return {\n merged: merged,\n changes: changes\n };\n}\nfunction allRemoves(changes) {\n return changes.reduce(function (prev, change) {\n return prev && change[0] === '-';\n }, true);\n}\nfunction skipRemoveSuperset(state, removeChanges, delta) {\n for (var i = 0; i < delta; i++) {\n var changeContent = removeChanges[removeChanges.length - delta + i].substr(1);\n if (state.lines[state.index + i] !== ' ' + changeContent) {\n return false;\n }\n }\n state.index += delta;\n return true;\n}\nfunction calcOldNewLineCount(lines) {\n var oldLines = 0;\n var newLines = 0;\n lines.forEach(function (line) {\n if (typeof line !== 'string') {\n var myCount = calcOldNewLineCount(line.mine);\n var theirCount = calcOldNewLineCount(line.theirs);\n if (oldLines !== undefined) {\n if (myCount.oldLines === theirCount.oldLines) {\n oldLines += myCount.oldLines;\n } else {\n oldLines = undefined;\n }\n }\n if (newLines !== undefined) {\n if (myCount.newLines === theirCount.newLines) {\n newLines += myCount.newLines;\n } else {\n newLines = undefined;\n }\n }\n } else {\n if (newLines !== undefined && (line[0] === '+' || line[0] === ' ')) {\n newLines++;\n }\n if (oldLines !== undefined && (line[0] === '-' || line[0] === ' ')) {\n oldLines++;\n }\n }\n });\n return {\n oldLines: oldLines,\n newLines: newLines\n };\n}\n\nfunction reversePatch(structuredPatch) {\n if (Array.isArray(structuredPatch)) {\n return structuredPatch.map(reversePatch).reverse();\n }\n return _objectSpread2(_objectSpread2({}, structuredPatch), {}, {\n oldFileName: structuredPatch.newFileName,\n oldHeader: structuredPatch.newHeader,\n newFileName: structuredPatch.oldFileName,\n newHeader: structuredPatch.oldHeader,\n hunks: structuredPatch.hunks.map(function (hunk) {\n return {\n oldLines: hunk.newLines,\n oldStart: hunk.newStart,\n newLines: hunk.oldLines,\n newStart: hunk.oldStart,\n lines: hunk.lines.map(function (l) {\n if (l.startsWith('-')) {\n return \"+\".concat(l.slice(1));\n }\n if (l.startsWith('+')) {\n return \"-\".concat(l.slice(1));\n }\n return l;\n })\n };\n })\n });\n}\n\n// See: http://code.google.com/p/google-diff-match-patch/wiki/API\nfunction convertChangesToDMP(changes) {\n var ret = [],\n change,\n operation;\n for (var i = 0; i < changes.length; i++) {\n change = changes[i];\n if (change.added) {\n operation = 1;\n } else if (change.removed) {\n operation = -1;\n } else {\n operation = 0;\n }\n ret.push([operation, change.value]);\n }\n return ret;\n}\n\nfunction convertChangesToXML(changes) {\n var ret = [];\n for (var i = 0; i < changes.length; i++) {\n var change = changes[i];\n if (change.added) {\n ret.push('<ins>');\n } else if (change.removed) {\n ret.push('<del>');\n }\n ret.push(escapeHTML(change.value));\n if (change.added) {\n ret.push('</ins>');\n } else if (change.removed) {\n ret.push('</del>');\n }\n }\n return ret.join('');\n}\nfunction escapeHTML(s) {\n var n = s;\n n = n.replace(/&/g, '&amp;');\n n = n.replace(/</g, '&lt;');\n n = n.replace(/>/g, '&gt;');\n n = n.replace(/\"/g, '&quot;');\n return n;\n}\n\nexport { Diff, applyPatch, applyPatches, canonicalize, convertChangesToDMP, convertChangesToXML, createPatch, createTwoFilesPatch, diffArrays, diffChars, diffCss, diffJson, diffLines, diffSentences, diffTrimmedLines, diffWords, diffWordsWithSpace, formatPatch, merge, parsePatch, reversePatch, structuredPatch };\n","import type { ParsedSpec, ParsedSection } from \"@specdx/core\";\nimport { createPatch } from \"diff\";\nimport type { SpecDiff, FieldChange, SectionChange } from \"./types.js\";\n\nexport function diffSpecs(before: ParsedSpec, after: ParsedSpec): SpecDiff {\n const frontmatter = diffFrontmatter(before.frontmatter, after.frontmatter);\n const sections = diffSections(before.parsedSections, after.parsedSections);\n const specId = after.frontmatter.id as string;\n\n const parts: string[] = [];\n if (frontmatter.length > 0) parts.push(`${frontmatter.length} field(s) changed`);\n if (sections.length > 0) parts.push(`${sections.length} section(s) changed`);\n const summary = parts.length > 0 ? `${specId}: ${parts.join(\", \")}` : `${specId}: no changes`;\n\n return { specId, filePath: after.filePath, frontmatter, sections, summary };\n}\n\nfunction diffFrontmatter(\n before: Record<string, unknown>,\n after: Record<string, unknown>,\n): FieldChange[] {\n const changes: FieldChange[] = [];\n const allKeys = new Set([...Object.keys(before), ...Object.keys(after)]);\n\n for (const key of allKeys) {\n const inBefore = Object.prototype.hasOwnProperty.call(before, key);\n const inAfter = Object.prototype.hasOwnProperty.call(after, key);\n\n if (inBefore && !inAfter) {\n changes.push({ field: key, type: \"removed\", before: before[key] });\n } else if (!inBefore && inAfter) {\n changes.push({ field: key, type: \"added\", after: after[key] });\n } else if (inBefore && inAfter) {\n const bVal = before[key];\n const aVal = after[key];\n if (JSON.stringify(bVal) !== JSON.stringify(aVal)) {\n changes.push({ field: key, type: \"modified\", before: bVal, after: aVal });\n }\n }\n }\n\n return changes;\n}\n\nfunction diffSections(before: ParsedSection[], after: ParsedSection[]): SectionChange[] {\n const changes: SectionChange[] = [];\n\n const beforeMap = new Map<string, ParsedSection>();\n for (const section of before) {\n beforeMap.set(section.heading, section);\n }\n\n const afterMap = new Map<string, ParsedSection>();\n for (const section of after) {\n afterMap.set(section.heading, section);\n }\n\n // Removed sections: in before but not in after\n for (const [heading] of beforeMap) {\n if (!afterMap.has(heading)) {\n changes.push({ heading, type: \"removed\" });\n }\n }\n\n // Added or modified sections\n for (const [heading, afterSection] of afterMap) {\n const beforeSection = beforeMap.get(heading);\n if (!beforeSection) {\n changes.push({ heading, type: \"added\" });\n } else if (beforeSection.content !== afterSection.content) {\n const contentDiff = createPatch(\n heading,\n beforeSection.content,\n afterSection.content,\n \"before\",\n \"after\",\n );\n changes.push({ heading, type: \"modified\", contentDiff });\n }\n }\n\n return changes;\n}\n","import type { RelationResolver, ParsedSpec } from \"@specdx/core\";\nimport type { SpecDiff, ImpactAnalysis, DownstreamImpact } from \"./types.js\";\n\nconst STRUCTURAL_SECTIONS = new Set([\n \"Goals\",\n \"Architecture\",\n \"Features\",\n \"Endpoints\",\n \"Data Model\",\n \"API Design\",\n \"Problem Statement\",\n]);\n\n/**\n * Calculate BFS distances from a starting spec id using relation edges.\n * Returns a map of specId -> shortest distance from the start spec.\n */\nfunction bfsDistances(startId: string, relations: RelationResolver): Map<string, number> {\n const distances = new Map<string, number>();\n const queue: Array<{ id: string; distance: number }> = [];\n\n // Seed queue with direct downstream neighbors (distance 1)\n for (const edge of relations.edges) {\n if (edge.from === startId) {\n if (!distances.has(edge.to)) {\n distances.set(edge.to, 1);\n queue.push({ id: edge.to, distance: 1 });\n }\n }\n }\n\n while (queue.length > 0) {\n const item = queue.shift()!;\n const currentDist = item.distance;\n\n for (const edge of relations.edges) {\n if (edge.from === item.id && !distances.has(edge.to)) {\n distances.set(edge.to, currentDist + 1);\n queue.push({ id: edge.to, distance: currentDist + 1 });\n }\n }\n }\n\n return distances;\n}\n\nfunction daysBetween(dateStr: string): number {\n const then = new Date(dateStr).getTime();\n const now = Date.now();\n return Math.max(0, (now - then) / (1000 * 60 * 60 * 24));\n}\n\nfunction clamp(min: number, max: number, value: number): number {\n return Math.min(max, Math.max(min, value));\n}\n\nexport function analyzeImpact(\n changedSpecId: string,\n diff: SpecDiff,\n relations: RelationResolver,\n allSpecs: ParsedSpec[],\n thresholdDays = 14,\n): ImpactAnalysis {\n // 1. BFS to get downstream spec IDs with their distances\n const distanceMap = bfsDistances(changedSpecId, relations);\n\n if (distanceMap.size === 0) {\n return {\n changedSpec: changedSpecId,\n downstream: [],\n totalAffected: 0,\n };\n }\n\n // 2. Pre-compute diff section metrics (same for all downstream specs)\n const totalSections = Math.max(1, diff.sections.length);\n const structuralSectionsChanged = diff.sections.filter((s) =>\n STRUCTURAL_SECTIONS.has(s.heading),\n ).length;\n\n // 3. Build a lookup map for specs\n const specById = new Map<string, ParsedSpec>();\n for (const spec of allSpecs) {\n const id = spec.frontmatter.id as string | undefined;\n if (id) specById.set(id, spec);\n }\n\n // 4. Build downstream impacts\n const downstream: DownstreamImpact[] = [];\n\n for (const [specId, distance] of distanceMap) {\n const spec = specById.get(specId);\n\n // Determine lastUpdated: use `updated` field if present, fall back to `created`\n const lastUpdated =\n (spec?.frontmatter.updated as string | undefined) ??\n (spec?.frontmatter.created as string | undefined) ??\n null;\n\n const filePath = spec?.filePath ?? `specs/${specId}.md`;\n\n // 5. Staleness formula\n let staleness: number;\n if (lastUpdated) {\n const daysSinceUpdate = daysBetween(lastUpdated);\n staleness = clamp(\n 0,\n 1,\n (daysSinceUpdate / thresholdDays) * 0.5 +\n (structuralSectionsChanged / totalSections) * 0.3 +\n (1 / distance) * 0.2,\n );\n } else {\n // No date info — use structural + distance terms only\n staleness = clamp(\n 0,\n 1,\n (structuralSectionsChanged / totalSections) * 0.3 + (1 / distance) * 0.2,\n );\n }\n\n // 6. Generate reason string\n const parts: string[] = [];\n parts.push(`depends on ${changedSpecId} (distance ${distance})`);\n if (structuralSectionsChanged > 0) {\n parts.push(`${structuralSectionsChanged} structural section(s) changed`);\n }\n if (lastUpdated) {\n const days = Math.round(daysBetween(lastUpdated));\n parts.push(`last updated ${days} day(s) ago`);\n }\n const reason = parts.join(\"; \");\n\n downstream.push({\n specId,\n filePath,\n distance,\n lastUpdated,\n staleness,\n reason,\n });\n }\n\n // Sort by distance ascending, then by staleness descending for stable output\n downstream.sort((a, b) => a.distance - b.distance || b.staleness - a.staleness);\n\n return {\n changedSpec: changedSpecId,\n downstream,\n totalAffected: downstream.length,\n };\n}\n","import type { ParsedSpec } from \"@specdx/core\";\n\nexport interface BrokenReference {\n specId: string;\n field: string;\n type: \"broken-reference\";\n referencedId: string;\n}\n\nexport function checkCrossReferences(\n allSpecs: ParsedSpec[],\n removedIds: string[],\n): BrokenReference[] {\n // Build set of all valid spec IDs, then remove any that were deleted\n const validIds = new Set(allSpecs.map((s) => s.frontmatter.id));\n for (const id of removedIds) {\n validIds.delete(id);\n }\n\n const broken: BrokenReference[] = [];\n\n for (const spec of allSpecs) {\n const references = spec.frontmatter.references;\n if (!references || references.length === 0) {\n continue;\n }\n\n for (const ref of references) {\n if (!validIds.has(ref.id)) {\n broken.push({\n specId: spec.frontmatter.id,\n field: \"references\",\n type: \"broken-reference\",\n referencedId: ref.id,\n });\n }\n }\n }\n\n return broken;\n}\n","import { execSync } from \"node:child_process\";\nimport { readFileSync, realpathSync } from \"node:fs\";\nimport { dirname, relative, resolve, sep } from \"node:path\";\nimport picomatch from \"picomatch\";\nimport { loadConfig, parseSpecFromString, buildRelationResolver } from \"@specdx/core\";\nimport type { ParsedSpec } from \"@specdx/core\";\nimport { diffSpecs } from \"./diff-specs.js\";\nimport { analyzeImpact } from \"./impact.js\";\nimport { checkCrossReferences } from \"./cross-refs.js\";\nimport { DiffError } from \"./types.js\";\nimport type { DiffResult, DiffOptions, SpecDiff, ImpactAnalysis } from \"./types.js\";\n\n/**\n * Get the real (symlink-resolved) git repo root for the given directory.\n */\nfunction getRepoRoot(cwd: string): string {\n let root: string;\n try {\n root = execSync(\"git rev-parse --show-toplevel\", {\n cwd,\n encoding: \"utf-8\",\n stdio: \"pipe\",\n }).trim();\n } catch {\n // Without this the raw git invocation and its \"fatal:\" output reach the\n // user, which reads as a crash rather than a precondition they can meet.\n throw new DiffError(\n \"diff compares specs across git history, and this directory is not inside a git repository. \" +\n \"Run `git init` first, or run diff from a checked-out project.\",\n );\n }\n return realpathSync(root);\n}\n\n/**\n * Validate that a git ref exists in the repository.\n */\nfunction validateRef(ref: string, cwd: string): void {\n try {\n execSync(`git rev-parse --verify ${ref}`, { cwd, encoding: \"utf-8\", stdio: \"pipe\" });\n } catch {\n throw new DiffError(`Invalid git ref: \"${ref}\"`);\n }\n}\n\n/**\n * Get file content at a specific git ref.\n * filePath should be relative to projectRoot.\n */\nfunction gitShow(ref: string, filePath: string, projectRoot: string, repoRoot: string): string {\n const relPath = relative(repoRoot, resolve(projectRoot, filePath));\n try {\n return execSync(`git show ${ref}:${relPath}`, {\n cwd: repoRoot,\n encoding: \"utf-8\",\n stdio: \"pipe\",\n });\n } catch {\n throw new DiffError(`Cannot read \"${filePath}\" at ref \"${ref}\"`);\n }\n}\n\n/** Git reports paths with forward slashes regardless of platform. */\nfunction toPosix(p: string): string {\n return sep === \"/\" ? p : p.split(sep).join(\"/\");\n}\n\ninterface EntryMatcher {\n /** Config entry key (may cover many spec files when the path is a glob). */\n key: string;\n /** Matches repo-relative, posix-separated paths against the entry's path. */\n isMatch: (repoRelPath: string) => boolean;\n}\n\n/**\n * Build one matcher per config entry.\n *\n * A config entry's `path` may be a glob (`specs/stories/*.md`), so it cannot be\n * compared to git's output by string equality -- the literal pattern is never\n * itself a changed path. Matching by pattern is what makes globbed specs\n * visible to diff at all.\n */\nfunction buildEntryMatchers(\n specPathsByKey: Map<string, string>,\n projectRoot: string,\n repoRoot: string,\n): EntryMatcher[] {\n return [...specPathsByKey].map(([key, specPath]) => ({\n key,\n isMatch: picomatch(toPosix(relative(repoRoot, resolve(projectRoot, specPath)))),\n }));\n}\n\n/** A spec file that changed between two refs, with the entry it belongs to. */\ninterface ChangedSpecFile {\n /** Project-relative path, as the rest of the pipeline expects. */\n path: string;\n entryKey: string;\n}\n\ninterface ChangedFiles {\n modified: ChangedSpecFile[];\n added: ChangedSpecFile[];\n deleted: ChangedSpecFile[];\n}\n\n/**\n * Get list of changed files between two refs, filtered to files that belong to\n * a configured spec entry.\n */\nfunction getChangedSpecFiles(\n baseRef: string,\n headRef: string,\n matchers: EntryMatcher[],\n projectRoot: string,\n repoRoot: string,\n): ChangedFiles {\n let diffOutput: string;\n try {\n diffOutput = execSync(`git diff --name-status ${baseRef} ${headRef}`, {\n cwd: repoRoot,\n encoding: \"utf-8\",\n stdio: \"pipe\",\n });\n } catch {\n throw new DiffError(`Failed to run git diff between \"${baseRef}\" and \"${headRef}\"`);\n }\n\n const result: ChangedFiles = { modified: [], added: [], deleted: [] };\n\n for (const line of diffOutput.trim().split(\"\\n\")) {\n if (!line) continue;\n const parts = line.split(\"\\t\");\n const status = parts[0];\n const filePath = parts[1];\n if (!status || !filePath) continue;\n\n const entry = matchers.find((m) => m.isMatch(filePath));\n if (!entry) continue;\n\n const changed: ChangedSpecFile = {\n path: relative(projectRoot, resolve(repoRoot, filePath)),\n entryKey: entry.key,\n };\n\n if (status === \"M\") {\n result.modified.push(changed);\n } else if (status === \"A\") {\n result.added.push(changed);\n } else if (status === \"D\") {\n result.deleted.push(changed);\n }\n }\n\n return result;\n}\n\n/**\n * List every spec file present at a ref, grouped by config entry key.\n *\n * Expanding globs against the ref rather than the working tree keeps impact\n * analysis accurate for specs that were added or deleted in the range.\n */\nfunction listSpecFilesAtRef(\n ref: string,\n matchers: EntryMatcher[],\n projectRoot: string,\n repoRoot: string,\n): Map<string, string[]> {\n const byEntry = new Map<string, string[]>(matchers.map((m) => [m.key, []]));\n\n let listing: string;\n try {\n listing = execSync(`git ls-tree -r --name-only ${ref}`, {\n cwd: repoRoot,\n encoding: \"utf-8\",\n stdio: \"pipe\",\n });\n } catch {\n throw new DiffError(`Failed to list files at ref \"${ref}\"`);\n }\n\n for (const filePath of listing.trim().split(\"\\n\")) {\n if (!filePath) continue;\n const entry = matchers.find((m) => m.isMatch(filePath));\n if (!entry) continue;\n byEntry.get(entry.key)?.push(relative(projectRoot, resolve(repoRoot, filePath)));\n }\n\n return byEntry;\n}\n\n/**\n * List every spec file in the working tree, grouped by config entry key.\n *\n * Uses git rather than a filesystem glob so ignored files are excluded the same\n * way they are on the ref side -- a file git cannot see is not a spec that can\n * be committed.\n */\nfunction listSpecFilesInWorktree(\n matchers: EntryMatcher[],\n projectRoot: string,\n repoRoot: string,\n): Map<string, string[]> {\n const byEntry = new Map<string, string[]>(matchers.map((m) => [m.key, []]));\n\n let listing: string;\n try {\n listing = execSync(\"git ls-files --cached --others --exclude-standard\", {\n cwd: repoRoot,\n encoding: \"utf-8\",\n stdio: \"pipe\",\n });\n } catch {\n throw new DiffError(\"Failed to list files in the working tree\");\n }\n\n for (const filePath of listing.trim().split(\"\\n\")) {\n if (!filePath) continue;\n const entry = matchers.find((m) => m.isMatch(filePath));\n if (!entry) continue;\n byEntry.get(entry.key)?.push(relative(projectRoot, resolve(repoRoot, filePath)));\n }\n\n return byEntry;\n}\n\n/** One side of a comparison: either a git ref or the working tree. */\ninterface ComparisonSide {\n /** Read a spec file's content on this side. Throws if absent. */\n read: (path: string) => string;\n /** Spec files present on this side, grouped by config entry key. */\n list: () => Map<string, string[]>;\n}\n\nfunction refSide(\n ref: string,\n matchers: EntryMatcher[],\n projectRoot: string,\n repoRoot: string,\n): ComparisonSide {\n return {\n read: (path) => gitShow(ref, path, projectRoot, repoRoot),\n list: () => listSpecFilesAtRef(ref, matchers, projectRoot, repoRoot),\n };\n}\n\nfunction worktreeSide(\n matchers: EntryMatcher[],\n projectRoot: string,\n repoRoot: string,\n): ComparisonSide {\n return {\n read: (path) => {\n try {\n return readFileSync(resolve(projectRoot, path), \"utf-8\");\n } catch {\n throw new DiffError(`Cannot read \"${path}\" in the working tree`);\n }\n },\n list: () => listSpecFilesInWorktree(matchers, projectRoot, repoRoot),\n };\n}\n\n/**\n * Get spec files that differ between a ref and the working tree.\n *\n * `git diff --name-status <ref>` covers tracked files, staged or not, but says\n * nothing about untracked ones -- and a brand new spec is untracked until the\n * commit this comparison exists to inform. Untracked spec files are therefore\n * folded in as additions.\n */\nfunction getChangedSpecFilesInWorktree(\n baseRef: string,\n matchers: EntryMatcher[],\n projectRoot: string,\n repoRoot: string,\n): ChangedFiles {\n let diffOutput: string;\n try {\n diffOutput = execSync(`git diff --name-status ${baseRef}`, {\n cwd: repoRoot,\n encoding: \"utf-8\",\n stdio: \"pipe\",\n });\n } catch {\n throw new DiffError(`Failed to diff \"${baseRef}\" against the working tree`);\n }\n\n const result: ChangedFiles = { modified: [], added: [], deleted: [] };\n const seen = new Set<string>();\n\n const record = (status: string, filePath: string): void => {\n const entry = matchers.find((m) => m.isMatch(filePath));\n if (!entry) return;\n if (seen.has(filePath)) return;\n seen.add(filePath);\n\n const changed: ChangedSpecFile = {\n path: relative(projectRoot, resolve(repoRoot, filePath)),\n entryKey: entry.key,\n };\n if (status === \"M\") result.modified.push(changed);\n else if (status === \"A\") result.added.push(changed);\n else if (status === \"D\") result.deleted.push(changed);\n };\n\n for (const line of diffOutput.trim().split(\"\\n\")) {\n if (!line) continue;\n const parts = line.split(\"\\t\");\n const status = parts[0];\n const filePath = parts[1];\n if (!status || !filePath) continue;\n record(status, filePath);\n }\n\n let untracked: string;\n try {\n untracked = execSync(\"git ls-files --others --exclude-standard\", {\n cwd: repoRoot,\n encoding: \"utf-8\",\n stdio: \"pipe\",\n });\n } catch {\n throw new DiffError(\"Failed to list untracked files\");\n }\n\n for (const filePath of untracked.trim().split(\"\\n\")) {\n if (!filePath) continue;\n record(\"A\", filePath);\n }\n\n return result;\n}\n\n/**\n * Spec files with uncommitted changes in the working tree.\n *\n * Reported alongside a ref-to-ref comparison so \"no spec changes\" is never\n * mistaken for \"nothing is about to change\".\n */\nfunction listUncommittedSpecFiles(\n matchers: EntryMatcher[],\n projectRoot: string,\n repoRoot: string,\n): string[] {\n let statusOutput: string;\n try {\n statusOutput = execSync(\"git status --porcelain\", {\n cwd: repoRoot,\n encoding: \"utf-8\",\n stdio: \"pipe\",\n });\n } catch {\n // Status is advisory -- never fail the diff over it.\n return [];\n }\n\n const files: string[] = [];\n for (const line of statusOutput.split(\"\\n\")) {\n if (!line.trim()) continue;\n // Porcelain v1: two status columns, a space, then the path. A rename reads\n // \"old -> new\"; the new path is the one that exists now. Paths containing\n // unusual characters are quoted.\n const rawPath = line.slice(3);\n const renamed = rawPath.includes(\" -> \") ? rawPath.split(\" -> \")[1] : undefined;\n const filePath = (renamed ?? rawPath).replace(/^\"|\"$/g, \"\");\n if (!matchers.some((m) => m.isMatch(filePath))) continue;\n files.push(relative(projectRoot, resolve(repoRoot, filePath)));\n }\n\n return files;\n}\n\n/**\n * Resolve the spec ids of files that only exist on one side of the range.\n *\n * The config entry key is not usable as a spec id: one glob entry covers many\n * specs, so the id has to come from each file's own frontmatter.\n */\nasync function specIdsFrom(\n files: ChangedSpecFile[],\n read: (path: string) => string,\n): Promise<string[]> {\n const ids: string[] = [];\n for (const file of files) {\n try {\n const parsed = await parseSpecFromString(read(file.path), file.path);\n ids.push(parsed.frontmatter.id);\n } catch {\n // Unparseable or unreadable on that side -- fall back to the entry key so\n // the spec is still reported as added/removed rather than dropped.\n ids.push(file.entryKey);\n }\n }\n return ids;\n}\n\n/**\n * Compare specs between two git refs, producing a full DiffResult with\n * structural diffs, impact analysis, and cross-reference checks.\n */\nexport async function diffBetweenRefs(\n configPath: string,\n baseRef: string,\n headRef: string,\n options: DiffOptions = {},\n): Promise<DiffResult> {\n const projectRoot = realpathSync(dirname(resolve(configPath)));\n const repoRoot = getRepoRoot(projectRoot);\n\n // Validate refs. In working mode the head side is the working tree, which is\n // not a ref and has nothing to validate.\n validateRef(baseRef, projectRoot);\n if (!options.working) validateRef(headRef, projectRoot);\n\n // Load config from filesystem (current version)\n const config = await loadConfig(configPath);\n\n // Collect all spec paths from config, keyed by entry. A path may be a glob,\n // so entries are matched by pattern rather than by string equality.\n const specPathsByKey = new Map<string, string>();\n for (const [key, entry] of Object.entries(config.specs)) {\n specPathsByKey.set(key, entry.path);\n }\n const matchers = buildEntryMatchers(specPathsByKey, projectRoot, repoRoot);\n\n const base = refSide(baseRef, matchers, projectRoot, repoRoot);\n const head = options.working\n ? worktreeSide(matchers, projectRoot, repoRoot)\n : refSide(headRef, matchers, projectRoot, repoRoot);\n\n // Determine which spec files changed\n const changed = options.working\n ? getChangedSpecFilesInWorktree(baseRef, matchers, projectRoot, repoRoot)\n : getChangedSpecFiles(baseRef, headRef, matchers, projectRoot, repoRoot);\n\n // Build diffs for modified specs\n const diffs: SpecDiff[] = [];\n\n for (const file of changed.modified) {\n const beforeSpec = await parseSpecFromString(base.read(file.path), file.path);\n const afterSpec = await parseSpecFromString(head.read(file.path), file.path);\n\n const diff = diffSpecs(beforeSpec, afterSpec);\n diffs.push(diff);\n }\n\n // Added and removed spec IDs, read from the frontmatter on the side of the\n // range where the file exists.\n const added = await specIdsFrom(changed.added, head.read);\n const removed = await specIdsFrom(changed.deleted, base.read);\n\n const impact: ImpactAnalysis[] = [];\n\n // Parse all specs present on the head side for impact analysis, keeping the\n // config entry each came from so requires edges can be mapped to spec ids.\n const allSpecs: ParsedSpec[] = [];\n const specsByEntry = new Map<string, ParsedSpec[]>();\n const filesAtHead = head.list();\n for (const [key, paths] of filesAtHead) {\n const forEntry: ParsedSpec[] = [];\n for (const path of paths) {\n try {\n const parsed = await parseSpecFromString(head.read(path), path);\n forEntry.push(parsed);\n allSpecs.push(parsed);\n } catch {\n // Unparseable on this side -- skip\n }\n }\n specsByEntry.set(key, forEntry);\n }\n\n // Impact works in spec id space: config requires and frontmatter references\n // unioned, so downstream is found whether entry keys match spec ids or not\n // (ADR: references/requires unification).\n const relations = buildRelationResolver(config, specsByEntry);\n\n const thresholdDays = config.diff?.staleness_threshold_days ?? 14;\n\n for (const diff of diffs) {\n const analysis = analyzeImpact(diff.specId, diff, relations, allSpecs, thresholdDays);\n if (analysis.totalAffected > 0) {\n impact.push(analysis);\n }\n }\n\n // Check cross-references for removed specs\n const _brokenRefs = checkCrossReferences(allSpecs, removed);\n\n // Generate summary\n const summaryParts: string[] = [];\n if (diffs.length > 0) {\n summaryParts.push(`${diffs.length} spec(s) modified`);\n }\n if (added.length > 0) {\n summaryParts.push(`${added.length} spec(s) added`);\n }\n if (removed.length > 0) {\n summaryParts.push(`${removed.length} spec(s) removed`);\n }\n if (impact.length > 0) {\n const totalDownstream = impact.reduce((sum, i) => sum + i.totalAffected, 0);\n summaryParts.push(`${totalDownstream} downstream spec(s) potentially affected`);\n }\n if (_brokenRefs.length > 0) {\n summaryParts.push(`${_brokenRefs.length} broken reference(s)`);\n }\n const summary = summaryParts.length > 0 ? summaryParts.join(\"; \") : \"No changes detected\";\n\n // Working mode already covers the working tree, so nothing there is missed.\n const uncommittedSpecFiles = options.working\n ? []\n : listUncommittedSpecFiles(matchers, projectRoot, repoRoot);\n\n return { diffs, added, removed, impact, summary, uncommittedSpecFiles };\n}\n","import type { DiffResult } from \"@specdx/diff\";\n\n/**\n * Render a diff as a markdown changelog.\n *\n * Formerly the `specdx changelog` command, which ran the same comparison as\n * `diff` and differed only in presentation. It is a format, not a second\n * question, so it lives as `diff --format changelog`.\n */\nexport function formatChangelog(result: DiffResult, baseRef: string, headRef: string): string {\n const lines: string[] = [];\n lines.push(`## Spec Changes (${baseRef}..${headRef})\\n`);\n\n if (result.diffs.length > 0) {\n lines.push(\"### Modified\");\n for (const diff of result.diffs) {\n const sections = diff.sections.map((s) => s.heading).join(\", \");\n const versionChange = diff.frontmatter.find((f) => f.field === \"version\");\n const versionStr = versionChange\n ? ` (${String(versionChange.before)} → ${String(versionChange.after)})`\n : \"\";\n lines.push(`- **${diff.specId}**${versionStr} — ${sections || \"frontmatter only\"}`);\n }\n lines.push(\"\");\n }\n\n if (result.added.length > 0) {\n lines.push(\"### Added\");\n for (const id of result.added) {\n lines.push(`- **${id}**`);\n }\n lines.push(\"\");\n }\n\n if (result.removed.length > 0) {\n lines.push(\"### Removed\");\n for (const id of result.removed) {\n lines.push(`- **${id}**`);\n }\n lines.push(\"\");\n }\n\n const allDownstream = result.impact.flatMap((i) => i.downstream);\n if (allDownstream.length > 0) {\n lines.push(\"### Downstream Impact\");\n for (const d of allDownstream) {\n lines.push(`- ${d.specId} may be stale (${d.reason})`);\n }\n lines.push(\"\");\n }\n\n if (result.diffs.length === 0 && result.added.length === 0 && result.removed.length === 0) {\n lines.push(\"No spec changes detected.\\n\");\n }\n\n // The uncommitted warning matters most here: a changelog is usually written\n // at release time, when unstaged spec edits are easy to miss.\n if (result.uncommittedSpecFiles.length > 0) {\n lines.push(\n `> ⚠ ${result.uncommittedSpecFiles.length} spec file(s) changed in the working tree are not covered by this range.\\n`,\n );\n }\n\n return lines.join(\"\\n\");\n}\n","import { defineCommand } from \"citty\";\nimport { loadConfig, parseSpec, buildGraph, resolveGlob } from \"@specdx/core\";\nimport { createLintEngine, getPreset } from \"@specdx/lint\";\nimport { DEFAULT_DIFF_CONFIG } from \"@specdx/diff\";\nimport type { StatusResult } from \"@specdx/diff\";\nimport type { ParsedSpec } from \"@specdx/core\";\nimport { sharedArgs, resolveFormat } from \"../../shared-args.js\";\nimport { createOutput } from \"../../output.js\";\n\nconst FORMATS = [\"pretty\", \"json\", \"github\"] as const;\n\nexport interface RunStatusOptions {\n /**\n * Directory holding spec.config.yaml. Defaults to the process cwd, which is\n * right for the CLI and useless to a library consumer — `runLint` and\n * `runPack` take one, so this does too (audit run 5, F8).\n */\n configDir?: string;\n}\n\nexport async function runStatus(options: RunStatusOptions = {}): Promise<StatusResult> {\n const configDir = options.configDir ?? process.cwd();\n const config = await loadConfig(undefined, configDir);\n\n // Resolve and parse all specs\n const specs: { spec: ParsedSpec; entry: { path: string; owner?: string } }[] = [];\n for (const [, entry] of Object.entries(config.specs)) {\n const paths = await resolveGlob(entry.path, configDir);\n for (const p of paths) {\n const spec = await parseSpec(p);\n specs.push({ spec, entry: entry as { path: string; owner?: string } });\n }\n }\n\n // Count by status\n const byStatus: Record<string, number> = {};\n for (const { spec } of specs) {\n const status = (spec.frontmatter.status as string) || \"unknown\";\n byStatus[status] = (byStatus[status] ?? 0) + 1;\n }\n\n // Lint health\n const presetName = config.lint?.extends ?? \"recommended\";\n const rules = getPreset(presetName);\n\n let graph;\n let graphError: string | undefined;\n try {\n graph = buildGraph(config);\n } catch (err) {\n graphError = (err as Error).message;\n }\n\n const engine = createLintEngine({ rules, config, graph });\n const lintResults = engine.lint(specs.map((s) => s.spec));\n\n if (graphError) {\n lintResults.diagnostics.push({\n ruleId: \"structure/no-circular-deps\",\n severity: \"error\",\n message: graphError,\n filePath: \"spec.config.yaml\",\n });\n lintResults.hasErrors = true;\n }\n\n const errors = lintResults.diagnostics.filter((d) => d.severity === \"error\").length;\n const warnings = lintResults.diagnostics.filter((d) => d.severity === \"warn\").length;\n\n // Specs carrying no error-severity diagnostic.\n //\n // This was `specs.length - errors`, which subtracts a diagnostic count from a\n // spec count -- one spec with seven errors reported `passing: -6`. The units\n // only agree when `errors` is 0, which is every suite the fixtures use\n // (audit run 6, G2).\n const specsWithErrors = new Set(\n lintResults.diagnostics.filter((d) => d.severity === \"error\").map((d) => d.filePath),\n );\n const passing = specs.filter(({ spec }) => !specsWithErrors.has(spec.filePath)).length;\n\n // Staleness\n const thresholdDays =\n config.diff?.staleness_threshold_days ?? DEFAULT_DIFF_CONFIG.staleness_threshold_days;\n const now = Date.now();\n const staleSpecs: { specId: string; daysSinceUpdate: number; owner?: string }[] = [];\n for (const { spec, entry } of specs) {\n const dateStr =\n (spec.frontmatter.updated as string | undefined) ||\n (spec.frontmatter.created as string | undefined);\n if (dateStr) {\n const daysSinceUpdate = Math.floor(\n (now - new Date(dateStr).getTime()) / (1000 * 60 * 60 * 24),\n );\n if (daysSinceUpdate > thresholdDays) {\n staleSpecs.push({\n specId: spec.frontmatter.id as string,\n daysSinceUpdate,\n owner: entry.owner,\n });\n }\n }\n }\n\n // Integrity issues\n const integrityIssues: string[] = [];\n if (graphError) {\n integrityIssues.push(graphError);\n }\n const refErrors = lintResults.diagnostics.filter(\n (d) => d.ruleId === \"structure/valid-references\",\n );\n for (const d of refErrors) {\n integrityIssues.push(d.message);\n }\n\n // Verdict — an empty suite is unassessed, never a vacuous \"healthy\"\n let verdict: StatusResult[\"verdict\"] = \"healthy\";\n if (errors > 0) verdict = \"errors\";\n else if (warnings > 0 || staleSpecs.length > 0) verdict = \"warnings\";\n else if (specs.length === 0) verdict = \"unassessed\";\n\n return {\n project: config.project?.name ?? \"unknown\",\n specFiles: specs.length,\n byStatus,\n lintHealth: { errors, warnings, passing },\n staleSpecs,\n integrityIssues,\n verdict,\n };\n}\n\nexport default defineCommand({\n meta: { name: \"status\", description: \"Show spec suite health overview\" },\n args: { ...sharedArgs(FORMATS) },\n async run({ args }) {\n const format = resolveFormat(args.format, FORMATS);\n if (!format.ok) {\n console.error(`\\n ✗ ${format.message}\\n`);\n process.exit(1);\n }\n const output = createOutput({ quiet: args.quiet });\n\n try {\n const result = await runStatus();\n\n if (format.format === \"json\") {\n console.log(JSON.stringify(result, null, 2));\n return;\n }\n\n if (format.format === \"github\") {\n // A headline always, at the level the verdict reports.\n //\n // This block used to render stale specs and integrity issues and\n // nothing else, so a suite whose only problem was lint errors emitted\n // zero bytes and exited 0 -- a workflow step showing nothing, on a run\n // whose own JSON said `verdict: \"errors\"` (audit run 6, G1). `check`\n // was given a headline for exactly this reason; status renders the same\n // format and was left able to say nothing at all.\n //\n // The level tracks the pretty renderer's icon so the two renderers of\n // one command cannot disagree. Lint diagnostics are deliberately not\n // re-annotated here -- `lint --format github` owns those, and a\n // workflow running both should not get each one twice.\n const level =\n result.verdict === \"errors\"\n ? \"error\"\n : result.verdict === \"healthy\"\n ? \"notice\"\n : \"warning\";\n console.log(\n `::${level}::specdx status — ${result.project} — ${result.verdict}: ` +\n `${result.specFiles} spec file(s), ${result.lintHealth.errors} error(s), ` +\n `${result.lintHealth.warnings} warning(s)`,\n );\n if (result.verdict === \"unassessed\") {\n console.log(\n \"::warning::No specs resolved — nothing was assessed. Check the spec paths in spec.config.yaml.\",\n );\n }\n for (const s of result.staleSpecs) {\n console.log(\n `::warning::Spec \"${s.specId}\" is stale (${s.daysSinceUpdate} days since update)`,\n );\n }\n for (const issue of result.integrityIssues) {\n console.log(`::error::${issue}`);\n }\n return;\n }\n\n // Pretty format\n const icon =\n result.verdict === \"healthy\"\n ? \"✓\"\n : result.verdict === \"warnings\" || result.verdict === \"unassessed\"\n ? \"⚠\"\n : \"✗\";\n const healthy = result.verdict === \"healthy\";\n const headline = `\\n ${icon} ${result.project} — ${result.verdict}`;\n if (healthy) output.info(headline);\n else output.out(headline);\n\n if (result.verdict === \"unassessed\") {\n output.out(\n \" No specs resolved — nothing was assessed. Check the spec paths in spec.config.yaml.\",\n );\n }\n output.info(\n ` ${result.specFiles} specs: ${Object.entries(result.byStatus)\n .map(([k, v]) => `${v} ${k}`)\n .join(\", \")}`,\n );\n output.info(\n ` Lint: ${result.lintHealth.errors} errors, ${result.lintHealth.warnings} warnings`,\n );\n\n if (result.staleSpecs.length > 0) {\n output.out(\n ` Stale: ${result.staleSpecs.map((s) => `${s.specId} (${s.daysSinceUpdate}d)`).join(\", \")}`,\n );\n }\n if (result.integrityIssues.length > 0) {\n output.out(` Issues: ${result.integrityIssues.join(\"; \")}`);\n }\n output.info();\n } catch (err) {\n console.error(`\\n ✗ ${(err as Error).message}\\n`);\n process.exit(1);\n }\n },\n});\n","import { defineCommand } from \"citty\";\nimport { loadConfig, buildGraph, resolveGlob, ConfigError, GraphError } from \"@specdx/core\";\nimport { sharedArgs, resolveFormat } from \"../../shared-args.js\";\nimport { createOutput } from \"../../output.js\";\n\nconst FORMATS = [\"pretty\", \"json\"] as const;\n\nexport interface ValidateResult {\n valid: boolean;\n /** Number of spec entries declared in the config. */\n specEntries?: number;\n /** Number of spec files those entries actually resolve to. */\n specFiles?: number;\n /** Non-fatal honesty notes: entries resolving to nothing, empty suite. */\n warnings: string[];\n error?: string;\n details?: unknown[];\n}\n\n/**\n * Validate spec.config.yaml: a schema-valid config, a buildable dependency\n * graph (issue #13), and declared spec paths that actually resolve. An entry\n * that matches no files makes every downstream verdict vacuous, so it is\n * reported here rather than silently flowing into lint/status/ready.\n */\nexport async function runValidate(configDir: string): Promise<ValidateResult> {\n const warnings: string[] = [];\n try {\n const config = await loadConfig(undefined, configDir);\n buildGraph(config);\n\n let specFiles = 0;\n const missingRequired: string[] = [];\n for (const [key, entry] of Object.entries(config.specs)) {\n const files = await resolveGlob(entry.path, configDir);\n specFiles += files.length;\n if (files.length > 0) continue;\n\n if ((entry as { required?: boolean }).required) {\n missingRequired.push(`\"${key}\" (${entry.path})`);\n } else {\n warnings.push(`spec entry \"${key}\" resolves to no files: ${entry.path}`);\n }\n }\n\n if (missingRequired.length > 0) {\n return {\n valid: false,\n specEntries: Object.keys(config.specs).length,\n specFiles,\n warnings,\n error: `required spec entry resolves to no files: ${missingRequired.join(\", \")}`,\n };\n }\n\n if (specFiles === 0) {\n warnings.push(\n \"no spec files found — every downstream check (lint, status, ready) would pass vacuously\",\n );\n }\n\n return {\n valid: true,\n specEntries: Object.keys(config.specs).length,\n specFiles,\n warnings,\n };\n } catch (err) {\n if (err instanceof ConfigError) {\n return { valid: false, warnings, error: err.message, details: err.errors ?? undefined };\n }\n if (err instanceof GraphError) {\n return { valid: false, warnings, error: err.message };\n }\n throw err;\n }\n}\n\nexport default defineCommand({\n meta: { name: \"validate\", description: \"Validate spec.config.yaml\" },\n args: { ...sharedArgs(FORMATS) },\n async run({ args }) {\n const format = resolveFormat(args.format, FORMATS);\n if (!format.ok) {\n console.error(`\\n ✗ ${format.message}\\n`);\n process.exit(1);\n }\n const output = createOutput({ quiet: args.quiet });\n\n const result = await runValidate(process.cwd());\n\n if (format.format === \"json\") {\n console.log(JSON.stringify(result, null, 2));\n if (!result.valid) process.exit(1);\n return;\n }\n\n if (result.valid) {\n output.info(\n ` ✓ Config valid. ${result.specEntries} spec entries, ${result.specFiles} spec files.`,\n );\n for (const w of result.warnings) output.out(` ⚠ ${w}`);\n return;\n }\n\n console.error(` ✗ Config invalid: ${result.error}`);\n for (const w of result.warnings) console.error(` ⚠ ${w}`);\n if (result.details) {\n for (const e of result.details) console.error(` - ${JSON.stringify(e)}`);\n }\n process.exit(1);\n },\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAEA,QAAM,YAAY;AAClB,QAAM,eAAe,KAAK,SAAS;AAMnC,QAAM,cAAc;AACpB,QAAM,eAAe;AACrB,QAAM,gBAAgB;AACtB,QAAM,gBAAgB;AACtB,QAAM,WAAW;AACjB,QAAM,QAAQ;AACd,QAAM,aAAa,MAAM,aAAa;AACt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AAO,KAAK,MAAM,CAAC;AAEjD,UAAM,SAAS,MAAM,YAAY,QAAQ,IAAI,CAAC;AAE9C,QAAI,OAAO,WAAW,QAAQ;AAC5B,cAAQ,IAAI,KAAK,UAAU,QAAQ,MAAM,CAAC,CAAC;AAC3C,UAAI,CAAC,OAAO,MAAO,SAAQ,KAAK,CAAC;AACjC;AAAA,IACF;AAEA,QAAI,OAAO,OAAO;AAChB,aAAO;AAAA,QACL,0BAAqB,OAAO,WAAW,kBAAkB,OAAO,SAAS;AAAA,MAC3E;AACA,iBAAW,KAAK,OAAO,SAAU,QAAO,IAAI,YAAO,CAAC,EAAE;AACtD;AAAA,IACF;AAEA,YAAQ,MAAM,4BAAuB,OAAO,KAAK,EAAE;AACnD,eAAW,KAAK,OAAO,SAAU,SAAQ,MAAM,YAAO,CAAC,EAAE;AACzD,QAAI,OAAO,SAAS;AAClB,iBAAW,KAAK,OAAO,QAAS,SAAQ,MAAM,SAAS,KAAK,UAAU,CAAC,CAAC,EAAE;AAAA,IAC5E;AACA,YAAQ,KAAK,CAAC;AAAA,EAChB;AACF,CAAC;","names":["glob","opts","value","rest","source","picomatch","glob","state","require_picomatch","picomatch","glob","defineCommand","join","join","readFile","parseYaml","readFile","parseYaml","join","readFile","resolve","isAbsolute","STOPWORDS","PLACEHOLDER_BODIES","meaningfulContent","basename","defineCommand","defineCommand","STOPWORDS","results","formatJson","formatJson","writeFile","defineCommand","defineCommand","join","tokenize","join","diff","value","overlap","r","o","diff","_loop","patchObj","diff","lastUpdated","execSync","dirname","resolve","execSync","resolve","picomatch","dirname","diff","diff","FORMATS","join","defineCommand","diff","defineCommand","FORMATS","defineCommand","defineCommand","FORMATS","defineCommand"]}