pisha-server 0.0.0-stage → 0.0.11

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 (125) 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 +1079 -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 +79 -0
  14. package/dashboard/dashboard.js +407 -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 +224 -0
  28. package/organization/index.js +1 -0
  29. package/organization/organization.js +218 -0
  30. package/package.json +54 -4
  31. package/permissions/index.js +1 -0
  32. package/permissions/permissions.js +211 -0
  33. package/pisha-host.mjs +3297 -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 +166 -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 +2093 -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 +40 -0
  79. package/ui/inbox.js +535 -0
  80. package/ui/index.html +103 -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 +141 -0
  85. package/ui/newteam.js +223 -0
  86. package/ui/org.js +653 -0
  87. package/ui/overlays.css +126 -0
  88. package/ui/palette.js +179 -0
  89. package/ui/people.js +370 -0
  90. package/ui/permissions.js +202 -0
  91. package/ui/qr.js +158 -0
  92. package/ui/router.js +171 -0
  93. package/ui/routes.js +46 -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 +113 -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/session.js +42 -0
  105. package/ui/shell.css +122 -0
  106. package/ui/signin.js +120 -0
  107. package/ui/squads.js +370 -0
  108. package/ui/state.js +59 -0
  109. package/ui/stream.js +268 -0
  110. package/ui/styles.css +343 -0
  111. package/ui/team.js +115 -0
  112. package/ui/teams.js +58 -0
  113. package/ui/terminal.js +261 -0
  114. package/ui/theme.js +32 -0
  115. package/ui/timeline.js +163 -0
  116. package/ui/topbar.js +205 -0
  117. package/ui/voice-parse.js +98 -0
  118. package/ui/voice.js +320 -0
  119. package/vendor/InterVariable.woff2 +0 -0
  120. package/vendor/LICENSE-inter +92 -0
  121. package/vendor/LICENSE-xterm +21 -0
  122. package/vendor/README.md +8 -0
  123. package/vendor/addon-fit.js +2 -0
  124. package/vendor/xterm.css +218 -0
  125. package/vendor/xterm.js +2 -0
package/boards/sync.js ADDED
@@ -0,0 +1,980 @@
1
+ import { readFileSync, writeFileSync } from 'node:fs'
2
+ import { join } from 'node:path'
3
+ import { randomBytes, createCipheriv, createDecipheriv } from 'node:crypto'
4
+ import { githubClient, parseProjectUrl, parseRepo, GithubError } from './github.js'
5
+
6
+ // A board kept in step with a GitHub project, both ways. GitHub is asked only
7
+ // while the board is in use: see «when GitHub is asked» below.
8
+ //
9
+ // columns GitHub's: the project's Status options are the board's columns
10
+ // (their category and step are set here). A column added or
11
+ // renamed here changes the field there; changed on both sides,
12
+ // GitHub's changes are kept and ours go over them.
13
+ // a task an issue in the project (a draft item, if it is one there). A
14
+ // task made here becomes an issue in the board's repository.
15
+ // agents a single-select field «Agent» of the project, with the agents
16
+ // of the board's teams. Its people, the issue's assignees: by the
17
+ // GitHub user in each one's profile (other assignees left alone).
18
+ // type a single-select field «Type»; labels, the issue's.
19
+ // subtasks sub-issues; comments, both ways (ours signed with the author);
20
+ // one edited there is edited here, one deleted there no longer shown.
21
+ // closed done closes the issue as completed, cancelled as not planned;
22
+ // reopened there, it goes back to the first column where work waits.
23
+ // PRs the repository's pull requests that name a task (SQ-12 in their
24
+ // title, branch or text) or close its issue: shown on the task.
25
+ // One merged takes it to the first done column (unless the board
26
+ // says not to); the ones merged before the board first read them, not.
27
+ //
28
+ // Each field of a task keeps the value both sides last agreed on: whichever
29
+ // side differs from it changed; if both did, the later change wins. Nothing
30
+ // that comes from GitHub tells an agent: it waits for a person to say so.
31
+
32
+ const FRESH = Number(process.env.PISHA_GITHUB_FRESH_MS) || 180_000 // (a board or task in use is read again after this; tests make it short)
33
+ const SLACK = FRESH / 9 // (so that a dashboard asking every 3 minutes is never just too early)
34
+ const OPENED = FRESH / 6 // (just opened: read, unless someone did a moment ago; a task, half that)
35
+ const SOON = 3_000 // (a change here goes there this soon, with the others made meanwhile)
36
+ const WAIT = 10_000 // (an agent reading the board waits this long for GitHub, at most)
37
+ const NO_COMMENTS = { content: { comments: { nodes: [] } } }
38
+ const FROM = { kind: 'github', id: 'github', name: 'GitHub' }
39
+ const ACTIVE = ['unstarted', 'started', 'review']
40
+ const OPTION_COLOR = { backlog: 'GRAY', unstarted: 'BLUE', started: 'YELLOW', review: 'PURPLE', done: 'GREEN', closed: 'RED' }
41
+ const LABEL_HEX = { gray: '8c959f', blue: '0969da', green: '1a7f37', yellow: 'bf8700', orange: 'bc4c00', red: 'cf222e', purple: '8250df', pink: 'bf3989' }
42
+ // (Found by any of these names; made with the first GitHub takes: it keeps «Type» for its own issue types.)
43
+ const AGENT_FIELD = ['Agent', 'Agente', 'Pisha agent'], TYPE_FIELD = ['Task type', 'Tipo de tarea', 'Tipo', 'Pisha type']
44
+
45
+ // What a column of GitHub's is, by its name, until a person says otherwise.
46
+ export function guessCategory(name) {
47
+ const n = String(name).toLowerCase()
48
+ if (/backlog|ideas?|icebox/.test(n)) return 'backlog'
49
+ if (/cancel|won.?t|descart|closed|cerrad/.test(n)) return 'closed'
50
+ if (/done|hecho|complet|terminad|finish|shipped|merged/.test(n)) return 'done'
51
+ if (/review|revis|qa|test/.test(n)) return 'review'
52
+ if (/progress|curso|doing|working|haciendo/.test(n)) return 'started'
53
+ if (/todo|to do|hacer|pendiente|ready|next|new|nuev/.test(n)) return 'unstarted'
54
+ return 'started'
55
+ }
56
+
57
+ export function createGithubSync(ctx) {
58
+ const { db, log, dataDir, inTx, MAX, cleanText } = ctx
59
+
60
+ db.exec(`
61
+ CREATE TABLE IF NOT EXISTS board_github (
62
+ board_id INTEGER PRIMARY KEY REFERENCES boards(id) ON DELETE CASCADE,
63
+ owner_kind TEXT NOT NULL, owner TEXT NOT NULL, number INTEGER NOT NULL, project_id TEXT NOT NULL, title TEXT, url TEXT,
64
+ repo TEXT NOT NULL, repo_id TEXT NOT NULL, token TEXT NOT NULL,
65
+ status_field TEXT NOT NULL, agent_field TEXT, type_field TEXT, columns_dirty INTEGER NOT NULL DEFAULT 1,
66
+ connected_by TEXT, connected_at INTEGER NOT NULL, synced_at INTEGER, error TEXT
67
+ );
68
+ CREATE TABLE IF NOT EXISTS task_github (
69
+ task_seq INTEGER PRIMARY KEY REFERENCES tasks(seq) ON DELETE CASCADE, board_id INTEGER NOT NULL,
70
+ item_id TEXT NOT NULL UNIQUE, issue_id TEXT, draft_id TEXT, number INTEGER, repo TEXT, url TEXT, synced TEXT NOT NULL
71
+ );
72
+ CREATE TABLE IF NOT EXISTS task_prs (
73
+ task_seq INTEGER NOT NULL REFERENCES tasks(seq) ON DELETE CASCADE, pr_id TEXT NOT NULL, board_id INTEGER NOT NULL,
74
+ number INTEGER NOT NULL, title TEXT NOT NULL, url TEXT NOT NULL, state TEXT NOT NULL, review TEXT, author TEXT, updated_at INTEGER NOT NULL,
75
+ PRIMARY KEY (task_seq, pr_id)
76
+ );
77
+ CREATE TABLE IF NOT EXISTS github_outbox (id INTEGER PRIMARY KEY AUTOINCREMENT, board_id INTEGER NOT NULL REFERENCES boards(id) ON DELETE CASCADE, item_id TEXT NOT NULL, issue_id TEXT);
78
+ `)
79
+ ctx.addColumn('github_outbox', 'task_seq', 'INTEGER')
80
+ ctx.addColumn('board_github', 'prs_at', 'TEXT') // (the last change to a pull request read: those after it are read next)
81
+ ctx.addColumn('board_github', 'prs_from', 'INTEGER') // (when they were first read: merged before, a task isn't moved)
82
+ ctx.addColumn('board_github', 'merge_moves', 'INTEGER NOT NULL DEFAULT 1')
83
+ ctx.addColumn('board_github', 'columns_seen', 'TEXT') // (GitHub's columns when both sides last agreed: what changed there since)
84
+ ctx.addColumn('board_statuses', 'gh_option', 'TEXT')
85
+ ctx.addColumn('task_comments', 'gh_id', 'TEXT')
86
+ db.exec('CREATE UNIQUE INDEX IF NOT EXISTS task_comments_gh ON task_comments(gh_id) WHERE gh_id IS NOT NULL')
87
+
88
+ // --- the token at rest: encrypted with a key that is not in the database --------
89
+ const key = (() => {
90
+ const file = join(dataDir, 'secrets-key')
91
+ try { const k = Buffer.from(readFileSync(file, 'utf8').trim(), 'base64url'); if (k.length === 32) return k } catch {}
92
+ const k = randomBytes(32)
93
+ writeFileSync(file, `${k.toString('base64url')}\n`, { mode: 0o600 })
94
+ return k
95
+ })()
96
+ const seal = (boardId, secret) => {
97
+ const iv = randomBytes(12)
98
+ const c = createCipheriv('aes-256-gcm', key, iv)
99
+ c.setAAD(Buffer.from(`github:${boardId}`))
100
+ const body = Buffer.concat([c.update(secret, 'utf8'), c.final()])
101
+ return [iv, c.getAuthTag(), body].map(x => x.toString('base64url')).join('.')
102
+ }
103
+ const unseal = (boardId, sealed) => {
104
+ const [iv, tag, body] = String(sealed).split('.').map(x => Buffer.from(x, 'base64url'))
105
+ const d = createDecipheriv('aes-256-gcm', key, iv)
106
+ d.setAAD(Buffer.from(`github:${boardId}`))
107
+ d.setAuthTag(tag)
108
+ return Buffer.concat([d.update(body), d.final()]).toString('utf8')
109
+ }
110
+
111
+ const conn = boardId => db.prepare('SELECT * FROM board_github WHERE board_id = ?').get(boardId)
112
+ const clientOf = c => {
113
+ try { return githubClient(unseal(c.board_id, c.token)) } catch { throw new GithubError('the saved token can no longer be read: connect the board again', { auth: true }) }
114
+ }
115
+ // (A task in the trash keeps its link, to be put back as it was: it isn't one of the board's here.)
116
+ const links = boardId => db.prepare('SELECT g.* FROM task_github g JOIN tasks t ON t.seq = g.task_seq WHERE g.board_id = ? AND t.deleted_at IS NULL').all(boardId)
117
+ const linkOf = seq => db.prepare('SELECT * FROM task_github WHERE task_seq = ?').get(seq)
118
+
119
+ // What the dashboard shows of the connection (never the token): when it was
120
+ // last read whole, whether it is being read now, and how many changes made
121
+ // here haven't reached GitHub yet.
122
+ function view(boardId) {
123
+ const c = conn(boardId)
124
+ if (!c) return null
125
+ return {
126
+ owner_kind: c.owner_kind, owner: c.owner, number: c.number, title: c.title, url: c.url, repo: c.repo, synced_at: c.synced_at ?? null, error: c.error ?? null, linked: links(boardId).length,
127
+ syncing: busy.has(boardId) || queued.has(boardId), pending: notSent(boardId), merge_moves: !!c.merge_moves,
128
+ }
129
+ }
130
+ function notSent(boardId) {
131
+ const seqs = new Set([...(soonTimers.get(boardId)?.seqs ?? []), ...(sending.get(boardId) ?? [])])
132
+ const board = seqs.delete(null) ? 1 : 0 // (a change to the board itself: its columns)
133
+ const rows = db.prepare(`SELECT t.seq FROM tasks t LEFT JOIN task_github g ON g.task_seq = t.seq WHERE t.board_id = @b AND t.deleted_at IS NULL AND (g.task_seq IS NULL OR g.item_id LIKE 'pending:%')
134
+ UNION SELECT c.task_seq FROM task_comments c JOIN task_github g ON g.task_seq = c.task_seq JOIN tasks t ON t.seq = c.task_seq
135
+ WHERE g.board_id = @b AND g.issue_id IS NOT NULL AND t.deleted_at IS NULL AND c.gh_id IS NULL AND c.author NOT LIKE '{"kind":"github"%'`).all({ b: boardId })
136
+ for (const r of rows) seqs.add(r.seq)
137
+ return seqs.size + board + db.prepare('SELECT COUNT(*) n FROM github_outbox WHERE board_id = ?').get(boardId).n
138
+ }
139
+
140
+ // --- connecting -------------------------------------------------------------------
141
+ async function connect(board, p, actor) {
142
+ const where = parseProjectUrl(p.url)
143
+ if (!where) throw ctx.bad('the project is its address on GitHub, such as https://github.com/orgs/acme/projects/3')
144
+ const repo = parseRepo(p.repo)
145
+ if (!repo) throw ctx.bad('the repository is owner/name, such as acme/web: new tasks become issues there')
146
+ const token = String(p.token ?? '').trim()
147
+ if (!token && !conn(board.id)) throw ctx.bad('a token is needed to reach GitHub')
148
+ const secret = token || unseal(board.id, conn(board.id).token)
149
+ if (secret.length > 400 || /\s/.test(secret)) throw ctx.bad('that is not a GitHub token')
150
+ const gh = githubClient(secret)
151
+ let project, repository
152
+ try {
153
+ project = await gh.project(where)
154
+ repository = await gh.repository(repo)
155
+ } catch (err) { throw ctx.bad(err.message) }
156
+ const status = project.fields.find(f => f.name === 'Status' && Array.isArray(f.options))
157
+ if (!status) throw ctx.bad('the project has no Status field: its columns come from there')
158
+ const old = conn(board.id)
159
+ inTx(() => {
160
+ // (Another project: the old links mean nothing there.)
161
+ if (old && old.project_id !== project.id) {
162
+ db.prepare('DELETE FROM task_github WHERE board_id = ?').run(board.id)
163
+ db.prepare('UPDATE board_statuses SET gh_option = NULL WHERE board_id = ?').run(board.id)
164
+ }
165
+ // (Another repository: its pull requests, read afresh.)
166
+ if (old && old.repo !== repository.name) {
167
+ db.prepare('DELETE FROM task_prs WHERE board_id = ?').run(board.id)
168
+ db.prepare('UPDATE board_github SET prs_at = NULL, prs_from = NULL WHERE board_id = ?').run(board.id)
169
+ }
170
+ db.prepare(`INSERT INTO board_github (board_id, owner_kind, owner, number, project_id, title, url, repo, repo_id, token, status_field, connected_by, connected_at, columns_dirty)
171
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1)
172
+ ON CONFLICT(board_id) DO UPDATE SET owner_kind = excluded.owner_kind, owner = excluded.owner, number = excluded.number, project_id = excluded.project_id, title = excluded.title, url = excluded.url,
173
+ repo = excluded.repo, repo_id = excluded.repo_id, token = excluded.token, status_field = excluded.status_field, columns_dirty = 1, error = NULL`)
174
+ .run(board.id, where.ownerKind, where.owner, where.number, project.id, project.title, project.url, repository.name, repository.id, seal(board.id, secret), status.id, JSON.stringify(actor), Date.now())
175
+ adoptColumns(board.id, status)
176
+ })
177
+ ctx.changedBoard()
178
+ void syncBoard(board.id) // (the first one may take a while: it shows on the board)
179
+ return view(board.id)
180
+ }
181
+
182
+ function disconnect(boardId) {
183
+ lastBoard.delete(boardId)
184
+ inTx(() => {
185
+ db.prepare('DELETE FROM board_github WHERE board_id = ?').run(boardId)
186
+ db.prepare('DELETE FROM task_github WHERE board_id = ?').run(boardId)
187
+ db.prepare('DELETE FROM github_outbox WHERE board_id = ?').run(boardId)
188
+ db.prepare('DELETE FROM task_prs WHERE board_id = ?').run(boardId)
189
+ db.prepare('UPDATE board_statuses SET gh_option = NULL WHERE board_id = ?').run(boardId)
190
+ })
191
+ ctx.changedBoard()
192
+ }
193
+ // Whether a merged pull request takes its tasks to done.
194
+ function setMergeMoves(boardId, on) {
195
+ db.prepare('UPDATE board_github SET merge_moves = ? WHERE board_id = ?').run(on ? 1 : 0, boardId)
196
+ ctx.changedBoard()
197
+ }
198
+
199
+ // GitHub's columns become the board's: matched by name (or by the option
200
+ // they were), the missing ones added here; the board's own that GitHub
201
+ // lacks stay, and are added there on the next sync. GitHub's order first.
202
+ function adoptColumns(boardId, field) {
203
+ const mine = ctx.statusRows(boardId)
204
+ const used = new Set()
205
+ let position = 0
206
+ for (const o of field.options) {
207
+ const s = mine.find(x => x.gh_option === o.id && !used.has(x.id)) ?? mine.find(x => !used.has(x.id) && x.name.toLowerCase() === o.name.toLowerCase())
208
+ if (s) {
209
+ used.add(s.id)
210
+ db.prepare('UPDATE board_statuses SET gh_option = ?, name = ?, position = ? WHERE id = ?').run(o.id, o.name.slice(0, MAX.name), position++, s.id)
211
+ } else if (mine.length + 1 <= MAX.statuses) {
212
+ const id = Number(db.prepare('INSERT INTO board_statuses (board_id, name, category, position, gh_option) VALUES (?, ?, ?, ?, ?)').run(boardId, o.name.slice(0, MAX.name), guessCategory(o.name), position++, o.id).lastInsertRowid)
213
+ used.add(id)
214
+ mine.push({ id, name: o.name, gh_option: o.id })
215
+ }
216
+ }
217
+ for (const s of mine.filter(x => !used.has(x.id))) {
218
+ const tasks = db.prepare('SELECT COUNT(*) n FROM tasks WHERE status_id = ? AND deleted_at IS NULL').get(s.id).n
219
+ // (Deleted in GitHub, and empty here: gone here too. With tasks: kept, and given back to GitHub.)
220
+ if (s.gh_option && !tasks) {
221
+ for (const col of ['next_id', 'back_id']) db.prepare(`UPDATE board_statuses SET ${col} = NULL WHERE ${col} = ?`).run(s.id)
222
+ db.prepare('DELETE FROM board_statuses WHERE id = ?').run(s.id)
223
+ continue
224
+ }
225
+ db.prepare('UPDATE board_statuses SET gh_option = NULL, position = ? WHERE id = ?').run(position++, s.id)
226
+ db.prepare('UPDATE board_github SET columns_dirty = 1 WHERE board_id = ?').run(boardId)
227
+ }
228
+ seenColumns(boardId, field)
229
+ }
230
+ const seenColumns = (boardId, field) => db.prepare('UPDATE board_github SET columns_seen = ? WHERE board_id = ?').run(JSON.stringify(field.options.map(o => ({ id: o.id, name: o.name }))), boardId)
231
+
232
+ // Changed here, on their way there: what GitHub changed meanwhile, kept.
233
+ // Added there, a column here too (where GitHub has it); renamed there and
234
+ // not here, its name; deleted there, untouched here and empty, gone here.
235
+ function mergeColumns(boardId, field) {
236
+ const seen = JSON.parse(conn(boardId)?.columns_seen ?? 'null')
237
+ if (!seen) return
238
+ const was = new Map(seen.map(o => [o.id, o.name]))
239
+ const mine = () => ctx.statusRows(boardId)
240
+ const named = (name, but) => mine().some(x => x.id !== but && x.name.toLowerCase() === name.toLowerCase())
241
+ const byOption = () => new Map(mine().filter(s => s.gh_option).map(s => [s.gh_option, s]))
242
+ for (const o of field.options) {
243
+ const s = byOption().get(o.id)
244
+ if (s && was.has(o.id) && o.name !== was.get(o.id) && s.name === was.get(o.id) && !named(o.name, s.id)) db.prepare('UPDATE board_statuses SET name = ? WHERE id = ?').run(o.name.slice(0, MAX.name), s.id)
245
+ }
246
+ field.options.forEach((o, i) => {
247
+ if (was.has(o.id) || byOption().has(o.id) || named(o.name) || mine().length >= MAX.statuses) return
248
+ const after = field.options.slice(0, i).reverse().map(x => byOption().get(x.id)).find(Boolean)
249
+ const at = after ? after.position + 1 : 0
250
+ db.prepare('UPDATE board_statuses SET position = position + 1 WHERE board_id = ? AND position >= ?').run(boardId, at)
251
+ db.prepare('INSERT INTO board_statuses (board_id, name, category, position, gh_option) VALUES (?, ?, ?, ?, ?)').run(boardId, o.name.slice(0, MAX.name), guessCategory(o.name), at, o.id)
252
+ })
253
+ for (const [id, name] of was) {
254
+ const s = byOption().get(id)
255
+ if (!s || field.options.some(o => o.id === id) || s.name !== name) continue
256
+ if (db.prepare('SELECT COUNT(*) n FROM tasks WHERE status_id = ?').get(s.id).n) continue
257
+ for (const col of ['next_id', 'back_id']) db.prepare(`UPDATE board_statuses SET ${col} = NULL WHERE ${col} = ?`).run(s.id)
258
+ db.prepare('DELETE FROM board_statuses WHERE id = ?').run(s.id)
259
+ }
260
+ }
261
+
262
+ // --- what each side says of a task ---------------------------------------------------
263
+ const norm = {
264
+ title: v => cleanText(String(v ?? '')).replace(/\s+/g, ' ').trim().slice(0, MAX.title),
265
+ body: v => cleanText(String(v ?? '')).replace(/\r\n?/g, '\n').trim().slice(0, MAX.description),
266
+ }
267
+ const categoryOf = s => s?.category ?? 'unstarted'
268
+ // People, by their GitHub user (in lower case): only the company's who have one in their profile.
269
+ const split = v => (v ? String(v).split('\n') : [])
270
+ const loginsOf = () => new Map(ctx.members().filter(m => m.github).map(m => [m.id, m.github.toLowerCase()]))
271
+ const peopleLogins = (seq, refused = []) => { const by = loginsOf(); return ctx.peopleOf(seq).map(id => by.get(id)).filter(l => l && !refused.includes(l)).sort().join('\n') }
272
+ const userIds = new Map() // (a GitHub user's id, by login: it doesn't change)
273
+ async function userIdOf(gh, login) {
274
+ if (!userIds.has(login)) userIds.set(login, await gh.userId(login))
275
+ return userIds.get(login)
276
+ }
277
+ function ours(t, parentIssue, refused = []) {
278
+ const s = ctx.statusRow(t.status_id)
279
+ const cat = categoryOf(s)
280
+ return {
281
+ title: t.title, body: t.description ?? '', status: s?.gh_option ?? null,
282
+ closed: cat === 'done' ? 'COMPLETED' : cat === 'closed' ? 'NOT_PLANNED' : 'OPEN',
283
+ agent: t.assignee_kind === 'session' ? t.assignee : null,
284
+ type: t.type_id ? ctx.typeRows(t.board_id).find(x => x.id === t.type_id)?.name.toLowerCase() ?? null : null,
285
+ labels: ctx.labelNames(t.seq).map(n => n.toLowerCase()).sort().join('\n'),
286
+ parent: parentIssue,
287
+ people: peopleLogins(t.seq, refused),
288
+ }
289
+ }
290
+ function theirs(item, fields) {
291
+ const pick = fieldId => item.fieldValues?.nodes?.find(v => v?.field?.id === fieldId)?.optionId ?? null
292
+ const name = (field, id) => field?.options?.find(o => o.id === id)?.name ?? null
293
+ const c = item.content
294
+ const out = {
295
+ title: norm.title(c.title), body: norm.body(c.body), status: pick(fields.status.id),
296
+ agent: fields.agent ? name(fields.agent, pick(fields.agent.id)) : null, type: fields.type ? name(fields.type, pick(fields.type.id))?.toLowerCase() ?? null : null,
297
+ }
298
+ if (c.__typename === 'Issue') {
299
+ out.closed = c.state === 'CLOSED' ? (c.stateReason === 'NOT_PLANNED' || c.stateReason === 'DUPLICATE' ? 'NOT_PLANNED' : 'COMPLETED') : 'OPEN'
300
+ out.labels = (c.labels?.nodes ?? []).map(l => l.name.toLowerCase()).sort().join('\n')
301
+ out.parent = c.parent?.id ?? null
302
+ const known = new Set(loginsOf().values()) // (assignees who aren't the company's people: left as they are)
303
+ out.people = (c.assignees?.nodes ?? []).filter(Boolean).map(n => n.login.toLowerCase()).filter(l => known.has(l)).sort().join('\n')
304
+ }
305
+ return out
306
+ }
307
+
308
+ // (Compared in lower case; made here as GitHub writes them.)
309
+ const typeThere = (item, fields) => fields.type?.options.find(o => o.id === item.fieldValues?.nodes?.find(v => v?.field?.id === fields.type.id)?.optionId)?.name ?? null
310
+ const labelsThere = item => (item.content.labels?.nodes ?? []).map(l => l.name)
311
+
312
+ // --- when GitHub is asked -------------------------------------------------------------
313
+ // Only while the board is in use: when someone opens it, and every few
314
+ // minutes while it stays open (the dashboard says so); when an agent reads
315
+ // it; and soon after a change here, for the tasks that changed. A task is
316
+ // read with its comments when it is opened. A board nobody uses costs nothing.
317
+ const chains = new Map() // board id -> its work, one thing at a time
318
+ const queued = new Map() // board id -> a whole sync waiting its turn
319
+ const lastBoard = new Map() // board id -> when it was last read whole
320
+ const lastTask = new Map() // task seq -> when it was last read
321
+ const lastAsked = new Map() // task seq -> when the button last asked for it
322
+ const soonTimers = new Map() // board id -> the changes waiting to go: { timer, seqs } (null: the whole board)
323
+ const busy = new Map() // board id -> whole syncs running
324
+ const sending = new Map() // board id -> Set of the tasks whose changes are on their way
325
+ let applying = 0 // (changes made here from GitHub don't ask for another sync)
326
+
327
+ function serial(boardId, fn) {
328
+ const p = (chains.get(boardId) ?? Promise.resolve()).then(fn)
329
+ const tail = p.catch(() => {})
330
+ chains.set(boardId, tail)
331
+ void tail.then(() => { if (chains.get(boardId) === tail) chains.delete(boardId) })
332
+ return p
333
+ }
334
+ const within = (p, ms) => Promise.race([p, new Promise(r => { const t = setTimeout(r, ms); t.unref?.() })])
335
+ const stale = (at, ms) => Date.now() - (at ?? 0) >= ms
336
+
337
+ function touch(boardId, seq = null) {
338
+ if (applying || !conn(boardId)) return
339
+ let w = soonTimers.get(boardId)
340
+ if (!w) {
341
+ w = { seqs: new Set() }
342
+ w.timer = setTimeout(() => {
343
+ soonTimers.delete(boardId)
344
+ if (w.seqs.has(null)) void syncBoard(boardId)
345
+ else void syncTasks(boardId, [...w.seqs], { sending: true })
346
+ }, SOON)
347
+ w.timer.unref?.()
348
+ soonTimers.set(boardId, w)
349
+ }
350
+ w.seqs.add(seq)
351
+ }
352
+ // (The dashboard sees it start and end: «syncing», «sending n changes».)
353
+ async function tracked(boardId, mark, fn) {
354
+ const undo = mark()
355
+ ctx.changedBoard()
356
+ try { return await fn() } finally { undo(); ctx.changedBoard() }
357
+ }
358
+ // The whole board (with the one already waiting its turn, if there is one).
359
+ function syncBoard(boardId) {
360
+ if (queued.has(boardId)) return queued.get(boardId)
361
+ lastBoard.set(boardId, Date.now())
362
+ const p = serial(boardId, () => {
363
+ queued.delete(boardId)
364
+ return tracked(boardId, () => { busy.set(boardId, (busy.get(boardId) ?? 0) + 1); return () => { const n = busy.get(boardId) - 1; if (n > 0) busy.set(boardId, n); else busy.delete(boardId) } }, () => attempt(boardId, run))
365
+ })
366
+ queued.set(boardId, p)
367
+ return p
368
+ }
369
+ // These tasks only: what changed here goes there, and each comes back with its comments.
370
+ function syncTasks(boardId, seqs, { sending: changes = false } = {}) {
371
+ for (const seq of seqs) lastTask.set(seq, Date.now())
372
+ const mark = () => {
373
+ if (!changes) return () => {}
374
+ const set = sending.get(boardId) ?? new Set()
375
+ sending.set(boardId, set)
376
+ for (const s of seqs) set.add(s)
377
+ return () => { for (const s of seqs) set.delete(s); if (!set.size) sending.delete(boardId) }
378
+ }
379
+ if (changes) { const undo = mark(); const p = serial(boardId, () => tracked(boardId, () => undo, () => attempt(boardId, (c, board) => runTasks(c, board, seqs)))); return p }
380
+ return serial(boardId, () => attempt(boardId, (c, board) => runTasks(c, board, seqs)))
381
+ }
382
+ async function attempt(boardId, fn) {
383
+ const c = conn(boardId)
384
+ const board = ctx.boardRow(boardId)
385
+ if (!c || !board || board.archived_at) return
386
+ try {
387
+ const whole = (await fn(c, board)) !== 'part'
388
+ if (whole) db.prepare('UPDATE board_github SET synced_at = ?, error = NULL WHERE board_id = ?').run(Date.now(), boardId)
389
+ else db.prepare('UPDATE board_github SET error = NULL WHERE board_id = ?').run(boardId)
390
+ } catch (err) {
391
+ log(`GitHub sync of board ${boardId}: ${err.message}`)
392
+ db.prepare('UPDATE board_github SET error = ? WHERE board_id = ?').run(String(err.message).slice(0, 500), boardId)
393
+ }
394
+ ctx.changedBoard()
395
+ }
396
+
397
+ // Someone has the board open, and maybe one of its tasks: what isn't fresh is read.
398
+ // (Asked for with the button: the task now, if the button didn't ask a moment ago.)
399
+ function watch(boardId, { task = null, opened = false, taskOpened = false, force = false } = {}) {
400
+ if (!conn(boardId)) return Promise.resolve()
401
+ const work = []
402
+ if (stale(lastBoard.get(boardId), opened ? OPENED : FRESH - SLACK)) work.push(syncBoard(boardId))
403
+ const t = task ? ctx.taskRow(task) : null
404
+ const due = force ? stale(lastAsked.get(t?.seq), SOON) : stale(lastTask.get(t?.seq), taskOpened ? OPENED / 2 : FRESH - SLACK)
405
+ if (t?.board_id === boardId && linkOf(t.seq) && due) { if (force) lastAsked.set(t.seq, Date.now()); work.push(syncTasks(boardId, [t.seq])) }
406
+ return Promise.all(work)
407
+ }
408
+ // An agent reads the board, or a task of it: GitHub's first, if it isn't fresh (waiting a little at most).
409
+ const fresh = boardId => (conn(boardId) && stale(lastBoard.get(boardId), FRESH - SLACK) ? within(syncBoard(boardId), WAIT) : Promise.resolve())
410
+ const freshTask = t => (t && conn(t.board_id) && linkOf(t.seq) && stale(lastTask.get(t.seq), OPENED) ? within(syncTasks(t.board_id, [t.seq]), WAIT) : Promise.resolve())
411
+
412
+ async function run(c, board) {
413
+ const gh = clientOf(c)
414
+ const where = { ownerKind: c.owner_kind, owner: c.owner, number: c.number }
415
+ let project = await gh.project(where)
416
+ const statusField = project.fields.find(f => f.id === c.status_field) ?? project.fields.find(f => f.name === 'Status' && f.options)
417
+ if (!statusField) throw new GithubError('the project has no Status field any more')
418
+ let items = await gh.items(project.id)
419
+
420
+ // The columns: GitHub's, unless they were changed here (then ours, there).
421
+ if (!conn(board.id).columns_dirty) inTx(() => adoptColumns(board.id, statusField))
422
+ if (conn(board.id).columns_dirty) {
423
+ inTx(() => mergeColumns(board.id, statusField))
424
+ await pushColumns(gh, project, statusField, items, board.id)
425
+ project = await gh.project(where)
426
+ items = await gh.items(project.id)
427
+ }
428
+ const fields = { status: project.fields.find(f => f.id === statusField.id) ?? statusField }
429
+
430
+ // The agent and type fields: with every agent and type of the board as an option.
431
+ const agents = ctx.assignableSessions(board.id).map(s => s.name)
432
+ const types = ctx.typeRows(board.id).map(t => t.name)
433
+ let refetch = false
434
+ for (const [key, names, wanted, column] of [['agent', AGENT_FIELD, agents, 'agent_field'], ['type', TYPE_FIELD, types, 'type_field']]) {
435
+ const r = await ensureSelect(gh, project, items, { id: c[column], names, wanted })
436
+ fields[key] = r.field
437
+ if (r.field && r.field.id !== c[column]) db.prepare(`UPDATE board_github SET ${column} = ? WHERE board_id = ?`).run(r.field.id, board.id)
438
+ refetch ||= r.changed
439
+ }
440
+ if (refetch) items = await gh.items(project.id)
441
+
442
+ // (Before the items: a task a merged pull request moves goes there in this same sync.)
443
+ try { await pullRequests(gh, conn(board.id), board) } catch (err) { log(`GitHub pull requests of board ${board.id}: ${err.message}`); if (err.auth && err.status === 401) throw err }
444
+
445
+ const seen = new Set()
446
+ const byIssue = new Map()
447
+ for (const l of links(board.id)) if (l.issue_id) byIssue.set(l.issue_id, l.task_seq)
448
+ // GitHub's items: new ones become tasks; the others, field by field.
449
+ const imported = []
450
+ const leaving = new Set(db.prepare('SELECT item_id FROM github_outbox WHERE board_id = ?').all(board.id).map(o => o.item_id)) // (deleted here, on their way out there)
451
+ for (const item of items) {
452
+ if (item.isArchived || !item.content || !['Issue', 'DraftIssue'].includes(item.content.__typename) || leaving.has(item.id)) continue
453
+ seen.add(item.id)
454
+ const link = db.prepare('SELECT * FROM task_github WHERE item_id = ?').get(item.id) ?? itemOfPending(item) ?? backFromTrash(item)
455
+ try {
456
+ if (!link) { const seq = importItem(board, item, fields); if (seq) { imported.push([seq, item]); if (item.content.__typename === 'Issue') byIssue.set(item.content.id, seq) } } else await reconcile(gh, c, board, link, item, fields, byIssue)
457
+ } catch (err) { log(`GitHub item ${item.id} of board ${board.id}: ${err.message}`) }
458
+ }
459
+ // (Parents once every task is there.)
460
+ for (const [seq, item] of imported) {
461
+ const parent = item.content.parent?.id && byIssue.get(item.content.parent.id)
462
+ if (parent) applyHere(seq, { parent }, item)
463
+ }
464
+ // Linked tasks whose item left the project: no longer linked. (Made, but not yet in it: into it.)
465
+ for (const l of links(board.id)) {
466
+ if (l.item_id.startsWith('pending:')) { await intoProject(gh, project, l); continue }
467
+ if (!seen.has(l.item_id)) removedThere(l)
468
+ }
469
+ await sendOutbox(gh, project, board.id)
470
+ // Ours not yet there: issues in the board's repository, parents first.
471
+ const linked = new Set(links(board.id).map(l => l.task_seq))
472
+ const missing = db.prepare('SELECT * FROM tasks WHERE board_id = ? AND deleted_at IS NULL ORDER BY seq').all(board.id).filter(t => !linked.has(t.seq))
473
+ const depth = t => { let n = 0; for (let x = t; x?.parent_seq && n < 10; x = ctx.taskRow(x.parent_seq)) n++; return n }
474
+ missing.sort((a, b) => depth(a) - depth(b) || a.seq - b.seq)
475
+ let repoLabels = null
476
+ for (const t of missing) {
477
+ try {
478
+ repoLabels ??= (await gh.repository(parseRepo(c.repo))).labels
479
+ await publish(gh, c, project, fields, ctx.taskRow(t.seq), repoLabels)
480
+ } catch (err) { log(`GitHub: task ${t.seq} could not be published: ${err.message}`); if (err.auth) throw err }
481
+ }
482
+ // Comments of ours that didn't get there (GitHub's come when a task is opened).
483
+ for (const l of links(board.id)) if (l.issue_id && !l.item_id.startsWith('pending:') && unsent(l.task_seq).length) await comments(gh, l, NO_COMMENTS)
484
+ }
485
+
486
+ // Some tasks, without reading the whole board: each item by itself. A whole
487
+ // sync instead if the board needs one (its columns changed here, or GitHub
488
+ // lacks an agent or type).
489
+ async function runTasks(c, board, seqs) {
490
+ if (c.columns_dirty) return run(c, board)
491
+ const gh = clientOf(c)
492
+ const project = await gh.project({ ownerKind: c.owner_kind, owner: c.owner, number: c.number })
493
+ const fields = fieldsOf(c, project, board.id)
494
+ if (!fields) return run(c, board)
495
+ await sendOutbox(gh, project, board.id)
496
+ // (A subtask's parents first, if they aren't on GitHub yet.)
497
+ const todo = new Set()
498
+ for (const seq of seqs) {
499
+ const up = []
500
+ const row = s => (s ? ctx.taskRow(s) : null)
501
+ for (let p = row(row(seq)?.parent_seq), n = 0; p && !linkOf(p.seq) && n < MAX.depth; p = row(p.parent_seq), n++) up.unshift(p.seq)
502
+ for (const x of [...up, seq]) todo.add(x)
503
+ }
504
+ const byIssue = new Map(links(board.id).filter(l => l.issue_id).map(l => [l.issue_id, l.task_seq]))
505
+ let repoLabels = null
506
+ for (const seq of todo) {
507
+ const t = ctx.taskRow(seq)
508
+ if (!t || t.board_id !== board.id) continue
509
+ try {
510
+ let link = linkOf(seq)
511
+ if (link?.item_id.startsWith('pending:')) { await intoProject(gh, project, link); link = linkOf(seq) }
512
+ if (link?.item_id.startsWith('pending:')) continue // (not in the project yet: next time)
513
+ if (!link) {
514
+ repoLabels ??= (await gh.repository(parseRepo(c.repo))).labels
515
+ await publish(gh, c, project, fields, t, repoLabels)
516
+ const made = linkOf(seq)
517
+ if (made && unsent(seq).length) await comments(gh, made, NO_COMMENTS)
518
+ continue
519
+ }
520
+ const item = await gh.item(link.item_id)
521
+ if (!item || item.isArchived || !item.content) { removedThere(link); continue }
522
+ if (item.content.__typename === 'Issue' && item.content.id) byIssue.set(item.content.id, seq)
523
+ await reconcile(gh, c, board, link, item, fields, byIssue)
524
+ if (item.content.__typename === 'Issue') await comments(gh, linkOf(seq), item)
525
+ } catch (err) { log(`GitHub: task ${seq}: ${err.message}`); if (err.auth) throw err }
526
+ }
527
+ return 'part'
528
+ }
529
+
530
+ // The project's fields as the last whole sync left them; null if the board
531
+ // needs a whole one first (a column, agent or type GitHub hasn't).
532
+ function fieldsOf(c, project, boardId) {
533
+ const status = project.fields.find(f => f.id === c.status_field && Array.isArray(f.options))
534
+ if (!status || ctx.statusRows(boardId).some(s => !status.options.some(o => o.id === s.gh_option))) return null
535
+ const out = { status }
536
+ for (const [key, wanted, column] of [['agent', ctx.assignableSessions(boardId).map(s => s.name), 'agent_field'], ['type', ctx.typeRows(boardId).map(t => t.name), 'type_field']]) {
537
+ const f = c[column] ? project.fields.find(x => x.id === c[column] && Array.isArray(x.options)) : null
538
+ if (!f && wanted.length) return null
539
+ if (f && wanted.some(n => !f.options.some(o => o.name.toLowerCase() === n.toLowerCase()))) return null
540
+ out[key] = f ?? null
541
+ }
542
+ return out
543
+ }
544
+ // Its issue into the project. The issue gone (deleted on GitHub): no longer linked, so the task is published again, as a new issue.
545
+ async function intoProject(gh, project, l) {
546
+ try { db.prepare('UPDATE task_github SET item_id = ? WHERE task_seq = ?').run(await gh.addItem(project.id, l.issue_id), l.task_seq) } catch (err) {
547
+ if (err.auth) throw err
548
+ if (err.notFound) { db.prepare('DELETE FROM task_github WHERE task_seq = ?').run(l.task_seq); return }
549
+ log(`GitHub: adding issue of task ${l.task_seq} to the project: ${err.message}`)
550
+ }
551
+ }
552
+ // Taken out of the project there: into the trash here (its subtasks stay, with
553
+ // no parent, as when deleted here). Its issue stays as it was.
554
+ function removedThere(l) {
555
+ const t = ctx.taskRow(l.task_seq)
556
+ if (!t) return
557
+ for (const c of ctx.childrenOf(t.seq)) {
558
+ const cl = linkOf(c.seq)
559
+ if (cl) db.prepare('UPDATE task_github SET synced = ? WHERE task_seq = ?').run(JSON.stringify({ ...JSON.parse(cl.synced), parent: null }), c.seq) // (not taken off its parent there)
560
+ }
561
+ if (l.issue_id) db.prepare("UPDATE task_github SET item_id = 'trashed:' || task_seq WHERE task_seq = ?").run(t.seq)
562
+ else db.prepare('DELETE FROM task_github WHERE task_seq = ?').run(t.seq) // (a draft: gone there)
563
+ applying++
564
+ try { ctx.trash(t, { github: 'taken out of the project' }) } finally { applying-- }
565
+ }
566
+ // An item of an issue made here that wasn't in the project yet (GitHub put it there by itself): its task's.
567
+ function itemOfPending(item) {
568
+ if (item.content.__typename !== 'Issue') return null
569
+ const l = db.prepare('SELECT * FROM task_github WHERE item_id = ?').get(`pending:${item.content.id}`)
570
+ if (!l) return null
571
+ db.prepare('UPDATE task_github SET item_id = ? WHERE task_seq = ?').run(item.id, l.task_seq)
572
+ return linkOf(l.task_seq)
573
+ }
574
+ // An item of an issue whose task is in the trash: put in the project again there, so back here (GitHub's, as it is there).
575
+ function backFromTrash(item) {
576
+ if (item.content.__typename !== 'Issue') return null
577
+ const l = db.prepare('SELECT g.* FROM task_github g JOIN tasks t ON t.seq = g.task_seq WHERE g.issue_id = ? AND t.deleted_at IS NOT NULL').get(item.content.id)
578
+ if (!l || db.prepare('SELECT 1 FROM github_outbox WHERE task_seq = ?').get(l.task_seq)) return null
579
+ applying++
580
+ try { ctx.restore(ctx.anyTask(l.task_seq)) } catch (err) { log(`GitHub: task ${l.task_seq} back from the trash: ${err.message}`); return null } finally { applying-- }
581
+ db.prepare('UPDATE task_github SET item_id = ?, synced = ? WHERE task_seq = ?').run(item.id, JSON.stringify({ prefer: 'there' }), l.task_seq)
582
+ return linkOf(l.task_seq)
583
+ }
584
+ // Deleted here: closed there and out of the project.
585
+ async function sendOutbox(gh, project, boardId) {
586
+ for (const o of db.prepare('SELECT * FROM github_outbox WHERE board_id = ?').all(boardId)) {
587
+ try {
588
+ if (!o.item_id.startsWith('pending:')) await gh.removeItem(project.id, o.item_id)
589
+ if (o.issue_id) await gh.closeIssue(o.issue_id, 'NOT_PLANNED')
590
+ } catch (err) {
591
+ log(`GitHub: closing a deleted task's issue: ${err.message}`)
592
+ if (err.auth) throw err
593
+ if (err.transient) continue // (tried again next time)
594
+ }
595
+ db.prepare('DELETE FROM github_outbox WHERE id = ?').run(o.id)
596
+ }
597
+ }
598
+ const unsent = seq => db.prepare('SELECT * FROM task_comments WHERE task_seq = ? AND gh_id IS NULL ORDER BY id').all(seq).filter(cm => JSON.parse(cm.author).kind !== 'github')
599
+
600
+ // A single-select field with these names as options (made if missing). Its
601
+ // options replaced, the items get back the value they had, by its name.
602
+ async function ensureSelect(gh, project, items, { id, names, wanted }) {
603
+ let field = project.fields.find(f => f.id === id && f.options) ?? project.fields.find(f => names.includes(f.name) && Array.isArray(f.options))
604
+ if (!field) {
605
+ if (!wanted.length) return { field: null, changed: false }
606
+ for (const name of names) {
607
+ if (project.fields.some(f => f.name.toLowerCase() === name.toLowerCase())) continue
608
+ try {
609
+ field = await gh.createField(project.id, name, wanted.map(n => ({ name: n, color: 'GRAY', description: '' })))
610
+ } catch (err) { if (/reserved|already been taken/i.test(err.message)) continue; throw err }
611
+ return { field, changed: true }
612
+ }
613
+ return { field: null, changed: false }
614
+ }
615
+ const have = new Set(field.options.map(o => o.name.toLowerCase()))
616
+ const add = wanted.filter(n => !have.has(n.toLowerCase()))
617
+ if (!add.length) return { field, changed: false }
618
+ const before = valuesOf(items, field)
619
+ const next = await gh.setOptions(field.id, [...field.options.map(o => ({ name: o.name, color: o.color, description: '' })), ...add.map(n => ({ name: n, color: 'GRAY', description: '' }))])
620
+ await putBack(gh, project.id, next, before)
621
+ return { field: next, changed: true }
622
+ }
623
+ const valuesOf = (items, field) => items.map(it => [it.id, field.options.find(o => o.id === it.fieldValues?.nodes?.find(v => v?.field?.id === field.id)?.optionId)?.name ?? null]).filter(x => x[1])
624
+ async function putBack(gh, projectId, field, before, rename = new Map()) {
625
+ for (const [itemId, name] of before) {
626
+ const o = field.options.find(x => x.name === (rename.get(name) ?? name))
627
+ if (o) await gh.setSelect(projectId, itemId, field.id, o.id)
628
+ }
629
+ }
630
+
631
+ // The board's columns, as GitHub's Status options; every item keeps its column.
632
+ async function pushColumns(gh, project, field, items, boardId) {
633
+ const mine = ctx.statusRows(boardId)
634
+ const byOption = new Map(mine.filter(s => s.gh_option).map(s => [s.gh_option, s]))
635
+ const colorOf = s => field.options.find(o => o.id === s.gh_option)?.color ?? OPTION_COLOR[s.category] ?? 'GRAY'
636
+ const next = await gh.setOptions(field.id, mine.map(s => ({ name: s.name, color: colorOf(s), description: '' })))
637
+ // (Renamed here: its old name there is its new one.)
638
+ const rename = new Map(field.options.filter(o => byOption.has(o.id)).map(o => [o.name, byOption.get(o.id).name]))
639
+ inTx(() => {
640
+ for (const s of mine) db.prepare('UPDATE board_statuses SET gh_option = ? WHERE id = ?').run(next.options.find(o => o.name === s.name)?.id ?? null, s.id)
641
+ db.prepare('UPDATE board_github SET columns_dirty = 0 WHERE board_id = ?').run(boardId)
642
+ seenColumns(boardId, next)
643
+ })
644
+ await putBack(gh, project.id, next, valuesOf(items, field), rename)
645
+ // (What agreed before still does: the option ids changed, not the columns.)
646
+ for (const l of links(boardId)) {
647
+ const synced = JSON.parse(l.synced)
648
+ const s = mine.find(x => x.gh_option === synced.status)
649
+ if (s) { synced.status = next.options.find(o => o.name === s.name)?.id ?? null; db.prepare('UPDATE task_github SET synced = ? WHERE task_seq = ?').run(JSON.stringify(synced), l.task_seq) }
650
+ }
651
+ }
652
+
653
+ // An item of GitHub's that has no task yet: a task now (nobody told).
654
+ function importItem(board, item, fields) {
655
+ const g = theirs(item, fields)
656
+ const p = { title: g.title || '(untitled)', description: g.body || null }
657
+ const s = ctx.statusRows(board.id).find(x => x.gh_option && x.gh_option === g.status)
658
+ if (s) p.status = s.id
659
+ if (g.type) p.type = typeId(board.id, typeThere(item, fields))
660
+ if (g.labels) p.labels = labelsThere(item).map(n => labelId(board.id, n)).filter(Boolean)
661
+ let assignee = null
662
+ if (g.agent) { try { assignee = ctx.checkAssignee(board.id, { kind: 'session', id: g.agent }) } catch {} }
663
+ applying++
664
+ try {
665
+ const seq = inTx(() => {
666
+ const seq = ctx.createTask(board, p, FROM, { assignee })
667
+ const t = ctx.taskRow(seq)
668
+ // (Closed there, but in a column that isn't: in one that is.)
669
+ if (g.closed && g.closed !== 'OPEN' && !['done', 'closed'].includes(categoryOf(ctx.statusRow(t.status_id)))) {
670
+ const to = columnFor(board.id, g.closed)
671
+ if (to) db.prepare('UPDATE tasks SET status_id = ? WHERE seq = ?').run(to, seq)
672
+ }
673
+ const c = item.content
674
+ db.prepare('INSERT INTO task_github (task_seq, board_id, item_id, issue_id, draft_id, number, repo, url, synced) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)')
675
+ .run(seq, board.id, item.id, c.__typename === 'Issue' ? c.id : null, c.__typename === 'DraftIssue' ? c.id : null, c.number ?? null, c.repository?.nameWithOwner ?? null, c.url ?? null, JSON.stringify(g))
676
+ return seq
677
+ })
678
+ ctx.changedTask(seq)
679
+ return seq
680
+ } finally { applying-- }
681
+ }
682
+ function columnFor(boardId, closed) {
683
+ const all = ctx.statusRows(boardId)
684
+ const cat = closed === 'NOT_PLANNED' ? 'closed' : closed === 'COMPLETED' ? 'done' : null
685
+ return (cat ? all.find(s => s.category === cat) ?? all.find(s => s.category === 'done') : all.find(s => ACTIVE.includes(s.category)))?.id ?? null
686
+ }
687
+ function typeId(boardId, name) {
688
+ const hit = ctx.typeRows(boardId).find(t => t.name.toLowerCase() === name.toLowerCase())
689
+ if (hit) return hit.id
690
+ if (ctx.typeRows(boardId).length >= MAX.types) return null
691
+ return Number(db.prepare("INSERT INTO board_types (board_id, name, color, position) VALUES (?, ?, 'gray', (SELECT COALESCE(MAX(position), 0) + 1 FROM board_types WHERE board_id = ?))").run(boardId, name.slice(0, MAX.name), boardId).lastInsertRowid)
692
+ }
693
+ function labelId(boardId, name) {
694
+ const hit = ctx.labelRows(boardId).find(l => l.name.toLowerCase() === name.toLowerCase())
695
+ if (hit) return hit.id
696
+ if (ctx.labelRows(boardId).length >= MAX.labels) return null
697
+ return Number(db.prepare("INSERT INTO board_labels (board_id, name, color, position) VALUES (?, ?, 'gray', (SELECT COALESCE(MAX(position), 0) + 1 FROM board_labels WHERE board_id = ?))").run(boardId, name.slice(0, MAX.name), boardId).lastInsertRowid)
698
+ }
699
+
700
+ // A change from GitHub, made here as GitHub's (pending for any agent it gives the task to).
701
+ function applyHere(seq, p, item, assignee) {
702
+ applying++
703
+ try {
704
+ inTx(() => ctx.updateTask(seq, p, FROM, { assignee, human: true }))
705
+ ctx.changedTask(seq)
706
+ } catch (err) { log(`GitHub change to task ${seq} not applied: ${err.message}`) } finally { applying-- }
707
+ }
708
+
709
+ async function reconcile(gh, c, board, link, item, fields, byIssue) {
710
+ let t = ctx.taskRow(link.task_seq)
711
+ if (!t) return
712
+ const parentLink = t.parent_seq ? linkOf(t.parent_seq) : null
713
+ const synced = JSON.parse(link.synced)
714
+ const prefer = synced.prefer // (back from the trash: one side's word, whatever the other says)
715
+ delete synced.prefer
716
+ // (People GitHub wouldn't assign to it: not its business. Taken off the task, forgotten.)
717
+ const refused = (synced.refused ?? []).filter(l => split(peopleLogins(t.seq)).includes(l))
718
+ if (refused.length) synced.refused = refused; else delete synced.refused
719
+ const here = ours(t, t.parent_seq ? parentLink?.issue_id ?? 'unpublished' : null, refused)
720
+ const there = theirs(item, fields)
721
+ const keys = Object.keys(there) // (a draft has no state, labels or parent)
722
+ const theirsAt = Math.max(Date.parse(item.updatedAt) || 0, Date.parse(item.content.updatedAt) || 0)
723
+ const toHere = [], toThere = []
724
+ for (const k of keys) {
725
+ if (here[k] === there[k]) { synced[k] = there[k]; continue }
726
+ if (k === 'parent' && here[k] === 'unpublished') continue // (its parent isn't on GitHub yet)
727
+ if (prefer) { (prefer === 'there' ? toHere : toThere).push(k); continue }
728
+ const hereChanged = here[k] !== synced[k], thereChanged = there[k] !== synced[k]
729
+ if (thereChanged && (!hereChanged || theirsAt > t.updated_at)) toHere.push(k)
730
+ else toThere.push(k)
731
+ }
732
+ // GitHub's changes, here.
733
+ if (toHere.length) {
734
+ const p = {}
735
+ let assignee
736
+ for (const k of toHere) {
737
+ if (k === 'title') p.title = there.title || t.title
738
+ if (k === 'body') p.description = there.body
739
+ if (k === 'status') { const s = ctx.statusRows(board.id).find(x => x.gh_option && x.gh_option === there.status); if (s) p.status = s.id }
740
+ if (k === 'type') p.type = there.type ? typeId(board.id, typeThere(item, fields)) : null
741
+ if (k === 'labels') p.labels = labelsThere(item).map(n => labelId(board.id, n)).filter(Boolean)
742
+ if (k === 'parent') p.parent = there.parent ? byIssue.get(there.parent) ?? null : null
743
+ if (k === 'people') {
744
+ // (Those GitHub can't have stay: people without a GitHub user, or one it wouldn't assign.)
745
+ const by = loginsOf()
746
+ const ids = new Map([...by].map(([id, l]) => [l, id]))
747
+ const keep = ctx.peopleOf(t.seq).filter(id => !by.has(id) || refused.includes(by.get(id)))
748
+ p.people = [...new Set([...keep, ...split(there.people).map(l => ids.get(l)).filter(Boolean)])].slice(0, MAX.people ?? 10)
749
+ }
750
+ if (k === 'agent') {
751
+ if (!there.agent) assignee = t.assignee_kind === 'session' ? null : undefined
752
+ else { try { assignee = ctx.checkAssignee(board.id, { kind: 'session', id: there.agent }) } catch {} }
753
+ }
754
+ }
755
+ // (Closed or opened there: a column that says so, unless its column came too.)
756
+ if (toHere.includes('closed')) {
757
+ const target = ctx.statusRow(p.status ?? t.status_id)
758
+ const fits = there.closed === 'OPEN' ? !['done', 'closed'].includes(target?.category) : target?.category === (there.closed === 'NOT_PLANNED' ? 'closed' : 'done')
759
+ if (!fits) p.status = columnFor(board.id, there.closed) ?? p.status
760
+ }
761
+ applyHere(t.seq, p, item, assignee)
762
+ t = ctx.taskRow(t.seq)
763
+ for (const k of toHere) synced[k] = there[k]
764
+ // (What that changed besides, such as the column a closed issue took here: there too.)
765
+ const after = ours(t, t.parent_seq ? linkOf(t.parent_seq)?.issue_id ?? 'unpublished' : null, refused)
766
+ for (const k of keys) if (!toHere.includes(k) && !toThere.includes(k) && after[k] !== there[k] && after[k] !== 'unpublished') toThere.push(k)
767
+ }
768
+ // Ours, there.
769
+ if (toThere.length) {
770
+ const now = ours(t, t.parent_seq ? linkOf(t.parent_seq)?.issue_id ?? null : null, refused)
771
+ const issue = link.issue_id
772
+ if (link.draft_id && (toThere.includes('title') || toThere.includes('body'))) await gh.updateDraft(link.draft_id, { title: now.title, body: now.body })
773
+ if (issue && (toThere.includes('title') || toThere.includes('body'))) await gh.updateIssue(issue, { title: now.title, body: now.body })
774
+ if (toThere.includes('status') && now.status) await gh.setSelect(c.project_id, link.item_id, fields.status.id, now.status)
775
+ for (const [k, f] of [['agent', fields.agent], ['type', fields.type]]) {
776
+ if (!toThere.includes(k) || !f) continue
777
+ await gh.setSelect(c.project_id, link.item_id, f.id, now[k] ? f.options.find(o => o.name.toLowerCase() === now[k].toLowerCase())?.id ?? null : null)
778
+ }
779
+ if (issue && toThere.includes('closed')) {
780
+ if (now.closed === 'OPEN') await gh.reopenIssue(issue)
781
+ else { if (there.closed !== 'OPEN') await gh.reopenIssue(issue); await gh.closeIssue(issue, now.closed) }
782
+ }
783
+ if (issue && toThere.includes('labels') && link.repo === c.repo) {
784
+ const repoLabels = (await gh.repository(parseRepo(c.repo))).labels
785
+ await gh.updateIssue(issue, { labelIds: await labelIdsThere(gh, c, repoLabels, now.labels) })
786
+ }
787
+ if (issue && toThere.includes('parent')) {
788
+ if (now.parent) await gh.setParent(now.parent, issue)
789
+ else if (there.parent) await gh.removeParent(there.parent, issue)
790
+ }
791
+ if (issue && toThere.includes('people')) {
792
+ const want = split(now.people), have = split(there.people)
793
+ const add = want.filter(l => !have.includes(l)), remove = have.filter(l => !want.includes(l))
794
+ if (remove.length) await gh.removeAssignees(issue, (item.content.assignees?.nodes ?? []).filter(n => remove.includes(n.login.toLowerCase())).map(n => n.id))
795
+ if (add.length) synced.refused = [...new Set([...refused, ...await assign(gh, issue, add)])]
796
+ }
797
+ for (const k of toThere) synced[k] = now[k]
798
+ if (synced.refused?.length) synced.people = split(synced.people).filter(l => !synced.refused.includes(l)).join('\n')
799
+ }
800
+ db.prepare('UPDATE task_github SET synced = ? WHERE task_seq = ?').run(JSON.stringify(synced), t.seq)
801
+ }
802
+
803
+ // People onto an issue; who GitHub wouldn't take (no such user, or no access to the repository).
804
+ async function assign(gh, issue, logins) {
805
+ const ids = []
806
+ for (const l of logins) { const id = await userIdOf(gh, l); if (id) ids.push(id) }
807
+ const after = ids.length ? new Set((await gh.addAssignees(issue, ids)).map(l => l.toLowerCase())) : new Set()
808
+ const refused = logins.filter(l => !after.has(l))
809
+ if (refused.length) log(`GitHub wouldn't assign ${refused.join(', ')}: they need access to the repository`)
810
+ return refused
811
+ }
812
+
813
+ async function labelIdsThere(gh, c, repoLabels, names) {
814
+ const ids = []
815
+ for (const name of names ? names.split('\n') : []) {
816
+ let l = repoLabels.find(x => x.name.toLowerCase() === name.toLowerCase())
817
+ if (!l) {
818
+ const mine = ctx.labelRows(c.board_id).find(x => x.name.toLowerCase() === name.toLowerCase())
819
+ l = await gh.createLabel(c.repo_id, mine?.name ?? name, LABEL_HEX[mine?.color] ?? LABEL_HEX.gray)
820
+ repoLabels.push(l)
821
+ }
822
+ ids.push(l.id)
823
+ }
824
+ return ids
825
+ }
826
+
827
+ // A task of ours, as an issue of the board's repository in the project.
828
+ async function publish(gh, c, project, fields, t, repoLabels) {
829
+ if (!t || linkOf(t.seq)) return
830
+ const parentIssue = t.parent_seq ? linkOf(t.parent_seq)?.issue_id ?? null : null
831
+ const now = ours(t, parentIssue)
832
+ const want = split(now.people)
833
+ const ids = []
834
+ for (const l of want) { const id = await userIdOf(gh, l); if (id) ids.push(id) }
835
+ const issue = await gh.createIssue({ repositoryId: c.repo_id, title: now.title, body: now.body, labelIds: await labelIdsThere(gh, c, repoLabels, now.labels), parentIssueId: parentIssue ?? undefined, assigneeIds: ids })
836
+ // (Linked at once, before it is in the project: a failure from here on is put right on the next sync, never made twice.)
837
+ const got = new Set(issue.assignees.map(l => l.toLowerCase()))
838
+ const refused = want.filter(l => !got.has(l))
839
+ const synced = { ...now, status: null, agent: null, type: null, closed: 'OPEN', people: want.filter(l => got.has(l)).join('\n'), ...(refused.length ? { refused } : {}) }
840
+ if (refused.length) log(`GitHub wouldn't assign ${refused.join(', ')} to ${c.repo}#${issue.number}: they need access to the repository`)
841
+ db.prepare('INSERT INTO task_github (task_seq, board_id, item_id, issue_id, number, repo, url, synced) VALUES (?, ?, ?, ?, ?, ?, ?, ?)')
842
+ .run(t.seq, c.board_id, `pending:${issue.id}`, issue.id, issue.number, c.repo, issue.url, JSON.stringify(synced))
843
+ const itemId = await gh.addItem(project.id, issue.id)
844
+ db.prepare('UPDATE task_github SET item_id = ? WHERE task_seq = ?').run(itemId, t.seq)
845
+ ctx.event(t.seq, FROM, 'changed', { github: `${c.repo}#${issue.number}` })
846
+ ctx.changedTask(t.seq)
847
+ if (now.status) { await gh.setSelect(project.id, itemId, fields.status.id, now.status); synced.status = now.status }
848
+ for (const [k, f] of [['agent', fields.agent], ['type', fields.type]]) {
849
+ const o = now[k] && f?.options.find(x => x.name.toLowerCase() === now[k].toLowerCase())
850
+ if (o) { await gh.setSelect(project.id, itemId, f.id, o.id); synced[k] = now[k] }
851
+ }
852
+ if (now.closed !== 'OPEN') { await gh.closeIssue(issue.id, now.closed); synced.closed = now.closed }
853
+ db.prepare('UPDATE task_github SET synced = ? WHERE task_seq = ?').run(JSON.stringify(synced), t.seq)
854
+ }
855
+
856
+ // Comments: GitHub's that are new here, and ours that aren't there yet.
857
+ // What a comment says, as GitHub has it (ours without the signature they were sent with).
858
+ const SIGNED = /^\*\*[^*\n]{1,200}\*\* \(Pisha\):\n\n/
859
+ const textOf = cm => cleanText(String(cm.body ?? '').replace(/\r\n/g, '\n').replace(SIGNED, '')).trim().slice(0, MAX.comment)
860
+ // GitHub's comments on the issue: new ones here, edited ones edited, deleted ones no longer shown.
861
+ function commentsChanged(link, list) {
862
+ const there = new Map(list.nodes.filter(cm => cm?.id).map(cm => [cm.id, cm]))
863
+ // (Of the latest 50 only: one older than those is still there, as far as can be told.)
864
+ const oldest = Math.min(...[...there.values()].map(cm => Date.parse(cm.createdAt) || 0))
865
+ const whole = (list.totalCount ?? there.size) <= there.size
866
+ let changed = false
867
+ for (const c of db.prepare('SELECT * FROM task_comments WHERE task_seq = ? AND gh_id IS NOT NULL AND deleted_at IS NULL').all(link.task_seq)) {
868
+ const cm = there.get(c.gh_id)
869
+ if (!cm) {
870
+ if (whole || c.created_at >= oldest) { db.prepare('UPDATE task_comments SET deleted_at = ? WHERE id = ?').run(Date.now(), c.id); changed = true }
871
+ continue
872
+ }
873
+ const text = textOf(cm)
874
+ if (text && text !== c.text) { db.prepare('UPDATE task_comments SET text = ?, edited_at = ? WHERE id = ?').run(text, Date.now(), c.id); changed = true }
875
+ }
876
+ return changed
877
+ }
878
+ async function comments(gh, link, item) {
879
+ const list = item.content.comments
880
+ if (list?.nodes && item !== NO_COMMENTS && commentsChanged(link, list)) { applying++; try { ctx.changedTask(link.task_seq) } finally { applying-- } }
881
+ for (const cm of list?.nodes ?? []) {
882
+ if (!cm?.id || db.prepare('SELECT 1 FROM task_comments WHERE gh_id = ?').get(cm.id)) continue
883
+ const login = cm.author?.login ?? 'ghost'
884
+ const text = textOf(cm)
885
+ if (!text) continue
886
+ if (db.prepare('SELECT COUNT(*) n FROM task_comments WHERE task_seq = ? AND deleted_at IS NULL').get(link.task_seq).n >= MAX.comments) break
887
+ db.prepare('INSERT INTO task_comments (task_seq, author, text, created_at, gh_id) VALUES (?, ?, ?, ?, ?)')
888
+ .run(link.task_seq, JSON.stringify({ kind: 'github', id: login, name: `@${login}` }), text, Date.parse(cm.createdAt) || Date.now(), cm.id)
889
+ applying++
890
+ try { ctx.changedTask(link.task_seq) } finally { applying-- }
891
+ }
892
+ for (const cm of unsent(link.task_seq)) {
893
+ const author = JSON.parse(cm.author)
894
+ const id = await gh.comment(link.issue_id, `**${author.kind === 'session' ? author.id : author.name}** (Pisha):\n\n${cm.text}`)
895
+ db.prepare('UPDATE task_comments SET gh_id = ? WHERE id = ?').run(id, cm.id)
896
+ }
897
+ }
898
+
899
+ // --- what boards.js tells it -------------------------------------------------------------
900
+ // Into the trash here: out of the project there, its issue closed as not planned.
901
+ // --- pull requests -----------------------------------------------------------------
902
+ const PR_STATE = pr => (pr.merged || pr.state === 'MERGED' ? 'merged' : pr.state === 'CLOSED' ? 'closed' : pr.isDraft ? 'draft' : 'open')
903
+ const REVIEW = { APPROVED: 'approved', CHANGES_REQUESTED: 'changes', REVIEW_REQUIRED: 'required' }
904
+ const prsOf = seq => db.prepare('SELECT number, title, url, state, review, author FROM task_prs WHERE task_seq = ? ORDER BY number DESC').all(seq)
905
+ // The tasks of this board a pull request names (SQ-12 in its title, branch or text), or whose issue it closes.
906
+ function tasksOfPr(pr, boardId, byIssue) {
907
+ const id = ctx.prefix().replace(/[^A-Za-z0-9]/g, '')
908
+ const re = new RegExp(`(?<![A-Za-z0-9])${id}-(\\d{1,9})(?![0-9])`, 'gi')
909
+ const seqs = new Set()
910
+ for (const text of [pr.title, pr.headRefName, pr.body]) for (const m of String(text ?? '').matchAll(re)) seqs.add(Number(m[1]))
911
+ for (const n of pr.closingIssuesReferences?.nodes ?? []) { const seq = n && byIssue.get(n.id); if (seq) seqs.add(seq) }
912
+ return [...seqs].filter(seq => ctx.taskRow(seq)?.board_id === boardId)
913
+ }
914
+ // The pull requests changed since the last time (the latest ones, the first time).
915
+ async function pullRequests(gh, c, board) {
916
+ const first = !c.prs_at
917
+ const prs = await gh.pullRequests(parseRepo(c.repo), c.prs_at)
918
+ const from = c.prs_from ?? Date.now()
919
+ const byIssue = new Map(links(board.id).filter(l => l.issue_id).map(l => [l.issue_id, l.task_seq]))
920
+ const moves = new Map() // task -> the pull request that, merged, takes it to done
921
+ const touched = new Set()
922
+ for (const pr of prs.slice().reverse()) { // (the oldest first: the latest word last)
923
+ const state = PR_STATE(pr), review = REVIEW[pr.reviewDecision] ?? null
924
+ const seqs = tasksOfPr(pr, board.id, byIssue)
925
+ const had = new Map(db.prepare('SELECT task_seq, state FROM task_prs WHERE pr_id = ? AND board_id = ?').all(pr.id, board.id).map(r => [r.task_seq, r.state]))
926
+ inTx(() => {
927
+ // (One that no longer names a task: off it.)
928
+ for (const seq of had.keys()) if (!seqs.includes(seq)) { db.prepare('DELETE FROM task_prs WHERE pr_id = ? AND task_seq = ?').run(pr.id, seq); touched.add(seq) }
929
+ for (const seq of seqs) {
930
+ db.prepare(`INSERT INTO task_prs (task_seq, pr_id, board_id, number, title, url, state, review, author, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
931
+ ON CONFLICT(task_seq, pr_id) DO UPDATE SET number = excluded.number, title = excluded.title, url = excluded.url, state = excluded.state, review = excluded.review, author = excluded.author, updated_at = excluded.updated_at`)
932
+ .run(seq, pr.id, board.id, pr.number, String(pr.title ?? '').slice(0, 300), pr.url, state, review, pr.author?.login ?? null, Date.parse(pr.updatedAt) || Date.now())
933
+ touched.add(seq)
934
+ const before = had.get(seq)
935
+ // (In the history: linked, and merged or closed; not the first time, for the old ones.)
936
+ const news = !before ? (first ? null : 'linked') : before !== state && ['merged', 'closed'].includes(state) ? state : null
937
+ if (news) ctx.event(seq, FROM, 'pr', { number: pr.number, title: String(pr.title ?? '').slice(0, 300), url: pr.url, state, ...(news === 'linked' ? { linked: true } : {}) })
938
+ if (state === 'merged' && before !== 'merged' && (Date.parse(pr.mergedAt) || 0) >= from) moves.set(seq, pr.number)
939
+ }
940
+ })
941
+ }
942
+ const latest = prs.reduce((m, pr) => (Date.parse(pr.updatedAt) > Date.parse(m ?? 0) ? pr.updatedAt : m), c.prs_at)
943
+ db.prepare('UPDATE board_github SET prs_at = ?, prs_from = ? WHERE board_id = ?').run(latest ?? new Date(from).toISOString(), from, board.id)
944
+ // Merged: to the first done column, unless it is done or cancelled already (or the board says not to).
945
+ if (conn(board.id)?.merge_moves) {
946
+ const done = ctx.statusRows(board.id).find(s => s.category === 'done')
947
+ for (const seq of moves.keys()) {
948
+ const t = ctx.taskRow(seq)
949
+ if (done && t && !['done', 'closed'].includes(categoryOf(ctx.statusRow(t.status_id)))) applyHere(seq, { status: done.id })
950
+ }
951
+ }
952
+ for (const seq of touched) ctx.changedTask(seq)
953
+ }
954
+
955
+ function taskDeleted(t) {
956
+ lastTask.delete(t.seq)
957
+ const l = linkOf(t.seq)
958
+ if (!l || l.item_id.startsWith('trashed:')) return
959
+ db.prepare('INSERT INTO github_outbox (board_id, item_id, issue_id, task_seq) VALUES (?, ?, ?, ?)').run(t.board_id, l.item_id, l.issue_id, t.seq)
960
+ if (l.issue_id) db.prepare("UPDATE task_github SET item_id = 'trashed:' || task_seq WHERE task_seq = ?").run(t.seq)
961
+ else db.prepare('DELETE FROM task_github WHERE task_seq = ?').run(t.seq) // (a draft is gone with its item: restored, it is published again)
962
+ }
963
+ // Out of the trash here: there again as it was (if it never left, nothing to do), ours the word.
964
+ function taskRestored(seq) {
965
+ const l = linkOf(seq)
966
+ if (!l) return
967
+ const o = db.prepare('SELECT * FROM github_outbox WHERE task_seq = ?').get(seq)
968
+ if (o) {
969
+ db.prepare('DELETE FROM github_outbox WHERE id = ?').run(o.id)
970
+ db.prepare('UPDATE task_github SET item_id = ? WHERE task_seq = ?').run(o.item_id, seq)
971
+ return
972
+ }
973
+ db.prepare("UPDATE task_github SET item_id = 'pending:' || issue_id, synced = ? WHERE task_seq = ?").run(JSON.stringify({ prefer: 'here' }), seq)
974
+ }
975
+ function columnsChanged(boardId) {
976
+ if (conn(boardId)) db.prepare('UPDATE board_github SET columns_dirty = 1 WHERE board_id = ?').run(boardId)
977
+ }
978
+
979
+ return { connect, disconnect, setMergeMoves, prsOf, view, touch, syncBoard, watch, fresh, freshTask, taskDeleted, taskRestored, columnsChanged, linkOf, FROM }
980
+ }