specdx 0.1.0-alpha.4 → 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/index.js CHANGED
@@ -95,7 +95,27 @@ var config_default = {
95
95
  },
96
96
  additionalProperties: false
97
97
  },
98
- pack: { type: "object" },
98
+ pack: {
99
+ type: "object",
100
+ properties: {
101
+ max_tokens: { type: "integer", minimum: 1 },
102
+ format: { type: "string", enum: ["xml", "markdown", "json"] },
103
+ compression: {
104
+ type: "object",
105
+ properties: {
106
+ strip_boilerplate: { type: "boolean" },
107
+ stable_days: { type: "integer", minimum: 0 },
108
+ collapse_resolved_adrs: { type: "boolean" }
109
+ },
110
+ additionalProperties: false
111
+ },
112
+ boilerplate_sections: {
113
+ type: "array",
114
+ items: { type: "string" }
115
+ }
116
+ },
117
+ additionalProperties: false
118
+ },
99
119
  diff: { type: "object" },
100
120
  ci: { type: "object" }
101
121
  },
@@ -282,7 +302,7 @@ async function scaffoldProject({
282
302
  var init_default = defineCommand({
283
303
  meta: {
284
304
  name: "init",
285
- description: "Initialize a new SDX project with spec scaffolding"
305
+ description: "Initialize a new specdx project with spec scaffolding"
286
306
  },
287
307
  args: {
288
308
  name: {
@@ -377,6 +397,22 @@ import { parse as parseYaml2 } from "yaml";
377
397
  import { unified } from "unified";
378
398
  import remarkParse from "remark-parse";
379
399
  import { visit } from "unist-util-visit";
400
+
401
+ // ../core/dist/tokens.js
402
+ import { encodingForModel } from "js-tiktoken";
403
+ var encoder;
404
+ function getEncoder() {
405
+ if (!encoder)
406
+ encoder = encodingForModel("gpt-4o");
407
+ return encoder;
408
+ }
409
+ function countTokens(text) {
410
+ if (!text)
411
+ return 0;
412
+ return getEncoder().encode(text).length;
413
+ }
414
+
415
+ // ../core/dist/parser.js
380
416
  var matter = grayMatterNs.default ?? grayMatterNs;
381
417
  var ParseError = class extends Error {
382
418
  constructor(message) {
@@ -399,7 +435,8 @@ async function parseSpec(filePath) {
399
435
  }
400
436
  function parseMarkdownSpec(filePath, raw) {
401
437
  const { data, content } = matter(raw);
402
- const sections = extractSections(content);
438
+ const parsedSections = extractParsedSections(content);
439
+ const sections = parsedSections.map((s) => s.heading).filter(Boolean);
403
440
  const frontmatter = data;
404
441
  const specType = frontmatter.type;
405
442
  let valid = false;
@@ -409,7 +446,7 @@ function parseMarkdownSpec(filePath, raw) {
409
446
  valid = result.valid;
410
447
  validationErrors = result.errors;
411
448
  }
412
- return { filePath, frontmatter, content, sections, valid, validationErrors };
449
+ return { filePath, frontmatter, content, sections, parsedSections, valid, validationErrors };
413
450
  }
414
451
  function parseYamlSpec(filePath, raw) {
415
452
  let data;
@@ -427,18 +464,39 @@ function parseYamlSpec(filePath, raw) {
427
464
  valid = result.valid;
428
465
  validationErrors = result.errors;
429
466
  }
430
- return { filePath, frontmatter, content: "", sections: [], valid, validationErrors };
467
+ return { filePath, frontmatter, content: "", sections: [], parsedSections: [], valid, validationErrors };
431
468
  }
432
- function extractSections(markdown) {
469
+ function extractParsedSections(markdown) {
433
470
  const tree = unified().use(remarkParse).parse(markdown);
434
- const sections = [];
471
+ const h2s = [];
435
472
  visit(tree, "heading", (node) => {
436
473
  if (node.depth === 2) {
437
474
  const text = node.children.filter((c) => c.type === "text").map((c) => c.value).join("");
438
- if (text)
439
- sections.push(text);
475
+ h2s.push({
476
+ heading: text,
477
+ startOffset: node.position.start.offset,
478
+ endOffset: node.position.end.offset
479
+ });
440
480
  }
441
481
  });
482
+ const sections = [];
483
+ const firstH2 = h2s[0];
484
+ const firstOffset = firstH2 ? firstH2.startOffset : markdown.length;
485
+ const preamble = markdown.slice(0, firstOffset).trim();
486
+ if (preamble) {
487
+ sections.push({ heading: "", content: preamble, tokens: countTokens(preamble) });
488
+ }
489
+ for (let i = 0; i < h2s.length; i++) {
490
+ const current = h2s[i];
491
+ const next = h2s[i + 1];
492
+ const end = next ? next.startOffset : markdown.length;
493
+ const content = markdown.slice(current.endOffset, end).trim();
494
+ sections.push({
495
+ heading: current.heading,
496
+ content,
497
+ tokens: countTokens(content)
498
+ });
499
+ }
442
500
  return sections;
443
501
  }
444
502
 
@@ -536,9 +594,6 @@ async function resolveGlob(pattern, baseDir) {
536
594
  return glob([absolutePattern], { absolute: true });
537
595
  }
538
596
 
539
- // ../core/dist/tokens.js
540
- import { encodingForModel } from "js-tiktoken";
541
-
542
597
  // ../core/dist/logger.js
543
598
  import { createConsola } from "consola";
544
599
  function createLogger(options) {
@@ -874,8 +929,660 @@ var lint_default = defineCommand2({
874
929
  }
875
930
  }
876
931
  });
932
+
933
+ // src/commands/pack.ts
934
+ import { defineCommand as defineCommand3 } from "citty";
935
+
936
+ // ../pack/dist/resolver.js
937
+ var STOPWORDS = /* @__PURE__ */ new Set([
938
+ "a",
939
+ "an",
940
+ "and",
941
+ "are",
942
+ "as",
943
+ "at",
944
+ "be",
945
+ "but",
946
+ "by",
947
+ "do",
948
+ "for",
949
+ "from",
950
+ "had",
951
+ "has",
952
+ "have",
953
+ "he",
954
+ "her",
955
+ "his",
956
+ "how",
957
+ "i",
958
+ "if",
959
+ "in",
960
+ "into",
961
+ "is",
962
+ "it",
963
+ "its",
964
+ "just",
965
+ "me",
966
+ "my",
967
+ "no",
968
+ "nor",
969
+ "not",
970
+ "of",
971
+ "on",
972
+ "or",
973
+ "our",
974
+ "out",
975
+ "own",
976
+ "say",
977
+ "she",
978
+ "so",
979
+ "some",
980
+ "such",
981
+ "than",
982
+ "that",
983
+ "the",
984
+ "their",
985
+ "them",
986
+ "then",
987
+ "there",
988
+ "these",
989
+ "they",
990
+ "this",
991
+ "to",
992
+ "too",
993
+ "up",
994
+ "us",
995
+ "very",
996
+ "was",
997
+ "we",
998
+ "were",
999
+ "what",
1000
+ "when",
1001
+ "where",
1002
+ "which",
1003
+ "while",
1004
+ "who",
1005
+ "whom",
1006
+ "why",
1007
+ "will",
1008
+ "with",
1009
+ "would",
1010
+ "you",
1011
+ "your"
1012
+ ]);
1013
+ function tokenize(task) {
1014
+ return task.split(/[\s\-_/.,;:!?()[\]{}'"]+/).map((t) => t.toLowerCase()).filter((t) => t.length > 1 && !STOPWORDS.has(t));
1015
+ }
1016
+ var WEIGHT_TAGS = 3;
1017
+ var WEIGHT_TITLE = 3;
1018
+ var WEIGHT_SECTIONS = 2;
1019
+ var WEIGHT_BODY = 1;
1020
+ var GRAPH_BOOST_FACTOR = 0.5;
1021
+ var SCORE_THRESHOLD = 0.1;
1022
+ function scoreSpecs(specs, task, graph) {
1023
+ const keywords = task ? tokenize(task) : [];
1024
+ if (keywords.length === 0) {
1025
+ const results2 = [];
1026
+ for (const specId of specs.keys()) {
1027
+ results2.push({
1028
+ specId,
1029
+ score: 1,
1030
+ rawScore: 1,
1031
+ matchedKeywords: [],
1032
+ graphBoosted: false
1033
+ });
1034
+ }
1035
+ return results2;
1036
+ }
1037
+ const rawScores = /* @__PURE__ */ new Map();
1038
+ const matchedMap = /* @__PURE__ */ new Map();
1039
+ for (const [specId, spec] of specs) {
1040
+ let weightedHits = 0;
1041
+ const matched = /* @__PURE__ */ new Set();
1042
+ for (const keyword of keywords) {
1043
+ let hit = false;
1044
+ const tags = spec.frontmatter.tags ?? [];
1045
+ for (const tag of tags) {
1046
+ if (typeof tag === "string" && tag.toLowerCase().includes(keyword)) {
1047
+ weightedHits += WEIGHT_TAGS;
1048
+ hit = true;
1049
+ break;
1050
+ }
1051
+ }
1052
+ const title = spec.frontmatter.title;
1053
+ if (typeof title === "string" && title.toLowerCase().includes(keyword)) {
1054
+ weightedHits += WEIGHT_TITLE;
1055
+ hit = true;
1056
+ }
1057
+ for (const heading of spec.sections) {
1058
+ if (heading.toLowerCase().includes(keyword)) {
1059
+ weightedHits += WEIGHT_SECTIONS;
1060
+ hit = true;
1061
+ break;
1062
+ }
1063
+ }
1064
+ if (spec.content.toLowerCase().includes(keyword)) {
1065
+ weightedHits += WEIGHT_BODY;
1066
+ hit = true;
1067
+ }
1068
+ if (hit) {
1069
+ matched.add(keyword);
1070
+ }
1071
+ }
1072
+ const raw = weightedHits / keywords.length;
1073
+ rawScores.set(specId, raw);
1074
+ matchedMap.set(specId, matched);
1075
+ }
1076
+ const boostScores = /* @__PURE__ */ new Map();
1077
+ const boostedSet = /* @__PURE__ */ new Set();
1078
+ for (const [specId, rawScore] of rawScores) {
1079
+ if (rawScore <= 0)
1080
+ continue;
1081
+ const boostAmount = rawScore * GRAPH_BOOST_FACTOR;
1082
+ for (const edge of graph.edges) {
1083
+ let neighborId;
1084
+ if (edge.from === specId) {
1085
+ neighborId = edge.to;
1086
+ } else if (edge.to === specId) {
1087
+ neighborId = edge.from;
1088
+ }
1089
+ if (neighborId !== void 0 && specs.has(neighborId)) {
1090
+ const existing = boostScores.get(neighborId) ?? 0;
1091
+ boostScores.set(neighborId, Math.max(existing, boostAmount));
1092
+ }
1093
+ }
1094
+ }
1095
+ const finalRawScores = /* @__PURE__ */ new Map();
1096
+ for (const specId of specs.keys()) {
1097
+ const raw = rawScores.get(specId) ?? 0;
1098
+ const boost = boostScores.get(specId) ?? 0;
1099
+ const combined = raw + boost;
1100
+ finalRawScores.set(specId, combined);
1101
+ if (boost > 0 && raw === 0) {
1102
+ boostedSet.add(specId);
1103
+ }
1104
+ }
1105
+ let maxScore = 0;
1106
+ for (const score of finalRawScores.values()) {
1107
+ if (score > maxScore)
1108
+ maxScore = score;
1109
+ }
1110
+ const results = [];
1111
+ for (const [specId] of specs) {
1112
+ const combined = finalRawScores.get(specId) ?? 0;
1113
+ const normalized = maxScore > 0 ? combined / maxScore : 0;
1114
+ if (normalized < SCORE_THRESHOLD)
1115
+ continue;
1116
+ results.push({
1117
+ specId,
1118
+ score: normalized,
1119
+ rawScore: rawScores.get(specId) ?? 0,
1120
+ matchedKeywords: [...matchedMap.get(specId) ?? []],
1121
+ graphBoosted: boostedSet.has(specId)
1122
+ });
1123
+ }
1124
+ results.sort((a, b) => b.score - a.score);
1125
+ return results;
1126
+ }
1127
+ function scoreSpecsByIds(specs, specIds, graph) {
1128
+ for (const id of specIds) {
1129
+ if (!specs.has(id)) {
1130
+ const available = [...specs.keys()].join(", ");
1131
+ throw new Error(`Unknown spec: "${id}". Available specs: ${available}`);
1132
+ }
1133
+ }
1134
+ const scoreMap = /* @__PURE__ */ new Map();
1135
+ for (const id of specIds) {
1136
+ scoreMap.set(id, 1);
1137
+ }
1138
+ for (const id of specIds) {
1139
+ const upstream = graph.getUpstream(id);
1140
+ for (const depId of upstream) {
1141
+ if (!scoreMap.has(depId) && specs.has(depId)) {
1142
+ scoreMap.set(depId, 0.5);
1143
+ }
1144
+ }
1145
+ }
1146
+ const results = [];
1147
+ for (const [specId, score] of scoreMap) {
1148
+ results.push({
1149
+ specId,
1150
+ score,
1151
+ rawScore: score,
1152
+ matchedKeywords: [],
1153
+ graphBoosted: score < 1
1154
+ });
1155
+ }
1156
+ results.sort((a, b) => b.score - a.score);
1157
+ return results;
1158
+ }
1159
+
1160
+ // ../pack/dist/compressor.js
1161
+ function isOlderThanDays(dateStr, days) {
1162
+ if (!dateStr)
1163
+ return false;
1164
+ const ms = Date.parse(dateStr);
1165
+ if (Number.isNaN(ms))
1166
+ return false;
1167
+ const diffMs = Date.now() - ms;
1168
+ return diffMs > days * 24 * 60 * 60 * 1e3;
1169
+ }
1170
+ function compressSpec(specId, type, title, status, updatedDate, parsedSections, options) {
1171
+ if (type === "adr" && status === "superseded" && options.collapseResolvedAdrs) {
1172
+ return {
1173
+ specId,
1174
+ type,
1175
+ title,
1176
+ sections: [],
1177
+ collapsed: true,
1178
+ collapsedSummary: `[ADR] ${title} \u2014 superseded`
1179
+ };
1180
+ }
1181
+ const stale = options.stableDays > 0 && isOlderThanDays(updatedDate, options.stableDays);
1182
+ const boilerplateSet = new Set(options.boilerplateSections.map((s) => s.toLowerCase()));
1183
+ const sections = [];
1184
+ for (const section of parsedSections) {
1185
+ if (options.stripBoilerplate && section.heading && boilerplateSet.has(section.heading.toLowerCase())) {
1186
+ continue;
1187
+ }
1188
+ if (stale && section.heading) {
1189
+ const stub = `[Unchanged since ${updatedDate} \u2014 ${section.tokens} tokens omitted]`;
1190
+ sections.push({
1191
+ heading: section.heading,
1192
+ content: stub,
1193
+ tokens: countTokens(stub),
1194
+ compressed: true,
1195
+ originalTokens: section.tokens
1196
+ });
1197
+ continue;
1198
+ }
1199
+ sections.push({
1200
+ heading: section.heading,
1201
+ content: section.content,
1202
+ tokens: section.tokens,
1203
+ compressed: false,
1204
+ originalTokens: section.tokens
1205
+ });
1206
+ }
1207
+ return {
1208
+ specId,
1209
+ type,
1210
+ title,
1211
+ sections,
1212
+ collapsed: false
1213
+ };
1214
+ }
1215
+
1216
+ // ../pack/dist/allocator.js
1217
+ function allocate(specs, scores, options) {
1218
+ const specMap = /* @__PURE__ */ new Map();
1219
+ for (const spec of specs) {
1220
+ specMap.set(spec.frontmatter.id, spec);
1221
+ }
1222
+ const items = [];
1223
+ for (const score of scores) {
1224
+ const spec = specMap.get(score.specId);
1225
+ if (!spec)
1226
+ continue;
1227
+ let compressed;
1228
+ if (options.full) {
1229
+ compressed = {
1230
+ specId: score.specId,
1231
+ type: String(spec.frontmatter.type),
1232
+ title: String(spec.frontmatter.title),
1233
+ sections: spec.parsedSections.map((s) => ({
1234
+ heading: s.heading,
1235
+ content: s.content,
1236
+ tokens: s.tokens,
1237
+ compressed: false,
1238
+ originalTokens: s.tokens
1239
+ })),
1240
+ collapsed: false
1241
+ };
1242
+ } else {
1243
+ compressed = compressSpec(score.specId, String(spec.frontmatter.type), String(spec.frontmatter.title), spec.frontmatter.status, spec.frontmatter.updated, spec.parsedSections, options.compression);
1244
+ }
1245
+ let tokens;
1246
+ if (compressed.collapsed) {
1247
+ tokens = countTokens(compressed.collapsedSummary ?? "");
1248
+ } else {
1249
+ tokens = 0;
1250
+ for (const section of compressed.sections) {
1251
+ tokens += section.tokens;
1252
+ }
1253
+ }
1254
+ items.push({ compressed, relevance: score.score, tokens });
1255
+ }
1256
+ items.sort((a, b) => b.relevance - a.relevance);
1257
+ const totalTokens = items.reduce((sum, item) => sum + item.tokens, 0);
1258
+ const withinBudget = totalTokens <= options.budget;
1259
+ const included = [];
1260
+ const excluded = [];
1261
+ let usedTokens = 0;
1262
+ if (withinBudget) {
1263
+ for (const item of items) {
1264
+ included.push(item);
1265
+ usedTokens += item.tokens;
1266
+ }
1267
+ } else {
1268
+ for (const item of items) {
1269
+ if (usedTokens + item.tokens <= options.budget) {
1270
+ included.push(item);
1271
+ usedTokens += item.tokens;
1272
+ } else {
1273
+ excluded.push(item);
1274
+ }
1275
+ }
1276
+ }
1277
+ let sectionsCompressed = 0;
1278
+ for (const item of included) {
1279
+ for (const section of item.compressed.sections) {
1280
+ if (section.compressed) {
1281
+ sectionsCompressed++;
1282
+ }
1283
+ }
1284
+ }
1285
+ const allocations = [];
1286
+ for (const item of included) {
1287
+ allocations.push({
1288
+ specId: item.compressed.specId,
1289
+ type: item.compressed.type,
1290
+ relevance: item.relevance,
1291
+ tokens: item.tokens,
1292
+ compressed: item.compressed.collapsed || item.compressed.sections.some((s) => s.compressed),
1293
+ included: true
1294
+ });
1295
+ }
1296
+ for (const item of excluded) {
1297
+ allocations.push({
1298
+ specId: item.compressed.specId,
1299
+ type: item.compressed.type,
1300
+ relevance: item.relevance,
1301
+ tokens: item.tokens,
1302
+ compressed: item.compressed.collapsed || item.compressed.sections.some((s) => s.compressed),
1303
+ included: false
1304
+ });
1305
+ }
1306
+ const stats = {
1307
+ budget: options.budget,
1308
+ used: usedTokens,
1309
+ specsIncluded: included.length,
1310
+ specsExcluded: excluded.length,
1311
+ sectionsCompressed,
1312
+ allocations
1313
+ };
1314
+ return {
1315
+ specs: included.map((item) => item.compressed),
1316
+ stats
1317
+ };
1318
+ }
1319
+
1320
+ // ../pack/dist/formatters/xml.js
1321
+ function escapeXml(text) {
1322
+ return text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
1323
+ }
1324
+ function formatXml(specs, stats) {
1325
+ const lines = [];
1326
+ lines.push(`<context budget="${stats.budget}" used="${stats.used}" specs="${stats.specsIncluded}" compressed="${stats.sectionsCompressed}">`);
1327
+ for (const spec of specs) {
1328
+ const alloc = stats.allocations.find((a) => a.specId === spec.specId);
1329
+ const relevance = alloc?.relevance ?? 0;
1330
+ const tokens = alloc?.tokens ?? 0;
1331
+ if (spec.collapsed) {
1332
+ lines.push(` <spec id="${escapeXml(spec.specId)}" type="${escapeXml(spec.type)}" relevance="${relevance}" tokens="${tokens}" collapsed="true">`);
1333
+ lines.push(` ${escapeXml(spec.collapsedSummary ?? "")}`);
1334
+ lines.push(" </spec>");
1335
+ } else {
1336
+ lines.push(` <spec id="${escapeXml(spec.specId)}" type="${escapeXml(spec.type)}" relevance="${relevance}" tokens="${tokens}">`);
1337
+ for (const section of spec.sections) {
1338
+ const compressedAttr = section.compressed ? ' compressed="true"' : "";
1339
+ lines.push(` <section name="${escapeXml(section.heading)}"${compressedAttr}>`);
1340
+ lines.push(` ${escapeXml(section.content)}`);
1341
+ lines.push(" </section>");
1342
+ }
1343
+ lines.push(" </spec>");
1344
+ }
1345
+ }
1346
+ lines.push("</context>");
1347
+ return lines.join("\n");
1348
+ }
1349
+
1350
+ // ../pack/dist/formatters/markdown.js
1351
+ function formatMarkdown(specs, stats) {
1352
+ const parts = [];
1353
+ for (let i = 0; i < specs.length; i++) {
1354
+ const spec = specs[i];
1355
+ const alloc = stats.allocations.find((a) => a.specId === spec.specId);
1356
+ const relevance = alloc?.relevance ?? 0;
1357
+ if (i > 0) {
1358
+ parts.push("---");
1359
+ parts.push("");
1360
+ }
1361
+ parts.push(`# ${spec.specId} (${spec.type}) [relevance: ${relevance}]`);
1362
+ parts.push("");
1363
+ if (spec.collapsed) {
1364
+ parts.push(spec.collapsedSummary ?? "");
1365
+ parts.push("");
1366
+ } else {
1367
+ for (const section of spec.sections) {
1368
+ if (section.heading) {
1369
+ parts.push(`## ${section.heading}`);
1370
+ parts.push("");
1371
+ }
1372
+ parts.push(section.content);
1373
+ parts.push("");
1374
+ }
1375
+ }
1376
+ }
1377
+ return parts.join("\n");
1378
+ }
1379
+
1380
+ // ../pack/dist/formatters/json.js
1381
+ function formatJson2(specs, stats) {
1382
+ const output = {
1383
+ budget: stats.budget,
1384
+ used: stats.used,
1385
+ specs: specs.map((spec) => {
1386
+ const alloc = stats.allocations.find((a) => a.specId === spec.specId);
1387
+ const relevance = alloc?.relevance ?? 0;
1388
+ const tokens = alloc?.tokens ?? 0;
1389
+ const jsonSpec = {
1390
+ id: spec.specId,
1391
+ type: spec.type,
1392
+ relevance,
1393
+ tokens,
1394
+ collapsed: spec.collapsed,
1395
+ sections: spec.sections.map((s) => ({
1396
+ name: s.heading,
1397
+ content: s.content,
1398
+ compressed: s.compressed
1399
+ }))
1400
+ };
1401
+ if (spec.collapsed) {
1402
+ jsonSpec.summary = spec.collapsedSummary ?? "";
1403
+ }
1404
+ return jsonSpec;
1405
+ })
1406
+ };
1407
+ return JSON.stringify(output, null, 2);
1408
+ }
1409
+
1410
+ // ../pack/dist/index.js
1411
+ function emptyGraph() {
1412
+ return {
1413
+ nodes: [],
1414
+ edges: [],
1415
+ topologicalSort: () => [],
1416
+ getDownstream: () => [],
1417
+ getUpstream: () => []
1418
+ };
1419
+ }
1420
+ function buildCompressionOptions(packConfig) {
1421
+ const compression = packConfig?.compression;
1422
+ return {
1423
+ stripBoilerplate: compression?.strip_boilerplate ?? true,
1424
+ stableDays: compression?.stable_days ?? 7,
1425
+ collapseResolvedAdrs: compression?.collapse_resolved_adrs ?? true,
1426
+ boilerplateSections: packConfig?.boilerplate_sections ?? [
1427
+ "Changelog",
1428
+ "Revision History",
1429
+ "Document History"
1430
+ ]
1431
+ };
1432
+ }
1433
+ function pack(specs, options, packConfig, graph) {
1434
+ const budget = options.budget ?? packConfig?.max_tokens ?? 12e3;
1435
+ const format = options.format ?? packConfig?.format ?? "xml";
1436
+ const full = options.full ?? false;
1437
+ const compression = buildCompressionOptions(packConfig);
1438
+ const resolvedGraph = graph ?? emptyGraph();
1439
+ const specMap = /* @__PURE__ */ new Map();
1440
+ for (const spec of specs) {
1441
+ specMap.set(spec.frontmatter.id, spec);
1442
+ }
1443
+ const scores = options.specs ? scoreSpecsByIds(specMap, options.specs, resolvedGraph) : scoreSpecs(specMap, options.task, resolvedGraph);
1444
+ const { specs: compressedSpecs, stats } = allocate(specs, scores, {
1445
+ budget,
1446
+ full,
1447
+ compression
1448
+ });
1449
+ if (options.dryRun) {
1450
+ return { output: "", stats };
1451
+ }
1452
+ let output;
1453
+ switch (format) {
1454
+ case "markdown":
1455
+ output = formatMarkdown(compressedSpecs, stats);
1456
+ break;
1457
+ case "json":
1458
+ output = formatJson2(compressedSpecs, stats);
1459
+ break;
1460
+ default:
1461
+ output = formatXml(compressedSpecs, stats);
1462
+ break;
1463
+ }
1464
+ return { output, stats };
1465
+ }
1466
+
1467
+ // src/commands/pack.ts
1468
+ import { writeFile as writeFile2 } from "fs/promises";
1469
+ async function runPack(options) {
1470
+ const config = await loadConfig(void 0, options.configDir);
1471
+ const allSpecs = [];
1472
+ for (const [, entry] of Object.entries(config.specs)) {
1473
+ const files = await resolveGlob(entry.path, options.configDir);
1474
+ for (const file of files) {
1475
+ allSpecs.push(await parseSpec(file));
1476
+ }
1477
+ }
1478
+ let graph;
1479
+ try {
1480
+ graph = buildGraph(config);
1481
+ } catch {
1482
+ }
1483
+ const result = pack(
1484
+ allSpecs,
1485
+ {
1486
+ task: options.task,
1487
+ specs: options.specs,
1488
+ budget: options.budget,
1489
+ format: options.format,
1490
+ full: options.full,
1491
+ dryRun: options.dryRun
1492
+ },
1493
+ config.pack,
1494
+ graph
1495
+ );
1496
+ return result;
1497
+ }
1498
+ var pack_default = defineCommand3({
1499
+ meta: { name: "pack", description: "Pack specs into AI-ready context" },
1500
+ args: {
1501
+ quiet: sharedArgs.quiet,
1502
+ verbose: sharedArgs.verbose,
1503
+ task: { type: "string", description: "Task or context to optimise relevance for" },
1504
+ specs: { type: "string", description: "Comma-separated spec IDs or glob patterns to include" },
1505
+ budget: { type: "string", description: "Maximum token budget for the output" },
1506
+ format: {
1507
+ type: "string",
1508
+ description: "Output format (xml, markdown, json)",
1509
+ default: "xml"
1510
+ },
1511
+ out: { type: "string", description: "Write output to file instead of stdout" },
1512
+ full: { type: "boolean", description: "Include all specs without budget trimming" },
1513
+ "dry-run": { type: "boolean", description: "Preview what would be packed without writing output" }
1514
+ },
1515
+ async run({ args }) {
1516
+ const logger = createLogger({ quiet: args.quiet, verbose: args.verbose });
1517
+ if (args.task && args.specs) {
1518
+ console.error("\n \u2717 --task and --specs are mutually exclusive\n");
1519
+ process.exit(1);
1520
+ }
1521
+ let budget;
1522
+ if (args.budget) {
1523
+ budget = Number(args.budget);
1524
+ if (Number.isNaN(budget)) {
1525
+ console.error("\n \u2717 --budget must be a valid number\n");
1526
+ process.exit(1);
1527
+ }
1528
+ }
1529
+ const format = args.format;
1530
+ if (format && !["xml", "markdown", "json"].includes(format)) {
1531
+ console.error(`
1532
+ \u2717 --format must be one of: xml, markdown, json
1533
+ `);
1534
+ process.exit(1);
1535
+ }
1536
+ try {
1537
+ const specsList = args.specs ? args.specs.split(",").map((s) => s.trim()) : void 0;
1538
+ const result = await runPack({
1539
+ configDir: process.cwd(),
1540
+ task: args.task,
1541
+ specs: specsList,
1542
+ budget,
1543
+ format,
1544
+ full: args.full,
1545
+ dryRun: args["dry-run"]
1546
+ });
1547
+ const { stats } = result;
1548
+ if (args["dry-run"]) {
1549
+ console.log("\n Dry Run Summary:\n");
1550
+ for (const alloc of stats.allocations) {
1551
+ const status = alloc.included ? "\u2713" : "\u2717";
1552
+ const compressed = alloc.compressed ? " (compressed)" : "";
1553
+ console.log(
1554
+ ` ${status} ${alloc.specId} relevance=${alloc.relevance.toFixed(2)} tokens=${alloc.tokens}${compressed}`
1555
+ );
1556
+ }
1557
+ console.log(`
1558
+ Budget: ${stats.used} / ${stats.budget} tokens`);
1559
+ console.log(` Included: ${stats.specsIncluded} / ${stats.specsIncluded + stats.specsExcluded} specs`);
1560
+ console.log(` Sections compressed: ${stats.sectionsCompressed}
1561
+ `);
1562
+ return;
1563
+ }
1564
+ if (args.out) {
1565
+ await writeFile2(args.out, result.output, "utf-8");
1566
+ logger.info(`Output written to ${args.out}`);
1567
+ } else {
1568
+ process.stdout.write(result.output);
1569
+ }
1570
+ const total = stats.specsIncluded + stats.specsExcluded;
1571
+ process.stderr.write(
1572
+ `Packed ${stats.specsIncluded}/${total} specs \u2022 ${stats.used} / ${stats.budget} tokens \u2022 ${stats.sectionsCompressed} sections compressed
1573
+ `
1574
+ );
1575
+ } catch (err) {
1576
+ console.error(`
1577
+ \u2717 ${err.message}
1578
+ `);
1579
+ process.exit(1);
1580
+ }
1581
+ }
1582
+ });
877
1583
  export {
878
1584
  runLint,
1585
+ runPack,
879
1586
  scaffoldProject
880
1587
  };
881
1588
  //# sourceMappingURL=index.js.map