ceulen 0.10.1 → 0.12.0
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/CHANGELOG.md +107 -1
- package/README.md +56 -1
- package/extensions/index.ts +5 -1
- package/extensions/lib/env.test.ts +147 -0
- package/extensions/lib/env.ts +180 -0
- package/extensions/lib/order.test.ts +74 -0
- package/extensions/lib/plan-bridge.ts +18 -0
- package/extensions/lib/registry.test.ts +8 -5
- package/extensions/lib/registry.ts +22 -3
- package/extensions/modules/a2a/configPanel.ts +42 -1
- package/extensions/modules/a2a/index.ts +4 -2
- package/extensions/modules/a2a/lib/config.ts +8 -3
- package/extensions/modules/a2a/test/configPanel.test.ts +7 -4
- package/extensions/modules/advisor/index.ts +6 -3
- package/extensions/modules/advisor/test/module.test.ts +31 -0
- package/extensions/modules/attachments/configPanel.ts +91 -0
- package/extensions/modules/attachments/index.ts +274 -0
- package/extensions/modules/attachments/lib/clipboard-files.ts +80 -0
- package/extensions/modules/attachments/lib/pastes.ts +45 -0
- package/extensions/modules/attachments/lib/paths.ts +74 -0
- package/extensions/modules/attachments/lib/registry.ts +70 -0
- package/extensions/modules/attachments/lib/settings.ts +99 -0
- package/extensions/modules/attachments/lib/tray.ts +74 -0
- package/extensions/modules/attachments/test/configPanel.test.ts +122 -0
- package/extensions/modules/attachments/test/index.test.ts +870 -0
- package/extensions/modules/attachments/test/module.test.ts +53 -0
- package/extensions/modules/classifier/index.ts +55 -1
- package/extensions/modules/classifier/test/classifier.test.ts +62 -0
- package/extensions/modules/composer/test/module.test.ts +2 -2
- package/extensions/modules/config/index.ts +3 -0
- package/extensions/modules/config/test/renderTools.test.ts +1 -1
- package/extensions/modules/cron/configPanel.ts +103 -0
- package/extensions/modules/cron/index.ts +638 -0
- package/extensions/modules/cron/lib/jobs.ts +201 -0
- package/extensions/modules/cron/lib/schedule.ts +161 -0
- package/extensions/modules/cron/test/cwd-repro.test.ts +98 -0
- package/extensions/modules/cron/test/index.test.ts +859 -0
- package/extensions/modules/cron/test/schedule.test.ts +93 -0
- package/extensions/modules/munin/index.ts +3 -1
- package/extensions/modules/permission/index.ts +567 -0
- package/extensions/modules/permission/test/permission.test.ts +789 -0
- package/extensions/modules/plan/index.ts +5 -0
- package/extensions/modules/repair/index.ts +160 -5
- package/extensions/modules/repair/test/freshness.test.ts +209 -0
- package/extensions/modules/repair/test/guard-selector.test.ts +67 -0
- package/extensions/modules/router/configPanel.ts +4 -4
- package/extensions/modules/router/index.ts +1 -1
- package/extensions/modules/router/lib/config.ts +9 -4
- package/extensions/modules/router/lib/systemone.ts +17 -4
- package/extensions/modules/router/test/unit.test.ts +46 -1
- package/extensions/modules/rules/index.ts +13 -3
- package/extensions/modules/rules/lib/rules.ts +24 -12
- package/extensions/modules/rules/test/lib.test.ts +20 -0
- package/extensions/modules/rules/test/module.test.ts +21 -0
- package/extensions/modules/subagent/index.ts +49 -10
- package/extensions/modules/subagent/lib/herdr.ts +5 -0
- package/extensions/modules/subagent/lib/routing.ts +31 -8
- package/extensions/modules/subagent/lib/runner.ts +356 -14
- package/extensions/modules/subagent/test/routing.test.ts +45 -0
- package/extensions/modules/subagent/test/worktree.test.ts +230 -0
- package/extensions/modules/usage/index.ts +193 -71
- package/extensions/modules/usage/test/context.test.ts +160 -120
- package/extensions/modules/web/configPanel.ts +67 -8
- package/extensions/modules/web/index.ts +3 -1
- package/extensions/modules/web/test/a11y.test.ts +1 -1
- package/extensions/modules/web/test/configPanel.test.ts +7 -3
- package/extensions/modules/web/test/settings.test.ts +6 -0
- package/package.json +2 -2
- package/skills/cron/SKILL.md +58 -0
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
// Job store: <agentDir>/cron/jobs.json. Atomic writes (tmp+rename), corrupt
|
|
2
|
+
// files quarantined (never crash), all mutators take a `now` for testability.
|
|
3
|
+
// Layout follows Hermes' proven ~/.hermes/cron/jobs.json pattern.
|
|
4
|
+
import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
|
|
5
|
+
import { join } from "node:path";
|
|
6
|
+
import { nextFire, validateSchedule } from "./schedule.ts";
|
|
7
|
+
|
|
8
|
+
export interface CronJob {
|
|
9
|
+
name: string;
|
|
10
|
+
schedule: string; // 5-field cron expression
|
|
11
|
+
prompt: string; // fired as a follow-up turn
|
|
12
|
+
cwd: string; // recorded working dir (used by `export`)
|
|
13
|
+
enabled: boolean;
|
|
14
|
+
nextRun: number; // epoch ms
|
|
15
|
+
lastRun?: number; // epoch ms
|
|
16
|
+
/** pi --model pattern ("provider/id", optionally "id:level"). Set → job runs headless. */
|
|
17
|
+
model?: string;
|
|
18
|
+
/** Thinking level pin: off|minimal|low|medium|high|xhigh|max. */
|
|
19
|
+
thinking?: string;
|
|
20
|
+
/** Outcome of the most recent pinned run (unpinned: "ok" = delivered). */
|
|
21
|
+
lastStatus?: "ok" | "fail";
|
|
22
|
+
/** Failure reason (truncated) when lastStatus is "fail". */
|
|
23
|
+
lastError?: string;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export const THINKING_LEVELS = ["off", "minimal", "low", "medium", "high", "xhigh", "max"] as const;
|
|
27
|
+
|
|
28
|
+
export const MAX_JOBS = 20;
|
|
29
|
+
const NAME_RE = /^[\w.-]{1,64}$/;
|
|
30
|
+
|
|
31
|
+
export function jobsDir(agentDir: string): string {
|
|
32
|
+
return join(agentDir, "cron");
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function jobsPath(dir: string): string {
|
|
36
|
+
return join(dir, "jobs.json");
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function isJob(v: unknown): v is CronJob {
|
|
40
|
+
const j = v as CronJob;
|
|
41
|
+
if (
|
|
42
|
+
!j ||
|
|
43
|
+
typeof j.name !== "string" ||
|
|
44
|
+
typeof j.schedule !== "string" ||
|
|
45
|
+
typeof j.prompt !== "string" ||
|
|
46
|
+
typeof j.cwd !== "string" ||
|
|
47
|
+
typeof j.enabled !== "boolean" ||
|
|
48
|
+
typeof j.nextRun !== "number"
|
|
49
|
+
) {
|
|
50
|
+
return false;
|
|
51
|
+
}
|
|
52
|
+
// Hand-edited/corrupt files must not smuggle shell metachars into crontab
|
|
53
|
+
// export lines: schedule (unquoted) AND name (export comment + log filename)
|
|
54
|
+
// are name/charset-validated; pins must be strings when present.
|
|
55
|
+
if (!NAME_RE.test(j.name)) return false;
|
|
56
|
+
const fields = j.schedule.trim().split(/\s+/);
|
|
57
|
+
if (fields.length !== 5 || fields.some((f) => !/^[\dA-Za-z\*\/\,\-]+$/.test(f))) return false;
|
|
58
|
+
if (j.model !== undefined && (typeof j.model !== "string" || j.model.trim() === "")) return false;
|
|
59
|
+
if (j.thinking !== undefined && (typeof j.thinking !== "string" || !THINKING_LEVELS.includes(j.thinking as (typeof THINKING_LEVELS)[number]))) return false;
|
|
60
|
+
if (j.lastStatus !== undefined && j.lastStatus !== "ok" && j.lastStatus !== "fail") return false;
|
|
61
|
+
return true;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export function loadJobs(dir: string): CronJob[] {
|
|
65
|
+
let raw: string;
|
|
66
|
+
try {
|
|
67
|
+
raw = readFileSync(jobsPath(dir), "utf8");
|
|
68
|
+
} catch {
|
|
69
|
+
return []; // missing file = no jobs
|
|
70
|
+
}
|
|
71
|
+
try {
|
|
72
|
+
const parsed = JSON.parse(raw) as { jobs?: unknown };
|
|
73
|
+
if (!Array.isArray(parsed?.jobs)) throw new Error("bad shape");
|
|
74
|
+
return parsed.jobs.filter(isJob);
|
|
75
|
+
} catch {
|
|
76
|
+
// Quarantine and start empty — a corrupt file must never wedge the agent.
|
|
77
|
+
try {
|
|
78
|
+
renameSync(jobsPath(dir), join(dir, `jobs.corrupt-${Date.now()}.json`));
|
|
79
|
+
} catch {
|
|
80
|
+
// rename race — next tick re-detects
|
|
81
|
+
}
|
|
82
|
+
return [];
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export function saveJobs(dir: string, jobs: CronJob[]): void {
|
|
87
|
+
// ponytail: no cross-process lock — single session per agentDir assumed;
|
|
88
|
+
// concurrent sessions can lose edits/double-fire (documented in README).
|
|
89
|
+
mkdirSync(dir, { recursive: true });
|
|
90
|
+
const tmp = join(dir, `.jobs.json.tmp-${process.pid}`);
|
|
91
|
+
writeFileSync(tmp, JSON.stringify({ jobs }, null, 2) + "\n");
|
|
92
|
+
renameSync(tmp, jobsPath(dir));
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export function findJob(jobs: CronJob[], name: string): CronJob | undefined {
|
|
96
|
+
return jobs.find((j) => j.name === name);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
export function addJob(
|
|
100
|
+
dir: string,
|
|
101
|
+
input: { name?: string; schedule?: string; prompt?: string; cwd?: string; enabled?: boolean; model?: string; thinking?: string },
|
|
102
|
+
now: number,
|
|
103
|
+
): CronJob {
|
|
104
|
+
const name = (input.name ?? "").trim();
|
|
105
|
+
if (!NAME_RE.test(name)) {
|
|
106
|
+
throw new Error(`Invalid job name ${JSON.stringify(input.name ?? "")} — allowed: letters, digits, _ . - (max 64 chars).`);
|
|
107
|
+
}
|
|
108
|
+
const jobs = loadJobs(dir);
|
|
109
|
+
if (jobs.some((j) => j.name === name)) {
|
|
110
|
+
throw new Error(`Job '${name}' already exists — remove it first (cron action:"remove" name:"${name}").`);
|
|
111
|
+
}
|
|
112
|
+
if (jobs.length >= MAX_JOBS) {
|
|
113
|
+
throw new Error(`Job cap reached (${MAX_JOBS}) — remove one first.`);
|
|
114
|
+
}
|
|
115
|
+
const schedule = (input.schedule ?? "").trim();
|
|
116
|
+
const schedErr = validateSchedule(schedule);
|
|
117
|
+
if (schedErr) throw new Error(`Invalid cron schedule '${schedule}': ${schedErr}`);
|
|
118
|
+
const prompt = (input.prompt ?? "").trim();
|
|
119
|
+
if (!prompt) throw new Error("Prompt is required — it becomes the fired turn.");
|
|
120
|
+
const nf = nextFire(schedule, new Date(now));
|
|
121
|
+
if (!nf) throw new Error(`Schedule '${schedule}' has no future fire time.`);
|
|
122
|
+
const model = input.model?.trim();
|
|
123
|
+
if (input.model !== undefined && !model) throw new Error("Model pin must be a non-empty pattern (e.g. 'zai-anthropic/glm-5.3-flash').");
|
|
124
|
+
const thinking = input.thinking?.trim().toLowerCase();
|
|
125
|
+
if (thinking && !THINKING_LEVELS.includes(thinking as (typeof THINKING_LEVELS)[number])) {
|
|
126
|
+
throw new Error(`Invalid thinking level '${input.thinking}' — allowed: ${THINKING_LEVELS.join(", ")}.`);
|
|
127
|
+
}
|
|
128
|
+
const job: CronJob = {
|
|
129
|
+
name,
|
|
130
|
+
schedule,
|
|
131
|
+
prompt,
|
|
132
|
+
cwd: input.cwd ?? process.cwd(),
|
|
133
|
+
enabled: input.enabled !== false,
|
|
134
|
+
nextRun: nf.getTime(),
|
|
135
|
+
...(model ? { model } : {}),
|
|
136
|
+
...(thinking ? { thinking } : {}),
|
|
137
|
+
};
|
|
138
|
+
jobs.push(job);
|
|
139
|
+
saveJobs(dir, jobs);
|
|
140
|
+
return job;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
export function removeJob(dir: string, name: string): boolean {
|
|
144
|
+
const jobs = loadJobs(dir);
|
|
145
|
+
const next = jobs.filter((j) => j.name !== name);
|
|
146
|
+
if (next.length === jobs.length) return false;
|
|
147
|
+
saveJobs(dir, next);
|
|
148
|
+
return true;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
export function dueJobs(jobs: CronJob[], now: number): CronJob[] {
|
|
152
|
+
return jobs.filter((j) => j.enabled && now >= j.nextRun);
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/**
|
|
156
|
+
* Enable/disable a job (reload-modify-save). Enabling recomputes nextRun from
|
|
157
|
+
* now: a parked job (markFired sets nextRun=MAX_SAFE_INTEGER) would otherwise
|
|
158
|
+
* never fire again, and a long-disabled job would catch-up-fire once on the
|
|
159
|
+
* next tick instead of resuming at its next future occurrence.
|
|
160
|
+
*/
|
|
161
|
+
export function setJobEnabled(dir: string, name: string, enabled: boolean, now: number): CronJob {
|
|
162
|
+
const jobs = loadJobs(dir);
|
|
163
|
+
const job = findJob(jobs, name);
|
|
164
|
+
if (!job) throw new Error(`No job named '${name}'.`);
|
|
165
|
+
if (enabled && !job.enabled) {
|
|
166
|
+
const nf = nextFire(job.schedule, new Date(now));
|
|
167
|
+
if (!nf) {
|
|
168
|
+
throw new Error(`Job '${name}' cannot be enabled — schedule '${job.schedule}' has no future fire time.`);
|
|
169
|
+
}
|
|
170
|
+
job.nextRun = nf.getTime();
|
|
171
|
+
}
|
|
172
|
+
job.enabled = enabled;
|
|
173
|
+
saveJobs(dir, jobs);
|
|
174
|
+
return job;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/** Persist the outcome of a job's most recent fire (reload-modify-save). */
|
|
178
|
+
export function setJobResult(dir: string, name: string, status: "ok" | "fail", error?: string): void {
|
|
179
|
+
const jobs = loadJobs(dir);
|
|
180
|
+
const job = findJob(jobs, name);
|
|
181
|
+
if (!job) return;
|
|
182
|
+
job.lastStatus = status;
|
|
183
|
+
if (error) job.lastError = error.slice(0, 200);
|
|
184
|
+
else delete job.lastError;
|
|
185
|
+
saveJobs(dir, jobs);
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/**
|
|
189
|
+
* Record a fire: lastRun=now, nextRun advances past `now` (skipping missed
|
|
190
|
+
* intermediates). A schedule with no future fire is parked disabled.
|
|
191
|
+
*/
|
|
192
|
+
export function markFired(job: CronJob, now: number): void {
|
|
193
|
+
job.lastRun = now;
|
|
194
|
+
const nf = nextFire(job.schedule, new Date(now));
|
|
195
|
+
if (nf) {
|
|
196
|
+
job.nextRun = nf.getTime();
|
|
197
|
+
} else {
|
|
198
|
+
job.enabled = false;
|
|
199
|
+
job.nextRun = Number.MAX_SAFE_INTEGER;
|
|
200
|
+
}
|
|
201
|
+
}
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
// Cron schedule math — hand-rolled 5-field matcher. One file so the
|
|
2
|
+
// implementation can be swapped without touching callers (upstream shipped
|
|
3
|
+
// cron-parser here; swapped per the ceulen zero-runtime-deps policy —
|
|
4
|
+
// cron-parser hard-depends on luxon, ~4.5MB, for timezone machinery a
|
|
5
|
+
// local-time session scheduler never needs).
|
|
6
|
+
//
|
|
7
|
+
// ponytail: minute-scan nextFire (≤527k iterations for a never-matching expr,
|
|
8
|
+
// typical fire <2k) — field-index jump if profiling ever demands it.
|
|
9
|
+
//
|
|
10
|
+
// Semantics (POSIX vixie-cron):
|
|
11
|
+
// fields: minute hour day-of-month month day-of-week
|
|
12
|
+
// each: * | */step | a | a-b | a-b/step | a,b,c (lists of any member)
|
|
13
|
+
// names: jan..dec, sun..sat (case-insensitive); dow 0 and 7 both = Sunday
|
|
14
|
+
// OR rule: when BOTH dom and dow are restricted (neither `*`-only), a day
|
|
15
|
+
// matches if EITHER field matches — the one vixie-cron quirk hand-rolls
|
|
16
|
+
// usually get wrong.
|
|
17
|
+
// No seconds / year / L / # / TZ — rejected by validate.
|
|
18
|
+
|
|
19
|
+
/** One parsed field: the set of allowed integers within the field's range. */
|
|
20
|
+
type Field = Set<number>;
|
|
21
|
+
|
|
22
|
+
interface FieldSpec {
|
|
23
|
+
min: number;
|
|
24
|
+
max: number;
|
|
25
|
+
/** Extra alias both modulo (0/7 → Sunday) and names resolve against. */
|
|
26
|
+
names?: Record<string, number>;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
const SPECS: FieldSpec[] = [
|
|
30
|
+
{ min: 0, max: 59 },
|
|
31
|
+
{ min: 0, max: 23 },
|
|
32
|
+
{ min: 1, max: 31 },
|
|
33
|
+
{
|
|
34
|
+
min: 1,
|
|
35
|
+
max: 12,
|
|
36
|
+
names: { jan: 1, feb: 2, mar: 3, apr: 4, may: 5, jun: 6, jul: 7, aug: 8, sep: 9, oct: 10, nov: 11, dec: 12 },
|
|
37
|
+
},
|
|
38
|
+
{
|
|
39
|
+
min: 0,
|
|
40
|
+
max: 7,
|
|
41
|
+
names: { sun: 0, mon: 1, tue: 2, wed: 3, thu: 4, fri: 5, sat: 6 },
|
|
42
|
+
},
|
|
43
|
+
];
|
|
44
|
+
|
|
45
|
+
/** Expand one comma-separated member (`*`, `n`, `a-b`, with optional `/step`)
|
|
46
|
+
* into allowed values. Throws with a human message on garbage. */
|
|
47
|
+
function expandMember(member: string, spec: FieldSpec): number[] {
|
|
48
|
+
// Atoms are digits or 3-letter names (jan..dec / sun..sat); `*` only alone.
|
|
49
|
+
const m = member.match(/^(\*|[a-z\d]+)(?:-([a-z\d]+))?(?:\/(\d+))?$/);
|
|
50
|
+
if (!m) throw new Error(`bad cron member '${member}'`);
|
|
51
|
+
const step = m[3] !== undefined ? Number(m[3]) : 1;
|
|
52
|
+
if (!Number.isInteger(step) || step < 1) throw new Error(`bad cron step in '${member}'`);
|
|
53
|
+
let lo: number;
|
|
54
|
+
let hi: number;
|
|
55
|
+
if (m[1] === "*") {
|
|
56
|
+
lo = spec.min;
|
|
57
|
+
hi = spec.max;
|
|
58
|
+
} else {
|
|
59
|
+
lo = resolveAtom(m[1], spec);
|
|
60
|
+
hi = m[2] !== undefined ? resolveAtom(m[2], spec) : lo;
|
|
61
|
+
}
|
|
62
|
+
if (m[2] !== undefined && hi < lo) throw new Error(`bad cron range '${member}'`);
|
|
63
|
+
const out: number[] = [];
|
|
64
|
+
for (let v = lo; v <= hi; v += step) out.push(v);
|
|
65
|
+
return out;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** Resolve one atom: name alias or integer. Dow 7 folds to 0 (Sunday). */
|
|
69
|
+
function resolveAtom(atom: string, spec: FieldSpec): number {
|
|
70
|
+
const lower = atom.toLowerCase();
|
|
71
|
+
const v = spec.names?.[lower] ?? (/^\d+$/.test(atom) ? Number(atom) : NaN);
|
|
72
|
+
if (!Number.isInteger(v) || v < spec.min || v > spec.max) {
|
|
73
|
+
throw new Error(`cron value ${atom} out of range ${spec.min}-${spec.max}`);
|
|
74
|
+
}
|
|
75
|
+
return spec.names && v === 7 ? 0 : v;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** Parse one 5-field expression into per-field value sets.
|
|
79
|
+
* Exported for tests. */
|
|
80
|
+
export function parseSchedule(expr: string): Field[] {
|
|
81
|
+
const fields = expr.trim().split(/\s+/);
|
|
82
|
+
if (fields.length !== 5) {
|
|
83
|
+
throw new Error("expected 5 fields (minute hour day-of-month month day-of-week), e.g. '0 9 * * mon'");
|
|
84
|
+
}
|
|
85
|
+
return fields.map((f, i) => {
|
|
86
|
+
const spec = SPECS[i]!;
|
|
87
|
+
const set: Field = new Set();
|
|
88
|
+
for (const member of f.split(",")) {
|
|
89
|
+
if (!member) throw new Error(`empty cron member in '${f}'`);
|
|
90
|
+
for (const v of expandMember(member, spec)) set.add(v);
|
|
91
|
+
}
|
|
92
|
+
if (set.size === 0) throw new Error(`cron field '${f}' matches nothing`);
|
|
93
|
+
return set;
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** True when a field spec is "restricted" for the dom/dow OR rule: any member
|
|
98
|
+
* other than a bare star (`*` alone; a step like star-slash-2 counts as
|
|
99
|
+
* restricted). */
|
|
100
|
+
function isRestricted(member: string): boolean {
|
|
101
|
+
return member.trim() !== "*";
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** Day matches when dom OR dow matches — but ONLY when both fields are
|
|
105
|
+
* restricted; with either unrestricted, standard AND semantics apply. */
|
|
106
|
+
function dayMatches(dom: Field, dow: Field, domRestricted: boolean, dowRestricted: boolean, date: Date): boolean {
|
|
107
|
+
const domHit = dom.has(date.getDate());
|
|
108
|
+
const dowHit = dow.has(date.getDay());
|
|
109
|
+
if (domRestricted && dowRestricted) return domHit || dowHit;
|
|
110
|
+
return domHit && dowHit;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
export function validateSchedule(expr: string): string | null {
|
|
114
|
+
try {
|
|
115
|
+
parseSchedule(expr);
|
|
116
|
+
return null;
|
|
117
|
+
} catch (e) {
|
|
118
|
+
return e instanceof Error ? e.message : String(e);
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
export function nextFire(expr: string, from: Date): Date | null {
|
|
123
|
+
let fields: Field[];
|
|
124
|
+
let domRestricted: boolean;
|
|
125
|
+
let dowRestricted: boolean;
|
|
126
|
+
try {
|
|
127
|
+
fields = parseSchedule(expr);
|
|
128
|
+
const members = expr.trim().split(/\s+/);
|
|
129
|
+
domRestricted = isRestricted(members[2]!);
|
|
130
|
+
dowRestricted = isRestricted(members[4]!);
|
|
131
|
+
} catch {
|
|
132
|
+
return null;
|
|
133
|
+
}
|
|
134
|
+
const t = new Date(from.getTime());
|
|
135
|
+
t.setSeconds(0, 0);
|
|
136
|
+
const cap = new Date(t.getTime());
|
|
137
|
+
// 4 years = the full leap cycle — "0 0 29 2 *" must find its next fire from
|
|
138
|
+
// any start date; never-firing exprs (Feb 30) scan ~2.1M cheap set checks.
|
|
139
|
+
cap.setFullYear(cap.getFullYear() + 4);
|
|
140
|
+
for (;;) {
|
|
141
|
+
t.setMinutes(t.getMinutes() + 1);
|
|
142
|
+
if (t > cap) return null; // e.g. Feb 30 — never fires
|
|
143
|
+
if (!fields[0]!.has(t.getMinutes())) continue;
|
|
144
|
+
if (!fields[1]!.has(t.getHours())) continue;
|
|
145
|
+
if (!fields[3]!.has(t.getMonth() + 1)) continue; // Date months are 0-11; specs are 1-12
|
|
146
|
+
if (!dayMatches(fields[2]!, fields[4]!, domRestricted, dowRestricted, t)) continue;
|
|
147
|
+
return new Date(t.getTime());
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
export function nextFires(expr: string, n: number, from: Date): Date[] {
|
|
152
|
+
const out: Date[] = [];
|
|
153
|
+
let cursor = from;
|
|
154
|
+
for (let i = 0; i < n; i++) {
|
|
155
|
+
const next = nextFire(expr, cursor);
|
|
156
|
+
if (!next) break;
|
|
157
|
+
out.push(next);
|
|
158
|
+
cursor = next;
|
|
159
|
+
}
|
|
160
|
+
return out;
|
|
161
|
+
}
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Regression: wrong-cwd delivery of unpinned cron fires.
|
|
3
|
+
*
|
|
4
|
+
* Bug (fixed in fire()): jobs.json is global to the agent dir. Any open pi
|
|
5
|
+
* session sharing the agent dir runs the 30s tickOnce() scheduler, and
|
|
6
|
+
* whichever session ticks first fires the job — including a session whose cwd
|
|
7
|
+
* differs from job.cwd. Unpinned fires were delivered as follow-up turns into
|
|
8
|
+
* THAT session (deliverFire → sendMessage), so the prompt ran under the wrong
|
|
9
|
+
* cwd. job.cwd was only honored by runHeadless (pinned jobs) and `export`.
|
|
10
|
+
*
|
|
11
|
+
* Driven at the seam where the fix landed: the real extension's fire()
|
|
12
|
+
* closure, reached via the cron tool's execute() with a foreign-session cwd.
|
|
13
|
+
* Both the ctx.cwd passed here AND process.cwd() point at the foreign session
|
|
14
|
+
* (pi's session cwd is process.cwd()). The scheduler tick routes through the
|
|
15
|
+
* same fire() closure, so pinning execute() pins both paths.
|
|
16
|
+
*/
|
|
17
|
+
import assert from "node:assert/strict";
|
|
18
|
+
import { mkdtempSync, readFileSync, realpathSync } from "node:fs";
|
|
19
|
+
import { tmpdir } from "node:os";
|
|
20
|
+
import { join } from "node:path";
|
|
21
|
+
import { describe, it } from "node:test";
|
|
22
|
+
import cronExtension from "../index.ts";
|
|
23
|
+
import { loadJobs, saveJobs } from "../lib/jobs.ts";
|
|
24
|
+
|
|
25
|
+
describe("cwd guard — unpinned fires must not run in a foreign-cwd session", () => {
|
|
26
|
+
it("does NOT deliver a due job into a session whose cwd differs from job.cwd", async () => {
|
|
27
|
+
const agentDir = mkdtempSync(join(tmpdir(), "ceulen-cron-cwd-agent-"));
|
|
28
|
+
const jobCwd = realpathSync(mkdtempSync(join(tmpdir(), "ceulen-cron-cwd-job-")));
|
|
29
|
+
const sessionCwd = realpathSync(mkdtempSync(join(tmpdir(), "ceulen-cron-cwd-session-")));
|
|
30
|
+
|
|
31
|
+
const prevAgentDir = process.env.PI_CODING_AGENT_DIR;
|
|
32
|
+
// Hermetic: a cron-fired headless session exports PI_CRON_DISABLED=1, which
|
|
33
|
+
// makes the mutation loop-guard refuse action:"add". Save + strip it for the
|
|
34
|
+
// test body; restore it in the finally below.
|
|
35
|
+
const prevCronDisabled = process.env.PI_CRON_DISABLED;
|
|
36
|
+
delete process.env.PI_CRON_DISABLED;
|
|
37
|
+
const prevCwd = process.cwd();
|
|
38
|
+
process.env.PI_CODING_AGENT_DIR = agentDir;
|
|
39
|
+
const sent: unknown[] = [];
|
|
40
|
+
// Minimal ExtensionAPI stand-in: capture the registered cron tool + sendMessage.
|
|
41
|
+
let execute!: (...args: unknown[]) => Promise<unknown>;
|
|
42
|
+
const fakePi = {
|
|
43
|
+
registerTool: (t: { execute: (...args: unknown[]) => Promise<unknown> }) => {
|
|
44
|
+
execute = t.execute;
|
|
45
|
+
},
|
|
46
|
+
registerCommand: () => {},
|
|
47
|
+
on: () => {},
|
|
48
|
+
sendMessage: (...args: unknown[]) => {
|
|
49
|
+
sent.push(args);
|
|
50
|
+
},
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
try {
|
|
54
|
+
cronExtension(fakePi as never);
|
|
55
|
+
|
|
56
|
+
// Session A (cwd = jobCwd) adds the job; cwd is recorded from ctx.
|
|
57
|
+
execute(undefined, { action: "add", name: "a", schedule: "* * * * *", prompt: "list files" }, undefined, undefined, {
|
|
58
|
+
cwd: jobCwd,
|
|
59
|
+
});
|
|
60
|
+
const store = join(agentDir, "cron");
|
|
61
|
+
assert.equal(loadJobs(store)[0]!.cwd, jobCwd, "job records the adding session's cwd");
|
|
62
|
+
|
|
63
|
+
// Make the job due now.
|
|
64
|
+
const jobs = loadJobs(store);
|
|
65
|
+
jobs[0]!.nextRun = 1;
|
|
66
|
+
saveJobs(store, jobs);
|
|
67
|
+
assert.ok(JSON.parse(readFileSync(join(store, "jobs.json"), "utf8")).jobs.length, "store on disk");
|
|
68
|
+
|
|
69
|
+
// Foreign session (cwd = sessionCwd) fires it — process chdir'd to match
|
|
70
|
+
// pi's real shape, so both candidate fix sources (ctx.cwd, process.cwd())
|
|
71
|
+
// agree this is the WRONG session for the job.
|
|
72
|
+
process.chdir(sessionCwd);
|
|
73
|
+
// Await the run: action:"run" on a cwd-mismatched job THROWS (recorded as
|
|
74
|
+
// a failed result) — an unawaited rejection is async activity after the
|
|
75
|
+
// test ends (unhandledRejection) and fails the suite spuriously.
|
|
76
|
+
await assert.rejects(
|
|
77
|
+
execute(undefined, { action: "run", name: "a" }, undefined, undefined, { cwd: sessionCwd }) as Promise<unknown>,
|
|
78
|
+
/cwd mismatch/,
|
|
79
|
+
);
|
|
80
|
+
|
|
81
|
+
// THE ASSERTION: delivery into the foreign session is the bug.
|
|
82
|
+
assert.deepEqual(
|
|
83
|
+
sent.map((a) => ((a as unknown[])[0] as { customType?: string }).customType),
|
|
84
|
+
[],
|
|
85
|
+
"no follow-up turn may be injected into a session whose cwd !== job.cwd",
|
|
86
|
+
);
|
|
87
|
+
assert.equal(loadJobs(store)[0]!.lastStatus, "fail", "skip is visible as a failed result, not a silent drop");
|
|
88
|
+
} finally {
|
|
89
|
+
process.chdir(prevCwd);
|
|
90
|
+
process.env.PI_CODING_AGENT_DIR = prevAgentDir;
|
|
91
|
+
if (prevCronDisabled === undefined) {
|
|
92
|
+
delete process.env.PI_CRON_DISABLED;
|
|
93
|
+
} else {
|
|
94
|
+
process.env.PI_CRON_DISABLED = prevCronDisabled;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
});
|
|
98
|
+
});
|