@polka-codes/cli-shared 0.11.7 → 0.12.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.
package/dist/index.js CHANGED
@@ -1,13 +1,10 @@
1
- import { createRequire } from "node:module";
2
- var __require = /* @__PURE__ */ createRequire(import.meta.url);
3
-
4
1
  // src/config.ts
5
2
  import { existsSync, readFileSync } from "node:fs";
6
3
  import { readFile } from "node:fs/promises";
7
4
  import { homedir } from "node:os";
8
5
  import { join } from "node:path";
9
6
  import { configSchema } from "@polka-codes/core";
10
- import { merge } from "lodash-es";
7
+ import { mergeWith } from "lodash-es";
11
8
  import { parse } from "yaml";
12
9
  import { ZodError } from "zod";
13
10
  function getGlobalConfigPath(home = homedir()) {
@@ -41,14 +38,16 @@ function mergeConfigs(configs) {
41
38
  return {};
42
39
  }
43
40
  const mergedConfig = configs.reduce((acc, config) => {
44
- const merged = merge({}, acc, config);
41
+ const merged = mergeWith({}, acc, config, (_previous, next) => Array.isArray(next) ? [...next] : undefined);
42
+ if (acc.scripts || config.scripts)
43
+ merged.scripts = { ...acc.scripts, ...config.scripts };
45
44
  const accRules = acc.rules ? Array.isArray(acc.rules) ? acc.rules : [acc.rules] : undefined;
46
45
  const configRules = config.rules ? Array.isArray(config.rules) ? config.rules : [config.rules] : undefined;
47
46
  merged.rules = mergeArray(accRules, configRules);
48
47
  merged.excludeFiles = mergeArray(acc.excludeFiles, config.excludeFiles);
49
48
  return merged;
50
49
  }, {});
51
- return mergedConfig;
50
+ return configSchema.parse(mergedConfig) ?? {};
52
51
  }
53
52
  async function resolveRules(rules) {
54
53
  if (!rules) {
@@ -121,33 +120,17 @@ async function loadConfig(paths, cwd = process.cwd(), home = homedir()) {
121
120
  ${error}`);
122
121
  }
123
122
  }
124
- if (paths && paths.length > 0) {
125
- const configPaths = Array.isArray(paths) ? paths : [paths];
126
- for (const path of configPaths) {
127
- try {
128
- const config = readConfig(path);
129
- configs.push(config);
130
- } catch (error) {
131
- const errorCode = error?.code;
132
- if (errorCode === "ENOENT") {
133
- continue;
134
- }
135
- console.error(`Error loading config file: ${path}
136
- ${error}`);
137
- throw error;
138
- }
139
- }
140
- } else {
141
- const configPath = join(cwd, localConfigFileName);
123
+ const configPaths = paths?.length ? Array.isArray(paths) ? paths : [paths] : [join(cwd, localConfigFileName)];
124
+ for (const configPath of configPaths) {
142
125
  try {
143
- const projectConfig = readConfig(configPath);
144
- configs.push(projectConfig);
126
+ configs.push(readConfig(configPath));
145
127
  } catch (error) {
146
- if (error instanceof ZodError) {
147
- console.error(`Error in config file: ${configPath}
148
- ${error}`);
149
- throw error;
128
+ if (error instanceof Error && "code" in error && error.code === "ENOENT") {
129
+ continue;
150
130
  }
131
+ console.error(`Error loading config file: ${configPath}
132
+ ${error}`);
133
+ throw error;
151
134
  }
152
135
  }
153
136
  const mergedConfig = configs.length > 0 ? mergeConfigs(configs) : undefined;
@@ -266,7 +249,6 @@ function normalizePath(path) {
266
249
  return normalize(path).split(sep).join("/");
267
250
  }
268
251
  // src/provider.ts
269
- import { spawn as spawn2 } from "node:child_process";
270
252
  import { mkdir, readFile as readFile2, realpath, rename, unlink, writeFile } from "node:fs/promises";
271
253
  import { dirname as dirname2, isAbsolute, normalize as normalize2, sep as pathSeparator, relative as relative2, resolve as resolve3 } from "node:path";
272
254
  import { vertex } from "@ai-sdk/google-vertex";
@@ -295,7 +277,7 @@ function checkRipgrep() {
295
277
 
296
278
  // src/utils/listFiles.ts
297
279
  import { promises as fs } from "node:fs";
298
- import { join as join2, relative, resolve as resolve2 } from "node:path";
280
+ import { join as join2, relative, resolve as resolve2, sep as sep2 } from "node:path";
299
281
  import ignore from "ignore";
300
282
  var DEFAULT_IGNORES = [
301
283
  "__pycache__",
@@ -312,56 +294,65 @@ var DEFAULT_IGNORES = [
312
294
  "out",
313
295
  "Thumbs.db"
314
296
  ];
315
- async function extendPatterns(basePatterns, dirPath) {
297
+ async function extendLayers(layers, directory) {
316
298
  try {
317
- const gitignorePath = join2(dirPath, ".gitignore");
318
- const content = await fs.readFile(gitignorePath, "utf8");
319
- const lines = content.split(/\r?\n/).filter(Boolean);
320
- return [...basePatterns, ...lines];
321
- } catch {
322
- return basePatterns;
299
+ const content = await fs.readFile(join2(directory, ".gitignore"), "utf8");
300
+ return [...layers, { base: directory, matcher: ignore().add(content) }];
301
+ } catch (error) {
302
+ if (error instanceof Error && "code" in error && error.code === "ENOENT")
303
+ return layers;
304
+ throw error;
323
305
  }
324
306
  }
325
- function createIgnore(patterns) {
326
- return ignore().add(patterns);
307
+ function isIgnored(path, directory, layers) {
308
+ let ignored = false;
309
+ for (const layer of layers) {
310
+ const result = layer.matcher.test(relative(layer.base, path).split(sep2).join("/") + (directory ? "/" : ""));
311
+ if (result.ignored)
312
+ ignored = true;
313
+ else if (result.unignored)
314
+ ignored = false;
315
+ }
316
+ return ignored;
327
317
  }
328
318
  async function listFiles(dirPath, recursive, maxCount, cwd, excludeFiles, includeIgnored) {
329
- let rootPatterns = [...excludeFiles || []];
330
- if (!includeIgnored) {
331
- rootPatterns.push(...DEFAULT_IGNORES);
332
- try {
333
- const rootGitignore = await fs.readFile(join2(cwd, ".gitignore"), "utf8");
334
- const lines = rootGitignore.split(/\r?\n/).filter(Boolean);
335
- rootPatterns = [...rootPatterns, ...lines];
336
- } catch {}
319
+ const root = resolve2(cwd);
320
+ const start = resolve2(dirPath);
321
+ let layers = [{ base: root, matcher: ignore().add([...excludeFiles ?? [], ...includeIgnored ? [] : DEFAULT_IGNORES]) }];
322
+ let ancestor = root;
323
+ for (const part of relative(root, start).split(sep2).filter(Boolean)) {
324
+ if (!includeIgnored)
325
+ layers = await extendLayers(layers, ancestor);
326
+ ancestor = join2(ancestor, part);
327
+ if (isIgnored(ancestor, true, layers))
328
+ return [[], false];
337
329
  }
338
330
  const results = [];
339
331
  const processedDirs = new Set;
340
332
  const queue = [
341
333
  {
342
- path: resolve2(dirPath),
343
- patterns: rootPatterns,
344
- relPath: relative(cwd, resolve2(dirPath)).replace(/\\/g, "/") || "."
334
+ path: start,
335
+ layers,
336
+ relPath: relative(cwd, resolve2(dirPath)).split(sep2).join("/") || "."
345
337
  }
346
338
  ];
347
339
  while (queue.length > 0) {
348
- const { path: currentPath, patterns: parentPatterns, relPath: currentRelPath } = queue.shift();
340
+ const { path: currentPath, layers: parentLayers, relPath: currentRelPath } = queue.shift();
349
341
  processedDirs.add(currentRelPath);
350
- const mergedPatterns = includeIgnored ? parentPatterns : await extendPatterns(parentPatterns, currentPath);
351
- const folderIg = createIgnore(mergedPatterns);
342
+ const currentLayers = includeIgnored ? parentLayers : await extendLayers(parentLayers, currentPath);
352
343
  const entries = await fs.readdir(currentPath, { withFileTypes: true });
353
344
  entries.sort((a, b) => a.name.localeCompare(b.name));
354
345
  for (const entry of entries) {
355
346
  const fullPath = join2(currentPath, entry.name);
356
- const relPath = relative(cwd, fullPath).replace(/\\/g, "/");
357
- if (folderIg.ignores(relPath)) {
347
+ const relPath = relative(cwd, fullPath).split(sep2).join("/");
348
+ if (isIgnored(fullPath, entry.isDirectory(), currentLayers)) {
358
349
  continue;
359
350
  }
360
351
  if (entry.isDirectory()) {
361
352
  if (recursive) {
362
353
  queue.push({
363
354
  path: fullPath,
364
- patterns: mergedPatterns,
355
+ layers: currentLayers,
365
356
  relPath
366
357
  });
367
358
  }
@@ -369,7 +360,7 @@ async function listFiles(dirPath, recursive, maxCount, cwd, excludeFiles, includ
369
360
  results.push(relPath);
370
361
  if (results.length >= maxCount) {
371
362
  const remainingEntries = entries.slice(entries.indexOf(entry) + 1);
372
- const hasRemainingFiles = remainingEntries.some((e) => !e.isDirectory() && !folderIg.ignores(relative(cwd, join2(currentPath, e.name)).replace(/\\/g, "/")));
363
+ const hasRemainingFiles = remainingEntries.some((e) => !e.isDirectory() && !isIgnored(join2(currentPath, e.name), false, currentLayers));
373
364
  if (hasRemainingFiles) {
374
365
  const marker = `${currentRelPath}/(files omitted)`;
375
366
  results.push(marker);
@@ -411,9 +402,7 @@ async function searchFiles(path, regex, filePattern, cwd, excludeFiles) {
411
402
  if (filePattern && filePattern !== "*") {
412
403
  const patterns = filePattern.split(",").map((p) => p.trim()).filter(Boolean);
413
404
  for (const pattern of patterns) {
414
- if (pattern) {
415
- args.push("--glob", pattern);
416
- }
405
+ args.push("--glob", pattern);
417
406
  }
418
407
  }
419
408
  if (excludeFiles) {
@@ -421,21 +410,21 @@ async function searchFiles(path, regex, filePattern, cwd, excludeFiles) {
421
410
  args.push("--glob", `!${pattern}`);
422
411
  }
423
412
  }
424
- args.push(regex, path);
425
- return new Promise((resolve3, reject) => {
426
- const results = [];
413
+ args.push("-e", regex, "--", path);
414
+ return new Promise((resolve, reject) => {
415
+ let stdout = "";
427
416
  let stderr = "";
428
417
  const rg = spawn("rg", args, {
429
418
  cwd,
430
419
  stdio: ["ignore", "pipe", "pipe"]
431
420
  });
421
+ rg.stdout.setEncoding("utf8");
432
422
  rg.stdout.on("data", (data) => {
433
- const lines = data.toString().split(`
434
- `).filter(Boolean);
435
- results.push(...lines);
423
+ stdout += data;
436
424
  });
425
+ rg.stderr.setEncoding("utf8");
437
426
  rg.stderr.on("data", (data) => {
438
- stderr += data.toString();
427
+ stderr += data;
439
428
  });
440
429
  rg.on("error", (error) => {
441
430
  reject(new Error(`Failed to execute ripgrep: ${error.message}`));
@@ -447,11 +436,39 @@ async function searchFiles(path, regex, filePattern, cwd, excludeFiles) {
447
436
  reject(new Error(`Ripgrep process exited with code ${code}${details}`));
448
437
  return;
449
438
  }
450
- resolve3(results);
439
+ resolve(stdout.split(`
440
+ `).filter(Boolean));
451
441
  });
452
442
  });
453
443
  }
454
444
 
445
+ // src/utils/spawnCommand.ts
446
+ import { spawn as spawn2 } from "node:child_process";
447
+ function spawnCommand(command, args, signal) {
448
+ signal?.throwIfAborted();
449
+ const processGroup = signal !== undefined && process.platform !== "win32";
450
+ const child = spawn2(command, args ?? [], {
451
+ shell: args === undefined,
452
+ stdio: ["ignore", "pipe", "pipe"],
453
+ detached: processGroup,
454
+ signal
455
+ });
456
+ const pid = child.pid;
457
+ if (processGroup && signal && pid !== undefined) {
458
+ const abort = () => {
459
+ try {
460
+ process.kill(-pid, "SIGTERM");
461
+ } catch (error) {
462
+ if (!(error instanceof Error && ("code" in error) && error.code === "ESRCH"))
463
+ child.emit("error", error);
464
+ }
465
+ };
466
+ signal.addEventListener("abort", abort, { once: true });
467
+ child.once("close", () => signal.removeEventListener("abort", abort));
468
+ }
469
+ return child;
470
+ }
471
+
455
472
  // src/provider.ts
456
473
  class InMemoryStore {
457
474
  #data;
@@ -470,6 +487,60 @@ function notifyCommandObserver(callback, value) {
470
487
  function isIMemoryStore(store) {
471
488
  return "readMemory" in store && "updateMemory" in store;
472
489
  }
490
+ function runCommand(command, args, options, signal) {
491
+ return new Promise((resolve, reject) => {
492
+ signal?.throwIfAborted();
493
+ const description = args ? [command, ...args.map((arg) => JSON.stringify(arg))].join(" ") : command;
494
+ notifyCommandObserver(options.command?.onStarted, description);
495
+ const child = spawnCommand(command, args, signal);
496
+ let stdoutText = "";
497
+ let stderrText = "";
498
+ child.stdout.setEncoding("utf8");
499
+ child.stdout.on("data", (dataStr) => {
500
+ notifyCommandObserver(options.command?.onStdout, dataStr);
501
+ stdoutText += dataStr;
502
+ });
503
+ child.stderr.setEncoding("utf8");
504
+ child.stderr.on("data", (dataStr) => {
505
+ notifyCommandObserver(options.command?.onStderr, dataStr);
506
+ stderrText += dataStr;
507
+ });
508
+ child.on("close", async (code) => {
509
+ if (signal?.aborted) {
510
+ reject(signal.reason);
511
+ return;
512
+ }
513
+ const exitCode = code ?? 1;
514
+ notifyCommandObserver(options.command?.onExit, exitCode);
515
+ const totalLength = stdoutText.length + stderrText.length;
516
+ if (totalLength > (options.summaryThreshold ?? 5000) && options.summarizeOutput) {
517
+ try {
518
+ const summary = await options.summarizeOutput(stdoutText, stderrText);
519
+ if (summary) {
520
+ resolve({
521
+ summary,
522
+ stdout: stdoutText,
523
+ stderr: stderrText,
524
+ exitCode
525
+ });
526
+ return;
527
+ }
528
+ } catch (_e) {
529
+ console.error("Summarization failed:", _e);
530
+ }
531
+ }
532
+ resolve({
533
+ stdout: stdoutText,
534
+ stderr: stderrText,
535
+ exitCode
536
+ });
537
+ });
538
+ child.on("error", (err) => {
539
+ notifyCommandObserver(options.command?.onError, err);
540
+ reject(err);
541
+ });
542
+ });
543
+ }
473
544
  var getProvider = (options = {}) => {
474
545
  const ig = ignore2().add(options.excludeFiles ?? []);
475
546
  const memoryStore = options.memoryStore ?? new InMemoryStore;
@@ -556,13 +627,13 @@ ${content}`;
556
627
  if (!item) {
557
628
  throw new Error(`To-do item with id ${id} not found`);
558
629
  }
559
- const subItems = todoItems.filter((i) => i.id.startsWith(`${id}.`) && i.id.split(".").length === id.split(".").length + 1).map(({ id: id2, title }) => ({ id: id2, title }));
630
+ const subItems = todoItems.filter((i) => i.id.startsWith(`${id}.`) && i.id.split(".").length === id.split(".").length + 1).map(({ id, title }) => ({ id, title }));
560
631
  return { ...item, subItems };
561
632
  },
562
- updateTodoItem: async (input2) => {
633
+ updateTodoItem: async (input) => {
563
634
  const todoItems = await todoItemStore.read() ?? [];
564
- if (input2.operation === "add") {
565
- const { parentId, title, description, status } = input2;
635
+ if (input.operation === "add") {
636
+ const { parentId, title, description, status } = input;
566
637
  if (!title) {
567
638
  throw new Error("Title is required for add operation");
568
639
  }
@@ -596,7 +667,7 @@ ${content}`;
596
667
  await todoItemStore.write([...todoItems, newItem]);
597
668
  return { id: newId };
598
669
  } else {
599
- const { id } = input2;
670
+ const { id } = input;
600
671
  if (!id) {
601
672
  throw new Error("ID is required for update operation");
602
673
  }
@@ -604,14 +675,14 @@ ${content}`;
604
675
  if (!item) {
605
676
  throw new Error(`To-do item with id ${id} not found`);
606
677
  }
607
- if (input2.title != null) {
608
- item.title = input2.title;
678
+ if (input.title != null) {
679
+ item.title = input.title;
609
680
  }
610
- if (input2.description != null) {
611
- item.description = input2.description ?? "";
681
+ if (input.description != null) {
682
+ item.description = input.description ?? "";
612
683
  }
613
- if (input2.status != null) {
614
- item.status = input2.status;
684
+ if (input.status != null) {
685
+ item.status = input.status;
615
686
  }
616
687
  await todoItemStore.write(todoItems);
617
688
  return { id };
@@ -668,11 +739,11 @@ ${content}`;
668
739
  if (projectRelativePath === ".." || projectRelativePath.startsWith(`..${pathSeparator}`) || isAbsolute(projectRelativePath)) {
669
740
  throw new Error(`Access to file path "${filePath}" is restricted.`);
670
741
  }
671
- const data2 = await readFile2(realFilePath);
672
- const mediaType2 = lookup(realFilePath) || "application/octet-stream";
742
+ const data = await readFile2(realFilePath);
743
+ const mediaType = lookup(realFilePath) || "application/octet-stream";
673
744
  return {
674
- base64Data: data2.toString("base64"),
675
- mediaType: mediaType2
745
+ base64Data: data.toString("base64"),
746
+ mediaType
676
747
  };
677
748
  }
678
749
  const response = await fetch(url);
@@ -686,56 +757,8 @@ ${content}`;
686
757
  mediaType
687
758
  };
688
759
  },
689
- executeCommand: (command, _needApprove) => {
690
- return new Promise((resolve4, reject) => {
691
- notifyCommandObserver(options.command?.onStarted, command);
692
- const child = spawn2(command, [], {
693
- shell: true,
694
- stdio: "pipe"
695
- });
696
- let stdoutText = "";
697
- let stderrText = "";
698
- child.stdout.on("data", (data) => {
699
- const dataStr = data.toString();
700
- notifyCommandObserver(options.command?.onStdout, dataStr);
701
- stdoutText += dataStr;
702
- });
703
- child.stderr.on("data", (data) => {
704
- const dataStr = data.toString();
705
- notifyCommandObserver(options.command?.onStderr, dataStr);
706
- stderrText += dataStr;
707
- });
708
- child.on("close", async (code) => {
709
- notifyCommandObserver(options.command?.onExit, code ?? 0);
710
- const totalLength = stdoutText.length + stderrText.length;
711
- if (totalLength > (options.summaryThreshold ?? 5000) && options.summarizeOutput) {
712
- try {
713
- const summary = await options.summarizeOutput(stdoutText, stderrText);
714
- if (summary) {
715
- resolve4({
716
- summary,
717
- stdout: stdoutText,
718
- stderr: stderrText,
719
- exitCode: code ?? 0
720
- });
721
- return;
722
- }
723
- } catch (_e) {
724
- console.error("Summarization failed:", _e);
725
- }
726
- }
727
- resolve4({
728
- stdout: stdoutText,
729
- stderr: stderrText,
730
- exitCode: code ?? 0
731
- });
732
- });
733
- child.on("error", (err) => {
734
- notifyCommandObserver(options.command?.onError, err);
735
- reject(err);
736
- });
737
- });
738
- },
760
+ executeCommand: (command, _needApprove, signal) => runCommand(command, undefined, options, signal),
761
+ executeFile: (file, args) => runCommand(file, args, options),
739
762
  askFollowupQuestion: async (question, answerOptions) => {
740
763
  if (options.yes) {
741
764
  if (answerOptions.length > 0) {
@@ -757,11 +780,11 @@ ${content}`;
757
780
  }
758
781
  return answer;
759
782
  },
760
- fetchUrl: async (url) => {
783
+ fetchUrl: async (url, signal) => {
761
784
  const isRaw = url.startsWith("https://raw.githubusercontent.com/");
762
785
  const urlToFetch = isRaw ? url : `https://r.jina.ai/${url}`;
763
786
  try {
764
- const response = await fetch(urlToFetch);
787
+ const response = await fetch(urlToFetch, { signal });
765
788
  if (!response.ok) {
766
789
  throw new Error(`HTTP error! status: ${response.status}`);
767
790
  }
@@ -798,21 +821,27 @@ ${content}`;
798
821
  import { AsyncLocalStorage } from "node:async_hooks";
799
822
  import { randomUUID } from "node:crypto";
800
823
  import { existsSync as existsSync3 } from "node:fs";
801
- import { mkdir as mkdir2, readdir, readFile as readFile3, rename as rename2, unlink as unlink2, writeFile as writeFile2 } from "node:fs/promises";
802
- import { createRequire as createRequire2 } from "node:module";
803
- import { basename, dirname as dirname3, resolve as resolve4 } from "node:path";
824
+ import { lstat, mkdir as mkdir2, mkdtemp, open, readdir, readFile as readFile3, rename as rename2, rm, unlink as unlink2, writeFile as writeFile2 } from "node:fs/promises";
825
+ import { createRequire } from "node:module";
826
+ import { basename, dirname as dirname3, isAbsolute as isAbsolute2, join as join3, relative as relative3, resolve as resolve4, sep as sep3 } from "node:path";
804
827
  import { fileURLToPath } from "node:url";
805
828
  import { DEFAULT_MEMORY_CONFIG, resolveHomePath } from "@polka-codes/core";
806
829
  import initSqlJs from "sql.js";
830
+ import { z } from "zod";
831
+ var lockDataSchema = z.object({ pid: z.number().int().positive(), acquiredAt: z.number().positive() });
832
+ function hasErrorCode(error, ...codes) {
833
+ return error instanceof Error && "code" in error && typeof error.code === "string" && codes.includes(error.code);
834
+ }
807
835
 
808
836
  class FileLock {
809
- lockfilePath;
837
+ #lockfilePath;
838
+ #attemptDirectory;
810
839
  static LOCK_TIMEOUT = 30000;
811
840
  static CLEANUP_AGE = 600000;
812
841
  static lastCleanupTime = 0;
813
842
  static CLEANUP_THROTTLE = 60000;
814
843
  constructor(dbPath) {
815
- this.lockfilePath = `${dbPath}.lock`;
844
+ this.#lockfilePath = `${dbPath}.lock`;
816
845
  }
817
846
  static resetCleanupThrottle() {
818
847
  FileLock.lastCleanupTime = 0;
@@ -827,7 +856,7 @@ class FileLock {
827
856
  const lockDir = dirname3(dbPath);
828
857
  const dbBaseName = basename(dbPath);
829
858
  const files = await readdir(lockDir);
830
- const now2 = Date.now();
859
+ const now = Date.now();
831
860
  for (const file of files) {
832
861
  if (!file.startsWith(`${dbBaseName}.lock.`)) {
833
862
  continue;
@@ -838,7 +867,7 @@ class FileLock {
838
867
  }
839
868
  const filePath = resolve4(lockDir, file);
840
869
  const timestamp = Number.parseInt(match[2], 10);
841
- const age = now2 - timestamp;
870
+ const age = now - timestamp;
842
871
  if (age > maxAge) {
843
872
  try {
844
873
  await unlink2(filePath);
@@ -855,63 +884,78 @@ class FileLock {
855
884
  }
856
885
  }
857
886
  async acquire(retries = 10, delay = 100) {
858
- for (let i = 0;i < retries; i++) {
887
+ const attempt = await mkdtemp(`${this.#lockfilePath}.pending-`);
888
+ const candidate = join3(attempt, "owner");
889
+ try {
890
+ await mkdir2(candidate, { mode: 448 });
891
+ await writeFile2(join3(candidate, "owner.json"), JSON.stringify({ pid: process.pid, acquiredAt: Date.now() }), { mode: 384 });
892
+ for (let i = 0;i < retries; i++) {
893
+ try {
894
+ await rename2(candidate, this.#lockfilePath);
895
+ this.#attemptDirectory = attempt;
896
+ return;
897
+ } catch (error) {
898
+ if (!hasErrorCode(error, "EEXIST", "ENOTEMPTY", "ENOTDIR", "EISDIR"))
899
+ throw error;
900
+ }
901
+ await this.#recoverAbandonedLock();
902
+ if (i < retries - 1)
903
+ await new Promise((resolve) => setTimeout(resolve, delay));
904
+ }
905
+ throw new Error(`Cannot acquire lock after ${retries} retries (file: ${this.#lockfilePath})`);
906
+ } finally {
907
+ if (this.#attemptDirectory !== attempt)
908
+ await rm(attempt, { recursive: true, force: true });
909
+ }
910
+ }
911
+ async#recoverAbandonedLock() {
912
+ try {
913
+ const lock = await lstat(this.#lockfilePath);
914
+ const ownerPath = lock.isDirectory() ? join3(this.#lockfilePath, "owner.json") : this.#lockfilePath;
915
+ const record = await open(ownerPath, "r");
859
916
  try {
860
- const lockData = JSON.stringify({
861
- pid: process.pid,
862
- acquiredAt: Date.now()
863
- });
864
- await writeFile2(this.lockfilePath, lockData, {
865
- flag: "wx",
866
- mode: 384
867
- });
868
- return;
869
- } catch (error) {
870
- const errorCode = error?.code;
871
- if (errorCode === "EEXIST") {
917
+ const stat = await record.stat({ bigint: true });
918
+ const content = await record.readFile("utf8");
919
+ let parsed;
920
+ try {
921
+ parsed = JSON.parse(content);
922
+ } catch (error) {
923
+ if (!(error instanceof SyntaxError))
924
+ throw error;
925
+ }
926
+ const owner = lockDataSchema.safeParse(parsed);
927
+ const acquiredAt = owner.success ? owner.data.acquiredAt : Number(stat.mtimeMs);
928
+ if (Date.now() - acquiredAt <= FileLock.LOCK_TIMEOUT)
929
+ return;
930
+ if (owner.success) {
872
931
  try {
873
- const lockContent = await readFile3(this.lockfilePath, "utf-8");
874
- const lockData = JSON.parse(lockContent);
875
- if (!lockData || typeof lockData.acquiredAt !== "number" || lockData.acquiredAt <= 0) {
876
- console.warn(`[FileLock] Lock file has invalid acquiredAt, treating as stale`);
877
- await rename2(this.lockfilePath, `${this.lockfilePath}.invalid.${Date.now()}`);
878
- continue;
879
- }
880
- const lockAge = Date.now() - lockData.acquiredAt;
881
- if (lockAge > FileLock.LOCK_TIMEOUT) {
882
- console.warn(`[FileLock] Breaking stale lock (age: ${lockAge}ms)`);
883
- await rename2(this.lockfilePath, `${this.lockfilePath}.stale.${Date.now()}`);
884
- continue;
885
- }
886
- } catch (readError) {
887
- if (readError instanceof SyntaxError) {
888
- console.warn(`[FileLock] Lock file contains invalid JSON, treating as stale`);
889
- await rename2(this.lockfilePath, `${this.lockfilePath}.corrupt.${Date.now()}`);
890
- continue;
891
- }
892
- }
893
- if (i < retries - 1) {
894
- await new Promise((resolve5) => setTimeout(resolve5, delay));
895
- } else {
896
- throw new Error(`Cannot acquire lock after ${retries} retries (file: ${this.lockfilePath})`);
932
+ process.kill(owner.data.pid, 0);
933
+ return;
934
+ } catch (error) {
935
+ if (!hasErrorCode(error, "ESRCH"))
936
+ throw error;
897
937
  }
898
- } else {
899
- throw error;
900
938
  }
939
+ const current = await lstat(ownerPath, { bigint: true });
940
+ if (current.dev !== stat.dev || current.ino !== stat.ino)
941
+ return;
942
+ await rename2(this.#lockfilePath, `${this.#lockfilePath}.retired-${stat.dev}-${stat.ino}`);
943
+ } finally {
944
+ await record.close();
901
945
  }
946
+ } catch (error) {
947
+ if (!hasErrorCode(error, "ENOENT", "EEXIST", "ENOTEMPTY", "ENOTDIR", "EISDIR"))
948
+ throw error;
902
949
  }
903
950
  }
904
951
  async release() {
905
- try {
906
- await rename2(this.lockfilePath, `${this.lockfilePath}.released.${Date.now()}`);
907
- const dbPath = this.lockfilePath.slice(0, -5);
908
- FileLock.cleanupOldLockFiles(dbPath).catch(() => {});
909
- } catch (error) {
910
- const errorCode = error.code;
911
- if (errorCode !== "ENOENT") {
912
- console.warn(`[FileLock] Error releasing lock: ${error instanceof Error ? error.message : String(error)}`);
913
- }
914
- }
952
+ const attempt = this.#attemptDirectory;
953
+ if (!attempt)
954
+ return;
955
+ await rename2(this.#lockfilePath, join3(attempt, "owner"));
956
+ this.#attemptDirectory = undefined;
957
+ await rm(attempt, { recursive: true, force: true });
958
+ await FileLock.cleanupOldLockFiles(this.#lockfilePath.slice(0, -5));
915
959
  }
916
960
  }
917
961
 
@@ -926,7 +970,7 @@ class ReentrantMutex {
926
970
  return () => this.release(owner);
927
971
  }
928
972
  while (this.locked) {
929
- await new Promise((resolve5) => this.queue.push(resolve5));
973
+ await new Promise((resolve) => this.queue.push(resolve));
930
974
  }
931
975
  this.locked = true;
932
976
  this.owner = owner;
@@ -951,7 +995,7 @@ class ReentrantMutex {
951
995
  var SqlJs = null;
952
996
  var SqlJsInitPromise = null;
953
997
  var moduleWasmPath = resolve4(dirname3(fileURLToPath(import.meta.url)), "sql-wasm.wasm");
954
- var mainModulePath = createRequire2(import.meta.url).main?.filename;
998
+ var mainModulePath = createRequire(import.meta.url).main?.filename;
955
999
  var mainModuleWasmPath = mainModulePath ? resolve4(dirname3(mainModulePath), "sql-wasm.wasm") : null;
956
1000
  var bundledWasmPath = mainModuleWasmPath && existsSync3(mainModuleWasmPath) ? mainModuleWasmPath : moduleWasmPath;
957
1001
  var hasBundledWasm = existsSync3(bundledWasmPath);
@@ -979,7 +1023,7 @@ async function getSqlJs() {
979
1023
  ` + `Attempted to locate WASM at:
980
1024
  ` + ` - ${bundledWasmPath}
981
1025
 
982
- ` + `If you're developing, run: bun run build in packages/cli-shared`);
1026
+ ` + `If you're developing, run: bun run build in packages/cli-shared`, { cause: error });
983
1027
  }
984
1028
  }
985
1029
  var transactionOwnerStorage = new AsyncLocalStorage;
@@ -1000,7 +1044,7 @@ class SQLiteMemoryStore {
1000
1044
  }
1001
1045
  getFileLock() {
1002
1046
  if (!this.fileLock) {
1003
- const dbPath = this.resolvePath(this.getDbPath());
1047
+ const dbPath = this.#resolvePath(this.getDbPath());
1004
1048
  this.fileLock = new FileLock(dbPath);
1005
1049
  }
1006
1050
  return this.fileLock;
@@ -1017,7 +1061,7 @@ class SQLiteMemoryStore {
1017
1061
  this.config = config;
1018
1062
  this.currentScope = scope;
1019
1063
  }
1020
- async initializeDatabase() {
1064
+ async initializeDatabase(recoverCorruption = false) {
1021
1065
  if (this.dbPromise) {
1022
1066
  return this.dbPromise;
1023
1067
  }
@@ -1025,82 +1069,64 @@ class SQLiteMemoryStore {
1025
1069
  if (this.db) {
1026
1070
  return this.db;
1027
1071
  }
1028
- const dbPath = this.resolvePath(this.getDbPath());
1072
+ const dbPath = this.#resolvePath(this.getDbPath());
1073
+ const SqlJs = await getSqlJs();
1074
+ let dbData;
1029
1075
  try {
1030
- const dir = dirname3(dbPath);
1031
- if (!existsSync3(dir)) {
1032
- await mkdir2(dir, { recursive: true, mode: 448 });
1076
+ dbData = await readFile3(dbPath);
1077
+ } catch (error) {
1078
+ if (!(error instanceof Error && ("code" in error) && error.code === "ENOENT"))
1079
+ throw error;
1080
+ }
1081
+ const openDatabase = (data) => {
1082
+ if (data && (data.length < 16 || new TextDecoder().decode(data.subarray(0, 16)) !== "SQLite format 3\x00")) {
1083
+ throw new Error("Invalid SQLite database header");
1033
1084
  }
1034
- FileLock.cleanupOldLockFiles(dbPath).catch(() => {});
1035
- let dbData;
1036
- if (existsSync3(dbPath)) {
1037
- const lock = this.getFileLock();
1038
- await lock.acquire();
1039
- try {
1040
- try {
1041
- dbData = await readFile3(dbPath);
1042
- if (dbData.length >= 16) {
1043
- const header = String.fromCharCode(...dbData.subarray(0, 15));
1044
- if (header !== "SQLite format 3") {
1045
- console.warn("[SQLiteMemoryStore] Invalid SQLite database header, will recreate");
1046
- dbData = undefined;
1047
- }
1048
- }
1049
- } catch (error) {
1050
- const errorCode = error?.code;
1051
- if (errorCode === "ENOENT") {
1052
- dbData = undefined;
1053
- } else {
1054
- throw new Error(`Failed to read database file at ${dbPath}: ${error instanceof Error ? error.message : String(error)}`);
1055
- }
1056
- }
1057
- } finally {
1058
- await lock.release();
1059
- }
1085
+ const db = new SqlJs.Database(data);
1086
+ try {
1087
+ this.configurePragmas(db);
1088
+ this.checkIntegrity(db);
1089
+ this.initializeSchema(db);
1090
+ return db;
1091
+ } catch (error) {
1092
+ db.close();
1093
+ throw error;
1060
1094
  }
1061
- const SqlJs2 = await getSqlJs();
1062
- const db = new SqlJs2.Database(dbData);
1063
- this.configurePragmas(db);
1064
- this.checkIntegrity(db);
1065
- this.initializeSchema(db);
1066
- this.db = db;
1067
- return db;
1095
+ };
1096
+ try {
1097
+ this.db = openDatabase(dbData);
1068
1098
  } catch (error) {
1069
- console.error("[SQLiteMemoryStore] Initialization failed:", error);
1070
- if (existsSync3(dbPath)) {
1071
- const backupPath = `${dbPath}.corrupted.${Date.now()}`;
1072
- console.warn(`[SQLiteMemoryStore] Backing up corrupted database to: ${backupPath}`);
1073
- try {
1074
- await rename2(dbPath, backupPath);
1075
- } catch (backupError) {
1076
- console.error("[SQLiteMemoryStore] Failed to backup corrupted database:", backupError);
1077
- this.dbPromise = null;
1078
- throw backupError;
1079
- }
1080
- this.dbPromise = null;
1081
- return this.initializeDatabase();
1082
- }
1083
- this.dbPromise = null;
1084
- throw error;
1099
+ const corruption = error instanceof Error && [
1100
+ "Invalid SQLite database header",
1101
+ "file is not a database",
1102
+ "database disk image is malformed",
1103
+ "Database integrity check failed"
1104
+ ].includes(error.message);
1105
+ if (!recoverCorruption || !dbData || !corruption)
1106
+ throw error;
1107
+ const backupPath = `${dbPath}.corrupted.${randomUUID()}`;
1108
+ await rename2(dbPath, backupPath);
1109
+ console.warn(`[SQLiteMemoryStore] Backed up corrupted database to: ${backupPath}`);
1110
+ this.db = openDatabase();
1085
1111
  }
1112
+ return this.db;
1086
1113
  })();
1087
- return this.dbPromise;
1114
+ try {
1115
+ return await this.dbPromise;
1116
+ } catch (error) {
1117
+ this.dbPromise = null;
1118
+ throw error;
1119
+ }
1088
1120
  }
1089
1121
  async saveDatabase() {
1090
1122
  if (!this.db) {
1091
1123
  return;
1092
1124
  }
1093
- const lock = this.getFileLock();
1094
- await lock.acquire();
1095
- try {
1096
- const dbPath = this.resolvePath(this.getDbPath());
1097
- const tempPath = `${dbPath}.tmp`;
1098
- const data = this.db.export();
1099
- await writeFile2(tempPath, data, { mode: 384 });
1100
- await rename2(tempPath, dbPath);
1101
- } finally {
1102
- await lock.release();
1103
- }
1125
+ const dbPath = this.#resolvePath(this.getDbPath());
1126
+ const tempPath = `${dbPath}.tmp`;
1127
+ const data = this.db.export();
1128
+ await writeFile2(tempPath, data, { mode: 384 });
1129
+ await rename2(tempPath, dbPath);
1104
1130
  }
1105
1131
  configurePragmas(db) {
1106
1132
  db.run("PRAGMA synchronous = NORMAL");
@@ -1109,14 +1135,9 @@ class SQLiteMemoryStore {
1109
1135
  db.run("PRAGMA temp_store = MEMORY");
1110
1136
  }
1111
1137
  checkIntegrity(db) {
1112
- try {
1113
- const results = db.exec("SELECT 1");
1114
- if (results.length === 0) {
1115
- throw new Error("Database query returned no results");
1116
- }
1117
- } catch (error) {
1118
- console.error("[SQLiteMemoryStore] Integrity check failed:", error);
1119
- throw new Error("Database is corrupted");
1138
+ const results = db.exec("PRAGMA quick_check");
1139
+ if (results[0]?.values.length !== 1 || results[0]?.values[0]?.[0] !== "ok") {
1140
+ throw new Error("Database integrity check failed");
1120
1141
  }
1121
1142
  }
1122
1143
  initializeSchema(db) {
@@ -1140,15 +1161,21 @@ class SQLiteMemoryStore {
1140
1161
  db.run("CREATE INDEX IF NOT EXISTS idx_memory_entries_scope_type ON memory_entries(scope, entry_type)");
1141
1162
  db.run("CREATE INDEX IF NOT EXISTS idx_memory_entries_updated ON memory_entries(updated_at)");
1142
1163
  }
1143
- async getDatabase() {
1164
+ async getDatabase(recoverCorruption = false) {
1144
1165
  if (!this.db) {
1145
- this.db = await this.initializeDatabase();
1166
+ this.db = await this.initializeDatabase(recoverCorruption);
1146
1167
  }
1147
1168
  return this.db;
1148
1169
  }
1149
- resolvePath(path) {
1150
- const resolved = resolveHomePath(path);
1151
- return resolve4(resolved);
1170
+ #resolvePath(path) {
1171
+ const resolved = resolve4(resolveHomePath(path));
1172
+ if (path.startsWith("~")) {
1173
+ const fromHome = relative3(resolveHomePath("~"), resolved);
1174
+ if (fromHome === ".." || fromHome.startsWith(`..${sep3}`) || isAbsolute2(fromHome)) {
1175
+ throw new Error("Memory path must not escape the home directory");
1176
+ }
1177
+ }
1178
+ return resolved;
1152
1179
  }
1153
1180
  generateUUID() {
1154
1181
  return randomUUID();
@@ -1163,9 +1190,17 @@ class SQLiteMemoryStore {
1163
1190
  }
1164
1191
  const release = await this.transactionMutex.acquire(owner);
1165
1192
  return transactionOwnerStorage.run(owner, async () => {
1193
+ const shouldBegin = !this.inTransaction;
1194
+ let lock;
1166
1195
  try {
1167
- const db = await this.getDatabase();
1168
- const shouldBegin = !this.inTransaction;
1196
+ if (shouldBegin) {
1197
+ await mkdir2(dirname3(this.#resolvePath(this.getDbPath())), { recursive: true, mode: 448 });
1198
+ const fileLock = this.getFileLock();
1199
+ await fileLock.acquire();
1200
+ lock = fileLock;
1201
+ await this.close();
1202
+ }
1203
+ const db = await this.getDatabase(shouldBegin);
1169
1204
  try {
1170
1205
  if (shouldBegin) {
1171
1206
  db.run("BEGIN TRANSACTION");
@@ -1179,7 +1214,7 @@ class SQLiteMemoryStore {
1179
1214
  await this.saveDatabase();
1180
1215
  } catch (saveError) {
1181
1216
  console.error("[SQLiteMemoryStore] Failed to save database after commit, closing:", saveError);
1182
- await this.close(true);
1217
+ await this.close();
1183
1218
  throw saveError;
1184
1219
  }
1185
1220
  }
@@ -1196,7 +1231,11 @@ class SQLiteMemoryStore {
1196
1231
  throw error;
1197
1232
  }
1198
1233
  } finally {
1199
- release();
1234
+ try {
1235
+ await lock?.release();
1236
+ } finally {
1237
+ release();
1238
+ }
1200
1239
  }
1201
1240
  });
1202
1241
  }
@@ -1221,9 +1260,9 @@ class SQLiteMemoryStore {
1221
1260
  const updatedAt = metadata?.updated_at ?? now;
1222
1261
  const lastAccessed = metadata?.last_accessed ?? now;
1223
1262
  if (operation === "remove") {
1224
- const stmt2 = db.prepare("DELETE FROM memory_entries WHERE name = ? AND scope = ?");
1225
- stmt2.run([topic, scope]);
1226
- stmt2.free();
1263
+ const stmt = db.prepare("DELETE FROM memory_entries WHERE name = ? AND scope = ?");
1264
+ stmt.run([topic, scope]);
1265
+ stmt.free();
1227
1266
  return;
1228
1267
  }
1229
1268
  const stmt = db.prepare("SELECT content, entry_type, status, priority, tags FROM memory_entries WHERE name = ? AND scope = ?");
@@ -1311,28 +1350,28 @@ ${content}`;
1311
1350
  async queryMemory(query = {}, options = {}) {
1312
1351
  if (options.operation === "delete") {
1313
1352
  return this.transaction(async () => {
1314
- const db2 = await this.getDatabase();
1315
- const { sql: sql2, params: params2 } = this.buildQuery(query);
1316
- const deleteSql = `DELETE FROM memory_entries WHERE id IN (SELECT id FROM (${sql2}))`;
1317
- const stmt2 = db2.prepare(deleteSql);
1318
- stmt2.bind(params2);
1319
- stmt2.step();
1320
- stmt2.free();
1321
- return db2.getRowsModified();
1353
+ const db = await this.getDatabase();
1354
+ const { sql, params } = this.buildQuery(query);
1355
+ const deleteSql = `DELETE FROM memory_entries WHERE id IN (SELECT id FROM (${sql}))`;
1356
+ const stmt = db.prepare(deleteSql);
1357
+ stmt.bind(params);
1358
+ stmt.step();
1359
+ stmt.free();
1360
+ return db.getRowsModified();
1322
1361
  });
1323
1362
  }
1324
1363
  const db = await this.getDatabase();
1325
1364
  const { sql, params } = this.buildQuery(query);
1326
1365
  if (options.operation === "count") {
1327
1366
  const countSql = `SELECT COUNT(*) as count FROM (${sql})`;
1328
- const stmt2 = db.prepare(countSql);
1329
- stmt2.bind(params);
1367
+ const stmt = db.prepare(countSql);
1368
+ stmt.bind(params);
1330
1369
  let count = 0;
1331
- if (stmt2.step()) {
1332
- const row = stmt2.getAsObject();
1370
+ if (stmt.step()) {
1371
+ const row = stmt.getAsObject();
1333
1372
  count = row.count;
1334
1373
  }
1335
- stmt2.free();
1374
+ stmt.free();
1336
1375
  return count;
1337
1376
  }
1338
1377
  const stmt = db.prepare(sql);
@@ -1348,13 +1387,9 @@ ${content}`;
1348
1387
  const conditions = [];
1349
1388
  const params = [];
1350
1389
  let sql = "SELECT * FROM memory_entries WHERE 1=1";
1351
- const scope = query.scope === "auto" ? this.currentScope : query.scope;
1352
- if (scope === "global") {
1353
- conditions.push(`scope = ?`);
1354
- params.push("global");
1355
- } else if (scope === "project" || !scope && this.currentScope !== "global") {
1390
+ if (query.scope !== undefined || this.currentScope !== "global") {
1356
1391
  conditions.push(`scope = ?`);
1357
- params.push(this.currentScope);
1392
+ params.push(query.scope === "global" ? "global" : this.currentScope);
1358
1393
  }
1359
1394
  if (query.name) {
1360
1395
  if (!query.name.trim()) {
@@ -1455,20 +1490,9 @@ ${content}`;
1455
1490
  }
1456
1491
  });
1457
1492
  }
1458
- async close(skipSave = false) {
1459
- const db = this.db;
1460
- if (db) {
1461
- try {
1462
- if (!skipSave) {
1463
- await this.saveDatabase();
1464
- }
1465
- } finally {
1466
- if (this.db === db) {
1467
- db.close();
1468
- this.db = null;
1469
- }
1470
- }
1471
- }
1493
+ async close(_skipSave) {
1494
+ this.db?.close();
1495
+ this.db = null;
1472
1496
  this.dbPromise = null;
1473
1497
  }
1474
1498
  async getStats() {
@@ -1482,10 +1506,10 @@ ${content}`;
1482
1506
  entriesByType[row[0]] = row[1];
1483
1507
  }
1484
1508
  }
1485
- const dbPath = this.resolvePath(this.getDbPath());
1509
+ const dbPath = this.#resolvePath(this.getDbPath());
1486
1510
  let databaseSize = 0;
1487
1511
  try {
1488
- const stats = await import("node:fs/promises").then((fs2) => fs2.stat(dbPath));
1512
+ const stats = await import("node:fs/promises").then((fs) => fs.stat(dbPath));
1489
1513
  databaseSize = stats.size;
1490
1514
  } catch {}
1491
1515
  return {
@@ -1764,10 +1788,29 @@ Tool error:`, event.tool));
1764
1788
  }
1765
1789
  };
1766
1790
  };
1791
+ // src/utils/git-status.ts
1792
+ function parseGitPorcelain(output) {
1793
+ const entries = [];
1794
+ const records = output.split("\x00");
1795
+ for (let index = 0;index < records.length; index++) {
1796
+ const record = records[index];
1797
+ if (!record)
1798
+ continue;
1799
+ const entry = { path: record.slice(3), indexStatus: record[0], workingTreeStatus: record[1] };
1800
+ const status = record.slice(0, 2);
1801
+ if (status.includes("R") || status.includes("C")) {
1802
+ entry.originalPath = records[++index];
1803
+ if (!entry.originalPath)
1804
+ throw new Error("Missing source path in Git status");
1805
+ }
1806
+ entries.push(entry);
1807
+ }
1808
+ return entries;
1809
+ }
1767
1810
  // src/utils/readMultiline.ts
1768
1811
  import readline from "node:readline";
1769
1812
  function readMultiline(prompt = "Enter text (Ctrl+D to finish):") {
1770
- return new Promise((resolve5) => {
1813
+ return new Promise((resolve) => {
1771
1814
  console.log(prompt);
1772
1815
  const rl = readline.createInterface({
1773
1816
  input: process.stdin,
@@ -1779,32 +1822,34 @@ function readMultiline(prompt = "Enter text (Ctrl+D to finish):") {
1779
1822
  lines.push(line);
1780
1823
  });
1781
1824
  rl.on("close", () => {
1782
- resolve5(lines.join(`
1825
+ resolve(lines.join(`
1783
1826
  `));
1784
1827
  });
1785
1828
  });
1786
1829
  }
1787
1830
  export {
1788
- simplifyToolParameters,
1789
- searchFiles,
1790
- resolveRules,
1791
- readMultiline,
1792
- readLocalConfig,
1793
- readConfig,
1794
- printEvent,
1795
- mergeConfigs,
1796
- logToolCallStats,
1797
- logGlobalToolCallStats,
1798
- localConfigFileName,
1799
- loadConfigAtPath,
1800
- loadConfig,
1801
- listFiles,
1802
- getProvider,
1803
- getGlobalConfigPath,
1804
- detectProjectScope,
1805
- configSchema,
1806
- checkRipgrep,
1807
- SQLiteMemoryStore,
1831
+ InMemoryStore,
1808
1832
  MemoryManager,
1809
- InMemoryStore
1833
+ SQLiteMemoryStore,
1834
+ checkRipgrep,
1835
+ configSchema,
1836
+ detectProjectScope,
1837
+ getGlobalConfigPath,
1838
+ getProvider,
1839
+ listFiles,
1840
+ loadConfig,
1841
+ loadConfigAtPath,
1842
+ localConfigFileName,
1843
+ logGlobalToolCallStats,
1844
+ logToolCallStats,
1845
+ mergeConfigs,
1846
+ parseGitPorcelain,
1847
+ printEvent,
1848
+ readConfig,
1849
+ readLocalConfig,
1850
+ readMultiline,
1851
+ resolveRules,
1852
+ searchFiles,
1853
+ simplifyToolParameters,
1854
+ spawnCommand
1810
1855
  };
@@ -1,6 +1,7 @@
1
1
  import type { DatabaseStats, IMemoryStore, MemoryConfig, MemoryEntry, MemoryOperation, MemoryQuery, QueryOptions } from '@polka-codes/core';
2
2
  export type { MemoryEntry, MemoryOperation, MemoryQuery, QueryOptions };
3
3
  export declare class SQLiteMemoryStore implements IMemoryStore {
4
+ #private;
4
5
  private db;
5
6
  private dbPromise;
6
7
  private config;
@@ -48,10 +49,6 @@ export declare class SQLiteMemoryStore implements IMemoryStore {
48
49
  * Get database instance
49
50
  */
50
51
  private getDatabase;
51
- /**
52
- * Resolve home directory in path using shared utility
53
- */
54
- private resolvePath;
55
52
  /**
56
53
  * Generate UUID v4
57
54
  */
@@ -101,10 +98,10 @@ export declare class SQLiteMemoryStore implements IMemoryStore {
101
98
  */
102
99
  batchUpdateMemory(operations: MemoryOperation[]): Promise<void>;
103
100
  /**
104
- * Close database connection
105
- * @param skipSave - If true, skip saving before close (useful when save already failed)
101
+ * Close the in-memory snapshot. Transactions persist their own changes.
102
+ * @param _skipSave Deprecated; accepted for compatibility and ignored.
106
103
  */
107
- close(skipSave?: boolean): Promise<void>;
104
+ close(_skipSave?: boolean): Promise<void>;
108
105
  /**
109
106
  * Get database statistics
110
107
  */
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,8 @@
1
+ export type GitStatusEntry = {
2
+ path: string;
3
+ originalPath?: string;
4
+ indexStatus: string;
5
+ workingTreeStatus: string;
6
+ };
7
+ /** Parse git status --porcelain=v1 -z without quoting or normalizing paths. */
8
+ export declare function parseGitPorcelain(output: string): GitStatusEntry[];
@@ -1,6 +1,8 @@
1
1
  export * from './checkRipgrep.js';
2
2
  export * from './eventHandler.js';
3
+ export { type GitStatusEntry, parseGitPorcelain } from './git-status.js';
3
4
  export * from './listFiles.js';
4
5
  export * from './parameterSimplifier.js';
5
6
  export * from './readMultiline.js';
6
7
  export * from './searchFiles.js';
8
+ export * from './spawnCommand.js';
@@ -9,4 +9,4 @@
9
9
  * @param excludeFiles - Additional patterns to exclude
10
10
  * @returns Array of search results with context
11
11
  */
12
- export declare function searchFiles(path: string, regex: string, filePattern: string, cwd: string, excludeFiles?: string[]): Promise<string[]>;
12
+ export declare function searchFiles(path: string, regex: string, filePattern: string, cwd: string, excludeFiles?: readonly string[]): Promise<string[]>;
@@ -0,0 +1,2 @@
1
+ /** Undefined arguments select a shell; an array passes arguments literally. */
2
+ export declare function spawnCommand(command: string, args?: string[], signal?: AbortSignal): import("node:child_process").ChildProcessByStdio<null, import("node:stream").Readable, import("node:stream").Readable>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@polka-codes/cli-shared",
3
- "version": "0.11.7",
3
+ "version": "0.12.0",
4
4
  "license": "AGPL-3.0",
5
5
  "author": "github@polka.codes",
6
6
  "repository": {
@@ -29,7 +29,7 @@
29
29
  "@ai-sdk/google-vertex": "^5.0.20",
30
30
  "@ai-sdk/provider": "^4.0.3",
31
31
  "@inquirer/prompts": "^8.5.2",
32
- "@polka-codes/core": "^0.11.7",
32
+ "@polka-codes/core": "^0.12.0",
33
33
  "ai": "^7.0.28",
34
34
  "chalk": "^5.6.2",
35
35
  "ignore": "^7.0.6",