@phren/cli 0.3.49 → 0.3.51

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 (35) hide show
  1. package/dist/bridge/computers.js +5 -4
  2. package/dist/bridge/conductor-role.d.ts +4 -0
  3. package/dist/bridge/conductor-role.js +20 -1
  4. package/dist/bridge/dispatch-origins.d.ts +32 -0
  5. package/dist/bridge/dispatch-origins.js +44 -0
  6. package/dist/bridge/dispatch-returns.d.ts +2 -1
  7. package/dist/bridge/dispatch-returns.js +9 -2
  8. package/dist/bridge/dispatch.d.ts +5 -0
  9. package/dist/bridge/dispatch.js +119 -23
  10. package/dist/bridge/hand-off.d.ts +1 -0
  11. package/dist/bridge/hand-off.js +1 -1
  12. package/dist/bridge/install.d.ts +1 -0
  13. package/dist/bridge/install.js +7 -0
  14. package/dist/bridge/project-memory.d.ts +2 -0
  15. package/dist/bridge/project-memory.js +27 -13
  16. package/dist/bridge/request-origin.d.ts +6 -0
  17. package/dist/bridge/request-origin.js +6 -0
  18. package/dist/bridge/scoped-gateway.d.ts +3 -0
  19. package/dist/bridge/scoped-gateway.js +22 -4
  20. package/dist/bridge/server-routes.d.ts +1 -0
  21. package/dist/bridge/server-routes.js +10 -2
  22. package/dist/bridge/session-move.d.ts +10 -2
  23. package/dist/bridge/session-move.js +124 -12
  24. package/dist/bridge-hook.mjs +2280 -1720
  25. package/dist/cli/hooks-output.js +21 -3
  26. package/dist/content/citation-freshness.d.ts +29 -0
  27. package/dist/content/citation-freshness.js +311 -0
  28. package/dist/modules/registry.js +1 -1
  29. package/dist/shared/retrieval.d.ts +2 -1
  30. package/dist/shared/retrieval.js +40 -8
  31. package/dist/sync/gitboy-webhook.d.ts +43 -0
  32. package/dist/sync/gitboy-webhook.js +119 -0
  33. package/dist/tools/dispatch.js +1 -1
  34. package/dist/tools/search.js +34 -4
  35. package/package.json +1 -1
@@ -3,7 +3,7 @@ import { chmod, lstat, mkdir, mkdtemp, readFile, rename, rm, writeFile } from "n
3
3
  import { homedir } from "node:os";
4
4
  import path from "node:path";
5
5
  import { promisify } from "node:util";
6
- import { forcedCommand } from "./install.js";
6
+ import { forcedCommand, peerForcedCommand } from "./install.js";
7
7
  import { BridgeError, bridgeRoot, computerName } from "./protocol.js";
8
8
  const exec = promisify(execFile);
9
9
  export { computerName };
@@ -20,7 +20,7 @@ export function publicComputerKey(value) {
20
20
  return `ssh-ed25519 ${match[1]}`;
21
21
  }
22
22
  export function computerKeyLine(name, publicKey) {
23
- return `restrict,pty,${forcedCommand} ${publicComputerKey(publicKey)} phren-computer:${computerName.parse(name)}`;
23
+ return `restrict,${peerForcedCommand} ${publicComputerKey(publicKey)} phren-computer:${computerName.parse(name)}`;
24
24
  }
25
25
  async function regularFile(file) {
26
26
  const info = await lstat(file).catch((error) => {
@@ -70,9 +70,10 @@ export async function enrollComputer(name, root = bridgeRoot()) {
70
70
  /** Accept a public key, rebuilding the restrictions rather than trusting supplied options. */
71
71
  export async function acceptComputer(name, input, sshDirectory = path.join(homedir(), ".ssh")) {
72
72
  computerName.parse(name);
73
- const prefix = `restrict,pty,${forcedCommand} `;
73
+ const prefixes = [`restrict,${peerForcedCommand} `, `restrict,pty,${forcedCommand} `];
74
74
  const raw = input.trim();
75
- const publicKey = publicComputerKey(raw.startsWith(prefix) ? raw.slice(prefix.length) : raw);
75
+ const prefix = prefixes.find(value => raw.startsWith(value));
76
+ const publicKey = publicComputerKey(prefix ? raw.slice(prefix.length) : raw);
76
77
  const line = computerKeyLine(name, publicKey);
77
78
  const encoded = publicKey.split(" ")[1];
78
79
  await appendAuthorizedKey(line, existing => existing.endsWith(` phren-computer:${name}`) || existing.split(/\s+/).includes(encoded), "This name or key is already enrolled differently. Revoke the old line explicitly first.", sshDirectory);
@@ -83,6 +83,10 @@ export declare function conductorPane(server: string, s: Json): Promise<Json | u
83
83
  export declare function recordedConductor(): Promise<ConductorRecord | undefined>;
84
84
  /** Makes `pane` on `server` this computer's conductor, replacing any record. */
85
85
  export declare function recordConductor(server: string, pane: Json, by: ConductorRecord["by"], session?: string): Promise<ConductorRecord>;
86
+ /** Move only the captured role. The optional hand-over holds the receipt
87
+ * writer's queue while preparing routing and committing this role; it must
88
+ * roll routing back if commit fails. No role writer can interleave here. */
89
+ export declare function transferConductor(expected: ConductorRecord, server: string, pane: Json, session?: string, handOver?: (commit: () => Promise<void>) => Promise<void>): Promise<ConductorRecord>;
86
90
  /** The session now running in the conductor's pane: a restart or new login reattaches here. */
87
91
  export declare function noteConductorSession(server: string, pane: string, session: string): Promise<void>;
88
92
  /** Ends the role. With `pane`, only when that pane holds it. Returns what was stopped. */
@@ -1,8 +1,9 @@
1
1
  import { lstatSync, readFileSync } from "node:fs";
2
2
  import path from "node:path";
3
3
  import { z } from "zod";
4
+ import { conductorOriginChanged } from "./dispatch-origins.js";
4
5
  import { isConductorName, paneAgentName } from "./herdr.js";
5
- import { atomicInPrivateDir, bridgeRoot, id, objects, provider, serverName } from "./protocol.js";
6
+ import { atomicInPrivateDir, BridgeError, bridgeRoot, id, objects, provider, serverName } from "./protocol.js";
6
7
  /**
7
8
  * Which pane is this computer's conductor, as the Hook keeps it
8
9
  * (docs/conductor-sets.md). The role follows the pane: server, pane id and
@@ -57,6 +58,7 @@ async function writeRoleState(state) {
57
58
  const file = roleFile();
58
59
  await atomicInPrivateDir(file, JSON.stringify(state, null, 2) + "\n");
59
60
  cached = { file, state };
61
+ conductorOriginChanged(state.conductor);
60
62
  }
61
63
  /** Every read-modify-write of the state runs one at a time: an overview poll
62
64
  * noting a moved pane must not interleave with a make or stop and bring back
@@ -148,6 +150,23 @@ export function recordConductor(server, pane, by, session) {
148
150
  return record;
149
151
  });
150
152
  }
153
+ /** Move only the captured role. The optional hand-over holds the receipt
154
+ * writer's queue while preparing routing and committing this role; it must
155
+ * roll routing back if commit fails. No role writer can interleave here. */
156
+ export function transferConductor(expected, server, pane, session, handOver = commit => commit()) {
157
+ return serialized(async () => {
158
+ const state = await readRoleState();
159
+ const current = state?.conductor;
160
+ // Include the generation (since), terminal and session, so a stop/make
161
+ // or another move cannot be overwritten even if it used the same pane.
162
+ if (!current || !recordSchema.keyof().options.every(field => current[field] === expected[field])) {
163
+ throw new BridgeError(409, "The conductor changed during the move; nothing was transferred.");
164
+ }
165
+ const record = recordFor(server, pane, "owner", session);
166
+ await handOver(() => writeRoleState({ ...state, version: 1, conductor: record }));
167
+ return record;
168
+ });
169
+ }
151
170
  /** The session now running in the conductor's pane: a restart or new login reattaches here. */
152
171
  export function noteConductorSession(server, pane, session) {
153
172
  return serialized(async () => {
@@ -0,0 +1,32 @@
1
+ import { type Provider } from "./protocol.js";
2
+ type PaneIdentity = {
3
+ server: string;
4
+ pane: string;
5
+ terminal?: string;
6
+ };
7
+ type Origin = PaneIdentity & {
8
+ workspace: string;
9
+ tab: string;
10
+ terminal: string;
11
+ agent: Provider;
12
+ };
13
+ export interface DispatchOriginWindow {
14
+ rewrite(origin: Origin | undefined): Origin | undefined;
15
+ finish(): void;
16
+ }
17
+ /** Register before a dispatch's first await; only these live operations can
18
+ * inherit a hand-over alias. A later dispatch starts with no aliases. */
19
+ export declare function trackDispatchOrigin(): DispatchOriginWindow;
20
+ /** Prepare while holding the receipt lock, then seal only after role commit.
21
+ * Keep prior chains in this snapshot because the role write invalidates them.
22
+ * Operations started during the commit are included; later ones never are. */
23
+ export declare function prepareDispatchOriginHandover(from: PaneIdentity, to: Origin): () => void;
24
+ /** Called after every successful role write, without acquiring another lock.
25
+ * A stop or reassignment must not let an earlier move redirect late workers
26
+ * away from the newly chosen conductor. No aliases survive a Hook restart. */
27
+ export declare function conductorOriginChanged(conductor: (PaneIdentity & {
28
+ source?: Provider;
29
+ workspace?: string;
30
+ tab?: string;
31
+ }) | null | undefined): void;
32
+ export {};
@@ -0,0 +1,44 @@
1
+ import { bridgeRoot } from "./protocol.js";
2
+ const pending = new Set();
3
+ const samePane = (left, right) => left.server === right.server && left.pane === right.pane && (left.terminal === undefined || left.terminal === right.terminal);
4
+ /** Register before a dispatch's first await; only these live operations can
5
+ * inherit a hand-over alias. A later dispatch starts with no aliases. */
6
+ export function trackDispatchOrigin() {
7
+ const entry = { root: bridgeRoot(), aliases: [] };
8
+ pending.add(entry);
9
+ return {
10
+ rewrite: origin => origin && (entry.aliases.find(alias => samePane(alias.from, origin))?.to ?? origin),
11
+ finish: () => { pending.delete(entry); entry.aliases = []; },
12
+ };
13
+ }
14
+ /** Prepare while holding the receipt lock, then seal only after role commit.
15
+ * Keep prior chains in this snapshot because the role write invalidates them.
16
+ * Operations started during the commit are included; later ones never are. */
17
+ export function prepareDispatchOriginHandover(from, to) {
18
+ const root = bridgeRoot();
19
+ const before = new Map([...pending].filter(entry => entry.root === root).map(entry => [entry, entry.aliases]));
20
+ return () => {
21
+ for (const entry of pending) {
22
+ if (entry.root !== root)
23
+ continue;
24
+ entry.aliases = (before.get(entry) ?? entry.aliases)
25
+ .filter(alias => !samePane(alias.from, to) && !samePane(alias.from, from))
26
+ .map(alias => samePane(alias.to, from) ? { ...alias, to } : alias);
27
+ entry.aliases.push({ from, to });
28
+ }
29
+ };
30
+ }
31
+ /** Called after every successful role write, without acquiring another lock.
32
+ * A stop or reassignment must not let an earlier move redirect late workers
33
+ * away from the newly chosen conductor. No aliases survive a Hook restart. */
34
+ export function conductorOriginChanged(conductor) {
35
+ const root = bridgeRoot();
36
+ for (const entry of pending) {
37
+ if (entry.root !== root)
38
+ continue;
39
+ entry.aliases = entry.aliases.filter(alias => conductor && samePane(alias.to, conductor)
40
+ && (conductor.source === undefined || alias.to.agent === conductor.source)
41
+ && (conductor.workspace === undefined || alias.to.workspace === conductor.workspace)
42
+ && (conductor.tab === undefined || alias.to.tab === conductor.tab));
43
+ }
44
+ }
@@ -231,7 +231,8 @@ export interface DispatchReturnsOptions {
231
231
  };
232
232
  now?: () => number;
233
233
  }
234
- /** One notice's delivery id, named by what it reports: the same returns keep the same id on a retry. */
234
+ /** The same returns to the same origin keep their id on retry. A role
235
+ * hand-over gets a fresh delivery instead of reusing the old chat's receipt. */
235
236
  export declare function noticeDeliveryId(receipts: readonly Receipt[]): string;
236
237
  /** Dispatching side: follows open dispatches and delivers their returns. */
237
238
  export declare class DispatchReturns {
@@ -522,9 +522,10 @@ export function returnRow(receipt) {
522
522
  ...(receipt.moves ? { moves: receipt.moves } : {}), ...(receipt.target ? { target: receipt.target } : {}) };
523
523
  }
524
524
  const originKey = (origin) => JSON.stringify([origin.server, origin.workspace, origin.tab, origin.pane, origin.terminal]);
525
- /** One notice's delivery id, named by what it reports: the same returns keep the same id on a retry. */
525
+ /** The same returns to the same origin keep their id on retry. A role
526
+ * hand-over gets a fresh delivery instead of reusing the old chat's receipt. */
526
527
  export function noticeDeliveryId(receipts) {
527
- return `notice-${createHash("sha256").update(receipts.map(receipt => `${receipt.id}@${receipt.returned.at}`).sort().join(",")).digest("hex").slice(0, 32)}`;
528
+ return `notice-${createHash("sha256").update(receipts.map(receipt => `${receipt.id}@${receipt.returned.at}@${receipt.origin ? originKey(receipt.origin) : ""}`).sort().join(",")).digest("hex").slice(0, 32)}`;
528
529
  }
529
530
  /** Dispatching side: follows open dispatches and delivers their returns. */
530
531
  export class DispatchReturns {
@@ -762,6 +763,12 @@ export class DispatchReturns {
762
763
  const at = new Date(this.now()).toISOString();
763
764
  for (const receipt of receipts) {
764
765
  await updateReceipt(receipt.id, current => {
766
+ // An in-flight notice to the old chat must not acknowledge a return
767
+ // whose origin changed while delivery was pending.
768
+ if (!current.origin || originKey(current.origin) !== key) {
769
+ busy = true;
770
+ return false;
771
+ }
765
772
  if (!current.returned || current.returned.read || current.returned.at !== receipt.returned.at)
766
773
  return false;
767
774
  current.returned.notifiedAt = at;
@@ -1,4 +1,5 @@
1
1
  import { z } from "zod";
2
+ import { type ConductorRecord } from "./conductor-role.js";
2
3
  import { type DispatchHost } from "./dispatch-hosts.js";
3
4
  import { type Json, type Provider, type Target } from "./protocol.js";
4
5
  import { type HarnessInventory } from "./harnesses.js";
@@ -421,6 +422,10 @@ export declare function dispatchProjectDirectory(project: unknown, home?: string
421
422
  * receipt still being placed (launching or sending) is never touched.
422
423
  */
423
424
  export declare function updateReceipt(receiptID: string, change: (receipt: Receipt) => boolean): Promise<Receipt | undefined>;
425
+ /** Hand over all open worker routes using the receipt writer's own lock and
426
+ * update path. Commit the role last; any failure restores the old origins.
427
+ * Placing receipts are refused because placement can still overwrite them. */
428
+ export declare function repointDispatchOrigins(from: Pick<ConductorRecord, "server" | "pane" | "terminal">, to: NonNullable<Receipt["origin"]>, commit: () => Promise<void>): Promise<void>;
424
429
  /** One bounded line for a log or a receipt: a Bridge message, an errno code, or the error's first line. */
425
430
  export declare function failureReason(error: unknown): string;
426
431
  export declare function dispatchStatus(): Promise<Receipt[]>;
@@ -13,6 +13,7 @@ import { findGrant, grantLabel, permissionModeAllowed, DEFAULT_MAX_PERMISSION_MO
13
13
  import { checkAgentDispatch, projectAuthority, readAuthority, RELEASE_ACTIONS, releaseAction } from "./authority.js";
14
14
  import { hookPeers } from "./peers.js";
15
15
  import { callerQuery, localCaller, oneWayHint } from "./conductor-group.js";
16
+ import { prepareDispatchOriginHandover, trackDispatchOrigin } from "./dispatch-origins.js";
16
17
  import { recordedConductor } from "./conductor-role.js";
17
18
  import { linkedComputer } from "./computer-identity.js";
18
19
  import { isLocalComputer, localHost, peerHost } from "./dispatch-hosts.js";
@@ -133,7 +134,20 @@ export async function dispatchProjectDirectory(project, home = homeDir()) {
133
134
  }
134
135
  throw new BridgeError(404, `Project ${name} is not on this computer: the store names no folder for ${getMachineName()} that exists here, and there is no ~/Projects/${name} checkout.`);
135
136
  }
136
- async function save(receipt) {
137
+ function save(receipt, originWindow) {
138
+ return serializeReceiptUpdate(async () => {
139
+ // Only this already-running dispatch can inherit a hand-over alias.
140
+ // Resolve it under the receipt lock, after any role change invalidation.
141
+ const origin = originWindow.rewrite(receipt.origin);
142
+ if (origin !== receipt.origin && !receipt.closedAt) {
143
+ receipt.origin = origin;
144
+ if (receipt.returned && !receipt.returned.read)
145
+ delete receipt.returned.notifiedAt;
146
+ }
147
+ await saveReceipt(receipt);
148
+ });
149
+ }
150
+ async function saveReceipt(receipt) {
137
151
  const root = path.join(bridgeRoot(), "dispatches");
138
152
  await mkdir(root, { recursive: true, mode: 0o700 });
139
153
  await atomic(path.join(root, `${receipt.id}.json`), receipt);
@@ -147,23 +161,99 @@ let receiptUpdates = Promise.resolve();
147
161
  * receipt still being placed (launching or sending) is never touched.
148
162
  */
149
163
  export function updateReceipt(receiptID, change) {
150
- const run = receiptUpdates.then(async () => {
151
- const file = path.join(bridgeRoot(), "dispatches", `${z.string().uuid().parse(receiptID)}.json`);
152
- const info = await lstat(file).catch(() => undefined);
153
- if (!info?.isFile() || info.isSymbolicLink() || info.size > MAX_RECEIPT_BYTES)
154
- return undefined;
155
- const receipt = receiptSchema.parse(JSON.parse(await readFile(file, "utf8")));
156
- if (["launching", "sending"].includes(receipt.state))
157
- return undefined;
158
- if (!change(receipt))
159
- return receipt;
160
- receipt.updatedAt = new Date().toISOString();
161
- await atomic(file, receiptSchema.parse(receipt));
162
- return receipt;
163
- });
164
+ return serializeReceiptUpdate(() => changeReceipt(receiptID, change));
165
+ }
166
+ function serializeReceiptUpdate(change) {
167
+ const run = receiptUpdates.then(change);
164
168
  receiptUpdates = run.catch(() => undefined);
165
169
  return run;
166
170
  }
171
+ async function readReceipt(receiptID) {
172
+ const file = path.join(bridgeRoot(), "dispatches", `${z.string().uuid().parse(receiptID)}.json`);
173
+ const info = await lstat(file).catch(error => {
174
+ if (error.code !== "ENOENT")
175
+ throw error;
176
+ return undefined;
177
+ });
178
+ if (!info?.isFile() || info.isSymbolicLink() || info.size > MAX_RECEIPT_BYTES)
179
+ return undefined;
180
+ return receiptSchema.parse(JSON.parse(await readFile(file, "utf8")));
181
+ }
182
+ /** Caller holds receiptUpdates; ordinary polling never edits a placing receipt. */
183
+ async function changeReceipt(receiptID, change) {
184
+ const receipt = await readReceipt(receiptID);
185
+ if (!receipt || ["launching", "sending"].includes(receipt.state))
186
+ return undefined;
187
+ if (!change(receipt))
188
+ return receipt;
189
+ receipt.updatedAt = new Date().toISOString();
190
+ await saveReceipt(receiptSchema.parse(receipt));
191
+ return receipt;
192
+ }
193
+ /** Hand over all open worker routes using the receipt writer's own lock and
194
+ * update path. Commit the role last; any failure restores the old origins.
195
+ * Placing receipts are refused because placement can still overwrite them. */
196
+ export function repointDispatchOrigins(from, to, commit) {
197
+ return serializeReceiptUpdate(async () => {
198
+ const seal = prepareDispatchOriginHandover(from, to);
199
+ const names = await readdir(path.join(bridgeRoot(), "dispatches")).catch(error => {
200
+ if (error.code !== "ENOENT")
201
+ throw error;
202
+ return [];
203
+ });
204
+ const matches = (origin) => origin?.server === from.server && origin.pane === from.pane
205
+ && (from.terminal === undefined || origin.terminal === from.terminal);
206
+ const selected = [];
207
+ for (const name of names.filter(name => /^[a-f0-9-]{36}\.json$/.test(name))) {
208
+ const receipt = await readReceipt(name.slice(0, -5));
209
+ if (!receipt || receipt.closedAt || !matches(receipt.origin))
210
+ continue;
211
+ if (["launching", "sending"].includes(receipt.state))
212
+ throw new BridgeError(409, "A conductor dispatch is still being placed; retry the move after it settles.");
213
+ selected.push(receipt);
214
+ }
215
+ const changed = [];
216
+ try {
217
+ for (const before of selected) {
218
+ await changeReceipt(before.id, receipt => {
219
+ if (receipt.closedAt || !matches(receipt.origin))
220
+ return false;
221
+ receipt.origin = to;
222
+ // Unread returns already announced to the old chat need a new notice.
223
+ if (receipt.returned && !receipt.returned.read)
224
+ delete receipt.returned.notifiedAt;
225
+ return true;
226
+ });
227
+ changed.push(before);
228
+ }
229
+ await commit();
230
+ seal();
231
+ }
232
+ catch (error) {
233
+ const failures = [];
234
+ for (const before of changed.reverse()) {
235
+ try {
236
+ await changeReceipt(before.id, receipt => {
237
+ receipt.origin = before.origin;
238
+ if (receipt.returned && receipt.returned.at === before.returned?.at) {
239
+ if (before.returned.notifiedAt)
240
+ receipt.returned.notifiedAt = before.returned.notifiedAt;
241
+ else
242
+ delete receipt.returned.notifiedAt;
243
+ }
244
+ return true;
245
+ });
246
+ }
247
+ catch (rollback) {
248
+ failures.push(`${before.id}: ${failureReason(rollback)}`);
249
+ }
250
+ }
251
+ if (failures.length)
252
+ throw new Error(`${failureReason(error)} Receipt routing rollback failed: ${failures.join("; ")}`);
253
+ throw error;
254
+ }
255
+ });
256
+ }
167
257
  /** No ledger yet is normal; any other read failure is logged before it reads as empty. */
168
258
  async function receiptNames(root) {
169
259
  try {
@@ -183,7 +273,11 @@ export function failureReason(error) {
183
273
  const message = error instanceof Error ? error.message.split("\n")[0] : String(error);
184
274
  return `${typeof code === "string" && !(error instanceof BridgeError) ? `${code}: ` : ""}${message}`.replace(/[\x00-\x1f\x7f]/g, " ").slice(0, 200);
185
275
  }
186
- export async function dispatchStatus() {
276
+ export function dispatchStatus() {
277
+ return serializeReceiptUpdate(readDispatchStatus);
278
+ }
279
+ /** Caller holds receiptUpdates, including for the entire routing snapshot. */
280
+ async function readDispatchStatus() {
187
281
  const root = path.join(bridgeRoot(), "dispatches");
188
282
  const names = (await receiptNames(root)).filter(name => /^[a-f0-9-]{36}\.json$/.test(name)).slice(0, 1024);
189
283
  const receipts = [];
@@ -476,6 +570,7 @@ export class DispatchService {
476
570
  if (this.active)
477
571
  throw new BridgeError(429, "A dispatch is already being placed. Try again after its receipt arrives.");
478
572
  this.active = true;
573
+ const originWindow = trackDispatchOrigin();
479
574
  let holding = true, placed;
480
575
  const release = () => { if (holding) {
481
576
  holding = false;
@@ -582,7 +677,7 @@ export class DispatchService {
582
677
  ...(grant ? { granted: grantLabel(grant) } : {}), ...(authority?.listed ? { authority: authority.line.slice(0, 600) } : {}),
583
678
  ...(checked?.confirmation ? { authorityConfirmed: checked.confirmation.confirmedAt } : {}),
584
679
  ...(skipped.length ? { skipped } : {}), ...(origin ? { origin } : {}), ...(continues ? { continues } : {}) };
585
- await save(receipt);
680
+ await save(receipt, originWindow);
586
681
  try {
587
682
  // The brief goes with the launch: a Hook that can start the harness
588
683
  // with it says so, and any other types it below.
@@ -602,11 +697,11 @@ export class DispatchService {
602
697
  const ignored = data.permissionMode && launched.permissionMode !== data.permissionMode ? IGNORED_MODE : undefined;
603
698
  if (launched.briefLaunched === true) {
604
699
  receipt.brief = "launch";
605
- await this.confirmLaunched(peer, receipt, launched);
700
+ await this.confirmLaunched(peer, receipt, launched, originWindow);
606
701
  if (ignored)
607
702
  receipt.error = [receipt.error, ignored].filter(Boolean).join(" ").slice(0, 500);
608
703
  receipt.updatedAt = new Date().toISOString();
609
- await save(receipt);
704
+ await save(receipt, originWindow);
610
705
  return { ok: receipt.state === "accepted", ...receipt };
611
706
  }
612
707
  receipt.brief = "typed";
@@ -622,7 +717,7 @@ export class DispatchService {
622
717
  receipt.target = target;
623
718
  receipt.state = "sending";
624
719
  receipt.updatedAt = new Date().toISOString();
625
- await save(receipt);
720
+ await save(receipt, originWindow);
626
721
  if (!("starting" in target)) {
627
722
  const result = await sendBrief(peer, target, prompt, `dispatch-${receipt.id}`);
628
723
  receipt.state = result.ok === true && result.deliveryUncertain !== true ? "accepted" : "uncertain";
@@ -647,10 +742,11 @@ export class DispatchService {
647
742
  }
648
743
  }
649
744
  receipt.updatedAt = new Date().toISOString();
650
- await save(receipt);
745
+ await save(receipt, originWindow);
651
746
  return { ok: receipt.state === "accepted", ...receipt };
652
747
  }
653
748
  finally {
749
+ originWindow.finish();
654
750
  release();
655
751
  if (placed) {
656
752
  const left = this.inFlight(placed) - 1;
@@ -724,13 +820,13 @@ export class DispatchService {
724
820
  * itself, so that is not a failure. Neither confirmed nor held reads
725
821
  * uncertain, and the returns loop keeps asking.
726
822
  */
727
- async confirmLaunched(peer, receipt, launched) {
823
+ async confirmLaunched(peer, receipt, launched, originWindow) {
728
824
  const known = remoteTarget.safeParse(launched.target);
729
825
  if (known.success && known.data.source === receipt.harness && known.data.server === peer.server)
730
826
  receipt.target = known.data;
731
827
  receipt.state = "sending";
732
828
  receipt.updatedAt = new Date().toISOString();
733
- await save(receipt);
829
+ await save(receipt, originWindow);
734
830
  const held = (status) => ["blocked", "waiting"].includes(String(status));
735
831
  const arrival = held(launched.agentStatus) ? await arrivalOf(peer, receipt.id).catch(() => undefined) ?? {}
736
832
  : await awaitArrival(peer, receipt.id, this.settleIntervalMs);
@@ -89,6 +89,7 @@ export declare const moveSessionSchema: z.ZodObject<{
89
89
  export declare function moveSession(input: unknown, options?: {
90
90
  waitMs?: number;
91
91
  pollMs?: number;
92
+ agent?: boolean;
92
93
  }): Promise<{
93
94
  ok: boolean;
94
95
  move: Json;
@@ -161,7 +161,7 @@ export async function moveSession(input, options = {}) {
161
161
  if (peer && target.server !== peer.server)
162
162
  throw new BridgeError(400, "The target belongs to a different Herdr server on that computer.");
163
163
  const to = { harness: data.harness, ...(data.account ? { account: data.account } : {}), ...(data.model ? { model: data.model } : {}), ...(data.effort ? { effort: data.effort } : {}) };
164
- move = object((await request("/v1/sessions/move", { target, to: moveToSchema.parse(to), ...(data.id ? { id: data.id } : {}) })).move);
164
+ move = object((await request("/v1/sessions/move", { target, to: moveToSchema.parse(to), ...(options.agent ? { origin: "agent" } : {}), ...(data.id ? { id: data.id } : {}) })).move);
165
165
  if (data.wait !== false && typeof move.id === "string") {
166
166
  const until = Date.now() + (options.waitMs ?? MOVE_WAIT_MS);
167
167
  while (!settled(move) && Date.now() < until) {
@@ -1,6 +1,7 @@
1
1
  import { type ModuleSnapshot } from "../modules/runtime.js";
2
2
  import type { GatewayScope } from "./scoped-gateway.js";
3
3
  import { type CodexServerEntry } from "./codex-servers.js";
4
+ export declare const peerForcedCommand = "command=\"sh ~/.local/share/phren/bridge/dispatch-scoped peer\"";
4
5
  export declare const forcedCommand = "command=\"sh ~/.local/share/phren/bridge/dispatch\"";
5
6
  /** A scoped key's forced command. A separate script, so a key added before
6
7
  * the Hook can serve its scope fails closed instead of reaching `dispatch`. */
@@ -22,6 +22,7 @@ import { serversInService } from "./codex-servers.js";
22
22
  const exec = promisify(execFile);
23
23
  const label = "com.phren.hook";
24
24
  const unit = "phren-hook.service";
25
+ export const peerForcedCommand = 'command="sh ~/.local/share/phren/bridge/dispatch-scoped peer"';
25
26
  export const forcedCommand = 'command="sh ~/.local/share/phren/bridge/dispatch"';
26
27
  /** A scoped key's forced command. A separate script, so a key added before
27
28
  * the Hook can serve its scope fails closed instead of reaching `dispatch`. */
@@ -52,6 +53,12 @@ export function upgradeKeys(text) {
52
53
  let changed = 0;
53
54
  const result = text.split(/(?<=\n)/).map(line => {
54
55
  const parsed = keyOptions(line);
56
+ if (parsed && parsed.options[0] === "restrict" && /^\s+ssh-ed25519 [A-Za-z0-9+/=]+ phren-computer:[A-Za-z0-9_.-]+\s*$/.test(parsed.rest)
57
+ && parsed.options.includes(forcedCommand)) {
58
+ changed++;
59
+ return parsed.options.filter(option => option !== "pty" && option.toLowerCase() !== "port-forwarding" && !option.toLowerCase().startsWith("permitopen="))
60
+ .map(option => option === forcedCommand ? peerForcedCommand : option).join(",") + parsed.rest;
61
+ }
55
62
  if (!parsed || parsed.options[0] !== "restrict" || !/^\s+ssh-ed25519 [A-Za-z0-9+/=]+ phren-(?:iphone|android)\s*$/.test(parsed.rest))
56
63
  return line;
57
64
  const old = /^command="(?:\/usr\/bin\/false|python3 ~\/\.local\/share\/phren\/chat-progress\.py|sh ~\/\.local\/share\/phren\/bridge\/dispatch)"$/;
@@ -1,3 +1,4 @@
1
+ import { type CitationFreshness } from "../content/citation-freshness.js";
1
2
  import { type FindingItem } from "../data/access.js";
2
3
  export declare const PROJECT_MEMORY_ROUTE: RegExp;
3
4
  export declare const MEMORY_LIMITS: {
@@ -12,6 +13,7 @@ export interface MemoryFinding {
12
13
  type: string | null;
13
14
  status: FindingItem["status"];
14
15
  created: string | null;
16
+ citationFreshness?: CitationFreshness;
15
17
  citation: {
16
18
  file: string | null;
17
19
  line: number | null;
@@ -1,3 +1,4 @@
1
+ import { cachedCitationFreshness, refreshCitationFreshness } from "../content/citation-freshness.js";
1
2
  import * as fs from "node:fs";
2
3
  import * as path from "node:path";
3
4
  import { readFindings } from "../data/access.js";
@@ -24,7 +25,11 @@ const TAG = new RegExp(`^\\[(${FINDING_TAGS.join("|")})\\]\\s*`, "i");
24
25
  const DATE = /^\d{4}-\d{2}-\d{2}/;
25
26
  /** Text that trips phren's credential detector is withheld whole, never cut. */
26
27
  const safe = (text) => redactSecretsForLog(text);
27
- function finding(item) {
28
+ function freshnessOptions(root, project) {
29
+ return { phrenPath: root, projectRemote: getProjectRemote(root, project, readProjectConfig(root, project)) };
30
+ }
31
+ function finding(item, opts) {
32
+ const citationFreshness = item.citationData ? cachedCitationFreshness(item.citationData, opts) : undefined;
28
33
  const tag = TAG.exec(item.text);
29
34
  const cite = item.citationData;
30
35
  const citation = cite && (cite.file || cite.line || cite.commit || cite.symbol)
@@ -36,6 +41,7 @@ function finding(item) {
36
41
  text: safe(tag ? item.text.slice(tag[0].length) : item.text),
37
42
  type: tag ? tag[1].toLowerCase() : null,
38
43
  status: item.status, created, citation,
44
+ ...(citationFreshness ? { citationFreshness } : {}),
39
45
  };
40
46
  }
41
47
  function task(item) {
@@ -66,10 +72,14 @@ function locate(base, rawProject) {
66
72
  return { project, root, storeId };
67
73
  }
68
74
  /** Newest first, so a cap drops the oldest. Undated findings sort last. */
69
- function sortedFindings(root, project) {
75
+ function sortedFindings(root, project, opts) {
70
76
  const result = readFindings(root, project);
71
77
  if (!result.ok)
72
78
  throw new BridgeError(404, "Project not found.");
79
+ const citations = result.data.flatMap(item => item.citationData ? [item.citationData] : []);
80
+ // One batch per poll, after the response has been shaped. Refresh deduplicates overlapping polls.
81
+ if (citations.length)
82
+ setImmediate(() => { void refreshCitationFreshness(citations, { ...opts, budgetMs: 1500 }); });
73
83
  return result.data.map((item, index) => ({ item, index, date: DATE.test(item.date) ? item.date : "" }))
74
84
  .sort((a, b) => b.date.localeCompare(a.date) || a.index - b.index).map(entry => entry.item);
75
85
  }
@@ -79,7 +89,8 @@ function readTruths(root, project) {
79
89
  }
80
90
  export function projectMemory(base, rawProject) {
81
91
  const { project, root, storeId } = locate(base, rawProject);
82
- const allFindings = sortedFindings(root, project);
92
+ const opts = freshnessOptions(root, project);
93
+ const allFindings = sortedFindings(root, project, opts);
83
94
  const truths = readTruths(root, project).map(text => ({ text: safe(text) }));
84
95
  // Tasks are their own module; with it off the sections are empty.
85
96
  const taskDoc = readTasks(root, project);
@@ -87,8 +98,8 @@ export function projectMemory(base, rawProject) {
87
98
  const truncated = allFindings.length > MEMORY_LIMITS.findings || items.Active.length > MEMORY_LIMITS.active
88
99
  || items.Queue.length > MEMORY_LIMITS.queue || items.Done.length > MEMORY_LIMITS.done;
89
100
  return {
90
- project, store_id: storeId, remote: getProjectRemote(root, project, readProjectConfig(root, project)), truncated,
91
- findings: allFindings.slice(0, MEMORY_LIMITS.findings).map(finding),
101
+ project, store_id: storeId, remote: opts.projectRemote ?? null, truncated,
102
+ findings: allFindings.slice(0, MEMORY_LIMITS.findings).map(item => finding(item, opts)),
92
103
  truths,
93
104
  tasks: {
94
105
  active: items.Active.slice(0, MEMORY_LIMITS.active).map(task),
@@ -102,11 +113,12 @@ export function projectMemory(base, rawProject) {
102
113
  * type or variable the code index places in one of them. */
103
114
  export async function memoryForFiles(base, rawProject, paths) {
104
115
  const { project, root, storeId } = locate(base, rawProject);
116
+ const opts = freshnessOptions(root, project);
105
117
  if (paths.length < 1 || paths.length > MAX_FILE_PATHS || !paths.every(isRepoPath)) {
106
118
  throw new BridgeError(400, `Send 1 to ${MAX_FILE_PATHS} repository-relative paths.`);
107
119
  }
108
120
  const wanted = new Set(paths);
109
- const all = sortedFindings(root, project);
121
+ const all = sortedFindings(root, project, opts);
110
122
  const citedFile = (item) => item.citationData?.file?.replace(/^\.\//, "");
111
123
  const named = all.filter(item => item.citationData?.symbol && !wanted.has(citedFile(item) ?? ""));
112
124
  let symbols = "unavailable";
@@ -125,9 +137,9 @@ export async function memoryForFiles(base, rawProject, paths) {
125
137
  for (const item of all) {
126
138
  const file = citedFile(item), name = item.citationData?.symbol;
127
139
  if (file && wanted.has(file))
128
- matches.push({ ...finding(item), match: "file" });
140
+ matches.push({ ...finding(item, opts), match: "file" });
129
141
  else if (name && files[name] && wanted.has(files[name]))
130
- matches.push({ ...finding(item), match: "symbol" });
142
+ matches.push({ ...finding(item, opts), match: "symbol" });
131
143
  }
132
144
  return { project, store_id: storeId, symbols, truncated: matches.length > MEMORY_LIMITS.findings,
133
145
  findings: matches.slice(0, MEMORY_LIMITS.findings) };
@@ -142,12 +154,13 @@ export async function memoryForFiles(base, rawProject, paths) {
142
154
  */
143
155
  export function memorySearch(base, rawProject, q, limit) {
144
156
  const { project, root } = locate(base, rawProject);
157
+ const opts = freshnessOptions(root, project);
145
158
  if (!isSearchText(q))
146
159
  throw new BridgeError(400, "q must be 1 to 1000 characters of text.");
147
160
  if (!Number.isInteger(limit) || limit < 1 || limit > MAX_SEARCH_LIMIT)
148
161
  throw new BridgeError(400, `limit must be 1 to ${MAX_SEARCH_LIMIT}.`);
149
162
  const entries = [
150
- ...sortedFindings(root, project).map(item => ({ kind: "finding", text: item.text, item })),
163
+ ...sortedFindings(root, project, opts).map(item => ({ kind: "finding", text: item.text, item })),
151
164
  ...readTruths(root, project).map(text => ({ kind: "truth", text, item: undefined })),
152
165
  ];
153
166
  const tokens = tokenizeForOverlap(q, 64);
@@ -170,7 +183,7 @@ export function memorySearch(base, rawProject, q, limit) {
170
183
  continue;
171
184
  const inactive = entry.item && entry.item.status !== "active";
172
185
  const score = Math.round((best.rarity / weight) * (inactive ? 0.5 : 1) * 1000) / 1000;
173
- const shaped = entry.item ? finding(entry.item) : null;
186
+ const shaped = entry.item ? finding(entry.item, opts) : null;
174
187
  hits.push({ kind: entry.kind, score, matched: best.distinct, text: shaped ? shaped.text : safe(entry.text), finding: shaped });
175
188
  }
176
189
  hits.sort((a, b) => b.score - a.score || b.matched - a.matched);
@@ -209,7 +222,8 @@ let writes = Promise.resolve();
209
222
  * project's write permission, duplicate and conflict checks, the secret
210
223
  * scan and citation validation against the code index. */
211
224
  export async function saveFinding(base, rawProject, input) {
212
- const { project } = locate(base, rawProject);
225
+ const { project, root } = locate(base, rawProject);
226
+ const opts = freshnessOptions(root, project);
213
227
  if (Buffer.byteLength(JSON.stringify(input ?? null)) > MAX_FINDING_BODY)
214
228
  throw new BridgeError(413, `The body must be at most ${MAX_FINDING_BODY} bytes.`);
215
229
  const body = findingWriteSchema.parse(input);
@@ -229,9 +243,9 @@ export async function saveFinding(base, rawProject, input) {
229
243
  throw new BridgeError(/permission|denied|not allowed/i.test(error) ? 403 : 400, safe(error));
230
244
  }
231
245
  const status = result.data?.status === "skipped" ? "duplicate" : "saved";
232
- const saved = status === "saved" ? sortedFindings(locate(base, rawProject).root, project)
246
+ const saved = status === "saved" ? sortedFindings(root, project, opts)
233
247
  .find(item => item.text === (result.data?.finding ?? "").replace(/^-\s+/, "").trim()) : undefined;
234
- return { project, status, finding: saved ? finding(saved) : null };
248
+ return { project, status, finding: saved ? finding(saved, opts) : null };
235
249
  }
236
250
  // ── POST /tasks/complete ─────────────────────────────────────────────────────
237
251
  /** Mark one open task done, by the stable id `/tasks?branch=` gave gitboy when