@phren/cli 0.3.31 → 0.3.33
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- 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/computer-names.d.ts +4 -0
- package/dist/bridge/computer-names.js +19 -0
- 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/model-switch.d.ts +4 -0
- package/dist/bridge/model-switch.js +16 -4
- package/dist/bridge/projects.d.ts +8 -0
- package/dist/bridge/projects.js +142 -24
- package/dist/bridge/schedule-format.d.ts +12 -0
- package/dist/bridge/schedule-format.js +33 -2
- package/dist/bridge/schedules.d.ts +8 -1
- package/dist/bridge/schedules.js +109 -45
- 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/server.js +1 -0
- package/dist/bridge/settings-switch.js +2 -6
- 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 +2794 -2223
- 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
|
@@ -24,6 +24,10 @@ export declare function claudeEffortReply(text: string): EffortReply | undefined
|
|
|
24
24
|
/** Empty prompts can draw a dim placeholder. Only ANSI evidence that every
|
|
25
25
|
* character after the prompt is dim distinguishes that from a person's draft. */
|
|
26
26
|
export declare function emptyComposer(line: string): boolean;
|
|
27
|
+
/** Typing a slash command into a draft or an open menu would corrupt both, so
|
|
28
|
+
* the terminal must show an empty composer and no menu first. The `code` says
|
|
29
|
+
* which: the phone names the cause and offers the terminal. */
|
|
30
|
+
export declare function assertComposerReady(before: string, action: string): void;
|
|
27
31
|
/** Only a footer below Codex's empty composer proves the active model. Text
|
|
28
32
|
* in history, a menu, or the startup banner must never confirm a switch. */
|
|
29
33
|
export declare function codexModelStatus(text: string, model: AgentModel): boolean;
|
|
@@ -82,6 +82,21 @@ export function emptyComposer(line) {
|
|
|
82
82
|
}
|
|
83
83
|
return prompt;
|
|
84
84
|
}
|
|
85
|
+
/** Typing a slash command into a draft or an open menu would corrupt both, so
|
|
86
|
+
* the terminal must show an empty composer and no menu first. The `code` says
|
|
87
|
+
* which: the phone names the cause and offers the terminal. */
|
|
88
|
+
export function assertComposerReady(before, action) {
|
|
89
|
+
const composer = before.split(/\r?\n/).reverse().find(line => /^\s*[›❯>]/.test(stripTerminal(line)));
|
|
90
|
+
if (visibleTerminalChoice(stripTerminal(before))) {
|
|
91
|
+
throw new BridgeError(409, `A menu is open in the terminal. Open terminal to finish it, then ${action}.`, { code: "terminal-menu" });
|
|
92
|
+
}
|
|
93
|
+
if (!composer) {
|
|
94
|
+
throw new BridgeError(409, `Phren couldn't find the terminal's input line. Open terminal to ${action}.`, { code: "terminal-unreadable" });
|
|
95
|
+
}
|
|
96
|
+
if (!emptyComposer(composer)) {
|
|
97
|
+
throw new BridgeError(409, `There's unsent text in the terminal. Send or clear it, then ${action}.`, { code: "terminal-draft" });
|
|
98
|
+
}
|
|
99
|
+
}
|
|
85
100
|
/** Only a footer below Codex's empty composer proves the active model. Text
|
|
86
101
|
* in history, a menu, or the startup banner must never confirm a switch. */
|
|
87
102
|
export function codexModelStatus(text, model) {
|
|
@@ -182,10 +197,7 @@ export class ModelSwitcher {
|
|
|
182
197
|
let claudeEffort;
|
|
183
198
|
const before = await this.hooks.paneLines(target, false);
|
|
184
199
|
// Preserve a person's draft and any pre-existing menu. Never clear it.
|
|
185
|
-
|
|
186
|
-
if (!composer || !emptyComposer(composer) || visibleTerminalChoice(stripTerminal(before))) {
|
|
187
|
-
throw new BridgeError(409, "The terminal has a draft or an unreadable prompt. Open terminal before switching models.");
|
|
188
|
-
}
|
|
200
|
+
assertComposerReady(before, "switch models");
|
|
189
201
|
await validate(true);
|
|
190
202
|
opened = true;
|
|
191
203
|
this.hooks.menuOpened(target, "/model");
|
|
@@ -1,6 +1,14 @@
|
|
|
1
1
|
import { type Json } from "./protocol.js";
|
|
2
|
+
/** Nested reads share one deadline. Abort and reap outstanding Git processes on
|
|
3
|
+
* expiry or failure; never leave a timed-out request running its command chain. */
|
|
4
|
+
export declare function withGitReadDeadline<T>(read: () => Promise<T>): Promise<T>;
|
|
5
|
+
/** Bind Git to the selected checkout, even when Hook inherited another Git
|
|
6
|
+
* process's repository/index environment. Keep user config (including excludes). */
|
|
7
|
+
export declare function checkoutGitEnv(): NodeJS.ProcessEnv;
|
|
2
8
|
export declare function git(cwd: string, ...args: string[]): Promise<string>;
|
|
3
9
|
export declare function gitRoot(dir: string): Promise<string | undefined>;
|
|
10
|
+
/** An unborn HEAD is normal; process/configuration failures are not. */
|
|
11
|
+
export declare function gitHead(root: string): Promise<string | undefined>;
|
|
4
12
|
/** The pane's working tree, plus anything the command named: files in the
|
|
5
13
|
* same repository that a hook already committed, and files in other
|
|
6
14
|
* repositories — the phren store, a sibling checkout — grouped by root. */
|
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,7 +88,10 @@ 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;
|
|
93
|
+
/** Whether this computer owns the schedule: it runs it and answers Run now. */
|
|
94
|
+
owned: boolean;
|
|
88
95
|
}
|
|
89
96
|
interface ScheduleDocument {
|
|
90
97
|
document: Record<string, unknown>;
|
|
@@ -100,6 +107,11 @@ export declare function computerMatches(wanted: string, current: string): boolea
|
|
|
100
107
|
export declare function scheduleNotifications(schedule: Schedule): Set<ScheduleNotify>;
|
|
101
108
|
export declare function scheduleSessionRoute(schedule: Schedule, launch: ScheduleLaunchRecord): string | undefined;
|
|
102
109
|
export declare function nextRun(schedule: Schedule, lastRun?: ScheduleRun): Date | null;
|
|
110
|
+
/** Summarize the newest firing of one owner's schedule, including old single runs. */
|
|
111
|
+
export declare function latestScheduleBatch(runs: ScheduleRun[]): {
|
|
112
|
+
lastRun: ScheduleRun | undefined;
|
|
113
|
+
lastRuns: ScheduleRun[];
|
|
114
|
+
};
|
|
103
115
|
export declare function readScheduleRuns(file: string): Promise<ScheduleRun[]>;
|
|
104
116
|
export declare function writeScheduleRuns(file: string, runs: ScheduleRun[]): Promise<void>;
|
|
105
117
|
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)
|
|
@@ -117,8 +121,16 @@ export function canonicalComputer(value) {
|
|
|
117
121
|
const normalized = value.trim().toLowerCase();
|
|
118
122
|
return normalized.endsWith(".local") ? normalized.slice(0, -".local".length) : normalized;
|
|
119
123
|
}
|
|
124
|
+
/** One computer's names differ only in punctuation across macOS ("Sam’s Mac mini",
|
|
125
|
+
* "Sams-Mac-mini"), so letters and digits alone also match. */
|
|
126
|
+
function foldedComputer(value) {
|
|
127
|
+
return canonicalComputer(value).replace(/[^\p{L}\p{N}]/gu, "");
|
|
128
|
+
}
|
|
120
129
|
export function computerMatches(wanted, current) {
|
|
121
|
-
|
|
130
|
+
if (canonicalComputer(wanted) === canonicalComputer(current))
|
|
131
|
+
return true;
|
|
132
|
+
const folded = foldedComputer(wanted);
|
|
133
|
+
return folded !== "" && folded === foldedComputer(current);
|
|
122
134
|
}
|
|
123
135
|
export function scheduleNotifications(schedule) {
|
|
124
136
|
return new Set(schedule.notify ?? ["finish", "failure"]);
|
|
@@ -227,6 +239,18 @@ export function nextRun(schedule, lastRun) {
|
|
|
227
239
|
return nextCron(schedule, after);
|
|
228
240
|
return nextDailyOrWeekly(schedule, after);
|
|
229
241
|
}
|
|
242
|
+
/** Summarize the newest firing of one owner's schedule, including old single runs. */
|
|
243
|
+
export function latestScheduleBatch(runs) {
|
|
244
|
+
const latest = runs.at(-1);
|
|
245
|
+
const lastRuns = latest ? runs.filter(run => latest.batchId ? run.batchId === latest.batchId : run.id === latest.id) : [];
|
|
246
|
+
const priority = ["blocked", "running", "launched", "failed", "needs-you", "finished", "skipped"];
|
|
247
|
+
const representative = [...lastRuns].sort((a, b) => priority.indexOf(a.status) - priority.indexOf(b.status))[0];
|
|
248
|
+
if (!representative)
|
|
249
|
+
return { lastRun: undefined, lastRuns };
|
|
250
|
+
const finishedAt = lastRuns.some(run => runningStatuses.has(run.status)) ? undefined
|
|
251
|
+
: lastRuns.map(run => run.finishedAt).filter((time) => Boolean(time)).sort().at(-1);
|
|
252
|
+
return { lastRun: { ...representative, finishedAt }, lastRuns };
|
|
253
|
+
}
|
|
230
254
|
export async function readScheduleRuns(file) {
|
|
231
255
|
let text;
|
|
232
256
|
try {
|
|
@@ -246,6 +270,8 @@ export async function readScheduleRuns(file) {
|
|
|
246
270
|
const launch = object(raw.launch);
|
|
247
271
|
if (typeof raw.id !== "string" || typeof raw.scheduleId !== "string" || typeof raw.project !== "string"
|
|
248
272
|
|| typeof raw.startedAt !== "string" || !SCHEDULE_RUN_STATUSES.includes(String(raw.status))
|
|
273
|
+
|| (raw.scheduleProject !== undefined && typeof raw.scheduleProject !== "string")
|
|
274
|
+
|| (raw.batchId !== undefined && typeof raw.batchId !== "string")
|
|
249
275
|
|| !["herdr", "headless"].includes(String(launch.mode)))
|
|
250
276
|
continue;
|
|
251
277
|
runs.push(raw);
|
|
@@ -255,7 +281,12 @@ export async function readScheduleRuns(file) {
|
|
|
255
281
|
return runs;
|
|
256
282
|
}
|
|
257
283
|
export async function writeScheduleRuns(file, runs) {
|
|
258
|
-
|
|
284
|
+
// Open children still block their owner. Keep entire retained batches so
|
|
285
|
+
// trimming cannot hide a sibling's failure from the aggregate status.
|
|
286
|
+
const recent = new Set(runs.slice(-MAX_RUNS).map(run => run.id));
|
|
287
|
+
const batches = new Set(runs.filter(run => recent.has(run.id) || runningStatuses.has(run.status))
|
|
288
|
+
.map(run => run.batchId).filter((id) => Boolean(id)));
|
|
289
|
+
const kept = runs.filter(run => recent.has(run.id) || runningStatuses.has(run.status) || (run.batchId && batches.has(run.batchId)));
|
|
259
290
|
await atomicInPrivateDir(file, kept.map(run => JSON.stringify(run)).join("\n") + (kept.length ? "\n" : ""));
|
|
260
291
|
}
|
|
261
292
|
export function newScheduleId(existing) {
|
|
@@ -8,11 +8,14 @@ export declare class Scheduler {
|
|
|
8
8
|
private readonly launch;
|
|
9
9
|
private readonly runsFile;
|
|
10
10
|
private readonly computer;
|
|
11
|
+
/** Every name this computer answers to; a schedule names one of them. */
|
|
12
|
+
private readonly names;
|
|
11
13
|
private readonly locateProject;
|
|
12
14
|
private readonly push?;
|
|
13
15
|
private readonly log;
|
|
14
16
|
private serial;
|
|
15
17
|
private ticking;
|
|
18
|
+
private readonly dispatching;
|
|
16
19
|
/** Runs this process launched; any other open run was left by an earlier Hook. */
|
|
17
20
|
private readonly own;
|
|
18
21
|
private recovered;
|
|
@@ -24,6 +27,8 @@ export declare class Scheduler {
|
|
|
24
27
|
launch: ScheduleLauncher;
|
|
25
28
|
runsFile: string;
|
|
26
29
|
computer?: string | (() => string);
|
|
30
|
+
/** Further names this computer answers to, such as its Hook computer id. */
|
|
31
|
+
aliases?: string[];
|
|
27
32
|
locateProject?: (project: string) => Promise<string | undefined>;
|
|
28
33
|
push?: SchedulePushSender;
|
|
29
34
|
log?: (message: string) => void;
|
|
@@ -31,6 +36,7 @@ export declare class Scheduler {
|
|
|
31
36
|
private projectDirectories;
|
|
32
37
|
private projectDirectory;
|
|
33
38
|
private exclusive;
|
|
39
|
+
private owns;
|
|
34
40
|
statuses(): Promise<{
|
|
35
41
|
computer: string;
|
|
36
42
|
timeZone: string;
|
|
@@ -41,7 +47,8 @@ export declare class Scheduler {
|
|
|
41
47
|
id?: string;
|
|
42
48
|
limit?: number;
|
|
43
49
|
}): Promise<ScheduleRun[]>;
|
|
44
|
-
launchNow(projectName: string, id: string): Promise<ScheduleRun>;
|
|
50
|
+
launchNow(projectName: string, id: string, onlyIfDue?: boolean, expectedUpdatedAt?: string): Promise<ScheduleRun[]>;
|
|
51
|
+
private prepareAndLaunch;
|
|
45
52
|
private updateRun;
|
|
46
53
|
private finishRun;
|
|
47
54
|
private recordBlockedStartup;
|