📦 EqualifyEverything / equalify-iris

📄 feedback.ts · 296 lines
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296import { existsSync, readFileSync, readdirSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { extractJson } from "../util/json.ts";
import { loadAgent, type AgentSpec } from "../agents/loader.ts";
import { ACCESSIBILITY_REQUIREMENTS } from "./accessibility.ts";
import { loadImage, type InputImage, type PipelineContext } from "./context.ts";
import type { FixtureCase } from "./regression.ts";

// Previously imported from github/contributions.ts, which was removed when the
// contribution model moved from close-time PRs to issues filed during the run.
// The feedback loop still records proposed library-agent updates in this shape
// (in agent-updates.md, gated by regression fixtures) for maintainer review.
export interface AgentUpdateContribution {
  agent_name: string; // e.g. "page.md"
  summary: string;
  diff_preview: string;
  content: string; // full updated agent file content
}

const FEEDBACK_AGENT = "feedback";

interface TrainOutput {
  changed?: boolean;
  summary?: string;
  agent_markdown?: string;
}

interface VerifyOutput {
  faithful?: boolean;
  accessible?: boolean;
  problems?: string[];
}

export interface VerifyVerdict {
  ok: boolean;
  problems: string[];
}

function loadFeedbackAgent(ctx: PipelineContext): AgentSpec | null {
  return loadAgent(FEEDBACK_AGENT, {
    agentsDir: ctx.paths.agentsDir,
    tmpAgentsDir: ctx.paths.tmpAgentsDir(ctx.sessionId),
  });
}

function loadTargetAgent(ctx: PipelineContext, agentFile: string): AgentSpec | null {
  return loadAgent(agentFile, {
    agentsDir: ctx.paths.agentsDir,
    tmpAgentsDir: ctx.paths.tmpAgentsDir(ctx.sessionId),
  });
}

// A naive line-level diff (added/removed lines) for the update PR body and as the
// "correction" context handed to the Feedback Agent. Not a true minimal diff —
// just enough to show what changed.
function diffPreview(before: string, after: string, maxLines = 80): string {
  const a = new Set(before.split("\n"));
  const b = new Set(after.split("\n"));
  const removed = before.split("\n").filter((l) => !b.has(l)).map((l) => `- ${l}`);
  const added = after.split("\n").filter((l) => !a.has(l)).map((l) => `+ ${l}`);
  const lines = [...removed, ...added];
  return (
    lines.slice(0, maxLines).join("\n") +
    (lines.length > maxLines ? `\n… (${lines.length - maxLines} more changed lines)` : "")
  );
}

// ---------------------------------------------------------------------------
// Build-time verification (source-fidelity, PRD §7.5/§7.12)
// ---------------------------------------------------------------------------

// Ask the Feedback Agent (VERIFY task) whether an agent's output faithfully and
// accessibly captures its source image. In the single-pass pipeline this verifies
// the page agent's per-page output; it is also reused by the regression gate.
// Non-blocking: returns ok=true when the Feedback Agent is unavailable or returns
// nothing, so verification never breaks a run.
export async function verifyAgentOutput(
  ctx: PipelineContext,
  agent: AgentSpec,
  img: InputImage,
  blocks: { html: string }[],
): Promise<VerifyVerdict> {
  const fb = loadFeedbackAgent(ctx);
  if (!fb || blocks.length === 0) return { ok: true, problems: [] };

  const html = blocks.map((b) => b.html).join("\n\n");
  const user =
    `TASK: verify\n\n` +
    `## Agent under test: ${agent.file}\n\`\`\`markdown\n${agent.content}\n\`\`\`\n\n` +
    `## The agent's output for source image "${img.name}"\n\`\`\`html\n${html}\n\`\`\`\n\n` +
    `Compare the output against the attached source image.`;

  const res = await ctx.router.complete(
    FEEDBACK_AGENT,
    "vision",
    [
      { role: "system", content: fb.content },
      { role: "user", content: user },
    ],
    { images: [loadImage(img)] },
  );
  ctx.log.agentCall({ agent: fb, phase: "extraction", image: img.name, output: res.text });

  const parsed = extractJson<VerifyOutput>(res.text);
  if (!parsed) return { ok: true, problems: [] };
  const ok = parsed.faithful !== false && parsed.accessible !== false;
  return { ok, problems: parsed.problems ?? [] };
}

// ---------------------------------------------------------------------------
// Regression gate (PRD §7.12): protect existing uses when an agent is updated
// ---------------------------------------------------------------------------

const MAX_GATE_FIXTURES = 3;

export interface RegressionResult {
  passed: boolean;
  failures: string[];
}

// Re-run an agent (given its current/updated content) on a fixture image, used by
// the regression gate. Accepts either output shape: { html } (whole-page agents
// like page.md) or { no_content, fragments[] } (content agents).
async function reRunAgentOnImage(
  ctx: PipelineContext,
  agent: AgentSpec,
  img: InputImage,
): Promise<{ html: string }[]> {
  const system = `${agent.content}\n\n${ACCESSIBILITY_REQUIREMENTS}`;
  const user =
    `Process source image "${img.name}" exactly as your contract specifies and respond with ONLY ` +
    `JSON — either { "html": "<accessible HTML>" } for a whole-page agent, or ` +
    `{ "no_content": false, "fragments": [ { "html": "<accessible HTML>" } ] } for a content agent ` +
    `({ "no_content": true } if nothing matches).`;
  const capability = agent.capabilities.includes("vision") ? "vision" : "text";
  const res = await ctx.router.complete(
    agent.name,
    capability,
    [
      { role: "system", content: system },
      { role: "user", content: user },
    ],
    { images: [loadImage(img)] },
  );
  ctx.log.agentCall({ agent, phase: "review", image: img.name, output: res.text });
  const parsed = extractJson<{ no_content?: boolean; html?: string; fragments?: { html?: string }[] }>(res.text);
  if (!parsed || parsed.no_content) return [];
  if (parsed.html) return [{ html: parsed.html }];
  if (parsed.fragments?.length) return parsed.fragments.filter((f) => f.html).map((f) => ({ html: f.html! }));
  return [];
}

// Before an existing agent is updated/merged, re-run the UPDATED agent against its
// stored regression fixtures and verify each still passes. Blocks the change if
// any fixture regresses, so an agent can't be changed in a way that breaks a use
// it already handled. Passes when the agent has no fixtures yet.
export async function regressionGate(
  ctx: PipelineContext,
  agentFile: string,
  updatedContent: string,
): Promise<RegressionResult> {
  const dir = ctx.paths.agentFixtures(agentFile);
  if (!existsSync(dir)) return { passed: true, failures: [] };
  const caseFiles = readdirSync(dir)
    .filter((f) => f.endsWith(".json"))
    .sort()
    .reverse()
    .slice(0, MAX_GATE_FIXTURES);
  if (caseFiles.length === 0) return { passed: true, failures: [] };

  const file = agentFile.endsWith(".md") ? agentFile : `${agentFile}.md`;
  const updatedAgent: AgentSpec = {
    name: file.replace(/\.md$/, ""),
    file,
    content: updatedContent,
    capabilities: /\bvision\b/i.test(updatedContent) ? ["vision"] : ["text"],
    sha: null,
    sessionBuilt: false,
  };

  const failures: string[] = [];
  for (const caseFile of caseFiles) {
    let c: FixtureCase;
    try {
      c = JSON.parse(readFileSync(join(dir, caseFile), "utf8")) as FixtureCase;
    } catch {
      continue;
    }
    const imgPath = join(dir, c.image_file);
    if (!existsSync(imgPath)) continue;
    const img: InputImage = { name: c.source_image, order: 0, path: imgPath };
    const blocks = await reRunAgentOnImage(ctx, updatedAgent, img);
    if (blocks.length === 0) {
      failures.push(`${c.image_file}: updated agent produced no output`);
      continue;
    }
    const verdict = await verifyAgentOutput(ctx, updatedAgent, img, blocks);
    if (!verdict.ok) failures.push(`${c.image_file}: ${verdict.problems.join("; ") || "failed verification"}`);
  }

  const passed = failures.length === 0;
  ctx.log.event("regression_gate", { agent: file, cases: caseFiles.length, passed, failures: failures.length });
  return { passed, failures };
}

// ---------------------------------------------------------------------------
// Feedback-driven agent training (PRD §7.12/§7.13)
// ---------------------------------------------------------------------------

// On a feedback re-run, turn the document-level correction (the prior reviewed
// body vs. this run's reviewed body) into an improved version of the agent that
// produced the document — the page agent in the single-pass pipeline. A library
// agent becomes an update PR (via agent-updates.md, opened on close), gated on its
// regression fixtures so the change can't break a use it already handled; a
// session-built agent is trained in place so its new-agent PR carries the fix.
export async function proposeAgentUpdatesFromFeedback(
  ctx: PipelineContext,
  args: { agentFile: string; before: string; after: string; feedback: string },
): Promise<AgentUpdateContribution[]> {
  const feedbackAgent = loadFeedbackAgent(ctx);
  if (!feedbackAgent) {
    ctx.log.event("feedback_agent_missing", {
      note: "agents/feedback.md not found; skipping agent-update proposals",
    });
    return [];
  }
  // Nothing changed this run -> no lesson to learn.
  if (!args.before.trim() || args.before.trim() === args.after.trim()) return [];

  const target = loadTargetAgent(ctx, args.agentFile);
  if (!target) {
    ctx.log.event("feedback_target_missing", { agent: args.agentFile });
    return [];
  }

  const correction = diffPreview(args.before, args.after);
  const user =
    `TASK: train\n\n` +
    `## Agent to improve: ${target.file}\n\`\`\`markdown\n${target.content}\n\`\`\`\n\n` +
    `## User feedback for this run\n${args.feedback}\n\n` +
    `## The correction the feedback caused (diff of the document body)\n\`\`\`diff\n${correction}\n\`\`\``;

  const res = await ctx.router.complete(FEEDBACK_AGENT, "text", [
    { role: "system", content: feedbackAgent.content },
    { role: "user", content: user },
  ]);
  ctx.log.agentCall({ agent: feedbackAgent, phase: "review", output: res.text });

  const parsed = extractJson<TrainOutput>(res.text);
  if (!parsed?.changed || !parsed.agent_markdown) return [];
  const updated = parsed.agent_markdown.trim();
  if (!updated || updated === target.content.trim()) return [];

  if (target.sessionBuilt) {
    // Train the session-built agent in place: overwrite its tmp file so the
    // new-agent PR opened on close carries the improved prompt.
    writeFileSync(join(ctx.paths.tmpAgentsDir(ctx.sessionId), target.file), updated);
    ctx.log.event("agent_trained", { agent: target.file, scope: "session_built" });
    return [];
  }

  // Existing library agent: gate the proposed update on its regression fixtures —
  // never propose a change that breaks a use it already handled.
  const gate = await regressionGate(ctx, target.file, updated);
  if (!gate.passed) {
    ctx.log.event("agent_update_blocked", { agent: target.file, failures: gate.failures });
    return [];
  }

  const proposal: AgentUpdateContribution = {
    agent_name: target.file,
    summary: parsed.summary?.trim() || `Improved ${target.name} from user feedback.`,
    diff_preview: diffPreview(target.content, updated),
    content: updated,
  };

  // Merge with any existing proposals (dedupe by agent_name; this run wins).
  const path = ctx.paths.sessionAgentUpdates(ctx.sessionId);
  let existing: AgentUpdateContribution[] = [];
  if (existsSync(path)) {
    try {
      const prior = JSON.parse(readFileSync(path, "utf8"));
      if (Array.isArray(prior)) existing = prior as AgentUpdateContribution[];
    } catch {
      existing = [];
    }
  }
  const merged = new Map<string, AgentUpdateContribution>();
  for (const p of existing) merged.set(p.agent_name, p);
  merged.set(proposal.agent_name, proposal);
  writeFileSync(path, JSON.stringify([...merged.values()], null, 2));

  ctx.log.event("agent_updates_proposed", { agents: [proposal.agent_name], count: 1 });
  return [proposal];
}