@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
@@ -13,6 +13,7 @@ import { loadCodePackage } from "../modules/code-package.js";
13
13
  import { moduleEnabled } from "../modules/runtime.js";
14
14
  import { addFindingToFile, addFindingsToFile, checkSemanticConflicts, } from "../shared/content.js";
15
15
  import { jaccardTokenize, jaccardSimilarity, stripMetadata, detectConflicts, extractDynamicEntities } from "../content/dedup.js";
16
+ import { scanForSecrets } from "../content/secrets.js";
16
17
  import { runCustomHooks } from "../hooks.js";
17
18
  import { incrementSessionFindings } from "./session.js";
18
19
  import { extractFragmentNames } from "../shared/fragment-graph.js";
@@ -117,7 +118,14 @@ function withLifecycleMutation(phrenPath, project, writeQueue, updateIndex, hand
117
118
  }
118
119
  // ── Handlers ─────────────────────────────────────────────────────────────────
119
120
  async function handleAddFinding(ctx, params) {
120
- const { finding, citation, sessionId, findingType, scope } = params;
121
+ const { finding, sessionId, findingType, scope } = params;
122
+ // `name` is the citation's code link (a function, type or variable);
123
+ // `symbol` is its deprecated spelling, accepted until 0.3.1. The stored
124
+ // citation keeps its existing key.
125
+ const { name: citedName, ...citationRest } = params.citation ?? {};
126
+ const citation = params.citation
127
+ ? { ...citationRest, ...(citedName ?? citationRest.symbol ? { symbol: citedName ?? citationRest.symbol } : {}) }
128
+ : undefined;
121
129
  // Resolve store-qualified project names (e.g., "team/arc" → store path + "arc")
122
130
  let phrenPath;
123
131
  let project;
@@ -141,35 +149,67 @@ async function handleAddFinding(ctx, params) {
141
149
  actor: getCurrentActor(),
142
150
  session_id: sessionId,
143
151
  };
152
+ const normalizedScope = normalizeMemoryScope(scope ?? "shared");
153
+ if (!normalizedScope)
154
+ return mcpResponse({ ok: false, error: `Invalid scope: "${scope}". Use lowercase letters/numbers with '-' or '_' (max 64 chars), e.g. "researcher".` });
155
+ // Size caps apply to every store; they used to sit after the team branch.
156
+ const findingList = Array.isArray(finding) ? finding : [finding];
157
+ if (findingList.length > 100)
158
+ return mcpResponse({ ok: false, error: "Bulk add limited to 100 findings per call." });
159
+ if (findingList.some((f) => f.length > 5000)) {
160
+ return mcpResponse({
161
+ ok: false,
162
+ error: Array.isArray(finding) ? "One or more findings exceed 5000 character limit." : "Finding text exceeds 5000 character limit.",
163
+ });
164
+ }
144
165
  // Team stores: use append-only journal (no FINDINGS.md mutation, no merge conflicts)
145
166
  {
146
167
  const storeResolved = resolveStoreForProject(ctx, params.project);
147
168
  if (storeResolved.storeRole === "team") {
148
169
  const { appendTeamJournal } = await import("../finding/journal.js");
149
- const findings = Array.isArray(finding) ? finding : [finding];
150
- const added = [];
151
- for (const f of findings) {
152
- const taggedFinding = applyFindingTypePrefix(f, findingType);
153
- const result = appendTeamJournal(phrenPath, project, taggedFinding, provenance.actor, provenance.machine);
154
- if (result.ok)
155
- added.push(taggedFinding);
170
+ // The journal is pushed to a repo shared with colleagues, so it gets the
171
+ // same secret scan the personal store applies.
172
+ const rejected = [];
173
+ const accepted = [];
174
+ for (const f of findingList) {
175
+ const secretType = scanForSecrets(f);
176
+ if (secretType)
177
+ rejected.push({ finding: f.slice(0, 60), reason: `Contains ${secretType}` });
178
+ else
179
+ accepted.push(applyFindingTypePrefix(f, findingType));
156
180
  }
157
- return mcpResponse({
158
- ok: added.length > 0,
159
- message: `Added ${added.length} finding(s) to ${params.project} journal`,
160
- data: { project: params.project, added, journalMode: true },
181
+ return withWriteQueue(async () => {
182
+ const added = [];
183
+ const journals = new Set();
184
+ for (const taggedFinding of accepted) {
185
+ const result = appendTeamJournal(phrenPath, project, taggedFinding, provenance.actor, provenance.machine);
186
+ if (result.ok) {
187
+ added.push(taggedFinding);
188
+ journals.add(path.join(phrenPath, project, "journal", result.data));
189
+ }
190
+ else {
191
+ rejected.push({ finding: taggedFinding.slice(0, 60), reason: result.error });
192
+ }
193
+ }
194
+ for (const journalPath of journals)
195
+ updateFileInIndex(journalPath);
196
+ if (added.length === 0) {
197
+ return mcpResponse({
198
+ ok: false,
199
+ error: `No findings written to ${params.project} journal: ${rejected.map((r) => `"${r.finding}" ${r.reason}`).join("; ")}`,
200
+ data: { project: params.project, rejected, journalMode: true },
201
+ });
202
+ }
203
+ return mcpResponse({
204
+ ok: true,
205
+ message: `Added ${added.length} finding(s) to ${params.project} journal${rejected.length > 0 ? `, ${rejected.length} rejected` : ""}`,
206
+ data: { project: params.project, added, journalMode: true, ...(rejected.length > 0 ? { rejected } : {}) },
207
+ });
161
208
  });
162
209
  }
163
210
  }
164
- const normalizedScope = normalizeMemoryScope(scope ?? "shared");
165
- if (!normalizedScope)
166
- return mcpResponse({ ok: false, error: `Invalid scope: "${scope}". Use lowercase letters/numbers with '-' or '_' (max 64 chars), e.g. "researcher".` });
167
211
  if (Array.isArray(finding)) {
168
212
  const findings = finding;
169
- if (findings.length > 100)
170
- return mcpResponse({ ok: false, error: "Bulk add limited to 100 findings per call." });
171
- if (findings.some((f) => f.length > 5000))
172
- return mcpResponse({ ok: false, error: "One or more findings exceed 5000 character limit." });
173
213
  return withWriteQueue(async () => {
174
214
  runCustomHooks(phrenPath, "pre-finding", { PHREN_PROJECT: project });
175
215
  const allPotentialDuplicates = [];
@@ -220,14 +260,12 @@ async function handleAddFinding(ctx, params) {
220
260
  });
221
261
  });
222
262
  }
223
- if (finding.length > 5000)
224
- return mcpResponse({ ok: false, error: "Finding text exceeds 5000 character limit." });
225
263
  return withWriteQueue(async () => {
226
264
  try {
227
265
  const taggedFinding = applyFindingTypePrefix(finding, findingType);
228
- // Memory link: auto-attach a symbol citation when the finding names one
229
- // unique symbol, or validate an explicit `symbol:` citation. Never rewrites
230
- // the finding text; only the citation comment gains the symbol.
266
+ // Memory link: link the finding to the one function, type or variable it
267
+ // names, or validate an explicit citation `name`. Never rewrites the
268
+ // finding text; only the citation comment gains the link.
231
269
  const code = moduleEnabled(phrenPath, "code") ? await loadCodePackage(phrenPath) : undefined;
232
270
  const symbolCitation = code ? await code.symbolCitationForFinding(phrenPath, project, taggedFinding, citation?.symbol) : citation?.symbol ? { symbol: citation.symbol } : {};
233
271
  const citationForWrite = (citation || symbolCitation.symbol)
@@ -508,6 +546,87 @@ async function handleRemoveFinding(ctx, { project: projectInput, finding }) {
508
546
  return mcpResponse({ ok: true, message: result.message, data: result.data });
509
547
  });
510
548
  }
549
+ /**
550
+ * Commit and push the team-safe pathspecs of every attached team store. Team
551
+ * stores are independent repos, so push_changes runs this whatever happens to
552
+ * the primary store.
553
+ */
554
+ export async function syncTeamStores(phrenPath) {
555
+ const teamResults = [];
556
+ try {
557
+ const { execFileSync } = await import("child_process");
558
+ const { getNonPrimaryStores } = await import("../store-registry.js");
559
+ const teamStores = getNonPrimaryStores(phrenPath).filter((s) => s.role === "team");
560
+ for (const store of teamStores) {
561
+ if (!fs.existsSync(store.path) || !fs.existsSync(path.join(store.path, ".git")))
562
+ continue;
563
+ const runStoreGit = (args, opts = {}) => execFileSync("git", args, {
564
+ cwd: store.path,
565
+ encoding: "utf8",
566
+ timeout: opts.timeout ?? EXEC_TIMEOUT_MS,
567
+ env: nonInteractiveGitEnv(opts.env),
568
+ stdio: ["ignore", "pipe", "pipe"],
569
+ }).trim();
570
+ const mergeStoreGit = async (_cwd, gitArgs) => {
571
+ try {
572
+ return { ok: true, output: runStoreGit(gitArgs) };
573
+ }
574
+ catch (err) {
575
+ return { ok: false, output: "", error: errorMessage(err) };
576
+ }
577
+ };
578
+ try {
579
+ if (!runStoreGit(["status", "--porcelain"]))
580
+ continue;
581
+ // Stage each team-safe pathspec individually — a single no-match
582
+ // (e.g. no */truths.md in this store) used to abort the whole add.
583
+ for (const spec of TEAM_STORE_PATHSPECS) {
584
+ try {
585
+ runStoreGit(["add", "--sparse", "--", spec]);
586
+ }
587
+ catch { /* best-effort */ }
588
+ }
589
+ if (!runStoreGit(["diff", "--cached", "--name-only"]))
590
+ continue;
591
+ const actor = process.env.PHREN_ACTOR || process.env.USER || "unknown";
592
+ runStoreGit(["commit", "-m", storeCommitMessage(`phren: ${actor} team sync`)]);
593
+ try {
594
+ runStoreGit(["push"], { timeout: 15000 });
595
+ teamResults.push({ store: store.name, pushed: true });
596
+ }
597
+ catch {
598
+ try {
599
+ const merged = await mergeStoreUpstream(store.path, { git: mergeStoreGit, commitLocalWrites: false });
600
+ if (merged.status !== "updated" && merged.status !== "unchanged")
601
+ throw new Error(merged.detail);
602
+ runStoreGit(["push"], { timeout: 15000 });
603
+ teamResults.push({ store: store.name, pushed: true });
604
+ }
605
+ catch (retryErr) {
606
+ teamResults.push({ store: store.name, pushed: false, error: errorMessage(retryErr) });
607
+ }
608
+ }
609
+ }
610
+ catch (storeErr) {
611
+ teamResults.push({ store: store.name, pushed: false, error: errorMessage(storeErr) });
612
+ }
613
+ }
614
+ }
615
+ catch (err) {
616
+ debugLog(`syncTeamStores: ${errorMessage(err)}`);
617
+ }
618
+ return teamResults;
619
+ }
620
+ /** Team-store outcomes appended to a push_changes message, so a failure is visible. */
621
+ function describeTeamSync(results) {
622
+ if (results.length === 0)
623
+ return "";
624
+ const pushed = results.filter((r) => r.pushed).map((r) => r.store);
625
+ const parts = pushed.length > 0 ? [`Pushed ${pushed.length} team store(s): ${pushed.join(", ")}.`] : [];
626
+ for (const failure of results.filter((r) => !r.pushed))
627
+ parts.push(`Team store "${failure.store}" failed: ${failure.error ?? "unknown error"}.`);
628
+ return ` ${parts.join(" ")}`;
629
+ }
511
630
  async function handlePushChanges(ctx, { message }) {
512
631
  const { phrenPath, withWriteQueue } = ctx;
513
632
  return withWriteQueue(async () => withFileLock(runtimeFile(phrenPath, "git-op"), async () => {
@@ -527,10 +646,13 @@ async function handlePushChanges(ctx, { message }) {
527
646
  return { ok: false, output: "", error: errorMessage(err) };
528
647
  }
529
648
  };
649
+ const teamResults = await syncTeamStores(phrenPath);
650
+ const teamSuffix = describeTeamSync(teamResults);
651
+ const teamData = teamResults.length > 0 ? { teamStores: teamResults } : {};
530
652
  try {
531
653
  const status = runGit(["status", "--porcelain"]);
532
654
  if (!status)
533
- return mcpResponse({ ok: true, message: "Nothing to save. Phren is up to date.", data: { files: 0, pushed: false } });
655
+ return mcpResponse({ ok: true, message: `Nothing to save. Phren is up to date.${teamSuffix}`, data: { files: 0, pushed: false, ...teamData } });
534
656
  const files = status.split("\n").filter(Boolean);
535
657
  const projectNames = Array.from(new Set(files
536
658
  .map((line) => line.slice(3).trim().split("/")[0])
@@ -561,7 +683,7 @@ async function handlePushChanges(ctx, { message }) {
561
683
  }
562
684
  if (!hasRemote) {
563
685
  const changedFiles = status.split("\n").filter(Boolean).length;
564
- return mcpResponse({ ok: true, message: `Saved ${changedFiles} changed file(s). No remote configured, skipping push.`, data: { files: changedFiles, pushed: false } });
686
+ return mcpResponse({ ok: true, message: `Saved ${changedFiles} changed file(s). No remote configured, skipping push.${teamSuffix}`, data: { files: changedFiles, pushed: false, ...teamData } });
565
687
  }
566
688
  let pushed = false;
567
689
  let lastPushError = "";
@@ -588,86 +710,18 @@ async function handlePushChanges(ctx, { message }) {
588
710
  const changedFiles = status.split("\n").filter(Boolean).length;
589
711
  runCustomHooks(phrenPath, "post-save", { PHREN_FILES_CHANGED: String(changedFiles), PHREN_PUSHED: String(pushed) });
590
712
  if (pushed) {
591
- return mcpResponse({ ok: true, message: `Saved ${changedFiles} changed file(s). Pushed to remote.`, data: { files: changedFiles, pushed: true } });
713
+ return mcpResponse({ ok: true, message: `Saved ${changedFiles} changed file(s). Pushed to remote.${teamSuffix}`, data: { files: changedFiles, pushed: true, ...teamData } });
592
714
  }
593
715
  else {
594
716
  return mcpResponse({
595
717
  ok: true,
596
- message: `Changes were committed but push failed.\n\nGit error: ${lastPushError}\n\nRun 'git push' manually from your phren directory.`,
597
- data: { files: changedFiles, pushed: false, pushError: lastPushError },
718
+ message: `Changes were committed but push failed.\n\nGit error: ${lastPushError}\n\nRun 'git push' manually from your phren directory.${teamSuffix}`,
719
+ data: { files: changedFiles, pushed: false, pushError: lastPushError, ...teamData },
598
720
  });
599
721
  }
600
722
  }
601
723
  catch (err) {
602
- return mcpResponse({ ok: false, error: `Save failed: ${errorMessage(err)}`, errorCode: "INTERNAL_ERROR" });
603
- }
604
- // Sync team stores: commit and push journal/tasks/truths changes
605
- try {
606
- const { getNonPrimaryStores } = await import("../store-registry.js");
607
- const teamStores = getNonPrimaryStores(phrenPath).filter((s) => s.role === "team");
608
- const teamResults = [];
609
- for (const store of teamStores) {
610
- if (!fs.existsSync(store.path) || !fs.existsSync(path.join(store.path, ".git")))
611
- continue;
612
- const runStoreGit = (args, opts = {}) => execFileSync("git", args, {
613
- cwd: store.path,
614
- encoding: "utf8",
615
- timeout: opts.timeout ?? EXEC_TIMEOUT_MS,
616
- env: nonInteractiveGitEnv(opts.env),
617
- stdio: ["ignore", "pipe", "pipe"],
618
- }).trim();
619
- const mergeStoreGit = async (_cwd, gitArgs) => {
620
- try {
621
- return { ok: true, output: runStoreGit(gitArgs) };
622
- }
623
- catch (err) {
624
- return { ok: false, output: "", error: errorMessage(err) };
625
- }
626
- };
627
- try {
628
- const storeStatus = runStoreGit(["status", "--porcelain"]);
629
- if (!storeStatus) {
630
- teamResults.push({ store: store.name, pushed: false });
631
- continue;
632
- }
633
- // Stage each team-safe pathspec individually — a single no-match
634
- // (e.g. no */truths.md in this store) used to abort the whole add.
635
- for (const spec of TEAM_STORE_PATHSPECS) {
636
- try {
637
- runStoreGit(["add", "--sparse", "--", spec]);
638
- }
639
- catch { /* best-effort */ }
640
- }
641
- const actor = process.env.PHREN_ACTOR || process.env.USER || "unknown";
642
- runStoreGit(["commit", "-m", storeCommitMessage(`phren: ${actor} team sync`)]);
643
- try {
644
- runStoreGit(["push"], { timeout: 15000 });
645
- teamResults.push({ store: store.name, pushed: true });
646
- }
647
- catch {
648
- try {
649
- const merged = await mergeStoreUpstream(store.path, { git: mergeStoreGit, commitLocalWrites: false });
650
- if (merged.status !== "updated" && merged.status !== "unchanged")
651
- throw new Error(merged.detail);
652
- runStoreGit(["push"], { timeout: 15000 });
653
- teamResults.push({ store: store.name, pushed: true });
654
- }
655
- catch (retryErr) {
656
- teamResults.push({ store: store.name, pushed: false, error: errorMessage(retryErr) });
657
- }
658
- }
659
- }
660
- catch (storeErr) {
661
- teamResults.push({ store: store.name, pushed: false, error: errorMessage(storeErr) });
662
- }
663
- }
664
- // Team store results are best-effort — don't fail the primary push for them
665
- if (teamResults.length > 0) {
666
- debugLog(`push_changes team stores: ${JSON.stringify(teamResults)}`);
667
- }
668
- }
669
- catch {
670
- // store-registry not available — skip silently
724
+ return mcpResponse({ ok: false, error: `Save failed: ${errorMessage(err)}${teamSuffix}`, errorCode: "INTERNAL_ERROR" });
671
725
  }
672
726
  }));
673
727
  }
@@ -688,7 +742,8 @@ export function register(server, ctx) {
688
742
  line: z.number().int().positive().optional().describe("1-based line number in file."),
689
743
  repo: z.string().optional().describe("Git repository root path for citation validation."),
690
744
  commit: z.string().optional().describe("Git commit SHA that supports this finding."),
691
- symbol: z.string().optional().describe("A code symbol this finding is about: Name, Type.member or name(). Validated against the project's code index; stored unresolved when it does not resolve."),
745
+ name: z.string().optional().describe("The function, type or variable this finding is about: Name, Type.member or name(). Validated against the project's code index; stored unresolved when it does not resolve."),
746
+ symbol: z.string().optional().describe("Deprecated: use name. Accepted until @phren/cli 0.3.1."),
692
747
  supersedes: z.string().optional().describe("First 60 chars of the old finding this one replaces. The old entry will be marked as superseded."),
693
748
  task_item: z.string().optional().describe("Task item stable ID like bid:abcd1234, positional ID like A1, or item text to link this finding to."),
694
749
  }).optional().describe("Optional source citation for traceability (only used when finding is a single string)."),
@@ -10,6 +10,8 @@ import { clearTaskCheckpoint } from "../session/checkpoints.js";
10
10
  import { incrementSessionTasksCompleted } from "./session.js";
11
11
  import { normalizeMemoryScope } from "../shared.js";
12
12
  import { permissionDeniedError } from "../governance/rbac.js";
13
+ import { getMachineName } from "../machine-identity.js";
14
+ import { claimTaskSynced } from "../sync/task-claim.js";
13
15
  const TASK_SECTION_ORDER = ["Active", "Queue", "Done"];
14
16
  const DEFAULT_TASK_LIMIT = 20;
15
17
  /** Done items are historical — cap tightly by default to avoid large responses. */
@@ -80,7 +82,8 @@ function buildTaskSummary(doc, includedSections) {
80
82
  const prio = item.priority ? ` [${item.priority}]` : "";
81
83
  const bidPrefix = item.stableId ? `bid:${item.stableId} ` : "";
82
84
  const githubTag = item.githubIssue ? ` [gh:#${item.githubIssue}]` : item.githubUrl ? " [gh]" : "";
83
- lines.push(` - ${bidPrefix}${item.line.slice(0, 80)}${item.line.length > 80 ? "\u2026" : ""}${prio}${githubTag}`);
85
+ const claimTag = item.claim ? ` [claimed: ${item.claim.computer}]` : "";
86
+ lines.push(` - ${bidPrefix}${item.line.slice(0, 80)}${item.line.length > 80 ? "\u2026" : ""}${prio}${githubTag}${claimTag}`);
84
87
  }
85
88
  if (items.length > 3)
86
89
  lines.push(` ... and ${items.length - 3} more`);
@@ -548,6 +551,42 @@ export function register(server, ctx) {
548
551
  return mcpResponse({ ok: true, message: result.data, data: { project, keep: keep ?? 30, dryRun: dry_run ?? false } });
549
552
  });
550
553
  });
554
+ server.registerTool("claim_task", {
555
+ title: "◆ phren · claim task",
556
+ description: "Claim a task for this computer so conductors that are not linked do not take the same work: " +
557
+ "syncs the store, moves the task to Active with a `Claimed:` line naming this computer, then commits and pushes. " +
558
+ "Refuses a task another computer holds. With release, clears this computer's claim and returns the task to the Queue. " +
559
+ "Conductors skip tasks claimed by other computers.",
560
+ inputSchema: z.object({
561
+ project: z.string().describe("Project name."),
562
+ item: z.string().describe("Task to claim: bid:XXXXXXXX, a positional ID (Q3) or its text."),
563
+ session: z.string().regex(/^[A-Za-z0-9._:-]{1,128}$/).optional().describe("The claiming conductor's session id, recorded with the claim."),
564
+ release: z.boolean().optional().describe("Release this computer's claim instead of taking one."),
565
+ force: z.boolean().optional().describe("Take over another computer's claim once it is more than a day old."),
566
+ }),
567
+ }, async ({ project: projectInput, item, session, release, force }) => {
568
+ const resolved = resolveStoreForProject(ctx, projectInput);
569
+ const project = resolved.project;
570
+ const targetPath = resolved.phrenPath;
571
+ if (!isValidProjectName(project))
572
+ return mcpResponse({ ok: false, error: `Invalid project name: "${project}"` });
573
+ const denied = permissionDeniedError(targetPath, "claim_task", project);
574
+ if (denied)
575
+ return mcpResponse({ ok: false, error: denied });
576
+ return withWriteQueue(async () => {
577
+ // The Claimed line takes a plain token; a name with spaces would never parse back.
578
+ const computer = getMachineName().replace(/[^A-Za-z0-9._-]+/g, "-").replace(/^[^A-Za-z0-9]+/, "") || "computer";
579
+ const claim = { computer, at: new Date().toISOString().replace(/\.\d{3}Z$/, "Z"), ...(session ? { session } : {}) };
580
+ const outcome = await claimTaskSynced(targetPath, project, item, claim, { release, force });
581
+ if (outcome.error)
582
+ return mcpResponse({ ok: false, error: outcome.error });
583
+ refreshTaskIndex(updateFileInIndex, targetPath, project);
584
+ const message = release ? `Released in ${project}. ${outcome.detail}`
585
+ : outcome.claimed ? `Claimed for ${claim.computer} in ${project}. ${outcome.detail}` : `Not claimed: ${outcome.detail}`;
586
+ return mcpResponse({ ok: release ? true : outcome.claimed, message,
587
+ data: { project, item: outcome.item?.stableId ? `bid:${outcome.item.stableId}` : item, claim: outcome.item?.claim, heldBy: outcome.heldBy, synced: outcome.synced } });
588
+ });
589
+ });
551
590
  server.registerTool("pin_task", {
552
591
  title: "◆ phren · pin task",
553
592
  description: "Pin or unpin a task. Pinned tasks always appear in hook context regardless of priority, " +
package/dist/ui/server.js CHANGED
@@ -683,7 +683,24 @@ function handlePostSync(req, res, url, ctx) {
683
683
  const status = runGit(["status", "--porcelain"]);
684
684
  if (!status)
685
685
  return jsonOk(res, { ok: true, message: "Nothing to sync — working tree clean." });
686
- runGit(["add", "--", "*.md", "*.json", "*.yaml", "*.yml", "*.jsonl", "*.txt"]);
686
+ // Stage each extension separately: `git add` exits 128 as soon as ONE
687
+ // pathspec matches nothing, and a normal store has no tracked .yml,
688
+ // .jsonl or .txt (.runtime/*.jsonl is gitignored, and gitignored files do
689
+ // not satisfy a pathspec). One combined add therefore failed on every
690
+ // non-clean store and the user saw a raw git fatal instead of a sync.
691
+ for (const spec of ["*.md", "*.json", "*.yaml", "*.yml", "*.jsonl", "*.txt"]) {
692
+ try {
693
+ execFileSync("git", ["add", "--", spec], {
694
+ env: nonInteractiveGitEnv(),
695
+ cwd: ctx.phrenPath,
696
+ encoding: "utf8",
697
+ timeout: EXEC_TIMEOUT,
698
+ // A non-matching pathspec is expected here; don't print git's fatal.
699
+ stdio: ["ignore", "ignore", "ignore"],
700
+ });
701
+ }
702
+ catch { /* no file with this extension */ }
703
+ }
687
704
  const stagedFiles = runGit(["diff", "--cached", "--name-only"]);
688
705
  if (!stagedFiles)
689
706
  return jsonOk(res, { ok: true, message: "Nothing to sync — no matching files to commit." });
package/dist/update.js CHANGED
@@ -1,16 +1,25 @@
1
1
  import * as fs from "fs";
2
2
  import * as path from "path";
3
3
  import { execFileSync } from "child_process";
4
- import { fileURLToPath } from "url";
5
4
  import { errorMessage } from "./utils.js";
6
- import { PACKAGE_NAME, PACKAGE_SPEC } from "./package-metadata.js";
5
+ import { PACKAGE_NAME, PACKAGE_SPEC, ROOT } from "./package-metadata.js";
6
+ import { resolveEntryScript } from "./init/shared.js";
7
+ import { findPhrenPath } from "./shared.js";
7
8
  import { logger } from "./logger.js";
8
9
  function shellCommand(bin) {
9
10
  return process.platform === "win32" ? `${bin}.cmd` : bin;
10
11
  }
11
- function packageRootFromRuntime() {
12
- const current = fileURLToPath(import.meta.url);
13
- return path.resolve(path.dirname(current), "..", "..");
12
+ /**
13
+ * The source checkout this build runs from, or null for an installed package.
14
+ * The package root is packages/cli, so the monorepo root is two levels above it.
15
+ * An installed package (under node_modules) is never treated as a checkout, even
16
+ * if some directory above it happens to be a git repo.
17
+ */
18
+ function sourceCheckoutRoot() {
19
+ if (ROOT.split(path.sep).includes("node_modules"))
20
+ return null;
21
+ const repoRoot = path.resolve(ROOT, "..", "..");
22
+ return fs.existsSync(path.join(repoRoot, ".git")) ? repoRoot : null;
14
23
  }
15
24
  function run(cmd, args, cwd) {
16
25
  return execFileSync(cmd, args, {
@@ -45,16 +54,18 @@ function maybeRefreshStarter(root, builtEntry, refreshStarter) {
45
54
  return " Run `phren update --refresh-starter` to refresh global starter assets.";
46
55
  }
47
56
  run(process.execPath, [builtEntry, "init", "--apply-starter-update", "-y"], root);
48
- const cleaned = cleanupStarterRefreshArtifacts(root);
57
+ // The staged starter files live in the store, not the package.
58
+ const phrenPath = findPhrenPath();
59
+ const cleaned = phrenPath ? cleanupStarterRefreshArtifacts(phrenPath) : 0;
49
60
  return cleaned > 0
50
61
  ? ` Refreshed starter assets and cleaned ${cleaned} staged starter artifact(s).`
51
62
  : " Refreshed starter assets.";
52
63
  }
53
64
  export async function runPhrenUpdate(opts = {}) {
54
- const root = packageRootFromRuntime();
55
- const hasGit = fs.existsSync(path.join(root, ".git"));
56
- const builtEntry = path.join(root, "mcp", "dist", "index.js");
57
- if (hasGit) {
65
+ const checkout = sourceCheckoutRoot();
66
+ const root = checkout ?? ROOT;
67
+ const builtEntry = resolveEntryScript();
68
+ if (checkout) {
58
69
  try {
59
70
  // Warn if working tree is dirty (autostash handles it, but good to know)
60
71
  try {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@phren/cli",
3
- "version": "0.2.16",
3
+ "version": "0.3.1",
4
4
  "description": "Knowledge layer for AI agents - CLI, MCP server, and data layer",
5
5
  "type": "module",
6
6
  "bin": {
@@ -149,14 +149,15 @@
149
149
  "preuninstall": "node scripts/preuninstall.mjs"
150
150
  },
151
151
  "dependencies": {
152
- "@modelcontextprotocol/sdk": "^1.30.0",
152
+ "@modelcontextprotocol/sdk": "^1.30.1",
153
153
  "chalk": "^6.0.0",
154
154
  "glob": "^13.0.6",
155
- "inquirer": "^14.1.0",
156
- "js-yaml": "^5.3.0",
155
+ "inquirer": "^14.2.2",
156
+ "js-yaml": "^5.4.2",
157
157
  "sql.js-fts5": "^1.4.0",
158
+ "uqr": "0.1.3",
158
159
  "ws": "8.21.3",
159
- "zod": "^4.4.3"
160
+ "zod": "^4.6.5"
160
161
  },
161
162
  "engines": {
162
163
  "node": ">=20.0.0"
@@ -177,9 +178,9 @@
177
178
  },
178
179
  "devDependencies": {
179
180
  "3d-force-graph": "^1.80.0",
181
+ "@phren/code": "workspace:*",
180
182
  "@types/ws": "8.18.1",
181
- "three": "^0.185.1",
182
- "@phren/code": "workspace:*"
183
+ "three": "^0.186.1"
183
184
  },
184
185
  "publishConfig": {
185
186
  "access": "public"
@@ -30,24 +30,45 @@ Your tools, use these instead of exploring the CLI or the Hook's files:
30
30
  - `dispatch`: start a new worker on a computer (or `anywhere`).
31
31
  - `dispatch_returns` (CLI `phren dispatch returns`): what your workers sent
32
32
  back since you last asked: done with the final reply, needs-you with the
33
- question, blocked, or gone. Reading them marks them read. In core use
33
+ question, failed with the error (a usage limit), blocked, or gone. Reading them marks them read. In core use
34
34
  `phren_admin(action: "dispatch_returns")`.
35
35
  - `phren dispatch status`: receipts of what you dispatched.
36
36
  - `get_tasks`, `get_project_summary`, `search_knowledge`: the store's memory.
37
37
 
38
- Keep
39
- engineering detail in worker briefs and review artifacts. In the owner's chat,
40
- write one short line per dispatch and one per return:
38
+ Keep engineering detail in worker briefs, Phren tasks and findings, and review
39
+ artifacts, not in the owner's chat.
40
+
41
+ ## Voice and pace
42
+
43
+ The owner talks to you from the phone, often in talk mode, where your replies
44
+ are read aloud in their voice. Sound like a good dispatcher: short, quick and
45
+ conversational.
46
+
47
+ - Lead with the outcome in one sentence. Keep the whole reply to one to four
48
+ short sentences unless the owner asks for detail.
49
+ - No tables, file paths, SHAs, PR numbers or run IDs in a reply unless the
50
+ owner asks for them. Record them in Phren tasks and findings instead.
51
+ - One short line per dispatch or return: who, what, result. A routine watcher
52
+ or monitor event where nothing changed gets silence or a single line.
53
+ - When the owner gives you a task, dispatch an engineer for it right away and
54
+ say so in one line. That is the owner's standing rule; do not ask first.
55
+ - Ask at most one question at a time, and name the options.
56
+ - Delegate reading and analysis to workers instead of running long
57
+ investigations yourself, so your own turns stay fast.
58
+ - A message that begins with `[voice]` was spoken in talk mode, and your reply
59
+ will be read aloud. Answer in one or two spoken sentences with no markdown,
60
+ lists, symbols or code, written to sound natural read aloud: "back in about
61
+ twenty minutes", not "ETA ~20m".
41
62
 
42
63
  ```text
43
- Linuxbox: parser checks sent to Codex (configured default); report due 14:20 PT.
44
- Desk: navigation checks returned; tests passed; not merged.
64
+ Linuxbox has the parser checks on Codex, back around two twenty.
65
+ Desk finished the navigation checks: tests passed, not merged yet.
45
66
  ```
46
67
 
47
- Include computer, brief, harness/model, and the next expected report time on a
48
- dispatch. Include who finished what, test result and merged/not merged on a
49
- return. If a result or deadline is unknown, say so. Surface questions in the same
50
- short voice with the worker's choices; do not turn the chat into code commentary.
68
+ If a result or return time is unknown, say so. Surface a worker's question in
69
+ the same short voice, with the worker's own choices.
70
+
71
+ ## Dispatching
51
72
 
52
73
  Pick five to ten independent tasks when that many are available and capacity
53
74
  permits. Do not manufacture tasks to fill the batch. Separate dependencies and
@@ -56,6 +77,17 @@ fanout limit, report time and integration instructions. Every brief repeats the
56
77
  owner's repository constraints, including any prohibition on commits, pushes,
57
78
  branches or particular tests. Dispatch never expands the owner's authorization.
58
79
 
80
+ You are the one conductor for this computer and every computer linked with
81
+ it; a second conductor in the group is refused at launch. Conductors on
82
+ computers that are not linked share only the store, so claim a task before you
83
+ dispatch it: `claim_task` (in core, `manage_task` with `action: "claim"`).
84
+ Skip tasks marked `[claimed: <computer>]` by another computer. A claim that
85
+ comes back not claimed, with `heldBy`, means another conductor got there first:
86
+ move on. Completing a task clears its claim; release one you will not do. Start
87
+ workers with `dispatch` or `hand_off`, never as tabs in your own Herdr
88
+ workspace. When a computer shows up in `notLinked`, tell the owner that
89
+ `phren bridge link <host>` can link it; never link a computer yourself.
90
+
59
91
  Prefer Codex. Use OpenCode Go when its account and harness are connected. Use
60
92
  OpenRouter only when the owner explicitly requests it; an unavailable account
61
93
  does not authorize another paid provider. Name an explicit model when instructed,