kibi-mcp 0.3.0 → 0.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,292 +0,0 @@
1
- import { escapeAtom } from "kibi-cli/prolog/codec";
2
- import { parseAtomList, parsePairList } from "./prolog-list.js";
3
- const RULES = [
4
- "transitively_implements",
5
- "transitively_depends",
6
- "impacted_by_change",
7
- "affected_symbols",
8
- "coverage_gap",
9
- "untested_symbols",
10
- "stale",
11
- "orphaned",
12
- "conflicting",
13
- "deprecated_still_used",
14
- "current_adr",
15
- "adr_chain",
16
- "superseded_by",
17
- "domain_contradictions",
18
- ];
19
- export async function handleKbDerive(prolog, args) {
20
- const params = args.params ?? {};
21
- const { rule } = args;
22
- if (!RULES.includes(rule)) {
23
- throw new Error(`Unsupported rule '${rule}'`);
24
- }
25
- let rows = [];
26
- switch (rule) {
27
- case "transitively_implements":
28
- rows = await deriveTransitivelyImplements(prolog, params);
29
- break;
30
- case "transitively_depends":
31
- rows = await deriveTransitivelyDepends(prolog, params);
32
- break;
33
- case "impacted_by_change":
34
- rows = await deriveImpactedByChange(prolog, params);
35
- break;
36
- case "affected_symbols":
37
- rows = await deriveAffectedSymbols(prolog, params);
38
- break;
39
- case "coverage_gap":
40
- rows = await deriveCoverageGap(prolog, params);
41
- break;
42
- case "untested_symbols":
43
- rows = await deriveUntestedSymbols(prolog);
44
- break;
45
- case "stale":
46
- rows = await deriveStale(prolog, params);
47
- break;
48
- case "orphaned":
49
- rows = await deriveOrphaned(prolog, params);
50
- break;
51
- case "conflicting":
52
- rows = await deriveConflicting(prolog, params);
53
- break;
54
- case "deprecated_still_used":
55
- rows = await deriveDeprecatedStillUsed(prolog, params);
56
- break;
57
- case "current_adr":
58
- rows = await deriveCurrentAdr(prolog);
59
- break;
60
- case "adr_chain":
61
- rows = await deriveAdrChain(prolog, params);
62
- break;
63
- case "superseded_by":
64
- rows = await deriveSupersededBy(prolog, params);
65
- break;
66
- case "domain_contradictions":
67
- rows = await deriveDomainContradictions(prolog);
68
- break;
69
- }
70
- return {
71
- content: [
72
- {
73
- type: "text",
74
- text: `Derived ${rows.length} row(s) for rule '${rule}'.`,
75
- },
76
- ],
77
- structuredContent: {
78
- rule,
79
- params,
80
- count: rows.length,
81
- rows,
82
- provenance: {
83
- predicate: rule,
84
- deterministic: true,
85
- },
86
- },
87
- };
88
- }
89
- async function deriveTransitivelyImplements(prolog, params) {
90
- const symbolFilter = asOptionalString(params.symbol);
91
- const reqFilter = asOptionalString(params.req);
92
- const cond = makeConjunction([
93
- symbolFilter ? `Symbol='${escapeAtom(symbolFilter)}'` : "",
94
- reqFilter ? `Req='${escapeAtom(reqFilter)}'` : "",
95
- ]);
96
- const goal = `setof([Symbol,Req], (transitively_implements(Symbol, Req)${cond}), Rows)`;
97
- const pairs = await queryPairRows(prolog, goal, "Rows");
98
- return pairs.map(([symbol, req]) => ({ symbol, req }));
99
- }
100
- async function deriveTransitivelyDepends(prolog, params) {
101
- const req1Filter = asOptionalString(params.req1);
102
- const req2Filter = asOptionalString(params.req2);
103
- const cond = makeConjunction([
104
- req1Filter ? `Req1='${escapeAtom(req1Filter)}'` : "",
105
- req2Filter ? `Req2='${escapeAtom(req2Filter)}'` : "",
106
- ]);
107
- const goal = `setof([Req1,Req2], (transitively_depends(Req1, Req2)${cond}), Rows)`;
108
- const pairs = await queryPairRows(prolog, goal, "Rows");
109
- return pairs.map(([req1, req2]) => ({ req1, req2 }));
110
- }
111
- async function deriveImpactedByChange(prolog, params) {
112
- const changed = asRequiredString(params.changed, "params.changed is required");
113
- const goal = `setof(Entity, impacted_by_change(Entity, '${escapeAtom(changed)}'), Rows)`;
114
- const entities = await queryAtomRows(prolog, goal, "Rows");
115
- return entities.map((entity) => ({ changed, entity }));
116
- }
117
- async function deriveAffectedSymbols(prolog, params) {
118
- const req = asRequiredString(params.req, "params.req is required");
119
- const goal = `affected_symbols('${escapeAtom(req)}', Symbols)`;
120
- const result = await prolog.query(goal);
121
- if (!result.success || !result.bindings.Symbols) {
122
- return [];
123
- }
124
- const symbols = parseAtomList(result.bindings.Symbols);
125
- return symbols.map((symbol) => ({ req, symbol }));
126
- }
127
- async function deriveCoverageGap(prolog, params) {
128
- const reqFilter = asOptionalString(params.req);
129
- const cond = reqFilter ? `Req='${escapeAtom(reqFilter)}'` : "";
130
- const goal = `setof([Req,Reason], (coverage_gap(Req, Reason)${makeConjunction([cond])}), Rows)`;
131
- const pairs = await queryPairRows(prolog, goal, "Rows");
132
- return pairs.map(([req, reason]) => ({ req, reason }));
133
- }
134
- async function deriveUntestedSymbols(prolog) {
135
- const result = await prolog.query("untested_symbols(Symbols)");
136
- if (!result.success || !result.bindings.Symbols) {
137
- return [];
138
- }
139
- const symbols = parseAtomList(result.bindings.Symbols);
140
- return symbols.map((symbol) => ({ symbol }));
141
- }
142
- async function deriveStale(prolog, params) {
143
- const maxAgeDays = Number(params.max_age_days ?? params.maxAgeDays);
144
- if (!Number.isFinite(maxAgeDays)) {
145
- throw new Error("params.max_age_days is required and must be numeric");
146
- }
147
- const entityFilter = asOptionalString(params.entity);
148
- const cond = entityFilter ? `Entity='${escapeAtom(entityFilter)}'` : "";
149
- const goal = `setof(Entity, (stale(Entity, ${maxAgeDays})${makeConjunction([cond])}), Rows)`;
150
- const entities = await queryAtomRows(prolog, goal, "Rows");
151
- return entities.map((entity) => ({ entity, max_age_days: maxAgeDays }));
152
- }
153
- async function deriveOrphaned(prolog, params) {
154
- const symbolFilter = asOptionalString(params.symbol);
155
- const cond = symbolFilter ? `Symbol='${escapeAtom(symbolFilter)}'` : "";
156
- const goal = `setof(Symbol, (orphaned(Symbol)${makeConjunction([cond])}), Rows)`;
157
- const symbols = await queryAtomRows(prolog, goal, "Rows");
158
- return symbols.map((symbol) => ({ symbol }));
159
- }
160
- async function deriveConflicting(prolog, params) {
161
- const adr1Filter = asOptionalString(params.adr1);
162
- const adr2Filter = asOptionalString(params.adr2);
163
- const cond = makeConjunction([
164
- adr1Filter ? `Adr1='${escapeAtom(adr1Filter)}'` : "",
165
- adr2Filter ? `Adr2='${escapeAtom(adr2Filter)}'` : "",
166
- ]);
167
- const goal = `setof([Adr1,Adr2], (conflicting(Adr1, Adr2)${cond}), Rows)`;
168
- const pairs = await queryPairRows(prolog, goal, "Rows");
169
- return pairs.map(([adr1, adr2]) => ({ adr1, adr2 }));
170
- }
171
- async function deriveDeprecatedStillUsed(prolog, params) {
172
- const adrFilter = asOptionalString(params.adr);
173
- const goal = adrFilter
174
- ? `deprecated_still_used('${escapeAtom(adrFilter)}', Symbols)`
175
- : "setof([Adr,Symbols], deprecated_still_used(Adr, Symbols), Rows)";
176
- if (adrFilter) {
177
- const result = await prolog.query(goal);
178
- if (!result.success || !result.bindings.Symbols) {
179
- return [];
180
- }
181
- return [
182
- { adr: adrFilter, symbols: parseAtomList(result.bindings.Symbols) },
183
- ];
184
- }
185
- const pairs = await queryPairRows(prolog, goal, "Rows");
186
- return pairs.map(([adr, symbolsRaw]) => ({
187
- adr,
188
- symbols: parseAtomList(symbolsRaw),
189
- }));
190
- }
191
- async function queryAtomRows(prolog, goal, bindingName) {
192
- const result = await prolog.query(goal);
193
- if (!result.success || !result.bindings[bindingName]) {
194
- return [];
195
- }
196
- return parseAtomList(result.bindings[bindingName]);
197
- }
198
- async function queryPairRows(prolog, goal, bindingName) {
199
- const result = await prolog.query(goal);
200
- if (!result.success || !result.bindings[bindingName]) {
201
- return [];
202
- }
203
- return parsePairList(result.bindings[bindingName]);
204
- }
205
- function asOptionalString(value) {
206
- return typeof value === "string" && value.length > 0 ? value : undefined;
207
- }
208
- function asRequiredString(value, message) {
209
- if (typeof value !== "string" || value.length === 0) {
210
- throw new Error(message);
211
- }
212
- return value;
213
- }
214
- function makeConjunction(parts) {
215
- const filtered = parts.filter((part) => part.length > 0);
216
- if (filtered.length === 0) {
217
- return "";
218
- }
219
- return `, ${filtered.join(", ")}`;
220
- }
221
- async function deriveCurrentAdr(prolog) {
222
- // Query for all current ADRs and their titles
223
- const result = await prolog.query("setof([Id,TitleAtom], (kb_entity(Id, adr, Props), memberchk(title=Title, Props), normalize_term_atom(Title, TitleAtom), current_adr(Id)), Rows)");
224
- if (!result.success || !result.bindings.Rows) {
225
- return [];
226
- }
227
- const pairs = parsePairList(result.bindings.Rows);
228
- return pairs.map(([id, title]) => ({ id, title }));
229
- }
230
- async function deriveAdrChain(prolog, params) {
231
- const adr = asRequiredString(params.adr, "params.adr is required");
232
- // Query for the full chain including status
233
- const result = await prolog.query(`findall([Id,TitleAtom,StatusAtom], (kb_entity(Id, adr, Props), memberchk(title=Title, Props), normalize_term_atom(Title, TitleAtom), memberchk(status=Status, Props), normalize_term_atom(Status, StatusAtom), adr_chain('${escapeAtom(adr)}', Chain), member(Id, Chain)), Rows)`);
234
- if (!result.success || !result.bindings.Rows) {
235
- return [];
236
- }
237
- // Parse triplets and include status
238
- const triplets = parseTripleList(result.bindings.Rows);
239
- return triplets.map(([id, title, status]) => ({ id, title, status }));
240
- }
241
- async function deriveSupersededBy(prolog, params) {
242
- const adr = asRequiredString(params.adr, "params.adr is required");
243
- // Query for direct supersession
244
- const result = await prolog.query(`superseded_by('${escapeAtom(adr)}', NewAdr), kb_entity(NewAdr, adr, Props), memberchk(title=Title, Props), normalize_term_atom(Title, TitleAtom)`);
245
- if (!result.success ||
246
- !result.bindings.NewAdr ||
247
- !result.bindings.TitleAtom) {
248
- return [];
249
- }
250
- const newAdr = String(result.bindings.NewAdr).replace(/^'|'$/g, "");
251
- const newAdrTitle = String(result.bindings.TitleAtom).replace(/^'|'$/g, "");
252
- return [
253
- {
254
- adr,
255
- successor_id: newAdr,
256
- successor_title: newAdrTitle,
257
- },
258
- ];
259
- }
260
- function parseTripleList(raw) {
261
- const match = raw.match(/\[(.*)\]/);
262
- if (!match) {
263
- return [];
264
- }
265
- const content = match[1].trim();
266
- if (!content) {
267
- return [];
268
- }
269
- // Parse triplets: [[a,b,c],[x,y,z],...]
270
- const triplets = [];
271
- const tripletRegex = /\[([^,]+),([^,]+),([^\]]+)\]/g;
272
- let tripletMatch;
273
- do {
274
- tripletMatch = tripletRegex.exec(content);
275
- if (tripletMatch !== null) {
276
- triplets.push([
277
- tripletMatch[1].trim().replace(/^'|'$/g, ""),
278
- tripletMatch[2].trim().replace(/^'|'$/g, ""),
279
- tripletMatch[3].trim().replace(/^'|'$/g, ""),
280
- ]);
281
- }
282
- } while (tripletMatch !== null);
283
- return triplets;
284
- }
285
- async function deriveDomainContradictions(prolog) {
286
- const result = await prolog.query("setof([ReqA,ReqB,Reason], contradicting_reqs(ReqA, ReqB, Reason), Rows)");
287
- if (!result.success || !result.bindings.Rows) {
288
- return [];
289
- }
290
- const rows = parseTripleList(result.bindings.Rows);
291
- return rows.map(([reqA, reqB, reason]) => ({ reqA, reqB, reason }));
292
- }
@@ -1,51 +0,0 @@
1
- import { escapeAtom } from "kibi-cli/prolog/codec";
2
- import { parseAtomList } from "./prolog-list.js";
3
- export async function handleKbImpact(prolog, args) {
4
- if (!args.entity || typeof args.entity !== "string") {
5
- throw new Error("'entity' is required");
6
- }
7
- const goal = `setof(Id, (impacted_by_change(Id, '${escapeAtom(args.entity)}'), Id \\= '${escapeAtom(args.entity)}'), Impacted)`;
8
- const impactedIds = await queryAtoms(prolog, goal, "Impacted");
9
- const impacted = [];
10
- for (const id of impactedIds) {
11
- const type = await getEntityType(prolog, id);
12
- impacted.push({ id, type: type ?? "unknown" });
13
- }
14
- impacted.sort((a, b) => {
15
- if (a.type === b.type) {
16
- return a.id.localeCompare(b.id);
17
- }
18
- return a.type.localeCompare(b.type);
19
- });
20
- return {
21
- content: [
22
- {
23
- type: "text",
24
- text: `Impact analysis for '${args.entity}': ${impacted.length} impacted entity(s).`,
25
- },
26
- ],
27
- structuredContent: {
28
- entity: args.entity,
29
- impacted,
30
- count: impacted.length,
31
- provenance: {
32
- predicate: "impacted_by_change",
33
- deterministic: true,
34
- },
35
- },
36
- };
37
- }
38
- async function queryAtoms(prolog, goal, bindingName) {
39
- const result = await prolog.query(goal);
40
- if (!result.success || !result.bindings[bindingName]) {
41
- return [];
42
- }
43
- return parseAtomList(result.bindings[bindingName]);
44
- }
45
- async function getEntityType(prolog, id) {
46
- const result = await prolog.query(`kb_entity('${escapeAtom(id)}', Type, _)`);
47
- if (!result.success || !result.bindings.Type) {
48
- return null;
49
- }
50
- return result.bindings.Type;
51
- }
@@ -1,58 +0,0 @@
1
- /**
2
- * Handle kb_list_entity_types tool calls
3
- * Returns the static list of supported KB entity type names (req, scenario, test, adr, flag, event, symbol, fact).
4
- */
5
- export async function handleKbListEntityTypes() {
6
- return {
7
- content: [
8
- {
9
- type: "text",
10
- text: "Available entity types: req, scenario, test, adr, flag, event, symbol, fact",
11
- },
12
- ],
13
- structuredContent: {
14
- types: [
15
- "req",
16
- "scenario",
17
- "test",
18
- "adr",
19
- "flag",
20
- "event",
21
- "symbol",
22
- "fact",
23
- ],
24
- },
25
- };
26
- }
27
- /**
28
- * Handle kb_list_relationship_types tool calls
29
- * Returns the static list of supported KB relationship type names (depends_on, specified_by, verified_by, etc.).
30
- */
31
- export async function handleKbListRelationshipTypes() {
32
- return {
33
- content: [
34
- {
35
- type: "text",
36
- text: "Available relationship types: depends_on, specified_by, verified_by, validates, implements, covered_by, constrained_by, constrains, requires_property, guards, publishes, consumes, supersedes, relates_to",
37
- },
38
- ],
39
- structuredContent: {
40
- types: [
41
- "depends_on",
42
- "specified_by",
43
- "verified_by",
44
- "validates",
45
- "implements",
46
- "covered_by",
47
- "constrained_by",
48
- "constrains",
49
- "requires_property",
50
- "guards",
51
- "publishes",
52
- "consumes",
53
- "supersedes",
54
- "relates_to",
55
- ],
56
- },
57
- };
58
- }
@@ -1,159 +0,0 @@
1
- const VALID_REL_TYPES = [
2
- "depends_on",
3
- "specified_by",
4
- "verified_by",
5
- "validates",
6
- "implements",
7
- "covered_by",
8
- "constrained_by",
9
- "constrains",
10
- "requires_property",
11
- "guards",
12
- "publishes",
13
- "consumes",
14
- "supersedes",
15
- "relates_to",
16
- ];
17
- /**
18
- * Handle kb_query_relationships tool calls.
19
- * Queries the kb_relationship/3 predicate which has arity (Type, From, To).
20
- *
21
- * Note: kb_relationship/3 requires RelType to be bound (atom_concat/3 in Prolog
22
- * does not work with an unbound first argument). When no type filter is given,
23
- * we iterate over all known type values.
24
- */
25
- export async function handleKbQueryRelationships(prolog, args) {
26
- const { from, to, type } = args;
27
- if (type && !VALID_REL_TYPES.includes(type)) {
28
- throw new Error(`Invalid relationship type '${type}'. Valid types: ${VALID_REL_TYPES.join(", ")}`);
29
- }
30
- // When type is specified we run one query; otherwise iterate all known types
31
- // (kb_relationship/3 requires the type to be bound due to atom_concat/3 in Prolog).
32
- const typesToQuery = type ? [type] : VALID_REL_TYPES;
33
- const allRelationships = [];
34
- for (const relType of typesToQuery) {
35
- // We collect what we actually need based on which args are bound.
36
- // When both from and to are specified, we just need to check existence.
37
- // Otherwise collect the unbound sides.
38
- let goal;
39
- if (from && to) {
40
- // Check if the specific triple exists
41
- goal = `(kb_relationship('${relType}', '${from}', '${to}') -> Results = [['${from}','${to}']] ; Results = [])`;
42
- }
43
- else if (from) {
44
- goal = `findall(To, kb_relationship('${relType}', '${from}', To), Results)`;
45
- }
46
- else if (to) {
47
- goal = `findall(From, kb_relationship('${relType}', From, '${to}'), Results)`;
48
- }
49
- else {
50
- goal = `findall([From,To], kb_relationship('${relType}', From, To), Results)`;
51
- }
52
- const queryResult = await prolog.query(goal);
53
- if (!queryResult.success) {
54
- throw new Error(queryResult.error || "Relationship query failed");
55
- }
56
- if (queryResult.bindings.Results) {
57
- const raw = queryResult.bindings.Results;
58
- if (from && to) {
59
- // Results is either [[from,to]] or []
60
- const pairs = parsePairResults(raw);
61
- for (const [pairFrom, pairTo] of pairs) {
62
- allRelationships.push({ relType, from: pairFrom, to: pairTo });
63
- }
64
- }
65
- else if (from) {
66
- // Results is [To, To, ...]
67
- const ids = parseIdList(raw);
68
- for (const toId of ids) {
69
- allRelationships.push({ relType, from, to: toId });
70
- }
71
- }
72
- else if (to) {
73
- // Results is [From, From, ...]
74
- const ids = parseIdList(raw);
75
- for (const fromId of ids) {
76
- allRelationships.push({ relType, from: fromId, to });
77
- }
78
- }
79
- else {
80
- // Results is [[From,To], ...]
81
- const pairs = parsePairResults(raw);
82
- for (const [pairFrom, pairTo] of pairs) {
83
- allRelationships.push({ relType, from: pairFrom, to: pairTo });
84
- }
85
- }
86
- }
87
- }
88
- const text = allRelationships.length === 0
89
- ? "No relationships found."
90
- : `Found ${allRelationships.length} relationship(s): ${allRelationships
91
- .map((r) => `${r.from} -[${r.relType}]-> ${r.to}`)
92
- .join(", ")}`;
93
- return {
94
- content: [{ type: "text", text }],
95
- structuredContent: {
96
- relationships: allRelationships,
97
- count: allRelationships.length,
98
- },
99
- };
100
- }
101
- /**
102
- * Parse a flat Prolog list of atoms "[A,B,C]" into a string array.
103
- */
104
- function parseIdList(raw) {
105
- const cleaned = raw.trim();
106
- if (cleaned === "[]" || cleaned === "")
107
- return [];
108
- const inner = cleaned.replace(/^\[/, "").replace(/\]$/, "");
109
- return inner
110
- .split(",")
111
- .map((s) => s.trim().replace(/^'|'$/g, "").replace(/^"|"$/g, ""))
112
- .filter(Boolean);
113
- }
114
- /**
115
- * Parse Prolog findall result "[[From,To],...]" into [from, to] pairs.
116
- */
117
- function parsePairResults(raw) {
118
- const cleaned = raw.trim();
119
- if (cleaned === "[]" || cleaned === "")
120
- return [];
121
- const inner = cleaned.replace(/^\[/, "").replace(/\]$/, "");
122
- const pairs = [];
123
- let depth = 0;
124
- let current = "";
125
- for (let i = 0; i < inner.length; i++) {
126
- const ch = inner[i];
127
- if (ch === "[") {
128
- depth++;
129
- current += ch;
130
- }
131
- else if (ch === "]") {
132
- depth--;
133
- current += ch;
134
- if (depth === 0) {
135
- const pair = parsePair(current.trim());
136
- if (pair)
137
- pairs.push(pair);
138
- current = "";
139
- }
140
- }
141
- else if (ch === "," && depth === 0) {
142
- // top-level separator between pairs — skip
143
- }
144
- else {
145
- current += ch;
146
- }
147
- }
148
- return pairs;
149
- }
150
- function parsePair(pairStr) {
151
- // expect "[From,To]"
152
- const inner = pairStr.replace(/^\[/, "").replace(/\]$/, "").trim();
153
- const parts = inner
154
- .split(",")
155
- .map((s) => s.trim().replace(/^'|'$/g, "").replace(/^"|"$/g, ""));
156
- if (parts.length < 2)
157
- return null;
158
- return [parts[0], parts[1]];
159
- }
@@ -1,121 +0,0 @@
1
- import { parseAtomList } from "./prolog-list.js";
2
- /**
3
- * Handle analyze_shared_facts tool calls
4
- * Analyzes requirements to suggest shared domain facts for extraction
5
- */
6
- export async function handleSuggestSharedFacts(prolog, args) {
7
- const minFreq = args.min_frequency ?? 2;
8
- try {
9
- // Query all requirements with their text properties
10
- const reqsResult = await prolog.query("findall([Id,Title], (kb_entity(Id, req, Props), memberchk(title=Title, Props)), Reqs)");
11
- if (!reqsResult.success || !reqsResult.bindings.Reqs) {
12
- return {
13
- content: [{ type: "text", text: "No requirements found in KB" }],
14
- structuredContent: { suggestions: [], count: 0 },
15
- };
16
- }
17
- const reqsList = parseAtomList(reqsResult.bindings.Reqs);
18
- const requirements = [];
19
- // Parse the list-of-lists format from Prolog
20
- const reqMatch = reqsList.join("").matchAll(/\[([^,]+),([^\]]+)\]/g);
21
- if (reqMatch) {
22
- for (const match of reqMatch) {
23
- const id = match[1].trim().replace(/^'|'$/g, "");
24
- const title = match[2].trim().replace(/^'|'$/g, "");
25
- requirements.push({ id, title, description: title });
26
- }
27
- }
28
- // Query all existing facts for context
29
- const factsResult = await prolog.query("findall([Id,Title], (kb_entity(Id, fact, Props), memberchk(title=Title, Props)), Facts)");
30
- if (!factsResult.success || !factsResult.bindings.Facts) {
31
- return {
32
- content: [{ type: "text", text: "No facts found in KB" }],
33
- structuredContent: { suggestions: [], count: 0 },
34
- };
35
- }
36
- const factsList = parseAtomList(factsResult.bindings.Facts);
37
- const existingFacts = new Set();
38
- const factMatch = factsList.join("").matchAll(/\[([^,]+),([^\]]+)\]/g);
39
- if (factMatch) {
40
- for (const match of factMatch) {
41
- const title = match[2].trim().replace(/^'|'$/g, "");
42
- existingFacts.add(title.toLowerCase());
43
- }
44
- }
45
- // Extract and analyze domain concepts from requirements
46
- const suggestions = analyzeSharedConcepts(requirements, existingFacts, minFreq);
47
- return {
48
- content: [
49
- {
50
- type: "text",
51
- text: `Found ${suggestions.length} potential shared fact(s) to consider creating.`,
52
- },
53
- ],
54
- structuredContent: {
55
- suggestions,
56
- count: suggestions.length,
57
- },
58
- };
59
- }
60
- catch (error) {
61
- const message = error instanceof Error ? error.message : String(error);
62
- throw new Error(`Shared facts analysis failed: ${message}`);
63
- }
64
- }
65
- /**
66
- * Lightweight heuristic to identify shared domain concepts
67
- * Focuses on:
68
- * - Capitalized terms (possible domain concepts)
69
- * - Repeated phrases across multiple requirements
70
- * - Excludes existing facts
71
- */
72
- function analyzeSharedConcepts(requirements, existingFacts, minFreq) {
73
- const conceptCounts = new Map();
74
- for (const req of requirements) {
75
- const originalText = `${req.title} ${req.description || ""}`;
76
- const text = originalText.toLowerCase();
77
- // Extract capitalized terms (potential domain concepts)
78
- // Pattern: words starting with capital letters that aren't at sentence start
79
- const capitalizedTerms = originalText.matchAll(/\b([A-Z][a-z]+)\b/g);
80
- // Extract repeated phrases (2+ words)
81
- // Extract repeated phrases (2+ words)
82
- const words = text.split(/\s+/).filter((w) => w.length > 3);
83
- for (let i = 0; i < words.length - 1; i++) {
84
- const phrase = `${words[i]} ${words[i + 1]}`;
85
- if (!conceptCounts.has(phrase)) {
86
- conceptCounts.set(phrase, new Set());
87
- }
88
- conceptCounts.get(phrase).add(req.id);
89
- }
90
- // Also track individual capitalized terms
91
- for (const match of capitalizedTerms) {
92
- const lowerTerm = match[1].toLowerCase(); // Get the captured group
93
- if (!conceptCounts.has(lowerTerm)) {
94
- conceptCounts.set(lowerTerm, new Set());
95
- }
96
- conceptCounts.get(lowerTerm).add(req.id);
97
- }
98
- }
99
- // Generate suggestions
100
- const suggestions = [];
101
- for (const [concept, reqIds] of conceptCounts) {
102
- if (reqIds.size >= minFreq) {
103
- // Skip if this concept already exists as a fact
104
- if (!existingFacts.has(concept)) {
105
- suggestions.push({
106
- concept: capitalizeConcept(concept),
107
- mentions: reqIds.size,
108
- requirements: Array.from(reqIds),
109
- });
110
- }
111
- }
112
- }
113
- // Sort by frequency (most mentioned first)
114
- return suggestions.sort((a, b) => b.mentions - a.mentions);
115
- }
116
- function capitalizeConcept(concept) {
117
- return concept
118
- .split(/\s+/)
119
- .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
120
- .join(" ");
121
- }