@phren/cli 0.3.78 → 0.3.80
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.
- package/dist/bridge/dispatch.js +17 -3
- package/dist/bridge/files.d.ts +1 -1
- package/dist/bridge/housekeeping/command.d.ts +5 -0
- package/dist/bridge/housekeeping/command.js +106 -0
- package/dist/bridge/housekeeping/housekeeper.d.ts +123 -0
- package/dist/bridge/housekeeping/housekeeper.js +459 -0
- package/dist/bridge/housekeeping/inventory.d.ts +145 -0
- package/dist/bridge/housekeeping/inventory.js +276 -0
- package/dist/bridge/housekeeping/report.d.ts +672 -0
- package/dist/bridge/housekeeping/report.js +168 -0
- package/dist/bridge/housekeeping/safety.d.ts +177 -0
- package/dist/bridge/housekeeping/safety.js +466 -0
- package/dist/bridge/owner-proof.d.ts +41 -0
- package/dist/bridge/owner-proof.js +119 -0
- package/dist/bridge/push.js +3 -1
- package/dist/bridge/resources.d.ts +8 -0
- package/dist/bridge/resources.js +18 -5
- package/dist/bridge/server-pane-routes.d.ts +6 -0
- package/dist/bridge/server-pane-routes.js +1 -1
- package/dist/bridge/server-routes.d.ts +6 -0
- package/dist/bridge/server-routes.js +53 -4
- package/dist/bridge/server.js +44 -8
- package/dist/bridge-hook.mjs +3093 -1219
- package/dist/cli-registry.js +18 -1
- package/dist/fanout/command.js +42 -15
- package/dist/heavy/budget-status.d.ts +26 -0
- package/dist/heavy/budget-status.js +26 -0
- package/dist/heavy/budget.d.ts +39 -0
- package/dist/heavy/budget.js +57 -0
- package/dist/heavy/command.d.ts +15 -0
- package/dist/heavy/command.js +119 -0
- package/dist/heavy/reap.d.ts +70 -0
- package/dist/heavy/reap.js +211 -0
- package/dist/heavy/slots.d.ts +58 -0
- package/dist/heavy/slots.js +142 -0
- package/dist/modules/registry.js +5 -4
- package/package.json +1 -1
- package/starter/global/skills/conductor/SKILL.md +10 -0
- package/starter/global/skills/fanout/SKILL.md +30 -0
|
@@ -0,0 +1,466 @@
|
|
|
1
|
+
import { execFile } from "node:child_process";
|
|
2
|
+
import { lstat, readdir, readlink, realpath, rm, stat } from "node:fs/promises";
|
|
3
|
+
import { homedir } from "node:os";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import { promisify } from "node:util";
|
|
6
|
+
import { git as runGit } from "../projects.js";
|
|
7
|
+
/**
|
|
8
|
+
* The housekeeping safety rules. Every housekeeping check and action goes
|
|
9
|
+
* through this module; nothing else in `bridge/housekeeping/` may run git,
|
|
10
|
+
* delete a path or remove a worktree. The rules come from the owner, after
|
|
11
|
+
* the 2026-11-08 incident in which a cleanup worker deleted worktrees with
|
|
12
|
+
* unpushed commits and ran `git reset --hard` across about 24 repositories:
|
|
13
|
+
*
|
|
14
|
+
* 1. Never delete a worktree or repository that has uncommitted changes,
|
|
15
|
+
* untracked files, commits on no remote, a stash, an operation in
|
|
16
|
+
* progress, a dirty or unpushed submodule, a live process inside it or a
|
|
17
|
+
* pane bound to it. Inspection that fails counts as a blocker.
|
|
18
|
+
* 2. Never run git reset, checkout, clean, restore, switch, push, branch or a
|
|
19
|
+
* stash change, and never pass --force. Git runs only through
|
|
20
|
+
* `housekeepingGit`, which admits a fixed set of read-only commands plus
|
|
21
|
+
* `worktree remove` (without force) and `worktree prune`.
|
|
22
|
+
* 3. Suggest by default. Only a path inside an allow-listed cache root,
|
|
23
|
+
* old enough and not in use, may be acted on without the owner.
|
|
24
|
+
*/
|
|
25
|
+
const exec = promisify(execFile);
|
|
26
|
+
// ---------------------------------------------------------------------------
|
|
27
|
+
// Rule 2: the git gate.
|
|
28
|
+
export class SafetyViolation extends Error {
|
|
29
|
+
code;
|
|
30
|
+
constructor(code, message) {
|
|
31
|
+
super(message);
|
|
32
|
+
this.code = code;
|
|
33
|
+
this.name = "SafetyViolation";
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
/** Subcommands that only read. */
|
|
37
|
+
const READ_ONLY = new Set(["status", "rev-list", "rev-parse", "for-each-ref", "symbolic-ref", "log", "show-ref", "ls-files"]);
|
|
38
|
+
/** Subcommands that discard or rewrite work; named so the refusal says why. */
|
|
39
|
+
const BANNED = new Set(["reset", "checkout", "clean", "restore", "switch", "push", "branch", "rebase", "merge", "pull", "fetch",
|
|
40
|
+
"commit", "am", "cherry-pick", "revert", "rm", "mv", "gc", "prune", "reflog", "update-ref", "filter-branch", "replace", "tag", "notes", "config"]);
|
|
41
|
+
/** Throws unless `args` is a git invocation housekeeping may run. Global
|
|
42
|
+
* options before the subcommand (-c, -C, --git-dir, --work-tree) are refused
|
|
43
|
+
* outright: they could re-target or reconfigure the command. */
|
|
44
|
+
export function assertHousekeepingGit(args) {
|
|
45
|
+
const [sub, ...rest] = args;
|
|
46
|
+
if (!sub || sub.startsWith("-"))
|
|
47
|
+
throw new SafetyViolation("git-global-option", `Housekeeping never passes git global options (${sub ?? "none"}).`);
|
|
48
|
+
for (const arg of rest) {
|
|
49
|
+
if (arg === "--")
|
|
50
|
+
break;
|
|
51
|
+
if (arg === "--force" || arg === "-f" || /^-[a-zA-Z]*f[a-zA-Z]*$/.test(arg) && sub === "worktree" || arg.startsWith("--force"))
|
|
52
|
+
throw new SafetyViolation("git-force", `Housekeeping never forces a git command (git ${sub} ${arg}).`);
|
|
53
|
+
}
|
|
54
|
+
if (BANNED.has(sub))
|
|
55
|
+
throw new SafetyViolation("git-banned", `Housekeeping never runs git ${sub}.`);
|
|
56
|
+
if (READ_ONLY.has(sub))
|
|
57
|
+
return;
|
|
58
|
+
const verb = rest[0];
|
|
59
|
+
if (sub === "stash" && verb === "list")
|
|
60
|
+
return;
|
|
61
|
+
if (sub === "submodule" && verb === "status")
|
|
62
|
+
return;
|
|
63
|
+
if (sub === "worktree" && (verb === "list" || verb === "remove"))
|
|
64
|
+
return;
|
|
65
|
+
if (sub === "worktree" && verb === "prune" && rest.every(arg => ["prune", "--dry-run", "-n", "--verbose", "-v"].includes(arg)))
|
|
66
|
+
return;
|
|
67
|
+
throw new SafetyViolation("git-not-allowed", `Housekeeping may not run git ${[sub, verb].filter(Boolean).join(" ")}.`);
|
|
68
|
+
}
|
|
69
|
+
/** The only git runner housekeeping uses. */
|
|
70
|
+
export async function housekeepingGit(cwd, ...args) {
|
|
71
|
+
assertHousekeepingGit(args);
|
|
72
|
+
return runGit(cwd, ...args);
|
|
73
|
+
}
|
|
74
|
+
const PLAIN = {
|
|
75
|
+
"not-a-checkout": "It isn't a checkout Phren can inspect.",
|
|
76
|
+
symlink: "It is a symbolic link; Phren never follows one.",
|
|
77
|
+
"inspection-failed": "Phren couldn't check it, so it stays.",
|
|
78
|
+
"main-checkout": "It is the repository's main checkout.",
|
|
79
|
+
"linked-worktrees": "Other worktrees depend on it.",
|
|
80
|
+
locked: "The worktree is locked.",
|
|
81
|
+
"uncommitted-changes": "It has uncommitted changes.",
|
|
82
|
+
"untracked-files": "It has untracked files.",
|
|
83
|
+
"unpushed-commits": "It has commits that aren't on any remote.",
|
|
84
|
+
stash: "The repository has stashed changes.",
|
|
85
|
+
"in-progress-operation": "A rebase, merge or similar is in progress.",
|
|
86
|
+
"dirty-submodule": "A submodule has uncommitted changes.",
|
|
87
|
+
"unpushed-submodule": "A submodule has commits that aren't on any remote.",
|
|
88
|
+
"live-process": "A process is using it now.",
|
|
89
|
+
"bound-pane": "An agent pane is working in it.",
|
|
90
|
+
"in-use": "Something is using it now.",
|
|
91
|
+
};
|
|
92
|
+
/** One plain sentence for the first blocker, for the phone. */
|
|
93
|
+
export function plainReason(blockers) {
|
|
94
|
+
return blockers.length ? PLAIN[blockers[0].code] : "";
|
|
95
|
+
}
|
|
96
|
+
const IN_PROGRESS = ["rebase-merge", "rebase-apply", "MERGE_HEAD", "CHERRY_PICK_HEAD", "REVERT_HEAD", "BISECT_LOG"];
|
|
97
|
+
const inside = (child, parent) => child === parent || child.startsWith(parent.endsWith(path.sep) ? parent : parent + path.sep);
|
|
98
|
+
const exists = (p) => lstat(p).then(() => true, () => false);
|
|
99
|
+
async function canonical(p) { return realpath(p).catch(() => path.resolve(p)); }
|
|
100
|
+
/** Processes and panes whose folder is `dir` or inside it. */
|
|
101
|
+
export async function inUseBlockers(dir, sources) {
|
|
102
|
+
const blockers = [];
|
|
103
|
+
const [processes, panes] = await Promise.all([sources.processes(), sources.panes()]);
|
|
104
|
+
for (const proc of processes) {
|
|
105
|
+
if (proc.pid === process.pid)
|
|
106
|
+
continue;
|
|
107
|
+
if (inside(await canonical(proc.cwd), dir))
|
|
108
|
+
blockers.push({ code: "live-process", detail: `pid ${proc.pid}${proc.command ? ` (${proc.command})` : ""} runs in ${proc.cwd}` });
|
|
109
|
+
}
|
|
110
|
+
for (const pane of panes) {
|
|
111
|
+
if (inside(await canonical(pane.cwd), dir))
|
|
112
|
+
blockers.push({ code: "bound-pane", detail: `pane ${pane.pane}${pane.title ? ` (${pane.title})` : ""} runs in ${pane.cwd}` });
|
|
113
|
+
}
|
|
114
|
+
return blockers;
|
|
115
|
+
}
|
|
116
|
+
async function submoduleBlockers(dir) {
|
|
117
|
+
const blockers = [];
|
|
118
|
+
const output = await housekeepingGit(dir, "submodule", "status", "--recursive");
|
|
119
|
+
for (const line of output.split("\n")) {
|
|
120
|
+
if (!line.trim() || line[0] === "-")
|
|
121
|
+
continue; // uninitialized: nothing checked out to lose
|
|
122
|
+
const rest = /^[ +U]/.test(line) ? line.slice(1) : line;
|
|
123
|
+
const space = rest.indexOf(" ");
|
|
124
|
+
if (space < 0)
|
|
125
|
+
continue;
|
|
126
|
+
let sub = rest.slice(space + 1);
|
|
127
|
+
const describe = sub.lastIndexOf(" (");
|
|
128
|
+
if (describe > 0 && sub.endsWith(")"))
|
|
129
|
+
sub = sub.slice(0, describe);
|
|
130
|
+
const checkout = path.join(dir, sub);
|
|
131
|
+
if (!(await stat(checkout).catch(() => undefined))?.isDirectory())
|
|
132
|
+
continue;
|
|
133
|
+
if ((await housekeepingGit(checkout, "status", "--porcelain=v1", "--untracked-files=normal")).trim())
|
|
134
|
+
blockers.push({ code: "dirty-submodule", detail: `submodule ${sub} has uncommitted changes` });
|
|
135
|
+
const unpushed = Number((await housekeepingGit(checkout, "rev-list", "--count", "HEAD", "--not", "--remotes")).trim()) || 0;
|
|
136
|
+
if (unpushed > 0)
|
|
137
|
+
blockers.push({ code: "unpushed-submodule", detail: `submodule ${sub} has ${unpushed} commit(s) on no remote` });
|
|
138
|
+
}
|
|
139
|
+
return blockers;
|
|
140
|
+
}
|
|
141
|
+
/**
|
|
142
|
+
* What `dir` holds and every reason it must not be deleted (no blockers means
|
|
143
|
+
* nothing would be lost). `worktree`: a linked worktree, removed with `git
|
|
144
|
+
* worktree remove`; only its HEAD's commits matter, since its branch stays.
|
|
145
|
+
* `repository`: the whole repository folder; every local branch counts, and
|
|
146
|
+
* linked worktrees block. Stashes block either way: the owner's rule names
|
|
147
|
+
* them without exception.
|
|
148
|
+
*/
|
|
149
|
+
export async function inspectCheckout(dir, target, sources) {
|
|
150
|
+
const info = await lstat(dir).catch(() => undefined);
|
|
151
|
+
if (!info)
|
|
152
|
+
return { blockers: [{ code: "not-a-checkout", detail: `${dir} does not exist` }] };
|
|
153
|
+
if (info.isSymbolicLink())
|
|
154
|
+
return { blockers: [{ code: "symlink", detail: `${dir} is a symbolic link; housekeeping never follows one` }] };
|
|
155
|
+
if (!info.isDirectory())
|
|
156
|
+
return { blockers: [{ code: "not-a-checkout", detail: `${dir} is not a folder` }] };
|
|
157
|
+
const abs = await canonical(dir);
|
|
158
|
+
const blockers = [];
|
|
159
|
+
let facts;
|
|
160
|
+
try {
|
|
161
|
+
const top = await canonical((await housekeepingGit(abs, "rev-parse", "--show-toplevel")).trim());
|
|
162
|
+
if (top !== abs)
|
|
163
|
+
return { blockers: [{ code: "not-a-checkout", detail: `${dir} is inside ${top}, not a checkout root` }] };
|
|
164
|
+
const gitDir = await canonical(path.resolve(abs, (await housekeepingGit(abs, "rev-parse", "--git-dir")).trim()));
|
|
165
|
+
const commonDir = await canonical(path.resolve(abs, (await housekeepingGit(abs, "rev-parse", "--git-common-dir")).trim()));
|
|
166
|
+
const isMain = gitDir === commonDir;
|
|
167
|
+
const worktrees = parseWorktreeList(await housekeepingGit(abs, "worktree", "list", "--porcelain"));
|
|
168
|
+
if (target === "worktree" && isMain)
|
|
169
|
+
blockers.push({ code: "main-checkout", detail: "this is the repository's main checkout, not a linked worktree" });
|
|
170
|
+
if (target === "repository") {
|
|
171
|
+
const linked = worktrees.filter(w => w.path !== abs && !w.prunable);
|
|
172
|
+
if (linked.length)
|
|
173
|
+
blockers.push({ code: "linked-worktrees", detail: `${linked.length} linked worktree(s) depend on it: ${linked.map(w => w.path).slice(0, 5).join(", ")}` });
|
|
174
|
+
}
|
|
175
|
+
const self = worktrees.find(w => w.path === abs);
|
|
176
|
+
if (self?.locked !== undefined)
|
|
177
|
+
blockers.push({ code: "locked", detail: `worktree is locked${self.locked ? `: ${self.locked}` : ""}` });
|
|
178
|
+
const status = (await housekeepingGit(abs, "status", "--porcelain=v1", "-z", "--untracked-files=normal", "--ignore-submodules=none")).split("\0").filter(Boolean);
|
|
179
|
+
let tracked = 0, untracked = 0;
|
|
180
|
+
for (let i = 0; i < status.length; i++) {
|
|
181
|
+
const code = status[i].slice(0, 2);
|
|
182
|
+
if (code === "??")
|
|
183
|
+
untracked++;
|
|
184
|
+
else
|
|
185
|
+
tracked++;
|
|
186
|
+
if (/[RC]/.test(code))
|
|
187
|
+
i++;
|
|
188
|
+
}
|
|
189
|
+
if (tracked)
|
|
190
|
+
blockers.push({ code: "uncommitted-changes", detail: `${tracked} changed tracked path(s)` });
|
|
191
|
+
if (untracked)
|
|
192
|
+
blockers.push({ code: "untracked-files", detail: `${untracked} untracked path(s) not ignored` });
|
|
193
|
+
const hasHead = await housekeepingGit(abs, "rev-parse", "--verify", "--quiet", "HEAD").then(() => true, () => false);
|
|
194
|
+
let unpushed = 0, lastCommitAt;
|
|
195
|
+
if (hasHead) {
|
|
196
|
+
const refs = target === "repository" ? ["HEAD", "--branches"] : ["HEAD"];
|
|
197
|
+
unpushed = Number((await housekeepingGit(abs, "rev-list", "--count", ...refs, "--not", "--remotes")).trim()) || 0;
|
|
198
|
+
if (unpushed > 0)
|
|
199
|
+
blockers.push({ code: "unpushed-commits", detail: `${unpushed} commit(s) on no remote branch` });
|
|
200
|
+
const stamp = (await housekeepingGit(abs, "log", "-1", "--format=%cI", "HEAD")).trim();
|
|
201
|
+
if (stamp)
|
|
202
|
+
lastCommitAt = new Date(stamp).toISOString();
|
|
203
|
+
}
|
|
204
|
+
const stashes = (await housekeepingGit(abs, "stash", "list")).split("\n").filter(Boolean);
|
|
205
|
+
if (stashes.length)
|
|
206
|
+
blockers.push({ code: "stash", detail: `${stashes.length} stash entr${stashes.length === 1 ? "y" : "ies"}` });
|
|
207
|
+
const inProgress = [];
|
|
208
|
+
for (const marker of IN_PROGRESS) {
|
|
209
|
+
if (await exists(path.join(gitDir, marker))) {
|
|
210
|
+
inProgress.push(marker);
|
|
211
|
+
blockers.push({ code: "in-progress-operation", detail: `${marker} is present: an operation is in progress` });
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
blockers.push(...await submoduleBlockers(abs));
|
|
215
|
+
const mainPath = worktrees[0] && !worktrees[0].bare ? worktrees[0].path : undefined;
|
|
216
|
+
facts = { main: isMain, ...(self?.branch ? { branch: self.branch } : {}), ...(mainPath ? { repo: mainPath } : {}),
|
|
217
|
+
dirty: tracked, untracked, unpushed, stashes: stashes.length, inProgress, locked: self?.locked !== undefined, ...(lastCommitAt ? { lastCommitAt } : {}) };
|
|
218
|
+
}
|
|
219
|
+
catch (error) {
|
|
220
|
+
// Fail closed: what could not be inspected is kept.
|
|
221
|
+
blockers.push({ code: "inspection-failed", detail: error instanceof Error ? error.message.slice(0, 300) : String(error) });
|
|
222
|
+
}
|
|
223
|
+
try {
|
|
224
|
+
blockers.push(...await inUseBlockers(abs, sources));
|
|
225
|
+
}
|
|
226
|
+
catch (error) {
|
|
227
|
+
blockers.push({ code: "inspection-failed", detail: `could not list processes or panes: ${error instanceof Error ? error.message : error}` });
|
|
228
|
+
}
|
|
229
|
+
return { ...(facts ? { facts } : {}), blockers };
|
|
230
|
+
}
|
|
231
|
+
/** Every reason `dir` must not be deleted; see `inspectCheckout`. */
|
|
232
|
+
export async function checkoutBlockers(dir, target, sources) {
|
|
233
|
+
return (await inspectCheckout(dir, target, sources)).blockers;
|
|
234
|
+
}
|
|
235
|
+
export function parseWorktreeList(porcelain) {
|
|
236
|
+
const out = [];
|
|
237
|
+
let current;
|
|
238
|
+
for (const line of porcelain.split("\n")) {
|
|
239
|
+
if (line.startsWith("worktree ")) {
|
|
240
|
+
current = { path: line.slice(9) };
|
|
241
|
+
out.push(current);
|
|
242
|
+
continue;
|
|
243
|
+
}
|
|
244
|
+
if (!current)
|
|
245
|
+
continue;
|
|
246
|
+
if (line.startsWith("branch "))
|
|
247
|
+
current.branch = line.slice(7).replace(/^refs\/heads\//, "");
|
|
248
|
+
else if (line === "locked" || line.startsWith("locked "))
|
|
249
|
+
current.locked = line.slice(7);
|
|
250
|
+
else if (line === "prunable" || line.startsWith("prunable "))
|
|
251
|
+
current.prunable = line.slice(9) || "prunable";
|
|
252
|
+
else if (line === "bare")
|
|
253
|
+
current.bare = true;
|
|
254
|
+
}
|
|
255
|
+
return out;
|
|
256
|
+
}
|
|
257
|
+
/** Remove a linked worktree only if it has no blockers right now, re-checked
|
|
258
|
+
* against fresh state, and only with plain `git worktree remove`. A refusal
|
|
259
|
+
* from git leaves the worktree where it is; nothing retries with force. */
|
|
260
|
+
export async function removeWorktreeSafely(dir, sources) {
|
|
261
|
+
const blockers = await checkoutBlockers(dir, "worktree", sources);
|
|
262
|
+
if (blockers.length)
|
|
263
|
+
return { removed: false, blockers };
|
|
264
|
+
const abs = await canonical(dir);
|
|
265
|
+
await housekeepingGit(abs, "worktree", "remove", "--", abs);
|
|
266
|
+
return { removed: true, blockers: [] };
|
|
267
|
+
}
|
|
268
|
+
/** Caches the disk-janitor proved safe to remove; every other path is
|
|
269
|
+
* suggest-only. Platform-specific roots are listed only where they exist. */
|
|
270
|
+
export function cacheRules(home = homedir(), platform = process.platform) {
|
|
271
|
+
const rules = [
|
|
272
|
+
{ id: "phren-ci-builds", root: path.join(home, "phren-ci-builds"), minAgeDays: 7 },
|
|
273
|
+
{ id: "npm-cacache", root: path.join(home, ".npm", "_cacache"), minAgeDays: 30 },
|
|
274
|
+
];
|
|
275
|
+
if (platform === "darwin")
|
|
276
|
+
rules.push({ id: "xctest-devices", root: path.join(home, "Library/Developer/XCTestDevices"), minAgeDays: 2 }, { id: "derived-data", root: path.join(home, "Library/Developer/Xcode/DerivedData"), minAgeDays: 14 }, { id: "ios-device-support", root: path.join(home, "Library/Developer/Xcode/iOS DeviceSupport"), minAgeDays: 90 }, { id: "swiftpm-cache", root: path.join(home, "Library/Caches/org.swift.swiftpm"), minAgeDays: 30 });
|
|
277
|
+
return rules;
|
|
278
|
+
}
|
|
279
|
+
/** Paths housekeeping never acts on, whatever a rule says. DeviceFS is a live
|
|
280
|
+
* view of booted simulators that `du` reports as ~160 GB; docker volumes hold
|
|
281
|
+
* data; the store and project folders hold work. */
|
|
282
|
+
export function protectedRoots(home = homedir()) {
|
|
283
|
+
return [
|
|
284
|
+
path.join(home, "Library/Developer/CoreDevice"),
|
|
285
|
+
"/var/lib/docker/volumes",
|
|
286
|
+
path.join(home, ".docker/volumes"),
|
|
287
|
+
path.join(home, ".phren"),
|
|
288
|
+
path.join(home, "Projects"),
|
|
289
|
+
path.join(home, "Sites"),
|
|
290
|
+
path.join(home, ".ssh"),
|
|
291
|
+
];
|
|
292
|
+
}
|
|
293
|
+
/**
|
|
294
|
+
* Whether `target` may be removed without the owner. `auto` only for an entry
|
|
295
|
+
* strictly inside an allow-listed root (resolved without following a link at
|
|
296
|
+
* the target), past the rule's age, under no protected root, and with no
|
|
297
|
+
* process or pane in it. Anything else is `suggest` (the owner may approve)
|
|
298
|
+
* or `keep` (a safety rule holds it).
|
|
299
|
+
*/
|
|
300
|
+
export async function cacheDecision(target, context) {
|
|
301
|
+
const info = await lstat(target).catch(() => undefined);
|
|
302
|
+
if (!info)
|
|
303
|
+
return { verdict: "keep", reason: "missing" };
|
|
304
|
+
if (info.isSymbolicLink())
|
|
305
|
+
return { verdict: "keep", reason: "symlink" };
|
|
306
|
+
// Resolve the parent, not the target, so a link at the target is never followed.
|
|
307
|
+
const abs = path.join(await canonical(path.dirname(target)), path.basename(target));
|
|
308
|
+
for (const root of context.protected ?? protectedRoots()) {
|
|
309
|
+
const real = await canonical(root);
|
|
310
|
+
if (inside(abs, real) || inside(real, abs))
|
|
311
|
+
return { verdict: "keep", reason: "protected-path" };
|
|
312
|
+
}
|
|
313
|
+
let matched;
|
|
314
|
+
for (const rule of context.rules ?? cacheRules()) {
|
|
315
|
+
const root = await canonical(rule.root);
|
|
316
|
+
if (abs !== root && inside(abs, root)) {
|
|
317
|
+
matched = rule;
|
|
318
|
+
break;
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
if (!matched)
|
|
322
|
+
return { verdict: "suggest", reason: "outside-allowlist" };
|
|
323
|
+
const ageDays = ((context.now ?? Date.now()) - info.mtimeMs) / 86_400_000;
|
|
324
|
+
if (ageDays < matched.minAgeDays)
|
|
325
|
+
return { verdict: "suggest", rule: matched.id, reason: "too-recent" };
|
|
326
|
+
const blockers = await inUseBlockers(abs, context).catch(error => [{ code: "inspection-failed", detail: String(error) }]);
|
|
327
|
+
if (blockers.length)
|
|
328
|
+
return { verdict: "keep", rule: matched.id, reason: "in-use", blockers };
|
|
329
|
+
return { verdict: "auto", rule: matched.id };
|
|
330
|
+
}
|
|
331
|
+
/** Delete an allow-listed cache entry, re-deciding against fresh state first.
|
|
332
|
+
* Refuses (returns the decision) unless the decision is `auto` now, or the
|
|
333
|
+
* owner approved it and the only thing short of `auto` is its age: an owner
|
|
334
|
+
* may clear a recent cache entry, never a path outside the cache roots. */
|
|
335
|
+
export async function removeCacheEntry(target, context, ownerApproved = false) {
|
|
336
|
+
const decision = await cacheDecision(target, context);
|
|
337
|
+
const approvedRecent = ownerApproved && decision.verdict === "suggest" && decision.reason === "too-recent";
|
|
338
|
+
if (decision.verdict !== "auto" && !approvedRecent)
|
|
339
|
+
return { removed: false, decision };
|
|
340
|
+
await rm(target, { recursive: true, force: false, maxRetries: 0 });
|
|
341
|
+
return { removed: true, decision };
|
|
342
|
+
}
|
|
343
|
+
// ---------------------------------------------------------------------------
|
|
344
|
+
// Owner-approved deletions beyond the caches: /tmp entries and node_modules.
|
|
345
|
+
/** Scratch roots whose direct children the owner may delete. */
|
|
346
|
+
export function tmpRoots(platform = process.platform) {
|
|
347
|
+
return platform === "darwin" ? ["/private/tmp"] : ["/tmp"];
|
|
348
|
+
}
|
|
349
|
+
const TMP_MIN_AGE_MS = 24 * 3_600_000;
|
|
350
|
+
/**
|
|
351
|
+
* Whether the owner may delete `target`, decided now against the disk:
|
|
352
|
+
* - an entry inside an allow-listed cache root (any age, since the owner asked);
|
|
353
|
+
* - a direct child of a scratch root this user owns, untouched for a day, not
|
|
354
|
+
* a git checkout (those go through the worktree rules), with nothing in it;
|
|
355
|
+
* - a checkout's own `node_modules` (it has package.json), with nothing
|
|
356
|
+
* running in that checkout.
|
|
357
|
+
* Never a symlink, never under a protected root except that node_modules.
|
|
358
|
+
*/
|
|
359
|
+
export async function deletionDecision(target, context) {
|
|
360
|
+
const info = await lstat(target).catch(() => undefined);
|
|
361
|
+
if (!info)
|
|
362
|
+
return { allowed: false, reason: "It is already gone." };
|
|
363
|
+
if (info.isSymbolicLink())
|
|
364
|
+
return { allowed: false, reason: "It is a symbolic link; Phren never follows one." };
|
|
365
|
+
const parent = await canonical(path.dirname(target));
|
|
366
|
+
const abs = path.join(parent, path.basename(target));
|
|
367
|
+
const inUse = async (dir) => {
|
|
368
|
+
const blockers = await inUseBlockers(dir, context).catch(error => [{ code: "inspection-failed", detail: String(error) }]);
|
|
369
|
+
return blockers.length ? { allowed: false, reason: plainReason(blockers), blockers } : undefined;
|
|
370
|
+
};
|
|
371
|
+
if (path.basename(abs) === "node_modules" && info.isDirectory()) {
|
|
372
|
+
if (!await exists(path.join(parent, "package.json")) || !await exists(path.join(parent, ".git")))
|
|
373
|
+
return { allowed: false, reason: "Phren only clears node_modules at the top of a checkout." };
|
|
374
|
+
return await inUse(parent) ?? { allowed: true, rule: "node-modules" };
|
|
375
|
+
}
|
|
376
|
+
const cache = await cacheDecision(target, context);
|
|
377
|
+
if (cache.verdict === "auto")
|
|
378
|
+
return { allowed: true, rule: cache.rule };
|
|
379
|
+
if (cache.verdict === "suggest" && cache.rule)
|
|
380
|
+
return { allowed: true, rule: cache.rule }; // only too recent; the owner asked
|
|
381
|
+
if (cache.verdict === "keep" && cache.reason !== "protected-path")
|
|
382
|
+
return { allowed: false, reason: cache.blockers?.length ? plainReason(cache.blockers) : "Phren won't remove it.", ...(cache.blockers ? { blockers: cache.blockers } : {}) };
|
|
383
|
+
if (cache.verdict === "keep")
|
|
384
|
+
return { allowed: false, reason: "It is under a folder Phren never touches." };
|
|
385
|
+
for (const root of context.tmpRoots ?? tmpRoots()) {
|
|
386
|
+
if (parent !== await canonical(root))
|
|
387
|
+
continue;
|
|
388
|
+
if (info.uid !== (context.uid ?? process.getuid?.() ?? info.uid))
|
|
389
|
+
return { allowed: false, reason: "Another user owns it." };
|
|
390
|
+
if ((context.now ?? Date.now()) - info.mtimeMs < TMP_MIN_AGE_MS)
|
|
391
|
+
return { allowed: false, reason: "It was changed in the last day." };
|
|
392
|
+
if (info.isDirectory() && await exists(path.join(abs, ".git")))
|
|
393
|
+
return { allowed: false, reason: "It is a git checkout; remove it as a worktree." };
|
|
394
|
+
return await inUse(abs) ?? { allowed: true, rule: "tmp" };
|
|
395
|
+
}
|
|
396
|
+
return { allowed: false, reason: "Phren only deletes caches, scratch folders and node_modules." };
|
|
397
|
+
}
|
|
398
|
+
/** Delete what the owner approved, deciding again just before. */
|
|
399
|
+
export async function removeApprovedPath(target, context) {
|
|
400
|
+
const decision = await deletionDecision(target, context);
|
|
401
|
+
if (!decision.allowed)
|
|
402
|
+
return { removed: false, decision };
|
|
403
|
+
await rm(target, { recursive: true, force: false, maxRetries: 0 });
|
|
404
|
+
return { removed: true, decision };
|
|
405
|
+
}
|
|
406
|
+
/** Why a pane must stay open, or undefined if the owner may close it. A
|
|
407
|
+
* pane whose dispatch return is unread keeps the evidence (the 2026-11-08
|
|
408
|
+
* lesson); a working or waiting agent and the conductor stay too. */
|
|
409
|
+
export function paneCloseBlock(pane, dispatches) {
|
|
410
|
+
if (pane.role === "conductor")
|
|
411
|
+
return "It is the conductor.";
|
|
412
|
+
if (pane.status === "working")
|
|
413
|
+
return "Its agent is working.";
|
|
414
|
+
if (pane.status === "blocked" || pane.status === "waiting")
|
|
415
|
+
return "Its agent is waiting for an answer.";
|
|
416
|
+
for (const receipt of dispatches) {
|
|
417
|
+
if (receipt.closedAt || receipt.server !== pane.server || receipt.pane !== pane.pane)
|
|
418
|
+
continue;
|
|
419
|
+
if (!receipt.returned)
|
|
420
|
+
return "Its dispatched work hasn't returned yet.";
|
|
421
|
+
if (!receipt.returned.read)
|
|
422
|
+
return "Its return hasn't been read yet.";
|
|
423
|
+
}
|
|
424
|
+
return undefined;
|
|
425
|
+
}
|
|
426
|
+
/** What an item of a given kind may be: only a cache can ever be `auto`. */
|
|
427
|
+
export function allowedVerdict(kind, proposed) {
|
|
428
|
+
return proposed === "auto" && kind !== "cache" ? "suggest" : proposed;
|
|
429
|
+
}
|
|
430
|
+
// ---------------------------------------------------------------------------
|
|
431
|
+
// Production in-use sources.
|
|
432
|
+
/** Every process's working directory this user can see: `lsof` on macOS,
|
|
433
|
+
* `/proc/<pid>/cwd` on Linux. A failure throws, so callers fail closed. */
|
|
434
|
+
export async function liveProcessCwds(platform = process.platform) {
|
|
435
|
+
if (platform === "linux") {
|
|
436
|
+
const out = [];
|
|
437
|
+
for (const entry of await readdir("/proc")) {
|
|
438
|
+
if (!/^\d+$/.test(entry))
|
|
439
|
+
continue;
|
|
440
|
+
const cwd = await readlink(`/proc/${entry}/cwd`).catch(() => undefined);
|
|
441
|
+
if (cwd)
|
|
442
|
+
out.push({ pid: Number(entry), cwd });
|
|
443
|
+
}
|
|
444
|
+
return out;
|
|
445
|
+
}
|
|
446
|
+
// lsof exits 1 when some processes could not be read; its output is still valid.
|
|
447
|
+
const { stdout } = await exec("lsof", ["-n", "-P", "-d", "cwd", "-F", "pcn"], { timeout: 15_000, maxBuffer: 16 * 1024 * 1024 })
|
|
448
|
+
.catch((error) => { if (typeof error.stdout === "string" && error.stdout)
|
|
449
|
+
return { stdout: error.stdout }; throw error; });
|
|
450
|
+
return parseLsofCwds(stdout);
|
|
451
|
+
}
|
|
452
|
+
export function parseLsofCwds(output) {
|
|
453
|
+
const out = [];
|
|
454
|
+
let pid = 0, command;
|
|
455
|
+
for (const line of output.split("\n")) {
|
|
456
|
+
if (line.startsWith("p")) {
|
|
457
|
+
pid = Number(line.slice(1));
|
|
458
|
+
command = undefined;
|
|
459
|
+
}
|
|
460
|
+
else if (line.startsWith("c"))
|
|
461
|
+
command = line.slice(1);
|
|
462
|
+
else if (line.startsWith("n") && pid)
|
|
463
|
+
out.push({ pid, cwd: line.slice(1), ...(command ? { command } : {}) });
|
|
464
|
+
}
|
|
465
|
+
return out;
|
|
466
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import type { IncomingMessage } from "node:http";
|
|
2
|
+
import { type Json } from "./protocol.js";
|
|
3
|
+
/**
|
|
4
|
+
* Owner proof for the actions an agent must not take for itself: release
|
|
5
|
+
* authority, raising a pane's permission mode, making or stopping the
|
|
6
|
+
* conductor, registering for this computer's alerts and linking computers.
|
|
7
|
+
*
|
|
8
|
+
* Agents run as the same Unix user as the Hook, so no header or local file can
|
|
9
|
+
* tell the owner's phone from an agent's `nc -U hook.sock`. The phone holds its
|
|
10
|
+
* paired SSH key's private half, so it signs these requests with it (the same
|
|
11
|
+
* key that already signs approval rules). Once the Hook has seen one valid
|
|
12
|
+
* signature, unsigned requests to these routes are refused: older apps keep
|
|
13
|
+
* working until the phone starts signing, and after that an agent cannot.
|
|
14
|
+
*/
|
|
15
|
+
export declare const OWNER_PROOF_HEADER = "x-phren-owner-proof";
|
|
16
|
+
export declare const ownerProofRoute: (method: string | undefined, pathname: string) => boolean;
|
|
17
|
+
export declare const bodyDigest: (raw: Buffer) => string;
|
|
18
|
+
/** Paired phone keys (iPhone and Android) on the restricted dispatch command. Scoped, computer and plain keys cannot sign. */
|
|
19
|
+
export declare function deviceKeys(authorizedKeys: string): Set<string>;
|
|
20
|
+
export interface OwnerProofOptions {
|
|
21
|
+
root?: string;
|
|
22
|
+
keys?: () => Promise<Set<string>>;
|
|
23
|
+
now?: () => number;
|
|
24
|
+
}
|
|
25
|
+
export declare class OwnerProof {
|
|
26
|
+
private options;
|
|
27
|
+
private seen;
|
|
28
|
+
private required?;
|
|
29
|
+
constructor(options?: OwnerProofOptions);
|
|
30
|
+
private get root();
|
|
31
|
+
private get file();
|
|
32
|
+
private now;
|
|
33
|
+
private keys;
|
|
34
|
+
/** Whether a phone has signed before, so unsigned owner actions are refused. */
|
|
35
|
+
isRequired(): Promise<boolean>;
|
|
36
|
+
/**
|
|
37
|
+
* Throws 403 unless an owner-only request may go ahead. Requests that carry
|
|
38
|
+
* an agent or peer origin are left to the route, which refuses them anyway.
|
|
39
|
+
*/
|
|
40
|
+
check(request: Pick<IncomingMessage, "headers" | "method">, pathname: string, data: Json, digest: string | undefined): Promise<void>;
|
|
41
|
+
}
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
import { createHash, createPublicKey, verify } from "node:crypto";
|
|
2
|
+
import { lstat, readFile } from "node:fs/promises";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { z } from "zod";
|
|
5
|
+
import { homeDir } from "../home-paths.js";
|
|
6
|
+
import { atomic, BridgeError, bridgeRoot } from "./protocol.js";
|
|
7
|
+
import { ownerRequest } from "./request-origin.js";
|
|
8
|
+
/**
|
|
9
|
+
* Owner proof for the actions an agent must not take for itself: release
|
|
10
|
+
* authority, raising a pane's permission mode, making or stopping the
|
|
11
|
+
* conductor, registering for this computer's alerts and linking computers.
|
|
12
|
+
*
|
|
13
|
+
* Agents run as the same Unix user as the Hook, so no header or local file can
|
|
14
|
+
* tell the owner's phone from an agent's `nc -U hook.sock`. The phone holds its
|
|
15
|
+
* paired SSH key's private half, so it signs these requests with it (the same
|
|
16
|
+
* key that already signs approval rules). Once the Hook has seen one valid
|
|
17
|
+
* signature, unsigned requests to these routes are refused: older apps keep
|
|
18
|
+
* working until the phone starts signing, and after that an agent cannot.
|
|
19
|
+
*/
|
|
20
|
+
export const OWNER_PROOF_HEADER = "x-phren-owner-proof";
|
|
21
|
+
const DOMAIN = "phren-owner-request-v1";
|
|
22
|
+
const WINDOW_MS = 300_000;
|
|
23
|
+
const ROUTES = new Set([
|
|
24
|
+
"POST /v1/authority", "POST /v1/authority/confirm", "DELETE /v1/authority",
|
|
25
|
+
"POST /v1/agents/permission-mode",
|
|
26
|
+
"POST /v1/conductor/make", "POST /v1/conductor/stop",
|
|
27
|
+
"POST /v1/push/register",
|
|
28
|
+
"POST /v1/sets/link",
|
|
29
|
+
"POST /v1/housekeeping/approve", "POST /v1/housekeeping/dismiss", "POST /v1/housekeeping/restore", "POST /v1/housekeeping/scan",
|
|
30
|
+
]);
|
|
31
|
+
const payloadSchema = z.object({
|
|
32
|
+
domain: z.literal(DOMAIN), nonce: z.string().uuid(), at: z.string().datetime({ offset: true }),
|
|
33
|
+
method: z.enum(["POST", "DELETE"]), path: z.string().min(1).max(4096), body: z.string().regex(/^[a-f0-9]{64}$/),
|
|
34
|
+
}).strict();
|
|
35
|
+
const envelopeSchema = z.object({ payload: z.string().min(1).max(8192), signature: z.string().min(1).max(128), publicKey: z.string().min(1).max(64) }).strict();
|
|
36
|
+
export const ownerProofRoute = (method, pathname) => ROUTES.has(`${method} ${pathname}`);
|
|
37
|
+
export const bodyDigest = (raw) => createHash("sha256").update(raw).digest("hex");
|
|
38
|
+
/** Paired phone keys (iPhone and Android) on the restricted dispatch command. Scoped, computer and plain keys cannot sign. */
|
|
39
|
+
export function deviceKeys(authorizedKeys) {
|
|
40
|
+
const result = new Set();
|
|
41
|
+
for (const line of authorizedKeys.split("\n")) {
|
|
42
|
+
const match = /^restrict,pty,command="sh ~\/\.local\/share\/phren\/bridge\/dispatch" ssh-ed25519 ([A-Za-z0-9+/]+={0,2}) phren-(?:iphone|android)\s*$/.exec(line);
|
|
43
|
+
if (!match)
|
|
44
|
+
continue;
|
|
45
|
+
const wire = Buffer.from(match[1], "base64");
|
|
46
|
+
// SSH string("ssh-ed25519"), string(32-byte key).
|
|
47
|
+
if (wire.length === 51 && wire.readUInt32BE(0) === 11 && wire.subarray(4, 15).toString() === "ssh-ed25519" && wire.readUInt32BE(15) === 32)
|
|
48
|
+
result.add(wire.subarray(19).toString("base64"));
|
|
49
|
+
}
|
|
50
|
+
return result;
|
|
51
|
+
}
|
|
52
|
+
export class OwnerProof {
|
|
53
|
+
options;
|
|
54
|
+
seen = new Map();
|
|
55
|
+
required;
|
|
56
|
+
constructor(options = {}) {
|
|
57
|
+
this.options = options;
|
|
58
|
+
}
|
|
59
|
+
get root() { return this.options.root ?? bridgeRoot(); }
|
|
60
|
+
get file() { return path.join(this.root, "owner-proof.json"); }
|
|
61
|
+
now() { return (this.options.now ?? Date.now)(); }
|
|
62
|
+
async keys() {
|
|
63
|
+
if (this.options.keys)
|
|
64
|
+
return this.options.keys();
|
|
65
|
+
return deviceKeys(await readFile(path.join(homeDir(), ".ssh", "authorized_keys"), "utf8").catch(() => ""));
|
|
66
|
+
}
|
|
67
|
+
/** Whether a phone has signed before, so unsigned owner actions are refused. */
|
|
68
|
+
async isRequired() {
|
|
69
|
+
if (this.required)
|
|
70
|
+
return true;
|
|
71
|
+
const info = await lstat(this.file).catch(() => undefined);
|
|
72
|
+
this.required = !!info?.isFile();
|
|
73
|
+
return this.required;
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* Throws 403 unless an owner-only request may go ahead. Requests that carry
|
|
77
|
+
* an agent or peer origin are left to the route, which refuses them anyway.
|
|
78
|
+
*/
|
|
79
|
+
async check(request, pathname, data, digest) {
|
|
80
|
+
if (!ownerProofRoute(request.method, pathname) || !ownerRequest(request, data))
|
|
81
|
+
return;
|
|
82
|
+
const header = request.headers?.[OWNER_PROOF_HEADER];
|
|
83
|
+
if (typeof header !== "string") {
|
|
84
|
+
if (await this.isRequired())
|
|
85
|
+
throw new BridgeError(403, "Confirm this on your paired phone: this action needs its signature.", { code: "owner-proof-required" });
|
|
86
|
+
return;
|
|
87
|
+
}
|
|
88
|
+
const refused = () => new BridgeError(403, "The phone's signature for this action did not verify.", { code: "owner-proof-invalid" });
|
|
89
|
+
let envelope, payload;
|
|
90
|
+
try {
|
|
91
|
+
envelope = envelopeSchema.parse(JSON.parse(Buffer.from(header, "base64url").toString("utf8")));
|
|
92
|
+
payload = payloadSchema.parse(JSON.parse(Buffer.from(envelope.payload, "base64").toString("utf8")));
|
|
93
|
+
}
|
|
94
|
+
catch {
|
|
95
|
+
throw refused();
|
|
96
|
+
}
|
|
97
|
+
const raw = Buffer.from(envelope.publicKey, "base64"), signature = Buffer.from(envelope.signature, "base64");
|
|
98
|
+
if (raw.length !== 32 || signature.length !== 64 || !(await this.keys()).has(raw.toString("base64")))
|
|
99
|
+
throw refused();
|
|
100
|
+
const key = createPublicKey({ key: Buffer.concat([Buffer.from("302a300506032b6570032100", "hex"), raw]), format: "der", type: "spki" });
|
|
101
|
+
if (!verify(null, Buffer.from(envelope.payload, "base64"), key, signature))
|
|
102
|
+
throw refused();
|
|
103
|
+
const at = Date.parse(payload.at), now = this.now();
|
|
104
|
+
if (payload.method !== request.method || payload.path !== pathname || payload.body !== digest || !(Math.abs(now - at) <= WINDOW_MS))
|
|
105
|
+
throw refused();
|
|
106
|
+
for (const [nonce, until] of this.seen)
|
|
107
|
+
if (until < now)
|
|
108
|
+
this.seen.delete(nonce);
|
|
109
|
+
if (this.seen.has(payload.nonce))
|
|
110
|
+
throw refused();
|
|
111
|
+
if (this.seen.size >= 4096)
|
|
112
|
+
throw new BridgeError(429, "Too many signed owner actions. Try again in a few minutes.");
|
|
113
|
+
this.seen.set(payload.nonce, now + 2 * WINDOW_MS);
|
|
114
|
+
if (!(await this.isRequired())) {
|
|
115
|
+
await atomic(this.file, JSON.stringify({ since: new Date(now).toISOString(), key: createHash("sha256").update(raw).digest("hex") }));
|
|
116
|
+
this.required = true;
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
}
|
package/dist/bridge/push.js
CHANGED
|
@@ -67,7 +67,9 @@ export function fanoutBlockedPushPayload(value) {
|
|
|
67
67
|
export function machineHealthPushPayload(value, host) {
|
|
68
68
|
return {
|
|
69
69
|
aps: { alert: { title: `${value.computer}: ${value.title}`, body: `${value.detail} ${value.fix}`.trim() }, sound: "default", category: "PHREN_HEALTH" },
|
|
70
|
-
|
|
70
|
+
// `housekeeping`: the same finding is a housekeeping warning with this id; a newer app opens it there, an older one routes to resources.
|
|
71
|
+
phren: { kind: "machineHealth", ...(host ? { host } : {}), computer: value.computer, id: value.id, title: value.title, detail: value.detail, fix: value.fix, route: "resources",
|
|
72
|
+
housekeeping: { computer: value.computer, id: value.id } },
|
|
71
73
|
};
|
|
72
74
|
}
|
|
73
75
|
export function schedulePushPayload(value) {
|