@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
@@ -14,6 +14,8 @@ import { projectSlugFromPath } from "../phren-paths.js";
14
14
  import { runBestEffortGit } from "../cli/session-git.js";
15
15
  import { mergeStoreUpstream } from "../sync/store-merge.js";
16
16
  import { countGit } from "./metrics.js";
17
+ import { resolveCodeStore } from "./code-routes.js";
18
+ import { isValidProjectName } from "../utils-paths.js";
17
19
  import { storeCommitMessage } from "../machine-identity.js";
18
20
  const exec = promisify(execFile);
19
21
  const runEnrollStoreGit = async (cwd, args) => {
@@ -178,9 +180,13 @@ async function publishStore(store, project) {
178
180
  return push.ok ? { store: "pushed" } : { store: "committed", storeDetail: push.error };
179
181
  }
180
182
  export async function enrollProject(input, env = process.env) {
181
- const store = phrenStoreRoot(env);
183
+ if (input.project !== undefined && (!isValidProjectName(input.project) || input.project === "global")) {
184
+ throw new BridgeError(400, "Choose a valid target project name.");
185
+ }
186
+ const baseStore = phrenStoreRoot(env);
187
+ const store = await resolveCodeStore(baseStore, input.store, true);
182
188
  try {
183
- if (!(await stat(path.join(store, ".config"))).isDirectory())
189
+ if (!(await stat(path.join(baseStore, ".config"))).isDirectory())
184
190
  throw new Error();
185
191
  }
186
192
  catch {
@@ -229,8 +235,8 @@ export async function enrollProject(input, env = process.env) {
229
235
  }
230
236
  else
231
237
  throw new BridgeError(400, "Choose a folder or a repository URL.");
232
- const added = addProjectFromPath(store, directory, env.PHREN_PROFILE || undefined, getProjectOwnershipDefault(store));
238
+ const added = addProjectFromPath(baseStore, directory, env.PHREN_PROFILE || undefined, getProjectOwnershipDefault(store), { writeToPath: store, projectName: input.project });
233
239
  if (!added.ok)
234
240
  throw new BridgeError(409, added.error);
235
- return { ok: true, project: added.data.project, directory, cloned, ...(await publishStore(store, added.data.project)) };
241
+ return { ok: true, project: added.data.project, directory, cloned, ...(input.project && input.store ? { target: { project: added.data.project, store: input.store } } : {}), ...(await publishStore(store, added.data.project)) };
236
242
  }
@@ -3,7 +3,7 @@ import { realpath, stat } from "node:fs/promises";
3
3
  import { homedir } from "node:os";
4
4
  import path from "node:path";
5
5
  import { BridgeError } from "./protocol.js";
6
- import { git, gitRoot } from "./projects.js";
6
+ import { git, gitHead, gitRoot, withGitReadDeadline } from "./projects.js";
7
7
  /** Workers edit in their own worktrees, so the pane's repository diff never
8
8
  * shows their work. These are the repository's other worktrees, exactly as
9
9
  * `git worktree list` reports them, each addressed by an opaque id the phone
@@ -17,10 +17,10 @@ export function worktreeId(abs) {
17
17
  /** `git worktree list --porcelain`: one block per worktree. Bare entries and
18
18
  * worktrees missing on disk are left out; nothing there can be shown. */
19
19
  async function listed(root) {
20
- const output = await git(root, "worktree", "list", "--porcelain");
20
+ const output = await git(root, "worktree", "list", "--porcelain", "-z");
21
21
  const blocks = [];
22
22
  let current;
23
- for (const line of output.split("\n")) {
23
+ for (const line of output.split("\0")) {
24
24
  if (!line) {
25
25
  current = undefined;
26
26
  continue;
@@ -98,28 +98,25 @@ async function workerFor(abs, workers, all = []) {
98
98
  /** The pane repository's other worktrees with branch, HEAD, commits ahead of
99
99
  * and behind this pane's HEAD, uncommitted file count and, when known, the
100
100
  * worker editing there. */
101
- export async function gitWorktrees(cwd, workers = []) {
101
+ export function gitWorktrees(cwd, workers = []) {
102
+ return withGitReadDeadline(() => readGitWorktrees(cwd, workers));
103
+ }
104
+ async function readGitWorktrees(cwd, workers) {
102
105
  const root = await gitRoot(cwd);
103
106
  if (!root)
104
- throw new BridgeError(409, "This pane is not in a Git repository.");
107
+ throw new BridgeError(409, "This pane is not in a Git repository.", { code: "git-not-repository" });
105
108
  const { main, worktrees } = await listed(root);
106
- const base = (await git(root, "rev-parse", "--verify", "HEAD").catch(() => "")).trim();
109
+ const base = await gitHead(root);
107
110
  const roots = [root, ...(main && main !== root ? [main] : [])];
108
111
  const others = worktrees.filter(worktree => worktree.abs !== root);
109
112
  const rows = await Promise.all(others.map(async (worktree) => {
110
113
  let ahead = 0, behind = 0;
111
114
  if (base && worktree.head && worktree.head !== base) {
112
- try {
113
- const counts = (await git(root, "rev-list", "--left-right", "--count", `${base}...${worktree.head}`)).trim().split(/\s+/);
114
- behind = Number(counts[0]) || 0;
115
- ahead = Number(counts[1]) || 0;
116
- }
117
- catch {
118
- ahead = 0;
119
- behind = 0;
120
- }
115
+ const counts = (await git(root, "rev-list", "--left-right", "--count", `${base}...${worktree.head}`)).trim().split(/\s+/);
116
+ behind = Number(counts[0]);
117
+ ahead = Number(counts[1]);
121
118
  }
122
- const changed = uncommitted(await git(worktree.abs, "status", "--porcelain=v1", "-z", "--untracked-files=normal").catch(() => ""));
119
+ const changed = uncommitted(await git(worktree.abs, "status", "--porcelain=v1", "-z", "--untracked-files=normal"));
123
120
  const worker = await workerFor(worktree.abs, workers, worktrees.map(item => item.abs));
124
121
  return {
125
122
  id: worktreeId(worktree.abs), path: displayPath(worktree.abs, roots), branch: worktree.branch,
@@ -142,7 +139,7 @@ export async function resolveWorktree(cwd, id) {
142
139
  throw new BridgeError(400, "Invalid worktree.");
143
140
  const root = await gitRoot(cwd);
144
141
  if (!root)
145
- throw new BridgeError(409, "This pane is not in a Git repository.");
142
+ throw new BridgeError(409, "This pane is not in a Git repository.", { code: "git-not-repository" });
146
143
  const match = (await listed(root)).worktrees.find(worktree => worktreeId(worktree.abs) === id);
147
144
  if (!match)
148
145
  throw new BridgeError(404, "That worktree is not part of this repository.");
@@ -9,8 +9,16 @@ export interface GitStatusFile {
9
9
  staged: boolean;
10
10
  additions: number;
11
11
  deletions: number;
12
+ binary?: boolean;
13
+ directory?: boolean;
14
+ countsComplete?: boolean;
12
15
  }
13
16
  export interface GitStatus {
17
+ repository: string;
18
+ observedAt: string;
19
+ truncated: boolean;
20
+ countsComplete: boolean;
21
+ totalFiles: number;
14
22
  branch: string;
15
23
  upstream: string | null;
16
24
  ahead: number;
@@ -26,7 +34,7 @@ export interface GitStatus {
26
34
  }
27
35
  /** Working-tree status, one record per section: a file edited in both the index
28
36
  * and the working tree appears once with `staged: true` and once with `false`. */
29
- export declare function gitStatus(cwd: string): Promise<GitStatus>;
37
+ export declare function gitStatus(cwd: string, untrackedPath?: string): Promise<GitStatus>;
30
38
  /** Commits newest first, plus a one-line summary of what is not committed yet. */
31
39
  export declare function gitLog(cwd: string, limit?: number, ref?: string): Promise<Json>;
32
40
  /** Local branches with their upstream and ahead/behind counts, and remote refs. */
@@ -47,7 +55,7 @@ export declare function invalidateTree(root: string): void;
47
55
  * Status refresh and phone mutations invalidate immediately as well. With
48
56
  * `ignored`, git-ignored folders and files at that level are added, marked. */
49
57
  export declare function gitTree(cwd: string, relPath?: unknown, ignored?: boolean): Promise<Json>;
50
- export declare function gitStage(cwd: string, paths: unknown): Promise<Json>;
58
+ export declare function gitStage(cwd: string, paths: unknown, confirmBulk?: boolean): Promise<Json>;
51
59
  export declare function gitUnstage(cwd: string, paths: unknown): Promise<Json>;
52
60
  /** Destructive: tracked files go back to the index, untracked files are
53
61
  * removed. The phone confirms first; no `-d` (directories) and no `-x`. */
@@ -1,10 +1,10 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { execFile } from "node:child_process";
3
- import { lstat, readdir, readFile, realpath, stat } from "node:fs/promises";
3
+ import { lstat, open, readdir, realpath } from "node:fs/promises";
4
4
  import path from "node:path";
5
5
  import { promisify } from "node:util";
6
6
  import { BridgeError } from "./protocol.js";
7
- import { git, gitRoot } from "./projects.js";
7
+ import { git, gitHead, gitRoot, withGitReadDeadline } from "./projects.js";
8
8
  const exec = promisify(execFile);
9
9
  /** A status code from `--name-status`: the letter alone, with `T` (type change)
10
10
  * shown as an edit and anything unrecognized treated as one. */
@@ -12,30 +12,7 @@ function statusLetter(code) {
12
12
  const letter = code[0];
13
13
  return ["M", "A", "D", "R", "C", "U"].includes(letter) ? letter : "M";
14
14
  }
15
- /** `--name-status -z` records as path-to-status; a rename carries old then new. */
16
- function parseNameStatus(out) {
17
- const map = new Map();
18
- const tokens = out.split("\0");
19
- for (let index = 0; index < tokens.length; index++) {
20
- const code = tokens[index];
21
- if (!code)
22
- continue;
23
- if (code[0] === "R" || code[0] === "C") {
24
- index++;
25
- const destination = tokens[++index];
26
- if (destination)
27
- map.set(destination, code[0]);
28
- }
29
- else {
30
- const file = tokens[++index];
31
- if (file)
32
- map.set(file, code[0]);
33
- }
34
- }
35
- return map;
36
- }
37
- /** `--numstat -z` per-path line counts; a rename leaves the path empty and the
38
- * two names follow as their own tokens. */
15
+ /** NUL records preserve tabs/newlines in names and both sides of renames. */
39
16
  function parseNumstat(out) {
40
17
  const map = new Map();
41
18
  const tokens = out.split("\0");
@@ -44,119 +21,166 @@ function parseNumstat(out) {
44
21
  if (!record)
45
22
  continue;
46
23
  const parts = record.split("\t");
47
- if (parts.length < 2)
48
- continue;
49
- const additions = parts[0] === "-" ? 0 : Number(parts[0]) || 0;
50
- const deletions = parts[1] === "-" ? 0 : Number(parts[1]) || 0;
24
+ if (parts.length < 3)
25
+ throw new BridgeError(503, "Git returned invalid line counts.", { code: "git-failed" });
26
+ const binary = parts[0] === "-" || parts[1] === "-";
51
27
  let file = parts.slice(2).join("\t");
52
28
  if (!file) {
53
29
  index++;
54
- const destination = tokens[++index];
55
- file = destination ?? "";
30
+ file = tokens[++index] ?? "";
56
31
  }
57
- if (file)
58
- map.set(file, { additions, deletions });
32
+ const additions = binary ? 0 : Number(parts[0]), deletions = binary ? 0 : Number(parts[1]);
33
+ if (!file || !Number.isSafeInteger(additions) || additions < 0 || !Number.isSafeInteger(deletions) || deletions < 0)
34
+ throw new BridgeError(503, "Git returned invalid line counts.", { code: "git-failed" });
35
+ map.set(file, { additions, deletions, binary, countsComplete: true });
59
36
  }
60
37
  return map;
61
38
  }
62
- /** A count of a text file's lines, for an untracked file whose diff has no base. */
63
- async function countLines(root, rel) {
64
- try {
65
- const abs = path.join(root, await repositoryPath(root, rel));
66
- if ((await stat(abs)).size > 5_000_000)
67
- return 0;
68
- const bytes = await readFile(abs);
69
- if (!bytes.length || bytes.includes(0))
70
- return 0;
71
- let lines = 0;
72
- for (const byte of bytes)
73
- if (byte === 10)
74
- lines++;
75
- return bytes[bytes.length - 1] === 10 ? lines : lines + 1;
76
- }
77
- catch {
78
- return 0;
39
+ const UNKNOWN_COUNTS = { additions: 0, deletions: 0, countsComplete: false };
40
+ const NO_DIFF = ["diff", "--no-ext-diff", "--no-textconv", "--no-color"];
41
+ const MAX_STATUS_ROWS = 500;
42
+ /** Git owns text/binary classification (including attributes) and line counts.
43
+ * Oversized files are only probed; symlink contents are never followed. */
44
+ async function untrackedCounts(root, rel) {
45
+ const abs = path.join(root, rel);
46
+ const info = await lstat(abs);
47
+ if (!info.isFile())
48
+ return { ...UNKNOWN_COUNTS };
49
+ await repositoryPath(root, rel);
50
+ if (info.size > 5_000_000) {
51
+ const handle = await open(abs, "r");
52
+ try {
53
+ const bytes = Buffer.alloc(8000);
54
+ const { bytesRead } = await handle.read(bytes, 0, bytes.length, 0);
55
+ return { ...UNKNOWN_COUNTS, ...(bytes.subarray(0, bytesRead).includes(0) ? { binary: true } : {}) };
56
+ }
57
+ finally {
58
+ await handle.close();
59
+ }
79
60
  }
61
+ const out = await git(root, ...NO_DIFF, "--no-index", "--numstat", "-z", "--", "/dev/null", rel);
62
+ return [...parseNumstat(out).values()][0] ?? { additions: 0, deletions: 0, binary: false, countsComplete: true };
80
63
  }
81
- /** Everything `git status` reports, kept apart by section so `gitLog` and
82
- * `gitTree` can reuse it. */
64
+ /** Status, rather than diff alone, owns membership (including conflicts and
65
+ * intent-to-add). Normal mode collapses wholly untracked directories. */
83
66
  async function collect(root) {
84
67
  const branch = (await git(root, "branch", "--show-current")).trim();
85
- let upstream;
68
+ const upstream = branch ? (await git(root, "for-each-ref", "--format=%(upstream:short)", `refs/heads/${branch}`)).trim() || undefined : undefined;
86
69
  let ahead = 0, behind = 0;
87
- try {
88
- upstream = (await git(root, "rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{upstream}")).trim() || undefined;
89
- }
90
- catch {
91
- upstream = undefined;
92
- }
93
70
  if (upstream) {
94
- try {
95
- const counts = (await git(root, "rev-list", "--left-right", "--count", `${upstream}...HEAD`)).trim().split(/\s+/);
96
- behind = Number(counts[0]) || 0;
97
- ahead = Number(counts[1]) || 0;
98
- }
99
- catch {
100
- ahead = 0;
101
- behind = 0;
71
+ const counts = (await git(root, "rev-list", "--left-right", "--count", `${upstream}...HEAD`)).trim().split(/\s+/);
72
+ behind = Number(counts[0]);
73
+ ahead = Number(counts[1]);
74
+ }
75
+ const [raw, stagedCounts, unstagedCounts] = await Promise.all([
76
+ git(root, "status", "--porcelain=v1", "-z", "--untracked-files=normal"),
77
+ git(root, ...NO_DIFF, "--cached", "--numstat", "-z"),
78
+ git(root, ...NO_DIFF, "--numstat", "-z"),
79
+ ]);
80
+ const staged = new Map(), unstaged = new Map(), untracked = [];
81
+ const tokens = raw.split("\0");
82
+ for (let i = 0; i < tokens.length; i++) {
83
+ const row = tokens[i];
84
+ if (!row)
85
+ continue;
86
+ const xy = row.slice(0, 2), file = row.slice(3);
87
+ if (xy === "??")
88
+ untracked.push(file);
89
+ else {
90
+ if (xy[0] !== " ")
91
+ staged.set(file, xy[0]);
92
+ if (xy[1] !== " ")
93
+ unstaged.set(file, xy[1]);
94
+ if (/[RC]/.test(xy))
95
+ i++;
102
96
  }
103
97
  }
104
- const [stagedRaw, unstagedRaw, stagedCounts, unstagedCounts, untrackedRaw] = await Promise.all([
105
- git(root, "diff", "--cached", "--name-status", "-z"),
106
- git(root, "diff", "--name-status", "-z"),
107
- git(root, "diff", "--cached", "--numstat", "-z"),
108
- git(root, "diff", "--numstat", "-z"),
109
- git(root, "ls-files", "--others", "--exclude-standard", "-z"),
110
- ]);
111
- const staged = parseNameStatus(stagedRaw), unstaged = parseNameStatus(unstagedRaw);
112
- const stagedStats = parseNumstat(stagedCounts), unstagedStats = parseNumstat(unstagedCounts);
113
- const untracked = untrackedRaw.split("\0").filter(Boolean);
114
- return { branch, upstream, ahead, behind, staged, unstaged, stagedStats, unstagedStats, untracked };
98
+ return { branch, upstream, ahead, behind, staged, unstaged,
99
+ stagedStats: parseNumstat(stagedCounts), unstagedStats: parseNumstat(unstagedCounts), untracked };
115
100
  }
116
101
  /** The remote's default branch as its `HEAD` records it. With no recorded
117
102
  * `HEAD`, `main` and `master` are treated as default so the guard errs on the
118
103
  * side of asking. */
119
104
  export async function defaultBranch(root, remote = "origin") {
120
- const head = (await git(root, "symbolic-ref", "--quiet", "--short", `refs/remotes/${remote}/HEAD`).catch(() => "")).trim();
105
+ const head = (await git(root, "symbolic-ref", "--quiet", "--short", `refs/remotes/${remote}/HEAD`).catch(error => {
106
+ if (error instanceof BridgeError && error.details?.exitCode === "1")
107
+ return "";
108
+ throw error;
109
+ })).trim();
121
110
  if (head.startsWith(remote + "/"))
122
111
  return head.slice(remote.length + 1);
123
- const branches = new Set((await git(root, "for-each-ref", "--format=%(refname:short)", "refs/heads").catch(() => "")).split("\n").filter(Boolean));
112
+ const branches = new Set((await git(root, "for-each-ref", "--format=%(refname:short)", "refs/heads")).split("\n").filter(Boolean));
124
113
  return branches.has("main") ? "main" : branches.has("master") ? "master" : null;
125
114
  }
126
115
  async function repository(cwd) {
127
116
  const root = await gitRoot(cwd);
128
117
  if (!root)
129
- throw new BridgeError(409, "This pane is not in a Git repository.");
118
+ throw new BridgeError(409, "This pane is not in a Git repository.", { code: "git-not-repository" });
130
119
  return root;
131
120
  }
132
121
  /** Working-tree status, one record per section: a file edited in both the index
133
122
  * and the working tree appears once with `staged: true` and once with `false`. */
134
- export async function gitStatus(cwd) {
123
+ export function gitStatus(cwd, untrackedPath) {
124
+ return withGitReadDeadline(() => readGitStatus(cwd, untrackedPath));
125
+ }
126
+ async function readGitStatus(cwd, untrackedPath) {
135
127
  const root = await repository(cwd);
136
128
  treeCache.delete(root);
137
129
  const data = await collect(root);
138
130
  const fallback = await defaultBranch(root, data.upstream?.split("/")[0] || "origin");
131
+ if (untrackedPath !== undefined) {
132
+ const prefix = await repositoryPath(root, untrackedPath);
133
+ if (!data.untracked.some(file => file.endsWith("/") && (prefix + "/").startsWith(file))
134
+ || !(await lstat(path.join(root, prefix))).isDirectory()
135
+ || await gitRoot(path.join(root, prefix)) !== root)
136
+ throw new BridgeError(409, "This is no longer an untracked directory in this repository.");
137
+ const ignored = await git(root, "check-ignore", "--", prefix).catch(error => {
138
+ if (error instanceof BridgeError && error.details?.exitCode === "1")
139
+ return "";
140
+ throw error;
141
+ });
142
+ if (ignored)
143
+ throw new BridgeError(409, "This directory is ignored by Git.");
144
+ // --directory can collapse the requested folder itself, even with -C.
145
+ // Let Git filter ignores, then collapse descendants to immediate children.
146
+ const descendants = (await git(root, "ls-files", "--others", "--exclude-standard", "--full-name", "-z", "--", `:(literal)${prefix}/`)).split("\0").filter(Boolean);
147
+ data.untracked = [...new Set(descendants.map(file => {
148
+ const slash = file.indexOf("/", prefix.length + 1);
149
+ return slash < 0 ? file : file.slice(0, slash + 1);
150
+ }))];
151
+ data.staged.clear();
152
+ data.unstaged.clear();
153
+ }
139
154
  const files = [];
140
155
  for (const [file, status] of data.staged) {
141
- const counts = data.stagedStats.get(file) ?? { additions: 0, deletions: 0 };
142
- files.push({ path: file, status: statusLetter(status), staged: true, ...counts });
156
+ if (files.length >= MAX_STATUS_ROWS)
157
+ break;
158
+ files.push({ path: file, status: statusLetter(status), staged: true, ...(data.stagedStats.get(file) ?? UNKNOWN_COUNTS) });
143
159
  }
144
160
  for (const [file, status] of data.unstaged) {
145
- const counts = data.unstagedStats.get(file) ?? { additions: 0, deletions: 0 };
146
- files.push({ path: file, status: statusLetter(status), staged: false, ...counts });
147
- }
148
- for (const file of data.untracked)
149
- files.push({ path: file, status: "?", staged: false, additions: await countLines(root, file), deletions: 0 });
150
- const additions = files.reduce((total, file) => total + file.additions, 0);
151
- const deletions = files.reduce((total, file) => total + file.deletions, 0);
152
- return { branch: data.branch, upstream: data.upstream ?? null, ahead: data.ahead, behind: data.behind,
153
- staged: data.staged.size, unstaged: data.unstaged.size, untracked: data.untracked.length, additions, deletions, files,
161
+ if (files.length >= MAX_STATUS_ROWS)
162
+ break;
163
+ files.push({ path: file, status: statusLetter(status), staged: false, ...(data.unstagedStats.get(file) ?? UNKNOWN_COUNTS) });
164
+ }
165
+ for (const file of data.untracked) {
166
+ if (files.length >= MAX_STATUS_ROWS)
167
+ break;
168
+ const directory = file.endsWith("/");
169
+ files.push({ path: file, status: "?", staged: false, ...(directory ? { ...UNKNOWN_COUNTS, directory: true } : await untrackedCounts(root, file)) });
170
+ }
171
+ const truncated = data.staged.size + data.unstaged.size + data.untracked.length > files.length;
172
+ return { repository: root, observedAt: new Date().toISOString(), truncated,
173
+ countsComplete: !truncated && files.every(file => file.countsComplete === true),
174
+ totalFiles: new Set([...data.staged.keys(), ...data.unstaged.keys(), ...data.untracked]).size,
175
+ branch: data.branch, upstream: data.upstream ?? null, ahead: data.ahead, behind: data.behind,
176
+ staged: data.staged.size, unstaged: data.unstaged.size, untracked: data.untracked.length,
177
+ additions: files.reduce((total, file) => total + file.additions, 0), deletions: files.reduce((total, file) => total + file.deletions, 0), files,
154
178
  defaultBranch: fallback };
155
179
  }
156
180
  /** The repository's remotes, so a branch ref can be told from a remote-tracking
157
181
  * one even when a local branch name contains a slash. */
158
182
  async function remotes(root) {
159
- return (await git(root, "remote").catch(() => "")).split("\n").map(line => line.trim()).filter(Boolean);
183
+ return (await git(root, "remote")).split("\n").map(line => line.trim()).filter(Boolean);
160
184
  }
161
185
  function refEntries(spec, remotes) {
162
186
  const refs = [];
@@ -194,7 +218,7 @@ export async function gitLog(cwd, limit = 60, ref) {
194
218
  }
195
219
  }
196
220
  else {
197
- revision = (await git(root, "rev-parse", "--verify", "HEAD").catch(() => "")).trim();
221
+ revision = await gitHead(root);
198
222
  }
199
223
  const known = await remotes(root);
200
224
  const output = revision ? await git(root, "log", "--decorate=short", "--date=iso-strict", "--format=%H%x00%h%x00%s%x00%an%x00%cI%x00%D%x00%P", "-n", String(count), revision, "--") : "";
@@ -206,7 +230,7 @@ export async function gitLog(cwd, limit = 60, ref) {
206
230
  commits.push({ sha, short, subject, author, date, refs: refEntries(spec ?? "", known), parents: (parents ?? "").split(" ").filter(Boolean) });
207
231
  }
208
232
  const status = await gitStatus(root);
209
- const uncommitted = { files: new Set(status.files.map(file => file.path)).size, additions: status.additions, deletions: status.deletions };
233
+ const uncommitted = { files: status.totalFiles, additions: status.additions, deletions: status.deletions, truncated: status.truncated, countsComplete: status.countsComplete };
210
234
  return { commits, uncommitted };
211
235
  }
212
236
  /** Local branches with their upstream and ahead/behind counts, and remote refs. */
@@ -308,7 +332,7 @@ async function repositoryPath(root, raw, allowRoot = false) {
308
332
  if (typeof raw !== "string" || raw.length > 4096 || raw.includes("\0") || path.isAbsolute(raw) || path.win32.isAbsolute(raw) || raw.startsWith("\\"))
309
333
  throw new BridgeError(400, "Invalid path.");
310
334
  const segments = raw.split(/[\\/]/);
311
- if (segments.includes(".."))
335
+ if (segments.includes("..") || segments.includes(".git"))
312
336
  throw new BridgeError(400, "Invalid path.");
313
337
  const clean = segments.filter(part => part && part !== ".").join("/");
314
338
  if ((!clean && !allowRoot) || clean.startsWith("-"))
@@ -370,7 +394,7 @@ async function treeSnapshot(root, head) {
370
394
  levels.set("", new Map());
371
395
  for (const file of files) {
372
396
  const parts = file.split("/");
373
- if (parts.includes("node_modules") || parts.includes(".git"))
397
+ if (parts.includes(".git"))
374
398
  continue;
375
399
  let parent = "";
376
400
  for (let i = 0; i < parts.length; i++) {
@@ -464,7 +488,7 @@ async function ignoredEntries(root, prefix, shown) {
464
488
  export async function gitTree(cwd, relPath = "", ignored = false) {
465
489
  const root = await repository(cwd);
466
490
  const prefix = await repositoryPath(root, relPath, true);
467
- const head = await git(root, "rev-parse", "HEAD").catch(() => "unborn");
491
+ const head = await gitHead(root) ?? "unborn";
468
492
  let cached = treeCache.get(root);
469
493
  if (!cached || cached.head !== head || cached.expires <= Date.now()) {
470
494
  if (treeCache.size >= 32)
@@ -488,10 +512,10 @@ export async function gitTree(cwd, relPath = "", ignored = false) {
488
512
  }
489
513
  }
490
514
  /** The phone's paths are repo-relative, at most 64, and can never climb out. */
491
- async function repositoryPaths(root, raw) {
515
+ async function repositoryPaths(root, raw, limit = 64) {
492
516
  const list = Array.isArray(raw) ? raw : [];
493
- if (!list.length || list.length > 64)
494
- throw new BridgeError(400, "Choose between 1 and 64 paths.");
517
+ if (!list.length || list.length > limit)
518
+ throw new BridgeError(400, `Choose between 1 and ${limit} paths.`);
495
519
  const paths = [];
496
520
  for (const entry of list) {
497
521
  const clean = await repositoryPath(root, entry);
@@ -499,14 +523,31 @@ async function repositoryPaths(root, raw) {
499
523
  paths.push(clean);
500
524
  }
501
525
  if (!paths.length)
502
- throw new BridgeError(400, "Choose between 1 and 64 paths.");
526
+ throw new BridgeError(400, `Choose between 1 and ${limit} paths.`);
503
527
  return paths;
504
528
  }
505
- export async function gitStage(cwd, paths) {
529
+ export async function gitStage(cwd, paths, confirmBulk = false) {
506
530
  const root = await repository(cwd);
507
531
  treeCache.delete(root);
508
532
  try {
509
- await git(root, "add", "--", ...(await repositoryPaths(root, paths)).map(file => `:(literal)${file}`));
533
+ const files = await repositoryPaths(root, paths, 500);
534
+ if (!confirmBulk) {
535
+ if (files.length > 100)
536
+ throw new BridgeError(409, "Confirm staging more than 100 paths with confirmBulk=true.");
537
+ const untracked = new Set((await git(root, "ls-files", "--others", "--exclude-standard", "-z", "--", ...files.map(file => `:(literal)${file}`))).split("\0").filter(Boolean));
538
+ for (const file of files) {
539
+ const info = await lstat(path.join(root, file)).catch(error => { if (error.code === "ENOENT")
540
+ return undefined; throw error; });
541
+ if (info?.isDirectory())
542
+ throw new BridgeError(409, "Confirm staging this directory and its contents with confirmBulk=true.");
543
+ if (untracked.has(file)) {
544
+ const counts = await untrackedCounts(root, file);
545
+ if (counts.binary || !counts.countsComplete)
546
+ throw new BridgeError(409, "Confirm staging this binary or uncounted untracked file with confirmBulk=true.");
547
+ }
548
+ }
549
+ }
550
+ await git(root, "add", "--", ...files.map(file => `:(literal)${file}`));
510
551
  return { ok: true };
511
552
  }
512
553
  finally {
@@ -518,7 +559,7 @@ export async function gitUnstage(cwd, paths) {
518
559
  treeCache.delete(root);
519
560
  try {
520
561
  const files = (await repositoryPaths(root, paths)).map(file => `:(literal)${file}`);
521
- const hasHead = await git(root, "rev-parse", "--verify", "HEAD").then(() => true, () => false);
562
+ const hasHead = await gitHead(root);
522
563
  if (hasHead)
523
564
  await git(root, "restore", "--staged", "--", ...files);
524
565
  else
@@ -37,6 +37,11 @@ export interface QueueOptions {
37
37
  validate: (target: Target) => Promise<Json>;
38
38
  send: (target: Target, text: string, deliveryId: string, typing: () => Promise<void>) => Promise<Json>;
39
39
  notify?: (target: Target, text: string, deliveryId: string, computer: string) => Promise<Json>;
40
+ /** The conversation the target's pane shows now, and its terminal. */
41
+ current?: (target: Target) => Promise<{
42
+ session: string;
43
+ terminal: unknown;
44
+ } | undefined>;
40
45
  now?: () => number;
41
46
  root?: string;
42
47
  }
@@ -69,6 +74,11 @@ export declare class HandOffQueue {
69
74
  private reply;
70
75
  enqueue(input: unknown): Promise<Json>;
71
76
  status(id: string, target: Target): Promise<Json>;
77
+ /** Validates the row's target. When the pane's conversation was replaced
78
+ * in the same terminal (a Codex thread change, a Claude /clear), the row
79
+ * follows it: a queued message is for the pane, not for a conversation
80
+ * that is no longer there. Saved by the caller's next state change. */
81
+ private validate;
72
82
  private attempt;
73
83
  /** Coalesced: the Hook calls this every 5 s whether or not the last tick
74
84
  * finished, and queuing each behind the lock would hold every enqueue and
@@ -22,7 +22,8 @@ export const HAND_OFF_RETENTION_MS = 7 * DAY;
22
22
  /** At most this many rows stay on disk; the oldest settled rows go first. */
23
23
  export const HAND_OFF_MAX_ROWS = 512;
24
24
  const settled = (row) => row.state !== "queued" && row.state !== "attempting";
25
- const sameTarget = (a, b) => ["server", "workspace", "tab", "pane", "source", "session"].every(key => a[key] === b[key]);
25
+ /** A row follows its pane's conversation, so it is found by pane. */
26
+ const samePane = (a, b) => ["server", "workspace", "tab", "pane", "source"].every(key => a[key] === b[key]);
26
27
  /** A durable outbox on the receiving Hook. Persist 'attempting' before input,
27
28
  * so a crash in the input/ack gap recovers as uncertain, never as a retry.
28
29
  * Tombstones are retained for HAND_OFF_RETENTION_MS, so a retried delivery id
@@ -127,30 +128,52 @@ export class HandOffQueue {
127
128
  const data = queuedHandOffSchema.parse(input), id = data.deliveryId ?? randomUUID().replaceAll("-", "");
128
129
  const prior = await this.read(id);
129
130
  if (prior) {
130
- if (!sameTarget(prior.target, data.target) || prior.text !== data.text)
131
+ if (!samePane(prior.target, data.target) || prior.text !== data.text)
131
132
  throw new BridgeError(409, "This message id was already used for a different message.");
132
133
  return { ...this.reply(prior), replayed: true };
133
134
  }
134
- const pane = await this.options.validate(data.target);
135
+ const row = { ...data, deliveryId: id };
136
+ const pane = await this.validate(row);
135
137
  if (typeof pane.terminal_id !== "string")
136
138
  throw new BridgeError(409, "This agent has no terminal binding.");
137
139
  const at = new Date(this.now()).toISOString();
138
- const row = { ...data, deliveryId: id, terminal: pane.terminal_id, state: "queued", createdAt: at, updatedAt: at };
140
+ Object.assign(row, { terminal: pane.terminal_id, state: "queued", createdAt: at, updatedAt: at });
139
141
  await this.save(row);
140
142
  // Older queued messages take precedence even if this one arrives at idle.
141
- const ahead = (await this.prune(await this.rows())).some(other => other.deliveryId !== id && sameTarget(other.target, row.target) && other.state === "queued");
143
+ const ahead = (await this.prune(await this.rows())).some(other => other.deliveryId !== id && samePane(other.target, row.target) && other.state === "queued");
142
144
  if (!ahead)
143
145
  await this.attempt(row, pane);
144
146
  return this.reply(row);
145
147
  });
146
148
  }
147
149
  status(id, target) {
148
- return this.serial(async () => { const row = await this.read(id); if (!row || !sameTarget(row.target, target))
150
+ return this.serial(async () => { const row = await this.read(id); if (!row || !samePane(row.target, target))
149
151
  throw new BridgeError(404, "No hand-off with this id and target."); return this.reply(row); });
150
152
  }
153
+ /** Validates the row's target. When the pane's conversation was replaced
154
+ * in the same terminal (a Codex thread change, a Claude /clear), the row
155
+ * follows it: a queued message is for the pane, not for a conversation
156
+ * that is no longer there. Saved by the caller's next state change. */
157
+ async validate(row) {
158
+ try {
159
+ return await this.options.validate(row.target);
160
+ }
161
+ catch (error) {
162
+ if (!(error instanceof BridgeError) || error.status !== 409 || !this.options.current)
163
+ throw error;
164
+ const now = await this.options.current(row.target).catch(() => undefined);
165
+ if (!now || now.session === row.target.session || (row.terminal && now.terminal !== row.terminal))
166
+ throw error;
167
+ row.target = { ...row.target, session: now.session };
168
+ return await this.options.validate(row.target);
169
+ }
170
+ }
151
171
  async attempt(row, pane) {
172
+ const session = row.target.session;
152
173
  try {
153
- pane ??= await this.options.validate(row.target);
174
+ pane ??= await this.validate(row);
175
+ if (row.target.session !== session)
176
+ await this.save(row);
154
177
  }
155
178
  catch (error) {
156
179
  if (error instanceof BridgeError && [404, 409].includes(error.status)) {
@@ -207,7 +230,7 @@ export class HandOffQueue {
207
230
  const attempted = new Set(), remote = [];
208
231
  for (const row of rows)
209
232
  if (row.state === "queued") {
210
- const key = JSON.stringify(row.target);
233
+ const key = JSON.stringify({ ...row.target, session: undefined });
211
234
  if (attempted.has(key))
212
235
  continue;
213
236
  attempted.add(key);
@@ -255,10 +278,10 @@ export class HandOffQueue {
255
278
  * A new hand-off cannot be accepted between the pending check and closure. */
256
279
  whenNoPending(target, close) {
257
280
  return this.serial(async () => {
258
- if ((await this.rows()).some(row => sameTarget(row.target, target) && ["queued", "attempting", "uncertain"].includes(row.state)))
281
+ if ((await this.rows()).some(row => samePane(row.target, target) && ["queued", "attempting", "uncertain"].includes(row.state)))
259
282
  return { ok: true, closed: false };
260
283
  return close();
261
284
  });
262
285
  }
263
- hasPending(target) { return this.serial(async () => (await this.rows()).some(row => sameTarget(row.target, target) && ["queued", "attempting", "uncertain"].includes(row.state))); }
286
+ hasPending(target) { return this.serial(async () => (await this.rows()).some(row => samePane(row.target, target) && ["queued", "attempting", "uncertain"].includes(row.state))); }
264
287
  }