@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,48 @@
1
+ import { isClosed, positionOf } from '../core/board/engine.js';
2
+ import { guardedBranch } from '../core/board/model.js';
3
+ import { selectEvents, selectItems } from '../store/queries.js';
4
+ import { sameRepo } from './gates.js';
5
+ import { liveBoardOf, liveBoards } from './next.js';
6
+ // When an item came to name the value its field holds now: the last update that set it, or else
7
+ // its creation.
8
+ function namedAt(ctx, item, key) {
9
+ const now = item.fields[key];
10
+ const set = selectEvents(ctx.db, item.id).findLast(({ type, data }) => {
11
+ const changes = data.changes;
12
+ return type === 'updated' && changes?.[key] !== undefined && changes[key].to === now;
13
+ });
14
+ return set?.at ?? item.createdAt;
15
+ }
16
+ // The open item, of any board, that names `branch` as its protected branch and named it before
17
+ // `item` did (P1-R3-1): each item works on its own branch, and a second item naming one would have
18
+ // its review read the other's work and its approval keep the other's tip. The item that named it
19
+ // first keeps it, so the mistake of the later one never blocks it. Items on another repo (a board
20
+ // whose guard reads one) and closed items never count. Undefined when none does.
21
+ export function branchNamedFirst(ctx, item, branch) {
22
+ const own = liveBoardOf(ctx, item.collection);
23
+ const guard = own && guardedBranch(own.def);
24
+ if (!guard)
25
+ return undefined;
26
+ const repo = guard.guard.repo === undefined ? undefined : item.fields[guard.guard.repo];
27
+ const mine = namedAt(ctx, item, guard.id);
28
+ const before = (other, at) => at < mine || (at === mine && other.createdAt < item.createdAt);
29
+ let first;
30
+ for (const board of liveBoards(ctx)) {
31
+ const part = guardedBranch(board.def);
32
+ if (!part)
33
+ continue;
34
+ for (const other of selectItems(ctx.db, { collection: board.collection })) {
35
+ if (other.id === item.id || other.fields[part.id] !== branch)
36
+ continue;
37
+ if (isClosed(positionOf(other.state)))
38
+ continue;
39
+ const theirs = part.guard.repo === undefined ? undefined : other.fields[part.guard.repo];
40
+ if (typeof repo === 'string' && typeof theirs === 'string' && !sameRepo(theirs, repo))
41
+ continue;
42
+ const at = namedAt(ctx, other, part.id);
43
+ if (before(other, at) && (!first || at < first.at))
44
+ first = { item: other, at };
45
+ }
46
+ }
47
+ return first?.item;
48
+ }
@@ -0,0 +1,53 @@
1
+ import { fieldsByName, stateName } from '../core/board/reading.js';
2
+ import { DEFAULT_LIMITS, DEFAULT_SUCCESS, writeBrief } from '../core/brief.js';
3
+ import { OteaError } from '../core/errors.js';
4
+ import { timeText } from '../core/time.js';
5
+ import { listItems, systemClock } from './items.js';
6
+ import { liveBoardOf } from './next.js';
7
+ import { listRelations } from './relations.js';
8
+ // The fields by name, choices by name; the description keeps its key, as the brief leads with it.
9
+ function namedFields(def, fields) {
10
+ const { description, ...rest } = fields;
11
+ return {
12
+ ...(description === undefined ? {} : { description }),
13
+ ...fieldsByName(def, rest),
14
+ };
15
+ }
16
+ // A brief for the chosen items, read from the project as they stand now.
17
+ export function briefFor(project, request, now = systemClock) {
18
+ if (request.ids.length === 0) {
19
+ throw new OteaError('invalid_id', 'A brief needs at least one item');
20
+ }
21
+ const items = listItems(project, {}, now);
22
+ const byId = new Map(items.map((item) => [item.id, item]));
23
+ const chosen = [...new Set(request.ids)].map((id) => {
24
+ const item = byId.get(id);
25
+ if (!item)
26
+ throw new OteaError('not_found', `Item "${id}" not found`);
27
+ return item;
28
+ });
29
+ const limits = request.limits ?? DEFAULT_LIMITS;
30
+ const success = request.success ?? DEFAULT_SUCCESS;
31
+ const brief = writeBrief({
32
+ project: project.identity.name,
33
+ items: chosen.map(({ id, title, collection, state, fields }) => {
34
+ // On a board, its step and its fields by name, never the hidden ids under them.
35
+ const def = liveBoardOf(project, collection)?.def;
36
+ if (!def)
37
+ return { id, title, collection, state, fields };
38
+ return {
39
+ id,
40
+ title,
41
+ collection,
42
+ state: stateName(def, state),
43
+ fields: namedFields(def, fields),
44
+ };
45
+ }),
46
+ relations: listRelations(project),
47
+ isOpen: (id) => byId.get(id)?.closes === undefined,
48
+ limits,
49
+ success,
50
+ writtenAt: timeText(now()),
51
+ });
52
+ return { ...brief, limits, success };
53
+ }
@@ -0,0 +1,61 @@
1
+ import { choiceOf, OPTION_CHOSEN, pickAt } from '../core/board/choices.js';
2
+ import { isClosed, positionOf } from '../core/board/engine.js';
3
+ import { stepById } from '../core/board/model.js';
4
+ import { OteaError } from '../core/errors.js';
5
+ import { appendEvent, selectEvents } from '../store/queries.js';
6
+ function refuse(id, why, message) {
7
+ throw new OteaError(why === 'not_person' ? 'forbidden' : 'invalid_transition', message, {
8
+ kind: 'choice',
9
+ item: id,
10
+ why,
11
+ });
12
+ }
13
+ // A person's approval out of a review that asks for a pick, made without one, is refused: picking
14
+ // is the point of that review (the desk opens the pick for it).
15
+ export function assertPicked(def, item, move, choice) {
16
+ if (choice || move.actor.kind !== 'human')
17
+ return;
18
+ const at = pickAt(def, item);
19
+ if (!at?.forward.includes(move.to))
20
+ return;
21
+ const letters = at.options.map(({ letter }) => letter).join(', ');
22
+ refuse(item.id, 'no_pick', `Not approved ${item.id}: pick one of its options (${letters}) as you approve it, on its page`);
23
+ }
24
+ export function recordChoice(db, def, item, move, choice) {
25
+ const { id } = item;
26
+ if (move.actor.kind !== 'human')
27
+ refuse(id, 'not_person', `Not chosen on ${id}: only the person picks an option`);
28
+ const position = positionOf(item.state);
29
+ if (isClosed(position) || position.phase !== 'review')
30
+ refuse(id, 'not_review', `Not chosen on ${id}: an option is picked when approving a review`);
31
+ const found = pickAt(def, item);
32
+ if (!found)
33
+ refuse(id, 'no_options', `Not chosen on ${id}: this review asks for no pick`);
34
+ if (!found.forward.includes(move.to))
35
+ refuse(id, 'not_forward', `Not chosen on ${id}: an option goes with an approval, not a send-back`);
36
+ const letter = choice.option.trim().toUpperCase();
37
+ const option = found.options.find((each) => each.letter === letter);
38
+ if (!option) {
39
+ const letters = found.options.map((each) => each.letter).join(', ');
40
+ refuse(id, 'unknown_option', `Not chosen on ${id}: its options are ${letters}`);
41
+ }
42
+ const comment = choice.comment?.trim() ?? '';
43
+ const last = choiceOf(selectEvents(db, id));
44
+ if (last && last.option === option.letter && !comment)
45
+ return;
46
+ appendEvent(db, {
47
+ itemId: id,
48
+ type: OPTION_CHOSEN,
49
+ actor: move.actor,
50
+ at: move.at,
51
+ data: {
52
+ option: option.letter,
53
+ name: option.name,
54
+ ...(comment ? { comment } : {}),
55
+ part: found.part,
56
+ step: position.step,
57
+ stepName: stepById(def, position.step)?.name ?? position.step,
58
+ channel: move.channel,
59
+ },
60
+ });
61
+ }
@@ -0,0 +1,101 @@
1
+ import { OteaError } from '../core/errors.js';
2
+ import { assertIconName } from '../core/icons.js';
3
+ import { prefixFor } from '../core/item.js';
4
+ import { DEFAULT_TYPE, typeOf } from '../core/preset.js';
5
+ import { typeViews } from '../core/views.js';
6
+ import { listBoards } from '../store/boards.js';
7
+ import { transaction } from '../store/database.js';
8
+ import { collectionTaken, findCollection, hasItems, hasItemsOfType, insertCollection, listCollections, renameItemType, updateCollectionIcon, } from '../store/queries.js';
9
+ import { requirePreset } from './presets.js';
10
+ export const DEFAULT_PRESET = 'tasks';
11
+ // Inserts a collection inside an open transaction, so several can be added at once.
12
+ export function insertNewCollection({ db, presets }, input) {
13
+ const preset = requirePreset(presets, input.preset ?? DEFAULT_PRESET);
14
+ const icon = input.icon === undefined ? null : assertIconName(input.icon);
15
+ const collection = {
16
+ name: input.name,
17
+ prefix: prefixFor(input.name),
18
+ preset: preset.name,
19
+ presetVersion: preset.version,
20
+ nextSeq: 1,
21
+ icon,
22
+ };
23
+ if (collectionTaken(db, collection.name, collection.prefix)) {
24
+ throw new OteaError('already_exists', `Name "${collection.name}" or prefix "${collection.prefix}" already in use`);
25
+ }
26
+ insertCollection(db, collection);
27
+ return collection;
28
+ }
29
+ export function addCollection(ctx, input) {
30
+ return transaction(ctx.db, () => insertNewCollection(ctx, input));
31
+ }
32
+ // The name of the collection a reader names, in any case (findCollection); the name as given when
33
+ // no collection has it, so what reads it finds nothing, as before.
34
+ export function collectionNamed(db, name) {
35
+ return findCollection(db, name)?.name ?? name;
36
+ }
37
+ export function getCollection(db, name) {
38
+ const collection = findCollection(db, name);
39
+ if (!collection)
40
+ throw new OteaError('not_found', `Collection "${name}" not found`);
41
+ return collection;
42
+ }
43
+ export function presetOf(ctx, collection) {
44
+ return requirePreset(ctx.presets, collection.preset);
45
+ }
46
+ // The type an item is of, in its collection's preset.
47
+ export function typeOfItem(ctx, item) {
48
+ return typeOf(presetOf(ctx, getCollection(ctx.db, item.collection)), item.type);
49
+ }
50
+ // Items stored while their preset declared no types are of the implicit type; once the preset names
51
+ // its only type, they take that name. Reading first keeps every later open from taking the write
52
+ // lock. Returns how many items it renamed.
53
+ export function nameImplicitTypes(ctx) {
54
+ const renames = listCollections(ctx.db).flatMap(({ name, preset }) => {
55
+ const types = ctx.presets.presets.get(preset)?.types ?? [];
56
+ const [only] = types;
57
+ if (types.length !== 1 || !only || only.name === DEFAULT_TYPE)
58
+ return [];
59
+ return hasItemsOfType(ctx.db, name, DEFAULT_TYPE) ? [{ name, type: only.name }] : [];
60
+ });
61
+ if (renames.length === 0)
62
+ return 0;
63
+ return transaction(ctx.db, () => renames.reduce((total, { name, type }) => total + renameItemType(ctx.db, name, DEFAULT_TYPE, type), 0));
64
+ }
65
+ // The icon a collection shows: its own, or else its preset's; null when neither has one.
66
+ export function collectionIcon(ctx, collection) {
67
+ return collection.icon ?? presetOf(ctx, collection).icon ?? null;
68
+ }
69
+ // Gives a collection its own icon, or, with null, goes back to its preset's.
70
+ export function setCollectionIcon(ctx, name, icon) {
71
+ const valid = icon === null ? null : assertIconName(icon);
72
+ return transaction(ctx.db, () => {
73
+ const collection = getCollection(ctx.db, name);
74
+ updateCollectionIcon(ctx.db, collection.name, valid);
75
+ return { ...collection, icon: valid };
76
+ });
77
+ }
78
+ // `archived`: an archived board's collection too (what reading its items needs).
79
+ export function listCollectionViews(ctx, options = {}) {
80
+ return listCollections(ctx.db, options).map((collection) => {
81
+ const { types, view } = presetOf(ctx, collection);
82
+ return {
83
+ name: collection.name,
84
+ prefix: collection.prefix,
85
+ preset: collection.preset,
86
+ icon: collectionIcon(ctx, collection),
87
+ types: typeViews(types),
88
+ view,
89
+ };
90
+ });
91
+ }
92
+ // The collections the places show: the built-in Pedidos only once it holds an item (an agent's
93
+ // board draft arrives on it), so a new project lists only the boards the person picked.
94
+ export function listShownCollectionViews(ctx) {
95
+ const idle = idleRequests(ctx);
96
+ return listCollectionViews(ctx).filter(({ name }) => name !== idle);
97
+ }
98
+ // The built-in Pedidos while it holds no item: what the places (and otea board) leave out.
99
+ export function idleRequests(ctx) {
100
+ return (listBoards(ctx.db).find((row) => row.builtin && row.collection !== null && !hasItems(ctx.db, row.collection))?.collection ?? undefined);
101
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,56 @@
1
+ import { existsSync, readFileSync, writeFileSync } from 'node:fs';
2
+ import { tmpdir } from 'node:os';
3
+ import { join, resolve } from 'node:path';
4
+ import { OteaError } from '../core/errors.js';
5
+ import { cropPng, imageSize, pixelRect, zoneOf } from '../core/image-crop.js';
6
+ import { findEvidence } from '../store/queries.js';
7
+ import { evidenceFile } from './evidence.js';
8
+ import { notesView } from './notes.js';
9
+ const pct = (n) => `${Math.round(n * 10) / 10}`;
10
+ // An agent asks for the zone of an image a note is on, cut out (a point: a fifth of the image
11
+ // around it). A PNG is cut into a file of its own, in the system's temp folder unless --out says
12
+ // where; any other image gets the zone's box in its pixels and where the file is.
13
+ export function cropNote(project, input) {
14
+ const { id, note } = input;
15
+ const found = notesView(project, id).notes.find((n) => n.note === note);
16
+ const anchor = found?.anchor;
17
+ if (!found || !anchor || anchor.x === undefined || anchor.y === undefined)
18
+ throw new OteaError('invalid_fields', found
19
+ ? `Note ${note} of ${id} is not on a point or a zone of an image: there is nothing to cut out`
20
+ : `${id} has no note ${note}`);
21
+ const zone = zoneOf({
22
+ x: anchor.x,
23
+ y: anchor.y,
24
+ ...(anchor.w === undefined ? {} : { w: anchor.w }),
25
+ ...(anchor.h === undefined ? {} : { h: anchor.h }),
26
+ });
27
+ const where = `x ${pct(zone.x)}–${pct(zone.x + zone.w)}%, y ${pct(zone.y)}–${pct(zone.y + zone.h)}%`;
28
+ const evidence = findEvidence(project.db, anchor.evidence);
29
+ const source = evidence ? evidenceFile(project.dataDir, evidence.sha256) : undefined;
30
+ const bytes = source && existsSync(source) ? readFileSync(source) : undefined;
31
+ const size = bytes ? imageSize(bytes) : null;
32
+ const base = { id, note, filename: anchor.filename, zone };
33
+ if (!bytes || !size)
34
+ return {
35
+ ...base,
36
+ text: `The zone of note ${note} is ${where} of ${anchor.filename}; Otea cannot read its size.`,
37
+ };
38
+ const rect = pixelRect(zone, size);
39
+ const pixels = { ...rect, of: `${size.width}×${size.height}` };
40
+ const box = `pixels ${rect.left},${rect.top} to ${rect.left + rect.width},${rect.top + rect.height} of ${size.width}×${size.height}`;
41
+ const cut = size.format === 'png' ? cropPng(bytes, rect) : null;
42
+ if (!cut)
43
+ return {
44
+ ...base,
45
+ pixels,
46
+ text: `The zone of note ${note} is ${where} of ${anchor.filename} (${box}); Otea cuts PNG images only. The image: ${source}`,
47
+ };
48
+ const file = resolve(input.out ?? join(tmpdir(), `otea-${id}-note-${note}.png`));
49
+ writeFileSync(file, cut);
50
+ return {
51
+ ...base,
52
+ pixels,
53
+ file,
54
+ text: `Cut the zone of note ${note}, ${where} of ${anchor.filename} (${box}), into ${file}`,
55
+ };
56
+ }
@@ -0,0 +1,62 @@
1
+ import { createHash, randomBytes } from 'node:crypto';
2
+ import { OteaError } from '../core/errors.js';
3
+ export const MAX_DEVICE_NAME = 60;
4
+ const hashToken = (token) => createHash('sha256').update(token).digest('hex');
5
+ function toDevice(row) {
6
+ return {
7
+ id: row.id,
8
+ name: row.name,
9
+ pairedAt: row.paired_at,
10
+ lastSeenAt: row.last_seen_at,
11
+ hint: row.token_hash.slice(-4),
12
+ via: row.via === 'tailscale' || row.via === 'lan' ? row.via : null,
13
+ };
14
+ }
15
+ export function deviceName(name) {
16
+ const trimmed = name.replace(/\s+/g, ' ').trim();
17
+ if (trimmed === '' || trimmed.length > MAX_DEVICE_NAME) {
18
+ throw new OteaError('invalid_name', `A device name has 1 to ${MAX_DEVICE_NAME} characters`);
19
+ }
20
+ return trimmed;
21
+ }
22
+ // Pairs a device and hands back its token, the only time it exists outside the device.
23
+ export function pairDevice(db, name, now = new Date(), via = null) {
24
+ const token = randomBytes(32).toString('base64url');
25
+ const id = randomBytes(4).toString('hex');
26
+ db.prepare('INSERT INTO devices (id, name, token_hash, paired_at, last_seen_at, via) VALUES (?, ?, ?, ?, ?, ?)').run(id, deviceName(name), hashToken(token), now.toISOString(), now.toISOString(), via);
27
+ const row = db.prepare('SELECT * FROM devices WHERE id = ?').get(id);
28
+ return { device: toDevice(row), token };
29
+ }
30
+ // Pairs a device that is paired already once more: it keeps its id (and so its notifications),
31
+ // takes the new name and a new token, and the old token opens nothing from now on.
32
+ export function repairDevice(db, id, name, now = new Date(), via = null) {
33
+ const token = randomBytes(32).toString('base64url');
34
+ db.prepare('UPDATE devices SET name = ?, token_hash = ?, paired_at = ?, last_seen_at = ?, via = coalesce(?, via) WHERE id = ?').run(deviceName(name), hashToken(token), now.toISOString(), now.toISOString(), via, id);
35
+ const row = db.prepare('SELECT * FROM devices WHERE id = ?').get(id);
36
+ if (!row)
37
+ throw new OteaError('not_found', `No paired device ${id}`);
38
+ return { device: toDevice(row), token };
39
+ }
40
+ // In the order they were paired: two paired in the same millisecond keep the order of their rows,
41
+ // not that of their random ids.
42
+ export function listDevices(db) {
43
+ const rows = db.prepare('SELECT * FROM devices ORDER BY paired_at, rowid').all();
44
+ return rows.map(toDevice);
45
+ }
46
+ // The device a token belongs to; a revoked device's token matches nothing.
47
+ export function deviceByToken(db, token) {
48
+ if (token === '')
49
+ return undefined;
50
+ const row = db.prepare('SELECT * FROM devices WHERE token_hash = ?').get(hashToken(token));
51
+ return row ? toDevice(row) : undefined;
52
+ }
53
+ export function touchDevice(db, id, now = new Date(), via = null) {
54
+ db.prepare('UPDATE devices SET last_seen_at = ?, via = coalesce(?, via) WHERE id = ?').run(now.toISOString(), via, id);
55
+ }
56
+ export function revokeDevice(db, id) {
57
+ const row = db.prepare('SELECT * FROM devices WHERE id = ?').get(id);
58
+ if (!row)
59
+ throw new OteaError('not_found', `No paired device ${id}`);
60
+ db.prepare('DELETE FROM devices WHERE id = ?').run(id);
61
+ return toDevice(row);
62
+ }
@@ -0,0 +1,82 @@
1
+ import { fileURLToPath } from 'node:url';
2
+ import { isClosed, positionOf } from '../core/board/engine.js';
3
+ import { readDefinition } from '../core/board/schema.js';
4
+ import { activeLease } from '../core/lease.js';
5
+ import { findBoard, findDraft, findVersion, listBoards } from '../store/boards.js';
6
+ import { findItem, selectEvents } from '../store/queries.js';
7
+ // A Pedido an agent drafts a board on ("Que lo esboce un agente"): the board waiting on it, and how
8
+ // the agent hands its draft in. The person's words stay the Pedido's field; how to hand it in is
9
+ // the step's instructions, which the agent reads in next and show and the page shows apart.
10
+ export const DRAFT_FILENAME = 'board.json';
11
+ // How the agent hands in the draft of the Pedido `id`: on stdin (--file -), so no board.json is
12
+ // left in the repo, nor written outside the project, where a harness asks the person's leave for
13
+ // every command that touches it (P8-R2-14, P1-R3-10).
14
+ export function handInCommand(id, agent = '<your name>') {
15
+ return `otea board draft ${id} --file - --as ${agent}`;
16
+ }
17
+ // The Pedido's title: the board it asks for, by the name the board has now.
18
+ const TITLE = {
19
+ en: (name) => `Draft the board ${name}`,
20
+ es: (name) => `Esbozar el tablero ${name}`,
21
+ };
22
+ export function draftTitle(lang, name) {
23
+ return TITLE[lang](name.trim());
24
+ }
25
+ // The JSON Schema of board.json Otea ships, generated from the board's zod schema.
26
+ export const BOARD_JSON_SCHEMA = fileURLToPath(new URL('../../schemas/board.schema.json', import.meta.url));
27
+ // How the agent hands its draft in on the Pedido `id`: agents read English. Each command names the
28
+ // agent (`agent`, the one drafting it), so it works as printed (P3C-R3-14).
29
+ export function handInText(id, agent = '<your name>') {
30
+ return [
31
+ `How to hand it in: start from the draft it prints with otea board draft ${id} --as ${agent},`,
32
+ 'change it (keep the ids of what is there; give what you add new ids), then hand it in on stdin, so no file is left in the repo nor written outside it:',
33
+ `${handInCommand(id, agent)}, with the JSON piped in (a here-document of your shell). It says what is wrong until the board is right.`,
34
+ `To check it before: its shape, each key with an example, is the JSON Schema ${BOARD_JSON_SCHEMA}.`,
35
+ 'Who does each step is its doer (any agent, a named agent or the person), never its text: write its instructions to whoever does it, and call the person "the person" (in Spanish, "la persona").',
36
+ 'Branches follow how the person works. For code, ask the person whether anything may reach the remote before they see it. When they work straight on main and want nothing pushed before they see it ("do not push anything I have not seen"), start from the mainline template (Code on main): each item\'s branch is main and only the step after their approval pushes it, so the gate refuses a push of main until they approve, wherever the repo has Otea\'s git hook, which Publicar offers to install (tell the person: without it, git lets a push through); never draft code on todos, which has no gate. When they work straight on main and pushes need not wait, take the guard off the branch part (or the part itself).',
37
+ 'Handing it in is your handoff: the person tries the board and publishes it in Studio, which closes this Pedido; there is no otea handoff to run.',
38
+ ].join('\n');
39
+ }
40
+ // `agent`: the agent the instructions name, else the one that holds or last held the Pedido.
41
+ export function draftRequestOf(ctx, item, agent) {
42
+ for (const { id } of listBoards(ctx.db)) {
43
+ const draft = findDraft(ctx.db, id);
44
+ if (draft?.requestItem !== item)
45
+ continue;
46
+ return {
47
+ board: id,
48
+ name: readDefinition(draft.definition).name,
49
+ arrived: draft.agentNote !== null,
50
+ instructions: handInText(item, agent ?? findItem(ctx.db, item)?.lease?.holder),
51
+ };
52
+ }
53
+ return publishedRequestOf(ctx, item);
54
+ }
55
+ // The board drafts an agent began and has not handed in yet, each with its Pedido and the agent
56
+ // that holds it now (null when none does): what a new session is pointed to (otea whoami), as one
57
+ // a restart cut off may have been drafting one.
58
+ export function openDraftsOf(ctx, at) {
59
+ return listBoards(ctx.db).flatMap(({ id }) => {
60
+ const draft = findDraft(ctx.db, id);
61
+ const item = draft?.requestItem ? findItem(ctx.db, draft.requestItem) : undefined;
62
+ if (!draft || !item || draft.agentNote !== null || isClosed(positionOf(item.state)))
63
+ return [];
64
+ const holder = activeLease(item.lease, at)?.holder ?? null;
65
+ return [{ item: item.id, name: readDefinition(draft.definition).name, holder }];
66
+ });
67
+ }
68
+ // The board whose publish closed the Pedido, while that publish stands (undoing it writes
69
+ // `unpublished_board`) and the board is still live, under its name today.
70
+ function publishedRequestOf(ctx, item) {
71
+ const mark = selectEvents(ctx.db, item).findLast(({ type, data }) => type === 'transitioned' &&
72
+ (typeof data.published_board === 'string' || typeof data.unpublished_board === 'string'));
73
+ const id = mark?.data.published_board;
74
+ if (typeof id !== 'string')
75
+ return undefined;
76
+ const row = findBoard(ctx.db, id);
77
+ const live = row?.liveVersion == null ? undefined : findVersion(ctx.db, id, row.liveVersion);
78
+ if (!live)
79
+ return undefined;
80
+ const name = readDefinition(live.definition).name;
81
+ return { board: id, name, arrived: true, published: true, instructions: '' };
82
+ }
@@ -0,0 +1,12 @@
1
+ import { selectEventsAfter } from '../store/queries.js';
2
+ import { getCollection } from './collections.js';
3
+ import { requireItem } from './items.js';
4
+ // The event log across items in commit order: `since` is the id of the last event already read.
5
+ export function listEvents(ctx, filter = {}) {
6
+ if (filter.item !== undefined)
7
+ requireItem(ctx.db, filter.item);
8
+ if (filter.collection === undefined)
9
+ return selectEventsAfter(ctx.db, filter);
10
+ const { name } = getCollection(ctx.db, filter.collection);
11
+ return selectEventsAfter(ctx.db, { ...filter, collection: name });
12
+ }