kovence-cli 0.0.0-stage → 1.0.1
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.
- package/CHANGELOG.md +15 -0
- package/LICENSE +21 -0
- package/README.md +386 -2
- package/SECURITY.md +13 -0
- package/nd.js +700 -0
- package/package.json +62 -5
- package/providers.js +530 -0
- package/src/agent/history.js +157 -0
- package/src/agent/project_context.js +136 -0
- package/src/agent/resilience.js +100 -0
- package/src/agent/turn.js +782 -0
- package/src/cli/args.js +171 -0
- package/src/cli/sinks.js +326 -0
- package/src/commands/handlers.js +1280 -0
- package/src/config/memory.js +175 -0
- package/src/config/model_registry.js +123 -0
- package/src/config/paths.js +268 -0
- package/src/config/providers.js +209 -0
- package/src/config/sessions.js +201 -0
- package/src/permissions/engine.js +846 -0
- package/src/permissions/store.js +113 -0
- package/src/settings/schema.js +340 -0
- package/src/settings/store.js +136 -0
- package/src/tools/checkpoints.js +108 -0
- package/src/tools/download.js +513 -0
- package/src/tools/exec.js +155 -0
- package/src/tools/fs_walk.js +165 -0
- package/src/tools/net.js +467 -0
- package/src/tools/patch_git.js +205 -0
- package/src/tools/sudo.js +212 -0
- package/src/tools/tasks.js +127 -0
- package/src/tui/settings_panel.js +223 -0
- package/src/tui/text_width.js +218 -0
- package/src/tui/themes.js +143 -0
- package/store.js +107 -0
- package/tools.js +1267 -0
- package/tui.js +1634 -0
- package/ui.js +394 -0
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
const { ensureStorageDirs, readJsonSafe, atomicWriteJson, resolvePaths } = require("./paths");
|
|
4
|
+
|
|
5
|
+
const MAX_GLOBAL_ITEMS = 50;
|
|
6
|
+
const MAX_GLOBAL_CHARS = 8000;
|
|
7
|
+
const MAX_ITEM_CHARS = 300;
|
|
8
|
+
const MAX_SESSION_PINNED = 30;
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Normalize raw memory entries (strings or provenance objects), dedupe case-insensitively, and enforce caps.
|
|
12
|
+
*/
|
|
13
|
+
function normalizeMemoryItems(rawItems, maxItems = MAX_GLOBAL_ITEMS, maxTotalChars = MAX_GLOBAL_CHARS) {
|
|
14
|
+
if (!Array.isArray(rawItems)) return [];
|
|
15
|
+
const seen = new Set();
|
|
16
|
+
const out = [];
|
|
17
|
+
let totalChars = 0;
|
|
18
|
+
|
|
19
|
+
for (const entry of rawItems) {
|
|
20
|
+
const text = String(typeof entry === "string" ? entry : entry?.text || "")
|
|
21
|
+
.replace(/\s+/g, " ")
|
|
22
|
+
.trim()
|
|
23
|
+
.slice(0, MAX_ITEM_CHARS);
|
|
24
|
+
if (!text) continue;
|
|
25
|
+
const key = text.toLowerCase();
|
|
26
|
+
if (seen.has(key)) continue;
|
|
27
|
+
if (out.length >= maxItems || totalChars + text.length > maxTotalChars) break;
|
|
28
|
+
seen.add(key);
|
|
29
|
+
totalChars += text.length;
|
|
30
|
+
out.push({
|
|
31
|
+
text,
|
|
32
|
+
createdAt: (typeof entry === "object" && entry?.createdAt) || new Date().toISOString(),
|
|
33
|
+
source: (typeof entry === "object" && entry?.source) || "user",
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
return out;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function memoryTexts(items) {
|
|
40
|
+
return (Array.isArray(items) ? items : []).map((x) => (typeof x === "string" ? x : x.text));
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function loadGlobalMemoryEntries(paths = resolvePaths()) {
|
|
44
|
+
const data = readJsonSafe(paths.globalMemoryFile, { items: [] });
|
|
45
|
+
return normalizeMemoryItems(data.items, MAX_GLOBAL_ITEMS, MAX_GLOBAL_CHARS);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function loadGlobalMemory(paths = resolvePaths()) {
|
|
49
|
+
return memoryTexts(loadGlobalMemoryEntries(paths));
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function saveGlobalMemory(items, paths = resolvePaths()) {
|
|
53
|
+
ensureStorageDirs(paths);
|
|
54
|
+
const normalized = normalizeMemoryItems(items, MAX_GLOBAL_ITEMS, MAX_GLOBAL_CHARS);
|
|
55
|
+
atomicWriteJson(paths.globalMemoryFile, {
|
|
56
|
+
updatedAt: new Date().toISOString(),
|
|
57
|
+
items: normalized,
|
|
58
|
+
});
|
|
59
|
+
return normalized;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function addGlobalMemory(fact, source = "user", paths = resolvePaths()) {
|
|
63
|
+
const clean = String(fact || "")
|
|
64
|
+
.replace(/\s+/g, " ")
|
|
65
|
+
.trim()
|
|
66
|
+
.slice(0, MAX_ITEM_CHARS);
|
|
67
|
+
if (!clean) return false;
|
|
68
|
+
const entries = loadGlobalMemoryEntries(paths);
|
|
69
|
+
if (entries.some((x) => x.text.toLowerCase() === clean.toLowerCase())) return false;
|
|
70
|
+
if (entries.length >= MAX_GLOBAL_ITEMS) return false;
|
|
71
|
+
entries.push({ text: clean, createdAt: new Date().toISOString(), source });
|
|
72
|
+
const after = saveGlobalMemory(entries, paths);
|
|
73
|
+
return after.some((x) => x.text.toLowerCase() === clean.toLowerCase());
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function removeGlobalMemoryAt(indexZeroBased, paths = resolvePaths()) {
|
|
77
|
+
const entries = loadGlobalMemoryEntries(paths);
|
|
78
|
+
if (indexZeroBased < 0 || indexZeroBased >= entries.length) return null;
|
|
79
|
+
const [removed] = entries.splice(indexZeroBased, 1);
|
|
80
|
+
saveGlobalMemory(entries, paths);
|
|
81
|
+
return removed;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function loadProjectMemoryEntries(paths = resolvePaths()) {
|
|
85
|
+
const data = readJsonSafe(paths.projectMemoryFile, { items: [] });
|
|
86
|
+
return normalizeMemoryItems(data.items, MAX_GLOBAL_ITEMS, MAX_GLOBAL_CHARS);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function saveProjectMemory(items, paths = resolvePaths()) {
|
|
90
|
+
ensureStorageDirs(paths);
|
|
91
|
+
const normalized = normalizeMemoryItems(items, MAX_GLOBAL_ITEMS, MAX_GLOBAL_CHARS);
|
|
92
|
+
atomicWriteJson(paths.projectMemoryFile, {
|
|
93
|
+
updatedAt: new Date().toISOString(),
|
|
94
|
+
items: normalized,
|
|
95
|
+
});
|
|
96
|
+
return normalized;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
function addProjectMemory(fact, source = "user", paths = resolvePaths()) {
|
|
100
|
+
const clean = String(fact || "")
|
|
101
|
+
.replace(/\s+/g, " ")
|
|
102
|
+
.trim()
|
|
103
|
+
.slice(0, MAX_ITEM_CHARS);
|
|
104
|
+
if (!clean) return false;
|
|
105
|
+
const entries = loadProjectMemoryEntries(paths);
|
|
106
|
+
if (entries.some((x) => x.text.toLowerCase() === clean.toLowerCase())) return false;
|
|
107
|
+
entries.push({ text: clean, createdAt: new Date().toISOString(), source });
|
|
108
|
+
saveProjectMemory(entries, paths);
|
|
109
|
+
return true;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
const LOCAL_ONLY_RE = /\b(this session|current session|only here|ei session|session memory|local memory)\b/i;
|
|
113
|
+
const EXPLICIT_MEMORY_RE =
|
|
114
|
+
/^(?:please\s+)?(?:remember(?:\s+(?:that|this))?|always\s+remember|save\s+(?:this\s+)?(?:to\s+)?(?:global|default|project|session)?\s*memory:?|mone\s+rakh(?:o|be|is)|et[ai]\s+mone\s+rakho)\b/i;
|
|
115
|
+
const EXPLICIT_DIRECTIVE_PREF_RE =
|
|
116
|
+
/^(?:from\s+now\s+on(?:,)?\s+|ekhon\s+theke(?:,)?\s+)(?:always|sobsomoy|shobsomoy|never)\s+(?:reply|respond|talk|speak|write|use|format|answer)\b/i;
|
|
117
|
+
const QUESTION_RE =
|
|
118
|
+
/\?\s*$|^(why|how|what|when|where|who|which|is|are|can|could|does|do|did|keno|kivabe|ki|kobe|kothay)\b/i;
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* Only classify explicit memory requests so ordinary bug reports containing "always"/"never" never become rules.
|
|
122
|
+
*/
|
|
123
|
+
function classifyMemoryIntent(userText) {
|
|
124
|
+
const clean = String(userText || "").trim();
|
|
125
|
+
if (!clean || clean.length > MAX_ITEM_CHARS) return null;
|
|
126
|
+
if (clean.startsWith("/") && !/^\/remember\b/i.test(clean)) return null;
|
|
127
|
+
if (QUESTION_RE.test(clean)) return null;
|
|
128
|
+
|
|
129
|
+
let body = clean;
|
|
130
|
+
if (/^\/remember\b/i.test(clean)) {
|
|
131
|
+
body = clean.replace(/^\/remember\s*/i, "").trim();
|
|
132
|
+
if (!body) return null;
|
|
133
|
+
const scope = LOCAL_ONLY_RE.test(body) ? "session" : "global";
|
|
134
|
+
return { scope, fact: body, explicitCommand: true };
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
if (EXPLICIT_MEMORY_RE.test(clean) || EXPLICIT_DIRECTIVE_PREF_RE.test(clean)) {
|
|
138
|
+
body =
|
|
139
|
+
clean
|
|
140
|
+
.replace(
|
|
141
|
+
/^(?:please\s+)?(?:remember(?:\s+(?:that|this))?|always\s+remember|save\s+(?:this\s+)?(?:to\s+)?(?:global|default|project|session)?\s*memory:?)\s*/i,
|
|
142
|
+
""
|
|
143
|
+
)
|
|
144
|
+
.trim() || clean;
|
|
145
|
+
const scope = LOCAL_ONLY_RE.test(clean) ? "session" : "global";
|
|
146
|
+
return { scope, fact: body, explicitCommand: false };
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
return null;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* Explicitly disabled auto-promotion heuristic for B4 safety; legacy callers get false unless explicit.
|
|
154
|
+
*/
|
|
155
|
+
function isGlobalMemoryFact() {
|
|
156
|
+
return false;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
module.exports = {
|
|
160
|
+
MAX_GLOBAL_ITEMS,
|
|
161
|
+
MAX_GLOBAL_CHARS,
|
|
162
|
+
MAX_ITEM_CHARS,
|
|
163
|
+
MAX_SESSION_PINNED,
|
|
164
|
+
normalizeMemoryItems,
|
|
165
|
+
loadGlobalMemoryEntries,
|
|
166
|
+
loadGlobalMemory,
|
|
167
|
+
saveGlobalMemory,
|
|
168
|
+
addGlobalMemory,
|
|
169
|
+
removeGlobalMemoryAt,
|
|
170
|
+
loadProjectMemoryEntries,
|
|
171
|
+
saveProjectMemory,
|
|
172
|
+
addProjectMemory,
|
|
173
|
+
classifyMemoryIntent,
|
|
174
|
+
isGlobalMemoryFact,
|
|
175
|
+
};
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
const MODEL_PROFILES = [
|
|
4
|
+
{
|
|
5
|
+
match: /claude-(?:3-7|sonnet-4|opus-4|haiku-4|3-5)/i,
|
|
6
|
+
contextWindow: 200000,
|
|
7
|
+
supportsTemperature: true,
|
|
8
|
+
supportsTools: true,
|
|
9
|
+
inputPer1M: 3.0,
|
|
10
|
+
outputPer1M: 15.0,
|
|
11
|
+
},
|
|
12
|
+
{
|
|
13
|
+
match: /claude-3/i,
|
|
14
|
+
contextWindow: 200000,
|
|
15
|
+
supportsTemperature: true,
|
|
16
|
+
supportsTools: true,
|
|
17
|
+
inputPer1M: 3.0,
|
|
18
|
+
outputPer1M: 15.0,
|
|
19
|
+
},
|
|
20
|
+
{
|
|
21
|
+
match: /\b(?:o1|o3|o4)(?:-|$)/i,
|
|
22
|
+
contextWindow: 200000,
|
|
23
|
+
supportsTemperature: false,
|
|
24
|
+
supportsTools: true,
|
|
25
|
+
inputPer1M: 2.0,
|
|
26
|
+
outputPer1M: 8.0,
|
|
27
|
+
},
|
|
28
|
+
{
|
|
29
|
+
match: /gpt-4\.1/i,
|
|
30
|
+
contextWindow: 1000000,
|
|
31
|
+
supportsTemperature: true,
|
|
32
|
+
supportsTools: true,
|
|
33
|
+
inputPer1M: 2.0,
|
|
34
|
+
outputPer1M: 8.0,
|
|
35
|
+
},
|
|
36
|
+
{
|
|
37
|
+
match: /gpt-4o-mini/i,
|
|
38
|
+
contextWindow: 128000,
|
|
39
|
+
supportsTemperature: true,
|
|
40
|
+
supportsTools: true,
|
|
41
|
+
inputPer1M: 0.15,
|
|
42
|
+
outputPer1M: 0.6,
|
|
43
|
+
},
|
|
44
|
+
{
|
|
45
|
+
match: /gpt-4o/i,
|
|
46
|
+
contextWindow: 128000,
|
|
47
|
+
supportsTemperature: true,
|
|
48
|
+
supportsTools: true,
|
|
49
|
+
inputPer1M: 2.5,
|
|
50
|
+
outputPer1M: 10.0,
|
|
51
|
+
},
|
|
52
|
+
{
|
|
53
|
+
match: /gemini-(?:2|2\.5|3|4)/i,
|
|
54
|
+
contextWindow: 1000000,
|
|
55
|
+
supportsTemperature: true,
|
|
56
|
+
supportsTools: true,
|
|
57
|
+
inputPer1M: 1.25,
|
|
58
|
+
outputPer1M: 5.0,
|
|
59
|
+
},
|
|
60
|
+
{
|
|
61
|
+
match: /gemma-/i,
|
|
62
|
+
contextWindow: 128000,
|
|
63
|
+
supportsTemperature: true,
|
|
64
|
+
supportsTools: true,
|
|
65
|
+
inputPer1M: 0.1,
|
|
66
|
+
outputPer1M: 0.2,
|
|
67
|
+
},
|
|
68
|
+
{
|
|
69
|
+
match: /deepseek-r1|deepseek-reasoner/i,
|
|
70
|
+
contextWindow: 128000,
|
|
71
|
+
supportsTemperature: false,
|
|
72
|
+
supportsTools: true,
|
|
73
|
+
inputPer1M: 0.55,
|
|
74
|
+
outputPer1M: 2.19,
|
|
75
|
+
},
|
|
76
|
+
{
|
|
77
|
+
match: /deepseek/i,
|
|
78
|
+
contextWindow: 128000,
|
|
79
|
+
supportsTemperature: true,
|
|
80
|
+
supportsTools: true,
|
|
81
|
+
inputPer1M: 0.27,
|
|
82
|
+
outputPer1M: 1.1,
|
|
83
|
+
},
|
|
84
|
+
{
|
|
85
|
+
match: /qwen|llama-3/i,
|
|
86
|
+
contextWindow: 128000,
|
|
87
|
+
supportsTemperature: true,
|
|
88
|
+
supportsTools: true,
|
|
89
|
+
inputPer1M: 0.2,
|
|
90
|
+
outputPer1M: 0.6,
|
|
91
|
+
},
|
|
92
|
+
];
|
|
93
|
+
|
|
94
|
+
function lookupModelCapabilities(modelId = "") {
|
|
95
|
+
const clean = String(modelId || "").trim();
|
|
96
|
+
for (const p of MODEL_PROFILES) {
|
|
97
|
+
if (p.match.test(clean)) return { ...p };
|
|
98
|
+
}
|
|
99
|
+
return {
|
|
100
|
+
contextWindow: 128000,
|
|
101
|
+
supportsTemperature: true,
|
|
102
|
+
supportsTools: true,
|
|
103
|
+
inputPer1M: 0,
|
|
104
|
+
outputPer1M: 0,
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function estimateTokenCostUsd(modelId, promptTokens = 0, completionTokens = 0) {
|
|
109
|
+
const prof = lookupModelCapabilities(modelId);
|
|
110
|
+
const inCost = (Math.max(0, Number(promptTokens) || 0) / 1_000_000) * (prof.inputPer1M || 0);
|
|
111
|
+
const outCost = (Math.max(0, Number(completionTokens) || 0) / 1_000_000) * (prof.outputPer1M || 0);
|
|
112
|
+
return {
|
|
113
|
+
totalUsd: inCost + outCost,
|
|
114
|
+
inCost,
|
|
115
|
+
outCost,
|
|
116
|
+
knownPricing: Boolean(prof.inputPer1M || prof.outputPer1M),
|
|
117
|
+
};
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
module.exports = {
|
|
121
|
+
lookupModelCapabilities,
|
|
122
|
+
estimateTokenCostUsd,
|
|
123
|
+
};
|
|
@@ -0,0 +1,268 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
const fs = require("node:fs");
|
|
4
|
+
const os = require("node:os");
|
|
5
|
+
const path = require("node:path");
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Sanitize an arbitrary identifier into a safe filename stem.
|
|
9
|
+
*/
|
|
10
|
+
function safeId(name) {
|
|
11
|
+
return (
|
|
12
|
+
String(name || "default")
|
|
13
|
+
.trim()
|
|
14
|
+
.replace(/[^a-zA-Z0-9._-]/g, "_") || "default"
|
|
15
|
+
);
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Walk upward from cwd to locate the nearest git repository root, falling back to cwd.
|
|
20
|
+
*/
|
|
21
|
+
function findProjectRoot(cwd = process.cwd()) {
|
|
22
|
+
let dir = path.resolve(cwd);
|
|
23
|
+
while (true) {
|
|
24
|
+
if (fs.existsSync(path.join(dir, ".git"))) return dir;
|
|
25
|
+
const parent = path.dirname(dir);
|
|
26
|
+
if (parent === dir) return path.resolve(cwd);
|
|
27
|
+
dir = parent;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Resolve all global (~/.config/kovence) and per-project (<project>/.kovence) paths.
|
|
33
|
+
*/
|
|
34
|
+
function resolvePaths(options = {}) {
|
|
35
|
+
const cwd = path.resolve(options.cwd || process.cwd());
|
|
36
|
+
const projectRoot = path.resolve(options.projectRoot || findProjectRoot(cwd));
|
|
37
|
+
const xdgConfig = process.env.XDG_CONFIG_HOME || path.join(os.homedir(), ".config");
|
|
38
|
+
const globalDir = path.resolve(
|
|
39
|
+
options.globalDir || process.env.KOVENCE_CONFIG_DIR || path.join(xdgConfig, "kovence")
|
|
40
|
+
);
|
|
41
|
+
const projectDir = path.resolve(options.projectDir || path.join(projectRoot, ".kovence"));
|
|
42
|
+
|
|
43
|
+
return {
|
|
44
|
+
cwd,
|
|
45
|
+
projectRoot,
|
|
46
|
+
globalDir,
|
|
47
|
+
projectDir,
|
|
48
|
+
sessionsDir: path.join(projectDir, "sessions"),
|
|
49
|
+
checkpointsDir: path.join(projectDir, "checkpoints"),
|
|
50
|
+
commandsDir: path.join(projectDir, "commands"),
|
|
51
|
+
settingsFile: path.join(globalDir, "settings.json"),
|
|
52
|
+
providersFile: path.join(globalDir, "providers.json"),
|
|
53
|
+
globalMemoryFile: path.join(globalDir, "global_memory.json"),
|
|
54
|
+
globalPermissionsFile: path.join(globalDir, "permissions.json"),
|
|
55
|
+
inputHistoryFile: path.join(globalDir, "input_history.json"),
|
|
56
|
+
projectMemoryFile: path.join(projectDir, "project_memory.json"),
|
|
57
|
+
projectPermissionsFile: path.join(projectDir, "permissions.json"),
|
|
58
|
+
migrationMarkerFile: path.join(projectDir, ".migrated_from_ai_harness"),
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Ensure .kovence/ is ignored via .git/info/exclude so user repos stay clean without editing .gitignore.
|
|
64
|
+
*/
|
|
65
|
+
function ensureGitInfoExclude(projectRoot) {
|
|
66
|
+
try {
|
|
67
|
+
const gitPath = path.join(projectRoot, ".git");
|
|
68
|
+
if (!fs.existsSync(gitPath) || !fs.statSync(gitPath).isDirectory()) return false;
|
|
69
|
+
const infoDir = path.join(gitPath, "info");
|
|
70
|
+
const excludeFile = path.join(infoDir, "exclude");
|
|
71
|
+
fs.mkdirSync(infoDir, { recursive: true });
|
|
72
|
+
const existing = fs.existsSync(excludeFile) ? fs.readFileSync(excludeFile, "utf8") : "";
|
|
73
|
+
const lines = existing.split(/\r?\n/).map((l) => l.trim());
|
|
74
|
+
if (lines.includes(".kovence") || lines.includes(".kovence/")) return false;
|
|
75
|
+
const prefix = existing && !existing.endsWith("\n") ? "\n" : "";
|
|
76
|
+
fs.writeFileSync(excludeFile, `${existing}${prefix}.kovence/\n`, "utf8");
|
|
77
|
+
return true;
|
|
78
|
+
} catch {
|
|
79
|
+
return false;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Ensure global and project storage directories exist with appropriate permissions.
|
|
85
|
+
*/
|
|
86
|
+
function ensureStorageDirs(paths) {
|
|
87
|
+
fs.mkdirSync(paths.globalDir, { recursive: true, mode: 0o700 });
|
|
88
|
+
fs.mkdirSync(paths.projectDir, { recursive: true });
|
|
89
|
+
fs.mkdirSync(paths.sessionsDir, { recursive: true });
|
|
90
|
+
ensureGitInfoExclude(paths.projectRoot);
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* Read JSON file safely with a fallback when missing or corrupt.
|
|
95
|
+
*/
|
|
96
|
+
function readJsonSafe(file, fallback) {
|
|
97
|
+
try {
|
|
98
|
+
if (!fs.existsSync(file)) return fallback;
|
|
99
|
+
return JSON.parse(fs.readFileSync(file, "utf8"));
|
|
100
|
+
} catch {
|
|
101
|
+
return fallback;
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* Atomically write JSON via temp file + rename and optional POSIX permissions mode.
|
|
107
|
+
*/
|
|
108
|
+
function atomicWriteJson(file, data, mode = null) {
|
|
109
|
+
const dir = path.dirname(file);
|
|
110
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
111
|
+
const tmp = path.join(dir, `.tmp.${path.basename(file)}.${process.pid}.${Date.now()}`);
|
|
112
|
+
fs.writeFileSync(tmp, JSON.stringify(data, null, 2) + "\n", {
|
|
113
|
+
encoding: "utf8",
|
|
114
|
+
mode: mode ?? 0o644,
|
|
115
|
+
});
|
|
116
|
+
fs.renameSync(tmp, file);
|
|
117
|
+
if (mode !== null) {
|
|
118
|
+
try {
|
|
119
|
+
fs.chmodSync(file, mode);
|
|
120
|
+
} catch {
|
|
121
|
+
// Non-POSIX filesystems may ignore chmod.
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* Normalize legacy .ai_harness settings before saving to global Kovence settings.
|
|
128
|
+
*/
|
|
129
|
+
function sanitizeMigratedSettings(rawSettings) {
|
|
130
|
+
if (!rawSettings || typeof rawSettings !== "object") return null;
|
|
131
|
+
const next = { ...rawSettings };
|
|
132
|
+
if (next.autoApprove === true && !next.agentMode) {
|
|
133
|
+
next.agentMode = "auto";
|
|
134
|
+
}
|
|
135
|
+
delete next.autoApprove;
|
|
136
|
+
if (typeof next.systemPrompt === "string") {
|
|
137
|
+
next.systemPrompt = next.systemPrompt
|
|
138
|
+
.split("\n")
|
|
139
|
+
.filter((line) => !line.startsWith("Workspace: "))
|
|
140
|
+
.join("\n");
|
|
141
|
+
}
|
|
142
|
+
return next;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* Migrate data once from legacy .ai_harness/ dirs into ~/.config/kovence and <project>/.kovence.
|
|
147
|
+
* Never overwrites newer data and keeps the legacy directory intact as a backup.
|
|
148
|
+
*/
|
|
149
|
+
function migrateLegacyAiHarness(paths) {
|
|
150
|
+
if (fs.existsSync(paths.migrationMarkerFile)) return { migrated: false, reason: "already-migrated" };
|
|
151
|
+
|
|
152
|
+
const candidates = Array.from(
|
|
153
|
+
new Set([path.join(paths.cwd, ".ai_harness"), path.join(paths.projectRoot, ".ai_harness")])
|
|
154
|
+
).filter((dir) => fs.existsSync(dir) && fs.statSync(dir).isDirectory());
|
|
155
|
+
|
|
156
|
+
if (candidates.length === 0) return { migrated: false, reason: "no-legacy-dir" };
|
|
157
|
+
|
|
158
|
+
ensureStorageDirs(paths);
|
|
159
|
+
const summary = {
|
|
160
|
+
migratedAt: new Date().toISOString(),
|
|
161
|
+
sources: candidates,
|
|
162
|
+
sessionsCopied: 0,
|
|
163
|
+
memoryMerged: 0,
|
|
164
|
+
settingsMigrated: false,
|
|
165
|
+
providersMigrated: 0,
|
|
166
|
+
};
|
|
167
|
+
|
|
168
|
+
for (const legacyDir of candidates) {
|
|
169
|
+
// 1. Sessions -> <project>/.kovence/sessions (copy without overwriting)
|
|
170
|
+
const legacySessions = path.join(legacyDir, "sessions");
|
|
171
|
+
if (fs.existsSync(legacySessions)) {
|
|
172
|
+
for (const entry of fs.readdirSync(legacySessions)) {
|
|
173
|
+
if (!entry.endsWith(".json")) continue;
|
|
174
|
+
const src = path.join(legacySessions, entry);
|
|
175
|
+
const dest = path.join(paths.sessionsDir, safeId(entry.replace(/\.json$/, "")) + ".json");
|
|
176
|
+
if (!fs.existsSync(dest)) {
|
|
177
|
+
const data = readJsonSafe(src, null);
|
|
178
|
+
if (data) {
|
|
179
|
+
atomicWriteJson(dest, data);
|
|
180
|
+
summary.sessionsCopied += 1;
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
// 2. Global memory -> ~/.config/kovence/global_memory.json (deduped merge)
|
|
187
|
+
const legacyMem = readJsonSafe(path.join(legacyDir, "global_memory.json"), null);
|
|
188
|
+
if (legacyMem && Array.isArray(legacyMem.items) && legacyMem.items.length > 0) {
|
|
189
|
+
const current = readJsonSafe(paths.globalMemoryFile, { items: [] });
|
|
190
|
+
const existingItems = Array.isArray(current.items) ? current.items : [];
|
|
191
|
+
const seen = new Set(
|
|
192
|
+
existingItems.map((x) =>
|
|
193
|
+
String(typeof x === "string" ? x : x?.text || "")
|
|
194
|
+
.trim()
|
|
195
|
+
.toLowerCase()
|
|
196
|
+
)
|
|
197
|
+
);
|
|
198
|
+
let added = 0;
|
|
199
|
+
for (const rawItem of legacyMem.items) {
|
|
200
|
+
const text = String(typeof rawItem === "string" ? rawItem : rawItem?.text || "").trim();
|
|
201
|
+
if (!text || seen.has(text.toLowerCase())) continue;
|
|
202
|
+
seen.add(text.toLowerCase());
|
|
203
|
+
existingItems.push({
|
|
204
|
+
text,
|
|
205
|
+
createdAt: (typeof rawItem === "object" && rawItem?.createdAt) || new Date().toISOString(),
|
|
206
|
+
source: "migrated",
|
|
207
|
+
});
|
|
208
|
+
added += 1;
|
|
209
|
+
}
|
|
210
|
+
if (added > 0) {
|
|
211
|
+
atomicWriteJson(paths.globalMemoryFile, {
|
|
212
|
+
updatedAt: new Date().toISOString(),
|
|
213
|
+
items: existingItems,
|
|
214
|
+
});
|
|
215
|
+
summary.memoryMerged += added;
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
// 3. Settings -> ~/.config/kovence/settings.json (only if absent)
|
|
220
|
+
if (!fs.existsSync(paths.settingsFile)) {
|
|
221
|
+
const legacySettings = readJsonSafe(path.join(legacyDir, "settings.json"), null);
|
|
222
|
+
const cleaned = sanitizeMigratedSettings(legacySettings);
|
|
223
|
+
if (cleaned) {
|
|
224
|
+
atomicWriteJson(paths.settingsFile, cleaned);
|
|
225
|
+
summary.settingsMigrated = true;
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
// 4. Providers -> ~/.config/kovence/providers.json (strip env 'default', chmod 600)
|
|
230
|
+
const legacyProv = readJsonSafe(path.join(legacyDir, "providers.json"), null);
|
|
231
|
+
if (legacyProv && legacyProv.providers && typeof legacyProv.providers === "object") {
|
|
232
|
+
const currentProv = readJsonSafe(paths.providersFile, { active: "default", providers: {} });
|
|
233
|
+
const merged = { ...(currentProv.providers || {}) };
|
|
234
|
+
let count = 0;
|
|
235
|
+
for (const [key, val] of Object.entries(legacyProv.providers)) {
|
|
236
|
+
if (key === "default" || !val || typeof val !== "object") continue;
|
|
237
|
+
if (!merged[key]) {
|
|
238
|
+
merged[key] = { ...val, name: safeId(key) };
|
|
239
|
+
count += 1;
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
const nextActive =
|
|
243
|
+
currentProv.active && (currentProv.active === "default" || merged[currentProv.active])
|
|
244
|
+
? currentProv.active
|
|
245
|
+
: legacyProv.active && merged[legacyProv.active]
|
|
246
|
+
? legacyProv.active
|
|
247
|
+
: "default";
|
|
248
|
+
if (count > 0 || !fs.existsSync(paths.providersFile)) {
|
|
249
|
+
atomicWriteJson(paths.providersFile, { active: nextActive, providers: merged }, 0o600);
|
|
250
|
+
summary.providersMigrated += count;
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
atomicWriteJson(paths.migrationMarkerFile, summary);
|
|
256
|
+
return { migrated: true, summary };
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
module.exports = {
|
|
260
|
+
safeId,
|
|
261
|
+
findProjectRoot,
|
|
262
|
+
resolvePaths,
|
|
263
|
+
ensureGitInfoExclude,
|
|
264
|
+
ensureStorageDirs,
|
|
265
|
+
readJsonSafe,
|
|
266
|
+
atomicWriteJson,
|
|
267
|
+
migrateLegacyAiHarness,
|
|
268
|
+
};
|