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,30 @@
1
+ /** Parse a task cutoff. A date starts at midnight in the local time zone. */
2
+ import { isDueDate } from './due.js';
3
+
4
+ export function parseDoneSince(value) {
5
+ if (typeof value !== 'string') throw new Error('done_since must be YYYY-MM-DD or an ISO datetime');
6
+ let instant;
7
+ if (/^\d{4}-\d{2}-\d{2}$/.test(value)) {
8
+ if (!isDueDate(value)) throw new Error('done_since must be YYYY-MM-DD or an ISO datetime');
9
+ const [year, month, day] = value.split('-').map(Number);
10
+ instant = new Date(0);
11
+ instant.setFullYear(year, month - 1, day);
12
+ instant.setHours(0, 0, 0, 0);
13
+ if (instant.getFullYear() !== year || instant.getMonth() + 1 !== month || instant.getDate() !== day) {
14
+ throw new Error('done_since must be YYYY-MM-DD or an ISO datetime');
15
+ }
16
+ } else if (/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:\d{2})?$/.test(value)) {
17
+ if (!isDueDate(value.slice(0, 10))) throw new Error('done_since must be YYYY-MM-DD or an ISO datetime');
18
+ instant = new Date(value);
19
+ } else {
20
+ throw new Error('done_since must be YYYY-MM-DD or an ISO datetime');
21
+ }
22
+ if (Number.isNaN(instant.getTime())) throw new Error('done_since must be YYYY-MM-DD or an ISO datetime');
23
+ return instant;
24
+ }
25
+
26
+ export function filterDoneSince(tasks, since) {
27
+ const cutoff = parseDoneSince(since).getTime();
28
+ return tasks.filter((task) => task.status === 'open' || task.status === 'in_progress'
29
+ || (task.status === 'done' && task.done_at && Date.parse(task.done_at) >= cutoff));
30
+ }
package/src/tasks.js ADDED
@@ -0,0 +1,129 @@
1
+ /** `crewboss task list|show|add|update|done|comment` on the configured tracker. */
2
+ import { TrackerError } from './errors.js';
3
+ import { openStore, TASK_PRIORITIES, TASK_STATUSES } from './store.js';
4
+ import { makeTracker } from './trackers/index.js';
5
+ import { filterDoneSince, parseDoneSince } from './task-time.js';
6
+
7
+ export const TASK_ACTIONS = ['list', 'projects', 'show', 'add', 'update', 'done', 'comment', 'tidy'];
8
+ export const LIST_STATUSES = [...TASK_STATUSES, 'all'];
9
+ export { TASK_PRIORITIES, TASK_STATUSES };
10
+
11
+ /** A tracker supports the task CLI if it implements these methods. */
12
+ function supportsTaskCli(tracker) {
13
+ return ['listTasks', 'getTask', 'updateTask', 'commentTask'].every((m) => typeof tracker[m] === 'function');
14
+ }
15
+
16
+ function formatTask(task) {
17
+ return `${task.id} ${(task.status || '-').padEnd(11)} ${(task.priority || '-').padEnd(6)} `
18
+ + `${task.assignee || '-'} due: ${task.due || '-'} [${task.project}] ${task.title}`;
19
+ }
20
+
21
+ function formatDetails(task) {
22
+ const lines = [
23
+ `${task.id} ${task.title}`,
24
+ `project: ${task.project} status: ${task.status || '-'} priority: ${task.priority || '-'} assignee: ${task.assignee || '-'} due: ${task.due || '-'}`,
25
+ ];
26
+ if (task.created_at || task.updated_at) lines.push(`created: ${task.created_at ?? '-'} updated: ${task.updated_at ?? '-'} done: ${task.done_at ?? '-'}`);
27
+ if (task.notes) lines.push('', task.notes);
28
+ const comments = task.comments ?? [];
29
+ if (comments.length) {
30
+ lines.push('', 'Comments:');
31
+ for (const c of comments) lines.push(`- ${c.created_at ?? ''} ${c.author || 'anonymous'}: ${c.body}`);
32
+ }
33
+ return `${lines.join('\n')}\n`;
34
+ }
35
+
36
+ /**
37
+ * Run one task action. `args` holds the parsed CLI values. Resolves with the exit code.
38
+ * Throws TrackerError (exit 1) or UnsupportedError (exit 2, handled by the caller).
39
+ */
40
+ export async function runTaskCommand(config, action, args, {
41
+ tracker = null,
42
+ store = undefined,
43
+ stdout = process.stdout,
44
+ env = process.env,
45
+ now = () => new Date(),
46
+ } = {}) {
47
+ const ownStore = !tracker && store === undefined && config.tracker.type === 'local';
48
+ const localStore = ownStore ? openStore(config.root) : store;
49
+ try {
50
+ const active = tracker ?? makeTracker(config.tracker, config.root, { store: localStore });
51
+ const print = (value, text) => stdout.write(args.json ? `${JSON.stringify(value, null, 2)}\n` : text);
52
+ if (action === 'projects') {
53
+ const projects = typeof active.listProjects === 'function' ? await active.listProjects() : [];
54
+ print(projects, projects.length ? `${projects.map(({ id, name }) => `${id} ${name}`).join('\n')}\n` : 'No projects.\n');
55
+ return 0;
56
+ }
57
+ if (!supportsTaskCli(active)) {
58
+ throw new TrackerError(`the ${config.tracker.type} tracker does not support the task commands; use the local tracker or a command plugin`);
59
+ }
60
+ if (action === 'list') {
61
+ if (args.doneSince !== undefined) parseDoneSince(args.doneSince);
62
+ let tasks = await active.listTasks({
63
+ project: args.project ?? null, status: args.doneSince !== undefined && args.status === undefined ? 'all' : args.status ?? null,
64
+ assignee: args.assignee ?? null, doneSince: args.doneSince ?? null,
65
+ });
66
+ if (args.doneSince !== undefined) tasks = filterDoneSince(tasks, args.doneSince);
67
+ if (args.dueBefore !== undefined) tasks = tasks.filter((task) => task.due && task.due <= args.dueBefore);
68
+ print(tasks, tasks.length ? `${tasks.map(formatTask).join('\n')}\n` : 'No tasks.\n');
69
+ return 0;
70
+ }
71
+ if (action === 'tidy') {
72
+ const days = args.staleDays ?? config.tasks?.stale_after_days;
73
+ if (days === undefined) throw new Error('task tidy needs --stale-days or tasks.stale_after_days in config');
74
+ const current = now();
75
+ const cutoff = current.getTime() - days * 86400000;
76
+ const tasks = await active.listTasks({ status: 'in_progress' });
77
+ const changed = [];
78
+ const skipped = [];
79
+ for (const task of tasks) {
80
+ if (task.status !== 'in_progress') continue;
81
+ if (!task.updated_at || Number.isNaN(Date.parse(task.updated_at))) {
82
+ skipped.push({ id: task.id, reason: 'missing updated_at' });
83
+ continue;
84
+ }
85
+ if (Date.parse(task.updated_at) >= cutoff) continue;
86
+ const comment = `Moved back to open by crewboss task tidy: no activity for ${days} days (last update ${task.updated_at.slice(0, 10)}).`;
87
+ if (!args.dryRun) {
88
+ await active.updateTask(task.id, { status: 'open' });
89
+ await active.commentTask(task.id, 'crewboss', comment);
90
+ }
91
+ changed.push({ id: task.id, updated_at: task.updated_at, comment });
92
+ }
93
+ const result = { dry_run: !!args.dryRun, stale_days: days, changed, skipped };
94
+ print(result, [...changed.map((task) => `${args.dryRun ? 'would move' : 'moved'} ${task.id} to open: ${task.comment}`),
95
+ ...skipped.map((task) => `skipped ${task.id}: ${task.reason}`),
96
+ ...(!changed.length && !skipped.length ? ['No stale tasks.'] : [])].join('\n') + '\n');
97
+ return 0;
98
+ }
99
+ if (action === 'show') {
100
+ const task = await active.getTask(args.id);
101
+ if (!task) throw new TrackerError(`task not found: ${args.id}`);
102
+ print(task, formatDetails(task));
103
+ return 0;
104
+ }
105
+ if (action === 'add') {
106
+ const id = await active.createTask(args.project, args.title, args.notes ?? '', args.priority ?? 'medium', args.assignee ?? '', args.due);
107
+ print({ id }, `${id}\n`);
108
+ return 0;
109
+ }
110
+ if (action === 'update' || action === 'done') {
111
+ const changes = action === 'done'
112
+ ? { status: 'done' }
113
+ : Object.fromEntries(['title', 'notes', 'status', 'priority', 'assignee', 'due']
114
+ .filter((k) => args[k] !== undefined).map((k) => [k, args[k]]));
115
+ const task = await active.updateTask(args.id, changes);
116
+ print(task, `updated ${task.id}: ${task.status}\n`);
117
+ return 0;
118
+ }
119
+ if (action === 'comment') {
120
+ const author = args.author ?? env.USER ?? '';
121
+ const comment = await active.commentTask(args.id, author, args.text);
122
+ print(comment, `commented on ${args.id}\n`);
123
+ return 0;
124
+ }
125
+ throw new Error(`unknown task action: ${action}`);
126
+ } finally {
127
+ if (ownStore) localStore.close();
128
+ }
129
+ }
@@ -0,0 +1,126 @@
1
+ /**
2
+ * Tracker plugin run as an executable, one process per operation:
3
+ * stdin {"op", "options", "args"} -> stdout {"result": ...} or {"error": "..."}.
4
+ * {"error": "unsupported"} means the plugin does not implement that operation.
5
+ */
6
+ import { TrackerError, UnsupportedError } from '../errors.js';
7
+ import { isDue } from '../due.js';
8
+ import { runPlugin } from '../plugin.js';
9
+
10
+ const isObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
11
+ const isTask = (t) => isObject(t) && t.id != null && typeof t.title === 'string';
12
+
13
+ /** A task as returned by list_tasks or update_task, with string fields filled in. */
14
+ function normalizeTask(task) {
15
+ if (task.due !== undefined && !isDue(task.due)) throw new TrackerError('tracker task has invalid due date; expected YYYY-MM-DD or null');
16
+ const normalized = {
17
+ ...task,
18
+ id: String(task.id),
19
+ project: String(task.project ?? ''),
20
+ title: task.title,
21
+ notes: String(task.notes ?? ''),
22
+ status: String(task.status ?? ''),
23
+ priority: String(task.priority ?? ''),
24
+ assignee: String(task.assignee ?? ''),
25
+ due: task.due ?? null,
26
+ };
27
+ if (task.comments !== undefined && !Array.isArray(task.comments)) delete normalized.comments;
28
+ return normalized;
29
+ }
30
+
31
+ export class CommandTracker {
32
+ constructor({ command, options = {}, timeout_seconds: timeoutSeconds = 60 }, root, { spawn, kill } = {}) {
33
+ this.command = command;
34
+ this.options = options;
35
+ this.timeoutSeconds = timeoutSeconds;
36
+ this.root = root;
37
+ this.processDeps = { spawn, kill };
38
+ }
39
+
40
+ async call(op, args) {
41
+ let response;
42
+ try {
43
+ response = await runPlugin(this.command, { op, options: this.options, args }, {
44
+ cwd: this.root, timeoutSeconds: this.timeoutSeconds, ...this.processDeps,
45
+ });
46
+ } catch (err) {
47
+ throw new TrackerError(`tracker ${op} failed: ${err.message}`);
48
+ }
49
+ if (!isObject(response)) throw new TrackerError(`tracker ${op} failed: response must be a JSON object`);
50
+ if (response.error === 'unsupported') throw new UnsupportedError(`the tracker plugin does not support ${op}`);
51
+ if ('error' in response) throw new TrackerError(`tracker ${op} failed: ${response.error}`);
52
+ if (!('result' in response)) throw new TrackerError(`tracker ${op} failed: response has no result`);
53
+ return response.result;
54
+ }
55
+
56
+ async openTasks(project) {
57
+ const result = await this.call('open_tasks', { project });
58
+ if (!Array.isArray(result) || !result.every(isTask)) {
59
+ throw new TrackerError('tracker open_tasks failed: result must be a list of {id, title, assignee}');
60
+ }
61
+ return result.map((t) => ({ id: String(t.id), title: t.title, assignee: String(t.assignee ?? '') }));
62
+ }
63
+
64
+ async createTask(project, title, notes, priority, assignee, due = undefined) {
65
+ if (due !== undefined && !isDue(due)) throw new TrackerError('invalid due date; expected YYYY-MM-DD or null');
66
+ const id = await this.call('create_task', { project, title, notes, priority, assignee, ...(due === undefined ? {} : { due }) });
67
+ if ((typeof id !== 'string' && typeof id !== 'number') || String(id) === '') {
68
+ throw new TrackerError('tracker create_task failed: result must be the task id');
69
+ }
70
+ return String(id);
71
+ }
72
+
73
+ async publishReport(project, source, title, status, summary, body, findings) {
74
+ await this.call('publish_report', { project, source, title, status, summary, body, findings });
75
+ }
76
+
77
+ // Task CLI (optional operations).
78
+
79
+ /** filters: {project?, status?, assignee?, ids?}; status null/absent = every task not done. */
80
+ async listTasks(filters = {}) {
81
+ const args = Object.fromEntries(Object.entries(filters).filter(([k, v]) => k !== 'doneSince' && v !== null && v !== undefined));
82
+ const result = await this.call('list_tasks', args);
83
+ if (!Array.isArray(result) || !result.every(isTask)) {
84
+ throw new TrackerError('tracker list_tasks failed: result must be a list of tasks with id and title');
85
+ }
86
+ return result.map(normalizeTask);
87
+ }
88
+
89
+ async listProjects() {
90
+ try {
91
+ const result = await this.call('list_projects', {});
92
+ if (!Array.isArray(result) || !result.every((project) => isObject(project)
93
+ && (typeof project.id === 'string' || typeof project.id === 'number')
94
+ && typeof project.name === 'string')) {
95
+ throw new TrackerError('tracker list_projects failed: result must be a list of {id, name}');
96
+ }
97
+ return result.map(({ id, name }) => ({ id: String(id), name }));
98
+ } catch {
99
+ // Older plugins do not implement list_projects. Derive names from tasks when possible.
100
+ try {
101
+ const tasks = await this.listTasks({ status: 'all' });
102
+ return [...new Set(tasks.map((task) => task.project).filter(Boolean))]
103
+ .map((project) => ({ id: project, name: project }));
104
+ } catch {
105
+ return [];
106
+ }
107
+ }
108
+ }
109
+
110
+ async getTask(id) {
111
+ const [task] = await this.listTasks({ ids: [id], status: 'all' });
112
+ return task ?? null;
113
+ }
114
+
115
+ async updateTask(id, changes) {
116
+ if (changes.due !== undefined && !isDue(changes.due)) throw new TrackerError('invalid due date; expected YYYY-MM-DD or null');
117
+ const result = await this.call('update_task', { id, changes });
118
+ if (!isTask(result)) throw new TrackerError('tracker update_task failed: result must be the updated task');
119
+ return normalizeTask(result);
120
+ }
121
+
122
+ async commentTask(id, author, body) {
123
+ const result = await this.call('comment_task', { id, author, body });
124
+ return isObject(result) ? result : { task_id: id, author, body };
125
+ }
126
+ }
@@ -0,0 +1,160 @@
1
+ /**
2
+ * Built-in tracker that keeps tasks and reports as local files.
3
+ * Tasks: <dir>/tasks.json, updated through task commands or directly in the file.
4
+ * Reports: <dir>/<source>/<YYYYmmdd-HHMM>[-n].md and .json.
5
+ */
6
+ import { randomUUID } from 'node:crypto';
7
+ import fs from 'node:fs';
8
+ import path from 'node:path';
9
+
10
+ import { NAME_RE } from '../config.js';
11
+ import { TrackerError } from '../errors.js';
12
+ import { isDue } from '../due.js';
13
+ import { isoNow, stamp, uniquePath } from '../rundir.js';
14
+ import { filterDoneSince } from '../task-time.js';
15
+
16
+ export const PRIORITIES = ['high', 'medium'];
17
+ const OPEN = 'open';
18
+
19
+ export class FileTracker {
20
+ constructor(dir, { now = () => new Date() } = {}) {
21
+ this.dir = dir;
22
+ this.tasksPath = path.join(dir, 'tasks.json');
23
+ this.now = now;
24
+ }
25
+
26
+ readTasks() {
27
+ if (!fs.existsSync(this.tasksPath)) return [];
28
+ let tasks;
29
+ try {
30
+ tasks = JSON.parse(fs.readFileSync(this.tasksPath, 'utf8'));
31
+ } catch (err) {
32
+ throw new TrackerError(`cannot read ${this.tasksPath}: ${err.message}`);
33
+ }
34
+ if (!Array.isArray(tasks)) throw new TrackerError(`${this.tasksPath} must contain a JSON list`);
35
+ return tasks;
36
+ }
37
+
38
+ async openTasks(project) {
39
+ return this.readTasks()
40
+ .filter((task) => task.project === project && task.status === OPEN)
41
+ .map((task) => ({ id: String(task.id ?? ''), title: String(task.title ?? ''), assignee: String(task.assignee ?? '') }));
42
+ }
43
+
44
+ async createTask(project, title, notes, priority, assignee, due = null) {
45
+ if (!PRIORITIES.includes(priority)) {
46
+ throw new TrackerError(`invalid priority '${priority}', expected one of ${PRIORITIES.join(', ')}`);
47
+ }
48
+ if (!isDue(due)) throw new TrackerError('invalid due date; expected YYYY-MM-DD or null');
49
+ const tasks = this.readTasks();
50
+ const ids = new Set(tasks.map((task) => task.id));
51
+ let id;
52
+ do {
53
+ id = randomUUID().replaceAll('-', '').slice(0, 8);
54
+ } while (ids.has(id));
55
+ const now = isoNow(this.now());
56
+ tasks.push({ id, project, title, notes, priority, assignee, due, status: OPEN, created_at: now, updated_at: now, done_at: null, comments: [] });
57
+ this.writeTasks(tasks);
58
+ return id;
59
+ }
60
+
61
+ writeTasks(tasks) {
62
+ try {
63
+ fs.mkdirSync(this.dir, { recursive: true });
64
+ const tmp = `${this.tasksPath}.tmp`;
65
+ fs.writeFileSync(tmp, JSON.stringify(tasks, null, 2) + '\n', 'utf8');
66
+ fs.renameSync(tmp, this.tasksPath);
67
+ } catch (err) {
68
+ throw new TrackerError(`cannot write ${this.tasksPath}: ${err.message}`);
69
+ }
70
+ }
71
+
72
+ async listTasks({ project = null, status = null, assignee = null, ids = null, doneSince = null } = {}) {
73
+ let tasks = this.readTasks().filter((task) => (project === null || task.project === project)
74
+ && (assignee === null || task.assignee === assignee)
75
+ && (ids === null || ids.includes(task.id))
76
+ && (status === 'all' || (status === null ? doneSince !== null || task.status !== 'done' : task.status === status)));
77
+ if (doneSince !== null) tasks = filterDoneSince(tasks, doneSince);
78
+ return tasks;
79
+ }
80
+
81
+ async listProjects() {
82
+ return [...new Set(this.readTasks().map((task) => String(task.project ?? '')).filter(Boolean))]
83
+ .map((project) => ({ id: project, name: project }));
84
+ }
85
+
86
+ async getTask(id) {
87
+ return this.readTasks().find((task) => task.id === id) ?? null;
88
+ }
89
+
90
+ async updateTask(id, changes) {
91
+ if (changes.due !== undefined && !isDue(changes.due)) throw new TrackerError('invalid due date; expected YYYY-MM-DD or null');
92
+ const tasks = this.readTasks();
93
+ const task = tasks.find((row) => row.id === id);
94
+ if (!task) throw new TrackerError(`task not found: ${id}`);
95
+ const fields = ['title', 'notes', 'status', 'priority', 'assignee', 'due'];
96
+ if (changes.status !== undefined && !['open', 'in_progress', 'done'].includes(changes.status)) throw new TrackerError('invalid task status');
97
+ if (changes.priority !== undefined && !['high', 'medium', 'low'].includes(changes.priority)) throw new TrackerError('invalid task priority');
98
+ if (fields.some((field) => changes[field] !== undefined)) {
99
+ const now = isoNow(this.now());
100
+ if (changes.status === 'done' && task.status !== 'done') task.done_at = now;
101
+ if (changes.status !== undefined && changes.status !== 'done') task.done_at = null;
102
+ for (const field of fields) if (changes[field] !== undefined) task[field] = changes[field];
103
+ task.updated_at = now;
104
+ this.writeTasks(tasks);
105
+ }
106
+ return task;
107
+ }
108
+
109
+ async commentTask(id, author, body) {
110
+ const tasks = this.readTasks();
111
+ const task = tasks.find((row) => row.id === id);
112
+ if (!task) throw new TrackerError(`task not found: ${id}`);
113
+ const created_at = isoNow(this.now());
114
+ const comment = { id: (task.comments?.length ?? 0) + 1, task_id: id, author, body, created_at };
115
+ task.comments ??= [];
116
+ task.comments.push(comment);
117
+ task.updated_at = created_at;
118
+ this.writeTasks(tasks);
119
+ return comment;
120
+ }
121
+
122
+ async publishReport(project, source, title, status, summary, body, findings) {
123
+ if (typeof source !== 'string' || !NAME_RE.test(source)) {
124
+ throw new TrackerError(`invalid report source: ${JSON.stringify(source)}`);
125
+ }
126
+ const report = { project, source, title, status, summary, body, findings, created: isoNow() };
127
+ try {
128
+ const base = path.join(this.dir, source);
129
+ fs.mkdirSync(base, { recursive: true });
130
+ const mdPath = uniquePath(base, stamp(), '.md');
131
+ fs.writeFileSync(mdPath, renderMarkdown(report), 'utf8');
132
+ fs.writeFileSync(mdPath.replace(/\.md$/, '.json'), JSON.stringify(report, null, 2) + '\n', 'utf8');
133
+ } catch (err) {
134
+ throw new TrackerError(`cannot write report for ${source}: ${err.message}`);
135
+ }
136
+ }
137
+ }
138
+
139
+ export function renderMarkdown(report) {
140
+ const lines = [
141
+ `# ${report.title}`, '',
142
+ `- Project: ${report.project}`,
143
+ `- Status: ${report.status}`,
144
+ `- Summary: ${report.summary}`, '',
145
+ ];
146
+ if (report.body.trim()) lines.push(report.body.trim(), '');
147
+ lines.push('## Findings', '');
148
+ if (!report.findings.length) lines.push('No findings.');
149
+ for (const finding of report.findings) {
150
+ const task = finding.task ? ` (task ${finding.task})` : '';
151
+ lines.push(`- **${finding.severity ?? '?'}** ${finding.title ?? ''}${task}`);
152
+ if (finding.evidence) lines.push(` - Evidence: ${finding.evidence}`);
153
+ if (finding.proposal) lines.push(` - Proposal: ${finding.proposal}`);
154
+ }
155
+ return `${lines.join('\n')}\n`;
156
+ }
157
+
158
+ export function makeFileTracker(options, root) {
159
+ return new FileTracker(path.resolve(root, options.dir ?? 'reports'));
160
+ }
@@ -0,0 +1,16 @@
1
+ /** Build the tracker described by a validated `tracker` config entry. */
2
+ import { ConfigError } from '../errors.js';
3
+ import { CommandTracker } from './command.js';
4
+ import { makeFileTracker } from './file.js';
5
+ import { LocalTracker } from './local.js';
6
+
7
+ /** `store` is required for the `local` tracker; `spawn`/`kill` are for tests of `command`. */
8
+ export function makeTracker(tracker, root, { store = null, spawn, kill } = {}) {
9
+ if (tracker.type === 'local') {
10
+ if (!store) throw new ConfigError('the local tracker needs the local store');
11
+ return new LocalTracker(store);
12
+ }
13
+ if (tracker.type === 'file') return makeFileTracker({ dir: tracker.dir }, root);
14
+ if (tracker.type === 'command') return new CommandTracker(tracker, root, { spawn, kill });
15
+ throw new ConfigError(`unknown tracker type '${tracker.type}'`);
16
+ }
@@ -0,0 +1,57 @@
1
+ /**
2
+ * Default tracker: tasks in the local SQLite store. Reports need nothing extra here,
3
+ * because every routine report is already kept in the local history.
4
+ */
5
+ import { TrackerError } from '../errors.js';
6
+ import { TASK_PRIORITIES } from '../store.js';
7
+
8
+ export class LocalTracker {
9
+ constructor(store) {
10
+ this.store = store;
11
+ }
12
+
13
+ async openTasks(project) {
14
+ return this.store.openTasks(project);
15
+ }
16
+
17
+ async createTask(project, title, notes, priority, assignee, due = null) {
18
+ if (!TASK_PRIORITIES.includes(priority)) {
19
+ throw new TrackerError(`invalid priority '${priority}', expected one of ${TASK_PRIORITIES.join(', ')}`);
20
+ }
21
+ return this.store.createTask({ project, title, notes, priority, assignee, due });
22
+ }
23
+
24
+ async publishReport() {
25
+ // Kept by the local history (Store.recordReport), which runs for every tracker.
26
+ }
27
+
28
+ // Task CLI.
29
+
30
+ async listTasks(filters = {}) {
31
+ return this.store.listTasks(filters);
32
+ }
33
+
34
+ async listProjects() {
35
+ const tasks = this.store.listTasks({ status: 'all' });
36
+ return [...new Set(tasks.map((task) => String(task.project ?? '')).filter(Boolean))]
37
+ .map((project) => ({ id: project, name: project }));
38
+ }
39
+
40
+ /** The task with its comments, or null. */
41
+ async getTask(id) {
42
+ const task = this.store.getTask(id);
43
+ return task ? { ...task, comments: this.store.comments(id) } : null;
44
+ }
45
+
46
+ async updateTask(id, changes) {
47
+ const task = this.store.updateTask(id, changes);
48
+ if (!task) throw new TrackerError(`task not found: ${id}`);
49
+ return task;
50
+ }
51
+
52
+ async commentTask(id, author, body) {
53
+ const comment = this.store.addComment(id, { author, body });
54
+ if (!comment) throw new TrackerError(`task not found: ${id}`);
55
+ return comment;
56
+ }
57
+ }
package/src/units.js ADDED
@@ -0,0 +1,117 @@
1
+ /** systemd user units (.service + .timer) for enabled routines. */
2
+ import { spawnSync } from 'node:child_process';
3
+ import fs from 'node:fs';
4
+ import os from 'node:os';
5
+ import path from 'node:path';
6
+ import { fileURLToPath } from 'node:url';
7
+
8
+ import { stableNodeCommand } from './node-command.js';
9
+ import { scheduledEntries } from './task-schedule.js';
10
+
11
+ export const BIN_PATH = fileURLToPath(new URL('../bin/crewboss.js', import.meta.url));
12
+
13
+ export function defaultUnitDir() {
14
+ return path.join(os.homedir(), '.config/systemd/user');
15
+ }
16
+
17
+ /** Escape systemd specifiers (%). */
18
+ function escapeSpecifiers(value) {
19
+ return value.replaceAll('%', '%%');
20
+ }
21
+
22
+ /** Quote a word for systemd when it contains whitespace, quotes or backslashes. */
23
+ function quote(word) {
24
+ const escaped = escapeSpecifiers(word);
25
+ if (!/[\s"'\\]/.test(escaped)) return escaped;
26
+ return `"${escaped.replaceAll('\\', '\\\\').replaceAll('"', '\\"')}"`;
27
+ }
28
+
29
+ export function unitName(config, routineName) {
30
+ return `${config.unitPrefix}${routineName}`;
31
+ }
32
+
33
+ /** Render the .service and .timer for one routine. */
34
+ export function renderUnits(config, routine, { env = process.env, nodeCommand = stableNodeCommand({ env }), binPath = BIN_PATH } = {}) {
35
+ const unit = unitName(config, routine.name);
36
+ const logFile = escapeSpecifiers(path.join(config.logsDir, 'routines', `${routine.name}.log`));
37
+ const execStart = [...nodeCommand, binPath, '--config', config.path,
38
+ ...(routine.tidy ? ['task', 'tidy'] : ['routines', 'run', routine.name])].map(quote).join(' ');
39
+ const service = [
40
+ '[Unit]',
41
+ `Description=crewboss ${routine.tidy ? 'task tidy' : `routine ${routine.name}`}`,
42
+ '',
43
+ '[Service]',
44
+ 'Type=oneshot',
45
+ `Environment=${quote(`PATH=${env.PATH ?? ''}`)}`,
46
+ `Environment=${quote(`HOME=${env.HOME ?? os.homedir()}`)}`,
47
+ `WorkingDirectory=${escapeSpecifiers(config.root)}`,
48
+ `ExecStart=${execStart}`,
49
+ `StandardOutput=append:${logFile}`,
50
+ `StandardError=append:${logFile}`,
51
+ '',
52
+ ].join('\n');
53
+ const timer = [
54
+ '[Unit]',
55
+ `Description=crewboss ${routine.tidy ? 'task tidy' : `routine ${routine.name}`} timer`,
56
+ '',
57
+ '[Timer]',
58
+ `OnCalendar=${routine.schedule}`,
59
+ 'Persistent=true',
60
+ `Unit=${unit}.service`,
61
+ '',
62
+ '[Install]',
63
+ 'WantedBy=timers.target',
64
+ '',
65
+ ].join('\n');
66
+ return { unit, service, timer };
67
+ }
68
+
69
+ /** Run `systemctl args`; with check, a failure throws. */
70
+ export function runSystemctl(args, { check = true } = {}) {
71
+ const result = spawnSync('systemctl', args, { stdio: ['ignore', 'inherit', 'inherit'] });
72
+ if (check && (result.error || result.status !== 0)) {
73
+ const reason = result.error ? result.error.message : `exit ${result.status}`;
74
+ throw new Error(`systemctl ${args.join(' ')} failed: ${reason}`);
75
+ }
76
+ return result.status;
77
+ }
78
+
79
+ /**
80
+ * Install units for enabled routines and remove those of disabled or deleted ones
81
+ * (every unit with the configured prefix). With uninstall, remove them all.
82
+ */
83
+ export function manageUnits(config, {
84
+ uninstall = false,
85
+ unitDir = defaultUnitDir(),
86
+ systemctl = runSystemctl,
87
+ env = process.env,
88
+ nodeCommand = stableNodeCommand({ env }),
89
+ binPath = BIN_PATH,
90
+ } = {}) {
91
+ const prefix = config.unitPrefix;
92
+ fs.mkdirSync(unitDir, { recursive: true });
93
+ fs.mkdirSync(path.join(config.logsDir, 'routines'), { recursive: true });
94
+ const desired = uninstall ? [] : scheduledEntries(config);
95
+ const desiredNames = new Set(desired.map((routine) => routine.name));
96
+ const existing = new Set(
97
+ fs.readdirSync(unitDir)
98
+ .filter((file) => file.startsWith(prefix) && /\.(service|timer)$/.test(file))
99
+ .map((file) => file.slice(prefix.length).replace(/\.(service|timer)$/, '')),
100
+ );
101
+
102
+ const removed = [...existing].filter((name) => !desiredNames.has(name)).sort();
103
+ for (const name of removed) {
104
+ systemctl(['--user', 'disable', '--now', `${prefix}${name}.timer`], { check: false });
105
+ for (const ext of ['service', 'timer']) fs.rmSync(path.join(unitDir, `${prefix}${name}.${ext}`), { force: true });
106
+ }
107
+ for (const routine of desired) {
108
+ const { unit, service, timer } = renderUnits(config, routine, { env, nodeCommand, binPath });
109
+ fs.writeFileSync(path.join(unitDir, `${unit}.service`), service, 'utf8');
110
+ fs.writeFileSync(path.join(unitDir, `${unit}.timer`), timer, 'utf8');
111
+ }
112
+ systemctl(['--user', 'daemon-reload'], { check: true });
113
+ for (const routine of desired) {
114
+ systemctl(['--user', 'enable', '--now', `${unitName(config, routine.name)}.timer`], { check: true });
115
+ }
116
+ return { installed: [...desiredNames], removed };
117
+ }
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Node 22 and 24 print an ExperimentalWarning when node:sqlite is loaded. crewboss
3
+ * silences that one warning only; every other warning is still emitted.
4
+ * Must run before node:sqlite is imported.
5
+ */
6
+ export function isSqliteExperimentalWarning(warning, typeOrOptions) {
7
+ const type = typeof typeOrOptions === 'string' ? typeOrOptions : typeOrOptions?.type;
8
+ const name = type ?? (warning instanceof Error ? warning.name : undefined);
9
+ const message = warning instanceof Error ? warning.message : String(warning);
10
+ return name === 'ExperimentalWarning' && /sqlite/i.test(message);
11
+ }
12
+
13
+ export function silenceSqliteExperimentalWarning(proc = process) {
14
+ const emitWarning = proc.emitWarning;
15
+ proc.emitWarning = function filteredEmitWarning(warning, ...rest) {
16
+ if (isSqliteExperimentalWarning(warning, rest[0])) return undefined;
17
+ return emitWarning.call(this, warning, ...rest);
18
+ };
19
+ }