@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,145 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import { existsSync, mkdirSync, realpathSync } from 'node:fs';
3
+ import { homedir } from 'node:os';
4
+ import { join, resolve } from 'node:path';
5
+ import { OteaError } from '../core/errors.js';
6
+ import { longestContaining, pathKey } from '../core/path-key.js';
7
+ import { compareRepos } from '../core/repo.js';
8
+ import { openDatabase, transaction } from '../store/database.js';
9
+ import { deleteProjectPath, insertProjectPath, insertRegisteredProject, migrateRegistry, selectProjectPaths, selectRegisteredProject, selectRegisteredProjects, updateProjectPath, } from '../store/registry.js';
10
+ // The user-level Otea folder: OTEA_HOME, or ~/.otea on every OS.
11
+ export function oteaHome(env = process.env) {
12
+ return env.OTEA_HOME ? resolve(env.OTEA_HOME) : join(homedir(), '.otea');
13
+ }
14
+ function registryPath(env) {
15
+ return join(oteaHome(env), 'registry.db');
16
+ }
17
+ export function openRegistry(env = process.env) {
18
+ mkdirSync(oteaHome(env), { recursive: true });
19
+ const db = openDatabase(registryPath(env));
20
+ migrateRegistry(db);
21
+ return db;
22
+ }
23
+ // Runs `use` on the registry, or returns undefined without creating it when there is none yet.
24
+ export function withRegistry(env, use) {
25
+ if (!existsSync(registryPath(env)))
26
+ return undefined;
27
+ const registry = openRegistry(env);
28
+ try {
29
+ return use(registry);
30
+ }
31
+ finally {
32
+ registry.close();
33
+ }
34
+ }
35
+ export function registerProject(registry, project) {
36
+ insertRegisteredProject(registry, project);
37
+ }
38
+ // The real path of a folder, or the resolved one when it no longer exists (a moved repo).
39
+ export function keyOf(path) {
40
+ const real = existsSync(path) ? realpathSync.native(path) : resolve(path);
41
+ return { path: real, pathKey: pathKey(real, process.platform) };
42
+ }
43
+ export const kindOf = (path) => existsSync(join(path, '.git')) ? 'repo' : 'folder';
44
+ function git(cwd, ...args) {
45
+ try {
46
+ const output = execFileSync('git', args, {
47
+ cwd,
48
+ encoding: 'utf8',
49
+ stdio: ['ignore', 'pipe', 'ignore'],
50
+ });
51
+ return output.trim() || null;
52
+ }
53
+ catch {
54
+ return null;
55
+ }
56
+ }
57
+ export function repoFingerprint(path) {
58
+ const roots = git(path, 'rev-list', '--max-parents=0', 'HEAD');
59
+ return {
60
+ remoteUrl: git(path, 'config', '--get', 'remote.origin.url'),
61
+ rootCommit: roots?.split(/\s+/).sort().join(' ') ?? null,
62
+ };
63
+ }
64
+ function linkedFolder(path, projectId, kind) {
65
+ if (!existsSync(path))
66
+ throw new OteaError('not_found', `No folder at ${path}`);
67
+ const fingerprint = kind === 'repo' ? repoFingerprint(path) : { remoteUrl: null, rootCommit: null };
68
+ return { ...keyOf(path), projectId, kind, ...fingerprint };
69
+ }
70
+ function assertFree(registry, pathKey, path) {
71
+ const taken = selectProjectPaths(registry).find((linked) => linked.pathKey === pathKey);
72
+ if (taken) {
73
+ throw new OteaError('already_exists', `${path} is already linked to ${taken.projectId}`);
74
+ }
75
+ }
76
+ // Links an existing folder to a registered project. A folder leads to one project only.
77
+ export function addProjectPath(registry, projectId, path, kind) {
78
+ const entry = linkedFolder(path, projectId, kind);
79
+ assertFree(registry, entry.pathKey, entry.path);
80
+ insertProjectPath(registry, entry);
81
+ return entry;
82
+ }
83
+ function linkedExactly(registry, path) {
84
+ const { pathKey: key, path: resolved } = keyOf(path);
85
+ const link = selectProjectPaths(registry).find((linked) => linked.pathKey === key);
86
+ if (!link)
87
+ throw new OteaError('not_found', `${resolved} is not linked to any project`);
88
+ return link;
89
+ }
90
+ // Points a link at the folder a repo moved to. The new folder must hold the same repo: same origin
91
+ // URL or same root commit, compared with the old folder if it still exists, else with what was
92
+ // recorded when it was linked. `force` links it anyway when they differ.
93
+ export function relinkProjectPath(registry, from, to, force = false) {
94
+ const old = linkedExactly(registry, from);
95
+ const entry = linkedFolder(to, old.projectId, kindOf(to));
96
+ const before = existsSync(old.path) && old.kind === 'repo' ? repoFingerprint(old.path) : old;
97
+ const match = compareRepos(before, entry);
98
+ if (match === 'different' && !force) {
99
+ throw new OteaError('different_repo', `${entry.path} is not the repo linked at ${old.path} (no matching remote URL or root commit); pass --force to relink anyway`);
100
+ }
101
+ if (entry.pathKey !== old.pathKey)
102
+ assertFree(registry, entry.pathKey, entry.path);
103
+ transaction(registry, () => updateProjectPath(registry, old.pathKey, entry));
104
+ return { link: entry, from: old.path, match };
105
+ }
106
+ // Unlinks a folder. The project and its data stay; with no folder left nothing resolves to it.
107
+ export function forgetProjectPath(registry, path) {
108
+ const link = linkedExactly(registry, path);
109
+ deleteProjectPath(registry, link.pathKey);
110
+ const remaining = selectProjectPaths(registry).filter((p) => p.projectId === link.projectId);
111
+ return { link, remaining: remaining.length };
112
+ }
113
+ // The nearest linked folder at or above `path`, with its project.
114
+ export function linkAt(registry, path) {
115
+ const link = longestContaining(selectProjectPaths(registry), keyOf(path).pathKey);
116
+ const project = link && selectRegisteredProject(registry, link.projectId);
117
+ return link && project && { link, project };
118
+ }
119
+ export function projectAt(registry, path) {
120
+ return linkAt(registry, path)?.project;
121
+ }
122
+ // A registered project by id, or by name when no other project has it.
123
+ export function findProject(registry, ref) {
124
+ const projects = selectRegisteredProjects(registry);
125
+ const byId = projects.find((project) => project.id === ref);
126
+ if (byId)
127
+ return byId;
128
+ const named = projects.filter((project) => project.name === ref);
129
+ if (named.length === 1 && named[0])
130
+ return named[0];
131
+ if (named.length > 1) {
132
+ const ids = named.map((project) => project.id).join(', ');
133
+ throw new OteaError('invalid_name', `Several projects are named "${ref}" (${ids}); use its id`);
134
+ }
135
+ throw new OteaError('not_found', `No registered project "${ref}"; run otea projects list`);
136
+ }
137
+ export function listProjects(registry) {
138
+ const paths = selectProjectPaths(registry);
139
+ return selectRegisteredProjects(registry).map((project) => ({
140
+ ...project,
141
+ paths: paths
142
+ .filter((linked) => linked.projectId === project.id)
143
+ .map(({ path, kind }) => ({ path, kind, missing: !existsSync(path) })),
144
+ }));
145
+ }
@@ -0,0 +1,36 @@
1
+ import { isListedKey, isSetKey, TEMPLATES } from '../core/board/templates.js';
2
+ import { OteaError } from '../core/errors.js';
3
+ import { addBoard, addBoardSet, listBoardSummaries } from './boards.js';
4
+ // The boards `otea init --template` starts a project with, only while it has no boards of its own
5
+ // (Pedidos aside): a template set's boards or one template's board, published at once. Without a
6
+ // template, or with `none`, it makes none: the person picks them. A template is checked even when
7
+ // no board is made, so a typo always fails.
8
+ const BY = { kind: 'human', name: 'otea' };
9
+ // Starts the project without boards (they are made later in Studio or with otea board add).
10
+ export const NO_BOARDS = 'none';
11
+ export function hasOwnBoards(ctx) {
12
+ return listBoardSummaries(ctx).some(({ builtin }) => !builtin);
13
+ }
14
+ export function initBoards(ctx, template, lang) {
15
+ if (template !== undefined && template !== NO_BOARDS && !isListedKey(template)) {
16
+ throw new OteaError('not_found', `There is no template ${template}`);
17
+ }
18
+ if (template === NO_BOARDS || hasOwnBoards(ctx))
19
+ return [];
20
+ // A project starts with no board: the person picks the ones it uses, here or in Studio.
21
+ if (template === undefined)
22
+ return [];
23
+ if (isSetKey(template)) {
24
+ const made = addBoardSet(ctx, { set: template, lang, boards: [], by: BY });
25
+ return made.map(({ record }) => named(record));
26
+ }
27
+ return [single(ctx, template, lang)];
28
+ }
29
+ function single(ctx, key, lang) {
30
+ const template = TEMPLATES.find((candidate) => candidate.key === key);
31
+ const name = template?.board[lang] ?? key;
32
+ return named(addBoard(ctx, { name, template: key, lang, by: BY }).record);
33
+ }
34
+ function named(record) {
35
+ return { id: record.id, name: (record.live ?? record.draft)?.definition.name ?? '' };
36
+ }
@@ -0,0 +1,25 @@
1
+ import { transaction } from '../store/database.js';
2
+ import { placeFile, recordEvidence } from './evidence.js';
3
+ import { insertNewItem, requireWritableItem, systemClock, } from './items.js';
4
+ // A new item and the files it was filed with, in one write: every file is placed (size, module,
5
+ // role) before any is stored, and a refusal of any of them creates nothing.
6
+ export function createItemWithEvidence(project, input, files, now = systemClock) {
7
+ return transaction(project.db, () => {
8
+ const at = now();
9
+ const { item, created } = insertNewItem(project, input, at);
10
+ const placed = files.map((file) => placeFile(project, item, file, input.actor, at));
11
+ const evidence = placed.map((file) => recordEvidence(project, item.id, file, input, at));
12
+ return { ...created, evidence };
13
+ });
14
+ }
15
+ // Files the person adds to an item that exists (ONB-18), in one write: every file is placed before
16
+ // any is stored, and a refusal of any of them attaches nothing. On a board they go where a person's
17
+ // files go (app/evidence.ts personsPlace): never into a part an agent hands, unless named.
18
+ export function attachFiles(project, input, files, now = systemClock) {
19
+ return transaction(project.db, () => {
20
+ const item = requireWritableItem(project.db, input.id);
21
+ const at = now();
22
+ const placed = files.map((file) => placeFile(project, item, file, input.actor, at));
23
+ return placed.map((file) => recordEvidence(project, item.id, file, input, at));
24
+ });
25
+ }
@@ -0,0 +1,141 @@
1
+ import { searchWords, wordsHeld } from '../core/search-words.js';
2
+ export const ITEM_HITS_AT_MOST = 5;
3
+ const SAID_MAX = 200;
4
+ const short = (text) => {
5
+ const line = text.trim().replace(/\s+/g, ' ');
6
+ return line.length <= SAID_MAX ? line : `${line.slice(0, SAID_MAX - 1).trimEnd()}…`;
7
+ };
8
+ // What an event of the item's thread says: its text, or its note when that is words (a handoff's
9
+ // or a send-back's), never a note's number.
10
+ function textOf(data) {
11
+ if (typeof data.text === 'string' && data.text.trim() !== '')
12
+ return data.text;
13
+ if (typeof data.note === 'string' && data.note.trim() !== '')
14
+ return data.note;
15
+ return undefined;
16
+ }
17
+ function kindOf(type, person) {
18
+ if (type === 'question_answered')
19
+ return 'answer';
20
+ if (type === 'question_asked')
21
+ return 'question';
22
+ if (type === 'note_left')
23
+ return 'note';
24
+ if (type === 'note_answered')
25
+ return 'reply';
26
+ if (type === 'transitioned')
27
+ return person ? 'move' : 'handoff';
28
+ return 'other';
29
+ }
30
+ // Of two entries, the one an item says best: the most words searched, the person's before an
31
+ // agent's, the latest of those.
32
+ function better(searched) {
33
+ return (kept, each) => {
34
+ const diff = wordsHeld(each.text, searched) - wordsHeld(kept.text, searched);
35
+ if (diff !== 0)
36
+ return diff > 0 ? each : kept;
37
+ if (each.person !== kept.person)
38
+ return each.person ? each : kept;
39
+ return each.at >= kept.at ? each : kept;
40
+ };
41
+ }
42
+ function saidOf({ text, ...rest }) {
43
+ return { said: short(text), ...rest };
44
+ }
45
+ // The items whose title, fields or thread hold any of the words searched, the one that holds the
46
+ // most first, then the one that said it last; five at most.
47
+ export function searchItems(ctx, search) {
48
+ const searched = searchWords(search);
49
+ if (searched.length === 0)
50
+ return [];
51
+ const items = ctx.db
52
+ .prepare('SELECT id, title, fields, created_at, created_by_name FROM items ORDER BY id')
53
+ .all();
54
+ const threads = new Map();
55
+ const events = ctx.db
56
+ .prepare('SELECT item_id, type, actor_kind, actor_name, at, data FROM events ORDER BY id')
57
+ .all();
58
+ for (const event of events) {
59
+ const data = JSON.parse(event.data);
60
+ const text = textOf(data);
61
+ if (text === undefined)
62
+ continue;
63
+ const person = event.actor_kind === 'human';
64
+ const via = typeof data.via === 'string' ? { via: data.via } : {};
65
+ const kind = kindOf(event.type, person);
66
+ const thread = threads.get(event.item_id) ?? [];
67
+ thread.push({ text, by: event.actor_name, at: event.at, kind, person, ...via });
68
+ threads.set(event.item_id, thread);
69
+ }
70
+ const best = better(searched);
71
+ const hits = items.flatMap((item) => {
72
+ const fields = Object.values(JSON.parse(item.fields || '{}'));
73
+ const own = [item.title, ...fields.filter((value) => typeof value === 'string')].map((text) => ({
74
+ text,
75
+ by: item.created_by_name,
76
+ at: item.created_at,
77
+ kind: 'item',
78
+ person: false,
79
+ }));
80
+ const thread = threads.get(item.id) ?? [];
81
+ const all = [...own, ...thread];
82
+ const score = wordsHeld(all.map(({ text }) => text).join('\n'), searched);
83
+ if (score === 0)
84
+ return [];
85
+ const top = all.reduce(best);
86
+ const persons = thread.filter((each) => each.person && wordsHeld(each.text, searched) > 0);
87
+ const theirs = top.person || persons.length === 0 ? undefined : persons.reduce(best);
88
+ const hit = {
89
+ id: item.id,
90
+ title: item.title,
91
+ ...saidOf(top),
92
+ ...(theirs ? { theirs: saidOf(theirs) } : {}),
93
+ };
94
+ return [{ hit, score }];
95
+ });
96
+ return hits
97
+ .sort((a, b) => b.score - a.score || b.hit.at.localeCompare(a.hit.at))
98
+ .slice(0, ITEM_HITS_AT_MOST)
99
+ .map(({ hit }) => hit);
100
+ }
101
+ // What an entry is and who said it, as an agent reads it before its words; nothing for the item's
102
+ // own words.
103
+ function whoSaid({ by, kind, via }) {
104
+ if (kind === 'item')
105
+ return undefined;
106
+ if (kind === 'answer')
107
+ return via ? `the person's answer (noted from the chat by ${via})` : "the person's answer";
108
+ if (kind === 'note')
109
+ return "the person's note";
110
+ if (kind === 'move')
111
+ return "the person's note on a move";
112
+ if (kind === 'question')
113
+ return `${by}'s question`;
114
+ if (kind === 'reply')
115
+ return `${by}'s reply`;
116
+ if (kind === 'handoff')
117
+ return `${by}'s handoff note`;
118
+ return by;
119
+ }
120
+ function saidLine(said) {
121
+ const who = whoSaid(said);
122
+ return ` ${who ? `${who}: ` : ''}${said.said}`;
123
+ }
124
+ // An item found as its lines: `head` (its id and title), then what it said, unless that is its
125
+ // title, and the person's own words beside it.
126
+ export function itemHitLines(hit, head = `${hit.id} ${hit.title}`) {
127
+ return [
128
+ head,
129
+ ...(hit.said === hit.title ? [] : [saidLine(hit)]),
130
+ ...(hit.theirs ? [saidLine(hit.theirs)] : []),
131
+ ];
132
+ }
133
+ // The items found, after the topics.
134
+ export function itemHitsText(hits) {
135
+ if (hits.length === 0)
136
+ return '';
137
+ return [
138
+ "In the items' threads (otea show <id>):",
139
+ ...hits.flatMap((hit) => itemHitLines(hit)),
140
+ ].join('\n');
141
+ }
@@ -0,0 +1,318 @@
1
+ import { authorizeMove } from '../core/authority.js';
2
+ import { guardedBranch } from '../core/board/model.js';
3
+ import { openQuestion } from '../core/board/questions.js';
4
+ import { OteaError } from '../core/errors.js';
5
+ import { assertCanLeave, intake, revise } from '../core/fields.js';
6
+ import { assertStandsAlone } from '../core/hierarchy.js';
7
+ import { formatItemId } from '../core/item.js';
8
+ import { activeLease } from '../core/lease.js';
9
+ import { typeFor, typeOf } from '../core/preset.js';
10
+ import { childrenSummary } from '../core/relations.js';
11
+ import { itemMoves } from '../core/views.js';
12
+ import { closesOf, turnOf } from '../core/workflow.js';
13
+ import { findBoardOfCollection } from '../store/boards.js';
14
+ import { transaction } from '../store/database.js';
15
+ import { appendEvent, archivedBoardOf, boardArchived, claimNextSeq, clearLease, collectionArchived, findItem, insertClientKey, insertItem, listCollections, selectEvents, selectEvidence, selectItems, selectRelations, selectStateEntries, updateItemContent, updateItemState, } from '../store/queries.js';
16
+ import { askingItems, withAsks } from './asking.js';
17
+ import { assertPicked, recordChoice } from './choices.js';
18
+ import { collectionNamed, getCollection, presetOf, typeOfItem } from './collections.js';
19
+ import { draftRequestOf } from './draft-request.js';
20
+ import { presentEvidence } from './evidence.js';
21
+ import { assertMayWriteItem } from './lease-take.js';
22
+ import { assertBranchMayChange, assertMayStandAlone, assertMoveHandsOff, backWithComments, boardBlockOf, boardFieldInput, boardMoves, boardStart, boardState, liftWhenWaitsClose, liveBoardOf, } from './next.js';
23
+ import { addRelation, assertMayEnter, childIds, childrenOf, refsOf, relatedItems, withRelations, } from './relations.js';
24
+ export const systemClock = () => new Date().toISOString();
25
+ // The names of the states an event is about (`{ from, to }` gives fromName and toName), kept with
26
+ // it so its history still reads them once their step is deleted; none for a state known by its key.
27
+ export function stateNames(workflow, states) {
28
+ return Object.fromEntries(Object.entries(states).flatMap(([key, state]) => {
29
+ const label = workflow.states.find(({ name }) => name === state)?.label;
30
+ return label === undefined ? [] : [[`${key}Name`, label]];
31
+ }));
32
+ }
33
+ // What readers see: the turn (and, once closed, how) derived from the state, and only a lease that
34
+ // is still active at `at`; one that ran out without a release is kept apart, as expiredLease.
35
+ export function present(item, workflow, at) {
36
+ const lease = activeLease(item.lease, at);
37
+ const presented = { ...item, turn: turnOf(workflow, item.state), lease };
38
+ if (item.lease && !lease)
39
+ presented.expiredLease = item.lease;
40
+ const closes = closesOf(workflow, item.state);
41
+ if (closes !== undefined)
42
+ presented.closes = closes;
43
+ return presented;
44
+ }
45
+ export function requireItem(db, id) {
46
+ const item = findItem(db, id);
47
+ if (!item)
48
+ throw new OteaError('not_found', `Item "${id}" not found`, { kind: 'item_missing', item: id });
49
+ return item;
50
+ }
51
+ // An item a write acts on: one on an archived board is refused before anything else is checked.
52
+ export function requireWritableItem(db, id) {
53
+ const item = requireItem(db, id);
54
+ const board = archivedBoardOf(db, id);
55
+ if (board !== undefined)
56
+ throw boardArchived(id, board);
57
+ return item;
58
+ }
59
+ // The workflow an item follows: its type's.
60
+ export function workflowOf(ctx, item) {
61
+ return typeOfItem(ctx, item).workflow;
62
+ }
63
+ // Writes the item, its created event and its parent link, inside the caller's transaction.
64
+ export function insertNewItem(ctx, input, at) {
65
+ const { db } = ctx;
66
+ const collection = getCollection(db, input.collection);
67
+ if (collectionArchived(db, collection.name))
68
+ throw new OteaError('board_archived', `${collection.name} is an archived board: it takes no new items until the person restores it in Studio`, { kind: 'board_archived', board: collection.name });
69
+ const preset = presetOf(ctx, collection);
70
+ const type = typeFor(preset, input.type);
71
+ if (input.parent === undefined)
72
+ assertStandsAlone(preset, type);
73
+ assertMayStandAlone(ctx, collection.name, input.parent);
74
+ const given = boardFieldInput(ctx, collection.name, input.fields ?? {});
75
+ const taken = intake(type, { ...given, title: input.title });
76
+ const { title, fields } = taken;
77
+ // On a board the engine says where the item starts.
78
+ const state = boardStart(ctx, collection.name, { ...fields, title }) ?? taken.state;
79
+ const seq = claimNextSeq(db, collection.name);
80
+ const item = {
81
+ id: formatItemId(collection.prefix, seq),
82
+ collection: collection.name,
83
+ seq,
84
+ type: type.name,
85
+ title,
86
+ fields,
87
+ presetVersion: preset.version,
88
+ state,
89
+ createdAt: at,
90
+ updatedAt: at,
91
+ createdBy: input.actor,
92
+ lease: null,
93
+ };
94
+ insertItem(db, item);
95
+ if (input.clientKey !== undefined)
96
+ insertClientKey(db, input.clientKey, item.id, at);
97
+ const { channel } = input;
98
+ const named = { state, ...stateNames(type.workflow, { state }) };
99
+ const data = channel === undefined ? named : { ...named, channel };
100
+ appendEvent(db, { itemId: item.id, type: 'created', actor: input.actor, at, data });
101
+ const created = present(item, type.workflow, at);
102
+ if (input.parent === undefined)
103
+ return { item, created };
104
+ const parent = { kind: 'parent', from: item.id, to: input.parent };
105
+ addRelation(ctx, parent, { actor: input.actor, channel: channel ?? 'cli' }, at);
106
+ return { item, created: { ...created, relations: refsOf([parent], item.id) } };
107
+ }
108
+ export function createItem(ctx, input, now = systemClock) {
109
+ return transaction(ctx.db, () => insertNewItem(ctx, input, now()).created);
110
+ }
111
+ function holdsFields(item, fields) {
112
+ return Object.entries(fields).every(([key, value]) => (key === 'title' ? item.title : item.fields[key]) === value);
113
+ }
114
+ export function listItems(ctx, filter = {}, now = systemClock) {
115
+ const presets = new Map(listCollections(ctx.db).map((record) => [record.name, presetOf(ctx, record)]));
116
+ const workflowFor = ({ collection, type }) => {
117
+ const preset = presets.get(collection);
118
+ if (!preset)
119
+ throw new OteaError('not_found', `Collection "${collection}" not found`);
120
+ return typeOf(preset, type).workflow;
121
+ };
122
+ const { turn, availableTo, parent, fields, ...given } = filter;
123
+ const stored = given.collection === undefined
124
+ ? given
125
+ : { ...given, collection: collectionNamed(ctx.db, given.collection) };
126
+ if (parent !== undefined)
127
+ requireItem(ctx.db, parent);
128
+ const relations = selectRelations(ctx.db);
129
+ const children = parent === undefined ? undefined : new Set(childIds(relations, parent));
130
+ const at = now();
131
+ const asking = askingItems(ctx.db);
132
+ const items = selectItems(ctx.db, stored)
133
+ .map((item) => withAsks(present(item, workflowFor(item), at), asking.get(item.id)))
134
+ .filter((item) => turn === undefined || item.turn === turn)
135
+ .filter(({ lease }) => availableTo === undefined || !lease || lease.holder === availableTo)
136
+ .filter(({ id }) => children === undefined || children.has(id))
137
+ .filter((item) => fields === undefined || holdsFields(item, fields));
138
+ if (relations.length === 0)
139
+ return items;
140
+ // A child may sit outside the filter, so the summaries read every item.
141
+ const closings = new Map(selectItems(ctx.db, {}).map((item) => [item.id, present(item, workflowFor(item), at)]));
142
+ return withRelations(items, relations, (id) => closings.get(id) ?? {});
143
+ }
144
+ // The matching item that has waited longest: the first to enter its current state, ties going to
145
+ // the first created. Field updates and leases do not reset the wait.
146
+ // `keep` leaves out the items it refuses (those next would never offer the agent waiting).
147
+ export function oldestWaiting(ctx, filter, now = systemClock, keep = () => true) {
148
+ const entered = selectStateEntries(ctx.db);
149
+ const since = (item) => entered.get(item.id) ?? item.createdAt;
150
+ return listItems(ctx, filter, now)
151
+ .filter(keep)
152
+ .reduce((oldest, item) => (oldest === undefined || since(item) < since(oldest) ? item : oldest), undefined);
153
+ }
154
+ export function getItem(ctx, id, now = systemClock) {
155
+ const item = requireItem(ctx.db, id);
156
+ const workflow = workflowOf(ctx, item);
157
+ const events = selectEvents(ctx.db, id);
158
+ return { ...withAsks(present(item, workflow, now()), openQuestion(events)), events };
159
+ }
160
+ export function showItem(ctx, id, performer, now = systemClock) {
161
+ const at = now();
162
+ const item = getItem(ctx, id, () => at);
163
+ const type = typeOfItem(ctx, item);
164
+ const children = childrenOf(ctx, item.id, at);
165
+ const { gates: stateGates, ...offered } = itemMoves(type, item.state, item.fields, performer);
166
+ const gates = withBranchGates(ctx, item, stateGates);
167
+ const moves = {
168
+ ...offered,
169
+ transitions: boardMoves(ctx, item, offered.transitions),
170
+ relayable: boardMoves(ctx, item, offered.relayable),
171
+ };
172
+ const board = boardBlockOf(ctx, item);
173
+ const archived = archivedBoardOf(ctx.db, item.id);
174
+ const archivedId = archived === undefined ? undefined : findBoardOfCollection(ctx.db, item.collection)?.id;
175
+ return {
176
+ ...item,
177
+ ...moves,
178
+ // An archived board's item is read-only: it offers no move to anyone.
179
+ ...(archived === undefined
180
+ ? {}
181
+ : { archived: { board: archived, id: archivedId ?? '' }, transitions: [], relayable: [] }),
182
+ // On a board, a file attached to no part stays outside the parts (the person's own).
183
+ evidence: presentEvidence(type.layout, selectEvidence(ctx.db, item.id), findBoardOfCollection(ctx.db, item.collection) !== undefined),
184
+ relations: relatedItems(ctx, item.id, at),
185
+ ...(children.length > 0 ? { children: childrenSummary(children) } : {}),
186
+ ...(gates === undefined ? {} : { gates }),
187
+ ...(board === undefined ? {} : { board }),
188
+ };
189
+ }
190
+ // The gates a board item's state allows, as its branch makes them true: an item that leaves its
191
+ // protected branch empty has no branch of its own to push, whatever its step allows (P5-R3-2).
192
+ function withBranchGates(ctx, item, gates) {
193
+ if (gates?.push !== true)
194
+ return gates;
195
+ const board = liveBoardOf(ctx, item.collection);
196
+ const branch = board ? guardedBranch(board.def) : undefined;
197
+ if (!branch || String(item.fields[branch.id] ?? '').trim() !== '')
198
+ return gates;
199
+ return { ...gates, push: false };
200
+ }
201
+ export function updateItem(ctx, input, now = systemClock) {
202
+ const { db } = ctx;
203
+ return transaction(db, () => {
204
+ const item = requireWritableItem(db, input.id);
205
+ const preset = presetOf(ctx, getCollection(db, item.collection));
206
+ const type = typeOf(preset, item.type);
207
+ const at = now();
208
+ assertMayWriteItem(db, item, input.actor, at);
209
+ if (turnOf(type.workflow, item.state) === 'none') {
210
+ throw new OteaError('item_closed', `${item.id} is ${item.state} (turn none) and can no longer be updated`, { kind: 'closed', item: item.id });
211
+ }
212
+ const fields = boardFieldInput(ctx, item.collection, input.fields ?? {});
213
+ assertBranchMayChange(ctx, item, fields, input.actor);
214
+ const changes = {
215
+ ...fields,
216
+ ...(input.title === undefined ? {} : { title: input.title }),
217
+ };
218
+ const revision = revise(type, item, changes);
219
+ if (Object.keys(revision.changes).length === 0)
220
+ return present(item, type.workflow, at);
221
+ const content = {
222
+ title: revision.title,
223
+ fields: revision.fields,
224
+ presetVersion: preset.version,
225
+ updatedAt: at,
226
+ };
227
+ updateItemContent(db, item.id, content);
228
+ appendEvent(db, {
229
+ itemId: item.id,
230
+ type: 'updated',
231
+ actor: input.actor,
232
+ at,
233
+ data: { changes: revision.changes },
234
+ });
235
+ return present({ ...item, ...content }, type.workflow, at);
236
+ });
237
+ }
238
+ // Lands an authorized move: the new state, its transitioned event and the release of the lease it
239
+ // carried. `trail` (who relayed it) is recorded on both. Off a board a lease lasts while the item
240
+ // stays on the agent turn (todo, then in_progress). On a board (`board`) a lease is for one step's
241
+ // doing or review: every move ends it, live or run out, so it never blocks the next step or reads
242
+ // as someone working there. An agent that goes on to the next step itself claims it again. A move
243
+ // that closes the item lifts the set-aside of what waited for it (liftWhenWaitsClose, P7-R3-1).
244
+ export function landMove(ctx, workflow, item, move, data, trail = {}) {
245
+ const { db } = ctx;
246
+ const { to, actor, at, board } = move;
247
+ const lease = board ? item.lease : move.lease;
248
+ updateItemState(db, item.id, to, at);
249
+ appendEvent(db, {
250
+ itemId: item.id,
251
+ type: 'transitioned',
252
+ actor,
253
+ at,
254
+ data: {
255
+ from: item.state,
256
+ to,
257
+ ...stateNames(workflow, { from: item.state, to }),
258
+ ...data,
259
+ ...trail,
260
+ },
261
+ });
262
+ const handoff = lease !== null && (board || turnOf(workflow, to) !== 'agent');
263
+ if (handoff) {
264
+ clearLease(db, item.id);
265
+ const released = { holder: lease.holder, cause: 'handoff', ...trail };
266
+ appendEvent(db, { itemId: item.id, type: 'released', actor, at, data: released });
267
+ }
268
+ if (turnOf(workflow, to) === 'none')
269
+ liftWhenWaitsClose(ctx, item.id, actor, at);
270
+ const moved = { ...item, state: to, updatedAt: at, lease: handoff ? null : item.lease };
271
+ return present(moved, workflow, at);
272
+ }
273
+ // A Pedido an agent drafts a board on closes as done when the person publishes the board, never
274
+ // by approving it while the board still waits as a draft (that closed the Pedido and left the
275
+ // board unpublished). Discarding it stays open to the person.
276
+ function assertDraftPublished(ctx, id, closes) {
277
+ if (closes !== 'done')
278
+ return;
279
+ const request = draftRequestOf(ctx, id);
280
+ if (!request || request.published)
281
+ return;
282
+ throw new OteaError('invalid_transition', `Not closed ${id}: the board ${request.name} it drafts is not published yet. The person publishes it in Studio, which closes this Pedido.`, { kind: 'board_unpublished', item: id, board: request.name });
283
+ }
284
+ export function moveItem(ctx, input, now = systemClock) {
285
+ const { db } = ctx;
286
+ return transaction(db, () => {
287
+ const item = requireWritableItem(db, input.id);
288
+ const type = typeOfItem(ctx, item);
289
+ const { workflow } = type;
290
+ const { actor, channel, reason } = input;
291
+ const to = boardState(ctx, item.collection, input.to);
292
+ const at = now();
293
+ const lease = activeLease(item.lease, at);
294
+ assertMayWriteItem(db, item, actor, at);
295
+ // On a board, the step engine says first, in the board's words, why a move is not this actor's.
296
+ const note = assertMoveHandsOff(ctx, item, to, actor, {
297
+ ...(reason === undefined ? {} : { reason }),
298
+ ...(input.note === undefined ? {} : { note: input.note }),
299
+ });
300
+ // A send-back that goes with the person's review comments needs no words of its own (P4-7).
301
+ const commented = !reason?.trim() && backWithComments(ctx, item, to);
302
+ authorizeMove(workflow, item.state, to, { actor, channel }, reason, commented);
303
+ assertDraftPublished(ctx, item.id, closesOf(workflow, to));
304
+ assertCanLeave(type, item.state, to, item.fields);
305
+ assertMayEnter(ctx, item, workflow, to, at);
306
+ const data = { ...(reason ? { reason } : {}), ...(note ? { note } : {}), channel };
307
+ const live = liveBoardOf(ctx, item.collection);
308
+ if (live)
309
+ assertPicked(live.def, item, { to, actor }, input.choice);
310
+ if (input.choice) {
311
+ if (!live)
312
+ throw new OteaError('invalid_transition', `Not chosen on ${item.id}: it is on no board`);
313
+ recordChoice(db, live.def, item, { to, actor, channel, at }, input.choice);
314
+ }
315
+ const board = live !== undefined;
316
+ return landMove(ctx, workflow, item, { to, actor, at, lease, board }, data);
317
+ });
318
+ }