@mfdaves/okf-mcp 0.9.0 → 0.12.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.
Files changed (97) hide show
  1. package/CHANGELOG.md +69 -0
  2. package/README.md +176 -19
  3. package/bin/okf-mcp.js +6 -1
  4. package/okf/okf-mcp/policies/authoring-safety.md +11 -1
  5. package/package.json +17 -5
  6. package/server.json +2 -2
  7. package/src/assets.js +165 -73
  8. package/src/authoring/candidates.js +391 -0
  9. package/src/authoring/git-preflight.js +225 -0
  10. package/src/authoring/git-publish.js +776 -0
  11. package/src/authoring/live.js +789 -0
  12. package/src/authoring/paths.js +112 -0
  13. package/src/authoring/policy-hook.js +221 -0
  14. package/src/authoring/proposal-policy.js +137 -0
  15. package/src/authoring/receipts.js +329 -0
  16. package/src/authoring/render.js +38 -0
  17. package/src/authoring/shared.js +75 -0
  18. package/src/authoring/staging.js +216 -0
  19. package/src/authoring.js +386 -287
  20. package/src/cache/files.js +147 -0
  21. package/src/cache/lock.js +201 -0
  22. package/src/cache/paths.js +197 -0
  23. package/src/cache/store.js +703 -0
  24. package/src/catalog-text.js +19 -0
  25. package/src/cli.js +184 -151
  26. package/src/computation.js +99 -61
  27. package/src/context/assemble.js +567 -0
  28. package/src/context/cli-options.js +88 -0
  29. package/src/context/score.js +234 -0
  30. package/src/context/sections.js +274 -0
  31. package/src/embed/interface.js +160 -0
  32. package/src/embed/openai.js +715 -0
  33. package/src/embed/prepare.js +182 -0
  34. package/src/embed/units.js +96 -0
  35. package/src/git-source.js +112 -52
  36. package/src/graph.js +95 -37
  37. package/src/http-server.js +36 -17
  38. package/src/index.js +15 -0
  39. package/src/indexer/assemble.js +566 -0
  40. package/src/indexer/build.js +290 -0
  41. package/src/indexer/cache.js +81 -0
  42. package/src/indexer/edges.js +430 -0
  43. package/src/indexer/index.js +44 -0
  44. package/src/indexer/paths.js +178 -0
  45. package/src/indexer/resolve.js +282 -0
  46. package/src/indexer/update.js +720 -0
  47. package/src/indexer.js +3 -1068
  48. package/src/live-authoring.js +4 -2329
  49. package/src/markdown.js +21 -16
  50. package/src/mcp/registry.js +328 -0
  51. package/src/mcp/resources.js +45 -0
  52. package/src/mcp/server.js +472 -0
  53. package/src/mcp/tools/catalog.js +244 -0
  54. package/src/mcp/tools/computation.js +83 -0
  55. package/src/mcp/tools/context.js +133 -0
  56. package/src/mcp/tools/graph.js +167 -0
  57. package/src/mcp/tools/live-authoring.js +316 -0
  58. package/src/mcp/tools/migration.js +86 -0
  59. package/src/mcp/tools/producers.js +79 -0
  60. package/src/mcp/tools/proposals.js +213 -0
  61. package/src/mcp/tools/provenance.js +87 -0
  62. package/src/mcp/tools/remote.js +79 -0
  63. package/src/mcp/tools/search.js +242 -0
  64. package/src/mcp-server.js +3 -1611
  65. package/src/migration.js +431 -253
  66. package/src/parser.js +245 -130
  67. package/src/plugins.js +71 -48
  68. package/src/policy/write-policy.js +713 -0
  69. package/src/producer-publisher.js +195 -77
  70. package/src/producers.js +265 -101
  71. package/src/project.js +277 -93
  72. package/src/remote.js +96 -61
  73. package/src/search/cli-options.js +107 -0
  74. package/src/search/confidence.js +61 -0
  75. package/src/search/dense.js +304 -0
  76. package/src/search/embedding-cli.js +57 -0
  77. package/src/search/embedding-config.js +217 -0
  78. package/src/search/fusion.js +249 -0
  79. package/src/search/hybrid.js +526 -0
  80. package/src/search/languages.js +200 -0
  81. package/src/search/lexical.js +695 -0
  82. package/src/search/query.js +620 -0
  83. package/src/search/stem/among.js +43 -0
  84. package/src/search/stem/base-stemmer.js +311 -0
  85. package/src/search/stem/en-regions.js +456 -0
  86. package/src/search/stem/en-suffixes.js +664 -0
  87. package/src/search/stem/en-tables.js +176 -0
  88. package/src/search/stem/en.js +238 -0
  89. package/src/search/stem/it-regions.js +459 -0
  90. package/src/search/stem/it-suffixes.js +471 -0
  91. package/src/search/stem/it-tables.js +257 -0
  92. package/src/search/stem/it.js +155 -0
  93. package/src/search-index.js +2 -81
  94. package/src/search.js +2 -252
  95. package/src/store.js +134 -81
  96. package/src/v02.js +301 -105
  97. package/src/validation.js +24 -20
@@ -0,0 +1,147 @@
1
+ "use strict";
2
+
3
+ // File primitives for the vector cache (S-1). Every file is opened through a
4
+ // descriptor that never follows a symbolic link and is checked with fstat, so
5
+ // a link swapped in between two steps fails closed. Node has no openat, so
6
+ // the directory is re-verified by the caller before each group of operations;
7
+ // that narrows the window on every platform and cannot close it entirely.
8
+
9
+ const crypto = require("node:crypto");
10
+ const fs = require("node:fs");
11
+ const path = require("node:path");
12
+
13
+ // Both are absent on Windows, where lstat before open remains the only guard
14
+ // and directory fsync is unsupported.
15
+ const O_NOFOLLOW = fs.constants.O_NOFOLLOW || 0;
16
+ const O_DIRECTORY = fs.constants.O_DIRECTORY || 0;
17
+
18
+ function writeAll(fd, content) {
19
+ let offset = 0;
20
+ while (offset < content.length) {
21
+ offset += fs.writeSync(fd, content, offset, content.length - offset);
22
+ }
23
+ }
24
+
25
+ // Errors that mean "this platform or filesystem does not sync directories";
26
+ // anything else (EIO, ENOSPC, ...) is a real failure and propagates.
27
+ const UNSUPPORTED_DIRECTORY_SYNC = new Set([
28
+ "EINVAL",
29
+ "ENOTSUP",
30
+ "EOPNOTSUPP",
31
+ "EPERM",
32
+ "EISDIR",
33
+ "EBADF",
34
+ ]);
35
+
36
+ // Makes a rename durable: the directory entry is flushed where the platform
37
+ // allows it. options.fsync exists for tests.
38
+ function syncDirectory(dir, options) {
39
+ if (!O_DIRECTORY) return;
40
+ const fsyncImpl = options?.fsync || fs.fsyncSync;
41
+ let fd = null;
42
+ try {
43
+ fd = fs.openSync(dir, fs.constants.O_RDONLY | O_DIRECTORY | O_NOFOLLOW);
44
+ fsyncImpl(fd);
45
+ } catch (error) {
46
+ if (!UNSUPPORTED_DIRECTORY_SYNC.has(error?.code)) throw error;
47
+ } finally {
48
+ if (fd !== null) fs.closeSync(fd);
49
+ }
50
+ }
51
+
52
+ // Creates a file without following links, writes and syncs it, then renames
53
+ // it over the target (rename replaces a link without following it) and syncs
54
+ // the directory entry. options.verify (the store's location check) runs
55
+ // immediately before the rename and before the temporary file is cleaned up;
56
+ // when it fails, nothing is renamed and the temporary file is left where it
57
+ // was written, for garbage collection by age, instead of being unlinked by a
58
+ // path that may now lead somewhere else.
59
+ function writeAtomic(target, content, options) {
60
+ const verify = options?.verify || (() => {});
61
+ const temporary = `${target}.${process.pid}.${crypto.randomBytes(6).toString("hex")}.tmp`;
62
+ let fd = null;
63
+ let renamed = false;
64
+ try {
65
+ fd = fs.openSync(
66
+ temporary,
67
+ fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL | O_NOFOLLOW,
68
+ 0o600,
69
+ );
70
+ writeAll(fd, content);
71
+ fs.fsyncSync(fd);
72
+ fs.closeSync(fd);
73
+ fd = null;
74
+ verify();
75
+ fs.renameSync(temporary, target);
76
+ renamed = true;
77
+ syncDirectory(path.dirname(target));
78
+ } finally {
79
+ if (fd !== null) fs.closeSync(fd);
80
+ if (!renamed) removeTemporary(temporary, verify);
81
+ }
82
+ }
83
+
84
+ // Best effort: never masks the error that made the write fail.
85
+ function removeTemporary(temporary, verify) {
86
+ try {
87
+ verify();
88
+ fs.unlinkSync(temporary);
89
+ } catch {
90
+ // Left in place; collected by age.
91
+ }
92
+ }
93
+
94
+ // Creates a file that must not exist yet, through a descriptor that never
95
+ // follows a link. Returns false when it already exists.
96
+ function createExclusive(target, content) {
97
+ let fd = null;
98
+ try {
99
+ fd = fs.openSync(
100
+ target,
101
+ fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL | O_NOFOLLOW,
102
+ 0o600,
103
+ );
104
+ writeAll(fd, content);
105
+ return true;
106
+ } catch (error) {
107
+ if (error?.code === "EEXIST") return false;
108
+ throw error;
109
+ } finally {
110
+ if (fd !== null) fs.closeSync(fd);
111
+ }
112
+ }
113
+
114
+ // Returns the bytes of a regular file, or null when it is missing or is
115
+ // anything other than a regular file.
116
+ function readRegularFile(target) {
117
+ let fd;
118
+ try {
119
+ if (fs.lstatSync(target).isSymbolicLink()) return null;
120
+ fd = fs.openSync(target, fs.constants.O_RDONLY | O_NOFOLLOW);
121
+ } catch {
122
+ return null;
123
+ }
124
+ try {
125
+ if (!fs.fstatSync(fd).isFile()) return null;
126
+ return fs.readFileSync(fd);
127
+ } finally {
128
+ fs.closeSync(fd);
129
+ }
130
+ }
131
+
132
+ function mtimeBefore(target, cutoff) {
133
+ try {
134
+ return fs.lstatSync(target).mtimeMs < cutoff;
135
+ } catch {
136
+ return false;
137
+ }
138
+ }
139
+
140
+ module.exports = {
141
+ createExclusive,
142
+ mtimeBefore,
143
+ readRegularFile,
144
+ syncDirectory,
145
+ writeAll,
146
+ writeAtomic,
147
+ };
@@ -0,0 +1,201 @@
1
+ "use strict";
2
+
3
+ // Advisory write lock of a cache directory: one writer at a time.
4
+ //
5
+ // `lock` is created with O_EXCL and holds { token, pid, createdAt, generation }
6
+ // where token = pid plus random bytes, unique per write. A live lock is
7
+ // polled asynchronously until waitMs has passed, then the writer fails with
8
+ // cache_locked. A lock older than staleMs belongs to a writer that crashed:
9
+ // it is reclaimed by renaming it to lock.stale.<token>, which only one
10
+ // reclaimer can win. The parked file is then read back: only when it still
11
+ // carries the token that was observed stale, and is still stale, is it
12
+ // removed; a fresh lock that slipped into the slot between the staleness
13
+ // read and the rename is put back with link(parked, lock) and the slot is
14
+ // treated as busy. Release works the same way: it renames `lock` to
15
+ // lock.release.<token> first, then reads the renamed file; it unlinks it only
16
+ // when it carries the releaser's token and otherwise puts the successor's
17
+ // lock back with link(). No pathname is ever unlinked on the strength of an
18
+ // earlier read, so a successor's lock survives a late release.
19
+ //
20
+ // Residual windows, documented rather than closed: a crashed writer blocks
21
+ // other writers for up to staleMs; a write that outlasts staleMs can lose
22
+ // its lock to a reclaimer; when a third writer creates `lock` between a
23
+ // mistaken park and the restoring link, the displaced fresh owner finishes
24
+ // its write without the lock while its parked copy waits for collection;
25
+ // and a late release that parks a successor's lock leaves the slot empty
26
+ // until the restoring link, so a writer that creates `lock` in that gap
27
+ // wins it, the successor finishes without the lock, and its copy under
28
+ // lock.release.<token> waits for collection. The deadline always ends in
29
+ // cache_locked, a failed or undone reclaim included.
30
+
31
+ const crypto = require("node:crypto");
32
+ const fs = require("node:fs");
33
+ const path = require("node:path");
34
+
35
+ const { readRegularFile } = require("./files");
36
+ const { VectorCacheError } = require("./paths");
37
+
38
+ const LOCK_FILE = "lock";
39
+ const LOCK_POLL_MS = 25;
40
+ // Names a lock is moved to by a reclaim or a release; leftovers are
41
+ // collected by age.
42
+ const LOCK_PARKED_PREFIXES = [`${LOCK_FILE}.stale.`, `${LOCK_FILE}.release.`];
43
+ const GENERATION_PATTERN = /^[0-9a-z]{1,16}-[0-9a-f]{8}$/;
44
+
45
+ function newLockToken() {
46
+ return `${process.pid}-${crypto.randomBytes(8).toString("hex")}`;
47
+ }
48
+
49
+ function sleep(ms) {
50
+ // Referenced on purpose: a process waiting for the lock must stay alive.
51
+ return new Promise((resolve) => setTimeout(resolve, ms));
52
+ }
53
+
54
+ // Reads a lock file; returns { token, pid, generation, ageMs } or null when
55
+ // absent. An unreadable or unparsable lock is aged by its mtime.
56
+ function readLock(lockPath) {
57
+ let stat;
58
+ try {
59
+ stat = fs.lstatSync(lockPath);
60
+ } catch {
61
+ return null;
62
+ }
63
+ let parsed = null;
64
+ const bytes = stat.isFile() ? readRegularFile(lockPath) : null;
65
+ if (bytes) {
66
+ try {
67
+ parsed = JSON.parse(bytes.toString("utf8"));
68
+ } catch {
69
+ parsed = null;
70
+ }
71
+ }
72
+ const createdAt =
73
+ parsed && typeof parsed.createdAt === "string" ? Date.parse(parsed.createdAt) : Number.NaN;
74
+ const since = Number.isFinite(createdAt) ? createdAt : stat.mtimeMs;
75
+ return {
76
+ token: parsed && typeof parsed.token === "string" ? parsed.token : null,
77
+ pid: parsed && Number.isSafeInteger(parsed.pid) ? parsed.pid : null,
78
+ generation:
79
+ parsed && typeof parsed.generation === "string" && GENERATION_PATTERN.test(parsed.generation)
80
+ ? parsed.generation
81
+ : null,
82
+ ageMs: Math.max(0, Date.now() - since),
83
+ };
84
+ }
85
+
86
+ // Puts a mistakenly parked fresh lock back, after a reclaim or a release.
87
+ // link() refuses when the slot has been taken meanwhile (EEXIST); then the
88
+ // parked copy stays for collection and its owner's release finds no token of
89
+ // its own and puts back whatever it moved.
90
+ function restoreParkedLock(lockPath, parked, io) {
91
+ try {
92
+ io.link(parked, lockPath);
93
+ } catch (error) {
94
+ if (error?.code === "EEXIST") return;
95
+ try {
96
+ if (!fs.existsSync(lockPath)) io.rename(parked, lockPath);
97
+ } catch {
98
+ // Left parked; collected by age.
99
+ }
100
+ return;
101
+ }
102
+ try {
103
+ io.remove(parked);
104
+ } catch {
105
+ // Left parked; collected by age.
106
+ }
107
+ }
108
+
109
+ // Parks the lock under a name only this reclaimer uses (the rename is the
110
+ // arbitration), then checks that what was parked is the stale lock that was
111
+ // observed. Returns true only when a stale lock was removed.
112
+ function reclaimStaleLock(lockPath, observed, token, staleMs, io) {
113
+ const parked = `${lockPath}.stale.${token}`;
114
+ try {
115
+ io.rename(lockPath, parked);
116
+ } catch {
117
+ return false;
118
+ }
119
+ const moved = readLock(parked);
120
+ if (moved && moved.token === observed.token && moved.ageMs > staleMs) {
121
+ try {
122
+ io.remove(parked);
123
+ } catch {
124
+ // Left behind for garbage collection.
125
+ }
126
+ return true;
127
+ }
128
+ restoreParkedLock(lockPath, parked, io);
129
+ return false;
130
+ }
131
+
132
+ // io: { create(target, content), rename(from, to), remove(target),
133
+ // link(from, to) }. The store's io verifies the directory inside every
134
+ // operation, the O_EXCL creation of each attempt included, so a directory
135
+ // swapped while waiting fails the wait (invalid_cache_dir) instead of placing
136
+ // the lock, and later the files, somewhere else.
137
+ async function acquireLock(dir, options) {
138
+ const { token, generation, waitMs, staleMs, io } = options;
139
+ const lockPath = path.join(dir, LOCK_FILE);
140
+ const deadline = Date.now() + waitMs;
141
+ for (;;) {
142
+ let created;
143
+ try {
144
+ const claim = { token, pid: process.pid, createdAt: new Date().toISOString(), generation };
145
+ created = io.create(lockPath, Buffer.from(JSON.stringify(claim)));
146
+ } catch (error) {
147
+ if (error instanceof VectorCacheError) throw error;
148
+ throw new VectorCacheError(
149
+ "The vector cache could not be locked for writing.",
150
+ "cache_write_failed",
151
+ { cause: typeof error?.code === "string" ? error.code : "unknown" },
152
+ );
153
+ }
154
+ if (created) return lockPath;
155
+ const holder = readLock(lockPath);
156
+ if (holder && holder.ageMs > staleMs) reclaimStaleLock(lockPath, holder, token, staleMs, io);
157
+ if (Date.now() >= deadline) {
158
+ throw new VectorCacheError(
159
+ "The vector cache is being written by another process.",
160
+ "cache_locked",
161
+ { pid: holder ? holder.pid : null, ageMs: holder ? holder.ageMs : null },
162
+ );
163
+ }
164
+ await sleep(LOCK_POLL_MS);
165
+ }
166
+ }
167
+
168
+ // Moves the lock aside under a name only this writer uses, then decides on
169
+ // what was moved: this writer's lock is unlinked, anyone else's is put back.
170
+ // Returns true only when this writer's lock was removed.
171
+ function releaseLock(lockPath, token, io) {
172
+ const released = `${lockPath}.release.${token}`;
173
+ try {
174
+ io.rename(lockPath, released);
175
+ } catch {
176
+ return false;
177
+ }
178
+ const moved = readLock(released);
179
+ if (!moved || moved.token !== token) {
180
+ restoreParkedLock(lockPath, released, io);
181
+ return false;
182
+ }
183
+ try {
184
+ io.remove(released);
185
+ return true;
186
+ } catch {
187
+ // Left behind for garbage collection.
188
+ return false;
189
+ }
190
+ }
191
+
192
+ module.exports = {
193
+ GENERATION_PATTERN,
194
+ LOCK_FILE,
195
+ LOCK_PARKED_PREFIXES,
196
+ LOCK_POLL_MS,
197
+ acquireLock,
198
+ newLockToken,
199
+ readLock,
200
+ releaseLock,
201
+ };
@@ -0,0 +1,197 @@
1
+ "use strict";
2
+
3
+ // Where the vector cache may live (docs/plan-1.0.md R-9, B-5, S-1).
4
+ //
5
+ // The directory is an absolute path without parent segments or reserved
6
+ // device names, never the filesystem root, and never inside the bundle root:
7
+ // an untracked file in the worktree blocks git-backed apply. Containment is
8
+ // judged on real paths, so a cache home that is a link into the root is
9
+ // caught. The directory itself must not be a symbolic link; its ancestors
10
+ // may be (a relocated ~/.cache is common) and are resolved first.
11
+
12
+ const crypto = require("node:crypto");
13
+ const fs = require("node:fs");
14
+ const os = require("node:os");
15
+ const path = require("node:path");
16
+
17
+ const WINDOWS_RESERVED = /^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\..*)?$/i;
18
+
19
+ class VectorCacheError extends Error {
20
+ constructor(message, code, details) {
21
+ super(message);
22
+ this.name = "VectorCacheError";
23
+ this.code = code;
24
+ if (details !== undefined) this.details = details;
25
+ }
26
+ }
27
+
28
+ // Segment-aware containment: "..cache" is inside, ".." and "../x" are not.
29
+ function isInside(root, target, platformPath) {
30
+ const relative = platformPath.relative(root, target);
31
+ if (relative === "") return true;
32
+ if (platformPath.isAbsolute(relative)) return false;
33
+ return relative !== ".." && !relative.startsWith(`..${platformPath.sep}`);
34
+ }
35
+
36
+ function hasUnsafeSegment(value) {
37
+ return String(value)
38
+ .split(/[\\/]+/)
39
+ .some((segment) => segment === ".." || WINDOWS_RESERVED.test(segment));
40
+ }
41
+
42
+ // The same rules bundle paths follow (S-1): a string without control
43
+ // characters, absolute once resolved, no parent segments, no reserved device
44
+ // names, and never the filesystem root itself.
45
+ function assertSafeCachePath(candidate, platformPath) {
46
+ if (typeof candidate !== "string" || !candidate.trim() || /\p{Cc}/u.test(candidate)) {
47
+ throw new VectorCacheError("Cache directory must be a safe path.", "invalid_cache_dir");
48
+ }
49
+ if (!platformPath.isAbsolute(candidate) || hasUnsafeSegment(candidate)) {
50
+ throw new VectorCacheError(
51
+ "Cache directory must be an absolute path without parent segments.",
52
+ "invalid_cache_dir",
53
+ );
54
+ }
55
+ const resolved = platformPath.resolve(candidate);
56
+ if (platformPath.parse(resolved).root === resolved) {
57
+ throw new VectorCacheError(
58
+ "Cache directory must not be the filesystem root.",
59
+ "invalid_cache_dir",
60
+ );
61
+ }
62
+ return resolved;
63
+ }
64
+
65
+ function realpathOrResolve(target) {
66
+ try {
67
+ return fs.realpathSync(target);
68
+ } catch {
69
+ return path.resolve(target);
70
+ }
71
+ }
72
+
73
+ // Real path of the deepest existing ancestor joined with the missing tail, so
74
+ // containment is judged on real locations before the directory exists.
75
+ function realpathOfExistingAncestors(target) {
76
+ const missing = [];
77
+ let current = target;
78
+ for (;;) {
79
+ try {
80
+ const real = fs.realpathSync(current);
81
+ return missing.length ? path.join(real, ...missing) : real;
82
+ } catch {
83
+ const parent = path.dirname(current);
84
+ if (parent === current) return target;
85
+ missing.unshift(path.basename(current));
86
+ current = parent;
87
+ }
88
+ }
89
+ }
90
+
91
+ // The cache directory itself is never a symbolic link (its ancestors may be).
92
+ function assertNotSymlink(dir) {
93
+ let stat;
94
+ try {
95
+ stat = fs.lstatSync(dir);
96
+ } catch {
97
+ return;
98
+ }
99
+ if (stat.isSymbolicLink()) {
100
+ throw new VectorCacheError("Cache directory must not be a symbolic link.", "invalid_cache_dir");
101
+ }
102
+ }
103
+
104
+ // Resolves the directory the way the store will use it: ancestors through
105
+ // their real paths, the directory itself checked not to be a link.
106
+ function realCacheDir(dir) {
107
+ assertNotSymlink(dir);
108
+ return path.join(realpathOfExistingAncestors(path.dirname(dir)), path.basename(dir));
109
+ }
110
+
111
+ function defaultCacheBase(env, platform, homedir, platformPath) {
112
+ const xdg = env.XDG_CACHE_HOME;
113
+ if (typeof xdg === "string" && xdg.trim() && platformPath.isAbsolute(xdg)) {
114
+ return platformPath.resolve(xdg);
115
+ }
116
+ const home = typeof homedir === "function" ? homedir() : homedir;
117
+ if (platform === "win32") {
118
+ const local = env.LOCALAPPDATA;
119
+ if (typeof local === "string" && local.trim() && platformPath.isAbsolute(local)) {
120
+ return platformPath.resolve(local);
121
+ }
122
+ if (home) return platformPath.join(home, "AppData", "Local");
123
+ } else if (home) {
124
+ return platformPath.join(home, ".cache");
125
+ }
126
+ throw new VectorCacheError(
127
+ "No cache location is available; set cacheDir explicitly.",
128
+ "cache_location_unavailable",
129
+ );
130
+ }
131
+
132
+ // Explicit cacheDir (relative to root) wins; otherwise
133
+ // $XDG_CACHE_HOME/okf-mcp/<sha256(realpath root)>/, falling back to
134
+ // ~/.cache on POSIX and %LOCALAPPDATA% on Windows. Either location is
135
+ // refused inside the root (R-9, B-5) unless the caller passes
136
+ // allowInsideRoot: true for an explicit cacheDir and takes responsibility
137
+ // for ignoring it in Git. `env`, `platform` and `homedir` exist for tests.
138
+ function resolveCacheDir(options) {
139
+ const config = options || {};
140
+ const platform = config.platform || process.platform;
141
+ const platformPath = platform === "win32" ? path.win32 : path.posix;
142
+ const hostPlatform = platform === process.platform;
143
+ const env = config.env || process.env;
144
+ const homedir = config.homedir || os.homedir;
145
+ const hasRoot = typeof config.root === "string" && config.root.trim() !== "";
146
+ const realRoot = hasRoot ? realpathOrResolve(config.root) : null;
147
+ const realDirOf = (dir) => (hostPlatform ? realCacheDir(dir) : dir);
148
+ if (config.cacheDir !== undefined && config.cacheDir !== null) {
149
+ const cacheDir = config.cacheDir;
150
+ if (
151
+ typeof cacheDir !== "string" ||
152
+ !cacheDir.trim() ||
153
+ /\p{Cc}/u.test(cacheDir) ||
154
+ hasUnsafeSegment(cacheDir)
155
+ ) {
156
+ throw new VectorCacheError("Cache directory must be a safe path.", "invalid_cache_dir");
157
+ }
158
+ const base = hasRoot ? platformPath.resolve(config.root) : process.cwd();
159
+ const dir = realDirOf(assertSafeCachePath(platformPath.resolve(base, cacheDir), platformPath));
160
+ if (realRoot && config.allowInsideRoot !== true && isInside(realRoot, dir, platformPath)) {
161
+ throw new VectorCacheError(
162
+ "The configured cacheDir falls inside the root, where it would dirty the worktree; move it or pass allowInsideRoot.",
163
+ "cache_inside_root",
164
+ );
165
+ }
166
+ return dir;
167
+ }
168
+ if (!hasRoot) {
169
+ throw new VectorCacheError(
170
+ "A bundle or project root is required to derive the cache location.",
171
+ "cache_root_required",
172
+ );
173
+ }
174
+ const base = defaultCacheBase(env, platform, homedir, platformPath);
175
+ const digest = crypto.createHash("sha256").update(realRoot, "utf8").digest("hex");
176
+ const dir = realDirOf(
177
+ assertSafeCachePath(platformPath.join(base, "okf-mcp", digest), platformPath),
178
+ );
179
+ if (isInside(realRoot, dir, platformPath)) {
180
+ throw new VectorCacheError(
181
+ "The default cache location falls inside the bundle root; set cacheDir explicitly.",
182
+ "cache_inside_root",
183
+ );
184
+ }
185
+ return dir;
186
+ }
187
+
188
+ module.exports = {
189
+ VectorCacheError,
190
+ assertNotSymlink,
191
+ assertSafeCachePath,
192
+ isInside,
193
+ realCacheDir,
194
+ realpathOfExistingAncestors,
195
+ realpathOrResolve,
196
+ resolveCacheDir,
197
+ };