agent-lyceum 0.54.1 → 0.55.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 (54) 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/message-store.d.ts +10 -0
  15. package/dist/message-store.js +26 -0
  16. package/dist/open-pr.d.ts +13 -1
  17. package/dist/open-pr.js +12 -4
  18. package/dist/playbook.d.ts +28 -0
  19. package/dist/playbook.js +40 -0
  20. package/dist/policy.d.ts +12 -0
  21. package/dist/policy.js +55 -0
  22. package/dist/project-lock.d.ts +16 -0
  23. package/dist/project-lock.js +34 -2
  24. package/dist/prompt.d.ts +2 -0
  25. package/dist/prompt.js +25 -7
  26. package/dist/records.d.ts +10 -0
  27. package/dist/records.js +46 -0
  28. package/dist/review-gate.d.ts +33 -0
  29. package/dist/review-gate.js +78 -0
  30. package/dist/run-cleanup.d.ts +9 -2
  31. package/dist/run-cleanup.js +67 -4
  32. package/dist/run-outcome.d.ts +4 -0
  33. package/dist/run-outcome.js +8 -1
  34. package/dist/run-session.d.ts +27 -0
  35. package/dist/run-session.js +347 -39
  36. package/dist/run-store.d.ts +17 -3
  37. package/dist/run-store.js +10 -2
  38. package/dist/scaffold.d.ts +1 -1
  39. package/dist/scaffold.js +5 -2
  40. package/dist/schema.d.ts +12 -0
  41. package/dist/schema.js +6 -0
  42. package/dist/status.d.ts +1 -1
  43. package/dist/task-bind.d.ts +4 -0
  44. package/dist/task-bind.js +42 -0
  45. package/dist/wake-cap.d.ts +5 -0
  46. package/dist/wake-cap.js +11 -0
  47. package/dist/worktree.d.ts +153 -6
  48. package/dist/worktree.js +378 -15
  49. package/package.json +1 -1
  50. package/web/dist/public/assets/index-CVkc3V2B.js +92 -0
  51. package/web/dist/public/assets/index-zT-RkrlC.css +2 -0
  52. package/web/dist/public/index.html +2 -2
  53. package/web/dist/public/assets/index-BPY1-W3F.css +0 -2
  54. package/web/dist/public/assets/index-CbQs5aMP.js +0 -92
package/README.md CHANGED
@@ -82,6 +82,8 @@ Older versions refuse a `team.yaml` or `project.yaml` that contains `model_tiers
82
82
 
83
83
  Likewise, older versions refuse a `project.yaml` that contains `verify` ("Unrecognized key"). Remove the `verify` block before using an older binary. Run state is unaffected. See [Verify](docs/configuration.md#verify). (Spec 27.4)
84
84
 
85
+ Older versions also refuse a `project.yaml` that contains `dispatcher.max_awake`, `verify.bind_task` or `verify.cross_runtime` ("Unrecognized key"). Remove those keys before using an older binary. Omitting `verify.cross_runtime` leaves the gate on, so an existing file does not need the key. Current mail parsing ignores unknown frontmatter keys, so `playbook` and `read_only` on a letter do not by themselves make an older binary fail. Do not leave unread mail that carries those keys if the older parser you are going back to rejects unknown keys. Do not leave a run that still has an unfinished read-only wake: an older `recover()` integrates a claim that reached `output_ready`, and edits from that wake would enter the repo.
86
+
85
87
  ## Topics
86
88
 
87
89
  | Topic | Read |
package/README.zh-TW.md CHANGED
@@ -82,6 +82,8 @@ agents:
82
82
 
83
83
  同樣地,舊版程式會拒絕載入含 `verify` 的 `project.yaml`(「Unrecognized key」)。改用舊版前,請先拿掉 `verify` 區塊。run 狀態不受影響。見[驗證](docs/configuration.zh-TW.md#驗證verify)。(spec 27.4)
84
84
 
85
+ 舊版也會拒絕載入含 `dispatcher.max_awake`、`verify.bind_task` 或 `verify.cross_runtime` 的 `project.yaml`(「Unrecognized key」)。改用舊版前拿掉這些鍵即可。沒寫 `verify.cross_runtime` 時閘門仍開,既有檔案不必加這個鍵。現在的信件解析會忽略未知的 frontmatter 鍵,所以信上的 `playbook` 與 `read_only` 本身不會讓舊版失敗。若你要退回的那個舊版會因未知鍵拒絕信件,降版前不要留下帶這兩個鍵的未讀信。也不要留下還有未完成唯讀喚醒的 run:舊版 `recover()` 看到 `output_ready` 會照樣整合,那次喚醒裡的改動會進 repo。
86
+
85
87
  ## 主題
86
88
 
87
89
  | 主題 | 閱讀 |
@@ -75,6 +75,10 @@ export function writeCursorCliConfig(workDir, input) {
75
75
  const pol = input.policy ?? writePolicy(project, agent);
76
76
  const allow = [...pol.allowDirs.map((d) => `Write(${d}/**)`), ...pol.allowFiles.map((f) => `Write(${f})`)];
77
77
  const deny = pol.deny.flatMap(denyRules);
78
+ // A read-only wake can see the repo (`--add-dir`) and must not Write it. Shell under `--force` can still write; those files stay out of the lead's branch.
79
+ if (input.policy)
80
+ for (const d of pol.readDirs)
81
+ deny.push(`Write(${d}/**)`);
78
82
  if (agent.allowWeb === "fetch" && !input.policy)
79
83
  allow.push("WebFetch(*)");
80
84
  else
@@ -128,7 +132,7 @@ export function buildCursorInvocation(raw) {
128
132
  const common = projectCommonDir(project);
129
133
  const withholdCommon = !input.policy && !projectCommonDirAllowed(project, agent);
130
134
  const fileDirs = pol.allowFiles.map((f) => path.dirname(f)).filter((d) => !withholdCommon || (d !== common && !d.startsWith(common + path.sep)));
131
- const addDirs = [...new Set([...pol.allowDirs, ...fileDirs].filter((d) => !(d === repo || d.startsWith(repo + path.sep))))];
135
+ const addDirs = [...new Set([...pol.allowDirs, ...fileDirs, ...(input.policy ? pol.readDirs : [])].filter((d) => !(d === repo || d.startsWith(repo + path.sep))))];
132
136
  const args = ["-p", "--force", "--trust", "--sandbox", "enabled", "--workspace", repo];
133
137
  // Placed before other flags so a variadic --add-dir can never swallow the positional prompt.
134
138
  for (const d of addDirs)
@@ -13,6 +13,8 @@ export interface ReviewRecord {
13
13
  export interface WorkerRef {
14
14
  agent: string;
15
15
  model?: string;
16
+ /** When the files were integrated. Absent on records written before this field existed. */
17
+ at?: string;
16
18
  }
17
19
  /** `name (model)`, or just `name` when the model is not known. Newlines are dropped so a value cannot start another trailer. */
18
20
  export declare function agentLabel(w: WorkerRef): string;
package/dist/cli.js CHANGED
@@ -13,8 +13,8 @@ import { reviewProposals } from "./proposals-review.js";
13
13
  import { RESULT_FILE, runTeam } from "./dispatcher.js";
14
14
  import { executeRunCleanup, planRunCleanup } from "./run-cleanup.js";
15
15
  import { diagnoseProject, formatDoctor, preflightRuntimes, runtimesUsed } from "./doctor.js";
16
- import { acquireProjectLock, forceUnlock, inspectRunLock, listRunLocks, listUnreadableRunLocks, LOCK_FILE, lockHolderAlive } from "./project-lock.js";
17
- import { planWorkspace } from "./worktree.js";
16
+ import { acquireProjectLock, forceUnlock, inspectRunLock, listRunLocks, listUnreadableRunLocks, LOCK_FILE, lockForPlan, lockHolderAlive } from "./project-lock.js";
17
+ import { assertCheckoutResumable, borrowsCheckout, checkoutBlockedNow, currentCheckoutRef, planWorkspace } from "./worktree.js";
18
18
  import { loadRunState, newRunId, outcomeOf, pickRunName, resolveRun, roundLimit, roundsLabel, runLabel, slugify, uniqueName } from "./run-store.js";
19
19
  import { printRun } from "./run-print.js";
20
20
  import { exitCodeForOutcome, RUNTIMES } from "./schema.js";
@@ -165,6 +165,20 @@ function takeLock(pr, runId, opts = {}) {
165
165
  return fail(e.message);
166
166
  }
167
167
  }
168
+ /** Lock for a new run. One that means to borrow the project checkout falls back to a worktree when the checkout is busy or no longer fit; the reason goes to stderr. */
169
+ function takeNewRunLock(pr, runId, intended) {
170
+ if (!borrowsCheckout(intended))
171
+ return { lease: takeLock(pr, runId, { checkout: !intended.leadWorktree, reason: intended.reason }), plan: intended };
172
+ try {
173
+ const r = lockForPlan(intended, (checkout) => acquireProjectLock(pr.paths.root, runId, { checkout, dir: pr.dir, reason: "it borrows the project checkout" }), () => checkoutBlockedNow(pr.dir, intended) === undefined, () => checkoutBlockedNow(pr.dir, intended) ?? "it is in use by another run");
174
+ if (r.plan.lockFallback !== undefined)
175
+ console.error(`The project checkout cannot be borrowed (${r.plan.lockFallback}); this run works in its own worktree.`);
176
+ return r;
177
+ }
178
+ catch (e) {
179
+ return fail(e.message);
180
+ }
181
+ }
168
182
  /**
169
183
  * Ctrl-C (or SIGTERM) stops the run cleanly: the first signal cancels it (agents are killed, unread mail is kept,
170
184
  * the lock is released, exit code 130); a second one quits at once.
@@ -226,6 +240,9 @@ async function continueRun(pr, dir, runId, followup) {
226
240
  if (state.lead_workspace !== planned.lead_workspace || state.workspace_mode !== planned.workspace_mode) {
227
241
  throw new Error(`Run ${runId} changed while it was starting (where it works was ${planned.lead_workspace ? "its own worktree" : planned.workspace_mode ?? "unset"}, now ${state.lead_workspace ? "its own worktree" : state.workspace_mode ?? "unset"}); try again.`);
228
242
  }
243
+ // Under the lock, so the starter that may still hold it is never raced: an unsent start is taken back here, a started run must still be on its branch.
244
+ if (state.workspace_mode === "checkout")
245
+ assertCheckoutResumable(pr.dir, dir, state);
229
246
  console.log(`Project ${pr.name} — repo ${pr.dir}`);
230
247
  if (followup)
231
248
  console.log(`Reopening run ${runLabel(state)} (follow-up ${(state.reopened?.length ?? 0) + 1}): ${firstLine(followup.text)}`);
@@ -336,8 +353,13 @@ program
336
353
  }
337
354
  const runId = newRunId();
338
355
  const runDir = path.join(pr.paths.runs, runId);
339
- const plan = planWorkspace(pr);
340
- const lease = takeLock(pr, runId, { checkout: !plan.leadWorktree, reason: plan.reason });
356
+ const locked = takeNewRunLock(pr, runId, planWorkspace(pr));
357
+ const { lease } = locked;
358
+ let { plan } = locked;
359
+ // The lock is held and the checkout is still the lead's to borrow: it works on its own branch there. `--agent`: that member is the lead of its run.
360
+ const startCheckout = borrowsCheckout(plan);
361
+ if (startCheckout)
362
+ plan = { ...plan, taskBranch: `agent-lyceum/${runId}/${opts.agent ?? pr.lead}`, checkoutFrom: currentCheckoutRef(pr.dir) };
341
363
  let summary;
342
364
  const cancel = cancelOnSignals();
343
365
  try {
@@ -348,7 +370,7 @@ program
348
370
  for (const w of lintTaskContent(prepared.content))
349
371
  console.error(`warning: task file ${w}`);
350
372
  const name = chosenName ?? uniqueName(slugify(taskMessageBody(prepared).subject), taken);
351
- summary = await runTeam({ project: pr, name, plan, task: prepared, runDir, soloAgent: opts.agent, tidy: opts.tidy, signal: cancel.signal });
373
+ summary = await runTeam({ project: pr, name, plan, task: prepared, runDir, soloAgent: opts.agent, tidy: opts.tidy, startCheckout, signal: cancel.signal });
352
374
  }
353
375
  finally {
354
376
  cancel.dispose();
@@ -549,8 +571,12 @@ program
549
571
  console.log(`Run ${label}${plan.summary.slice(full.length)}`);
550
572
  for (const i of plan.items)
551
573
  console.log(` ${opts.dryRun ? "would delete" : "delete "} ${i.label}`);
552
- for (const k of plan.keep)
553
- console.log(` kept worktree of ${k.agent}: ${k.path} (branch ${k.branch})${k.files.length ? `, holding ${k.files.join(", ")}` : ""}`);
574
+ for (const k of plan.keep) {
575
+ if (k.reason)
576
+ console.log(` kept branch ${k.branch}: ${k.reason}`);
577
+ else
578
+ console.log(` kept worktree of ${k.agent}: ${k.path} (branch ${k.branch})${k.files.length ? `, holding ${k.files.join(", ")}` : ""}`);
579
+ }
554
580
  };
555
581
  const refuse = (plan) => {
556
582
  for (const r of plan.refusals)
package/dist/config.d.ts CHANGED
@@ -157,6 +157,8 @@ export declare function loadProjectRaw(home: string, name: string): {
157
157
  } | undefined;
158
158
  verify?: {
159
159
  max_rejections?: number | undefined;
160
+ bind_task?: boolean | undefined;
161
+ cross_runtime?: boolean | undefined;
160
162
  commands: {
161
163
  name: string;
162
164
  run: string;
@@ -179,6 +181,7 @@ export declare function loadProjectRaw(home: string, name: string): {
179
181
  }[] | undefined;
180
182
  fallback_cooldown_sec?: number | undefined;
181
183
  max_instances?: number | undefined;
184
+ max_awake?: number | undefined;
182
185
  };
183
186
  agents: Record<string, {
184
187
  runtime?: "claude-code" | "codex" | "cursor" | undefined;
package/dist/config.js CHANGED
@@ -71,9 +71,11 @@ export function resolveProjectFrom(home, name, g, p) {
71
71
  modelTiersFrom[rt] = fromProject ? "project" : "global";
72
72
  }
73
73
  }
74
- const verify = p.verify?.commands.length
74
+ const verify = p.verify && (p.verify.commands.length > 0 || p.verify.bind_task === true || p.verify.cross_runtime === false)
75
75
  ? {
76
76
  max_rejections: p.verify.max_rejections ?? VERIFY_DEFAULTS.max_rejections,
77
+ bind_task: p.verify.bind_task === true,
78
+ cross_runtime: p.verify.cross_runtime !== false,
77
79
  commands: p.verify.commands.map((c) => ({ name: c.name, run: c.run, timeout_sec: c.timeout_sec ?? VERIFY_DEFAULTS.timeout_sec })),
78
80
  }
79
81
  : undefined;
@@ -353,6 +355,8 @@ export function resolveProjectWithSources(home, name) {
353
355
  }
354
356
  if (raw.dispatcher.max_instances !== undefined)
355
357
  sources["dispatcher.max_instances"] = { file: projectFile, key: "dispatcher.max_instances" };
358
+ if (raw.dispatcher.max_awake !== undefined)
359
+ sources["dispatcher.max_awake"] = { file: projectFile, key: "dispatcher.max_awake" };
356
360
  for (const rt of RUNTIMES) {
357
361
  const from = project.modelTiersFrom[rt];
358
362
  if (from)
@@ -1,9 +1,14 @@
1
1
  import { RunSession } from "./run-session.js";
2
2
  import { newRunId } from "./run-store.js";
3
- import { planWorkspace } from "./worktree.js";
3
+ import { borrowsCheckout, planWorkspace, toLeadWorktree } from "./worktree.js";
4
4
  export { newRunId };
5
5
  export { MAX_DONE_REJECTIONS, RESULT_FILE } from "./run-session.js";
6
+ /** For a caller that passed no plan: a new run that was offered the project checkout works in its own worktree instead (it has taken no checkout lock); a resumed run keeps what its state recorded. */
7
+ function defaultPlan(opts) {
8
+ const plan = planWorkspace(opts.project, opts.resume);
9
+ return !opts.resume && borrowsCheckout(plan) ? toLeadWorktree(plan) : plan;
10
+ }
6
11
  /** `plan` is what the CLI decided before taking the run's lock. The CLI always passes it; the fallback exists only for direct callers and tests. */
7
12
  export async function runTeam(opts) {
8
- return new RunSession({ ...opts, plan: opts.plan ?? planWorkspace(opts.project, opts.resume) }).run();
13
+ return new RunSession({ ...opts, plan: opts.plan ?? defaultPlan(opts) }).run();
9
14
  }
package/dist/doctor.js CHANGED
@@ -4,7 +4,8 @@ import path from "node:path";
4
4
  import { cursorConfigDir, hasCursorAuth } from "./adapters/cursor.js";
5
5
  import { findOnPath } from "./fs-util.js";
6
6
  import { tidyAdvice } from "./memory-tidy.js";
7
- import { listRecords, RECORD_KINDS } from "./records.js";
7
+ import { teamRunFindings } from "./review-gate.js";
8
+ import { lessonGuardFindings, listRecords, RECORD_KINDS } from "./records.js";
8
9
  import { listRunLocks, listUnreadableRunLocks, lockHolderAlive } from "./project-lock.js";
9
10
  import { checkDecisions, listProposals, oldestPending, pendingProposals } from "./proposals.js";
10
11
  import { runInvocation } from "./process-runner.js";
@@ -185,7 +186,10 @@ export async function diagnoseProject(project, opts = {}) {
185
186
  ? { level: "info", subject: "pr", message: `A run cannot open a pull request (a lead asks for one with \`open_pr: true\`): ${missing.join("; ")}.` }
186
187
  : { level: "ok", subject: "pr", message: "`gh` and `origin` found: a run can open a pull request when the lead asks for one." });
187
188
  }
188
- if (project.verify) {
189
+ if (project.verify?.bind_task && project.verify.commands.length === 0) {
190
+ checks.push({ level: "error", subject: "verify", message: "verify.bind_task is true but verify.commands is empty, so a completed done cannot be bound to anything." });
191
+ }
192
+ else if (project.verify && project.verify.commands.length > 0) {
189
193
  const cmds = project.verify.commands.map((c) => `${c.name}: ${c.run} (timeout ${c.timeout_sec}s)`).join("; ");
190
194
  checks.push({
191
195
  level: "warn",
@@ -193,7 +197,7 @@ export async function diagnoseProject(project, opts = {}) {
193
197
  message: `Before it accepts a lead's \`completed\` done, the dispatcher runs ${project.verify.commands.length} verify command(s), up to ${project.verify.max_rejections} rejection(s): ${cmds}. They run OUTSIDE the agents' sandbox with your permissions and execute code the agents wrote, in the lead's worktree, or directly in ${project.dir} when runs do not use worktrees. Only you can change them (project.yaml).`,
194
198
  });
195
199
  }
196
- else {
200
+ else if (!project.verify) {
197
201
  const suggestion = suggestVerify(project.dir);
198
202
  if (suggestion)
199
203
  checks.push({ level: "info", subject: "verify", message: suggestion });
@@ -224,6 +228,9 @@ export async function diagnoseProject(project, opts = {}) {
224
228
  checks.push({ level: "warn", subject: "records", message: `${r.file}: supersedes "${s}", but no ${kind} entry has that id.` });
225
229
  }
226
230
  }
231
+ for (const f of lessonGuardFindings(listRecords(project, "lessons"), project.verify?.commands.length ?? 0)) {
232
+ checks.push({ level: f.level, subject: "records", message: f.message });
233
+ }
227
234
  // Spec 30: proposals waiting for the lead, and decisions or files that are not in the right format.
228
235
  const waiting = pendingProposals(project);
229
236
  if (waiting.length)
@@ -234,6 +241,8 @@ export async function diagnoseProject(project, opts = {}) {
234
241
  }
235
242
  for (const d of checkDecisions(listProposals(project), project))
236
243
  checks.push({ level: "warn", subject: "proposals", message: `${d.file}: ${d.problem}.` });
244
+ for (const f of teamRunFindings(project))
245
+ checks.push({ level: f.level, subject: "team", message: f.message });
237
246
  const runtimes = await probeProjectRuntimes(project, opts, true);
238
247
  checks.push(...judgeRuntimes(project, runtimes));
239
248
  checks.push({ level: "info", subject: "login", message: "Login status is unknown: agent-lyceum does not read credentials, and the CLIs offer no read-only login check it can rely on." });
package/dist/format.d.ts CHANGED
@@ -4,7 +4,8 @@ import { type RunOutcome } from "./schema.js";
4
4
  export declare const REQUIRED_SECTIONS: Partial<Record<MessageType, string[]>>;
5
5
  /** Required sections that have no Markdown heading in `body` (case-insensitive, any heading level). */
6
6
  export declare function missingSections(type: MessageType, body: string): string[];
7
- export declare function formatWarning(type: MessageType, missing: string[]): string;
7
+ /** `missing` names headings only; `acceptance` carries `acceptanceIssues` sentences, which follow the heading list on their own. */
8
+ export declare function formatWarning(type: MessageType, missing: string[], acceptance?: string[]): string;
8
9
  export interface Step {
9
10
  text: string;
10
11
  done: boolean;
@@ -17,6 +18,8 @@ export declare function mergeSteps(base: Step[] | undefined, latest: Step[]): St
17
18
  export declare function briefOf(body: string): string | undefined;
18
19
  /** Text under the `##` heading `name` (case-insensitive) up to the next heading, or undefined if there is no such heading. */
19
20
  export declare function sectionText(body: string, name: string): string | undefined;
21
+ /** Problems with `## Acceptance criteria`: no item names a command, a file or a test. No such heading gives [] (`missingSections` owns that). */
22
+ export declare function acceptanceIssues(body: string): string[];
20
23
  /** Outcomes a lead may declare in `done`; `cancelled` is only ever the dispatcher's. */
21
24
  export declare const DECLARABLE_OUTCOMES: readonly ["completed", "partial", "blocked", "failed"];
22
25
  export interface DoneContract {
package/dist/format.js CHANGED
@@ -12,8 +12,14 @@ export function missingSections(type, body) {
12
12
  const headings = new Set([...body.matchAll(/^#{1,6}[ \t]+(.+?)[ \t]*:?[ \t]*#*[ \t]*$/gm)].map((m) => (m[1] ?? "").trim().toLowerCase()));
13
13
  return required.filter((s) => !headings.has(s.toLowerCase()));
14
14
  }
15
- export function formatWarning(type, missing) {
16
- return `[agent-lyceum] Format warning: this ${type} is missing required section(s): ${missing.map((s) => `\`## ${s}\``).join(", ")}.`;
15
+ /** `missing` names headings only; `acceptance` carries `acceptanceIssues` sentences, which follow the heading list on their own. */
16
+ export function formatWarning(type, missing, acceptance = []) {
17
+ const parts = [];
18
+ if (missing.length)
19
+ parts.push(`this ${type} is missing required section(s): ${missing.map((s) => `\`## ${s}\``).join(", ")}.`);
20
+ for (const s of acceptance)
21
+ parts.push(`${s}.`);
22
+ return `[agent-lyceum] Format warning: ${parts.join(" ")}`;
17
23
  }
18
24
  /** Checklist items (`- [ ] x` / `- [x] x`). With `section`, only those under a `## Steps` heading; otherwise the whole text. */
19
25
  export function parseSteps(body, section = true) {
@@ -73,6 +79,38 @@ export function sectionText(body, name) {
73
79
  const end = heads[i + 1]?.index ?? body.length;
74
80
  return body.slice(start, end).trim();
75
81
  }
82
+ const ACCEPTANCE_PLACEHOLDERS = new Set(["none", "as stated", "as stated in the goal", "同上", "如目標", "待補", "tbd", "todo"]);
83
+ function isPlaceholder(item) {
84
+ const t = item
85
+ .replace(/^(?:[-*]|\d+\.)[ \t]+/, "")
86
+ .replace(/`/g, "")
87
+ .replace(/\s+/g, " ")
88
+ .trim()
89
+ .toLowerCase();
90
+ return ACCEPTANCE_PLACEHOLDERS.has(t);
91
+ }
92
+ /** A backtick command (it contains a space, a slash, or a file extension) or a path or test name. A lone word in backticks is not a check. */
93
+ function isCheckable(item) {
94
+ if (isPlaceholder(item))
95
+ return false;
96
+ const ticks = [...item.matchAll(/`([^`]+)`/g)].map((m) => m[1].trim()).filter((t) => t !== "" && !isPlaceholder(t));
97
+ const command = ticks.some((t) => /\s/.test(t) || /[\\/]/.test(t) || /\.[A-Za-z0-9]+$/.test(t));
98
+ const outside = item.replace(/`[^`]*`/g, " ");
99
+ const file = /\S+\.[A-Za-z0-9]+/.test(outside);
100
+ return command || file;
101
+ }
102
+ /** Problems with `## Acceptance criteria`: no item names a command, a file or a test. No such heading gives [] (`missingSections` owns that). */
103
+ export function acceptanceIssues(body) {
104
+ const text = sectionText(body, "Acceptance criteria");
105
+ if (text === undefined)
106
+ return [];
107
+ const items = text
108
+ .split(/\r?\n/)
109
+ .map((l) => l.trim())
110
+ .filter((l) => l !== "" && !l.startsWith("#"));
111
+ const checkable = items.filter((l) => isCheckable(l));
112
+ return checkable.length ? [] : ["Acceptance criteria has no checkable item (a `command`, a file or a test name)"];
113
+ }
76
114
  /** Outcomes a lead may declare in `done`; `cancelled` is only ever the dispatcher's. */
77
115
  export const DECLARABLE_OUTCOMES = ["completed", "partial", "blocked", "failed"];
78
116
  /**
package/dist/mailbox.d.ts CHANGED
@@ -3,6 +3,7 @@ import { type Step } from "./format.js";
3
3
  import { atomicWrite } from "./fs-util.js";
4
4
  import { type InstanceCap } from "./instances.js";
5
5
  import type { Tier } from "./schema.js";
6
+ import { type Playbook } from "./playbook.js";
6
7
  import { type Verdict } from "./attribution.js";
7
8
  import { RouteJournal } from "./message-store.js";
8
9
  export { atomicWrite };
@@ -21,6 +22,10 @@ export interface MessageMeta {
21
22
  run_id?: string;
22
23
  /** The lead-chosen difficulty tier, validated by the dispatcher at delivery (spec 24.5.3). Absent = the ceiling. */
23
24
  tier?: Tier;
25
+ /** The lead-chosen playbook of a task. Written only when it took effect. */
26
+ playbook?: Playbook;
27
+ /** The task runs read-only. Written only as `true`: an `investigate` playbook or an explicit `read_only: true`. */
28
+ read_only?: true;
24
29
  }
25
30
  export interface Message {
26
31
  meta: MessageMeta;
@@ -46,6 +51,10 @@ export interface DeliverInput {
46
51
  reply_to?: string;
47
52
  /** Written to the mail only when set (spec 24.5.3), so mail without it is unchanged. */
48
53
  tier?: Tier;
54
+ /** Written to the mail only when set; a task from the lead that named a valid playbook. */
55
+ playbook?: Playbook;
56
+ /** Written to the mail only as `true`. */
57
+ read_only?: true;
49
58
  }
50
59
  /** Deliver a message into `to`'s inbox (dispatcher-side; senders other than agents allowed). */
51
60
  export declare function deliver(project: ResolvedProject, input: DeliverInput & {
@@ -99,7 +108,8 @@ export interface RouteResult {
99
108
  from: string;
100
109
  id: string;
101
110
  subject: string;
102
- missing: string[];
111
+ missing: string[]; /** `acceptanceIssues` sentences; kept apart from the heading names in `missing`. */
112
+ acceptance?: string[];
103
113
  }[];
104
114
  /** The lead's `done`. Its file stays in the outbox until the caller has stored the result and calls `finishDone`. */
105
115
  done?: {
@@ -128,6 +138,24 @@ export interface RouteResult {
128
138
  type: string;
129
139
  reason: "not-lead" | "not-a-task" | "no-tiers";
130
140
  }[];
141
+ /** `playbook` fields delivered without effect; same shape as `tierIgnored`. */
142
+ playbookIgnored: {
143
+ from: string;
144
+ id: string;
145
+ to: string;
146
+ subject: string;
147
+ type: string;
148
+ reason: "not-lead" | "not-a-task";
149
+ }[];
150
+ /** `read_only` fields delivered without effect; same shape as `tierIgnored`. */
151
+ readOnlyIgnored: {
152
+ from: string;
153
+ id: string;
154
+ to: string;
155
+ subject: string;
156
+ type: string;
157
+ reason: "not-lead" | "not-a-task";
158
+ }[];
131
159
  }
132
160
  /** Move a handled `done` file out of the outbox (to `read/`). */
133
161
  export declare function finishDone(file: string): void;
package/dist/mailbox.js CHANGED
@@ -3,11 +3,12 @@ import fs from "node:fs";
3
3
  import path from "node:path";
4
4
  import YAML from "yaml";
5
5
  import { duplicateNoticeKey, shouldNotifyDuplicate } from "./duplicate-notices.js";
6
- import { formatWarning, missingSections, parseSteps } from "./format.js";
6
+ import { acceptanceIssues, formatWarning, missingSections, parseSteps, sectionText } from "./format.js";
7
7
  import { atomicWrite, readRegularFileNoFollow } from "./fs-util.js";
8
8
  import { countFormatRejection, formatRejectionKey, formatRejections, MAX_FORMAT_REJECTIONS } from "./format-rejections.js";
9
9
  import { parallelFlag, roleOfName } from "./instances.js";
10
10
  import { effectiveTier, tierFlag } from "./tiers.js";
11
+ import { effectiveReadOnly, extraSections, playbookFlag, readOnlyFlag } from "./playbook.js";
11
12
  import { isVerdict } from "./attribution.js";
12
13
  import { deterministicId, fault, RouteJournal, sourceIdOf } from "./message-store.js";
13
14
  import { inboxDir, outboxDir, sharedDir } from "./policy.js";
@@ -86,6 +87,8 @@ export function deliver(project, input) {
86
87
  created: input.created ?? new Date().toISOString(),
87
88
  ...(project.run?.layout === "run" ? { run_id: project.run.id } : {}),
88
89
  ...(input.tier ? { tier: input.tier } : {}),
90
+ ...(input.playbook ? { playbook: input.playbook } : {}),
91
+ ...(input.read_only ? { read_only: true } : {}),
89
92
  };
90
93
  const file = path.join(inboxDir(project, input.to), input.fileName ?? `${stamp()}-${input.from}-${id}.md`);
91
94
  atomicWrite(file, serialize(meta, input.body));
@@ -146,6 +149,8 @@ function deliveredMeta(project, input, planned) {
146
149
  created: planned.created,
147
150
  ...(project.run?.layout === "run" ? { run_id: project.run.id } : {}),
148
151
  ...(input.tier ? { tier: input.tier } : {}),
152
+ ...(input.playbook ? { playbook: input.playbook } : {}),
153
+ ...(input.read_only ? { read_only: true } : {}),
149
154
  };
150
155
  }
151
156
  export function readMessage(file) {
@@ -222,7 +227,7 @@ function sameText(body) {
222
227
  * An earlier mail from `from` to `to` with the same type, the same reply target and the same text (unread or already read):
223
228
  * sending it again changes nothing and is how two agents end up in a loop. Texts too short to mean anything are never duplicates.
224
229
  */
225
- function earlierDuplicate(project, from, to, type, replyTo, body, held = false, tier = "high") {
230
+ function earlierDuplicate(project, from, to, type, replyTo, body, held = false, tier = "high", playbook, readOnly = false) {
226
231
  const text = sameText(body);
227
232
  if (text.length < 20)
228
233
  return undefined;
@@ -238,7 +243,7 @@ function earlierDuplicate(project, from, to, type, replyTo, body, held = false,
238
243
  continue;
239
244
  try {
240
245
  const m = readMessage(path.join(d, e.name));
241
- if (m.meta.from === from && m.meta.type === type && (m.meta.reply_to ?? "") === (replyTo ?? "") && sameText(m.body) === text && effectiveTier(m.meta) === tier)
246
+ if (m.meta.from === from && m.meta.type === type && (m.meta.reply_to ?? "") === (replyTo ?? "") && sameText(m.body) === text && effectiveTier(m.meta) === tier && m.meta.playbook === playbook && (m.meta.read_only === true) === readOnly)
242
247
  return m;
243
248
  }
244
249
  catch {
@@ -250,7 +255,7 @@ function earlierDuplicate(project, from, to, type, replyTo, body, held = false,
250
255
  }
251
256
  /** Validate each agent's outbox and move accepted mail into recipients' inboxes. Safe to run again after a crash. */
252
257
  export function routeOutboxes(project, routing) {
253
- const res = { delivered: [], rejected: [], warnings: [], asks: [], tierIgnored: [] };
258
+ const res = { delivered: [], rejected: [], warnings: [], asks: [], tierIgnored: [], playbookIgnored: [], readOnlyIgnored: [] };
254
259
  const journal = project.run ? new RouteJournal(project.run.dir) : undefined;
255
260
  for (const sender of Object.values(project.agents)) {
256
261
  const dir = outboxDir(project, sender.name);
@@ -386,12 +391,44 @@ export function routeOutboxes(project, routing) {
386
391
  const f = tiers.get(to);
387
392
  return f === "low" || f === "mid" || f === "high" ? f : undefined;
388
393
  };
389
- const missing = missingSections(type, parsed.body);
390
- if (missing.length && project.run?.layout === "run") {
391
- const key = formatRejectionKey(sender.name, type, subject);
392
- if (formatRejections(project.run.dir, key) < MAX_FORMAT_REJECTIONS) {
393
- const n = countFormatRejection(project.run.dir, key);
394
- reject(`this ${type} is missing required section(s): ${missing.map((s) => `\`## ${s}\``).join(", ")}. Add them (write \`None\` where a section is empty) and send it again. (Attempt ${n} of ${MAX_FORMAT_REJECTIONS}; after that it is delivered with a warning.)`);
394
+ // `playbook` and `read_only` are the lead's, on a task. Only a value that took effect reaches the mail.
395
+ const pf = playbookFlag({ value: d.playbook, senderIsLead: sender.name === project.lead, type });
396
+ if (pf === "invalid") {
397
+ reject(`playbook must be investigate, fix, feature or refactor, not ${JSON.stringify(d.playbook)}. Write it on a new task, or leave the line out.`);
398
+ continue;
399
+ }
400
+ const rf = readOnlyFlag({ value: d.read_only, senderIsLead: sender.name === project.lead, type });
401
+ if (rf === "invalid") {
402
+ reject(`read_only must be true or false (YAML boolean), not ${JSON.stringify(d.read_only)}.`);
403
+ continue;
404
+ }
405
+ const playbook = typeof pf === "string" && pf !== "absent" ? pf : undefined;
406
+ const readOnly = effectiveReadOnly(playbook, rf);
407
+ const baseMissing = missingSections(type, parsed.body);
408
+ const shapeMissing = extraSections(playbook).filter((s) => sectionText(parsed.body, s) === undefined);
409
+ const missing = [...baseMissing, ...shapeMissing];
410
+ const acceptance = type === "task" ? acceptanceIssues(parsed.body) : [];
411
+ if ((missing.length || acceptance.length) && project.run?.layout === "run") {
412
+ const base = formatRejectionKey(sender.name, type, subject);
413
+ const runDir = project.run.dir;
414
+ // Each reason has its own count; only a reason that is still under the cap holds the mail back (and uses up one try).
415
+ const reasons = [
416
+ { present: baseMissing.length > 0, key: base },
417
+ { present: shapeMissing.length > 0, key: `${base}:shape` },
418
+ { present: acceptance.length > 0, key: `${base}:acceptance` },
419
+ ].filter((r) => r.present);
420
+ const persistent = shapeMissing.length > 0 || acceptance.length > 0;
421
+ if (persistent || reasons.some((r) => formatRejections(runDir, r.key) < MAX_FORMAT_REJECTIONS)) {
422
+ const held = reasons.filter((r) => persistent || formatRejections(runDir, r.key) < MAX_FORMAT_REJECTIONS);
423
+ const n = Math.max(...held.map((r) => countFormatRejection(runDir, r.key)));
424
+ const parts = [
425
+ ...(missing.length ? [`this ${type} is missing required section(s): ${missing.map((s) => `\`## ${s}\``).join(", ")}.`] : []),
426
+ ...acceptance.map((s) => `${s}.`),
427
+ ];
428
+ const tail = persistent
429
+ ? `(Attempt ${n}. A missing \`## Shape\`, or an acceptance line that is not a command, a file or a test name, is not delivered.)`
430
+ : `(Attempt ${n} of ${MAX_FORMAT_REJECTIONS}; after that it is delivered with a warning.)`;
431
+ reject(`${parts.join(" ")} Fix them and send it again (an empty section is written \`None\`, except \`## Acceptance criteria\`, which needs a command, a file name or a test name; a lone word in backticks is rejected too). ${tail}`);
395
432
  continue;
396
433
  }
397
434
  }
@@ -402,7 +439,7 @@ export function routeOutboxes(project, routing) {
402
439
  for (const to of targets) {
403
440
  if (journal?.get(source, to))
404
441
  continue;
405
- const earlier = earlierDuplicate(project, sender.name, to, type, replyTo, parsed.body, !!routing?.held(roleOf(to)), tierOf(to) ?? "high");
442
+ const earlier = earlierDuplicate(project, sender.name, to, type, replyTo, parsed.body, !!routing?.held(roleOf(to)), tierOf(to) ?? "high", playbook, readOnly);
406
443
  if (earlier)
407
444
  repeats.set(to, earlier);
408
445
  }
@@ -431,7 +468,7 @@ export function routeOutboxes(project, routing) {
431
468
  });
432
469
  res.rejected.push({ from: sender.name, file, reason: `duplicate: ${repeatNote()}` });
433
470
  }
434
- const body = missing.length ? `${formatWarning(type, missing)}\n\n${parsed.body}` : parsed.body;
471
+ const body = missing.length || acceptance.length ? `${formatWarning(type, missing, acceptance)}\n\n${parsed.body}` : parsed.body;
435
472
  if (sender.name === project.lead) {
436
473
  const st = parseSteps(parsed.body);
437
474
  if (st.length)
@@ -445,13 +482,17 @@ export function routeOutboxes(project, routing) {
445
482
  const tf = tiers.get(to);
446
483
  if (typeof tf === "object" && !journal?.get(source, to))
447
484
  res.tierIgnored.push({ from: sender.name, id: deterministicId(source, to), to, subject, type, reason: tf.ignored });
485
+ if (typeof pf === "object" && !journal?.get(source, to))
486
+ res.playbookIgnored.push({ from: sender.name, id: deterministicId(source, to), to, subject, type, reason: pf.ignored });
487
+ if (typeof rf === "object" && !journal?.get(source, to))
488
+ res.readOnlyIgnored.push({ from: sender.name, id: deterministicId(source, to), to, subject, type, reason: rf.ignored });
448
489
  if (typeof flag === "object" && !journal?.get(source, to))
449
490
  routing?.ignored(flag.ignored, { from: sender.name, id: deterministicId(source, to), to, subject });
450
491
  // The first valid parallel task makes the role's instances durable before a single file of this mail exists.
451
492
  if (routing && flag === "on" && !routing.held(role))
452
493
  routing.enable(role);
453
494
  const held = !!routing?.held(role);
454
- const { msg, fresh } = deliverOnce(project, journal, source, { from: sender.name, to, type, subject, body, thread, reply_to: replyTo, ...(tierOf(to) ? { tier: tierOf(to) } : {}) }, {
495
+ const { msg, fresh } = deliverOnce(project, journal, source, { from: sender.name, to, type, subject, body, thread, reply_to: replyTo, ...(tierOf(to) ? { tier: tierOf(to) } : {}), ...(playbook ? { playbook } : {}), ...(readOnly ? { read_only: true } : {}) }, {
455
496
  ...(held ? { held: true } : {}),
456
497
  ...(held && flag === "on" ? { parallel: true } : {}),
457
498
  ...(routing?.held(roleOf(sender.name)) ? { from: sender.name } : {}),
@@ -459,8 +500,8 @@ export function routeOutboxes(project, routing) {
459
500
  if (!fresh)
460
501
  continue;
461
502
  res.delivered.push({ from: sender.name, to, id: msg.meta.id, file: msg.file, type, subject, ...(verdict ? { verdict } : {}) });
462
- if (missing.length)
463
- res.warnings.push({ from: sender.name, id: msg.meta.id, subject, missing });
503
+ if (missing.length || acceptance.length)
504
+ res.warnings.push({ from: sender.name, id: msg.meta.id, subject, missing, ...(acceptance.length ? { acceptance } : {}) });
464
505
  }
465
506
  fault("route:source-done");
466
507
  fs.mkdirSync(path.join(dir, "sent"), { recursive: true });
@@ -77,8 +77,18 @@ export interface ClaimRecord {
77
77
  files: string[];
78
78
  status: ClaimStatus;
79
79
  created: string;
80
+ /** Set when the wake must not edit the repo. Absent on older claims, which are not read-only. */
81
+ read_only?: true;
82
+ /** The checkout's HEAD when the read-only wake started. */
83
+ head?: string;
84
+ /** Paths already dirty at the start. A read-only wake does not put these back. */
85
+ dirty?: string[];
80
86
  }
81
87
  export declare function loadClaim(runDir: string, id: string): ClaimRecord;
88
+ /** Mark a claim read-only. `head` and `dirty` are the checkout at the start; shared mode may have neither. */
89
+ export declare function setClaimReadOnly(runDir: string, claimId: string, head?: string, dirty?: string[]): void;
90
+ /** The latest other claim for `agent`, read from disk. The in-memory map only holds the claim being woken. */
91
+ export declare function previousClaim(runDir: string, agent: string, exceptId: string): ClaimRecord | undefined;
82
92
  /** Record that `agent` is about to handle these messages. They stay unread until `commitClaim`. */
83
93
  export declare function claimMessages(runDir: string, agent: string, messages: {
84
94
  file: string;
@@ -158,6 +158,32 @@ function saveClaim(runDir, c) {
158
158
  export function loadClaim(runDir, id) {
159
159
  return JSON.parse(fs.readFileSync(claimFile(runDir, id), "utf8"));
160
160
  }
161
+ /** Mark a claim read-only. `head` and `dirty` are the checkout at the start; shared mode may have neither. */
162
+ export function setClaimReadOnly(runDir, claimId, head, dirty) {
163
+ const c = loadClaim(runDir, claimId);
164
+ saveClaim(runDir, { ...c, read_only: true, ...(head ? { head } : {}), ...(dirty ? { dirty } : {}) });
165
+ }
166
+ /** The latest other claim for `agent`, read from disk. The in-memory map only holds the claim being woken. */
167
+ export function previousClaim(runDir, agent, exceptId) {
168
+ const dir = path.join(mailDir(runDir), "claims");
169
+ if (!fs.existsSync(dir))
170
+ return undefined;
171
+ let best;
172
+ for (const name of fs.readdirSync(dir).filter((f) => f.endsWith(".json"))) {
173
+ let c;
174
+ try {
175
+ c = JSON.parse(fs.readFileSync(path.join(dir, name), "utf8"));
176
+ }
177
+ catch {
178
+ continue;
179
+ }
180
+ if (c.agent !== agent || c.id === exceptId)
181
+ continue;
182
+ if (!best || c.created > best.created)
183
+ best = c;
184
+ }
185
+ return best;
186
+ }
161
187
  /** Record that `agent` is about to handle these messages. They stay unread until `commitClaim`. */
162
188
  export function claimMessages(runDir, agent, messages) {
163
189
  const rec = {
package/dist/open-pr.d.ts CHANGED
@@ -47,6 +47,18 @@ export interface OpenPrInput {
47
47
  run: CommandRunner;
48
48
  /** The run already has a pull request for this branch: while it is still open only the branch is pushed; otherwise (merged, closed) a new one is opened. */
49
49
  existingUrl?: string;
50
+ /** The branch the pull request targets. Without it the repo's default branch is looked up. */
51
+ base?: string;
52
+ /** Git arguments that go in front of `push` (the pins that keep git from running anything an agent planted). */
53
+ pinnedGit?: string[];
50
54
  }
51
- /** Push the branch and open a pull request against the default branch. Never throws; says how to finish by hand when a step fails. */
55
+ /** The commands that finish the job by hand. `base` is left out when it is not known, so gh picks the repo's default branch. */
56
+ export declare function manualPrCommands(i: {
57
+ cwd: string;
58
+ branch: string;
59
+ base?: string;
60
+ title: string;
61
+ bodyFile: string;
62
+ }): string[];
63
+ /** Push the branch and open a pull request against `base` (the default branch when none is given). Never throws; says how to finish by hand when a step fails. */
52
64
  export declare function openPullRequest(i: OpenPrInput): OpenPrResult;