crewboss 0.0.0-stage → 0.3.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.
@@ -0,0 +1,160 @@
1
+ /**
2
+ * Presence of main sessions. Claude Code hooks can call
3
+ * `crewboss presence busy|idle|gone` (UserPromptSubmit, Stop, SessionEnd);
4
+ * runs launched with `--notify <session>` are linked to that session.
5
+ *
6
+ * A hook must never break the session it hangs from, so `crewboss presence` is silent, fast and
7
+ * always exits 0: its errors only go to a log file. crewboss's own agents are Claude sessions too,
8
+ * so with CREWBOSS_RUN_ID in the environment the command does nothing.
9
+ */
10
+ import fs from 'node:fs';
11
+ import os from 'node:os';
12
+ import path from 'node:path';
13
+
14
+ import { findConfig, loadConfig } from './config.js';
15
+ import { RUN_ID_ENV } from './events.js';
16
+ import { sessionFromEnv, UDS_PREFIX } from './session.js';
17
+ import { isoNow } from './rundir.js';
18
+ import { openStore, PRESENCE_STATES } from './store.js';
19
+
20
+ export const PRESENCE_ACTIONS = [...PRESENCE_STATES, 'gone'];
21
+ /** A presence nobody updated for this long is gone (a busy session may think for a long time). */
22
+ export const IDLE_TTL_MS = 15 * 60 * 1000;
23
+ export const BUSY_TTL_MS = 60 * 60 * 1000;
24
+ export const LOG_NAME = 'presence.log';
25
+ const STDIN_TIMEOUT_MS = 1000;
26
+ const SESSION_RE = /^[^\s\u0000-\u001f]{1,100}$/;
27
+
28
+ /** Milliseconds since `updated_at` (Infinity if the row has no valid date). */
29
+ function ageOf(row, now) {
30
+ const time = Date.parse(row?.updated_at);
31
+ return Number.isNaN(time) ? Infinity : now - time;
32
+ }
33
+
34
+ /** True while a presence row is still valid: updated within its TTL (15 min idle, 60 min busy). */
35
+ export function isPresent(row, now = Date.now()) {
36
+ return ageOf(row, now) <= (row.state === 'busy' ? BUSY_TTL_MS : IDLE_TTL_MS);
37
+ }
38
+
39
+ /** The rows of `store` that are still present, oldest start first. */
40
+ export function livePresence(store, now = Date.now()) {
41
+ return store.listPresence().filter((row) => isPresent(row, now));
42
+ }
43
+
44
+ /** The short, stable part of an identity: `uds:/tmp/cc-socks/61164.sock` -> `61164`, `claude-3f2a9c1d` -> `3f2a`. */
45
+ export function identitySuffix(session) {
46
+ const text = String(session ?? '');
47
+ if (text.startsWith(UDS_PREFIX)) {
48
+ const base = path.basename(text.slice(UDS_PREFIX.length)).replace(/\.[^.]*$/, '').replace(/[^A-Za-z0-9]/g, '');
49
+ return base.slice(-6);
50
+ }
51
+ const id = text.replace(/^claude-/, '').replace(/[^A-Za-z0-9]/g, '');
52
+ return id.slice(0, 4);
53
+ }
54
+
55
+ /**
56
+ * The name shown for a presence: `label` if given; else, for an identity crewboss derived (a socket
57
+ * address or `claude-<id>`), the name of the folder of `cwd` plus the short suffix of the identity
58
+ * (`Workspace·61164`); a session the user named with `--session` shows that name. Never the socket path.
59
+ */
60
+ export function presenceLabel({ session, cwd = '', label = '' }) {
61
+ const given = String(label ?? '').trim();
62
+ if (given) return given;
63
+ const derived = String(session).startsWith(UDS_PREFIX) || /^claude-/.test(String(session));
64
+ if (!derived) return String(session);
65
+ const folder = path.basename(String(cwd ?? '').replace(/[\\/]+$/, ''));
66
+ const suffix = identitySuffix(session);
67
+ return [folder, suffix].filter(Boolean).join('·') || 'session';
68
+ }
69
+
70
+ /**
71
+ * The name of a session when neither `--session` nor the messaging socket is available: `claude-` plus the first 8 characters of the
72
+ * `session_id` that Claude Code sends to hooks on stdin (for example `claude-3f2a9c1d`). The main
73
+ * session can pass a friendlier name with `--session` (the one `ListAgents` shows, e.g. `workspace-fd`),
74
+ * which is also the one to give `crewboss agent --notify`.
75
+ */
76
+ export function sessionFromHook(input) {
77
+ const id = typeof input?.session_id === 'string' ? input.session_id.replace(/[^A-Za-z0-9_-]/g, '') : '';
78
+ return id ? `claude-${id.slice(0, 8)}` : null;
79
+ }
80
+
81
+ /** The JSON object Claude Code sends to a hook on stdin; {} if the text is empty or not an object. */
82
+ export function parseHookInput(text) {
83
+ try {
84
+ const value = JSON.parse(text);
85
+ return value && typeof value === 'object' && !Array.isArray(value) ? value : {};
86
+ } catch {
87
+ return {};
88
+ }
89
+ }
90
+
91
+ /** What stdin holds, read for at most `timeoutMs`; '' for a terminal or an unreadable stream. */
92
+ export function readStdin(stream, timeoutMs = STDIN_TIMEOUT_MS) {
93
+ if (!stream || stream.isTTY) return Promise.resolve('');
94
+ return new Promise((resolve) => {
95
+ const chunks = [];
96
+ let timer = null;
97
+ const done = () => {
98
+ clearTimeout(timer);
99
+ stream.off?.('data', onData);
100
+ resolve(Buffer.concat(chunks).toString('utf8'));
101
+ };
102
+ const onData = (chunk) => chunks.push(Buffer.from(chunk));
103
+ timer = setTimeout(done, timeoutMs);
104
+ stream.on('data', onData);
105
+ stream.once('end', done);
106
+ stream.once('error', done);
107
+ });
108
+ }
109
+
110
+ /** Append a line to the presence log; never throws. */
111
+ export function logPresenceError(file, message) {
112
+ try {
113
+ fs.mkdirSync(path.dirname(file), { recursive: true });
114
+ fs.appendFileSync(file, `${isoNow()} ${String(message).replace(/\s*\n\s*/g, ' ')}\n`);
115
+ } catch {
116
+ // nothing else can be done: a hook stays silent
117
+ }
118
+ }
119
+
120
+ /**
121
+ * Run `crewboss presence <action>`. Resolves with 0 always, writing nothing to stdout or stderr.
122
+ * `args`: {action, session?, cwd?, label?}. The session is `--session`, else `uds:<$CLAUDE_CODE_MESSAGING_SOCKET>`,
123
+ * else read from the hook JSON on stdin (the only case where stdin is read).
124
+ */
125
+ export async function runPresenceCommand(args, {
126
+ configPath = null, env = process.env, cwd = process.cwd(), stdin = process.stdin, store = undefined, now = Date.now,
127
+ } = {}) {
128
+ if (env[RUN_ID_ENV]) return 0;
129
+ let logFile = path.join(os.tmpdir(), LOG_NAME);
130
+ let db = store;
131
+ try {
132
+ const config = loadConfig(findConfig({ cliPath: configPath, env, cwd }));
133
+ logFile = path.join(config.logsDir, LOG_NAME);
134
+ let session = args.session ?? null;
135
+ let dir = args.cwd ?? null;
136
+ session ??= sessionFromEnv(env);
137
+ if (!session) {
138
+ const input = parseHookInput(await readStdin(stdin));
139
+ session ??= sessionFromHook(input);
140
+ dir ??= typeof input.cwd === 'string' ? input.cwd : null;
141
+ }
142
+ if (!session) throw new Error('no session: pass --session <name> or pipe the hook JSON (with session_id) to stdin');
143
+ if (!SESSION_RE.test(session)) throw new Error(`invalid session name '${session}'`);
144
+ db ??= openStore(config.root);
145
+ if (args.action === 'gone') {
146
+ db.removePresence(session);
147
+ } else {
148
+ const where = dir ?? cwd;
149
+ db.setPresence(session, {
150
+ state: args.action, cwd: where, label: presenceLabel({ session, cwd: where, label: args.label }),
151
+ expired: (row) => !isPresent(row, now()),
152
+ });
153
+ }
154
+ } catch (err) {
155
+ logPresenceError(logFile, `presence ${args.action}: ${err.message}`);
156
+ } finally {
157
+ if (!store) db?.close();
158
+ }
159
+ return 0;
160
+ }
package/src/process.js ADDED
@@ -0,0 +1,37 @@
1
+ import { TimeoutError } from './errors.js';
2
+
3
+ /**
4
+ * Wait for a spawned child to close and resolve with its exit code.
5
+ * With a timeout the child must have been spawned with `detached: true`: on expiry
6
+ * its whole process group is killed and the promise rejects with TimeoutError.
7
+ */
8
+ export function waitForExit(child, { timeoutSeconds = null, kill = process.kill.bind(process) } = {}) {
9
+ return new Promise((resolve, reject) => {
10
+ let timedOut = false;
11
+ let timer = null;
12
+ if (timeoutSeconds != null) {
13
+ timer = setTimeout(() => {
14
+ timedOut = true;
15
+ killGroup(child.pid, kill);
16
+ }, timeoutSeconds * 1000);
17
+ }
18
+ child.once('error', (err) => {
19
+ clearTimeout(timer);
20
+ reject(err);
21
+ });
22
+ child.once('close', (code) => {
23
+ clearTimeout(timer);
24
+ if (timedOut) reject(new TimeoutError(`process timed out after ${timeoutSeconds}s`));
25
+ else resolve(code ?? 1);
26
+ });
27
+ });
28
+ }
29
+
30
+ /** SIGKILL a whole process group; ignore it if it is already gone. */
31
+ export function killGroup(pid, kill = process.kill.bind(process)) {
32
+ try {
33
+ kill(-pid, 'SIGKILL');
34
+ } catch (err) {
35
+ if (err.code !== 'ESRCH') throw err;
36
+ }
37
+ }
package/src/quota.js ADDED
@@ -0,0 +1,34 @@
1
+ /** Optional quota plugin: decides whether a candidate must be skipped. */
2
+ import { PluginError } from './errors.js';
3
+ import { runPlugin } from './plugin.js';
4
+
5
+ const isObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
6
+
7
+ /**
8
+ * Build `check(candidate) -> Promise<string | null>` from the `quota` config, or null
9
+ * when there is no plugin. A returned string is the reason to skip the candidate.
10
+ */
11
+ export function makeQuotaChecker(quota, root, { spawn, kill } = {}) {
12
+ if (!quota) return null;
13
+ return async (candidate) => {
14
+ const response = await runPlugin(quota.command, { candidate }, {
15
+ cwd: root, timeoutSeconds: quota.timeout_seconds, spawn, kill,
16
+ });
17
+ if (!isObject(response) || !('skip' in response)
18
+ || (response.skip !== null && typeof response.skip !== 'string')) {
19
+ throw new PluginError('quota plugin must return {"skip": null} or {"skip": "reason"}');
20
+ }
21
+ return response.skip || null;
22
+ };
23
+ }
24
+
25
+ /** Run a quota check, turning a plugin failure into a skip reason. */
26
+ export async function quotaReason(check, candidate) {
27
+ if (!check) return null;
28
+ try {
29
+ const reason = await check(candidate);
30
+ return reason ? `quota limit exceeded: ${reason}` : null;
31
+ } catch (err) {
32
+ return `quota check failed: ${err.message}`;
33
+ }
34
+ }
@@ -0,0 +1,401 @@
1
+ /** Scheduled routines: collect data, run an agent, and publish exactly one report per run. */
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+
5
+ import { formatCandidateLabel, selectCandidates } from './candidates.js';
6
+ import { collectData } from './collect.js';
7
+ import {
8
+ assertCommunicationAllowed, communicationSection, recordFinished, recordStarted, runEnv,
9
+ } from './events.js';
10
+ import { findBinary, writeJson } from './fsutil.js';
11
+ import { acquireLock } from './lock.js';
12
+ import { memorySection, routineReportScopes, routineScopes } from './memory.js';
13
+ import { makeQuotaChecker, quotaReason } from './quota.js';
14
+ import { humanStamp, isoNow, newRunDir } from './rundir.js';
15
+ import * as runners from './runners/index.js';
16
+ import { openStore } from './store.js';
17
+ import { makeTracker } from './trackers/index.js';
18
+
19
+ export const JSON_BLOCK_RE = /```json\s*([\s\S]*?)\s*```/gi;
20
+ const AGENT_STATUSES = ['ok', 'issues'];
21
+ const SEVERITIES = ['high', 'medium', 'low'];
22
+ const TASK_SEVERITIES = new Set(['high', 'medium']);
23
+ const OK_STATUSES = new Set(['ok', 'issues', 'skipped']);
24
+ const INLINE_COLLECT_BYTES = 60_000;
25
+ const DETAILS_BYTES = 50_000;
26
+ const ERROR_TAIL_CHARS = 4000;
27
+ const LOCK_HELD = 'Skipped because the routine lock is held.';
28
+
29
+ const isObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
30
+ const nonEmptyString = (v) => typeof v === 'string' && v.trim() !== '';
31
+
32
+ /**
33
+ * Parse and validate the fenced JSON report at the end of an agent answer. An optional
34
+ * `memory: [{scope, text}]` may only use `memoryScopes` (the routine and its project).
35
+ */
36
+ export function parseReport(answer, { memoryScopes = [] } = {}) {
37
+ const blocks = [...answer.matchAll(JSON_BLOCK_RE)].map((match) => match[1]);
38
+ if (!blocks.length) throw new Error('missing fenced JSON report');
39
+ let report;
40
+ try {
41
+ report = JSON.parse(blocks.at(-1));
42
+ } catch (err) {
43
+ throw new Error(`malformed JSON report: ${err.message}`);
44
+ }
45
+ if (!isObject(report) || !AGENT_STATUSES.includes(report.status)) throw new Error('report needs status ok|issues');
46
+ if (!nonEmptyString(report.summary)) throw new Error('report needs a nonempty summary');
47
+ if (!Array.isArray(report.findings)) throw new Error('report needs findings array');
48
+ for (const finding of report.findings) {
49
+ if (!isObject(finding) || !['title', 'evidence', 'proposal'].every((k) => nonEmptyString(finding[k]))
50
+ || !SEVERITIES.includes(finding.severity)) {
51
+ throw new Error('invalid finding');
52
+ }
53
+ }
54
+ if ('notify' in report) {
55
+ const { notify } = report;
56
+ if (!isObject(notify) || typeof notify.send !== 'boolean' || typeof notify.message !== 'string') {
57
+ throw new Error('notify must contain boolean send and string message');
58
+ }
59
+ }
60
+ if ('memory' in report) {
61
+ if (!Array.isArray(report.memory)) throw new Error('memory must be a list of {scope, text}');
62
+ for (const note of report.memory) {
63
+ if (!isObject(note) || !nonEmptyString(note.text) || typeof note.scope !== 'string') {
64
+ throw new Error('memory must be a list of {scope, text}');
65
+ }
66
+ if (!memoryScopes.includes(note.scope)) {
67
+ throw new Error(`memory scope '${note.scope}' not allowed; use one of: ${memoryScopes.join(', ')}`);
68
+ }
69
+ }
70
+ }
71
+ return report;
72
+ }
73
+
74
+ /** The agent answer without its JSON block. */
75
+ export function agentMarkdown(answer) {
76
+ return answer.replace(JSON_BLOCK_RE, '').trim();
77
+ }
78
+
79
+ export function formatOpenTasks(tasks) {
80
+ if (!tasks.length) return '';
81
+ const lines = ['\n\n# Already known open tasks (do not report again unless something got worse; reference the task id instead)'];
82
+ for (const task of tasks) lines.push(`${task.id}: ${task.title}`);
83
+ return `${lines.join('\n')}\n`;
84
+ }
85
+
86
+ function taskNotes(finding) {
87
+ return `Evidence: ${finding.evidence}\n\nProposal: ${finding.proposal}`;
88
+ }
89
+
90
+ const taskKey = (title, assignee) => JSON.stringify([title, assignee]);
91
+
92
+ /**
93
+ * Decide which high/medium findings need a new task. Dedup is by (title, assignee)
94
+ * against open tasks and within the report. Findings matching an open task get its id.
95
+ */
96
+ export function planTasks(findings, openTasks, assignee) {
97
+ const existing = new Map(openTasks.map((task) => [taskKey(task.title, task.assignee), task.id]));
98
+ const pending = new Map();
99
+ const planned = findings.map((finding) => ({ ...finding }));
100
+ for (const finding of planned) {
101
+ if (!TASK_SEVERITIES.has(finding.severity)) continue;
102
+ const key = taskKey(finding.title, assignee);
103
+ if (existing.has(key)) {
104
+ if (existing.get(key)) finding.task = existing.get(key);
105
+ } else if (!pending.has(key)) {
106
+ pending.set(key, { title: finding.title, notes: taskNotes(finding), priority: finding.severity, assignee });
107
+ }
108
+ }
109
+ return { findings: planned, pending: [...pending.values()] };
110
+ }
111
+
112
+ /**
113
+ * Create the pending tasks, link them to their findings and publish the report.
114
+ * With dryRun, only read open tasks. Resolves with {lines, findings}: the lines describing
115
+ * what was (or would be) written, and the findings with the ids of their tasks.
116
+ */
117
+ export async function publishRoutineReport(tracker, routine, report, { dryRun = false, title, body, status }) {
118
+ const { name, project, assignee } = routine;
119
+ const needsTasks = report.findings.some((finding) => TASK_SEVERITIES.has(finding.severity));
120
+ const openTasks = needsTasks ? await tracker.openTasks(project) : [];
121
+ const { findings, pending } = planTasks(report.findings, openTasks, assignee);
122
+ const lines = [
123
+ `report ${name}: ${title} [${status}]\nSummary: ${report.summary}\n\n${body}`,
124
+ ...pending.map((task) => `task project ${project}: ${task.title} (assignee ${task.assignee})\n${task.notes}`),
125
+ ];
126
+ if (dryRun) return { lines, findings };
127
+ for (const task of pending) {
128
+ const id = await tracker.createTask(project, task.title, task.notes, task.priority, task.assignee);
129
+ for (const finding of findings) {
130
+ if (TASK_SEVERITIES.has(finding.severity) && finding.title === task.title && !finding.task) finding.task = id;
131
+ }
132
+ }
133
+ await tracker.publishReport(project, name, title, status, report.summary, body, findings);
134
+ return { lines, findings };
135
+ }
136
+
137
+ function truncateBytes(text, maxBytes) {
138
+ const buffer = Buffer.from(text, 'utf8');
139
+ if (buffer.length <= maxBytes) return text;
140
+ return buffer.subarray(0, maxBytes).toString('utf8').replace(/�+$/, '');
141
+ }
142
+
143
+ /** Report body: agent markdown, a notify line, and the collected data folded in <details>. */
144
+ export function reportBody(markdown, collected, notify) {
145
+ let body = markdown.trim();
146
+ if (notify) body += `${body ? '\n\n' : ''}Notify: send=${notify.send} — ${notify.message}`;
147
+ if (collected) {
148
+ body += `\n\n<details><summary>Collected data</summary>\n\n\`\`\`text\n${truncateBytes(collected, DETAILS_BYTES)}\n\`\`\`\n</details>`;
149
+ }
150
+ return body;
151
+ }
152
+
153
+ /** Prompt = preamble + routine prompt + open tasks + memory + communication + collected data + mode instruction. */
154
+ export function buildRoutinePrompt(config, routine, {
155
+ openTasks = [], collected = '', collectPath = null, memory = '', communication = '',
156
+ } = {}) {
157
+ let prompt = config.preamble.trim() ? `${config.preamble.trim()}\n\n` : '';
158
+ prompt += fs.readFileSync(routine.promptPath ?? path.resolve(config.root, routine.prompt), 'utf8');
159
+ prompt += formatOpenTasks(openTasks);
160
+ if (memory.trim()) prompt += `\n\n${memory.trim()}\n`;
161
+ if (communication.trim()) prompt += `\n\n${communication.trim()}\n`;
162
+ let attachment = null;
163
+ if (collected) {
164
+ if (Buffer.byteLength(collected, 'utf8') < INLINE_COLLECT_BYTES) {
165
+ prompt += `\n\n# Collected data\n\n${collected}`;
166
+ } else {
167
+ attachment = collectPath;
168
+ prompt += `\n\n# Collected data\nRead the attached context file: ${collectPath}\n`;
169
+ }
170
+ }
171
+ if (routine.mode === 'write') {
172
+ if (config.writeInstructions.trim()) prompt += `\n\n${config.writeInstructions.trim()}`;
173
+ prompt += '\n\nReturn the Markdown report and fenced JSON block specified above, documenting what you changed.\n';
174
+ } else {
175
+ prompt += '\n\nReturn the Markdown report and fenced JSON block specified above. Do not edit files or run writing commands.\n';
176
+ }
177
+ return { prompt, attachment };
178
+ }
179
+
180
+ function tail(file, chars) {
181
+ try {
182
+ return fs.readFileSync(file, 'utf8').slice(-chars);
183
+ } catch {
184
+ return '';
185
+ }
186
+ }
187
+
188
+ function writeStatus(runDir, status, summary) {
189
+ writeJson(path.join(runDir, 'status.json'), { status, summary, time: isoNow() });
190
+ }
191
+
192
+ /**
193
+ * Candidates for a routine: its tier (never paid, filtered by quota) or its fixed
194
+ * tool + model (binary must exist; skipped if the quota plugin says so).
195
+ */
196
+ async function routineCandidates(config, routine, which, quota) {
197
+ if ('size' in routine) {
198
+ const { usable, skipped } = await selectCandidates(routine.size, config.tiers, { allowPaid: false, quota });
199
+ const reasons = skipped.map((s) => `${formatCandidateLabel(s.candidate)}: ${s.reason}`).join('; ');
200
+ return { candidates: usable, skipReason: usable.length ? null : `Skipped because no candidate is usable${reasons ? `: ${reasons}` : ''}` };
201
+ }
202
+ if (!which(routine.tool)) {
203
+ throw new Error(`Required binary '${routine.tool}' not found in PATH: ${process.env.PATH ?? ''}`);
204
+ }
205
+ const candidate = { tool: routine.tool, model: routine.model, paid: false };
206
+ if (routine.effort) candidate.effort = routine.effort;
207
+ const reason = await quotaReason(quota, candidate);
208
+ return { candidates: reason ? [] : [candidate], skipReason: reason ? `Skipped because of ${reason}` : null };
209
+ }
210
+
211
+ function startupFailureMessage(routine, candidates, skipped) {
212
+ const reasons = skipped.map((s) => `${formatCandidateLabel(s.candidate)}: ${s.reason}`).join('; ');
213
+ const head = 'size' in routine
214
+ ? `All candidates in tier '${routine.size}' failed at startup`
215
+ : `Candidate ${formatCandidateLabel(candidates[0])} failed at startup`;
216
+ return reasons ? `${head}: ${reasons}` : head;
217
+ }
218
+
219
+ /**
220
+ * Run one routine under its lock and publish exactly one report (ok, issues, error
221
+ * or skipped). Candidates are filtered by quota and tried with fallback on startup
222
+ * failure. With dryRun the agent always runs in read mode and the tracker is only read.
223
+ * The run, and the report unless dryRun, are always kept in the local history, even
224
+ * when publishing to the tracker fails. Resolves with 0 for ok/issues/skipped and 1 otherwise.
225
+ */
226
+ export async function runRoutine(config, routine, options = {}) {
227
+ const history = options.store ?? openStore(config.root);
228
+ try {
229
+ return await runWithHistory(config, routine, history, options);
230
+ } finally {
231
+ if (!options.store) history.close();
232
+ }
233
+ }
234
+
235
+ async function runWithHistory(config, routine, history, {
236
+ dryRun = false,
237
+ tracker = null,
238
+ launch = runners.launch,
239
+ collect = collectData,
240
+ which = findBinary,
241
+ quota = undefined,
242
+ clock = undefined,
243
+ lock = {},
244
+ stdout = process.stdout,
245
+ stderr = process.stderr,
246
+ } = {}) {
247
+ const { name } = routine;
248
+ const activeTracker = tracker ?? makeTracker(config.tracker, config.root, { store: history });
249
+ const check = quota === undefined ? makeQuotaChecker(config.quota, config.root) : quota;
250
+ const mode = dryRun ? 'read' : routine.mode;
251
+ const base = path.join(config.logsDir, 'routines');
252
+ const title = `${name} ${humanStamp()}`;
253
+ const print = (line) => stdout.write(`${line}\n`);
254
+
255
+ /** Publish to the tracker, then keep the report in the local history (not on dry runs). */
256
+ const publish = async (report, body, status, runId) => {
257
+ let findings = report.findings;
258
+ let published = true;
259
+ try {
260
+ const result = await publishRoutineReport(activeTracker, routine, report, { dryRun, title, body, status });
261
+ findings = result.findings;
262
+ for (const line of result.lines) print(`${dryRun ? 'DRY RUN' : 'POSTED'} ${line}`);
263
+ } catch (err) {
264
+ stderr.write(`${name}: reporting error: ${err.message}\n`);
265
+ published = false;
266
+ }
267
+ if (!dryRun) {
268
+ history.recordReport({ runId, project: routine.project, source: name, title, status, summary: report.summary, body, findings });
269
+ }
270
+ return published;
271
+ };
272
+
273
+ const release = acquireLock(path.join(base, `${name}.lock`), lock);
274
+ if (!release) {
275
+ print(`${name}: skipped: already running`);
276
+ const runId = history.startRun({ kind: 'routine', name, dryRun });
277
+ const report = { status: 'skipped', summary: LOCK_HELD, findings: [] };
278
+ const published = await publish(report, LOCK_HELD, 'skipped', runId);
279
+ history.finishRun(runId, { status: 'skipped', summary: LOCK_HELD });
280
+ recordFinished(history, runId);
281
+ return published ? 0 : 1;
282
+ }
283
+
284
+ try {
285
+ const runDir = newRunDir(path.join(base, name));
286
+ const runId = history.startRun({ kind: 'routine', name, dryRun, logDir: runDir });
287
+ recordStarted(history, runId, `${mode} mode${dryRun ? ' (dry run)' : ''}, project ${routine.project}`);
288
+ let chosen = null;
289
+ let agentExit = null;
290
+ const agentLog = path.join(runDir, 'agent.log');
291
+ const answerPath = path.join(runDir, 'answer.md');
292
+ const collectPath = path.join(runDir, 'collect.txt');
293
+ fs.writeFileSync(agentLog, '', 'utf8');
294
+ let status = 'error';
295
+ let summary = 'unknown error';
296
+ let report = null;
297
+ let markdown = '';
298
+ let collected = '';
299
+
300
+ try {
301
+ const { candidates, skipReason } = await routineCandidates(config, routine, which, check);
302
+ if (skipReason) {
303
+ status = 'skipped';
304
+ summary = skipReason;
305
+ } else {
306
+ if (routine.collect) {
307
+ const timeout = (routine.collect_timeout_minutes ?? 10) * 60;
308
+ collected = await collect(routine.collect, timeout, {
309
+ cwd: config.root,
310
+ env: routine.modDir ? { ...process.env, CREWBOSS_MOD_DIR: routine.modDir } : process.env,
311
+ });
312
+ fs.writeFileSync(collectPath, collected, 'utf8');
313
+ }
314
+ if (candidates.some((c) => c.tool === 'claude')) {
315
+ assertCommunicationAllowed(routine.disallowed_tools ?? [], `routine '${name}' disallowed_tools`);
316
+ }
317
+ const openTasks = await activeTracker.openTasks(routine.project);
318
+ const memory = memorySection(history, routineScopes(routine), config.memoryMaxBytes);
319
+ const communication = communicationSection(config.preamble, { claude: candidates[0]?.tool === 'claude' });
320
+ const { prompt, attachment } = buildRoutinePrompt(config, { ...routine, mode }, {
321
+ openTasks, collected, collectPath, memory, communication,
322
+ });
323
+ fs.writeFileSync(path.join(runDir, 'prompt.txt'), prompt, 'utf8');
324
+
325
+ const result = await runners.launchWithFallback(candidates, prompt, runDir, config.root, {
326
+ mode,
327
+ attachment,
328
+ allowedTools: routine.allowed_tools,
329
+ disallowedTools: routine.disallowed_tools,
330
+ env: runEnv(runId, config),
331
+ timeoutSeconds: routine.timeout_minutes * 60,
332
+ checkStartup: true,
333
+ launcher: launch,
334
+ clock,
335
+ stdout,
336
+ stderr,
337
+ });
338
+ if (!result.chosen) throw new Error(startupFailureMessage(routine, candidates, result.skipped));
339
+ chosen = result.chosen;
340
+ if (result.error) throw result.error;
341
+ agentExit = result.proc.returncode;
342
+ if (result.proc.returncode) throw new Error(`agent exited ${result.proc.returncode}; log: ${tail(agentLog, 1200)}`);
343
+ const answer = fs.readFileSync(answerPath, 'utf8');
344
+ try {
345
+ report = parseReport(answer, { memoryScopes: routineReportScopes(routine) });
346
+ } catch (err) {
347
+ throw new Error(`${err.message}; raw tail: ${answer.slice(-1500)}`);
348
+ }
349
+ status = report.status;
350
+ summary = report.summary;
351
+ markdown = agentMarkdown(answer);
352
+ }
353
+ } catch (err) {
354
+ report = null;
355
+ summary = String(err.message).slice(0, 1800);
356
+ }
357
+
358
+ writeStatus(runDir, status, summary);
359
+ let body;
360
+ if (report === null) {
361
+ let tails = '';
362
+ for (const file of [agentLog, answerPath, collectPath]) {
363
+ if (fs.existsSync(file)) tails += `\n\n--- ${path.basename(file)} tail ---\n${tail(file, ERROR_TAIL_CHARS)}`;
364
+ }
365
+ report = { status, summary, findings: [] };
366
+ body = `${status[0].toUpperCase()}${status.slice(1)}: ${summary}${tails}`;
367
+ } else {
368
+ body = reportBody(markdown, collected, report.notify);
369
+ }
370
+ const published = await publish(report, body, status, runId);
371
+ for (const note of report.memory ?? []) {
372
+ if (dryRun) print(`DRY RUN memory [${note.scope}] ${note.text}`);
373
+ else history.addMemory({ scope: note.scope, text: note.text, author: `routine:${name}` });
374
+ }
375
+ history.finishRun(runId, { status, summary, tool: chosen?.tool ?? null, model: chosen?.model ?? null, exitCode: agentExit });
376
+ recordFinished(history, runId, { answerPath: fs.existsSync(answerPath) ? answerPath : null });
377
+ if (!published) return 1;
378
+ print(`${name}: ${status}: ${summary} (${runDir})`);
379
+ return OK_STATUSES.has(status) ? 0 : 1;
380
+ } finally {
381
+ release();
382
+ }
383
+ }
384
+
385
+ /** One line per routine: name, on/off, model choice, schedule, last run time and status. */
386
+ export function listRoutines(config, { stdout = process.stdout } = {}) {
387
+ if (config.tasks?.stale_after_days !== undefined) {
388
+ stdout.write(`tidy on task tidy *-*-* 07:00:00 - -\n`);
389
+ }
390
+ for (const routine of config.routines) {
391
+ const base = path.join(config.logsDir, 'routines', routine.name);
392
+ let last = {};
393
+ if (fs.existsSync(base)) {
394
+ const runs = fs.readdirSync(base).filter((dir) => fs.existsSync(path.join(base, dir, 'status.json'))).sort().reverse();
395
+ if (runs.length) last = JSON.parse(fs.readFileSync(path.join(base, runs[0], 'status.json'), 'utf8'));
396
+ }
397
+ const choice = 'size' in routine ? `size=${routine.size}` : `tool=${routine.tool} model=${routine.model}`;
398
+ stdout.write(`${routine.name.padEnd(16)} ${(routine.enabled ? 'on' : 'off').padEnd(3)} ${choice} ${routine.mod ? `mod=${routine.mod} ` : ''}`
399
+ + `${routine.schedule} ${last.time ?? '-'} ${last.status ?? '-'}\n`);
400
+ }
401
+ }
package/src/rundir.js ADDED
@@ -0,0 +1,43 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+
4
+ const pad = (n) => String(n).padStart(2, '0');
5
+
6
+ /** Local time as YYYYmmdd-HHMM. */
7
+ export function stamp(date = new Date()) {
8
+ return `${date.getFullYear()}${pad(date.getMonth() + 1)}${pad(date.getDate())}`
9
+ + `-${pad(date.getHours())}${pad(date.getMinutes())}`;
10
+ }
11
+
12
+ /** Local time as YYYY-mm-dd HH:MM, for report titles. */
13
+ export function humanStamp(date = new Date()) {
14
+ return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`
15
+ + ` ${pad(date.getHours())}:${pad(date.getMinutes())}`;
16
+ }
17
+
18
+ /** Local time as ISO 8601 with offset, e.g. 2026-11-23T10:00:00+01:00. */
19
+ export function isoNow(date = new Date()) {
20
+ const offset = -date.getTimezoneOffset();
21
+ const sign = offset >= 0 ? '+' : '-';
22
+ const abs = Math.abs(offset);
23
+ return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`
24
+ + `T${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`
25
+ + `${sign}${pad(Math.floor(abs / 60))}:${pad(abs % 60)}`;
26
+ }
27
+
28
+ /** Return base/name+suffix, or base/name-N+suffix if it already exists. */
29
+ export function uniquePath(base, name, suffix = '') {
30
+ let candidate = path.join(base, `${name}${suffix}`);
31
+ for (let n = 1; fs.existsSync(candidate); n += 1) {
32
+ candidate = path.join(base, `${name}-${n}${suffix}`);
33
+ }
34
+ return candidate;
35
+ }
36
+
37
+ /** Create base/<YYYYmmdd-HHMM>[-n]/ and return its path. */
38
+ export function newRunDir(base, date = new Date()) {
39
+ fs.mkdirSync(base, { recursive: true });
40
+ const dir = uniquePath(base, stamp(date));
41
+ fs.mkdirSync(dir);
42
+ return dir;
43
+ }