@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,1116 @@
1
+ import { PERSON_READER } from '../item.js';
2
+ import { timeText } from '../time.js';
3
+ import { mappedScales, rolePart, viewsOf } from './analysis.js';
4
+ import { backTarget, backWaysOf, gateAt, isClosed, isLandStep, landStepOf, NOTE_REF, NOTES_REF, reopenStep, startsWith, WAIT_BLOCKERS, WAIT_PARTS, waysOf, whenHolds, } from './engine.js';
5
+ import { mentionText } from './mentions.js';
6
+ import { LEVEL_SAID, TITLE_NAME, YES_NO_SAID } from './template-words.js';
7
+ // The language the board was made in (reading.ts's langOf, which reads next.ts): its values are
8
+ // given to the agent in it, as the board stores and accepts them.
9
+ const boardLangOf = (def) => (def.title === TITLE_NAME.es ? 'es' : 'en');
10
+ import { choiceLines } from './choices.js';
11
+ import { DONE, guardedBranch, isEvidence, LEVELS, motiveById, partOf, stepById, usedRefs, } from './model.js';
12
+ import { notesBlock, notesHandLine, notesRefusal } from './notes.js';
13
+ import { answersBlock, waitingAnswerText } from './questions.js';
14
+ // The one writer of what an agent reads: `next`'s answer for an item at a step, the refusal of a
15
+ // handoff and the line after one. Studio's "Lo que lee el agente" calls the same functions on the
16
+ // draft, so the preview is the real text. Agents read English, as the CLI and the API speak it; the
17
+ // board's own words (names, hints, instructions) appear as the person typed them.
18
+ export const DONE_NAME = 'Done';
19
+ export const DROPPED_NAME = 'Dropped';
20
+ // The note's hint when the round was sent back and the step itself asks for no note.
21
+ export const SENT_BACK_HINT = 'what you changed since it was sent back';
22
+ // Another agent's say on the item keeps the asking agent off it: a live lease it does not hold, or
23
+ // a stuck item the person left for someone else.
24
+ function heldElsewhere(input) {
25
+ const { me, holder, leftFor, plannedBy } = input;
26
+ if (me === undefined)
27
+ return undefined;
28
+ if (plannedBy)
29
+ return `Waits for ${plannedBy.id}, which planned it, to leave ${plannedBy.step}: pick another item.`;
30
+ if (holder && holder.name !== me)
31
+ return `Held by ${holder.name} until ${timeText(holder.expiresAt)}: pick another item.`;
32
+ if (!holder && leftFor !== undefined && leftFor !== me)
33
+ return `Left for ${leftFor}: pick another item.`;
34
+ return undefined;
35
+ }
36
+ // Whether the asking agent holds the item, and until when; or that it claims it before it starts,
37
+ // so no other agent takes it meanwhile.
38
+ function holdLine({ id, holder, me }) {
39
+ if (holder && holder.name === me)
40
+ return `You hold it until ${timeText(holder.expiresAt)}; your otea calls keep it, and on a long step with none (a rebase, a test run), otea heartbeat ${id} every 10 minutes.`;
41
+ if (holder)
42
+ return `Held by ${holder.name} until ${timeText(holder.expiresAt)}.`;
43
+ return `Claim it first: otea claim ${id} (otea next --claim takes and claims the next in one call).`;
44
+ }
45
+ function and(words, last = 'and') {
46
+ if (words.length < 2)
47
+ return words.join('');
48
+ return `${words.slice(0, -1).join(', ')} ${last} ${words.at(-1)}`;
49
+ }
50
+ export function targetName(def, target) {
51
+ if (target === DONE)
52
+ return DONE_NAME;
53
+ return stepById(def, target)?.name ?? target;
54
+ }
55
+ // The way an agent names (`--way "Animar"`, `--way Done`), as a target of the step; undefined when
56
+ // the step has no such way.
57
+ export function wayByName(def, stepId, name) {
58
+ const wanted = name.trim().toLocaleLowerCase();
59
+ // Forward ways first, then the ways back to earlier steps (`--way "Triar"`).
60
+ return [...waysOf(def, stepId), ...backWaysOf(def, stepId)].find((target) => {
61
+ if (target === DONE)
62
+ return ['done', 'hecho', DONE_NAME.toLowerCase()].includes(wanted);
63
+ return target === name || targetName(def, target).trim().toLocaleLowerCase() === wanted;
64
+ });
65
+ }
66
+ function choiceNames(part, value) {
67
+ const ids = Array.isArray(value)
68
+ ? value.map(String)
69
+ : typeof value === 'string' && value.startsWith('[')
70
+ ? JSON.parse(value).map(String)
71
+ : String(value)
72
+ .split(',')
73
+ .map((piece) => piece.trim());
74
+ return ids.map((id) => part.options.find((choice) => choice.id === id)?.name ?? id).join(', ');
75
+ }
76
+ // "IDE-1 · Pantano vivo (Ideas, Planificar): what it decided is in otea show IDE-1".
77
+ function parentLine({ id, title, board, step }) {
78
+ const where = step ? `${board}, ${step}` : board;
79
+ return `${id} · ${title} (${where}): what it decided is in otea show ${id}`;
80
+ }
81
+ function isEmpty(part, input) {
82
+ if (isEvidence(part))
83
+ return (input.evidence[part.id] ?? 0) === 0;
84
+ const value = part.id === 'title' ? input.title : input.fields[part.id];
85
+ if (value === undefined || value === null)
86
+ return true;
87
+ return Array.isArray(value) ? value.length === 0 : String(value).trim() === '';
88
+ }
89
+ function valueText(part, input) {
90
+ if (isEvidence(part)) {
91
+ const count = input.evidence[part.id] ?? 0;
92
+ return count === 0 ? 'none yet' : count === 1 ? '1 file' : `${count} files`;
93
+ }
94
+ const value = part.id === 'title' ? input.title : input.fields[part.id];
95
+ if (value === undefined || value === null || value === '')
96
+ return '(empty)';
97
+ if (['choice', 'multi', 'check'].includes(part.kind))
98
+ return choiceNames(part, value);
99
+ const text = String(value).trimEnd();
100
+ const whole = text.length <= VALUE_BRIEF
101
+ ? text
102
+ : `${text.slice(0, VALUE_BRIEF - 1).trimEnd()}… (the whole of it: otea show ${input.id})`;
103
+ // Every line of the value, the later ones indented under its name.
104
+ return whole.split(/\r?\n/).join('\n ');
105
+ }
106
+ // A value longer than this is given up to here in `Starts with`, and read whole with otea show, so
107
+ // every next stays short.
108
+ const VALUE_BRIEF = 500;
109
+ const REASON = {
110
+ missing: 'missing',
111
+ not_new: 'not new this round',
112
+ unchecked: 'boxes still open',
113
+ unproved: 'points without proof',
114
+ open: 'not finished',
115
+ };
116
+ // What a missing part says after its name: its reason, and for a checklist short of proof, the
117
+ // points that have none ("no proof yet: Paleta, Silueta").
118
+ function reasonText(missing) {
119
+ if (missing.reason === 'unproved' && missing.points?.length)
120
+ return `no proof yet: ${missing.points.join(', ')}`;
121
+ return REASON[missing.reason];
122
+ }
123
+ // How an agent proves a checklist point: a line of a log or a test of a report it attached, an
124
+ // evidence entry it attached, or a file it attaches for that point.
125
+ export function proveText(id) {
126
+ return `Prove each point with otea tick ${id} "<point>" --log <file>:<line> | --test "<test name>" | --evidence <n>, or otea attach ${id} <file> --point "<point>".`;
127
+ }
128
+ // "RT-4 in Implementar, RT-7 in Propuesta"
129
+ function inSteps(open) {
130
+ return open.map(({ id, step }) => (step ? `${id} in ${step}` : id)).join(', ');
131
+ }
132
+ // "BUG-9 on Errores, in Arreglar, and BUG-11 on Errores, in Triar"
133
+ function onBoards(open) {
134
+ const list = and(open.map(({ id, board, step }) => `${id} on ${board}${step ? `, in ${step}` : ''}`));
135
+ return open.at(-1)?.step ? `${list},` : list;
136
+ }
137
+ // What the note of the handoff says: the step's hint, or, on a round sent back where the step asks
138
+ // for no note and hints at none, what changed since.
139
+ function noteHint(step, sentBack) {
140
+ const hint = step.note.hint.trim();
141
+ if (hint || step.note.req === 'always')
142
+ return hint;
143
+ return sentBack ? SENT_BACK_HINT : '';
144
+ }
145
+ // Whether the handoff carries a note: the step asks for one, or the round was sent back.
146
+ function wantsNote(step, input) {
147
+ return step.note.req === 'always' || input.sentBack !== undefined;
148
+ }
149
+ // The note the handoff carries: always the first line of the Handoff when it needs one.
150
+ function noteLine(step, input) {
151
+ // Under review the note was handed already: the reviewer reads it above, it owes none.
152
+ if (!isClosed(input.position) && input.position.phase !== 'doing')
153
+ return [];
154
+ if (!wantsNote(step, input))
155
+ return [];
156
+ const missing = input.missing.some(({ ref }) => ref === NOTE_REF);
157
+ const hint = noteHint(step, input.sentBack !== undefined);
158
+ return [` ${missing ? '✗' : '✓'} Note: required${hint ? ` (${hint})` : ''}`];
159
+ }
160
+ // The block a round sent back starts with: the note as the reviewer wrote it, then who, when and
161
+ // from which review.
162
+ // A reopened round starts with the reason it was reopened for, who reopened it and when.
163
+ function sentBackLines(sent) {
164
+ const [first = '', ...rest] = sent.note.trim().split(/\r?\n/);
165
+ const lead = sent.reopened ? 'Reopened' : 'Sent back to you';
166
+ // A send-back with no words of its own went with the person's review comments (P4-7).
167
+ const bare = first.trim() === '';
168
+ const quoted = bare
169
+ ? [`${lead} with the notes from the person above: answer each`]
170
+ : [`${lead}: "${first}`, ...rest.map((line) => ` ${line}`)];
171
+ if (!bare)
172
+ quoted[quoted.length - 1] += '"';
173
+ const who = sent.by.kind === 'human' ? 'the person' : sent.by.name;
174
+ const from = sent.reopened
175
+ ? `after it was ${sent.step}`
176
+ : `from the review of ${sent.step} round ${sent.round}`;
177
+ return ['', ...quoted, ` by ${who}, ${timeText(sent.at)}, ${from}`];
178
+ }
179
+ // The note an approval carried into this step: what the reviewer said, who and when.
180
+ function approvedLines(approved) {
181
+ const [first = '', ...rest] = approved.note.trim().split(/\r?\n/);
182
+ const quoted = [`Approved with a note: "${first}`, ...rest.map((line) => ` ${line}`)];
183
+ quoted[quoted.length - 1] += '"';
184
+ const who = approved.by.kind === 'human' ? 'the person' : approved.by.name;
185
+ return [
186
+ '',
187
+ ...quoted,
188
+ ` by ${who}, ${timeText(approved.at)}, from the review of ${approved.step} round ${approved.round}`,
189
+ ];
190
+ }
191
+ // What the step waits for: the last lines of the Handoff.
192
+ function waitLines(step, input) {
193
+ const out = [];
194
+ if (step.waits.includes('parts')) {
195
+ const parts = input.parts ?? [];
196
+ const open = parts.filter(({ closed }) => !closed);
197
+ const name = input.child?.name ?? parts[0]?.board ?? 'Parts';
198
+ out.push(parts.length === 0
199
+ ? ` ✓ ${name} finished: none yet, so nothing holds the handoff; add them first if it has any`
200
+ : open.length === 0
201
+ ? ` ✓ ${name} finished: required`
202
+ : ` ✗ ${name} finished: required (${open.length} of ${parts.length} open: ${inSteps(open)})`);
203
+ }
204
+ if (step.waits.includes('blockers')) {
205
+ const open = (input.blockers ?? []).filter(({ closed }) => !closed);
206
+ const verb = open.length === 1 ? 'blocks' : 'block';
207
+ out.push(open.length === 0
208
+ ? ' ✓ Nothing open blocks it: required'
209
+ : ` ✗ Nothing open blocks it: required (${onBoards(open)} ${verb} it)`);
210
+ }
211
+ return out;
212
+ }
213
+ // The Parts section of a board that divides: how many are finished, and how to add one.
214
+ function partsLines(def, input) {
215
+ const child = input.child ?? def;
216
+ const parts = input.parts ?? [];
217
+ const open = parts.filter(({ closed }) => !closed);
218
+ const count = parts.length === 0
219
+ ? ` ${child.name}: none yet`
220
+ : ` ${child.name}: ${parts.length - open.length} of ${parts.length} finished${open.length > 0 ? ` (open: ${inSteps(open)})` : ''}`;
221
+ const fields = child.form
222
+ .filter(({ required }) => required)
223
+ .flatMap(({ ref }) => {
224
+ const part = partOf(child, ref);
225
+ return part ? [` --field "${part.name}=…"`] : [];
226
+ })
227
+ .join('');
228
+ return [
229
+ count,
230
+ ` Add one: otea create --collection "${child.name}" --parent ${input.id} --title "…"${fields}`,
231
+ ];
232
+ }
233
+ function branchOf(def, fields) {
234
+ const branch = guardedBranch(def);
235
+ if (!branch)
236
+ return undefined;
237
+ const value = String(fields[branch.id] ?? '').trim();
238
+ const repo = branch.guard.repo ? String(fields[branch.guard.repo] ?? '').trim() : '';
239
+ const unasked = value === '' ? unaskedWhen(def, branch.id, fields) : undefined;
240
+ return {
241
+ value,
242
+ name: branch.name,
243
+ named: value !== '',
244
+ ...(repo ? { repo } : {}),
245
+ push: branch.guard.push.flatMap((id) => stepById(def, id)?.name ?? []),
246
+ ...(unasked === undefined ? {} : { unasked }),
247
+ };
248
+ }
249
+ // When the board asks for a part only on conditions the item does not meet (every step that hands
250
+ // it asks for it "required only when…", and none of them holds): the first condition, in words.
251
+ // Undefined when the item takes the part: it is on the form or open at any time, a step asks for it
252
+ // always or leaves it optional, or a condition holds.
253
+ function unaskedWhen(def, ref, fields) {
254
+ if (def.form.some((entry) => entry.ref === ref) || def.anytime.includes(ref))
255
+ return undefined;
256
+ const hands = def.steps.flatMap(({ hand }) => hand.filter((entry) => entry.ref === ref));
257
+ const [first] = hands;
258
+ if (!first?.when)
259
+ return undefined;
260
+ for (const hand of hands) {
261
+ if (hand.req !== 'when' || !hand.when)
262
+ return undefined;
263
+ if (whenHolds(def, { fields }, hand.when.part, hand.when.value))
264
+ return undefined;
265
+ }
266
+ return whenWords(def, first.when);
267
+ }
268
+ function branchLines(def, step, position, input) {
269
+ const branch = branchOf(def, input.fields);
270
+ if (!branch)
271
+ return [];
272
+ // An item whose branch is empty has nothing to push or merge yet (P5-R3-2): never «you may push».
273
+ if (!branch.named)
274
+ return emptyBranchLines(input.id, step, position, def, branch);
275
+ const base = guardedBranch(def)?.guard.base;
276
+ const land = landStepOf(def);
277
+ const landing = gateAt(def, position, 'merge').why === 'landing';
278
+ // A forge merges the branch as its remote has it, which a clone without Otea's hook can push to
279
+ // after the approval: the merge check, right before the merge, holds it to the approved tip
280
+ // (P3C-R3-1).
281
+ const at = input.approvedTip ? ` at ${input.approvedTip}` : '';
282
+ const named = String(input.fields[guardedBranch(def)?.id ?? ''] ?? '').trim();
283
+ const into = !base
284
+ ? []
285
+ : landing
286
+ ? [
287
+ ` ${base} is protected too: merge ${branch.value} into it now, in ${step.name}; the person approved ${input.id}${at}.`,
288
+ ...(named === '' || named === base
289
+ ? []
290
+ : [
291
+ ` Right before any merge, a forge's too (a script, a CLI or the PR's button), run otea check --gate merge --branch ${branch.value}; if it refuses, merge nothing and ask the person: otea ask ${input.id} "<question>".`,
292
+ ]),
293
+ ]
294
+ : land
295
+ ? [
296
+ ` ${base} is protected too: push or merge ${branch.value} into it only in ${land.name}, once the person approved ${input.id}.`,
297
+ ]
298
+ : [
299
+ ` ${base} is protected too: push or merge ${branch.value} into it only once ${input.id} is ${DONE_NAME}.`,
300
+ ];
301
+ return [...pushLines(def, step, position, branch), ...into];
302
+ }
303
+ // What is true of the push on an item that leaves its branch empty: with no branch the board asks
304
+ // of it, nothing is pushed at all; else nothing until it is set, then only that branch, while a step
305
+ // that pushes it is being done.
306
+ function emptyBranchLines(id, step, position, def, branch) {
307
+ if (branch.unasked !== undefined)
308
+ return [
309
+ ` No branch: ${id} takes a ${branch.name} only when ${branch.unasked}, so push nothing for it.`,
310
+ ];
311
+ if (gateAt(def, position, 'push').why !== 'doing')
312
+ return [` ${branch.name} is empty: push nothing.`];
313
+ return [
314
+ ` ${branch.name} is empty: push nothing until it is set (otea update ${id} --field "${branch.name}=<branch>"); then push only that branch, while you do ${step.name}.`,
315
+ ];
316
+ }
317
+ function pushLines(def, step, position, branch) {
318
+ const where = `${branch.value}${branch.repo ? ` in ${branch.repo}` : ''}`;
319
+ const land = landStepOf(def);
320
+ const mergedWhen = land
321
+ ? `once the person approves it, an agent merges it in ${land.name}`
322
+ : `it can be merged only once it is ${DONE_NAME}`;
323
+ const merge = `${mergedWhen.charAt(0).toUpperCase()}${mergedWhen.slice(1)}.`;
324
+ const answer = gateAt(def, position, 'push');
325
+ if (answer.why === 'doing') {
326
+ // The land step itself is where the branch is merged; a step nobody reviews never freezes it.
327
+ if (land?.id === step.id)
328
+ return [
329
+ ` ${where}: you may push while you do ${step.name}; it is merged here, in ${step.name}.`,
330
+ ];
331
+ if (step.reviewer === 'none')
332
+ return [` ${where}: you may push while you do ${step.name}; ${mergedWhen}.`];
333
+ return [
334
+ ` ${where}: you may push while you do ${step.name}. While it is reviewed it is frozen; ${mergedWhen}.`,
335
+ ];
336
+ }
337
+ if (answer.why === 'review') {
338
+ return [` ${where} is frozen while ${reviewerName(step)} reviews it: do not push. ${merge}`];
339
+ }
340
+ const elsewhere = branch.push.length > 0 ? ` You may push in ${and(branch.push, 'or')}.` : '';
341
+ return [` ${where}: no pushes in ${step.name}.${elsewhere}`];
342
+ }
343
+ // How a closed item reads: Done, Dropped, or Dropped with its motive.
344
+ export function closedName(def, position) {
345
+ if (!isClosed(position) || position.closed === DONE)
346
+ return DONE_NAME;
347
+ const motive = position.motive ? motiveById(def, position.motive) : undefined;
348
+ return motive ? `${DROPPED_NAME} (${motive.name})` : DROPPED_NAME;
349
+ }
350
+ // ` --motive "Rechazado|Duplicado"` on a board with motives.
351
+ function motiveFlag(def) {
352
+ const names = def.drop.motives.map(({ name }) => name);
353
+ return names.length === 0 ? '' : ` --motive "${names.join('|')}"`;
354
+ }
355
+ // The note flag a command shows: the hint as a <placeholder>, so it reads as what to write, never
356
+ // as the note itself.
357
+ function noteArg(hint) {
358
+ return `--note "<${hint}>"`;
359
+ }
360
+ function noteFlag(step, input) {
361
+ if (!wantsNote(step, input))
362
+ return '';
363
+ return ` ${noteArg(noteHint(step, input.sentBack !== undefined) || 'what changed in this round')}`;
364
+ }
365
+ function whenText(def, hand) {
366
+ if (!hand.when)
367
+ return 'required sometimes';
368
+ return `required when ${whenWords(def, hand.when)}`;
369
+ }
370
+ // A "required only when…" as a sentence says it: «En el repositorio is yes».
371
+ function whenWords(def, when) {
372
+ const read = partOf(def, when.part);
373
+ const value = read?.options.find(({ id }) => id === when.value)?.name ?? when.value;
374
+ return `${read?.name ?? '…'} is ${value}`;
375
+ }
376
+ function handLines(def, step, input) {
377
+ const lines = [
378
+ ...noteLine(step, input),
379
+ ...partLines(def, step.hand, input),
380
+ ...notesHandLine(input.notes ?? []),
381
+ ...waitLines(step, input),
382
+ ];
383
+ return lines.length === 0 ? [' nothing required'] : lines;
384
+ }
385
+ function partLines(def, hands, input) {
386
+ return hands.flatMap((hand) => {
387
+ const part = partOf(def, hand.ref);
388
+ if (!part)
389
+ return [];
390
+ const missing = input.missing.find(({ ref }) => ref === hand.ref);
391
+ const fresh = hand.fresh && isEvidence(part) ? ', new this round' : '';
392
+ const req = hand.req === 'always'
393
+ ? `required${fresh}`
394
+ : hand.req === 'when'
395
+ ? whenText(def, hand)
396
+ : 'optional';
397
+ const mark = missing ? '✗' : hand.req === 'always' ? '✓' : '·';
398
+ const proof = part.kind === 'check' && part.proof ? ', each ticked point with its proof' : '';
399
+ const line = ` ${mark} ${part.name}: ${req}${proof}${missing ? ` (${reasonText(missing)})` : ''}${choicesText(part, hand.req !== 'no', boardLangOf(def))}`;
400
+ return part.hint && hand.req !== 'no' ? [line, ` what goes here: ${part.hint}`] : [line];
401
+ });
402
+ }
403
+ // What a field takes, when it is a choice: the names an agent fills it with. A checklist the
404
+ // handoff asks for (`asked`) takes every box ticked, as the handoff checks.
405
+ function choicesText(part, asked, lang) {
406
+ if (part.kind === 'level')
407
+ return `; one of ${LEVELS.map((level) => LEVEL_SAID[lang][level]).join(', ')}`;
408
+ if (part.kind === 'yesno')
409
+ return `; ${YES_NO_SAID[lang]}`;
410
+ if (part.options.length === 0 || isEvidence(part))
411
+ return '';
412
+ const names = part.options.map(({ name }) => name).join(', ');
413
+ if (part.kind === 'choice')
414
+ return `; one of ${names}`;
415
+ return part.kind === 'check' && asked ? `; tick every one of ${names}` : `; any of ${names}`;
416
+ }
417
+ // The analysis matrix weighs items by the fields the board maps to effort, risk and impact
418
+ // (core/board/analysis.ts): an agent doing a step estimates the ones still empty, and the person
419
+ // corrects them.
420
+ function estimateLines(def, input) {
421
+ const empty = mappedScales(def)
422
+ .map((role) => rolePart(def, role))
423
+ .filter((part) => part !== undefined)
424
+ .filter((part) => {
425
+ const value = input.fields[part.id];
426
+ return value === undefined || value === null || value === '';
427
+ });
428
+ if (empty.length === 0)
429
+ return [];
430
+ const names = empty.map(({ name }) => name).join(', ');
431
+ const flags = empty.map(({ name }) => ` --field "${name}=…"`).join('');
432
+ // What each takes, so the agent never has to look for it elsewhere.
433
+ const lang = boardLangOf(def);
434
+ const values = empty.flatMap((part) => {
435
+ const takes = choicesText(part, false, lang).replace(/^; /, '');
436
+ return takes ? [` ${part.name}: ${takes}`] : [];
437
+ });
438
+ return [
439
+ ` The person weighs items by ${names}: estimate them (otea update ${input.id}${flags}); they correct you.`,
440
+ ...values,
441
+ ];
442
+ }
443
+ // Why next offers it first: its place in the person's order.
444
+ function orderLine(order) {
445
+ if (order.pin !== undefined)
446
+ return `The person put it on top (number ${order.pin}).`;
447
+ return `It is number ${order.rank} in the order the person fixed on the Matrix.`;
448
+ }
449
+ function section(title, lines) {
450
+ return lines.length === 0 ? [] : ['', title, ...lines];
451
+ }
452
+ function indent(text) {
453
+ return text
454
+ .split(/\r?\n/)
455
+ .filter((line) => line.trim() !== '')
456
+ .map((line) => ` ${line}`);
457
+ }
458
+ // A long board text (a playbook a preset carried) is read whole with otea board; next gives its
459
+ // first paragraph and says where the rest is, so every next stays short.
460
+ const ABOUT_BRIEF = 600;
461
+ function aboutBrief(def) {
462
+ const text = mentionText(def, def.about);
463
+ if (text.length <= ABOUT_BRIEF)
464
+ return text;
465
+ const paragraphs = text.split(/\r?\n\s*\r?\n/).filter((p) => !/^\s*#/.test(p) && p.trim());
466
+ const first = paragraphs[0]?.trim() ?? '';
467
+ const brief = first.length > ABOUT_BRIEF ? `${first.slice(0, ABOUT_BRIEF - 1)}…` : first;
468
+ return `${brief}\n(The whole of it: otea board "${def.name}")`;
469
+ }
470
+ export function nextText(def, input) {
471
+ const { position, id } = input;
472
+ if (isClosed(position)) {
473
+ const branch = branchOf(def, input.fields);
474
+ const said = input.merged?.commit ? ` (${input.merged.commit})` : '';
475
+ // On a board with a land step, Done means an agent already merged it there.
476
+ const land = landStepOf(def);
477
+ // An item that names no branch has nothing to merge, whatever the board protects (P5-R2-6).
478
+ const named = branch && String(input.fields[guardedBranch(def)?.id ?? ''] ?? '').trim() !== '';
479
+ const merge = position.closed !== DONE || !branch || !named
480
+ ? ''
481
+ : input.merged
482
+ ? ` Its branch ${branch.value} was merged${said}.`
483
+ : land
484
+ ? ` Its branch ${branch.value} was merged in ${land.name}.`
485
+ : ` Its branch ${branch.value} may be merged now; once it is, otea merged ${id} --pr <url>.${reopenHint(def, id)}`;
486
+ const chose = input.chosen
487
+ ? ` The person chose ${input.chosen.option} · ${input.chosen.name}.`
488
+ : '';
489
+ return `${id} · ${def.item} · ${closedName(def, position)}\nClosed: nothing left to do.${chose}${merge}`;
490
+ }
491
+ const step = stepById(def, position.step);
492
+ if (!step)
493
+ return `${id} · ${def.item}\nThis item stands in a step the board no longer has.`;
494
+ const head = `${id} · ${def.item} · ${step.name}, round ${input.round}`;
495
+ const reviewing = position.phase !== 'doing';
496
+ if (!reviewing && step.doer === 'you')
497
+ return `${head}\nThe person does this step: pick another item.`;
498
+ if (reviewing && step.reviewer !== 'any')
499
+ return `${head}\nWaiting for the person to review it: pick another item.`;
500
+ if (reviewing && input.me !== undefined && input.did?.includes(input.me))
501
+ return `${head}\nYou did this step in this round: another agent reviews it. Pick another item.`;
502
+ const elsewhere = heldElsewhere(input);
503
+ if (elsewhere)
504
+ return `${head}\n${elsewhere}`;
505
+ const open = reviewing ? undefined : input.questions?.find(({ answer }) => !answer);
506
+ if (open)
507
+ return [head, ...waitingAnswerText(open, input.me)].join('\n');
508
+ const ways = waysOf(def, step.id);
509
+ const names = ways.map((way) => targetName(def, way));
510
+ const doerName = input.did?.length
511
+ ? and([...input.did], 'and')
512
+ : step.doer === 'you'
513
+ ? 'the person'
514
+ : 'another agent';
515
+ // The person reading at a terminal (no agent name) reads what the agent is told, as the agent's.
516
+ const person = input.me === PERSON_READER.name;
517
+ const turn = reviewing
518
+ ? `review this step (${doerName} did it).`
519
+ : person
520
+ ? 'an agent does this step.'
521
+ : 'do this step.';
522
+ const lines = [head, `${person ? "An agent's turn" : 'Your turn'}: ${turn}`];
523
+ if (!reviewing && input.retaken)
524
+ lines.push(input.retaken);
525
+ if (input.order)
526
+ lines.push(orderLine(input.order));
527
+ if (!input.holder && input.leftFor !== undefined && input.leftFor === input.me)
528
+ lines.push('The person left it for you.');
529
+ if (!person)
530
+ lines.push(holdLine(input));
531
+ else if (input.holder)
532
+ lines.push(`Held by ${input.holder.name} until ${timeText(input.holder.expiresAt)}.`);
533
+ if (reviewing && input.handed?.note.trim())
534
+ lines.push('', `Handoff note from ${input.handed.by}:`, ...input.handed.note
535
+ .trim()
536
+ .split(/\r?\n/)
537
+ .map((line) => ` ${line}`));
538
+ if (!reviewing)
539
+ lines.push(...notesBlock(id, input.notes ?? [], input.me));
540
+ if (!reviewing && input.sentBack)
541
+ lines.push(...sentBackLines(input.sentBack));
542
+ if (!reviewing && input.approved)
543
+ lines.push(...approvedLines(input.approved));
544
+ if (!reviewing)
545
+ lines.push(...answersBlock(input.questions ?? [], input.me));
546
+ lines.push(...section('About this board', indent(aboutBrief(def))));
547
+ if (input.chosen)
548
+ lines.push(...section('The person chose', choiceLines(input.chosen)));
549
+ if (input.parent)
550
+ lines.push(...section('Part of', [` ${parentLine(input.parent)}`]));
551
+ if (input.implements?.length)
552
+ lines.push(...section('Implements', input.implements.map((it) => ` ${parentLine(it)}`)));
553
+ lines.push(...section('Starts with', startsWith(def, step.id).flatMap(({ ref, from }) => {
554
+ const part = partOf(def, ref);
555
+ if (!part)
556
+ return [];
557
+ // What an earlier step left empty (a deliverable asked only sometimes) is not there to read.
558
+ if (from && isEmpty(part, input))
559
+ return [];
560
+ const origin = from ? ` (from ${stepById(def, from)?.name ?? from})` : '';
561
+ return [` ${part.name}${origin}: ${valueText(part, input)}`];
562
+ })));
563
+ if (def.split)
564
+ lines.push(...section('Parts', partsLines(def, input)));
565
+ const instruction = reviewing ? step.instructions.review : step.instructions.take;
566
+ lines.push(...section(reviewing ? 'When you review it' : 'When you take it', indent(mentionText(def, instruction))));
567
+ // Work handed in some other way carries nothing of an otea handoff.
568
+ if (reviewing || !input.handIn)
569
+ lines.push(...section('Handoff', handLines(def, step, input)));
570
+ if (!reviewing)
571
+ lines.push(...section('Estimate', estimateLines(def, input)));
572
+ lines.push(...section('Branch', branchLines(def, step, position, input)));
573
+ if (!reviewing)
574
+ lines.push(...section('Before you hand it off', indent(mentionText(def, step.instructions.before))));
575
+ let after;
576
+ const several = ways.length > 1;
577
+ if (reviewing) {
578
+ const back = targetName(def, backTarget(def, step.id));
579
+ const pick = several
580
+ ? `${and(names, 'or')}: you pick with --way when approving`
581
+ : `${names[0]}, once you approve it`;
582
+ after = `${pick}; a send-back returns it to ${back}`;
583
+ }
584
+ else if (step.reviewer === 'none') {
585
+ after = several ? `${and(names, 'or')}: you pick with --way and say why` : `${names[0]}`;
586
+ }
587
+ else {
588
+ const who = reviewerName(step);
589
+ after = several
590
+ ? `${and(names, 'or')}: ${who} picks when approving it`
591
+ : `${names[0]}, once ${who} approves it`;
592
+ }
593
+ const others = [];
594
+ if (!reviewing) {
595
+ for (const earlier of backWaysOf(def, step.id)) {
596
+ const name = targetName(def, earlier);
597
+ others.push(` Or take it back to ${name} (no review; ${name} starts its next round):`, ` otea handoff ${id} --way "${name}" --reason "why"`);
598
+ }
599
+ if (step.doerMayDrop && step.doer !== 'you')
600
+ others.push(` Or drop it if it is not worth doing: otea drop ${id} --reason "why"${motiveFlag(def)}`);
601
+ }
602
+ const handIn = reviewing ? undefined : input.handIn;
603
+ if (handIn) {
604
+ lines.push(...section('Next', [` ${handIn.after}`]));
605
+ lines.push(...section('When you finish', [` ${handIn.command}`]));
606
+ return lines.join('\n');
607
+ }
608
+ lines.push(...section('Next', [` ${after}`, ...others]));
609
+ const choice = `"<${names.join('|')}>"`;
610
+ const finish = reviewing
611
+ ? [
612
+ ` otea approve ${id}${several ? ` --way ${choice}` : ''}`,
613
+ ` otea send-back ${id} --reason "what to change"`,
614
+ ]
615
+ : [
616
+ ` otea handoff ${id}${several && step.reviewer === 'none' ? ` --way ${choice} --reason "why"` : ''}${noteFlag(step, input)}`,
617
+ ];
618
+ lines.push(...section('When you finish', finish));
619
+ return lines.join('\n');
620
+ }
621
+ const MISSING_NOTE = {
622
+ missing: '',
623
+ not_new: 'new this round',
624
+ unchecked: 'every box ticked',
625
+ unproved: 'a proof for each ticked point',
626
+ open: '',
627
+ };
628
+ // "RT-4 (Implementar), RT-7 (Propuesta)"; with `board`, "BUG-9 (Errores, Arreglar)".
629
+ function named(open, board = false) {
630
+ return open.map(({ id, board: on, step, unmerged }) => {
631
+ const at = step ?? (unmerged ? `${DONE_NAME}, not merged yet` : '');
632
+ const where = [board ? on : '', at].filter(Boolean).join(', ');
633
+ return where ? `${id} (${where})` : id;
634
+ });
635
+ }
636
+ // What holds a parent back while its parts are open, said of the item `id`.
637
+ // Parts that are Done but wait to be merged are said so: "not merged yet".
638
+ function partsHold(id, wait) {
639
+ const open = wait.open ?? [];
640
+ const total = wait.total ?? open.length;
641
+ const list = named(open).join(', ');
642
+ const state = open.length > 0 && open.every((linked) => linked.unmerged) ? 'not merged yet' : 'not finished';
643
+ if (total === 1 && open.length === 1)
644
+ return `its part ${list} is ${state}`;
645
+ if (open.length === total)
646
+ return `its ${total} ${wait.name} are ${state}: ${list}`;
647
+ const verb = open.length === 1 ? 'is' : 'are';
648
+ return `${open.length} of its ${total} ${wait.name} ${verb} ${state}: ${list}`;
649
+ }
650
+ // `unmerged`: every one of them is Done and waits to be merged; `some`, at least one is.
651
+ function blockersHold(wait) {
652
+ const open = wait.open ?? [];
653
+ const one = open.length === 1;
654
+ const unmerged = open.length > 0 && open.every((linked) => linked.unmerged);
655
+ const some = open.some((linked) => linked.unmerged);
656
+ const state = unmerged ? 'not merged yet' : 'not finished';
657
+ const text = `${and(named(open, true))} ${one ? 'blocks it and is' : 'block it and are'} ${state}`;
658
+ return { text, them: one ? (open[0]?.id ?? '') : 'they', one, unmerged, some };
659
+ }
660
+ // The exact refusal of a handoff that lacks something: the parts and the note lead; when only
661
+ // what it waits for holds it, that alone, with what to do.
662
+ export function refusalText(id, missing) {
663
+ const asked = missing.find(({ ref }) => ref === NOTES_REF)?.notes ?? [];
664
+ const rest = missing.filter(({ ref }) => ref !== NOTES_REF);
665
+ const notes = notesRefusal(id, asked);
666
+ if (rest.length === 0)
667
+ return notes.join('\n');
668
+ return [lackingText(id, rest), ...notes].join('\n');
669
+ }
670
+ function lackingText(id, missing) {
671
+ const note = missing.find(({ ref }) => ref === NOTE_REF);
672
+ const hint = note?.hint?.trim() || (note?.sentBack ? SENT_BACK_HINT : 'what changed in this round');
673
+ const flag = note ? ` with ${noteArg(hint)}` : '';
674
+ const parts = missing.filter(({ reason, ref }) => reason !== 'open' && ref !== NOTE_REF);
675
+ if (parts.length > 0 || note) {
676
+ const what = parts.map(({ name, reason, fresh, points }) => {
677
+ const said = reason === 'missing' && fresh
678
+ ? 'new this round'
679
+ : reason === 'unproved' && points?.length
680
+ ? `a proof for ${and(points)}`
681
+ : MISSING_NOTE[reason];
682
+ return said ? `${name} (${said})` : name;
683
+ });
684
+ if (note)
685
+ what.push(note.sentBack ? 'a note (it was sent back: say what you changed)' : 'a note');
686
+ const then = parts.length === 0
687
+ ? `Call handoff again${flag}.`
688
+ : `Attach or fill them with otea attach ${id} / otea update ${id}, then call handoff again${flag}.`;
689
+ const prove = parts.some(({ reason }) => reason === 'unproved') ? [proveText(id)] : [];
690
+ return [`Not handed off ${id}: missing ${and(what)}.`, then, ...prove].join('\n');
691
+ }
692
+ const lines = [];
693
+ const waitingParts = missing.find(({ ref }) => ref === WAIT_PARTS);
694
+ const waitingBlockers = missing.find(({ ref }) => ref === WAIT_BLOCKERS);
695
+ if (waitingParts) {
696
+ const unmerged = (waitingParts.open ?? []).some((linked) => linked.unmerged);
697
+ const until = unmerged ? `${DONE_NAME} and merged (otea merged)` : DONE_NAME;
698
+ lines.push(`Not handed off ${id}: ${partsHold(id, waitingParts)}.`, `Nothing moves ${id} for them: hand it off again once they are ${until} or ${DROPPED_NAME}.`);
699
+ }
700
+ if (waitingBlockers) {
701
+ const hold = blockersHold(waitingBlockers);
702
+ const record = hold.one ? ` (otea merged ${hold.them})` : '';
703
+ const until = hold.unmerged
704
+ ? `merged${record}`
705
+ : hold.some
706
+ ? `${DONE_NAME} and merged`
707
+ : DONE_NAME;
708
+ lines.push(`Not handed off ${id}: ${hold.text}.`, `Hand it off again once ${hold.them} ${hold.one ? 'is' : 'are'} ${until} or ${DROPPED_NAME}, or ask the person to remove the link.`);
709
+ }
710
+ return lines.join('\n');
711
+ }
712
+ // The refusal of an approval whose waits do not hold: a part not finished (reopened, or never
713
+ // finished), or a blocker added. Parts are said as a handoff says them, and as the web UI does.
714
+ export function approvalRefusalText(id, missing) {
715
+ const sentences = missing.flatMap((wait) => {
716
+ if (wait.ref === WAIT_PARTS)
717
+ return [partsHold(id, wait)];
718
+ if (wait.ref === WAIT_BLOCKERS)
719
+ return [blockersHold(wait).text];
720
+ return [];
721
+ });
722
+ return `Not approved ${id}: ${sentences.join('; ')}.`;
723
+ }
724
+ // The refusal of a way back without a reason.
725
+ export const NOT_TAKEN_BACK = 'Not taken back: say why with --reason.';
726
+ // The refusal of a way the step does not have, with the ways it has: on to a later step (or Done)
727
+ // and, while it is being done, back to an earlier one with a reason.
728
+ export function noWayText(def, id, stepId, way, reviewing = false,
729
+ // The item's facts: the ways it may take now (a lead that holds leaves the next step out).
730
+ facts) {
731
+ const name = targetName(def, stepId);
732
+ const on = waysOf(def, stepId, facts).map((target) => targetName(def, target));
733
+ const back = reviewing ? [] : backWaysOf(def, stepId).map((target) => targetName(def, target));
734
+ const choice = back.length === 1 ? (back[0] ?? '') : `<${back.join('|')}>`;
735
+ const backText = back.length === 0
736
+ ? ''
737
+ : `, or back to ${and(back, 'or')} (otea handoff ${id} --way "${choice}" --reason "why")`;
738
+ return `${id} has no way "${way}" from ${name}. From ${name} it goes on to ${and(on, 'or')}${backText}.`;
739
+ }
740
+ // The line after the doer takes an item back to an earlier step.
741
+ export function takenBackText(def, id, stepId, round) {
742
+ return `Taken back. ${id} returns to ${targetName(def, stepId)}, round ${round}.`;
743
+ }
744
+ // The way to record the person's own decision to drop an item, where they may drop it through an
745
+ // agent: the exact relay, so an agent the person told in the chat never dead-ends (P1-R3-4).
746
+ function relayDropText(def, id) {
747
+ if (def.drop.by === 'page')
748
+ return '';
749
+ return ` If the person told you to drop it, relay their decision in their words: otea relay ${id} ${DROPPED_NAME} --quote "<the person's words>" --reason "<why>"${motiveFlag(def)}`;
750
+ }
751
+ // Why a discard was refused (engine drop codes), in the agent's words.
752
+ export function dropRefusalText(def, id, code) {
753
+ switch (code) {
754
+ case 'not_open':
755
+ return `Not dropped ${id}: it is already closed.`;
756
+ case 'reason_required':
757
+ return `Not dropped ${id}: say why with --reason.`;
758
+ case 'motive_required':
759
+ return `Not dropped ${id}: say which with${motiveFlag(def)}.`;
760
+ case 'not_droppable':
761
+ return `Not dropped ${id}: only the person drops items here.${relayDropText(def, id)}`;
762
+ case 'not_relayable':
763
+ return `Not relayed: on ${def.name} the person drops items from the item's page.`;
764
+ }
765
+ }
766
+ // The line after a discard.
767
+ export function droppedText(def, id, to) {
768
+ return `Dropped. ${id} is ${closedName(def, to)}.`;
769
+ }
770
+ // The line after otea create: where the item starts, and why when the first step was skipped or
771
+ // still lacks something.
772
+ export function createdText(def, id, at, missing) {
773
+ if (isClosed(at))
774
+ return `Created ${id}.`;
775
+ const name = targetName(def, at.step);
776
+ const first = def.steps[0];
777
+ if (first && first.id !== at.step)
778
+ return `Created ${id} in ${name}: it already had everything ${first.name} asks for.`;
779
+ const lacking = missing.filter(({ reason }) => reason !== 'open' && reason !== undefined);
780
+ if (first?.skipWhenReady && lacking.length > 0)
781
+ return `Created ${id} in ${name}: missing ${and(lacking.map(({ name: part }) => part))}. Fill ${lacking.length === 1 ? 'it' : 'them'}, then otea handoff ${id}.`;
782
+ return `Created ${id} in ${name}.`;
783
+ }
784
+ // The refusal of a part created alone on a board whose items are always part of another's.
785
+ export function parentRequiredText(child, parent) {
786
+ return `Not created: each ${child.item} is always part of one ${parent.item}. Create it with --parent <the id of that ${parent.item}>.`;
787
+ }
788
+ // The refusal of a part on a board the parent does not divide into.
789
+ export function parentTypeText(parent, child, other, otherBoard) {
790
+ return `Not linked: the parts of each ${parent.item} are on ${child.name}, and ${other} is on ${otherBoard}.`;
791
+ }
792
+ // A board that divides into nothing keeps an item's parts on itself: a part on another board is
793
+ // refused, and the links that are free between boards are named.
794
+ export function partsAtHomeText(parent, parentId, other, otherBoard) {
795
+ return `Not linked: a ${parent.item}'s parts stay on ${parent.name}, and ${other} is on ${otherBoard}. Link ${other} blocks ${parentId} to make ${parentId} wait, or ${other} implements ${parentId}.`;
796
+ }
797
+ // Where an item is, as a sentence says it after "is in": the step, or its review ("the review of
798
+ // Implementar"), so an item that waits for a review never reads as still being done.
799
+ export function placeText(def, position) {
800
+ if (isClosed(position))
801
+ return position.closed === DONE ? DONE_NAME : DROPPED_NAME;
802
+ const name = stepById(def, position.step)?.name ?? position.step;
803
+ if (position.phase === 'review')
804
+ return `the review of ${name}`;
805
+ return name;
806
+ }
807
+ // The way back for a Done item whose branch is not merged yet: its PR may stop merging as it is
808
+ // (another branch merged first and now conflicts), and its frozen branch cannot be fixed while it
809
+ // stays Done. Empty on a board that protects no branch.
810
+ function reopenHint(def, id) {
811
+ const step = reopenStep(def);
812
+ const name = step === undefined ? undefined : stepById(def, step)?.name;
813
+ if (name === undefined)
814
+ return '';
815
+ return ` If its PR cannot merge as it is (a conflict), otea reopen ${id} --reason "…" takes it back to ${name}.`;
816
+ }
817
+ // The line after otea reopen: where the item stands again, and that it is reviewed again.
818
+ export function reopenedText(def, id, step) {
819
+ const name = stepById(def, step)?.name ?? step;
820
+ return `Reopened ${id}: it is in ${name} again. Fix its branch there and hand it off: it goes through review again before it is ${DONE_NAME}.`;
821
+ }
822
+ // What otea check answers for one item, in the board's words. `merged`: whether a Done item's
823
+ // branch was marked merged; while it is not, a refused push says how to reopen it.
824
+ export function gateText(def, id, position, action, round, merged = true) {
825
+ const answer = gateAt(def, position, action);
826
+ const push = and((guardedBranch(def)?.guard.push ?? []).flatMap((s) => stepById(def, s)?.name ?? []), 'or');
827
+ const step = isClosed(position) ? undefined : stepById(def, position.step);
828
+ const name = step?.name ?? '';
829
+ const where = placeText(def, position);
830
+ switch (answer.why) {
831
+ case 'unguarded':
832
+ return `${action} allowed: ${def.name} protects no branch.`;
833
+ case 'doing':
834
+ return `push allowed: ${id} is being done in ${name}.`;
835
+ case 'done':
836
+ return `merge allowed: ${id} is ${DONE_NAME}.`;
837
+ case 'landing':
838
+ return `merge allowed: ${id} is being landed in ${name}, after the person's approval.`;
839
+ case 'review': {
840
+ const who = step ? reviewerName(step) : 'the person';
841
+ return `push refused: ${id} waits for ${who} to review ${name}; its branch can be pushed only while ${push} is being done.`;
842
+ }
843
+ case 'not_push_step':
844
+ return `push refused: ${id} is in ${where}; its branch can be pushed only while ${push} is being done.`;
845
+ case 'closed': {
846
+ const refused = `push refused: ${id} is ${closedName(def, position)}; nothing is pushed to a closed item's branch.`;
847
+ const step = reopenStep(def);
848
+ const name = step === undefined ? undefined : stepById(def, step)?.name;
849
+ const done = isClosed(position) && position.closed === DONE;
850
+ // On a board with a land step, a Done item was merged there: it never reopens.
851
+ if (!done || merged || name === undefined || landStepOf(def))
852
+ return refused;
853
+ return `${refused} If its PR cannot merge as it is (a conflict), reopen it: otea reopen ${id} --reason "…" takes it back to ${name}, and through review again.`;
854
+ }
855
+ case 'not_done':
856
+ return isClosed(position)
857
+ ? `merge refused: ${id} is ${closedName(def, position)}; its branch can be merged ${mergedOnlyWhen(def, id)}.`
858
+ : `merge refused: ${id} is in ${where}, round ${round}; its branch can be merged ${mergedOnlyWhen(def, id)}.`;
859
+ }
860
+ }
861
+ // When an item's branch may be merged: once it is Done, or on a board with a land step once the
862
+ // person approved it, while an agent lands it there.
863
+ function mergedOnlyWhen(def, id) {
864
+ const land = landStepOf(def);
865
+ return land
866
+ ? `only once the person approved ${id}: while it is being landed in ${land.name}, or once it is ${DONE_NAME}`
867
+ : `only once ${id} is ${DONE_NAME}`;
868
+ }
869
+ // What otea check answers for one item whose branch a push or merge brings into the base branch
870
+ // the board protects: allowed only once the item is Hecho.
871
+ export function baseGateText(def, id, position, action, round, base) {
872
+ if (isClosed(position) && position.closed === DONE)
873
+ return `${action} allowed: ${id} is ${DONE_NAME}; ${base} takes its branch.`;
874
+ if (gateAt(def, position, 'merge').why === 'landing')
875
+ return `${action} allowed: ${id} is being landed in ${placeText(def, position)}, after the person's approval; ${base} takes its branch.`;
876
+ const where = isClosed(position)
877
+ ? `is ${closedName(def, position)}`
878
+ : `is in ${stepById(def, position.step)?.name ?? ''}, round ${round}`;
879
+ return `${action} refused: ${id} ${where}; ${base} takes its branch ${mergedOnlyWhen(def, id)}.`;
880
+ }
881
+ // Why a push or merge into the protected base branch that brings in no item of the board is
882
+ // refused.
883
+ // Said once for every board that protects `base`, so a branch of any of them is named.
884
+ export function baseRefusal(all, action, base) {
885
+ const { names, verb, items, when } = baseWords(all);
886
+ return `${action} refused: ${base} is the base branch ${names} ${verb}; it takes only the branch of ${items} ${when}, and this ${action} brings in none.`;
887
+ }
888
+ // Why a push that rewinds the protected base branch (a force push of an older commit: it removes
889
+ // commits the remote has and brings in none) is refused (P8-R3-4): «brings in none» read as if it
890
+ // added nothing, when it takes commits away.
891
+ export function rewindRefusal(all, base) {
892
+ const { names, verb, items, when } = baseWords(all);
893
+ return `push refused: this push removes commits from ${base}, the base branch ${names} ${verb}; ${base} only takes the branch of ${items} ${when}, added on top of what it has.`;
894
+ }
895
+ // The words both refusals of a protected base use: its boards, and the items it takes.
896
+ function baseWords(all) {
897
+ const names = all.map((def) => def.name).join(' and ');
898
+ // Named by board, never "a <item>": an item's name is the board's language ("a Entrega").
899
+ const items = `an item of ${all.map((def) => def.name).join(' or ')}`;
900
+ const verb = all.length > 1 ? 'protect' : 'protects';
901
+ const lands = all.flatMap((def) => landStepOf(def)?.name ?? []);
902
+ const when = lands.length === all.length
903
+ ? `the person approved (being landed in ${[...new Set(lands)].join(' or ')}, or ${DONE_NAME})`
904
+ : `that is ${DONE_NAME}`;
905
+ return { names, verb, items, when };
906
+ }
907
+ // What the person reads under a refused push into a protected base (P2S-R3-4): the hook shows the
908
+ // refusal to whoever pushes, and a person pushing a commit of their own got only the agents' words,
909
+ // with no way out. Said in the language of the first board that protects it; an agent is told the
910
+ // bypass is never its own.
911
+ const FOR_PERSON = {
912
+ en: "For the person: if the commit is yours, put it through the board (ask your agent for an item and approve it in Otea) or push it yourself this once with git push --no-verify, which skips Otea's check. An agent never uses --no-verify.",
913
+ es: 'Para la persona: si el commit es tuyo, pásalo por el tablero (pídele a tu agente un ítem y apruébalo en Otea) o súbelo tú esta vez con git push --no-verify, que se salta la revisión de Otea. Un agente nunca usa --no-verify.',
914
+ };
915
+ export function forPersonText(all) {
916
+ const [first] = all;
917
+ return FOR_PERSON[first?.title === TITLE_NAME.es ? 'es' : 'en'];
918
+ }
919
+ // Why a push of a branch no item names is refused, in a project where a board protects a base
920
+ // (P5-R3-2): there, a push takes only an item's branch, while its step allows it, or the base, as
921
+ // its board lets it. Said once for every board that protects a base; the field is the first
922
+ // board's protected branch, by name.
923
+ export function unnamedBranchRefusal(all, branch) {
924
+ const names = and(all.map((def) => def.name), 'and');
925
+ const bases = and([...new Set(all.flatMap((def) => guardedBranch(def)?.guard.base ?? []))], 'and');
926
+ const verb = all.length > 1 ? 'protect' : 'protects';
927
+ const field = all.map((def) => guardedBranch(def)?.name).find(Boolean) ?? 'branch';
928
+ const lets = all.length > 1 ? 'as their boards let it' : 'as the board lets it';
929
+ return `push refused: no item names the branch ${branch}, and ${names} ${verb} ${bases}: a push in this project takes only the branch of an item, while its step allows it, or ${bases}, ${lets}. Push the branch of the item you work on, as otea next shows it under Branch; to push ${branch} for an item, set it on that item first, in a step that pushes it: otea update <id> --field "${field}=${branch}".`;
930
+ }
931
+ // What the person reads under that refusal: the same way out as for the protected base, said of a
932
+ // branch, in the language of the first board that protects a base; never an agent's.
933
+ const BRANCH_FOR_PERSON = {
934
+ en: "For the person: if the branch is yours, put it through the board (ask your agent for an item with that branch and approve it in Otea) or push it yourself this once with git push --no-verify, which skips Otea's check. An agent never uses --no-verify.",
935
+ es: 'Para la persona: si la rama es tuya, pásala por el tablero (pídele a tu agente un ítem con esa rama y apruébalo en Otea) o súbela tú esta vez con git push --no-verify, que se salta la revisión de Otea. Un agente nunca usa --no-verify.',
936
+ };
937
+ export function branchForPersonText(all) {
938
+ const [first] = all;
939
+ return BRANCH_FOR_PERSON[first?.title === TITLE_NAME.es ? 'es' : 'en'];
940
+ }
941
+ // What the person reads under a refused push into a protected base that brings commits no approved
942
+ // item holds or records (P5-R3-3), for a person who is no programmer: what happened, by the
943
+ // commits' own words, then what to ask the agent or do in the desk, and the same way past it as
944
+ // under the other refusals of the base. In the language of the first board that protects it.
945
+ const COMMITS_FOR_PERSON = {
946
+ en: (base, count, shown) => `For the person: this push brings to ${base} ${count === 1 ? '1 change' : `${count} changes`} that no approved item claims as its own: ${shown}. Otea lets only what you approved reach ${base}. If it is the work of an item you approved, ask your agent to record that change on the item; if the item waits for your review, review it in Otea's desk; then push again. If the change is yours, push it yourself this once with git push --no-verify, which skips Otea's check. An agent never uses --no-verify.`,
947
+ es: (base, count, shown) => `Para la persona: esta subida lleva a ${base} ${count === 1 ? '1 cambio que ningún ítem aprobado reconoce como suyo' : `${count} cambios que ningún ítem aprobado reconoce como suyos`}: ${shown}. Otea solo deja llegar a ${base} lo que aprobaste. Si es de un ítem que ya aprobaste, pídele a tu agente que anote ese cambio en el ítem; si el ítem espera tu revisión, revísalo en el escritorio de Otea; luego vuelve a subir. Si el cambio es tuyo, súbelo tú esta vez con git push --no-verify, que se salta la revisión de Otea. Un agente nunca usa --no-verify.`,
948
+ };
949
+ export function commitsForPersonText(all, base, commits) {
950
+ const [first] = all;
951
+ const lang = first?.title === TITLE_NAME.es ? 'es' : 'en';
952
+ const [open, close] = lang === 'es' ? ['«', '»'] : ['“', '”'];
953
+ const shown = commits
954
+ .slice(0, 5)
955
+ .map(({ commit, subject }) => subject ? `${commit.slice(0, 7)} ${open}${subject}${close}` : commit.slice(0, 7))
956
+ .join(', ') + (commits.length > 5 ? ', …' : '');
957
+ return COMMITS_FOR_PERSON[lang](base, commits.length, shown);
958
+ }
959
+ // What the person reads under a refused push of an item's branch while its step is reviewed
960
+ // (P5-R3-13): why the branch holds still, where to act, and the same way past it as under the other
961
+ // refusals, in the board's language; never an agent's.
962
+ const REVIEW_FOR_PERSON = {
963
+ en: (id, step) => `For the person: ${id} waits for the review of ${step}, and its branch holds still while it is reviewed: so what you approve is what gets pushed. Review it in Otea's desk. If the change is yours, push it yourself this once with git push --no-verify, which skips Otea's check. An agent never uses --no-verify.`,
964
+ es: (id, step) => `Para la persona: ${id} espera la revisión de ${step}, y su rama no cambia mientras se revisa: así lo que apruebas es lo que se sube. Revísalo en el escritorio de Otea. Si el cambio es tuyo, súbelo tú esta vez con git push --no-verify, que se salta la revisión de Otea. Un agente nunca usa --no-verify.`,
965
+ };
966
+ export function reviewForPersonText(def, id, step) {
967
+ return REVIEW_FOR_PERSON[def.title === TITLE_NAME.es ? 'es' : 'en'](id, step);
968
+ }
969
+ // What the person reads under a refused push that rewrites an item's branch (P1-R3-3): the same
970
+ // way out as for the protected base, said in the board's language; never an agent's.
971
+ const REWRITE_FOR_PERSON = {
972
+ en: "For the person: if you mean to rewrite the branch, push it yourself this once with git push --force-with-lease --no-verify, which skips Otea's check. An agent never uses --no-verify.",
973
+ es: 'Para la persona: si quieres reescribir la rama, súbela tú esta vez con git push --force-with-lease --no-verify, que se salta la revisión de Otea. Un agente nunca usa --no-verify.',
974
+ };
975
+ export function rewriteForPersonText(def) {
976
+ return REWRITE_FOR_PERSON[def.title === TITLE_NAME.es ? 'es' : 'en'];
977
+ }
978
+ // The line after a handoff or an approval: where the item stands now.
979
+ export function handedText(def, id, to, said = 'Handed off') {
980
+ if (isClosed(to))
981
+ return `${said}. ${id} is ${to.closed === DONE ? DONE_NAME : DROPPED_NAME}.`;
982
+ const step = stepById(def, to.step);
983
+ const name = step?.name ?? to.step;
984
+ if (to.phase === 'doing')
985
+ return `${said}. ${id} moves on to ${name}.`;
986
+ const who = step ? reviewerName(step) : 'the person';
987
+ return `${said}. ${id} waits for ${who} to review ${name}.`;
988
+ }
989
+ // The line after a send-back: the step it returns to, for its next round.
990
+ export function sentBackText(def, id, step, round) {
991
+ return `Sent back. ${id} returns to ${targetName(def, step)}, round ${round}.`;
992
+ }
993
+ // What `next` answers when nothing on the boards asked is the agent's: that, once, naming them; each
994
+ // board's own words for idle time and its cap on new items when it is on. next itself ends with how
995
+ // to wait for the next item.
996
+ export function idleText(boards) {
997
+ const names = boards.map(({ def }) => def.name);
998
+ const lines = [`Nothing to do on ${and(names, 'or')} right now.`];
999
+ const of = (title, def) => boards.length > 1 ? `${title} on ${def.name}` : title;
1000
+ for (const { def, waitingForYou } of boards) {
1001
+ lines.push(...section(boards.length > 1
1002
+ ? `On ${def.name}, when there is nothing to do`
1003
+ : 'When there is nothing to do', indent(mentionText(def, def.idle))));
1004
+ if (def.cap.on) {
1005
+ const room = waitingForYou < def.cap.n;
1006
+ lines.push(...section(of('New items', def), [
1007
+ room
1008
+ ? ` You may add items while fewer than ${def.cap.n} wait for the person (${waitingForYou} do).`
1009
+ : ` Do not add items: ${waitingForYou} already wait for the person (the cap is ${def.cap.n}).`,
1010
+ ]));
1011
+ }
1012
+ }
1013
+ lines.push(...mergeLines(boards.flatMap(({ toMerge: done }) => done ?? [])));
1014
+ // How to wait for the next one is next's last line, with the agent's name (app/keep-waiting.ts).
1015
+ return lines.join('\n');
1016
+ }
1017
+ export function mergeLines(toMerge) {
1018
+ return section('Waiting to be merged', toMerge.map(({ id, branch }) => ` ${id} (${branch}) is ${DONE_NAME}: merge its PR, then otea merged ${id} --pr <url>.`));
1019
+ }
1020
+ // What next says when the item to take waits for parts still to be merged: merge them first.
1021
+ export function mergeFirstText(id, toMerge) {
1022
+ return [
1023
+ `Merge first: ${id} waits for its parts to be merged.`,
1024
+ ...mergeLines(toMerge),
1025
+ '',
1026
+ 'Then run otea next again.',
1027
+ ].join('\n');
1028
+ }
1029
+ // A name as a command line takes it: bare when it is one plain word, quoted otherwise.
1030
+ export function quoted(name) {
1031
+ return /^[\w.-]+$/.test(name) ? name : `"${name}"`;
1032
+ }
1033
+ // Who reviews a step, as a sentence names them: never the agent that did the round.
1034
+ function reviewerName(step) {
1035
+ return step.reviewer === 'any' ? 'another agent' : 'the person';
1036
+ }
1037
+ function whoDoes(step) {
1038
+ return step.doer === 'you' ? 'the person does it' : 'any agent does it';
1039
+ }
1040
+ function whoReviews(step) {
1041
+ if (step.reviewer === 'none')
1042
+ return '';
1043
+ if (step.reviewer === 'you')
1044
+ return '; the person reviews it';
1045
+ return '; another agent reviews it, never the one that did it';
1046
+ }
1047
+ // What `otea board` prints: the board's own words for agents (about it, idle time, the cap) and
1048
+ // each step's instructions, mentions read with today's names.
1049
+ // The values each field the board uses takes, as the board says them, so an agent never has to
1050
+ // look for them elsewhere (an agent once read otea.db for a choice's options).
1051
+ function fieldValueLines(def) {
1052
+ const used = usedRefs(def);
1053
+ const lang = boardLangOf(def);
1054
+ return Object.values(def.parts).flatMap((part) => {
1055
+ const takes = used.has(part.id) ? choicesText(part, false, lang).replace(/^; /, '') : '';
1056
+ return takes ? [` ${part.name}: ${takes}`] : [];
1057
+ });
1058
+ }
1059
+ // How to add an item: the fields of the board's own form, by name, so an agent never tries an
1060
+ // option the board does not take (--description on a board with no description field). On a board
1061
+ // with the Matrix, its fields the form leaves out come after: an agent estimates them as it
1062
+ // creates the item (P4-R3-4).
1063
+ function createLines(def) {
1064
+ const fields = def.form.flatMap(({ ref, required }) => {
1065
+ const part = def.parts[ref];
1066
+ return part ? [{ name: part.name, required }] : [];
1067
+ });
1068
+ const formed = new Set(def.form.map(({ ref }) => ref));
1069
+ const scales = viewsOf(def).includes('matrix')
1070
+ ? mappedScales(def).flatMap((role) => {
1071
+ const part = rolePart(def, role);
1072
+ return part && !formed.has(part.id) ? [part.name] : [];
1073
+ })
1074
+ : [];
1075
+ const given = [...fields.map(({ name }) => name), ...scales]
1076
+ .map((name) => ` --field "${name}=…"`)
1077
+ .join('');
1078
+ const later = fields.filter(({ required }) => !required).map(({ name }) => name);
1079
+ const wait = later.length > 0 ? ` (${and(later)} may wait)` : '';
1080
+ const quoted = /\s/.test(def.name) ? `"${def.name}"` : def.name;
1081
+ return [` otea create --collection ${quoted} --title "<title>"${given}${wait}`];
1082
+ }
1083
+ // The Matrix, on a board that maps two scale roles (core/board/analysis.ts): what the person does
1084
+ // there and what it asks of an agent. An agent told "use the Matrix" knows the word from here.
1085
+ function matrixLines(def) {
1086
+ if (!viewsOf(def).includes('matrix'))
1087
+ return [];
1088
+ const names = mappedScales(def)
1089
+ .map((role) => rolePart(def, role)?.name)
1090
+ .filter((name) => name !== undefined);
1091
+ const [first = ''] = names;
1092
+ return [
1093
+ ` The person weighs this board’s items on the Matrix, ${names.join(' × ')}, and fixes the order you take them in: otea next offers them in that order. Estimate ${and(names, 'and')} on every item you create (otea create … --field "${first}=…"), the person’s own included, and on every item you take that lacks them (otea update <id> --field "${first}=…"); the person corrects you.`,
1094
+ ];
1095
+ }
1096
+ export function boardText(def) {
1097
+ const lines = [`${def.name}: steps for each ${def.item}`];
1098
+ lines.push(...section('About this board', indent(mentionText(def, def.about))));
1099
+ lines.push(...section('When there is nothing to do', indent(mentionText(def, def.idle))));
1100
+ if (def.cap.on)
1101
+ lines.push(...section('New items', [
1102
+ ` Add items only while fewer than ${def.cap.n} wait for the person.`,
1103
+ ]));
1104
+ lines.push(...section('What its fields take', fieldValueLines(def)));
1105
+ lines.push(...section('To add one', createLines(def)));
1106
+ lines.push(...section('The Matrix', matrixLines(def)));
1107
+ def.steps.forEach((step, index) => {
1108
+ const say = (title, text) => {
1109
+ const body = indent(mentionText(def, text)).map((line) => ` ${line}`);
1110
+ return body.length === 0 ? [] : [` ${title}`, ...body];
1111
+ };
1112
+ lines.push('', `${index + 1}. ${step.name}: ${whoDoes(step)}${whoReviews(step)}`, ...say('When you take it', step.instructions.take), ...say('Before you hand it off', step.instructions.before), ...(step.reviewer === 'none' ? [] : say('When you review it', step.instructions.review)));
1113
+ });
1114
+ lines.push('', 'Run otea next to get the item to take now.');
1115
+ return lines.join('\n');
1116
+ }