pisha-server 0.0.0-stage → 0.0.12

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 (129) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +40 -2
  3. package/accounts/accounts.js +754 -0
  4. package/accounts/index.js +1 -0
  5. package/accounts/passwords.js +41 -0
  6. package/accounts/totp.js +54 -0
  7. package/boards/boards.js +1087 -0
  8. package/boards/github.js +212 -0
  9. package/boards/index.js +1 -0
  10. package/boards/sync.js +980 -0
  11. package/companies.js +294 -0
  12. package/company-export.js +101 -0
  13. package/company.js +82 -0
  14. package/dashboard/dashboard.js +408 -0
  15. package/dashboard/index.js +1 -0
  16. package/data-upgrade.js +69 -0
  17. package/install/linux.sh +181 -0
  18. package/install/macos.sh +121 -0
  19. package/install/windows.bat +54 -0
  20. package/machines/index.js +3 -0
  21. package/machines/machines.js +910 -0
  22. package/messaging/inbox.js +252 -0
  23. package/messaging/index.js +3 -0
  24. package/messaging/messaging.js +551 -0
  25. package/messaging/plans.js +67 -0
  26. package/observation/index.js +1 -0
  27. package/observation/observation.js +231 -0
  28. package/organization/index.js +1 -0
  29. package/organization/organization.js +218 -0
  30. package/package.json +55 -4
  31. package/permissions/index.js +1 -0
  32. package/permissions/permissions.js +211 -0
  33. package/pisha-host.mjs +3303 -0
  34. package/pisha-host.mjs.sig +1 -0
  35. package/platform/acme.js +207 -0
  36. package/platform/basics.js +14 -0
  37. package/platform/config.js +154 -0
  38. package/platform/control.js +93 -0
  39. package/platform/credentials.js +151 -0
  40. package/platform/database.js +251 -0
  41. package/platform/errors.js +13 -0
  42. package/platform/files.js +50 -0
  43. package/platform/http.js +207 -0
  44. package/platform/index.js +58 -0
  45. package/platform/limits.js +122 -0
  46. package/platform/listen.js +183 -0
  47. package/platform/roles.js +6 -0
  48. package/platform/stream.js +19 -0
  49. package/platform/text.js +83 -0
  50. package/platform/ws.js +186 -0
  51. package/routes.js +405 -0
  52. package/server.js +65 -0
  53. package/sessions/index.js +1 -0
  54. package/sessions/sessions.js +533 -0
  55. package/ui/LICENSE-affectui.txt +26 -0
  56. package/ui/addmachine.js +151 -0
  57. package/ui/api.js +20 -0
  58. package/ui/app.js +143 -0
  59. package/ui/attention.js +78 -0
  60. package/ui/back.js +168 -0
  61. package/ui/boards.js +958 -0
  62. package/ui/chat.js +388 -0
  63. package/ui/content.js +157 -0
  64. package/ui/dialogs.js +135 -0
  65. package/ui/doing.js +112 -0
  66. package/ui/dom.js +6 -0
  67. package/ui/ds-base.css +146 -0
  68. package/ui/ds-components.css +229 -0
  69. package/ui/fonts/LICENSE-space-grotesk.txt +93 -0
  70. package/ui/fonts/space-grotesk-latin-700-normal.woff2 +0 -0
  71. package/ui/fonts/space-grotesk-latin-ext-700-normal.woff2 +0 -0
  72. package/ui/format.js +25 -0
  73. package/ui/i18n.js +2145 -0
  74. package/ui/icons/apple-touch-icon.png +0 -0
  75. package/ui/icons/icon-192.png +0 -0
  76. package/ui/icons/icon-512.png +0 -0
  77. package/ui/icons/maskable-512.png +0 -0
  78. package/ui/icons.js +41 -0
  79. package/ui/inbox.js +535 -0
  80. package/ui/index.html +105 -0
  81. package/ui/machines.js +261 -0
  82. package/ui/manifest.webmanifest +16 -0
  83. package/ui/mosaic.js +189 -0
  84. package/ui/nav.js +142 -0
  85. package/ui/newteam.js +223 -0
  86. package/ui/org.js +669 -0
  87. package/ui/overlays.css +126 -0
  88. package/ui/palette.js +180 -0
  89. package/ui/people.js +371 -0
  90. package/ui/permissions.js +202 -0
  91. package/ui/qr.js +158 -0
  92. package/ui/router.js +173 -0
  93. package/ui/routes.js +47 -0
  94. package/ui/screen-boards.css +241 -0
  95. package/ui/screen-inbox.css +201 -0
  96. package/ui/screen-machines.css +76 -0
  97. package/ui/screen-mosaic.css +26 -0
  98. package/ui/screen-newteam.css +90 -0
  99. package/ui/screen-org.css +119 -0
  100. package/ui/screen-session.css +99 -0
  101. package/ui/screen-signin.css +28 -0
  102. package/ui/screen-team.css +80 -0
  103. package/ui/screen-teams.css +41 -0
  104. package/ui/screen-usage.css +60 -0
  105. package/ui/session.js +42 -0
  106. package/ui/shell.css +122 -0
  107. package/ui/signin.js +120 -0
  108. package/ui/squads.js +371 -0
  109. package/ui/state.js +59 -0
  110. package/ui/stream.js +269 -0
  111. package/ui/styles.css +343 -0
  112. package/ui/team.js +115 -0
  113. package/ui/teams.js +58 -0
  114. package/ui/terminal.js +261 -0
  115. package/ui/theme.js +32 -0
  116. package/ui/timeline.js +163 -0
  117. package/ui/topbar.js +211 -0
  118. package/ui/usage.js +175 -0
  119. package/ui/voice-parse.js +98 -0
  120. package/ui/voice.js +320 -0
  121. package/usage/index.js +1 -0
  122. package/usage/usage.js +127 -0
  123. package/vendor/InterVariable.woff2 +0 -0
  124. package/vendor/LICENSE-inter +92 -0
  125. package/vendor/LICENSE-xterm +21 -0
  126. package/vendor/README.md +8 -0
  127. package/vendor/addon-fit.js +2 -0
  128. package/vendor/xterm.css +218 -0
  129. package/vendor/xterm.js +2 -0
@@ -0,0 +1,1087 @@
1
+ import { now, cleanText, bad, ApiError } from '../platform/index.js'
2
+ import { createGithubSync } from './sync.js'
3
+
4
+ // Task boards: the company's, each seen by one or more teams. People and
5
+ // agents work on the same tasks; a task is someone's, a person's or a
6
+ // session's. Assigning never sets anyone to work by itself: the coordinator of
7
+ // the team hears of it only when a person says so (now, or later with the
8
+ // others: "notify the teams"), and always hears when it stops being its team's.
9
+ //
10
+ // Who asks:
11
+ // people the dashboard, with their role in the company (see dashboard.js)
12
+ // agents the plugin's board tool: a coordinator sees the boards of its team
13
+ // and changes what is its team's or nobody's; a worker sees only
14
+ // its own tasks, moves them as its column's step says (or, with no
15
+ // step, up to review) and comments on them.
16
+ //
17
+ // A column can be a step of the board's flow, as the people set it: who
18
+ // handles it (a person, a team's coordinator or one agent), what to do there,
19
+ // and where a task goes once done there, or back to if it isn't acceptable.
20
+ // A task moved into it is that one's: told at once when an agent moved it
21
+ // (the flow is the people's word), asked first when a person did.
22
+ //
23
+ // A task can have subtasks, as GitHub's sub-issues: each a task of its own on
24
+ // the same board (its card, status and who has it), up to 8 levels deep.
25
+
26
+ // Sent by the server itself: no session can have this name (see NAME_RE).
27
+ export const BOARD_SENDER = 'pisha:board'
28
+ export const CATEGORIES = ['backlog', 'unstarted', 'started', 'review', 'done', 'closed']
29
+ export const COLORS = ['gray', 'blue', 'green', 'yellow', 'orange', 'red', 'purple', 'pink']
30
+ // Where a task waits to be worked on: notifying a team of it makes sense.
31
+ const ACTIVE = new Set(['unstarted', 'started', 'review'])
32
+ const DEFAULT_STATUSES = [['Backlog', 'backlog'], ['To do', 'unstarted'], ['In progress', 'started'], ['In review', 'review'], ['Done', 'done'], ['Cancelled', 'closed']]
33
+ const DEFAULT_TYPES = [['Task', 'blue'], ['Bug', 'red']]
34
+ const PREFIX_RE = /^[A-Z][A-Z0-9]{0,5}$/
35
+ const DUE_RE = /^\d{4}-\d{2}-\d{2}$/
36
+ const MAX = {
37
+ boards: 100, statuses: 20, labels: 60, types: 20, teams: 50, tasks: 5000, name: 60, boardDescription: 1000,
38
+ title: 200, description: 20_000, comment: 8000, instructions: 4000, comments: 500, events: 200, labelsPerTask: 20,
39
+ subtasks: 100, depth: 8, // (as GitHub: 100 sub-issues on an issue, 8 levels)
40
+ people: 10, // (as GitHub: 10 assignees on an issue)
41
+ }
42
+ const AGENT_CHANGES_PER_HOUR = 300
43
+
44
+ export function createBoards(platform, { sessions, messaging, members }) {
45
+ const { db, broadcast, allow, rateLimit, spendStorage, inTx, log } = platform
46
+ let sync = null // (a board kept in step with GitHub: see sync.js)
47
+ const { NAME_RE, identityExists } = sessions
48
+
49
+ db.exec(`
50
+ CREATE TABLE IF NOT EXISTS board_settings (k TEXT PRIMARY KEY, v TEXT);
51
+ CREATE TABLE IF NOT EXISTS boards (
52
+ id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, description TEXT,
53
+ created_by TEXT, created_at INTEGER NOT NULL, updated_at INTEGER NOT NULL, archived_at INTEGER
54
+ );
55
+ CREATE TABLE IF NOT EXISTS board_teams (board_id INTEGER NOT NULL REFERENCES boards(id) ON DELETE CASCADE, coordinator TEXT NOT NULL, PRIMARY KEY (board_id, coordinator));
56
+ CREATE TABLE IF NOT EXISTS board_statuses (
57
+ id INTEGER PRIMARY KEY AUTOINCREMENT, board_id INTEGER NOT NULL REFERENCES boards(id) ON DELETE CASCADE, name TEXT NOT NULL, category TEXT NOT NULL, position INTEGER NOT NULL,
58
+ handler_kind TEXT, handler TEXT, instructions TEXT, next_id INTEGER, back_id INTEGER
59
+ );
60
+ CREATE TABLE IF NOT EXISTS board_labels (id INTEGER PRIMARY KEY AUTOINCREMENT, board_id INTEGER NOT NULL REFERENCES boards(id) ON DELETE CASCADE, name TEXT NOT NULL, color TEXT NOT NULL, position INTEGER NOT NULL);
61
+ CREATE TABLE IF NOT EXISTS board_types (id INTEGER PRIMARY KEY AUTOINCREMENT, board_id INTEGER NOT NULL REFERENCES boards(id) ON DELETE CASCADE, name TEXT NOT NULL, color TEXT NOT NULL, position INTEGER NOT NULL);
62
+ CREATE TABLE IF NOT EXISTS tasks (
63
+ seq INTEGER PRIMARY KEY AUTOINCREMENT,
64
+ board_id INTEGER NOT NULL REFERENCES boards(id) ON DELETE CASCADE,
65
+ title TEXT NOT NULL, description TEXT,
66
+ status_id INTEGER NOT NULL, type_id INTEGER, priority INTEGER NOT NULL DEFAULT 0, due TEXT, rank REAL NOT NULL,
67
+ assignee_kind TEXT, assignee TEXT,
68
+ notify_state TEXT NOT NULL DEFAULT 'none', notified_to TEXT,
69
+ created_by TEXT NOT NULL, created_at INTEGER NOT NULL, updated_by TEXT NOT NULL, updated_at INTEGER NOT NULL,
70
+ version INTEGER NOT NULL DEFAULT 1,
71
+ parent_seq INTEGER REFERENCES tasks(seq) ON DELETE SET NULL
72
+ );
73
+ CREATE INDEX IF NOT EXISTS tasks_board ON tasks(board_id, rank);
74
+ CREATE INDEX IF NOT EXISTS tasks_assignee ON tasks(assignee_kind, assignee);
75
+ CREATE TABLE IF NOT EXISTS task_labels (task_seq INTEGER NOT NULL REFERENCES tasks(seq) ON DELETE CASCADE, label_id INTEGER NOT NULL REFERENCES board_labels(id) ON DELETE CASCADE, PRIMARY KEY (task_seq, label_id));
76
+ CREATE TABLE IF NOT EXISTS task_comments (id INTEGER PRIMARY KEY AUTOINCREMENT, task_seq INTEGER NOT NULL REFERENCES tasks(seq) ON DELETE CASCADE, author TEXT NOT NULL, text TEXT NOT NULL, notified TEXT, created_at INTEGER NOT NULL);
77
+ CREATE INDEX IF NOT EXISTS task_comments_task ON task_comments(task_seq, id);
78
+ CREATE TABLE IF NOT EXISTS task_events (id INTEGER PRIMARY KEY AUTOINCREMENT, task_seq INTEGER NOT NULL REFERENCES tasks(seq) ON DELETE CASCADE, at INTEGER NOT NULL, who TEXT NOT NULL, what TEXT NOT NULL, data TEXT);
79
+ CREATE INDEX IF NOT EXISTS task_events_task ON task_events(task_seq, id);
80
+ `)
81
+ // (Columns added since the first boards.)
82
+ const addColumn = (table, column, type) => { if (!db.prepare(`PRAGMA table_info(${table})`).all().some(c => c.name === column)) db.exec(`ALTER TABLE ${table} ADD COLUMN ${column} ${type}`) }
83
+ addColumn('tasks', 'parent_seq', 'INTEGER REFERENCES tasks(seq) ON DELETE SET NULL')
84
+ db.exec('CREATE INDEX IF NOT EXISTS tasks_parent ON tasks(parent_seq)')
85
+ // (Deleting a task puts it in the board's trash: it can be restored, it is never gone for good.)
86
+ addColumn('tasks', 'deleted_at', 'INTEGER')
87
+ addColumn('tasks', 'deleted_by', 'TEXT')
88
+ // (A comment edited or deleted on GitHub: edited here too; deleted, kept but no longer shown.)
89
+ addColumn('task_comments', 'edited_at', 'INTEGER')
90
+ addColumn('task_comments', 'deleted_at', 'INTEGER')
91
+ addColumn('tasks', 'trash_batch', 'INTEGER') // (the task whose deletion took it: its subtasks go back with it)
92
+ // A task has at most one agent (the session that works on it, and is told),
93
+ // and any people besides, up to 10: as GitHub's Agent field and assignees.
94
+ // (Tasks given to a person before: that person is one of its people now.)
95
+ db.exec(`
96
+ CREATE TABLE IF NOT EXISTS task_people (task_seq INTEGER NOT NULL REFERENCES tasks(seq) ON DELETE CASCADE, user_id TEXT NOT NULL, position INTEGER NOT NULL, PRIMARY KEY (task_seq, user_id));
97
+ INSERT OR IGNORE INTO task_people (task_seq, user_id, position) SELECT seq, assignee, 0 FROM tasks WHERE assignee_kind = 'user';
98
+ UPDATE tasks SET assignee_kind = NULL, assignee = NULL, notify_state = 'none', notified_to = NULL WHERE assignee_kind = 'user';
99
+ `)
100
+
101
+ // --- who is who ---------------------------------------------------------------
102
+ // Someone is kept as JSON {kind, id, name}: a person (kind user, by their id)
103
+ // or a session (kind session, by its name). The name is how they were called
104
+ // then: a person who left still reads as they were.
105
+ const person = actor => ({ kind: 'user', id: actor?.id ?? 'server', name: actor?.name ?? 'server token' })
106
+ const agent = name => ({ kind: 'session', id: name, name })
107
+ const who = text => { try { return JSON.parse(text) } catch { return null } }
108
+
109
+ const prefix = () => db.prepare("SELECT v FROM board_settings WHERE k = 'prefix'").get()?.v ?? 'SQ'
110
+ const taskId = seq => `${prefix()}-${seq}`
111
+ // The first of this company's tasks a text names ("SQ-12", with its prefix), or null.
112
+ function taskIn(text) {
113
+ const p = prefix()
114
+ for (const m of String(text ?? '').slice(0, 20_000).matchAll(/\b([A-Z][A-Z0-9]{0,5})-(\d{1,9})\b/g)) {
115
+ if (m[1] === p && db.prepare('SELECT 1 FROM tasks WHERE seq = ? AND deleted_at IS NULL').get(Number(m[2]))) return `${p}-${Number(m[2])}`
116
+ }
117
+ return null
118
+ }
119
+ // "SQ-12", "sq-12", "#12" or 12.
120
+ function seqOf(id) {
121
+ const m = /^(?:[A-Za-z][A-Za-z0-9]{0,5}-|#)?(\d{1,9})$/.exec(String(id ?? '').trim())
122
+ if (!m) throw bad(`"${String(id ?? '').slice(0, 40)}" is not a task id (such as ${prefix()}-12)`)
123
+ return Number(m[1])
124
+ }
125
+
126
+ // The team a session is in: a coordinator's own name, a worker's coordinator.
127
+ // (Until it first logs in, what it was opened as.)
128
+ function teamOf(name) {
129
+ const r = db.prepare('SELECT role, coordinator, opened_role, opened_coordinator, host_id FROM identities WHERE name = ?').get(name)
130
+ if (!r) return null
131
+ const role = r.role ?? (r.host_id ? r.opened_role : null)
132
+ if (role === 'coordinator') return name
133
+ if (role === 'worker') return (r.role ? r.coordinator : r.opened_coordinator) ?? null
134
+ return null
135
+ }
136
+ const teamsOf = boardId => db.prepare('SELECT coordinator FROM board_teams WHERE board_id = ? ORDER BY coordinator').all(boardId).map(r => r.coordinator)
137
+ const memberList = () => { try { return members() } catch (err) { log(`members of the company could not be read: ${err.message}`); return [] } }
138
+ const memberName = id => memberList().find(m => m.id === id)?.name ?? null
139
+
140
+ // Who a board's tasks can be given to: the company's people, and the
141
+ // sessions of the teams that see it.
142
+ function assignableSessions(boardId) {
143
+ const teams = new Set(teamsOf(boardId))
144
+ return db.prepare('SELECT name FROM identities ORDER BY name').all().map(r => r.name)
145
+ .map(name => ({ name, team: teamOf(name) })).filter(s => s.team && teams.has(s.team))
146
+ }
147
+ function checkAssignee(boardId, a) {
148
+ if (a == null) return null
149
+ if (typeof a !== 'object') throw bad('assignee must be {kind: "user" | "session", id} or null')
150
+ const id = String(a.id ?? '')
151
+ if (a.kind === 'user') {
152
+ const m = memberList().find(x => x.id === id)
153
+ if (!m) throw bad('that person is not in this company')
154
+ return { kind: 'user', id, name: m.name }
155
+ }
156
+ if (a.kind === 'session') {
157
+ if (!NAME_RE.test(id) || !identityExists(id)) throw bad(`there is no session "${id.slice(0, 40)}"`)
158
+ const team = teamOf(id)
159
+ if (!team || !teamsOf(boardId).includes(team)) throw bad(`"${id}" is not in a team that sees this board`)
160
+ return { kind: 'session', id, name: id }
161
+ }
162
+ throw bad('assignee must be {kind: "user" | "session", id} or null')
163
+ }
164
+
165
+ const peopleOf = seq => db.prepare('SELECT user_id FROM task_people WHERE task_seq = ? ORDER BY position, user_id').all(seq).map(r => r.user_id)
166
+ // A list of the company's people (their ids), checked.
167
+ function checkPeople(list) {
168
+ if (list === null) return []
169
+ if (!Array.isArray(list)) throw bad('people must be a list of the company\'s people (their ids)')
170
+ const ids = [...new Set(list.map(x => String(typeof x === 'object' && x ? x.id : x)))]
171
+ if (ids.length > MAX.people) throw bad(`at most ${MAX.people} people on a task`)
172
+ const all = memberList()
173
+ for (const id of ids) if (!all.some(m => m.id === id)) throw bad('that person is not in this company')
174
+ return ids
175
+ }
176
+ // What the dashboard says of who has it: the agent (assignee), and the people.
177
+ // (An assignee that is a person, as before: that person, and no agent.)
178
+ function agentParam(board, p) {
179
+ if (p.assignee?.kind === 'user') { if (p.people === undefined) p.people = [p.assignee.id]; return null }
180
+ return p.assignee === undefined ? undefined : checkAssignee(board.id, p.assignee)
181
+ }
182
+ const withPerson = (list, id) => (list.includes(id) ? list : [...list, id].slice(0, MAX.people))
183
+
184
+ // --- reading ------------------------------------------------------------------
185
+ const short = (value, max, what, { lines = false } = {}) => {
186
+ let text = cleanText(String(value ?? ''))
187
+ text = lines ? text.replace(/\r\n?/g, '\n').trim() : text.replace(/\s+/g, ' ').trim()
188
+ if (text.length > max) throw bad(`${what} is too long (max ${max} chars)`)
189
+ return text
190
+ }
191
+
192
+ // A column, with its step when it has one: who handles it, what to do, where next.
193
+ const statusView = r => ({
194
+ id: r.id, name: r.name, category: r.category,
195
+ handler: r.handler_kind ? { kind: r.handler_kind, id: r.handler, name: r.handler_kind === 'user' ? memberName(r.handler) ?? '?' : r.handler } : null,
196
+ instructions: r.instructions ?? '', next: r.next_id ?? null, back: r.back_id ?? null,
197
+ })
198
+ const statusesOf = boardId => db.prepare('SELECT * FROM board_statuses WHERE board_id = ? ORDER BY position, id').all(boardId).map(statusView)
199
+ const labelsOf = boardId => db.prepare('SELECT id, name, color FROM board_labels WHERE board_id = ? ORDER BY position, id').all(boardId)
200
+ const typesOf = boardId => db.prepare('SELECT id, name, color FROM board_types WHERE board_id = ? ORDER BY position, id').all(boardId)
201
+ const boardRow = id => db.prepare('SELECT * FROM boards WHERE id = ?').get(Number(id))
202
+
203
+ function boardView(b) {
204
+ const counts = Object.fromEntries(db.prepare('SELECT status_id, COUNT(*) n FROM tasks WHERE board_id = ? AND deleted_at IS NULL GROUP BY status_id').all(b.id).map(r => [r.status_id, r.n]))
205
+ return {
206
+ id: b.id, name: b.name, description: b.description ?? '', created_at: b.created_at, updated_at: b.updated_at, archived_at: b.archived_at ?? null,
207
+ teams: teamsOf(b.id), statuses: statusesOf(b.id).map(s => ({ ...s, tasks: counts[s.id] ?? 0 })), labels: labelsOf(b.id), types: typesOf(b.id),
208
+ pending: pendingOf(b.id).length, github: sync?.view(b.id) ?? null,
209
+ trash: db.prepare('SELECT COUNT(*) n FROM tasks WHERE board_id = ? AND deleted_at IS NOT NULL').get(b.id).n,
210
+ }
211
+ }
212
+ const boardList = () => db.prepare('SELECT * FROM boards ORDER BY archived_at IS NOT NULL, name COLLATE NOCASE, id').all().map(boardView)
213
+
214
+ function taskView(t, { full = false } = {}) {
215
+ const labels = db.prepare('SELECT label_id FROM task_labels WHERE task_seq = ? ORDER BY label_id').all(t.seq).map(r => r.label_id)
216
+ const assignee = t.assignee_kind ? { kind: t.assignee_kind, id: t.assignee, name: t.assignee_kind === 'user' ? memberName(t.assignee) ?? '?' : t.assignee } : null
217
+ const people = peopleOf(t.seq).map(id => ({ id, name: memberName(id) })).filter(x => x.name) // (one who left the company: no longer shown)
218
+ const view = {
219
+ id: taskId(t.seq), seq: t.seq, board: t.board_id, title: t.title, status: t.status_id, type: t.type_id ?? null, labels,
220
+ priority: t.priority, due: t.due ?? null, rank: t.rank, assignee, people, notify: t.notify_state, notified_to: t.notified_to ?? null,
221
+ created_by: who(t.created_by), created_at: t.created_at, updated_by: who(t.updated_by), updated_at: t.updated_at, version: t.version,
222
+ comments: db.prepare('SELECT COUNT(*) n FROM task_comments WHERE task_seq = ? AND deleted_at IS NULL').get(t.seq).n,
223
+ parent: t.parent_seq ?? null, subtasks: progressOf(t.seq), prs: sync?.prsOf(t.seq) ?? [],
224
+ }
225
+ if (!full) return view
226
+ return {
227
+ ...view,
228
+ description: t.description ?? '',
229
+ comments: db.prepare('SELECT id, author, text, notified, created_at, edited_at FROM task_comments WHERE task_seq = ? AND deleted_at IS NULL ORDER BY id').all(t.seq)
230
+ .map(c => ({ id: c.id, author: who(c.author), text: c.text, notified: c.notified ?? null, created_at: c.created_at, edited_at: c.edited_at ?? null })),
231
+ events: db.prepare('SELECT at, who, what, data FROM task_events WHERE task_seq = ? ORDER BY id DESC LIMIT 100').all(t.seq).reverse()
232
+ .map(e => ({ at: e.at, who: who(e.who), what: e.what, data: e.data ? JSON.parse(e.data) : null })),
233
+ parent_title: t.parent_seq ? taskRow(t.parent_seq)?.title ?? null : null,
234
+ github: (l => (l?.url ? { url: l.url, number: l.number, repo: l.repo } : l ? { draft: true } : null))(sync?.linkOf(t.seq)),
235
+ children: childrenOf(t.seq).map(c => ({ seq: c.seq, id: taskId(c.seq), title: c.title, status: c.status_id, assignee: c.assignee_kind ? { kind: c.assignee_kind, id: c.assignee, name: c.assignee_kind === 'user' ? memberName(c.assignee) ?? '?' : c.assignee } : null, people: peopleOf(c.seq).map(id => ({ id, name: memberName(id) })).filter(x => x.name), subtasks: progressOf(c.seq) })),
236
+ }
237
+ }
238
+ // --- subtasks -------------------------------------------------------------------
239
+ const childrenOf = seq => db.prepare('SELECT * FROM tasks WHERE parent_seq = ? AND deleted_at IS NULL ORDER BY rank, seq').all(seq)
240
+ // How many it has, and how many of those are finished (done or cancelled, as GitHub counts closed ones).
241
+ function progressOf(seq) {
242
+ const r = db.prepare("SELECT COUNT(*) total, COALESCE(SUM(s.category IN ('done', 'closed')), 0) done FROM tasks c JOIN board_statuses s ON s.id = c.status_id WHERE c.parent_seq = ? AND c.deleted_at IS NULL").get(seq)
243
+ return r.total ? { done: r.done, total: r.total } : null
244
+ }
245
+ // Levels above a task (0: it has no parent), and levels from it down (1: no subtasks).
246
+ const above = seq => { let n = 0; for (let t = taskRow(seq); t?.parent_seq && n <= MAX.depth; t = taskRow(t.parent_seq)) n++; return n }
247
+ const below = (seq, n = 1) => (n > MAX.depth ? n : Math.max(n, ...childrenOf(seq).map(c => below(c.seq, n + 1))))
248
+ // A parent for a task (seq, or null for a new one), checked: same board, no loop, not too deep.
249
+ function checkParent(board, value, seq) {
250
+ if (value === null || value === '') return null
251
+ const parent = taskRow(seqOf(value))
252
+ if (!parent || parent.board_id !== board.id) throw bad(`no task ${String(value).slice(0, 40)} on this board to be its parent`)
253
+ if (seq != null) for (let t = parent; t; t = t.parent_seq ? taskRow(t.parent_seq) : null) if (t.seq === seq) throw bad('a task can\'t be a subtask of itself or of its own subtasks')
254
+ if (parent.seq !== taskRow(seq ?? -1)?.parent_seq && childrenOf(parent.seq).length >= MAX.subtasks) throw bad(`at most ${MAX.subtasks} subtasks on a task`)
255
+ if (above(parent.seq) + 1 + (seq != null ? below(seq) : 1) > MAX.depth) throw bad(`subtasks go ${MAX.depth} levels deep at most`)
256
+ return parent.seq
257
+ }
258
+
259
+ const taskRow = seq => db.prepare('SELECT * FROM tasks WHERE seq = ? AND deleted_at IS NULL').get(seq) // (not one in the trash)
260
+ const anyTask = seq => db.prepare('SELECT * FROM tasks WHERE seq = ?').get(seq)
261
+ const statusRow = id => db.prepare('SELECT * FROM board_statuses WHERE id = ?').get(id)
262
+ const categoryOf = t => statusRow(t.status_id)?.category ?? 'unstarted'
263
+
264
+ // Tasks given to a session of a team, not yet told to its coordinator, where
265
+ // they wait to be worked on.
266
+ function pendingOf(boardId) {
267
+ return db.prepare(`SELECT t.* FROM tasks t JOIN board_statuses s ON s.id = t.status_id
268
+ WHERE t.board_id = ? AND t.deleted_at IS NULL AND t.notify_state = 'pending' AND t.assignee_kind = 'session' AND s.category IN ('unstarted', 'started', 'review') ORDER BY t.rank, t.seq`).all(boardId)
269
+ }
270
+
271
+ // --- what changed, and who is told --------------------------------------------
272
+ function event(seq, by, what, data = null) {
273
+ db.prepare('INSERT INTO task_events (task_seq, at, who, what, data) VALUES (?, ?, ?, ?, ?)').run(seq, now(), JSON.stringify(by), what, data == null ? null : JSON.stringify(data))
274
+ db.prepare('DELETE FROM task_events WHERE task_seq = ? AND id <= (SELECT id FROM task_events WHERE task_seq = ? ORDER BY id DESC LIMIT 1 OFFSET ?)').run(seq, seq, MAX.events)
275
+ }
276
+ const changedBoard = boardId => broadcast('boards', boardList()) // (counts and what waits to be told)
277
+ // (A parent's progress changes with its subtasks: it is sent too, and the one it had before.)
278
+ const changedTask = (seq, ...more) => {
279
+ const t = taskRow(seq)
280
+ if (!t) return
281
+ for (const s of new Set([seq, t.parent_seq, ...more].filter(Boolean))) { const x = taskRow(s); if (x) broadcast('task', taskView(x)) }
282
+ sync?.touch(t.board_id, seq) // (first: the board sent below counts it as on its way to GitHub)
283
+ changedBoard(t.board_id)
284
+ }
285
+
286
+ // A message from the board to a coordinator: the server's, signed as such,
287
+ // and taken by the plugin as an order (only what a person did sends one).
288
+ function tell(coordinator, text) {
289
+ try {
290
+ messaging.boardNotice(coordinator, text)
291
+ return true
292
+ } catch (err) {
293
+ log(`board notice for ${coordinator} failed: ${err.message}`)
294
+ return false
295
+ }
296
+ }
297
+ const quoted = t => `${taskId(t.seq)} «${t.title}»`
298
+ const forWhom = (t, coordinator) => (t.assignee === coordinator ? 'you' : `your worker ${t.assignee}`)
299
+ const READ_IT = 'Read each with board (action "get") before starting; when you hand one to a worker, tell the worker yourself.'
300
+
301
+ // Told now: the tasks a person gave this team and said to tell it about.
302
+ function notifyTeam(coordinator, tasks, by) {
303
+ const lines = tasks.map(t => { const s = statusRow(t.status_id); const next = s?.next_id ? statusRow(s.next_id)?.name : null; return `- ${quoted(t)} → ${forWhom(t, coordinator)} [${s?.name ?? '?'}${next ? `; when done: «${next}»` : ''}]` })
304
+ const text = `From the task board, the user's order (${by.name}): ${tasks.length === 1 ? 'this task is' : 'these tasks are'} now your team's.\n${lines.join('\n')}\n${READ_IT}`
305
+ if (!tell(coordinator, text)) return false
306
+ for (const t of tasks) {
307
+ db.prepare("UPDATE tasks SET notify_state = 'sent', notified_to = ? WHERE seq = ?").run(coordinator, t.seq)
308
+ event(t.seq, by, 'notified', { to: coordinator })
309
+ }
310
+ return true
311
+ }
312
+
313
+ // Once a team was told, it is told too when that stops being so.
314
+ function correct(before, after, by) {
315
+ const told = before.notify_state === 'sent' ? before.notified_to : null
316
+ if (!told) return
317
+ const sameAssignee = after && after.assignee_kind === before.assignee_kind && after.assignee === before.assignee
318
+ let text = null
319
+ if (!after) text = `From the task board: the user (${by.name}) deleted ${quoted(before)}. Stop working on it and don't hand it out.`
320
+ else if (!sameAssignee) {
321
+ const now = after.assignee_kind === 'session' && teamOf(after.assignee) === told ? `it now goes to ${forWhom(after, told)}, who will be told when the user says so` : 'it is no longer your team\'s'
322
+ text = `From the task board: the user (${by.name}) changed who has ${quoted(before)}: ${now}. Stop working on it until then.`
323
+ } else if (categoryOf(after) === 'closed' && categoryOf(before) !== 'closed') text = `From the task board: the user (${by.name}) cancelled ${quoted(before)}. Stop working on it.`
324
+ if (!text) return
325
+ tell(told, text)
326
+ if (after && !sameAssignee) db.prepare("UPDATE tasks SET notify_state = CASE WHEN assignee_kind = 'session' THEN 'pending' ELSE 'none' END, notified_to = NULL WHERE seq = ?").run(after.seq)
327
+ if (after && sameAssignee) db.prepare("UPDATE tasks SET notify_state = 'pending', notified_to = NULL WHERE seq = ?").run(after.seq)
328
+ }
329
+
330
+ // --- the flow: a column as a step ----------------------------------------------
331
+ // Who a task moved into this column goes to (if they still can have it).
332
+ function handlerOf(s, boardId) {
333
+ if (!s?.handler_kind) return null
334
+ try { return checkAssignee(boardId, { kind: s.handler_kind, id: s.handler }) } catch { return null }
335
+ }
336
+ const nameOf = id => (id ? statusRow(id)?.name ?? null : null)
337
+ // What a step asks, said to whoever does it.
338
+ function stepText(s) {
339
+ const next = nameOf(s.next_id), back = nameOf(s.back_id)
340
+ return [
341
+ s.instructions ? `The step: ${s.instructions}` : '',
342
+ next ? `When done, move it to «${next}»${back ? `; if it isn't acceptable, back to «${back}»` : ''}.` : back ? `If it isn't acceptable, move it back to «${back}».` : '',
343
+ ].filter(Boolean).join(' ')
344
+ }
345
+ // Moved along the flow by an agent: the team that has it now hears at once
346
+ // (the flow is the people's word). Its own coordinator moving it there knows.
347
+ function handOn(t, by) {
348
+ const team = teamOf(t.assignee)
349
+ if (!team) return
350
+ const s = statusRow(t.status_id)
351
+ const sent = () => db.prepare("UPDATE tasks SET notify_state = 'sent', notified_to = ? WHERE seq = ?").run(team, t.seq)
352
+ if (by.kind === 'session' && by.id === team) return sent()
353
+ const text = `From the task board, the user's flow: ${by.name} moved ${quoted(t)} to «${s.name}», a step now for ${forWhom(t, team)}. ${stepText(s)} ${READ_IT}`.replace(/ {2,}/g, ' ')
354
+ if (!tell(team, text)) return
355
+ sent()
356
+ event(t.seq, by, 'notified', { to: team })
357
+ }
358
+
359
+ // --- changing a task ----------------------------------------------------------
360
+ // What can be set on a task, checked against its board.
361
+ function fields(board, p, { creating, seq = null }) {
362
+ const out = {}
363
+ if (creating || p.title !== undefined) {
364
+ out.title = short(p.title, MAX.title, 'title')
365
+ if (!out.title) throw bad('a task needs a title')
366
+ }
367
+ if (p.description !== undefined) out.description = short(p.description, MAX.description, 'description', { lines: true }) || null
368
+ if (p.status !== undefined && p.status !== null) {
369
+ const s = findIn(statusesOf(board.id), p.status, 'status')
370
+ out.status_id = s.id
371
+ } else if (creating) {
372
+ const list = statusesOf(board.id)
373
+ out.status_id = (list.find(s => s.category === 'unstarted') ?? list[0])?.id
374
+ if (!out.status_id) throw bad('this board has no statuses')
375
+ }
376
+ if (p.type !== undefined) out.type_id = p.type === null || p.type === '' ? null : findIn(typesOf(board.id), p.type, 'type').id
377
+ if (p.labels !== undefined) {
378
+ if (!Array.isArray(p.labels)) throw bad('labels must be a list')
379
+ if (p.labels.length > MAX.labelsPerTask) throw bad(`at most ${MAX.labelsPerTask} labels on a task`)
380
+ const all = labelsOf(board.id)
381
+ out.labels = [...new Set(p.labels.map(l => findIn(all, l, 'label').id))]
382
+ }
383
+ if (p.priority !== undefined) {
384
+ const n = Number(p.priority ?? 0)
385
+ if (!Number.isInteger(n) || n < 0 || n > 4) throw bad('priority is 0 (none) to 4 (urgent)')
386
+ out.priority = n
387
+ }
388
+ if (p.due !== undefined) {
389
+ if (p.due === null || p.due === '') out.due = null
390
+ else if (!DUE_RE.test(String(p.due)) || Number.isNaN(Date.parse(String(p.due)))) throw bad('due is a date: YYYY-MM-DD')
391
+ else out.due = String(p.due)
392
+ }
393
+ if (p.parent !== undefined) out.parent_seq = checkParent(board, p.parent, seq)
394
+ if (p.people !== undefined) out.people = checkPeople(p.people)
395
+ if (p.rank !== undefined) {
396
+ const r = Number(p.rank)
397
+ if (!Number.isFinite(r)) throw bad('rank must be a number')
398
+ out.rank = r
399
+ }
400
+ return out
401
+ }
402
+ // By its id, or by its name (any case): what an agent says.
403
+ function findIn(list, value, what) {
404
+ const hit = list.find(x => x.id === Number(value)) ?? list.find(x => x.name.toLowerCase() === String(value).trim().toLowerCase())
405
+ if (!hit) throw bad(`no ${what} "${String(value).slice(0, 40)}" on this board: ${list.map(x => x.name).join(', ') || 'none'}`)
406
+ return hit
407
+ }
408
+
409
+ function setPeople(seq, ids) {
410
+ db.prepare('DELETE FROM task_people WHERE task_seq = ?').run(seq)
411
+ ids.forEach((id, i) => db.prepare('INSERT INTO task_people (task_seq, user_id, position) VALUES (?, ?, ?)').run(seq, id, i))
412
+ }
413
+ function writeTask(seq, f, by) {
414
+ const cols = Object.keys(f).filter(k => k !== 'labels' && k !== 'people')
415
+ if (cols.length) db.prepare(`UPDATE tasks SET ${cols.map(c => `${c} = ?`).join(', ')} WHERE seq = ?`).run(...cols.map(c => f[c]), seq)
416
+ if (f.labels) {
417
+ db.prepare('DELETE FROM task_labels WHERE task_seq = ?').run(seq)
418
+ for (const l of f.labels) db.prepare('INSERT INTO task_labels (task_seq, label_id) VALUES (?, ?)').run(seq, l)
419
+ }
420
+ if (f.people) setPeople(seq, f.people)
421
+ db.prepare('UPDATE tasks SET updated_by = ?, updated_at = ?, version = version + 1 WHERE seq = ?').run(JSON.stringify(by), now(), seq)
422
+ }
423
+
424
+ // What the history says changed (not the description's text: only that it did).
425
+ function changes(before, f) {
426
+ const out = {}
427
+ for (const [k, v] of Object.entries(f)) {
428
+ if (k === 'rank' || k === 'notify_state' || k === 'notified_to') continue
429
+ if (k === 'labels') { const old = db.prepare('SELECT label_id FROM task_labels WHERE task_seq = ? ORDER BY label_id').all(before.seq).map(r => r.label_id); if (old.join() !== [...v].sort((a, b) => a - b).join()) out.labels = v; continue }
430
+ if (k === 'description') { if ((before.description ?? null) !== v) out.description = true; continue }
431
+ if (k === 'people') { if ([...peopleOf(before.seq)].sort().join() !== [...v].sort().join()) out.people = v.map(id => ({ id, name: memberName(id) ?? '?' })); continue }
432
+ if ((before[k] ?? null) !== v) out[k] = v
433
+ }
434
+ return out
435
+ }
436
+
437
+ function createTask(board, p, by, { assignee = null, notifyNow = false, byAgentTeam = null } = {}) {
438
+ if (board.archived_at) throw bad('this board is archived')
439
+ if (liveCount(board.id) >= MAX.tasks) throw bad(`at most ${MAX.tasks} tasks on a board: archive this one and start another`)
440
+ const f = fields(board, p, { creating: true })
441
+ // (Nobody given, in a column someone handles: theirs.)
442
+ let viaFlow = false
443
+ const h = handlerOf(statusRow(f.status_id), board.id)
444
+ if (h?.kind === 'session' && !assignee) { assignee = h; viaFlow = true }
445
+ if (h?.kind === 'user') f.people = withPerson(f.people ?? [], h.id) // (a person's step: one of its people too)
446
+ const rank = f.rank ?? (db.prepare('SELECT MAX(rank) r FROM tasks WHERE board_id = ?').get(board.id).r ?? 0) + 1
447
+ const at = now(), json = JSON.stringify(by)
448
+ // (Given by its own coordinator: that coordinator knows already.)
449
+ const state = assignee?.kind === 'session' ? (byAgentTeam && !viaFlow ? 'sent' : 'pending') : 'none'
450
+ const info = db.prepare(`INSERT INTO tasks (board_id, title, description, status_id, type_id, priority, due, rank, assignee_kind, assignee, notify_state, notified_to, created_by, created_at, updated_by, updated_at, parent_seq)
451
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(board.id, f.title, f.description ?? null, f.status_id, f.type_id ?? null, f.priority ?? 0, f.due ?? null, rank,
452
+ assignee?.kind ?? null, assignee?.id ?? null, state, state === 'sent' ? byAgentTeam : null, json, at, json, at, f.parent_seq ?? null)
453
+ const seq = Number(info.lastInsertRowid)
454
+ for (const l of f.labels ?? []) db.prepare('INSERT INTO task_labels (task_seq, label_id) VALUES (?, ?)').run(seq, l)
455
+ if (f.people?.length) setPeople(seq, f.people)
456
+ const said = { ...(assignee ? { assignee } : {}), ...(f.people?.length ? { people: f.people.map(id => ({ id, name: memberName(id) ?? '?' })) } : {}), ...(f.parent_seq ? { parent: taskId(f.parent_seq) } : {}) }
457
+ event(seq, by, 'created', Object.keys(said).length ? said : null)
458
+ if (viaFlow && by.kind === 'session' && assignee.kind === 'session') handOn(taskRow(seq), by)
459
+ if (notifyNow) notifyIfDue(seq, by)
460
+ return seq
461
+ }
462
+
463
+ // A person said to tell the team now: if it is in a column where work waits.
464
+ function notifyIfDue(seq, by) {
465
+ const t = taskRow(seq)
466
+ if (t?.notify_state !== 'pending' || t.assignee_kind !== 'session' || !ACTIVE.has(categoryOf(t))) return false
467
+ const team = teamOf(t.assignee)
468
+ return team ? notifyTeam(team, [t], by) : false
469
+ }
470
+
471
+ function updateTask(seq, p, by, { assignee, human }) {
472
+ const before = taskRow(seq)
473
+ const board = boardRow(before.board_id)
474
+ if (board.archived_at) throw bad('this board is archived')
475
+ const f = fields(board, p, { creating: false, seq })
476
+ const sameAs = a => (a?.kind ?? null) === (before.assignee_kind ?? null) && (a?.id ?? null) === (before.assignee ?? null)
477
+ // Moved into a column someone handles, with nobody else said: theirs now.
478
+ let viaFlow = false
479
+ if (f.status_id !== undefined && f.status_id !== before.status_id) {
480
+ const h = handlerOf(statusRow(f.status_id), board.id)
481
+ if (h?.kind === 'session' && (assignee === undefined || sameAs(assignee)) && !sameAs(h)) { assignee = h; viaFlow = true }
482
+ if (h?.kind === 'user') f.people = withPerson(f.people ?? peopleOf(seq), h.id) // (a person's step: one of its people too)
483
+ }
484
+ if (assignee !== undefined && !sameAs(assignee)) {
485
+ f.assignee_kind = assignee?.kind ?? null
486
+ f.assignee = assignee?.id ?? null
487
+ // (Given by an agent to its own team: it knows. Along the flow: told below.
488
+ // By a person: pending until they say.)
489
+ f.notify_state = assignee?.kind === 'session' ? (human || viaFlow ? 'pending' : 'sent') : 'none'
490
+ f.notified_to = !human && !viaFlow && assignee?.kind === 'session' ? teamOf(assignee.id) : null
491
+ }
492
+ const diff = changes(before, f)
493
+ // (Who has it, said once: as the history reads it.)
494
+ if ('assignee' in diff || 'assignee_kind' in diff) { delete diff.assignee_kind; diff.assignee = assignee ?? null }
495
+ if ('parent_seq' in diff) { diff.parent = diff.parent_seq ? taskId(diff.parent_seq) : null; delete diff.parent_seq }
496
+ if (!Object.keys(diff).length && (f.rank === undefined || f.rank === before.rank)) return false
497
+ writeTask(seq, f, by)
498
+ if (Object.keys(diff).length) event(seq, by, 'changed', diff)
499
+ if (human) correct(before, taskRow(seq), by)
500
+ else if (viaFlow && assignee?.kind === 'session') handOn(taskRow(seq), by)
501
+ return viaFlow ? 'flow' : true
502
+ }
503
+
504
+ function commentOn(seq, text, by) {
505
+ const body = short(text, MAX.comment, 'comment', { lines: true })
506
+ if (!body) throw bad('the comment is empty')
507
+ if (db.prepare('SELECT COUNT(*) n FROM task_comments WHERE task_seq = ? AND deleted_at IS NULL').get(seq).n >= MAX.comments) throw bad(`at most ${MAX.comments} comments on a task`)
508
+ const id = Number(db.prepare('INSERT INTO task_comments (task_seq, author, text, created_at) VALUES (?, ?, ?, ?)').run(seq, JSON.stringify(by), body, now()).lastInsertRowid)
509
+ db.prepare('UPDATE tasks SET updated_at = ? WHERE seq = ?').run(now(), seq)
510
+ return { id, body }
511
+ }
512
+
513
+ // --- people (the dashboard) ---------------------------------------------------
514
+ function boardConfig(boardId, p, { creating }) {
515
+ const out = {}
516
+ if (creating || p.name !== undefined) {
517
+ out.name = short(p.name, MAX.name, 'name')
518
+ if (!out.name) throw bad('a board needs a name')
519
+ }
520
+ if (p.description !== undefined) out.description = short(p.description, MAX.boardDescription, 'description', { lines: true }) || null
521
+ if (p.teams !== undefined) {
522
+ if (!Array.isArray(p.teams) || p.teams.length > MAX.teams) throw bad(`teams must be a list of coordinators (at most ${MAX.teams})`)
523
+ out.teams = [...new Set(p.teams.map(String))]
524
+ for (const c of out.teams) if (!NAME_RE.test(c) || teamOf(c) !== c) throw bad(`"${c.slice(0, 40)}" is not the coordinator of a team`)
525
+ }
526
+ const listOf = (key, max, withCategory) => {
527
+ if (p[key] === undefined) return
528
+ if (!Array.isArray(p[key]) || !p[key].length && withCategory) throw bad(`${key} must be a list${withCategory ? ', with at least one' : ''}`)
529
+ if (p[key].length > max) throw bad(`at most ${max} ${key}`)
530
+ const names = new Set()
531
+ out[key] = p[key].map((x, i) => {
532
+ const name = short(x?.name, MAX.name, `${key} ${i + 1}'s name`)
533
+ if (!name) throw bad(`${key} ${i + 1} needs a name`)
534
+ if (names.has(name.toLowerCase())) throw bad(`two ${key} are called "${name}"`)
535
+ names.add(name.toLowerCase())
536
+ const id = x.id == null ? null : Number(x.id)
537
+ if (withCategory) {
538
+ if (!CATEGORIES.includes(x.category)) throw bad(`${key} ${i + 1}'s category must be one of: ${CATEGORIES.join(', ')}`)
539
+ return { id, name, category: x.category }
540
+ }
541
+ return { id, name, color: COLORS.includes(x.color) ? x.color : 'gray' }
542
+ })
543
+ }
544
+ listOf('statuses', MAX.statuses, true)
545
+ listOf('labels', MAX.labels, false)
546
+ listOf('types', MAX.types, false)
547
+ for (const [key, table] of [['statuses', 'board_statuses'], ['labels', 'board_labels'], ['types', 'board_types']]) if (out[key]) checkList(boardId, table, out[key])
548
+ return out
549
+ }
550
+
551
+ // A list of statuses, labels or types as it is now: ids kept, new ones added,
552
+ // the ones left out deleted (a status only once no task is in it).
553
+ // (Checked before anything is written: a list refused changes nothing.)
554
+ function checkList(boardId, table, list) {
555
+ const old = boardId == null ? [] : db.prepare(`SELECT * FROM ${table} WHERE board_id = ?`).all(boardId)
556
+ const kept = new Set(list.filter(x => x.id != null).map(x => x.id))
557
+ for (const x of list) if (x.id != null && !old.some(o => o.id === x.id)) throw bad(`there is no ${table.replace('board_', '').slice(0, -1)} ${x.id} on this board`)
558
+ if (table !== 'board_statuses') return
559
+ for (const o of old.filter(o => !kept.has(o.id))) {
560
+ const n = db.prepare('SELECT COUNT(*) n FROM tasks WHERE status_id = ? AND deleted_at IS NULL').get(o.id).n // (one in the trash goes back to another column)
561
+ if (n) throw bad(`the status "${o.name}" has ${n} task${n === 1 ? '' : 's'}: move ${n === 1 ? 'it' : 'them'} first`)
562
+ }
563
+ }
564
+ function saveList(boardId, table, list, withCategory) {
565
+ const old = db.prepare(`SELECT * FROM ${table} WHERE board_id = ?`).all(boardId)
566
+ const kept = new Set(list.filter(x => x.id != null).map(x => x.id))
567
+ for (const o of old.filter(o => !kept.has(o.id))) {
568
+ if (table === 'board_types') db.prepare('UPDATE tasks SET type_id = NULL WHERE type_id = ?').run(o.id)
569
+ if (table === 'board_statuses') for (const c of ['next_id', 'back_id']) db.prepare(`UPDATE board_statuses SET ${c} = NULL WHERE ${c} = ?`).run(o.id)
570
+ db.prepare(`DELETE FROM ${table} WHERE id = ?`).run(o.id)
571
+ }
572
+ list.forEach((x, i) => {
573
+ const extra = withCategory ? x.category : x.color
574
+ const col = withCategory ? 'category' : 'color'
575
+ if (x.id == null) db.prepare(`INSERT INTO ${table} (board_id, name, ${col}, position) VALUES (?, ?, ?, ?)`).run(boardId, x.name, extra, i)
576
+ else db.prepare(`UPDATE ${table} SET name = ?, ${col} = ?, position = ? WHERE id = ?`).run(x.name, extra, i, x.id)
577
+ })
578
+ }
579
+
580
+ function saveTeams(boardId, teams) {
581
+ const before = teamsOf(boardId)
582
+ // (A team no longer on the board: its tasks there stay, but nobody of it has them.)
583
+ for (const gone of before.filter(c => !teams.includes(c))) {
584
+ for (const t of db.prepare("SELECT * FROM tasks WHERE board_id = ? AND deleted_at IS NULL AND assignee_kind = 'session'").all(boardId)) {
585
+ if (teamOf(t.assignee) === gone) {
586
+ const by = { kind: 'user', id: 'server', name: 'board settings' }
587
+ updateTask(t.seq, {}, by, { assignee: null, human: true })
588
+ }
589
+ }
590
+ }
591
+ // (Nor does any session of it handle a step there.)
592
+ for (const r of db.prepare("SELECT id, handler FROM board_statuses WHERE board_id = ? AND handler_kind = 'session'").all(boardId)) {
593
+ if (!teams.includes(teamOf(r.handler))) db.prepare('UPDATE board_statuses SET handler_kind = NULL, handler = NULL WHERE id = ?').run(r.id)
594
+ }
595
+ db.prepare('DELETE FROM board_teams WHERE board_id = ?').run(boardId)
596
+ for (const c of teams) db.prepare('INSERT INTO board_teams (board_id, coordinator) VALUES (?, ?)').run(boardId, c)
597
+ }
598
+
599
+ const humanBoard = id => {
600
+ const b = boardRow(id)
601
+ if (!b) throw new ApiError(404, 'Not Found: no such board')
602
+ return b
603
+ }
604
+ const humanTask = id => {
605
+ const t = taskRow(seqOf(id))
606
+ if (!t) throw new ApiError(404, `Not Found: no task ${String(id).slice(0, 40)}`)
607
+ return t
608
+ }
609
+ const versionCheck = (t, p) => {
610
+ if (p.version != null && Number(p.version) !== t.version) {
611
+ throw new ApiError(409, `Conflict: ${taskId(t.seq)} changed meanwhile`, { parameters: { reason: 'changed', task: taskView(t, { full: true }) } })
612
+ }
613
+ }
614
+ // --- the trash -------------------------------------------------------------------
615
+ const liveCount = boardId => db.prepare('SELECT COUNT(*) n FROM tasks WHERE board_id = ? AND deleted_at IS NULL').get(boardId).n
616
+ // Its subtasks, all levels down, parents first.
617
+ function subtasksOf(seq) {
618
+ const out = []
619
+ for (let level = childrenOf(seq), n = 0; level.length && n < MAX.depth; n++) { out.push(...level); level = level.flatMap(c => childrenOf(c.seq)) }
620
+ return out
621
+ }
622
+ // The subtasks in the trash that were deleted with it, all levels down, parents first.
623
+ function trashedWith(t) {
624
+ const out = []
625
+ const under = seq => db.prepare('SELECT * FROM tasks WHERE parent_seq = ? AND deleted_at IS NOT NULL AND trash_batch = ? ORDER BY rank, seq').all(seq, t.trash_batch)
626
+ for (let level = under(t.seq), n = 0; level.length && n < MAX.depth; n++) { out.push(...level); level = level.flatMap(c => under(c.seq)) }
627
+ return out
628
+ }
629
+ // (github: removed from the project there; nothing to do there about it.)
630
+ function trashTasks(t, { subtasks = false, by, data = null, github = false }) {
631
+ const gone = [t, ...(subtasks ? subtasksOf(t.seq) : [])]
632
+ const loose = subtasks ? [] : childrenOf(t.seq).map(c => c.seq)
633
+ const at = now()
634
+ inTx(() => {
635
+ for (const x of gone) {
636
+ correct(x, null, by)
637
+ if (!github) sync.taskDeleted(x)
638
+ db.prepare('UPDATE tasks SET deleted_at = ?, deleted_by = ?, trash_batch = ?, version = version + 1 WHERE seq = ?').run(at, JSON.stringify(by), t.seq, x.seq)
639
+ event(x.seq, by, 'deleted', x.seq === t.seq ? data : { with: taskId(t.seq) })
640
+ }
641
+ // (Its subtasks left on the board stay, with no parent: as GitHub does.)
642
+ for (const c of loose) { db.prepare('UPDATE tasks SET parent_seq = NULL, version = version + 1 WHERE seq = ?').run(c); event(c, by, 'changed', { parent: null }) }
643
+ })
644
+ for (const x of gone) broadcast('task', { id: taskId(x.seq), seq: x.seq, board: x.board_id, deleted: true })
645
+ for (const c of loose) changedTask(c)
646
+ if (t.parent_seq) changedTask(t.parent_seq)
647
+ changedBoard()
648
+ return gone.map(x => x.seq)
649
+ }
650
+ function restoreTasks(t, { subtasks = false, by, github = false }) {
651
+ const b = humanBoard(t.board_id)
652
+ if (b.archived_at) throw bad('this board is archived')
653
+ const back = [t, ...(subtasks ? trashedWith(t) : [])]
654
+ if (liveCount(b.id) + back.length > MAX.tasks) throw bad(`at most ${MAX.tasks} tasks on a board`)
655
+ const statuses = statusesOf(b.id)
656
+ const home = statuses.find(s => ACTIVE.has(s.category))?.id ?? statuses[0]?.id
657
+ let withoutParent = null
658
+ inTx(() => {
659
+ for (const x of back) {
660
+ let parent = x.parent_seq
661
+ if (x.seq === t.seq && parent) {
662
+ // (Its parent on the board, and room under it: back under it. Otherwise with no parent.)
663
+ let ok = !!taskRow(parent)
664
+ if (ok) { try { checkParent(b, parent, null) } catch { ok = false } }
665
+ if (!ok) { withoutParent = taskId(parent); parent = null }
666
+ }
667
+ // (Its column gone: the first where work waits. Who had it can't any more: nobody.)
668
+ const status = statuses.some(s => s.id === x.status_id) ? x.status_id : home
669
+ let assignee = x.assignee_kind ? { kind: x.assignee_kind, id: x.assignee } : null
670
+ if (assignee) { try { assignee = checkAssignee(b.id, assignee) } catch { assignee = null } }
671
+ db.prepare(`UPDATE tasks SET deleted_at = NULL, deleted_by = NULL, trash_batch = NULL, parent_seq = ?, status_id = ?, assignee_kind = ?, assignee = ?,
672
+ notify_state = ?, notified_to = NULL, version = version + 1, updated_by = ?, updated_at = ? WHERE seq = ?`)
673
+ .run(parent ?? null, status, assignee?.kind ?? null, assignee?.id ?? null, assignee?.kind === 'session' ? 'pending' : 'none', JSON.stringify(by), now(), x.seq)
674
+ event(x.seq, by, 'restored', x.seq === t.seq ? (withoutParent ? { without_parent: withoutParent } : null) : { with: taskId(t.seq) })
675
+ if (!github) sync.taskRestored(x.seq)
676
+ }
677
+ })
678
+ for (const x of back) changedTask(x.seq)
679
+ changedBoard()
680
+ return { restored: back.map(x => taskId(x.seq)), without_parent: withoutParent }
681
+ }
682
+
683
+
684
+ const boardReads = {
685
+ boards: () => ({ prefix: prefix(), boards: boardList(), members: memberList().map(m => ({ id: m.id, name: m.name, github: m.github ?? null })), sessions: Object.fromEntries(db.prepare('SELECT id FROM boards').all().map(b => [b.id, assignableSessions(b.id)])) }),
686
+ tasks(q) {
687
+ const b = humanBoard(q.get('board'))
688
+ return db.prepare('SELECT * FROM tasks WHERE board_id = ? AND deleted_at IS NULL ORDER BY rank, seq').all(b.id).map(t => taskView(t))
689
+ },
690
+ // The board's trash: the latest deleted first, each with its parent (on the board or in the trash too) and the subtasks deleted with it.
691
+ trash(q) {
692
+ const b = humanBoard(q.get('board'))
693
+ return db.prepare('SELECT * FROM tasks WHERE board_id = ? AND deleted_at IS NOT NULL ORDER BY deleted_at DESC, seq LIMIT 500').all(b.id).map(t => {
694
+ const parent = t.parent_seq ? anyTask(t.parent_seq) : null
695
+ return {
696
+ id: taskId(t.seq), seq: t.seq, title: t.title, deleted_at: t.deleted_at, deleted_by: who(t.deleted_by),
697
+ parent: parent ? { id: taskId(parent.seq), seq: parent.seq, title: parent.title, trashed: !!parent.deleted_at } : null,
698
+ subtasks: trashedWith(t).length,
699
+ }
700
+ })
701
+ },
702
+ task: q => taskView(humanTask(q.get('id')), { full: true }),
703
+ }
704
+
705
+ const boardActions = {
706
+ 'boards/create'(p, actor) {
707
+ if (db.prepare('SELECT COUNT(*) n FROM boards').get().n >= MAX.boards) throw bad(`at most ${MAX.boards} boards`)
708
+ const c = boardConfig(null, { statuses: DEFAULT_STATUSES.map(([name, category]) => ({ name, category })), types: DEFAULT_TYPES.map(([name, color]) => ({ name, color })), ...p }, { creating: true })
709
+ const id = inTx(() => {
710
+ const at = now()
711
+ const id = Number(db.prepare('INSERT INTO boards (name, description, created_by, created_at, updated_at) VALUES (?, ?, ?, ?, ?)').run(c.name, c.description ?? null, JSON.stringify(person(actor)), at, at).lastInsertRowid)
712
+ saveList(id, 'board_statuses', c.statuses, true)
713
+ saveList(id, 'board_types', c.types, false)
714
+ if (c.labels) saveList(id, 'board_labels', c.labels, false)
715
+ if (c.teams) saveTeams(id, c.teams)
716
+ return id
717
+ })
718
+ changedBoard()
719
+ return boardView(boardRow(id))
720
+ },
721
+ 'boards/update'(p) {
722
+ const b = humanBoard(p.id)
723
+ const c = boardConfig(b.id, p, { creating: false })
724
+ inTx(() => {
725
+ if (c.name !== undefined || c.description !== undefined) db.prepare('UPDATE boards SET name = COALESCE(?, name), description = CASE WHEN ? THEN ? ELSE description END WHERE id = ?').run(c.name ?? null, c.description !== undefined ? 1 : 0, c.description ?? null, b.id)
726
+ if (c.statuses) {
727
+ const was = statusesOf(b.id).map(s => `${s.id}:${s.name}`).join()
728
+ saveList(b.id, 'board_statuses', c.statuses, true)
729
+ if (statusesOf(b.id).map(s => `${s.id}:${s.name}`).join() !== was) sync.columnsChanged(b.id)
730
+ }
731
+ if (c.labels) saveList(b.id, 'board_labels', c.labels, false)
732
+ if (c.types) saveList(b.id, 'board_types', c.types, false)
733
+ if (c.teams) saveTeams(b.id, c.teams)
734
+ if (p.archived !== undefined) db.prepare('UPDATE boards SET archived_at = ? WHERE id = ?').run(p.archived ? now() : null, b.id)
735
+ db.prepare('UPDATE boards SET updated_at = ? WHERE id = ?').run(now(), b.id)
736
+ })
737
+ sync.touch(b.id)
738
+ changedBoard()
739
+ return boardView(boardRow(b.id))
740
+ },
741
+ // Kept in step with a GitHub project: its address, a repository for new issues, a token.
742
+ async 'boards/github'(p, actor) {
743
+ const b = humanBoard(p.board)
744
+ if (b.archived_at) throw bad('this board is archived')
745
+ return sync.connect(b, p, person(actor))
746
+ },
747
+ // Whether a merged pull request takes its tasks to done.
748
+ 'boards/github-merge'(p) {
749
+ const b = humanBoard(p.board)
750
+ if (!sync.view(b.id)) throw bad('this board is not connected to GitHub')
751
+ sync.setMergeMoves(b.id, !!p.on)
752
+ return boardView(boardRow(b.id))
753
+ },
754
+ 'boards/github-off'(p) {
755
+ const b = humanBoard(p.board)
756
+ sync.disconnect(b.id)
757
+ return boardView(boardRow(b.id))
758
+ },
759
+ // Someone has the board open (and maybe a task): GitHub is read if it isn't fresh.
760
+ async 'boards/github-watch'(p) {
761
+ const b = humanBoard(p.board)
762
+ await sync.watch(b.id, { task: p.task == null ? null : Number(p.task), opened: p.opened === true, taskOpened: p.taskOpened === true, force: p.force === true })
763
+ return true
764
+ },
765
+ async 'boards/github-sync'(p) {
766
+ const b = humanBoard(p.board)
767
+ if (!sync.view(b.id)) throw bad('this board is not connected to GitHub')
768
+ await sync.syncBoard(b.id)
769
+ return boardView(boardRow(b.id))
770
+ },
771
+ 'boards/delete'(p) {
772
+ const b = humanBoard(p.id)
773
+ if (!b.archived_at) throw bad('archive the board first: deleting it deletes its tasks')
774
+ db.prepare('DELETE FROM boards WHERE id = ?').run(b.id)
775
+ broadcast('board-deleted', { id: b.id })
776
+ changedBoard()
777
+ return { id: b.id, deleted: true }
778
+ },
779
+ // One column's step: who handles it, what to do there, where it goes next.
780
+ 'boards/flow'(p) {
781
+ const b = humanBoard(p.board)
782
+ const s = statusesOf(b.id).find(x => x.id === Number(p.status))
783
+ if (!s) throw bad('no such status on this board')
784
+ const handler = p.handler == null || p.handler === '' ? null : checkAssignee(b.id, p.handler)
785
+ const instructions = short(p.instructions ?? '', MAX.instructions, 'instructions', { lines: true }) || null
786
+ const ref = (v, what) => {
787
+ if (v == null || v === '') return null
788
+ const to = findIn(statusesOf(b.id), v, 'status')
789
+ if (to.id === s.id) throw bad(`${what} is another status, not this one`)
790
+ return to.id
791
+ }
792
+ const next = ref(p.next, 'where it goes when done'), back = ref(p.back, 'where it goes back')
793
+ db.prepare('UPDATE board_statuses SET handler_kind = ?, handler = ?, instructions = ?, next_id = ?, back_id = ? WHERE id = ?').run(handler?.kind ?? null, handler?.id ?? null, instructions, next, back, s.id)
794
+ db.prepare('UPDATE boards SET updated_at = ? WHERE id = ?').run(now(), b.id)
795
+ changedBoard()
796
+ return boardView(boardRow(b.id))
797
+ },
798
+ 'boards/prefix'(p) {
799
+ const v = String(p.prefix ?? '').trim().toUpperCase()
800
+ if (!PREFIX_RE.test(v)) throw bad('the prefix is 1 to 6 letters or digits, starting with a letter (such as SQ)')
801
+ db.prepare("INSERT INTO board_settings (k, v) VALUES ('prefix', ?) ON CONFLICT(k) DO UPDATE SET v = excluded.v").run(v)
802
+ changedBoard()
803
+ return { prefix: v }
804
+ },
805
+ 'tasks/create'(p, actor) {
806
+ const b = humanBoard(p.board)
807
+ const by = person(actor)
808
+ const seq = inTx(() => createTask(b, p, by, { assignee: agentParam(b, p) ?? null, notifyNow: p.notify === true }))
809
+ changedTask(seq)
810
+ return taskView(taskRow(seq), { full: true })
811
+ },
812
+ 'tasks/update'(p, actor) {
813
+ const t = humanTask(p.id)
814
+ versionCheck(t, p)
815
+ const by = person(actor)
816
+ const assignee = agentParam(boardRow(t.board_id), p)
817
+ inTx(() => {
818
+ updateTask(t.seq, p, by, { assignee, human: true })
819
+ if (p.notify === true) notifyIfDue(t.seq, by)
820
+ })
821
+ changedTask(t.seq, t.parent_seq)
822
+ return taskView(taskRow(t.seq), { full: true })
823
+ },
824
+ // Into the trash, with its subtasks if asked; if not, they stay on the board with no parent.
825
+ 'tasks/delete'(p, actor) {
826
+ const t = humanTask(p.id)
827
+ const gone = trashTasks(t, { subtasks: p.subtasks === true, by: person(actor) })
828
+ return { id: taskId(t.seq), deleted: true, trashed: gone.map(taskId) }
829
+ },
830
+ // Out of the trash, with the subtasks deleted with it if asked. Its parent
831
+ // still in the trash (or gone): restored with no parent, and said so.
832
+ 'tasks/restore'(p, actor) {
833
+ const t = anyTask(seqOf(p.id))
834
+ if (!t?.deleted_at) throw new ApiError(404, `Not Found: no task ${String(p.id).slice(0, 40)} in the trash`)
835
+ return restoreTasks(t, { subtasks: p.subtasks === true, by: person(actor) })
836
+ },
837
+ 'tasks/comment'(p, actor) {
838
+ const t = humanTask(p.id)
839
+ const by = person(actor)
840
+ const c = inTx(() => commentOn(t.seq, p.text, by))
841
+ // Said to the coordinator too, if asked: the user's word on that task.
842
+ let notified = null
843
+ if (p.notify === true && t.assignee_kind === 'session') {
844
+ const team = teamOf(t.assignee)
845
+ if (team && tell(team, `From the task board, the user's order (${by.name}) on ${quoted(t)}, which ${forWhom(t, team)} ${t.assignee === team ? 'have' : 'has'}: ${c.body}`)) {
846
+ notified = team
847
+ db.prepare('UPDATE task_comments SET notified = ? WHERE id = ?').run(team, c.id)
848
+ }
849
+ }
850
+ changedTask(t.seq)
851
+ return { id: c.id, notified }
852
+ },
853
+ // Every task waiting to be told, each team in one message.
854
+ 'tasks/notify'(p, actor) {
855
+ const b = humanBoard(p.board)
856
+ const by = person(actor)
857
+ const wanted = Array.isArray(p.ids) ? new Set(p.ids.map(seqOf)) : null
858
+ const byTeam = new Map()
859
+ for (const t of pendingOf(b.id)) {
860
+ if (wanted && !wanted.has(t.seq)) continue
861
+ const team = teamOf(t.assignee)
862
+ if (!team || !teamsOf(b.id).includes(team)) continue
863
+ if (!byTeam.has(team)) byTeam.set(team, [])
864
+ byTeam.get(team).push(t)
865
+ }
866
+ const told = [], failed = []
867
+ for (const [team, list] of byTeam) (inTx(() => notifyTeam(team, list, by)) ? told : failed).push({ team, tasks: list.map(t => taskId(t.seq)) })
868
+ for (const list of byTeam.values()) for (const t of list) broadcast('task', taskView(taskRow(t.seq)))
869
+ changedBoard()
870
+ return { told, failed }
871
+ },
872
+ }
873
+
874
+ // --- agents (the plugin's board tool) -------------------------------------------
875
+ // A coordinator acts for its team; a worker for itself. (An unapproved
876
+ // coordinator, or a session in no team, sees no board.)
877
+ function agentOf(name) {
878
+ const r = db.prepare('SELECT role, coordinator, needs_approval FROM identities WHERE name = ?').get(name)
879
+ if (r?.role === 'coordinator' && !r.needs_approval) return { name, role: 'coordinator', team: name }
880
+ if (r?.role === 'worker' && r.coordinator) return { name, role: 'worker', team: r.coordinator }
881
+ throw new ApiError(403, r?.role === 'coordinator' ? 'Forbidden: an approved coordinator sees its team\'s boards: the user must approve this session first' : 'Forbidden: only the sessions of a team see its boards')
882
+ }
883
+ const agentBoards = me => db.prepare('SELECT b.* FROM boards b JOIN board_teams t ON t.board_id = b.id WHERE t.coordinator = ? AND b.archived_at IS NULL ORDER BY b.name COLLATE NOCASE, b.id').all(me.team)
884
+ const mine = (me, t) => t.assignee_kind === 'session' && t.assignee === me.name
885
+ // A coordinator changes what is its team's or nobody's.
886
+ const ours = (me, t) => !t.assignee_kind || (t.assignee_kind === 'session' && teamOf(t.assignee) === me.team)
887
+ const notFound = id => new ApiError(404, `Not Found: no task ${String(id ?? '').slice(0, 40)} on your boards`)
888
+ function agentTask(me, id) {
889
+ const t = taskRow(seqOf(id))
890
+ if (!t || !teamsOf(t.board_id).includes(me.team) || boardRow(t.board_id).archived_at) throw notFound(id)
891
+ if (me.role === 'worker' && !mine(me, t)) throw notFound(id)
892
+ return t
893
+ }
894
+ function agentBoard(me, id) {
895
+ const list = agentBoards(me)
896
+ if (id == null || id === '') {
897
+ if (list.length === 1) return list[0]
898
+ throw bad(list.length ? `say which board: ${list.map(b => `${b.id} (${b.name})`).join(', ')}` : 'your team sees no board')
899
+ }
900
+ const hit = list.find(b => b.id === Number(id)) ?? list.find(b => b.name.toLowerCase() === String(id).trim().toLowerCase())
901
+ if (!hit) throw bad(`your team sees no board "${String(id).slice(0, 40)}"${list.length ? `: ${list.map(b => `${b.id} (${b.name})`).join(', ')}` : ''}`)
902
+ return hit
903
+ }
904
+ function agentAssignee(me, board, value) {
905
+ if (value === undefined) return undefined
906
+ if (value === null || value === '') return null
907
+ const a = checkAssignee(board.id, { kind: 'session', id: String(value) })
908
+ if (teamOf(a.id) !== me.team) throw bad(`"${a.id}" is not in your team: you give tasks to yourself or your workers. If a person must do it, ask_user`)
909
+ return a
910
+ }
911
+
912
+ // How an agent reads a task: names, not ids.
913
+ function agentView(t, { full = false } = {}) {
914
+ const v = taskView(t, { full })
915
+ const status = statusRow(t.status_id)
916
+ const typeName = t.type_id ? typesOf(t.board_id).find(x => x.id === t.type_id)?.name ?? null : null
917
+ const labels = labelsOf(t.board_id).filter(l => v.labels.includes(l.id)).map(l => l.name)
918
+ const out = {
919
+ id: v.id, title: v.title, status: status?.name ?? null, category: status?.category ?? null, type: typeName, labels,
920
+ priority: v.priority || undefined, due: v.due ?? undefined,
921
+ assignee: v.assignee ? (v.assignee.kind === 'user' ? `${v.assignee.name} (a person)` : v.assignee.id) : null,
922
+ people: v.people.length ? v.people.map(x => x.name).join(', ') : undefined,
923
+ board: boardRow(t.board_id)?.name,
924
+ when_done: nameOf(status?.next_id) ?? undefined,
925
+ parent: t.parent_seq ? quoted(taskRow(t.parent_seq)) : undefined,
926
+ subtasks: v.subtasks ? `${v.subtasks.done} of ${v.subtasks.total} finished` : undefined,
927
+ pull_requests: v.prs.length ? v.prs.map(p => `#${p.number} «${p.title}»: ${p.state}${p.review ? ` (review: ${p.review})` : ''}`) : undefined,
928
+ }
929
+ if (!full) return out
930
+ const handler = status && handlerOf(status, t.board_id)
931
+ if (status && (handler || status.instructions || status.next_id || status.back_id)) {
932
+ out.step = {
933
+ handled_by: handler ? (handler.kind === 'user' ? `${handler.name} (a person)` : handler.id) : undefined,
934
+ instructions: status.instructions || undefined, when_done: nameOf(status.next_id) ?? undefined, if_rejected: nameOf(status.back_id) ?? undefined,
935
+ }
936
+ }
937
+ if (v.children.length) out.subtasks = v.children.map(c => `${c.id} «${c.title}»: ${statusRow(c.status)?.name ?? '?'}${c.assignee ? `, ${c.assignee.kind === 'user' ? `${c.assignee.name} (a person)` : c.assignee.id}` : ''}${c.people.length ? `, people: ${c.people.map(x => x.name).join(', ')}` : ''}`)
938
+ return {
939
+ ...out, description: v.description || undefined,
940
+ comments: v.comments.map(c => `${c.author?.name ?? '?'}${c.author?.kind === 'user' ? ' (a person)' : ''}, ${new Date(c.created_at).toISOString().slice(0, 16).replace('T', ' ')}: ${c.text}`),
941
+ }
942
+ }
943
+ function boardForAgent(b) {
944
+ return {
945
+ id: b.id, name: b.name, description: b.description || undefined,
946
+ statuses: statusesOf(b.id).map(s => `${s.name} (${s.category})${s.handler ? `, handled by ${s.handler.kind === 'user' ? `${s.handler.name} (a person)` : s.handler.id}` : ''}${s.next ? `, then «${nameOf(s.next)}»` : ''}`), labels: labelsOf(b.id).map(l => l.name), types: typesOf(b.id).map(t => t.name),
947
+ }
948
+ }
949
+
950
+ // What an agent hears after the flow gave its task on: who has it, and who
951
+ // tells them (its coordinator was told; a coordinator tells its own worker).
952
+ function handedOn(me, t) {
953
+ const s = statusRow(t.status_id)
954
+ const step = stepText(s)
955
+ if (t.assignee_kind === 'user') return `The board's flow gave it to ${memberName(t.assignee) ?? 'a person'} (a person), at the step «${s.name}».`
956
+ const team = teamOf(t.assignee)
957
+ if (t.assignee === me.name) return `The board's flow gave it to you, at the step «${s.name}». ${step}`.trim()
958
+ if (me.role === 'coordinator' && team === me.team) return `The board's flow gave it to your worker ${t.assignee}, at the step «${s.name}»: tell ${t.assignee} yourself now, with the task id and the step. ${step}`.trim()
959
+ return `The board's flow gave it to ${t.assignee}, at the step «${s.name}»; the board told ${team === me.team ? 'your coordinator' : `its coordinator (${team})`}. It is not yours any more.`
960
+ }
961
+
962
+ function agentChange(name) {
963
+ rateLimit(name)
964
+ if (!allow('board', name, AGENT_CHANGES_PER_HOUR, 3600_000)) throw new ApiError(429, `Too Many Requests: at most ${AGENT_CHANGES_PER_HOUR} board changes an hour`)
965
+ }
966
+
967
+ const boardMethods = {
968
+ async board(name, p) {
969
+ const me = agentOf(name)
970
+ const action = String(p.action ?? '')
971
+ const by = agent(name)
972
+ switch (action) {
973
+ case 'boards':
974
+ rateLimit(name)
975
+ return agentBoards(me).map(boardForAgent)
976
+ case 'list': {
977
+ rateLimit(name)
978
+ const boards = p.board == null || p.board === '' ? agentBoards(me) : [agentBoard(me, p.board)]
979
+ await Promise.all(boards.map(b => sync.fresh(b.id))) // (GitHub's changes first, if it wasn't read lately)
980
+ const text = p.text == null ? '' : String(p.text).toLowerCase().slice(0, 100)
981
+ const parentWanted = p.parent == null || p.parent === '' ? null : seqOf(p.parent)
982
+ const out = []
983
+ for (const b of boards) {
984
+ const statuses = statusesOf(b.id)
985
+ const want = p.status == null || p.status === '' ? null : findIn(statuses, p.status, 'status').id
986
+ // (Done and cancelled ones only when asked for.)
987
+ const shown = new Set(statuses.filter(s => want ? s.id === want : !['done', 'closed'].includes(s.category)).map(s => s.id))
988
+ for (const t of db.prepare('SELECT * FROM tasks WHERE board_id = ? AND deleted_at IS NULL ORDER BY rank, seq').all(b.id)) {
989
+ if (!shown.has(t.status_id) && (parentWanted == null || want != null)) continue
990
+ if (me.role === 'worker' || p.mine === true ? !mine(me, t) : false) continue
991
+ if (p.assignee != null && p.assignee !== '' && t.assignee !== String(p.assignee)) continue
992
+ if (parentWanted != null && t.parent_seq !== parentWanted) continue
993
+ if (text && !`${t.title}\n${t.description ?? ''}`.toLowerCase().includes(text)) continue
994
+ out.push(agentView(t))
995
+ if (out.length >= 200) return { tasks: out, more: 'only the first 200: narrow it with status, assignee or text' }
996
+ }
997
+ }
998
+ return { tasks: out }
999
+ }
1000
+ case 'get': {
1001
+ rateLimit(name)
1002
+ const t = agentTask(me, p.id)
1003
+ await sync.freshTask(t) // (with GitHub's comments)
1004
+ return agentView(taskRow(t.seq) ?? t, { full: true })
1005
+ }
1006
+ case 'create': {
1007
+ if (me.role !== 'coordinator') throw new ApiError(403, 'Forbidden: workers don\'t create tasks: ask your coordinator')
1008
+ agentChange(name)
1009
+ const b = agentBoard(me, p.board)
1010
+ spendStorage('text', name, String(p.title ?? '').length + String(p.description ?? '').length)
1011
+ const assignee = agentAssignee(me, b, p.assignee) ?? null
1012
+ const seq = inTx(() => createTask(b, p, by, { assignee, byAgentTeam: assignee ? me.team : null }))
1013
+ changedTask(seq)
1014
+ const made = taskRow(seq)
1015
+ return { created: agentView(made), ...(!assignee && made.assignee_kind ? { handed_on: handedOn(me, made) } : {}) }
1016
+ }
1017
+ case 'update': {
1018
+ agentChange(name)
1019
+ const t = agentTask(me, p.id)
1020
+ const b = boardRow(t.board_id)
1021
+ let assignee
1022
+ if (me.role === 'worker') {
1023
+ const extra = ['title', 'description', 'type', 'labels', 'priority', 'due', 'assignee', 'parent'].filter(k => p[k] !== undefined)
1024
+ if (extra.length) throw new ApiError(403, `Forbidden: a worker only moves its tasks (status) and comments on them; ${extra.join(', ')} is your coordinator's to change`)
1025
+ if (p.status != null) {
1026
+ const to = findIn(statusesOf(b.id), p.status, 'status')
1027
+ const here = statusRow(t.status_id)
1028
+ const ways = [here.next_id, here.back_id].filter(Boolean)
1029
+ if (to.id !== here.id && ways.length && !ways.includes(to.id)) {
1030
+ throw new ApiError(403, `Forbidden: the board's flow takes ${taskId(t.seq)} from «${here.name}» ${here.next_id ? `to «${nameOf(here.next_id)}» when done` : ''}${here.next_id && here.back_id ? ', or ' : ''}${here.back_id ? `back to «${nameOf(here.back_id)}» if it isn't acceptable` : ''}: anything else is your coordinator's to say`)
1031
+ }
1032
+ if (to.id !== here.id && !ways.length && ['done', 'closed'].includes(to.category)) throw new ApiError(403, 'Forbidden: a worker moves its tasks up to review at most: done or cancelled is your coordinator\'s to say')
1033
+ }
1034
+ } else {
1035
+ if (!ours(me, t)) throw new ApiError(403, `Forbidden: ${taskId(t.seq)} is not your team's${t.assignee_kind === 'user' ? ' (a person has it)' : ''}: comment on it instead`)
1036
+ assignee = agentAssignee(me, b, p.assignee)
1037
+ }
1038
+ spendStorage('text', name, String(p.title ?? '').length + String(p.description ?? '').length)
1039
+ const { version, rank, ...rest } = p
1040
+ const changed = inTx(() => updateTask(t.seq, rest, by, { assignee, human: false }))
1041
+ if (changed) changedTask(t.seq, t.parent_seq)
1042
+ const out = { [changed ? 'updated' : 'unchanged']: agentView(taskRow(t.seq)) }
1043
+ if (changed === 'flow') out.handed_on = handedOn(me, taskRow(t.seq))
1044
+ return out
1045
+ }
1046
+ case 'comment': {
1047
+ agentChange(name)
1048
+ const t = agentTask(me, p.id)
1049
+ spendStorage('text', name, String(p.text ?? '').length)
1050
+ const c = inTx(() => commentOn(t.seq, p.text, by))
1051
+ changedTask(t.seq)
1052
+ return { commented: taskId(t.seq), comment: c.id }
1053
+ }
1054
+ default:
1055
+ throw bad('action must be one of: boards, list, get, create, update, comment')
1056
+ }
1057
+ },
1058
+ }
1059
+
1060
+ // A session deleted: its tasks are nobody's, and a coordinator's team no
1061
+ // longer sees its boards (a new session with that name won't either).
1062
+ function forget(name) {
1063
+ const by = { kind: 'user', id: 'server', name: 'session deleted' }
1064
+ const hit = db.prepare("SELECT seq, board_id FROM tasks WHERE assignee_kind = 'session' AND assignee = ?").all(name)
1065
+ for (const t of hit) {
1066
+ db.prepare("UPDATE tasks SET assignee_kind = NULL, assignee = NULL, notify_state = 'none', notified_to = NULL, version = version + 1, updated_at = ? WHERE seq = ?").run(now(), t.seq)
1067
+ event(t.seq, by, 'changed', { assignee: null, deleted_session: name })
1068
+ changedTask(t.seq)
1069
+ }
1070
+ db.prepare("UPDATE tasks SET notify_state = CASE WHEN assignee_kind = 'session' THEN 'pending' ELSE 'none' END, notified_to = NULL WHERE notified_to = ?").run(name)
1071
+ const steps = db.prepare("UPDATE board_statuses SET handler_kind = NULL, handler = NULL WHERE handler_kind = 'session' AND handler = ?").run(name).changes
1072
+ if (db.prepare('DELETE FROM board_teams WHERE coordinator = ?').run(name).changes || steps) changedBoard()
1073
+ }
1074
+
1075
+ const FROM_GITHUB = () => sync.FROM
1076
+ sync = createGithubSync({
1077
+ db, inTx, log, MAX, cleanText, bad, addColumn, dataDir: platform.dataDir,
1078
+ statusRows: boardId => db.prepare('SELECT * FROM board_statuses WHERE board_id = ? ORDER BY position, id').all(boardId),
1079
+ statusRow, taskRow, boardRow, typeRows: typesOf, labelRows: labelsOf,
1080
+ labelNames: seq => db.prepare('SELECT l.name FROM task_labels x JOIN board_labels l ON l.id = x.label_id WHERE x.task_seq = ?').all(seq).map(r => r.name),
1081
+ createTask, updateTask, checkAssignee, assignableSessions, event, changedTask, changedBoard, childrenOf, anyTask, members: memberList, peopleOf, prefix,
1082
+ trash: (t, data) => trashTasks(t, { by: FROM_GITHUB(), data, github: true }),
1083
+ restore: t => restoreTasks(t, { by: FROM_GITHUB(), github: true }),
1084
+ })
1085
+
1086
+ return { boardReads, boardActions, boardMethods, boardList, forget, taskIn, BOARD_SENDER }
1087
+ }