@phren/cli 0.2.16 → 0.3.1

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 (102) hide show
  1. package/dist/bridge/agent-hooks.d.ts +17 -6
  2. package/dist/bridge/agent-hooks.js +59 -24
  3. package/dist/bridge/claude-question-dialog.d.ts +65 -0
  4. package/dist/bridge/claude-question-dialog.js +210 -0
  5. package/dist/bridge/code-note.d.ts +2 -1
  6. package/dist/bridge/code-note.js +13 -4
  7. package/dist/bridge/code-routes.d.ts +32 -14
  8. package/dist/bridge/code-routes.js +131 -8
  9. package/dist/bridge/command.js +92 -2
  10. package/dist/bridge/computers.d.ts +5 -0
  11. package/dist/bridge/computers.js +10 -4
  12. package/dist/bridge/conductor-group.d.ts +23 -0
  13. package/dist/bridge/conductor-group.js +25 -0
  14. package/dist/bridge/dispatch-returns.d.ts +2 -0
  15. package/dist/bridge/dispatch-returns.js +12 -8
  16. package/dist/bridge/dispatch.d.ts +4 -1
  17. package/dist/bridge/dispatch.js +30 -5
  18. package/dist/bridge/hand-off.js +5 -1
  19. package/dist/bridge/herdr.d.ts +7 -0
  20. package/dist/bridge/herdr.js +53 -2
  21. package/dist/bridge/install.d.ts +0 -4
  22. package/dist/bridge/install.js +3 -3
  23. package/dist/bridge/link.d.ts +48 -0
  24. package/dist/bridge/link.js +136 -0
  25. package/dist/bridge/memory-store.d.ts +23 -0
  26. package/dist/bridge/memory-store.js +152 -0
  27. package/dist/bridge/pair.d.ts +46 -0
  28. package/dist/bridge/pair.js +240 -0
  29. package/dist/bridge/peers.d.ts +9 -0
  30. package/dist/bridge/peers.js +25 -2
  31. package/dist/bridge/protocol.js +20 -1
  32. package/dist/bridge/schedule-watch.d.ts +2 -0
  33. package/dist/bridge/schedule-watch.js +16 -3
  34. package/dist/bridge/server-launch.d.ts +9 -0
  35. package/dist/bridge/server-launch.js +34 -11
  36. package/dist/bridge/server-pane-routes.d.ts +7 -0
  37. package/dist/bridge/server-pane-routes.js +128 -18
  38. package/dist/bridge/server-routes.d.ts +3 -0
  39. package/dist/bridge/server-routes.js +55 -29
  40. package/dist/bridge/server-stream.js +4 -1
  41. package/dist/bridge/speech-key.d.ts +33 -0
  42. package/dist/bridge/speech-key.js +106 -0
  43. package/dist/bridge/speech-transcribe.js +1 -1
  44. package/dist/bridge/speech.d.ts +1 -3
  45. package/dist/bridge/speech.js +2 -16
  46. package/dist/bridge/transcript-preview.d.ts +2 -0
  47. package/dist/bridge/transcript-preview.js +15 -0
  48. package/dist/bridge-hook.mjs +9940 -3601
  49. package/dist/cli/config-policy.js +25 -0
  50. package/dist/cli/extract.d.ts +0 -8
  51. package/dist/cli/extract.js +1 -1
  52. package/dist/cli-handlers.js +6 -0
  53. package/dist/cli-registry.js +21 -9
  54. package/dist/content/learning.js +1 -1
  55. package/dist/content/validate.d.ts +14 -3
  56. package/dist/content/validate.js +174 -114
  57. package/dist/data/access.d.ts +9 -0
  58. package/dist/data/access.js +18 -0
  59. package/dist/data/tasks.d.ts +26 -0
  60. package/dist/data/tasks.js +72 -1
  61. package/dist/entrypoint.js +7 -0
  62. package/dist/generated/memory-ui-graph.browser.js +520 -410
  63. package/dist/governance/policy.js +4 -3
  64. package/dist/governance/rbac.d.ts +1 -1
  65. package/dist/governance/rbac.js +1 -0
  66. package/dist/hooks.d.ts +0 -15
  67. package/dist/hooks.js +1 -1
  68. package/dist/init/init-uninstall.js +13 -3
  69. package/dist/init/init-walkthrough.d.ts +10 -0
  70. package/dist/init/init-walkthrough.js +24 -1
  71. package/dist/init/init.d.ts +5 -0
  72. package/dist/init/init.js +54 -32
  73. package/dist/init/setup.js +19 -5
  74. package/dist/init/store-gitignore.d.ts +0 -5
  75. package/dist/init/store-gitignore.js +0 -8
  76. package/dist/link/context-imports.d.ts +15 -0
  77. package/dist/link/context-imports.js +101 -0
  78. package/dist/link/doctor.js +38 -4
  79. package/dist/mcp/profile.d.ts +0 -4
  80. package/dist/mcp/profile.js +2 -14
  81. package/dist/memory-ui-graph.runtime.js +520 -410
  82. package/dist/modules/code-package.js +10 -2
  83. package/dist/modules/config.d.ts +7 -0
  84. package/dist/modules/config.js +17 -0
  85. package/dist/modules/registry.js +6 -5
  86. package/dist/profile-store.js +39 -3
  87. package/dist/project-topics.d.ts +1 -0
  88. package/dist/project-topics.js +9 -6
  89. package/dist/shared/retrieval.d.ts +0 -2
  90. package/dist/shared/retrieval.js +1 -1
  91. package/dist/sync/task-claim.d.ts +22 -0
  92. package/dist/sync/task-claim.js +45 -0
  93. package/dist/tools/code.js +29 -21
  94. package/dist/tools/config.js +3 -0
  95. package/dist/tools/dispatch.js +3 -3
  96. package/dist/tools/finding.d.ts +11 -0
  97. package/dist/tools/finding.js +154 -99
  98. package/dist/tools/tasks.js +40 -1
  99. package/dist/ui/server.js +18 -1
  100. package/dist/update.js +21 -10
  101. package/package.json +8 -7
  102. package/starter/global/skills/conductor/SKILL.md +42 -10
@@ -26,6 +26,14 @@ function npmPath() {
26
26
  entries.push(entry);
27
27
  return entries.join(path.delimiter);
28
28
  }
29
+ /** Run npm. On Windows npm is `npm.cmd`, which only a shell can start (a
30
+ * plain spawn of it fails with EINVAL), and the shell needs each argument quoted. */
31
+ function npm(args, options) {
32
+ const env = { ...process.env, PATH: npmPath() };
33
+ if (process.platform !== "win32")
34
+ return String(execFileSync("npm", args, { ...options, env }) ?? "");
35
+ return String(execFileSync("npm.cmd", args.map(arg => `"${arg}"`), { ...options, env, shell: true }) ?? "");
36
+ }
29
37
  /** The entry file an installed package declares, without executing anything. */
30
38
  function packageEntry(directory) {
31
39
  const manifest = JSON.parse(fs.readFileSync(path.join(directory, "package.json"), "utf8"));
@@ -43,7 +51,7 @@ async function importDirectory(directory) {
43
51
  }
44
52
  function globalPackageDirectory() {
45
53
  try {
46
- const root = execFileSync("npm", ["root", "-g"], { encoding: "utf8", timeout: 10_000, env: { ...process.env, PATH: npmPath() } }).trim();
54
+ const root = npm(["root", "-g"], { encoding: "utf8", timeout: 10_000 }).trim();
47
55
  return root ? path.join(root, "@phren", "code") : undefined;
48
56
  }
49
57
  catch {
@@ -134,7 +142,7 @@ export async function installCodePackage(store) {
134
142
  return code;
135
143
  }
136
144
  try {
137
- execFileSync("npm", ["install", "--prefix", packages, "@phren/code"], { stdio: "inherit", timeout: 120_000, env: { ...process.env, PATH: npmPath() } });
145
+ npm(["install", "--prefix", packages, "@phren/code"], { stdio: "inherit", timeout: 120_000 });
138
146
  }
139
147
  catch {
140
148
  throw new Error(`${CODE_PACKAGE_HINT}\nInstallation failed. Run: npm install --prefix ${packages} @phren/code`);
@@ -2,3 +2,10 @@ export declare function setModuleEnabled(store: string, name: string, value: boo
2
2
  /** Freeze legacy surfaces before runtime defaults can change an existing install. */
3
3
  export declare function migrateModules(store: string, hookInstalled?: boolean): void;
4
4
  export declare function initializeModules(store: string): void;
5
+ /**
6
+ * `phren pair` and `phren bridge install` are how a person asks for the Hook,
7
+ * so they turn its module on instead of refusing. Returns true when this
8
+ * call enabled it. Without a store there is nothing to record; the Hook's
9
+ * legacy default already allows it there.
10
+ */
11
+ export declare function enableHookForPhone(store: string): boolean;
@@ -68,3 +68,20 @@ export function initializeModules(store) {
68
68
  atomicWriteText(file, yaml.dump({ version: 1, enabled: Object.fromEntries(BUILTIN_MODULES.map(module => [module.name, module.defaultEnabled])) }, { noRefs: true }));
69
69
  });
70
70
  }
71
+ /**
72
+ * `phren pair` and `phren bridge install` are how a person asks for the Hook,
73
+ * so they turn its module on instead of refusing. Returns true when this
74
+ * call enabled it. Without a store there is nothing to record; the Hook's
75
+ * legacy default already allows it there.
76
+ */
77
+ export function enableHookForPhone(store) {
78
+ const hasStore = !!readConfig(store) || fs.existsSync(path.join(store, "phren.root.yaml")) || fs.existsSync(installPreferencesFile(store));
79
+ if (!hasStore)
80
+ return false;
81
+ const config = readConfig(store);
82
+ if (config?.enabled?.hook === true)
83
+ return false;
84
+ migrateModules(store);
85
+ setModuleEnabled(store, "hook", true);
86
+ return true;
87
+ }
@@ -40,7 +40,8 @@ export const BUILTIN_MODULES = [
40
40
  { agents: ["claude", "codex", "copilot", "cursor"], events: ["Stop"], handler: "phren hook-stop" },
41
41
  { agents: ["claude"], events: ["PostToolUse"], handler: "phren hook-tool" },
42
42
  ],
43
- hookRoutes: [], capabilities: ["memory"],
43
+ hookRoutes: [...routes("GET", ["/v1/store/head", "/v1/store/tree", "/v1/store/blob"]), ...routes("POST", ["/v1/store/file", "/v1/store/delete"])],
44
+ capabilities: ["memory", "memoryStore"],
44
45
  storeFiles: [
45
46
  "phren.root.yaml", "machines.yaml", "profiles/*.yaml", ".config/modules.yaml", ".config/*.json",
46
47
  "<project>/AGENTS.md", "<project>/summary.md", "<project>/FINDINGS.md", "<project>/truths.md",
@@ -56,7 +57,7 @@ export const BUILTIN_MODULES = [
56
57
  schemaVersion: 1, name: "tasks", version: VERSION, defaultEnabled: false, requires: ["memory"],
57
58
  tools: [
58
59
  ...core(["get_tasks", "add_task", "manage_task"]),
59
- ...full(["complete_task", "remove_task", "update_task", "tidy_done_tasks", "pin_task"]),
60
+ ...full(["complete_task", "remove_task", "update_task", "tidy_done_tasks", "pin_task", "claim_task"]),
60
61
  ],
61
62
  cliCommands: ["task", "tasks", "config task-mode", "config proactivity.tasks"], agentHooks: [], hookRoutes: [], capabilities: ["tasks"],
62
63
  storeFiles: ["<project>/tasks.md", ".sessions/checkpoint-*.json"], localFiles: [],
@@ -67,7 +68,7 @@ export const BUILTIN_MODULES = [
67
68
  tools: [],
68
69
  cliCommands: [
69
70
  "bridge", "bridge install", "bridge update", "bridge uninstall", "bridge rollback", "bridge status",
70
- "bridge doctor", "bridge usage", "bridge usage-statusline", "bridge hook", "bridge serve", "bridge ssh",
71
+ "bridge doctor", "bridge usage", "bridge usage-statusline", "bridge hook", "bridge serve", "bridge ssh", "pair",
71
72
  "bridge fanouts archive", "canary",
72
73
  ],
73
74
  agentHooks: [
@@ -127,7 +128,7 @@ export const BUILTIN_MODULES = [
127
128
  {
128
129
  schemaVersion: 1, name: "conductor", version: VERSION, defaultEnabled: false, requires: ["memory", "hook"],
129
130
  tools: full(["dispatch", "dispatch_returns", "hand_off", "live_sessions"]), cliCommands: ["dispatch", "dispatch status", "dispatch returns", "dispatch sessions", "hand-off", "conductor", "conductor grants", "bridge enroll-computer"], agentHooks: [],
130
- hookRoutes: [...routes("GET", ["/v1/dispatch", "/v1/dispatch/capacity", "/v1/conductor/grants"]),
131
+ hookRoutes: [...routes("GET", ["/v1/dispatch", "/v1/dispatch/capacity", "/v1/conductor", "/v1/conductor/grants"]),
131
132
  ...routes("POST", ["/v1/dispatch", "/v1/dispatch/workers", "/v1/dispatch/returns", "/v1/conductor/grants"]), ...routes("DELETE", ["/v1/conductor/grants"])],
132
133
  capabilities: ["dispatch"], storeFiles: ["global/skills/conductor/**"],
133
134
  localFiles: ["<bridge>/hooks.yaml", "<bridge>/conductor.yaml", "<bridge>/dispatches/*.json"], phoneScreens: [], skills: ["conductor"],
@@ -143,7 +144,7 @@ export const BUILTIN_MODULES = [
143
144
  tools: full(["code_search", "code_definition", "code_references", "code_outline", "code_usage"]),
144
145
  cliCommands: ["code index", "code status", "code search", "code outline", "code refs", "code def", "code usage"],
145
146
  agentHooks: [],
146
- hookRoutes: [...routes("GET", ["/v1/code/tree", "/v1/code/usage-page", "/v1/code/recent", "/v1/code/status", "/v1/code/search", "/v1/code/outline", "/v1/code/outline-summary", "/v1/code/file-references", "/v1/code/definition", "/v1/code/references", "/v1/code/usage"]), ...routes("POST", ["/v1/code/note", "/v1/code/reindex", "/v1/code/disable"])],
147
+ hookRoutes: [...routes("GET", ["/v1/code/tree", "/v1/code/usage-page", "/v1/code/changed", "/v1/code/change-counts", "/v1/code/status", "/v1/code/search", "/v1/code/outline", "/v1/code/outline-summary", "/v1/code/file-references", "/v1/code/definition", "/v1/code/references", "/v1/code/usage"]), ...routes("POST", ["/v1/code/note", "/v1/code/reindex", "/v1/code/disable"])],
147
148
  capabilities: ["code"],
148
149
  storeFiles: [], localFiles: ["<store>/.runtime/code/*.sqlite"],
149
150
  phoneScreens: [{ screen: "CodeView", capability: "code" }], skills: ["code"],
@@ -104,12 +104,28 @@ export function setMachineProfile(phrenPath, machine, profile) {
104
104
  const machinesPath = path.join(phrenPath, "machines.yaml");
105
105
  return withSafeLock(machinesPath, () => {
106
106
  const current = listMachines(phrenPath);
107
+ // writeMachines rebuilds the whole file, so rewriting one phren cannot parse
108
+ // from an empty map would drop every other machine's mapping. The file is
109
+ // git-synced, so conflict markers are the likely cause. A comments-only file
110
+ // (the shipped starter) also fails to parse and is fine to write into.
111
+ if (!current.ok && current.code !== PhrenError.FILE_NOT_FOUND && hasMachineEntries(machinesPath)) {
112
+ return phrenErr(`${machinesPath} could not be parsed, so phren will not rewrite it. Fix the file by hand (check for git conflict markers), then map again.`, PhrenError.MALFORMED_YAML);
113
+ }
107
114
  const data = current.ok ? current.data : {};
108
115
  data[machine] = profile;
109
116
  writeMachines(phrenPath, data);
110
117
  return phrenOk(`Mapped machine ${machine} -> ${profile}.`);
111
118
  });
112
119
  }
120
+ /** Does machines.yaml hold anything besides comments and blank lines? */
121
+ function hasMachineEntries(machinesPath) {
122
+ try {
123
+ return loadYamlDocument(fs.readFileSync(machinesPath, "utf8"), () => true) === true;
124
+ }
125
+ catch {
126
+ return false;
127
+ }
128
+ }
113
129
  function pickEnumVal(value, allowed) {
114
130
  return typeof value === "string" && allowed.includes(value) ? value : undefined;
115
131
  }
@@ -235,14 +251,34 @@ export function listProfiles(phrenPath) {
235
251
  }
236
252
  return phrenOk(profiles);
237
253
  }
254
+ /**
255
+ * Rewrite a profile's projects, keeping every other key (the `defaults:` policy
256
+ * block included) and the file's leading comment, the way writeMachines does.
257
+ */
238
258
  function writeProfile(file, name, projects, description) {
239
259
  const backup = `${file}.bak`;
240
- if (fs.existsSync(file))
260
+ const existing = fs.existsSync(file) ? fs.readFileSync(file, "utf8") : "";
261
+ if (existing)
241
262
  fs.copyFileSync(file, backup);
263
+ // listProfiles already refused an unparsable file, so this parse succeeds.
264
+ const parsed = existing ? loadYamlDocument(existing, (text) => yaml.load(text, { schema: yaml.CORE_SCHEMA })) : undefined;
265
+ const rest = parsed && typeof parsed === "object" && !Array.isArray(parsed)
266
+ ? { ...parsed }
267
+ : {};
268
+ delete rest.name;
269
+ delete rest.description;
270
+ delete rest.projects;
271
+ const headerLines = [];
272
+ for (const line of existing.split("\n")) {
273
+ if (!line.startsWith("#") && line.trim() !== "")
274
+ break;
275
+ headerLines.push(line);
276
+ }
277
+ const header = headerLines.length ? `${headerLines.join("\n").replace(/\n+$/, "")}\n` : "";
242
278
  const normalized = [...new Set(projects)].sort();
243
- const out = yaml.dump({ name, ...(description ? { description } : {}), projects: normalized }, { lineWidth: 1000 });
279
+ const out = yaml.dump({ name, ...(description ? { description } : {}), projects: normalized, ...rest }, { lineWidth: 1000 });
244
280
  const tmpPath = `${file}.tmp-${crypto.randomUUID()}`;
245
- fs.writeFileSync(tmpPath, out);
281
+ fs.writeFileSync(tmpPath, header + out);
246
282
  fs.renameSync(tmpPath, file);
247
283
  }
248
284
  export function addProjectToProfile(phrenPath, profile, project) {
@@ -71,6 +71,7 @@ export declare function readProjectTopics(phrenPath: string, project: string): {
71
71
  source: ProjectTopicSource;
72
72
  topics: ProjectTopic[];
73
73
  domain?: string;
74
+ error?: string;
74
75
  };
75
76
  export declare function pinProjectTopicSuggestion(phrenPath: string, project: string, topic: ProjectTopic): {
76
77
  ok: true;
@@ -57,7 +57,7 @@ const SOFTWARE_TOPICS = [
57
57
  slug: "architecture",
58
58
  label: "Architecture",
59
59
  description: "System shape, module boundaries, design patterns, and structural decisions.",
60
- keywords: ["architecture", "design", "pattern", "layer", "module", "system", "structure", "microservice", "monolith", "event-driven", "plugin"],
60
+ keywords: ["architecture", "design", "pattern", "layer", "module", "system", "structure", "microservice", "monolith", "event-driven"],
61
61
  },
62
62
  {
63
63
  slug: "debugging",
@@ -81,7 +81,7 @@ const SOFTWARE_TOPICS = [
81
81
  slug: "data",
82
82
  label: "Data",
83
83
  description: "Data models, serialization, parsing, validation, and data flow details.",
84
- keywords: ["data", "model", "schema", "serialize", "deserialize", "json", "csv", "transform", "validate", "parse", "format", "encode"],
84
+ keywords: ["data", "serialize", "deserialize", "json", "csv", "transform", "validate", "parse", "format", "encode"],
85
85
  },
86
86
  {
87
87
  slug: "mobile",
@@ -93,7 +93,7 @@ const SOFTWARE_TOPICS = [
93
93
  slug: "ai_ml",
94
94
  label: "AI / ML",
95
95
  description: "Models, embeddings, prompts, inference, and ML-specific systems.",
96
- keywords: ["ai", "ml", "model", "embedding", "vector", "llm", "prompt", "token", "inference", "training", "neural", "gpt", "claude"],
96
+ keywords: ["ai", "ml", "model", "embedding", "vector", "llm", "prompt", "inference", "training", "neural", "gpt", "claude"],
97
97
  },
98
98
  {
99
99
  slug: "general",
@@ -115,7 +115,7 @@ const DOMAIN_TOPICS = {
115
115
  slug: "production",
116
116
  label: "Production",
117
117
  description: "Session workflow, recording choices, and production techniques.",
118
- keywords: ["production", "recording", "session", "tracking", "workflow", "arrangement", "producer"],
118
+ keywords: ["production", "recording", "session", "tracking", "workflow", "producer"],
119
119
  },
120
120
  {
121
121
  slug: "mixing",
@@ -259,7 +259,7 @@ const DOMAIN_TOPICS = {
259
259
  slug: "style",
260
260
  label: "Style",
261
261
  description: "Tone, diction, constraints, and stylistic direction.",
262
- keywords: ["style", "tone", "voice", "diction", "register", "aesthetic"],
262
+ keywords: ["style", "tone", "diction", "register", "aesthetic"],
263
263
  },
264
264
  {
265
265
  slug: "research",
@@ -570,8 +570,11 @@ export function readProjectTopics(phrenPath, project) {
570
570
  const normalized = ensureGeneralTopic(normalizeTopics(parsed.topics));
571
571
  const validationError = validateTopics(normalized);
572
572
  if (validationError) {
573
+ // Falling back silently made a rejected config indistinguishable from having
574
+ // none: `get_config topic` reported source "default" while the file sat
575
+ // plainly on disk, and the only trace was a debug line. Return the reason.
573
576
  debugLog(`readProjectTopics: invalid ${configPath}: ${validationError}`);
574
- return { source: "default", topics: builtinTopics };
577
+ return { source: "default", topics: builtinTopics, error: validationError };
575
578
  }
576
579
  return { source: "custom", topics: normalized, domain: typeof parsed.domain === "string" ? parsed.domain : undefined };
577
580
  }
@@ -52,8 +52,6 @@ export declare function tokenRarity(db: SqlJsDatabase | null | undefined, queryT
52
52
  */
53
53
  /** @internal Exported for tests. */
54
54
  export declare function rrfMerge(tiers: DocRow[][], k?: number): DocRow[];
55
- /** @internal Exported for tests. */
56
- export declare function shouldRunVectorExpansion(rows: DocRow[] | null, prompt: string, desiredResults?: number): boolean;
57
55
  declare function approximateTokens(text: string): number;
58
56
  export declare function filterTaskByPriority(items: string[], allowedPriorities?: string[]): string[];
59
57
  export declare function searchDocuments(db: SqlJsDatabase, safeQuery: string, prompt: string, keywords: string, detectedProject: string | null, searchAllProjects?: boolean, phrenPath?: string): DocRow[] | null;
@@ -398,7 +398,7 @@ function semanticFallbackDocs(db, prompt, project) {
398
398
  return scored;
399
399
  }
400
400
  /** @internal Exported for tests. */
401
- export function shouldRunVectorExpansion(rows, prompt, desiredResults = VECTOR_FALLBACK_SKIP_COUNT) {
401
+ function shouldRunVectorExpansion(rows, prompt, desiredResults = VECTOR_FALLBACK_SKIP_COUNT) {
402
402
  if (!rows || rows.length === 0)
403
403
  return true;
404
404
  const targetCount = Math.max(2, Math.min(VECTOR_FALLBACK_SKIP_COUNT, desiredResults));
@@ -0,0 +1,22 @@
1
+ import { type TaskClaim, type TaskItem } from "../data/tasks.js";
2
+ export interface ClaimOutcome {
3
+ /** True when this computer holds the claim after syncing; false after a release. */
4
+ claimed: boolean;
5
+ item?: TaskItem;
6
+ /** The claim that won when another computer's reached the remote first. */
7
+ heldBy?: TaskClaim;
8
+ /** False when the claim could not reach the store's remote. */
9
+ synced: boolean;
10
+ detail: string;
11
+ error?: string;
12
+ }
13
+ /**
14
+ * Claims a task across unlinked conductors: pull the store so a claim already
15
+ * pushed elsewhere refuses this one, write the claim, then commit and push.
16
+ * When another computer's claim reached the remote first, the store merge
17
+ * keeps theirs, so the task is read again after the push to see who won.
18
+ */
19
+ export declare function claimTaskSynced(phrenPath: string, project: string, match: string, claim: TaskClaim, opts?: {
20
+ release?: boolean;
21
+ force?: boolean;
22
+ }): Promise<ClaimOutcome>;
@@ -0,0 +1,45 @@
1
+ import { runBestEffortGit } from "../cli/session-git.js";
2
+ import { claimTask, resolveTaskItem } from "../data/tasks.js";
3
+ import { withFileLock } from "../governance/locks.js";
4
+ import { runtimeFile } from "../phren-paths.js";
5
+ import { mergeStoreUpstream } from "./store-merge.js";
6
+ const git = async (cwd, args) => {
7
+ const result = await runBestEffortGit(args, cwd);
8
+ return { ok: result.ok, output: result.output ?? "", error: result.error };
9
+ };
10
+ /**
11
+ * Claims a task across unlinked conductors: pull the store so a claim already
12
+ * pushed elsewhere refuses this one, write the claim, then commit and push.
13
+ * When another computer's claim reached the remote first, the store merge
14
+ * keeps theirs, so the task is read again after the push to see who won.
15
+ */
16
+ export async function claimTaskSynced(phrenPath, project, match, claim, opts = {}) {
17
+ return withFileLock(runtimeFile(phrenPath, "git-op"), async () => {
18
+ const pulled = await mergeStoreUpstream(phrenPath, { git, commitMessage: "auto-save phren (task claim)" });
19
+ const offline = pulled.status === "error" || pulled.status === "busy" ? pulled.detail : undefined;
20
+ const written = claimTask(phrenPath, project, match, claim, opts);
21
+ if (!written.ok)
22
+ return { claimed: false, synced: !offline, detail: offline ?? "", error: written.error };
23
+ const bid = written.data.stableId ?? match;
24
+ const verb = opts.release ? "releases" : "claims";
25
+ const saved = await mergeStoreUpstream(phrenPath, { git, commitMessage: `phren: ${claim.computer} ${verb} ${project} task ${bid}` });
26
+ if (offline || saved.status === "error" || saved.status === "busy") {
27
+ return { claimed: !opts.release, item: written.data, synced: false, detail: `The change is written on this computer but not synced: ${offline ?? saved.detail}` };
28
+ }
29
+ if (/no tracking remote/i.test(saved.detail)) {
30
+ return { claimed: !opts.release, item: written.data, synced: false, detail: "The store has no remote, so the change is only on this computer." };
31
+ }
32
+ let pushed = await git(phrenPath, ["push", "--quiet"]);
33
+ if (!pushed.ok) {
34
+ const merged = await mergeStoreUpstream(phrenPath, { git, commitLocalWrites: false });
35
+ pushed = merged.status === "updated" || merged.status === "unchanged" ? await git(phrenPath, ["push", "--quiet"]) : { ok: false, output: "", error: merged.detail };
36
+ }
37
+ const current = resolveTaskItem(phrenPath, project, bid);
38
+ const now = current.ok ? current.data : undefined;
39
+ if (!opts.release && now?.claim && now.claim.computer !== claim.computer) {
40
+ return { claimed: false, item: now, heldBy: now.claim, synced: pushed.ok, detail: `${now.claim.computer} claimed this task first.` };
41
+ }
42
+ return { claimed: !opts.release, item: now ?? written.data, synced: pushed.ok,
43
+ detail: pushed.ok ? "Pushed to the store's remote." : `Committed but not pushed: ${pushed.error ?? "push failed"}` };
44
+ });
45
+ }
@@ -2,11 +2,11 @@ import { z } from "zod";
2
2
  import { resolveStoreForProject } from "./types.js";
3
3
  import { loadCodePackage, CODE_PACKAGE_HINT } from "../modules/code-package.js";
4
4
  /**
5
- * Read tools over the `code` module's local symbol index (stage 2).
5
+ * Read tools over the `code` module's local code index (stage 2).
6
6
  *
7
- * These answer symbol questions from the project's own index instead of a grep
7
+ * These answer questions about functions, types and variables from the project's own index instead of a grep
8
8
  * sweep: a definition, the references grouped by file, a file's outline, a
9
- * ranked search and the hottest and coldest symbols. Every tool lives in the
9
+ * ranked search and the most and least used functions and types. Every tool lives in the
10
10
  * `code` module, so it is absent until the module is enabled and the project is
11
11
  * indexed; the result is compact text, one line per hit, not a JSON dump.
12
12
  */
@@ -44,11 +44,11 @@ function usageLine(entry) {
44
44
  export function register(server, ctx) {
45
45
  server.registerTool("code_search", {
46
46
  title: "◆ phren · code search",
47
- description: "Search a project's code index for symbols by name, signature or doc text. Use this instead of grep when you want a symbol (a function, class, method, type) rather than raw text: results are ranked exact name, then prefix, then full-text relevance, then usage count, and each hit carries its kind, signature, doc and path:line. Pass `kind` to narrow to function, method, class, struct, enum, interface, type or variable.",
47
+ description: "Find functions, methods, types (classes, structs, enums, interfaces) and variables in a project's code index by name, signature or doc text. Use this instead of grep when you want a declaration rather than raw text: results are ranked exact name, then prefix, then full-text relevance, then how often it is used, and each hit carries its kind, signature, doc and path:line. Pass `kind` to narrow to function, method, class, struct, enum, interface, type or variable.",
48
48
  inputSchema: z.object({
49
49
  project: z.string().describe("Project name, optionally store-qualified."),
50
- query: z.string().describe("Symbol name or words from its signature or doc comment."),
51
- kind: z.enum(["function", "method", "class", "struct", "enum", "interface", "type", "variable"]).optional().describe("Only symbols of this kind."),
50
+ query: z.string().describe("A name, or words from its signature or doc comment."),
51
+ kind: z.enum(["function", "method", "class", "struct", "enum", "interface", "type", "variable"]).optional().describe("Only this kind."),
52
52
  limit: z.number().int().min(1).max(100).optional().describe("Maximum hits. Defaults to 20."),
53
53
  }),
54
54
  }, async ({ project: projectInput, query, kind, limit }) => {
@@ -63,17 +63,21 @@ export function register(server, ctx) {
63
63
  if (!result.available)
64
64
  return text(noIndex(target.project));
65
65
  if (result.value.length === 0)
66
- return text(`No symbols match "${query}" in ${target.project}.`);
66
+ return text(`Nothing named or described "${query}" in ${target.project}.`);
67
67
  return text(`${target.project}: ${result.value.length} match(es) for "${query}"\n${result.value.map(formatSymbolLine).join("\n")}`);
68
68
  });
69
69
  server.registerTool("code_definition", {
70
70
  title: "◆ phren · code definition",
71
- description: "Go to a symbol's definition in a project's code index. Use this instead of grep to find where a function, class or method is declared: it accepts `Foo`, `Foo.bar` and `bar()` forms and returns the file and lines, signature, doc comment, the last change (a blame hash and date, never a name) and a short source snippet. When a common name matches several symbols it prefers an exported, non-variable declaration and reports how many candidates there were.",
71
+ description: "Go to where a function, method, type or variable is defined, from a project's code index. Use this instead of grep: it accepts `Foo`, `Foo.bar` and `bar()` forms and returns the file and lines, signature, doc comment, the last change (a blame hash and date, never a name), a short source snippet and any Phren findings linked to it. When a common name matches several declarations it prefers an exported, non-variable one and reports how many candidates there were.",
72
72
  inputSchema: z.object({
73
73
  project: z.string().describe("Project name, optionally store-qualified."),
74
- symbol: z.string().describe("A symbol name: Foo, Foo.bar or bar()."),
74
+ name: z.string().optional().describe("What to look up: Foo, Foo.bar or bar()."),
75
+ symbol: z.string().optional().describe("Deprecated: use name. Accepted until @phren/cli 0.3.1."),
75
76
  }),
76
- }, async ({ project: projectInput, symbol }) => {
77
+ }, async ({ project: projectInput, name: nameInput, symbol: legacyName }) => {
78
+ const symbol = nameInput ?? legacyName;
79
+ if (!symbol)
80
+ return text("Pass name: the function, type or variable to look up.");
77
81
  const code = await loadCodePackage(ctx.phrenPath);
78
82
  if (!code)
79
83
  return text(CODE_PACKAGE_HINT);
@@ -85,7 +89,7 @@ export function register(server, ctx) {
85
89
  if (!result.available)
86
90
  return text(noIndex(target.project));
87
91
  if (!result.value)
88
- return text(`No symbol "${symbol}" in ${target.project}.`);
92
+ return text(`Nothing named "${symbol}" in ${target.project}.`);
89
93
  const { symbol: hit, candidates, snippet, blame } = result.value;
90
94
  const lines = [
91
95
  `${hit.file}:${hit.line}-${hit.endLine} ${hit.kind} ${hit.name}${hit.exported ? " (exported)" : ""}`,
@@ -100,13 +104,17 @@ export function register(server, ctx) {
100
104
  });
101
105
  server.registerTool("code_references", {
102
106
  title: "◆ phren · code references",
103
- description: "Find every resolved reference to a symbol in a project's code index, grouped by file. Use this instead of grep to answer who calls or uses a function, class or method: it accepts `Foo`, `Foo.bar` and `bar()` forms and counts only references the index could resolve to exactly one definition. Common-name ambiguity is reported as a candidate count.",
107
+ description: "Find every place a function, method, type or variable is used, from a project's code index, grouped by file. Use this instead of grep to answer who calls or uses it: it accepts `Foo`, `Foo.bar` and `bar()` forms and counts only uses the index could resolve to exactly one definition. Common-name ambiguity is reported as a candidate count.",
104
108
  inputSchema: z.object({
105
109
  project: z.string().describe("Project name, optionally store-qualified."),
106
- symbol: z.string().describe("A symbol name: Foo, Foo.bar or bar()."),
110
+ name: z.string().optional().describe("What to look up: Foo, Foo.bar or bar()."),
111
+ symbol: z.string().optional().describe("Deprecated: use name. Accepted until @phren/cli 0.3.1."),
107
112
  limit: z.number().int().min(1).max(500).optional().describe("Maximum reference lines. Defaults to 200."),
108
113
  }),
109
- }, async ({ project: projectInput, symbol, limit }) => {
114
+ }, async ({ project: projectInput, name: nameInput, symbol: legacyName, limit }) => {
115
+ const symbol = nameInput ?? legacyName;
116
+ if (!symbol)
117
+ return text("Pass name: the function, type or variable to look up.");
110
118
  const code = await loadCodePackage(ctx.phrenPath);
111
119
  if (!code)
112
120
  return text(CODE_PACKAGE_HINT);
@@ -118,7 +126,7 @@ export function register(server, ctx) {
118
126
  if (!result.available)
119
127
  return text(noIndex(target.project));
120
128
  if (!result.value)
121
- return text(`No symbol "${symbol}" in ${target.project}.`);
129
+ return text(`Nothing named "${symbol}" in ${target.project}.`);
122
130
  const { symbol: hit, candidates, groups, total } = result.value;
123
131
  const header = `references for ${hit.name} (${hit.file}:${hit.line} ${hit.kind}), ${total} in ${groups.length} file(s)`;
124
132
  const note = candidates > 1 ? `\n${candidates} candidates shared this name; showing the best.` : "";
@@ -129,7 +137,7 @@ export function register(server, ctx) {
129
137
  });
130
138
  server.registerTool("code_outline", {
131
139
  title: "◆ phren · code outline",
132
- description: "List a file's symbols in source order, nested under their parent class or container. Use this before reading a large file: it is far cheaper than opening the source and it shows the structure (classes and their methods, top-level functions and types) with each symbol's line, signature and doc. The path is the project-relative path the index uses.",
140
+ description: "List a file's functions, types and variables in source order, methods nested under their class or container. Use this before reading a large file: it is far cheaper than opening the source and it shows the structure with each declaration's line, signature and doc. The path is the project-relative path the index uses.",
133
141
  inputSchema: z.object({
134
142
  project: z.string().describe("Project name, optionally store-qualified."),
135
143
  path: z.string().describe("Project-relative file path, as stored in the index."),
@@ -146,16 +154,16 @@ export function register(server, ctx) {
146
154
  if (!result.available)
147
155
  return text(noIndex(target.project));
148
156
  if (result.value.length === 0)
149
- return text(`No indexed symbols for ${filePath} in ${target.project}.`);
157
+ return text(`No functions, types or variables indexed for ${filePath} in ${target.project}.`);
150
158
  const count = result.value.reduce((n, entry) => n + 1 + countOutline(entry.children), 0);
151
- return text(`${target.project}/${filePath} (${count} symbols)\n${outlineLines(result.value).join("\n")}`);
159
+ return text(`${target.project}/${filePath} (${count} declarations)\n${outlineLines(result.value).join("\n")}`);
152
160
  });
153
161
  server.registerTool("code_usage", {
154
162
  title: "◆ phren · code usage",
155
- description: "Show a project's hottest and coldest symbols by resolved-reference count. Use this instead of grep to see what code is central and what is barely used: it returns the top and bottom N so cold code is visible too. Local variables are excluded from the hot list so a busy one-function local or a one-letter loop name cannot dominate it.",
163
+ description: "Show a project's most used and least used functions and types, by how many places use them. Use this instead of grep to see what code is central and what is barely used: it returns the top and bottom N so rarely used code is visible too. Local variables are left out of the most-used list so a busy one-function local or a one-letter loop name cannot dominate it.",
156
164
  inputSchema: z.object({
157
165
  project: z.string().describe("Project name, optionally store-qualified."),
158
- top: z.number().int().min(1).max(100).optional().describe("How many hot and how many cold symbols. Defaults to 10."),
166
+ top: z.number().int().min(1).max(100).optional().describe("How many most used and how many least used. Defaults to 10."),
159
167
  }),
160
168
  }, async ({ project: projectInput, top }) => {
161
169
  const code = await loadCodePackage(ctx.phrenPath);
@@ -170,7 +178,7 @@ export function register(server, ctx) {
170
178
  return text(noIndex(target.project));
171
179
  const { top: hot, bottom: cold } = result.value;
172
180
  const section = (label, entries) => entries.length === 0 ? `${label}\nnone` : `${label}\n${entries.map(usageLine).join("\n")}`;
173
- return text(`${target.project} symbols by reference count\n${section("hot", hot)}\n${section("cold", cold)}`);
181
+ return text(`${target.project} functions and types by how many places use them\n${section("most used", hot)}\n${section("least used", cold)}`);
174
182
  });
175
183
  }
176
184
  function countOutline(entries) {
@@ -66,6 +66,9 @@ function getTopicConfigData(phrenPath, project) {
66
66
  domain: result.domain ?? raw?.domain ?? null,
67
67
  topics: result.topics,
68
68
  pinnedTopics: raw?.pinnedTopics ?? [],
69
+ // A topic-config.json that exists but was rejected reported source
70
+ // "default" with no hint that the file was being ignored.
71
+ ...(result.error ? { configError: result.error } : {}),
69
72
  },
70
73
  };
71
74
  }
@@ -21,7 +21,7 @@ export function register(server) {
21
21
  });
22
22
  server.registerTool("dispatch_returns", {
23
23
  title: "◆ phren · dispatch returns",
24
- description: "List unread returns from dispatched workers and mark them read: the worker finished (done, with its final reply), finished by asking the owner something (needs-you, with the question), is blocked on terminal input, or its pane is gone. Each row has the dispatch id, computer, project, label and the worker's target for hand_off.",
24
+ description: "List unread returns from dispatched workers and mark them read: the worker finished (done, with its final reply), finished by asking the owner something (needs-you, with the question), failed (the harness ended the turn on an error such as a usage limit, with the error), is blocked on terminal input, or its pane is gone. Each row has the dispatch id, computer, project, label and the worker's target for hand_off.",
25
25
  inputSchema: {},
26
26
  }, async () => {
27
27
  try {
@@ -41,9 +41,9 @@ export function register(server) {
41
41
  try {
42
42
  const result = await listLiveSessions();
43
43
  const note = result.peerError ? ` Enrolled computers were skipped: ${result.peerError}`
44
- : result.enrolled === 0 && !result.notLinked.length ? " No other computers are enrolled here; run `phren bridge enroll-computer` to add them." : "";
44
+ : result.enrolled === 0 && !result.notLinked.length ? " No other computers are linked here; `phren bridge discover` lists the ones you already reach over ssh, and `phren bridge link <host>` links one." : "";
45
45
  const unlinked = result.notLinked.length
46
- ? ` Not linked, so not checked (this does not mean nothing is running there): ${result.notLinked.map(item => item.aliases?.length ? `${item.name} (also ${item.aliases.join(", ")})` : item.name).join("; ")}. Link one with \`phren bridge enroll-computer\`.` : "";
46
+ ? ` Not linked, so not checked (this does not mean nothing is running there): ${result.notLinked.map(item => item.aliases?.length ? `${item.name} (also ${item.aliases.join(", ")})` : item.name).join("; ")}. If you reach one over ssh, the owner can link it with \`phren bridge link <host>\`; never link a computer without the owner asking.` : "";
47
47
  return mcpResponse({ ok: true, data: result, message: `${result.sessions.length} live sessions across ${result.enrolled + 1} computers.${note}${unlinked}` });
48
48
  }
49
49
  catch (error) {
@@ -1,4 +1,15 @@
1
1
  import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2
2
  import { type McpContext } from "./types.js";
3
3
  export declare function findConflictCandidates(phrenPath: string, project: string, finding: string): string[];
4
+ export interface TeamStoreSyncResult {
5
+ store: string;
6
+ pushed: boolean;
7
+ error?: string;
8
+ }
9
+ /**
10
+ * Commit and push the team-safe pathspecs of every attached team store. Team
11
+ * stores are independent repos, so push_changes runs this whatever happens to
12
+ * the primary store.
13
+ */
14
+ export declare function syncTeamStores(phrenPath: string): Promise<TeamStoreSyncResult[]>;
4
15
  export declare function register(server: McpServer, ctx: McpContext): void;