@otea/cli 0.0.1 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (243) hide show
  1. package/LICENSE +661 -0
  2. package/README.es.md +151 -0
  3. package/README.md +251 -3
  4. package/THIRD_PARTY_NOTICES.md +114 -0
  5. package/bin/otea.mjs +28 -0
  6. package/dist/app/agent-detail.js +26 -0
  7. package/dist/app/agent-draft.js +429 -0
  8. package/dist/app/agent-prompts.js +52 -0
  9. package/dist/app/agents.js +77 -0
  10. package/dist/app/asking.js +43 -0
  11. package/dist/app/board-archive.js +243 -0
  12. package/dist/app/board-migration.js +272 -0
  13. package/dist/app/boards.js +870 -0
  14. package/dist/app/branch-owner.js +48 -0
  15. package/dist/app/brief.js +53 -0
  16. package/dist/app/choices.js +61 -0
  17. package/dist/app/collections.js +101 -0
  18. package/dist/app/context.js +1 -0
  19. package/dist/app/crop.js +56 -0
  20. package/dist/app/devices.js +62 -0
  21. package/dist/app/draft-request.js +82 -0
  22. package/dist/app/events.js +12 -0
  23. package/dist/app/evidence.js +287 -0
  24. package/dist/app/gates.js +610 -0
  25. package/dist/app/guide.js +37 -0
  26. package/dist/app/home.js +145 -0
  27. package/dist/app/init-boards.js +36 -0
  28. package/dist/app/intake.js +25 -0
  29. package/dist/app/item-search.js +141 -0
  30. package/dist/app/items.js +318 -0
  31. package/dist/app/keep-waiting.js +44 -0
  32. package/dist/app/land-order.js +107 -0
  33. package/dist/app/language.js +52 -0
  34. package/dist/app/launcher.js +56 -0
  35. package/dist/app/lease-take.js +54 -0
  36. package/dist/app/leases.js +86 -0
  37. package/dist/app/machine.js +39 -0
  38. package/dist/app/merged.js +89 -0
  39. package/dist/app/migrate.js +171 -0
  40. package/dist/app/next.js +1637 -0
  41. package/dist/app/notes.js +319 -0
  42. package/dist/app/notify-targets.js +113 -0
  43. package/dist/app/opened.js +25 -0
  44. package/dist/app/owner-only.js +34 -0
  45. package/dist/app/performance.js +28 -0
  46. package/dist/app/phone.js +97 -0
  47. package/dist/app/presence.js +596 -0
  48. package/dist/app/preset-views.js +25 -0
  49. package/dist/app/presets.js +129 -0
  50. package/dist/app/priority.js +156 -0
  51. package/dist/app/profile.js +86 -0
  52. package/dist/app/project.js +247 -0
  53. package/dist/app/proofs.js +179 -0
  54. package/dist/app/questions.js +215 -0
  55. package/dist/app/reader-filter.js +58 -0
  56. package/dist/app/relations.js +164 -0
  57. package/dist/app/relay.js +98 -0
  58. package/dist/app/repos.js +176 -0
  59. package/dist/app/restart.js +92 -0
  60. package/dist/app/set-aside.js +64 -0
  61. package/dist/app/system-locale.js +6 -0
  62. package/dist/app/tailscale-cli.js +77 -0
  63. package/dist/app/tailscale-testing.js +41 -0
  64. package/dist/app/tailscale.js +177 -0
  65. package/dist/app/tips.js +30 -0
  66. package/dist/app/topics-everywhere.js +53 -0
  67. package/dist/app/topics.js +453 -0
  68. package/dist/app/undo.js +52 -0
  69. package/dist/app/validate.js +131 -0
  70. package/dist/app/watch.js +48 -0
  71. package/dist/cli/command.js +44 -0
  72. package/dist/cli/commands.js +3303 -0
  73. package/dist/cli/exit-codes.js +70 -0
  74. package/dist/cli/forge.js +176 -0
  75. package/dist/cli/format.js +340 -0
  76. package/dist/cli/gh.js +17 -0
  77. package/dist/cli/gitrepo.js +489 -0
  78. package/dist/cli/help.js +101 -0
  79. package/dist/cli/hooks.js +232 -0
  80. package/dist/cli/main.js +37 -0
  81. package/dist/cli/merged-outside.js +58 -0
  82. package/dist/cli/names.js +154 -0
  83. package/dist/cli/opener.js +21 -0
  84. package/dist/cli/owner.js +154 -0
  85. package/dist/cli/phone.js +221 -0
  86. package/dist/cli/ports.js +24 -0
  87. package/dist/cli/probe.js +18 -0
  88. package/dist/cli/run.js +246 -0
  89. package/dist/cli/serve-file.js +21 -0
  90. package/dist/cli/stats.js +55 -0
  91. package/dist/cli/version.js +3 -0
  92. package/dist/core/agent-guide.js +31 -0
  93. package/dist/core/agent-prompts.js +139 -0
  94. package/dist/core/authority.js +94 -0
  95. package/dist/core/board/analysis.js +86 -0
  96. package/dist/core/board/choices.js +100 -0
  97. package/dist/core/board/compile.js +362 -0
  98. package/dist/core/board/engine.js +523 -0
  99. package/dist/core/board/hints.js +46 -0
  100. package/dist/core/board/history.js +146 -0
  101. package/dist/core/board/ids.js +87 -0
  102. package/dist/core/board/joins.js +30 -0
  103. package/dist/core/board/mentions.js +68 -0
  104. package/dist/core/board/merged.js +18 -0
  105. package/dist/core/board/model.js +135 -0
  106. package/dist/core/board/next.js +1116 -0
  107. package/dist/core/board/notes.js +298 -0
  108. package/dist/core/board/performance.js +218 -0
  109. package/dist/core/board/plan.js +299 -0
  110. package/dist/core/board/problems.js +232 -0
  111. package/dist/core/board/proofs.js +84 -0
  112. package/dist/core/board/questions.js +114 -0
  113. package/dist/core/board/reading.js +220 -0
  114. package/dist/core/board/readings.js +534 -0
  115. package/dist/core/board/schema.js +335 -0
  116. package/dist/core/board/shape-words.js +179 -0
  117. package/dist/core/board/template-words.js +23 -0
  118. package/dist/core/board/templates-catalogue.js +965 -0
  119. package/dist/core/board/templates-coverage.js +261 -0
  120. package/dist/core/board/templates-flows.js +779 -0
  121. package/dist/core/board/templates.js +586 -0
  122. package/dist/core/brief.js +93 -0
  123. package/dist/core/diagram.js +80 -0
  124. package/dist/core/errors.js +12 -0
  125. package/dist/core/evidence.js +33 -0
  126. package/dist/core/fields.js +129 -0
  127. package/dist/core/hierarchy.js +30 -0
  128. package/dist/core/icons.js +181 -0
  129. package/dist/core/image-crop.js +166 -0
  130. package/dist/core/item.js +49 -0
  131. package/dist/core/lease.js +31 -0
  132. package/dist/core/modules.js +318 -0
  133. package/dist/core/notify/planner.js +117 -0
  134. package/dist/core/notify/signals.js +66 -0
  135. package/dist/core/notify/text.js +60 -0
  136. package/dist/core/path-key.js +22 -0
  137. package/dist/core/placement.js +161 -0
  138. package/dist/core/preset-labels.js +66 -0
  139. package/dist/core/preset-notes.js +109 -0
  140. package/dist/core/preset.js +541 -0
  141. package/dist/core/profile.js +55 -0
  142. package/dist/core/project-id.js +20 -0
  143. package/dist/core/refusal.js +1 -0
  144. package/dist/core/relations.js +208 -0
  145. package/dist/core/repo.js +54 -0
  146. package/dist/core/samples.js +161 -0
  147. package/dist/core/search-words.js +68 -0
  148. package/dist/core/test-report.js +120 -0
  149. package/dist/core/time.js +8 -0
  150. package/dist/core/validation.js +60 -0
  151. package/dist/core/views.js +171 -0
  152. package/dist/core/workflow.js +51 -0
  153. package/dist/mcp/commands.js +101 -0
  154. package/dist/mcp/server.js +239 -0
  155. package/dist/mcp/words.js +95 -0
  156. package/dist/server/boards.js +232 -0
  157. package/dist/server/changes.js +42 -0
  158. package/dist/server/diff-tip.js +83 -0
  159. package/dist/server/drift.js +87 -0
  160. package/dist/server/errors.js +87 -0
  161. package/dist/server/evidence.js +82 -0
  162. package/dist/server/hosts.js +6 -0
  163. package/dist/server/hub.js +98 -0
  164. package/dist/server/lan-access.js +62 -0
  165. package/dist/server/lan.js +164 -0
  166. package/dist/server/listen.js +70 -0
  167. package/dist/server/notifier.js +156 -0
  168. package/dist/server/notify-api.js +151 -0
  169. package/dist/server/pairing.js +124 -0
  170. package/dist/server/projects.js +191 -0
  171. package/dist/server/push.js +199 -0
  172. package/dist/server/server.js +960 -0
  173. package/dist/server/session.js +43 -0
  174. package/dist/server/stream.js +36 -0
  175. package/dist/server/test-push.js +38 -0
  176. package/dist/server/token.js +37 -0
  177. package/dist/server/transports.js +54 -0
  178. package/dist/server/ui.js +44 -0
  179. package/dist/server/writes.js +361 -0
  180. package/dist/server/wrong-address.js +36 -0
  181. package/dist/store/boards.js +111 -0
  182. package/dist/store/database.js +45 -0
  183. package/dist/store/machine.js +77 -0
  184. package/dist/store/migrations.js +493 -0
  185. package/dist/store/queries.js +585 -0
  186. package/dist/store/registry.js +72 -0
  187. package/package.json +72 -4
  188. package/presets/architecture/playbook.md +69 -0
  189. package/presets/architecture/preset.yaml +80 -0
  190. package/presets/architecture/samples.yaml +23 -0
  191. package/presets/bug-triage/playbook.md +129 -0
  192. package/presets/bug-triage/preset.yaml +127 -0
  193. package/presets/bug-triage/samples/wall-slide-after.png +0 -0
  194. package/presets/bug-triage/samples/wall-slide-before.png +0 -0
  195. package/presets/bug-triage/samples.yaml +72 -0
  196. package/presets/change/playbook.md +115 -0
  197. package/presets/change/preset.yaml +141 -0
  198. package/presets/change/samples.yaml +62 -0
  199. package/presets/review/playbook.md +51 -0
  200. package/presets/review/preset.yaml +62 -0
  201. package/presets/review/samples.yaml +27 -0
  202. package/presets/tasks/playbook.md +78 -0
  203. package/presets/tasks/preset.yaml +61 -0
  204. package/presets/tasks/samples.yaml +46 -0
  205. package/schemas/board.schema.json +764 -0
  206. package/ui/dist/THIRD_PARTY_NOTICES.md +114 -0
  207. package/ui/dist/assets/dm-mono-latin-400-normal--0xN8mdc.woff +0 -0
  208. package/ui/dist/assets/dm-mono-latin-400-normal-4GdczIuU.woff2 +0 -0
  209. package/ui/dist/assets/dm-mono-latin-500-normal-CN8Miw6E.woff +0 -0
  210. package/ui/dist/assets/dm-mono-latin-500-normal-DRMDZjhP.woff2 +0 -0
  211. package/ui/dist/assets/dm-mono-latin-ext-400-normal-1aZr6b2b.woff +0 -0
  212. package/ui/dist/assets/dm-mono-latin-ext-400-normal-C2zvOubV.woff2 +0 -0
  213. package/ui/dist/assets/dm-mono-latin-ext-500-normal-BtRyHRi6.woff2 +0 -0
  214. package/ui/dist/assets/dm-mono-latin-ext-500-normal-Dw3M13d8.woff +0 -0
  215. package/ui/dist/assets/index-C3OzJope.js +103 -0
  216. package/ui/dist/assets/index-COdEjckQ.css +1 -0
  217. package/ui/dist/assets/newsreader-latin-ext-opsz-italic-CSPGnFdO.woff2 +0 -0
  218. package/ui/dist/assets/newsreader-latin-ext-opsz-normal-BQn1nviT.woff2 +0 -0
  219. package/ui/dist/assets/newsreader-latin-opsz-italic-kJKFiXvB.woff2 +0 -0
  220. package/ui/dist/assets/newsreader-latin-opsz-normal-s-izfB6B.woff2 +0 -0
  221. package/ui/dist/assets/newsreader-vietnamese-opsz-italic-DTr-ymY4.woff2 +0 -0
  222. package/ui/dist/assets/newsreader-vietnamese-opsz-normal-BjhtXyW2.woff2 +0 -0
  223. package/ui/dist/assets/pdf-YwugTw7Y.js +54 -0
  224. package/ui/dist/assets/pdf-engine-CkBopwck.js +1 -0
  225. package/ui/dist/assets/pdf-rELvHkft.js +56 -0
  226. package/ui/dist/assets/pdf.worker.min-B5Yc7dP4.mjs +27 -0
  227. package/ui/dist/assets/pdf.worker.min-B7U8ptvh.js +1 -0
  228. package/ui/dist/assets/pdf.worker.min-CIqJB0yW.mjs +28 -0
  229. package/ui/dist/assets/pdf.worker.min-UqOn5EDC.js +1 -0
  230. package/ui/dist/assets/schibsted-grotesk-latin-ext-wght-normal-hsMS0n0O.woff2 +0 -0
  231. package/ui/dist/assets/schibsted-grotesk-latin-wght-normal-Bb8VGrTG.woff2 +0 -0
  232. package/ui/dist/icons/apple-touch-icon.png +0 -0
  233. package/ui/dist/icons/otea-192.png +0 -0
  234. package/ui/dist/icons/otea-512.png +0 -0
  235. package/ui/dist/icons/otea-badge.png +0 -0
  236. package/ui/dist/icons/otea-maskable-512.png +0 -0
  237. package/ui/dist/index.html +25 -0
  238. package/ui/dist/manifest.webmanifest +24 -0
  239. package/ui/dist/otea-idle.svg +5 -0
  240. package/ui/dist/otea-working.svg +5 -0
  241. package/ui/dist/otea-yours-working.svg +5 -0
  242. package/ui/dist/otea-yours.svg +5 -0
  243. package/ui/dist/sw.js +1 -0
@@ -0,0 +1,243 @@
1
+ import { rmSync } from 'node:fs';
2
+ import { isClosed, positionOf } from '../core/board/engine.js';
3
+ import { DONE, SAME, stepById } from '../core/board/model.js';
4
+ import { stateName } from '../core/board/reading.js';
5
+ import { readDefinition } from '../core/board/schema.js';
6
+ import { OteaError } from '../core/errors.js';
7
+ import { activeLease } from '../core/lease.js';
8
+ import { deleteBoard, deleteDraft, findBoard, findDraft, findVersion, listBoards, setArchived, } from '../store/boards.js';
9
+ import { transaction } from '../store/database.js';
10
+ import { appendEvent, clearLease, deleteCollection, selectItems } from '../store/queries.js';
11
+ import { syncBoardPresets } from './boards.js';
12
+ import { evidenceFile } from './evidence.js';
13
+ import { systemClock } from './items.js';
14
+ import { forgetTopicItem } from './topics.js';
15
+ function definitionOf(ctx, row) {
16
+ const version = row.liveVersion === null ? undefined : findVersion(ctx.db, row.id, row.liveVersion);
17
+ if (version)
18
+ return readDefinition(version.definition);
19
+ const draft = findDraft(ctx.db, row.id);
20
+ return draft ? readDefinition(draft.definition) : undefined;
21
+ }
22
+ const nameOf = (ctx, row) => definitionOf(ctx, row)?.name ?? row.collection ?? row.id;
23
+ function requireRow(ctx, id) {
24
+ const row = findBoard(ctx.db, id);
25
+ if (!row)
26
+ throw new OteaError('not_found', `There is no board ${id}`);
27
+ return row;
28
+ }
29
+ function refuseBuiltin(ctx, row, act) {
30
+ if (!row.builtin)
31
+ return;
32
+ const board = nameOf(ctx, row);
33
+ throw new OteaError('forbidden', `${board} is the project's own board for requests: it cannot be ${act}`, {
34
+ kind: 'board_builtin',
35
+ board,
36
+ });
37
+ }
38
+ // The board `row` divides into, when it is another board.
39
+ function childOf(ctx, row) {
40
+ const split = definitionOf(ctx, row)?.split;
41
+ if (!split || split.board === SAME || split.board === row.id)
42
+ return undefined;
43
+ const child = findBoard(ctx.db, split.board);
44
+ return child && !child.builtin ? child : undefined;
45
+ }
46
+ // The board that divides into `row`, if one does.
47
+ function parentOf(ctx, row) {
48
+ return listBoards(ctx.db, { archived: true }).find((other) => other.id !== row.id && childOf(ctx, other)?.id === row.id);
49
+ }
50
+ function refuseChild(ctx, row, parent, act) {
51
+ const board = nameOf(ctx, row);
52
+ const name = nameOf(ctx, parent);
53
+ throw new OteaError('in_use', `${board} is the board ${name} divides into: ${act} ${name}, and ${board} goes with it`, { kind: 'board_split_child', board, parent: name });
54
+ }
55
+ const itemsOf = (ctx, row) => row.collection === null
56
+ ? []
57
+ : selectItems(ctx.db, { collection: row.collection, archived: true });
58
+ const isOpen = (state) => !isClosed(positionOf(state));
59
+ function group(ctx, row) {
60
+ const child = childOf(ctx, row);
61
+ return child ? [row, child] : [row];
62
+ }
63
+ export function archivePlan(ctx, id, now = systemClock) {
64
+ const at = now();
65
+ return {
66
+ boards: group(ctx, requireRow(ctx, id)).map((row) => {
67
+ const items = itemsOf(ctx, row);
68
+ return {
69
+ id: row.id,
70
+ name: nameOf(ctx, row),
71
+ items: items.length,
72
+ open: items.filter(({ state }) => isOpen(state)).length,
73
+ held: items.filter(({ lease }) => activeLease(lease, at)).length,
74
+ };
75
+ }),
76
+ };
77
+ }
78
+ function refuseArchived(ctx, row) {
79
+ if (row.archivedAt === null)
80
+ return;
81
+ const board = nameOf(ctx, row);
82
+ throw new OteaError('board_archived', `${board} is already archived`, {
83
+ kind: 'board_archived',
84
+ board,
85
+ });
86
+ }
87
+ export function archiveBoard(ctx, id, who, now = systemClock) {
88
+ const result = transaction(ctx.db, () => {
89
+ const row = requireRow(ctx, id);
90
+ refuseBuiltin(ctx, row, 'archived');
91
+ refuseArchived(ctx, row);
92
+ if (row.collection === null || row.liveVersion === null)
93
+ throw new OteaError('invalid_board', `${nameOf(ctx, row)} is not published: discard its draft instead`);
94
+ const parent = parentOf(ctx, row);
95
+ if (parent && parent.archivedAt === null)
96
+ refuseChild(ctx, row, parent, 'archive');
97
+ const at = now();
98
+ const boards = group(ctx, row).filter((each) => each.archivedAt === null);
99
+ for (const board of boards) {
100
+ for (const item of itemsOf(ctx, board)) {
101
+ if (!item.lease)
102
+ continue;
103
+ clearLease(ctx.db, item.id);
104
+ const lease = activeLease(item.lease, at);
105
+ if (!lease)
106
+ continue;
107
+ const data = { holder: lease.holder, cause: 'archive' };
108
+ appendEvent(ctx.db, { itemId: item.id, type: 'released', actor: who.by, at, data });
109
+ }
110
+ }
111
+ for (const board of boards)
112
+ setArchived(ctx.db, board.id, at);
113
+ return { archived: boards.map((board) => board.id) };
114
+ });
115
+ syncBoardPresets(ctx);
116
+ return result;
117
+ }
118
+ export function unarchiveBoard(ctx, id, _who, _now = systemClock) {
119
+ const result = transaction(ctx.db, () => {
120
+ const row = requireRow(ctx, id);
121
+ if (row.archivedAt === null) {
122
+ const board = nameOf(ctx, row);
123
+ throw new OteaError('invalid_board', `${board} is not archived`, {
124
+ kind: 'board_not_archived',
125
+ board,
126
+ });
127
+ }
128
+ const parent = parentOf(ctx, row);
129
+ if (parent && parent.archivedAt !== null)
130
+ refuseChild(ctx, row, parent, 'restore');
131
+ const boards = group(ctx, row).filter((each) => each.archivedAt !== null);
132
+ for (const board of boards)
133
+ setArchived(ctx.db, board.id, null);
134
+ return { restored: boards.map((board) => board.id) };
135
+ });
136
+ syncBoardPresets(ctx);
137
+ return result;
138
+ }
139
+ const same = (a, b) => a.trim().toLocaleLowerCase() === b.trim().toLocaleLowerCase();
140
+ export function deletePlan(ctx, id) {
141
+ const boards = group(ctx, requireRow(ctx, id)).map((row) => ({
142
+ id: row.id,
143
+ name: nameOf(ctx, row),
144
+ items: itemsOf(ctx, row).length,
145
+ archived: row.archivedAt !== null,
146
+ }));
147
+ const items = boards.reduce((sum, board) => sum + board.items, 0);
148
+ return { boards, items, confirm: items > 0 };
149
+ }
150
+ export function deleteBoardForever(project, id, input) {
151
+ const { db } = project;
152
+ const files = new Set();
153
+ const result = transaction(db, () => {
154
+ const row = requireRow(project, id);
155
+ refuseBuiltin(project, row, 'deleted');
156
+ const parent = parentOf(project, row);
157
+ if (parent)
158
+ refuseChild(project, row, parent, 'delete');
159
+ const boards = group(project, row);
160
+ let total = 0;
161
+ for (const board of boards) {
162
+ const items = itemsOf(project, board).length;
163
+ total += items;
164
+ if (items > 0 && board.archivedAt === null) {
165
+ const name = nameOf(project, board);
166
+ throw new OteaError('in_use', `${name} has ${items} item(s): archive it first, then delete it`, { kind: 'board_has_items', board: name, items });
167
+ }
168
+ }
169
+ const name = nameOf(project, row);
170
+ if (total > 0 && !same(input.confirm ?? '', name))
171
+ throw new OteaError('reason_required', `Deleting ${name} deletes ${total} item(s): type the board's name to confirm`, { kind: 'board_delete_confirm', board: name, items: total });
172
+ const at = new Date().toISOString();
173
+ for (const board of boards) {
174
+ // Archived first, so the board's append-only rows may go (store/migrations.ts).
175
+ setArchived(db, board.id, board.archivedAt ?? at);
176
+ const ids = itemsOf(project, board).map((item) => item.id);
177
+ for (const item of ids) {
178
+ const shas = db.prepare('SELECT sha256 FROM evidence WHERE item_id = ?').all(item);
179
+ for (const sha of shas)
180
+ files.add(String(sha.sha256));
181
+ db.prepare('DELETE FROM relations WHERE from_id = ? OR to_id = ?').run(item, item);
182
+ db.prepare('DELETE FROM evidence WHERE item_id = ?').run(item);
183
+ db.prepare('DELETE FROM events WHERE item_id = ?').run(item);
184
+ db.prepare('DELETE FROM item_priority WHERE item_id = ?').run(item);
185
+ forgetTopicItem(project, item, at);
186
+ db.prepare('DELETE FROM items WHERE id = ?').run(item);
187
+ }
188
+ deleteDraft(db, board.id);
189
+ db.prepare('DELETE FROM board_versions WHERE board_id = ?').run(board.id);
190
+ deleteBoard(db, board.id);
191
+ if (board.collection !== null)
192
+ deleteCollection(db, board.collection);
193
+ }
194
+ return { deleted: boards.map((board) => board.id) };
195
+ });
196
+ // A file stays while any other item's evidence names it; one left over is harmless, so a file
197
+ // that cannot be removed now is not an error.
198
+ for (const sha of files) {
199
+ if (db.prepare('SELECT 1 FROM evidence WHERE sha256 = ? LIMIT 1').get(sha))
200
+ continue;
201
+ rmSync(evidenceFile(project.dataDir, sha), { force: true });
202
+ }
203
+ syncBoardPresets(project);
204
+ return result;
205
+ }
206
+ function entryStep(def, state) {
207
+ const position = positionOf(state);
208
+ if (isClosed(position))
209
+ return { stateName: stateName(def, state), review: false };
210
+ const name = stepById(def, position.step)?.name ?? position.step;
211
+ return { stateName: name, review: position.phase === 'review' };
212
+ }
213
+ // Studio's Archivados: every archived board with its items.
214
+ export function listArchivedBoards(ctx) {
215
+ const rows = listBoards(ctx.db, { archived: true }).filter((row) => row.archivedAt !== null && row.collection !== null);
216
+ return rows.flatMap((row) => {
217
+ const def = definitionOf(ctx, row);
218
+ if (!def || row.collection === null || row.archivedAt === null)
219
+ return [];
220
+ const items = itemsOf(ctx, row);
221
+ const parent = parentOf(ctx, row);
222
+ return [
223
+ {
224
+ id: row.id,
225
+ name: def.name,
226
+ item: def.item,
227
+ icon: def.icon,
228
+ collection: row.collection,
229
+ archivedAt: row.archivedAt,
230
+ items: items.length,
231
+ open: items.filter(({ state }) => isOpen(state)).length,
232
+ parent: parent?.archivedAt ? parent.id : null,
233
+ entries: items.map((item) => ({
234
+ id: item.id,
235
+ title: item.title,
236
+ state: item.state,
237
+ ...entryStep(def, item.state),
238
+ closed: isOpen(item.state) ? false : item.state === DONE ? 'done' : 'dropped',
239
+ })),
240
+ },
241
+ ];
242
+ });
243
+ }
@@ -0,0 +1,272 @@
1
+ import { existsSync, readFileSync, rmSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { parse } from 'yaml';
4
+ import { compileBoard } from '../core/board/compile.js';
5
+ import { newId } from '../core/board/ids.js';
6
+ import { genericBoard, genericState, readBoards, readingOf, rereadable, routeItem, } from '../core/board/readings.js';
7
+ import { parseDefinition, readDefinition } from '../core/board/schema.js';
8
+ import { findBoardOfCollection, findVersion, insertBoard, insertVersion, listBoards, maxVersion, setBoardCollection, setLiveVersion, } from '../store/boards.js';
9
+ import { transaction } from '../store/database.js';
10
+ import { appendEvent, insertCollection, listCollections, selectEvents, selectEvidence, selectItems, setCollectionPreset, updateItemState, } from '../store/queries.js';
11
+ import { prefixOf, syncBoardPresets } from './boards.js';
12
+ import { systemClock } from './items.js';
13
+ // Every collection becomes a board when a project opens, once: a collection still on a preset, and
14
+ // a board an earlier reading made of a shipped preset that nobody published since, are read by
15
+ // core/board/readings.ts. A preset with a second kind of item (change: its repo tasks) becomes a
16
+ // second board its items move to, with their history, links and evidence; Falta información
17
+ // becomes Completar's next round, with the person's question as its note. Collections on presets
18
+ // Otea never shipped read as one step that keeps their data. Returns how many collections it read.
19
+ const OTEA = { kind: 'human', name: 'otea' };
20
+ function pending(ctx) {
21
+ return listCollections(ctx.db).flatMap((collection) => {
22
+ const row = findBoardOfCollection(ctx.db, collection.name);
23
+ if (!row) {
24
+ if (listBoards(ctx.db).some(({ id }) => id === collection.preset))
25
+ return [];
26
+ const reading = readingOf(collection.preset);
27
+ return [{ collection, ...(reading ? { reading } : {}) }];
28
+ }
29
+ if (row.liveVersion === null)
30
+ return [];
31
+ const version = findVersion(ctx.db, row.id, row.liveVersion);
32
+ if (!version)
33
+ return [];
34
+ const live = readDefinition(version.definition);
35
+ const board = {
36
+ liveVersion: row.liveVersion,
37
+ publishedBy: version.publishedBy,
38
+ ...(live.template === undefined ? {} : { template: live.template }),
39
+ };
40
+ // An earlier reading named its board after the preset; this one after its own template.
41
+ if (!rereadable(board) || !live.template)
42
+ return [];
43
+ const reading = readingOf(live.template);
44
+ return reading
45
+ ? [{ collection, board: { id: row.id, version: row.liveVersion }, reading }]
46
+ : [];
47
+ });
48
+ }
49
+ // The board names taken in the project, for the second board of a reading.
50
+ function freeName(ctx, wanted) {
51
+ const taken = new Set(listCollections(ctx.db).map(({ name }) => name.toLocaleLowerCase()));
52
+ for (let n = 1;; n++) {
53
+ const name = n === 1 ? wanted : `${wanted} ${n}`;
54
+ if (!taken.has(name.toLocaleLowerCase()))
55
+ return name;
56
+ }
57
+ }
58
+ function checked(def) {
59
+ const reading = parseDefinition(JSON.parse(JSON.stringify(def)));
60
+ if (!reading.ok)
61
+ return undefined;
62
+ try {
63
+ compileBoard('bcheck', 1, reading.definition);
64
+ }
65
+ catch {
66
+ return undefined;
67
+ }
68
+ return reading.definition;
69
+ }
70
+ // The reason of the item's last move into `state`: the person's question in Falta información.
71
+ function askedReason(ctx, item, state) {
72
+ const moves = selectEvents(ctx.db, item).filter(({ type, data }) => type === 'transitioned' && data.to === state);
73
+ const reason = moves.at(-1)?.data.reason;
74
+ return typeof reason === 'string' && reason !== 'migrate' ? reason : undefined;
75
+ }
76
+ // The preset state an earlier reading moved the item out of.
77
+ function migratedFrom(ctx, item) {
78
+ const moves = selectEvents(ctx.db, item).filter(({ type, data }) => type === 'transitioned' && data.reason === 'migrate');
79
+ const from = moves.at(-1)?.data.from;
80
+ return typeof from === 'string' ? from : undefined;
81
+ }
82
+ function publish(ctx, board, version, definition, at) {
83
+ insertVersion(ctx.db, {
84
+ boardId: board,
85
+ version,
86
+ definition: JSON.stringify(definition),
87
+ publishedAt: at,
88
+ publishedBy: 'otea',
89
+ });
90
+ setLiveVersion(ctx.db, board, version);
91
+ }
92
+ // A board other boards' items block (a blueprint's `blocks` connection into it) waits, on its
93
+ // working step (its last), for nothing open to block an item.
94
+ function waitingForBlockers(def) {
95
+ const last = def.steps.at(-1);
96
+ if (!last || last.waits.includes('blockers'))
97
+ return def;
98
+ return {
99
+ ...def,
100
+ steps: def.steps.map((step) => step === last ? { ...step, waits: [...step.waits, 'blockers'] } : step),
101
+ };
102
+ }
103
+ function readOne(ctx, plan, lang, at, ids, blocked) {
104
+ const { collection, reading } = plan;
105
+ const waits = (def) => blocked.has(collection.name) ? waitingForBlockers(def) : def;
106
+ const items = selectItems(ctx.db, { collection: collection.name });
107
+ if (!reading) {
108
+ // Without its preset, Otea cannot tell its closed states from its open ones: it waits for it.
109
+ const preset = ctx.presets.presets.get(collection.preset);
110
+ if (!preset)
111
+ return false;
112
+ const gates = preset.workflow.gates ?? {};
113
+ const declared = (key) => key in preset.fields;
114
+ const fields = [
115
+ ...new Set([
116
+ ...items.flatMap((item) => Object.keys(item.fields)),
117
+ ...['branch', 'repo'].filter(declared),
118
+ ]),
119
+ ];
120
+ const gated = (gates.push !== undefined || gates.merge !== undefined) && declared('branch');
121
+ const branch = gated
122
+ ? { field: 'branch', ...(declared('repo') ? { repo: 'repo' } : {}) }
123
+ : undefined;
124
+ const evidence = [
125
+ ...new Map(items
126
+ .flatMap((item) => selectEvidence(ctx.db, item.id))
127
+ .flatMap(({ module }) => (module ? [[module, { id: module, module }]] : []))).values(),
128
+ ];
129
+ const def = checked(waits(genericBoard(collection.name, lang, fields, evidence, ids, branch, preset.playbookText)));
130
+ if (!def)
131
+ return false;
132
+ const closes = (state) => preset.workflow.states.find(({ name }) => name === state)?.closes;
133
+ const id = ids('b');
134
+ insertBoard(ctx.db, { id, createdAt: at, builtin: false });
135
+ publish(ctx, id, 1, def, at);
136
+ setBoardCollection(ctx.db, id, collection.name);
137
+ setCollectionPreset(ctx.db, collection.name, id, 1);
138
+ for (const item of items) {
139
+ const closed = closes(item.state);
140
+ const to = closed === 'done'
141
+ ? 'done'
142
+ : genericState(def, { state: item.state, open: closed === undefined });
143
+ move(ctx, item, collection.name, to, at);
144
+ }
145
+ return true;
146
+ }
147
+ const boardIds = reading.boards.map((_, index) => index === 0 && plan.board ? plan.board.id : ids('b'));
148
+ const names = reading.boards.map(({ template }, index) => index === 0 ? collection.name : freeName(ctx, template.board[lang]));
149
+ const defs = readBoards(reading, lang, names, boardIds).map((def, index) => checked(index === 0 ? waits(def) : def));
150
+ if (defs.some((def) => def === undefined))
151
+ return false;
152
+ defs.forEach((def, index) => {
153
+ const id = boardIds[index] ?? '';
154
+ if (!def)
155
+ return;
156
+ if (index === 0 && plan.board) {
157
+ const version = maxVersion(ctx.db, id) + 1;
158
+ publish(ctx, id, version, def, at);
159
+ setCollectionPreset(ctx.db, collection.name, id, version);
160
+ return;
161
+ }
162
+ insertBoard(ctx.db, { id, createdAt: at, builtin: false });
163
+ publish(ctx, id, 1, def, at);
164
+ if (index === 0) {
165
+ setBoardCollection(ctx.db, id, collection.name);
166
+ setCollectionPreset(ctx.db, collection.name, id, 1);
167
+ return;
168
+ }
169
+ const name = names[index] ?? def.name;
170
+ insertCollection(ctx.db, {
171
+ name,
172
+ prefix: prefixOf(ctx, def.item, name),
173
+ preset: id,
174
+ presetVersion: 1,
175
+ nextSeq: 1,
176
+ icon: null,
177
+ });
178
+ setBoardCollection(ctx.db, id, name);
179
+ });
180
+ for (const item of items) {
181
+ const from = plan.board ? migratedFrom(ctx, item.id) : undefined;
182
+ const route = routeItem(reading, {
183
+ type: item.type,
184
+ state: item.state,
185
+ ...(from === undefined ? {} : { migratedFrom: from }),
186
+ });
187
+ const to = names[route.board] ?? collection.name;
188
+ const note = route.note ? askedReason(ctx, item.id, item.state) : undefined;
189
+ move(ctx, item, to, route.state, at, note);
190
+ }
191
+ for (const name of names.slice(1))
192
+ numberAfterMoved(ctx, name);
193
+ return true;
194
+ }
195
+ // Moved items keep their number; the board they moved to numbers its new items after the highest.
196
+ function numberAfterMoved(ctx, collection) {
197
+ ctx.db
198
+ .prepare(`UPDATE collections SET next_seq = MAX(next_seq,
199
+ (SELECT COALESCE(MAX(seq), 0) + 1 FROM items WHERE collection = ?)) WHERE name = ?`)
200
+ .run(collection, collection);
201
+ }
202
+ // Puts an item on its board: its collection, the one item type, and its state, with a migrate
203
+ // event (the start of its history on the board; `note`, the note of the round it starts).
204
+ function move(ctx, item, collection, state, at, note) {
205
+ ctx.db
206
+ .prepare("UPDATE items SET collection = ?, type = 'item' WHERE id = ?")
207
+ .run(collection, item.id);
208
+ if (state === item.state && collection === item.collection && note === undefined)
209
+ return;
210
+ updateItemState(ctx.db, item.id, state, item.updatedAt);
211
+ appendEvent(ctx.db, {
212
+ itemId: item.id,
213
+ type: 'transitioned',
214
+ actor: OTEA,
215
+ at,
216
+ data: {
217
+ from: item.state,
218
+ to: state,
219
+ reason: 'migrate',
220
+ channel: 'ui',
221
+ ...(note === undefined ? {} : { note }),
222
+ },
223
+ });
224
+ }
225
+ export function migrateBoards(ctx, lang, now = systemClock, ids = newId,
226
+ // Collections a blueprint's `blocks` connection pointed into.
227
+ blocked = new Set()) {
228
+ if (pending(ctx).length === 0)
229
+ return 0;
230
+ // Read again inside the write lock: another process may have just read them.
231
+ const count = transaction(ctx.db, () => {
232
+ const at = now();
233
+ return pending(ctx).filter((plan) => readOne(ctx, plan, lang, at, ids, blocked)).length;
234
+ });
235
+ syncBoardPresets(ctx);
236
+ return count;
237
+ }
238
+ // The boards a project's old blueprint (`.otea/blueprint.yaml`) said other boards' items block:
239
+ // `<board>.<type> blocks <board>.<type>`. Missing reads as none; unreadable as undefined.
240
+ export function blockedByBlueprint(dataDir) {
241
+ const path = join(dataDir, 'blueprint.yaml');
242
+ if (!existsSync(path))
243
+ return new Set();
244
+ try {
245
+ const doc = parse(readFileSync(path, 'utf8'));
246
+ const connections = doc && typeof doc === 'object' && 'connections' in doc && Array.isArray(doc.connections)
247
+ ? doc.connections
248
+ : [];
249
+ return new Set(connections.flatMap((text) => {
250
+ const match = typeof text === 'string' ? /^\s*\S+\.\S+\s+blocks\s+(\S+)\.\S+\s*$/.exec(text) : null;
251
+ return match?.[1] ? [match[1]] : [];
252
+ }));
253
+ }
254
+ catch {
255
+ return undefined;
256
+ }
257
+ }
258
+ // Reads every collection as boards (a blueprint's blocks become waits), then forgets the
259
+ // blueprint: boards link freely, and "se divide en" is the only join they declare. The blueprint
260
+ // stays while a collection is left unread (it is read on a later open) or it cannot be read.
261
+ export function migrateProjectBoards(ctx, lang) {
262
+ const path = join(ctx.dataDir, 'blueprint.yaml');
263
+ const blocked = blockedByBlueprint(ctx.dataDir);
264
+ const count = migrateBoards(ctx, lang, systemClock, newId, blocked ?? new Set());
265
+ const unread = pending(ctx).map(({ collection }) => collection.name);
266
+ if (unread.length > 0) {
267
+ process.emitWarning(`Otea could not read ${unread.join(', ')} as boards yet`, 'OteaMigration');
268
+ }
269
+ if (existsSync(path) && blocked !== undefined && unread.length === 0)
270
+ rmSync(path, { force: true });
271
+ return count;
272
+ }