kibi-cli 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/bin/kibi +19 -0
  2. package/dist/cli.d.ts +2 -0
  3. package/dist/cli.d.ts.map +1 -0
  4. package/dist/cli.js +117 -0
  5. package/dist/commands/branch.d.ts +3 -0
  6. package/dist/commands/branch.d.ts.map +1 -0
  7. package/dist/commands/branch.js +66 -0
  8. package/dist/commands/check.d.ts +12 -0
  9. package/dist/commands/check.d.ts.map +1 -0
  10. package/dist/commands/check.js +439 -0
  11. package/dist/commands/doctor.d.ts +2 -0
  12. package/dist/commands/doctor.d.ts.map +1 -0
  13. package/dist/commands/doctor.js +268 -0
  14. package/dist/commands/gc.d.ts +6 -0
  15. package/dist/commands/gc.d.ts.map +1 -0
  16. package/dist/commands/gc.js +117 -0
  17. package/dist/commands/init-helpers.d.ts +8 -0
  18. package/dist/commands/init-helpers.d.ts.map +1 -0
  19. package/dist/commands/init-helpers.js +150 -0
  20. package/dist/commands/init.d.ts +6 -0
  21. package/dist/commands/init.d.ts.map +1 -0
  22. package/dist/commands/init.js +85 -0
  23. package/dist/commands/query.d.ts +12 -0
  24. package/dist/commands/query.d.ts.map +1 -0
  25. package/dist/commands/query.js +469 -0
  26. package/dist/commands/sync.d.ts +7 -0
  27. package/dist/commands/sync.d.ts.map +1 -0
  28. package/dist/commands/sync.js +587 -0
  29. package/dist/extractors/manifest.d.ts +30 -0
  30. package/dist/extractors/manifest.d.ts.map +1 -0
  31. package/dist/extractors/manifest.js +122 -0
  32. package/dist/extractors/markdown.d.ts +39 -0
  33. package/dist/extractors/markdown.d.ts.map +1 -0
  34. package/dist/extractors/markdown.js +203 -0
  35. package/dist/extractors/symbols-coordinator.d.ts +4 -0
  36. package/dist/extractors/symbols-coordinator.d.ts.map +1 -0
  37. package/dist/extractors/symbols-coordinator.js +131 -0
  38. package/dist/extractors/symbols-ts.d.ts +21 -0
  39. package/dist/extractors/symbols-ts.d.ts.map +1 -0
  40. package/dist/extractors/symbols-ts.js +197 -0
  41. package/dist/prolog.d.ts +35 -0
  42. package/dist/prolog.d.ts.map +1 -0
  43. package/dist/prolog.js +328 -0
  44. package/dist/public/extractors/symbols-coordinator.d.ts +2 -0
  45. package/dist/public/extractors/symbols-coordinator.d.ts.map +1 -0
  46. package/dist/public/extractors/symbols-coordinator.js +46 -0
  47. package/dist/public/prolog/index.d.ts +2 -0
  48. package/dist/public/prolog/index.d.ts.map +1 -0
  49. package/dist/public/prolog/index.js +46 -0
  50. package/dist/public/schemas/entity.d.ts +58 -0
  51. package/dist/public/schemas/entity.d.ts.map +1 -0
  52. package/dist/public/schemas/entity.js +102 -0
  53. package/dist/public/schemas/relationship.d.ts +35 -0
  54. package/dist/public/schemas/relationship.d.ts.map +1 -0
  55. package/dist/public/schemas/relationship.js +81 -0
  56. package/dist/types/changeset.d.ts +22 -0
  57. package/dist/types/changeset.d.ts.map +1 -0
  58. package/dist/types/changeset.js +18 -0
  59. package/dist/types/entities.d.ts +40 -0
  60. package/dist/types/entities.d.ts.map +1 -0
  61. package/dist/types/entities.js +18 -0
  62. package/dist/types/relationships.d.ts +11 -0
  63. package/dist/types/relationships.d.ts.map +1 -0
  64. package/dist/types/relationships.js +18 -0
  65. package/package.json +57 -0
  66. package/schema/entities.pl +50 -0
  67. package/schema/relationships.pl +47 -0
  68. package/schema/validation.pl +49 -0
  69. package/src/public/extractors/symbols-coordinator.ts +50 -0
  70. package/src/public/prolog/index.ts +47 -0
  71. package/src/public/schemas/entity.ts +104 -0
  72. package/src/public/schemas/relationship.ts +83 -0
  73. package/src/schemas/changeset.schema.json +48 -0
  74. package/src/schemas/entity.schema.json +55 -0
  75. package/src/schemas/relationship.schema.json +34 -0
@@ -0,0 +1,197 @@
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
+ 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
+ import * as fs from "node:fs";
46
+ import * as path from "node:path";
47
+ import { Project, } from "ts-morph";
48
+ const SUPPORTED_SOURCE_EXTENSIONS = new Set([
49
+ ".ts",
50
+ ".tsx",
51
+ ".js",
52
+ ".jsx",
53
+ ".mts",
54
+ ".cts",
55
+ ".mjs",
56
+ ".cjs",
57
+ ]);
58
+ export async function enrichSymbolCoordinatesWithTsMorph(entries, workspaceRoot) {
59
+ const project = new Project({
60
+ skipAddingFilesFromTsConfig: true,
61
+ });
62
+ const sourceFileCache = new Map();
63
+ const enriched = [];
64
+ for (const entry of entries) {
65
+ try {
66
+ const resolved = resolveSourcePath(entry.sourceFile, workspaceRoot);
67
+ if (!resolved) {
68
+ enriched.push(entry);
69
+ continue;
70
+ }
71
+ const sourceFile = getOrAddSourceFile(project, sourceFileCache, resolved);
72
+ if (!sourceFile) {
73
+ enriched.push(entry);
74
+ continue;
75
+ }
76
+ const match = findNamedDeclaration(sourceFile, entry.title);
77
+ if (!match) {
78
+ enriched.push(entry);
79
+ continue;
80
+ }
81
+ const nameStart = match.getNameNode().getStart();
82
+ const end = match.node.getEnd();
83
+ const startLc = sourceFile.getLineAndColumnAtPos(nameStart);
84
+ const endLc = sourceFile.getLineAndColumnAtPos(end);
85
+ const coordinates = {
86
+ sourceLine: startLc.line,
87
+ sourceColumn: Math.max(0, startLc.column - 1),
88
+ sourceEndLine: endLc.line,
89
+ sourceEndColumn: Math.max(0, endLc.column - 1),
90
+ coordinatesGeneratedAt: new Date().toISOString(),
91
+ };
92
+ enriched.push({
93
+ ...entry,
94
+ ...coordinates,
95
+ });
96
+ }
97
+ catch (error) {
98
+ const message = error instanceof Error ? error.message : String(error);
99
+ console.warn(`[kibi] Failed to enrich symbol coordinates for ${entry.id}: ${message}`);
100
+ enriched.push(entry);
101
+ }
102
+ }
103
+ return enriched;
104
+ }
105
+ function resolveSourcePath(sourceFile, workspaceRoot) {
106
+ if (!sourceFile)
107
+ return null;
108
+ const absolute = path.isAbsolute(sourceFile)
109
+ ? sourceFile
110
+ : path.resolve(workspaceRoot, sourceFile);
111
+ const ext = path.extname(absolute).toLowerCase();
112
+ if (!SUPPORTED_SOURCE_EXTENSIONS.has(ext))
113
+ return null;
114
+ if (!fs.existsSync(absolute))
115
+ return null;
116
+ return absolute;
117
+ }
118
+ function getOrAddSourceFile(project, cache, absolutePath) {
119
+ const cached = cache.get(absolutePath);
120
+ if (cached)
121
+ return cached;
122
+ try {
123
+ const sourceFile = project.addSourceFileAtPath(absolutePath);
124
+ cache.set(absolutePath, sourceFile);
125
+ return sourceFile;
126
+ }
127
+ catch {
128
+ return null;
129
+ }
130
+ }
131
+ function findNamedDeclaration(sourceFile, title) {
132
+ const candidates = [];
133
+ for (const decl of sourceFile.getFunctions()) {
134
+ if (!decl.isExported())
135
+ continue;
136
+ if (decl.getName() !== title)
137
+ continue;
138
+ const nameNode = decl.getNameNode();
139
+ if (!nameNode)
140
+ continue;
141
+ candidates.push({ node: decl, getNameNode: () => nameNode });
142
+ }
143
+ for (const decl of sourceFile.getClasses()) {
144
+ if (!decl.isExported())
145
+ continue;
146
+ if (decl.getName() !== title)
147
+ continue;
148
+ const nameNode = decl.getNameNode();
149
+ if (!nameNode)
150
+ continue;
151
+ candidates.push({ node: decl, getNameNode: () => nameNode });
152
+ }
153
+ for (const decl of sourceFile.getInterfaces()) {
154
+ if (!decl.isExported())
155
+ continue;
156
+ if (decl.getName() !== title)
157
+ continue;
158
+ const nameNode = decl.getNameNode();
159
+ if (!nameNode)
160
+ continue;
161
+ candidates.push({ node: decl, getNameNode: () => nameNode });
162
+ }
163
+ for (const decl of sourceFile.getTypeAliases()) {
164
+ if (!decl.isExported())
165
+ continue;
166
+ if (decl.getName() !== title)
167
+ continue;
168
+ const nameNode = decl.getNameNode();
169
+ if (!nameNode)
170
+ continue;
171
+ candidates.push({ node: decl, getNameNode: () => nameNode });
172
+ }
173
+ for (const decl of sourceFile.getEnums()) {
174
+ if (!decl.isExported())
175
+ continue;
176
+ if (decl.getName() !== title)
177
+ continue;
178
+ const nameNode = decl.getNameNode();
179
+ if (!nameNode)
180
+ continue;
181
+ candidates.push({ node: decl, getNameNode: () => nameNode });
182
+ }
183
+ for (const statement of sourceFile.getVariableStatements()) {
184
+ if (!statement.isExported())
185
+ continue;
186
+ for (const declaration of statement.getDeclarations()) {
187
+ if (declaration.getName() !== title)
188
+ continue;
189
+ const nameNode = declaration.getNameNode();
190
+ candidates.push({ node: declaration, getNameNode: () => nameNode });
191
+ }
192
+ }
193
+ if (candidates.length === 0)
194
+ return null;
195
+ candidates.sort((a, b) => a.getNameNode().getStart() - b.getNameNode().getStart());
196
+ return candidates[0] ?? null;
197
+ }
@@ -0,0 +1,35 @@
1
+ export interface PrologOptions {
2
+ swiplPath?: string;
3
+ timeout?: number;
4
+ }
5
+ export interface QueryResult {
6
+ success: boolean;
7
+ bindings: Record<string, string>;
8
+ error?: string;
9
+ }
10
+ export declare class PrologProcess {
11
+ private process;
12
+ private swiplPath;
13
+ private timeout;
14
+ private outputBuffer;
15
+ private errorBuffer;
16
+ private cache;
17
+ private useOneShotMode;
18
+ private attachedKbPath;
19
+ private onProcessExit;
20
+ constructor(options?: PrologOptions);
21
+ start(): Promise<void>;
22
+ private waitForReady;
23
+ query(goal: string | string[]): Promise<QueryResult>;
24
+ invalidateCache(): void;
25
+ private isCacheableGoal;
26
+ private queryOneShot;
27
+ private execOneShot;
28
+ private normalizeGoal;
29
+ private extractBindings;
30
+ private translateError;
31
+ isRunning(): boolean;
32
+ getPid(): number;
33
+ terminate(): Promise<void>;
34
+ }
35
+ //# sourceMappingURL=prolog.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"prolog.d.ts","sourceRoot":"","sources":["../src/prolog.ts"],"names":[],"mappings":"AAoDA,MAAM,WAAW,aAAa;IAC5B,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB;AAED,MAAM,WAAW,WAAW;IAC1B,OAAO,EAAE,OAAO,CAAC;IACjB,QAAQ,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACjC,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;AAED,qBAAa,aAAa;IACxB,OAAO,CAAC,OAAO,CAA6B;IAC5C,OAAO,CAAC,SAAS,CAAS;IAC1B,OAAO,CAAC,OAAO,CAAS;IACxB,OAAO,CAAC,YAAY,CAAM;IAC1B,OAAO,CAAC,WAAW,CAAM;IACzB,OAAO,CAAC,KAAK,CAAuC;IACpD,OAAO,CAAC,cAAc,CACyC;IAC/D,OAAO,CAAC,cAAc,CAAuB;IAC7C,OAAO,CAAC,aAAa,CAA6B;gBAEtC,OAAO,GAAE,aAAkB;IAKjC,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;YAqCd,YAAY;IAapB,KAAK,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,EAAE,GAAG,OAAO,CAAC,WAAW,CAAC;IAmF1D,eAAe,IAAI,IAAI;IAIvB,OAAO,CAAC,eAAe;YAYT,YAAY;IA0B1B,OAAO,CAAC,WAAW;IA8EnB,OAAO,CAAC,aAAa;IAIrB,OAAO,CAAC,eAAe;IAevB,OAAO,CAAC,cAAc;IA8BtB,SAAS,IAAI,OAAO;IAIpB,MAAM,IAAI,MAAM;IAIV,SAAS,IAAI,OAAO,CAAC,IAAI,CAAC;CAyBjC"}
package/dist/prolog.js ADDED
@@ -0,0 +1,328 @@
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
+ 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
+ import { spawn, spawnSync } from "node:child_process";
46
+ import { existsSync } from "node:fs";
47
+ import path from "node:path";
48
+ import { fileURLToPath } from "node:url";
49
+ const importMetaDir = path.dirname(fileURLToPath(import.meta.url));
50
+ export class PrologProcess {
51
+ process = null;
52
+ swiplPath;
53
+ timeout;
54
+ outputBuffer = "";
55
+ errorBuffer = "";
56
+ cache = new Map();
57
+ useOneShotMode = typeof globalThis.Bun !== "undefined";
58
+ attachedKbPath = null;
59
+ onProcessExit = null;
60
+ constructor(options = {}) {
61
+ this.swiplPath = options.swiplPath || "swipl";
62
+ this.timeout = options.timeout || 30000;
63
+ }
64
+ async start() {
65
+ if (!existsSync(this.swiplPath) && this.swiplPath !== "swipl") {
66
+ throw new Error(`SWI-Prolog not found at ${this.swiplPath}. Please install SWI-Prolog or check your PATH.`);
67
+ }
68
+ const kbPath = path.resolve(importMetaDir, "../../core/src/kb.pl");
69
+ this.process = spawn(this.swiplPath, [
70
+ "-g",
71
+ `use_module('${kbPath}'), set_prolog_flag(answer_write_options, [max_depth(0), quoted(true)])`,
72
+ "--quiet",
73
+ ]);
74
+ if (!this.process.stdout || !this.process.stderr || !this.process.stdin) {
75
+ throw new Error("Failed to spawn Prolog process");
76
+ }
77
+ this.process.stdout.on("data", (chunk) => {
78
+ this.outputBuffer += chunk.toString();
79
+ });
80
+ this.process.stderr.on("data", (chunk) => {
81
+ this.errorBuffer += chunk.toString();
82
+ });
83
+ if (!this.onProcessExit) {
84
+ this.onProcessExit = () => {
85
+ void this.terminate();
86
+ };
87
+ process.on("exit", this.onProcessExit);
88
+ }
89
+ await this.waitForReady();
90
+ }
91
+ async waitForReady() {
92
+ await new Promise((resolve) => setTimeout(resolve, 500));
93
+ if (this.errorBuffer.includes("ERROR")) {
94
+ throw new Error(`Failed to load kb module: ${this.translateError(this.errorBuffer)}`);
95
+ }
96
+ this.outputBuffer = "";
97
+ this.errorBuffer = "";
98
+ }
99
+ async query(goal) {
100
+ const isSingleGoal = typeof goal === "string";
101
+ const goalKey = isSingleGoal ? goal : null;
102
+ const cacheable = goalKey !== null && this.isCacheableGoal(goalKey);
103
+ if (cacheable) {
104
+ const cachedResult = this.cache.get(goalKey);
105
+ if (cachedResult) {
106
+ return cachedResult;
107
+ }
108
+ }
109
+ if (this.useOneShotMode) {
110
+ const oneShotResult = await this.queryOneShot(goal);
111
+ if (!cacheable && oneShotResult.success) {
112
+ this.invalidateCache();
113
+ }
114
+ if (cacheable && oneShotResult.success) {
115
+ this.cache.set(goalKey, oneShotResult);
116
+ }
117
+ return oneShotResult;
118
+ }
119
+ if (!isSingleGoal) {
120
+ const batchGoal = `(${goal.map((item) => this.normalizeGoal(item)).join(", ")})`;
121
+ return this.query(batchGoal);
122
+ }
123
+ if (!this.process || !this.process.stdin) {
124
+ throw new Error("Prolog process not started");
125
+ }
126
+ this.outputBuffer = "";
127
+ this.errorBuffer = "";
128
+ this.process.stdin.write(`${goal}.
129
+ `);
130
+ return new Promise((resolve, reject) => {
131
+ const timeoutId = setTimeout(() => {
132
+ reject(new Error("Query timeout after 30s"));
133
+ }, this.timeout);
134
+ const checkResult = () => {
135
+ if (this.errorBuffer.length > 0 && this.errorBuffer.includes("ERROR")) {
136
+ clearTimeout(timeoutId);
137
+ resolve({
138
+ success: false,
139
+ bindings: {},
140
+ error: this.translateError(this.errorBuffer),
141
+ });
142
+ }
143
+ else if (this.outputBuffer.includes("true.") ||
144
+ this.outputBuffer.match(/^[A-Z_][A-Za-z0-9_]*\s*=\s*.+\./m)) {
145
+ clearTimeout(timeoutId);
146
+ const result = {
147
+ success: true,
148
+ bindings: this.extractBindings(this.outputBuffer),
149
+ };
150
+ if (cacheable) {
151
+ this.cache.set(goalKey, result);
152
+ }
153
+ resolve(result);
154
+ }
155
+ else if (this.outputBuffer.includes("false.") ||
156
+ this.outputBuffer.includes("fail.")) {
157
+ clearTimeout(timeoutId);
158
+ resolve({
159
+ success: false,
160
+ bindings: {},
161
+ error: "Query failed",
162
+ });
163
+ }
164
+ else {
165
+ setTimeout(checkResult, 50);
166
+ }
167
+ };
168
+ checkResult();
169
+ });
170
+ }
171
+ invalidateCache() {
172
+ this.cache.clear();
173
+ }
174
+ isCacheableGoal(goal) {
175
+ const trimmed = goal.trim();
176
+ return !(trimmed.startsWith("kb_attach(") ||
177
+ trimmed.startsWith("kb_detach") ||
178
+ trimmed.startsWith("kb_save") ||
179
+ trimmed.startsWith("kb_assert_") ||
180
+ trimmed.startsWith("kb_delete_") ||
181
+ trimmed.startsWith("kb_retract_"));
182
+ }
183
+ async queryOneShot(goal) {
184
+ if (Array.isArray(goal)) {
185
+ return this.execOneShot(goal, this.attachedKbPath);
186
+ }
187
+ const trimmedGoal = this.normalizeGoal(goal);
188
+ // Keep a lightweight compatibility layer for callers that rely on
189
+ // stateful attach/detach across multiple query() calls.
190
+ if (trimmedGoal.startsWith("kb_detach")) {
191
+ this.attachedKbPath = null;
192
+ return { success: true, bindings: {} };
193
+ }
194
+ const attachMatch = trimmedGoal.match(/^kb_attach\('(.+)'\)$/);
195
+ if (attachMatch) {
196
+ const attachResult = this.execOneShot(trimmedGoal, null);
197
+ if (attachResult.success) {
198
+ this.attachedKbPath = attachMatch[1];
199
+ }
200
+ return attachResult;
201
+ }
202
+ return this.execOneShot(trimmedGoal, this.attachedKbPath);
203
+ }
204
+ execOneShot(goal, kbPath) {
205
+ const goalList = Array.isArray(goal)
206
+ ? goal.map((item) => this.normalizeGoal(item))
207
+ : [this.normalizeGoal(goal)];
208
+ const isBatch = goalList.length > 1;
209
+ const combinedGoal = goalList.length === 1 ? goalList[0] : `(${goalList.join(", ")})`;
210
+ const kbModulePath = path.resolve(importMetaDir, "../../core/src/kb.pl");
211
+ const prologGoal = [
212
+ `use_module('${kbModulePath}')`,
213
+ "use_module(library(semweb/rdf_db))",
214
+ "set_prolog_flag(answer_write_options, [max_depth(0), quoted(true)])",
215
+ "getenv('KIBI_GOAL', GoalAtom)",
216
+ "read_term_from_atom(GoalAtom, Goal, [variable_names(Vars)])",
217
+ kbPath ? "getenv('KIBI_KB_PATH', KBPath), kb_attach(KBPath)" : "true",
218
+ isBatch ? "WrappedGoal = rdf_transaction(Goal)" : "WrappedGoal = Goal",
219
+ "(catch(call(WrappedGoal), E, (print_message(error, E), fail)) -> (forall(member(Name=Value, Vars), (write(Name), write('='), write_term(Value, [quoted(true), max_depth(0)]), writeln('.'))), writeln('__KIBI_TRUE__.')) ; writeln('__KIBI_FALSE__.'))",
220
+ kbPath ? "kb_save, kb_detach" : "true",
221
+ ].join(", ");
222
+ const result = spawnSync(this.swiplPath, ["-q", "-g", prologGoal, "-t", "halt"], {
223
+ encoding: "utf8",
224
+ timeout: this.timeout,
225
+ env: {
226
+ ...process.env,
227
+ KIBI_GOAL: combinedGoal,
228
+ ...(kbPath ? { KIBI_KB_PATH: kbPath } : {}),
229
+ },
230
+ stdio: ["ignore", "pipe", "pipe"],
231
+ });
232
+ if (result.error &&
233
+ (result.error.message.includes("timed out") ||
234
+ // Bun/Node differ here; keep a conservative timeout detection.
235
+ result.error.message.includes("ETIMEDOUT"))) {
236
+ throw new Error("Query timeout after 30s");
237
+ }
238
+ const stdout = result.stdout ?? "";
239
+ const stderr = result.stderr ?? "";
240
+ if (stdout.includes("__KIBI_TRUE__")) {
241
+ const clean = stdout
242
+ .split("\n")
243
+ .filter((line) => !line.includes("__KIBI_TRUE__"))
244
+ .join("\n");
245
+ return {
246
+ success: true,
247
+ bindings: this.extractBindings(clean),
248
+ };
249
+ }
250
+ if (stderr.includes("ERROR")) {
251
+ return {
252
+ success: false,
253
+ bindings: {},
254
+ error: this.translateError(stderr),
255
+ };
256
+ }
257
+ return {
258
+ success: false,
259
+ bindings: {},
260
+ error: "Query failed",
261
+ };
262
+ }
263
+ normalizeGoal(goal) {
264
+ return goal.trim().replace(/\.+\s*$/, "");
265
+ }
266
+ extractBindings(output) {
267
+ const bindings = {};
268
+ const lines = output.split("\n");
269
+ for (const line of lines) {
270
+ const match = line.match(/^([A-Z_][A-Za-z0-9_]*)\s*=\s*(.+)\.?\s*$/);
271
+ if (match) {
272
+ const [, varName, value] = match;
273
+ bindings[varName] = value.trim().replace(/\.$/, "").replace(/,$/, "");
274
+ }
275
+ }
276
+ return bindings;
277
+ }
278
+ translateError(errorText) {
279
+ if (errorText.includes("existence_error") ||
280
+ errorText.includes("Unknown procedure")) {
281
+ return "Predicate or file not found";
282
+ }
283
+ if (errorText.includes("permission_error")) {
284
+ return "Access denied or KB locked";
285
+ }
286
+ if (errorText.includes("syntax_error") ||
287
+ errorText.includes("Operator expected")) {
288
+ return "Invalid query syntax";
289
+ }
290
+ if (errorText.includes("timeout_error")) {
291
+ return "Operation exceeded 30s timeout";
292
+ }
293
+ const simpleError = errorText
294
+ .replace(/ERROR:\s*/g, "")
295
+ .replace(/^\*\*.*\*\*$/gm, "")
296
+ .replace(/^\s+/gm, "")
297
+ .split("\n")[0]
298
+ .trim();
299
+ return simpleError || "Unknown error";
300
+ }
301
+ isRunning() {
302
+ return this.process !== null && !this.process.killed;
303
+ }
304
+ getPid() {
305
+ return this.process?.pid || 0;
306
+ }
307
+ async terminate() {
308
+ if (this.onProcessExit) {
309
+ process.off("exit", this.onProcessExit);
310
+ this.onProcessExit = null;
311
+ }
312
+ if (this.process) {
313
+ this.process.stdin?.end();
314
+ this.process.kill("SIGTERM");
315
+ await new Promise((resolve) => {
316
+ const timeout = setTimeout(() => {
317
+ this.process?.kill("SIGKILL");
318
+ resolve(undefined);
319
+ }, 1000);
320
+ this.process?.on("exit", () => {
321
+ clearTimeout(timeout);
322
+ resolve(undefined);
323
+ });
324
+ });
325
+ this.process = null;
326
+ }
327
+ }
328
+ }
@@ -0,0 +1,2 @@
1
+ export { enrichSymbolCoordinates, type ManifestSymbolEntry, } from "../../extractors/symbols-coordinator.js";
2
+ //# sourceMappingURL=symbols-coordinator.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"symbols-coordinator.d.ts","sourceRoot":"","sources":["../../../src/public/extractors/symbols-coordinator.ts"],"names":[],"mappings":"AA8CA,OAAO,EACL,uBAAuB,EACvB,KAAK,mBAAmB,GACzB,MAAM,yCAAyC,CAAC"}
@@ -0,0 +1,46 @@
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
+ 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
+ // Public re-export of symbols coordinator
46
+ export { enrichSymbolCoordinates, } from "../../extractors/symbols-coordinator.js";
@@ -0,0 +1,2 @@
1
+ export { PrologProcess } from "../../prolog.js";
2
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/public/prolog/index.ts"],"names":[],"mappings":"AA8CA,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC"}
@@ -0,0 +1,46 @@
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
+ 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
+ // Public re-export of PrologProcess
46
+ export { PrologProcess } from "../../prolog.js";