@cydm/pie 4.15.0 → 4.15.2

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.
@@ -1,7 +1,7 @@
1
1
  import { createRequire as __createRequire } from "node:module"; const require = __createRequire(import.meta.url);
2
2
  import {
3
3
  registerCronPanelBridge
4
- } from "../../../chunks/chunk-CAPBTMLI.js";
4
+ } from "../../../chunks/chunk-F2F4QXPE.js";
5
5
  import {
6
6
  Type
7
7
  } from "../../../chunks/chunk-XXGYUYXI.js";
@@ -916,17 +916,22 @@ function completeInterrupted(job, error, now = Date.now()) {
916
916
  }
917
917
 
918
918
  // builtin/extensions/cron/runtime.ts
919
- import * as fs4 from "node:fs";
920
- import * as path4 from "node:path";
919
+ import * as fs5 from "node:fs";
920
+ import * as path5 from "node:path";
921
921
  import { randomUUID as randomUUID3 } from "node:crypto";
922
922
 
923
923
  // builtin/extensions/cron/managed-memory.ts
924
924
  import * as path2 from "node:path";
925
925
  import * as fs2 from "node:fs";
926
926
  import { homedir } from "node:os";
927
- function configPath() {
928
- const env = process.env.PIE_CODING_AGENT_DIR;
929
- return path2.resolve(env === "~" ? homedir() : env?.startsWith("~/") ? path2.join(homedir(), env.slice(2)) : env || path2.join(homedir(), ".pie"));
927
+ function configPath(env = process.env) {
928
+ const raw = env.PIE_CODING_AGENT_DIR;
929
+ return path2.resolve(raw === "~" ? homedir() : raw?.startsWith("~/") ? path2.join(homedir(), raw.slice(2)) : raw || path2.join(homedir(), ".pie"));
930
+ }
931
+ function isManagedSubWorker(env = process.env, rootDir) {
932
+ if (env.PIE_PROC_LAUNCH_TOKEN || env.PIE_PROC_REGISTRY_ROOT) return true;
933
+ const normalized = path2.resolve(rootDir ?? configPath(env)).replace(/\\/g, "/");
934
+ return /\/pie-proc\/agents\/[^/]+(?:\/|$)/.test(normalized);
930
935
  }
931
936
  function localTimeToCronUtc(time) {
932
937
  const m = /^(\d{1,2}):(\d{2})$/.exec(time);
@@ -971,1334 +976,1386 @@ function managedMemoryCommand() {
971
976
  ];
972
977
  }
973
978
 
974
- // builtin/extensions/cron/worker.ts
975
- import { spawn } from "node:child_process";
976
- import { randomUUID as randomUUID2 } from "node:crypto";
979
+ // builtin/extensions/cron/panel-bridge.ts
977
980
  import * as fs3 from "node:fs";
978
981
  import * as path3 from "node:path";
979
- import { StringDecoder } from "node:string_decoder";
980
- function runWorker(job, signal, cli = process.argv[1], configDir) {
981
- if (signal.aborted) return Promise.reject(new Error("worker interrupted before launch"));
982
- return new Promise((resolve3, reject) => {
983
- const child = spawn(process.execPath, [path3.resolve(cli), "--json-events", "--session-id", job.sessionId, "--resume-required"], {
984
- cwd: job.cwd,
985
- // R5-P2: a cron worker is an INDEPENDENT session — strip the manager
986
- // identity/model quartet so it never inherits the manager's model or
987
- // curated name (same boundary contract as pie-proc and the bash tool).
988
- env: (() => {
989
- const { PIE_DEFAULT_PROVIDER: _p, PIE_DEFAULT_MODEL: _m, PIE_MANAGER_BOOTSTRAP: _b, PIE_PROC_CURATED_NAME: _c, ...cleanEnv } = process.env;
990
- return { ...cleanEnv, ...configDir ? { PIE_CODING_AGENT_DIR: configDir } : {}, PIE_CRON_ROLE: "worker" };
991
- })(),
992
- stdio: ["pipe", "pipe", "pipe"],
993
- windowsHide: true
994
- });
995
- const decoder = new StringDecoder("utf8");
996
- const turnId = randomUUID2();
997
- let buffer = "", settled = false, sent = false, completed = false;
998
- let failure;
999
- let killTimer;
1000
- const stop = () => {
1001
- failure ??= "worker interrupted; outcome uncertain";
1002
- child.kill();
1003
- killTimer ??= setTimeout(() => child.kill("SIGKILL"), 5e3);
1004
- killTimer.unref();
1005
- };
1006
- const protocolError = (message) => {
1007
- failure = message;
1008
- stop();
1009
- };
1010
- signal.addEventListener("abort", stop, { once: true });
1011
- const timer = setTimeout(stop, 15 * 6e4);
1012
- timer.unref();
1013
- child.stdin.on("error", () => {
1014
- });
1015
- child.stderr.resume();
1016
- child.stdout.on("data", (chunk) => {
1017
- buffer += decoder.write(chunk);
1018
- if (buffer.length > 2e6) {
1019
- protocolError("oversized worker event; outcome uncertain");
1020
- return;
1021
- }
1022
- let index;
1023
- while ((index = buffer.indexOf("\n")) >= 0) {
1024
- const line = buffer.slice(0, index);
1025
- buffer = buffer.slice(index + 1);
1026
- try {
1027
- const event = JSON.parse(line);
1028
- if (!event || typeof event.type !== "string") throw new Error("invalid event");
1029
- if (event.type === "agent.ready") {
1030
- if (sent || event.sessionId !== job.sessionId) {
1031
- protocolError("worker readiness/session mismatch");
1032
- return;
1033
- }
1034
- sent = true;
1035
- child.stdin.write(JSON.stringify({ type: "turn.request", sessionId: job.sessionId, turnId, prompt: job.prompt }) + "\n");
1036
- }
1037
- if (["turn.completed", "turn.failed", "turn.cancelled", "turn.stalled", "turn.settled"].includes(event.type)) {
1038
- if (!sent || event.sessionId !== job.sessionId || event.turnId !== turnId || settled) {
1039
- protocolError("worker turn identity/order mismatch");
1040
- return;
1041
- }
1042
- if (event.type === "turn.completed") {
1043
- if (completed) {
1044
- protocolError("duplicate worker completion");
1045
- return;
1046
- }
1047
- completed = true;
1048
- } else if (event.type === "turn.settled") {
1049
- if (!completed) {
1050
- protocolError("worker settled without completion");
1051
- return;
1052
- }
1053
- settled = true;
1054
- child.stdin.end(JSON.stringify({ type: "shutdown" }) + "\n");
1055
- } else {
1056
- protocolError(`worker ${event.type}`);
1057
- return;
1058
- }
1059
- }
1060
- if (event.type === "error") {
1061
- protocolError("worker protocol error; inspect session before resuming");
1062
- return;
1063
- }
1064
- } catch {
1065
- protocolError("invalid worker output");
1066
- return;
1067
- }
1068
- }
1069
- });
1070
- child.on("error", (error) => {
1071
- failure = error.message;
1072
- });
1073
- child.on("close", (code) => {
1074
- clearTimeout(timer);
1075
- clearTimeout(killTimer);
1076
- signal.removeEventListener("abort", stop);
1077
- buffer += decoder.end();
1078
- if (buffer.trim()) failure ??= "truncated worker event; outcome uncertain";
1079
- if (failure || !settled || !completed || code !== 0) reject(new Error(failure ?? `worker exited ${code}; outcome uncertain`));
1080
- else resolve3();
1081
- });
1082
- if (signal.aborted) stop();
1083
- });
982
+ var SAFE_WORKER_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,47}$/;
983
+ var SAFE_JOB_ID = /^[A-Za-z0-9-]{8,64}$/;
984
+ function isContainedNonSymlink(rootDir, targetPath, kind) {
985
+ try {
986
+ if (!fs3.existsSync(rootDir) || !fs3.existsSync(targetPath)) return false;
987
+ const st = fs3.lstatSync(targetPath);
988
+ if (st.isSymbolicLink()) return false;
989
+ if (kind === "dir" ? !st.isDirectory() : !st.isFile()) return false;
990
+ const canonicalRoot = fs3.realpathSync(rootDir);
991
+ const canonicalTarget = fs3.realpathSync(targetPath);
992
+ const rel = path3.relative(canonicalRoot, canonicalTarget);
993
+ return Boolean(rel && !rel.startsWith("..") && !path3.isAbsolute(rel));
994
+ } catch {
995
+ return false;
996
+ }
1084
997
  }
1085
- function processJobEnv(configDir) {
1086
- const allow = [
1087
- "PATH",
1088
- "PATHEXT",
1089
- "SYSTEMROOT",
1090
- "SYSTEMDRIVE",
1091
- "COMSPEC",
1092
- "LANG",
1093
- "LC_ALL",
1094
- "TZ",
1095
- "TERM",
1096
- "TMPDIR",
1097
- "TEMP",
1098
- "TMP",
1099
- "HOME",
1100
- "USERPROFILE",
1101
- "XDG_CONFIG_HOME",
1102
- "XDG_CACHE_HOME",
1103
- "HTTP_PROXY",
1104
- "HTTPS_PROXY",
1105
- "ALL_PROXY",
1106
- "NO_PROXY",
1107
- "http_proxy",
1108
- "https_proxy",
1109
- "all_proxy",
1110
- "no_proxy",
1111
- "NODE_EXTRA_CA_CERTS",
1112
- "SSL_CERT_FILE"
1113
- ];
1114
- const env = {};
1115
- for (const key of allow) {
1116
- const value = process.env[key];
1117
- if (value !== void 0) env[key] = value;
998
+ function formatEverySeconds(seconds) {
999
+ if (seconds % 86400 === 0) return `${seconds / 86400}d`;
1000
+ if (seconds % 3600 === 0) return `${seconds / 3600}h`;
1001
+ if (seconds % 60 === 0) return `${seconds / 60}m`;
1002
+ return `${seconds}s`;
1003
+ }
1004
+ function summarizeSchedule(schedule) {
1005
+ if ("at" in schedule) {
1006
+ return { kind: "at", text: `at ${schedule.at}` };
1118
1007
  }
1119
- env.PIE_CRON_ROLE = "worker";
1120
- if (configDir) env.PIE_CODING_AGENT_DIR = configDir;
1121
- return env;
1008
+ if ("every" in schedule) {
1009
+ return {
1010
+ kind: "every",
1011
+ text: `every ${formatEverySeconds(schedule.every)}`,
1012
+ ...schedule.count !== void 0 ? { count: schedule.count } : {}
1013
+ };
1014
+ }
1015
+ return {
1016
+ kind: "cron",
1017
+ text: `cron ${schedule.cron}`,
1018
+ ...schedule.count !== void 0 ? { count: schedule.count } : {}
1019
+ };
1122
1020
  }
1123
- function readProcessErrorExcerpt(logFile, startOffset) {
1021
+ function toJobView(job, storeKey, storeOwnerLabel) {
1022
+ const processCmd = parseProcessCommand(job);
1023
+ const isProc = isProcessJob(job);
1024
+ const managedBy = processCmd?.managedBy;
1025
+ const summary = managedBy ? managedBy : isProc ? processCmd?.command.slice(0, 3).join(" ") ?? "process" : job.prompt.replace(/\s+/g, " ").trim().slice(0, 80);
1026
+ const ownerLabel = storeOwnerLabel ?? (isProc ? "system" : void 0);
1027
+ return {
1028
+ id: job.id,
1029
+ storeKey,
1030
+ ...ownerLabel ? { ownerLabel } : {},
1031
+ sessionId: job.sessionId,
1032
+ cwd: job.cwd,
1033
+ isProcess: isProc,
1034
+ ...managedBy ? { managedBy } : {},
1035
+ summary,
1036
+ schedule: summarizeSchedule(job.schedule),
1037
+ enabled: job.enabled,
1038
+ state: job.state,
1039
+ next: job.next,
1040
+ ...job.remaining !== void 0 ? { remaining: job.remaining } : {},
1041
+ ...job.pendingAction ? { pendingAction: job.pendingAction } : {},
1042
+ ...typeof job.error === "string" && job.error ? { error: job.error.slice(0, 200) } : {}
1043
+ };
1044
+ }
1045
+ function stateSortRank(job) {
1046
+ if (job.state === "running") return 0;
1047
+ if (job.state === "blocked") return 1;
1048
+ if (job.enabled) return 2;
1049
+ return 3;
1050
+ }
1051
+ function sortJobs(jobs) {
1052
+ return jobs.sort((a, b) => {
1053
+ if (a.isProcess !== b.isProcess) return a.isProcess ? 1 : -1;
1054
+ const rankDiff = stateSortRank(a) - stateSortRank(b);
1055
+ if (rankDiff !== 0) return rankDiff;
1056
+ const aNext = a.next ?? Number.MAX_SAFE_INTEGER;
1057
+ const bNext = b.next ?? Number.MAX_SAFE_INTEGER;
1058
+ if (aNext !== bNext) return aNext - bNext;
1059
+ return a.id.localeCompare(b.id);
1060
+ });
1061
+ }
1062
+ function pinContainedDir(parentDir, targetDir) {
1063
+ if (!isContainedNonSymlink(parentDir, targetDir, "dir")) return void 0;
1124
1064
  try {
1125
- const stat = fs3.statSync(logFile);
1126
- if (!stat.isFile() || stat.size <= startOffset) return void 0;
1127
- const maxRead = 4096;
1128
- const readStart = Math.max(startOffset, stat.size - maxRead);
1129
- const length = stat.size - readStart;
1130
- if (length <= 0) return void 0;
1131
- const buf = Buffer.alloc(length);
1132
- const fd = fs3.openSync(logFile, "r");
1133
- try {
1134
- fs3.readSync(fd, buf, 0, length, readStart);
1135
- } finally {
1136
- fs3.closeSync(fd);
1137
- }
1138
- const lines = buf.toString("utf8").replace(/\x1b\[[0-9;]*[a-zA-Z]/g, "").split(/\r?\n/).map((line) => line.replace(/[\x00-\x1f\x7f]/g, " ").replace(/\s+/g, " ").trim()).filter((line) => line.length > 0 && !/^at\s+/.test(line) && !/^[{}[\],]+$/.test(line) && !/^(?:code|path|requestPath|requireStack):/.test(line) && !/^-\s+/.test(line));
1139
- if (lines.length === 0) return void 0;
1140
- const preferred = lines.find((line) => /Fatal error:|Error:|failed\b|Cannot find module/i.test(line)) ?? lines[lines.length - 1];
1141
- return preferred.length > 200 ? `${preferred.slice(0, 197)}...` : preferred;
1065
+ const st = fs3.lstatSync(targetDir, { bigint: true });
1066
+ if (st.isSymbolicLink() || !st.isDirectory()) return void 0;
1067
+ return { path: targetDir, dev: st.dev, ino: st.ino };
1142
1068
  } catch {
1143
1069
  return void 0;
1144
1070
  }
1145
1071
  }
1146
- var PROCESS_WORKER_RETRYABLE_EXIT_CODE = 75;
1147
- var ProcessWorkerCancelled = class extends Error {
1148
- aborted = true;
1149
- constructor(message) {
1150
- super(message);
1151
- this.name = "ProcessWorkerCancelled";
1072
+ function assertPinnedChain(configRoot, chain) {
1073
+ let parent = configRoot;
1074
+ for (const node of chain) {
1075
+ if (!isContainedNonSymlink(parent, node.path, "dir")) {
1076
+ throw new Error("worker cron store containment check failed");
1077
+ }
1078
+ const st = fs3.lstatSync(node.path, { bigint: true });
1079
+ if (st.isSymbolicLink() || !st.isDirectory() || st.dev !== node.dev || st.ino !== node.ino) {
1080
+ throw new Error("worker cron store directory identity changed");
1081
+ }
1082
+ parent = node.path;
1152
1083
  }
1153
- };
1154
- var ProcessWorkerRetryable = class extends Error {
1155
- retryable = true;
1156
- constructor(message) {
1157
- super(message);
1158
- this.name = "ProcessWorkerRetryable";
1084
+ }
1085
+ function resolveVerifiedAgentsDir(configRoot) {
1086
+ const pieProcDir = path3.join(configRoot, "pie-proc");
1087
+ const pinnedPieProc = pinContainedDir(configRoot, pieProcDir);
1088
+ if (!pinnedPieProc) return void 0;
1089
+ const agentsDir = path3.join(pieProcDir, "agents");
1090
+ const pinnedAgents = pinContainedDir(pieProcDir, agentsDir);
1091
+ if (!pinnedAgents) return void 0;
1092
+ return { agentsDir, prefixChain: [pinnedPieProc, pinnedAgents] };
1093
+ }
1094
+ function resolveVerifiedWorkerStore(configRoot, resolvedAgents, name) {
1095
+ if (!SAFE_WORKER_NAME.test(name)) return void 0;
1096
+ const agentDir = path3.join(resolvedAgents.agentsDir, name);
1097
+ const pinnedAgent = pinContainedDir(resolvedAgents.agentsDir, agentDir);
1098
+ if (!pinnedAgent) return void 0;
1099
+ const cronDir = path3.join(agentDir, "cron");
1100
+ const pinnedCron = pinContainedDir(agentDir, cronDir);
1101
+ if (!pinnedCron) return void 0;
1102
+ const stateFile = path3.join(cronDir, "state.json");
1103
+ if (!isContainedNonSymlink(cronDir, stateFile, "file")) return void 0;
1104
+ const fullChain = [...resolvedAgents.prefixChain, pinnedAgent, pinnedCron];
1105
+ return {
1106
+ storeKey: `worker:${name}`,
1107
+ ownerLabel: name,
1108
+ store: new Store(cronDir, {
1109
+ createDir: false,
1110
+ verifyDir: () => assertPinnedChain(configRoot, fullChain)
1111
+ })
1112
+ };
1113
+ }
1114
+ function enumerateVerifiedStores(primaryStore, configRoot) {
1115
+ const stores = [{ storeKey: "host", store: primaryStore }];
1116
+ const resolvedAgents = resolveVerifiedAgentsDir(configRoot);
1117
+ if (!resolvedAgents) return stores;
1118
+ let entries;
1119
+ try {
1120
+ entries = fs3.readdirSync(resolvedAgents.agentsDir).sort();
1121
+ } catch {
1122
+ return stores;
1159
1123
  }
1160
- };
1161
- function runProcessWorker(job, command, cwd, deadlineMs = 30 * 60 * 1e3, logDir, signal, configDir) {
1162
- return new Promise((resolve3, reject) => {
1163
- const dir = logDir ?? path3.join(process.cwd(), "cron");
1164
- const logFile = path3.join(dir, "process.log");
1165
- try {
1166
- fs3.mkdirSync(dir, { recursive: true, mode: 448 });
1167
- } catch {
1168
- }
1169
- const stamp = (/* @__PURE__ */ new Date()).toISOString();
1170
- const header = `[${stamp}] job=${job.id} cwd=${cwd} cmd=${JSON.stringify(command.command)}
1171
- `;
1172
- try {
1173
- fs3.appendFileSync(logFile, header);
1174
- } catch {
1175
- }
1176
- const logStartOffset = (() => {
1177
- try {
1178
- return fs3.statSync(logFile).size;
1179
- } catch {
1180
- return 0;
1181
- }
1182
- })();
1183
- let out;
1184
- try {
1185
- out = fs3.openSync(logFile, "a");
1186
- } catch {
1187
- }
1188
- let child;
1189
- let settled = false;
1190
- let failure;
1191
- let hostCancelled = false;
1192
- let termination;
1193
- let cleanupFailure;
1194
- let leaderExited = false;
1195
- let deadlineTimer;
1196
- const ABORT_FAILURE = "worker interrupted; outcome uncertain";
1197
- const signalGroup = (signal2) => {
1198
- if (!child?.pid) return false;
1199
- try {
1200
- process.kill(-child.pid, signal2);
1201
- return true;
1202
- } catch (error) {
1203
- if (error.code === "ESRCH") return false;
1204
- throw error;
1205
- }
1206
- };
1207
- const terminate = () => {
1208
- if (settled || termination) return;
1209
- termination = (async () => {
1210
- if (!child?.pid) return;
1211
- if (process.platform === "win32") {
1212
- if (leaderExited) return;
1213
- const pid = child.pid;
1214
- await new Promise((resolve4, reject2) => {
1215
- const killer = spawn("taskkill", ["/F", "/T", "/PID", String(pid)], { stdio: "ignore", windowsHide: true });
1216
- killer.on("error", reject2);
1217
- killer.on("close", (code) => code === 0 ? resolve4() : reject2(new Error(`taskkill exited ${code}`)));
1218
- });
1219
- return;
1220
- }
1221
- if (!signalGroup("SIGTERM")) return;
1222
- const until = Date.now() + 5e3;
1223
- while (Date.now() < until) {
1224
- await new Promise((resolve4) => setTimeout(resolve4, 25));
1225
- if (!signalGroup(0)) return;
1226
- }
1227
- signalGroup("SIGKILL");
1228
- await new Promise((resolve4) => setTimeout(resolve4, 50));
1229
- })().catch((error) => {
1230
- cleanupFailure = error;
1231
- });
1232
- };
1233
- const stop = () => {
1234
- if (settled) return;
1235
- hostCancelled = true;
1236
- failure ??= ABORT_FAILURE;
1237
- terminate();
1238
- };
1239
- try {
1240
- child = spawn(command.command[0], command.command.slice(1), {
1241
- cwd,
1242
- env: processJobEnv(configDir),
1243
- stdio: ["ignore", out ?? "ignore", out ?? "ignore"],
1244
- detached: process.platform !== "win32",
1245
- windowsHide: true
1246
- });
1247
- } catch (error) {
1248
- if (out !== void 0) {
1124
+ for (const name of entries) {
1125
+ const verified = resolveVerifiedWorkerStore(configRoot, resolvedAgents, name);
1126
+ if (verified) stores.push(verified);
1127
+ }
1128
+ return stores;
1129
+ }
1130
+ function resolveStoresForKey(primaryStore, configRoot, storeKey) {
1131
+ if (!storeKey) return enumerateVerifiedStores(primaryStore, configRoot);
1132
+ if (storeKey === "host") return [{ storeKey: "host", store: primaryStore }];
1133
+ if (storeKey.startsWith("worker:")) {
1134
+ const resolvedAgents = resolveVerifiedAgentsDir(configRoot);
1135
+ if (!resolvedAgents) return [];
1136
+ const verified = resolveVerifiedWorkerStore(configRoot, resolvedAgents, storeKey.slice("worker:".length));
1137
+ return verified ? [verified] : [];
1138
+ }
1139
+ return [];
1140
+ }
1141
+ function createCronPanelBridge(params) {
1142
+ const { primaryStore, configRoot, getAuthorization, getStartupError } = params;
1143
+ return {
1144
+ listJobs(opts) {
1145
+ const stores = enumerateVerifiedStores(primaryStore, configRoot);
1146
+ const jobs = [];
1147
+ const warnings = [];
1148
+ let hostJobMatched = false;
1149
+ for (const entry of stores) {
1249
1150
  try {
1250
- fs3.closeSync(out);
1251
- } catch {
1151
+ const state = entry.store.read();
1152
+ let invalidIdCount = 0;
1153
+ for (const job of state.jobs) {
1154
+ if (opts?.sessionId && job.sessionId !== opts.sessionId) continue;
1155
+ if (!SAFE_JOB_ID.test(job.id)) {
1156
+ invalidIdCount++;
1157
+ continue;
1158
+ }
1159
+ if (entry.storeKey === "host") hostJobMatched = true;
1160
+ jobs.push(toJobView(job, entry.storeKey, entry.ownerLabel));
1161
+ }
1162
+ if (invalidIdCount > 0) {
1163
+ warnings.push(`${entry.storeKey}: skipped ${invalidIdCount} job(s) with invalid id`);
1164
+ }
1165
+ } catch (error) {
1166
+ warnings.push(`${entry.storeKey}: ${error instanceof Error ? error.message : String(error)}`);
1252
1167
  }
1253
1168
  }
1254
- reject(error instanceof Error ? error : new Error(String(error)));
1255
- return;
1256
- }
1257
- const cleanup = () => {
1258
- if (deadlineTimer !== void 0) clearTimeout(deadlineTimer);
1259
- signal?.removeEventListener("abort", stop);
1260
- if (out !== void 0) {
1169
+ const hostStartupErr = getStartupError?.();
1170
+ if (hostStartupErr && (!opts?.sessionId || hostJobMatched)) {
1171
+ warnings.push(`host: cron unavailable (${hostStartupErr}); see docs/cron.md recovery`);
1172
+ }
1173
+ return {
1174
+ jobs: sortJobs(jobs),
1175
+ ...warnings.length > 0 ? { warnings } : {}
1176
+ };
1177
+ },
1178
+ mutateJob(jobId, action, opts) {
1179
+ if (!SAFE_JOB_ID.test(jobId)) {
1180
+ return { ok: false, detail: "invalid job id" };
1181
+ }
1182
+ const stores = resolveStoresForKey(primaryStore, configRoot, opts?.storeKey);
1183
+ const candidates = [];
1184
+ for (const entry2 of stores) {
1261
1185
  try {
1262
- fs3.closeSync(out);
1186
+ const found = entry2.store.read().jobs.find((j) => j.id === jobId);
1187
+ if (found) candidates.push({ entry: entry2, job: found });
1263
1188
  } catch {
1264
1189
  }
1265
1190
  }
1266
- };
1267
- deadlineTimer = setTimeout(() => {
1268
- if (settled) return;
1269
- failure = `process job exceeded ${deadlineMs}ms`;
1270
- terminate();
1271
- }, deadlineMs);
1272
- deadlineTimer.unref();
1273
- if (signal?.aborted) stop();
1274
- else signal?.addEventListener("abort", stop, { once: true });
1275
- child.on("error", (error) => {
1276
- failure = error.message;
1277
- });
1278
- child.on("exit", () => {
1279
- leaderExited = true;
1280
- });
1281
- child.on("close", async (code) => {
1282
- if (settled) return;
1283
- cleanup();
1284
- if (!termination && process.platform !== "win32") {
1285
- try {
1286
- if (signalGroup(0)) {
1287
- failure = "command left background descendants";
1288
- terminate();
1289
- }
1290
- } catch (error) {
1291
- cleanupFailure = error;
1292
- }
1191
+ if (candidates.length === 0) {
1192
+ return { ok: false, detail: "unknown job (already removed or not found)" };
1293
1193
  }
1294
- await termination;
1295
- settled = true;
1296
- if (cleanupFailure) failure = `process cleanup failed: ${String(cleanupFailure)}`;
1297
- const excerpt = !failure && !cleanupFailure && code !== 0 ? readProcessErrorExcerpt(logFile, logStartOffset) : void 0;
1298
- try {
1299
- fs3.appendFileSync(logFile, `[${(/* @__PURE__ */ new Date()).toISOString()}] job=${job.id} exit=${code}${failure ? ` error=${failure}` : ""}
1300
- `);
1301
- } catch {
1194
+ if (candidates.length > 1) {
1195
+ return { ok: false, detail: "ambiguous job id across multiple stores" };
1302
1196
  }
1303
- if (hostCancelled && !cleanupFailure) {
1304
- reject(new ProcessWorkerCancelled(failure ?? `cancelled (exit ${code})`));
1305
- return;
1197
+ const { entry, job: before } = candidates[0];
1198
+ if (opts?.sessionId && before.sessionId !== opts.sessionId) {
1199
+ return { ok: false, detail: "job does not belong to target worker session" };
1306
1200
  }
1307
- if (!failure && !cleanupFailure && command.managedBy === "memory" && code === PROCESS_WORKER_RETRYABLE_EXIT_CODE) {
1308
- reject(new ProcessWorkerRetryable(`transient memory distillation failure (exit ${code})${excerpt ? `: ${excerpt}` : ""}`));
1309
- return;
1201
+ const beforeView = toJobView(before, entry.storeKey, entry.ownerLabel);
1202
+ if (entry.storeKey === "host") {
1203
+ const hostStartupErr = getStartupError?.();
1204
+ if (hostStartupErr) {
1205
+ return {
1206
+ ok: false,
1207
+ detail: `cron unavailable: ${hostStartupErr}; see docs/cron.md recovery`,
1208
+ job: beforeView
1209
+ };
1210
+ }
1310
1211
  }
1311
- if (failure || code !== 0) reject(new Error(failure ?? `process exited ${code}${excerpt ? `: ${excerpt}` : ""}`));
1312
- else resolve3();
1313
- });
1314
- });
1315
- }
1316
-
1317
- // builtin/extensions/cron/runtime.ts
1318
- var delay = (ms) => new Promise((resolve3) => setTimeout(resolve3, ms));
1319
- var isContention = (error) => error?.code === "EEXIST";
1320
- var COORDINATOR_OWNER_FILE = "owner.json";
1321
- var COORDINATOR_METADATA_GRACE_MS = 5e3;
1322
- var STORE_OWNER_SWEEP_INTERVAL_MS = 5 * 6e4;
1323
- function defaultProcessAlive(pid) {
1324
- try {
1325
- process.kill(pid, 0);
1326
- return true;
1327
- } catch (error) {
1328
- return error?.code !== "ESRCH";
1329
- }
1330
- }
1331
- var Runtime = class {
1332
- constructor(ctx, store, execute = runWorker, processAlive = defaultProcessAlive, executeProcess = runProcessWorker) {
1333
- this.ctx = ctx;
1334
- this.store = store;
1335
- this.execute = execute;
1336
- this.processAlive = processAlive;
1337
- this.executeProcess = executeProcess;
1338
- this.cwd = fs4.realpathSync(ctx.cwd);
1339
- }
1340
- ctx;
1341
- store;
1342
- execute;
1343
- processAlive;
1344
- executeProcess;
1345
- id = randomUUID3();
1346
- sessionId = null;
1347
- leader = false;
1348
- recovering = false;
1349
- stopped = false;
1350
- /** Non-contention poll-failure backoff (schema-invalid state): 1s → 5min.
1351
- * Cleared on the first successful poll after a failure. */
1352
- pollFailureBackoffMs;
1353
- /** Earliest wall-clock time a poll may run again after a non-contention
1354
- * failure. The 1s interval keeps firing but poll() gates on this;
1355
- * scheduleRecoveryPoll arms a timer AT the gate so recovery actually
1356
- * happens — round-5 finding: the backoff value was computed but never
1357
- * consumed, so a poisoned state logged once per second forever. */
1358
- pollRetryAt;
1359
- recoveryPollTimer;
1360
- initialized = false;
1361
- binding = 0;
1362
- polling = false;
1363
- timer;
1364
- abort = new AbortController();
1365
- processAbort = new AbortController();
1366
- worker;
1367
- cwd;
1368
- notices = /* @__PURE__ */ new Set();
1369
- completions = /* @__PURE__ */ new Map();
1370
- accepted;
1371
- /** P1-3b: consecutive idle observations for the current delivery. A queued
1372
- * follow-up turn can leave a single idle gap between turns, so one idle
1373
- * poll is not proof the delivery is over. */
1374
- acceptedIdlePolls = 0;
1375
- unreadableCoordinatorSince;
1376
- coordinatorNotices = /* @__PURE__ */ new Set();
1377
- lastOwnerSweepAt = 0;
1378
- get ready() {
1379
- return this.initialized && !this.stopped;
1380
- }
1381
- get generation() {
1382
- return this.binding;
1383
- }
1384
- onStart() {
1385
- if (this.accepted?.consumed) this.accepted.busy = true;
1386
- }
1387
- onMessage(message) {
1388
- if (!this.accepted || message.role !== "user") return;
1389
- const text = typeof message.content === "string" ? message.content : message.content.filter((block) => block.type === "text").map((block) => block.text).join("\n");
1390
- if (text.includes(this.accepted.content)) {
1391
- this.accepted.consumed = true;
1392
- this.accepted.busy = true;
1393
- }
1394
- }
1395
- onFailure() {
1396
- if (this.accepted?.consumed) this.accepted.error = "interactive turn failed or cancelled; inspect before resuming";
1397
- }
1398
- start() {
1399
- this.initialized = false;
1400
- this.timer = setInterval(() => void this.poll(), 1e3);
1401
- this.timer.unref();
1402
- void this.ensureMemoryDistillationDefault();
1403
- }
1404
- /** Default daily distillation at 03:00 local. Idempotent: an existing
1405
- * managed job keeps user pause/running reservations, while:
1406
- * - enabled repeating `blocked` jobs auto-recover on startup (and refresh
1407
- * stale/upgraded CLI commands) so a fixed release or config heals
1408
- * itself without manual intervention on every machine;
1409
- * - enabled `ready` jobs migrate their command in-place when
1410
- * `PIE_SESSIONS_DIR` mismatches or the persisted node/CLI binary path
1411
- * no longer exists on disk (e.g. Homebrew node upgrade). */
1412
- async ensureMemoryDistillationDefault() {
1413
- try {
1414
- const existing = this.store.findProcess("memory");
1415
- if (existing) {
1416
- const currentCmd = (() => {
1417
- try {
1418
- return JSON.parse(existing.prompt).command ?? [];
1419
- } catch {
1420
- return [];
1421
- }
1422
- })();
1423
- const desiredCmd = managedMemoryCommand();
1424
- const isManagedDistillCmd = currentCmd.includes("memory") && currentCmd.includes("distill");
1425
- const hasMissingBinaryOrEntry = (() => {
1426
- if (!isManagedDistillCmd) return false;
1427
- const bin = currentCmd[0];
1428
- if (bin && path4.isAbsolute(bin) && !fs4.existsSync(bin)) return true;
1429
- const memIdx = currentCmd.indexOf("memory");
1430
- const entry = memIdx >= 2 ? currentCmd[memIdx - 1] : void 0;
1431
- if (entry && path4.isAbsolute(entry) && !fs4.existsSync(entry)) return true;
1432
- return false;
1433
- })();
1434
- const isBundledCli = (() => {
1435
- const hasLoader = desiredCmd.some((arg) => /^--(?:import|loader|experimental-loader)(?:=|$)/.test(arg));
1436
- if (hasLoader) return false;
1437
- const memIdx = desiredCmd.indexOf("memory");
1438
- const entry = memIdx >= 2 ? desiredCmd[memIdx - 1] : void 0;
1439
- return Boolean(entry && /(?:^|[\\/])cli\.js$/i.test(entry) && fs4.existsSync(entry));
1440
- })();
1441
- const sessionsDirMismatch = (() => {
1442
- if (!process.env.PIE_SESSIONS_DIR || !desiredCmd.includes("--sessions-dir")) return false;
1443
- const curIdx = currentCmd.indexOf("--sessions-dir");
1444
- const wantIdx = desiredCmd.indexOf("--sessions-dir");
1445
- const curDir = curIdx >= 0 ? currentCmd[curIdx + 1] : void 0;
1446
- const wantDir = wantIdx >= 0 ? desiredCmd[wantIdx + 1] : void 0;
1447
- return curDir !== wantDir ? wantDir : false;
1448
- })();
1449
- if (existing.enabled && existing.state === "blocked") {
1450
- const shouldRefreshCmd = isManagedDistillCmd && (hasMissingBinaryOrEntry || Boolean(sessionsDirMismatch) || isBundledCli && (currentCmd.length !== desiredCmd.length || currentCmd.some((v, i) => v !== desiredCmd[i])));
1451
- const rec = this.store.recoverBlockedProcess("memory", {
1452
- ...shouldRefreshCmd ? { command: desiredCmd } : {}
1212
+ const authorization = getAuthorization();
1213
+ const actor = opts?.senderId ? `im-panel:${opts.senderId}` : "im-panel";
1214
+ try {
1215
+ const outcome = entry.store.change(jobId, action, Date.now(), {
1216
+ ...action === "resume" ? { authorization } : {},
1217
+ ...opts?.sessionId ? { expectedSessionId: opts.sessionId } : {},
1218
+ ...action === "remove" ? { disableManagedOnRemove: true } : {}
1219
+ });
1220
+ const after = entry.store.read().jobs.find((j) => j.id === jobId);
1221
+ const afterView = after ? toJobView(after, entry.storeKey, entry.ownerLabel) : beforeView;
1222
+ try {
1223
+ entry.store.audit({
1224
+ kind: action,
1225
+ jobId,
1226
+ sessionId: before.sessionId,
1227
+ cwd: before.cwd,
1228
+ authorization,
1229
+ detail: outcome === "deferred" ? `${actor} (deferred until running occurrence settles)` : actor
1453
1230
  });
1454
- if (rec.recovered) {
1455
- this.ctx.log(
1456
- `cron: auto-recovered blocked managed memory distillation job (was: ${rec.previousError ?? "unknown"}; next ${rec.next !== void 0 ? new Date(rec.next).toISOString() : "none"}${rec.commandUpdated ? "; refreshed command" : ""})`
1457
- );
1458
- }
1459
- return;
1460
- }
1461
- if (sessionsDirMismatch || hasMissingBinaryOrEntry) {
1462
- const outcome = this.store.syncProcessCommand("memory", desiredCmd);
1463
- if (outcome === "updated") {
1464
- const reason = sessionsDirMismatch ? `pin --sessions-dir ${sessionsDirMismatch}` : "repair missing node/CLI executable path";
1465
- this.ctx.log(`cron: migrated managed memory distillation command to ${reason}`);
1466
- } else if (outcome === "deferred" && sessionsDirMismatch) {
1467
- this.ctx.log(`cron: managed memory distillation job needs repair to pin --sessions-dir ${sessionsDirMismatch} (currently ${existing.state === "running" ? "running" : !existing.enabled ? "paused" : existing.state}; run 'pie memory schedule on' when ready)`);
1468
- }
1231
+ } catch {
1469
1232
  }
1470
- return;
1233
+ return {
1234
+ ok: true,
1235
+ outcome,
1236
+ detail: outcome === "deferred" ? `${action} queued until current run finishes` : `${action} applied`,
1237
+ job: afterView
1238
+ };
1239
+ } catch (error) {
1240
+ return {
1241
+ ok: false,
1242
+ detail: error instanceof Error ? error.message : String(error),
1243
+ job: beforeView
1244
+ };
1471
1245
  }
1472
- await new Promise((resolve3) => setImmediate(resolve3));
1473
- const command = managedMemoryCommand();
1474
- const cronSpec = localTimeToCronUtc("03:00");
1475
- if ("error" in cronSpec) throw new Error(cronSpec.error);
1476
- if (this.store.ensureProcess(command, "memory", process.cwd(), cronSpec))
1477
- this.ctx.log("cron: registered the default daily memory distillation (03:00)");
1478
- } catch (error) {
1479
- const message = String(error instanceof Error ? error.message : error);
1480
- if (/managed job is (blocked|paused|currently running)/.test(message)) return;
1481
- this.ctx.log(`cron: default memory distillation registration failed: ${message}`);
1482
- }
1483
- }
1484
- markUnsafe() {
1485
- fs4.mkdirSync(path4.join(this.store.dir, "unsafe.lock"), { recursive: true, mode: 448 });
1486
- }
1487
- coordinatorDir() {
1488
- return path4.join(this.store.dir, "scheduler.lock");
1489
- }
1490
- coordinatorOwnerFile() {
1491
- return path4.join(this.coordinatorDir(), COORDINATOR_OWNER_FILE);
1492
- }
1493
- readCoordinatorOwner() {
1494
- try {
1495
- const file = this.coordinatorOwnerFile(), stat = fs4.lstatSync(file);
1496
- if (!stat.isFile() || stat.size > 4096) return void 0;
1497
- const raw = fs4.readFileSync(file, "utf8"), value = JSON.parse(raw);
1498
- if (value?.version !== 1 || !Number.isSafeInteger(value.pid) || value.pid <= 0 || typeof value.instanceId !== "string" || !value.instanceId || value.instanceId.length > 128 || !Number.isSafeInteger(value.createdAt)) return void 0;
1499
- return { value, raw };
1500
- } catch {
1501
- return void 0;
1502
- }
1503
- }
1504
- noteCoordinatorMetadata(valid, now) {
1505
- if (valid) {
1506
- this.unreadableCoordinatorSince = void 0;
1507
- return;
1508
- }
1509
- if (this.unreadableCoordinatorSince === void 0) {
1510
- this.unreadableCoordinatorSince = now;
1511
- return;
1512
1246
  }
1513
- if (this.coordinatorNotices.has("metadata") || now - this.unreadableCoordinatorSince < COORDINATOR_METADATA_GRACE_MS) return;
1514
- this.coordinatorNotices.add("metadata");
1515
- this.ctx.ui.notify("cron: coordinator lock metadata is missing or invalid; scheduling is paused. See docs/cron.md offline recovery.", "warning");
1516
- }
1517
- withCoordinatorMutex(fn) {
1518
- return this.store.withWriteLock(() => fn());
1247
+ };
1248
+ }
1249
+ function pruneWorkerManagedMemoryJobs(configRoot) {
1250
+ const result = { pruned: 0, skippedRunning: 0, errors: [] };
1251
+ const resolvedAgents = resolveVerifiedAgentsDir(configRoot);
1252
+ if (!resolvedAgents) return result;
1253
+ let entries;
1254
+ try {
1255
+ entries = fs3.readdirSync(resolvedAgents.agentsDir).sort();
1256
+ } catch {
1257
+ return result;
1519
1258
  }
1520
- acquireCoordinator() {
1521
- const dir = this.coordinatorDir();
1522
- fs4.mkdirSync(dir, { mode: 448 });
1523
- const owner = { version: 1, pid: process.pid, instanceId: this.id, createdAt: Date.now() };
1259
+ for (const name of entries) {
1260
+ const verified = resolveVerifiedWorkerStore(configRoot, resolvedAgents, name);
1261
+ if (!verified) continue;
1524
1262
  try {
1525
- fs4.writeFileSync(this.coordinatorOwnerFile(), JSON.stringify(owner), { mode: 384, flag: "wx" });
1526
- } catch (error) {
1527
- try {
1528
- fs4.unlinkSync(this.coordinatorOwnerFile());
1529
- } catch {
1263
+ const existing = verified.store.findProcess("memory");
1264
+ if (!existing) continue;
1265
+ if (existing.state === "running") {
1266
+ result.skippedRunning += 1;
1267
+ continue;
1530
1268
  }
1531
- try {
1532
- fs4.rmdirSync(dir);
1533
- } catch {
1269
+ if (verified.store.disableProcess("memory")) {
1270
+ result.pruned += 1;
1534
1271
  }
1535
- throw error;
1272
+ } catch (error) {
1273
+ result.errors.push(`${verified.storeKey}: ${error instanceof Error ? error.message : String(error)}`);
1536
1274
  }
1537
- this.leader = true;
1538
- this.recovering = true;
1539
- this.noteCoordinatorMetadata(true, Date.now());
1540
1275
  }
1541
- reclaimDeadCoordinator(now) {
1542
- const held = this.readCoordinatorOwner();
1543
- if (!held) {
1544
- this.noteCoordinatorMetadata(false, now);
1545
- return false;
1546
- }
1547
- this.noteCoordinatorMetadata(true, now);
1548
- if (this.processAlive(held.value.pid)) return false;
1549
- if (this.store.read().jobs.some((job) => job.state === "running")) {
1550
- const key = `running:${held.value.instanceId}`;
1551
- if (!this.coordinatorNotices.has(key)) {
1552
- this.coordinatorNotices.add(key);
1553
- this.ctx.ui.notify("cron: dead coordinator has running work; scheduling remains paused for offline recovery.", "warning");
1554
- }
1555
- return false;
1556
- }
1557
- const latest = this.readCoordinatorOwner();
1558
- if (!latest || latest.raw !== held.raw) return false;
1276
+ return result;
1277
+ }
1278
+
1279
+ // builtin/extensions/cron/worker.ts
1280
+ import { spawn } from "node:child_process";
1281
+ import { randomUUID as randomUUID2 } from "node:crypto";
1282
+ import * as fs4 from "node:fs";
1283
+ import * as path4 from "node:path";
1284
+ import { StringDecoder } from "node:string_decoder";
1285
+ function runWorker(job, signal, cli = process.argv[1], configDir) {
1286
+ if (signal.aborted) return Promise.reject(new Error("worker interrupted before launch"));
1287
+ return new Promise((resolve3, reject) => {
1288
+ const child = spawn(process.execPath, [path4.resolve(cli), "--json-events", "--session-id", job.sessionId, "--resume-required"], {
1289
+ cwd: job.cwd,
1290
+ // R5-P2: a cron worker is an INDEPENDENT session — strip the manager
1291
+ // identity/model quartet so it never inherits the manager's model or
1292
+ // curated name (same boundary contract as pie-proc and the bash tool).
1293
+ env: (() => {
1294
+ const { PIE_DEFAULT_PROVIDER: _p, PIE_DEFAULT_MODEL: _m, PIE_MANAGER_BOOTSTRAP: _b, PIE_PROC_CURATED_NAME: _c, ...cleanEnv } = process.env;
1295
+ return { ...cleanEnv, ...configDir ? { PIE_CODING_AGENT_DIR: configDir } : {}, PIE_CRON_ROLE: "worker" };
1296
+ })(),
1297
+ stdio: ["pipe", "pipe", "pipe"],
1298
+ windowsHide: true
1299
+ });
1300
+ const decoder = new StringDecoder("utf8");
1301
+ const turnId = randomUUID2();
1302
+ let buffer = "", settled = false, sent = false, completed = false;
1303
+ let failure;
1304
+ let killTimer;
1305
+ const stop = () => {
1306
+ failure ??= "worker interrupted; outcome uncertain";
1307
+ child.kill();
1308
+ killTimer ??= setTimeout(() => child.kill("SIGKILL"), 5e3);
1309
+ killTimer.unref();
1310
+ };
1311
+ const protocolError = (message) => {
1312
+ failure = message;
1313
+ stop();
1314
+ };
1315
+ signal.addEventListener("abort", stop, { once: true });
1316
+ const timer = setTimeout(stop, 15 * 6e4);
1317
+ timer.unref();
1318
+ child.stdin.on("error", () => {
1319
+ });
1320
+ child.stderr.resume();
1321
+ child.stdout.on("data", (chunk) => {
1322
+ buffer += decoder.write(chunk);
1323
+ if (buffer.length > 2e6) {
1324
+ protocolError("oversized worker event; outcome uncertain");
1325
+ return;
1326
+ }
1327
+ let index;
1328
+ while ((index = buffer.indexOf("\n")) >= 0) {
1329
+ const line = buffer.slice(0, index);
1330
+ buffer = buffer.slice(index + 1);
1331
+ try {
1332
+ const event = JSON.parse(line);
1333
+ if (!event || typeof event.type !== "string") throw new Error("invalid event");
1334
+ if (event.type === "agent.ready") {
1335
+ if (sent || event.sessionId !== job.sessionId) {
1336
+ protocolError("worker readiness/session mismatch");
1337
+ return;
1338
+ }
1339
+ sent = true;
1340
+ child.stdin.write(JSON.stringify({ type: "turn.request", sessionId: job.sessionId, turnId, prompt: job.prompt }) + "\n");
1341
+ }
1342
+ if (["turn.completed", "turn.failed", "turn.cancelled", "turn.stalled", "turn.settled"].includes(event.type)) {
1343
+ if (!sent || event.sessionId !== job.sessionId || event.turnId !== turnId || settled) {
1344
+ protocolError("worker turn identity/order mismatch");
1345
+ return;
1346
+ }
1347
+ if (event.type === "turn.completed") {
1348
+ if (completed) {
1349
+ protocolError("duplicate worker completion");
1350
+ return;
1351
+ }
1352
+ completed = true;
1353
+ } else if (event.type === "turn.settled") {
1354
+ if (!completed) {
1355
+ protocolError("worker settled without completion");
1356
+ return;
1357
+ }
1358
+ settled = true;
1359
+ child.stdin.end(JSON.stringify({ type: "shutdown" }) + "\n");
1360
+ } else {
1361
+ protocolError(`worker ${event.type}`);
1362
+ return;
1363
+ }
1364
+ }
1365
+ if (event.type === "error") {
1366
+ protocolError("worker protocol error; inspect session before resuming");
1367
+ return;
1368
+ }
1369
+ } catch {
1370
+ protocolError("invalid worker output");
1371
+ return;
1372
+ }
1373
+ }
1374
+ });
1375
+ child.on("error", (error) => {
1376
+ failure = error.message;
1377
+ });
1378
+ child.on("close", (code) => {
1379
+ clearTimeout(timer);
1380
+ clearTimeout(killTimer);
1381
+ signal.removeEventListener("abort", stop);
1382
+ buffer += decoder.end();
1383
+ if (buffer.trim()) failure ??= "truncated worker event; outcome uncertain";
1384
+ if (failure || !settled || !completed || code !== 0) reject(new Error(failure ?? `worker exited ${code}; outcome uncertain`));
1385
+ else resolve3();
1386
+ });
1387
+ if (signal.aborted) stop();
1388
+ });
1389
+ }
1390
+ function processJobEnv(configDir) {
1391
+ const allow = [
1392
+ "PATH",
1393
+ "PATHEXT",
1394
+ "SYSTEMROOT",
1395
+ "SYSTEMDRIVE",
1396
+ "COMSPEC",
1397
+ "LANG",
1398
+ "LC_ALL",
1399
+ "TZ",
1400
+ "TERM",
1401
+ "TMPDIR",
1402
+ "TEMP",
1403
+ "TMP",
1404
+ "HOME",
1405
+ "USERPROFILE",
1406
+ "XDG_CONFIG_HOME",
1407
+ "XDG_CACHE_HOME",
1408
+ "HTTP_PROXY",
1409
+ "HTTPS_PROXY",
1410
+ "ALL_PROXY",
1411
+ "NO_PROXY",
1412
+ "http_proxy",
1413
+ "https_proxy",
1414
+ "all_proxy",
1415
+ "no_proxy",
1416
+ "NODE_EXTRA_CA_CERTS",
1417
+ "SSL_CERT_FILE"
1418
+ ];
1419
+ const env = {};
1420
+ for (const key of allow) {
1421
+ const value = process.env[key];
1422
+ if (value !== void 0) env[key] = value;
1423
+ }
1424
+ env.PIE_CRON_ROLE = "worker";
1425
+ if (configDir) env.PIE_CODING_AGENT_DIR = configDir;
1426
+ return env;
1427
+ }
1428
+ function readProcessErrorExcerpt(logFile, startOffset) {
1429
+ try {
1430
+ const stat = fs4.statSync(logFile);
1431
+ if (!stat.isFile() || stat.size <= startOffset) return void 0;
1432
+ const maxRead = 4096;
1433
+ const readStart = Math.max(startOffset, stat.size - maxRead);
1434
+ const length = stat.size - readStart;
1435
+ if (length <= 0) return void 0;
1436
+ const buf = Buffer.alloc(length);
1437
+ const fd = fs4.openSync(logFile, "r");
1559
1438
  try {
1560
- fs4.unlinkSync(this.coordinatorOwnerFile());
1561
- fs4.rmdirSync(this.coordinatorDir());
1562
- return true;
1563
- } catch {
1564
- return false;
1439
+ fs4.readSync(fd, buf, 0, length, readStart);
1440
+ } finally {
1441
+ fs4.closeSync(fd);
1565
1442
  }
1443
+ const lines = buf.toString("utf8").replace(/\x1b\[[0-9;]*[a-zA-Z]/g, "").split(/\r?\n/).map((line) => line.replace(/[\x00-\x1f\x7f]/g, " ").replace(/\s+/g, " ").trim()).filter((line) => line.length > 0 && !/^at\s+/.test(line) && !/^[{}[\],]+$/.test(line) && !/^(?:code|path|requestPath|requireStack):/.test(line) && !/^-\s+/.test(line));
1444
+ if (lines.length === 0) return void 0;
1445
+ const preferred = lines.find((line) => /Fatal error:|Error:|failed\b|Cannot find module/i.test(line)) ?? lines[lines.length - 1];
1446
+ return preferred.length > 200 ? `${preferred.slice(0, 197)}...` : preferred;
1447
+ } catch {
1448
+ return void 0;
1566
1449
  }
1567
- releaseCoordinator() {
1568
- fs4.rmSync(this.coordinatorOwnerFile(), { force: true });
1569
- fs4.rmdirSync(this.coordinatorDir());
1570
- this.leader = false;
1450
+ }
1451
+ var PROCESS_WORKER_RETRYABLE_EXIT_CODE = 75;
1452
+ var ProcessWorkerCancelled = class extends Error {
1453
+ aborted = true;
1454
+ constructor(message) {
1455
+ super(message);
1456
+ this.name = "ProcessWorkerCancelled";
1571
1457
  }
1572
- persistOwner(sessionId) {
1573
- this.store.transaction((state) => {
1574
- sweepStaleOwners(state, this.store.dir, { sessionId, keepKey: this.id, warn: (message) => this.ctx.log(message) });
1575
- state.owners[this.id] = { sessionId, cwd: this.cwd, busy: !this.ctx.isIdle(), registeredAt: Date.now() };
1576
- });
1458
+ };
1459
+ var ProcessWorkerRetryable = class extends Error {
1460
+ retryable = true;
1461
+ constructor(message) {
1462
+ super(message);
1463
+ this.name = "ProcessWorkerRetryable";
1464
+ }
1465
+ };
1466
+ function runProcessWorker(job, command, cwd, deadlineMs = 30 * 60 * 1e3, logDir, signal, configDir) {
1467
+ return new Promise((resolve3, reject) => {
1468
+ const dir = logDir ?? path4.join(process.cwd(), "cron");
1469
+ const logFile = path4.join(dir, "process.log");
1577
1470
  try {
1578
- const livenessDir = path4.join(this.store.dir, "owners-liveness");
1579
- fs4.mkdirSync(livenessDir, { recursive: true });
1580
- const liveness = path4.join(livenessDir, `${this.id}.json`);
1581
- try {
1582
- fs4.unlinkSync(liveness);
1583
- } catch {
1584
- }
1585
- fs4.writeFileSync(liveness, JSON.stringify({ pid: process.pid, at: Date.now() }), { mode: 384 });
1471
+ fs4.mkdirSync(dir, { recursive: true, mode: 448 });
1586
1472
  } catch {
1587
1473
  }
1588
- this.sessionId = sessionId;
1589
- this.initialized = true;
1590
- }
1591
- register(sessionId) {
1474
+ const stamp = (/* @__PURE__ */ new Date()).toISOString();
1475
+ const header = `[${stamp}] job=${job.id} cwd=${cwd} cmd=${JSON.stringify(command.command)}
1476
+ `;
1592
1477
  try {
1593
- this.persistOwner(sessionId);
1594
- } catch (error) {
1595
- this.markUnsafe();
1596
- throw error;
1478
+ fs4.appendFileSync(logFile, header);
1479
+ } catch {
1597
1480
  }
1598
- }
1599
- async bind(sessionId) {
1600
- const generation = ++this.binding;
1601
- this.initialized = false;
1602
- for (let attempt = 0; attempt < 20; attempt++) {
1603
- if (this.stopped || generation !== this.binding) return;
1481
+ const logStartOffset = (() => {
1604
1482
  try {
1605
- this.persistOwner(sessionId);
1606
- return;
1607
- } catch (error) {
1608
- if (!isContention(error)) break;
1609
- await delay(25 + Math.floor(Math.random() * 25));
1483
+ return fs4.statSync(logFile).size;
1484
+ } catch {
1485
+ return 0;
1610
1486
  }
1611
- }
1612
- if (!this.stopped && generation === this.binding) this.register(sessionId);
1613
- }
1614
- /** Best-effort durable audit: scheduling must never stop because the audit
1615
- * file is unwritable — the state file remains the source of truth. */
1616
- auditQuiet(record) {
1487
+ })();
1488
+ let out;
1617
1489
  try {
1618
- this.store.audit(record);
1490
+ out = fs4.openSync(logFile, "a");
1619
1491
  } catch {
1620
1492
  }
1621
- }
1622
- /** Block a job with LAYERED handling (review round 2, P1-4).
1623
- *
1624
- * One blocked job freezes the whole session's schedule set, so blocking is
1625
- * expensive. `executed` separates the two cases that used to be conflated:
1626
- *
1627
- * - false: the occurrence provably never ran (duplicate owner, owner
1628
- * changed before delivery). Retrying is safe, so a repeating prompt job
1629
- * is rescheduled ONCE automatically (`retriedOnce`) instead of freezing
1630
- * the session until a human notices. Mirrors completeInterrupted's
1631
- * precedent, and does NOT consume a count-capped execution because
1632
- * nothing executed.
1633
- * - true: the occurrence may already have produced side effects. Keep the
1634
- * conservative block; only a human can decide (double execution is worse
1635
- * than a stalled schedule).
1636
- */
1637
- handleBlock(state, job, error, executed) {
1638
- const pending = job.pendingAction;
1639
- delete job.pendingAction;
1640
- if (pending === "remove") {
1641
- state.jobs = state.jobs.filter((item) => item !== job);
1642
- return;
1643
- }
1644
- if (job.state === "blocked" && job.error === error && !pending) {
1645
- return;
1646
- }
1647
- const repeating = !("at" in job.schedule);
1648
- if (!executed && repeating && !isProcessJob(job) && !job.retriedOnce) {
1649
- job.retriedOnce = true;
1650
- job.state = "ready";
1651
- delete job.target;
1652
- delete job.deliveryStarted;
1653
- job.next = nextTime(job.schedule, Math.max(Date.now(), job.occurrence ?? Date.now()));
1654
- if (job.next === null || pending === "pause") job.enabled = false;
1655
- job.error = `retried automatically after a block that never executed: ${error}`.slice(0, 500);
1656
- this.auditQuiet({ kind: "auto-retry", jobId: job.id, sessionId: job.sessionId, cwd: job.cwd, detail: error });
1657
- return;
1658
- }
1659
- complete(job, error);
1660
- if (pending === "pause") job.enabled = false;
1661
- this.auditQuiet({ kind: "blocked", jobId: job.id, sessionId: job.sessionId, cwd: job.cwd, detail: error });
1662
- }
1663
- notify(job, owners) {
1664
- if (isProcessJob(job)) return;
1665
- if (job.sessionId !== this.sessionId || !job.error) return;
1666
- const key = job.id + job.error;
1667
- if (!this.notices.has(key)) {
1668
- this.notices.add(key);
1669
- this.ctx.ui.notify(`cron ${job.id}: ${job.error}`, "warning");
1670
- }
1671
- this.noticeBlockedToUser(job, owners);
1672
- }
1673
- /** B plan (review round 2, P1-4): an unattended host has nobody reading
1674
- * ui.notify or the host log, so a blocked job used to fail in total
1675
- * silence — the user simply stops receiving their schedule.
1676
- *
1677
- * We ask the AGENT to tell the user, through the same input channel a job
1678
- * delivery uses. Guards, because this costs a real turn:
1679
- * - unattended hosts only (an interactive host already shows the notice);
1680
- * - blocked jobs only, and only while the job still belongs to this session;
1681
- * - once per job+ERROR (persisted `noticedError`), so a persistent block
1682
- * cannot spam;
1683
- * - bounded attempts (3) because a submission can be rejected while
1684
- * ownership is uncertain (the crash case) — we then retry on a later
1685
- * healthy poll instead of looping now;
1686
- * - only with a single registered owner, so the input interception cannot
1687
- * reject it as an ownership conflict.
1688
- * The marker is written BEFORE submitting: a rejection must never loop. */
1689
- noticeAttempts = /* @__PURE__ */ new Map();
1690
- noticeBlockedToUser(job, owners) {
1691
- if (!this.ctx.capabilities.unattended) return;
1692
- if (job.state !== "blocked" || !job.error) return;
1693
- if (job.noticedError === job.error) return;
1694
- if (owners !== 1 || !this.ctx.isIdle()) return;
1695
- const attempts = this.noticeAttempts.get(job.id) ?? 0;
1696
- if (attempts >= 3) return;
1697
- this.noticeAttempts.set(job.id, attempts + 1);
1698
- const reason = job.error;
1493
+ let child;
1494
+ let settled = false;
1495
+ let failure;
1496
+ let hostCancelled = false;
1497
+ let deadlineExceeded = false;
1498
+ let termination;
1499
+ let cleanupFailure;
1500
+ let leaderExited = false;
1501
+ let deadlineTimer;
1502
+ const ABORT_FAILURE = "worker interrupted; outcome uncertain";
1503
+ const signalGroup = (signal2) => {
1504
+ if (!child?.pid) return false;
1505
+ try {
1506
+ process.kill(-child.pid, signal2);
1507
+ return true;
1508
+ } catch (error) {
1509
+ if (error.code === "ESRCH") return false;
1510
+ throw error;
1511
+ }
1512
+ };
1513
+ const terminate = () => {
1514
+ if (settled || termination) return;
1515
+ termination = (async () => {
1516
+ if (!child?.pid) return;
1517
+ if (process.platform === "win32") {
1518
+ if (leaderExited) return;
1519
+ const pid = child.pid;
1520
+ await new Promise((resolve4, reject2) => {
1521
+ const killer = spawn("taskkill", ["/F", "/T", "/PID", String(pid)], { stdio: "ignore", windowsHide: true });
1522
+ killer.on("error", reject2);
1523
+ killer.on("close", (code) => code === 0 ? resolve4() : reject2(new Error(`taskkill exited ${code}`)));
1524
+ });
1525
+ return;
1526
+ }
1527
+ if (!signalGroup("SIGTERM")) return;
1528
+ const until = Date.now() + 5e3;
1529
+ while (Date.now() < until) {
1530
+ await new Promise((resolve4) => setTimeout(resolve4, 25));
1531
+ if (!signalGroup(0)) return;
1532
+ }
1533
+ signalGroup("SIGKILL");
1534
+ await new Promise((resolve4) => setTimeout(resolve4, 50));
1535
+ })().catch((error) => {
1536
+ cleanupFailure = error;
1537
+ });
1538
+ };
1539
+ const stop = () => {
1540
+ if (settled) return;
1541
+ hostCancelled = true;
1542
+ failure ??= ABORT_FAILURE;
1543
+ terminate();
1544
+ };
1699
1545
  try {
1700
- this.store.transaction((state) => {
1701
- const target = state.jobs.find((item) => item.id === job.id);
1702
- if (target) target.noticedError = reason;
1546
+ child = spawn(command.command[0], command.command.slice(1), {
1547
+ cwd,
1548
+ env: processJobEnv(configDir),
1549
+ stdio: ["ignore", out ?? "ignore", out ?? "ignore"],
1550
+ detached: process.platform !== "win32",
1551
+ windowsHide: true
1703
1552
  });
1704
- } catch {
1553
+ } catch (error) {
1554
+ if (out !== void 0) {
1555
+ try {
1556
+ fs4.closeSync(out);
1557
+ } catch {
1558
+ }
1559
+ }
1560
+ reject(error instanceof Error ? error : new Error(String(error)));
1705
1561
  return;
1706
1562
  }
1707
- this.auditQuiet({ kind: "noticed", jobId: job.id, sessionId: job.sessionId, cwd: job.cwd, detail: reason });
1708
- const scope = this.ctx.beginUserInput?.(() => !this.stopped && this.sessionId === job.sessionId);
1709
- if (!scope) return;
1710
- const text = `[Cron notice job=${job.id}]
1711
- A scheduled prompt is blocked: ${reason}
1712
- Tell the user in one short message and wait for their decision. Do not resume or recreate it yourself.`;
1713
- void (async () => {
1563
+ const cleanup = () => {
1564
+ if (deadlineTimer !== void 0) clearTimeout(deadlineTimer);
1565
+ signal?.removeEventListener("abort", stop);
1566
+ if (out !== void 0) {
1567
+ try {
1568
+ fs4.closeSync(out);
1569
+ } catch {
1570
+ }
1571
+ }
1572
+ };
1573
+ deadlineTimer = setTimeout(() => {
1574
+ if (settled) return;
1575
+ deadlineExceeded = true;
1576
+ failure = `process job exceeded ${deadlineMs}ms`;
1577
+ terminate();
1578
+ }, deadlineMs);
1579
+ deadlineTimer.unref();
1580
+ if (signal?.aborted) stop();
1581
+ else signal?.addEventListener("abort", stop, { once: true });
1582
+ child.on("error", (error) => {
1583
+ failure = error.message;
1584
+ });
1585
+ child.on("exit", () => {
1586
+ leaderExited = true;
1587
+ });
1588
+ child.on("close", async (code) => {
1589
+ if (settled) return;
1590
+ cleanup();
1591
+ if (!termination && process.platform !== "win32") {
1592
+ try {
1593
+ if (signalGroup(0)) {
1594
+ failure = "command left background descendants";
1595
+ terminate();
1596
+ }
1597
+ } catch (error) {
1598
+ cleanupFailure = error;
1599
+ }
1600
+ }
1601
+ await termination;
1602
+ settled = true;
1603
+ if (cleanupFailure) failure = `process cleanup failed: ${String(cleanupFailure)}`;
1604
+ const excerpt = !failure && !cleanupFailure && code !== 0 ? readProcessErrorExcerpt(logFile, logStartOffset) : void 0;
1714
1605
  try {
1715
- await scope.submit(text);
1606
+ fs4.appendFileSync(logFile, `[${(/* @__PURE__ */ new Date()).toISOString()}] job=${job.id} exit=${code}${failure ? ` error=${failure}` : ""}
1607
+ `);
1716
1608
  } catch {
1717
- } finally {
1718
- scope.dispose();
1719
1609
  }
1720
- })();
1721
- }
1722
- flushCompletions() {
1723
- for (const [id, entry] of this.completions) {
1724
- const { error, cancelled, retryable } = entry;
1725
- try {
1726
- this.store.transaction((state) => {
1727
- const job = state.jobs.find((item) => item.id === id);
1728
- if (job?.state === "running") {
1729
- settleJob(state, job, error, Date.now(), {
1730
- interrupted: cancelled === true && error !== void 0 && isProcessJob(job) && job.target === "worker",
1731
- retryable: retryable === true && error !== void 0 && isProcessJob(job) && job.target === "worker"
1732
- });
1733
- }
1734
- });
1735
- this.completions.delete(id);
1736
- } catch (failure) {
1737
- if (!isContention(failure)) this.markUnsafe();
1610
+ if (hostCancelled && !cleanupFailure) {
1611
+ reject(new ProcessWorkerCancelled(failure ?? `cancelled (exit ${code})`));
1738
1612
  return;
1739
1613
  }
1740
- }
1614
+ if (deadlineExceeded && !hostCancelled && !cleanupFailure && command.managedBy === "memory") {
1615
+ reject(new ProcessWorkerRetryable(`memory distillation exceeded ${deadlineMs}ms deadline; partial progress preserved for retry`));
1616
+ return;
1617
+ }
1618
+ if (!failure && !cleanupFailure && command.managedBy === "memory" && code === PROCESS_WORKER_RETRYABLE_EXIT_CODE) {
1619
+ reject(new ProcessWorkerRetryable(`transient memory distillation failure (exit ${code})${excerpt ? `: ${excerpt}` : ""}`));
1620
+ return;
1621
+ }
1622
+ if (failure || code !== 0) reject(new Error(failure ?? `process exited ${code}${excerpt ? `: ${excerpt}` : ""}`));
1623
+ else resolve3();
1624
+ });
1625
+ });
1626
+ }
1627
+
1628
+ // builtin/extensions/cron/runtime.ts
1629
+ var delay = (ms) => new Promise((resolve3) => setTimeout(resolve3, ms));
1630
+ var isContention = (error) => error?.code === "EEXIST";
1631
+ var COORDINATOR_OWNER_FILE = "owner.json";
1632
+ var COORDINATOR_METADATA_GRACE_MS = 5e3;
1633
+ var STORE_OWNER_SWEEP_INTERVAL_MS = 5 * 6e4;
1634
+ function defaultProcessAlive(pid) {
1635
+ try {
1636
+ process.kill(pid, 0);
1637
+ return true;
1638
+ } catch (error) {
1639
+ return error?.code !== "ESRCH";
1741
1640
  }
1742
- finish(id, error, cancelled, retryable) {
1743
- this.completions.set(id, { error, cancelled, retryable });
1744
- this.flushCompletions();
1641
+ }
1642
+ var Runtime = class {
1643
+ constructor(ctx, store, execute = runWorker, processAlive = defaultProcessAlive, executeProcess = runProcessWorker) {
1644
+ this.ctx = ctx;
1645
+ this.store = store;
1646
+ this.execute = execute;
1647
+ this.processAlive = processAlive;
1648
+ this.executeProcess = executeProcess;
1649
+ this.cwd = fs5.realpathSync(ctx.cwd);
1745
1650
  }
1746
- async poll(now = Date.now()) {
1747
- if (this.stopped || this.polling || !this.initialized) return;
1748
- if (this.pollRetryAt !== void 0 && Date.now() < this.pollRetryAt) return;
1749
- if (fs4.existsSync(path4.join(this.store.dir, "unsafe.lock"))) {
1750
- this.abort.abort();
1751
- this.processAbort.abort();
1752
- this.ctx.ui.setStatus?.("cron", void 0);
1753
- return;
1754
- }
1755
- this.polling = true;
1756
- try {
1757
- this.flushCompletions();
1758
- if (this.pollRetryAt !== void 0) {
1759
- this.pollRetryAt = void 0;
1760
- this.pollFailureBackoffMs = void 0;
1761
- }
1762
- if (this.completions.size) return;
1763
- if (!this.leader) this.withCoordinatorMutex(() => {
1764
- try {
1765
- this.acquireCoordinator();
1766
- } catch (error) {
1767
- if (!isContention(error)) throw error;
1768
- if (this.reclaimDeadCoordinator(now)) {
1769
- try {
1770
- this.acquireCoordinator();
1771
- } catch (failure) {
1772
- if (!isContention(failure)) throw failure;
1773
- }
1774
- }
1775
- }
1776
- });
1777
- let delivery, launch;
1778
- let processLaunch;
1779
- this.store.transaction((state2) => {
1780
- if (this.recovering) {
1781
- for (const job of [...state2.jobs]) {
1782
- if (job.state === "running" && (job.target === "worker" || !job.target || !state2.owners[job.target])) {
1783
- this.handleBlock(state2, job, "coordinator restarted; outcome uncertain", true);
1784
- }
1785
- }
1786
- }
1787
- state2.owners[this.id] = { sessionId: this.sessionId, cwd: this.cwd, busy: !this.ctx.isIdle() };
1788
- if (this.leader && (this.recovering || now - this.lastOwnerSweepAt >= STORE_OWNER_SWEEP_INTERVAL_MS)) {
1789
- sweepStaleOwners(state2, this.store.dir, { keepKey: this.id, now });
1790
- this.lastOwnerSweepAt = now;
1791
- }
1792
- for (const job of [...state2.jobs]) {
1793
- if (isProcessJob(job)) continue;
1794
- const owners = Object.entries(state2.owners).filter(([, owner]) => owner.sessionId === job.sessionId);
1795
- if (this.leader && job.state === "running" && job.target === "worker" && owners.length) this.abort.abort();
1796
- if (job.enabled && owners.length > 1 && job.state !== "running" && job.state !== "blocked") this.handleBlock(state2, job, "duplicate participating session owners; close duplicate and resume job", false);
1797
- if (job.state === "running" && job.target === this.id && this.accepted?.id === job.id) {
1798
- if (!this.accepted.consumed) {
1799
- for (const message of this.ctx.getMessages?.() ?? []) this.onMessage(message);
1800
- }
1801
- if (owners.length !== 1 || this.sessionId !== job.sessionId) {
1802
- this.handleBlock(state2, job, "owner changed or duplicate during delivery", !this.accepted.consumed);
1803
- this.accepted = void 0;
1804
- this.acceptedIdlePolls = 0;
1805
- } else if (this.accepted.consumed && this.accepted.busy) {
1806
- if (this.ctx.isIdle()) {
1807
- this.acceptedIdlePolls += 1;
1808
- if (this.acceptedIdlePolls >= 2) {
1809
- settleJob(state2, job, this.accepted.error);
1810
- this.accepted = void 0;
1811
- this.acceptedIdlePolls = 0;
1812
- }
1813
- } else {
1814
- this.acceptedIdlePolls = 0;
1815
- }
1816
- } else if (!this.accepted.consumed && now - this.accepted.at > 6e4) {
1817
- this.handleBlock(state2, job, "input accepted but execution not observed; inspect before resuming", true);
1818
- this.accepted = void 0;
1819
- this.acceptedIdlePolls = 0;
1820
- }
1821
- }
1822
- if (job.state === "running" && job.target === this.id && !job.deliveryStarted && this.ctx.isIdle()) {
1823
- if (owners.length !== 1 || owners[0][0] !== this.id || this.sessionId !== job.sessionId || this.cwd !== job.cwd) {
1824
- this.handleBlock(state2, job, "owner changed or duplicate; delivery blocked", false);
1825
- } else {
1826
- job.deliveryStarted = true;
1827
- delivery = { ...job };
1828
- }
1829
- }
1830
- }
1831
- if (this.leader && !state2.jobs.some((job) => job.state === "running")) {
1832
- const due = state2.jobs.filter((job) => job.enabled && job.state === "ready" && job.next !== null && job.next <= now).sort((a, b) => a.next - b.next);
1833
- for (const job of due) {
1834
- if (isProcessJob(job)) {
1835
- job.state = "running";
1836
- job.occurrence = job.next;
1837
- job.target = "worker";
1838
- processLaunch = job;
1839
- break;
1840
- }
1841
- if (state2.jobs.some((other) => other.enabled && other.sessionId === job.sessionId && other.state === "blocked")) continue;
1842
- const owners = Object.entries(state2.owners).filter(([, owner]) => owner.sessionId === job.sessionId);
1843
- if (owners.length > 1) {
1844
- complete(job, "duplicate participating session owners");
1845
- continue;
1846
- }
1847
- if (owners.length === 1 && owners[0][1].cwd !== job.cwd) {
1848
- complete(job, "owner cwd differs from bound cwd");
1849
- continue;
1850
- }
1851
- if (owners[0]?.[1].busy) continue;
1852
- job.state = "running";
1853
- job.occurrence = job.next;
1854
- job.target = owners[0]?.[0] ?? "worker";
1855
- if (job.target === "worker") launch = { ...job };
1856
- break;
1651
+ ctx;
1652
+ store;
1653
+ execute;
1654
+ processAlive;
1655
+ executeProcess;
1656
+ id = randomUUID3();
1657
+ sessionId = null;
1658
+ leader = false;
1659
+ recovering = false;
1660
+ stopped = false;
1661
+ /** Non-contention poll-failure backoff (schema-invalid state): 1s → 5min.
1662
+ * Cleared on the first successful poll after a failure. */
1663
+ pollFailureBackoffMs;
1664
+ /** Earliest wall-clock time a poll may run again after a non-contention
1665
+ * failure. The 1s interval keeps firing but poll() gates on this;
1666
+ * scheduleRecoveryPoll arms a timer AT the gate so recovery actually
1667
+ * happens — round-5 finding: the backoff value was computed but never
1668
+ * consumed, so a poisoned state logged once per second forever. */
1669
+ pollRetryAt;
1670
+ recoveryPollTimer;
1671
+ initialized = false;
1672
+ binding = 0;
1673
+ polling = false;
1674
+ timer;
1675
+ abort = new AbortController();
1676
+ processAbort = new AbortController();
1677
+ worker;
1678
+ cwd;
1679
+ notices = /* @__PURE__ */ new Set();
1680
+ completions = /* @__PURE__ */ new Map();
1681
+ accepted;
1682
+ /** P1-3b: consecutive idle observations for the current delivery. A queued
1683
+ * follow-up turn can leave a single idle gap between turns, so one idle
1684
+ * poll is not proof the delivery is over. */
1685
+ acceptedIdlePolls = 0;
1686
+ unreadableCoordinatorSince;
1687
+ coordinatorNotices = /* @__PURE__ */ new Set();
1688
+ lastOwnerSweepAt = 0;
1689
+ get ready() {
1690
+ return this.initialized && !this.stopped;
1691
+ }
1692
+ get generation() {
1693
+ return this.binding;
1694
+ }
1695
+ onStart() {
1696
+ if (this.accepted?.consumed) this.accepted.busy = true;
1697
+ }
1698
+ onMessage(message) {
1699
+ if (!this.accepted || message.role !== "user") return;
1700
+ const text = typeof message.content === "string" ? message.content : message.content.filter((block) => block.type === "text").map((block) => block.text).join("\n");
1701
+ if (text.includes(this.accepted.content)) {
1702
+ this.accepted.consumed = true;
1703
+ this.accepted.busy = true;
1704
+ }
1705
+ }
1706
+ onFailure() {
1707
+ if (this.accepted?.consumed) this.accepted.error = "interactive turn failed or cancelled; inspect before resuming";
1708
+ }
1709
+ start() {
1710
+ this.initialized = false;
1711
+ this.timer = setInterval(() => void this.poll(), 1e3);
1712
+ this.timer.unref();
1713
+ void this.ensureMemoryDistillationDefault();
1714
+ }
1715
+ /** Default daily distillation at 03:00 local. Idempotent: an existing
1716
+ * managed job keeps user pause/running reservations, while:
1717
+ * - enabled repeating `blocked` jobs auto-recover on startup (and refresh
1718
+ * stale/upgraded CLI commands) so a fixed release or config heals
1719
+ * itself without manual intervention on every machine;
1720
+ * - enabled `ready` jobs migrate their command in-place when
1721
+ * `PIE_SESSIONS_DIR` mismatches or the persisted node/CLI binary path
1722
+ * no longer exists on disk (e.g. Homebrew node upgrade). */
1723
+ async ensureMemoryDistillationDefault() {
1724
+ try {
1725
+ const storeConfigRoot = path5.dirname(this.store.dir);
1726
+ if (isManagedSubWorker(process.env, storeConfigRoot)) {
1727
+ const existingWorkerMem = this.store.findProcess("memory");
1728
+ if (existingWorkerMem && existingWorkerMem.state !== "running") {
1729
+ if (this.store.disableProcess("memory")) {
1730
+ this.ctx.log("cron: disabled legacy duplicate memory distillation job in managed sub-worker");
1857
1731
  }
1858
1732
  }
1859
- });
1860
- this.recovering = false;
1861
- if (delivery) {
1862
- const job = delivery;
1863
- const scope = this.ctx.beginUserInput?.(() => !this.stopped && this.ready && this.sessionId === job.sessionId && !fs4.existsSync(path4.join(this.store.dir, "unsafe.lock")) && Object.values(this.store.read().owners).filter((owner) => owner.sessionId === job.sessionId).length === 1);
1864
- let error;
1865
- const content = `[Cron job=${job.id} scheduledAt=${job.occurrence}]
1866
- ${job.prompt}`;
1867
- this.accepted = { id: job.id, at: now, busy: false, consumed: false, content };
1868
- this.acceptedIdlePolls = 0;
1869
- try {
1870
- if (!scope || !await scope.submit(content)) error = "input rejected or session changed; inspect before resuming";
1871
- } catch (failure) {
1872
- error = `input outcome uncertain: ${String(failure)}`;
1873
- } finally {
1874
- scope?.dispose();
1875
- }
1876
- if (error) {
1877
- this.accepted = void 0;
1878
- this.finish(job.id, error);
1879
- }
1733
+ return;
1880
1734
  }
1881
- if (launch) {
1882
- const job = launch;
1883
- const latest = this.store.read();
1884
- if (this.stopped || fs4.existsSync(path4.join(this.store.dir, "unsafe.lock")) || Object.values(latest.owners).some((owner) => owner.sessionId === job.sessionId)) {
1885
- this.finish(job.id, "ownership changed before worker launch; inspect before resuming");
1886
- return;
1735
+ try {
1736
+ const pruned = pruneWorkerManagedMemoryJobs(storeConfigRoot);
1737
+ if (pruned.pruned > 0) {
1738
+ this.ctx.log(`cron: pruned ${pruned.pruned} legacy duplicate memory distillation job(s) from pie-proc worker stores`);
1887
1739
  }
1888
- this.abort = new AbortController();
1889
- this.worker = this.execute(job, this.abort.signal, void 0, path4.dirname(this.store.dir)).then(() => this.finish(job.id), (error) => this.finish(job.id, String(error))).catch(() => {
1890
- try {
1891
- this.markUnsafe();
1892
- } catch {
1893
- }
1894
- });
1740
+ } catch {
1895
1741
  }
1896
- if (processLaunch) {
1897
- const job = processLaunch;
1898
- const command = parseProcessCommand(job);
1899
- this.processAbort = new AbortController();
1900
- this.worker = this.executeProcess(job, command, job.cwd, 30 * 60 * 1e3, this.store.dir, this.processAbort.signal, path4.dirname(this.store.dir)).then(
1901
- () => this.finish(job.id),
1902
- (error) => this.finish(
1903
- job.id,
1904
- String(error),
1905
- error?.aborted === true,
1906
- error?.retryable === true
1907
- )
1908
- ).catch(() => {
1742
+ const existing = this.store.findProcess("memory");
1743
+ if (existing) {
1744
+ const currentCmd = (() => {
1909
1745
  try {
1910
- this.markUnsafe();
1746
+ return JSON.parse(existing.prompt).command ?? [];
1911
1747
  } catch {
1748
+ return [];
1912
1749
  }
1913
- });
1914
- }
1915
- const state = this.store.read(), enabled = state.jobs.filter((job) => job.enabled);
1916
- const enabledCount = enabled.length;
1917
- const blockedCount = enabled.filter((job) => job.state === "blocked").length;
1918
- this.ctx.ui.setStatus?.("cron", this.leader && enabledCount > 0 && enabled.some((job) => job.sessionId === this.sessionId || isProcessJob(job)) ? blockedCount > 0 ? `[CRON.${enabledCount}.${blockedCount}]` : `[CRON.${enabledCount}]` : void 0);
1919
- for (const job of state.jobs) {
1920
- this.notify(job, Object.values(state.owners).filter((owner) => owner.sessionId === job.sessionId).length);
1750
+ })();
1751
+ const desiredCmd = managedMemoryCommand();
1752
+ const isManagedDistillCmd = currentCmd.includes("memory") && currentCmd.includes("distill");
1753
+ const hasMissingBinaryOrEntry = (() => {
1754
+ if (!isManagedDistillCmd) return false;
1755
+ const bin = currentCmd[0];
1756
+ if (bin && path5.isAbsolute(bin) && !fs5.existsSync(bin)) return true;
1757
+ const memIdx = currentCmd.indexOf("memory");
1758
+ const entry = memIdx >= 2 ? currentCmd[memIdx - 1] : void 0;
1759
+ if (entry && path5.isAbsolute(entry) && !fs5.existsSync(entry)) return true;
1760
+ return false;
1761
+ })();
1762
+ const isBundledCli = (() => {
1763
+ const hasLoader = desiredCmd.some((arg) => /^--(?:import|loader|experimental-loader)(?:=|$)/.test(arg));
1764
+ if (hasLoader) return false;
1765
+ const memIdx = desiredCmd.indexOf("memory");
1766
+ const entry = memIdx >= 2 ? desiredCmd[memIdx - 1] : void 0;
1767
+ return Boolean(entry && /(?:^|[\\/])cli\.js$/i.test(entry) && fs5.existsSync(entry));
1768
+ })();
1769
+ const sessionsDirMismatch = (() => {
1770
+ if (!process.env.PIE_SESSIONS_DIR || !desiredCmd.includes("--sessions-dir")) return false;
1771
+ const curIdx = currentCmd.indexOf("--sessions-dir");
1772
+ const wantIdx = desiredCmd.indexOf("--sessions-dir");
1773
+ const curDir = curIdx >= 0 ? currentCmd[curIdx + 1] : void 0;
1774
+ const wantDir = wantIdx >= 0 ? desiredCmd[wantIdx + 1] : void 0;
1775
+ return curDir !== wantDir ? wantDir : false;
1776
+ })();
1777
+ if (existing.enabled && existing.state === "blocked") {
1778
+ const shouldRefreshCmd = isManagedDistillCmd && (hasMissingBinaryOrEntry || Boolean(sessionsDirMismatch) || isBundledCli && (currentCmd.length !== desiredCmd.length || currentCmd.some((v, i) => v !== desiredCmd[i])));
1779
+ const rec = this.store.recoverBlockedProcess("memory", {
1780
+ ...shouldRefreshCmd ? { command: desiredCmd } : {}
1781
+ });
1782
+ if (rec.recovered) {
1783
+ this.ctx.log(
1784
+ `cron: auto-recovered blocked managed memory distillation job (was: ${rec.previousError ?? "unknown"}; next ${rec.next !== void 0 ? new Date(rec.next).toISOString() : "none"}${rec.commandUpdated ? "; refreshed command" : ""})`
1785
+ );
1786
+ }
1787
+ return;
1788
+ }
1789
+ if (sessionsDirMismatch || hasMissingBinaryOrEntry) {
1790
+ const outcome = this.store.syncProcessCommand("memory", desiredCmd);
1791
+ if (outcome === "updated") {
1792
+ const reason = sessionsDirMismatch ? `pin --sessions-dir ${sessionsDirMismatch}` : "repair missing node/CLI executable path";
1793
+ this.ctx.log(`cron: migrated managed memory distillation command to ${reason}`);
1794
+ } else if (outcome === "deferred" && sessionsDirMismatch) {
1795
+ this.ctx.log(`cron: managed memory distillation job needs repair to pin --sessions-dir ${sessionsDirMismatch} (currently ${existing.state === "running" ? "running" : !existing.enabled ? "paused" : existing.state}; run 'pie memory schedule on' when ready)`);
1796
+ }
1797
+ }
1798
+ return;
1921
1799
  }
1800
+ await new Promise((resolve3) => setImmediate(resolve3));
1801
+ const command = managedMemoryCommand();
1802
+ const cronSpec = localTimeToCronUtc("03:00");
1803
+ if ("error" in cronSpec) throw new Error(cronSpec.error);
1804
+ if (this.store.ensureProcess(command, "memory", process.cwd(), cronSpec))
1805
+ this.ctx.log("cron: registered the default daily memory distillation (03:00)");
1922
1806
  } catch (error) {
1923
- if (isContention(error)) {
1924
- this.ctx.ui.setStatus?.("cron", void 0);
1925
- return;
1926
- }
1927
- this.pollFailureBackoffMs = Math.min((this.pollFailureBackoffMs ?? 1e3) * 2, 3e5);
1928
- this.pollRetryAt = Date.now() + this.pollFailureBackoffMs;
1929
- this.ctx.log?.(`cron: poll failed (${String(error instanceof Error ? error.message : error).slice(0, 200)}); backing off ${Math.round(this.pollFailureBackoffMs / 1e3)}s. If this persists, the state file is invalid \u2014 recover via /tools/cron or repair the file offline.`);
1930
- this.ctx.ui.setStatus?.("cron", "[CRON!]");
1931
- this.scheduleRecoveryPoll();
1932
- } finally {
1933
- this.polling = false;
1807
+ const message = String(error instanceof Error ? error.message : error);
1808
+ if (/managed job is (blocked|paused|currently running)/.test(message)) return;
1809
+ this.ctx.log(`cron: default memory distillation registration failed: ${message}`);
1934
1810
  }
1935
1811
  }
1936
- /** One-shot delayed poll after a non-contention failure (schema-invalid
1937
- * state): replaces the silent once-per-second retry loop with a backed-off
1938
- * recovery attempt; the regular timer keeps running for healthy states. */
1939
- scheduleRecoveryPoll() {
1940
- if (this.stopped || this.recoveryPollTimer !== void 0) return;
1941
- const delay2 = this.pollFailureBackoffMs ?? 1e3;
1942
- this.recoveryPollTimer = setTimeout(() => {
1943
- this.recoveryPollTimer = void 0;
1944
- void this.poll().catch(() => {
1945
- });
1946
- }, delay2);
1947
- this.recoveryPollTimer.unref();
1812
+ markUnsafe() {
1813
+ fs5.mkdirSync(path5.join(this.store.dir, "unsafe.lock"), { recursive: true, mode: 448 });
1948
1814
  }
1949
- async stop() {
1950
- this.stopped = true;
1951
- clearInterval(this.timer);
1952
- if (this.recoveryPollTimer !== void 0) clearTimeout(this.recoveryPollTimer);
1953
- this.abort.abort();
1954
- this.processAbort.abort();
1955
- await this.worker;
1956
- while (this.polling) await delay(10);
1957
- const shutdownDeadline = Date.now() + 1e4;
1958
- const budgetLeft = () => Date.now() < shutdownDeadline;
1959
- for (let attempt = 0; ; attempt++) {
1960
- if (attempt > 0 && !budgetLeft()) {
1961
- this.noteShutdownDegradation("cron: shutdown budget expired before the final state transaction completed; session ownership may be stale. If input stays blocked, run /tools/cron list and remove the stale owner row.");
1962
- break;
1815
+ coordinatorDir() {
1816
+ return path5.join(this.store.dir, "scheduler.lock");
1817
+ }
1818
+ coordinatorOwnerFile() {
1819
+ return path5.join(this.coordinatorDir(), COORDINATOR_OWNER_FILE);
1820
+ }
1821
+ readCoordinatorOwner() {
1822
+ try {
1823
+ const file = this.coordinatorOwnerFile(), stat = fs5.lstatSync(file);
1824
+ if (!stat.isFile() || stat.size > 4096) return void 0;
1825
+ const raw = fs5.readFileSync(file, "utf8"), value = JSON.parse(raw);
1826
+ if (value?.version !== 1 || !Number.isSafeInteger(value.pid) || value.pid <= 0 || typeof value.instanceId !== "string" || !value.instanceId || value.instanceId.length > 128 || !Number.isSafeInteger(value.createdAt)) return void 0;
1827
+ return { value, raw };
1828
+ } catch {
1829
+ return void 0;
1830
+ }
1831
+ }
1832
+ noteCoordinatorMetadata(valid, now) {
1833
+ if (valid) {
1834
+ this.unreadableCoordinatorSince = void 0;
1835
+ return;
1836
+ }
1837
+ if (this.unreadableCoordinatorSince === void 0) {
1838
+ this.unreadableCoordinatorSince = now;
1839
+ return;
1840
+ }
1841
+ if (this.coordinatorNotices.has("metadata") || now - this.unreadableCoordinatorSince < COORDINATOR_METADATA_GRACE_MS) return;
1842
+ this.coordinatorNotices.add("metadata");
1843
+ this.ctx.ui.notify("cron: coordinator lock metadata is missing or invalid; scheduling is paused. See docs/cron.md offline recovery.", "warning");
1844
+ }
1845
+ withCoordinatorMutex(fn) {
1846
+ return this.store.withWriteLock(() => fn());
1847
+ }
1848
+ acquireCoordinator() {
1849
+ const dir = this.coordinatorDir();
1850
+ fs5.mkdirSync(dir, { mode: 448 });
1851
+ const owner = { version: 1, pid: process.pid, instanceId: this.id, createdAt: Date.now() };
1852
+ try {
1853
+ fs5.writeFileSync(this.coordinatorOwnerFile(), JSON.stringify(owner), { mode: 384, flag: "wx" });
1854
+ } catch (error) {
1855
+ try {
1856
+ fs5.unlinkSync(this.coordinatorOwnerFile());
1857
+ } catch {
1963
1858
  }
1964
1859
  try {
1965
- this.store.transaction((state) => {
1966
- for (const [id, entry] of this.completions) {
1967
- const job = state.jobs.find((item) => item.id === id);
1968
- if (job?.state === "running") {
1969
- settleJob(state, job, entry.error, Date.now(), {
1970
- interrupted: entry.cancelled === true && entry.error !== void 0 && isProcessJob(job) && job.target === "worker",
1971
- retryable: entry.retryable === true && entry.error !== void 0 && isProcessJob(job) && job.target === "worker"
1972
- });
1973
- }
1974
- }
1975
- delete state.owners[this.id];
1976
- for (const job of [...state.jobs]) {
1977
- if (job.state === "running" && job.target === this.id) {
1978
- settleJob(state, job, "owner closed before delivery; inspect before resuming");
1979
- }
1980
- }
1981
- });
1982
- try {
1983
- fs4.rmSync(path4.join(this.store.dir, "owners-liveness", `${this.id}.json`), { force: true });
1984
- } catch {
1985
- }
1986
- this.completions.clear();
1987
- break;
1988
- } catch (error) {
1989
- if (isContention(error) && attempt < 39 && budgetLeft()) {
1990
- await delay(25 + Math.floor(Math.random() * 25));
1991
- continue;
1992
- }
1993
- this.noteShutdownDegradation(`cron: exit left session ownership uncommitted (${String(error)}). If input stays blocked, run /tools/cron list and remove the stale owner row.`);
1994
- break;
1860
+ fs5.rmdirSync(dir);
1861
+ } catch {
1995
1862
  }
1863
+ throw error;
1996
1864
  }
1997
- if (this.leader) {
1998
- for (let attempt = 0; ; attempt++) {
1999
- if (!budgetLeft()) {
2000
- this.noteShutdownDegradation("cron: shutdown budget expired before the coordinator lock was released; scheduling pauses until it is reclaimed; see docs/cron.md.");
2001
- break;
2002
- }
2003
- try {
2004
- this.withCoordinatorMutex(() => this.releaseCoordinator());
2005
- break;
2006
- } catch (error) {
2007
- if (isContention(error) && attempt < 39 && budgetLeft()) {
2008
- await delay(25 + Math.floor(Math.random() * 25));
2009
- continue;
2010
- }
2011
- this.noteShutdownDegradation(`cron: coordinator lock not released (${String(error)}). Scheduling pauses until it is reclaimed; see docs/cron.md.`);
2012
- break;
2013
- }
1865
+ this.leader = true;
1866
+ this.recovering = true;
1867
+ this.noteCoordinatorMetadata(true, Date.now());
1868
+ }
1869
+ reclaimDeadCoordinator(now) {
1870
+ const held = this.readCoordinatorOwner();
1871
+ if (!held) {
1872
+ this.noteCoordinatorMetadata(false, now);
1873
+ return false;
1874
+ }
1875
+ this.noteCoordinatorMetadata(true, now);
1876
+ if (this.processAlive(held.value.pid)) return false;
1877
+ if (this.store.read().jobs.some((job) => job.state === "running")) {
1878
+ const key = `running:${held.value.instanceId}`;
1879
+ if (!this.coordinatorNotices.has(key)) {
1880
+ this.coordinatorNotices.add(key);
1881
+ this.ctx.ui.notify("cron: dead coordinator has running work; scheduling remains paused for offline recovery.", "warning");
2014
1882
  }
1883
+ return false;
2015
1884
  }
2016
- this.ctx.ui.setStatus?.("cron", void 0);
2017
- }
2018
- /** Surface a best-effort shutdown degradation. Never throws: diagnostics
2019
- * must not turn a contained skip into a failed exit. */
2020
- noteShutdownDegradation(message) {
1885
+ const latest = this.readCoordinatorOwner();
1886
+ if (!latest || latest.raw !== held.raw) return false;
2021
1887
  try {
2022
- this.ctx.log?.(message);
1888
+ fs5.unlinkSync(this.coordinatorOwnerFile());
1889
+ fs5.rmdirSync(this.coordinatorDir());
1890
+ return true;
2023
1891
  } catch {
1892
+ return false;
2024
1893
  }
1894
+ }
1895
+ releaseCoordinator() {
1896
+ fs5.rmSync(this.coordinatorOwnerFile(), { force: true });
1897
+ fs5.rmdirSync(this.coordinatorDir());
1898
+ this.leader = false;
1899
+ }
1900
+ persistOwner(sessionId) {
1901
+ this.store.transaction((state) => {
1902
+ sweepStaleOwners(state, this.store.dir, { sessionId, keepKey: this.id, warn: (message) => this.ctx.log(message) });
1903
+ state.owners[this.id] = { sessionId, cwd: this.cwd, busy: !this.ctx.isIdle(), registeredAt: Date.now() };
1904
+ });
2025
1905
  try {
2026
- this.ctx.ui.notify?.(message, "warning");
1906
+ const livenessDir = path5.join(this.store.dir, "owners-liveness");
1907
+ fs5.mkdirSync(livenessDir, { recursive: true });
1908
+ const liveness = path5.join(livenessDir, `${this.id}.json`);
1909
+ try {
1910
+ fs5.unlinkSync(liveness);
1911
+ } catch {
1912
+ }
1913
+ fs5.writeFileSync(liveness, JSON.stringify({ pid: process.pid, at: Date.now() }), { mode: 384 });
2027
1914
  } catch {
2028
1915
  }
1916
+ this.sessionId = sessionId;
1917
+ this.initialized = true;
2029
1918
  }
2030
- };
2031
-
2032
- // builtin/extensions/cron/panel-bridge.ts
2033
- import * as fs5 from "node:fs";
2034
- import * as path5 from "node:path";
2035
- var SAFE_WORKER_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,47}$/;
2036
- var SAFE_JOB_ID = /^[A-Za-z0-9-]{8,64}$/;
2037
- function isContainedNonSymlink(rootDir, targetPath, kind) {
2038
- try {
2039
- if (!fs5.existsSync(rootDir) || !fs5.existsSync(targetPath)) return false;
2040
- const st = fs5.lstatSync(targetPath);
2041
- if (st.isSymbolicLink()) return false;
2042
- if (kind === "dir" ? !st.isDirectory() : !st.isFile()) return false;
2043
- const canonicalRoot = fs5.realpathSync(rootDir);
2044
- const canonicalTarget = fs5.realpathSync(targetPath);
2045
- const rel = path5.relative(canonicalRoot, canonicalTarget);
2046
- return Boolean(rel && !rel.startsWith("..") && !path5.isAbsolute(rel));
2047
- } catch {
2048
- return false;
1919
+ register(sessionId) {
1920
+ try {
1921
+ this.persistOwner(sessionId);
1922
+ } catch (error) {
1923
+ this.markUnsafe();
1924
+ throw error;
1925
+ }
2049
1926
  }
2050
- }
2051
- function formatEverySeconds(seconds) {
2052
- if (seconds % 86400 === 0) return `${seconds / 86400}d`;
2053
- if (seconds % 3600 === 0) return `${seconds / 3600}h`;
2054
- if (seconds % 60 === 0) return `${seconds / 60}m`;
2055
- return `${seconds}s`;
2056
- }
2057
- function summarizeSchedule(schedule) {
2058
- if ("at" in schedule) {
2059
- return { kind: "at", text: `at ${schedule.at}` };
1927
+ async bind(sessionId) {
1928
+ const generation = ++this.binding;
1929
+ this.initialized = false;
1930
+ for (let attempt = 0; attempt < 20; attempt++) {
1931
+ if (this.stopped || generation !== this.binding) return;
1932
+ try {
1933
+ this.persistOwner(sessionId);
1934
+ return;
1935
+ } catch (error) {
1936
+ if (!isContention(error)) break;
1937
+ await delay(25 + Math.floor(Math.random() * 25));
1938
+ }
1939
+ }
1940
+ if (!this.stopped && generation === this.binding) this.register(sessionId);
2060
1941
  }
2061
- if ("every" in schedule) {
2062
- return {
2063
- kind: "every",
2064
- text: `every ${formatEverySeconds(schedule.every)}`,
2065
- ...schedule.count !== void 0 ? { count: schedule.count } : {}
2066
- };
1942
+ /** Best-effort durable audit: scheduling must never stop because the audit
1943
+ * file is unwritable — the state file remains the source of truth. */
1944
+ auditQuiet(record) {
1945
+ try {
1946
+ this.store.audit(record);
1947
+ } catch {
1948
+ }
2067
1949
  }
2068
- return {
2069
- kind: "cron",
2070
- text: `cron ${schedule.cron}`,
2071
- ...schedule.count !== void 0 ? { count: schedule.count } : {}
2072
- };
2073
- }
2074
- function toJobView(job, storeKey, storeOwnerLabel) {
2075
- const processCmd = parseProcessCommand(job);
2076
- const isProc = isProcessJob(job);
2077
- const managedBy = processCmd?.managedBy;
2078
- const summary = managedBy ? managedBy : isProc ? processCmd?.command.slice(0, 3).join(" ") ?? "process" : job.prompt.replace(/\s+/g, " ").trim().slice(0, 80);
2079
- const ownerLabel = storeOwnerLabel ?? (isProc ? "system" : void 0);
2080
- return {
2081
- id: job.id,
2082
- storeKey,
2083
- ...ownerLabel ? { ownerLabel } : {},
2084
- sessionId: job.sessionId,
2085
- cwd: job.cwd,
2086
- isProcess: isProc,
2087
- ...managedBy ? { managedBy } : {},
2088
- summary,
2089
- schedule: summarizeSchedule(job.schedule),
2090
- enabled: job.enabled,
2091
- state: job.state,
2092
- next: job.next,
2093
- ...job.remaining !== void 0 ? { remaining: job.remaining } : {},
2094
- ...job.pendingAction ? { pendingAction: job.pendingAction } : {},
2095
- ...typeof job.error === "string" && job.error ? { error: job.error.slice(0, 200) } : {}
2096
- };
2097
- }
2098
- function stateSortRank(job) {
2099
- if (job.state === "running") return 0;
2100
- if (job.state === "blocked") return 1;
2101
- if (job.enabled) return 2;
2102
- return 3;
2103
- }
2104
- function sortJobs(jobs) {
2105
- return jobs.sort((a, b) => {
2106
- if (a.isProcess !== b.isProcess) return a.isProcess ? 1 : -1;
2107
- const rankDiff = stateSortRank(a) - stateSortRank(b);
2108
- if (rankDiff !== 0) return rankDiff;
2109
- const aNext = a.next ?? Number.MAX_SAFE_INTEGER;
2110
- const bNext = b.next ?? Number.MAX_SAFE_INTEGER;
2111
- if (aNext !== bNext) return aNext - bNext;
2112
- return a.id.localeCompare(b.id);
2113
- });
2114
- }
2115
- function pinContainedDir(parentDir, targetDir) {
2116
- if (!isContainedNonSymlink(parentDir, targetDir, "dir")) return void 0;
2117
- try {
2118
- const st = fs5.lstatSync(targetDir, { bigint: true });
2119
- if (st.isSymbolicLink() || !st.isDirectory()) return void 0;
2120
- return { path: targetDir, dev: st.dev, ino: st.ino };
2121
- } catch {
2122
- return void 0;
2123
- }
2124
- }
2125
- function assertPinnedChain(configRoot, chain) {
2126
- let parent = configRoot;
2127
- for (const node of chain) {
2128
- if (!isContainedNonSymlink(parent, node.path, "dir")) {
2129
- throw new Error("worker cron store containment check failed");
1950
+ /** Block a job with LAYERED handling (review round 2, P1-4).
1951
+ *
1952
+ * One blocked job freezes the whole session's schedule set, so blocking is
1953
+ * expensive. `executed` separates the two cases that used to be conflated:
1954
+ *
1955
+ * - false: the occurrence provably never ran (duplicate owner, owner
1956
+ * changed before delivery). Retrying is safe, so a repeating prompt job
1957
+ * is rescheduled ONCE automatically (`retriedOnce`) instead of freezing
1958
+ * the session until a human notices. Mirrors completeInterrupted's
1959
+ * precedent, and does NOT consume a count-capped execution because
1960
+ * nothing executed.
1961
+ * - true: the occurrence may already have produced side effects. Keep the
1962
+ * conservative block; only a human can decide (double execution is worse
1963
+ * than a stalled schedule).
1964
+ */
1965
+ handleBlock(state, job, error, executed) {
1966
+ const pending = job.pendingAction;
1967
+ delete job.pendingAction;
1968
+ if (pending === "remove") {
1969
+ state.jobs = state.jobs.filter((item) => item !== job);
1970
+ return;
2130
1971
  }
2131
- const st = fs5.lstatSync(node.path, { bigint: true });
2132
- if (st.isSymbolicLink() || !st.isDirectory() || st.dev !== node.dev || st.ino !== node.ino) {
2133
- throw new Error("worker cron store directory identity changed");
1972
+ if (job.state === "blocked" && job.error === error && !pending) {
1973
+ return;
2134
1974
  }
2135
- parent = node.path;
1975
+ const repeating = !("at" in job.schedule);
1976
+ if (!executed && repeating && !isProcessJob(job) && !job.retriedOnce) {
1977
+ job.retriedOnce = true;
1978
+ job.state = "ready";
1979
+ delete job.target;
1980
+ delete job.deliveryStarted;
1981
+ job.next = nextTime(job.schedule, Math.max(Date.now(), job.occurrence ?? Date.now()));
1982
+ if (job.next === null || pending === "pause") job.enabled = false;
1983
+ job.error = `retried automatically after a block that never executed: ${error}`.slice(0, 500);
1984
+ this.auditQuiet({ kind: "auto-retry", jobId: job.id, sessionId: job.sessionId, cwd: job.cwd, detail: error });
1985
+ return;
1986
+ }
1987
+ complete(job, error);
1988
+ if (pending === "pause") job.enabled = false;
1989
+ this.auditQuiet({ kind: "blocked", jobId: job.id, sessionId: job.sessionId, cwd: job.cwd, detail: error });
2136
1990
  }
2137
- }
2138
- function resolveVerifiedAgentsDir(configRoot) {
2139
- const pieProcDir = path5.join(configRoot, "pie-proc");
2140
- const pinnedPieProc = pinContainedDir(configRoot, pieProcDir);
2141
- if (!pinnedPieProc) return void 0;
2142
- const agentsDir = path5.join(pieProcDir, "agents");
2143
- const pinnedAgents = pinContainedDir(pieProcDir, agentsDir);
2144
- if (!pinnedAgents) return void 0;
2145
- return { agentsDir, prefixChain: [pinnedPieProc, pinnedAgents] };
2146
- }
2147
- function resolveVerifiedWorkerStore(configRoot, resolvedAgents, name) {
2148
- if (!SAFE_WORKER_NAME.test(name)) return void 0;
2149
- const agentDir = path5.join(resolvedAgents.agentsDir, name);
2150
- const pinnedAgent = pinContainedDir(resolvedAgents.agentsDir, agentDir);
2151
- if (!pinnedAgent) return void 0;
2152
- const cronDir = path5.join(agentDir, "cron");
2153
- const pinnedCron = pinContainedDir(agentDir, cronDir);
2154
- if (!pinnedCron) return void 0;
2155
- const stateFile = path5.join(cronDir, "state.json");
2156
- if (!isContainedNonSymlink(cronDir, stateFile, "file")) return void 0;
2157
- const fullChain = [...resolvedAgents.prefixChain, pinnedAgent, pinnedCron];
2158
- return {
2159
- storeKey: `worker:${name}`,
2160
- ownerLabel: name,
2161
- store: new Store(cronDir, {
2162
- createDir: false,
2163
- verifyDir: () => assertPinnedChain(configRoot, fullChain)
2164
- })
2165
- };
2166
- }
2167
- function enumerateVerifiedStores(primaryStore, configRoot) {
2168
- const stores = [{ storeKey: "host", store: primaryStore }];
2169
- const resolvedAgents = resolveVerifiedAgentsDir(configRoot);
2170
- if (!resolvedAgents) return stores;
2171
- let entries;
2172
- try {
2173
- entries = fs5.readdirSync(resolvedAgents.agentsDir).sort();
2174
- } catch {
2175
- return stores;
1991
+ notify(job, owners) {
1992
+ if (isProcessJob(job)) return;
1993
+ if (job.sessionId !== this.sessionId || !job.error) return;
1994
+ const key = job.id + job.error;
1995
+ if (!this.notices.has(key)) {
1996
+ this.notices.add(key);
1997
+ this.ctx.ui.notify(`cron ${job.id}: ${job.error}`, "warning");
1998
+ }
1999
+ this.noticeBlockedToUser(job, owners);
2176
2000
  }
2177
- for (const name of entries) {
2178
- const verified = resolveVerifiedWorkerStore(configRoot, resolvedAgents, name);
2179
- if (verified) stores.push(verified);
2001
+ /** B plan (review round 2, P1-4): an unattended host has nobody reading
2002
+ * ui.notify or the host log, so a blocked job used to fail in total
2003
+ * silence — the user simply stops receiving their schedule.
2004
+ *
2005
+ * We ask the AGENT to tell the user, through the same input channel a job
2006
+ * delivery uses. Guards, because this costs a real turn:
2007
+ * - unattended hosts only (an interactive host already shows the notice);
2008
+ * - blocked jobs only, and only while the job still belongs to this session;
2009
+ * - once per job+ERROR (persisted `noticedError`), so a persistent block
2010
+ * cannot spam;
2011
+ * - bounded attempts (3) because a submission can be rejected while
2012
+ * ownership is uncertain (the crash case) — we then retry on a later
2013
+ * healthy poll instead of looping now;
2014
+ * - only with a single registered owner, so the input interception cannot
2015
+ * reject it as an ownership conflict.
2016
+ * The marker is written BEFORE submitting: a rejection must never loop. */
2017
+ noticeAttempts = /* @__PURE__ */ new Map();
2018
+ noticeBlockedToUser(job, owners) {
2019
+ if (!this.ctx.capabilities.unattended) return;
2020
+ if (job.state !== "blocked" || !job.error) return;
2021
+ if (job.noticedError === job.error) return;
2022
+ if (owners !== 1 || !this.ctx.isIdle()) return;
2023
+ const attempts = this.noticeAttempts.get(job.id) ?? 0;
2024
+ if (attempts >= 3) return;
2025
+ this.noticeAttempts.set(job.id, attempts + 1);
2026
+ const reason = job.error;
2027
+ try {
2028
+ this.store.transaction((state) => {
2029
+ const target = state.jobs.find((item) => item.id === job.id);
2030
+ if (target) target.noticedError = reason;
2031
+ });
2032
+ } catch {
2033
+ return;
2034
+ }
2035
+ this.auditQuiet({ kind: "noticed", jobId: job.id, sessionId: job.sessionId, cwd: job.cwd, detail: reason });
2036
+ const scope = this.ctx.beginUserInput?.(() => !this.stopped && this.sessionId === job.sessionId);
2037
+ if (!scope) return;
2038
+ const text = `[Cron notice job=${job.id}]
2039
+ A scheduled prompt is blocked: ${reason}
2040
+ Tell the user in one short message and wait for their decision. Do not resume or recreate it yourself.`;
2041
+ void (async () => {
2042
+ try {
2043
+ await scope.submit(text);
2044
+ } catch {
2045
+ } finally {
2046
+ scope.dispose();
2047
+ }
2048
+ })();
2180
2049
  }
2181
- return stores;
2182
- }
2183
- function resolveStoresForKey(primaryStore, configRoot, storeKey) {
2184
- if (!storeKey) return enumerateVerifiedStores(primaryStore, configRoot);
2185
- if (storeKey === "host") return [{ storeKey: "host", store: primaryStore }];
2186
- if (storeKey.startsWith("worker:")) {
2187
- const resolvedAgents = resolveVerifiedAgentsDir(configRoot);
2188
- if (!resolvedAgents) return [];
2189
- const verified = resolveVerifiedWorkerStore(configRoot, resolvedAgents, storeKey.slice("worker:".length));
2190
- return verified ? [verified] : [];
2050
+ flushCompletions() {
2051
+ for (const [id, entry] of this.completions) {
2052
+ const { error, cancelled, retryable } = entry;
2053
+ try {
2054
+ this.store.transaction((state) => {
2055
+ const job = state.jobs.find((item) => item.id === id);
2056
+ if (job?.state === "running") {
2057
+ settleJob(state, job, error, Date.now(), {
2058
+ interrupted: cancelled === true && error !== void 0 && isProcessJob(job) && job.target === "worker",
2059
+ retryable: retryable === true && error !== void 0 && isProcessJob(job) && job.target === "worker"
2060
+ });
2061
+ }
2062
+ });
2063
+ this.completions.delete(id);
2064
+ } catch (failure) {
2065
+ if (!isContention(failure)) this.markUnsafe();
2066
+ return;
2067
+ }
2068
+ }
2191
2069
  }
2192
- return [];
2193
- }
2194
- function createCronPanelBridge(params) {
2195
- const { primaryStore, configRoot, getAuthorization, getStartupError } = params;
2196
- return {
2197
- listJobs(opts) {
2198
- const stores = enumerateVerifiedStores(primaryStore, configRoot);
2199
- const jobs = [];
2200
- const warnings = [];
2201
- let hostJobMatched = false;
2202
- for (const entry of stores) {
2070
+ finish(id, error, cancelled, retryable) {
2071
+ this.completions.set(id, { error, cancelled, retryable });
2072
+ this.flushCompletions();
2073
+ }
2074
+ async poll(now = Date.now()) {
2075
+ if (this.stopped || this.polling || !this.initialized) return;
2076
+ if (this.pollRetryAt !== void 0 && Date.now() < this.pollRetryAt) return;
2077
+ if (fs5.existsSync(path5.join(this.store.dir, "unsafe.lock"))) {
2078
+ this.abort.abort();
2079
+ this.processAbort.abort();
2080
+ this.ctx.ui.setStatus?.("cron", void 0);
2081
+ return;
2082
+ }
2083
+ this.polling = true;
2084
+ try {
2085
+ this.flushCompletions();
2086
+ if (this.pollRetryAt !== void 0) {
2087
+ this.pollRetryAt = void 0;
2088
+ this.pollFailureBackoffMs = void 0;
2089
+ }
2090
+ if (this.completions.size) return;
2091
+ if (!this.leader) this.withCoordinatorMutex(() => {
2203
2092
  try {
2204
- const state = entry.store.read();
2205
- let invalidIdCount = 0;
2206
- for (const job of state.jobs) {
2207
- if (opts?.sessionId && job.sessionId !== opts.sessionId) continue;
2208
- if (!SAFE_JOB_ID.test(job.id)) {
2209
- invalidIdCount++;
2210
- continue;
2093
+ this.acquireCoordinator();
2094
+ } catch (error) {
2095
+ if (!isContention(error)) throw error;
2096
+ if (this.reclaimDeadCoordinator(now)) {
2097
+ try {
2098
+ this.acquireCoordinator();
2099
+ } catch (failure) {
2100
+ if (!isContention(failure)) throw failure;
2101
+ }
2102
+ }
2103
+ }
2104
+ });
2105
+ let delivery, launch;
2106
+ let processLaunch;
2107
+ this.store.transaction((state2) => {
2108
+ if (this.recovering) {
2109
+ for (const job of [...state2.jobs]) {
2110
+ if (job.state === "running" && (job.target === "worker" || !job.target || !state2.owners[job.target])) {
2111
+ this.handleBlock(state2, job, "coordinator restarted; outcome uncertain", true);
2112
+ }
2113
+ }
2114
+ }
2115
+ state2.owners[this.id] = { sessionId: this.sessionId, cwd: this.cwd, busy: !this.ctx.isIdle() };
2116
+ if (this.leader && (this.recovering || now - this.lastOwnerSweepAt >= STORE_OWNER_SWEEP_INTERVAL_MS)) {
2117
+ sweepStaleOwners(state2, this.store.dir, { keepKey: this.id, now });
2118
+ this.lastOwnerSweepAt = now;
2119
+ }
2120
+ for (const job of [...state2.jobs]) {
2121
+ if (isProcessJob(job)) continue;
2122
+ const owners = Object.entries(state2.owners).filter(([, owner]) => owner.sessionId === job.sessionId);
2123
+ if (this.leader && job.state === "running" && job.target === "worker" && owners.length) this.abort.abort();
2124
+ if (job.enabled && owners.length > 1 && job.state !== "running" && job.state !== "blocked") this.handleBlock(state2, job, "duplicate participating session owners; close duplicate and resume job", false);
2125
+ if (job.state === "running" && job.target === this.id && this.accepted?.id === job.id) {
2126
+ if (!this.accepted.consumed) {
2127
+ for (const message of this.ctx.getMessages?.() ?? []) this.onMessage(message);
2128
+ }
2129
+ if (owners.length !== 1 || this.sessionId !== job.sessionId) {
2130
+ this.handleBlock(state2, job, "owner changed or duplicate during delivery", !this.accepted.consumed);
2131
+ this.accepted = void 0;
2132
+ this.acceptedIdlePolls = 0;
2133
+ } else if (this.accepted.consumed && this.accepted.busy) {
2134
+ if (this.ctx.isIdle()) {
2135
+ this.acceptedIdlePolls += 1;
2136
+ if (this.acceptedIdlePolls >= 2) {
2137
+ settleJob(state2, job, this.accepted.error);
2138
+ this.accepted = void 0;
2139
+ this.acceptedIdlePolls = 0;
2140
+ }
2141
+ } else {
2142
+ this.acceptedIdlePolls = 0;
2143
+ }
2144
+ } else if (!this.accepted.consumed && now - this.accepted.at > 6e4) {
2145
+ this.handleBlock(state2, job, "input accepted but execution not observed; inspect before resuming", true);
2146
+ this.accepted = void 0;
2147
+ this.acceptedIdlePolls = 0;
2148
+ }
2149
+ }
2150
+ if (job.state === "running" && job.target === this.id && !job.deliveryStarted && this.ctx.isIdle()) {
2151
+ if (owners.length !== 1 || owners[0][0] !== this.id || this.sessionId !== job.sessionId || this.cwd !== job.cwd) {
2152
+ this.handleBlock(state2, job, "owner changed or duplicate; delivery blocked", false);
2153
+ } else {
2154
+ job.deliveryStarted = true;
2155
+ delivery = { ...job };
2211
2156
  }
2212
- if (entry.storeKey === "host") hostJobMatched = true;
2213
- jobs.push(toJobView(job, entry.storeKey, entry.ownerLabel));
2214
2157
  }
2215
- if (invalidIdCount > 0) {
2216
- warnings.push(`${entry.storeKey}: skipped ${invalidIdCount} job(s) with invalid id`);
2158
+ }
2159
+ if (this.leader && !state2.jobs.some((job) => job.state === "running")) {
2160
+ const due = state2.jobs.filter((job) => job.enabled && job.state === "ready" && job.next !== null && job.next <= now).sort((a, b) => a.next - b.next);
2161
+ for (const job of due) {
2162
+ if (isProcessJob(job)) {
2163
+ job.state = "running";
2164
+ job.occurrence = job.next;
2165
+ job.target = "worker";
2166
+ processLaunch = job;
2167
+ break;
2168
+ }
2169
+ if (state2.jobs.some((other) => other.enabled && other.sessionId === job.sessionId && other.state === "blocked")) continue;
2170
+ const owners = Object.entries(state2.owners).filter(([, owner]) => owner.sessionId === job.sessionId);
2171
+ if (owners.length > 1) {
2172
+ complete(job, "duplicate participating session owners");
2173
+ continue;
2174
+ }
2175
+ if (owners.length === 1 && owners[0][1].cwd !== job.cwd) {
2176
+ complete(job, "owner cwd differs from bound cwd");
2177
+ continue;
2178
+ }
2179
+ if (owners[0]?.[1].busy) continue;
2180
+ job.state = "running";
2181
+ job.occurrence = job.next;
2182
+ job.target = owners[0]?.[0] ?? "worker";
2183
+ if (job.target === "worker") launch = { ...job };
2184
+ break;
2217
2185
  }
2218
- } catch (error) {
2219
- warnings.push(`${entry.storeKey}: ${error instanceof Error ? error.message : String(error)}`);
2220
2186
  }
2221
- }
2222
- const hostStartupErr = getStartupError?.();
2223
- if (hostStartupErr && (!opts?.sessionId || hostJobMatched)) {
2224
- warnings.push(`host: cron unavailable (${hostStartupErr}); see docs/cron.md recovery`);
2225
- }
2226
- return {
2227
- jobs: sortJobs(jobs),
2228
- ...warnings.length > 0 ? { warnings } : {}
2229
- };
2230
- },
2231
- mutateJob(jobId, action, opts) {
2232
- if (!SAFE_JOB_ID.test(jobId)) {
2233
- return { ok: false, detail: "invalid job id" };
2234
- }
2235
- const stores = resolveStoresForKey(primaryStore, configRoot, opts?.storeKey);
2236
- const candidates = [];
2237
- for (const entry2 of stores) {
2187
+ });
2188
+ this.recovering = false;
2189
+ if (delivery) {
2190
+ const job = delivery;
2191
+ const scope = this.ctx.beginUserInput?.(() => !this.stopped && this.ready && this.sessionId === job.sessionId && !fs5.existsSync(path5.join(this.store.dir, "unsafe.lock")) && Object.values(this.store.read().owners).filter((owner) => owner.sessionId === job.sessionId).length === 1);
2192
+ let error;
2193
+ const content = `[Cron job=${job.id} scheduledAt=${job.occurrence}]
2194
+ ${job.prompt}`;
2195
+ this.accepted = { id: job.id, at: now, busy: false, consumed: false, content };
2196
+ this.acceptedIdlePolls = 0;
2238
2197
  try {
2239
- const found = entry2.store.read().jobs.find((j) => j.id === jobId);
2240
- if (found) candidates.push({ entry: entry2, job: found });
2241
- } catch {
2198
+ if (!scope || !await scope.submit(content)) error = "input rejected or session changed; inspect before resuming";
2199
+ } catch (failure) {
2200
+ error = `input outcome uncertain: ${String(failure)}`;
2201
+ } finally {
2202
+ scope?.dispose();
2203
+ }
2204
+ if (error) {
2205
+ this.accepted = void 0;
2206
+ this.finish(job.id, error);
2242
2207
  }
2243
2208
  }
2244
- if (candidates.length === 0) {
2245
- return { ok: false, detail: "unknown job (already removed or not found)" };
2209
+ if (launch) {
2210
+ const job = launch;
2211
+ const latest = this.store.read();
2212
+ if (this.stopped || fs5.existsSync(path5.join(this.store.dir, "unsafe.lock")) || Object.values(latest.owners).some((owner) => owner.sessionId === job.sessionId)) {
2213
+ this.finish(job.id, "ownership changed before worker launch; inspect before resuming");
2214
+ return;
2215
+ }
2216
+ this.abort = new AbortController();
2217
+ this.worker = this.execute(job, this.abort.signal, void 0, path5.dirname(this.store.dir)).then(() => this.finish(job.id), (error) => this.finish(job.id, String(error))).catch(() => {
2218
+ try {
2219
+ this.markUnsafe();
2220
+ } catch {
2221
+ }
2222
+ });
2246
2223
  }
2247
- if (candidates.length > 1) {
2248
- return { ok: false, detail: "ambiguous job id across multiple stores" };
2224
+ if (processLaunch) {
2225
+ const job = processLaunch;
2226
+ const command = parseProcessCommand(job);
2227
+ this.processAbort = new AbortController();
2228
+ this.worker = this.executeProcess(job, command, job.cwd, 30 * 60 * 1e3, this.store.dir, this.processAbort.signal, path5.dirname(this.store.dir)).then(
2229
+ () => this.finish(job.id),
2230
+ (error) => this.finish(
2231
+ job.id,
2232
+ String(error),
2233
+ error?.aborted === true,
2234
+ error?.retryable === true
2235
+ )
2236
+ ).catch(() => {
2237
+ try {
2238
+ this.markUnsafe();
2239
+ } catch {
2240
+ }
2241
+ });
2249
2242
  }
2250
- const { entry, job: before } = candidates[0];
2251
- if (opts?.sessionId && before.sessionId !== opts.sessionId) {
2252
- return { ok: false, detail: "job does not belong to target worker session" };
2243
+ const state = this.store.read(), enabled = state.jobs.filter((job) => job.enabled);
2244
+ const enabledCount = enabled.length;
2245
+ const blockedCount = enabled.filter((job) => job.state === "blocked").length;
2246
+ this.ctx.ui.setStatus?.("cron", this.leader && enabledCount > 0 && enabled.some((job) => job.sessionId === this.sessionId || isProcessJob(job)) ? blockedCount > 0 ? `[CRON.${enabledCount}.${blockedCount}]` : `[CRON.${enabledCount}]` : void 0);
2247
+ for (const job of state.jobs) {
2248
+ this.notify(job, Object.values(state.owners).filter((owner) => owner.sessionId === job.sessionId).length);
2253
2249
  }
2254
- const beforeView = toJobView(before, entry.storeKey, entry.ownerLabel);
2255
- if (entry.storeKey === "host") {
2256
- const hostStartupErr = getStartupError?.();
2257
- if (hostStartupErr) {
2258
- return {
2259
- ok: false,
2260
- detail: `cron unavailable: ${hostStartupErr}; see docs/cron.md recovery`,
2261
- job: beforeView
2262
- };
2263
- }
2250
+ } catch (error) {
2251
+ if (isContention(error)) {
2252
+ this.ctx.ui.setStatus?.("cron", void 0);
2253
+ return;
2254
+ }
2255
+ this.pollFailureBackoffMs = Math.min((this.pollFailureBackoffMs ?? 1e3) * 2, 3e5);
2256
+ this.pollRetryAt = Date.now() + this.pollFailureBackoffMs;
2257
+ this.ctx.log?.(`cron: poll failed (${String(error instanceof Error ? error.message : error).slice(0, 200)}); backing off ${Math.round(this.pollFailureBackoffMs / 1e3)}s. If this persists, the state file is invalid \u2014 recover via /tools/cron or repair the file offline.`);
2258
+ this.ctx.ui.setStatus?.("cron", "[CRON!]");
2259
+ this.scheduleRecoveryPoll();
2260
+ } finally {
2261
+ this.polling = false;
2262
+ }
2263
+ }
2264
+ /** One-shot delayed poll after a non-contention failure (schema-invalid
2265
+ * state): replaces the silent once-per-second retry loop with a backed-off
2266
+ * recovery attempt; the regular timer keeps running for healthy states. */
2267
+ scheduleRecoveryPoll() {
2268
+ if (this.stopped || this.recoveryPollTimer !== void 0) return;
2269
+ const delay2 = this.pollFailureBackoffMs ?? 1e3;
2270
+ this.recoveryPollTimer = setTimeout(() => {
2271
+ this.recoveryPollTimer = void 0;
2272
+ void this.poll().catch(() => {
2273
+ });
2274
+ }, delay2);
2275
+ this.recoveryPollTimer.unref();
2276
+ }
2277
+ async stop() {
2278
+ this.stopped = true;
2279
+ clearInterval(this.timer);
2280
+ if (this.recoveryPollTimer !== void 0) clearTimeout(this.recoveryPollTimer);
2281
+ this.abort.abort();
2282
+ this.processAbort.abort();
2283
+ await this.worker;
2284
+ while (this.polling) await delay(10);
2285
+ const shutdownDeadline = Date.now() + 1e4;
2286
+ const budgetLeft = () => Date.now() < shutdownDeadline;
2287
+ for (let attempt = 0; ; attempt++) {
2288
+ if (attempt > 0 && !budgetLeft()) {
2289
+ this.noteShutdownDegradation("cron: shutdown budget expired before the final state transaction completed; session ownership may be stale. If input stays blocked, run /tools/cron list and remove the stale owner row.");
2290
+ break;
2264
2291
  }
2265
- const authorization = getAuthorization();
2266
- const actor = opts?.senderId ? `im-panel:${opts.senderId}` : "im-panel";
2267
2292
  try {
2268
- const outcome = entry.store.change(jobId, action, Date.now(), {
2269
- ...action === "resume" ? { authorization } : {},
2270
- ...opts?.sessionId ? { expectedSessionId: opts.sessionId } : {},
2271
- ...action === "remove" ? { disableManagedOnRemove: true } : {}
2293
+ this.store.transaction((state) => {
2294
+ for (const [id, entry] of this.completions) {
2295
+ const job = state.jobs.find((item) => item.id === id);
2296
+ if (job?.state === "running") {
2297
+ settleJob(state, job, entry.error, Date.now(), {
2298
+ interrupted: entry.cancelled === true && entry.error !== void 0 && isProcessJob(job) && job.target === "worker",
2299
+ retryable: entry.retryable === true && entry.error !== void 0 && isProcessJob(job) && job.target === "worker"
2300
+ });
2301
+ }
2302
+ }
2303
+ delete state.owners[this.id];
2304
+ for (const job of [...state.jobs]) {
2305
+ if (job.state === "running" && job.target === this.id) {
2306
+ settleJob(state, job, "owner closed before delivery; inspect before resuming");
2307
+ }
2308
+ }
2272
2309
  });
2273
- const after = entry.store.read().jobs.find((j) => j.id === jobId);
2274
- const afterView = after ? toJobView(after, entry.storeKey, entry.ownerLabel) : beforeView;
2275
2310
  try {
2276
- entry.store.audit({
2277
- kind: action,
2278
- jobId,
2279
- sessionId: before.sessionId,
2280
- cwd: before.cwd,
2281
- authorization,
2282
- detail: outcome === "deferred" ? `${actor} (deferred until running occurrence settles)` : actor
2283
- });
2311
+ fs5.rmSync(path5.join(this.store.dir, "owners-liveness", `${this.id}.json`), { force: true });
2284
2312
  } catch {
2285
2313
  }
2286
- return {
2287
- ok: true,
2288
- outcome,
2289
- detail: outcome === "deferred" ? `${action} queued until current run finishes` : `${action} applied`,
2290
- job: afterView
2291
- };
2314
+ this.completions.clear();
2315
+ break;
2292
2316
  } catch (error) {
2293
- return {
2294
- ok: false,
2295
- detail: error instanceof Error ? error.message : String(error),
2296
- job: beforeView
2297
- };
2317
+ if (isContention(error) && attempt < 39 && budgetLeft()) {
2318
+ await delay(25 + Math.floor(Math.random() * 25));
2319
+ continue;
2320
+ }
2321
+ this.noteShutdownDegradation(`cron: exit left session ownership uncommitted (${String(error)}). If input stays blocked, run /tools/cron list and remove the stale owner row.`);
2322
+ break;
2298
2323
  }
2299
2324
  }
2300
- };
2301
- }
2325
+ if (this.leader) {
2326
+ for (let attempt = 0; ; attempt++) {
2327
+ if (!budgetLeft()) {
2328
+ this.noteShutdownDegradation("cron: shutdown budget expired before the coordinator lock was released; scheduling pauses until it is reclaimed; see docs/cron.md.");
2329
+ break;
2330
+ }
2331
+ try {
2332
+ this.withCoordinatorMutex(() => this.releaseCoordinator());
2333
+ break;
2334
+ } catch (error) {
2335
+ if (isContention(error) && attempt < 39 && budgetLeft()) {
2336
+ await delay(25 + Math.floor(Math.random() * 25));
2337
+ continue;
2338
+ }
2339
+ this.noteShutdownDegradation(`cron: coordinator lock not released (${String(error)}). Scheduling pauses until it is reclaimed; see docs/cron.md.`);
2340
+ break;
2341
+ }
2342
+ }
2343
+ }
2344
+ this.ctx.ui.setStatus?.("cron", void 0);
2345
+ }
2346
+ /** Surface a best-effort shutdown degradation. Never throws: diagnostics
2347
+ * must not turn a contained skip into a failed exit. */
2348
+ noteShutdownDegradation(message) {
2349
+ try {
2350
+ this.ctx.log?.(message);
2351
+ } catch {
2352
+ }
2353
+ try {
2354
+ this.ctx.ui.notify?.(message, "warning");
2355
+ } catch {
2356
+ }
2357
+ }
2358
+ };
2302
2359
 
2303
2360
  // builtin/extensions/cron/index.ts
2304
2361
  function cron(ctx) {