@phren/cli 0.3.42 → 0.3.44

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.
@@ -81,6 +81,11 @@ function recordFor(server, pane, by, session) {
81
81
  ...(session ? { session } : {}), since: new Date().toISOString(), by,
82
82
  };
83
83
  }
84
+ /** The one pane in a snapshot whose agent reports this session; none when it is absent or ambiguous. */
85
+ function sessionPane(session, s) {
86
+ const found = objects(s.panes).filter(p => runsAgent(p) && objects([p.agent_session])[0]?.value === session);
87
+ return found.length === 1 ? found[0] : undefined;
88
+ }
84
89
  /** The recorded pane in a snapshot of its server, when it is still the same terminal. */
85
90
  function recordedPane(record, s) {
86
91
  const pane = objects(s.panes).find(p => p.pane_id === record.pane);
@@ -109,10 +114,17 @@ export function conductorPane(server, s) {
109
114
  const record = state.conductor;
110
115
  if (!record || record.server !== server)
111
116
  return undefined;
112
- const pane = recordedPane(record, s);
117
+ let pane = recordedPane(record, s);
113
118
  if (!pane) {
114
- await writeRoleState({ ...state, conductor: null });
115
- return undefined;
119
+ // The pane went away or was recreated (a moved tab, a Herdr restart): the
120
+ // role follows the session, so a pane running it takes the role over.
121
+ const adopted = record.session ? sessionPane(record.session, s) : undefined;
122
+ if (!adopted) {
123
+ await writeRoleState({ ...state, conductor: null });
124
+ return undefined;
125
+ }
126
+ await writeRoleState({ ...state, conductor: { ...recordFor(server, adopted, record.by, record.session), since: record.since } });
127
+ return adopted;
116
128
  }
117
129
  // Keep the place current: a pane moved to another tab or workspace is the same pane.
118
130
  const moved = (id.safeParse(pane.workspace_id).success && pane.workspace_id !== record.workspace) || (id.safeParse(pane.tab_id).success && pane.tab_id !== record.tab)
@@ -18,6 +18,13 @@ export async function runDispatch(args) {
18
18
  console.log(JSON.stringify(await hookRequest("/v1/dispatch/report", { origin, prs: prsSchema.parse(JSON.parse(values.prs)), ...(dispatch ? { dispatch } : {}) }), null, 2));
19
19
  return 0;
20
20
  }
21
+ if (args.length === 1 && args[0] === "close-self") {
22
+ const origin = await terminalPaneFromEnv();
23
+ if (!origin)
24
+ throw new Error("phren dispatch close-self runs inside the agent's own terminal pane.");
25
+ console.log(JSON.stringify(await hookRequest("/v1/dispatch/close-self", { origin }), null, 2));
26
+ return 0;
27
+ }
21
28
  if (args.length === 1 && args[0] === "status") {
22
29
  console.log(JSON.stringify(await hookRequest("/v1/dispatch"), null, 2));
23
30
  return 0;
@@ -29,4 +29,9 @@ export declare const findingWriteSchema: z.ZodObject<{
29
29
  name: z.ZodOptional<z.ZodString>;
30
30
  }, z.core.$strict>>;
31
31
  }, z.core.$strict>;
32
+ /** Complete one task by its stable id (`bid:` plus 8 hex digits), as `/tasks?branch=` lists it. */
33
+ export declare const taskCompleteSchema: z.ZodObject<{
34
+ id: z.ZodString;
35
+ }, z.core.$strict>;
36
+ export type TaskComplete = z.infer<typeof taskCompleteSchema>;
32
37
  export type FindingWrite = z.infer<typeof findingWriteSchema>;
@@ -44,3 +44,5 @@ export const findingWriteSchema = z.object({
44
44
  name: z.string().min(1).max(200).refine(value => !/[\x00-\x1f\x7f]/.test(value)).optional(),
45
45
  }).strict().optional(),
46
46
  }).strict();
47
+ /** Complete one task by its stable id (`bid:` plus 8 hex digits), as `/tasks?branch=` lists it. */
48
+ export const taskCompleteSchema = z.object({ id: z.string().regex(/^bid:[0-9a-f]{8}$/) }).strict();
@@ -241,7 +241,7 @@ async function runScopedPair(args, version) {
241
241
  text = await readFile(key, "utf8");
242
242
  const line = await acceptScopedKey(scope, text);
243
243
  const fingerprint = await hostFingerprint();
244
- console.log(`Authorized ${SCOPE_KEY_COMMENT[scope]} for ${scope}: ${scope === "gitboy-write" ? "POST /v1/projects/<project>/findings only" : "GET /v1/projects/<project>/memory, memory/files, memory/search and tasks only"}.`);
244
+ console.log(`Authorized ${SCOPE_KEY_COMMENT[scope]} for ${scope}: ${scope === "gitboy-write" ? "POST /v1/projects/<project>/findings and tasks/complete only" : "GET /v1/projects/<project>/memory, memory/files, memory/search and tasks only"}.`);
245
245
  console.log(` ${line}`);
246
246
  console.log(` SSH user: ${userInfo().username} host key: ${fingerprint ?? "unknown (no /etc/ssh/ssh_host_ed25519_key.pub)"}`);
247
247
  console.log(` Addresses: ${(await pairingHosts()).join(", ") || "none found"}`);
@@ -16,6 +16,8 @@ export declare function paneStatus(server: string, pane: string, terminal: strin
16
16
  status: string;
17
17
  seq: number;
18
18
  } | undefined>;
19
+ /** Claude's optional "Teach auto mode about your environment?" dialog. */
20
+ export declare function claudeTeachAutoModeDialog(screen: string): boolean;
19
21
  /** Whether `screen` (a pane's visible lines, with or without colors) shows a
20
22
  * dialog waiting for `agent`'s owner. Stricter than the readers that answer
21
23
  * a dialog, because it runs while the agent is still writing: Claude's and
@@ -90,6 +90,10 @@ export async function paneStatus(server, pane, terminal) {
90
90
  return undefined;
91
91
  }
92
92
  }
93
+ /** Claude's optional "Teach auto mode about your environment?" dialog. */
94
+ export function claudeTeachAutoModeDialog(screen) {
95
+ return /Teach auto mode about your environment/i.test(stripTerminal(screen));
96
+ }
93
97
  /** Whether `screen` (a pane's visible lines, with or without colors) shows a
94
98
  * dialog waiting for `agent`'s owner. Stricter than the readers that answer
95
99
  * a dialog, because it runs while the agent is still writing: Claude's and
@@ -101,7 +105,7 @@ export function screenDialog(agent, screen) {
101
105
  return !!opencodePermissionDialog(screen);
102
106
  if (agent === "codex" || agent === "copilot")
103
107
  return !!visibleTerminalChoice(text);
104
- if (agent === "claude" && claudeQuestionDialog(text))
108
+ if (agent === "claude" && (claudeQuestionDialog(text) || claudeTeachAutoModeDialog(text)))
105
109
  return true;
106
110
  return /Esc to cancel/i.test(text) && !!numberedDialog(text);
107
111
  }
@@ -0,0 +1,8 @@
1
+ import { type Json } from "./protocol.js";
2
+ /** `GET /v1/projects/:project/git`: the project's host, branch and open pull
3
+ * requests with their checks, read from its checkout on this computer, so the
4
+ * desktop's Projects page needs no session running there. */
5
+ export declare const PROJECT_GIT_ROUTE: RegExp;
6
+ /** The recorded source folder for this computer wins; otherwise the folders
7
+ * `/v1/projects/locate` offers, newest session first. */
8
+ export declare function projectGit(base: string, rawProject: string, activity: Json[]): Promise<Json>;
@@ -0,0 +1,39 @@
1
+ import { getProjectSourcePath } from "../project-config.js";
2
+ import { resolveProject } from "../store-routing.js";
3
+ import { isValidProjectName } from "../utils.js";
4
+ import { gitPulls } from "./git.js";
5
+ import { locateProject } from "./locate.js";
6
+ import { gitRoot } from "./projects.js";
7
+ import { BridgeError } from "./protocol.js";
8
+ /** `GET /v1/projects/:project/git`: the project's host, branch and open pull
9
+ * requests with their checks, read from its checkout on this computer, so the
10
+ * desktop's Projects page needs no session running there. */
11
+ export const PROJECT_GIT_ROUTE = /^\/v1\/projects\/([^/]+)\/git$/;
12
+ /** The recorded source folder for this computer wins; otherwise the folders
13
+ * `/v1/projects/locate` offers, newest session first. */
14
+ export async function projectGit(base, rawProject, activity) {
15
+ let project;
16
+ try {
17
+ project = decodeURIComponent(rawProject);
18
+ }
19
+ catch {
20
+ throw new BridgeError(400, "Invalid project name.");
21
+ }
22
+ if (!isValidProjectName(project))
23
+ throw new BridgeError(400, "Invalid project name.");
24
+ const folders = [];
25
+ try {
26
+ const source = getProjectSourcePath(resolveProject(base, project).store.path, project);
27
+ if (source)
28
+ folders.push(source);
29
+ }
30
+ catch { /* not in the store: located folders only */ }
31
+ for (const candidate of await locateProject(project, activity))
32
+ folders.push(candidate.directory);
33
+ for (const folder of folders) {
34
+ const root = await gitRoot(folder).catch(() => undefined);
35
+ if (root)
36
+ return { project, directory: root, ...(await gitPulls(root)) };
37
+ }
38
+ throw new BridgeError(404, "No checkout of this project on this computer.", { code: "no-checkout" });
39
+ }
@@ -92,3 +92,15 @@ export declare function saveFinding(base: string, rawProject: string, input: unk
92
92
  status: string;
93
93
  finding: MemoryFinding | null;
94
94
  }>;
95
+ /** Mark one open task done, by the stable id `/tasks?branch=` gave gitboy when
96
+ * its pull request merged. Exact ids only: no text matching, so a wrong guess
97
+ * can never complete another task. A task already done answers `already-done`. */
98
+ export declare function completeProjectTask(base: string, rawProject: string, input: unknown): {
99
+ project: string;
100
+ id: string;
101
+ status: "already-done";
102
+ } | {
103
+ project: string;
104
+ id: string;
105
+ status: "completed";
106
+ };
@@ -1,7 +1,7 @@
1
1
  import * as fs from "node:fs";
2
2
  import * as path from "node:path";
3
3
  import { readFindings } from "../data/access.js";
4
- import { readTasks } from "../data/tasks.js";
4
+ import { completeTask, readTasks } from "../data/tasks.js";
5
5
  import { taskStores } from "../data/task-store-directory.js";
6
6
  import { FINDING_TAGS } from "../phren-core.js";
7
7
  import { getProjectRemote, readProjectConfig } from "../project-config.js";
@@ -12,13 +12,13 @@ import { BridgeError } from "./protocol.js";
12
12
  import { moduleEnabled } from "../modules/runtime.js";
13
13
  import { loadCodePackage } from "../modules/code-package.js";
14
14
  import { bestChunkMatch, tokenizeForOverlap } from "../shared/retrieval.js";
15
- import { findingWriteSchema, isBranchName, isRepoPath, isSearchText, MAX_FILE_PATHS, MAX_FINDING_BODY, MAX_SEARCH_LIMIT } from "./gitboy-contract.js";
15
+ import { findingWriteSchema, taskCompleteSchema, isBranchName, isRepoPath, isSearchText, MAX_FILE_PATHS, MAX_FINDING_BODY, MAX_SEARCH_LIMIT } from "./gitboy-contract.js";
16
16
  // `GET /v1/projects/:project/memory`: one project's findings, truths and
17
17
  // tasks as a fixed read-only contract, for a client that renders them beside
18
18
  // the repository (gitboy). Phren stays the source of truth; nothing here
19
19
  // writes. The scoped `gitboy-read` SSH key reaches only this route
20
20
  // (scoped-gateway.ts). Contract: docs/phren-hook.md#gitboy-read-only-memory.
21
- export const PROJECT_MEMORY_ROUTE = /^\/v1\/projects\/([^/]+)\/(memory|memory\/files|memory\/search|tasks|findings)$/;
21
+ export const PROJECT_MEMORY_ROUTE = /^\/v1\/projects\/([^/]+)\/(memory|memory\/files|memory\/search|tasks|tasks\/complete|findings)$/;
22
22
  export const MEMORY_LIMITS = { findings: 500, active: 200, queue: 200, done: 50 };
23
23
  const TAG = new RegExp(`^\\[(${FINDING_TAGS.join("|")})\\]\\s*`, "i");
24
24
  const DATE = /^\d{4}-\d{2}-\d{2}/;
@@ -233,3 +233,27 @@ export async function saveFinding(base, rawProject, input) {
233
233
  .find(item => item.text === (result.data?.finding ?? "").replace(/^-\s+/, "").trim()) : undefined;
234
234
  return { project, status, finding: saved ? finding(saved) : null };
235
235
  }
236
+ // ── POST /tasks/complete ─────────────────────────────────────────────────────
237
+ /** Mark one open task done, by the stable id `/tasks?branch=` gave gitboy when
238
+ * its pull request merged. Exact ids only: no text matching, so a wrong guess
239
+ * can never complete another task. A task already done answers `already-done`. */
240
+ export function completeProjectTask(base, rawProject, input) {
241
+ const { project, root } = locate(base, rawProject);
242
+ if (Buffer.byteLength(JSON.stringify(input ?? null)) > 256)
243
+ throw new BridgeError(413, "The body must be at most 256 bytes.");
244
+ const { id } = taskCompleteSchema.parse(input);
245
+ const doc = readTasks(root, project);
246
+ if (!doc.ok)
247
+ throw new BridgeError(404, "No tasks for this project.");
248
+ const stable = id.slice(4);
249
+ const open = [...doc.data.items.Active, ...doc.data.items.Queue].find(item => item.stableId === stable);
250
+ if (!open) {
251
+ if (doc.data.items.Done.some(item => item.stableId === stable))
252
+ return { project, id, status: "already-done" };
253
+ throw new BridgeError(404, "No task with this id.");
254
+ }
255
+ const done = completeTask(root, project, id);
256
+ if (!done.ok)
257
+ throw new BridgeError(400, safe(done.error));
258
+ return { project, id, status: "completed" };
259
+ }
@@ -83,8 +83,8 @@ export interface ScheduleLaunchContext {
83
83
  projectDir: string;
84
84
  cwd: string;
85
85
  runId: string;
86
- /** With `session: reuse`, the session this target's last run used, to continue if it is still open. */
87
- reuse?: ScheduleLaunchRecord;
86
+ /** With `session: reuse`, the panes this target's earlier runs used, newest first: the newest still open is continued. */
87
+ reuse?: ScheduleLaunchRecord[];
88
88
  blockedStartup?: (promptText: string) => void | Promise<void>;
89
89
  }
90
90
  export type ScheduleLauncher = ((context: ScheduleLaunchContext) => Promise<ScheduleLaunchResult>) & {
@@ -103,6 +103,8 @@ export interface ScheduleStatus extends Schedule {
103
103
  running: boolean;
104
104
  /** Whether this computer owns the schedule: it runs it and answers Run now. */
105
105
  owned: boolean;
106
+ /** Why this schedule can never fire, when something is wrong with its computer or source paths. */
107
+ problems?: string[];
106
108
  }
107
109
  interface ScheduleDocument {
108
110
  document: Record<string, unknown>;
@@ -123,8 +125,8 @@ export declare function latestScheduleBatch(runs: ScheduleRun[]): {
123
125
  lastRun: ScheduleRun | undefined;
124
126
  lastRuns: ScheduleRun[];
125
127
  };
126
- /** The newest Herdr session among a target's runs, which `session: reuse` continues. */
127
- export declare function reusableLaunch(runs: readonly ScheduleRun[]): ScheduleLaunchRecord | undefined;
128
+ /** The distinct Herdr panes a target's runs used, newest first, which `session: reuse` continues (the newest still open) and tidies (the older finished ones). */
129
+ export declare function reusableLaunches(runs: readonly ScheduleRun[]): ScheduleLaunchRecord[];
128
130
  export declare function readScheduleRuns(file: string): Promise<ScheduleRun[]>;
129
131
  export declare function writeScheduleRuns(file: string, runs: ScheduleRun[]): Promise<void>;
130
132
  export declare function newScheduleId(existing: Iterable<string>): string;
@@ -255,14 +255,22 @@ export function latestScheduleBatch(runs) {
255
255
  : lastRuns.map(run => run.finishedAt).filter((time) => Boolean(time)).sort().at(-1);
256
256
  return { lastRun: { ...representative, finishedAt }, lastRuns };
257
257
  }
258
- /** The newest Herdr session among a target's runs, which `session: reuse` continues. */
259
- export function reusableLaunch(runs) {
260
- for (let index = runs.length - 1; index >= 0; index--) {
258
+ /** Max panes of one schedule `session: reuse` looks through, and tidies. */
259
+ const REUSE_PANES = 8;
260
+ /** The distinct Herdr panes a target's runs used, newest first, which `session: reuse` continues (the newest still open) and tidies (the older finished ones). */
261
+ export function reusableLaunches(runs) {
262
+ const seen = new Set(), found = [];
263
+ for (let index = runs.length - 1; index >= 0 && found.length < REUSE_PANES; index--) {
261
264
  const launch = runs[index].launch;
262
- if (launch.mode === "herdr" && launch.server && launch.workspaceId && launch.tabId && launch.paneId && launch.sessionId)
263
- return launch;
265
+ if (launch.mode !== "herdr" || !launch.server || !launch.workspaceId || !launch.tabId || !launch.paneId)
266
+ continue;
267
+ const key = [launch.server, launch.workspaceId, launch.tabId, launch.paneId].join("\0");
268
+ if (seen.has(key))
269
+ continue;
270
+ seen.add(key);
271
+ found.push(launch);
264
272
  }
265
- return undefined;
273
+ return found;
266
274
  }
267
275
  export async function readScheduleRuns(file) {
268
276
  let text;
@@ -9,15 +9,25 @@ export interface ContinueEnv {
9
9
  panes?: (server: string) => Promise<Json[]>;
10
10
  transcriptStamp?: typeof realTranscriptStamp;
11
11
  watch?: typeof watchHerdrRun;
12
+ /** The conversation a pane runs, for a record that never learned its id. */
13
+ identity?: (server: string, pane: Json) => Promise<string | undefined>;
14
+ /** The pane's visible lines, to see a dialog that would swallow the prompt. */
15
+ screen?: (server: string, pane: string) => Promise<string>;
16
+ keys?: (server: string, pane: string, keys: string[]) => Promise<void>;
17
+ /** Closes a finished pane of this schedule once a newer one has taken the firing. */
18
+ close?: (server: string, pane: Json) => Promise<void>;
12
19
  }
13
20
  /**
14
- * `session: reuse`: types the prompt into the session the target's last run
15
- * used, while its pane still runs that harness. A busy session is skipped
16
- * rather than given a second prompt. Undefined when the session is gone (the
17
- * pane closed, its agent exited, its conversation was replaced), so the caller
18
- * starts a new one, which the next firing continues.
21
+ * `session: reuse`: types the prompt into the newest session of this schedule
22
+ * whose pane still runs its harness (`previous`, newest first). A busy newest
23
+ * session is skipped rather than given a second prompt; a pane whose prompt
24
+ * cannot be delivered (a dialog that will not dismiss, a refused delivery)
25
+ * passes the firing to the next older one. Once a pane has taken the firing,
26
+ * the schedule's older finished panes are closed. Undefined when no session is
27
+ * left (the panes closed, their agents exited, their conversations were
28
+ * replaced), so the caller starts a new one, which the next firing continues.
19
29
  */
20
- export declare function continueSession(context: ScheduleLaunchContext, previous: ScheduleLaunchRecord, deliver: ScheduleDeliver, signal: AbortSignal, env?: ContinueEnv): Promise<ScheduleLaunchResult | undefined>;
30
+ export declare function continueSession(context: ScheduleLaunchContext, previous: ScheduleLaunchRecord[], deliver: ScheduleDeliver, signal: AbortSignal, env?: ContinueEnv): Promise<ScheduleLaunchResult | undefined>;
21
31
  /**
22
32
  * The outcome of a run a previous Hook process launched and never saw finish
23
33
  * (a restart or crash mid-run). A Herdr pane is followed again to its real
@@ -13,6 +13,7 @@ import { agentNotReady, terminalProvider } from "./terminal.js";
13
13
  import { atomicInPrivateDir, BridgeError, object, objects } from "./protocol.js";
14
14
  import { defaultPhrenPath } from "../shared.js";
15
15
  import { realTranscriptStamp, watchHerdrRun } from "./schedule-watch.js";
16
+ import { claudeTeachAutoModeDialog } from "./pane-status.js";
16
17
  /** Starting a scheduled run: in a Herdr pane when a server is live, otherwise
17
18
  * as a headless job under the fan-out root. */
18
19
  const CLAUDE_SCHEDULE_SETTINGS = JSON.stringify({ enableAllProjectMcpServers: true });
@@ -38,45 +39,90 @@ function busyReason(status) {
38
39
  const state = status === "blocked" || status === "waiting" ? "is waiting for you" : status === "working" || status === "starting" ? "is still working" : `is ${status || "busy"}`;
39
40
  return `The session this schedule continues ${state}, so this firing was skipped.`;
40
41
  }
42
+ const finishedPane = (pane) => pane.agent_status === "idle" || pane.agent_status === "done";
43
+ /** Claude's optional "Teach auto mode about your environment?" dialog takes a typed prompt as an answer. */
44
+ async function dismissAutoModeDialog(server, pane, env) {
45
+ const screen = env.screen ?? ((name, id) => terminalProvider().readScreen(name, id, { scope: "pane", source: "visible", lines: 120, stripAnsi: true, timeoutMs: 1000 }));
46
+ const keys = env.keys ?? ((name, id, pressed) => terminalProvider().sendKeys(name, id, pressed));
47
+ for (let attempt = 0; attempt < 2; attempt++) {
48
+ const shown = await screen(server, pane).then(text => claudeTeachAutoModeDialog(text), () => false);
49
+ if (!shown)
50
+ return true;
51
+ await keys(server, pane, ["esc"]).catch(() => undefined);
52
+ await new Promise(resolve => setTimeout(resolve, 300));
53
+ }
54
+ return !await screen(server, pane).then(text => claudeTeachAutoModeDialog(text), () => false);
55
+ }
41
56
  /**
42
- * `session: reuse`: types the prompt into the session the target's last run
43
- * used, while its pane still runs that harness. A busy session is skipped
44
- * rather than given a second prompt. Undefined when the session is gone (the
45
- * pane closed, its agent exited, its conversation was replaced), so the caller
46
- * starts a new one, which the next firing continues.
57
+ * `session: reuse`: types the prompt into the newest session of this schedule
58
+ * whose pane still runs its harness (`previous`, newest first). A busy newest
59
+ * session is skipped rather than given a second prompt; a pane whose prompt
60
+ * cannot be delivered (a dialog that will not dismiss, a refused delivery)
61
+ * passes the firing to the next older one. Once a pane has taken the firing,
62
+ * the schedule's older finished panes are closed. Undefined when no session is
63
+ * left (the panes closed, their agents exited, their conversations were
64
+ * replaced), so the caller starts a new one, which the next firing continues.
47
65
  */
48
66
  export async function continueSession(context, previous, deliver, signal, env = {}) {
49
- const { server, workspaceId, tabId, paneId, sessionId } = previous, source = context.schedule.harness;
50
- if (!server || !workspaceId || !tabId || !paneId || !sessionId)
51
- return undefined;
67
+ const source = context.schedule.harness;
52
68
  const panes = env.panes ?? (async (name) => objects((await snapshot(name)).panes));
53
- const pane = findPane({ panes: await panes(server).catch(() => []) }, { workspace: workspaceId, tab: tabId, pane: paneId, source });
54
- if (!pane)
55
- return undefined;
56
- const launch = { mode: "herdr", server, workspaceId, tabId, paneId, sessionId, reused: true };
57
- const status = String(pane.agent_status ?? "");
58
- if (status !== "idle" && status !== "done")
59
- return { launch, skipped: busyReason(status) };
60
- const transcript = await (env.transcriptStamp ?? realTranscriptStamp)(source, sessionId).catch(() => undefined);
61
- let result;
62
- try {
63
- result = await deliver({ server, workspace: workspaceId, tab: tabId, pane: paneId, source, session: sessionId }, context.schedule.prompt, `schedule-${context.runId.replaceAll("-", "")}`);
64
- }
65
- catch (error) {
66
- // The pane or its conversation went away between the look and the send.
67
- if (error instanceof BridgeError && (error.status === 404 || error.status === 409))
68
- return undefined;
69
- throw error;
69
+ const looked = new Map(), live = [];
70
+ for (const record of previous) {
71
+ const { server, workspaceId, tabId, paneId } = record;
72
+ if (!server || !workspaceId || !tabId || !paneId)
73
+ continue;
74
+ if (!looked.has(server))
75
+ looked.set(server, await panes(server).catch(() => []));
76
+ const pane = findPane({ panes: looked.get(server) }, { workspace: workspaceId, tab: tabId, pane: paneId, source });
77
+ if (pane)
78
+ live.push({ record, pane });
70
79
  }
71
- if (result.state === "failed")
80
+ if (!live.length)
72
81
  return undefined;
73
- if (result.delivered !== true && result.queued !== true) {
74
- throw new Error(`The prompt to the session this schedule continues was not confirmed${typeof result.error === "string" ? `: ${result.error}` : "."}`);
82
+ const recordOf = (item, sessionId) => ({ mode: "herdr", server: item.record.server, workspaceId: item.record.workspaceId, tabId: item.record.tabId, paneId: item.record.paneId, ...(sessionId ? { sessionId } : {}), reused: true });
83
+ const newest = live[0];
84
+ if (!finishedPane(newest.pane))
85
+ return { launch: recordOf(newest, newest.record.sessionId), skipped: busyReason(String(newest.pane.agent_status ?? "")) };
86
+ for (const item of live) {
87
+ if (!finishedPane(item.pane))
88
+ continue;
89
+ const { server, workspaceId, tabId, paneId } = item.record;
90
+ const sessionId = item.record.sessionId ?? await (env.identity ?? ((name, pane) => paneIdentity(name, pane)))(server, item.pane).catch(() => undefined);
91
+ if (!sessionId)
92
+ continue;
93
+ if (source === "claude" && !await dismissAutoModeDialog(server, paneId, env))
94
+ continue;
95
+ const transcript = await (env.transcriptStamp ?? realTranscriptStamp)(source, sessionId).catch(() => undefined);
96
+ let result;
97
+ try {
98
+ result = await deliver({ server, workspace: workspaceId, tab: tabId, pane: paneId, source, session: sessionId }, context.schedule.prompt, `schedule-${context.runId.replaceAll("-", "")}`);
99
+ }
100
+ catch (error) {
101
+ // The pane or its conversation went away between the look and the send.
102
+ if (error instanceof BridgeError && (error.status === 404 || error.status === 409))
103
+ continue;
104
+ throw error;
105
+ }
106
+ if (result.state === "failed")
107
+ continue;
108
+ if (result.delivered !== true && result.queued !== true) {
109
+ throw new Error(`The prompt to the session this schedule continues was not confirmed${typeof result.error === "string" ? `: ${result.error}` : "."}`);
110
+ }
111
+ // A Claude /clear in the same terminal moves the delivery to the new conversation.
112
+ const session = typeof object(result.target).session === "string" ? String(object(result.target).session) : sessionId;
113
+ const close = env.close ?? closeFinishedPane;
114
+ for (const other of live)
115
+ if (other !== item && finishedPane(other.pane))
116
+ await close(String(other.record.server), other.pane).catch(() => undefined);
117
+ return { launch: recordOf(item, session),
118
+ completion: (env.watch ?? watchHerdrRun)(server, { workspaceId, tabId, paneId }, signal, { source, startedAt: Date.now(), sessionId: session, continued: { transcript } }) };
75
119
  }
76
- // A Claude /clear in the same terminal moves the delivery to the new conversation.
77
- const session = typeof object(result.target).session === "string" ? String(object(result.target).session) : sessionId;
78
- return { launch: { ...launch, sessionId: session },
79
- completion: (env.watch ?? watchHerdrRun)(server, { workspaceId, tabId, paneId }, signal, { source, startedAt: Date.now(), sessionId: session, continued: { transcript } }) };
120
+ return undefined;
121
+ }
122
+ async function closeFinishedPane(server, pane) {
123
+ const { markPaneClosed } = await import("./worker-close.js");
124
+ await markPaneClosed(server, pane).catch(() => undefined);
125
+ await terminalProvider().closePane(server, String(pane.pane_id));
80
126
  }
81
127
  /**
82
128
  * The outcome of a run a previous Hook process launched and never saw finish
@@ -0,0 +1,13 @@
1
+ import { type Schedule } from "./schedule-format.js";
2
+ /**
3
+ * Why a schedule can never fire, so a list or the app says it instead of the
4
+ * schedule sitting silent: a computer the store does not know (no Hook answers
5
+ * to the name), or, on the computer that owns it, a target project with no
6
+ * source directory or one that is gone. `locate` finds a checkout the Hook
7
+ * discovered; only the owning computer can know its own paths.
8
+ */
9
+ export declare function scheduleProblems(schedule: Schedule, project: string, options: {
10
+ store: string;
11
+ owned: boolean;
12
+ locate?: (project: string) => Promise<string | undefined>;
13
+ }): Promise<string[]>;
@@ -0,0 +1,39 @@
1
+ import { stat } from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { getProjectSourcePath } from "../project-config.js";
4
+ import { listMachines } from "../profile-store.js";
5
+ import { getProjectDirs } from "../shared.js";
6
+ import { canonicalComputer } from "./schedule-format.js";
7
+ /**
8
+ * Why a schedule can never fire, so a list or the app says it instead of the
9
+ * schedule sitting silent: a computer the store does not know (no Hook answers
10
+ * to the name), or, on the computer that owns it, a target project with no
11
+ * source directory or one that is gone. `locate` finds a checkout the Hook
12
+ * discovered; only the owning computer can know its own paths.
13
+ */
14
+ export async function scheduleProblems(schedule, project, options) {
15
+ const problems = [];
16
+ const machines = listMachines(options.store);
17
+ if (!options.owned && machines.ok && !Object.keys(machines.data).some(name => canonicalComputer(name) === canonicalComputer(schedule.computer))) {
18
+ problems.push(`Computer "${schedule.computer}" is not a machine in this store, so no Hook will run this schedule.`);
19
+ }
20
+ if (!options.owned)
21
+ return problems;
22
+ for (const name of schedule.projects ?? [project]) {
23
+ const directory = getProjectDirs(options.store).find(candidate => path.basename(candidate).toLowerCase() === name.toLowerCase());
24
+ if (!directory) {
25
+ problems.push(`Project "${name}" is not in this store.`);
26
+ continue;
27
+ }
28
+ const target = path.basename(directory);
29
+ const source = getProjectSourcePath(options.store, target) ?? await options.locate?.(target);
30
+ if (!source) {
31
+ if (schedule.projects)
32
+ problems.push(`No source directory for project "${target}" on this computer.`);
33
+ continue;
34
+ }
35
+ if (!await stat(source).then(info => info.isDirectory()).catch(() => false))
36
+ problems.push(`Source directory for project "${target}" is unavailable: ${source}`);
37
+ }
38
+ return problems;
39
+ }
@@ -13,6 +13,7 @@ export declare class Scheduler {
13
13
  private readonly locateProject;
14
14
  private readonly push?;
15
15
  private readonly log;
16
+ private readonly revisionWaitMs;
16
17
  private serial;
17
18
  private ticking;
18
19
  private readonly dispatching;
@@ -32,6 +33,8 @@ export declare class Scheduler {
32
33
  locateProject?: (project: string) => Promise<string | undefined>;
33
34
  push?: SchedulePushSender;
34
35
  log?: (message: string) => void;
36
+ /** How long Run now waits for the store to catch up with the revision the app saw (default 30 s). */
37
+ revisionWaitMs?: number;
35
38
  });
36
39
  private projectDirectories;
37
40
  private projectDirectory;
@@ -48,6 +51,10 @@ export declare class Scheduler {
48
51
  limit?: number;
49
52
  }): Promise<ScheduleRun[]>;
50
53
  launchNow(projectName: string, id: string, onlyIfDue?: boolean, expectedUpdatedAt?: string): Promise<ScheduleRun[]>;
54
+ /** An edit made on another computer reaches this one with the store's sync. A Run now right after it waits for the
55
+ * schedule to arrive (or catch up) rather than failing; a copy newer than the app's, or none after the wait, is
56
+ * left to `prepareAndLaunch`'s revision check. */
57
+ private awaitRevision;
51
58
  private prepareAndLaunch;
52
59
  private updateRun;
53
60
  private finishRun;
@@ -3,9 +3,10 @@ import { stat } from "node:fs/promises";
3
3
  import { localNames, stableComputerName } from "./computer-names.js";
4
4
  import path from "node:path";
5
5
  import { BridgeError } from "./protocol.js";
6
+ import { scheduleProblems } from "./schedule-problems.js";
6
7
  import { getProjectSourcePath } from "../project-config.js";
7
8
  import { getProjectDirs } from "../shared.js";
8
- import { computerMatches, latestScheduleBatch, nextRun, readScheduleDocument, readScheduleRuns, reusableLaunch, runningStatuses, scheduleNotifications, scheduleSessionRoute, writeScheduleDocument, writeScheduleRuns, } from "./schedule-format.js";
9
+ import { computerMatches, latestScheduleBatch, nextRun, readScheduleDocument, readScheduleRuns, reusableLaunches, runningStatuses, scheduleNotifications, scheduleSessionRoute, writeScheduleDocument, writeScheduleRuns, } from "./schedule-format.js";
9
10
  export * from "./schedule-format.js";
10
11
  export * from "./schedule-launch.js";
11
12
  export * from "./schedule-watch.js";
@@ -20,6 +21,7 @@ export class Scheduler {
20
21
  locateProject;
21
22
  push;
22
23
  log;
24
+ revisionWaitMs;
23
25
  serial = Promise.resolve();
24
26
  ticking = false;
25
27
  dispatching = new Set();
@@ -29,6 +31,7 @@ export class Scheduler {
29
31
  /** When the scheduler last looked for due work; a health read shows it. */
30
32
  lastTickAt;
31
33
  constructor(options) {
34
+ this.revisionWaitMs = options.revisionWaitMs ?? 30_000;
32
35
  this.now = options.now;
33
36
  this.store = options.store;
34
37
  this.launch = options.launch;
@@ -84,7 +87,8 @@ export class Scheduler {
84
87
  const running = matching.some(run => runningStatuses.has(run.status));
85
88
  const due = this.owns(schedule, names) ? nextRun(schedule, last) : null;
86
89
  const owned = this.owns(schedule, names);
87
- result.push({ ...schedule, project, lastRuns, owned, nextRun: due?.toISOString() ?? null,
90
+ const problems = await scheduleProblems(schedule, project, { store: this.store, owned, locate: this.locateProject });
91
+ result.push({ ...schedule, project, lastRuns, owned, ...(problems.length ? { problems } : {}), nextRun: due?.toISOString() ?? null,
88
92
  lastRun: last ? { startedAt: last.startedAt, ...(last.finishedAt ? { finishedAt: last.finishedAt } : {}), status: last.status,
89
93
  ...(last.batchId ? { batchId: last.batchId, scheduleProject: last.scheduleProject } : {}),
90
94
  ...(last.reason ? { reason: last.reason } : {}),
@@ -105,12 +109,28 @@ export class Scheduler {
105
109
  throw new BridgeError(409, "This schedule is already launching.");
106
110
  this.dispatching.add(key);
107
111
  try {
112
+ if (expectedUpdatedAt !== undefined)
113
+ await this.awaitRevision(projectName, id, expectedUpdatedAt);
108
114
  return await this.prepareAndLaunch(projectName, id, onlyIfDue, expectedUpdatedAt);
109
115
  }
110
116
  finally {
111
117
  this.dispatching.delete(key);
112
118
  }
113
119
  }
120
+ /** An edit made on another computer reaches this one with the store's sync. A Run now right after it waits for the
121
+ * schedule to arrive (or catch up) rather than failing; a copy newer than the app's, or none after the wait, is
122
+ * left to `prepareAndLaunch`'s revision check. */
123
+ async awaitRevision(projectName, id, expectedUpdatedAt) {
124
+ const expected = Date.parse(expectedUpdatedAt), deadline = Date.now() + this.revisionWaitMs;
125
+ for (;;) {
126
+ const found = await readScheduleDocument(this.projectDirectory(projectName)).then(file => file.schedules.find(item => item.id === id), () => undefined);
127
+ if (found && Date.parse(found.updatedAt) >= expected)
128
+ return;
129
+ if (Date.now() >= deadline)
130
+ return;
131
+ await new Promise(resolve => setTimeout(resolve, Math.min(1_000, Math.max(10, this.revisionWaitMs / 10))));
132
+ }
133
+ }
114
134
  async prepareAndLaunch(projectName, id, onlyIfDue, expectedUpdatedAt) {
115
135
  const prepared = await this.exclusive(async () => {
116
136
  const projectDir = this.projectDirectory(projectName), project = path.basename(projectDir);
@@ -145,7 +165,7 @@ export class Scheduler {
145
165
  }
146
166
  const batchId = randomUUID(), startedAt = this.now().toISOString();
147
167
  const children = targets.map(target => ({ ...target,
148
- ...(schedule.session === "reuse" ? { reuse: reusableLaunch(matching.filter(run => run.project === target.project)) } : {}), run: {
168
+ ...(schedule.session === "reuse" ? { reuse: reusableLaunches(matching.filter(run => run.project === target.project)) } : {}), run: {
149
169
  id: randomUUID(), scheduleId: id, project: target.project, scheduleProject: project, batchId,
150
170
  startedAt, status: "launched", launch: { mode: "headless" },
151
171
  } }));