@phren/cli 0.3.35 → 0.3.36

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 (68) hide show
  1. package/dist/bridge/agent-hooks.d.ts +11 -1
  2. package/dist/bridge/agent-hooks.js +56 -19
  3. package/dist/bridge/changes.js +18 -9
  4. package/dist/bridge/dispatch-command.js +3 -1
  5. package/dist/bridge/health.js +3 -1
  6. package/dist/bridge/host-key.d.ts +16 -0
  7. package/dist/bridge/host-key.js +35 -0
  8. package/dist/bridge/launch-brief.d.ts +2 -0
  9. package/dist/bridge/launch-brief.js +5 -0
  10. package/dist/bridge/link.js +11 -4
  11. package/dist/bridge/owner-inbox-sources.d.ts +5 -0
  12. package/dist/bridge/owner-inbox-sources.js +94 -0
  13. package/dist/bridge/owner-inbox-view.js +20 -1
  14. package/dist/bridge/owner-inbox.d.ts +7 -3
  15. package/dist/bridge/owner-inbox.js +113 -69
  16. package/dist/bridge/pair.js +3 -2
  17. package/dist/bridge/server.js +3 -23
  18. package/dist/bridge/sudo.d.ts +36 -6
  19. package/dist/bridge/sudo.js +180 -37
  20. package/dist/bridge/worker-reports.d.ts +8 -1
  21. package/dist/bridge/worker-reports.js +28 -7
  22. package/dist/bridge-hook.mjs +809 -471
  23. package/dist/clanker.d.ts +54 -0
  24. package/dist/clanker.js +188 -0
  25. package/dist/cli/config.js +30 -0
  26. package/dist/cli/hooks-output.d.ts +1 -1
  27. package/dist/cli/hooks-output.js +28 -21
  28. package/dist/cli/hooks.js +1 -1
  29. package/dist/cli/namespaces-skills.js +2 -2
  30. package/dist/cli/namespaces-tasks.js +46 -7
  31. package/dist/cli/session-start.js +12 -3
  32. package/dist/cli/session-stop.js +9 -0
  33. package/dist/cli/team.js +3 -0
  34. package/dist/cli-handlers.js +7 -0
  35. package/dist/cli-registry.js +1 -0
  36. package/dist/data/task-format.d.ts +5 -1
  37. package/dist/data/task-format.js +13 -5
  38. package/dist/index.js +82 -50
  39. package/dist/init/init-configure.d.ts +2 -0
  40. package/dist/init/init-configure.js +12 -0
  41. package/dist/init/init-uninstall.js +21 -2
  42. package/dist/init/init.d.ts +2 -0
  43. package/dist/init/init.js +11 -3
  44. package/dist/init/preferences.d.ts +6 -0
  45. package/dist/init/teardown.js +18 -4
  46. package/dist/link/doctor.js +2 -2
  47. package/dist/link/link.js +9 -0
  48. package/dist/link/refresh.d.ts +10 -0
  49. package/dist/link/refresh.js +34 -0
  50. package/dist/mcp/local-index.d.ts +20 -0
  51. package/dist/mcp/local-index.js +39 -1
  52. package/dist/shared/index.d.ts +14 -0
  53. package/dist/shared/index.js +88 -74
  54. package/dist/shared/retrieval.js +1 -1
  55. package/dist/skill/files.js +40 -11
  56. package/dist/skill/registry.d.ts +6 -0
  57. package/dist/skill/registry.js +21 -5
  58. package/dist/task/lifecycle.js +3 -1
  59. package/dist/tools/dispatch.js +5 -2
  60. package/dist/tools/finding.js +20 -11
  61. package/dist/tools/graph.d.ts +2 -0
  62. package/dist/tools/graph.js +2 -0
  63. package/dist/tools/search.d.ts +2 -0
  64. package/dist/tools/search.js +88 -6
  65. package/dist/tools/tasks.js +45 -0
  66. package/dist/tools/types.d.ts +3 -1
  67. package/dist/tools/types.js +3 -2
  68. package/package.json +1 -1
@@ -3,9 +3,11 @@ import * as path from "node:path";
3
3
  import { atomicWriteText } from "../phren-paths.js";
4
4
  import { withFileLock } from "../governance/locks.js";
5
5
  import { permissionDeniedError } from "../governance/rbac.js";
6
- import { registeredStoreIdentity } from "../store-registry.js";
6
+ import { registeredStoreIdentity, registerStoreIdentity } from "../store-registry.js";
7
7
  const file = (base) => path.join(base, ".config", "task-format.json");
8
- export const taskFormatMigrationHint = "Task metadata is not enabled for this store. Upgrade every CLI, MCP, Hook, sync and app writer first; an owner can then run phren task format enable --all-writers-compatible. Existing writers must be replaced through the coordinated adoption workflow.";
8
+ /** The oldest writers that keep task metadata when they rewrite a task. */
9
+ export const taskFormatCurrentWriters = "Phren CLI, MCP and Hook 0.3.30, iOS build 177, Android 1.0.5";
10
+ export const taskFormatMigrationHint = `Task metadata is off for this store. Once every app and tool that writes it is current (${taskFormatCurrentWriters} or later), an owner can turn it on with phren task format enable --all-writers-compatible.`;
9
11
  /** An explicit store-owner acknowledgement, not inferred from one serving Hook.
10
12
  * It cannot fence an old binary that ignores this file: coordinated adoption of
11
13
  * every writer remains a prerequisite, and is stated at the activation boundary. */
@@ -40,9 +42,15 @@ export function enableTaskFormat(base, allWritersCompatible) {
40
42
  throw new Error(denied);
41
43
  if (allWritersCompatible !== true)
42
44
  throw new Error(taskFormatMigrationHint);
43
- const storeId = registeredStoreIdentity(base);
44
- if (!storeId)
45
- throw new Error("Register a portable store identity with phren store identity --create before enabling task metadata.");
45
+ // Enabling is the owner's explicit act on this store, so a legacy store
46
+ // without a portable identity gets one here instead of needing a second command.
47
+ writeTaskFormat(base, registerStoreIdentity(base));
48
+ }
49
+ /** A store phren has just created has no old writers, so metadata starts on. */
50
+ export function initializeTaskFormat(base) {
51
+ writeTaskFormat(base, registerStoreIdentity(base));
52
+ }
53
+ function writeTaskFormat(base, storeId) {
46
54
  fs.mkdirSync(path.dirname(file(base)), { recursive: true });
47
55
  withFileLock(file(base), () => {
48
56
  if (taskFormatStatus(base).enabled)
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, captureIndexInputs, flushEmbeddingQueue, updateFileInIndex: updateFileInIndexFn }, { runCustomHooks }, { mcpResponse }, { startEmbeddingWarmup }, { resolveRuntimeProfile }, { VERSION: PACKAGE_VERSION },] = await Promise.all([
81
+ const [{ McpServer }, { StdioServerTransport }, { buildIndex, captureIndexInputs, flushEmbeddingQueue, isIndexBusyError, 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"),
@@ -105,7 +105,11 @@ async function main() {
105
105
  let db = null;
106
106
  // The first call also verifies startup's possibly stale lock-contention fallback.
107
107
  let localInputs;
108
- const { localIndexRefresh, indexReaders } = await import("./mcp/local-index.js");
108
+ const { localIndexRefresh, indexReaders, retryWhileBusy, indexBusyWaitMs } = await import("./mcp/local-index.js");
109
+ // Another process (a hook's detached reindex, another session's server)
110
+ // holding the rebuild lock is waited out for this long before a call falls
111
+ // back to the last good index. A store rebuild takes ~1.5 s idle, ~4 s p90.
112
+ const busyWait = { isBusy: isIndexBusyError, maxWaitMs: indexBusyWaitMs() };
109
113
  const readers = indexReaders(() => {
110
114
  if (!db)
111
115
  throw new Error("Index unavailable - check phren setup");
@@ -203,14 +207,26 @@ async function main() {
203
207
  }
204
208
  const runIndexExclusive = (fn) => {
205
209
  const run = writeQueue.then(fn);
206
- writeQueue = run.catch((error) => { logger.warn("index-refresh", errorMessage(error)); });
210
+ writeQueue = run.catch((error) => {
211
+ // Busy is expected under concurrent writers and retried by the caller.
212
+ if (isIndexBusyError(error))
213
+ debugLog(`index-refresh: ${errorMessage(error)}`);
214
+ else
215
+ logger.warn("index-refresh", errorMessage(error));
216
+ });
207
217
  return run;
208
218
  };
209
219
  const localIndex = localIndexRefresh({
210
220
  isFresh: () => localInputs?.() ?? false,
211
221
  refresh: () => rebuildIndex(true),
212
222
  runExclusive: runIndexExclusive,
223
+ busyWait,
213
224
  });
225
+ // Tools registered by a module that exports `readsIndex = true` answer from
226
+ // the FTS index and refresh it first. Everything else (tasks, findings,
227
+ // sessions, account usage, live sessions, dispatch...) reads and writes the
228
+ // store's files directly and must not wait on, or fail because of, a rebuild.
229
+ let registeringIndexModule = false;
214
230
  const server = new McpServer({
215
231
  name: "phren-mcp",
216
232
  version: PACKAGE_VERSION,
@@ -232,50 +248,59 @@ async function main() {
232
248
  modules: enabledModules,
233
249
  alwaysLoad: ALWAYS_LOAD_TOOLS,
234
250
  register: (name, config, handler) => origRegisterTool(name, config, handler),
235
- wrap: (registeredName, handler) => async (...args) => {
236
- if (shuttingDown) {
237
- return {
238
- content: [{
239
- type: "text",
240
- text: JSON.stringify({
241
- ok: false,
242
- error: "phren-mcp server is shutting down; retry in a new session",
243
- }, null, 2),
244
- }],
245
- };
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
- }
254
- if (!indexReady || !db) {
255
- return {
256
- content: [{
257
- type: "text",
258
- text: JSON.stringify({
259
- ok: false,
260
- error: "Index unavailable - check phren setup",
261
- }, null, 2),
262
- }],
263
- };
264
- }
265
- const owner = toolOwner(registeredName);
266
- if (owner && owner.name !== "memory") {
267
- const input = args[0];
268
- const store = typeof input?.project === "string" ? resolveStoreForProject(ctx, input.project).phrenPath : phrenPath;
269
- if (!snapshots.get(store)?.has(owner.name))
270
- return mcpResponse({ ok: false, error: disabledHint(owner.name), errorCode: "UNAVAILABLE" });
271
- }
272
- try {
273
- trackToolCall(phrenPath, registeredName);
274
- }
275
- catch (err) {
276
- logger.warn("trackToolCall", errorMessage(err));
277
- }
278
- return readers.run(() => handler(...args));
251
+ wrap: (registeredName, handler) => {
252
+ const readsIndex = registeringIndexModule;
253
+ return async (...args) => {
254
+ if (shuttingDown) {
255
+ return {
256
+ content: [{
257
+ type: "text",
258
+ text: JSON.stringify({
259
+ ok: false,
260
+ error: "phren-mcp server is shutting down; retry in a new session",
261
+ }, null, 2),
262
+ }],
263
+ };
264
+ }
265
+ if (readsIndex) {
266
+ try {
267
+ await localIndex.ensureFresh();
268
+ }
269
+ catch (error) {
270
+ // Serve the last good index rather than failing the call: it lags
271
+ // the newest write at most, the same trade the prompt hook makes.
272
+ // The baseline is not advanced, so the next call refreshes again.
273
+ logger.warn("local-index", `${errorMessage(error)}${db ? " (serving last good index)" : ""}`);
274
+ if (!db)
275
+ return mcpResponse({ ok: false, error: "Could not refresh the local index; retry shortly." });
276
+ }
277
+ }
278
+ if (!indexReady || !db) {
279
+ return {
280
+ content: [{
281
+ type: "text",
282
+ text: JSON.stringify({
283
+ ok: false,
284
+ error: "Index unavailable - check phren setup",
285
+ }, null, 2),
286
+ }],
287
+ };
288
+ }
289
+ const owner = toolOwner(registeredName);
290
+ if (owner && owner.name !== "memory") {
291
+ const input = args[0];
292
+ const store = typeof input?.project === "string" ? resolveStoreForProject(ctx, input.project).phrenPath : phrenPath;
293
+ if (!snapshots.get(store)?.has(owner.name))
294
+ return mcpResponse({ ok: false, error: disabledHint(owner.name), errorCode: "UNAVAILABLE" });
295
+ }
296
+ try {
297
+ trackToolCall(phrenPath, registeredName);
298
+ }
299
+ catch (err) {
300
+ logger.warn("trackToolCall", errorMessage(err));
301
+ }
302
+ return readers.run(() => handler(...args));
303
+ };
279
304
  },
280
305
  });
281
306
  server.registerTool = gate.registerTool;
@@ -284,7 +309,7 @@ async function main() {
284
309
  phrenPath,
285
310
  get profile() { return profile; },
286
311
  db: () => readers.get(),
287
- rebuildIndex,
312
+ rebuildIndex: () => retryWhileBusy(() => rebuildIndex(), busyWait),
288
313
  withWriteQueue,
289
314
  updateFileInIndex: (filePath) => {
290
315
  if (!db)
@@ -313,8 +338,15 @@ async function main() {
313
338
  ...(codeAvailable ? [import("./tools/code.js")] : []),
314
339
  ...(hasModule("conductor") ? [import("./tools/dispatch.js")] : []),
315
340
  ]);
316
- for (const mod of toolModules)
317
- mod.register(server, ctx);
341
+ for (const mod of toolModules) {
342
+ registeringIndexModule = "readsIndex" in mod && mod.readsIndex === true;
343
+ try {
344
+ mod.register(server, ctx);
345
+ }
346
+ finally {
347
+ registeringIndexModule = false;
348
+ }
349
+ }
318
350
  gate.finish();
319
351
  const transport = new StdioServerTransport();
320
352
  await server.connect(transport);
@@ -23,4 +23,6 @@ export declare function writeWalkthroughEnvDefaults(phrenPath: string, opts: Ini
23
23
  export declare function collectRepairedAssetLabels(repaired: ReturnType<typeof repairPreexistingInstall>): string[];
24
24
  export declare function applyProjectStorageBindings(repoRoot: string, phrenPath: string): string[];
25
25
  export declare function warmSemanticSearch(phrenPath: string, profile?: string): Promise<string>;
26
+ /** A new store has no old writers, so task metadata starts on. Init still succeeds without it. */
27
+ export declare function enableTaskMetadataForNewStore(phrenPath: string): void;
26
28
  export declare function runProjectLocalInit(opts?: InitOptions): Promise<void>;
@@ -9,6 +9,7 @@ import { getProjectOwnershipDefault } from "../project-config.js";
9
9
  import { atomicWriteText, debugLog, ensurePrivateDir, projectSlugFromPath, readRootManifest, writeRootManifest, } from "../shared.js";
10
10
  import { STORE_SECRET_GITIGNORE_LINES } from "./store-gitignore.js";
11
11
  import { errorMessage } from "../utils.js";
12
+ import { initializeTaskFormat } from "../data/task-format.js";
12
13
  import { configureAllHooks, installPhrenCliWrapper, ensureLocalBinOnWindowsPath } from "../hooks.js";
13
14
  import { updateWorkflowPolicy } from "../shared/governance.js";
14
15
  import { configureClaude, configureVSCode, configureCursorMcp, configureCopilotMcp, configureCodexMcp, logMcpTargetStatus, } from "./config.js";
@@ -302,6 +303,15 @@ export async function warmSemanticSearch(phrenPath, profile) {
302
303
  catch { /* ignore close errors in init */ }
303
304
  }
304
305
  }
306
+ /** A new store has no old writers, so task metadata starts on. Init still succeeds without it. */
307
+ export function enableTaskMetadataForNewStore(phrenPath) {
308
+ try {
309
+ initializeTaskFormat(phrenPath);
310
+ }
311
+ catch (e) {
312
+ log(` Task metadata left off: ${errorMessage(e)}. Turn it on later with phren task format enable --all-writers-compatible.`);
313
+ }
314
+ }
305
315
  export async function runProjectLocalInit(opts = {}) {
306
316
  const detectedRoot = detectProjectDir(process.cwd(), path.join(process.cwd(), ".phren")) || process.cwd();
307
317
  const hasWorkspaceMarker = fs.existsSync(path.join(detectedRoot, ".git")) ||
@@ -344,6 +354,8 @@ export async function runProjectLocalInit(opts = {}) {
344
354
  primaryProject: projectName,
345
355
  });
346
356
  ensureGovernanceFiles(phrenPath);
357
+ if (!existingManifest)
358
+ enableTaskMetadataForNewStore(phrenPath);
347
359
  repairPreexistingInstall(phrenPath);
348
360
  fs.mkdirSync(path.join(phrenPath, "global", "skills"), { recursive: true });
349
361
  ensurePrivateDir(path.join(phrenPath, ".runtime"));
@@ -95,9 +95,21 @@ function sweepSkillSymlinks(phrenPath) {
95
95
  continue;
96
96
  }
97
97
  for (const entry of entries) {
98
- if (!entry.isSymbolicLink())
98
+ // A flat skill is linked as <name>/SKILL.md inside a folder phren made.
99
+ const wrapper = entry.isDirectory() ? path.join(dir, entry.name) : null;
100
+ if (wrapper) {
101
+ try {
102
+ const children = fs.readdirSync(wrapper);
103
+ if (children.length !== 1 || children[0] !== "SKILL.md" || !fs.lstatSync(path.join(wrapper, "SKILL.md")).isSymbolicLink())
104
+ continue;
105
+ }
106
+ catch {
107
+ continue;
108
+ }
109
+ }
110
+ else if (!entry.isSymbolicLink())
99
111
  continue;
100
- const fullPath = path.join(dir, entry.name);
112
+ const fullPath = wrapper ? path.join(wrapper, "SKILL.md") : path.join(dir, entry.name);
101
113
  try {
102
114
  const target = fs.realpathSync(fullPath);
103
115
  if (target.startsWith(resolvedPhren + path.sep) || target === resolvedPhren) {
@@ -115,6 +127,13 @@ function sweepSkillSymlinks(phrenPath) {
115
127
  debugLog(`sweepSkillSymlinks: could not remove broken symlink ${fullPath}: ${errorMessage(err2)}`);
116
128
  }
117
129
  }
130
+ if (wrapper) {
131
+ try {
132
+ if (fs.readdirSync(wrapper).length === 0)
133
+ fs.rmdirSync(wrapper);
134
+ }
135
+ catch { /* already gone */ }
136
+ }
118
137
  }
119
138
  // Remove phren-generated manifest files from the skills parent directory
120
139
  const parentDir = path.dirname(dir);
@@ -34,6 +34,8 @@ export interface InitOptions {
34
34
  profile?: string;
35
35
  mcp?: McpMode;
36
36
  hooks?: McpMode;
37
+ /** Clanker mode (compact id/title/keyword retrieval). New installs default to on. */
38
+ clanker?: McpMode;
37
39
  projectOwnershipDefault?: ProjectOwnershipMode;
38
40
  /** Management preset controlling phren's machine footprint (managed | assisted | manual). */
39
41
  managementPreset?: ManagementPreset;
package/dist/init/init.js CHANGED
@@ -28,7 +28,7 @@ export { runPreset } from "./init-preset.js";
28
28
  export { printSelfWiringSnippet } from "./self-wiring.js";
29
29
  export { runUninstall } from "./init-uninstall.js";
30
30
  // Internal imports from extracted modules (used by runInit)
31
- import { configureMcpTargets, configureHooksIfEnabled, applyOnboardingPreferences, writeWalkthroughEnvDefaults, collectRepairedAssetLabels, applyProjectStorageBindings, warmSemanticSearch, runProjectLocalInit, } from "./init-configure.js";
31
+ import { configureMcpTargets, configureHooksIfEnabled, applyOnboardingPreferences, writeWalkthroughEnvDefaults, collectRepairedAssetLabels, applyProjectStorageBindings, warmSemanticSearch, runProjectLocalInit, enableTaskMetadataForNewStore, } from "./init-configure.js";
32
32
  import { runWalkthrough, createWalkthroughPrompts, createWalkthroughStyle } from "./init-walkthrough.js";
33
33
  import { assertNoGlobalWiringConflict } from "./guard-globals.js";
34
34
  import { getMcpEnabledPreference, getHooksEnabledPreference, writeInstallPreferences, readInstallPreferences, setManagementPresetPreference, } from "./preferences.js";
@@ -277,6 +277,11 @@ export async function runInit(opts = {}) {
277
277
  // On re-runs of existing installs, preserve the existing syncIntent unless the user provided a new clone URL.
278
278
  const existingSyncIntent = hasExistingInstall ? readInstallPreferences(phrenPath).syncIntent : undefined;
279
279
  const syncIntent = opts._walkthroughCloneUrl ? "sync" : (existingSyncIntent ?? "local");
280
+ // Clanker mode is on for a machine's first init (a cloned store included);
281
+ // a machine that ran init before keeps what it has (unset means off),
282
+ // unless --clanker says otherwise.
283
+ const priorPrefs = readInstallPreferences(phrenPath);
284
+ const clanker = opts.clanker ? opts.clanker === "on" : (priorPrefs.clanker ?? (priorPrefs.installedVersion ? undefined : true));
280
285
  // Resolve the management preset for this run: explicit flag/walkthrough answer,
281
286
  // else the stored preset on existing installs, else the default (managed).
282
287
  const managementPreset = parseManagementPreset(opts.managementPreset)
@@ -422,6 +427,7 @@ export async function runInit(opts = {}) {
422
427
  log(` Management preset: ${managementPreset} — ${presetSummaryLines(managementPreset)}`);
423
428
  log(` MCP mode: ${mcpLabel}`);
424
429
  log(` Hooks mode: ${hooksLabel}`);
430
+ log(` Clanker mode: ${clanker ? "on" : "off"} (phren config clanker on|off)`);
425
431
  log(` Default project ownership: ${ownershipDefault}`);
426
432
  if (moduleEnabled(phrenPath, "tasks"))
427
433
  log(` Task mode: ${getWorkflowPolicy(phrenPath).taskMode}`);
@@ -445,7 +451,7 @@ export async function runInit(opts = {}) {
445
451
  log(` No starter template updates were applied (starter files not found).`);
446
452
  }
447
453
  }
448
- writeInstallPreferences(phrenPath, { mcpEnabled, hooksEnabled, skillsScope, installedVersion: VERSION, syncIntent });
454
+ writeInstallPreferences(phrenPath, { mcpEnabled, hooksEnabled, skillsScope, installedVersion: VERSION, syncIntent, clanker });
449
455
  if (repaired.removedLegacyProjects > 0) {
450
456
  log(` Removed ${repaired.removedLegacyProjects} legacy starter project entr${repaired.removedLegacyProjects === 1 ? "y" : "ies"} from profiles.`);
451
457
  }
@@ -607,6 +613,7 @@ export async function runInit(opts = {}) {
607
613
  persistMachineName(effectiveMachine);
608
614
  updateMachinesYaml(phrenPath, effectiveMachine, opts.profile);
609
615
  ensureGovernanceFiles(phrenPath);
616
+ enableTaskMetadataForNewStore(phrenPath);
610
617
  setManagementPresetPreference(phrenPath, managementPreset);
611
618
  const repaired = repairPreexistingInstall(phrenPath, { caps: managementCaps, preset: managementPreset });
612
619
  applyOnboardingPreferences(phrenPath, opts);
@@ -615,6 +622,7 @@ export async function runInit(opts = {}) {
615
622
  log(` Management preset: ${managementPreset} — ${presetSummaryLines(managementPreset)}`);
616
623
  log(` MCP mode: ${mcpLabel}`);
617
624
  log(` Hooks mode: ${hooksLabel}`);
625
+ log(` Clanker mode: ${clanker ? "on" : "off"} (phren config clanker on|off)`);
618
626
  log(` Default project ownership: ${ownershipDefault}`);
619
627
  if (moduleEnabled(phrenPath, "tasks"))
620
628
  log(` Task mode: ${getWorkflowPolicy(phrenPath).taskMode}`);
@@ -630,7 +638,7 @@ export async function runInit(opts = {}) {
630
638
  configureMcpTargets(phrenPath, { mcpEnabled, hooksEnabled, caps: managementCaps }, "Configured");
631
639
  configureHooksIfEnabled(phrenPath, hooksEnabled, "Configured", managementCaps);
632
640
  await reconcileModuleHooks(phrenPath);
633
- writeInstallPreferences(phrenPath, { mcpEnabled, hooksEnabled, skillsScope, installedVersion: VERSION, syncIntent });
641
+ writeInstallPreferences(phrenPath, { mcpEnabled, hooksEnabled, skillsScope, installedVersion: VERSION, syncIntent, clanker });
634
642
  // Post-init verification
635
643
  log(`\nVerifying setup...`);
636
644
  const verify = runPostInitVerify(phrenPath);
@@ -7,6 +7,12 @@ export interface InstallPreferences {
7
7
  * PHREN_MCP_PROFILE overrides it. See mcp/profile.ts.
8
8
  */
9
9
  mcpProfile?: "core" | "full";
10
+ /**
11
+ * Clanker mode: the prompt hook and the search/list tools return compact
12
+ * id/title/keyword rows and agents fetch full text by id. PHREN_CLANKER
13
+ * overrides it. See clanker.ts.
14
+ */
15
+ clanker?: boolean;
10
16
  hooksEnabled?: boolean;
11
17
  skillsScope?: "global" | "project";
12
18
  projectOwnershipDefault?: "phren-managed" | "detached" | "repo-managed";
@@ -202,17 +202,24 @@ export function removeGitExcludes(projectDir, entries) {
202
202
  */
203
203
  export function sweepProjectMirrors(phrenPath) {
204
204
  const resolvedPhren = path.resolve(phrenPath);
205
+ // realpathSync resolves symlinks in the store's own path too (macOS /var ->
206
+ // /private/var), so compare a link's real target with the store's real path.
207
+ let realPhren = resolvedPhren;
208
+ try {
209
+ realPhren = fs.realpathSync(phrenPath);
210
+ }
211
+ catch { /* store missing: keep the resolved path */ }
212
+ const inStore = (p, root) => p.startsWith(root + path.sep) || p === root;
205
213
  const resolvesIntoStore = (p) => {
206
214
  try {
207
- const target = fs.realpathSync(p);
208
- return target.startsWith(resolvedPhren + path.sep) || target === resolvedPhren;
215
+ return inStore(fs.realpathSync(p), realPhren);
209
216
  }
210
217
  catch {
211
218
  // Broken symlink — check its raw (unresolved) target.
212
219
  try {
213
220
  const raw = fs.readlinkSync(p);
214
221
  const resolved = path.resolve(path.dirname(p), raw);
215
- return resolved.startsWith(resolvedPhren + path.sep) || resolved === resolvedPhren;
222
+ return inStore(resolved, resolvedPhren) || inStore(resolved, realPhren);
216
223
  }
217
224
  catch {
218
225
  return false;
@@ -277,8 +284,15 @@ export function sweepProjectMirrors(phrenPath) {
277
284
  if (fs.existsSync(skillsDir)) {
278
285
  try {
279
286
  for (const entry of fs.readdirSync(skillsDir, { withFileTypes: true })) {
287
+ const rel = path.join(".claude", "skills", entry.name);
280
288
  if (entry.isSymbolicLink())
281
- removeMirror(path.join(".claude", "skills", entry.name));
289
+ removeMirror(rel);
290
+ // A flat skill is linked as <name>/SKILL.md inside a folder phren made.
291
+ else if (entry.isDirectory() && fs.readdirSync(path.join(repo, rel)).join() === "SKILL.md") {
292
+ removeMirror(path.join(rel, "SKILL.md"));
293
+ if (fs.readdirSync(path.join(repo, rel)).length === 0)
294
+ fs.rmdirSync(path.join(repo, rel));
295
+ }
282
296
  }
283
297
  }
284
298
  catch { /* skills dir unreadable — skip */ }
@@ -14,7 +14,7 @@ import { validateTaskFormat, validateFindingsFormat } from "../shared/content.js
14
14
  import { commandExists, detectInstalledTools, isEphemeralNpxPath, findStaleHookEntrypoints } from "../hooks.js";
15
15
  import { validateSkillFrontmatter, validateSkillsDir } from "./skills.js";
16
16
  import { verifyFileChecksums, updateFileChecksums } from "./checksums.js";
17
- import { buildSkillManifest } from "../skill/registry.js";
17
+ import { buildSkillManifest, skillMirrorPath } from "../skill/registry.js";
18
18
  import { inspectTaskHygiene } from "../task/hygiene.js";
19
19
  import { resolveTaskFilePath, TASK_FILE_ALIASES } from "../data/tasks.js";
20
20
  import { FINDINGS_FILENAME } from "../data/access.js";
@@ -197,7 +197,7 @@ function pushSkillMirrorChecks(checks, scope, manifest, destDir) {
197
197
  : `missing generated command registry at ${path.join(parentDir, "skill-commands.json")}`,
198
198
  });
199
199
  for (const skill of manifest.skills.filter((entry) => entry.visibleToAgents)) {
200
- const dest = path.join(destDir, skill.format === "folder" ? skill.name : path.basename(skill.path));
200
+ const dest = skillMirrorPath(destDir, skill);
201
201
  let ok = false;
202
202
  try {
203
203
  ok = fs.existsSync(dest) && fs.realpathSync(dest) === fs.realpathSync(skill.root);
package/dist/link/link.js CHANGED
@@ -20,6 +20,7 @@ import { listMachines as listMachinesShared, listProfiles as listProfilesShared,
20
20
  import { writeSkillMd, isManagedSymlink } from "./skills.js";
21
21
  import { resolveManagementCapabilities } from "../init/management-preset.js";
22
22
  import { syncScopeSkillsToDir } from "../skill/files.js";
23
+ import { teamStoreProjectCheckouts } from "./refresh.js";
23
24
  import { findProjectDir } from "../project-locator.js";
24
25
  import { getProjectOwnershipMode, readProjectConfig, } from "../project-config.js";
25
26
  import { writeContextDefault, writeContextDebugging, writeContextPlanning, writeContextClean, readBackNativeMemory, rebuildMemory, } from "./context.js";
@@ -496,6 +497,14 @@ export async function runLink(phrenPath, opts = {}) {
496
497
  if (p !== "global")
497
498
  linkProject(phrenPath, p, detectedTools, caps);
498
499
  }
500
+ if (caps.repoMirroring) {
501
+ for (const { project, target, skills } of teamStoreProjectCheckouts(phrenPath)) {
502
+ if (!skills)
503
+ continue;
504
+ syncScopeSkillsToDir(phrenPath, project, path.join(target, ".claude", "skills"));
505
+ log(` ${project} -> ${target} (team store skills)`);
506
+ }
507
+ }
499
508
  // Remove stale phren__<project>__* MCP entries for removed projects
500
509
  pruneStaleProjectMcpServers(projects.filter(p => p !== "global"));
501
510
  log("");
@@ -1 +1,11 @@
1
+ /**
2
+ * Projects from attached team stores whose checkout is on this machine. Profiles
3
+ * list only the primary store's projects, so link and refresh reach these here;
4
+ * a project the primary store also has is left to the primary.
5
+ */
6
+ export declare function teamStoreProjectCheckouts(phrenPath: string): Array<{
7
+ project: string;
8
+ target: string;
9
+ skills: boolean;
10
+ }>;
1
11
  export declare function refreshLinkedContext(phrenPath: string, profile: string): void;
@@ -7,6 +7,35 @@ import { readProjectConfig, getProjectSourcePath, getProjectOwnershipMode } from
7
7
  import { findProjectDir } from "../project-locator.js";
8
8
  import { resolveManagementCapabilities } from "../init/management-preset.js";
9
9
  import { syncScopeSkillsToDir } from "../skill/files.js";
10
+ import { getNonPrimaryStores, getStoreProjectDirs } from "../store-registry.js";
11
+ /**
12
+ * Projects from attached team stores whose checkout is on this machine. Profiles
13
+ * list only the primary store's projects, so link and refresh reach these here;
14
+ * a project the primary store also has is left to the primary.
15
+ */
16
+ export function teamStoreProjectCheckouts(phrenPath) {
17
+ const found = [];
18
+ const seen = new Set();
19
+ for (const store of getNonPrimaryStores(phrenPath)) {
20
+ if (!fs.existsSync(store.path))
21
+ continue;
22
+ for (const dir of getStoreProjectDirs(store)) {
23
+ const project = path.basename(dir);
24
+ if (project === "global" || seen.has(project) || fs.existsSync(path.join(phrenPath, project)))
25
+ continue;
26
+ seen.add(project);
27
+ const config = readProjectConfig(store.path, project);
28
+ if (getProjectOwnershipMode(store.path, project, config) !== "phren-managed")
29
+ continue;
30
+ // The store is shared between computers, so its sourcePath may be another machine's.
31
+ const configured = getProjectSourcePath(store.path, project, config);
32
+ const target = configured && fs.existsSync(configured) ? configured : findProjectDir(project);
33
+ if (target && fs.existsSync(target))
34
+ found.push({ project, target, skills: config.skills !== false });
35
+ }
36
+ }
37
+ return found;
38
+ }
10
39
  export function refreshLinkedContext(phrenPath, profile) {
11
40
  const caps = resolveManagementCapabilities(phrenPath);
12
41
  if (caps.installSkillLinks) {
@@ -45,4 +74,9 @@ export function refreshLinkedContext(phrenPath, profile) {
45
74
  fs.unlinkSync(agentsPath);
46
75
  fs.symlinkSync(claudePath, agentsPath);
47
76
  }
77
+ for (const { project, target, skills } of teamStoreProjectCheckouts(phrenPath)) {
78
+ if (skills && fs.existsSync(path.join(target, ".claude", "skill-manifest.json"))) {
79
+ syncScopeSkillsToDir(phrenPath, project, path.join(target, ".claude", "skills"));
80
+ }
81
+ }
48
82
  }
@@ -4,6 +4,24 @@ export declare function indexReaders<T>(current: () => T, close: (handle: T) =>
4
4
  retire(handle: T): void;
5
5
  run<R>(fn: () => R | Promise<R>): Promise<R>;
6
6
  };
7
+ export interface BusyWait {
8
+ /** Whether an error means "another process is rebuilding" (worth waiting out). */
9
+ isBusy: (error: unknown) => boolean;
10
+ /** Total budget across retries. */
11
+ maxWaitMs: number;
12
+ now?: () => number;
13
+ sleep?: (ms: number) => Promise<void>;
14
+ }
15
+ /** PHREN_INDEX_BUSY_WAIT_MS, default 5000, capped at 30000; 0 disables the wait. */
16
+ export declare function indexBusyWaitMs(env?: NodeJS.ProcessEnv): number;
17
+ /**
18
+ * Run `fn`, and while it fails only because another process holds the rebuild
19
+ * lock, retry with jittered backoff until `maxWaitMs` is spent. Any other
20
+ * error, or the last busy error once the budget is gone, propagates.
21
+ * Another process's rebuild usually leaves a cache entry for the same store
22
+ * state, so the retry after it is a cheap cache load rather than a second build.
23
+ */
24
+ export declare function retryWhileBusy<T>(fn: () => Promise<T>, wait: BusyWait): Promise<T>;
7
25
  /** Coalesce local freshness checks without a timer or any remote polling. */
8
26
  export declare function localIndexRefresh(options: {
9
27
  isFresh: () => boolean;
@@ -11,6 +29,8 @@ export declare function localIndexRefresh(options: {
11
29
  runExclusive: (fn: () => Promise<void>) => Promise<unknown>;
12
30
  now?: () => number;
13
31
  intervalMs?: number;
32
+ /** Wait out another process's rebuild instead of failing on the first busy lock. */
33
+ busyWait?: BusyWait;
14
34
  }): {
15
35
  ensureFresh: () => Promise<void>;
16
36
  };
@@ -43,6 +43,40 @@ export function indexReaders(current, close) {
43
43
  },
44
44
  };
45
45
  }
46
+ /** PHREN_INDEX_BUSY_WAIT_MS, default 5000, capped at 30000; 0 disables the wait. */
47
+ export function indexBusyWaitMs(env = process.env) {
48
+ const parsed = Number.parseInt(env.PHREN_INDEX_BUSY_WAIT_MS ?? "", 10);
49
+ if (!Number.isFinite(parsed) || parsed < 0)
50
+ return 5000;
51
+ return Math.min(parsed, 30_000);
52
+ }
53
+ const sleepMs = (ms) => new Promise(resolve => setTimeout(resolve, ms));
54
+ /**
55
+ * Run `fn`, and while it fails only because another process holds the rebuild
56
+ * lock, retry with jittered backoff until `maxWaitMs` is spent. Any other
57
+ * error, or the last busy error once the budget is gone, propagates.
58
+ * Another process's rebuild usually leaves a cache entry for the same store
59
+ * state, so the retry after it is a cheap cache load rather than a second build.
60
+ */
61
+ export async function retryWhileBusy(fn, wait) {
62
+ const now = wait.now ?? Date.now;
63
+ const sleep = wait.sleep ?? sleepMs;
64
+ const deadline = now() + Math.max(0, wait.maxWaitMs);
65
+ let delay = 50;
66
+ for (;;) {
67
+ try {
68
+ return await fn();
69
+ }
70
+ catch (error) {
71
+ const remaining = deadline - now();
72
+ if (!wait.isBusy(error) || remaining <= 0)
73
+ throw error;
74
+ // Jitter so a crowd of waiting servers does not retry in lockstep.
75
+ await sleep(Math.min(remaining, delay + Math.floor(Math.random() * delay)));
76
+ delay = Math.min(delay * 2, 500);
77
+ }
78
+ }
79
+ }
46
80
  /** Coalesce local freshness checks without a timer or any remote polling. */
47
81
  export function localIndexRefresh(options) {
48
82
  const now = options.now ?? Date.now;
@@ -70,7 +104,11 @@ export function localIndexRefresh(options) {
70
104
  failure = error;
71
105
  throw error;
72
106
  }
73
- pending = options.runExclusive(options.refresh).then(() => { failure = undefined; })
107
+ // The wait happens outside runExclusive so queued writes keep flowing
108
+ // between attempts; every concurrent caller shares this one pending run.
109
+ const attempt = () => options.runExclusive(options.refresh);
110
+ const run = options.busyWait ? retryWhileBusy(attempt, options.busyWait) : attempt();
111
+ pending = run.then(() => { failure = undefined; })
74
112
  .catch((error) => { failure = error; throw error; })
75
113
  .finally(() => { checkedAt = now(); pending = undefined; });
76
114
  return pending;
@@ -29,6 +29,20 @@ export declare function updateFileInIndex(db: SqlJsDatabase, filePath: string, p
29
29
  * known paths: no glob, content reads, Git operations, or database rebuild.
30
30
  */
31
31
  export declare function captureIndexInputs(phrenPath: string, profile?: string): Promise<() => boolean>;
32
+ /** Thrown by a `requireFresh` build while another process holds the rebuild lock. */
33
+ export declare class IndexBusyError extends Error {
34
+ readonly code = "PHREN_INDEX_BUSY";
35
+ constructor(message?: string);
36
+ }
37
+ export declare function isIndexBusyError(error: unknown): boolean;
38
+ /**
39
+ * Whether another process is rebuilding right now. A lock younger than the
40
+ * stale threshold still counts as free when the pid written into it is gone:
41
+ * a rebuild killed mid-way (a hook timed out, a detached reindex OOM-killed)
42
+ * never unlinks its lock, and without the pid check every fresh-required
43
+ * refresh in every MCP server failed for up to 30 s after it.
44
+ */
45
+ export declare function isRebuildLockHeld(phrenPath: string): boolean;
32
46
  export declare function buildIndex(phrenPath: string, profile?: string, options?: {
33
47
  force?: boolean;
34
48
  requireFresh?: boolean;