tryharness 0.7.53 → 0.7.54

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 (69) hide show
  1. package/README.md +10 -5
  2. package/assets/dsh-plugin.mjs +72 -0
  3. package/assets/opencode-plugin.js +4 -3
  4. package/cli.mjs +115 -36
  5. package/lib/adapters.mjs +157 -222
  6. package/lib/agentRuntimes.mjs +26 -16
  7. package/lib/agentSignIn.mjs +226 -0
  8. package/lib/audit.mjs +643 -0
  9. package/lib/backupSetup.mjs +141 -0
  10. package/lib/boardAccess.mjs +8 -1
  11. package/lib/boardBackup.mjs +283 -0
  12. package/lib/boardMirror.mjs +71 -7
  13. package/lib/boardProtocol.json +59 -2
  14. package/lib/boardWaits.mjs +102 -0
  15. package/lib/book.mjs +659 -0
  16. package/lib/bridge.mjs +1 -1
  17. package/lib/cards.mjs +138 -28
  18. package/lib/cloudBoot.mjs +124 -0
  19. package/lib/commands.mjs +7 -2
  20. package/lib/context.mjs +18 -4
  21. package/lib/contractGate.mjs +377 -0
  22. package/lib/coordinator.mjs +149 -43
  23. package/lib/daemon.mjs +349 -28
  24. package/lib/desk.mjs +239 -0
  25. package/lib/desktop.mjs +106 -6
  26. package/lib/environments.mjs +237 -7
  27. package/lib/folders.mjs +2 -2
  28. package/lib/gitHost.mjs +174 -0
  29. package/lib/hookDialects.mjs +298 -0
  30. package/lib/landed.mjs +887 -0
  31. package/lib/live.mjs +284 -13
  32. package/lib/mcp-stdio.mjs +68 -2
  33. package/lib/members.json +16 -2
  34. package/lib/models.mjs +8 -8
  35. package/lib/museSession.mjs +16 -13
  36. package/lib/nativeHost.mjs +1 -1
  37. package/lib/neovim.mjs +126 -0
  38. package/lib/nudge.mjs +47 -16
  39. package/lib/ownMachines.mjs +343 -39
  40. package/lib/pairing.mjs +27 -10
  41. package/lib/paths.mjs +4 -0
  42. package/lib/personModel.mjs +89 -0
  43. package/lib/phones.mjs +66 -11
  44. package/lib/places.mjs +330 -10
  45. package/lib/readiness.mjs +135 -18
  46. package/lib/record.mjs +115 -0
  47. package/lib/runWorker.mjs +17 -2
  48. package/lib/runner.mjs +8 -4
  49. package/lib/sessionControl.mjs +377 -89
  50. package/lib/specialties.json +74 -0
  51. package/lib/specialties.mjs +477 -0
  52. package/lib/specialtyKeys.d.ts +3 -0
  53. package/lib/specialtyKeys.js +58 -0
  54. package/lib/specialtyNotice.mjs +147 -0
  55. package/lib/specialtySnapshot.mjs +138 -0
  56. package/lib/store.mjs +284 -1
  57. package/lib/swarm.mjs +137 -21
  58. package/lib/t3.mjs +13 -4
  59. package/lib/taskCommands.mjs +36 -9
  60. package/lib/taskRuns.mjs +9 -2
  61. package/lib/team.json +255 -148
  62. package/lib/team.mjs +529 -188
  63. package/lib/threadLine.mjs +116 -0
  64. package/lib/threadRuns.mjs +75 -11
  65. package/lib/threadView.mjs +15 -2
  66. package/lib/worktrees.mjs +51 -13
  67. package/package.json +4 -4
  68. package/lib/modelTiers.json +0 -1183
  69. package/lib/modelTiers.mjs +0 -133
package/lib/landed.mjs ADDED
@@ -0,0 +1,887 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { spawn } from "node:child_process";
4
+ import { paths } from "./paths.mjs";
5
+ import { LIVE_AGENTS } from "./live.mjs";
6
+ import { nameOf } from "./members.mjs";
7
+ import {
8
+ EDITOR_IDS,
9
+ editorInstall,
10
+ editorName,
11
+ t3App,
12
+ t3CommitCommands,
13
+ t3Link,
14
+ t3Thread,
15
+ } from "./places.mjs";
16
+ import {
17
+ changesPage,
18
+ commitPage,
19
+ comparePage,
20
+ createGithub,
21
+ remoteWeb,
22
+ } from "./gitHost.mjs";
23
+
24
+ // What a thread's work, or a repository's, put into the world: pull requests that landed, ones in review, and changes
25
+ // still only on this computer. Pushed work opens on its git host; work that is not out yet opens in the app the agent
26
+ // that made it is used in most (sessionControl homeOf), in that app's own diff view. Harness draws no diff of its own.
27
+
28
+ const WEEK_MS = 7 * 24 * 60 * 60_000;
29
+ // An editor gets one diff tab per file: past this many, the rest are a note rather than a wall of tabs.
30
+ const DIFF_FILES = 12;
31
+ const PULL_LINK = /https:\/\/[^\s/]+\/[^\s]+?\/(?:pull|-\/merge_requests)\/\d+/;
32
+ // A repository's view asks git of every checkout of it (on the owner's Mac, 37 T3 Code checkouts of ~/harness at about
33
+ // ten calls of 25-50 ms each): never all at once, and never holding the daemon while git runs.
34
+ const AT_ONCE = 6;
35
+ // The buddy reads a repository's view every 30 s while it shows; one read serves the moments around it.
36
+ const FOLDER_FRESH_MS = 15_000;
37
+ // Which repository a folder is in, and that repository's host, change rarely.
38
+ const ROOT_FRESH_MS = 10 * 60_000;
39
+
40
+ /** Git's answer without holding the daemon's event loop. `raw` keeps the output as bytes (a file's content). */
41
+ function git(cwd, args, { raw = false } = {}) {
42
+ return new Promise((resolve) => {
43
+ const child = spawn("git", args, {
44
+ cwd,
45
+ stdio: ["ignore", "pipe", "ignore"],
46
+ });
47
+ const chunks = [];
48
+ child.stdout.on("data", (chunk) => chunks.push(chunk));
49
+ child.on("error", () => resolve({ ok: false, out: "", bytes: null }));
50
+ child.on("close", (code) => {
51
+ const bytes = Buffer.concat(chunks);
52
+ resolve({
53
+ ok: code === 0,
54
+ out: raw ? "" : bytes.toString("utf8").trim(),
55
+ bytes: raw ? bytes : null,
56
+ });
57
+ });
58
+ });
59
+ }
60
+
61
+ /** `work` over `items`, a few at a time, answers in the items' order. */
62
+ async function fewAtOnce(items, work) {
63
+ const answers = new Array(items.length);
64
+ let next = 0;
65
+ const worker = async () => {
66
+ while (next < items.length) {
67
+ const index = next++;
68
+ answers[index] = await work(items[index]);
69
+ }
70
+ };
71
+ await Promise.all(
72
+ Array.from({ length: Math.min(AT_ONCE, items.length) }, worker)
73
+ );
74
+ return answers;
75
+ }
76
+
77
+ const kept = (map, key, fetch) => {
78
+ const entry = map.get(key);
79
+ if (entry && Date.now() - entry.at < ROOT_FRESH_MS) return entry.value;
80
+ const value = fetch();
81
+ map.set(key, { at: Date.now(), value });
82
+ return value;
83
+ };
84
+ const roots = new Map();
85
+ const hosts = new Map();
86
+
87
+ /** The repository a folder is in, as the person's own checkout (a thread's or T3's worktree stands for it). */
88
+ const repositoryRoot = (folder) =>
89
+ !folder || !fs.existsSync(folder)
90
+ ? Promise.resolve(null)
91
+ : kept(roots, folder, async () => {
92
+ const found = await git(folder, [
93
+ "rev-parse",
94
+ "--path-format=absolute",
95
+ "--show-toplevel",
96
+ "--git-common-dir",
97
+ ]);
98
+ const [top, common] = found.ok ? found.out.split("\n") : [];
99
+ if (!top) return null;
100
+ const root =
101
+ common && path.basename(common) === ".git"
102
+ ? path.dirname(common)
103
+ : top;
104
+ try {
105
+ return fs.realpathSync(root);
106
+ } catch {
107
+ return null;
108
+ }
109
+ });
110
+
111
+ /** The repository's host, from `origin` (else its first remote); null when it has none with a web page. */
112
+ const hostOf = (root) =>
113
+ kept(hosts, root, async () => {
114
+ const remotes = (await git(root, ["remote"])).out
115
+ .split("\n")
116
+ .filter(Boolean);
117
+ const name = remotes.includes("origin") ? "origin" : remotes[0];
118
+ if (!name) return null;
119
+ const web = remoteWeb((await git(root, ["remote", "get-url", name])).out);
120
+ return web ? { ...web, remote: name } : null;
121
+ });
122
+
123
+ /** The branch work goes into on the host: the remote's HEAD, else main. */
124
+ const intoBranch = async (root, remote) =>
125
+ (
126
+ await git(root, ["symbolic-ref", "--short", `refs/remotes/${remote}/HEAD`])
127
+ ).out.replace(`${remote}/`, "") || "main";
128
+
129
+ /** Whether `commit` is already on the remote's copy of `branch`: pushed. */
130
+ const pushed = async (root, remote, branch, commit) =>
131
+ Boolean(branch && commit) &&
132
+ (
133
+ await git(root, [
134
+ "merge-base",
135
+ "--is-ancestor",
136
+ commit,
137
+ `refs/remotes/${remote}/${branch}`,
138
+ ])
139
+ ).ok;
140
+
141
+ /** Only what is not on the host yet: the commit the host's copy of the branch is at, when it holds part of it. */
142
+ async function pushedPart(tree, host) {
143
+ if (!host || !tree.branch) return null;
144
+ const ref = `refs/remotes/${host.remote}/${tree.branch}`;
145
+ return (await git(tree.path, ["merge-base", "--is-ancestor", ref, "HEAD"])).ok
146
+ ? (await git(tree.path, ["rev-parse", ref])).out
147
+ : null;
148
+ }
149
+
150
+ /**
151
+ * Where a T3 Code checkout's branch left the work it goes into: the host's copy of that branch, else the local one
152
+ * (a repository made here and pushed has no record of the host's HEAD), else what the person has checked out.
153
+ */
154
+ async function forkPoint(tree, host) {
155
+ const into = host ? await intoBranch(tree.path, host.remote) : null;
156
+ const checkedOut = (
157
+ await git(tree.repo ?? tree.path, ["rev-parse", "--abbrev-ref", "HEAD"])
158
+ ).out;
159
+ const refs = [
160
+ host ? `${host.remote}/${into}` : null,
161
+ into,
162
+ checkedOut,
163
+ ].filter((ref) => ref && ref !== "HEAD" && ref !== tree.branch);
164
+ for (const ref of refs) {
165
+ const base = (await git(tree.path, ["merge-base", "HEAD", ref])).out;
166
+ if (base) return base;
167
+ }
168
+ return null;
169
+ }
170
+
171
+ // A repository's commits since a day, and where each stands, read once for every thread a view asks about (one read
172
+ // per commit was most of the 16.7 s ~/harness took with 305 commits this week).
173
+ const histories = new Map();
174
+ const HISTORY_FRESH_MS = 15_000;
175
+ const DAY_MS = 24 * 60 * 60_000;
176
+
177
+ /** Commits in `ref`'s history since `since`, as a set of their ids. */
178
+ const idsIn = async (root, since, ref) =>
179
+ new Set(
180
+ (await git(root, ["rev-list", `--since=${since}`, ...ref])).out
181
+ .split("\n")
182
+ .filter(Boolean)
183
+ );
184
+
185
+ /**
186
+ * The repository's commits on any branch since the start of the day `from` falls in, with the ones on the host's main
187
+ * line, on the person's own main line, and on any branch pushed to the host.
188
+ */
189
+ function historyOf(root, host, from) {
190
+ const day = new Date(Math.floor(from / DAY_MS) * DAY_MS).toISOString();
191
+ const key = `${root}\0${day}`;
192
+ const entry = histories.get(key);
193
+ if (entry && Date.now() - entry.at < HISTORY_FRESH_MS) return entry.value;
194
+ const value = (async () => {
195
+ const into = host
196
+ ? await intoBranch(root, host.remote)
197
+ : (await git(root, ["rev-parse", "--abbrev-ref", "HEAD"])).out;
198
+ const [log, onHost, onMain, pushed] = await Promise.all([
199
+ git(root, [
200
+ "log",
201
+ "--branches",
202
+ "--remotes",
203
+ `--since=${day}`,
204
+ "--format=%H%x09%ct%x09%s",
205
+ ]),
206
+ host
207
+ ? idsIn(root, day, [`refs/remotes/${host.remote}/${into}`])
208
+ : new Set(),
209
+ into && into !== "HEAD"
210
+ ? idsIn(root, day, [`refs/heads/${into}`])
211
+ : new Set(),
212
+ host ? idsIn(root, day, ["--remotes"]) : new Set(),
213
+ ]);
214
+ const commits = log.out
215
+ .split("\n")
216
+ .filter(Boolean)
217
+ .map((line) => {
218
+ const [sha, seconds, subject] = line.split("\t");
219
+ return {
220
+ sha,
221
+ at: new Date(Number(seconds) * 1000).toISOString(),
222
+ subject: subject ?? "",
223
+ };
224
+ });
225
+ return { commits, onHost, onMain, pushed };
226
+ })();
227
+ histories.set(key, { at: Date.now(), value });
228
+ return value;
229
+ }
230
+
231
+ // A subject this short could be anyone's ("fix tests"): such a commit is the thread's only when git's own report of
232
+ // making it is in the thread.
233
+ const SUBJECT_MIN = 16;
234
+
235
+ /**
236
+ * The commits a thread working in the project itself made: those whose own report ("[main 5bb9b09f] ...") is in one of
237
+ * its commit commands, or whose subject it typed in one. Read from what it ran, so another session's commits to the
238
+ * same branch are never its.
239
+ */
240
+ async function commitsMade(context, root, host, floor = null) {
241
+ const commands = await t3CommitCommands(context.t3Thread);
242
+ if (!commands.length) return null;
243
+ const reported = new Set();
244
+ for (const command of commands)
245
+ for (const found of String(command.output || "").matchAll(
246
+ /^\[[^\]\n]*? ([0-9a-f]{7,40})\]/gm
247
+ ))
248
+ reported.add(found[1]);
249
+ const typed = commands.map((command) => String(command.input || ""));
250
+ const began = Date.parse(context.createdAt || "") || Date.now() - WEEK_MS;
251
+ // An hour before the thread began: a clock between git and T3 a little apart never loses its first commit. A view
252
+ // that only shows a week reads no further back than that.
253
+ const from = Math.max(began - 60 * 60_000, floor ?? 0);
254
+ const history = await historyOf(root, host, from);
255
+ const made = history.commits.filter(
256
+ (commit) =>
257
+ Date.parse(commit.at) >= from &&
258
+ ([...reported].some((sha) => commit.sha.startsWith(sha)) ||
259
+ (commit.subject.length >= SUBJECT_MIN &&
260
+ typed.some((input) => input.includes(commit.subject))))
261
+ );
262
+ return { made, history };
263
+ }
264
+
265
+ /** The pull request numbers a thread's posts link to on its repository's host. */
266
+ function requestsNamed(posts, host) {
267
+ if (!host) return [];
268
+ const prefix = `${host.web}/${host.kind === "gitlab" ? "-/merge_requests" : "pull"}/`;
269
+ const numbers = new Set();
270
+ for (const post of posts)
271
+ for (const word of String(post.text || "").split(/[\s()<>"'`[\]]+/))
272
+ if (word.startsWith(prefix)) {
273
+ const number = Number.parseInt(word.slice(prefix.length), 10);
274
+ if (number > 0) numbers.add(number);
275
+ }
276
+ return [...numbers];
277
+ }
278
+
279
+ /** A turn's commit subject as a title: worktrees commit each turn as "<agent>: <what it was asked>". */
280
+ function titleOf(subject) {
281
+ const colon = subject.indexOf(": ");
282
+ const agent = colon > 0 ? subject.slice(0, colon) : "";
283
+ const asked = LIVE_AGENTS.includes(agent)
284
+ ? subject.slice(colon + 2)
285
+ : subject;
286
+ return asked ? asked[0].toUpperCase() + asked.slice(1) : asked;
287
+ }
288
+
289
+ /** What the person last asked the thread for (by `at`, when given), as a title: the words after any @names. */
290
+ function askedFor(posts, at = null) {
291
+ const asked = posts.findLast(
292
+ (post) =>
293
+ post.author === "user" &&
294
+ // A commit's time is in whole seconds: a message sent in that same second came before it.
295
+ (!at || Date.parse(post.created_at) < Date.parse(at) + 1000)
296
+ );
297
+ const words = String(asked?.text || "")
298
+ .split("\n")[0]
299
+ .replace(/^(\s*@[\w./-]+[,:]?)+\s*/, "")
300
+ .trim();
301
+ if (!words) return null;
302
+ const title = words.length > 90 ? `${words.slice(0, 89)}…` : words;
303
+ return title[0].toUpperCase() + title.slice(1);
304
+ }
305
+
306
+ /** An editor's everyday name: Visual Studio Code is VS Code. */
307
+ const editorLabel = (name) =>
308
+ String(name)
309
+ .replace(/ \(.*\)$/, "")
310
+ .replace(/^Visual Studio Code/, "VS Code");
311
+
312
+ /** The coding agent whose work a thread's changes are: the one that ran in it last. */
313
+ function maker(runs) {
314
+ const run = [...runs]
315
+ .reverse()
316
+ .find((entry) => LIVE_AGENTS.includes(entry.target_agent));
317
+ return run?.target_agent ?? null;
318
+ }
319
+
320
+ /**
321
+ * What a thread's copy holds that is not out yet, or what it merged here: the git range that shows it and where.
322
+ * `to` null is the files as they are now (T3 Code's checkout keeps uncommitted changes).
323
+ */
324
+ async function localWork({ thread, tree, posts, title }, host) {
325
+ if (!tree) return null;
326
+ if (tree.state === "open" && tree.path && fs.existsSync(tree.path)) {
327
+ const [newest] = (
328
+ await git(tree.path, [
329
+ "log",
330
+ "--format=%H%x09%ct%x09%s",
331
+ `${tree.base}..HEAD`,
332
+ ])
333
+ ).out.split("\n");
334
+ if (!newest) return null;
335
+ const [tip, seconds, subject] = newest.split("\t");
336
+ const at = new Date(Number(seconds) * 1000).toISOString();
337
+ return {
338
+ tip,
339
+ at,
340
+ title: askedFor(posts, at) || titleOf(subject) || title,
341
+ sides: {
342
+ cwd: tree.path,
343
+ from: (await pushedPart(tree, host)) || tree.base,
344
+ to: null,
345
+ folder: tree.path,
346
+ },
347
+ out: host
348
+ ? await pushed(tree.repo, host.remote, tree.branch, tip)
349
+ : false,
350
+ };
351
+ }
352
+ if (tree.state === "t3" && tree.path && fs.existsSync(tree.path)) {
353
+ const [base, dirty] = await Promise.all([
354
+ forkPoint(tree, host),
355
+ git(tree.path, ["status", "--porcelain"]).then((found) => found.out),
356
+ ]);
357
+ const ahead = base
358
+ ? Number(
359
+ (await git(tree.path, ["rev-list", "--count", `${base}..HEAD`])).out
360
+ )
361
+ : 0;
362
+ if (!dirty && !ahead) return null;
363
+ const tip = (await git(tree.path, ["rev-parse", "HEAD"])).out;
364
+ return {
365
+ tip,
366
+ at: thread.updated_at,
367
+ title: askedFor(posts) || title,
368
+ sides: {
369
+ cwd: tree.path,
370
+ from: (await pushedPart(tree, host)) || base || "HEAD",
371
+ to: null,
372
+ folder: tree.path,
373
+ },
374
+ out:
375
+ !dirty && host
376
+ ? await pushed(tree.path, host.remote, tree.branch, tip)
377
+ : false,
378
+ };
379
+ }
380
+ if (tree.state === "merged" && tree.tip)
381
+ return {
382
+ tip: tree.tip,
383
+ at: tree.mergedAt,
384
+ // A merge brings in every turn: the thread's own title.
385
+ title,
386
+ merged: true,
387
+ sides: {
388
+ cwd: tree.repo,
389
+ from: tree.base,
390
+ to: tree.tip,
391
+ folder: tree.repo,
392
+ },
393
+ };
394
+ return null;
395
+ }
396
+
397
+ export function createLanded({
398
+ store,
399
+ worktrees,
400
+ homeOf,
401
+ /** A thread's title as every surface shows it (threadView.mjs). */
402
+ threadTitle = (thread) => thread.objective,
403
+ /** The T3 Code threads the board follows (environments.mjs): those working in a checkout of their own can land too. */
404
+ outside = () => null,
405
+ log = () => {},
406
+ github = createGithub({ log }),
407
+ }) {
408
+ /** What items are made of for one thread: its copy, runs, posts and title, and the agent whose changes they are. */
409
+ const contextOf = (thread, tree = worktrees.record(thread.id)) => {
410
+ const posts = store.roomPosts(thread.id, 0, 500);
411
+ const runs = store.threadRuns(thread.id);
412
+ const agent = maker(runs);
413
+ return {
414
+ thread,
415
+ tree,
416
+ posts,
417
+ runs,
418
+ agent,
419
+ by: agent ? nameOf(agent) : null,
420
+ title: threadTitle(thread, posts),
421
+ };
422
+ };
423
+
424
+ /** A followed T3 Code thread as items are made of it: its checkout as a T3 copy, T3's own thread as its session. */
425
+ const outsideContext = async (work) => ({
426
+ thread: {
427
+ id: work.id,
428
+ objective: work.title,
429
+ updated_at: work.updatedAt,
430
+ },
431
+ // Working in the project itself, the thread has no copy of its own: what it landed is the commits it made.
432
+ tree: {
433
+ state: work.inPlace ? "in_project" : "t3",
434
+ path: work.path,
435
+ branch: work.inPlace ? null : work.branch,
436
+ repo: await repositoryRoot(work.path),
437
+ },
438
+ inPlace: Boolean(work.inPlace),
439
+ createdAt: work.createdAt ?? null,
440
+ posts: [],
441
+ runs: [],
442
+ t3Thread: work.threadId,
443
+ agent: work.agent,
444
+ by: nameOf(work.agent),
445
+ title: work.title,
446
+ });
447
+
448
+ /** The thread a surface asked about, as items are made of it; null when there is none (or nothing of its own). */
449
+ const contextFor = async (id) => {
450
+ const t3 = outside();
451
+ if (t3?.owns(id)) {
452
+ const work = t3.work(id);
453
+ return work ? outsideContext(work) : null;
454
+ }
455
+ const thread = store.getTask(id);
456
+ return thread?.goal ? contextOf(thread) : null;
457
+ };
458
+
459
+ const rootOf = async (context) =>
460
+ context.tree?.repo ?? repositoryRoot(context.thread.goal?.workspace);
461
+
462
+ /** The app that shows a thread's changes not out yet: the T3 thread, an editor's diff tabs, else a command to copy. */
463
+ const homeDoor = ({ tree, runs, agent, t3Thread: inT3 }) => {
464
+ // A T3 Code thread opens in T3 before anything else is asked: an agent's home is not cheap, and a repository's view
465
+ // asks this of every thread in it.
466
+ if (inT3 || tree.state === "t3") {
467
+ const session =
468
+ inT3 ??
469
+ [...runs]
470
+ .reverse()
471
+ .find(
472
+ (run) =>
473
+ run.session_id && t3Thread(run.session_id) === run.session_id
474
+ )?.session_id;
475
+ const link = session ? t3Link(session) : null;
476
+ if (link) return { name: "T3 Code", link };
477
+ const t3 = t3App();
478
+ if (t3) return { name: "T3 Code", app: t3.app };
479
+ }
480
+ const home = agent ? homeOf(agent) : null;
481
+ if (home?.kind === "codex-app" && agent === "codex") {
482
+ const run = [...runs]
483
+ .reverse()
484
+ .find((entry) => entry.target_agent === "codex" && entry.session_id);
485
+ if (run)
486
+ return { name: "Codex", link: `codex://threads/${run.session_id}` };
487
+ }
488
+ // The agent's own editor; else the editor another of the person's agents lives in; else any editor here.
489
+ const homes = [
490
+ home,
491
+ ...LIVE_AGENTS.map((id) => (id === agent ? null : homeOf(id))),
492
+ ];
493
+ const installed = EDITOR_IDS.map((id) => {
494
+ const install = editorInstall(id);
495
+ return install ? { editor: id, name: editorName(id), ...install } : null;
496
+ }).filter(Boolean);
497
+ const editor =
498
+ homes.find((place) => place?.kind === "editor" && place.cli) ??
499
+ installed.find((one) =>
500
+ homes.some(
501
+ (place) => place?.kind === "editor" && place.editor === one.editor
502
+ )
503
+ ) ??
504
+ installed.find((one) => one.editor === "vscode") ??
505
+ installed[0];
506
+ if (editor) return { name: editorLabel(editor.name), editor };
507
+ return { name: null, copy: true };
508
+ };
509
+
510
+ /** An editor shows the changes as its own diff tabs: what it was, beside the file as the thread has it. */
511
+ const showInEditor = async (editor, sides, threadId) => {
512
+ const listed = (
513
+ await git(sides.cwd, [
514
+ "diff",
515
+ "--name-status",
516
+ "--no-renames",
517
+ sides.from,
518
+ ...(sides.to ? [sides.to] : []),
519
+ ])
520
+ ).out
521
+ .split("\n")
522
+ .filter(Boolean);
523
+ const files = listed.map((line) => line.split("\t")).slice(0, DIFF_FILES);
524
+ const dir = path.join(paths.home, "diffs", threadId);
525
+ fs.rmSync(dir, { recursive: true, force: true });
526
+ const written = async (side, rev, file, gone) => {
527
+ const at = path.join(dir, side, file);
528
+ fs.mkdirSync(path.dirname(at), { recursive: true });
529
+ const shown = gone
530
+ ? null
531
+ : await git(sides.cwd, ["show", `${rev}:${file}`], { raw: true });
532
+ fs.writeFileSync(at, shown?.ok ? shown.bytes : "");
533
+ return at;
534
+ };
535
+ const pairs = [];
536
+ for (const [status, file] of files)
537
+ pairs.push([
538
+ await written("before", sides.from, file, status === "A"),
539
+ sides.to
540
+ ? await written("after", sides.to, file, status === "D")
541
+ : status === "D"
542
+ ? await written("after", null, file, true)
543
+ : path.join(sides.folder, file),
544
+ ]);
545
+ const env = { ...process.env };
546
+ // Not inside one of the editor's terminals: a tool started there would replace that window's folder.
547
+ delete env.VSCODE_IPC_HOOK_CLI;
548
+ delete env.ELECTRON_RUN_AS_NODE;
549
+ const calls = [
550
+ [sides.folder],
551
+ ...pairs.map(([before, after]) => [
552
+ "--reuse-window",
553
+ "--diff",
554
+ before,
555
+ after,
556
+ ]),
557
+ ];
558
+ // One at a time: the first may start the editor, and the tabs belong in the window it opens.
559
+ for (const args of calls)
560
+ await new Promise((resolve) => {
561
+ const child = spawn(editor.cli, args, { env, stdio: "ignore" });
562
+ child.on("error", resolve);
563
+ child.on("close", resolve);
564
+ });
565
+ return listed.length;
566
+ };
567
+
568
+ /** The person's threads that work in this repository, and the T3 Code threads with a checkout of it. */
569
+ const threadsIn = async (root) => {
570
+ const goals = store
571
+ .goals({ all: true })
572
+ .map((thread) => ({ thread, tree: worktrees.record(thread.id) }));
573
+ const own = await fewAtOnce(goals, async ({ thread, tree }) =>
574
+ (tree?.repo ?? (await repositoryRoot(thread.goal.workspace))) === root
575
+ ? contextOf(thread, tree)
576
+ : null
577
+ );
578
+ const since = Date.now() - WEEK_MS;
579
+ const t3 = await fewAtOnce(
580
+ // A thread in the project itself last moved before this week landed nothing this week.
581
+ (outside()?.worked() ?? []).filter(
582
+ (work) => !work.inPlace || Date.parse(work.updatedAt) >= since
583
+ ),
584
+ outsideContext
585
+ );
586
+ return [
587
+ ...own.filter(Boolean),
588
+ ...t3.filter((context) => context.tree.repo === root),
589
+ ];
590
+ };
591
+
592
+ /** A thread's items: its pull requests (by its branch or a link in it) and what it has here. */
593
+ const itemsOf = async (context, host, requests, floor = null) => {
594
+ const { tree } = context;
595
+ const named = requestsNamed(context.posts, host);
596
+ const items = requests
597
+ .filter(
598
+ (request) =>
599
+ (tree?.branch && request.branch === tree.branch) ||
600
+ named.includes(request.number)
601
+ )
602
+ .map((request) => requestItem(host, request, context));
603
+ const work = await localWork(context, host);
604
+ if (work && !(work.out && items.some((item) => item.stage !== "landed")))
605
+ items.push(await workItem(context, host, work));
606
+ if (context.inPlace)
607
+ items.push(...(await commitItems(context, host, tree.repo, floor)));
608
+ return { items, named };
609
+ };
610
+
611
+ /**
612
+ * A thread's commits, each where it stands: on the host's main line it landed; on the person's own main line it
613
+ * landed here, not pushed; pushed on another branch it waits; anywhere else it is not out yet.
614
+ */
615
+ const commitItems = async (context, host, root, floor) => {
616
+ if (!root) return [];
617
+ const found = await commitsMade(context, root, host, floor);
618
+ if (!found?.made.length) return [];
619
+ const { made, history } = found;
620
+ const door = homeDoor(context);
621
+ const here = {
622
+ kind: "home",
623
+ name: door.name ?? "Terminal",
624
+ label: door.copy ? "Copy the diff command" : `Open in ${door.name}`,
625
+ };
626
+ return made.map((commit) => {
627
+ const onHost = history.onHost.has(commit.sha);
628
+ const onMain = onHost || history.onMain.has(commit.sha);
629
+ const pushedElsewhere = !onMain && history.pushed.has(commit.sha);
630
+ return {
631
+ key: `commit:${commit.sha}`,
632
+ stage: onMain ? "landed" : pushedElsewhere ? "review" : "local",
633
+ label: commit.sha.slice(0, 7),
634
+ title: commit.subject,
635
+ at: commit.at,
636
+ by: context.by,
637
+ thread: { id: context.thread.id, title: context.title },
638
+ door:
639
+ onHost || pushedElsewhere
640
+ ? {
641
+ kind: "host",
642
+ name: host.name,
643
+ url: commitPage(host, commit.sha),
644
+ }
645
+ : here,
646
+ };
647
+ });
648
+ };
649
+
650
+ /** A pull request's line; `context` is the thread it came from, or null for one no thread made. */
651
+ const requestItem = (host, request, context) => ({
652
+ key: `pr:${request.number}`,
653
+ stage:
654
+ request.state === "MERGED"
655
+ ? "landed"
656
+ : request.state === "CLOSED"
657
+ ? "closed"
658
+ : "review",
659
+ label: `#${request.number}`,
660
+ title: request.title,
661
+ at:
662
+ request.state === "MERGED"
663
+ ? request.mergedAt
664
+ : request.updatedAt || request.createdAt,
665
+ by: context?.by ?? request.author,
666
+ thread: context ? { id: context.thread.id, title: context.title } : null,
667
+ door: { kind: "host", name: host.name, url: changesPage(host, request) },
668
+ });
669
+
670
+ const workItem = async (context, host, work) => {
671
+ const { thread, tree, by } = context;
672
+ const from = { id: thread.id, title: context.title };
673
+ if (work.out && host)
674
+ return {
675
+ key: `branch:${thread.id}`,
676
+ stage: "review",
677
+ label: "pushed",
678
+ title: work.title,
679
+ at: work.at,
680
+ by,
681
+ thread: from,
682
+ door: {
683
+ kind: "host",
684
+ name: host.name,
685
+ url: comparePage(
686
+ host,
687
+ await intoBranch(tree.repo ?? tree.path, host.remote),
688
+ tree.branch
689
+ ),
690
+ },
691
+ };
692
+ const door = homeDoor(context);
693
+ return {
694
+ key: `here:${thread.id}`,
695
+ stage: work.merged ? "landed" : "local",
696
+ label: "local",
697
+ title: work.title,
698
+ at: work.at,
699
+ by,
700
+ thread: from,
701
+ door: {
702
+ kind: "home",
703
+ name: door.name ?? "Terminal",
704
+ label: door.copy ? "Copy the diff command" : `Open in ${door.name}`,
705
+ },
706
+ };
707
+ };
708
+
709
+ /** The repository's pull requests as the host has them: a list, or why there is none. */
710
+ const requestsOf = async (host) => {
711
+ if (!host) return { answer: "no_host", requests: [] };
712
+ if (host.kind !== "github") return { answer: "other_host", requests: [] };
713
+ const listed = await github.list(host.slug);
714
+ return listed.ok
715
+ ? { answer: "ok", requests: listed.requests }
716
+ : { answer: listed.answer, requests: [] };
717
+ };
718
+
719
+ /** One thread's view: its items and the repository they are in. */
720
+ const threadView = async (context) => {
721
+ const root = await rootOf(context);
722
+ if (!root) return { ok: true, scope: "thread", repo: null, items: [] };
723
+ const host = await hostOf(root);
724
+ const { answer, requests } = await requestsOf(host);
725
+ const { items, named } = await itemsOf(context, host, requests);
726
+ // A pull request the thread linked that is older than the host's list reaches.
727
+ const missing = named.filter(
728
+ (number) => !requests.some((request) => request.number === number)
729
+ );
730
+ if (answer === "ok")
731
+ for (const number of missing) {
732
+ const found = await github.one(host.slug, number);
733
+ if (found.ok) items.push(requestItem(host, found.request, context));
734
+ }
735
+ return {
736
+ ok: true,
737
+ scope: "thread",
738
+ repo: repoOf(root, host),
739
+ github: answer,
740
+ items: settled(items),
741
+ };
742
+ };
743
+
744
+ /** A repository's view: this week's landings, everything in review, and every thread's work not out yet. */
745
+ const folderView = async (root) => {
746
+ const host = await hostOf(root);
747
+ const [{ answer, requests }, contexts] = await Promise.all([
748
+ requestsOf(host),
749
+ threadsIn(root),
750
+ ]);
751
+ const since = Date.now() - WEEK_MS;
752
+ const recent = (item) =>
753
+ item.stage !== "landed" || Date.parse(item.at) >= since;
754
+ const found = await fewAtOnce(contexts, (context) =>
755
+ itemsOf(context, host, requests, since)
756
+ );
757
+ const items = [];
758
+ const claimed = new Set();
759
+ for (const { items: own } of found)
760
+ for (const item of own) {
761
+ if (item.key.startsWith("pr:")) {
762
+ if (claimed.has(item.key)) continue;
763
+ claimed.add(item.key);
764
+ }
765
+ items.push(item);
766
+ }
767
+ for (const request of requests)
768
+ if (!claimed.has(`pr:${request.number}`))
769
+ items.push(requestItem(host, request, null));
770
+ return {
771
+ ok: true,
772
+ scope: "folder",
773
+ repo: repoOf(root, host),
774
+ github: answer,
775
+ items: settled(items.filter(recent)),
776
+ };
777
+ };
778
+ const folderViews = new Map();
779
+ const folderViewOf = (root) => {
780
+ const entry = folderViews.get(root);
781
+ if (entry && Date.now() - entry.at < FOLDER_FRESH_MS) return entry.view;
782
+ const view = folderView(root);
783
+ folderViews.set(root, { at: Date.now(), view });
784
+ // A read that failed is not kept for the next one.
785
+ view.catch(() => folderViews.delete(root));
786
+ return view;
787
+ };
788
+
789
+ const home = process.env.HOME || "";
790
+ const repoOf = (root, host) => ({
791
+ root,
792
+ name:
793
+ home && root.startsWith(home + path.sep)
794
+ ? `~${root.slice(home.length)}`
795
+ : root,
796
+ host: host ? { name: host.name, web: host.web } : null,
797
+ });
798
+
799
+ /** Newest first, closed pull requests left out: they neither landed nor wait on anyone. */
800
+ const settled = (items) =>
801
+ items
802
+ .filter((item) => item.stage !== "closed")
803
+ .sort((a, b) => Date.parse(b.at || 0) - Date.parse(a.at || 0));
804
+
805
+ /** The person opens a thread's changes not out yet: the app that shows them, doing it now. */
806
+ const openWork = async (context) => {
807
+ const door = homeDoor(context);
808
+ // A T3 Code thread opens at itself: T3 shows what each of its turns changed, committed or not.
809
+ if (door.link) return { ok: true, opensIn: door.name, link: door.link };
810
+ if (door.app) return { ok: true, opensIn: door.name, app: door.app };
811
+ const root = await rootOf(context);
812
+ const work = await localWork(context, root ? await hostOf(root) : null);
813
+ if (!work)
814
+ return { ok: false, error: "this thread has nothing here to show" };
815
+ const range = `${work.sides.from}${work.sides.to ? `..${work.sides.to}` : ""}`;
816
+ if (door.editor) {
817
+ const shown = await showInEditor(
818
+ door.editor,
819
+ work.sides,
820
+ context.thread.id
821
+ );
822
+ return {
823
+ ok: true,
824
+ opensIn: door.name,
825
+ ...(shown > DIFF_FILES
826
+ ? {
827
+ note: `${door.name} shows the first ${DIFF_FILES} of ${shown} files. The rest are in git diff ${range} there.`,
828
+ }
829
+ : {}),
830
+ };
831
+ }
832
+ return {
833
+ ok: true,
834
+ opensIn: null,
835
+ copy: `git -C '${work.sides.cwd.replace(/'/g, "'\\''")}' diff ${range}`,
836
+ note: "No app on this computer shows diffs, so the command that does is copied. Paste it in your terminal.",
837
+ };
838
+ };
839
+
840
+ /** What a surface asked for, once the thread it names is known. */
841
+ async function answer(request, id) {
842
+ const context = await contextFor(id);
843
+ if (!context)
844
+ return {
845
+ ok: false,
846
+ error: outside()?.owns(id)
847
+ ? "this T3 Code thread works in its project, not in a checkout of its own"
848
+ : "no such thread",
849
+ };
850
+ if (request.command === "board.landed.folder") {
851
+ const root = await rootOf(context);
852
+ return root
853
+ ? folderViewOf(root)
854
+ : { ok: false, error: "this thread's folder is not a repository" };
855
+ }
856
+ if (request.command === "board.landed.thread") return threadView(context);
857
+ return openWork(context);
858
+ }
859
+
860
+ const COMMANDS = new Set([
861
+ "board.landed.thread",
862
+ "board.landed.folder",
863
+ "board.landed.open",
864
+ ]);
865
+
866
+ return {
867
+ /** Whether a thread made anything that can land: a branch of its own, or a pull request it links. Cheap. */
868
+ produced(thread, posts) {
869
+ const tree = worktrees.record(thread.id);
870
+ if (tree?.branch && tree.state !== "discarded") return true;
871
+ return posts.some((post) => PULL_LINK.test(String(post.text || "")));
872
+ },
873
+ command(request, agent) {
874
+ if (agent !== "user")
875
+ return { ok: false, error: "only the person reads what landed" };
876
+ if (!COMMANDS.has(request.command))
877
+ return { ok: false, error: `unknown command ${request.command}` };
878
+ return {
879
+ // Git or gh failing in a way not foreseen still answers the surface that asked, in words.
880
+ pending: answer(request, String(request.id || "")).catch((error) => {
881
+ log(`landed: ${error.message}`);
882
+ return { ok: false, error: "what landed could not be read" };
883
+ }),
884
+ };
885
+ },
886
+ };
887
+ }