@phren/cli 0.2.10 → 0.2.12

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
@@ -3,6 +3,7 @@ import { listMachines as listMachinesStore, listProfiles as listProfilesStore }
3
3
  import { setTelemetryEnabled, getTelemetrySummary, resetTelemetry } from "../telemetry.js";
4
4
  import { readInstallPreferences, updateInstallPreferences } from "../init/preferences.js";
5
5
  import { resolveMcpProfile } from "../mcp/profile.js";
6
+ import { parsePullInterval, resolvePullInterval, periodicPullEnabled } from "../sync/pull.js";
6
7
  import * as path from "path";
7
8
  import { buildConfigView } from "../config/resolve.js";
8
9
  import { CONFIG_DOMAINS } from "../config/schema.js";
@@ -119,6 +120,8 @@ export async function handleConfig(args) {
119
120
  return handleConfigTelemetry(rest);
120
121
  case "mcp-profile":
121
122
  return handleConfigMcpProfile(rest);
123
+ case "pull-interval":
124
+ return handleConfigPullInterval(rest);
122
125
  case "proactivity":
123
126
  case "proactivity.findings":
124
127
  case "proactivity.tasks":
@@ -164,6 +167,8 @@ Subcommands:
164
167
  Manage project learned synonyms
165
168
  phren config machines Registered machines and profiles
166
169
  phren config profiles All profiles and their projects
170
+ phren config pull-interval [seconds|off]
171
+ Periodic MCP remote checks (default: off)
167
172
  phren config telemetry [on|off|reset] Local usage stats (opt-in, no external reporting)`);
168
173
  if (sub) {
169
174
  console.error(`\nUnknown config subcommand: "${sub}"`);
@@ -172,6 +177,28 @@ Subcommands:
172
177
  }
173
178
  }
174
179
  // ── Machines and profiles ────────────────────────────────────────────────────
180
+ function handleConfigPullInterval(args) {
181
+ const phrenPath = getPhrenPath();
182
+ if (args.length > 0) {
183
+ const seconds = parsePullInterval(args[0]);
184
+ if (seconds === undefined || args.length !== 1) {
185
+ console.error("Use phren config pull-interval <seconds|off>: 0 disables polling; otherwise use a whole number from 30 to 86400.");
186
+ process.exitCode = 1;
187
+ return;
188
+ }
189
+ updateInstallPreferences(phrenPath, () => ({ pullIntervalSeconds: seconds }));
190
+ console.log(seconds === 0 ? "Periodic pulls disabled on this machine." : `Periodic remote checks set to every ${seconds} seconds on this machine.`);
191
+ }
192
+ const seconds = resolvePullInterval(phrenPath);
193
+ const source = process.env.PHREN_PULL_INTERVAL_SECONDS !== undefined
194
+ && parsePullInterval(process.env.PHREN_PULL_INTERVAL_SECONDS) !== undefined
195
+ ? "PHREN_PULL_INTERVAL_SECONDS" : readInstallPreferences(phrenPath).pullIntervalSeconds !== undefined ? "install preferences" : "default";
196
+ console.log(`Pull interval: ${seconds === 0 ? "off" : `${seconds} seconds`} (${source}).`);
197
+ if (!periodicPullEnabled(phrenPath))
198
+ console.log("Periodic pulls are inactive for this install mode or management preset.");
199
+ else
200
+ console.log("Running MCP servers pick up changes automatically. Only changed remotes are fetched; updates are fast-forward only.");
201
+ }
175
202
  function handleConfigMachines() {
176
203
  const manifest = readRootManifest(getPhrenPath());
177
204
  if (manifest?.installMode === "project-local") {
@@ -239,8 +239,8 @@ export function handleSkillsNamespace(args, profile) {
239
239
  console.error(`Skill not found: "${name}" in "${scope}"`);
240
240
  process.exit(1);
241
241
  }
242
- setSkillEnabledAndSync(getPhrenPath(), scope, resolved.name, subcommand === "enable");
243
- console.log(`${subcommand === "enable" ? "Enabled" : "Disabled"} skill ${resolved.name} in ${scope}.`);
242
+ setSkillEnabledAndSync(getPhrenPath(), resolved.source, resolved.name, subcommand === "enable");
243
+ console.log(`${subcommand === "enable" ? "Enabled" : "Disabled"} skill ${resolved.name} in ${resolved.source}${resolved.source === "global" ? " (all projects)" : ""}.`);
244
244
  return;
245
245
  }
246
246
  if (subcommand === "remove") {
@@ -27,6 +27,12 @@ export declare function hasUnrelatedHistories(cwd: string): Promise<boolean>;
27
27
  */
28
28
  export declare const TEAM_STORE_PATHSPECS: readonly ["*/journal/*", "*/tasks.md", "*/truths.md", "*/FINDINGS.md", "*/FINDINGS.md.bak", "*/summary.md", "*/review.md", "*/CLAUDE.md", "*/topic-config.json", "*/phren.project.yaml", "*/reference/**", "*/skills/**", "*/notes/**", ".phren-team.yaml"];
29
29
  export declare function countUnsyncedCommits(cwd: string): Promise<number>;
30
+ /** Startup pulls share the store's Git lock and clean up only rebases they started. */
31
+ export declare function pullAtSessionStart(cwd: string): Promise<{
32
+ ok: boolean;
33
+ output?: string;
34
+ error?: string;
35
+ }>;
30
36
  export declare function recoverPushConflict(cwd: string): Promise<{
31
37
  ok: boolean;
32
38
  detail: string;
@@ -8,6 +8,8 @@ import * as path from "path";
8
8
  import { EXEC_TIMEOUT_MS, debugLog, errorMessage, } from "./hooks-context.js";
9
9
  import { runGit } from "../utils.js";
10
10
  import { isTaskFileName } from "../data/tasks.js";
11
+ import { withFileLock } from "../governance/locks.js";
12
+ import { runtimeFile } from "../phren-paths.js";
11
13
  import { autoMergeConflicts, mergeTask, mergeFindings, } from "../shared/content.js";
12
14
  export function getGitContext(cwd) {
13
15
  if (!cwd)
@@ -126,6 +128,30 @@ export async function countUnsyncedCommits(cwd) {
126
128
  const parsed = Number.parseInt(ahead.output.trim(), 10);
127
129
  return Number.isNaN(parsed) ? 0 : parsed;
128
130
  }
131
+ /** Startup pulls share the store's Git lock and clean up only rebases they started. */
132
+ export async function pullAtSessionStart(cwd) {
133
+ try {
134
+ return await withFileLock(runtimeFile(cwd, "git-op"), async () => {
135
+ const gitDir = await runBestEffortGit(["rev-parse", "--absolute-git-dir"], cwd);
136
+ if (!gitDir.ok || !gitDir.output)
137
+ return { ok: false, error: gitDir.error || "Cannot locate Git directory." };
138
+ const rebasing = () => ["rebase-merge", "rebase-apply"].some((name) => fs.existsSync(path.join(gitDir.output, name)));
139
+ if (rebasing() || ["MERGE_HEAD", "CHERRY_PICK_HEAD", "REVERT_HEAD", "sequencer"].some((name) => fs.existsSync(path.join(gitDir.output, name)))) {
140
+ return { ok: false, error: "Store already has a Git operation in progress; session-start pull deferred." };
141
+ }
142
+ const result = await runBestEffortGit(["pull", "--rebase", "--quiet"], cwd);
143
+ if (!result.ok && rebasing()) {
144
+ const abort = await runBestEffortGit(["rebase", "--abort"], cwd);
145
+ if (!abort.ok)
146
+ return { ok: false, error: `${result.error}; rebase cleanup failed: ${abort.error}` };
147
+ }
148
+ return result;
149
+ });
150
+ }
151
+ catch (err) {
152
+ return { ok: false, error: errorMessage(err) };
153
+ }
154
+ }
129
155
  // ── Merge helpers ───────────────────────────────────────────────────────────
130
156
  function isMergeableMarkdown(relPath) {
131
157
  const filename = path.basename(relPath).toLowerCase();
@@ -11,7 +11,7 @@ import { FINDINGS_FILENAME } from "../data/access.js";
11
11
  import { readInstallPreferences } from "../init/preferences.js";
12
12
  import { logger } from "../logger.js";
13
13
  import { sessionFileForId, readSessionStateFile, writeSessionStateFile, } from "../session/utils.js";
14
- import { runBestEffortGit, countUnsyncedCommits } from "./session-git.js";
14
+ import { runBestEffortGit, countUnsyncedCommits, pullAtSessionStart } from "./session-git.js";
15
15
  import { scheduleBackgroundMaintenance } from "./session-background.js";
16
16
  import { runDoctor } from "./hooks-context.js";
17
17
  const SESSION_START_ONBOARDING_MARKER = "session-start-onboarding-v1";
@@ -146,7 +146,7 @@ export async function handleHookSessionStart() {
146
146
  const pull = !gitRepo.ok
147
147
  ? { ok: false, error: gitRepo.detail }
148
148
  : hasRemote
149
- ? await runBestEffortGit(["pull", "--rebase", "--quiet"], phrenPath)
149
+ ? await pullAtSessionStart(phrenPath)
150
150
  : {
151
151
  ok: true,
152
152
  output: gitRepo.initialized
@@ -182,7 +182,7 @@ export async function handleHookSessionStart() {
182
182
  if (!fs.existsSync(store.path) || !fs.existsSync(path.join(store.path, ".git")))
183
183
  continue;
184
184
  try {
185
- await runBestEffortGit(["pull", "--rebase", "--quiet"], store.path);
185
+ await pullAtSessionStart(store.path);
186
186
  }
187
187
  catch (err) {
188
188
  debugLog(`session-start store-pull ${store.name}: ${errorMessage(err)}`);
@@ -505,63 +505,65 @@ export async function handleBackgroundSync() {
505
505
  const now = new Date().toISOString();
506
506
  const lockPath = runtimeFile(phrenPathLocal, "background-sync.lock");
507
507
  try {
508
- const previousSync = getRuntimeHealth(phrenPathLocal).lastSync;
509
- const record = (autoSaveStatus, patch, detail) => {
510
- updateRuntimeHealth(phrenPathLocal, {
511
- lastAutoSave: { at: now, status: autoSaveStatus, detail },
512
- lastSync: nextSyncStatus(previousSync, patch, now),
513
- });
514
- appendAuditLog(phrenPathLocal, "background_sync", `status=${patch.lastPushStatus} detail=${JSON.stringify(detail)}`);
515
- };
516
- const remotes = await runBestEffortGit(["remote"], phrenPathLocal);
517
- if (!remotes.ok || !remotes.output) {
508
+ await withFileLock(runtimeFile(phrenPathLocal, "git-op"), async () => {
509
+ const previousSync = getRuntimeHealth(phrenPathLocal).lastSync;
510
+ const record = (autoSaveStatus, patch, detail) => {
511
+ updateRuntimeHealth(phrenPathLocal, {
512
+ lastAutoSave: { at: now, status: autoSaveStatus, detail },
513
+ lastSync: nextSyncStatus(previousSync, patch, now),
514
+ });
515
+ appendAuditLog(phrenPathLocal, "background_sync", `status=${patch.lastPushStatus} detail=${JSON.stringify(detail)}`);
516
+ };
517
+ const remotes = await runBestEffortGit(["remote"], phrenPathLocal);
518
+ if (!remotes.ok || !remotes.output) {
519
+ const unsyncedCommits = await countUnsyncedCommits(phrenPathLocal);
520
+ const detail = "background sync skipped; no remote configured";
521
+ record("saved-local", { lastPushAt: now, lastPushStatus: "saved-local", lastPushDetail: detail, unsyncedCommits }, detail);
522
+ return;
523
+ }
524
+ const push = await runBestEffortGit(["push"], phrenPathLocal);
525
+ if (push.ok) {
526
+ const detail = "commit pushed by background sync";
527
+ record("saved-pushed", { lastPushAt: now, lastPushStatus: "saved-pushed", lastPushDetail: detail, unsyncedCommits: 0 }, detail);
528
+ return;
529
+ }
530
+ const recovered = await recoverPushConflict(phrenPathLocal);
531
+ if (recovered.ok) {
532
+ record("saved-pushed", {
533
+ lastPushAt: now,
534
+ lastPushStatus: "saved-pushed",
535
+ lastPushDetail: recovered.detail,
536
+ lastPullAt: now,
537
+ lastPullStatus: recovered.pullStatus,
538
+ lastPullDetail: recovered.pullDetail,
539
+ lastSuccessfulPullAt: now,
540
+ unsyncedCommits: 0,
541
+ }, recovered.detail);
542
+ return;
543
+ }
544
+ // The push leg genuinely failed. Report *which* leg failed instead of the
545
+ // old success-shaped "saved-local", and name the unrelated-histories case
546
+ // specifically — no retry will ever clear it, so a generic "pull failed"
547
+ // would send the user chasing the wrong problem.
518
548
  const unsyncedCommits = await countUnsyncedCommits(phrenPathLocal);
519
- const detail = "background sync skipped; no remote configured";
520
- record("saved-local", { lastPushAt: now, lastPushStatus: "saved-local", lastPushDetail: detail, unsyncedCommits }, detail);
521
- return;
522
- }
523
- const push = await runBestEffortGit(["push"], phrenPathLocal);
524
- if (push.ok) {
525
- const detail = "commit pushed by background sync";
526
- record("saved-pushed", { lastPushAt: now, lastPushStatus: "saved-pushed", lastPushDetail: detail, unsyncedCommits: 0 }, detail);
527
- return;
528
- }
529
- const recovered = await recoverPushConflict(phrenPathLocal);
530
- if (recovered.ok) {
531
- record("saved-pushed", {
549
+ const unrelated = recovered.pullStatus === "error" && await hasUnrelatedHistories(phrenPathLocal);
550
+ const pushStatus = unrelated
551
+ ? "unrelated-histories"
552
+ : recovered.pullStatus === "error" ? "pull-failed" : "push-failed";
553
+ const failDetail = unrelated
554
+ ? `local and remote histories are unrelated (no merge base) — the remote was most likely re-initialized. ` +
555
+ `Reconcile manually: cd ${phrenPathLocal} && git fetch && git log --oneline origin/HEAD`
556
+ : (recovered.detail || push.error || "background sync push failed");
557
+ record("sync-failed", {
532
558
  lastPushAt: now,
533
- lastPushStatus: "saved-pushed",
534
- lastPushDetail: recovered.detail,
559
+ lastPushStatus: pushStatus,
560
+ lastPushDetail: failDetail,
535
561
  lastPullAt: now,
536
562
  lastPullStatus: recovered.pullStatus,
537
563
  lastPullDetail: recovered.pullDetail,
538
- lastSuccessfulPullAt: now,
539
- unsyncedCommits: 0,
540
- }, recovered.detail);
541
- return;
542
- }
543
- // The push leg genuinely failed. Report *which* leg failed instead of the
544
- // old success-shaped "saved-local", and name the unrelated-histories case
545
- // specifically — no retry will ever clear it, so a generic "pull failed"
546
- // would send the user chasing the wrong problem.
547
- const unsyncedCommits = await countUnsyncedCommits(phrenPathLocal);
548
- const unrelated = recovered.pullStatus === "error" && await hasUnrelatedHistories(phrenPathLocal);
549
- const pushStatus = unrelated
550
- ? "unrelated-histories"
551
- : recovered.pullStatus === "error" ? "pull-failed" : "push-failed";
552
- const failDetail = unrelated
553
- ? `local and remote histories are unrelated (no merge base) — the remote was most likely re-initialized. ` +
554
- `Reconcile manually: cd ${phrenPathLocal} && git fetch && git log --oneline origin/HEAD`
555
- : (recovered.detail || push.error || "background sync push failed");
556
- record("sync-failed", {
557
- lastPushAt: now,
558
- lastPushStatus: pushStatus,
559
- lastPushDetail: failDetail,
560
- lastPullAt: now,
561
- lastPullStatus: recovered.pullStatus,
562
- lastPullDetail: recovered.pullDetail,
563
- unsyncedCommits,
564
- }, failDetail);
564
+ unsyncedCommits,
565
+ }, failDetail);
566
+ });
565
567
  }
566
568
  finally {
567
569
  try {
@@ -35,7 +35,7 @@ export interface Command {
35
35
  hidden?: boolean;
36
36
  run: RunFn;
37
37
  }
38
- export declare const ENV_HELP = "Environment variables:\n PHREN_PATH Override phren directory (default: ~/.phren)\n PHREN_PROFILE Active profile name\n PHREN_DEBUG Enable debug logging (set to 1)\n\n Embeddings:\n PHREN_OLLAMA_URL Ollama base URL (default: http://localhost:11434, 'off' to disable)\n PHREN_EMBEDDING_API_URL OpenAI-compatible /embeddings endpoint\n PHREN_EMBEDDING_API_KEY API key for embedding endpoint\n PHREN_EMBEDDING_MODEL Embedding model (default: nomic-embed-text)\n\n Context injection:\n PHREN_CONTEXT_TOKEN_BUDGET Max tokens injected per prompt (default: 550)\n PHREN_MAX_INJECT_TOKENS Hard cap on total injected tokens (default: 2000)\n PHREN_HOOK_TIMEOUT_MS Hook subprocess timeout in ms (default: 14000)\n\n Feature flags:\n PHREN_FEATURE_AGENTS=1 Show running coding agents on the graph\n PHREN_FEATURE_TOOL_HOOK=0 Skip the PostToolUse subprocess (perf)\n PHREN_FEATURE_AUTO_EXTRACT=0 Disable auto memory extraction\n PHREN_FEATURE_AUTO_CAPTURE=1 Extract insights from conversations\n PHREN_FEATURE_SEMANTIC_DEDUP=1 LLM-based dedup on add_finding\n PHREN_FEATURE_HYBRID_SEARCH=0 Disable TF-IDF cosine fallback\n\n Run 'phren help all' to see everything.\n";
38
+ export declare const ENV_HELP = "Environment variables:\n PHREN_PATH Override phren directory (default: ~/.phren)\n PHREN_PROFILE Active profile name\n PHREN_DEBUG Enable debug logging (set to 1)\n PHREN_PULL_INTERVAL_SECONDS Remote check interval in seconds (default: off; 0 disables)\n\n Embeddings:\n PHREN_OLLAMA_URL Ollama base URL (default: http://localhost:11434, 'off' to disable)\n PHREN_EMBEDDING_API_URL OpenAI-compatible /embeddings endpoint\n PHREN_EMBEDDING_API_KEY API key for embedding endpoint\n PHREN_EMBEDDING_MODEL Embedding model (default: nomic-embed-text)\n\n Context injection:\n PHREN_CONTEXT_TOKEN_BUDGET Max tokens injected per prompt (default: 550)\n PHREN_MAX_INJECT_TOKENS Hard cap on total injected tokens (default: 2000)\n PHREN_HOOK_TIMEOUT_MS Hook subprocess timeout in ms (default: 14000)\n\n Feature flags:\n PHREN_FEATURE_AGENTS=1 Show running coding agents on the graph\n PHREN_FEATURE_TOOL_HOOK=0 Skip the PostToolUse subprocess (perf)\n PHREN_FEATURE_AUTO_EXTRACT=0 Disable auto memory extraction\n PHREN_FEATURE_AUTO_CAPTURE=1 Extract insights from conversations\n PHREN_FEATURE_SEMANTIC_DEDUP=1 LLM-based dedup on add_finding\n PHREN_FEATURE_HYBRID_SEARCH=0 Disable TF-IDF cosine fallback\n\n Run 'phren help all' to see everything.\n";
39
39
  export declare const DOC_TOPICS: Record<string, string>;
40
40
  export declare const REGISTRY: Command[];
41
41
  export declare function lookupCommand(name: string): Command | undefined;
@@ -30,6 +30,7 @@ export const ENV_HELP = `Environment variables:
30
30
  PHREN_PATH Override phren directory (default: ~/.phren)
31
31
  PHREN_PROFILE Active profile name
32
32
  PHREN_DEBUG Enable debug logging (set to 1)
33
+ PHREN_PULL_INTERVAL_SECONDS Remote check interval in seconds (default: off; 0 disables)
33
34
 
34
35
  Embeddings:
35
36
  PHREN_OLLAMA_URL Ollama base URL (default: http://localhost:11434, 'off' to disable)
@@ -95,6 +96,7 @@ const CONFIG_SUBCOMMANDS = [
95
96
  { name: "profiles", usage: "phren config profiles", summary: "Profiles and projects" },
96
97
  { name: "telemetry", usage: "phren config telemetry [on|off]", summary: "Opt-in usage telemetry" },
97
98
  { name: "mcp-profile", usage: "phren config mcp-profile [core|full]", summary: "MCP tool surface: 10 core tools or all of them" },
99
+ { name: "pull-interval", usage: "phren config pull-interval [seconds|off]", summary: "Periodic MCP remote checks (default: off; 0 disables)" },
98
100
  ];
99
101
  const MAINTAIN_SUBCOMMANDS = [
100
102
  { name: "govern", usage: "phren maintain govern [project]", summary: "Queue stale memories for review" },
@@ -117,6 +119,15 @@ const TEAM_SUBCOMMANDS = [
117
119
  ];
118
120
  // ── Registry ─────────────────────────────────────────────────────────────────
119
121
  export const REGISTRY = [
122
+ {
123
+ name: "bridge", topic: "setup", usage: "phren bridge <install|status|doctor|update|rollback|uninstall>",
124
+ summary: "Install and manage Phren Hook for iPhone agent connections",
125
+ run: async (args) => {
126
+ const { runBridge } = await import("./bridge/command.js");
127
+ const { VERSION } = await import("./package-metadata.js");
128
+ return runBridge(args, VERSION);
129
+ },
130
+ },
120
131
  // Setup (featured: init, quickstart)
121
132
  {
122
133
  name: "init",