agent-lyceum 0.55.0 → 0.57.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.
package/dist/proposals.js CHANGED
@@ -1,8 +1,10 @@
1
1
  import fs from "node:fs";
2
2
  import path from "node:path";
3
3
  import { parse as parseYaml } from "yaml";
4
+ import { isVerdict } from "./attribution.js";
5
+ import { parseSlotName } from "./instances.js";
4
6
  import { readRegularFileNoFollow } from "./fs-util.js";
5
- import { proposalsKindDir, recordsDir, recordsKindDir } from "./policy.js";
7
+ import { proposalsKindDir, recordsDir, recordsKindDir, reviewerNames } from "./policy.js";
6
8
  import { RECORD_KINDS } from "./records.js";
7
9
  import { git, isGitRepo } from "./worktree.js";
8
10
  export const PROPOSAL_KINDS = RECORD_KINDS;
@@ -13,6 +15,8 @@ export const PENDING_SHOWN = 10;
13
15
  const ID_RE = /^[a-z0-9-]+$/;
14
16
  const DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
15
17
  const SHA_RE = /^[0-9a-f]{7,40}$/;
18
+ /** A run id is a timestamp, a hyphen, then lowercase letters or digits (`newRunId`). Nothing else is joined onto `runs/`. */
19
+ const RUN_ID_RE = /^\d{8}T\d+Z-[a-z0-9]+$/;
16
20
  /** The part of a run or call id that is unique: its first 8 lowercase letters or digits after the timestamp (D-10). */
17
21
  export function shortIdOf(runId) {
18
22
  const rest = runId.includes("-") ? runId.slice(runId.indexOf("-") + 1) : runId;
@@ -34,6 +38,37 @@ export function proposalStatusOf(buf) {
34
38
  }
35
39
  /** The id's own prefix: what comes before the first `-`. */
36
40
  export const prefixOf = (id) => id.split("-")[0] ?? "";
41
+ export { isReviewer, reviewerNames } from "./policy.js";
42
+ /** A run id (`newRunId`): timestamp, hyphen, then lowercase letters or digits. Solo proposals are not held to this. */
43
+ export const isRunId = (value) => RUN_ID_RE.test(value);
44
+ /**
45
+ * The reviewer a team file name belongs to. `id` is the file name without `.md`: `<8 lowercase letters or digits>-<agent>-<slug>`.
46
+ * When one reviewer name is a prefix of another (`cli-reviewer` and `cli-reviewer--2`), the longer name wins. A `<role>--<k>-<slug>`
47
+ * file belongs to that slot when the role is one of `names`, even if the slot itself is not. A solo `<short id>-<slug>` has no owner.
48
+ */
49
+ export function proposalOwner(id, names) {
50
+ const rest = /^[a-z0-9]{8}-(.+)$/.exec(id)?.[1];
51
+ if (!rest)
52
+ return undefined;
53
+ // `<role>--<k>-<slug>` belongs to that slot when the role is a reviewer, even if the slot is not in `names` (a later run, or doctor, has no instance table).
54
+ const slot = /^(.+--(?:[2-9]|[1-9]\d+))-([a-z0-9][a-z0-9-]*)$/.exec(rest);
55
+ if (slot?.[1] && slot[2]) {
56
+ const parsed = parseSlotName(slot[1]);
57
+ if (parsed && (names.includes(parsed.role) || names.includes(slot[1])))
58
+ return slot[1];
59
+ }
60
+ let best;
61
+ for (const name of names) {
62
+ if ((rest === name || rest.startsWith(`${name}-`)) && (best === undefined || name.length > best.length))
63
+ best = name;
64
+ }
65
+ if (!best || !rest.startsWith(`${best}-`) || rest.length === best.length + 1)
66
+ return undefined;
67
+ const slug = rest.slice(best.length + 1);
68
+ if (slug.startsWith("-") || !/^[a-z0-9-]+$/.test(slug))
69
+ return undefined;
70
+ return best;
71
+ }
37
72
  const isoDate = (v) => {
38
73
  // YAML parses an unquoted 2026-01-02 as a Date.
39
74
  const d = v instanceof Date ? v.toISOString().slice(0, 10) : v;
@@ -68,9 +103,37 @@ function parseEvidenceItem(item) {
68
103
  }
69
104
  return `unknown evidence kind "${key}"`;
70
105
  }
106
+ /** The evidence value as written, for the verbatim copy a record must carry. */
107
+ function evidenceRaw(item) {
108
+ if (!item || typeof item !== "object" || Array.isArray(item))
109
+ return undefined;
110
+ const keys = Object.keys(item);
111
+ if (keys.length !== 1)
112
+ return undefined;
113
+ const val = item[keys[0]];
114
+ return typeof val === "string" && val.trim() ? val.trim() : undefined;
115
+ }
116
+ /** `finding` is optional. A bad severity is still stored, so doctor can name `minor` or `nit`. */
117
+ function parseFinding(v, problems) {
118
+ if (!v || typeof v !== "object" || Array.isArray(v)) {
119
+ problems.push("finding must be a mapping");
120
+ return undefined;
121
+ }
122
+ const f = v;
123
+ const mail = oneLine(f.mail);
124
+ const severity = oneLine(f.severity);
125
+ const className = oneLine(f.class);
126
+ if (!mail || /[\\/]/.test(mail) || mail.includes(".."))
127
+ problems.push("finding.mail must be a file name");
128
+ if (!severity || (severity !== "blocker" && severity !== "major"))
129
+ problems.push("finding.severity must be blocker or major");
130
+ if (!className)
131
+ problems.push("finding.class must be one non-empty line");
132
+ return { mail: mail ?? "", severity: severity ?? "", className: className ?? "" };
133
+ }
71
134
  export function parseProposal(kind, file) {
72
135
  const id = path.basename(file, ".md");
73
- const base = { kind, id, file, date: "", title: path.basename(file), proposedBy: "", run: "", evidence: [], supersedes: [], body: "", bytes: 0, problems: [] };
136
+ const base = { kind, id, file, date: "", title: path.basename(file), proposedBy: "", run: "", evidence: [], evidenceText: [], supersedes: [], body: "", bytes: 0, problems: [] };
74
137
  // Never open a symlink or a FIFO/device (spec 30, acceptance 11).
75
138
  const buf = readRegularFileNoFollow(file);
76
139
  if (!buf)
@@ -112,6 +175,7 @@ export function parseProposal(kind, file) {
112
175
  if (!run)
113
176
  problems.push("run is required");
114
177
  const evidence = [];
178
+ const evidenceText = [];
115
179
  if (!Array.isArray(f.evidence) || f.evidence.length === 0)
116
180
  problems.push("evidence is required: at least one entry");
117
181
  else
@@ -119,9 +183,14 @@ export function parseProposal(kind, file) {
119
183
  const e = parseEvidenceItem(item);
120
184
  if (typeof e === "string")
121
185
  problems.push(e);
122
- else
186
+ else {
123
187
  evidence.push(e);
188
+ const raw = evidenceRaw(item);
189
+ if (raw)
190
+ evidenceText.push(raw);
191
+ }
124
192
  }
193
+ const finding = f.finding === undefined ? undefined : parseFinding(f.finding, problems);
125
194
  let supersedes = [];
126
195
  if (f.supersedes !== undefined) {
127
196
  if (Array.isArray(f.supersedes) && f.supersedes.every((x) => typeof x === "string"))
@@ -145,6 +214,8 @@ export function parseProposal(kind, file) {
145
214
  proposedBy: proposedBy ?? "",
146
215
  run: run ?? "",
147
216
  evidence,
217
+ evidenceText,
218
+ ...(finding ? { finding } : {}),
148
219
  ...(repo && path.isAbsolute(repo) ? { repo } : {}),
149
220
  ...(oneLine(f.scope) ? { scope: oneLine(f.scope) } : {}),
150
221
  supersedes,
@@ -201,22 +272,46 @@ export function describeProposals(project) {
201
272
  lines.push(` problem ${d.file}: ${d.problem}`);
202
273
  return lines;
203
274
  }
204
- /** Whether `<kind>/<id>` is a record of the project, live or archived by a tidy (`.archive/<stamp>/<kind>/<id>.md`). */
205
- function recordExists(project, ref) {
275
+ /** The live or archived file for `<kind>/<id>`, if one exists. */
276
+ function recordFile(project, ref) {
206
277
  const m = /^(decisions|lessons)\/([a-z0-9-]+)$/.exec(ref);
207
278
  if (!m)
208
- return false;
279
+ return undefined;
209
280
  const kind = m[1];
210
281
  const id = m[2];
211
- if (fs.existsSync(path.join(recordsKindDir(project, kind), `${id}.md`)))
212
- return true;
282
+ const live = path.join(recordsKindDir(project, kind), `${id}.md`);
283
+ if (fs.existsSync(live))
284
+ return live;
213
285
  const archive = path.join(recordsDir(project), ".archive");
214
286
  try {
215
- return fs.readdirSync(archive).some((stamp) => fs.existsSync(path.join(archive, stamp, kind, `${id}.md`)));
287
+ for (const stamp of fs.readdirSync(archive)) {
288
+ const file = path.join(archive, stamp, kind, `${id}.md`);
289
+ if (fs.existsSync(file))
290
+ return file;
291
+ }
216
292
  }
217
293
  catch {
218
- return false;
294
+ // no archive
219
295
  }
296
+ return undefined;
297
+ }
298
+ /** Whether `<kind>/<id>` is a record of the project, live or archived by a tidy (`.archive/<stamp>/<kind>/<id>.md`). */
299
+ const recordExists = (project, ref) => recordFile(project, ref) !== undefined;
300
+ /** Body after the frontmatter. A file that is not a regular file counts as empty, so a symlink is never treated as a copy. */
301
+ function recordBody(project, ref) {
302
+ const file = recordFile(project, ref);
303
+ const buf = file ? readRegularFileNoFollow(file) : undefined;
304
+ if (!buf)
305
+ return "";
306
+ const text = buf.toString("utf8");
307
+ const m = /^---\r?\n[\s\S]*?\r?\n---[ \t]*(?:\r?\n([\s\S]*))?$/.exec(text);
308
+ return m ? (m[1] ?? "") : text;
309
+ }
310
+ const hasEvidenceHeading = (body) => body.split(/\r?\n/).some((line) => line.trim() === "## Evidence");
311
+ function copiesFinding(body, p) {
312
+ if (!p.finding)
313
+ return false;
314
+ return [...p.evidenceText, p.finding.mail, p.finding.severity, p.finding.className].every((bit) => bit !== "" && body.includes(bit));
220
315
  }
221
316
  /**
222
317
  * Layer 1 of D-09: the lead's decisions are complete. Only decided proposals are looked at. An `accepted` one must be a
@@ -245,10 +340,187 @@ export function checkDecisions(proposals, project) {
245
340
  add(p, `accepted_as ${p.acceptedAs} is not a record of the project`);
246
341
  if (!p.decided)
247
342
  add(p, "accepted without decided (YYYY-MM-DD)");
343
+ const owner = proposalOwner(p.id, reviewerNames(project));
344
+ if (owner)
345
+ addReviewerAcceptance(p, project, owner, add);
248
346
  }
249
347
  }
250
348
  return out;
251
349
  }
350
+ /** Extra acceptance rules for a file a reviewer owns (issue 177). A solo file has no owner, so spec 30 is unchanged. */
351
+ function addReviewerAcceptance(p, project, owner, add) {
352
+ if (!isRunId(p.run))
353
+ add(p, "accepted but run must be a run id");
354
+ if (!p.finding)
355
+ add(p, "accepted but finding is required");
356
+ else if (p.finding.mail && !/[\\/]/.test(p.finding.mail) && !p.finding.mail.includes("..")) {
357
+ const mail = checkFindingMail(project, p.run, p.finding.mail, owner);
358
+ if (mail === "missing")
359
+ add(p, "accepted but finding.mail was not found");
360
+ else if (mail === "not-a-verdict-reply")
361
+ add(p, "accepted but finding.mail is not a reply with verdict");
362
+ }
363
+ if (p.proposedBy !== owner)
364
+ add(p, "accepted but proposed_by does not match the file name");
365
+ if (checkEvidence(p, project.dir).strength !== "verified")
366
+ add(p, "accepted but evidence is not verified");
367
+ if (!p.acceptedAs || !recordExists(project, p.acceptedAs))
368
+ return;
369
+ const body = recordBody(project, p.acceptedAs);
370
+ if (!hasEvidenceHeading(body))
371
+ add(p, "accepted but the record has no ## Evidence section");
372
+ else if (!copiesFinding(body, p))
373
+ add(p, "accepted but the record does not copy the evidence and finding");
374
+ }
375
+ /** A real directory, never a symlink. */
376
+ function realRunDir(dir) {
377
+ try {
378
+ const st = fs.lstatSync(dir);
379
+ return st.isDirectory() && !st.isSymbolicLink();
380
+ }
381
+ catch {
382
+ return false;
383
+ }
384
+ }
385
+ /**
386
+ * The run directory whose mail can be checked. `claimedRun` is used only when it is a run id whose short id matches and whose
387
+ * directory is still there. Otherwise the directory is the one under `runs/` with that short id, so a short id or a missing
388
+ * claimed directory cannot skip the check while the run still exists. No such directory means the run was cleared: `skip`.
389
+ * Several directories with the same short id, and none of them the claimed id, is `ambiguous` (checked as missing, never skipped).
390
+ */
391
+ function resolveFindingRunDir(project, claimedRun, shortId) {
392
+ const root = project.paths.runs;
393
+ if (RUN_ID_RE.test(claimedRun) && shortIdOf(claimedRun) === shortId) {
394
+ const claimed = path.join(root, claimedRun);
395
+ if (realRunDir(claimed) && fs.existsSync(path.join(claimed, "state.json")))
396
+ return claimed;
397
+ }
398
+ let names;
399
+ try {
400
+ names = fs.readdirSync(root);
401
+ }
402
+ catch {
403
+ return "skip";
404
+ }
405
+ const matches = [];
406
+ for (const name of names) {
407
+ if (!RUN_ID_RE.test(name) || shortIdOf(name) !== shortId)
408
+ continue;
409
+ const dir = path.join(root, name);
410
+ if (realRunDir(dir) && fs.existsSync(path.join(dir, "state.json")))
411
+ matches.push(dir);
412
+ }
413
+ if (matches.length === 1)
414
+ return matches[0];
415
+ if (matches.length === 0)
416
+ return "skip";
417
+ return "ambiguous";
418
+ }
419
+ /**
420
+ * Whether `mailBase` is one reply carrying `verdict:` under the run's mail. The file name is the one the reviewer wrote in
421
+ * their outbox: after routing, `sent/<name>` wins over a rejected copy of the same name, and over every other agent's outbox.
422
+ * A delivered copy (a different file name) is looked up in inboxes, including `pending/`. No run directory left, or `mail_layout`
423
+ * other than `run`, means the mail cannot be checked any more: that is `skip`, not a failure. `runId` is never joined onto
424
+ * `runs/` unless it is a single run id.
425
+ */
426
+ export function checkFindingMail(project, runId, mailBase, owner) {
427
+ if (!mailBase || /[\\/]/.test(mailBase) || mailBase.includes(".."))
428
+ return "missing";
429
+ const resolved = resolveFindingRunDir(project, runId, shortIdOf(runId));
430
+ if (resolved === "skip")
431
+ return "skip";
432
+ if (resolved === "ambiguous")
433
+ return "missing";
434
+ const runDir = resolved;
435
+ const stateFile = path.join(runDir, "state.json");
436
+ if (!fs.existsSync(stateFile))
437
+ return "skip";
438
+ let layout;
439
+ try {
440
+ layout = JSON.parse(fs.readFileSync(stateFile, "utf8")).mail_layout;
441
+ }
442
+ catch {
443
+ return "skip";
444
+ }
445
+ if (layout !== "run")
446
+ return "skip";
447
+ const file = locateFindingMail(runDir, mailBase, owner);
448
+ if (!file)
449
+ return "missing";
450
+ const buf = readRegularFileNoFollow(file);
451
+ if (!buf)
452
+ return "missing";
453
+ return isVerdictReply(buf.toString("utf8")) ? "ok" : "not-a-verdict-reply";
454
+ }
455
+ function isRegularFile(file) {
456
+ try {
457
+ return fs.lstatSync(file).isFile();
458
+ }
459
+ catch {
460
+ return false;
461
+ }
462
+ }
463
+ /**
464
+ * The owner's `sent/` copy is the one that was routed. A same-named file in `rejected/`, or in another agent's outbox, does not count beside it.
465
+ * Without an outbox copy, one inbox file (including `read/` and `pending/`) is the delivered name.
466
+ */
467
+ function locateFindingMail(runDir, mailBase, owner) {
468
+ if (owner && !/[\\/]/.test(owner) && !owner.includes("..")) {
469
+ const base = path.join(runDir, "mail", "outbox", owner);
470
+ const sent = path.join(base, "sent", mailBase);
471
+ if (isRegularFile(sent))
472
+ return sent;
473
+ const live = [path.join(base, mailBase), path.join(base, "read", mailBase)].filter(isRegularFile);
474
+ if (live.length > 1)
475
+ return undefined;
476
+ if (live.length === 1)
477
+ return live[0];
478
+ const rejected = path.join(base, "rejected", mailBase);
479
+ if (isRegularFile(rejected))
480
+ return rejected;
481
+ }
482
+ const hits = [];
483
+ const root = path.join(runDir, "mail", "inbox");
484
+ let agents;
485
+ try {
486
+ agents = fs.readdirSync(root).filter((name) => {
487
+ try {
488
+ const st = fs.lstatSync(path.join(root, name));
489
+ return st.isDirectory() && !st.isSymbolicLink();
490
+ }
491
+ catch {
492
+ return false;
493
+ }
494
+ });
495
+ }
496
+ catch {
497
+ return undefined;
498
+ }
499
+ for (const agent of agents) {
500
+ for (const dir of [path.join(root, agent), path.join(root, agent, "read"), path.join(root, agent, "pending")]) {
501
+ const file = path.join(dir, mailBase);
502
+ if (isRegularFile(file))
503
+ hits.push(file);
504
+ }
505
+ }
506
+ return hits.length === 1 ? hits[0] : undefined;
507
+ }
508
+ /** A reply (type omitted counts as reply, the same as the mailbox) whose `verdict` is one of the three review results. */
509
+ function isVerdictReply(text) {
510
+ const m = /^---\r?\n([\s\S]*?)\r?\n---/.exec(text);
511
+ if (!m)
512
+ return false;
513
+ try {
514
+ const fm = parseYaml(m[1]);
515
+ if (!fm || typeof fm !== "object" || Array.isArray(fm))
516
+ return false;
517
+ const type = fm.type ?? "reply";
518
+ return type === "reply" && isVerdict(fm.verdict);
519
+ }
520
+ catch {
521
+ return false;
522
+ }
523
+ }
252
524
  const tryGit = (cwd, args) => {
253
525
  try {
254
526
  return git(cwd, args);
package/dist/quota.js CHANGED
@@ -50,9 +50,16 @@ function windowOf(label, used, resets) {
50
50
  function roundPercent(n) {
51
51
  return Math.round(n * 10) / 10;
52
52
  }
53
+ const CLAUDE_USAGE = ["-p", "--no-session-persistence", "--output-format", "text", "/usage"];
54
+ const CODEX_LIMITS = ["app-server", "--stdio"];
55
+ const CODEX_LIMITS_NO_PLUGINS = ["app-server", "--disable", "plugins", "--stdio"];
56
+ const CLAUDE_ADDED_OPTIONS = ["--safe-mode"];
57
+ const CODEX_ADDED_OPTIONS = ["--disable", "plugins"];
53
58
  export async function claudeQuota(signal) {
54
59
  try {
55
- const text = await capture("claude", ["-p", "--no-session-persistence", "--output-format", "text", "/usage"], 20_000, signal);
60
+ let text = await capture("claude", ["--safe-mode", ...CLAUDE_USAGE], 20_000, signal);
61
+ if (optionRejected(text, CLAUDE_ADDED_OPTIONS))
62
+ text = await capture("claude", CLAUDE_USAGE, 20_000, signal);
56
63
  const windows = parseClaudeUsage(text.stdout);
57
64
  if (windows.length === 0)
58
65
  return { runtime: "claude", windows: [], error: firstLine(text.stderr) || firstLine(text.stdout) || "claude /usage 沒有回傳額度。" };
@@ -66,7 +73,15 @@ export async function claudeQuota(signal) {
66
73
  }
67
74
  export async function codexQuota(signal) {
68
75
  try {
69
- const limits = await readCodexLimits(signal);
76
+ let limits;
77
+ try {
78
+ limits = await readCodexLimits(signal, CODEX_LIMITS_NO_PLUGINS);
79
+ }
80
+ catch (error) {
81
+ if (isAbort(error) || !(error instanceof OptionRejected))
82
+ throw error;
83
+ limits = await readCodexLimits(signal, CODEX_LIMITS);
84
+ }
70
85
  return { runtime: "codex", windows: codexWindows(limits) };
71
86
  }
72
87
  catch (error) {
@@ -347,35 +362,61 @@ function missing(cmd, error) {
347
362
  function firstLine(text) {
348
363
  return text.split("\n").map((line) => line.trim()).find(Boolean) ?? "";
349
364
  }
365
+ /** An old CLI that does not know the new flag. Timeouts and aborts are not this. */
366
+ class OptionRejected extends Error {
367
+ constructor(message) {
368
+ super(message);
369
+ this.name = "OptionRejected";
370
+ }
371
+ }
372
+ /** The rejection names one of the flags this version added. Any other unknown option stays a real failure. */
373
+ function addedOptionRejected(text, added) {
374
+ for (const match of text.matchAll(/(?:unknown option|unexpected argument)\s+(['"]?)([^\s'"]+)\1/gi)) {
375
+ const name = match[2];
376
+ if (name && added.includes(name))
377
+ return true;
378
+ }
379
+ return false;
380
+ }
381
+ function optionRejected(out, added) {
382
+ return out.code !== 0 && out.code !== null && addedOptionRejected(`${out.stderr}\n${out.stdout}`, added);
383
+ }
350
384
  function capture(cmd, args, timeoutMs, signal) {
351
385
  return new Promise((resolve, reject) => {
352
386
  const child = spawn(cmd, args, { stdio: ["ignore", "pipe", "pipe"], ...(signal ? { signal } : {}) });
353
387
  let stdout = "";
354
388
  let stderr = "";
389
+ let settled = false;
355
390
  const timer = setTimeout(() => {
391
+ if (settled)
392
+ return;
393
+ settled = true;
356
394
  child.kill();
357
395
  reject(new Error(`${cmd} 超過 ${Math.round(timeoutMs / 1000)} 秒沒有回應。`));
358
396
  }, timeoutMs);
359
397
  child.stdout.on("data", (chunk) => (stdout += String(chunk)));
360
398
  child.stderr.on("data", (chunk) => (stderr += String(chunk)));
361
399
  child.on("error", (error) => {
400
+ if (settled)
401
+ return;
402
+ settled = true;
362
403
  clearTimeout(timer);
363
404
  reject(error);
364
405
  });
365
- child.on("close", () => {
406
+ child.on("close", (code) => {
407
+ if (settled)
408
+ return;
409
+ settled = true;
366
410
  clearTimeout(timer);
367
- resolve({ stdout, stderr });
411
+ resolve({ stdout, stderr, code });
368
412
  });
369
413
  });
370
414
  }
371
- function readCodexLimits(signal) {
415
+ function readCodexLimits(signal, args) {
372
416
  return new Promise((resolve, reject) => {
373
- const child = spawn("codex", ["app-server", "--stdio"], { stdio: ["pipe", "pipe", "pipe"], ...(signal ? { signal } : {}) });
417
+ const child = spawn("codex", args, { stdio: ["pipe", "pipe", "pipe"], ...(signal ? { signal } : {}) });
374
418
  let buf = "";
375
- const timer = setTimeout(() => {
376
- child.kill();
377
- reject(new Error("codex 超過 20 秒沒有回應。"));
378
- }, 20_000);
419
+ let stderr = "";
379
420
  let done = false;
380
421
  const finish = (error, limits) => {
381
422
  if (done)
@@ -388,7 +429,18 @@ function readCodexLimits(signal) {
388
429
  else
389
430
  resolve(limits ?? {});
390
431
  };
432
+ const timer = setTimeout(() => {
433
+ finish(new Error("codex 超過 20 秒沒有回應。"));
434
+ }, 20_000);
391
435
  child.on("error", (error) => finish(error));
436
+ child.stderr.on("data", (chunk) => (stderr += String(chunk)));
437
+ child.on("close", (code) => {
438
+ const text = `${stderr}\n${buf}`;
439
+ if (code !== 0 && code !== null && addedOptionRejected(text, CODEX_ADDED_OPTIONS))
440
+ finish(new OptionRejected(firstLine(text)));
441
+ else
442
+ finish(new Error(firstLine(stderr) || firstLine(buf) || "codex 沒有回傳額度。"));
443
+ });
392
444
  child.stdout.on("data", (chunk) => {
393
445
  buf += String(chunk);
394
446
  let cut = buf.indexOf("\n");
@@ -6,7 +6,7 @@ import { agentForCandidate, candidatesFor, Cooldowns, defaultSleep, deferredAtte
6
6
  import { compareWithLastRejection, repeatAction, repeatStopNote, stoppedInSegment, withRepeatLabel } from "./repeat-detect.js";
7
7
  import { commandPassed, describeFailure, rejectionMessage, runVerify, verificationSection } from "./verify.js";
8
8
  import { briefOf, digestOf, doneContract, mergeSteps, parseSteps } from "./format.js";
9
- import { otherCallPrefixes, ProtectedGuard, runsStartedAfter } from "./guard.js";
9
+ import { otherCallPrefixes, proposalForeignPrefixes, ProtectedGuard, runsStartedAfter } from "./guard.js";
10
10
  import { listRunLocks, lockHolderAlive } from "./project-lock.js";
11
11
  import { addBatch, askersWithAnswers, askReplyPath, checkAnswers, describeCheck, isComplete, markDelivered, parseAskBody, readAskReply, renderAnswers, resolveOptionLetters, writeAskReply } from "./ask-reply.js";
12
12
  import { deliver, deliverOnce, ensureAgentDirs, ensureProjectDirs, finishDone, listUnread, PENDING_DIR, readMessageNoFollow, rejectDone, routeOutboxes, unreadFiles } from "./mailbox.js";
@@ -19,7 +19,7 @@ import { crossRuntimeBlock } from "./review-gate.js";
19
19
  import { unboundCommands } from "./task-bind.js";
20
20
  import { capBatch, DEFAULT_MAX_AWAKE } from "./wake-cap.js";
21
21
  import { wakeIsReadOnly } from "./playbook.js";
22
- import { coordinatePolicy, inboxDir, osSandboxAvailable, outboxDir, proposalsDir, readOnlyPolicy, sharedIndex } from "./policy.js";
22
+ import { coordinatePolicy, ensureReviewerProposalDir, inboxDir, osSandboxAvailable, outboxDir, proposalsDir, readOnlyPolicy, sharedIndex } from "./policy.js";
23
23
  import { buildSystemPrompt, buildUserPrompt, pickMessages } from "./prompt.js";
24
24
  import { collectDrafts, priorFailedAttempts, redoUserPrompt } from "./redo.js";
25
25
  import { atomicWrite, readFileCapped } from "./fs-util.js";
@@ -238,6 +238,8 @@ export class RunSession {
238
238
  // The agent of `run --agent` writes its proposals here; runtimes only get a directory that exists (spec 30, D-18).
239
239
  if (project.solo === "run")
240
240
  fs.mkdirSync(proposalsDir(project), { recursive: true });
241
+ else
242
+ ensureReviewerProposalDir(project);
241
243
  fs.mkdirSync(runDir, { recursive: true });
242
244
  const log = createRunLog(path.join(runDir, "log.jsonl"), cfg.log_max_bytes);
243
245
  if (concurrent && !resume) {
@@ -324,7 +326,10 @@ export class RunSession {
324
326
  // Concurrent runs: the repo's instruction files the run can touch are the lead worktree's copies; your own tree is never watched (or restored).
325
327
  const otherLiveRuns = () => listRunLocks(project.paths.root).filter((l) => !l.call && l.run_id !== runId && lockHolderAlive(l)).map((l) => l.run_id);
326
328
  // A solo agent is judged against every other run that began while it worked, live or not (spec 30, D-03): such a run's lead may write the shared files.
327
- const guardOpts = project.solo ? { startedAfter: (stamp) => runsStartedAfter(project.paths.runs, stamp, runId), otherPrefixes: otherCallPrefixes(project.home, project.paths.root, runId) } : {};
329
+ // A normal run does not feed those runs into `other` (that would keep every proposal change). It only leaves their proposal prefixes alone.
330
+ const guardOpts = project.solo
331
+ ? { startedAfter: (stamp) => runsStartedAfter(project.paths.runs, stamp, runId), otherPrefixes: otherCallPrefixes(project.home, project.paths.root, runId) }
332
+ : { otherPrefixes: proposalForeignPrefixes(project.home, project.paths.root, project.paths.runs, runId) };
328
333
  const guard = new ProtectedGuard(leadSpace ? { ...project, workspaces: { ...project.workspaces, [project.lead]: leadSpace } } : project, otherLiveRuns, guardOpts);
329
334
  if (resume) {
330
335
  log("resume", { rounds: state.rounds, interrupted: Object.keys(resume.active ?? {}) });
@@ -15,8 +15,9 @@ export type WatchFrame = {
15
15
  */
16
16
  /**
17
17
  * Reports of finished runs, kept so a sweep does not rebuild them (about 300 ms each). An entry is reused while the
18
- * run's state.json is unchanged and it is younger than `FINISHED_TTL_MS`; the TTL picks up what lives outside that file
19
- * (unread mail, memory advice).
18
+ * run's state.json is unchanged and it is younger than `FINISHED_TTL_MS`. That TTL still covers what lives outside
19
+ * the file, such as unread mail. Advice is copied from the lines passed for this call, so it stays inside
20
+ * `ADVICE_TTL_MS` and the two TTLs do not stack.
20
21
  */
21
22
  export type FinishedCache = Map<string, {
22
23
  stamp: string;
@@ -26,6 +27,7 @@ export type FinishedCache = Map<string, {
26
27
  export declare function buildWatchFrame(project: ResolvedProject, tracked: Set<string>, opts?: {
27
28
  allTasks?: boolean;
28
29
  cache?: FinishedCache;
30
+ advice?: string[];
29
31
  }): WatchFrame;
30
32
  export interface WatchDeps {
31
33
  /** The project, loaded again each time so config edits and new runs show up. */
@@ -1,7 +1,19 @@
1
1
  import fs from "node:fs";
2
2
  import path from "node:path";
3
- import { buildStatusReport, buildTaskListReport, currentRun, isFinishedRun } from "./status.js";
3
+ import { buildStatusReport, buildTaskListReport, currentRun, isFinishedRun, memoryAdviceLines } from "./status.js";
4
4
  const FINISHED_TTL_MS = 5 * 60_000;
5
+ /** Tidy advice is the same for every run of a project. Recompute it on this cadence, not on every beat. */
6
+ const ADVICE_TTL_MS = 5 * 60_000;
7
+ function withAdvice(report, advice) {
8
+ const current = report.memory_advice ?? [];
9
+ if (current.length === advice.length && current.every((line, index) => line === advice[index]))
10
+ return report;
11
+ if (advice.length === 0) {
12
+ const { memory_advice: _dropped, ...rest } = report;
13
+ return rest;
14
+ }
15
+ return { ...report, memory_advice: advice };
16
+ }
5
17
  function stampOf(project, id) {
6
18
  try {
7
19
  const st = fs.statSync(path.join(project.paths.runs, id, "state.json"));
@@ -21,14 +33,18 @@ export function buildWatchFrame(project, tracked, opts) {
21
33
  const finished = new Set(all.filter(isFinishedRun).map((r) => r.run_id));
22
34
  const cache = opts?.cache;
23
35
  const now = Date.now();
36
+ const advice = opts?.advice ?? memoryAdviceLines(project);
24
37
  for (const id of new Set(ids)) {
25
38
  const stamp = cache && finished.has(id) ? stampOf(project, id) : "";
26
39
  const hit = stamp ? cache?.get(id) : undefined;
27
40
  if (hit && hit.stamp === stamp && now - hit.at < FINISHED_TTL_MS) {
28
- runs[id] = hit.report;
41
+ const report = withAdvice(hit.report, advice);
42
+ if (report !== hit.report)
43
+ cache?.set(id, { stamp: hit.stamp, at: hit.at, report });
44
+ runs[id] = report;
29
45
  continue;
30
46
  }
31
- runs[id] = buildStatusReport(project, id);
47
+ runs[id] = buildStatusReport(project, id, now, advice);
32
48
  if (stamp)
33
49
  cache?.set(id, { stamp, at: now, report: runs[id] });
34
50
  }
@@ -38,7 +54,7 @@ export function buildWatchFrame(project, tracked, opts) {
38
54
  cache.delete(id);
39
55
  // The project's own report shows the current run, which is usually one already built above.
40
56
  const currentId = currentRun(project)?.state.run_id;
41
- const report = currentId && runs[currentId] ? runs[currentId] : buildStatusReport(project);
57
+ const report = currentId && runs[currentId] ? runs[currentId] : buildStatusReport(project, undefined, now, advice);
42
58
  tracked.clear();
43
59
  for (const id of running)
44
60
  tracked.add(id);
@@ -60,12 +76,18 @@ export function createStatusWatcher(d) {
60
76
  let watching = "";
61
77
  let watcher;
62
78
  let timer;
79
+ let adviceCache;
63
80
  const emit = () => {
64
81
  let frame;
65
82
  let project;
66
83
  try {
67
84
  project = d.load();
68
- frame = buildWatchFrame(project, tracked, { allTasks: d.allTasks, cache });
85
+ const now = Date.now();
86
+ const key = `${project.name}\0${project.dir}`;
87
+ if (!adviceCache || adviceCache.key !== key || now - adviceCache.at >= ADVICE_TTL_MS) {
88
+ adviceCache = { key, at: now, lines: memoryAdviceLines(project) };
89
+ }
90
+ frame = buildWatchFrame(project, tracked, { allTasks: d.allTasks, cache, advice: adviceCache.lines });
69
91
  }
70
92
  catch (e) {
71
93
  frame = { schema_version: 1, error: e.message };
package/dist/status.d.ts CHANGED
@@ -177,8 +177,10 @@ export declare function buildRunReport(run: {
177
177
  }): RunReport;
178
178
  /** A run that ended with a `completed` or `partial` outcome: the only kinds the monitor stops listing (blocked, failed and cancelled stay). */
179
179
  export declare const isFinishedRun: (r: Pick<RunReport, "state" | "outcome">) => boolean;
180
+ /** Tidy hints for a status report. A failure is an empty list: a hint must not break status. */
181
+ export declare function memoryAdviceLines(project: ResolvedProject): string[];
180
182
  /** The status of a project: its agents and one run (the newest running one, else the newest, or the one named by `runId`). */
181
- export declare function buildStatusReport(base: ResolvedProject, runId?: string, now?: number): StatusReport;
183
+ export declare function buildStatusReport(base: ResolvedProject, runId?: string, now?: number, memoryAdvice?: string[]): StatusReport;
182
184
  /** Every run of the project, newest first. */
183
185
  export declare function buildTaskListReport(project: ResolvedProject): TaskListReport;
184
186
  /** Live view: summary and agent table, plus the latest run and any run still going, wake by wake. */