@ulm0/gonogo 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.
Files changed (54) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +30 -2
  3. package/bin/gonogo.js +18 -0
  4. package/dist/client/THIRD-PARTY-NOTICES.md +409 -0
  5. package/dist/client/apple-touch-icon.png +0 -0
  6. package/dist/client/assets/doto-latin-900-normal-D1bF_x6I.woff +0 -0
  7. package/dist/client/assets/geist-latin-400-normal-B40WzpMT.woff2 +0 -0
  8. package/dist/client/assets/geist-latin-400-normal-akEymXtG.woff +0 -0
  9. package/dist/client/assets/geist-latin-500-normal-BDXIbFrL.woff +0 -0
  10. package/dist/client/assets/geist-latin-500-normal-CTWBw9NS.woff2 +0 -0
  11. package/dist/client/assets/geist-latin-600-normal-CSETrqM2.woff2 +0 -0
  12. package/dist/client/assets/geist-latin-600-normal-DsPlZH-9.woff +0 -0
  13. package/dist/client/assets/geist-mono-latin-400-normal-B2yvC1Cq.woff +0 -0
  14. package/dist/client/assets/geist-mono-latin-400-normal-DTRLJnHl.woff2 +0 -0
  15. package/dist/client/assets/geist-mono-latin-500-normal-D-GG86Jb.woff +0 -0
  16. package/dist/client/assets/geist-mono-latin-500-normal-YINYabwD.woff2 +0 -0
  17. package/dist/client/assets/geist-mono-latin-600-normal-V-KvD_pi.woff2 +0 -0
  18. package/dist/client/assets/geist-mono-latin-600-normal-bZn07FKM.woff +0 -0
  19. package/dist/client/assets/index-B6MsSoeo.css +1 -0
  20. package/dist/client/assets/index-DRtiRh1Y.js +31 -0
  21. package/dist/client/favicon.ico +0 -0
  22. package/dist/client/favicon.svg +1 -0
  23. package/dist/client/index.html +19 -0
  24. package/dist/server/cleanroom.js +214 -0
  25. package/dist/server/cli.js +630 -0
  26. package/dist/server/command.js +44 -0
  27. package/dist/server/constants.js +427 -0
  28. package/dist/server/docking.js +541 -0
  29. package/dist/server/downlink.js +191 -0
  30. package/dist/server/home.js +497 -0
  31. package/dist/server/hooks.js +166 -0
  32. package/dist/server/hub.js +2484 -0
  33. package/dist/server/launcher.js +542 -0
  34. package/dist/server/livery.js +210 -0
  35. package/dist/server/logsearch.js +112 -0
  36. package/dist/server/mcp.js +196 -0
  37. package/dist/server/migrate.js +119 -0
  38. package/dist/server/missionlog.js +209 -0
  39. package/dist/server/payload.js +168 -0
  40. package/dist/server/propellant.js +314 -0
  41. package/dist/server/providers.js +137 -0
  42. package/dist/server/relay.js +300 -0
  43. package/dist/server/relaykinds.js +182 -0
  44. package/dist/server/schedules.js +277 -0
  45. package/dist/server/tasks.js +272 -0
  46. package/dist/server/terminal.js +635 -0
  47. package/dist/server/uplinks.js +356 -0
  48. package/dist/server/web.js +1466 -0
  49. package/dist/shared/cron.js +149 -0
  50. package/dist/shared/fuel.js +18 -0
  51. package/dist/shared/livery.js +348 -0
  52. package/dist/shared/positions.js +132 -0
  53. package/dist/shared/protocol.js +212 -0
  54. package/package.json +84 -3
@@ -0,0 +1,277 @@
1
+ /**
2
+ * Launch Window: messages the Director wrote once and gonogo sends by itself on a cron rule (docs/launch-window-spec.md).
3
+ *
4
+ * A firing is `Hub.sendFromUser`, the same path as a message typed in the Brief box, so Max Q, Redline and held mail apply.
5
+ * One timer runs on the minute: it fires what is due and starts again. A fire more than SCHEDULE_GRACE_MS late (the
6
+ * machine slept, the event loop stalled) is skipped and logged, never replayed, and so are fires missed while gonogo was down.
7
+ * The clock, the timers and the send are injected, so tests run it on a fake clock.
8
+ *
9
+ * shortcut: a schedule that was disabled for a while and then enabled reports "missed" at the next start if its rule
10
+ * would have fired in between; track when it was turned off if the log line ever confuses.
11
+ * shortcut: `to` is an agent name, so after a rename the schedule writes to the old name and its fires end as
12
+ * "not sent: unknown recipient"; follow renames (key by record id) if renames get common.
13
+ */
14
+ import { randomBytes } from 'node:crypto';
15
+ import { readFile, rename, writeFile } from 'node:fs/promises';
16
+ import { join } from 'node:path';
17
+ import { nextFire, parseCron } from '../shared/cron.js';
18
+ import { AGENT_NAME_PATTERN, BODY_MAX_CHARS, CRON_MAX_CHARS, SCHEDULE_NAME_MAX_CHARS, SCHEDULES_MAX, scheduleSubject, SUBJECT_MAX_CHARS, } from '../shared/protocol.js';
19
+ import { FILE_MODE, SCHEDULE_GRACE_MS, SCHEDULE_RESULT_MAX_CHARS, SCHEDULES_FILE } from './constants.js';
20
+ import { HubError } from './hub.js';
21
+ const NAME_RE = new RegExp(AGENT_NAME_PATTERN);
22
+ const ID_RE = /^s[1-9]\d{0,5}$/;
23
+ const EDITABLE = ['name', 'to', 'subject', 'body', 'rule', 'enabled'];
24
+ // C0, DEL, C1 and bidi controls: the name is part of a subject and must stay one clean line.
25
+ export const UNSAFE_IN_NAME = /[\u0000-\u001f\u007f-\u009f‎‏‪-‮⁦-⁩]/;
26
+ const MINUTE_MS = 60_000;
27
+ const isRecord = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
28
+ const bad = (message, field) => new HubError('bad_request', message, field);
29
+ function ruleOf(text) {
30
+ const rule = parseCron(text);
31
+ if (typeof rule === 'string')
32
+ throw bad(rule, 'rule');
33
+ return rule;
34
+ }
35
+ /** The fields a request may carry, checked one by one. With `whole` the four that have no default must be there. */
36
+ function validate(input, whole) {
37
+ if (!isRecord(input))
38
+ throw new HubError('bad_request', 'request body must be a JSON object');
39
+ for (const key of Object.keys(input))
40
+ if (!EDITABLE.includes(key))
41
+ throw bad(`unknown field "${key}"`, key);
42
+ if (whole)
43
+ for (const key of ['name', 'to', 'body', 'rule'])
44
+ if (input[key] === undefined)
45
+ throw bad(`${key} is required`, key);
46
+ const out = {};
47
+ if (input.name !== undefined) {
48
+ const name = typeof input.name === 'string' ? input.name.trim() : '';
49
+ if (name === '' || name.length > SCHEDULE_NAME_MAX_CHARS || UNSAFE_IN_NAME.test(name)) {
50
+ throw bad(`name must be 1 to ${SCHEDULE_NAME_MAX_CHARS} characters on one line`, 'name');
51
+ }
52
+ out.name = name;
53
+ }
54
+ if (input.to !== undefined) {
55
+ if (typeof input.to !== 'string' || (input.to !== 'boss' && (input.to === 'user' || !NAME_RE.test(input.to)))) {
56
+ throw bad('to must be an agent name or "boss"', 'to');
57
+ }
58
+ out.to = input.to;
59
+ }
60
+ if (input.subject !== undefined) {
61
+ if (typeof input.subject !== 'string')
62
+ throw bad('subject must be text', 'subject');
63
+ out.subject = input.subject.trim();
64
+ }
65
+ if (input.body !== undefined) {
66
+ if (typeof input.body !== 'string' || input.body.trim() === '' || input.body.length > BODY_MAX_CHARS) {
67
+ throw bad(`body must be 1 to ${BODY_MAX_CHARS} characters`, 'body');
68
+ }
69
+ out.body = input.body;
70
+ }
71
+ if (input.rule !== undefined) {
72
+ if (typeof input.rule !== 'string' || input.rule.length > CRON_MAX_CHARS)
73
+ throw bad(`rule must be text of at most ${CRON_MAX_CHARS} characters`, 'rule');
74
+ ruleOf(input.rule);
75
+ out.rule = input.rule.trim().split(/\s+/).join(' ');
76
+ }
77
+ if (input.enabled !== undefined) {
78
+ if (typeof input.enabled !== 'boolean')
79
+ throw bad('enabled must be true or false', 'enabled');
80
+ out.enabled = input.enabled;
81
+ }
82
+ return out;
83
+ }
84
+ /** The whole subject has to fit the hub's limit once the prefix is on it. */
85
+ function checkSubject(schedule) {
86
+ if (scheduleSubject(schedule.name, schedule.subject).length > SUBJECT_MAX_CHARS) {
87
+ throw bad(`the name and the subject together must be at most ${SUBJECT_MAX_CHARS - 'Launch Window: : '.length} characters`, 'subject');
88
+ }
89
+ }
90
+ const cut = (text) => text.slice(0, SCHEDULE_RESULT_MAX_CHARS);
91
+ export function createSchedules(options) {
92
+ const { dir, now, log } = options;
93
+ const path = join(dir, SCHEDULES_FILE);
94
+ let entries = [];
95
+ let seq = 0;
96
+ let timer = null;
97
+ let closed = false;
98
+ let chain = Promise.resolve();
99
+ const later = (fn) => {
100
+ const run = chain.then(fn);
101
+ chain = run.catch((error) => log.error('launch window could not write', error));
102
+ return run.then(() => undefined);
103
+ };
104
+ const save = () => {
105
+ const json = JSON.stringify({ version: 1, schedules: entries.map((e) => e.schedule) }, null, 2);
106
+ return later(async () => {
107
+ const tmp = join(dir, `.${SCHEDULES_FILE}.${process.pid}.${randomBytes(4).toString('hex')}.tmp`);
108
+ await writeFile(tmp, json, { mode: FILE_MODE, flag: 'wx' });
109
+ await rename(tmp, path);
110
+ });
111
+ };
112
+ const view = (e) => ({ ...e.schedule, nextAt: e.next });
113
+ const list = () => entries.map(view);
114
+ /** Tells the browsers and saves; a failed save is logged by `later`, so the caller that does not wait may ignore it. */
115
+ const changed = () => {
116
+ options.emit(list());
117
+ return save();
118
+ };
119
+ const entryOf = (id) => {
120
+ const e = ID_RE.test(id) ? entries.find((x) => x.schedule.id === id) : undefined;
121
+ if (!e)
122
+ throw new HubError('not_found', 'unknown schedule');
123
+ return e;
124
+ };
125
+ const nextOf = (e) => (e.schedule.enabled ? nextFire(e.rule, now()) : null);
126
+ const fire = (e) => {
127
+ const s = e.schedule;
128
+ s.lastRunAt = now();
129
+ let failed = false;
130
+ try {
131
+ const sent = options.send({ to: s.to, subject: scheduleSubject(s.name, s.subject), body: s.body });
132
+ failed = !sent.ok;
133
+ s.lastResult = cut(sent.ok ? `sent ${sent.id}: ${sent.status}${sent.note ? ` (${sent.note})` : ''}` : `undelivered ${sent.id}: ${sent.note ?? 'no reason given'}`);
134
+ }
135
+ catch (error) {
136
+ failed = true;
137
+ s.lastResult = cut(`not sent: ${error instanceof Error ? error.message : String(error)}`);
138
+ }
139
+ if (failed)
140
+ options.notify?.('launch-window', `${s.name}: ${s.lastResult}`);
141
+ };
142
+ const tick = () => {
143
+ const t = now();
144
+ let any = false;
145
+ for (const e of entries) {
146
+ if (e.next === null || e.next > t)
147
+ continue;
148
+ const due = e.next;
149
+ e.next = nextFire(e.rule, t);
150
+ any = true;
151
+ if (t - due > SCHEDULE_GRACE_MS)
152
+ log.warn(`launch window "${e.schedule.name}" missed its fire at ${new Date(due).toISOString()}; missed fires are not replayed`);
153
+ else
154
+ fire(e);
155
+ }
156
+ if (any)
157
+ void changed().catch(() => undefined);
158
+ arm();
159
+ };
160
+ // On the minute: a timer that fires a millisecond early only finds nothing due and starts again for that millisecond.
161
+ function arm() {
162
+ if (!closed)
163
+ timer = options.setTimer(tick, MINUTE_MS - (now() % MINUTE_MS));
164
+ }
165
+ return {
166
+ async load() {
167
+ let saved = null;
168
+ try {
169
+ saved = JSON.parse(await readFile(path, 'utf8'));
170
+ if (!isRecord(saved) || saved.version !== 1 || !Array.isArray(saved.schedules))
171
+ throw new Error('not a version 1 schedules file');
172
+ }
173
+ catch (error) {
174
+ saved = null;
175
+ if (error.code !== 'ENOENT') {
176
+ // kept aside, so that the next save cannot overwrite what the Director wrote
177
+ log.error(`${SCHEDULES_FILE} could not be read; schedules start empty and the file is kept as ${SCHEDULES_FILE}.bad`, error);
178
+ await rename(path, `${path}.bad`).catch(() => undefined);
179
+ }
180
+ }
181
+ const t = now();
182
+ const records = isRecord(saved) && Array.isArray(saved.schedules) ? saved.schedules : [];
183
+ for (const raw of records) {
184
+ try {
185
+ if (!isRecord(raw) || typeof raw.id !== 'string' || !ID_RE.test(raw.id))
186
+ throw new Error('no valid id');
187
+ if (entries.some((x) => x.schedule.id === raw.id))
188
+ throw new Error(`the id ${raw.id} is used twice`);
189
+ const { id, createdAt, lastRunAt, lastResult } = raw;
190
+ const own = validate(Object.fromEntries(EDITABLE.map((k) => [k, raw[k]])), true);
191
+ const schedule = {
192
+ id,
193
+ name: own.name,
194
+ to: own.to,
195
+ subject: own.subject ?? '',
196
+ body: own.body,
197
+ rule: own.rule,
198
+ enabled: own.enabled === true,
199
+ createdAt: typeof createdAt === 'number' ? createdAt : t,
200
+ lastRunAt: typeof lastRunAt === 'number' ? lastRunAt : null,
201
+ lastResult: typeof lastResult === 'string' ? cut(lastResult) : null,
202
+ };
203
+ checkSubject(schedule);
204
+ const e = { schedule, rule: ruleOf(schedule.rule), next: null };
205
+ e.next = nextOf(e);
206
+ entries.push(e);
207
+ seq = Math.max(seq, Number(id.slice(1)));
208
+ }
209
+ catch (error) {
210
+ log.warn(`${SCHEDULES_FILE}: a schedule was skipped: ${error instanceof Error ? error.message : String(error)}`);
211
+ }
212
+ }
213
+ const missed = entries.filter((e) => {
214
+ const at = e.schedule.enabled ? nextFire(e.rule, e.schedule.lastRunAt ?? e.schedule.createdAt) : null;
215
+ // every fire before now counts: one in the last minute before the start is not sent either, so it is logged too
216
+ return at !== null && at <= t;
217
+ });
218
+ if (missed.length > 0)
219
+ log.warn(`launch window: fires were missed while gonogo was down (${missed.map((e) => e.schedule.name).join(', ')}); missed fires are not replayed`);
220
+ arm();
221
+ },
222
+ list,
223
+ async create(input) {
224
+ const request = validate(input, true);
225
+ if (entries.length >= SCHEDULES_MAX)
226
+ throw new HubError('conflict', `at most ${SCHEDULES_MAX} schedules`);
227
+ const schedule = {
228
+ id: `s${seq + 1}`,
229
+ name: request.name,
230
+ to: request.to,
231
+ subject: request.subject ?? '',
232
+ body: request.body,
233
+ rule: request.rule,
234
+ enabled: request.enabled ?? true,
235
+ createdAt: now(),
236
+ lastRunAt: null,
237
+ lastResult: null,
238
+ };
239
+ checkSubject(schedule);
240
+ seq += 1;
241
+ const e = { schedule, rule: ruleOf(schedule.rule), next: null };
242
+ e.next = nextOf(e);
243
+ entries.push(e);
244
+ await changed();
245
+ return view(e);
246
+ },
247
+ async update(id, input) {
248
+ const e = entryOf(id);
249
+ const patch = validate(input, false);
250
+ const next = { ...e.schedule, ...patch };
251
+ checkSubject(next);
252
+ e.schedule = next;
253
+ e.rule = ruleOf(next.rule);
254
+ e.next = nextOf(e);
255
+ await changed();
256
+ return view(e);
257
+ },
258
+ async remove(id) {
259
+ const e = entryOf(id);
260
+ entries = entries.filter((x) => x !== e);
261
+ await changed();
262
+ },
263
+ async run(id) {
264
+ const e = entryOf(id);
265
+ fire(e);
266
+ await changed();
267
+ return view(e);
268
+ },
269
+ close() {
270
+ closed = true;
271
+ if (timer !== null)
272
+ options.clearTimer(timer);
273
+ timer = null;
274
+ return chain.then(() => undefined);
275
+ },
276
+ };
277
+ }
@@ -0,0 +1,272 @@
1
+ /**
2
+ * Flight Plan: the task board (docs/flight-plan-spec.md).
3
+ *
4
+ * The Director (the browser) and every agent (the MCP tools task_list, task_create, task_update) change one list, kept in
5
+ * tasks.json. The server stamps who did what: `createdBy`, and one history line per change. Assigning a task to an agent
6
+ * sends that agent a message through the normal path: Hub.sendFromUser for the Director, Hub.sendFromAgent for an agent, so
7
+ * the send limit, Redline, held mail and the hop limit apply. The clock and the send are injected for tests.
8
+ *
9
+ * shortcut: the whole list is in every frame and every snapshot; at the limits (500 open tasks with 4000-character details)
10
+ * that nears the 4 MB socket buffer of web.ts. Send the details on demand if a board ever gets that big.
11
+ * shortcut: `assignee` is an agent name, so a task does not follow a renamed console and keeps the name of a removed one;
12
+ * key by record id if renames get common.
13
+ */
14
+ import { randomBytes } from 'node:crypto';
15
+ import { readFile, rename, writeFile } from 'node:fs/promises';
16
+ import { join } from 'node:path';
17
+ import { AGENT_NAME_PATTERN, STATION_NAME_PATTERN, SUBJECT_MAX_CHARS, TASK_DETAIL_MAX_CHARS, TASK_NOTE_MAX_CHARS, TASK_STATUSES, TASK_TITLE_MAX_CHARS, TASKS_OPEN_MAX, taskSubject, } from '../shared/protocol.js';
18
+ import { FILE_MODE, TASK_NOTES_MAX, TASKS_DONE_KEEP, TASKS_FILE } from './constants.js';
19
+ import { isRecord } from './hooks.js';
20
+ import { HubError } from './hub.js';
21
+ import { UNSAFE_IN_NAME } from './schedules.js';
22
+ const NAME_RE = new RegExp(AGENT_NAME_PATTERN);
23
+ const STATION_RE = new RegExp(STATION_NAME_PATTERN);
24
+ const ID_RE = /^t[1-9]\d{0,5}$/;
25
+ const CREATE_FIELDS = ['title', 'detail', 'assignee'];
26
+ const PATCH_FIELDS = ['status', 'assignee', 'note'];
27
+ const bad = (message, field) => new HubError('bad_request', message, field);
28
+ const copy = (task) => ({ ...task, notes: [...task.notes] });
29
+ const isOpen = (task) => task.status !== 'done';
30
+ /** "2026-11-17 14:03 UTC": a history line starts with it. */
31
+ const stamp = (at) => `${new Date(at).toISOString().slice(0, 16).replace('T', ' ')} UTC`;
32
+ const director = (actor) => (actor.kind === 'dock' ? `Director of ${actor.station}` : 'Director');
33
+ const line = (actor, text, at) => `${stamp(at)} ${actor.kind === 'agent' ? actor.name : director(actor)}: ${text}`;
34
+ /** The fields a request may carry, checked one by one. A task is made with a title; a change has at least one field. */
35
+ function validate(input, whole, isAgent) {
36
+ if (!isRecord(input))
37
+ throw bad('request body must be a JSON object');
38
+ const allowed = whole ? CREATE_FIELDS : PATCH_FIELDS;
39
+ for (const key of Object.keys(input))
40
+ if (!allowed.includes(key))
41
+ throw bad(`unknown field "${key}"`, key);
42
+ if (whole && input.title === undefined)
43
+ throw bad('title is required', 'title');
44
+ if (!whole && Object.keys(input).length === 0)
45
+ throw bad('nothing to change: give a status, an assignee or a note');
46
+ const out = {};
47
+ if (input.title !== undefined) {
48
+ const title = typeof input.title === 'string' ? input.title.trim() : '';
49
+ if (title === '' || title.length > TASK_TITLE_MAX_CHARS || UNSAFE_IN_NAME.test(title)) {
50
+ throw bad(`title must be 1 to ${TASK_TITLE_MAX_CHARS} characters on one line`, 'title');
51
+ }
52
+ out.title = title;
53
+ }
54
+ if (input.detail !== undefined) {
55
+ if (typeof input.detail !== 'string' || input.detail.length > TASK_DETAIL_MAX_CHARS)
56
+ throw bad(`detail must be text of at most ${TASK_DETAIL_MAX_CHARS} characters`, 'detail');
57
+ out.detail = input.detail.trim();
58
+ }
59
+ if (input.status !== undefined) {
60
+ if (typeof input.status !== 'string' || !TASK_STATUSES.includes(input.status))
61
+ throw bad(`status must be one of: ${TASK_STATUSES.join(', ')}`, 'status');
62
+ out.status = input.status;
63
+ }
64
+ if (input.assignee !== undefined) {
65
+ if (input.assignee !== null && (typeof input.assignee !== 'string' || !NAME_RE.test(input.assignee) || !isAgent(input.assignee))) {
66
+ throw bad('assignee must be the name of an agent in the room, or null', 'assignee');
67
+ }
68
+ out.assignee = input.assignee;
69
+ }
70
+ if (input.note !== undefined) {
71
+ // one line: the history is a list of lines
72
+ const note = typeof input.note === 'string' ? input.note.replace(/\s+/g, ' ').trim() : '';
73
+ if (note === '' || note.length > TASK_NOTE_MAX_CHARS || UNSAFE_IN_NAME.test(note))
74
+ throw bad(`note must be 1 to ${TASK_NOTE_MAX_CHARS} characters`, 'note');
75
+ out.note = note;
76
+ }
77
+ return out;
78
+ }
79
+ /** A saved record read back; one that is not a task throws, and the caller skips it. Unlike a request, it may name an agent that is gone. */
80
+ function fromRecord(raw, at) {
81
+ if (!isRecord(raw) || typeof raw.id !== 'string' || !ID_RE.test(raw.id))
82
+ throw new Error('no valid id');
83
+ const { id, title, detail, status, assignee, createdBy, createdAt, updatedAt, notes, handedOff } = raw;
84
+ if (typeof title !== 'string' || title === '' || title.length > TASK_TITLE_MAX_CHARS)
85
+ throw new Error('no valid title');
86
+ if (typeof status !== 'string' || !TASK_STATUSES.includes(status))
87
+ throw new Error('no valid status');
88
+ return {
89
+ id,
90
+ title,
91
+ detail: typeof detail === 'string' ? detail.slice(0, TASK_DETAIL_MAX_CHARS) : '',
92
+ status: status,
93
+ assignee: typeof assignee === 'string' && NAME_RE.test(assignee) ? assignee : null,
94
+ createdBy: typeof createdBy === 'string' && NAME_RE.test(createdBy) ? createdBy : 'user',
95
+ createdAt: typeof createdAt === 'number' ? createdAt : at,
96
+ updatedAt: typeof updatedAt === 'number' ? updatedAt : at,
97
+ notes: Array.isArray(notes) ? notes.filter((n) => typeof n === 'string').slice(-TASK_NOTES_MAX) : [],
98
+ ...(typeof handedOff === 'string' && STATION_RE.test(handedOff) ? { handedOff } : {}),
99
+ };
100
+ }
101
+ export function createTasks(options) {
102
+ const { dir, now, log } = options;
103
+ const path = join(dir, TASKS_FILE);
104
+ let tasks = [];
105
+ let seq = 0;
106
+ let chain = Promise.resolve();
107
+ const later = (fn) => {
108
+ const run = chain.then(fn);
109
+ chain = run.catch((error) => log.error('flight plan could not write', error));
110
+ return run.then(() => undefined);
111
+ };
112
+ const save = () => {
113
+ // `seq` is the number of the last id given, so an id that was removed or dropped is not given again after a restart
114
+ const json = JSON.stringify({ version: 1, seq, tasks }, null, 2);
115
+ return later(async () => {
116
+ const tmp = join(dir, `.${TASKS_FILE}.${process.pid}.${randomBytes(4).toString('hex')}.tmp`);
117
+ await writeFile(tmp, json, { mode: FILE_MODE, flag: 'wx' });
118
+ await rename(tmp, path);
119
+ });
120
+ };
121
+ const list = () => tasks.map(copy);
122
+ /** Tells the browsers and saves. */
123
+ const changed = () => {
124
+ options.emit(list());
125
+ return save();
126
+ };
127
+ const find = (id) => {
128
+ const task = ID_RE.test(id) ? tasks.find((x) => x.id === id) : undefined;
129
+ if (!task)
130
+ throw new HubError('not_found', 'unknown task');
131
+ return task;
132
+ };
133
+ const full = () => new HubError('conflict', `at most ${TASKS_OPEN_MAX} open tasks: finish or remove one first`, 'tasks');
134
+ /** Done tasks are history: the newest TASKS_DONE_KEEP stay, so the file and every frame stop growing. */
135
+ const prune = () => {
136
+ const done = tasks.filter((x) => !isOpen(x));
137
+ if (done.length <= TASKS_DONE_KEEP)
138
+ return;
139
+ const drop = new Set(done.sort((a, b) => b.updatedAt - a.updatedAt).slice(TASKS_DONE_KEEP));
140
+ tasks = tasks.filter((x) => !drop.has(x));
141
+ };
142
+ /**
143
+ * Tells the assignee of `task`. Runs before the change is stored, so a refusal of the hub (the session of the acting agent
144
+ * ended, the recipient is being removed) leaves the board as it was. A message that was made but not delivered is a note.
145
+ */
146
+ const tell = (actor, task, at) => {
147
+ const to = task.assignee;
148
+ if (to === null || (actor.kind === 'agent' && actor.name === to))
149
+ return;
150
+ const by = actor.kind === 'agent' ? actor.name : `the ${director(actor)}`;
151
+ const body = `${task.detail === '' ? '(no detail)' : task.detail}\n\nAssigned by ${by}. Set its status with task_update.`;
152
+ const sent = options.send(actor, { to, subject: taskSubject(task.id, task.title).slice(0, SUBJECT_MAX_CHARS), body });
153
+ if (!sent.ok)
154
+ task.notes.push(line(actor, `the message to ${to} was not delivered: ${sent.note ?? 'no reason given'}`, at));
155
+ };
156
+ return {
157
+ async load() {
158
+ let saved = null;
159
+ try {
160
+ saved = JSON.parse(await readFile(path, 'utf8'));
161
+ if (!isRecord(saved) || saved.version !== 1 || !Array.isArray(saved.tasks))
162
+ throw new Error('not a version 1 tasks file');
163
+ }
164
+ catch (error) {
165
+ saved = null;
166
+ if (error.code !== 'ENOENT') {
167
+ // kept aside, so that the next save cannot overwrite what the Director and the agents wrote
168
+ log.error(`${TASKS_FILE} could not be read; the board starts empty and the file is kept as ${TASKS_FILE}.bad`, error instanceof SyntaxError ? 'not valid JSON' : error);
169
+ await rename(path, `${path}.bad`).catch(() => undefined);
170
+ }
171
+ }
172
+ const records = isRecord(saved) && Array.isArray(saved.tasks) ? saved.tasks : [];
173
+ if (isRecord(saved) && typeof saved.seq === 'number' && Number.isSafeInteger(saved.seq) && saved.seq > 0)
174
+ seq = saved.seq;
175
+ for (const raw of records) {
176
+ try {
177
+ const task = fromRecord(raw, now());
178
+ if (tasks.some((x) => x.id === task.id))
179
+ throw new Error(`the id ${task.id} is used twice`);
180
+ tasks.push(task);
181
+ seq = Math.max(seq, Number(task.id.slice(1)));
182
+ }
183
+ catch (error) {
184
+ log.warn(`${TASKS_FILE}: a task was skipped: ${error instanceof Error ? error.message : String(error)}`);
185
+ }
186
+ }
187
+ },
188
+ list,
189
+ async create(actor, input) {
190
+ const request = validate(input, true, options.isAgent);
191
+ if (tasks.filter(isOpen).length >= TASKS_OPEN_MAX)
192
+ throw full();
193
+ const at = now();
194
+ const task = {
195
+ id: `t${seq + 1}`,
196
+ title: request.title ?? '',
197
+ detail: request.detail ?? '',
198
+ status: 'todo',
199
+ assignee: request.assignee ?? null,
200
+ createdBy: actor.kind === 'agent' ? actor.name : 'user',
201
+ createdAt: at,
202
+ updatedAt: at,
203
+ notes: [],
204
+ };
205
+ task.notes.push(line(actor, task.assignee === null ? 'created' : `created; assigned to ${task.assignee}`, at));
206
+ tell(actor, task, at);
207
+ seq += 1;
208
+ tasks.push(task);
209
+ prune();
210
+ await changed();
211
+ return copy(task);
212
+ },
213
+ async handOff(id, station, assignee) {
214
+ const task = find(id);
215
+ if (!isOpen(task) || task.handedOff !== undefined)
216
+ throw new HubError('conflict', 'only a task that is open here can be handed off', 'task');
217
+ const at = now();
218
+ const next = copy(task);
219
+ next.status = 'done';
220
+ next.handedOff = station;
221
+ next.updatedAt = at;
222
+ next.notes.push(line({ kind: 'user' }, `handed off to ${assignee === null ? '' : `${assignee}@`}${station}`, at));
223
+ next.notes = next.notes.slice(-TASK_NOTES_MAX);
224
+ tasks[tasks.indexOf(task)] = next;
225
+ prune();
226
+ await changed();
227
+ return copy(next);
228
+ },
229
+ async update(actor, id, input) {
230
+ const task = find(id);
231
+ const patch = validate(input, false, options.isAgent);
232
+ const at = now();
233
+ const next = copy(task);
234
+ const parts = [];
235
+ if (patch.status !== undefined && patch.status !== task.status) {
236
+ if (!isOpen(task) && patch.status !== 'done' && tasks.filter(isOpen).length >= TASKS_OPEN_MAX)
237
+ throw full();
238
+ next.status = patch.status;
239
+ parts.push(`status ${patch.status}`);
240
+ }
241
+ if (patch.assignee !== undefined && patch.assignee !== task.assignee) {
242
+ next.assignee = patch.assignee;
243
+ parts.push(patch.assignee === null ? 'unassigned' : `assigned to ${patch.assignee}`);
244
+ }
245
+ if (patch.note !== undefined)
246
+ parts.push(patch.note);
247
+ if (parts.length === 0)
248
+ return copy(task);
249
+ next.updatedAt = at;
250
+ next.notes.push(line(actor, parts.join('; '), at));
251
+ if (next.assignee !== task.assignee)
252
+ tell(actor, next, at);
253
+ next.notes = next.notes.slice(-TASK_NOTES_MAX);
254
+ tasks[tasks.indexOf(task)] = next;
255
+ // the Director sees what he moved himself; the inbox is for what an agent did
256
+ if (actor.kind === 'agent' && next.status !== task.status && (next.status === 'blocked' || next.status === 'review')) {
257
+ options.notify?.('flight-plan', `${actor.name} moved ${next.id} to ${next.status}: ${next.title}`);
258
+ }
259
+ prune();
260
+ await changed();
261
+ return copy(next);
262
+ },
263
+ async remove(id) {
264
+ const task = find(id);
265
+ tasks = tasks.filter((x) => x !== task);
266
+ await changed();
267
+ },
268
+ close() {
269
+ return chain.then(() => undefined);
270
+ },
271
+ };
272
+ }