agent-lyceum 0.44.1 → 0.46.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/README.md CHANGED
@@ -56,6 +56,7 @@ Its own data (config, mailboxes, logs, memory, worktrees) lives in `~/agent-lyce
56
56
  | `call <agent>` | Ask one global agent on its own, outside any project. [details](docs/commands.md#call) |
57
57
  | `demo` | Try a 3-agent team on a throwaway sample repo. [details](docs/commands.md#demo) |
58
58
  | `tidy` | Have agents tidy their own memory (archives, never deletes). [details](docs/commands.md#tidy) |
59
+ | `proposals` | List, or have the lead decide, lesson proposals of agents that ran alone. [details](docs/commands.md#proposals) |
59
60
 
60
61
  `agent-lyceum <command> --help` prints the full options. Ctrl-C cancels cleanly; [exit codes](docs/commands.md#exit-codes) tell scripts how a run ended.
61
62
 
package/README.zh-TW.md CHANGED
@@ -56,6 +56,7 @@ npx agent-lyceum status
56
56
  | `call <agent>` | 在任何專案之外單獨呼叫一個全域 agent。 [詳細](docs/commands.zh-TW.md#call) |
57
57
  | `demo` | 在拋棄式範例 repo 上試跑 3 個 agent 的團隊。 [詳細](docs/commands.zh-TW.md#demo) |
58
58
  | `tidy` | 讓 agent 整理自己的記憶(只封存,不刪除)。 [詳細](docs/commands.zh-TW.md#tidy) |
59
+ | `proposals` | 列出單獨執行的 agent 提出的教訓提案,或讓 lead 決議。 [詳細](docs/commands.zh-TW.md#proposals) |
59
60
 
60
61
  `agent-lyceum <指令> --help` 會印出完整選項。Ctrl-C 可乾淨取消;腳本可依[結束碼](docs/commands.zh-TW.md#退出碼)判斷 run 的結果。
61
62
 
package/dist/call.d.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import { type Invoker } from "./adapters/index.js";
2
2
  import { type ResolvedAgent, type ResolvedProject } from "./config.js";
3
3
  import { type Tried } from "./fallback.js";
4
+ import { type ProjectPaths } from "./paths.js";
4
5
  export declare const CALL_PROJECT = "(call)";
5
6
  export declare const callsDir: (home: string) => string;
6
7
  export interface CallOptions {
@@ -9,6 +10,8 @@ export interface CallOptions {
9
10
  task: string;
10
11
  /** Working directory; must exist. */
11
12
  dir: string;
13
+ /** `call -p`: a registered project this call may write proposals to (spec 30). Without it a call reads and writes no project. */
14
+ project?: string;
12
15
  invoker?: Invoker;
13
16
  signal?: AbortSignal;
14
17
  say?: (line: string) => void;
@@ -30,6 +33,11 @@ export interface CallResult {
30
33
  }
31
34
  /** A global agent (from team.yaml) as a `call` uses it: global persona and memory, nobody to mail, nothing to ask, nothing to edit. */
32
35
  export declare function resolveCallAgent(home: string, name: string): ResolvedAgent;
36
+ /** The registered project a `call -p` proposes to: where its trees are and its repository. Reads only `project.yaml`; no members, no permissions, never a guess from the current directory. */
37
+ export declare function resolveProjectRef(home: string, name: string): {
38
+ paths: ProjectPaths;
39
+ dir: string;
40
+ };
33
41
  /** The made-up project a call runs in: the working directory is its repo, and every other path is inside the call's own folder. */
34
42
  export declare function callProject(home: string, agent: ResolvedAgent, dir: string, callDir: string): ResolvedProject;
35
43
  /** One call per agent at a time (two would write the same global memory). A lock whose process is gone, or that cannot be read, is taken over. */
package/dist/call.js CHANGED
@@ -3,13 +3,14 @@ import path from "node:path";
3
3
  import { invokeWithSandboxChecks } from "./sandbox-invocation.js";
4
4
  import { realInvoker } from "./adapters/index.js";
5
5
  import { must } from "./assert.js";
6
- import { ConfigError, loadGlobal, resolveProjectFrom } from "./config.js";
6
+ import { ConfigError, loadGlobal, loadProjectRaw, resolveProjectFrom } from "./config.js";
7
7
  import { agentForCandidate, candidatesFor, Cooldowns, runWithFallback } from "./fallback.js";
8
8
  import { atomicWrite } from "./fs-util.js";
9
- import { ProtectedGuard } from "./guard.js";
10
- import { assertName, homePaths, isInside } from "./paths.js";
9
+ import { otherCallPrefixes, ProtectedGuard, runsStartedAfter } from "./guard.js";
10
+ import { assertName, configPath, homePaths, isInside, projectPaths } from "./paths.js";
11
11
  import { memoryDirs } from "./policy.js";
12
- import { lockHolderAlive } from "./project-lock.js";
12
+ import { acquireProjectLock, listRunLocks, lockHolderAlive } from "./project-lock.js";
13
+ import { shortIdOf } from "./proposals.js";
13
14
  import { buildCallUserPrompt, buildSoloSystemPrompt } from "./prompt.js";
14
15
  import { newRunId } from "./run-store.js";
15
16
  import { DISPATCHER_DEFAULTS } from "./schema.js";
@@ -37,6 +38,13 @@ export function resolveCallAgent(home, name) {
37
38
  canEditAgentMd: false,
38
39
  };
39
40
  }
41
+ /** The registered project a `call -p` proposes to: where its trees are and its repository. Reads only `project.yaml`; no members, no permissions, never a guess from the current directory. */
42
+ export function resolveProjectRef(home, name) {
43
+ assertName("project", name);
44
+ const paths = projectPaths(home, name);
45
+ const raw = loadProjectRaw(home, name); // throws a ConfigError when there is no such project
46
+ return { paths, dir: configPath(raw.dir, paths.root) };
47
+ }
40
48
  /** The made-up project a call runs in: the working directory is its repo, and every other path is inside the call's own folder. */
41
49
  export function callProject(home, agent, dir, callDir) {
42
50
  const paths = {
@@ -128,16 +136,29 @@ export async function callAgent(o) {
128
136
  }
129
137
  if (!o.task.trim())
130
138
  throw new Error("No task given: pass it as text or with --task-file.");
139
+ const ref = o.project ? resolveProjectRef(o.home, o.project) : undefined;
131
140
  const callId = newRunId();
132
141
  const callDir = path.join(callsDir(o.home), callId);
133
142
  const lease = lockAgent(o.home, agent.name, callId);
143
+ let projectLease;
134
144
  try {
145
+ // A `call -p` is active in the project like a run without being one: a memory tidy or `proposals review` must wait for it, other runs need not (spec 30, D-04).
146
+ if (ref)
147
+ projectLease = acquireProjectLock(ref.paths.root, callId, { call: true });
135
148
  fs.mkdirSync(path.join(callDir, "log"), { recursive: true });
136
149
  fs.writeFileSync(path.join(callDir, "task.md"), o.task);
137
150
  for (const d of memoryDirs(agent))
138
151
  fs.mkdirSync(d, { recursive: true });
139
- const project = callProject(o.home, agent, dir, callDir);
140
- const guard = new ProtectedGuard(project);
152
+ const base = callProject(o.home, agent, dir, callDir);
153
+ const project = ref
154
+ ? { ...base, proposalsRef: { projectRoot: ref.paths.root, recordsRoot: path.join(ref.paths.shared, "common", "records"), proposalsRoot: path.join(ref.paths.root, "proposals"), dir: ref.dir, shortId: shortIdOf(callId) } }
155
+ : base;
156
+ if (project.proposalsRef)
157
+ fs.mkdirSync(project.proposalsRef.proposalsRoot, { recursive: true });
158
+ // Another run of the project that is live, or began and ended while this call worked, may have written the shared files legitimately; this call may not.
159
+ const guard = ref
160
+ ? new ProtectedGuard(project, () => listRunLocks(ref.paths.root).filter((l) => !l.call && lockHolderAlive(l)).map((l) => l.run_id), { recordsRoot: project.proposalsRef.recordsRoot, proposalsRoot: project.proposalsRef.proposalsRoot, shortId: project.proposalsRef.shortId, violationsDir: path.join(callDir, "guard-violations"), startedAfter: (stamp) => runsStartedAfter(ref.paths.runs, stamp), otherPrefixes: otherCallPrefixes(o.home, ref.paths.root, callId) })
161
+ : new ProtectedGuard(project);
141
162
  say(`Calling ${agent.name} in ${dir} (call ${callId})`);
142
163
  const invoke = o.invoker ?? realInvoker;
143
164
  const all = candidatesFor(agent);
@@ -163,7 +184,7 @@ export async function callAgent(o) {
163
184
  agent: agentForCandidate(agent, c),
164
185
  workDir: callDir,
165
186
  systemPrompt: buildSoloSystemPrompt(project, agent),
166
- userPrompt: buildCallUserPrompt(agent, o.task),
187
+ userPrompt: buildCallUserPrompt(agent, o.task, project),
167
188
  timeoutSec: project.dispatcher.wake_timeout_sec,
168
189
  signal: o.signal,
169
190
  logDir: logDirFor(c),
@@ -181,6 +202,7 @@ export async function callAgent(o) {
181
202
  return { callId, callDir, ok: result.ok, cancelled, text: result.ok ? result.text : "", error, ...(tried ? { tried } : {}), reverted };
182
203
  }
183
204
  finally {
205
+ projectLease?.release();
184
206
  lease.release();
185
207
  }
186
208
  }
package/dist/cli.js CHANGED
@@ -8,6 +8,8 @@ import { Command } from "commander";
8
8
  import { ConfigError, findProjectForCwd, flattenResolved, listProjects, loadGlobal, resolveProject, resolveProjectWithSources } from "./config.js";
9
9
  import { openInEditor, prepareAnswers } from "./ask-answer.js";
10
10
  import { restoreMemory, tidyMemory, tidyStamp } from "./memory-tidy.js";
11
+ import { describeProposals, pendingProposals } from "./proposals.js";
12
+ import { reviewProposals } from "./proposals-review.js";
11
13
  import { RESULT_FILE, runTeam } from "./dispatcher.js";
12
14
  import { executeRunCleanup, planRunCleanup } from "./run-cleanup.js";
13
15
  import { diagnoseProject, formatDoctor, preflightRuntimes, runtimesUsed } from "./doctor.js";
@@ -623,6 +625,7 @@ program
623
625
  .description("Call one agent of the global library on its own, outside any project.\n\n - it works in --dir (default: the current directory)\n - its final answer is printed\n - it cannot mail anyone or ask you")
624
626
  .option("--task-file <path>", "read the task from a file")
625
627
  .option("--dir <path>", "the directory the agent works in (default: the current directory)")
628
+ .option("-p, --project <name>", "a registered project the agent may write lesson/decision proposals to (it also sees the titles of the project's records; the lead decides the proposals)")
626
629
  .action(async (agentName, task, opts) => {
627
630
  try {
628
631
  if (task !== undefined && opts.taskFile)
@@ -637,7 +640,7 @@ program
637
640
  const cancel = cancelOnSignals();
638
641
  let r;
639
642
  try {
640
- r = await callAgent({ home: h, agent: agentName, task: text, dir, signal: cancel.signal });
643
+ r = await callAgent({ home: h, agent: agentName, task: text, dir, ...(opts.project ? { project: opts.project } : {}), signal: cancel.signal });
641
644
  }
642
645
  finally {
643
646
  cancel.dispose();
@@ -694,7 +697,11 @@ program
694
697
  console.log(` restored records/${f}`);
695
698
  for (const k of r.records?.skipped ?? [])
696
699
  console.log(` skipped records/${k.rel}: ${k.reason}`);
697
- if (!r.restored.length && !r.skipped.length && !r.records?.restored.length && !r.records?.skipped.length)
700
+ for (const f of r.proposals?.restored ?? [])
701
+ console.log(` restored proposals/${f}`);
702
+ for (const k of r.proposals?.skipped ?? [])
703
+ console.log(` skipped proposals/${k.rel}: ${k.reason}`);
704
+ if (!r.restored.length && !r.skipped.length && !r.records?.restored.length && !r.records?.skipped.length && !r.proposals?.restored.length && !r.proposals?.skipped.length)
698
705
  console.log(`Archive ${opts.undo} holds no files to restore.`);
699
706
  }
700
707
  finally {
@@ -729,11 +736,11 @@ program
729
736
  console.log(`No agent has ${layer} memory configured. ${layer === "project" ? "The template gives agents global memory only: set `memory.project` for an agent in project.yaml (or tidy global memory with --layer global)." : "Set `memory.global` for an agent."}`);
730
737
  for (const r of results) {
731
738
  if (r.status === "tidied")
732
- console.log(` ${r.agent} (${r.layer}): tidied. Archive: ${path.join(r.dir, ".archive", r.archive ?? "")}${r.recordsDir && r.recordsDir !== r.dir ? `, records: ${path.join(r.recordsDir, ".archive", r.archive ?? "")}` : ""} — undo with: agent-lyceum tidy --undo ${r.archive} -p ${pr.name} --agent ${r.agent}${r.layer === "global" ? " --layer global" : ""}`);
739
+ console.log(` ${r.agent} (${r.layer}): tidied. Archive: ${path.join(r.dir, ".archive", r.archive ?? "")}${r.recordsDir && r.recordsDir !== r.dir ? `, records: ${path.join(r.recordsDir, ".archive", r.archive ?? "")}` : ""}${r.proposalsDir ? `, proposals: ${path.join(r.proposalsDir, ".archive", r.archive ?? "")}` : ""} — undo with: agent-lyceum tidy --undo ${r.archive} -p ${pr.name} --agent ${r.agent}${r.layer === "global" ? " --layer global" : ""}`);
733
740
  else if (r.status === "skipped")
734
741
  console.log(` ${r.agent} (${r.layer}): skipped — ${r.problems.join("; ")}`);
735
742
  else if (r.status === "failed") {
736
- console.error(` ${r.agent} (${r.layer}): FAILED, ${r.recordsDir === r.dir ? "project records" : r.recordsDir ? "memory and project records" : "memory"} restored to how it was`);
743
+ console.error(` ${r.agent} (${r.layer}): FAILED, ${r.recordsDir === r.dir ? "project records" : r.recordsDir ? "memory and project records" : r.proposalsDir ? "memory and proposals" : "memory"} restored to how it was`);
737
744
  for (const p of r.problems)
738
745
  console.error(` - ${p}`);
739
746
  }
@@ -744,6 +751,64 @@ program
744
751
  fail(e instanceof ConfigError ? e.message : e.message);
745
752
  }
746
753
  });
754
+ const proposals = program
755
+ .command("proposals")
756
+ .summary("List, or have the lead decide, lesson and decision proposals of agents that ran alone")
757
+ .description("Agents that run alone (`run --agent`, `call -p`) write lesson and decision proposals; only the lead decides them.\n\n" +
758
+ "Subcommands:\n - list: show the proposals (reads only)\n - review: wake the lead once to accept or reject the pending ones and write the records\n\n" +
759
+ "Neither writes a proposal or a record itself, and a review that leaves a decision incomplete is rolled back.");
760
+ proposals
761
+ .command("list")
762
+ .description("Show the proposals of a project: how many wait, their evidence, and decisions that are incomplete. Reads only.")
763
+ .option("-p, --project <name>")
764
+ .action((opts) => {
765
+ try {
766
+ for (const line of describeProposals(loadProject(opts.project)))
767
+ console.log(line);
768
+ }
769
+ catch (e) {
770
+ fail(e instanceof ConfigError ? e.message : e.message);
771
+ }
772
+ });
773
+ proposals
774
+ .command("review")
775
+ .description("Wake the project's lead once to decide the pending proposals.\n\n - needs the project to itself: refused while a run or a `call -p` is active\n - the lead may write only the records and the proposals\n - an incomplete decision, a deleted record or proposal, or a records kind over budget undoes the whole review")
776
+ .option("-p, --project <name>")
777
+ .action(async (opts) => {
778
+ try {
779
+ const pr = loadProject(opts.project);
780
+ if (pendingProposals(pr).length === 0) {
781
+ console.log("No pending proposals.");
782
+ return;
783
+ }
784
+ const res = validateProject(pr);
785
+ for (const i of res.issues)
786
+ console.error(`${i.level === "error" ? "ERROR" : "warn "} ${i.message}`);
787
+ if (!res.ok)
788
+ fail("Configuration is invalid; fix the errors above (see `agent-lyceum doctor`).");
789
+ await preflight(pr);
790
+ const lease = takeLock(pr, `review-${tidyStamp()}`, { exclusive: true });
791
+ const cancel = cancelOnSignals();
792
+ let r;
793
+ try {
794
+ r = await reviewProposals({ project: pr, signal: cancel.signal });
795
+ }
796
+ finally {
797
+ cancel.dispose();
798
+ lease.release();
799
+ }
800
+ if (r.status === "failed") {
801
+ console.error("Review FAILED; the records and proposals are back as they were:");
802
+ for (const p of r.problems)
803
+ console.error(` - ${p}`);
804
+ process.exit(1);
805
+ }
806
+ console.log(`Reviewed: ${r.accepted} accepted, ${r.rejected} rejected. Report: ${r.report}`);
807
+ }
808
+ catch (e) {
809
+ fail(e instanceof ConfigError ? e.message : e.message);
810
+ }
811
+ });
747
812
  function useColor() {
748
813
  if (process.env.NO_COLOR)
749
814
  return false;
@@ -1015,7 +1080,7 @@ program
1015
1080
  const HELP_LAYERS = {
1016
1081
  "Project:": ["init", "project"],
1017
1082
  "Diagnose:": ["doctor", "status"],
1018
- "Run:": ["run", "resume", "clear", "call", "tidy"],
1083
+ "Run:": ["run", "resume", "clear", "call", "tidy", "proposals"],
1019
1084
  "Try it:": ["demo"],
1020
1085
  };
1021
1086
  for (const [heading, names] of Object.entries(HELP_LAYERS))
package/dist/config.d.ts CHANGED
@@ -92,6 +92,17 @@ export interface ResolvedProject {
92
92
  workspaces?: Record<string, AgentWorkspace>;
93
93
  /** Set for a single agent working alone: "run" = inside a run of this project (`run --agent`), "call" = outside any project (`call`). */
94
94
  solo?: "run" | "call";
95
+ /**
96
+ * Set only for `call -p <project>` (spec 30): the real project a `call` may propose to. A `call` project is a temporary
97
+ * one whose `paths.root` is the call's own directory, so the proposals and records of the real project are named here.
98
+ */
99
+ proposalsRef?: {
100
+ projectRoot: string;
101
+ recordsRoot: string;
102
+ proposalsRoot: string; /** the project's repository (`project.yaml` `dir`) */
103
+ dir: string; /** the file-name prefix of this call's proposals */
104
+ shortId: string;
105
+ };
95
106
  }
96
107
  export declare function loadGlobal(home: string): {
97
108
  model_tiers?: {
package/dist/doctor.js CHANGED
@@ -6,6 +6,7 @@ import { findOnPath } from "./fs-util.js";
6
6
  import { tidyAdvice } from "./memory-tidy.js";
7
7
  import { listRecords, RECORD_KINDS } from "./records.js";
8
8
  import { listRunLocks, listUnreadableRunLocks, lockHolderAlive } from "./project-lock.js";
9
+ import { checkDecisions, listProposals, oldestPending, pendingProposals } from "./proposals.js";
9
10
  import { runInvocation } from "./process-runner.js";
10
11
  import { validateProject } from "./validate.js";
11
12
  import { diagnoseInstances } from "./doctor-instances.js";
@@ -203,7 +204,7 @@ export async function diagnoseProject(project, opts = {}) {
203
204
  level: "warn",
204
205
  subject: "lock",
205
206
  message: alive
206
- ? `A run is active: ${lock.run_id} (pid ${lock.pid}).`
207
+ ? `${lock.call ? "A call is active" : "A run is active"}: ${lock.run_id} (pid ${lock.pid}).`
207
208
  : `A stale run lock is left by ${lock.run_id} (pid ${lock.pid} is gone); \`agent-lyceum clear --lock ${lock.run_id} --force\` clears it.`,
208
209
  });
209
210
  }
@@ -223,6 +224,16 @@ export async function diagnoseProject(project, opts = {}) {
223
224
  checks.push({ level: "warn", subject: "records", message: `${r.file}: supersedes "${s}", but no ${kind} entry has that id.` });
224
225
  }
225
226
  }
227
+ // Spec 30: proposals waiting for the lead, and decisions or files that are not in the right format.
228
+ const waiting = pendingProposals(project);
229
+ if (waiting.length)
230
+ checks.push({ level: "info", subject: "proposals", message: `${waiting.length} proposal(s) wait for the lead (oldest ${oldestPending(waiting) ?? "unknown"}): \`agent-lyceum proposals review -p ${project.name}\`.` });
231
+ for (const pr of listProposals(project)) {
232
+ if (pr.problems.length && (pr.status === undefined || pr.status === "proposed"))
233
+ checks.push({ level: "warn", subject: "proposals", message: `${pr.file}: ${pr.problems.join("; ")}.` });
234
+ }
235
+ for (const d of checkDecisions(listProposals(project), project))
236
+ checks.push({ level: "warn", subject: "proposals", message: `${d.file}: ${d.problem}.` });
226
237
  const runtimes = await probeProjectRuntimes(project, opts, true);
227
238
  checks.push(...judgeRuntimes(project, runtimes));
228
239
  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/guard.d.ts CHANGED
@@ -16,6 +16,33 @@ export interface Unattributed {
16
16
  otherRuns: string[];
17
17
  }
18
18
  export declare const MAX_KEEP_BYTES: number;
19
+ /** Options for a guard that watches more than the project it was made for (spec 30): a `call -p` watches the real project, and a solo agent's proposals. */
20
+ export interface GuardOptions {
21
+ /** The records tree to watch, when it is not `recordsDir(project)` (a `call -p` project is a temporary one). */
22
+ recordsRoot?: string;
23
+ /** The proposals tree to watch, when it is not `proposalsDir(project)`. */
24
+ proposalsRoot?: string;
25
+ /** The only file-name prefix this agent may write in the proposals tree. Without it (and without `project.run`) proposals are not watched. */
26
+ shortId?: string;
27
+ /** Where rejected versions are kept for a project that is bound to no run (a `call -p`). */
28
+ violationsDir?: string;
29
+ /**
30
+ * Run ids that started after the given run-id timestamp (see `runStamp`), alive or not. A run that began and ended
31
+ * inside one watched window leaves no live lock for `check()` to see, yet its lead may have written to the shared files.
32
+ */
33
+ startedAfter?: (stamp: string) => string[];
34
+ /**
35
+ * File-name prefixes (short ids) of the other `call -p` and `run --agent` agents that wrote proposals while this one worked,
36
+ * live or already finished (see `otherCallPrefixes`). Their proposals sit in the same tree: changes under those prefixes are theirs, not this agent's.
37
+ */
38
+ otherPrefixes?: (stamp: string) => string[];
39
+ }
40
+ /** The short ids of the calls other than `selfId` that hold a live project lock, or that started after `stamp` (their ids sort by start time). */
41
+ export declare function otherCallPrefixes(home: string, projectRoot: string, selfId: string): (stamp: string) => string[];
42
+ /** The timestamp part of a run id, for `Date` (the same text `newRunId` starts with). */
43
+ export declare const runStamp: (d?: Date) => string;
44
+ /** Ids under `runsDir` whose timestamp is after `stamp`, except `selfId`. Run ids sort by start time. */
45
+ export declare function runsStartedAfter(runsDir: string, stamp: string, selfId?: string): string[];
19
46
  /**
20
47
  * Detects (and reverts) changes to protected files made by agents that may not edit them.
21
48
  * This is the runtime-independent safety net behind the OS/tool-level enforcement.
@@ -23,15 +50,23 @@ export declare const MAX_KEEP_BYTES: number;
23
50
  export declare class ProtectedGuard {
24
51
  private project;
25
52
  private otherLiveRuns;
53
+ private opts;
26
54
  private baseline;
27
55
  /** Regular files of the records tree (including `.archive/`); any agent in the running batch may change them. */
28
56
  private records;
29
57
  /** Changes kept (not reverted) because another live run may have made them; see `takeUnattributed`. */
30
58
  private unattributed;
59
+ /** Regular files of the proposals tree, for a solo agent (spec 30): only its own proposed files may change. */
60
+ private proposals;
31
61
  /** Other runs that were live at the last `rebase()` (or at `check()` time); computed once per batch. */
32
62
  private liveAtBase;
33
- /** `otherLiveRuns`: ids of the project's other runs that have a live lock holder right now. */
34
- constructor(project: ResolvedProject, otherLiveRuns?: () => string[]);
63
+ /** When the current batch's baseline was taken, as a run-id timestamp. */
64
+ private baseStamp;
65
+ /** `otherLiveRuns`: ids of the project's other runs that have a live lock holder right now (asked again on every `check`). */
66
+ constructor(project: ResolvedProject, otherLiveRuns?: () => string[], opts?: GuardOptions);
67
+ private recordsRoot;
68
+ private proposalsRoot;
69
+ private ownPrefix;
35
70
  /** The unattributed changes since the last call (they were kept and adopted as the baseline). */
36
71
  takeUnattributed(): Unattributed[];
37
72
  /** Files shared by every run of the project: only these can be changed by another run's lead. */
@@ -49,6 +84,14 @@ export declare class ProtectedGuard {
49
84
  /** Compare against the baseline after `running` agents finished; revert unauthorized changes. */
50
85
  check(running: ResolvedAgent[]): Violation[];
51
86
  private checkRecords;
87
+ /**
88
+ * A solo agent may create and change only its own `proposals/<kind>/<short id>-<slug>.md`, and only while the file is
89
+ * `proposed` (spec 30, D-03). Everything else under the proposals tree is put back: other prefixes, other folders,
90
+ * `.archive/`, deletions, a file that was already decided (even one with its own prefix, e.g. after a resume), and a
91
+ * write of `accepted` or `rejected`. A file that is merely badly formed is let through; D-09 flags it for the lead.
92
+ * Not watched for an ordinary run: its members are held back by the write policy only (30.8).
93
+ */
94
+ private checkProposals;
52
95
  /**
53
96
  * Make every directory from the records root down to `dir` a real directory. A symlink or file standing in for one is an
54
97
  * unauthorized change: unlink it (never follow it), recreate the directory and report it. False when `dir` is not safe to write into.
package/dist/guard.js CHANGED
@@ -3,8 +3,41 @@ import fs from "node:fs";
3
3
  import path from "node:path";
4
4
  import { readRegularFileNoFollow } from "./fs-util.js";
5
5
  import { escapesParent } from "./paths.js";
6
- import { mayEditProtected, recordsDir, repoInstructionFiles, sharedContextFiles, sharedIndex } from "./policy.js";
6
+ import { mayEditProtected, proposalsDir, recordsDir, repoInstructionFiles, sharedContextFiles, sharedIndex } from "./policy.js";
7
+ import { listRunLocks, lockHolderAlive } from "./project-lock.js";
8
+ import { prefixOf, proposalStatusOf, shortIdOf } from "./proposals.js";
7
9
  export const MAX_KEEP_BYTES = 1024 * 1024;
10
+ /** The short ids of the calls other than `selfId` that hold a live project lock, or that started after `stamp` (their ids sort by start time). */
11
+ export function otherCallPrefixes(home, projectRoot, selfId) {
12
+ return (stamp) => {
13
+ const ids = new Set();
14
+ for (const l of listRunLocks(projectRoot))
15
+ if (l.call && l.run_id !== selfId && lockHolderAlive(l))
16
+ ids.add(l.run_id);
17
+ try {
18
+ for (const n of fs.readdirSync(path.join(home, "calls")))
19
+ if (n !== selfId && /^\d{8}T\d+Z-/.test(n) && n.slice(0, n.indexOf("-")) > stamp)
20
+ ids.add(n);
21
+ }
22
+ catch {
23
+ /* no calls yet */
24
+ }
25
+ return [...ids].map(shortIdOf);
26
+ };
27
+ }
28
+ /** The timestamp part of a run id, for `Date` (the same text `newRunId` starts with). */
29
+ export const runStamp = (d = new Date()) => d.toISOString().replace(/[-:]/g, "").replace(/\.(\d+)Z$/, "$1Z");
30
+ /** Ids under `runsDir` whose timestamp is after `stamp`, except `selfId`. Run ids sort by start time. */
31
+ export function runsStartedAfter(runsDir, stamp, selfId) {
32
+ try {
33
+ return fs
34
+ .readdirSync(runsDir)
35
+ .filter((n) => n !== selfId && /^\d{8}T\d+Z-/.test(n) && n.slice(0, n.indexOf("-")) > stamp);
36
+ }
37
+ catch {
38
+ return [];
39
+ }
40
+ }
8
41
  function safeName(file) {
9
42
  return file.replace(/[\\/:]/g, "_").replace(/^_+/, "");
10
43
  }
@@ -15,19 +48,28 @@ function safeName(file) {
15
48
  export class ProtectedGuard {
16
49
  project;
17
50
  otherLiveRuns;
51
+ opts;
18
52
  baseline = new Map();
19
53
  /** Regular files of the records tree (including `.archive/`); any agent in the running batch may change them. */
20
54
  records = new Map();
21
55
  /** Changes kept (not reverted) because another live run may have made them; see `takeUnattributed`. */
22
56
  unattributed = [];
57
+ /** Regular files of the proposals tree, for a solo agent (spec 30): only its own proposed files may change. */
58
+ proposals = new Map();
23
59
  /** Other runs that were live at the last `rebase()` (or at `check()` time); computed once per batch. */
24
60
  liveAtBase = [];
25
- /** `otherLiveRuns`: ids of the project's other runs that have a live lock holder right now. */
26
- constructor(project, otherLiveRuns = () => []) {
61
+ /** When the current batch's baseline was taken, as a run-id timestamp. */
62
+ baseStamp = runStamp();
63
+ /** `otherLiveRuns`: ids of the project's other runs that have a live lock holder right now (asked again on every `check`). */
64
+ constructor(project, otherLiveRuns = () => [], opts = {}) {
27
65
  this.project = project;
28
66
  this.otherLiveRuns = otherLiveRuns;
67
+ this.opts = opts;
29
68
  this.rebase();
30
69
  }
70
+ recordsRoot = () => this.opts.recordsRoot ?? recordsDir(this.project);
71
+ proposalsRoot = () => this.opts.proposalsRoot ?? proposalsDir(this.project);
72
+ ownPrefix = () => this.opts.shortId ?? (this.project.run ? shortIdOf(this.project.run.id) : undefined);
31
73
  /** The unattributed changes since the last call (they were kept and adopted as the baseline). */
32
74
  takeUnattributed() {
33
75
  const out = this.unattributed;
@@ -45,10 +87,12 @@ export class ProtectedGuard {
45
87
  * judged: edits made in between (you, or another run of the project) are not the batch's doing.
46
88
  */
47
89
  rebase() {
90
+ this.baseStamp = runStamp();
48
91
  this.liveAtBase = this.otherLiveRuns();
49
92
  for (const f of ProtectedGuard.protectedFiles(this.project))
50
93
  this.baseline.set(f, read(f));
51
- this.records = readTree(recordsDir(this.project));
94
+ this.records = readTree(this.recordsRoot());
95
+ this.proposals = readTree(this.proposalsRoot());
52
96
  }
53
97
  static protectedFiles(project) {
54
98
  const files = new Set();
@@ -75,11 +119,11 @@ export class ProtectedGuard {
75
119
  }
76
120
  /** Keep what an agent wrote into a protected file before it is reverted. Nothing is written without a bound run. */
77
121
  keep(file, content) {
78
- const run = this.project.run;
79
- if (!content || !run)
122
+ const base = this.project.run?.dir ?? this.opts.violationsDir;
123
+ if (!content || !base)
80
124
  return {};
81
125
  const sha256 = crypto.createHash("sha256").update(content).digest("hex");
82
- const dir = path.join(run.dir, "violations");
126
+ const dir = this.project.run ? path.join(base, "violations") : base;
83
127
  fs.mkdirSync(dir, { recursive: true });
84
128
  const n = String(fs.readdirSync(dir).length + 1).padStart(3, "0");
85
129
  const saved = path.join(dir, `${n}-${safeName(file)}`);
@@ -90,7 +134,7 @@ export class ProtectedGuard {
90
134
  /** Compare against the baseline after `running` agents finished; revert unauthorized changes. */
91
135
  check(running) {
92
136
  const violations = [];
93
- const other = [...new Set([...this.liveAtBase, ...this.otherLiveRuns()])];
137
+ const other = [...new Set([...this.liveAtBase, ...this.otherLiveRuns(), ...(this.opts.startedAfter?.(this.baseStamp) ?? [])])];
94
138
  for (const [file, before] of this.baseline) {
95
139
  if (unsafeToRead(file)) {
96
140
  const kept = this.keep(file, null);
@@ -128,15 +172,17 @@ export class ProtectedGuard {
128
172
  }
129
173
  }
130
174
  this.checkRecords(running, violations, other);
175
+ this.checkProposals(running, violations, other);
131
176
  return violations;
132
177
  }
133
178
  checkRecords(running, violations, other) {
134
- const root = recordsDir(this.project);
179
+ const root = this.recordsRoot();
135
180
  // Never write through a symlinked parent of the records tree: skip its protection for this batch.
136
181
  if (isLink(path.dirname(root)) || isLink(path.dirname(path.dirname(root))))
137
182
  return;
138
183
  const now = readTree(root);
139
- const authorized = running.some((a) => a.name === this.project.lead);
184
+ // A solo agent is the lead of a team of one, but it may not write the records: only a real lead may (spec 30, D-03).
185
+ const authorized = !this.project.solo && running.some((a) => a.name === this.project.lead);
140
186
  const suspects = running.map((a) => a.name);
141
187
  const fixedDirs = new Set();
142
188
  for (const file of new Set([...this.records.keys(), ...now.keys()])) {
@@ -168,6 +214,66 @@ export class ProtectedGuard {
168
214
  if (authorized || other.length)
169
215
  this.records = now;
170
216
  }
217
+ /**
218
+ * A solo agent may create and change only its own `proposals/<kind>/<short id>-<slug>.md`, and only while the file is
219
+ * `proposed` (spec 30, D-03). Everything else under the proposals tree is put back: other prefixes, other folders,
220
+ * `.archive/`, deletions, a file that was already decided (even one with its own prefix, e.g. after a resume), and a
221
+ * write of `accepted` or `rejected`. A file that is merely badly formed is let through; D-09 flags it for the lead.
222
+ * Not watched for an ordinary run: its members are held back by the write policy only (30.8).
223
+ */
224
+ checkProposals(running, violations, other) {
225
+ if (!this.project.solo)
226
+ return;
227
+ const prefix = this.ownPrefix();
228
+ if (!prefix)
229
+ return;
230
+ const root = this.proposalsRoot();
231
+ if (isLink(path.dirname(root)) || isLink(path.dirname(path.dirname(root))))
232
+ return;
233
+ const now = readTree(root);
234
+ const suspects = running.map((a) => a.name);
235
+ const fixedDirs = new Set();
236
+ const theirs = new Set(this.opts.otherPrefixes?.(this.baseStamp) ?? []);
237
+ const own = new RegExp(`^(?:lessons|decisions)${escapeRe(path.sep)}${escapeRe(prefix)}-[a-z0-9-]+\\.md$`);
238
+ for (const file of new Set([...this.proposals.keys(), ...now.keys()])) {
239
+ const before = this.proposals.get(file) ?? null;
240
+ const cur = now.get(file) ?? null;
241
+ if (same(before, cur))
242
+ continue;
243
+ if (other.length) {
244
+ this.unattributed.push({ file, agents: suspects, otherRuns: other });
245
+ continue;
246
+ }
247
+ // A proposal of another live or just-finished call is that call's own, not a change by this agent.
248
+ if (theirs.has(prefixOf(path.basename(file))))
249
+ continue;
250
+ let ok = own.test(path.relative(root, file));
251
+ if (ok && before && proposalStatusOf(before) !== "proposed" && proposalStatusOf(before) !== undefined)
252
+ ok = false;
253
+ if (ok && cur) {
254
+ const st = proposalStatusOf(cur);
255
+ if (st === "accepted" || st === "rejected")
256
+ ok = false;
257
+ }
258
+ if (ok)
259
+ continue;
260
+ const kept = this.keep(file, cur);
261
+ if (before === null) {
262
+ if (!insideRoot(root, path.dirname(file)))
263
+ continue;
264
+ fs.rmSync(file, { force: true });
265
+ violations.push({ file, action: "removed", suspects, ...kept });
266
+ }
267
+ else {
268
+ if (!this.realDirs(root, path.dirname(file), fixedDirs, suspects, violations))
269
+ continue;
270
+ fs.rmSync(file, { recursive: true, force: true });
271
+ fs.writeFileSync(file, before);
272
+ violations.push({ file, action: "restored", suspects, ...kept });
273
+ }
274
+ }
275
+ this.proposals = readTree(root);
276
+ }
171
277
  /**
172
278
  * Make every directory from the records root down to `dir` a real directory. A symlink or file standing in for one is an
173
279
  * unauthorized change: unlink it (never follow it), recreate the directory and report it. False when `dir` is not safe to write into.
@@ -197,6 +303,7 @@ export class ProtectedGuard {
197
303
  return insideRoot(root, dir);
198
304
  }
199
305
  }
306
+ const escapeRe = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
200
307
  function isLink(p) {
201
308
  try {
202
309
  return fs.lstatSync(p).isSymbolicLink();
package/dist/mailbox.js CHANGED
@@ -11,7 +11,8 @@ import { effectiveTier, tierFlag } from "./tiers.js";
11
11
  import { isVerdict } from "./attribution.js";
12
12
  import { deterministicId, fault, RouteJournal, sourceIdOf } from "./message-store.js";
13
13
  import { inboxDir, outboxDir, sharedDir } from "./policy.js";
14
- import { activeRecordsBytes, RECORD_KINDS, RECORDS_BUDGET } from "./records.js";
14
+ import { checkDecisions, listProposals } from "./proposals.js";
15
+ import { RECORDS_BUDGET, recordsOverBudget } from "./records.js";
15
16
  import { must } from "./assert.js";
16
17
  export { atomicWrite };
17
18
  export const MESSAGE_TYPES = ["task", "reply", "failure", "done", "ask"];
@@ -318,9 +319,18 @@ export function routeOutboxes(project, routing) {
318
319
  reject(`only the lead ("${project.lead}") may send a "done" message.`);
319
320
  continue;
320
321
  }
321
- const over = RECORD_KINDS.map((k) => ({ k, n: activeRecordsBytes(project, k) })).filter((x) => x.n > RECORDS_BUDGET);
322
+ const over = recordsOverBudget(project);
322
323
  if (over.length) {
323
- reject(`${over.map((x) => `records/${x.k} hold ${x.n} bytes of active entries`).join(" and ")}; the budget is ${RECORDS_BUDGET} bytes (6 KB) per kind. Merge entries, or mark obsolete ones "status: superseded" (or name them in a newer entry's "supersedes"), then send "done" again.`);
324
+ reject(`${over.map((x) => `records/${x.kind} hold ${x.bytes} bytes of active entries`).join(" and ")}; the budget is ${RECORDS_BUDGET} bytes (${RECORDS_BUDGET / 1024} KB) per kind. Merge entries, or mark obsolete ones "status: superseded" (or name them in a newer entry's "supersedes"), then send "done" again.`);
325
+ continue;
326
+ }
327
+ // Spec 30, D-09 layer 1: a decision on a proposal must be complete. Not for a solo run: its lead is the agent that wrote them and cannot fix them.
328
+ const undecided = project.solo ? [] : checkDecisions(listProposals(project), project);
329
+ if (undecided.length) {
330
+ reject(`proposals have incomplete decisions: ${undecided
331
+ .slice(0, 5)
332
+ .map((x) => `${x.file} (${x.problem})`)
333
+ .join("; ")}${undecided.length > 5 ? `; and ${undecided.length - 5} more` : ""}. Fix them (an accepted one needs accepted_as and decided, a rejected one reject_reason and decided), then send "done" again.`);
324
334
  continue;
325
335
  }
326
336
  res.done = { from: sender.name, subject, body: parsed.body, file, meta: d };