@phren/cli 0.3.31 → 0.3.33

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 (68) hide show
  1. package/dist/bridge/agent-hooks.js +23 -7
  2. package/dist/bridge/approval-rules.d.ts +70 -0
  3. package/dist/bridge/approval-rules.js +231 -0
  4. package/dist/bridge/authority.d.ts +1 -2
  5. package/dist/bridge/authority.js +2 -7
  6. package/dist/bridge/changes.d.ts +4 -0
  7. package/dist/bridge/changes.js +47 -33
  8. package/dist/bridge/claude-suggestion.js +1 -1
  9. package/dist/bridge/computer-names.d.ts +4 -0
  10. package/dist/bridge/computer-names.js +19 -0
  11. package/dist/bridge/dispatch.js +1 -1
  12. package/dist/bridge/enroll.d.ts +6 -0
  13. package/dist/bridge/enroll.js +10 -4
  14. package/dist/bridge/git-worktrees.js +14 -17
  15. package/dist/bridge/git.d.ts +10 -2
  16. package/dist/bridge/git.js +148 -107
  17. package/dist/bridge/health.js +9 -5
  18. package/dist/bridge/herdr.js +6 -1
  19. package/dist/bridge/locate.js +14 -1
  20. package/dist/bridge/model-switch.d.ts +4 -0
  21. package/dist/bridge/model-switch.js +16 -4
  22. package/dist/bridge/projects.d.ts +8 -0
  23. package/dist/bridge/projects.js +142 -24
  24. package/dist/bridge/schedule-format.d.ts +12 -0
  25. package/dist/bridge/schedule-format.js +33 -2
  26. package/dist/bridge/schedules.d.ts +8 -1
  27. package/dist/bridge/schedules.js +109 -45
  28. package/dist/bridge/server-launch.js +39 -15
  29. package/dist/bridge/server-pane-routes.js +19 -11
  30. package/dist/bridge/server-routes.d.ts +2 -0
  31. package/dist/bridge/server-routes.js +36 -8
  32. package/dist/bridge/server.js +1 -0
  33. package/dist/bridge/settings-switch.js +2 -6
  34. package/dist/bridge/speech-key.d.ts +2 -9
  35. package/dist/bridge/speech-key.js +4 -37
  36. package/dist/bridge/terminal-tmux.js +22 -4
  37. package/dist/bridge/tmux-test-server.d.ts +13 -0
  38. package/dist/bridge/tmux-test-server.js +103 -0
  39. package/dist/bridge/transcript-claude.d.ts +3 -3
  40. package/dist/bridge/transcript-claude.js +7 -7
  41. package/dist/bridge/transcript-codex.js +6 -4
  42. package/dist/bridge/transcript-preview.js +1 -1
  43. package/dist/bridge/transcripts.js +14 -3
  44. package/dist/bridge-hook.mjs +2794 -2223
  45. package/dist/cli/schedules.js +8 -2
  46. package/dist/cli/session-stop.js +9 -1
  47. package/dist/cli-registry.js +1 -1
  48. package/dist/core/project-registry.d.ts +1 -0
  49. package/dist/core/project-registry.js +6 -2
  50. package/dist/core/project.d.ts +1 -0
  51. package/dist/core/project.js +5 -0
  52. package/dist/modules/registry.js +9 -7
  53. package/dist/phren-core.js +1 -1
  54. package/dist/phren-paths.d.ts +2 -2
  55. package/dist/phren-paths.js +2 -2
  56. package/dist/store-routing.d.ts +2 -2
  57. package/dist/store-routing.js +2 -2
  58. package/dist/sync/git-state.d.ts +13 -0
  59. package/dist/sync/git-state.js +22 -0
  60. package/dist/sync/store-merge.d.ts +2 -0
  61. package/dist/sync/store-merge.js +6 -1
  62. package/dist/test-global-setup.js +7 -0
  63. package/dist/tools/data.js +1 -1
  64. package/dist/tools/finding.js +1 -1
  65. package/dist/tools/search.js +1 -1
  66. package/dist/tools/tasks.js +1 -1
  67. package/package.json +1 -1
  68. package/starter/global/skills/conductor/SKILL.md +2 -2
@@ -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>;
@@ -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
@@ -9,7 +9,7 @@ import { resolveAllStores } from "../store-registry.js";
9
9
  import { publicComputerKey } from "./computers.js";
10
10
  import { hookPeers, peerRequest } from "./peers.js";
11
11
  import { BridgeError, bridgeRoot, errorCode } from "./protocol.js";
12
- import { canonicalComputer, readScheduleDocument, readScheduleRuns, scheduleRunsFile } from "./schedules.js";
12
+ import { canonicalComputer, latestScheduleBatch, readScheduleDocument, readScheduleRuns, scheduleRunsFile } from "./schedules.js";
13
13
  import { countGit } from "./metrics.js";
14
14
  import { tmuxHealth } from "./terminal-tmux.js";
15
15
  const exec = promisify(execFile);
@@ -134,14 +134,18 @@ export async function storeSync(store) {
134
134
  /** The newest run in schedule-runs.jsonl, with its schedule's name when the project still has it. */
135
135
  export async function lastScheduledRun(store, runsFile = scheduleRunsFile()) {
136
136
  const runs = await readScheduleRuns(runsFile).catch(() => []);
137
- const last = runs.reduce((newest, run) => !newest || run.startedAt >= newest.startedAt ? run : newest, undefined);
138
- if (!last)
137
+ const newest = runs.reduce((newest, run) => !newest || run.startedAt >= newest.startedAt ? run : newest, undefined);
138
+ if (!newest)
139
139
  return null;
140
+ const owner = newest.scheduleProject ?? newest.project;
141
+ const matching = runs.filter(run => (run.scheduleProject ?? run.project) === owner && run.scheduleId === newest.scheduleId
142
+ && (newest.batchId ? run.batchId === newest.batchId : run.id === newest.id));
143
+ const last = latestScheduleBatch(matching).lastRun;
140
144
  let name;
141
- const directory = getProjectDirs(store).find(dir => path.basename(dir).toLowerCase() === last.project.toLowerCase());
145
+ const directory = getProjectDirs(store).find(dir => path.basename(dir).toLowerCase() === owner.toLowerCase());
142
146
  if (directory)
143
147
  name = (await readScheduleDocument(directory).catch(() => undefined))?.schedules.find(item => item.id === last.scheduleId)?.name;
144
- return { ...(name ? { name } : {}), project: last.project, status: last.status, ...(last.reason ? { reason: plainError(last.reason) } : {}),
148
+ return { ...(name ? { name } : {}), project: owner, status: last.status, ...(last.reason ? { reason: plainError(last.reason) } : {}),
145
149
  startedAt: last.startedAt, ...(last.finishedAt ? { finishedAt: last.finishedAt } : {}) };
146
150
  }
147
151
  /** This computer's public SSH host key, the pin a peer's hooks.yaml holds for it. */
@@ -670,5 +670,10 @@ export async function trustedDirectory(pane) {
670
670
  const cwd = pane.foreground_cwd || pane.cwd;
671
671
  if (typeof cwd !== "string" || !path.isAbsolute(cwd))
672
672
  throw new BridgeError(409, "This pane has no project folder.");
673
- return realpath(cwd);
673
+ try {
674
+ return await realpath(cwd);
675
+ }
676
+ catch {
677
+ throw new BridgeError(409, "This pane's project folder is no longer available. Reopen the chat from its current checkout.");
678
+ }
674
679
  }
@@ -7,9 +7,18 @@ import { herdrRoot } from "./herdr.js";
7
7
  import { phrenStoreRoot } from "./transcripts.js";
8
8
  const PROJECT_NAME = /^[a-z0-9][a-z0-9-]*$/;
9
9
  const SEARCH_ROOTS = ["", "Sites", "Projects", "projects", "Code", "code", "dev", "src", "repos", "workspace"];
10
+ function realHome() {
11
+ try {
12
+ return realpathSync.native(homedir());
13
+ }
14
+ catch {
15
+ return path.resolve(homedir());
16
+ }
17
+ }
10
18
  export async function locateProject(project, activity, env = process.env) {
11
19
  if (!PROJECT_NAME.test(project) || project.length > 100)
12
20
  throw new BridgeError(400, "Invalid project name.");
21
+ const home = realHome();
13
22
  const found = [];
14
23
  const seen = new Set();
15
24
  const offer = async (directory, source, lastSeen) => {
@@ -24,6 +33,11 @@ export async function locateProject(project, activity, env = process.env) {
24
33
  catch {
25
34
  return; /* not on this computer */
26
35
  }
36
+ // A folder that contains the home folder holds every project, so it is
37
+ // never one: a project named after the user ("sam") must not be offered
38
+ // /home/sam because every journal path runs through it.
39
+ if (dir === path.parse(dir).root || home === dir || home.startsWith(dir + path.sep))
40
+ return;
27
41
  if (seen.has(dir))
28
42
  return;
29
43
  seen.add(dir);
@@ -67,7 +81,6 @@ export async function locateProject(project, activity, env = process.env) {
67
81
  }
68
82
  catch { /* unregistered */ }
69
83
  // 4. The roots phren's locator searches.
70
- const home = homedir();
71
84
  for (const root of [...(env.PROJECTS_DIR ? [env.PROJECTS_DIR] : []), ...SEARCH_ROOTS.map(r => path.join(home, r))]) {
72
85
  await offer(path.join(root, project), "search");
73
86
  }