kibi-mcp 0.2.4 → 0.3.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.
@@ -1,27 +1,4 @@
1
- /*
2
- Kibi — repo-local, per-branch, queryable long-term memory for software projects
3
- Copyright (C) 2026 Piotr Franczyk
4
-
5
- This program is free software: you can redistribute it and/or modify
6
- it under the terms of the GNU Affero General Public License as published by
7
- the Free Software Foundation, either version 3 of the License, or
8
- (at your option) any later version.
9
-
10
- This program is distributed in the hope that it will be useful,
11
- but WITHOUT ANY WARRANTY; without even the implied warranty of
12
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
- GNU Affero General Public License for more details.
14
-
15
- You should have received a copy of the GNU Affero General Public License
16
- along with this program. If not, see <https://www.gnu.org/licenses/>.
17
- */
18
- /**
19
- * Escape a string for embedding inside a single-quoted Prolog atom.
20
- * Doubles single-quote characters per ISO Prolog standard.
21
- */
22
- function escapeAtomContent(value) {
23
- return value.replace(/'/g, "''");
24
- }
1
+ import { escapeAtomContent, parseEntityFromBinding, parseEntityFromList, parseListOfLists, } from "kibi-cli/prolog/codec";
25
2
  export const VALID_ENTITY_TYPES = [
26
3
  "req",
27
4
  "scenario",
@@ -174,234 +151,3 @@ function dedupeEntities(entities) {
174
151
  }
175
152
  return deduped;
176
153
  }
177
- /**
178
- * Parse a Prolog list of lists into a JavaScript array.
179
- * Input: "[[a,b,c],[d,e,f]]"
180
- * Output: [["a", "b", "c"], ["d", "e", "f"]]
181
- */
182
- export function parseListOfLists(listStr) {
183
- const cleaned = listStr.trim().replace(/^\[/, "").replace(/\]$/, "");
184
- if (cleaned === "") {
185
- return [];
186
- }
187
- const results = [];
188
- let depth = 0;
189
- let current = "";
190
- let currentList = [];
191
- for (let i = 0; i < cleaned.length; i++) {
192
- const char = cleaned[i];
193
- if (char === "[") {
194
- depth++;
195
- if (depth > 1)
196
- current += char;
197
- }
198
- else if (char === "]") {
199
- depth--;
200
- if (depth === 0) {
201
- if (current) {
202
- currentList.push(current.trim());
203
- current = "";
204
- }
205
- if (currentList.length > 0) {
206
- results.push(currentList);
207
- currentList = [];
208
- }
209
- }
210
- else {
211
- current += char;
212
- }
213
- }
214
- else if (char === "," && depth === 1) {
215
- if (current) {
216
- currentList.push(current.trim());
217
- current = "";
218
- }
219
- }
220
- else if (char === "," && depth === 0) {
221
- // Skip comma between lists
222
- }
223
- else {
224
- current += char;
225
- }
226
- }
227
- return results;
228
- }
229
- /**
230
- * Parse a single entity from Prolog binding format.
231
- * Input: "[abc123, req, [id=abc123, title=\"Test\", ...]]"
232
- */
233
- export function parseEntityFromBinding(bindingStr) {
234
- const cleaned = bindingStr.trim().replace(/^\[/, "").replace(/\]$/, "");
235
- const parts = splitTopLevel(cleaned, ",");
236
- if (parts.length < 3) {
237
- return {};
238
- }
239
- const id = parts[0].trim();
240
- const type = parts[1].trim();
241
- const propsStr = parts.slice(2).join(",").trim();
242
- const props = parsePropertyList(propsStr);
243
- return { ...props, id: normalizeEntityId(stripOuterQuotes(id)), type };
244
- }
245
- /**
246
- * Parse entity from array returned by parseListOfLists.
247
- * Input: ["abc123", "req", "[id=abc123, title=\"Test\", ...]"]
248
- */
249
- export function parseEntityFromList(data) {
250
- if (data.length < 3) {
251
- return {};
252
- }
253
- const id = data[0].trim();
254
- const type = data[1].trim();
255
- const propsStr = data[2].trim();
256
- const props = parsePropertyList(propsStr);
257
- return { ...props, id: normalizeEntityId(stripOuterQuotes(id)), type };
258
- }
259
- /**
260
- * Parse Prolog property list into JavaScript object.
261
- */
262
- export function parsePropertyList(propsStr) {
263
- const props = {};
264
- let cleaned = propsStr.trim();
265
- if (cleaned.startsWith("[")) {
266
- cleaned = cleaned.substring(1);
267
- }
268
- if (cleaned.endsWith("]")) {
269
- cleaned = cleaned.substring(0, cleaned.length - 1);
270
- }
271
- const pairs = splitTopLevel(cleaned, ",");
272
- for (const pair of pairs) {
273
- const eqIndex = pair.indexOf("=");
274
- if (eqIndex === -1)
275
- continue;
276
- const key = pair.substring(0, eqIndex).trim();
277
- const value = pair.substring(eqIndex + 1).trim();
278
- if (key === "..." || value === "..." || value === "...|...") {
279
- continue;
280
- }
281
- const parsed = parsePrologValue(value);
282
- props[key] = parsed;
283
- }
284
- return props;
285
- }
286
- /**
287
- * Parse a single Prolog value, handling typed literals and URIs.
288
- */
289
- export function parsePrologValue(valueInput) {
290
- const value = valueInput.trim();
291
- // Handle typed literal: ^^("value", type)
292
- if (value.startsWith("^^(")) {
293
- const innerStart = value.indexOf("(") + 1;
294
- let depth = 1;
295
- let innerEnd = innerStart;
296
- for (let i = innerStart; i < value.length; i++) {
297
- if (value[i] === "(")
298
- depth++;
299
- if (value[i] === ")") {
300
- depth--;
301
- if (depth === 0) {
302
- innerEnd = i;
303
- break;
304
- }
305
- }
306
- }
307
- const innerContent = value.substring(innerStart, innerEnd);
308
- const parts = splitTopLevel(innerContent, ",");
309
- if (parts.length >= 2) {
310
- let literalValue = parts[0].trim();
311
- if (literalValue.startsWith('"') && literalValue.endsWith('"')) {
312
- literalValue = literalValue.substring(1, literalValue.length - 1);
313
- }
314
- // Handle array notation
315
- if (literalValue.startsWith("[") && literalValue.endsWith("]")) {
316
- const listContent = literalValue.substring(1, literalValue.length - 1);
317
- if (listContent === "") {
318
- return [];
319
- }
320
- return splitTopLevel(listContent, ",").map((item) => item.trim());
321
- }
322
- return literalValue;
323
- }
324
- }
325
- // Handle URI
326
- if (value.startsWith("file:///")) {
327
- const lastSlash = value.lastIndexOf("/");
328
- if (lastSlash !== -1) {
329
- return value.substring(lastSlash + 1);
330
- }
331
- return value;
332
- }
333
- // Handle quoted string
334
- if (value.startsWith('"') && value.endsWith('"')) {
335
- return value.substring(1, value.length - 1);
336
- }
337
- // Handle quoted atom
338
- if (value.startsWith("'") && value.endsWith("'")) {
339
- return value.substring(1, value.length - 1);
340
- }
341
- // Handle list
342
- if (value.startsWith("[") && value.endsWith("]")) {
343
- const listContent = value.substring(1, value.length - 1);
344
- if (listContent === "") {
345
- return [];
346
- }
347
- const items = splitTopLevel(listContent, ",").map((item) => {
348
- return parsePrologValue(item.trim());
349
- });
350
- return items;
351
- }
352
- return value;
353
- }
354
- /**
355
- * Split a string by delimiter at the top level (not inside brackets or quotes).
356
- */
357
- export function splitTopLevel(str, delimiter) {
358
- const results = [];
359
- let current = "";
360
- let depth = 0;
361
- let inQuotes = false;
362
- for (let i = 0; i < str.length; i++) {
363
- const char = str[i];
364
- const prevChar = i > 0 ? str[i - 1] : "";
365
- if (char === '"' && prevChar !== "\\") {
366
- inQuotes = !inQuotes;
367
- current += char;
368
- }
369
- else if (!inQuotes && (char === "[" || char === "(")) {
370
- depth++;
371
- current += char;
372
- }
373
- else if (!inQuotes && (char === "]" || char === ")")) {
374
- depth--;
375
- current += char;
376
- }
377
- else if (!inQuotes && depth === 0 && char === delimiter) {
378
- if (current) {
379
- results.push(current);
380
- current = "";
381
- }
382
- }
383
- else {
384
- current += char;
385
- }
386
- }
387
- if (current) {
388
- results.push(current);
389
- }
390
- return results;
391
- }
392
- function stripOuterQuotes(value) {
393
- if (value.startsWith("'") && value.endsWith("'")) {
394
- return value.slice(1, -1);
395
- }
396
- if (value.startsWith('"') && value.endsWith('"')) {
397
- return value.slice(1, -1);
398
- }
399
- return value;
400
- }
401
- function normalizeEntityId(value) {
402
- if (!value.startsWith("file:///")) {
403
- return value;
404
- }
405
- const idx = value.lastIndexOf("/");
406
- return idx === -1 ? value : value.slice(idx + 1);
407
- }
@@ -1,20 +1,3 @@
1
- /*
2
- Kibi — repo-local, per-branch, queryable long-term memory for software projects
3
- Copyright (C) 2026 Piotr Franczyk
4
-
5
- This program is free software: you can redistribute it and/or modify
6
- it under the terms of the GNU Affero General Public License as published by
7
- the Free Software Foundation, either version 3 of the License, or
8
- (at your option) any later version.
9
-
10
- This program is distributed in the hope that it will be useful,
11
- but WITHOUT ANY WARRANTY; without even the implied warranty of
12
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
- GNU Affero General Public License for more details.
14
-
15
- You should have received a copy of the GNU Affero General Public License
16
- along with this program. If not, see <https://www.gnu.org/licenses/>.
17
- */
18
1
  import { parseAtomList } from "./prolog-list.js";
19
2
  /**
20
3
  * Handle analyze_shared_facts tool calls
@@ -96,7 +79,7 @@ function analyzeSharedConcepts(requirements, existingFacts, minFreq) {
96
79
  const capitalizedTerms = originalText.matchAll(/\b([A-Z][a-z]+)\b/g);
97
80
  // Extract repeated phrases (2+ words)
98
81
  // Extract repeated phrases (2+ words)
99
- const words = text.split(/\s+/).filter(w => w.length > 3);
82
+ const words = text.split(/\s+/).filter((w) => w.length > 3);
100
83
  for (let i = 0; i < words.length - 1; i++) {
101
84
  const phrase = `${words[i]} ${words[i + 1]}`;
102
85
  if (!conceptCounts.has(phrase)) {
@@ -133,6 +116,6 @@ function analyzeSharedConcepts(requirements, existingFacts, minFreq) {
133
116
  function capitalizeConcept(concept) {
134
117
  return concept
135
118
  .split(/\s+/)
136
- .map(word => word.charAt(0).toUpperCase() + word.slice(1))
119
+ .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
137
120
  .join(" ");
138
121
  }
@@ -15,33 +15,6 @@
15
15
  You should have received a copy of the GNU Affero General Public License
16
16
  along with this program. If not, see <https://www.gnu.org/licenses/>.
17
17
  */
18
- /*
19
- How to apply this header to source files (examples)
20
-
21
- 1) Prepend header to a single file (POSIX shells):
22
-
23
- cat LICENSE_HEADER.txt "$FILE" > "$FILE".with-header && mv "$FILE".with-header "$FILE"
24
-
25
- 2) Apply to multiple files (example: the project's main entry files):
26
-
27
- for f in packages/cli/bin/kibi packages/mcp/bin/kibi-mcp packages/cli/src/*.ts packages/mcp/src/*.ts; do
28
- if [ -f "$f" ]; then
29
- cp "$f" "$f".bak
30
- (cat LICENSE_HEADER.txt; echo; cat "$f" ) > "$f".new && mv "$f".new "$f"
31
- fi
32
- done
33
-
34
- 3) Avoid duplicating the header: run a quick guard to only add if missing
35
-
36
- for f in packages/cli/bin/kibi packages/mcp/bin/kibi-mcp; do
37
- if [ -f "$f" ]; then
38
- if ! head -n 5 "$f" | grep -q "Copyright (C) 2026 Piotr Franczyk"; then
39
- cp "$f" "$f".bak
40
- (cat LICENSE_HEADER.txt; echo; cat "$f" ) > "$f".new && mv "$f".new "$f"
41
- fi
42
- fi
43
- done
44
- */
45
18
  import { existsSync, readFileSync, writeFileSync } from "node:fs";
46
19
  import path from "node:path";
47
20
  import { dump as dumpYAML, load as parseYAML } from "js-yaml";
@@ -16,18 +16,10 @@
16
16
  along with this program. If not, see <https://www.gnu.org/licenses/>.
17
17
  */
18
18
  import Ajv from "ajv";
19
+ import { escapeAtom, toPrologAtom } from "kibi-cli/prolog/codec";
19
20
  import entitySchema from "kibi-cli/schemas/entity";
20
21
  import relationshipSchema from "kibi-cli/schemas/relationship";
21
22
  import { refreshCoordinatesForSymbolId } from "./symbols.js";
22
- function escapeAtom(value) {
23
- return value.replace(/'/g, "''");
24
- }
25
- function toPrologAtom(value) {
26
- const simplePrologAtom = /^[a-z][a-zA-Z0-9_]*$/;
27
- return simplePrologAtom.test(value)
28
- ? value
29
- : `'${value.replace(/'/g, "''")}'`;
30
- }
31
23
  const ajv = new Ajv({ strict: false });
32
24
  const validateEntity = ajv.compile(entitySchema);
33
25
  const validateRelationship = ajv.compile(relationshipSchema);
@@ -122,11 +114,17 @@ export async function handleKbUpsert(prolog, args) {
122
114
  }
123
115
  relationshipsCreated++;
124
116
  }
125
- // Save KB to disk
117
+ // Note: kb_save is intentionally NOT called here for performance.
118
+ // Callers that need durability across restarts should explicitly call kb_save.
119
+ // This allows batching multiple upserts before a single disk write.
120
+ prolog.invalidateCache();
121
+ // Save KB to disk to ensure durability across process restarts
126
122
  await prolog.query("kb_save");
127
123
  prolog.invalidateCache();
124
+ // multiple upserts and save once at the end for better performance.
125
+ prolog.invalidateCache();
128
126
  let contradictionPairsDetected;
129
- if (type === "req") {
127
+ if (type === "req" && !args._skipContradictionCheck) {
130
128
  contradictionPairsDetected = await detectContradictionPairs(prolog, id);
131
129
  }
132
130
  if (type === "symbol") {
@@ -15,37 +15,10 @@
15
15
  You should have received a copy of the GNU Affero General Public License
16
16
  along with this program. If not, see <https://www.gnu.org/licenses/>.
17
17
  */
18
- /*
19
- How to apply this header to source files (examples)
20
-
21
- 1) Prepend header to a single file (POSIX shells):
22
-
23
- cat LICENSE_HEADER.txt "$FILE" > "$FILE".with-header && mv "$FILE".with-header "$FILE"
24
-
25
- 2) Apply to multiple files (example: the project's main entry files):
26
-
27
- for f in packages/cli/bin/kibi packages/mcp/bin/kibi-mcp packages/cli/src/*.ts packages/mcp/src/*.ts; do
28
- if [ -f "$f" ]; then
29
- cp "$f" "$f".bak
30
- (cat LICENSE_HEADER.txt; echo; cat "$f" ) > "$f".new && mv "$f".new "$f"
31
- fi
32
- done
33
-
34
- 3) Avoid duplicating the header: run a quick guard to only add if missing
35
-
36
- for f in packages/cli/bin/kibi packages/mcp/bin/kibi-mcp; do
37
- if [ -f "$f" ]; then
38
- if ! head -n 5 "$f" | grep -q "Copyright (C) 2026 Piotr Franczyk"; then
39
- cp "$f" "$f".bak
40
- (cat LICENSE_HEADER.txt; echo; cat "$f" ) > "$f".new && mv "$f".new "$f"
41
- fi
42
- fi
43
- done
44
- */
45
18
  export const TOOLS = [
46
19
  {
47
20
  name: "kb_query",
48
- description: "Read entities from the KB with filters. Use for discovery and lookup before edits. Do not use for writes. No mutation side effects.",
21
+ description: "Read entities from the KB with filters. Use for discovery and lookup before edits. Do not use for writes. No mutation side effects. Tags filter by metadata tags only, not entity IDs.",
49
22
  inputSchema: {
50
23
  type: "object",
51
24
  properties: {
@@ -91,7 +64,7 @@ export const TOOLS = [
91
64
  },
92
65
  {
93
66
  name: "kb_upsert",
94
- description: "Create or update one entity and optional relationships. Use for KB mutations after validating intent. Use the `relationships` array for batch creation of multiple links in a single call (e.g., linking a requirement to multiple tests or facts). Prefer modeling requirements as reusable fact links (`constrains`, `requires_property`) so consistency and contradiction checks remain queryable. Do not use for read-only inspection. Side effects: writes KB, may refresh symbol coordinates.",
67
+ description: "Create or update one entity and optional relationships. Use for KB mutations after validating intent. Use the `relationships` array for batch creation of multiple links in a single call (e.g., linking a requirement to multiple tests or facts). Prefer modeling requirements as reusable fact links (`constrains`, `requires_property`) so consistency and contradiction checks remain queryable. Relationship endpoints must already exist in KB. Do not use for read-only inspection. Side effects: writes KB, may refresh symbol coordinates.",
95
68
  inputSchema: {
96
69
  type: "object",
97
70
  required: ["type", "id", "properties"],
@@ -228,7 +201,7 @@ export const TOOLS = [
228
201
  },
229
202
  {
230
203
  name: "kb_check",
231
- description: "Run KB validation rules and return violations. Use before or after mutations. Do not use for point lookups. No write side effects.",
204
+ description: "Run KB validation rules and return violations. Use before or after mutations. Do not use for point lookups. No write side effects. Prefer explicit rules for faster iteration.",
232
205
  inputSchema: {
233
206
  type: "object",
234
207
  properties: {
@@ -238,13 +211,16 @@ export const TOOLS = [
238
211
  type: "string",
239
212
  enum: [
240
213
  "must-priority-coverage",
214
+ "symbol-coverage",
215
+ "symbol-traceability",
241
216
  "no-dangling-refs",
242
217
  "no-cycles",
243
218
  "required-fields",
244
- "symbol-coverage",
219
+ "deprecated-adr-no-successor",
220
+ "domain-contradictions",
245
221
  ],
246
222
  },
247
- description: "Optional rule subset. Allowed: must-priority-coverage, no-dangling-refs, no-cycles, required-fields, symbol-coverage. If omitted, server runs all.",
223
+ description: "Optional rule subset. Allowed: must-priority-coverage, symbol-coverage, symbol-traceability, no-dangling-refs, no-cycles, required-fields, deprecated-adr-no-successor, domain-contradictions. If omitted, server runs all.",
248
224
  },
249
225
  },
250
226
  },
package/dist/workspace.js CHANGED
@@ -15,33 +15,6 @@
15
15
  You should have received a copy of the GNU Affero General Public License
16
16
  along with this program. If not, see <https://www.gnu.org/licenses/>.
17
17
  */
18
- /*
19
- How to apply this header to source files (examples)
20
-
21
- 1) Prepend header to a single file (POSIX shells):
22
-
23
- cat LICENSE_HEADER.txt "$FILE" > "$FILE".with-header && mv "$FILE".with-header "$FILE"
24
-
25
- 2) Apply to multiple files (example: the project's main entry files):
26
-
27
- for f in packages/cli/bin/kibi packages/mcp/bin/kibi-mcp packages/cli/src/*.ts packages/mcp/src/*.ts; do
28
- if [ -f "$f" ]; then
29
- cp "$f" "$f".bak
30
- (cat LICENSE_HEADER.txt; echo; cat "$f" ) > "$f".new && mv "$f".new "$f"
31
- fi
32
- done
33
-
34
- 3) Avoid duplicating the header: run a quick guard to only add if missing
35
-
36
- for f in packages/cli/bin/kibi packages/mcp/bin/kibi-mcp; do
37
- if [ -f "$f" ]; then
38
- if ! head -n 5 "$f" | grep -q "Copyright (C) 2026 Piotr Franczyk"; then
39
- cp "$f" "$f".bak
40
- (cat LICENSE_HEADER.txt; echo; cat "$f" ) > "$f".new && mv "$f".new "$f"
41
- fi
42
- fi
43
- done
44
- */
45
18
  import fs from "node:fs";
46
19
  import path from "node:path";
47
20
  const WORKSPACE_ENV_KEYS = [
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "kibi-mcp",
3
- "version": "0.2.4",
3
+ "version": "0.3.0",
4
4
  "dependencies": {
5
5
  "@modelcontextprotocol/sdk": "^1.26.0",
6
6
  "ajv": "^8.18.0",
@@ -9,7 +9,7 @@
9
9
  "fast-glob": "^3.2.12",
10
10
  "gray-matter": "^4.0.3",
11
11
  "js-yaml": "^4.1.0",
12
- "kibi-cli": "^0.2.3",
12
+ "kibi-cli": "^0.2.5",
13
13
  "kibi-core": "^0.1.8",
14
14
  "mcpcat": "^0.1.12",
15
15
  "ts-morph": "^23.0.0",