@phren/cli 0.3.40 → 0.3.42

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.
Files changed (39) hide show
  1. package/dist/bridge/health.d.ts +15 -0
  2. package/dist/bridge/health.js +32 -2
  3. package/dist/bridge/schedule-format.d.ts +13 -0
  4. package/dist/bridge/schedule-format.js +13 -0
  5. package/dist/bridge/schedule-launch.d.ts +19 -4
  6. package/dist/bridge/schedule-launch.js +52 -3
  7. package/dist/bridge/schedule-watch.d.ts +15 -0
  8. package/dist/bridge/schedule-watch.js +15 -1
  9. package/dist/bridge/schedules.js +8 -3
  10. package/dist/bridge/server-routes.js +4 -2
  11. package/dist/bridge/server.js +7 -2
  12. package/dist/bridge-hook.mjs +21923 -21257
  13. package/dist/cli/govern.js +8 -2
  14. package/dist/cli/schedules.js +6 -3
  15. package/dist/cli/session-git.js +1 -0
  16. package/dist/cli/session-start.js +18 -10
  17. package/dist/cli/session-stop.js +12 -1
  18. package/dist/cli-registry.js +1 -1
  19. package/dist/governance/policy.d.ts +3 -0
  20. package/dist/governance/policy.js +4 -0
  21. package/dist/link/doctor.js +57 -0
  22. package/dist/sync/auth-heal.d.ts +15 -0
  23. package/dist/sync/auth-heal.js +94 -0
  24. package/dist/sync/auth.js +19 -5
  25. package/dist/sync/conflict-resolve.d.ts +1 -1
  26. package/dist/sync/conflict-resolve.js +28 -8
  27. package/dist/sync/maintenance-writer.d.ts +7 -0
  28. package/dist/sync/maintenance-writer.js +37 -0
  29. package/dist/sync/pull.d.ts +2 -0
  30. package/dist/sync/pull.js +5 -3
  31. package/dist/sync/store-cleanup.d.ts +11 -0
  32. package/dist/sync/store-cleanup.js +117 -0
  33. package/dist/sync/store-merge.d.ts +4 -0
  34. package/dist/sync/store-merge.js +14 -1
  35. package/dist/sync/store-sync.d.ts +60 -0
  36. package/dist/sync/store-sync.js +182 -0
  37. package/dist/sync/task-merge.d.ts +5 -0
  38. package/dist/sync/task-merge.js +57 -15
  39. package/package.json +1 -1
@@ -18,8 +18,17 @@ export interface StoreSync {
18
18
  lastPushAt?: string;
19
19
  lastSuccessfulPushAt?: string;
20
20
  consecutiveFailures?: number;
21
+ lastSuccessfulPullAt?: string;
22
+ /** The newest successful pull or push. */
23
+ lastSyncedAt?: string;
24
+ /** Both the store and its remote have commits the other lacks. */
25
+ diverged?: boolean;
26
+ /** No successful sync for over STORE_STALE_MS while the store has a remote. */
27
+ stale?: boolean;
21
28
  /** The last sync failure in plain words, only while the store is failing. */
22
29
  error?: string;
30
+ /** One line a computer list shows as is when the store needs attention. */
31
+ warning?: string;
23
32
  degraded: boolean;
24
33
  }
25
34
  export interface LastScheduledRun {
@@ -121,6 +130,12 @@ export declare function toolVersion(tool: string, executable?: string, args?: st
121
130
  export declare function clearVersionCache(): void;
122
131
  /** Branch and ahead/behind against the upstream as last fetched; nothing is fetched here. */
123
132
  export declare function storeSync(store: string): Promise<StoreSync[]>;
133
+ /**
134
+ * The degraded stores' warnings for the overview: the last answer at once,
135
+ * refreshed in the background once a minute old, so the overview never
136
+ * waits on Git.
137
+ */
138
+ export declare function cachedStoreWarnings(store: string, now?: number): string[];
124
139
  /** The newest run in schedule-runs.jsonl, with its schedule's name when the project still has it. */
125
140
  export declare function lastScheduledRun(store: string, runsFile?: string): Promise<LastScheduledRun | null>;
126
141
  /** This computer's public SSH host key, the pin a peer's hooks.yaml holds for it. */
@@ -13,6 +13,7 @@ import { BridgeError, bridgeRoot, errorCode } from "./protocol.js";
13
13
  import { canonicalComputer, latestScheduleBatch, readScheduleDocument, readScheduleRuns, scheduleRunsFile } from "./schedules.js";
14
14
  import { countGit } from "./metrics.js";
15
15
  import { tmuxHealth } from "./terminal-tmux.js";
16
+ import { lastSyncedAt, STORE_STALE_MS, storeWarning } from "../sync/store-sync.js";
16
17
  const exec = promisify(execFile);
17
18
  /** The running servers the Hook lists (Herdr's, else tmux's) and tmux's own state. */
18
19
  export async function terminalHealth() {
@@ -126,14 +127,43 @@ export async function storeSync(store) {
126
127
  result.lastSuccessfulPushAt = sync.lastSuccessfulPushAt;
127
128
  if (sync?.consecutiveFailures)
128
129
  result.consecutiveFailures = sync.consecutiveFailures;
130
+ if (sync?.lastSuccessfulPullAt)
131
+ result.lastSuccessfulPullAt = sync.lastSuccessfulPullAt;
132
+ const synced = lastSyncedAt(sync);
133
+ if (synced)
134
+ result.lastSyncedAt = synced;
129
135
  const failing = sync?.lastPushStatus !== undefined && FAILED_PUSH_STATUSES.has(sync.lastPushStatus);
130
136
  const pullFailed = sync?.lastPullStatus === "error";
131
137
  if (failing || pullFailed)
132
- result.error = plainError(sync?.lastPushDetail || sync?.lastPullDetail) ?? `Last sync: ${sync?.lastPushStatus ?? "pull failed"}`;
133
- result.degraded = assessSyncOutage(sync).degraded;
138
+ result.error = plainError(sync?.lastError || sync?.lastPushDetail || sync?.lastPullDetail) ?? `Last sync: ${sync?.lastPushStatus ?? "pull failed"}`;
139
+ if (upstream) {
140
+ result.diverged = (result.ahead ?? 0) > 0 && (result.behind ?? 0) > 0;
141
+ result.stale = !synced || Date.now() - Date.parse(synced) > STORE_STALE_MS;
142
+ }
143
+ result.degraded = assessSyncOutage(sync).degraded || result.diverged === true || result.stale === true;
144
+ const warning = storeWarning(result);
145
+ if (warning && result.degraded)
146
+ result.warning = warning;
134
147
  return result;
135
148
  }));
136
149
  }
150
+ const warningCache = new Map();
151
+ /**
152
+ * The degraded stores' warnings for the overview: the last answer at once,
153
+ * refreshed in the background once a minute old, so the overview never
154
+ * waits on Git.
155
+ */
156
+ export function cachedStoreWarnings(store, now = Date.now()) {
157
+ const entry = warningCache.get(store) ?? { at: 0, value: [] };
158
+ warningCache.set(store, entry);
159
+ if (now - entry.at > 60_000 && !entry.refreshing) {
160
+ entry.refreshing = storeSync(store)
161
+ .then(stores => { entry.value = stores.flatMap(item => item.warning ? [item.warning] : []); entry.at = Date.now(); })
162
+ .catch(() => { entry.at = Date.now(); })
163
+ .finally(() => { entry.refreshing = undefined; });
164
+ }
165
+ return entry.value;
166
+ }
137
167
  /** The newest run in schedule-runs.jsonl, with its schedule's name when the project still has it. */
138
168
  export async function lastScheduledRun(store, runsFile = scheduleRunsFile()) {
139
169
  const runs = await readScheduleRuns(runsFile).catch(() => []);
@@ -5,10 +5,13 @@ export declare const SCHEDULE_EVERY: readonly ["interval", "daily", "weekly", "o
5
5
  export declare const SCHEDULE_HARNESSES: readonly ["claude", "codex", "opencode", "copilot"];
6
6
  export declare const SCHEDULE_NOTIFY: readonly ["start", "finish", "failure"];
7
7
  export declare const WEEKDAYS: readonly ["sun", "mon", "tue", "wed", "thu", "fri", "sat"];
8
+ /** `new` starts a session per firing; `reuse` types the prompt into the schedule's last session while it is still open. */
9
+ export declare const SCHEDULE_SESSIONS: readonly ["new", "reuse"];
8
10
  export type ScheduleEvery = typeof SCHEDULE_EVERY[number];
9
11
  export type ScheduleHarness = typeof SCHEDULE_HARNESSES[number];
10
12
  export type ScheduleNotify = typeof SCHEDULE_NOTIFY[number];
11
13
  export type Weekday = typeof WEEKDAYS[number];
14
+ export type ScheduleSession = typeof SCHEDULE_SESSIONS[number];
12
15
  export declare const SCHEDULE_RUN_STATUSES: readonly ["launched", "running", "blocked", "finished", "needs-you", "failed", "skipped"];
13
16
  export type ScheduleRunStatus = typeof SCHEDULE_RUN_STATUSES[number];
14
17
  /** How a run ended: done, done but waiting on the owner's answer, or not done. */
@@ -28,6 +31,8 @@ export interface Schedule {
28
31
  notify?: ScheduleNotify[];
29
32
  /** Explicit targets; absent means the directory owning this schedule. */
30
33
  projects?: string[];
34
+ /** Absent means `new`. */
35
+ session?: ScheduleSession;
31
36
  every: ScheduleEvery;
32
37
  at?: string;
33
38
  days?: Weekday[];
@@ -47,6 +52,8 @@ export interface ScheduleLaunchRecord {
47
52
  sessionId?: string;
48
53
  server?: string;
49
54
  jobDir?: string;
55
+ /** The prompt went to the schedule's earlier session instead of a new one. */
56
+ reused?: boolean;
50
57
  }
51
58
  export interface ScheduleRun {
52
59
  id: string;
@@ -67,6 +74,8 @@ export interface ScheduleRun {
67
74
  export interface ScheduleLaunchResult {
68
75
  launch: ScheduleLaunchRecord;
69
76
  completion?: Promise<ScheduleRunOutcome>;
77
+ /** Nothing was started: the reused session was busy, for this reason. */
78
+ skipped?: string;
70
79
  }
71
80
  export interface ScheduleLaunchContext {
72
81
  schedule: Schedule;
@@ -74,6 +83,8 @@ export interface ScheduleLaunchContext {
74
83
  projectDir: string;
75
84
  cwd: string;
76
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;
77
88
  blockedStartup?: (promptText: string) => void | Promise<void>;
78
89
  }
79
90
  export type ScheduleLauncher = ((context: ScheduleLaunchContext) => Promise<ScheduleLaunchResult>) & {
@@ -112,6 +123,8 @@ export declare function latestScheduleBatch(runs: ScheduleRun[]): {
112
123
  lastRun: ScheduleRun | undefined;
113
124
  lastRuns: ScheduleRun[];
114
125
  };
126
+ /** The newest Herdr session among a target's runs, which `session: reuse` continues. */
127
+ export declare function reusableLaunch(runs: readonly ScheduleRun[]): ScheduleLaunchRecord | undefined;
115
128
  export declare function readScheduleRuns(file: string): Promise<ScheduleRun[]>;
116
129
  export declare function writeScheduleRuns(file: string, runs: ScheduleRun[]): Promise<void>;
117
130
  export declare function newScheduleId(existing: Iterable<string>): string;
@@ -12,6 +12,8 @@ export const SCHEDULE_EVERY = ["interval", "daily", "weekly", "once", "cron"];
12
12
  export const SCHEDULE_HARNESSES = ["claude", "codex", "opencode", "copilot"];
13
13
  export const SCHEDULE_NOTIFY = ["start", "finish", "failure"];
14
14
  export const WEEKDAYS = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"];
15
+ /** `new` starts a session per firing; `reuse` types the prompt into the schedule's last session while it is still open. */
16
+ export const SCHEDULE_SESSIONS = ["new", "reuse"];
15
17
  export const SCHEDULE_RUN_STATUSES = ["launched", "running", "blocked", "finished", "needs-you", "failed", "skipped"];
16
18
  const scheduleId = z.string().regex(/^[a-f0-9]{8}$/);
17
19
  const plain = (max) => z.string().min(1).max(max).refine(value => !/[\x00-\x08\x0b-\x1f\x7f]/.test(value));
@@ -65,6 +67,8 @@ export function parseSchedule(value) {
65
67
  if (raw.projects !== undefined)
66
68
  schedule.projects = z.array(z.string().refine(isValidProjectName, "Invalid project slug."))
67
69
  .min(1).max(64).refine(projects => new Set(projects).size === projects.length, "Projects must be unique.").parse(raw.projects);
70
+ if (raw.session !== undefined)
71
+ schedule.session = z.enum(SCHEDULE_SESSIONS).parse(raw.session);
68
72
  if (raw.model !== undefined)
69
73
  schedule.model = singleLine(200).parse(raw.model);
70
74
  if (raw.account !== undefined)
@@ -251,6 +255,15 @@ export function latestScheduleBatch(runs) {
251
255
  : lastRuns.map(run => run.finishedAt).filter((time) => Boolean(time)).sort().at(-1);
252
256
  return { lastRun: { ...representative, finishedAt }, lastRuns };
253
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--) {
261
+ const launch = runs[index].launch;
262
+ if (launch.mode === "herdr" && launch.server && launch.workspaceId && launch.tabId && launch.paneId && launch.sessionId)
263
+ return launch;
264
+ }
265
+ return undefined;
266
+ }
254
267
  export async function readScheduleRuns(file) {
255
268
  let text;
256
269
  try {
@@ -1,8 +1,23 @@
1
- import { type Json } from "./protocol.js";
2
- import type { Schedule, ScheduleLauncher, ScheduleRun, ScheduleRunOutcome } from "./schedule-format.js";
3
- import { watchHerdrRun } from "./schedule-watch.js";
1
+ import { type Json, type Target } from "./protocol.js";
2
+ import type { Schedule, ScheduleLauncher, ScheduleLaunchContext, ScheduleLaunchRecord, ScheduleLaunchResult, ScheduleRun, ScheduleRunOutcome } from "./schedule-format.js";
3
+ import { realTranscriptStamp, watchHerdrRun } from "./schedule-watch.js";
4
4
  type HerdrLauncher = (server: string, data: Json) => Promise<Json>;
5
- export declare function createScheduleLauncher(launchHerdr: HerdrLauncher, store?: string): ScheduleLauncher;
5
+ /** Types a prompt into a live session: the Hook's hand-off queue. */
6
+ export type ScheduleDeliver = (target: Target, text: string, deliveryId: string) => Promise<Json>;
7
+ export declare function createScheduleLauncher(launchHerdr: HerdrLauncher, store?: string, deliver?: ScheduleDeliver): ScheduleLauncher;
8
+ export interface ContinueEnv {
9
+ panes?: (server: string) => Promise<Json[]>;
10
+ transcriptStamp?: typeof realTranscriptStamp;
11
+ watch?: typeof watchHerdrRun;
12
+ }
13
+ /**
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.
19
+ */
20
+ export declare function continueSession(context: ScheduleLaunchContext, previous: ScheduleLaunchRecord, deliver: ScheduleDeliver, signal: AbortSignal, env?: ContinueEnv): Promise<ScheduleLaunchResult | undefined>;
6
21
  /**
7
22
  * The outcome of a run a previous Hook process launched and never saw finish
8
23
  * (a restart or crash mid-run). A Herdr pane is followed again to its real
@@ -10,15 +10,20 @@ import { fanoutRoot } from "./fanouts.js";
10
10
  import { pretrustFolder } from "./folder-trust.js";
11
11
  import { findPane, paneIdentity, servers, snapshot } from "./herdr.js";
12
12
  import { agentNotReady, terminalProvider } from "./terminal.js";
13
- import { atomicInPrivateDir, BridgeError } from "./protocol.js";
13
+ import { atomicInPrivateDir, BridgeError, object, objects } from "./protocol.js";
14
14
  import { defaultPhrenPath } from "../shared.js";
15
- import { watchHerdrRun } from "./schedule-watch.js";
15
+ import { realTranscriptStamp, watchHerdrRun } from "./schedule-watch.js";
16
16
  /** Starting a scheduled run: in a Herdr pane when a server is live, otherwise
17
17
  * as a headless job under the fan-out root. */
18
18
  const CLAUDE_SCHEDULE_SETTINGS = JSON.stringify({ enableAllProjectMcpServers: true });
19
- export function createScheduleLauncher(launchHerdr, store = defaultPhrenPath()) {
19
+ export function createScheduleLauncher(launchHerdr, store = defaultPhrenPath(), deliver) {
20
20
  const abort = new AbortController(), children = new Set();
21
21
  const launcher = async (context) => {
22
+ if (context.reuse && deliver) {
23
+ const continued = await continueSession(context, context.reuse, deliver, abort.signal);
24
+ if (continued)
25
+ return continued;
26
+ }
22
27
  const live = await servers();
23
28
  if (live.length)
24
29
  return launchInHerdr(String(live[0].session), context, launchHerdr, abort.signal);
@@ -29,6 +34,50 @@ export function createScheduleLauncher(launchHerdr, store = defaultPhrenPath())
29
34
  launcher.resume = (run, schedule) => resumeScheduleRun(run, schedule, abort.signal);
30
35
  return launcher;
31
36
  }
37
+ function busyReason(status) {
38
+ const state = status === "blocked" || status === "waiting" ? "is waiting for you" : status === "working" || status === "starting" ? "is still working" : `is ${status || "busy"}`;
39
+ return `The session this schedule continues ${state}, so this firing was skipped.`;
40
+ }
41
+ /**
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.
47
+ */
48
+ 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;
52
+ 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;
70
+ }
71
+ if (result.state === "failed")
72
+ 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}` : "."}`);
75
+ }
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 } }) };
80
+ }
32
81
  /**
33
82
  * The outcome of a run a previous Hook process launched and never saw finish
34
83
  * (a restart or crash mid-run). A Herdr pane is followed again to its real
@@ -17,7 +17,18 @@ interface StartupWatch {
17
17
  startedAt: number;
18
18
  sessionId?: string;
19
19
  onBlocked?: (promptText: string) => void | Promise<void>;
20
+ /** The prompt went to a session that was already idle, whose transcript
21
+ * looked like this beforehand. Idle ends the run only once the pane was
22
+ * seen busy or the transcript moved; otherwise it is the turn not started. */
23
+ continued?: {
24
+ transcript?: {
25
+ size: number;
26
+ mtimeMs: number;
27
+ };
28
+ };
20
29
  }
30
+ /** How long a continued session may sit idle without taking up the prompt. */
31
+ export declare const CONTINUED_TURN_START_MS = 120000;
21
32
  export interface StartupWatchEnv {
22
33
  now?: () => number;
23
34
  pause?: (ms: number) => Promise<void>;
@@ -75,6 +86,10 @@ export declare function readFinalTurn(source: ScheduleHarness, sessionId: string
75
86
  /** When a finished reply ends by asking the owner something (a question, or
76
87
  * numbered options introduced as a choice), the question's first line. */
77
88
  export declare function ownerQuestion(text: string): string | undefined;
89
+ export declare function realTranscriptStamp(source: ScheduleHarness, sessionId: string | undefined): Promise<{
90
+ size: number;
91
+ mtimeMs: number;
92
+ } | undefined>;
78
93
  export declare function watchHerdrRun(server: string, target: {
79
94
  workspaceId: string;
80
95
  tabId: string;
@@ -35,6 +35,8 @@ export function watchFailureReason(error) {
35
35
  const first = (error instanceof Error ? error.message : String(error)).split("\n")[0].replace(/[\x00-\x1f\x7f]/g, " ").trim().slice(0, 200);
36
36
  return `Watching the scheduled prompt failed: ${first || "unknown error"}`;
37
37
  }
38
+ /** How long a continued session may sit idle without taking up the prompt. */
39
+ export const CONTINUED_TURN_START_MS = 120_000;
38
40
  /** The public text of one assistant row, without reasoning or tool output. */
39
41
  export function publicAssistant(raw, source) {
40
42
  if (source === "codex") {
@@ -326,7 +328,7 @@ export function ownerQuestion(text) {
326
328
  first--;
327
329
  return plainLine(lines[first]) || last;
328
330
  }
329
- async function realTranscriptStamp(source, sessionId) {
331
+ export async function realTranscriptStamp(source, sessionId) {
330
332
  if (!sessionId)
331
333
  return undefined;
332
334
  const file = await transcriptPath(source, sessionId).catch(() => undefined);
@@ -346,6 +348,7 @@ export async function watchHerdrRun(server, target, signal, startup, env = {}) {
346
348
  let stamp;
347
349
  let recordedBlock = false;
348
350
  let paneReads = 0;
351
+ let turnStarted = !startup.continued;
349
352
  while (!signal.aborted) {
350
353
  await pause(1000);
351
354
  if (signal.aborted)
@@ -360,6 +363,16 @@ export async function watchHerdrRun(server, target, signal, startup, env = {}) {
360
363
  if (status === "idle" || status === "done") {
361
364
  if (!sessionId)
362
365
  sessionId = await resolveSession(server, pane);
366
+ if (!turnStarted) {
367
+ const moved = await transcriptStamp(startup.source, sessionId);
368
+ const before = startup.continued?.transcript;
369
+ turnStarted = !!moved && (!before || moved.size !== before.size || moved.mtimeMs !== before.mtimeMs);
370
+ if (!turnStarted) {
371
+ if (now() - startup.startedAt > CONTINUED_TURN_START_MS)
372
+ return { status: "failed", reason: "The session this schedule continues never took up the prompt." };
373
+ continue;
374
+ }
375
+ }
363
376
  const turn = await finalTurn(startup.source, sessionId).catch(() => undefined);
364
377
  if (turn?.completed && turn.error)
365
378
  return { status: "failed", reason: turn.error };
@@ -369,6 +382,7 @@ export async function watchHerdrRun(server, target, signal, startup, env = {}) {
369
382
  if (!["working", "starting", "blocked", "waiting", "unknown"].includes(status)) {
370
383
  return { status: "failed", reason: "The scheduled agent stopped before the prompt finished." };
371
384
  }
385
+ turnStarted = true;
372
386
  const elapsedMs = now() - startup.startedAt;
373
387
  const withinWindow = elapsedMs <= STARTUP_BLOCK_WINDOW_MS + STARTUP_BLOCK_WINDOW_OPEN_MS;
374
388
  if (!transcriptActive && startup.onBlocked && !recordedBlock && withinWindow) {
@@ -5,7 +5,7 @@ import path from "node:path";
5
5
  import { BridgeError } from "./protocol.js";
6
6
  import { getProjectSourcePath } from "../project-config.js";
7
7
  import { getProjectDirs } from "../shared.js";
8
- import { computerMatches, latestScheduleBatch, nextRun, readScheduleDocument, readScheduleRuns, runningStatuses, scheduleNotifications, scheduleSessionRoute, writeScheduleDocument, writeScheduleRuns, } from "./schedule-format.js";
8
+ import { computerMatches, latestScheduleBatch, nextRun, readScheduleDocument, readScheduleRuns, reusableLaunch, runningStatuses, scheduleNotifications, scheduleSessionRoute, writeScheduleDocument, writeScheduleRuns, } from "./schedule-format.js";
9
9
  export * from "./schedule-format.js";
10
10
  export * from "./schedule-launch.js";
11
11
  export * from "./schedule-watch.js";
@@ -144,7 +144,8 @@ export class Scheduler {
144
144
  targets.push({ project: target, projectDir: targetDir, cwd });
145
145
  }
146
146
  const batchId = randomUUID(), startedAt = this.now().toISOString();
147
- const children = targets.map(target => ({ ...target, run: {
147
+ const children = targets.map(target => ({ ...target,
148
+ ...(schedule.session === "reuse" ? { reuse: reusableLaunch(matching.filter(run => run.project === target.project)) } : {}), run: {
148
149
  id: randomUUID(), scheduleId: id, project: target.project, scheduleProject: project, batchId,
149
150
  startedAt, status: "launched", launch: { mode: "headless" },
150
151
  } }));
@@ -171,8 +172,12 @@ export class Scheduler {
171
172
  return Promise.all(prepared.children.map(async (child) => {
172
173
  try {
173
174
  const launched = await this.launch({ schedule: prepared.schedule, project: child.project, projectDir: child.projectDir,
174
- cwd: child.cwd, runId: child.run.id,
175
+ cwd: child.cwd, runId: child.run.id, ...(child.reuse ? { reuse: child.reuse } : {}),
175
176
  blockedStartup: promptText => this.recordBlockedStartup(child.run.id, prepared.schedule, promptText) });
177
+ // A busy reused session keeps its turn; this firing is recorded and nothing is sent.
178
+ if (launched.skipped) {
179
+ return await this.updateRun(child.run.id, { status: "skipped", finishedAt: this.now().toISOString(), reason: launched.skipped, launch: launched.launch });
180
+ }
176
181
  const running = await this.updateRun(child.run.id, { status: "running", launch: launched.launch });
177
182
  const notified = this.notifyRun(running, prepared.schedule, "scheduleStarted");
178
183
  if (launched.completion)
@@ -40,7 +40,7 @@ import { listUploads, removeUpload, saveUpload, uploadImage } from "./uploads.js
40
40
  import { currentModel, currentStep } from "./steps.js";
41
41
  import { capacityRoom, usageForCaller } from "./usage.js";
42
42
  import { readFinalTurn } from "./schedule-watch.js";
43
- import { healthDetails, listsCaller } from "./health.js";
43
+ import { cachedStoreWarnings, healthDetails, listsCaller } from "./health.js";
44
44
  import { defaultPhrenPath } from "../shared.js";
45
45
  import { loadCodePackage, loadedFrom } from "../modules/code-package.js";
46
46
  import { gitRepository, paneRoute, uploadBody } from "./server-pane-routes.js";
@@ -266,7 +266,9 @@ export function workspacesReader(ctx) {
266
266
  expired = true;
267
267
  clearTimeout(timer);
268
268
  const mux = terminalMux(server);
269
- return { ...workspaces, kind: mux.kind, mux, phren: info };
269
+ // A diverged or long-unsynced store, for the computer list (health.ts storeWarning).
270
+ const storeWarnings = cachedStoreWarnings(defaultPhrenPath());
271
+ return { ...workspaces, kind: mux.kind, mux, phren: info, ...(storeWarnings.length ? { storeWarnings } : {}) };
270
272
  };
271
273
  }
272
274
  /** One read-only GET to every linked peer, each answer or its error by computer name. */
@@ -63,6 +63,7 @@ import { targetTranscriptPath } from "./transcripts.js";
63
63
  import { codexAppServerEnabled, codexServers } from "./codex-servers.js";
64
64
  import { CodexAuthKeeper, codexAuthRefreshEnabled } from "./codex-auth-refresh.js";
65
65
  import { localNames } from "./computer-names.js";
66
+ import { startStoreSyncLoop } from "../sync/store-sync.js";
66
67
  export { capabilities, capabilitiesForModules, requireRoute } from "./server-routes.js";
67
68
  export { streamCloseReason } from "./server-stream.js";
68
69
  export { herdrAgentName, launchSession } from "./server-launch.js";
@@ -171,7 +172,9 @@ export async function serve(version, options = {}) {
171
172
  const scheduler = modules.has("schedules") ? new Scheduler({ now: () => new Date(), store: scheduleStore, runsFile: scheduleRunsFile(),
172
173
  aliases: [computerID],
173
174
  // A schedule starts in its project's folder, which the Hook resolved itself.
174
- launch: createScheduleLauncher((server, data) => launchSession(server, data, { trustFolder: true }), scheduleStore),
175
+ launch: createScheduleLauncher((server, data) => launchSession(server, data, { trustFolder: true }), scheduleStore,
176
+ // `session: reuse` continues a session through the same queue a hand-off takes.
177
+ (target, text, deliveryId) => handOffs ? handOffs.enqueue({ target, text, deliveryId }) : sendPrompt(target, text, deliveryId, async () => { })),
175
178
  push: { notify: value => agentHooks.push.notifySchedule(value) },
176
179
  locateProject: async (project) => (await locateProject(project, await journal.recent()))[0]?.directory }) : undefined;
177
180
  const fanoutMessages = new FanoutMessages({ ...process.env, PHREN_PATH: scheduleStore }, {
@@ -299,6 +302,8 @@ export async function serve(version, options = {}) {
299
302
  const codexAuthTimer = codexAuth ? setInterval(() => { void codexAuth.tick().catch(() => { }); }, 60 * 60_000) : undefined;
300
303
  if (codexAuth)
301
304
  setTimeout(() => { void codexAuth.tick().catch(() => { }); }, 60_000).unref();
305
+ // Every store converges with its remote even when no agent session runs here (store-sync.ts).
306
+ const storeSync = startStoreSyncLoop(scheduleStore);
302
307
  const canaryTimer = setInterval(() => { countTick("canary"); void dailyCanaryDue().then(due => due ? canary("daily") : undefined).catch(() => { }); }, 10 * 60_000);
303
308
  let recording = false;
304
309
  const activityTimer = setInterval(() => {
@@ -346,7 +351,7 @@ export async function serve(version, options = {}) {
346
351
  })().finally(() => { recording = false; }).catch(() => { });
347
352
  }, 5000);
348
353
  await new Promise(resolve => {
349
- const stop = () => { fanoutMessages.close(); stopRetention(); clearInterval(scheduleTimer); clearInterval(canaryTimer); clearInterval(codexAuthTimer); clearInterval(activityTimer); scheduler?.close(); codeReindexer?.close(); codexServers.close(); agentHooks.close(); ws.clients.forEach(c => c.terminate()); ws.close(); http.close(() => resolve()); http.closeAllConnections(); };
354
+ const stop = () => { storeSync.stop(); fanoutMessages.close(); stopRetention(); clearInterval(scheduleTimer); clearInterval(canaryTimer); clearInterval(codexAuthTimer); clearInterval(activityTimer); scheduler?.close(); codeReindexer?.close(); codexServers.close(); agentHooks.close(); ws.clients.forEach(c => c.terminate()); ws.close(); http.close(() => resolve()); http.closeAllConnections(); };
350
355
  process.once("SIGTERM", stop);
351
356
  process.once("SIGINT", stop);
352
357
  });