@phren/cli 0.3.25 → 0.3.27

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.
@@ -20,6 +20,9 @@ export declare function processTable(now?: number): Promise<ProcessRow[]>;
20
20
  export declare function isCodexDaemon(command: string): boolean;
21
21
  /** When a pane's agent started: its oldest foreground process. */
22
22
  export declare function startedAt(rows: ProcessRow[], pids: number[]): number | undefined;
23
+ /** A direct `codex resume <id>` launch, including its shell/npm wrapper.
24
+ * This is only a hint: the command line survives later /new and /resume. */
25
+ export declare function resumedConversation(rows: ProcessRow[], pids: number[]): string | undefined;
23
26
  /** True when this process runs under a Codex app-server daemon: a hook the
24
27
  * daemon ran carries the environment of the pane that started the daemon,
25
28
  * which is not the pane of the conversation it reports. */
@@ -55,5 +58,6 @@ export declare function sameDirectory(a: unknown, b: unknown): Promise<boolean>;
55
58
  export interface CodexPaneStart {
56
59
  key: string;
57
60
  start: number;
61
+ resumed?: string;
58
62
  }
59
63
  export declare function assignDaemonConversation(here: DaemonRollout[], self: CodexPaneStart, claimed: Set<string>, rivals: CodexPaneStart[], now?: number): string | undefined;
@@ -51,6 +51,15 @@ export function startedAt(rows, pids) {
51
51
  const times = rows.filter(row => pids.includes(row.pid)).map(row => row.startedAt);
52
52
  return times.length ? Math.min(...times) : undefined;
53
53
  }
54
+ /** A direct `codex resume <id>` launch, including its shell/npm wrapper.
55
+ * This is only a hint: the command line survives later /new and /resume. */
56
+ export function resumedConversation(rows, pids) {
57
+ const ids = new Set(rows.filter(row => pids.includes(row.pid)).flatMap(row => {
58
+ const match = /^(?:(?:\S*\/)?(?:sh|bash|zsh|node)\s+)?(?:\S*\/)?codex\s+resume\s+([a-f0-9-]{36})(?:\s|$)/i.exec(row.command);
59
+ return match && sessionId.safeParse(match[1]).success ? [match[1]] : [];
60
+ }));
61
+ return ids.size === 1 ? [...ids][0] : undefined;
62
+ }
54
63
  /** True when this process runs under a Codex app-server daemon: a hook the
55
64
  * daemon ran carries the environment of the pane that started the daemon,
56
65
  * which is not the pane of the conversation it reports. */
@@ -179,7 +188,15 @@ export function assignDaemonConversation(here, self, claimed, rivals, now = Date
179
188
  if (!rivals.length) {
180
189
  const pool = after(self.start);
181
190
  const held = pool.filter(r => r.held);
182
- return (held.length ? held : pool).sort((a, b) => b.activeAt - a.activeAt)[0]?.id;
191
+ const current = (held.length ? held : pool).sort((a, b) => b.activeAt - a.activeAt)[0]?.id;
192
+ if (current)
193
+ return current;
194
+ // An explicit resume may name a conversation older than this TUI. Only
195
+ // use it when the daemon holds exactly one unclaimed conversation that
196
+ // has advanced since launch, and no other pane in this folder competes.
197
+ // A later /new above takes precedence over the stale launch arguments.
198
+ const resumed = open.filter(r => r.held && r.activeAt >= self.start && r.activeAt <= now + 60_000);
199
+ return resumed.length === 1 && resumed[0].id === self.resumed ? self.resumed : undefined;
183
200
  }
184
201
  const order = [...rivals, self].sort((a, b) => b.start - a.start || (a.key < b.key ? 1 : a.key > b.key ? -1 : 0));
185
202
  const taken = new Set();
@@ -14,7 +14,7 @@ import { tabActivityKey } from "./tab-activity.js";
14
14
  import { intervalFromEnv } from "./limits.js";
15
15
  import { countHerdr, countIdentity } from "./metrics.js";
16
16
  import { phrenStoreRoot } from "./transcripts.js";
17
- import { assignDaemonConversation, daemonRollouts, processTable, sameDirectory, startedAt } from "./codex-daemon.js";
17
+ import { assignDaemonConversation, daemonRollouts, processTable, resumedConversation, sameDirectory, startedAt } from "./codex-daemon.js";
18
18
  import { codexServers } from "./codex-servers.js";
19
19
  // terminal.ts and terminal-tmux.ts import this module, so it reaches them at
20
20
  // call time; a static import back would be an import cycle.
@@ -503,7 +503,7 @@ async function codexDaemonIdentity(server, pane, pids) {
503
503
  if (peerStart !== undefined)
504
504
  rivals.push({ key: String(peer.pane_id), start: peerStart });
505
505
  }
506
- return { sessionId: assignDaemonConversation(here, { key: String(pane.pane_id), start }, claimed, rivals), known };
506
+ return { sessionId: assignDaemonConversation(here, { key: String(pane.pane_id), start, resumed: resumedConversation(rows, pids) }, claimed, rivals), known };
507
507
  }
508
508
  /** The Codex pane that shows `session`, for a lifecycle callback that ran
509
509
  * inside a Codex daemon and so cannot name its pane. Falls back to the only
@@ -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.25" : "0.0.0";
25355
+ BUNDLED_VERSION = true ? "0.3.27" : "0.0.0";
25356
25356
  PACKAGE_JSON = readPackageJson();
25357
25357
  PACKAGE_NAME = PACKAGE_JSON.name || "phren";
25358
25358
  VERSION = PACKAGE_JSON.version || BUNDLED_VERSION;
@@ -29492,6 +29492,13 @@ function startedAt(rows, pids) {
29492
29492
  const times = rows.filter((row) => pids.includes(row.pid)).map((row) => row.startedAt);
29493
29493
  return times.length ? Math.min(...times) : void 0;
29494
29494
  }
29495
+ function resumedConversation(rows, pids) {
29496
+ const ids = new Set(rows.filter((row) => pids.includes(row.pid)).flatMap((row) => {
29497
+ const match = /^(?:(?:\S*\/)?(?:sh|bash|zsh|node)\s+)?(?:\S*\/)?codex\s+resume\s+([a-f0-9-]{36})(?:\s|$)/i.exec(row.command);
29498
+ return match && sessionId.safeParse(match[1]).success ? [match[1]] : [];
29499
+ }));
29500
+ return ids.size === 1 ? [...ids][0] : void 0;
29501
+ }
29495
29502
  async function underCodexDaemon(env = process.env, pid = process.pid) {
29496
29503
  if (env.CODEX_INTERNAL_APP_SERVER_REMOTE_CONTROL_DISABLED !== void 0) return true;
29497
29504
  if (process.platform === "win32") return false;
@@ -29585,7 +29592,10 @@ function assignDaemonConversation(here, self, claimed, rivals, now = Date.now())
29585
29592
  if (!rivals.length) {
29586
29593
  const pool2 = after(self.start);
29587
29594
  const held = pool2.filter((r) => r.held);
29588
- return (held.length ? held : pool2).sort((a, b) => b.activeAt - a.activeAt)[0]?.id;
29595
+ const current2 = (held.length ? held : pool2).sort((a, b) => b.activeAt - a.activeAt)[0]?.id;
29596
+ if (current2) return current2;
29597
+ const resumed = open25.filter((r) => r.held && r.activeAt >= self.start && r.activeAt <= now + 6e4);
29598
+ return resumed.length === 1 && resumed[0].id === self.resumed ? self.resumed : void 0;
29589
29599
  }
29590
29600
  const order = [...rivals, self].sort((a, b) => b.start - a.start || (a.key < b.key ? 1 : a.key > b.key ? -1 : 0));
29591
29601
  const taken = /* @__PURE__ */ new Set();
@@ -36018,7 +36028,7 @@ async function codexDaemonIdentity(server, pane, pids) {
36018
36028
  const peerStart = startedAt(rows, peerPids);
36019
36029
  if (peerStart !== void 0) rivals.push({ key: String(peer.pane_id), start: peerStart });
36020
36030
  }
36021
- return { sessionId: assignDaemonConversation(here, { key: String(pane.pane_id), start }, claimed, rivals), known: known2 };
36031
+ return { sessionId: assignDaemonConversation(here, { key: String(pane.pane_id), start, resumed: resumedConversation(rows, pids) }, claimed, rivals), known: known2 };
36022
36032
  }
36023
36033
  async function paneForCodexSession(server, session, cwd) {
36024
36034
  const s = await snapshot(server);
@@ -61120,7 +61130,7 @@ async function readSecret(prompt) {
61120
61130
  // src/bridge/hook-main.ts
61121
61131
  init_utils_helpers();
61122
61132
  Object.assign(process.env, nonInteractiveGitEnv());
61123
- runBridge(process.argv.slice(2), "0.3.25").then((code) => {
61133
+ runBridge(process.argv.slice(2), "0.3.27").then((code) => {
61124
61134
  process.exitCode = code;
61125
61135
  }).catch((error62) => {
61126
61136
  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.25",
3
+ "version": "0.3.27",
4
4
  "description": "Knowledge layer for AI agents - CLI, MCP server, and data layer",
5
5
  "type": "module",
6
6
  "bin": {