tryharness 0.7.40 → 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.
@@ -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
+ }
package/lib/wakes.mjs CHANGED
@@ -315,12 +315,13 @@ export function createLocalWaker({
315
315
  }),
316
316
  state.get(agent));
317
317
  // A wake that holds is out until the agent reports; a result to read is sent only when none is out and holds nothing.
318
- const wake = async (agent, taskId, { holds = true } = {}) => {
318
+ // `force`: work it was woken for was not picked up (handoffs.mjs), so this wake goes past the one still out.
319
+ const wake = async (agent, taskId, { holds = true, force = false } = {}) => {
319
320
  const target = targets()[agent];
320
321
  if (!target) return "none";
321
322
  const s = of(agent),
322
323
  now = Date.now();
323
- if (s.outstandingAt && now - s.outstandingAt < ANSWER_WINDOW_MS) {
324
+ if (!force && s.outstandingAt && now - s.outstandingAt < ANSWER_WINDOW_MS) {
324
325
  s.more = true;
325
326
  log(`wake ${agent}: merged (${taskId})`);
326
327
  return "merged";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tryharness",
3
- "version": "0.7.40",
3
+ "version": "0.7.41",
4
4
  "description": "Harness Relay: the daemon that turns the agents on this machine into your personal swarm. Memory, history, and work handed between any of them.",
5
5
  "bin": {
6
6
  "tryharness": "cli.mjs"