specdx 0.3.0-alpha.3 → 0.4.0-alpha.10

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 (82) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/LICENSE +21 -0
  3. package/dist/{changelog-OUP2RXWN.js → changelog-GR53T6IG.js} +18 -11
  4. package/dist/{changelog-OUP2RXWN.js.map → changelog-GR53T6IG.js.map} +1 -1
  5. package/dist/{check-3XQYO3HU.js → check-OMWCIY5D.js} +37 -10
  6. package/dist/check-OMWCIY5D.js.map +1 -0
  7. package/dist/chunk-3GMYCATE.js +526 -0
  8. package/dist/chunk-3GMYCATE.js.map +1 -0
  9. package/dist/{chunk-6BWZEAST.js → chunk-N77RNV7J.js} +161 -26
  10. package/dist/chunk-N77RNV7J.js.map +1 -0
  11. package/dist/{pack-PI6V6OR2.js → chunk-SDDTD4R3.js} +97 -171
  12. package/dist/chunk-SDDTD4R3.js.map +1 -0
  13. package/dist/{chunk-ZX4HVL5M.js → chunk-SJCIM4TC.js} +119 -17
  14. package/dist/chunk-SJCIM4TC.js.map +1 -0
  15. package/dist/{chunk-DDFLMRPC.js → chunk-VMMTEGYN.js} +15 -11
  16. package/dist/chunk-VMMTEGYN.js.map +1 -0
  17. package/dist/{chunk-PHR7AV6I.js → chunk-Z77VQUZ3.js} +156 -2
  18. package/dist/chunk-Z77VQUZ3.js.map +1 -0
  19. package/dist/diff-AUBYOQWU.js +107 -0
  20. package/dist/diff-AUBYOQWU.js.map +1 -0
  21. package/dist/dist-BXYQB2UO.js +306 -0
  22. package/dist/dist-BXYQB2UO.js.map +1 -0
  23. package/dist/dist-RL2DT3ZE.js +15 -0
  24. package/dist/{explain-I7AQMEEH.js → explain-EUID6MZF.js} +35 -28
  25. package/dist/explain-EUID6MZF.js.map +1 -0
  26. package/dist/{generate-PC7BIB7G.js → generate-U3EFOCNS.js} +3 -3
  27. package/dist/{generate-story-7WHPPFHY.js → generate-story-U6FMQIYZ.js} +8 -4
  28. package/dist/generate-story-U6FMQIYZ.js.map +1 -0
  29. package/dist/{generate-test-plan-U5LMWGKX.js → generate-test-plan-HOCWDYKF.js} +11 -6
  30. package/dist/generate-test-plan-HOCWDYKF.js.map +1 -0
  31. package/dist/graph-TA54D4XA.js +102 -0
  32. package/dist/graph-TA54D4XA.js.map +1 -0
  33. package/dist/index.js +777 -158
  34. package/dist/index.js.map +1 -1
  35. package/dist/{lint-6Z2TVWAQ.js → lint-L5WOBD25.js} +17 -6
  36. package/dist/lint-L5WOBD25.js.map +1 -0
  37. package/dist/main.js +100 -15
  38. package/dist/main.js.map +1 -1
  39. package/dist/mcp-GNQQGD7X.js +17 -0
  40. package/dist/mcp-GNQQGD7X.js.map +1 -0
  41. package/dist/{migrate-L7W5RHSS.js → migrate-YEJQWIMX.js} +4 -4
  42. package/dist/migrate-YEJQWIMX.js.map +1 -0
  43. package/dist/pack-AQH5XQUF.js +168 -0
  44. package/dist/pack-AQH5XQUF.js.map +1 -0
  45. package/dist/ready-DB5ORK2E.js +229 -0
  46. package/dist/ready-DB5ORK2E.js.map +1 -0
  47. package/dist/skills/specdx-check-drift.md +1 -1
  48. package/dist/skills/specdx-verify.md +12 -1
  49. package/dist/{status-AV5GSWVI.js → status-3QUQMF4L.js} +46 -31
  50. package/dist/status-3QUQMF4L.js.map +1 -0
  51. package/dist/{update-HIWDDEZQ.js → update-PE2DPYDR.js} +5 -5
  52. package/dist/update-PE2DPYDR.js.map +1 -0
  53. package/dist/validate-YNZMV6KZ.js +86 -0
  54. package/dist/validate-YNZMV6KZ.js.map +1 -0
  55. package/hooks/session-start +0 -0
  56. package/package.json +49 -16
  57. package/dist/check-3XQYO3HU.js.map +0 -1
  58. package/dist/chunk-6BWZEAST.js.map +0 -1
  59. package/dist/chunk-DDFLMRPC.js.map +0 -1
  60. package/dist/chunk-PHR7AV6I.js.map +0 -1
  61. package/dist/chunk-WTFWNYJA.js +0 -261
  62. package/dist/chunk-WTFWNYJA.js.map +0 -1
  63. package/dist/chunk-ZX4HVL5M.js.map +0 -1
  64. package/dist/diff-275PLXYH.js +0 -100
  65. package/dist/diff-275PLXYH.js.map +0 -1
  66. package/dist/dist-PQCG2XXF.js +0 -11
  67. package/dist/explain-I7AQMEEH.js.map +0 -1
  68. package/dist/generate-story-7WHPPFHY.js.map +0 -1
  69. package/dist/generate-test-plan-U5LMWGKX.js.map +0 -1
  70. package/dist/graph-RCAPF55A.js +0 -54
  71. package/dist/graph-RCAPF55A.js.map +0 -1
  72. package/dist/lint-6Z2TVWAQ.js.map +0 -1
  73. package/dist/migrate-L7W5RHSS.js.map +0 -1
  74. package/dist/pack-PI6V6OR2.js.map +0 -1
  75. package/dist/ready-B7IFPL3S.js +0 -159
  76. package/dist/ready-B7IFPL3S.js.map +0 -1
  77. package/dist/status-AV5GSWVI.js.map +0 -1
  78. package/dist/update-HIWDDEZQ.js.map +0 -1
  79. package/dist/validate-N2WSG75W.js +0 -34
  80. package/dist/validate-N2WSG75W.js.map +0 -1
  81. /package/dist/{dist-PQCG2XXF.js.map → dist-RL2DT3ZE.js.map} +0 -0
  82. /package/dist/{generate-PC7BIB7G.js.map → generate-U3EFOCNS.js.map} +0 -0
package/dist/index.js CHANGED
@@ -3,6 +3,23 @@ import { defineCommand } from "citty";
3
3
  import { mkdir, writeFile } from "fs/promises";
4
4
  import { join } from "path";
5
5
 
6
+ // ../schema/dist/types.js
7
+ var SPEC_TYPES = [
8
+ "prd",
9
+ "technical-design",
10
+ "user-story",
11
+ "test-plan",
12
+ "adr",
13
+ "api-contract",
14
+ "epic",
15
+ "quick-spec",
16
+ "project-context"
17
+ ];
18
+ var DEPENDENCY_RELATIONSHIPS = {
19
+ "depends-on": "self-requires-target",
20
+ "implemented-by": "target-requires-self"
21
+ };
22
+
6
23
  // ../schema/dist/sections.js
7
24
  var REQUIRED_SECTIONS = {
8
25
  prd: ["Problem Statement", "Goals", "Non-Goals", "Features", "Success Criteria"],
@@ -33,30 +50,123 @@ var base_spec_default = {
33
50
  $schema: "http://json-schema.org/draft-07/schema#",
34
51
  type: "object",
35
52
  properties: {
36
- id: { type: "string", minLength: 1 },
37
- type: { type: "string", enum: ["prd", "technical-design", "user-story", "test-plan", "adr", "api-contract", "epic", "quick-spec", "project-context"] },
38
- title: { type: "string", minLength: 1 },
39
- status: { type: "string", enum: ["draft", "review", "approved", "superseded"] },
40
- version: { type: "string" },
41
- created: { type: "string", format: "date" },
42
- updated: { type: "string", format: "date" },
43
- authors: { type: "array", items: { type: "string" }, minItems: 1 },
44
- tags: { type: "array", items: { type: "string" }, default: [] },
53
+ id: {
54
+ type: "string",
55
+ minLength: 1
56
+ },
57
+ type: {
58
+ type: "string",
59
+ enum: [
60
+ "prd",
61
+ "technical-design",
62
+ "user-story",
63
+ "test-plan",
64
+ "adr",
65
+ "api-contract",
66
+ "epic",
67
+ "quick-spec",
68
+ "project-context"
69
+ ]
70
+ },
71
+ title: {
72
+ type: "string",
73
+ minLength: 1
74
+ },
75
+ status: {
76
+ type: "string",
77
+ enum: [
78
+ "draft",
79
+ "review",
80
+ "approved",
81
+ "superseded"
82
+ ]
83
+ },
84
+ version: {
85
+ type: "string"
86
+ },
87
+ created: {
88
+ type: "string",
89
+ format: "date"
90
+ },
91
+ updated: {
92
+ type: "string",
93
+ format: "date"
94
+ },
95
+ authors: {
96
+ type: "array",
97
+ items: {
98
+ type: "string"
99
+ },
100
+ minItems: 1
101
+ },
102
+ tags: {
103
+ type: "array",
104
+ items: {
105
+ type: "string"
106
+ },
107
+ default: []
108
+ },
45
109
  references: {
46
110
  type: "array",
47
111
  items: {
48
112
  type: "object",
49
113
  properties: {
50
- id: { type: "string" },
51
- relationship: { type: "string", enum: ["implemented-by", "decomposed-into", "depends-on", "supersedes", "related-to"] }
114
+ id: {
115
+ type: "string"
116
+ },
117
+ relationship: {
118
+ type: "string",
119
+ enum: [
120
+ "implemented-by",
121
+ "decomposed-into",
122
+ "depends-on",
123
+ "supersedes",
124
+ "related-to"
125
+ ]
126
+ }
52
127
  },
53
- required: ["id", "relationship"],
128
+ required: [
129
+ "id",
130
+ "relationship"
131
+ ],
132
+ additionalProperties: false
133
+ },
134
+ default: []
135
+ },
136
+ artifacts: {
137
+ type: "array",
138
+ items: {
139
+ type: "object",
140
+ properties: {
141
+ path: {
142
+ type: "string",
143
+ minLength: 1
144
+ },
145
+ exports: {
146
+ type: "array",
147
+ items: {
148
+ type: "string",
149
+ minLength: 1
150
+ }
151
+ }
152
+ },
153
+ required: [
154
+ "path"
155
+ ],
54
156
  additionalProperties: false
55
157
  },
56
158
  default: []
57
159
  }
58
160
  },
59
- required: ["id", "type", "title", "status", "version", "created", "authors"],
161
+ required: [
162
+ "id",
163
+ "type",
164
+ "title",
165
+ "status",
166
+ "version",
167
+ "created",
168
+ "authors"
169
+ ],
60
170
  additionalProperties: true
61
171
  };
62
172
 
@@ -81,7 +191,7 @@ var config_default = {
81
191
  type: "object",
82
192
  properties: {
83
193
  path: { type: "string" },
84
- type: { type: "string", enum: ["prd", "technical-design", "user-story", "test-plan", "adr", "api-contract"] },
194
+ type: { type: "string", enum: ["prd", "technical-design", "user-story", "test-plan", "adr", "api-contract", "epic", "quick-spec", "project-context"] },
85
195
  required: { type: "boolean", default: false },
86
196
  requires: { type: "array", items: { type: "string" } },
87
197
  owner: { type: "string" }
@@ -290,9 +400,13 @@ var project_context_default = {
290
400
  // ../schema/dist/validator.js
291
401
  import * as addFormatsNs from "ajv-formats";
292
402
  var addFormats = addFormatsNs.default ?? addFormatsNs;
403
+ var runtimeBaseSpecSchema = structuredClone(base_spec_default);
404
+ runtimeBaseSpecSchema.properties.type.enum = [...SPEC_TYPES];
405
+ var runtimeConfigSchema = structuredClone(config_default);
406
+ runtimeConfigSchema.properties.specs.additionalProperties.properties.type.enum = [...SPEC_TYPES];
293
407
  var ajv = new AjvClass({ allErrors: true, strict: true });
294
408
  addFormats(ajv, ["date"]);
295
- ajv.addSchema(base_spec_default);
409
+ ajv.addSchema(runtimeBaseSpecSchema);
296
410
  var specValidators = {
297
411
  prd: ajv.compile(prd_default),
298
412
  "technical-design": ajv.compile(technical_design_default),
@@ -304,7 +418,7 @@ var specValidators = {
304
418
  "quick-spec": ajv.compile(quick_spec_default),
305
419
  "project-context": ajv.compile(project_context_default)
306
420
  };
307
- var configValidator = ajv.compile(config_default);
421
+ var configValidator = ajv.compile(runtimeConfigSchema);
308
422
  function validateSpec(type, data) {
309
423
  const validate = specValidators[type];
310
424
  if (!validate) {
@@ -699,6 +813,112 @@ function buildGraph(config) {
699
813
  };
700
814
  }
701
815
 
816
+ // ../core/dist/relations.js
817
+ function mapEntriesToIds(config, specsByEntry) {
818
+ const entryIds = /* @__PURE__ */ new Map();
819
+ for (const key of Object.keys(config.specs)) {
820
+ const ids = [];
821
+ for (const spec of specsByEntry.get(key) ?? []) {
822
+ const id = spec.frontmatter.id;
823
+ if (typeof id === "string")
824
+ ids.push(id);
825
+ }
826
+ entryIds.set(key, ids);
827
+ }
828
+ return entryIds;
829
+ }
830
+ function collectKnownIds(specsByEntry) {
831
+ const ids = /* @__PURE__ */ new Set();
832
+ for (const specs of specsByEntry.values()) {
833
+ for (const spec of specs) {
834
+ const id = spec.frontmatter.id;
835
+ if (typeof id === "string")
836
+ ids.add(id);
837
+ }
838
+ }
839
+ return ids;
840
+ }
841
+ function walk(specId, adjacency) {
842
+ const visited = /* @__PURE__ */ new Set();
843
+ const stack = [specId];
844
+ while (stack.length > 0) {
845
+ const current = stack.pop();
846
+ for (const next of adjacency.get(current) ?? []) {
847
+ if (!visited.has(next)) {
848
+ visited.add(next);
849
+ stack.push(next);
850
+ }
851
+ }
852
+ }
853
+ visited.delete(specId);
854
+ return [...visited];
855
+ }
856
+ function buildRelationResolver(config, specsByEntry) {
857
+ const entryIds = config ? mapEntriesToIds(config, specsByEntry) : /* @__PURE__ */ new Map();
858
+ const knownIds = collectKnownIds(specsByEntry);
859
+ const edgeSources = /* @__PURE__ */ new Map();
860
+ const addEdge = (from, to, source) => {
861
+ if (from === to)
862
+ return;
863
+ const key = `${from}\0${to}`;
864
+ const existing = edgeSources.get(key);
865
+ if (!existing) {
866
+ edgeSources.set(key, source);
867
+ } else if (existing !== source) {
868
+ edgeSources.set(key, "both");
869
+ }
870
+ };
871
+ for (const [key, entry] of Object.entries(config?.specs ?? {})) {
872
+ const requires = entry.requires ?? [];
873
+ for (const dep of requires) {
874
+ for (const from of entryIds.get(dep) ?? []) {
875
+ for (const to of entryIds.get(key) ?? []) {
876
+ addEdge(from, to, "requires");
877
+ }
878
+ }
879
+ }
880
+ }
881
+ for (const specs of specsByEntry.values()) {
882
+ for (const spec of specs) {
883
+ const selfId = spec.frontmatter.id;
884
+ if (typeof selfId !== "string")
885
+ continue;
886
+ const refs = spec.frontmatter.references;
887
+ if (!Array.isArray(refs))
888
+ continue;
889
+ for (const ref of refs) {
890
+ if (!ref || typeof ref !== "object")
891
+ continue;
892
+ const { id: targetId, relationship } = ref;
893
+ if (typeof targetId !== "string" || typeof relationship !== "string")
894
+ continue;
895
+ if (!knownIds.has(targetId))
896
+ continue;
897
+ const direction = DEPENDENCY_RELATIONSHIPS[relationship];
898
+ if (direction === "self-requires-target") {
899
+ addEdge(targetId, selfId, "references");
900
+ } else if (direction === "target-requires-self") {
901
+ addEdge(selfId, targetId, "references");
902
+ }
903
+ }
904
+ }
905
+ }
906
+ const edges = [];
907
+ const downstreamAdj = /* @__PURE__ */ new Map();
908
+ const upstreamAdj = /* @__PURE__ */ new Map();
909
+ for (const [key, source] of edgeSources) {
910
+ const [from, to] = key.split("\0");
911
+ edges.push({ from, to, source });
912
+ downstreamAdj.set(from, [...downstreamAdj.get(from) ?? [], to]);
913
+ upstreamAdj.set(to, [...upstreamAdj.get(to) ?? [], from]);
914
+ }
915
+ return {
916
+ edges,
917
+ getUpstream: (specId) => walk(specId, upstreamAdj),
918
+ getDownstream: (specId) => walk(specId, downstreamAdj)
919
+ };
920
+ }
921
+
702
922
  // ../core/dist/glob.js
703
923
  import { glob } from "tinyglobby";
704
924
  import { join as join3, isAbsolute } from "path";
@@ -847,30 +1067,57 @@ var storyCoverageRule = {
847
1067
  };
848
1068
 
849
1069
  // ../lint/dist/rules/staleness-check.js
1070
+ function groupByEntry(config, specs) {
1071
+ const byEntry = /* @__PURE__ */ new Map();
1072
+ for (const key of Object.keys(config.specs))
1073
+ byEntry.set(key, []);
1074
+ for (const spec of specs) {
1075
+ let bestKey;
1076
+ let bestLen = -1;
1077
+ for (const [key, entry] of Object.entries(config.specs)) {
1078
+ const prefix = entry.path.split("*")[0] ?? "";
1079
+ const normalized = spec.filePath.replace(/\\/g, "/");
1080
+ if (normalized.includes(prefix) && prefix.length > bestLen) {
1081
+ bestKey = key;
1082
+ bestLen = prefix.length;
1083
+ }
1084
+ }
1085
+ if (bestKey)
1086
+ byEntry.get(bestKey).push(spec);
1087
+ }
1088
+ return byEntry;
1089
+ }
1090
+ function lastUpdated(spec) {
1091
+ return spec.frontmatter.updated ?? spec.frontmatter.created ?? "";
1092
+ }
850
1093
  var stalenessCheckRule = {
851
1094
  id: "freshness/staleness-check",
852
1095
  description: "Warns if a spec hasn't been updated since its upstream dependency changed",
853
1096
  severity: "warn",
854
1097
  run(context) {
855
- const refs = context.spec.frontmatter.references;
856
- if (!refs || refs.length === 0)
1098
+ const specId = context.spec.frontmatter.id;
1099
+ if (typeof specId !== "string")
1100
+ return [];
1101
+ const specUpdated = lastUpdated(context.spec);
1102
+ if (!specUpdated)
857
1103
  return [];
858
- const specUpdated = context.spec.frontmatter.updated ?? context.spec.frontmatter.created;
859
1104
  const specDate = new Date(specUpdated);
1105
+ const byEntry = context.config ? groupByEntry(context.config, context.allSpecs) : /* @__PURE__ */ new Map([["", context.allSpecs]]);
1106
+ const relations = buildRelationResolver(context.config, byEntry);
1107
+ const upstreamIds = relations.getUpstream(specId);
860
1108
  const diagnostics = [];
861
- for (const ref of refs) {
862
- if (ref.relationship !== "depends-on" && ref.relationship !== "implemented-by")
863
- continue;
864
- const upstream = context.allSpecs.find((s) => s.frontmatter.id === ref.id);
1109
+ for (const upstreamId of upstreamIds) {
1110
+ const upstream = context.allSpecs.find((s) => s.frontmatter.id === upstreamId);
865
1111
  if (!upstream)
866
1112
  continue;
867
- const upstreamUpdated = upstream.frontmatter.updated ?? upstream.frontmatter.created;
868
- const upstreamDate = new Date(upstreamUpdated);
869
- if (upstreamDate > specDate) {
1113
+ const upstreamUpdated = lastUpdated(upstream);
1114
+ if (!upstreamUpdated)
1115
+ continue;
1116
+ if (new Date(upstreamUpdated) > specDate) {
870
1117
  diagnostics.push({
871
1118
  ruleId: "freshness/staleness-check",
872
1119
  severity: "warn",
873
- message: `Potentially stale: upstream "${upstream.frontmatter.id}" was updated on ${upstreamUpdated}, but this spec was last updated on ${specUpdated}`,
1120
+ message: `Potentially stale: upstream "${upstreamId}" was updated on ${upstreamUpdated}, but this spec was last updated on ${specUpdated}`,
874
1121
  filePath: context.spec.filePath
875
1122
  });
876
1123
  }
@@ -942,6 +1189,236 @@ var singleProjectContextRule = {
942
1189
  }
943
1190
  };
944
1191
 
1192
+ // ../lint/dist/rules/terminology.js
1193
+ function normalizeCompound(term) {
1194
+ return term.replace(/([a-z])([A-Z])/g, "$1 $2").replace(/[-_]/g, " ").toLowerCase().trim();
1195
+ }
1196
+ function extractCompoundTerms(content) {
1197
+ const terms = [];
1198
+ const camelCaseRegex = /\b[a-zA-Z]*[a-z][A-Z][a-zA-Z]*\b/g;
1199
+ let match;
1200
+ while ((match = camelCaseRegex.exec(content)) !== null) {
1201
+ terms.push(match[0]);
1202
+ }
1203
+ const hyphenatedRegex = /\b[a-z][a-z0-9]*(?:-[a-z][a-z0-9]*)+\b/g;
1204
+ while ((match = hyphenatedRegex.exec(content)) !== null) {
1205
+ terms.push(match[0]);
1206
+ }
1207
+ return terms;
1208
+ }
1209
+ var terminologyRule = {
1210
+ id: "consistency/terminology",
1211
+ description: "Detects terminology drift (e.g., user-profile vs UserProfile vs user profile) across specs",
1212
+ severity: "warn",
1213
+ run(context) {
1214
+ if (context.spec !== context.allSpecs[0])
1215
+ return [];
1216
+ const termMap = /* @__PURE__ */ new Map();
1217
+ for (const spec of context.allSpecs) {
1218
+ if (!spec.content)
1219
+ continue;
1220
+ const terms = extractCompoundTerms(spec.content);
1221
+ for (const term of terms) {
1222
+ const normalized = normalizeCompound(term);
1223
+ if (!normalized.includes(" "))
1224
+ continue;
1225
+ if (!termMap.has(normalized)) {
1226
+ termMap.set(normalized, /* @__PURE__ */ new Set());
1227
+ }
1228
+ termMap.get(normalized).add(term);
1229
+ }
1230
+ }
1231
+ const diagnostics = [];
1232
+ for (const [normalized, variants] of termMap) {
1233
+ if (variants.size >= 2) {
1234
+ const variantList = [...variants].join(", ");
1235
+ diagnostics.push({
1236
+ ruleId: "consistency/terminology",
1237
+ severity: "warn",
1238
+ message: `Inconsistent terminology for "${normalized}": found variants [${variantList}]. Standardize terminology across specs.`,
1239
+ filePath: context.spec.filePath
1240
+ });
1241
+ }
1242
+ }
1243
+ return diagnostics;
1244
+ }
1245
+ };
1246
+
1247
+ // ../lint/dist/rules/edge-case-coverage.js
1248
+ var EDGE_CASE_KEYWORDS = [
1249
+ "error",
1250
+ "invalid",
1251
+ "empty",
1252
+ "timeout",
1253
+ "fails",
1254
+ "failure",
1255
+ "boundary",
1256
+ "edge case",
1257
+ "null",
1258
+ "undefined",
1259
+ "reject",
1260
+ "unauthorized",
1261
+ "forbidden",
1262
+ "404",
1263
+ "500",
1264
+ "missing",
1265
+ "malformed",
1266
+ "overflow",
1267
+ "duplicate",
1268
+ "graceful",
1269
+ "fall back",
1270
+ "fallback",
1271
+ "crash",
1272
+ "nonexistent",
1273
+ "corrupt"
1274
+ ];
1275
+ var edgeCaseCoverageRule = {
1276
+ id: "completeness/edge-case-coverage",
1277
+ description: "Flag user stories or test plans that don't mention error states or edge cases",
1278
+ severity: "warn",
1279
+ run(context) {
1280
+ const type = context.spec.frontmatter.type;
1281
+ if (type !== "user-story" && type !== "test-plan")
1282
+ return [];
1283
+ const content = context.spec.content.toLowerCase();
1284
+ const hasEdgeCases = EDGE_CASE_KEYWORDS.some((kw) => content.includes(kw));
1285
+ if (hasEdgeCases)
1286
+ return [];
1287
+ return [
1288
+ {
1289
+ ruleId: "completeness/edge-case-coverage",
1290
+ severity: "warn",
1291
+ message: "No error states or edge cases mentioned. Consider adding error handling, boundary conditions, or failure mode scenarios.",
1292
+ filePath: context.spec.filePath
1293
+ }
1294
+ ];
1295
+ }
1296
+ };
1297
+
1298
+ // ../lint/dist/rules/naming-conventions.js
1299
+ var namingConventionsRule = {
1300
+ id: "consistency/naming-conventions",
1301
+ description: "Enforce consistent naming conventions across specs",
1302
+ severity: "warn",
1303
+ run(context) {
1304
+ const { spec } = context;
1305
+ const type = spec.frontmatter.type;
1306
+ const diagnostics = [];
1307
+ if (type === "prd") {
1308
+ const sectionParts = spec.content.split(/^(?=## )/m);
1309
+ const featuresSection = sectionParts.find((p) => /^## Features\b/.test(p));
1310
+ if (featuresSection) {
1311
+ const bullets = featuresSection.match(/^- .+$/gm) ?? [];
1312
+ for (const bullet of bullets) {
1313
+ if (bullet.match(/^- \*\*F\d+\*\*:/) === null && bullet.trim().length > 2) {
1314
+ diagnostics.push({
1315
+ ruleId: "consistency/naming-conventions",
1316
+ severity: "warn",
1317
+ message: `PRD feature missing feature ID pattern (**F<N>**:): "${bullet.slice(0, 60)}"`,
1318
+ filePath: spec.filePath
1319
+ });
1320
+ }
1321
+ }
1322
+ }
1323
+ }
1324
+ if (type === "user-story") {
1325
+ const id = spec.frontmatter.id;
1326
+ if (!id.startsWith("story-")) {
1327
+ diagnostics.push({
1328
+ ruleId: "consistency/naming-conventions",
1329
+ severity: "warn",
1330
+ message: `User story ID "${id}" should start with "story-" (e.g., "story-${id}")`,
1331
+ filePath: spec.filePath
1332
+ });
1333
+ }
1334
+ }
1335
+ if (type === "api-contract") {
1336
+ const endpointRe = /^###\s+(GET|POST|PUT|PATCH|DELETE)\s+(\S+)/gm;
1337
+ let match;
1338
+ while ((match = endpointRe.exec(spec.content)) !== null) {
1339
+ const path = match[2];
1340
+ if (/\/[a-z]+[A-Z]/.test(path)) {
1341
+ diagnostics.push({
1342
+ ruleId: "consistency/naming-conventions",
1343
+ severity: "warn",
1344
+ message: `Endpoint path "${path}" uses camelCase \u2014 use kebab-case instead (e.g., "${path.replace(/([a-z])([A-Z])/g, "$1-$2").toLowerCase()}")`,
1345
+ filePath: spec.filePath
1346
+ });
1347
+ }
1348
+ }
1349
+ }
1350
+ return diagnostics;
1351
+ }
1352
+ };
1353
+
1354
+ // ../lint/dist/rules/threat-coverage.js
1355
+ var STOPWORDS = /* @__PURE__ */ new Set(["the", "and", "for", "with", "from", "that", "this", "into", "via"]);
1356
+ function extractThreats(content) {
1357
+ const parts = content.split(/^(?=## )/m);
1358
+ const threats = [];
1359
+ for (const part of parts) {
1360
+ if (!/^##\s+(Threats|Security)\b/i.test(part))
1361
+ continue;
1362
+ const bullets = part.match(/^- .+$/gm) ?? [];
1363
+ threats.push(...bullets.map((b) => b.slice(2).trim()));
1364
+ }
1365
+ return threats;
1366
+ }
1367
+ function extractKeyTerms(text) {
1368
+ return text.toLowerCase().split(/\W+/).filter((w) => w.length > 3).filter((w) => !STOPWORDS.has(w));
1369
+ }
1370
+ var threatCoverageRule = {
1371
+ id: "security/threat-coverage",
1372
+ description: "Technical design specs must address threats identified in other specs",
1373
+ severity: "warn",
1374
+ run(context) {
1375
+ if (context.spec.frontmatter.type !== "technical-design")
1376
+ return [];
1377
+ const allThreats = [];
1378
+ for (const spec of context.allSpecs) {
1379
+ if (spec.filePath === context.spec.filePath)
1380
+ continue;
1381
+ allThreats.push(...extractThreats(spec.content));
1382
+ }
1383
+ if (allThreats.length === 0)
1384
+ return [];
1385
+ const techContent = context.spec.content.toLowerCase();
1386
+ const diagnostics = [];
1387
+ for (const threat of allThreats) {
1388
+ const keyTerms = extractKeyTerms(threat);
1389
+ const covered = keyTerms.some((term) => techContent.includes(term));
1390
+ if (!covered) {
1391
+ diagnostics.push({
1392
+ ruleId: "security/threat-coverage",
1393
+ severity: "warn",
1394
+ message: `Threat not addressed in technical design: "${threat}". Ensure the design covers this threat.`,
1395
+ filePath: context.spec.filePath
1396
+ });
1397
+ }
1398
+ }
1399
+ return diagnostics;
1400
+ }
1401
+ };
1402
+
1403
+ // ../lint/dist/rules/ambiguity-score-ai.js
1404
+ var ambiguityScoreAiRule = {
1405
+ id: "clarity/ambiguity-score-ai",
1406
+ description: "AI-powered ambiguity detection (requires ANTHROPIC_API_KEY)",
1407
+ severity: "info",
1408
+ run(context) {
1409
+ if (!process.env["ANTHROPIC_API_KEY"])
1410
+ return [];
1411
+ return [
1412
+ {
1413
+ ruleId: "clarity/ambiguity-score-ai",
1414
+ severity: "info",
1415
+ message: "AI ambiguity analysis available \u2014 run `sdx check --ai` for LLM-powered ambiguity detection",
1416
+ filePath: context.spec.filePath
1417
+ }
1418
+ ];
1419
+ }
1420
+ };
1421
+
945
1422
  // ../lint/dist/rules/index.js
946
1423
  var structureRules = [
947
1424
  validFrontmatterRule,
@@ -953,7 +1430,12 @@ var structureRules = [
953
1430
  var contentRules = [
954
1431
  storyCoverageRule,
955
1432
  stalenessCheckRule,
956
- noVagueLanguageRule
1433
+ noVagueLanguageRule,
1434
+ terminologyRule,
1435
+ edgeCaseCoverageRule,
1436
+ namingConventionsRule,
1437
+ threatCoverageRule,
1438
+ ambiguityScoreAiRule
957
1439
  ];
958
1440
  var allBuiltinRules = [...structureRules, ...contentRules];
959
1441
 
@@ -1018,7 +1500,6 @@ async function runLint(options) {
1018
1500
  for (const [, entry] of Object.entries(config.specs)) {
1019
1501
  const files = await resolveGlob(entry.path, options.configDir);
1020
1502
  for (const file of files) {
1021
- if (options.specPath && !file.includes(options.specPath)) continue;
1022
1503
  specs.push(await parseSpec(file));
1023
1504
  }
1024
1505
  }
@@ -1031,6 +1512,12 @@ async function runLint(options) {
1031
1512
  }
1032
1513
  const engine = createLintEngine({ rules, config, graph });
1033
1514
  const results = engine.lint(specs);
1515
+ if (options.specPath) {
1516
+ const specPath = options.specPath;
1517
+ results.diagnostics = results.diagnostics.filter((d) => d.filePath.includes(specPath));
1518
+ results.hasErrors = results.diagnostics.some((d) => d.severity === "error");
1519
+ results.hasWarnings = results.diagnostics.some((d) => d.severity === "warn");
1520
+ }
1034
1521
  if (graphError) {
1035
1522
  results.diagnostics.push({
1036
1523
  ruleId: "structure/no-circular-deps",
@@ -1040,7 +1527,7 @@ async function runLint(options) {
1040
1527
  });
1041
1528
  results.hasErrors = true;
1042
1529
  }
1043
- return results;
1530
+ return { ...results, specCount: specs.length, assessed: specs.length > 0 };
1044
1531
  }
1045
1532
  var lint_default = defineCommand2({
1046
1533
  meta: { name: "lint", description: "Lint all specs in the suite" },
@@ -1062,6 +1549,12 @@ var lint_default = defineCommand2({
1062
1549
  preset: args.preset
1063
1550
  });
1064
1551
  const formatter = args.format === "json" ? formatJson : args.format === "github" ? formatGithub : formatPretty;
1552
+ if (!results.assessed) {
1553
+ console.error(
1554
+ "\n \u26A0 No specs found \u2014 nothing was linted. Check the spec paths in spec.config.yaml.\n"
1555
+ );
1556
+ process.exit(3);
1557
+ }
1065
1558
  console.log(formatter(results.diagnostics));
1066
1559
  if (results.hasErrors) process.exit(1);
1067
1560
  } catch (err) {
@@ -1077,7 +1570,7 @@ var lint_default = defineCommand2({
1077
1570
  import { defineCommand as defineCommand3 } from "citty";
1078
1571
 
1079
1572
  // ../pack/dist/resolver.js
1080
- var STOPWORDS = /* @__PURE__ */ new Set([
1573
+ var STOPWORDS2 = /* @__PURE__ */ new Set([
1081
1574
  "a",
1082
1575
  "an",
1083
1576
  "and",
@@ -1154,12 +1647,13 @@ var STOPWORDS = /* @__PURE__ */ new Set([
1154
1647
  "your"
1155
1648
  ]);
1156
1649
  function tokenize(task) {
1157
- return task.split(/[\s\-_/.,;:!?()[\]{}'"]+/).map((t) => t.toLowerCase()).filter((t) => t.length > 1 && !STOPWORDS.has(t));
1650
+ return task.split(/[\s\-_/.,;:!?()[\]{}'"]+/).map((t) => t.toLowerCase()).filter((t) => t.length > 1 && !STOPWORDS2.has(t));
1158
1651
  }
1159
1652
  var WEIGHT_TAGS = 3;
1160
1653
  var WEIGHT_TITLE = 3;
1161
1654
  var WEIGHT_SECTIONS = 2;
1162
1655
  var WEIGHT_BODY = 1;
1656
+ var ID_MATCH_MIN_LENGTH = 3;
1163
1657
  var GRAPH_BOOST_FACTOR = 0.5;
1164
1658
  var SCORE_THRESHOLD = 0.1;
1165
1659
  function scoreSpecs(specs, task, graph) {
@@ -1179,9 +1673,15 @@ function scoreSpecs(specs, task, graph) {
1179
1673
  }
1180
1674
  const rawScores = /* @__PURE__ */ new Map();
1181
1675
  const matchedMap = /* @__PURE__ */ new Map();
1676
+ const idMatchedSet = /* @__PURE__ */ new Set();
1677
+ const taskLower = (task ?? "").toLowerCase();
1182
1678
  for (const [specId, spec] of specs) {
1183
1679
  let weightedHits = 0;
1184
1680
  const matched = /* @__PURE__ */ new Set();
1681
+ const idLower = specId.toLowerCase();
1682
+ if (idLower.length >= ID_MATCH_MIN_LENGTH && taskLower.includes(idLower)) {
1683
+ idMatchedSet.add(specId);
1684
+ }
1185
1685
  for (const keyword of keywords) {
1186
1686
  let hit = false;
1187
1687
  const tags = spec.frontmatter.tags ?? [];
@@ -1253,7 +1753,8 @@ function scoreSpecs(specs, task, graph) {
1253
1753
  const results = [];
1254
1754
  for (const [specId] of specs) {
1255
1755
  const combined = finalRawScores.get(specId) ?? 0;
1256
- const normalized = maxScore > 0 ? combined / maxScore : 0;
1756
+ const idMatched = idMatchedSet.has(specId);
1757
+ const normalized = idMatched ? 1 : maxScore > 0 ? combined / maxScore : 0;
1257
1758
  if (normalized < SCORE_THRESHOLD)
1258
1759
  continue;
1259
1760
  results.push({
@@ -1261,10 +1762,11 @@ function scoreSpecs(specs, task, graph) {
1261
1762
  score: normalized,
1262
1763
  rawScore: rawScores.get(specId) ?? 0,
1263
1764
  matchedKeywords: [...matchedMap.get(specId) ?? []],
1264
- graphBoosted: boostedSet.has(specId)
1765
+ graphBoosted: boostedSet.has(specId),
1766
+ idMatched
1265
1767
  });
1266
1768
  }
1267
- results.sort((a, b) => b.score - a.score);
1769
+ results.sort((a, b) => b.score - a.score || Number(b.idMatched ?? false) - Number(a.idMatched ?? false));
1268
1770
  return results;
1269
1771
  }
1270
1772
  function scoreSpecsByIds(specs, specIds, graph) {
@@ -1357,6 +1859,69 @@ function compressSpec(specId, type, title, status, updatedDate, parsedSections,
1357
1859
  }
1358
1860
 
1359
1861
  // ../pack/dist/allocator.js
1862
+ var HIGH_RELEVANCE = 0.75;
1863
+ var MIN_TRIM_BUDGET = 150;
1864
+ function omissionMarker(sections) {
1865
+ const names = sections.map((s) => s.heading || "(untitled)");
1866
+ const noun = names.length === 1 ? "section" : "sections";
1867
+ return `[${names.length} ${noun} omitted to fit token budget: ${names.join(", ")}]`;
1868
+ }
1869
+ function trimToBudget(compressed, budget) {
1870
+ const sections = compressed.sections;
1871
+ let reserve = 0;
1872
+ for (; ; ) {
1873
+ const effective = budget - reserve;
1874
+ const keep = new Array(sections.length).fill(false);
1875
+ let used = 0;
1876
+ let keptReal = false;
1877
+ for (let i = 0; i < sections.length; i++) {
1878
+ if (used + sections[i].tokens <= effective) {
1879
+ keep[i] = true;
1880
+ used += sections[i].tokens;
1881
+ keptReal = true;
1882
+ }
1883
+ }
1884
+ if (!keptReal)
1885
+ return null;
1886
+ const runs = [];
1887
+ for (let i = 0; i < sections.length; i++) {
1888
+ if (keep[i])
1889
+ continue;
1890
+ const start = i;
1891
+ const run = [];
1892
+ while (i < sections.length && !keep[i]) {
1893
+ run.push(sections[i]);
1894
+ i++;
1895
+ }
1896
+ i--;
1897
+ const marker = omissionMarker(run);
1898
+ runs.push({ start, sections: run, marker, markerTokens: countTokens(marker) });
1899
+ }
1900
+ const markerTokens = runs.reduce((sum, r) => sum + r.markerTokens, 0);
1901
+ if (markerTokens > reserve) {
1902
+ reserve = markerTokens;
1903
+ continue;
1904
+ }
1905
+ const out = [];
1906
+ for (let i = 0; i < sections.length; i++) {
1907
+ const run = runs.find((r) => r.start === i);
1908
+ if (run) {
1909
+ out.push({
1910
+ heading: "",
1911
+ content: run.marker,
1912
+ tokens: run.markerTokens,
1913
+ compressed: true,
1914
+ originalTokens: run.sections.reduce((sum, s) => sum + s.tokens, 0),
1915
+ omittedSections: run.sections.length
1916
+ });
1917
+ i += run.sections.length - 1;
1918
+ continue;
1919
+ }
1920
+ out.push(sections[i]);
1921
+ }
1922
+ return { spec: { ...compressed, sections: out }, tokens: used + markerTokens };
1923
+ }
1924
+ }
1360
1925
  function allocate(specs, scores, options) {
1361
1926
  const specMap = /* @__PURE__ */ new Map();
1362
1927
  for (const spec of specs) {
@@ -1394,9 +1959,9 @@ function allocate(specs, scores, options) {
1394
1959
  tokens += section.tokens;
1395
1960
  }
1396
1961
  }
1397
- items.push({ compressed, relevance: score.score, tokens });
1962
+ items.push({ compressed, relevance: score.score, tokens, idMatched: score.idMatched ?? false });
1398
1963
  }
1399
- items.sort((a, b) => b.relevance - a.relevance);
1964
+ items.sort((a, b) => b.relevance - a.relevance || Number(b.idMatched) - Number(a.idMatched));
1400
1965
  const totalTokens = items.reduce((sum, item) => sum + item.tokens, 0);
1401
1966
  const withinBudget = totalTokens <= options.budget;
1402
1967
  const included = [];
@@ -1412,17 +1977,28 @@ function allocate(specs, scores, options) {
1412
1977
  if (usedTokens + item.tokens <= options.budget) {
1413
1978
  included.push(item);
1414
1979
  usedTokens += item.tokens;
1415
- } else {
1416
- excluded.push(item);
1980
+ continue;
1417
1981
  }
1982
+ const remaining = options.budget - usedTokens;
1983
+ if ((item.idMatched || item.relevance >= HIGH_RELEVANCE) && remaining >= MIN_TRIM_BUDGET && !item.compressed.collapsed) {
1984
+ const trimmed = trimToBudget(item.compressed, remaining);
1985
+ if (trimmed) {
1986
+ included.push({ ...item, compressed: trimmed.spec, tokens: trimmed.tokens });
1987
+ usedTokens += trimmed.tokens;
1988
+ continue;
1989
+ }
1990
+ }
1991
+ excluded.push(item);
1418
1992
  }
1419
1993
  }
1420
1994
  let sectionsCompressed = 0;
1995
+ let sectionsOmitted = 0;
1421
1996
  for (const item of included) {
1422
1997
  for (const section of item.compressed.sections) {
1423
1998
  if (section.compressed) {
1424
1999
  sectionsCompressed++;
1425
2000
  }
2001
+ sectionsOmitted += section.omittedSections ?? 0;
1426
2002
  }
1427
2003
  }
1428
2004
  const allocations = [];
@@ -1452,6 +2028,7 @@ function allocate(specs, scores, options) {
1452
2028
  specsIncluded: included.length,
1453
2029
  specsExcluded: excluded.length,
1454
2030
  sectionsCompressed,
2031
+ sectionsOmitted,
1455
2032
  allocations
1456
2033
  };
1457
2034
  return {
@@ -1466,7 +2043,7 @@ function escapeXml(text) {
1466
2043
  }
1467
2044
  function formatXml(specs, stats) {
1468
2045
  const lines = [];
1469
- lines.push(`<context budget="${stats.budget}" used="${stats.used}" specs="${stats.specsIncluded}" compressed="${stats.sectionsCompressed}">`);
2046
+ lines.push(`<context budget="${stats.budget}" used="${stats.used}" specs="${stats.specsIncluded}" compressed="${stats.sectionsCompressed}" omitted="${stats.sectionsOmitted}">`);
1470
2047
  for (const spec of specs) {
1471
2048
  const alloc = stats.allocations.find((a) => a.specId === spec.specId);
1472
2049
  const relevance = alloc?.relevance ?? 0;
@@ -1525,6 +2102,7 @@ function formatJson2(specs, stats) {
1525
2102
  const output = {
1526
2103
  budget: stats.budget,
1527
2104
  used: stats.used,
2105
+ sectionsOmitted: stats.sectionsOmitted,
1528
2106
  specs: specs.map((spec) => {
1529
2107
  const alloc = stats.allocations.find((a) => a.specId === spec.specId);
1530
2108
  const relevance = alloc?.relevance ?? 0;
@@ -1768,7 +2346,8 @@ var pack_default = defineCommand3({
1768
2346
  console.log(
1769
2347
  ` Included: ${stats.specsIncluded} / ${stats.specsIncluded + stats.specsExcluded} specs`
1770
2348
  );
1771
- console.log(` Sections compressed: ${stats.sectionsCompressed}
2349
+ console.log(` Sections compressed: ${stats.sectionsCompressed}`);
2350
+ console.log(` Sections omitted: ${stats.sectionsOmitted}
1772
2351
  `);
1773
2352
  return;
1774
2353
  }
@@ -1785,7 +2364,7 @@ var pack_default = defineCommand3({
1785
2364
  }
1786
2365
  const total = stats.specsIncluded + stats.specsExcluded;
1787
2366
  process.stderr.write(
1788
- `Packed ${stats.specsIncluded}/${total} specs \u2022 ${stats.used} / ${stats.budget} tokens \u2022 ${stats.sectionsCompressed} sections compressed
2367
+ `Packed ${stats.specsIncluded}/${total} specs \u2022 ${stats.used} / ${stats.budget} tokens \u2022 ${stats.sectionsCompressed} sections compressed \u2022 ${stats.sectionsOmitted} sections omitted
1789
2368
  `
1790
2369
  );
1791
2370
  } catch (err) {
@@ -2688,10 +3267,10 @@ var STRUCTURAL_SECTIONS = /* @__PURE__ */ new Set([
2688
3267
  "API Design",
2689
3268
  "Problem Statement"
2690
3269
  ]);
2691
- function bfsDistances(startId, graph) {
3270
+ function bfsDistances(startId, relations) {
2692
3271
  const distances = /* @__PURE__ */ new Map();
2693
3272
  const queue = [];
2694
- for (const edge of graph.edges) {
3273
+ for (const edge of relations.edges) {
2695
3274
  if (edge.from === startId) {
2696
3275
  if (!distances.has(edge.to)) {
2697
3276
  distances.set(edge.to, 1);
@@ -2702,7 +3281,7 @@ function bfsDistances(startId, graph) {
2702
3281
  while (queue.length > 0) {
2703
3282
  const item = queue.shift();
2704
3283
  const currentDist = item.distance;
2705
- for (const edge of graph.edges) {
3284
+ for (const edge of relations.edges) {
2706
3285
  if (edge.from === item.id && !distances.has(edge.to)) {
2707
3286
  distances.set(edge.to, currentDist + 1);
2708
3287
  queue.push({ id: edge.to, distance: currentDist + 1 });
@@ -2719,8 +3298,8 @@ function daysBetween(dateStr) {
2719
3298
  function clamp(min, max, value) {
2720
3299
  return Math.min(max, Math.max(min, value));
2721
3300
  }
2722
- function analyzeImpact(changedSpecId, diff2, graph, allSpecs, thresholdDays = 14) {
2723
- const distanceMap = bfsDistances(changedSpecId, graph);
3301
+ function analyzeImpact(changedSpecId, diff2, relations, allSpecs, thresholdDays = 14) {
3302
+ const distanceMap = bfsDistances(changedSpecId, relations);
2724
3303
  if (distanceMap.size === 0) {
2725
3304
  return {
2726
3305
  changedSpec: changedSpecId,
@@ -2739,11 +3318,11 @@ function analyzeImpact(changedSpecId, diff2, graph, allSpecs, thresholdDays = 14
2739
3318
  const downstream = [];
2740
3319
  for (const [specId, distance] of distanceMap) {
2741
3320
  const spec = specById.get(specId);
2742
- const lastUpdated = spec?.frontmatter.updated ?? spec?.frontmatter.created ?? null;
3321
+ const lastUpdated2 = spec?.frontmatter.updated ?? spec?.frontmatter.created ?? null;
2743
3322
  const filePath = spec?.filePath ?? `specs/${specId}.md`;
2744
3323
  let staleness;
2745
- if (lastUpdated) {
2746
- const daysSinceUpdate = daysBetween(lastUpdated);
3324
+ if (lastUpdated2) {
3325
+ const daysSinceUpdate = daysBetween(lastUpdated2);
2747
3326
  staleness = clamp(0, 1, daysSinceUpdate / thresholdDays * 0.5 + structuralSectionsChanged / totalSections * 0.3 + 1 / distance * 0.2);
2748
3327
  } else {
2749
3328
  staleness = clamp(0, 1, structuralSectionsChanged / totalSections * 0.3 + 1 / distance * 0.2);
@@ -2753,8 +3332,8 @@ function analyzeImpact(changedSpecId, diff2, graph, allSpecs, thresholdDays = 14
2753
3332
  if (structuralSectionsChanged > 0) {
2754
3333
  parts.push(`${structuralSectionsChanged} structural section(s) changed`);
2755
3334
  }
2756
- if (lastUpdated) {
2757
- const days = Math.round(daysBetween(lastUpdated));
3335
+ if (lastUpdated2) {
3336
+ const days = Math.round(daysBetween(lastUpdated2));
2758
3337
  parts.push(`last updated ${days} day(s) ago`);
2759
3338
  }
2760
3339
  const reason = parts.join("; ");
@@ -2762,7 +3341,7 @@ function analyzeImpact(changedSpecId, diff2, graph, allSpecs, thresholdDays = 14
2762
3341
  specId,
2763
3342
  filePath,
2764
3343
  distance,
2765
- lastUpdated,
3344
+ lastUpdated: lastUpdated2,
2766
3345
  staleness,
2767
3346
  reason
2768
3347
  });
@@ -2894,20 +3473,24 @@ async function diffBetweenRefs(configPath, baseRef, headRef) {
2894
3473
  }
2895
3474
  const added = changed.added.map((p) => specIdByPath.get(p)).filter((id) => id !== void 0);
2896
3475
  const removed = changed.deleted.map((p) => specIdByPath.get(p)).filter((id) => id !== void 0);
2897
- const graph = buildGraph(config);
2898
3476
  const impact = [];
2899
3477
  const allSpecs = [];
2900
- for (const entry of Object.values(config.specs)) {
3478
+ const specsByEntry = /* @__PURE__ */ new Map();
3479
+ for (const [key, entry] of Object.entries(config.specs)) {
3480
+ const forEntry = [];
2901
3481
  try {
2902
3482
  const content = gitShow(headRef, entry.path, projectRoot, repoRoot);
2903
3483
  const parsed = await parseSpecFromString(content, entry.path);
3484
+ forEntry.push(parsed);
2904
3485
  allSpecs.push(parsed);
2905
3486
  } catch {
2906
3487
  }
3488
+ specsByEntry.set(key, forEntry);
2907
3489
  }
3490
+ const relations = buildRelationResolver(config, specsByEntry);
2908
3491
  const thresholdDays = config.diff?.staleness_threshold_days ?? 14;
2909
3492
  for (const diff2 of diffs) {
2910
- const analysis = analyzeImpact(diff2.specId, diff2, graph, allSpecs, thresholdDays);
3493
+ const analysis = analyzeImpact(diff2.specId, diff2, relations, allSpecs, thresholdDays);
2911
3494
  if (analysis.totalAffected > 0) {
2912
3495
  impact.push(analysis);
2913
3496
  }
@@ -2962,58 +3545,65 @@ var diff_default = defineCommand4({
2962
3545
  },
2963
3546
  async run({ args }) {
2964
3547
  try {
2965
- const result = await runDiff({
2966
- base: args.base,
2967
- head: args.head,
2968
- spec: args.spec,
2969
- format: args.format
2970
- });
2971
- if (args.format === "json") {
2972
- console.log(JSON.stringify(result, null, 2));
2973
- return;
2974
- }
2975
- if (result.diffs.length === 0 && result.added.length === 0 && result.removed.length === 0) {
2976
- console.log(" \u2713 No spec changes detected.");
2977
- return;
2978
- }
2979
- console.log(result.summary);
2980
- console.log();
2981
- for (const diff2 of result.diffs) {
2982
- console.log(` ${diff2.specId}:`);
2983
- for (const fc of diff2.frontmatter) {
2984
- const detail = fc.before !== void 0 || fc.after !== void 0 ? ` (${String(fc.before)} \u2192 ${String(fc.after)})` : "";
2985
- console.log(` ${fc.type}: ${fc.field}${detail}`);
3548
+ try {
3549
+ const result = await runDiff({
3550
+ base: args.base,
3551
+ head: args.head,
3552
+ spec: args.spec,
3553
+ format: args.format
3554
+ });
3555
+ if (args.format === "json") {
3556
+ console.log(JSON.stringify(result, null, 2));
3557
+ return;
2986
3558
  }
2987
- for (const sc of diff2.sections) {
2988
- console.log(` ${sc.type}: ${sc.heading}`);
3559
+ if (result.diffs.length === 0 && result.added.length === 0 && result.removed.length === 0) {
3560
+ console.log(" \u2713 No spec changes detected.");
3561
+ return;
2989
3562
  }
2990
- }
2991
- if (result.added.length > 0) {
2992
- console.log(`
3563
+ console.log(result.summary);
3564
+ console.log();
3565
+ for (const diff2 of result.diffs) {
3566
+ console.log(` ${diff2.specId}:`);
3567
+ for (const fc of diff2.frontmatter) {
3568
+ const detail = fc.before !== void 0 || fc.after !== void 0 ? ` (${String(fc.before)} \u2192 ${String(fc.after)})` : "";
3569
+ console.log(` ${fc.type}: ${fc.field}${detail}`);
3570
+ }
3571
+ for (const sc of diff2.sections) {
3572
+ console.log(` ${sc.type}: ${sc.heading}`);
3573
+ }
3574
+ }
3575
+ if (result.added.length > 0) {
3576
+ console.log(`
2993
3577
  Added: ${result.added.join(", ")}`);
2994
- }
2995
- if (result.removed.length > 0) {
2996
- console.log(`
3578
+ }
3579
+ if (result.removed.length > 0) {
3580
+ console.log(`
2997
3581
  Removed: ${result.removed.join(", ")}`);
2998
- }
2999
- if (result.impact.length > 0) {
3000
- console.log("\n Downstream Impact:");
3001
- for (const impact of result.impact) {
3002
- for (const d of impact.downstream) {
3003
- console.log(
3004
- ` ${d.specId} \u2014 staleness: ${d.staleness.toFixed(2)} \u2014 ${d.reason}`
3005
- );
3582
+ }
3583
+ if (result.impact.length > 0) {
3584
+ console.log("\n Downstream Impact:");
3585
+ for (const impact of result.impact) {
3586
+ for (const d of impact.downstream) {
3587
+ console.log(
3588
+ ` ${d.specId} \u2014 staleness: ${d.staleness.toFixed(2)} \u2014 ${d.reason}`
3589
+ );
3590
+ }
3006
3591
  }
3007
3592
  }
3593
+ } catch (err) {
3594
+ if (err instanceof DiffError) {
3595
+ console.error(`
3596
+ \u2717 ${err.message}
3597
+ `);
3598
+ process.exit(1);
3599
+ }
3600
+ throw err;
3008
3601
  }
3009
3602
  } catch (err) {
3010
- if (err instanceof DiffError) {
3011
- console.error(`
3603
+ console.error(`
3012
3604
  \u2717 ${err.message}
3013
3605
  `);
3014
- process.exit(1);
3015
- }
3016
- throw err;
3606
+ process.exit(1);
3017
3607
  }
3018
3608
  }
3019
3609
  });
@@ -3089,6 +3679,7 @@ async function runStatus(_options = {}) {
3089
3679
  let verdict = "healthy";
3090
3680
  if (errors > 0) verdict = "errors";
3091
3681
  else if (warnings > 0 || staleSpecs.length > 0) verdict = "warnings";
3682
+ else if (specs.length === 0) verdict = "unassessed";
3092
3683
  return {
3093
3684
  project: config.project?.name ?? "unknown",
3094
3685
  specCount: specs.length,
@@ -3109,38 +3700,52 @@ var status_default = defineCommand5({
3109
3700
  }
3110
3701
  },
3111
3702
  async run({ args }) {
3112
- const result = await runStatus({ format: args.format });
3113
- if (args.format === "json") {
3114
- console.log(JSON.stringify(result, null, 2));
3115
- return;
3116
- }
3117
- if (args.format === "github") {
3118
- for (const s of result.staleSpecs) {
3119
- console.log(
3120
- `::warning::Spec "${s.specId}" is stale (${s.daysSinceUpdate} days since update)`
3121
- );
3703
+ try {
3704
+ const result = await runStatus({ format: args.format });
3705
+ if (args.format === "json") {
3706
+ console.log(JSON.stringify(result, null, 2));
3707
+ return;
3122
3708
  }
3123
- for (const issue of result.integrityIssues) {
3124
- console.log(`::error::${issue}`);
3709
+ if (args.format === "github") {
3710
+ for (const s of result.staleSpecs) {
3711
+ console.log(
3712
+ `::warning::Spec "${s.specId}" is stale (${s.daysSinceUpdate} days since update)`
3713
+ );
3714
+ }
3715
+ for (const issue of result.integrityIssues) {
3716
+ console.log(`::error::${issue}`);
3717
+ }
3718
+ return;
3125
3719
  }
3126
- return;
3127
- }
3128
- const icon = result.verdict === "healthy" ? "\u2713" : result.verdict === "warnings" ? "\u26A0" : "\u2717";
3129
- console.log(`
3720
+ const icon = result.verdict === "healthy" ? "\u2713" : result.verdict === "warnings" || result.verdict === "unassessed" ? "\u26A0" : "\u2717";
3721
+ console.log(`
3130
3722
  ${icon} ${result.project} \u2014 ${result.verdict}`);
3131
- console.log(
3132
- ` ${result.specCount} specs: ${Object.entries(result.byStatus).map(([k, v]) => `${v} ${k}`).join(", ")}`
3133
- );
3134
- console.log(` Lint: ${result.lintHealth.errors} errors, ${result.lintHealth.warnings} warnings`);
3135
- if (result.staleSpecs.length > 0) {
3723
+ if (result.verdict === "unassessed") {
3724
+ console.log(
3725
+ " No specs resolved \u2014 nothing was assessed. Check the spec paths in spec.config.yaml."
3726
+ );
3727
+ }
3136
3728
  console.log(
3137
- ` Stale: ${result.staleSpecs.map((s) => `${s.specId} (${s.daysSinceUpdate}d)`).join(", ")}`
3729
+ ` ${result.specCount} specs: ${Object.entries(result.byStatus).map(([k, v]) => `${v} ${k}`).join(", ")}`
3138
3730
  );
3731
+ console.log(
3732
+ ` Lint: ${result.lintHealth.errors} errors, ${result.lintHealth.warnings} warnings`
3733
+ );
3734
+ if (result.staleSpecs.length > 0) {
3735
+ console.log(
3736
+ ` Stale: ${result.staleSpecs.map((s) => `${s.specId} (${s.daysSinceUpdate}d)`).join(", ")}`
3737
+ );
3738
+ }
3739
+ if (result.integrityIssues.length > 0) {
3740
+ console.log(` Issues: ${result.integrityIssues.join("; ")}`);
3741
+ }
3742
+ console.log();
3743
+ } catch (err) {
3744
+ console.error(`
3745
+ \u2717 ${err.message}
3746
+ `);
3747
+ process.exit(1);
3139
3748
  }
3140
- if (result.integrityIssues.length > 0) {
3141
- console.log(` Issues: ${result.integrityIssues.join("; ")}`);
3142
- }
3143
- console.log();
3144
3749
  }
3145
3750
  });
3146
3751
 
@@ -3202,16 +3807,23 @@ var changelog_default = defineCommand6({
3202
3807
  },
3203
3808
  async run({ args }) {
3204
3809
  try {
3205
- const output = await runChangelog(args);
3206
- console.log(output);
3207
- } catch (err) {
3208
- if (err instanceof DiffError) {
3209
- console.error(`
3810
+ try {
3811
+ const output = await runChangelog(args);
3812
+ console.log(output);
3813
+ } catch (err) {
3814
+ if (err instanceof DiffError) {
3815
+ console.error(`
3210
3816
  \u2717 ${err.message}
3211
3817
  `);
3212
- process.exit(1);
3818
+ process.exit(1);
3819
+ }
3820
+ throw err;
3213
3821
  }
3214
- throw err;
3822
+ } catch (err) {
3823
+ console.error(`
3824
+ \u2717 ${err.message}
3825
+ `);
3826
+ process.exit(1);
3215
3827
  }
3216
3828
  }
3217
3829
  });
@@ -3274,35 +3886,42 @@ var explain_default = defineCommand7({
3274
3886
  format: { type: "string", description: "Output format: pretty, json", default: "pretty" }
3275
3887
  },
3276
3888
  async run({ args }) {
3277
- const result = await runExplain({ format: args.format });
3278
- if (args.format === "json") {
3279
- console.log(JSON.stringify(result, null, 2));
3280
- return;
3281
- }
3282
- console.log(`
3889
+ try {
3890
+ const result = await runExplain({ format: args.format });
3891
+ if (args.format === "json") {
3892
+ console.log(JSON.stringify(result, null, 2));
3893
+ return;
3894
+ }
3895
+ console.log(`
3283
3896
  ${result.project}`);
3284
- if (result.description) {
3285
- console.log(` ${result.description}`);
3286
- }
3287
- console.log(
3288
- `
3897
+ if (result.description) {
3898
+ console.log(` ${result.description}`);
3899
+ }
3900
+ console.log(
3901
+ `
3289
3902
  ${result.specCount} specs: ${Object.entries(result.byType).map(([k, v]) => `${v} ${k}`).join(", ")}`
3290
- );
3291
- console.log(
3292
- ` Status: ${Object.entries(result.byStatus).map(([k, v]) => `${v} ${k}`).join(", ")}`
3293
- );
3294
- console.log("\n Specs:");
3295
- for (const spec of result.specs) {
3296
- console.log(` ${spec.id} (${spec.type}, ${spec.status}) \u2014 ${spec.title}`);
3297
- if (spec.firstLine) {
3298
- console.log(` ${spec.firstLine}`);
3299
- }
3300
- }
3301
- console.log("\n Dependencies:");
3302
- for (const line of result.graph) {
3303
- console.log(` ${line}`);
3304
- }
3305
- console.log();
3903
+ );
3904
+ console.log(
3905
+ ` Status: ${Object.entries(result.byStatus).map(([k, v]) => `${v} ${k}`).join(", ")}`
3906
+ );
3907
+ console.log("\n Specs:");
3908
+ for (const spec of result.specs) {
3909
+ console.log(` ${spec.id} (${spec.type}, ${spec.status}) \u2014 ${spec.title}`);
3910
+ if (spec.firstLine) {
3911
+ console.log(` ${spec.firstLine}`);
3912
+ }
3913
+ }
3914
+ console.log("\n Dependencies:");
3915
+ for (const line of result.graph) {
3916
+ console.log(` ${line}`);
3917
+ }
3918
+ console.log();
3919
+ } catch (err) {
3920
+ console.error(`
3921
+ \u2717 ${err.message}
3922
+ `);
3923
+ process.exit(1);
3924
+ }
3306
3925
  }
3307
3926
  });
3308
3927
  export {