deployontime 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +661 -0
- package/README.md +266 -2
- package/SECURITY.md +61 -0
- package/mcp/jobs.mjs +137 -0
- package/mcp/runner.mjs +64 -0
- package/mcp/server.mjs +209 -0
- package/mcp/tools.mjs +380 -0
- package/package.json +48 -4
- package/queue/README.md +885 -0
- package/queue/args.mjs +136 -0
- package/queue/cli.mjs +207 -0
- package/queue/clock.mjs +49 -0
- package/queue/commands.mjs +35 -0
- package/queue/failstop.mjs +45 -0
- package/queue/files.mjs +71 -0
- package/queue/fingerprint.mjs +63 -0
- package/queue/gate.mjs +37 -0
- package/queue/git.mjs +61 -0
- package/queue/health.mjs +154 -0
- package/queue/idle.mjs +63 -0
- package/queue/job-wrapper.mjs +116 -0
- package/queue/journal.mjs +216 -0
- package/queue/kinds.mjs +95 -0
- package/queue/limits.mjs +79 -0
- package/queue/linux.mjs +72 -0
- package/queue/nested.mjs +83 -0
- package/queue/notices.mjs +114 -0
- package/queue/notify.mjs +47 -0
- package/queue/probes.mjs +162 -0
- package/queue/proctree.mjs +124 -0
- package/queue/project.mjs +26 -0
- package/queue/ps.mjs +54 -0
- package/queue/reaper.mjs +278 -0
- package/queue/run.mjs +628 -0
- package/queue/schedule-check.mjs +177 -0
- package/queue/settings.mjs +145 -0
- package/queue/setup.mjs +270 -0
- package/queue/slots.mjs +144 -0
- package/queue/stats.mjs +8 -0
- package/queue/stray.mjs +38 -0
- package/queue/timer.mjs +47 -0
- package/queue/units.mjs +8 -0
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// A read-only report on the scheduled jobs in ~/Library/LaunchAgents: is each one loaded, did its last run end with
|
|
3
|
+
// an accepted exit code, do its scripts exist, and is its log as recent as its schedule implies. Problems go out as
|
|
4
|
+
// one notice. Flags: --dry (no notice, no log entry) and --json. Rules come from $DOTIME_HOME/schedule-check.json.
|
|
5
|
+
import { existsSync, readdirSync, statSync } from "node:fs";
|
|
6
|
+
import { homedir } from "node:os";
|
|
7
|
+
import { join } from "node:path";
|
|
8
|
+
import { isMainModule, paths, timeZone } from "./settings.mjs";
|
|
9
|
+
import { dateTime } from "./clock.mjs";
|
|
10
|
+
import { notify } from "./notify.mjs";
|
|
11
|
+
import { probeReadPlist, probeScheduledJobs } from "./probes.mjs";
|
|
12
|
+
import { appendLine, readJson } from "./files.mjs";
|
|
13
|
+
import { flagError, SCRIPT_FLAGS, USAGE_EXIT } from "./args.mjs";
|
|
14
|
+
import { DAY, HOUR, MINUTE } from "./units.mjs";
|
|
15
|
+
|
|
16
|
+
export const LIST_ERROR = "could not read the job list";
|
|
17
|
+
|
|
18
|
+
/** Why the report cannot run on this platform, or null on macOS. It reads launchd job files and launchctl, which
|
|
19
|
+
* only macOS has. */
|
|
20
|
+
export function platformError(platform) {
|
|
21
|
+
if (platform === "darwin") return null;
|
|
22
|
+
return `works on macOS only for now: it reads launchd jobs in ~/Library/LaunchAgents through launchctl, `
|
|
23
|
+
+ `which ${platform === "linux" ? "Linux does" : "this system does"} not have; nothing was checked`;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
const warnOnStderr = (text) => process.stderr.write(`schedule-check: ${text}\n`);
|
|
27
|
+
/** The rules file as an object:
|
|
28
|
+
* { skip: [label patterns], okExit: { label: [codes] }, maxLogAgeH: { label: hours | null } }.
|
|
29
|
+
* A missing file means no rules. A file that cannot be read or is not one JSON object is reported through warn
|
|
30
|
+
* and also means no rules. */
|
|
31
|
+
export function readRules(file, { warn = warnOnStderr } = {}) {
|
|
32
|
+
const none = { skip: [], okExit: {} };
|
|
33
|
+
const missing = Symbol("no rules");
|
|
34
|
+
const rules = readJson(file, missing, (problem, code) => warn(problem === "invalid"
|
|
35
|
+
? `rules file ignored: ${file} is not valid JSON`
|
|
36
|
+
: `rules file ignored: ${file} could not be read (${code})`));
|
|
37
|
+
if (rules === missing) return none;
|
|
38
|
+
if (!rules || typeof rules !== "object" || Array.isArray(rules)) {
|
|
39
|
+
warn(`rules file ignored: ${file} needs one JSON object`);
|
|
40
|
+
return none;
|
|
41
|
+
}
|
|
42
|
+
return rules;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Matches a label against a pattern in which * stands for any text. */
|
|
46
|
+
export function globMatch(pattern, label) {
|
|
47
|
+
const literal = (text) => text.replace(/[.+?^${}()|[\]\\]/g, "\\$&");
|
|
48
|
+
return new RegExp(`^${pattern.split("*").map(literal).join(".*")}$`).test(label);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** Returns, in ms, how stale a job's log can get given how often the job is scheduled to run; null for a job
|
|
52
|
+
* that has no schedule. */
|
|
53
|
+
export function maxLogAgeMs(plist) {
|
|
54
|
+
if (plist.StartInterval) return Math.max(3 * plist.StartInterval * 1000, 30 * MINUTE);
|
|
55
|
+
const calendar = plist.StartCalendarInterval;
|
|
56
|
+
if (!calendar) return null;
|
|
57
|
+
const entries = Array.isArray(calendar) ? calendar : [calendar];
|
|
58
|
+
if (entries.some((e) => e.Day != null)) return 32 * DAY;
|
|
59
|
+
if (entries.some((e) => e.Weekday != null)) return 8 * DAY;
|
|
60
|
+
if (entries.every((e) => e.Hour == null)) return 3 * HOUR;
|
|
61
|
+
return 26 * HOUR;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
const SCRIPT_RE = /\.(mjs|cjs|js|ts|sh|zsh|py)$/;
|
|
65
|
+
/** The script files among a job's arguments: absolute paths with a script extension. */
|
|
66
|
+
export function scriptsOf(plist) {
|
|
67
|
+
const args = plist.ProgramArguments ?? [plist.Program];
|
|
68
|
+
const isScript = (arg) => typeof arg === "string" && arg.startsWith("/") && SCRIPT_RE.test(arg);
|
|
69
|
+
return args.filter(isScript);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** Judges one job from the facts gathered about it. Returns { label, ok, problems, log }. */
|
|
73
|
+
export function judge({ label, plist, loaded, exit, logMtime, scriptsMissing }, rules, now, tz) {
|
|
74
|
+
const problems = [];
|
|
75
|
+
if (!loaded) problems.push("not loaded in the scheduler");
|
|
76
|
+
if (scriptsMissing.length) problems.push(`script not found: ${scriptsMissing.join(", ")}`);
|
|
77
|
+
const accepted = rules.okExit?.[label] ?? [0];
|
|
78
|
+
if (loaded && exit != null && !accepted.includes(exit)) {
|
|
79
|
+
problems.push(exit < 0 ? `last run ended by signal ${-exit}` : `last run exit code ${exit}`);
|
|
80
|
+
}
|
|
81
|
+
const ageRules = rules.maxLogAgeH ?? {};
|
|
82
|
+
const maxAge = label in ageRules ? (ageRules[label] == null ? null : ageRules[label] * HOUR) : maxLogAgeMs(plist);
|
|
83
|
+
const log = plist.StandardErrorPath ?? plist.StandardOutPath ?? null;
|
|
84
|
+
if (maxAge && log) {
|
|
85
|
+
if (logMtime == null) { if (loaded) problems.push("log file not found"); }
|
|
86
|
+
else if (now - logMtime > maxAge) problems.push(`log not written since ${dateTime(logMtime, tz)}`);
|
|
87
|
+
}
|
|
88
|
+
return { label, ok: problems.length === 0, problems, log };
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** Judges every job file in a folder. Each reading can be replaced, so tests run on made-up jobs. Without rules
|
|
92
|
+
* given, they are read from rulesFile. Returns { results, error, warnings }; error is set, and results empty, when
|
|
93
|
+
* the scheduler's job list cannot be read; warnings name a rules file that could not be used. */
|
|
94
|
+
export function checkAll({
|
|
95
|
+
rules, rulesFile, warn = warnOnStderr, now = Date.now(), dir = join(homedir(), "Library", "LaunchAgents"),
|
|
96
|
+
list = () => readdirSync(dir), status = probeScheduledJobs, readPlist = probeReadPlist,
|
|
97
|
+
exists = existsSync, mtime = (file) => statSync(file).mtimeMs, tz,
|
|
98
|
+
}) {
|
|
99
|
+
const warnings = [];
|
|
100
|
+
if (!rules) rules = readRules(rulesFile, { warn: (text) => { warnings.push(text); warn(text); } });
|
|
101
|
+
let files;
|
|
102
|
+
try {
|
|
103
|
+
files = list().filter((name) => name.endsWith(".plist")).sort();
|
|
104
|
+
} catch { return { results: [], error: null, warnings }; }
|
|
105
|
+
const loadedJobs = status();
|
|
106
|
+
if (!loadedJobs) return { results: [], error: LIST_ERROR, warnings };
|
|
107
|
+
const results = [];
|
|
108
|
+
for (const name of files) {
|
|
109
|
+
const plist = readPlist(join(dir, name));
|
|
110
|
+
if (!plist) {
|
|
111
|
+
results.push({ label: name, ok: false, problems: ["job file unreadable"], log: null });
|
|
112
|
+
continue;
|
|
113
|
+
}
|
|
114
|
+
const label = plist.Label ?? name.replace(/\.plist$/, "");
|
|
115
|
+
if ((rules.skip ?? []).some((pattern) => globMatch(pattern, label))) continue;
|
|
116
|
+
const entry = loadedJobs.get(label);
|
|
117
|
+
const log = plist.StandardErrorPath ?? plist.StandardOutPath;
|
|
118
|
+
let logMtime = null;
|
|
119
|
+
try { if (log) logMtime = mtime(log); } catch { /* no log file */ }
|
|
120
|
+
const scriptsMissing = scriptsOf(plist).filter((script) => !exists(script));
|
|
121
|
+
const facts = { label, plist, loaded: !!entry, exit: entry?.exit ?? null, logMtime, scriptsMissing };
|
|
122
|
+
results.push(judge(facts, rules, now, tz));
|
|
123
|
+
}
|
|
124
|
+
return { results, error: null, warnings };
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** The notice text: the warnings, then the jobs with problems; null when there is nothing to say. */
|
|
128
|
+
export function reportText(results, warnings = []) {
|
|
129
|
+
const broken = results.filter((r) => !r.ok);
|
|
130
|
+
const parts = [...warnings];
|
|
131
|
+
if (broken.length) {
|
|
132
|
+
const each = broken.map((r) => `${r.label}: ${r.problems.join(", ")}`).join("; ");
|
|
133
|
+
parts.push(`scheduled jobs with problems: ${broken.length} of ${results.length}; ${each}`);
|
|
134
|
+
}
|
|
135
|
+
return parts.length ? parts.join("; ") : null;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
async function main() {
|
|
139
|
+
const badFlag = flagError(["schedule-check", ...process.argv.slice(2)], SCRIPT_FLAGS);
|
|
140
|
+
if (badFlag) {
|
|
141
|
+
process.stderr.write(`schedule-check: ${badFlag}; usage: schedule-check.mjs [--dry] [--json]\n`);
|
|
142
|
+
process.exitCode = USAGE_EXIT;
|
|
143
|
+
return;
|
|
144
|
+
}
|
|
145
|
+
const unsupported = platformError(process.platform);
|
|
146
|
+
if (unsupported) {
|
|
147
|
+
process.stderr.write(`schedule-check: ${unsupported}\n`);
|
|
148
|
+
process.exitCode = 1;
|
|
149
|
+
return;
|
|
150
|
+
}
|
|
151
|
+
const dry = process.argv.includes("--dry");
|
|
152
|
+
const asJson = process.argv.includes("--json");
|
|
153
|
+
const now = Date.now();
|
|
154
|
+
const files = paths();
|
|
155
|
+
const tz = timeZone();
|
|
156
|
+
const { results, error, warnings } = checkAll({ now, rulesFile: files.scheduleRules, tz });
|
|
157
|
+
const text = error ? [...warnings, error].join("; ") : reportText(results, warnings);
|
|
158
|
+
if (asJson) console.log(JSON.stringify(error ? { error } : results, null, 1));
|
|
159
|
+
else if (error) console.log(`schedule-check ${dateTime(now, tz)}: ${text}`);
|
|
160
|
+
else {
|
|
161
|
+
const counts = `jobs checked ${results.length}, with problems ${results.filter((r) => !r.ok).length}`;
|
|
162
|
+
console.log(`schedule-check ${dateTime(now, tz)}: ${counts}${text ? `; ${text}` : ""}`);
|
|
163
|
+
}
|
|
164
|
+
if (!dry) {
|
|
165
|
+
if (text) {
|
|
166
|
+
try {
|
|
167
|
+
notify("dotime: scheduled jobs", text, { env: process.env, logFile: files.notifyLog });
|
|
168
|
+
} catch { /* the printed line already says it */ }
|
|
169
|
+
}
|
|
170
|
+
// The report does not depend on its log: a line that cannot be written is left out.
|
|
171
|
+
const line = { at: new Date(now).toISOString(), error, warnings, results };
|
|
172
|
+
appendLine(files.scheduleLog, `${JSON.stringify(line)}\n`);
|
|
173
|
+
}
|
|
174
|
+
if (error) process.exitCode = 1;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
if (isMainModule(import.meta.url)) await main();
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
// Settings and file locations. Every value is a built-in default unless $DOTIME_HOME/config.json replaces it; that
|
|
2
|
+
// file is shared by all callers on the machine, so one caller cannot loosen a limit for itself. The environment only
|
|
3
|
+
// selects the state folder, the time zone and the notice channel.
|
|
4
|
+
import { realpathSync } from "node:fs";
|
|
5
|
+
import { homedir } from "node:os";
|
|
6
|
+
import { join, resolve } from "node:path";
|
|
7
|
+
import { pathToFileURL } from "node:url";
|
|
8
|
+
import { readJson } from "./files.mjs";
|
|
9
|
+
import { MAX_TIMER_MS } from "./timer.mjs";
|
|
10
|
+
|
|
11
|
+
export const DEFAULTS = Object.freeze({
|
|
12
|
+
slots: 2,
|
|
13
|
+
nestedPerJob: 2,
|
|
14
|
+
mcpMaxJobs: 20,
|
|
15
|
+
maxWaitMin: 60,
|
|
16
|
+
pollMs: 3000,
|
|
17
|
+
health: { loadPerCore: 1.0, busyCpuPct: 90, minFreeMemPct: 20, minFreeDiskGB: 10, minBatteryPct: 15 },
|
|
18
|
+
limits: {
|
|
19
|
+
defaultMin: 30, debugMin: 15, floorMin: 10, p90Factor: 1.5, longRunFactor: 2, longRunUnmeasuredMin: 20,
|
|
20
|
+
minSamples: 5, windowDays: 14, failWindowHours: 6, priorityGrace: 2, killGraceMs: 10_000, orphanCheckMs: 2000,
|
|
21
|
+
},
|
|
22
|
+
idle: { serverIdleMin: 30, serverCpuS: 10, slotIdleMin: 10, slotCpuS: 5 },
|
|
23
|
+
reaper: {
|
|
24
|
+
overloadPerCore: 2.0, overloadSwapPct: 80, overloadMemPct: 10, overloadDiskGB: 5, lowDiskGB: 20,
|
|
25
|
+
serverPattern: [
|
|
26
|
+
"\\bvite(\\s(?!build\\b)|$)", "\\bvitest\\b", "\\bnext dev\\b", "\\bwrangler dev\\b",
|
|
27
|
+
"webpack(-dev-server| serve)", "\\bnodemon\\b",
|
|
28
|
+
].join("|"),
|
|
29
|
+
keepPattern: "/Applications/|LaunchAgents",
|
|
30
|
+
},
|
|
31
|
+
outputDirs: [
|
|
32
|
+
"node_modules", "dist", "build", "out", "coverage", ".cache", ".next", ".turbo", ".wrangler", ".vercel",
|
|
33
|
+
"test-results", "playwright-report",
|
|
34
|
+
],
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
const above0 = [(n) => n > 0, "a number above 0"];
|
|
38
|
+
const from0 = [(n) => n >= 0, "a number of 0 or more"];
|
|
39
|
+
const from1 = [(n) => n >= 1, "a number of 1 or more"];
|
|
40
|
+
const whole1 = [(n) => Number.isInteger(n) && n >= 1, "a whole number of 1 or more"];
|
|
41
|
+
const pct = [(n) => n > 0 && n <= 100, "a number above 0 and at most 100"];
|
|
42
|
+
// Numbers may be 0 or more unless a stricter rule is listed here.
|
|
43
|
+
const NUMBER_RULES = {
|
|
44
|
+
"slots": from1, "nestedPerJob": whole1, "mcpMaxJobs": whole1, "pollMs": above0, "health.loadPerCore": above0, "health.busyCpuPct": pct,
|
|
45
|
+
"limits.defaultMin": above0, "limits.debugMin": above0, "limits.floorMin": above0, "limits.p90Factor": above0,
|
|
46
|
+
"limits.longRunFactor": above0, "limits.longRunUnmeasuredMin": above0, "limits.minSamples": from1,
|
|
47
|
+
"limits.windowDays": above0, "limits.priorityGrace": from1, "limits.orphanCheckMs": above0,
|
|
48
|
+
"idle.serverIdleMin": above0, "idle.slotIdleMin": above0, "reaper.overloadPerCore": above0,
|
|
49
|
+
};
|
|
50
|
+
|
|
51
|
+
export const defaultHome = () => join(homedir(), ".dotime");
|
|
52
|
+
export const homeDir = (env = process.env) => (env.DOTIME_HOME ? resolve(env.DOTIME_HOME) : defaultHome());
|
|
53
|
+
|
|
54
|
+
/** True when this module file is the script node was started with, also through a symlink. */
|
|
55
|
+
export function isMainModule(moduleUrl, script = process.argv[1]) {
|
|
56
|
+
try { return pathToFileURL(realpathSync(script)).href === moduleUrl; } catch { return false; }
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export function paths(env = process.env) {
|
|
60
|
+
const home = homeDir(env);
|
|
61
|
+
return {
|
|
62
|
+
home,
|
|
63
|
+
config: join(home, "config.json"),
|
|
64
|
+
slots: join(home, "slots"),
|
|
65
|
+
waitingLine: join(home, "line"),
|
|
66
|
+
nested: join(home, "nested"),
|
|
67
|
+
places: join(home, "places"),
|
|
68
|
+
journal: join(home, "journal.jsonl"),
|
|
69
|
+
notices: join(home, "notices"),
|
|
70
|
+
notifyLog: join(home, "notify.log"),
|
|
71
|
+
reaperState: join(home, "reaper-state.json"),
|
|
72
|
+
healthCache: join(home, "health.json"),
|
|
73
|
+
scheduleRules: join(home, "schedule-check.json"),
|
|
74
|
+
scheduleLog: join(home, "schedule-check.jsonl"),
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export function timeZone(env = process.env) {
|
|
79
|
+
const zone = env.DOTIME_TZ || "UTC";
|
|
80
|
+
try { new Intl.DateTimeFormat("en-US", { timeZone: zone }); return zone; } catch { return "UTC"; }
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
const told = new Set();
|
|
84
|
+
function warnOnce(text) {
|
|
85
|
+
if (told.has(text)) return;
|
|
86
|
+
told.add(text);
|
|
87
|
+
process.stderr.write(`dotime-queue: ${text}\n`);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function parseOr(text, problem) {
|
|
91
|
+
try { return JSON.parse(text); } catch { problem("invalid"); return {}; }
|
|
92
|
+
}
|
|
93
|
+
const isPlain = (x) => !!x && typeof x === "object" && !Array.isArray(x);
|
|
94
|
+
/** null when the value fits the setting, else a few words on what the setting needs. */
|
|
95
|
+
function misfit(name, fallback, value) {
|
|
96
|
+
if (typeof fallback === "number") {
|
|
97
|
+
const [fits, needs] = NUMBER_RULES[name] ?? from0;
|
|
98
|
+
// A longer timer would fire at once.
|
|
99
|
+
if (name.endsWith("Ms") && value > MAX_TIMER_MS) return `${needs} and at most ${MAX_TIMER_MS}`;
|
|
100
|
+
return typeof value === "number" && Number.isFinite(value) && fits(value) ? null : needs;
|
|
101
|
+
}
|
|
102
|
+
if (Array.isArray(fallback)) {
|
|
103
|
+
const folderName = (x) => typeof x === "string" && x !== "" && !x.includes("/");
|
|
104
|
+
return Array.isArray(value) && value.every(folderName) ? null : "a list of folder names";
|
|
105
|
+
}
|
|
106
|
+
if (typeof value !== "string" || value === "") return "a regular expression as text";
|
|
107
|
+
try { new RegExp(value); return null; } catch { return "a valid regular expression"; }
|
|
108
|
+
}
|
|
109
|
+
function overlay(defaults, given, prefix, warn) {
|
|
110
|
+
const out = {};
|
|
111
|
+
for (const [key, fallback] of Object.entries(defaults)) {
|
|
112
|
+
const name = prefix + key;
|
|
113
|
+
const value = given[key];
|
|
114
|
+
if (isPlain(fallback)) {
|
|
115
|
+
if (value !== undefined && !isPlain(value)) warn(`setting ignored: ${name} needs an object, defaults kept`);
|
|
116
|
+
out[key] = overlay(fallback, isPlain(value) ? value : {}, `${name}.`, warn);
|
|
117
|
+
continue;
|
|
118
|
+
}
|
|
119
|
+
const needs = value === undefined ? null : misfit(name, fallback, value);
|
|
120
|
+
if (needs) {
|
|
121
|
+
const kept = `default ${JSON.stringify(fallback)} kept`;
|
|
122
|
+
warn(`setting ignored: ${name} is ${JSON.stringify(value)}, needs ${needs}, ${kept}`);
|
|
123
|
+
}
|
|
124
|
+
out[key] = structuredClone(value === undefined || needs ? fallback : value);
|
|
125
|
+
}
|
|
126
|
+
for (const key of Object.keys(given)) {
|
|
127
|
+
if (!(key in defaults)) warn(`setting ignored: ${prefix}${key} is not a known setting`);
|
|
128
|
+
}
|
|
129
|
+
return out;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** The settings in force. A value that does not fit is replaced by its default, with one warning per process. */
|
|
133
|
+
export function loadSettings(env = process.env, { configText, warn = warnOnce } = {}) {
|
|
134
|
+
const problem = (kind, code) => warn(kind === "invalid"
|
|
135
|
+
? "config.json ignored: it is not valid JSON"
|
|
136
|
+
: `config.json ignored: it could not be read (${code}), defaults kept`);
|
|
137
|
+
let given = configText === undefined ? readJson(paths(env).config, {}, problem) : parseOr(configText, problem);
|
|
138
|
+
if (!isPlain(given)) {
|
|
139
|
+
warn("config.json ignored: it needs one JSON object");
|
|
140
|
+
given = {};
|
|
141
|
+
}
|
|
142
|
+
const settings = overlay(DEFAULTS, given, "", warn);
|
|
143
|
+
settings.slots = Math.floor(settings.slots);
|
|
144
|
+
return settings;
|
|
145
|
+
}
|
package/queue/setup.mjs
ADDED
|
@@ -0,0 +1,270 @@
|
|
|
1
|
+
// `dotime-queue setup`: puts the queue instruction into a project's agent instruction files, between a begin and an
|
|
2
|
+
// end marker, so a second run updates that block and leaves the rest of each file as it was. Without --write it only
|
|
3
|
+
// says what it would do. It writes inside the project folder only, and only the files it names.
|
|
4
|
+
import { accessSync, constants, existsSync, readFileSync, realpathSync, statSync, writeFileSync } from "node:fs";
|
|
5
|
+
import { dirname, join, relative, resolve, sep } from "node:path";
|
|
6
|
+
import { fileURLToPath } from "node:url";
|
|
7
|
+
|
|
8
|
+
/** The shared agent instruction files looked for, in this order. AGENTS.md is the one created when none exists. */
|
|
9
|
+
export const AGENT_FILES = Object.freeze(["AGENTS.md", "CLAUDE.md", ".claude/CLAUDE.md"]);
|
|
10
|
+
/** The files Claude Code reads in place of AGENTS.md: when one of them is in the folder or above it, Claude Code does
|
|
11
|
+
* not read AGENTS.md. */
|
|
12
|
+
export const CLAUDE_FILES = Object.freeze(["CLAUDE.md", ".claude/CLAUDE.md", "CLAUDE.local.md"]);
|
|
13
|
+
/** A personal file for one person's Claude Code. It gets the block only when no shared Claude Code file exists, or
|
|
14
|
+
* when it holds the block already. */
|
|
15
|
+
export const LOCAL_FILE = "CLAUDE.local.md";
|
|
16
|
+
export const BEGIN = "<!-- dotime-queue setup: begin; `dotime-queue setup --write` updates this block -->";
|
|
17
|
+
export const END = "<!-- dotime-queue setup: end -->";
|
|
18
|
+
const BEGIN_RE = /^<!-- dotime-queue setup: begin\b.*-->[ \t]*\r?$/;
|
|
19
|
+
const END_RE = /^<!-- dotime-queue setup: end\b.*-->[ \t]*\r?$/;
|
|
20
|
+
|
|
21
|
+
/** The lines between the markers. */
|
|
22
|
+
export const BLOCK_LINES = Object.freeze([
|
|
23
|
+
"## Heavy commands",
|
|
24
|
+
"",
|
|
25
|
+
"Start every test run, build and other heavy command through the queue:",
|
|
26
|
+
"",
|
|
27
|
+
"```",
|
|
28
|
+
'dotime-queue run --label "<project>: <task>" -- <command>',
|
|
29
|
+
"```",
|
|
30
|
+
"",
|
|
31
|
+
'A test or lint run that prints "skipped:" already passed on this exact commit and exits 0; add --no-skip in front',
|
|
32
|
+
"of the -- only to run it again on purpose. Exit 75 means the job gave up waiting for a slot, not a failure; exit",
|
|
33
|
+
"124 means it was stopped at its run limit. Exit 3 means the same check already failed twice on unchanged code",
|
|
34
|
+
"and was not run: change the code first, or, when the failure was not caused by the code, add",
|
|
35
|
+
'--after-fix "<what changed>" in front of the --.',
|
|
36
|
+
]);
|
|
37
|
+
|
|
38
|
+
/** The whole block, markers included, with the given line ending and none after the end marker. */
|
|
39
|
+
export const blockText = (eol = "\n") => [BEGIN, ...BLOCK_LINES, END].join(eol);
|
|
40
|
+
|
|
41
|
+
/** For each line, whether it is part of a fenced code block: a fence line of three or more backticks or tildes, the
|
|
42
|
+
* lines after it, and the line that closes it. */
|
|
43
|
+
export function fencedLines(lines) {
|
|
44
|
+
let open = null;
|
|
45
|
+
return lines.map((line) => {
|
|
46
|
+
const fence = /^ {0,3}(`{3,}|~{3,})/.exec(line)?.[1];
|
|
47
|
+
if (open) {
|
|
48
|
+
if (fence && fence[0] === open[0] && fence.length >= open.length && /^ {0,3}[`~]+[ \t]*\r?$/.test(line)) {
|
|
49
|
+
open = null;
|
|
50
|
+
}
|
|
51
|
+
return true;
|
|
52
|
+
}
|
|
53
|
+
if (fence) open = fence;
|
|
54
|
+
return Boolean(fence);
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** The paths a Claude Code instruction file imports with `@path`, outside code blocks and code spans. A path with
|
|
59
|
+
* spaces is written with a backslash before each space. */
|
|
60
|
+
export function importedPaths(text) {
|
|
61
|
+
const lines = text.split("\n");
|
|
62
|
+
const fenced = fencedLines(lines);
|
|
63
|
+
return lines.flatMap((line, i) => {
|
|
64
|
+
if (fenced[i]) return [];
|
|
65
|
+
const plain = line.replace(/(`+)[^`]*?\1/g, " ");
|
|
66
|
+
return [...plain.matchAll(/(?:^|\s)@((?:\\ |\S)+)/g)].map((m) => m[1].replaceAll("\\ ", " "));
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** What setup does to one file's text: { action, text } with action "create", "add", "update" or "unchanged", or
|
|
71
|
+
* { error }. text is the file's text (null when there is no file). The block takes the file's line ending: CRLF
|
|
72
|
+
* when its first line ends in CRLF. Only the lines from the begin marker to the end marker are replaced; a file
|
|
73
|
+
* without a block gets it at the end, after a blank line, and every byte before it stays as it was. Marker lines
|
|
74
|
+
* inside a fenced code block are not counted; spaces after a marker are. */
|
|
75
|
+
export function planText(text) {
|
|
76
|
+
if (text === null) return { action: "create", text: `${blockText()}\n` };
|
|
77
|
+
const eol = /^[^\n]*\r\n/.test(text) ? "\r\n" : "\n";
|
|
78
|
+
const lines = text.split("\n");
|
|
79
|
+
// Marker lines inside a fenced code block are an example, not the block.
|
|
80
|
+
const fenced = fencedLines(lines);
|
|
81
|
+
const begins = lines.flatMap((line, i) => (!fenced[i] && BEGIN_RE.test(line) ? [i] : []));
|
|
82
|
+
const ends = lines.flatMap((line, i) => (!fenced[i] && END_RE.test(line) ? [i] : []));
|
|
83
|
+
if (begins.length === 0 && ends.length === 0) {
|
|
84
|
+
const gap = text === "" ? "" : text.endsWith("\n") ? eol : `${eol}${eol}`;
|
|
85
|
+
return { action: "add", text: `${text}${gap}${blockText(eol)}${eol}` };
|
|
86
|
+
}
|
|
87
|
+
if (begins.length !== 1 || ends.length !== 1 || ends[0] < begins[0]) {
|
|
88
|
+
return { error: "its dotime-queue setup markers do not form one begin and one end; fix them by hand" };
|
|
89
|
+
}
|
|
90
|
+
const before = lines.slice(0, begins[0]).join("\n");
|
|
91
|
+
const after = lines.slice(ends[0] + 1).join("\n");
|
|
92
|
+
const endLine = lines[ends[0]];
|
|
93
|
+
// The end marker's own line ending stays with the text after it.
|
|
94
|
+
const tail = endLine.endsWith("\r") ? "\r" : "";
|
|
95
|
+
const head = begins[0] ? `${before}\n` : "";
|
|
96
|
+
const rest = ends[0] < lines.length - 1 ? `\n${after}` : "";
|
|
97
|
+
const next = `${head}${blockText(eol)}${tail}${rest}`;
|
|
98
|
+
return next === text ? { action: "unchanged", text } : { action: "update", text: next };
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
const inside = (root, path) => path === root || path.startsWith(root + sep);
|
|
102
|
+
|
|
103
|
+
/** Does the file at `shown` (inside root) import the file at `target` with `@path`? */
|
|
104
|
+
function importsFile(text, shown, target) {
|
|
105
|
+
return importedPaths(text).some((path) => {
|
|
106
|
+
if (path.startsWith("~")) return false;
|
|
107
|
+
const named = resolve(dirname(shown), path);
|
|
108
|
+
try {
|
|
109
|
+
return realpathSync(named) === target;
|
|
110
|
+
} catch {
|
|
111
|
+
return false;
|
|
112
|
+
}
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** The first Claude Code instruction file in a folder above root, or null. */
|
|
117
|
+
function claudeFileAbove(root) {
|
|
118
|
+
for (let dir = dirname(root); ; dir = dirname(dir)) {
|
|
119
|
+
for (const file of CLAUDE_FILES) if (existsSync(join(dir, file))) return join(dir, file);
|
|
120
|
+
if (dirname(dir) === dir) return null;
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** Reads one agent file: { file, path, text }, null when there is none, or { error }. */
|
|
125
|
+
function readAgentFile(root, file) {
|
|
126
|
+
let path;
|
|
127
|
+
try {
|
|
128
|
+
path = realpathSync(join(root, file));
|
|
129
|
+
} catch (err) {
|
|
130
|
+
if (err.code === "ENOENT" || err.code === "ENOTDIR") return null;
|
|
131
|
+
return { error: `${file}: cannot be read (${err.code})` };
|
|
132
|
+
}
|
|
133
|
+
if (!inside(root, path)) return { error: `${file}: is a link to ${path}, outside the project folder` };
|
|
134
|
+
try {
|
|
135
|
+
const stat = statSync(path);
|
|
136
|
+
if (!stat.isFile()) return { error: `${file}: is not a file` };
|
|
137
|
+
// Another name of a hard link may be outside the project folder, and nothing tells where it is.
|
|
138
|
+
if (stat.nlink > 1) {
|
|
139
|
+
const why = "setup does not write through one; replace it by a plain file";
|
|
140
|
+
return { error: `${file}: has ${stat.nlink} hard links; ${why}` };
|
|
141
|
+
}
|
|
142
|
+
return { file, path, text: readFileSync(path, "utf8") };
|
|
143
|
+
} catch (err) {
|
|
144
|
+
return { error: `${file}: cannot be read (${err.code})` };
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/** The plan for a project folder: { root, changes: [{ file, action, text, path }], notes }, or { error } with
|
|
149
|
+
* folder: true when dir is no folder. file is the name as shown, path the real path written. A file that is a
|
|
150
|
+
* link is followed only when it ends inside the project folder; a second name for a file already planned is left
|
|
151
|
+
* out, and a file with more than one hard link is refused. A file that cannot be read or written is an error,
|
|
152
|
+
* found before anything is written.
|
|
153
|
+
*
|
|
154
|
+
* Claude Code does not read AGENTS.md when the folder or one above it has a CLAUDE.md, a .claude/CLAUDE.md or a
|
|
155
|
+
* CLAUDE.local.md, so those get the block too. A CLAUDE.local.md gets it only when neither shared one exists (or
|
|
156
|
+
* it holds the block already), since it is one person's own file. A Claude Code file without the block that
|
|
157
|
+
* imports AGENTS.md with `@AGENTS.md` is skipped (action "imported"): it reads the block from AGENTS.md. notes
|
|
158
|
+
* are lines that explain the plan. */
|
|
159
|
+
export function planFolder(dir) {
|
|
160
|
+
let root;
|
|
161
|
+
try {
|
|
162
|
+
root = realpathSync(dir);
|
|
163
|
+
if (!statSync(root).isDirectory()) return { error: `${dir} is not a folder`, folder: true };
|
|
164
|
+
} catch {
|
|
165
|
+
return { error: `${dir}: no such folder`, folder: true };
|
|
166
|
+
}
|
|
167
|
+
const found = [];
|
|
168
|
+
const seen = new Set();
|
|
169
|
+
for (const file of [...AGENT_FILES, LOCAL_FILE]) {
|
|
170
|
+
const one = readAgentFile(root, file);
|
|
171
|
+
if (one === null) continue;
|
|
172
|
+
if (one.error) return one;
|
|
173
|
+
if (seen.has(one.path)) continue;
|
|
174
|
+
seen.add(one.path);
|
|
175
|
+
found.push(one);
|
|
176
|
+
}
|
|
177
|
+
const shared = found.filter((one) => one.file !== LOCAL_FILE);
|
|
178
|
+
const notes = [];
|
|
179
|
+
const planned = [];
|
|
180
|
+
for (const one of found) {
|
|
181
|
+
const plan = planText(one.text);
|
|
182
|
+
if (plan.error) return { error: `${one.file}: ${plan.error}` };
|
|
183
|
+
if (one.file === LOCAL_FILE && plan.action === "add" && shared.some((s) => s.file !== "AGENTS.md")) continue;
|
|
184
|
+
planned.push({ ...one, plan });
|
|
185
|
+
}
|
|
186
|
+
if (!shared.length) {
|
|
187
|
+
try {
|
|
188
|
+
accessSync(root, constants.W_OK);
|
|
189
|
+
} catch (err) {
|
|
190
|
+
return { error: `${root}: cannot create AGENTS.md in it (${err.code})` };
|
|
191
|
+
}
|
|
192
|
+
planned.unshift({ file: AGENT_FILES[0], path: join(root, AGENT_FILES[0]), plan: planText(null) });
|
|
193
|
+
}
|
|
194
|
+
const agents = planned.find((one) => one.file === AGENT_FILES[0]);
|
|
195
|
+
const changes = [];
|
|
196
|
+
for (const one of planned) {
|
|
197
|
+
let plan = one.plan;
|
|
198
|
+
const imports = agents && one !== agents && importsFile(one.text ?? "", join(root, one.file), agents.path);
|
|
199
|
+
if (imports && plan.action === "add") plan = { action: "imported", text: one.text };
|
|
200
|
+
if (one.text !== undefined && !["unchanged", "imported"].includes(plan.action)) {
|
|
201
|
+
try {
|
|
202
|
+
accessSync(one.path, constants.W_OK);
|
|
203
|
+
} catch (err) {
|
|
204
|
+
return { error: `${one.file}: cannot be written (${err.code}); make it writable and run setup again` };
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
if (one.file === LOCAL_FILE && plan.action === "add") {
|
|
208
|
+
notes.push(`note: ${LOCAL_FILE} gets the block because Claude Code reads it and not AGENTS.md; it is your`,
|
|
209
|
+
"own file, so for everyone else's Claude Code add a CLAUDE.md with the line @AGENTS.md");
|
|
210
|
+
}
|
|
211
|
+
changes.push({ file: relative(root, one.path) || one.file, path: one.path, ...plan });
|
|
212
|
+
}
|
|
213
|
+
const claudeSees = changes.some((c) => CLAUDE_FILES.includes(c.file));
|
|
214
|
+
const above = claudeSees ? null : claudeFileAbove(root);
|
|
215
|
+
if (above) {
|
|
216
|
+
notes.push(`note: Claude Code reads ${above} and not AGENTS.md; to give it the block, add the`,
|
|
217
|
+
`line @${join(relative(dirname(above), root), "AGENTS.md")} to that file, or run setup in its folder`);
|
|
218
|
+
}
|
|
219
|
+
return { root, changes, notes };
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
const DONE = {
|
|
223
|
+
create: "created", add: "added the block to", update: "updated the block in", unchanged: "unchanged:",
|
|
224
|
+
imported: "skipped",
|
|
225
|
+
};
|
|
226
|
+
const WOULD = {
|
|
227
|
+
create: "would create", add: "would add the block to", update: "would update the block in", unchanged: "unchanged:",
|
|
228
|
+
imported: "would skip",
|
|
229
|
+
};
|
|
230
|
+
const WRITES = new Set(["create", "add", "update"]);
|
|
231
|
+
|
|
232
|
+
/** Carries out a plan: writes each changed file and returns the lines to print and the files changed, as
|
|
233
|
+
* { lines, changed } or, when a write fails, { lines, changed, error } with the files written before it. */
|
|
234
|
+
export function applyPlan({ changes }, { write = false, writeFile = writeFileSync } = {}) {
|
|
235
|
+
const lines = [], changed = [];
|
|
236
|
+
for (const change of changes) {
|
|
237
|
+
if (write && WRITES.has(change.action)) {
|
|
238
|
+
try {
|
|
239
|
+
writeFile(change.path, change.text, change.action === "create" ? { flag: "wx" } : undefined);
|
|
240
|
+
} catch (err) {
|
|
241
|
+
return { lines, changed, error: `${change.file}: cannot be written (${err.code ?? err.message})` };
|
|
242
|
+
}
|
|
243
|
+
changed.push(change.file);
|
|
244
|
+
}
|
|
245
|
+
const why = change.action === "imported" ? `: it imports ${AGENT_FILES[0]}, which holds the block` : "";
|
|
246
|
+
lines.push(`${(write ? DONE : WOULD)[change.action]} ${change.file}${why}`);
|
|
247
|
+
}
|
|
248
|
+
return { lines, changed };
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
const SERVER_PATH = fileURLToPath(new URL("../mcp/server.mjs", import.meta.url));
|
|
252
|
+
|
|
253
|
+
/** The lines --mcp prints: the generic entry, the Claude Code command, and the form without `npm link`. */
|
|
254
|
+
export function mcpLines(serverPath = SERVER_PATH) {
|
|
255
|
+
const entry = { mcpServers: { "dotime-queue": { command: "dotime-mcp" } } };
|
|
256
|
+
const unlinked = { mcpServers: { "dotime-queue": { command: "node", args: [resolve(serverPath)] } } };
|
|
257
|
+
return [
|
|
258
|
+
"MCP server: dotime-mcp, on standard input and output",
|
|
259
|
+
"",
|
|
260
|
+
"Generic entry for a client's MCP server settings:",
|
|
261
|
+
JSON.stringify(entry, null, 2),
|
|
262
|
+
"",
|
|
263
|
+
"Claude Code: run the command below, or put the generic entry in .mcp.json at the project root to share it",
|
|
264
|
+
"with everyone in the project (an entry without a type is read as a stdio server):",
|
|
265
|
+
"claude mcp add --transport stdio dotime-queue -- dotime-mcp",
|
|
266
|
+
"",
|
|
267
|
+
"Without npm link:",
|
|
268
|
+
JSON.stringify(unlinked, null, 2),
|
|
269
|
+
];
|
|
270
|
+
}
|