specdx 0.1.0-alpha.3 → 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,666 @@
1
+ import {
2
+ buildGraph,
3
+ countTokens,
4
+ createLogger,
5
+ loadConfig,
6
+ parseSpec,
7
+ resolveGlob,
8
+ sharedArgs
9
+ } from "./chunk-PL7UZ73U.js";
10
+ import "./chunk-CV2CHFFG.js";
11
+
12
+ // src/commands/pack.ts
13
+ import { defineCommand } from "citty";
14
+
15
+ // ../pack/dist/resolver.js
16
+ var STOPWORDS = /* @__PURE__ */ new Set([
17
+ "a",
18
+ "an",
19
+ "and",
20
+ "are",
21
+ "as",
22
+ "at",
23
+ "be",
24
+ "but",
25
+ "by",
26
+ "do",
27
+ "for",
28
+ "from",
29
+ "had",
30
+ "has",
31
+ "have",
32
+ "he",
33
+ "her",
34
+ "his",
35
+ "how",
36
+ "i",
37
+ "if",
38
+ "in",
39
+ "into",
40
+ "is",
41
+ "it",
42
+ "its",
43
+ "just",
44
+ "me",
45
+ "my",
46
+ "no",
47
+ "nor",
48
+ "not",
49
+ "of",
50
+ "on",
51
+ "or",
52
+ "our",
53
+ "out",
54
+ "own",
55
+ "say",
56
+ "she",
57
+ "so",
58
+ "some",
59
+ "such",
60
+ "than",
61
+ "that",
62
+ "the",
63
+ "their",
64
+ "them",
65
+ "then",
66
+ "there",
67
+ "these",
68
+ "they",
69
+ "this",
70
+ "to",
71
+ "too",
72
+ "up",
73
+ "us",
74
+ "very",
75
+ "was",
76
+ "we",
77
+ "were",
78
+ "what",
79
+ "when",
80
+ "where",
81
+ "which",
82
+ "while",
83
+ "who",
84
+ "whom",
85
+ "why",
86
+ "will",
87
+ "with",
88
+ "would",
89
+ "you",
90
+ "your"
91
+ ]);
92
+ function tokenize(task) {
93
+ return task.split(/[\s\-_/.,;:!?()[\]{}'"]+/).map((t) => t.toLowerCase()).filter((t) => t.length > 1 && !STOPWORDS.has(t));
94
+ }
95
+ var WEIGHT_TAGS = 3;
96
+ var WEIGHT_TITLE = 3;
97
+ var WEIGHT_SECTIONS = 2;
98
+ var WEIGHT_BODY = 1;
99
+ var GRAPH_BOOST_FACTOR = 0.5;
100
+ var SCORE_THRESHOLD = 0.1;
101
+ function scoreSpecs(specs, task, graph) {
102
+ const keywords = task ? tokenize(task) : [];
103
+ if (keywords.length === 0) {
104
+ const results2 = [];
105
+ for (const specId of specs.keys()) {
106
+ results2.push({
107
+ specId,
108
+ score: 1,
109
+ rawScore: 1,
110
+ matchedKeywords: [],
111
+ graphBoosted: false
112
+ });
113
+ }
114
+ return results2;
115
+ }
116
+ const rawScores = /* @__PURE__ */ new Map();
117
+ const matchedMap = /* @__PURE__ */ new Map();
118
+ for (const [specId, spec] of specs) {
119
+ let weightedHits = 0;
120
+ const matched = /* @__PURE__ */ new Set();
121
+ for (const keyword of keywords) {
122
+ let hit = false;
123
+ const tags = spec.frontmatter.tags ?? [];
124
+ for (const tag of tags) {
125
+ if (typeof tag === "string" && tag.toLowerCase().includes(keyword)) {
126
+ weightedHits += WEIGHT_TAGS;
127
+ hit = true;
128
+ break;
129
+ }
130
+ }
131
+ const title = spec.frontmatter.title;
132
+ if (typeof title === "string" && title.toLowerCase().includes(keyword)) {
133
+ weightedHits += WEIGHT_TITLE;
134
+ hit = true;
135
+ }
136
+ for (const heading of spec.sections) {
137
+ if (heading.toLowerCase().includes(keyword)) {
138
+ weightedHits += WEIGHT_SECTIONS;
139
+ hit = true;
140
+ break;
141
+ }
142
+ }
143
+ if (spec.content.toLowerCase().includes(keyword)) {
144
+ weightedHits += WEIGHT_BODY;
145
+ hit = true;
146
+ }
147
+ if (hit) {
148
+ matched.add(keyword);
149
+ }
150
+ }
151
+ const raw = weightedHits / keywords.length;
152
+ rawScores.set(specId, raw);
153
+ matchedMap.set(specId, matched);
154
+ }
155
+ const boostScores = /* @__PURE__ */ new Map();
156
+ const boostedSet = /* @__PURE__ */ new Set();
157
+ for (const [specId, rawScore] of rawScores) {
158
+ if (rawScore <= 0)
159
+ continue;
160
+ const boostAmount = rawScore * GRAPH_BOOST_FACTOR;
161
+ for (const edge of graph.edges) {
162
+ let neighborId;
163
+ if (edge.from === specId) {
164
+ neighborId = edge.to;
165
+ } else if (edge.to === specId) {
166
+ neighborId = edge.from;
167
+ }
168
+ if (neighborId !== void 0 && specs.has(neighborId)) {
169
+ const existing = boostScores.get(neighborId) ?? 0;
170
+ boostScores.set(neighborId, Math.max(existing, boostAmount));
171
+ }
172
+ }
173
+ }
174
+ const finalRawScores = /* @__PURE__ */ new Map();
175
+ for (const specId of specs.keys()) {
176
+ const raw = rawScores.get(specId) ?? 0;
177
+ const boost = boostScores.get(specId) ?? 0;
178
+ const combined = raw + boost;
179
+ finalRawScores.set(specId, combined);
180
+ if (boost > 0 && raw === 0) {
181
+ boostedSet.add(specId);
182
+ }
183
+ }
184
+ let maxScore = 0;
185
+ for (const score of finalRawScores.values()) {
186
+ if (score > maxScore)
187
+ maxScore = score;
188
+ }
189
+ const results = [];
190
+ for (const [specId] of specs) {
191
+ const combined = finalRawScores.get(specId) ?? 0;
192
+ const normalized = maxScore > 0 ? combined / maxScore : 0;
193
+ if (normalized < SCORE_THRESHOLD)
194
+ continue;
195
+ results.push({
196
+ specId,
197
+ score: normalized,
198
+ rawScore: rawScores.get(specId) ?? 0,
199
+ matchedKeywords: [...matchedMap.get(specId) ?? []],
200
+ graphBoosted: boostedSet.has(specId)
201
+ });
202
+ }
203
+ results.sort((a, b) => b.score - a.score);
204
+ return results;
205
+ }
206
+ function scoreSpecsByIds(specs, specIds, graph) {
207
+ for (const id of specIds) {
208
+ if (!specs.has(id)) {
209
+ const available = [...specs.keys()].join(", ");
210
+ throw new Error(`Unknown spec: "${id}". Available specs: ${available}`);
211
+ }
212
+ }
213
+ const scoreMap = /* @__PURE__ */ new Map();
214
+ for (const id of specIds) {
215
+ scoreMap.set(id, 1);
216
+ }
217
+ for (const id of specIds) {
218
+ const upstream = graph.getUpstream(id);
219
+ for (const depId of upstream) {
220
+ if (!scoreMap.has(depId) && specs.has(depId)) {
221
+ scoreMap.set(depId, 0.5);
222
+ }
223
+ }
224
+ }
225
+ const results = [];
226
+ for (const [specId, score] of scoreMap) {
227
+ results.push({
228
+ specId,
229
+ score,
230
+ rawScore: score,
231
+ matchedKeywords: [],
232
+ graphBoosted: score < 1
233
+ });
234
+ }
235
+ results.sort((a, b) => b.score - a.score);
236
+ return results;
237
+ }
238
+
239
+ // ../pack/dist/compressor.js
240
+ function isOlderThanDays(dateStr, days) {
241
+ if (!dateStr)
242
+ return false;
243
+ const ms = Date.parse(dateStr);
244
+ if (Number.isNaN(ms))
245
+ return false;
246
+ const diffMs = Date.now() - ms;
247
+ return diffMs > days * 24 * 60 * 60 * 1e3;
248
+ }
249
+ function compressSpec(specId, type, title, status, updatedDate, parsedSections, options) {
250
+ if (type === "adr" && status === "superseded" && options.collapseResolvedAdrs) {
251
+ return {
252
+ specId,
253
+ type,
254
+ title,
255
+ sections: [],
256
+ collapsed: true,
257
+ collapsedSummary: `[ADR] ${title} \u2014 superseded`
258
+ };
259
+ }
260
+ const stale = options.stableDays > 0 && isOlderThanDays(updatedDate, options.stableDays);
261
+ const boilerplateSet = new Set(options.boilerplateSections.map((s) => s.toLowerCase()));
262
+ const sections = [];
263
+ for (const section of parsedSections) {
264
+ if (options.stripBoilerplate && section.heading && boilerplateSet.has(section.heading.toLowerCase())) {
265
+ continue;
266
+ }
267
+ if (stale && section.heading) {
268
+ const stub = `[Unchanged since ${updatedDate} \u2014 ${section.tokens} tokens omitted]`;
269
+ sections.push({
270
+ heading: section.heading,
271
+ content: stub,
272
+ tokens: countTokens(stub),
273
+ compressed: true,
274
+ originalTokens: section.tokens
275
+ });
276
+ continue;
277
+ }
278
+ sections.push({
279
+ heading: section.heading,
280
+ content: section.content,
281
+ tokens: section.tokens,
282
+ compressed: false,
283
+ originalTokens: section.tokens
284
+ });
285
+ }
286
+ return {
287
+ specId,
288
+ type,
289
+ title,
290
+ sections,
291
+ collapsed: false
292
+ };
293
+ }
294
+
295
+ // ../pack/dist/allocator.js
296
+ function allocate(specs, scores, options) {
297
+ const specMap = /* @__PURE__ */ new Map();
298
+ for (const spec of specs) {
299
+ specMap.set(spec.frontmatter.id, spec);
300
+ }
301
+ const items = [];
302
+ for (const score of scores) {
303
+ const spec = specMap.get(score.specId);
304
+ if (!spec)
305
+ continue;
306
+ let compressed;
307
+ if (options.full) {
308
+ compressed = {
309
+ specId: score.specId,
310
+ type: String(spec.frontmatter.type),
311
+ title: String(spec.frontmatter.title),
312
+ sections: spec.parsedSections.map((s) => ({
313
+ heading: s.heading,
314
+ content: s.content,
315
+ tokens: s.tokens,
316
+ compressed: false,
317
+ originalTokens: s.tokens
318
+ })),
319
+ collapsed: false
320
+ };
321
+ } else {
322
+ compressed = compressSpec(score.specId, String(spec.frontmatter.type), String(spec.frontmatter.title), spec.frontmatter.status, spec.frontmatter.updated, spec.parsedSections, options.compression);
323
+ }
324
+ let tokens;
325
+ if (compressed.collapsed) {
326
+ tokens = countTokens(compressed.collapsedSummary ?? "");
327
+ } else {
328
+ tokens = 0;
329
+ for (const section of compressed.sections) {
330
+ tokens += section.tokens;
331
+ }
332
+ }
333
+ items.push({ compressed, relevance: score.score, tokens });
334
+ }
335
+ items.sort((a, b) => b.relevance - a.relevance);
336
+ const totalTokens = items.reduce((sum, item) => sum + item.tokens, 0);
337
+ const withinBudget = totalTokens <= options.budget;
338
+ const included = [];
339
+ const excluded = [];
340
+ let usedTokens = 0;
341
+ if (withinBudget) {
342
+ for (const item of items) {
343
+ included.push(item);
344
+ usedTokens += item.tokens;
345
+ }
346
+ } else {
347
+ for (const item of items) {
348
+ if (usedTokens + item.tokens <= options.budget) {
349
+ included.push(item);
350
+ usedTokens += item.tokens;
351
+ } else {
352
+ excluded.push(item);
353
+ }
354
+ }
355
+ }
356
+ let sectionsCompressed = 0;
357
+ for (const item of included) {
358
+ for (const section of item.compressed.sections) {
359
+ if (section.compressed) {
360
+ sectionsCompressed++;
361
+ }
362
+ }
363
+ }
364
+ const allocations = [];
365
+ for (const item of included) {
366
+ allocations.push({
367
+ specId: item.compressed.specId,
368
+ type: item.compressed.type,
369
+ relevance: item.relevance,
370
+ tokens: item.tokens,
371
+ compressed: item.compressed.collapsed || item.compressed.sections.some((s) => s.compressed),
372
+ included: true
373
+ });
374
+ }
375
+ for (const item of excluded) {
376
+ allocations.push({
377
+ specId: item.compressed.specId,
378
+ type: item.compressed.type,
379
+ relevance: item.relevance,
380
+ tokens: item.tokens,
381
+ compressed: item.compressed.collapsed || item.compressed.sections.some((s) => s.compressed),
382
+ included: false
383
+ });
384
+ }
385
+ const stats = {
386
+ budget: options.budget,
387
+ used: usedTokens,
388
+ specsIncluded: included.length,
389
+ specsExcluded: excluded.length,
390
+ sectionsCompressed,
391
+ allocations
392
+ };
393
+ return {
394
+ specs: included.map((item) => item.compressed),
395
+ stats
396
+ };
397
+ }
398
+
399
+ // ../pack/dist/formatters/xml.js
400
+ function escapeXml(text) {
401
+ return text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
402
+ }
403
+ function formatXml(specs, stats) {
404
+ const lines = [];
405
+ lines.push(`<context budget="${stats.budget}" used="${stats.used}" specs="${stats.specsIncluded}" compressed="${stats.sectionsCompressed}">`);
406
+ for (const spec of specs) {
407
+ const alloc = stats.allocations.find((a) => a.specId === spec.specId);
408
+ const relevance = alloc?.relevance ?? 0;
409
+ const tokens = alloc?.tokens ?? 0;
410
+ if (spec.collapsed) {
411
+ lines.push(` <spec id="${escapeXml(spec.specId)}" type="${escapeXml(spec.type)}" relevance="${relevance}" tokens="${tokens}" collapsed="true">`);
412
+ lines.push(` ${escapeXml(spec.collapsedSummary ?? "")}`);
413
+ lines.push(" </spec>");
414
+ } else {
415
+ lines.push(` <spec id="${escapeXml(spec.specId)}" type="${escapeXml(spec.type)}" relevance="${relevance}" tokens="${tokens}">`);
416
+ for (const section of spec.sections) {
417
+ const compressedAttr = section.compressed ? ' compressed="true"' : "";
418
+ lines.push(` <section name="${escapeXml(section.heading)}"${compressedAttr}>`);
419
+ lines.push(` ${escapeXml(section.content)}`);
420
+ lines.push(" </section>");
421
+ }
422
+ lines.push(" </spec>");
423
+ }
424
+ }
425
+ lines.push("</context>");
426
+ return lines.join("\n");
427
+ }
428
+
429
+ // ../pack/dist/formatters/markdown.js
430
+ function formatMarkdown(specs, stats) {
431
+ const parts = [];
432
+ for (let i = 0; i < specs.length; i++) {
433
+ const spec = specs[i];
434
+ const alloc = stats.allocations.find((a) => a.specId === spec.specId);
435
+ const relevance = alloc?.relevance ?? 0;
436
+ if (i > 0) {
437
+ parts.push("---");
438
+ parts.push("");
439
+ }
440
+ parts.push(`# ${spec.specId} (${spec.type}) [relevance: ${relevance}]`);
441
+ parts.push("");
442
+ if (spec.collapsed) {
443
+ parts.push(spec.collapsedSummary ?? "");
444
+ parts.push("");
445
+ } else {
446
+ for (const section of spec.sections) {
447
+ if (section.heading) {
448
+ parts.push(`## ${section.heading}`);
449
+ parts.push("");
450
+ }
451
+ parts.push(section.content);
452
+ parts.push("");
453
+ }
454
+ }
455
+ }
456
+ return parts.join("\n");
457
+ }
458
+
459
+ // ../pack/dist/formatters/json.js
460
+ function formatJson(specs, stats) {
461
+ const output = {
462
+ budget: stats.budget,
463
+ used: stats.used,
464
+ specs: specs.map((spec) => {
465
+ const alloc = stats.allocations.find((a) => a.specId === spec.specId);
466
+ const relevance = alloc?.relevance ?? 0;
467
+ const tokens = alloc?.tokens ?? 0;
468
+ const jsonSpec = {
469
+ id: spec.specId,
470
+ type: spec.type,
471
+ relevance,
472
+ tokens,
473
+ collapsed: spec.collapsed,
474
+ sections: spec.sections.map((s) => ({
475
+ name: s.heading,
476
+ content: s.content,
477
+ compressed: s.compressed
478
+ }))
479
+ };
480
+ if (spec.collapsed) {
481
+ jsonSpec.summary = spec.collapsedSummary ?? "";
482
+ }
483
+ return jsonSpec;
484
+ })
485
+ };
486
+ return JSON.stringify(output, null, 2);
487
+ }
488
+
489
+ // ../pack/dist/index.js
490
+ function emptyGraph() {
491
+ return {
492
+ nodes: [],
493
+ edges: [],
494
+ topologicalSort: () => [],
495
+ getDownstream: () => [],
496
+ getUpstream: () => []
497
+ };
498
+ }
499
+ function buildCompressionOptions(packConfig) {
500
+ const compression = packConfig?.compression;
501
+ return {
502
+ stripBoilerplate: compression?.strip_boilerplate ?? true,
503
+ stableDays: compression?.stable_days ?? 7,
504
+ collapseResolvedAdrs: compression?.collapse_resolved_adrs ?? true,
505
+ boilerplateSections: packConfig?.boilerplate_sections ?? [
506
+ "Changelog",
507
+ "Revision History",
508
+ "Document History"
509
+ ]
510
+ };
511
+ }
512
+ function pack(specs, options, packConfig, graph) {
513
+ const budget = options.budget ?? packConfig?.max_tokens ?? 12e3;
514
+ const format = options.format ?? packConfig?.format ?? "xml";
515
+ const full = options.full ?? false;
516
+ const compression = buildCompressionOptions(packConfig);
517
+ const resolvedGraph = graph ?? emptyGraph();
518
+ const specMap = /* @__PURE__ */ new Map();
519
+ for (const spec of specs) {
520
+ specMap.set(spec.frontmatter.id, spec);
521
+ }
522
+ const scores = options.specs ? scoreSpecsByIds(specMap, options.specs, resolvedGraph) : scoreSpecs(specMap, options.task, resolvedGraph);
523
+ const { specs: compressedSpecs, stats } = allocate(specs, scores, {
524
+ budget,
525
+ full,
526
+ compression
527
+ });
528
+ if (options.dryRun) {
529
+ return { output: "", stats };
530
+ }
531
+ let output;
532
+ switch (format) {
533
+ case "markdown":
534
+ output = formatMarkdown(compressedSpecs, stats);
535
+ break;
536
+ case "json":
537
+ output = formatJson(compressedSpecs, stats);
538
+ break;
539
+ default:
540
+ output = formatXml(compressedSpecs, stats);
541
+ break;
542
+ }
543
+ return { output, stats };
544
+ }
545
+
546
+ // src/commands/pack.ts
547
+ import { writeFile } from "fs/promises";
548
+ async function runPack(options) {
549
+ const config = await loadConfig(void 0, options.configDir);
550
+ const allSpecs = [];
551
+ for (const [, entry] of Object.entries(config.specs)) {
552
+ const files = await resolveGlob(entry.path, options.configDir);
553
+ for (const file of files) {
554
+ allSpecs.push(await parseSpec(file));
555
+ }
556
+ }
557
+ let graph;
558
+ try {
559
+ graph = buildGraph(config);
560
+ } catch {
561
+ }
562
+ const result = pack(
563
+ allSpecs,
564
+ {
565
+ task: options.task,
566
+ specs: options.specs,
567
+ budget: options.budget,
568
+ format: options.format,
569
+ full: options.full,
570
+ dryRun: options.dryRun
571
+ },
572
+ config.pack,
573
+ graph
574
+ );
575
+ return result;
576
+ }
577
+ var pack_default = defineCommand({
578
+ meta: { name: "pack", description: "Pack specs into AI-ready context" },
579
+ args: {
580
+ quiet: sharedArgs.quiet,
581
+ verbose: sharedArgs.verbose,
582
+ task: { type: "string", description: "Task or context to optimise relevance for" },
583
+ specs: { type: "string", description: "Comma-separated spec IDs or glob patterns to include" },
584
+ budget: { type: "string", description: "Maximum token budget for the output" },
585
+ format: {
586
+ type: "string",
587
+ description: "Output format (xml, markdown, json)",
588
+ default: "xml"
589
+ },
590
+ out: { type: "string", description: "Write output to file instead of stdout" },
591
+ full: { type: "boolean", description: "Include all specs without budget trimming" },
592
+ "dry-run": { type: "boolean", description: "Preview what would be packed without writing output" }
593
+ },
594
+ async run({ args }) {
595
+ const logger = createLogger({ quiet: args.quiet, verbose: args.verbose });
596
+ if (args.task && args.specs) {
597
+ console.error("\n \u2717 --task and --specs are mutually exclusive\n");
598
+ process.exit(1);
599
+ }
600
+ let budget;
601
+ if (args.budget) {
602
+ budget = Number(args.budget);
603
+ if (Number.isNaN(budget)) {
604
+ console.error("\n \u2717 --budget must be a valid number\n");
605
+ process.exit(1);
606
+ }
607
+ }
608
+ const format = args.format;
609
+ if (format && !["xml", "markdown", "json"].includes(format)) {
610
+ console.error(`
611
+ \u2717 --format must be one of: xml, markdown, json
612
+ `);
613
+ process.exit(1);
614
+ }
615
+ try {
616
+ const specsList = args.specs ? args.specs.split(",").map((s) => s.trim()) : void 0;
617
+ const result = await runPack({
618
+ configDir: process.cwd(),
619
+ task: args.task,
620
+ specs: specsList,
621
+ budget,
622
+ format,
623
+ full: args.full,
624
+ dryRun: args["dry-run"]
625
+ });
626
+ const { stats } = result;
627
+ if (args["dry-run"]) {
628
+ console.log("\n Dry Run Summary:\n");
629
+ for (const alloc of stats.allocations) {
630
+ const status = alloc.included ? "\u2713" : "\u2717";
631
+ const compressed = alloc.compressed ? " (compressed)" : "";
632
+ console.log(
633
+ ` ${status} ${alloc.specId} relevance=${alloc.relevance.toFixed(2)} tokens=${alloc.tokens}${compressed}`
634
+ );
635
+ }
636
+ console.log(`
637
+ Budget: ${stats.used} / ${stats.budget} tokens`);
638
+ console.log(` Included: ${stats.specsIncluded} / ${stats.specsIncluded + stats.specsExcluded} specs`);
639
+ console.log(` Sections compressed: ${stats.sectionsCompressed}
640
+ `);
641
+ return;
642
+ }
643
+ if (args.out) {
644
+ await writeFile(args.out, result.output, "utf-8");
645
+ logger.info(`Output written to ${args.out}`);
646
+ } else {
647
+ process.stdout.write(result.output);
648
+ }
649
+ const total = stats.specsIncluded + stats.specsExcluded;
650
+ process.stderr.write(
651
+ `Packed ${stats.specsIncluded}/${total} specs \u2022 ${stats.used} / ${stats.budget} tokens \u2022 ${stats.sectionsCompressed} sections compressed
652
+ `
653
+ );
654
+ } catch (err) {
655
+ console.error(`
656
+ \u2717 ${err.message}
657
+ `);
658
+ process.exit(1);
659
+ }
660
+ }
661
+ });
662
+ export {
663
+ pack_default as default,
664
+ runPack
665
+ };
666
+ //# sourceMappingURL=pack-KCLS3VVU.js.map