@nanocollective/roster 0.1.0-alpha.9 → 0.1.0-beta.10

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 (151) hide show
  1. package/README.md +6 -0
  2. package/dist/cli.js +4189 -1971
  3. package/dist/worker/assets/assets/css/base.css +327 -0
  4. package/dist/worker/assets/assets/css/brain.css +116 -0
  5. package/dist/worker/assets/assets/css/diff.css +33 -0
  6. package/dist/worker/assets/assets/css/graph.css +39 -0
  7. package/dist/worker/assets/assets/css/health.css +75 -0
  8. package/dist/worker/assets/assets/css/home.css +114 -0
  9. package/dist/worker/assets/assets/css/inbox.css +199 -0
  10. package/dist/worker/assets/assets/css/layout.css +181 -0
  11. package/dist/worker/assets/assets/css/markdown.css +96 -0
  12. package/dist/worker/assets/assets/css/runs.css +13 -0
  13. package/dist/worker/assets/assets/css/search.css +48 -0
  14. package/dist/worker/assets/assets/css/setup.css +194 -0
  15. package/dist/worker/assets/assets/js/api.js +191 -0
  16. package/dist/worker/assets/assets/js/app.js +500 -0
  17. package/dist/worker/assets/assets/js/dialog.js +196 -0
  18. package/dist/worker/assets/assets/js/dom.js +131 -0
  19. package/dist/worker/assets/assets/js/homesort.js +174 -0
  20. package/dist/worker/assets/assets/js/icons.js +142 -0
  21. package/dist/worker/assets/assets/js/inflight.js +18 -0
  22. package/dist/worker/assets/assets/js/lightbox.js +273 -0
  23. package/dist/worker/assets/assets/js/md.js +406 -0
  24. package/dist/worker/assets/assets/js/mdedit.js +84 -0
  25. package/dist/worker/assets/assets/js/mention.js +264 -0
  26. package/dist/worker/assets/assets/js/readiness.js +70 -0
  27. package/dist/worker/assets/assets/js/refresh.js +197 -0
  28. package/dist/worker/assets/assets/js/router.js +20 -0
  29. package/dist/worker/assets/assets/js/search.js +366 -0
  30. package/dist/worker/assets/assets/js/state.js +213 -0
  31. package/dist/worker/assets/assets/js/textdiff.js +96 -0
  32. package/dist/worker/assets/assets/js/views/app.js +145 -0
  33. package/dist/worker/assets/assets/js/views/brain.js +260 -0
  34. package/dist/worker/assets/assets/js/views/changed.js +157 -0
  35. package/dist/worker/assets/assets/js/views/checklist.js +115 -0
  36. package/dist/worker/assets/assets/js/views/credential.js +84 -0
  37. package/dist/worker/assets/assets/js/views/docs.js +174 -0
  38. package/dist/worker/assets/assets/js/views/files.js +139 -0
  39. package/dist/worker/assets/assets/js/views/graph.js +436 -0
  40. package/dist/worker/assets/assets/js/views/health.js +304 -0
  41. package/dist/worker/assets/assets/js/views/hire.js +593 -0
  42. package/dist/worker/assets/assets/js/views/home.js +621 -0
  43. package/dist/worker/assets/assets/js/views/inbox.js +1558 -0
  44. package/dist/worker/assets/assets/js/views/memory.js +150 -0
  45. package/dist/worker/assets/assets/js/views/org.js +195 -0
  46. package/dist/worker/assets/assets/js/views/orgedit.js +240 -0
  47. package/dist/worker/assets/assets/js/views/paste.js +216 -0
  48. package/dist/worker/assets/assets/js/views/prompt.js +457 -0
  49. package/dist/worker/assets/assets/js/views/repos.js +97 -0
  50. package/dist/worker/assets/assets/js/views/runonce.js +94 -0
  51. package/dist/worker/assets/assets/js/views/runs.js +182 -0
  52. package/dist/worker/assets/assets/js/views/setup.js +557 -0
  53. package/dist/worker/assets/assets/js/views/staff.js +291 -0
  54. package/dist/worker/assets/assets/js/views/todo.js +62 -0
  55. package/dist/worker/assets/assets/js/yaml.js +134 -0
  56. package/dist/worker/assets/docs-images/brain.jpg +0 -0
  57. package/dist/worker/assets/docs-images/home.jpg +0 -0
  58. package/dist/worker/assets/docs-images/org.jpg +0 -0
  59. package/dist/worker/assets/docs-images/prompt.jpg +0 -0
  60. package/dist/worker/assets/docs-images/setup-org.jpg +0 -0
  61. package/dist/worker/assets/docs-images/setup-plan.jpg +0 -0
  62. package/dist/worker/assets/docs-images/staff.jpg +0 -0
  63. package/dist/worker/assets/index.html +82 -0
  64. package/dist/worker/index.js +5143 -0
  65. package/docs/README.md +2 -2
  66. package/docs/architecture.md +23 -4
  67. package/docs/charters/analyst.md +65 -0
  68. package/docs/charters/community.md +63 -0
  69. package/docs/charters/designer.md +65 -0
  70. package/docs/charters/devops.md +65 -0
  71. package/docs/charters/pm.md +70 -0
  72. package/docs/charters/qa.md +65 -0
  73. package/docs/charters/writer.md +63 -0
  74. package/docs/commands.md +36 -9
  75. package/docs/concepts.md +34 -21
  76. package/docs/cost.md +3 -3
  77. package/docs/developing.md +28 -10
  78. package/docs/doctor-codes.md +3 -1
  79. package/docs/export.md +2 -0
  80. package/docs/getting-started.md +49 -29
  81. package/docs/hosting.md +114 -43
  82. package/docs/images/brain.jpg +0 -0
  83. package/docs/images/home.jpg +0 -0
  84. package/docs/images/org.jpg +0 -0
  85. package/docs/images/prompt.jpg +0 -0
  86. package/docs/images/staff.jpg +0 -0
  87. package/docs/manual-steps.md +3 -2
  88. package/docs/memory.md +2 -1
  89. package/docs/org-yaml.md +3 -0
  90. package/docs/portal.md +144 -45
  91. package/docs/prompts.md +6 -0
  92. package/docs/security.md +70 -11
  93. package/docs/session-workflow.md +24 -6
  94. package/docs/staff-yaml.md +21 -2
  95. package/docs/upgrading.md +3 -3
  96. package/docs/writing-a-charter.md +19 -6
  97. package/package.json +4 -3
  98. package/templates/brain/.github/workflows/%%STAFF%%-daily.yaml +20 -1
  99. package/templates/brain/.github/workflows/%%STAFF%%-mention.yaml +53 -13
  100. package/templates/brain/CHARTER.md +2 -2
  101. package/templates/brain/STATE.md +16 -0
  102. package/templates/brain/memory/INDEX.md +1 -1
  103. package/templates/brain/staff.yaml +4 -1
  104. package/templates/briefs/amend.md +4 -3
  105. package/templates/briefs/priorities.md +46 -0
  106. package/templates/ops/.github/workflows/session.yaml +150 -3
  107. package/templates/ops/compose.mjs +35 -8
  108. package/templates/ops/org/operating.md +29 -10
  109. package/templates/ops/org/voice.md +2 -1
  110. package/templates/ops/prompts/daily.md +51 -14
  111. package/templates/ops/prompts/mention.md +24 -2
  112. package/templates/ops/run-record.mjs +5 -3
  113. package/templates/ops/status-week.mjs +169 -0
  114. package/templates/portal/css/base.css +49 -0
  115. package/templates/portal/css/health.css +14 -1
  116. package/templates/portal/css/home.css +114 -0
  117. package/templates/portal/css/inbox.css +21 -4
  118. package/templates/portal/css/layout.css +35 -3
  119. package/templates/portal/css/markdown.css +19 -0
  120. package/templates/portal/css/search.css +48 -0
  121. package/templates/portal/css/setup.css +79 -4
  122. package/templates/portal/index.html +15 -9
  123. package/templates/portal/js/api.js +60 -4
  124. package/templates/portal/js/app.js +125 -7
  125. package/templates/portal/js/dialog.js +36 -0
  126. package/templates/portal/js/homesort.js +174 -0
  127. package/templates/portal/js/icons.js +41 -0
  128. package/templates/portal/js/inflight.js +18 -0
  129. package/templates/portal/js/md.js +5 -2
  130. package/templates/portal/js/mdedit.js +84 -0
  131. package/templates/portal/js/readiness.js +70 -0
  132. package/templates/portal/js/refresh.js +10 -2
  133. package/templates/portal/js/search.js +366 -0
  134. package/templates/portal/js/state.js +11 -5
  135. package/templates/portal/js/views/app.js +1 -2
  136. package/templates/portal/js/views/brain.js +1 -1
  137. package/templates/portal/js/views/checklist.js +19 -4
  138. package/templates/portal/js/views/credential.js +42 -51
  139. package/templates/portal/js/views/health.js +11 -6
  140. package/templates/portal/js/views/hire.js +593 -0
  141. package/templates/portal/js/views/home.js +621 -0
  142. package/templates/portal/js/views/inbox.js +237 -68
  143. package/templates/portal/js/views/org.js +31 -111
  144. package/templates/portal/js/views/orgedit.js +240 -0
  145. package/templates/portal/js/views/paste.js +111 -66
  146. package/templates/portal/js/views/prompt.js +94 -40
  147. package/templates/portal/js/views/repos.js +10 -10
  148. package/templates/portal/js/views/runs.js +21 -4
  149. package/templates/portal/js/views/setup.js +130 -163
  150. package/templates/portal/js/views/staff.js +181 -301
  151. package/templates/portal/js/views/todo.js +62 -0
@@ -0,0 +1,366 @@
1
+ /* Search everything: ⌘K, or the search field in the sidebar.
2
+ *
3
+ * One dialog over the whole portal: issues and pull requests, staff, every fact and file in
4
+ * every brain, the org files, the docs, runs, and the screens themselves. All of it except the
5
+ * docs is already in the page, so it is searched here as you type; the docs are searched on the
6
+ * server, which reads every page rather than only titles.
7
+ *
8
+ * `index()` and `rank()` are plain functions over plain data, so what is found, and in which
9
+ * order, can be tested without a page. */
10
+
11
+ import { getOrgLayer, getRuns, searchDocs } from "./api.js";
12
+ import { ago, el } from "./dom.js";
13
+ import { icon, staffIcon } from "./icons.js";
14
+ import { ensureInbox } from "./refresh.js";
15
+ import { go } from "./router.js";
16
+ import { S } from "./state.js";
17
+ import { openThread } from "./views/home.js";
18
+
19
+ /** The groups, in the order they are shown. */
20
+ const GROUPS = ["Screens", "Staff", "Issues", "Pull requests", "Memory", "Files", "Org", "Runs", "Docs"];
21
+ /** How many of each a query shows; an empty query shows only screens and staff. */
22
+ const PER_GROUP = 5;
23
+
24
+ const SCREENS = [
25
+ ["home", "Home", "What needs you, and who is working"],
26
+ ["inbox", "Trackers", "Every open issue on each tracker"],
27
+ ["runs", "Runs", "What ran, and what it cost"],
28
+ ["org", "Org", "The files every staff member reads"],
29
+ ["staff", "Staff", "Hire, set up, retire"],
30
+ ["docs", "Docs", "How roster works"],
31
+ ];
32
+ const STAFF_SCREENS = [
33
+ ["brain", "Brain"],
34
+ ["prompt", "Prompt"],
35
+ ["graph", "Graph"],
36
+ ["changed", "What changed"],
37
+ ["health", "Health"],
38
+ ];
39
+
40
+ /**
41
+ * Every searchable thing, as `{ group, title, sub, text, icon, open }`. `text` is what is
42
+ * matched beyond the title; `open` is what choosing it does.
43
+ */
44
+ export function index(state) {
45
+ const out = [];
46
+ const staff = state.data?.staff ?? [];
47
+
48
+ for (const [view, title, sub] of SCREENS) {
49
+ out.push({ group: "Screens", title, sub, text: view, icon: "square", open: () => go({ view }) });
50
+ }
51
+ for (const s of staff) {
52
+ for (const [view, label] of STAFF_SCREENS) {
53
+ out.push({
54
+ group: "Screens",
55
+ title: `${s.name} · ${label}`,
56
+ sub: s.handle,
57
+ text: `${s.handle} ${label}`,
58
+ icon: staffIcon(s),
59
+ open: () => go({ view, staffHandle: s.handle }),
60
+ });
61
+ }
62
+ }
63
+
64
+ for (const s of staff) {
65
+ out.push({
66
+ group: "Staff",
67
+ title: s.name,
68
+ sub: [s.handle, s.brain].filter(Boolean).join(" · "),
69
+ text: `${s.handle} ${s.brain ?? ""} ${s.mention ?? ""}`,
70
+ icon: staffIcon(s),
71
+ open: () => go({ view: "brain", staffHandle: s.handle, openFile: "mem:*", fileQuery: "" }),
72
+ });
73
+
74
+ for (const f of s.facts ?? []) {
75
+ out.push({
76
+ group: "Memory",
77
+ title: f.statement,
78
+ sub: `${s.name} · ${f.section} · ${f.slug}`,
79
+ text: `${f.slug} ${f.consequence ?? ""} ${f.section}`,
80
+ icon: "lightbulb",
81
+ open: () =>
82
+ go({ view: "brain", staffHandle: s.handle, openFile: "fact:" + f.slug, fileQuery: "" }),
83
+ });
84
+ }
85
+
86
+ for (const surface of s.surfaces ?? []) {
87
+ for (const file of surface.files ?? []) {
88
+ const note = /(^|\/)notes\//.test(file.path);
89
+ out.push({
90
+ group: note ? "Memory" : "Files",
91
+ title: file.path.split("/").pop(),
92
+ sub: `${s.name} · ${file.path}`,
93
+ text: file.path,
94
+ icon: "file",
95
+ open: () => go({ view: "brain", staffHandle: s.handle, openFile: file.path, fileQuery: "" }),
96
+ });
97
+ }
98
+ }
99
+ }
100
+
101
+ const brains = new Map(staff.filter((s) => s.brain).map((s) => [s.brain, s]));
102
+ for (const item of state.inbox?.items ?? []) {
103
+ const owner = brains.get(item.repo);
104
+ const repo = item.repo.split("/")[1] ?? item.repo;
105
+ const where = owner ? owner.name : repo;
106
+ const open = item.state === "OPEN";
107
+ out.push({
108
+ group: item.kind === "pr" ? "Pull requests" : "Issues",
109
+ title: item.title,
110
+ sub: `${where} · #${item.number} · ${open ? "open" : item.state.toLowerCase()} · ${ago(item.updatedAt)}`,
111
+ text: `#${item.number} ${repo}#${item.number} ${(item.labels ?? []).join(" ")} ${item.author}`,
112
+ icon: item.kind === "pr" ? (item.state === "MERGED" ? "merged" : "review") : open ? "issue-open" : "issue-closed",
113
+ // Open work first among equal matches: it is usually what is being looked for.
114
+ weight: open ? 1 : 0,
115
+ open: () => openThread(item),
116
+ });
117
+ }
118
+
119
+ for (const f of state.orgFiles ?? []) {
120
+ out.push({
121
+ group: "Org",
122
+ title: f.path.split("/").pop(),
123
+ sub: f.path,
124
+ text: f.path,
125
+ icon: "file",
126
+ open: () => go({ view: "org", orgOpen: f.path }),
127
+ });
128
+ }
129
+
130
+ for (const s of state.runs?.staff ?? []) {
131
+ for (const r of s.runs ?? []) {
132
+ const word = r.record?.outcome ?? r.conclusion ?? r.status;
133
+ out.push({
134
+ group: "Runs",
135
+ title: `${s.name} · ${r.kind} run · ${word}`,
136
+ sub: `${ago(r.createdAt)} · opens the log on GitHub`,
137
+ text: `${s.handle} ${r.kind} ${word} ${r.id}`,
138
+ icon: "play",
139
+ open: () => window.open(r.url, "_blank", "noopener"),
140
+ });
141
+ }
142
+ }
143
+
144
+ return out;
145
+ }
146
+
147
+ /**
148
+ * The best matches for a query, grouped. Every word has to appear somewhere; a match in the
149
+ * title outranks one elsewhere, and the start of the title outranks the middle of it.
150
+ */
151
+ export function rank(entries, query) {
152
+ const words = String(query ?? "").toLowerCase().split(/\s+/).filter(Boolean);
153
+ const groups = new Map(GROUPS.map((g) => [g, []]));
154
+ if (!words.length) {
155
+ for (const e of entries) {
156
+ if (e.group === "Screens" || e.group === "Staff") groups.get(e.group).push({ e, score: 0 });
157
+ }
158
+ } else {
159
+ for (const e of entries) {
160
+ const title = e.title.toLowerCase();
161
+ const all = `${title} ${String(e.sub ?? "").toLowerCase()} ${String(e.text ?? "").toLowerCase()}`;
162
+ if (!words.every((w) => all.includes(w))) continue;
163
+ let score = e.weight ?? 0;
164
+ for (const w of words) {
165
+ if (title.startsWith(w)) score += 6;
166
+ else if (new RegExp(`\\b${w.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}`).test(title)) score += 4;
167
+ else if (title.includes(w)) score += 2;
168
+ }
169
+ groups.get(e.group)?.push({ e, score });
170
+ }
171
+ }
172
+ const out = [];
173
+ for (const [group, list] of groups) {
174
+ if (!list.length) continue;
175
+ list.sort((a, b) => b.score - a.score);
176
+ const shown = list.slice(0, words.length ? PER_GROUP : 40);
177
+ out.push({ group, entries: shown.map((x) => x.e), more: list.length - shown.length });
178
+ }
179
+ return out;
180
+ }
181
+
182
+ /* --------------------------------- the dialog --------------------------------- */
183
+
184
+ let current = null;
185
+
186
+ /** Open the search dialog, or focus it when it is already open. */
187
+ export function openSearch() {
188
+ if (current) {
189
+ current.input.focus();
190
+ return;
191
+ }
192
+ const box = document.createElement("dialog");
193
+ if (typeof box.showModal !== "function") return;
194
+ box.className = "palette";
195
+
196
+ const input = el("input", {
197
+ type: "search",
198
+ className: "palinput",
199
+ placeholder: "Search issues, pull requests, memory, files, runs and docs",
200
+ autocomplete: "off",
201
+ spellcheck: false,
202
+ });
203
+ const results = el("div", { className: "palresults", role: "listbox" });
204
+ const foot = el("div", { className: "palfoot" }, [
205
+ el("span", { innerHTML: "<kbd>↑</kbd><kbd>↓</kbd> move" }),
206
+ el("span", { innerHTML: "<kbd>↵</kbd> open" }),
207
+ el("span", { innerHTML: "<kbd>esc</kbd> close" }),
208
+ ]);
209
+ box.append(el("div", { className: "palhead" }, [icon("search", "ic"), input]), results, foot);
210
+ document.body.append(box);
211
+ box.showModal();
212
+ input.focus();
213
+
214
+ let entries = index(S);
215
+ let flat = [];
216
+ let at = 0;
217
+ let docs = [];
218
+ let docsFor = "";
219
+ let docTimer = null;
220
+
221
+ const close = () => {
222
+ if (!current) return;
223
+ current = null;
224
+ clearTimeout(docTimer);
225
+ box.close();
226
+ box.remove();
227
+ };
228
+ current = { input, close };
229
+ box.addEventListener("close", () => {
230
+ current = null;
231
+ box.remove();
232
+ });
233
+ box.addEventListener("click", (e) => {
234
+ if (e.target === box) close();
235
+ });
236
+
237
+ const choose = (e) => {
238
+ close();
239
+ e.open();
240
+ };
241
+
242
+ const paint = () => {
243
+ const q = input.value.trim();
244
+ const grouped = rank(entries, q);
245
+ if (q && docsFor === q && docs.length) {
246
+ grouped.push({
247
+ group: "Docs",
248
+ entries: docs.slice(0, PER_GROUP).map((h) => ({
249
+ title: h.title,
250
+ sub: h.matches?.[0]?.text ?? h.file,
251
+ icon: "book-open",
252
+ open: () => go({ view: "docs", openDoc: h.file, docQuery: q }),
253
+ })),
254
+ more: Math.max(0, docs.length - PER_GROUP),
255
+ });
256
+ }
257
+ flat = grouped.flatMap((g) => g.entries);
258
+ at = Math.min(at, Math.max(0, flat.length - 1));
259
+ results.replaceChildren();
260
+ if (!flat.length) {
261
+ results.append(el("p", { className: "palempty", textContent: q ? "Nothing matches “" + q + "”." : "" }));
262
+ return;
263
+ }
264
+ let i = 0;
265
+ for (const g of grouped) {
266
+ results.append(
267
+ el("div", { className: "palgroup", textContent: g.group + (g.more ? ` · ${g.more} more` : "") }),
268
+ );
269
+ for (const e of g.entries) {
270
+ const n = i++;
271
+ const row = el("button", { className: "palrow", role: "option" }, [
272
+ icon(e.icon ?? "file", "ic"),
273
+ el("span", { className: "paltext" }, [
274
+ el("span", { className: "paltitle", innerHTML: highlight(e.title, q) }),
275
+ el("span", { className: "palsub", textContent: e.sub ?? "" }),
276
+ ]),
277
+ ]);
278
+ row.setAttribute("aria-selected", String(n === at));
279
+ row.onmouseenter = () => {
280
+ at = n;
281
+ mark();
282
+ };
283
+ row.onclick = () => choose(e);
284
+ results.append(row);
285
+ }
286
+ }
287
+ mark();
288
+ };
289
+
290
+ const mark = () => {
291
+ const rows = results.querySelectorAll(".palrow");
292
+ rows.forEach((r, n) => r.setAttribute("aria-selected", String(n === at)));
293
+ rows[at]?.scrollIntoView({ block: "nearest" });
294
+ };
295
+
296
+ input.addEventListener("input", () => {
297
+ at = 0;
298
+ paint();
299
+ const q = input.value.trim();
300
+ clearTimeout(docTimer);
301
+ if (q.length < 2) return;
302
+ docTimer = setTimeout(() => {
303
+ searchDocs(q)
304
+ .then((r) => {
305
+ docs = r.hits ?? [];
306
+ docsFor = q;
307
+ if (current && input.value.trim() === q) paint();
308
+ })
309
+ .catch(() => {});
310
+ }, 150);
311
+ });
312
+ input.addEventListener("keydown", (e) => {
313
+ if (e.key === "ArrowDown") {
314
+ e.preventDefault();
315
+ at = Math.min(at + 1, flat.length - 1);
316
+ mark();
317
+ } else if (e.key === "ArrowUp") {
318
+ e.preventDefault();
319
+ at = Math.max(at - 1, 0);
320
+ mark();
321
+ } else if (e.key === "Enter") {
322
+ e.preventDefault();
323
+ if (flat[at]) choose(flat[at]);
324
+ }
325
+ });
326
+
327
+ paint();
328
+
329
+ /* What is not in the page yet is fetched once and folded in as it lands: the issues, the org
330
+ files and the runs. The dialog is usable straight away with whatever is already here. */
331
+ const refill = () => {
332
+ if (!current) return;
333
+ entries = index(S);
334
+ paint();
335
+ };
336
+ if (!S.inbox) ensureInbox(false).then(refill).catch(() => {});
337
+ if (!S.orgFiles) {
338
+ getOrgLayer()
339
+ .then((r) => {
340
+ S.orgFiles = r.files ?? [];
341
+ refill();
342
+ })
343
+ .catch(() => {});
344
+ }
345
+ if (!S.runs) {
346
+ getRuns(false)
347
+ .then((r) => {
348
+ S.runs = r;
349
+ refill();
350
+ })
351
+ .catch(() => {});
352
+ }
353
+ }
354
+
355
+ /** The title with each query word marked, escaped first. */
356
+ function highlight(title, q) {
357
+ let html = String(title ?? "")
358
+ .replace(/&/g, "&amp;")
359
+ .replace(/</g, "&lt;")
360
+ .replace(/>/g, "&gt;");
361
+ for (const w of String(q ?? "").toLowerCase().split(/\s+/).filter((x) => x.length > 1)) {
362
+ const re = new RegExp(`(${w.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")})`, "ig");
363
+ html = html.replace(re, "<mark>$1</mark>");
364
+ }
365
+ return html;
366
+ }
@@ -0,0 +1,213 @@
1
+ /* Every screen's state in one object, and the URL that mirrors it.
2
+ *
3
+ * The URL is the state, so a refresh lands where you were and a link is shareable. Changing
4
+ * staff or view pushes; typing in a filter replaces, so a search does not bury the back
5
+ * button under one entry per keystroke.
6
+ *
7
+ * This used to be a wall of top-level `var`s in a classic script, kept as `var` on purpose
8
+ * because a top-level `let` is not reachable as a global and the state was otherwise
9
+ * untestable. As a module it is exported, so it is neither global nor hidden. */
10
+
11
+ export const VIEWS = [
12
+ ["brain", "Brain"],
13
+ ["prompt", "Prompt"],
14
+ ["graph", "Graph"],
15
+ ["changed", "What changed"],
16
+ ["health", "Health"],
17
+ ];
18
+
19
+ /* Memory used to be its own view. It is a surface of the brain — both manifests already
20
+ declare `memory/` with `render: memory` — so it is now the brain's first stop, and the
21
+ old links still land somewhere sensible. */
22
+ export const VIEW_ALIAS = { memory: "brain" };
23
+
24
+ /** Screens that belong to the org rather than to one staff member. */
25
+ export const ORG_WIDE = new Set(["setup", "home", "inbox", "prs", "runs", "org", "staff", "docs"]);
26
+
27
+ /** The two screens that read the inbox, and so share its filters and its `?t=` thread. */
28
+ const INBOXY = new Set(["inbox", "prs"]);
29
+
30
+ export const S = {
31
+ /** The org export from /api/org. Everything the brain screens read comes off this. */
32
+ data: null,
33
+ /** `{login}` on a hosted portal, null on your own machine. Hosted has no setup, hire or doctor. */
34
+ hosted: null,
35
+ docs: null,
36
+ inbox: null,
37
+ /** /api/runs. Kept once read: it is minutes of downloads on a cold cache. */
38
+ runs: null,
39
+ sync: null,
40
+ loadedAt: null,
41
+ /** The role whose hire list is open on the Staff screen, kept across a refresh. */
42
+ staffOpen: null,
43
+ /** Per staff member, what is left before they can run. See readiness.js. */
44
+ readiness: null,
45
+
46
+ staffHandle: null,
47
+ /* What is waiting on you, not whose brain you read last. The org-wide screens are where a
48
+ session starts, which is also why the Staff list below them opens folded. */
49
+ view: "home",
50
+ /** The inbox filter box. Brain and "what changed" keep their own, below. */
51
+ query: "",
52
+
53
+ /* What the brain's right pane is showing: a file path, or one of the memory pseudo-paths
54
+ `mem:*`, `mem:<section>`, `fact:<slug>`. One key, so the URL carries either. */
55
+ openFile: null,
56
+ fileQuery: "",
57
+ /** Which surfaces are unfolded in the brain navigator. Not in the URL: it is furniture. */
58
+ openSurfaces: null,
59
+
60
+ changedQuery: "",
61
+ changedFilter: "",
62
+
63
+ openDoc: null,
64
+ /** The docs search box. Its own field: the Docs screen keeps it while you read a page. */
65
+ docQuery: "",
66
+
67
+ /** Which kind of run the Prompt screen is showing, and which layer of it is open. */
68
+ promptKind: "daily",
69
+ promptOpen: null,
70
+
71
+ /** Which org-layer file the Org screen is showing, and what it found on disk. */
72
+ orgOpen: null,
73
+ orgFiles: [],
74
+
75
+ inboxFilter: "",
76
+ inboxStaff: "",
77
+ /** "" is open only, which is what an inbox is for. `closed` and `all` widen it. */
78
+ inboxState: "",
79
+ inboxOpen: null,
80
+
81
+ applyingHash: false,
82
+ };
83
+
84
+ /* The sidebar badge counts open items, not everything loaded. Once the inbox could show
85
+ closed work the two stopped being the same number, and a badge that says 135 when 34 things
86
+ need you is worse than no badge. Pull requests are excluded for the same reason: they are
87
+ Pending work's, and counting them here would bill you twice for the same pile. */
88
+ export const openCount = () =>
89
+ (S.inbox?.items ?? []).filter((i) => i.state === "OPEN" && i.kind !== "pr").length;
90
+
91
+ /** Issues with activity you have not read, from GitHub's notifications. */
92
+ export const unreadCount = () =>
93
+ (S.inbox?.items ?? []).filter((i) => i.unread && i.state === "OPEN" && i.kind !== "pr").length;
94
+
95
+ export const staff = () => S.data.staff.find((s) => s.handle === S.staffHandle) ?? S.data.staff[0];
96
+
97
+ /**
98
+ * Everyone the staff answer to.
99
+ *
100
+ * An org can have more than one. `humans` is the list the export sends now; `human` is what a
101
+ * portal whose server predates the list sends, and falling back to it is what keeps the page
102
+ * working across the upgrade rather than showing an org with nobody in it.
103
+ */
104
+ export const humansOf = () =>
105
+ S.data?.humans?.length ? S.data.humans : S.data?.human?.github ? [S.data.human] : [];
106
+
107
+ /** Whether a login is one of them. Assignment to any of them is assignment to "us". */
108
+ export const isHuman = (login) =>
109
+ !!login &&
110
+ humansOf().some((h) => String(h.github ?? "").toLowerCase() === String(login).toLowerCase());
111
+
112
+ /** What to call them collectively, for a filter label or a count. */
113
+ export const humanLabel = () => {
114
+ const humans = humansOf();
115
+ if (!humans.length) return "you";
116
+ if (humans.length === 1) return humans[0].name ?? humans[0].github ?? "you";
117
+ return humans.map((h) => h.name ?? h.github).join(" or ");
118
+ };
119
+
120
+ export function readHash() {
121
+ const raw = (location.hash || "").replace(/^#\/?/, "");
122
+ if (!raw) return null;
123
+ const [path, qs] = raw.split("?");
124
+ const [handle, view] = path.split("/");
125
+ const p = new URLSearchParams(qs || "");
126
+ return {
127
+ handle,
128
+ view,
129
+ q: p.get("q") || "",
130
+ f: p.get("f") || null,
131
+ k: p.get("k") || "",
132
+ x: p.get("x") || "",
133
+ s: p.get("s") || "",
134
+ w: p.get("w") || "",
135
+ t: p.get("t") || null,
136
+ p: p.get("p") || null,
137
+ };
138
+ }
139
+
140
+ export function writeHash(push) {
141
+ if (S.applyingHash) return;
142
+ if (!S.staffHandle && !ORG_WIDE.has(S.view)) return;
143
+ const params = new URLSearchParams();
144
+ const q =
145
+ S.view === "brain"
146
+ ? S.fileQuery
147
+ : S.view === "changed"
148
+ ? S.changedQuery
149
+ : S.view === "docs"
150
+ ? S.docQuery
151
+ : S.query;
152
+ if (q) params.set("q", q);
153
+ if (S.view === "brain" && S.openFile) params.set("f", S.openFile);
154
+ if (S.view === "docs" && S.openDoc) params.set("p", S.openDoc);
155
+ if (S.view === "org" && S.orgOpen) params.set("f", S.orgOpen);
156
+ if (S.view === "prompt") {
157
+ if (S.promptKind !== "daily") params.set("k", S.promptKind);
158
+ if (S.promptOpen) params.set("f", S.promptOpen);
159
+ }
160
+ if (INBOXY.has(S.view)) {
161
+ if (S.inboxFilter) params.set("s", S.inboxFilter);
162
+ if (S.inboxStaff) params.set("w", S.inboxStaff);
163
+ if (S.inboxState) params.set("x", S.inboxState);
164
+ if (S.inboxOpen) {
165
+ params.set("t", S.inboxOpen.repo + "#" + S.inboxOpen.number + ":" + S.inboxOpen.kind);
166
+ }
167
+ }
168
+ const qs = params.toString();
169
+ const next = "#/" + (S.staffHandle ?? "-") + "/" + S.view + (qs ? "?" + qs : "");
170
+ if (location.hash === next) return;
171
+ if (history.pushState) history[push ? "pushState" : "replaceState"](null, "", next);
172
+ else location.hash = next;
173
+ }
174
+
175
+ export function applyHash() {
176
+ const h = readHash();
177
+ if (!h) return false;
178
+ const known = S.data.staff.some((s) => s.handle === h.handle);
179
+ if (known) S.staffHandle = h.handle;
180
+ const asked = VIEW_ALIAS[h.view] ?? h.view;
181
+ if (ORG_WIDE.has(asked) || VIEWS.some(([id]) => id === asked)) S.view = asked;
182
+
183
+ if (S.view === "brain") {
184
+ S.fileQuery = h.q;
185
+ S.openFile = h.f;
186
+ } else if (S.view === "changed") {
187
+ S.changedQuery = h.q;
188
+ } else if (S.view === "docs") {
189
+ S.docQuery = h.q;
190
+ } else {
191
+ S.query = h.q;
192
+ }
193
+
194
+ if (S.view === "docs") S.openDoc = h.p;
195
+ if (S.view === "org") S.orgOpen = h.f;
196
+
197
+ if (S.view === "prompt") {
198
+ S.promptKind = h.k || "daily";
199
+ S.promptOpen = h.f;
200
+ }
201
+
202
+ if (INBOXY.has(S.view)) {
203
+ S.inboxFilter = h.s;
204
+ S.inboxStaff = h.w;
205
+ S.inboxState = h.x;
206
+ if (h.t) {
207
+ const [repoNum, kind] = h.t.split(":");
208
+ const [repo, number] = repoNum.split("#");
209
+ S.inboxOpen = { repo, number: Number(number), kind: kind === "pr" ? "pr" : "issue" };
210
+ }
211
+ }
212
+ return known;
213
+ }
@@ -0,0 +1,96 @@
1
+ /* A unified diff between two strings, in the format `renderDiff` already parses.
2
+ *
3
+ * Editing a layer changes a file, but what you meant to change is the composed prompt, and
4
+ * those are not the same thing: a line added to one fragment can land three times or not at
5
+ * all. Showing the file diff would answer a question nobody asked.
6
+ *
7
+ * There is no git here, so the diff is computed in the page. Plain LCS: these are a few
8
+ * hundred lines of prose, and anything cleverer would be solving a problem this does not have.
9
+ */
10
+
11
+ export function unifiedDiff(before, after, name, context = 3) {
12
+ const a = String(before).split("\n");
13
+ const b = String(after).split("\n");
14
+ const ops = lcsOps(a, b);
15
+ if (!ops.some((o) => o.op !== " ")) return "";
16
+
17
+ /* Only the neighbourhood of a change is worth printing. A whole 400-line prompt with six
18
+ lines highlighted is not a diff, it is the prompt again. */
19
+ const keep = new Set();
20
+ ops.forEach((o, i) => {
21
+ if (o.op === " ") return;
22
+ for (let j = Math.max(0, i - context); j <= Math.min(ops.length - 1, i + context); j++) {
23
+ keep.add(j);
24
+ }
25
+ });
26
+
27
+ const out = ["diff --git a/" + name + " b/" + name];
28
+ let i = 0;
29
+ let oldNo = 1;
30
+ let newNo = 1;
31
+ // Walk once, emitting a hunk each time the kept region starts again.
32
+ const lineNos = ops.map((o) => {
33
+ const at = { old: oldNo, new: newNo };
34
+ if (o.op !== "+") oldNo++;
35
+ if (o.op !== "-") newNo++;
36
+ return at;
37
+ });
38
+
39
+ while (i < ops.length) {
40
+ if (!keep.has(i)) {
41
+ i++;
42
+ continue;
43
+ }
44
+ let end = i;
45
+ while (end + 1 < ops.length && keep.has(end + 1)) end++;
46
+ const rows = ops.slice(i, end + 1);
47
+ const oldCount = rows.filter((o) => o.op !== "+").length;
48
+ const newCount = rows.filter((o) => o.op !== "-").length;
49
+ out.push(`@@ -${lineNos[i].old},${oldCount} +${lineNos[i].new},${newCount} @@`);
50
+ for (const row of rows) out.push(row.op + row.text);
51
+ i = end + 1;
52
+ }
53
+ return out.join("\n");
54
+ }
55
+
56
+ /** Longest common subsequence, as a flat list of ` `, `-` and `+` rows. */
57
+ function lcsOps(a, b) {
58
+ const n = a.length;
59
+ const m = b.length;
60
+ const grid = new Uint32Array((n + 1) * (m + 1));
61
+ const at = (i, j) => i * (m + 1) + j;
62
+ for (let i = n - 1; i >= 0; i--) {
63
+ for (let j = m - 1; j >= 0; j--) {
64
+ grid[at(i, j)] =
65
+ a[i] === b[j]
66
+ ? grid[at(i + 1, j + 1)] + 1
67
+ : Math.max(grid[at(i + 1, j)], grid[at(i, j + 1)]);
68
+ }
69
+ }
70
+ const ops = [];
71
+ let i = 0;
72
+ let j = 0;
73
+ while (i < n && j < m) {
74
+ if (a[i] === b[j]) {
75
+ ops.push({ op: " ", text: a[i] });
76
+ i++;
77
+ j++;
78
+ } else if (grid[at(i + 1, j)] >= grid[at(i, j + 1)]) {
79
+ ops.push({ op: "-", text: a[i++] });
80
+ } else {
81
+ ops.push({ op: "+", text: b[j++] });
82
+ }
83
+ }
84
+ while (i < n) ops.push({ op: "-", text: a[i++] });
85
+ while (j < m) ops.push({ op: "+", text: b[j++] });
86
+ return ops;
87
+ }
88
+
89
+ /** How much moved, for a one-line summary beside the commit. */
90
+ export function diffStat(before, after) {
91
+ const ops = lcsOps(String(before).split("\n"), String(after).split("\n"));
92
+ return {
93
+ added: ops.filter((o) => o.op === "+").length,
94
+ removed: ops.filter((o) => o.op === "-").length,
95
+ };
96
+ }