@otea/cli 0.0.0-stage → 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 +252 -2
  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 +73 -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,287 @@
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import { copyFileSync, existsSync, linkSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync, } from 'node:fs';
3
+ import { basename, dirname, join } from 'node:path';
4
+ import { gateAt, isClosed, positionOf } from '../core/board/engine.js';
5
+ import { guardedBranch, stepById } from '../core/board/model.js';
6
+ import { OteaError } from '../core/errors.js';
7
+ import { evidenceTypeOf, MAX_EVIDENCE_BYTES, MAX_EVIDENCE_MB, } from '../core/evidence.js';
8
+ import { diffPartFor, diffPartText, evidenceModules, holderOf, moduleAccepts, placeEvidence, } from '../core/placement.js';
9
+ import { turnOf } from '../core/workflow.js';
10
+ import { transaction } from '../store/database.js';
11
+ import { appendEvent, findEvidence, insertEvidence, selectEvents, selectEvidence, } from '../store/queries.js';
12
+ import { typeOfItem } from './collections.js';
13
+ import { requireWritableItem, systemClock } from './items.js';
14
+ import { assertMayWriteItem } from './lease-take.js';
15
+ import { boardModule, liveBoardOf } from './next.js';
16
+ // Files are stored once under evidence/ in the project's data folder, named by their sha256, so
17
+ // attaching the same file again, to any item, stores nothing new.
18
+ export function evidenceDir(dataDir) {
19
+ return join(dataDir, 'evidence');
20
+ }
21
+ export function evidenceFile(dataDir, sha256) {
22
+ return join(evidenceDir(dataDir), sha256);
23
+ }
24
+ // A path an agent can open: the stored file under the name it was attached with, so a reader that
25
+ // goes by the extension opens a sketch as an image. Linked to the stored copy (copied where a link
26
+ // is refused), once, in files/<its number>/ beside evidence/. A file the person attached had only
27
+ // its name and hash, and the agent found no sketch (P5-R2-4). Undefined when the stored copy is gone.
28
+ export function evidenceReadPath(dataDir, evidence) {
29
+ const stored = evidenceFile(dataDir, evidence.sha256);
30
+ if (!existsSync(stored))
31
+ return undefined;
32
+ const name = basename(evidence.filename).replace(/[<>:"/\\|?*]/g, '_') || 'file';
33
+ const named = join(dataDir, 'files', String(evidence.id), name);
34
+ if (existsSync(named))
35
+ return named;
36
+ mkdirSync(dirname(named), { recursive: true });
37
+ try {
38
+ linkSync(stored, named);
39
+ }
40
+ catch {
41
+ copyFileSync(stored, named);
42
+ }
43
+ return named;
44
+ }
45
+ function readEvidence(path) {
46
+ const stats = statSync(path, { throwIfNoEntry: false });
47
+ if (!stats)
48
+ throw new OteaError('file_not_found', `File "${path}" not found`);
49
+ if (!stats.isFile())
50
+ throw new OteaError('file_not_found', `"${path}" is not a file`);
51
+ if (stats.size > MAX_EVIDENCE_BYTES) {
52
+ throw new OteaError('evidence_too_large', `${basename(path)} is over the ${MAX_EVIDENCE_MB} MB evidence limit`);
53
+ }
54
+ return readFileSync(path);
55
+ }
56
+ // Written aside and renamed into place, so a reader never sees a partial file.
57
+ function store(dataDir, sha256, bytes) {
58
+ const target = evidenceFile(dataDir, sha256);
59
+ if (existsSync(target))
60
+ return;
61
+ mkdirSync(evidenceDir(dataDir), { recursive: true });
62
+ const partial = `${target}.${randomUUID()}.partial`;
63
+ writeFileSync(partial, bytes);
64
+ renameSync(partial, target);
65
+ }
66
+ // Evidence obeys the rules of an update: another agent's lease and a closed item refuse it. It goes
67
+ // to a module of the item's layout that accepts it, in a role that module takes (see placeEvidence).
68
+ // Where a file the person attaches to a board item goes when they name no part (ONB3-4): the
69
+ // first part the board's creation form asks for that takes it, else nowhere, kept with the item
70
+ // outside the parts. The parts the steps hand are the agents' deliverables: a file of the person's
71
+ // never fills one, unless the person names it. undefined: the usual placement (an agent's file, a
72
+ // named part, an item that is not on a board).
73
+ function personsPlace(project, item, actor, request) {
74
+ if (actor.kind !== 'human' || request.module !== undefined)
75
+ return undefined;
76
+ const board = liveBoardOf(project, item.collection);
77
+ if (!board)
78
+ return undefined;
79
+ const asked = new Set(board.def.form.map(({ ref }) => ref));
80
+ const type = typeOfItem(project, item);
81
+ const form = evidenceModules(type.layout).find((entry) => asked.has(entry.id) && moduleAccepts(entry, request.filename));
82
+ if (form) {
83
+ return placeEvidence(type.layout, { id: item.id, type: type.name }, {
84
+ ...request,
85
+ module: form.id,
86
+ });
87
+ }
88
+ return { module: null, role: request.role ?? 'single' };
89
+ }
90
+ // The part that takes diffs, for a diff saved as a text file (core/placement.ts). Only the start of
91
+ // a large file is read: a diff says so in its first lines.
92
+ function diffPartOf(layout, file) {
93
+ return diffPartFor(layout, file.filename, file.bytes.subarray(0, 64 * 1024).toString('utf8'));
94
+ }
95
+ export function placeFile(project, item, file, actor, at) {
96
+ if (file.bytes.length > MAX_EVIDENCE_BYTES) {
97
+ throw new OteaError('evidence_too_large', `${file.filename} is over the ${MAX_EVIDENCE_MB} MB evidence limit`);
98
+ }
99
+ const type = typeOfItem(project, item);
100
+ assertMayWriteItem(project.db, item, actor, at);
101
+ if (turnOf(type.workflow, item.state) === 'none') {
102
+ throw new OteaError('item_closed', `${item.id} is ${item.state} (turn none) and can no longer take evidence`);
103
+ }
104
+ const request = {
105
+ filename: file.filename,
106
+ ...(file.role === undefined ? {} : { role: file.role }),
107
+ ...(file.module === undefined
108
+ ? {}
109
+ : { module: boardModule(project, item.collection, file.module) }),
110
+ };
111
+ const { filename, bytes, caption } = file;
112
+ let placement;
113
+ try {
114
+ placement =
115
+ personsPlace(project, item, actor, request) ??
116
+ placeEvidence(type.layout, { id: item.id, type: type.name }, request);
117
+ }
118
+ catch (error) {
119
+ // Asked which log part, a diff saved as text names the part that takes diffs too (P8-R3-5).
120
+ const diff = request.module === undefined && diffPartOf(type.layout, file);
121
+ if (!(error instanceof OteaError) || error.code !== 'module_required' || !diff)
122
+ throw error;
123
+ throw new OteaError(error.code, `${error.message}. ${diffPartText(item.id, filename, diff)}`, error.details);
124
+ }
125
+ return { filename, bytes, ...(caption === undefined ? {} : { caption }), ...placement };
126
+ }
127
+ // Evidence is append-only, like the event log: the file is stored once, then its entry and its
128
+ // evidence_added event are written, inside the caller's transaction.
129
+ export function recordEvidence(project, itemId, file, { actor, channel }, at) {
130
+ const { filename, bytes, module, role } = file;
131
+ const sha256 = createHash('sha256').update(bytes).digest('hex');
132
+ const { kind, contentType } = evidenceTypeOf(filename);
133
+ const caption = file.caption?.trim() || null;
134
+ store(project.dataDir, sha256, bytes);
135
+ const entry = {
136
+ itemId,
137
+ role,
138
+ module,
139
+ kind,
140
+ filename,
141
+ contentType,
142
+ size: bytes.length,
143
+ sha256,
144
+ caption,
145
+ createdAt: at,
146
+ actor,
147
+ channel,
148
+ };
149
+ const id = insertEvidence(project.db, entry);
150
+ const data = {
151
+ evidenceId: id,
152
+ role,
153
+ ...(module === null ? {} : { module }),
154
+ kind,
155
+ filename,
156
+ ...(caption ? { caption } : {}),
157
+ channel,
158
+ };
159
+ appendEvent(project.db, { itemId, type: 'evidence_added', actor, at, data });
160
+ return { id, ...entry };
161
+ }
162
+ // The evidence ids attached since the item last moved (its current round).
163
+ function addedSinceMoved(project, itemId) {
164
+ const events = selectEvents(project.db, itemId);
165
+ const moved = events.findLast(({ type }) => type === 'transitioned')?.id ?? 0;
166
+ return new Set(events.flatMap(({ id, type, data }) => type === 'evidence_added' && id > moved ? [Number(data.evidenceId)] : []));
167
+ }
168
+ // The entry the item already has for the same bytes in the same module and role, with the same
169
+ // caption, attached since it last moved: attaching it again adds nothing. Once the item moves (a
170
+ // new round), the same file is new again.
171
+ function sameSinceMoved(project, itemId, file) {
172
+ const sha256 = createHash('sha256').update(file.bytes).digest('hex');
173
+ const since = addedSinceMoved(project, itemId);
174
+ return selectEvidence(project.db, itemId).findLast((entry) => since.has(entry.id) &&
175
+ entry.sha256 === sha256 &&
176
+ entry.module === file.module &&
177
+ entry.role === file.role &&
178
+ entry.caption === (file.caption?.trim() || null));
179
+ }
180
+ // While a step that pushes the board's protected branch is reviewed, the branch is frozen: an
181
+ // agent attaches nothing, so the reviewer approves only what was handed off, never work the branch
182
+ // never got. The person may still attach.
183
+ function refuseWhileFrozen(project, item, actor) {
184
+ if (actor.kind !== 'agent')
185
+ return;
186
+ const board = liveBoardOf(project, item.collection);
187
+ if (!board)
188
+ return;
189
+ const position = positionOf(item.state);
190
+ if (isClosed(position) || position.phase === 'doing')
191
+ return;
192
+ if (gateAt(board.def, position, 'push').why !== 'review')
193
+ return;
194
+ const step = stepById(board.def, position.step)?.name ?? position.step;
195
+ // An item that names no branch has none to freeze or push (P4-R2-4): only the review holds.
196
+ const branch = guardedBranch(board.def);
197
+ const named = branch && String(item.fields[branch.id] ?? '').trim() !== '';
198
+ throw new OteaError('invalid_transition', named
199
+ ? `Not attached to ${item.id}: its branch is frozen while ${step} is reviewed, so the reviewer reads only what was handed off. Push and attach once it is sent back.`
200
+ : `Not attached to ${item.id}: ${step} is being reviewed, so the reviewer reads only what was handed off. Attach it once it is sent back.`, { kind: 'frozen_in_review', item: item.id, step });
201
+ }
202
+ // Attaches the file at a path. A refusal stores nothing; the same file again adds nothing.
203
+ export function attachEvidence(project, input, now = systemClock) {
204
+ const file = {
205
+ filename: basename(input.path),
206
+ bytes: readEvidence(input.path),
207
+ ...(input.role === undefined ? {} : { role: input.role }),
208
+ ...(input.module === undefined ? {} : { module: input.module }),
209
+ ...(input.caption === undefined ? {} : { caption: input.caption }),
210
+ };
211
+ return transaction(project.db, () => {
212
+ const item = requireWritableItem(project.db, input.id);
213
+ refuseWhileFrozen(project, item, input.actor);
214
+ const at = now();
215
+ const placed = placeFile(project, item, file, input.actor, at);
216
+ const same = sameSinceMoved(project, item.id, placed);
217
+ const attached = same
218
+ ? { ...same, duplicate: true }
219
+ : recordEvidence(project, item.id, placed, input, at);
220
+ if (input.module !== undefined)
221
+ return attached;
222
+ const layout = typeOfItem(project, item).layout;
223
+ const diff = diffPartOf(layout, file);
224
+ if (!diff || diff.id === placed.module)
225
+ return attached;
226
+ const went = evidenceModules(layout).find(({ id }) => id === placed.module);
227
+ const name = diff.label ?? diff.id;
228
+ const note = `${diffPartText(item.id, file.filename, diff, went && (went.label ?? went.id))}, then otea detach ${item.id} ${attached.id}`;
229
+ return { ...attached, diffPart: name, diffNote: note };
230
+ });
231
+ }
232
+ // Takes back a file attached by mistake (AGENTS3-4): only the one who attached it, while the item
233
+ // has not moved since, and while no note of the person or proof of a point rests on it. Evidence
234
+ // stays append-only: an evidence_detached event takes it off the item's list, and the history
235
+ // keeps both.
236
+ export function detachEvidence(project, input, now = systemClock) {
237
+ return transaction(project.db, () => {
238
+ const item = requireWritableItem(project.db, input.id);
239
+ const at = now();
240
+ assertMayWriteItem(project.db, item, input.actor, at);
241
+ const entry = selectEvidence(project.db, item.id).find(({ id }) => id === input.evidence);
242
+ if (!entry) {
243
+ throw new OteaError('not_found', `${item.id} has no attached file #${input.evidence}`);
244
+ }
245
+ const said = `#${entry.id} ${entry.filename}`;
246
+ if (entry.actor.kind !== input.actor.kind || entry.actor.name !== input.actor.name) {
247
+ throw new OteaError('forbidden', `${said} was attached by ${entry.actor.name}: only who attached a file may detach it`);
248
+ }
249
+ if (!addedSinceMoved(project, item.id).has(entry.id)) {
250
+ throw new OteaError('forbidden', `${said} went with an earlier move of ${item.id}, so it stays in the record: attach the right file instead`);
251
+ }
252
+ const resting = selectEvents(project.db, item.id).find(({ type, data }) => (type === 'point_proved' && Number(data.evidence) === entry.id) ||
253
+ (type === 'note_left' &&
254
+ Number(data.anchor?.evidence) === entry.id));
255
+ if (resting) {
256
+ const what = resting.type === 'note_left' ? 'a note of the person' : 'the proof of a point';
257
+ throw new OteaError('in_use', `${said} cannot be detached: ${what} rests on it`);
258
+ }
259
+ appendEvent(project.db, {
260
+ itemId: item.id,
261
+ type: 'evidence_detached',
262
+ actor: input.actor,
263
+ at,
264
+ data: {
265
+ evidenceId: entry.id,
266
+ filename: entry.filename,
267
+ ...(entry.module === null ? {} : { module: entry.module }),
268
+ channel: input.channel,
269
+ },
270
+ });
271
+ return entry;
272
+ });
273
+ }
274
+ // Each entry with the module that draws it in this layout (see holderOf), for readers.
275
+ export function presentEvidence(layout, evidence, keepLoose = false) {
276
+ return evidence.map((entry) => ({ ...entry, module: holderOf(layout, entry, keepLoose) }));
277
+ }
278
+ const EVIDENCE_ID = /^[1-9][0-9]*$/;
279
+ // The entry and where its file is stored; not_found when either is missing.
280
+ export function evidenceToServe(project, id) {
281
+ const evidence = EVIDENCE_ID.test(id) ? findEvidence(project.db, Number(id)) : undefined;
282
+ const path = evidence && evidenceFile(project.dataDir, evidence.sha256);
283
+ if (!evidence || !path || !existsSync(path)) {
284
+ throw new OteaError('not_found', `Evidence "${id}" not found`);
285
+ }
286
+ return { evidence, path };
287
+ }