agent-lyceum 0.45.0 → 0.47.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/prompt.js CHANGED
@@ -3,8 +3,9 @@ import path from "node:path";
3
3
  import { REQUIRED_SECTIONS } from "./format.js";
4
4
  import { senderLabel, slotName } from "./instances.js";
5
5
  import { modelForTier } from "./tiers.js";
6
- import { buildRecordsView, RECORDS_BUDGET } from "./records.js";
7
- import { commonFile, memoryDirs, outboxDir, ownAgentDirAllowed, projectAgentDir, recordsKindDir, repoDirFor, sharedDir, sharedIndex } from "./policy.js";
6
+ import { checkEvidence, oldestPending, pendingProposals, PENDING_SHOWN, shortIdOf } from "./proposals.js";
7
+ import { activeRecordsBytes, buildRecordsView, effectiveActive, listRecords, RECORD_KINDS, RECORDS_BUDGET } from "./records.js";
8
+ import { commonFile, mayPropose, memoryDirs, outboxDir, ownAgentDirAllowed, projectAgentDir, proposalsDir, recordsKindDir, repoDirFor, sharedDir, sharedIndex } from "./policy.js";
8
9
  function memoryLabel(agent, dir) {
9
10
  if (dir === agent.memory.task)
10
11
  return "task (this task only, isolated)";
@@ -109,11 +110,15 @@ function writeScopeRules(project, agent) {
109
110
  const ownDir = projectAgentDir(project, agent.name);
110
111
  const mayWriteOwn = project.solo !== "call" && ownAgentDirAllowed(project, agent);
111
112
  const ownPersona = mayWriteOwn && (agent.agentMd === path.join(ownDir, "AGENT.md") || agent.agentMd.startsWith(ownDir + path.sep));
112
- const records = `decisions in \`${recordsKindDir(project, "decisions")}/\` and lessons in \`${recordsKindDir(project, "lessons")}/\`. The file name without \`.md\` is the entry id (lowercase letters, digits, \`-\`). Each file starts with YAML frontmatter between \`---\` lines: \`status: active|superseded\`, \`date: YYYY-MM-DD\`, \`title: <one line>\`, optionally \`run: <run id>\` and \`supersedes: [<ids of entries of the same kind>]\`; the body is the decision or lesson and its reason. Prompts show only effective-active entries (\`status: active\` and not named in another entry's \`supersedes\`), newest first, up to ${CONTEXT_LIMIT / 1024} KB per kind, and list what does not fit as one line each. When an entry becomes outdated, mark it \`status: superseded\` or name it in a new entry's \`supersedes\`.`;
113
+ // A `call -p` has a temporary project: the records and COMMON.md it reads are the real project's (spec 30, D-04).
114
+ const recRoot = project.proposalsRef?.recordsRoot;
115
+ const kindDir = (k) => (recRoot ? path.join(recRoot, k) : recordsKindDir(project, k));
116
+ const commonPath = recRoot ? path.join(path.dirname(recRoot), "COMMON.md") : commonFile(project);
117
+ const records = `decisions in \`${kindDir("decisions")}/\` and lessons in \`${kindDir("lessons")}/\`. The file name without \`.md\` is the entry id (lowercase letters, digits, \`-\`). Each file starts with YAML frontmatter between \`---\` lines: \`status: active|superseded\`, \`date: YYYY-MM-DD\`, \`title: <one line>\`, optionally \`run: <run id>\` and \`supersedes: [<ids of entries of the same kind>]\`; the body is the decision or lesson and its reason. Prompts show only effective-active entries (\`status: active\` and not named in another entry's \`supersedes\`), newest first, up to ${CONTEXT_LIMIT / 1024} KB per kind, and list what does not fit as one line each. When an entry becomes outdated, mark it \`status: superseded\` or name it in a new entry's \`supersedes\`.`;
113
118
  return [
114
119
  isLead
115
- ? `- You keep the shared team context \`${commonFile(project)}\` (you maintain it; keep it short) and two kinds of durable records for every future run of this project, one Markdown file per entry: ${records} Add or update entries before you send \`done\`.`
116
- : `- The shared team context is in \`${commonFile(project)}\` (read-only). Project records are ${records} Both are read-only.`,
120
+ ? `- You keep the shared team context \`${commonPath}\` (you maintain it; keep it short) and two kinds of durable records for every future run of this project, one Markdown file per entry: ${records} Add or update entries before you send \`done\`.`
121
+ : `- The shared team context is in \`${commonPath}\` (read-only). Project records are ${records} Both are read-only.`,
117
122
  ...(mayWriteOwn ? [`- You may write your project agent directory \`${ownDir}/\`. Creating \`AGENT.md\` there makes it this project's persona on the next run; the global persona file stays read-only.`] : []),
118
123
  ...(ownPersona ? [`- You may edit your project persona \`${agent.agentMd}\`.`] : []),
119
124
  ...(agent.canEditAgentMd
@@ -145,14 +150,100 @@ export function buildSoloSystemPrompt(project, agent) {
145
150
  const extra = extraWritableDirs(project, agent);
146
151
  lines.push(`Keep a \`MEMORY.md\` index in each memory directory (one line per entry, pointing at a file). Its contents are shown in your prompt on every wake-up.${extraWriteClause(extra)}`, "Use memory only for durable lessons that stay true across tasks; never record task-specific details there.");
147
152
  }
153
+ lines.push(...proposalRules(project, isCall));
148
154
  lines.push("", "## Rules", ...writeScopeRules(project, agent), PR_ATTRIBUTION_RULE, NO_DAEMONS_RULE);
149
155
  return lines.join("\n");
150
156
  }
157
+ /**
158
+ * What an agent working alone is told about proposals (spec 30, D-17, 30.12). The file-name prefix is given as a literal:
159
+ * the guard removes a proposal whose name does not start with it, so the agent must not derive it from a run id itself.
160
+ * Nothing is said when the agent may not propose (a plain `call`).
161
+ */
162
+ function proposalRules(project, isCall) {
163
+ if (!mayPropose(project))
164
+ return [];
165
+ const prefix = project.proposalsRef?.shortId ?? (project.run ? shortIdOf(project.run.id) : undefined);
166
+ if (!prefix)
167
+ return [];
168
+ const dir = proposalsDir(project);
169
+ return [
170
+ "",
171
+ "## Proposals",
172
+ `You cannot write the project's decisions or lessons. When you learn something that stays true across tasks and would change how the next run should work, write it as a proposal: one Markdown file \`${prefix}-<slug>.md\` in \`${dir}/lessons/\` or \`${dir}/decisions/\`. The prefix \`${prefix}\` is fixed for this run (never derive another one); the slug uses only lowercase letters, digits and \`-\`.`,
173
+ "Start the file with `status: proposed`, `date`, `title`, `proposed_by`, `run` and at least one `evidence` entry. Each entry is a mapping with exactly one key, never a bare string: `- path: src/a.ts:42 @ <commit sha>`, `- commit: <sha>`, `- mail: <id or subject>` or `- output: <command and its key output>`. Put `repo` when the evidence is in a different repository than the project. Quote any YAML value that contains `: `. Write the facts you observed first, then your guess about the cause, and mark it as a guess.",
174
+ "Never edit an existing proposal of another run, and never set `status` to anything but `proposed`. The lead decides.",
175
+ `Where things go: a proposal is for lessons and decisions that outlive this task; ${isCall ? "" : "the handoff notes are for the state, next steps and pitfalls of this task only; "}your memory is for habits that matter to you alone.`,
176
+ ];
177
+ }
178
+ /** The lead's note about proposals waiting for a decision (spec 30, D-06, D-11, D-15); empty when there are none. */
179
+ export function pendingProposalLines(project) {
180
+ const pending = pendingProposals(project).sort((a, b) => a.date.localeCompare(b.date) || a.id.localeCompare(b.id));
181
+ if (pending.length === 0)
182
+ return [];
183
+ const strength = (p) => {
184
+ if (p.problems.length)
185
+ return `format problem: ${p.problems[0]}`;
186
+ const c = checkEvidence(p, project.dir);
187
+ return c.strength === "verified" ? "evidence verified" : c.strength === "weak" ? "weak evidence (no commit)" : "no machine-verifiable evidence";
188
+ };
189
+ const shown = pending.slice(0, PENDING_SHOWN);
190
+ const used = RECORD_KINDS.map((k) => `${k} ${activeRecordsBytes(project, k)} of ${RECORDS_BUDGET} bytes`).join(", ");
191
+ return [
192
+ "",
193
+ "## Proposals waiting for you",
194
+ `${pending.length} proposals await a decision (oldest: ${oldestPending(pending) ?? "unknown"}). Showing ${shown.length}:`,
195
+ ...shown.map((p) => `- \`${p.file}\` — ${p.title} — ${strength(p)}`),
196
+ `For each one, check the evidence yourself, then either create the record (a new file, not a copy) and set the proposal to \`status: accepted\` with \`accepted_as: <kind>/<id>\`, or set \`status: rejected\` with \`reject_reason\`. In both cases also write \`decided: <today's date>\`. Put a short summary of the evidence in the record's body. Active entries use ${used}; merge or supersede before you exceed it.`,
197
+ ];
198
+ }
199
+ /** The prompts of a `proposals review` wake-up (spec 30, D-14): the lead decides the pending proposals and writes the records, nothing else. */
200
+ export function buildReviewPrompts(project, agent, reportFile) {
201
+ const dirs = `\`${recordsKindDir(project, "decisions")}/\` and \`${recordsKindDir(project, "lessons")}/\``;
202
+ const systemPrompt = [
203
+ readPersona(agent),
204
+ "",
205
+ "---",
206
+ "",
207
+ "# Proposals review (injected by agent-lyceum)",
208
+ "",
209
+ `You are **${agent.name}**, the lead of this project. Agents that ran alone wrote proposals of lessons and decisions; you decide them now. This is a short maintenance wake-up: there is no task, no mail and nobody to ask.`,
210
+ "",
211
+ "## What you may write",
212
+ `- The project records, in ${dirs}, and the proposals in \`${proposalsDir(project)}\`. Nothing else: not the repository, not COMMON.md, not any memory or mail.`,
213
+ "- Never delete a proposal or a record. An outdated record is marked `status: superseded` or named in a new entry's `supersedes`.",
214
+ "- A record is one Markdown file per entry; the file name without `.md` is its id (lowercase letters, digits, `-`). It starts with YAML frontmatter: `status: active`, `date: YYYY-MM-DD`, `title: <one line>`, optionally `run` and `supersedes: [<ids>]`; the body is the decision or lesson and its reason, with a short summary of the evidence.",
215
+ "",
216
+ "## How to decide",
217
+ "- Check the evidence yourself in the repository before you accept: read the file at the line, look at the commit. A proposal whose evidence you cannot confirm, or that only repeats an existing record, is rejected with a reason.",
218
+ "- Facts and guesses are written apart in a proposal: accept the facts, and state the guess as a guess in the record, or leave it out.",
219
+ "- Accepting means creating a new record (a new file, not a copy of the proposal) and setting the proposal to `status: accepted` with `accepted_as: <kind>/<id>` and `decided: <today's date>`. Rejecting means `status: rejected` with `reject_reason: <one line>` and `decided`.",
220
+ `- Active entries of one kind may not exceed ${RECORDS_BUDGET} bytes together; merge or supersede first.`,
221
+ ].join("\n");
222
+ const userPrompt = [
223
+ ...pendingProposalLines(project),
224
+ "",
225
+ `When you are done, write a short report to \`${reportFile}\`: one line per proposal you decided (accepted or rejected, and why), and anything you left for a person.`,
226
+ ].join("\n");
227
+ return { systemPrompt, userPrompt };
228
+ }
229
+ /** One line per effective-active record of the real project a `call -p` proposes to. */
230
+ function realRecordTitles(project) {
231
+ const ref = project.proposalsRef;
232
+ if (!ref)
233
+ return [];
234
+ // The call's own project roots at its call directory: look at the real project's `shared/` instead.
235
+ const real = { ...project, paths: { ...project.paths, shared: path.dirname(path.dirname(ref.recordsRoot)) } };
236
+ return RECORD_KINDS.flatMap((k) => effectiveActive(listRecords(real, k)).map((r) => `- [${k}/${r.id}] ${r.title}`));
237
+ }
151
238
  /** The prompt of a `call`: the memory indexes the agent is used to, then the task. */
152
- export function buildCallUserPrompt(agent, task) {
239
+ export function buildCallUserPrompt(agent, task, project) {
153
240
  const parts = [];
154
241
  for (const dir of memoryDirs(agent))
155
242
  parts.push(...memoryBlock(agent, dir), "");
243
+ // `call -p` (spec 30, D-16): the titles of what the project already records, so a proposal does not repeat it. Bodies are read on demand.
244
+ const titles = project?.proposalsRef ? realRecordTitles(project) : [];
245
+ if (titles.length)
246
+ parts.push('<existing_records note="titles only; the files are in the project records folders">', ...titles, "</existing_records>", "");
156
247
  parts.push("<task>", task.trim(), "</task>");
157
248
  return parts.join("\n");
158
249
  }
@@ -316,6 +407,9 @@ export function buildUserPrompt(project, agent, unread, handleCount = 1, handoff
316
407
  if (view)
317
408
  parts.push("", `<${tag}>`, view, `</${tag}>`); // nothing recorded yet: no tag, no tokens
318
409
  }
410
+ // Only the real lead decides proposals: a solo agent is the lead of a team of one and must not be told to (spec 30, D-02).
411
+ if (agent.name === project.lead && !project.solo)
412
+ parts.push(...pendingProposalLines(project));
319
413
  parts.push(...userTaskBlock(project, agent, unread, userTask?.text, userTask?.file));
320
414
  const handoffFile = handoff ? sharedIndex(project) : undefined;
321
415
  const notes = handoffFile ? readCapped(handoffFile, HANDOFF_LIMIT) : undefined;
@@ -355,8 +449,8 @@ export function buildUserPrompt(project, agent, unread, handleCount = 1, handoff
355
449
  }
356
450
  /** The prompts of a memory-tidy wake-up: a maintenance job, not a task, so it has none of the mail protocol. */
357
451
  export function buildTidyPrompts(agent, ctx) {
358
- const { dir, archiveDir, records } = ctx;
359
- const touch = [dir ? `your ${ctx.layer} memory (\`${dir}\`)` : "", records ? `the project records (\`${records.dir}\`)` : ""].filter(Boolean).join(" and ");
452
+ const { dir, archiveDir, records, proposals } = ctx;
453
+ const touch = [dir ? `your ${ctx.layer} memory (\`${dir}\`)` : "", records ? `the project records (\`${records.dir}\`)` : "", proposals ? `the proposals (\`${proposals.dir}\`)` : ""].filter(Boolean).join(" and ");
360
454
  const systemPrompt = [
361
455
  readPersona(agent),
362
456
  "",
@@ -364,10 +458,10 @@ export function buildTidyPrompts(agent, ctx) {
364
458
  "",
365
459
  "# Memory tidy (injected by agent-lyceum)",
366
460
  "",
367
- `You are **${agent.name}**. This wake-up is a maintenance job, not a task: there is no mail to send or read, and nothing to do in the repository. Your only job is to tidy ${records ? touch : `your own ${ctx.layer} memory`} so it stays small, accurate and useful.`,
461
+ `You are **${agent.name}**. This wake-up is a maintenance job, not a task: there is no mail to send or read, and nothing to do in the repository. Your only job is to tidy ${records || proposals ? touch : `your own ${ctx.layer} memory`} so it stays small, accurate and useful.`,
368
462
  "",
369
463
  "## What you may touch",
370
- `Only files inside ${[dir ? `\`${dir}\`` : "", records ? `\`${records.dir}\`` : ""].filter(Boolean).join(" and ")}. Everything else is read-only. Do not touch your other memory directories, \`${dir ? `${dir}/` : ""}.tidy-state.json\` or the archive folders of earlier tidies.`,
464
+ `Only files inside ${[dir ? `\`${dir}\`` : "", records ? `\`${records.dir}\`` : "", proposals ? `\`${proposals.dir}\`` : ""].filter(Boolean).join(" and ")}. Everything else is read-only. Do not touch your other memory directories, \`${dir ? `${dir}/` : ""}.tidy-state.json\` or the archive folders of earlier tidies.`,
371
465
  ...(dir && archiveDir
372
466
  ? [
373
467
  "",
@@ -398,6 +492,17 @@ export function buildTidyPrompts(agent, ctx) {
398
492
  `Write \`${records.archiveDir}/tidy-report.md\` — even when you changed nothing — with the headings \`## Merged\`, \`## Archived\`, \`## Unsure\` (\`None\` when empty). The tidy of both folders is rolled back if the report is missing or any file went missing.`,
399
493
  ]
400
494
  : []),
495
+ ...(proposals
496
+ ? [
497
+ "",
498
+ "## What to do with the proposals",
499
+ `Agents that ran alone wrote proposals of lessons and decisions (\`${proposals.dir}/lessons/<id>.md\`, \`${proposals.dir}/decisions/<id>.md\`); the lead decided them with \`status: accepted\` or \`status: rejected\` and a \`decided\` date. Today is ${proposals.today}.`,
500
+ `- Archive only a proposal that is decided (\`accepted\` or \`rejected\`) and whose \`decided\` date is more than ${proposals.keepDays} days before today (the list below marks them). Never archive a proposal that is still \`proposed\`.`,
501
+ "- Do not edit any proposal, and do not merge or rewrite them: moving a file is the only change.",
502
+ `To archive one, move it into \`${proposals.archiveDir}\`, keeping its relative path (\`${proposals.dir}/lessons/x.md\` goes to \`${proposals.archiveDir}/lessons/x.md\`). Never delete a file.`,
503
+ `Write \`${proposals.archiveDir}/tidy-report.md\` — even when you archived nothing — with the headings \`## Archived\` and \`## Unsure\` (\`None\` when empty). The tidy of every folder is rolled back if the report is missing, a proposal was changed, or one that is not eligible was moved.`,
504
+ ]
505
+ : []),
401
506
  ].join("\n");
402
507
  const parts = [];
403
508
  if (dir && archiveDir) {
@@ -426,5 +531,8 @@ export function buildTidyPrompts(agent, ctx) {
426
531
  ? records.entries.map((e) => `${e.rel} ${e.status} ${e.date || "no date"} ${e.bytes} B ${e.title}${e.invalid ? ` [INVALID: ${e.invalid}]` : ""}`)
427
532
  : ["(none)"]), ...(records.otherFiles.length ? ["", "Other files (leave them alone):", ...records.otherFiles.map((f) => `${f.rel} ${f.bytes} B`)] : []));
428
533
  }
534
+ if (proposals) {
535
+ parts.push(...(parts.length ? [""] : []), "# Proposals", `Proposals archive directory: ${proposals.archiveDir}`, `Proposals directory: ${proposals.dir}`, "", "Entries (path status date decided size title; ELIGIBLE = may be archived now):", ...(proposals.entries.length ? proposals.entries.map((e) => `${e.rel} ${e.status} ${e.date || "no date"} ${e.decided || "-"} ${e.bytes} B ${e.title}${e.eligible ? " [ELIGIBLE]" : ""}`) : ["(none)"]));
536
+ }
429
537
  return { systemPrompt, userPrompt: parts.join("\n") };
430
538
  }
@@ -0,0 +1,26 @@
1
+ import type { Invoker } from "./adapters/index.js";
2
+ import type { ResolvedProject } from "./config.js";
3
+ export interface ReviewOptions {
4
+ project: ResolvedProject;
5
+ invoker?: Invoker;
6
+ signal?: AbortSignal;
7
+ say?: (line: string) => void;
8
+ now?: () => Date;
9
+ }
10
+ export interface ReviewResult {
11
+ status: "reviewed" | "nothing" | "failed";
12
+ /** The report the lead wrote (only for a finished review). */
13
+ report?: string;
14
+ accepted: number;
15
+ rejected: number;
16
+ problems: string[];
17
+ }
18
+ /** Where the lead's report of one review goes: inside the proposals folder, which is the only place besides the records it may write. */
19
+ export declare const reviewReportFile: (project: ResolvedProject, stamp: string) => string;
20
+ /**
21
+ * Wake the project's lead once to decide the pending proposals (spec 30, D-14). This function writes nothing itself and
22
+ * decides nothing: the lead does, inside the same all-or-nothing wake a memory tidy uses, and a decision that is incomplete,
23
+ * a record or proposal that disappeared, or a records kind over its budget puts everything back. The caller holds the
24
+ * project's exclusive lock. It never goes through the guard.
25
+ */
26
+ export declare function reviewProposals(o: ReviewOptions): Promise<ReviewResult>;
@@ -0,0 +1,94 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { fingerprint, listMemoryFiles, tidyStamp, tidyWorkDir, wakeWithRollback } from "./memory-tidy.js";
4
+ import { memoryDirs, proposalsDir, recordsDir } from "./policy.js";
5
+ import { buildReviewPrompts } from "./prompt.js";
6
+ import { checkDecisions, listProposals, pendingProposals, proposalStatusOf } from "./proposals.js";
7
+ import { recordsOverBudget } from "./records.js";
8
+ /** Where the lead's report of one review goes: inside the proposals folder, which is the only place besides the records it may write. */
9
+ export const reviewReportFile = (project, stamp) => path.join(proposalsDir(project), ".reviews", `${stamp}.md`);
10
+ /**
11
+ * Wake the project's lead once to decide the pending proposals (spec 30, D-14). This function writes nothing itself and
12
+ * decides nothing: the lead does, inside the same all-or-nothing wake a memory tidy uses, and a decision that is incomplete,
13
+ * a record or proposal that disappeared, or a records kind over its budget puts everything back. The caller holds the
14
+ * project's exclusive lock. It never goes through the guard.
15
+ */
16
+ export async function reviewProposals(o) {
17
+ const { project } = o;
18
+ const say = o.say ?? ((s) => console.log(s));
19
+ const pending = pendingProposals(project);
20
+ if (pending.length === 0)
21
+ return { status: "nothing", accepted: 0, rejected: 0, problems: [] };
22
+ const stamp = tidyStamp(o.now?.());
23
+ const lead = project.agents[project.lead];
24
+ if (!lead)
25
+ return { status: "failed", accepted: 0, rejected: 0, problems: [`the lead "${project.lead}" is not an agent of the project`] };
26
+ const pDir = proposalsDir(project);
27
+ const rDir = recordsDir(project);
28
+ fs.mkdirSync(path.join(pDir, ".reviews"), { recursive: true }); // D-18: runtimes only get directories that exist
29
+ fs.mkdirSync(rDir, { recursive: true });
30
+ const report = reviewReportFile(project, stamp);
31
+ const statusBefore = new Map(pending.map((p) => [p.file, p.status ?? "proposed"]));
32
+ const hashBefore = fingerprint(pDir);
33
+ const decidedBefore = new Set(listProposals(project)
34
+ .filter((p) => p.status === "accepted" || p.status === "rejected")
35
+ .map((p) => path.relative(pDir, p.file)));
36
+ const recordsBefore = listMemoryFiles(rDir).map((f) => f.rel);
37
+ say(`reviewing ${pending.length} proposal(s) with ${project.lead} …`);
38
+ const woke = await wakeWithRollback({
39
+ project,
40
+ agentName: project.lead,
41
+ dirs: [rDir, pDir],
42
+ allowDirs: [rDir, pDir],
43
+ others: memoryDirs(lead).filter((d) => fs.existsSync(d)),
44
+ othersLabel: "not the records or the proposals",
45
+ workDir: tidyWorkDir(project, stamp, `review-${project.lead}`),
46
+ prompts: buildReviewPrompts(project, lead, report),
47
+ invoker: o.invoker,
48
+ signal: o.signal,
49
+ check: () => {
50
+ const problems = [];
51
+ // Layer 1 of D-09, the same function a lead's `done` uses.
52
+ for (const d of checkDecisions(listProposals(project), project))
53
+ problems.push(`${d.file}: ${d.problem}`);
54
+ for (const x of recordsOverBudget(project))
55
+ problems.push(`records/${x.kind} hold ${x.bytes} bytes of active entries, over the budget`);
56
+ // Nothing may disappear, and a proposal that was already decided stays as it was (only the lead's decision on a pending one is new).
57
+ const hashAfter = fingerprint(pDir);
58
+ for (const rel of Object.keys(hashBefore)) {
59
+ if (!(rel in hashAfter))
60
+ problems.push(`proposals/${rel} was deleted`);
61
+ else if (hashAfter[rel] !== hashBefore[rel] && (rel.startsWith(".archive/") || rel.startsWith(".reviews/") || decidedBefore.has(rel)))
62
+ problems.push(`proposals/${rel} was already decided or archived and may not change`);
63
+ }
64
+ const recordsAfter = new Set(listMemoryFiles(rDir).map((f) => f.rel));
65
+ for (const rel of recordsBefore)
66
+ if (!recordsAfter.has(rel))
67
+ problems.push(`records/${rel} was deleted (mark it superseded instead)`);
68
+ let ok = false;
69
+ try {
70
+ ok = fs.statSync(report).isFile() && fs.readFileSync(report, "utf8").trim() !== "";
71
+ }
72
+ catch {
73
+ ok = false;
74
+ }
75
+ if (!ok)
76
+ problems.push(`the report ${path.relative(project.paths.root, report)} is missing or empty`);
77
+ return problems;
78
+ },
79
+ });
80
+ if (!woke.ok)
81
+ return { status: "failed", accepted: 0, rejected: 0, problems: woke.problems };
82
+ let accepted = 0;
83
+ let rejected = 0;
84
+ for (const [file, before] of statusBefore) {
85
+ if (before !== "proposed")
86
+ continue;
87
+ const now = proposalStatusOf(fs.readFileSync(file));
88
+ if (now === "accepted")
89
+ accepted++;
90
+ else if (now === "rejected")
91
+ rejected++;
92
+ }
93
+ return { status: "reviewed", report, accepted, rejected, problems: [] };
94
+ }
@@ -0,0 +1,88 @@
1
+ import type { ResolvedProject } from "./config.js";
2
+ import { type RecordKind } from "./records.js";
3
+ /**
4
+ * Proposals of lessons and decisions from agents that run alone (spec 30). Everything here only reads: a proposal is written
5
+ * by the agent (status `proposed`) and decided by the lead, and no code in this file writes either.
6
+ */
7
+ export type ProposalKind = RecordKind;
8
+ export declare const PROPOSAL_KINDS: readonly ProposalKind[];
9
+ export type ProposalStatus = "proposed" | "accepted" | "rejected";
10
+ /** One proposal file is at most this big; a larger one is "not in the right format" (D-11). */
11
+ export declare const PROPOSAL_MAX_BYTES: number;
12
+ /** The lead's prompt lists at most this many pending proposals (D-11). */
13
+ export declare const PENDING_SHOWN = 10;
14
+ export type Evidence = {
15
+ type: "path";
16
+ file: string;
17
+ line?: number;
18
+ commit?: string;
19
+ } | {
20
+ type: "commit";
21
+ commit: string;
22
+ } | {
23
+ type: "mail";
24
+ value: string;
25
+ } | {
26
+ type: "output";
27
+ value: string;
28
+ };
29
+ export interface Proposal {
30
+ kind: ProposalKind;
31
+ /** The file name without `.md`: `<short id>-<slug>`. */
32
+ id: string;
33
+ file: string;
34
+ /** Undefined when the file has no readable `status` of the three values. */
35
+ status?: ProposalStatus;
36
+ date: string;
37
+ title: string;
38
+ proposedBy: string;
39
+ run: string;
40
+ evidence: Evidence[];
41
+ repo?: string;
42
+ scope?: string;
43
+ supersedes: string[];
44
+ rejectReason?: string;
45
+ acceptedAs?: string;
46
+ decided?: string;
47
+ body: string;
48
+ bytes: number;
49
+ /** Why the file is not in the right format (empty when it is). Never makes the listing throw. */
50
+ problems: string[];
51
+ }
52
+ /** The part of a run or call id that is unique: its first 8 lowercase letters or digits after the timestamp (D-10). */
53
+ export declare function shortIdOf(runId: string): string;
54
+ /** The `status` in a proposal's frontmatter, or undefined when the text has none of the three values (or is not a proposal at all). */
55
+ export declare function proposalStatusOf(buf: Buffer): ProposalStatus | undefined;
56
+ /** The id's own prefix: what comes before the first `-`. */
57
+ export declare const prefixOf: (id: string) => string;
58
+ export declare function parseProposal(kind: ProposalKind, file: string): Proposal;
59
+ /** Every `*.md` proposal of one kind, sorted by id. A missing or symlinked folder lists nothing; `.archive/` is never read. */
60
+ export declare function listKindProposals(project: ResolvedProject, kind: ProposalKind): Proposal[];
61
+ export declare const listProposals: (project: ResolvedProject) => Proposal[];
62
+ /** Proposals waiting for the lead: `status: proposed`, or with no readable status (they are shown as "format problem", never lost). */
63
+ export declare const pendingProposals: (project: ResolvedProject) => Proposal[];
64
+ export declare function oldestPending(pending: Proposal[]): string | undefined;
65
+ /** What `proposals list` shows: the counts, the pending ones with their evidence, and every decision that is not complete. Reads only. */
66
+ export declare function describeProposals(project: ResolvedProject): string[];
67
+ export interface DecisionProblem {
68
+ file: string;
69
+ problem: string;
70
+ }
71
+ /**
72
+ * Layer 1 of D-09: the lead's decisions are complete. Only decided proposals are looked at. An `accepted` one must be a
73
+ * whole proposal (format, evidence, a prefix that matches its run) with `accepted_as` pointing at a record and a `decided`
74
+ * date. A `rejected` one only needs `reject_reason` and `decided`, so the lead can reject a badly formed one without being
75
+ * sent back for it. Evidence that does not exist on disk is not checked here (layer 2, `checkEvidence`).
76
+ */
77
+ export declare function checkDecisions(proposals: Proposal[], project: ResolvedProject): DecisionProblem[];
78
+ export type EvidenceStrength = "verified" | "weak" | "none";
79
+ export interface EvidenceCheck {
80
+ strength: EvidenceStrength;
81
+ notes: string[];
82
+ }
83
+ /**
84
+ * Layer 2 of D-09: does the evidence exist (30.7). `root` is the repository `path:` and `commit:` refer to (`project.dir`);
85
+ * a proposal's own `repo` takes its place, and when that is missing or not a git repository the evidence is only "weak".
86
+ * `mail:` and `output:` are format-only and never count as verified. Nothing here judges whether the lesson is right.
87
+ */
88
+ export declare function checkEvidence(p: Proposal, root: string): EvidenceCheck;