specdx 0.4.0-alpha.3 → 0.4.0-alpha.5
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/LICENSE +21 -0
- package/dist/{changelog-B2BDIW2P.js → changelog-HL6HA7HG.js} +15 -8
- package/dist/{changelog-B2BDIW2P.js.map → changelog-HL6HA7HG.js.map} +1 -1
- package/dist/{check-RWF2UOZB.js → check-XTL2VATS.js} +6 -3
- package/dist/check-XTL2VATS.js.map +1 -0
- package/dist/diff-GJYKGIG6.js +107 -0
- package/dist/diff-GJYKGIG6.js.map +1 -0
- package/dist/{dist-DISODEN3.js → dist-7GA3NJ3Y.js} +2 -2
- package/dist/{dist-DISODEN3.js.map → dist-7GA3NJ3Y.js.map} +1 -1
- package/dist/{explain-GGWBNDX2.js → explain-2I3M7ICY.js} +33 -26
- package/dist/explain-2I3M7ICY.js.map +1 -0
- package/dist/{generate-RAUVLJKF.js → generate-O6FWRGND.js} +3 -3
- package/dist/{generate-story-PIV6JDTF.js → generate-story-YRMLUF2A.js} +6 -2
- package/dist/generate-story-YRMLUF2A.js.map +1 -0
- package/dist/{generate-test-plan-4VEYZDMU.js → generate-test-plan-Q5C52KPL.js} +5 -2
- package/dist/{generate-test-plan-4VEYZDMU.js.map → generate-test-plan-Q5C52KPL.js.map} +1 -1
- package/dist/index.js +132 -104
- package/dist/index.js.map +1 -1
- package/dist/main.js +10 -10
- package/dist/{mcp-RFGBEGM3.js → mcp-DKM3YAHJ.js} +2 -2
- package/dist/{migrate-F3JBCVDR.js → migrate-677E4C5U.js} +2 -2
- package/dist/migrate-677E4C5U.js.map +1 -0
- package/dist/{ready-VFVDQS3A.js → ready-CYFUHCV3.js} +31 -24
- package/dist/{ready-VFVDQS3A.js.map → ready-CYFUHCV3.js.map} +1 -1
- package/dist/skills/specdx-check-drift.md +1 -1
- package/dist/skills/specdx-verify.md +1 -1
- package/dist/{status-GUYBEGOX.js → status-ZWDR2EZN.js} +36 -29
- package/dist/status-ZWDR2EZN.js.map +1 -0
- package/dist/{update-CTVV2TIE.js → update-P52U4ROV.js} +2 -2
- package/dist/update-P52U4ROV.js.map +1 -0
- package/hooks/session-start +0 -0
- package/package.json +18 -19
- package/dist/check-RWF2UOZB.js.map +0 -1
- package/dist/diff-7LJ4VVNG.js +0 -100
- package/dist/diff-7LJ4VVNG.js.map +0 -1
- package/dist/explain-GGWBNDX2.js.map +0 -1
- package/dist/generate-story-PIV6JDTF.js.map +0 -1
- package/dist/migrate-F3JBCVDR.js.map +0 -1
- package/dist/status-GUYBEGOX.js.map +0 -1
- package/dist/update-CTVV2TIE.js.map +0 -1
- /package/dist/{generate-RAUVLJKF.js.map → generate-O6FWRGND.js.map} +0 -0
- /package/dist/{mcp-RFGBEGM3.js.map → mcp-DKM3YAHJ.js.map} +0 -0
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/commands/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/lint.ts","../../core/src/config.ts","../../core/src/parser.ts","../../core/src/tokens.ts","../../core/src/graph.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/index.ts","../../lint/src/presets.ts","../../lint/src/custom-rule-loader.ts","../src/shared-args.ts","../src/formatters/pretty.ts","../src/formatters/json.ts","../src/formatters/github.ts","../src/commands/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/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/commands/status.ts","../src/commands/changelog.ts","../src/commands/explain.ts"],"sourcesContent":["import { defineCommand } from \"citty\";\nimport { mkdir, writeFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { REQUIRED_SECTIONS } from \"@specdx/schema\";\n\nexport type Template = \"lightweight\" | \"bmad\" | \"api-first\" | \"quick\" | \"context\";\n\ninterface 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 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\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\",\n required: true,\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 { name, 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 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","export 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\nexport interface SpecReference {\n id: string;\n relationship: \"implemented-by\" | \"decomposed-into\" | \"depends-on\" | \"supersedes\" | \"related-to\";\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}\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\": { \"type\": \"string\", \"minLength\": 1 },\n \"type\": { \"type\": \"string\", \"enum\": [\"prd\", \"technical-design\", \"user-story\", \"test-plan\", \"adr\", \"api-contract\", \"epic\", \"quick-spec\", \"project-context\"] },\n \"title\": { \"type\": \"string\", \"minLength\": 1 },\n \"status\": { \"type\": \"string\", \"enum\": [\"draft\", \"review\", \"approved\", \"superseded\"] },\n \"version\": { \"type\": \"string\" },\n \"created\": { \"type\": \"string\", \"format\": \"date\" },\n \"updated\": { \"type\": \"string\", \"format\": \"date\" },\n \"authors\": { \"type\": \"array\", \"items\": { \"type\": \"string\" }, \"minItems\": 1 },\n \"tags\": { \"type\": \"array\", \"items\": { \"type\": \"string\" }, \"default\": [] },\n \"references\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"object\",\n \"properties\": {\n \"id\": { \"type\": \"string\" },\n \"relationship\": { \"type\": \"string\", \"enum\": [\"implemented-by\", \"decomposed-into\", \"depends-on\", \"supersedes\", \"related-to\"] }\n },\n \"required\": [\"id\", \"relationship\"],\n \"additionalProperties\": false\n },\n \"default\": []\n }\n },\n \"required\": [\"id\", \"type\", \"title\", \"status\", \"version\", \"created\", \"authors\"],\n \"additionalProperties\": true\n}\n","{\n \"$id\": \"sdx-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 } from \"../shared-args.js\";\nimport { formatPretty } from \"../formatters/pretty.js\";\nimport { formatJson } from \"../formatters/json.js\";\nimport { formatGithub } from \"../formatters/github.js\";\n\nexport interface RunLintOptions {\n configDir: string;\n specPath?: string;\n preset?: \"minimal\" | \"recommended\" | \"strict\";\n}\n\nexport async function runLint(options: RunLintOptions): Promise<LintResults> {\n const config = await loadConfig(undefined, options.configDir);\n const preset = options.preset ?? config.lint?.extends ?? \"recommended\";\n const rules = getPreset(preset);\n\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 if (options.specPath && !file.includes(options.specPath)) continue;\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 (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;\n}\n\nexport default defineCommand({\n meta: { name: \"lint\", description: \"Lint all specs in the suite\" },\n args: {\n ...sharedArgs,\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\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 args.format === \"json\"\n ? formatJson\n : args.format === \"github\"\n ? formatGithub\n : formatPretty;\n console.log(formatter(results.diagnostics));\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 'sdx 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\";\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","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 diagnostics.push(...results);\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\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: ${err.message ?? JSON.stringify(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\";\n\nconst FEATURE_PATTERN = /\\*\\*F\\d+\\*\\*:\\s*(.+)/g;\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 const features: string[] = [];\n let match;\n const re = new RegExp(FEATURE_PATTERN.source, \"g\");\n while ((match = re.exec(context.spec.content)) !== null) {\n features.push(match[1]!.trim());\n }\n if (features.length === 0) return [];\n const stories = context.allSpecs.filter((s) => s.frontmatter.type === \"user-story\");\n const storyContent = stories.map((s) => s.content + \" \" + s.frontmatter.title).join(\" \");\n return features\n .filter((feature) => !storyContent.toLowerCase().includes(feature.toLowerCase()))\n .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 type { LintRule } from \"../types.js\";\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 refs = context.spec.frontmatter.references;\n if (!refs || (refs as unknown[]).length === 0) return [];\n const specUpdated =\n (context.spec.frontmatter.updated as string | undefined) ??\n (context.spec.frontmatter.created as string);\n const specDate = new Date(specUpdated);\n const diagnostics = [];\n for (const ref of refs as Array<{ id: string; relationship: string }>) {\n if (ref.relationship !== \"depends-on\" && ref.relationship !== \"implemented-by\") continue;\n const upstream = context.allSpecs.find((s) => s.frontmatter.id === ref.id);\n if (!upstream) continue;\n const upstreamUpdated =\n (upstream.frontmatter.updated as string | undefined) ??\n (upstream.frontmatter.created as string);\n const upstreamDate = new Date(upstreamUpdated);\n if (upstreamDate > specDate) {\n diagnostics.push({\n ruleId: \"freshness/staleness-check\",\n severity: \"warn\" as const,\n message: `Potentially stale: upstream \"${upstream.frontmatter.id}\" 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 \"404\",\n \"500\",\n \"missing\",\n \"malformed\",\n \"overflow\",\n \"duplicate\",\n \"graceful\",\n \"fall back\",\n \"fallback\",\n \"crash\",\n \"nonexistent\",\n \"corrupt\",\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 const content = context.spec.content.toLowerCase();\n const hasEdgeCases = EDGE_CASE_KEYWORDS.some((kw) => content.includes(kw));\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 `sdx check --ai` for LLM-powered ambiguity detection\",\n filePath: context.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 type { LintRule } from \"../types.js\";\n\nexport const structureRules: LintRule[] = [\n validFrontmatterRule,\n requiredSectionsRule,\n validReferencesRule,\n noCircularDepsRule,\n singleProjectContextRule,\n];\n\nexport const contentRules: LintRule[] = [\n storyCoverageRule,\n stalenessCheckRule,\n noVagueLanguageRule,\n terminologyRule,\n edgeCaseCoverageRule,\n namingConventionsRule,\n threatCoverageRule,\n ambiguityScoreAiRule,\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};\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 return allBuiltinRules.map((rule) => ({ ...rule, severity: \"error\" as const }));\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","export const sharedArgs = {\n quiet: { type: \"boolean\" as const, description: \"Suppress info output\", alias: [\"q\"] },\n verbose: { type: \"boolean\" as const, description: \"Enable debug output\", alias: [\"V\"] },\n format: {\n type: \"string\" as const,\n description: \"Output format (pretty, json, github)\",\n default: \"pretty\",\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\";\nexport function formatGithub(diagnostics: Diagnostic[]): string {\n return diagnostics\n .map((d) => {\n const level = d.severity === \"error\" ? \"error\" : \"warning\";\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 { sharedArgs } 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\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(options: RunPackOptions): Promise<PackResult> {\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;\n}\n\nexport default defineCommand({\n meta: { name: \"pack\", description: \"Pack specs into AI-ready context\" },\n args: {\n quiet: sharedArgs.quiet,\n verbose: sharedArgs.verbose,\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(\n ` Included: ${stats.specsIncluded} / ${stats.specsIncluded + stats.specsExcluded} specs`,\n );\n console.log(` Sections compressed: ${stats.sectionsCompressed}\\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\\n`,\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/** 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\n for (const [specId, spec] of specs) {\n let weightedHits = 0;\n const matched = new Set<string>();\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\n const results: RelevanceScore[] = [];\n for (const [specId] of specs) {\n const combined = finalRawScores.get(specId) ?? 0;\n const normalized = 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 });\n }\n\n // Sort descending by score\n results.sort((a, b) => b.score - a.score);\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/**\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 }\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\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 compressed = 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 options.compression,\n );\n }\n\n // 3. Calculate token count\n let tokens: number;\n if (compressed.collapsed) {\n tokens = countTokens(compressed.collapsedSummary ?? \"\");\n } else {\n tokens = 0;\n for (const section of compressed.sections) {\n tokens += section.tokens;\n }\n }\n\n items.push({ compressed, relevance: score.score, tokens });\n }\n\n // 4. Sort by relevance descending\n items.sort((a, b) => b.relevance - a.relevance);\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\n for (const item of items) {\n if (usedTokens + item.tokens <= options.budget) {\n included.push(item);\n usedTokens += item.tokens;\n } else {\n excluded.push(item);\n }\n }\n }\n\n // 6. Build stats\n let sectionsCompressed = 0;\n for (const item of included) {\n for (const section of item.compressed.sections) {\n if (section.compressed) {\n sectionsCompressed++;\n }\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 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, \"&\")\n .replace(/</g, \"<\")\n .replace(/>/g, \">\")\n .replace(/\"/g, \""\");\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}\">`,\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 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 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 type { DiffResult } from \"@specdx/diff\";\n\nexport interface RunDiffOptions {\n base?: string;\n head?: string;\n spec?: string;\n format?: string;\n}\n\nexport async function runDiff(options: RunDiffOptions): Promise<DiffResult> {\n const 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\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 spec: { type: \"string\", description: \"Scope to a single spec ID\" },\n format: {\n type: \"string\",\n description: \"Output format: pretty, json\",\n default: \"pretty\",\n },\n },\n async run({ args }) {\n try {\n const result = await runDiff({\n base: args.base,\n head: args.head,\n spec: args.spec,\n format: args.format,\n });\n\n if (args.format === \"json\") {\n console.log(JSON.stringify(result, null, 2));\n return;\n }\n\n // Pretty format\n if (result.diffs.length === 0 && result.added.length === 0 && result.removed.length === 0) {\n console.log(\" \\u2713 No spec changes detected.\");\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 } 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 },\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\nexport interface StatusResult {\n project: string;\n specCount: 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 verdict: \"healthy\" | \"warnings\" | \"errors\";\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 ˇ ˇ Caron\n// - U+02D8 ˘ ˘ Breve\n// - U+02D9 ˙ ˙ Dot Above\n// - U+02DA ˚ ˚ Ring Above\n// - U+02DB ˛ ˛ Ogonek\n// - U+02DC ˜ ˜ Small Tilde\n// - U+02DD ˝ ˝ 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, '&');\n n = n.replace(/</g, '<');\n n = n.replace(/>/g, '>');\n n = n.replace(/\"/g, '"');\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 { DependencyGraph, 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 node using the graph's edges.\n * Returns a map of nodeId -> shortest distance from the start node.\n */\nfunction bfsDistances(startId: string, graph: DependencyGraph): 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 graph.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 graph.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 graph: DependencyGraph,\n allSpecs: ParsedSpec[],\n thresholdDays = 14,\n): ImpactAnalysis {\n // 1. BFS to get downstream spec IDs with their distances\n const distanceMap = bfsDistances(changedSpecId, graph);\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 { realpathSync } from \"node:fs\";\nimport { dirname, relative, resolve } from \"node:path\";\nimport { loadConfig, parseSpecFromString, buildGraph } 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, 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 const root = execSync(\"git rev-parse --show-toplevel\", {\n cwd,\n encoding: \"utf-8\",\n stdio: \"pipe\",\n }).trim();\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\ninterface ChangedFiles {\n modified: string[];\n added: string[];\n deleted: string[];\n}\n\n/**\n * Get list of changed files between two refs, filtered to the given spec paths.\n */\nfunction getChangedSpecFiles(\n baseRef: string,\n headRef: string,\n specPaths: string[],\n projectRoot: string,\n repoRoot: string,\n): ChangedFiles {\n // Build a map from repo-relative path to project-relative path\n const repoRelToProjectRel = new Map<string, string>();\n for (const p of specPaths) {\n const repoRel = relative(repoRoot, resolve(projectRoot, p));\n repoRelToProjectRel.set(repoRel, p);\n }\n\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 projectRelPath = repoRelToProjectRel.get(filePath);\n if (projectRelPath === undefined) continue;\n\n if (status === \"M\") {\n result.modified.push(projectRelPath);\n } else if (status === \"A\") {\n result.added.push(projectRelPath);\n } else if (status === \"D\") {\n result.deleted.push(projectRelPath);\n }\n }\n\n return result;\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): Promise<DiffResult> {\n const projectRoot = realpathSync(dirname(resolve(configPath)));\n const repoRoot = getRepoRoot(projectRoot);\n\n // Validate refs\n validateRef(baseRef, projectRoot);\n validateRef(headRef, projectRoot);\n\n // Load config from filesystem (current version)\n const config = await loadConfig(configPath);\n\n // Collect all spec file paths from config\n const specPaths: string[] = [];\n const specIdByPath = new Map<string, string>();\n\n for (const [specId, entry] of Object.entries(config.specs)) {\n specPaths.push(entry.path);\n specIdByPath.set(entry.path, specId);\n }\n\n // Determine which spec files changed\n const changed = getChangedSpecFiles(baseRef, headRef, specPaths, projectRoot, repoRoot);\n\n // Build diffs for modified specs\n const diffs: SpecDiff[] = [];\n\n for (const filePath of changed.modified) {\n const beforeContent = gitShow(baseRef, filePath, projectRoot, repoRoot);\n const afterContent = gitShow(headRef, filePath, projectRoot, repoRoot);\n\n const beforeSpec = await parseSpecFromString(beforeContent, filePath);\n const afterSpec = await parseSpecFromString(afterContent, filePath);\n\n const diff = diffSpecs(beforeSpec, afterSpec);\n diffs.push(diff);\n }\n\n // Added and removed spec IDs\n const added = changed.added\n .map((p) => specIdByPath.get(p))\n .filter((id): id is string => id !== undefined);\n\n const removed = changed.deleted\n .map((p) => specIdByPath.get(p))\n .filter((id): id is string => id !== undefined);\n\n // Build graph and run impact analysis for each changed spec\n const graph = buildGraph(config);\n const impact: ImpactAnalysis[] = [];\n\n // Parse all current specs from head ref for impact analysis\n const allSpecs: ParsedSpec[] = [];\n for (const entry of Object.values(config.specs)) {\n try {\n const content = gitShow(headRef, entry.path, projectRoot, repoRoot);\n const parsed = await parseSpecFromString(content, entry.path);\n allSpecs.push(parsed);\n } catch {\n // Spec may have been deleted at head ref -- skip\n }\n }\n\n const thresholdDays = config.diff?.staleness_threshold_days ?? 14;\n\n for (const diff of diffs) {\n const analysis = analyzeImpact(diff.specId, diff, graph, 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 return { diffs, added, removed, impact, summary };\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\";\n\nexport async function runStatus(_options: { format?: string } = {}): Promise<StatusResult> {\n const 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\n let verdict: \"healthy\" | \"warnings\" | \"errors\" = \"healthy\";\n if (errors > 0) verdict = \"errors\";\n else if (warnings > 0 || staleSpecs.length > 0) verdict = \"warnings\";\n\n return {\n project: config.project?.name ?? \"unknown\",\n specCount: 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: {\n format: {\n type: \"string\",\n description: \"Output format: pretty, json, github\",\n default: \"pretty\",\n },\n },\n async run({ args }) {\n const result = await runStatus({ format: args.format });\n\n if (args.format === \"json\") {\n console.log(JSON.stringify(result, null, 2));\n return;\n }\n\n if (args.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 = result.verdict === \"healthy\" ? \"✓\" : result.verdict === \"warnings\" ? \"⚠\" : \"✗\";\n console.log(`\\n ${icon} ${result.project} — ${result.verdict}`);\n console.log(\n ` ${result.specCount} specs: ${Object.entries(result.byStatus)\n .map(([k, v]) => `${v} ${k}`)\n .join(\", \")}`,\n );\n console.log(\n ` Lint: ${result.lintHealth.errors} errors, ${result.lintHealth.warnings} warnings`,\n );\n\n if (result.staleSpecs.length > 0) {\n console.log(\n ` Stale: ${result.staleSpecs.map((s) => `${s.specId} (${s.daysSinceUpdate}d)`).join(\", \")}`,\n );\n }\n if (result.integrityIssues.length > 0) {\n console.log(` Issues: ${result.integrityIssues.join(\"; \")}`);\n }\n console.log();\n },\n});\n","import { defineCommand } from \"citty\";\nimport { join } from \"node:path\";\nimport { loadConfig } from \"@specdx/core\";\nimport { diffBetweenRefs, DEFAULT_DIFF_CONFIG, DiffError } from \"@specdx/diff\";\n\nexport interface RunChangelogOptions {\n from?: string;\n to?: string;\n}\n\nexport async function runChangelog(options: RunChangelogOptions): Promise<string> {\n const configDir = process.cwd();\n const config = await loadConfig(undefined, configDir);\n\n const fromRef = options.from ?? config.diff?.baseline_ref ?? DEFAULT_DIFF_CONFIG.baseline_ref;\n const toRef = options.to ?? \"HEAD\";\n\n const configPath = join(configDir, \"spec.config.yaml\");\n\n const result = await diffBetweenRefs(configPath, fromRef, toRef);\n\n const lines: string[] = [];\n lines.push(`## Spec Changes (${fromRef}..${toRef})\\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)} \\u2192 ${String(versionChange.after)})`\n : \"\";\n lines.push(`- **${diff.specId}**${versionStr} \\u2014 ${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 return lines.join(\"\\n\");\n}\n\nexport default defineCommand({\n meta: { name: \"changelog\", description: \"Generate changelog of spec changes between git refs\" },\n args: {\n from: { type: \"string\", description: \"Start git ref (default: from config or 'main')\" },\n to: { type: \"string\", description: \"End git ref (default: HEAD)\" },\n },\n async run({ args }) {\n try {\n const output = await runChangelog(args);\n console.log(output);\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 },\n});\n","import { defineCommand } from \"citty\";\nimport { loadConfig, parseSpec, buildGraph, resolveGlob } from \"@specdx/core\";\nimport type { ParsedSpec } from \"@specdx/core\";\n\ninterface ExplainResult {\n project: string;\n description?: string;\n specCount: number;\n byType: Record<string, number>;\n byStatus: Record<string, number>;\n specs: { id: string; type: string; title: string; status: string; firstLine: string }[];\n graph: string[];\n}\n\nexport async function runExplain(_options: { format?: string } = {}): Promise<ExplainResult> {\n const configDir = process.cwd();\n const config = await loadConfig(undefined, configDir);\n\n // Parse all specs\n const specs: ParsedSpec[] = [];\n for (const [, entry] of Object.entries(config.specs)) {\n const paths = await resolveGlob(entry.path, configDir);\n for (const p of paths) {\n specs.push(await parseSpec(p));\n }\n }\n\n // Count by type and status\n const byType: Record<string, number> = {};\n const byStatus: Record<string, number> = {};\n for (const spec of specs) {\n const type = (spec.frontmatter.type as string) || \"unknown\";\n const status = (spec.frontmatter.status as string) || \"unknown\";\n byType[type] = (byType[type] ?? 0) + 1;\n byStatus[status] = (byStatus[status] ?? 0) + 1;\n }\n\n // Build spec summaries — first sentence of first section content\n const specSummaries = specs.map((spec) => {\n const firstSection = spec.parsedSections[0];\n const firstLine =\n firstSection?.content\n ?.split(\"\\n\")\n .find((l) => l.trim().length > 0)\n ?.trim() ?? \"\";\n const truncated = firstLine.slice(0, 120) + (firstLine.length > 120 ? \"...\" : \"\");\n return {\n id: spec.frontmatter.id as string,\n type: spec.frontmatter.type as string,\n title: spec.frontmatter.title as string,\n status: spec.frontmatter.status as string,\n firstLine: truncated,\n };\n });\n\n // Build dependency graph lines\n const graph = buildGraph(config);\n const graphLines: string[] = [];\n for (const node of graph.nodes) {\n const downstream = graph.edges.filter((e) => e.from === node).map((e) => e.to);\n if (downstream.length > 0) {\n graphLines.push(`${node} → ${downstream.join(\", \")}`);\n } else {\n graphLines.push(node);\n }\n }\n\n return {\n project: config.project?.name ?? \"unknown\",\n description: config.project?.description,\n specCount: specs.length,\n byType,\n byStatus,\n specs: specSummaries,\n graph: graphLines,\n };\n}\n\nexport default defineCommand({\n meta: { name: \"explain\", description: \"Explain the spec suite for onboarding\" },\n args: {\n format: { type: \"string\", description: \"Output format: pretty, json\", default: \"pretty\" },\n },\n async run({ args }) {\n const result = await runExplain({ format: args.format });\n\n if (args.format === \"json\") {\n console.log(JSON.stringify(result, null, 2));\n return;\n }\n\n // Pretty format\n console.log(`\\n ${result.project}`);\n if (result.description) {\n console.log(` ${result.description}`);\n }\n console.log(\n `\\n ${result.specCount} specs: ${Object.entries(result.byType)\n .map(([k, v]) => `${v} ${k}`)\n .join(\", \")}`,\n );\n console.log(\n ` Status: ${Object.entries(result.byStatus)\n .map(([k, v]) => `${v} ${k}`)\n .join(\", \")}`,\n );\n\n console.log(\"\\n Specs:\");\n for (const spec of result.specs) {\n console.log(` ${spec.id} (${spec.type}, ${spec.status}) — ${spec.title}`);\n if (spec.firstLine) {\n console.log(` ${spec.firstLine}`);\n }\n }\n\n console.log(\"\\n Dependencies:\");\n for (const line of result.graph) {\n console.log(` ${line}`);\n }\n console.log();\n },\n});\n"],"mappings":";AAAA,SAAS,qBAAqB;AAC9B,SAAS,OAAO,iBAAiB;AACjC,SAAS,YAAY;;;ACFd,IAAM,aAAa;EACxB;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;;;ACPK,IAAM,oBAAgD;EAC3D,KAAK,CAAC,qBAAqB,SAAS,aAAa,YAAY,kBAAkB;EAC/E,oBAAoB;IAClB;IACA;IACA;IACA;IACA;IACA;IACA;;EAEF,cAAc,CAAC,eAAe,uBAAuB,gBAAgB,OAAO;EAC5E,aAAa,CAAC,SAAS,cAAc,mBAAmB,YAAY;EACpE,KAAK,CAAC,WAAW,YAAY,UAAU,cAAc;EACrD,gB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,SAAS,SAAS;AAAA,EAC1F;AAAA,EACA,MAAM,IAAI,EAAE,KAAK,GAAG;AAClB,UAAM,SAAS,MAAM,WAAW,EAAE,QAAQ,KAAK,OAAO,CAAC;AAEvD,QAAI,KAAK,WAAW,QAAQ;AAC1B,cAAQ,IAAI,KAAK,UAAU,QAAQ,MAAM,CAAC,CAAC;AAC3C;AAAA,IACF;AAGA,YAAQ,IAAI;AAAA,IAAO,OAAO,OAAO,EAAE;AACnC,QAAI,OAAO,aAAa;AACtB,cAAQ,IAAI,KAAK,OAAO,WAAW,EAAE;AAAA,IACvC;AACA,YAAQ;AAAA,MACN;AAAA,IAAO,OAAO,SAAS,WAAW,OAAO,QAAQ,OAAO,MAAM,EAC3D,IAAI,CAAC,CAAC,GAAG,CAAC,MAAM,GAAG,CAAC,IAAI,CAAC,EAAE,EAC3B,KAAK,IAAI,CAAC;AAAA,IACf;AACA,YAAQ;AAAA,MACN,aAAa,OAAO,QAAQ,OAAO,QAAQ,EACxC,IAAI,CAAC,CAAC,GAAG,CAAC,MAAM,GAAG,CAAC,IAAI,CAAC,EAAE,EAC3B,KAAK,IAAI,CAAC;AAAA,IACf;AAEA,YAAQ,IAAI,YAAY;AACxB,eAAW,QAAQ,OAAO,OAAO;AAC/B,cAAQ,IAAI,OAAO,KAAK,EAAE,KAAK,KAAK,IAAI,KAAK,KAAK,MAAM,YAAO,KAAK,KAAK,EAAE;AAC3E,UAAI,KAAK,WAAW;AAClB,gBAAQ,IAAI,SAAS,KAAK,SAAS,EAAE;AAAA,MACvC;AAAA,IACF;AAEA,YAAQ,IAAI,mBAAmB;AAC/B,eAAW,QAAQ,OAAO,OAAO;AAC/B,cAAQ,IAAI,OAAO,IAAI,EAAE;AAAA,IAC3B;AACA,YAAQ,IAAI;AAAA,EACd;AACF,CAAC;","names":["defineCommand","join","join","readFile","parseYaml","readFile","parseYaml","join","readFile","isAbsolute","defineCommand","defineCommand","STOPWORDS","results","formatJson","formatJson","writeFile","defineCommand","defineCommand","join","tokenize","join","diff","value","r","o","diff","_loop","patchObj","diff","execSync","dirname","resolve","execSync","resolve","dirname","diff","join","defineCommand","diff","defineCommand","defineCommand","defineCommand","join","join","diff","defineCommand","defineCommand","defineCommand"]}
|
|
1
|
+
{"version":3,"sources":["../src/commands/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/lint.ts","../../core/src/config.ts","../../core/src/parser.ts","../../core/src/tokens.ts","../../core/src/graph.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/index.ts","../../lint/src/presets.ts","../../lint/src/custom-rule-loader.ts","../src/shared-args.ts","../src/formatters/pretty.ts","../src/formatters/json.ts","../src/formatters/github.ts","../src/commands/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/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/commands/status.ts","../src/commands/changelog.ts","../src/commands/explain.ts"],"sourcesContent":["import { defineCommand } from \"citty\";\nimport { mkdir, writeFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { REQUIRED_SECTIONS } from \"@specdx/schema\";\n\nexport type Template = \"lightweight\" | \"bmad\" | \"api-first\" | \"quick\" | \"context\";\n\ninterface 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 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\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\",\n required: true,\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 { name, 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 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","export 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\nexport interface SpecReference {\n id: string;\n relationship: \"implemented-by\" | \"decomposed-into\" | \"depends-on\" | \"supersedes\" | \"related-to\";\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}\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\": { \"type\": \"string\", \"minLength\": 1 },\n \"type\": { \"type\": \"string\", \"enum\": [\"prd\", \"technical-design\", \"user-story\", \"test-plan\", \"adr\", \"api-contract\", \"epic\", \"quick-spec\", \"project-context\"] },\n \"title\": { \"type\": \"string\", \"minLength\": 1 },\n \"status\": { \"type\": \"string\", \"enum\": [\"draft\", \"review\", \"approved\", \"superseded\"] },\n \"version\": { \"type\": \"string\" },\n \"created\": { \"type\": \"string\", \"format\": \"date\" },\n \"updated\": { \"type\": \"string\", \"format\": \"date\" },\n \"authors\": { \"type\": \"array\", \"items\": { \"type\": \"string\" }, \"minItems\": 1 },\n \"tags\": { \"type\": \"array\", \"items\": { \"type\": \"string\" }, \"default\": [] },\n \"references\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"object\",\n \"properties\": {\n \"id\": { \"type\": \"string\" },\n \"relationship\": { \"type\": \"string\", \"enum\": [\"implemented-by\", \"decomposed-into\", \"depends-on\", \"supersedes\", \"related-to\"] }\n },\n \"required\": [\"id\", \"relationship\"],\n \"additionalProperties\": false\n },\n \"default\": []\n }\n },\n \"required\": [\"id\", \"type\", \"title\", \"status\", \"version\", \"created\", \"authors\"],\n \"additionalProperties\": true\n}\n","{\n \"$id\": \"sdx-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 } from \"../shared-args.js\";\nimport { formatPretty } from \"../formatters/pretty.js\";\nimport { formatJson } from \"../formatters/json.js\";\nimport { formatGithub } from \"../formatters/github.js\";\n\nexport interface RunLintOptions {\n configDir: string;\n specPath?: string;\n preset?: \"minimal\" | \"recommended\" | \"strict\";\n}\n\nexport async function runLint(options: RunLintOptions): Promise<LintResults> {\n const config = await loadConfig(undefined, options.configDir);\n const preset = options.preset ?? config.lint?.extends ?? \"recommended\";\n const rules = getPreset(preset);\n\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 if (options.specPath && !file.includes(options.specPath)) continue;\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 (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;\n}\n\nexport default defineCommand({\n meta: { name: \"lint\", description: \"Lint all specs in the suite\" },\n args: {\n ...sharedArgs,\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\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 args.format === \"json\"\n ? formatJson\n : args.format === \"github\"\n ? formatGithub\n : formatPretty;\n console.log(formatter(results.diagnostics));\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 'sdx 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\";\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","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 diagnostics.push(...results);\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\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: ${err.message ?? JSON.stringify(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\";\n\nconst FEATURE_PATTERN = /\\*\\*F\\d+\\*\\*:\\s*(.+)/g;\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 const features: string[] = [];\n let match;\n const re = new RegExp(FEATURE_PATTERN.source, \"g\");\n while ((match = re.exec(context.spec.content)) !== null) {\n features.push(match[1]!.trim());\n }\n if (features.length === 0) return [];\n const stories = context.allSpecs.filter((s) => s.frontmatter.type === \"user-story\");\n const storyContent = stories.map((s) => s.content + \" \" + s.frontmatter.title).join(\" \");\n return features\n .filter((feature) => !storyContent.toLowerCase().includes(feature.toLowerCase()))\n .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 type { LintRule } from \"../types.js\";\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 refs = context.spec.frontmatter.references;\n if (!refs || (refs as unknown[]).length === 0) return [];\n const specUpdated =\n (context.spec.frontmatter.updated as string | undefined) ??\n (context.spec.frontmatter.created as string);\n const specDate = new Date(specUpdated);\n const diagnostics = [];\n for (const ref of refs as Array<{ id: string; relationship: string }>) {\n if (ref.relationship !== \"depends-on\" && ref.relationship !== \"implemented-by\") continue;\n const upstream = context.allSpecs.find((s) => s.frontmatter.id === ref.id);\n if (!upstream) continue;\n const upstreamUpdated =\n (upstream.frontmatter.updated as string | undefined) ??\n (upstream.frontmatter.created as string);\n const upstreamDate = new Date(upstreamUpdated);\n if (upstreamDate > specDate) {\n diagnostics.push({\n ruleId: \"freshness/staleness-check\",\n severity: \"warn\" as const,\n message: `Potentially stale: upstream \"${upstream.frontmatter.id}\" 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 \"404\",\n \"500\",\n \"missing\",\n \"malformed\",\n \"overflow\",\n \"duplicate\",\n \"graceful\",\n \"fall back\",\n \"fallback\",\n \"crash\",\n \"nonexistent\",\n \"corrupt\",\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 const content = context.spec.content.toLowerCase();\n const hasEdgeCases = EDGE_CASE_KEYWORDS.some((kw) => content.includes(kw));\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 `sdx check --ai` for LLM-powered ambiguity detection\",\n filePath: context.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 type { LintRule } from \"../types.js\";\n\nexport const structureRules: LintRule[] = [\n validFrontmatterRule,\n requiredSectionsRule,\n validReferencesRule,\n noCircularDepsRule,\n singleProjectContextRule,\n];\n\nexport const contentRules: LintRule[] = [\n storyCoverageRule,\n stalenessCheckRule,\n noVagueLanguageRule,\n terminologyRule,\n edgeCaseCoverageRule,\n namingConventionsRule,\n threatCoverageRule,\n ambiguityScoreAiRule,\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};\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 return allBuiltinRules.map((rule) => ({ ...rule, severity: \"error\" as const }));\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","export const sharedArgs = {\n quiet: { type: \"boolean\" as const, description: \"Suppress info output\", alias: [\"q\"] },\n verbose: { type: \"boolean\" as const, description: \"Enable debug output\", alias: [\"V\"] },\n format: {\n type: \"string\" as const,\n description: \"Output format (pretty, json, github)\",\n default: \"pretty\",\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\";\nexport function formatGithub(diagnostics: Diagnostic[]): string {\n return diagnostics\n .map((d) => {\n const level = d.severity === \"error\" ? \"error\" : \"warning\";\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 { sharedArgs } 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\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(options: RunPackOptions): Promise<PackResult> {\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;\n}\n\nexport default defineCommand({\n meta: { name: \"pack\", description: \"Pack specs into AI-ready context\" },\n args: {\n quiet: sharedArgs.quiet,\n verbose: sharedArgs.verbose,\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(\n ` Included: ${stats.specsIncluded} / ${stats.specsIncluded + stats.specsExcluded} specs`,\n );\n console.log(` Sections compressed: ${stats.sectionsCompressed}\\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\\n`,\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/** 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\n for (const [specId, spec] of specs) {\n let weightedHits = 0;\n const matched = new Set<string>();\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\n const results: RelevanceScore[] = [];\n for (const [specId] of specs) {\n const combined = finalRawScores.get(specId) ?? 0;\n const normalized = 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 });\n }\n\n // Sort descending by score\n results.sort((a, b) => b.score - a.score);\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/**\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 }\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\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 compressed = 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 options.compression,\n );\n }\n\n // 3. Calculate token count\n let tokens: number;\n if (compressed.collapsed) {\n tokens = countTokens(compressed.collapsedSummary ?? \"\");\n } else {\n tokens = 0;\n for (const section of compressed.sections) {\n tokens += section.tokens;\n }\n }\n\n items.push({ compressed, relevance: score.score, tokens });\n }\n\n // 4. Sort by relevance descending\n items.sort((a, b) => b.relevance - a.relevance);\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\n for (const item of items) {\n if (usedTokens + item.tokens <= options.budget) {\n included.push(item);\n usedTokens += item.tokens;\n } else {\n excluded.push(item);\n }\n }\n }\n\n // 6. Build stats\n let sectionsCompressed = 0;\n for (const item of included) {\n for (const section of item.compressed.sections) {\n if (section.compressed) {\n sectionsCompressed++;\n }\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 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, \"&\")\n .replace(/</g, \"<\")\n .replace(/>/g, \">\")\n .replace(/\"/g, \""\");\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}\">`,\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 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 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 type { DiffResult } from \"@specdx/diff\";\n\nexport interface RunDiffOptions {\n base?: string;\n head?: string;\n spec?: string;\n format?: string;\n}\n\nexport async function runDiff(options: RunDiffOptions): Promise<DiffResult> {\n const 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\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 spec: { type: \"string\", description: \"Scope to a single spec ID\" },\n format: {\n type: \"string\",\n description: \"Output format: pretty, json\",\n default: \"pretty\",\n },\n },\n async run({ args }) {\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 });\n\n if (args.format === \"json\") {\n console.log(JSON.stringify(result, null, 2));\n return;\n }\n\n // Pretty format\n if (result.diffs.length === 0 && result.added.length === 0 && result.removed.length === 0) {\n console.log(\" \\u2713 No spec changes detected.\");\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 } 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\nexport interface StatusResult {\n project: string;\n specCount: 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 verdict: \"healthy\" | \"warnings\" | \"errors\";\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 ˇ ˇ Caron\n// - U+02D8 ˘ ˘ Breve\n// - U+02D9 ˙ ˙ Dot Above\n// - U+02DA ˚ ˚ Ring Above\n// - U+02DB ˛ ˛ Ogonek\n// - U+02DC ˜ ˜ Small Tilde\n// - U+02DD ˝ ˝ 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, '&');\n n = n.replace(/</g, '<');\n n = n.replace(/>/g, '>');\n n = n.replace(/\"/g, '"');\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 { DependencyGraph, 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 node using the graph's edges.\n * Returns a map of nodeId -> shortest distance from the start node.\n */\nfunction bfsDistances(startId: string, graph: DependencyGraph): 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 graph.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 graph.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 graph: DependencyGraph,\n allSpecs: ParsedSpec[],\n thresholdDays = 14,\n): ImpactAnalysis {\n // 1. BFS to get downstream spec IDs with their distances\n const distanceMap = bfsDistances(changedSpecId, graph);\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 { realpathSync } from \"node:fs\";\nimport { dirname, relative, resolve } from \"node:path\";\nimport { loadConfig, parseSpecFromString, buildGraph } 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, 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 const root = execSync(\"git rev-parse --show-toplevel\", {\n cwd,\n encoding: \"utf-8\",\n stdio: \"pipe\",\n }).trim();\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\ninterface ChangedFiles {\n modified: string[];\n added: string[];\n deleted: string[];\n}\n\n/**\n * Get list of changed files between two refs, filtered to the given spec paths.\n */\nfunction getChangedSpecFiles(\n baseRef: string,\n headRef: string,\n specPaths: string[],\n projectRoot: string,\n repoRoot: string,\n): ChangedFiles {\n // Build a map from repo-relative path to project-relative path\n const repoRelToProjectRel = new Map<string, string>();\n for (const p of specPaths) {\n const repoRel = relative(repoRoot, resolve(projectRoot, p));\n repoRelToProjectRel.set(repoRel, p);\n }\n\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 projectRelPath = repoRelToProjectRel.get(filePath);\n if (projectRelPath === undefined) continue;\n\n if (status === \"M\") {\n result.modified.push(projectRelPath);\n } else if (status === \"A\") {\n result.added.push(projectRelPath);\n } else if (status === \"D\") {\n result.deleted.push(projectRelPath);\n }\n }\n\n return result;\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): Promise<DiffResult> {\n const projectRoot = realpathSync(dirname(resolve(configPath)));\n const repoRoot = getRepoRoot(projectRoot);\n\n // Validate refs\n validateRef(baseRef, projectRoot);\n validateRef(headRef, projectRoot);\n\n // Load config from filesystem (current version)\n const config = await loadConfig(configPath);\n\n // Collect all spec file paths from config\n const specPaths: string[] = [];\n const specIdByPath = new Map<string, string>();\n\n for (const [specId, entry] of Object.entries(config.specs)) {\n specPaths.push(entry.path);\n specIdByPath.set(entry.path, specId);\n }\n\n // Determine which spec files changed\n const changed = getChangedSpecFiles(baseRef, headRef, specPaths, projectRoot, repoRoot);\n\n // Build diffs for modified specs\n const diffs: SpecDiff[] = [];\n\n for (const filePath of changed.modified) {\n const beforeContent = gitShow(baseRef, filePath, projectRoot, repoRoot);\n const afterContent = gitShow(headRef, filePath, projectRoot, repoRoot);\n\n const beforeSpec = await parseSpecFromString(beforeContent, filePath);\n const afterSpec = await parseSpecFromString(afterContent, filePath);\n\n const diff = diffSpecs(beforeSpec, afterSpec);\n diffs.push(diff);\n }\n\n // Added and removed spec IDs\n const added = changed.added\n .map((p) => specIdByPath.get(p))\n .filter((id): id is string => id !== undefined);\n\n const removed = changed.deleted\n .map((p) => specIdByPath.get(p))\n .filter((id): id is string => id !== undefined);\n\n // Build graph and run impact analysis for each changed spec\n const graph = buildGraph(config);\n const impact: ImpactAnalysis[] = [];\n\n // Parse all current specs from head ref for impact analysis\n const allSpecs: ParsedSpec[] = [];\n for (const entry of Object.values(config.specs)) {\n try {\n const content = gitShow(headRef, entry.path, projectRoot, repoRoot);\n const parsed = await parseSpecFromString(content, entry.path);\n allSpecs.push(parsed);\n } catch {\n // Spec may have been deleted at head ref -- skip\n }\n }\n\n const thresholdDays = config.diff?.staleness_threshold_days ?? 14;\n\n for (const diff of diffs) {\n const analysis = analyzeImpact(diff.specId, diff, graph, 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 return { diffs, added, removed, impact, summary };\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\";\n\nexport async function runStatus(_options: { format?: string } = {}): Promise<StatusResult> {\n const 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\n let verdict: \"healthy\" | \"warnings\" | \"errors\" = \"healthy\";\n if (errors > 0) verdict = \"errors\";\n else if (warnings > 0 || staleSpecs.length > 0) verdict = \"warnings\";\n\n return {\n project: config.project?.name ?? \"unknown\",\n specCount: 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: {\n format: {\n type: \"string\",\n description: \"Output format: pretty, json, github\",\n default: \"pretty\",\n },\n },\n async run({ args }) {\n try {\n const result = await runStatus({ format: args.format });\n\n if (args.format === \"json\") {\n console.log(JSON.stringify(result, null, 2));\n return;\n }\n\n if (args.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 = result.verdict === \"healthy\" ? \"✓\" : result.verdict === \"warnings\" ? \"⚠\" : \"✗\";\n console.log(`\\n ${icon} ${result.project} — ${result.verdict}`);\n console.log(\n ` ${result.specCount} specs: ${Object.entries(result.byStatus)\n .map(([k, v]) => `${v} ${k}`)\n .join(\", \")}`,\n );\n console.log(\n ` Lint: ${result.lintHealth.errors} errors, ${result.lintHealth.warnings} warnings`,\n );\n\n if (result.staleSpecs.length > 0) {\n console.log(\n ` Stale: ${result.staleSpecs.map((s) => `${s.specId} (${s.daysSinceUpdate}d)`).join(\", \")}`,\n );\n }\n if (result.integrityIssues.length > 0) {\n console.log(` Issues: ${result.integrityIssues.join(\"; \")}`);\n }\n console.log();\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 { join } from \"node:path\";\nimport { loadConfig } from \"@specdx/core\";\nimport { diffBetweenRefs, DEFAULT_DIFF_CONFIG, DiffError } from \"@specdx/diff\";\n\nexport interface RunChangelogOptions {\n from?: string;\n to?: string;\n}\n\nexport async function runChangelog(options: RunChangelogOptions): Promise<string> {\n const configDir = process.cwd();\n const config = await loadConfig(undefined, configDir);\n\n const fromRef = options.from ?? config.diff?.baseline_ref ?? DEFAULT_DIFF_CONFIG.baseline_ref;\n const toRef = options.to ?? \"HEAD\";\n\n const configPath = join(configDir, \"spec.config.yaml\");\n\n const result = await diffBetweenRefs(configPath, fromRef, toRef);\n\n const lines: string[] = [];\n lines.push(`## Spec Changes (${fromRef}..${toRef})\\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)} \\u2192 ${String(versionChange.after)})`\n : \"\";\n lines.push(`- **${diff.specId}**${versionStr} \\u2014 ${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 return lines.join(\"\\n\");\n}\n\nexport default defineCommand({\n meta: { name: \"changelog\", description: \"Generate changelog of spec changes between git refs\" },\n args: {\n from: { type: \"string\", description: \"Start git ref (default: from config or 'main')\" },\n to: { type: \"string\", description: \"End git ref (default: HEAD)\" },\n },\n async run({ args }) {\n try {\n try {\n const output = await runChangelog(args);\n console.log(output);\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","import { defineCommand } from \"citty\";\nimport { loadConfig, parseSpec, buildGraph, resolveGlob } from \"@specdx/core\";\nimport type { ParsedSpec } from \"@specdx/core\";\n\ninterface ExplainResult {\n project: string;\n description?: string;\n specCount: number;\n byType: Record<string, number>;\n byStatus: Record<string, number>;\n specs: { id: string; type: string; title: string; status: string; firstLine: string }[];\n graph: string[];\n}\n\nexport async function runExplain(_options: { format?: string } = {}): Promise<ExplainResult> {\n const configDir = process.cwd();\n const config = await loadConfig(undefined, configDir);\n\n // Parse all specs\n const specs: ParsedSpec[] = [];\n for (const [, entry] of Object.entries(config.specs)) {\n const paths = await resolveGlob(entry.path, configDir);\n for (const p of paths) {\n specs.push(await parseSpec(p));\n }\n }\n\n // Count by type and status\n const byType: Record<string, number> = {};\n const byStatus: Record<string, number> = {};\n for (const spec of specs) {\n const type = (spec.frontmatter.type as string) || \"unknown\";\n const status = (spec.frontmatter.status as string) || \"unknown\";\n byType[type] = (byType[type] ?? 0) + 1;\n byStatus[status] = (byStatus[status] ?? 0) + 1;\n }\n\n // Build spec summaries — first sentence of first section content\n const specSummaries = specs.map((spec) => {\n const firstSection = spec.parsedSections[0];\n const firstLine =\n firstSection?.content\n ?.split(\"\\n\")\n .find((l) => l.trim().length > 0)\n ?.trim() ?? \"\";\n const truncated = firstLine.slice(0, 120) + (firstLine.length > 120 ? \"...\" : \"\");\n return {\n id: spec.frontmatter.id as string,\n type: spec.frontmatter.type as string,\n title: spec.frontmatter.title as string,\n status: spec.frontmatter.status as string,\n firstLine: truncated,\n };\n });\n\n // Build dependency graph lines\n const graph = buildGraph(config);\n const graphLines: string[] = [];\n for (const node of graph.nodes) {\n const downstream = graph.edges.filter((e) => e.from === node).map((e) => e.to);\n if (downstream.length > 0) {\n graphLines.push(`${node} → ${downstream.join(\", \")}`);\n } else {\n graphLines.push(node);\n }\n }\n\n return {\n project: config.project?.name ?? \"unknown\",\n description: config.project?.description,\n specCount: specs.length,\n byType,\n byStatus,\n specs: specSummaries,\n graph: graphLines,\n };\n}\n\nexport default defineCommand({\n meta: { name: \"explain\", description: \"Explain the spec suite for onboarding\" },\n args: {\n format: { type: \"string\", description: \"Output format: pretty, json\", default: \"pretty\" },\n },\n async run({ args }) {\n try {\n const result = await runExplain({ format: args.format });\n\n if (args.format === \"json\") {\n console.log(JSON.stringify(result, null, 2));\n return;\n }\n\n // Pretty format\n console.log(`\\n ${result.project}`);\n if (result.description) {\n console.log(` ${result.description}`);\n }\n console.log(\n `\\n ${result.specCount} specs: ${Object.entries(result.byType)\n .map(([k, v]) => `${v} ${k}`)\n .join(\", \")}`,\n );\n console.log(\n ` Status: ${Object.entries(result.byStatus)\n .map(([k, v]) => `${v} ${k}`)\n .join(\", \")}`,\n );\n\n console.log(\"\\n Specs:\");\n for (const spec of result.specs) {\n console.log(` ${spec.id} (${spec.type}, ${spec.status}) — ${spec.title}`);\n if (spec.firstLine) {\n console.log(` ${spec.firstLine}`);\n }\n }\n\n console.log(\"\\n Dependencies:\");\n for (const line of result.graph) {\n console.log(` ${line}`);\n }\n console.log();\n } catch (err) {\n console.error(`\\n ✗ ${(err as Error).message}\\n`);\n process.exit(1);\n }\n },\n});\n"],"mappings":";AAAA,SAAS,qBAAqB;AAC9B,SAAS,OAAO,iBAAiB;AACjC,SAAS,YAAY;;;ACFd,IAAM,aAAa;EACxB;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;;;ACPK,IAAM,oBAAgD;EAC3D,KAAK,CAAC,qBAAqB,SAAS,aAAa,YAAY,kBAAkB;EAC/E,oBAAoB;IAClB;IACA;IACA;IACA;IACA;IACA;IACA;;EAEF,cAAc,CAAC,eAAe,uBAAuB,gBAAgB,OAAO;EAC5E,aAAa,CAAC,SAAS,cAAc,mBAAmB,YAAY;EACpE,KAAK,CAAC,WAAW,YAAY,UAAU,cAAc;EACrD,gBAAgB,CAAC,aAAa,4BAA4B,QAAQ,aAAa;EAC/E,MAAM,CAAC,YAAY,WAAW,uBAAuB,cAAc;EACnE,cAAc,CAAC,UAAU,cAAc,OAAO;EAC9C,mBAAmB,CAAC,oBAAoB,iC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,mBAAmB;AAC/B,iBAAW,QAAQ,OAAO,OAAO;AAC/B,gBAAQ,IAAI,OAAO,IAAI,EAAE;AAAA,MAC3B;AACA,cAAQ,IAAI;AAAA,IACd,SAAS,KAAK;AACZ,cAAQ,MAAM;AAAA,WAAU,IAAc,OAAO;AAAA,CAAI;AACjD,cAAQ,KAAK,CAAC;AAAA,IAChB;AAAA,EACF;AACF,CAAC;","names":["defineCommand","join","join","readFile","parseYaml","readFile","parseYaml","join","readFile","isAbsolute","defineCommand","defineCommand","STOPWORDS","results","formatJson","formatJson","writeFile","defineCommand","defineCommand","join","tokenize","join","diff","value","r","o","diff","_loop","patchObj","diff","execSync","dirname","resolve","execSync","resolve","dirname","diff","join","defineCommand","diff","defineCommand","defineCommand","defineCommand","join","join","diff","defineCommand","defineCommand","defineCommand"]}
|