specdx 0.4.0-alpha.9 → 0.4.0

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.
Files changed (114) hide show
  1. package/.claude-plugin/plugin.json +7 -2
  2. package/README.md +259 -0
  3. package/dist/{check-4FSSC6HN.js → check-PHXXA7VY.js} +68 -30
  4. package/dist/check-PHXXA7VY.js.map +1 -0
  5. package/dist/chunk-2BZIG7OE.js +185 -0
  6. package/dist/chunk-2BZIG7OE.js.map +1 -0
  7. package/dist/{chunk-N77RNV7J.js → chunk-3YXRWQGX.js} +217 -42
  8. package/dist/chunk-3YXRWQGX.js.map +1 -0
  9. package/dist/chunk-5WRI5ZAA.js +31 -0
  10. package/dist/chunk-DMGABJ6T.js +41 -0
  11. package/dist/chunk-DMGABJ6T.js.map +1 -0
  12. package/dist/{chunk-7JXW2GTJ.js → chunk-HCJDCS26.js} +9 -2
  13. package/dist/chunk-HCJDCS26.js.map +1 -0
  14. package/dist/chunk-LJTLNXGV.js +835 -0
  15. package/dist/chunk-LJTLNXGV.js.map +1 -0
  16. package/dist/chunk-NAWYG4VV.js +2846 -0
  17. package/dist/chunk-NAWYG4VV.js.map +1 -0
  18. package/dist/chunk-NHD44ZYN.js +20 -0
  19. package/dist/chunk-NHD44ZYN.js.map +1 -0
  20. package/dist/chunk-OVIKIIR4.js +103 -0
  21. package/dist/chunk-OVIKIIR4.js.map +1 -0
  22. package/dist/{chunk-IHTYAW7C.js → chunk-SNQNQ2MP.js} +111 -7
  23. package/dist/chunk-SNQNQ2MP.js.map +1 -0
  24. package/dist/{chunk-AKNPCB37.js → chunk-YRQPY5NF.js} +32 -12
  25. package/dist/chunk-YRQPY5NF.js.map +1 -0
  26. package/dist/diff-6C5LJ7SH.js +200 -0
  27. package/dist/diff-6C5LJ7SH.js.map +1 -0
  28. package/dist/{dist-4DIRTBJH.js → dist-PK52GA7M.js} +43 -20
  29. package/dist/dist-PK52GA7M.js.map +1 -0
  30. package/dist/{dist-RL2DT3ZE.js → dist-ROHCFKYT.js} +3 -2
  31. package/dist/dist-ROHCFKYT.js.map +1 -0
  32. package/dist/generate-K72WD455.js +21 -0
  33. package/dist/generate-K72WD455.js.map +1 -0
  34. package/dist/{generate-story-EFHGINHA.js → generate-story-NUCNYL3I.js} +43 -19
  35. package/dist/generate-story-NUCNYL3I.js.map +1 -0
  36. package/dist/{generate-test-plan-BO7444RG.js → generate-test-plan-Z46W3N3B.js} +61 -11
  37. package/dist/generate-test-plan-Z46W3N3B.js.map +1 -0
  38. package/dist/{graph-5XINV7PT.js → graph-4RNURBNP.js} +49 -11
  39. package/dist/graph-4RNURBNP.js.map +1 -0
  40. package/dist/index.d.ts +275 -0
  41. package/dist/index.js +2660 -371
  42. package/dist/index.js.map +1 -1
  43. package/dist/{lint-PTMWMLDQ.js → lint-2VZPNLE3.js} +46 -18
  44. package/dist/lint-2VZPNLE3.js.map +1 -0
  45. package/dist/main.js +10 -229
  46. package/dist/main.js.map +1 -1
  47. package/dist/mcp-E6PJWBDQ.js +35 -0
  48. package/dist/mcp-E6PJWBDQ.js.map +1 -0
  49. package/dist/{migrate-4KF6GHLO.js → migrate-FKFC7UAO.js} +21 -9
  50. package/dist/migrate-FKFC7UAO.js.map +1 -0
  51. package/dist/{pack-DSOODXAN.js → pack-DE4UBTCC.js} +41 -13
  52. package/dist/pack-DE4UBTCC.js.map +1 -0
  53. package/dist/{ready-6DNKIHP6.js → ready-K74SLQ24.js} +55 -14
  54. package/dist/ready-K74SLQ24.js.map +1 -0
  55. package/dist/skills/{specdx-author-spec.md → core/specdx-author-spec/SKILL.md} +10 -6
  56. package/dist/skills/{specdx-author-spec → core/specdx-author-spec/references}/step-01-frontmatter.md +1 -1
  57. package/dist/skills/{specdx-author-spec → core/specdx-author-spec/references}/step-02-sections.md +41 -0
  58. package/dist/skills/{specdx-onboard.md → core/specdx-onboard/SKILL.md} +8 -3
  59. package/dist/skills/{specdx-plan-from-spec.md → core/specdx-plan-from-spec/SKILL.md} +5 -1
  60. package/dist/skills/{specdx-pre-commit.md → core/specdx-pre-commit/SKILL.md} +16 -2
  61. package/dist/skills/{specdx-review-spec.md → core/specdx-review-spec/SKILL.md} +5 -1
  62. package/dist/skills/core/specdx-router/SKILL.md +67 -0
  63. package/dist/skills/{specdx-sprint-review.md → core/specdx-sprint-review/SKILL.md} +6 -2
  64. package/dist/skills/{specdx-start-task.md → core/specdx-start-task/SKILL.md} +5 -1
  65. package/dist/skills/{specdx-check-drift.md → experimental/specdx-check-drift/SKILL.md} +10 -4
  66. package/dist/skills/{specdx-verify.md → experimental/specdx-verify/SKILL.md} +6 -2
  67. package/dist/skills-36SRUEMR.js +121 -0
  68. package/dist/skills-36SRUEMR.js.map +1 -0
  69. package/dist/{status-WZK247CI.js → status-IAE3BB77.js} +63 -32
  70. package/dist/status-IAE3BB77.js.map +1 -0
  71. package/dist/{update-JTNSYX3B.js → update-UFOHZEAK.js} +22 -12
  72. package/dist/update-UFOHZEAK.js.map +1 -0
  73. package/dist/{validate-LBDYWUDX.js → validate-EZHUB5TW.js} +36 -17
  74. package/dist/validate-EZHUB5TW.js.map +1 -0
  75. package/hooks/hooks.json +12 -6
  76. package/hooks/session-start +35 -3
  77. package/package.json +28 -13
  78. package/dist/changelog-XUVHY3QK.js +0 -93
  79. package/dist/changelog-XUVHY3QK.js.map +0 -1
  80. package/dist/check-4FSSC6HN.js.map +0 -1
  81. package/dist/chunk-7JXW2GTJ.js.map +0 -1
  82. package/dist/chunk-AKNPCB37.js.map +0 -1
  83. package/dist/chunk-DAZCOUVK.js +0 -496
  84. package/dist/chunk-DAZCOUVK.js.map +0 -1
  85. package/dist/chunk-GAM4MXPC.js +0 -15
  86. package/dist/chunk-GAM4MXPC.js.map +0 -1
  87. package/dist/chunk-IHTYAW7C.js.map +0 -1
  88. package/dist/chunk-N77RNV7J.js.map +0 -1
  89. package/dist/chunk-SRZ33RJP.js +0 -1147
  90. package/dist/chunk-SRZ33RJP.js.map +0 -1
  91. package/dist/diff-OXZ34NU4.js +0 -107
  92. package/dist/diff-OXZ34NU4.js.map +0 -1
  93. package/dist/dist-4DIRTBJH.js.map +0 -1
  94. package/dist/explain-QBV3AESQ.js +0 -109
  95. package/dist/explain-QBV3AESQ.js.map +0 -1
  96. package/dist/generate-7GNPT2WJ.js +0 -13
  97. package/dist/generate-7GNPT2WJ.js.map +0 -1
  98. package/dist/generate-story-EFHGINHA.js.map +0 -1
  99. package/dist/generate-test-plan-BO7444RG.js.map +0 -1
  100. package/dist/graph-5XINV7PT.js.map +0 -1
  101. package/dist/lint-PTMWMLDQ.js.map +0 -1
  102. package/dist/mcp-BGFAPM6G.js +0 -17
  103. package/dist/mcp-BGFAPM6G.js.map +0 -1
  104. package/dist/migrate-4KF6GHLO.js.map +0 -1
  105. package/dist/pack-DSOODXAN.js.map +0 -1
  106. package/dist/ready-6DNKIHP6.js.map +0 -1
  107. package/dist/skills-3GBBWZW2.js +0 -93
  108. package/dist/skills-3GBBWZW2.js.map +0 -1
  109. package/dist/status-WZK247CI.js.map +0 -1
  110. package/dist/update-JTNSYX3B.js.map +0 -1
  111. package/dist/validate-LBDYWUDX.js.map +0 -1
  112. /package/dist/{dist-RL2DT3ZE.js.map → chunk-5WRI5ZAA.js.map} +0 -0
  113. /package/dist/skills/{spec-type-reference.md → core/specdx-author-spec/references/spec-type-reference.md} +0 -0
  114. /package/dist/skills/{specdx-author-spec → core/specdx-author-spec/references}/step-03-finalize.md +0 -0
@@ -0,0 +1,103 @@
1
+ // package.json
2
+ var package_default = {
3
+ name: "specdx",
4
+ version: "0.4.0",
5
+ description: "Spec-driven development toolchain. Validate, lint, pack, and ship specs for LLM-assisted workflows.",
6
+ type: "module",
7
+ license: "MIT",
8
+ author: "Umar Gora (https://github.com/umxr)",
9
+ repository: {
10
+ type: "git",
11
+ url: "https://github.com/umxr/specdx.git",
12
+ directory: "packages/cli"
13
+ },
14
+ homepage: "https://github.com/umxr/specdx#readme",
15
+ bugs: {
16
+ url: "https://github.com/umxr/specdx/issues"
17
+ },
18
+ keywords: [
19
+ "spec",
20
+ "specification",
21
+ "prd",
22
+ "technical-design",
23
+ "api-contract",
24
+ "lint",
25
+ "validation",
26
+ "llm",
27
+ "ai",
28
+ "context-packing",
29
+ "spec-driven-development",
30
+ "claude-code"
31
+ ],
32
+ engines: {
33
+ node: ">=18.0.0"
34
+ },
35
+ bin: {
36
+ specdx: "./dist/main.js"
37
+ },
38
+ exports: {
39
+ ".": {
40
+ types: "./dist/index.d.ts",
41
+ import: "./dist/index.js"
42
+ }
43
+ },
44
+ files: [
45
+ "dist",
46
+ ".claude-plugin",
47
+ "hooks",
48
+ "README.md"
49
+ ],
50
+ scripts: {
51
+ build: "tsup",
52
+ typecheck: "tsc --noEmit",
53
+ test: "vitest run",
54
+ clean: "rm -rf dist *.tsbuildinfo"
55
+ },
56
+ dependencies: {
57
+ "@modelcontextprotocol/sdk": "^1.27.0",
58
+ ajv: "^8.18.0",
59
+ "ajv-formats": "^3.0.1",
60
+ citty: "^0.2.1",
61
+ consola: "^3.4.0",
62
+ "gray-matter": "^4.0.3",
63
+ "js-tiktoken": "^1.0.18",
64
+ "remark-parse": "^11.0.0",
65
+ tinyglobby: "^0.2.12",
66
+ unified: "^11.0.0",
67
+ "unist-util-visit": "^5.0.0",
68
+ yaml: "^2.7.0",
69
+ zod: "^3.23.0"
70
+ },
71
+ devDependencies: {
72
+ "@specdx/check": "workspace:*",
73
+ "@specdx/core": "workspace:*",
74
+ "@specdx/diff": "workspace:*",
75
+ "@specdx/lint": "workspace:*",
76
+ "@specdx/mcp": "workspace:*",
77
+ "@specdx/pack": "workspace:*",
78
+ "@specdx/schema": "workspace:*",
79
+ "@specdx/skills": "workspace:*",
80
+ tsup: "^8.5.1",
81
+ typescript: "^5.7.0"
82
+ },
83
+ publishConfig: {
84
+ access: "public"
85
+ },
86
+ peerDependencies: {
87
+ "ts-morph": ">=20",
88
+ "@anthropic-ai/sdk": ">=0.30"
89
+ },
90
+ peerDependenciesMeta: {
91
+ "ts-morph": {
92
+ optional: true
93
+ },
94
+ "@anthropic-ai/sdk": {
95
+ optional: true
96
+ }
97
+ }
98
+ };
99
+
100
+ export {
101
+ package_default
102
+ };
103
+ //# sourceMappingURL=chunk-OVIKIIR4.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../package.json"],"sourcesContent":["{\n \"name\": \"specdx\",\n \"version\": \"0.4.0\",\n \"description\": \"Spec-driven development toolchain. Validate, lint, pack, and ship specs for LLM-assisted workflows.\",\n \"type\": \"module\",\n \"license\": \"MIT\",\n \"author\": \"Umar Gora (https://github.com/umxr)\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"https://github.com/umxr/specdx.git\",\n \"directory\": \"packages/cli\"\n },\n \"homepage\": \"https://github.com/umxr/specdx#readme\",\n \"bugs\": {\n \"url\": \"https://github.com/umxr/specdx/issues\"\n },\n \"keywords\": [\n \"spec\",\n \"specification\",\n \"prd\",\n \"technical-design\",\n \"api-contract\",\n \"lint\",\n \"validation\",\n \"llm\",\n \"ai\",\n \"context-packing\",\n \"spec-driven-development\",\n \"claude-code\"\n ],\n \"engines\": {\n \"node\": \">=18.0.0\"\n },\n \"bin\": {\n \"specdx\": \"./dist/main.js\"\n },\n \"exports\": {\n \".\": {\n \"types\": \"./dist/index.d.ts\",\n \"import\": \"./dist/index.js\"\n }\n },\n \"files\": [\n \"dist\",\n \".claude-plugin\",\n \"hooks\",\n \"README.md\"\n ],\n \"scripts\": {\n \"build\": \"tsup\",\n \"typecheck\": \"tsc --noEmit\",\n \"test\": \"vitest run\",\n \"clean\": \"rm -rf dist *.tsbuildinfo\"\n },\n \"dependencies\": {\n \"@modelcontextprotocol/sdk\": \"^1.27.0\",\n \"ajv\": \"^8.18.0\",\n \"ajv-formats\": \"^3.0.1\",\n \"citty\": \"^0.2.1\",\n \"consola\": \"^3.4.0\",\n \"gray-matter\": \"^4.0.3\",\n \"js-tiktoken\": \"^1.0.18\",\n \"remark-parse\": \"^11.0.0\",\n \"tinyglobby\": \"^0.2.12\",\n \"unified\": \"^11.0.0\",\n \"unist-util-visit\": \"^5.0.0\",\n \"yaml\": \"^2.7.0\",\n \"zod\": \"^3.23.0\"\n },\n \"devDependencies\": {\n \"@specdx/check\": \"workspace:*\",\n \"@specdx/core\": \"workspace:*\",\n \"@specdx/diff\": \"workspace:*\",\n \"@specdx/lint\": \"workspace:*\",\n \"@specdx/mcp\": \"workspace:*\",\n \"@specdx/pack\": \"workspace:*\",\n \"@specdx/schema\": \"workspace:*\",\n \"@specdx/skills\": \"workspace:*\",\n \"tsup\": \"^8.5.1\",\n \"typescript\": \"^5.7.0\"\n },\n \"publishConfig\": {\n \"access\": \"public\"\n },\n \"peerDependencies\": {\n \"ts-morph\": \">=20\",\n \"@anthropic-ai/sdk\": \">=0.30\"\n },\n \"peerDependenciesMeta\": {\n \"ts-morph\": {\n \"optional\": true\n },\n \"@anthropic-ai/sdk\": {\n \"optional\": true\n }\n }\n}\n"],"mappings":";AAAA;AAAA,EACE,MAAQ;AAAA,EACR,SAAW;AAAA,EACX,aAAe;AAAA,EACf,MAAQ;AAAA,EACR,SAAW;AAAA,EACX,QAAU;AAAA,EACV,YAAc;AAAA,IACZ,MAAQ;AAAA,IACR,KAAO;AAAA,IACP,WAAa;AAAA,EACf;AAAA,EACA,UAAY;AAAA,EACZ,MAAQ;AAAA,IACN,KAAO;AAAA,EACT;AAAA,EACA,UAAY;AAAA,IACV;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AAAA,EACA,SAAW;AAAA,IACT,MAAQ;AAAA,EACV;AAAA,EACA,KAAO;AAAA,IACL,QAAU;AAAA,EACZ;AAAA,EACA,SAAW;AAAA,IACT,KAAK;AAAA,MACH,OAAS;AAAA,MACT,QAAU;AAAA,IACZ;AAAA,EACF;AAAA,EACA,OAAS;AAAA,IACP;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AAAA,EACA,SAAW;AAAA,IACT,OAAS;AAAA,IACT,WAAa;AAAA,IACb,MAAQ;AAAA,IACR,OAAS;AAAA,EACX;AAAA,EACA,cAAgB;AAAA,IACd,6BAA6B;AAAA,IAC7B,KAAO;AAAA,IACP,eAAe;AAAA,IACf,OAAS;AAAA,IACT,SAAW;AAAA,IACX,eAAe;AAAA,IACf,eAAe;AAAA,IACf,gBAAgB;AAAA,IAChB,YAAc;AAAA,IACd,SAAW;AAAA,IACX,oBAAoB;AAAA,IACpB,MAAQ;AAAA,IACR,KAAO;AAAA,EACT;AAAA,EACA,iBAAmB;AAAA,IACjB,iBAAiB;AAAA,IACjB,gBAAgB;AAAA,IAChB,gBAAgB;AAAA,IAChB,gBAAgB;AAAA,IAChB,eAAe;AAAA,IACf,gBAAgB;AAAA,IAChB,kBAAkB;AAAA,IAClB,kBAAkB;AAAA,IAClB,MAAQ;AAAA,IACR,YAAc;AAAA,EAChB;AAAA,EACA,eAAiB;AAAA,IACf,QAAU;AAAA,EACZ;AAAA,EACA,kBAAoB;AAAA,IAClB,YAAY;AAAA,IACZ,qBAAqB;AAAA,EACvB;AAAA,EACA,sBAAwB;AAAA,IACtB,YAAY;AAAA,MACV,UAAY;AAAA,IACd;AAAA,IACA,qBAAqB;AAAA,MACnB,UAAY;AAAA,IACd;AAAA,EACF;AACF;","names":[]}
@@ -1,7 +1,8 @@
1
1
  import {
2
+ DEPENDENCY_RELATIONSHIPS,
2
3
  validateConfig,
3
4
  validateSpec
4
- } from "./chunk-7JXW2GTJ.js";
5
+ } from "./chunk-HCJDCS26.js";
5
6
 
6
7
  // ../core/dist/config.js
7
8
  import { readFile } from "fs/promises";
@@ -19,7 +20,7 @@ var CONFIG_FILENAME = "spec.config.yaml";
19
20
  async function loadConfig(filePath, searchFrom) {
20
21
  const resolvedPath = filePath ?? await findConfig(searchFrom ?? process.cwd());
21
22
  if (!resolvedPath) {
22
- throw new ConfigError(`No ${CONFIG_FILENAME} found. Run 'sdx init' to create one.`);
23
+ throw new ConfigError(`No ${CONFIG_FILENAME} found. Run 'specdx init' to create one.`);
23
24
  }
24
25
  let raw;
25
26
  try {
@@ -262,10 +263,6 @@ function buildGraph(config) {
262
263
  }
263
264
  };
264
265
  }
265
- var DEPENDENCY_RELATIONSHIPS = {
266
- "depends-on": "self-requires-target",
267
- "implemented-by": "target-requires-self"
268
- };
269
266
  function collectReferenceEdges(specs) {
270
267
  const edges = [];
271
268
  for (const spec of specs) {
@@ -330,6 +327,112 @@ function createLogger(options) {
330
327
  return createConsola({ level });
331
328
  }
332
329
 
330
+ // ../core/dist/relations.js
331
+ function mapEntriesToIds(config, specsByEntry) {
332
+ const entryIds = /* @__PURE__ */ new Map();
333
+ for (const key of Object.keys(config.specs)) {
334
+ const ids = [];
335
+ for (const spec of specsByEntry.get(key) ?? []) {
336
+ const id = spec.frontmatter.id;
337
+ if (typeof id === "string")
338
+ ids.push(id);
339
+ }
340
+ entryIds.set(key, ids);
341
+ }
342
+ return entryIds;
343
+ }
344
+ function collectKnownIds(specsByEntry) {
345
+ const ids = /* @__PURE__ */ new Set();
346
+ for (const specs of specsByEntry.values()) {
347
+ for (const spec of specs) {
348
+ const id = spec.frontmatter.id;
349
+ if (typeof id === "string")
350
+ ids.add(id);
351
+ }
352
+ }
353
+ return ids;
354
+ }
355
+ function walk(specId, adjacency) {
356
+ const visited = /* @__PURE__ */ new Set();
357
+ const stack = [specId];
358
+ while (stack.length > 0) {
359
+ const current = stack.pop();
360
+ for (const next of adjacency.get(current) ?? []) {
361
+ if (!visited.has(next)) {
362
+ visited.add(next);
363
+ stack.push(next);
364
+ }
365
+ }
366
+ }
367
+ visited.delete(specId);
368
+ return [...visited];
369
+ }
370
+ function buildRelationResolver(config, specsByEntry) {
371
+ const entryIds = config ? mapEntriesToIds(config, specsByEntry) : /* @__PURE__ */ new Map();
372
+ const knownIds = collectKnownIds(specsByEntry);
373
+ const edgeSources = /* @__PURE__ */ new Map();
374
+ const addEdge = (from, to, source) => {
375
+ if (from === to)
376
+ return;
377
+ const key = `${from}\0${to}`;
378
+ const existing = edgeSources.get(key);
379
+ if (!existing) {
380
+ edgeSources.set(key, source);
381
+ } else if (existing !== source) {
382
+ edgeSources.set(key, "both");
383
+ }
384
+ };
385
+ for (const [key, entry] of Object.entries(config?.specs ?? {})) {
386
+ const requires = entry.requires ?? [];
387
+ for (const dep of requires) {
388
+ for (const from of entryIds.get(dep) ?? []) {
389
+ for (const to of entryIds.get(key) ?? []) {
390
+ addEdge(from, to, "requires");
391
+ }
392
+ }
393
+ }
394
+ }
395
+ for (const specs of specsByEntry.values()) {
396
+ for (const spec of specs) {
397
+ const selfId = spec.frontmatter.id;
398
+ if (typeof selfId !== "string")
399
+ continue;
400
+ const refs = spec.frontmatter.references;
401
+ if (!Array.isArray(refs))
402
+ continue;
403
+ for (const ref of refs) {
404
+ if (!ref || typeof ref !== "object")
405
+ continue;
406
+ const { id: targetId, relationship } = ref;
407
+ if (typeof targetId !== "string" || typeof relationship !== "string")
408
+ continue;
409
+ if (!knownIds.has(targetId))
410
+ continue;
411
+ const direction = DEPENDENCY_RELATIONSHIPS[relationship];
412
+ if (direction === "self-requires-target") {
413
+ addEdge(targetId, selfId, "references");
414
+ } else if (direction === "target-requires-self") {
415
+ addEdge(selfId, targetId, "references");
416
+ }
417
+ }
418
+ }
419
+ }
420
+ const edges = [];
421
+ const downstreamAdj = /* @__PURE__ */ new Map();
422
+ const upstreamAdj = /* @__PURE__ */ new Map();
423
+ for (const [key, source] of edgeSources) {
424
+ const [from, to] = key.split("\0");
425
+ edges.push({ from, to, source });
426
+ downstreamAdj.set(from, [...downstreamAdj.get(from) ?? [], to]);
427
+ upstreamAdj.set(to, [...upstreamAdj.get(to) ?? [], from]);
428
+ }
429
+ return {
430
+ edges,
431
+ getUpstream: (specId) => walk(specId, upstreamAdj),
432
+ getDownstream: (specId) => walk(specId, downstreamAdj)
433
+ };
434
+ }
435
+
333
436
  // ../core/dist/preset.js
334
437
  import { readFile as readFile3 } from "fs/promises";
335
438
  import { resolve, isAbsolute as isAbsolute2 } from "path";
@@ -344,7 +447,8 @@ export {
344
447
  buildGraph,
345
448
  collectReferenceEdges,
346
449
  findUnreflectedReferences,
450
+ buildRelationResolver,
347
451
  resolveGlob,
348
452
  createLogger
349
453
  };
350
- //# sourceMappingURL=chunk-IHTYAW7C.js.map
454
+ //# sourceMappingURL=chunk-SNQNQ2MP.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../core/src/config.ts","../../core/src/parser.ts","../../core/src/tokens.ts","../../core/src/graph.ts","../../core/src/glob.ts","../../core/src/logger.ts","../../core/src/relations.ts","../../core/src/preset.ts"],"sourcesContent":["import { readFile } from \"node:fs/promises\";\nimport { join, dirname } from \"node:path\";\nimport { parse as parseYaml } from \"yaml\";\nimport { validateConfig, type SdxConfig } from \"@specdx/schema\";\n\nexport class ConfigError extends Error {\n constructor(\n message: string,\n public readonly errors?: unknown[],\n ) {\n super(message);\n this.name = \"ConfigError\";\n }\n}\n\nconst CONFIG_FILENAME = \"spec.config.yaml\";\n\nexport async function loadConfig(filePath?: string, searchFrom?: string): Promise<SdxConfig> {\n const resolvedPath = filePath ?? (await findConfig(searchFrom ?? process.cwd()));\n if (!resolvedPath) {\n throw new ConfigError(`No ${CONFIG_FILENAME} found. Run 'specdx init' to create one.`);\n }\n\n let raw: string;\n try {\n raw = await readFile(resolvedPath, \"utf-8\");\n } catch {\n throw new ConfigError(`Cannot read config file: ${resolvedPath}`);\n }\n\n let data: Record<string, unknown>;\n try {\n data = parseYaml(raw) as Record<string, unknown>;\n } catch (err) {\n throw new ConfigError(`Invalid YAML in ${resolvedPath}: ${(err as Error).message}`);\n }\n\n const result = validateConfig(data);\n if (!result.valid) {\n throw new ConfigError(`Invalid config in ${resolvedPath}`, result.errors ?? undefined);\n }\n\n return data as unknown as SdxConfig;\n}\n\nasync function findConfig(from: string): Promise<string | undefined> {\n let dir = from;\n while (true) {\n const candidate = join(dir, CONFIG_FILENAME);\n try {\n await readFile(candidate, \"utf-8\");\n return candidate;\n } catch {\n const parent = dirname(dir);\n if (parent === dir) return undefined;\n dir = parent;\n }\n }\n}\n","import { readFile } from \"node:fs/promises\";\nimport { extname } from \"node:path\";\nimport * as grayMatterNs from \"gray-matter\";\nimport { parse as parseYaml } from \"yaml\";\nimport { unified } from \"unified\";\nimport remarkParse from \"remark-parse\";\nimport { visit } from \"unist-util-visit\";\nimport { validateSpec, type ValidationResult } from \"@specdx/schema\";\nimport type { BaseSpec, SpecType } from \"@specdx/schema\";\nimport { countTokens } from \"./tokens.js\";\n\n// gray-matter is CJS — its callable default is exposed via .default in an ESM context\ntype GrayMatterFn = (input: string) => { data: Record<string, unknown>; content: string };\nconst matter = ((grayMatterNs as unknown as { default?: GrayMatterFn }).default ??\n (grayMatterNs as unknown as GrayMatterFn)) as GrayMatterFn;\n\nexport class ParseError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"ParseError\";\n }\n}\n\nexport interface ParsedSection {\n heading: string;\n content: string;\n tokens: number;\n}\n\nexport interface ParsedSpec {\n filePath: string;\n frontmatter: BaseSpec & Record<string, unknown>;\n content: string;\n sections: string[];\n parsedSections: ParsedSection[];\n valid: boolean;\n validationErrors: ValidationResult[\"errors\"];\n}\n\nexport async function parseSpec(filePath: string): Promise<ParsedSpec> {\n let raw: string;\n try {\n raw = await readFile(filePath, \"utf-8\");\n } catch {\n throw new ParseError(`Cannot read spec file: ${filePath}`);\n }\n\n return parseSpecFromString(raw, filePath);\n}\n\nexport function parseSpecFromString(content: string, filePath: string): Promise<ParsedSpec> {\n const ext = extname(filePath).toLowerCase();\n if (ext === \".yaml\" || ext === \".yml\") {\n return Promise.resolve(parseYamlSpec(filePath, content));\n }\n return Promise.resolve(parseMarkdownSpec(filePath, content));\n}\n\nfunction parseMarkdownSpec(filePath: string, raw: string): ParsedSpec {\n const { data, content } = matter(raw);\n const parsedSections = extractParsedSections(content);\n const sections = parsedSections.map((s) => s.heading).filter(Boolean);\n const frontmatter = data as BaseSpec & Record<string, unknown>;\n const specType = frontmatter.type as SpecType | undefined;\n\n let valid = false;\n let validationErrors: ValidationResult[\"errors\"] = null;\n if (specType) {\n const result = validateSpec(specType, data);\n valid = result.valid;\n validationErrors = result.errors;\n }\n\n return { filePath, frontmatter, content, sections, parsedSections, valid, validationErrors };\n}\n\nfunction parseYamlSpec(filePath: string, raw: string): ParsedSpec {\n let data: Record<string, unknown>;\n try {\n data = parseYaml(raw) as Record<string, unknown>;\n } catch (err) {\n throw new ParseError(`Invalid YAML in ${filePath}: ${(err as Error).message}`);\n }\n\n const frontmatter = data as BaseSpec & Record<string, unknown>;\n const specType = frontmatter.type as SpecType | undefined;\n\n let valid = false;\n let validationErrors: ValidationResult[\"errors\"] = null;\n if (specType) {\n const result = validateSpec(specType, data);\n valid = result.valid;\n validationErrors = result.errors;\n }\n\n return {\n filePath,\n frontmatter,\n content: \"\",\n sections: [],\n parsedSections: [],\n valid,\n validationErrors,\n };\n}\n\nfunction extractParsedSections(markdown: string): ParsedSection[] {\n const tree = unified().use(remarkParse).parse(markdown);\n\n const h2s: { heading: string; startOffset: number; endOffset: number }[] = [];\n\n visit(tree, \"heading\", (node) => {\n if (node.depth === 2) {\n const text = (node.children as Array<{ type: string; value?: string }>)\n .filter((c) => c.type === \"text\")\n .map((c) => c.value ?? \"\")\n .join(\"\");\n h2s.push({\n heading: text,\n startOffset: node.position!.start.offset as number,\n endOffset: node.position!.end.offset as number,\n });\n }\n });\n\n const sections: ParsedSection[] = [];\n\n // Preamble: content before first H2\n const firstH2 = h2s[0];\n const firstOffset = firstH2 ? firstH2.startOffset : markdown.length;\n const preamble = markdown.slice(0, firstOffset).trim();\n if (preamble) {\n sections.push({ heading: \"\", content: preamble, tokens: countTokens(preamble) });\n }\n\n // Each H2 section: content AFTER the heading line, up to the next H2 (or end)\n for (let i = 0; i < h2s.length; i++) {\n const current = h2s[i]!;\n const next = h2s[i + 1];\n const end = next ? next.startOffset : markdown.length;\n const content = markdown.slice(current.endOffset, end).trim();\n sections.push({\n heading: current.heading,\n content,\n tokens: countTokens(content),\n });\n }\n\n return sections;\n}\n","import { encodingForModel } from \"js-tiktoken\";\n\nlet encoder: ReturnType<typeof encodingForModel> | undefined;\n\nfunction getEncoder() {\n if (!encoder) encoder = encodingForModel(\"gpt-4o\");\n return encoder;\n}\n\nexport function countTokens(text: string): number {\n if (!text) return 0;\n return getEncoder().encode(text).length;\n}\n","import type { SdxConfig } from \"@specdx/schema\";\nimport { DEPENDENCY_RELATIONSHIPS } from \"@specdx/schema\";\n\nexport class GraphError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"GraphError\";\n }\n}\n\nexport interface Edge {\n from: string;\n to: string;\n}\n\nexport interface DependencyGraph {\n nodes: string[];\n edges: Edge[];\n topologicalSort(): string[];\n getDownstream(nodeId: string): string[];\n getUpstream(nodeId: string): string[];\n}\n\nexport function buildGraph(config: SdxConfig): DependencyGraph {\n const specNames = Object.keys(config.specs);\n const adjacency = new Map<string, string[]>();\n const reverseAdj = new Map<string, string[]>();\n const edges: Edge[] = [];\n\n for (const name of specNames) {\n adjacency.set(name, []);\n reverseAdj.set(name, []);\n }\n\n for (const [name, entry] of Object.entries(config.specs)) {\n if (!entry.requires) continue;\n for (const dep of entry.requires) {\n if (!adjacency.has(dep)) {\n throw new GraphError(\n `Spec \"${name}\" requires \"${dep}\", which does not exist in the config.`,\n );\n }\n adjacency.get(dep)!.push(name);\n reverseAdj.get(name)!.push(dep);\n edges.push({ from: dep, to: name });\n }\n }\n\n // Kahn's algorithm for cycle detection + topological sort\n const inDegree = new Map<string, number>();\n for (const name of specNames) inDegree.set(name, reverseAdj.get(name)!.length);\n\n const queue: string[] = [];\n for (const [name, degree] of inDegree) {\n if (degree === 0) queue.push(name);\n }\n\n const sorted: string[] = [];\n while (queue.length > 0) {\n const node = queue.shift()!;\n sorted.push(node);\n for (const neighbor of adjacency.get(node)!) {\n const newDegree = inDegree.get(neighbor)! - 1;\n inDegree.set(neighbor, newDegree);\n if (newDegree === 0) queue.push(neighbor);\n }\n }\n\n if (sorted.length !== specNames.length) {\n const remaining = specNames.filter((n) => !sorted.includes(n));\n throw new GraphError(`Circular dependency detected involving: ${remaining.join(\", \")}`);\n }\n\n return {\n nodes: specNames,\n edges,\n topologicalSort: () => [...sorted],\n getDownstream(nodeId: string): string[] {\n const visited = new Set<string>();\n const stack = [nodeId];\n while (stack.length > 0) {\n const current = stack.pop()!;\n for (const neighbor of adjacency.get(current) ?? []) {\n if (!visited.has(neighbor)) {\n visited.add(neighbor);\n stack.push(neighbor);\n }\n }\n }\n return [...visited];\n },\n getUpstream(nodeId: string): string[] {\n const visited = new Set<string>();\n const stack = [nodeId];\n while (stack.length > 0) {\n const current = stack.pop()!;\n for (const dep of reverseAdj.get(current) ?? []) {\n if (!visited.has(dep)) {\n visited.add(dep);\n stack.push(dep);\n }\n }\n }\n return [...visited];\n },\n };\n}\n\n/** A relationship edge declared in a spec's frontmatter `references`. */\nexport interface ReferenceEdge {\n fromId: string;\n toId: string;\n relationship: string;\n}\n\n// The dependency-implying taxonomy lives in @specdx/schema so it is versioned\n// with the schema it describes, rather than hardcoded here (ADR:\n// references/requires unification).\n\n/**\n * Collect relationship edges declared in spec frontmatter `references` fields.\n * Edges point from the declaring spec's id to the referenced spec's id.\n */\nexport function collectReferenceEdges(\n specs: { frontmatter: Record<string, unknown> }[],\n): ReferenceEdge[] {\n const edges: ReferenceEdge[] = [];\n for (const spec of specs) {\n const fromId = spec.frontmatter.id;\n if (typeof fromId !== \"string\") continue;\n const refs = spec.frontmatter.references;\n if (!Array.isArray(refs)) continue;\n for (const ref of refs) {\n if (ref && typeof ref === \"object\" && \"id\" in ref) {\n const r = ref as { id: unknown; relationship?: unknown };\n if (typeof r.id === \"string\") {\n edges.push({\n fromId,\n toId: r.id,\n relationship: typeof r.relationship === \"string\" ? r.relationship : \"related-to\",\n });\n }\n }\n }\n }\n return edges;\n}\n\n/**\n * Find dependency-implying frontmatter references that the config-level\n * `requires` graph does not reflect. `idToEntry` maps spec frontmatter ids to\n * config entry keys. References within the same entry (e.g. story-to-story\n * under one glob) and references to unmapped ids are skipped — reference\n * existence itself is the `structure/valid-references` lint rule's concern.\n */\nexport interface UnreflectedReference {\n edge: ReferenceEdge;\n requiringEntry: string;\n requiredEntry: string;\n /** True when adding the suggested requires edge would create a cycle. */\n createsCycle: boolean;\n}\n\nexport function findUnreflectedReferences(\n referenceEdges: ReferenceEdge[],\n idToEntry: Map<string, string>,\n graph: DependencyGraph,\n): UnreflectedReference[] {\n const configEdges = new Set(graph.edges.map((e) => `${e.from}→${e.to}`));\n const missing: UnreflectedReference[] = [];\n\n for (const edge of referenceEdges) {\n const direction = DEPENDENCY_RELATIONSHIPS[edge.relationship as never];\n if (!direction) continue;\n\n const selfEntry = idToEntry.get(edge.fromId);\n const targetEntry = idToEntry.get(edge.toId);\n if (!selfEntry || !targetEntry || selfEntry === targetEntry) continue;\n\n const requiringEntry = direction === \"self-requires-target\" ? selfEntry : targetEntry;\n const requiredEntry = direction === \"self-requires-target\" ? targetEntry : selfEntry;\n\n // Config edges point dependency → dependent\n if (!configEdges.has(`${requiredEntry}→${requiringEntry}`)) {\n // The suggested edge closes a cycle when the required entry is already\n // downstream of the requiring one (issue #13) — never recommend it.\n const createsCycle = graph.getDownstream(requiringEntry).includes(requiredEntry);\n missing.push({ edge, requiringEntry, requiredEntry, createsCycle });\n }\n }\n\n return missing;\n}\n","import { glob } from \"tinyglobby\";\nimport { join, isAbsolute } from \"node:path\";\n\nexport async function resolveGlob(pattern: string, baseDir: string): Promise<string[]> {\n const absolutePattern = isAbsolute(pattern) ? pattern : join(baseDir, pattern);\n return glob([absolutePattern], { absolute: true });\n}\n","import { createConsola, type ConsolaInstance } from \"consola\";\n\nexport type LogLevel = \"debug\" | \"info\" | \"warn\" | \"error\";\n\nexport interface LoggerOptions {\n quiet?: boolean;\n verbose?: boolean;\n}\n\nexport interface Logger extends ConsolaInstance {\n level: number;\n}\n\nexport function createLogger(options?: LoggerOptions): Logger {\n let level = 3; // info\n if (options?.quiet) level = 1; // only errors\n if (options?.verbose) level = 4; // debug\n return createConsola({ level }) as Logger;\n}\n","import type { SdxConfig } from \"@specdx/schema\";\nimport { DEPENDENCY_RELATIONSHIPS } from \"@specdx/schema\";\n\n/** Where a relation edge was declared. */\nexport type RelationSource = \"requires\" | \"references\" | \"both\";\n\n/** A dependency edge in **spec id** space, pointing upstream → downstream. */\nexport interface RelationEdge {\n /** Spec id of the dependency. */\n from: string;\n /** Spec id of the dependent. */\n to: string;\n /** Which declaration(s) produced this edge. */\n source: RelationSource;\n}\n\n/**\n * Answers \"what is upstream / downstream of this spec?\" in spec id space.\n *\n * specdx declares relationships two ways: config `requires` (keyed by config\n * entry, glob-aware, cheap) and frontmatter `references` (keyed by spec id,\n * typed). Consumers used to read one or the other, so the same question got\n * different answers — `freshness/staleness-check` saw only references, while\n * impact analysis saw only the config graph. This resolver unions both at\n * query time so every consumer agrees, without changing which source owns\n * graph topology (ADR: references/requires unification, Option B).\n */\nexport interface RelationResolver {\n /** All dependency edges, in spec id space, deduplicated. */\n edges: RelationEdge[];\n /** Spec ids this spec depends on, transitively. */\n getUpstream(specId: string): string[];\n /** Spec ids that depend on this spec, transitively. */\n getDownstream(specId: string): string[];\n}\n\ninterface SpecLike {\n frontmatter: Record<string, unknown>;\n}\n\n/** Map each config entry key to the spec ids its path resolved to. */\nfunction mapEntriesToIds(\n config: SdxConfig,\n specsByEntry: Map<string, SpecLike[]>,\n): Map<string, string[]> {\n const entryIds = new Map<string, string[]>();\n for (const key of Object.keys(config.specs)) {\n const ids: string[] = [];\n for (const spec of specsByEntry.get(key) ?? []) {\n const id = spec.frontmatter.id;\n if (typeof id === \"string\") ids.push(id);\n }\n entryIds.set(key, ids);\n }\n return entryIds;\n}\n\n/** Every spec id present, regardless of which entry it came from. */\nfunction collectKnownIds(specsByEntry: Map<string, SpecLike[]>): Set<string> {\n const ids = new Set<string>();\n for (const specs of specsByEntry.values()) {\n for (const spec of specs) {\n const id = spec.frontmatter.id;\n if (typeof id === \"string\") ids.add(id);\n }\n }\n return ids;\n}\n\nfunction walk(specId: string, adjacency: Map<string, string[]>): string[] {\n const visited = new Set<string>();\n const stack = [specId];\n while (stack.length > 0) {\n const current = stack.pop()!;\n for (const next of adjacency.get(current) ?? []) {\n if (!visited.has(next)) {\n visited.add(next);\n stack.push(next);\n }\n }\n }\n visited.delete(specId);\n return [...visited];\n}\n\n/**\n * Build a resolver from config `requires` and dependency-implying frontmatter\n * `references`.\n *\n * A glob entry is one config entry but many spec ids, so one `requires` edge\n * between entries expands to the cross-product of their spec ids. Structural\n * reference kinds (`decomposed-into`, `supersedes`, `related-to`) are not\n * dependency-implying and are excluded — see DEPENDENCY_RELATIONSHIPS.\n *\n * @param config - Spec config. When undefined, only frontmatter references\n * contribute edges — useful for callers that have specs but no config.\n * @param specsByEntry - Parsed specs grouped by the config entry key they resolved from.\n */\nexport function buildRelationResolver(\n config: SdxConfig | undefined,\n specsByEntry: Map<string, SpecLike[]>,\n): RelationResolver {\n const entryIds = config ? mapEntriesToIds(config, specsByEntry) : new Map<string, string[]>();\n const knownIds = collectKnownIds(specsByEntry);\n\n // key \"from→to\" -> source, so a relation declared both ways is one edge\n const edgeSources = new Map<string, RelationSource>();\n const addEdge = (from: string, to: string, source: \"requires\" | \"references\"): void => {\n if (from === to) return;\n const key = `${from}\u0000${to}`;\n const existing = edgeSources.get(key);\n if (!existing) {\n edgeSources.set(key, source);\n } else if (existing !== source) {\n edgeSources.set(key, \"both\");\n }\n };\n\n // 1. Config requires: entry-level edges expand across the entries' spec ids\n for (const [key, entry] of Object.entries(config?.specs ?? {})) {\n const requires = (entry as { requires?: string[] }).requires ?? [];\n for (const dep of requires) {\n for (const from of entryIds.get(dep) ?? []) {\n for (const to of entryIds.get(key) ?? []) {\n addEdge(from, to, \"requires\");\n }\n }\n }\n }\n\n // 2. Frontmatter references, already in spec id space\n for (const specs of specsByEntry.values()) {\n for (const spec of specs) {\n const selfId = spec.frontmatter.id;\n if (typeof selfId !== \"string\") continue;\n const refs = spec.frontmatter.references;\n if (!Array.isArray(refs)) continue;\n\n for (const ref of refs) {\n if (!ref || typeof ref !== \"object\") continue;\n const { id: targetId, relationship } = ref as { id?: unknown; relationship?: unknown };\n if (typeof targetId !== \"string\" || typeof relationship !== \"string\") continue;\n // Referencing a spec outside the suite is valid-references' concern.\n if (!knownIds.has(targetId)) continue;\n\n const direction = DEPENDENCY_RELATIONSHIPS[relationship as never];\n if (direction === \"self-requires-target\") {\n addEdge(targetId, selfId, \"references\");\n } else if (direction === \"target-requires-self\") {\n addEdge(selfId, targetId, \"references\");\n }\n }\n }\n }\n\n const edges: RelationEdge[] = [];\n const downstreamAdj = new Map<string, string[]>();\n const upstreamAdj = new Map<string, string[]>();\n\n for (const [key, source] of edgeSources) {\n const [from, to] = key.split(\"\u0000\") as [string, string];\n edges.push({ from, to, source });\n downstreamAdj.set(from, [...(downstreamAdj.get(from) ?? []), to]);\n upstreamAdj.set(to, [...(upstreamAdj.get(to) ?? []), from]);\n }\n\n return {\n edges,\n getUpstream: (specId) => walk(specId, upstreamAdj),\n getDownstream: (specId) => walk(specId, downstreamAdj),\n };\n}\n","import { readFile } from \"node:fs/promises\";\nimport { resolve, isAbsolute } from \"node:path\";\nimport { ConfigError } from \"./config.js\";\n\nconst BUILTINS = [\"minimal\", \"recommended\", \"strict\"];\n\n/**\n * Resolve a preset name to its config content.\n * Returns null for built-in presets (handled by @specdx/lint).\n * Resolves local file paths and npm package names.\n */\nexport async function resolvePreset(\n name: string,\n cwd = process.cwd(),\n): Promise<Record<string, unknown> | null> {\n if (BUILTINS.includes(name)) {\n return null;\n }\n\n // Try local file path\n const localPath = isAbsolute(name) ? name : resolve(cwd, name);\n try {\n const content = await readFile(localPath, \"utf-8\");\n const { default: yaml } = await import(\"yaml\");\n return yaml.parse(content) as Record<string, unknown>;\n } catch {\n // Not a local file, try npm\n }\n\n // Try npm package\n try {\n const mod = (await import(name)) as { default?: Record<string, unknown> };\n return (mod.default ?? mod) as Record<string, unknown>;\n } catch {\n throw new ConfigError(`Could not resolve preset \"${name}\" as a local file or npm package`);\n }\n}\n"],"mappings":";;;;;;;AAAA,SAAS,gBAAgB;AACzB,SAAS,MAAM,eAAe;AAC9B,SAAS,SAAS,iBAAiB;AAG7B,IAAO,cAAP,cAA2B,MAAK;EAGlB;EAFlB,YACE,SACgB,QAAkB;AAElC,UAAM,OAAO;AAFG,SAAA,SAAA;AAGhB,SAAK,OAAO;EACd;;AAGF,IAAM,kBAAkB;AAExB,eAAsB,WAAW,UAAmB,YAAmB;AACrE,QAAM,eAAe,YAAa,MAAM,WAAW,cAAc,QAAQ,IAAG,CAAE;AAC9E,MAAI,CAAC,cAAc;AACjB,UAAM,IAAI,YAAY,MAAM,eAAe,0CAA0C;EACvF;AAEA,MAAI;AACJ,MAAI;AACF,UAAM,MAAM,SAAS,cAAc,OAAO;EAC5C,QAAQ;AACN,UAAM,IAAI,YAAY,4BAA4B,YAAY,EAAE;EAClE;AAEA,MAAI;AACJ,MAAI;AACF,WAAO,UAAU,GAAG;EACtB,SAAS,KAAK;AACZ,UAAM,IAAI,YAAY,mBAAmB,YAAY,KAAM,IAAc,OAAO,EAAE;EACpF;AAEA,QAAM,SAAS,eAAe,IAAI;AAClC,MAAI,CAAC,OAAO,OAAO;AACjB,UAAM,IAAI,YAAY,qBAAqB,YAAY,IAAI,OAAO,UAAU,MAAS;EACvF;AAEA,SAAO;AACT;AAEA,eAAe,WAAW,MAAY;AACpC,MAAI,MAAM;AACV,SAAO,MAAM;AACX,UAAM,YAAY,KAAK,KAAK,eAAe;AAC3C,QAAI;AACF,YAAM,SAAS,WAAW,OAAO;AACjC,aAAO;IACT,QAAQ;AACN,YAAM,SAAS,QAAQ,GAAG;AAC1B,UAAI,WAAW;AAAK,eAAO;AAC3B,YAAM;IACR;EACF;AACF;;;AC1DA,SAAS,YAAAA,iBAAgB;AACzB,SAAS,eAAe;A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yB,YAAqB;AAChE,YAAI,cAAc,wBAAwB;AACxC,kBAAQ,UAAU,QAAQ,YAAY;QACxC,WAAW,cAAc,wBAAwB;AAC/C,kBAAQ,QAAQ,UAAU,YAAY;QACxC;MACF;IACF;EACF;AAEA,QAAM,QAAwB,CAAA;AAC9B,QAAM,gBAAgB,oBAAI,IAAG;AAC7B,QAAM,cAAc,oBAAI,IAAG;AAE3B,aAAW,CAAC,KAAK,MAAM,KAAK,aAAa;AACvC,UAAM,CAAC,MAAM,EAAE,IAAI,IAAI,MAAM,IAAG;AAChC,UAAM,KAAK,EAAE,MAAM,IAAI,OAAM,CAAE;AAC/B,kBAAc,IAAI,MAAM,CAAC,GAAI,cAAc,IAAI,IAAI,KAAK,CAAA,GAAK,EAAE,CAAC;AAChE,gBAAY,IAAI,IAAI,CAAC,GAAI,YAAY,IAAI,EAAE,KAAK,CAAA,GAAK,IAAI,CAAC;EAC5D;AAEA,SAAO;IACL;IACA,aAAa,CAAC,WAAW,KAAK,QAAQ,WAAW;IACjD,eAAe,CAAC,WAAW,KAAK,QAAQ,aAAa;;AAEzD;;;AC3KA,SAAS,YAAAC,iBAAgB;AACzB,SAAS,SAAS,cAAAC,mBAAkB;","names":["readFile","parseYaml","readFile","parseYaml","join","readFile","isAbsolute"]}
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  countTokens
3
- } from "./chunk-IHTYAW7C.js";
3
+ } from "./chunk-SNQNQ2MP.js";
4
4
 
5
5
  // ../pack/dist/resolver.js
6
6
  var STOPWORDS = /* @__PURE__ */ new Set([
@@ -360,12 +360,18 @@ function allocate(specs, scores, options) {
360
360
  for (const spec of specs) {
361
361
  specMap.set(spec.frontmatter.id, spec);
362
362
  }
363
+ function tokensOf(compressed) {
364
+ if (compressed.collapsed)
365
+ return countTokens(compressed.collapsedSummary ?? "");
366
+ return compressed.sections.reduce((sum, section) => sum + section.tokens, 0);
367
+ }
363
368
  const items = [];
364
369
  for (const score of scores) {
365
370
  const spec = specMap.get(score.specId);
366
371
  if (!spec)
367
372
  continue;
368
373
  let compressed;
374
+ let stale;
369
375
  if (options.full) {
370
376
  compressed = {
371
377
  specId: score.specId,
@@ -381,20 +387,34 @@ function allocate(specs, scores, options) {
381
387
  collapsed: false
382
388
  };
383
389
  } else {
384
- compressed = compressSpec(score.specId, String(spec.frontmatter.type), String(spec.frontmatter.title), spec.frontmatter.status, spec.frontmatter.updated, spec.parsedSections, options.compression);
385
- }
386
- let tokens;
387
- if (compressed.collapsed) {
388
- tokens = countTokens(compressed.collapsedSummary ?? "");
389
- } else {
390
- tokens = 0;
391
- for (const section of compressed.sections) {
392
- tokens += section.tokens;
390
+ const compress = (compression) => compressSpec(score.specId, String(spec.frontmatter.type), String(spec.frontmatter.title), spec.frontmatter.status, spec.frontmatter.updated, spec.parsedSections, compression);
391
+ compressed = compress({ ...options.compression, stableDays: 0 });
392
+ if (options.compression.stableDays > 0) {
393
+ const collapsed = compress(options.compression);
394
+ const collapsedTokens = tokensOf(collapsed);
395
+ if (collapsedTokens < tokensOf(compressed)) {
396
+ stale = { spec: collapsed, tokens: collapsedTokens };
397
+ }
393
398
  }
394
399
  }
395
- items.push({ compressed, relevance: score.score, tokens, idMatched: score.idMatched ?? false });
400
+ items.push({
401
+ compressed,
402
+ relevance: score.score,
403
+ tokens: tokensOf(compressed),
404
+ idMatched: score.idMatched ?? false,
405
+ stale
406
+ });
396
407
  }
397
408
  items.sort((a, b) => b.relevance - a.relevance || Number(b.idMatched) - Number(a.idMatched));
409
+ let projected = items.reduce((sum, item) => sum + item.tokens, 0);
410
+ for (let i = items.length - 1; i >= 0 && projected > options.budget; i--) {
411
+ const item = items[i];
412
+ if (!item.stale)
413
+ continue;
414
+ projected -= item.tokens - item.stale.tokens;
415
+ item.compressed = item.stale.spec;
416
+ item.tokens = item.stale.tokens;
417
+ }
398
418
  const totalTokens = items.reduce((sum, item) => sum + item.tokens, 0);
399
419
  const withinBudget = totalTokens <= options.budget;
400
420
  const included = [];
@@ -664,4 +684,4 @@ function pack(specs, options, packConfig, graph) {
664
684
  export {
665
685
  pack
666
686
  };
667
- //# sourceMappingURL=chunk-AKNPCB37.js.map
687
+ //# sourceMappingURL=chunk-YRQPY5NF.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../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 type { ParsedSpec, DependencyGraph } from \"@specdx/core\";\nimport type { RelevanceScore } from \"./types.js\";\n\n/**\n * Common English stopwords to filter from task tokenization.\n */\nconst STOPWORDS = new Set([\n \"a\",\n \"an\",\n \"and\",\n \"are\",\n \"as\",\n \"at\",\n \"be\",\n \"but\",\n \"by\",\n \"do\",\n \"for\",\n \"from\",\n \"had\",\n \"has\",\n \"have\",\n \"he\",\n \"her\",\n \"his\",\n \"how\",\n \"i\",\n \"if\",\n \"in\",\n \"into\",\n \"is\",\n \"it\",\n \"its\",\n \"just\",\n \"me\",\n \"my\",\n \"no\",\n \"nor\",\n \"not\",\n \"of\",\n \"on\",\n \"or\",\n \"our\",\n \"out\",\n \"own\",\n \"say\",\n \"she\",\n \"so\",\n \"some\",\n \"such\",\n \"than\",\n \"that\",\n \"the\",\n \"their\",\n \"them\",\n \"then\",\n \"there\",\n \"these\",\n \"they\",\n \"this\",\n \"to\",\n \"too\",\n \"up\",\n \"us\",\n \"very\",\n \"was\",\n \"we\",\n \"were\",\n \"what\",\n \"when\",\n \"where\",\n \"which\",\n \"while\",\n \"who\",\n \"whom\",\n \"why\",\n \"will\",\n \"with\",\n \"would\",\n \"you\",\n \"your\",\n]);\n\n/** Tokenize a task string into lowercase keywords, dropping stopwords and short tokens. */\nfunction tokenize(task: string): string[] {\n return task\n .split(/[\\s\\-_/.,;:!?()[\\]{}'\"]+/)\n .map((t) => t.toLowerCase())\n .filter((t) => t.length > 1 && !STOPWORDS.has(t));\n}\n\n/** Field weights for keyword matching. */\nconst WEIGHT_TAGS = 3;\nconst WEIGHT_TITLE = 3;\nconst WEIGHT_SECTIONS = 2;\nconst WEIGHT_BODY = 1;\n\n/** Minimum id length considered for verbatim matching (avoids ids like \"a\"). */\nconst ID_MATCH_MIN_LENGTH = 3;\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 const idMatchedSet = new Set<string>();\n const taskLower = (task ?? \"\").toLowerCase();\n\n for (const [specId, spec] of specs) {\n let weightedHits = 0;\n const matched = new Set<string>();\n\n // Verbatim id match: a task that names a spec dominates keyword scoring\n const idLower = specId.toLowerCase();\n if (idLower.length >= ID_MATCH_MIN_LENGTH && taskLower.includes(idLower)) {\n idMatchedSet.add(specId);\n }\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. A spec the task names verbatim is\n // clamped to 1.0 — an explicit mention always outranks keyword inference —\n // without distorting the normalization of the other specs' scores.\n const results: RelevanceScore[] = [];\n for (const [specId] of specs) {\n const combined = finalRawScores.get(specId) ?? 0;\n const idMatched = idMatchedSet.has(specId);\n const normalized = idMatched ? 1.0 : 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 idMatched,\n });\n }\n\n // Sort descending by score; ties prefer specs the task named explicitly\n results.sort(\n (a, b) => b.score - a.score || Number(b.idMatched ?? false) - Number(a.idMatched ?? false),\n );\n\n return results;\n}\n\n/**\n * Score specs by explicit IDs. Named specs get 1.0, their transitive\n * upstream dependencies get 0.5.\n *\n * Throws if any specId is not found in the specs map.\n */\nexport function scoreSpecsByIds(\n specs: Map<string, ParsedSpec>,\n specIds: string[],\n graph: DependencyGraph,\n): RelevanceScore[] {\n // Validate all IDs exist\n for (const id of specIds) {\n if (!specs.has(id)) {\n const available = [...specs.keys()].join(\", \");\n throw new Error(`Unknown spec: \"${id}\". Available specs: ${available}`);\n }\n }\n\n const scoreMap = new Map<string, number>();\n\n // Named specs get 1.0\n for (const id of specIds) {\n scoreMap.set(id, 1.0);\n }\n\n // Upstream deps get 0.5 (unless already named at 1.0)\n for (const id of specIds) {\n const upstream = graph.getUpstream(id);\n for (const depId of upstream) {\n if (!scoreMap.has(depId) && specs.has(depId)) {\n scoreMap.set(depId, 0.5);\n }\n }\n }\n\n const results: RelevanceScore[] = [];\n for (const [specId, score] of scoreMap) {\n results.push({\n specId,\n score,\n rawScore: score,\n matchedKeywords: [],\n graphBoosted: score < 1.0,\n });\n }\n\n // Sort descending by score\n results.sort((a, b) => b.score - a.score);\n\n return results;\n}\n","import { countTokens } from \"@specdx/core\";\nimport type { ParsedSection } from \"@specdx/core\";\nimport type { CompressedSpec, CompressedSection, CompressionOptions } from \"./types.js\";\n\n/**\n * Returns true when `dateStr` is more than `days` days before now.\n * Returns false for invalid / missing dates (treat as fresh).\n */\nfunction isOlderThanDays(dateStr: string | undefined, days: number): boolean {\n if (!dateStr) return false;\n const ms = Date.parse(dateStr);\n if (Number.isNaN(ms)) return false;\n const diffMs = Date.now() - ms;\n return diffMs > days * 24 * 60 * 60 * 1000;\n}\n\n/**\n * Compress a single spec according to the provided options.\n */\nexport function compressSpec(\n specId: string,\n type: string,\n title: string,\n status: string | undefined,\n updatedDate: string | undefined,\n parsedSections: ParsedSection[],\n options: CompressionOptions,\n): CompressedSpec {\n // 1. Collapse superseded ADRs\n if (type === \"adr\" && status === \"superseded\" && options.collapseResolvedAdrs) {\n return {\n specId,\n type,\n title,\n sections: [],\n collapsed: true,\n collapsedSummary: `[ADR] ${title} — superseded`,\n };\n }\n\n // 2. Determine staleness\n const stale = options.stableDays > 0 && isOlderThanDays(updatedDate, options.stableDays);\n\n // 3. Process sections\n const boilerplateSet = new Set(options.boilerplateSections.map((s) => s.toLowerCase()));\n\n const sections: CompressedSection[] = [];\n\n for (const section of parsedSections) {\n // 3a. Strip boilerplate\n if (\n options.stripBoilerplate &&\n section.heading &&\n boilerplateSet.has(section.heading.toLowerCase())\n ) {\n continue;\n }\n\n // 3b. Collapse stale headed sections (preserve preamble)\n if (stale && section.heading) {\n const stub = `[Unchanged since ${updatedDate} — ${section.tokens} tokens omitted]`;\n sections.push({\n heading: section.heading,\n content: stub,\n tokens: countTokens(stub),\n compressed: true,\n originalTokens: section.tokens,\n });\n continue;\n }\n\n // 3c. Pass through unchanged\n sections.push({\n heading: section.heading,\n content: section.content,\n tokens: section.tokens,\n compressed: false,\n originalTokens: section.tokens,\n });\n }\n\n return {\n specId,\n type,\n title,\n sections,\n collapsed: false,\n };\n}\n","import { countTokens } from \"@specdx/core\";\nimport type { ParsedSpec } from \"@specdx/core\";\nimport { compressSpec } from \"./compressor.js\";\nimport type {\n CompressedSpec,\n CompressionOptions,\n PackStats,\n RelevanceScore,\n SpecAllocation,\n} from \"./types.js\";\n\n/** Options for the token allocator. */\nexport interface AllocatorOptions {\n /** Maximum token budget. */\n budget: number;\n /** When true, include full spec content without compression. */\n full: boolean;\n /** Compression settings (used when `full` is false). */\n compression: CompressionOptions;\n}\n\n/** Result of the allocation pass. */\nexport interface AllocationResult {\n /** Compressed specs that fit within the budget. */\n specs: CompressedSpec[];\n /** Statistics about how the budget was spent. */\n stats: PackStats;\n}\n\n/** Relevance at or above which a spec is trimmed to fit rather than excluded. */\nconst HIGH_RELEVANCE = 0.75;\n\n/** Minimum remaining budget worth trimming into. */\nconst MIN_TRIM_BUDGET = 150;\n\n/** Build the marker text for a contiguous run of omitted sections. */\nfunction omissionMarker(sections: CompressedSpec[\"sections\"]): string {\n const names = sections.map((s) => s.heading || \"(untitled)\");\n const noun = names.length === 1 ? \"section\" : \"sections\";\n return `[${names.length} ${noun} omitted to fit token budget: ${names.join(\", \")}]`;\n}\n\n/**\n * Produce a variant of `compressed` that fits within `budget` by keeping\n * sections in order while they fit and replacing each contiguous run of\n * omitted sections with an explicit marker naming them. Marker cost is\n * reserved out of the budget before sections are kept, so markers are always\n * emitted — a trimmed spec must never read as complete (issue #12).\n * Returns null when not even one real section fits.\n */\nfunction trimToBudget(\n compressed: CompressedSpec,\n budget: number,\n): { spec: CompressedSpec; tokens: number } | null {\n const sections = compressed.sections;\n let reserve = 0;\n\n // The kept set only shrinks as the reserve grows, so this converges.\n for (;;) {\n const effective = budget - reserve;\n const keep: boolean[] = new Array(sections.length).fill(false);\n let used = 0;\n let keptReal = false;\n\n for (let i = 0; i < sections.length; i++) {\n if (used + sections[i]!.tokens <= effective) {\n keep[i] = true;\n used += sections[i]!.tokens;\n keptReal = true;\n }\n }\n\n if (!keptReal) return null;\n\n // Group omitted sections into contiguous runs and price their markers.\n interface OmittedRun {\n start: number;\n sections: CompressedSpec[\"sections\"];\n marker: string;\n markerTokens: number;\n }\n const runs: OmittedRun[] = [];\n for (let i = 0; i < sections.length; i++) {\n if (keep[i]) continue;\n const start = i;\n const run: CompressedSpec[\"sections\"] = [];\n while (i < sections.length && !keep[i]) {\n run.push(sections[i]!);\n i++;\n }\n i--;\n const marker = omissionMarker(run);\n runs.push({ start, sections: run, marker, markerTokens: countTokens(marker) });\n }\n\n const markerTokens = runs.reduce((sum, r) => sum + r.markerTokens, 0);\n if (markerTokens > reserve) {\n reserve = markerTokens;\n continue;\n }\n\n // Assemble output: kept sections in order, markers at each cut.\n const out: CompressedSpec[\"sections\"] = [];\n for (let i = 0; i < sections.length; i++) {\n const run = runs.find((r) => r.start === i);\n if (run) {\n out.push({\n heading: \"\",\n content: run.marker,\n tokens: run.markerTokens,\n compressed: true,\n originalTokens: run.sections.reduce((sum, s) => sum + s.tokens, 0),\n omittedSections: run.sections.length,\n });\n i += run.sections.length - 1;\n continue;\n }\n out.push(sections[i]!);\n }\n\n return { spec: { ...compressed, sections: out }, tokens: used + markerTokens };\n }\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 idMatched: boolean;\n /**\n * Staleness-collapsed variant, spent only under budget pressure (issue #33).\n * Undefined when there is nothing to collapse, or in full mode.\n */\n stale?: { spec: CompressedSpec; tokens: number };\n }\n\n function tokensOf(compressed: CompressedSpec): number {\n if (compressed.collapsed) return countTokens(compressed.collapsedSummary ?? \"\");\n return compressed.sections.reduce((sum, section) => sum + section.tokens, 0);\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 let stale: ScoredCompressed[\"stale\"];\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 const compress = (compression: CompressionOptions): CompressedSpec =>\n 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 compression,\n );\n\n // Boilerplate stripping and superseded-ADR collapse are hygiene, not\n // budget management -- they apply either way. Only the staleness collapse\n // is held back until the budget actually needs it.\n compressed = compress({ ...options.compression, stableDays: 0 });\n\n if (options.compression.stableDays > 0) {\n const collapsed = compress(options.compression);\n const collapsedTokens = tokensOf(collapsed);\n if (collapsedTokens < tokensOf(compressed)) {\n stale = { spec: collapsed, tokens: collapsedTokens };\n }\n }\n }\n\n items.push({\n compressed,\n relevance: score.score,\n tokens: tokensOf(compressed),\n idMatched: score.idMatched ?? false,\n stale,\n });\n }\n\n // 4. Sort by relevance descending; ties prefer specs the task named explicitly\n items.sort((a, b) => b.relevance - a.relevance || Number(b.idMatched) - Number(a.idMatched));\n\n // 4b. Collapse stale specs only while the budget is short, least relevant\n // first. Compression is a response to pressure: applied without it, the\n // caller asked for context and got stubs against a barely-touched budget.\n let projected = items.reduce((sum, item) => sum + item.tokens, 0);\n for (let i = items.length - 1; i >= 0 && projected > options.budget; i--) {\n const item = items[i]!;\n if (!item.stale) continue;\n projected -= item.tokens - item.stale.tokens;\n item.compressed = item.stale.spec;\n item.tokens = item.stale.tokens;\n }\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. High-relevance specs\n // that don't fit are trimmed into the remaining budget before being\n // excluded — a task-named spec should never silently drop out.\n for (const item of items) {\n if (usedTokens + item.tokens <= options.budget) {\n included.push(item);\n usedTokens += item.tokens;\n continue;\n }\n const remaining = options.budget - usedTokens;\n if (\n (item.idMatched || item.relevance >= HIGH_RELEVANCE) &&\n remaining >= MIN_TRIM_BUDGET &&\n !item.compressed.collapsed\n ) {\n const trimmed = trimToBudget(item.compressed, remaining);\n if (trimmed) {\n included.push({ ...item, compressed: trimmed.spec, tokens: trimmed.tokens });\n usedTokens += trimmed.tokens;\n continue;\n }\n }\n excluded.push(item);\n }\n }\n\n // 6. Build stats\n let sectionsCompressed = 0;\n let sectionsOmitted = 0;\n for (const item of included) {\n for (const section of item.compressed.sections) {\n if (section.compressed) {\n sectionsCompressed++;\n }\n sectionsOmitted += section.omittedSections ?? 0;\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 sectionsOmitted,\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(specs: CompressedSpec[], stats: PackStats): string {\n const lines: string[] = [];\n\n lines.push(\n `<context budget=\"${stats.budget}\" used=\"${stats.used}\" specs=\"${stats.specsIncluded}\" compressed=\"${stats.sectionsCompressed}\" omitted=\"${stats.sectionsOmitted}\">`,\n );\n\n for (const spec of specs) {\n const alloc = stats.allocations.find((a) => a.specId === spec.specId);\n const relevance = alloc?.relevance ?? 0;\n const tokens = alloc?.tokens ?? 0;\n\n if (spec.collapsed) {\n lines.push(\n ` <spec id=\"${escapeXml(spec.specId)}\" type=\"${escapeXml(spec.type)}\" relevance=\"${relevance}\" tokens=\"${tokens}\" collapsed=\"true\">`,\n );\n lines.push(` ${escapeXml(spec.collapsedSummary ?? \"\")}`);\n lines.push(\" </spec>\");\n } else {\n lines.push(\n ` <spec id=\"${escapeXml(spec.specId)}\" type=\"${escapeXml(spec.type)}\" relevance=\"${relevance}\" tokens=\"${tokens}\">`,\n );\n for (const section of spec.sections) {\n const compressedAttr = section.compressed ? ' compressed=\"true\"' : \"\";\n lines.push(` <section name=\"${escapeXml(section.heading)}\"${compressedAttr}>`);\n lines.push(` ${escapeXml(section.content)}`);\n lines.push(\" </section>\");\n }\n lines.push(\" </spec>\");\n }\n }\n\n lines.push(\"</context>\");\n\n return lines.join(\"\\n\");\n}\n","import type { CompressedSpec, PackStats } from \"../types.js\";\n\n/**\n * Format compressed specs as Markdown.\n *\n * @param specs - Compressed specs to render.\n * @param stats - Pack statistics with allocation details.\n * @returns A Markdown string representing the packed context.\n */\nexport function formatMarkdown(specs: CompressedSpec[], stats: PackStats): string {\n const parts: string[] = [];\n\n for (let i = 0; i < specs.length; i++) {\n const spec = specs[i]!;\n const alloc = stats.allocations.find((a) => a.specId === spec.specId);\n const relevance = alloc?.relevance ?? 0;\n\n if (i > 0) {\n parts.push(\"---\");\n parts.push(\"\");\n }\n\n parts.push(`# ${spec.specId} (${spec.type}) [relevance: ${relevance}]`);\n parts.push(\"\");\n\n if (spec.collapsed) {\n parts.push(spec.collapsedSummary ?? \"\");\n parts.push(\"\");\n } else {\n for (const section of spec.sections) {\n if (section.heading) {\n parts.push(`## ${section.heading}`);\n parts.push(\"\");\n }\n parts.push(section.content);\n parts.push(\"\");\n }\n }\n }\n\n return parts.join(\"\\n\");\n}\n","import type { CompressedSpec, PackStats } from \"../types.js\";\n\ninterface JsonSection {\n name: string;\n content: string;\n compressed: boolean;\n}\n\ninterface JsonSpec {\n id: string;\n type: string;\n relevance: number;\n tokens: number;\n collapsed: boolean;\n summary?: string;\n sections: JsonSection[];\n}\n\ninterface JsonOutput {\n budget: number;\n used: number;\n sectionsOmitted: number;\n specs: JsonSpec[];\n}\n\n/**\n * Format compressed specs as a JSON string.\n *\n * @param specs - Compressed specs to render.\n * @param stats - Pack statistics with allocation details.\n * @returns A pretty-printed JSON string representing the packed context.\n */\nexport function formatJson(specs: CompressedSpec[], stats: PackStats): string {\n const output: JsonOutput = {\n budget: stats.budget,\n used: stats.used,\n sectionsOmitted: stats.sectionsOmitted,\n specs: specs.map((spec) => {\n const alloc = stats.allocations.find((a) => a.specId === spec.specId);\n const relevance = alloc?.relevance ?? 0;\n const tokens = alloc?.tokens ?? 0;\n\n const jsonSpec: JsonSpec = {\n id: spec.specId,\n type: spec.type,\n relevance,\n tokens,\n collapsed: spec.collapsed,\n sections: spec.sections.map((s) => ({\n name: s.heading,\n content: s.content,\n compressed: s.compressed,\n })),\n };\n\n if (spec.collapsed) {\n jsonSpec.summary = spec.collapsedSummary ?? \"\";\n }\n\n return jsonSpec;\n }),\n };\n\n return JSON.stringify(output, null, 2);\n}\n","import type { ParsedSpec, DependencyGraph } from \"@specdx/core\";\nimport type { PackConfig } from \"@specdx/schema\";\nimport type {\n PackOptions,\n PackResult,\n CompressionOptions,\n CompressedSpec,\n RelevanceScore,\n} from \"./types.js\";\nimport { scoreSpecs, scoreSpecsByIds } from \"./resolver.js\";\nimport { allocate } from \"./allocator.js\";\nimport { formatXml } from \"./formatters/xml.js\";\nimport { formatMarkdown } from \"./formatters/markdown.js\";\nimport { formatJson } from \"./formatters/json.js\";\n\nexport type {\n PackOptions,\n PackResult,\n PackStats,\n SpecAllocation,\n RelevanceScore,\n CompressedSpec,\n CompressedSection,\n CompressionOptions,\n} from \"./types.js\";\n\nexport { scoreSpecs, scoreSpecsByIds } from \"./resolver.js\";\nexport { allocate, type AllocatorOptions, type AllocationResult } from \"./allocator.js\";\nexport { compressSpec } from \"./compressor.js\";\nexport { formatXml } from \"./formatters/xml.js\";\nexport { formatMarkdown } from \"./formatters/markdown.js\";\nexport { formatJson } from \"./formatters/json.js\";\n\n/**\n * Default empty dependency graph used when none is provided.\n */\nfunction emptyGraph(): DependencyGraph {\n return {\n nodes: [],\n edges: [],\n topologicalSort: () => [],\n getDownstream: () => [],\n getUpstream: () => [],\n };\n}\n\n/**\n * Build CompressionOptions from PackConfig with sensible defaults.\n */\nfunction buildCompressionOptions(packConfig: PackConfig | undefined): CompressionOptions {\n const compression = packConfig?.compression;\n return {\n stripBoilerplate: compression?.strip_boilerplate ?? true,\n stableDays: compression?.stable_days ?? 7,\n collapseResolvedAdrs: compression?.collapse_resolved_adrs ?? true,\n boilerplateSections: packConfig?.boilerplate_sections ?? [\n \"Changelog\",\n \"Revision History\",\n \"Document History\",\n ],\n };\n}\n\n/**\n * Pack specs into a formatted context string within a token budget.\n *\n * Pipeline:\n * 1. Resolve relevance scores\n * 2. Allocate token budget across specs\n * 3. Format output in the requested format\n */\nexport function pack(\n specs: ParsedSpec[],\n options: PackOptions,\n packConfig: PackConfig | undefined,\n graph: DependencyGraph | undefined,\n): PackResult {\n // 1. Resolve defaults\n const budget = options.budget ?? packConfig?.max_tokens ?? 12000;\n const format = options.format ?? packConfig?.format ?? \"xml\";\n const full = options.full ?? false;\n const compression = buildCompressionOptions(packConfig);\n const resolvedGraph = graph ?? emptyGraph();\n\n // 2. Extract project-context specs and reserve budget\n const projectContextSpecs: ParsedSpec[] = [];\n const regularSpecs: ParsedSpec[] = [];\n for (const spec of specs) {\n if (spec.frontmatter.type === \"project-context\") {\n projectContextSpecs.push(spec);\n } else {\n regularSpecs.push(spec);\n }\n }\n\n let reservedTokens = 0;\n let reservedCompressed: CompressedSpec[] = [];\n if (projectContextSpecs.length > 0) {\n const maxReserved = Math.min(budget, 2000);\n const ctxScores: RelevanceScore[] = projectContextSpecs.map((s) => ({\n specId: s.frontmatter.id,\n score: 1.0,\n rawScore: 1.0,\n matchedKeywords: [],\n graphBoosted: false,\n }));\n const ctxResult = allocate(projectContextSpecs, ctxScores, {\n budget: maxReserved,\n full: true,\n compression,\n });\n reservedCompressed = ctxResult.specs;\n reservedTokens = ctxResult.stats.used;\n }\n\n const regularBudget = Math.max(0, budget - reservedTokens);\n\n // 3. Build spec map for resolver (regular specs only)\n const specMap = new Map<string, ParsedSpec>();\n for (const spec of regularSpecs) {\n specMap.set(spec.frontmatter.id, spec);\n }\n\n // 4. Stage 1 - Resolve\n const scores = options.specs\n ? scoreSpecsByIds(specMap, options.specs, resolvedGraph)\n : scoreSpecs(specMap, options.task, resolvedGraph);\n\n // 5. Stage 2 - Allocate\n const { specs: compressedSpecs, stats } = allocate(regularSpecs, scores, {\n budget: regularBudget,\n full,\n compression,\n });\n\n // 6. Combine project-context and regular specs\n const allCompressed = [...reservedCompressed, ...compressedSpecs];\n\n // Update stats to include reserved specs\n stats.budget = budget;\n stats.used += reservedTokens;\n stats.specsIncluded += reservedCompressed.length;\n for (const ctx of reservedCompressed) {\n stats.allocations.unshift({\n specId: ctx.specId,\n type: ctx.type,\n relevance: 1.0,\n tokens: reservedTokens,\n compressed: false,\n included: true,\n });\n }\n\n // 7. Dry run: return stats without output\n if (options.dryRun) {\n return { output: \"\", stats };\n }\n\n // 8. Stage 3 - Format\n let output: string;\n switch (format) {\n case \"markdown\":\n output = formatMarkdown(allCompressed, stats);\n break;\n case \"json\":\n output = formatJson(allCompressed, stats);\n break;\n default:\n output = formatXml(allCompressed, stats);\n break;\n }\n\n return { output, stats };\n}\n"],"mappings":";;;;;AAMA,IAAM,YAAY,oBAAI,IAAI;EACxB;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACD;AAGD,SAAS,SAAS,MAAY;AAC5B,SAAO,KACJ,MAAM,0BAA0B,EAChC,IAAI,CAAC,MAAM,EAAE,YAAW,CAAE,EAC1B,OAAO,CAAC,MAAM,EAAE,SAAS,KAAK,CAAC,UAAU,IAAI,CAAC,CAAC;AACpD;AAGA,IAAM,cAAc;AACpB,IAAM,eAAe;AACrB,IAAM,kBAAkB;AACxB,IAAM,cAAc;AAGpB,IAAM,sBAAsB;AAG5B,IAAM,qBAAqB;AAG3B,IAAM,kBAAkB;AAUlB,SAAU,WACd,OACA,MACA,OAAsB;AAEtB,QAAM,WAAW,OAAO,SAAS,IAAI,IAAI,CAAA;AAGzC,MAAI,SAAS,WAAW,GAAG;AACzB,UAAMA,WAA4B,CAAA;AAClC,eAAW,UAAU,MAAM,KAAI,GAAI;AACjC,MAAAA,SAAQ,KAAK;QACX;QACA,OAAO;QACP,UAAU;QACV,iBAAiB,CAAA;QACjB,cAAc;OACf;IACH;AACA,WAAOA;EACT;AAGA,QAAM,YAAY,oBAAI,IAAG;AACzB,QAAM,aAAa,oBAAI,IAAG;AAC1B,QAAM,eAAe,oBAAI,IAAG;AAC5B,QAAM,aAAa,QAAQ,IAAI,YAA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