agent-lyceum 0.49.2 → 0.51.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/cli.js CHANGED
@@ -285,6 +285,7 @@ program
285
285
  .option("--task-file <path>", "read the task from a file")
286
286
  .option("--agent <name>", "run only this member of the project, alone: it cannot mail teammates or ask you, and its own `done` ends the run")
287
287
  .option("--name <name>", "name for this run (default: made from the task)")
288
+ .option("--tidy", "mark this run as a commit tidy (the web console shows a tag on it)")
288
289
  .option("--assume-defaults", "when the run stops to ask, use the suggested answer for every question that has one")
289
290
  .action(async (task, opts) => {
290
291
  try {
@@ -325,7 +326,7 @@ program
325
326
  for (const w of lintTaskContent(prepared.content))
326
327
  console.error(`warning: task file ${w}`);
327
328
  const name = opts.name ?? uniqueName(slugify(taskMessageBody(prepared).subject), taken);
328
- summary = await runTeam({ project: pr, name, plan, task: prepared, runDir, soloAgent: opts.agent, signal: cancel.signal });
329
+ summary = await runTeam({ project: pr, name, plan, task: prepared, runDir, soloAgent: opts.agent, tidy: opts.tidy, signal: cancel.signal });
329
330
  }
330
331
  finally {
331
332
  cancel.dispose();
@@ -709,7 +710,11 @@ program
709
710
  console.log(` restored proposals/${f}`);
710
711
  for (const k of r.proposals?.skipped ?? [])
711
712
  console.log(` skipped proposals/${k.rel}: ${k.reason}`);
712
- if (!r.restored.length && !r.skipped.length && !r.records?.restored.length && !r.records?.skipped.length && !r.proposals?.restored.length && !r.proposals?.skipped.length)
713
+ for (const f of r.promoted?.removed ?? [])
714
+ console.log(` removed records/${f} (promoted by that tidy)`);
715
+ for (const k of r.promoted?.kept ?? [])
716
+ console.log(` kept records/${k.rel}: ${k.reason}`);
717
+ if (!r.restored.length && !r.skipped.length && !r.records?.restored.length && !r.records?.skipped.length && !r.proposals?.restored.length && !r.proposals?.skipped.length && !r.promoted)
713
718
  console.log(`Archive ${opts.undo} holds no files to restore.`);
714
719
  }
715
720
  finally {
@@ -7,9 +7,32 @@ export type DecisionLogResult = {
7
7
  };
8
8
  /** Where the entry for a run goes: one stable file per run, so saving twice is harmless. */
9
9
  export declare function decisionLogId(runId: string): string;
10
+ type DecisionEntry = {
11
+ id: string;
12
+ text: string;
13
+ outcome?: string;
14
+ };
10
15
  /**
11
16
  * Keep what a run decided before `clear` deletes the run folder: its `## Decisions` (and `## Not done` as consequences) with the
12
17
  * task as context. Never overwrites an existing entry. Returns `none` when the run reported no decision.
13
18
  * Throws when the entry cannot be written, so the caller can stop before deleting anything.
14
19
  */
15
20
  export declare function saveRunDecisions(project: ResolvedProject, runId: string): DecisionLogResult;
21
+ /**
22
+ * The decisions a tidy should turn into records before it tidies: the `## Decisions` of every completed run, plus what `clear`
23
+ * kept in the decision log, minus what the records already hold. Only completed runs count; a partial or failed run's choices
24
+ * are often provisional. Writes nothing.
25
+ */
26
+ export declare function listPromotable(project: ResolvedProject): DecisionEntry[];
27
+ export declare const promotedManifest: (project: ResolvedProject, stamp: string) => string;
28
+ /** Write `listPromotable` into `records/decisions/` (never over an existing file) and note them under `stamp` so `tidy --undo` can take them back. */
29
+ export declare function promoteDecisions(project: ResolvedProject, stamp: string): string[];
30
+ /** Remove what the tidy `stamp` promoted, except files someone has changed since. */
31
+ export declare function undoPromoted(project: ResolvedProject, stamp: string): {
32
+ removed: string[];
33
+ kept: {
34
+ rel: string;
35
+ reason: string;
36
+ }[];
37
+ };
38
+ export {};
@@ -1,6 +1,7 @@
1
+ import crypto from "node:crypto";
1
2
  import fs from "node:fs";
2
3
  import path from "node:path";
3
- import { decisionLogDir } from "./policy.js";
4
+ import { decisionLogDir, recordsDir, recordsKindDir } from "./policy.js";
4
5
  /** Body of the `## <name>` section of a done report, up to the next `## ` heading. */
5
6
  function section(text, name) {
6
7
  const m = new RegExp(`^##[ \\t]+${name}[ \\t]*\\r?\\n([\\s\\S]*?)(?=^##[ \\t]|(?![\\s\\S]))`, "m").exec(text);
@@ -15,29 +16,27 @@ const oneLine = (s) => s.replace(/\s+/g, " ").trim();
15
16
  export function decisionLogId(runId) {
16
17
  return `run-${runId.toLowerCase().replace(/[^a-z0-9-]/g, "").slice(0, 28)}`;
17
18
  }
18
- /**
19
- * Keep what a run decided before `clear` deletes the run folder: its `## Decisions` (and `## Not done` as consequences) with the
20
- * task as context. Never overwrites an existing entry. Returns `none` when the run reported no decision.
21
- * Throws when the entry cannot be written, so the caller can stop before deleting anything.
22
- */
23
- export function saveRunDecisions(project, runId) {
19
+ /** The decision-log entry of one run, or why there is none. Reads the run's report and state; writes nothing. */
20
+ function buildEntry(project, runId) {
24
21
  const runDir = path.join(project.paths.runs, runId);
25
22
  let result;
26
23
  try {
27
24
  result = fs.readFileSync(path.join(runDir, "result.md"), "utf8");
28
25
  }
29
26
  catch {
30
- return { status: "none", reason: "no result.md" };
27
+ return { reason: "no result.md" };
31
28
  }
32
29
  const decisions = section(result, "Decisions");
33
30
  if (isEmpty(decisions))
34
- return { status: "none", reason: "the report lists no decisions" };
31
+ return { reason: "the report lists no decisions" };
35
32
  let summary = "";
36
33
  let started = "";
34
+ let stateOutcome;
37
35
  try {
38
36
  const state = JSON.parse(fs.readFileSync(path.join(runDir, "state.json"), "utf8"));
39
37
  summary = state.task_summary ?? "";
40
38
  started = state.started_at ?? "";
39
+ stateOutcome = state.outcome;
41
40
  }
42
41
  catch {
43
42
  // The report is enough to keep.
@@ -45,10 +44,9 @@ export function saveRunDecisions(project, runId) {
45
44
  const heading = /^#\s+(.+)$/m.exec(result)?.[1]?.trim();
46
45
  const title = oneLine(heading || summary || runId).slice(0, 200);
47
46
  const date = /^\d{4}-\d{2}-\d{2}/.exec(started)?.[0] ?? new Date().toISOString().slice(0, 10);
48
- const outcome = /^\*\*Outcome:\*\*\s*(\S+)/m.exec(result)?.[1];
47
+ const outcome = /^\*\*Outcome:\*\*\s*(\S+)/m.exec(result)?.[1] ?? stateOutcome;
49
48
  const notDone = section(result, "Not done");
50
49
  const id = decisionLogId(runId);
51
- const file = path.join(decisionLogDir(project), `${id}.md`);
52
50
  const text = [
53
51
  "---",
54
52
  "status: active",
@@ -65,6 +63,19 @@ export function saveRunDecisions(project, runId) {
65
63
  ...(isEmpty(notDone) ? [] : ["", "## Consequences", notDone]),
66
64
  "",
67
65
  ].join("\n");
66
+ return { entry: { id, text, ...(outcome ? { outcome } : {}) } };
67
+ }
68
+ /**
69
+ * Keep what a run decided before `clear` deletes the run folder: its `## Decisions` (and `## Not done` as consequences) with the
70
+ * task as context. Never overwrites an existing entry. Returns `none` when the run reported no decision.
71
+ * Throws when the entry cannot be written, so the caller can stop before deleting anything.
72
+ */
73
+ export function saveRunDecisions(project, runId) {
74
+ const built = buildEntry(project, runId);
75
+ if ("reason" in built)
76
+ return { status: "none", reason: built.reason };
77
+ const { id, text } = built.entry;
78
+ const file = path.join(decisionLogDir(project), `${id}.md`);
68
79
  fs.mkdirSync(path.dirname(file), { recursive: true });
69
80
  try {
70
81
  fs.writeFileSync(file, text, { flag: "wx" });
@@ -76,3 +87,129 @@ export function saveRunDecisions(project, runId) {
76
87
  }
77
88
  return { status: "saved", id, file };
78
89
  }
90
+ const ID_FILE_RE = /^[a-z0-9-]+\.md$/;
91
+ const sha = (text) => crypto.createHash("sha256").update(text).digest("hex");
92
+ /** Ids the records already hold for decisions, live or archived by a tidy: a decision a tidy merged away must not come back. */
93
+ function knownDecisionIds(project) {
94
+ const known = new Set();
95
+ const add = (dir) => {
96
+ try {
97
+ for (const n of fs.readdirSync(dir))
98
+ if (ID_FILE_RE.test(n))
99
+ known.add(n.slice(0, -3));
100
+ }
101
+ catch {
102
+ // A missing folder holds nothing.
103
+ }
104
+ };
105
+ add(recordsKindDir(project, "decisions"));
106
+ const archive = path.join(recordsDir(project), ".archive");
107
+ try {
108
+ for (const stamp of fs.readdirSync(archive))
109
+ add(path.join(archive, stamp, "decisions"));
110
+ }
111
+ catch {
112
+ // No archive yet.
113
+ }
114
+ return known;
115
+ }
116
+ /**
117
+ * The decisions a tidy should turn into records before it tidies: the `## Decisions` of every completed run, plus what `clear`
118
+ * kept in the decision log, minus what the records already hold. Only completed runs count; a partial or failed run's choices
119
+ * are often provisional. Writes nothing.
120
+ */
121
+ export function listPromotable(project) {
122
+ const known = knownDecisionIds(project);
123
+ const out = new Map();
124
+ let runs = [];
125
+ try {
126
+ runs = fs.readdirSync(project.paths.runs, { withFileTypes: true }).filter((d) => d.isDirectory()).map((d) => d.name).sort();
127
+ }
128
+ catch {
129
+ // No runs yet.
130
+ }
131
+ for (const runId of runs) {
132
+ const built = buildEntry(project, runId);
133
+ if ("reason" in built || built.entry.outcome !== "completed" || known.has(built.entry.id))
134
+ continue;
135
+ out.set(built.entry.id, built.entry);
136
+ }
137
+ let kept = [];
138
+ try {
139
+ kept = fs.readdirSync(decisionLogDir(project)).filter((n) => ID_FILE_RE.test(n)).sort();
140
+ }
141
+ catch {
142
+ // No decision log.
143
+ }
144
+ for (const n of kept) {
145
+ const id = n.slice(0, -3);
146
+ if (known.has(id))
147
+ continue;
148
+ let text;
149
+ try {
150
+ text = fs.readFileSync(path.join(decisionLogDir(project), n), "utf8");
151
+ }
152
+ catch {
153
+ continue;
154
+ }
155
+ if (!/^outcome:\s*completed\s*$/m.test(/^---\r?\n([\s\S]*?)\r?\n---/.exec(text)?.[1] ?? ""))
156
+ continue;
157
+ out.set(id, { id, text, outcome: "completed" });
158
+ }
159
+ return [...out.values()];
160
+ }
161
+ export const promotedManifest = (project, stamp) => path.join(project.paths.root, "tidy-promoted", `${stamp}.json`);
162
+ /** Write `listPromotable` into `records/decisions/` (never over an existing file) and note them under `stamp` so `tidy --undo` can take them back. */
163
+ export function promoteDecisions(project, stamp) {
164
+ const todo = listPromotable(project);
165
+ const dir = recordsKindDir(project, "decisions");
166
+ const done = [];
167
+ for (const e of todo) {
168
+ fs.mkdirSync(dir, { recursive: true });
169
+ try {
170
+ fs.writeFileSync(path.join(dir, `${e.id}.md`), e.text, { flag: "wx" });
171
+ }
172
+ catch (err) {
173
+ if (err.code === "EEXIST")
174
+ continue;
175
+ throw err;
176
+ }
177
+ done.push({ rel: `decisions/${e.id}.md`, sha: sha(e.text) });
178
+ }
179
+ if (done.length) {
180
+ fs.mkdirSync(path.dirname(promotedManifest(project, stamp)), { recursive: true });
181
+ fs.writeFileSync(promotedManifest(project, stamp), JSON.stringify({ files: done }, null, 2));
182
+ }
183
+ return done.map((d) => d.rel.slice("decisions/".length, -3));
184
+ }
185
+ /** Remove what the tidy `stamp` promoted, except files someone has changed since. */
186
+ export function undoPromoted(project, stamp) {
187
+ const removed = [];
188
+ const kept = [];
189
+ let files;
190
+ try {
191
+ files = JSON.parse(fs.readFileSync(promotedManifest(project, stamp), "utf8")).files;
192
+ }
193
+ catch {
194
+ return { removed, kept };
195
+ }
196
+ for (const f of files) {
197
+ const file = path.join(recordsDir(project), f.rel);
198
+ let text;
199
+ try {
200
+ text = fs.readFileSync(file, "utf8");
201
+ }
202
+ catch {
203
+ kept.push({ rel: f.rel, reason: "it is gone already (archived or deleted)" });
204
+ continue;
205
+ }
206
+ if (sha(text) !== f.sha) {
207
+ kept.push({ rel: f.rel, reason: "it was changed after the tidy; it was not removed" });
208
+ continue;
209
+ }
210
+ fs.rmSync(file);
211
+ removed.push(f.rel);
212
+ }
213
+ fs.rmSync(promotedManifest(project, stamp), { force: true });
214
+ return { removed, kept };
215
+ }
@@ -157,6 +157,14 @@ export interface RestoreResult {
157
157
  reason: string;
158
158
  }[];
159
159
  };
160
+ /** The decisions that tidy had turned into records, taken back out (a file changed since is kept). */
161
+ promoted?: {
162
+ removed: string[];
163
+ kept: {
164
+ rel: string;
165
+ reason: string;
166
+ }[];
167
+ };
160
168
  }
161
169
  /**
162
170
  * Move the files of one tidy's archive back to where they were. Nothing that exists now is overwritten.
@@ -7,6 +7,7 @@ import { atomicWrite } from "./fs-util.js";
7
7
  import { ensureProjectDirs } from "./mailbox.js";
8
8
  import { commonFile, memoryDirs, proposalsDir, recordsDir, repoDirFor, writePolicy } from "./policy.js";
9
9
  import { parseProposal, PROPOSAL_KINDS } from "./proposals.js";
10
+ import { listPromotable, promoteDecisions, undoPromoted } from "./decision-log.js";
10
11
  import { buildTidyPrompts, MEMORY_INDEX_LIMIT } from "./prompt.js";
11
12
  import { activeRecordsBytes, effectiveActive, listRecords, RECORD_KINDS, RECORDS_BUDGET } from "./records.js";
12
13
  import { git, isGitRepo } from "./worktree.js";
@@ -450,6 +451,20 @@ async function tidyOne(o, t, stamp, withRecords) {
450
451
  /** Tidy the memory of the chosen agents, one after another. Only ever called by a person (`agent-lyceum tidy`). */
451
452
  export async function tidyMemory(o) {
452
453
  const say = o.say ?? ((s) => console.log(s));
454
+ const stamp = tidyStamp(o.now?.()); // one per tidy, for every agent
455
+ // Before the lead tidies the records, decisions that runs reported become records, so the tidy can merge them with what is there.
456
+ if (recordsInScope(o)) {
457
+ if (o.dryRun) {
458
+ const todo = listPromotable(o.project);
459
+ if (todo.length)
460
+ say(`decisions to promote into the project records: ${todo.map((e) => e.id).join(", ")}`);
461
+ }
462
+ else {
463
+ const ids = promoteDecisions(o.project, stamp);
464
+ if (ids.length)
465
+ say(`promoted ${ids.length} decision(s) into the project records: ${ids.join(", ")}`);
466
+ }
467
+ }
453
468
  const withRecords = recordsInScope(o) && (liveRecordFiles(o.project).length > 0 || liveProposalFiles(o.project).length > 0);
454
469
  const lead = o.project.lead;
455
470
  let targets;
@@ -463,7 +478,6 @@ export async function tidyMemory(o) {
463
478
  targets = [];
464
479
  }
465
480
  const results = [];
466
- const stamp = tidyStamp(o.now?.()); // one per tidy, for every agent
467
481
  const jobs = targets.map((t) => ({ ...t }));
468
482
  if (withRecords && !jobs.some((j) => j.agent === lead))
469
483
  jobs.push({ agent: lead, layer: o.layer, dir: undefined });
@@ -545,7 +559,9 @@ export function restoreMemory(o) {
545
559
  }
546
560
  const archive = dir ? path.join(dir, ARCHIVE_DIR, o.stamp) : undefined;
547
561
  const memHas = !!archive && fs.existsSync(archive);
548
- if (!memHas && !recHas && !propHas) {
562
+ const promoted = isLead ? undoPromoted(o.project, o.stamp) : undefined;
563
+ const promotedAny = !!promoted && (promoted.removed.length > 0 || promoted.kept.length > 0);
564
+ if (!memHas && !recHas && !propHas && !promotedAny) {
549
565
  const recs = isLead ? `${dir ? "; project records archives: " : " Project records archives: "}${listArchives(recDir).join(", ") || "(none)"}` : "";
550
566
  throw new Error(`No archive ${o.stamp} for ${o.agent} (${o.layer}).${dir ? ` Archives: ${listArchives(dir).join(", ") || "(none)"}` : ""}${recs}.`);
551
567
  }
@@ -557,7 +573,7 @@ export function restoreMemory(o) {
557
573
  if (add.length)
558
574
  atomicWrite(indexFile, `${index.replace(/\n*$/, index ? "\n" : "")}${add.join("\n")}\n`);
559
575
  }
560
- return { ...mem, ...(recHas ? { records: moveBack(recDir, recArchive) } : {}), ...(propHas ? { proposals: moveBack(pDir, propArchive) } : {}) };
576
+ return { ...mem, ...(recHas ? { records: moveBack(recDir, recArchive) } : {}), ...(propHas ? { proposals: moveBack(pDir, propArchive) } : {}), ...(promotedAny ? { promoted } : {}) };
561
577
  }
562
578
  /** The stamps of the archives in a memory directory, oldest first. */
563
579
  export function listArchives(dir) {
@@ -49,6 +49,8 @@ export interface RunOptions {
49
49
  name?: string;
50
50
  /** Run only this member of the project, alone (`run --agent`). A resumed run uses the one recorded in its state. */
51
51
  soloAgent?: string;
52
+ /** Mark a new run as a commit tidy (`run --tidy`). */
53
+ tidy?: boolean;
52
54
  /** The task for a new run; omit when resuming. */
53
55
  task?: PreparedTask;
54
56
  /** Continue this earlier run (same run dir, sessions and counters) instead of starting a new one. */
@@ -267,6 +267,7 @@ export class RunSession {
267
267
  state = newRunState({
268
268
  run_id: runId,
269
269
  name: opts.name,
270
+ ...(opts.tidy ? { tidy: true } : {}),
270
271
  project: project.name,
271
272
  task_source: task.source,
272
273
  task_path: task.sourcePath,
@@ -187,6 +187,8 @@ export interface RunState {
187
187
  step_base?: Step[];
188
188
  /** Readable name; lets `resume`, `clear` and `status` find the run without its id. Absent on runs from older versions. */
189
189
  name?: string;
190
+ /** Set by `run --tidy`: this run only tidies existing commits. The web console marks such runs. */
191
+ tidy?: boolean;
190
192
  /** One entry per time a finished run was reopened with a follow-up. */
191
193
  reopened?: {
192
194
  at: string;
package/dist/run-store.js CHANGED
@@ -82,6 +82,7 @@ const WireState = z
82
82
  cooldowns: z.unknown().transform(lenientCooldowns).optional(),
83
83
  step_base: z.array(z.object({ text: z.string(), done: z.boolean() })).optional(),
84
84
  name: z.string().optional(),
85
+ tidy: z.boolean().optional(),
85
86
  reopened: z.array(z.object({ at: z.string() })).optional(),
86
87
  round_floor: nonNeg.optional(),
87
88
  instances: z.object({ roles: z.record(z.string(), z.array(z.string()).min(1)) }).optional(),
package/dist/status.d.ts CHANGED
@@ -60,6 +60,8 @@ export interface RunReport {
60
60
  run_id: string;
61
61
  /** Absent on runs from older versions. */
62
62
  name?: string;
63
+ /** Started with `run --tidy`. */
64
+ tidy?: boolean;
63
65
  dir: string;
64
66
  /** running: its dispatcher is alive; interrupted: it died mid-run; ended: it stopped (see end_reason). */
65
67
  state: "running" | "interrupted" | "ended" | "waiting";
package/dist/status.js CHANGED
@@ -231,6 +231,7 @@ export function buildRunReport(run, project, opts = {}) {
231
231
  const report = {
232
232
  run_id: s.run_id,
233
233
  name: s.name,
234
+ ...(s.tidy ? { tidy: true } : {}),
234
235
  dir: run.dir,
235
236
  state: s.end_reason === "waiting" ? "waiting" : s.end_reason ? "ended" : live ? "running" : "interrupted",
236
237
  live,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agent-lyceum",
3
- "version": "0.49.2",
3
+ "version": "0.51.0",
4
4
  "description": "Config + dispatcher for teams of Claude Code / Codex agents with scoped context and file-based mailboxes",
5
5
  "keywords": [
6
6
  "ai",
@@ -116,6 +116,7 @@ export const COMMANDS = {
116
116
  { name: "task", label: "任務", kind: "textarea", required: true },
117
117
  { name: "name", label: "任務名稱(可留空)", kind: "text", help: "小寫英數與 -,最多 30 字。" },
118
118
  { name: "agent", label: "只交給這一位 agent(可留空)", kind: "text" },
119
+ { name: "tidy", label: "標記為 tidy(整理 commit 的任務)", kind: "checkbox" },
119
120
  { name: "assumeDefaults", label: "有建議值的問題直接採用,不暫停", kind: "checkbox" },
120
121
  ],
121
122
  mode: always("detached"),
@@ -129,6 +130,8 @@ export const COMMANDS = {
129
130
  const agent = text(b, "agent", { re: NAME_RE, what: "agent" });
130
131
  if (agent)
131
132
  out.push("--agent", agent);
133
+ if (flag(b, "tidy"))
134
+ out.push("--tidy");
132
135
  if (flag(b, "assumeDefaults"))
133
136
  out.push("--assume-defaults");
134
137
  out.push("--", need(text(b, "task", { required: true, what: "任務", max: TEXT_LIMIT })));