@phren/cli 0.3.30 → 0.3.32

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 (81) hide show
  1. package/dist/bridge/agent-hooks.d.ts +5 -55
  2. package/dist/bridge/agent-hooks.js +45 -162
  3. package/dist/bridge/approval-rules.d.ts +70 -0
  4. package/dist/bridge/approval-rules.js +231 -0
  5. package/dist/bridge/authority.d.ts +1 -2
  6. package/dist/bridge/authority.js +2 -7
  7. package/dist/bridge/changes.d.ts +4 -0
  8. package/dist/bridge/changes.js +47 -33
  9. package/dist/bridge/claude-suggestion.js +1 -1
  10. package/dist/bridge/codex-servers.d.ts +12 -0
  11. package/dist/bridge/codex-servers.js +35 -3
  12. package/dist/bridge/codex-thread-origin.d.ts +12 -0
  13. package/dist/bridge/codex-thread-origin.js +31 -0
  14. package/dist/bridge/dispatch.js +1 -1
  15. package/dist/bridge/enroll.d.ts +6 -0
  16. package/dist/bridge/enroll.js +10 -4
  17. package/dist/bridge/git-worktrees.js +14 -17
  18. package/dist/bridge/git.d.ts +10 -2
  19. package/dist/bridge/git.js +148 -107
  20. package/dist/bridge/hand-off-queue.d.ts +10 -0
  21. package/dist/bridge/hand-off-queue.js +33 -10
  22. package/dist/bridge/health.js +9 -5
  23. package/dist/bridge/herdr.js +6 -1
  24. package/dist/bridge/hook-main.js +12 -2
  25. package/dist/bridge/locate.js +14 -1
  26. package/dist/bridge/projects.d.ts +8 -0
  27. package/dist/bridge/projects.js +142 -24
  28. package/dist/bridge/prompt-deliveries.d.ts +99 -0
  29. package/dist/bridge/prompt-deliveries.js +327 -0
  30. package/dist/bridge/prompt-once.d.ts +2 -0
  31. package/dist/bridge/prompt-once.js +2 -0
  32. package/dist/bridge/schedule-format.d.ts +10 -0
  33. package/dist/bridge/schedule-format.js +24 -1
  34. package/dist/bridge/schedules.d.ts +3 -1
  35. package/dist/bridge/schedules.js +96 -40
  36. package/dist/bridge/server-launch.js +39 -15
  37. package/dist/bridge/server-pane-routes.js +91 -45
  38. package/dist/bridge/server-routes.d.ts +3 -0
  39. package/dist/bridge/server-routes.js +36 -8
  40. package/dist/bridge/server-stream.js +4 -2
  41. package/dist/bridge/server.js +12 -3
  42. package/dist/bridge/speech-key.d.ts +2 -9
  43. package/dist/bridge/speech-key.js +4 -37
  44. package/dist/bridge/sudo.d.ts +1 -1
  45. package/dist/bridge/sudo.js +51 -17
  46. package/dist/bridge/terminal-tmux.js +22 -4
  47. package/dist/bridge/tmux-test-server.d.ts +13 -0
  48. package/dist/bridge/tmux-test-server.js +103 -0
  49. package/dist/bridge/transcript-claude.d.ts +3 -3
  50. package/dist/bridge/transcript-claude.js +7 -7
  51. package/dist/bridge/transcript-codex.js +6 -4
  52. package/dist/bridge/transcript-preview.js +1 -1
  53. package/dist/bridge/transcripts.js +14 -3
  54. package/dist/bridge-hook.mjs +16011 -14121
  55. package/dist/cli/schedules.js +8 -2
  56. package/dist/cli/session-stop.js +9 -1
  57. package/dist/cli-registry.js +1 -1
  58. package/dist/core/project-registry.d.ts +1 -0
  59. package/dist/core/project-registry.js +6 -2
  60. package/dist/core/project.d.ts +1 -0
  61. package/dist/core/project.js +5 -0
  62. package/dist/generated/memory-ui-graph.browser.js +328 -333
  63. package/dist/init/setup.js +2 -2
  64. package/dist/memory-ui-graph.runtime.js +328 -333
  65. package/dist/modules/registry.js +9 -7
  66. package/dist/phren-core.js +1 -1
  67. package/dist/phren-paths.d.ts +2 -2
  68. package/dist/phren-paths.js +2 -2
  69. package/dist/store-routing.d.ts +2 -2
  70. package/dist/store-routing.js +2 -2
  71. package/dist/sync/git-state.d.ts +13 -0
  72. package/dist/sync/git-state.js +22 -0
  73. package/dist/sync/store-merge.d.ts +2 -0
  74. package/dist/sync/store-merge.js +6 -1
  75. package/dist/test-global-setup.js +7 -0
  76. package/dist/tools/data.js +1 -1
  77. package/dist/tools/finding.js +1 -1
  78. package/dist/tools/search.js +1 -1
  79. package/dist/tools/tasks.js +1 -1
  80. package/package.json +8 -8
  81. package/starter/global/skills/conductor/SKILL.md +2 -2
@@ -0,0 +1,231 @@
1
+ import { execFile } from "node:child_process";
2
+ import { promisify } from "node:util";
3
+ import { nonInteractiveGitEnv } from "../utils-helpers.js";
4
+ import { createHash, createPublicKey, verify } from "node:crypto";
5
+ import { lstat, mkdir, readFile, realpath } from "node:fs/promises";
6
+ import { hostname } from "node:os";
7
+ import path from "node:path";
8
+ import { z } from "zod";
9
+ import { homeDir } from "../home-paths.js";
10
+ import { tryFileLock } from "../governance/locks.js";
11
+ import { atomic, BridgeError, bridgeRoot, object } from "./protocol.js";
12
+ const exec = promisify(execFile);
13
+ // Each context needs at most two reads; slow Git falls back to ordinary approval.
14
+ async function git(cwd, ...args) {
15
+ return (await exec("git", ["-C", cwd, "--no-pager", ...args], {
16
+ timeout: 150, maxBuffer: 4_194_304,
17
+ env: nonInteractiveGitEnv({ ...process.env, GIT_OPTIONAL_LOCKS: "0", GIT_CONFIG_NOSYSTEM: "1" }),
18
+ })).stdout;
19
+ }
20
+ const text = z.string().min(1).max(4096).refine(value => !/[\x00-\x1f\x7f]/.test(value));
21
+ const scopeSchema = z.object({
22
+ project: text.refine(value => path.isAbsolute(value) && path.normalize(value) === value),
23
+ harness: z.enum(["claude", "codex", "copilot", "opencode", "phren"]).optional(),
24
+ session: text.optional(), computer: text.optional(),
25
+ }).strict();
26
+ export const approvalRuleDraftSchema = z.object({
27
+ tool: z.literal("Bash"), command: text, match: z.enum(["exact", "prefix", "glob"]),
28
+ effect: z.enum(["always-ask", "deny"]), scope: scopeSchema,
29
+ projectName: z.string().min(1).max(100), until: z.string().datetime({ offset: true }).optional(),
30
+ }).strict();
31
+ const operationSchema = z.discriminatedUnion("operation", [
32
+ z.object({ domain: z.literal("phren-approval-rules-v1"), operation: z.literal("add"), nonce: z.string().uuid(), at: z.string().datetime({ offset: true }), rule: approvalRuleDraftSchema }).strict(),
33
+ z.object({ domain: z.literal("phren-approval-rules-v1"), operation: z.literal("set-enabled"), nonce: z.string().uuid(), at: z.string().datetime({ offset: true }), id: z.string().uuid(), enabled: z.boolean() }).strict(),
34
+ z.object({ domain: z.literal("phren-approval-rules-v1"), operation: z.literal("revoke"), nonce: z.string().uuid(), at: z.string().datetime({ offset: true }), id: z.string().uuid() }).strict(),
35
+ ]);
36
+ const envelopeSchema = z.object({ payload: z.string().min(1).max(16384), signature: z.string().min(1).max(128), publicKey: z.string().min(1).max(64) }).strict();
37
+ const policySchema = z.object({ operations: z.array(envelopeSchema).max(2048) }).strict();
38
+ const policyPath = (root) => path.join(root, "approval-rules.json");
39
+ const forbidden = () => new BridgeError(403, "Confirm this change with the paired iPhone's signing key.");
40
+ /** Restricted phone keys only; dispatch keys and arbitrary SSH keys cannot sign policy. */
41
+ async function ownerKeys() {
42
+ const keys = await readFile(path.join(homeDir(), ".ssh", "authorized_keys"), "utf8");
43
+ const result = new Set();
44
+ for (const line of keys.split("\n")) {
45
+ const match = /^restrict,pty,command="sh ~\/\.local\/share\/phren\/bridge\/dispatch" ssh-ed25519 ([A-Za-z0-9+/]+={0,2}) phren-iphone\s*$/.exec(line);
46
+ if (!match)
47
+ continue;
48
+ const wire = Buffer.from(match[1], "base64");
49
+ // SSH string("ssh-ed25519"), string(32-byte key).
50
+ if (wire.length === 51 && wire.readUInt32BE(0) === 11 && wire.subarray(4, 15).toString() === "ssh-ed25519" && wire.readUInt32BE(15) === 32)
51
+ result.add(wire.subarray(19).toString("base64"));
52
+ }
53
+ return result;
54
+ }
55
+ function verified(envelope, keys) {
56
+ const raw = Buffer.from(envelope.publicKey, "base64"), signature = Buffer.from(envelope.signature, "base64"), payload = Buffer.from(envelope.payload, "base64");
57
+ if (raw.length !== 32 || signature.length !== 64 || !keys.has(raw.toString("base64")))
58
+ throw forbidden();
59
+ const key = createPublicKey({ key: Buffer.concat([Buffer.from("302a300506032b6570032100", "hex"), raw]), format: "der", type: "spki" });
60
+ if (!verify(null, payload, key, signature))
61
+ throw forbidden();
62
+ const operation = operationSchema.parse(JSON.parse(payload.toString("utf8")));
63
+ return { operation, owner: createHash("sha256").update(raw).digest("hex") };
64
+ }
65
+ async function privateJSON(file, fallback, max = 2_097_152) {
66
+ const info = await lstat(file).catch(error => { if (error.code === "ENOENT")
67
+ return undefined; throw error; });
68
+ if (!info)
69
+ return fallback;
70
+ if (!info.isFile() || info.isSymbolicLink() || (info.mode & 0o077) || info.size > max)
71
+ throw new BridgeError(409, "Approval policy must be a private regular file.");
72
+ return JSON.parse(await readFile(file, "utf8"));
73
+ }
74
+ async function readPolicy(root) {
75
+ const policy = policySchema.parse(await privateJSON(policyPath(root), { operations: [] }));
76
+ const keys = policy.operations.length ? await ownerKeys() : new Set();
77
+ const rules = new Map(), nonces = new Set();
78
+ for (const envelope of policy.operations) {
79
+ const { operation, owner } = verified(envelope, keys);
80
+ if (nonces.has(operation.nonce))
81
+ throw new BridgeError(409, "Repeated policy operation.");
82
+ nonces.add(operation.nonce);
83
+ if (operation.operation === "add")
84
+ rules.set(operation.nonce, { ...operation.rule, id: operation.nonce, createdAt: operation.at, owner, enabled: true });
85
+ else if (operation.operation === "revoke")
86
+ rules.delete(operation.id);
87
+ else {
88
+ const rule = rules.get(operation.id);
89
+ if (rule)
90
+ rule.enabled = operation.enabled;
91
+ }
92
+ }
93
+ return { policy, rules, nonces };
94
+ }
95
+ const queues = new Map();
96
+ async function locked(root, work) {
97
+ const key = path.resolve(root), previous = queues.get(key) ?? Promise.resolve();
98
+ const next = previous.catch(() => { }).then(async () => {
99
+ await mkdir(key, { recursive: true, mode: 0o700 });
100
+ const release = tryFileLock(policyPath(key));
101
+ if (!release)
102
+ throw new BridgeError(409, "Approval rules are busy. Try again.");
103
+ try {
104
+ return await work();
105
+ }
106
+ finally {
107
+ release();
108
+ }
109
+ });
110
+ queues.set(key, next);
111
+ try {
112
+ return await next;
113
+ }
114
+ finally {
115
+ if (queues.get(key) === next)
116
+ queues.delete(key);
117
+ }
118
+ }
119
+ export async function listApprovalRules(root = bridgeRoot(), pairedKey) {
120
+ try {
121
+ const pairedOwner = pairedKey ? createHash("sha256").update(Buffer.from(pairedKey, "base64")).digest("hex") : undefined;
122
+ return [...(await readPolicy(root)).rules.values()].map(rule => ({ ...rule,
123
+ signerFingerprint: "SHA256:" + Buffer.from(rule.owner, "hex").toString("base64").replace(/=+$/, ""),
124
+ matchesPairedKey: rule.owner === pairedOwner,
125
+ }));
126
+ }
127
+ catch {
128
+ throw new BridgeError(409, "Approval rules could not be loaded. Existing agent permissions and phone approvals continue unchanged.");
129
+ }
130
+ }
131
+ /** The signed operations remain on disk and are verified again at every decision. */
132
+ export async function changeApprovalRule(input, method, root = bridgeRoot()) {
133
+ const envelope = envelopeSchema.parse(input), proof = verified(envelope, await ownerKeys());
134
+ if ((method === "DELETE" ? proof.operation.operation !== "revoke" : proof.operation.operation === "revoke") || !Number.isFinite(Date.parse(proof.operation.at)) || Math.abs(Date.now() - Date.parse(proof.operation.at)) > 300_000)
135
+ throw forbidden();
136
+ return locked(root, async () => {
137
+ const { policy, rules, nonces } = await readPolicy(root);
138
+ if (nonces.has(proof.operation.nonce))
139
+ throw new BridgeError(409, "This change has already been applied.");
140
+ if (proof.operation.operation === "add" && rules.size >= 128)
141
+ throw new BridgeError(409, "Revoke a rule before adding another.");
142
+ if (proof.operation.operation !== "add" && !rules.has(proof.operation.id))
143
+ throw new BridgeError(409, "This rule is no longer listed.");
144
+ if (policy.operations.length >= 2048)
145
+ throw new BridgeError(409, "Approval policy history is full; owner maintenance is required.");
146
+ policy.operations.push(envelope);
147
+ const bytes = JSON.stringify(policy);
148
+ if (Buffer.byteLength(bytes) > 2_097_152)
149
+ throw new BridgeError(409, "Approval policy history is full; owner maintenance is required.");
150
+ await atomic(policyPath(root), bytes);
151
+ return { ok: true };
152
+ });
153
+ }
154
+ /** Bind project scope to the main repository, including linked worktrees. */
155
+ export async function approvalRuleContext(cwd, harness, session) {
156
+ if (!path.isAbsolute(cwd))
157
+ return undefined;
158
+ try {
159
+ const directories = (await git(cwd, "rev-parse", "--path-format=absolute", "--git-common-dir", "--show-toplevel")).trim().split(/\r?\n/);
160
+ if (directories.length !== 2)
161
+ return undefined;
162
+ const [common, checkout, directory] = await Promise.all([...directories, cwd].map(value => realpath(value)));
163
+ const relative = path.relative(checkout, directory);
164
+ if (relative === ".." || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative))
165
+ return undefined;
166
+ if (path.basename(common) !== ".git")
167
+ return undefined;
168
+ // A writable .git pointer alone is not proof that a folder belongs to this repository.
169
+ const listed = (await git(common, "worktree", "list", "--porcelain", "-z")).split("\0")
170
+ .filter(field => field.startsWith("worktree ")).map(field => field.slice("worktree ".length));
171
+ const registered = await Promise.all(listed.map(directory => realpath(directory).catch(() => undefined)));
172
+ if (!registered.includes(checkout))
173
+ return undefined;
174
+ return { project: path.dirname(common), harness: scopeSchema.shape.harness.unwrap().parse(harness), session, computer: hostname() };
175
+ }
176
+ catch {
177
+ return undefined;
178
+ }
179
+ }
180
+ function commandMatches(rule, command) {
181
+ if (rule.match === "exact")
182
+ return command === rule.command;
183
+ if (rule.match === "prefix")
184
+ return command === rule.command || command.startsWith(rule.command + " ");
185
+ // Bound pattern/command sizes avoid unbounded glob backtracking.
186
+ let i = 0, j = 0, star = -1, retry = 0;
187
+ while (j < command.length) {
188
+ if (i < rule.command.length && (rule.command[i] === "?" || rule.command[i] === command[j])) {
189
+ i++;
190
+ j++;
191
+ }
192
+ else if (rule.command[i] === "*") {
193
+ star = i++;
194
+ retry = j;
195
+ }
196
+ else if (star !== -1) {
197
+ i = star + 1;
198
+ j = ++retry;
199
+ }
200
+ else
201
+ return false;
202
+ }
203
+ while (rule.command[i] === "*")
204
+ i++;
205
+ return i === rule.command.length;
206
+ }
207
+ /** Rules can only restrict a request the harness has already raised. Invalid policy
208
+ * falls back to that ordinary approval path; Settings reports the load error. */
209
+ export async function approvalRuleEffect(tool, input, context, root = bridgeRoot(), knownScope = {}) {
210
+ const command = object(input).command;
211
+ if (tool !== "Bash" || typeof command !== "string")
212
+ return undefined;
213
+ try {
214
+ const { rules } = await readPolicy(root), now = Date.now();
215
+ const applicable = [...rules.values()].filter(rule => rule.enabled && rule.tool === tool && (!rule.until || Date.parse(rule.until) > now)
216
+ && Object.entries(knownScope).every(([key, value]) => !rule.scope[key] || rule.scope[key] === value)
217
+ && commandMatches(rule, command));
218
+ if (!applicable.length)
219
+ return undefined;
220
+ const resolved = typeof context === "function" ? await context() : context;
221
+ if (!resolved)
222
+ return undefined;
223
+ const matches = applicable.filter(rule => Object.entries(rule.scope).every(([key, value]) => resolved[key] === value));
224
+ if (matches.some(rule => rule.effect === "deny"))
225
+ return "deny";
226
+ return matches.some(rule => rule.effect === "always-ask") ? "always-ask" : undefined;
227
+ }
228
+ catch {
229
+ return undefined;
230
+ }
231
+ }
@@ -99,8 +99,7 @@ declare const fileSchema: z.ZodObject<{
99
99
  }>>;
100
100
  }, z.core.$strict>;
101
101
  export type AuthorityFile = z.infer<typeof fileSchema>;
102
- /** Used until the owner first writes the policy: hub and safety are ask-first,
103
- * and Mina is go for App Store work (the owner's word, 2026-09-29). */
102
+ /** Used until the owner first writes the policy: no project is restricted. */
104
103
  export declare const DEFAULT_AUTHORITY: AuthorityFile;
105
104
  /** The permission ceiling of a project with any ask-first action that names none. */
106
105
  export declare const ASK_FIRST_PERMISSION_MODE: PermissionMode;
@@ -31,13 +31,8 @@ const fileSchema = z.object({
31
31
  updatedAt: z.string().datetime({ offset: true }).optional(),
32
32
  updatedBy: writer.optional(),
33
33
  }).strict();
34
- /** Used until the owner first writes the policy: hub and safety are ask-first,
35
- * and Mina is go for App Store work (the owner's word, 2026-09-29). */
36
- export const DEFAULT_AUTHORITY = { projects: {
37
- hub: { default: "ask" },
38
- safety: { default: "ask" },
39
- mina: { actions: { "app-store": "go" }, note: "Owner authorized App Store work on 2026-09-29." },
40
- } };
34
+ /** Used until the owner first writes the policy: no project is restricted. */
35
+ export const DEFAULT_AUTHORITY = { projects: {} };
41
36
  /** The permission ceiling of a project with any ask-first action that names none. */
42
37
  export const ASK_FIRST_PERMISSION_MODE = "auto-edits";
43
38
  const authorityFile = (root = bridgeRoot()) => path.join(root, "authority.yaml");
@@ -11,6 +11,8 @@ export declare const changedFileSchema: z.ZodObject<{
11
11
  added: z.ZodNumber;
12
12
  removed: z.ZodNumber;
13
13
  redacted: z.ZodOptional<z.ZodBoolean>;
14
+ binary: z.ZodOptional<z.ZodBoolean>;
15
+ truncated: z.ZodOptional<z.ZodBoolean>;
14
16
  }, z.core.$strip>;
15
17
  export type ChangedFile = z.infer<typeof changedFileSchema>;
16
18
  export declare const secretName: (file: string) => boolean;
@@ -33,6 +35,8 @@ export declare class ToolChanges {
33
35
  private results;
34
36
  private controllers;
35
37
  private claims;
38
+ private failures;
39
+ private failed;
36
40
  /** A hook callback's wall-clock cap on Git work; past it the call records
37
41
  * no change. Tests about what is captured raise it, since a loaded Windows
38
42
  * runner's Git can take longer than a person's machine ever does. */
@@ -1,10 +1,10 @@
1
- import { nonInteractiveGitEnv } from "../utils-helpers.js";
1
+ import { checkoutGitEnv } from "./projects.js";
2
2
  import { execFile } from "node:child_process";
3
3
  import { appendFile, copyFile, mkdir, mkdtemp, readdir, readFile, realpath, rm, stat, unlink, utimes } from "node:fs/promises";
4
4
  import { homeDir } from "../home-paths.js";
5
5
  import path from "node:path";
6
6
  import { promisify } from "node:util";
7
- import { bridgeRoot, object } from "./protocol.js";
7
+ import { BridgeError, bridgeRoot, object } from "./protocol.js";
8
8
  import { z } from "zod";
9
9
  import { ProcessPool } from "./limits.js";
10
10
  import { phrenStoreRoot } from "./transcripts.js";
@@ -14,7 +14,7 @@ const exec = promisify(execFile);
14
14
  * tree before the call and after it. `root` is the repository; `path` is
15
15
  * relative to it. */
16
16
  export const changedFileSchema = z.object({ root: z.string(), path: z.string(), status: z.string(), patch: z.string(),
17
- added: z.number().int().nonnegative(), removed: z.number().int().nonnegative(), redacted: z.boolean().optional() });
17
+ added: z.number().int().nonnegative(), removed: z.number().int().nonnegative(), redacted: z.boolean().optional(), binary: z.boolean().optional(), truncated: z.boolean().optional() });
18
18
  const changeRowSchema = z.object({ toolUseId: z.string(), files: z.array(changedFileSchema) });
19
19
  export const secretName = (file) => /^(?:\.env(?:\..*)?|.*\.(?:pem|key|p12|pfx|keychain-db|tfstate)|id_rsa.*|id_ed25519.*|(?:.*\.)?credentials\.json|\.netrc|\.npmrc|\.pypirc)$/i.test(path.basename(file));
20
20
  const gitPool = new ProcessPool(2);
@@ -52,7 +52,7 @@ export function namedPaths(command, input = {}) {
52
52
  }
53
53
  async function git(cwd, args, extra = {}, signal) {
54
54
  return gitPool.run(signal, async () => (countGit("changes"), await exec("git", ["-C", cwd, "--no-pager", ...args], {
55
- signal, timeout: 10_000, maxBuffer: 8_388_608, env: nonInteractiveGitEnv({ ...process.env, GIT_OPTIONAL_LOCKS: "0", GIT_CONFIG_NOSYSTEM: "1", ...extra }),
55
+ signal, timeout: 10_000, maxBuffer: 8_388_608, env: { ...checkoutGitEnv(), ...extra },
56
56
  })).stdout);
57
57
  }
58
58
  /** The repository holding `target` (a file, a folder, or something not yet
@@ -72,10 +72,12 @@ async function repositoryOf(target, cwd, home = homeDir(), signal) {
72
72
  return undefined;
73
73
  const dir = (await stat(real)).isDirectory() ? real : path.dirname(real);
74
74
  try {
75
- return await realpath((await git(dir, ["rev-parse", "--show-toplevel"], {}, signal)).trim());
75
+ return await realpath((await git(dir, ["rev-parse", "--show-toplevel"], {}, signal)).replace(/\r?\n$/, ""));
76
76
  }
77
- catch {
78
- return undefined;
77
+ catch (error) {
78
+ if (/not a git repository/.test(String(error.stderr)))
79
+ return undefined;
80
+ throw error;
79
81
  }
80
82
  }
81
83
  async function scratchTree(root, signal) {
@@ -99,10 +101,11 @@ async function treeHash(root, env, signal) {
99
101
  const index = path.resolve(root, (await git(root, ["rev-parse", "--git-path", "index"], {}, signal)).trim());
100
102
  const temp = env.GIT_INDEX_FILE;
101
103
  await unlink(temp).catch(() => undefined);
102
- await copyFile(index, temp).catch(() => undefined);
104
+ await copyFile(index, temp).catch(error => { if (error.code !== "ENOENT")
105
+ throw error; });
103
106
  // Force content checks for files rewritten to the same size in one instant.
104
107
  await utimes(temp, 1, 1).catch(() => undefined);
105
- await git(root, ["add", "-A", "--ignore-errors", "--", "."], env, signal);
108
+ await git(root, ["add", "-A", "--", "."], env, signal);
106
109
  return (await git(root, ["write-tree"], env, signal)).trim();
107
110
  }
108
111
  const NO_DIFF = ["diff", "--no-ext-diff", "--no-textconv", "--no-color"];
@@ -111,21 +114,25 @@ async function treeDiff(root, before, after, env, signal) {
111
114
  return [];
112
115
  const records = (await git(root, [...NO_DIFF, "--name-status", "-z", before, after], env, signal)).split("\0");
113
116
  const files = [];
114
- for (let i = 0; i + 1 < records.length && files.length < 40; i += 2) {
117
+ for (let i = 0; i + 1 < records.length; i += 2) {
115
118
  const status = records[i].slice(0, 1), original = records[i + 1];
116
119
  let file = original;
117
120
  if (/[RC]/.test(status))
118
121
  file = records[++i + 1]; // the new name follows the old
119
122
  if (!file)
120
123
  continue;
121
- const spec = `:(literal)${file}`;
122
- const counts = (await git(root, [...NO_DIFF, "--numstat", before, after, "--", spec], env, signal)).split("\t");
123
- const redacted = secretName(original) || secretName(file) || counts[0] === "-" || counts[1] === "-";
124
- let patch = redacted ? "" : await git(root, [...NO_DIFF, before, after, "--", spec], env, signal);
125
- if (patch.length > 200_000)
124
+ if (files.length >= 40)
125
+ throw new BridgeError(413, "This tool changed more than 40 files; open repository Changes for the full status.", { code: "git-output-limit" });
126
+ const specs = [...new Set([original, file])].map(name => `:(literal)${name}`);
127
+ const counts = (await git(root, [...NO_DIFF, "--numstat", before, after, "--", ...specs], env, signal)).split("\t");
128
+ const binary = counts[0] === "-" || counts[1] === "-";
129
+ const redacted = secretName(original) || secretName(file) || binary;
130
+ let patch = redacted ? "" : await git(root, [...NO_DIFF, before, after, "--", ...specs], env, signal);
131
+ const truncated = patch.length > 200_000;
132
+ if (truncated)
126
133
  patch = patch.slice(0, 200_000) + "\n… (truncated)\n";
127
134
  const added = Number(counts[0]) || 0, removed = Number(counts[1]) || 0;
128
- files.push({ root, path: file, status, patch, added, removed, ...(redacted ? { redacted: true } : {}) });
135
+ files.push({ root, path: file, status, patch, added, removed, binary, truncated, ...(redacted ? { redacted: true } : {}) });
129
136
  }
130
137
  return files;
131
138
  }
@@ -192,6 +199,14 @@ export class ToolChanges {
192
199
  results = new Map();
193
200
  controllers = new Set();
194
201
  claims = [];
202
+ failures = new Map();
203
+ failed(key, error) {
204
+ const failure = error instanceof BridgeError ? error : new BridgeError(503, "Git change capture failed or timed out. Refresh repository Changes for the current status.", { code: "git-capture-failed" });
205
+ if (this.failures.size >= 512)
206
+ this.failures.delete(this.failures.keys().next().value);
207
+ this.failures.set(key, failure);
208
+ return failure;
209
+ }
195
210
  /** A hook callback's wall-clock cap on Git work; past it the call records
196
211
  * no change. Tests about what is captured raise it, since a loaded Windows
197
212
  * runner's Git can take longer than a person's machine ever does. */
@@ -236,6 +251,7 @@ export class ToolChanges {
236
251
  this.snapshots.set(key, snapshot);
237
252
  try {
238
253
  await this.budget(async (signal) => {
254
+ await realpath(cwd); // A vanished checkout must not resolve to its parent repository.
239
255
  const roots = new Set();
240
256
  for (const target of [cwd, phrenStoreRoot(), ...namedPaths(command, input)]) {
241
257
  signal.throwIfAborted();
@@ -246,12 +262,7 @@ export class ToolChanges {
246
262
  roots.add(root);
247
263
  }
248
264
  for (const root of roots) {
249
- try {
250
- snapshot.trees.set(root, await scratchTree(root, signal));
251
- }
252
- catch {
253
- signal.throwIfAborted();
254
- }
265
+ snapshot.trees.set(root, await scratchTree(root, signal));
255
266
  }
256
267
  signal.throwIfAborted();
257
268
  });
@@ -273,7 +284,8 @@ export class ToolChanges {
273
284
  }, 30 * 60_000);
274
285
  snapshot.expiry.unref();
275
286
  }
276
- catch {
287
+ catch (error) {
288
+ this.failed(key, error);
277
289
  if (this.snapshots.get(key) === snapshot)
278
290
  this.snapshots.delete(key);
279
291
  await this.discard(snapshot);
@@ -315,7 +327,14 @@ export class ToolChanges {
315
327
  return;
316
328
  }
317
329
  snapshot.result ??= this.compute(snapshot);
318
- const files = await snapshot.result;
330
+ let files;
331
+ try {
332
+ files = await snapshot.result;
333
+ }
334
+ catch (error) {
335
+ this.snapshots.delete(key);
336
+ throw this.failed(key, error);
337
+ }
319
338
  if (this.snapshots.get(key) === snapshot) {
320
339
  this.snapshots.delete(key);
321
340
  await this.record(conversation, toolUseId, files);
@@ -326,12 +345,7 @@ export class ToolChanges {
326
345
  return await this.budget(async (signal) => {
327
346
  const files = [];
328
347
  for (const [root, before] of snapshot.trees) {
329
- try {
330
- files.push(...await treeDiff(root, before.hash, await treeHash(root, before.env, signal), before.env, signal));
331
- }
332
- catch {
333
- signal.throwIfAborted();
334
- }
348
+ files.push(...await treeDiff(root, before.hash, await treeHash(root, before.env, signal), before.env, signal));
335
349
  }
336
350
  // A file another agent's edit named during this call is its change,
337
351
  // not this call's, even though it landed inside the same window.
@@ -349,9 +363,6 @@ export class ToolChanges {
349
363
  return kept;
350
364
  });
351
365
  }
352
- catch {
353
- return [];
354
- }
355
366
  finally {
356
367
  await this.discard(snapshot);
357
368
  }
@@ -407,6 +418,9 @@ export class ToolChanges {
407
418
  return !!snapshot && !snapshot.result && Date.now() - snapshot.at < PENDING_FOR;
408
419
  },
409
420
  changes: async (toolUseId) => {
421
+ const failure = this.failures.get(`${conversation}\0${toolUseId}`);
422
+ if (failure)
423
+ throw failure;
410
424
  await this.after(conversation, toolUseId);
411
425
  const known = (await this.load(conversation)).files.get(toolUseId);
412
426
  return known?.length ? known : undefined;
@@ -7,7 +7,7 @@
7
7
  import { stripTerminal } from "../terminal-text.js";
8
8
  const MAX_SUGGESTION = 500;
9
9
  // The input box sits between two rules; the upper one can carry the session
10
- // title ("───── Claude sesh ─").
10
+ // title ("───── Docs refresh ─").
11
11
  const rule = (line) => /^[─━═]{3,}/.test(line.trim());
12
12
  // Dim text Claude also draws in the empty input that is not a prediction: the
13
13
  // first-turn example, the queued-message hints and a teammate's name.
@@ -54,6 +54,8 @@ export type CodexNextTurn = NonNullable<CodexServerEntry["nextTurn"]>;
54
54
  export interface CodexApprovalSink {
55
55
  request(target: Target, request: PendingServerRequest, answer: (result: Json) => void): void;
56
56
  resolved(target: Target, requestId: AppServerRequestId): void;
57
+ /** The pane moved to another thread; input still pending on `previous` will not show there. */
58
+ threadChanged?(previous: Target): void;
57
59
  }
58
60
  export interface CodexServerDeps {
59
61
  spawn: typeof spawnAppServer;
@@ -158,6 +160,16 @@ export declare class CodexServers {
158
160
  prompt(entry: CodexServerEntry, text: string): Promise<{
159
161
  turnId: string;
160
162
  }>;
163
+ /** A phone message, sent as the pane's TUI sends Enter: steered into the
164
+ * running turn, else a new turn. Either way Codex holds it as input until
165
+ * the model's next step takes it (after the tool call that is running, which
166
+ * can be long), and only then runs UserPromptSubmit; on Codex 0.160 a
167
+ * `turn/start` during a turn is merged into it the same way. So the turn id
168
+ * acknowledges the hand-over, not the delivery. A held model change starts
169
+ * a turn, which carries it. */
170
+ send(entry: CodexServerEntry, text: string): Promise<{
171
+ turnId: string;
172
+ }>;
161
173
  /** `thread/name/set` on the pane's thread: Codex's own rename, which its TUI
162
174
  * shows and `session_index.jsonl` keeps. Allowed while a turn runs. */
163
175
  renameThread(entry: CodexServerEntry, name: string): Promise<void>;
@@ -226,8 +226,11 @@ export class CodexServers {
226
226
  await this.save(entry);
227
227
  this.live.set(serverId, live);
228
228
  this.lost.delete(paneKey(place.server, place.pane));
229
- const args = entry.threadId ? ["resume", entry.threadId, "--remote", `unix://${socket}`]
230
- : ["--remote", `unix://${socket}`, ...(options.model ? ["--model", options.model] : []), ...(options.effort ? ["-c", `model_reasoning_effort=${options.effort}`] : []), ...(options.remoteArgs ?? [])];
229
+ // The resumed TUI carries the model too: without it a /new in the pane
230
+ // fell back to config.toml's default, not the model this pane was given.
231
+ const model = [...(options.model ? ["--model", options.model] : []), ...(options.effort ? ["-c", `model_reasoning_effort=${options.effort}`] : [])];
232
+ const args = entry.threadId ? ["resume", entry.threadId, "--remote", `unix://${socket}`, ...model]
233
+ : ["--remote", `unix://${socket}`, ...model, ...(options.remoteArgs ?? [])];
231
234
  return { entry, args };
232
235
  }
233
236
  catch (error) {
@@ -287,6 +290,29 @@ export class CodexServers {
287
290
  }
288
291
  return started;
289
292
  }
293
+ /** A phone message, sent as the pane's TUI sends Enter: steered into the
294
+ * running turn, else a new turn. Either way Codex holds it as input until
295
+ * the model's next step takes it (after the tool call that is running, which
296
+ * can be long), and only then runs UserPromptSubmit; on Codex 0.160 a
297
+ * `turn/start` during a turn is merged into it the same way. So the turn id
298
+ * acknowledges the hand-over, not the delivery. A held model change starts
299
+ * a turn, which carries it. */
300
+ async send(entry, text) {
301
+ if (!entry.threadId)
302
+ throw new CodexServerUnavailable("The Codex pane has not started its thread yet.");
303
+ const live = this.live.get(entry.id)?.entry ?? entry, running = live.activeTurn;
304
+ if (running && !live.nextTurn) {
305
+ const client = await this.client(entry);
306
+ try {
307
+ return await client.turnSteer({ threadId: entry.threadId, expectedTurnId: running, input: [{ type: "text", text, text_elements: [] }] });
308
+ }
309
+ catch (error) {
310
+ if (!(error instanceof AppServerRpcError))
311
+ throw error;
312
+ }
313
+ }
314
+ return await this.prompt(entry, text);
315
+ }
290
316
  /** `thread/name/set` on the pane's thread: Codex's own rename, which its TUI
291
317
  * shows and `session_index.jsonl` keeps. Allowed while a turn runs. */
292
318
  async renameThread(entry, name) {
@@ -491,6 +517,8 @@ export class CodexServers {
491
517
  if (entry.threadId === threadId)
492
518
  return;
493
519
  const previous = entry.threadId;
520
+ if (previous)
521
+ this.sink?.threadChanged?.(this.target(entry));
494
522
  // The old thread's cards cannot be answered from this pane any more.
495
523
  if (previous && live.client) {
496
524
  const target = this.target(entry);
@@ -599,9 +627,13 @@ export class CodexServers {
599
627
  // thread only at launch, so a top-level thread in the pane's folder
600
628
  // is the one the pane now shows (helper threads, such as the one
601
629
  // naming the thread, have no environment; subagents have a parent).
630
+ // Codex's auto-review guardian runs as a subagent thread in the
631
+ // pane's folder with no parent id, and a `codex exec` is not the TUI's:
632
+ // following either moved the pane off its conversation (w63, 2026-10-04).
602
633
  const thread = object(event.params.thread);
603
634
  const here = objects(thread.environments).some(environment => typeof environment.cwd === "string" && path.resolve(environment.cwd) === path.resolve(entry.cwd));
604
- if (typeof thread.id === "string" && thread.id && !thread.parentThreadId && here)
635
+ const foreign = thread.source === "exec" || (typeof thread.source === "object" && thread.source !== null && "subAgent" in thread.source) || thread.ephemeral === true;
636
+ if (typeof thread.id === "string" && thread.id && !thread.parentThreadId && here && !foreign)
605
637
  this.rebind(live, thread.id);
606
638
  return;
607
639
  }
@@ -0,0 +1,12 @@
1
+ /** Whether a Codex hook callback comes from a thread that is not the pane's
2
+ * own conversation: a `codex exec` started inside the pane (a fanout worker,
3
+ * a review run) or a subagent (the guardian reviewer, a spawned thread). They
4
+ * inherit the pane's variables, so their callbacks name the pane, and each
5
+ * one used to rebind it: the pane's conversation then looked replaced, phone
6
+ * sends were refused as "conversation changed" and queued hand-offs failed.
7
+ * Read from the rollout's first row (`originator`, `source`); a rollout that
8
+ * cannot be read counts as the pane's own. */
9
+ export declare function codexForeignThread(transcriptPath: unknown): Promise<boolean>;
10
+ /** The session_meta fields come before its long instructions, so the head of
11
+ * the line is enough; no full parse. */
12
+ export declare function foreignMeta(head: string): boolean;
@@ -0,0 +1,31 @@
1
+ import { open } from "node:fs/promises";
2
+ import path from "node:path";
3
+ /** Whether a Codex hook callback comes from a thread that is not the pane's
4
+ * own conversation: a `codex exec` started inside the pane (a fanout worker,
5
+ * a review run) or a subagent (the guardian reviewer, a spawned thread). They
6
+ * inherit the pane's variables, so their callbacks name the pane, and each
7
+ * one used to rebind it: the pane's conversation then looked replaced, phone
8
+ * sends were refused as "conversation changed" and queued hand-offs failed.
9
+ * Read from the rollout's first row (`originator`, `source`); a rollout that
10
+ * cannot be read counts as the pane's own. */
11
+ export async function codexForeignThread(transcriptPath) {
12
+ if (typeof transcriptPath !== "string" || !path.isAbsolute(transcriptPath) || !/^rollout-.*\.jsonl$/.test(path.basename(transcriptPath)))
13
+ return false;
14
+ const file = await open(transcriptPath, "r").catch(() => undefined);
15
+ if (!file)
16
+ return false;
17
+ try {
18
+ const buffer = Buffer.alloc(4096), { bytesRead } = await file.read(buffer, 0, buffer.length, 0);
19
+ return foreignMeta(buffer.subarray(0, bytesRead).toString("utf8"));
20
+ }
21
+ finally {
22
+ await file.close();
23
+ }
24
+ }
25
+ /** The session_meta fields come before its long instructions, so the head of
26
+ * the line is enough; no full parse. */
27
+ export function foreignMeta(head) {
28
+ if (!head.includes('"session_meta"'))
29
+ return false;
30
+ return /"originator"\s*:\s*"codex_exec"/.test(head) || /"source"\s*:\s*"exec"/.test(head) || /"source"\s*:\s*\{\s*"subagent"/.test(head);
31
+ }
@@ -443,7 +443,7 @@ export class DispatchService {
443
443
  // This computer needs no hooks.yaml entry, so a missing file only
444
444
  // matters when the dispatch names another computer.
445
445
  const here = this.local();
446
- // An alias or hostname (`Mac`, `Squids-Mac-mini.local`) names the same computer as its hooks.yaml name.
446
+ // An alias or hostname (`Mac`, `Sams-Mac-mini.local`) names the same computer as its hooks.yaml name.
447
447
  const named = data.computer === "anywhere" || isLocalComputer(data.computer, here.names) ? undefined : await linkedComputer(data.computer).catch(() => undefined);
448
448
  const toLocal = data.computer !== "anywhere" && (isLocalComputer(data.computer, here.names) || (named !== undefined && "local" in named));
449
449
  const peerName = named && "peer" in named ? named.peer : data.computer;
@@ -19,6 +19,8 @@ export declare function candidateRepos(activity: Json[], env?: NodeJS.ProcessEnv
19
19
  export interface EnrollInput {
20
20
  directory?: string;
21
21
  cloneUrl?: string;
22
+ project?: string;
23
+ store?: string;
22
24
  }
23
25
  export interface Enrolled {
24
26
  ok: true;
@@ -27,5 +29,9 @@ export interface Enrolled {
27
29
  cloned: boolean;
28
30
  store: "pushed" | "committed" | "unchanged" | "error";
29
31
  storeDetail?: string;
32
+ target?: {
33
+ project: string;
34
+ store: string;
35
+ };
30
36
  }
31
37
  export declare function enrollProject(input: EnrollInput, env?: NodeJS.ProcessEnv): Promise<Enrolled>;