kibi-mcp 0.13.0 → 0.14.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,4 +1,5 @@
1
1
  import { escapeAtom, parseEntityFromList, parseListOfLists } from "kibi-cli/prolog/codec";
2
+ import { writeBriefPendingMarker } from "../utils/brief-marker.js";
2
3
  /**
3
4
  * Handle kb.delete tool calls
4
5
  * Prevents deletion of entities with dependents (referential integrity)
@@ -12,6 +13,8 @@ prolog, args) {
12
13
  let deleted = 0;
13
14
  let skipped = 0;
14
15
  const errors = [];
16
+ const pendingEntityIds = [];
17
+ const pendingRelationships = [];
15
18
  try {
16
19
  for (const id of ids) {
17
20
  const safeId = escapeAtom(id);
@@ -42,6 +45,7 @@ prolog, args) {
42
45
  }
43
46
  // No dependents, safe to delete
44
47
  const entityMetadata = await loadEntityMetadataForDelete(prolog, id, safeId);
48
+ const relationships = await loadOutgoingRelationshipsForDelete(prolog, safeId);
45
49
  const deleteGoal = buildDeleteGoal(safeId, entityMetadata);
46
50
  const deleteResult = await prolog.query(deleteGoal);
47
51
  if (!deleteResult.success) {
@@ -50,6 +54,8 @@ prolog, args) {
50
54
  }
51
55
  else {
52
56
  deleted++;
57
+ pendingEntityIds.push(id);
58
+ pendingRelationships.push(...relationships);
53
59
  }
54
60
  }
55
61
  // Save KB to disk
@@ -57,6 +63,14 @@ prolog, args) {
57
63
  if (!saveResult.success) {
58
64
  throw new Error(`Failed to save KB after delete: ${saveResult.error || "Unknown error"}`);
59
65
  }
66
+ if (pendingEntityIds.length > 0 || pendingRelationships.length > 0) {
67
+ writeBriefPendingMarker({
68
+ ...(args._requestId ? { sessionId: args._requestId } : {}),
69
+ operation: "delete",
70
+ entityIds: pendingEntityIds,
71
+ relationships: pendingRelationships,
72
+ });
73
+ }
60
74
  prolog.invalidateCache();
61
75
  return {
62
76
  content: [
@@ -91,6 +105,38 @@ async function loadEntityMetadataForDelete(prolog, id, safeId) {
91
105
  const { id: _entityId, type: _entityType, ...props } = entity;
92
106
  return { type, props };
93
107
  }
108
+ async function loadOutgoingRelationshipsForDelete(prolog, safeId) {
109
+ const result = await prolog.query(`findall([Type,'${safeId}',To], (member(Type, [depends_on, verified_by, validates, specified_by, relates_to, guards, publishes, consumes, implements, covered_by, executable_for, constrains, requires_property, supersedes, constrained_by]), kb_relationship(Type, '${safeId}', To)), Relationships)`);
110
+ if (!result.success) {
111
+ throw new Error(`Failed to load outgoing relationships for entity ${safeId}: ${result.error || "Unknown error"}`);
112
+ }
113
+ const rows = result.bindings.Relationships
114
+ ? parseListOfLists(result.bindings.Relationships)
115
+ : [];
116
+ return rows.flatMap((row) => {
117
+ const type = row[0];
118
+ const from = row[1];
119
+ const to = row[2];
120
+ if (type === undefined || from === undefined || to === undefined) {
121
+ return [];
122
+ }
123
+ return [
124
+ {
125
+ type: normalizeDeleteRelationshipValue(type),
126
+ from: normalizeDeleteRelationshipValue(from),
127
+ to: normalizeDeleteRelationshipValue(to),
128
+ },
129
+ ];
130
+ });
131
+ }
132
+ function normalizeDeleteRelationshipValue(value) {
133
+ const normalized = String(value);
134
+ if ((normalized.startsWith("'") && normalized.endsWith("'")) ||
135
+ (normalized.startsWith('"') && normalized.endsWith('"'))) {
136
+ return normalized.slice(1, -1);
137
+ }
138
+ return normalized;
139
+ }
94
140
  function buildDeleteGoal(safeId, metadata) {
95
141
  const auditProps = [`id='${safeId}'`, ...serializeDeleteProps(metadata.props)];
96
142
  return `kb_retract_entity('${safeId}', ${metadata.type}, [${auditProps.join(", ")}])`;
@@ -20,19 +20,16 @@ import path from "node:path";
20
20
  import { dump as dumpYAML, load as parseYAML } from "js-yaml";
21
21
  import { enrichSymbolCoordinates, } from "kibi-cli/extractors/symbols-coordinator";
22
22
  import { resolveWorkspaceRoot } from "../workspace.js";
23
- const COMMENT_BLOCK = `# symbols.yaml
24
- # AUTHORED fields (edit freely):
25
- # id, title, sourceFile, links, status, tags, owner, priority
26
- # GENERATED fields (never edit manually — overwritten by kibi sync and kb_symbols_refresh):
27
- # sourceLine, sourceColumn, sourceEndLine, sourceEndColumn, coordinatesGeneratedAt
28
- # Run \`kibi sync\` or call the \`kb_symbols_refresh\` MCP tool to refresh coordinates.
23
+ const SYMBOL_COORDINATES_COMMENT_BLOCK = `# symbol-coordinates.yaml
24
+ # GENERATED coordinate artifact — do not edit manually.
25
+ # Run \`kibi sync --refresh-symbol-coordinates\` to refresh.
29
26
  `;
27
+ const DEFAULT_COORDINATE_ARTIFACT_NAME = "symbol-coordinates.yaml";
30
28
  const GENERATED_COORD_FIELDS = [
31
29
  "sourceLine",
32
30
  "sourceColumn",
33
31
  "sourceEndLine",
34
32
  "sourceEndColumn",
35
- "coordinatesGeneratedAt",
36
33
  ];
37
34
  const SOURCE_EXTENSIONS = new Set([
38
35
  ".ts",
@@ -48,7 +45,7 @@ export async function handleKbSymbolsRefresh(args) {
48
45
  // implements REQ-vscode-traceability
49
46
  const dryRun = args.dryRun === true;
50
47
  const workspaceRoot = args.workspaceRoot ?? resolveWorkspaceRoot();
51
- const manifestPath = await resolveManifestPath(workspaceRoot);
48
+ const { coordinatesPath, manifestPath } = await resolveManifestPaths(workspaceRoot);
52
49
  const rawContent = await readFile(manifestPath, "utf8");
53
50
  const parsed = parseYAML(rawContent);
54
51
  if (!isRecord(parsed) || !Array.isArray(parsed.symbols)) {
@@ -89,20 +86,16 @@ export async function handleKbSymbolsRefresh(args) {
89
86
  unchanged++;
90
87
  }
91
88
  }
92
- const dumped = dumpYAML(parsed, {
93
- lineWidth: -1,
94
- noRefs: true,
95
- sortKeys: false,
96
- });
97
- const nextContent = `${COMMENT_BLOCK}${dumped}`;
98
- if (!dryRun && rawContent !== nextContent) {
99
- await writeFile(manifestPath, nextContent, "utf8");
89
+ const nextCoordinates = writeCoordinateArtifact(buildCoordinatesMap(finalized));
90
+ const currentCoordinates = await readOptionalTextFile(coordinatesPath);
91
+ if (!dryRun && currentCoordinates !== nextCoordinates) {
92
+ await writeFile(coordinatesPath, nextCoordinates, "utf8");
100
93
  }
101
94
  return {
102
95
  content: [
103
96
  {
104
97
  type: "text",
105
- text: `kb_symbols_refresh ${dryRun ? "(dry run) " : ""}completed for ${path.relative(workspaceRoot, manifestPath)}: refreshed=${refreshed}, unchanged=${unchanged}, failed=${failed}`,
98
+ text: `kb_symbols_refresh ${dryRun ? "(dry run) " : ""}completed for ${path.relative(workspaceRoot, coordinatesPath)}: refreshed=${refreshed}, unchanged=${unchanged}, failed=${failed}`,
106
99
  },
107
100
  ],
108
101
  structuredContent: {
@@ -115,7 +108,7 @@ export async function handleKbSymbolsRefresh(args) {
115
108
  }
116
109
  export async function refreshCoordinatesForSymbolId(symbolId, workspaceRoot = resolveWorkspaceRoot()) {
117
110
  // implements REQ-vscode-traceability
118
- const manifestPath = await resolveManifestPath(workspaceRoot);
111
+ const { coordinatesPath, manifestPath } = await resolveManifestPaths(workspaceRoot);
119
112
  const rawContent = await readFile(manifestPath, "utf8");
120
113
  const parsed = parseYAML(rawContent);
121
114
  if (!isRecord(parsed) || !Array.isArray(parsed.symbols)) {
@@ -143,17 +136,30 @@ export async function refreshCoordinatesForSymbolId(symbolId, workspaceRoot = re
143
136
  symbols[index] = finalized;
144
137
  parsed.symbols = symbols;
145
138
  const refreshed = GENERATED_COORD_FIELDS.some((field) => original[field] !== finalized[field]);
146
- const dumped = dumpYAML(parsed, {
147
- lineWidth: -1,
148
- noRefs: true,
149
- sortKeys: false,
150
- });
151
- const nextContent = `${COMMENT_BLOCK}${dumped}`;
152
- if (rawContent !== nextContent) {
153
- await writeFile(manifestPath, nextContent, "utf8");
139
+ const artifact = await readCoordinateArtifactFromPath(coordinatesPath);
140
+ const nextCoordinates = {
141
+ ...artifact.coordinates,
142
+ };
143
+ const coordinatesRecord = toCoordinateRecord(finalized);
144
+ if (coordinatesRecord) {
145
+ nextCoordinates[symbolId] = coordinatesRecord;
146
+ }
147
+ if (coordinatesRecord || Object.keys(nextCoordinates).length > 0) {
148
+ const nextContent = writeCoordinateArtifact(nextCoordinates);
149
+ const currentContent = await readOptionalTextFile(coordinatesPath);
150
+ if (currentContent !== nextContent) {
151
+ await writeFile(coordinatesPath, nextContent, "utf8");
152
+ }
154
153
  }
155
154
  return { refreshed, found: true };
156
155
  }
156
+ async function resolveManifestPaths(workspaceRoot) {
157
+ const manifestPath = await resolveManifestPath(workspaceRoot);
158
+ return {
159
+ manifestPath,
160
+ coordinatesPath: path.join(path.dirname(manifestPath), DEFAULT_COORDINATE_ARTIFACT_NAME),
161
+ };
162
+ }
157
163
  export async function resolveManifestPath(workspaceRoot) {
158
164
  // implements REQ-002, REQ-013
159
165
  const configPath = path.join(workspaceRoot, ".kb", "config.json");
@@ -190,9 +196,7 @@ function hasGeneratedCoordinates(entry) {
190
196
  return (typeof entry.sourceLine === "number" &&
191
197
  typeof entry.sourceColumn === "number" &&
192
198
  typeof entry.sourceEndLine === "number" &&
193
- typeof entry.sourceEndColumn === "number" &&
194
- typeof entry.coordinatesGeneratedAt === "string" &&
195
- entry.coordinatesGeneratedAt.length > 0);
199
+ typeof entry.sourceEndColumn === "number");
196
200
  }
197
201
  async function isEligible(sourceFile, workspaceRoot) {
198
202
  if (!sourceFile)
@@ -251,7 +255,6 @@ async function fillMissingCoordinates(before, after, workspaceRoot) {
251
255
  sourceColumn: match.index,
252
256
  sourceEndLine: index + 1,
253
257
  sourceEndColumn: match.index + title.length,
254
- coordinatesGeneratedAt: new Date().toISOString(),
255
258
  };
256
259
  }
257
260
  }
@@ -263,3 +266,86 @@ async function fillMissingCoordinates(before, after, workspaceRoot) {
263
266
  function isRecord(value) {
264
267
  return typeof value === "object" && value !== null && !Array.isArray(value);
265
268
  }
269
+ function normalizeCoordinateRecord(value) {
270
+ if (!isRecord(value)) {
271
+ return null;
272
+ }
273
+ const { sourceColumn, sourceEndColumn, sourceEndLine, sourceFile, sourceLine } = value;
274
+ if (typeof sourceFile !== "string" ||
275
+ typeof sourceLine !== "number" ||
276
+ typeof sourceColumn !== "number" ||
277
+ typeof sourceEndLine !== "number" ||
278
+ typeof sourceEndColumn !== "number") {
279
+ return null;
280
+ }
281
+ return {
282
+ sourceFile,
283
+ sourceLine,
284
+ sourceColumn,
285
+ sourceEndLine,
286
+ sourceEndColumn,
287
+ };
288
+ }
289
+ function sortCoordinates(coordinates) {
290
+ const sortedCoordinates = {};
291
+ for (const symbolId of Object.keys(coordinates).sort((left, right) => left.localeCompare(right))) {
292
+ const record = normalizeCoordinateRecord(coordinates[symbolId]);
293
+ if (!record) {
294
+ continue;
295
+ }
296
+ sortedCoordinates[symbolId] = record;
297
+ }
298
+ return sortedCoordinates;
299
+ }
300
+ function readCoordinateArtifact(content) {
301
+ const parsed = parseYAML(content);
302
+ if (!isRecord(parsed) || !isRecord(parsed.coordinates)) {
303
+ return { coordinates: {} };
304
+ }
305
+ const coordinates = {};
306
+ for (const [symbolId, record] of Object.entries(parsed.coordinates)) {
307
+ const normalizedRecord = normalizeCoordinateRecord(record);
308
+ if (!normalizedRecord) {
309
+ continue;
310
+ }
311
+ coordinates[symbolId] = normalizedRecord;
312
+ }
313
+ return { coordinates };
314
+ }
315
+ function writeCoordinateArtifact(coordinates) {
316
+ return `${SYMBOL_COORDINATES_COMMENT_BLOCK}${dumpYAML({ coordinates: sortCoordinates(coordinates) }, {
317
+ lineWidth: -1,
318
+ noRefs: true,
319
+ sortKeys: true,
320
+ })}`;
321
+ }
322
+ function toCoordinateRecord(entry) {
323
+ return normalizeCoordinateRecord(entry);
324
+ }
325
+ function buildCoordinatesMap(entries) {
326
+ const coordinates = {};
327
+ for (const entry of entries) {
328
+ const id = typeof entry.id === "string" ? entry.id : undefined;
329
+ const record = toCoordinateRecord(entry);
330
+ if (!id || !record) {
331
+ continue;
332
+ }
333
+ coordinates[id] = record;
334
+ }
335
+ return coordinates;
336
+ }
337
+ async function readCoordinateArtifactFromPath(coordinatesPath) {
338
+ const content = await readOptionalTextFile(coordinatesPath);
339
+ if (content === null) {
340
+ return { coordinates: {} };
341
+ }
342
+ return readCoordinateArtifact(content);
343
+ }
344
+ async function readOptionalTextFile(filePath) {
345
+ try {
346
+ return await readFile(filePath, "utf8");
347
+ }
348
+ catch {
349
+ return null;
350
+ }
351
+ }
@@ -20,6 +20,7 @@ import { escapeAtom, toPrologAtom, toPrologString, } from "kibi-cli/prolog/codec
20
20
  import entitySchema from "kibi-cli/schemas/entity";
21
21
  import relationshipSchema from "kibi-cli/schemas/relationship";
22
22
  import { isMcpDebugEnabled } from "../env.js";
23
+ import { writeBriefPendingMarker } from "../utils/brief-marker.js";
23
24
  import { refreshCoordinatesForSymbolId } from "./symbols.js";
24
25
  let refreshCoordinatesForSymbolIdImpl = refreshCoordinatesForSymbolId;
25
26
  const ajv = new Ajv({ strict: false });
@@ -155,6 +156,16 @@ export async function handleKbUpsert(prolog, args) {
155
156
  if (!saveResult.success) {
156
157
  throw new Error(`Failed to save KB after upsert: ${saveResult.error || "Unknown error"}`);
157
158
  }
159
+ writeBriefPendingMarker({
160
+ ...(args._requestId ? { sessionId: args._requestId } : {}),
161
+ operation: "upsert",
162
+ entityIds: [id],
163
+ relationships: relationships.map((rel) => ({
164
+ from: String(rel.from),
165
+ to: String(rel.to),
166
+ type: String(rel.type),
167
+ })),
168
+ });
158
169
  if (type === "symbol") {
159
170
  try {
160
171
  await refreshCoordinatesForSymbolIdImpl(id);
@@ -0,0 +1,107 @@
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
+ import fs from "node:fs";
19
+ import path from "node:path";
20
+ import { resolveWorkspaceRoot } from "../workspace.js";
21
+ // implements REQ-opencode-kibi-briefing-v2
22
+ export function writeBriefPendingMarker(args) {
23
+ const workspaceRoot = resolveWorkspaceRoot();
24
+ const pendingDir = path.join(workspaceRoot, ".kb", "briefs", "pending");
25
+ fs.mkdirSync(pendingDir, { recursive: true });
26
+ const sessionId = normalizeSessionId(args.sessionId);
27
+ const existing = loadExistingMarker(pendingDir, sessionId);
28
+ const timestamp = existing?.payload.timestamp ?? Date.now();
29
+ const payload = {
30
+ sessionId,
31
+ timestamp,
32
+ branch: resolveMarkerBranch(workspaceRoot),
33
+ operation: args.operation,
34
+ entityIds: mergeUniqueStrings(existing?.payload.entityIds ?? [], args.entityIds),
35
+ relationships: mergeRelationships(existing?.payload.relationships ?? [], args.relationships ?? []),
36
+ };
37
+ const filePath = existing?.filePath ??
38
+ path.join(pendingDir, `${sanitizeSessionId(sessionId)}-${timestamp}.json`);
39
+ fs.writeFileSync(filePath, `${JSON.stringify(payload, null, 2)}\n`, "utf8");
40
+ return payload;
41
+ }
42
+ function loadExistingMarker(pendingDir, sessionId) {
43
+ const prefix = `${sanitizeSessionId(sessionId)}-`;
44
+ const matches = fs
45
+ .readdirSync(pendingDir, { withFileTypes: true })
46
+ .filter((entry) => entry.isFile())
47
+ .map((entry) => entry.name)
48
+ .filter((name) => name.startsWith(prefix) && name.endsWith(".json"))
49
+ .sort();
50
+ const latest = matches.at(-1);
51
+ if (!latest) {
52
+ return null;
53
+ }
54
+ const filePath = path.join(pendingDir, latest);
55
+ const raw = fs.readFileSync(filePath, "utf8");
56
+ return {
57
+ filePath,
58
+ payload: JSON.parse(raw),
59
+ };
60
+ }
61
+ function normalizeSessionId(sessionId) {
62
+ const normalized = sessionId?.trim();
63
+ return normalized && normalized.length > 0 ? normalized : "unknown";
64
+ }
65
+ function sanitizeSessionId(sessionId) {
66
+ return sessionId.replace(/[\\/:*?"<>|]+/g, "_");
67
+ }
68
+ function resolveMarkerBranch(workspaceRoot) {
69
+ const envBranch = process.env.KIBI_BRANCH?.trim();
70
+ if (envBranch) {
71
+ return envBranch;
72
+ }
73
+ const branchesDir = path.join(workspaceRoot, ".kb", "branches");
74
+ if (!fs.existsSync(branchesDir)) {
75
+ return "unknown";
76
+ }
77
+ const branches = fs
78
+ .readdirSync(branchesDir, { withFileTypes: true })
79
+ .filter((entry) => entry.isDirectory())
80
+ .map((entry) => entry.name)
81
+ .sort();
82
+ return branches.length === 1 ? (branches[0] ?? "unknown") : "unknown";
83
+ }
84
+ function mergeUniqueStrings(existing, incoming) {
85
+ const merged = new Set();
86
+ for (const value of existing) {
87
+ if (value) {
88
+ merged.add(value);
89
+ }
90
+ }
91
+ for (const value of incoming) {
92
+ if (value) {
93
+ merged.add(value);
94
+ }
95
+ }
96
+ return [...merged];
97
+ }
98
+ function mergeRelationships(existing, incoming) {
99
+ const merged = new Map();
100
+ for (const relationship of [...existing, ...incoming]) {
101
+ if (!relationship.from || !relationship.to || !relationship.type) {
102
+ continue;
103
+ }
104
+ merged.set(`${relationship.type}\u0000${relationship.from}\u0000${relationship.to}`, relationship);
105
+ }
106
+ return [...merged.values()];
107
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "kibi-mcp",
3
- "version": "0.13.0",
3
+ "version": "0.14.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.10.0",
12
+ "kibi-cli": "^0.11.0",
13
13
  "kibi-core": "^0.5.3",
14
14
  "mcpcat": "^0.1.12",
15
15
  "ts-morph": "^23.0.0",