tryharness 0.7.69 → 0.7.70

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.
@@ -4,7 +4,7 @@ import os from "node:os";
4
4
  import { spawnSync } from "node:child_process";
5
5
  import { PS } from "./nudge.mjs";
6
6
  import { paths } from "./paths.mjs";
7
- import { MACHINE_RUNNERS } from "./members.mjs";
7
+ import { MACHINE_RUNNERS, MEMBERS, nameOf } from "./members.mjs";
8
8
  import { runCapability, runningPids } from "./runner.mjs";
9
9
  import {
10
10
  descendsFrom,
@@ -13,6 +13,11 @@ import {
13
13
  seesPeers,
14
14
  } from "./peerProcess.mjs";
15
15
 
16
+ /**
17
+ * Set by the daemon on a board call Harness's server made for a hosted agent (daemon.mjs, the bridge's board message):
18
+ * no JSON a local caller or another computer writes can set it, unlike the hostedCaller field, which only ever narrows.
19
+ */
20
+ export const HOSTED_CALLER = Symbol("a board call Harness's server made");
16
21
  /** The run Harness started that made a socket call, set by checkCaller; no JSON a caller writes can set it. */
17
22
  export const RUN_CALLER = Symbol("the run that called");
18
23
  /** How the run that made a call was held in, so what it asks for is held in too: "review", "restricted" or null. */
@@ -60,6 +65,15 @@ const PERSON_READS = new Set([
60
65
  "board.swarm.list",
61
66
  "board.swarm.read",
62
67
  ]);
68
+ /**
69
+ * The person's own agents that run elsewhere and can be handed work (Grok Bot, Muse): the only agents whose asks a coding
70
+ * agent's standing permission may take, and only when the person named them on it (board.standing.set proposers).
71
+ * Harness's server, another person's agents and any other name never qualify.
72
+ */
73
+ export const PROPOSERS = MEMBERS.filter(
74
+ (entry) => entry.road === "hosted" && entry.runs === "self" && entry.target
75
+ ).map((entry) => entry.id);
76
+
63
77
  const runMayAsk = (command) =>
64
78
  command.startsWith("board.") ||
65
79
  command.startsWith("mcp.") ||
@@ -150,6 +164,144 @@ export function createRunAuthority({ store, installedAgents }) {
150
164
  : { started: false, reason: `It could not be authorized. ${start}` };
151
165
  };
152
166
 
167
+ // Why a proposed turn did not start, by what the store found (authorizeProposed): the end of "<agent> waits for your
168
+ // Start: ...".
169
+ const proposedWhy = (why, { target, proposer, folder }) =>
170
+ ({
171
+ off: "its standing permission is off.",
172
+ "not-proposer": `it starts on ${nameOf(proposer)}'s asks only if you let it: npx tryharness board standing ${target} --from ${proposer}`,
173
+ outside: `${folder} is outside the folders it may run in without asking.`,
174
+ cap: "it already started its runs for today without asking, its daily limit.",
175
+ gone: "its turn could not be authorized.",
176
+ })[why];
177
+
178
+ // Why an ask from one of the person's own agents elsewhere cannot use a standing permission at all, or null.
179
+ // `hosted`: it came from Harness's server itself (HOSTED_CALLER), never a local process or another computer.
180
+ const askRefusal = (ask) => {
181
+ const proposer = String(ask?.proposer ?? "");
182
+ return !PROPOSERS.includes(proposer)
183
+ ? `${nameOf(proposer)} is not one of your own agents that may start it.`
184
+ : ask.hosted !== true || ask.window
185
+ ? `${nameOf(proposer)}'s ask did not come through Harness as its asks do.`
186
+ : ask.limited
187
+ ? `${nameOf(proposer)} asked from a held-in run.`
188
+ : ask.guard?.verdict !== "clean" || ask.guard.unavailable
189
+ ? `the guard on this computer did not read ${nameOf(proposer)}'s words as clean.`
190
+ : null;
191
+ };
192
+ // Authorized on the rule in one transaction (store.mjs authorizeProposed), its receipt naming the folder checked
193
+ // and the computer it is for, which proposedHold checks again before it starts.
194
+ const authorizeOnRule = (task, proposer, folder, scratch = null) => {
195
+ const why = store.authorizeProposed(task.id, {
196
+ agent: task.target_agent,
197
+ proposer,
198
+ since: startOfToday(),
199
+ covered: (rule) => !folder || covers(rule, folder),
200
+ folder,
201
+ scratch,
202
+ });
203
+ return why
204
+ ? {
205
+ started: false,
206
+ reason: proposedWhy(why, {
207
+ target: task.target_agent,
208
+ proposer,
209
+ folder,
210
+ }),
211
+ }
212
+ : { started: true };
213
+ };
214
+
215
+ /**
216
+ * One of the person's own agents elsewhere (PROPOSERS) asked a coding agent here for a turn in a thread whose own work
217
+ * does not run on the person's go (threadAuthority.mjs threadMayRun: another agent wrote it). The turn starts only
218
+ * on the coding agent's standing permission, where the person named that asker on it: its words reached here through
219
+ * Harness's server and the guard on this computer read them clean, from no restricted run, review or linked window.
220
+ * It counts against the agent's daily limit like any standing run and keeps the agent-written label; the thread's
221
+ * own folder is the one checked (null: a fresh scratch folder of the thread's, which holds nothing of the person's).
222
+ *
223
+ * `ask`: { proposer, hosted, guard, limited, window }, as the thread heard it. Returns { started } or { started:
224
+ * false, reason }, the reason ending "<agent> waits for your Start: ".
225
+ */
226
+ const admitProposed = (wake, ask, folder) => {
227
+ const reason = askRefusal(ask);
228
+ return reason
229
+ ? { started: false, reason }
230
+ : authorizeOnRule(wake, String(ask.proposer), folder);
231
+ };
232
+ /**
233
+ * The task itself one of the person's own agents elsewhere posted for a coding agent (post_task), started on the same
234
+ * standing permission and the same checks as admitProposed: the poster is the asker, so no second ask is needed. A
235
+ * task naming no folder runs in its thread's scratch folder: `scratch`, made here when it runs here, or null for
236
+ * another computer, which makes its own (machineRuns.mjs).
237
+ */
238
+ const admitPosted = (task, ask, { scratch = null } = {}) => {
239
+ const reason =
240
+ askRefusal(ask) ??
241
+ (task.origin_agent !== ask.proposer ||
242
+ task.trust !== "agent" ||
243
+ task.kind !== "task" ||
244
+ !task.parent_id ||
245
+ !RUNNERS.has(task.target_agent)
246
+ ? "it is not a task that agent posted for a coding agent."
247
+ : null);
248
+ return reason
249
+ ? { started: false, reason }
250
+ : authorizeOnRule(
251
+ task,
252
+ String(ask.proposer),
253
+ task.run_workspace ?? null,
254
+ task.run_workspace ? null : scratch
255
+ );
256
+ };
257
+
258
+ // Why a turn admitProposed or admitPosted started may no longer start, or null: the person set the agent to wait,
259
+ // took the asker off the rule, no longer covers the folder it was admitted in, lowered the day's limit below the
260
+ // runs already started, or the task now names another agent, folder or computer than the receipt it was admitted
261
+ // with; or its thread is no longer open. Its run is already
262
+ // counted for the day, so the limit is checked again only when the rule changed after it was admitted.
263
+ const proposedHold = (task) => {
264
+ if (task.run_authorized_by !== "standing") return null;
265
+ const proposal = store.standingProposal(task.id);
266
+ if (!proposal) return null;
267
+ const [rule] = store.standing([task.target_agent], startOfToday());
268
+ const thread = task.parent_id ? store.getTask(task.parent_id) : null;
269
+ const changed = rule?.set_at !== proposal.rule_set_at;
270
+ return rule?.mode === "off"
271
+ ? `${nameOf(task.target_agent)} is set to wait for your Start.`
272
+ : !rule?.proposers.includes(proposal.proposer)
273
+ ? `you took ${nameOf(proposal.proposer)}'s asks off ${nameOf(task.target_agent)}'s standing permission.`
274
+ : proposal.folder && !covers(rule, proposal.folder)
275
+ ? `${proposal.folder} is no longer among the folders it may run in without asking.`
276
+ : changed && rule.runs_today > rule.daily_cap
277
+ ? "you lowered its daily limit below the runs it already started today."
278
+ : (Object.hasOwn(proposal, "machine") &&
279
+ (task.target_machine ?? null) !== proposal.machine) ||
280
+ (Object.hasOwn(proposal, "agent") &&
281
+ task.target_agent !== proposal.agent) ||
282
+ (Object.hasOwn(proposal, "workspace") &&
283
+ (task.run_workspace ?? null) !== proposal.workspace)
284
+ ? "it changed after it was admitted: another agent, folder or computer."
285
+ : thread?.status !== "open"
286
+ ? `the thread is ${thread?.status ?? "gone"}.`
287
+ : null;
288
+ };
289
+ /**
290
+ * Checked just before a turn admitProposed started is handed to an agent, here or to another computer: one that may
291
+ * no longer start waits for the person's Start again, and its thread hears why. Why it was held, or null.
292
+ */
293
+ const recheckProposed = (task) => {
294
+ const why = proposedHold(task);
295
+ if (why && store.withdrawProposed(task.id) && task.parent_id)
296
+ store.roomPost({
297
+ goalId: task.parent_id,
298
+ author: "harness",
299
+ kind: "note",
300
+ text: `${nameOf(task.target_agent)} waits for your Start: ${why}`,
301
+ });
302
+ return why;
303
+ };
304
+
153
305
  /**
154
306
  * Who a call on the local socket is, before anything acts on it; a refusal to answer with, or null. A call carrying a
155
307
  * run's capability is that run's agent with that run's limits, whatever agent it names. Without one, a call as the
@@ -216,6 +368,10 @@ export function createRunAuthority({ store, installedAgents }) {
216
368
  standingRules,
217
369
  standingVerdict,
218
370
  applyStanding,
371
+ admitProposed,
372
+ admitPosted,
373
+ proposedHold,
374
+ recheckProposed,
219
375
  checkCaller,
220
376
  markPrompt,
221
377
  };
package/lib/runWorker.mjs CHANGED
@@ -119,6 +119,10 @@ export function createRunWorker({
119
119
  })) {
120
120
  const agent = task.target_agent;
121
121
  if (dispatches?.refusal(task.id)) continue;
122
+ if (authority.recheckProposed?.(task)) {
123
+ notifyBoard(store.getTask(task.id));
124
+ continue;
125
+ }
122
126
  // Where a task runs is settled once, before its slot: a run T3 carries out holds its thread, not a folder.
123
127
  if (task.kind === "task" && store.meta(`t3-run:${task.id}`) === null)
124
128
  store.meta(`t3-run:${task.id}`, taskInT3(task, agent) ? "1" : "0");
@@ -152,6 +156,15 @@ export function createRunWorker({
152
156
  void startBoardRun(task, agent);
153
157
  }
154
158
  };
159
+ // A turn started on another of the person's agents' asks, checked again once its preparation (which may wait on the
160
+ // model) is done: one that may no longer start goes back to wait for the person's Start (runAuthority.mjs).
161
+ const heldOnStart = (task) => {
162
+ const why = authority.proposedHold?.(store.getTask(task.id));
163
+ if (!why) return null;
164
+ store.requeueRun(task.id);
165
+ authority.recheckProposed(store.getTask(task.id));
166
+ return why;
167
+ };
155
168
  const startBoardRun = async (task, agent) => {
156
169
  const wake = task.kind === "wake";
157
170
  const room = !wake && task.parent_id ? store.getTask(task.parent_id) : null;
@@ -179,7 +192,7 @@ export function createRunWorker({
179
192
  const { model, effort } = chosen;
180
193
  // Preparation may await context/model selection. Recheck a queued dispatch
181
194
  // immediately before any executor or secret-use grant receives the task.
182
- const refusal = dispatches?.begin(task.id);
195
+ const refusal = dispatches?.begin(task.id) ?? heldOnStart(task);
183
196
  if (refusal) {
184
197
  activeRuns.delete(slotOf(task));
185
198
  store.requeueRun(task.id);
@@ -190,7 +203,11 @@ export function createRunWorker({
190
203
  const t3 = inT3 ? t3Turn(task, agent, { model, effort }) : null;
191
204
  // The person's environment grants (vault.mjs), never for a run they did not authorize: the values are in this
192
205
  // run's environment, and what it says is scrubbed of them.
193
- const secrets = restricted ? null : vaultEnv(task, agent);
206
+ // Nor for a turn another of the person's agents asked for on standing permission: that grants a start, no secrets.
207
+ const secrets =
208
+ restricted || store.standingProposal(task.id)
209
+ ? null
210
+ : vaultEnv(task, agent);
194
211
  const granted = secrets && Object.keys(secrets.env).length ? secrets : null;
195
212
  startTurn(task);
196
213
  taskRuns.startTask(
@@ -415,6 +432,7 @@ export function createRunWorker({
415
432
  runBoard,
416
433
  interruptAll,
417
434
  hold,
435
+ held: () => runsHeld,
418
436
  activeRuns: {
419
437
  get: (slot) => activeRuns.get(slot),
420
438
  values: () => activeRuns.values(),
package/lib/store.mjs CHANGED
@@ -32,6 +32,11 @@ export const DEFAULT_DAILY_RUNS = 10;
32
32
  export const FAILURE_CAUSES = ["person", "start", "exit", "agent"];
33
33
  // An agent's record leaves out failures that say nothing about it: the person's stop and a run that never started.
34
34
  const AGENTS_OWN = "not (status = 'failed' and failure in ('person', 'start'))";
35
+ // What an asker hears of under finished (finishedFor), and the receipt naming one such result: the full task id, the
36
+ // status it reached and when it was reported, so a task asked again and reported anew is a new result to tell.
37
+ const FINISHED_STATUSES = "('done', 'failed', 'needs_input')";
38
+ const RESULT_RECEIPT =
39
+ "t.id || ':' || t.status || ':' || coalesce(t.reported_at, t.updated_at)";
35
40
  // What the swarm's memory can show (swarmMemory.mjs): what was said, made, checked or asked in the person's threads and
36
41
  // tasks. A contribution's thread is its own task when that is a thread, else its task's parent thread.
37
42
  export const MEMORY_KINDS = [
@@ -176,7 +181,8 @@ export function openStore(file) {
176
181
  mode text not null,
177
182
  workspaces text not null,
178
183
  daily_cap integer not null,
179
- set_at text not null
184
+ set_at text not null,
185
+ proposers text not null default '[]'
180
186
  );
181
187
  create table if not exists board_goals (
182
188
  goal_id text primary key,
@@ -448,6 +454,14 @@ export function openStore(file) {
448
454
  db.exec(
449
455
  "alter table board_standing add column mode text not null default 'named'"
450
456
  );
457
+ if (
458
+ !db
459
+ .all("pragma table_info(board_standing)")
460
+ .some((column) => column.name === "proposers")
461
+ )
462
+ db.exec(
463
+ "alter table board_standing add column proposers text not null default '[]'"
464
+ );
451
465
  if (
452
466
  !db
453
467
  .all("pragma table_info(board_contributions)")
@@ -575,6 +589,15 @@ export function openStore(file) {
575
589
  // What the auditor's code found comparing a report's claims with its receipts (audit.mjs).
576
590
  if (!boardColumns.has("audit") && boardColumns.size)
577
591
  db.exec("alter table board_tasks add column audit text");
592
+ // Only the asker's explicit receipt establishes delivery. A pre-receipt board has no such evidence; its results
593
+ // remain available after upgrade rather than assuming an unrelated last-seen timestamp meant they were read.
594
+ db.exec(`create table if not exists board_result_acks (
595
+ agent text not null,
596
+ receipt text not null,
597
+ task_id text not null,
598
+ acked_at text not null,
599
+ primary key (agent, receipt)
600
+ )`);
578
601
 
579
602
  for (const [table, columns] of [
580
603
  ["board_tasks", ["returned"]],
@@ -1158,12 +1181,42 @@ export function openStore(file) {
1158
1181
  new Date().toISOString()
1159
1182
  );
1160
1183
  },
1184
+ // Back to the default; the agents the person let start it (setStandingProposers) stay theirs to take back.
1161
1185
  resetStanding(agent) {
1186
+ const row = execute(
1187
+ "get",
1188
+ "select proposers from board_standing where agent = ?",
1189
+ agent
1190
+ );
1191
+ if (!row) return false;
1192
+ if (JSON.parse(row.proposers || "[]").length)
1193
+ return (
1194
+ execute(
1195
+ "run",
1196
+ "update board_standing set mode = 'default', workspaces = '[]', daily_cap = ?, set_at = ? where agent = ?",
1197
+ DEFAULT_DAILY_RUNS,
1198
+ new Date().toISOString(),
1199
+ agent
1200
+ ).changes === 1
1201
+ );
1162
1202
  return (
1163
1203
  execute("run", "delete from board_standing where agent = ?", agent)
1164
1204
  .changes === 1
1165
1205
  );
1166
1206
  },
1207
+ // The person's own agents elsewhere whose clean asks in a thread start this agent's turn on its standing permission
1208
+ // (runAuthority.mjs admitProposed). Its mode, folders and daily limit stay as they are.
1209
+ setStandingProposers(agent, proposers) {
1210
+ execute(
1211
+ "run",
1212
+ `insert into board_standing(agent, mode, workspaces, daily_cap, set_at, proposers) values(?, 'default', '[]', ?, ?, ?)
1213
+ on conflict(agent) do update set proposers = excluded.proposers, set_at = excluded.set_at`,
1214
+ agent,
1215
+ DEFAULT_DAILY_RUNS,
1216
+ new Date().toISOString(),
1217
+ JSON.stringify(proposers)
1218
+ );
1219
+ },
1167
1220
  // One rule per agent installed here, with the runs it started since `since`.
1168
1221
  standing(agents, since) {
1169
1222
  const rows = new Map(
@@ -1189,6 +1242,7 @@ export function openStore(file) {
1189
1242
  workspaces,
1190
1243
  daily_cap: row ? Number(row.daily_cap) : DEFAULT_DAILY_RUNS,
1191
1244
  set_at: row?.set_at || null,
1245
+ proposers: JSON.parse(row?.proposers || "[]"),
1192
1246
  runs_today:
1193
1247
  Number(this.meta(`prompt-quota:${since}:${agent}`) || "0") +
1194
1248
  Number(
@@ -2931,6 +2985,87 @@ export function openStore(file) {
2931
2985
  );
2932
2986
  return written.changes === 1;
2933
2987
  },
2988
+ /**
2989
+ * A thread's turn that one of the person's own agents elsewhere asked for, or the task it posted itself for a coding
2990
+ * agent, started on its agent's standing permission: the rule read, the day's runs counted and the row authorized in
2991
+ * one transaction, so two asks at once never both take the last run of the day. It counts as one of the day's
2992
+ * standing runs, whoever asked. `covered`: whether the rule covers `folder`, the folder checked (runAuthority.mjs).
2993
+ * `scratch`: where a posted task naming no folder runs on this computer; another computer's makes its own. The
2994
+ * receipt keeps the rule's revision, the folder checked, and the agent, folder and computer it was admitted to run
2995
+ * with, for the check again before it starts (runAuthority.mjs proposedHold). Null when
2996
+ * it started; otherwise why not.
2997
+ */
2998
+ authorizeProposed(
2999
+ id,
3000
+ { agent, proposer, since, covered, folder = null, scratch = null }
3001
+ ) {
3002
+ db.exec("begin immediate");
3003
+ try {
3004
+ const rule = this.standing([agent], since)[0];
3005
+ const why =
3006
+ rule.mode === "off"
3007
+ ? "off"
3008
+ : !rule.proposers.includes(proposer)
3009
+ ? "not-proposer"
3010
+ : !covered(rule)
3011
+ ? "outside"
3012
+ : rule.runs_today >= rule.daily_cap
3013
+ ? "cap"
3014
+ : null;
3015
+ const now = new Date().toISOString();
3016
+ const written =
3017
+ !why &&
3018
+ execute(
3019
+ "run",
3020
+ `update board_tasks set run_authorized_by = 'standing', run_authorized_at = @now, updated_at = @now, version = version + 1,
3021
+ run_workspace = case when kind = 'task' then coalesce(run_workspace, @scratch) else run_workspace end
3022
+ where id = @id and status = 'open' and trust = 'agent' and target_agent = @agent and run_authorized_at is null
3023
+ and id not in (select task_id from board_threads)
3024
+ and ((kind = 'wake' and (run_workspace is not null or target_machine is not null))
3025
+ or (kind = 'task' and origin_agent = @proposer and parent_id is not null
3026
+ and coalesce(run_workspace, @scratch, target_machine) is not null))`,
3027
+ { id, agent, proposer, scratch, now }
3028
+ ).changes === 1;
3029
+ if (written)
3030
+ this.meta(
3031
+ `standing-proposal:${id}`,
3032
+ JSON.stringify({
3033
+ proposer,
3034
+ rule_set_at: rule.set_at,
3035
+ folder,
3036
+ agent,
3037
+ workspace: this.getTask(id).run_workspace ?? null,
3038
+ machine: this.getTask(id).target_machine ?? null,
3039
+ at: now,
3040
+ })
3041
+ );
3042
+ db.exec("commit");
3043
+ return why ?? (written ? null : "gone");
3044
+ } catch (error) {
3045
+ if (db.inTransaction) db.exec("rollback");
3046
+ throw error;
3047
+ }
3048
+ },
3049
+ /** Who asked for a turn started on standing permission (authorizeProposed), or null. */
3050
+ standingProposal(id) {
3051
+ try {
3052
+ return JSON.parse(this.meta(`standing-proposal:${id}`) || "null");
3053
+ } catch {
3054
+ return null;
3055
+ }
3056
+ },
3057
+ // A turn started on another agent's ask that may no longer start: it waits for the person's Start again.
3058
+ withdrawProposed(id) {
3059
+ const now = new Date().toISOString();
3060
+ const written = execute(
3061
+ "run",
3062
+ `update board_tasks set run_authorized_by = null, run_authorized_at = null, updated_at = @now, version = version + 1
3063
+ where id = @id and status = 'open' and run_authorized_by = 'standing'`,
3064
+ { id, now }
3065
+ );
3066
+ if (written.changes === 1) this.meta(`standing-proposal:${id}`, "");
3067
+ return written.changes === 1;
3068
+ },
2934
3069
  // Tasks a computer should run now: authorized, still open, for an agent installed there. `machine`: that computer;
2935
3070
  // home runs the tasks meant for it and for no computer in particular, a worker (`only`) just those meant for it.
2936
3071
  runnableTasks(agents, machine = null, { only = false } = {}) {
@@ -3768,17 +3903,67 @@ export function openStore(file) {
3768
3903
  null
3769
3904
  );
3770
3905
  },
3771
- // Work an agent asked for that finished, failed or came back with a question since it last called the board: how an
3772
- // asker that cannot be woken (the Claude app, ChatGPT) learns of its answers.
3773
- finishedFor(agent, since) {
3906
+ // Work an agent asked for that finished, failed or came back with a question and whose result it has not yet
3907
+ // acknowledged: how an asker that cannot be woken (the Claude app, ChatGPT), or one woken by mail (Grok Bot), learns
3908
+ // of its answers. Any other board call, a list or a read leaves a result here; only the asker's own receipt for that
3909
+ // very result (ackResult) takes it off, so a result is never spent by an unrelated call or a restart.
3910
+ finishedFor(agent) {
3774
3911
  return execute(
3775
3912
  "all",
3776
- `select id, objective, target_agent, claimed_by, status, updated_at from board_tasks
3777
- where origin_agent = ? and kind = 'task' and removed_at is null and status in ('done', 'failed', 'needs_input') and updated_at > ?
3913
+ `select id, objective, target_agent, claimed_by, status, parent_id, updated_at, reported_at,
3914
+ ${RESULT_RECEIPT} as receipt
3915
+ from board_tasks t
3916
+ where origin_agent = ? and kind = 'task' and removed_at is null and status in ${FINISHED_STATUSES}
3917
+ and not exists (select 1 from board_result_acks a where a.agent = t.origin_agent and a.receipt = ${RESULT_RECEIPT})
3778
3918
  order by updated_at desc limit 20`,
3919
+ agent
3920
+ ).map((row) => ({ ...row, root_id: this.rootIdOf(row.id) }));
3921
+ },
3922
+ // The asker's receipt for one result, exactly as finished gave it: the task, its status and when it was reported.
3923
+ // Another agent's receipt, or one for a result the task no longer holds (asked again, answered and reported anew),
3924
+ // takes nothing. A receipt grants nothing either; it only stops the result being told again.
3925
+ ackResult(agent, taskId, receipt) {
3926
+ const current = execute(
3927
+ "get",
3928
+ `select origin_agent, ${RESULT_RECEIPT} as receipt from board_tasks t
3929
+ where id = ? and kind = 'task' and removed_at is null and status in ${FINISHED_STATUSES}`,
3930
+ taskId
3931
+ );
3932
+ if (!current || current.origin_agent !== agent)
3933
+ return {
3934
+ acked: false,
3935
+ reason:
3936
+ "only the agent that asked for this work can acknowledge its result",
3937
+ };
3938
+ if (current.receipt !== String(receipt))
3939
+ return {
3940
+ acked: false,
3941
+ reason: "that receipt is not this task's current result",
3942
+ receipt: current.receipt,
3943
+ };
3944
+ execute(
3945
+ "run",
3946
+ "insert or ignore into board_result_acks(agent, receipt, task_id, acked_at) values (?, ?, ?, ?)",
3779
3947
  agent,
3780
- since || "1970-01-01T00:00:00.000Z"
3948
+ current.receipt,
3949
+ taskId,
3950
+ new Date().toISOString()
3781
3951
  );
3952
+ return { acked: true, receipt: current.receipt };
3953
+ },
3954
+ // The task a chain of handoffs started from: the asker's original request, so a result finds its way back to it.
3955
+ rootIdOf(taskId) {
3956
+ let id = taskId;
3957
+ for (let depth = 0; depth < 50; depth++) {
3958
+ const parent = execute(
3959
+ "get",
3960
+ "select parent_id from board_tasks where id = ?",
3961
+ id
3962
+ )?.parent_id;
3963
+ if (!parent || parent === taskId) return id;
3964
+ id = parent;
3965
+ }
3966
+ return id;
3782
3967
  },
3783
3968
  // Messages another person's agent sent on this agent's tasks since it last read the board from `machine`.
3784
3969
  unreadFor(agent, machine = null) {
package/lib/swarm.mjs CHANGED
@@ -163,6 +163,8 @@ export function createSwarm({
163
163
  roomAgents,
164
164
  mentionsIn,
165
165
  wakeFor,
166
+ // The computers a message sends its agents to (threadActions.mjs computerAddress).
167
+ computerAddress,
166
168
  notifyBoard,
167
169
  goalCommand,
168
170
  stopThreadRuns,
@@ -1107,6 +1109,10 @@ export function createSwarm({
1107
1109
  ok: false,
1108
1110
  error: `name who the thread is for with @, one of: ${roomAgents.filter((name) => name !== agent && name !== "harness").join(", ")}`,
1109
1111
  };
1112
+ // Where its agents work is settled before the thread exists: a choice that cannot be read starts nothing.
1113
+ const target = request.targetMachine ?? null;
1114
+ const address = computerAddress(text, agent, { target });
1115
+ if (!address.ok) return { ok: false, error: address.error };
1110
1116
  const objective =
1111
1117
  text
1112
1118
  .split("\n")
@@ -1131,21 +1137,32 @@ export function createSwarm({
1131
1137
  const [from] = store.threadsWorkedIn(agent);
1132
1138
  if (from)
1133
1139
  linkThreads(store.getTask(from), store.getTask(thread.id), agent);
1134
- const first = store.roomPost({
1135
- goalId: thread.id,
1136
- author: agent,
1137
- kind: "post",
1138
- text,
1139
- mentions: addressed(store.getTask(thread.id), text),
1140
- machine,
1141
- });
1142
- wakeFor(thread.id, first, agent);
1143
- notifyBoard(store.getTask(thread.id));
1144
- return {
1145
- ok: true,
1146
- thread: summary(store.getTask(thread.id)),
1147
- note: "Agents here run only after the person's Start; read the thread with read_room and add to it with post_to_room.",
1140
+ // The first message crosses the same admission seam as every later post:
1141
+ // guard readings and actual caller limits must survive thread creation.
1142
+ const posted = goalCommand(
1143
+ {
1144
+ ...request,
1145
+ command: "board.room.post",
1146
+ id: thread.id,
1147
+ text,
1148
+ ask: [...team],
1149
+ },
1150
+ agent,
1151
+ machine
1152
+ );
1153
+ const started = (result) => {
1154
+ notifyBoard(store.getTask(thread.id));
1155
+ return {
1156
+ ...result,
1157
+ thread: summary(store.getTask(thread.id)),
1158
+ note:
1159
+ result.note ??
1160
+ "Read the thread with read_room and add to it with post_to_room; its tasks report whether work is running or waiting.",
1161
+ };
1148
1162
  };
1163
+ return posted?.pending
1164
+ ? { pending: Promise.resolve(posted.pending).then(started) }
1165
+ : started(posted);
1149
1166
  }
1150
1167
  if (agent !== "user" && command === "board.swarm.stop") {
1151
1168
  const thread = store.getTask(String(request.id || ""));
@@ -1413,6 +1430,9 @@ export function createSwarm({
1413
1430
  ]);
1414
1431
  const picked = picksIn(store, text, roomAgents);
1415
1432
  if (picked.error) return { ok: false, error: picked.error };
1433
+ const target = request.targetMachine ?? null;
1434
+ const address = computerAddress(text, "user", { target });
1435
+ if (!address.ok) return { ok: false, error: address.error };
1416
1436
  if (from) {
1417
1437
  const agentName = String(from.agent || ""),
1418
1438
  sessionId = String(from.sessionId || "");
@@ -1477,7 +1497,7 @@ export function createSwarm({
1477
1497
  };
1478
1498
  const hear = ({ id, first }) => {
1479
1499
  const opened = store.getTask(id);
1480
- wakeFor(id, first, "user");
1500
+ wakeFor(id, first, "user", undefined, { target });
1481
1501
  if (!to) heardBy(opened, first, text);
1482
1502
  heardPerson(opened, first);
1483
1503
  };