specdx 0.2.0-alpha.1 → 0.2.0-alpha.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-PL7UZ73U.js → chunk-NTNH2EPU.js} +1 -1
- package/dist/chunk-NTNH2EPU.js.map +1 -0
- package/dist/{graph-5GRXP63B.js → graph-GOJ4EJED.js} +2 -2
- package/dist/graph-GOJ4EJED.js.map +1 -0
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/{lint-KLELGQD2.js → lint-3WMYPOU4.js} +2 -2
- package/dist/lint-3WMYPOU4.js.map +1 -0
- package/dist/main.js +7 -7
- package/dist/main.js.map +1 -1
- package/dist/{pack-KCLS3VVU.js → pack-T4SVXU5B.js} +2 -2
- package/dist/pack-T4SVXU5B.js.map +1 -0
- package/dist/skills/specdx-author-spec/SKILL.md +115 -0
- package/dist/skills/specdx-start-task/SKILL.md +58 -0
- package/dist/{skills-4K7GSN5D.js → skills-FVSFWYHN.js} +10 -9
- package/dist/skills-FVSFWYHN.js.map +1 -0
- package/dist/{validate-G26G2F27.js → validate-TGMAJAPX.js} +2 -2
- package/dist/validate-TGMAJAPX.js.map +1 -0
- package/package.json +7 -7
- package/dist/chunk-PL7UZ73U.js.map +0 -1
- package/dist/graph-5GRXP63B.js.map +0 -1
- package/dist/lint-KLELGQD2.js.map +0 -1
- package/dist/pack-KCLS3VVU.js.map +0 -1
- package/dist/skills/sdx-author-spec.md +0 -327
- package/dist/skills/sdx-start-task.md +0 -244
- package/dist/skills-4K7GSN5D.js.map +0 -1
- package/dist/validate-G26G2F27.js.map +0 -1
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/commands/init.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","../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","../../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/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"],"sourcesContent":["import { defineCommand } from \"citty\";\nimport { mkdir, writeFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { REQUIRED_SECTIONS } from \"@sdx/schema\";\n\nexport type Template = \"lightweight\" | \"bmad\" | \"api-first\";\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};\n\nconst TEMPLATE_EXTRA_DIRS: Record<Template, string[]> = {\n lightweight: [],\n bmad: [\"specs/stories\", \"specs/adr\"],\n \"api-first\": [],\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 SDX 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\"];\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","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};\n","import { Ajv as AjvClass, type ErrorObject } from \"ajv\";\nimport 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\" };\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\nconst ajv = new AjvClass({ allErrors: true, strict: true });\naddFormats(ajv, [\"date\"]);\najv.addSchema(baseSpecSchema);\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};\n\nconst configValidator = ajv.compile(configSchema);\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\"] },\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\"] },\n \"required\": { \"type\": \"boolean\", \"default\": false },\n \"requires\": { \"type\": \"array\", \"items\": { \"type\": \"string\" } }\n },\n \"required\": [\"path\", \"type\"],\n \"additionalProperties\": false\n }\n },\n \"lint\": {\n \"type\": \"object\",\n \"properties\": {\n \"extends\": { \"type\": \"string\", \"enum\": [\"minimal\", \"recommended\", \"strict\"] },\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\": { \"type\": \"object\" },\n \"ci\": { \"type\": \"object\" }\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","import { defineCommand } from \"citty\";\nimport { loadConfig, parseSpec, resolveGlob, buildGraph, createLogger } from \"@sdx/core\";\nimport { createLintEngine, getPreset, type LintResults } from \"@sdx/lint\";\nimport type { ParsedSpec } from \"@sdx/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 as any) ?? \"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 any,\n });\n\n const formatter =\n args.format === \"json\" ? formatJson : args.format === \"github\" ? formatGithub : 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 \"@sdx/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 \"@sdx/schema\";\nimport type { BaseSpec, SpecType } from \"@sdx/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 const ext = extname(filePath).toLowerCase();\n if (ext === \".yaml\" || ext === \".yml\") {\n return parseYamlSpec(filePath, raw);\n }\n return parseMarkdownSpec(filePath, raw);\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 { filePath, frontmatter, content: \"\", sections: [], parsedSections: [], valid, validationErrors };\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: any) => {\n if (node.depth === 2) {\n const text = node.children\n .filter((c: any) => c.type === \"text\")\n .map((c: any) => 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 \"@sdx/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 type { ParsedSpec, DependencyGraph } from \"@sdx/core\";\nimport type { SdxConfig } from \"@sdx/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 \"@sdx/schema\";\nimport type { SpecType } from \"@sdx/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 { 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 type { LintRule } from \"../types.js\";\n\nexport const structureRules: LintRule[] = [\n validFrontmatterRule,\n requiredSectionsRule,\n validReferencesRule,\n noCircularDepsRule,\n];\n\nexport const contentRules: LintRule[] = [\n storyCoverageRule,\n stalenessCheckRule,\n noVagueLanguageRule,\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};\n","import type { LintRule } from \"./types.js\";\nimport { structureRules, allBuiltinRules } from \"./rules/index.js\";\n\nexport function getPreset(name: \"minimal\" | \"recommended\" | \"strict\"): 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 }\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 \"@sdx/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 \"@sdx/lint\";\nexport function formatJson(diagnostics: Diagnostic[]): string {\n return JSON.stringify(diagnostics, null, 2);\n}\n","import type { Diagnostic } from \"@sdx/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 \"@sdx/core\";\nimport { pack, type PackResult } from \"@sdx/pack\";\nimport type { ParsedSpec } from \"@sdx/core\";\nimport { sharedArgs } from \"../shared-args.js\";\nimport { writeFile } from \"node:fs/promises\";\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 full: { type: \"boolean\", description: \"Include all specs without budget trimming\" },\n \"dry-run\": { type: \"boolean\", description: \"Preview what would be packed without writing output\" },\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: --budget is a valid number\n let budget: number | undefined;\n if (args.budget) {\n budget = Number(args.budget);\n if (Number.isNaN(budget)) {\n console.error(\"\\n \\u2717 --budget must be a valid number\\n\");\n process.exit(1);\n }\n }\n\n // Validate: --format is valid\n const format = args.format as string;\n if (format && ![\"xml\", \"markdown\", \"json\"].includes(format)) {\n console.error(`\\n \\u2717 --format must be one of: xml, markdown, json\\n`);\n process.exit(1);\n }\n\n try {\n const specsList = args.specs ? args.specs.split(\",\").map((s: string) => s.trim()) : undefined;\n\n const result = await runPack({\n configDir: process.cwd(),\n task: args.task,\n specs: specsList,\n budget,\n format: format as \"xml\" | \"markdown\" | \"json\" | undefined,\n full: args.full,\n dryRun: args[\"dry-run\"],\n });\n\n const { stats } = result;\n\n // Dry-run: print plan to stdout\n if (args[\"dry-run\"]) {\n console.log(\"\\n Dry Run Summary:\\n\");\n for (const alloc of stats.allocations) {\n const status = alloc.included ? \"\\u2713\" : \"\\u2717\";\n const compressed = alloc.compressed ? \" (compressed)\" : \"\";\n console.log(\n ` ${status} ${alloc.specId} relevance=${alloc.relevance.toFixed(2)} tokens=${alloc.tokens}${compressed}`,\n );\n }\n console.log(`\\n Budget: ${stats.used} / ${stats.budget} tokens`);\n console.log(` Included: ${stats.specsIncluded} / ${stats.specsIncluded + stats.specsExcluded} specs`);\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 } else {\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 \"@sdx/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\", \"an\", \"and\", \"are\", \"as\", \"at\", \"be\", \"but\", \"by\", \"do\", \"for\",\n \"from\", \"had\", \"has\", \"have\", \"he\", \"her\", \"his\", \"how\", \"i\", \"if\",\n \"in\", \"into\", \"is\", \"it\", \"its\", \"just\", \"me\", \"my\", \"no\", \"nor\",\n \"not\", \"of\", \"on\", \"or\", \"our\", \"out\", \"own\", \"say\", \"she\", \"so\",\n \"some\", \"such\", \"than\", \"that\", \"the\", \"their\", \"them\", \"then\",\n \"there\", \"these\", \"they\", \"this\", \"to\", \"too\", \"up\", \"us\", \"very\",\n \"was\", \"we\", \"were\", \"what\", \"when\", \"where\", \"which\", \"while\",\n \"who\", \"whom\", \"why\", \"will\", \"with\", \"would\", \"you\", \"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 \"@sdx/core\";\nimport type { ParsedSection } from \"@sdx/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 (\n type === \"adr\" &&\n status === \"superseded\" &&\n options.collapseResolvedAdrs\n ) {\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 =\n options.stableDays > 0 && isOlderThanDays(updatedDate, options.stableDays);\n\n // 3. Process sections\n const boilerplateSet = new Set(\n options.boilerplateSections.map((s) => s.toLowerCase()),\n );\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 \"@sdx/core\";\nimport type { ParsedSpec } from \"@sdx/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(\n specs: CompressedSpec[],\n stats: PackStats,\n): 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\n ? ' compressed=\"true\"'\n : \"\";\n lines.push(\n ` <section name=\"${escapeXml(section.heading)}\"${compressedAttr}>`,\n );\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(\n specs: CompressedSpec[],\n stats: PackStats,\n): 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(\n specs: CompressedSpec[],\n stats: PackStats,\n): 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 \"@sdx/core\";\nimport type { PackConfig } from \"@sdx/schema\";\nimport type { PackOptions, PackResult, CompressionOptions } 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. Build spec map for resolver\n const specMap = new Map<string, ParsedSpec>();\n for (const spec of specs) {\n specMap.set(spec.frontmatter.id, spec);\n }\n\n // 3. Stage 1 - Resolve\n const scores = options.specs\n ? scoreSpecsByIds(specMap, options.specs, resolvedGraph)\n : scoreSpecs(specMap, options.task, resolvedGraph);\n\n // 4. Stage 2 - Allocate\n const { specs: compressedSpecs, stats } = allocate(specs, scores, {\n budget,\n full,\n compression,\n });\n\n // 5. Dry run: return stats without output\n if (options.dryRun) {\n return { output: \"\", stats };\n }\n\n // 6. Stage 3 - Format\n let output: string;\n switch (format) {\n case \"markdown\":\n output = formatMarkdown(compressedSpecs, stats);\n break;\n case \"json\":\n output = formatJson(compressedSpecs, stats);\n break;\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,MAAM,aAAa,MAAM,MAAM,gBAAgB,MAAM,aAAa,QAAQ;AACrG,gBAAQ,IAAI,0BAA0B,MAAM,kBAAkB;AAAA,CAAI;AAClE;AAAA,MACF;AAGA,UAAI,KAAK,KAAK;AACZ,cAAMD,WAAU,KAAK,KAAK,OAAO,QAAQ,OAAO;AAChD,eAAO,KAAK,qBAAqB,KAAK,GAAG,EAAE;AAAA,MAC7C,OAAO;AACL,gBAAQ,OAAO,MAAM,OAAO,MAAM;AAAA,MACpC;AAGA,YAAM,QAAQ,MAAM,gBAAgB,MAAM;AAC1C,cAAQ,OAAO;AAAA,QACb,UAAU,MAAM,aAAa,IAAI,KAAK,iBAAiB,MAAM,IAAI,MAAM,MAAM,MAAM,kBAAkB,MAAM,kBAAkB;AAAA;AAAA,MAC/H;AAAA,IACF,SAAS,KAAK;AACZ,cAAQ,MAAM;AAAA,WAAe,IAAc,OAAO;AAAA,CAAI;AACtD,cAAQ,KAAK,CAAC;AAAA,IAChB;AAAA,EACF;AACF,CAAC;","names":["defineCommand","join","join","readFile","parseYaml","readFile","parseYaml","join","defineCommand","defineCommand","results","formatJson","formatJson","writeFile","defineCommand"]}
|
|
1
|
+
{"version":3,"sources":["../src/commands/init.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","../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","../../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/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"],"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\";\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};\n\nconst TEMPLATE_EXTRA_DIRS: Record<Template, string[]> = {\n lightweight: [],\n bmad: [\"specs/stories\", \"specs/adr\"],\n \"api-first\": [],\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\"];\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","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};\n","import { Ajv as AjvClass, type ErrorObject } from \"ajv\";\nimport 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\" };\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\nconst ajv = new AjvClass({ allErrors: true, strict: true });\naddFormats(ajv, [\"date\"]);\najv.addSchema(baseSpecSchema);\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};\n\nconst configValidator = ajv.compile(configSchema);\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\"] },\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\"] },\n \"required\": { \"type\": \"boolean\", \"default\": false },\n \"requires\": { \"type\": \"array\", \"items\": { \"type\": \"string\" } }\n },\n \"required\": [\"path\", \"type\"],\n \"additionalProperties\": false\n }\n },\n \"lint\": {\n \"type\": \"object\",\n \"properties\": {\n \"extends\": { \"type\": \"string\", \"enum\": [\"minimal\", \"recommended\", \"strict\"] },\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\": { \"type\": \"object\" },\n \"ci\": { \"type\": \"object\" }\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","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 as any) ?? \"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 any,\n });\n\n const formatter =\n args.format === \"json\" ? formatJson : args.format === \"github\" ? formatGithub : 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 const ext = extname(filePath).toLowerCase();\n if (ext === \".yaml\" || ext === \".yml\") {\n return parseYamlSpec(filePath, raw);\n }\n return parseMarkdownSpec(filePath, raw);\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 { filePath, frontmatter, content: \"\", sections: [], parsedSections: [], valid, validationErrors };\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: any) => {\n if (node.depth === 2) {\n const text = node.children\n .filter((c: any) => c.type === \"text\")\n .map((c: any) => 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 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 { 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 type { LintRule } from \"../types.js\";\n\nexport const structureRules: LintRule[] = [\n validFrontmatterRule,\n requiredSectionsRule,\n validReferencesRule,\n noCircularDepsRule,\n];\n\nexport const contentRules: LintRule[] = [\n storyCoverageRule,\n stalenessCheckRule,\n noVagueLanguageRule,\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};\n","import type { LintRule } from \"./types.js\";\nimport { structureRules, allBuiltinRules } from \"./rules/index.js\";\n\nexport function getPreset(name: \"minimal\" | \"recommended\" | \"strict\"): 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 }\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\";\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 full: { type: \"boolean\", description: \"Include all specs without budget trimming\" },\n \"dry-run\": { type: \"boolean\", description: \"Preview what would be packed without writing output\" },\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: --budget is a valid number\n let budget: number | undefined;\n if (args.budget) {\n budget = Number(args.budget);\n if (Number.isNaN(budget)) {\n console.error(\"\\n \\u2717 --budget must be a valid number\\n\");\n process.exit(1);\n }\n }\n\n // Validate: --format is valid\n const format = args.format as string;\n if (format && ![\"xml\", \"markdown\", \"json\"].includes(format)) {\n console.error(`\\n \\u2717 --format must be one of: xml, markdown, json\\n`);\n process.exit(1);\n }\n\n try {\n const specsList = args.specs ? args.specs.split(\",\").map((s: string) => s.trim()) : undefined;\n\n const result = await runPack({\n configDir: process.cwd(),\n task: args.task,\n specs: specsList,\n budget,\n format: format as \"xml\" | \"markdown\" | \"json\" | undefined,\n full: args.full,\n dryRun: args[\"dry-run\"],\n });\n\n const { stats } = result;\n\n // Dry-run: print plan to stdout\n if (args[\"dry-run\"]) {\n console.log(\"\\n Dry Run Summary:\\n\");\n for (const alloc of stats.allocations) {\n const status = alloc.included ? \"\\u2713\" : \"\\u2717\";\n const compressed = alloc.compressed ? \" (compressed)\" : \"\";\n console.log(\n ` ${status} ${alloc.specId} relevance=${alloc.relevance.toFixed(2)} tokens=${alloc.tokens}${compressed}`,\n );\n }\n console.log(`\\n Budget: ${stats.used} / ${stats.budget} tokens`);\n console.log(` Included: ${stats.specsIncluded} / ${stats.specsIncluded + stats.specsExcluded} specs`);\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 } else {\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\", \"an\", \"and\", \"are\", \"as\", \"at\", \"be\", \"but\", \"by\", \"do\", \"for\",\n \"from\", \"had\", \"has\", \"have\", \"he\", \"her\", \"his\", \"how\", \"i\", \"if\",\n \"in\", \"into\", \"is\", \"it\", \"its\", \"just\", \"me\", \"my\", \"no\", \"nor\",\n \"not\", \"of\", \"on\", \"or\", \"our\", \"out\", \"own\", \"say\", \"she\", \"so\",\n \"some\", \"such\", \"than\", \"that\", \"the\", \"their\", \"them\", \"then\",\n \"there\", \"these\", \"they\", \"this\", \"to\", \"too\", \"up\", \"us\", \"very\",\n \"was\", \"we\", \"were\", \"what\", \"when\", \"where\", \"which\", \"while\",\n \"who\", \"whom\", \"why\", \"will\", \"with\", \"would\", \"you\", \"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 (\n type === \"adr\" &&\n status === \"superseded\" &&\n options.collapseResolvedAdrs\n ) {\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 =\n options.stableDays > 0 && isOlderThanDays(updatedDate, options.stableDays);\n\n // 3. Process sections\n const boilerplateSet = new Set(\n options.boilerplateSections.map((s) => s.toLowerCase()),\n );\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(\n specs: CompressedSpec[],\n stats: PackStats,\n): 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\n ? ' compressed=\"true\"'\n : \"\";\n lines.push(\n ` <section name=\"${escapeXml(section.heading)}\"${compressedAttr}>`,\n );\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(\n specs: CompressedSpec[],\n stats: PackStats,\n): 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(\n specs: CompressedSpec[],\n stats: PackStats,\n): 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 { PackOptions, PackResult, CompressionOptions } 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. Build spec map for resolver\n const specMap = new Map<string, ParsedSpec>();\n for (const spec of specs) {\n specMap.set(spec.frontmatter.id, spec);\n }\n\n // 3. Stage 1 - Resolve\n const scores = options.specs\n ? scoreSpecsByIds(specMap, options.specs, resolvedGraph)\n : scoreSpecs(specMap, options.task, resolvedGraph);\n\n // 4. Stage 2 - Allocate\n const { specs: compressedSpecs, stats } = allocate(specs, scores, {\n budget,\n full,\n compression,\n });\n\n // 5. Dry run: return stats without output\n if (options.dryRun) {\n return { output: \"\", stats };\n }\n\n // 6. Stage 3 - Format\n let output: string;\n switch (format) {\n case \"markdown\":\n output = formatMarkdown(compressedSpecs, stats);\n break;\n case \"json\":\n output = formatJson(compressedSpecs, stats);\n break;\n default:\n output = formatXml(compressedSpecs, stats);\n break;\n }\n\n return { output, stats };\n}\n"],"mappings":";AAAA,SAAS,qBAAqB;AAC9B,SAAS,OAAO,iBAAiB;AACjC,SAAS,YAAY;;;ACAd,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,mB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AAgB,MAAM;AAC1C,cAAQ,OAAO;AAAA,QACb,UAAU,MAAM,aAAa,IAAI,KAAK,iBAAiB,MAAM,IAAI,MAAM,MAAM,MAAM,kBAAkB,MAAM,kBAAkB;AAAA;AAAA,MAC/H;AAAA,IACF,SAAS,KAAK;AACZ,cAAQ,MAAM;AAAA,WAAe,IAAc,OAAO;AAAA,CAAI;AACtD,cAAQ,KAAK,CAAC;AAAA,IAChB;AAAA,EACF;AACF,CAAC;","names":["defineCommand","join","join","readFile","parseYaml","readFile","parseYaml","join","defineCommand","defineCommand","results","formatJson","formatJson","writeFile","defineCommand"]}
|
|
@@ -5,7 +5,7 @@ import {
|
|
|
5
5
|
parseSpec,
|
|
6
6
|
resolveGlob,
|
|
7
7
|
sharedArgs
|
|
8
|
-
} from "./chunk-
|
|
8
|
+
} from "./chunk-NTNH2EPU.js";
|
|
9
9
|
import {
|
|
10
10
|
REQUIRED_SECTIONS
|
|
11
11
|
} from "./chunk-CV2CHFFG.js";
|
|
@@ -330,4 +330,4 @@ export {
|
|
|
330
330
|
lint_default as default,
|
|
331
331
|
runLint
|
|
332
332
|
};
|
|
333
|
-
//# sourceMappingURL=lint-
|
|
333
|
+
//# sourceMappingURL=lint-3WMYPOU4.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/commands/lint.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/index.ts","../../lint/src/presets.ts","../../lint/src/custom-rule-loader.ts","../src/formatters/pretty.ts","../src/formatters/json.ts","../src/formatters/github.ts"],"sourcesContent":["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 as any) ?? \"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 any,\n });\n\n const formatter =\n args.format === \"json\" ? formatJson : args.format === \"github\" ? formatGithub : 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 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 { 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 type { LintRule } from \"../types.js\";\n\nexport const structureRules: LintRule[] = [\n validFrontmatterRule,\n requiredSectionsRule,\n validReferencesRule,\n noCircularDepsRule,\n];\n\nexport const contentRules: LintRule[] = [\n storyCoverageRule,\n stalenessCheckRule,\n noVagueLanguageRule,\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};\n","import type { LintRule } from \"./types.js\";\nimport { structureRules, allBuiltinRules } from \"./rules/index.js\";\n\nexport function getPreset(name: \"minimal\" | \"recommended\" | \"strict\"): 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 }\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","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"],"mappings":";;;;;;;;;;;;;AAAA,SAAS,qBAAqB;;;ACcxB,SAAU,iBAAiB,SAA0B;AACzD,SAAO;IACL,KAAK,OAAmB;AACtB,YAAM,cAA4B,CAAA;AAClC,iBAAW,QAAQ,OAAO;AACxB,mBAAW,QAAQ,QAAQ,OAAO;AAChC,gBAAM,UAAU,KAAK,IAAI;YACvB;YACA,UAAU;YACV,QAAQ,QAAQ;YAChB,OAAO,QAAQ;WAChB;AACD,sBAAY,KAAK,GAAG,OAAO;QAC7B;MACF;AACA,aAAO;QACL;QACA,WAAW,YAAY,KAAK,CAAC,MAAM,EAAE,aAAa,OAAO;QACzD,aAAa,YAAY,KAAK,CAAC,MAAM,EAAE,aAAa,MAAM;;IAE9D;;AAEJ;;;AClCO,IAAM,uBAAiC;EAC5C,IAAI;EACJ,aAAa;EACb,UAAU;EACV,IAAI,SAAO;AACT,QAAI,QAAQ,KAAK;AAAO,aAAO,CAAA;AAC/B,UAAM,SAAS,QAAQ,KAAK,oBAAoB,CAAA;AAChD,WAAO,OAAO,IAAI,CAAC,SAAS;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