@phren/cli 0.3.44 → 0.3.46
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/agent-hook-asks.d.ts +34 -0
- package/dist/bridge/agent-hook-asks.js +72 -0
- package/dist/bridge/agent-hook-callback.d.ts +22 -0
- package/dist/bridge/agent-hook-callback.js +114 -0
- package/dist/bridge/agent-hooks.d.ts +7 -74
- package/dist/bridge/agent-hooks.js +22 -186
- package/dist/bridge/claude-question-dialog.d.ts +6 -0
- package/dist/bridge/claude-question-dialog.js +29 -7
- package/dist/bridge/codex-app-server.d.ts +5 -0
- package/dist/bridge/codex-app-server.js +15 -0
- package/dist/bridge/codex-auth-refresh.js +7 -0
- package/dist/bridge/dispatch-command.js +7 -1
- package/dist/bridge/file-write.js +3 -1
- package/dist/bridge/git-host-auth.d.ts +6 -0
- package/dist/bridge/git-host-auth.js +45 -0
- package/dist/bridge/git-publish.d.ts +1 -1
- package/dist/bridge/git-publish.js +75 -8
- package/dist/bridge/git-review.js +23 -2
- package/dist/bridge/git.d.ts +5 -1
- package/dist/bridge/git.js +103 -8
- package/dist/bridge/health.d.ts +1 -0
- package/dist/bridge/health.js +8 -5
- package/dist/bridge/lookup-cache.d.ts +17 -0
- package/dist/bridge/lookup-cache.js +70 -0
- package/dist/bridge/memory-store.js +40 -14
- package/dist/bridge/pair.js +4 -0
- package/dist/bridge/peers.js +36 -0
- package/dist/bridge/projects.d.ts +14 -0
- package/dist/bridge/projects.js +48 -1
- package/dist/bridge/prompt-deliveries.d.ts +38 -3
- package/dist/bridge/prompt-deliveries.js +196 -36
- package/dist/bridge/schedule-format.d.ts +4 -0
- package/dist/bridge/schedule-format.js +34 -0
- package/dist/bridge/schedule-problems.js +4 -0
- package/dist/bridge/scoped-gateway.d.ts +1 -0
- package/dist/bridge/scoped-gateway.js +10 -1
- package/dist/bridge/server-launch.js +6 -2
- package/dist/bridge/server-routes.js +5 -1
- package/dist/bridge/session-activity.d.ts +10 -0
- package/dist/bridge/session-activity.js +25 -0
- package/dist/bridge/session-servers.js +3 -0
- package/dist/bridge/{codex-thread-origin.d.ts → thread-origin.d.ts} +8 -0
- package/dist/bridge/{codex-thread-origin.js → thread-origin.js} +24 -6
- package/dist/bridge/usage.d.ts +4 -0
- package/dist/bridge/usage.js +22 -8
- package/dist/bridge-hook.mjs +1149 -469
- package/dist/cli/namespaces-tasks.js +19 -5
- package/dist/cli/ops.d.ts +1 -1
- package/dist/cli/ops.js +2 -2
- package/dist/cli/schedules.js +16 -9
- package/dist/content/summarize.js +46 -6
- package/dist/content/validate.d.ts +3 -1
- package/dist/content/validate.js +33 -4
- package/dist/data/access.d.ts +8 -1
- package/dist/data/access.js +27 -9
- package/dist/data/notes.d.ts +2 -0
- package/dist/data/notes.js +2 -1
- package/dist/entrypoint.js +2 -1
- package/dist/generated/memory-ui-graph.browser.js +1 -1
- package/dist/governance/locks.js +17 -1
- package/dist/governance/policy.js +37 -23
- package/dist/link/link.js +6 -1
- package/dist/memory-ui-graph.runtime.js +1 -1
- package/dist/sync/conflict-resolve.d.ts +1 -1
- package/dist/sync/conflict-resolve.js +91 -8
- package/dist/task/lifecycle.js +2 -1
- package/package.json +1 -1
|
@@ -3,7 +3,7 @@ import { nonInteractiveGitEnv } from "../utils-helpers.js";
|
|
|
3
3
|
import { BridgeError } from "./protocol.js";
|
|
4
4
|
import { git, gitRoot } from "./projects.js";
|
|
5
5
|
import { countGit } from "./metrics.js";
|
|
6
|
-
import { defaultBranch, invalidateTree } from "./git.js";
|
|
6
|
+
import { defaultBranch, invalidatePulls, invalidateTree } from "./git.js";
|
|
7
7
|
import { z } from "zod";
|
|
8
8
|
import { detectHost, providerFor, unknownHost } from "./git-hosts.js";
|
|
9
9
|
import { writeHostToken } from "./git-host-auth.js";
|
|
@@ -18,17 +18,27 @@ const MAX_OUTPUT = 65_536;
|
|
|
18
18
|
const COMMIT_TIMEOUT_MS = 110_000;
|
|
19
19
|
const PUSH_TIMEOUT_MS = 110_000;
|
|
20
20
|
const MAX_MESSAGE = 20_000;
|
|
21
|
+
/** After a timeout's SIGTERM: SIGKILL after this long, answer after twice it. */
|
|
22
|
+
const KILL_GRACE_MS = 2_000;
|
|
21
23
|
/** One process with stdout and stderr interleaved in arrival order, bounded,
|
|
22
24
|
* never attached to a terminal and never prompting. */
|
|
23
|
-
export function runCombined(command, args, cwd, timeout, extraEnv = {}) {
|
|
25
|
+
export function runCombined(command, args, cwd, timeout, extraEnv = {}, killGraceMs = KILL_GRACE_MS) {
|
|
24
26
|
return new Promise(resolve => {
|
|
25
27
|
let output = "", truncated = false, timedOut = false, settled = false;
|
|
26
|
-
|
|
28
|
+
let deadline;
|
|
29
|
+
const finish = (run) => {
|
|
30
|
+
if (settled)
|
|
31
|
+
return;
|
|
32
|
+
// The SIGKILL escalation is left to fire: git exiting on SIGTERM must
|
|
33
|
+
// not spare a hook's child that ignores it.
|
|
27
34
|
settled = true;
|
|
35
|
+
clearTimeout(deadline);
|
|
28
36
|
resolve(run);
|
|
29
|
-
}
|
|
37
|
+
};
|
|
38
|
+
// Its own process group, so a timeout reaches what a Git hook started too.
|
|
39
|
+
const group = process.platform !== "win32";
|
|
30
40
|
const child = spawn(command, args, {
|
|
31
|
-
cwd, stdio: ["ignore", "pipe", "pipe"],
|
|
41
|
+
cwd, stdio: ["ignore", "pipe", "pipe"], detached: group,
|
|
32
42
|
env: nonInteractiveGitEnv({ ...process.env, ...extraEnv, GIT_CONFIG_NOSYSTEM: "1", GIT_EDITOR: "true", GH_PROMPT_DISABLED: "1", GH_NO_UPDATE_NOTIFIER: "1", NO_COLOR: "1" }),
|
|
33
43
|
});
|
|
34
44
|
const append = (chunk) => {
|
|
@@ -42,7 +52,54 @@ export function runCombined(command, args, cwd, timeout, extraEnv = {}) {
|
|
|
42
52
|
};
|
|
43
53
|
child.stdout.on("data", append);
|
|
44
54
|
child.stderr.on("data", append);
|
|
45
|
-
const
|
|
55
|
+
const kill = (signal) => {
|
|
56
|
+
try {
|
|
57
|
+
if (group && child.pid)
|
|
58
|
+
process.kill(-child.pid, signal);
|
|
59
|
+
else
|
|
60
|
+
child.kill(signal);
|
|
61
|
+
}
|
|
62
|
+
catch {
|
|
63
|
+
child.kill(signal);
|
|
64
|
+
}
|
|
65
|
+
};
|
|
66
|
+
// The SIGKILL goes only to a group that still has a member: a group id is
|
|
67
|
+
// not reused while any member lives, so a hook's child that ignored
|
|
68
|
+
// SIGTERM is still ours. Residual race, not closed: if every member exited
|
|
69
|
+
// during the grace and the id was then taken by a new group, the probe
|
|
70
|
+
// cannot tell the two apart; that needs both an emptied group and an id
|
|
71
|
+
// reuse inside one grace period.
|
|
72
|
+
const escalate = () => {
|
|
73
|
+
if (!group || !child.pid) {
|
|
74
|
+
child.kill("SIGKILL");
|
|
75
|
+
return;
|
|
76
|
+
}
|
|
77
|
+
try {
|
|
78
|
+
process.kill(-child.pid, 0);
|
|
79
|
+
}
|
|
80
|
+
catch {
|
|
81
|
+
return;
|
|
82
|
+
}
|
|
83
|
+
try {
|
|
84
|
+
process.kill(-child.pid, "SIGKILL");
|
|
85
|
+
}
|
|
86
|
+
catch { /* gone since the probe */ }
|
|
87
|
+
};
|
|
88
|
+
// A timeout signals the group at most twice: SIGTERM now, and one grace
|
|
89
|
+
// later SIGKILL if the group is still there, whether or not git has
|
|
90
|
+
// exited; never again after that.
|
|
91
|
+
const timer = setTimeout(() => {
|
|
92
|
+
timedOut = true;
|
|
93
|
+
kill("SIGTERM");
|
|
94
|
+
setTimeout(escalate, killGraceMs).unref();
|
|
95
|
+
// A descendant outside the group can hold the pipes open forever:
|
|
96
|
+
// answer at the deadline whether or not 'close' ever comes.
|
|
97
|
+
deadline = setTimeout(() => {
|
|
98
|
+
child.stdout.destroy();
|
|
99
|
+
child.stderr.destroy();
|
|
100
|
+
finish({ code: null, output: output.trimEnd(), missing: false, timedOut: true });
|
|
101
|
+
}, killGraceMs * 2);
|
|
102
|
+
}, timeout);
|
|
46
103
|
child.on("error", (error) => {
|
|
47
104
|
clearTimeout(timer);
|
|
48
105
|
finish({ code: null, output: error.message, missing: error.code === "ENOENT", timedOut: false });
|
|
@@ -137,7 +194,12 @@ export async function gitPullRequest(cwd, draft) {
|
|
|
137
194
|
const { reason, message } = unknownHost(host);
|
|
138
195
|
return { ok: false, reason, message, host };
|
|
139
196
|
}
|
|
140
|
-
|
|
197
|
+
try {
|
|
198
|
+
return { ...await provider.open(root, branch, draft === true, host), host };
|
|
199
|
+
}
|
|
200
|
+
finally {
|
|
201
|
+
invalidatePulls(root);
|
|
202
|
+
}
|
|
141
203
|
}
|
|
142
204
|
const MergeBody = z.object({
|
|
143
205
|
number: z.number().int().positive(),
|
|
@@ -158,7 +220,12 @@ export async function gitMergeRequest(cwd, data) {
|
|
|
158
220
|
const { reason, message } = unknownHost(host);
|
|
159
221
|
return { ok: false, reason, message, host };
|
|
160
222
|
}
|
|
161
|
-
|
|
223
|
+
try {
|
|
224
|
+
return { ...await provider.merge(root, request, host), host };
|
|
225
|
+
}
|
|
226
|
+
finally {
|
|
227
|
+
invalidatePulls(root);
|
|
228
|
+
}
|
|
162
229
|
}
|
|
163
230
|
/** Connect (or, with an empty token, disconnect) this repository's GitLab or
|
|
164
231
|
* gitboy host: the token is checked against the host first and stored in the
|
|
@@ -82,7 +82,30 @@ function headerName(raw) {
|
|
|
82
82
|
export function patchFiles(patch) {
|
|
83
83
|
const files = new Set();
|
|
84
84
|
let hunks = 0;
|
|
85
|
+
// Lines still owed to the current hunk's old and new sides: inside a hunk
|
|
86
|
+
// body, `--- x` is a removed line `-- x`, never a file header.
|
|
87
|
+
let oldLeft = 0, newLeft = 0;
|
|
85
88
|
for (const line of patch.split("\n")) {
|
|
89
|
+
if (oldLeft > 0 || newLeft > 0) {
|
|
90
|
+
if (line.startsWith("\\"))
|
|
91
|
+
continue;
|
|
92
|
+
if (line.startsWith("-"))
|
|
93
|
+
oldLeft--;
|
|
94
|
+
else if (line.startsWith("+"))
|
|
95
|
+
newLeft--;
|
|
96
|
+
else {
|
|
97
|
+
oldLeft--;
|
|
98
|
+
newLeft--;
|
|
99
|
+
}
|
|
100
|
+
continue;
|
|
101
|
+
}
|
|
102
|
+
const hunk = /^@@ -\d+(?:,(\d+))? \+\d+(?:,(\d+))? @@/.exec(line);
|
|
103
|
+
if (hunk) {
|
|
104
|
+
hunks++;
|
|
105
|
+
oldLeft = hunk[1] === undefined ? 1 : Number(hunk[1]);
|
|
106
|
+
newLeft = hunk[2] === undefined ? 1 : Number(hunk[2]);
|
|
107
|
+
continue;
|
|
108
|
+
}
|
|
86
109
|
if (/^(?:rename|copy) (?:from|to) |^(?:old|new|deleted file|new file) mode |^GIT binary patch|^Binary files /.test(line)) {
|
|
87
110
|
throw new BridgeError(400, "Only text hunks can be staged one at a time. Stage the whole file instead.");
|
|
88
111
|
}
|
|
@@ -91,8 +114,6 @@ export function patchFiles(patch) {
|
|
|
91
114
|
if (name)
|
|
92
115
|
files.add(name);
|
|
93
116
|
}
|
|
94
|
-
if (line.startsWith("@@ "))
|
|
95
|
-
hunks++;
|
|
96
117
|
}
|
|
97
118
|
if (!files.size || !hunks)
|
|
98
119
|
throw new BridgeError(400, "This patch has no hunks.");
|
package/dist/bridge/git.d.ts
CHANGED
|
@@ -48,11 +48,15 @@ export declare function gitStatus(cwd: string, untrackedPath?: string): Promise<
|
|
|
48
48
|
export declare function gitLog(cwd: string, limit?: number, ref?: string): Promise<Json>;
|
|
49
49
|
/** Local branches with their upstream and ahead/behind counts, and remote refs. */
|
|
50
50
|
export declare function gitBranches(cwd: string): Promise<Json>;
|
|
51
|
+
/** Invalidate every branch/host lookup of this checkout's repository after a Hook write. */
|
|
52
|
+
export declare function invalidatePulls(root: string): void;
|
|
53
|
+
/** Tokens belong to a domain, so revoke every checkout and pending generation. */
|
|
54
|
+
export declare function invalidatePullsForDomain(domain: string): void;
|
|
51
55
|
/** Open pull or merge requests and the checked-out branch's own (any state)
|
|
52
56
|
* with its checks, from whichever host the remote is on (git-hosts.ts). A
|
|
53
57
|
* host that cannot answer (a missing CLI, a stubbed provider, an unknown
|
|
54
58
|
* domain) is `{ available: false, reason, message }`, never an error. */
|
|
55
|
-
export declare function gitPulls(cwd: string): Promise<Json>;
|
|
59
|
+
export declare function gitPulls(cwd: string, retried?: boolean): Promise<Json>;
|
|
56
60
|
/** A repo-relative tree path, or the repository root for `""`. */
|
|
57
61
|
export declare function repositoryPath(root: string, raw: unknown, allowRoot?: boolean): Promise<string>;
|
|
58
62
|
/** Drop the cached tree after a write (commit, push) outside this module. */
|
package/dist/bridge/git.js
CHANGED
|
@@ -1,9 +1,12 @@
|
|
|
1
1
|
import { createHash } from "node:crypto";
|
|
2
|
+
import { readFileSync, realpathSync } from "node:fs";
|
|
2
3
|
import { lstat, open, readdir, realpath } from "node:fs/promises";
|
|
3
4
|
import path from "node:path";
|
|
4
5
|
import { BridgeError } from "./protocol.js";
|
|
5
|
-
import { git, gitHead, gitRoot, withGitReadDeadline } from "./projects.js";
|
|
6
|
+
import { git, gitHead, gitRoot, withGitReadDeadline, withIndependentGitReadDeadline, withoutGitReadDeadline } from "./projects.js";
|
|
6
7
|
import { detectHost, providerFor, unknownHost } from "./git-hosts.js";
|
|
8
|
+
import { hostCredentialIdentity } from "./git-host-auth.js";
|
|
9
|
+
import { LookupCache } from "./lookup-cache.js";
|
|
7
10
|
export { checkRollup, checkRuns } from "./git-hosts.js";
|
|
8
11
|
/** A status code from `--name-status`: the letter alone, with `T` (type change)
|
|
9
12
|
* shown as an edit and anything unrecognized treated as one. */
|
|
@@ -259,17 +262,98 @@ export async function gitBranches(cwd) {
|
|
|
259
262
|
}
|
|
260
263
|
return { current, local, remote };
|
|
261
264
|
}
|
|
265
|
+
// An auth or not-found refusal means access was lost: it replaces a cached success at once.
|
|
266
|
+
const REVOKING = new Set(["auth", "not-found"]);
|
|
267
|
+
const pullsCache = new LookupCache(30_000, 300_000, 64, value => value.available === true, 45_000, value => value.available === false && REVOKING.has(String(value.reason)));
|
|
268
|
+
// GitLab's fingerprint can need a glab subprocess, so it is read at most every
|
|
269
|
+
// few seconds per host with concurrent polls sharing one read. The others are
|
|
270
|
+
// plain file reads and stay exact, so a sign-out is seen on the next poll.
|
|
271
|
+
const credentialReads = new Map();
|
|
272
|
+
const CREDENTIAL_TTL_MS = 5_000;
|
|
273
|
+
function credentialIdentity(host, fresh = false) {
|
|
274
|
+
const key = JSON.stringify([host.kind ?? null, (host.domain ?? "").toLowerCase()]);
|
|
275
|
+
const hit = credentialReads.get(key);
|
|
276
|
+
if (host.kind !== "gitlab")
|
|
277
|
+
return hostCredentialIdentity(host);
|
|
278
|
+
if (!fresh && hit && Date.now() - hit.at < CREDENTIAL_TTL_MS)
|
|
279
|
+
return hit.value;
|
|
280
|
+
const value = hostCredentialIdentity(host).catch(error => { credentialReads.delete(key); throw error; });
|
|
281
|
+
credentialReads.set(key, { at: Date.now(), value });
|
|
282
|
+
if (credentialReads.size > 64)
|
|
283
|
+
credentialReads.delete(credentialReads.keys().next().value);
|
|
284
|
+
return value;
|
|
285
|
+
}
|
|
286
|
+
class CredentialsChanged extends Error {
|
|
287
|
+
}
|
|
288
|
+
/** The repository a checkout belongs to: its common git directory, which every worktree of
|
|
289
|
+
* it shares, so a pull-request write seen from one checkout reaches the others. A path that
|
|
290
|
+
* cannot be read stands for itself. */
|
|
291
|
+
function repositoryId(root) {
|
|
292
|
+
try {
|
|
293
|
+
const dotGit = path.join(root, ".git");
|
|
294
|
+
let gitDir = dotGit;
|
|
295
|
+
try {
|
|
296
|
+
const link = /^gitdir:\s*(.+)$/m.exec(readFileSync(dotGit, "utf8"));
|
|
297
|
+
if (link)
|
|
298
|
+
gitDir = path.resolve(root, link[1].trim());
|
|
299
|
+
}
|
|
300
|
+
catch { /* a directory: the main checkout */ }
|
|
301
|
+
let common = gitDir;
|
|
302
|
+
try {
|
|
303
|
+
common = path.resolve(gitDir, readFileSync(path.join(gitDir, "commondir"), "utf8").trim());
|
|
304
|
+
}
|
|
305
|
+
catch { /* no commondir: gitDir is the common one */ }
|
|
306
|
+
return realpathSync(common);
|
|
307
|
+
}
|
|
308
|
+
catch {
|
|
309
|
+
return root;
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
/** Invalidate every branch/host lookup of this checkout's repository after a Hook write. */
|
|
313
|
+
export function invalidatePulls(root) {
|
|
314
|
+
const prefix = repositoryId(root) + "\0";
|
|
315
|
+
pullsCache.invalidate(key => key.startsWith(prefix));
|
|
316
|
+
}
|
|
317
|
+
/** Tokens belong to a domain, so revoke every checkout and pending generation. */
|
|
318
|
+
export function invalidatePullsForDomain(domain) {
|
|
319
|
+
const normalized = domain.trim().toLowerCase().replace(/\.$/, "");
|
|
320
|
+
for (const key of credentialReads.keys())
|
|
321
|
+
if (JSON.parse(key)[1] === normalized)
|
|
322
|
+
credentialReads.delete(key);
|
|
323
|
+
pullsCache.invalidate(key => key.split("\0")[1] === normalized);
|
|
324
|
+
}
|
|
262
325
|
/** Open pull or merge requests and the checked-out branch's own (any state)
|
|
263
326
|
* with its checks, from whichever host the remote is on (git-hosts.ts). A
|
|
264
327
|
* host that cannot answer (a missing CLI, a stubbed provider, an unknown
|
|
265
328
|
* domain) is `{ available: false, reason, message }`, never an error. */
|
|
266
|
-
export async function gitPulls(cwd) {
|
|
267
|
-
const root = await
|
|
268
|
-
|
|
269
|
-
|
|
329
|
+
export async function gitPulls(cwd, retried = false) {
|
|
330
|
+
const { root, branch, host } = await withIndependentGitReadDeadline(async () => {
|
|
331
|
+
const root = await repository(cwd);
|
|
332
|
+
const branch = (await git(root, "branch", "--show-current").catch(() => "")).trim();
|
|
333
|
+
return { root, branch, host: await detectHost(root, branch) };
|
|
334
|
+
});
|
|
270
335
|
const provider = providerFor(host);
|
|
271
|
-
const
|
|
272
|
-
|
|
336
|
+
const credential = await credentialIdentity(host);
|
|
337
|
+
const key = repositoryId(root) + "\0" + (host.domain ?? "").toLowerCase().replace(/\.$/, "") + "\0" + JSON.stringify([branch, host, credential]);
|
|
338
|
+
try {
|
|
339
|
+
return await pullsCache.get(key, () => withoutGitReadDeadline(async () => {
|
|
340
|
+
const list = provider ? await provider.list(root, branch, host) : unknownHost(host);
|
|
341
|
+
// A sign-in or token change during the lookup: never cache what the old credentials returned.
|
|
342
|
+
if (await credentialIdentity(host, true) !== credential) {
|
|
343
|
+
pullsCache.invalidate(candidate => candidate === key);
|
|
344
|
+
throw new CredentialsChanged();
|
|
345
|
+
}
|
|
346
|
+
return { ...list, branch: branch || null, host };
|
|
347
|
+
}));
|
|
348
|
+
}
|
|
349
|
+
catch (error) {
|
|
350
|
+
if (!(error instanceof CredentialsChanged))
|
|
351
|
+
throw error;
|
|
352
|
+
// Read again once under the new credentials rather than failing the request.
|
|
353
|
+
if (!retried)
|
|
354
|
+
return gitPulls(cwd, true);
|
|
355
|
+
throw new BridgeError(409, "Forge credentials keep changing. Retry.");
|
|
356
|
+
}
|
|
273
357
|
}
|
|
274
358
|
/** A repo-relative tree path, or the repository root for `""`. */
|
|
275
359
|
export async function repositoryPath(root, raw, allowRoot = false) {
|
|
@@ -311,7 +395,7 @@ export async function repositoryPath(root, raw, allowRoot = false) {
|
|
|
311
395
|
}
|
|
312
396
|
const treeCache = new Map();
|
|
313
397
|
/** Drop the cached tree after a write (commit, push) outside this module. */
|
|
314
|
-
export function invalidateTree(root) { treeCache.delete(root); }
|
|
398
|
+
export function invalidateTree(root) { treeCache.delete(root); invalidatePulls(root); }
|
|
315
399
|
const TREE_TTL_MS = 2_000;
|
|
316
400
|
/** Build directory children once, without diff hunks, line counts or upstream walks. */
|
|
317
401
|
async function treeSnapshot(root, head) {
|
|
@@ -521,6 +605,17 @@ export async function gitDiscard(cwd, paths) {
|
|
|
521
605
|
treeCache.delete(root);
|
|
522
606
|
try {
|
|
523
607
|
const files = await repositoryPaths(root, paths);
|
|
608
|
+
// A directory pathspec would revert or remove everything under it.
|
|
609
|
+
for (const file of files) {
|
|
610
|
+
const info = await lstat(path.join(root, file)).catch(error => { if (error.code === "ENOENT")
|
|
611
|
+
return undefined; throw error; });
|
|
612
|
+
// A deleted folder is gone from disk but still a directory in the index,
|
|
613
|
+
// which is what `git checkout` restores from.
|
|
614
|
+
const indexed = info ? "" : await git(root, "ls-files", "-z", "--", `:(literal)${file}`);
|
|
615
|
+
if (info?.isDirectory() || indexed.split("\0").some(entry => entry.startsWith(`${file}/`))) {
|
|
616
|
+
throw new BridgeError(409, "Discard the files in this directory one at a time.");
|
|
617
|
+
}
|
|
618
|
+
}
|
|
524
619
|
const untracked = new Set((await git(root, "ls-files", "--others", "--exclude-standard", "-z")).split("\0").filter(Boolean));
|
|
525
620
|
for (const file of files) {
|
|
526
621
|
const literal = `:(literal)${file}`;
|
package/dist/bridge/health.d.ts
CHANGED
package/dist/bridge/health.js
CHANGED
|
@@ -174,11 +174,14 @@ export async function lastScheduledRun(store, runsFile = scheduleRunsFile()) {
|
|
|
174
174
|
const matching = runs.filter(run => (run.scheduleProject ?? run.project) === owner && run.scheduleId === newest.scheduleId
|
|
175
175
|
&& (newest.batchId ? run.batchId === newest.batchId : run.id === newest.id));
|
|
176
176
|
const last = latestScheduleBatch(matching).lastRun;
|
|
177
|
-
let name;
|
|
177
|
+
let name, paused = false;
|
|
178
178
|
const directory = getProjectDirs(store).find(dir => path.basename(dir).toLowerCase() === owner.toLowerCase());
|
|
179
|
-
if (directory)
|
|
180
|
-
|
|
181
|
-
|
|
179
|
+
if (directory) {
|
|
180
|
+
const found = (await readScheduleDocument(directory).catch(() => undefined))?.schedules.find(item => item.id === last.scheduleId);
|
|
181
|
+
name = found?.name;
|
|
182
|
+
paused = found?.enabled === false;
|
|
183
|
+
}
|
|
184
|
+
return { ...(name ? { name } : {}), ...(paused ? { paused } : {}), project: owner, status: last.status, ...(last.reason ? { reason: plainError(last.reason) } : {}),
|
|
182
185
|
startedAt: last.startedAt, ...(last.finishedAt ? { finishedAt: last.finishedAt } : {}) };
|
|
183
186
|
}
|
|
184
187
|
/** This computer's public SSH host key, the pin a peer's hooks.yaml holds for it. */
|
|
@@ -304,7 +307,7 @@ export function formatHealth(health, color) {
|
|
|
304
307
|
lines.push(` ${store.degraded ? red : yellow}! ${store.error}${reset}`);
|
|
305
308
|
}
|
|
306
309
|
const run = health.schedules.lastRun;
|
|
307
|
-
lines.push(` ${dim}schedule${reset} ${run ? `${run.name ?? "a schedule"} in ${run.project}: ${run.status === "failed" ? `${red}failed${reset}` : run.status} ${dim}${run.startedAt}${reset}${run.reason ? ` · ${run.reason}` : ""}` : `${dim}no runs yet${reset}`}`);
|
|
310
|
+
lines.push(` ${dim}schedule${reset} ${run ? `${run.name ?? "a schedule"} in ${run.project}: ${run.status === "failed" ? `${red}failed${reset}` : run.status} ${dim}${run.startedAt}${reset}${run.reason ? ` · ${run.reason}` : ""}${run.paused ? ` ${dim}(schedule is paused)${reset}` : ""}` : `${dim}no runs yet${reset}`}`);
|
|
308
311
|
if (!health.peers.configured)
|
|
309
312
|
lines.push(` ${dim}peers${reset} ${dim}none enrolled${reset}`);
|
|
310
313
|
else if (health.peers.error)
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/** Bounded Hook lookups. Invalidated/expired refreshes may finish, but cannot
|
|
2
|
+
* repopulate the cache. Failed refreshes retain successes only until maxAge. */
|
|
3
|
+
export declare class LookupCache<T> {
|
|
4
|
+
private readonly ttl;
|
|
5
|
+
private readonly maxAge;
|
|
6
|
+
private readonly limit;
|
|
7
|
+
private readonly available;
|
|
8
|
+
private readonly pendingTimeout;
|
|
9
|
+
/** A result that revokes what was cached (lost access), so the old success is never served again. */
|
|
10
|
+
private readonly revokes;
|
|
11
|
+
private readonly entries;
|
|
12
|
+
constructor(ttl: number, maxAge?: number, limit?: number, available?: (value: T) => boolean, pendingTimeout?: number,
|
|
13
|
+
/** A result that revokes what was cached (lost access), so the old success is never served again. */
|
|
14
|
+
revokes?: (value: T) => boolean);
|
|
15
|
+
invalidate(matches: (key: string) => boolean): void;
|
|
16
|
+
get(key: string, read: () => Promise<T>): Promise<T>;
|
|
17
|
+
}
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import { BridgeError } from "./protocol.js";
|
|
2
|
+
/** Bounded Hook lookups. Invalidated/expired refreshes may finish, but cannot
|
|
3
|
+
* repopulate the cache. Failed refreshes retain successes only until maxAge. */
|
|
4
|
+
export class LookupCache {
|
|
5
|
+
ttl;
|
|
6
|
+
maxAge;
|
|
7
|
+
limit;
|
|
8
|
+
available;
|
|
9
|
+
pendingTimeout;
|
|
10
|
+
revokes;
|
|
11
|
+
entries = new Map();
|
|
12
|
+
constructor(ttl, maxAge = 300_000, limit = 64, available = () => true, pendingTimeout = 45_000,
|
|
13
|
+
/** A result that revokes what was cached (lost access), so the old success is never served again. */
|
|
14
|
+
revokes = () => false) {
|
|
15
|
+
this.ttl = ttl;
|
|
16
|
+
this.maxAge = maxAge;
|
|
17
|
+
this.limit = limit;
|
|
18
|
+
this.available = available;
|
|
19
|
+
this.pendingTimeout = pendingTimeout;
|
|
20
|
+
this.revokes = revokes;
|
|
21
|
+
}
|
|
22
|
+
invalidate(matches) {
|
|
23
|
+
for (const key of this.entries.keys())
|
|
24
|
+
if (matches(key))
|
|
25
|
+
this.entries.delete(key);
|
|
26
|
+
}
|
|
27
|
+
get(key, read) {
|
|
28
|
+
let entry = this.entries.get(key);
|
|
29
|
+
if (!entry) {
|
|
30
|
+
entry = {};
|
|
31
|
+
this.entries.set(key, entry);
|
|
32
|
+
if (this.entries.size > this.limit)
|
|
33
|
+
this.entries.delete(this.entries.keys().next().value);
|
|
34
|
+
}
|
|
35
|
+
const cached = entry.value;
|
|
36
|
+
const age = cached ? Date.now() - cached.at : Infinity;
|
|
37
|
+
const available = cached && this.available(cached.data);
|
|
38
|
+
const ttl = available ? this.ttl : 5_000;
|
|
39
|
+
const maxAge = available ? this.maxAge : 5_000;
|
|
40
|
+
if (cached && age < ttl)
|
|
41
|
+
return Promise.resolve(cached.data);
|
|
42
|
+
if (!entry.pending) {
|
|
43
|
+
const current = entry;
|
|
44
|
+
let timer;
|
|
45
|
+
const timeout = new Promise((_, reject) => {
|
|
46
|
+
timer = setTimeout(() => reject(new BridgeError(504, "Lookup did not finish within the request time limit.", { code: "lookup-timeout" })), this.pendingTimeout);
|
|
47
|
+
});
|
|
48
|
+
const pending = Promise.race([Promise.resolve().then(read), timeout]).then(data => {
|
|
49
|
+
if (this.entries.get(key) === current && current.pending === pending) {
|
|
50
|
+
const previous = current.value;
|
|
51
|
+
const keepSuccess = previous && this.available(previous.data) &&
|
|
52
|
+
!this.available(data) && !this.revokes(data) && Date.now() - previous.at < this.maxAge;
|
|
53
|
+
if (!keepSuccess)
|
|
54
|
+
current.value = { data, at: Date.now() };
|
|
55
|
+
}
|
|
56
|
+
return data;
|
|
57
|
+
}).finally(() => {
|
|
58
|
+
clearTimeout(timer);
|
|
59
|
+
if (current.pending === pending)
|
|
60
|
+
current.pending = undefined;
|
|
61
|
+
});
|
|
62
|
+
entry.pending = pending;
|
|
63
|
+
}
|
|
64
|
+
if (cached && age < maxAge && !this.revokes(cached.data)) {
|
|
65
|
+
void entry.pending.catch(() => { });
|
|
66
|
+
return Promise.resolve(cached.data);
|
|
67
|
+
}
|
|
68
|
+
return entry.pending;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
@@ -1,9 +1,11 @@
|
|
|
1
1
|
import { execFile, spawn } from "node:child_process";
|
|
2
2
|
import { createHash } from "node:crypto";
|
|
3
|
-
import {
|
|
3
|
+
import { mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
|
|
4
|
+
import { lstat, mkdir, realpath } from "node:fs/promises";
|
|
4
5
|
import path from "node:path";
|
|
5
6
|
import { promisify } from "node:util";
|
|
6
7
|
import { z } from "zod";
|
|
8
|
+
import { withFileLock } from "../governance/locks.js";
|
|
7
9
|
import { BridgeError, bridgeRoot } from "./protocol.js";
|
|
8
10
|
// The phone reads memory from a paired computer through these routes, in the
|
|
9
11
|
// same git terms its sync engine uses with GitHub: a head, a recursive tree,
|
|
@@ -217,10 +219,26 @@ export async function storeFile(store, relative) {
|
|
|
217
219
|
throw new BridgeError(400, "Invalid store path.");
|
|
218
220
|
return file;
|
|
219
221
|
}
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
222
|
+
/** `withFileLock` on a store file, a held lock answered as a 409 to retry. */
|
|
223
|
+
function lockedStoreFile(file, rel, work) {
|
|
224
|
+
try {
|
|
225
|
+
withFileLock(file, work);
|
|
226
|
+
}
|
|
227
|
+
catch (error) {
|
|
228
|
+
if (error instanceof BridgeError || !/could not acquire lock/.test(String(error?.message)))
|
|
229
|
+
throw error;
|
|
230
|
+
throw new BridgeError(409, `${rel} is being written on this computer (its lock is held). Try again.`);
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
function currentShaSync(file) {
|
|
234
|
+
try {
|
|
235
|
+
return blobSha(readFileSync(file));
|
|
236
|
+
}
|
|
237
|
+
catch (error) {
|
|
238
|
+
if (error.code === "ENOENT")
|
|
239
|
+
return null;
|
|
240
|
+
throw error;
|
|
241
|
+
}
|
|
224
242
|
}
|
|
225
243
|
const putSchema = z.object({ path: z.string().max(1024), content: z.string(), sha: z.string().regex(SHA).nullable().optional() });
|
|
226
244
|
const deleteSchema = z.object({ path: z.string().max(1024), sha: z.string().regex(SHA) });
|
|
@@ -232,12 +250,17 @@ export function putStoreFile(store, data) {
|
|
|
232
250
|
throw new BridgeError(413, "This file is too large for the phone to write.");
|
|
233
251
|
return serialized(async () => {
|
|
234
252
|
const file = await storeFile(store, input.path);
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
253
|
+
// Under the lock the CLI's writers take (`<file>.lock`), so a write of
|
|
254
|
+
// theirs cannot land between the sha check and the swap. withFileLock
|
|
255
|
+
// waits synchronously, so the work inside it is synchronous too.
|
|
256
|
+
lockedStoreFile(file, input.path, () => {
|
|
257
|
+
if (currentShaSync(file) !== (input.sha ?? null))
|
|
258
|
+
throw new BridgeError(409, `${input.path} changed on this computer.`);
|
|
259
|
+
mkdirSync(path.dirname(file), { recursive: true });
|
|
260
|
+
const temporary = `${file}.phren-${process.pid}-${Date.now()}`;
|
|
261
|
+
writeFileSync(temporary, content, { flag: "wx" });
|
|
262
|
+
renameSync(temporary, file);
|
|
263
|
+
});
|
|
241
264
|
return { content: { sha: blobSha(content), path: input.path }, commit: { sha: blobSha(content) } };
|
|
242
265
|
});
|
|
243
266
|
}
|
|
@@ -245,9 +268,12 @@ export function deleteStoreFile(store, data) {
|
|
|
245
268
|
const input = deleteSchema.parse(data);
|
|
246
269
|
return serialized(async () => {
|
|
247
270
|
const file = await storeFile(store, input.path);
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
271
|
+
// The writers' lock across check and delete, as in putStoreFile.
|
|
272
|
+
lockedStoreFile(file, input.path, () => {
|
|
273
|
+
if (currentShaSync(file) !== input.sha)
|
|
274
|
+
throw new BridgeError(409, `${input.path} changed on this computer.`);
|
|
275
|
+
unlinkSync(file);
|
|
276
|
+
});
|
|
251
277
|
return { ok: true };
|
|
252
278
|
});
|
|
253
279
|
}
|
package/dist/bridge/pair.js
CHANGED
|
@@ -294,6 +294,10 @@ export async function runPair(args, version) {
|
|
|
294
294
|
console.log(renderUnicodeCompact(url, { border: 2 }));
|
|
295
295
|
const typed = `${code.slice(0, 3)}-${code.slice(3)}`;
|
|
296
296
|
console.log(`\n Can't scan? Choose "Enter code" and type: ${hosts[0]}${session.port === PAIR_PORT ? "" : `:${session.port}`} ${typed}`);
|
|
297
|
+
if (process.env.WSL_DISTRO_NAME) {
|
|
298
|
+
console.log(`\n This is WSL: Windows may block inbound port ${session.port} (and SSH) from the phone. If it cannot connect, run once in an admin PowerShell:`);
|
|
299
|
+
console.log(` New-NetFirewallHyperVRule -Name phren-pair -DisplayName "Phren pairing" -Direction Inbound -VMCreatorId '{40E0AC32-46A5-438A-A0B2-2B479E8F2E90}' -Protocol TCP -LocalPorts ${session.port},22`);
|
|
300
|
+
}
|
|
297
301
|
console.log(` Waiting for your phone (${minutes} min). Ctrl-C cancels.`);
|
|
298
302
|
const cancel = () => session.close();
|
|
299
303
|
process.once("SIGINT", cancel);
|
package/dist/bridge/peers.js
CHANGED
|
@@ -4,6 +4,7 @@ import path from "node:path";
|
|
|
4
4
|
import { Duplex } from "node:stream";
|
|
5
5
|
import { dump, load } from "js-yaml";
|
|
6
6
|
import { z } from "zod";
|
|
7
|
+
import { tryFileLock } from "../governance/locks.js";
|
|
7
8
|
import { logger } from "../logger.js";
|
|
8
9
|
import { hookRequest } from "./client.js";
|
|
9
10
|
import { dispatchKeyPath, publicComputerKey } from "./computers.js";
|
|
@@ -41,6 +42,41 @@ export async function hookPeers(root = bridgeRoot()) {
|
|
|
41
42
|
*/
|
|
42
43
|
export async function addHookPeer(input, root = bridgeRoot()) {
|
|
43
44
|
const peer = peerSchema.parse(input);
|
|
45
|
+
return lockedHooksYaml(root, () => addHookPeerNow(peer, root));
|
|
46
|
+
}
|
|
47
|
+
/** One hooks.yaml change at a time, in this process and across processes, so
|
|
48
|
+
* two links read, check and write in turn and neither loses the other's peer. */
|
|
49
|
+
const hooksYamlQueues = new Map();
|
|
50
|
+
const HOOKS_YAML_LOCK_WAIT_MS = 5_000;
|
|
51
|
+
async function lockedHooksYaml(root, work) {
|
|
52
|
+
const file = path.join(path.resolve(root), "hooks.yaml");
|
|
53
|
+
const previous = hooksYamlQueues.get(file) ?? Promise.resolve();
|
|
54
|
+
const next = previous.catch(() => undefined).then(async () => {
|
|
55
|
+
const deadline = Date.now() + HOOKS_YAML_LOCK_WAIT_MS;
|
|
56
|
+
let release = tryFileLock(file);
|
|
57
|
+
while (!release) {
|
|
58
|
+
if (Date.now() >= deadline)
|
|
59
|
+
throw new BridgeError(409, "hooks.yaml is being changed by another process. Try again.");
|
|
60
|
+
await new Promise(resolve => setTimeout(resolve, 50));
|
|
61
|
+
release = tryFileLock(file);
|
|
62
|
+
}
|
|
63
|
+
try {
|
|
64
|
+
return await work();
|
|
65
|
+
}
|
|
66
|
+
finally {
|
|
67
|
+
release();
|
|
68
|
+
}
|
|
69
|
+
});
|
|
70
|
+
hooksYamlQueues.set(file, next);
|
|
71
|
+
try {
|
|
72
|
+
return await next;
|
|
73
|
+
}
|
|
74
|
+
finally {
|
|
75
|
+
if (hooksYamlQueues.get(file) === next)
|
|
76
|
+
hooksYamlQueues.delete(file);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
async function addHookPeerNow(peer, root) {
|
|
44
80
|
const existing = await hookPeers(root).catch(error => {
|
|
45
81
|
if (error instanceof BridgeError && error.details?.hooksYaml === "missing")
|
|
46
82
|
return [];
|
|
@@ -2,6 +2,11 @@ import { type Json } from "./protocol.js";
|
|
|
2
2
|
/** Nested reads share one deadline. Abort and reap outstanding Git processes on
|
|
3
3
|
* expiry or failure; never leave a timed-out request running its command chain. */
|
|
4
4
|
export declare function withGitReadDeadline<T>(read: () => Promise<T>): Promise<T>;
|
|
5
|
+
/** Run provider work outside a completed route's local Git budget. Each local
|
|
6
|
+
* Git call retains its own timeout, while forge requests use provider limits. */
|
|
7
|
+
export declare function withoutGitReadDeadline<T>(read: () => Promise<T>): Promise<T>;
|
|
8
|
+
/** A background lookup owns its deadline even after the requesting route ends. */
|
|
9
|
+
export declare function withIndependentGitReadDeadline<T>(read: () => Promise<T>): Promise<T>;
|
|
5
10
|
/** Bind Git to the selected checkout, even when Hook inherited another Git
|
|
6
11
|
* process's repository/index environment. Keep user config (including excludes). */
|
|
7
12
|
export declare function checkoutGitEnv(): NodeJS.ProcessEnv;
|
|
@@ -17,13 +22,22 @@ export declare function repositoryDiff(cwd: string, touched?: unknown[], allowed
|
|
|
17
22
|
* worktree's through its `.git` file), found without spawning git. */
|
|
18
23
|
export declare function headFile(cwd: string): Promise<string | undefined>;
|
|
19
24
|
export declare function repositoryBranch(cwd: string): Promise<string | undefined>;
|
|
25
|
+
/** `unverified`: the owner could not be checked against the live socket table, so no session may be handed this server. */
|
|
20
26
|
export interface LocalServer {
|
|
21
27
|
name: string;
|
|
22
28
|
port: number;
|
|
23
29
|
origin: string;
|
|
24
30
|
process?: string;
|
|
25
31
|
pid?: number;
|
|
32
|
+
unverified?: true;
|
|
26
33
|
}
|
|
34
|
+
/** The web servers listening here. A cached listener is checked against the live socket table
|
|
35
|
+
* before it is returned: if the process that held its address and port no longer listens there
|
|
36
|
+
* (it stopped, or closed the socket and kept running), the port may already belong to another
|
|
37
|
+
* session's server, and attributing it to the old owner would open that session's preview on the
|
|
38
|
+
* wrong app. Such a result drops the entry and refreshes the cache. */
|
|
27
39
|
export declare function webServers(): Promise<LocalServer[]>;
|
|
40
|
+
/** The key `addListener` files a server under: its host with the port always spelled out (a URL's host drops the default one). */
|
|
41
|
+
export declare function listenerKey(server: Pick<LocalServer, "origin" | "port">): string;
|
|
28
42
|
/** Launch only in real local directories under home or a locator candidate. */
|
|
29
43
|
export declare function launchDirectory(raw: unknown, activity?: Json[], located?: Iterable<string>): Promise<string>;
|