@phren/cli 0.3.0 → 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 (55) hide show
  1. package/dist/bridge/agent-hooks.d.ts +15 -6
  2. package/dist/bridge/agent-hooks.js +55 -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/command.js +92 -2
  6. package/dist/bridge/computers.d.ts +5 -0
  7. package/dist/bridge/computers.js +10 -4
  8. package/dist/bridge/conductor-group.d.ts +23 -0
  9. package/dist/bridge/conductor-group.js +25 -0
  10. package/dist/bridge/hand-off.js +5 -1
  11. package/dist/bridge/herdr.d.ts +7 -0
  12. package/dist/bridge/herdr.js +53 -2
  13. package/dist/bridge/link.d.ts +48 -0
  14. package/dist/bridge/link.js +136 -0
  15. package/dist/bridge/memory-store.d.ts +23 -0
  16. package/dist/bridge/memory-store.js +152 -0
  17. package/dist/bridge/pair.d.ts +46 -0
  18. package/dist/bridge/pair.js +240 -0
  19. package/dist/bridge/peers.d.ts +9 -0
  20. package/dist/bridge/peers.js +25 -2
  21. package/dist/bridge/server-launch.d.ts +9 -0
  22. package/dist/bridge/server-launch.js +34 -11
  23. package/dist/bridge/server-pane-routes.js +38 -7
  24. package/dist/bridge/server-routes.d.ts +1 -0
  25. package/dist/bridge/server-routes.js +11 -3
  26. package/dist/bridge/server-stream.js +4 -1
  27. package/dist/bridge/speech-key.d.ts +33 -0
  28. package/dist/bridge/speech-key.js +106 -0
  29. package/dist/bridge/speech-transcribe.js +1 -1
  30. package/dist/bridge/speech.d.ts +1 -3
  31. package/dist/bridge/speech.js +2 -16
  32. package/dist/bridge-hook.mjs +1198 -492
  33. package/dist/cli-handlers.js +6 -0
  34. package/dist/cli-registry.js +14 -2
  35. package/dist/content/learning.js +1 -1
  36. package/dist/data/tasks.d.ts +26 -0
  37. package/dist/data/tasks.js +72 -1
  38. package/dist/entrypoint.js +7 -0
  39. package/dist/governance/rbac.d.ts +1 -1
  40. package/dist/governance/rbac.js +1 -0
  41. package/dist/init/init-walkthrough.d.ts +10 -0
  42. package/dist/init/init-walkthrough.js +24 -1
  43. package/dist/init/init.d.ts +5 -0
  44. package/dist/init/init.js +54 -32
  45. package/dist/link/doctor.js +10 -0
  46. package/dist/mcp/profile.js +2 -1
  47. package/dist/modules/config.d.ts +7 -0
  48. package/dist/modules/config.js +17 -0
  49. package/dist/modules/registry.js +5 -4
  50. package/dist/sync/task-claim.d.ts +22 -0
  51. package/dist/sync/task-claim.js +45 -0
  52. package/dist/tools/dispatch.js +2 -2
  53. package/dist/tools/tasks.js +40 -1
  54. package/package.json +2 -1
  55. package/starter/global/skills/conductor/SKILL.md +41 -9
@@ -150,11 +150,17 @@ export async function runInitCommand(args) {
150
150
  dryRun: args.includes("--dry-run"),
151
151
  yes: args.includes("--yes") || args.includes("-y"),
152
152
  express: args.includes("--express"),
153
+ advanced: args.includes("--advanced"),
153
154
  force: args.includes("--force"),
154
155
  _walkthroughCloneUrl: cloneUrl,
155
156
  });
156
157
  }
157
158
  catch (err) {
159
+ // Ctrl-C inside a prompt: say so plainly instead of Inquirer's internals.
160
+ if (err instanceof Error && err.name === "ExitPromptError") {
161
+ console.error("\nSetup cancelled. Run phren init again any time.");
162
+ return 130;
163
+ }
158
164
  console.error(errorMessage(err));
159
165
  return 1;
160
166
  }
@@ -132,11 +132,23 @@ const TEAM_SUBCOMMANDS = [
132
132
  // ── Registry ─────────────────────────────────────────────────────────────────
133
133
  export const REGISTRY = [
134
134
  {
135
- name: "bridge", topic: "setup", usage: "phren bridge <install|status|doctor|update|rollback|uninstall|enroll-computer|fanouts archive>",
135
+ name: "pair", topic: "setup", usage: "phren pair [--minutes <1-30>] [--port <n>] [--no-install]",
136
+ summary: "Connect your phone: show a pairing QR code and authorize the phone that scans it",
137
+ run: async (args) => {
138
+ const { runPair } = await import("./bridge/pair.js");
139
+ const { VERSION } = await import("./package-metadata.js");
140
+ return runPair(args, VERSION);
141
+ },
142
+ },
143
+ {
144
+ name: "bridge", topic: "setup", usage: "phren bridge <install|status|doctor|update|rollback|uninstall|enroll-computer|discover|link|fanouts archive|speech-key set>",
136
145
  summary: "Install Phren Hook and enroll phone or computer connections",
137
146
  subcommands: [
138
147
  { name: "enroll-computer", usage: "phren bridge enroll-computer <name> [--accept <public-key-file>]", summary: "Print or accept a restricted computer dispatch key" },
148
+ { name: "discover", usage: "phren bridge discover", summary: "List computers you already reach over ssh that run Phren Hook and are not linked" },
149
+ { name: "link", usage: "phren bridge link <ssh-host> [--name <name>] [--as <name>] [--back-address <address>] [--yes]", summary: "Link this computer and an ssh host both ways in one step, after confirming" },
139
150
  { name: "fanouts archive", usage: "phren bridge fanouts archive [--dry-run] [--parent <session-id>] [--older-than <minutes>]", summary: "Archive finished fan-out jobs older than 24 hours, or one parent chat's, or older than N minutes" },
151
+ { name: "speech-key set", usage: "phren bridge speech-key set", summary: "Store this computer's ElevenLabs key for spoken replies and dictation (read from stdin, mode 600)" },
140
152
  ],
141
153
  run: async (args) => {
142
154
  const { runBridge } = await import("./bridge/command.js");
@@ -174,7 +186,7 @@ export const REGISTRY = [
174
186
  {
175
187
  name: "init",
176
188
  topic: "setup",
177
- usage: "phren init [--preset managed|assisted|manual] [--mode shared|project-local] [--machine <n>] [--profile <n>] [--dry-run] [-y]",
189
+ usage: "phren init [--advanced] [--preset managed|assisted|manual] [--mode shared|project-local] [--machine <n>] [--profile <n>] [--dry-run] [-y]",
178
190
  cheatUsage: "phren init",
179
191
  summary: "Set up phren",
180
192
  featured: true,
@@ -20,7 +20,7 @@ const DEFAULT_FINDINGS_CAP = 20;
20
20
  const LIFECYCLE_ANNOTATION_RE = METADATA_REGEX.lifecycleAnnotation;
21
21
  /** Default finding-id source: 8 lowercase hex chars from a CSPRNG. Overridable
22
22
  * via `AddFindingOptions.idSource` for deterministic fixture generation
23
- * (apps/ios/scripts/generate-fixtures.mjs) — production callers never set it,
23
+ * (the phren apps' generate-fixtures.mjs) — production callers never set it,
24
24
  * so this is the only thing that ever runs outside tests. */
25
25
  function defaultFindingIdSource() {
26
26
  return crypto.randomBytes(4).toString("hex");
@@ -14,6 +14,8 @@ export interface TaskItem {
14
14
  pinned?: boolean;
15
15
  githubIssue?: number;
16
16
  githubUrl?: string;
17
+ /** The computer (and optionally the session) that took this task; see claimTask. */
18
+ claim?: TaskClaim;
17
19
  rank?: number;
18
20
  lastActivity?: string;
19
21
  createdAt?: string;
@@ -23,6 +25,17 @@ export interface TaskItem {
23
25
  speculative?: boolean;
24
26
  parentFinding?: string;
25
27
  }
28
+ /**
29
+ * A conductor's claim on a task, written under it in tasks.md as
30
+ * ` Claimed: <computer> <ISO time> [session:<id>]`. Conductors that are not
31
+ * linked coordinate through the synced store: a claimed task is Active and
32
+ * belongs to the claiming computer until it is done or released.
33
+ */
34
+ export interface TaskClaim {
35
+ computer: string;
36
+ at: string;
37
+ session?: string;
38
+ }
26
39
  export interface TaskDoc {
27
40
  project: string;
28
41
  title: string;
@@ -94,6 +107,19 @@ export declare function unpinTask(phrenPath: string, project: string, match: str
94
107
  export declare function reorderTask(phrenPath: string, project: string, match: string, targetRank: number): PhrenResult<string>;
95
108
  export declare function appendChildFinding(phrenPath: string, project: string, match: string, findingId: string): PhrenResult<string>;
96
109
  export declare function promoteTask(phrenPath: string, project: string, match: string, moveToActive: boolean): PhrenResult<TaskItem>;
110
+ /** A claim this old may be taken over with `force`: its conductor has likely gone. */
111
+ export declare const STALE_CLAIM_MS: number;
112
+ /**
113
+ * Takes a task for `claim.computer`: moves it to Active and records the claim.
114
+ * Refuses a task another computer holds unless `force` is set and that claim
115
+ * is stale; claiming again from the same computer refreshes it. With
116
+ * `release`, clears this computer's claim and returns the task to the Queue.
117
+ */
118
+ export declare function claimTask(phrenPath: string, project: string, match: string, claim: TaskClaim, opts?: {
119
+ release?: boolean;
120
+ force?: boolean;
121
+ now?: number;
122
+ }): PhrenResult<TaskItem>;
97
123
  export declare function workNextTask(phrenPath: string, project: string): PhrenResult<string>;
98
124
  export declare function tidyDoneTasks(phrenPath: string, project: string, keep?: number, dryRun?: boolean): PhrenResult<string>;
99
125
  export declare function taskMarkdown(doc: TaskDoc): string;
@@ -13,6 +13,10 @@ const ACTIVE_HEADINGS = new Set(["active", "in progress", "in-progress", "curren
13
13
  const QUEUE_HEADINGS = new Set(["queue", "queued", "task", "todo", "upcoming", "next"]);
14
14
  const DONE_HEADINGS = new Set(["done", "completed", "finished", "archived"]);
15
15
  export { TASK_FILE_ALIASES, TASKS_FILENAME, isTaskFileName } from "../filenames.js";
16
+ const CLAIM_LINE = /^Claimed:\s+([A-Za-z0-9][A-Za-z0-9._-]{0,252})\s+(\d{4}-\d{2}-\d{2}T[0-9:.]+Z)(?:\s+session:([A-Za-z0-9._:-]{1,128}))?$/;
17
+ function formatClaim(claim) {
18
+ return `Claimed: ${claim.computer} ${claim.at}${claim.session ? ` session:${claim.session}` : ""}`;
19
+ }
16
20
  const TASK_SECTIONS = ["Active", "Queue", "Done"];
17
21
  function normalizePriority(text) {
18
22
  const m = text.replace(/\s*\[pinned\]/gi, "").match(/\[(high|medium|low)\]\s*$/i);
@@ -77,6 +81,7 @@ function formatGitHubIssueReference(item) {
77
81
  }
78
82
  function parseContinuation(lines, idx) {
79
83
  let context;
84
+ let claim;
80
85
  let githubIssue;
81
86
  let githubUrl;
82
87
  let linesToSkip = 0;
@@ -94,6 +99,12 @@ function parseContinuation(lines, idx) {
94
99
  linesToSkip++;
95
100
  continue;
96
101
  }
102
+ const claimed = CLAIM_LINE.exec(trimmed);
103
+ if (claimed) {
104
+ claim = { computer: claimed[1], at: claimed[2], ...(claimed[3] ? { session: claimed[3] } : {}) };
105
+ linesToSkip++;
106
+ continue;
107
+ }
97
108
  if (trimmed.startsWith("GitHub:")) {
98
109
  const parsed = parseGitHubIssueReference(trimmed.slice("GitHub:".length));
99
110
  githubIssue = parsed.githubIssue;
@@ -103,7 +114,7 @@ function parseContinuation(lines, idx) {
103
114
  }
104
115
  break;
105
116
  }
106
- return { context, githubIssue, githubUrl, linesToSkip };
117
+ return { context, githubIssue, githubUrl, claim, linesToSkip };
107
118
  }
108
119
  /** Pattern that matches the task metadata comment embedded in task item lines.
109
120
  * Format: <!-- bid:HASH [rank:N] [lastActivity:ISO] -->
@@ -251,6 +262,7 @@ function parseTaskContent(project, taskPath, content) {
251
262
  pinned: pinned || undefined,
252
263
  githubIssue: continuation.githubIssue,
253
264
  githubUrl: continuation.githubUrl,
265
+ claim: continuation.claim,
254
266
  });
255
267
  i += continuation.linesToSkip;
256
268
  }
@@ -277,6 +289,8 @@ function renderTask(doc) {
277
289
  const githubRef = formatGitHubIssueReference(item);
278
290
  if (githubRef)
279
291
  out.push(` GitHub: ${githubRef}`);
292
+ if (item.claim)
293
+ out.push(` ${formatClaim(item.claim)}`);
280
294
  }
281
295
  out.push("");
282
296
  }
@@ -499,6 +513,7 @@ export function completeTasks(phrenPath, project, matches) {
499
513
  const [item] = parsed.data.items[found.match.section].splice(found.match.index, 1);
500
514
  item.section = "Done";
501
515
  item.checked = true;
516
+ item.claim = undefined;
502
517
  parsed.data.items.Done.unshift(item);
503
518
  completed.push(item.line);
504
519
  }
@@ -525,6 +540,7 @@ export function completeTask(phrenPath, project, match) {
525
540
  const [item] = parsed.data.items[found.match.section].splice(found.match.index, 1);
526
541
  item.section = "Done";
527
542
  item.checked = true;
543
+ item.claim = undefined;
528
544
  parsed.data.items.Done.unshift(item);
529
545
  writeTaskDoc(parsed.data);
530
546
  return phrenOk(`Marked done in ${project}: ${item.line}`);
@@ -804,6 +820,61 @@ export function promoteTask(phrenPath, project, match, moveToActive) {
804
820
  return phrenOk(item);
805
821
  });
806
822
  }
823
+ /** A claim this old may be taken over with `force`: its conductor has likely gone. */
824
+ export const STALE_CLAIM_MS = 24 * 60 * 60 * 1000;
825
+ /**
826
+ * Takes a task for `claim.computer`: moves it to Active and records the claim.
827
+ * Refuses a task another computer holds unless `force` is set and that claim
828
+ * is stale; claiming again from the same computer refreshes it. With
829
+ * `release`, clears this computer's claim and returns the task to the Queue.
830
+ */
831
+ export function claimTask(phrenPath, project, match, claim, opts = {}) {
832
+ const bPath = canonicalTaskFilePath(phrenPath, project);
833
+ if (!bPath)
834
+ return phrenErr(`Project name "${project}" is not valid.`, PhrenError.INVALID_PROJECT_NAME);
835
+ const preCheck = ensureProject(phrenPath, project);
836
+ if (!preCheck.ok)
837
+ return forwardErr(preCheck);
838
+ return withSafeLock(bPath, () => {
839
+ const parsed = readTasks(phrenPath, project);
840
+ if (!parsed.ok)
841
+ return forwardErr(parsed);
842
+ const found = findItemByMatch(parsed.data, match);
843
+ if (found.error)
844
+ return phrenErr(found.error, found.errorCode ?? PhrenError.AMBIGUOUS_MATCH);
845
+ if (!found.match)
846
+ return taskItemNotFound(project, match);
847
+ const item = parsed.data.items[found.match.section][found.match.index];
848
+ if (item.section === "Done")
849
+ return phrenErr(`This task is already done: ${item.line}`, PhrenError.VALIDATION_ERROR);
850
+ const held = item.claim && item.claim.computer !== claim.computer ? item.claim : undefined;
851
+ if (held) {
852
+ const stale = (opts.now ?? Date.now()) - Date.parse(held.at) > STALE_CLAIM_MS;
853
+ if (!opts.force || !stale) {
854
+ return phrenErr(`${held.computer} claimed this task at ${held.at}${stale ? "; the claim is over a day old, so force can take it over" : ""}.`, PhrenError.PERMISSION_DENIED);
855
+ }
856
+ }
857
+ if (opts.release) {
858
+ if (!item.claim)
859
+ return phrenErr(`This task is not claimed: ${item.line}`, PhrenError.VALIDATION_ERROR);
860
+ item.claim = undefined;
861
+ parsed.data.items[item.section].splice(found.match.index, 1);
862
+ item.section = "Queue";
863
+ parsed.data.items.Queue.unshift(item);
864
+ }
865
+ else {
866
+ item.claim = claim;
867
+ if (item.section !== "Active") {
868
+ parsed.data.items[item.section].splice(found.match.index, 1);
869
+ item.section = "Active";
870
+ item.checked = false;
871
+ parsed.data.items.Active.unshift(item);
872
+ }
873
+ }
874
+ writeTaskDoc(parsed.data);
875
+ return phrenOk(item);
876
+ });
877
+ }
807
878
  export function workNextTask(phrenPath, project) {
808
879
  const bPath = canonicalTaskFilePath(phrenPath, project);
809
880
  if (!bPath)
@@ -1,4 +1,5 @@
1
1
  import { activateModules, moduleSnapshot } from "./modules/runtime.js";
2
+ import { enableHookForPhone } from "./modules/config.js";
2
3
  import { disabledCommand } from "./cli-registry.js";
3
4
  import * as fs from "fs";
4
5
  import * as path from "path";
@@ -149,6 +150,12 @@ export async function runTopLevelCommand(argv, opts = {}) {
149
150
  const store = findPhrenPath() ?? defaultPhrenPath();
150
151
  snapshot = ["modules", "init", "quickstart", "verify", "uninstall", "doctor"].includes(cmd.name) || argv.includes("--help") || argv.includes("-h")
151
152
  ? moduleSnapshot(store) : activateModules(store);
153
+ const wantsHook = cmd.name === "pair" || (cmd.name === "bridge" && argv[1] === "install");
154
+ if (wantsHook && !snapshot.has("hook") && !argv.includes("--help") && !argv.includes("-h")) {
155
+ if (enableHookForPhone(store))
156
+ console.log("Turned on the Hook module for this store (phren modules disable hook turns it off).");
157
+ snapshot = activateModules(store, undefined, true);
158
+ }
152
159
  const unavailable = disabledCommand([cmd.name, ...argv.slice(1)].join(" "), snapshot);
153
160
  if (unavailable) {
154
161
  console.error(unavailable);
@@ -16,7 +16,7 @@
16
16
  *
17
17
  * The actor is read from the PHREN_ACTOR env var (falls back to open if unset).
18
18
  */
19
- type RbacAction = "add_finding" | "remove_finding" | "edit_finding" | "complete_task" | "add_task" | "remove_task" | "update_task" | "pin_task" | "add_note" | "edit_note" | "remove_note" | "promote_note" | "manage_config";
19
+ type RbacAction = "add_finding" | "remove_finding" | "edit_finding" | "complete_task" | "add_task" | "remove_task" | "update_task" | "pin_task" | "claim_task" | "add_note" | "edit_note" | "remove_note" | "promote_note" | "manage_config";
20
20
  /**
21
21
  * Appended to every ACL-write denial. The natural way to lock yourself out is
22
22
  * to run the very first `phren config access set --admins=someone-else`: that
@@ -145,6 +145,7 @@ const CONTRIBUTOR_ACTIONS = new Set([
145
145
  "remove_task",
146
146
  "update_task",
147
147
  "pin_task",
148
+ "claim_task",
148
149
  "add_note",
149
150
  "edit_note",
150
151
  "remove_note",
@@ -53,6 +53,10 @@ export interface WalkthroughResult {
53
53
  findingSensitivity: "minimal" | "conservative" | "balanced" | "aggressive";
54
54
  githubUsername?: string;
55
55
  githubRepo?: string;
56
+ /** Create the private repo with gh and push, instead of printing the steps. */
57
+ githubCreate?: boolean;
58
+ /** Install Phren Hook and show the pairing QR code once setup finishes. */
59
+ connectPhone?: boolean;
56
60
  cloneUrl?: string;
57
61
  domain: InitProjectDomain;
58
62
  inferredScaffold?: InferredInitScaffold;
@@ -60,6 +64,12 @@ export interface WalkthroughResult {
60
64
  export interface WalkthroughOptions {
61
65
  /** When true, skip the express prompt and use recommended defaults immediately */
62
66
  express?: boolean;
67
+ /** When true, skip the express prompt and ask about every setting */
68
+ advanced?: boolean;
69
+ /** The signed-in GitHub login from gh, for the sync offer; injectable for tests */
70
+ githubLogin?: () => Promise<string | undefined>;
63
71
  }
72
+ /** The login gh is signed in as, or undefined when gh is missing or signed out. */
73
+ export declare function ghLogin(): Promise<string | undefined>;
64
74
  export declare function runWalkthrough(phrenPath: string, options?: WalkthroughOptions): Promise<WalkthroughResult>;
65
75
  export {};
@@ -125,6 +125,16 @@ async function readlineWalkthroughPrompts() {
125
125
  function detectRepoRootForStorage(phrenPath) {
126
126
  return detectProjectDir(process.cwd(), phrenPath);
127
127
  }
128
+ /** The login gh is signed in as, or undefined when gh is missing or signed out. */
129
+ export async function ghLogin() {
130
+ const { execFile } = await import("child_process");
131
+ return new Promise(resolve => {
132
+ execFile("gh", ["api", "user", "--jq", ".login"], { timeout: 8000 }, (error, stdout) => {
133
+ const login = String(stdout ?? "").trim();
134
+ resolve(!error && /^[A-Za-z0-9-]{1,39}$/.test(login) ? login : undefined);
135
+ });
136
+ });
137
+ }
128
138
  // Interactive walkthrough for first-time init
129
139
  export async function runWalkthrough(phrenPath, options) {
130
140
  const prompts = await createWalkthroughPrompts();
@@ -151,7 +161,7 @@ export async function runWalkthrough(phrenPath, options) {
151
161
  log("Every option can be changed later.\n");
152
162
  // Express mode: skip the entire walkthrough with recommended defaults
153
163
  const useExpress = options?.express === true
154
- || (options?.express !== false && await prompts.confirm("Use recommended settings? (global storage, MCP on, hooks on, auto tasks)", true));
164
+ || (options?.express !== false && options?.advanced !== true && await prompts.confirm("Use recommended settings? (global storage, MCP on, hooks on, auto tasks)", true));
155
165
  if (useExpress) {
156
166
  const expressResult = {
157
167
  storageChoice: "global",
@@ -184,6 +194,19 @@ export async function runWalkthrough(phrenPath, options) {
184
194
  "Task mode: auto",
185
195
  "Domain: software",
186
196
  ]);
197
+ // Only a live terminal gets the follow-up offers; --express stays silent.
198
+ if (options?.express !== true) {
199
+ const login = await (options?.githubLogin ?? ghLogin)();
200
+ if (login && await prompts.confirm(`Sync memory to a private GitHub repo (${login}/my-phren)?`, true)) {
201
+ expressResult.githubUsername = login;
202
+ expressResult.githubRepo = "my-phren";
203
+ expressResult.githubCreate = true;
204
+ }
205
+ if (["darwin", "linux"].includes(process.platform)
206
+ && await prompts.confirm("Connect your phone now? (shows a QR code to scan in the Phren app)", false)) {
207
+ expressResult.connectPhone = true;
208
+ }
209
+ }
187
210
  return expressResult;
188
211
  }
189
212
  printSection("Storage Location");
@@ -49,6 +49,8 @@ export interface InitOptions {
49
49
  yes?: boolean;
50
50
  /** Skip walkthrough entirely with recommended defaults (express mode) */
51
51
  express?: boolean;
52
+ /** Ask about every setting instead of offering recommended defaults */
53
+ advanced?: boolean;
52
54
  /**
53
55
  * Allow init to repoint global wiring (~/.local/bin/phren wrapper and
54
56
  * Claude settings.json hooks/mcpServers.phren) at a different phren root
@@ -64,7 +66,10 @@ export interface InitOptions {
64
66
  _walkthroughGithub?: {
65
67
  username?: string;
66
68
  repo: string;
69
+ create?: boolean;
67
70
  };
71
+ /** Set by walkthrough when the user wants the phone connected right away */
72
+ _walkthroughPair?: boolean;
68
73
  /** Set by walkthrough to seed project docs/topics by domain */
69
74
  _walkthroughDomain?: InitProjectDomain;
70
75
  /** Set by walkthrough to seed adaptive project scaffold from current repo content */
package/dist/init/init.js CHANGED
@@ -74,6 +74,35 @@ export function isVersionNewer(current, previous) {
74
74
  return true;
75
75
  return c.pre > p.pre;
76
76
  }
77
+ function hasGitRemote(phrenPath) {
78
+ try {
79
+ return execFileSync("git", ["-C", phrenPath, "remote"], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], env: nonInteractiveGitEnv() }).trim() !== "";
80
+ }
81
+ catch {
82
+ return false;
83
+ }
84
+ }
85
+ /** Commit the new store and publish it as a private repo with gh. Returns whether it is now synced. */
86
+ async function createGithubStore(phrenPath, username, repo) {
87
+ const git = (args) => execFileSync("git", ["-C", phrenPath, ...args], { stdio: ["ignore", "pipe", "pipe"], env: nonInteractiveGitEnv() });
88
+ try {
89
+ git(["add", "-A"]);
90
+ try {
91
+ git(["commit", "-q", "-m", "Initial phren setup"]);
92
+ }
93
+ catch { /* nothing new to commit */ }
94
+ log(`\nCreating private repo ${username}/${repo} and pushing your memory…`);
95
+ execFileSync("gh", ["repo", "create", `${username}/${repo}`, "--private", `--source=${phrenPath}`, "--remote=origin", "--push"], { stdio: ["ignore", "pipe", "pipe"], timeout: 120_000 });
96
+ writeInstallPreferences(phrenPath, { syncIntent: "sync" });
97
+ log(` Synced: https://github.com/${username}/${repo} (private). Hooks pull and push it after each session.`);
98
+ return true;
99
+ }
100
+ catch (err) {
101
+ const stderr = String(err.stderr ?? "").trim().split("\n")[0];
102
+ log(` Couldn't create the GitHub repo${stderr ? `: ${stderr}` : ""}. Your memory is safe locally.`);
103
+ return false;
104
+ }
105
+ }
77
106
  function normalizedBootstrapProjectName(projectPath) {
78
107
  return projectSlugFromPath(projectPath);
79
108
  }
@@ -165,7 +194,7 @@ export async function runInit(opts = {}) {
165
194
  // --express bypasses the TTY check since it skips all interactive prompts
166
195
  const isTTY = process.stdin.isTTY && process.stdout.isTTY;
167
196
  if (!hasExistingInstall && !dryRun && !opts.yes && (isTTY || opts.express)) {
168
- const answers = await runWalkthrough(phrenPath, { express: opts.express });
197
+ const answers = await runWalkthrough(phrenPath, { express: opts.express, advanced: opts.advanced });
169
198
  opts._walkthroughStorageChoice = answers.storageChoice;
170
199
  opts._walkthroughStoragePath = answers.storagePath;
171
200
  opts._walkthroughStorageRepoRoot = answers.storageRepoRoot;
@@ -188,8 +217,9 @@ export async function runInit(opts = {}) {
188
217
  opts._walkthroughCloneUrl = answers.cloneUrl;
189
218
  }
190
219
  if (answers.githubRepo) {
191
- opts._walkthroughGithub = { username: answers.githubUsername, repo: answers.githubRepo };
220
+ opts._walkthroughGithub = { username: answers.githubUsername, repo: answers.githubRepo, create: answers.githubCreate };
192
221
  }
222
+ opts._walkthroughPair = answers.connectPhone;
193
223
  opts._walkthroughDomain = answers.domain;
194
224
  if (answers.inferredScaffold) {
195
225
  opts._walkthroughInferredScaffold = answers.inferredScaffold;
@@ -654,41 +684,33 @@ export async function runInit(opts = {}) {
654
684
  }
655
685
  }
656
686
  log(`\n\x1b[95m◆\x1b[0m phren initialized`);
657
- log(`\nNext steps:`);
658
- let step = 1;
659
- log(` ${step++}. Start a new Claude session in your project directory — phren injects context automatically`);
660
- log(` ${step++}. Run \`phren doctor\` to verify everything is wired correctly`);
661
- log(` ${step++}. Change defaults anytime: \`phren config project-ownership\`, \`phren config workflow\`, \`phren config proactivity.findings\`, \`phren config proactivity.tasks\``);
662
687
  const gh = opts._walkthroughGithub;
663
- if (gh) {
664
- const remote = gh.username
665
- ? `git@github.com:${gh.username}/${gh.repo}.git`
666
- : `git@github.com:YOUR_USERNAME/${gh.repo}.git`;
667
- log(` ${step++}. Push your phren to GitHub (private repo recommended):`);
668
- log(` cd ${phrenPath}`);
669
- log(` git add . && git commit -m "Initial phren setup"`);
670
- if (gh.username) {
671
- log(` gh repo create ${gh.username}/${gh.repo} --private --source=. --push`);
672
- log(` # or manually: git remote add origin ${remote} && git push -u origin main`);
688
+ let synced = hasGitRemote(phrenPath);
689
+ if (!synced && gh?.create && gh.username)
690
+ synced = await createGithubStore(phrenPath, gh.username, gh.repo);
691
+ let paired = false;
692
+ if (opts._walkthroughPair) {
693
+ const { enableHookForPhone } = await import("../modules/config.js");
694
+ const { runPair } = await import("../bridge/pair.js");
695
+ enableHookForPhone(phrenPath);
696
+ try {
697
+ paired = await runPair([], VERSION) === 0;
673
698
  }
674
- else {
675
- log(` git remote add origin ${remote}`);
676
- log(` git push -u origin main`);
699
+ catch (err) {
700
+ log(` Phone pairing didn't finish: ${errorMessage(err)}`);
677
701
  }
678
702
  }
679
- else {
680
- log(` ${step++}. Push to GitHub for cross-machine sync (private repo recommended):`);
681
- log(` cd ${phrenPath}`);
682
- log(` git add . && git commit -m "Initial phren setup"`);
683
- log(` git remote add origin git@github.com:YOUR_USERNAME/my-phren.git`);
684
- log(` git push -u origin main`);
703
+ log(`\nNext:`);
704
+ let step = 1;
705
+ log(` ${step++}. Start a new agent session (Claude, Codex, Copilot…) in a project. Phren loads its memory automatically.`);
706
+ if (!paired)
707
+ log(` ${step++}. Connect your phone any time: phren pair`);
708
+ if (!synced) {
709
+ const repo = gh ? `${gh.username ? `${gh.username}/` : ""}${gh.repo}` : "my-phren";
710
+ log(` ${step++}. Sync across computers: cd ${phrenPath} && gh repo create ${repo} --private --source=. --push`);
685
711
  }
686
- log(` ${step++}. Add more projects: cd ~/your-project && phren add`);
687
- if (!mcpEnabled) {
712
+ if (!mcpEnabled)
688
713
  log(` ${step++}. Turn MCP on: phren mcp-mode on`);
689
- }
690
- log(` ${step++}. After your first week, run phren-discover to surface gaps in your project knowledge`);
691
- log(` ${step++}. After working across projects, run phren-consolidate to find cross-project patterns`);
692
- log(`\n Read ${phrenPath}/README.md for a guided tour of each file.`);
714
+ log(` Settings: phren config · Health check: phren doctor`);
693
715
  log(``);
694
716
  }
@@ -934,6 +934,16 @@ export async function runDoctor(phrenPath, fix = false, checkData = false, confi
934
934
  catch (err) {
935
935
  debugLog(`doctor: context-imports scan failed: ${errorMessage(err)}`);
936
936
  }
937
+ // Spoken replies are optional, so only a stored key other users can read,
938
+ // or a broken file, fails the check. The key itself is never shown.
939
+ try {
940
+ const { speechKeyStatus } = await import("../bridge/speech-key.js");
941
+ const speech = await speechKeyStatus();
942
+ checks.push({ name: "speech-key", ok: !speech.problem, detail: `${speech.configured ? "configured" : "not configured"}: ${speech.detail}` });
943
+ }
944
+ catch (err) {
945
+ debugLog(`doctor: speech-key check failed: ${errorMessage(err)}`);
946
+ }
937
947
  const ok = checks.every((c) => c.ok);
938
948
  return { ok, machine, profile: profile || undefined, checks };
939
949
  }
@@ -62,9 +62,10 @@ const COMPOSITES = {
62
62
  },
63
63
  manage_task: {
64
64
  title: "◆ phren · manage task",
65
- summary: "Change an existing task: complete, update, remove, pin, or tidy the done list. Pass `action` plus that action's own parameters.",
65
+ summary: "Change an existing task: complete, update, remove, pin, claim for this computer, or tidy the done list. Pass `action` plus that action's own parameters.",
66
66
  actions: {
67
67
  complete: "complete_task",
68
+ claim: "claim_task",
68
69
  update: "update_task",
69
70
  remove: "remove_task",
70
71
  pin: "pin_task",
@@ -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"],
@@ -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>;