@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,453 @@
1
+ import { OteaError } from '../core/errors.js';
2
+ import { commonWords, searchWords, tellingWords, wordsHeld, } from '../core/search-words.js';
3
+ import { transaction } from '../store/database.js';
4
+ import { selectItems } from '../store/queries.js';
5
+ import { requireItem, systemClock } from './items.js';
6
+ // Side topics: questions the person asks an agent off the work at hand. Each is a short
7
+ // conversation, so none is left hanging in a chat: the person's question, the agent's answer (a
8
+ // summary, with the full answer folded), and notes that keep it going. They are not work: next
9
+ // never offers them and they take no lease. Off until the person turns them on for the project.
10
+ //
11
+ // Whose turn: open is the agent's (to answer); answered is the person's (to read and decide: close
12
+ // it, keep it going with a note, or turn it into a task). Only the person closes a topic. An open
13
+ // topic nobody touched for a day reads as left hanging.
14
+ export const HANGING_AFTER_MS = 24 * 60 * 60 * 1000;
15
+ // A task made by the same agent this long after a topic it opened is suggested as related to it.
16
+ export const SUGGEST_WITHIN_MS = 12 * 60 * 60 * 1000;
17
+ const TITLE_MAX = 120;
18
+ function refuse(code, message) {
19
+ throw new OteaError(code, message);
20
+ }
21
+ export function topicsOn(ctx) {
22
+ const row = ctx.db.prepare('SELECT enabled FROM topics_switch WHERE id = 1').get();
23
+ return row?.enabled === 1;
24
+ }
25
+ export function setTopicsOn(ctx, on) {
26
+ ctx.db
27
+ .prepare('INSERT INTO topics_switch (id, enabled) VALUES (1, ?) ON CONFLICT (id) DO UPDATE SET enabled = excluded.enabled')
28
+ .run(on ? 1 : 0);
29
+ }
30
+ function effectiveState(row, nowIso) {
31
+ if (row.state === 'open' && Date.parse(nowIso) - Date.parse(row.updated_at) > HANGING_AFTER_MS)
32
+ return 'hanging';
33
+ return row.state;
34
+ }
35
+ function turnOf(state) {
36
+ if (state === 'open' || state === 'hanging')
37
+ return 'agent';
38
+ if (state === 'answered')
39
+ return 'human';
40
+ return 'none';
41
+ }
42
+ function toTopic(ctx, row, nowIso) {
43
+ const turns = ctx.db
44
+ .prepare('SELECT id, kind, text, full, source, actor_kind, actor_name, at FROM topic_turns WHERE topic_id = ? ORDER BY id')
45
+ .all(row.id).map((turn, index) => ({
46
+ n: index + 1,
47
+ kind: turn.kind,
48
+ text: turn.text,
49
+ ...(turn.full === null ? {} : { full: turn.full }),
50
+ ...(turn.source === null ? {} : { source: turn.source }),
51
+ by: { kind: turn.actor_kind, name: turn.actor_name },
52
+ at: turn.at,
53
+ }));
54
+ const links = ctx.db
55
+ .prepare("SELECT item_id FROM topic_links WHERE topic_id = ? AND via <> 'dismissed' ORDER BY at")
56
+ .all(row.id).map(({ item_id }) => item_id);
57
+ const state = effectiveState(row, nowIso);
58
+ return {
59
+ id: row.id,
60
+ title: row.title,
61
+ state,
62
+ turn: turnOf(state),
63
+ ...(row.agent === null ? {} : { agent: row.agent }),
64
+ ...(row.session === null ? {} : { session: row.session }),
65
+ ...(row.resume === null ? {} : { resume: row.resume }),
66
+ ...(row.task === null ? {} : { task: row.task }),
67
+ createdAt: row.created_at,
68
+ updatedAt: row.updated_at,
69
+ by: { kind: row.created_by_kind, name: row.created_by_name },
70
+ turns,
71
+ links,
72
+ };
73
+ }
74
+ function findRow(ctx, id) {
75
+ return ctx.db.prepare('SELECT * FROM topics WHERE id = ? COLLATE NOCASE').get(id.trim());
76
+ }
77
+ function requireRow(ctx, id) {
78
+ const row = findRow(ctx, id);
79
+ if (!row)
80
+ throw new OteaError('not_found', `Topic "${id}" not found`);
81
+ return row;
82
+ }
83
+ export function requireTopic(ctx, id, now = systemClock) {
84
+ return toTopic(ctx, requireRow(ctx, id), now());
85
+ }
86
+ function titleOf(question) {
87
+ const line = question.trim().split(/\r?\n/)[0] ?? '';
88
+ return line.length <= TITLE_MAX ? line : `${line.slice(0, TITLE_MAX - 1).trimEnd()}…`;
89
+ }
90
+ function addTurn(ctx, id, turn, at) {
91
+ ctx.db
92
+ .prepare(`INSERT INTO topic_turns (topic_id, kind, text, full, source, actor_kind, actor_name, at)
93
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)`)
94
+ .run(id, turn.kind, turn.text, turn.full ?? null, turn.source ?? null, turn.by.kind, turn.by.name, at);
95
+ }
96
+ function setState(ctx, id, state, at) {
97
+ ctx.db.prepare('UPDATE topics SET state = ?, updated_at = ? WHERE id = ?').run(state, at, id);
98
+ }
99
+ // A follow-up goes on the topic it follows: a new question, the turn of the agent that recorded it
100
+ // (it answers in its chat). A closed topic opens again; one turned into a task keeps going there.
101
+ function followUp(ctx, input, question, at) {
102
+ const row = requireRow(ctx, input.to ?? '');
103
+ if (row.state === 'task')
104
+ refuse('invalid_transition', `${row.id} became ${row.task}: keep it going there`);
105
+ return transaction(ctx.db, () => {
106
+ addTurn(ctx, row.id, { kind: 'question', text: question, by: input.actor }, at);
107
+ if (input.actor.kind === 'agent')
108
+ ctx.db.prepare('UPDATE topics SET agent = ? WHERE id = ?').run(input.actor.name, row.id);
109
+ if (input.session || input.resume)
110
+ ctx.db
111
+ .prepare('UPDATE topics SET session = coalesce(?, session), resume = coalesce(?, resume) WHERE id = ?')
112
+ .run(input.session ?? null, input.resume ?? null, row.id);
113
+ setState(ctx, row.id, 'open', at);
114
+ return toTopic(ctx, requireRow(ctx, row.id), at);
115
+ });
116
+ }
117
+ // Opens a topic with the person's question, the agent's turn to answer. An agent records the
118
+ // question the person asked it in its chat; the person may open one too. With `to`, the question
119
+ // follows up on that topic instead.
120
+ export function addTopic(ctx, input, now = systemClock) {
121
+ const question = input.question.trim();
122
+ if (question === '')
123
+ refuse('invalid_fields', 'A topic needs the question it is about');
124
+ const at = now();
125
+ if (input.to !== undefined)
126
+ return followUp(ctx, input, question, at);
127
+ const title = input.title?.trim() || titleOf(question);
128
+ return transaction(ctx.db, () => {
129
+ const seq = (ctx.db.prepare('SELECT max(seq) AS seq FROM topics').get().seq ??
130
+ 0) + 1;
131
+ const id = `TEM-${seq}`;
132
+ const agent = input.actor.kind === 'agent' ? input.actor.name : null;
133
+ ctx.db
134
+ .prepare(`INSERT INTO topics (id, seq, title, state, agent, session, resume, created_at, updated_at,
135
+ created_by_kind, created_by_name)
136
+ VALUES (?, ?, ?, 'open', ?, ?, ?, ?, ?, ?, ?)`)
137
+ .run(id, seq, title, agent, input.session ?? null, input.resume ?? null, at, at, input.actor.kind, input.actor.name);
138
+ // The question is the person's, even when the agent writes it down.
139
+ addTurn(ctx, id, { kind: 'question', text: question, by: input.actor }, at);
140
+ return toTopic(ctx, requireRow(ctx, id), at);
141
+ });
142
+ }
143
+ // The agent's answer: a short summary to read in the list and the full answer, folded, both as the
144
+ // agent copied them (no harness hook reads its chat).
145
+ export function answerTopic(ctx, input, now = systemClock) {
146
+ if (input.actor.kind !== 'agent')
147
+ refuse('forbidden', 'Only an agent answers a topic');
148
+ const row = requireRow(ctx, input.id);
149
+ if (row.state === 'closed' || row.state === 'task')
150
+ refuse('invalid_transition', `${row.id} is closed: it takes no more answers`);
151
+ const at = now();
152
+ return transaction(ctx.db, () => {
153
+ const last = ctx.db
154
+ .prepare('SELECT id, kind, text, full, source FROM topic_turns WHERE topic_id = ? ORDER BY id DESC LIMIT 1')
155
+ .get(row.id);
156
+ const summary = input.summary?.trim();
157
+ const full = input.full?.trim();
158
+ if (last?.kind === 'answer') {
159
+ // The same answer again: a later summary and full text replace the earlier ones.
160
+ ctx.db
161
+ .prepare("UPDATE topic_turns SET text = ?, full = ?, source = 'agent' WHERE id = ?")
162
+ .run(summary || last.text, full ?? last.full, last.id);
163
+ }
164
+ else {
165
+ if (!summary)
166
+ refuse('invalid_fields', 'An answer needs its summary (--summary)');
167
+ addTurn(ctx, row.id, {
168
+ kind: 'answer',
169
+ text: summary || titleOf(full ?? ''),
170
+ ...(full === undefined ? {} : { full }),
171
+ source: 'agent',
172
+ by: input.actor,
173
+ }, at);
174
+ }
175
+ if (input.session || input.resume)
176
+ ctx.db
177
+ .prepare('UPDATE topics SET session = coalesce(?, session), resume = coalesce(?, resume) WHERE id = ?')
178
+ .run(input.session ?? null, input.resume ?? null, row.id);
179
+ if (row.agent === null)
180
+ ctx.db.prepare('UPDATE topics SET agent = ? WHERE id = ?').run(input.actor.name, row.id);
181
+ setState(ctx, row.id, 'answered', at);
182
+ return toTopic(ctx, requireRow(ctx, row.id), at);
183
+ });
184
+ }
185
+ // The person keeps a topic going: the note goes to the agent that answered it, which a waiting
186
+ // agent gets with otea wait. A closed topic opens again.
187
+ export function noteTopic(ctx, input, now = systemClock) {
188
+ if (input.actor.kind !== 'human')
189
+ refuse('forbidden', 'Only the person adds a note to a topic');
190
+ const text = input.text.trim();
191
+ if (text === '')
192
+ refuse('invalid_fields', 'The note is empty');
193
+ const row = requireRow(ctx, input.id);
194
+ if (row.state === 'task')
195
+ refuse('invalid_transition', `${row.id} became ${row.task}: keep it going there`);
196
+ const at = now();
197
+ return transaction(ctx.db, () => {
198
+ addTurn(ctx, row.id, { kind: 'note', text, by: input.actor }, at);
199
+ setState(ctx, row.id, 'open', at);
200
+ return toTopic(ctx, requireRow(ctx, row.id), at);
201
+ });
202
+ }
203
+ export function closeTopic(ctx, input, now = systemClock) {
204
+ if (input.actor.kind !== 'human')
205
+ refuse('forbidden', 'Only the person closes a topic');
206
+ const row = requireRow(ctx, input.id);
207
+ const at = now();
208
+ setState(ctx, row.id, 'closed', at);
209
+ return toTopic(ctx, requireRow(ctx, row.id), at);
210
+ }
211
+ export function linkTopic(ctx, input, now = systemClock) {
212
+ const row = requireRow(ctx, input.id);
213
+ const item = requireItem(ctx.db, input.item);
214
+ const at = now();
215
+ ctx.db
216
+ .prepare(`INSERT INTO topic_links (topic_id, item_id, via, at) VALUES (?, ?, ?, ?)
217
+ ON CONFLICT (topic_id, item_id) DO UPDATE SET via = excluded.via, at = excluded.at`)
218
+ .run(row.id, item.id, input.via, at);
219
+ return toTopic(ctx, requireRow(ctx, row.id), at);
220
+ }
221
+ // The person turns a topic into a task: the item, made on a board of their choice, and the topic
222
+ // point to each other, and the topic is done.
223
+ export function convertTopic(ctx, input, now = systemClock) {
224
+ if (input.actor.kind !== 'human')
225
+ refuse('forbidden', 'Only the person turns a topic into a task');
226
+ const row = requireRow(ctx, input.id);
227
+ const item = requireItem(ctx.db, input.item);
228
+ const at = now();
229
+ return transaction(ctx.db, () => {
230
+ linkTopic(ctx, { id: row.id, item: item.id, via: 'convert' }, () => at);
231
+ ctx.db
232
+ .prepare("UPDATE topics SET state = 'task', task = ?, updated_at = ? WHERE id = ?")
233
+ .run(item.id, at, row.id);
234
+ return toTopic(ctx, requireRow(ctx, row.id), at);
235
+ });
236
+ }
237
+ // An item is being deleted (with its board): topics lose their link to it, and a topic it was
238
+ // turned into goes back to whose turn it was, with a line in its thread naming the deleted task.
239
+ export function forgetTopicItem(ctx, item, at) {
240
+ ctx.db.prepare('DELETE FROM topic_links WHERE item_id = ?').run(item);
241
+ const converted = ctx.db.prepare('SELECT id FROM topics WHERE task = ?').all(item);
242
+ for (const { id } of converted) {
243
+ const answered = ctx.db
244
+ .prepare("SELECT 1 FROM topic_turns WHERE topic_id = ? AND kind = 'answer' LIMIT 1")
245
+ .get(id);
246
+ ctx.db
247
+ .prepare('UPDATE topics SET state = ?, task = NULL, updated_at = ? WHERE id = ?')
248
+ .run(answered ? 'answered' : 'open', at, id);
249
+ addTurn(ctx, id, { kind: 'event', text: item, by: { kind: 'human', name: 'otea' } }, at);
250
+ }
251
+ }
252
+ export function dismissTopicSuggestion(ctx, input, now = systemClock) {
253
+ const row = requireRow(ctx, input.id);
254
+ const item = requireItem(ctx.db, input.item);
255
+ ctx.db
256
+ .prepare(`INSERT INTO topic_links (topic_id, item_id, via, at) VALUES (?, ?, 'dismissed', ?)
257
+ ON CONFLICT (topic_id, item_id) DO NOTHING`)
258
+ .run(row.id, item.id, now());
259
+ }
260
+ const isPending = (state) => state === 'open' || state === 'answered' || state === 'hanging';
261
+ // The topics an item is linked to, each saying whether it still waits on someone.
262
+ export function topicsOfItem(ctx, item, now = systemClock) {
263
+ const at = now();
264
+ const rows = ctx.db
265
+ .prepare(`SELECT t.* FROM topics t JOIN topic_links l ON l.topic_id = t.id
266
+ WHERE l.item_id = ? AND l.via <> 'dismissed' ORDER BY t.seq`)
267
+ .all(item);
268
+ return rows.map((row) => {
269
+ const topic = toTopic(ctx, row, at);
270
+ return { ...topic, pending: isPending(topic.state) };
271
+ });
272
+ }
273
+ // At most this many topics are suggested for an item.
274
+ export const SUGGEST_AT_MOST = 3;
275
+ // The words an item says: its title and the text of its fields.
276
+ function itemWords(item) {
277
+ const values = Object.values(item.fields).filter((value) => typeof value === 'string');
278
+ return [item.title, ...values].join('\n');
279
+ }
280
+ // Open topics the item may have come from, for the person to confirm: one the same agent opened
281
+ // shortly before it made the item, or one of the same session, that shares a telling word with
282
+ // the item in what the topic itself says (its title, questions and the answers' summaries, never a
283
+ // full answer's long text). A telling word is no stop word, no word any work request says (error,
284
+ // arreglar, archivo) and no word common among the project's items (core/search-words.ts,
285
+ // commonWords): one such word alone tied an unrelated topic to an item (P6-R3-7). The topics that
286
+ // share the most words come first, then the latest; three at most; none rather than noise
287
+ // (P4-R2-7). Never one already linked or dismissed for it.
288
+ export function topicSuggestions(ctx, item, now = systemClock, session) {
289
+ const record = requireItem(ctx.db, item);
290
+ const common = commonWords(selectItems(ctx.db, {}).map(itemWords));
291
+ const searched = tellingWords(itemWords(record)).filter(([word]) => !common.has(word ?? ''));
292
+ const madeAt = Date.parse(record.createdAt);
293
+ const at = now();
294
+ const rows = ctx.db
295
+ .prepare(`SELECT t.* FROM topics t
296
+ WHERE t.state IN ('open', 'answered')
297
+ AND NOT EXISTS (SELECT 1 FROM topic_links l WHERE l.topic_id = t.id AND l.item_id = ?)
298
+ ORDER BY t.seq`)
299
+ .all(record.id);
300
+ return rows
301
+ .filter((row) => {
302
+ if (session && row.session === session)
303
+ return true;
304
+ if (record.createdBy.kind !== 'agent' || row.agent !== record.createdBy.name)
305
+ return false;
306
+ const opened = Date.parse(row.created_at);
307
+ return opened <= madeAt && madeAt - opened <= SUGGEST_WITHIN_MS;
308
+ })
309
+ .map((row) => toTopic(ctx, row, at))
310
+ .map((topic) => ({ topic, score: said(topic, searched) }))
311
+ .filter(({ score }) => score > 0)
312
+ .sort((a, b) => b.score - a.score || b.topic.createdAt.localeCompare(a.topic.createdAt))
313
+ .slice(0, SUGGEST_AT_MOST)
314
+ .map(({ topic }) => topic);
315
+ }
316
+ // How many of the words a topic says itself: its title, its questions and its answers' summaries.
317
+ function said(topic, searched) {
318
+ const own = topic.turns.filter(({ kind }) => kind === 'question' || kind === 'answer');
319
+ return wordsHeld([topic.title, ...own.map(({ text }) => text)].join('\n'), searched);
320
+ }
321
+ const ORDER = {
322
+ hanging: 0,
323
+ open: 1,
324
+ answered: 2,
325
+ task: 3,
326
+ closed: 4,
327
+ };
328
+ // How many of the words searched (core/search-words.ts) a topic holds, anywhere in it: its id,
329
+ // title, the question, each answer's summary and full text, and the person's notes.
330
+ function score(topic, searched) {
331
+ const parts = topic.turns.flatMap((turn) => [turn.text, turn.full ?? '']);
332
+ return wordsHeld([topic.id, topic.title, ...parts].join('\n'), searched);
333
+ }
334
+ const byState = (a, b) => ORDER[a.state] - ORDER[b.state] || a.id.localeCompare(b.id, 'en', { numeric: true });
335
+ // The topics, what is left hanging first; closed ones and those turned into tasks only when asked.
336
+ // A search looks in every topic, closed ones too, as the person asks what was concluded before: it
337
+ // finds a topic that holds any of the words, the one that holds the most first.
338
+ export function listTopics(ctx, filter = {}, now = systemClock) {
339
+ const at = now();
340
+ const searched = searchWords(filter.search ?? '');
341
+ const rows = ctx.db.prepare('SELECT * FROM topics ORDER BY seq').all();
342
+ const topics = rows.map((row) => toTopic(ctx, row, at));
343
+ if (searched.length === 0)
344
+ return topics.filter((topic) => filter.all || isPending(topic.state)).sort(byState);
345
+ return topics
346
+ .map((topic) => ({ topic, score: score(topic, searched) }))
347
+ .filter(({ score }) => score > 0)
348
+ .sort((a, b) => b.score - a.score || byState(a.topic, b.topic))
349
+ .map(({ topic }) => topic);
350
+ }
351
+ // A note the person left on a topic this agent answers, not yet delivered: otea wait wakes for it
352
+ // once, and the agent answers it with otea topic answer.
353
+ export function topicWaiting(ctx, agent, now = systemClock) {
354
+ const row = ctx.db
355
+ .prepare(`SELECT n.id, n.topic_id, n.text FROM topic_turns n JOIN topics t ON t.id = n.topic_id
356
+ WHERE t.agent = ? AND t.state = 'open' AND n.kind = 'note' AND n.seen_at IS NULL
357
+ ORDER BY n.id LIMIT 1`)
358
+ .get(agent);
359
+ if (!row)
360
+ return undefined;
361
+ ctx.db.prepare('UPDATE topic_turns SET seen_at = ? WHERE id = ?').run(now(), row.id);
362
+ return {
363
+ topic: row.topic_id,
364
+ note: row.text,
365
+ text: `The person left a note on topic ${row.topic_id}: "${row.text}"\nAnswer it with otea topic answer ${row.topic_id} --summary "<short answer>" --full "<your answer as you gave it>".`,
366
+ };
367
+ }
368
+ // The topics waiting for this agent's answer: its open ones, a question it recorded and has not
369
+ // answered or a note the person left (which otea wait woke it for only once), for otea next to name.
370
+ export function topicsAwaiting(ctx, agent, now = systemClock) {
371
+ return listTopics(ctx, {}, now).filter((topic) => topic.turn === 'agent' && topic.agent === agent);
372
+ }
373
+ // The person's notes since the agent last answered: otea wait showed them only once, and an agent
374
+ // that runs next instead reads here what it is to answer.
375
+ function notesSinceAnswer(topic) {
376
+ const last = topic.turns.findLastIndex((turn) => turn.kind === 'answer');
377
+ if (last < 0)
378
+ return [];
379
+ return topic.turns
380
+ .slice(last + 1)
381
+ .filter((turn) => turn.kind === 'note')
382
+ .map((turn) => turn.text);
383
+ }
384
+ export function topicsAwaitingText(topics) {
385
+ if (topics.length === 0)
386
+ return undefined;
387
+ return [
388
+ 'Topics waiting for your answer (the person reads it in Temas):',
389
+ ...topics.map((topic) => {
390
+ const { id, title } = topic;
391
+ const answer = `otea topic answer ${id} --summary "<short answer>" --full "<your answer as you gave it>"`;
392
+ const notes = notesSinceAnswer(topic);
393
+ if (notes.length === 0)
394
+ return ` ${id} "${title}": ${answer}`;
395
+ const wrote = notes.map((note) => `"${note}"`).join(' ');
396
+ return ` ${id} "${title}": the person wrote after your answer: ${wrote}. Answer it: ${answer}`;
397
+ }),
398
+ ].join('\n');
399
+ }
400
+ // Refuses topic work while topics are off for the project.
401
+ export function requireTopicsOn(ctx) {
402
+ if (!topicsOn(ctx))
403
+ throw new OteaError('forbidden', 'Topics are off for this project: the person turns them on with otea topic on, or in Settings');
404
+ }
405
+ const STATE_WORDS = {
406
+ open: "open, the agent's turn to answer",
407
+ hanging: 'left hanging: open and untouched for a day',
408
+ answered: "answered, the person's turn",
409
+ closed: 'closed',
410
+ task: 'turned into a task',
411
+ };
412
+ // A topic as text: its state, then each turn; an answer's summary, then its full text.
413
+ export function topicText(topic) {
414
+ const head = `${topic.id} · ${topic.title} (${STATE_WORDS[topic.state]})`;
415
+ const lines = [head];
416
+ if (topic.task)
417
+ lines.push(`Became ${topic.task}.`);
418
+ if (topic.links.length > 0)
419
+ lines.push(`Linked to ${topic.links.join(', ')}.`);
420
+ if (topic.resume)
421
+ lines.push(`Resume the session: ${topic.resume}`);
422
+ for (const turn of topic.turns) {
423
+ const who = turn.by.kind === 'human' ? 'the person' : turn.by.name;
424
+ if (turn.kind === 'event') {
425
+ lines.push(`${turn.n}. The task ${turn.text} was deleted with its board, so the topic is pending again.`);
426
+ }
427
+ else if (turn.kind === 'answer') {
428
+ const from = turn.source === 'session' ? 'read from the session' : 'saved by the agent';
429
+ lines.push(`${turn.n}. Answer by ${who}: ${turn.text}`);
430
+ if (turn.full)
431
+ lines.push(` Answer ${from}:\n${turn.full.replace(/^/gm, ' ')}`);
432
+ }
433
+ else {
434
+ const label = turn.kind === 'question' ? 'Question' : 'Note from the person';
435
+ lines.push(`${turn.n}. ${label}: ${turn.text}`);
436
+ }
437
+ }
438
+ return lines.join('\n');
439
+ }
440
+ // One line per topic; a search gives each topic found its last answer, often all that was asked.
441
+ export function topicsListText(topics, search) {
442
+ const searched = search?.trim() ?? '';
443
+ if (topics.length === 0)
444
+ return searched === '' ? 'No topics wait on anyone.' : `No topic mentions "${searched}".`;
445
+ return topics
446
+ .map((topic) => {
447
+ const line = `${topic.id} ${topic.state.padEnd(8)} ${topic.title}`;
448
+ const answer = searched === '' ? undefined : lastAnswerOf(topic);
449
+ return answer ? `${line}\n ${answer.text}` : line;
450
+ })
451
+ .join('\n');
452
+ }
453
+ const lastAnswerOf = (topic) => topic.turns.findLast((turn) => turn.kind === 'answer');
@@ -0,0 +1,52 @@
1
+ import { OteaError } from '../core/errors.js';
2
+ import { transaction } from '../store/database.js';
3
+ import { appendEvent, selectEvents, updateItemState } from '../store/queries.js';
4
+ import { typeOfItem } from './collections.js';
5
+ import { present, requireWritableItem, stateNames, systemClock, } from './items.js';
6
+ // The person takes back their last move while its toast is still up: the item returns to the state
7
+ // it left, outside the workflow's transitions (an approval has no move back). The undo is itself a
8
+ // transitioned event that names the event it undoes, so readers can drop the pair.
9
+ // The toast stays about 6 s; the undo is honoured a little longer, for a slow click or a slow link.
10
+ export const UNDO_WINDOW_MS = 30_000;
11
+ export function undoMove(ctx, input, now = systemClock) {
12
+ const { db } = ctx;
13
+ return transaction(db, () => {
14
+ const item = requireWritableItem(db, input.id);
15
+ const at = now();
16
+ const moves = selectEvents(db, item.id).filter((e) => e.type === 'transitioned');
17
+ const last = moves.at(-1);
18
+ const refuse = (why, text) => {
19
+ throw new OteaError('not_undoable', `${item.id}: ${text}`, {
20
+ kind: 'undo',
21
+ item: item.id,
22
+ why,
23
+ });
24
+ };
25
+ if (!last)
26
+ return refuse('not_moved', 'it has not moved');
27
+ if (last.data.undoes !== undefined)
28
+ return refuse('already_undone', 'its last move is already undone');
29
+ if (last.actor.kind !== input.actor.kind || last.actor.name !== input.actor.name)
30
+ return refuse('not_yours', 'its last move is not yours');
31
+ if (last.data.to !== item.state || last.data.from !== input.from)
32
+ return refuse('not_from', `its last move is not from "${input.from}"`);
33
+ if (Date.parse(at) - Date.parse(last.at) > UNDO_WINDOW_MS)
34
+ return refuse('too_old', 'the move is too old to take back');
35
+ const { workflow } = typeOfItem(ctx, item);
36
+ updateItemState(db, item.id, input.from, at);
37
+ appendEvent(db, {
38
+ itemId: item.id,
39
+ type: 'transitioned',
40
+ actor: input.actor,
41
+ at,
42
+ data: {
43
+ from: item.state,
44
+ to: input.from,
45
+ ...stateNames(workflow, { from: item.state, to: input.from }),
46
+ undoes: last.id,
47
+ channel: input.channel,
48
+ },
49
+ });
50
+ return present({ ...item, state: input.from, updatedAt: at }, workflow, at);
51
+ });
52
+ }
@@ -0,0 +1,131 @@
1
+ import { instructionHints } from '../core/board/hints.js';
2
+ import { partRule } from '../core/board/joins.js';
3
+ import { readDefinition } from '../core/board/schema.js';
4
+ import { OteaError } from '../core/errors.js';
5
+ import { itemFindings } from '../core/validation.js';
6
+ import { findVersion, listBoards } from '../store/boards.js';
7
+ import { findItem, listCollections, selectItems, selectRelations } from '../store/queries.js';
8
+ import { workflowOf } from './items.js';
9
+ import { liveBoardOf } from './next.js';
10
+ import { requirePreset } from './presets.js';
11
+ function resolve(ctx, name) {
12
+ try {
13
+ return requirePreset(ctx.presets, name);
14
+ }
15
+ catch (error) {
16
+ if (error instanceof OteaError)
17
+ return error.message;
18
+ throw error;
19
+ }
20
+ }
21
+ // Whether some state of the item's workflow waits for its children; false when its preset is gone.
22
+ function waitsForChildren(ctx, item) {
23
+ let workflow;
24
+ try {
25
+ workflow = workflowOf(ctx, item);
26
+ }
27
+ catch (error) {
28
+ if (error instanceof OteaError)
29
+ return false;
30
+ throw error;
31
+ }
32
+ return workflow.states.some(({ requires }) => requires?.includes('children_closed'));
33
+ }
34
+ // A parent on another board, linked before a tree had to live in one: it still reads, and each is
35
+ // reported with its two ways out. Making its board divide into the child's keeps the tree; blocks
36
+ // keeps the wait of a parent that waits for its parts, and implements keeps the rest. A part
37
+ // on the board its parent's board divides into ("se divide en") is the declared join, not a stray.
38
+ function declaredPart(ctx, child, parent) {
39
+ const childBoard = liveBoardOf(ctx, child);
40
+ const parentBoard = liveBoardOf(ctx, parent);
41
+ return !!childBoard && !!parentBoard && partRule(parentBoard, childBoard) === 'ok';
42
+ }
43
+ function parentAcrossBoards(ctx) {
44
+ return selectRelations(ctx.db, 'parent').flatMap(({ from, to }) => {
45
+ const child = findItem(ctx.db, from);
46
+ const parent = findItem(ctx.db, to);
47
+ if (!child || !parent || child.collection === parent.collection)
48
+ return [];
49
+ if (declaredPart(ctx, child.collection, parent.collection))
50
+ return [];
51
+ const join = `in Studio make ${parent.collection} divide into ${child.collection}`;
52
+ const unlink = `otea unlink ${from} parent ${to}`;
53
+ const convert = waitsForChildren(ctx, parent)
54
+ ? `convert the link to blocks, since ${to} waits for its parts: ${unlink}, otea link ${from} blocks ${to}, and in Studio have ${parent.collection} wait for nothing holding it back where it waits for its parts`
55
+ : `convert the link to implements: ${unlink}, otea link ${from} implements ${to}`;
56
+ return [
57
+ {
58
+ severity: 'warning',
59
+ subject: from,
60
+ message: `parent ${to} is on another board (${parent.collection}); ${join}, or ${convert}`,
61
+ },
62
+ ];
63
+ });
64
+ }
65
+ // The preset notes otea validate prints: the warnings of the project's own presets. An official
66
+ // preset is read-only, so its notes (an approval only the web UI may give, say) are by design, and
67
+ // Studio shows them; info notes only say what a preset does, and stay in Studio too.
68
+ function presetWarnings(ctx) {
69
+ return ctx.presets.warnings
70
+ .filter(({ origin, level = 'warning' }) => origin === 'project' && level === 'warning')
71
+ .map(({ preset, message }) => ({
72
+ severity: 'warning',
73
+ subject: `preset ${preset}`,
74
+ message,
75
+ }));
76
+ }
77
+ function hintWords({ code, params }) {
78
+ const step = `step "${params.step}"`;
79
+ if (code === 'instructions_missing')
80
+ return `${step}: an agent works it, but no instructions tell it what to do; write them in Studio`;
81
+ if (code === 'instructions_ask_part')
82
+ return `${step}: its instructions ask for "${params.part ?? ''}", but its handoff does not require it`;
83
+ return `${step}: its instructions ask to attach something, but its handoff requires no evidence`;
84
+ }
85
+ // The soft hints on what agents read on each live board (Studio shows the same on the step's card).
86
+ // The built-in Pedidos board is left out: what each Pedido asks is its own instruction.
87
+ function boardHints(ctx) {
88
+ return listBoards(ctx.db).flatMap((row) => {
89
+ if (row.builtin || row.liveVersion === null)
90
+ return [];
91
+ const live = findVersion(ctx.db, row.id, row.liveVersion);
92
+ if (!live)
93
+ return [];
94
+ const def = readDefinition(live.definition);
95
+ return instructionHints(def).map((hint) => ({
96
+ severity: 'warning',
97
+ subject: `board ${def.name}`,
98
+ message: hintWords(hint),
99
+ }));
100
+ });
101
+ }
102
+ // `extra` carries findings checked elsewhere.
103
+ export function validateProject(ctx, extra = []) {
104
+ const findings = [
105
+ ...ctx.presets.problems.map(({ preset, message }) => ({
106
+ severity: 'error',
107
+ subject: `preset ${preset}`,
108
+ message,
109
+ })),
110
+ ...presetWarnings(ctx),
111
+ ];
112
+ findings.push(...extra);
113
+ for (const collection of listCollections(ctx.db)) {
114
+ const preset = resolve(ctx, collection.preset);
115
+ if (typeof preset === 'string') {
116
+ findings.push({
117
+ severity: 'error',
118
+ subject: `collection ${collection.name}`,
119
+ message: preset,
120
+ });
121
+ continue;
122
+ }
123
+ for (const item of selectItems(ctx.db, { collection: collection.name })) {
124
+ findings.push(...itemFindings(preset, item));
125
+ }
126
+ }
127
+ findings.push(...parentAcrossBoards(ctx));
128
+ findings.push(...boardHints(ctx));
129
+ const errors = findings.filter(({ severity }) => severity === 'error').length;
130
+ return { errors, warnings: findings.length - errors, findings };
131
+ }