specdx 0.1.0-alpha.4 → 0.2.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../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 { 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, \"&amp;\")\n .replace(/</g, \"&lt;\")\n .replace(/>/g, \"&gt;\")\n .replace(/\"/g, \"&quot;\");\n}\n\n/**\n * Format compressed specs as XML.\n *\n * @param specs - Compressed specs to render.\n * @param stats - Pack statistics with allocation details.\n * @returns An XML string representing the packed context.\n */\nexport function formatXml(\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;\n default:\n output = formatXml(compressedSpecs, stats);\n break;\n }\n\n return { output, stats };\n}\n"],"mappings":";;;;;;;;;;;;AAAA,SAAS,qBAAqB;;;ACM9B,IAAM,YAAY,oBAAI,IAAI;EACxB;EAAK;EAAM;EAAO;EAAO;EAAM;EAAM;EAAM;EAAO;EAAM;EAAM;EAC9D;EAAQ;EAAO;EAAO;EAAQ;EAAM;EAAO;EAAO;EAAO;EAAK;EAC9D;EAAM;EAAQ;EAAM;EAAM;EAAO;EAAQ;EAAM;EAAM;EAAM;EAC3D;EAAO;EAAM;EAAM;EAAM;EAAO;EAAO;EAAO;EAAO;E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O,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":["results"]}
@@ -0,0 +1,327 @@
1
+ ---
2
+ name: sdx:author-spec
3
+ description: Guided, interactive spec authoring with iterative linting
4
+ ---
5
+
6
+ # sdx:author-spec
7
+
8
+ You are helping the user author a new SDX spec. SDX specs are structured markdown documents with YAML frontmatter that capture project decisions, architecture, processes, and conventions.
9
+
10
+ This is an **interactive, guided process**. Walk through sections one at a time, validate iteratively, and produce a clean, lintable spec at the end.
11
+
12
+ ## Step 1: Determine the spec type
13
+
14
+ Ask the user what kind of spec they want to create. The supported types are:
15
+
16
+ | Type | Purpose | Common use |
17
+ |------|---------|------------|
18
+ | `rfc` | Request for Comments — proposes a change or new approach | Architecture proposals, feature designs, process changes |
19
+ | `adr` | Architecture Decision Record — captures a specific decision | Technology choices, pattern selections, trade-off resolutions |
20
+ | `runbook` | Operational procedure — step-by-step instructions | Deployment, incident response, on-call procedures |
21
+ | `design` | Design document — detailed technical design | System design, API design, data model design |
22
+ | `standard` | Standard — defines conventions and rules | Coding standards, naming conventions, API guidelines |
23
+ | `custom` | Custom type — any other structured document | Meeting notes, retrospectives, onboarding guides |
24
+
25
+ If the user isn't sure, help them choose:
26
+ - "I need to propose something" → `rfc`
27
+ - "I made a decision and want to record it" → `adr`
28
+ - "I need step-by-step instructions" → `runbook`
29
+ - "I need to detail how something works" → `design`
30
+ - "I need to define rules/conventions" → `standard`
31
+
32
+ ## Step 2: Collect metadata
33
+
34
+ Each spec needs YAML frontmatter. Collect the following from the user:
35
+
36
+ ### Required fields (all types)
37
+ - **id**: A unique identifier. Convention: `<type>-<NNN>` (e.g., `rfc-004`, `adr-015`). Check existing specs to find the next available number.
38
+ - **title**: A clear, concise title. Should be specific enough to understand the decision or topic without reading the body.
39
+ - **status**: Starting status. Usually `draft` for new specs.
40
+
41
+ ### Required date fields
42
+ - **createdDate**: Today's date in `YYYY-MM-DD` format.
43
+ - **updatedDate**: Same as createdDate for new specs.
44
+
45
+ ### Optional but recommended fields
46
+ - **author**: The person or team authoring the spec.
47
+ - **reviewers**: List of people who should review it.
48
+ - **dependencies**: List of spec IDs this spec relates to or depends on.
49
+ - **tags**: List of keywords for discoverability.
50
+ - **supersedes**: (For ADRs) ID of the spec this one replaces.
51
+
52
+ ### Tips for good metadata
53
+ - Use feature IDs from your issue tracker in tags (e.g., `PROJ-1234`)
54
+ - Quote dates in YAML: `"2026-03-18"` to avoid parser issues
55
+ - Keep titles under 80 characters
56
+ - Use lowercase kebab-case for IDs: `adr-015` not `ADR_015`
57
+
58
+ ## Step 3: Write sections one at a time
59
+
60
+ Each spec type has required and recommended sections. Walk through them **one at a time**, asking the user for input, then assembling the section.
61
+
62
+ ### RFC sections
63
+
64
+ 1. **Summary** (required) — One paragraph overview of the proposal. Write this LAST after all other sections are done, but it appears first in the document.
65
+ 2. **Context** (required) — What is the current situation? What problem or opportunity does this address?
66
+ 3. **Proposal** (required) — What specifically is being proposed? Be concrete and detailed.
67
+ 4. **Alternatives Considered** (recommended) — What other approaches were evaluated? Why were they rejected?
68
+ 5. **Migration Strategy** (recommended) — How do we get from the current state to the proposed state?
69
+ 6. **Risks** (recommended) — What could go wrong? What are the trade-offs?
70
+ 7. **Open Questions** (optional) — Unresolved points that need discussion during review.
71
+
72
+ ### ADR sections
73
+
74
+ 1. **Context** (required) — What forces are at play? What is the situation that led to this decision?
75
+ 2. **Decision** (required) — What was decided? State it clearly and unambiguously.
76
+ 3. **Consequences** (required) — What are the results of this decision? Include both positive and negative consequences.
77
+ 4. **Alternatives Considered** (recommended) — What other options were evaluated?
78
+
79
+ ### Runbook sections
80
+
81
+ 1. **Overview** (required) — What does this runbook cover? When should it be used?
82
+ 2. **Prerequisites** (required) — What access, tools, or knowledge is needed before starting?
83
+ 3. **Steps** (required) — The numbered, step-by-step procedure. Each step should be atomic and verifiable.
84
+ 4. **Rollback** (recommended) — How to undo or recover if something goes wrong.
85
+ 5. **Troubleshooting** (recommended) — Common issues and their resolutions.
86
+
87
+ ### Design sections
88
+
89
+ 1. **Overview** (required) — High-level summary of the design.
90
+ 2. **Goals and Non-Goals** (required) — What this design does and does not aim to achieve.
91
+ 3. **Architecture** (required) — The technical design. Include diagrams if helpful (Mermaid syntax works well).
92
+ 4. **Data Model** (recommended) — Schema, types, data flow.
93
+ 5. **API Design** (recommended) — Endpoints, interfaces, contracts.
94
+ 6. **Security Considerations** (recommended) — Authentication, authorization, data protection.
95
+ 7. **Performance Considerations** (recommended) — Scalability, latency, resource usage.
96
+
97
+ ### Standard sections
98
+
99
+ 1. **Purpose** (required) — Why does this standard exist? What problem does it solve?
100
+ 2. **Scope** (required) — What does this standard apply to? What is excluded?
101
+ 3. **Rules** (required) — The actual rules or conventions. Be specific and enforceable.
102
+ 4. **Examples** (recommended) — Good and bad examples demonstrating the rules.
103
+ 5. **Exceptions** (recommended) — When is it acceptable to deviate from this standard?
104
+
105
+ ### For each section
106
+
107
+ When writing each section:
108
+ 1. Ask the user for their thoughts on the topic
109
+ 2. Draft the section content based on their input
110
+ 3. Show them the draft and ask for feedback
111
+ 4. Refine until they're satisfied
112
+ 5. Move to the next section
113
+
114
+ ## Step 4: Assemble and lint iteratively
115
+
116
+ After each section is drafted, assemble the full document so far and run:
117
+
118
+ ```bash
119
+ sdx lint --path <file>
120
+ ```
121
+
122
+ This catches issues early:
123
+ - Missing required frontmatter fields
124
+ - Missing required sections for the spec type
125
+ - Vague language (weasel words like "should probably", "might", "fairly")
126
+ - Missing status field
127
+ - Structural issues
128
+
129
+ ### Handling lint results
130
+
131
+ - **Errors**: Must be fixed. Work with the user to resolve them before continuing.
132
+ - **Warnings**: Should be addressed. Discuss with the user whether to fix or accept.
133
+ - **Info**: Optional improvements. Mention them but don't block on them.
134
+
135
+ ### Common lint fixes
136
+
137
+ | Issue | Fix |
138
+ |-------|-----|
139
+ | "Vague language detected" | Replace weasel words with concrete language. "We should probably use caching" → "We will use Redis for caching" |
140
+ | "Missing required section" | Add the section, even if minimal. Can flesh out later. |
141
+ | "Status field missing" | Add `status: draft` to frontmatter |
142
+ | "Title too long" | Shorten to under 80 characters. Move detail to Summary section. |
143
+ | "Missing dependencies" | If referencing other specs, add their IDs to `dependencies` list |
144
+
145
+ ## Step 5: Handle references and dependencies
146
+
147
+ If the spec references other specs:
148
+
149
+ 1. List them in the `dependencies` frontmatter field
150
+ 2. Use the spec ID when referencing inline: "As decided in ADR-007, we use cursor-based pagination."
151
+ 3. Check that referenced specs exist: `sdx validate` will catch broken references
152
+
153
+ If the spec supersedes another:
154
+ 1. Add `supersedes: <old-spec-id>` to frontmatter
155
+ 2. Mention the superseded spec in the Context section
156
+ 3. After publishing, update the old spec's status to `superseded`
157
+
158
+ ## Step 6: Final validation
159
+
160
+ When all sections are complete, run the strict lint preset:
161
+
162
+ ```bash
163
+ sdx lint --path <file> --preset strict
164
+ ```
165
+
166
+ The strict preset enables all rules including:
167
+ - Content quality checks (no vague language, no TODOs in accepted specs)
168
+ - Reference validation (all dependency IDs exist)
169
+ - Section completeness (all recommended sections present, not just required)
170
+ - Frontmatter completeness (all recommended fields present)
171
+
172
+ ### Final checklist
173
+
174
+ Before declaring the spec done, verify:
175
+
176
+ - [ ] All required sections are present and substantive
177
+ - [ ] Frontmatter has all required fields with valid values
178
+ - [ ] Status is set correctly (usually `draft` for new specs)
179
+ - [ ] Dates are in `YYYY-MM-DD` format and quoted in YAML
180
+ - [ ] Title is clear, specific, and under 80 characters
181
+ - [ ] No vague or hedging language remains
182
+ - [ ] Dependencies list is complete and all referenced specs exist
183
+ - [ ] The Summary/Overview section accurately reflects the full content
184
+ - [ ] The spec is saved in the correct directory (usually `specs/<type>/`)
185
+
186
+ ## Step 7: Save the spec
187
+
188
+ Save the completed spec to the project's specs directory:
189
+
190
+ ```bash
191
+ # Check the configured specs directory
192
+ cat sdx.config.ts # or sdx.config.yaml
193
+ ```
194
+
195
+ The default location is `specs/` at the project root, organized by type:
196
+ ```
197
+ specs/
198
+ rfc/
199
+ rfc-001-api-versioning.md
200
+ rfc-002-event-driven-architecture.md
201
+ adr/
202
+ adr-001-use-typescript.md
203
+ adr-002-use-postgresql.md
204
+ runbook/
205
+ runbook-001-deployment.md
206
+ ```
207
+
208
+ Name the file using the pattern: `<id>-<kebab-case-title>.md`
209
+
210
+ ## Writing tips
211
+
212
+ ### Avoid vague language
213
+ The SDX linter will flag these. Replace them with concrete statements:
214
+
215
+ | Avoid | Prefer |
216
+ |-------|--------|
217
+ | "We should probably..." | "We will..." |
218
+ | "This might help..." | "This reduces latency by ~200ms" |
219
+ | "Fairly straightforward" | "Requires updating 3 files in the auth module" |
220
+ | "In the near future" | "By 2026-Q2" or "Before the v2.0 release" |
221
+ | "Various improvements" | "Adds caching, batching, and connection pooling" |
222
+ | "Relatively simple" | "Estimated 2-day implementation" |
223
+ | "It seems like" | "Based on load testing results," |
224
+ | "Potentially" | "If traffic exceeds 10k RPM," |
225
+
226
+ ### Use feature IDs
227
+ If your project uses an issue tracker, link specs to issues:
228
+ ```yaml
229
+ tags:
230
+ - PROJ-1234
231
+ - authentication
232
+ - security
233
+ ```
234
+
235
+ ### Quote dates in YAML
236
+ YAML can interpret unquoted dates in unexpected ways:
237
+ ```yaml
238
+ # Bad — YAML may parse as a Date object
239
+ createdDate: 2026-03-18
240
+
241
+ # Good — always a string
242
+ createdDate: "2026-03-18"
243
+ ```
244
+
245
+ ### Be specific in Consequences (ADRs)
246
+ Both positive and negative consequences should be listed:
247
+ ```markdown
248
+ ## Consequences
249
+
250
+ ### Positive
251
+ - Type safety catches bugs at compile time rather than runtime
252
+ - IDE support improves developer experience (autocomplete, refactoring)
253
+
254
+ ### Negative
255
+ - Build step adds ~15 seconds to CI pipeline
256
+ - Team needs TypeScript training (estimated 1-week ramp-up)
257
+ - Some npm packages lack type definitions
258
+ ```
259
+
260
+ ### Make runbook steps atomic
261
+ Each step should be independently verifiable:
262
+ ```markdown
263
+ ## Steps
264
+
265
+ 1. SSH into the production server:
266
+ ```bash
267
+ ssh deploy@prod.example.com
268
+ ```
269
+ **Verify:** You see the `deploy@prod` prompt.
270
+
271
+ 2. Pull the latest release:
272
+ ```bash
273
+ cd /opt/app && git pull origin main
274
+ ```
275
+ **Verify:** Git reports the new commit hash.
276
+ ```
277
+
278
+ ## Troubleshooting
279
+
280
+ ### `sdx lint` not found
281
+ - Install: `npm install -g specdx` or use `npx sdx lint`
282
+ - In a monorepo, check if it's a devDependency
283
+
284
+ ### Lint reports "unknown spec type"
285
+ - Ensure the `type` in frontmatter matches one of: `rfc`, `adr`, `runbook`, `design`, `standard`, `custom`
286
+ - Check for typos (e.g., `RFC` instead of `rfc`)
287
+
288
+ ### Lint passes but spec feels incomplete
289
+ - Try the strict preset: `sdx lint --path <file> --preset strict`
290
+ - Review the recommended (not just required) sections for the spec type
291
+ - Ask a colleague to review — specs benefit from a second perspective
292
+
293
+ ### User isn't sure what to write for a section
294
+ - Offer prompting questions:
295
+ - **Context**: "What problem are you trying to solve? What's the current situation?"
296
+ - **Decision**: "If you had to state the decision in one sentence, what would it be?"
297
+ - **Consequences**: "What gets better? What gets worse or harder?"
298
+ - **Alternatives**: "What else did you consider? Why didn't you go with those?"
299
+
300
+ ## Example: Creating an ADR
301
+
302
+ User: "I want to record our decision to use SQLite for the local cache"
303
+
304
+ 1. **Type**: ADR (recording a decision)
305
+ 2. **Metadata**:
306
+ ```yaml
307
+ ---
308
+ id: adr-015
309
+ type: adr
310
+ title: Use SQLite for local cache storage
311
+ status: draft
312
+ createdDate: "2026-03-18"
313
+ updatedDate: "2026-03-18"
314
+ author: Team Backend
315
+ tags:
316
+ - caching
317
+ - storage
318
+ - PROJ-892
319
+ ---
320
+ ```
321
+ 3. **Context section**: Discuss why a local cache is needed, what options exist
322
+ 4. **Decision section**: "We will use SQLite via better-sqlite3 for local cache storage"
323
+ 5. **Consequences section**: List pros (embedded, zero-config, fast reads) and cons (single-writer, no replication)
324
+ 6. **Alternatives section**: Redis (too heavy for local), plain files (no querying), LevelDB (less tooling)
325
+ 7. **Lint**: `sdx lint --path specs/adr/adr-015-use-sqlite-for-local-cache.md`
326
+ 8. **Strict lint**: `sdx lint --path specs/adr/adr-015-use-sqlite-for-local-cache.md --preset strict`
327
+ 9. **Save**: `specs/adr/adr-015-use-sqlite-for-local-cache.md`
@@ -0,0 +1,244 @@
1
+ ---
2
+ name: sdx:start-task
3
+ description: Load project spec context for a coding task using sdx pack
4
+ ---
5
+
6
+ # sdx:start-task
7
+
8
+ You are about to begin a coding task within a project that uses **SDX (Spec Developer Experience)** to manage its specifications. SDX specs are structured markdown documents (RFCs, ADRs, runbooks, designs, etc.) that capture project decisions, architecture, and conventions.
9
+
10
+ Your job is to load relevant spec context before starting work, so you have the full picture of what the project expects.
11
+
12
+ ## Step 1: Pack the context
13
+
14
+ Run the following command, replacing `<task-description>` with the user's task description:
15
+
16
+ ```bash
17
+ sdx pack --task "<task-description>" --format xml
18
+ ```
19
+
20
+ This will:
21
+ - Scan the project's `specs/` directory (or configured spec paths)
22
+ - Identify specs relevant to the task description using keyword matching and dependency analysis
23
+ - Compress stale or resolved specs to save context tokens
24
+ - Output a structured XML document with all relevant spec content
25
+
26
+ ### Alternative formats
27
+
28
+ If XML is too verbose for the model's context window, you can try:
29
+
30
+ ```bash
31
+ sdx pack --task "<task-description>" --format markdown
32
+ ```
33
+
34
+ Or for a minimal structured output:
35
+
36
+ ```bash
37
+ sdx pack --task "<task-description>" --format json
38
+ ```
39
+
40
+ ### Limiting token budget
41
+
42
+ If the context is too large, you can set a token budget:
43
+
44
+ ```bash
45
+ sdx pack --task "<task-description>" --format xml --budget 8000
46
+ ```
47
+
48
+ ## Step 2: Read and internalize the packed context
49
+
50
+ After running `sdx pack`, read the output carefully. The packed context includes:
51
+
52
+ ### Spec metadata
53
+ Each spec entry contains:
54
+ - **id**: Unique identifier (e.g., `rfc-001`, `adr-012`)
55
+ - **type**: The spec type (`rfc`, `adr`, `runbook`, `design`, `standard`, `custom`)
56
+ - **title**: Human-readable title
57
+ - **status**: Current lifecycle status (`draft`, `review`, `accepted`, `superseded`, `deprecated`, `withdrawn`)
58
+ - **dependencies**: Other specs this one references or depends on
59
+
60
+ ### Spec sections
61
+ Each spec is broken into its constituent sections (e.g., Context, Decision, Consequences for an ADR). Sections from stale specs may be compressed to save tokens — these will be marked with a compression notice.
62
+
63
+ ### Collapsed specs
64
+ Some specs may be fully collapsed to a one-line summary (e.g., superseded ADRs). This is intentional — they provide awareness without consuming significant context.
65
+
66
+ ## Step 3: Apply the context to your task
67
+
68
+ When working on the task, you MUST:
69
+
70
+ 1. **Reference specs by ID** — When your implementation relates to a spec, mention it explicitly (e.g., "Per ADR-012, we use PostgreSQL for persistence").
71
+
72
+ 2. **Flag drift** — If you notice the codebase diverges from what a spec describes, call it out:
73
+ - "NOTE: The code uses Redis here, but ADR-012 specifies PostgreSQL. This may be intentional drift or the ADR may need updating."
74
+
75
+ 3. **Note gaps** — If the task requires decisions not covered by any spec, say so:
76
+ - "GAP: No spec covers error retry strategy for this service. Consider authoring an ADR."
77
+
78
+ 4. **Respect status** — Treat spec statuses appropriately:
79
+ - `accepted` / `active`: These are current truth. Follow them.
80
+ - `draft` / `review`: These are proposed but not finalized. Follow them tentatively but note they may change.
81
+ - `superseded`: Check what supersedes it. Follow the newer spec.
82
+ - `deprecated` / `withdrawn`: Do not follow these. Note if code still references them.
83
+
84
+ 5. **Follow conventions** — Standards and runbooks often define coding conventions, naming patterns, deployment procedures, etc. Adhere to them.
85
+
86
+ ## Step 4: Verify spec alignment before finishing
87
+
88
+ Before completing the task, do a quick check:
89
+
90
+ - [ ] Does the implementation align with all relevant accepted specs?
91
+ - [ ] Are there any specs in `draft` or `review` that this work might affect?
92
+ - [ ] Did you introduce any patterns not covered by existing specs?
93
+ - [ ] If you found drift or gaps, did you document them in your response?
94
+
95
+ ## Troubleshooting
96
+
97
+ ### `sdx pack` returns no specs
98
+ - Check that the project has an `sdx.config.ts` or `sdx.config.yaml` file
99
+ - Verify specs exist in the configured `specsDir` (default: `specs/`)
100
+ - Try a broader task description — the relevance matcher uses keywords from spec titles and content
101
+
102
+ ### `sdx pack` returns too many specs
103
+ - Use `--budget` to limit token count
104
+ - Make the task description more specific
105
+ - The packer prioritizes by relevance score; lower-scored specs are trimmed first
106
+
107
+ ### Specs seem outdated
108
+ - Check `updatedDate` in spec frontmatter
109
+ - Run `sdx lint` to identify specs with structural or content issues
110
+ - Suggest the user update stale specs
111
+
112
+ ### Command not found
113
+ - Ensure `specdx` is installed: `npm install -g specdx` or `npx specdx pack ...`
114
+ - In a monorepo, it may be a devDependency: `npx sdx pack ...`
115
+
116
+ ## Understanding the output formats
117
+
118
+ ### XML format (recommended for Claude)
119
+
120
+ The XML format wraps specs in tags that are easy for LLMs to parse:
121
+
122
+ ```xml
123
+ <sdx-context task="Add pagination to /api/users" specs="4" tokens="3200">
124
+ <spec id="rfc-003" type="rfc" status="accepted" title="REST API Design Guidelines">
125
+ <section heading="Pagination">
126
+ All list endpoints MUST support cursor-based pagination...
127
+ </section>
128
+ </spec>
129
+ <spec id="adr-002" type="adr" status="superseded" collapsed="true">
130
+ [ADR] Use Express.js — superseded
131
+ </spec>
132
+ </sdx-context>
133
+ ```
134
+
135
+ Key attributes:
136
+ - `specs` — total number of specs included
137
+ - `tokens` — estimated token count of the full output
138
+ - `collapsed="true"` — spec was reduced to a one-liner
139
+
140
+ ### Markdown format
141
+
142
+ The markdown format uses headings and horizontal rules to separate specs:
143
+
144
+ ```markdown
145
+ # SDX Context: Add pagination to /api/users
146
+
147
+ ---
148
+
149
+ ## rfc-003: REST API Design Guidelines
150
+ **Type:** rfc | **Status:** accepted
151
+
152
+ ### Pagination
153
+ All list endpoints MUST support cursor-based pagination...
154
+
155
+ ---
156
+
157
+ ## adr-002: Use Express.js
158
+ > [ADR] Use Express.js — superseded
159
+ ```
160
+
161
+ ### JSON format
162
+
163
+ The JSON format is compact and machine-parseable:
164
+
165
+ ```json
166
+ {
167
+ "task": "Add pagination to /api/users",
168
+ "specs": [
169
+ {
170
+ "id": "rfc-003",
171
+ "type": "rfc",
172
+ "status": "accepted",
173
+ "title": "REST API Design Guidelines",
174
+ "sections": [{ "heading": "Pagination", "content": "..." }]
175
+ }
176
+ ]
177
+ }
178
+ ```
179
+
180
+ ## How relevance scoring works
181
+
182
+ The packer uses multiple signals to rank spec relevance:
183
+
184
+ 1. **Keyword overlap** — Words from the task description are matched against spec titles, tags, and section headings. More matches = higher score.
185
+ 2. **Type affinity** — ADRs and standards are weighted slightly higher because they represent binding decisions and rules.
186
+ 3. **Status weighting** — `accepted` and `active` specs score higher than `draft` or `deprecated` ones.
187
+ 4. **Dependency inclusion** — If a high-relevance spec depends on another spec, the dependency is pulled in automatically (transitive closure).
188
+ 5. **Recency boost** — Recently updated specs get a small relevance boost.
189
+
190
+ Specs below the relevance threshold are excluded entirely unless they are transitive dependencies of included specs.
191
+
192
+ ## Example session
193
+
194
+ User says: "Add pagination to the /api/users endpoint"
195
+
196
+ 1. Run: `sdx pack --task "Add pagination to the /api/users endpoint" --format xml`
197
+ 2. Read the output — you might see:
198
+ - `rfc-003: REST API Design Guidelines` (status: accepted) — defines pagination patterns
199
+ - `adr-007: Use cursor-based pagination` (status: accepted) — specific decision
200
+ - `standard-001: API Response Envelope` (status: active) — response format requirements
201
+ - `adr-002: Use Express.js` (status: superseded) — collapsed, just for awareness
202
+ 3. Implement pagination following the cursor-based approach from ADR-007
203
+ 4. Use the response envelope format from standard-001
204
+ 5. Follow the REST conventions from RFC-003
205
+ 6. Note in your response: "Implemented per ADR-007 (cursor-based pagination) and standard-001 (envelope format)"
206
+
207
+ ## Example: handling drift
208
+
209
+ User says: "Refactor the auth middleware to use JWT"
210
+
211
+ 1. Run: `sdx pack --task "Refactor auth middleware to use JWT" --format xml`
212
+ 2. Output includes:
213
+ - `adr-003: Use session-based authentication` (status: accepted)
214
+ - `standard-002: Security Standards` (status: active)
215
+ 3. The task asks for JWT, but ADR-003 says session-based auth is the accepted approach.
216
+ 4. Respond with: "DRIFT: This task requests JWT-based auth, but ADR-003 (accepted) specifies session-based authentication. Before proceeding, we should either: (a) create a new ADR superseding ADR-003 to adopt JWT, or (b) confirm this is a deliberate exception."
217
+ 5. Do NOT silently ignore the spec. Always surface the conflict.
218
+
219
+ ## Example: noting gaps
220
+
221
+ User says: "Add rate limiting to the API gateway"
222
+
223
+ 1. Run: `sdx pack --task "Add rate limiting to the API gateway" --format xml`
224
+ 2. Output includes general API specs but nothing about rate limiting specifically.
225
+ 3. Respond with: "GAP: No spec covers rate limiting strategy (algorithm, limits, response codes, retry headers). Recommend authoring an ADR before implementation to align on approach. In the meantime, proceeding with token bucket algorithm at 100 req/min as a reasonable default."
226
+
227
+ ## Notes
228
+
229
+ - The `sdx pack` command is read-only — it never modifies specs or project files
230
+ - Token counts in the output are estimates based on the `cl100k_base` tokenizer
231
+ - Compressed sections can be expanded by re-running without `--budget` or with a larger budget
232
+ - If a spec has `dependencies`, the packer automatically includes those transitive dependencies
233
+ - The packer respects `.sdxignore` patterns if present in the project root
234
+ - Multiple `--task` flags are not supported; combine related work into one description
235
+ - The `--format` flag defaults to `xml` if omitted
236
+
237
+ ## When NOT to use this skill
238
+
239
+ - For simple, self-contained tasks that don't touch architecture or conventions (e.g., fixing a typo)
240
+ - When the user explicitly says to skip spec context
241
+ - When running in a project that doesn't use SDX (no `sdx.config.*` file)
242
+ - For tasks that only modify tests without changing production behavior
243
+
244
+ In those cases, proceed directly with the task without running `sdx pack`.