agent-lyceum 0.54.1 → 0.56.0

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 (61) hide show
  1. package/README.md +2 -0
  2. package/README.zh-TW.md +2 -0
  3. package/dist/adapters/cursor.js +5 -1
  4. package/dist/attribution.d.ts +2 -0
  5. package/dist/cli.js +33 -7
  6. package/dist/config.d.ts +3 -0
  7. package/dist/config.js +5 -1
  8. package/dist/dispatcher.js +7 -2
  9. package/dist/doctor.js +12 -3
  10. package/dist/format.d.ts +4 -1
  11. package/dist/format.js +40 -2
  12. package/dist/mailbox.d.ts +29 -1
  13. package/dist/mailbox.js +56 -15
  14. package/dist/memory-tidy.js +18 -2
  15. package/dist/message-store.d.ts +10 -0
  16. package/dist/message-store.js +26 -0
  17. package/dist/open-pr.d.ts +13 -1
  18. package/dist/open-pr.js +12 -4
  19. package/dist/playbook.d.ts +28 -0
  20. package/dist/playbook.js +40 -0
  21. package/dist/policy.d.ts +12 -0
  22. package/dist/policy.js +55 -0
  23. package/dist/project-lock.d.ts +16 -0
  24. package/dist/project-lock.js +34 -2
  25. package/dist/prompt.d.ts +2 -0
  26. package/dist/prompt.js +25 -7
  27. package/dist/quota.js +62 -10
  28. package/dist/records.d.ts +10 -0
  29. package/dist/records.js +46 -0
  30. package/dist/review-gate.d.ts +33 -0
  31. package/dist/review-gate.js +78 -0
  32. package/dist/run-cleanup.d.ts +9 -2
  33. package/dist/run-cleanup.js +67 -4
  34. package/dist/run-outcome.d.ts +4 -0
  35. package/dist/run-outcome.js +8 -1
  36. package/dist/run-session.d.ts +27 -0
  37. package/dist/run-session.js +347 -39
  38. package/dist/run-store.d.ts +17 -3
  39. package/dist/run-store.js +10 -2
  40. package/dist/scaffold.d.ts +1 -1
  41. package/dist/scaffold.js +5 -2
  42. package/dist/schema.d.ts +12 -0
  43. package/dist/schema.js +6 -0
  44. package/dist/status-watch.d.ts +4 -2
  45. package/dist/status-watch.js +27 -5
  46. package/dist/status.d.ts +4 -2
  47. package/dist/status.js +11 -8
  48. package/dist/task-bind.d.ts +4 -0
  49. package/dist/task-bind.js +42 -0
  50. package/dist/wake-cap.d.ts +5 -0
  51. package/dist/wake-cap.js +11 -0
  52. package/dist/worktree.d.ts +153 -6
  53. package/dist/worktree.js +378 -15
  54. package/package.json +1 -1
  55. package/web/dist/public/assets/index-CVkc3V2B.js +92 -0
  56. package/web/dist/public/assets/index-zT-RkrlC.css +2 -0
  57. package/web/dist/public/index.html +2 -2
  58. package/web/dist/server/hub.js +40 -5
  59. package/web/dist/start.js +45 -5
  60. package/web/dist/public/assets/index-BPY1-W3F.css +0 -2
  61. package/web/dist/public/assets/index-CbQs5aMP.js +0 -92
@@ -12,25 +12,32 @@ import { addBatch, askersWithAnswers, askReplyPath, checkAnswers, describeCheck,
12
12
  import { deliver, deliverOnce, ensureAgentDirs, ensureProjectDirs, finishDone, listUnread, PENDING_DIR, readMessageNoFollow, rejectDone, routeOutboxes, unreadFiles } from "./mailbox.js";
13
13
  import { instanceContainment } from "./instance-containment.js";
14
14
  import { DEFAULT_MAX_INSTANCES, assertInstancesResumable, heldStallKey, instanceCap, ownersOf, parseSlotName, planAssignments, roleOfName } from "./instances.js";
15
- import { abandonClaim, attemptLogDir, sourceIdOf, beginAttempt, claimMessages, commitClaim, fault, finishAttempt, loadClaim, markOutputReady, parkOutbox, recoverRunMail, RouteJournal } from "./message-store.js";
15
+ import { abandonClaim, attemptLogDir, sourceIdOf, beginAttempt, claimMessages, commitClaim, fault, finishAttempt, loadClaim, markOutputReady, parkOutbox, previousClaim, recoverRunMail, setClaimReadOnly, RouteJournal } from "./message-store.js";
16
16
  import { createRunLog } from "./run-log.js";
17
17
  import { endOutcome, resolveDoneOutcome } from "./run-outcome.js";
18
- import { inboxDir, outboxDir, proposalsDir, sharedIndex } from "./policy.js";
18
+ import { crossRuntimeBlock } from "./review-gate.js";
19
+ import { unboundCommands } from "./task-bind.js";
20
+ import { capBatch, DEFAULT_MAX_AWAKE } from "./wake-cap.js";
21
+ import { wakeIsReadOnly } from "./playbook.js";
22
+ import { coordinatePolicy, inboxDir, osSandboxAvailable, outboxDir, proposalsDir, readOnlyPolicy, sharedIndex } from "./policy.js";
19
23
  import { buildSystemPrompt, buildUserPrompt, pickMessages } from "./prompt.js";
20
24
  import { collectDrafts, priorFailedAttempts, redoUserPrompt } from "./redo.js";
21
25
  import { atomicWrite, readFileCapped } from "./fs-util.js";
22
26
  import { trailers, withTrailers } from "./attribution.js";
23
- import { assertWorktreeRunnable, collectAgentChanges, dirtyPaths, existingAgentWorkspace, finishLeadBranch, integrateAgentChanges, prepareAgentWorkspace, recutLeadWorkspace, refusedIntegration, snapshotBase, snapshotHead, toplevel } from "./worktree.js";
24
- import { workingTreeHash } from "./worktree.js";
25
- import { bindRunProject, newRunId, newRunState, roundLimit, roundsLabel, saveRunState } from "./run-store.js";
27
+ import { agentGit, assertWorktreeRunnable, beginCheckoutRun, checkoutHeadProblem, collectAgentChanges, commitWorkspace, dirtyPaths, existingAgentWorkspace, finishCheckoutBranch, finishLeadBranch, integrateAgentChanges, prepareAgentWorkspace, recutLeadWorkspace, refusedIntegration, remoteBaseNote, borrowedEdits, restoreWorkspaceEdits, rollbackCheckoutStart, snapshotBase, snapshotCheckout, snapshotCommit, snapshotHead, toplevel, workspaceDirty, workspaceStatusPaths, workingTreeHash, PINNED_CONFIG } from "./worktree.js";
28
+ import { bindRunProject, CHECKOUT_SCHEMA_VERSION, newRunId, newRunState, roundLimit, roundsLabel, saveRunState } from "./run-store.js";
26
29
  import { soloProject } from "./solo.js";
27
30
  import { taskMessageBody } from "./task.js";
28
31
  import { must } from "./assert.js";
29
32
  import { modelForTier, wakeTier } from "./tiers.js";
30
- import { openPullRequest, prBody, prTitle, realRunner } from "./open-pr.js";
33
+ import { manualPrCommands, openPullRequest, prBody, prTitle, realRunner } from "./open-pr.js";
31
34
  export { newRunId };
32
35
  export const RESULT_FILE = "result.md";
33
36
  /** How many times a non-conforming `done` goes back to the lead before it is accepted as `partial`. */
37
+ /** The acceptance line of a follow-up task. It names the task file, so the mail's acceptance check can see a real path. */
38
+ export function followupAcceptance(taskFile) {
39
+ return `- The follow-up's Goal is met, and every item under Acceptance criteria in \`${taskFile}\` still holds.`;
40
+ }
34
41
  export const MAX_DONE_REJECTIONS = 2;
35
42
  /** How many times a malformed `ask` goes back to its sender before the lead is told instead. */
36
43
  export const MAX_ASK_REJECTIONS = 2;
@@ -119,6 +126,10 @@ export class RunSession {
119
126
  resume;
120
127
  /** The handoff index as this segment started; the lead is noted when it is the same at `done`. */
121
128
  sharedAtStart;
129
+ /** Set once at run start when `bind_task` names checks that are not in project.yaml. A note only; it does not change the outcome. */
130
+ bindNote;
131
+ /** Checkout at the start of a read-only wake. The claim stores the same pair so a resume can put paths back. */
132
+ roSnaps = new Map();
122
133
  invoke;
123
134
  say;
124
135
  cfg;
@@ -196,11 +207,20 @@ export class RunSession {
196
207
  const { plan } = opts;
197
208
  const concurrent = plan.leadWorktree;
198
209
  const wsMode = plan.mode;
210
+ // A checkout run whose task never reached the lead cannot say what it did or did not do on its branch: refuse before anything is written
211
+ // (`end_reason` included). The branch named is the one recorded in the state, never one derived from the lead's current name.
212
+ if (resume?.workspace_mode === "checkout" && resume.task_sent !== true) {
213
+ throw new Error(`Run ${runId} works in the project checkout (task_branch ${resume.task_branch ?? "not recorded"}), but its state has no task_sent: the task was never recorded as delivered to ${project.lead}, so the run cannot be resumed.`);
214
+ }
215
+ const checkout = plan.taskBranch !== undefined || resume?.workspace_mode === "checkout";
216
+ const stateMode = checkout ? "checkout" : wsMode;
199
217
  if (resume && wsMode === "worktree")
200
218
  assertWorktreeRunnable(project);
201
219
  // Concurrent runs: the lead works in its own worktree cut from HEAD, so no other run (and not you) shares its files.
202
220
  let leadSpace;
203
221
  let recut = false;
222
+ if (!resume && plan.fetchFailed)
223
+ say(" git fetch origin failed or timed out; using the remote refs already in the repo");
204
224
  if (concurrent && resume) {
205
225
  leadSpace = existingAgentWorkspace(project, runId, project.lead);
206
226
  if (!leadSpace)
@@ -222,17 +242,24 @@ export class RunSession {
222
242
  const log = createRunLog(path.join(runDir, "log.jsonl"), cfg.log_max_bytes);
223
243
  if (concurrent && !resume) {
224
244
  // Before the task is delivered or any state written, so a failure here leaves no half-started run.
225
- leadSpace = prepareAgentWorkspace(project, runId, project.lead, snapshotHead(project, runId));
245
+ // With a remote base the lead starts from it, not from whatever the local HEAD is.
246
+ leadSpace = prepareAgentWorkspace(project, runId, project.lead, plan.baseSha !== undefined ? snapshotCommit(project, runId, plan.baseSha) : snapshotHead(project, runId));
226
247
  const uncommitted = dirtyPaths(project.dir).length;
227
- say(` starting from HEAD ${leadSpace.base.slice(0, 8)}${uncommitted ? ` (your ${uncommitted} uncommitted file(s) are not part of this run)` : ""}; ${project.lead} works on branch ${leadSpace.branch}`);
248
+ const from = plan.baseSha !== undefined ? `${plan.baseRef ?? "the remote base"} ${leadSpace.base.slice(0, 8)}` : `HEAD ${leadSpace.base.slice(0, 8)}`;
249
+ say(` starting from ${from}${uncommitted ? ` (your ${uncommitted} uncommitted file(s) are not part of this run)` : ""}; ${project.lead} works on branch ${leadSpace.branch}`);
250
+ const note = plan.baseSha !== undefined ? remoteBaseNote(project, plan.baseSha, plan.baseRef) : undefined;
251
+ if (note)
252
+ say(` ${note}`);
228
253
  log("lead-workspace", { base: leadSpace.base, branch: leadSpace.branch, dir: leadSpace.dir, uncommitted });
229
254
  }
230
255
  if (!resume && plan.mode === "shared" && plan.reason) {
231
256
  say(` agents take turns in ${project.dir} (no separate git worktrees: ${plan.reason}); commit to a git repo to run them in parallel`);
232
257
  }
258
+ if (!resume && plan.mode === "worktree" && concurrent && plan.reason)
259
+ say(` ${project.lead} works in its own git worktree (${plan.reason})`);
233
260
  let state;
234
261
  if (resume) {
235
- state = { ...resume, max_rounds: roundLimit(resume, cfg.max_rounds), pid: process.pid, ended_at: undefined, end_reason: undefined, failure: undefined, workspace_mode: wsMode, outcome: undefined, outcome_note: undefined, verification: undefined, active: {}, wakes: [...resume.wakes] };
262
+ state = { ...resume, max_rounds: roundLimit(resume, cfg.max_rounds), pid: process.pid, ended_at: undefined, end_reason: undefined, failure: undefined, workspace_mode: stateMode, outcome: undefined, outcome_note: undefined, verification: undefined, active: {}, wakes: [...resume.wakes] };
236
263
  // A wake that was running when the process died never finished; keep it in the history as interrupted.
237
264
  for (const [agent, a] of Object.entries(resume.active ?? {})) {
238
265
  state.wakes.push({
@@ -277,10 +304,18 @@ export class RunSession {
277
304
  pid: process.pid,
278
305
  task_summary: t.subject,
279
306
  mail_layout: layout,
280
- workspace_mode: wsMode,
307
+ workspace_mode: stateMode,
281
308
  solo_agent: soloName,
282
309
  lead_workspace: concurrent ? true : undefined,
310
+ ...(plan.taskBranch !== undefined
311
+ ? { task_branch: plan.taskBranch, base_ref: plan.baseRef, base_sha: plan.baseSha, origin_url: plan.originUrl, ...(plan.checkoutFrom !== undefined ? { checkout_from: plan.checkoutFrom } : {}) }
312
+ : plan.baseSha !== undefined
313
+ ? { base_ref: plan.baseRef, base_sha: plan.baseSha, ...(plan.originUrl !== undefined ? { origin_url: plan.originUrl } : {}) }
314
+ : {}),
283
315
  });
316
+ // Only a checkout run is written as v4 (it must not be started by a binary that does not know its branch); the others stay as they were.
317
+ if (plan.taskBranch !== undefined)
318
+ state.schema_version = CHECKOUT_SCHEMA_VERSION;
284
319
  const seed = parseSteps(task.content, false);
285
320
  if (seed.length)
286
321
  state.steps = seed;
@@ -309,18 +344,49 @@ export class RunSession {
309
344
  to: project.lead,
310
345
  type: "task",
311
346
  subject: opts.followup.text.split("\n").find((l) => l.trim())?.slice(0, 80) ?? "Follow-up",
312
- body: `## Goal\n${opts.followup.text.trimEnd()}\n\n## Acceptance criteria\nAs stated in the goal; the earlier result still holds unless the goal changes it.\n\n## Scope\nThis run's earlier work and files.\n\n## Upstream\nThe previous final report is in \`${path.join(runDir, `done-${n}.md`)}\`; the original task is in \`${path.join(runDir, "task.md")}\`.${handoffLine}\n${state.step_base?.length ? "\n## Progress\nThe earlier checklist stays in the progress; your `## Steps` lists only this follow-up's steps, which are shown after it.\n" : ""}`,
347
+ body: `## Goal\n${opts.followup.text.trimEnd()}\n\n## Acceptance criteria\n${followupAcceptance(path.join(runDir, "task.md"))}\n\n## Scope\nThis run's earlier work and files.\n\n## Upstream\nThe previous final report is in \`${path.join(runDir, `done-${n}.md`)}\`; the original task is in \`${path.join(runDir, "task.md")}\`.${handoffLine}\n${state.step_base?.length ? "\n## Progress\nThe earlier checklist stays in the progress; your `## Steps` lists only this follow-up's steps, which are shown after it.\n" : ""}`,
313
348
  });
314
349
  log("reopen", { n });
315
350
  }
316
351
  }
317
352
  else {
318
353
  const t = taskMessageBody(task);
319
- guard.saveSnapshot(path.join(runDir, "snapshots"));
320
- deliver(project, { from: "user", to: project.lead, type: "task", subject: t.subject, body: t.body });
354
+ const cutting = checkout && opts.startCheckout === true;
355
+ if (cutting) {
356
+ // The state names the branch before git creates it, so a start that dies in between can be told from one that never began.
357
+ saveState();
358
+ beginCheckoutRun(project.dir, runDir, state);
359
+ }
360
+ try {
361
+ guard.saveSnapshot(path.join(runDir, "snapshots"));
362
+ deliver(project, { from: "user", to: project.lead, type: "task", subject: t.subject, body: t.body });
363
+ }
364
+ catch (e) {
365
+ if (cutting) {
366
+ try {
367
+ rollbackCheckoutStart(project.dir, runDir, state);
368
+ }
369
+ catch (back) {
370
+ throw new Error(`${e.message}\nThe start could not be taken back: ${back.message}`);
371
+ }
372
+ }
373
+ throw e;
374
+ }
375
+ // Only now: a checkout run is resumable only when its task is known to be in the lead's inbox.
376
+ if (checkout)
377
+ state.task_sent = true;
321
378
  log("start", { task_source: task.source, bytes: task.bytes, inline: task.inline });
379
+ if (plan.taskBranch !== undefined) {
380
+ const ref = plan.baseRef ?? "the remote base";
381
+ const sha = (plan.baseSha ?? "").slice(0, 8);
382
+ say(` starting from ${ref} ${sha}; ${project.lead} works in the project folder ${project.dir} on branch ${plan.taskBranch}`);
383
+ log("checkout-start", { ref: plan.baseRef, sha: plan.baseSha, branch: plan.taskBranch, dir: project.dir });
384
+ }
322
385
  }
323
386
  saveState();
387
+ // The state exists now: the reason a run meant for the project checkout works in a worktree instead goes in its log.
388
+ if (!resume && plan.lockFallback !== undefined)
389
+ log("workspace-fallback", { reason: plan.lockFallback });
324
390
  this.leadSpace = leadSpace;
325
391
  this.opts = opts;
326
392
  this.prRunner = opts.pr ?? realRunner;
@@ -384,6 +450,80 @@ export class RunSession {
384
450
  : `${t.from}'s mail ${t.id} ("${t.subject}") has \`tier\` but is a ${t.type}: tiers apply to tasks only, so it was delivered without one.`);
385
451
  }
386
452
  }
453
+ /** A `playbook` or `read_only` that did not apply: log every one, and tell the sender once per reason. */
454
+ noteFlagIgnored(kind, items) {
455
+ for (const t of items) {
456
+ this.log(`${kind}_ignored`, { from: t.from, id: t.id, to: t.to, subject: t.subject, type: t.type, reason: t.reason });
457
+ const key = `${kind}\u0000${t.from}\u0000${t.reason}`;
458
+ if (this.ignoredNoted.has(key))
459
+ continue;
460
+ this.ignoredNoted.add(key);
461
+ const field = kind === "playbook" ? "playbook" : "read_only";
462
+ this.note(t.reason === "not-lead"
463
+ ? `${t.from}'s mail ${t.id} has \`${field}\`, but only the lead (${this.project.lead}) can set it on a task: it was delivered without one.`
464
+ : `${t.from}'s mail ${t.id} ("${t.subject}") has \`${field}\` but is a ${t.type}: it applies to tasks only, so it was delivered without one.`);
465
+ }
466
+ }
467
+ /**
468
+ * A read-only wake in its own worktree puts back only the paths that changed. Paths that were already dirty stay.
469
+ * This is not `reset --hard` and not a clean of the whole tree.
470
+ * A wake with no worktree shares the project folder with the user, so it only notes a moved HEAD and new paths.
471
+ * Cursor denies `Write` on the repo. Claude and Codex rely on the OS sandbox. When that cannot block the write,
472
+ * a worktree is still put back; a borrowed folder is only noted.
473
+ */
474
+ revertReadOnly(agent, ws, claim) {
475
+ const { project, log } = this;
476
+ const sandboxOff = agent.runtime === "cursor" || ((agent.runtime === "claude-code" || agent.runtime === "codex") && !osSandboxAvailable());
477
+ if (sandboxOff)
478
+ log("read-only-unenforced", { agent: agent.name, runtime: agent.runtime });
479
+ const snap = this.roSnaps.get(agent.name) ?? (claim.head ? { head: claim.head, dirty: claim.dirty ?? [] } : undefined);
480
+ this.roSnaps.delete(agent.name);
481
+ if (!snap)
482
+ return;
483
+ if (!ws) {
484
+ let drift;
485
+ try {
486
+ drift = borrowedEdits(project.dir, snap);
487
+ }
488
+ catch (e) {
489
+ const message = e.message.split("\n")[0] ?? e.message;
490
+ this.note(`Could not compare ${agent.name}'s checkout with the start of the wake: ${message}. The project folder was left as it is.`);
491
+ return;
492
+ }
493
+ if (!drift.headMoved && !drift.paths.length)
494
+ return;
495
+ log("read-only-left", { agent: agent.name, files: drift.paths, headMoved: drift.headMoved });
496
+ const moved = drift.headMoved ? " HEAD moved." : "";
497
+ const listed = drift.paths.length ? ` Paths: ${drift.paths.join(", ")}.` : "";
498
+ this.note(`${agent.name}'s wake has no worktree of its own. Changes in the project folder were left as they are, because this run cannot tell your edits from the agent's.${moved}${listed}`);
499
+ return;
500
+ }
501
+ let restored = [];
502
+ try {
503
+ restored = restoreWorkspaceEdits(ws, snap);
504
+ }
505
+ catch (e) {
506
+ const message = e.message.split("\n")[0] ?? e.message;
507
+ if (agent.name === project.lead)
508
+ this.note(`Could not put ${agent.name}'s checkout back: ${message}`);
509
+ else
510
+ this.refuseMember(agent, message);
511
+ return;
512
+ }
513
+ if (!restored.length)
514
+ return;
515
+ log("read-only-restored", { agent: agent.name, files: restored, sandbox: sandboxOff ? "off" : "on" });
516
+ const leadWake = agent.name === project.lead && !project.solo;
517
+ deliver(project, {
518
+ from: "dispatcher",
519
+ to: project.lead,
520
+ type: "failure",
521
+ subject: leadWake ? "Lead wake edited the repository" : `Read-only wake edited ${agent.name}`,
522
+ body: leadWake
523
+ ? `Your wake changed the repository. Those paths were put back. Files that were already changed were left as they were. Send the code change to a teammate. A one-line fix is \`run --agent <name>\` of the agent who writes it. The mail you sent was still delivered.`
524
+ : `The read-only wake of ${agent.name} changed its checkout. Those paths were put back${sandboxOff ? " (the sandbox did not block the write)" : ""}. Files that were already changed were left as they were. The mail it sent was still delivered.`,
525
+ });
526
+ }
387
527
  /** Bind the project to this run again, after its slot table changed. */
388
528
  rebind() {
389
529
  this.project = withCapability(bindRunProject(this.base, this.runDir, this.layout, this.state.instances), this.wsMode, this.instanceCheck, this.state.instances);
@@ -396,7 +536,8 @@ export class RunSession {
396
536
  held: (role) => !!state.instances?.roles[role],
397
537
  enable: (role) => {
398
538
  // Durable before any file of the mail that opens the role's instances exists; a crash after this replays into `pending/`.
399
- state.schema_version = 3;
539
+ if (state.schema_version !== CHECKOUT_SCHEMA_VERSION)
540
+ state.schema_version = 3;
400
541
  state.instances = { roles: { ...(state.instances?.roles ?? {}), [role]: [role] } };
401
542
  this.saveState();
402
543
  fault("instances:enabled");
@@ -590,12 +731,7 @@ export class RunSession {
590
731
  }
591
732
  pickBatch(pending) {
592
733
  const { project } = this;
593
- const lead = pending.find((a) => a.name === project.lead);
594
- if (lead)
595
- return [lead];
596
- if (this.opts.plan.mode !== "worktree")
597
- return [must(pending[0], "an agent to wake")];
598
- return pending;
734
+ return capBatch(pending, project.lead, this.opts.plan.mode === "worktree" ? "worktree" : "shared", this.cfg.max_awake ?? DEFAULT_MAX_AWAKE);
599
735
  }
600
736
  /** The run's original task as the user wrote it (`task.md` in the run folder), for the teammates' prompts; undefined when there is none. */
601
737
  userTask() {
@@ -615,6 +751,8 @@ export class RunSession {
615
751
  const workDir = path.join(runDir, "agents", agent.name);
616
752
  const spaces = this.leadSpace ? { ...this.batchSpaces, [project.lead]: this.leadSpace } : this.batchSpaces;
617
753
  const aproject = Object.keys(spaces).length ? { ...project, workspaces: spaces } : project;
754
+ const coordinate = agent.name === project.lead && !project.solo;
755
+ const readOnly = coordinate || (agent.name !== project.lead && wakeIsReadOnly(unread.map((m) => ({ type: m.meta.type, playbook: m.meta.playbook, read_only: m.meta.read_only }))));
618
756
  const base = {
619
757
  project: aproject,
620
758
  agent,
@@ -623,7 +761,49 @@ export class RunSession {
623
761
  systemPrompt: buildSystemPrompt(aproject, agent),
624
762
  userPrompt: buildUserPrompt(project, agent, queue, unread.length, (state.reopened?.length ?? 0) > 0, this.userTask()),
625
763
  timeoutSec: cfg.wake_timeout_sec,
764
+ policy: coordinate ? coordinatePolicy(aproject, agent) : readOnly ? readOnlyPolicy(aproject, agent) : undefined,
626
765
  };
766
+ const ws = spaces[agent.name];
767
+ if (readOnly) {
768
+ try {
769
+ if (coordinate && ws && workspaceDirty(ws)) {
770
+ // Member changes are applied onto this checkout and left uncommitted. Commit them before recording the
771
+ // wake's head, or putting this wake's paths back would drop them.
772
+ commitWorkspace(ws, "agent-lyceum: keep integrated edits before the lead wakes");
773
+ }
774
+ else if (ws && workspaceDirty(ws)) {
775
+ const prev = previousClaim(runDir, agent.name, claim.id);
776
+ if (prev && prev.read_only !== true)
777
+ commitWorkspace(ws, "agent-lyceum: keep edits from before a read-only wake");
778
+ }
779
+ if (ws) {
780
+ const snap = { head: agentGit(ws, ["rev-parse", "HEAD"]), dirty: workspaceStatusPaths(ws) };
781
+ this.roSnaps.set(agent.name, snap);
782
+ setClaimReadOnly(runDir, claim.id, snap.head, snap.dirty);
783
+ }
784
+ else {
785
+ const snap = snapshotCheckout(project.dir);
786
+ if (snap) {
787
+ this.roSnaps.set(agent.name, snap);
788
+ setClaimReadOnly(runDir, claim.id, snap.head, snap.dirty);
789
+ }
790
+ else
791
+ setClaimReadOnly(runDir, claim.id);
792
+ }
793
+ }
794
+ catch (e) {
795
+ const message = e.message;
796
+ if (coordinate) {
797
+ this.note(`Could not record ${agent.name}'s checkout before the wake: ${message.split("\n")[0]}`);
798
+ }
799
+ else {
800
+ abandonClaim(runDir, claim.id);
801
+ claims.delete(agent.name);
802
+ this.refuseMember(agent, message);
803
+ return { ok: false, error: message };
804
+ }
805
+ }
806
+ }
627
807
  // Without a fallback chain (one candidate) the loop, its output and its records are exactly those of plain retries (spec 20.2 decision 11).
628
808
  // A lead's `tier` (spec 24.5.3): only for an agent with a ladder, and only a valid value counts.
629
809
  const messageIds = unread.map((m) => m.meta.id);
@@ -759,6 +939,7 @@ export class RunSession {
759
939
  error: result.error,
760
940
  ...which,
761
941
  ...(tier ? { tier } : {}),
942
+ ...(readOnly ? { read_only: true } : {}),
762
943
  });
763
944
  state.last_wake[agent.name] = { at: new Date().toISOString(), ok: result.ok, error: result.error, ...(chain ? { runtime: c.runtime, model: c.model } : {}), ...(tier ? { tier } : {}) };
764
945
  log("wake", {
@@ -812,6 +993,9 @@ export class RunSession {
812
993
  markOutputReady(runDir, claim.id);
813
994
  return { ok: true };
814
995
  }
996
+ // Put back only what this read-only wake changed, including when the sandbox could not block the write.
997
+ if (readOnly)
998
+ this.revertReadOnly(agent, ws, loadClaim(runDir, claim.id));
815
999
  // The input stays unread for the resume: the round limit, or a cancel (during a call or a backoff).
816
1000
  abandonClaim(runDir, claim.id);
817
1001
  claims.delete(agent.name);
@@ -875,7 +1059,16 @@ export class RunSession {
875
1059
  /** The agent and the model it last ran on (a tier or fallback shows in `last_wake`), else its configured model. */
876
1060
  workerRef(agent) {
877
1061
  const model = this.state.last_wake[agent.name]?.model ?? agent.model;
878
- return { agent: agent.name, ...(model ? { model } : {}) };
1062
+ return { agent: agent.name, ...(model ? { model } : {}), at: new Date().toISOString() };
1063
+ }
1064
+ /** A checkout run's task branch (the lead works in the project checkout, not in a worktree of its own), else undefined. Always the recorded one. */
1065
+ checkoutBranch() {
1066
+ return this.leadSpace === undefined && this.opts.plan.leadWorktree === false ? this.state.task_branch : undefined;
1067
+ }
1068
+ /** Why the project checkout is no longer on a checkout run's task branch, or undefined (also for runs that do not work in the checkout). */
1069
+ checkoutMoved() {
1070
+ const branch = this.checkoutBranch();
1071
+ return branch === undefined ? undefined : checkoutHeadProblem(this.project.dir, branch);
879
1072
  }
880
1073
  integrateMember(agent, ws, key) {
881
1074
  const { say, project, log, state } = this;
@@ -884,6 +1077,10 @@ export class RunSession {
884
1077
  try {
885
1078
  const who = this.workerRef(agent);
886
1079
  changes = collectAgentChanges(ws, withTrailers(`agent-lyceum: changes by ${agent.name}`, undefined, trailers({ implementers: [who], runId: this.runId })));
1080
+ // A checkout run writes into the project checkout: nothing is applied once HEAD is not the task branch (it is the same refusal path as any blocked integration).
1081
+ const moved = this.checkoutMoved();
1082
+ if (moved)
1083
+ throw new Error(`${moved} Nothing was applied: ${agent.name}'s work is kept on its own branch.`);
887
1084
  r = integrateAgentChanges(project, changes, this.leadSpace);
888
1085
  }
889
1086
  catch (e) {
@@ -913,7 +1110,7 @@ export class RunSession {
913
1110
  subject: `${agent.name}'s changes could not be brought into the repo`,
914
1111
  body: `${agent.name} finished, but its changes could not be brought into the repo, and nothing was applied.\n\n${r.reason}\n\n` +
915
1112
  `Its work is kept: branch \`${r.branch}\`, worktree \`${r.workspace}\`, report \`${r.report}\`, patch \`${r.patch}\`.\n` +
916
- `You can send ${agent.name} a task to redo or adjust it (it continues in the same worktree and the integration is retried after its next wake-up), or apply the patch yourself. ` +
1113
+ `You can send ${agent.name} a task to redo or adjust it (it continues in the same worktree and the integration is retried after its next wake-up). You do not edit the repository yourself. A one-line fix is \`run --agent <name>\` of the agent who writes it. ` +
917
1114
  (instanced ? `New tasks are not given to ${agent.name} while this work is not in the repo. To redo or adjust it, reply to this message (or to ${agent.name}'s last mail): only replies reach ${agent.name} now. ` : "") +
918
1115
  `Do not report the job \`completed\` while this work is missing from the repo.`,
919
1116
  }, instanced ? { about: agent.name } : {});
@@ -929,7 +1126,7 @@ export class RunSession {
929
1126
  to: project.lead,
930
1127
  type: "failure",
931
1128
  subject: `${agent.name} cannot be woken: its worktree was refused`,
932
- body: `${agent.name} has unread mail, but its worktree cannot be used, so it is not woken again in this run and its unread mail stays unread.\n\n${reason}\n\nDo its work yourself or give it to another agent; do not wait for ${agent.name}.`,
1129
+ body: `${agent.name} has unread mail, but its worktree cannot be used, so it is not woken again in this run and its unread mail stays unread.\n\n${reason}\n\nGive the work to another teammate. You do not edit the repository yourself. A one-line fix is \`run --agent <name>\` of the agent who writes it. Do not wait for ${agent.name}.`,
933
1130
  }, this.state.instances?.roles[roleOfName(project.agents, agent.name)] ? { about: agent.name } : {});
934
1131
  this.saveState();
935
1132
  }
@@ -957,9 +1154,16 @@ export class RunSession {
957
1154
  // Crash seam: every wake of the batch is finished and marked output_ready; nothing of it is integrated or routed yet.
958
1155
  fault("wake:ready");
959
1156
  batch.forEach((a, i) => {
960
- const ws = this.batchSpaces[a.name];
1157
+ const id = claims.get(a.name)?.id;
1158
+ const stored = id ? loadClaim(runDir, id) : undefined;
1159
+ // The lead's checkout is the run branch. Only a coordinate wake may be reset, and only back to the commit recorded for that wake.
1160
+ const ws = this.batchSpaces[a.name] ?? (a.name === project.lead && stored?.read_only === true ? this.leadSpace : undefined);
1161
+ if (stored?.read_only === true) {
1162
+ this.revertReadOnly(a, ws, stored);
1163
+ return;
1164
+ }
961
1165
  if (ws && results[i]?.ok)
962
- this.integrateMember(a, ws, claims.get(a.name)?.id ?? `${a.name}-${state.rounds}`);
1166
+ this.integrateMember(a, ws, id ?? `${a.name}-${state.rounds}`);
963
1167
  });
964
1168
  const route = routeOutboxes(project, this.routing());
965
1169
  for (const m of route.delivered) {
@@ -991,9 +1195,32 @@ export class RunSession {
991
1195
  contract = undefined;
992
1196
  }
993
1197
  }
1198
+ let gateFailure;
1199
+ if (route.done && contract && contract.missing.length === 0 && contract.outcome === "completed") {
1200
+ const why = crossRuntimeBlock(project, state, this.opts.plan.mode === "worktree" ? "worktree" : "shared");
1201
+ if (why && (state.done_rejections ?? 0) < MAX_DONE_REJECTIONS) {
1202
+ state.done_rejections = (state.done_rejections ?? 0) + 1;
1203
+ deliverOnce(project, this.journal(), `done-gate:${sourceIdOf(route.done.from, route.done.file)}`, {
1204
+ from: "dispatcher",
1205
+ to: project.lead,
1206
+ type: "failure",
1207
+ subject: "Your done report was not accepted",
1208
+ body: `${why}${this.bindNote ? `\n\n${this.bindNote}` : ""}\n\n(Reminder ${state.done_rejections} of ${MAX_DONE_REJECTIONS}.)`,
1209
+ });
1210
+ rejectDone(route.done.file);
1211
+ say(` done report sent back to ${project.lead}: ${why}`);
1212
+ log("done-rejected", { gate: why, count: state.done_rejections });
1213
+ route.done = undefined;
1214
+ contract = undefined;
1215
+ }
1216
+ else {
1217
+ if (why)
1218
+ gateFailure = { note: why };
1219
+ }
1220
+ }
994
1221
  // Spec 27: a completed done that met the contract is judged by the project's verify commands (the contract came first).
995
1222
  let verified;
996
- if (route.done && contract && contract.missing.length === 0 && contract.outcome === "completed" && project.verify) {
1223
+ if (route.done && contract && contract.missing.length === 0 && contract.outcome === "completed" && project.verify && project.verify.commands.length > 0) {
997
1224
  const v = await this.verifyDone(route.done, project.verify);
998
1225
  if (v.kind === "cancelled") {
999
1226
  // No verdict: the done stays in the outbox (routed again on resume); the rest of this settle still runs.
@@ -1009,6 +1236,8 @@ export class RunSession {
1009
1236
  verified = v;
1010
1237
  }
1011
1238
  this.noteTierIgnored(route);
1239
+ this.noteFlagIgnored("playbook", route.playbookIgnored);
1240
+ this.noteFlagIgnored("read_only", route.readOnlyIgnored);
1012
1241
  const askAccepted = this.handleAsks(route);
1013
1242
  for (const d of route.delivered)
1014
1243
  log("route", d);
@@ -1056,7 +1285,7 @@ export class RunSession {
1056
1285
  }
1057
1286
  this.doneMessage = { subject: route.done.subject, body: route.done.body };
1058
1287
  this.openPrRequested = route.done.meta.open_pr === true;
1059
- const resolved = resolveDoneOutcome(must(contract, "completion contract of the done report"), state.done_rejections ?? 0, state.blocked_integrations ?? [], verified?.failure);
1288
+ const resolved = resolveDoneOutcome(must(contract, "completion contract of the done report"), state.done_rejections ?? 0, state.blocked_integrations ?? [], verified?.failure, gateFailure);
1060
1289
  this.doneOutcome = resolved.outcome;
1061
1290
  this.doneNote = resolved.note;
1062
1291
  this.doneVerification = resolved.verification;
@@ -1244,19 +1473,28 @@ export class RunSession {
1244
1473
  */
1245
1474
  finishLead(endReason) {
1246
1475
  const { say, log, state, runDir, runId, project } = this;
1247
- if (!this.leadSpace || endReason === "waiting")
1476
+ const checkoutBranch = this.checkoutBranch();
1477
+ if ((!this.leadSpace && checkoutBranch === undefined) || endReason === "waiting")
1248
1478
  return undefined;
1479
+ // Where the lead's work is and what it is called, for the notes: the recorded task branch for a checkout run.
1480
+ const where = this.leadSpace ? { branch: this.leadSpace.branch, dir: this.leadSpace.root } : { branch: must(checkoutBranch, "task branch"), dir: project.dir };
1249
1481
  try {
1250
1482
  const lead = project.agents[project.lead];
1251
1483
  const message = withTrailers(`agent-lyceum: ${project.lead}'s work for run ${runId}`, state.task_summary, trailers({ implementers: state.implementers, lead: lead ? this.workerRef(lead) : undefined, reviews: state.reviews, runId }));
1252
- const rb = finishLeadBranch(this.leadSpace, message, path.join(runDir, "lead.patch"));
1484
+ const patch = path.join(runDir, "lead.patch");
1485
+ const rb = this.leadSpace ? finishLeadBranch(this.leadSpace, message, patch) : finishCheckoutBranch(project.dir, where.branch, must(state.base_sha, "base_sha"), message, patch);
1486
+ if (!rb) {
1487
+ // Nothing was committed: HEAD is not the task branch, so a commit would land on whatever it names now.
1488
+ this.note(`The work was not committed: ${checkoutHeadProblem(project.dir, where.branch) ?? `the project checkout is not on ${where.branch}`} It is still in ${where.dir}; no result branch is recorded.`);
1489
+ return undefined;
1490
+ }
1253
1491
  state.result_branch = rb;
1254
1492
  log("lead-branch", { ...rb });
1255
1493
  say(rb.files ? ` work is on branch ${rb.branch} (${rb.files} file(s)); bring it into your repo with: git merge ${rb.branch}` : ` ${rb.branch}: no file changes`);
1256
1494
  return rb;
1257
1495
  }
1258
1496
  catch (e) {
1259
- this.note(`Could not commit the work on ${this.leadSpace.branch}: ${e.message.split("\n")[0]}. It is still in ${this.leadSpace.root}.`);
1497
+ this.note(`Could not commit the work on ${where.branch}: ${e.message.split("\n")[0]}. It is still in ${where.dir}.`);
1260
1498
  return undefined;
1261
1499
  }
1262
1500
  }
@@ -1274,20 +1512,53 @@ export class RunSession {
1274
1512
  };
1275
1513
  if (endReason !== "done" || outcome !== "completed")
1276
1514
  return skip(`the run did not end completed (${endReason}, outcome ${outcome}).`);
1277
- if (!this.leadSpace)
1278
- return skip(`this run works directly in ${this.project.dir} (not a git repo with a commit), so there is no branch to push.`);
1279
- if (!rb)
1280
- return skip(`the work could not be committed on ${this.leadSpace.branch}.`);
1515
+ const checkout = state.workspace_mode === "checkout";
1516
+ const branchName = this.leadSpace?.branch ?? state.task_branch;
1517
+ if (!rb) {
1518
+ if (!this.leadSpace && !checkout)
1519
+ return skip(`this run works directly in ${this.project.dir} (not a git repo with a commit), so there is no branch to push.`);
1520
+ return skip(`the work could not be committed on ${branchName ?? "the task branch"}.`);
1521
+ }
1281
1522
  if (!rb.files)
1282
1523
  return skip(`${rb.branch} has no file changes.`);
1283
1524
  const existingUrl = state.pr_url;
1525
+ // Never the lead's worktree: the agent can write it (and its git pointers), and git would run what it planted there.
1526
+ const cwd = toplevel(project.dir);
1527
+ const base = state.base_ref?.replace(/^origin\//, "");
1528
+ const bodyFile = path.join(runDir, "pr-body.md");
1529
+ const title = prTitle(state.task_summary);
1530
+ const body = prBody(this.doneMessage?.body ?? "");
1531
+ // Where the push goes is what the run recorded when it started. A remote someone changed since (config, pushurl, an agent's write) is not pushed to.
1532
+ if (checkout || state.base_ref !== undefined || state.origin_url !== undefined) {
1533
+ const recorded = state.origin_url;
1534
+ const now = this.prRunner("git", ["remote", "get-url", "--push", "origin"], cwd);
1535
+ const problem = !recorded
1536
+ ? "the push URL of origin was not recorded when the run started"
1537
+ : !now.ok || !now.out.trim()
1538
+ ? "the push URL of origin can no longer be read"
1539
+ : now.out.trim() !== recorded
1540
+ ? `the push URL of origin is now ${now.out.trim()}, but the run recorded ${recorded}`
1541
+ : undefined;
1542
+ if (problem) {
1543
+ let written = "";
1544
+ try {
1545
+ atomicWrite(bodyFile, body);
1546
+ }
1547
+ catch {
1548
+ written = " (the description could not be written to the run directory)";
1549
+ }
1550
+ const manual = manualPrCommands({ cwd, branch: rb.branch, base, title, bodyFile });
1551
+ return skip(`${problem}, so ${rb.branch} was not pushed. If the remote is right, finish by hand${written}:\n${manual.map((m) => ` ${m}`).join("\n")}`);
1552
+ }
1553
+ }
1284
1554
  const result = openPullRequest({
1285
- // Never the lead's worktree: the agent can write it (and its git pointers), and git would run what it planted there.
1286
- cwd: toplevel(project.dir),
1555
+ cwd,
1287
1556
  branch: rb.branch,
1288
- title: prTitle(state.task_summary),
1289
- body: prBody(this.doneMessage?.body ?? ""),
1290
- bodyFile: path.join(runDir, "pr-body.md"),
1557
+ title,
1558
+ body,
1559
+ bodyFile,
1560
+ base,
1561
+ pinnedGit: PINNED_CONFIG,
1291
1562
  run: this.prRunner,
1292
1563
  existingUrl,
1293
1564
  });
@@ -1303,6 +1574,16 @@ export class RunSession {
1303
1574
  }
1304
1575
  return result;
1305
1576
  }
1577
+ /** Checks named in the task that are not verify commands. Undefined when binding is off or everything matches. */
1578
+ bindMismatch() {
1579
+ const verify = this.project.verify;
1580
+ if (!verify?.bind_task)
1581
+ return undefined;
1582
+ const missing = unboundCommands(this.userTask()?.text ?? "", verify.commands.map((c) => c.run));
1583
+ if (!missing.length)
1584
+ return undefined;
1585
+ return `These checks are named in the task's Verification section but are not in project.yaml verify.commands, so they were not run: ${missing.join(", ")}. The outcome is unchanged. Add them to verify.commands before the next run. The dispatcher does not run commands taken from the task.`;
1586
+ }
1306
1587
  /** On resume: sort out what the interrupted process left behind before anything is woken. */
1307
1588
  async recover() {
1308
1589
  const { say, runId, runDir, project, wsMode, log } = this;
@@ -1316,9 +1597,26 @@ export class RunSession {
1316
1597
  if (rec.abandoned.length || rec.finalized.length || rec.ready.length) {
1317
1598
  log("recover", { abandoned: rec.abandoned.map((c) => c.id), finalized: rec.finalized, ready: rec.ready.map((c) => c.id) });
1318
1599
  }
1600
+ const undoReadOnly = (c) => {
1601
+ if (c.read_only !== true || !c.head)
1602
+ return;
1603
+ const agent = project.agents[c.agent];
1604
+ if (!agent)
1605
+ return;
1606
+ const own = agent.name === project.lead ? (this.leadSpace ?? existingAgentWorkspace(project, runId, project.lead)) : existingAgentWorkspace(project, runId, agent.name);
1607
+ if (!own && wsMode === "worktree" && agent.name !== project.lead)
1608
+ return;
1609
+ this.revertReadOnly(agent, own, c);
1610
+ };
1611
+ for (const c of rec.abandoned)
1612
+ undoReadOnly(c);
1613
+ for (const c of rec.ready)
1614
+ undoReadOnly(c);
1319
1615
  // A member whose wake-up finished before the crash: bring its files in (repeating is harmless) before its mail is routed.
1320
1616
  if (wsMode === "worktree") {
1321
1617
  for (const c of rec.ready) {
1618
+ if (c.read_only === true)
1619
+ continue;
1322
1620
  const agent = project.agents[c.agent];
1323
1621
  const ws = agent && agent.name !== project.lead ? existingAgentWorkspace(project, runId, agent.name) : undefined;
1324
1622
  if (agent && ws)
@@ -1335,6 +1633,9 @@ export class RunSession {
1335
1633
  async run() {
1336
1634
  if (this.resume)
1337
1635
  await this.recover();
1636
+ this.bindNote = this.bindMismatch();
1637
+ if (this.bindNote)
1638
+ this.note(this.bindNote);
1338
1639
  const { say, runId, runDir, wsMode, log, state, opts } = this;
1339
1640
  let project = this.project;
1340
1641
  // When the lead was the last one woken and left every mailbox empty without a `done`, remind it once instead of ending silently.
@@ -1384,6 +1685,13 @@ export class RunSession {
1384
1685
  this.batchSpaces = {};
1385
1686
  const members = batch.filter((a) => a.name !== project.lead);
1386
1687
  if (wsMode === "worktree" && members.length) {
1688
+ // A checkout run snapshots the project checkout: not once HEAD is off the task branch (the members would start from, and the lead's work be taken for, another branch).
1689
+ const moved = this.checkoutMoved();
1690
+ if (moved) {
1691
+ this.note(`${moved} The members were not woken and nothing was committed.`);
1692
+ this.endReason = "lead_failed";
1693
+ break;
1694
+ }
1387
1695
  state.snapshots = (state.snapshots ?? 0) + 1;
1388
1696
  this.saveState();
1389
1697
  let ref;