@phren/cli 0.3.31 → 0.3.32
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bridge/agent-hooks.js +23 -7
- package/dist/bridge/approval-rules.d.ts +70 -0
- package/dist/bridge/approval-rules.js +231 -0
- package/dist/bridge/authority.d.ts +1 -2
- package/dist/bridge/authority.js +2 -7
- package/dist/bridge/changes.d.ts +4 -0
- package/dist/bridge/changes.js +47 -33
- package/dist/bridge/claude-suggestion.js +1 -1
- package/dist/bridge/dispatch.js +1 -1
- package/dist/bridge/enroll.d.ts +6 -0
- package/dist/bridge/enroll.js +10 -4
- package/dist/bridge/git-worktrees.js +14 -17
- package/dist/bridge/git.d.ts +10 -2
- package/dist/bridge/git.js +148 -107
- package/dist/bridge/health.js +9 -5
- package/dist/bridge/herdr.js +6 -1
- package/dist/bridge/locate.js +14 -1
- package/dist/bridge/projects.d.ts +8 -0
- package/dist/bridge/projects.js +142 -24
- package/dist/bridge/schedule-format.d.ts +10 -0
- package/dist/bridge/schedule-format.js +24 -1
- package/dist/bridge/schedules.d.ts +3 -1
- package/dist/bridge/schedules.js +96 -40
- package/dist/bridge/server-launch.js +39 -15
- package/dist/bridge/server-pane-routes.js +19 -11
- package/dist/bridge/server-routes.d.ts +2 -0
- package/dist/bridge/server-routes.js +36 -8
- package/dist/bridge/speech-key.d.ts +2 -9
- package/dist/bridge/speech-key.js +4 -37
- package/dist/bridge/terminal-tmux.js +22 -4
- package/dist/bridge/tmux-test-server.d.ts +13 -0
- package/dist/bridge/tmux-test-server.js +103 -0
- package/dist/bridge/transcript-claude.d.ts +3 -3
- package/dist/bridge/transcript-claude.js +7 -7
- package/dist/bridge/transcript-codex.js +6 -4
- package/dist/bridge/transcript-preview.js +1 -1
- package/dist/bridge/transcripts.js +14 -3
- package/dist/bridge-hook.mjs +2753 -2216
- package/dist/cli/schedules.js +8 -2
- package/dist/cli/session-stop.js +9 -1
- package/dist/cli-registry.js +1 -1
- package/dist/core/project-registry.d.ts +1 -0
- package/dist/core/project-registry.js +6 -2
- package/dist/core/project.d.ts +1 -0
- package/dist/core/project.js +5 -0
- package/dist/modules/registry.js +9 -7
- package/dist/phren-core.js +1 -1
- package/dist/phren-paths.d.ts +2 -2
- package/dist/phren-paths.js +2 -2
- package/dist/store-routing.d.ts +2 -2
- package/dist/store-routing.js +2 -2
- package/dist/sync/git-state.d.ts +13 -0
- package/dist/sync/git-state.js +22 -0
- package/dist/sync/store-merge.d.ts +2 -0
- package/dist/sync/store-merge.js +6 -1
- package/dist/test-global-setup.js +7 -0
- package/dist/tools/data.js +1 -1
- package/dist/tools/finding.js +1 -1
- package/dist/tools/search.js +1 -1
- package/dist/tools/tasks.js +1 -1
- package/package.json +1 -1
- package/starter/global/skills/conductor/SKILL.md +2 -2
package/dist/bridge/projects.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
1
2
|
import { nonInteractiveGitEnv } from "../utils-helpers.js";
|
|
2
3
|
import { execFile } from "node:child_process";
|
|
3
4
|
import { promisify } from "node:util";
|
|
@@ -11,18 +12,107 @@ import { locateProject } from "./locate.js";
|
|
|
11
12
|
import { BridgeError } from "./protocol.js";
|
|
12
13
|
import { countGit } from "./metrics.js";
|
|
13
14
|
const exec = promisify(execFile);
|
|
15
|
+
const gitReadBudget = new AsyncLocalStorage();
|
|
16
|
+
const GIT_READ_MS = 10_000;
|
|
17
|
+
const gitTimeout = () => new BridgeError(504, "Git did not finish within the request time limit. Retry when the repository is idle.", { code: "git-timeout" });
|
|
18
|
+
function remainingGitTime(budget) {
|
|
19
|
+
const remaining = budget.deadline - performance.now();
|
|
20
|
+
if (budget.controller.signal.aborted || remaining <= 0)
|
|
21
|
+
throw gitTimeout();
|
|
22
|
+
return Math.max(1, Math.ceil(remaining));
|
|
23
|
+
}
|
|
24
|
+
/** Nested reads share one deadline. Abort and reap outstanding Git processes on
|
|
25
|
+
* expiry or failure; never leave a timed-out request running its command chain. */
|
|
26
|
+
export async function withGitReadDeadline(read) {
|
|
27
|
+
const inherited = gitReadBudget.getStore();
|
|
28
|
+
if (inherited) {
|
|
29
|
+
remainingGitTime(inherited);
|
|
30
|
+
return read();
|
|
31
|
+
}
|
|
32
|
+
const budget = { deadline: performance.now() + GIT_READ_MS, controller: new AbortController(), pending: new Set() };
|
|
33
|
+
const timer = setTimeout(() => budget.controller.abort(), GIT_READ_MS);
|
|
34
|
+
try {
|
|
35
|
+
return await gitReadBudget.run(budget, async () => {
|
|
36
|
+
const result = await read();
|
|
37
|
+
remainingGitTime(budget);
|
|
38
|
+
return result;
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
finally {
|
|
42
|
+
clearTimeout(timer);
|
|
43
|
+
budget.controller.abort();
|
|
44
|
+
await Promise.allSettled([...budget.pending]);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
/** Bind Git to the selected checkout, even when Hook inherited another Git
|
|
48
|
+
* process's repository/index environment. Keep user config (including excludes). */
|
|
49
|
+
export function checkoutGitEnv() {
|
|
50
|
+
const env = nonInteractiveGitEnv({ ...process.env, GIT_OPTIONAL_LOCKS: "0", LC_ALL: "C" });
|
|
51
|
+
for (const key of ["GIT_DIR", "GIT_WORK_TREE", "GIT_COMMON_DIR", "GIT_INDEX_FILE", "GIT_OBJECT_DIRECTORY", "GIT_ALTERNATE_OBJECT_DIRECTORIES", "GIT_PREFIX"])
|
|
52
|
+
delete env[key];
|
|
53
|
+
return env;
|
|
54
|
+
}
|
|
14
55
|
export async function git(cwd, ...args) {
|
|
56
|
+
const budget = gitReadBudget.getStore();
|
|
57
|
+
const timeout = budget ? remainingGitTime(budget) : 10_000;
|
|
15
58
|
countGit("projects");
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
59
|
+
let pending;
|
|
60
|
+
try {
|
|
61
|
+
pending = exec("git", ["-C", cwd, "--no-pager", ...args], {
|
|
62
|
+
timeout, maxBuffer: 4_194_304, env: checkoutGitEnv(),
|
|
63
|
+
...(budget ? { signal: budget.controller.signal, killSignal: "SIGKILL" } : {}),
|
|
64
|
+
});
|
|
65
|
+
budget?.pending.add(pending);
|
|
66
|
+
const result = await pending;
|
|
67
|
+
if (budget)
|
|
68
|
+
remainingGitTime(budget);
|
|
69
|
+
return result.stdout;
|
|
70
|
+
}
|
|
71
|
+
catch (error) {
|
|
72
|
+
const failure = error;
|
|
73
|
+
if (budget && (budget.controller.signal.aborted || performance.now() >= budget.deadline))
|
|
74
|
+
throw gitTimeout();
|
|
75
|
+
const stderr = String(failure.stderr ?? "");
|
|
76
|
+
// No-index uses exit 1 for differences, even with conversion warnings.
|
|
77
|
+
// Keep read errors and unknown diagnostics fatal, including partial output.
|
|
78
|
+
const diagnostics = stderr.split(/\r?\n/).filter(line => line.trim() && !line.startsWith("warning:"));
|
|
79
|
+
const options = args.slice(0, args.indexOf("--") < 0 ? args.length : args.indexOf("--"));
|
|
80
|
+
if (args[0] === "diff" && options.includes("--no-index") && String(failure.code) === "1"
|
|
81
|
+
&& diagnostics.length === 0 && !failure.killed && !failure.signal && failure.errno === undefined
|
|
82
|
+
&& failure.syscall === undefined && failure.name !== "AbortError")
|
|
83
|
+
return failure.stdout ?? "";
|
|
84
|
+
const [status, code, message] = failure.code === "ERR_CHILD_PROCESS_STDIO_MAXBUFFER"
|
|
85
|
+
? [413, "git-output-limit", "Git output exceeded the 4 MiB limit. Narrow the selection."]
|
|
86
|
+
: failure.killed || failure.signal ? [504, "git-timeout", "Git did not finish within its time limit. Retry when the repository is idle."]
|
|
87
|
+
: /index\.lock/.test(stderr) ? [409, "git-index-locked", "Git could not lock the index. Wait for the other Git operation to finish; the Hook has not removed the lock."]
|
|
88
|
+
: /not a git repository/.test(stderr) ? [409, "git-not-repository", "This folder is not a Git repository."]
|
|
89
|
+
: [503, "git-failed", `Git ${args[0]} failed: ${stderr.trim().slice(0, 1000) || "the command could not complete"}`];
|
|
90
|
+
throw new BridgeError(status, message, { code, ...(failure.code !== undefined ? { exitCode: String(failure.code) } : {}) });
|
|
91
|
+
}
|
|
92
|
+
finally {
|
|
93
|
+
if (pending)
|
|
94
|
+
budget?.pending.delete(pending);
|
|
95
|
+
}
|
|
19
96
|
}
|
|
20
97
|
export async function gitRoot(dir) {
|
|
21
98
|
try {
|
|
22
|
-
return await realpath((await git(dir, "rev-parse", "--show-toplevel")).
|
|
99
|
+
return await realpath((await git(dir, "rev-parse", "--show-toplevel")).replace(/\r?\n$/, ""));
|
|
23
100
|
}
|
|
24
|
-
catch {
|
|
25
|
-
|
|
101
|
+
catch (error) {
|
|
102
|
+
if (error instanceof BridgeError && error.details?.code === "git-not-repository")
|
|
103
|
+
return undefined;
|
|
104
|
+
throw error;
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
/** An unborn HEAD is normal; process/configuration failures are not. */
|
|
108
|
+
export async function gitHead(root) {
|
|
109
|
+
try {
|
|
110
|
+
return (await git(root, "rev-parse", "--verify", "--quiet", "HEAD")).trim();
|
|
111
|
+
}
|
|
112
|
+
catch (error) {
|
|
113
|
+
if (error instanceof BridgeError && error.details?.exitCode === "1")
|
|
114
|
+
return undefined;
|
|
115
|
+
throw error;
|
|
26
116
|
}
|
|
27
117
|
}
|
|
28
118
|
/** `git status` as the app lists it: one record per file, a staged and an
|
|
@@ -30,30 +120,46 @@ export async function gitRoot(dir) {
|
|
|
30
120
|
async function statusFiles(root, pathspecs = []) {
|
|
31
121
|
const status = (await git(root, "status", "--porcelain=v1", "-z", "--untracked-files=normal", "--", ...pathspecs.map(spec => `:(literal)${spec}`))).split("\0");
|
|
32
122
|
const files = [];
|
|
33
|
-
|
|
123
|
+
let totalFiles = 0, truncated = false, remaining = 1_000_000;
|
|
124
|
+
for (let index = 0; index < status.length; index++) {
|
|
34
125
|
const record = status[index];
|
|
35
126
|
if (!record)
|
|
36
127
|
continue;
|
|
37
128
|
const code = record.slice(0, 2), file = record.slice(3);
|
|
38
|
-
|
|
39
|
-
|
|
129
|
+
const original = /[RC]/.test(code) ? status[++index] : undefined;
|
|
130
|
+
totalFiles++;
|
|
131
|
+
if (files.length >= 500) {
|
|
132
|
+
truncated = true;
|
|
133
|
+
continue;
|
|
134
|
+
}
|
|
40
135
|
const sections = [];
|
|
41
|
-
for (const [kind, staged] of [["staged", true], ["unstaged", false]]) {
|
|
42
|
-
if (code === "??")
|
|
136
|
+
for (const [kind, staged, column] of [["staged", true, 0], ["unstaged", false, 1]]) {
|
|
137
|
+
if (code === "??" || code[column] === " ")
|
|
43
138
|
continue;
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
139
|
+
if (remaining <= 0) {
|
|
140
|
+
sections.push({ id: `${kind}:${file}`, kind, loadState: "loaded", patch: "", truncated: true });
|
|
141
|
+
truncated = true;
|
|
142
|
+
continue;
|
|
143
|
+
}
|
|
144
|
+
const patch = await git(root, "diff", "--no-ext-diff", "--no-textconv", "--no-color", ...(staged ? ["--cached"] : []), "--", ...[file, ...(original ? [original] : [])].map(name => `:(literal)${name}`));
|
|
145
|
+
if (patch) {
|
|
146
|
+
const limit = Math.min(200_000, remaining), clipped = patch.length > limit;
|
|
147
|
+
sections.push({ id: `${kind}:${file}`, kind, binary: /^(?:Binary files |GIT binary patch)/m.test(patch), loadState: "loaded", patch: patch.slice(0, limit), truncated: clipped });
|
|
148
|
+
remaining -= Math.min(patch.length, limit);
|
|
149
|
+
truncated ||= clipped;
|
|
150
|
+
}
|
|
47
151
|
}
|
|
48
|
-
files.push({ path: file, status: code, sections });
|
|
152
|
+
files.push({ path: file, status: code, ...(file.endsWith("/") ? { directory: true, countsComplete: false } : {}), sections });
|
|
49
153
|
}
|
|
50
|
-
return files;
|
|
154
|
+
return { files, totalFiles, truncated };
|
|
51
155
|
}
|
|
52
156
|
/** The last commit that touched `pathspec` in the past half hour — what a
|
|
53
157
|
* command changed when a hook (phren's own Stop hook, say) committed it before
|
|
54
158
|
* anyone looked. */
|
|
55
159
|
async function committed(root, pathspec) {
|
|
56
|
-
|
|
160
|
+
if (!await gitHead(root))
|
|
161
|
+
return undefined;
|
|
162
|
+
const log = await git(root, "log", "-1", "--since=30.minutes", "--format=%h%x1f%s%x1f%cr", "-p", "--no-ext-diff", "--no-textconv", "--no-color", "--", `:(literal)${pathspec}`);
|
|
57
163
|
const newline = log.indexOf("\n");
|
|
58
164
|
if (newline < 0)
|
|
59
165
|
return undefined;
|
|
@@ -61,7 +167,7 @@ async function committed(root, pathspec) {
|
|
|
61
167
|
const patch = log.slice(newline + 1).replace(/^\n+/, "");
|
|
62
168
|
if (!patch)
|
|
63
169
|
return undefined;
|
|
64
|
-
return { id: `committed:${pathspec}`, kind: "committed", binary: patch.includes("Binary files"), loadState: "loaded", patch, note: `${hash} · ${subject.slice(0, 120)} · ${when}` };
|
|
170
|
+
return { id: `committed:${pathspec}`, kind: "committed", binary: patch.includes("Binary files"), loadState: "loaded", patch: patch.slice(0, 200_000), truncated: patch.length > 200_000, note: `${hash} · ${subject.slice(0, 120)} · ${when}` };
|
|
65
171
|
}
|
|
66
172
|
/** A path a command named, made absolute and real — `~/` expanded, relative
|
|
67
173
|
* ones taken from the pane. The caller checks conversation scope after
|
|
@@ -86,10 +192,13 @@ async function resolveTouched(raw, cwd) {
|
|
|
86
192
|
/** The pane's working tree, plus anything the command named: files in the
|
|
87
193
|
* same repository that a hook already committed, and files in other
|
|
88
194
|
* repositories — the phren store, a sibling checkout — grouped by root. */
|
|
89
|
-
export
|
|
195
|
+
export function repositoryDiff(cwd, touched = [], allowedPaths = []) {
|
|
196
|
+
return withGitReadDeadline(() => readRepositoryDiff(cwd, touched, allowedPaths));
|
|
197
|
+
}
|
|
198
|
+
async function readRepositoryDiff(cwd, touched, allowedPaths) {
|
|
90
199
|
const root = await gitRoot(cwd);
|
|
91
200
|
if (!root)
|
|
92
|
-
throw new BridgeError(409, "This pane is not in a Git repository.");
|
|
201
|
+
throw new BridgeError(409, "This pane is not in a Git repository.", { code: "git-not-repository" });
|
|
93
202
|
const allowed = (await Promise.all([root, phrenStoreRoot(), ...allowedPaths].map(raw => resolveTouched(raw, cwd)))).filter((p) => !!p);
|
|
94
203
|
const requested = [];
|
|
95
204
|
for (const raw of touched.slice(0, 24)) {
|
|
@@ -99,7 +208,7 @@ export async function repositoryDiff(cwd, touched = [], allowedPaths = []) {
|
|
|
99
208
|
requested.push(file);
|
|
100
209
|
}
|
|
101
210
|
const branch = (await git(root, "branch", "--show-current")).trim();
|
|
102
|
-
const
|
|
211
|
+
const listing = await statusFiles(root);
|
|
103
212
|
const byRoot = new Map();
|
|
104
213
|
for (const file of requested) {
|
|
105
214
|
const owner = await gitRoot((await stat(file).catch(() => undefined))?.isDirectory() ? file : path.dirname(file));
|
|
@@ -118,22 +227,31 @@ export async function repositoryDiff(cwd, touched = [], allowedPaths = []) {
|
|
|
118
227
|
for (const [owner, specs] of byRoot) {
|
|
119
228
|
if (related.length >= 8)
|
|
120
229
|
break;
|
|
121
|
-
const
|
|
230
|
+
const ownerListing = owner === root ? listing : await statusFiles(owner, specs);
|
|
231
|
+
const listed = ownerListing.files;
|
|
122
232
|
const seen = new Set(listed.map(file => file.path));
|
|
123
233
|
for (const spec of specs) {
|
|
124
234
|
// Uncommitted changes under the path are already listed; otherwise show the commit.
|
|
125
235
|
if ([...seen].some(file => file === spec || spec === "." || file.startsWith(spec + "/")))
|
|
126
236
|
continue;
|
|
237
|
+
if (ownerListing.truncated)
|
|
238
|
+
continue; // An omitted dirty row must not be replaced with a historical commit.
|
|
127
239
|
const section = await committed(owner, spec);
|
|
128
240
|
if (section) {
|
|
241
|
+
ownerListing.totalFiles++;
|
|
242
|
+
if (listed.length >= 500) {
|
|
243
|
+
ownerListing.truncated = true;
|
|
244
|
+
continue;
|
|
245
|
+
}
|
|
129
246
|
listed.push({ path: spec, status: " ", sections: [section] });
|
|
130
247
|
seen.add(spec);
|
|
248
|
+
ownerListing.truncated ||= section.truncated === true;
|
|
131
249
|
}
|
|
132
250
|
}
|
|
133
251
|
if (owner !== root && listed.length)
|
|
134
|
-
related.push({ root: owner, branch: (await git(owner, "branch", "--show-current")).trim(),
|
|
252
|
+
related.push({ root: owner, branch: (await git(owner, "branch", "--show-current")).trim(), ...ownerListing });
|
|
135
253
|
}
|
|
136
|
-
return { branch, root, launchPath: cwd,
|
|
254
|
+
return { branch, root, repository: root, observedAt: new Date().toISOString(), launchPath: cwd, ...listing, ...(related.length ? { related } : {}) };
|
|
137
255
|
}
|
|
138
256
|
/** The HEAD file of the repository holding `cwd` (`.git/HEAD`, or a linked
|
|
139
257
|
* worktree's through its `.git` file), found without spawning git. */
|
|
@@ -26,6 +26,8 @@ export interface Schedule {
|
|
|
26
26
|
/** Claude account id (a slug) the run uses; absent means the default account. */
|
|
27
27
|
account?: string;
|
|
28
28
|
notify?: ScheduleNotify[];
|
|
29
|
+
/** Explicit targets; absent means the directory owning this schedule. */
|
|
30
|
+
projects?: string[];
|
|
29
31
|
every: ScheduleEvery;
|
|
30
32
|
at?: string;
|
|
31
33
|
days?: Weekday[];
|
|
@@ -50,6 +52,8 @@ export interface ScheduleRun {
|
|
|
50
52
|
id: string;
|
|
51
53
|
scheduleId: string;
|
|
52
54
|
project: string;
|
|
55
|
+
scheduleProject?: string;
|
|
56
|
+
batchId?: string;
|
|
53
57
|
startedAt: string;
|
|
54
58
|
finishedAt?: string;
|
|
55
59
|
status: ScheduleRunStatus;
|
|
@@ -84,6 +88,7 @@ export interface ScheduleStatus extends Schedule {
|
|
|
84
88
|
project: string;
|
|
85
89
|
nextRun: string | null;
|
|
86
90
|
lastRun: Omit<ScheduleRun, "id" | "scheduleId" | "project"> | null;
|
|
91
|
+
lastRuns: ScheduleRun[];
|
|
87
92
|
running: boolean;
|
|
88
93
|
}
|
|
89
94
|
interface ScheduleDocument {
|
|
@@ -100,6 +105,11 @@ export declare function computerMatches(wanted: string, current: string): boolea
|
|
|
100
105
|
export declare function scheduleNotifications(schedule: Schedule): Set<ScheduleNotify>;
|
|
101
106
|
export declare function scheduleSessionRoute(schedule: Schedule, launch: ScheduleLaunchRecord): string | undefined;
|
|
102
107
|
export declare function nextRun(schedule: Schedule, lastRun?: ScheduleRun): Date | null;
|
|
108
|
+
/** Summarize the newest firing of one owner's schedule, including old single runs. */
|
|
109
|
+
export declare function latestScheduleBatch(runs: ScheduleRun[]): {
|
|
110
|
+
lastRun: ScheduleRun | undefined;
|
|
111
|
+
lastRuns: ScheduleRun[];
|
|
112
|
+
};
|
|
103
113
|
export declare function readScheduleRuns(file: string): Promise<ScheduleRun[]>;
|
|
104
114
|
export declare function writeScheduleRuns(file: string, runs: ScheduleRun[]): Promise<void>;
|
|
105
115
|
export declare function newScheduleId(existing: Iterable<string>): string;
|
|
@@ -4,6 +4,7 @@ import path from "node:path";
|
|
|
4
4
|
import * as yaml from "js-yaml";
|
|
5
5
|
import { z } from "zod";
|
|
6
6
|
import { atomicInPrivateDir, bridgeRoot, object } from "./protocol.js";
|
|
7
|
+
import { isValidProjectName } from "../utils-paths.js";
|
|
7
8
|
import { isAccountSlug } from "./claude-accounts.js";
|
|
8
9
|
/** The schedules.yaml store: the schedule and run record shapes, validation,
|
|
9
10
|
* the five timing forms evaluated in local time, and the run history file. */
|
|
@@ -61,6 +62,9 @@ export function parseSchedule(value) {
|
|
|
61
62
|
createdAt: timestamp.parse(raw.createdAt),
|
|
62
63
|
updatedAt: timestamp.parse(raw.updatedAt),
|
|
63
64
|
};
|
|
65
|
+
if (raw.projects !== undefined)
|
|
66
|
+
schedule.projects = z.array(z.string().refine(isValidProjectName, "Invalid project slug."))
|
|
67
|
+
.min(1).max(64).refine(projects => new Set(projects).size === projects.length, "Projects must be unique.").parse(raw.projects);
|
|
64
68
|
if (raw.model !== undefined)
|
|
65
69
|
schedule.model = singleLine(200).parse(raw.model);
|
|
66
70
|
if (raw.account !== undefined)
|
|
@@ -227,6 +231,18 @@ export function nextRun(schedule, lastRun) {
|
|
|
227
231
|
return nextCron(schedule, after);
|
|
228
232
|
return nextDailyOrWeekly(schedule, after);
|
|
229
233
|
}
|
|
234
|
+
/** Summarize the newest firing of one owner's schedule, including old single runs. */
|
|
235
|
+
export function latestScheduleBatch(runs) {
|
|
236
|
+
const latest = runs.at(-1);
|
|
237
|
+
const lastRuns = latest ? runs.filter(run => latest.batchId ? run.batchId === latest.batchId : run.id === latest.id) : [];
|
|
238
|
+
const priority = ["blocked", "running", "launched", "failed", "needs-you", "finished", "skipped"];
|
|
239
|
+
const representative = [...lastRuns].sort((a, b) => priority.indexOf(a.status) - priority.indexOf(b.status))[0];
|
|
240
|
+
if (!representative)
|
|
241
|
+
return { lastRun: undefined, lastRuns };
|
|
242
|
+
const finishedAt = lastRuns.some(run => runningStatuses.has(run.status)) ? undefined
|
|
243
|
+
: lastRuns.map(run => run.finishedAt).filter((time) => Boolean(time)).sort().at(-1);
|
|
244
|
+
return { lastRun: { ...representative, finishedAt }, lastRuns };
|
|
245
|
+
}
|
|
230
246
|
export async function readScheduleRuns(file) {
|
|
231
247
|
let text;
|
|
232
248
|
try {
|
|
@@ -246,6 +262,8 @@ export async function readScheduleRuns(file) {
|
|
|
246
262
|
const launch = object(raw.launch);
|
|
247
263
|
if (typeof raw.id !== "string" || typeof raw.scheduleId !== "string" || typeof raw.project !== "string"
|
|
248
264
|
|| typeof raw.startedAt !== "string" || !SCHEDULE_RUN_STATUSES.includes(String(raw.status))
|
|
265
|
+
|| (raw.scheduleProject !== undefined && typeof raw.scheduleProject !== "string")
|
|
266
|
+
|| (raw.batchId !== undefined && typeof raw.batchId !== "string")
|
|
249
267
|
|| !["herdr", "headless"].includes(String(launch.mode)))
|
|
250
268
|
continue;
|
|
251
269
|
runs.push(raw);
|
|
@@ -255,7 +273,12 @@ export async function readScheduleRuns(file) {
|
|
|
255
273
|
return runs;
|
|
256
274
|
}
|
|
257
275
|
export async function writeScheduleRuns(file, runs) {
|
|
258
|
-
|
|
276
|
+
// Open children still block their owner. Keep entire retained batches so
|
|
277
|
+
// trimming cannot hide a sibling's failure from the aggregate status.
|
|
278
|
+
const recent = new Set(runs.slice(-MAX_RUNS).map(run => run.id));
|
|
279
|
+
const batches = new Set(runs.filter(run => recent.has(run.id) || runningStatuses.has(run.status))
|
|
280
|
+
.map(run => run.batchId).filter((id) => Boolean(id)));
|
|
281
|
+
const kept = runs.filter(run => recent.has(run.id) || runningStatuses.has(run.status) || (run.batchId && batches.has(run.batchId)));
|
|
259
282
|
await atomicInPrivateDir(file, kept.map(run => JSON.stringify(run)).join("\n") + (kept.length ? "\n" : ""));
|
|
260
283
|
}
|
|
261
284
|
export function newScheduleId(existing) {
|
|
@@ -13,6 +13,7 @@ export declare class Scheduler {
|
|
|
13
13
|
private readonly log;
|
|
14
14
|
private serial;
|
|
15
15
|
private ticking;
|
|
16
|
+
private readonly dispatching;
|
|
16
17
|
/** Runs this process launched; any other open run was left by an earlier Hook. */
|
|
17
18
|
private readonly own;
|
|
18
19
|
private recovered;
|
|
@@ -41,7 +42,8 @@ export declare class Scheduler {
|
|
|
41
42
|
id?: string;
|
|
42
43
|
limit?: number;
|
|
43
44
|
}): Promise<ScheduleRun[]>;
|
|
44
|
-
launchNow(projectName: string, id: string): Promise<ScheduleRun>;
|
|
45
|
+
launchNow(projectName: string, id: string, onlyIfDue?: boolean, expectedUpdatedAt?: string): Promise<ScheduleRun[]>;
|
|
46
|
+
private prepareAndLaunch;
|
|
45
47
|
private updateRun;
|
|
46
48
|
private finishRun;
|
|
47
49
|
private recordBlockedStartup;
|
package/dist/bridge/schedules.js
CHANGED
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { stat } from "node:fs/promises";
|
|
2
3
|
import { hostname } from "node:os";
|
|
3
4
|
import path from "node:path";
|
|
4
5
|
import { BridgeError } from "./protocol.js";
|
|
5
6
|
import { getProjectSourcePath } from "../project-config.js";
|
|
6
7
|
import { getProjectDirs } from "../shared.js";
|
|
7
|
-
import { computerMatches, nextRun, readScheduleDocument, readScheduleRuns, runningStatuses, scheduleNotifications, scheduleSessionRoute, writeScheduleDocument, writeScheduleRuns, } from "./schedule-format.js";
|
|
8
|
+
import { computerMatches, latestScheduleBatch, nextRun, readScheduleDocument, readScheduleRuns, runningStatuses, scheduleNotifications, scheduleSessionRoute, writeScheduleDocument, writeScheduleRuns, } from "./schedule-format.js";
|
|
8
9
|
export * from "./schedule-format.js";
|
|
9
10
|
export * from "./schedule-launch.js";
|
|
10
11
|
export * from "./schedule-watch.js";
|
|
@@ -19,6 +20,7 @@ export class Scheduler {
|
|
|
19
20
|
log;
|
|
20
21
|
serial = Promise.resolve();
|
|
21
22
|
ticking = false;
|
|
23
|
+
dispatching = new Set();
|
|
22
24
|
/** Runs this process launched; any other open run was left by an earlier Hook. */
|
|
23
25
|
own = new Set();
|
|
24
26
|
recovered = false;
|
|
@@ -70,11 +72,13 @@ export class Scheduler {
|
|
|
70
72
|
}
|
|
71
73
|
const project = path.basename(directory);
|
|
72
74
|
for (const schedule of schedules) {
|
|
73
|
-
const matching = runs.filter(run => run.project === project && run.scheduleId === schedule.id);
|
|
74
|
-
const
|
|
75
|
+
const matching = runs.filter(run => (run.scheduleProject ?? run.project) === project && run.scheduleId === schedule.id);
|
|
76
|
+
const { lastRun: last, lastRuns } = latestScheduleBatch(matching);
|
|
77
|
+
const running = matching.some(run => runningStatuses.has(run.status));
|
|
75
78
|
const due = computerMatches(schedule.computer, computer) ? nextRun(schedule, last) : null;
|
|
76
|
-
result.push({ ...schedule, project, nextRun: due?.toISOString() ?? null,
|
|
79
|
+
result.push({ ...schedule, project, lastRuns, nextRun: due?.toISOString() ?? null,
|
|
77
80
|
lastRun: last ? { startedAt: last.startedAt, ...(last.finishedAt ? { finishedAt: last.finishedAt } : {}), status: last.status,
|
|
81
|
+
...(last.batchId ? { batchId: last.batchId, scheduleProject: last.scheduleProject } : {}),
|
|
78
82
|
...(last.reason ? { reason: last.reason } : {}),
|
|
79
83
|
...(last.blockedStartupPrompt ? { blockedStartupPrompt: last.blockedStartupPrompt } : {}),
|
|
80
84
|
...(last.blockNotified !== undefined ? { blockNotified: last.blockNotified } : {}), launch: last.launch } : null, running });
|
|
@@ -84,52 +88,99 @@ export class Scheduler {
|
|
|
84
88
|
}
|
|
85
89
|
async history(filters = {}) {
|
|
86
90
|
const limit = Math.min(500, Math.max(1, filters.limit ?? 50));
|
|
87
|
-
return (await readScheduleRuns(this.runsFile)).filter(run => (!filters.project || run.project.toLowerCase() === filters.project.toLowerCase())
|
|
91
|
+
return (await readScheduleRuns(this.runsFile)).filter(run => (!filters.project || (run.scheduleProject ?? run.project).toLowerCase() === filters.project.toLowerCase())
|
|
88
92
|
&& (!filters.id || run.scheduleId === filters.id)).slice(-limit).reverse();
|
|
89
93
|
}
|
|
90
|
-
async launchNow(projectName, id) {
|
|
94
|
+
async launchNow(projectName, id, onlyIfDue = false, expectedUpdatedAt) {
|
|
95
|
+
const key = `${projectName.toLowerCase()}/${id}`;
|
|
96
|
+
if (this.dispatching.has(key))
|
|
97
|
+
throw new BridgeError(409, "This schedule is already launching.");
|
|
98
|
+
this.dispatching.add(key);
|
|
99
|
+
try {
|
|
100
|
+
return await this.prepareAndLaunch(projectName, id, onlyIfDue, expectedUpdatedAt);
|
|
101
|
+
}
|
|
102
|
+
finally {
|
|
103
|
+
this.dispatching.delete(key);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
async prepareAndLaunch(projectName, id, onlyIfDue, expectedUpdatedAt) {
|
|
91
107
|
const prepared = await this.exclusive(async () => {
|
|
92
108
|
const projectDir = this.projectDirectory(projectName), project = path.basename(projectDir);
|
|
93
109
|
const file = await readScheduleDocument(projectDir), schedule = file.schedules.find(item => item.id === id);
|
|
94
110
|
if (!schedule)
|
|
95
111
|
throw new BridgeError(404, `Schedule "${id}" was not found in ${project}.`);
|
|
112
|
+
if (expectedUpdatedAt !== undefined && Date.parse(expectedUpdatedAt) !== Date.parse(schedule.updatedAt)) {
|
|
113
|
+
throw new BridgeError(409, "This computer has a different schedule revision. Wait for store sync to finish, refresh the schedule, and try Run now again.");
|
|
114
|
+
}
|
|
96
115
|
if (!computerMatches(schedule.computer, this.computer()))
|
|
97
116
|
throw new BridgeError(409, `${schedule.computer} owns this schedule; run it from that computer.`);
|
|
98
117
|
const runs = await readScheduleRuns(this.runsFile);
|
|
99
|
-
|
|
118
|
+
const matching = runs.filter(run => (run.scheduleProject ?? run.project) === project && run.scheduleId === id);
|
|
119
|
+
if (matching.some(run => runningStatuses.has(run.status))) {
|
|
100
120
|
throw new BridgeError(409, `Schedule "${schedule.name}" is already running.`);
|
|
101
121
|
}
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
122
|
+
// Recheck a tick's snapshot after a concurrent Run now or schedule edit.
|
|
123
|
+
const due = nextRun(schedule, matching.at(-1));
|
|
124
|
+
if (onlyIfDue && (!schedule.enabled || !due || due > this.now()))
|
|
125
|
+
return undefined;
|
|
126
|
+
const targets = [];
|
|
127
|
+
for (const name of schedule.projects ?? [project]) {
|
|
128
|
+
const targetDir = this.projectDirectory(name), target = path.basename(targetDir);
|
|
129
|
+
const source = getProjectSourcePath(this.store, target) ?? await this.locateProject(target);
|
|
130
|
+
if (!source && schedule.projects)
|
|
131
|
+
throw new BridgeError(409, `No source directory for project "${target}" on this computer.`);
|
|
132
|
+
const cwd = source ?? targetDir;
|
|
133
|
+
if (!await stat(cwd).then(info => info.isDirectory()).catch(() => false)) {
|
|
134
|
+
throw new BridgeError(409, `Source directory for project "${target}" is unavailable: ${cwd}`);
|
|
135
|
+
}
|
|
136
|
+
targets.push({ project: target, projectDir: targetDir, cwd });
|
|
137
|
+
}
|
|
138
|
+
const batchId = randomUUID(), startedAt = this.now().toISOString();
|
|
139
|
+
const children = targets.map(target => ({ ...target, run: {
|
|
140
|
+
id: randomUUID(), scheduleId: id, project: target.project, scheduleProject: project, batchId,
|
|
141
|
+
startedAt, status: "launched", launch: { mode: "headless" },
|
|
142
|
+
} }));
|
|
143
|
+
// One atomic replacement reserves every target before any external launch.
|
|
144
|
+
await writeScheduleRuns(this.runsFile, [...runs, ...children.map(child => child.run)]);
|
|
145
|
+
for (const child of children)
|
|
146
|
+
this.own.add(child.run.id);
|
|
105
147
|
if (schedule.every === "once" && schedule.enabled) {
|
|
106
|
-
const
|
|
107
|
-
|
|
108
|
-
|
|
148
|
+
const schedules = file.schedules.map(item => item.id === id ? { ...item, enabled: false, updatedAt: startedAt } : item);
|
|
149
|
+
try {
|
|
150
|
+
await writeScheduleDocument(projectDir, schedules, file.document);
|
|
151
|
+
}
|
|
152
|
+
catch (error) {
|
|
153
|
+
// The durable batch already consumes the occurrence. A YAML write
|
|
154
|
+
// failure must not strand pending children in this running process.
|
|
155
|
+
this.log(`[schedule] Could not disable consumed once schedule ${project}/${id}: ${String(error)}`);
|
|
156
|
+
}
|
|
109
157
|
}
|
|
110
|
-
|
|
111
|
-
return { projectDir, project, schedule, run, cwd: source ?? await this.locateProject(project) ?? projectDir };
|
|
158
|
+
return { schedule, children };
|
|
112
159
|
});
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
160
|
+
if (!prepared)
|
|
161
|
+
return [];
|
|
162
|
+
// Independent attempts: one target's startup failure never cancels siblings.
|
|
163
|
+
return Promise.all(prepared.children.map(async (child) => {
|
|
164
|
+
try {
|
|
165
|
+
const launched = await this.launch({ schedule: prepared.schedule, project: child.project, projectDir: child.projectDir,
|
|
166
|
+
cwd: child.cwd, runId: child.run.id,
|
|
167
|
+
blockedStartup: promptText => this.recordBlockedStartup(child.run.id, prepared.schedule, promptText) });
|
|
168
|
+
const running = await this.updateRun(child.run.id, { status: "running", launch: launched.launch });
|
|
169
|
+
const notified = this.notifyRun(running, prepared.schedule, "scheduleStarted");
|
|
170
|
+
if (launched.completion)
|
|
171
|
+
void launched.completion.then(async (result) => {
|
|
172
|
+
await this.finishRun(child.run.id, prepared.schedule, result.status, result.reason, notified);
|
|
173
|
+
}).catch(async (error) => {
|
|
174
|
+
await this.finishRun(child.run.id, prepared.schedule, "failed", error instanceof Error ? error.message : "The scheduled agent failed.", notified);
|
|
175
|
+
}).catch(error => this.log(`[schedule] Could not finish run ${child.run.id}: ${String(error)}`));
|
|
176
|
+
await notified;
|
|
177
|
+
return running;
|
|
178
|
+
}
|
|
179
|
+
catch (error) {
|
|
180
|
+
const reason = error instanceof Error ? error.message : "The scheduled agent could not start.";
|
|
181
|
+
return this.finishRun(child.run.id, prepared.schedule, "failed", reason);
|
|
182
|
+
}
|
|
183
|
+
}));
|
|
133
184
|
}
|
|
134
185
|
async updateRun(id, patch) {
|
|
135
186
|
return this.exclusive(async () => {
|
|
@@ -145,8 +196,9 @@ export class Scheduler {
|
|
|
145
196
|
const run = await this.updateRun(id, { status, finishedAt: this.now().toISOString(), ...(reason ? { reason } : {}) });
|
|
146
197
|
await previousNotification;
|
|
147
198
|
if (run.blockedStartupPrompt && run.blockNotified)
|
|
148
|
-
return;
|
|
199
|
+
return run;
|
|
149
200
|
await this.notifyRun(run, schedule, status === "failed" ? "scheduleFailed" : "scheduleFinished");
|
|
201
|
+
return run;
|
|
150
202
|
}
|
|
151
203
|
async recordBlockedStartup(id, schedule, promptText) {
|
|
152
204
|
try {
|
|
@@ -199,12 +251,16 @@ export class Scheduler {
|
|
|
199
251
|
if (this.recovered || !resume)
|
|
200
252
|
return;
|
|
201
253
|
this.recovered = true;
|
|
202
|
-
const open =
|
|
254
|
+
const open = await this.exclusive(async () => {
|
|
255
|
+
const pending = (await readScheduleRuns(this.runsFile)).filter(run => runningStatuses.has(run.status) && !this.own.has(run.id));
|
|
256
|
+
for (const run of pending)
|
|
257
|
+
this.own.add(run.id);
|
|
258
|
+
return pending;
|
|
259
|
+
});
|
|
203
260
|
for (const run of open) {
|
|
204
|
-
this.own.add(run.id);
|
|
205
261
|
let schedule;
|
|
206
262
|
try {
|
|
207
|
-
schedule = (await readScheduleDocument(this.projectDirectory(run.project))).schedules.find(item => item.id === run.scheduleId);
|
|
263
|
+
schedule = (await readScheduleDocument(this.projectDirectory(run.scheduleProject ?? run.project))).schedules.find(item => item.id === run.scheduleId);
|
|
208
264
|
}
|
|
209
265
|
catch {
|
|
210
266
|
schedule = undefined;
|
|
@@ -234,7 +290,7 @@ export class Scheduler {
|
|
|
234
290
|
for (const schedule of status.schedules) {
|
|
235
291
|
if (!schedule.enabled || schedule.running || !schedule.nextRun || new Date(schedule.nextRun) > now)
|
|
236
292
|
continue;
|
|
237
|
-
await this.launchNow(schedule.project, schedule.id).catch(() => { });
|
|
293
|
+
await this.launchNow(schedule.project, schedule.id, true).catch(() => { });
|
|
238
294
|
}
|
|
239
295
|
}
|
|
240
296
|
finally {
|