tryharness 0.7.38 → 0.7.41

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.
package/lib/swarm.mjs CHANGED
@@ -6,6 +6,7 @@ import { readRunSteps } from "./runner.mjs";
6
6
  import { createSubagents } from "./subagents.mjs";
7
7
  import { nameOf, resolveMember } from "./members.mjs";
8
8
  import { setNote, swarmBlock, swarmCards, swarmDigest } from "./cards.mjs";
9
+ import { askOfRun } from "./threadView.mjs";
9
10
  import {
10
11
  DEFAULT_ROUTING,
11
12
  PICKABLE,
@@ -33,6 +34,8 @@ const SAY_LIMIT = 4_000;
33
34
  // `@swarm` in the person's message: written to their whole swarm, not to one agent.
34
35
  const SWARM = /(^|\s)@swarm\b/;
35
36
  const UUID = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i;
37
+ // A setup check's own room, from before checks stopped opening one (onboard.mjs): never a thread for the person.
38
+ const SETUP_CHECK = /^Setup check from Harness: reply ready$/;
36
39
 
37
40
  // The id an agent resumes a session by: the index keys sessions by their file name.
38
41
  export function nativeSessionId(agent, sessionId) {
@@ -109,6 +112,10 @@ export function createSwarm({
109
112
  lessons = null,
110
113
  // The subagents each run's own session spawned (subagents.mjs), for the thread's canvas.
111
114
  subagents = createSubagents(),
115
+ // Work wired to wait for other work in the thread (plans.mjs).
116
+ plansOf = () => [],
117
+ // The thread as the person reads it on every surface (threadView.mjs).
118
+ threadView = null,
112
119
  }) {
113
120
  // What the person let a thread spend of their Harness credits, in dollars, or null for no limit of its own.
114
121
  const ceilingOf = (threadId) => {
@@ -209,9 +216,13 @@ export function createSwarm({
209
216
  const last = posts.at(-1);
210
217
  const live = runs.find((run) => run.status === "running");
211
218
  const step = live ? readRunSteps(runLog(live.id), 1)[0] : null;
219
+ const view = threadView?.row(thread, posts) ?? null;
212
220
  return {
213
221
  id: thread.id,
214
- title: thread.objective,
222
+ title: view?.title ?? thread.objective,
223
+ objective: thread.objective,
224
+ // The same title, state, line and needs-you items on every surface (threadView.mjs).
225
+ view,
215
226
  status: thread.status,
216
227
  agents: agentsOf(thread),
217
228
  coordinator: thread.goal.facilitator,
@@ -354,22 +365,20 @@ export function createSwarm({
354
365
  : [],
355
366
  });
356
367
 
357
- // Who handed a run its work and what they asked: a task names its poster; a wake, whoever woke it (threadRuns.mjs),
358
- // read back from the words it was woken with for wakes from before the asker was kept.
359
- const askOf = (run) => {
360
- if (run.kind !== "wake")
361
- return { askedBy: run.origin_agent, ask: run.objective };
362
- let why = null;
363
- try {
364
- why = JSON.parse(store.meta(`wake-reason:${run.id}`) || "null");
365
- } catch {}
366
- const said = /^(\S+) (?:mentioned|asked) you: ([^]*)$/.exec(
367
- why?.reason ?? ""
368
+ const askOf = (run) => askOfRun(store, run);
369
+ const linkThreads = (from, to, agent) => {
370
+ const note = (goalId, text) =>
371
+ store.roomPost({ goalId, author: "harness", kind: "note", text });
372
+ note(
373
+ from.id,
374
+ `${nameOf(agent)} started a thread for part of this: ${to.objective}`
368
375
  );
369
- return {
370
- askedBy: why?.asker ?? said?.[1] ?? run.origin_agent,
371
- ask: said?.[2] ?? why?.reason ?? run.objective,
372
- };
376
+ note(
377
+ to.id,
378
+ `Started by ${nameOf(agent)} from the thread: ${from.objective}`
379
+ );
380
+ store.meta(`thread-from:${to.id}`, from.id);
381
+ notifyBoard(store.getTask(from.id));
373
382
  };
374
383
 
375
384
  const read = (thread, hostedCaller = false) => {
@@ -401,13 +410,17 @@ export function createSwarm({
401
410
  endedAt: run.reported_at,
402
411
  }),
403
412
  }));
413
+ const posts = store.roomPosts(thread.id, 0, 500);
404
414
  return {
405
415
  ok: true,
406
416
  thread: summary(thread),
407
- posts: store.roomPosts(thread.id, 0, 500),
417
+ posts,
418
+ // The thread in order as the person reads it: messages, steps gathered into groups, files (threadView.mjs).
419
+ timeline: threadView?.timeline(thread, posts) ?? [],
408
420
  // What each of the person's posts changed in what the swarm keeps (lessons.mjs), for the line under the post.
409
421
  kept: store.lessonsFromThread?.(thread.id) ?? [],
410
422
  runs,
423
+ plans: hostedCaller ? [] : plansOf(thread.id),
411
424
  // Posts held for the person (who wrote one, when, never its words), and the post that replaced each one an agent
412
425
  // posted again.
413
426
  held: store.heldPosts(thread.id).map((post) => ({
@@ -466,7 +479,10 @@ export function createSwarm({
466
479
  };
467
480
  return {
468
481
  ok: true,
469
- threads: store.goals({ all: request.all === true }).map(summary),
482
+ threads: store
483
+ .goals({ all: request.all === true })
484
+ .filter((thread) => !SETUP_CHECK.test(thread.objective))
485
+ .map(summary),
470
486
  sessions: request.sessions === false ? [] : sessions(),
471
487
  agents: roster(),
472
488
  };
@@ -604,6 +620,10 @@ export function createSwarm({
604
620
  maxWakes: defaults.maxWakes,
605
621
  });
606
622
  if (request.hostedCaller) store.meta(`hosted-thread:${thread.id}`, "1");
623
+ // A thread an agent starts from another says so in both, so neither is a dead end for the person.
624
+ const [from] = store.threadsWorkedIn(agent);
625
+ if (from)
626
+ linkThreads(store.getTask(from), store.getTask(thread.id), agent);
607
627
  const first = store.roomPost({
608
628
  goalId: thread.id,
609
629
  author: agent,
@@ -1050,6 +1070,66 @@ export function createSwarm({
1050
1070
  stopThreadRuns(thread.id);
1051
1071
  return { ok: true, thread: summary(store.getTask(thread.id)) };
1052
1072
  }
1073
+ // A post held for the person (it looked like a secret, or like orders to the agents): they read it, then send it into
1074
+ // the thread as its author wrote it or throw it away (owner, October 19: "yes" to Send and Discard). Its words
1075
+ // reach only the person's own sealed surfaces (boardProtocol.json).
1076
+ if (command === "board.swarm.held") {
1077
+ const held = store.heldPost(thread.id, String(request.post || ""));
1078
+ if (!held || store.meta(`held-replaced:${held.id}`))
1079
+ return { ok: false, error: "that post is not held any more" };
1080
+ if (request.action === "show")
1081
+ return { ok: true, author: held.author, text: held.text };
1082
+ const note = (text) =>
1083
+ store.roomPost({
1084
+ goalId: thread.id,
1085
+ author: "user",
1086
+ kind: "note",
1087
+ text,
1088
+ });
1089
+ if (request.action === "discard") {
1090
+ store.meta(`held-replaced:${held.id}`, "discarded");
1091
+ note(`Discarded by you: ${nameOf(held.author)}'s held post.`);
1092
+ } else if (request.action === "send") {
1093
+ const sent = store.roomPost({
1094
+ goalId: thread.id,
1095
+ author: held.author,
1096
+ kind: "post",
1097
+ text: held.text,
1098
+ mentions: mentionsIn(held.text, thread.goal.team),
1099
+ });
1100
+ store.meta(`held-replaced:${held.id}`, sent.id);
1101
+ note(`Sent by you: ${nameOf(held.author)}'s held post.`);
1102
+ if (thread.status === "open") wakeFor(thread.id, sent, held.author);
1103
+ } else return { ok: false, error: "action is show, send or discard" };
1104
+ notifyBoard(store.getTask(thread.id));
1105
+ return { ok: true, thread: summary(store.getTask(thread.id)) };
1106
+ }
1107
+ // The person's Done, or the thread back in their list, kept here so every surface agrees. Accepting work that is
1108
+ // ready for review is Done too, and closes the thread's goal.
1109
+ if (command === "board.swarm.file") {
1110
+ if (!threadView)
1111
+ return { ok: false, error: "this computer cannot file threads" };
1112
+ if (request.accept === true && thread.status === "open") {
1113
+ store.roomPost({
1114
+ goalId: thread.id,
1115
+ author: "user",
1116
+ kind: "note",
1117
+ text: "Accepted by you.",
1118
+ });
1119
+ store.setGoalState(thread.id, {
1120
+ status: "done",
1121
+ result: "Accepted by you.",
1122
+ });
1123
+ }
1124
+ threadView.file(thread.id, request.done !== false);
1125
+ // What Harness's server left for the browser is not taken over once the person says the thread is done.
1126
+ if (request.done !== false)
1127
+ for (const run of store.threadRuns(thread.id))
1128
+ if (run.status === "open" && store.meta(`harness-window:${run.id}`))
1129
+ store.removeTask(run.id);
1130
+ notifyBoard(store.getTask(thread.id));
1131
+ return { ok: true, thread: summary(store.getTask(thread.id)) };
1132
+ }
1053
1133
  // What the thread may spend of the person's Harness credits, set or cleared by the person; a task waiting on the old
1054
1134
  // limit is offered again.
1055
1135
  if (command === "board.swarm.ceiling") {
@@ -4,11 +4,25 @@ import { randomUUID } from "node:crypto";
4
4
  import { readRunSteps, stopAgentTask } from "./runner.mjs";
5
5
  import { provenanceFor } from "./provenance.mjs";
6
6
  import { LOCAL_WAKE_AGENTS } from "./wakes.mjs";
7
- import { aboutOf, member, nameOf, resolveMember } from "./members.mjs";
7
+ import {
8
+ TAGGED_ONLY,
9
+ aboutOf,
10
+ member,
11
+ nameOf,
12
+ resolveMember,
13
+ } from "./members.mjs";
8
14
  import { LIVE_AGENTS, sessionOfProcess } from "./live.mjs";
9
15
  import { swarmBlock, swarmDigest } from "./cards.mjs";
10
16
  import { PICKABLE, resolvePick, setRunPick } from "./models.mjs";
11
17
 
18
+ // An agent working in a thread may bring another agent in for part of the work there, as Harness does when it names
19
+ // one; an agent that moves money or takes positions joins only when the person names it (members.mjs TAGGED_ONLY).
20
+ const joinsThread = (thread, target, roomAgents) =>
21
+ !target ||
22
+ thread.goal.team.includes(String(target)) ||
23
+ (roomAgents.includes(String(target)) &&
24
+ !TAGGED_ONLY.includes(String(target)));
25
+
12
26
  export function createTaskCommands({
13
27
  CLOUD_TARGETS,
14
28
  OPENED,
@@ -48,6 +62,14 @@ export function createTaskCommands({
48
62
  actors,
49
63
  files: boardFiles,
50
64
  }) {
65
+ // The one open thread an agent is working in now, when the work it hands on may join it there.
66
+ const soleThreadOf = (agent, target) => {
67
+ const working = store.threadsWorkedIn(agent);
68
+ const thread = working.length === 1 ? store.getTask(working[0]) : null;
69
+ return thread && joinsThread(thread, target, ROOM_AGENTS)
70
+ ? thread.id
71
+ : null;
72
+ };
51
73
  return (request, { agent, id, expected, lastLooked }) => {
52
74
  let outcome;
53
75
  if (
@@ -129,6 +151,13 @@ export function createTaskCommands({
129
151
  if (!resolved.ok) return { ok: false, error: resolved.error };
130
152
  pick = resolved.pick;
131
153
  }
154
+ // Work an agent hands on while it works in one thread is placed in that thread, not a new one (owner, October 19:
155
+ // "new threads get spun up when the agents hand work off"). It is placed after it is posted, so whether it waits
156
+ // for the person's Start is decided exactly as for work outside any thread: placing it grants nothing.
157
+ const workingThread =
158
+ !request.parentId && !request.thread && agent !== "user"
159
+ ? soleThreadOf(agent, request.targetAgent)
160
+ : null;
132
161
  // Provenance is code's: the local parent's label and what Harness sent from above the poster can only tighten it.
133
162
  const parentTask = request.parentId
134
163
  ? store.getTask(String(request.parentId))
@@ -402,7 +431,9 @@ export function createTaskCommands({
402
431
  : restrictedWait(String(task.target_agent)),
403
432
  }
404
433
  : authority.applyStanding(task);
405
- if (
434
+ // A setup check is never a thread: it is only there to be answered, and goes if it is not (handoffs.mjs).
435
+ if (request.check === true) store.meta(`setup-check:${task.id}`, "1");
436
+ else if (
406
437
  !thread &&
407
438
  !goalParent &&
408
439
  !request.parentId &&
@@ -412,6 +443,7 @@ export function createTaskCommands({
412
443
  )
413
444
  openTaskRoom(store.getTask(task.id), agent, provenance, {
414
445
  hosted: Boolean(request.hostedCaller),
446
+ into: workingThread,
415
447
  });
416
448
  const note = task.target_agent
417
449
  ? actors.setupNote(task.target_agent)
@@ -0,0 +1,426 @@
1
+ import { nameOf } from "./members.mjs";
2
+
3
+ // A thread as the person reads it, worked out once here so the buddy, the phone, the PiP, the dashboard and the
4
+ // notices all say the same thing: its title, its state in one word, one line on where it stands, what needs the
5
+ // person (each item with a stable id a notice can open), and its timeline of messages, steps and files.
6
+
7
+ const IDLE_TO_DONE_MS = 2 * 24 * 60 * 60 * 1000;
8
+ const TITLE_LIMIT = 64;
9
+ const OPEN_RUN = ["open", "claimed", "running", "needs_input"];
10
+ const PERSON_STOPS = ["Stopped by you", "Stopped by the owner"];
11
+ const SLOW_PICKUP_MS = 60_000;
12
+
13
+ const minutesOf = (ms) =>
14
+ ms < 90_000
15
+ ? "a minute"
16
+ : ms < 90 * 60_000
17
+ ? `${Math.round(ms / 60_000)} min`
18
+ : `${Math.round(ms / 3_600_000)} h`;
19
+
20
+ const firstLine = (text) =>
21
+ String(text || "")
22
+ .split("\n")
23
+ .map((line) => line.trim())
24
+ .find(Boolean) ?? "";
25
+
26
+ // At a word boundary, with an ellipsis, never mid-word.
27
+ export function shorten(text, limit) {
28
+ const clean = String(text || "")
29
+ .replace(/\s+/g, " ")
30
+ .trim();
31
+ if (clean.length <= limit) return clean;
32
+ const cut = clean.lastIndexOf(" ", limit - 1);
33
+ return `${clean.slice(0, cut > limit / 2 ? cut : limit - 1).replace(/[,.;:]$/, "")}…`;
34
+ }
35
+
36
+ const capitalized = (text) => text.charAt(0).toUpperCase() + text.slice(1);
37
+
38
+ const withoutMentions = (text) =>
39
+ text.replace(/(^|\s)@[a-z][a-z0-9:./-]*/gi, "$1").trim();
40
+
41
+ /**
42
+ * Who handed a run its work and what they asked: a task names its poster; a wake, whoever woke it (threadRuns.mjs),
43
+ * read back from the words it was woken with for wakes from before the asker was kept.
44
+ */
45
+ export function askOfRun(store, run) {
46
+ if (run.kind !== "wake")
47
+ return { askedBy: run.origin_agent, ask: run.objective };
48
+ let why = null;
49
+ try {
50
+ why = JSON.parse(store.meta(`wake-reason:${run.id}`) || "null");
51
+ } catch {}
52
+ const said = /^(\S+) (?:mentioned|asked) you: ([^]*)$/.exec(
53
+ why?.reason ?? ""
54
+ );
55
+ return {
56
+ askedBy: why?.asker ?? said?.[1] ?? run.origin_agent,
57
+ ask: said?.[2] ?? why?.reason ?? run.objective,
58
+ };
59
+ }
60
+
61
+ // The first sentence leads a result; the rest follows it.
62
+ function headlineOf(text) {
63
+ const line = withoutMentions(firstLine(text).replace(/^#+\s*/, ""));
64
+ const sentence = /^(.{12,160}?[.!?])(\s|$)/.exec(line)?.[1];
65
+ return shorten(sentence ?? line, 160);
66
+ }
67
+
68
+ export function createThreadView({
69
+ store,
70
+ goals = null,
71
+ handoffs = null,
72
+ now = Date.now,
73
+ }) {
74
+ const coordinated = (post) =>
75
+ Boolean(store.meta(`coordinator-post:${post.id}`));
76
+ const filing = (threadId) => {
77
+ try {
78
+ return JSON.parse(store.meta(`thread-filed:${threadId}`) || "null");
79
+ } catch {
80
+ return null;
81
+ }
82
+ };
83
+ const awaitingStart = (run) =>
84
+ run.status === "open" &&
85
+ Boolean(run.run_workspace) &&
86
+ !run.run_authorized_at;
87
+ // What a run was asked, without the thread's title in front of it.
88
+ const askOf = (run) => {
89
+ const { ask } = askOfRun(store, run);
90
+ const asked =
91
+ /^Asked in "[^]*?": (?:\S+ (?:asked|mentioned) you: )?([^]*)$/.exec(ask);
92
+ return firstLine(asked?.[1] ?? ask);
93
+ };
94
+
95
+ function titleOf(thread, posts) {
96
+ const written = goals?.record(thread.id)?.title;
97
+ if (written) return written;
98
+ // A task's own thread is named by its task, not by what the person writes in it later.
99
+ const taskRoom = Boolean(store.meta(`task-room:${thread.id}`));
100
+ const first = taskRoom
101
+ ? null
102
+ : posts.find((post) => post.author === "user" && post.kind === "post");
103
+ const words = withoutMentions(firstLine(first?.text ?? thread.objective));
104
+ return capitalized(shorten(words || "New thread", TITLE_LIMIT));
105
+ }
106
+
107
+ // What waits on the person, newest last. An item's id stays the same while it waits, so a notice sent for it once is
108
+ // not sent again, and every surface clears it together once it is answered.
109
+ function needsYouOf(thread, posts, runs) {
110
+ const items = [];
111
+ for (const run of runs) {
112
+ if (run.status === "needs_input" && run.holder === "user")
113
+ items.push({
114
+ id: `answer:${run.id}`,
115
+ kind: "answer",
116
+ agent: run.claimed_by || run.target_agent,
117
+ text: String(run.result || "").trim(),
118
+ runId: run.id,
119
+ at: run.updated_at,
120
+ });
121
+ if (awaitingStart(run))
122
+ items.push({
123
+ id: `start:${run.id}`,
124
+ kind: "start",
125
+ agent: run.target_agent,
126
+ text: askOf(run),
127
+ runId: run.id,
128
+ folder: run.run_workspace,
129
+ at: run.created_at,
130
+ });
131
+ }
132
+ // A question from the lead waits until the person writes again; an agent's question is its run's (above).
133
+ const lastMine = posts.findLastIndex((post) => post.author === "user");
134
+ const asked = posts
135
+ .slice(lastMine + 1)
136
+ .findLast((post) => post.kind === "question" && coordinated(post));
137
+ if (asked && thread.status === "open")
138
+ items.push({
139
+ id: `question:${asked.id}`,
140
+ kind: "answer",
141
+ agent: asked.author,
142
+ text: asked.text,
143
+ seq: asked.seq,
144
+ at: asked.created_at,
145
+ });
146
+ const goal = goals?.record(thread.id);
147
+ // A review waits only in an open thread that is still moving: one the lead closed, or one left for two days, the
148
+ // person has already moved past (October 20: nine stale reviews from the week before).
149
+ const moving =
150
+ thread.status === "open" &&
151
+ now() - Date.parse(posts.at(-1)?.created_at ?? thread.updated_at) <
152
+ IDLE_TO_DONE_MS;
153
+ const reviewing = ["ready_for_review", "met"].includes(goal?.state);
154
+ if (
155
+ reviewing &&
156
+ moving &&
157
+ !filedAfter(thread.id, goal.versions?.at(-1)?.at)
158
+ )
159
+ items.push({
160
+ id: `review:${thread.id}:${goal.version}`,
161
+ kind: "review",
162
+ agent: thread.goal.facilitator,
163
+ text: goal.statement,
164
+ reached: goal.criteria
165
+ .filter((criterion) => criterion.status === "met")
166
+ .map((criterion) => criterion.text),
167
+ at: goal.versions?.at(-1)?.at ?? thread.updated_at,
168
+ });
169
+ const reason = thread.goal.paused_reason || "";
170
+ if (thread.status === "paused" && !PERSON_STOPS.includes(reason))
171
+ items.push({
172
+ id: `decide:${thread.id}:${thread.updated_at}`,
173
+ kind: "decide",
174
+ agent: thread.goal.facilitator,
175
+ text: reason.replace(/^The room is paused:\s*/, "") || "Paused.",
176
+ at: thread.updated_at,
177
+ });
178
+ // What Harness's server left for the browser waits on the person opening their Harness window (October 18: one
179
+ // such part waited 9 hours with nothing saying so).
180
+ for (const run of runs)
181
+ if (
182
+ run.target_agent === "harness" &&
183
+ run.status === "open" &&
184
+ store.meta(`harness-window:${run.id}`)
185
+ )
186
+ items.push({
187
+ id: `window:${run.id}`,
188
+ kind: "window",
189
+ agent: "harness",
190
+ text: "Harness needs your browser to finish this: open Harness on your computer.",
191
+ runId: run.id,
192
+ at: run.updated_at,
193
+ });
194
+ for (const held of store.heldPosts(thread.id))
195
+ if (!store.meta(`held-replaced:${held.id}`))
196
+ items.push({
197
+ id: `held:${held.id}`,
198
+ kind: "held",
199
+ agent: held.author,
200
+ text: `${nameOf(held.author)}'s post was held for you: it may contain a secret.`,
201
+ seq: held.seq,
202
+ at: held.created_at,
203
+ });
204
+ return items.sort((a, b) => String(a.at).localeCompare(String(b.at)));
205
+ }
206
+
207
+ // Filed Done after `at`: an answer from the person (Accept, Done) that came after the thing it settles.
208
+ function filedAfter(threadId, at) {
209
+ const filed = filing(threadId);
210
+ return Boolean(filed?.done && (!at || filed.at >= at));
211
+ }
212
+
213
+ // The newest thing a person or an agent said: Harness's own notes do not bring a filed thread back.
214
+ const lastWords = (posts) =>
215
+ posts.findLast(
216
+ (post) => post.kind !== "note" && post.kind !== "goal_update"
217
+ );
218
+
219
+ function stateOf(thread, items, runs) {
220
+ if (items.length) return "needs_you";
221
+ if (runs.some((run) => OPEN_RUN.includes(run.status))) return "working";
222
+ if (thread.status === "paused") return "stopped";
223
+ if (thread.status === "failed") return "failed";
224
+ return "returned";
225
+ }
226
+
227
+ // A handoff nobody picked up in time (handoffs.mjs): the working line is about it.
228
+ const lateHandoff = (runs) =>
229
+ runs.map((run) => handoffs?.of(run)).find(Boolean) ?? null;
230
+
231
+ function lineOf(state, items, runs, posts, thread) {
232
+ if (state === "needs_you") return itemLine(items.at(-1));
233
+ if (state === "working") {
234
+ const late = lateHandoff(runs);
235
+ if (late) return late.line;
236
+ const working = [
237
+ ...new Set(
238
+ runs
239
+ .filter((run) => ["claimed", "running"].includes(run.status))
240
+ .map((run) => nameOf(run.claimed_by || run.target_agent))
241
+ ),
242
+ ];
243
+ return working.length
244
+ ? `${working.join(" and ")} ${working.length > 1 ? "are" : "is"} working`
245
+ : "Waiting for its turn";
246
+ }
247
+ if (state === "stopped")
248
+ return PERSON_STOPS.includes(thread.goal.paused_reason)
249
+ ? "Stopped by you"
250
+ : thread.goal.paused_reason || "Stopped";
251
+ const last = lastWords(posts);
252
+ if (!last) return "Nothing yet";
253
+ const who = last.author === "user" ? "You" : nameOf(last.author);
254
+ return `${who}: ${shorten(withoutMentions(firstLine(last.text)), 140)}`;
255
+ }
256
+
257
+ function itemLine(item) {
258
+ const who = nameOf(item.agent);
259
+ if (item.kind === "answer")
260
+ return `${who} asks you: ${shorten(firstLine(item.text), 140)}`;
261
+ if (item.kind === "start") return `${who} waits for your Start`;
262
+ if (item.kind === "review") return "Ready for your review";
263
+ if (item.kind === "held") return item.text;
264
+ if (item.kind === "window") return "Harness needs your browser to finish";
265
+ return `${who} needs you to decide: ${shorten(item.text, 120)}`;
266
+ }
267
+
268
+ function doneOf(thread, state, posts) {
269
+ if (state === "needs_you" || state === "working") return false;
270
+ const filed = filing(thread.id);
271
+ const last = lastWords(posts);
272
+ if (filed) return filed.done && (!last || filed.at >= last.created_at);
273
+ const idle = now() - Date.parse(last?.created_at ?? thread.updated_at);
274
+ return idle > IDLE_TO_DONE_MS;
275
+ }
276
+
277
+ /** The thread's row: the same title, state, line and needs-you items in every list. */
278
+ function row(thread, posts = store.roomPosts(thread.id, 0, 500)) {
279
+ const runs = store.threadRuns(thread.id);
280
+ const items = needsYouOf(thread, posts, runs);
281
+ const state = stateOf(thread, items, runs);
282
+ return {
283
+ title: titleOf(thread, posts),
284
+ state,
285
+ line: lineOf(state, items, runs, posts, thread),
286
+ // The line is a late or moved handoff, so a list can mark it apart from work going as planned.
287
+ late: state === "working" && Boolean(lateHandoff(runs)),
288
+ needsYou: items,
289
+ done: doneOf(thread, state, posts),
290
+ };
291
+ }
292
+
293
+ /** The person's Done (or back in the list), kept here so their phone and their desk agree. */
294
+ function file(threadId, done) {
295
+ store.meta(
296
+ `thread-filed:${threadId}`,
297
+ JSON.stringify({ done: Boolean(done), at: new Date(now()).toISOString() })
298
+ );
299
+ }
300
+
301
+ // A run as steps, only where they tell something its agent's own words do not: a slow pickup, a late or moved
302
+ // handoff, a run that stopped. A run picked up at once that answered in the thread needs no line of its own.
303
+ function runSteps(run) {
304
+ const agent = run.claimed_by || run.target_agent;
305
+ const step = (at, text) => ({ agent, at, runId: run.id, text });
306
+ const steps = [];
307
+ const waited = Date.parse(run.claimed_at) - Date.parse(run.created_at);
308
+ if (run.claimed_at && waited > SLOW_PICKUP_MS)
309
+ steps.push(
310
+ step(
311
+ run.claimed_at,
312
+ `${nameOf(agent)} picked it up after ${minutesOf(waited)}`
313
+ )
314
+ );
315
+ const handoff = handoffs?.of(run);
316
+ if (handoff) steps.push({ ...step(handoff.at, handoff.line), late: true });
317
+ if (run.status === "failed" && !handoff?.movedTo && run.reported_at)
318
+ steps.push(
319
+ step(
320
+ run.reported_at,
321
+ `${nameOf(agent)} stopped: ${shorten(firstLine(run.result), 120)}`
322
+ )
323
+ );
324
+ return steps;
325
+ }
326
+
327
+ // A post as the person reads it: words from someone, or a step in how the work moved.
328
+ function entryOf(post, taskRoom = false) {
329
+ if (post.kind === "file")
330
+ return {
331
+ type: "file",
332
+ seq: post.seq,
333
+ author: post.author,
334
+ file: post.file,
335
+ at: post.created_at,
336
+ };
337
+ const step = {
338
+ type: "step",
339
+ agent: post.author,
340
+ at: post.created_at,
341
+ seq: post.seq,
342
+ };
343
+ // A job post repeats an ask the thread already shows (the asker's own words, or the lead's step), except a task's
344
+ // own thread's first post, which is the ask itself.
345
+ if (post.kind === "job" && !(post.seq === 1 && taskRoom)) return null;
346
+ if (post.kind === "job")
347
+ return {
348
+ type: "message",
349
+ seq: post.seq,
350
+ author: post.author,
351
+ text: post.text,
352
+ result: false,
353
+ asks: false,
354
+ headline: null,
355
+ at: post.created_at,
356
+ };
357
+ if (post.kind === "note" || post.kind === "receipt")
358
+ return { ...step, text: firstLine(post.text) };
359
+ if (post.kind === "goal_update" || post.kind === "open_item")
360
+ return { ...step, text: shorten(firstLine(post.text), 140) };
361
+ if (
362
+ post.kind === "post" &&
363
+ coordinated(post) &&
364
+ post.mentions?.length !== 0
365
+ )
366
+ return { ...step, text: handOnLine(post) };
367
+ return {
368
+ type: "message",
369
+ seq: post.seq,
370
+ author: post.author,
371
+ text: post.text,
372
+ result: post.kind === "result" || post.kind === "answer",
373
+ asks: post.kind === "question",
374
+ headline: post.kind === "result" ? headlineOf(post.text) : null,
375
+ at: post.created_at,
376
+ };
377
+ }
378
+
379
+ function handOnLine(post) {
380
+ const named = /^@([a-z][a-z0-9-]*)\s*(\(review, no changes\)\s*)?/i.exec(
381
+ post.text
382
+ );
383
+ if (!named) return shorten(firstLine(post.text), 200);
384
+ const ask = shorten(firstLine(post.text.slice(named[0].length)), 160);
385
+ const review = named[2] ? " to review" : "";
386
+ if (named[1] === post.author)
387
+ return `${nameOf(post.author)} took it on: ${ask}`;
388
+ return `${nameOf(post.author)} asked ${nameOf(named[1])}${review}: ${ask}`;
389
+ }
390
+
391
+ /** The thread in order, with consecutive steps gathered into one group. */
392
+ function timeline(thread, posts = store.roomPosts(thread.id, 0, 500)) {
393
+ const runs = store.threadRuns(thread.id);
394
+ const entries = [
395
+ ...posts
396
+ .map((post) =>
397
+ entryOf(post, Boolean(store.meta(`task-room:${thread.id}`)))
398
+ )
399
+ .filter(Boolean),
400
+ ...runs.flatMap(runSteps).map((step) => ({ type: "step", ...step })),
401
+ ].sort((a, b) => String(a.at).localeCompare(String(b.at)));
402
+ const grouped = [];
403
+ for (const entry of entries) {
404
+ const previous = grouped.at(-1);
405
+ if (entry.type !== "step") grouped.push(entry);
406
+ else if (previous?.type === "steps") previous.steps.push(entry);
407
+ else grouped.push({ type: "steps", at: entry.at, steps: [entry] });
408
+ }
409
+ return grouped;
410
+ }
411
+
412
+ /** Everything that waits on the person across open threads, for notices. */
413
+ function waiting() {
414
+ return store
415
+ .goals()
416
+ .filter((thread) => !store.meta(`setup-check:${thread.id}`))
417
+ .flatMap((thread) => {
418
+ const posts = store.roomPosts(thread.id, 0, 500);
419
+ const items = needsYouOf(thread, posts, store.threadRuns(thread.id));
420
+ const title = titleOf(thread, posts);
421
+ return items.map((item) => ({ ...item, threadId: thread.id, title }));
422
+ });
423
+ }
424
+
425
+ return { row, timeline, file, waiting, itemLine };
426
+ }