@floydous/pi-agent-kernel 0.4.0 → 0.4.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.
@@ -26,6 +26,7 @@ export interface EditingConfig {
26
26
  mode: "smart_anchor" | "standard";
27
27
  default_anchors: boolean;
28
28
  read_mode: "auto" | "plain" | "anchored";
29
+ syntax_gate?: "warn" | "block";
29
30
  }
30
31
 
31
32
  export interface KernelConfigOverrides {
@@ -75,7 +76,7 @@ const DEFAULT_CONFIG: KernelConfig = {
75
76
  safety: {
76
77
  enable_epistemic_guard: true,
77
78
  max_line_length: 300,
78
- max_lines: 40,
79
+ max_lines: 100,
79
80
  max_total_bytes: 20 * 1024,
80
81
  exec_timeout_ms: 5000,
81
82
  },
@@ -83,6 +84,7 @@ const DEFAULT_CONFIG: KernelConfig = {
83
84
  mode: "smart_anchor",
84
85
  default_anchors: false,
85
86
  read_mode: "plain",
87
+ syntax_gate: "warn",
86
88
  },
87
89
  lsp: {
88
90
  idle_timeout_ms: 5 * 60 * 1000, // 5 minutes
@@ -100,6 +102,138 @@ const DEFAULT_CONFIG: KernelConfig = {
100
102
  },
101
103
  };
102
104
 
105
+ export class KernelConfigError extends Error {}
106
+
107
+ const ALLOWED_CONFIG_KEYS: Record<keyof KernelConfig, ReadonlySet<string>> = {
108
+ retrieval: new Set([
109
+ "default_profile",
110
+ "repo_map_budget",
111
+ "repo_map_min_files",
112
+ "repo_map_min_bytes",
113
+ "max_search_results",
114
+ "enable_tools",
115
+ ]),
116
+ safety: new Set([
117
+ "enable_epistemic_guard",
118
+ "max_line_length",
119
+ "max_lines",
120
+ "max_total_bytes",
121
+ "exec_timeout_ms",
122
+ ]),
123
+ editing: new Set(["mode", "default_anchors", "read_mode", "syntax_gate"]),
124
+ lsp: new Set([
125
+ "idle_timeout_ms",
126
+ "diagnostic_timeout_ms",
127
+ "init_timeout_ms",
128
+ "spinner_interval_ms",
129
+ "disabled_servers",
130
+ ]),
131
+ ui: new Set(["enable_pastel_footer"]),
132
+ instructions: new Set(["enabled", "pi_docs"]),
133
+ };
134
+
135
+ function configPath(parts: string[]): string {
136
+ return parts.join(".");
137
+ }
138
+
139
+ function requireBoolean(value: unknown, path: string): void {
140
+ if (typeof value !== "boolean") throw new KernelConfigError(`${path} must be a boolean`);
141
+ }
142
+
143
+ function requireSafeInt(value: unknown, path: string, min: number, max: number): void {
144
+ if (!Number.isSafeInteger(value) || (value as number) < min || (value as number) > max) {
145
+ throw new KernelConfigError(`${path} must be a safe integer between ${min} and ${max}`);
146
+ }
147
+ }
148
+
149
+ function requireEnum<T extends string>(value: unknown, path: string, values: readonly T[]): void {
150
+ if (typeof value !== "string" || !values.includes(value as T)) {
151
+ throw new KernelConfigError(`${path} must be one of: ${values.join(", ")}`);
152
+ }
153
+ }
154
+
155
+ export function validateKernelConfig(config: KernelConfig): KernelConfig {
156
+ for (const section of Object.keys(config) as Array<keyof KernelConfig>) {
157
+ const value = (config as any)[section];
158
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
159
+ throw new KernelConfigError(`${section} must be a table`);
160
+ }
161
+ for (const key of Object.keys(value)) {
162
+ if (!ALLOWED_CONFIG_KEYS[section].has(key)) {
163
+ throw new KernelConfigError(`Unknown configuration key: ${configPath([section, key])}`);
164
+ }
165
+ }
166
+ }
167
+
168
+ const retrieval = config.retrieval;
169
+ requireEnum(retrieval.default_profile, "retrieval.default_profile", ["auto", "lean", "hybrid", "full", "off"]);
170
+ requireSafeInt(retrieval.repo_map_budget, "retrieval.repo_map_budget", 64, 32_768);
171
+ requireSafeInt(retrieval.repo_map_min_files, "retrieval.repo_map_min_files", 0, 10_000);
172
+ requireSafeInt(retrieval.repo_map_min_bytes, "retrieval.repo_map_min_bytes", 0, 1024 * 1024 * 1024);
173
+ requireSafeInt(retrieval.max_search_results, "retrieval.max_search_results", 1, 15);
174
+ requireBoolean(retrieval.enable_tools, "retrieval.enable_tools");
175
+
176
+ const safety = config.safety;
177
+ requireBoolean(safety.enable_epistemic_guard, "safety.enable_epistemic_guard");
178
+ requireSafeInt(safety.max_line_length, "safety.max_line_length", 20, 10_000);
179
+ requireSafeInt(safety.max_lines, "safety.max_lines", 1, 10_000);
180
+ requireSafeInt(safety.max_total_bytes, "safety.max_total_bytes", 64, 10 * 1024 * 1024);
181
+ requireSafeInt(safety.exec_timeout_ms, "safety.exec_timeout_ms", 100, 120_000);
182
+
183
+ requireEnum(config.editing.mode, "editing.mode", ["smart_anchor", "standard"]);
184
+ requireBoolean(config.editing.default_anchors, "editing.default_anchors");
185
+ requireEnum(config.editing.read_mode, "editing.read_mode", ["auto", "plain", "anchored"]);
186
+ if (config.editing.syntax_gate !== undefined) {
187
+ requireEnum(config.editing.syntax_gate, "editing.syntax_gate", ["warn", "block"]);
188
+ }
189
+
190
+ requireSafeInt(config.lsp.idle_timeout_ms, "lsp.idle_timeout_ms", 1_000, 60 * 60 * 1_000);
191
+ requireSafeInt(config.lsp.diagnostic_timeout_ms, "lsp.diagnostic_timeout_ms", 100, 120_000);
192
+ requireSafeInt(config.lsp.init_timeout_ms, "lsp.init_timeout_ms", 100, 5 * 60 * 1_000);
193
+ requireSafeInt(config.lsp.spinner_interval_ms, "lsp.spinner_interval_ms", 16, 1_000);
194
+ if (
195
+ !Array.isArray(config.lsp.disabled_servers) ||
196
+ config.lsp.disabled_servers.length > 64 ||
197
+ config.lsp.disabled_servers.some(
198
+ (server) => typeof server !== "string" || !/^[a-z0-9._-]{1,64}$/i.test(server),
199
+ )
200
+ ) {
201
+ throw new KernelConfigError("lsp.disabled_servers must be an array of up to 64 safe server keys");
202
+ }
203
+
204
+ requireBoolean(config.ui.enable_pastel_footer, "ui.enable_pastel_footer");
205
+ requireBoolean(config.instructions.enabled, "instructions.enabled");
206
+ requireBoolean(config.instructions.pi_docs, "instructions.pi_docs");
207
+ return config;
208
+ }
209
+
210
+ export function mergeKernelConfig(target: KernelConfig, source: unknown): KernelConfig {
211
+ const candidate = structuredClone(target);
212
+ if (!source || typeof source !== "object" || Array.isArray(source)) {
213
+ throw new KernelConfigError("Configuration root must be a table");
214
+ }
215
+ for (const [section, value] of Object.entries(source as Record<string, unknown>)) {
216
+ if (!ALLOWED_CONFIG_KEYS[section as keyof KernelConfig]) {
217
+ throw new KernelConfigError(`Unknown configuration section: ${section}`);
218
+ }
219
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
220
+ throw new KernelConfigError(`${section} must be a table`);
221
+ }
222
+ for (const key of Object.keys(value as Record<string, unknown>)) {
223
+ if (!ALLOWED_CONFIG_KEYS[section as keyof KernelConfig].has(key)) {
224
+ throw new KernelConfigError(`Unknown configuration key: ${configPath([section, key])}`);
225
+ }
226
+ }
227
+ }
228
+ mergeDeep(candidate, source);
229
+ validateKernelConfig(candidate);
230
+ for (const key of Object.keys(target) as Array<keyof KernelConfig>) {
231
+ delete (target as any)[key];
232
+ }
233
+ Object.assign(target, candidate);
234
+ return target;
235
+ }
236
+
103
237
  /**
104
238
  * Resolve ~/.pi root directory
105
239
  */
@@ -129,18 +263,15 @@ export function getGlobalConfigPath(): string {
129
263
  }
130
264
 
131
265
  /**
132
- * Resolve workspace project-local configuration path (.pi/config.toml, agent-kernel/config.toml, or config.toml)
266
+ * Resolve workspace project-local configuration path (.pi/config.toml only).
267
+ * Generic root config.toml and agent-kernel/config.toml are intentionally ignored.
133
268
  */
134
269
  export function getProjectConfigPath(cwd = process.cwd()): string | null {
135
270
  let current = path.resolve(cwd);
136
271
  const root = path.parse(current).root;
137
272
 
138
273
  while (current && current !== root) {
139
- const candidates = [
140
- path.join(current, ".pi", "config.toml"),
141
- path.join(current, "config.toml"),
142
- path.join(current, "agent-kernel", "config.toml"),
143
- ];
274
+ const candidates = [path.join(current, ".pi", "config.toml")];
144
275
  for (const candidate of candidates) {
145
276
  if (fs.existsSync(candidate)) {
146
277
  return candidate;
@@ -158,7 +289,10 @@ export function getProjectConfigPath(cwd = process.cwd()): string | null {
158
289
  * Load and merge hierarchical configuration:
159
290
  * Defaults -> Global (~/.pi/agent/config.toml) -> Project (.pi/config.toml) -> Environment Variables
160
291
  */
161
- export function loadKernelConfig(cwd = process.cwd()): KernelConfig {
292
+ export function loadKernelConfig(
293
+ cwd = process.cwd(),
294
+ options: { projectTrusted?: boolean } = {},
295
+ ): KernelConfig {
162
296
  // Deep clone defaults
163
297
  const config: KernelConfig = structuredClone(DEFAULT_CONFIG);
164
298
 
@@ -168,19 +302,21 @@ export function loadKernelConfig(cwd = process.cwd()): KernelConfig {
168
302
  try {
169
303
  const raw = fs.readFileSync(globalPath, "utf-8");
170
304
  const parsed = parseToml(raw);
171
- mergeDeep(config, parsed);
305
+ mergeKernelConfig(config, parsed);
172
306
  } catch (e) {
173
307
  kernelDebug(e);
174
308
  }
175
309
  }
176
310
 
177
311
  // 2. Merge Project-Local Config if present
178
- const projectPath = getProjectConfigPath(cwd);
312
+ const projectPath = options.projectTrusted === true
313
+ ? getProjectConfigPath(cwd)
314
+ : null;
179
315
  if (projectPath && fs.existsSync(projectPath)) {
180
316
  try {
181
317
  const raw = fs.readFileSync(projectPath, "utf-8");
182
318
  const parsed = parseToml(raw);
183
- mergeDeep(config, parsed);
319
+ mergeKernelConfig(config, parsed);
184
320
  } catch (e) {
185
321
  kernelDebug(e);
186
322
  }
@@ -199,7 +335,7 @@ export function loadKernelConfig(cwd = process.cwd()): KernelConfig {
199
335
  }
200
336
  }
201
337
 
202
- return config;
338
+ return validateKernelConfig(config);
203
339
  }
204
340
 
205
341
  /**
@@ -212,15 +348,11 @@ export function saveGlobalKernelConfig(updates: KernelConfigOverrides): void {
212
348
  fs.mkdirSync(parentDir, { recursive: true });
213
349
  }
214
350
 
215
- let existing: Record<string, TomlValue> = {};
216
- if (fs.existsSync(globalPath)) {
217
- try {
218
- existing = parseToml(fs.readFileSync(globalPath, "utf-8"));
219
- } catch (e) {
220
- kernelDebug(e);
221
- }
222
- }
223
-
351
+ const existing: Record<string, TomlValue> = fs.existsSync(globalPath)
352
+ ? parseToml(fs.readFileSync(globalPath, "utf-8"))
353
+ : {};
354
+ validateConfigDocument(existing);
355
+ validateConfigDocument({ ...existing, ...updates });
224
356
  mergeDeep(existing, updates);
225
357
  const tomlString = stringifyToml(existing);
226
358
  writeFileSyncAtomic(globalPath, tomlString);
@@ -240,6 +372,7 @@ export function removeGlobalKernelConfigKey(section: string, key: string): void
240
372
  if (Object.keys(existing[section]).length === 0) {
241
373
  delete existing[section];
242
374
  }
375
+ validateConfigDocument(existing);
243
376
  const tomlString = stringifyToml(existing);
244
377
  writeFileSyncAtomic(globalPath, tomlString);
245
378
  }
@@ -272,6 +405,18 @@ export function getTargetProjectConfigPath(cwd = process.cwd()): string {
272
405
  return path.join(path.resolve(cwd), ".pi", "config.toml");
273
406
  }
274
407
 
408
+ export function removeProjectKernelConfigKey(cwd: string, section: string, key: string): void {
409
+ const projectPath = getTargetProjectConfigPath(cwd);
410
+ if (!fs.existsSync(projectPath)) return;
411
+ const existing = parseToml(fs.readFileSync(projectPath, "utf-8"));
412
+ const table = existing[section];
413
+ if (!table || typeof table !== "object" || Array.isArray(table) || !(key in table)) return;
414
+ delete (table as Record<string, TomlValue>)[key];
415
+ if (Object.keys(table).length === 0) delete existing[section];
416
+ validateConfigDocument(existing);
417
+ writeFileSyncAtomic(projectPath, stringifyToml(existing));
418
+ }
419
+
275
420
  /**
276
421
  * Save user overrides to project-local configuration file (.pi/config.toml)
277
422
  */
@@ -282,21 +427,21 @@ export function saveProjectKernelConfig(cwd: string, updates: KernelConfigOverri
282
427
  fs.mkdirSync(parentDir, { recursive: true });
283
428
  }
284
429
 
285
- let existing: Record<string, TomlValue> = {};
286
- if (fs.existsSync(projectPath)) {
287
- try {
288
- existing = parseToml(fs.readFileSync(projectPath, "utf-8"));
289
- } catch (e) {
290
- kernelDebug(e);
291
- }
292
- }
293
-
430
+ const existing: Record<string, TomlValue> = fs.existsSync(projectPath)
431
+ ? parseToml(fs.readFileSync(projectPath, "utf-8"))
432
+ : {};
433
+ validateConfigDocument(existing);
434
+ validateConfigDocument({ ...existing, ...updates });
294
435
  mergeDeep(existing, updates);
295
436
  const tomlString = stringifyToml(existing);
296
437
  writeFileSyncAtomic(projectPath, tomlString);
297
438
  return projectPath;
298
439
  }
299
440
 
441
+ export function validateConfigDocument(source: unknown): KernelConfig {
442
+ return mergeKernelConfig(structuredClone(DEFAULT_CONFIG), source);
443
+ }
444
+
300
445
  export function mergeDeep(target: any, source: any) {
301
446
  if (!source || typeof source !== "object") return;
302
447
  for (const key of Object.keys(source)) {
@@ -1,117 +1,198 @@
1
- import * as fs from "fs";
2
- import * as path from "path";
3
- import * as os from "os";
1
+ import * as crypto from "node:crypto";
2
+ import * as fs from "node:fs";
3
+ import * as path from "node:path";
4
4
  import { getPiHomeDir } from "../config";
5
5
  import { writeFileSyncAtomic } from "../safety/atomic_write";
6
+ import { kernelDebug } from "../safety/kernel_debug";
6
7
 
7
- const MAX_SESSION_FILE_SIZE = 10 * 1024 * 1024; // 10MB
8
+ const MAX_SESSION_FILE_SIZE = 10 * 1024 * 1024;
8
9
  const MAX_SESSIONS_SCANNED = 20;
9
10
 
10
- /**
11
- * Sanitizes and repairs session JSONL files in ~/.pi/agent/sessions/
12
- * Ensures that any compaction, branch_summary, or message entry with a partial
13
- * usage object has a valid `cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 }`
14
- * to prevent uncaught TypeErrors in Pi's TUI footer renderer (usage-totals.js:15).
15
- */
16
- export function sanitizeSessionFiles(agentDir?: string): { repairedFiles: number; repairedEntries: number } {
17
- let repairedFiles = 0;
18
- let repairedEntries = 0;
11
+ export interface SessionRepairOptions {
12
+ agentDir?: string;
13
+ skipFile?: string;
14
+ apply?: boolean;
15
+ }
16
+
17
+ export interface SessionRepairStats {
18
+ scannedFiles: number;
19
+ candidateFiles: number;
20
+ repairedFiles: number;
21
+ repairedEntries: number;
22
+ skippedFiles: number;
23
+ failedFiles: number;
24
+ dryRun: boolean;
25
+ }
26
+
27
+ interface FileRepairResult {
28
+ candidate: boolean;
29
+ repaired: boolean;
30
+ entries: number;
31
+ skipped: boolean;
32
+ error?: string;
33
+ }
19
34
 
35
+ function sha256(content: string): string {
36
+ return crypto.createHash("sha256").update(content).digest("hex");
37
+ }
38
+
39
+ function samePath(left: string, right: string): boolean {
40
+ const a = path.resolve(left);
41
+ const b = path.resolve(right);
42
+ return process.platform === "win32"
43
+ ? a.toLowerCase() === b.toLowerCase()
44
+ : a === b;
45
+ }
46
+
47
+ function withRepairLock<T>(filePath: string, operation: () => T): T {
48
+ const lockPath = `${filePath}.agent-kernel-repair.lock`;
49
+ let descriptor: number | undefined;
20
50
  try {
21
- const baseAgentDir = agentDir || path.join(getPiHomeDir(), "agent");
22
- const sessionsDir = path.join(baseAgentDir, "sessions");
51
+ descriptor = fs.openSync(lockPath, "wx", 0o600);
52
+ } catch (error: any) {
53
+ if (error?.code === "EEXIST") throw new Error("another repair holds the file lock");
54
+ throw error;
55
+ }
56
+ try {
57
+ fs.writeFileSync(descriptor, `${process.pid}\n${new Date().toISOString()}\n`, "utf8");
58
+ return operation();
59
+ } finally {
60
+ if (descriptor !== undefined) fs.closeSync(descriptor);
61
+ try {
62
+ fs.unlinkSync(lockPath);
63
+ } catch (error) {
64
+ kernelDebug(error);
65
+ }
66
+ }
67
+ }
23
68
 
24
- if (!fs.existsSync(sessionsDir)) {
25
- return { repairedFiles: 0, repairedEntries: 0 };
69
+ function repairSessionFile(filePath: string, apply: boolean): FileRepairResult {
70
+ const stat = fs.lstatSync(filePath);
71
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.size > MAX_SESSION_FILE_SIZE) {
72
+ return { candidate: false, repaired: false, entries: 0, skipped: true };
73
+ }
74
+
75
+ const original = fs.readFileSync(filePath, "utf8");
76
+ let entriesRepaired = 0;
77
+ const repairedLines = original.split(/(\r?\n)/).map((line, index) => {
78
+ // Keep captured separators verbatim so repaired records retain each original EOL.
79
+ if (index % 2 === 1 || !line.trim()) return line;
80
+ try {
81
+ const entry = JSON.parse(line);
82
+ let modified = false;
83
+ if ((entry.type === "compaction" || entry.type === "branch_summary") && entry.usage) {
84
+ if (!entry.usage.cost || typeof entry.usage.cost.total !== "number") {
85
+ entry.usage.cost = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 };
86
+ modified = true;
87
+ }
88
+ }
89
+ if (entry.type === "message" && entry.message?.usage) {
90
+ if (!entry.message.usage.cost || typeof entry.message.usage.cost.total !== "number") {
91
+ entry.message.usage.cost = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 };
92
+ modified = true;
93
+ }
94
+ }
95
+ if (modified) {
96
+ entriesRepaired++;
97
+ return JSON.stringify(entry);
98
+ }
99
+ } catch {
100
+ // Leave malformed lines byte-for-byte unchanged.
101
+ }
102
+ return line;
103
+ });
104
+
105
+ if (entriesRepaired === 0) {
106
+ return { candidate: false, repaired: false, entries: 0, skipped: false };
107
+ }
108
+ if (!apply) {
109
+ return { candidate: true, repaired: false, entries: entriesRepaired, skipped: false };
110
+ }
111
+
112
+ const originalHash = sha256(original);
113
+ const repairedContent = repairedLines.join("");
114
+ return withRepairLock(filePath, () => {
115
+ const current = fs.readFileSync(filePath, "utf8");
116
+ if (sha256(current) !== originalHash) {
117
+ return { candidate: true, repaired: false, entries: 0, skipped: true, error: "file changed during repair" };
26
118
  }
27
119
 
120
+ const backupPath = `${filePath}.${Date.now()}.agent-kernel.bak`;
121
+ fs.copyFileSync(filePath, backupPath, fs.constants.COPYFILE_EXCL);
122
+ if (sha256(fs.readFileSync(filePath, "utf8")) !== originalHash) {
123
+ throw new Error("file changed before replacement");
124
+ }
125
+ writeFileSyncAtomic(filePath, repairedContent);
126
+ if (fs.readFileSync(filePath, "utf8") !== repairedContent) {
127
+ throw new Error("repaired content verification failed");
128
+ }
129
+ return { candidate: true, repaired: true, entries: entriesRepaired, skipped: false };
130
+ });
131
+ }
132
+
133
+ export function sanitizeSessionFiles(
134
+ optionsOrAgentDir: SessionRepairOptions | string = {},
135
+ ): SessionRepairStats {
136
+ const options = typeof optionsOrAgentDir === "string"
137
+ ? { agentDir: optionsOrAgentDir }
138
+ : optionsOrAgentDir;
139
+ const apply = options.apply === true;
140
+ const stats: SessionRepairStats = {
141
+ scannedFiles: 0,
142
+ candidateFiles: 0,
143
+ repairedFiles: 0,
144
+ repairedEntries: 0,
145
+ skippedFiles: 0,
146
+ failedFiles: 0,
147
+ dryRun: !apply,
148
+ };
149
+
150
+ try {
151
+ const baseAgentDir = options.agentDir || path.join(getPiHomeDir(), "agent");
152
+ const sessionsDir = path.join(baseAgentDir, "sessions");
153
+ if (!fs.existsSync(sessionsDir)) return stats;
154
+
28
155
  const sessionFolders = fs.readdirSync(sessionsDir)
29
156
  .map((folder) => {
30
157
  const folderPath = path.join(sessionsDir, folder);
31
158
  try {
32
159
  const stat = fs.lstatSync(folderPath);
33
- return { folder, folderPath, isDir: stat.isDirectory() && !stat.isSymbolicLink(), mtime: stat.mtimeMs };
160
+ return { folderPath, isDir: stat.isDirectory() && !stat.isSymbolicLink(), mtime: stat.mtimeMs };
34
161
  } catch {
35
- return { folder, folderPath, isDir: false, mtime: 0 };
162
+ return { folderPath, isDir: false, mtime: 0 };
36
163
  }
37
164
  })
38
- .filter((f) => f.isDir)
165
+ .filter((folder) => folder.isDir)
39
166
  .sort((a, b) => b.mtime - a.mtime)
40
167
  .slice(0, MAX_SESSIONS_SCANNED);
41
168
 
42
169
  for (const { folderPath } of sessionFolders) {
43
- const files = fs.readdirSync(folderPath);
44
- for (const file of files) {
170
+ for (const file of fs.readdirSync(folderPath)) {
45
171
  if (!file.endsWith(".jsonl")) continue;
46
-
47
172
  const filePath = path.join(folderPath, file);
173
+ if (options.skipFile && samePath(filePath, options.skipFile)) {
174
+ stats.skippedFiles++;
175
+ continue;
176
+ }
177
+ stats.scannedFiles++;
48
178
  try {
49
- const stat = fs.lstatSync(filePath);
50
- if (!stat.isFile() || stat.isSymbolicLink() || stat.size > MAX_SESSION_FILE_SIZE) {
51
- continue;
52
- }
53
-
54
- const content = fs.readFileSync(filePath, "utf8");
55
- const lines = content.split("\n");
56
- let fileModified = false;
57
-
58
- const repairedLines = lines.map((line) => {
59
- if (!line.trim()) return line;
60
- try {
61
- const entry = JSON.parse(line);
62
- let entryModified = false;
63
-
64
- // Check compaction / branch_summary usage
65
- if ((entry.type === "compaction" || entry.type === "branch_summary") && entry.usage) {
66
- if (!entry.usage.cost || typeof entry.usage.cost.total !== "number") {
67
- entry.usage.cost = {
68
- input: 0,
69
- output: 0,
70
- cacheRead: 0,
71
- cacheWrite: 0,
72
- total: 0,
73
- };
74
- entryModified = true;
75
- }
76
- }
77
-
78
- // Check message usage
79
- if (entry.type === "message" && entry.message && entry.message.usage) {
80
- if (!entry.message.usage.cost || typeof entry.message.usage.cost.total !== "number") {
81
- entry.message.usage.cost = {
82
- input: 0,
83
- output: 0,
84
- cacheRead: 0,
85
- cacheWrite: 0,
86
- total: 0,
87
- };
88
- entryModified = true;
89
- }
90
- }
91
-
92
- if (entryModified) {
93
- fileModified = true;
94
- repairedEntries++;
95
- return JSON.stringify(entry);
96
- }
97
- } catch (e) {
98
- // Ignore unparseable lines
99
- }
100
- return line;
101
- });
102
-
103
- if (fileModified) {
104
- writeFileSyncAtomic(filePath, repairedLines.join("\n"));
105
- repairedFiles++;
179
+ const result = repairSessionFile(filePath, apply);
180
+ if (result.candidate) stats.candidateFiles++;
181
+ if (result.repaired) {
182
+ stats.repairedFiles++;
183
+ stats.repairedEntries += result.entries;
106
184
  }
107
- } catch (err) {
108
- // Ignore individual file read errors
185
+ if (result.skipped) stats.skippedFiles++;
186
+ } catch (error) {
187
+ stats.failedFiles++;
188
+ kernelDebug(`Session repair failed for ${filePath}: ${error instanceof Error ? error.message : String(error)}`);
109
189
  }
110
190
  }
111
191
  }
112
- } catch (err) {
113
- // Ignore top-level directory errors
192
+ } catch (error) {
193
+ stats.failedFiles++;
194
+ kernelDebug(error);
114
195
  }
115
196
 
116
- return { repairedFiles, repairedEntries };
197
+ return stats;
117
198
  }
@@ -442,6 +442,7 @@ export function applySurgicalPatch(
442
442
  end_line?: number;
443
443
  line_hint?: number;
444
444
  autoHeal?: boolean;
445
+ syntaxGate?: "warn" | "block";
445
446
  },
446
447
  ): PatchResult {
447
448
  const resolvedPath = resolvePatchPath(filePath);
@@ -466,7 +467,7 @@ export function applySurgicalPatch(
466
467
  // Delimiter & Bracket Auto-Healing:
467
468
  if (!syntax.valid) {
468
469
  const ext = path.extname(resolvedPath).toLowerCase();
469
- if (ext === ".json") {
470
+ if (ext === ".json" && options?.autoHeal !== false) {
470
471
  const healedJson = healJsonContent(candidateContent);
471
472
  if (healedJson) {
472
473
  candidateContent = healedJson;
@@ -493,12 +494,15 @@ export function applySurgicalPatch(
493
494
  }
494
495
 
495
496
  if (!syntax.valid) {
496
- return {
497
- success: false,
498
- filePath: resolvedPath,
499
- strategy: result.strategy,
500
- error: syntax.error || "Candidate syntax validation failed",
501
- };
497
+ const shouldBlock = options?.syntaxGate !== "warn";
498
+ if (shouldBlock) {
499
+ return {
500
+ success: false,
501
+ filePath: resolvedPath,
502
+ strategy: result.strategy,
503
+ error: syntax.error || "Candidate syntax validation failed",
504
+ };
505
+ }
502
506
  }
503
507
 
504
508
  const writeError = writePatchedContent(
@@ -513,7 +517,9 @@ export function applySurgicalPatch(
513
517
 
514
518
  const finalStrategy = autoHealed
515
519
  ? `${result.strategy} (auto-healed syntax)`
516
- : result.strategy;
520
+ : !syntax.valid
521
+ ? `${result.strategy} (applied with syntax warning)`
522
+ : result.strategy;
517
523
 
518
524
  return {
519
525
  success: true,
@@ -531,6 +537,7 @@ export function applySurgicalPatch(
531
537
  export function applyMultiBlockPatch(
532
538
  filePath: string,
533
539
  blocks: PatchBlock[],
540
+ options: { autoHeal?: boolean; syntaxGate?: "warn" | "block" } = {},
534
541
  ): PatchResult {
535
542
  const resolvedPath = resolvePatchPath(filePath);
536
543
  const target = readPatchTarget(resolvedPath);
@@ -632,7 +639,7 @@ export function applyMultiBlockPatch(
632
639
 
633
640
  if (!syntax.valid) {
634
641
  const ext = path.extname(resolvedPath).toLowerCase();
635
- if (ext === ".json") {
642
+ if (ext === ".json" && options.autoHeal !== false) {
636
643
  const healedJson = healJsonContent(candidateContent);
637
644
  if (healedJson) {
638
645
  candidateContent = healedJson;
@@ -643,12 +650,15 @@ export function applyMultiBlockPatch(
643
650
  }
644
651
 
645
652
  if (!syntax.valid) {
646
- return {
647
- success: false,
648
- filePath: resolvedPath,
649
- strategy: appliedStrategies.join(", "),
650
- error: syntax.error || "Candidate syntax validation failed",
651
- };
653
+ const shouldBlock = options.syntaxGate !== "warn";
654
+ if (shouldBlock) {
655
+ return {
656
+ success: false,
657
+ filePath: resolvedPath,
658
+ strategy: appliedStrategies.join(", "),
659
+ error: syntax.error || "Candidate syntax validation failed",
660
+ };
661
+ }
652
662
  }
653
663
 
654
664
  const writeError = writePatchedContent(
@@ -663,7 +673,9 @@ export function applyMultiBlockPatch(
663
673
 
664
674
  const finalStrategy = autoHealed
665
675
  ? `${appliedStrategies.join(", ")} (auto-healed syntax)`
666
- : appliedStrategies.join(", ");
676
+ : !syntax.valid
677
+ ? `${appliedStrategies.join(", ")} (applied with syntax warning)`
678
+ : appliedStrategies.join(", ");
667
679
 
668
680
  return {
669
681
  success: true,