@phren/cli 0.2.10 → 0.2.11

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 (52) hide show
  1. package/README.md +3 -0
  2. package/dist/bridge/activity.d.ts +8 -0
  3. package/dist/bridge/activity.js +43 -0
  4. package/dist/bridge/agent-hooks.d.ts +15 -0
  5. package/dist/bridge/agent-hooks.js +160 -0
  6. package/dist/bridge/command.d.ts +1 -0
  7. package/dist/bridge/command.js +42 -0
  8. package/dist/bridge/herdr.d.ts +12 -0
  9. package/dist/bridge/herdr.js +147 -0
  10. package/dist/bridge/hook-main.d.ts +1 -0
  11. package/dist/bridge/hook-main.js +7 -0
  12. package/dist/bridge/install.d.ts +15 -0
  13. package/dist/bridge/install.js +264 -0
  14. package/dist/bridge/projects.d.ts +10 -0
  15. package/dist/bridge/projects.js +89 -0
  16. package/dist/bridge/protocol.d.ts +35 -0
  17. package/dist/bridge/protocol.js +34 -0
  18. package/dist/bridge/server.d.ts +16 -0
  19. package/dist/bridge/server.js +291 -0
  20. package/dist/bridge/transcripts.d.ts +30 -0
  21. package/dist/bridge/transcripts.js +177 -0
  22. package/dist/bridge/transport.d.ts +4 -0
  23. package/dist/bridge/transport.js +64 -0
  24. package/dist/bridge/uploads.d.ts +2 -0
  25. package/dist/bridge/uploads.js +45 -0
  26. package/dist/bridge-hook.mjs +22571 -0
  27. package/dist/cli/config.js +27 -0
  28. package/dist/cli/namespaces-skills.js +2 -2
  29. package/dist/cli/session-git.d.ts +6 -0
  30. package/dist/cli/session-git.js +26 -0
  31. package/dist/cli/session-start.js +3 -3
  32. package/dist/cli/session-stop.js +54 -52
  33. package/dist/cli-registry.d.ts +1 -1
  34. package/dist/cli-registry.js +11 -0
  35. package/dist/generated/memory-ui-graph.browser.js +86 -86
  36. package/dist/governance/locks.d.ts +2 -0
  37. package/dist/governance/locks.js +45 -0
  38. package/dist/index.js +38 -2
  39. package/dist/init/preferences.d.ts +2 -0
  40. package/dist/link/refresh.d.ts +1 -0
  41. package/dist/link/refresh.js +47 -0
  42. package/dist/memory-ui-graph.runtime.js +86 -86
  43. package/dist/shared/index.d.ts +3 -1
  44. package/dist/shared/index.js +3 -2
  45. package/dist/skill/state.d.ts +10 -0
  46. package/dist/skill/state.js +41 -17
  47. package/dist/sync/pull.d.ts +29 -0
  48. package/dist/sync/pull.js +225 -0
  49. package/dist/tools/finding.js +4 -2
  50. package/dist/tools/skills.js +3 -3
  51. package/dist/ui/server.js +1 -1
  52. package/package.json +3 -1
@@ -1,3 +1,5 @@
1
+ /** A non-blocking lock for background work. Uses the same files as withFileLock. */
2
+ export declare function tryFileLock(filePath: string): (() => void) | null;
1
3
  export declare function withFileLock<T>(filePath: string, fn: () => T): T extends Promise<infer U> ? Promise<U> : T;
2
4
  export declare function isFiniteNumber(value: unknown): value is number;
3
5
  export declare function hasValidSchemaVersion(data: Record<string, unknown>): boolean;
@@ -84,6 +84,51 @@ function releaseFileLock(lockPath) {
84
84
  logger.debug("releaseFileLock", `${errorMessage(err)}`);
85
85
  }
86
86
  }
87
+ /** A non-blocking lock for background work. Uses the same files as withFileLock. */
88
+ export function tryFileLock(filePath) {
89
+ const lockPath = filePath + ".lock";
90
+ const owner = `${process.pid}\n${Date.now()}\n${Math.random()}`;
91
+ fs.mkdirSync(path.dirname(lockPath), { recursive: true });
92
+ for (let attempt = 0; attempt < 2; attempt++) {
93
+ try {
94
+ fs.writeFileSync(lockPath, owner, { flag: "wx", mode: 0o600 });
95
+ return () => {
96
+ try {
97
+ if (fs.readFileSync(lockPath, "utf8") === owner)
98
+ fs.unlinkSync(lockPath);
99
+ }
100
+ catch { /* already released */ }
101
+ };
102
+ }
103
+ catch (err) {
104
+ if (err.code !== "EEXIST")
105
+ throw err;
106
+ try {
107
+ const contents = fs.readFileSync(lockPath, "utf8");
108
+ const pid = Number.parseInt(contents.split("\n")[0], 10);
109
+ if (pid > 0) {
110
+ try {
111
+ process.kill(pid, 0);
112
+ return null;
113
+ }
114
+ catch (error) {
115
+ if (error.code !== "ESRCH")
116
+ return null;
117
+ }
118
+ }
119
+ else if (Date.now() - fs.statSync(lockPath).mtimeMs < 30_000) {
120
+ return null;
121
+ }
122
+ if (fs.readFileSync(lockPath, "utf8") === contents)
123
+ fs.unlinkSync(lockPath);
124
+ }
125
+ catch {
126
+ return null;
127
+ }
128
+ }
129
+ }
130
+ return null;
131
+ }
87
132
  // Q10: withFileLock now accepts both sync and async callbacks.
88
133
  // When the callback returns a Promise, the lock file is held until the
89
134
  // Promise settles — preventing concurrent processes from seeing partial state.
package/dist/index.js CHANGED
@@ -41,6 +41,17 @@ function cleanStaleLocks(phrenPath) {
41
41
  try {
42
42
  const stat = fs.statSync(lockPath);
43
43
  if (Date.now() - stat.mtimeMs > STALE_LOCK_MS) {
44
+ const pid = Number.parseInt(fs.readFileSync(lockPath, "utf8").split("\n")[0], 10);
45
+ if (pid > 0) {
46
+ try {
47
+ process.kill(pid, 0);
48
+ continue;
49
+ }
50
+ catch (err) {
51
+ if (err.code !== "ESRCH")
52
+ continue;
53
+ }
54
+ }
44
55
  fs.unlinkSync(lockPath);
45
56
  debugLog(`Cleaned stale lock: ${entry}`);
46
57
  }
@@ -95,12 +106,12 @@ async function main() {
95
106
  let writeQueueDepth = 0;
96
107
  const MAX_QUEUE_DEPTH = 50;
97
108
  const WRITE_TIMEOUT_MS = 30_000;
98
- async function rebuildIndex() {
109
+ async function rebuildIndex(force = false) {
99
110
  runCustomHooks(phrenPath, "pre-index");
100
111
  const oldDb = db;
101
112
  try {
102
113
  indexReady = false;
103
- db = await buildIndex(phrenPath, profile);
114
+ db = await buildIndex(phrenPath, profile, { force });
104
115
  indexReady = true;
105
116
  // buildIndex() hands back its cached handle inside the debounce
106
117
  // window, so oldDb can be the very database we just installed.
@@ -252,10 +263,35 @@ async function main() {
252
263
  const transport = new StdioServerTransport();
253
264
  await server.connect(transport);
254
265
  console.error(`phren-mcp running (${phrenPath}) · profile ${mcpProfile} · ${gate.exposed.size} tools`);
266
+ const { startPullPolling } = await import("./sync/pull.js");
267
+ const { refreshLinkedContext } = await import("./link/refresh.js");
268
+ const polling = startPullPolling(phrenPath, {
269
+ onChange: async () => {
270
+ // Index refresh still succeeds if an external mirror is temporarily unwritable.
271
+ try {
272
+ refreshLinkedContext(phrenPath, profile);
273
+ }
274
+ catch (err) {
275
+ logger.warn("periodic-pull", `context refresh: ${errorMessage(err)}`);
276
+ }
277
+ await rebuildIndex(true);
278
+ },
279
+ runExclusive: (fn) => {
280
+ // Network calls have their own timeouts. Do not release the queue while
281
+ // an underlying Git operation is still running, as Promise.race would.
282
+ const run = writeQueue.then(fn);
283
+ writeQueue = run.catch((err) => { logger.warn("periodic-pull", errorMessage(err)); });
284
+ return run;
285
+ },
286
+ });
287
+ server.server.onclose = () => { void shutdown("transport closed"); };
255
288
  // Graceful shutdown: drain write queue and close DB before exit
256
289
  async function shutdown(signal) {
290
+ if (shuttingDown)
291
+ return;
257
292
  shuttingDown = true;
258
293
  structuredLog("info", "shutdown", `Received ${signal}, draining write queue...`);
294
+ await polling.stop();
259
295
  try {
260
296
  await writeQueue;
261
297
  }
@@ -44,6 +44,8 @@ export interface InstallPreferences {
44
44
  managedPrePromptSiblingCommands?: string[];
45
45
  /** Whether the user intended cross-machine sync ("sync") or local-only ("local"). */
46
46
  syncIntent?: "sync" | "local";
47
+ /** Seconds between MCP remote checks. 0 disables periodic pulls (the default). */
48
+ pullIntervalSeconds?: number;
47
49
  }
48
50
  export declare function governanceInstallPreferencesFile(phrenPath: string): string;
49
51
  export declare function readInstallPreferences(phrenPath: string): InstallPreferences;
@@ -0,0 +1 @@
1
+ export declare function refreshLinkedContext(phrenPath: string, profile: string): void;
@@ -0,0 +1,47 @@
1
+ /** Refresh existing managed context destinations after a store pull, without relinking the installation. */
2
+ import * as fs from "fs";
3
+ import * as path from "path";
4
+ import { atomicWriteText, homePath } from "../phren-paths.js";
5
+ import { getProjectDirs } from "../shared.js";
6
+ import { readProjectConfig, getProjectSourcePath, getProjectOwnershipMode } from "../project-config.js";
7
+ import { findProjectDir } from "../project-locator.js";
8
+ import { resolveManagementCapabilities } from "../init/management-preset.js";
9
+ import { syncScopeSkillsToDir } from "../skill/files.js";
10
+ import { buildSkillManifest, renderSkillInstructionsSection } from "../skill/registry.js";
11
+ export function refreshLinkedContext(phrenPath, profile) {
12
+ const caps = resolveManagementCapabilities(phrenPath);
13
+ if (caps.installSkillLinks) {
14
+ for (const tool of [".claude", ".copilot"]) {
15
+ const dir = homePath(tool, "skills");
16
+ if (fs.existsSync(path.join(path.dirname(dir), "skill-manifest.json")))
17
+ syncScopeSkillsToDir(phrenPath, "global", dir);
18
+ }
19
+ }
20
+ if (!caps.repoMirroring)
21
+ return;
22
+ for (const source of getProjectDirs(phrenPath, profile)) {
23
+ const project = path.basename(source);
24
+ if (project === "global")
25
+ continue;
26
+ const config = readProjectConfig(phrenPath, project);
27
+ if (getProjectOwnershipMode(phrenPath, project, config) !== "phren-managed")
28
+ continue;
29
+ const target = getProjectSourcePath(phrenPath, project, config) ?? findProjectDir(project);
30
+ if (!target || !fs.existsSync(target))
31
+ continue;
32
+ const skillsDir = path.join(target, ".claude", "skills");
33
+ const manifest = config.skills !== false && fs.existsSync(path.join(target, ".claude", "skill-manifest.json"))
34
+ ? syncScopeSkillsToDir(phrenPath, project, skillsDir)
35
+ : buildSkillManifest(phrenPath, profile, project);
36
+ const agentsPath = path.join(target, "AGENTS.md");
37
+ const claudePath = path.join(source, "CLAUDE.md");
38
+ // The generated file is a snapshot, unlike the live CLAUDE.md symlink.
39
+ // Preserve native/user-owned instructions and installations without a Codex mirror.
40
+ if (!fs.existsSync(agentsPath) || !fs.existsSync(claudePath) || fs.lstatSync(agentsPath).isSymbolicLink())
41
+ continue;
42
+ const marker = "<!-- phren:generated-agents -->";
43
+ if (!fs.readFileSync(agentsPath, "utf8").includes(marker))
44
+ continue;
45
+ atomicWriteText(agentsPath, `${fs.readFileSync(claudePath, "utf8").trimEnd()}\n\n${marker}\n${renderSkillInstructionsSection(manifest)}\n`);
46
+ }
47
+ }