@operad-io/engine 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 (102) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +11 -2
  3. package/config.schema.json +188 -0
  4. package/keys.schema.json +12 -0
  5. package/package.json +22 -4
  6. package/src/config/config.ts +627 -0
  7. package/src/config/index.ts +1 -0
  8. package/src/flow/define-flow.ts +57 -0
  9. package/src/flow/index.ts +5 -0
  10. package/src/flow/load.ts +41 -0
  11. package/src/flow/types.ts +107 -0
  12. package/src/flow/validate.ts +296 -0
  13. package/src/http/address.ts +142 -0
  14. package/src/http/index.ts +25 -0
  15. package/src/http/link.ts +20 -0
  16. package/src/http/server.ts +920 -0
  17. package/src/http/token.ts +90 -0
  18. package/src/index.ts +18 -0
  19. package/src/kernel/decide.ts +689 -0
  20. package/src/kernel/index.ts +3 -0
  21. package/src/kernel/state.ts +275 -0
  22. package/src/kernel/types.ts +366 -0
  23. package/src/log/errors.ts +77 -0
  24. package/src/log/facts.ts +50 -0
  25. package/src/log/index.ts +6 -0
  26. package/src/log/json-value.ts +67 -0
  27. package/src/log/open-log.ts +17 -0
  28. package/src/log/schema.ts +5 -0
  29. package/src/log/secret.ts +30 -0
  30. package/src/log/sqlite.ts +1011 -0
  31. package/src/log/types.ts +230 -0
  32. package/src/loop/code-watch.ts +486 -0
  33. package/src/loop/index.ts +3 -0
  34. package/src/loop/older-code.ts +58 -0
  35. package/src/loop/serve.ts +483 -0
  36. package/src/markdown.ts +451 -0
  37. package/src/notify/index.ts +10 -0
  38. package/src/notify/notify.ts +256 -0
  39. package/src/platform/file-lock.ts +385 -0
  40. package/src/platform/index.ts +13 -0
  41. package/src/platform/load.ts +18 -0
  42. package/src/platform/process-group.ts +675 -0
  43. package/src/platform/process-watch.ts +152 -0
  44. package/src/platform/sqlite-open.ts +104 -0
  45. package/src/platform/step-reap.ts +668 -0
  46. package/src/platform/watch.ts +158 -0
  47. package/src/platform/worker-reports.ts +34 -0
  48. package/src/plugin/action-schema.ts +550 -0
  49. package/src/plugin/declared-flows.ts +74 -0
  50. package/src/plugin/define-plugin.ts +12 -0
  51. package/src/plugin/errors.ts +73 -0
  52. package/src/plugin/filters.ts +46 -0
  53. package/src/plugin/harness.ts +50 -0
  54. package/src/plugin/home.ts +13 -0
  55. package/src/plugin/index.ts +65 -0
  56. package/src/plugin/install.ts +268 -0
  57. package/src/plugin/keys.ts +63 -0
  58. package/src/plugin/load.ts +256 -0
  59. package/src/plugin/logger.ts +30 -0
  60. package/src/plugin/object-facts.ts +132 -0
  61. package/src/plugin/open-store.ts +32 -0
  62. package/src/plugin/paging.ts +133 -0
  63. package/src/plugin/registry.ts +1786 -0
  64. package/src/plugin/secrets.ts +141 -0
  65. package/src/plugin/semver.ts +110 -0
  66. package/src/plugin/settings.ts +64 -0
  67. package/src/plugin/sqlite-store.ts +756 -0
  68. package/src/plugin/store.ts +318 -0
  69. package/src/plugin/types.ts +1243 -0
  70. package/src/plugin/usage.ts +157 -0
  71. package/src/plugin/validate.ts +1028 -0
  72. package/src/runner/answer.ts +156 -0
  73. package/src/runner/ask.ts +483 -0
  74. package/src/runner/cancel.ts +51 -0
  75. package/src/runner/errors.ts +20 -0
  76. package/src/runner/grants.ts +92 -0
  77. package/src/runner/index.ts +33 -0
  78. package/src/runner/limits.ts +403 -0
  79. package/src/runner/lock.ts +140 -0
  80. package/src/runner/runner.ts +1175 -0
  81. package/src/runner/service.ts +184 -0
  82. package/src/runner/step-worker.ts +303 -0
  83. package/src/testing/clock.ts +67 -0
  84. package/src/testing/index.ts +90 -0
  85. package/src/testing/types.ts +116 -0
  86. package/src/testing/world.ts +369 -0
  87. package/src/trigger/cron.ts +193 -0
  88. package/src/trigger/index.ts +32 -0
  89. package/src/trigger/kernel.ts +1221 -0
  90. package/src/trigger/rules.ts +300 -0
  91. package/src/trigger/store.ts +233 -0
  92. package/src/trigger/types.ts +156 -0
  93. package/src/util.ts +50 -0
  94. package/src/views/history.ts +634 -0
  95. package/src/views/index.ts +7 -0
  96. package/src/views/pending.ts +209 -0
  97. package/src/views/presentation.ts +2609 -0
  98. package/src/views/running.ts +255 -0
  99. package/src/views/settings.ts +452 -0
  100. package/src/views/types.ts +72 -0
  101. package/src/views/uploads.ts +228 -0
  102. package/triggers.schema.json +48 -0
@@ -0,0 +1,2609 @@
1
+ /**
2
+ * The presentation kernel: the one API every client calls. It knows no plugin
3
+ * name; it asks the loaded plugins for rows, sections and actions and adds the
4
+ * flags and the history section the kernel itself owns.
5
+ */
6
+
7
+ import { readFileSync } from "node:fs";
8
+ import { objectLink } from "../http/link.ts";
9
+ import type { LogBackend } from "../log/types.ts";
10
+ import {
11
+ followsChanges,
12
+ type FollowOptions,
13
+ } from "../platform/index.ts";
14
+ import { runTimes } from "./running.ts";
15
+ import type { PluginRegistry, ActionInfo } from "../plugin/registry.ts";
16
+ import { rankOf, sortByRank, splitActionName } from "../plugin/registry.ts";
17
+ import { messageOf } from "../plugin/errors.ts";
18
+ import { createPluginLogger } from "../plugin/logger.ts";
19
+ import { FileSecretStore } from "../plugin/secrets.ts";
20
+ import {
21
+ assertWhere,
22
+ CursorError,
23
+ decodeCursor,
24
+ encodeCursor,
25
+ MAX_PAGE_LIMIT,
26
+ pageLimit,
27
+ whereFingerprint,
28
+ WhereError,
29
+ } from "../plugin/paging.ts";
30
+ import { ALL_FILTER, filterShows, typeFilters, type TypeFilter } from "../plugin/filters.ts";
31
+ import { ActionArgsError, fileProperties, noteProperty, validateActionArgs } from "../plugin/action-schema.ts";
32
+ import { attachmentDir, UploadMissingError, Uploads } from "./uploads.ts";
33
+ import type {
34
+ ActionTypeDefinition,
35
+ Actor,
36
+ FactWriter,
37
+ FactsOptions,
38
+ FactsPage,
39
+ ListOptions,
40
+ ObjectRef,
41
+ ObjectViews,
42
+ PluginFact,
43
+ PluginStore,
44
+ StoredObject,
45
+ RowMark,
46
+ ViewContext,
47
+ } from "../plugin/types.ts";
48
+ import { ROW_BADGE_MAX, ROW_MARKS } from "../plugin/types.ts";
49
+ import {
50
+ localMinute,
51
+ runHistoryLines,
52
+ type HistoryFact,
53
+ } from "./history.ts";
54
+ import { readState } from "../runner/service.ts";
55
+ import { recordAnswer } from "../runner/answer.ts";
56
+ import { StateError } from "../runner/errors.ts";
57
+ import { listPending, type CandidateSource, type PendingItem } from "./pending.ts";
58
+ import {
59
+ listSettings,
60
+ setSetting,
61
+ SettingsError,
62
+ type SettingInfo,
63
+ type SettingsOptions,
64
+ } from "./settings.ts";
65
+ import { isRecord } from "../util.ts";
66
+ import { configPath } from "../config/config.ts";
67
+ import { prepareSettings } from "../plugin/settings.ts";
68
+ import type { JsonValue } from "../log/types.ts";
69
+
70
+ /** The final section the kernel adds to every object. */
71
+ export const HISTORY_SECTION = "history";
72
+
73
+ /** The default time a section's `load` may take. */
74
+ export const DEFAULT_LOAD_TIMEOUT_MS = 10_000;
75
+
76
+ /** The default number of bytes a section may return. */
77
+ export const DEFAULT_SECTION_CAP_BYTES = 256 * 1024;
78
+
79
+ /** The default time `row` may take before it is an error row. */
80
+ export const DEFAULT_ROW_TIMEOUT_MS = 50;
81
+
82
+ /** The default number of ids an event consumer remembers. */
83
+ export const DEFAULT_MAX_EVENT_IDS = 1024;
84
+
85
+ /**
86
+ * How often the kernel announces one object whose live section grows. A
87
+ * section that grows faster than this is announced at most once per window;
88
+ * the last growth in the window is announced when the window ends.
89
+ */
90
+ export const GROWTH_EVENT_INTERVAL_MS = 250;
91
+
92
+ /** A row as a client sees it: the plugin's row plus the kernel's two flags. */
93
+ export interface ViewRow {
94
+ readonly id: string;
95
+ readonly title: string;
96
+ readonly state: string;
97
+ readonly note?: string | undefined;
98
+ /** Why the object waits, whole and separate from `note`; absent when it does not. */
99
+ readonly wait?: string | undefined;
100
+ /** The namespace the id lives in; set only when the list shows it. */
101
+ readonly scope?: string | undefined;
102
+ /** The row's state is final for its type; absent when the plugin did not say. */
103
+ readonly final?: boolean | undefined;
104
+ /** The plugin's semantic mark; the precedence against the flags is the client's. */
105
+ readonly mark?: RowMark | undefined;
106
+ /** A short text shown after the state. */
107
+ readonly badge?: string | undefined;
108
+ /** The object one level up, exactly as the plugin's row names it. */
109
+ readonly parent?: string | undefined;
110
+ /** The siblings this object waits for, exactly as the plugin's row names them. */
111
+ readonly after?: readonly string[] | undefined;
112
+ /** A person wait is open on this object. */
113
+ readonly waiting: boolean;
114
+ /** The object's run is working. */
115
+ readonly running: boolean;
116
+ /** Set when the plugin's `row` failed; the row is then an error row. */
117
+ readonly error?: string | undefined;
118
+ }
119
+
120
+ /** One entry in a detail page's section directory. */
121
+ export interface ViewSectionInfo {
122
+ readonly id: string;
123
+ readonly title: string;
124
+ readonly live?: boolean | undefined;
125
+ }
126
+
127
+ /** An action a client may offer for an object right now. */
128
+ export interface ViewAction extends ActionInfo {
129
+ /** The key bound to this action, when one is. */
130
+ readonly key?: string | undefined;
131
+ }
132
+
133
+ /** What `get` returns: a row, the section directory and the actions. */
134
+ export interface ViewObject {
135
+ readonly id: string;
136
+ readonly type: string;
137
+ /** The link that opens this object in the app. */
138
+ readonly link: string;
139
+ readonly row: ViewRow;
140
+ readonly sections: readonly ViewSectionInfo[];
141
+ readonly actions: readonly ViewAction[];
142
+ /** Set when the object's plugin is no longer loaded. */
143
+ readonly unavailable?: string | undefined;
144
+ /** The ids of the objects of this type whose row has this one in `after`. */
145
+ readonly dependents?: readonly string[] | undefined;
146
+ }
147
+
148
+ /** What one section read returns. */
149
+ export interface ViewSectionContent {
150
+ readonly markdown: string;
151
+ readonly next?: string | undefined;
152
+ /** The section's table of contents, passed through from the plugin. */
153
+ readonly pages?: readonly ViewSectionPage[] | undefined;
154
+ /**
155
+ * An opaque position the finished content goes to. Pass it back as `after`
156
+ * to read only what follows it. The plugin owns its meaning.
157
+ */
158
+ readonly mark?: string | undefined;
159
+ /**
160
+ * The part that is still changing, always its whole current text. The size
161
+ * cap never cuts it; it shortens the finished page instead.
162
+ */
163
+ readonly tail?: string | undefined;
164
+ /**
165
+ * Present on a read that asked with `after`: true when `markdown` holds only
166
+ * what follows the mark, false when the plugin answered with a whole page
167
+ * and the client must replace its content instead of appending.
168
+ */
169
+ readonly delta?: boolean | undefined;
170
+ }
171
+
172
+ /** One entry of a section's table of contents. */
173
+ export interface ViewSectionPage {
174
+ readonly label: string;
175
+ readonly cursor?: string | undefined;
176
+ }
177
+
178
+ /** One change a client may react to. */
179
+ export interface ViewEvent {
180
+ readonly id: string;
181
+ }
182
+
183
+ /** Why a presentation call refused. */
184
+ export type ViewErrorKind =
185
+ | "not-found"
186
+ | "ambiguous"
187
+ | "no-views"
188
+ | "section"
189
+ | "timeout"
190
+ | "action"
191
+ | "not-available"
192
+ | "unavailable"
193
+ | "note"
194
+ | "confirm"
195
+ | "args"
196
+ | "where"
197
+ | "filter"
198
+ | "cursor";
199
+
200
+ function settingsViewError(error: unknown): unknown {
201
+ return error instanceof SettingsError
202
+ ? new ViewError(error.kind, error.message, { cause: error })
203
+ : error;
204
+ }
205
+
206
+ /** A presentation call cannot do what was asked. */
207
+ export class ViewError extends Error {
208
+ readonly kind: ViewErrorKind;
209
+
210
+ constructor(kind: ViewErrorKind, message: string, options?: ErrorOptions) {
211
+ super(message, options);
212
+ this.name = "ViewError";
213
+ this.kind = kind;
214
+ }
215
+ }
216
+
217
+ export interface ViewsOptions extends FollowOptions {
218
+ readonly registry: PluginRegistry;
219
+ readonly store?: PluginStore | undefined;
220
+ readonly log?: LogBackend | undefined;
221
+ readonly cwd?: string | undefined;
222
+ /** A namespace named explicitly, handed to each type's `resolve`. */
223
+ readonly scope?: string | undefined;
224
+ readonly clock?: (() => number) | undefined;
225
+ readonly rowTimeoutMs?: number | undefined;
226
+ readonly loadTimeoutMs?: number | undefined;
227
+ readonly sectionCapBytes?: number | undefined;
228
+ readonly maxEventIds?: number | undefined;
229
+ readonly onLog?: ((message: string) => void) | undefined;
230
+ /** The operad home whose `config.json` holds the global settings. */
231
+ readonly home?: string | undefined;
232
+ }
233
+
234
+ export interface ActOptions {
235
+ /** The person's values, already named as the action's schema names them. */
236
+ readonly args?: Readonly<Record<string, unknown>> | undefined;
237
+ /** `args` for the note property, kept as `--note` convenience. */
238
+ readonly note?: string | undefined;
239
+ readonly yes?: boolean | undefined;
240
+ /** Where the person asked: the command line or the HTTP interface. */
241
+ readonly surface?: "cli" | "http" | undefined;
242
+ /** Who asked; the CLI passes `{ via: "cli", id: <user> }`. */
243
+ readonly actor: Actor;
244
+ }
245
+
246
+ /**
247
+ * The in-process client API: the calls HTTP and the TUI make. A source plugin's
248
+ * `start` receives the same `Views` object that serves them, narrowed to these.
249
+ * `act` and `answer` both take an actor naming the person who acted.
250
+ */
251
+ export type ClientApi = Pick<
252
+ Views,
253
+ "list" | "get" | "section" | "events" | "act" | "pending" | "answer"
254
+ >;
255
+
256
+ /** What answers one open question of a pending item. */
257
+ export interface AnswerViewOptions {
258
+ readonly runId: string;
259
+ /** The wait id the pending item named. */
260
+ readonly waitId: string;
261
+ readonly choice: string;
262
+ readonly note?: string | undefined;
263
+ /** Confirms an action-backed choice whose action asks to confirm. */
264
+ readonly confirmed?: boolean | undefined;
265
+ /** Where the person asked: the command line or the HTTP interface. */
266
+ readonly surface?: "cli" | "http" | undefined;
267
+ /** Who answered. */
268
+ readonly actor: Actor;
269
+ }
270
+
271
+ /** How many hidden rows would draw each mark role. */
272
+ export interface ViewHiddenCounts {
273
+ readonly done: number;
274
+ readonly cancelled: number;
275
+ readonly other: number;
276
+ }
277
+
278
+ /** One page of rows and where to continue. */
279
+ export interface ViewListPage {
280
+ readonly rows: readonly ViewRow[];
281
+ readonly next?: string | undefined;
282
+ /** How many rows of the type the filter left out; absent without a filter or on `all`. */
283
+ readonly hidden?: number | undefined;
284
+ /** The hidden rows by the mark role they would draw; present with `hidden`. */
285
+ readonly hiddenCounts?: ViewHiddenCounts | undefined;
286
+ }
287
+
288
+ /** The mark role a hidden row adds to: done, cancelled or other. */
289
+ function hiddenRole(row: ViewRow): keyof ViewHiddenCounts {
290
+ if (row.mark === "cancelled" || /(^|\.)cancelled$/i.test(row.state)) {
291
+ return "cancelled";
292
+ }
293
+ if (row.mark === "done" || (row.mark === undefined && /^(done|merged)$/i.test(row.state))) {
294
+ return "done";
295
+ }
296
+ return "other";
297
+ }
298
+
299
+ /** What a hierarchy list adds to the flat list's options. */
300
+ export interface TreeListOptions extends ListOptions {
301
+ /** Which filter to apply; each type's default filter when absent. */
302
+ readonly filter?: string | undefined;
303
+ /** Only rows with no parent. */
304
+ readonly root?: boolean | undefined;
305
+ /** Only rows whose parent is this object id. */
306
+ readonly parent?: string | undefined;
307
+ }
308
+
309
+ /** An action that ran. */
310
+ export interface ViewActionRun {
311
+ readonly plugin: string;
312
+ readonly action: string;
313
+ readonly name: string;
314
+ readonly value: unknown;
315
+ /** The object the action created, as `type:id`; only one that exists. */
316
+ readonly opens?: string | undefined;
317
+ /** The result was already true, so nothing ran; `value` says so. */
318
+ readonly settled?: true | undefined;
319
+ }
320
+
321
+ export interface SectionOptions {
322
+ /** Return the whole section, without the size cap. */
323
+ readonly full?: boolean | undefined;
324
+ /** Return only the finished content after this mark from an earlier read. */
325
+ readonly after?: string | undefined;
326
+ }
327
+
328
+ function isThenable(value: unknown): boolean {
329
+ return (
330
+ typeof value === "object" &&
331
+ value !== null &&
332
+ typeof (value as { then?: unknown }).then === "function"
333
+ );
334
+ }
335
+
336
+ function pagesOf(value: unknown): readonly ViewSectionPage[] | undefined {
337
+ if (!Array.isArray(value)) return undefined;
338
+ const pages: ViewSectionPage[] = [];
339
+ for (const entry of value as unknown[]) {
340
+ if (!isRecord(entry)) continue;
341
+ const label = textOf(entry.label);
342
+ if (label === undefined) continue;
343
+ const cursor = textOf(entry.cursor);
344
+ pages.push(cursor === undefined ? { label } : { label, cursor });
345
+ }
346
+ return pages;
347
+ }
348
+
349
+ function textOf(value: unknown): string | undefined {
350
+ return typeof value === "string" ? value : undefined;
351
+ }
352
+
353
+ function objectKey(type: string, id: string): string {
354
+ return `${type}:${id}`;
355
+ }
356
+
357
+ function splitId(id: string): { readonly type: string; readonly id: string } | undefined {
358
+ const at = id.indexOf(":");
359
+ if (at <= 0 || at === id.length - 1) return undefined;
360
+ return { type: id.slice(0, at), id: id.slice(at + 1) };
361
+ }
362
+
363
+ function capBytes(markdown: string, limit: number): string {
364
+ const bytes = Buffer.from(markdown, "utf8");
365
+ if (bytes.length <= limit) return markdown;
366
+ let end = limit;
367
+ // A UTF-8 continuation byte at `end` means the character that started before
368
+ // it does not fit; back off to the boundary so decoding adds no U+FFFD and
369
+ // the result never grows past the limit.
370
+ while (end > 0 && ((bytes[end] ?? 0) & 0xc0) === 0x80) {
371
+ end -= 1;
372
+ }
373
+ return bytes.subarray(0, end).toString("utf8");
374
+ }
375
+
376
+ function truncationNote(id: string, sectionId: string): string {
377
+ return `\n\n[Truncated. See all of it with \`operad show ${id} --section ${sectionId} --full\`.]\n`;
378
+ }
379
+
380
+ /** The envelope a section mark carries, so a mark is used only where it was made. */
381
+ const SECTION_MARK_KIND = "section-mark";
382
+
383
+ function encodeSectionMark(
384
+ type: string,
385
+ id: string,
386
+ section: string,
387
+ mark: string,
388
+ ): string {
389
+ return encodeCursor({ kind: SECTION_MARK_KIND, type, id, section, mark });
390
+ }
391
+
392
+ /**
393
+ * The plugin's own mark inside an opaque one this section gave, or a refusal a
394
+ * person can read when the mark names another section or object.
395
+ */
396
+ function decodeSectionMark(
397
+ value: string,
398
+ type: string,
399
+ id: string,
400
+ section: string,
401
+ ): string {
402
+ const label = `section "${section}" of "${id}"`;
403
+ let decoded: Record<string, unknown>;
404
+ try {
405
+ decoded = decodeCursor(value, label);
406
+ } catch {
407
+ throw new ViewError(
408
+ "cursor",
409
+ `${label}: "after" is not a mark this section gave; read the section once without "after" first`,
410
+ );
411
+ }
412
+ if (decoded.kind !== SECTION_MARK_KIND) {
413
+ throw new ViewError(
414
+ "cursor",
415
+ `${label}: "after" is not a mark this section gave; read the section once without "after" first`,
416
+ );
417
+ }
418
+ if (
419
+ decoded.type !== type ||
420
+ decoded.id !== id ||
421
+ decoded.section !== section
422
+ ) {
423
+ const madeFor =
424
+ typeof decoded.section === "string" &&
425
+ typeof decoded.type === "string" &&
426
+ typeof decoded.id === "string"
427
+ ? `the mark was made for section "${decoded.section}" of "${decoded.type}:${decoded.id}"`
428
+ : "the mark was made for another section or object";
429
+ throw new ViewError(
430
+ "cursor",
431
+ `${label}: ${madeFor}; read this section without "after" first`,
432
+ );
433
+ }
434
+ const mark = decoded.mark;
435
+ if (typeof mark !== "string") {
436
+ throw new ViewError(
437
+ "cursor",
438
+ `${label}: "after" is not a mark this section gave; read the section once without "after" first`,
439
+ );
440
+ }
441
+ return mark;
442
+ }
443
+
444
+ interface ResolvedObject {
445
+ readonly type: string;
446
+ readonly id: string;
447
+ readonly object: StoredObject | undefined;
448
+ }
449
+
450
+ interface RunFlags {
451
+ readonly waiting: boolean;
452
+ readonly running: boolean;
453
+ }
454
+
455
+ /** A bounded, coalescing stream of ids. */
456
+ class EventStream implements AsyncIterable<ViewEvent> {
457
+ private readonly pending = new Set<string>();
458
+ private readonly max: number;
459
+ private readonly listeners: Set<(id: string) => void>;
460
+ private readonly flush: () => void;
461
+ private closed = false;
462
+ private resume: (() => void) | undefined;
463
+
464
+ constructor(
465
+ max: number,
466
+ listeners: Set<(id: string) => void>,
467
+ flush: () => void,
468
+ ) {
469
+ this.max = Math.max(1, max);
470
+ this.listeners = listeners;
471
+ this.flush = flush;
472
+ }
473
+
474
+ readonly listener = (id: string): void => {
475
+ if (this.closed) return;
476
+ if (this.pending.size >= this.max && !this.pending.has(id)) {
477
+ const oldest = this.pending.values().next().value;
478
+ if (oldest !== undefined) this.pending.delete(oldest);
479
+ }
480
+ this.pending.delete(id);
481
+ this.pending.add(id);
482
+ this.wake();
483
+ };
484
+
485
+ [Symbol.asyncIterator](): AsyncIterator<ViewEvent> {
486
+ this.listeners.add(this.listener);
487
+ return {
488
+ next: () => this.next(),
489
+ return: async () => this.stop(),
490
+ throw: async () => this.stop(),
491
+ };
492
+ }
493
+
494
+ private async next(): Promise<IteratorResult<ViewEvent>> {
495
+ // A growth held back for the rate window becomes due with the clock, not
496
+ // only when another change arrives.
497
+ this.flush();
498
+ while (!this.closed && this.pending.size === 0) {
499
+ await new Promise<void>((resolve) => {
500
+ this.resume = resolve;
501
+ });
502
+ }
503
+ if (this.closed) return { done: true, value: undefined };
504
+ const id = this.pending.values().next().value;
505
+ if (id === undefined) return { done: false, value: { id: "" } };
506
+ this.pending.delete(id);
507
+ return { done: false, value: { id } };
508
+ }
509
+
510
+ private stop(): IteratorResult<ViewEvent> {
511
+ this.closed = true;
512
+ this.listeners.delete(this.listener);
513
+ this.wake();
514
+ return { done: true, value: undefined };
515
+ }
516
+
517
+ private wake(): void {
518
+ const resume = this.resume;
519
+ this.resume = undefined;
520
+ resume?.();
521
+ }
522
+ }
523
+
524
+ /** The fact an action leaves on its object to say who asked. */
525
+ const ACTION_FACT = "action_invoked";
526
+
527
+ /** An object named for a short list: its type, id, state and title. */
528
+ export interface RecentObject {
529
+ readonly type: string;
530
+ readonly id: string;
531
+ readonly state: string;
532
+ readonly title: string;
533
+ }
534
+
535
+ function editDistance(left: string, right: string): number {
536
+ let previous = Array.from({ length: right.length + 1 }, (_, index) => index);
537
+ for (let row = 1; row <= left.length; row += 1) {
538
+ const current = [row];
539
+ for (let column = 1; column <= right.length; column += 1) {
540
+ const cost = left[row - 1] === right[column - 1] ? 0 : 1;
541
+ current[column] = Math.min(
542
+ (previous[column] ?? 0) + 1,
543
+ (current[column - 1] ?? 0) + 1,
544
+ (previous[column - 1] ?? 0) + cost,
545
+ );
546
+ }
547
+ previous = current;
548
+ }
549
+ return previous[right.length] ?? 0;
550
+ }
551
+
552
+ /** One object fact in words, with the time it happened. */
553
+ function describeFact(fact: PluginFact): string {
554
+ const time = new Date(fact.at).toISOString();
555
+ if (fact.type === ACTION_FACT) {
556
+ const data = fact.data;
557
+ const action =
558
+ typeof data.action === "string" ? data.action.replace("/", ":") : "an action";
559
+ const actor = isRecord(data.actor) ? data.actor : {};
560
+ const who: string[] = [];
561
+ if (typeof actor.via === "string") who.push(`via ${actor.via}`);
562
+ if (typeof actor.id === "string") who.push(`as ${actor.id}`);
563
+ return `${time} ${action}${who.length === 0 ? "" : ` (${who.join(", ")})`}`;
564
+ }
565
+ return `${time} changed by ${fact.cause}`;
566
+ }
567
+
568
+ /** The in-process presentation API. */
569
+ export class Views {
570
+ private readonly registry: PluginRegistry;
571
+ private readonly store: PluginStore;
572
+ private readonly log: LogBackend | undefined;
573
+ private readonly cwd: string;
574
+ private readonly scope: string | undefined;
575
+ private readonly clock: () => number;
576
+ private readonly rowTimeoutMs: number;
577
+ private readonly loadTimeoutMs: number;
578
+ private readonly sectionCapBytes: number;
579
+ private readonly maxEventIds: number;
580
+ private readonly onLog: (message: string) => void;
581
+ private readonly home: string;
582
+ private readonly uploads: Uploads;
583
+ private readonly eventListeners = new Set<(id: string) => void>();
584
+ /** When each object's live growth was last announced, for the rate limit. */
585
+ private readonly growthAnnouncedAt = new Map<string, number>();
586
+ /** Objects whose growth was held back in the current rate window. */
587
+ private readonly growthPending = new Set<string>();
588
+ /** The timer that announces an object when its rate window ends. */
589
+ private readonly growthTimers = new Map<string, ReturnType<typeof setTimeout>>();
590
+ private readonly unsubscribe: (() => void)[] = [];
591
+ private candidateSource: CandidateSource | undefined;
592
+ private preparing: Promise<void> | undefined;
593
+
594
+ constructor(options: ViewsOptions) {
595
+ this.registry = options.registry;
596
+ this.store = options.store ?? options.registry.store;
597
+ this.log = options.log;
598
+ this.cwd = options.cwd ?? options.registry.workdir;
599
+ this.scope = options.scope;
600
+ this.clock = options.clock ?? (() => Date.now());
601
+ this.rowTimeoutMs = options.rowTimeoutMs ?? DEFAULT_ROW_TIMEOUT_MS;
602
+ this.loadTimeoutMs = options.loadTimeoutMs ?? DEFAULT_LOAD_TIMEOUT_MS;
603
+ this.sectionCapBytes =
604
+ options.sectionCapBytes ?? DEFAULT_SECTION_CAP_BYTES;
605
+ this.maxEventIds = options.maxEventIds ?? DEFAULT_MAX_EVENT_IDS;
606
+ this.onLog = options.onLog ?? ((message) => console.error(message));
607
+ this.home = options.home ?? options.registry.home;
608
+ this.uploads = new Uploads({ home: this.home, clock: this.clock });
609
+
610
+ if (followsChanges(options)) {
611
+ if (typeof this.store.subscribe === "function") {
612
+ this.unsubscribe.push(
613
+ this.store.subscribe((object) => this.publish(object.id)),
614
+ );
615
+ }
616
+ if (typeof this.log?.subscribe === "function") {
617
+ this.unsubscribe.push(
618
+ this.log.subscribe((change) => {
619
+ const parsed = change.object === undefined
620
+ ? undefined
621
+ : splitId(change.object);
622
+ if (parsed === undefined) return;
623
+ if (parsed.type === "flow") return;
624
+ this.publish(parsed.id, true);
625
+ }),
626
+ );
627
+ }
628
+ }
629
+ }
630
+
631
+ /** Runs each object type's `prepare` once; a failure is tried again next time. */
632
+ private prepared(): Promise<void> {
633
+ if (this.preparing === undefined) {
634
+ const running = (async () => {
635
+ for (const entry of this.registry.objectTypes()) {
636
+ await entry.definition.prepare?.({
637
+ store: this.store,
638
+ home: this.registry.home,
639
+ settings: this.registry.settingsFor(entry.plugin),
640
+ });
641
+ }
642
+ })();
643
+ this.preparing = running;
644
+ running.catch(() => {
645
+ if (this.preparing === running) this.preparing = undefined;
646
+ });
647
+ }
648
+ return this.preparing;
649
+ }
650
+
651
+ /**
652
+ * One plugin's settings from the file now, validated and with defaults. The
653
+ * registry's copy stands in when the file or the section is unusable.
654
+ */
655
+ private settingsInForce(plugin: string): Readonly<Record<string, JsonValue>> {
656
+ const fallback = this.registry.settingsFor(plugin);
657
+ const schema = this.registry
658
+ .settingsDeclarations()
659
+ .find((entry) => entry.plugin === plugin)?.schema;
660
+ if (schema === undefined) return fallback;
661
+ let parsed: unknown;
662
+ try {
663
+ parsed = JSON.parse(readFileSync(configPath(this.registry.home), "utf8"));
664
+ } catch {
665
+ return fallback;
666
+ }
667
+ const plugins = isRecord(parsed) ? parsed.plugins : undefined;
668
+ const entry = isRecord(plugins) ? plugins[plugin] : undefined;
669
+ const section = isRecord(entry) ? entry.settings : undefined;
670
+ try {
671
+ return prepareSettings(schema, section, plugin);
672
+ } catch {
673
+ return fallback;
674
+ }
675
+ }
676
+
677
+ /** An object after its type's `prepare` runs with the settings in force now. */
678
+ private async refreshedObject(
679
+ type: string,
680
+ id: string,
681
+ ): Promise<StoredObject | undefined> {
682
+ const entry = this.registry.objectTypes().find((item) => item.type === type);
683
+ const prepare = entry?.definition.prepare;
684
+ if (entry !== undefined && prepare !== undefined) {
685
+ try {
686
+ await prepare({
687
+ store: this.store,
688
+ home: this.registry.home,
689
+ settings: this.settingsInForce(entry.plugin),
690
+ });
691
+ } catch (error) {
692
+ this.onLog(
693
+ `plugin "${entry.plugin}": prepare failed: ${messageOf(error)}`,
694
+ );
695
+ }
696
+ }
697
+ return this.store.get(type, id);
698
+ }
699
+
700
+ /** Closes the change listeners this view opened. */
701
+ close(): void {
702
+ for (const unsubscribe of this.unsubscribe.splice(0)) unsubscribe();
703
+ for (const timer of this.growthTimers.values()) clearTimeout(timer);
704
+ this.growthTimers.clear();
705
+ this.growthPending.clear();
706
+ this.growthAnnouncedAt.clear();
707
+ }
708
+
709
+ /** The filter a list of this type uses when the caller names none. */
710
+ defaultFilterOf(type: string): string | undefined {
711
+ return typeFilters(this.registry.objectType(type))?.default;
712
+ }
713
+
714
+ /**
715
+ * One page of rows for a type, with the kernel's flags. A `filter` keeps the
716
+ * rows whose state it names and counts the rest in `hidden`; a list without
717
+ * one shows every row.
718
+ */
719
+ async list(
720
+ type: string,
721
+ options: TreeListOptions = {},
722
+ ): Promise<ViewListPage> {
723
+ await this.prepared();
724
+ const tree = options;
725
+ const { filter, root: _root, parent: _parent, ...listOptions } = options;
726
+ if (tree.root === true || tree.parent !== undefined) {
727
+ return this.listTree(type, options);
728
+ }
729
+ if (filter !== undefined) return this.listFiltered(type, filter, listOptions);
730
+ return this.listPlain(type, listOptions);
731
+ }
732
+
733
+ /**
734
+ * The rows of one level of the hierarchy: `root` keeps rows with no parent,
735
+ * `parent` keeps rows whose parent is that object. Without a type it covers
736
+ * every type that has views, in the order the plugins declare them, and each
737
+ * type's rows in the order its own list has. A parent that names no object
738
+ * lists nothing. A filter applies per type (each type's default when none is
739
+ * named; a type that does not declare the named filter shows every row), and
740
+ * `hidden` counts the rows of the level the filter left out.
741
+ */
742
+ async listTree(
743
+ type: string | undefined,
744
+ options: TreeListOptions,
745
+ ): Promise<ViewListPage> {
746
+ await this.prepared();
747
+ const root = options.root === true;
748
+ const parent = options.parent;
749
+ if (root && parent !== undefined) {
750
+ throw new ViewError("args", "root and parent cannot be combined");
751
+ }
752
+ if (!root && (parent === undefined || parent.trim().length === 0)) {
753
+ throw new ViewError("args", "parent needs an object id");
754
+ }
755
+ const label = type === undefined ? "list" : `list "${type}"`;
756
+ const types: string[] = [];
757
+ if (type === undefined) {
758
+ for (const entry of this.registry.objectTypes()) {
759
+ if (types.includes(entry.type)) continue;
760
+ if (this.registry.viewsFor(entry.type) === undefined) continue;
761
+ types.push(entry.type);
762
+ }
763
+ } else {
764
+ if (this.registry.viewsFor(type) === undefined) {
765
+ throw new ViewError(
766
+ "no-views",
767
+ `no loaded plugin shows objects of type "${type}"`,
768
+ );
769
+ }
770
+ types.push(type);
771
+ }
772
+ const fingerprint = whereFingerprint(options.where ?? {});
773
+ let after: { readonly t: number; readonly id: string } | undefined;
774
+ if (options.cursor !== undefined) {
775
+ try {
776
+ const cursor = decodeCursor(options.cursor, label);
777
+ const mark = cursor.after;
778
+ if (
779
+ cursor.kind !== "tree" ||
780
+ (cursor.type ?? undefined) !== type ||
781
+ (cursor.filter ?? undefined) !== options.filter ||
782
+ cursor.where !== fingerprint ||
783
+ (cursor.root === true) !== root ||
784
+ (cursor.parent ?? undefined) !== parent ||
785
+ !isRecord(mark) ||
786
+ typeof mark.t !== "number" ||
787
+ typeof mark.id !== "string"
788
+ ) {
789
+ throw new CursorError(`${label}: the cursor was made for a different list`);
790
+ }
791
+ after = { t: mark.t, id: mark.id };
792
+ } catch (error) {
793
+ if (error instanceof CursorError) {
794
+ throw new ViewError("cursor", error.message, { cause: error });
795
+ }
796
+ throw error;
797
+ }
798
+ }
799
+ const limit = (() => {
800
+ try {
801
+ return pageLimit(options.limit);
802
+ } catch (error) {
803
+ throw new ViewError("args", messageOf(error), { cause: error });
804
+ }
805
+ })();
806
+
807
+ const accepted = root || parent === undefined ? undefined : await this.parentForms(parent);
808
+ const flags = await this.allRunFlags();
809
+ const shown: { readonly t: number; readonly id: string; readonly row: ViewRow }[] = [];
810
+ let hidden = 0;
811
+ const hiddenCounts = { done: 0, cancelled: 0, other: 0 };
812
+ let counted = false;
813
+ for (const [t, name] of types.entries()) {
814
+ const owner = this.registry.viewsFor(name);
815
+ if (owner === undefined) continue;
816
+ const declared = typeFilters(this.registry.objectType(name));
817
+ let chosen: TypeFilter | undefined;
818
+ const wanted = options.filter ?? declared?.default;
819
+ if (wanted !== undefined) {
820
+ chosen = declared?.filters.find((candidate) => candidate.name === wanted);
821
+ if (chosen === undefined && type !== undefined) {
822
+ throw new ViewError(
823
+ "filter",
824
+ declared === undefined
825
+ ? `type "${name}": this type has no filters`
826
+ : `type "${name}": unknown filter "${wanted}"; allowed: ${declared.filters
827
+ .map((candidate) => candidate.name)
828
+ .join(", ")}`,
829
+ );
830
+ }
831
+ if (chosen?.name === ALL_FILTER) chosen = undefined;
832
+ }
833
+ if (chosen !== undefined) counted = true;
834
+ const withScope = await this.scopeShown(owner.plugin, name, owner.views);
835
+ let cursor: string | undefined;
836
+ do {
837
+ let page;
838
+ try {
839
+ page = await this.store.list(name, {
840
+ ...(options.where === undefined ? {} : { where: options.where }),
841
+ ...(options.index === undefined ? {} : { index: options.index }),
842
+ ...(cursor === undefined ? {} : { cursor }),
843
+ limit: MAX_PAGE_LIMIT,
844
+ });
845
+ } catch (error) {
846
+ if (error instanceof WhereError || error instanceof CursorError) {
847
+ throw new ViewError(
848
+ error instanceof CursorError ? "cursor" : "where",
849
+ error.message,
850
+ { cause: error },
851
+ );
852
+ }
853
+ throw error;
854
+ }
855
+ for (const object of page.objects) {
856
+ const row = this.listRow(owner.plugin, name, object, flags, withScope);
857
+ const rowParent = row.parent;
858
+ const inLevel =
859
+ accepted === undefined ? rowParent === undefined : rowParent !== undefined && accepted.has(rowParent);
860
+ if (!inLevel) continue;
861
+ if (chosen === undefined || filterShows(chosen, row.state)) {
862
+ shown.push({ t, id: object.id, row });
863
+ } else {
864
+ hidden += 1;
865
+ hiddenCounts[hiddenRole(row)] += 1;
866
+ }
867
+ }
868
+ cursor = page.next;
869
+ } while (cursor !== undefined);
870
+ }
871
+
872
+ let start = 0;
873
+ if (after !== undefined) {
874
+ const resume = after;
875
+ const next = shown.findIndex(
876
+ (entry) => entry.t > resume.t || (entry.t === resume.t && entry.id > resume.id),
877
+ );
878
+ start = next >= 0 ? next : shown.length;
879
+ }
880
+ const slice = shown.slice(start, start + limit);
881
+ const last = slice[slice.length - 1];
882
+ const more = start + limit < shown.length && last !== undefined;
883
+ return {
884
+ rows: slice.map((entry) => entry.row),
885
+ ...(more
886
+ ? {
887
+ next: encodeCursor({
888
+ kind: "tree",
889
+ type: type ?? null,
890
+ filter: options.filter ?? null,
891
+ where: fingerprint,
892
+ root,
893
+ parent: parent ?? null,
894
+ after: { t: last.t, id: last.id },
895
+ }),
896
+ }
897
+ : {}),
898
+ ...(counted ? { hidden, hiddenCounts } : {}),
899
+ };
900
+ }
901
+
902
+ /** The spellings a row's `parent` may use for the object this id names. */
903
+ private async parentForms(parent: string): Promise<ReadonlySet<string>> {
904
+ const forms = new Set<string>([parent]);
905
+ try {
906
+ const resolved = await this.resolve(parent);
907
+ forms.add(objectKey(resolved.type, resolved.id));
908
+ forms.add(resolved.id);
909
+ } catch {
910
+ // An id that names nothing, or names two things, matches only as written.
911
+ }
912
+ return forms;
913
+ }
914
+
915
+ private async listFiltered(
916
+ type: string,
917
+ name: string,
918
+ options: ListOptions,
919
+ ): Promise<ViewListPage> {
920
+ const declared = typeFilters(this.registry.objectType(type));
921
+ if (declared === undefined) {
922
+ throw new ViewError("filter", `type "${type}": this type has no filters`);
923
+ }
924
+ const chosen = declared.filters.find((candidate) => candidate.name === name);
925
+ if (chosen === undefined) {
926
+ throw new ViewError(
927
+ "filter",
928
+ `type "${type}": unknown filter "${name}"; allowed: ${declared.filters
929
+ .map((candidate) => candidate.name)
930
+ .join(", ")}`,
931
+ );
932
+ }
933
+ if (chosen.name === ALL_FILTER) return this.listPlain(type, options);
934
+
935
+ const owner = this.registry.viewsFor(type);
936
+ if (owner === undefined) {
937
+ throw new ViewError(
938
+ "no-views",
939
+ `no loaded plugin shows objects of type "${type}"`,
940
+ );
941
+ }
942
+ const label = `list "${type}"`;
943
+ const fingerprint = whereFingerprint(options.where ?? {});
944
+ let after: string | undefined;
945
+ if (options.cursor !== undefined) {
946
+ try {
947
+ const cursor = decodeCursor(options.cursor, label);
948
+ if (
949
+ cursor.kind !== "filtered" ||
950
+ cursor.type !== type ||
951
+ cursor.filter !== chosen.name ||
952
+ cursor.where !== fingerprint ||
953
+ typeof cursor.after !== "string"
954
+ ) {
955
+ throw new CursorError(`${label}: the cursor was made for a different list`);
956
+ }
957
+ after = cursor.after;
958
+ } catch (error) {
959
+ if (error instanceof CursorError) {
960
+ throw new ViewError("cursor", error.message, { cause: error });
961
+ }
962
+ throw error;
963
+ }
964
+ }
965
+ const limit = (() => {
966
+ try {
967
+ return pageLimit(options.limit);
968
+ } catch (error) {
969
+ throw new ViewError("args", messageOf(error), { cause: error });
970
+ }
971
+ })();
972
+
973
+ // The state is the plugin's row, so every object is read to be judged.
974
+ const flags = await this.allRunFlags();
975
+ const withScope = await this.scopeShown(owner.plugin, type, owner.views);
976
+ const shown: { readonly id: string; readonly row: ViewRow }[] = [];
977
+ let hidden = 0;
978
+ const hiddenCounts = { done: 0, cancelled: 0, other: 0 };
979
+ let cursor: string | undefined;
980
+ do {
981
+ let page;
982
+ try {
983
+ page = await this.store.list(type, {
984
+ ...(options.where === undefined ? {} : { where: options.where }),
985
+ ...(options.index === undefined ? {} : { index: options.index }),
986
+ ...(cursor === undefined ? {} : { cursor }),
987
+ limit: MAX_PAGE_LIMIT,
988
+ });
989
+ } catch (error) {
990
+ if (error instanceof WhereError || error instanceof CursorError) {
991
+ throw new ViewError(
992
+ error instanceof CursorError ? "cursor" : "where",
993
+ error.message,
994
+ { cause: error },
995
+ );
996
+ }
997
+ throw error;
998
+ }
999
+ for (const object of page.objects) {
1000
+ const row = this.listRow(owner.plugin, type, object, flags, withScope);
1001
+ if (filterShows(chosen, row.state)) shown.push({ id: object.id, row });
1002
+ else {
1003
+ hidden += 1;
1004
+ hiddenCounts[hiddenRole(row)] += 1;
1005
+ }
1006
+ }
1007
+ cursor = page.next;
1008
+ } while (cursor !== undefined);
1009
+
1010
+ let start = 0;
1011
+ if (after !== undefined) {
1012
+ const resume = after;
1013
+ const at = shown.findIndex((entry) => entry.id === resume);
1014
+ const next = shown.findIndex((entry) => entry.id > resume);
1015
+ start = at >= 0 ? at + 1 : next >= 0 ? next : shown.length;
1016
+ }
1017
+ const slice = shown.slice(start, start + limit);
1018
+ const last = slice[slice.length - 1];
1019
+ const more = start + limit < shown.length && last !== undefined;
1020
+ return {
1021
+ rows: slice.map((entry) => entry.row),
1022
+ ...(more
1023
+ ? {
1024
+ next: encodeCursor({
1025
+ kind: "filtered",
1026
+ type,
1027
+ filter: chosen.name,
1028
+ where: fingerprint,
1029
+ after: last.id,
1030
+ }),
1031
+ }
1032
+ : {}),
1033
+ hidden,
1034
+ hiddenCounts,
1035
+ };
1036
+ }
1037
+
1038
+ private async listPlain(type: string, options: ListOptions): Promise<ViewListPage> {
1039
+ const owner = this.registry.viewsFor(type);
1040
+ if (owner === undefined) {
1041
+ throw new ViewError(
1042
+ "no-views",
1043
+ `no loaded plugin shows objects of type "${type}"`,
1044
+ );
1045
+ }
1046
+
1047
+ if (options.where !== undefined) {
1048
+ try {
1049
+ assertWhere(
1050
+ options.index ?? this.registry.indexFor(type) ?? Object.keys(options.where),
1051
+ options.where,
1052
+ `list "${type}"`,
1053
+ );
1054
+ } catch (error) {
1055
+ if (error instanceof WhereError) {
1056
+ throw new ViewError("where", error.message, { cause: error });
1057
+ }
1058
+ throw error;
1059
+ }
1060
+ }
1061
+
1062
+ let page;
1063
+ try {
1064
+ page = await this.store.list(type, options);
1065
+ } catch (error) {
1066
+ if (error instanceof WhereError || error instanceof CursorError) {
1067
+ throw new ViewError(
1068
+ error instanceof CursorError ? "cursor" : "where",
1069
+ error.message,
1070
+ { cause: error },
1071
+ );
1072
+ }
1073
+ throw error;
1074
+ }
1075
+ const flags = await this.allRunFlags();
1076
+ const withScope = await this.scopeShown(owner.plugin, type, owner.views);
1077
+ const rows = page.objects.map((object) =>
1078
+ this.listRow(owner.plugin, type, object, flags, withScope),
1079
+ );
1080
+ return { rows, ...(page.next === undefined ? {} : { next: page.next }) };
1081
+ }
1082
+
1083
+ /**
1084
+ * The rows `list` would show for these objects, keyed `<type>:<id>`. One
1085
+ * read of the run flags serves them all. An object that is gone, or whose
1086
+ * type no loaded plugin shows, gets an error row, and a plugin whose `row`
1087
+ * throws gets the same error row `list` shows; this never throws for one
1088
+ * object.
1089
+ */
1090
+ async rowsOf(
1091
+ objects: readonly ObjectRef[],
1092
+ ): Promise<ReadonlyMap<string, ViewRow>> {
1093
+ const rows = new Map<string, ViewRow>();
1094
+ if (objects.length === 0) return rows;
1095
+ const flags = await this.allRunFlags();
1096
+ const shown = new Map<string, boolean>();
1097
+ for (const ref of objects) {
1098
+ const key = objectKey(ref.type, ref.id);
1099
+ if (rows.has(key)) continue;
1100
+ const owner = this.registry.viewsFor(ref.type);
1101
+ let stored: StoredObject | undefined;
1102
+ try {
1103
+ stored = await this.store.get(ref.type, ref.id);
1104
+ } catch (error) {
1105
+ this.onLog(`could not read "${key}": ${messageOf(error)}`);
1106
+ }
1107
+ if (owner === undefined || stored === undefined) {
1108
+ rows.set(
1109
+ key,
1110
+ this.errorRow(
1111
+ ref.id,
1112
+ owner === undefined
1113
+ ? `no loaded plugin shows objects of type "${ref.type}"`
1114
+ : `no object "${key}"`,
1115
+ ),
1116
+ );
1117
+ continue;
1118
+ }
1119
+ let withScope = shown.get(ref.type);
1120
+ if (withScope === undefined) {
1121
+ withScope = await this.scopeShown(owner.plugin, ref.type, owner.views);
1122
+ shown.set(ref.type, withScope);
1123
+ }
1124
+ rows.set(key, this.listRow(owner.plugin, ref.type, stored, flags, withScope));
1125
+ }
1126
+ return rows;
1127
+ }
1128
+
1129
+ /** One list row: the plugin's row with the run flags and, when shown, its scope. */
1130
+ private listRow(
1131
+ plugin: string,
1132
+ type: string,
1133
+ object: StoredObject,
1134
+ flags: ReadonlyMap<string, RunFlags>,
1135
+ withScope: boolean,
1136
+ ): ViewRow {
1137
+ const { scope, ...row } = this.guardedRow(plugin, type, object);
1138
+ const flag = flags.get(objectKey(type, object.id)) ?? {
1139
+ waiting: false,
1140
+ running: false,
1141
+ };
1142
+ return {
1143
+ ...row,
1144
+ ...(withScope && scope !== undefined ? { scope } : {}),
1145
+ // A plugin's own `waiting` is an object a person must act on that has no run.
1146
+ waiting: row.waiting || flag.waiting,
1147
+ running: flag.running,
1148
+ };
1149
+ }
1150
+
1151
+ /** One page of one object's facts in sequence order. */
1152
+ async facts(id: string, options: FactsOptions = {}): Promise<FactsPage> {
1153
+ const resolved = await this.resolve(id);
1154
+ return this.store.facts({ type: resolved.type, id: resolved.id }, options);
1155
+ }
1156
+
1157
+ /** One object: its row, its section directory and the actions available now. */
1158
+ async get(id: string): Promise<ViewObject> {
1159
+ const resolved = await this.resolve(id);
1160
+ const owner = this.registry.viewsFor(resolved.type);
1161
+ const object = resolved.object;
1162
+ if (
1163
+ object === undefined &&
1164
+ owner !== undefined &&
1165
+ !(await this.hasRun(resolved.type, resolved.id)) &&
1166
+ this.store.facts({ type: resolved.type, id: resolved.id }, { limit: 1 }).facts.length === 0
1167
+ ) {
1168
+ // A plugin that scopes ids claims any well-formed id; nothing stored or
1169
+ // recorded under it means the id matches nothing.
1170
+ throw new ViewError(
1171
+ "not-found",
1172
+ `no object "${id}" of type "${resolved.type}"`,
1173
+ );
1174
+ }
1175
+ const flags = await this.flagsFor(resolved.type, resolved.id);
1176
+
1177
+ let row: ViewRow;
1178
+ let sections: ViewSectionInfo[] = [];
1179
+ const actions: ViewAction[] = [];
1180
+ let unavailable: string | undefined;
1181
+ let dependents: readonly string[] = [];
1182
+
1183
+ if (owner !== undefined && object !== undefined) {
1184
+ const { scope, ...guarded } = this.guardedRow(
1185
+ owner.plugin,
1186
+ resolved.type,
1187
+ object,
1188
+ );
1189
+ row = { ...guarded, ...flags, waiting: guarded.waiting || flags.waiting };
1190
+ try {
1191
+ sections = this.sectionDirectory(owner.plugin, object);
1192
+ } catch (error) {
1193
+ this.onLog(
1194
+ `plugin "${owner.plugin}": sections failed for "${resolved.type}:${resolved.id}": ${messageOf(error)}`,
1195
+ );
1196
+ sections = [];
1197
+ }
1198
+ actions.push(...(await this.availableActions(resolved.type, object)));
1199
+ dependents = await this.dependentsOf(owner.plugin, resolved.type, row.id, scope);
1200
+ } else {
1201
+ row = {
1202
+ id: resolved.id,
1203
+ title: resolved.id,
1204
+ state: "unknown",
1205
+ ...flags,
1206
+ };
1207
+ if (owner === undefined) {
1208
+ unavailable = `the plugin that owns "${resolved.type}" is not loaded; showing history only`;
1209
+ }
1210
+ }
1211
+
1212
+ sections = sections.filter((section) => section.id !== HISTORY_SECTION);
1213
+ sections.push({ id: HISTORY_SECTION, title: "History" });
1214
+
1215
+ return {
1216
+ id: resolved.id,
1217
+ type: resolved.type,
1218
+ link: objectLink(resolved.type, resolved.id),
1219
+ row,
1220
+ sections,
1221
+ actions,
1222
+ ...(unavailable === undefined ? {} : { unavailable }),
1223
+ ...(dependents.length === 0 ? {} : { dependents }),
1224
+ };
1225
+ }
1226
+
1227
+ /**
1228
+ * The ids of the objects of a type whose row names `rowId` in `after`. A row
1229
+ * with a scope names only rows of its own scope.
1230
+ */
1231
+ private async dependentsOf(
1232
+ plugin: string,
1233
+ type: string,
1234
+ rowId: string,
1235
+ scope: string | undefined,
1236
+ ): Promise<readonly string[]> {
1237
+ const found: string[] = [];
1238
+ let cursor: string | undefined;
1239
+ do {
1240
+ const page = await this.store.list(type, cursor === undefined ? {} : { cursor });
1241
+ for (const object of page.objects) {
1242
+ const row = this.guardedRow(plugin, type, object);
1243
+ if (
1244
+ row.id !== rowId &&
1245
+ row.scope === scope &&
1246
+ row.after?.includes(rowId) === true
1247
+ ) {
1248
+ found.push(row.id);
1249
+ }
1250
+ }
1251
+ cursor = page.next;
1252
+ } while (cursor !== undefined);
1253
+ return found.sort();
1254
+ }
1255
+
1256
+ /** The Markdown of one section; `history` is served by the kernel. */
1257
+ async section(
1258
+ id: string,
1259
+ sectionId: string,
1260
+ cursor?: string,
1261
+ options: SectionOptions = {},
1262
+ ): Promise<ViewSectionContent> {
1263
+ const resolved = await this.resolve(id);
1264
+ const after =
1265
+ options.after === undefined
1266
+ ? undefined
1267
+ : decodeSectionMark(options.after, resolved.type, resolved.id, sectionId);
1268
+ if (sectionId === HISTORY_SECTION) {
1269
+ const markdown = await this.historyMarkdown(
1270
+ resolved.type,
1271
+ resolved.id,
1272
+ options.full === true,
1273
+ );
1274
+ return this.finishSection(
1275
+ id,
1276
+ sectionId,
1277
+ markdown,
1278
+ undefined,
1279
+ undefined,
1280
+ undefined,
1281
+ options.full === true,
1282
+ after === undefined ? undefined : false,
1283
+ );
1284
+ }
1285
+
1286
+ const owner = this.registry.viewsFor(resolved.type);
1287
+ if (owner === undefined) {
1288
+ throw new ViewError(
1289
+ "unavailable",
1290
+ `the plugin that owns "${resolved.type}" is not loaded; only "${HISTORY_SECTION}" is available`,
1291
+ );
1292
+ }
1293
+ const object = resolved.object;
1294
+ if (object === undefined) {
1295
+ throw new ViewError(
1296
+ "not-found",
1297
+ `no object "${id}" of type "${resolved.type}"`,
1298
+ );
1299
+ }
1300
+ const directory = this.sectionDirectory(owner.plugin, object);
1301
+ const section = directory.find((entry) => entry.id === sectionId);
1302
+ if (section === undefined) {
1303
+ throw new ViewError(
1304
+ "section",
1305
+ `object "${id}" has no section "${sectionId}"`,
1306
+ );
1307
+ }
1308
+
1309
+ const controller = new AbortController();
1310
+ let timer: ReturnType<typeof setTimeout> | undefined;
1311
+ const timeout = new Promise<never>((_, reject) => {
1312
+ timer = setTimeout(() => {
1313
+ controller.abort();
1314
+ reject(
1315
+ new ViewError(
1316
+ "timeout",
1317
+ `section "${sectionId}" of "${id}" did not answer within ${this.loadTimeoutMs}ms`,
1318
+ ),
1319
+ );
1320
+ }, this.loadTimeoutMs);
1321
+ });
1322
+
1323
+ let content: unknown;
1324
+ try {
1325
+ const ctx = this.viewContext(owner.plugin, controller.signal);
1326
+ const work = Promise.resolve().then(() =>
1327
+ owner.views.load(ctx, object, sectionId, {
1328
+ ...(cursor === undefined ? {} : { cursor }),
1329
+ ...(after === undefined ? {} : { after }),
1330
+ }),
1331
+ );
1332
+ content = await Promise.race([work, timeout]);
1333
+ } catch (error) {
1334
+ if (error instanceof ViewError) throw error;
1335
+ throw new ViewError(
1336
+ "section",
1337
+ `section "${sectionId}" of "${id}" failed: ${messageOf(error)}`,
1338
+ { cause: error },
1339
+ );
1340
+ } finally {
1341
+ if (timer !== undefined) clearTimeout(timer);
1342
+ }
1343
+
1344
+ const markdown = isRecord(content) ? textOf(content.markdown) : undefined;
1345
+ if (markdown === undefined) {
1346
+ throw new ViewError(
1347
+ "section",
1348
+ `section "${sectionId}" of "${id}": load must return { markdown, next? }`,
1349
+ );
1350
+ }
1351
+ const next = isRecord(content) ? textOf(content.next) : undefined;
1352
+ const pages = isRecord(content) ? pagesOf(content.pages) : undefined;
1353
+ const rawMark = isRecord(content) ? textOf(content.mark) : undefined;
1354
+ const tail = isRecord(content) ? textOf(content.tail) : undefined;
1355
+ // A plugin that ignored `after` answers with a whole page; only one that
1356
+ // says its answer is the delta may be appended to by a client.
1357
+ const honoured =
1358
+ isRecord(content) && content.delta === true && after !== undefined;
1359
+ const mark =
1360
+ rawMark === undefined
1361
+ ? undefined
1362
+ : encodeSectionMark(resolved.type, resolved.id, section.id, rawMark);
1363
+ const finished = this.finishSection(
1364
+ id,
1365
+ section.id,
1366
+ markdown,
1367
+ next,
1368
+ mark,
1369
+ tail,
1370
+ options.full === true,
1371
+ after === undefined ? undefined : honoured,
1372
+ );
1373
+ return pages === undefined ? finished : { ...finished, pages };
1374
+ }
1375
+
1376
+ /** An async stream of ids that changed. Repeated ids coalesce. */
1377
+ events(): AsyncIterable<ViewEvent> {
1378
+ return new EventStream(
1379
+ this.maxEventIds,
1380
+ this.eventListeners,
1381
+ () => this.flushDueGrowth(),
1382
+ );
1383
+ }
1384
+
1385
+ /** Every setting in a scope (global and every repository when omitted). */
1386
+ async settings(scope?: string | undefined): Promise<readonly SettingInfo[]> {
1387
+ try {
1388
+ return await listSettings(this.settingsOptions(), scope);
1389
+ } catch (error) {
1390
+ throw settingsViewError(error);
1391
+ }
1392
+ }
1393
+
1394
+ /** Changes one setting; a refusal writes nothing. */
1395
+ async set(
1396
+ name: string,
1397
+ value: unknown,
1398
+ options: { readonly scope?: string | undefined; readonly confirmed?: boolean | undefined } = {},
1399
+ ): Promise<SettingInfo> {
1400
+ try {
1401
+ return await setSetting(this.settingsOptions(), name, value, options);
1402
+ } catch (error) {
1403
+ throw settingsViewError(error);
1404
+ }
1405
+ }
1406
+
1407
+ private settingsOptions(): SettingsOptions {
1408
+ return { registry: this.registry, store: this.store, home: this.home };
1409
+ }
1410
+
1411
+ /**
1412
+ * Answers one question of a pending item by the wait id it named. A closed
1413
+ * question is refused, as it is for the command line and a plugin action.
1414
+ */
1415
+ async answer(options: AnswerViewOptions): Promise<void> {
1416
+ const who: unknown = (options as { actor?: unknown } | undefined)?.actor;
1417
+ if (
1418
+ !isRecord(who) ||
1419
+ typeof who.via !== "string" ||
1420
+ who.via.length === 0 ||
1421
+ typeof who.id !== "string" ||
1422
+ who.id.length === 0
1423
+ ) {
1424
+ throw new ViewError(
1425
+ "args",
1426
+ "answer needs an actor: { via, id } says who answered",
1427
+ );
1428
+ }
1429
+ if (this.log === undefined) {
1430
+ throw new ViewError(
1431
+ "not-available",
1432
+ "this server has no run log, so it cannot answer a question",
1433
+ );
1434
+ }
1435
+ const pending = await listPending(this.log, this.registry);
1436
+ const item = pending.find(
1437
+ (candidate) =>
1438
+ candidate.runId === options.runId && candidate.waitId === options.waitId,
1439
+ );
1440
+ // A wait whose choices are the object's actions answers through that
1441
+ // action, so its note, confirmation and object update still happen.
1442
+ const throughAction =
1443
+ item !== undefined &&
1444
+ item.choices.every((name) =>
1445
+ item.actions.some((action) => action.action === name),
1446
+ )
1447
+ ? item.actions.find((action) => action.action === options.choice)
1448
+ : undefined;
1449
+ if (item !== undefined && throughAction !== undefined) {
1450
+ const info = this.resolveActionInfo(
1451
+ `${throughAction.plugin}:${throughAction.action}`,
1452
+ );
1453
+ if (item.object === undefined) {
1454
+ throw new ViewError(
1455
+ "not-found",
1456
+ `the pending item "${options.waitId}" names no object`,
1457
+ );
1458
+ }
1459
+ await this.act(info.name, item.object, {
1460
+ ...(options.note === undefined ? {} : { note: options.note }),
1461
+ ...(options.surface === undefined ? {} : { surface: options.surface }),
1462
+ yes: options.confirmed === true,
1463
+ actor: options.actor,
1464
+ });
1465
+ return;
1466
+ }
1467
+ try {
1468
+ await recordAnswer({
1469
+ log: this.log,
1470
+ runId: options.runId,
1471
+ waitId: options.waitId,
1472
+ choice: options.choice,
1473
+ ...(options.note === undefined ? {} : { note: options.note }),
1474
+ actor: options.actor,
1475
+ });
1476
+ } catch (error) {
1477
+ if (error instanceof StateError) {
1478
+ throw new ViewError("not-available", error.message, { cause: error });
1479
+ }
1480
+ throw error;
1481
+ }
1482
+ }
1483
+
1484
+ /**
1485
+ * Where `pending` gets the trigger candidates and refused starts, the same
1486
+ * source HTTP passes `listPending`. The host that owns the kernel sets it.
1487
+ */
1488
+ useCandidates(source: CandidateSource | undefined): void {
1489
+ this.candidateSource = source;
1490
+ }
1491
+
1492
+ /** What waits for a person: the pending view, as HTTP serves it. */
1493
+ async pending(): Promise<readonly PendingItem[]> {
1494
+ if (this.log === undefined) {
1495
+ throw new ViewError(
1496
+ "not-available",
1497
+ "this server has no run log, so it cannot list what is pending",
1498
+ );
1499
+ }
1500
+ return listPending(this.log, this.registry, this.candidateSource, this);
1501
+ }
1502
+
1503
+ /** Runs one action by `<plugin>:<action>`, honouring note and confirm. */
1504
+ async act(
1505
+ name: string,
1506
+ id: string | undefined,
1507
+ options: ActOptions,
1508
+ ): Promise<ViewActionRun> {
1509
+ // The type asks for an actor; a caller outside the type checker (a plugin
1510
+ // in plain JavaScript) is refused here, before anything runs.
1511
+ const who: unknown = (options as { actor?: unknown } | undefined)?.actor;
1512
+ if (
1513
+ !isRecord(who) ||
1514
+ typeof who.via !== "string" ||
1515
+ who.via.length === 0 ||
1516
+ typeof who.id !== "string" ||
1517
+ who.id.length === 0
1518
+ ) {
1519
+ throw new ViewError(
1520
+ "args",
1521
+ `action "${name}" needs an actor: { via, id } says who asked`,
1522
+ );
1523
+ }
1524
+ // An action that targets no object names no id. The kernel has no such
1525
+ // action today, but the HTTP body allows it, so the views say why it
1526
+ // cannot run instead of refusing the request before looking it up.
1527
+ if (id === undefined) {
1528
+ const info = this.resolveActionInfo(name);
1529
+ throw new ViewError(
1530
+ "not-found",
1531
+ `action "${info.name}" targets ${info.on} objects; pass the object id`,
1532
+ );
1533
+ }
1534
+ const resolved = await this.resolve(id);
1535
+ const object = resolved.object;
1536
+ if (object === undefined) {
1537
+ throw new ViewError(
1538
+ "not-found",
1539
+ `no object "${id}" of type "${resolved.type}"`,
1540
+ );
1541
+ }
1542
+
1543
+ const owner = this.registry.viewsFor(resolved.type);
1544
+ const subject =
1545
+ owner === undefined
1546
+ ? resolved.id
1547
+ : this.guardedRow(owner.plugin, resolved.type, object).id;
1548
+ const target = this.resolveAction(name, resolved.type, subject);
1549
+ const env = this.registry.actionEnv();
1550
+
1551
+ // A result that is already true is not an error: the plugin says so and
1552
+ // nothing runs.
1553
+ if (target.action.settled !== undefined) {
1554
+ let message: string | undefined;
1555
+ try {
1556
+ message = await target.action.settled(object, options.args ?? {}, env);
1557
+ } catch (error) {
1558
+ this.onLog(
1559
+ `plugin "${target.plugin}": action "${target.action.name}": settled failed: ${messageOf(error)}`,
1560
+ );
1561
+ }
1562
+ if (message !== undefined && message.length > 0) {
1563
+ return {
1564
+ plugin: target.plugin,
1565
+ action: target.action.name,
1566
+ name: target.info.name,
1567
+ value: message,
1568
+ settled: true,
1569
+ };
1570
+ }
1571
+ }
1572
+
1573
+ let holds: unknown;
1574
+ try {
1575
+ holds = await target.action.when(object.data, env);
1576
+ } catch (error) {
1577
+ this.onLog(
1578
+ `plugin "${target.plugin}": action "${target.action.name}": when failed: ${messageOf(error)}`,
1579
+ );
1580
+ throw new ViewError(
1581
+ "not-available",
1582
+ `${subject} cannot ${target.info.name} now`,
1583
+ );
1584
+ }
1585
+ if (holds !== true) {
1586
+ throw new ViewError("not-available", await this.refusal(target, object, subject));
1587
+ }
1588
+
1589
+ const args: Record<string, unknown> = { ...(options.args ?? {}) };
1590
+ const note = noteProperty(target.action.args);
1591
+ if (
1592
+ note !== undefined &&
1593
+ options.note !== undefined &&
1594
+ args[note.name] === undefined
1595
+ ) {
1596
+ args[note.name] = options.note;
1597
+ }
1598
+ if (
1599
+ note?.required === true &&
1600
+ (args[note.name] === undefined ||
1601
+ (typeof args[note.name] === "string" &&
1602
+ (args[note.name] as string).trim().length === 0))
1603
+ ) {
1604
+ throw new ViewError(
1605
+ "note",
1606
+ `action "${target.info.name}" needs a note; pass --${note.name} <text>`,
1607
+ );
1608
+ }
1609
+
1610
+ let personArgs: Record<string, unknown>;
1611
+ try {
1612
+ personArgs = validateActionArgs(
1613
+ target.action.argsFor?.(object, env) ?? target.action.args,
1614
+ args,
1615
+ `action "${target.info.name}"`,
1616
+ );
1617
+ } catch (error) {
1618
+ if (error instanceof ActionArgsError) {
1619
+ throw new ViewError("args", error.message, { cause: error });
1620
+ }
1621
+ throw error;
1622
+ }
1623
+
1624
+ if (target.action.confirm === true && options.yes !== true) {
1625
+ const hint =
1626
+ options.surface === "http"
1627
+ ? 'send "confirmed": true in the request body'
1628
+ : "pass --yes";
1629
+ throw new ViewError(
1630
+ "confirm",
1631
+ `action "${target.info.name}" needs confirmation; ${hint}`,
1632
+ );
1633
+ }
1634
+
1635
+ // An uploaded file is taken only now that nothing else can refuse the call;
1636
+ // the action gets the stored path where the client sent the reference.
1637
+ const stored = await this.takeFiles(
1638
+ target.action.argsFor?.(object, env) ?? target.action.args,
1639
+ personArgs,
1640
+ resolved.type,
1641
+ resolved.id,
1642
+ target.info.name,
1643
+ );
1644
+
1645
+ const runId = await this.waitingRunId(resolved.type, resolved.id);
1646
+ const result = await this.registry.runAction(
1647
+ `${target.plugin}/${target.action.name}`,
1648
+ stored,
1649
+ {
1650
+ object,
1651
+ ...(runId === undefined ? {} : { runId }),
1652
+ actor: options.actor,
1653
+ cwd: this.cwd,
1654
+ },
1655
+ );
1656
+ const opens = await this.existingOpens(target.info.name, result.opens);
1657
+ return {
1658
+ plugin: target.plugin,
1659
+ action: target.action.name,
1660
+ name: target.info.name,
1661
+ value: result.value,
1662
+ ...(opens === undefined ? {} : { opens }),
1663
+ };
1664
+ }
1665
+
1666
+ /** Replaces each file argument's upload reference with the path the file is stored at. */
1667
+ private async takeFiles(
1668
+ schema: Parameters<typeof fileProperties>[0],
1669
+ args: Record<string, unknown>,
1670
+ type: string,
1671
+ id: string,
1672
+ label: string,
1673
+ ): Promise<Record<string, unknown>> {
1674
+ const files = fileProperties(schema);
1675
+ if (files.every((file) => args[file.name] === undefined)) return args;
1676
+ const dir = attachmentDir(this.home, type, id);
1677
+ const next: Record<string, unknown> = { ...args };
1678
+ for (const file of files) {
1679
+ const value = args[file.name];
1680
+ if (value === undefined) continue;
1681
+ const refs = Array.isArray(value) ? value : [value];
1682
+ const paths: string[] = [];
1683
+ for (const ref of refs) {
1684
+ try {
1685
+ paths.push((await this.uploads.take(String(ref), dir)).path);
1686
+ } catch (error) {
1687
+ if (error instanceof UploadMissingError) {
1688
+ throw new ViewError("args", `action "${label}": args.${file.name}: ${error.message}`, { cause: error });
1689
+ }
1690
+ throw error;
1691
+ }
1692
+ }
1693
+ next[file.name] = file.many ? paths : paths[0];
1694
+ }
1695
+ return next;
1696
+ }
1697
+
1698
+ /** `opens` when it names an object that exists; otherwise the log says why. */
1699
+ private async existingOpens(action: string, opens: string | undefined): Promise<string | undefined> {
1700
+ if (opens === undefined) return undefined;
1701
+ const typed = splitId(opens);
1702
+ if (typed === undefined) {
1703
+ this.onLog(`action "${action}": opens "${opens}" is not <type>:<id>; not passed on`);
1704
+ return undefined;
1705
+ }
1706
+ let found: ResolvedObject | undefined;
1707
+ try {
1708
+ found = await this.resolve(opens);
1709
+ } catch (error) {
1710
+ this.onLog(`action "${action}": opens "${opens}" cannot be resolved (${messageOf(error)}); not passed on`);
1711
+ return undefined;
1712
+ }
1713
+ if (found.object === undefined) {
1714
+ this.onLog(`action "${action}": opens "${opens}" names no existing object; not passed on`);
1715
+ return undefined;
1716
+ }
1717
+ return opens;
1718
+ }
1719
+
1720
+ private finishSection(
1721
+ id: string,
1722
+ sectionId: string,
1723
+ markdown: string,
1724
+ next: string | undefined,
1725
+ mark: string | undefined,
1726
+ tail: string | undefined,
1727
+ full: boolean,
1728
+ delta: boolean | undefined,
1729
+ ): ViewSectionContent {
1730
+ const result = (
1731
+ shownMarkdown: string,
1732
+ shownTail: string | undefined,
1733
+ ): ViewSectionContent => ({
1734
+ markdown: shownMarkdown,
1735
+ ...(next === undefined ? {} : { next }),
1736
+ ...(mark === undefined ? {} : { mark }),
1737
+ ...(shownTail === undefined ? {} : { tail: shownTail }),
1738
+ ...(delta === undefined ? {} : { delta }),
1739
+ });
1740
+ if (full) return result(markdown, tail);
1741
+
1742
+ const suffix = truncationNote(id, sectionId);
1743
+ const limit = this.sectionCapBytes;
1744
+ const markdownBytes = Buffer.byteLength(markdown, "utf8");
1745
+ const tailBytes = tail === undefined ? 0 : Buffer.byteLength(tail, "utf8");
1746
+ if (markdownBytes + tailBytes <= limit) return result(markdown, tail);
1747
+
1748
+ // The cap covers the finished page, the changing tail and the note
1749
+ // together. The tail is never cut: if even the tail and the note do not
1750
+ // fit, the section is refused and the client asks for it whole.
1751
+ const suffixBytes = Buffer.byteLength(suffix, "utf8");
1752
+ if (tailBytes + suffixBytes > limit) {
1753
+ throw new ViewError(
1754
+ "section",
1755
+ `section "${sectionId}" of "${id}" is over the ${limit}-byte size cap; ${suffix.trim()}`,
1756
+ );
1757
+ }
1758
+ const body = capBytes(markdown, limit - suffixBytes - tailBytes);
1759
+ return result(`${body}${suffix}`, tail);
1760
+ }
1761
+
1762
+ private resolveActionInfo(name: string): ActionInfo {
1763
+ const target = splitActionName(name);
1764
+ const candidates = this.registry.actions().filter((info) =>
1765
+ target === undefined
1766
+ ? info.action === name
1767
+ : info.plugin === target.plugin && info.action === target.action,
1768
+ );
1769
+ if (candidates.length === 0) {
1770
+ throw new ViewError(
1771
+ "action",
1772
+ `there is no action "${name}"`,
1773
+ );
1774
+ }
1775
+ if (candidates.length > 1) {
1776
+ throw new ViewError(
1777
+ "ambiguous",
1778
+ `action "${name}" is offered by ${candidates.map((info) => `"${info.name}"`).join(", ")}; use "<plugin>:<action>"`,
1779
+ );
1780
+ }
1781
+ const only = candidates[0];
1782
+ if (only === undefined) {
1783
+ throw new ViewError("action", `there is no action "${name}"`);
1784
+ }
1785
+ return only;
1786
+ }
1787
+
1788
+ /**
1789
+ * The line for an action this object cannot take at all: it starts with the
1790
+ * object's own name, like every refusal, and says where the action works.
1791
+ */
1792
+ private notOffered(subject: string, name: string, type: string): ViewError {
1793
+ const target = splitActionName(name);
1794
+ const types = [
1795
+ ...new Set(
1796
+ this.registry
1797
+ .actions()
1798
+ .filter((info) =>
1799
+ target === undefined
1800
+ ? info.action === name
1801
+ : info.plugin === target.plugin && info.action === target.action,
1802
+ )
1803
+ .map((info) => info.on),
1804
+ ),
1805
+ ];
1806
+ return new ViewError(
1807
+ "action",
1808
+ types.length === 0
1809
+ ? `${subject} has no action "${name}"`
1810
+ : `${subject} is a ${type}; ${name} works on ${types.join(" or ")}`,
1811
+ );
1812
+ }
1813
+
1814
+ private resolveAction(
1815
+ name: string,
1816
+ type: string,
1817
+ subject: string,
1818
+ ): {
1819
+ readonly plugin: string;
1820
+ readonly action: ActionTypeDefinition;
1821
+ readonly info: ActionInfo;
1822
+ } {
1823
+ let target = splitActionName(name);
1824
+ if (target === undefined) {
1825
+ const candidates = this.registry
1826
+ .actions()
1827
+ .filter((info) => info.action === name && info.on === type);
1828
+ if (candidates.length === 0) throw this.notOffered(subject, name, type);
1829
+ if (candidates.length > 1) {
1830
+ throw new ViewError(
1831
+ "ambiguous",
1832
+ `action "${name}" is offered by ${candidates.map((info) => `"${info.name}"`).join(", ")}; use "<plugin>:<action>"`,
1833
+ );
1834
+ }
1835
+ const only = candidates[0];
1836
+ if (only === undefined) throw this.notOffered(subject, name, type);
1837
+ target = { plugin: only.plugin, action: only.action };
1838
+ }
1839
+
1840
+ const info = this.registry
1841
+ .actions()
1842
+ .find(
1843
+ (entry) =>
1844
+ entry.name === `${target.plugin}:${target.action}` &&
1845
+ entry.on === type,
1846
+ );
1847
+ if (info === undefined) throw this.notOffered(subject, name, type);
1848
+ const found = this.actionDefinition(target.plugin, target.action, type);
1849
+ if (found === undefined) throw this.notOffered(subject, name, type);
1850
+ return { plugin: target.plugin, action: found, info };
1851
+ }
1852
+
1853
+ private actionDefinition(
1854
+ pluginName: string,
1855
+ actionName: string,
1856
+ objectType?: string | undefined,
1857
+ ): ActionTypeDefinition | undefined {
1858
+ return this.registry.actionDefinition(pluginName, actionName, objectType);
1859
+ }
1860
+
1861
+ private async availableActions(
1862
+ type: string,
1863
+ object: StoredObject,
1864
+ ): Promise<readonly ViewAction[]> {
1865
+ const keys = new Map(this.registry.keyBindings().map((item) => [item.name, item.key]));
1866
+ const actions: (ViewAction & { readonly rank: number })[] = [];
1867
+ const env = this.registry.actionEnv();
1868
+ for (const info of this.registry.actions()) {
1869
+ if (info.on !== type) continue;
1870
+ const action = this.registry.actionDefinition(
1871
+ info.plugin,
1872
+ info.action,
1873
+ info.on,
1874
+ );
1875
+ if (action === undefined) continue;
1876
+ let holds: unknown;
1877
+ try {
1878
+ holds = await action.when(object.data, env);
1879
+ } catch (error) {
1880
+ this.onLog(
1881
+ `plugin "${info.plugin}": action "${info.action}": when failed: ${messageOf(error)}`,
1882
+ );
1883
+ continue;
1884
+ }
1885
+ if (holds !== true) continue;
1886
+ const key = keys.get(info.name);
1887
+ const args = action.argsFor?.(object, env) ?? info.args;
1888
+ actions.push({
1889
+ ...info,
1890
+ ...(args === undefined ? {} : { args }),
1891
+ ...(key === undefined ? {} : { key }),
1892
+ rank: rankOf(action, object.data),
1893
+ });
1894
+ }
1895
+ return sortByRank(actions).map(({ rank: _rank, ...view }) => view);
1896
+ }
1897
+
1898
+ private async resolve(id: string): Promise<ResolvedObject> {
1899
+ await this.prepared();
1900
+ const typed = splitId(id);
1901
+ // A qualified id names its namespace; a different `--repo` is a mistake.
1902
+ const qualified = (typed?.id ?? id).split("/");
1903
+ if (this.scope !== undefined && qualified.length > 1 && qualified[0] !== this.scope) {
1904
+ throw new ViewError(
1905
+ "args",
1906
+ `"${id}" is in repository "${qualified[0]}", but --repo names "${this.scope}"`,
1907
+ );
1908
+ }
1909
+ // A plugin may refuse a qualified id whose namespace is not valid (an
1910
+ // unregistered repository) even when an object is still stored under it.
1911
+ // A typed id is checked only by its own type's hook.
1912
+ if (qualified.length > 1) {
1913
+ await this.resolveWithPlugins(typed?.id ?? id, typed?.type);
1914
+ }
1915
+ if (typed !== undefined) {
1916
+ const object = await this.store.get(typed.type, typed.id);
1917
+ if (object !== undefined || (await this.hasRun(typed.type, typed.id))) {
1918
+ return { type: typed.type, id: typed.id, object };
1919
+ }
1920
+ // A typed bare id (`task:T-0043-x`) names a scoped object the same way
1921
+ // the bare id does, limited to its type: the operad app opens a row as
1922
+ // `<type>:<row id>`, and a row's id carries no namespace.
1923
+ if (!typed.id.includes("/")) {
1924
+ const scoped = await this.resolveWithPlugins(typed.id, typed.type);
1925
+ if (scoped !== undefined) return scoped;
1926
+ const suffixed: ResolvedObject[] = [];
1927
+ let cursor: string | undefined;
1928
+ for (;;) {
1929
+ const page = await this.store.list(
1930
+ typed.type,
1931
+ cursor === undefined ? {} : { cursor },
1932
+ );
1933
+ for (const object of page.objects) {
1934
+ if (!object.id.endsWith(`/${typed.id}`)) continue;
1935
+ suffixed.push({ type: typed.type, id: object.id, object });
1936
+ }
1937
+ if (page.next === undefined) break;
1938
+ cursor = page.next;
1939
+ }
1940
+ if (suffixed.length > 1) {
1941
+ throw new ViewError(
1942
+ "ambiguous",
1943
+ `"${id}" is ambiguous: use ${suffixed
1944
+ .map((match) => `${match.type}:${match.id}`)
1945
+ .sort()
1946
+ .join(", ")}`,
1947
+ );
1948
+ }
1949
+ const only = suffixed[0];
1950
+ if (only !== undefined) return only;
1951
+ }
1952
+ }
1953
+
1954
+ const matches: ResolvedObject[] = [];
1955
+ for (const entry of this.registry.objectTypes()) {
1956
+ const object = await this.store.get(entry.type, id);
1957
+ if (object !== undefined) {
1958
+ matches.push({ type: entry.type, id, object });
1959
+ }
1960
+ }
1961
+ if (matches.length > 1) {
1962
+ throw new ViewError(
1963
+ "ambiguous",
1964
+ `"${id}" is ambiguous: use ${matches.map((match) => `${match.type}:${id}`).sort().join(", ")}`,
1965
+ );
1966
+ }
1967
+ const only = matches[0];
1968
+ if (only !== undefined) return only;
1969
+
1970
+ // A plugin may scope a bare id to a namespace of its own (the dev plugin
1971
+ // scopes plans and tasks to a repository). A returned key is the answer
1972
+ // even when no object is stored there, so the lookup cannot fall through to
1973
+ // another namespace; the kernel's suffix lookup runs only when none claims
1974
+ // the id.
1975
+ if (!id.includes(":")) {
1976
+ const scoped = await this.resolveWithPlugins(id);
1977
+ if (scoped !== undefined) return scoped;
1978
+ }
1979
+
1980
+ // An object key may carry a namespace before a slash (a plugin's objects
1981
+ // can be scoped, such as one plan per repository). A bare id then still
1982
+ // names the object when exactly one key ends with `/<id>`.
1983
+ if (!id.includes("/")) {
1984
+ const suffixed: ResolvedObject[] = [];
1985
+ for (const entry of this.registry.objectTypes()) {
1986
+ let cursor: string | undefined;
1987
+ for (;;) {
1988
+ const page = await this.store.list(
1989
+ entry.type,
1990
+ cursor === undefined ? {} : { cursor },
1991
+ );
1992
+ for (const object of page.objects) {
1993
+ if (object.id === id || !object.id.endsWith(`/${id}`)) continue;
1994
+ suffixed.push({ type: entry.type, id: object.id, object });
1995
+ }
1996
+ if (page.next === undefined) break;
1997
+ cursor = page.next;
1998
+ }
1999
+ }
2000
+ if (suffixed.length > 1) {
2001
+ throw new ViewError(
2002
+ "ambiguous",
2003
+ `"${id}" is ambiguous: use ${suffixed
2004
+ .map((match) => `${match.type}:${match.id}`)
2005
+ .sort()
2006
+ .join(", ")}`,
2007
+ );
2008
+ }
2009
+ const scoped = suffixed[0];
2010
+ if (scoped !== undefined) return scoped;
2011
+ }
2012
+
2013
+ // A match in a declared type wins: types seen only in the facts (a type no
2014
+ // loaded plugin declares any more) are looked at last, through the store's
2015
+ // lookup by object id, when nothing else claimed the id.
2016
+ const undeclared: ResolvedObject[] = [];
2017
+ for (const type of this.store.objectTypesOf(id)) {
2018
+ undeclared.push({ type, id, object: await this.store.get(type, id) });
2019
+ }
2020
+ if (undeclared.length > 1) {
2021
+ throw new ViewError(
2022
+ "ambiguous",
2023
+ `"${id}" is ambiguous: use ${undeclared.map((match) => `${match.type}:${id}`).sort().join(", ")}`,
2024
+ );
2025
+ }
2026
+ const orphan = undeclared[0];
2027
+ if (orphan !== undefined) return orphan;
2028
+
2029
+ if (this.log !== undefined) {
2030
+ const found = (await this.log.runs({ object: id }))[0];
2031
+ const parsed = found === undefined ? undefined : splitId(found.object);
2032
+ if (parsed !== undefined) {
2033
+ const object = await this.store.get(parsed.type, parsed.id);
2034
+ return { type: parsed.type, id: parsed.id, object };
2035
+ }
2036
+ }
2037
+
2038
+ throw new ViewError("not-found", `no object "${id}"`);
2039
+ }
2040
+
2041
+ /**
2042
+ * Asks each object type's `resolve` hook for the key of a bare id. More than
2043
+ * one type claiming the id is ambiguous, and the typed form is the answer.
2044
+ */
2045
+ private async resolveWithPlugins(
2046
+ id: string,
2047
+ onlyType?: string,
2048
+ ): Promise<ResolvedObject | undefined> {
2049
+ const matches: ResolvedObject[] = [];
2050
+ for (const entry of this.registry.objectTypes()) {
2051
+ if (onlyType !== undefined && entry.type !== onlyType) continue;
2052
+ const resolve = entry.definition.resolve;
2053
+ if (resolve === undefined) continue;
2054
+ let key: unknown;
2055
+ try {
2056
+ key = await resolve(
2057
+ {
2058
+ cwd: this.cwd,
2059
+ store: this.store,
2060
+ ...(this.scope === undefined ? {} : { scope: this.scope }),
2061
+ },
2062
+ entry.type,
2063
+ id,
2064
+ );
2065
+ } catch (error) {
2066
+ // A plugin refuses with a ViewError when it knows why the id is wrong.
2067
+ if (error instanceof ViewError) throw error;
2068
+ this.onLog(
2069
+ `plugin "${entry.plugin}": resolve failed for "${entry.type}:${id}": ${messageOf(error)}`,
2070
+ );
2071
+ continue;
2072
+ }
2073
+ if (typeof key !== "string" || key.length === 0) continue;
2074
+ matches.push({
2075
+ type: entry.type,
2076
+ id: key,
2077
+ object: await this.store.get(entry.type, key),
2078
+ });
2079
+ }
2080
+ if (matches.length > 1) {
2081
+ throw new ViewError(
2082
+ "ambiguous",
2083
+ `"${id}" is ambiguous: use ${matches
2084
+ .map((match) => `${match.type}:${match.id}`)
2085
+ .sort()
2086
+ .join(", ")}`,
2087
+ );
2088
+ }
2089
+ return matches[0];
2090
+ }
2091
+
2092
+ private async hasRun(type: string, id: string): Promise<boolean> {
2093
+ if (this.log === undefined) return false;
2094
+ const runs = await this.log.runs({ object: objectKey(type, id) });
2095
+ return runs.length > 0;
2096
+ }
2097
+
2098
+ private guardedRow(
2099
+ plugin: string,
2100
+ type: string,
2101
+ object: StoredObject,
2102
+ ): ViewRow {
2103
+ const owner = this.registry.viewsFor(type);
2104
+ const views = owner?.views;
2105
+ if (views === undefined) {
2106
+ return this.errorRow(object.id, `no loaded plugin shows objects of type "${type}"`);
2107
+ }
2108
+
2109
+ // A row is synchronous, so the clock cannot tell its own time from time
2110
+ // the process lost to the machine: a process descheduled between the two
2111
+ // reads makes a fast row look slow. A row over the limit is measured once
2112
+ // more, and is an error only when both times are over.
2113
+ let outcome: unknown;
2114
+ let elapsed = 0;
2115
+ for (let attempt = 0; attempt < 2; attempt += 1) {
2116
+ const started = this.clock();
2117
+ try {
2118
+ outcome = views.row(object);
2119
+ } catch (error) {
2120
+ return this.failRow(plugin, object, error);
2121
+ }
2122
+ elapsed = this.clock() - started;
2123
+ if (elapsed <= this.rowTimeoutMs || isThenable(outcome)) break;
2124
+ }
2125
+
2126
+ if (isThenable(outcome)) {
2127
+ Promise.resolve(outcome).catch(() => undefined);
2128
+ return this.failRow(
2129
+ plugin,
2130
+ object,
2131
+ new Error("row returned a Promise; row must be synchronous"),
2132
+ );
2133
+ }
2134
+ if (elapsed > this.rowTimeoutMs) {
2135
+ return this.failRow(
2136
+ plugin,
2137
+ object,
2138
+ new Error(`row took ${elapsed}ms; the limit is ${this.rowTimeoutMs}ms`),
2139
+ );
2140
+ }
2141
+ if (!isRecord(outcome)) {
2142
+ return this.failRow(plugin, object, new Error("row returned no row"));
2143
+ }
2144
+ const id = textOf(outcome.id);
2145
+ const title = textOf(outcome.title);
2146
+ const state = textOf(outcome.state);
2147
+ if (id === undefined || title === undefined || state === undefined) {
2148
+ return this.failRow(
2149
+ plugin,
2150
+ object,
2151
+ new Error("row must return { id, title, state, note? }"),
2152
+ );
2153
+ }
2154
+ const note = textOf(outcome.note);
2155
+ const wait = textOf(outcome.wait);
2156
+ const scope = textOf(outcome.scope);
2157
+ let mark: RowMark | undefined;
2158
+ if (outcome.mark !== undefined) {
2159
+ const found = ROW_MARKS.find((allowed) => allowed === outcome.mark);
2160
+ if (found === undefined) {
2161
+ return this.failRow(
2162
+ plugin,
2163
+ object,
2164
+ new Error(
2165
+ `row mark ${JSON.stringify(outcome.mark)} is not allowed; the marks are ${ROW_MARKS.join(", ")}`,
2166
+ ),
2167
+ );
2168
+ }
2169
+ mark = found;
2170
+ }
2171
+ const badge = outcome.badge;
2172
+ if (badge !== undefined) {
2173
+ if (
2174
+ typeof badge !== "string" ||
2175
+ /[\r\n]/.test(badge) ||
2176
+ Array.from(badge).length > ROW_BADGE_MAX
2177
+ ) {
2178
+ return this.failRow(
2179
+ plugin,
2180
+ object,
2181
+ new Error(
2182
+ `row badge must be a single line of at most ${ROW_BADGE_MAX} characters`,
2183
+ ),
2184
+ );
2185
+ }
2186
+ }
2187
+ const parent = outcome.parent;
2188
+ if (parent !== undefined && (typeof parent !== "string" || parent.length === 0)) {
2189
+ return this.failRow(
2190
+ plugin,
2191
+ object,
2192
+ new Error("row parent must be a non-empty object id"),
2193
+ );
2194
+ }
2195
+ const after = outcome.after;
2196
+ if (
2197
+ after !== undefined &&
2198
+ (!Array.isArray(after) ||
2199
+ Array.from(after).some((entry) => typeof entry !== "string" || entry.length === 0))
2200
+ ) {
2201
+ return this.failRow(
2202
+ plugin,
2203
+ object,
2204
+ new Error("row after must be an array of non-empty object ids"),
2205
+ );
2206
+ }
2207
+ return {
2208
+ id,
2209
+ title,
2210
+ state,
2211
+ ...(note === undefined ? {} : { note }),
2212
+ ...(wait === undefined ? {} : { wait }),
2213
+ ...(typeof parent === "string" ? { parent } : {}),
2214
+ ...(Array.isArray(after) ? { after: Array.from(after) } : {}),
2215
+ ...(scope === undefined ? {} : { scope }),
2216
+ ...(outcome.final === true ? { final: true } : {}),
2217
+ ...(mark === undefined ? {} : { mark }),
2218
+ ...(typeof badge === "string" ? { badge } : {}),
2219
+ waiting: outcome.waiting === true,
2220
+ running: false,
2221
+ };
2222
+ }
2223
+
2224
+ private failRow(
2225
+ plugin: string,
2226
+ object: StoredObject,
2227
+ error: unknown,
2228
+ ): ViewRow {
2229
+ const message = messageOf(error);
2230
+ this.onLog(
2231
+ `plugin "${plugin}": row failed for "${object.type}:${object.id}": ${message}`,
2232
+ );
2233
+ return this.errorRow(object.id, message);
2234
+ }
2235
+
2236
+ private errorRow(id: string, message: string): ViewRow {
2237
+ return {
2238
+ id,
2239
+ title: id,
2240
+ state: "error",
2241
+ note: message,
2242
+ waiting: false,
2243
+ running: false,
2244
+ error: message,
2245
+ };
2246
+ }
2247
+
2248
+ private sectionDirectory(
2249
+ plugin: string,
2250
+ object: StoredObject,
2251
+ ): ViewSectionInfo[] {
2252
+ const views = this.registry.viewsFor(object.type)?.views;
2253
+ if (views === undefined) return [];
2254
+ const raw = views.sections(object);
2255
+ if (!Array.isArray(raw)) {
2256
+ throw new Error("sections must return an array");
2257
+ }
2258
+ const sections: ViewSectionInfo[] = [];
2259
+ for (const entry of raw) {
2260
+ if (!isRecord(entry)) {
2261
+ throw new Error("each section must be { id, title, live? }");
2262
+ }
2263
+ const id = textOf(entry.id);
2264
+ const title = textOf(entry.title);
2265
+ if (id === undefined || title === undefined) {
2266
+ throw new Error("each section must be { id, title, live? }");
2267
+ }
2268
+ if (id === HISTORY_SECTION) {
2269
+ this.onLog(
2270
+ `plugin "${plugin}": section "${HISTORY_SECTION}" is reserved; the kernel serves it`,
2271
+ );
2272
+ continue;
2273
+ }
2274
+ const live = entry.live;
2275
+ if (live !== undefined && typeof live !== "boolean") {
2276
+ throw new Error("section.live must be a boolean");
2277
+ }
2278
+ sections.push({ id, title, ...(live === true ? { live } : {}) });
2279
+ }
2280
+ return sections;
2281
+ }
2282
+
2283
+ private viewContext(plugin: string, signal: AbortSignal): ViewContext {
2284
+ const log = this.log;
2285
+ // One read of the log's runs serves every run this view asks about.
2286
+ let runs: ReturnType<LogBackend["runs"]> | undefined;
2287
+ return {
2288
+ plugin,
2289
+ home: this.registry.home,
2290
+ cwd: this.cwd,
2291
+ store: this.store,
2292
+ facts: this.factsFor(`view:${plugin}`),
2293
+ logger: createPluginLogger(this.store.root, plugin, "views"),
2294
+ signal,
2295
+ settings: this.registry.settingsFor(plugin),
2296
+ settingsInForce: (name: string) => this.settingsInForce(name),
2297
+ refreshedObject: (type: string, id: string) =>
2298
+ this.refreshedObject(type, id),
2299
+ secrets: new FileSecretStore({ home: this.registry.home, plugin }),
2300
+ ...(log === undefined
2301
+ ? {}
2302
+ : {
2303
+ runTimes: (runId: string) => {
2304
+ runs ??= log.runs();
2305
+ return runTimes(log, runId, runs);
2306
+ },
2307
+ }),
2308
+ };
2309
+ }
2310
+
2311
+ private factsFor(cause: string): FactWriter {
2312
+ return {
2313
+ append: (input) =>
2314
+ this.store.append({ ...input, cause: input.cause ?? cause }),
2315
+ };
2316
+ }
2317
+
2318
+ private async flagsFor(type: string, id: string): Promise<RunFlags> {
2319
+ const flags = await this.allRunFlags();
2320
+ return flags.get(objectKey(type, id)) ?? { waiting: false, running: false };
2321
+ }
2322
+
2323
+ private async allRunFlags(): Promise<Map<string, RunFlags>> {
2324
+ const flags = new Map<string, RunFlags>();
2325
+ if (this.log === undefined) return flags;
2326
+ const runs = await this.log.runs({ active: true });
2327
+ for (const run of runs) {
2328
+ const parsed = splitId(run.object);
2329
+ if (parsed === undefined) continue;
2330
+ let state;
2331
+ try {
2332
+ state = await readState(this.log, run.runId);
2333
+ } catch (error) {
2334
+ this.onLog(`run "${run.runId}": could not read its state: ${messageOf(error)}`);
2335
+ continue;
2336
+ }
2337
+ if (state.status === "ended") continue;
2338
+ const key = objectKey(parsed.type, parsed.id);
2339
+ const previous = flags.get(key) ?? { waiting: false, running: false };
2340
+ flags.set(key, {
2341
+ waiting: previous.waiting || state.status === "waiting_person",
2342
+ running:
2343
+ previous.running || state.status !== "waiting_person",
2344
+ });
2345
+ }
2346
+ return flags;
2347
+ }
2348
+
2349
+ private async waitingRunId(
2350
+ type: string,
2351
+ id: string,
2352
+ ): Promise<string | undefined> {
2353
+ if (this.log === undefined) return undefined;
2354
+ const runs = await this.log.runs({ active: true });
2355
+ for (const run of runs) {
2356
+ if (run.object !== objectKey(type, id)) continue;
2357
+ try {
2358
+ const state = await readState(this.log, run.runId);
2359
+ if (state.status === "waiting_person") return run.runId;
2360
+ } catch {
2361
+ continue;
2362
+ }
2363
+ }
2364
+ return undefined;
2365
+ }
2366
+
2367
+ private async historyMarkdown(
2368
+ type: string,
2369
+ id: string,
2370
+ full: boolean,
2371
+ ): Promise<string> {
2372
+ const actions = this.personActions(type, id);
2373
+ const runs =
2374
+ this.log === undefined
2375
+ ? []
2376
+ : (await this.log.runs({ object: objectKey(type, id) }))
2377
+ .sort((left, right) => left.startedAt - right.startedAt);
2378
+ if (runs.length === 0 && actions.length === 0) return "No history yet.\n";
2379
+
2380
+ const lines: string[] = [];
2381
+ if (actions.length > 0) {
2382
+ lines.push("## Person actions");
2383
+ for (const action of actions) lines.push(`- ${action}`);
2384
+ lines.push("");
2385
+ }
2386
+ for (const run of runs) {
2387
+ if (this.log === undefined) break;
2388
+ lines.push(`## ${run.flow} run · started ${localMinute(run.startedAt)}`);
2389
+ try {
2390
+ const facts: HistoryFact[] = [];
2391
+ for await (const fact of this.log.read(run.runId)) facts.push(fact);
2392
+ for (const line of runHistoryLines(facts, { now: this.clock(), full })) {
2393
+ lines.push(line.startsWith("**") ? line : `- ${line}`);
2394
+ }
2395
+ } catch (error) {
2396
+ lines.push(`- could not read this run: ${messageOf(error)}`);
2397
+ }
2398
+ lines.push("");
2399
+ }
2400
+ return `${lines.join("\n").trimEnd()}\n`;
2401
+ }
2402
+
2403
+ /** Every fact of one object, oldest first. */
2404
+ private objectFacts(type: string, id: string): readonly PluginFact[] {
2405
+ const facts: PluginFact[] = [];
2406
+ let cursor: string | undefined;
2407
+ for (;;) {
2408
+ const page = this.store.facts(
2409
+ { type, id },
2410
+ cursor === undefined ? {} : { cursor },
2411
+ );
2412
+ facts.push(...page.facts);
2413
+ if (page.next === undefined) return facts;
2414
+ cursor = page.next;
2415
+ }
2416
+ }
2417
+
2418
+ /** The actions a person ran on an object, one line each, with who ran it. */
2419
+ private personActions(type: string, id: string): readonly string[] {
2420
+ const lines: string[] = [];
2421
+ for (const fact of this.objectFacts(type, id)) {
2422
+ if (fact.type !== ACTION_FACT) continue;
2423
+ lines.push(describeFact(fact));
2424
+ }
2425
+ return lines;
2426
+ }
2427
+
2428
+ /**
2429
+ * What happened to an object in its own words: the actions people ran on it
2430
+ * and each change, oldest first. An object that never had a run still has
2431
+ * these.
2432
+ */
2433
+ async objectHistory(id: string): Promise<readonly string[]> {
2434
+ const resolved = await this.resolve(id);
2435
+ return this.objectFacts(resolved.type, resolved.id).map(describeFact);
2436
+ }
2437
+
2438
+ /** The objects that changed most recently, newest first. */
2439
+ async recent(limit: number): Promise<readonly RecentObject[]> {
2440
+ const found: { readonly at: number; readonly entry: RecentObject }[] = [];
2441
+ for (const entry of this.registry.objectTypes()) {
2442
+ const owner = this.registry.viewsFor(entry.type);
2443
+ if (owner === undefined) continue;
2444
+ for (const object of await this.allObjects(entry.type)) {
2445
+ const row = this.guardedRow(owner.plugin, entry.type, object);
2446
+ found.push({
2447
+ at: object.at,
2448
+ entry: {
2449
+ type: entry.type,
2450
+ id: row.id,
2451
+ state: row.state,
2452
+ title: row.title,
2453
+ },
2454
+ });
2455
+ }
2456
+ }
2457
+ found.sort((left, right) => right.at - left.at);
2458
+ return found.slice(0, limit).map((item) => item.entry);
2459
+ }
2460
+
2461
+ /** The ids nearest to a name that matched nothing, nearest first. */
2462
+ async closest(id: string, limit: number): Promise<readonly RecentObject[]> {
2463
+ const wanted = (id.includes(":") ? id.slice(id.indexOf(":") + 1) : id)
2464
+ .toLowerCase();
2465
+ const scored: { readonly score: number; readonly entry: RecentObject }[] = [];
2466
+ for (const entry of this.registry.objectTypes()) {
2467
+ const owner = this.registry.viewsFor(entry.type);
2468
+ if (owner === undefined) continue;
2469
+ for (const object of await this.allObjects(entry.type)) {
2470
+ const row = this.guardedRow(owner.plugin, entry.type, object);
2471
+ const candidate = row.id.toLowerCase();
2472
+ const near = candidate.includes(wanted) || wanted.includes(candidate);
2473
+ scored.push({
2474
+ score: near ? 0 : editDistance(wanted, candidate),
2475
+ entry: {
2476
+ type: entry.type,
2477
+ id: row.id,
2478
+ state: row.state,
2479
+ title: row.title,
2480
+ },
2481
+ });
2482
+ }
2483
+ }
2484
+ scored.sort(
2485
+ (left, right) =>
2486
+ left.score - right.score || left.entry.id.localeCompare(right.entry.id),
2487
+ );
2488
+ return scored.slice(0, limit).map((item) => item.entry);
2489
+ }
2490
+
2491
+ private async allObjects(type: string): Promise<readonly StoredObject[]> {
2492
+ const objects: StoredObject[] = [];
2493
+ let cursor: string | undefined;
2494
+ for (;;) {
2495
+ const page = await this.store.list(
2496
+ type,
2497
+ cursor === undefined ? {} : { cursor },
2498
+ );
2499
+ objects.push(...page.objects);
2500
+ if (page.next === undefined) return objects;
2501
+ cursor = page.next;
2502
+ }
2503
+ }
2504
+
2505
+ /** The line an action refusal prints: the plugin's reason, or a plain one. */
2506
+ private async refusal(
2507
+ target: { readonly action: ActionTypeDefinition; readonly info: ActionInfo },
2508
+ object: StoredObject,
2509
+ subject: string,
2510
+ ): Promise<string> {
2511
+ try {
2512
+ const why = await target.action.why?.(object, this.registry.actionEnv());
2513
+ if (why !== undefined && why.length > 0) return why;
2514
+ } catch (error) {
2515
+ this.onLog(`action "${target.info.name}": why failed: ${messageOf(error)}`);
2516
+ }
2517
+ return `${subject} cannot ${target.info.name} now`;
2518
+ }
2519
+
2520
+ private async scopeShown(
2521
+ plugin: string,
2522
+ type: string,
2523
+ views: ObjectViews,
2524
+ ): Promise<boolean> {
2525
+ if (views.showScope === undefined) return false;
2526
+ try {
2527
+ const ctx = this.viewContext(plugin, new AbortController().signal);
2528
+ return (await views.showScope(ctx)) === true;
2529
+ } catch (error) {
2530
+ this.onLog(
2531
+ `plugin "${plugin}": showScope failed for "${type}": ${messageOf(error)}`,
2532
+ );
2533
+ return false;
2534
+ }
2535
+ }
2536
+
2537
+ /**
2538
+ * Announces an object. A run's growth can arrive far faster than a client
2539
+ * can read it, so growth is announced at most once per object per window;
2540
+ * the last growth in a window is announced when the window ends. An object's
2541
+ * own stored change is always announced.
2542
+ */
2543
+ private publish(id: string, growth = false): void {
2544
+ if (growth) {
2545
+ const now = this.clock();
2546
+ const last = this.growthAnnouncedAt.get(id);
2547
+ if (last !== undefined && now - last < GROWTH_EVENT_INTERVAL_MS) {
2548
+ this.growthPending.add(id);
2549
+ this.scheduleGrowth(id, GROWTH_EVENT_INTERVAL_MS - (now - last));
2550
+ return;
2551
+ }
2552
+ this.growthPending.delete(id);
2553
+ this.clearGrowthTimer(id);
2554
+ this.growthAnnouncedAt.set(id, now);
2555
+ }
2556
+ this.announce(id);
2557
+ }
2558
+
2559
+ private announce(id: string): void {
2560
+ for (const listener of this.eventListeners) listener(id);
2561
+ }
2562
+
2563
+ /** Announces a held-back growth once its window has passed, or waits again. */
2564
+ private flushGrowth(id: string): void {
2565
+ if (!this.growthPending.has(id)) return;
2566
+ const now = this.clock();
2567
+ const last = this.growthAnnouncedAt.get(id);
2568
+ if (last !== undefined && now - last < GROWTH_EVENT_INTERVAL_MS) {
2569
+ this.scheduleGrowth(id, GROWTH_EVENT_INTERVAL_MS - (now - last));
2570
+ return;
2571
+ }
2572
+ this.growthPending.delete(id);
2573
+ this.clearGrowthTimer(id);
2574
+ this.growthAnnouncedAt.set(id, now);
2575
+ this.announce(id);
2576
+ }
2577
+
2578
+ /** Announces every held-back growth whose window has passed by the clock. */
2579
+ private flushDueGrowth(): void {
2580
+ for (const id of [...this.growthPending]) {
2581
+ const last = this.growthAnnouncedAt.get(id);
2582
+ if (last === undefined || this.clock() - last >= GROWTH_EVENT_INTERVAL_MS) {
2583
+ this.flushGrowth(id);
2584
+ }
2585
+ }
2586
+ }
2587
+
2588
+ /** The one timer per object that wakes a reader when its window ends. */
2589
+ private scheduleGrowth(id: string, waitMs: number): void {
2590
+ if (this.growthTimers.has(id)) return;
2591
+ const timer = setTimeout(() => {
2592
+ this.growthTimers.delete(id);
2593
+ this.flushGrowth(id);
2594
+ }, Math.max(0, waitMs));
2595
+ this.growthTimers.set(id, timer);
2596
+ }
2597
+
2598
+ private clearGrowthTimer(id: string): void {
2599
+ const timer = this.growthTimers.get(id);
2600
+ if (timer === undefined) return;
2601
+ clearTimeout(timer);
2602
+ this.growthTimers.delete(id);
2603
+ }
2604
+ }
2605
+
2606
+ /** Builds the presentation API for a registry and its store. */
2607
+ export function createViews(options: ViewsOptions): Views {
2608
+ return new Views(options);
2609
+ }