@phren/cli 0.3.26 → 0.3.28

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.
@@ -146,6 +146,30 @@ async function recentRollouts(now) {
146
146
  return files.slice(0, MAX_ROLLOUTS);
147
147
  }
148
148
  let rollouts;
149
+ /** Launcher wrappers may have the same command as their native server child.
150
+ * Count the server once, and keep the shared managed daemon ahead of private
151
+ * per-pane servers when the bounded probe is full. */
152
+ function daemonPids(rows) {
153
+ const byPid = new Map(rows.map(row => [row.pid, row]));
154
+ const servers = rows.filter(row => isCodexDaemon(row.command));
155
+ const serverIds = new Set(servers.map(row => row.pid));
156
+ const wrappers = new Set();
157
+ for (const server of servers) {
158
+ let parent = server.ppid;
159
+ for (let depth = 0; depth < 8 && parent > 1; depth++) {
160
+ if (serverIds.has(parent))
161
+ wrappers.add(parent);
162
+ const ancestor = byPid.get(parent);
163
+ if (!ancestor || ancestor.ppid === parent)
164
+ break;
165
+ parent = ancestor.ppid;
166
+ }
167
+ }
168
+ const managed = (row) => /(?:^|\s)--managed-daemon(?:\s|$)/.test(row.command) ? 1 : 0;
169
+ return servers.filter(row => !wrappers.has(row.pid))
170
+ .sort((a, b) => managed(b) - managed(a) || a.startedAt - b.startedAt || a.pid - b.pid)
171
+ .slice(0, MAX_DAEMONS).map(row => row.pid);
172
+ }
149
173
  /**
150
174
  * The conversations a running Codex daemon holds open (by `openFiles`, the
151
175
  * caller's lsof or /proc read), else, when it holds none, the recent rollouts
@@ -156,7 +180,7 @@ export function daemonRollouts(openFiles, now = Date.now()) {
156
180
  if (rollouts && now - rollouts.at < CACHE_MS)
157
181
  return rollouts.value;
158
182
  const value = (async () => {
159
- const daemons = (await processTable(now)).filter(row => isCodexDaemon(row.command)).map(row => row.pid).slice(0, MAX_DAEMONS);
183
+ const daemons = daemonPids(await processTable(now));
160
184
  if (!daemons.length)
161
185
  return [];
162
186
  countIdentity("codex-daemon");
@@ -25352,7 +25352,7 @@ var init_package_metadata = __esm({
25352
25352
  __dirname = path15.dirname(fileURLToPath2(import.meta.url));
25353
25353
  ROOT = path15.join(__dirname, "..");
25354
25354
  PACKAGE_JSON_PATH = path15.join(ROOT, "package.json");
25355
- BUNDLED_VERSION = true ? "0.3.26" : "0.0.0";
25355
+ BUNDLED_VERSION = true ? "0.3.28" : "0.0.0";
25356
25356
  PACKAGE_JSON = readPackageJson();
25357
25357
  PACKAGE_NAME = PACKAGE_JSON.name || "phren";
25358
25358
  VERSION = PACKAGE_JSON.version || BUNDLED_VERSION;
@@ -29562,10 +29562,27 @@ async function recentRollouts(now) {
29562
29562
  }
29563
29563
  return files.slice(0, MAX_ROLLOUTS);
29564
29564
  }
29565
+ function daemonPids(rows) {
29566
+ const byPid = new Map(rows.map((row) => [row.pid, row]));
29567
+ const servers2 = rows.filter((row) => isCodexDaemon(row.command));
29568
+ const serverIds = new Set(servers2.map((row) => row.pid));
29569
+ const wrappers = /* @__PURE__ */ new Set();
29570
+ for (const server of servers2) {
29571
+ let parent = server.ppid;
29572
+ for (let depth = 0; depth < 8 && parent > 1; depth++) {
29573
+ if (serverIds.has(parent)) wrappers.add(parent);
29574
+ const ancestor = byPid.get(parent);
29575
+ if (!ancestor || ancestor.ppid === parent) break;
29576
+ parent = ancestor.ppid;
29577
+ }
29578
+ }
29579
+ const managed = (row) => /(?:^|\s)--managed-daemon(?:\s|$)/.test(row.command) ? 1 : 0;
29580
+ return servers2.filter((row) => !wrappers.has(row.pid)).sort((a, b) => managed(b) - managed(a) || a.startedAt - b.startedAt || a.pid - b.pid).slice(0, MAX_DAEMONS).map((row) => row.pid);
29581
+ }
29565
29582
  function daemonRollouts(openFiles, now = Date.now()) {
29566
29583
  if (rollouts && now - rollouts.at < CACHE_MS) return rollouts.value;
29567
29584
  const value2 = (async () => {
29568
- const daemons = (await processTable(now)).filter((row) => isCodexDaemon(row.command)).map((row) => row.pid).slice(0, MAX_DAEMONS);
29585
+ const daemons = daemonPids(await processTable(now));
29569
29586
  if (!daemons.length) return [];
29570
29587
  countIdentity("codex-daemon");
29571
29588
  const held = (await openFiles(daemons).catch(() => [])).filter((file3) => ROLLOUT.test(file3)).slice(0, MAX_ROLLOUTS);
@@ -61130,7 +61147,7 @@ async function readSecret(prompt) {
61130
61147
  // src/bridge/hook-main.ts
61131
61148
  init_utils_helpers();
61132
61149
  Object.assign(process.env, nonInteractiveGitEnv());
61133
- runBridge(process.argv.slice(2), "0.3.26").then((code) => {
61150
+ runBridge(process.argv.slice(2), "0.3.28").then((code) => {
61134
61151
  process.exitCode = code;
61135
61152
  }).catch((error62) => {
61136
61153
  console.error(error62 instanceof Error ? error62.message : "Phren Hook failed.");
package/dist/index.js CHANGED
@@ -78,7 +78,7 @@ async function main() {
78
78
  // Lazy-load the MCP-server-only module graph. Only the long-lived MCP server
79
79
  // reaches main(), so paying the import cost here — not at module scope — keeps
80
80
  // every hook subprocess fast (hook-prompt, hook-tool, --version never get here).
81
- const [{ McpServer }, { StdioServerTransport }, { buildIndex, flushEmbeddingQueue, updateFileInIndex: updateFileInIndexFn }, { runCustomHooks }, { mcpResponse }, { startEmbeddingWarmup }, { resolveRuntimeProfile }, { VERSION: PACKAGE_VERSION },] = await Promise.all([
81
+ const [{ McpServer }, { StdioServerTransport }, { buildIndex, captureIndexInputs, flushEmbeddingQueue, updateFileInIndex: updateFileInIndexFn }, { runCustomHooks }, { mcpResponse }, { startEmbeddingWarmup }, { resolveRuntimeProfile }, { VERSION: PACKAGE_VERSION },] = await Promise.all([
82
82
  import("@modelcontextprotocol/sdk/server/mcp.js"),
83
83
  import("@modelcontextprotocol/sdk/server/stdio.js"),
84
84
  import("./shared/index.js"),
@@ -88,7 +88,7 @@ async function main() {
88
88
  import("./runtime-profile.js"),
89
89
  import("./package-metadata.js"),
90
90
  ]);
91
- const profile = resolveRuntimeProfile(phrenPath);
91
+ let profile = resolveRuntimeProfile(phrenPath);
92
92
  const { activateModules: moduleSnapshot } = await import("./modules/runtime.js");
93
93
  const { BUILTIN_MODULES, toolOwner, disabledHint } = await import("./modules/registry.js");
94
94
  const { resolveAllStores } = await import("./store-registry.js");
@@ -103,6 +103,21 @@ async function main() {
103
103
  // /tmp. A 0700 root makes it unreachable to other local accounts.
104
104
  ensureFtsCacheRootPrivate();
105
105
  let db = null;
106
+ // The first call also verifies startup's possibly stale lock-contention fallback.
107
+ let localInputs;
108
+ const { localIndexRefresh, indexReaders } = await import("./mcp/local-index.js");
109
+ const readers = indexReaders(() => {
110
+ if (!db)
111
+ throw new Error("Index unavailable - check phren setup");
112
+ return db;
113
+ }, (retired) => {
114
+ try {
115
+ retired.close();
116
+ }
117
+ catch (error) {
118
+ logger.warn("rebuildIndex", errorMessage(error));
119
+ }
120
+ });
106
121
  let indexReady = false;
107
122
  let shuttingDown = false;
108
123
  try {
@@ -127,18 +142,18 @@ async function main() {
127
142
  runCustomHooks(phrenPath, "pre-index");
128
143
  const oldDb = db;
129
144
  try {
130
- indexReady = false;
131
- db = await buildIndex(phrenPath, profile, { force });
145
+ const nextProfile = resolveRuntimeProfile(phrenPath);
146
+ const inputs = await captureIndexInputs(phrenPath, nextProfile);
147
+ db = await buildIndex(phrenPath, nextProfile, { force, requireFresh: true });
148
+ profile = nextProfile;
149
+ localInputs = inputs;
132
150
  indexReady = true;
133
151
  // buildIndex() hands back its cached handle inside the debounce
134
152
  // window, so oldDb can be the very database we just installed.
135
- try {
136
- if (oldDb && oldDb !== db)
137
- oldDb.close();
138
- }
139
- catch (err) {
140
- logger.warn("rebuildIndex", `dbClose: ${errorMessage(err)}`);
141
- }
153
+ // An already-running search may retain its handle across an await.
154
+ // Close it once its own readers finish, even while newer calls stay busy.
155
+ if (oldDb && oldDb !== db)
156
+ readers.retire(oldDb);
142
157
  }
143
158
  catch (err) {
144
159
  // Restore old state on failure
@@ -186,6 +201,16 @@ async function main() {
186
201
  });
187
202
  return run;
188
203
  }
204
+ const runIndexExclusive = (fn) => {
205
+ const run = writeQueue.then(fn);
206
+ writeQueue = run.catch((error) => { logger.warn("index-refresh", errorMessage(error)); });
207
+ return run;
208
+ };
209
+ const localIndex = localIndexRefresh({
210
+ isFresh: () => localInputs?.() ?? false,
211
+ refresh: () => rebuildIndex(true),
212
+ runExclusive: runIndexExclusive,
213
+ });
189
214
  const server = new McpServer({
190
215
  name: "phren-mcp",
191
216
  version: PACKAGE_VERSION,
@@ -219,6 +244,13 @@ async function main() {
219
244
  }],
220
245
  };
221
246
  }
247
+ try {
248
+ await localIndex.ensureFresh();
249
+ }
250
+ catch (error) {
251
+ logger.warn("local-index", errorMessage(error));
252
+ return mcpResponse({ ok: false, error: "Could not refresh the local index; retry shortly." });
253
+ }
222
254
  if (!indexReady || !db) {
223
255
  return {
224
256
  content: [{
@@ -243,19 +275,15 @@ async function main() {
243
275
  catch (err) {
244
276
  logger.warn("trackToolCall", errorMessage(err));
245
277
  }
246
- return handler(...args);
278
+ return readers.run(() => handler(...args));
247
279
  },
248
280
  });
249
281
  server.registerTool = gate.registerTool;
250
282
  // Register all tool handlers from domain modules
251
283
  const ctx = {
252
284
  phrenPath,
253
- profile,
254
- db: () => {
255
- if (!db)
256
- throw new Error("Index unavailable - check phren setup");
257
- return db;
258
- },
285
+ get profile() { return profile; },
286
+ db: () => readers.get(),
259
287
  rebuildIndex,
260
288
  withWriteQueue,
261
289
  updateFileInIndex: (filePath) => {
@@ -304,13 +332,8 @@ async function main() {
304
332
  }
305
333
  await rebuildIndex(true);
306
334
  },
307
- runExclusive: (fn) => {
308
- // Network calls have their own timeouts. Do not release the queue while
309
- // an underlying Git operation is still running, as Promise.race would.
310
- const run = writeQueue.then(fn);
311
- writeQueue = run.catch((err) => { logger.warn("periodic-pull", errorMessage(err)); });
312
- return run;
313
- },
335
+ // No timeout races: the queue stays owned until the actual work ends.
336
+ runExclusive: runIndexExclusive,
314
337
  });
315
338
  server.server.onclose = () => { void shutdown("transport closed"); };
316
339
  // Graceful shutdown: drain write queue and close DB before exit
@@ -0,0 +1,16 @@
1
+ /** Keep only the handles each in-flight reader actually obtained. */
2
+ export declare function indexReaders<T>(current: () => T, close: (handle: T) => void): {
3
+ get(): T;
4
+ retire(handle: T): void;
5
+ run<R>(fn: () => R | Promise<R>): Promise<R>;
6
+ };
7
+ /** Coalesce local freshness checks without a timer or any remote polling. */
8
+ export declare function localIndexRefresh(options: {
9
+ isFresh: () => boolean;
10
+ refresh: () => Promise<void>;
11
+ runExclusive: (fn: () => Promise<void>) => Promise<unknown>;
12
+ now?: () => number;
13
+ intervalMs?: number;
14
+ }): {
15
+ ensureFresh: () => Promise<void>;
16
+ };
@@ -0,0 +1,79 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+ /** Keep only the handles each in-flight reader actually obtained. */
3
+ export function indexReaders(current, close) {
4
+ const calls = new AsyncLocalStorage();
5
+ const readers = new Map();
6
+ const retired = new Set();
7
+ return {
8
+ get() {
9
+ const handle = current();
10
+ const call = calls.getStore();
11
+ if (call?.active && !call.handles.has(handle)) {
12
+ call.handles.add(handle);
13
+ readers.set(handle, (readers.get(handle) ?? 0) + 1);
14
+ }
15
+ return handle;
16
+ },
17
+ retire(handle) {
18
+ if (readers.has(handle))
19
+ retired.add(handle);
20
+ else
21
+ close(handle);
22
+ },
23
+ run(fn) {
24
+ const call = { active: true, handles: new Set() };
25
+ return calls.run(call, async () => {
26
+ try {
27
+ return await fn();
28
+ }
29
+ finally {
30
+ call.active = false;
31
+ for (const handle of call.handles) {
32
+ const count = readers.get(handle) - 1;
33
+ if (count)
34
+ readers.set(handle, count);
35
+ else {
36
+ readers.delete(handle);
37
+ if (retired.delete(handle))
38
+ close(handle);
39
+ }
40
+ }
41
+ }
42
+ });
43
+ },
44
+ };
45
+ }
46
+ /** Coalesce local freshness checks without a timer or any remote polling. */
47
+ export function localIndexRefresh(options) {
48
+ const now = options.now ?? Date.now;
49
+ const interval = options.intervalMs ?? 1000;
50
+ let checkedAt = -Infinity;
51
+ let pending;
52
+ let failure;
53
+ return {
54
+ async ensureFresh() {
55
+ if (pending)
56
+ return pending;
57
+ if (now() - checkedAt < interval) {
58
+ if (failure)
59
+ throw failure;
60
+ return;
61
+ }
62
+ checkedAt = now();
63
+ try {
64
+ if (options.isFresh()) {
65
+ failure = undefined;
66
+ return;
67
+ }
68
+ }
69
+ catch (error) {
70
+ failure = error;
71
+ throw error;
72
+ }
73
+ pending = options.runExclusive(options.refresh).then(() => { failure = undefined; })
74
+ .catch((error) => { failure = error; throw error; })
75
+ .finally(() => { checkedAt = now(); pending = undefined; });
76
+ return pending;
77
+ },
78
+ };
79
+ }
@@ -22,8 +22,16 @@ export declare function normalizeIndexedContent(content: string, type: string, p
22
22
  * Touches the sentinel file to invalidate caches.
23
23
  */
24
24
  export declare function updateFileInIndex(db: SqlJsDatabase, filePath: string, phrenPath: string): void;
25
+ /**
26
+ * A process-owned metadata snapshot taken BEFORE an MCP index build. Unlike
27
+ * the shared on-disk sentinel, another process cannot advance this baseline
28
+ * while this process still holds an older database. Warm checks only stat
29
+ * known paths: no glob, content reads, Git operations, or database rebuild.
30
+ */
31
+ export declare function captureIndexInputs(phrenPath: string, profile?: string): Promise<() => boolean>;
25
32
  export declare function buildIndex(phrenPath: string, profile?: string, options?: {
26
33
  force?: boolean;
34
+ requireFresh?: boolean;
27
35
  }): Promise<SqlJsDatabase>;
28
36
  /**
29
37
  * @internal Exported for tests. The prune is a one-shot per process, so a test
@@ -270,7 +270,7 @@ function computePhrenHash(phrenPath, profile, preGlobbed) {
270
270
  for (const f of preGlobbed) {
271
271
  try {
272
272
  const stat = fs.statSync(f);
273
- hash.update(`${f}:${stat.mtimeMs}:${stat.size}`);
273
+ hash.update(`${f}:${stat.mtimeMs}:${stat.ctimeMs}:${stat.size}:${stat.ino}`);
274
274
  }
275
275
  catch (err) {
276
276
  logger.debug("computePhrenHash skip", errorMessage(err));
@@ -279,7 +279,7 @@ function computePhrenHash(phrenPath, profile, preGlobbed) {
279
279
  for (const configPath of topicConfigEntries) {
280
280
  try {
281
281
  const stat = fs.statSync(configPath);
282
- hash.update(`topic-config:${configPath}:${stat.mtimeMs}:${stat.size}`);
282
+ hash.update(`topic-config:${configPath}:${stat.mtimeMs}:${stat.ctimeMs}:${stat.size}:${stat.ino}`);
283
283
  }
284
284
  catch (err) {
285
285
  logger.debug("computePhrenHash topicConfig", errorMessage(err));
@@ -320,7 +320,7 @@ function computePhrenHash(phrenPath, profile, preGlobbed) {
320
320
  for (const f of files) {
321
321
  try {
322
322
  const stat = fs.statSync(f);
323
- hash.update(`${f}:${stat.mtimeMs}:${stat.size}`);
323
+ hash.update(`${f}:${stat.mtimeMs}:${stat.ctimeMs}:${stat.size}:${stat.ino}`);
324
324
  }
325
325
  catch (err) {
326
326
  logger.debug("computePhrenHash skip", errorMessage(err));
@@ -329,7 +329,7 @@ function computePhrenHash(phrenPath, profile, preGlobbed) {
329
329
  for (const configPath of topicConfigEntries) {
330
330
  try {
331
331
  const stat = fs.statSync(configPath);
332
- hash.update(`topic-config:${configPath}:${stat.mtimeMs}:${stat.size}`);
332
+ hash.update(`topic-config:${configPath}:${stat.mtimeMs}:${stat.ctimeMs}:${stat.size}:${stat.ino}`);
333
333
  }
334
334
  catch (err) {
335
335
  logger.debug("computePhrenHash topicConfig", errorMessage(err));
@@ -339,7 +339,7 @@ function computePhrenHash(phrenPath, profile, preGlobbed) {
339
339
  for (const mem of nativeMemoryEnabled() ? collectNativeMemoryFiles() : []) {
340
340
  try {
341
341
  const stat = fs.statSync(mem.fullPath);
342
- hash.update(`native:${mem.fullPath}:${stat.mtimeMs}:${stat.size}`);
342
+ hash.update(`native:${mem.fullPath}:${stat.mtimeMs}:${stat.ctimeMs}:${stat.size}:${stat.ino}`);
343
343
  }
344
344
  catch (err) {
345
345
  logger.debug("computePhrenHash skip", errorMessage(err));
@@ -353,7 +353,7 @@ function computePhrenHash(phrenPath, profile, preGlobbed) {
353
353
  try {
354
354
  const fp = path.join(globalDir, f);
355
355
  const stat = fs.statSync(fp);
356
- hash.update(`global:${f}:${stat.mtimeMs}:${stat.size}`);
356
+ hash.update(`global:${f}:${stat.mtimeMs}:${stat.ctimeMs}:${stat.size}:${stat.ino}`);
357
357
  }
358
358
  catch (err) {
359
359
  logger.debug("computePhrenHash skip", errorMessage(err));
@@ -365,7 +365,7 @@ function computePhrenHash(phrenPath, profile, preGlobbed) {
365
365
  if (fs.existsSync(manualLinksPath)) {
366
366
  try {
367
367
  const stat = fs.statSync(manualLinksPath);
368
- hash.update(`manual-links:${stat.mtimeMs}:${stat.size}`);
368
+ hash.update(`manual-links:${stat.mtimeMs}:${stat.ctimeMs}:${stat.size}:${stat.ino}`);
369
369
  }
370
370
  catch (err) {
371
371
  logger.debug("computePhrenHash skip", errorMessage(err));
@@ -375,7 +375,7 @@ function computePhrenHash(phrenPath, profile, preGlobbed) {
375
375
  if (fs.existsSync(indexPolicyPath)) {
376
376
  try {
377
377
  const stat = fs.statSync(indexPolicyPath);
378
- hash.update(`index-policy-file:${stat.mtimeMs}:${stat.size}`);
378
+ hash.update(`index-policy-file:${stat.mtimeMs}:${stat.ctimeMs}:${stat.size}:${stat.ino}`);
379
379
  }
380
380
  catch (err) {
381
381
  logger.debug("computePhrenHash skip", errorMessage(err));
@@ -810,7 +810,7 @@ export function updateFileInIndex(db, filePath, phrenPath) {
810
810
  const hashData = loadHashMap(phrenPath);
811
811
  hashData.hashes[resolvedPath] = raw !== null ? hashContent(raw) : hashFileContent(resolvedPath);
812
812
  const stat = fs.statSync(resolvedPath);
813
- saveHashMap(phrenPath, hashData.hashes, undefined, { [resolvedPath]: { mtimeMs: stat.mtimeMs, size: stat.size } });
813
+ saveHashMap(phrenPath, hashData.hashes, undefined, { [resolvedPath]: { mtimeMs: stat.mtimeMs, ctimeMs: stat.ctimeMs, ino: stat.ino, size: stat.size } });
814
814
  }
815
815
  catch (err) {
816
816
  logger.debug("updateFileInIndex hashMap", errorMessage(err));
@@ -945,6 +945,59 @@ function snapshotContentDirs(phrenPath, projectDirs) {
945
945
  }
946
946
  return snapshot;
947
947
  }
948
+ /**
949
+ * A process-owned metadata snapshot taken BEFORE an MCP index build. Unlike
950
+ * the shared on-disk sentinel, another process cannot advance this baseline
951
+ * while this process still holds an older database. Warm checks only stat
952
+ * known paths: no glob, content reads, Git operations, or database rebuild.
953
+ */
954
+ export async function captureIndexInputs(phrenPath, profile) {
955
+ const stamp = (file) => {
956
+ try {
957
+ const stat = fs.statSync(file);
958
+ return `${stat.mtimeMs}:${stat.ctimeMs}:${stat.size}:${stat.ino}`;
959
+ }
960
+ catch (error) {
961
+ if (["ENOENT", "ENOTDIR"].includes(error.code ?? ""))
962
+ return "absent";
963
+ throw error;
964
+ }
965
+ };
966
+ await refreshStoreProjectDirs(phrenPath, profile);
967
+ const { resolveAllStores } = await import("../store-registry.js");
968
+ const projectDirs = getAllStoreProjectDirs(phrenPath, profile);
969
+ const globalDir = path.join(phrenPath, "global");
970
+ // runtimeFile may create .runtime on a new store; do that before the baseline.
971
+ const runtimeInputs = [runtimeFile(phrenPath, "attached-stores.yaml"), runtimeFile(phrenPath, "manual-links.json")];
972
+ // Directory stamps precede the glob: additions during it must stay dirty.
973
+ const inputs = new Map(collectContentDirs(phrenPath, [...projectDirs, globalDir]).map(dir => [dir, stamp(dir)]));
974
+ const paths = new Set([
975
+ ...globAllFiles(phrenPath, profile).filePaths,
976
+ // Imported global documents also contribute to indexed content.
977
+ ...globSync("**/*.md", { cwd: globalDir, nodir: true }).map(file => path.join(globalDir, file)),
978
+ ...runtimeInputs,
979
+ ]);
980
+ for (const store of resolveAllStores(phrenPath)) {
981
+ for (const file of ["", "phren.root.yaml", "stores.yaml", "machines.yaml", ".config/index-policy.json", ".config/modules.yaml"]) {
982
+ paths.add(path.join(store.path, file));
983
+ }
984
+ if (profile)
985
+ paths.add(path.join(store.path, "profiles", `${profile}.yaml`));
986
+ }
987
+ for (const dir of projectDirs) {
988
+ paths.add(path.join(dir, "topic-config.json"));
989
+ paths.add(path.join(dir, "phren.project.yaml"));
990
+ }
991
+ for (const file of paths)
992
+ if (!inputs.has(file))
993
+ inputs.set(file, stamp(file));
994
+ return () => {
995
+ for (const [file, previous] of inputs)
996
+ if (stamp(file) !== previous)
997
+ return false;
998
+ return true;
999
+ };
1000
+ }
948
1001
  function readIndexSentinel(phrenPath) {
949
1002
  try {
950
1003
  const sentinelPath = indexSentinelPath(phrenPath);
@@ -1313,7 +1366,8 @@ async function buildIndexImpl(phrenPath, profile) {
1313
1366
  const prevHash = savedHashes[entry.fullPath];
1314
1367
  const prevMeta = savedMeta[entry.fullPath];
1315
1368
  const statUnchanged = prevHash !== undefined && prevMeta !== undefined
1316
- && prevMeta.mtimeMs === stat.mtimeMs && prevMeta.size === stat.size;
1369
+ && prevMeta.mtimeMs === stat.mtimeMs && prevMeta.size === stat.size
1370
+ && prevMeta.ctimeMs === stat.ctimeMs && prevMeta.ino === stat.ino;
1317
1371
  let fileHash;
1318
1372
  if (statUnchanged) {
1319
1373
  fileHash = prevHash;
@@ -1326,7 +1380,7 @@ async function buildIndexImpl(phrenPath, profile) {
1326
1380
  contentCache.put(entry.fullPath, raw);
1327
1381
  }
1328
1382
  currentHashes[entry.fullPath] = fileHash;
1329
- currentMeta[entry.fullPath] = { mtimeMs: stat.mtimeMs, size: stat.size };
1383
+ currentMeta[entry.fullPath] = { mtimeMs: stat.mtimeMs, ctimeMs: stat.ctimeMs, ino: stat.ino, size: stat.size };
1330
1384
  if (!(entry.fullPath in savedHashes)) {
1331
1385
  newFiles.push(entry);
1332
1386
  }
@@ -1513,7 +1567,7 @@ async function buildIndexImpl(phrenPath, profile) {
1513
1567
  try {
1514
1568
  newHashes[entry.fullPath] = hashContent(raw);
1515
1569
  const stat = fs.statSync(entry.fullPath);
1516
- newMeta[entry.fullPath] = { mtimeMs: stat.mtimeMs, size: stat.size };
1570
+ newMeta[entry.fullPath] = { mtimeMs: stat.mtimeMs, ctimeMs: stat.ctimeMs, ino: stat.ino, size: stat.size };
1517
1571
  }
1518
1572
  catch (err) {
1519
1573
  logger.debug("buildIndex statFile", errorMessage(err));
@@ -1699,7 +1753,7 @@ function isDbOpen(db) {
1699
1753
  export async function buildIndex(phrenPath, profile, options = {}) {
1700
1754
  const debounceMs = getIndexDebounceMs();
1701
1755
  const buildKey = storeCacheKey(phrenPath, profile);
1702
- if (!options.force &&
1756
+ if (!options.force && !options.requireFresh &&
1703
1757
  debounceMs > 0 &&
1704
1758
  _lastBuiltDb !== null &&
1705
1759
  _lastBuildKey === buildKey &&
@@ -1708,7 +1762,7 @@ export async function buildIndex(phrenPath, profile, options = {}) {
1708
1762
  debugLog(`buildIndex debounce hit (${Date.now() - _lastBuildTimestamp}ms < ${debounceMs}ms)`);
1709
1763
  return _lastBuiltDb;
1710
1764
  }
1711
- const result = buildLock.then(() => _buildIndexGuarded(phrenPath, profile));
1765
+ const result = buildLock.then(() => _buildIndexGuarded(phrenPath, profile, options.requireFresh));
1712
1766
  // Update the lock chain; swallow rejections so the chain doesn't stall
1713
1767
  buildLock = result.catch(() => null);
1714
1768
  const db = await result;
@@ -1920,9 +1974,11 @@ export async function loadIndexForHook(phrenPath, profile) {
1920
1974
  });
1921
1975
  return loadIndexSnapshotOrEmpty(phrenPath, profile, hash);
1922
1976
  }
1923
- async function _buildIndexGuarded(phrenPath, profile) {
1977
+ async function _buildIndexGuarded(phrenPath, profile, requireFresh = false) {
1924
1978
  const lockTarget = runtimeFile(phrenPath, "index-rebuild");
1925
1979
  if (isRebuildLockHeld(phrenPath)) {
1980
+ if (requireFresh)
1981
+ throw new Error("Index rebuild is busy; retry shortly.");
1926
1982
  return loadIndexSnapshotOrEmpty(phrenPath, profile);
1927
1983
  }
1928
1984
  try {
@@ -1942,6 +1998,8 @@ async function _buildIndexGuarded(phrenPath, profile) {
1942
1998
  catch (err) {
1943
1999
  const message = errorMessage(err);
1944
2000
  if (message.includes("could not acquire lock")) {
2001
+ if (requireFresh)
2002
+ throw err;
1945
2003
  debugLog(`FTS rebuild skipped because another process holds the rebuild lock: ${message}`);
1946
2004
  return loadIndexSnapshotOrEmpty(phrenPath, profile);
1947
2005
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@phren/cli",
3
- "version": "0.3.26",
3
+ "version": "0.3.28",
4
4
  "description": "Knowledge layer for AI agents - CLI, MCP server, and data layer",
5
5
  "type": "module",
6
6
  "bin": {