dsh-better-edit 0.3.2 → 0.4.0-rc.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 +16 -2
- package/README.md +67 -51
- package/README.zh.md +44 -33
- package/lib/canonical-path.js +86 -0
- package/lib/fs-bridge.js +7 -6
- package/lib/hash-store.js +38 -34
- package/lib/index.js +12 -0
- package/lib/paths.js +12 -91
- package/lib/session-view.js +9 -9
- package/lib/store-config.js +317 -0
- package/lib/store-lifecycle.js +236 -0
- package/lib/store-tenancy.js +101 -0
- package/lib/types/canonical-path.d.ts +11 -0
- package/lib/types/hash-store.d.ts +12 -6
- package/lib/types/paths.d.ts +3 -23
- package/lib/types/session-view.d.ts +1 -1
- package/lib/types/store-config.d.ts +33 -0
- package/lib/types/store-lifecycle.d.ts +12 -0
- package/lib/types/store-tenancy.d.ts +13 -0
- package/package.json +4 -3
package/lib/index.js
CHANGED
|
@@ -24,6 +24,8 @@ import { registerWriteHook } from "./write-hook.js";
|
|
|
24
24
|
import { initHasher } from "./hashline/hash-assign.js";
|
|
25
25
|
import { composeSections, ensurePresetGuidance, GUIDANCE_SECTIONS, } from "./guidance.js";
|
|
26
26
|
import { configDir } from "./paths.js";
|
|
27
|
+
import { ensureDefaultConfig } from "./store-config.js";
|
|
28
|
+
import { onAppStart, onSessionStart } from "./store-lifecycle.js";
|
|
27
29
|
/** Cordis plugin name used by loader diagnostics. */
|
|
28
30
|
export const name = "dsh-better-edit";
|
|
29
31
|
/**
|
|
@@ -98,6 +100,11 @@ function installAgentTools(rootCtx, agent) {
|
|
|
98
100
|
}
|
|
99
101
|
/** Mount the bundle: initialize the store, then install tools per agent. */
|
|
100
102
|
export function apply(rootCtx) {
|
|
103
|
+
// Central lifecycle janitor — throttled 24h, never deletes live hash (mtime hot)
|
|
104
|
+
// Runs once at app start and on each session-start (central mode only)
|
|
105
|
+
queueMicrotask(() => {
|
|
106
|
+
onAppStart().catch((e) => rootCtx.logger.warn(`dsh-better-edit: central janitor failed: ${e instanceof Error ? e.message : String(e)}`));
|
|
107
|
+
});
|
|
101
108
|
// Warm the hasher once; the per-workspace stores are opened lazily on the
|
|
102
109
|
// first tool call in each workspace (there is no shared store to prune at
|
|
103
110
|
// boot anymore).
|
|
@@ -107,11 +114,16 @@ export function apply(rootCtx) {
|
|
|
107
114
|
// Seed each shipped preset's guidance directory once, so users have
|
|
108
115
|
// editable per-preset overrides (idempotent: never rewrites existing
|
|
109
116
|
// files). A failure must never fail the boot.
|
|
117
|
+
ensureDefaultConfig().catch((error) => {
|
|
118
|
+
rootCtx.logger.warn(`dsh-better-edit: default config materialization failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
119
|
+
});
|
|
110
120
|
ensurePresetGuidance(configDir()).catch((error) => {
|
|
111
121
|
rootCtx.logger.warn(`dsh-better-edit: guidance materialization failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
112
122
|
});
|
|
113
123
|
const registered = new WeakSet();
|
|
114
124
|
rootCtx.on("agent/session-start", ({ agent }) => {
|
|
125
|
+
// throttled central janitor on session-start (inside same handler to avoid extra listener)
|
|
126
|
+
onSessionStart().catch((e) => rootCtx.logger.warn(`dsh-better-edit: central janitor failed: ${e instanceof Error ? e.message : String(e)}`));
|
|
115
127
|
if (registered.has(agent))
|
|
116
128
|
return;
|
|
117
129
|
registered.add(agent);
|
package/lib/paths.js
CHANGED
|
@@ -1,97 +1,18 @@
|
|
|
1
|
-
import { homedir } from "node:os";
|
|
2
|
-
import { isAbsolute, resolve as resolvePath, join, dirname, parse, sep, } from "node:path";
|
|
3
|
-
import { lstat, readlink } from "node:fs/promises";
|
|
4
|
-
import { resolveDshHome } from "@deepseek-ai/dsh-home-paths";
|
|
5
|
-
import { errCode } from "./utils.js";
|
|
6
1
|
/**
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
*
|
|
12
|
-
*
|
|
13
|
-
* so a caller without a workspace never writes into an arbitrary cwd.
|
|
14
|
-
* @param cwd - the workspace root, or undefined for the shared-home fallback.
|
|
2
|
+
* Paths — thin adapter over StoreTenancy + CanonicalPath.
|
|
3
|
+
* Public API preserved for compat: configDir, hashStorePath, hashStoreDir,
|
|
4
|
+
* legacyHashStorePath, resolveTarget, toCwd.
|
|
5
|
+
* Deep tenancy lives in StoreTenancy (config via StoreConfig); canonical
|
|
6
|
+
* resolution in CanonicalPath.
|
|
7
|
+
* @module dsh-better-edit/paths
|
|
15
8
|
*/
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
}
|
|
21
|
-
export
|
|
22
|
-
return join(configDir(cwd), "hash-store.sqlite");
|
|
23
|
-
}
|
|
24
|
-
export function legacyHashStorePath(cwd) {
|
|
25
|
-
return join(configDir(cwd), "hash-store.json");
|
|
26
|
-
}
|
|
27
|
-
export function hashStoreDir(cwd) {
|
|
28
|
-
return dirname(hashStorePath(cwd));
|
|
29
|
-
}
|
|
30
|
-
function homeBase() {
|
|
31
|
-
const envHome = process.env.HOME;
|
|
32
|
-
return envHome && envHome.length > 0 ? envHome : homedir();
|
|
33
|
-
}
|
|
34
|
-
function expand(filePath) {
|
|
35
|
-
const home = homeBase();
|
|
36
|
-
if (filePath === "~")
|
|
37
|
-
return home;
|
|
38
|
-
if (filePath.startsWith("~/"))
|
|
39
|
-
return home + filePath.slice(1);
|
|
40
|
-
return filePath;
|
|
41
|
-
}
|
|
9
|
+
import { isAbsolute } from "node:path";
|
|
10
|
+
import { resolve as resolvePath } from "node:path";
|
|
11
|
+
import { expand } from "./store-tenancy.js";
|
|
12
|
+
export * from "./store-tenancy.js";
|
|
13
|
+
export { canonicalAsync as resolveTarget } from "./canonical-path.js";
|
|
14
|
+
export { canonicalSync } from "./canonical-path.js";
|
|
42
15
|
export function toCwd(filePath, cwd) {
|
|
43
16
|
const expanded = expand(filePath);
|
|
44
17
|
return isAbsolute(expanded) ? expanded : resolvePath(cwd, expanded);
|
|
45
18
|
}
|
|
46
|
-
/**
|
|
47
|
-
* Canonicalize a path, resolving every symlink component to its target
|
|
48
|
-
* (loop-guarded, ELOOP on cycles). Non-existent final components resolve
|
|
49
|
-
* lexically — the canonical form of a not-yet-created file. The hashline
|
|
50
|
-
* tools key their state by canonical absolute paths, so the same file reached
|
|
51
|
-
* through different symlink spellings lands on the same store rows.
|
|
52
|
-
* @param path - the path to canonicalize (absolute or relative).
|
|
53
|
-
*/
|
|
54
|
-
export async function resolveTarget(path) {
|
|
55
|
-
const absolutePath = resolvePath(path);
|
|
56
|
-
const { root } = parse(absolutePath);
|
|
57
|
-
const parts = absolutePath
|
|
58
|
-
.slice(root.length)
|
|
59
|
-
.split(sep)
|
|
60
|
-
.filter((part) => part.length > 0);
|
|
61
|
-
const visitedSymlinks = new Set();
|
|
62
|
-
async function resParts(currentPath, remainingParts) {
|
|
63
|
-
if (remainingParts.length === 0) {
|
|
64
|
-
return currentPath;
|
|
65
|
-
}
|
|
66
|
-
const [nextPart, ...tail] = remainingParts;
|
|
67
|
-
const candidatePath = join(currentPath, nextPart);
|
|
68
|
-
try {
|
|
69
|
-
const candidateStats = await lstat(candidatePath);
|
|
70
|
-
if (!candidateStats.isSymbolicLink()) {
|
|
71
|
-
return resParts(candidatePath, tail);
|
|
72
|
-
}
|
|
73
|
-
if (visitedSymlinks.has(candidatePath)) {
|
|
74
|
-
const error = new Error(`Too many symbolic links while resolving ${path}`);
|
|
75
|
-
error.code = "ELOOP";
|
|
76
|
-
throw error;
|
|
77
|
-
}
|
|
78
|
-
visitedSymlinks.add(candidatePath);
|
|
79
|
-
const linkTargetPath = resolvePath(dirname(candidatePath), await readlink(candidatePath));
|
|
80
|
-
const targetParts = linkTargetPath
|
|
81
|
-
.slice(parse(linkTargetPath).root.length)
|
|
82
|
-
.split(sep)
|
|
83
|
-
.filter((part) => part.length > 0);
|
|
84
|
-
return resParts(parse(linkTargetPath).root, [
|
|
85
|
-
...targetParts,
|
|
86
|
-
...tail,
|
|
87
|
-
]);
|
|
88
|
-
}
|
|
89
|
-
catch (error) {
|
|
90
|
-
if (errCode(error) === "ENOENT") {
|
|
91
|
-
return join(candidatePath, ...tail);
|
|
92
|
-
}
|
|
93
|
-
throw error;
|
|
94
|
-
}
|
|
95
|
-
}
|
|
96
|
-
return resParts(root, parts);
|
|
97
|
-
}
|
package/lib/session-view.js
CHANGED
|
@@ -30,7 +30,7 @@
|
|
|
30
30
|
import { randomUUID } from "node:crypto";
|
|
31
31
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
32
32
|
import { HASH_RE } from "./hashline/hash-assign.js";
|
|
33
|
-
import { loadHashStore, withStore } from "./hash-store.js";
|
|
33
|
+
import { loadHashStore, loadServedStore, withStore } from "./hash-store.js";
|
|
34
34
|
import { SERVED_ECHO_CAP } from "./constants.js";
|
|
35
35
|
import { fmtServedRows } from "./hashline/served.js";
|
|
36
36
|
import { configDir, hashStorePath, resolveTarget } from "./paths.js";
|
|
@@ -59,7 +59,7 @@ export function execSessionKey(exec) {
|
|
|
59
59
|
// --- paths re-export (seam visibility) ---
|
|
60
60
|
export { configDir, hashStorePath, resolveTarget };
|
|
61
61
|
// --- hash-store re-export (persistence note) ---
|
|
62
|
-
export { loadHashStore, shutdownHashStore, withStore } from "./hash-store.js";
|
|
62
|
+
export { loadHashStore, loadServedStore, shutdownHashStore, withStore } from "./hash-store.js";
|
|
63
63
|
/**
|
|
64
64
|
* Merge served rows into a copy of the stored array. This single helper owns
|
|
65
65
|
* the served-merge invariant shared by recordServed and recordServedTruncated.
|
|
@@ -121,14 +121,14 @@ export function _mergeServedRows(current, rows, options) {
|
|
|
121
121
|
return updated;
|
|
122
122
|
}
|
|
123
123
|
export async function loadServed(sessionKey, path) {
|
|
124
|
-
const store = await
|
|
124
|
+
const store = await loadServedStore();
|
|
125
125
|
return store.getServed(sessionKey, path);
|
|
126
126
|
}
|
|
127
127
|
export async function recordServed(sessionKey, path, rows, lineCount) {
|
|
128
128
|
if (rows.length === 0)
|
|
129
129
|
return;
|
|
130
130
|
try {
|
|
131
|
-
const store = await
|
|
131
|
+
const store = await loadServedStore();
|
|
132
132
|
withStore(() => {
|
|
133
133
|
const current = store.getServed(sessionKey, path);
|
|
134
134
|
const updated = _mergeServedRows(current, rows, lineCount === undefined ? undefined : { truncateTo: lineCount });
|
|
@@ -145,7 +145,7 @@ export async function recordServedTruncated(sessionKey, path, rows, lineCount, c
|
|
|
145
145
|
if (rows.length === 0)
|
|
146
146
|
return;
|
|
147
147
|
try {
|
|
148
|
-
const store = await
|
|
148
|
+
const store = await loadServedStore();
|
|
149
149
|
withStore(() => {
|
|
150
150
|
const current = store.getServed(sessionKey, path);
|
|
151
151
|
const updated = _mergeServedRows(current, rows, { truncateTo: lineCount, clearFrom });
|
|
@@ -161,7 +161,7 @@ export async function recordServedTruncated(sessionKey, path, rows, lineCount, c
|
|
|
161
161
|
}
|
|
162
162
|
export async function driftReported(sessionKey, path) {
|
|
163
163
|
try {
|
|
164
|
-
const store = await
|
|
164
|
+
const store = await loadServedStore();
|
|
165
165
|
return store.getServedReported(sessionKey, path);
|
|
166
166
|
}
|
|
167
167
|
catch (error) {
|
|
@@ -174,7 +174,7 @@ export async function markDriftReported(sessionKey, path, hashes) {
|
|
|
174
174
|
const valid = hashes.filter((hash) => HASH_RE.test(hash));
|
|
175
175
|
if (valid.length === 0)
|
|
176
176
|
return;
|
|
177
|
-
const store = await
|
|
177
|
+
const store = await loadServedStore();
|
|
178
178
|
withStore(() => {
|
|
179
179
|
const current = store.getServedReported(sessionKey, path);
|
|
180
180
|
for (const hash of valid)
|
|
@@ -188,7 +188,7 @@ export async function markDriftReported(sessionKey, path, hashes) {
|
|
|
188
188
|
}
|
|
189
189
|
export async function clearDriftReported(sessionKey, path) {
|
|
190
190
|
try {
|
|
191
|
-
const store = await
|
|
191
|
+
const store = await loadServedStore();
|
|
192
192
|
withStore(() => {
|
|
193
193
|
store.clearServedReported(sessionKey, path);
|
|
194
194
|
});
|
|
@@ -199,7 +199,7 @@ export async function clearDriftReported(sessionKey, path) {
|
|
|
199
199
|
}
|
|
200
200
|
export async function wipeServedState(sessionKey) {
|
|
201
201
|
try {
|
|
202
|
-
const store = await
|
|
202
|
+
const store = await loadServedStore();
|
|
203
203
|
store.wipeServed(sessionKey);
|
|
204
204
|
}
|
|
205
205
|
catch (error) {
|
|
@@ -0,0 +1,317 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* StoreConfig — deep module owning store tenancy config.
|
|
3
|
+
* Owns yaml parsing, Zod validation, fs + env adapters, merge and mtime cache.
|
|
4
|
+
* Paths and hash-store remain thin adapters via loadConfig().
|
|
5
|
+
* @module dsh-better-edit/store-config
|
|
6
|
+
*/
|
|
7
|
+
import { homedir } from "node:os";
|
|
8
|
+
import { isAbsolute, join } from "node:path";
|
|
9
|
+
import { readFileSync, statSync } from "node:fs";
|
|
10
|
+
import { mkdir, writeFile } from "node:fs/promises";
|
|
11
|
+
import { resolveDshHome } from "@deepseek-ai/dsh-home-paths";
|
|
12
|
+
import { z } from "zod";
|
|
13
|
+
import { errCode } from "./utils.js";
|
|
14
|
+
// ---- helpers (pure, no IO) ----
|
|
15
|
+
function homeBase() {
|
|
16
|
+
const envHome = process.env.HOME;
|
|
17
|
+
return envHome && envHome.length > 0 ? envHome : homedir();
|
|
18
|
+
}
|
|
19
|
+
export function expand(filePath) {
|
|
20
|
+
const home = homeBase();
|
|
21
|
+
if (filePath === "~")
|
|
22
|
+
return home;
|
|
23
|
+
if (filePath.startsWith("~/"))
|
|
24
|
+
return home + filePath.slice(1);
|
|
25
|
+
return filePath;
|
|
26
|
+
}
|
|
27
|
+
function stripQuotes(value) {
|
|
28
|
+
const t = value.trim();
|
|
29
|
+
if ((t.startsWith('"') && t.endsWith('"')) || (t.startsWith("'") && t.endsWith("'"))) {
|
|
30
|
+
return t.slice(1, -1).trim();
|
|
31
|
+
}
|
|
32
|
+
return t;
|
|
33
|
+
}
|
|
34
|
+
function stripInlineComment(value) {
|
|
35
|
+
const idx = value.indexOf(" #");
|
|
36
|
+
return idx === -1 ? value : value.slice(0, idx).trim();
|
|
37
|
+
}
|
|
38
|
+
function parseSimpleYaml(content) {
|
|
39
|
+
const out = {};
|
|
40
|
+
for (const rawLine of content.split("\n")) {
|
|
41
|
+
const line = rawLine.trim();
|
|
42
|
+
if (line.length === 0 || line.startsWith("#"))
|
|
43
|
+
continue;
|
|
44
|
+
const colon = line.indexOf(":");
|
|
45
|
+
if (colon === -1)
|
|
46
|
+
continue;
|
|
47
|
+
const key = line.slice(0, colon).trim();
|
|
48
|
+
let value = line.slice(colon + 1).trim();
|
|
49
|
+
value = stripQuotes(value);
|
|
50
|
+
value = stripInlineComment(value);
|
|
51
|
+
out[key] = value;
|
|
52
|
+
}
|
|
53
|
+
return out;
|
|
54
|
+
}
|
|
55
|
+
function normalizeStoreDir(v) {
|
|
56
|
+
const val = stripQuotes(v.trim());
|
|
57
|
+
if (val.length === 0)
|
|
58
|
+
return undefined;
|
|
59
|
+
if (val === "workspace" || val === "central")
|
|
60
|
+
return val;
|
|
61
|
+
const expanded = expand(val);
|
|
62
|
+
return isAbsolute(expanded) ? expanded : undefined;
|
|
63
|
+
}
|
|
64
|
+
function parseAutoGitIgnoreRaw(v) {
|
|
65
|
+
const t = v.trim().toLowerCase();
|
|
66
|
+
if (t === "true")
|
|
67
|
+
return true;
|
|
68
|
+
if (t === "false")
|
|
69
|
+
return false;
|
|
70
|
+
return undefined;
|
|
71
|
+
}
|
|
72
|
+
// ---- Zod schema (single source of truth) ----
|
|
73
|
+
const StoreConfigSchema = z.object({
|
|
74
|
+
storeDir: z
|
|
75
|
+
.string()
|
|
76
|
+
.default("central")
|
|
77
|
+
.transform((v) => normalizeStoreDir(v) ?? "central"), // where the store lives: "central" (default, in $DSH_HOME/.../runtime/<name>-<hash8>/) | "workspace" (legacy <ws>/.dsh_better_edit/) | "/abs/path" (custom root)
|
|
78
|
+
autoGitignore: z.boolean().default(false), // workspace only: auto-append ".dsh_better_edit/" to .gitignore when .git exists but entry missing (false = warn once)
|
|
79
|
+
undo_ttl_s: z.number().int().min(-1).default(604800), // undo history TTL in seconds; -1 = keep forever (default 604800 = 7 days)
|
|
80
|
+
storeMaxAgeS: z.number().int().min(1).default(2592000), // central janitor: max idle age in seconds before evicting runtime/<name>-<hash8>/ (default 2592000 = 30 days)
|
|
81
|
+
storeMaxTotalBytes: z.number().int().min(0).default(524288000), // central janitor: max total bytes under runtime/ before LRU eviction (default 524288000 = 500 MB)
|
|
82
|
+
});
|
|
83
|
+
const DEFAULT_CONFIG = StoreConfigSchema.parse({});
|
|
84
|
+
let cachedConfig;
|
|
85
|
+
let cachedMtimeMs;
|
|
86
|
+
let cachedYamlPath;
|
|
87
|
+
let cachedEnvStoreDir;
|
|
88
|
+
let cachedEnvAutoGitignore;
|
|
89
|
+
function configYamlPath() {
|
|
90
|
+
return join(resolveDshHome(), "plugins", "dsh-better-edit", "config.yaml");
|
|
91
|
+
}
|
|
92
|
+
/** Default config.yaml content with comments — generated when the file does not exist. */
|
|
93
|
+
export const DEFAULT_CONFIG_YAML = `# dsh-better-edit config
|
|
94
|
+
# Location: $DSH_HOME/plugins/dsh-better-edit/config.yaml
|
|
95
|
+
# Docs: https://github.com/Rianico/dsh-better-edit#configuration
|
|
96
|
+
# Generated with defaults on first load — edit or delete freely.
|
|
97
|
+
# DB files are disposable caches — safe to delete, rebuilt on next \`read\`.
|
|
98
|
+
|
|
99
|
+
# where the store lives: "central" (default, in $DSH_HOME/.../runtime/<name>-<hash8>/) | "workspace" (legacy <ws>/.dsh_better_edit/) | "/abs/path" (custom root)
|
|
100
|
+
storeDir: central
|
|
101
|
+
|
|
102
|
+
# workspace only: when .git exists but .gitignore lacks .dsh_better_edit/, true = auto-append ".dsh_better_edit/", false = warn once
|
|
103
|
+
autoGitignore: false
|
|
104
|
+
|
|
105
|
+
# undo history TTL in seconds; -1 = keep forever (default 604800 = 7 days)
|
|
106
|
+
undo_ttl_s: 604800
|
|
107
|
+
|
|
108
|
+
# central janitor: max idle age in seconds before evicting runtime/<name>-<hash8>/ (default 2592000 = 30 days)
|
|
109
|
+
storeMaxAgeS: 2592000
|
|
110
|
+
|
|
111
|
+
# central janitor: max total bytes under runtime/ before LRU eviction (default 524288000 = 500 MB)
|
|
112
|
+
storeMaxTotalBytes: 524288000
|
|
113
|
+
`;
|
|
114
|
+
/**
|
|
115
|
+
* Ensure a default config.yaml exists in the plugin home.
|
|
116
|
+
* Idempotent and concurrent-safe (wx) — never overwrites an existing file.
|
|
117
|
+
* Best-effort: failures are logged but never throw to the caller.
|
|
118
|
+
*/
|
|
119
|
+
export async function ensureDefaultConfig(homeDir) {
|
|
120
|
+
const dir = homeDir ?? join(resolveDshHome(), "plugins", "dsh-better-edit");
|
|
121
|
+
const yamlPath = join(dir, "config.yaml");
|
|
122
|
+
try {
|
|
123
|
+
await mkdir(dir, { recursive: true });
|
|
124
|
+
await writeFile(yamlPath, DEFAULT_CONFIG_YAML, { encoding: "utf-8", flag: "wx" });
|
|
125
|
+
}
|
|
126
|
+
catch (error) {
|
|
127
|
+
if (errCode(error) === "EEXIST")
|
|
128
|
+
return;
|
|
129
|
+
// ENOENT for missing parent is handled by mkdir, other errors are best-effort
|
|
130
|
+
console.warn(`dsh-better-edit: failed to materialize default config at ${yamlPath}: ${error instanceof Error ? error.message : String(error)}`);
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
// ---- adapters ----
|
|
134
|
+
function fsAdapter() {
|
|
135
|
+
const yamlPath = configYamlPath();
|
|
136
|
+
try {
|
|
137
|
+
const raw = readFileSync(yamlPath, "utf-8");
|
|
138
|
+
const parsed = parseSimpleYaml(raw);
|
|
139
|
+
const out = {};
|
|
140
|
+
if (parsed.storeDir !== undefined) {
|
|
141
|
+
const norm = normalizeStoreDir(parsed.storeDir);
|
|
142
|
+
if (norm === undefined) {
|
|
143
|
+
console.warn(`dsh-better-edit: storeDir "${parsed.storeDir}" illegal/malformed — not absolute after expand, fallback to central`);
|
|
144
|
+
}
|
|
145
|
+
else {
|
|
146
|
+
// validate via Zod shape for enum/abs
|
|
147
|
+
const res = z.string().safeParse(norm);
|
|
148
|
+
if (res.success)
|
|
149
|
+
out.storeDir = norm;
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
if (parsed.autoGitignore !== undefined) {
|
|
153
|
+
const b = parseAutoGitIgnoreRaw(parsed.autoGitignore);
|
|
154
|
+
if (b === undefined) {
|
|
155
|
+
console.warn(`dsh-better-edit: autoGitignore "${parsed.autoGitignore}" invalid — expected true|false, fallback to false`);
|
|
156
|
+
}
|
|
157
|
+
else {
|
|
158
|
+
const res = z.boolean().safeParse(b);
|
|
159
|
+
if (res.success)
|
|
160
|
+
out.autoGitignore = b;
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
if (parsed.undo_ttl_s !== undefined) {
|
|
164
|
+
const n = Number(parsed.undo_ttl_s);
|
|
165
|
+
const res = z.number().int().min(-1).safeParse(n);
|
|
166
|
+
if (res.success) {
|
|
167
|
+
out.undo_ttl_s = n;
|
|
168
|
+
}
|
|
169
|
+
else {
|
|
170
|
+
console.warn(`dsh-better-edit: undo_ttl_s "${parsed.undo_ttl_s}" invalid — expected int -1 or >=0, fallback to 604800`);
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
// storeMaxAgeS — unified seconds (canonical); deprecated aliases: storeMaxAgeDays / store_max_age_days (days -> seconds), store_max_age_s (snake)
|
|
174
|
+
{
|
|
175
|
+
let rawMaxAge;
|
|
176
|
+
let rawSource;
|
|
177
|
+
if (parsed.storeMaxAgeS !== undefined) {
|
|
178
|
+
rawMaxAge = parsed.storeMaxAgeS;
|
|
179
|
+
rawSource = "storeMaxAgeS";
|
|
180
|
+
}
|
|
181
|
+
else if (parsed.store_max_age_s !== undefined) {
|
|
182
|
+
rawMaxAge = parsed.store_max_age_s;
|
|
183
|
+
rawSource = "store_max_age_s";
|
|
184
|
+
}
|
|
185
|
+
else if (parsed.storeMaxAgeDays !== undefined) {
|
|
186
|
+
rawMaxAge = parsed.storeMaxAgeDays;
|
|
187
|
+
rawSource = "storeMaxAgeDays";
|
|
188
|
+
}
|
|
189
|
+
else if (parsed.store_max_age_days !== undefined) {
|
|
190
|
+
rawMaxAge = parsed.store_max_age_days;
|
|
191
|
+
rawSource = "store_max_age_days";
|
|
192
|
+
}
|
|
193
|
+
if (rawMaxAge !== undefined && rawSource !== undefined) {
|
|
194
|
+
const n = Number(rawMaxAge);
|
|
195
|
+
const isLegacyDays = rawSource === "storeMaxAgeDays" || rawSource === "store_max_age_days";
|
|
196
|
+
if (isLegacyDays) {
|
|
197
|
+
const res = z.number().int().min(1).safeParse(n);
|
|
198
|
+
if (res.success) {
|
|
199
|
+
out.storeMaxAgeS = n * 86400;
|
|
200
|
+
console.warn(`dsh-better-edit: ${rawSource} is deprecated — use storeMaxAgeS (seconds) instead; converted ${n} days -> ${n * 86400} seconds`);
|
|
201
|
+
}
|
|
202
|
+
else {
|
|
203
|
+
console.warn(`dsh-better-edit: ${rawSource} "${rawMaxAge}" invalid — expected int >=1 (days)`);
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
else {
|
|
207
|
+
const res = z.number().int().min(1).safeParse(n);
|
|
208
|
+
if (res.success) {
|
|
209
|
+
out.storeMaxAgeS = n;
|
|
210
|
+
if (rawSource !== "storeMaxAgeS") {
|
|
211
|
+
console.warn(`dsh-better-edit: ${rawSource} is deprecated — use storeMaxAgeS instead`);
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
else {
|
|
215
|
+
console.warn(`dsh-better-edit: ${rawSource} "${rawMaxAge}" invalid — expected int >=1 (seconds)`);
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
if (parsed.storeMaxTotalBytes !== undefined) {
|
|
221
|
+
const n = Number(parsed.storeMaxTotalBytes);
|
|
222
|
+
const res = z.number().int().min(0).safeParse(n);
|
|
223
|
+
if (res.success) {
|
|
224
|
+
out.storeMaxTotalBytes = n;
|
|
225
|
+
}
|
|
226
|
+
else {
|
|
227
|
+
console.warn(`dsh-better-edit: storeMaxTotalBytes "${parsed.storeMaxTotalBytes}" invalid — expected int >=0`);
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
return out;
|
|
231
|
+
}
|
|
232
|
+
catch (error) {
|
|
233
|
+
if (errCode(error) === "ENOENT")
|
|
234
|
+
return {};
|
|
235
|
+
console.warn(`dsh-better-edit: failed to read config yaml ${yamlPath}: ${error instanceof Error ? error.message : String(error)} — fallback to central`);
|
|
236
|
+
return {};
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
function envAdapter(base) {
|
|
240
|
+
const out = {};
|
|
241
|
+
const envStoreDir = process.env.DSH_BETTER_EDIT_STORE_DIR;
|
|
242
|
+
if (envStoreDir !== undefined) {
|
|
243
|
+
const trimmed = envStoreDir.trim();
|
|
244
|
+
if (trimmed.length === 0) {
|
|
245
|
+
console.warn(`dsh-better-edit: DSH_BETTER_EDIT_STORE_DIR empty — fallback to ${base.storeDir}`);
|
|
246
|
+
}
|
|
247
|
+
else {
|
|
248
|
+
const norm = normalizeStoreDir(trimmed);
|
|
249
|
+
if (norm === undefined) {
|
|
250
|
+
console.warn(`dsh-better-edit: DSH_BETTER_EDIT_STORE_DIR "${envStoreDir}" illegal/malformed — not absolute after expand, fallback to central`);
|
|
251
|
+
}
|
|
252
|
+
else {
|
|
253
|
+
out.storeDir = norm;
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
const envAuto = process.env.DSH_BETTER_EDIT_AUTO_GITIGNORE;
|
|
258
|
+
if (envAuto !== undefined) {
|
|
259
|
+
const b = parseAutoGitIgnoreRaw(envAuto);
|
|
260
|
+
if (b === undefined) {
|
|
261
|
+
console.warn(`dsh-better-edit: DSH_BETTER_EDIT_AUTO_GITIGNORE "${envAuto}" invalid — expected true|false, fallback to ${base.autoGitignore}`);
|
|
262
|
+
}
|
|
263
|
+
else {
|
|
264
|
+
out.autoGitignore = b;
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
return out;
|
|
268
|
+
}
|
|
269
|
+
// ---- public load (merged, cached) ----
|
|
270
|
+
export function loadConfig() {
|
|
271
|
+
const yamlPath = configYamlPath();
|
|
272
|
+
let mtime;
|
|
273
|
+
try {
|
|
274
|
+
mtime = statSync(yamlPath).mtimeMs;
|
|
275
|
+
}
|
|
276
|
+
catch {
|
|
277
|
+
// no yaml file — fall through to defaults/cache miss
|
|
278
|
+
}
|
|
279
|
+
const envStoreDir = process.env.DSH_BETTER_EDIT_STORE_DIR;
|
|
280
|
+
const envAuto = process.env.DSH_BETTER_EDIT_AUTO_GITIGNORE;
|
|
281
|
+
if (cachedConfig !== undefined &&
|
|
282
|
+
cachedMtimeMs === mtime &&
|
|
283
|
+
cachedYamlPath === yamlPath &&
|
|
284
|
+
cachedEnvStoreDir === envStoreDir &&
|
|
285
|
+
cachedEnvAutoGitignore === envAuto) {
|
|
286
|
+
return cachedConfig;
|
|
287
|
+
}
|
|
288
|
+
const yamlPartial = fsAdapter();
|
|
289
|
+
const envPartial = envAdapter({ ...DEFAULT_CONFIG, ...yamlPartial });
|
|
290
|
+
const merged = { ...DEFAULT_CONFIG, ...yamlPartial, ...envPartial };
|
|
291
|
+
// final Zod validation + normalization (expand abs, fallback)
|
|
292
|
+
const parsed = StoreConfigSchema.safeParse(merged);
|
|
293
|
+
const cfg = parsed.success ? parsed.data : { ...DEFAULT_CONFIG, ...yamlPartial, ...envPartial };
|
|
294
|
+
if (cfg.storeDir !== "workspace" && cfg.storeDir !== "central") {
|
|
295
|
+
const expanded = expand(cfg.storeDir);
|
|
296
|
+
if (isAbsolute(expanded))
|
|
297
|
+
cfg.storeDir = expanded;
|
|
298
|
+
else {
|
|
299
|
+
console.warn(`dsh-better-edit: storeDir "${cfg.storeDir}" illegal/malformed — fallback to central`);
|
|
300
|
+
cfg.storeDir = "central";
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
cachedConfig = cfg;
|
|
304
|
+
cachedMtimeMs = mtime;
|
|
305
|
+
cachedYamlPath = yamlPath;
|
|
306
|
+
cachedEnvStoreDir = envStoreDir;
|
|
307
|
+
cachedEnvAutoGitignore = envAuto;
|
|
308
|
+
return cfg;
|
|
309
|
+
}
|
|
310
|
+
// For tests: reset cache
|
|
311
|
+
export function _resetConfigCache() {
|
|
312
|
+
cachedConfig = undefined;
|
|
313
|
+
cachedMtimeMs = undefined;
|
|
314
|
+
cachedYamlPath = undefined;
|
|
315
|
+
cachedEnvStoreDir = undefined;
|
|
316
|
+
cachedEnvAutoGitignore = undefined;
|
|
317
|
+
}
|