@phren/cli 0.3.1 → 0.3.2

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.
@@ -195,6 +195,11 @@ export declare class AgentHooks {
195
195
  * phone with its own keys: let the callback fall back to the terminal at
196
196
  * once instead of leaving the card up until the 55-second timer. */
197
197
  releaseChoice(target: Target): void;
198
+ /** The phone's Esc or Cancel on a question the Hook holds. A held
199
+ * AskUserQuestion has no terminal choice, so `releaseChoice` never lets it
200
+ * go and the terminal stays frozen until the hold timer; decline it now so
201
+ * Claude moves on. True when a held question was cancelled. */
202
+ cancelHeldQuestion(target: Target): boolean;
198
203
  answerPush(binding: string, decision: unknown): Promise<void>;
199
204
  /** Where a pushed ask lives, without answering it: the phone opens that
200
205
  * session's details when the notification itself is tapped. */
@@ -809,6 +809,25 @@ export class AgentHooks {
809
809
  entry.response.end("{}");
810
810
  }
811
811
  }
812
+ /** The phone's Esc or Cancel on a question the Hook holds. A held
813
+ * AskUserQuestion has no terminal choice, so `releaseChoice` never lets it
814
+ * go and the terminal stays frozen until the hold timer; decline it now so
815
+ * Claude moves on. True when a held question was cancelled. */
816
+ cancelHeldQuestion(target) {
817
+ let cancelled = false;
818
+ for (const [id, entry] of this.pending) {
819
+ if (entry.tool !== "AskUserQuestion" || JSON.stringify(entry.target) !== JSON.stringify(target))
820
+ continue;
821
+ this.pending.delete(id);
822
+ this.dropPushBindings(id);
823
+ clearTimeout(entry.timer);
824
+ if (!entry.response.destroyed)
825
+ entry.response.end(JSON.stringify({ hookSpecificOutput: { hookEventName: "PermissionRequest",
826
+ decision: { behavior: "deny", message: "The user cancelled this question in Phren without answering." } } }));
827
+ cancelled = true;
828
+ }
829
+ return cancelled;
830
+ }
812
831
  async answerPush(binding, decision) {
813
832
  if (!["approve", "deny"].includes(String(decision)))
814
833
  throw new BridgeError(400, "The approval answer is not valid.");
@@ -1,7 +1,8 @@
1
1
  import { type Json } from "./protocol.js";
2
2
  export declare function runBridge(args: string[], version: string): Promise<number>;
3
- /** Doctor's push check, from the running Hook's own capability: only a Hook
4
- * that loaded apns.json and its key offers `approvalPush`. */
3
+ /** Doctor's push check, from the running Hook's own capability: a Hook that
4
+ * loaded apns.json and its key, or one whose phones registered through the
5
+ * push relay, offers `approvalPush`. */
5
6
  export declare function approvalPushCheck(helper: Json): {
6
7
  configured: boolean;
7
8
  warning?: string;
@@ -131,10 +131,12 @@ export async function runBridge(args, version) {
131
131
  }
132
132
  return 0;
133
133
  }
134
- /** Doctor's push check, from the running Hook's own capability: only a Hook
135
- * that loaded apns.json and its key offers `approvalPush`. */
134
+ /** Doctor's push check, from the running Hook's own capability: a Hook that
135
+ * loaded apns.json and its key, or one whose phones registered through the
136
+ * push relay, offers `approvalPush`. */
136
137
  export function approvalPushCheck(helper) {
137
- const configured = object(helper.capabilities).approvalPush === "direct-apns";
138
+ const capability = object(helper.capabilities).approvalPush;
139
+ const configured = capability === "direct-apns" || capability === "relay";
138
140
  return configured ? { configured } : { configured, warning: apnsSetupSteps() };
139
141
  }
140
142
  const SPEECH_KEY_USAGE = "Usage: phren bridge speech-key set (paste the key when asked, or pipe it on stdin)";
@@ -1,8 +1,23 @@
1
1
  import { z } from "zod";
2
+ /** A phone registered through the phren push relay: the relay knows where to
3
+ * deliver, and `key` (32 bytes, base64url) encrypts what the notification says
4
+ * so only the phone reads it. The phone made the key and sent it over SSH. */
5
+ declare const relaySchema: z.ZodObject<{
6
+ url: z.ZodString;
7
+ relayId: z.ZodString;
8
+ secret: z.ZodString;
9
+ key: z.ZodString;
10
+ }, z.core.$strip>;
2
11
  declare const deviceSchema: z.ZodObject<{
3
12
  deviceID: z.ZodString;
4
13
  hostID: z.ZodString;
5
- token: z.ZodString;
14
+ token: z.ZodOptional<z.ZodString>;
15
+ relay: z.ZodOptional<z.ZodObject<{
16
+ url: z.ZodString;
17
+ relayId: z.ZodString;
18
+ secret: z.ZodString;
19
+ key: z.ZodString;
20
+ }, z.core.$strip>>;
6
21
  environment: z.ZodEnum<{
7
22
  development: "development";
8
23
  production: "production";
@@ -54,11 +69,29 @@ export declare function fanoutBlockedPushPayload(value: FanoutBlockedPush): Reco
54
69
  export declare function schedulePushPayload(value: SchedulePush): Record<string, unknown>;
55
70
  /** What `phren bridge doctor` prints when the Hook has no APNs sender. */
56
71
  export declare function apnsSetupSteps(configFile?: string): string;
57
- /** The capability a phone reads: only a Hook with a loaded APNs sender offers push. */
72
+ /** The capability a phone reads: a Hook with its own APNs key sends direct;
73
+ * one whose phones registered through the relay sends through it. */
58
74
  export declare function approvalPushCapability(status: {
59
75
  configured: boolean;
60
- }): "direct-apns" | undefined;
76
+ direct?: boolean;
77
+ }): "direct-apns" | "relay" | undefined;
61
78
  export declare function upsertPushDevice(devices: PushDevice[], value: unknown): PushDevice[];
79
+ /** The relay refuses ciphertext longer than this (it keeps the APNs payload under 4 KB). */
80
+ export declare const RELAY_MAX_CIPHERTEXT = 2800;
81
+ /** What the phone's notification extension shows, encrypted with the phone's
82
+ * key: ChaCha20-Poly1305, base64url of nonce (12) + ciphertext + tag (16), the
83
+ * layout CryptoKit's `ChaChaPoly.SealedBox(combined:)` reads. A long body is
84
+ * shortened until it fits the relay's limit. */
85
+ export declare function relayCiphertext(key: string, payload: Record<string, unknown>, nonce?: NonSharedBuffer): string;
86
+ /** Signs a relay send: base64url HMAC-SHA256 of `${timestamp}.${body}` under the phone's send secret. */
87
+ export declare function relaySignature(secret: string, timestamp: string, body: string): string;
88
+ type RelayRegistration = z.infer<typeof relaySchema>;
89
+ /** "gone" means the relay (Apple) no longer knows the phone: stop sending until it registers again. */
90
+ export type RelayResult = "sent" | "failed" | "gone";
91
+ export declare function sendThroughRelay(relay: RelayRegistration, payload: Record<string, unknown>, headers: {
92
+ expiration: string;
93
+ collapseId: string;
94
+ }, fetcher?: typeof fetch, now?: () => number): Promise<RelayResult>;
62
95
  /** Direct Hook -> APNs delivery. Apple receives only a short-lived opaque
63
96
  * binding; conversation identity, action id, command and SSH key stay local. */
64
97
  export declare class ApprovalPushService {
@@ -66,13 +99,19 @@ export declare class ApprovalPushService {
66
99
  private sender?;
67
100
  private readonly devicesFile;
68
101
  start(): Promise<void>;
102
+ /** Phones this Hook can reach: through the relay, or direct with its own key. */
103
+ private get reachable();
69
104
  get available(): boolean;
70
105
  get status(): {
71
106
  supported: boolean;
72
107
  configured: boolean;
108
+ direct: boolean;
73
109
  devices: number;
110
+ relay: number;
74
111
  };
75
112
  register(value: unknown): Promise<void>;
113
+ /** One phone: the relay when it registered through one, otherwise direct. */
114
+ private send;
76
115
  notify(value: ApprovalPush): Promise<boolean>;
77
116
  /** A headless worker whose permission the plugin refused. Approval-registered
78
117
  * phones already accept agent alerts; the payload carries the reason so the
@@ -1,16 +1,27 @@
1
- import { createPrivateKey, sign } from "node:crypto";
1
+ import { createCipheriv, createHmac, createPrivateKey, randomBytes, sign } from "node:crypto";
2
2
  import { readFile, stat } from "node:fs/promises";
3
3
  import { connect } from "node:http2";
4
4
  import path from "node:path";
5
5
  import { z } from "zod";
6
6
  import { atomic, bridgeRoot } from "./protocol.js";
7
+ /** A phone registered through the phren push relay: the relay knows where to
8
+ * deliver, and `key` (32 bytes, base64url) encrypts what the notification says
9
+ * so only the phone reads it. The phone made the key and sent it over SSH. */
10
+ const relaySchema = z.object({
11
+ url: z.string().url().refine(value => /^https:\/\//.test(value) || /^http:\/\/(127\.0\.0\.1|localhost)(:\d+)?\//.test(`${value}/`), "The relay must use https."),
12
+ relayId: z.string().regex(/^[A-Za-z0-9_-]{40,400}$/),
13
+ secret: z.string().regex(/^[A-Za-z0-9_-]{20,100}$/),
14
+ key: z.string().regex(/^[A-Za-z0-9_-]{43}$/),
15
+ });
7
16
  const deviceSchema = z.object({
8
17
  deviceID: z.string().uuid(),
9
18
  hostID: z.string().uuid(),
10
- token: z.string().regex(/^[0-9a-f]{64}$/),
19
+ /** The APNs token, for a Hook with its own key (apns.json). */
20
+ token: z.string().regex(/^[0-9a-f]{64}$/).optional(),
21
+ relay: relaySchema.optional(),
11
22
  environment: z.enum(["development", "production"]),
12
23
  kinds: z.array(z.enum(["approval", "scheduleStarted", "scheduleFinished", "scheduleFailed", "scheduleBlocked"])).max(5).default(["approval"]),
13
- });
24
+ }).refine(device => device.token !== undefined || device.relay !== undefined, "A phone needs an APNs token or a relay registration.");
14
25
  const configSchema = z.object({
15
26
  keyId: z.string().regex(/^[A-Z0-9]{10}$/),
16
27
  teamId: z.string().regex(/^[A-Z0-9]{10}$/),
@@ -83,15 +94,59 @@ export function apnsSetupSteps(configFile = process.env.PHREN_APNS_CONFIG || pat
83
94
  "4. Restart the Hook (phren bridge install), then run phren bridge doctor again.",
84
95
  ].join("\n");
85
96
  }
86
- /** The capability a phone reads: only a Hook with a loaded APNs sender offers push. */
97
+ /** The capability a phone reads: a Hook with its own APNs key sends direct;
98
+ * one whose phones registered through the relay sends through it. */
87
99
  export function approvalPushCapability(status) {
88
- return status.configured ? "direct-apns" : undefined;
100
+ if (!status.configured)
101
+ return undefined;
102
+ return status.direct === false ? "relay" : "direct-apns";
89
103
  }
90
104
  export function upsertPushDevice(devices, value) {
91
105
  const device = deviceSchema.parse(value);
92
106
  return [...devices.filter(item => item.deviceID !== device.deviceID), device].slice(-16);
93
107
  }
94
108
  const base64url = (value) => Buffer.from(value).toString("base64url");
109
+ /** The relay refuses ciphertext longer than this (it keeps the APNs payload under 4 KB). */
110
+ export const RELAY_MAX_CIPHERTEXT = 2_800;
111
+ /** What the phone's notification extension shows, encrypted with the phone's
112
+ * key: ChaCha20-Poly1305, base64url of nonce (12) + ciphertext + tag (16), the
113
+ * layout CryptoKit's `ChaChaPoly.SealedBox(combined:)` reads. A long body is
114
+ * shortened until it fits the relay's limit. */
115
+ export function relayCiphertext(key, payload, nonce = randomBytes(12)) {
116
+ const aps = (payload.aps ?? {});
117
+ let body = aps.alert?.body ?? "";
118
+ for (;;) {
119
+ const content = JSON.stringify({ t: aps.alert?.title ?? "phren", b: body, ...(aps.category ? { c: aps.category } : {}),
120
+ ...(aps["interruption-level"] ? { i: aps["interruption-level"] } : {}), ...(payload.phren ? { p: payload.phren } : {}) });
121
+ const cipher = createCipheriv("chacha20-poly1305", Buffer.from(key, "base64url"), nonce, { authTagLength: 16 });
122
+ const sealed = Buffer.concat([nonce, cipher.update(content, "utf8"), cipher.final(), cipher.getAuthTag()]).toString("base64url");
123
+ if (sealed.length <= RELAY_MAX_CIPHERTEXT || !body)
124
+ return sealed;
125
+ body = body.length > 40 ? `${body.slice(0, Math.floor(body.length * 0.8))}…` : "";
126
+ }
127
+ }
128
+ /** Signs a relay send: base64url HMAC-SHA256 of `${timestamp}.${body}` under the phone's send secret. */
129
+ export function relaySignature(secret, timestamp, body) {
130
+ return createHmac("sha256", secret).update(`${timestamp}.${body}`).digest("base64url");
131
+ }
132
+ export async function sendThroughRelay(relay, payload, headers, fetcher = fetch, now = Date.now) {
133
+ const aps = (payload.aps ?? {});
134
+ const body = JSON.stringify({ kind: "alert", ciphertext: relayCiphertext(relay.key, payload),
135
+ collapseId: headers.collapseId.slice(0, 64), expiration: Number(headers.expiration) || 0,
136
+ ...(aps.category ? { category: aps.category } : {}) });
137
+ const timestamp = String(Math.floor(now() / 1000));
138
+ try {
139
+ const response = await fetcher(`${relay.url.replace(/\/+$/, "")}/v1/send`, {
140
+ method: "POST", body, signal: AbortSignal.timeout(10_000),
141
+ headers: { "content-type": "application/json", "x-phren-relay": relay.relayId, "x-phren-timestamp": timestamp,
142
+ "x-phren-signature": relaySignature(relay.secret, timestamp, body) },
143
+ });
144
+ return response.status === 410 ? "gone" : response.ok ? "sent" : "failed";
145
+ }
146
+ catch {
147
+ return "failed";
148
+ }
149
+ }
95
150
  class APNsSender {
96
151
  config;
97
152
  key;
@@ -149,19 +204,35 @@ export class ApprovalPushService {
149
204
  if (key)
150
205
  this.sender = new APNsSender(config, key);
151
206
  }
152
- get available() { return this.sender !== undefined && this.devices.length > 0; }
153
- get status() { return { supported: true, configured: this.sender !== undefined, devices: this.devices.length }; }
207
+ /** Phones this Hook can reach: through the relay, or direct with its own key. */
208
+ get reachable() { return this.devices.filter(device => device.relay || (this.sender && device.token)); }
209
+ get available() { return this.reachable.length > 0; }
210
+ get status() {
211
+ const relay = this.devices.filter(device => device.relay).length;
212
+ return { supported: true, configured: this.sender !== undefined || relay > 0, direct: this.sender !== undefined,
213
+ devices: this.devices.length, relay };
214
+ }
154
215
  async register(value) {
155
216
  this.devices = upsertPushDevice(this.devices, value);
156
217
  await atomic(this.devicesFile, JSON.stringify(this.devices));
157
218
  }
219
+ /** One phone: the relay when it registered through one, otherwise direct. */
220
+ async send(device, payload, headers) {
221
+ if (device.relay) {
222
+ const result = await sendThroughRelay(device.relay, payload, headers);
223
+ if (result === "gone") {
224
+ this.devices = this.devices.filter(item => item.deviceID !== device.deviceID);
225
+ await atomic(this.devicesFile, JSON.stringify(this.devices)).catch(() => { });
226
+ }
227
+ return result === "sent";
228
+ }
229
+ return this.sender && device.token ? this.sender.send(device, payload, headers) : false;
230
+ }
158
231
  async notify(value) {
159
- if (!this.sender || !this.devices.length)
160
- return false;
161
- const devices = this.devices.filter(device => device.kinds.includes("approval"));
232
+ const devices = this.reachable.filter(device => device.kinds.includes("approval"));
162
233
  if (!devices.length)
163
234
  return false;
164
- return (await Promise.all(devices.map(device => this.sender.send(device, approvalPushPayload(value, device.hostID), {
235
+ return (await Promise.all(devices.map(device => this.send(device, approvalPushPayload(value, device.hostID), {
165
236
  expiration: String(Math.floor(Date.parse(value.expiresAt) / 1000)), collapseId: value.binding,
166
237
  })))).some(Boolean);
167
238
  }
@@ -169,25 +240,24 @@ export class ApprovalPushService {
169
240
  * phones already accept agent alerts; the payload carries the reason so the
170
241
  * notification is actionable on its own. */
171
242
  async notifyFanoutBlocked(value) {
172
- if (!this.sender || !this.devices.length)
173
- return false;
174
- const devices = this.devices.filter(device => device.kinds.includes("approval"));
243
+ const devices = this.reachable.filter(device => device.kinds.includes("approval"));
175
244
  if (!devices.length)
176
245
  return false;
177
- return (await Promise.all(devices.map(device => this.sender.send(device, fanoutBlockedPushPayload(value), {
246
+ return (await Promise.all(devices.map(device => this.send(device, fanoutBlockedPushPayload(value), {
178
247
  expiration: "0", collapseId: `fanout-${value.job}`,
179
248
  })))).some(Boolean);
180
249
  }
181
250
  async notifySchedule(value) {
182
- if (!this.sender)
183
- return { notified: false, reason: "no push config" };
184
- let devices = this.devices.filter(device => device.kinds.includes(value.kind));
251
+ const reachable = this.reachable;
252
+ if (!reachable.length)
253
+ return { notified: false, reason: this.sender || this.devices.length ? "no registered devices" : "no push config" };
254
+ let devices = reachable.filter(device => device.kinds.includes(value.kind));
185
255
  if (!devices.length && value.kind === "scheduleBlocked")
186
- devices = this.devices.filter(device => device.kinds.includes("scheduleFailed"));
256
+ devices = reachable.filter(device => device.kinds.includes("scheduleFailed"));
187
257
  if (!devices.length)
188
258
  return { notified: false, reason: "no registered devices" };
189
259
  try {
190
- const notified = (await Promise.all(devices.map(device => this.sender.send(device, schedulePushPayload(value), {
260
+ const notified = (await Promise.all(devices.map(device => this.send(device, schedulePushPayload(value), {
191
261
  expiration: "0", collapseId: scheduleCollapseId(value.kind, value.runId),
192
262
  })))).some(Boolean);
193
263
  return notified ? { notified: true } : { notified: false, reason: "push delivery failed" };
@@ -364,15 +364,21 @@ export async function paneRoute(ctx, url, data, response) {
364
364
  // not hold) is being answered even when Herdr reads the pane as
365
365
  // working or idle; Herdr's status lags the agent's own dialog.
366
366
  const holding = menu || !!agentHooks.terminalPrompt(target);
367
+ // Esc on a question the Hook still holds declines it at once, whatever
368
+ // Herdr reads the pane as: an esc typed into the held pane does nothing.
369
+ const cancelled = keys.every(key => key === "Escape") && agentHooks.cancelHeldQuestion(target);
367
370
  // Escape interrupts a working agent. Everything else answers a
368
371
  // prompt the agent is holding: a menu, a y/n, a trust question.
369
- if (!holding && (keys.every(key => key === "Escape") ? !["working", "blocked", "waiting", "unknown"].includes(status)
372
+ if (!cancelled && !holding && (keys.every(key => key === "Escape") ? !["working", "blocked", "waiting", "unknown"].includes(status)
370
373
  : !["blocked", "waiting", "unknown"].includes(status)))
371
374
  throw new BridgeError(409, keys.every(key => key === "Escape") ? "This agent is no longer working." : "This agent is not waiting for an answer.");
372
- // An older phone answers a released AskUserQuestion one question at
373
- // a time with its digits; the Hook walks that question in the pane
374
- // and submits the set after the last.
375
- if (await agentHooks.answerReleasedQuestion(target, keys)) {
375
+ if (cancelled) {
376
+ result = { ok: true };
377
+ // An older phone answers a released AskUserQuestion one question at
378
+ // a time with its digits; the Hook walks that question in the pane
379
+ // and submits the set after the last.
380
+ }
381
+ else if (await agentHooks.answerReleasedQuestion(target, keys)) {
376
382
  result = { ok: true };
377
383
  }
378
384
  else {
@@ -24,6 +24,12 @@ export interface SpeechOptions {
24
24
  /** A fixed message per ElevenLabs failure: its own response text is never
25
25
  * passed on. */
26
26
  export declare function speechError(upstream: Response): Promise<BridgeError>;
27
+ /** A reply as it should sound: markdown the agent wrote for the chat bubble
28
+ * (emphasis, headings, bullets, links, inline code, tables) is read aloud
29
+ * literally by ElevenLabs, so it is reduced to its words. A code block is
30
+ * skipped, a link keeps its text and a bare URL becomes "a link". Empty when
31
+ * nothing speakable is left. */
32
+ export declare function speakableText(text: string): string;
27
33
  /** Starts ElevenLabs' streaming synthesis and returns its audio body. */
28
34
  export declare function synthesizeSpeech(text: string, signal: AbortSignal, options?: SpeechOptions): Promise<ReadableStream<Uint8Array>>;
29
35
  /** POST /v1/speech: writes the audio to the phone as ElevenLabs produces it.
@@ -36,6 +36,37 @@ export async function speechError(upstream) {
36
36
  default: return new BridgeError(502, `ElevenLabs failed (HTTP ${upstream.status}).`, { code: "speech-failed" });
37
37
  }
38
38
  }
39
+ /** A reply as it should sound: markdown the agent wrote for the chat bubble
40
+ * (emphasis, headings, bullets, links, inline code, tables) is read aloud
41
+ * literally by ElevenLabs, so it is reduced to its words. A code block is
42
+ * skipped, a link keeps its text and a bare URL becomes "a link". Empty when
43
+ * nothing speakable is left. */
44
+ export function speakableText(text) {
45
+ return text
46
+ .replace(/```[\s\S]*?(?:```|$)/g, " ")
47
+ .replace(/!\[([^\]]*)\]\([^)]*\)/g, "$1")
48
+ .replace(/\[([^\]]+)\]\([^)]*\)/g, "$1")
49
+ .replace(/https?:\/\/\S+/g, "a link")
50
+ .replace(/`([^`]*)`/g, "$1")
51
+ .split(/\r?\n/)
52
+ .map(line => {
53
+ // A heading, bullet or table row ends where its line does; a
54
+ // paragraph's soft-wrapped lines run on.
55
+ const block = /^\s{0,3}(?:#{1,6}\s|[-*+]\s|\d+[.)]\s|\|)/.test(line);
56
+ const words = line
57
+ .replace(/^\s*\|?[\s:|-]*-[\s:|-]*\|?\s*$/, "")
58
+ .replace(/^\s{0,3}(?:#{1,6}\s+|>\s?|[-*+]\s+(?:\[[ xX]\]\s+)?)/, "")
59
+ .replace(/\s*\|\s*/g, (bar, offset, whole) => offset === 0 || offset + bar.length === whole.length ? "" : ", ")
60
+ .replace(/(\*\*|__|~~)(.+?)\1/g, "$2")
61
+ .replace(/(^|[^\w*])[*_](\S(?:.*?\S)?)[*_](?![\w*])/g, "$1$2")
62
+ .trim();
63
+ return block && words && !/[.!?:;,]$/.test(words) ? `${words}.` : words;
64
+ })
65
+ .filter(Boolean)
66
+ .join(" ")
67
+ .replace(/\s+/g, " ")
68
+ .trim();
69
+ }
39
70
  /** Starts ElevenLabs' streaming synthesis and returns its audio body. */
40
71
  export async function synthesizeSpeech(text, signal, options = {}) {
41
72
  const key = await (options.key ?? readSpeechKey)();
@@ -63,7 +94,9 @@ export async function synthesizeSpeech(text, signal, options = {}) {
63
94
  * failure mid-stream cuts the response off, which the phone treats as an
64
95
  * error. The phone hanging up cancels the ElevenLabs request. */
65
96
  export async function streamSpeech(data, response, options = {}) {
66
- const { text } = speechRequest.parse(data);
97
+ const text = speakableText(speechRequest.parse(data).text);
98
+ if (!text)
99
+ throw new BridgeError(400, "There is nothing to say in this reply.", { code: "speech-invalid" });
67
100
  const abort = new AbortController();
68
101
  response.once("close", () => { if (!response.writableEnded)
69
102
  abort.abort(); });
@@ -28275,7 +28275,7 @@ var init_package_metadata = __esm({
28275
28275
  __dirname = path24.dirname(fileURLToPath2(import.meta.url));
28276
28276
  ROOT = path24.join(__dirname, "..");
28277
28277
  PACKAGE_JSON_PATH = path24.join(ROOT, "package.json");
28278
- BUNDLED_VERSION = true ? "0.3.1" : "0.0.0";
28278
+ BUNDLED_VERSION = true ? "0.3.2" : "0.0.0";
28279
28279
  PACKAGE_JSON = readPackageJson();
28280
28280
  PACKAGE_NAME = PACKAGE_JSON.name || "phren";
28281
28281
  VERSION = PACKAGE_JSON.version || BUNDLED_VERSION;
@@ -30522,7 +30522,7 @@ var require_websocket = __commonJS({
30522
30522
  var http = __require("http");
30523
30523
  var net = __require("net");
30524
30524
  var tls = __require("tls");
30525
- var { randomBytes: randomBytes4, createHash: createHash19 } = __require("crypto");
30525
+ var { randomBytes: randomBytes5, createHash: createHash19 } = __require("crypto");
30526
30526
  var { Duplex: Duplex2, Readable } = __require("stream");
30527
30527
  var { URL: URL2 } = __require("url");
30528
30528
  var PerMessageDeflate2 = require_permessage_deflate();
@@ -31060,7 +31060,7 @@ var require_websocket = __commonJS({
31060
31060
  }
31061
31061
  }
31062
31062
  const defaultPort = isSecure ? 443 : 80;
31063
- const key = randomBytes4(16).toString("base64");
31063
+ const key = randomBytes5(16).toString("base64");
31064
31064
  const request6 = isSecure ? https.request : http.request;
31065
31065
  const protocolSet = /* @__PURE__ */ new Set();
31066
31066
  let perMessageDeflate;
@@ -34506,17 +34506,28 @@ async function removeGrant(input2, root = bridgeRoot()) {
34506
34506
  // src/bridge/push.ts
34507
34507
  init_zod();
34508
34508
  init_protocol();
34509
- import { createPrivateKey, sign } from "node:crypto";
34509
+ import { createCipheriv, createHmac as createHmac2, createPrivateKey, randomBytes as randomBytes3, sign } from "node:crypto";
34510
34510
  import { readFile as readFile12, stat as stat9 } from "node:fs/promises";
34511
34511
  import { connect as connect2 } from "node:http2";
34512
34512
  import path34 from "node:path";
34513
+ var relaySchema = external_exports.object({
34514
+ url: external_exports.string().url().refine(
34515
+ (value2) => /^https:\/\//.test(value2) || /^http:\/\/(127\.0\.0\.1|localhost)(:\d+)?\//.test(`${value2}/`),
34516
+ "The relay must use https."
34517
+ ),
34518
+ relayId: external_exports.string().regex(/^[A-Za-z0-9_-]{40,400}$/),
34519
+ secret: external_exports.string().regex(/^[A-Za-z0-9_-]{20,100}$/),
34520
+ key: external_exports.string().regex(/^[A-Za-z0-9_-]{43}$/)
34521
+ });
34513
34522
  var deviceSchema = external_exports.object({
34514
34523
  deviceID: external_exports.string().uuid(),
34515
34524
  hostID: external_exports.string().uuid(),
34516
- token: external_exports.string().regex(/^[0-9a-f]{64}$/),
34525
+ /** The APNs token, for a Hook with its own key (apns.json). */
34526
+ token: external_exports.string().regex(/^[0-9a-f]{64}$/).optional(),
34527
+ relay: relaySchema.optional(),
34517
34528
  environment: external_exports.enum(["development", "production"]),
34518
34529
  kinds: external_exports.array(external_exports.enum(["approval", "scheduleStarted", "scheduleFinished", "scheduleFailed", "scheduleBlocked"])).max(5).default(["approval"])
34519
- });
34530
+ }).refine((device) => device.token !== void 0 || device.relay !== void 0, "A phone needs an APNs token or a relay registration.");
34520
34531
  var configSchema2 = external_exports.object({
34521
34532
  keyId: external_exports.string().regex(/^[A-Z0-9]{10}$/),
34522
34533
  teamId: external_exports.string().regex(/^[A-Z0-9]{10}$/),
@@ -34596,13 +34607,62 @@ function apnsSetupSteps(configFile = process.env.PHREN_APNS_CONFIG || path34.joi
34596
34607
  ].join("\n");
34597
34608
  }
34598
34609
  function approvalPushCapability(status) {
34599
- return status.configured ? "direct-apns" : void 0;
34610
+ if (!status.configured) return void 0;
34611
+ return status.direct === false ? "relay" : "direct-apns";
34600
34612
  }
34601
34613
  function upsertPushDevice(devices, value2) {
34602
34614
  const device = deviceSchema.parse(value2);
34603
34615
  return [...devices.filter((item) => item.deviceID !== device.deviceID), device].slice(-16);
34604
34616
  }
34605
34617
  var base64url3 = (value2) => Buffer.from(value2).toString("base64url");
34618
+ var RELAY_MAX_CIPHERTEXT = 2800;
34619
+ function relayCiphertext(key, payload, nonce = randomBytes3(12)) {
34620
+ const aps = payload.aps ?? {};
34621
+ let body2 = aps.alert?.body ?? "";
34622
+ for (; ; ) {
34623
+ const content = JSON.stringify({
34624
+ t: aps.alert?.title ?? "phren",
34625
+ b: body2,
34626
+ ...aps.category ? { c: aps.category } : {},
34627
+ ...aps["interruption-level"] ? { i: aps["interruption-level"] } : {},
34628
+ ...payload.phren ? { p: payload.phren } : {}
34629
+ });
34630
+ const cipher = createCipheriv("chacha20-poly1305", Buffer.from(key, "base64url"), nonce, { authTagLength: 16 });
34631
+ const sealed = Buffer.concat([nonce, cipher.update(content, "utf8"), cipher.final(), cipher.getAuthTag()]).toString("base64url");
34632
+ if (sealed.length <= RELAY_MAX_CIPHERTEXT || !body2) return sealed;
34633
+ body2 = body2.length > 40 ? `${body2.slice(0, Math.floor(body2.length * 0.8))}\u2026` : "";
34634
+ }
34635
+ }
34636
+ function relaySignature(secret, timestamp4, body2) {
34637
+ return createHmac2("sha256", secret).update(`${timestamp4}.${body2}`).digest("base64url");
34638
+ }
34639
+ async function sendThroughRelay(relay2, payload, headers, fetcher = fetch, now = Date.now) {
34640
+ const aps = payload.aps ?? {};
34641
+ const body2 = JSON.stringify({
34642
+ kind: "alert",
34643
+ ciphertext: relayCiphertext(relay2.key, payload),
34644
+ collapseId: headers.collapseId.slice(0, 64),
34645
+ expiration: Number(headers.expiration) || 0,
34646
+ ...aps.category ? { category: aps.category } : {}
34647
+ });
34648
+ const timestamp4 = String(Math.floor(now() / 1e3));
34649
+ try {
34650
+ const response = await fetcher(`${relay2.url.replace(/\/+$/, "")}/v1/send`, {
34651
+ method: "POST",
34652
+ body: body2,
34653
+ signal: AbortSignal.timeout(1e4),
34654
+ headers: {
34655
+ "content-type": "application/json",
34656
+ "x-phren-relay": relay2.relayId,
34657
+ "x-phren-timestamp": timestamp4,
34658
+ "x-phren-signature": relaySignature(relay2.secret, timestamp4, body2)
34659
+ }
34660
+ });
34661
+ return response.status === 410 ? "gone" : response.ok ? "sent" : "failed";
34662
+ } catch {
34663
+ return "failed";
34664
+ }
34665
+ }
34606
34666
  var APNsSender = class {
34607
34667
  constructor(config3, key, now = Date.now) {
34608
34668
  this.config = config3;
@@ -34669,21 +34729,44 @@ var ApprovalPushService = class {
34669
34729
  const key = await secureFile(keyPath);
34670
34730
  if (key) this.sender = new APNsSender(config3, key);
34671
34731
  }
34732
+ /** Phones this Hook can reach: through the relay, or direct with its own key. */
34733
+ get reachable() {
34734
+ return this.devices.filter((device) => device.relay || this.sender && device.token);
34735
+ }
34672
34736
  get available() {
34673
- return this.sender !== void 0 && this.devices.length > 0;
34737
+ return this.reachable.length > 0;
34674
34738
  }
34675
34739
  get status() {
34676
- return { supported: true, configured: this.sender !== void 0, devices: this.devices.length };
34740
+ const relay2 = this.devices.filter((device) => device.relay).length;
34741
+ return {
34742
+ supported: true,
34743
+ configured: this.sender !== void 0 || relay2 > 0,
34744
+ direct: this.sender !== void 0,
34745
+ devices: this.devices.length,
34746
+ relay: relay2
34747
+ };
34677
34748
  }
34678
34749
  async register(value2) {
34679
34750
  this.devices = upsertPushDevice(this.devices, value2);
34680
34751
  await atomic(this.devicesFile, JSON.stringify(this.devices));
34681
34752
  }
34753
+ /** One phone: the relay when it registered through one, otherwise direct. */
34754
+ async send(device, payload, headers) {
34755
+ if (device.relay) {
34756
+ const result = await sendThroughRelay(device.relay, payload, headers);
34757
+ if (result === "gone") {
34758
+ this.devices = this.devices.filter((item) => item.deviceID !== device.deviceID);
34759
+ await atomic(this.devicesFile, JSON.stringify(this.devices)).catch(() => {
34760
+ });
34761
+ }
34762
+ return result === "sent";
34763
+ }
34764
+ return this.sender && device.token ? this.sender.send(device, payload, headers) : false;
34765
+ }
34682
34766
  async notify(value2) {
34683
- if (!this.sender || !this.devices.length) return false;
34684
- const devices = this.devices.filter((device) => device.kinds.includes("approval"));
34767
+ const devices = this.reachable.filter((device) => device.kinds.includes("approval"));
34685
34768
  if (!devices.length) return false;
34686
- return (await Promise.all(devices.map((device) => this.sender.send(device, approvalPushPayload(value2, device.hostID), {
34769
+ return (await Promise.all(devices.map((device) => this.send(device, approvalPushPayload(value2, device.hostID), {
34687
34770
  expiration: String(Math.floor(Date.parse(value2.expiresAt) / 1e3)),
34688
34771
  collapseId: value2.binding
34689
34772
  })))).some(Boolean);
@@ -34692,21 +34775,21 @@ var ApprovalPushService = class {
34692
34775
  * phones already accept agent alerts; the payload carries the reason so the
34693
34776
  * notification is actionable on its own. */
34694
34777
  async notifyFanoutBlocked(value2) {
34695
- if (!this.sender || !this.devices.length) return false;
34696
- const devices = this.devices.filter((device) => device.kinds.includes("approval"));
34778
+ const devices = this.reachable.filter((device) => device.kinds.includes("approval"));
34697
34779
  if (!devices.length) return false;
34698
- return (await Promise.all(devices.map((device) => this.sender.send(device, fanoutBlockedPushPayload(value2), {
34780
+ return (await Promise.all(devices.map((device) => this.send(device, fanoutBlockedPushPayload(value2), {
34699
34781
  expiration: "0",
34700
34782
  collapseId: `fanout-${value2.job}`
34701
34783
  })))).some(Boolean);
34702
34784
  }
34703
34785
  async notifySchedule(value2) {
34704
- if (!this.sender) return { notified: false, reason: "no push config" };
34705
- let devices = this.devices.filter((device) => device.kinds.includes(value2.kind));
34706
- if (!devices.length && value2.kind === "scheduleBlocked") devices = this.devices.filter((device) => device.kinds.includes("scheduleFailed"));
34786
+ const reachable = this.reachable;
34787
+ if (!reachable.length) return { notified: false, reason: this.sender || this.devices.length ? "no registered devices" : "no push config" };
34788
+ let devices = reachable.filter((device) => device.kinds.includes(value2.kind));
34789
+ if (!devices.length && value2.kind === "scheduleBlocked") devices = reachable.filter((device) => device.kinds.includes("scheduleFailed"));
34707
34790
  if (!devices.length) return { notified: false, reason: "no registered devices" };
34708
34791
  try {
34709
- const notified = (await Promise.all(devices.map((device) => this.sender.send(device, schedulePushPayload(value2), {
34792
+ const notified = (await Promise.all(devices.map((device) => this.send(device, schedulePushPayload(value2), {
34710
34793
  expiration: "0",
34711
34794
  collapseId: scheduleCollapseId(value2.kind, value2.runId)
34712
34795
  })))).some(Boolean);
@@ -35798,6 +35881,25 @@ var AgentHooks = class {
35798
35881
  if (!entry.response.destroyed) entry.response.end("{}");
35799
35882
  }
35800
35883
  }
35884
+ /** The phone's Esc or Cancel on a question the Hook holds. A held
35885
+ * AskUserQuestion has no terminal choice, so `releaseChoice` never lets it
35886
+ * go and the terminal stays frozen until the hold timer; decline it now so
35887
+ * Claude moves on. True when a held question was cancelled. */
35888
+ cancelHeldQuestion(target) {
35889
+ let cancelled = false;
35890
+ for (const [id2, entry] of this.pending) {
35891
+ if (entry.tool !== "AskUserQuestion" || JSON.stringify(entry.target) !== JSON.stringify(target)) continue;
35892
+ this.pending.delete(id2);
35893
+ this.dropPushBindings(id2);
35894
+ clearTimeout(entry.timer);
35895
+ if (!entry.response.destroyed) entry.response.end(JSON.stringify({ hookSpecificOutput: {
35896
+ hookEventName: "PermissionRequest",
35897
+ decision: { behavior: "deny", message: "The user cancelled this question in Phren without answering." }
35898
+ } }));
35899
+ cancelled = true;
35900
+ }
35901
+ return cancelled;
35902
+ }
35801
35903
  async answerPush(binding, decision) {
35802
35904
  if (!["approve", "deny"].includes(String(decision))) throw new BridgeError(400, "The approval answer is not valid.");
35803
35905
  const linked = this.pushBindings.consume(binding);
@@ -44452,6 +44554,8 @@ function conflictStrategy(relFile) {
44452
44554
  if (/^\.config\/task-archive\/[^/]+\.md$/i.test(file2)) return "archive";
44453
44555
  if (/(^|\/)reference\/topics\/[^/]+\.md$/i.test(file2)) return "topic";
44454
44556
  if (name === "summary.md") return "summary";
44557
+ if (name === "review.md") return "union";
44558
+ if (/(^|\/)(notes|journal)\/[^/]+\.md$/i.test(file2)) return "union";
44455
44559
  return null;
44456
44560
  }
44457
44561
  function git4(cwd, args) {
@@ -44491,11 +44595,26 @@ function mergeText(base, ours, theirs) {
44491
44595
  fs32.rmSync(dir, { recursive: true, force: true });
44492
44596
  }
44493
44597
  }
44494
- function mergeWithGeneratedBlock(base, ours, theirs, start, end, where) {
44598
+ function unionText(base, ours, theirs) {
44599
+ const clean2 = mergeText(base, ours, theirs);
44600
+ if (clean2 !== null) return clean2;
44601
+ const dir = fs32.mkdtempSync(path65.join(os3.tmpdir(), "phren-merge-"));
44602
+ try {
44603
+ const [o, b, t] = ["ours", "base", "theirs"].map((name) => path65.join(dir, name));
44604
+ fs32.writeFileSync(o, ours);
44605
+ fs32.writeFileSync(b, base);
44606
+ fs32.writeFileSync(t, theirs);
44607
+ const result = spawnSync2("git", ["merge-file", "--union", "-p", o, b, t], { encoding: "utf8", env: nonInteractiveGitEnv(), timeout: EXEC_TIMEOUT_MS });
44608
+ return result.status === 0 ? result.stdout : null;
44609
+ } finally {
44610
+ fs32.rmSync(dir, { recursive: true, force: true });
44611
+ }
44612
+ }
44613
+ function mergeWithGeneratedBlock(base, ours, theirs, start, end, where, merge2 = unionText) {
44495
44614
  const b = splitBlock(base, start, end);
44496
44615
  const o = splitBlock(ours, start, end);
44497
44616
  const t = splitBlock(theirs, start, end);
44498
- const rest = mergeText(b.rest, o.rest, t.rest);
44617
+ const rest = merge2(b.rest, o.rest, t.rest);
44499
44618
  if (rest === null) return null;
44500
44619
  const block = t.block ?? o.block;
44501
44620
  if (!block) return rest;
@@ -44512,8 +44631,13 @@ function resolveContent(strategy, base, ours, theirs) {
44512
44631
  return mergeTask(theirs, ours);
44513
44632
  case "topic":
44514
44633
  return mergeWithGeneratedBlock(base, ours, theirs, NOW_START, NOW_END, "top");
44634
+ // Summaries are regenerated from the store: when the hand-written part
44635
+ // doesn't merge cleanly, take the incoming file whole and let the next
44636
+ // summarize pass fold in anything only this machine had.
44515
44637
  case "summary":
44516
- return mergeWithGeneratedBlock(base, ours, theirs, KNOWS_START, KNOWS_END, "bottom");
44638
+ return mergeWithGeneratedBlock(base, ours, theirs, KNOWS_START, KNOWS_END, "bottom", mergeText) ?? theirs;
44639
+ case "union":
44640
+ return unionText(base, ours, theirs);
44517
44641
  }
44518
44642
  }
44519
44643
  function resolveStoreConflicts(cwd) {
@@ -46764,8 +46888,11 @@ async function paneRoute(ctx, url2, data, response) {
46764
46888
  const keys = external_exports.array(external_exports.enum(ANSWER_KEYS)).min(1).max(4).parse(data.keys);
46765
46889
  const status = String(pane.agent_status), menu = agentHooks.menuOpen(target);
46766
46890
  const holding = menu || !!agentHooks.terminalPrompt(target);
46767
- if (!holding && (keys.every((key) => key === "Escape") ? !["working", "blocked", "waiting", "unknown"].includes(status) : !["blocked", "waiting", "unknown"].includes(status))) throw new BridgeError(409, keys.every((key) => key === "Escape") ? "This agent is no longer working." : "This agent is not waiting for an answer.");
46768
- if (await agentHooks.answerReleasedQuestion(target, keys)) {
46891
+ const cancelled = keys.every((key) => key === "Escape") && agentHooks.cancelHeldQuestion(target);
46892
+ if (!cancelled && !holding && (keys.every((key) => key === "Escape") ? !["working", "blocked", "waiting", "unknown"].includes(status) : !["blocked", "waiting", "unknown"].includes(status))) throw new BridgeError(409, keys.every((key) => key === "Escape") ? "This agent is no longer working." : "This agent is not waiting for an answer.");
46893
+ if (cancelled) {
46894
+ result = { ok: true };
46895
+ } else if (await agentHooks.answerReleasedQuestion(target, keys)) {
46769
46896
  result = { ok: true };
46770
46897
  } else {
46771
46898
  const answerKeys = await agentHooks.dialogAnswerKeys(target, keys);
@@ -47149,6 +47276,13 @@ async function speechError(upstream) {
47149
47276
  return new BridgeError(502, `ElevenLabs failed (HTTP ${upstream.status}).`, { code: "speech-failed" });
47150
47277
  }
47151
47278
  }
47279
+ function speakableText(text3) {
47280
+ return text3.replace(/```[\s\S]*?(?:```|$)/g, " ").replace(/!\[([^\]]*)\]\([^)]*\)/g, "$1").replace(/\[([^\]]+)\]\([^)]*\)/g, "$1").replace(/https?:\/\/\S+/g, "a link").replace(/`([^`]*)`/g, "$1").split(/\r?\n/).map((line) => {
47281
+ const block = /^\s{0,3}(?:#{1,6}\s|[-*+]\s|\d+[.)]\s|\|)/.test(line);
47282
+ const words = line.replace(/^\s*\|?[\s:|-]*-[\s:|-]*\|?\s*$/, "").replace(/^\s{0,3}(?:#{1,6}\s+|>\s?|[-*+]\s+(?:\[[ xX]\]\s+)?)/, "").replace(/\s*\|\s*/g, (bar, offset, whole) => offset === 0 || offset + bar.length === whole.length ? "" : ", ").replace(/(\*\*|__|~~)(.+?)\1/g, "$2").replace(/(^|[^\w*])[*_](\S(?:.*?\S)?)[*_](?![\w*])/g, "$1$2").trim();
47283
+ return block && words && !/[.!?:;,]$/.test(words) ? `${words}.` : words;
47284
+ }).filter(Boolean).join(" ").replace(/\s+/g, " ").trim();
47285
+ }
47152
47286
  async function synthesizeSpeech(text3, signal, options = {}) {
47153
47287
  const key = await (options.key ?? readSpeechKey)();
47154
47288
  if (!key) throw new BridgeError(503, "Spoken replies aren't set up on this computer: it has no ElevenLabs key.", { code: "speech-unconfigured" });
@@ -47169,7 +47303,8 @@ async function synthesizeSpeech(text3, signal, options = {}) {
47169
47303
  return upstream.body;
47170
47304
  }
47171
47305
  async function streamSpeech(data, response, options = {}) {
47172
- const { text: text3 } = speechRequest.parse(data);
47306
+ const text3 = speakableText(speechRequest.parse(data).text);
47307
+ if (!text3) throw new BridgeError(400, "There is nothing to say in this reply.", { code: "speech-invalid" });
47173
47308
  const abort = new AbortController();
47174
47309
  response.once("close", () => {
47175
47310
  if (!response.writableEnded) abort.abort();
@@ -48833,7 +48968,8 @@ async function runBridge(args, version3) {
48833
48968
  return 0;
48834
48969
  }
48835
48970
  function approvalPushCheck(helper2) {
48836
- const configured = object2(helper2.capabilities).approvalPush === "direct-apns";
48971
+ const capability = object2(helper2.capabilities).approvalPush;
48972
+ const configured = capability === "direct-apns" || capability === "relay";
48837
48973
  return configured ? { configured } : { configured, warning: apnsSetupSteps() };
48838
48974
  }
48839
48975
  var SPEECH_KEY_USAGE = "Usage: phren bridge speech-key set (paste the key when asked, or pipe it on stdin)";
@@ -48879,7 +49015,7 @@ async function readSecret(prompt) {
48879
49015
  // src/bridge/hook-main.ts
48880
49016
  init_utils_helpers();
48881
49017
  Object.assign(process.env, nonInteractiveGitEnv());
48882
- runBridge(process.argv.slice(2), "0.3.1").then((code) => {
49018
+ runBridge(process.argv.slice(2), "0.3.2").then((code) => {
48883
49019
  process.exitCode = code;
48884
49020
  }).catch((error62) => {
48885
49021
  console.error(error62 instanceof Error ? error62.message : "Phren Hook failed.");
@@ -214,6 +214,7 @@ export async function handleStoreNamespace(args) {
214
214
  if (subcommand === "sync") {
215
215
  const stores = resolveAllStores(phrenPath);
216
216
  let hasErrors = false;
217
+ let primarySynced = false;
217
218
  const git = async (cwd, gitArgs) => {
218
219
  try {
219
220
  const output = execFileSync("git", gitArgs, {
@@ -279,12 +280,32 @@ export async function handleStoreNamespace(args) {
279
280
  }
280
281
  }
281
282
  console.log(` ${store.name}: ok (${result.detail})`);
283
+ if (store.role === "primary")
284
+ primarySynced = true;
282
285
  }
283
286
  catch (err) {
284
287
  console.log(` ${store.name}: FAILED (${errorMessage(err).split("\n")[0]})`);
285
288
  hasErrors = true;
286
289
  }
287
290
  }
291
+ // A pull can bring new skills or a changed global AGENTS.md. Refresh the
292
+ // home and repo links the way SessionStart does, so doctor doesn't report
293
+ // drift until the next session or a `doctor --fix`.
294
+ if (primarySynced) {
295
+ try {
296
+ const [{ repairPreexistingInstall }, { refreshLinkedContext }, { resolveRuntimeProfile }] = await Promise.all([
297
+ import("../init/setup.js"),
298
+ import("../link/refresh.js"),
299
+ import("../runtime-profile.js"),
300
+ ]);
301
+ repairPreexistingInstall(phrenPath);
302
+ refreshLinkedContext(phrenPath, resolveRuntimeProfile(phrenPath));
303
+ }
304
+ catch (err) {
305
+ console.log(` relink: FAILED (${errorMessage(err).split("\n")[0]}). Run 'phren doctor --fix'.`);
306
+ hasErrors = true;
307
+ }
308
+ }
288
309
  if (hasErrors) {
289
310
  console.error("\nSome stores failed to sync. Run 'phren doctor' for details.");
290
311
  }
@@ -362,7 +362,7 @@ export async function runWalkthrough(phrenPath, options) {
362
362
  printSection("Semantic Search (Optional)");
363
363
  log("Phren can use a local embedding model for semantic (fuzzy) search via Ollama.");
364
364
  log(" Best fit: paraphrase-heavy or weak-lexical queries.");
365
- log(" Skip it if you mostly search by filenames, symbols, commands, or exact phrases.");
365
+ log(" Skip it if you mostly search by filenames, function names, commands, or exact phrases.");
366
366
  log(" - Model: nomic-embed-text (274 MB, one-time download)");
367
367
  log(" - Ollama runs locally, no cloud, no cost");
368
368
  log(" - Falls back to FTS5 keyword search if disabled or unavailable");
package/dist/link/link.js CHANGED
@@ -525,8 +525,13 @@ export async function runLink(phrenPath, opts = {}) {
525
525
  logger.debug("link", `link writeSkillMd: ${errorMessage(err)}`);
526
526
  }
527
527
  log("");
528
- // Step 7: Context file
529
- if (opts.task === "debugging") {
528
+ // Step 7: Context file. ~/.phren-context.md and the root MEMORY.md in Claude
529
+ // Code's memory directory are home surfaces: only presets with selfHeal
530
+ // (managed, or an explicit override) create them, matching repair and doctor.
531
+ if (!caps.selfHeal) {
532
+ log(" ~/.phren-context.md and Claude memory skipped (preset without self-heal)");
533
+ }
534
+ else if (opts.task === "debugging") {
530
535
  writeContextDebugging(machine, profile, mcpStatusForContext, projects, phrenPath);
531
536
  }
532
537
  else if (opts.task === "planning") {
@@ -540,7 +545,8 @@ export async function runLink(phrenPath, opts = {}) {
540
545
  }
541
546
  // Step 8: Memory (read back native changes, then rebuild)
542
547
  readBackNativeMemory(phrenPath, projects);
543
- rebuildMemory(phrenPath, projects);
548
+ if (caps.selfHeal)
549
+ rebuildMemory(phrenPath, projects);
544
550
  log(`\nDone. Profile '${profile}' is active.`);
545
551
  if (opts.task)
546
552
  log(`Task mode: ${opts.task}`);
@@ -1,13 +1,12 @@
1
1
  /** Refresh existing managed context destinations after a store pull, without relinking the installation. */
2
2
  import * as fs from "fs";
3
3
  import * as path from "path";
4
- import { atomicWriteText, homePath } from "../phren-paths.js";
4
+ import { homePath } from "../phren-paths.js";
5
5
  import { getProjectDirs } from "../shared.js";
6
6
  import { readProjectConfig, getProjectSourcePath, getProjectOwnershipMode } from "../project-config.js";
7
7
  import { findProjectDir } from "../project-locator.js";
8
8
  import { resolveManagementCapabilities } from "../init/management-preset.js";
9
9
  import { syncScopeSkillsToDir } from "../skill/files.js";
10
- import { buildSkillManifest, renderSkillInstructionsSection } from "../skill/registry.js";
11
10
  export function refreshLinkedContext(phrenPath, profile) {
12
11
  const caps = resolveManagementCapabilities(phrenPath);
13
12
  if (caps.installSkillLinks) {
@@ -30,18 +29,20 @@ export function refreshLinkedContext(phrenPath, profile) {
30
29
  if (!target || !fs.existsSync(target))
31
30
  continue;
32
31
  const skillsDir = path.join(target, ".claude", "skills");
33
- const manifest = config.skills !== false && fs.existsSync(path.join(target, ".claude", "skill-manifest.json"))
34
- ? syncScopeSkillsToDir(phrenPath, project, skillsDir)
35
- : buildSkillManifest(phrenPath, profile, project);
32
+ if (config.skills !== false && fs.existsSync(path.join(target, ".claude", "skill-manifest.json"))) {
33
+ syncScopeSkillsToDir(phrenPath, project, skillsDir);
34
+ }
36
35
  const agentsPath = path.join(target, "AGENTS.md");
37
36
  const claudePath = path.join(source, "AGENTS.md");
38
- // The generated file is a snapshot, unlike the live AGENTS.md symlink.
39
- // Preserve native/user-owned instructions and installations without a Codex mirror.
37
+ // Older releases wrote AGENTS.md as a generated snapshot with a skills table;
38
+ // link and doctor --fix replace that with a symlink to the store's AGENTS.md.
39
+ // Do the same here instead of regenerating the snapshot, or a pull and a
40
+ // doctor run keep flipping the file between the two shapes.
40
41
  if (!fs.existsSync(agentsPath) || !fs.existsSync(claudePath) || fs.lstatSync(agentsPath).isSymbolicLink())
41
42
  continue;
42
- const marker = "<!-- phren:generated-agents -->";
43
- if (!fs.readFileSync(agentsPath, "utf8").includes(marker))
43
+ if (!fs.readFileSync(agentsPath, "utf8").includes("<!-- phren:generated-agents -->"))
44
44
  continue;
45
- atomicWriteText(agentsPath, `${fs.readFileSync(claudePath, "utf8").trimEnd()}\n\n${marker}\n${renderSkillInstructionsSection(manifest)}\n`);
45
+ fs.unlinkSync(agentsPath);
46
+ fs.symlinkSync(claudePath, agentsPath);
46
47
  }
47
48
  }
@@ -2,7 +2,7 @@ export interface ConflictResolution {
2
2
  resolved: string[];
3
3
  unresolved: string[];
4
4
  }
5
- type Strategy = "tasks" | "findings" | "archive" | "topic" | "summary" | null;
5
+ type Strategy = "tasks" | "findings" | "archive" | "topic" | "summary" | "union" | null;
6
6
  export declare function conflictStrategy(relFile: string): Strategy;
7
7
  /** Resolves what it can in the store's in-progress merge and stages it. */
8
8
  export declare function resolveStoreConflicts(cwd: string): ConflictResolution;
@@ -1,8 +1,14 @@
1
1
  /**
2
2
  * Resolves the content conflicts a store merge can settle without a person:
3
- * tasks.md per task id against the merge base, generated blocks from the
4
- * incoming side, and the record-oriented files that already union-merge.
5
- * Everything else stays conflicted so the caller aborts and names it.
3
+ * tasks.md per task id against the merge base, generated summaries from the
4
+ * incoming side, and the append-only record files (findings, notes, journal,
5
+ * review queue, topic archives) as a union of both sides. Everything else
6
+ * stays conflicted so the caller aborts and names it.
7
+ *
8
+ * Any file left unresolved aborts the whole merge, and every later auto-save
9
+ * then commits locally and fails to push, so a store drifts further from its
10
+ * remote each session. Every file phren itself writes during normal use needs
11
+ * a strategy here.
6
12
  */
7
13
  import { execFileSync, spawnSync } from "child_process";
8
14
  import * as crypto from "crypto";
@@ -29,6 +35,10 @@ export function conflictStrategy(relFile) {
29
35
  return "topic";
30
36
  if (name === "summary.md")
31
37
  return "summary";
38
+ if (name === "review.md")
39
+ return "union";
40
+ if (/(^|\/)(notes|journal)\/[^/]+\.md$/i.test(file))
41
+ return "union";
32
42
  return null;
33
43
  }
34
44
  function git(cwd, args) {
@@ -71,15 +81,38 @@ function mergeText(base, ours, theirs) {
71
81
  fs.rmSync(dir, { recursive: true, force: true });
72
82
  }
73
83
  }
84
+ /**
85
+ * A line-level three-way merge that keeps both sides of a conflicting hunk,
86
+ * local lines first (`git merge-file --union`). For append-only records two
87
+ * machines adding entries at the same spot is not a real conflict.
88
+ */
89
+ function unionText(base, ours, theirs) {
90
+ const clean = mergeText(base, ours, theirs);
91
+ if (clean !== null)
92
+ return clean;
93
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "phren-merge-"));
94
+ try {
95
+ const [o, b, t] = ["ours", "base", "theirs"].map((name) => path.join(dir, name));
96
+ fs.writeFileSync(o, ours);
97
+ fs.writeFileSync(b, base);
98
+ fs.writeFileSync(t, theirs);
99
+ const result = spawnSync("git", ["merge-file", "--union", "-p", o, b, t], { encoding: "utf8", env: nonInteractiveGitEnv(), timeout: EXEC_TIMEOUT_MS });
100
+ return result.status === 0 ? result.stdout : null;
101
+ }
102
+ finally {
103
+ fs.rmSync(dir, { recursive: true, force: true });
104
+ }
105
+ }
74
106
  /**
75
107
  * Generated blocks regenerate, so the incoming block wins; the rest of the
76
- * file must still merge line by line.
108
+ * file merges with `merge`: a union of both sides by default (a topic
109
+ * archive's bullets).
77
110
  */
78
- function mergeWithGeneratedBlock(base, ours, theirs, start, end, where) {
111
+ function mergeWithGeneratedBlock(base, ours, theirs, start, end, where, merge = unionText) {
79
112
  const b = splitBlock(base, start, end);
80
113
  const o = splitBlock(ours, start, end);
81
114
  const t = splitBlock(theirs, start, end);
82
- const rest = mergeText(b.rest, o.rest, t.rest);
115
+ const rest = merge(b.rest, o.rest, t.rest);
83
116
  if (rest === null)
84
117
  return null;
85
118
  const block = t.block ?? o.block;
@@ -94,7 +127,11 @@ function resolveContent(strategy, base, ours, theirs) {
94
127
  // Archived tasks only accumulate: keep both sides, the incoming version of any duplicate.
95
128
  case "archive": return mergeTask(theirs, ours);
96
129
  case "topic": return mergeWithGeneratedBlock(base, ours, theirs, NOW_START, NOW_END, "top");
97
- case "summary": return mergeWithGeneratedBlock(base, ours, theirs, KNOWS_START, KNOWS_END, "bottom");
130
+ // Summaries are regenerated from the store: when the hand-written part
131
+ // doesn't merge cleanly, take the incoming file whole and let the next
132
+ // summarize pass fold in anything only this machine had.
133
+ case "summary": return mergeWithGeneratedBlock(base, ours, theirs, KNOWS_START, KNOWS_END, "bottom", mergeText) ?? theirs;
134
+ case "union": return unionText(base, ours, theirs);
98
135
  }
99
136
  }
100
137
  /** Resolves what it can in the store's in-progress merge and stages it. */
@@ -698,7 +698,7 @@ async function handleGetFindings(ctx, { project, limit, include_superseded, incl
698
698
  if (entry.scope)
699
699
  metadata.push(`scope=${entry.scope}`);
700
700
  if (entry.symbol)
701
- metadata.push(`symbol=${entry.symbol}`);
701
+ metadata.push(`name=${entry.symbol}`);
702
702
  if (entry.supersedes)
703
703
  metadata.push(`supersedes="${entry.supersedes.slice(0, 30)}"`);
704
704
  if (entry.supersededBy)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@phren/cli",
3
- "version": "0.3.1",
3
+ "version": "0.3.2",
4
4
  "description": "Knowledge layer for AI agents - CLI, MCP server, and data layer",
5
5
  "type": "module",
6
6
  "bin": {