@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,1637 @@
1
+ import { choiceOf } from '../core/board/choices.js';
2
+ import { approve, backWaysOf, drop, gateAt, handoff, handoffCheck, initialPosition, isClosed, isLandStep, mayReview, mayTake, openWaits, positionOf, refusalCode, reopenedAt, roundsOf, sendBack, sentBackAt, stateOf, turnAt, WAIT_PARTS, waysOf, } from '../core/board/engine.js';
3
+ import { HANDOFF_AMENDED, handoffNotes, historyOf, roundAfter, } from '../core/board/history.js';
4
+ import { requiredParent } from '../core/board/joins.js';
5
+ import { mergedFrom } from '../core/board/merged.js';
6
+ import { DONE, DROPPED, guardedBranch, SAME, stepById, stepIndex, } from '../core/board/model.js';
7
+ import { approvalRefusalText, closedName, createdText, droppedText, dropRefusalText, handedText, idleText, mergeFirstText, mergeLines, NOT_TAKEN_BACK, nextText, noWayText, parentRequiredText, placeText, refusalText, sentBackText, takenBackText, targetName, wayByName, } from '../core/board/next.js';
8
+ import { laterNotesRefusal, notesBlock, notesOf, notesOfRound, unansweredOf, } from '../core/board/notes.js';
9
+ import { proofsFrom, provedPoints } from '../core/board/proofs.js';
10
+ import { openQuestion, questionsOf } from '../core/board/questions.js';
11
+ import { evidenceByName, readFieldInput, stateByName, stateName } from '../core/board/reading.js';
12
+ import { readDefinition } from '../core/board/schema.js';
13
+ import { OteaError } from '../core/errors.js';
14
+ import { activeLease } from '../core/lease.js';
15
+ import { closesOf, turnOf } from '../core/workflow.js';
16
+ import { findBoardOfCollection, findVersion, listBoards } from '../store/boards.js';
17
+ import { transaction } from '../store/database.js';
18
+ import { appendEvent, findAgent, findItem, saveOffer, selectEvents, selectEvidence, selectItems, selectOffers, selectRelationsOf, selectStateEntries, } from '../store/queries.js';
19
+ import { collectionNamed } from './collections.js';
20
+ import { draftRequestOf, handInCommand } from './draft-request.js';
21
+ import { getItem, landMove, requireItem, requireWritableItem, systemClock, workflowOf, } from './items.js';
22
+ import { landsFirst, landsFirstLine, landsFirstText } from './land-order.js';
23
+ import { assertMayWriteItem, takeItem } from './lease-take.js';
24
+ import { sessionAlive, sessionRuns } from './presence.js';
25
+ import { priorityOf } from './priority.js';
26
+ import { liftSetAside, retakeOf, retakeText, SET_ASIDE_LIFTED, setAsideOf } from './set-aside.js';
27
+ import { approvedTipOf } from './tips.js';
28
+ // The live version of the board a collection is on; undefined for a collection still on a preset.
29
+ export function liveBoardOf(ctx, collection) {
30
+ const row = findBoardOfCollection(ctx.db, collection);
31
+ if (!row || row.liveVersion === null)
32
+ return undefined;
33
+ const version = findVersion(ctx.db, row.id, row.liveVersion);
34
+ if (!version)
35
+ return undefined;
36
+ return {
37
+ id: row.id,
38
+ version: row.liveVersion,
39
+ collection,
40
+ def: readDefinition(version.definition),
41
+ };
42
+ }
43
+ // Every published board that is on a collection.
44
+ export function liveBoards(ctx) {
45
+ return listBoards(ctx.db).flatMap((row) => row.collection === null ? [] : (liveBoardOf(ctx, row.collection) ?? []));
46
+ }
47
+ // The item's moves as the engine replays them (core/board/history.ts), the moves taken back left
48
+ // out.
49
+ function historyFor(item, def, events) {
50
+ return historyOf(events, {
51
+ initial: def.steps[0]?.id ?? item.state,
52
+ createdAt: item.createdAt,
53
+ });
54
+ }
55
+ // The live board with this id, when it is published on a collection.
56
+ export function liveBoardById(ctx, id) {
57
+ const row = listBoards(ctx.db).find((board) => board.id === id);
58
+ return row?.collection == null ? undefined : liveBoardOf(ctx, row.collection);
59
+ }
60
+ // The board an item's parts are on: the one its board divides into (itself for SAME).
61
+ export function partsBoardOf(ctx, board) {
62
+ const split = board.def.split;
63
+ if (!split)
64
+ return undefined;
65
+ return split.board === SAME ? board : liveBoardById(ctx, split.board);
66
+ }
67
+ // Another item as a wait reads it: its board and, while open, its step, by name. `blocking`: read
68
+ // as a blocker or a part, whose work must be in before the item waiting for it goes on: a Done item
69
+ // whose protected branch is not merged yet (on a board with no land step, where Done is merged
70
+ // already) still holds it, as `unmerged`.
71
+ function linkedOf(ctx, id, waited = false) {
72
+ const item = requireItem(ctx.db, id);
73
+ const board = liveBoardOf(ctx, item.collection);
74
+ if (!board) {
75
+ const closed = closesOf(workflowOf(ctx, item), item.state) !== undefined;
76
+ return { id, board: item.collection, ...(closed ? {} : { step: item.state }), closed };
77
+ }
78
+ const position = positionOf(item.state);
79
+ if (isClosed(position)) {
80
+ if (waited && waitsToMerge(ctx, board, item))
81
+ return { id, board: board.def.name, closed: false, unmerged: true };
82
+ return { id, board: board.def.name, closed: true };
83
+ }
84
+ const step = stepById(board.def, position.step)?.name ?? position.step;
85
+ return { id, board: board.def.name, step, closed: false };
86
+ }
87
+ // An item's parts (its children, on any board), what blocks it and what it blocks, oldest first.
88
+ export function linksOf(ctx, id) {
89
+ const relations = selectRelationsOf(ctx.db, id);
90
+ const into = (kind) => relations
91
+ .filter((r) => r.kind === kind && r.to === id)
92
+ .map(({ from }) => linkedOf(ctx, from, true));
93
+ return {
94
+ parts: into('parent'),
95
+ blockers: into('blocks'),
96
+ blocking: relations
97
+ .filter((r) => r.kind === 'blocks' && r.from === id)
98
+ .map(({ to }) => linkedOf(ctx, to)),
99
+ };
100
+ }
101
+ // The approval that started the round of the step being done, when the reviewer said something
102
+ // with it (P6-11): its note, who, when and the review it came from.
103
+ function approvedOf(def, position, history) {
104
+ if (isClosed(position) || position.phase !== 'doing')
105
+ return undefined;
106
+ const index = history.moves.length - 1;
107
+ const move = history.moves[index];
108
+ const said = history.said[index];
109
+ if (!move || !said?.text?.trim())
110
+ return undefined;
111
+ const from = positionOf(move.from);
112
+ const to = positionOf(move.to);
113
+ if (isClosed(from) || from.phase !== 'review' || isClosed(to) || to.step !== position.step)
114
+ return undefined;
115
+ if (from.step === position.step)
116
+ return undefined;
117
+ return {
118
+ note: said.text,
119
+ by: { kind: said.by.kind, name: said.by.name },
120
+ at: move.at,
121
+ step: stepById(def, from.step)?.name ?? from.step,
122
+ round: roundAfter(def, history, from.step, index),
123
+ };
124
+ }
125
+ // The send-back that started the round of the step being done, with its note, who sent it, when
126
+ // and the review it came from; undefined when the round began any other way.
127
+ function sentBackOf(def, position, history) {
128
+ if (isClosed(position) || position.phase !== 'doing')
129
+ return undefined;
130
+ const reopened = reopenedAt(history.moves, position.step);
131
+ const reopen = history.moves[reopened];
132
+ const why = history.said[reopened];
133
+ if (reopen && why) {
134
+ return {
135
+ note: why.text ?? '',
136
+ by: { kind: why.by.kind, name: why.by.name },
137
+ at: reopen.at,
138
+ step: closedName(def, positionOf(reopen.from)),
139
+ round: roundAfter(def, history, position.step, reopened + 1),
140
+ reopened: true,
141
+ };
142
+ }
143
+ const index = sentBackAt(def, history.moves, position.step);
144
+ const move = history.moves[index];
145
+ const said = history.said[index];
146
+ if (!move || !said)
147
+ return undefined;
148
+ const from = positionOf(move.from);
149
+ if (isClosed(from))
150
+ return undefined;
151
+ return {
152
+ note: said.text ?? '',
153
+ by: { kind: said.by.kind, name: said.by.name },
154
+ at: move.at,
155
+ step: stepById(def, from.step)?.name ?? from.step,
156
+ round: roundAfter(def, history, from.step, index),
157
+ };
158
+ }
159
+ // What an agent does while doing a step, short of handing it off: taking the item, attaching its
160
+ // evidence, changing its fields.
161
+ const STEP_WORK = new Set(['evidence_added', 'updated']);
162
+ // The agents that did the step the item stands in, in its current round (since `since`): each one
163
+ // that handed the item off out of the step's doing or, while the item stood in that doing,
164
+ // attached evidence to it or changed its fields (the step's work, even when another agent handed
165
+ // it off). Claiming it and letting it go untouched is not work: that agent may still review it. Work of an earlier round, or done in another step, does not count. None of them
166
+ // reviews the step, nor relays the decision on it.
167
+ function roundWorkers(position, events, since) {
168
+ if (isClosed(position) || since === undefined)
169
+ return [];
170
+ const doing = (state) => {
171
+ const at = positionOf(String(state));
172
+ return !isClosed(at) && at.step === position.step && at.phase === 'doing';
173
+ };
174
+ const out = new Set();
175
+ let state;
176
+ for (const event of events) {
177
+ const before = state;
178
+ if (event.type === 'created')
179
+ state = event.data.state;
180
+ if (event.type === 'transitioned')
181
+ state = event.data.to;
182
+ if (event.at < since || event.actor.kind !== 'agent')
183
+ continue;
184
+ const moved = event.type === 'transitioned' && doing(event.data.from);
185
+ if (moved || (STEP_WORK.has(event.type) && doing(before)))
186
+ out.add(event.actor.name);
187
+ }
188
+ return [...out];
189
+ }
190
+ // The moves a board item offers as the engine reads the item: a way on that a lead that holds
191
+ // leaves out is no move, and the ways it keeps come in the engine's order (the lead first), so the
192
+ // page's primary takes the lead (P4-R3-1). The rest of the moves stay as the workflow lists them.
193
+ export function boardMoves(ctx, item, moves) {
194
+ const board = liveBoardOf(ctx, item.collection);
195
+ const position = positionOf(item.state);
196
+ if (!board || isClosed(position))
197
+ return [...moves];
198
+ const step = stepById(board.def, position.step);
199
+ if (!step?.lead)
200
+ return [...moves];
201
+ const all = waysOf(board.def, step.id);
202
+ const kept = waysOf(board.def, step.id, { fields: item.fields });
203
+ const on = moves.filter(({ to }) => all.includes(to));
204
+ const ordered = kept.flatMap((way) => on.filter(({ to }) => to === way));
205
+ let next = 0;
206
+ return moves.flatMap((move) => {
207
+ if (!all.includes(move.to))
208
+ return [move];
209
+ const taken = ordered[next++];
210
+ return taken === undefined ? [] : [taken];
211
+ });
212
+ }
213
+ // The item as the engine reads it: its fields (title included), its evidence by part and when, the
214
+ // rounds of each step, read from its moves, its parts and what blocks it, the note of each round
215
+ // handed off, and the send-back its current round started with.
216
+ export function itemOnBoard(ctx, item, def) {
217
+ const position = positionOf(item.state);
218
+ const events = selectEvents(ctx.db, item.id);
219
+ const history = historyFor(item, def, events);
220
+ const rounds = roundsOf(def, history.initial, history.createdAt, history.moves);
221
+ const evidence = selectEvidence(ctx.db, item.id).flatMap((entry) => entry.module === null ? [] : [{ part: entry.module, at: entry.createdAt }]);
222
+ const step = isClosed(position) ? undefined : position.step;
223
+ const startedAt = step === undefined ? undefined : rounds.startedAt[step];
224
+ const links = linksOf(ctx, item.id);
225
+ const sentBack = sentBackOf(def, position, history);
226
+ const approved = sentBack === undefined ? approvedOf(def, position, history) : undefined;
227
+ const round = step === undefined ? 0 : (rounds.rounds[step] ?? 1);
228
+ const thread = notesOf(events);
229
+ const roundNotes = notesOfRound(thread, step, round);
230
+ const unanswered = isClosed(position) || position.phase !== 'doing' ? [] : unansweredOf(roundNotes);
231
+ const questions = questionsOf(events);
232
+ const roundQuestions = questions.filter((q) => q.step === step && q.round === round);
233
+ const asking = isClosed(position) || position.phase !== 'doing' ? undefined : openQuestion(events);
234
+ const did = roundWorkers(position, events, startedAt);
235
+ const proofs = step === undefined ? [] : proofsFrom(events, startedAt);
236
+ const chosen = choiceOf(events);
237
+ const facts = {
238
+ fields: { ...item.fields, title: item.title },
239
+ evidence,
240
+ ...(startedAt === undefined ? {} : { roundStartedAt: startedAt }),
241
+ ...(sentBack === undefined ? {} : { sentBack: true }),
242
+ parts: links.parts,
243
+ blockers: links.blockers,
244
+ ...(unanswered.length === 0 ? {} : { unanswered }),
245
+ ...(did.length === 0 ? {} : { did }),
246
+ ...(proofs.length === 0 ? {} : { proofs: provedPoints(proofs) }),
247
+ };
248
+ const notes = handoffNotes(def, history).map(({ step: id, round: n, note, at, by }) => ({
249
+ step: stepById(def, id)?.name ?? id,
250
+ round: n,
251
+ note,
252
+ at,
253
+ by: by.name,
254
+ }));
255
+ return {
256
+ position,
257
+ facts,
258
+ rounds,
259
+ round,
260
+ notes,
261
+ links,
262
+ ...(sentBack === undefined ? {} : { sentBack }),
263
+ ...(approved === undefined ? {} : { approved }),
264
+ thread,
265
+ roundNotes,
266
+ questions,
267
+ roundQuestions,
268
+ ...(asking === undefined ? {} : { asking }),
269
+ proofs,
270
+ ...(chosen === undefined ? {} : { chosen }),
271
+ };
272
+ }
273
+ // The checklists of the board that ask for proof, and those with a point proved anyway, each point with whether it is ticked and the
274
+ // proof it has in the round.
275
+ function provedChecklists(def, fields, proofs) {
276
+ return Object.values(def.parts)
277
+ .filter((part) => part.kind === 'check' &&
278
+ (part.proof === true || proofs.some((one) => one.part === part.id)))
279
+ .map((part) => {
280
+ const ticked = new Set(tickedOf(fields[part.id]));
281
+ return {
282
+ part: part.id,
283
+ name: part.name,
284
+ asks: part.proof === true,
285
+ points: part.options.map(({ id, name }) => {
286
+ const proof = proofs.find((one) => one.part === part.id && one.point === id);
287
+ return { id, name, ticked: ticked.has(id), ...(proof === undefined ? {} : { proof }) };
288
+ }),
289
+ };
290
+ });
291
+ }
292
+ function tickedOf(value) {
293
+ if (Array.isArray(value))
294
+ return value.map(String);
295
+ if (typeof value !== 'string' || value.trim() === '')
296
+ return [];
297
+ try {
298
+ const parsed = JSON.parse(value);
299
+ return Array.isArray(parsed) ? parsed.map(String) : [];
300
+ }
301
+ catch {
302
+ return [];
303
+ }
304
+ }
305
+ // Who did a closed item's work and who approved it: the last agent that handed the item off out of
306
+ // a step's doing, and the last one that moved it out of a review (or, for a step nobody reviews
307
+ // that the person closed, the person). An agent that only landed it (the land step) did not do it.
308
+ // When the last step's work was the person's own (a step they do), they did it, not an agent that
309
+ // handed it to them before (P4-R3-3).
310
+ function closedByOf(def, events) {
311
+ const out = {};
312
+ for (const event of events) {
313
+ if (event.type !== 'transitioned')
314
+ continue;
315
+ const from = positionOf(String(event.data.from));
316
+ if (isClosed(from))
317
+ continue;
318
+ const landing = isLandStep(def, from.step);
319
+ if (from.phase === 'doing' && event.actor.kind === 'agent' && !landing) {
320
+ out.doer = event.actor.name;
321
+ if (event.profile)
322
+ out.doerProfile = event.profile;
323
+ else
324
+ delete out.doerProfile;
325
+ delete out.doneByPerson;
326
+ }
327
+ const theirs = stepById(def, from.step)?.doer === 'you';
328
+ if (from.phase === 'doing' && event.actor.kind === 'human' && theirs && !landing) {
329
+ delete out.doer;
330
+ delete out.doerProfile;
331
+ out.doneByPerson = true;
332
+ }
333
+ if (from.phase === 'review')
334
+ out.reviewer = event.actor;
335
+ }
336
+ const last = events.findLast(({ type }) => type === 'transitioned');
337
+ if (!out.reviewer && last?.actor.kind === 'human')
338
+ out.reviewer = last.actor;
339
+ return out;
340
+ }
341
+ // The agent doing the item's step now: the one holding its lease (even run out); none on a step the
342
+ // person does, nobody holds, or off a doing phase.
343
+ export function workerOf(ctx, item, def, at = systemClock()) {
344
+ const position = positionOf(item.state);
345
+ if (isClosed(position) || position.phase !== 'doing')
346
+ return undefined;
347
+ const step = stepById(def, position.step);
348
+ if (!step || step.doer === 'you')
349
+ return undefined;
350
+ const name = item.lease?.holder;
351
+ if (name === undefined)
352
+ return undefined;
353
+ const holds = activeLease(item.lease, at)?.holder === name;
354
+ return { name, lastSeen: findAgent(ctx.db, name)?.lastSeen ?? null, holds };
355
+ }
356
+ function filled(value) {
357
+ return typeof value === 'string' && value.trim() !== '';
358
+ }
359
+ export function boardBlockOf(ctx, item) {
360
+ const board = liveBoardOf(ctx, item.collection);
361
+ if (!board)
362
+ return undefined;
363
+ const on = itemOnBoard(ctx, item, board.def);
364
+ const guarded = guardedBranch(board.def);
365
+ const value = guarded ? item.fields[guarded.id] : undefined;
366
+ const repo = guarded?.guard.repo === undefined ? undefined : item.fields[guarded.guard.repo];
367
+ const gate = (action) => gateAt(board.def, on.position, action);
368
+ const request = draftRequestOf(ctx, item.id);
369
+ const worker = workerOf(ctx, item, board.def);
370
+ const events = selectEvents(ctx.db, item.id);
371
+ const merged = mergedFrom(events);
372
+ const checklists = provedChecklists(board.def, item.fields, on.proofs);
373
+ return {
374
+ parts: on.links.parts,
375
+ partsBoard: partsBoardOf(ctx, board)?.def.name ?? null,
376
+ blockers: on.links.blockers,
377
+ blocking: on.links.blocking,
378
+ notes: on.notes,
379
+ gates: guarded ? { push: gate('push'), merge: gate('merge') } : null,
380
+ branch: filled(value) ? { value, ...(filled(repo) ? { repo } : {}) } : null,
381
+ missing: isClosed(on.position) || on.position.phase !== 'doing'
382
+ ? []
383
+ : handoffCheck(board.def, on.position.step, on.facts).missing,
384
+ ...(on.sentBack === undefined ? {} : { sentBack: on.sentBack }),
385
+ ...(request === undefined ? {} : { request }),
386
+ ...(on.thread.length === 0 ? {} : { thread: on.thread }),
387
+ ...(on.questions.length === 0 ? {} : { questions: on.questions }),
388
+ ...(on.asking === undefined ? {} : { asking: on.asking }),
389
+ ...(on.chosen === undefined ? {} : { chosen: on.chosen }),
390
+ ...(worker === undefined ? {} : { worker }),
391
+ ...(isClosed(on.position) ? { closedBy: closedByOf(board.def, events) } : {}),
392
+ ...(merged === undefined ? {} : { merged }),
393
+ ...(on.proofs.length === 0 ? {} : { proofs: on.proofs }),
394
+ ...(checklists.length === 0 ? {} : { checklists }),
395
+ };
396
+ }
397
+ // The round of the step an item is on, as the engine counts it (what `otea next` says); undefined
398
+ // off a board, 0 once closed. `boards` lets a list read the live boards once.
399
+ export function boardRoundOf(ctx, item, boards = liveBoards(ctx)) {
400
+ const board = boards.find(({ collection }) => collection === item.collection);
401
+ if (!board)
402
+ return undefined;
403
+ // A closed item is in no round: 0, so no list falls back to counting rounds across its steps.
404
+ if (isClosed(positionOf(item.state)))
405
+ return 0;
406
+ return itemOnBoard(ctx, item, board.def).round;
407
+ }
408
+ export function rowFactsOf(ctx, item, boards = liveBoards(ctx)) {
409
+ const board = boards.find(({ collection }) => collection === item.collection);
410
+ if (!board || !isClosed(positionOf(item.state)))
411
+ return {};
412
+ const events = selectEvents(ctx.db, item.id);
413
+ const { doer, doerProfile } = closedByOf(board.def, events);
414
+ const out = doer ? { doer, ...(doerProfile ? { doerProfile } : {}) } : {};
415
+ if (waitsToMerge(ctx, board, item))
416
+ out.merge = 'waiting';
417
+ else if (mergedFrom(events))
418
+ out.merge = 'merged';
419
+ return out;
420
+ }
421
+ // `next`'s text for one item, as the agent `me` reads it; undefined off a board.
422
+ export function itemNextText(ctx, item, me, now = systemClock) {
423
+ const board = liveBoardOf(ctx, item.collection);
424
+ if (!board)
425
+ return undefined;
426
+ return textFor(ctx, item, board.def, now(), me);
427
+ }
428
+ // The agent the person left a stuck item for (Reasignar), while no agent has claimed or moved it
429
+ // since; undefined otherwise.
430
+ export function leftFor(ctx, id) {
431
+ const last = selectEvents(ctx.db, id).findLast(({ type }) => ['claimed', 'released', 'transitioned'].includes(type));
432
+ if (last?.type !== 'released' || last.actor.kind !== 'human')
433
+ return undefined;
434
+ const { cause, next } = last.data;
435
+ return cause === 'reassign' && typeof next === 'string' ? next : undefined;
436
+ }
437
+ // The agent that last let go of the item (otea release), and why, while it has not moved, been
438
+ // claimed nor had its set-aside lifted since; undefined otherwise.
439
+ function agentRelease(ctx, id) {
440
+ const last = selectEvents(ctx.db, id).findLast(({ type }) => ['claimed', 'released', 'transitioned', SET_ASIDE_LIFTED].includes(type));
441
+ if (last?.type !== 'released' || last.actor.kind !== 'agent')
442
+ return undefined;
443
+ return { agent: last.actor.name, cause: last.data.cause };
444
+ }
445
+ // The agent that set the item aside for later (otea release --later), while nothing lifted it
446
+ // (app/set-aside.ts); undefined otherwise.
447
+ export function setAsideBy(ctx, id) {
448
+ return setAsideOf(selectEvents(ctx.db, id))?.by;
449
+ }
450
+ // Why the item cannot be set aside for later now: it is not agent work right now (P7-R3-1). It
451
+ // waits for its parts or what blocks it, or for the person (their turn, or their answer to a
452
+ // question): next offers it again on its own then, and a set-aside would only hide it once it is
453
+ // back. Undefined when it is agent work.
454
+ export function setAsideRefusal(ctx, item) {
455
+ const board = liveBoardOf(ctx, item.collection);
456
+ const turn = turnOf(workflowOf(ctx, item), item.state);
457
+ const position = positionOf(item.state);
458
+ const where = board ? placeText(board.def, position) : item.state;
459
+ const nothing = 'nothing to set aside.';
460
+ if (turn === 'none')
461
+ return new OteaError('item_closed', `${item.id} is closed (${where}): ${nothing}`);
462
+ if (turn !== 'agent')
463
+ return new OteaError('not_claimable', `${item.id} is in ${where}, on the person’s turn: otea next offers it again once it is back on an agent’s; ${nothing}`);
464
+ if (!board || isClosed(position))
465
+ return undefined;
466
+ const on = itemOnBoard(ctx, item, board.def);
467
+ if (on.asking)
468
+ return new OteaError('not_claimable', `${item.id} waits for the person’s answer to ${on.asking.by}’s question: otea next offers it again once they answer; ${nothing}`);
469
+ const step = stepById(board.def, position.step);
470
+ if (position.phase !== 'doing' || step === undefined)
471
+ return undefined;
472
+ for (const wait of openWaits(step, on.facts)) {
473
+ const open = (wait.open ?? []).filter(({ unmerged }) => !unmerged).map(({ id }) => id);
474
+ if (open.length === 0)
475
+ continue;
476
+ const what = wait.ref === WAIT_PARTS ? 'its parts' : 'what blocks it';
477
+ return new OteaError(wait.ref === WAIT_PARTS ? 'children_open' : 'blockers_open', `${item.id} waits for ${what} (${open.join(', ')}): otea next offers it again once they close; ${nothing}`);
478
+ }
479
+ return undefined;
480
+ }
481
+ // Why the item, agent work now, is not set aside for later: the person may want it now (P7-R3-8).
482
+ // A note of theirs waits for an answer; or they took it up again after an agent set it aside, and
483
+ // asked nothing since: only their newer words, relayed (`quote`), set it aside again. Undefined
484
+ // when it may be set aside.
485
+ export function wantedNowRefusal(ctx, item, quote) {
486
+ const board = liveBoardOf(ctx, item.collection);
487
+ const position = positionOf(item.state);
488
+ if (board && !isClosed(position) && position.phase === 'doing') {
489
+ const open = itemOnBoard(ctx, item, board.def).roundNotes.filter(({ answer }) => !answer);
490
+ if (open.length > 0)
491
+ return new OteaError('invalid_transition', laterNotesRefusal(item.id, open));
492
+ }
493
+ const retake = retakeOf(selectEvents(ctx.db, item.id));
494
+ if (!retake || quote)
495
+ return undefined;
496
+ return new OteaError('invalid_transition', `Not set aside ${item.id}: the person took it up again (${retakeText(retake)}) after ${retake.by} set it aside: do it now. If they asked you since to leave it for later, relay their words: otea release ${item.id} --later --quote "<the person's words>"`);
497
+ }
498
+ // What next and show say while the person took the item up again (P5-R3-8): an agent that had
499
+ // heard «leave it for later» held off, unsure its set-aside had held.
500
+ export function retakeLine(ctx, id) {
501
+ const retake = retakeOf(selectEvents(ctx.db, id));
502
+ return retake ? `The person took it up again (${retakeText(retake)}): do it now.` : undefined;
503
+ }
504
+ // What otea wait adds to the item it wakes an agent for (P7-R3-8, P5-R3-8): that the person took
505
+ // it up again, and their notes still unanswered in the round, in their words, with the reply. Its
506
+ // row alone said neither, and the agent set the item aside again.
507
+ export function wokeLines(ctx, id) {
508
+ const item = findItem(ctx.db, id);
509
+ const board = item && liveBoardOf(ctx, item.collection);
510
+ const position = item && positionOf(item.state);
511
+ if (!item || !board || !position || isClosed(position))
512
+ return [];
513
+ const on = itemOnBoard(ctx, item, board.def);
514
+ const retake = retakeLine(ctx, id);
515
+ const open = position.phase === 'doing' ? on.roundNotes.filter(({ answer }) => !answer) : [];
516
+ return [...(retake ? [retake] : []), ...notesBlock(id, open)];
517
+ }
518
+ // Once an item closes, what waited for it as a part or a blocker and stood aside for later is
519
+ // agent work again: its set-aside lifts, saying so (P7-R3-1). It waited until now, so the agent
520
+ // that set it aside was waiting for exactly this.
521
+ export function liftWhenWaitsClose(ctx, closed, actor, at) {
522
+ for (const relation of selectRelationsOf(ctx.db, closed)) {
523
+ if (relation.from !== closed || (relation.kind !== 'parent' && relation.kind !== 'blocks'))
524
+ continue;
525
+ const waiting = findItem(ctx.db, relation.to);
526
+ if (!waiting || setAsideBy(ctx, waiting.id) === undefined)
527
+ continue;
528
+ const board = liveBoardOf(ctx, waiting.collection);
529
+ const position = positionOf(waiting.state);
530
+ if (!board || isClosed(position) || position.phase !== 'doing')
531
+ continue;
532
+ const kind = relation.kind === 'parent' ? 'parts' : 'blockers';
533
+ if (!stepById(board.def, position.step)?.waits.includes(kind))
534
+ continue;
535
+ if (waitsOpen(board.def, itemOnBoard(ctx, waiting, board.def)))
536
+ continue;
537
+ liftSetAside(ctx.db, { id: waiting.id, actor, at, cause: kind }, { after: closed });
538
+ }
539
+ }
540
+ // What next and wait add when they offer an agent the item it just let go of: a plain release
541
+ // leaves it free, so it comes straight back, and the agent stopped waiting, then polled on its
542
+ // own (P3C-R3-2). Undefined for any other item.
543
+ export function laterLine(ctx, id, agent) {
544
+ const released = agentRelease(ctx, id);
545
+ if (released?.agent !== agent || released.cause !== 'release')
546
+ return undefined;
547
+ return `You released ${id}: if the person asked you to leave it for later, otea release ${id} --later sets it aside, so next and wait skip it; then keep waiting with otea wait, never a polling loop of your own.`;
548
+ }
549
+ // On a Pedido an agent drafts a board on, how to hand the draft in follows the instructions of the
550
+ // step it stands on: the agent reads it where it reads any step's, apart from the person's words.
551
+ function withHandIn(ctx, item, def, me) {
552
+ const position = positionOf(item.state);
553
+ if (isClosed(position))
554
+ return def;
555
+ const request = draftRequestOf(ctx, item.id, me);
556
+ if (!request || request.published)
557
+ return def;
558
+ const steps = def.steps.map((step) => {
559
+ if (step.id !== position.step)
560
+ return step;
561
+ const take = [step.instructions.take.trim(), request.instructions].filter(Boolean).join('\n\n');
562
+ // Handing the draft in is the handoff: the step asks for nothing otea handoff would carry.
563
+ return { ...step, hand: [], instructions: { ...step.instructions, take } };
564
+ });
565
+ return { ...def, steps };
566
+ }
567
+ // The item `id` is part of, as next names it: its title, board and step (no step once closed).
568
+ function parentOf(ctx, id) {
569
+ const relation = selectRelationsOf(ctx.db, id).find((r) => r.kind === 'parent' && r.from === id);
570
+ const item = relation ? findItem(ctx.db, relation.to) : undefined;
571
+ if (!relation || !item)
572
+ return undefined;
573
+ const linked = linkedOf(ctx, relation.to);
574
+ return {
575
+ id: item.id,
576
+ title: item.title,
577
+ board: linked.board,
578
+ ...(linked.closed || linked.step === undefined ? {} : { step: linked.step }),
579
+ };
580
+ }
581
+ // What the item `id` implements (`id implements X`), as next names a parent: title, board and step.
582
+ function implementedBy(ctx, id) {
583
+ return selectRelationsOf(ctx.db, id)
584
+ .filter((r) => r.kind === 'implements' && r.from === id)
585
+ .flatMap(({ to }) => {
586
+ const item = findItem(ctx.db, to);
587
+ if (!item)
588
+ return [];
589
+ const linked = linkedOf(ctx, to);
590
+ return [
591
+ {
592
+ id: item.id,
593
+ title: item.title,
594
+ board: linked.board,
595
+ ...(linked.closed || linked.step === undefined ? {} : { step: linked.step }),
596
+ },
597
+ ];
598
+ });
599
+ }
600
+ function textFor(ctx, item, live, at, me) {
601
+ const def = withHandIn(ctx, item, live, me);
602
+ const on = itemOnBoard(ctx, item, def);
603
+ const lease = activeLease(item.lease, at);
604
+ const left = leftFor(ctx, item.id);
605
+ const counts = {};
606
+ for (const { part } of on.facts.evidence)
607
+ counts[part] = (counts[part] ?? 0) + 1;
608
+ const missing = isClosed(on.position)
609
+ ? []
610
+ : handoffCheck(def, on.position.step, on.facts).missing;
611
+ const board = liveBoardOf(ctx, item.collection);
612
+ const child = board ? partsBoardOf(ctx, board) : undefined;
613
+ const planned = isClosed(on.position) ? undefined : plannedBy(ctx, item);
614
+ const merged = isClosed(on.position) ? mergedFrom(selectEvents(ctx.db, item.id)) : undefined;
615
+ const stepName = isClosed(on.position) ? undefined : stepById(def, on.position.step)?.name;
616
+ const handed = on.notes.findLast(({ step, round }) => step === stepName && round === on.round);
617
+ const parent = parentOf(ctx, item.id);
618
+ const implemented = implementedBy(ctx, item.id);
619
+ const order = priorityOf(ctx.db).get(item.id);
620
+ // What the person approved of its branch, for the land step to name (P3C-R3-1).
621
+ const guard = guardedBranch(def);
622
+ const named = guard ? String(item.fields[guard.id] ?? '').trim() : '';
623
+ const tip = named === '' ? undefined : approvedTipOf(ctx, item.id, named);
624
+ // A Pedido whose board draft is still to hand in (withHandIn gave its step the instructions).
625
+ const handIn = def === live
626
+ ? undefined
627
+ : {
628
+ after: 'Done, once the person tries the board and publishes it in Studio',
629
+ command: handInCommand(item.id, me ?? item.lease?.holder ?? '<your name>'),
630
+ };
631
+ const retaken = isClosed(on.position) ? undefined : retakeLine(ctx, item.id);
632
+ return nextText(def, {
633
+ id: item.id,
634
+ title: item.title,
635
+ position: on.position,
636
+ round: on.round,
637
+ fields: item.fields,
638
+ evidence: counts,
639
+ missing,
640
+ parts: on.links.parts,
641
+ blockers: on.links.blockers,
642
+ ...(child === undefined ? {} : { child: child.def }),
643
+ ...(me === undefined ? {} : { me }),
644
+ ...(on.sentBack === undefined ? {} : { sentBack: on.sentBack }),
645
+ ...(on.approved === undefined ? {} : { approved: on.approved }),
646
+ ...(tip && !tip.unchanged ? { approvedTip: tip.commit.slice(0, 7) } : {}),
647
+ ...(on.facts.did === undefined ? {} : { did: on.facts.did }),
648
+ ...(lease ? { holder: { name: lease.holder, expiresAt: lease.expiresAt } } : {}),
649
+ ...(left === undefined ? {} : { leftFor: left }),
650
+ ...(planned === undefined ? {} : { plannedBy: planned }),
651
+ ...(parent === undefined ? {} : { parent }),
652
+ ...(implemented.length === 0 ? {} : { implements: implemented }),
653
+ ...(handed === undefined ? {} : { handed: { note: handed.note, by: handed.by } }),
654
+ ...(merged === undefined ? {} : { merged }),
655
+ ...(on.roundNotes.length === 0 ? {} : { notes: on.roundNotes }),
656
+ ...(on.roundQuestions.length === 0 ? {} : { questions: on.roundQuestions }),
657
+ ...(on.chosen === undefined ? {} : { chosen: on.chosen }),
658
+ ...(order && (order.pin !== undefined || order.rank !== undefined) ? { order } : {}),
659
+ ...(handIn ? { handIn } : {}),
660
+ ...(retaken === undefined ? {} : { retaken }),
661
+ });
662
+ }
663
+ // The agent whose question the person answered in this round, while it has done nothing on the
664
+ // item since: the item stays its own, though its lease ran out while the person thought, so the
665
+ // answer reaches the agent that asked it, never another one. Once its session is no longer alive,
666
+ // nobody would read it there: the item is any agent's again (P3C-R3-11, P7-R3-11).
667
+ export function answeredFor(ctx, item, on, now = systemClock()) {
668
+ const answered = on.roundQuestions.findLast((q) => q.answer);
669
+ const at = answered?.answer?.at;
670
+ if (!answered || at === undefined)
671
+ return undefined;
672
+ // It acted since, or the person freed the item for any agent (Retomar, Reasignar).
673
+ const done = selectEvents(ctx.db, item.id).some((event) => event.at > at &&
674
+ ((event.actor.kind === 'agent' && event.actor.name === answered.by) ||
675
+ (event.actor.kind === 'human' && event.type === 'released')));
676
+ if (done || !sessionAlive(ctx.db, answered.by, () => now))
677
+ return undefined;
678
+ return answered.by;
679
+ }
680
+ // Whether the item is the agent's to take now (mayTakeNow), and, on a land step, its turn to land
681
+ // in its base (app/land-order.ts, P1-R3-2).
682
+ function isTheirs(ctx, def, item, agent, at) {
683
+ return mayTakeNow(ctx, def, item, agent, at) && landTurnFor(ctx, item, agent, at) === undefined;
684
+ }
685
+ // What lands in the item's base before it, for the agent; undefined when its turn is now.
686
+ function landTurnFor(ctx, item, agent, at) {
687
+ return landsFirst(ctx, item, agent, at, (board, other) => mayTakeNow(ctx, board.def, other, agent, at));
688
+ }
689
+ // Whether the item is the agent's to take now, whatever else lands first: a doing phase it may
690
+ // take, or a review any agent does that it did not do itself; never one another agent holds, nor
691
+ // one the person left for another agent.
692
+ function mayTakeNow(ctx, def, item, agent, at) {
693
+ const lease = activeLease(item.lease, at);
694
+ if (lease && lease.holder !== agent)
695
+ return false;
696
+ // A lease that ran out while its holder's session runs is still its holder's (P1-R3-6).
697
+ const ranOut = !lease && item.lease && item.lease.holder !== agent ? item.lease : null;
698
+ if (ranOut && sessionRuns(ctx.db, ranOut.holder, () => at))
699
+ return false;
700
+ const position = positionOf(item.state);
701
+ if (isClosed(position))
702
+ return false;
703
+ // A question waits for the person: the turn is theirs until they answer it.
704
+ const on = itemOnBoard(ctx, item, def);
705
+ if (on.asking)
706
+ return false;
707
+ // Their answer goes to the agent that asked it.
708
+ const asker = answeredFor(ctx, item, on, at);
709
+ if (asker !== undefined && asker !== agent)
710
+ return false;
711
+ // Planned work waits for the plan that made it to be approved.
712
+ if (plannedBy(ctx, item))
713
+ return false;
714
+ // What an agent set aside for later waits until it is taken up again: it is the person's wish,
715
+ // so it holds for every agent (P7-R3-6).
716
+ if (setAsideBy(ctx, item.id) !== undefined)
717
+ return false;
718
+ // A step that waits for parts or blockers still being worked on is not the agent's work yet: its
719
+ // handoff cannot pass, and offering it would loop the agent on it (P7-R2-2).
720
+ if (waitsOpen(def, on))
721
+ return false;
722
+ const mine = position.phase === 'doing'
723
+ ? mayTake(def, position.step)
724
+ : stepById(def, position.step)?.reviewer === 'any' &&
725
+ mayReview(def, position, { kind: 'agent', name: agent }, roundWorkersOf(ctx, item, def));
726
+ if (!mine || lease)
727
+ return mine;
728
+ const left = leftFor(ctx, item.id);
729
+ return left === undefined || left === agent;
730
+ }
731
+ // The agents that did the step the item stands in, in its current round.
732
+ export function roundWorkersOf(ctx, item, def) {
733
+ return itemOnBoard(ctx, item, def).facts.did ?? [];
734
+ }
735
+ // How many of the board's open items wait for the person.
736
+ export function waitingForYou(ctx, board) {
737
+ return selectItems(ctx.db, { collection: board.collection }).filter(({ state }) => turnAt(board.def, positionOf(state)).who === 'you').length;
738
+ }
739
+ // For this long after `next` offers an item to an agent, no other agent is offered it, so two
740
+ // agents asking at once never take the same item; claiming it holds it longer.
741
+ export const OFFER_MS = 2 * 60_000;
742
+ // Whether `next` offered the item to another agent a moment ago, in the state it is still in.
743
+ function offeredElsewhere(ctx, agent, at) {
744
+ const offers = selectOffers(ctx.db).filter((offer) => offer.agent !== agent && Date.parse(at) - Date.parse(offer.at) < OFFER_MS);
745
+ // An item the person left for this agent (Reasignar) is its own, whoever was offered it before.
746
+ return (item) => offers.some((offer) => offer.item === item.id && offer.state === item.state) &&
747
+ leftFor(ctx, item.id) !== agent;
748
+ }
749
+ // Whether next could offer the item to the agent now: on a board, it is the agent's to do or
750
+ // review, and neither left for nor just offered to another agent. An item off the boards always is.
751
+ export function offerableTo(ctx, agent, now = systemClock) {
752
+ const at = now();
753
+ const offered = offeredElsewhere(ctx, agent, at);
754
+ const boards = liveBoards(ctx);
755
+ return (item) => {
756
+ const board = boards.find(({ collection }) => collection === item.collection);
757
+ if (!board)
758
+ return true;
759
+ const record = requireItem(ctx.db, item.id);
760
+ return !offered(record) && isTheirs(ctx, board.def, record, agent, at);
761
+ };
762
+ }
763
+ // Whether a Done item of the board waits to be merged: its protected branch is set and not marked
764
+ // merged, on a board with no land step (one with a land step merges in it, before Done).
765
+ function waitsToMerge(ctx, board, item) {
766
+ const branch = guardedBranch(board.def);
767
+ if (!branch || item.state !== DONE)
768
+ return false;
769
+ if (board.def.steps.some((step) => isLandStep(board.def, step.id)))
770
+ return false;
771
+ if (String(item.fields[branch.id] ?? '').trim() === '')
772
+ return false;
773
+ return mergedFrom(selectEvents(ctx.db, item.id)) === undefined;
774
+ }
775
+ // The board's Done items whose protected branch is set and not marked merged yet, oldest first: on a
776
+ // board with no land step an agent merges them once the person approved them, and nothing else
777
+ // offers that work. A board with a land step merges in it, before Done.
778
+ function waitingToMerge(ctx, board) {
779
+ const branch = guardedBranch(board.def);
780
+ if (!branch || board.def.steps.some((step) => isLandStep(board.def, step.id)))
781
+ return [];
782
+ return selectItems(ctx.db, { collection: board.collection, state: DONE }).flatMap((item) => {
783
+ const name = String(item.fields[branch.id] ?? '').trim();
784
+ if (name === '' || mergedFrom(selectEvents(ctx.db, item.id)))
785
+ return [];
786
+ return [{ id: item.id, branch: name }];
787
+ });
788
+ }
789
+ // Whether the step being done waits for its parts and one of them is Done but waits to be merged
790
+ // (`merging`): the merge comes first.
791
+ function waitsForMerges(def, on, merging) {
792
+ const position = on.position;
793
+ if (isClosed(position) || position.phase !== 'doing')
794
+ return false;
795
+ const step = stepById(def, position.step);
796
+ if (!step?.waits.includes('parts'))
797
+ return false;
798
+ return on.links.parts.some(({ id }) => merging.has(id));
799
+ }
800
+ // What next says of an item whose step waits for Done parts still to be merged: merge them first,
801
+ // naming each; undefined for any other item. otea wait says it with the item it woke for, so the
802
+ // agent reads the merge to make there, not only after otea next (P6-R2-9).
803
+ export function mergeFirstFor(ctx, id) {
804
+ const item = requireItem(ctx.db, id);
805
+ const board = liveBoardOf(ctx, item.collection);
806
+ if (!board)
807
+ return undefined;
808
+ const toMerge = liveBoards(ctx).flatMap((each) => waitingToMerge(ctx, each));
809
+ const on = itemOnBoard(ctx, item, board.def);
810
+ if (!waitsForMerges(board.def, on, new Set(toMerge.map(({ id }) => id))))
811
+ return undefined;
812
+ const theirs = toMerge.filter(({ id }) => on.links.parts.some((part) => part.id === id));
813
+ return mergeFirstText(item.id, theirs);
814
+ }
815
+ // Whether the step being done waits for parts or blockers still being worked on: its handoff cannot
816
+ // pass yet. One Done and waiting only to be merged is merge work for an agent (waitsForMerges).
817
+ function waitsOpen(def, on) {
818
+ const position = on.position;
819
+ if (isClosed(position) || position.phase !== 'doing')
820
+ return false;
821
+ const step = stepById(def, position.step);
822
+ if (step === undefined)
823
+ return false;
824
+ return openWaits(step, on.facts).some(({ open }) => open?.some(({ unmerged }) => !unmerged));
825
+ }
826
+ // How far along its board an open item stands: whether it waits for a review, and its step's place.
827
+ function progressOf(def, item) {
828
+ const position = positionOf(item.state);
829
+ if (isClosed(position))
830
+ return { review: false, along: -1 };
831
+ return {
832
+ review: position.phase !== 'doing',
833
+ along: def.steps.findIndex((step) => step.id === position.step),
834
+ };
835
+ }
836
+ // Lower first; two items with no place in an order tie.
837
+ function byOrder(a, b) {
838
+ return a === b ? 0 : a < b ? -1 : 1;
839
+ }
840
+ // With nothing to do: what was set aside for later, the agent's own first, then other agents' (a
841
+ // set-aside holds for every agent, P7-R3-6), and how to take it up again. The first of them in the
842
+ // person's order (on top, then the Matrix order) is named with its place, as the one to take up
843
+ // first (P7-R3-1).
844
+ function setAsideLines(ctx, boards, agent) {
845
+ const aside = boards.flatMap((board) => selectItems(ctx.db, { collection: board.collection }).flatMap((item) => {
846
+ const by = isClosed(positionOf(item.state)) ? undefined : setAsideBy(ctx, item.id);
847
+ return by === undefined ? [] : [{ id: item.id, by }];
848
+ }));
849
+ if (aside.length === 0)
850
+ return [];
851
+ const setters = [...new Set(aside.map(({ by }) => by))].sort((a, b) => Number(b === agent) - Number(a === agent));
852
+ const who = setters
853
+ .map((by) => {
854
+ const theirs = aside.filter((each) => each.by === by).map(({ id }) => id);
855
+ return `${by === agent ? 'You' : by} set aside ${theirs.join(', ')} for later`;
856
+ })
857
+ .join('; ');
858
+ const ids = aside.map(({ id }) => id);
859
+ const priority = priorityOf(ctx.db);
860
+ const placed = ids
861
+ .flatMap((id) => {
862
+ const { pin, rank } = priority.get(id) ?? {};
863
+ return pin === undefined && rank === undefined ? [] : [{ id, pin, rank }];
864
+ })
865
+ .sort((a, b) => byOrder(a.pin ?? Number.POSITIVE_INFINITY, b.pin ?? Number.POSITIVE_INFINITY) ||
866
+ byOrder(a.rank ?? Number.POSITIVE_INFINITY, b.rank ?? Number.POSITIVE_INFINITY));
867
+ const first = placed[0];
868
+ if (first) {
869
+ const said = first.pin !== undefined
870
+ ? `The person put ${first.id} on top (number ${first.pin})`
871
+ : `${first.id} is number ${first.rank} in the order the person fixed on the Matrix`;
872
+ return [`${who}. ${said}: otea claim ${first.id} takes it up again.`];
873
+ }
874
+ const one = ids.length === 1;
875
+ return [`${who}: otea claim ${one ? ids[0] : '<id>'} takes ${one ? 'it' : 'one'} up again.`];
876
+ }
877
+ // With nothing to do: the approved items the agent would land but for another landing first
878
+ // (P1-R3-2), so it knows what it waits for.
879
+ function landingLines(ctx, boards, agent, at) {
880
+ return boards.flatMap((board) => selectItems(ctx.db, { collection: board.collection }).flatMap((item) => {
881
+ if (!mayTakeNow(ctx, board.def, item, agent, at))
882
+ return [];
883
+ const first = landTurnFor(ctx, item, agent, at);
884
+ return first ? [landsFirstLine(item.id, first)] : [];
885
+ }));
886
+ }
887
+ // With nothing to do while other agents hold the boards' work (P6-18): who holds what, and how two
888
+ // agents share a board, so the idle one neither waits blind nor takes over what another holds.
889
+ function heldElsewhere(ctx, boards, agent, at) {
890
+ const held = new Map();
891
+ for (const board of boards) {
892
+ for (const item of selectItems(ctx.db, { collection: board.collection })) {
893
+ const lease = activeLease(item.lease, at);
894
+ if (!lease || lease.holder === agent)
895
+ continue;
896
+ held.set(lease.holder, [...(held.get(lease.holder) ?? []), item.id]);
897
+ }
898
+ }
899
+ if (held.size === 0)
900
+ return [];
901
+ const who = [...held].map(([holder, ids]) => `${holder} holds ${ids.join(', ')}`).join('; ');
902
+ return [
903
+ `${who} now. Two agents share a board by taking different items: ask the person for more, or to split a big one into parts, which next then offers you; never work on an item another agent holds.`,
904
+ ];
905
+ }
906
+ // The item the agent should take, and its text: one it holds first, then what was sent back to it,
907
+ // then what the person pinned and the order they fixed, then reviews and work furthest along, then
908
+ // the oldest waiting; never one another agent holds or was just offered. With `claim`, the
909
+ // agent claims it in the same transaction, so no other agent can take it between the two. When
910
+ // there is none: that, once, each board's words for idle time and its cap, and how to wait.
911
+ export function nextFor(ctx, agent, options = {}, now = systemClock) {
912
+ const { collection } = options;
913
+ const named = collection === undefined ? undefined : collectionNamed(ctx.db, collection);
914
+ const boards = liveBoards(ctx).filter((board) => named === undefined || board.collection === named);
915
+ if (options.collection !== undefined && boards.length === 0) {
916
+ throw new OteaError('not_found', `There is no published board on collection "${options.collection}"`);
917
+ }
918
+ return transaction(ctx.db, () => {
919
+ const at = now();
920
+ const entered = selectStateEntries(ctx.db);
921
+ const since = (item) => entered.get(item.id) ?? item.createdAt;
922
+ const offered = offeredElsewhere(ctx, agent, at);
923
+ const priority = priorityOf(ctx.db);
924
+ // The Done items whose branch waits to be merged: an agent merges them before the step of an
925
+ // item that waits for them as its parts, and next keeps naming them under what it offers.
926
+ const toMerge = liveBoards(ctx).flatMap((board) => waitingToMerge(ctx, board));
927
+ const merging = new Set(toMerge.map(({ id }) => id));
928
+ const pinOf = (item) => priority.get(item.id)?.pin ?? Number.POSITIVE_INFINITY;
929
+ const rankOf = (item) => priority.get(item.id)?.rank ?? Number.POSITIVE_INFINITY;
930
+ const candidates = boards.flatMap((board) => selectItems(ctx.db, { collection: board.collection })
931
+ .filter((item) => !offered(item) && isTheirs(ctx, board.def, item, agent, at))
932
+ .map((item) => {
933
+ const on = itemOnBoard(ctx, item, board.def);
934
+ return {
935
+ item,
936
+ board,
937
+ held: activeLease(item.lease, at) !== null,
938
+ left: leftFor(ctx, item.id) === agent,
939
+ returned: on.sentBack !== undefined,
940
+ merges: waitsForMerges(board.def, on, merging),
941
+ ...progressOf(board.def, item),
942
+ };
943
+ }));
944
+ // What the agent holds, then what the person left for it (Reasignar), then what was sent back
945
+ // to it; then anything that can move on before a step that waits for its parts to be merged;
946
+ // then what the person put on top, then the order they fixed (app/priority.ts); then work
947
+ // already handed on comes before new work: a review, then the step furthest along (its earlier
948
+ // steps are approved), and only then the oldest. A step that waits for what is still open is
949
+ // never offered (isTheirs).
950
+ candidates.sort((a, b) => Number(b.held) - Number(a.held) ||
951
+ Number(b.left) - Number(a.left) ||
952
+ Number(b.returned) - Number(a.returned) ||
953
+ Number(a.merges) - Number(b.merges) ||
954
+ byOrder(pinOf(a.item), pinOf(b.item)) ||
955
+ byOrder(rankOf(a.item), rankOf(b.item)) ||
956
+ Number(b.review) - Number(a.review) ||
957
+ b.along - a.along ||
958
+ since(a.item).localeCompare(since(b.item)) ||
959
+ a.item.createdAt.localeCompare(b.item.createdAt));
960
+ const first = candidates[0];
961
+ if (!first) {
962
+ // Pedidos, there on every project, is named only once something was asked on it.
963
+ const used = boards.filter((board) => !findBoardOfCollection(ctx.db, board.collection)?.builtin ||
964
+ selectItems(ctx.db, { collection: board.collection }).length > 0);
965
+ const idle = (used.length > 0 ? used : boards).map((board) => {
966
+ const toMerge = waitingToMerge(ctx, board);
967
+ return {
968
+ def: board.def,
969
+ waitingForYou: waitingForYou(ctx, board),
970
+ ...(toMerge.length === 0 ? {} : { toMerge }),
971
+ };
972
+ });
973
+ return {
974
+ item: null,
975
+ collection: options.collection ?? null,
976
+ text: [
977
+ idleText(idle),
978
+ ...setAsideLines(ctx, boards, agent),
979
+ ...landingLines(ctx, boards, agent, at),
980
+ ...heldElsewhere(ctx, boards, agent, at),
981
+ ].join('\n\n'),
982
+ idle: true,
983
+ };
984
+ }
985
+ if (first.merges) {
986
+ const { links } = itemOnBoard(ctx, first.item, first.board.def);
987
+ const theirs = toMerge.filter(({ id }) => links.parts.some((part) => part.id === id));
988
+ return {
989
+ item: null,
990
+ collection: options.collection ?? null,
991
+ text: mergeFirstText(first.item.id, theirs),
992
+ };
993
+ }
994
+ const { board } = first;
995
+ const lease = options.claim
996
+ ? takeItem(ctx.db, first.item, { kind: 'agent', name: agent }, at)
997
+ : (activeLease(first.item.lease, at) ?? undefined);
998
+ const item = lease ? { ...first.item, lease } : first.item;
999
+ if (!lease)
1000
+ saveOffer(ctx.db, { agent, item: item.id, state: item.state, at });
1001
+ const { sentBack, roundNotes } = itemOnBoard(ctx, item, board.def);
1002
+ const later = laterLine(ctx, item.id, agent);
1003
+ return {
1004
+ item: item.id,
1005
+ collection: board.collection,
1006
+ text: [
1007
+ textFor(ctx, item, board.def, at, agent),
1008
+ ...mergeLines(toMerge),
1009
+ ...(later === undefined ? [] : [later]),
1010
+ ].join('\n'),
1011
+ ...(sentBack === undefined ? {} : { sentBack }),
1012
+ ...(lease ? { lease } : {}),
1013
+ ...(roundNotes.length === 0 ? {} : { notes: roundNotes }),
1014
+ };
1015
+ });
1016
+ }
1017
+ function requireBoard(ctx, item) {
1018
+ const board = liveBoardOf(ctx, item.collection);
1019
+ if (!board)
1020
+ throw new OteaError('invalid_transition', `${item.id} is on collection "${item.collection}", which is not a published board; use otea move`);
1021
+ return board;
1022
+ }
1023
+ function wayOf(def, position, id, way) {
1024
+ if (way === undefined || isClosed(position))
1025
+ return undefined;
1026
+ const target = wayByName(def, position.step, way);
1027
+ if (target === undefined)
1028
+ refuseWay(def, id, position, way);
1029
+ return target;
1030
+ }
1031
+ // A way the step does not have, refused with the ways it has (on, and back while it is done).
1032
+ function refuseWay(def, id, position, way, facts) {
1033
+ if (isClosed(position))
1034
+ throw new OteaError('invalid_transition', `${id} is closed`, { kind: 'no_way', item: id });
1035
+ const reviewing = position.phase !== 'doing';
1036
+ const name = (target) => targetName(def, target);
1037
+ const text = noWayText(def, id, position.step, way, reviewing, facts);
1038
+ throw new OteaError('invalid_transition', text, {
1039
+ kind: 'no_way',
1040
+ item: id,
1041
+ way,
1042
+ step: name(position.step),
1043
+ ways: waysOf(def, position.step, facts).map(name),
1044
+ back: reviewing ? [] : backWaysOf(def, position.step).map(name),
1045
+ });
1046
+ }
1047
+ const PHASE_WORDS = {
1048
+ not_doing: 'is not being worked on: it waits for a review or is closed',
1049
+ not_review: 'is not waiting for a review',
1050
+ unknown_step: 'stands in a step the board no longer has',
1051
+ };
1052
+ function refuse(def, item, result,
1053
+ // The way the mover asked for, as it named it.
1054
+ tried, facts) {
1055
+ if (result.code === 'missing')
1056
+ refuseHandoff(item.id, result.missing);
1057
+ if (result.code === 'reason_required')
1058
+ throw new OteaError('reason_required', NOT_TAKEN_BACK, {
1059
+ kind: 'way_back_reason',
1060
+ item: item.id,
1061
+ });
1062
+ if (result.code === 'bad_way')
1063
+ refuseWay(def, item.id, positionOf(item.state), tried ?? 'that way', facts);
1064
+ if (result.code === 'not_yours') {
1065
+ const position = positionOf(item.state);
1066
+ const step = isClosed(position) ? undefined : stepById(def, position.step);
1067
+ throw new OteaError('forbidden', `Not your turn: the person does ${step?.name ?? 'this step'} on ${item.id}`, {
1068
+ kind: 'not_your_turn',
1069
+ item: item.id,
1070
+ review: false,
1071
+ ...(step ? { step: step.name } : {}),
1072
+ });
1073
+ }
1074
+ // assertReviewer refuses an agent's review of its own round before the engine is asked.
1075
+ if (result.code === 'own_work')
1076
+ throw new Error('own work reached the engine unchecked');
1077
+ throw new OteaError('invalid_transition', `${item.id} ${PHASE_WORDS[result.code] ?? result.code}`, { kind: 'not_here', item: item.id, why: result.code });
1078
+ }
1079
+ // An agent's handoff while its question waits for the person: the turn is theirs.
1080
+ function refuseAsking(id, asking) {
1081
+ throw new OteaError('invalid_transition', `Not handed off ${id}: the question to the person waits for their answer ("${asking.text}"), and otea wait --turn agent wakes you when they answer; if they answered in the chat, put their words on it: otea answer ${id} "<their words>"`, { kind: 'question', item: id, why: 'asking' });
1082
+ }
1083
+ // A handoff that lacks what its step asks for, or whose waits do not hold.
1084
+ function refuseHandoff(id, missing) {
1085
+ throw new OteaError(refusalCode(missing), refusalText(id, missing), {
1086
+ kind: 'handoff',
1087
+ item: id,
1088
+ missing,
1089
+ });
1090
+ }
1091
+ // An approval whose waits no longer hold (a part reopened, a blocker added during the review).
1092
+ function refuseApproval(item, result) {
1093
+ if (result.code !== 'missing')
1094
+ throw new Error('not an approval refusal');
1095
+ throw new OteaError(refusalCode(result.missing), approvalRefusalText(item.id, result.missing), {
1096
+ kind: 'approval',
1097
+ item: item.id,
1098
+ missing: result.missing,
1099
+ });
1100
+ }
1101
+ // Whether the performer reviews the item now: any agent but the one that did the round, on a step
1102
+ // any agent reviews; the person for their own reviews (an agent relays those with otea relay, never
1103
+ // approves them).
1104
+ function assertReviewer(ctx, def, item, actor) {
1105
+ const position = positionOf(item.state);
1106
+ if (isClosed(position) || position.phase === 'doing')
1107
+ return;
1108
+ if (mayReview(def, position, actor, roundWorkersOf(ctx, item, def)))
1109
+ return;
1110
+ if (turnAt(def, position).who === 'agent')
1111
+ refuseOwnWork(def, item, actor.name);
1112
+ const step = stepById(def, position.step);
1113
+ throw new OteaError('forbidden', `Not your turn: the person reviews ${step?.name ?? 'this step'} on ${item.id}`, {
1114
+ kind: 'not_your_turn',
1115
+ item: item.id,
1116
+ review: true,
1117
+ ...(step ? { step: step.name } : {}),
1118
+ });
1119
+ }
1120
+ // An agent reviewing a step it did in that round: another agent reviews it.
1121
+ function refuseOwnWork(def, item, who) {
1122
+ const position = positionOf(item.state);
1123
+ const step = isClosed(position) ? position.closed : stepById(def, position.step)?.name;
1124
+ const name = step ?? 'this step';
1125
+ throw new OteaError('forbidden', `Not your review: ${who} did ${name} on ${item.id} in this round, so another agent reviews it; pick another item (otea next)`, { kind: 'own_review', item: item.id, step: name, who });
1126
+ }
1127
+ function land(ctx, item, board, to, input, at) {
1128
+ const lease = activeLease(item.lease, at);
1129
+ const reviewed = !isClosed(to) && to.phase !== 'doing';
1130
+ const data = {
1131
+ ...(input.reason ? { reason: input.reason } : {}),
1132
+ ...(input.note?.trim() ? { note: input.note } : {}),
1133
+ ...(input.tip && reviewed ? { tip: input.tip } : {}),
1134
+ channel: input.channel,
1135
+ };
1136
+ return landMove(ctx, workflowOf(ctx, item), item, { to: stateOf(to), actor: input.actor, at, lease, board: true }, data);
1137
+ }
1138
+ // The agent that just handed a step off changes its note while the review still waits (P3C-11):
1139
+ // otea handoff again with --note. Only the round's own handoff, by the agent that made it.
1140
+ function amendHandoff(ctx, item, board, input, at) {
1141
+ const position = positionOf(item.state);
1142
+ const note = input.note?.trim();
1143
+ if (!note || isClosed(position) || position.phase !== 'review' || input.actor.kind !== 'agent')
1144
+ return undefined;
1145
+ const last = selectEvents(ctx.db, item.id)
1146
+ .filter(({ type }) => type === 'transitioned')
1147
+ .at(-1);
1148
+ if (!last || String(last.data.to) !== item.state)
1149
+ return undefined;
1150
+ if (last.actor.kind !== 'agent' || last.actor.name !== input.actor.name)
1151
+ return undefined;
1152
+ appendEvent(ctx.db, {
1153
+ itemId: item.id,
1154
+ type: HANDOFF_AMENDED,
1155
+ actor: input.actor,
1156
+ at,
1157
+ data: { note, channel: input.channel },
1158
+ });
1159
+ const name = stepById(board.def, position.step)?.name ?? position.step;
1160
+ return {
1161
+ item: getItem(ctx, item.id),
1162
+ text: `Changed the note of the handoff of ${item.id} (${name}); it still waits for its review.`,
1163
+ };
1164
+ }
1165
+ // A handoff from the doing phase: refused, in the agent's words, while something required is
1166
+ // missing (its parts, the note, what it waits for); otherwise to the review, or along the way
1167
+ // picked. A way back to an earlier step takes only a reason, and starts that step's next round.
1168
+ export function handoffItem(ctx, input, now = systemClock) {
1169
+ return transaction(ctx.db, () => {
1170
+ const item = requireWritableItem(ctx.db, input.id);
1171
+ const board = requireBoard(ctx, item);
1172
+ const at = now();
1173
+ const amended = amendHandoff(ctx, item, board, input, at);
1174
+ if (amended)
1175
+ return amended;
1176
+ const lease = activeLease(item.lease, at);
1177
+ assertMayWriteItem(ctx.db, item, input.actor, at);
1178
+ // An agent that holds no lease on it never hands off an item left for or just offered to
1179
+ // another agent; whether the step is an agent's at all, the handoff itself answers.
1180
+ if (input.actor.kind === 'agent' && !lease)
1181
+ assertMayHandOff(ctx, item, input.actor.name, at);
1182
+ const on = itemOnBoard(ctx, item, board.def);
1183
+ if (on.asking && input.actor.kind === 'agent')
1184
+ refuseAsking(item.id, on.asking);
1185
+ const way = wayOf(board.def, on.position, item.id, input.way);
1186
+ const by = { kind: input.actor.kind, name: input.actor.name };
1187
+ // A step that asks for a note (or a round sent back) reads the reason when no note is given,
1188
+ // as a move does.
1189
+ const step = isClosed(on.position) ? undefined : stepById(board.def, on.position.step);
1190
+ const wanted = step?.note.req === 'always' || on.facts.sentBack === true;
1191
+ const asked = way === undefined && wanted && !input.note?.trim();
1192
+ const note = asked && input.reason?.trim() ? input.reason : input.note;
1193
+ const facts = note === undefined ? on.facts : { ...on.facts, note };
1194
+ const result = handoff(board.def, on.position, facts, {
1195
+ by,
1196
+ ...(way === undefined ? {} : { way }),
1197
+ ...(input.reason === undefined ? {} : { reason: input.reason }),
1198
+ });
1199
+ if (!result.ok)
1200
+ refuse(board.def, item, result, input.way, facts);
1201
+ const moved = land(ctx, item, board, result.to, { ...input, ...(note ? { note } : {}) }, at);
1202
+ if (result.back && !isClosed(result.to)) {
1203
+ const round = itemOnBoard(ctx, requireItem(ctx.db, item.id), board.def).round;
1204
+ return { item: moved, text: takenBackText(board.def, item.id, result.to.step, round) };
1205
+ }
1206
+ return { item: moved, text: handedText(board.def, item.id, result.to) };
1207
+ });
1208
+ }
1209
+ // An approval from a review, along the way picked or the default; what the step waits for is
1210
+ // checked again.
1211
+ export function approveItem(ctx, input, now = systemClock) {
1212
+ return transaction(ctx.db, () => {
1213
+ const item = requireWritableItem(ctx.db, input.id);
1214
+ const board = requireBoard(ctx, item);
1215
+ const at = now();
1216
+ const position = positionOf(item.state);
1217
+ assertReviewer(ctx, board.def, item, input.actor);
1218
+ const way = wayOf(board.def, position, item.id, input.way);
1219
+ const facts = itemOnBoard(ctx, item, board.def).facts;
1220
+ const result = approve(board.def, position, way, facts, input.actor);
1221
+ if (!result.ok) {
1222
+ if (result.code === 'missing')
1223
+ refuseApproval(item, result);
1224
+ if (result.code === 'own_work')
1225
+ refuseOwnWork(board.def, item, input.actor.name);
1226
+ refuse(board.def, item, result, input.way);
1227
+ }
1228
+ const moved = land(ctx, item, board, result.to, input, at);
1229
+ return { item: moved, text: handedText(board.def, item.id, result.to, 'Approved') };
1230
+ });
1231
+ }
1232
+ // Whether the review open on an item holds comments of the person: a send-back goes with them as
1233
+ // what to change, with no words of its own needed.
1234
+ function reviewCommented(ctx, item) {
1235
+ const board = liveBoardOf(ctx, item.collection);
1236
+ if (!board)
1237
+ return false;
1238
+ const on = itemOnBoard(ctx, item, board.def);
1239
+ if (isClosed(on.position) || on.position.phase !== 'review')
1240
+ return false;
1241
+ const { step } = on.position;
1242
+ return on.thread.some((note) => note.review !== undefined && note.step === step && note.round === on.round);
1243
+ }
1244
+ // A move from the review back to a doing step, while the review holds the person's comments: the
1245
+ // page's Devolver, which then needs no words of its own.
1246
+ export function backWithComments(ctx, item, to) {
1247
+ const target = positionOf(to);
1248
+ return !isClosed(target) && target.phase === 'doing' && reviewCommented(ctx, item);
1249
+ }
1250
+ // A send-back from a review (the person's Devolver, an agent reviewer's Pedir otra ronda): the item
1251
+ // goes back to the step's `back` for its next round, with why.
1252
+ export function sendBackItem(ctx, input, now = systemClock) {
1253
+ return transaction(ctx.db, () => {
1254
+ const item = requireWritableItem(ctx.db, input.id);
1255
+ // The review comments are what to change: with some, the send-back needs no words of its own.
1256
+ if (!input.reason?.trim() && !reviewCommented(ctx, item))
1257
+ throw new OteaError('reason_required', `Sending ${input.id} back needs a reason: what to change`, { kind: 'send_back_reason', item: input.id });
1258
+ const board = requireBoard(ctx, item);
1259
+ const at = now();
1260
+ const position = positionOf(item.state);
1261
+ assertReviewer(ctx, board.def, item, input.actor);
1262
+ const did = roundWorkersOf(ctx, item, board.def);
1263
+ const result = sendBack(board.def, position, { by: input.actor, did });
1264
+ if (!result.ok && result.code === 'own_work')
1265
+ refuseOwnWork(board.def, item, input.actor.name);
1266
+ if (!result.ok)
1267
+ refuse(board.def, item, result);
1268
+ const moved = land(ctx, item, board, result.to, input, at);
1269
+ if (isClosed(result.to))
1270
+ return { item: moved, text: handedText(board.def, item.id, result.to) };
1271
+ const round = itemOnBoard(ctx, requireItem(ctx.db, item.id), board.def).round;
1272
+ return { item: moved, text: sentBackText(board.def, item.id, result.to.step, round) };
1273
+ });
1274
+ }
1275
+ const DROP_CODES = {
1276
+ not_open: 'item_closed',
1277
+ reason_required: 'reason_required',
1278
+ motive_required: 'reason_required',
1279
+ not_droppable: 'forbidden',
1280
+ not_relayable: 'not_relayable',
1281
+ };
1282
+ // The motive a reader names (`--motive "Duplicado"`, or its id); undefined when it names none.
1283
+ export function motiveByName(def, name) {
1284
+ if (name === undefined)
1285
+ return undefined;
1286
+ const wanted = name.trim().toLocaleLowerCase();
1287
+ return def.drop.motives.find(({ id, name: said }) => id === name.trim() || said.trim().toLocaleLowerCase() === wanted)?.id;
1288
+ }
1289
+ function dropTarget(board, item, input) {
1290
+ const via = input.via ?? (input.actor.kind === 'agent' ? 'agent' : 'page');
1291
+ const motive = motiveByName(board.def, input.motive);
1292
+ const result = drop(board.def, positionOf(item.state), {
1293
+ by: { kind: input.actor.kind, name: input.actor.name },
1294
+ via,
1295
+ ...(input.reason === undefined ? {} : { reason: input.reason }),
1296
+ ...(motive === undefined ? {} : { motive }),
1297
+ });
1298
+ if (!result.ok)
1299
+ throw new OteaError(DROP_CODES[result.code], dropRefusalText(board.def, item.id, result.code), {
1300
+ kind: 'drop',
1301
+ item: item.id,
1302
+ board: board.def.name,
1303
+ why: result.code,
1304
+ motives: board.def.drop.motives.map(({ name }) => name),
1305
+ });
1306
+ return result.to;
1307
+ }
1308
+ // A discard (otea drop): always with a reason, with one of the board's motives when it has any; an
1309
+ // agent drops only while doing a step that lets it, a relay only where the person may discard
1310
+ // through an agent.
1311
+ export function dropItem(ctx, input, now = systemClock) {
1312
+ return transaction(ctx.db, () => {
1313
+ const item = requireWritableItem(ctx.db, input.id);
1314
+ const board = requireBoard(ctx, item);
1315
+ const at = now();
1316
+ if (input.actor.kind === 'agent' && input.via !== 'relay')
1317
+ assertMayWriteItem(ctx.db, item, input.actor, at);
1318
+ const to = dropTarget(board, item, input);
1319
+ const moved = land(ctx, item, board, to, input, at);
1320
+ return { item: moved, text: droppedText(board.def, item.id, to) };
1321
+ });
1322
+ }
1323
+ // Whether a move into `target` from a review approves it: on to a later step or to Hecho.
1324
+ function approves(def, from, target) {
1325
+ if (isClosed(from) || from.phase === 'doing')
1326
+ return false;
1327
+ if (isClosed(target))
1328
+ return target.closed === DONE;
1329
+ return target.phase === 'doing' && stepIndex(def, target.step) > stepIndex(def, from.step);
1330
+ }
1331
+ // An agent's move along the compiled workflow is one of the engine's moves, checked as the engine
1332
+ // checks it: from a doing phase, the handoff this agent would make (into its review, yours when
1333
+ // the agent reviews the step itself, along a way, or back to an earlier step) or its own drop;
1334
+ // from a review, an approval or a send-back by the step's reviewer. So otea move cannot walk
1335
+ // around who may act.
1336
+ function assertAgentMove(ctx, board, item, to, actor, words) {
1337
+ const on = itemOnBoard(ctx, item, board.def);
1338
+ const target = positionOf(to);
1339
+ const position = on.position;
1340
+ if (isClosed(position))
1341
+ return;
1342
+ if (isClosed(target) && target.closed === DROPPED) {
1343
+ const motive = target.motive;
1344
+ dropTarget(board, item, {
1345
+ actor,
1346
+ channel: 'cli',
1347
+ ...(words.reason === undefined ? {} : { reason: words.reason }),
1348
+ ...(motive === undefined ? {} : { motive }),
1349
+ });
1350
+ return;
1351
+ }
1352
+ if (position.phase === 'doing') {
1353
+ const way = isClosed(target)
1354
+ ? target.closed === DONE
1355
+ ? DONE
1356
+ : undefined
1357
+ : target.step === position.step
1358
+ ? undefined
1359
+ : target.step;
1360
+ const note = words.note ?? words.reason;
1361
+ const result = handoff(board.def, position, note === undefined ? on.facts : { ...on.facts, note }, {
1362
+ by: { kind: 'agent', name: actor.name },
1363
+ ...(way === undefined ? {} : { way }),
1364
+ ...(words.reason === undefined ? {} : { reason: words.reason }),
1365
+ });
1366
+ if (!result.ok)
1367
+ refuse(board.def, item, result, stateName(board.def, to), on.facts);
1368
+ if (stateOf(result.to) === to)
1369
+ return;
1370
+ const step = stepById(board.def, position.step);
1371
+ const into = result.to;
1372
+ const name = step?.name ?? position.step;
1373
+ throw new OteaError('invalid_transition', `${item.id} cannot go to ${stateName(board.def, to)}: a handoff from ${name} goes to ${stateName(board.def, stateOf(into))}; use otea handoff ${item.id}`);
1374
+ }
1375
+ assertReviewer(ctx, board.def, item, actor);
1376
+ if (approves(board.def, position, target)) {
1377
+ const result = approve(board.def, position, undefined, on.facts);
1378
+ if (!result.ok && result.code === 'missing')
1379
+ refuseApproval(item, result);
1380
+ }
1381
+ }
1382
+ // A move along the compiled workflow is checked as the engine checks it, whoever makes it: a
1383
+ // handoff (into the step's review, or out of a step nobody reviews) needs what the step asks, its
1384
+ // note included (the move's note, or its reason), and what it waits for; an approval re-checks the
1385
+ // waits; a discard goes through drop(). Returns the note the move carries, to keep with its round.
1386
+ export function assertMoveHandsOff(ctx, item, to, actor, words = {}) {
1387
+ const board = liveBoardOf(ctx, item.collection);
1388
+ if (!board)
1389
+ return undefined;
1390
+ const from = positionOf(item.state);
1391
+ const step = isClosed(from) ? undefined : stepById(board.def, from.step);
1392
+ const sentBack = itemOnBoard(ctx, item, board.def).sentBack !== undefined;
1393
+ const note = noteFor(board.def, step, from, positionOf(to), words, sentBack);
1394
+ if (actor?.kind === 'agent') {
1395
+ assertAgentMove(ctx, board, item, to, actor, words);
1396
+ return note;
1397
+ }
1398
+ const target = positionOf(to);
1399
+ if (isClosed(from) || !step)
1400
+ return note;
1401
+ if (isClosed(target) && target.closed === DROPPED) {
1402
+ const motive = target.motive;
1403
+ dropTarget(board, item, {
1404
+ actor: actor ?? { kind: 'human', name: 'you' },
1405
+ channel: 'ui',
1406
+ via: words.via ?? 'page',
1407
+ ...(words.reason === undefined ? {} : { reason: words.reason }),
1408
+ ...(motive === undefined ? {} : { motive }),
1409
+ });
1410
+ return note;
1411
+ }
1412
+ const on = itemOnBoard(ctx, item, board.def);
1413
+ if (from.phase !== 'doing') {
1414
+ if (!approves(board.def, from, target))
1415
+ return note;
1416
+ const result = approve(board.def, from, undefined, on.facts);
1417
+ if (!result.ok && result.code === 'missing')
1418
+ refuseApproval(item, result);
1419
+ return note;
1420
+ }
1421
+ const intoReview = !isClosed(target) && target.phase !== 'doing' && target.step === step.id;
1422
+ const along = step.reviewer === 'none' &&
1423
+ (isClosed(target)
1424
+ ? target.closed === DONE
1425
+ : stepIndex(board.def, target.step) > stepIndex(board.def, step.id));
1426
+ if (!intoReview && !along)
1427
+ return note;
1428
+ // A way the item may not take now: a lead that holds leaves the next step out (P4-R3-1).
1429
+ const way = isClosed(target) ? DONE : target.step;
1430
+ if (along && !waysOf(board.def, step.id, on.facts).includes(way))
1431
+ refuseWay(board.def, item.id, from, stateName(board.def, to), on.facts);
1432
+ // The person's own notes wait for the agent's answer, never for the person.
1433
+ const { unanswered: _notes, ...theirs } = on.facts;
1434
+ const facts = note === undefined ? theirs : { ...theirs, note };
1435
+ const check = handoffCheck(board.def, step.id, facts);
1436
+ if (!check.ok)
1437
+ refuseHandoff(item.id, check.missing);
1438
+ return note;
1439
+ }
1440
+ // The note a move hands off with: the one given, or, on a step that asks for a note (or a round
1441
+ // sent back), its reason; none for a discard or a way back (their reason is theirs).
1442
+ function noteFor(def, step, from, to, words, sentBack) {
1443
+ if (!step || isClosed(from) || from.phase !== 'doing')
1444
+ return undefined;
1445
+ if (isClosed(to) ? to.closed !== DONE : stepIndex(def, to.step) < stepIndex(def, step.id))
1446
+ return undefined;
1447
+ if (words.note?.trim())
1448
+ return words.note;
1449
+ if (step.note.req !== 'always' && !sentBack)
1450
+ return undefined;
1451
+ return words.reason?.trim() ? words.reason : undefined;
1452
+ }
1453
+ // An item of a board that is always part of another's is refused without a parent.
1454
+ export function assertMayStandAlone(ctx, collection, parent) {
1455
+ const board = liveBoardOf(ctx, collection);
1456
+ if (!board || parent !== undefined)
1457
+ return;
1458
+ const owner = requiredParent(liveBoards(ctx), board.id);
1459
+ if (owner)
1460
+ throw new OteaError('parent_required', parentRequiredText(board.def, owner.def), {
1461
+ kind: 'parent_required',
1462
+ item: board.def.item,
1463
+ parent: owner.def.item,
1464
+ });
1465
+ }
1466
+ // Where a new item starts on the board a collection is on (undefined off a board): the first
1467
+ // step, or the next one when the first is skipped for an item created with everything it asks.
1468
+ export function boardStart(ctx, collection, fields) {
1469
+ const board = liveBoardOf(ctx, collection);
1470
+ if (!board)
1471
+ return undefined;
1472
+ return stateOf(initialPosition(board.def, { fields, evidence: [] }).position);
1473
+ }
1474
+ // What otea create says of a new item on a board: where it starts, and why when its first step was
1475
+ // skipped or still lacks what it asks for.
1476
+ export function createdTextOf(ctx, item) {
1477
+ const board = liveBoardOf(ctx, item.collection);
1478
+ if (!board)
1479
+ return undefined;
1480
+ const on = itemOnBoard(ctx, item, board.def);
1481
+ const missing = isClosed(on.position)
1482
+ ? []
1483
+ : handoffCheck(board.def, on.position.step, on.facts).missing;
1484
+ return createdText(board.def, item.id, on.position, missing);
1485
+ }
1486
+ // Fields a reader typed by name on a board (`--field Tamaño=Una`) as the item stores them; on a
1487
+ // collection still on a preset, as given.
1488
+ export function boardFieldInput(ctx, collection, fields) {
1489
+ const board = liveBoardOf(ctx, collection);
1490
+ if (!board || Object.keys(fields).length === 0)
1491
+ return fields;
1492
+ return readFieldInput(board.def, fields);
1493
+ }
1494
+ // An agent cannot move the protected branch (or the repository it is read from) away from the
1495
+ // gate: once the branch is set, it changes only while a step that pushes it is being done, never in
1496
+ // its review or at a step that does not push it, where pushes and merges stay refused.
1497
+ export function assertBranchMayChange(ctx, item, changes, actor) {
1498
+ if (actor.kind !== 'agent')
1499
+ return;
1500
+ const board = liveBoardOf(ctx, item.collection);
1501
+ const branch = board ? guardedBranch(board.def) : undefined;
1502
+ if (!board || !branch)
1503
+ return;
1504
+ const position = positionOf(item.state);
1505
+ if (gateAt(board.def, position, 'push').allowed)
1506
+ return;
1507
+ const keys = [branch.id, ...(branch.guard.repo === undefined ? [] : [branch.guard.repo])];
1508
+ const moved = keys.filter((key) => {
1509
+ const was = item.fields[key];
1510
+ return key in changes && was !== undefined && was !== '' && changes[key] !== was;
1511
+ });
1512
+ const first = moved[0];
1513
+ if (first === undefined)
1514
+ return;
1515
+ const name = board.def.parts[first]?.name ?? first;
1516
+ const pushers = branch.guard.push.map((id) => stepById(board.def, id)?.name ?? id).join(', ');
1517
+ throw new OteaError('forbidden', `Not updated ${item.id}: its ${name} is frozen here; it can change only while ${pushers} is being done.`, {
1518
+ kind: 'frozen',
1519
+ item: item.id,
1520
+ part: name,
1521
+ steps: branch.guard.push.map((id) => stepById(board.def, id)?.name ?? id),
1522
+ });
1523
+ }
1524
+ // The state a reader names on a board (a step's name, `Done`), as the workflow's state.
1525
+ export function boardState(ctx, collection, to) {
1526
+ const board = liveBoardOf(ctx, collection);
1527
+ return board ? stateByName(board.def, to) : to;
1528
+ }
1529
+ // The evidence part a reader names on a board (`--module Bocetos`), as its module id.
1530
+ export function boardModule(ctx, collection, module) {
1531
+ const board = liveBoardOf(ctx, collection);
1532
+ return board ? evidenceByName(board.def, module) : module;
1533
+ }
1534
+ // An agent claims only what is its own on a board: a step it may take, or a review it does.
1535
+ // The item a planned item waits for, if any: what it implements (or, for a sub-item, what its
1536
+ // parent waits for), while that item is open and still in the step it stood in when the plan was
1537
+ // linked. A step that waits for its parts never holds them, which would hold both forever.
1538
+ export function plannedBy(ctx, item, seen = new Set()) {
1539
+ if (seen.has(item.id))
1540
+ return undefined;
1541
+ seen.add(item.id);
1542
+ for (const relation of selectRelationsOf(ctx.db, item.id)) {
1543
+ if (relation.from !== item.id)
1544
+ continue;
1545
+ if (relation.kind === 'parent') {
1546
+ const held = plannedBy(ctx, requireItem(ctx.db, relation.to), seen);
1547
+ if (held)
1548
+ return held;
1549
+ continue;
1550
+ }
1551
+ if (relation.kind !== 'implements')
1552
+ continue;
1553
+ const plan = requireItem(ctx.db, relation.to);
1554
+ const board = liveBoardOf(ctx, plan.collection);
1555
+ const position = positionOf(plan.state);
1556
+ if (!board || isClosed(position))
1557
+ continue;
1558
+ const step = stepById(board.def, position.step);
1559
+ if (!step || step.waits.includes('parts'))
1560
+ continue;
1561
+ const then = selectEvents(ctx.db, plan.id)
1562
+ .filter(({ type, at }) => (type === 'created' || type === 'transitioned') && at <= relation.createdAt)
1563
+ .at(-1);
1564
+ const state = then?.type === 'created' ? then.data.state : then?.data.to;
1565
+ if (typeof state !== 'string')
1566
+ continue;
1567
+ const was = positionOf(state);
1568
+ if (!isClosed(was) && was.step === position.step)
1569
+ return { id: plan.id, step: step.name };
1570
+ }
1571
+ return undefined;
1572
+ }
1573
+ // The agent that claimed the item last while it stands where it is: none once it moved or was
1574
+ // released since.
1575
+ function lastClaimer(ctx, id) {
1576
+ const last = selectEvents(ctx.db, id).findLast(({ type }) => ['claimed', 'released', 'transitioned'].includes(type));
1577
+ return last?.type === 'claimed' && last.actor.kind === 'agent' ? last.actor.name : undefined;
1578
+ }
1579
+ function assertMayHandOff(ctx, item, agent, at) {
1580
+ const left = leftFor(ctx, item.id);
1581
+ if (left !== undefined && left !== agent) {
1582
+ throw new OteaError('not_claimable', `${item.id} was left for ${left}; hand off only what is yours (otea next)`);
1583
+ }
1584
+ // Another agent claimed it in this step: its lease may have run out, the work is still its own.
1585
+ const claimer = lastClaimer(ctx, item.id);
1586
+ if (left === undefined && claimer !== undefined && claimer !== agent) {
1587
+ throw new OteaError('not_claimable', `${item.id} was claimed by ${claimer}; hand off only what is yours (otea next)`);
1588
+ }
1589
+ const offer = offeredElsewhere(ctx, agent, at);
1590
+ if (left === undefined && offer(item)) {
1591
+ throw new OteaError('not_claimable', `${item.id} was just offered to another agent; hand off only what is yours (otea next)`);
1592
+ }
1593
+ }
1594
+ export function assertMayClaim(ctx, item, agent, at = systemClock()) {
1595
+ const board = liveBoardOf(ctx, item.collection);
1596
+ if (!board)
1597
+ return;
1598
+ const position = positionOf(item.state);
1599
+ if (isClosed(position))
1600
+ return;
1601
+ const step = stepById(board.def, position.step);
1602
+ if (!step)
1603
+ return;
1604
+ const left = leftFor(ctx, item.id);
1605
+ if (left !== undefined && left !== agent) {
1606
+ throw new OteaError('not_claimable', `${item.id} was left for ${left}; claim only what is yours (otea next)`);
1607
+ }
1608
+ const planned = plannedBy(ctx, item);
1609
+ if (planned) {
1610
+ throw new OteaError('not_claimable', `${item.id} waits for ${planned.id}, which planned it, to leave ${planned.step}; claim only what is yours (otea next)`);
1611
+ }
1612
+ // While a question waits, and once answered until the agent that asked it reads the answer, the
1613
+ // item stays with that agent.
1614
+ const on = itemOnBoard(ctx, item, board.def);
1615
+ const asking = on.asking;
1616
+ if (asking && asking.by !== agent) {
1617
+ throw new OteaError('not_claimable', `${item.id} waits for the person to answer ${asking.by}'s question; claim only what is yours (otea next)`);
1618
+ }
1619
+ const asker = answeredFor(ctx, item, on, at);
1620
+ if (asker !== undefined && asker !== agent) {
1621
+ throw new OteaError('not_claimable', `${item.id} waits for ${asker} to read the person's answer to its question; claim only what is yours (otea next)`);
1622
+ }
1623
+ if (position.phase === 'doing') {
1624
+ if (!mayTake(board.def, step.id))
1625
+ throw new OteaError('not_claimable', `${item.id} is at ${step.name}, which the person does; claim only what is yours (otea next)`);
1626
+ const first = landTurnFor(ctx, item, agent, at);
1627
+ if (first)
1628
+ throw new OteaError('not_claimable', landsFirstText(item.id, first));
1629
+ return;
1630
+ }
1631
+ const did = roundWorkersOf(ctx, item, board.def);
1632
+ if (mayReview(board.def, position, { kind: 'agent', name: agent }, did))
1633
+ return;
1634
+ const who = step.reviewer === 'any' ? 'another agent' : 'the person';
1635
+ const own = did.includes(agent) ? ' (you did it in this round)' : '';
1636
+ throw new OteaError('not_claimable', `${item.id} waits for ${who} to review ${step.name}${own}; claim only what is yours (otea next)`);
1637
+ }